code: detached probe, so every version can be measured
Browse filesFiles changed (2)
120 unmodified lines12112212312412512627 unmodified lines154155156157158159120 unmodified linesreturn model, headdef test_eval(net, model, head):rates = D.student_greedy(model, "cpu", [3], 8, np.random.default_rng(4))assert set(rates) == {3} and 0.0 <= rates[3] <= 1.027 unmodified linestest_targets(teacher)test_hard_targets(teacher)test_solved_start(teacher)model, head = test_train_step(teacher)test_eval(teacher, model, head)print("\nall smoke tests passed")120 unmodified lines12112212312412512612712812913013113213313413513613713813914014114214314414514627 unmodified lines174175176177178179180120 unmodified linesreturn model, headdef test_probe_is_detached(net):"""The probe must train itself and leave the model it measures alone."""class Args:hidden, layers, heads = 32, 2, 2model = D.build_policy(Args())head, probe = D.StateHead(32), D.StateHead(32)rng = np.random.default_rng(11)states0, _ = C.random_walk(8, 8, rng)batch = D.rollout_batch(net, states0, "cpu", 6, 0.35, 0.0, rng, amp=False)# state_weight 0 removes the attached head, so anything reaching the trunk# after that comes from the move loss alone -- never from the probe.loss, _, _, _ = D.losses(model, head, batch, "cpu", 0.0, torch.bfloat16, False,probe)loss.backward()assert all(q.grad is not None and q.grad.abs().sum() > 0 for q in probe.parameters())assert all(q.grad is None or q.grad.abs().sum() == 0 for q in head.parameters())print("ok the probe trains itself and does not reach the attached head")def test_eval(net, model, head):rates = D.student_greedy(model, "cpu", [3], 8, np.random.default_rng(4))assert set(rates) == {3} and 0.0 <= rates[3] <= 1.027 unmodified linestest_targets(teacher)test_hard_targets(teacher)test_solved_start(teacher)test_probe_is_detached(teacher)model, head = test_train_step(teacher)test_eval(teacher, model, head)print("\nall smoke tests passed")
295 unmodified lines2962972982993003014 unmodified lines30630730830931031131212 unmodified lines325326327328329330331332333334335199 unmodified lines5355365375385395406 unmodified lines54754854955055155255329 unmodified lines5835845855865875885895905915925937 unmodified lines60160260360460560660712 unmodified lines620621622623624625626627628629630631632295 unmodified linesto reconstruct the cube itself and let the trunk off the hook, which wouldmake the diagnostic meaningless. The question is whether the trunk carriesthe cube, so the probe must be weak."""def __init__(self, hidden):4 unmodified linesreturn self.proj(h).view(*h.shape[:-1], T.STATE_LEN, len(C.COLORS))def losses(model, head, batch, device, state_weight, amp_dtype, use_amp):ids = batch["ids"].to(device)attn = batch["attn"].to(device)posmask = batch["posmask"].to(device)12 unmodified lineslogp = torch.log_softmax(logits.float(), dim=-1)[..., ANSWER_IDS]move_loss = -(soft * logp).sum(-1)[posmask].mean()sel = face_logits.float()[posmask]face_loss = F.cross_entropy(sel.reshape(-1, len(C.COLORS)), faces[posmask].reshape(-1))with torch.no_grad():face_acc = (sel.argmax(-1) == faces[posmask]).float().mean()return move_loss + state_weight * face_loss, move_loss, face_loss, face_acc# --------------------------------------------------------------------------199 unmodified linesmodel = build_policy(args).to(device)head = StateHead(args.hidden).to(device)n_params = sum(q.numel() for q in model.parameters())print(f"policy {n_params/1e6:.1f}M params | teacher {args.teacher} "f"({getattr(net, 'value_kind', '?')}) | {device}", flush=True)6 unmodified linesamp_dtype = torch.float16print("bf16 unsupported on this GPU; using fp16", flush=True)opt = torch.optim.AdamW(list(model.parameters()) + list(head.parameters()),lr=args.lr, weight_decay=0.1, betas=(0.9, 0.95))sched = torch.optim.lr_scheduler.LambdaLR(opt, lambda s: min((s + 1) / max(args.warmup, 1), 1.0)29 unmodified linesbuffer.pop(0)batch = buffer[rng.integers(len(buffer))]loss, mloss, floss, facc = losses(model, head, batch, device,args.state_weight, amp_dtype, amp)opt.zero_grad(set_to_none=True)loss.backward()torch.nn.utils.clip_grad_norm_(list(model.parameters()) + list(head.parameters()), 1.0)opt.step()sched.step()7 unmodified linesev = np.random.default_rng(12345)rates = student_greedy(model, device, depths, args.eval_n, ev)ev = np.random.default_rng(999)per_pos, exact = state_accuracy(model, head, net, device, depths,max(args.eval_n // 4, 8), ev,args.rollout_len, args.tau, amp)mean = float(np.mean(list(rates.values())))12 unmodified lines# Latest always, best additionally -- a saturating metric must never# be the only thing that chooses a checkpoint (CLAUDE.md).model.save_pretrained(str(out_dir))torch.save({"head": head.state_dict(), "hidden": args.hidden},out_dir / "state_head.pt")if mean >= best:best = meanmodel.save_pretrained(f"{args.out}-best")torch.save({"head": head.state_dict(), "hidden": args.hidden},Path(f"{args.out}-best") / "state_head.pt")if api is not None:try:# Keyed on the output directory, so arms run back to295 unmodified lines2962972982993003013023033043053063073083093103113123133143154 unmodified lines32032132232332432532612 unmodified lines339340341342343344345346347348349350351352353354355356357358359360361199 unmodified lines5615625635645655665676 unmodified lines57457557657757857958058129 unmodified lines6116126136146156166176186196206216227 unmodified lines63063163263363463563612 unmodified lines649650651652653654655656657658659660661295 unmodified linesto reconstruct the cube itself and let the trunk off the hook, which wouldmake the diagnostic meaningless. The question is whether the trunk carriesthe cube, so the probe must be weak.Two of these are built, and the difference is the whole reason there are two:- the **probe** reads `hidden.detach()`, so it is a pure measurement. It istrained in every arm, including the ones with no auxiliary loss, and itnever changes the model it measures.- the **auxiliary head** reads the live hidden state, so its loss flows intothe trunk. That is the intervention, and `--state-weight 0` removes it.The first version of this trainer used one head for both jobs. That readscorrectly in the arms that use the auxiliary loss and reads pure chance in thearms that do not -- the head is simply never trained there -- so trackingcould not be compared across arms at all, which was the comparison worthhaving. Runs before 2026-09-16 have that limitation."""def __init__(self, hidden):4 unmodified linesreturn self.proj(h).view(*h.shape[:-1], T.STATE_LEN, len(C.COLORS))def losses(model, head, batch, device, state_weight, amp_dtype, use_amp, probe=None):ids = batch["ids"].to(device)attn = batch["attn"].to(device)posmask = batch["posmask"].to(device)12 unmodified lineslogp = torch.log_softmax(logits.float(), dim=-1)[..., ANSWER_IDS]move_loss = -(soft * logp).sum(-1)[posmask].mean()target = faces[posmask].reshape(-1)sel = face_logits.float()[posmask]face_loss = F.cross_entropy(sel.reshape(-1, len(C.COLORS)), target)total = move_loss + state_weight * face_lossif probe is not None:# Detached, so this term trains the probe and nothing else. Always on, at# weight 1, in every arm -- it is the measurement, not the intervention.with torch.autocast("cuda", dtype=amp_dtype, enabled=use_amp):probe_logits = probe(hidden.detach())psel = probe_logits.float()[posmask]probe_loss = F.cross_entropy(psel.reshape(-1, len(C.COLORS)), target)total = total + probe_losssel = pselwith torch.no_grad():face_acc = (sel.argmax(-1) == faces[posmask]).float().mean()return total, move_loss, face_loss, face_acc# --------------------------------------------------------------------------199 unmodified linesmodel = build_policy(args).to(device)head = StateHead(args.hidden).to(device)probe = StateHead(args.hidden).to(device)n_params = sum(q.numel() for q in model.parameters())print(f"policy {n_params/1e6:.1f}M params | teacher {args.teacher} "f"({getattr(net, 'value_kind', '?')}) | {device}", flush=True)6 unmodified linesamp_dtype = torch.float16print("bf16 unsupported on this GPU; using fp16", flush=True)opt = torch.optim.AdamW(list(model.parameters()) + list(head.parameters())+ list(probe.parameters()),lr=args.lr, weight_decay=0.1, betas=(0.9, 0.95))sched = torch.optim.lr_scheduler.LambdaLR(opt, lambda s: min((s + 1) / max(args.warmup, 1), 1.0)29 unmodified linesbuffer.pop(0)batch = buffer[rng.integers(len(buffer))]loss, mloss, floss, facc = losses(model, head, batch, device,args.state_weight, amp_dtype, amp, probe)opt.zero_grad(set_to_none=True)loss.backward()torch.nn.utils.clip_grad_norm_(list(model.parameters()) + list(head.parameters())+ list(probe.parameters()), 1.0)opt.step()sched.step()7 unmodified linesev = np.random.default_rng(12345)rates = student_greedy(model, device, depths, args.eval_n, ev)ev = np.random.default_rng(999)per_pos, exact = state_accuracy(model, probe, net, device, depths,max(args.eval_n // 4, 8), ev,args.rollout_len, args.tau, amp)mean = float(np.mean(list(rates.values())))12 unmodified lines# Latest always, best additionally -- a saturating metric must never# be the only thing that chooses a checkpoint (CLAUDE.md).model.save_pretrained(str(out_dir))torch.save({"head": head.state_dict(), "probe": probe.state_dict(),"hidden": args.hidden}, out_dir / "state_head.pt")if mean >= best:best = meanmodel.save_pretrained(f"{args.out}-best")torch.save({"head": head.state_dict(), "probe": probe.state_dict(),"hidden": args.hidden}, Path(f"{args.out}-best") / "state_head.pt")if api is not None:try:# Keyed on the output directory, so arms run back to
code/test_policy_distill.py+21
code/train_policy_distill.py+40-11