Download code/diagnose_4hop.py from fhyfhy/Implicit-Reasoning-checkpoints: direct link, hf CLI and curl.
- Browser
- Download file 5.77 kB
-
https://huggingface.co/fhyfhy/Implicit-Reasoning-checkpoints/resolve/main/code/diagnose_4hop.py
- Command line
-
hf download hf://fhyfhy/Implicit-Reasoning-checkpoints/code/diagnose_4hop.py
-
curl -L -o diagnose_4hop.py https://huggingface.co/fhyfhy/Implicit-Reasoning-checkpoints/resolve/main/code/diagnose_4hop.py
5.77 kB
| """Diagnose why the 2/3/4-hop discoloop run is stuck. | |
| 1. Dumps a few batched samples: tokens, labels, which position is supervised, | |
| and whether the supervised target equals the ground-truth answer. | |
| 2. Reports init loss and per-stage residual norms for several configs. | |
| 3. Trains each config for a few hundred steps on the curriculum stage-1 mix | |
| (atoms + 2-hop) and reports loss / atom accuracy. | |
| """ | |
| import json | |
| import types | |
| from pathlib import Path | |
| import torch | |
| import torch.nn.functional as F | |
| from torch.utils.data import DataLoader | |
| from transformers import default_data_collator | |
| import train_twin_hyper as m | |
| DATA = Path("data/twin_234hop_truood_diff.500.50.10") | |
| MAXLEN = 6 | |
| STEPS = 300 | |
| BS = 512 | |
| DEV = "cuda" | |
| def build(tokenizer, num_stages, scheme, alpha, beta): | |
| args = types.SimpleNamespace( | |
| model_name="gpt2-big", from_scratch=True, trust_remote_code=False, | |
| use_small_tokenizer=True, create_special_token=True, tokenizer_name=None, | |
| data_dir=DATA, init_one_hot=0, freeze_embeddings=0, | |
| ) | |
| torch.manual_seed(14) | |
| base = m.build_base_model(args, tokenizer) | |
| return m.HyperConnectionGPT2LM( | |
| base_model=base, num_stages=num_stages, architecture="looping", | |
| gate_mode="fixed", fixed_alpha=alpha, fixed_beta=beta, norm_type="rms", | |
| zero_final_gate=True, sg_phi=False, use_position_embeddings=True, | |
| atom_penalty=0.0, loop_scheme=scheme, | |
| ).to(DEV) | |
| def main(): | |
| args = types.SimpleNamespace( | |
| model_name="gpt2-big", from_scratch=True, trust_remote_code=False, | |
| use_small_tokenizer=True, create_special_token=True, tokenizer_name=None, | |
| data_dir=DATA, init_one_hot=0, freeze_embeddings=0, | |
| ) | |
| tok = m.build_tokenizer(args) | |
| train = json.loads((DATA / "train.json").read_text()) | |
| hops = [m.record_hops(r) for r in train] | |
| ds = m.JsonTextDataset(train, tok, MAXLEN, "answer") | |
| # ---------- 1. data / loss wiring ---------- | |
| print("=" * 70) | |
| print("1. DATA + LOSS WIRING (one atom, one 4-hop)") | |
| for want in (1, 4): | |
| idx = hops.index(want) | |
| rec, item = train[idx], ds[idx] | |
| ids = item["input_ids"].tolist() | |
| lab = item["labels"].tolist() | |
| sup = [i for i, l in enumerate(lab) if l != -100] | |
| print(f"\n hops={want} record={rec['target_text']}") | |
| print(f" tokens : {[tok.id_to_token[i] for i in ids]}") | |
| print(f" attention_mask: {item['attention_mask'].tolist()} input_len={int(item['input_len'])}") | |
| print(f" labels : {lab}") | |
| print(f" supervised pos: {sup} -> token {[tok.id_to_token[lab[p]] for p in sup]}") | |
| print(f" true answer : {rec['target_text'][-1]} MATCH={all(tok.id_to_token[lab[p]] == rec['target_text'][-1] for p in sup)}") | |
| # after the causal shift, which position's logits are used? | |
| print(f" shifted: logits@pos {sup[0]-1} predict labels@pos {sup[0]}") | |
| print(f"\n vocab size = {len(tok)} random-guess CE = {torch.log(torch.tensor(float(len(tok)))):.3f}") | |
| # ---------- 2 & 3. config comparison ---------- | |
| stage1 = [i for i, h in enumerate(hops) if h in (1, 2)] # curriculum stage 1 | |
| sub = torch.utils.data.Subset(ds, stage1) | |
| loader = DataLoader(sub, batch_size=BS, shuffle=True, collate_fn=default_data_collator, drop_last=True) | |
| atom_idx = [i for i, h in enumerate(hops) if h == 1][:2000] | |
| atom_batch = default_data_collator([ds[i] for i in atom_idx]) | |
| atom_batch = {k: v.to(DEV) for k, v in atom_batch.items()} | |
| configs = [ | |
| ("discoloop m4 a=1 b=0 (current)", 4, "discoloop", 1.0, 0.0), | |
| ("discoloop m4 a=0.5 b=0.5", 4, "discoloop", 0.5, 0.5), | |
| ("discoloop m2 a=1 b=0", 2, "discoloop", 1.0, 0.0), | |
| ("vanillaloop m4", 4, "vanillaloop", 0.5, 0.5), | |
| ] | |
| print("\n" + "=" * 70) | |
| print("2. INIT DIAGNOSTICS + 3. SHORT TRAINING (atoms+2hop, lr 1e-3 constant)") | |
| for name, ns, scheme, a, b in configs: | |
| model = build(tok, ns, scheme, a, b) | |
| model.eval() | |
| with torch.no_grad(): | |
| out = model(**atom_batch) | |
| h0, h, mask = model._prepare_inputs(atom_batch["input_ids"], atom_batch["attention_mask"]) | |
| _, hidden, norms = model._run_stages(h0, h, mask, True, True) | |
| hn = [f"{x.float().norm(dim=-1).mean():.1f}" for x in hidden] | |
| phin = [f"{n['phi_norm'].mean():.3f}" for n in norms] | |
| logit_std = model.lm_head(hidden[-1]).float().std().item() | |
| print(f"\n [{name}]") | |
| print(f" init loss={out.loss.item():.3f} logit_std={logit_std:.2f}") | |
| print(f" per-stage |H|={hn} raw |phi|={phin}") | |
| model.train() | |
| opt = torch.optim.AdamW(model.parameters(), lr=1e-3, weight_decay=0.01) | |
| it, losses = iter(loader), [] | |
| for step in range(STEPS): | |
| try: | |
| batch = next(it) | |
| except StopIteration: | |
| it = iter(loader); batch = next(it) | |
| batch = {k: v.to(DEV) for k, v in batch.items()} | |
| loss = model(**batch).loss | |
| loss.backward() | |
| torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) | |
| opt.step(); opt.zero_grad() | |
| losses.append(loss.item()) | |
| model.eval() | |
| with torch.no_grad(): | |
| logits = model(**atom_batch).logits | |
| il = atom_batch["input_len"] | |
| pred = logits[torch.arange(len(il)), il - 1].argmax(-1) | |
| gold = atom_batch["input_ids"][torch.arange(len(il)), il] | |
| acc = (pred == gold).float().mean().item() | |
| print(f" after {STEPS} steps: loss {losses[0]:.2f} -> {sum(losses[-20:])/20:.2f} atom_acc={acc:.4f}") | |
| del model, opt | |
| torch.cuda.empty_cache() | |
| if __name__ == "__main__": | |
| main() | |