SGD、动量与 Adam
在同一目标上实跑更新,区分历史方向、二阶矩和解耦权重衰减。
学完这一章,你能够
- 在同一目标上实跑更新,区分历史方向、二阶矩和解耦权重衰减。
三种更新各自积累什么
SGD 使用随机样本或小批的梯度估计 g,并按 θ新=θ旧−ηg 更新。固定全量数据时得到同式全量梯度步。随机批的方向会随样本波动,收敛表现也取决于学习率和数据。
用 v←βv+ηg、θ←θ−v 可写出固定学习率下的动量更新。历史方向一致时会累积,反向时可能减弱摆动,也可能越过最优点。PyTorch SGD 把学习率放在动量缓冲外,调度学习率时需要按接口定义解释。
Adam 同时维护梯度的一阶移动均值与梯度平方的二阶移动均值,再用偏置修正与 ε 计算逐参数缩放。外部学习率仍是共享的控制量。AdamW 把权重衰减从梯度矩估计中解耦。
从同一起点实测完整轨迹
目标 J(w,b)=(w−3)²+2(b+2)²,起点 (0,0) 的损失是 17。给三种方法同样的 0.1 学习率,第一步后全量梯度和动量都为 8.64,Adam 为 15.63。三十步末,本例依次约为 0.000014、0.071263、0.260575。初值和每一步后损失分别记录,收敛排序随目标和超参数改变。

在另一个实验中只考察权重衰减。权重为 2、学习率 0.1、衰减 0.2、数据梯度为零。耦合 Adam 的权重变为约 1.9,衰减项参与了二阶矩;AdamW 的权重变为 1.96,二阶矩为零。
按任务与更新机制选择
| 优化器 | 常见用途 | 复核依据 |
|---|---|---|
| 带动量的 SGD | 在视觉模型训练中常见。 | 本例对照逐步更新。实际效果依赖批量、步长与动量。 |
| Adam | 曾用于许多 Transformer 训练方案。 | 一阶、二阶矩及偏置修正决定每个参数的步幅。 |
| AdamW | 常用于需要解耦权重衰减的模型训练。 | 零数据梯度时仍执行参数乘法衰减,动量估计保持零。 |
记录三种更新的每一步损失
"""Compare actual parameter trajectories on one differentiable objective."""
import argparse
import json
from math import sqrt
import platform
def objective(w,b):
return (w-3)**2+2*(b+2)**2
def trajectory(method,lr,steps,record_parameters=False):
values=[0.,0.]
velocity=[0.,0.]
m=[0.,0.]
v=[0.,0.]
records=[[values.copy(),objective(*values)]]
for step in range(1,steps+1):
gradient=[2*(values[0]-3),4*(values[1]+2)]
for i,g in enumerate(gradient):
if method=="sgd":
delta=lr*g
elif method=="momentum":
velocity[i]=.9*velocity[i]+lr*g
delta=velocity[i]
elif method=="adam":
m[i]=.9*m[i]+.1*g
v[i]=.999*v[i]+.001*g*g
delta=lr*(m[i]/(1-.9**step))/(sqrt(v[i]/(1-.999**step))+1e-8)
else:
raise ValueError(method)
values[i]-=delta
records.append([values.copy(),objective(*values)])
return records if record_parameters else [loss for _,loss in records]
def main():
parser=argparse.ArgumentParser()
parser.add_argument("--torch",action="store_true")
args=parser.parse_args()
versions={}
cases=[]
def check(name,inputs,expected,actual,operation):
assert expected==actual,(name,expected,actual)
cases.append(dict(name=name,input=inputs,expected=expected,actual=actual,operation=operation,passed=True))
method_names=["sgd","momentum","adam"]
traces=[trajectory(name,.1,30) for name in method_names]
check("objective_before_and_after_first_step",{"start":[0,0],"lr":.1},
[[17,8.64],[17,8.64],[17,15.63]],[[round(x,6) for x in trace[:2]] for trace in traces],
"separate initial objective from the first post-update loss")
check("momentum_can_be_nonmonotonic",{"beta":.9,"steps":30},True,
any(b>a for a,b in zip(traces[1],traces[1][1:])),
"compare successive measured values on the momentum path")
check("trajectory_timing_and_method_order",{"methods":method_names,"lr":.1,"steps":30},[31]*3,
[len(trace) for trace in traces],"record the initial state and all thirty step outcomes")
cases[-1]["final_losses"]=[trace[-1] for trace in traces]
if args.torch:
import torch
versions["torch"]=torch.__version__
frameworks=[]
for label in method_names:
param=torch.nn.Parameter(torch.zeros(2,dtype=torch.float64))
if label=="adam":
opt=torch.optim.Adam([param],lr=.1)
else:
opt=torch.optim.SGD([param],lr=.1,momentum=.9 if label=="momentum" else 0)
history=[float(objective(*param).detach())]
for _ in range(30):
opt.zero_grad(set_to_none=True)
objective(*param).backward()
opt.step()
history.append(float(objective(*param).detach()))
frameworks.append(history)
check("sgd_native_matches_hand_updates",{"lr":.1,"steps":30},True,
all(abs(a-b)<1e-10 for a,b in zip(frameworks[0],traces[0],strict=True)),
"compare each full-gradient SGD loss with PyTorch")
check("momentum_native_matches_hand_updates",{"momentum":.9,"lr":.1,"steps":30},True,
all(abs(a-b)<1e-10 for a,b in zip(frameworks[1],traces[1],strict=True)),
"compare momentum loss trajectories under constant learning rate")
check("adam_native_matches_hand_updates",{"betas":[.9,.999],"lr":.1,"steps":30},True,
all(abs(a-b)<1e-8 for a,b in zip(frameworks[2],traces[2],strict=True)),
"compare each real Adam loss with bias-corrected first and second moments")
final=[]
for constructor in (torch.optim.Adam,torch.optim.AdamW):
w=torch.nn.Parameter(torch.tensor(2.,dtype=torch.float64))
opt=constructor([w],lr=.1,weight_decay=.2)
w.grad=torch.zeros_like(w)
opt.step()
final.append([round(float(w.detach()),7),round(float(opt.state[w]["exp_avg_sq"]),7)])
check("adamw_decoupled_weight_decay",{"weight":2,"data_grad":0,"lr":.1,"decay":.2},
[[1.9,.00016],[1.96,0.]],final,
"compare coupled Adam weight decay and decoupled AdamW while data gradient is zero")
print(json.dumps(dict(version=platform.python_version(),library_versions=versions,cases=cases)))
if __name__=="__main__":
main()
- 三条轨迹从损失 17 开始,并以实际更新后的损失作比较。
所需环境:Windows、Python 3.12.14。torch 2.10.0+cpu。
当前源码 SHA256:df19cddd76bf75f030836e55ede045bc527372fe1ddda0d57e4160a0003e6912
复跑实验
解压后按 README 运行自编程序。
所需环境:Windows、Python 3.12.14。torch 2.10.0+cpu。
ZIP SHA256:dfe8eb88e72a0d48b7156e7a175882a2739770c625a6e7350cbeed077cdee044
常见错误与边界
- 把同目标、同初值和同测量时机作为比较条件。
- 根据任务验证超参数。
练习与解答
只有解耦衰减时,参数 2、学习率 0.1、衰减 0.2,参数更新到哪里?
展开参考解答
2×(1−0.1×0.2)=1.96。