蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

逐步验证计算图的梯度

PYTHONWindows、Python 3.12.14、PyTorch 2.10 CPU。符号计算使用 SymPy 1.14。chain-lab.py
chain-lab.py87 行
"""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()
本例需在 Windows、Python 3.12.14、PyTorch 2.10 CPU。符号计算使用 SymPy 1.14。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows、Python 3.12.14、PyTorch 2.10 CPU。符号计算使用 SymPy 1.14。

入口文件:projects/ai-math-chain-rule-lab/chain-lab.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 chain-lab.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows、Python 3.12.14、PyTorch 2.10 CPU。符号计算使用 SymPy 1.14。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

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

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

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

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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