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

279. 构建一个微型反向模式 autograd 引擎

MediumAutograd

编写一个 Value 类,该类封装一个 float 并记录其生成方式,以便在最终结果上调用 .backward() 时,能为每个输入填充 .grad。

支持:Value(3.0), a + b, a * b, a.tanh(), 以及 + 和 * 两侧的普通数字(例如 2 * a 和 a + 1 均需有效)。每个 Value 都有 .data 和 .grad(初始为 0.0)。backward() 将输出的 grad 设置为 1,并按反向拓扑顺序进行传播。当一个值被使用多次时,梯度必须进行累加(ACCUMULATE)。

函数class Value

示例 1

输入: a = Value(2.0); b = a * a + 1; b.backward()

输出: b.data = 5.0 and a.grad = 4.0

约束条件

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

Every operation creates a new Value that remembers its inputs and a small function that knows how to push the output's grad back to those inputs.

提示 2

Give each Value _prev and a _backward closure; add, mul and tanh set these, and backward() builds a topological order with a DFS, sets its own grad to 1, then calls every _backward in reverse order.

提示 3

Closures must use += on input grads so reused values accumulate; wrap plain numbers with Value in add and mul, set __radd__ = __add__ and __rmul__ = __mul__, and use 1 - t*t as the tanh derivative.

常见错误
  • 使用 = 进行覆盖(错误的实现方式)会导致除了最后一条路径外的所有路径都丢失。
理解思路

反向模式 autograd 引擎将每个数字封装在一个对象中,该对象记录了哪些值产生了它以及如何产生。对最终结果调用 backward 会将其梯度设置为 1,然后按反向拓扑顺序遍历图,每个操作将传入的梯度乘以其局部导数,并累加到其输入中。

Worked example

a = 2, c = a x a, b = c + a, 所以 b = 6。手动计算,db/da = 2a + 1 = 5。在引擎中:b.grad = 1。+ 节点给出 c.grad += 1 和 a.grad += 1。x 节点使用了两次 a,使得 a.grad += c.grad x a = 2 发生两次,因此 a.grad = 1 + 2 + 2 = 5。这只有在使用 += 时才有效;如果用 = 覆盖则会丢失路径。局部规则:对于 a + b,两者都获得输出梯度;对于 a x b,a 获得 out.grad x b,b 获得 out.grad x a;对于 t = tanh(a),a 获得 out.grad x (1 - t^2)。普通数字也必须被封装。PyTorch 的 autograd 对 tensor 也是同样的思路。

主题
Autograd
相似题目
  • 将广播梯度还原回输入形状Medium
  • Route gradients through a max reductionMedium
  • Compute a gradient on a DAG with memoized backpropMedium
  • 使用拓扑排序为反向传播排列计算图Easy
所有 Autograd 道题目
反馈
279 / 903
Python 3solution.pyPython 空闲
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import math
​
class Value:
def __init__(self, data, _prev=()):
self.data = float(data)
self.grad = 0.0
self._prev = _prev
self._backward = lambda: None
​
def __add__(self, o):
# your code here
pass
​
def __mul__(self, o):
# your code here
pass
​
def tanh(self):
# your code here
pass
​
def backward(self):
# your code here
pass
​

此用例使用生成数据,因此按原样运行。按 + 添加你自己的用例。

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

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