File size: 22,461 Bytes
e349bd8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
#!/usr/bin/env python3
"""Exact 5-regime offline evaluator comparing Stock DSpark (mtp.safetensors) vs DWarp-v1
against frozen thinkingmachines/Inkling-2-Mini target logits on an on-policy JSONL eval set.

Evaluates:
  1. Stock DSpark (B=8, linear chain, exact rejection sampling)
  2. DWarp-v1 Cold 1-Pass Chain (B=16, full vocab vs L1-resident top-64 shortlisted fold_w)
  3. DWarp-v1 Adaptive Pivot-Tree (M<=16, duplicate-free without-replacement SpecInfer/Sequoia tree accept)

Reports exact mean emitted tokens per verify step (tau = E[accepted] + 1) across:
  prose, code, math, tools, long_ctx (both Greedy T=0 and Sampled T=0.85 top_p=0.95).
"""
import argparse, json, math, time, types
from pathlib import Path
import orjson
import torch
import torch.nn.functional as F
from transformers import Inkling2LoopForCausalLM
from transformers.models.inkling2_loop import modeling_inkling2_loop as _ink_mod

from dwarp_model import DWarpV1, DWarpConfig, StockDSpark


def _chunked_attn_core(self, hidden_states, key_hidden_states, value_hidden_states, conv_mask, cache_offset, kwargs):
    """Exact O(L)-memory chunked-Q attention for frozen Inkling-2-Mini teacher (sliding + full,
    with relative position bias & attention sinks). Eliminates O(L^2) 14.5 GB softmax OOMs."""
    pos_ids = kwargs["position_ids"]
    B, L, _ = hidden_states.shape
    dev = hidden_states.device

    q = self.q_proj(hidden_states, pos_ids)
    k = self.k_proj(key_hidden_states, cache=None, conv_mask=conv_mask, cache_offset=cache_offset, **kwargs)
    v = self.v_proj(value_hidden_states, cache=None, conv_mask=conv_mask, cache_offset=cache_offset, **kwargs)

    rpb = self.relative_position_bias
    rel_s = rpb.linear(hidden_states).view(B, L, self.num_heads, -1)
    rel_s = rpb.norm(rel_s, pos_ids)
    rel_logits = (rel_s @ rpb.proj).transpose(1, 2)  # [B, NH, L, rel_extent]
    sinks = self.sink_proj(hidden_states).transpose(1, 2).unsqueeze(-1)  # [B, NH, L, 1]

    NH, HD = self.num_heads, self.head_dim
    Q_BLK = 512
    attn_out = torch.empty((B, L, NH, HD), device=dev, dtype=q.dtype)
    k_full = _ink_mod.repeat_kv(k, self.num_key_value_groups)
    v_full = _ink_mod.repeat_kv(v, self.num_key_value_groups)
    win = self.sliding_window
    rext = self.rel_extent
    ar_all = torch.arange(L, device=dev)

    for q0 in range(0, L, Q_BLK):
        q1 = min(q0 + Q_BLK, L)
        Qc = q1 - q0
        k0 = max(0, q0 - (win - 1)) if win is not None else 0
        k1 = q1
        Kc = k1 - k0
        qc = q[:, :, q0:q1, :]
        kc = k_full[:, :, k0:k1, :]
        vc = v_full[:, :, k0:k1, :]

        w = torch.matmul(qc, kc.transpose(2, 3)) * self.scaling
        dist = ar_all[q0:q1].unsqueeze(1) - ar_all[k0:k1].unsqueeze(0)
        in_rel = (dist >= 0) & (dist < rext)
        g_idx = dist.clamp(0, rext - 1).view(1, 1, Qc, Kc).expand(B, NH, Qc, Kc)
        pb = rel_logits[:, :, q0:q1, :].gather(-1, g_idx)
        pb = pb.masked_fill(~in_rel.view(1, 1, Qc, Kc), 0.0)
        w = w + pb
        inv = (dist < 0) if win is None else ((dist < 0) | (dist >= win))
        w = w.masked_fill(inv.view(1, 1, Qc, Kc), float("-inf"))
        comb = torch.cat([w, sinks[:, :, q0:q1, :]], dim=-1).float()
        probs = F.softmax(comb, dim=-1)[..., :-1].to(q.dtype)
        attn_out[:, q0:q1, :, :] = torch.matmul(probs, vc).transpose(1, 2)

    attn_out = attn_out.reshape(B, L, -1).contiguous()
    return self.o_proj(attn_out, hidden_states), None


def patch_inkling_teacher_fast(model):
    def sliding_fwd(self, hidden_states, attention_mask, relative_distance, conv_mask=None, cache=None,
                    key_hidden_states=None, value_hidden_states=None, cache_offset=0, **kwargs):
        kh = hidden_states if key_hidden_states is None else key_hidden_states
        vh = hidden_states if value_hidden_states is None else value_hidden_states
        return _chunked_attn_core(self, hidden_states, kh, vh, conv_mask, cache_offset, kwargs)

    def full_fwd(self, hidden_states, key_hidden_states, value_hidden_states, attention_mask, relative_distance,
                 conv_mask=None, cache=None, cache_offset=0, **kwargs):
        return _chunked_attn_core(self, hidden_states, key_hidden_states, value_hidden_states, conv_mask, cache_offset, kwargs)

    for mod in model.modules():
        if isinstance(mod, _ink_mod.Inkling2LoopSlidingAttention):
            mod.forward = types.MethodType(sliding_fwd, mod)
        elif isinstance(mod, _ink_mod.Inkling2LoopFullAttention):
            mod.forward = types.MethodType(full_fwd, mod)
    # Skip allocating unused O(L^2) int64 relative_distance matrices inside Inkling2LoopTextModel.forward
    _ink_mod.get_relative_distance = lambda *a, **kw: None


class InklingTeacher:
    """Wraps frozen Inkling2LoopForCausalLM (grouped_mm MoE + O(L) chunked-Q attention)
    and captures exact veloGB10 tap visits [5, 17, 23, 29, 41, 48] via forward pre-hooks."""
    def __init__(self, model_dir: str, device: torch.device):
        self.device = device
        t0 = time.time()
        self.model = Inkling2LoopForCausalLM.from_pretrained(
            model_dir,
            dtype=torch.bfloat16,
            device_map={"": device},
            experts_implementation="grouped_mm",
        )
        self.model.eval()
        for p in self.model.parameters():
            p.requires_grad_(False)
        patch_inkling_teacher_fast(self.model)
        self._buf = {}
        self._cnt = {}
        self._install_hooks()
        self.softcap = float(self.model.config.final_logit_softcapping)
        print(f"[Teacher] Loaded Inkling2LoopForCausalLM (grouped_mm + chunked-Q) on {device} in {time.time()-t0:.1f}s", flush=True)

    def _install_hooks(self):
        layers = self.model.model.layers

        def make_hook(phys_idx):
            def hook(mod, args):
                c = self._cnt.get(phys_idx, 0)
                self._cnt[phys_idx] = c + 1
                h = args[0]  # [B, L, D] residual entering this layer
                if phys_idx == 5 and c == 0:
                    self._buf[5] = h.detach()
                elif phys_idx == 11 and c == 1:
                    self._buf[23] = h.detach()
                elif phys_idx == 17:
                    visit = 17 + 12 * c  # c=0 -> 17, c=1 -> 29, c=2 -> 41
                    self._buf[visit] = h.detach()
            return hook

        self._hooks = [
            layers[5].register_forward_pre_hook(make_hook(5)),
            layers[11].register_forward_pre_hook(make_hook(11)),
            layers[17].register_forward_pre_hook(make_hook(17)),
        ]

    @torch.no_grad()
    def forward_taps_and_logits(self, input_ids: torch.Tensor, logit_positions: torch.Tensor):
        """input_ids: [1, L] long; logit_positions: [P] long.
        Returns:
          taps5: [L, 5, D] bf16 ([5, 17, 29, 41, 48])
          taps4: [L, 4, D] bf16 ([5, 23, 41, 48])
          logits: [P, V] fp32 softcapped target logits at logit_positions
        """
        self._buf.clear()
        self._cnt.clear()
        am = {"full_attention": None, "sliding_attention": None, "linear_attention": None}
        out = self.model.model(input_ids=input_ids, attention_mask=am, use_cache=False)
        h_fin = out.last_hidden_state.detach()  # [1, L, D] = visit 48
        t5 = torch.stack([self._buf[5][0], self._buf[17][0], self._buf[29][0], self._buf[41][0], h_fin[0]], dim=1)
        t4 = torch.stack([self._buf[5][0], self._buf[23][0], self._buf[41][0], h_fin[0]], dim=1)
        h_sel = h_fin[0, logit_positions, :]  # [P, D]
        logits = self.lm_head_softcap(h_sel)
        return t5, t4, logits

    @torch.no_grad()
    def forward_taps_batch(self, input_ids: torch.Tensor, attention_mask: torch.Tensor):
        """Batched teacher forward for length-bucketed sequences!
        input_ids: [B, L] long, attention_mask: [B, L] long (1=real, 0=pad).
        Returns:
          taps5: [B, L, 5, D] bf16 ([5, 17, 29, 41, 48])
          h_fin: [B, L, D] bf16 (visit 48 for on-demand lm_head slicing)
        """
        self._buf.clear()
        self._cnt.clear()
        am = {"full_attention": None, "sliding_attention": None, "linear_attention": attention_mask.bool()}
        out = self.model.model(input_ids=input_ids, attention_mask=am, use_cache=False)
        h_fin = out.last_hidden_state.detach()  # [B, L, D]
        t5 = torch.stack([self._buf[5], self._buf[17], self._buf[29], self._buf[41], h_fin], dim=2)  # [B, L, 5, D]
        return t5, h_fin

    @torch.no_grad()
    def embed_normed(self, token_ids: torch.Tensor) -> torch.Tensor:
        return self.model.model.embed_tokens(token_ids)

    def lm_head_raw(self, hidden: torch.Tensor) -> torch.Tensor:
        return self.model.lm_head(hidden).float()

    def lm_head_softcap(self, hidden: torch.Tensor) -> torch.Tensor:
        logits = self.model.lm_head(hidden).float()
        return self.softcap * torch.tanh(logits / self.softcap)


def trunc_softmax(logits: torch.Tensor, temp: float, top_p: float = 0.95, top_k: int = 128) -> torch.Tensor:
    """Truncated target distribution matching veloGB10 accept_sparse_trunc (top_k=128 + top_p)."""
    if temp <= 1e-4:
        p = torch.zeros_like(logits)
        p.scatter_(-1, logits.argmax(dim=-1, keepdim=True), 1.0)
        return p
    scaled = logits / temp
    k = min(top_k, logits.shape[-1])
    vals, idx = torch.topk(scaled, k, dim=-1)
    probs_k = F.softmax(vals, dim=-1)
    if top_p < 1.0:
        csum = torch.cumsum(probs_k, dim=-1)
        mask = (csum - probs_k) < top_p
        mask[..., 0] = True
        probs_k = probs_k * mask
        probs_k = probs_k / probs_k.sum(dim=-1, keepdim=True).clamp(min=1e-12)
    p = torch.zeros_like(logits)
    p.scatter_(-1, idx, probs_k)
    return p


def expected_chain_tau(p_rows: torch.Tensor, q_rows: torch.Tensor, temp: float) -> float:
    """Exact analytical expected emitted tokens (1 + sum_k prod_{j<=k} alpha_j) for a single chain.
    p_rows, q_rows: [K, V] probabilities (or logits for greedy).
    """
    K = p_rows.shape[0]
    if temp <= 1e-4:
        eq = (p_rows.argmax(dim=-1) == q_rows.argmax(dim=-1)).float()
        surv = 1.0
        e = 1.0
        for j in range(K):
            surv *= float(eq[j].item())
            e += surv
        return e
    # Stochastic lossless: alpha_j = sum_x min(p_j(x), q_j(x)) = 1 - TV(p_j, q_j)
    alpha = torch.minimum(p_rows, q_rows).sum(dim=-1)  # [K]
    surv = 1.0
    e = 1.0
    for j in range(K):
        surv *= float(alpha[j].item())
        e += surv
    return e


def expected_tree_step_alpha_w(p: torch.Tensor, q: torch.Tensor, w: int, temp: float) -> float:
    """Exact duplicate-free without-replacement multi-draft residual acceptance probability for width w.
    For greedy (T=0): 1.0 iff argmax(p) is in top-w(q).
    For sampled (T>0): exact SpecInfer/Sequoia sequential without-replacement verification
    estimated via 256 vectorized unbiased Monte Carlo trials on top-64 support.
    """
    if w <= 1:
        if temp <= 1e-4:
            return float((p.argmax() == q.argmax()).item())
        return float(torch.minimum(p, q).sum().item())
    if temp <= 1e-4:
        topw = torch.topk(q, w).indices
        return float((topw == p.argmax()).any().item())
    K = min(64, q.shape[-1])
    vals_q, idx_q = torch.topk(q, K)
    pq = p[idx_q]
    qq = vals_q / vals_q.sum().clamp(min=1e-12)
    out_mass = (1.0 - pq.sum()).clamp(min=0.0)
    # Append (K+1)-th bucket holding exact out-of-top64 target probability mass (q_out = 0)
    # so residual normalization is 100% exact over the full 200K vocabulary.
    pq_ext = torch.cat([pq, out_mass.unsqueeze(0)], dim=0)
    qq_ext = torch.cat([qq, torch.zeros(1, device=p.device, dtype=qq.dtype)], dim=0)
    T_mc = 256
    rem_p = pq_ext.unsqueeze(0).expand(T_mc, K + 1).clone()
    rem_q = qq_ext.unsqueeze(0).expand(T_mc, K + 1).clone()
    accepted = torch.zeros(T_mc, device=p.device, dtype=torch.bool)
    for _ in range(w):
        q_sum = rem_q.sum(dim=-1, keepdim=True)
        alive = (~accepted) & (q_sum.squeeze(-1) > 1e-9) & (rem_p.sum(dim=-1) > 1e-9)
        if not alive.any():
            break
        qn = rem_q / q_sum.clamp(min=1e-12)
        probs_draw = torch.where(alive.unsqueeze(-1), qn[:, :K], torch.ones_like(qn[:, :K]))
        draw = torch.multinomial(probs_draw, 1).squeeze(-1)  # [T_mc]
        p_d = rem_p.gather(1, draw.unsqueeze(1)).squeeze(1)
        q_d = qn.gather(1, draw.unsqueeze(1)).squeeze(1)
        u = torch.rand(T_mc, device=p.device)
        hit = alive & (u < (p_d / q_d.clamp(min=1e-12)).clamp(max=1.0))
        accepted = accepted | hit
        # Residual update for rejected trials: p <- (p - qn)+ / Z, q <- zero out drawn token
        p_res = (rem_p - qn).clamp(min=0.0)
        rem_p = p_res / p_res.sum(dim=-1, keepdim=True).clamp(min=1e-12)
        rem_q.scatter_(1, draw.unsqueeze(1), 0.0)
    return float(accepted.float().mean().item())


@torch.no_grad()
def evaluate_models(
    teacher: InklingTeacher,
    stock: StockDSpark | None,
    dwarp: DWarpV1 | None,
    eval_path: Path,
    max_per_regime: int = 40,
    anchors_per_seq: int = 12,
):
    recs_by_reg = {}
    with open(eval_path, "rb") as f:
        for line in f:
            r = orjson.loads(line)
            lst = recs_by_reg.setdefault(r["regime"], [])
            if len(lst) < max_per_regime:
                lst.append(r)

    results = {}
    for reg, items in sorted(recs_by_reg.items()):
        metrics = {
            "stock_g": [], "stock_s": [],
            "dwarp_c8_g": [], "dwarp_c8_s": [],
            "dwarp_c16_g": [], "dwarp_c16_s": [],
            "dwarp_top64_g": [], "dwarp_top64_s": [],
            "dwarp_tree_g": [], "dwarp_tree_s": [],
        }
        for rec in items:
            pids = rec["prompt_ids"]
            gids = rec["gen_ids"]
            if len(gids) < 24:
                continue
            # Truncate ultra-long prompts slightly if needed to keep eval snappy while preserving 8K-16K
            if len(pids) > 12288:
                pids = pids[:12288]
            full = pids + gids
            if len(full) > 14336:
                full = full[:14336]
            p_len = len(pids)
            L = len(full)
            if L - p_len < 20:
                continue

            # Pick evenly spaced anchor positions inside the generated response
            lo_a = max(1, p_len)
            hi_a = L - 17
            if hi_a <= lo_a:
                continue
            step = max(1, (hi_a - lo_a) // anchors_per_seq)
            anchors = list(range(lo_a, hi_a, step))[:anchors_per_seq]
            N_blk = len(anchors)

            ids_t = torch.tensor(full, device=teacher.device, dtype=torch.long)
            ap_t = torch.tensor(anchors, device=teacher.device, dtype=torch.long)

            # Positions where we need teacher logits: anchor + 0..14 (predicting anchor+1..anchor+15)
            pos_grid = ap_t.unsqueeze(1) + torch.arange(15, device=teacher.device).unsqueeze(0)  # [N_blk, 15]
            flat_pos = pos_grid.reshape(-1)
            t5, t4, tgt_logits = teacher.forward_taps_and_logits(ids_t.unsqueeze(0), flat_pos)
            tgt_logits = tgt_logits.view(N_blk, 15, -1)  # [N_blk, 15, V]

            # Exact teacher probabilities for T=0 and T=0.85, top_p=0.95
            p_s = trunc_softmax(tgt_logits, temp=0.85, top_p=0.95, top_k=128)
            anchor_emb = teacher.embed_normed(ids_t[ap_t])  # [N_blk, D]
            prev_all = ids_t[pos_grid]  # [N_blk, 15]: prev_all[:, 0] = anchor tok, prev_all[:, j] = true tok at anchor+j

            # 1. Stock DSpark (B=8, K=7)
            if stock is not None:
                fin_s, frnn_s = stock.forward_blocks(t4, ap_t, anchor_emb)
                hv_s = stock.markov_head.forward_chain(fin_s[:, 1:, :], prev_all[:, :7], frnn_s)
                st_logits = teacher.lm_head_softcap(fin_s[:, 1:, :] + hv_s)  # [N_blk, 7, V]
                q_st = F.softmax(st_logits / 0.85, dim=-1)
                for b in range(N_blk):
                    metrics["stock_g"].append(expected_chain_tau(tgt_logits[b, :7], st_logits[b], 0.0))
                    metrics["stock_s"].append(expected_chain_tau(p_s[b, :7], q_st[b], 0.85))

            # 2. DWarp-v1
            if dwarp is not None:
                M = 16
                depths = torch.arange(M, device=teacher.device).unsqueeze(0).expand(N_blk, M)
                pos_blk = ap_t.unsqueeze(1) + depths
                parent_idx = depths - 1
                blk_mask = torch.ones(N_blk, M, M, device=teacher.device, dtype=torch.bool)

                # Evaluate at T=0.0 (greedy) and T=0.85 (prose/sampled)
                for mode_name, eval_t, eval_p in [("g", 0.0, 1.0), ("s", 0.85, 0.95)]:
                    t_vec = torch.full((N_blk,), eval_t, device=teacher.device)
                    p_vec = torch.full((N_blk,), eval_p, device=teacher.device)
                    out = dwarp.forward_sequence(
                        t5, ap_t, anchor_emb, pos_blk, depths, parent_idx, blk_mask,
                        t_vec, p_vec, prev_toks=prev_all,
                    )
                    # Full-vocab step logits
                    dw_logits = teacher.lm_head_softcap(out["step_hidden"])  # [N_blk, 15, V]
                    # Top-64 shortlisted base candidates (simulating exact GB10 32KB L1 fold_w!)
                    base_logits = teacher.lm_head_raw(out["base_hidden"])  # [N_blk, 15, V]
                    top64_idx = torch.topk(base_logits, 64, dim=-1).indices  # [N_blk, 15, 64]
                    short_logits = torch.full_like(dw_logits, -1e9)
                    short_logits.scatter_(-1, top64_idx, torch.gather(dw_logits, -1, top64_idx))

                    q_dw = F.softmax(dw_logits / eval_t, dim=-1) if eval_t > 1e-4 else dw_logits
                    q_sh = F.softmax(short_logits / eval_t, dim=-1) if eval_t > 1e-4 else short_logits
                    p_ref = p_s if eval_t > 1e-4 else tgt_logits

                    for b in range(N_blk):
                        metrics[f"dwarp_c8_{mode_name}"].append(expected_chain_tau(p_ref[b, :7], q_dw[b, :7], eval_t))
                        metrics[f"dwarp_c16_{mode_name}"].append(expected_chain_tau(p_ref[b], q_dw[b], eval_t))
                        metrics[f"dwarp_top64_{mode_name}"].append(expected_chain_tau(p_ref[b], q_sh[b], eval_t))

                        # Lean Pivot-Tree (w=3 at slot 0 if low confidence, w=2 at slot 1 if low conf, total <= 16 nodes)
                        surv = 1.0
                        e_tree = 1.0
                        used_w = [1] * 15
                        q0_p = q_sh[b, 0] if eval_t > 1e-4 else F.softmax(dw_logits[b, 0], dim=-1)
                        q0_max = float(q0_p.max().item())
                        if q0_max < 0.60:
                            used_w[0] = 3
                            max_depth = 5  # 3 branches x 5 depth = 15 nodes (+ anchor = 16)
                        else:
                            q1_p = q_sh[b, 1] if eval_t > 1e-4 else F.softmax(dw_logits[b, 1], dim=-1)
                            q1_max = float(q1_p.max().item())
                            if q1_max < 0.55:
                                used_w[1] = 2
                                max_depth = 8  # 1 + 2 x 7 = 15 nodes (+ anchor = 16)
                            else:
                                max_depth = 15  # 1-pass fast chain = 15 nodes!
                        for j in range(max_depth):
                            aj = expected_tree_step_alpha_w(p_ref[b, j], q_sh[b, j], used_w[j], eval_t)
                            surv *= aj
                            e_tree += surv
                        metrics[f"dwarp_tree_{mode_name}"].append(e_tree)

        def avg(k):
            v = metrics[k]
            return sum(v) / max(len(v), 1)

        results[reg] = {k: avg(k) for k in metrics}
        r = results[reg]
        print(
            f"[{reg:9s}] "
            f"Stock(B8) g={r['stock_g']:.2f} s={r['stock_s']:.2f} | "
            f"C8 g={r['dwarp_c8_g']:.2f} s={r['dwarp_c8_s']:.2f} | "
            f"C16 g={r['dwarp_c16_g']:.2f} s={r['dwarp_c16_s']:.2f} | "
            f"Top64 g={r['dwarp_top64_g']:.2f} s={r['dwarp_top64_s']:.2f} | "
            f"Tree16 g={r['dwarp_tree_g']:.2f} s={r['dwarp_tree_s']:.2f}",
            flush=True,
        )

    # Overall macro average across all 5 regimes
    print("-" * 118, flush=True)
    for key in ["stock_g", "stock_s", "dwarp_c8_g", "dwarp_c8_s", "dwarp_c16_g", "dwarp_c16_s", "dwarp_top64_g", "dwarp_top64_s", "dwarp_tree_g", "dwarp_tree_s"]:
        vals = [results[reg][key] for reg in results]
        print(f"  MACRO AVG {key:14s}: {sum(vals)/max(len(vals),1):.3f}", flush=True)
    return results


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--model-dir", default="./Inkling-2-Mini", help="Local path to thinkingmachines/Inkling-2-Mini")
    ap.add_argument("--eval-jsonl", default="./rollouts_eval.jsonl", help="Held-out on-policy JSONL eval file")
    ap.add_argument("--dwarp-ckpt", default="")
    ap.add_argument("--max-per-regime", type=int, default=40)
    ap.add_argument("--anchors-per-seq", type=int, default=12)
    args = ap.parse_args()

    dev = torch.device("cuda:0")
    teacher = InklingTeacher(args.model_dir, dev)
    stock = StockDSpark(Path(args.model_dir) / "mtp.safetensors").to(dev, dtype=torch.bfloat16).eval()

    dwarp = None
    if args.dwarp_ckpt:
        cfg_p = Path(args.dwarp_ckpt) / "dwarp_config.json"
        cfg = DWarpConfig(**json.loads(cfg_p.read_text())) if cfg_p.exists() else DWarpConfig()
        # normalize lists -> tuples
        cfg.local_layer_ids = tuple(cfg.local_layer_ids)
        cfg.target_layer_ids = tuple(cfg.target_layer_ids)
        dwarp = DWarpV1(cfg).to(dev, dtype=torch.bfloat16)
        from safetensors.torch import load_file
        dwarp.load_state_dict(load_file(str(Path(args.dwarp_ckpt) / "dwarp.safetensors")))
        dwarp.eval()
    else:
        # Sanity test: warm-started DWarp step 0!
        dwarp = DWarpV1(DWarpConfig()).to(dev, dtype=torch.bfloat16)
        dwarp.warm_start_from_stock_mtp(Path(args.model_dir) / "mtp.safetensors")
        dwarp.eval()
        print("[Eval] No --dwarp-ckpt passed: evaluating step-0 warm-started DWarp parity vs Stock DSpark", flush=True)

    evaluate_models(teacher, stock, dwarp, Path(args.eval_jsonl), args.max_per_regime, args.anchors_per_seq)


if __name__ == "__main__":
    main()