蓝色天空.知识 · 实践 · 创造
我的收藏
AI 数学基础 教程目录 54章
课程介绍
AI 数学基础 / LEARN BY DOING

链式法则与反向传播

用符号求导、计算图和梯度检查验证复合函数的导数。

学完这一章,你能够

  • 用符号求导、计算图和梯度检查验证复合函数的导数。

确定外层、内层与求导点

设 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 的具体优化需按目标设备和运算核另行验证。

逐步验证计算图的梯度

含完整源码 · 87 行
展开查看收起
python
"""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。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

复跑实验

解压后按 README 运行自编程序。

下载本章实验包 (mbskycom202612a33.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:AI 数学基础

课程关联工程包(登记关联54章) · 含当前章节或实例 · mbskycom202612a33.zip

下载课程关联工程包:AI 数学基础

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a39.zip

常见错误与边界检查

  • 外层导数在内层输出处计算。
  • 梯度检查要控制精度、步长和可微条件。

技术规范与官方资料

练习与参考解答

查看参考解答

两条贡献相加得到 60。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习