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

276. 在存在值复用的 op tape 上运行反向模式

EasyAutograd

Autograd 引擎会在 tape 上记录每个操作,然后进行反向遍历。当一个值作为多个后续操作的输入时,其梯度是沿每个使用路径回传梯度的总和(SUM)。使用赋值(overwriting)而不是累加(adding)是最常见的 autograd bug。

编写 tape_grads(inputs, tape)。inputs 是一个 dict,格式为 name -> float。tape 是一个按执行顺序排列的 (out, op, args) 列表,其中 op 是 "add", "sub", "mul" 或 "square",args 是一个名称列表(add/sub/mul 有两个,square 有一个)。最后一条记录的 output 是最终结果 f。
返回一个 dict,包含 inputs 中每个 name 的 df/dname(未使用的输入为 0.0)。

函数def tape_grads(inputs, tape)

示例 1

输入: inputs {"x": 3.0}, tape [("y", "mul", ["x", "x"])]

输出: {"x": 6.0}

示例 2

输入: inputs = {'a': 2.0, 'b': -1.0}, tape = [('c', 'add', ['a', 'b']), ('d', 'square', ['c'])]

输出: {'a': 2.0, 'b': 2.0}

示例 3

输入: inputs = {'x': 2.0, 'w': 0.5}, tape = [('p', 'mul', ['x', 'w']), ('q', 'sub', ['x', 'p']), ('r', 'mul', ['p', 'q']), ('s', 'add', ['r', 'x'])]

输出: {'x': 2.0, 'w': 0.0}

约束条件

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

先进行 forward pass 以获取每个值。

提示 2

然后设置 grad[f] = 1,并反向遍历 tape,执行 grad[arg] += local_derivative * grad[out].

常见错误
  • 有 bug 的版本使用 = 而不是 += 进行赋值,因此最后一次访问的使用会覆盖其他使用:x * x 的结果是 3 而不是 6。
理解思路

Reverse mode autodiff 从最后一个操作开始到第一个操作重新回放 tape,将每个 output 的梯度传回其 inputs。当一个值在多个地方被使用时,每次使用都会传回它各自的部分,这些部分必须相加,绝不能被覆盖。

Worked example

inputs x = 2, y = 3. Tape: a = mul(x, y) = 6, 然后 f = add(a, x) = 8. 从 df/df = 1 开始。add 将 1 传给 a 和 1 传给 x。mul 将 a 的梯度乘以 y = 3 传给 x,乘以 x = 2 传给 y。因此 df/dx = 1 + 3 = 4 且 df/dy = 2. Rules for local derivatives: add 将梯度原样传给两个 args,sub 传 +g 和 -g,mul 传 g 乘以另一个 arg,square 传 g * 2 * arg. 从未出现的 inputs 得到 0。对于 mul(x, x),两个 args 都是 x,因此 x 接收到两次贡献,结果为 2x。从 PyTorch 到 JAX,每个框架都以这种方式累加梯度。

主题
Autograd
相似题目
  • 使用拓扑排序为反向传播排列计算图Easy
  • 编写矩阵乘法的 backward passEasy
  • 在一个微型指令列表上运行前向模式自动微分Easy
  • 构建一个微型反向模式 autograd 引擎Medium
所有 Autograd 道题目
反馈
276 / 903
Python 3solution.pyPython 空闲
1
2
3
4
def tape_grads(inputs, tape):
# your code here
pass
​

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

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