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

记录三种更新的每一步损失

PYTHONWindows、Python 3.12.14。torch 2.10.0+cpu。optimizers-lab.py
optimizers-lab.py101 行
"""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()
本例需在 Windows、Python 3.12.14。torch 2.10.0+cpu。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows、Python 3.12.14。torch 2.10.0+cpu。

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

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

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

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

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

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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