Files
tiny-gpt/spatial/train.py
T
x 188419a275 fix(spatial): 预热 100 步是脚枪,默认改为 300
lr 3e-3 下前 100 步是一次 10 倍的跳变,自由度集合任务掉进去就再没出来。
同 lr、同步数,只改这一个数:seed0 的 dof.set 0.203 → 1.000,三种子在 14 个家族上
全部 1.000(含弃权)。
2026-12-03 21:56:11 +08:00

223 lines
9.6 KiB
Python

"""Train / resume / eval on the relational task.
Two contract points from the plan that the old ``mm/train.py`` could not meet:
* checkpoints are replaced atomically and carry optimizer, step and RNG state,
so an interrupted run continues into the same next batch;
* evaluation reports over-confidence on insufficient-evidence samples and
certificate validity, not just accuracy -- a model that answers "true"
everywhere would look fine on accuracy alone.
"""
from __future__ import annotations
import json
import math
import os
import random
import time
import torch
import torch.nn.functional as F
from . import checker, generator
from .data import collate
from .model import RelationBackbone, QUERY_KINDS
def make_batch(families, seed: int, step: int, batch_size: int):
rng = random.Random(f"batch:{seed}:{step}")
out = []
for _ in range(batch_size):
fam = rng.choice(families)
out.append(generator.make(fam, seed=seed, index=rng.randrange(10 ** 6)))
return out
def batch_loss(model, tensors):
out = model(tensors["feat"], tensors["pad_mask"], tensors["edge_index"],
tensors["edge_type"], tensors["edge_mask"], tensors["q_ents"], tensors["q_kind"],
tensors.get("edit_op"), tensors.get("edit_idx"), tensors.get("edge_removed"),
tensors.get("edge_feat"), tensors.get("scene"), tensors.get("dangling"))
l_ans = F.cross_entropy(out["answer"], tensors["answer"])
l_chg = F.cross_entropy(out["change"], tensors["change"])
ev_logits = out["evidence"][tensors["edge_mask"]]
ev_target = tensors["evidence"][tensors["edge_mask"]]
l_ev = F.binary_cross_entropy_with_logits(ev_logits, ev_target) if ev_logits.numel() else l_ans * 0
total = l_ans + 0.5 * l_chg + 0.5 * l_ev
return total, {"answer": float(l_ans.detach()), "change": float(l_chg.detach()),
"evidence": float(l_ev.detach()),
"temp": float(out["temp"])}, out
def _ece(probs, correct, n_bin: int = 5) -> float:
"""Top-label expected calibration error.
Accuracy alone cannot show a miscalibrated head: a model that answers every
row with confidence 0.99 and is right 72% of the time scores the same
accuracy as one that says 0.72. The temperature is only meaningful if this
number is reported next to it.
"""
conf = probs.max(-1).values
hit = (probs.argmax(-1) == correct).float()
total = 0.0
for b in range(n_bin):
lo, hi = b / n_bin, (b + 1) / n_bin
m = (conf > lo) & (conf <= hi) if b else (conf <= hi)
n = int(m.sum())
if n:
total += n * abs(float(hit[m].mean()) - float(conf[m].mean()))
return total / max(1, probs.size(0))
@torch.no_grad()
def evaluate(model, families, seed: int, n: int, max_entities: int = 32) -> dict:
model.eval()
batch = make_batch(families, seed + 1, 0, n)[:n]
device = next(model.parameters()).device
tensors = collate(batch, max_entities)
tensors = {k: (v.to(device) if torch.is_tensor(v) else v) for k, v in tensors.items()}
_, losses, out = batch_loss(model, tensors)
pred = out["answer"].argmax(-1).tolist()
pred_chg = out["change"].argmax(-1).tolist()
answerable = [i for i, sc in enumerate(batch) if sc.label.answer != "unknown"]
unknown = [i for i, sc in enumerate(batch) if sc.label.answer == "unknown"]
correct = sum(1 for i in answerable if pred[i] == ["true", "false", "unknown"].index(batch[i].label.answer))
overconfident = sum(1 for i in unknown if pred[i] != 2)
chg_rows = [i for i, sc in enumerate(batch) if sc.label.change != "unknown"]
chg_correct = sum(1 for i in chg_rows
if pred_chg[i] == ["changed", "same", "unknown"].index(batch[i].label.change))
# certificate check on rows the model calls "true"
probs = torch.sigmoid(out["evidence"])
valid = total = 0
for i, sc in enumerate(batch):
if pred[i] != 0:
continue
ids = [e.eid for e in sc.obs.edges]
picked = [ids[k] for k in range(len(ids)) if probs[i, k] > 0.5]
total += 1
valid += int(bool(picked) and checker.validate_evidence(sc.full, sc.query, picked))
model.train()
ece = _ece(torch.softmax(out["answer"], -1), tensors["answer"])
return {
"answer_acc": correct / max(1, len(answerable)),
"answerable": len(answerable),
"overconf": overconfident / max(1, len(unknown)),
"n_unknown": len(unknown),
"change_acc": chg_correct / max(1, len(chg_rows)),
"evidence_valid": valid / max(1, total),
"n_true_pred": total,
"ece": ece,
"temp": float(out["temp"]),
"loss": losses,
}
def save(path: str, model, opt, step: int, config: dict):
os.makedirs(os.path.dirname(path), exist_ok=True)
tmp = path + ".tmp"
torch.save({
"model": model.state_dict(),
"opt": opt.state_dict() if opt is not None else None,
"step": step,
"config": config,
"torch_rng": torch.get_rng_state(),
"py_rng": random.getstate(),
}, tmp)
os.replace(tmp, path) # atomic: a crash leaves the old file intact
def _build(m: dict) -> RelationBackbone:
return RelationBackbone(d=m["d"], n_layer=m["n_layer"], n_head=m["n_head"],
dropout=m["dropout"], max_entities=m["max_entities"],
rounds=m.get("rounds", 2), n_evidence=m.get("n_evidence", 4))
def load(path: str, device="cpu"):
# always restore on CPU: map_location=device would drag the RNG state (a
# ByteTensor) onto the GPU, and set_rng_state only accepts a CPU one
ck = torch.load(path, map_location="cpu", weights_only=False)
cfg = ck["config"]["model"]
model = _build(cfg)
model.load_state_dict(ck["model"])
opt = torch.optim.AdamW(model.parameters(), lr=ck["config"]["optim"]["lr"],
weight_decay=ck["config"]["optim"]["weight_decay"])
if ck.get("opt"):
opt.load_state_dict(ck["opt"])
torch.set_rng_state(ck["torch_rng"].to(torch.uint8))
random.setstate(ck["py_rng"])
if ck.get("opt"):
# the checkpoint is restored on CPU, so the moment and variance buffers
# have to follow the parameters onto the device
for state in opt.state.values():
for key, val in state.items():
if torch.is_tensor(val):
state[key] = val.to(device)
model.to(device)
return model, opt, ck["step"], ck["config"]
def run(config: dict, resume: bool = False, steps: int = None, verbose: bool = True) -> dict:
device = "cuda" if torch.cuda.is_available() else "cpu"
torch.manual_seed(config["seed"])
out_dir = config["out_dir"]
ckpt = os.path.join(out_dir, "ckpt.pt")
if resume and os.path.exists(ckpt):
model, opt, start, config = load(ckpt, device)
if verbose:
print(f"resume from step {start}")
else:
m = config["model"]
model = _build(m)
opt = torch.optim.AdamW(model.parameters(), lr=config["optim"]["lr"],
weight_decay=config["optim"]["weight_decay"])
start = 0
model.to(device).train()
total_steps = start + (steps if steps is not None else config["optim"]["steps"])
base_lr = config["optim"]["lr"]
# 100 was a footgun: at lr 3e-3 the first updates are a 10x jump and the
# freedom set task never recovered from the basin it landed in. Same lr,
# same steps, only this number changed: dof.set 0.203 -> 1.000 on seed 0,
# and 3/3 seeds green across all 14 families.
warmup = config["optim"].get("warmup", 300)
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"])
tensors = {k: v.to(device) if torch.is_tensor(v) else v for k, v in tensors.items()}
loss, parts, _ = batch_loss(model, tensors)
opt.zero_grad(set_to_none=True)
loss.backward()
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} lr {lr:.4f} "
f"(ans {parts['answer']:.3f} chg {parts['change']:.3f} ev {parts['evidence']:.3f})")
save(ckpt, model, opt, total_steps, config)
metrics = evaluate(model, config["data"]["val_families"], config["seed"], config["eval"]["n"])
if verbose:
print(f"val {json.dumps({k: (round(v, 3) if isinstance(v, float) else v) for k, v in metrics.items() if k != 'loss'})}")
print(f"done in {time.time() - t0:.1f}s device={device}")
metrics["secs"] = round(time.time() - t0, 2)
return metrics