import json, os, subprocess, sys, time, gc, collections from pathlib import Path CFG = json.loads(Path(sys.argv[1]).read_text("utf-8")) ROOT = Path(CFG["OUT_ROOT"]) MODEL_ID = "deepseek-ai/DeepSeek-R1-Distill-Llama-8B" THINK = "" RESERVE, MINWORK = 4.0, 20.0 os.environ["TOKENIZERS_PARALLELISM"] = "false" os.environ["HF_HUB_ENABLE_HF_TRANSFER"] = "1" q = subprocess.run(["nvidia-smi", "--query-gpu=index,name,memory.total,memory.free,utilization.gpu", "--format=csv,noheader,nounits"], capture_output=True, text=True, check=True).stdout gpus = [] for line in q.strip().splitlines(): i, n, tot, free, u = [x.strip() for x in line.split(",")] gpus.append({"index": int(i), "name": n, "total": int(tot)/1024, "free": int(free)/1024, "util": int(u)}) print("devices: " + " ".join(f"[{g['index']}] {g['free']:.0f}/{g['total']:.0f}G {g['util']}%" for g in gpus)) d = (max(gpus, key=lambda g: g["free"]) if CFG["DEVICE_ID"] is None else next(g for g in gpus if g["index"] == CFG["DEVICE_ID"])) os.environ["CUDA_VISIBLE_DEVICES"] = str(d["index"]) if d["free"] - RESERVE < MINWORK: sys.exit(f"device {d['index']}: {d['free']-RESERVE:.1f} GiB usable, need {MINWORK}") print(f"device {d['index']} | {d['free']:.1f} GiB free") import torch from transformers import AutoTokenizer, AutoModelForCausalLM tok = AutoTokenizer.from_pretrained(MODEL_ID) model = AutoModelForCausalLM.from_pretrained( MODEL_ID, torch_dtype=torch.bfloat16, device_map={"": 0}).eval() NL, H = len(model.model.layers), model.config.hidden_size DT = getattr(torch, CFG["STORE_DTYPE"]) print(f"{NL} layers, hidden {H}, storing {CFG['STORE_DTYPE']}") # ---- hooks: reduce to per-item means INSIDE the hook --------------------- CUR = {"ans": None, "rsn": None} ACC_A, ACC_R = {}, {} def _mk(L): def hook(_m, _a, out): h = out[0] if isinstance(out, tuple) else out for spans, acc in ((CUR["ans"], ACC_A), (CUR["rsn"], ACC_R)): if spans is None: continue acc[L] = torch.stack([ h[i, a:b].float().mean(0) if b > a else torch.zeros(H, device=h.device) for i, (a, b) in enumerate(spans)]).to(DT).cpu() return None # read-only: perturb nothing return hook handles = [model.model.layers[L].register_forward_hook(_mk(L)) for L in range(NL)] # Prove the index convention on THIS model before pooling 23,200 of anything. with torch.no_grad(): p = tok("hello world", return_tensors="pt", add_special_tokens=False).to(model.device) CUR["ans"] = [(0, p.input_ids.shape[1])]; CUR["rsn"] = None o = model(**p, output_hidden_states=True) for L in range(NL - 1): ref = o.hidden_states[L+1][0, :].float().mean(0).to(DT).cpu() assert torch.allclose(ACC_A[L][0], ref, atol=1e-2), f"layer convention broken at {L}" lastref = o.hidden_states[NL][0, :].float().mean(0).to(DT).cpu() assert not torch.allclose(ACC_A[NL-1][0], lastref, atol=1e-2), \ "expected the last hidden_states entry to be post-final-norm" print("layer convention verified: our L == layers[L] out == hidden_states[L+1];") print(" last hidden_states entry IS post-norm and is correctly NOT used") ACC_A.clear(); ACC_R.clear() def spans_for(r): """(tokens, answer_start, answer_end, prompt_len) in absolute token indices.""" p_ids = tok(r["rendered_prompt"], add_special_tokens=False).input_ids c_ids = tok(r["completion"], add_special_tokens=False).input_ids i = r["completion"].rfind(THINK) if i < 0: return None pre = r["completion"][:i + len(THINK)] n_pre = len(tok(pre, add_special_tokens=False).input_ids) a0, a1 = len(p_ids) + n_pre, len(p_ids) + len(c_ids) return p_ids + c_ids, a0, a1, len(p_ids) @torch.no_grad() def run(batch): seqs = [] for r in batch: s = spans_for(r) if s is None: continue ids, a0, a1, r0 = s if a1 - a0 < 5: continue seqs.append((r, ids, a0, a1, r0)) if not seqs: return [] L = max(len(s[1]) for s in seqs) pad = tok.pad_token_id or tok.eos_token_id inp = torch.full((len(seqs), L), pad, dtype=torch.long) att = torch.zeros((len(seqs), L), dtype=torch.long) for i, (_, ids, *_ ) in enumerate(seqs): inp[i, :len(ids)] = torch.tensor(ids); att[i, :len(ids)] = 1 CUR["ans"] = [(a0, a1) for _, _, a0, a1, _ in seqs] CUR["rsn"] = [(r0, a0) for _, _, a0, _, r0 in seqs] model(input_ids=inp.to(model.device), attention_mask=att.to(model.device)) out = [] for i, (r, ids, a0, a1, r0) in enumerate(seqs): out.append((r, torch.stack([ACC_A[L2][i] for L2 in range(NL)]), torch.stack([ACC_R[L2][i] for L2 in range(NL)]), a1 - a0, a0 - r0)) return out summary = {} for MODE in CFG["JOBS"]: idir = ROOT / MODE files = sorted(idir.glob("rollouts_shard*.jsonl")) if not files: print(f"\n[{MODE}] no rollouts, skipping"); continue rows = [] for f in files: for line in f.read_text("utf-8").splitlines(): if line.strip(): try: rows.append(json.loads(line)) except Exception: pass print(f"\n{'='*66}\n[{MODE}] {len(rows)} rollouts from {len(files)} shard file(s)\n{'='*66}") pt = idir / "pooled.pt" store = torch.load(pt, map_location="cpu") if pt.exists() else {} meta_f = idir / "pooled_meta.jsonl" done = {k for k in store if not k.endswith("::rsn")} todo = [r for r in rows if r["uid"] not in done] print(f"resume: {len(done)} pooled, {len(todo)} to go") # Adaptive batching by token budget: a fixed batch size either wastes memory # on short sequences or OOMs on long ones. todo.sort(key=lambda r: r["n_out_tokens"]) skipped, t0, n_done = [], time.time(), 0 i = 0 while i < len(todo): est = todo[i]["n_out_tokens"] + 400 bs = max(1, min(CFG["MAX_BATCH"], CFG["TOKEN_BUDGET"] // max(est, 1))) batch = todo[i:i+bs]; i += bs try: res = run(batch) except torch.cuda.OutOfMemoryError: torch.cuda.empty_cache() res = [] for r in batch: # fall back to one at a time try: res += run([r]) except Exception as e: skipped.append((r["uid"], type(e).__name__)) got = {r["uid"] for r, *_ in res} for r in batch: if r["uid"] not in got: skipped.append((r["uid"], "no_think_or_short")) with meta_f.open("a", encoding="utf-8") as fh: for r, pa, pr, na, nr in res: store[r["uid"]] = pa store[r["uid"] + "::rsn"] = pr fh.write(json.dumps({"uid": r["uid"], "role": r["role"], "prompt_idx": r["prompt_idx"], "question_id": r["question_id"], "condition": r["condition"], "shard": r["shard"], "n_answer_tokens": na, "n_reasoning_tokens": nr, "finish_reason": r["finish_reason"], "gen_max_tokens": r.get("gen_max_tokens")}) + "\n") n_done += len(res) if n_done and n_done % CFG["CKPT_EVERY"] < bs: torch.save(store, pt) el = time.time() - t0 print(f" {n_done}/{len(todo)} {n_done/max(el,1)*3600:.0f}/h " f"eta {(len(todo)-n_done)/max(n_done,1)*el/3600:.2f}h " f"skipped {len(skipped)}", flush=True) if CFG["HF_PUSH"]: try: from huggingface_hub import HfApi HfApi().upload_file(path_or_fileobj=str(pt), repo_id=CFG["HF_REPO"], repo_type="dataset", path_in_repo=f"{CFG['RUN_ID']}/{MODE}/pooled.pt") except Exception as e: print(f" (push failed: {type(e).__name__}; disk ok)") torch.save(store, pt) n_prim = sum(1 for k in store if not k.endswith("::rsn")) gib = sum(v.numel()*v.element_size() for v in store.values())/1024**3 rep = {"mode": MODE, "n_pooled": n_prim, "n_rollouts": len(rows), "n_skipped": len(skipped), "coverage": round(n_prim/max(len(rows),1), 4), "skip_reasons": dict(collections.Counter(x[1] for x in skipped)), "n_layers": NL, "hidden": H, "store_dtype": CFG["STORE_DTYPE"], "bytes_per_output": NL*H*2, "total_gib": round(gib, 2), "pooling_primary": "mean over answer tokens after the last ", "pooling_secondary": "mean over reasoning tokens (prompt end -> )", "site": "post-MLP residual, forward hook on model.model.layers[L]", "layer_convention": "our L == layers[L] output == hidden_states[L+1]", "output_hidden_states_used": False} (idir / "activation_report.json").write_text(json.dumps(rep, indent=2), "utf-8") if skipped: (idir/"activation_skipped.json").write_text(json.dumps(skipped, indent=2), "utf-8") print("\n" + json.dumps(rep, indent=2)) summary[MODE] = rep if CFG["HF_PUSH"]: try: from huggingface_hub import HfApi api = HfApi() for local, dest in ((pt, f"{MODE}/pooled.pt"), (meta_f, f"{MODE}/pooled_meta.jsonl"), (idir/"activation_report.json", f"{MODE}/activation_report.json")): api.upload_file(path_or_fileobj=str(local), repo_type="dataset", path_in_repo=f"{CFG['RUN_ID']}/{dest}", repo_id=CFG["HF_REPO"]) print(f" pushed {dest}") except Exception as e: print(f" push failed: {type(e).__name__}: {e}") for h in handles: h.remove() print("\n" + "="*66 + "\nSUMMARY\n" + "="*66) for m, r in summary.items(): print(f" {m:14s} {r['n_pooled']:6d}/{r['n_rollouts']:6d} pooled " f"({r['coverage']:.2%}) {r['total_gib']:.2f} GiB skipped {r['n_skipped']}") print("\nSkipped rollouts are 'degenerate' for the judge, NOT 'no role-playing'. " "They must be excluded there too, not scored 0.")