File size: 14,152 Bytes
6f2ed01
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
#!/usr/bin/env python
"""J-Lens: randomized factorized estimate of the layer-to-final Jacobian.  [GPU]

    python src/jlens.py --model Llama-3.2-1B --rank 256
    python src/jlens.py --model Llama-3.2-1B --validate      # spec 7.1 action check

Official transport (J-Lens spec 1):

    z^l = J^l h^l,    J^l = E_{x~C}[ d h^L(x) / d h^l(x) ]

with NO unembedding matrix -- the metric lives in the final-layer residual
basis, not in vocabulary space.

d x d is unaffordable at d = 5120, so spec 6 prescribes randomized range
finding:

    Y = J Omega   (JVPs)        Q = qr(Y)
    B = Q^T J     (VJPs)        Jhat = Q B

and spec 6.4 says to store only Q and B. Downstream we only ever take cosines,
and Q is orthonormal, so cos(Q y1, Q y2) = cos(y1, y2) -- iss.py consumes
y = B h directly in r dimensions.

--- how the per-example Jacobian is taken -------------------------------------

J_x is the Jacobian of the map

    h^l at the last position  ->  h^L at the last position

holding the prefix fixed. Attention is causal, so perturbing the last position's
residual cannot change any earlier position: the prefix KV cache computed once
is exactly right, and the map can be evaluated by a single-token decode step
with a hook that substitutes h at block l. That costs one token through the
blocks instead of a full re-prefill, and it goes through the stock HF decode
path, so it stays correct for Llama / Qwen2 / Mistral / Gemma2 (sliding window,
logit softcap) / OLMo2 alike without per-architecture code.

Tangents are batched along the batch dimension: the map is block-diagonal across
batch rows, so one jvp call returns J_x v_i for as many probe columns as fit.
"""
import os, sys, json, time, argparse, copy

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
from extract_hidden import decoder_layers


# --------------------------------------------------------------- calibration
def calibration_prompts(tok, n, seq_len, seed):
    """Spec 13.1: general text, independent of the factual benchmark.

    Every model sees the same document slice and the same token count, so the
    corpus contributes no cross-model variation (spec 8.1: "same construction
    rule for all models").
    """
    from datasets import load_dataset
    ds = load_dataset("NeelNanda/pile-10k", split="train")
    rng = np.random.default_rng(seed)
    picks = rng.choice(len(ds), size=min(4 * n, len(ds)), replace=False)
    out, used = [], []
    for i in picks:
        ids = tok(ds[int(i)]["text"], return_tensors="pt",
                  truncation=True, max_length=seq_len)["input_ids"][0]
        if ids.numel() < seq_len:
            continue                       # fixed length only (spec 8.1)
        out.append(ids[:seq_len])
        used.append(int(i))
        if len(out) == n:
            break
    if len(out) < n:
        raise SystemExit(f"only {len(out)}/{n} calibration prompts reached {seq_len} tokens")
    return torch.stack(out), used


FP32_BUDGET_GB = 110.0     # of the 143 GB H200, leaving room for activations


def pick_dtype(name, requested="auto"):
    """float32 wherever the weights fit, bfloat16 only when they cannot.

    Measured on Qwen2.5-0.5B, a bf16 JVP agrees with the fp32 one to
    cos >= 0.996 but with 1-8% relative error, worst at early layers -- above
    the 0.05 action-error threshold the J-Lens spec (7.3) sets for accepting an
    estimator. Corpus averaging suppresses most of that, but it is cheaper to
    avoid the noise than to argue about it, so fp32 is the default and the
    fallback is recorded in metadata for the uncertainty report (spec 18).
    """
    if requested != "auto":
        return getattr(torch, requested)
    params_b = float(mc.model_entry(name).get("params_b", 0) or 0)
    return torch.float32 if params_b * 4.0 < FP32_BUDGET_GB else torch.bfloat16


def load_for_jacobian(name, dtype="auto"):
    """Eager attention is mandatory here.

    The fused SDPA/flash kernels have no double-backward rule, and the JVP below
    is reverse-over-reverse. Eager attention is slower but it is the only
    implementation that differentiates twice. Generation and hidden-state
    extraction are unaffected -- they never take a second derivative.
    """
    dt = pick_dtype(name, dtype)
    path = mc.model_path(name)
    tok = AutoTokenizer.from_pretrained(path)
    model = AutoModelForCausalLM.from_pretrained(
        path, dtype=dt, device_map={"": 0}, attn_implementation="eager").eval()
    for prm in model.parameters():
        prm.requires_grad_(False)
    return model, tok


def _cache_tensors(cache):
    """The K/V tensor slots of a Cache, across the layouts transformers uses."""
    slots = []
    if getattr(cache, "layers", None):
        for lay in cache.layers:
            for attr in ("keys", "values"):
                if getattr(lay, attr, None) is not None:
                    slots.append((lay, attr))
    for attr in ("key_cache", "value_cache"):
        seq = getattr(cache, attr, None)
        if seq is not None:
            for i in range(len(seq)):
                slots.append((seq, i))
    return slots


def _expand_cache(cache, b):
    """Replicate a batch-1 prefix cache to batch b without re-running the prefix."""
    c = copy.deepcopy(cache)
    for holder, key in _cache_tensors(c):
        t = holder[key] if isinstance(key, int) else getattr(holder, key)
        t = t.expand(b, *t.shape[1:]).contiguous()
        if isinstance(key, int):
            holder[key] = t
        else:
            setattr(holder, key, t)
    return c


class TailMap:
    """h^l(last position) -> h^L(last position), prefix held fixed.

    Causal attention is what makes this well defined: the last position cannot
    influence earlier ones, so the prefix KV computed once is exactly correct
    however h^l is perturbed.
    """

    def __init__(self, model, blocks, layer, ids):
        self.model, self.blocks, self.layer = model, blocks, layer
        self.n_layers = len(blocks)
        self.sub = None          # tensor substituted at block `layer`
        self.final = None
        with torch.no_grad():
            pre = model(input_ids=ids[:, :-1].to(model.device), use_cache=True)
        self.prefix = pre.past_key_values
        self.last = ids[:, -1:].to(model.device)
        self._install()

    def _install(self):
        def sub_hook(_m, _i, output):
            if self.sub is None:
                return output
            tup = isinstance(output, tuple)
            h = output[0] if tup else output
            # Rebuild rather than index-assign: the substituted row carries the
            # autograd graph and an in-place write into a non-leaf bf16 buffer
            # is both fragile and unnecessary here (sequence length is 1).
            h = self.sub.to(h.dtype).unsqueeze(1)
            return (h,) + tuple(output[1:]) if tup else h

        def grab_hook(_m, _i, output):
            h = output[0] if isinstance(output, tuple) else output
            self.final = h[:, -1, :]

        self.h1 = self.blocks[self.layer].register_forward_hook(sub_hook)
        self.h2 = self.blocks[self.n_layers - 1].register_forward_hook(grab_hook)

    def close(self):
        self.h1.remove()
        self.h2.remove()

    def baseline(self):
        """h^l at the last position, unperturbed -- the expansion point."""
        got = {}

        def hook(_m, _i, output):
            h = output[0] if isinstance(output, tuple) else output
            got["h"] = h[:, -1, :].detach().clone()
        hd = self.blocks[self.layer].register_forward_hook(hook)
        self.sub = None
        with torch.no_grad():
            self._decode(1)
        hd.remove()
        return got["h"]

    def _decode(self, batch):
        cache = _expand_cache(self.prefix, batch) if batch > 1 \
            else copy.deepcopy(self.prefix)
        self.model(input_ids=self.last.expand(batch, 1),
                   past_key_values=cache, use_cache=True)
        return self.final

    def __call__(self, h):
        """h: [b, d] -> [b, d]. Differentiable in reverse mode."""
        self.sub = h
        try:
            return self._decode(h.shape[0])
        finally:
            self.sub = None


def jvp(f, x, v):
    """J v via double backward.

    torch.func.jvp cannot be used here: forward-mode duals do not survive the
    module hooks that substitute the residual, and the model runs in bfloat16.
    The double-backward identity d/du (J^T u) . v = J v needs only reverse mode,
    which the hooks handle natively.
    """
    x = x.detach().requires_grad_(True)
    y = f(x)
    u = torch.zeros_like(y, requires_grad=True)
    (g,) = torch.autograd.grad(y, x, grad_outputs=u, create_graph=True)
    (out,) = torch.autograd.grad(g, u, grad_outputs=v)
    return out


def probes(d, r, seed, device):
    """Nested Gaussian probes: spec 5.3 requires rank k's directions to be a
    prefix of rank 2k's, so a rank sweep is a genuine refinement rather than an
    unrelated redraw."""
    g = torch.Generator(device="cpu").manual_seed(seed)
    return torch.randn(d, r, generator=g).to(device)


def estimate(model, blocks, layer, corpus, r, seed, chunk, device):
    """Y = E_x[J_x Omega] then Q = qr(Y); B^T = E_x[J_x^T Q]."""
    d = model.config.hidden_size
    Om = probes(d, r, seed, device)
    Y = torch.zeros(d, r, device=device, dtype=torch.float32)

    maps = []
    for ids in corpus:
        tm = TailMap(model, blocks, layer, ids.unsqueeze(0))
        maps.append(tm)

    for tm in maps:
        h0 = tm.baseline().float()
        for s in range(0, r, chunk):
            v = Om[:, s:s + chunk].T.contiguous()               # [b, d]
            base = h0.expand(v.shape[0], d).contiguous()
            Y[:, s:s + chunk] += jvp(lambda x: tm(x).float(), base, v).T.float()
    Y /= len(maps)
    Q, _ = torch.linalg.qr(Y.double())
    Q = Q.float()                                               # [d, r]

    Bt = torch.zeros(d, r, device=device, dtype=torch.float32)
    for tm in maps:
        h0 = tm.baseline().float()
        for s in range(0, r, chunk):
            w = Q[:, s:s + chunk].T.contiguous()
            b = w.shape[0]
            base = h0.expand(b, d).contiguous().requires_grad_(True)
            outp = tm(base).float()
            gr = torch.autograd.grad(outp, base, grad_outputs=w.float())[0]
            Bt[:, s:s + chunk] += gr.T.float()
    Bt /= len(maps)
    for tm in maps:
        tm.close()
    return Q, Bt.T.contiguous()                                 # Q [d,r], B [r,d]


def direct_action(model, blocks, layer, corpus, H, device):
    """u_i = J h_i computed directly (spec 7.1) -- the validation reference.

    Needs no d x d matrix: it is one JVP per held-out activation, averaged over
    the same calibration corpus the estimator used.
    """
    d = model.config.hidden_size
    U = torch.zeros(H.shape[0], d, device=device, dtype=torch.float32)
    for ids in corpus:
        tm = TailMap(model, blocks, layer, ids.unsqueeze(0))
        h0 = tm.baseline().float()
        for s in range(0, H.shape[0], 16):
            v = H[s:s + 16].to(device).float()
            base = h0.expand(v.shape[0], d).contiguous()
            U[s:s + 16] += jvp(lambda x: tm(x).float(), base, v).float()
        tm.close()
    return U / len(corpus)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--model", required=True)
    ap.add_argument("--rank", type=int, default=256)
    ap.add_argument("--seed", type=int, default=None)
    ap.add_argument("--layers", nargs="*", type=int, default=None)
    ap.add_argument("--n-prompts", type=int, default=None)
    ap.add_argument("--chunk", type=int, default=32, help="probe columns per jvp call")
    ap.add_argument("--dtype", default="auto", choices=["auto", "float32", "bfloat16"])
    ap.add_argument("--validate", action="store_true",
                    help="spec 7.1 direct-action check on held-out activations")
    args = ap.parse_args()

    C = mc.cfg()["jlens"]
    seed = args.seed if args.seed is not None else C["estimator"]["primary_seed"]
    n_prompts = args.n_prompts or C["corpus"]["n_prompts"]
    p = C["estimator"]["oversampling"]
    r = args.rank + p
    device = "cuda"

    model, tok = load_for_jacobian(args.model, args.dtype)
    compute_dtype = str(next(model.parameters()).dtype).replace("torch.", "")
    blocks = decoder_layers(model)
    L, d = len(blocks), int(model.config.hidden_size)
    if r > d:
        r = d
    window = args.layers if args.layers else mc.layer_window(L)

    corpus, used = calibration_prompts(tok, n_prompts, C["corpus"]["seq_len"],
                                       C["corpus"]["seed"])
    print(f"[{args.model}] d={d} L={L} rank={args.rank}+{p}={r} "
          f"corpus={n_prompts}x{C['corpus']['seq_len']} layers={len(window)}", flush=True)

    for l in window:
        t0 = time.time()
        Q, B = estimate(model, blocks, l, corpus, r, seed, args.chunk, device)
        dest = mc.out("jlens", args.model, f"L{l:03d}")
        np.save(os.path.join(dest, "Q.npy"), Q.cpu().numpy().astype(np.float32))
        np.save(os.path.join(dest, "B.npy"), B.cpu().numpy().astype(np.float32))
        meta = {"model": args.model, "layer": l, "hidden_dimension": d,
                "rank": args.rank, "oversampling": p, "stored_rank": r,
                "power_iterations": C["estimator"]["power_iterations"],
                "calibration_corpus": C["corpus"]["name"],
                "calibration_corpus_size": n_prompts,
                "calibration_sequence_length": C["corpus"]["seq_len"],
                "calibration_sample_ids": used, "random_seed": seed,
                "compute_dtype": compute_dtype,
                "seconds": round(time.time() - t0, 1), "validated": None}
        mc.write_json(os.path.join(dest, "metadata.json"), meta)
        print(f"  L{l:03d}  Q{tuple(Q.shape)} B{tuple(B.shape)}  "
              f"{meta['seconds']}s", flush=True)
    print(f"[{args.model}] JLENS_DONE", flush=True)


if __name__ == "__main__":
    main()