对比 SGD、Momentum 和 Adam 的优化轨迹
对比狭长二次谷地上的首达步数、坐标异号与最终损失。
学完这一章,你能够
- 对比狭长二次谷地上的首达步数、坐标异号与最终损失。
分别写出三种更新规则
令 f(x,y)=0.5x²+5y²,完整梯度是 (x,10y)。普通梯度更新没有历史状态。这里的 Momentum 用 v←0.9v+0.1g,随后按学习率沿 v 更新。Adam 维护一阶、二阶矩,对两者作初始偏差校正,再按各坐标的校正统计量更新。
比较首达步数和最后一步
固定起点 (4,4) 和 60 步。普通梯度与 EMA 动量用 0.1,Adam 用 0.3。严格以到原点距离小于 0.05 计第一次到达,得到 42、未达到、15。只在相邻非零 y 异号时计为跨轴,分别有 0、6、2 次。普通梯度第一步让 y 精确归零,这是一条到达轴的记录。

比较算法时要分开报告固定步数的损失、阈值首次达成与后续稳定性。同一实验还跑相同学习率的对照。AdamW 使用解耦权重衰减。Transformer 的具体优化器与泛化效果由任务、数据、正则化及训练预算决定。
训练任务中的优化器选择
| 场景 | 可选方案 | 比较条件 |
|---|---|---|
| 常规训练 | SGD/Momentum/Adam | SGD、Momentum 和 Adam 均可候选。 |
| 大型编码器训练 | AdamW | AdamW 常作候选,权重衰减可独立于数据梯度。 |
| 精度与泛化 | 以验证集比较候选 | 对训练速度和样本外指标分别比较。二次谷地只验证轨迹,不提供泛化结论。 |
复跑三种更新并画出参数路径
"""Compare normalized momentum, Adam and gradient updates in a fixed quadratic valley."""
import argparse
from hashlib import sha256
import json
from pathlib import Path
import platform
import struct
import matplotlib
matplotlib.use("Agg")
from matplotlib import pyplot as plt
import numpy as np
def record(cases,name,operation,inputs,expected,actual):
assert expected == actual, (name,expected,actual)
cases.append(dict(name=name,operation=operation,inputs=inputs,expected=expected,actual=actual,passed=True))
def path(kind,rate):
p=np.array([4.,4.])
a=np.zeros(2)
b=np.zeros(2)
points=[p.copy()]
for t in range(1,61):
g=p*np.array([1.,10.])
direction=g
if kind!="GD":
a=.9*a+.1*g
direction=a
if kind=="Adam":
b=.999*b+.001*g*g
direction=(a/(1-.9**t))/(np.sqrt(b/(1-.999**t))+1e-8)
p=p-rate*direction
points.append(p)
return np.array(points)
def main():
cli=argparse.ArgumentParser()
cli.add_argument("--torch",action="store_true")
args=cli.parse_args()
cases=[]
versions={"numpy":np.__version__,"matplotlib":matplotlib.__version__}
names=("GD","EMA momentum","Adam")
rates=(.1,.1,.3)
points=[path(name,rate) for name,rate in zip(names,rates,strict=True)]
value=lambda r: .5*r[...,0]**2+5*r[...,1]**2
hits=[next((idx for idx,d in enumerate(np.linalg.norm(h,axis=1)) if d<.05),None) for h in points]
losses=[round(float(value(h[-1])),8) for h in points]
record(cases,"first_hit_is_not_last_loss","measure first hit and loss after the final update",
{"steps":60,"rates":rates,"threshold":.05},[[42,None,15],[.00002583,.11606783,.00137983]],[hits,losses])
crosses=[int(np.sum(h[1:,1]*h[:-1,1]<0)) for h in points]
record(cases,"sign_crossing_excludes_hitting_zero","compare true axis crossing with sign-to-zero event",
{"axis":"y"},[[0,6,2],0.],[crosses,points[0][1,1]])
equal=[path(kind,.1) for kind in names]
record(cases,"same_rate_comparison","hold the base rate fixed and inspect terminal losses",
{"rate":.1,"rules":names},[True,True],[bool(value(equal[0][-1])<value(equal[1][-1])),
bool(value(equal[2][-1])!=value(points[2][-1]))])
record(cases,"first_update_momentum_convention","check normalized EMA's effective first movement",
{"rate":.1,"beta":.9},[3.96,3.6],np.round(points[1][1],6).tolist())
record(cases,"adam_bias_correction","measure each first step after moment correction",
{"rate":.3},[3.7,3.7],np.round(points[2][1],6).tolist())
output=Path(__file__).resolve().parent/"outputs/valley-paths.png"
output.parent.mkdir(exist_ok=True)
fig,axes=plt.subplots(1,2,figsize=(9,4.2),layout="constrained")
for name,h,c in zip(names,points,("#166c7d","#a44c26","#6359a3"),strict=True):
axes[0].plot(h[:,0],h[:,1],label=name,color=c)
axes[1].semilogy(value(h),label=name,color=c)
axes[0].set(title="Coordinate trajectories",xlabel="x",ylabel="y")
axes[1].set(title="Loss after each update",xlabel="Update",ylabel="Loss")
for ax in axes:
ax.grid(alpha=.3)
ax.legend()
fig.savefig(output,dpi=100)
plt.close(fig)
data=output.read_bytes()
record(cases,"valley_paths_rendered","draw three coordinate and loss paths",
{"paths":3,"points_per_path":61},[[900,420],True],
[list(struct.unpack(">II",data[16:24])),data.startswith(b"\x89PNG\r\n\x1a\n")])
cases[-1]["artifact"]=dict(path="outputs/valley-paths.png",sha256=sha256(data).hexdigest(),bytes=len(data))
if args.torch:
import torch
versions["torch"]=torch.__version__
x=torch.tensor(10.,dtype=torch.float64,requires_grad=True)
x.grad=torch.tensor(0.,dtype=torch.float64)
optim=torch.optim.AdamW([x],lr=.1,weight_decay=.2)
optim.step()
record(cases,"decoupled_decay_with_zero_gradient","apply AdamW with zero data gradient and nonzero decay",
{"initial":10,"decay":.2,"rate":.1},[9.8,0.],
[round(x.item(),8),optim.state[x]["exp_avg"].item()])
print(json.dumps(dict(version=platform.python_version(),library_versions=versions,cases=cases)))
if __name__=="__main__":
main()
- 三种方法的首达阈值分别为 42 步、60 步内未达到、15 步。
所需环境:Windows、Python 3.12.14。numpy 2.5.4;matplotlib 3.11.2;torch 2.10.0+cpu。
当前源码 SHA256:5caed2fc3917a9ce24fb53077a18c041e26f085ab5745d6a9edf01a3755d3550
复跑实验
解压后按 README 运行自编程序。
所需环境:Windows、Python 3.12.14。numpy 2.5.4;matplotlib 3.11.2;torch 2.10.0+cpu。
ZIP SHA256:b9c7c3844a53126bdad8eab5171468e6b48cad0f486424b7c5ebed5a0d67f85a
常见错误与边界
- 声明动量约定、基础学习率和初值。
- 相同优化步数与相同有效步幅是不同的比较条件。
练习与解答
为什么这里普通梯度没有跨 y=0 轴?
展开参考解答
学习率 0.1 乘以 y 向的曲率 10,第一步把 y 乘以零。