"""What are the oscillating top-1 predictions, and is there a pattern? For a k-hop chain r_1 ... r_k the recurrence should walk through the intermediate bridge entities b_1 ... b_{k-1} and stop at the answer. When the recurrence fails to converge we can ask *which* tokens it cycles between: are they the chain's own bridge entities (i.e. the model keeps re-walking the chain), unrelated entities, or relations? For every loop n we classify the top-1 token at the answer position as answer | b_j (the j-th intermediate bridge) | head | other entity | relation and we report the size of the set of distinct predictions in the late regime. Usage: python loop_flip_analysis.py --ckpt --data --max-length 8 --max-loops 20 """ import argparse import json from collections import Counter from pathlib import Path import torch from transformers import default_data_collator import train_twin_hyper as m from loop_dynamics import build_model, run_n_loops def main(): ap = argparse.ArgumentParser() ap.add_argument("--ckpt", type=Path, required=True) ap.add_argument("--data", type=Path, required=True) ap.add_argument("--atoms-from", type=Path, default=Path("data/twin_twohop_truood_diff.500.50.10")) ap.add_argument("--max-length", type=int, required=True) ap.add_argument("--max-loops", type=int, default=20) ap.add_argument("--late-from", type=int, default=11, help="first loop of the 'late' regime") ap.add_argument("--n-samples", type=int, default=1000) ap.add_argument("--batch-size", type=int, default=500) ap.add_argument("--device", type=str, default="cuda") ap.add_argument("--out", type=Path, default=None) args = ap.parse_args() dev = torch.device(args.device) model, tok, hc, _ = build_model(args.ckpt, args.data, None, dev) n_trained = hc["num_stages"] - 1 # adjacency, to name the intermediate bridges of each chain adj = {} for r in json.loads((args.atoms_from / "train.json").read_text()): if len(r["target_text"]) == 3: h, rel, t = r["target_text"] adj[(h, rel)] = t splits = {} for tag, fn in (("id", "test_id.json"), ("ood", "test_ood.json")): p = args.data / fn if p.exists(): for h, recs in sorted(m.group_by_hops(json.loads(p.read_text())).items()): splits[f"{tag}_{h}hop"] = recs report = {} for name, recs in splits.items(): recs = recs[: args.n_samples] hops = len(recs[0]["target_text"]) - 2 ds = m.JsonTextDataset(recs, tok, args.max_length, "answer") # role of every token for every chain: answer / b_j / head roles = [] for rec in recs: toks = rec["target_text"] cur, chain = toks[0], {toks[0]: "head"} for j, rel in enumerate(toks[1:-1], start=1): cur = adj[(cur, rel)] chain[cur] = "answer" if j == hops else f"b{j}" roles.append(chain) top1 = [[] for _ in recs] # per sample, per n for s in range(0, len(recs), args.batch_size): idx = list(range(s, min(s + args.batch_size, len(recs)))) b = default_data_collator([ds[i] for i in idx]) b = {k: v.to(dev) for k, v in b.items()} il = b["input_len"]; ar = torch.arange(len(il), device=dev); pos = il - 1 for n in range(1, args.max_loops + 1): h = run_n_loops(model, b["input_ids"], n, n_trained, "last") t = model.lm_head(h)[ar, pos].argmax(-1).tolist() for k, i in enumerate(idx): top1[i].append(tok.id_to_token[t[k]]) def role_of(sample_i, token): r = roles[sample_i].get(token) if r: return r return "relation" if token.startswith("14s}" for o in order) print(hdr) for n in list(range(1, min(8, args.max_loops + 1))) + [args.max_loops // 2, args.max_loops]: c = per_n[n] print(f" {n:2d} " + "".join(f"{c.get(o, 0) / n_tot:13.1%} " for o in order)) if pairs: print(" most common role sets among oscillating samples:") for combo, cnt in pairs.most_common(5): print(f" {'+'.join(combo):40s} {cnt / n_tot:6.1%}") print() report[name] = { "hops": hops, "distinct_sizes": {str(k): v for k, v in sizes.items()}, "role_by_loop": {str(n): dict(c) for n, c in per_n.items()}, "oscillating_role_sets": {"+".join(k): v for k, v in pairs.items()}, } if args.out: args.out.parent.mkdir(parents=True, exist_ok=True) args.out.write_text(json.dumps(report, indent=2)) print(f"written to {args.out}") if __name__ == "__main__": main()