Download dataset_upload/metrics/extract_hidden.py from LucasLoading/stable: direct link, hf CLI and curl.
- Browser
- Download file 6.62 kB
-
https://huggingface.co/datasets/LucasLoading/stable/resolve/main/dataset_upload/metrics/extract_hidden.py
- Command line
-
hf download hf://datasets/LucasLoading/stable/dataset_upload/metrics/extract_hidden.py
-
curl -L -o extract_hidden.py https://huggingface.co/datasets/LucasLoading/stable/resolve/main/dataset_upload/metrics/extract_hidden.py
6.62 kB
| #!/usr/bin/env python | |
| """Query-end residual states for the main-forward queries. [GPU] | |
| python src/extract_hidden.py --model Llama-3.2-1B | |
| Protocol 2.4 fixes the probe position: | |
| the last valid input token -- the model has read the question but has not | |
| yet emitted an answer token | |
| which is exactly the prefill position that produces the first generated token | |
| in eval_run.py. The prompt string is therefore built by importing eval_run's own | |
| `build_prompt`, not by re-deriving it here: if the two ever diverged, ISS would | |
| be measured on a different question than BCS/BES, and nothing downstream would | |
| notice. | |
| Only decoder blocks inside the J-Lens analysis window (protocol 7.10, | |
| d_l = l/(L-1) >= 0.4) are stored. Layer `l` is the OUTPUT of block l, so the | |
| last stored layer, l = L-1, is the final residual stream that J-Lens transports | |
| into. | |
| Output, per model: | |
| outputs/hidden/<model>/L###.npy float16 [n_queries, d] | |
| outputs/hidden/<model>/index.json query order + layer list + checksums | |
| """ | |
| import os, sys, json, time, argparse, hashlib | |
| import numpy as np | |
| import torch | |
| from transformers import AutoModelForCausalLM, AutoTokenizer | |
| sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) | |
| import mcommon as mc | |
| # eval_run.py owns the prompt format; import it so there is exactly one copy. | |
| sys.path.insert(0, mc.runner_dir()) | |
| from eval_run import build_prompt # noqa: E402 | |
| def decoder_layers(model): | |
| """The block list, across Llama / Qwen2 / Mistral / Gemma2 / OLMo2.""" | |
| for attr in ("model.layers", "model.decoder.layers", "transformer.h"): | |
| obj = model | |
| try: | |
| for part in attr.split("."): | |
| obj = getattr(obj, part) | |
| if isinstance(obj, torch.nn.ModuleList) and len(obj): | |
| return obj | |
| except AttributeError: | |
| continue | |
| raise SystemExit(f"cannot locate decoder blocks on {type(model).__name__}") | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--model", required=True) | |
| ap.add_argument("--batch", type=int, default=0) | |
| ap.add_argument("--limit", type=int, default=0, help="debug: first N queries") | |
| ap.add_argument("--force", action="store_true") | |
| args = ap.parse_args() | |
| conf = mc.cfg()["extraction"] | |
| entry = mc.model_entry(args.model) | |
| dest = mc.out("hidden", args.model) | |
| os.makedirs(dest, exist_ok=True) | |
| index_path = os.path.join(dest, "index.json") | |
| if os.path.exists(index_path) and not args.force: | |
| if json.load(open(index_path)).get("complete"): | |
| print(f"[{args.model}] already extracted; --force to redo") | |
| return | |
| rows = mc.main_forward_queries() | |
| if args.limit: | |
| rows = rows[:args.limit] | |
| N = len(rows) | |
| path = mc.model_path(args.model) | |
| tok = AutoTokenizer.from_pretrained(path) | |
| if tok.pad_token is None: | |
| tok.pad_token = tok.eos_token | |
| # Left padding is what makes position -1 the last REAL token for every row | |
| # in a ragged batch; with right padding it would be a pad token. | |
| tok.padding_side = "left" | |
| tok.truncation_side = "left" | |
| model = AutoModelForCausalLM.from_pretrained( | |
| path, dtype=torch.bfloat16, device_map={"": 0}).eval() | |
| blocks = decoder_layers(model) | |
| L = len(blocks) | |
| if L != entry.get("n_layers", L): | |
| raise SystemExit(f"{args.model}: config.json has {L} layers but " | |
| f"models.yaml says {entry['n_layers']}") | |
| d = int(model.config.hidden_size) | |
| window = mc.layer_window(L) | |
| if len(window) != entry.get("jlens_window", len(window)): | |
| raise SystemExit(f"{args.model}: computed window {len(window)} layers " | |
| f"but models.yaml says {entry['jlens_window']}") | |
| print(f"[{args.model}] L={L} d={d} window={window[0]}..{window[-1]} " | |
| f"({len(window)} layers) N={N}", flush=True) | |
| stores = {l: np.lib.format.open_memmap( | |
| os.path.join(dest, f"L{l:03d}.npy"), mode="w+", | |
| dtype=np.float16, shape=(N, d)) for l in window} | |
| grabbed = {} | |
| def make_hook(l): | |
| def hook(_module, _inp, output): | |
| h = output[0] if isinstance(output, tuple) else output | |
| # Detach immediately and keep only the probe position, otherwise the | |
| # full [B, T, d] activation for every window layer stays alive. | |
| grabbed[l] = h[:, -1, :].detach().float() | |
| return hook | |
| handles = [blocks[l].register_forward_hook(make_hook(l)) for l in window] | |
| prompts = [build_prompt(r) for r in rows] | |
| B = args.batch or conf["batch_size"] | |
| max_len = conf["max_prompt_len"] | |
| # Length-sorted batching keeps padding low; `order` maps back to row index. | |
| order = sorted(range(N), key=lambda i: len(prompts[i])) | |
| t0 = time.time() | |
| with torch.no_grad(): | |
| for b in range(0, N, B): | |
| idx = order[b:b + B] | |
| enc = tok([prompts[i] for i in idx], return_tensors="pt", padding=True, | |
| truncation=True, max_length=max_len).to(0) | |
| grabbed.clear() | |
| model(**enc, use_cache=False) | |
| for l in window: | |
| stores[l][idx] = grabbed[l].to(torch.float16).cpu().numpy() | |
| if b % (B * 40) == 0: | |
| done = b + len(idx) | |
| print(f" {done}/{N} {done / max(time.time() - t0, 1e-9):.1f}/s", | |
| flush=True) | |
| for h in handles: | |
| h.remove() | |
| for l in window: | |
| stores[l].flush() | |
| meta = { | |
| "model": args.model, | |
| "complete": True, | |
| "n_queries": N, | |
| "n_layers": L, | |
| "d_model": d, | |
| "window": window, | |
| "window_depths": [round(l / max(L - 1, 1), 4) for l in window], | |
| "late_window": mc.late_window(L), | |
| "position": conf["position"], | |
| "dtype": "float16", | |
| "max_prompt_len": max_len, | |
| "batch_size": B, | |
| "seconds": round(time.time() - t0, 1), | |
| # The query order is the contract between this file and every consumer; | |
| # the hash lets a consumer prove it is reading the same ordering. | |
| "query_ids": [r["query_id"] for r in rows], | |
| "fact_ids": [r["fact_id"] for r in rows], | |
| "families": [r["condition_family"] for r in rows], | |
| "query_order_sha256": hashlib.sha256( | |
| "\n".join(r["query_id"] for r in rows).encode()).hexdigest(), | |
| } | |
| mc.write_json(index_path, meta) | |
| gb = N * len(window) * d * 2 / 1e9 | |
| print(f"[{args.model}] wrote {len(window)} layers x {N} x {d} " | |
| f"({gb:.1f} GB) {meta['seconds']}s EXTRACT_DONE", flush=True) | |
| if __name__ == "__main__": | |
| main() | |