File size: 30,358 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
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
#!/usr/bin/env python3
"""DWarp-v1: Multi-regime Block-Diffusion + Pivot-Tree + Carry-Over Edit Speculator
for thinkingmachines/Inkling-2-Mini (co-designed for veloGB10).

Research Lineage & Attributions:
  - Target model & warm-start base weights (mtp.safetensors): Thinking Machines Lab, Inc.
  - Parallel block-diffusion drafting: DFlash (Chen, Liang, & Liu, UC San Diego / z-lab, arXiv:2602.06036)
  - Two-tap dynamic convolutions & candidate-path gating: DFlash 2 (Inco AI & z-lab, Aug 2026)
  - Layer-wise target feature fusion (dflare_norm / fuse_weight): DFlare (Zhang et al., Tencent, arXiv:2606.02091)
  - Semi-autoregressive parallel backbone + recurrent Markov head: DSpark (Cheng et al., DeepSeek-AI, arXiv:2607.05147)
  - Calibrated draft trees: TreeSpark (Zhou et al., arXiv:2609.22098; Zhao et al., arXiv:2610.20175)
  - Rejected-state reuse: Token Recycling (Luo et al., arXiv:2408.08696) & Carryover Drafting (Koo et al., arXiv:2609.14717)

Key features:
  1. 4-layer hybrid backbone (SWA-1024 on layers [0, 1, 3], Global on layer [2]),
     warm-startable directly from Inkling-2-Mini's bundled 3-layer mtp.safetensors.
  2. Tree-aware two-tap grouped dynamic convolutions (DynConv2, group=16)
     wrapping Attention & MLP on every layer (reduces suffix decay up to B=16).
  3. 5-tap loop-trajectory fusion [5, 17, 29, 41, 48] + explicit cross-loop delta
     RMSNorm(tap[41] - tap[17]) feeding f_rnn and the pivot/acceptance head.
  4. Unified block input supporting:
       - Cold [MASK] slots (1-pass fast chain up to B=16),
       - Plausibility-gated Warm-Start Carry-Over Edit slots (refining rejected tails),
       - Committed Pivot Prefix slots (conditional tree fill).
  5. Sampler-conditioned (temperature, top_p) adaptation for T=0..1 prose & code.
  6. Warm-started Micro-RNN + context-gated bilinear head (DWarpHead) that folds
     directly through target unembed into [V, 256] for 32 KB L1 top-64 scoring.
"""
import json, math
from dataclasses import dataclass, asdict
from pathlib import Path
from typing import Optional

import torch
import torch.nn as nn
import torch.nn.functional as F
from safetensors.torch import load_file, save_file


@dataclass
class DWarpConfig:
    hidden_size: int = 2304
    num_hidden_layers: int = 4
    num_attention_heads: int = 24
    num_key_value_heads: int = 8
    head_dim: int = 128
    intermediate_size: int = 9216
    vocab_size: int = 201024
    unpadded_vocab_size: int = 200058
    rms_norm_eps: float = 1e-6
    rope_theta: float = 1_000_000.0
    sliding_window_size: int = 1024
    local_layer_ids: tuple = (0, 1, 3)
    target_layer_ids: tuple = (5, 17, 29, 41, 48)
    block_size: int = 16
    markov_rank: int = 256
    dynconv_group_size: int = 16
    logit_softcap: float = 30.0
    max_position_embeddings: int = 1048576


class RMSNorm(nn.Module):
    def __init__(self, dim: int, eps: float = 1e-6):
        super().__init__()
        self.eps = eps
        self.weight = nn.Parameter(torch.ones(dim))

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        xf = x.float()
        y = xf * torch.rsqrt(xf.pow(2).mean(dim=-1, keepdim=True) + self.eps)
        return (y * self.weight.float()).to(x.dtype)


def rmsnorm_no_weight(x: torch.Tensor, eps: float = 1e-6) -> torch.Tensor:
    xf = x.float()
    return (xf * torch.rsqrt(xf.pow(2).mean(dim=-1, keepdim=True) + eps)).to(x.dtype)


def apply_rope_neox(x: torch.Tensor, pos: torch.Tensor, theta: float = 1_000_000.0) -> torch.Tensor:
    """Exact GPT-NeoX-style rotary position embedding (RoPE).
    x: [..., HD], pos: [...] broadcastable to x.shape[:-1] (or [..., 1]).
    """
    hd = x.shape[-1]
    half = hd // 2
    idx = torch.arange(half, device=x.device, dtype=torch.float32)
    inv_freq = 1.0 / (theta ** (2.0 * idx / hd))
    ang = pos.float().unsqueeze(-1) * inv_freq  # [..., half]
    cos = torch.cos(ang)
    sin = torch.sin(ang)
    xf = x.float()
    x1, x2 = xf[..., :half], xf[..., half:]
    o1 = x1 * cos - x2 * sin
    o2 = x2 * cos + x1 * sin
    return torch.cat([o1, o2], dim=-1).to(x.dtype)


class DynConv2(nn.Module):
    """DFlash2-style two-tap grouped causal dynamic convolution generalized to tree parents.
    Exact identity at init (base_w = [1, 0], dyn_proj = 0).
    """
    def __init__(self, dim: int, group_size: int = 16):
        super().__init__()
        assert dim % group_size == 0
        self.dim = dim
        self.group_size = group_size
        self.n_groups = dim // group_size
        self.base_w = nn.Parameter(torch.zeros(2, dim))
        with torch.no_grad():
            self.base_w[0].fill_(1.0)
            self.base_w[1].fill_(0.0)
        self.dyn_proj = nn.Linear(dim, 2 * self.n_groups, bias=False)
        nn.init.zeros_(self.dyn_proj.weight)

    def forward(self, x: torch.Tensor, parent_idx: torch.Tensor) -> torch.Tensor:
        """
        x: [N_blk, M, D]
        parent_idx: [N_blk, M] long (-1 for anchor/root, else index in 0..M-1)
        """
        n_blk, m, d = x.shape
        dk = self.dyn_proj(x).view(n_blk, m, 2, self.n_groups)
        dk = dk.repeat_interleave(self.group_size, dim=-1)  # [N_blk, M, 2, D]
        k0 = self.base_w[0].to(x.dtype) + dk[:, :, 0, :]
        k1 = self.base_w[1].to(x.dtype) + dk[:, :, 1, :]
        valid = (parent_idx >= 0).unsqueeze(-1).to(x.dtype)
        safe_p = parent_idx.clamp(min=0).unsqueeze(-1).expand(n_blk, m, d)
        x_prev = torch.gather(x, dim=1, index=safe_p) * valid
        return k0 * x + k1 * x_prev


class DWarpLayer(nn.Module):
    def __init__(self, cfg: DWarpConfig, local: bool):
        super().__init__()
        self.cfg = cfg
        self.local = local
        D = cfg.hidden_size
        NH, NKV, HD = cfg.num_attention_heads, cfg.num_key_value_heads, cfg.head_dim

        self.dflare_norm = RMSNorm(D, cfg.rms_norm_eps)
        self.input_layernorm = RMSNorm(D, cfg.rms_norm_eps)
        self.post_attention_layernorm = RMSNorm(D, cfg.rms_norm_eps)

        self.q_proj = nn.Linear(D, NH * HD, bias=False)
        self.k_proj = nn.Linear(D, NKV * HD, bias=False)
        self.v_proj = nn.Linear(D, NKV * HD, bias=False)
        self.k_proj_ctx = nn.Linear(D, NKV * HD, bias=False)
        self.v_proj_ctx = nn.Linear(D, NKV * HD, bias=False)
        self.o_proj = nn.Linear(NH * HD, D, bias=False)

        self.q_norm = RMSNorm(HD, cfg.rms_norm_eps)
        self.k_norm = RMSNorm(HD, cfg.rms_norm_eps)
        self.k_norm_ctx = RMSNorm(HD, cfg.rms_norm_eps)

        self.dconv_attn = DynConv2(D, cfg.dynconv_group_size)
        self.dconv_mlp = DynConv2(D, cfg.dynconv_group_size)

        self.gate_proj = nn.Linear(D, cfg.intermediate_size, bias=False)
        self.up_proj = nn.Linear(D, cfg.intermediate_size, bias=False)
        self.down_proj = nn.Linear(cfg.intermediate_size, D, bias=False)

    def project_ctx_kv(self, ctx_feat: torch.Tensor, ctx_pos: torch.Tensor):
        """ctx_feat: [L_ctx, D], ctx_pos: [L_ctx] -> (k_ctx, v_ctx) [L_ctx, NKV, HD]."""
        L = ctx_feat.shape[0]
        NKV, HD = self.cfg.num_key_value_heads, self.cfg.head_dim
        k = self.k_proj_ctx(ctx_feat).view(L, NKV, HD)
        k = self.k_norm_ctx(k)
        k = apply_rope_neox(k, ctx_pos.unsqueeze(-1), self.cfg.rope_theta)
        v = self.v_proj_ctx(ctx_feat).view(L, NKV, HD)
        return k, v

    def forward_blocks(
        self,
        h: torch.Tensor,           # [N_blk, M, D]
        pos_blk: torch.Tensor,     # [N_blk, M]
        parent_idx: torch.Tensor,  # [N_blk, M]
        ctx_k: torch.Tensor,       # [L_ctx, NKV, HD]
        ctx_v: torch.Tensor,       # [L_ctx, NKV, HD]
        attn_mask: torch.Tensor,   # [N_blk * M, L_ctx + N_blk * M] bool (True = attend)
    ) -> torch.Tensor:
        N_blk, M, D = h.shape
        NH, NKV, HD = self.cfg.num_attention_heads, self.cfg.num_key_value_heads, self.cfg.head_dim
        Q_tot = N_blk * M

        x = self.input_layernorm(h)
        x = self.dconv_attn(x, parent_idx)

        q = self.q_proj(x).view(N_blk, M, NH, HD)
        bk = self.k_proj(x).view(N_blk, M, NKV, HD)
        bv = self.v_proj(x).view(N_blk, M, NKV, HD)

        q = apply_rope_neox(self.q_norm(q), pos_blk.unsqueeze(-1), self.cfg.rope_theta)
        bk = apply_rope_neox(self.k_norm(bk), pos_blk.unsqueeze(-1), self.cfg.rope_theta)

        # Concatenate shared sequence context KV with all blocks' own KV -> single SDPA call!
        q_sdpa = q.reshape(1, Q_tot, NH, HD).transpose(1, 2)  # [1, NH, Q_tot, HD]
        k_all = torch.cat([ctx_k, bk.reshape(Q_tot, NKV, HD)], dim=0)  # [L_ctx + Q_tot, NKV, HD]
        v_all = torch.cat([ctx_v, bv.reshape(Q_tot, NKV, HD)], dim=0)
        k_sdpa = k_all.unsqueeze(0).transpose(1, 2)  # [1, NKV, K_tot, HD]
        v_sdpa = v_all.unsqueeze(0).transpose(1, 2)

        # PyTorch 2.15 SDPA supports enable_gqa=True natively
        att = F.scaled_dot_product_attention(
            q_sdpa, k_sdpa, v_sdpa,
            attn_mask=attn_mask.unsqueeze(0).unsqueeze(0),
            enable_gqa=True,
        )  # [1, NH, Q_tot, HD]
        att = att.transpose(1, 2).reshape(N_blk, M, NH * HD)
        h = h + self.o_proj(att)

        x2 = self.post_attention_layernorm(h)
        x2 = self.dconv_mlp(x2, parent_idx)
        h = h + self.down_proj(F.silu(self.gate_proj(x2)) * self.up_proj(x2))
        return h


class DWarpHead(nn.Module):
    """Warm-started Micro-RNN Markov Head + DFlash2 Context-Gated Bilinear Residual + Pivot Predictor."""
    def __init__(self, cfg: DWarpConfig):
        super().__init__()
        self.cfg = cfg
        D, R, V = cfg.hidden_size, cfg.markov_rank, cfg.vocab_size
        self.dflare_norm = RMSNorm(D, cfg.rms_norm_eps)
        self.markov_w1 = nn.Embedding(V, R)
        self.rnn_proj = nn.Linear(2 * R + 2 * D, 3 * R, bias=True)
        self.hidden_out = nn.Linear(R, D, bias=True)

        # DWarp additions (exact zero/identity at init!)
        self.pair_gate = nn.Linear(D + R, R, bias=True)
        nn.init.zeros_(self.pair_gate.weight)
        nn.init.zeros_(self.pair_gate.bias)

        self.loop_delta_proj = nn.Linear(D, D, bias=False)
        nn.init.zeros_(self.loop_delta_proj.weight)

        # Calibrated per-slot survival / pivot predictor: outputs logit of P(accept slot r)
        self.pivot_mlp = nn.Sequential(
            nn.Linear(2 * D + 16, 512),
            nn.SiLU(),
            nn.Linear(512, 1),
        )

    def step_rnn(
        self,
        state: torch.Tensor,     # [N, R]
        prev_tok: torch.Tensor,  # [N] long
        fin_h: torch.Tensor,     # [N, D]
        f_rnn: torch.Tensor,     # [N, D]
    ):
        w1 = self.markov_w1(prev_tok)  # [N, R]
        inp = torch.cat([state, w1, fin_h, f_rnn], dim=-1)  # [N, 2R + 2D]
        y = self.rnn_proj(inp)
        gr, cr, or_ = y.chunk(3, dim=-1)
        gate = torch.sigmoid(gr)
        next_state = gate * state + (1.0 - gate) * torch.tanh(cr)
        latent = torch.tanh(or_)
        # DFlash2 context-gated bilinear term (folds through the exact same hidden_out -> fold_w!)
        pg = torch.tanh(self.pair_gate(torch.cat([fin_h, next_state], dim=-1)))
        z = latent + pg * w1
        hv = self.hidden_out(z)  # [N, D]
        return next_state, z, hv

    def forward_chain(
        self,
        fin_slots: torch.Tensor,   # [N_blk, K, D] (slots 1..K)
        prev_toks: torch.Tensor,   # [N_blk, K] long (prev_toks[:, 0] = anchor, prev_toks[:, j] = tok at slot j)
        f_rnn: torch.Tensor,       # [N_blk, D]
    ) -> torch.Tensor:
        """Teacher-forced chain unroll returning delta hidden hv [N_blk, K, D] to add to fin_slots."""
        N_blk, K, D = fin_slots.shape
        state = fin_slots.new_zeros(N_blk, self.cfg.markov_rank)
        hvs = []
        for j in range(K):
            state, _, hv = self.step_rnn(state, prev_toks[:, j], fin_slots[:, j], f_rnn)
            hvs.append(hv)
        return torch.stack(hvs, dim=1)  # [N_blk, K, D]


class DWarpV1(nn.Module):
    def __init__(self, cfg: Optional[DWarpConfig] = None):
        super().__init__()
        self.cfg = cfg or DWarpConfig()
        D = self.cfg.hidden_size
        L = self.cfg.num_hidden_layers
        n_taps = len(self.cfg.target_layer_ids)

        # Row 0..L-1 = backbone layers, Row L = markov head f_rnn
        self.fuse_weight = nn.Parameter(torch.zeros(L + 1, n_taps))
        self.layers = nn.ModuleList([
            DWarpLayer(self.cfg, local=(l in self.cfg.local_layer_ids))
            for l in range(L)
        ])
        self.norm = RMSNorm(D, self.cfg.rms_norm_eps)
        self.mask_embed = nn.Parameter(torch.zeros(D))

        # DWarp block conditioning (all zero-initialized for clean step-0 warm-start!)
        self.slot_pos_embed = nn.Parameter(torch.zeros(self.cfg.block_size, D))
        self.edit_embed = nn.Parameter(torch.zeros(D))
        self.edit_gate = nn.Parameter(torch.full((D,), -2.0))  # sigmoid(-2) ~ 0.12 gentle start
        self.commit_embed = nn.Parameter(torch.zeros(D))

        # Sampler conditioning (temp, top_p) -> [D] & [16]
        self.samp_feat = nn.Sequential(
            nn.Linear(4, 64),
            nn.SiLU(),
            nn.Linear(64, 16),
        )
        self.samp_to_hidden = nn.Linear(16, D, bias=False)
        nn.init.zeros_(self.samp_to_hidden.weight)

        self.markov_head = DWarpHead(self.cfg)

    def mix_taps(self, taps: torch.Tensor, row: int, norm_mod: RMSNorm) -> torch.Tensor:
        """taps: [..., 5, D] -> [..., D]."""
        alpha = F.softmax(self.fuse_weight[row].float(), dim=-1).to(taps.dtype)
        mixed = torch.einsum("...td,t->...d", taps, alpha)
        return norm_mod(mixed)

    def encode_sampler(self, temp: torch.Tensor, top_p: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
        """temp, top_p: [N_blk] -> (s16 [N_blk, 16], sD [N_blk, D])."""
        is_greedy = (temp <= 1e-4).to(temp.dtype)
        feats = torch.stack([temp.clamp(0.0, 2.0), top_p.clamp(0.0, 1.0), is_greedy, temp * top_p], dim=-1)
        s16 = self.samp_feat(feats.to(self.mask_embed.dtype))
        sD = self.samp_to_hidden(s16)
        return s16, sD

    def build_block_inputs(
        self,
        anchor_emb: torch.Tensor,          # [N_blk, D] (already embed_norm'd!)
        depths: torch.Tensor,              # [N_blk, M] long in 0..B-1 (0 at anchor)
        temp: torch.Tensor,                # [N_blk]
        top_p: torch.Tensor,               # [N_blk]
        carry_emb: Optional[torch.Tensor] = None,      # [N_blk, M, D] (embed_norm'd)
        is_carry: Optional[torch.Tensor] = None,       # [N_blk, M] bool
        commit_emb: Optional[torch.Tensor] = None,     # [N_blk, M, D] (embed_norm'd)
        is_commit: Optional[torch.Tensor] = None,      # [N_blk, M] bool
    ):
        N_blk, M = depths.shape
        D = self.cfg.hidden_size
        s16, sD = self.encode_sampler(temp, top_p)

        # Base masked slots + relative slot pos + sampler conditioning
        h = self.mask_embed.view(1, 1, D).expand(N_blk, M, D).clone()
        h = h + self.slot_pos_embed[depths] + sD.unsqueeze(1)

        # Warm-start carry-over edit slots (discrete edit diffusion!)
        if carry_emb is not None and is_carry is not None:
            gate = torch.sigmoid(self.edit_gate).to(h.dtype).view(1, 1, D)
            carry_vec = h + gate * (carry_emb + self.edit_embed.view(1, 1, D))
            h = torch.where(is_carry.unsqueeze(-1), carry_vec, h)

        # Committed Pass-2 pivot prefix slots
        if commit_emb is not None and is_commit is not None:
            comm_vec = commit_emb + self.commit_embed.view(1, 1, D) + self.slot_pos_embed[depths]
            h = torch.where(is_commit.unsqueeze(-1), comm_vec, h)

        # Slot 0 is always exact anchor embedding
        h[:, 0, :] = anchor_emb
        return h, s16

    def build_attn_masks(
        self,
        L_ctx: int,
        anchor_pos: torch.Tensor,          # [N_blk] long (positions 0..anchor_pos-1 are ctx)
        blk_internal_mask: torch.Tensor,   # [N_blk, M, M] bool
    ):
        """Build [Q_tot, L_ctx + Q_tot] bool masks for (local_swa, global) layers."""
        N_blk, M, _ = blk_internal_mask.shape
        Q_tot = N_blk * M
        dev = anchor_pos.device
        ctx_idx = torch.arange(L_ctx, device=dev).unsqueeze(0)  # [1, L_ctx]
        ap = anchor_pos.unsqueeze(1)  # [N_blk, 1]

        # Global context visibility: t < anchor_pos[b]
        ctx_glob = (ctx_idx < ap).unsqueeze(1).expand(N_blk, M, L_ctx).reshape(Q_tot, L_ctx)
        # Local SWA-1024 context visibility: anchor_pos[b] - 1024 <= t < anchor_pos[b]
        lo = (ap - self.cfg.sliding_window_size).clamp(min=0)
        ctx_loc = ((ctx_idx < ap) & (ctx_idx >= lo)).unsqueeze(1).expand(N_blk, M, L_ctx).reshape(Q_tot, L_ctx)

        # Block-diagonal internal mask [Q_tot, Q_tot]
        blk_diag = torch.zeros(N_blk, M, N_blk, M, device=dev, dtype=torch.bool)
        idx = torch.arange(N_blk, device=dev)
        blk_diag[idx, :, idx, :] = blk_internal_mask
        blk_diag = blk_diag.reshape(Q_tot, Q_tot)

        mask_glob = torch.cat([ctx_glob, blk_diag], dim=1)
        mask_loc = torch.cat([ctx_loc, blk_diag], dim=1)
        return mask_loc, mask_glob

    def forward(self, *args, **kwargs):
        return self.forward_sequence(*args, **kwargs)

    def forward_sequence(
        self,
        taps: torch.Tensor,                # [L_seq, 5, D] bf16
        anchor_pos: torch.Tensor,          # [N_blk] long (each >= 1, < L_seq)
        anchor_emb: torch.Tensor,          # [N_blk, D]
        pos_blk: torch.Tensor,             # [N_blk, M] long
        depths: torch.Tensor,              # [N_blk, M] long
        parent_idx: torch.Tensor,          # [N_blk, M] long
        blk_internal_mask: torch.Tensor,   # [N_blk, M, M] bool
        temp: torch.Tensor,                # [N_blk]
        top_p: torch.Tensor,               # [N_blk]
        prev_toks: Optional[torch.Tensor] = None,  # [N_blk, M-1] long (teacher-forced RNN prev tokens)
        carry_emb: Optional[torch.Tensor] = None,
        is_carry: Optional[torch.Tensor] = None,
        commit_emb: Optional[torch.Tensor] = None,
        is_commit: Optional[torch.Tensor] = None,
    ):
        """Single-sequence vectorized forward across N_blk blocks (100% shared ctx KV)."""
        L_seq = taps.shape[0]
        dev = taps.device
        ctx_pos = torch.arange(L_seq, device=dev, dtype=torch.long)
        mask_loc, mask_glob = self.build_attn_masks(L_seq, anchor_pos, blk_internal_mask)

        h, s16 = self.build_block_inputs(
            anchor_emb, depths, temp, top_p,
            carry_emb=carry_emb, is_carry=is_carry,
            commit_emb=commit_emb, is_commit=is_commit,
        )

        for l, ly in enumerate(self.layers):
            ctx_feat = self.mix_taps(taps, l, ly.dflare_norm)
            ctx_k, ctx_v = ly.project_ctx_kv(ctx_feat, ctx_pos)
            h = ly.forward_blocks(h, pos_blk, parent_idx, ctx_k, ctx_v, mask_loc if ly.local else mask_glob)

        fin = self.norm(h)  # [N_blk, M, D]

        # Anchor-1 tap features for f_rnn + cross-loop convergence delta delta_13 = RMSNorm(tap[41] - tap[17])
        a_taps = taps[anchor_pos - 1]  # [N_blk, 5, D] (uses committed pre-anchor tap at p-1)
        f_rnn = self.mix_taps(a_taps, self.cfg.num_hidden_layers, self.markov_head.dflare_norm)
        delta_13 = rmsnorm_no_weight(a_taps[:, 3, :] - a_taps[:, 1, :], self.cfg.rms_norm_eps)
        f_rnn = f_rnn + self.markov_head.loop_delta_proj(delta_13)

        # Pivot / acceptance predictor over draft slots 1..M-1
        fin_draft = fin[:, 1:, :]  # [N_blk, M-1, D]
        K = fin_draft.shape[1]
        piv_in = torch.cat([
            fin_draft,
            delta_13.unsqueeze(1).expand(-1, K, -1),
            s16.unsqueeze(1).expand(-1, K, -1),
        ], dim=-1)
        pivot_logits = self.markov_head.pivot_mlp(piv_in).squeeze(-1)  # [N_blk, M-1]

        step_hidden = None
        if prev_toks is not None:
            hv = self.markov_head.forward_chain(fin_draft, prev_toks, f_rnn)
            step_hidden = fin_draft + hv  # add directly in D space -> identical to base + unembed @ hv!

        return {
            "fin": fin,                     # [N_blk, M, D]
            "base_hidden": fin_draft,       # [N_blk, M-1, D]
            "step_hidden": step_hidden,     # [N_blk, M-1, D] or None
            "f_rnn": f_rnn,                 # [N_blk, D]
            "delta_13": delta_13,           # [N_blk, D]
            "pivot_logits": pivot_logits,   # [N_blk, M-1]
        }

    def warm_start_from_stock_mtp(self, mtp_path: str | Path):
        """Warm-start DWarp-v1 from stock Inkling-2-Mini mtp.safetensors so step 0 == exact DSpark."""
        st = load_file(str(mtp_path))
        with torch.no_grad():
            # Map stock layers [0(loc), 1(glob), 2(loc)] -> DWarp [0(loc), 2(glob), 3(loc)]
            layer_map = {0: 0, 1: 2, 2: 3}
            for src_l, dst_l in layer_map.items():
                dst = self.layers[dst_l]
                p = f"layers.{src_l}."
                dst.dflare_norm.weight.copy_(st[f"{p}dflare_norm.weight"])
                dst.input_layernorm.weight.copy_(st[f"{p}input_layernorm.weight"])
                dst.post_attention_layernorm.weight.copy_(st[f"{p}post_attention_layernorm.weight"])
                dst.q_proj.weight.copy_(st[f"{p}self_attn.q_proj.weight"])
                dst.k_proj.weight.copy_(st[f"{p}self_attn.k_proj.weight"])
                dst.v_proj.weight.copy_(st[f"{p}self_attn.v_proj.weight"])
                dst.k_proj_ctx.weight.copy_(st[f"{p}self_attn.k_proj_ctx.weight"])
                dst.v_proj_ctx.weight.copy_(st[f"{p}self_attn.v_proj_ctx.weight"])
                dst.o_proj.weight.copy_(st[f"{p}self_attn.o_proj.weight"])
                dst.q_norm.weight.copy_(st[f"{p}self_attn.q_norm.weight"])
                dst.k_norm.weight.copy_(st[f"{p}self_attn.k_norm.weight"])
                dst.k_norm_ctx.weight.copy_(st[f"{p}self_attn.k_norm_ctx.weight"])
                dst.gate_proj.weight.copy_(st[f"{p}mlp.gate_proj.weight"])
                dst.up_proj.weight.copy_(st[f"{p}mlp.up_proj.weight"])
                dst.down_proj.weight.copy_(st[f"{p}mlp.down_proj.weight"])

            # Inserted layer 1 (local): init projections from layer 0, ZERO o_proj & down_proj -> exact identity!
            dst1 = self.layers[1]
            src0 = self.layers[0]
            dst1.load_state_dict(src0.state_dict())
            dst1.o_proj.weight.zero_()
            dst1.down_proj.weight.zero_()

            # Fuse weights: stock [4, 4] over [5, 23, 41, 48] -> DWarp [5, 5] over [5, 17, 29, 41, 48]
            fw_old = st["fuse_weight"].float()  # [4, 4]
            row_map = {0: 0, 1: 0, 2: 1, 3: 2, 4: 3}
            for dst_r, src_r in row_map.items():
                w = fw_old[src_r]
                # Split tap 23 weight evenly across loop1(17) and loop2(29) in log-space (subtract ln 2)
                ln2 = math.log(2.0)
                self.fuse_weight[dst_r, 0] = w[0]
                self.fuse_weight[dst_r, 1] = w[1] - ln2
                self.fuse_weight[dst_r, 2] = w[1] - ln2
                self.fuse_weight[dst_r, 3] = w[2]
                self.fuse_weight[dst_r, 4] = w[3]

            self.norm.weight.copy_(st["norm.weight"])
            self.mask_embed.copy_(st["mask_embed"])

            # Markov head exact warm-start
            mh = self.markov_head
            mh.dflare_norm.weight.copy_(st["markov_head.dflare_norm.weight"])
            mh.markov_w1.weight.copy_(st["markov_head.markov_w1.weight"])
            mh.rnn_proj.weight.copy_(st["markov_head.rnn_proj.weight"])
            mh.rnn_proj.bias.copy_(st["markov_head.rnn_proj.bias"])
            mh.hidden_out.weight.copy_(st["markov_head.hidden_out.weight"])
            mh.hidden_out.bias.copy_(st["markov_head.hidden_out.bias"])

    def save_pretrained(self, out_dir: str | Path):
        out = Path(out_dir)
        out.mkdir(parents=True, exist_ok=True)
        sd = {k: v.detach().to(torch.bfloat16).cpu().contiguous() for k, v in self.state_dict().items()}
        save_file(sd, str(out / "dwarp.safetensors"))
        with open(out / "dwarp_config.json", "w") as f:
            json.dump(asdict(self.cfg), f, indent=2)


class StockDSpark(nn.Module):
    """Exact PyTorch replica of stock Inkling-2-Mini mtp.safetensors for apples-to-apples eval."""
    def __init__(self, mtp_path: str | Path):
        super().__init__()
        cfg = DWarpConfig(
            num_hidden_layers=3,
            local_layer_ids=(0, 2),
            target_layer_ids=(5, 23, 41, 48),
            block_size=8,
        )
        self.cfg = cfg
        D = cfg.hidden_size
        self.fuse_weight = nn.Parameter(torch.zeros(4, 4))
        self.layers = nn.ModuleList([DWarpLayer(cfg, local=(l in (0, 2))) for l in range(3)])
        self.norm = RMSNorm(D, cfg.rms_norm_eps)
        self.mask_embed = nn.Parameter(torch.zeros(D))
        self.markov_head = DWarpHead(cfg)

        st = load_file(str(mtp_path))
        with torch.no_grad():
            self.fuse_weight.copy_(st["fuse_weight"])
            for l in range(3):
                p = f"layers.{l}."
                ly = self.layers[l]
                ly.dflare_norm.weight.copy_(st[f"{p}dflare_norm.weight"])
                ly.input_layernorm.weight.copy_(st[f"{p}input_layernorm.weight"])
                ly.post_attention_layernorm.weight.copy_(st[f"{p}post_attention_layernorm.weight"])
                ly.q_proj.weight.copy_(st[f"{p}self_attn.q_proj.weight"])
                ly.k_proj.weight.copy_(st[f"{p}self_attn.k_proj.weight"])
                ly.v_proj.weight.copy_(st[f"{p}self_attn.v_proj.weight"])
                ly.k_proj_ctx.weight.copy_(st[f"{p}self_attn.k_proj_ctx.weight"])
                ly.v_proj_ctx.weight.copy_(st[f"{p}self_attn.v_proj_ctx.weight"])
                ly.o_proj.weight.copy_(st[f"{p}self_attn.o_proj.weight"])
                ly.q_norm.weight.copy_(st[f"{p}self_attn.q_norm.weight"])
                ly.k_norm.weight.copy_(st[f"{p}self_attn.k_norm.weight"])
                ly.k_norm_ctx.weight.copy_(st[f"{p}self_attn.k_norm_ctx.weight"])
                ly.gate_proj.weight.copy_(st[f"{p}mlp.gate_proj.weight"])
                ly.up_proj.weight.copy_(st[f"{p}mlp.up_proj.weight"])
                ly.down_proj.weight.copy_(st[f"{p}mlp.down_proj.weight"])
            self.norm.weight.copy_(st["norm.weight"])
            self.mask_embed.copy_(st["mask_embed"])
            mh = self.markov_head
            mh.dflare_norm.weight.copy_(st["markov_head.dflare_norm.weight"])
            mh.markov_w1.weight.copy_(st["markov_head.markov_w1.weight"])
            mh.rnn_proj.weight.copy_(st["markov_head.rnn_proj.weight"])
            mh.rnn_proj.bias.copy_(st["markov_head.rnn_proj.bias"])
            mh.hidden_out.weight.copy_(st["markov_head.hidden_out.weight"])
            mh.hidden_out.bias.copy_(st["markov_head.hidden_out.bias"])

    @torch.no_grad()
    def forward_blocks(self, taps4: torch.Tensor, anchor_pos: torch.Tensor, anchor_emb: torch.Tensor):
        """taps4: [L_seq, 4, D] (taps [5, 23, 41, 48]), anchor_pos: [N_blk], anchor_emb: [N_blk, D]."""
        L_seq = taps4.shape[0]
        N_blk = anchor_pos.shape[0]
        M = 8
        D = self.cfg.hidden_size
        dev = taps4.device
        ctx_pos = torch.arange(L_seq, device=dev)
        pos_blk = anchor_pos.unsqueeze(1) + torch.arange(M, device=dev).unsqueeze(0)
        parent_idx = torch.arange(M, device=dev).unsqueeze(0).expand(N_blk, M) - 1
        blk_mask = torch.ones(N_blk, M, M, device=dev, dtype=torch.bool)

        # Build masks
        ctx_idx = torch.arange(L_seq, device=dev).unsqueeze(0)
        ap = anchor_pos.unsqueeze(1)
        Q_tot = N_blk * M
        ctx_glob = (ctx_idx < ap).unsqueeze(1).expand(N_blk, M, L_seq).reshape(Q_tot, L_seq)
        lo = (ap - self.cfg.sliding_window_size).clamp(min=0)
        ctx_loc = ((ctx_idx < ap) & (ctx_idx >= lo)).unsqueeze(1).expand(N_blk, M, L_seq).reshape(Q_tot, L_seq)
        blk_diag = torch.zeros(N_blk, M, N_blk, M, device=dev, dtype=torch.bool)
        ii = torch.arange(N_blk, device=dev)
        blk_diag[ii, :, ii, :] = blk_mask
        blk_diag = blk_diag.reshape(Q_tot, Q_tot)
        mask_loc = torch.cat([ctx_loc, blk_diag], dim=1)
        mask_glob = torch.cat([ctx_glob, blk_diag], dim=1)

        h = self.mask_embed.view(1, 1, D).expand(N_blk, M, D).clone()
        h[:, 0, :] = anchor_emb
        for l, ly in enumerate(self.layers):
            alpha = F.softmax(self.fuse_weight[l].float(), dim=-1).to(taps4.dtype)
            ctx_feat = ly.dflare_norm(torch.einsum("ltd,t->ld", taps4, alpha))
            ctx_k, ctx_v = ly.project_ctx_kv(ctx_feat, ctx_pos)
            h = ly.forward_blocks(h, pos_blk, parent_idx, ctx_k, ctx_v, mask_loc if ly.local else mask_glob)
        fin = self.norm(h)
        alpha3 = F.softmax(self.fuse_weight[3].float(), dim=-1).to(taps4.dtype)
        f_rnn = self.markov_head.dflare_norm(torch.einsum("ntd,t->nd", taps4[anchor_pos - 1], alpha3))
        return fin, f_rnn


if __name__ == "__main__":
    cfg = DWarpConfig()
    m = DWarpV1(cfg).cuda().to(torch.bfloat16)
    n_params = sum(p.numel() for p in m.parameters())
    print(f"DWarpV1 params: {n_params/1e6:.2f}M ({n_params*2/1e6:.1f} MB BF16, ~{n_params*0.53/1e6:.1f} MB NVFP4)")
    # Smoke test forward + backward
    L_seq, N_blk, M = 128, 4, 16
    taps = torch.randn(L_seq, 5, cfg.hidden_size, device="cuda", dtype=torch.bfloat16)
    ap = torch.tensor([16, 48, 80, 100], device="cuda")
    a_emb = torch.randn(N_blk, cfg.hidden_size, device="cuda", dtype=torch.bfloat16)
    depths = torch.arange(M, device="cuda").unsqueeze(0).expand(N_blk, M)
    pos_blk = ap.unsqueeze(1) + depths
    parent_idx = depths - 1
    blk_mask = torch.ones(N_blk, M, M, device="cuda", dtype=torch.bool)
    temp = torch.tensor([0.0, 0.7, 0.85, 1.0], device="cuda")
    top_p = torch.tensor([1.0, 0.95, 0.95, 0.95], device="cuda")
    prev = torch.randint(0, 1000, (N_blk, M - 1), device="cuda")
    out = m.forward_sequence(taps, ap, a_emb, pos_blk, depths, parent_idx, blk_mask, temp, top_p, prev_toks=prev)
    loss = out["step_hidden"].float().pow(2).mean() + out["pivot_logits"].float().pow(2).mean()
    loss.backward()
    print("Forward+backward smoke test PASSED! step_hidden:", out["step_hidden"].shape, "pivot:", out["pivot_logits"].shape)