"""Generate a plot of scalar quadratic descent and check framework learning-rate controls."""
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
CASES = []
def record(name, operation, inputs, expected, actual):
assert actual == expected, (name, expected, actual)
CASES.append(dict(name=name, operation=operation, inputs=inputs,
expected=expected, actual=actual, passed=True))
def trajectory(rate, steps, start=8.):
positions = [start]
for _ in range(steps):
current = positions[-1]
positions.append(current - rate * 2 * current)
return positions
def main():
cli = argparse.ArgumentParser()
cli.add_argument("--torch", action="store_true")
args = cli.parse_args()
versions = {"matplotlib": matplotlib.__version__}
rates = (.01, .2, 1.05)
sequences = [trajectory(rate, 30) for rate in rates]
end = [seq[-1] for seq in sequences]
record("historical_rate_endpoints", "check signed positions and loss after 30 updates",
{"start": 8, "steps": 30, "rates": rates},
[[4.363875, .000002, 139.595218], [19.043401, 0., 19486.824931]],
[[round(x, 6) for x in end], [round(x * x, 6) for x in end]])
record("threshold_hit_steps", "locate the first step satisfying the strict absolute threshold",
{"threshold": .01, "limit": 1000, "rates": rates}, [331, 14, None],
[next((index for index, x in enumerate(trajectory(rate, 1000)) if abs(x) < .01), None)
for rate in rates])
comparison = [0, .25, .5, .75, 1., 1.05, -.1]
record("all_stability_regions", "compare representative two-step sign and magnitude changes",
comparison, [[8., 8.], [4., 2.], [0., 0.], [-4., 2.], [-8., 8.], [-8.8, 9.68], [9.6, 11.52]],
[[round(x, 8) for x in trajectory(rate, 2)[1:]] for rate in comparison])
record("stationary_start_is_special", "start at the minimum even under noncontracting rates",
[0, 1, 1.05], [[0., 0., 0.]] * 3,
[trajectory(rate, 2, start=0.) for rate in (0, 1, 1.05)])
output = Path(__file__).resolve().parent / "outputs/rate-comparison.png"
output.parent.mkdir(exist_ok=True)
fig, panels = plt.subplots(1, 2, figsize=(9, 4.1), layout="constrained")
for seq, rate, color in zip(sequences, rates, ("#136f7e", "#5962a7", "#a95128")):
panels[0].plot(range(len(seq)), seq, label=f"rate {rate:g}", color=color)
panels[1].semilogy(range(len(seq)), [x*x for x in seq], label=f"rate {rate:g}", color=color)
for panel, title, ylabel in zip(panels, ("Signed position", "Log-scale loss"), ("x", "x squared")):
panel.set(title=title, xlabel="Step", ylabel=ylabel)
panel.grid(alpha=.3)
panel.legend()
fig.savefig(output, dpi=100)
plt.close(fig)
image = output.read_bytes()
record("rate_plot_rendered", "plot signed paths and log-scale losses and read PNG dimensions",
{"paths": 3, "points_per_path": 31}, [[900, 410], True],
[list(struct.unpack(">II", image[16:24])), image.startswith(b"\x89PNG\r\n\x1a\n")])
CASES[-1]["artifact"] = dict(path="outputs/rate-comparison.png", sha256=sha256(image).hexdigest(), bytes=len(image))
if args.torch:
import torch
versions["torch"] = torch.__version__
knob = torch.tensor(1., dtype=torch.float64, requires_grad=True)
optimizer = torch.optim.SGD([knob], lr=.08)
decay = torch.optim.lr_scheduler.StepLR(optimizer, step_size=1, gamma=.5)
seen = [optimizer.param_groups[0]["lr"]]
for _ in range(3):
optimizer.step()
decay.step()
seen.append(optimizer.param_groups[0]["lr"])
record("torch_decay_schedule", "read the rate used after each scheduler tick",
{"initial": .08, "factor": .5}, [.08, .04, .02, .01], [round(x, 8) for x in seen])
optimizer = torch.optim.SGD([knob], lr=.08)
warmup = torch.optim.lr_scheduler.LinearLR(optimizer, start_factor=.25, total_iters=3)
seen = [optimizer.param_groups[0]["lr"]]
for _ in range(3):
optimizer.step()
warmup.step()
seen.append(optimizer.param_groups[0]["lr"])
record("torch_warmup_schedule", "raise the rate linearly over three ticks",
{"target": .08, "start_factor": .25, "ticks": 3},
[.02, .04, .06, .08], [round(x, 8) for x in seen])
params = torch.tensor([1., 1.], dtype=torch.float64, requires_grad=True)
adam = torch.optim.Adam([params], lr=.01)
params.grad = torch.tensor([1., 4.], dtype=torch.float64)
adam.step()
moments = adam.state[params]["exp_avg_sq"].tolist()
record("torch_adam_moments", "observe separate squared-gradient moment estimates",
{"global_rate": .01, "first_gradients": [1, 4]}, [.001, .016], [round(x, 8) for x in moments])
print(json.dumps(dict(version=platform.python_version(), library_versions=versions, cases=CASES)))
if __name__ == "__main__":
main()
本例需在 Windows、Python 3.12.14。matplotlib 3.11.2;torch 2.10.0+cpu。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows、Python 3.12.14。matplotlib 3.11.2;torch 2.10.0+cpu。
入口文件:projects/ai-math-learning-rate-comparison-lab/quadratic-step-sizes.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
quadratic-step-sizes.py,或下载右侧课程工程包。 - 确认本地已准备 Windows、Python 3.12.14。matplotlib 3.11.2;torch 2.10.0+cpu。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联54章) · 含当前章节或实例 · mbskycom202612a33.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a65.zip