"""Measure directional derivatives, parameter updates and gradient clipping."""
import argparse
import json
import math
import platform
import numpy as np
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--torch", action="store_true")
args = parser.parse_args()
cases = []
versions = {"numpy": np.__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))
point = np.array([1.5,1.0])
gradient = 2*point
norm = float(np.linalg.norm(gradient))
check("bowl_gradient", point.tolist(), [[3,2],3.605551], [gradient.tolist(),round(norm,6)],
"differentiate x²+y² and compute the Euclidean norm")
direction = gradient/norm
tangent = np.array([-direction[1],direction[0]])
directions = np.stack([direction,-direction,tangent])
check("unit_directional_derivatives", directions.tolist(), [3.605551,-3.605551,0],
[round(float(d@gradient),6) for d in directions], "take the dot product with three unit directions")
check("normalization_matters", [2,0], [6,3],
[float(v@gradient) for v in (np.array([2,0]),np.array([1,0]))], "compare a doubled vector and its unit direction")
def objective(vector):
return float(vector@vector)
new = point-.25*gradient
check("downhill_small_step", {"point":point.tolist(),"eta":.25}, [[.75,.5],3.25,.8125],
[new.tolist(),objective(point),objective(new)], "take one negative-gradient update")
check("large_step_overshoots", {"point":point.tolist(),"eta":1.25}, [7.3125,20.3125],
[objective(point - 1.25*gradient),objective(point + .75*gradient)],
"compare overshoot with positive-gradient ascent")
h = .5
check("zero_gradient_multiple_behaviors", ["x²+y²","x²−y²","x³+y²",h],
[[.25,.25],[.25,-.25],[.125,-.125]],
[[fun(a,b),fun(c,d)] for fun,(a,b,c,d) in (
(lambda x,y:x*x+y*y,(h,0,0,h)), (lambda x,y:x*x-y*y,(h,0,0,h)),
(lambda x,y:x**3+y*y,(h,0,-h,0)))],
"sample both signs or coordinate directions around three stationary points")
if args.torch:
import torch
versions["torch"] = torch.__version__
theta = torch.nn.Parameter(torch.tensor(point.tolist(),dtype=torch.float64))
optimizer = torch.optim.SGD([theta],lr=.25)
optimizer.zero_grad(set_to_none=True)
loss = (theta**2).sum()
loss.backward()
grad = theta.grad.tolist()
optimizer.step()
check("sgd_backward_then_step", {"point":point.tolist(),"lr":.25}, [[3,2],[.75,.5]],
[grad,theta.detach().tolist()], "run a real CPU backward pass and SGD step")
weight_a = torch.nn.Parameter(torch.tensor(0.,dtype=torch.float64))
weight_b = torch.nn.Parameter(torch.tensor(0.,dtype=torch.float64))
(3*weight_a+4*weight_b).backward()
before = float(torch.nn.utils.clip_grad_norm_([weight_a,weight_b],1.0))
after = math.hypot(float(weight_a.grad),float(weight_b.grad))
vector = [float(weight_a.grad),float(weight_b.grad)]
assert math.isclose(after,1,rel_tol=0,abs_tol=1e-6) and after<=1
check("clip_global_l2", {"weight_grads":[3,4],"max_norm":1}, [5,1,.6,.8],
[round(v,6) for v in (before,after,*vector)],
"clip both gradient components in-place by their combined norm")
weight_a.grad = None
(0.25*weight_a).backward()
returned = float(torch.nn.utils.clip_grad_norm_([weight_a],1.0))
check("clip_keeps_small_gradient", {"gradient":.25,"max_norm":1}, [.25,.25],
[returned,float(weight_a.grad)], "compare pre-clip norm and untouched value")
def chain_gain(gain):
x = torch.tensor(1.,dtype=torch.float64,requires_grad=True)
value = x
for _ in range(6):
value = gain*value
value.backward()
return float(x.grad)
check("gradient_scale_and_skip_path", {"local_gains":[.25,4,1.25],"depth":6}, [.25**6,4**6,1.25**6],
[chain_gain(gain) for gain in (.25,4,1.25)],
"compare a small, large, and identity-plus-small local factor across six stages")
layer_grads = np.array([.001,.002,.009,.05,.2,1.5])
buckets, _ = np.histogram(layer_grads,[0,.01,.1,1,2])
check("gradient_histogram_local", {"abs_gradients":layer_grads.tolist(),"edges":[0,.01,.1,1,2]}, [3,1,1,1],
buckets.tolist(), "count local gradient magnitudes by bin")
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。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows、Python 3.12.14、PyTorch 2.10 CPU。
入口文件:projects/ai-math-gradient-lab/gradient-lab.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
gradient-lab.py,或下载右侧课程工程包。 - 确认本地已准备 Windows、Python 3.12.14、PyTorch 2.10 CPU。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联54章) · 含当前章节或实例 · mbskycom202612a33.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a61.zip