File size: 24,139 Bytes
53ce2f5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
# Copyright (c) 2026 Philip Bartsch (@batteryphil).
# Licensed under the Bartsch Personal-Free & 5% Commercial Profit-Share License v1.0 (see LICENSE).
"""
Exact Fused Triton Decode Kernels for `thinkingmachines/Inkling-2-Mini`
=======================================================================
Eliminates the `~43 ms/tok` non-quantized PyTorch/rocBLAS overhead inside `Inkling-2-Mini`'s
48-pass looped decode step while preserving 100% exact mathematical parity with Hugging Face
`transformers.models.inkling2_loop.modeling_inkling2_loop`:

  1. `short_conv1d_step_res_triton`       (176 calls/tok): in-place 4-tap conv state shift + residual / sqrt(5)
  2. `dyn_short_conv1d_step_res_triton`   ( 16 calls/tok): dynamic + static 4-tap conv state shift + residual / 3
  3. `message_gate_triton`                ( 96 calls/tok): 2-kernel fused RMSNorm + rank-64 tanh forget/message gate
  4. `attn_res_step_triton`               (120 calls/tok): 2-kernel fused Block & Message Attention Residuals (zero rocBLAS)
  5. `dense_gemv_triton`                  (112 calls/tok): fast M=1 FP32/BF16 GEMV for TopKRouter, sink_proj, weight_proj
  6. `inkling2_decode_attn_triton`        ( 48 calls/tok): fused GQA + RelativePositionBias + Per-Head Sink + Ring-Buffer
                                                           Sliding Window / Full Attention (supports 1K..32K+ context in
                                                           one single HIP/CUDA Graph with zero per-token KV cache roll!)
"""

from __future__ import annotations

import math
from typing import Optional

import torch
import triton
import triton.language as tl


@triton.jit
def _short_conv1d_step_res_kernel(
    x_ptr,
    state_ptr,
    w_ptr,
    out_ptr,
    C,
    INV_SCALE: tl.constexpr,
    BLOCK_C: tl.constexpr,
):
    """In-place 4-tap static depthwise causal conv1d update + residual / sqrt(5) for B=1, T=1."""
    pid = tl.program_id(0)
    c = pid * BLOCK_C + tl.arange(0, BLOCK_C)
    m = c < C

    x_f = tl.load(x_ptr + c, mask=m, other=0.0).to(tl.float32)
    base = c * 4
    s0 = tl.load(state_ptr + base + 1, mask=m, other=0.0).to(tl.float32)
    s1 = tl.load(state_ptr + base + 2, mask=m, other=0.0).to(tl.float32)
    s2 = tl.load(state_ptr + base + 3, mask=m, other=0.0).to(tl.float32)
    s3 = x_f

    tl.store(state_ptr + base + 0, s0.to(state_ptr.dtype.element_ty), mask=m)
    tl.store(state_ptr + base + 1, s1.to(state_ptr.dtype.element_ty), mask=m)
    tl.store(state_ptr + base + 2, s2.to(state_ptr.dtype.element_ty), mask=m)
    tl.store(state_ptr + base + 3, s3.to(state_ptr.dtype.element_ty), mask=m)

    w0 = tl.load(w_ptr + base + 0, mask=m, other=0.0).to(tl.float32)
    w1 = tl.load(w_ptr + base + 1, mask=m, other=0.0).to(tl.float32)
    w2 = tl.load(w_ptr + base + 2, mask=m, other=0.0).to(tl.float32)
    w3 = tl.load(w_ptr + base + 3, mask=m, other=0.0).to(tl.float32)

    dot = s0 * w0 + s1 * w1 + s2 * w2 + s3 * w3
    out = (dot + x_f) * INV_SCALE
    tl.store(out_ptr + c, out.to(out_ptr.dtype.element_ty), mask=m)


@triton.jit
def _dyn_short_conv1d_step_res_kernel(
    x_ptr,
    state_ptr,
    static_w_ptr,  # [4, C] row-major: lag 0 = current token, lag 3 = oldest
    dyn_w_ptr,     # [num_heads, 4] row-major
    out_ptr,
    C,
    HEAD_DIM: tl.constexpr,
    INV_SCALE: tl.constexpr,
    BLOCK_C: tl.constexpr,
):
    """In-place 4-tap dynamic+static causal conv1d update + residual / sqrt(9) for B=1, T=1."""
    pid = tl.program_id(0)
    c = pid * BLOCK_C + tl.arange(0, BLOCK_C)
    m = c < C
    h = c // HEAD_DIM

    x_f = tl.load(x_ptr + c, mask=m, other=0.0).to(tl.float32)
    base = c * 4
    s0 = tl.load(state_ptr + base + 1, mask=m, other=0.0).to(tl.float32)  # lag 3 (oldest)
    s1 = tl.load(state_ptr + base + 2, mask=m, other=0.0).to(tl.float32)  # lag 2
    s2 = tl.load(state_ptr + base + 3, mask=m, other=0.0).to(tl.float32)  # lag 1
    s3 = x_f                                                               # lag 0 (current)

    tl.store(state_ptr + base + 0, s0.to(state_ptr.dtype.element_ty), mask=m)
    tl.store(state_ptr + base + 1, s1.to(state_ptr.dtype.element_ty), mask=m)
    tl.store(state_ptr + base + 2, s2.to(state_ptr.dtype.element_ty), mask=m)
    tl.store(state_ptr + base + 3, s3.to(state_ptr.dtype.element_ty), mask=m)

    # static_w[lag, c] + dyn_w[h, lag] where lag 0 multiplies s3 (current) and lag 3 multiplies s0 (oldest)
    w_lag0 = tl.load(static_w_ptr + 0 * C + c, mask=m, other=0.0).to(tl.float32) + tl.load(dyn_w_ptr + h * 4 + 0, mask=m, other=0.0).to(tl.float32)
    w_lag1 = tl.load(static_w_ptr + 1 * C + c, mask=m, other=0.0).to(tl.float32) + tl.load(dyn_w_ptr + h * 4 + 1, mask=m, other=0.0).to(tl.float32)
    w_lag2 = tl.load(static_w_ptr + 2 * C + c, mask=m, other=0.0).to(tl.float32) + tl.load(dyn_w_ptr + h * 4 + 2, mask=m, other=0.0).to(tl.float32)
    w_lag3 = tl.load(static_w_ptr + 3 * C + c, mask=m, other=0.0).to(tl.float32) + tl.load(dyn_w_ptr + h * 4 + 3, mask=m, other=0.0).to(tl.float32)

    dot = s3 * w_lag0 + s2 * w_lag1 + s1 * w_lag2 + s0 * w_lag3
    out = (dot + x_f) * INV_SCALE
    tl.store(out_ptr + c, out.to(out_ptr.dtype.element_ty), mask=m)


@triton.jit
def _dense_gemv_kernel(
    x_ptr,
    w_ptr,
    out_ptr,
    rows,
    cols,
    BLOCK_R: tl.constexpr,
    BLOCK_K: tl.constexpr,
):
    """Coalesced FP32/BF16 M=1 GEMV (y = W @ x) bypassing slow rocBLAS small-M Tensile kernels."""
    pid = tl.program_id(0)
    r = pid * BLOCK_R + tl.arange(0, BLOCK_R)
    r_mask = r < rows
    r_i64 = r.to(tl.int64)
    acc = tl.zeros((BLOCK_R,), dtype=tl.float32)
    k_offs = tl.arange(0, BLOCK_K)
    for k0 in range(0, cols, BLOCK_K):
        k = k0 + k_offs
        k_mask = k < cols
        xv = tl.load(x_ptr + k, mask=k_mask, other=0.0).to(tl.float32)
        wv = tl.load(w_ptr + r_i64[:, None] * cols + k[None, :], mask=r_mask[:, None] & k_mask[None, :], other=0.0).to(tl.float32)
        acc += tl.sum(wv * xv[None, :], axis=1)
    tl.store(out_ptr + r, acc.to(out_ptr.dtype.element_ty), mask=r_mask)


@triton.jit
def _msg_gate_stage1_kernel(
    h_ptr,
    m_ptr,
    wdn_ptr,  # [R=64, 2*H] bf16/fp32
    g_ptr,    # [R=64] fp32
    R,
    H,
    eps,
    BLOCK_R: tl.constexpr,
    BLOCK_K: tl.constexpr,
):
    """Fused RMSNorm(h), RMSNorm(m), and down_proj -> g[64] in fp32 (exact cast parity with wdn.dtype)."""
    pid = tl.program_id(0)
    r = pid * BLOCK_R + tl.arange(0, BLOCK_R)
    r_mask = r < R
    r_i64 = r.to(tl.int64)
    k_offs = tl.arange(0, BLOCK_K)

    ss_h = 0.0
    ss_m = 0.0
    for k0 in range(0, H, BLOCK_K):
        k = k0 + k_offs
        km = k < H
        hv = tl.load(h_ptr + k, mask=km, other=0.0).to(tl.float32)
        mv = tl.load(m_ptr + k, mask=km, other=0.0).to(tl.float32)
        ss_h += tl.sum(hv * hv, axis=0)
        ss_m += tl.sum(mv * mv, axis=0)
    inv_h = tl.rsqrt(ss_h / H + eps)
    inv_m = tl.rsqrt(ss_m / H + eps)

    acc = tl.zeros((BLOCK_R,), dtype=tl.float32)
    stride_r = 2 * H
    for k0 in range(0, H, BLOCK_K):
        k = k0 + k_offs
        km = k < H
        hv = tl.load(h_ptr + k, mask=km, other=0.0).to(tl.float32)
        mv = tl.load(m_ptr + k, mask=km, other=0.0).to(tl.float32)
        # Match upstream `gate_hidden_states.to(self.down_proj.weight.dtype)` rounding
        hn = (hv * inv_h).to(wdn_ptr.dtype.element_ty).to(tl.float32)
        mn = (mv * inv_m).to(wdn_ptr.dtype.element_ty).to(tl.float32)
        w0 = tl.load(wdn_ptr + r_i64[:, None] * stride_r + k[None, :], mask=r_mask[:, None] & km[None, :], other=0.0).to(tl.float32)
        w1 = tl.load(wdn_ptr + r_i64[:, None] * stride_r + (H + k)[None, :], mask=r_mask[:, None] & km[None, :], other=0.0).to(tl.float32)
        acc += tl.sum(w0 * hn[None, :] + w1 * mn[None, :], axis=1)
    tl.store(g_ptr + r, acc, mask=r_mask)


@triton.jit
def _msg_gate_stage2_kernel(
    h_ptr,
    m_ptr,
    g_ptr,    # [R=64] fp32
    wfg_ptr,  # [H, R=64] fp32
    wmg_ptr,  # [H, R=64] fp32
    out_ptr,  # [H] fp32
    H,
    R: tl.constexpr,
    BLOCK_H: tl.constexpr,
):
    """Fused tanh(w_fg @ g), tanh(w_mg @ g), and (1 - fg) * h + mg * m -> fp32."""
    pid = tl.program_id(0)
    h_idx = pid * BLOCK_H + tl.arange(0, BLOCK_H)
    hm = h_idx < H
    h_i64 = h_idx.to(tl.int64)

    r_offs = tl.arange(0, R)
    gv = tl.load(g_ptr + r_offs).to(tl.float32)

    off = h_i64[:, None] * R + r_offs[None, :]
    wfg = tl.load(wfg_ptr + off, mask=hm[:, None], other=0.0).to(tl.float32)
    wmg = tl.load(wmg_ptr + off, mask=hm[:, None], other=0.0).to(tl.float32)

    fg_pre = tl.sum(wfg * gv[None, :], axis=1)
    mg_pre = tl.sum(wmg * gv[None, :], axis=1)
    fg = 2.0 * tl.sigmoid(2.0 * fg_pre) - 1.0
    mg = 2.0 * tl.sigmoid(2.0 * mg_pre) - 1.0

    hv = tl.load(h_ptr + h_idx, mask=hm, other=0.0).to(tl.float32)
    mv = tl.load(m_ptr + h_idx, mask=hm, other=0.0).to(tl.float32)
    out = (1.0 - fg) * hv + mg * mv
    tl.store(out_ptr + h_idx, out, mask=hm)


@triton.jit
def _attn_res_stage1_kernel(
    bs_ptr,      # [S_prev, H]
    part_ptr,    # [H]
    q_ptr,       # [Q, H] fp32
    inv_rms_ptr, # [S] fp32
    scores_ptr,  # [Q, S] fp32
    S_prev,
    H,
    Q,
    Q_PAD: tl.constexpr,
    BLOCK_K: tl.constexpr,
):
    """Single-pass AttnRes stage 1: computes inv_rms[s] and (q @ v) * inv_rms / sqrt(H) in ONE pass over H."""
    s = tl.program_id(0)
    is_part = s == S_prev
    s_i64 = s.to(tl.int64)
    k_offs = tl.arange(0, BLOCK_K)
    q_offs = tl.arange(0, Q_PAD)
    qm = q_offs < Q
    q_i64 = q_offs.to(tl.int64)

    ss = 0.0
    acc = tl.zeros((Q_PAD,), dtype=tl.float32)
    for k0 in range(0, H, BLOCK_K):
        k = k0 + k_offs
        km = k < H
        if is_part:
            v = tl.load(part_ptr + k, mask=km, other=0.0).to(tl.float32)
        else:
            v = tl.load(bs_ptr + s_i64 * H + k, mask=km, other=0.0).to(tl.float32)
        ss += tl.sum(v * v, axis=0)
        qv = tl.load(q_ptr + q_i64[:, None] * H + k[None, :], mask=qm[:, None] & km[None, :], other=0.0).to(tl.float32)
        acc += tl.sum(qv * v[None, :], axis=1)

    inv_r = tl.rsqrt(ss / H + 1.0e-6)
    tl.store(inv_rms_ptr + s, inv_r)
    scale = inv_r * tl.rsqrt(tl.cast(H, tl.float32))
    S_tot = S_prev + 1
    tl.store(scores_ptr + q_i64 * S_tot + s, acc * scale, mask=qm)


@triton.jit
def _router_topk_kernel(
    logits_ptr,
    bias_ptr,
    out_w_ptr,
    out_idx_ptr,
    scale,
    E: tl.constexpr,
    TOP_K: tl.constexpr,
):
    """Single-CTA fused sigmoid + bias + top-K + gather + normalize * scale (4.25x faster than 4 PyTorch kernels)."""
    offs = tl.arange(0, E)
    logits = tl.load(logits_ptr + offs).to(tl.float32)
    bias = tl.load(bias_ptr + offs).to(tl.float32)
    scores = tl.sigmoid(logits)
    biased = scores + bias

    w_sum = 0.0
    for k in tl.static_range(0, TOP_K):
        idx = tl.argmax(biased, axis=0)
        w_k = tl.sum(tl.where(offs == idx, scores, 0.0), axis=0)
        w_sum += w_k
        tl.store(out_idx_ptr + k, idx.to(tl.int64))
        tl.store(out_w_ptr + k, w_k)
        biased = tl.where(offs == idx, -1.0e30, biased)

    inv_sum = scale / (w_sum + 1.0e-20)
    k_offs = tl.arange(0, TOP_K)
    wk_all = tl.load(out_w_ptr + k_offs) * inv_sum
    tl.store(out_w_ptr + k_offs, wk_all)


@triton.jit
def _unweighted_rmsnorm_kernel(
    x_ptr,
    out_ptr,
    eps,
    D: tl.constexpr,
):
    """Single-kernel unweighted RMSNorm along last dim D (power-of-2; 8x faster than 4-op eager path)."""
    row = tl.program_id(0).to(tl.int64)
    d = tl.arange(0, D)
    xv = tl.load(x_ptr + row * D + d).to(tl.float32)
    inv_r = tl.rsqrt(tl.sum(xv * xv, axis=0) / D + eps)
    tl.store(out_ptr + row * D + d, (xv * inv_r).to(out_ptr.dtype.element_ty))


@triton.jit
def _attn_res_stage2_kernel(
    bs_ptr,      # [S_prev, H]
    part_ptr,    # [H]
    inv_rms_ptr, # [S] fp32
    scores_ptr,  # [Q, S] fp32
    out_ptr,     # [Q, H] fp32
    S_prev,
    H,
    Q,
    Q_PAD: tl.constexpr,
    S_PAD: tl.constexpr,
    BLOCK_H: tl.constexpr,
):
    """Applies exact softmax over S states and accumulates weighted normalized states -> [Q, H] fp32."""
    pid = tl.program_id(0)
    h = pid * BLOCK_H + tl.arange(0, BLOCK_H)
    hm = h < H
    h_i64 = h.to(tl.int64)

    S_tot = S_prev + 1
    s_offs = tl.arange(0, S_PAD)
    s_mask = s_offs < S_tot
    q_offs = tl.arange(0, Q_PAD)
    qm = q_offs < Q
    q_i64 = q_offs.to(tl.int64)

    # Load scores [Q_PAD, S_PAD] and compute softmax over axis=1
    sc = tl.load(
        scores_ptr + q_i64[:, None] * S_tot + s_offs[None, :],
        mask=qm[:, None] & s_mask[None, :],
        other=-1.0e9,
    )
    sc_max = tl.max(sc, axis=1)[:, None]
    ex = tl.where(s_mask[None, :], tl.exp(sc - sc_max), 0.0)
    w = ex / tl.sum(ex, axis=1)[:, None]  # [Q_PAD, S_PAD]

    inv_r = tl.load(inv_rms_ptr + s_offs, mask=s_mask, other=0.0)  # [S_PAD]
    w_eff = w * inv_r[None, :]  # [Q_PAD, S_PAD]

    acc = tl.zeros((Q_PAD, BLOCK_H), dtype=tl.float32)
    for s in range(0, S_tot):
        if s == S_prev:
            v = tl.load(part_ptr + h, mask=hm, other=0.0).to(tl.float32)
        else:
            v = tl.load(bs_ptr + tl.cast(s, tl.int64) * H + h, mask=hm, other=0.0).to(tl.float32)
        ws = tl.sum(tl.where(s_offs[None, :] == s, w_eff, 0.0), axis=1)  # [Q_PAD]
        acc += ws[:, None] * v[None, :]

    tl.store(out_ptr + q_i64[:, None] * H + h_i64[None, :], acc, mask=qm[:, None] & hm[None, :])


@triton.jit
def _kv_cache_write_kernel(
    k_new_ptr,    # [H_kv, D]
    v_new_ptr,    # [H_kv, D]
    k_cache_ptr,  # [H_kv, L, D]
    v_cache_ptr,  # [H_kv, L, D]
    cur_pos_ptr,  # [1] int64
    L,
    IS_SLIDING: tl.constexpr,
    SLIDING_MASK: tl.constexpr,
    D: tl.constexpr,
):
    """Writes single-token K/V into StaticCache at `pos` (full) or `pos & (W-1)` (ring-buffer sliding)."""
    h = tl.program_id(0)
    d = tl.arange(0, D)
    pos = tl.load(cur_pos_ptr).to(tl.int64)
    slot = (pos & SLIDING_MASK) if IS_SLIDING else pos

    src_off = h.to(tl.int64) * D + d
    dst_off = (h.to(tl.int64) * L + slot) * D + d
    tl.store(k_cache_ptr + dst_off, tl.load(k_new_ptr + src_off))
    tl.store(v_cache_ptr + dst_off, tl.load(v_new_ptr + src_off))


@triton.jit
def _inkling2_decode_attn_kernel(
    q_ptr,          # [H_q, D] bf16
    k_cache_ptr,    # [H_kv, L, D] bf16
    v_cache_ptr,    # [H_kv, L, D] bf16
    rel_s_ptr,      # [H_q, D_REL] bf16
    rel_p_ptr,      # [D_REL, REL_EXTENT] bf16
    sinks_ptr,      # [H_q] bf16
    cur_pos_ptr,    # [1] int64
    out_ptr,        # [H_q, D] bf16
    L,
    scaling,
    GQA_GROUPS: tl.constexpr,
    IS_SLIDING: tl.constexpr,
    SLIDING_WIN: tl.constexpr,
    REL_EXTENT: tl.constexpr,
    D: tl.constexpr,
    D_REL: tl.constexpr,
    BLOCK_N: tl.constexpr,
):
    """
    Exact fused GQA + RelativePositionBias + Per-Head Sink + Ring-Buffer Sliding/Full Decode Attention.
    Zero `repeat_kv`, zero `[H_q, L]` materialization, dynamic loop bound `j0 < n_valid` inside CUDA Graph.
    """
    h = tl.program_id(0)
    kv_h = h // GQA_GROUPS
    d = tl.arange(0, D)
    r_idx = tl.arange(0, D_REL)

    q = tl.load(q_ptr + h.to(tl.int64) * D + d).to(tl.float32) * scaling
    rs = tl.load(rel_s_ptr + h.to(tl.int64) * D_REL + r_idx).to(tl.float32)
    sink = tl.load(sinks_ptr + h).to(tl.float32)
    cur_pos = tl.load(cur_pos_ptr).to(tl.int32)

    n_valid = tl.minimum(cur_pos + 1, SLIDING_WIN) if IS_SLIDING else (cur_pos + 1)

    # Exact attention sink initialization: one extra logit `sink` with zero value vector
    m_i = sink
    l_i = 1.0
    acc = tl.zeros((D,), dtype=tl.float32)

    kv_base = kv_h.to(tl.int64) * L * D
    n_offs = tl.arange(0, BLOCK_N)
    j0 = 0
    while j0 < n_valid:
        j = j0 + n_offs
        j_mask = j < n_valid
        j_i64 = j.to(tl.int64)

        kv_off = kv_base + j_i64[:, None] * D + d[None, :]
        k_tile = tl.load(k_cache_ptr + kv_off, mask=j_mask[:, None], other=0.0).to(tl.float32)
        scores = tl.sum(k_tile * q[None, :], axis=1)

        if IS_SLIDING:
            dist = (cur_pos - j) & (SLIDING_WIN - 1)
        else:
            dist = cur_pos - j
        in_rel = j_mask & (dist >= 0) & (dist < REL_EXTENT)
        dist_safe = tl.where(in_rel, dist, 0).to(tl.int64)

        rp_off = r_idx[:, None].to(tl.int64) * REL_EXTENT + dist_safe[None, :]
        rp_tile = tl.load(rel_p_ptr + rp_off, mask=in_rel[None, :], other=0.0).to(tl.float32)
        bias = tl.sum(rp_tile * rs[:, None], axis=0)
        scores = scores + tl.where(in_rel, bias, 0.0)
        scores = tl.where(j_mask, scores, -1.0e9)

        m_blk = tl.max(scores, axis=0)
        m_new = tl.maximum(m_i, m_blk)
        alpha = tl.exp(m_i - m_new)
        p = tl.where(j_mask, tl.exp(scores - m_new), 0.0)
        l_i = l_i * alpha + tl.sum(p, axis=0)

        v_tile = tl.load(v_cache_ptr + kv_off, mask=j_mask[:, None], other=0.0).to(tl.float32)
        acc = acc * alpha + tl.sum(p[:, None] * v_tile, axis=0)
        m_i = m_new
        j0 += BLOCK_N

    out = acc / l_i
    tl.store(out_ptr + h.to(tl.int64) * D + d, out.to(out_ptr.dtype.element_ty))


def short_conv1d_step_res_triton(
    x: torch.Tensor,
    conv_state: torch.Tensor,
    weight_2d: torch.Tensor,
) -> torch.Tensor:
    """Fast Triton 4-tap static short conv update + residual / sqrt(5) for `[1, 1, C]` decode."""
    C = x.shape[-1]
    out = torch.empty_like(x)
    BLOCK_C = 256
    _short_conv1d_step_res_kernel[(triton.cdiv(C, BLOCK_C),)](
        x.contiguous(),
        conv_state,
        weight_2d.contiguous(),
        out,
        C,
        INV_SCALE=1.0 / math.sqrt(5.0),
        BLOCK_C=BLOCK_C,
        num_warps=4,
    )
    return out


def dense_gemv_triton(x_1d: torch.Tensor, weight_2d: torch.Tensor, out_dtype: Optional[torch.dtype] = None) -> torch.Tensor:
    """Fast coalesced M=1 Triton GEMV for small/medium FP32/BF16 linear layers."""
    rows, cols = weight_2d.shape
    dt = out_dtype if out_dtype is not None else x_1d.dtype
    out = torch.empty((rows,), device=weight_2d.device, dtype=dt)
    BLOCK_R = 4 if rows <= 128 else 8
    _dense_gemv_kernel[(triton.cdiv(rows, BLOCK_R),)](
        x_1d.contiguous(),
        weight_2d.contiguous(),
        out,
        rows,
        cols,
        BLOCK_R=BLOCK_R,
        BLOCK_K=256,
        num_warps=4,
    )
    return out


def dyn_short_conv1d_step_res_triton(
    x: torch.Tensor,
    dynamic_input: torch.Tensor,
    conv_state: torch.Tensor,
    static_weight: torch.Tensor,
    weight_proj_w: torch.Tensor,
    num_heads: int,
) -> torch.Tensor:
    """Fast Triton 4-tap dynamic+static short conv update + residual / 3 for `[1, 1, C]` decode."""
    C = x.shape[-1]
    dyn_w = dense_gemv_triton(dynamic_input.view(-1), weight_proj_w, out_dtype=torch.float32)
    out = torch.empty_like(x)
    BLOCK_C = 256
    _dyn_short_conv1d_step_res_kernel[(triton.cdiv(C, BLOCK_C),)](
        x.contiguous(),
        conv_state,
        static_weight.contiguous(),
        dyn_w,
        out,
        C,
        HEAD_DIM=C // num_heads,
        INV_SCALE=1.0 / 3.0,
        BLOCK_C=BLOCK_C,
        num_warps=4,
    )
    return out


def message_gate_triton(
    h: torch.Tensor,
    m: torch.Tensor,
    w_dn: torch.Tensor,
    w_fg: torch.Tensor,
    w_mg: torch.Tensor,
    eps: float,
) -> torch.Tensor:
    """Exact 2-kernel fused Triton Inkling2LoopMessageGate for `B*T == 1` (returns fp32 `[1, 1, H]`)."""
    R, two_H = w_dn.shape
    H = two_H // 2
    g = torch.empty((R,), device=h.device, dtype=torch.float32)
    BLOCK_R = 2
    _msg_gate_stage1_kernel[(triton.cdiv(R, BLOCK_R),)](
        h.contiguous(),
        m.contiguous(),
        w_dn.contiguous(),
        g,
        R,
        H,
        eps,
        BLOCK_R=BLOCK_R,
        BLOCK_K=512,
        num_warps=2,
    )
    out = torch.empty(h.shape, device=h.device, dtype=torch.float32)
    BLOCK_H = 32
    _msg_gate_stage2_kernel[(triton.cdiv(H, BLOCK_H),)](
        h.contiguous(),
        m.contiguous(),
        g,
        w_fg.contiguous(),
        w_mg.contiguous(),
        out,
        H,
        R=R,
        BLOCK_H=BLOCK_H,
        num_warps=4,
    )
    return out


def router_topk_triton(
    logits: torch.Tensor,
    bias: torch.Tensor,
    top_k: int,
    scale: float,
) -> tuple[torch.Tensor, torch.Tensor]:
    """Single-CTA fused sigmoid + bias + top-K + gather + normalize * scale for `B*T == 1`."""
    E = int(bias.shape[-1])
    w_out = torch.empty((1, top_k), device=logits.device, dtype=torch.float32)
    i_out = torch.empty((1, top_k), device=logits.device, dtype=torch.long)
    _router_topk_kernel[(1,)](
        logits.contiguous(),
        bias.contiguous(),
        w_out,
        i_out,
        float(scale),
        E=E,
        TOP_K=int(top_k),
        num_warps=2,
    )
    return w_out, i_out


def unweighted_rmsnorm_triton(x: torch.Tensor, eps: float) -> torch.Tensor:
    """Single-kernel unweighted RMSNorm along last dim D (power-of-2; 8x faster than eager)."""
    D = int(x.shape[-1])
    x_c = x.contiguous()
    out = torch.empty_like(x_c)
    n_rows = x_c.numel() // D
    _unweighted_rmsnorm_kernel[(n_rows,)](x_c, out, float(eps), D=D, num_warps=2)
    return out


def attn_res_step_triton(
    block_states: torch.Tensor,
    partial: torch.Tensor,
    query: torch.Tensor,
) -> torch.Tensor:
    """Exact 2-kernel fused Triton Block/Message Attention Residual for `B=1, T=1` -> `[1, 1, Q, H]` fp32."""
    S_prev = int(block_states.shape[-2])
    H = int(partial.shape[-1])
    q_2d = query.view(-1, H).contiguous()
    Q = int(q_2d.shape[0])
    Q_PAD = 1 << (Q - 1).bit_length()
    S_tot = S_prev + 1
    S_PAD = 1 << (S_tot - 1).bit_length()
    if S_PAD < 2:
        S_PAD = 2

    inv_rms = torch.empty((S_tot,), device=partial.device, dtype=torch.float32)
    scores = torch.empty((Q, S_tot), device=partial.device, dtype=torch.float32)
    bs_c = block_states.contiguous()
    p_c = partial.contiguous()
    _attn_res_stage1_kernel[(S_tot,)](
        bs_c,
        p_c,
        q_2d,
        inv_rms,
        scores,
        S_prev,
        H,
        Q,
        Q_PAD=Q_PAD,
        BLOCK_K=512,
        num_warps=4,
    )
    out = torch.empty((1, 1, Q, H), device=partial.device, dtype=torch.float32)
    BLOCK_H = 64
    _attn_res_stage2_kernel[(triton.cdiv(H, BLOCK_H),)](
        bs_c,
        p_c,
        inv_rms,
        scores,
        out,
        S_prev,
        H,
        Q,
        Q_PAD=Q_PAD,
        S_PAD=S_PAD,
        BLOCK_H=BLOCK_H,
        num_warps=2,
    )
    return out


def inkling2_decode_attn_triton(
    q: torch.Tensor,          # [1, 24, 1, 128]
    k_new: torch.Tensor,      # [1, 8, 1, 128]
    v_new: torch.Tensor,      # [1, 8, 1, 128]
    k_cache: torch.Tensor,    # [1, 8, L, 128]
    v_cache: torch.Tensor,    # [1, 8, L, 128]
    rel_states: torch.Tensor, # [1, 1, 24, 16]
    rel_proj: torch.Tensor,   # [16, 1024]
    sinks: torch.Tensor,      # [1, 24, 1, 1] or [24]
    cur_pos: torch.Tensor,    # [1] int64
    scaling: float,
    is_sliding: bool,
    sliding_window: int = 1024,
    rel_extent: int = 1024,
) -> torch.Tensor:
    """Writes single-token K/V into cache and runs exact fused GQA+RelBias+Sink attention -> `[1, 1, 24, 128]`."""
    H_q = int(q.shape[1])
    H_kv = int(k_cache.shape[1])
    L = int(k_cache.shape[2])
    D = int(q.shape[-1])
    D_rel = int(rel_states.shape[-1])

    _kv_cache_write_kernel[(H_kv,)](
        k_new.contiguous(),
        v_new.contiguous(),
        k_cache,
        v_cache,
        cur_pos,
        L,
        IS_SLIDING=is_sliding,
        SLIDING_MASK=sliding_window - 1,
        D=D,
        num_warps=2,
    )

    out = torch.empty((1, 1, H_q, D), device=q.device, dtype=q.dtype)
    _inkling2_decode_attn_kernel[(H_q,)](
        q.contiguous(),
        k_cache,
        v_cache,
        rel_states.contiguous(),
        rel_proj.contiguous(),
        sinks.contiguous(),
        cur_pos,
        out,
        L,
        scaling,
        GQA_GROUPS=H_q // H_kv,
        IS_SLIDING=is_sliding,
        SLIDING_WIN=sliding_window,
        REL_EXTENT=rel_extent,
        D=D,
        D_REL=D_rel,
        BLOCK_N=64,
        num_warps=4,
    )
    return out