"""Load a DiscoLoop / looped-GPT-2 checkpoint from this repo and evaluate it. Run from the repo root (the directory that contains code/, outputs/ and checkpoints_index.json): python examples/load_checkpoint.py --run [--which final|latest|checkpoint-N] [--limit 2000] [--device cpu] The architecture is rebuilt with code/train_twin_hyper.py (the trainer that wrote every checkpoint here). Hyper-parameters come from checkpoints_index.json; base-model size, number of loop stages, gate type and embedding tying are read from the weight shapes, so this also works for runs that never wrote hyper_model.pt. Weights are loaded with strict=True. """ import argparse import json import os import random import sys import types from pathlib import Path import torch REPO = Path(__file__).resolve().parent.parent CODE = REPO / "code" sys.path.insert(0, str(CODE)) import train_twin_hyper as m # noqa: E402 SHAPE_TO_MODEL = {(8, 768): "gpt2", (2, 768): "gpt2-small", (2, 1280): "gpt2-big"} def as_bool(v, default=False): if v is None: return default if isinstance(v, str): return v.lower() in ("1", "true", "yes") return bool(v) def load_model(run: str, which: str = "final", device: str = "cpu"): index = {e["run"]: e for e in json.loads((REPO / "checkpoints_index.json").read_text())} entry = index[run] cfg = entry.get("config", {}) s2 = REPO / "outputs" / run / "stage2_hyper" if which == "final" and (s2 / "hyper_model.pt").is_file(): wpath = s2 / "hyper_model.pt" elif which in ("final", "latest"): ck = sorted(s2.glob("checkpoint-*"), key=lambda p: int(p.name.split("-")[1])) wpath = ck[-1] / "pytorch_model.bin" else: wpath = s2 / which / "pytorch_model.bin" blob = torch.load(wpath, map_location="cpu", weights_only=False) sd = blob.get("state_dict", blob) n_layer = len({int(k.split(".")[2]) for k in sd if k.startswith("transformer.h.")}) n_embd = sd["transformer.wte.weight"].shape[1] num_stages = len([k for k in sd if k.startswith("norms.") and k.endswith(".weight")]) learned = any(k.startswith("w_alpha") for k in sd) untied = not torch.equal(sd["lm_head.weight"], sd["transformer.wte.weight"]) loop_scheme = cfg.get("loop_scheme", "discoloop") data_dir = CODE / cfg["data_dir"] tok_name = cfg.get("tokenizer_name") small = tok_name in (None, "None") and as_bool(cfg.get("use_small_tokenizer"), True) ns_args = types.SimpleNamespace( model_name=SHAPE_TO_MODEL[(n_layer, n_embd)], from_scratch=True, trust_remote_code=False, use_small_tokenizer=small, create_special_token=as_bool(cfg.get("create_special_token"), small), tokenizer_name=None if small else str(CODE / tok_name), data_dir=data_dir, init_one_hot=0, freeze_embeddings=0, ) tokenizer = m.build_tokenizer(ns_args) base = m.build_base_model(ns_args, tokenizer) model = m.HyperConnectionGPT2LM( base_model=base, num_stages=num_stages, architecture="looping", gate_mode="learned" if learned else "fixed", fixed_alpha=float(cfg.get("fixed_alpha", 0.5)), fixed_beta=float(cfg.get("fixed_beta", 0.5)), norm_type=cfg.get("norm_type", "rms"), zero_final_gate=as_bool(cfg.get("zero_final_gate"), True), sg_phi=as_bool(cfg.get("sg_phi"), False), use_position_embeddings=as_bool(cfg.get("use_position_embeddings"), True), loop_scheme=loop_scheme, untie_embeddings=untied, ) model.load_state_dict(sd, strict=True) print(f"loaded {wpath.relative_to(REPO)}: {loop_scheme} K={num_stages} gate={'learned' if learned else 'fixed'} " f"alpha={cfg.get('fixed_alpha')} beta={cfg.get('fixed_beta')} base={ns_args.model_name} untied={untied}") return model.eval().to(device), tokenizer, entry, data_dir def main(): ap = argparse.ArgumentParser() ap.add_argument("--run", required=True) ap.add_argument("--which", default="final") ap.add_argument("--limit", type=int, default=2000, help="examples per split (random, seeded); -1 = all") ap.add_argument("--device", default="cpu") ap.add_argument("--batch-size", type=int, default=512) a = ap.parse_args() model, tok, entry, data_dir = load_model(a.run, a.which, a.device) max_len = int(entry["config"].get("max_length") or 8) rng = random.Random(0) def sub(recs): return recs if a.limit < 0 or len(recs) <= a.limit else rng.sample(recs, a.limit) splits = {} for tag, fn in (("id", "test_id.json"), ("ood", "test_ood.json"), ("ood", "test.json")): p = data_dir / fn if p.exists(): for h, recs in sorted(m.group_by_hops(json.loads(p.read_text())).items()): splits[f"test_{h}hop_{tag}"] = sub(recs) ds = {k: m.JsonTextDataset(v, tok, max_len, "answer") for k, v in splits.items()} metrics = m.evaluate_named_splits(model, ds, torch.device(a.device), a.batch_size) K = model.num_stages print(f"{'split':18s}" + "".join(f"{'loop'+str(i):>9s}" for i in range(1, K + 1)) + f"{'n':>7s}") for k in ds: print(f"{k:18s}" + "".join(f"{metrics[f'{k}_stage{i}_acc']:9.4f}" for i in range(1, K + 1)) + f"{int(metrics[f'{k}_count']):7d}") if "final_acc" in entry: print("recorded final_metrics.json (final-loop acc):", json.dumps(entry["final_acc"])) if __name__ == "__main__": main()