File size: 11,424 Bytes
fd5366a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
# 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


@dataclass
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]


@torch.no_grad()
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

    @torch.no_grad()
    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,
    }