Files
tiny-gpt/spatial/train.py
T
liuhuajie 085ad1415f feat(spatial): 跳数偏置、边内容进 value、证据回灌第二轮、学习温度
四件结构补齐,每件都有对应的失效模式:

- 跳数偏置:原来只靠 no-position 的注意力,实体顺序被打乱会让输出漂移。
  改为按截断最短路分桶的注意力偏置(HOP_MAX=4),并遵守干预语义——被切掉的
  边不参与连通,否则"剪掉主干后是否还连通"的跳数本身就是错的。
- 边内容进 value:边类型此前只是注意力偏置,只能表达"看那边",不能表达
  "那是一个 0.8 的接触面、锁的是 tz 轴"。现在把入射边的特征投影后累加进实体
  的 value,接触面积由两端 box 重叠算出,并按单位归一化。
- 证据回灌:第一轮选出 top-k 边作为候选凭证,第二轮让所有实体都能注意到
  自己所在的那张凭证。此前证据头和答案头看的根本不是同一个对象。
- 学习温度:答案/变化/证据 logits 统一除以 exp(log_temp),并在评估里加 ECE。
  只报准确率的话,置信度 0.99 而正确率 0.72 和直接报 0.72 是同一个数。

另外:把边偏置的累加改成扁平 index_put_(accumulate),平行边不再互相覆盖;
新增 configs/cross.json(训练 cond.p1/area.sup2/dof.c6,验证 held-out 家族)。
2026-12-03 18:14:19 +08:00

203 lines
8.5 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 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"))
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"])
t0 = time.time()
for step in range(start, total_steps):
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} "
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