fix(spatial): 学习率预热+余弦衰减,loss 不再两个数量级地跳

平坦 3e-3 下 loss 从 step 1200 的 0.085 跳到 2000 的 1.126,于是"哪个家族弱"
这个判断其实取决于采样恰好在波峰还是波谷。改为预热 100 步后余弦退火到 10%。
This commit is contained in:
liuhuajie committed 2026-12-03 18:27:56 +08:00
1 parent f5443278b9
commit 6af4cb8799
1 file changed
+17 -1
+17 -1
View File
@@ -11,6 +11,7 @@ Two contract points from the plan that the old ``mm/train.py`` could not meet:
from __future__ import annotations
import json
import math
import os
import random
import time
@@ -178,8 +179,23 @@ def run(config: dict, resume: bool = False, steps: int = None, verbose: bool = T
model.to(device).train()
total_steps = start + (steps if steps is not None else config["optim"]["steps"])
base_lr = config["optim"]["lr"]
warmup = config["optim"].get("warmup", 100)
min_frac = config["optim"].get("min_lr_frac", 0.1)
t0 = time.time()
for step in range(start, total_steps):
# a flat 3e-3 ran 0.085 at step 1200 and 1.126 at step 2000: the loss
# oscillated by two orders of magnitude, so the "which family is weak"
# question was really "which family happened to be sampled at a peak".
# Warm up, then decay, so the curve means something.
if step < warmup:
lr = base_lr * (step + 1) / warmup
else:
frac = (step - warmup) / max(1, total_steps - warmup)
lr = base_lr * (min_frac + (1 - min_frac) * 0.5 * (1 + math.cos(math.pi * frac)))
for g in opt.param_groups:
g["lr"] = lr
batch = make_batch(config["data"]["train_families"], config["seed"], step,
config["optim"]["batch"])
tensors = collate(batch, config["model"]["max_entities"])
@@ -190,7 +206,7 @@ def run(config: dict, resume: bool = False, steps: int = None, verbose: bool = T
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
opt.step()
if verbose and (step % max(1, config["optim"]["log_every"]) == 0):
print(f"step {step:4d} loss {float(loss.detach()):.4f} "
print(f"step {step:4d} loss {float(loss.detach()):.4f} lr {lr:.4f} "
f"(ans {parts['answer']:.3f} chg {parts['change']:.3f} ev {parts['evidence']:.3f})")
save(ckpt, model, opt, total_steps, config)