fhyfhy's picture
Add code/
74b7543 verified
Raw History Blame Contribute Delete
11.8 kB
"""Loop-depth dynamics of a trained DiscoLoop model (pure evaluation).
For a checkpoint trained with K loops, we re-run the recurrence for n = 1..N loops
and, at the **answer position** (the position whose logits predict the answer),
track how the state and its decoded distribution change from one loop to the next:
cos(H_n, H_{n-1}) how much the hidden state still moves
TV(p_n, p_{n-1}) how much the decoded distribution still moves
TV(p_n, onehot(answer)) how far the decoded distribution is from the answer
(equal to 1 - p_n[answer])
Unrolling convention. We mirror the training code path exactly: loops 1..n-1 apply
the DiscoLoop update and loop n is the vanilla read-out step (`zero_final_gate`).
The trained model has per-stage norms for the DiscoLoop steps 0..K-2 only, so for
n > K the extra steps reuse the last *trained* norm (`--norm-policy last`, default);
`--norm-policy own` instead uses each stage's own norm, which is untrained (identity
scale) beyond the trained depth.
Usage:
python loop_dynamics.py --ckpt outputs/scratch_2345hop_m5/stage2_hyper/checkpoint-100000 \
--data data/twin_2345hop_truood_diff.500.50.10 --max-loops 10 --n-samples 1000
"""
import argparse
import json
import types
from pathlib import Path
import torch
import torch.nn.functional as F
from transformers import default_data_collator
import train_twin_hyper as m
# reference categorical palette, slots 1-3 in fixed order (blue / orange / aqua)
SERIES = [
("cos(H_n, H_n-1)", "#2a78d6"),
("TV(p_n, p_n-1)", "#eb6834"),
("TV(p_n, answer)", "#1baf7a"),
]
INK, INK_MUTED, GRID = "#0b0b0b", "#52514e", "#d8d7d2"
def build_model(ckpt: Path, data: Path, num_stages_hint: int, device):
blob = torch.load(ckpt.parent / "hyper_model.pt", map_location="cpu", weights_only=False)
hc, saved = blob["hyper_config"], blob["args"]
ns_args = types.SimpleNamespace(
model_name=saved["model_name"], from_scratch=True, trust_remote_code=False,
use_small_tokenizer=saved.get("use_small_tokenizer", True),
create_special_token=saved.get("create_special_token", True),
tokenizer_name=saved.get("tokenizer_name"),
data_dir=data, init_one_hot=0, freeze_embeddings=0,
)
tok = m.build_tokenizer(ns_args)
base = m.build_base_model(ns_args, tok)
model = m.HyperConnectionGPT2LM(
base_model=base, num_stages=hc["num_stages"], architecture=hc["architecture"],
gate_mode=hc["gate_mode"], fixed_alpha=hc["fixed_alpha"], fixed_beta=hc["fixed_beta"],
norm_type=saved.get("norm_type", "rms"), zero_final_gate=hc["zero_final_gate"],
sg_phi=hc["sg_phi"], use_position_embeddings=hc["use_position_embeddings"],
loop_scheme=hc["loop_scheme"],
)
sd = torch.load(ckpt / "pytorch_model.bin", map_location="cpu", weights_only=False)
missing, unexpected = model.load_state_dict(sd, strict=False)
assert not missing and not unexpected, (missing, unexpected)
return model.eval().to(device), tok, hc, saved
@torch.no_grad()
def run_n_loops(model, ids, n, n_trained_disco, norm_policy):
"""Return the hidden state after exactly n loops (last loop = vanilla read-out)."""
h0, h, mask = model._prepare_inputs(ids, None)
blocks, ln_f = model._stage_blocks(0) # looping: weights shared across stages
for i in range(n):
fi = m._run_gpt2_blocks(h, mask, blocks, ln_f)
if i == n - 1: # final loop: clean vanilla read-out
h = fi
else:
phi = model._phi_softmax_phiT(fi)
mix = model.fixed_alpha * phi + model.fixed_beta * h0
idx = min(i, n_trained_disco - 1) if norm_policy == "last" else min(i, len(model.norms) - 1)
h = fi + model.norms[idx](mix)
return h
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--ckpt", type=Path, required=True)
ap.add_argument("--data", type=Path, required=True)
ap.add_argument("--max-loops", type=int, default=10)
ap.add_argument("--n-samples", type=int, default=1000)
ap.add_argument("--max-length", type=int, default=7)
ap.add_argument("--batch-size", type=int, default=500)
ap.add_argument("--norm-policy", choices=["last", "own"], default="last")
ap.add_argument("--device", type=str, default="cuda")
ap.add_argument("--out", type=Path, default=Path("outputs/loop_dynamics"))
ap.add_argument("--replot", action="store_true", help="re-draw the figure from a saved json")
args = ap.parse_args()
if args.replot:
blob = json.loads((args.out / "loop_dynamics.json").read_text())
plot(blob["results"], blob["K_trained"], args.out, args.max_loops)
return
dev = torch.device(args.device)
model, tok, hc, saved = build_model(args.ckpt, args.data, None, dev)
K = hc["num_stages"]
n_trained_disco = K - 1 # stages 0..K-2 are DiscoLoop steps
print(f"checkpoint trained with K={K} loops ({n_trained_disco} DiscoLoop steps + 1 vanilla read-out)")
print(f"unrolling n=1..{args.max_loops}, norm policy for n>K: {args.norm_policy}")
# ---- splits: atoms + k-hop for train / id / ood ----
splits = {}
train_path = args.data / "train.json"
if train_path.exists():
train = json.loads(train_path.read_text())
for hops, recs in sorted(m.group_by_hops(train).items()):
splits[("train", hops)] = recs
for tag, fn in (("id", "test_id.json"), ("ood", "test_ood.json")):
p = args.data / fn
if p.exists():
for hops, recs in sorted(m.group_by_hops(json.loads(p.read_text())).items()):
splits[(tag, hops)] = recs
results = {}
for (tag, hops), recs in splits.items():
name = f"{tag}_{'atom' if hops == 1 else str(hops) + 'hop'}"
recs = recs[: args.n_samples]
ds = m.JsonTextDataset(recs, tok, args.max_length, "answer")
cos_s, tv_prev_s, tv_gt_s, cnt = (
torch.zeros(args.max_loops + 1), torch.zeros(args.max_loops + 1),
torch.zeros(args.max_loops + 1), 0,
)
for start in range(0, len(recs), args.batch_size):
batch = default_data_collator([ds[i] for i in range(start, min(start + args.batch_size, len(recs)))])
batch = {k: v.to(dev) for k, v in batch.items()}
il = batch["input_len"]
ar = torch.arange(len(il), device=dev)
pos = il - 1 # logits here predict the answer
gold = batch["input_ids"][ar, il]
prev_h = prev_p = None
for n in range(1, args.max_loops + 1):
h = run_n_loops(model, batch["input_ids"], n, n_trained_disco, args.norm_policy)
hn = h[ar, pos].float()
pn = torch.softmax(model.lm_head(h)[ar, pos].float(), dim=-1)
tv_gt_s[n] += (1.0 - pn[ar, gold]).sum().cpu() # TV to one-hot answer
if prev_h is not None:
cos_s[n] += F.cosine_similarity(hn, prev_h, dim=-1).sum().cpu()
tv_prev_s[n] += (0.5 * (pn - prev_p).abs().sum(-1)).sum().cpu()
prev_h, prev_p = hn, pn
cnt += len(il)
results[name] = {
"n": list(range(1, args.max_loops + 1)),
"n_samples": cnt,
"cos_prev": [None] + [float(cos_s[n] / cnt) for n in range(2, args.max_loops + 1)],
"tv_prev": [None] + [float(tv_prev_s[n] / cnt) for n in range(2, args.max_loops + 1)],
"tv_gt": [float(tv_gt_s[n] / cnt) for n in range(1, args.max_loops + 1)],
}
r = results[name]
print(f" {name:14s} n={cnt:5d} | TV(p_n,gt) @n=1,{K},{args.max_loops}: "
f"{r['tv_gt'][0]:.3f} {r['tv_gt'][K-1]:.3f} {r['tv_gt'][-1]:.3f}")
args.out.mkdir(parents=True, exist_ok=True)
(args.out / "loop_dynamics.json").write_text(json.dumps(
{"checkpoint": str(args.ckpt), "K_trained": K, "norm_policy": args.norm_policy,
"results": results}, indent=2))
plot(results, K, args.out, args.max_loops)
print(f"\nwritten to {args.out}/")
def plot(results, K, out: Path, max_loops: int):
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
# one row per hop depth, one column per split; row 0 is the atomic facts
cols = ["train", "id", "ood"]
depths = sorted({int(k.split("_")[1].replace("hop", ""))
for k in results if k.split("_")[1] != "atom"})
grid = []
if "train_atom" in results:
grid.append([("train_atom", "atomic facts (train)"), None, None])
for h in depths:
row = [(f"{c}_{h}hop", f"{h}-hop ({c})") if f"{c}_{h}hop" in results else None for c in cols]
if any(row):
grid.append(row)
# drop columns that are empty for every row (e.g. an eval-only dataset has no train split)
keep = [j for j in range(3) if any(row[j] for row in grid)]
grid = [[row[j] for j in keep] for row in grid]
nrow, ncol = len(grid), len(keep)
fig, axes = plt.subplots(nrow, ncol, figsize=(4.2 * ncol, 3.0 * nrow),
sharex=True, sharey=True, squeeze=False)
bottom_of_col = [max((i for i in range(nrow) if grid[i][j]), default=None) for j in range(ncol)]
handles = labels = None
for i in range(nrow):
first_visible = next((j for j in range(ncol) if grid[i][j]), None)
for j in range(ncol):
cell, ax = grid[i][j], axes[i][j]
if cell is None:
ax.set_visible(False)
continue
name, title = cell
_panel(ax, results[name], title, K, max_loops)
if handles is None:
handles, labels = ax.get_legend_handles_labels()
if i == bottom_of_col[j]:
ax.set_xlabel("number of loops $n$", fontsize=9, color=INK_MUTED)
if j == first_visible:
# a shared y-axis hides ticks on non-first columns; re-enable them here
ax.tick_params(labelleft=True)
ax.set_ylabel("value", fontsize=9, color=INK_MUTED)
fig.legend(handles, labels, loc="lower center", ncol=3, frameon=False,
fontsize=9.5, labelcolor=INK, bbox_to_anchor=(0.5, -0.004))
fig.suptitle("Per-loop change at the answer position", fontsize=13, color=INK, y=0.997)
fig.tight_layout(rect=[0, 0.03, 1, 0.978])
fig.savefig(out / "loop_dynamics.png", dpi=180, facecolor="white")
print(f" figure: {out}/loop_dynamics.png")
def _panel(ax, r, title, K, max_loops):
ns = r["n"]
for (label, color), key in zip(SERIES, ("cos_prev", "tv_prev", "tv_gt")):
y = r[key]
xs = [n for n, v in zip(ns, y) if v is not None]
ys = [v for v in y if v is not None]
ax.plot(xs, ys, color=color, linewidth=2, marker="o", markersize=4.5,
markeredgecolor="white", markeredgewidth=0.8, label=label, zorder=3)
ax.axvline(K, color=INK_MUTED, linewidth=1, linestyle=(0, (4, 3)), zorder=1)
ax.annotate(f"trained K={K}", xy=(K, 1.02), xycoords=("data", "axes fraction"),
ha="center", fontsize=7.5, color=INK_MUTED)
ax.set_title(title, fontsize=10, color=INK, pad=14)
ax.set_ylim(-0.05, 1.05)
step = 1 if max_loops <= 12 else 2
ax.set_xticks([1] + list(range(step if step > 1 else 2, max_loops + 1, step)))
ax.grid(True, color=GRID, linewidth=0.6, zorder=0)
ax.set_axisbelow(True)
for s in ("top", "right"):
ax.spines[s].set_visible(False)
for s in ("left", "bottom"):
ax.spines[s].set_color(GRID)
ax.tick_params(colors=INK_MUTED, labelsize=8.5)
if __name__ == "__main__":
main()