Download src/clsa/transcoder/harvest.py from fahadhafeezofficial/clsa-code: direct link, hf CLI and curl.
- Browser
- Download file 11.4 kB
-
https://huggingface.co/datasets/fahadhafeezofficial/clsa-code/resolve/main/src/clsa/transcoder/harvest.py
- Command line
-
hf download hf://datasets/fahadhafeezofficial/clsa-code/src/clsa/transcoder/harvest.py
-
curl -L -o harvest.py https://huggingface.co/datasets/fahadhafeezofficial/clsa-code/resolve/main/src/clsa/transcoder/harvest.py
11.4 kB
| # Copyright (c) 2026 CLSA contributors | |
| # SPDX-License-Identifier: MIT | |
| """Harvest activations and LM candidate scores from an open-weight backbone. | |
| This is the only LLM-bound step in the pipeline. Everything downstream reads the | |
| cache, so the nine experiments and all figures re-run in seconds. | |
| Design notes | |
| ------------ | |
| * The backend is Hugging Face Transformers with white-box hidden-state access. | |
| No vendor SDK is involved. | |
| * Candidate scoring uses one prompt prefill plus a KV-cached forward per | |
| candidate, which is exact next-token log-probability scoring at a fraction of | |
| the cost of re-prefilling the prompt for every candidate. | |
| * Outputs are written incrementally, so an interrupted run resumes. | |
| """ | |
| from __future__ import annotations | |
| import json | |
| import time | |
| from dataclasses import dataclass | |
| from pathlib import Path | |
| import numpy as np | |
| import torch | |
| from clsa.util import DATA, load_config, seed_everything, set_threads, utc_now | |
| CACHE = DATA / "activations" | |
| TOKENS_PER_STATE = 32 | |
| class StateRecord: | |
| state_id: str | |
| episode_id: str | |
| step: int | |
| split: str | |
| family: str | |
| prompt: str | |
| candidates: list[dict] | |
| image_feats: dict | None | |
| tool_state: dict | |
| def action_text(action: dict, max_chars: int = 96) -> str: | |
| """Compact signature for scoring. Long bodies are truncated: the LM is | |
| ranking the action, not grading an essay, and unbounded args would make | |
| scoring cost dominate the whole pipeline.""" | |
| parts = [] | |
| for k, v in sorted(action.get("args", {}).items()): | |
| s = str(v) | |
| if len(s) > 32: | |
| s = s[:32] + "..." | |
| parts.append(f"{k}={s}") | |
| text = f"{action['name']}({', '.join(parts)})" | |
| return text[:max_chars] | |
| def score_candidates(model, tok, cands: list[dict], past, last_logits) -> dict[str, float]: | |
| """Length-normalised log-probability of each candidate continuation.""" | |
| candidate_texts = [action_text(c) for c in cands] | |
| scores: dict[str, float] = {} | |
| for text in candidate_texts: | |
| ids = tok(" " + text, return_tensors="pt", add_special_tokens=False)["input_ids"] | |
| ids = ids[:, :12] | |
| if ids.shape[1] == 0: | |
| scores[text] = -1e9 | |
| continue | |
| lp = float(torch.log_softmax(last_logits, dim=-1)[ids[0, 0]]) | |
| if ids.shape[1] > 1: | |
| o = model(input_ids=ids[:, :-1], past_key_values=past, use_cache=True) | |
| logits = o.logits[0] | |
| lsm = torch.log_softmax(logits, dim=-1) | |
| for i in range(1, ids.shape[1]): | |
| lp += float(lsm[i - 1, ids[0, i]]) | |
| scores[text] = lp / ids.shape[1] | |
| return scores | |
| class BackboneHarness: | |
| def __init__(self, model_name: str, layer_frac: float = 0.6, max_tokens: int = 128, threads: int = 4): | |
| from transformers import AutoModelForCausalLM, AutoTokenizer | |
| set_threads(threads) | |
| t0 = time.time() | |
| self.name = model_name | |
| self.tok = AutoTokenizer.from_pretrained(model_name) | |
| if self.tok.pad_token is None: | |
| self.tok.pad_token = self.tok.eos_token | |
| self.model = AutoModelForCausalLM.from_pretrained( | |
| model_name, torch_dtype=torch.float32, attn_implementation="sdpa" | |
| ) | |
| self.model.eval() | |
| L = self.model.config.num_hidden_layers | |
| self.layer = max(1, int(round(layer_frac * L))) | |
| self.d = int(self.model.config.hidden_size) | |
| self.max_tokens = max_tokens | |
| self.load_seconds = time.time() - t0 | |
| def encode(self, prompt: str, candidates: list[dict], score: bool = True) -> dict: | |
| enc = self.tok( | |
| prompt, return_tensors="pt", truncation=True, max_length=self.max_tokens | |
| ) | |
| ids = enc["input_ids"] | |
| out = self.model( | |
| input_ids=ids, | |
| output_hidden_states=True, | |
| use_cache=True, | |
| ) | |
| hs = out.hidden_states[self.layer][0] # (T, d) | |
| last = hs[-1].float().numpy() | |
| n = min(TOKENS_PER_STATE, hs.shape[0]) | |
| idx = torch.linspace(0, hs.shape[0] - 1, n).long() | |
| toks = hs[idx].float().numpy() | |
| last_logits = out.logits[0, -1].clone() | |
| past = out.past_key_values | |
| del out | |
| scores = ( | |
| score_candidates(self.model, self.tok, candidates, past, last_logits) | |
| if score | |
| else {} | |
| ) | |
| return { | |
| "hidden": last.astype(np.float16), | |
| "token_hidden": toks.astype(np.float16), | |
| "candidate_scores": scores, | |
| "n_tokens": int(ids.shape[1]), | |
| } | |
| def state_records(limit_supplementary: int = 150) -> list[StateRecord]: | |
| """Unique decision states from the benchmark plus supplementary items.""" | |
| from clsa.envs.bench_io import load_preact_bench | |
| from clsa.envs.supplementary import SUP_DIR | |
| from clsa.util import read_jsonl | |
| items = load_preact_bench() | |
| sup_path = SUP_DIR / "probe_train.jsonl" | |
| if sup_path.exists(): | |
| sup = read_jsonl(sup_path) | |
| step = max(1, len(sup) // max(1, limit_supplementary)) | |
| items = items + sup[::step][:limit_supplementary] | |
| seen: dict[str, StateRecord] = {} | |
| for it in items: | |
| key = f"{it['episode_id']}|s{it['step']}" | |
| if key in seen: | |
| continue | |
| seen[key] = StateRecord( | |
| state_id=key, | |
| episode_id=it["episode_id"], | |
| step=int(it["step"]), | |
| split=it["split"], | |
| family=it["family"], | |
| prompt=it["observation"]["text"], | |
| candidates=it["candidate_set"], | |
| image_feats=None, | |
| tool_state=it["observation"]["tool_state"], | |
| ) | |
| return list(seen.values()) | |
| def cache_path(model_name: str) -> Path: | |
| safe = model_name.replace("/", "__") | |
| return CACHE / safe / "states.npz" | |
| def partial_path(model_name: str) -> Path: | |
| safe = model_name.replace("/", "__") | |
| return CACHE / safe / "states.partial.npz" | |
| def _persist(path: Path, hidden, tok_hidden, ids, scores) -> None: | |
| """Atomic checkpoint so a disconnect costs at most one batch of work. | |
| Metadata and scores are JSON-encoded strings: an object array of dicts is | |
| not reliably round-tripped by numpy and silently corrupts on reload. | |
| """ | |
| arr = { | |
| "hidden": np.stack(hidden), | |
| "token_hidden": np.stack(tok_hidden), | |
| "meta": np.array([json.dumps(m) for m in ids], dtype=object), | |
| "scores": np.array([json.dumps(s) for s in scores], dtype=object), | |
| } | |
| tmp = path.with_suffix(".tmp.npz") | |
| np.savez_compressed(tmp, **arr) | |
| import os | |
| os.replace(tmp, path) | |
| def _load_partial(model_name: str) -> tuple[list, list, list, list]: | |
| p = partial_path(model_name) | |
| if not p.exists(): | |
| return [], [], [], [] | |
| try: | |
| blob = np.load(p, allow_pickle=True) | |
| return ( | |
| list(blob["hidden"].astype(np.float32)), | |
| list(blob["token_hidden"].astype(np.float32)), | |
| [json.loads(m) for m in blob["meta"]], | |
| [json.loads(s) for s in blob["scores"]], | |
| ) | |
| except Exception: | |
| return [], [], [], [] | |
| def harvest(model_name: str, cfg: dict | None = None, limit: int | None = None) -> dict: | |
| cfg = cfg or load_config("transcoder") | |
| seed_everything(int(cfg.get("seed", 0))) | |
| records = state_records(int(cfg.get("supplementary_states", 150))) | |
| if limit and limit < len(records): | |
| # Stratified: evaluation splits first (they carry candidate scores and are | |
| # what transfer is measured on), then train/calib to fill the budget. | |
| eval_splits = set(cfg.get("score_splits", ["test", "heldout"])) | |
| ev = [r for r in records if r.split in eval_splits] | |
| sup = [r for r in records if r.split == "probe_train"] | |
| rest = [r for r in records if r.split not in eval_splits and r.split != "probe_train"] | |
| third = max(1, limit // 3) | |
| half = max(1, limit // 2) | |
| picked = ev[:half] + sup[:third] | |
| picked += rest[: max(0, limit - len(picked))] | |
| if len(picked) < limit: | |
| picked += ev[half : half + (limit - len(picked))] | |
| records = picked[:limit] | |
| out_path = cache_path(model_name) | |
| out_path.parent.mkdir(parents=True, exist_ok=True) | |
| if out_path.exists(): | |
| return {"model": model_name, "n_new": 0, "n_total": int(len(load_cache(model_name)["meta"]))} | |
| hidden, tok_hidden, ids, scores = _load_partial(model_name) | |
| done = {str(m["state_id"]): m for m in ids if isinstance(m, dict)} | |
| h = BackboneHarness( | |
| model_name, | |
| layer_frac=float(cfg.get("layer_frac", 0.6)), | |
| max_tokens=int(cfg.get("max_tokens", 128)), | |
| threads=int(cfg.get("threads", 4)), | |
| ) | |
| log = open(out_path.parent / "harvest.log", "a", encoding="utf-8") | |
| log.write(f"\n=== {utc_now()} harvest {model_name} layer={h.layer} d={h.d} n={len(records)} ===\n") | |
| log.flush() | |
| t0 = time.time() | |
| for i, rec in enumerate(records): | |
| if rec.state_id in done: | |
| continue | |
| enc = h.encode( | |
| rec.prompt, rec.candidates, score=rec.split in ("test", "heldout") | |
| ) | |
| hidden.append(enc["hidden"]) | |
| tok_hidden.append(enc["token_hidden"]) | |
| scores.append(enc["candidate_scores"]) | |
| ids.append( | |
| { | |
| "state_id": rec.state_id, | |
| "episode_id": rec.episode_id, | |
| "step": rec.step, | |
| "split": rec.split, | |
| "family": rec.family, | |
| "candidates": rec.candidates, | |
| "tool_state": rec.tool_state, | |
| "n_tokens": enc["n_tokens"], | |
| } | |
| ) | |
| if (i + 1) % 10 == 0 or i == len(records) - 1: | |
| _persist(partial_path(model_name), hidden, tok_hidden, ids, scores) | |
| if (i + 1) % 20 == 0 or i == len(records) - 1: | |
| elapsed = time.time() - t0 | |
| rate = (i + 1) / max(elapsed, 1e-6) | |
| msg = f"{len(ids)}/{len(records)} states, {elapsed:.0f}s, {rate:.2f} states/s" | |
| print(msg, flush=True) | |
| log.write(msg + "\n") | |
| log.flush() | |
| log.close() | |
| if not hidden: | |
| return {"model": model_name, "n_new": 0, "n_total": len(done)} | |
| H = np.stack(hidden) | |
| TH = np.stack(tok_hidden) | |
| if out_path.exists() and done: | |
| prev = np.load(out_path, allow_pickle=True) | |
| H = np.concatenate([prev["hidden"], H]) | |
| TH = np.concatenate([prev["token_hidden"], TH]) | |
| ids = list(prev["meta"]) + ids | |
| scores = list(prev["scores"]) + scores | |
| _persist(out_path, list(H), list(TH), list(ids), list(scores)) | |
| if partial_path(model_name).exists(): | |
| partial_path(model_name).unlink(missing_ok=True) | |
| return { | |
| "model": model_name, | |
| "n_new": len(hidden), | |
| "n_total": len(H), | |
| "layer": h.layer, | |
| "d": h.d, | |
| "path": str(out_path.relative_to(DATA.parent)), | |
| "seconds": round(time.time() - t0, 1), | |
| } | |
| def load_cache(model_name: str): | |
| p = cache_path(model_name) | |
| if not p.exists(): | |
| p = partial_path(model_name) | |
| blob = np.load(p, allow_pickle=True) | |
| return { | |
| "hidden": blob["hidden"].astype(np.float32), | |
| "token_hidden": blob["token_hidden"].astype(np.float32), | |
| "meta": [json.loads(m) for m in blob["meta"]], | |
| "scores": [json.loads(s) for s in blob["scores"]], | |
| "path": p, | |
| } | |