链式法则与反向传播
用符号求导、计算图和梯度检查验证复合函数的导数。
学完这一章,你能够
- 用符号求导、计算图和梯度检查验证复合函数的导数。
确定外层、内层与求导点
设 y=g(x),z=f(y)。若 g 在 x 可导、f 在 y=g(x) 可导,则 dz/dx=f′(g(x))g′(x)。外层导数应在内层输出处取值。例如 sin(x²) 的导数是 2x cos(x²)。
假设挡位等外部条件固定,并用油门决定车速、再由车速决定耗油率的简化模型。耗油率对油门的局部变化率是这两段变化率的乘积。如果耗油率还直接依赖油门,另一路变化也要计入。
沿每条路径传播,再汇总分支
前向依次算 x、y=g(x)、z=f(y)、L。对标量损失,反传从 ∂L/∂L=1 开始,再把上游传来的导数乘以每条边的局部导数。张量情况下使用相应的向量与雅可比矩阵的乘积。节点有多条路径通向损失时,反向贡献相加。
实验设中间值 a=wx,损失 L=(a−1)²。取 w=2、x=3,先得到 a=6、L=25,再算 ∂L/∂a=10、∂a/∂w=3,于是 ∂L/∂w=30。令 x=0 后,局部导数为零,沿这条路径回到 w 的梯度也为零。

PyTorch 在启用梯度、且有输入要求梯度的运算中记录相关计算图。对标量损失调用 backward() 会把结果累加到相应叶节点的梯度。若也要观察中间张量的梯度,可在前向后调用 retain_grad()。
用数值近似对照解析梯度
梯度检查可用中心差分 [f(x+h)−f(x−h)]/(2h) 近似导数,在双精度的可微测试点比较解析梯度与数值梯度。PyTorch gradcheck 同时使用绝对公差和相对公差,步长与公差需按问题选择。实验以正确平方运算通过、漏乘系数 2 的自编反向规则未通过作为对照。
合并运算可减少中间结果读写。比较改写前后的实现时,训练路径还需要检查反向值和不同精度的误差。本例用 CPU 比较 (3w−1)² 与 9w²−6w+1,在 w=2 得到相同前向值 25 和梯度 30。TensorRT 与 XLA 的具体优化需按目标设备和运算核另行验证。
逐步验证计算图的梯度
"""Follow local derivatives through a calculation graph."""
import argparse
import json
import platform
import sympy as sp
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--torch", action="store_true")
args = parser.parse_args()
cases = []
versions = {"sympy":sp.__version__}
def check(name, inputs, expected, actual, operation):
assert actual == expected, (name,expected,actual)
cases.append(dict(name=name,input=inputs,operation=operation,expected=expected,actual=actual,passed=True))
x = sp.Symbol("x", real=True)
inner = x*x
direct = sp.diff(sp.sin(inner),x)
decomposed = sp.cos(inner)*sp.diff(inner,x)
check("sine_square_chain", str(x), ["2*x*cos(x**2)",True], [str(decomposed),sp.simplify(direct-decomposed)==0],
"compare symbolic differentiation with outer derivative times inner derivative")
w, sample, label, signal = sp.symbols("w sample label signal", real=True)
activation = w*sample
loss = (signal-label)**2
local = sp.diff(loss,signal).subs(signal,activation)
partial = sp.diff(activation,w)
substituted = sp.diff(loss.subs(signal,activation),w)
point = {w:2,sample:3,label:1}
check("square_loss_through_linear_node", {"w":2,"sample":3,"label":1}, [10,3,30,True],
[int(local.subs(point)),int(partial.subs(point)),int(substituted.subs(point)),sp.simplify(local*partial-substituted)==0],
"compute local factors, multiply, and compare with the direct derivative")
check("branch_contributions", {"x":2,"graph":"(x*x+x)**2"}, [48,12,60],
[int(v.subs(x,2)) for v in (2*(x*x+x)*2*x,2*(x*x+x),sp.diff((x*x+x)**2,x))],
"measure the squared branch, direct branch, and total")
if args.torch:
import torch
versions["torch"] = torch.__version__
options = {"eps":1e-6,"atol":1e-5,"rtol":1e-3,"raise_exception":False}
class WrongSquare(torch.autograd.Function):
@staticmethod
def forward(ctx, value):
ctx.save_for_backward(value)
return value.square()
@staticmethod
def backward(ctx, upstream):
value, = ctx.saved_tensors
return upstream*value
x64 = torch.tensor(1.5,dtype=torch.float64,requires_grad=True)
checks = [torch.autograd.gradcheck(operation,(x64,),**options)
for operation in (torch.square,WrongSquare.apply)]
check("gradcheck_accept_and_reject", {"x":1.5,"dtype":"float64",**options}, [True,False], checks,
"run finite-difference validation on correct and deliberately incorrect backward rules")
def backward_observation(function):
w = torch.tensor(2.,dtype=torch.float64,requires_grad=True)
output = function(w)
gradient, = torch.autograd.grad(output,w)
return [float(output.detach()),float(gradient)]
graph_a = lambda w: (w*3-1).square()
graph_b = lambda w: 9*w.square()-6*w+1
check("graph_rewrite_forward_backward", {"w":2}, [[25,30],[25,30]],
[backward_observation(graph) for graph in (graph_a,graph_b)],
"compare staged and expanded expressions on both forward value and backward gradient")
w = torch.tensor(2.,dtype=torch.float64,requires_grad=True)
signal = w*3
signal.retain_grad()
(signal-1).square().backward()
check("retained_node_gradient", {"w":2,"sample":3,"label":1}, [10,30],
[float(signal.grad),float(w.grad)], "retain and inspect the intermediate gradient")
print(json.dumps(dict(version=platform.python_version(),library_versions=versions,cases=cases)))
if __name__ == "__main__":
main()
- sin(x²) 的直接求导与链式拆解一致。示例平方损失对权重的梯度为 30。
所需环境:Windows、Python 3.12.14、PyTorch 2.10 CPU。符号计算使用 SymPy 1.14。
当前源码 SHA256:ded712df0c5b9b33e977ded5fa53d705ca6d030e7e6544f8d13d8e323108fc64
复跑实验
解压后按 README 运行自编程序。
所需环境:Windows、Python 3.12.14、PyTorch 2.10 CPU。符号计算使用 SymPy 1.14。
ZIP SHA256:596ca0d84ed1b862d62c3fd4a9f90b1bb626023f3a6fc306c65952facccfe126
常见错误与边界
- 外层导数在内层输出处计算。
- 梯度检查要控制精度、步长和可微条件。
练习与解答
同一变量的两条反向路径给出 48 和 12,合计梯度为多少?
展开参考解答
两条贡献相加得到 60。