梯度与变化方向
用单位方向、损失曲面和参数更新理解梯度,并实际观察梯度裁剪。
学完这一章,你能够
- 用单位方向、损失曲面和参数更新理解梯度,并实际观察梯度裁剪。
梯度汇集所有坐标方向的偏导
在欧氏坐标下,多变量可微函数的梯度把每个坐标方向的偏导组成向量。对 f(x,y)=x²+y²,梯度是 (2x,2y)。在 (1.5,1) 得到 (3,2),欧氏范数为 √13,约为 3.606。
沿单位向量 u 的方向导数为 ∇f·u=‖∇f‖cosθ。当梯度非零,沿归一化梯度的斜率最大,沿反向最小,沿垂直方向的一阶变化率为零。向量长度若加倍,点积也加倍,所以比较方向时要先归一化。
在梯度为零的点,各单位方向的一阶变化率都是零。继续观察邻域可区分极值、鞍点和其他驻点。例如 x²−y² 在原点向两个坐标方向分别上升和下降。
从局部方向走到实际下一步
把坡面比作损失函数。每次在当前位置重新测方向,再选步长 η>0,按 θ新=θ旧−η∇J 更新。可微且梯度非零时,足够小的正步长沿负梯度会降低目标值。过大的步幅可能跨过谷底,更新后仍要看损失。
在曲面实验里,改变视角会重投影网格和箭头,采样点、梯度和损失保持不变。棕色和绿色箭头分别显示正负梯度在曲面切平面上的方向。从 (1.5,1) 用 η=0.25 更新后,损失从 3.25 变为 0.8125。改用 η=1.25,第一步的损失反而变为 7.3125。

训练、裁剪和监测
在 PyTorch 中可先清梯度,再调用 loss.backward() 计算梯度,最后由 optimizer.step() 更新参数。无动量和权重衰减的单步 SGD 与本例负梯度公式一致。带动量等状态的优化器要按自身更新关系解释。
反传链上的局部导数连乘可以放大或缩小梯度。残差块 x+F(x) 的导数含一条恒等项,有助于梯度经过深层结构。标量实验比较六层局部系数 0.25、4 和 1.25;实际网络的矩阵、激活和分布还会影响结果。
clip_grad_norm_() 可以把参与参数的梯度视为拼接后的向量,使用 L2 范数检查整体阈值。若向量是 (3,4),阈值取 1 时两分量约变为 (0.6,0.8)。阈值是训练配置。应在反向计算之后、参数更新之前裁剪。
可把每层梯度的范数或分布写入 TensorBoard 或 W&B,按层、按步与训练历史比较。统一阈值无法判断所有层的梯度是否异常。随实验附带的本地直方图先验证区间计数。
测量梯度、损失更新和裁剪结果
"""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()
- 在 (1.5,1) 得到梯度 (3,2),一次 η=0.25 的更新把损失从 3.25 降到 0.8125。
所需环境:Windows、Python 3.12.14、PyTorch 2.10 CPU。
当前源码 SHA256:532141ec92dc84e2f6e91ee083193183d5680e2db7ec48aff6f8f6f7d6e45bd0
复跑实验
解压后按 README 运行自编程序。
所需环境:Windows、Python 3.12.14、PyTorch 2.10 CPU。
ZIP SHA256:f5d7193a81250fce060f7f8f69c630a8d44236162e1b18220cc6bc6c69594b90
常见错误与边界
- 方向比较要归一化。
- 用更新后的损失检查步长是否合适。
- 记录裁剪前的梯度范数以便诊断。
练习与解答
在 (1.5,1) 的下降最快单位方向是什么?
展开参考解答
把负梯度 (−3,−2) 除以 √13。