File size: 24,334 Bytes
aa204f5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# SPDX-License-Identifier: Apache-2.0
# Adapted from this workspace's Qwen3-ASR bundle (tt_qwen3_asr/tt/ttnn_decoder.py, Apache-2.0), itself adapted from
# tt-metal models/demos/audio/qwen3_tts (Apache-2.0, Tenstorrent): the M=1 decode matmul configs, fused QKV,
# nlp_create_qkv_heads_decode + rotary_embedding_hf + paged_fused_update_cache + sdpa_decode, the KV fill_cache
# chunking and the persistent-input trace pattern. GLM changes: sandwich norms, untied head, M-RoPE (host tables per
# prompt row, decode at p + delta), q / k rows permuted to the half-split rope layout, on-device greedy loop.
"""ttnn baseline of the GLM-OCR text decoder (GLM-0.5B, 16 layers).

* ``prefill(rows [L, D] host bf16, cos, sin [L, 128], L)``: rows zero-padded to the smallest bucket >= L, H2D (row
  major, tilized on device), the bucket's trace: KV [0, Lb), logits of row L - 1 (one-hot row select).
* ``step(token, pos, rope_pos)``: one decode step (host argmax / sampling path); ``loop(K)``: K greedy steps in one
  trace with on-device argmax -> embedding -> next step (token / position / rope rows stay on the device).
"""

from __future__ import annotations

from typing import Dict, List, Optional, Sequence

import torch

from ..reference import model as R

PFX_L = "model.language_model."
CACHE_TILE_MULTIPLE = 64
DECODE_IN0_BLOCK_W = 4
DECODE_MAX_SUBBLOCK = 4
TARGET_PER_CORE_N = 5
D, NQ, NKV, HD, I, V = R.T_D, R.T_HEADS, R.T_KV, R.T_HD, R.T_I, R.VOCAB


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, 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 half_perm() -> torch.Tensor:
    """Row permutation of one 128-dim head: [0, 2, .., 126, 1, 3, .., 127] (interleaved pairs -> half split)."""
    return torch.cat([torch.arange(0, HD, 2), torch.arange(1, HD, 2)])


def rope_half(pos3d: torch.Tensor):
    """cos / sin [L, 128] in the half-split layout for 3D positions [3, L] (M-RoPE sections 16 / 24 / 24)."""
    c, s = R.mrope_cos_sin(pos3d)  # interleaved [L, 128]: pair j at 2j, 2j+1
    p = half_perm()
    return c[:, p], s[:, p]


class TtnnDecoder:
    def __init__(self, device, W, buckets: Sequence[int], max_seq: int, attn_dtype: str = "bf16",
                 mlp_dtype: str = "bfp8", head_dtype: str = "bf16", residual_fp32: bool = True, kv=None,
                 decode: bool = True, pre_fidelity: str = "HiFi4", loop_steps: int = 8, rope_mm: bool = False):
        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
        self.cc_pre = ttnn.init_device_compute_kernel_config(device.arch(),
                                                             math_fidelity=getattr(ttnn.MathFidelity, pre_fidelity),
                                                             math_approx_mode=False, fp32_dest_acc_en=True,
                                                             packer_l1_acc=True)
        self.cc = ttnn.init_device_compute_kernel_config(device.arch(), math_fidelity=ttnn.MathFidelity.HiFi4,
                                                         math_approx_mode=False, fp32_dest_acc_en=True,
                                                         packer_l1_acc=True)
        self.res_dtype = ttnn.float32 if residual_fp32 else ttnn.bfloat16
        self.rope_mm = bool(rope_mm)  # prefill rope as x cos + (x @ RH) sin instead of rotary_embedding_hf
        up = lambda t, dt: ttnn.from_torch(t.contiguous(), dtype=dt, layout=ttnn.TILE_LAYOUT, device=device,  # noqa
                                           memory_config=ttnn.DRAM_MEMORY_CONFIG)
        ad, md = ttnn_dtype(attn_dtype), ttnn_dtype(mlp_dtype)
        perm = half_perm()
        qp = torch.cat([h * HD + perm for h in range(NQ)])
        kp = torch.cat([h * HD + perm for h in range(NKV)])
        self.layers = []
        for i in range(R.T_LAYERS):
            p = PFX_L + f"layers.{i}."
            g = lambda n: W[p + n].float()  # noqa: E731
            qkv = torch.cat([g("self_attn.q_proj.weight")[qp], g("self_attn.k_proj.weight")[kp],
                             g("self_attn.v_proj.weight")], 0)
            gu = g("mlp.gate_up_proj.weight")
            nrm = lambda n: up(g(n).reshape(1, 1, 1, -1), ttnn.bfloat16)  # noqa: E731
            self.layers.append({
                "in_norm": nrm("input_layernorm.weight"), "psa_norm": nrm("post_self_attn_layernorm.weight"),
                "pa_norm": nrm("post_attention_layernorm.weight"), "pm_norm": nrm("post_mlp_layernorm.weight"),
                "qkv": up(qkv.T, ad), "o": up(g("self_attn.o_proj.weight").T, ad),
                "gate": up(gu[:I].T, md), "up": up(gu[I:].T, md), "down": up(g("mlp.down_proj.weight").T, md),
            })
        self.norm = up(W[PFX_L + "norm.weight"].float().reshape(1, 1, 1, -1), ttnn.bfloat16)
        rh = torch.zeros(HD, HD)  # rotate_half as a matmul: x @ RH = cat(-x[64:], x[:64]) (exact)
        for j in range(HD // 2):
            rh[j + HD // 2, j] = -1.0
            rh[j, j + HD // 2] = 1.0
        self.rot_half = up(rh, ttnn.bfloat16)
        self.head = up(W["lm_head.weight"].float().T, ttnn_dtype(head_dtype))  # [D, V]
        self.kv_ext = kv
        self.decode_enabled = decode
        if kv is None:
            self.k_cache = [ttnn.zeros([1, NKV, self.max_seq, HD], dtype=ttnn.bfloat16, layout=ttnn.TILE_LAYOUT,
                                       device=device, memory_config=ttnn.DRAM_MEMORY_CONFIG) for _ in self.layers]
            self.v_cache = [ttnn.zeros([1, NKV, self.max_seq, HD], dtype=ttnn.bfloat16, layout=ttnn.TILE_LAYOUT,
                                       device=device, memory_config=ttnn.DRAM_MEMORY_CONFIG) for _ in self.layers]
        g = device.compute_with_storage_grid_size()
        self.n_cores = int(g.x) * int(g.y)
        silu = ttnn.UnaryWithParam(ttnn.UnaryOpType.SILU)
        L0 = self.layers[0]
        self.mm = {n: decode_matmul_config(device, *tuple(L0[n].shape)[-2:], silu if n == "gate" else None)
                   for n in ("qkv", "o", "gate", "up", "down")}
        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=(g.x, g.y), q_chunk_size=32,
                                                   k_chunk_size=0, exp_approx_mode=False)
        self.sdpa_pre_cfg = ttnn.SDPAProgramConfig(compute_with_storage_grid_size=(g.x, g.y), q_chunk_size=128,
                                                   k_chunk_size=128, exp_approx_mode=False)
        # decode inputs (persistent): the embedding table (on-device greedy loop: argmax -> embedding -> next
        # step), the input token of the first step, and per loop step k: cache index pos[k] and rope rows cos / sin[k]
        self.loop_steps = int(loop_steps)
        if decode:
            self.embed = ttnn.from_torch(W[PFX_L + "embed_tokens.weight"].to(torch.bfloat16), dtype=ttnn.bfloat16,
                                         layout=ttnn.ROW_MAJOR_LAYOUT, device=device,
                                         memory_config=ttnn.DRAM_MEMORY_CONFIG)
            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_rows(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))
        self._pin, self._psel, self._prope = {}, {}, {}
        for Lb in self.buckets:
            self._pin[Lb] = ttnn.from_torch(torch.zeros(1, 1, Lb, D), dtype=ttnn.bfloat16,
                                            layout=ttnn.ROW_MAJOR_LAYOUT, device=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=device)
            z = torch.zeros(1, 1, Lb, HD)
            self._prope[Lb] = (ttnn.from_torch(z, dtype=ttnn.bfloat16, layout=ttnn.TILE_LAYOUT, device=device),
                               ttnn.from_torch(z, dtype=ttnn.bfloat16, layout=ttnn.TILE_LAYOUT, device=device))
        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 = []

    @staticmethod
    def _rope_rows(rope_pos: int):
        c, s = rope_half(torch.full((3, 1), int(rope_pos), dtype=torch.long))
        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 _mlp(self, x, L, decode: bool):
        ttnn = self.ttnn
        cfg = self.mm if decode else {}
        cc = self.cc if decode else self.cc_pre
        if decode:
            gate = ttnn.linear(x, L["gate"], compute_kernel_config=cc, program_config=cfg["gate"])
        else:
            gate = ttnn.linear(x, L["gate"], compute_kernel_config=cc, activation="silu")
        upv = ttnn.linear(x, L["up"], compute_kernel_config=cc, program_config=cfg.get("up"))
        return ttnn.linear(ttnn.multiply(gate, upv), L["down"], compute_kernel_config=cc,
                           program_config=cfg.get("down"))

    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 _rope_pre(self, x, cos, sin):
        return self._rope_mm(x, cos, sin) if self.rope_mm else self._rotate(x, cos, sin)

    def _rope_mm(self, x, cos, sin):
        """Prefill rope: x * cos + rotate_half(x) * sin, fp32 products (rotary_embedding_hf is slow at large L)."""
        ttnn = self.ttnn
        r = ttnn.matmul(x, self.rot_half, compute_kernel_config=self.cc, dtype=ttnn.bfloat16)
        a = ttnn.multiply(x, cos, dtype=ttnn.float32)
        b = ttnn.multiply(r, sin, dtype=ttnn.float32)
        ttnn.deallocate(r)
        return ttnn.add(a, b, dtype=ttnn.bfloat16)

    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=NQ, num_kv_heads=NKV,
                                                             transpose_k_heads=False,
                                                             memory_config=ttnn.DRAM_MEMORY_CONFIG)
            ttnn.deallocate(qkv)
            q = self._rope_pre(q, cos, sin)
            k = self._rope_pre(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)
            ttnn.deallocate(o)
            x = self._add(x, self._rms(y, L["psa_norm"], out_bf16=False))
            a = self._rms(x, L["pa_norm"])
            y = self._mlp(a, L, False)
            ttnn.deallocate(a)
            x = self._add(x, self._rms(y, L["pm_norm"], out_bf16=False))
            if stages is not None and i in (0, 7, 15):
                stages[f"t_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):
        """KV rows [0, length) of one layer (``ttnn.fill_cache``, chunked so that no core's write run crosses a head
        boundary: the tt-metal hazard handled the same way in the Qwen3-TTS / Qwen3-ASR bundles)."""
        ttnn = self.ttnn
        tiles = (length + 31) // 32
        if NKV * tiles <= self.n_cores:
            ttnn.fill_cache(cache, x, batch)
            return
        step = max(1, self.n_cores // NKV)
        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, NKV, last, HD))
            ttnn.fill_cache(cache, chunk, batch, update_idx=first)
            ttnn.deallocate(chunk)

    def prefill(self, rows: torch.Tensor, pos3d: torch.Tensor, L: int, stages: Optional[dict] = None):
        """Enqueue the prefill of L host rows [L, D] at 3D positions [3, L]; returns the logits device tensor."""
        ttnn = self.ttnn
        Lb = self.bucket(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
        pos = torch.zeros(3, Lb, dtype=torch.long)
        pos[:, :L] = torch.as_tensor(pos3d)[:, :L]
        c, s = rope_half(pos)
        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])
        ttnn.copy_host_to_device_tensor(ttnn.from_torch(c.reshape(1, 1, Lb, HD), dtype=ttnn.bfloat16,
                                                        layout=ttnn.TILE_LAYOUT), self._prope[Lb][0])
        ttnn.copy_host_to_device_tensor(ttnn.from_torch(s.reshape(1, 1, Lb, HD), dtype=ttnn.bfloat16,
                                                        layout=ttnn.TILE_LAYOUT), self._prope[Lb][1])
        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):
        """One step: input token tensor [1, 1] uint32, cache index self._pos[k], rope rows self._cos / _sin[k];
        returns logits [1, 1, 1, V] fp32 (row major)."""
        ttnn = self.ttnn
        pos, cos, sin = self._pos[k], self._cos[k], self._sin[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=NQ, num_kv_heads=NKV)
            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=pos, 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, NQ * HD))
            y = ttnn.linear(att, L["o"], compute_kernel_config=self.cc, program_config=self.mm["o"])
            x = self._add(x, self._rms(y, L["psa_norm"], out_bf16=False))
            a = self._rms(x, L["pa_norm"])
            x = self._add(x, self._rms(self._mlp(a, L, True), L["pm_norm"], out_bf16=False))
        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 set_step(self, token: Optional[int], pos: int, rope_pos: int, k: int = 0):
        """Upload the inputs of loop step k (the token only for k = 0 / single steps)."""
        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)
        ttnn.copy_host_to_device_tensor(ttnn.from_torch(torch.tensor([pos], dtype=torch.int32)), self._pos[k])
        c, s = self._rope_rows(rope_pos)
        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, rope_pos: int):
        """One decode step for input token at cache index pos (rope position rope_pos): logits device tensor."""
        ttnn = self.ttnn
        self.set_step(token, pos, rope_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]  # [1, K] uint32

    def loop(self, token: int, pos: int, rope_pos: int):
        """K = loop_steps greedy steps from input ``token`` at cache index ``pos`` (rope position ``rope_pos``); the
        on-device argmax feeds each next step. Returns the [1, K] uint32 token tensor (device)."""
        ttnn = self.ttnn
        for k in range(self.loop_steps):
            self.set_step(token if k == 0 else None, pos + k, rope_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, 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
        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()