如何解决从PyTorch模块中提取执行DAG
让我们考虑一个简单的前馈深网,甚至是一个renet。在这两种情况下,您都可以将执行流视为DAG(有向无环图),其中的节点是层(如果没有跳过连接,则是一条链)。
出于某种原因,我需要pyTorch模型使用此DAG。到目前为止,我一直在使用自定义对象子类nn.Module(用于存储所需的信息),但是我希望最终能够在管道的输入中使用任意模型。有没有一种方法可以自动提取此DAG? (不管是否在所有情况下都行不通,我主要是在寻求实现我的目标的一般想法/原则。)
解决方法
那确实是可能的。考虑对以下简单公式求值,作为更复杂网络的代表:
<template>
<div class="container">
<h3>Meal Table</h3>
<div class="container">
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th>Meal</th>
<th>Type</th>
<th>Price in $</th>
</tr>
</thead>
<tbody>
<tr v-for="d in mealTables.mealTableWeek" v-bind:key="d.id">
<th></th>
<td>{{d.name}}</td>
<td>{{d.type}}</td>
<td>{{d.price}}</td>
</tr>
</tbody>
</table>
</div>
</div>
</template>
<script>
import MealTableDataService from "@/service/MealTableDataService";
export default {
name: "MealTableWeekComponent",data() {
return {
mealTables: {
id: " ",mealTableWeek: {
name: {
id: " ",name: " ",type: " ",price: " "
}
}
}
};
},methods: {
refreshMealTable() {
const id = this.$route.params.id;
MealTableDataService.retrieveMealTableById(id)
.then(response => {
console.log(response)
this.mealTables = response.data;
});
}
},created() {
this.refreshMealTable();
}
};
</script>
<style scoped lang="scss">
</style>
然后import torch
a = torch.randn(3,requires_grad=True)
b = 3*a + 1
c = torch.relu(b)
d = c.sum()
有一个d
属性,您可以像这样通过它遍历评估图
.grad_fn
基本上,d.grad_fn
d.grad_fn.next_functions
d.grad_fn.next_functions
d.grad_fn.next_functions[0][0].next_functions
d.grad_fn.next_functions[0][0].next_functions[0][0].next_functions
为您提供了当前模块/操作的参数列表,该列表的每个条目都是带有实际对象的元组,以及指示参数位置的整数。 here对此进行了详细记录。
如果您不想自己做,也可以将可视化工具用于张量板中内置的计算图,即next_functions
,如here所述。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。