File size: 31,641 Bytes
ca1a504
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# SPDX-License-Identifier: Apache-2.0
# Adapted from this workspace's GLM-OCR bundle (tt_glmocr/tt/ttnn_decoder.py, Apache-2.0), itself from the Qwen3-ASR
# bundle and tt-metal models/demos/audio/qwen3_tts (Apache-2.0, Tenstorrent): M=1 decode matmul configs, fused QKV,
# nlp_create_qkv_heads(_decode), rotary_embedding_hf, fill_cache chunking, paged_fused_update_cache, sdpa_decode and the
# persistent-input trace pattern. DeepSeek-OCR changes: plain 1D rope (half-split natively), standard pre-norm layers,
# layer 0 dense SwiGLU, layers 1-11 MoE computed DENSELY over all 64 experts with the router's top-6 softmax weights
# as a per-expert mask (a fixed-shape graph: exact up to bf16 rounding; the decode megakernel is the sparse path).
"""ttnn baseline of the DeepSeek-OCR family decoder (12 layers, hidden 1280, 10 heads, MoE 64 x 896 top-6 + shared).

* ``prefill(rows [L, D] host, L)``: rows zero-padded to the bucket, one trace per bucket: KV [0, Lb), logits of row
  L - 1 (one-hot row select); routing of every row available as a stage tensor (debug).
* ``step(token, pos)``: one decode step (logits read back: host sampling / n-gram rule); ``loop(token, pos)``: K greedy
  steps in one trace (on-device argmax -> embedding -> next step).
"""

from __future__ import annotations

from typing import Dict, List, Optional, Sequence

import torch

from ..reference import model as R
from . import trace_safety as TS

CACHE_TILE_MULTIPLE = 64
DECODE_IN0_BLOCK_W = 4
DECODE_MAX_SUBBLOCK = 4
TARGET_PER_CORE_N = 5
D, NH, HD, V = R.D, R.NH, R.HD, R.VOCAB
NE, IE, TOPK = R.N_EXP, R.I_MOE, R.TOPK
PFX = "model."


def ttnn_dtype(name: str):
    import ttnn

    return {"bf16": ttnn.bfloat16, "bfp8": ttnn.bfloat8_b, "bfp4": ttnn.bfloat4_b, "fp32": ttnn.float32}[name]


def decode_matmul_config(device, in_features: int, out_features: int, fused_activation=None):
    import ttnn

    k_tiles, n_tiles = in_features // 32, out_features // 32
    grid = device.compute_with_storage_grid_size()
    in0_block_w = 8 if k_tiles % 8 == 0 and k_tiles > 64 else DECODE_IN0_BLOCK_W
    if k_tiles % in0_block_w:
        in0_block_w = next(w for w in (6, 5, 4, 3, 2, 1) if k_tiles % w == 0)
    cols = grid.x
    rows = max(1, min(grid.y, round(n_tiles / (cols * TARGET_PER_CORE_N))))
    per_core_n = -(-n_tiles // (cols * rows))
    return ttnn.MatmulMultiCoreReuseMultiCast1DProgramConfig(
        compute_with_storage_grid_size=(cols, rows), in0_block_w=in0_block_w, out_subblock_h=1,
        out_subblock_w=next(w for w in range(min(per_core_n, DECODE_MAX_SUBBLOCK), 0, -1) if per_core_n % w == 0),
        per_core_M=1, per_core_N=per_core_n, fuse_batch=True, fused_activation=fused_activation, mcast_in0=True)


def rope_rows(positions: torch.Tensor):
    """cos / sin [n, 128] (transformers 4.46 default rope, theta 10000)."""
    return R.rope_cos_sin(positions, HD, R.THETA)


class TtnnDecoder:
    def __init__(self, device, W: R.Weights, buckets: Sequence[int], max_seq: int, attn_dtype: str = "bf16",
                 mlp_dtype: str = "bfp8", expert_dtype: str = "bfp8", head_dtype: str = "bf16",
                 residual_fp32: bool = True, kv=None, decode: bool = True, pre_fidelity: str = "HiFi2",
                 loop_steps: int = 8, sparse_decode: bool = False, window: int = 0):
        """``window`` > 0: decode attention over the prompt + the last ``window`` generated positions (a KV ring
        after the prompt: the step writes row ``L + (p - L) mod window`` once the ring is full and attends rows
        ``0 .. L + window - 1``; schift-ocr-1-beta)."""
        import ttnn

        self.ttnn, self.device = ttnn, device
        self.buckets = sorted(int(b) for b in buckets)
        self.max_seq = -(-int(max_seq) // CACHE_TILE_MULTIPLE) * CACHE_TILE_MULTIPLE
        mk = lambda fid: ttnn.init_device_compute_kernel_config(  # noqa: E731
            device.arch(), math_fidelity=getattr(ttnn.MathFidelity, fid), math_approx_mode=False,
            fp32_dest_acc_en=True, packer_l1_acc=True)
        self.cc_pre = mk(pre_fidelity)
        self.cc = mk("HiFi4")
        self.res_dtype = ttnn.float32 if residual_fp32 else ttnn.bfloat16
        dram = ttnn.DRAM_MEMORY_CONFIG
        up = lambda t, dt: ttnn.from_torch(t.contiguous(), dtype=dt, layout=ttnn.TILE_LAYOUT, device=device,  # noqa
                                           memory_config=dram)
        ad, md, ed = ttnn_dtype(attn_dtype), ttnn_dtype(mlp_dtype), ttnn_dtype(expert_dtype)
        g = lambda n: W.get(PFX + n, cache=False)  # noqa: E731
        nrm = lambda n: up(g(n).reshape(1, 1, 1, -1), ttnn.bfloat16)  # noqa: E731
        self.NE = int(g("layers.1.mlp.gate.weight").shape[0])   # routed experts (64; schift-ocr-1-beta: 72)
        NE = self.NE
        # the router works on whole tiles: NEp = NE rounded up to 32 columns; padded experts get a -1e30 logit bias
        # (probability 0, never selected); 64 experts need no padding (bit-identical to before)
        self.NEp = NEp = -(-NE // 32) * 32
        self.window = int(window)
        self.win_base: Optional[int] = None   # the prompt length of the current request (set by prefill)
        self.layers = []
        for i in range(R.NL):
            p = f"layers.{i}."
            qkv = torch.cat([g(p + "self_attn.q_proj.weight"), g(p + "self_attn.k_proj.weight"),
                             g(p + "self_attn.v_proj.weight")], 0)
            L = {"in_norm": nrm(p + "input_layernorm.weight"), "pa_norm": nrm(p + "post_attention_layernorm.weight"),
                 "qkv": up(qkv.T, ad), "o": up(g(p + "self_attn.o_proj.weight").T, ad)}
            if i == 0:
                L["gate"] = up(g(p + "mlp.gate_proj.weight").T, md)
                L["up"] = up(g(p + "mlp.up_proj.weight").T, md)
                L["down"] = up(g(p + "mlp.down_proj.weight").T, md)
            else:
                m = p + "mlp."
                rw = g(m + "gate.weight")
                if NEp > NE:
                    rw = torch.cat([rw, torch.zeros(NEp - NE, rw.shape[1], dtype=rw.dtype)], 0)
                L["router"] = up(rw.T, ttnn.bfloat16)  # [D, NEp]
                L["sg"] = up(g(m + "shared_experts.gate_proj.weight").T, md)
                L["su"] = up(g(m + "shared_experts.up_proj.weight").T, md)
                L["sd"] = up(g(m + "shared_experts.down_proj.weight").T, md)
                gcat = torch.cat([g(m + f"experts.{e}.gate_proj.weight") for e in range(NE)], 0)  # [NE * IE, D]
                ucat = torch.cat([g(m + f"experts.{e}.up_proj.weight") for e in range(NE)], 0)
                dcat = torch.cat([g(m + f"experts.{e}.down_proj.weight") for e in range(NE)], 1).T
                L["eg"], L["eu"], L["ed"] = up(gcat.T, ed), up(ucat.T, ed), up(dcat, ed)
                if sparse_decode and decode:
                    # decode: the 6 routed experts' rows gathered on the device (ttnn.embedding needs bf16 row-major
                    # tables): [NE * IE, D] = gate / up rows and the down matrix's input rows
                    rm = lambda t: ttnn.from_torch(t.to(torch.bfloat16).contiguous(), dtype=ttnn.bfloat16,  # noqa
                                                   layout=ttnn.ROW_MAJOR_LAYOUT, device=device, memory_config=dram)
                    L["tg"], L["tu"], L["td"] = rm(gcat), rm(ucat), rm(dcat)
                del gcat, ucat, dcat
            self.layers.append(L)
        self.norm = nrm("norm.weight")
        self.head = up(W.get("lm_head.weight", cache=False).T, ttnn_dtype(head_dtype))  # [D, V]
        ex = torch.zeros(NEp, NE * IE)
        for e in range(NE):
            ex[e, e * IE:(e + 1) * IE] = 1.0
        rb = torch.zeros(1, 1, 1, NEp)
        rb[..., NE:] = -1e30
        self.rmask = up(rb, ttnn.float32) if NEp > NE else None
        self.expand = up(ex, ttnn.bfloat16)  # routing weights [*, 64] -> per expert column mask [*, 64 * 896]
        self.kv_ext = kv
        self.decode_enabled = decode
        if kv is None:
            self.k_cache = [ttnn.zeros([1, NH, self.max_seq, HD], dtype=ttnn.bfloat16, layout=ttnn.TILE_LAYOUT,
                                       device=device, memory_config=dram) for _ in self.layers]
            self.v_cache = [ttnn.zeros([1, NH, self.max_seq, HD], dtype=ttnn.bfloat16, layout=ttnn.TILE_LAYOUT,
                                       device=device, memory_config=dram) for _ in self.layers]
        gr = device.compute_with_storage_grid_size()
        self.n_cores = int(gr.x) * int(gr.y)
        silu = ttnn.UnaryWithParam(ttnn.UnaryOpType.SILU)
        L0, L1 = self.layers[0], self.layers[1]
        self.mm = {
            "qkv": decode_matmul_config(device, D, 3 * D), "o": decode_matmul_config(device, D, D),
            "gate0": decode_matmul_config(device, D, R.I_DENSE, silu), "up0": decode_matmul_config(device, D, R.I_DENSE),
            "down0": decode_matmul_config(device, R.I_DENSE, D),
            "sg": decode_matmul_config(device, D, IE * 2, silu), "su": decode_matmul_config(device, D, IE * 2),
            "sd": decode_matmul_config(device, IE * 2, D),
            "eg": decode_matmul_config(device, D, NE * IE, silu), "eu": decode_matmul_config(device, D, NE * IE),
            "ed": decode_matmul_config(device, NE * IE, D),
        }
        self.k_shard = self._single_core_shard(0)
        self.v_shard = self._single_core_shard(1)
        self.sdpa_dec_cfg = ttnn.SDPAProgramConfig(compute_with_storage_grid_size=(gr.x, gr.y), q_chunk_size=32,
                                                   k_chunk_size=0, exp_approx_mode=False)
        self.sdpa_pre_cfg = ttnn.SDPAProgramConfig(compute_with_storage_grid_size=(gr.x, gr.y), q_chunk_size=128,
                                                   k_chunk_size=128, exp_approx_mode=False)
        self.loop_steps = int(loop_steps)
        self.sparse_decode = bool(sparse_decode and decode)
        if self.sparse_decode:
            f32 = lambda t: up(t.float(), ttnn.float32)  # noqa: E731
            n = TOPK * IE
            j = torch.arange(n)
            e6 = torch.zeros(TOPK, n)
            e6[j // IE, j] = 1.0
            self.sp = {"tri": f32(torch.ones(NEp, NEp).tril()),                     # p_e = sum_{i <= e} s_i
                       "ones6": f32(torch.ones(1, TOPK)),
                       "krow": f32(torch.arange(1, TOPK + 1).float()[None].expand(NEp, TOPK)),
                       "ar64": f32(torch.arange(NEp).float()[None]),
                       "e6": f32(e6), "e6t": f32(e6.T.contiguous()),
                       "arj": f32((j % IE).float()[None])}
        if decode:
            self.embed = ttnn.from_torch(W.get(PFX + "embed_tokens.weight", cache=False).to(torch.bfloat16),
                                         dtype=ttnn.bfloat16, layout=ttnn.ROW_MAJOR_LAYOUT, device=device,
                                         memory_config=dram)
            self._tok = ttnn.from_torch(torch.zeros(1, 1, dtype=torch.int32), dtype=ttnn.uint32,
                                        layout=ttnn.ROW_MAJOR_LAYOUT, device=device)
            self._pos, self._cos, self._sin = [], [], []
            for _ in range(self.loop_steps):
                self._pos.append(ttnn.from_torch(torch.zeros(1, dtype=torch.int32), device=device))
                c, s_ = self._rope_dec(0)
                self._cos.append(ttnn.from_torch(c, dtype=ttnn.bfloat16, layout=ttnn.TILE_LAYOUT, device=device))
                self._sin.append(ttnn.from_torch(s_, dtype=ttnn.bfloat16, layout=ttnn.TILE_LAYOUT, device=device))
            # KV write rows: the attended extent (cur_pos) and the written row differ only with a decode window
            self._wpos = ([ttnn.from_torch(torch.zeros(1, dtype=torch.int32), device=device)
                           for _ in range(self.loop_steps)] if self.window else self._pos)
        self._pin, self._psel, self._prope = {}, {}, {}
        for Lb in self.buckets:
            self._alloc_bucket(Lb)
        self.step_trace = None
        self.loop_trace = None
        self.pre_traces: Dict[int, int] = {}
        self.pre_outs: Dict[int, object] = {}
        self.logits = None
        self.loop_out: List = []

    def _alloc_bucket(self, Lb: int):
        ttnn = self.ttnn
        self._pin[Lb] = ttnn.from_torch(torch.zeros(1, 1, Lb, D), dtype=ttnn.bfloat16, layout=ttnn.ROW_MAJOR_LAYOUT,
                                        device=self.device, memory_config=ttnn.DRAM_MEMORY_CONFIG)
        self._psel[Lb] = ttnn.from_torch(torch.zeros(1, 1, 1, Lb), dtype=ttnn.bfloat16, layout=ttnn.TILE_LAYOUT,
                                         device=self.device)
        c, s = rope_rows(torch.arange(Lb))
        self._prope[Lb] = (ttnn.from_torch(c.reshape(1, 1, Lb, HD), dtype=ttnn.bfloat16, layout=ttnn.TILE_LAYOUT,
                                           device=self.device),
                           ttnn.from_torch(s.reshape(1, 1, Lb, HD), dtype=ttnn.bfloat16, layout=ttnn.TILE_LAYOUT,
                                           device=self.device))

    @staticmethod
    def _rope_dec(pos: int):
        c, s = rope_rows(torch.tensor([int(pos)]))
        return (c.reshape(1, 1, 1, HD).expand(1, 1, 32, HD).contiguous(),
                s.reshape(1, 1, 1, HD).expand(1, 1, 32, HD).contiguous())

    def _single_core_shard(self, column):
        ttnn = self.ttnn
        return ttnn.MemoryConfig(
            ttnn.TensorMemoryLayout.HEIGHT_SHARDED, ttnn.BufferType.L1,
            ttnn.ShardSpec(ttnn.CoreRangeSet({ttnn.CoreRange(ttnn.CoreCoord(column, 0), ttnn.CoreCoord(column, 0))}),
                           (32, HD), ttnn.ShardOrientation.ROW_MAJOR))

    def bucket(self, L: int) -> int:
        for b in self.buckets:
            if L <= b:
                return b
        raise ValueError(f"prompt of {L} rows exceeds the largest prefill bucket {self.buckets[-1]}")

    # ------------------------------------------------------------------ pieces
    def _rms(self, x, w, out_bf16=True):
        ttnn = self.ttnn
        y = ttnn.rms_norm(x, weight=w, epsilon=R.EPS, compute_kernel_config=self.cc)
        return ttnn.typecast(y, ttnn.bfloat16) if (out_bf16 and y.dtype != ttnn.bfloat16) else y

    def _add(self, x, y):
        ttnn = self.ttnn
        if x.dtype != y.dtype:
            y = ttnn.typecast(y, x.dtype)
        return ttnn.add(x, y)

    def _lin(self, x, w, decode: bool, cfg: Optional[str] = None, act=None, dtype=None):
        ttnn = self.ttnn
        kw = {}
        if decode and cfg:
            kw["program_config"] = self.mm[cfg]
        elif act:
            kw["activation"] = act
        if dtype is not None:
            kw["dtype"] = dtype
        return ttnn.linear(x, w, compute_kernel_config=self.cc if decode else self.cc_pre, **kw)

    def _swiglu(self, x, wg, wu, wd, decode, names):
        ttnn = self.ttnn
        g = self._lin(x, wg, decode, names[0], act="silu")
        u = self._lin(x, wu, decode, names[1])
        a = ttnn.multiply(g, u)
        ttnn.deallocate(g)
        ttnn.deallocate(u)
        y = self._lin(a, wd, decode, names[2])
        ttnn.deallocate(a)
        return y

    def route_weights(self, h, L):
        """Router of one MoE layer: [rows, 64] fp32 = softmax probabilities where the expert is in the row's top-6, else
        0 (6th largest by iterated max: exact in fp32; exact ties keep both)."""
        ttnn = self.ttnn
        logits = ttnn.linear(h, L["router"], compute_kernel_config=self.cc, dtype=ttnn.float32)
        if self.rmask is not None:
            lm = ttnn.add(logits, self.rmask)
            ttnn.deallocate(logits)
            logits = lm
        p = ttnn.softmax(logits, dim=-1, numeric_stable=True, compute_kernel_config=self.cc)
        ttnn.deallocate(logits)
        x = p
        for k in range(TOPK):
            m = ttnn.max(x, dim=-1, keepdim=True)
            if k == TOPK - 1:
                break
            hit = ttnn.ge(x, m)
            x2 = ttnn.where(hit, -1.0, x)
            if x is not p:
                ttnn.deallocate(x)
            ttnn.deallocate(hit)
            ttnn.deallocate(m)
            x = x2
        keep = ttnn.ge(p, m, dtype=ttnn.float32)
        w = ttnn.multiply(p, keep)
        ttnn.deallocate(keep)
        if x is not p:
            ttnn.deallocate(x)
        ttnn.deallocate(p)
        return w

    def _moe_sparse(self, h, L):
        """Decode MoE over the 6 routed experts only (one row): slot k <- the k-th selected expert (prefix counts of
        the top-6 mask, exact small integers), their gate / up / down rows gathered from the row tables with
        ttnn.embedding, column-oriented matmuls (no transpose of the gathered weights). Reads 6 / 64 of the expert
        weights of the dense path (bf16: ~41 MB per layer instead of ~233 MB bfp8)."""
        ttnn, sp, f32 = self.ttnn, self.sp, self.ttnn.float32
        cc = self.cc
        w = self.route_weights(h, L)                                            # [1, 1, 1, NE] (0 = not routed)
        wt = ttnn.transpose(w, -2, -1)                                          # [1, 1, NE, 1]
        s = ttnn.typecast(ttnn.gt(wt, 0.0), f32)
        p = ttnn.matmul(sp["tri"], s, compute_kernel_config=cc, dtype=f32)     # inclusive prefix counts
        p6 = ttnn.matmul(p, sp["ones6"], compute_kernel_config=cc, dtype=f32)  # [NE, 6]
        s6 = ttnn.matmul(s, sp["ones6"], compute_kernel_config=cc, dtype=f32)
        mt = ttnn.multiply(ttnn.typecast(ttnn.eq(p6, sp["krow"]), f32), s6)    # [NE, 6] one-hot expert of slot k
        ids = ttnn.matmul(sp["ar64"], mt, compute_kernel_config=cc, dtype=f32)  # [1, 6] expert ids
        wsel = ttnn.matmul(w, mt, compute_kernel_config=cc, dtype=f32)         # [1, 6] their routing weights
        idf = ttnn.matmul(ids, sp["e6"], compute_kernel_config=cc, dtype=f32)  # [1, 6 * IE] id of each row
        idf = ttnn.add(ttnn.multiply(idf, float(IE)), sp["arj"])                # row index e * IE + j (exact fp32)
        idx = ttnn.to_layout(ttnn.typecast(idf, ttnn.uint32), ttnn.ROW_MAJOR_LAYOUT)
        n = TOPK * IE
        rows = [ttnn.reshape(ttnn.embedding(idx, L[t], layout=ttnn.TILE_LAYOUT), (1, 1, n, D))
                for t in ("tg", "tu", "td")]
        xt = ttnn.transpose(h, -2, -1)                                          # [1, 1, D, 1]
        gc = ttnn.matmul(rows[0], xt, compute_kernel_config=cc, dtype=f32)     # [1, 1, n, 1]
        uc = ttnn.matmul(rows[1], xt, compute_kernel_config=cc, dtype=f32)
        wc = ttnn.matmul(sp["e6t"], ttnn.transpose(wsel, -2, -1), compute_kernel_config=cc, dtype=f32)
        a = ttnn.multiply(ttnn.multiply(ttnn.silu(gc), uc), wc, dtype=ttnn.bfloat16)
        ar = ttnn.transpose(a, -2, -1)                                          # [1, 1, 1, n]
        y = ttnn.matmul(ar, rows[2], compute_kernel_config=cc, dtype=f32)      # [1, 1, 1, D]
        for t in rows + [wt, s, p, p6, s6, mt, ids, wsel, idf, idx, xt, gc, uc, wc, a, ar, w]:
            ttnn.deallocate(t)
        ys = self._swiglu(h, L["sg"], L["su"], L["sd"], True, ("sg", "su", "sd"))
        out = ttnn.add(y, ys, dtype=ttnn.float32)
        ttnn.deallocate(y)
        ttnn.deallocate(ys)
        return out

    def _moe(self, h, L, decode: bool, stages=None, i=0):
        ttnn = self.ttnn
        if decode and self.sparse_decode and stages is None:
            return self._moe_sparse(h, L)
        w = self.route_weights(h, L)
        if stages is not None:
            stages[f"route{i}"] = w
        mask = ttnn.matmul(w, self.expand, compute_kernel_config=self.cc, dtype=ttnn.float32)  # [rows, 64 * 896]
        if stages is None:
            ttnn.deallocate(w)
        g = self._lin(h, L["eg"], decode, "eg", act="silu")
        u = self._lin(h, L["eu"], decode, "eu")
        a = ttnn.multiply(g, u)
        ttnn.deallocate(g)
        ttnn.deallocate(u)
        am = ttnn.multiply(a, mask, dtype=ttnn.bfloat16)
        ttnn.deallocate(a)
        ttnn.deallocate(mask)
        y = self._lin(am, L["ed"], decode, "ed", dtype=ttnn.float32)
        ttnn.deallocate(am)
        ys = self._swiglu(h, L["sg"], L["su"], L["sd"], decode, ("sg", "su", "sd"))
        out = ttnn.add(y, ys, dtype=ttnn.float32)
        ttnn.deallocate(y)
        ttnn.deallocate(ys)
        return out

    def _mlp(self, h, i, L, decode, stages=None):
        if i == 0:
            return self._swiglu(h, L["gate"], L["up"], L["down"], decode, ("gate0", "up0", "down0"))
        return self._moe(h, L, decode, stages, i)

    def _rotate(self, x, cos, sin, decode=False):
        return self.ttnn.experimental.rotary_embedding_hf(x, cos, sin, is_decode_mode=decode,
                                                          compute_kernel_config=self.cc)

    def _kv(self, i):
        if self.kv_ext is not None:
            return self.kv_ext, 2 * i, self.kv_ext, 2 * i + 1
        return self.k_cache[i], 0, self.v_cache[i], 0

    # ------------------------------------------------------------------ prefill
    def _prefill_ops(self, Lb: int, stages: Optional[dict] = None):
        ttnn = self.ttnn
        cos, sin = self._prope[Lb]
        x = ttnn.to_layout(self._pin[Lb], ttnn.TILE_LAYOUT)
        if self.res_dtype != ttnn.bfloat16:
            x = ttnn.typecast(x, self.res_dtype)
        for i, L in enumerate(self.layers):
            a = self._rms(x, L["in_norm"])
            qkv = ttnn.linear(a, L["qkv"], compute_kernel_config=self.cc_pre, dtype=ttnn.bfloat16)
            ttnn.deallocate(a)
            q, k, v = ttnn.experimental.nlp_create_qkv_heads(qkv, num_heads=NH, num_kv_heads=NH,
                                                             transpose_k_heads=False,
                                                             memory_config=ttnn.DRAM_MEMORY_CONFIG)
            ttnn.deallocate(qkv)
            q = self._rotate(q, cos, sin)
            k = self._rotate(k, cos, sin)
            kc, kb, vc, vb = self._kv(i)
            self._seed(kc, kb, k, Lb)
            self._seed(vc, vb, v, Lb)
            o = ttnn.transformer.scaled_dot_product_attention(q, k, v, is_causal=True, scale=HD ** -0.5,
                                                              compute_kernel_config=self.cc,
                                                              program_config=self.sdpa_pre_cfg)
            ttnn.deallocate(q)
            ttnn.deallocate(k)
            ttnn.deallocate(v)
            o = ttnn.experimental.nlp_concat_heads(o, memory_config=ttnn.DRAM_MEMORY_CONFIG)
            y = ttnn.linear(o, L["o"], compute_kernel_config=self.cc_pre, dtype=ttnn.float32)
            ttnn.deallocate(o)
            x = self._add(x, y)
            a = self._rms(x, L["pa_norm"])
            y = self._mlp(a, i, L, False, stages)
            ttnn.deallocate(a)
            x = self._add(x, y)
            if stages is not None:
                stages[f"layer{i}"] = x
        xb = ttnn.typecast(x, ttnn.bfloat16) if x.dtype != ttnn.bfloat16 else x
        last = ttnn.matmul(self._psel[Lb], xb, compute_kernel_config=self.cc, dtype=ttnn.float32)  # row L-1
        h = self._rms(last, self.norm)
        lg = ttnn.linear(h, self.head, compute_kernel_config=self.cc, dtype=ttnn.float32)
        return ttnn.to_layout(lg, ttnn.ROW_MAJOR_LAYOUT)  # [1, 1, 1, V]

    def _seed(self, cache, batch: int, x, length: int):
        ttnn = self.ttnn
        tiles = (length + 31) // 32
        if NH * tiles <= self.n_cores:
            ttnn.fill_cache(cache, x, batch)
            return
        step = max(1, self.n_cores // NH)
        for start in range(0, tiles, step):
            first, last = 32 * start, min(32 * (start + step), length)
            chunk = ttnn.slice(x, (0, 0, first, 0), (1, NH, last, HD))
            ttnn.fill_cache(cache, chunk, batch, update_idx=first)
            ttnn.deallocate(chunk)

    def prefill(self, rows: torch.Tensor, L: int, stages: Optional[dict] = None):
        """Enqueue the prefill of L host rows [L, D] at positions 0..L-1; returns the logits device tensor."""
        ttnn = self.ttnn
        Lb = self.bucket(L)
        self.win_base = int(L)
        x = torch.zeros(1, 1, Lb, D, dtype=torch.bfloat16)
        x[0, 0, :L] = rows[:L].to(torch.bfloat16)
        sel = torch.zeros(1, 1, 1, Lb)
        sel[0, 0, 0, L - 1] = 1.0
        ttnn.copy_host_to_device_tensor(ttnn.from_torch(x, dtype=ttnn.bfloat16, layout=ttnn.ROW_MAJOR_LAYOUT),
                                        self._pin[Lb])
        ttnn.copy_host_to_device_tensor(ttnn.from_torch(sel, dtype=ttnn.bfloat16, layout=ttnn.TILE_LAYOUT),
                                        self._psel[Lb])
        if Lb in self.pre_traces and stages is None:
            ttnn.execute_trace(self.device, self.pre_traces[Lb], cq_id=0, blocking=False)
            self.logits = self.pre_outs[Lb]
        else:
            self.logits = self._prefill_ops(Lb, stages)
        return self.logits

    # ------------------------------------------------------------------ decode step
    def _step_core(self, tok, k: int = 0):
        ttnn = self.ttnn
        pos, cos, sin, wpos = self._pos[k], self._cos[k], self._sin[k], self._wpos[k]
        x = ttnn.embedding(tok, self.embed, layout=ttnn.TILE_LAYOUT)
        x = ttnn.reshape(x, (1, 1, 1, D))
        if self.res_dtype != ttnn.bfloat16:
            x = ttnn.typecast(x, self.res_dtype)
        for i, L in enumerate(self.layers):
            a = self._rms(x, L["in_norm"])
            qkv = ttnn.linear(a, L["qkv"], compute_kernel_config=self.cc, program_config=self.mm["qkv"],
                              dtype=ttnn.bfloat16)
            q, k_, v = ttnn.experimental.nlp_create_qkv_heads_decode(
                ttnn.reshape(qkv, (1, 1, 1, qkv.shape[-1])), num_heads=NH, num_kv_heads=NH)
            q = ttnn.sharded_to_interleaved(q)
            k_ = ttnn.sharded_to_interleaved(k_)
            q = self._rotate(q, cos, sin)
            k_ = self._rotate(k_, cos, sin)
            if self.kv_ext is not None:
                raise NotImplementedError("decode on the external KV tensor: use the DEC megakernel")
            kc, vc = self.k_cache[i], self.v_cache[i]
            ttnn.experimental.paged_fused_update_cache(
                kc, ttnn.to_memory_config(k_, self.k_shard), vc, ttnn.to_memory_config(v, self.v_shard),
                update_idxs_tensor=wpos, page_table=None)
            att = ttnn.transformer.scaled_dot_product_attention_decode(
                q, kc, vc, cur_pos_tensor=pos, scale=HD ** -0.5, compute_kernel_config=self.cc,
                program_config=self.sdpa_dec_cfg)
            att = ttnn.reshape(ttnn.experimental.nlp_concat_heads(att), (1, 1, 1, NH * HD))
            y = ttnn.linear(att, L["o"], compute_kernel_config=self.cc, program_config=self.mm["o"])
            x = self._add(x, y)
            a = self._rms(x, L["pa_norm"])
            x = self._add(x, self._mlp(a, i, L, True))
        h = self._rms(x, self.norm)
        lg = ttnn.linear(h, self.head, compute_kernel_config=self.cc, dtype=ttnn.float32)
        return ttnn.to_layout(lg, ttnn.ROW_MAJOR_LAYOUT)

    def _argmax(self, lg):
        ttnn = self.ttnn
        t = ttnn.argmax(lg, dim=-1, keepdim=True)
        return ttnn.reshape(t, (1, 1))

    def kv_slots(self, pos: int):
        """(KV row written by the step at position ``pos``, last attended row): (pos, pos) without a window or before
        the ring is full; then (L + (pos - L) mod window, L + window - 1)."""
        W, L = self.window, self.win_base
        if W and L is not None and pos >= L + W:
            return L + (pos - L) % W, L + W - 1
        return pos, pos

    def set_step(self, token: Optional[int], pos: int, k: int = 0):
        ttnn = self.ttnn
        if token is not None:
            ttnn.copy_host_to_device_tensor(ttnn.from_torch(torch.tensor([[token]], dtype=torch.int32),
                                                            dtype=ttnn.uint32, layout=ttnn.ROW_MAJOR_LAYOUT),
                                            self._tok)
        wrow, ext = self.kv_slots(pos)
        ttnn.copy_host_to_device_tensor(ttnn.from_torch(torch.tensor([ext], dtype=torch.int32)), self._pos[k])
        if self.window:
            ttnn.copy_host_to_device_tensor(ttnn.from_torch(torch.tensor([wrow], dtype=torch.int32)), self._wpos[k])
        c, s = self._rope_dec(pos)   # RoPE: the absolute position
        ttnn.copy_host_to_device_tensor(ttnn.from_torch(c, dtype=ttnn.bfloat16, layout=ttnn.TILE_LAYOUT),
                                        self._cos[k])
        ttnn.copy_host_to_device_tensor(ttnn.from_torch(s, dtype=ttnn.bfloat16, layout=ttnn.TILE_LAYOUT),
                                        self._sin[k])

    def step(self, token: int, pos: int):
        ttnn = self.ttnn
        self.set_step(token, pos, 0)
        if self.step_trace is not None:
            ttnn.execute_trace(self.device, self.step_trace, cq_id=0, blocking=False)
            self.logits = self.step_out
        else:
            self.logits = self._step_core(self._tok, 0)
        return self.logits

    def _loop_ops(self):
        tok, outs = self._tok, []
        for k in range(self.loop_steps):
            tok = self._argmax(self._step_core(tok, k))
            outs.append(tok)
        return self.ttnn.concat(outs, dim=1) if len(outs) > 1 else outs[0]

    def loop(self, token: int, pos: int):
        ttnn = self.ttnn
        for k in range(self.loop_steps):
            self.set_step(token if k == 0 else None, pos + k, k)
        if self.loop_trace is not None:
            ttnn.execute_trace(self.device, self.loop_trace, cq_id=0, blocking=False)
            return self.loop_out
        return self._loop_ops()

    def logits_host(self) -> torch.Tensor:
        return self.ttnn.to_torch(self.logits).float().reshape(-1, self.logits.shape[-1])[0, :V]

    # ------------------------------------------------------------------ traces
    def warmup(self, prefill: bool = True):
        if self.decode_enabled:
            self.set_step(0, 0, 0)
            self._step_core(self._tok, 0)
            self._loop_ops()
        for Lb in self.buckets if prefill else ():
            self._prefill_ops(Lb)
        self.ttnn.synchronize_device(self.device)
        self._warm = True

    def capture(self, prefill: bool = True):
        ttnn = self.ttnn
        if not getattr(self, "_warm", False):
            self.warmup(prefill)
        if self.decode_enabled:
            self.step_trace = ttnn.begin_trace_capture(self.device, cq_id=0)
            self.step_out = self._step_core(self._tok, 0)
            ttnn.end_trace_capture(self.device, self.step_trace, cq_id=0)
            self.loop_trace = ttnn.begin_trace_capture(self.device, cq_id=0)
            self.loop_out = self._loop_ops()
            ttnn.end_trace_capture(self.device, self.loop_trace, cq_id=0)
        for Lb in self.buckets if prefill else ():
            tid = ttnn.begin_trace_capture(self.device, cq_id=0)
            self.pre_outs[Lb] = self._prefill_ops(Lb)
            ttnn.end_trace_capture(self.device, tid, cq_id=0)
            self.pre_traces[Lb] = tid
        # outputs are read (logits / argmax tokens to the host) right after their replay
        TS.acknowledge_outputs(self.step_out if self.decode_enabled else None,
                               self.loop_out if self.decode_enabled else None, self.pre_outs)
        ttnn.synchronize_device(self.device)

    def release(self):
        ttnn = self.ttnn
        for t in (self.step_trace, self.loop_trace):
            if t is not None:
                ttnn.release_trace(self.device, t)
        self.step_trace = self.loop_trace = None
        for tid in self.pre_traces.values():
            ttnn.release_trace(self.device, tid)
        self.pre_traces.clear()