File size: 27,603 Bytes
f882f26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# SPDX-License-Identifier: Apache-2.0
"""The ``ttnn`` engine: laya's decision model in stock ttnn ops (the A/B baseline of the megakernel and its fallback).

Rows (one per (state, question)) are padded to a (batch, length) bucket; ttnn shapes are compile-time, so one Metal
trace per bucket.  Per launch the host uploads the token ids [B, S] (uint32), the key-padding bias [B, 1, 32, S],
the type-embedding rows [B, 1, 32, D] (row 0 used) and the selection matrix [B, 32, S] (row 0 = [CLS], rows
1..K = the [MASK] markers); the device returns the scorer logits [B, 32, 32] (column 0, rows 1..K) and the pooled
[CLS] projection of the action head [B, 32, 256] (row 0).  The host finishes the action head (4 features).

Precision: residual stream float32 (ModernBERT's activations reach ~2e4), bf16 matmul inputs / weights with fp32
accumulation (HiFi4 by default), LayerNorm / softmax in fp32, the embedding table in fp32.
"""
from __future__ import annotations

import math
import time
from typing import Dict, List, Optional, Sequence, Tuple

import numpy as np

from ..weights import Arch
from . import traces

MASK_NEG = -1e9
SEL_ROWS = 128         # [CLS] + up to 127 markers per row gathered (more options -> host error, see api)
ACT_HID = 256


def sdpa_key_chunk(S: int, kmax: int = 512) -> int:
    """The SDPA key chunk for a bucket of S keys: the largest multiple of 32 <= min(S, kmax) whose chunk count
    ceil(S / k) is EVEN. tt-metal 44d6650's non-causal SDPA returns wrong (batch, head) slots when the key-chunk count
    is odd (1 included) and batch x heads is large enough for its KV chain forwarding (upstream fix PR #60493;
    logs/sdpa_audit/REPORT.md); F8 (k 1024 at S 1024: one chunk) was this bug. S of 32 keeps a single chunk (the
    configuration refuses sequence buckets below 64)."""
    kc = min(S, kmax)
    kc -= kc % 32 if kc > 32 else 0
    if S > 32:
        # largest even-count chunk <= kmax; else (a small debug cap, e.g. 256 at S = 32 x 145) the largest <= 512
        cands = list(range(kc, 31, -32)) + list(range(min(S, 512) - min(S, 512) % 32, kc, -32))
        kc = next((k for k in cands if -(-S // k) % 2 == 0), kc)
    return kc


def bucket_of(n: int, buckets: Sequence[int]) -> int:
    for b in sorted(buckets):
        if n <= b:
            return b
    raise ValueError("%d exceeds the largest bucket %d" % (n, max(buckets)))


class TtnnEngine:
    name = "ttnn"

    def __init__(self, device, sd: Dict, arch: Arch, batch_buckets=(1, 2, 4, 8, 16, 32),
                 seq_buckets=(64, 128, 256, 512), trace: bool = True, fidelity: str = "HiFi4",
                 weight_dtype: str = "bf16", rope: str = "fp32", sdpa: str = ""):
        import torch
        import ttnn

        self.device, self.a = device, arch
        traces.invalidate(device)   # this engine's weights must not sit under another engine's trace
        self.batch_buckets = tuple(sorted(int(b) for b in batch_buckets))
        self.seq_buckets = tuple(sorted(int(s) for s in seq_buckets))
        for s in self.seq_buckets:
            if s % 32:
                raise ValueError("sequence bucket %d: multiples of 32" % s)
        self.trace = bool(trace)
        fid = {"HiFi4": ttnn.MathFidelity.HiFi4, "HiFi3": ttnn.MathFidelity.HiFi3,
               "HiFi2": ttnn.MathFidelity.HiFi2, "LoFi": ttnn.MathFidelity.LoFi}[fidelity]
        self.fidelity = fidelity
        self.ckc = ttnn.init_device_compute_kernel_config(device.arch(), math_fidelity=fid, math_approx_mode=False,
                                                          fp32_dest_acc_en=True, packer_l1_acc=True)
        self.ckc4 = 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)
        wdt = {"bf16": ttnn.bfloat16, "bfp8": ttnn.bfloat8_b}[weight_dtype]
        if rope not in ("fp32", "hf"):
            raise ValueError("rope: fp32 | hf")
        # "fp32": RoPE on the float32 q / k accumulators, rotate_half folded into a second weight (exact in bf16):
        #   qkv' = (y @ Wqkv) * cos + (y @ Wrot) * sin, cos / sin float32 tables (v columns: 1 / 0).
        # "hf": ttnn.experimental.rotary_embedding_hf on bf16 q / k with bf16 tables (faster, less exact).
        self.rope = rope
        self.sdpa = sdpa   # "" = the chunks below; "default" = the op's own config; "<q>,<k>" = chunk caps (debug)
        self.weight_dtype = weight_dtype
        dram = ttnn.DRAM_MEMORY_CONFIG
        a, W = arch, {k: v.float() for k, v in sd.items()}
        D, I = a.hidden, a.inter

        def mat(t, dt=None):   # torch [out, in] -> ttnn [in, out]
            return ttnn.from_torch(t.t().contiguous(), dtype=dt or wdt, layout=ttnn.TILE_LAYOUT, device=device,
                                   memory_config=dram)

        def vec(t, dt=None):
            return ttnn.from_torch(t.reshape(1, -1).contiguous(), dtype=dt or ttnn.float32, layout=ttnn.TILE_LAYOUT,
                                   device=device, memory_config=dram)

        # the fp16 table as hi + lo bf16 tables (ttnn.embedding takes bf16 only): exact for fp16 values
        tab = W["encoder.embeddings.tok_embeddings.weight"].contiguous()
        hi = tab.to(torch.bfloat16)
        lo = (tab - hi.float()).to(torch.bfloat16)
        self.emb = [ttnn.from_torch(t, dtype=ttnn.bfloat16, layout=ttnn.ROW_MAJOR_LAYOUT, device=device,
                                    memory_config=dram) for t in (hi, lo)]
        self.g_emb = vec(W["encoder.embeddings.norm.weight"])
        self.g_final = vec(W["encoder.final_norm.weight"])
        self.layers = []
        for l in range(a.layers):
            p = "encoder.layers.%d." % l
            wi = W[p + "mlp.Wi.weight"]
            wqkv = W[p + "attn.Wqkv.weight"]
            rot = None
            if rope == "fp32":
                r = torch.zeros_like(wqkv)
                h = a.head_dim // 2
                for c0 in range(0, 2 * D, a.head_dim):      # q and k heads: rotate_half on the output rows
                    r[c0:c0 + h] = -wqkv[c0 + h:c0 + 2 * h]
                    r[c0 + h:c0 + 2 * h] = wqkv[c0:c0 + h]
                rot = mat(r)
            self.layers.append({"wrot": rot,
                "g1": None if l == 0 else vec(W[p + "attn_norm.weight"]),
                "wqkv": mat(W[p + "attn.Wqkv.weight"]), "wo": mat(W[p + "attn.Wo.weight"]),
                "g2": vec(W[p + "mlp_norm.weight"]),
                "wu": mat(wi[:I]), "wg": mat(wi[I:]), "wo2": mat(W[p + "mlp.Wo.weight"]),
                "global": a.is_global(l)})
        self.head = []
        for i in range(a.head_layers):
            p = "head.layers.%d." % i
            self.head.append({
                "n1w": vec(W[p + "norm1.weight"]), "n1b": vec(W[p + "norm1.bias"]),
                "win": mat(W[p + "self_attn.in_proj_weight"]), "bin": vec(W[p + "self_attn.in_proj_bias"], ttnn.bfloat16),
                "wout": mat(W[p + "self_attn.out_proj.weight"]), "bout": vec(W[p + "self_attn.out_proj.bias"]),
                "n2w": vec(W[p + "norm2.weight"]), "n2b": vec(W[p + "norm2.bias"]),
                "w1": mat(W[p + "linear1.weight"]), "b1": vec(W[p + "linear1.bias"], ttnn.bfloat16),
                "w2": mat(W[p + "linear2.weight"]), "b2": vec(W[p + "linear2.bias"])})
        self.type_emb = W["type_emb.weight"].numpy().astype(np.float32)
        self.s_lnw, self.s_lnb = vec(W["scorer.0.weight"]), vec(W["scorer.0.bias"])
        self.s_w1, self.s_b1 = mat(W["scorer.1.weight"]), vec(W["scorer.1.bias"], ttnn.bfloat16)
        w3 = torch.zeros(32, D)
        w3[0] = W["scorer.3.weight"][0]
        b3 = torch.zeros(32)
        b3[0] = W["scorer.3.bias"][0]
        self.s_w3, self.s_b3 = mat(w3, ttnn.bfloat16), vec(b3)
        aw = W["act_head.0.weight"]
        self.act_wp = mat(aw[:, :D], ttnn.bfloat16)              # pooled part on the device
        self.act_wf = aw[:, D:].numpy().astype(np.float32)      # 4 features on the host
        self.act_b0 = W["act_head.0.bias"].numpy().astype(np.float32)
        self.act_w2 = W["act_head.2.weight"].numpy().astype(np.float32)
        self.act_b2 = W["act_head.2.bias"].numpy().astype(np.float32)
        self.pad_id = 0
        self._rope: Dict[Tuple[int, float], tuple] = {}
        self._band: Dict[int, object] = {}
        self._sdpa: Dict[int, object] = {}
        self._io: Dict[Tuple[int, int], dict] = {}
        self.timings: Dict[str, float] = {}
        traces.register(device, self)

    # ------------------------------------------------------------------ constants per length
    def _rope_tables(self, S: int, theta: float):
        import torch
        import ttnn

        key = (S, theta)
        if key not in self._rope:
            hd = self.a.head_dim
            inv = 1.0 / (theta ** (torch.arange(0, hd, 2, dtype=torch.float32) / hd))
            fr = torch.arange(S, dtype=torch.float32)[:, None] * inv[None]
            emb = torch.cat([fr, fr], -1)
            mk = lambda t: ttnn.from_torch(t.reshape(1, 1, S, hd), dtype=ttnn.bfloat16, layout=ttnn.TILE_LAYOUT,
                                           device=self.device, memory_config=ttnn.DRAM_MEMORY_CONFIG)
            if self.rope == "fp32":   # [1, S, 3D] float32: q and k columns per head, v columns cos 1 / sin 0
                D = self.a.hidden
                c = torch.ones(S, 3 * D)
                s = torch.zeros(S, 3 * D)
                c[:, :2 * D] = emb.cos().repeat(1, 2 * D // hd)
                s[:, :2 * D] = emb.sin().repeat(1, 2 * D // hd)
                mk = lambda t: ttnn.from_torch(t.reshape(1, S, 3 * D), dtype=ttnn.float32,  # noqa: E731
                                               layout=ttnn.TILE_LAYOUT, device=self.device,
                                               memory_config=ttnn.DRAM_MEMORY_CONFIG)
                self._rope[key] = (mk(c), mk(s))
            else:
                self._rope[key] = (mk(emb.cos()), mk(emb.sin()))
        return self._rope[key]

    def _band_mask(self, S: int):
        import torch
        import ttnn

        if S not in self._band:
            i = torch.arange(S)
            m = torch.where((i[:, None] - i[None, :]).abs() > self.a.window, MASK_NEG, 0.0)
            self._band[S] = ttnn.from_torch(m.reshape(1, 1, S, S), dtype=ttnn.bfloat16, layout=ttnn.TILE_LAYOUT,
                                            device=self.device, memory_config=ttnn.DRAM_MEMORY_CONFIG)
        return self._band[S]

    # ------------------------------------------------------------------ graph
    def _sdpa_config(self, S: int):
        """SDPA chunks: the op keeps its running output / max in bf16 and rescales them once per key chunk (default
        chunks: 32 keys -> S / 32 bf16 rescales). Key chunks of up to 512 and exact exp keep the long rows close to
        float32 (english 1024-token rows: max |dlogit| 0.087 with the defaults).

        The key chunk is chosen by ``sdpa_key_chunk``: an EVEN number of key chunks. With an odd count the op returns
        wrong attention for some (batch, head) units -- e.g. k 1024 at S 1024 (one chunk): batch slots 5-7 of an
        8 x 1024 launch with 12 heads (mmBERT) wrong and run-to-run different, q 64 / k 1024 inf (F8,
        research/laya/tools/dev_f8_localize.py); S 1216 at k 512 (three chunks) likewise (logs/sdpa_audit). Every
        slot of every batch size is gated (scripts/eval_gates.py --slots)."""
        import ttnn

        if S not in self._sdpa:
            if self.sdpa == "default":
                self._sdpa[S] = None
            else:
                if self.sdpa:
                    qmax, kmax = (int(v) for v in self.sdpa.split("/"))
                    kc, qc = sdpa_key_chunk(S, kmax), min(S, qmax)
                else:
                    kc, qc = sdpa_key_chunk(S), min(S, 64)
                self._sdpa[S] = ttnn.SDPAProgramConfig(
                    compute_with_storage_grid_size=self.device.compute_with_storage_grid_size(),
                    q_chunk_size=qc, k_chunk_size=kc, exp_approx_mode=False)
        return self._sdpa[S]

    def _attn(self, q, k, v, mask):
        import ttnn

        return ttnn.transformer.scaled_dot_product_attention(
            q, k, v, attn_mask=mask, is_causal=False, scale=1.0 / math.sqrt(self.a.head_dim),
            program_config=self._sdpa_config(int(q.shape[2])), compute_kernel_config=self.ckc4,
            output_concat_heads=True)

    def _tap(self, name, t):
        """Debug: with ``self._taps`` a dict (eager runs only), keep a host copy of an intermediate tensor."""
        if getattr(self, "_taps", None) is not None:
            import ttnn

            self._taps[name] = ttnn.to_torch(t).float()

    def _forward(self, io):
        import ttnn

        a, ck = self.a, self.ckc
        B, S = io["B"], io["S"]
        H, hd, D = a.heads, a.head_dim, a.hidden
        eps = a.norm_eps
        bf, f32 = ttnn.bfloat16, ttnn.float32
        e = ttnn.add(ttnn.embedding(io["ids"], self.emb[0], layout=ttnn.TILE_LAYOUT, dtype=f32),
                     ttnn.embedding(io["ids"], self.emb[1], layout=ttnn.TILE_LAYOUT, dtype=f32), dtype=f32)
        x = ttnn.layer_norm(e, epsilon=eps, weight=self.g_emb, compute_kernel_config=self.ckc4)
        ttnn.deallocate(e)
        self._tap("emb", x)
        mask_g = io["padb"]                                               # [B, 1, S, S] key padding
        mask_l = ttnn.add(io["padb"], self._band_mask(S), dtype=bf)       # + band
        rope_g = self._rope_tables(S, a.theta_global)
        rope_l = self._rope_tables(S, a.theta_local)
        for l, L in enumerate(self.layers):
            y = x if L["g1"] is None else ttnn.layer_norm(x, epsilon=eps, weight=L["g1"], compute_kernel_config=self.ckc4)
            yb = ttnn.typecast(y, bf)
            if L["g1"] is not None:
                ttnn.deallocate(y)
            cos, sin = rope_g if L["global"] else rope_l
            if self.rope == "fp32":
                qkv = ttnn.linear(yb, L["wqkv"], compute_kernel_config=ck, dtype=f32)
                qr = ttnn.linear(yb, L["wrot"], compute_kernel_config=ck, dtype=f32)
                ttnn.deallocate(yb)
                t1 = ttnn.multiply(qkv, cos, dtype=f32)
                ttnn.deallocate(qkv)
                t2 = ttnn.multiply(qr, sin, dtype=f32)
                ttnn.deallocate(qr)
                if l == 0:
                    self._tap("l0.t1", t1)
                    self._tap("l0.t2", t2)
                qkv = ttnn.add(t1, t2, dtype=bf)
                ttnn.deallocate(t1)
                ttnn.deallocate(t2)
                if l == 0:
                    self._tap("l0.qkv", qkv)
                q2, k2, v = ttnn.transformer.split_query_key_value_and_split_heads(qkv, num_heads=H,
                                                                                   transpose_key=False)
                ttnn.deallocate(qkv)
            else:
                qkv = ttnn.linear(yb, L["wqkv"], compute_kernel_config=ck, dtype=bf)
                ttnn.deallocate(yb)
                q, k, v = ttnn.transformer.split_query_key_value_and_split_heads(qkv, num_heads=H,
                                                                                 transpose_key=False)
                ttnn.deallocate(qkv)
                q2 = ttnn.experimental.rotary_embedding_hf(ttnn.reshape(q, (1, B * H, S, hd)), cos, sin)
                k2 = ttnn.experimental.rotary_embedding_hf(ttnn.reshape(k, (1, B * H, S, hd)), cos, sin)
                ttnn.deallocate(q)
                ttnn.deallocate(k)
            if l == 0:
                self._tap("l0.q", q2)
                self._tap("l0.k", k2)
                self._tap("l0.v", v)
            ctx = self._attn(ttnn.reshape(q2, (B, H, S, hd)), ttnn.reshape(k2, (B, H, S, hd)), v,
                             mask_g if L["global"] else mask_l)
            if l in (0, 1):
                self._tap("l%d.ctx" % l, ctx)
            ttnn.deallocate(q2)
            ttnn.deallocate(k2)
            ttnn.deallocate(v)
            o = ttnn.linear(ttnn.reshape(ctx, (B, S, D)), L["wo"], compute_kernel_config=ck, dtype=f32)
            ttnn.deallocate(ctx)
            x = ttnn.add(x, o, dtype=f32)
            ttnn.deallocate(o)
            y = ttnn.layer_norm(x, epsilon=eps, weight=L["g2"], compute_kernel_config=self.ckc4)
            yb = ttnn.typecast(y, bf)
            ttnn.deallocate(y)
            u = ttnn.linear(yb, L["wu"], compute_kernel_config=ck, dtype=f32)
            g = ttnn.linear(yb, L["wg"], compute_kernel_config=ck, dtype=f32)
            ttnn.deallocate(yb)
            u = ttnn.gelu(u, fast_and_approximate_mode=False)
            m = ttnn.multiply(u, g, dtype=bf)
            ttnn.deallocate(u)
            ttnn.deallocate(g)
            o = ttnn.linear(m, L["wo2"], compute_kernel_config=ck, dtype=f32)
            ttnn.deallocate(m)
            x = ttnn.add(x, o, dtype=f32)
            ttnn.deallocate(o)
            self._tap("x%02d" % l, x)
        h = ttnn.layer_norm(x, epsilon=eps, weight=self.g_final, compute_kernel_config=self.ckc4)
        ttnn.deallocate(x)
        h = ttnn.add(h, io["te"], dtype=f32)                     # + type embedding (row broadcast)
        for i, L in enumerate(self.head):
            y = ttnn.layer_norm(h, epsilon=1e-5, weight=L["n1w"], bias=L["n1b"], compute_kernel_config=self.ckc4)
            yb = ttnn.typecast(y, bf)
            ttnn.deallocate(y)
            qkv = ttnn.linear(yb, L["win"], bias=L["bin"], compute_kernel_config=ck, dtype=bf)
            ttnn.deallocate(yb)
            q, k, v = ttnn.transformer.split_query_key_value_and_split_heads(qkv, num_heads=H, transpose_key=False)
            ttnn.deallocate(qkv)
            ctx = self._attn(q, k, v, mask_g)
            ttnn.deallocate(q)
            ttnn.deallocate(k)
            ttnn.deallocate(v)
            o = ttnn.linear(ttnn.reshape(ctx, (B, S, D)), L["wout"], bias=L["bout"], compute_kernel_config=ck,
                            dtype=f32)
            ttnn.deallocate(ctx)
            h = ttnn.add(h, o, dtype=f32)
            ttnn.deallocate(o)
            y = ttnn.layer_norm(h, epsilon=1e-5, weight=L["n2w"], bias=L["n2b"], compute_kernel_config=self.ckc4)
            yb = ttnn.typecast(y, bf)
            ttnn.deallocate(y)
            f = ttnn.linear(yb, L["w1"], bias=L["b1"], activation="relu", compute_kernel_config=ck, dtype=bf)
            ttnn.deallocate(yb)
            o = ttnn.linear(f, L["w2"], bias=L["b2"], compute_kernel_config=ck, dtype=f32)
            ttnn.deallocate(f)
            h = ttnn.add(h, o, dtype=f32)
            ttnn.deallocate(o)
        ttnn.deallocate(mask_l)
        m = ttnn.matmul(io["sel"], h, compute_kernel_config=self.ckc4, dtype=f32)      # [B, 32, D]
        ttnn.deallocate(h)
        y = ttnn.layer_norm(m, epsilon=1e-5, weight=self.s_lnw, bias=self.s_lnb, compute_kernel_config=self.ckc4)
        yb = ttnn.typecast(y, bf)
        ttnn.deallocate(y)
        z = ttnn.linear(yb, self.s_w1, bias=self.s_b1, compute_kernel_config=self.ckc4, dtype=f32)
        ttnn.deallocate(yb)
        z = ttnn.gelu(z, fast_and_approximate_mode=False)
        zb = ttnn.typecast(z, bf)
        ttnn.deallocate(z)
        logits = ttnn.linear(zb, self.s_w3, bias=self.s_b3, compute_kernel_config=self.ckc4, dtype=f32)
        ttnn.deallocate(zb)
        mb = ttnn.typecast(m, bf)
        ttnn.deallocate(m)
        actp = ttnn.matmul(mb, self.act_wp, compute_kernel_config=self.ckc4, dtype=f32)
        ttnn.deallocate(mb)
        return logits, actp

    # ------------------------------------------------------------------ buckets
    def _get(self, B: int, S: int) -> dict:
        import torch
        import ttnn

        key = (B, S)
        if key in self._io:
            io = self._io[key]
            if self.trace and io["tid"] is None:
                self._capture(io)   # released by traces.invalidate
            return io
        # new persistent buffers (inputs, RoPE tables, band mask): no trace may replay over them
        traces.invalidate(self.device)
        dev, dram = self.device, ttnn.DRAM_MEMORY_CONFIG
        D = self.a.hidden
        io = {"B": B, "S": S,
              "ids": ttnn.from_torch(torch.zeros(B, S, dtype=torch.int32), dtype=ttnn.uint32,
                                     layout=ttnn.ROW_MAJOR_LAYOUT, device=dev, memory_config=dram),
              "padb": ttnn.from_torch(torch.zeros(B, 1, S, S), dtype=ttnn.bfloat16, layout=ttnn.TILE_LAYOUT,
                                      device=dev, memory_config=dram),
              "te": ttnn.from_torch(torch.zeros(B, 1, D), dtype=ttnn.float32, layout=ttnn.TILE_LAYOUT, device=dev,
                                    memory_config=dram),
              "sel": ttnn.from_torch(torch.zeros(B, SEL_ROWS, S), dtype=ttnn.bfloat16, layout=ttnn.TILE_LAYOUT,
                                     device=dev, memory_config=dram)}
        t0 = time.perf_counter()
        io["out"] = self._forward(io)       # compile (eager)
        ttnn.synchronize_device(dev)
        io["compile_s"] = time.perf_counter() - t0
        io["tid"] = None
        if self.trace:
            self._capture(io)
        self._io[key] = io
        return io

    def _capture(self, io: dict) -> None:
        import ttnn

        for t in io["out"]:
            ttnn.deallocate(t)
        tid = ttnn.begin_trace_capture(self.device, cq_id=0)
        io["out"] = self._forward(io)
        ttnn.end_trace_capture(self.device, tid, cq_id=0)
        io["tid"] = tid

    def drop_traces(self) -> bool:
        """Release every bucket's trace (another allocation follows); each is captured again at its next launch."""
        import ttnn

        had = False
        for io in self._io.values():
            if io.get("tid") is not None:
                ttnn.release_trace(self.device, io["tid"])
                io["tid"] = None
                had = True
        return had

    def warm(self, buckets: Optional[Sequence[Tuple[int, int]]] = None) -> Dict[str, float]:
        out = {}
        for B in self.batch_buckets:
            for S in self.seq_buckets:
                if buckets is not None and (B, S) not in buckets:
                    continue
                out["%dx%d" % (B, S)] = self._get(B, S)["compile_s"]
        return out

    # ------------------------------------------------------------------ run
    def host_inputs(self, rows):
        n = len(rows)
        B = bucket_of(n, self.batch_buckets)
        S = bucket_of(max(len(r.ids) for r in rows), self.seq_buckets)
        import torch

        ids = np.zeros((B, S), dtype=np.int32)
        # bf16 torch tensors built in place (a host fp32 -> bf16 conversion of [B, 1, S, S] costs ~3.5 ms per
        # million entries)
        padb = torch.full((B, 1, S, S), MASK_NEG, dtype=torch.bfloat16)
        te = np.zeros((B, 1, self.a.hidden), dtype=np.float32)
        sel = torch.zeros((B, SEL_ROWS, S), dtype=torch.bfloat16)
        for b, r in enumerate(rows):
            L = len(r.ids)
            ids[b, :L] = r.ids
            padb[b, :, :, :L] = 0.0
            te[b, 0] = self.type_emb[r.qtype]
            if len(r.markers) + 1 > SEL_ROWS:
                raise ValueError("%d options: the ttnn engine gathers at most %d" % (len(r.markers), SEL_ROWS - 1))
            sel[b, 0, 0] = 1.0
            for j, m in enumerate(r.markers):
                sel[b, 1 + j, m] = 1.0
        padb[n:, :, :, 0] = 0.0
        return B, S, ids, padb, te, sel

    def run(self, rows) -> Tuple[List[np.ndarray], List[np.ndarray]]:
        """text.Row list -> (raw logits [K] per row, act probabilities [n_act] per row). More rows than the largest
        batch bucket run as several calls of rows of similar length."""
        import torch
        import ttnn

        bmax = max(self.batch_buckets)
        if len(rows) > bmax:
            order = sorted(range(len(rows)), key=lambda i: len(rows[i].ids))
            logits, acts = [None] * len(rows), [None] * len(rows)
            for c in range(0, len(order), bmax):
                idx = order[c:c + bmax]
                l, a = self.run([rows[i] for i in idx])
                for j, i in enumerate(idx):
                    logits[i], acts[i] = l[j], a[j]
            return logits, acts
        B, S, ids, padb, te, sel = self.host_inputs(rows)
        io = self._get(B, S)
        up = ttnn.copy_host_to_device_tensor
        up(ttnn.from_torch(torch.from_numpy(ids), dtype=ttnn.uint32, layout=ttnn.ROW_MAJOR_LAYOUT), io["ids"])
        up(ttnn.from_torch(padb, dtype=ttnn.bfloat16, layout=ttnn.TILE_LAYOUT), io["padb"])
        up(ttnn.from_torch(torch.from_numpy(te), dtype=ttnn.float32, layout=ttnn.TILE_LAYOUT), io["te"])
        up(ttnn.from_torch(sel, dtype=ttnn.bfloat16, layout=ttnn.TILE_LAYOUT), io["sel"])
        if io["tid"] is not None:
            ttnn.execute_trace(self.device, io["tid"], cq_id=0, blocking=False)
        else:
            io["out"] = self._forward(io)
        lg = ttnn.to_torch(io["out"][0]).float().numpy()
        ap = ttnn.to_torch(io["out"][1]).float().numpy()
        logits, acts = [], []
        for b, r in enumerate(rows):
            K = len(r.markers)
            l = lg[b, 1:1 + K, 0].astype(np.float32)
            logits.append(l)
            acts.append(self.finish_act(ap[b, 0], l))
        return logits, acts

    def bench_device(self, rows, n: int = 20) -> float:
        """Device time per call (ms): the bucket's trace replayed n times back to back."""
        import ttnn

        self.run(rows)
        B, S, *_ = self.host_inputs(rows)
        io = self._get(B, S)
        t0 = time.perf_counter()
        for _ in range(n):
            ttnn.execute_trace(self.device, io["tid"], cq_id=0, blocking=False)
        ttnn.synchronize_device(self.device)
        return (time.perf_counter() - t0) * 1e3 / n

    def finish_act(self, pooled_proj: np.ndarray, logits: np.ndarray) -> np.ndarray:
        """Host half of the action head: features of the raw answer distribution + the 256 -> n_act layer."""
        return finish_act(pooled_proj, logits, self.act_wf, self.act_b0, self.act_w2, self.act_b2)

    def describe(self):
        return {"engine": "ttnn", "fidelity": self.fidelity, "weights": self.weight_dtype,
                "batch_buckets": list(self.batch_buckets), "seq_buckets": list(self.seq_buckets),
                "trace": self.trace, "compiled": sorted("%dx%d" % k for k in self._io)}

    def close(self):
        import ttnn

        for io in self._io.values():
            if io.get("tid") is not None:
                try:
                    ttnn.release_trace(self.device, io["tid"])
                except Exception:  # noqa: BLE001
                    pass
        self._io.clear()


def _gelu(x: np.ndarray) -> np.ndarray:
    from math import erf, sqrt

    v = np.vectorize(lambda t: 0.5 * t * (1.0 + erf(t / sqrt(2.0))), otypes=[np.float64])
    return v(x.astype(np.float64)).astype(np.float32)


def finish_act(pooled_proj, logits, wf, b0, w2, b2) -> np.ndarray:
    K = len(logits)
    z = logits.astype(np.float64)
    p = np.exp(z - z.max())
    p /= p.sum()
    k = float(max(K, 2))
    ent = -(p * np.log(np.clip(p, 1e-9, None))).sum() / math.log(k)
    top = np.sort(p)[::-1]
    t1 = top[0]
    t2 = top[1] if K >= 2 else 0.0
    feats = np.array([t1, t1 - t2, ent, k / 255.0], dtype=np.float32)
    hid = _gelu(pooled_proj + wf @ feats + b0)
    a = w2 @ hid + b2
    a = np.exp(a - a.max())
    return (a / a.sum()).astype(np.float32)