BLOGLLM Logo
Go Pro
Guest
Not signed in
所有博客课程练习面试准备系列标签书签价格
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboard游戏
Articles
练习 / Autograd1 of 11 in topic

275. 使用拓扑排序为反向传播排列计算图

EasyAutograd

像 micrograd 和 PyTorch 这样的 Autograd 引擎通过按反向拓扑顺序访问节点来进行反向传播:只有在所有使用该节点的节点都处理完毕后,才会处理该节点。

编写 topo_order(graph, root),其中 graph 将每个节点名称映射到其输入节点名称的列表。返回从 root 可达的所有节点列表,排序要求每个节点都出现在其所有输入节点之后(root 在最后)。使用深度优先搜索,并按列表中列出的顺序访问输入,以确保答案是唯一的。

函数def topo_order(graph, root)

示例 1

输入: graph = {'loss': ['y'], 'y': ['x']}, root = 'loss'

输出: ['x', 'y', 'loss']

约束条件

  • Python 3 standard library. Code runs in your browser.
  • Your code must pass all 3 tests to be accepted.
提示 1

A node can only be added after all of its inputs, which is exactly what post-order depth-first search gives you.

提示 2

Write a recursive visit with a seen set: if a node is new, mark it, visit each of its inputs in the listed order, then append the node to the output.

提示 3

Use graph.get(n, []) so leaf nodes that are not keys in the dict still work, and mark the node as seen before visiting its inputs so shared nodes appear only once.

常见错误
  • 有 Bug 的版本在访问输入之前就添加了节点(前序遍历),这破坏了上述保证。
理解思路

反向传播必须在所有使用该节点的节点都传回梯度后,才能处理该节点。因此,你首先要对节点进行排序,使得每个节点都出现在其所有输入之后(即拓扑排序),然后反向遍历该列表。就像穿衣服一样:必须先穿袜子,再穿鞋子。深度优先搜索可以实现这一点:先访问节点的所有输入,然后再添加该节点。

Worked example

graph {L: [a, b], a: [x], b: [x, y], x: [], y: []}, root L. 访问 L,前往 a,前往 x,x 没有输入,因此添加 x。添加 a。前往 b;x 已被访问,前往 y,添加 y。添加 b。最后添加 L。顺序为:[x, a, y, b, L]。每个节点都出现在其输入之后,root 在最后。在访问输入之前就添加节点(前序遍历)会破坏这一特性。

使用带有 visited 集合的后序 DFS,输入按列表顺序访问。micrograd 和 PyTorch 的 autograd 都依赖于这种排序。
主题
Autograd
相似题目
  • 在存在值复用的 op tape 上运行反向模式Easy
  • 编写矩阵乘法的 backward passEasy
  • 在一个微型指令列表上运行前向模式自动微分Easy
  • 构建一个微型反向模式 autograd 引擎Medium
所有 Autograd 道题目
反馈
275 / 903
Python 3solution.pyPython 空闲
1
2
3
4
def topo_order(graph, root):
# your code here
pass
​

Run 会在浏览器中检查这些用例,无需登录。 Submit 会检查所有 3 个测试。

Ctrl/按 + 回车 运行
© BlogLLM, Bengaluru, India关于条款隐私退款DMCA联系我们RSS