Skip to content

GLM-5.3-Flash EXL3 on 2x DGX Spark with TensorFold

Python
32.2 KB
Raw Blame
diff --git tensorfold/families/glm5_next/cuda/forward.py tensorfold/families/glm5_next/cuda/forward.py
index 98ed9e6..c1fb8ce 100644
--- tensorfold/families/glm5_next/cuda/forward.py
+++ tensorfold/families/glm5_next/cuda/forward.py
@@ -285,7 +285,7 @@ def kda_block(layer: LayerW, w: Weights, st: State, b: Buffers, R: int) -> torch
     with prof.timed("kda: recurrence"):
         out = kda_mod.chain(p, k.b_off, b.ka[:R], b.kg[:R], st.conv[li], k.conv, st.rec[cur, li], k.a_log,
                             k.dt_bias, k.norm, c.eps, c.lower, R, b.kscratch if pre else st.scratch[li],
-                            st.rec[1 - cur, li])
+                            st.rec[1 - cur, li], pos=st.pos if pre else None)
     if pre:                              # a prompt chunk keeps every row: the layer commits now
         st.cur[li] = 1 - cur
         _shift_conv(st.conv[li:li + 1], b.kproj[:, :R], R)
diff --git tensorfold/families/glm5_next/cuda/kda.py tensorfold/families/glm5_next/cuda/kda.py
index b4a8a60..9975ab1 100644
--- tensorfold/families/glm5_next/cuda/kda.py
+++ tensorfold/families/glm5_next/cuda/kda.py
@@ -2,6 +2,7 @@
 
 from __future__ import annotations
 
+import os
 from functools import lru_cache
 from pathlib import Path
 
@@ -56,6 +57,8 @@ def replay_layers(state_in: torch.Tensor, scratch: KDAScratchSet, rows: int, sta
 
 
 WIDE_ROWS = 64          # windows of this many rows or more (prefill chunks) run the chain in three kernels
+# prompt chunks in chunked (WY) form, 64-row sub-chunks at absolute positions (kda_chunked.py): close, not the same bits
+CHUNKED = os.environ.get("TF_GLM_KDA_CHUNKED", "0") == "1"
 _tmp: dict = {}
 
 
@@ -73,9 +76,14 @@ def _wide_scratch(rows: int, heads: int, device) -> tuple[torch.Tensor, torch.Te
 def chain(p: torch.Tensor, b_off: int, a: torch.Tensor, g: torch.Tensor, conv_state: torch.Tensor,
           conv_w: torch.Tensor, state_in: torch.Tensor, a_log: torch.Tensor, dt_bias: torch.Tensor,
           norm_w: torch.Tensor, eps: float, lower: float, rows: int, scratch: KDAScratch,
-          state_out: torch.Tensor, *, wide: bool | None = None) -> torch.Tensor:
-    """Run projection rows p [q | k | v | ... | b at b_off ...] and bf16 gate rows a and g; windows of WIDE_ROWS rows or more take the three-kernel path, same bits."""
+          state_out: torch.Tensor, *, wide: bool | None = None, pos: int | None = None) -> torch.Tensor:
+    """Run projection rows p [q | k | v | ... | b at b_off ...] and bf16 gate rows a and g; windows of WIDE_ROWS rows or more take the three-kernel path, same bits; a prompt chunk (``pos``: its first row's position) takes the chunked form under TF_GLM_KDA_CHUNKED=1 (scratch's k/v/g/b are not written)."""
 
+    if CHUNKED and pos is not None:
+        from . import kda_chunked
+
+        return kda_chunked.chain(p, b_off, a, g, conv_state, conv_w, state_in, a_log, dt_bias, norm_w, eps, lower,
+                                 rows, scratch.out, state_out, pos)
     if wide if wide is not None else rows >= WIDE_ROWS:
         q_tmp, y_tmp = _wide_scratch(rows, a_log.numel(), p.device)
         _ext().chain_wide(p, p.stride(0), int(b_off), a, a.stride(0), g, g.stride(0), conv_state, conv_w, state_in,
diff --git tensorfold/families/glm5_next/cuda/kda_chunked.py tensorfold/families/glm5_next/cuda/kda_chunked.py
new file mode 100644
index 0000000..0ee9823
--- /dev/null
+++ tensorfold/families/glm5_next/cuda/kda_chunked.py
@@ -0,0 +1,574 @@
+"""GLM-5.3-Flash's KDA prompt chunks in chunked (WY) form: sub-chunks of 64 rows at absolute positions, the
+intra-chunk part as matmuls, the 128 x 128 state carried from sub-chunk to sub-chunk.
+
+Per row the definition is kda.cu's (conv + SiLU rounded to bf16, fp32 L2 norms, q times 128^-0.5, beta =
+bf16(sigmoid(b)), log-decay l = lower * sigmoid(exp(A_log) * (a + dt_bias)) per key channel, the delta rule
+S <- S diag(e^l); S <- S + beta (v - S k) k^T; o = S q, o rounded to bf16, then the gated RMSNorm). The state S is
+[value, key] as in kda.cu.
+
+Sub-chunk of rows 0..63 (T = 64), entering state S0, G = cumsum(l) within the sub-chunk (per key channel, <= 0 and
+decreasing: every l is in (lower, 0) = (-5, 0)):
+
+    L[s, j]  = beta_s sum_c k_s[c] k_j[c] e^(G_s[c] - G_j[c])      j < s          (strictly lower)
+    M[s, j]  =        sum_c q_s[c] k_j[c] e^(G_s[c] - G_j[c])      j <= s
+    T        = (I + L)^-1                                           (unit lower triangular)
+    W        = T (beta * k * e^G),   U = T (beta * v)               the WY / UT transform
+    V'       = U - W S0^T                                           the corrected values ("v_new")
+    O        = (q * e^G) S0^T + M V'
+    S_end    = S0 diag(e^G_63) + V'^T (k * e^(G_63 - G))
+
+Every exponent above is <= 0 except inside L and M, which are formed as matmuls of row and column factors about a
+reference point: for the rows of 16-row block b, R = G at the block's first row; row factor e^(G_s - R) in
+[e^-75, 1] (15 steps of at most 5), column factor e^(R - G_j) <= 1 for earlier blocks and <= e^75 inside the block
+(< fp32's e^88.7); only blocks j <= b are formed. Their products are true decays (<= 1). T is inverted per 16-row
+diagonal block by forward substitution, then block rows are joined with matmuls (T_bj = -T_bb sum L_bm T_mj).
+Everything is fp32; the matmuls take tl.dot's ``input_precision`` (TF_GLM_KDA_PREC, default tf32x3, about fp32:
+~2e-6 relative against float64; "tf32" is faster and ~5e-4, half a bf16 step).
+
+Kernels (``chain``): _kda_lm (sub-chunk, head, block): the conv, norms, beta and decays of its rows, L and M rows,
+q e^G; _kda_solve (sub-chunk, head): T and the sub-chunk's total log-decay; _kda_wu (sub-chunk, head, block): W, U
+and the keys decayed to the sub-chunk's end; _kda_state (head, 16 value rows): the only sequential part, sub-chunk
+after sub-chunk, V' and the state entering each sub-chunk; _kda_out (sub-chunk, head): O, bf16, the gated RMSNorm.
+q, k, v, G are recomputed from the projection rows where needed rather than kept (registers) or stored (traffic).
+
+Sub-chunks start at absolute positions that are multiples of 64 (``pos`` gives the first row's position); a
+prompt chunk that starts mid-sub-chunk takes a short first sub-chunk (padded rows are zero rows: no decay, no
+key). A row's output depends only on its sub-chunk's rows and the state entering it, so it is the same whichever
+prefill chunk it came in, as long as chunk boundaries are multiples of 64 (a short last sub-chunk included).
+
+The torch functions (``*_reference``) are the CPU references of the tests; ``chain`` runs the Triton kernels.
+"""
+
+from __future__ import annotations
+
+import math
+import os
+
+import torch
+import triton
+import triton.language as tl
+
+DK = DV = 128
+TAPS = 4
+CHUNK = 64              # rows of a sub-chunk (the state is carried between sub-chunks)
+BLOCK = 16              # rows of a reference block inside a sub-chunk (16 x 5 = 80 < 88: no fp32 overflow)
+SCALE = 1.0 / math.sqrt(DK)
+
+
+# -- references (torch, CPU or GPU) ----------------------------------------------------------------------------
+def _bf(x: torch.Tensor) -> torch.Tensor:
+    return x.to(torch.bfloat16).to(x.dtype)
+
+
+def _sigmoid(x: torch.Tensor) -> torch.Tensor:
+    return 1.0 / (1.0 + torch.exp(-x))
+
+
+def prep_reference(p: torch.Tensor, b_off: int, a: torch.Tensor, conv_state: torch.Tensor, conv_w: torch.Tensor,
+                   a_log: torch.Tensor, dt_bias: torch.Tensor, lower: float, rows: int):
+    """kda.cu's per-row work in fp32: q, k [rows, H, 128] normalized (q scaled), v [rows, H, 128] (bf16 values),
+    the log-decay l [rows, H, 128] (kda.cu's decay is e^l) and beta [rows, H]."""
+
+    H = a_log.numel()
+    C = 3 * H * DK
+    x = torch.cat([conv_state.float(), p[:rows, :C].float()])
+    w = conv_w.float()
+    acc = torch.zeros((rows, C), dtype=torch.float32, device=p.device)
+    for tap in range(TAPS):
+        acc = acc + w[:, tap] * x[tap:tap + rows]
+    act = _bf(acc / (1.0 + torch.exp(-acc))).view(rows, 3, H, DK)
+
+    def l2(t: torch.Tensor) -> torch.Tensor:
+        return t * (1.0 / torch.sqrt((t * t).sum(-1, keepdim=True) + 1e-6))
+
+    q = l2(act[:, 0]) * torch.tensor(SCALE, dtype=torch.float32)
+    k = l2(act[:, 1])
+    v = act[:, 2].contiguous()
+    rate = torch.exp(a_log.float()).view(1, H, 1)
+    ga = a[:rows].float().view(rows, H, DK) + dt_bias.float().view(1, H, DK)
+    lg = torch.tensor(lower, dtype=torch.float32) * _sigmoid(rate * ga)
+    beta = _bf(_sigmoid(p[:rows, b_off:b_off + H].float()))
+    return q, k, v, lg, beta
+
+
+def recurrent_reference(q, k, v, lg, beta, state, dtype=torch.float64):
+    """The delta rule row by row (kda.cu's chain): read-outs [rows, H, 128] and the final state [H, 128, 128]."""
+
+    q, k, v, beta = (t.to(dtype) for t in (q, k, v, beta))
+    g = torch.exp(lg.to(dtype))
+    S = state.to(dtype).clone()
+    out = torch.empty(v.shape, dtype=dtype, device=v.device)
+    for r in range(q.shape[0]):
+        S = S * g[r][:, None, :]
+        kv = (S * k[r][:, None, :]).sum(-1)
+        delta = (v[r] - kv) * beta[r][:, None]
+        S = S + delta[:, :, None] * k[r][:, None, :]
+        out[r] = (S * q[r][:, None, :]).sum(-1)
+    return out, S
+
+
+def tf32(x: torch.Tensor) -> torch.Tensor:
+    """fp32 -> TF32 (10 mantissa bits, round to nearest, ties away: cvt.rna.tf32.f32), as fp32."""
+
+    i = x.float().contiguous().view(torch.int32)
+    return ((i + 0x1000) & ~0x1FFF).view(torch.float32)
+
+
+def _tri_inverse(Ld: torch.Tensor) -> torch.Tensor:
+    """(I + Ld)^-1 for strictly lower Ld [..., n, n], by forward substitution a row at a time."""
+
+    n = Ld.shape[-1]
+    T = torch.eye(n, dtype=Ld.dtype, device=Ld.device).expand(Ld.shape).clone()
+    for s in range(1, n):
+        T[..., s, :] = -(Ld[..., s, :, None] * T).sum(-2)
+        T[..., s, s] = 1.0
+    return T
+
+
+def chunked_reference(q, k, v, lg, beta, state, pos: int = 0, dtype=torch.float64, mm_round=None, state_round=...):
+    """The chunked algorithm as the kernels run it (sub-chunks at absolute positions, reference blocks, the block
+    triangular inverse): read-outs [rows, H, 128] and the final state. ``mm_round`` rounds matmul inputs (``tf32``
+    emulates tl.dot's TF32 path), ``state_round`` those of the products with the state (default: ``mm_round``)."""
+
+    rows, H, _ = q.shape
+    dev = q.device
+    off = pos % CHUNK
+    nc = -(-(rows + off) // CHUNK)
+    total = nc * CHUNK
+
+    def pad(t):
+        t = t.to(dtype)
+        z = torch.zeros((total,) + tuple(t.shape[1:]), dtype=dtype, device=dev)
+        z[off:off + rows] = t
+        return z.view((nc, CHUNK) + tuple(t.shape[1:])).transpose(1, 2)     # [nc, H, 64, ...]
+
+    qc, kc, vc, lc, bc = pad(q), pad(k), pad(v), pad(lg), pad(beta)
+    rnd = mm_round or (lambda x: x)
+    srnd = rnd if state_round is ... else (state_round or (lambda x: x))
+
+    def mm(x, y):
+        return rnd(x) @ rnd(y)
+
+    def mms(x, y):
+        return srnd(x) @ srnd(y)
+
+    t = torch.arange(CHUNK, device=dev)
+    lower_strict = t[:, None] > t[None, :]
+    lower_incl = t[:, None] >= t[None, :]
+    nb = CHUNK // BLOCK
+    S = state.to(dtype).clone()                     # [H, V, K]
+    out = torch.empty((total, H, DV), dtype=dtype, device=dev)
+    for c in range(nc):
+        qx, kx, vx, lx, bx = qc[c], kc[c], vc[c], lc[c], bc[c]     # [H, 64, 128] (beta [H, 64])
+        G = torch.cumsum(lx, dim=1)
+        Akk = torch.zeros((H, CHUNK, CHUNK), dtype=dtype, device=dev)
+        Aqk = torch.zeros_like(Akk)
+        for b in range(nb):
+            rs = slice(b * BLOCK, (b + 1) * BLOCK)
+            R = G[:, b * BLOCK][:, None, :]
+            rf = torch.exp(G[:, rs] - R)
+            cols = (t < (b + 1) * BLOCK)[None, :, None]
+            cf = torch.where(cols, torch.exp(torch.where(cols, R - G, torch.zeros_like(G))), torch.zeros_like(G))
+            kt = (kx * cf).transpose(1, 2)
+            Akk[:, rs] = mm(kx[:, rs] * rf, kt)
+            Aqk[:, rs] = mm(qx[:, rs] * rf, kt)
+        L = torch.where(lower_strict, bx[:, :, None] * Akk, torch.zeros_like(Akk))
+        M = torch.where(lower_incl, Aqk, torch.zeros_like(Aqk))
+        T = torch.zeros_like(L)
+        for b in range(nb):
+            rs = slice(b * BLOCK, (b + 1) * BLOCK)
+            Tbb = _tri_inverse(L[:, rs, rs])
+            X = mm(L[:, rs, :b * BLOCK], T[:, :b * BLOCK, :]) if b else torch.zeros_like(T[:, rs])
+            T[:, rs] = -mm(Tbb, X)
+            T[:, rs, rs] = Tbb
+        eG = torch.exp(G)
+        W = mm(T, bx[:, :, None] * kx * eG)
+        U = mm(T, bx[:, :, None] * vx)
+        gl = G[:, -1:, :]
+        Ke = kx * torch.exp(gl - G)
+        Qt = qx * eG
+        ST = S.transpose(1, 2)                                      # [H, K, V]
+        Vn = U - mms(W, ST)
+        out[c * CHUNK:(c + 1) * CHUNK] = (mms(Qt, ST) + mm(M, Vn)).transpose(0, 1)
+        S = S * torch.exp(gl) + mms(Vn.transpose(1, 2), Ke)
+    return out[off:off + rows], S
+
+
+def gate_norm_reference(y: torch.Tensor, gate: torch.Tensor, norm_w: torch.Tensor, eps: float) -> torch.Tensor:
+    """kda.cu's gated RMSNorm of bf16 read-outs y [rows, H, 128] with gate rows [rows, H * 128]: bf16 [rows, H*128]."""
+
+    rows, H, _ = y.shape
+    yb = _bf(y.float())
+    rinv = 1.0 / torch.sqrt((yb * yb).sum(-1, keepdim=True) / DV + eps)
+    yw = norm_w.float() * (yb * rinv)
+    return (yw * _sigmoid(gate[:rows].float().view(rows, H, DV))).to(torch.bfloat16).view(rows, H * DV)
+
+
+def chain_reference(p, b_off, a, g, conv_state, conv_w, state_in, a_log, dt_bias, norm_w, eps, lower, rows, *,
+                    pos: int = 0, chunked: bool = True, dtype=torch.float32, mm_round=None):
+    """A whole prompt chunk: (out bf16 [rows, H * 128], final state fp32 [H, 128, 128], read-outs y [rows, H, 128])."""
+
+    q, k, v, lg, beta = prep_reference(p, b_off, a, conv_state, conv_w, a_log, dt_bias, lower, rows)
+    if chunked:
+        y, S = chunked_reference(q, k, v, lg, beta, state_in, pos, dtype=dtype, mm_round=mm_round)
+    else:
+        y, S = recurrent_reference(q, k, v, lg, beta, state_in, dtype=dtype)
+    return gate_norm_reference(y, g, norm_w, eps), S.float(), y
+
+
+# -- Triton kernels ---------------------------------------------------------------------------------------------
[email protected]
+def _bf16(x):
+    """fp32 rounded to bf16 (to nearest even), as fp32: bit arithmetic, so Triton's CPU interpreter (which truncates
+    in casts) rounds as the GPU does."""
+    b = x.to(tl.uint32, bitcast=True)
+    b = (b + 0x7FFF + ((b >> 16) & 1)) & 0xFFFF0000
+    return b.to(tl.float32, bitcast=True)
+
+
[email protected]
+def _conv_act(P, p_stride, CS, CW, r, valid, ch, C3, BT: tl.constexpr, DK_: tl.constexpr, TAPS_: tl.constexpr):
+    """Depthwise conv over [conv state; P rows] of channels ch for rows r, SiLU, rounded to bf16: [BT, DK] fp32."""
+
+    acc = tl.zeros((BT, DK_), dtype=tl.float32)
+    for tap in tl.static_range(TAPS_):
+        at = r + (tap - (TAPS_ - 1))                        # P row (negative: conv state row at + TAPS - 1)
+        from_p = valid & (at >= 0)
+        from_s = valid & (at < 0)
+        xp = tl.load(P + at.to(tl.int64)[:, None] * p_stride + ch[None, :], mask=from_p[:, None], other=0.0)
+        xs = tl.load(CS + (at + (TAPS_ - 1)).to(tl.int64)[:, None] * C3 + ch[None, :], mask=from_s[:, None],
+                     other=0.0)
+        x = tl.where(from_s[:, None], xs.to(tl.float32), xp.to(tl.float32))
+        wt = tl.load(CW + ch * TAPS_ + tap).to(tl.float32)
+        acc = acc + wt[None, :] * x
+    act = acc / (1.0 + tl.exp(-acc))
+    return _bf16(act)
+
+
[email protected]
+def _l2(x):
+    ss = tl.sum(x * x, axis=1)
+    return x * (1.0 / tl.sqrt_rn(ss + 1e-6))[:, None]
+
+
[email protected]
+def _row(x, t, s):
+    """Row s of x [n, N] as [N] (a sum with zeros: exact)."""
+    return tl.sum(tl.where((t == s)[:, None], x, 0.0), axis=0)
+
+
[email protected]
+def _tri_inv(Ld, BC: tl.constexpr):
+    """(I + Ld)^-1 of a strictly lower [BC, BC] block by forward substitution."""
+
+    i = tl.arange(0, BC)
+    T = tl.where(i[:, None] == i[None, :], 1.0, 0.0)
+    for s in range(1, BC):
+        lrow = tl.sum(tl.where((i == s)[:, None], Ld, 0.0), axis=0)          # Ld[s, :]
+        trow = -tl.sum(lrow[:, None] * T, axis=0)                           # -sum_m Ld[s, m] T[m, :]
+        T = tl.where((i == s)[:, None], trow[None, :] + tl.where(i == s, 1.0, 0.0)[None, :], T)
+    return T
+
+
[email protected]
+def _dot_k(a, b, NS: tl.constexpr, PREC: tl.constexpr):
+    """a [M, K] @ b [K, N] as a batched dot over NS slices of K, summed: with M = N = 16 a warp then holds a slice of
+    the operands instead of all of K."""
+    M: tl.constexpr = a.shape[0]
+    K: tl.constexpr = a.shape[1]
+    N: tl.constexpr = b.shape[1]
+    a3 = tl.permute(tl.reshape(a, (M, NS, K // NS)), (1, 0, 2))
+    b3 = tl.reshape(b, (NS, K // NS, N))
+    return tl.sum(tl.dot(a3, b3, input_precision=PREC), axis=0)
+
+
[email protected]
+def _gates(A, a_stride, r, valid, hd, ch, rate, dtb, lower, carry):
+    """G for rows r: carry (the running log-decay before them) + their running sum; zero rows outside the chunk."""
+    av = tl.load(A + r.to(tl.int64)[:, None] * a_stride + hd + ch[None, :], mask=valid[:, None], other=0.0)
+    lg = lower * (1.0 / (1.0 + tl.exp(-(rate * (av.to(tl.float32) + dtb[None, :])))))
+    return carry[None, :] + tl.cumsum(tl.where(valid[:, None], lg, 0.0), axis=0)
+
+
[email protected]
+def _beta(P, p_stride, b_off, h, r, valid):
+    braw = tl.load(P + r.to(tl.int64) * p_stride + b_off + h, mask=valid, other=0.0).to(tl.float32)
+    return tl.where(valid, _bf16(1.0 / (1.0 + tl.exp(-braw))), 0.0)
+
+
[email protected]
+def _kda_lm(P, p_stride, b_off, A, a_stride, CS, CW, ALOG, DTB, lower, rows, off, H, QT, L, M,
+            DK_: tl.constexpr, BT: tl.constexpr, BC: tl.constexpr, TAPS_: tl.constexpr, KSPLIT: tl.constexpr,
+            PREC: tl.constexpr):
+    """Program (sub-chunk, head, 16-row block b): block b's rows of L (beta k k decays, strictly lower) and M (q k
+    decays, with the diagonal) against blocks j <= b, and its decayed q (QT = q e^G). Rows outside the prompt chunk
+    are zero rows (no decay, no key). The products are taken about R = G at block b's first row: row factors
+    e^(G - R) in [e^-75, 1], column factors e^(R - G_j) <= 1 for j < b and <= e^75 for j = b (< fp32's e^88.7)."""
+
+    c = tl.program_id(0)
+    h = tl.program_id(1)
+    b = tl.program_id(2)
+    i = tl.arange(0, BC)
+    ch = tl.arange(0, DK_)
+    C3 = 3 * H * DK_
+    hd = h * DK_
+    rate = tl.exp(tl.load(ALOG + h))
+    dtb = tl.load(DTB + hd + ch)
+    r0 = c * BT - off
+    tile = (c.to(tl.int64) * H + h) * BT * BT + (b * BC + i)[:, None] * BT + i[None, :]    # + j * BC: tile (b, j)
+
+    carry = tl.zeros((DK_,), dtype=tl.float32)
+    for j in range(0, b):
+        rj = r0 + j * BC + i
+        carry = _row(_gates(A, a_stride, rj, (rj >= 0) & (rj < rows), hd, ch, rate, dtb, lower, carry), i, BC - 1)
+    r = r0 + b * BC + i
+    valid = (r >= 0) & (r < rows)
+    G = _gates(A, a_stride, r, valid, hd, ch, rate, dtb, lower, carry)
+    k = _l2(_conv_act(P, p_stride, CS, CW, r, valid, H * DK_ + hd + ch, C3, BC, DK_, TAPS_))
+    q = _l2(_conv_act(P, p_stride, CS, CW, r, valid, hd + ch, C3, BC, DK_, TAPS_)) * 0.08838834764831845
+    rowbase = (r.to(tl.int64) * H + h) * DK_
+    tl.store(QT + rowbase[:, None] + ch[None, :], q * tl.exp(G), mask=valid[:, None])
+    beta = _beta(P, p_stride, b_off, h, r, valid)
+    R = _row(G, i, 0)
+    rf = tl.exp(G - R[None, :])
+    rk = k * rf
+    rq = q * rf
+
+    col = tl.trans(k * tl.exp(R[None, :] - G))                                   # the diagonal tile
+    akk = tl.where(i[:, None] > i[None, :], _dot_k(rk, col, KSPLIT, PREC), 0.0)
+    aqk = tl.where(i[:, None] >= i[None, :], _dot_k(rq, col, KSPLIT, PREC), 0.0)
+    tl.store(L + tile + b * BC, beta[:, None] * akk)
+    tl.store(M + tile + b * BC, aqk)
+    carry = tl.zeros((DK_,), dtype=tl.float32)
+    for j in range(0, b):
+        rj = r0 + j * BC + i
+        vj = (rj >= 0) & (rj < rows)
+        Gj = _gates(A, a_stride, rj, vj, hd, ch, rate, dtb, lower, carry)
+        carry = _row(Gj, i, BC - 1)
+        kj = _l2(_conv_act(P, p_stride, CS, CW, rj, vj, H * DK_ + hd + ch, C3, BC, DK_, TAPS_))
+        col = tl.trans(kj * tl.exp(R[None, :] - Gj))                            # [DK, BC]
+        tl.store(L + tile + j * BC, beta[:, None] * _dot_k(rk, col, KSPLIT, PREC))
+        tl.store(M + tile + j * BC, _dot_k(rq, col, KSPLIT, PREC))
+
+
[email protected]
+def _kda_solve(A, a_stride, ALOG, DTB, lower, rows, off, H, L, T, GL,
+               DK_: tl.constexpr, BT: tl.constexpr, BC: tl.constexpr, PREC: tl.constexpr):
+    """Program (sub-chunk, head): T = (I + L)^-1 in 16-row blocks (T_bb by forward substitution, T_bj = -T_bb
+    sum_{j<=m<b} L_bm T_mj), and the sub-chunk's total log-decay GL."""
+
+    NB: tl.constexpr = BT // BC
+    c = tl.program_id(0)
+    h = tl.program_id(1)
+    i = tl.arange(0, BC)
+    ch = tl.arange(0, DK_)
+    hd = h * DK_
+    base = (c.to(tl.int64) * H + h) * BT * BT
+    Ts = ()
+    for b in tl.static_range(NB):
+        Lrow = ()
+        for j in tl.static_range(b + 1):
+            Lrow = Lrow + (tl.load(L + base + (b * BC + i)[:, None] * BT + j * BC + i[None, :]),)
+        Tbb = _tri_inv(Lrow[b], BC)
+        Trow = ()
+        for j in tl.static_range(b):
+            X = tl.zeros((BC, BC), dtype=tl.float32)
+            for m in tl.static_range(j, b):
+                X += tl.dot(Lrow[m], Ts[m][j], input_precision=PREC)
+            Trow = Trow + (-tl.dot(Tbb, X, input_precision=PREC),)
+        Trow = Trow + (Tbb,)
+        Ts = Ts + (Trow,)
+        for j in tl.static_range(b + 1):
+            tl.store(T + base + (b * BC + i)[:, None] * BT + j * BC + i[None, :], Trow[j])
+    rate = tl.exp(tl.load(ALOG + h))
+    dtb = tl.load(DTB + hd + ch)
+    carry = tl.zeros((DK_,), dtype=tl.float32)
+    for b in range(0, NB):
+        r = c * BT - off + b * BC + i
+        carry = _row(_gates(A, a_stride, r, (r >= 0) & (r < rows), hd, ch, rate, dtb, lower, carry), i, BC - 1)
+    tl.store(GL + (c.to(tl.int64) * H + h) * DK_ + ch, carry)
+
+
[email protected]
+def _kda_wu(P, p_stride, b_off, A, a_stride, CS, CW, ALOG, DTB, lower, rows, off, H, T, GL, W, U, KE,
+            DK_: tl.constexpr, BT: tl.constexpr, BC: tl.constexpr, TAPS_: tl.constexpr, PREC: tl.constexpr):
+    """Program (sub-chunk, head, 16-row block b): W_b = sum_{j<=b} T_bj (beta k e^G)_j, U_b = sum_{j<=b} T_bj
+    (beta v)_j (the WY / UT transform), and block b's keys decayed to the sub-chunk's end (KE = k e^(GL - G))."""
+
+    c = tl.program_id(0)
+    h = tl.program_id(1)
+    b = tl.program_id(2)
+    i = tl.arange(0, BC)
+    ch = tl.arange(0, DK_)
+    C3 = 3 * H * DK_
+    hd = h * DK_
+    rate = tl.exp(tl.load(ALOG + h))
+    dtb = tl.load(DTB + hd + ch)
+    r0 = c * BT - off
+    gl = tl.load(GL + (c.to(tl.int64) * H + h) * DK_ + ch)
+    tbase = (c.to(tl.int64) * H + h) * BT * BT + (b * BC + i)[:, None] * BT + i[None, :]
+    rb = r0 + b * BC + i
+    vb = (rb >= 0) & (rb < rows)
+    rowbase = (rb.to(tl.int64) * H + h) * DK_
+    wv = tl.zeros((BC, DK_), dtype=tl.float32)
+    uv = tl.zeros((BC, DK_), dtype=tl.float32)
+    carry = tl.zeros((DK_,), dtype=tl.float32)
+    for j in range(0, b + 1):
+        rj = r0 + j * BC + i
+        vj = (rj >= 0) & (rj < rows)
+        Gj = _gates(A, a_stride, rj, vj, hd, ch, rate, dtb, lower, carry)
+        carry = _row(Gj, i, BC - 1)
+        kj = _l2(_conv_act(P, p_stride, CS, CW, rj, vj, H * DK_ + hd + ch, C3, BC, DK_, TAPS_))
+        tl.store(KE + rowbase[:, None] + ch[None, :], kj * tl.exp(gl[None, :] - Gj), mask=(vb & (j == b))[:, None])
+        bj = _beta(P, p_stride, b_off, h, rj, vj)
+        vv = _conv_act(P, p_stride, CS, CW, rj, vj, 2 * H * DK_ + hd + ch, C3, BC, DK_, TAPS_)
+        tbj = tl.load(T + tbase + j * BC)
+        wv += tl.dot(tbj, bj[:, None] * kj * tl.exp(Gj), input_precision=PREC)
+        uv += tl.dot(tbj, bj[:, None] * vv, input_precision=PREC)
+    tl.store(W + rowbase[:, None] + ch[None, :], wv, mask=vb[:, None])
+    tl.store(U + rowbase[:, None] + ch[None, :], uv, mask=vb[:, None])
+
+
[email protected]
+def _kda_state(S_IN, S_OUT, W, U, KE, GL, HB, rows, off, NC, H,
+               DK_: tl.constexpr, DV_: tl.constexpr, BT: tl.constexpr, BC: tl.constexpr, BV: tl.constexpr,
+               PREC: tl.constexpr):
+    """Program (head, value tile): the state S [BV value rows, K] from sub-chunk to sub-chunk (the only sequential
+    part), BC rows at a time: V'^T = U^T - S W^T (written over U), S <- S diag(e^GL) + V'^T KE. Saves each
+    sub-chunk's entering state (HB [NC, H, V, K], the state's layout)."""
+
+    h = tl.program_id(0)
+    v0 = tl.program_id(1) * BV
+    ki = tl.arange(0, DK_)
+    vi = v0 + tl.arange(0, BV)
+    i = tl.arange(0, BC)
+    sbase = h.to(tl.int64) * DV_ * DK_
+    S = tl.load(S_IN + sbase + vi[:, None] * DK_ + ki[None, :])               # [BV, K]
+    for c in range(NC):
+        cb = (c * H + h).to(tl.int64)
+        tl.store(HB + cb * DV_ * DK_ + vi[:, None] * DK_ + ki[None, :], S)
+        nxt = S * tl.exp(tl.load(GL + cb * DK_ + ki))[None, :]
+        for b in tl.static_range(BT // BC):
+            r = c * BT - off + b * BC + i
+            valid = (r >= 0) & (r < rows)
+            rowbase = (r.to(tl.int64) * H + h) * DK_
+            wb = tl.load(W + rowbase[:, None] + ki[None, :], mask=valid[:, None], other=0.0)     # [BC, K]
+            ub = tl.load(U + rowbase[:, None] + vi[None, :], mask=valid[:, None], other=0.0)     # [BC, BV]
+            vnt = tl.trans(ub) - tl.dot(S, tl.trans(wb), input_precision=PREC)                 # [BV, BC]
+            tl.store(U + rowbase[:, None] + vi[None, :], tl.trans(vnt), mask=valid[:, None])
+            kb = tl.load(KE + rowbase[:, None] + ki[None, :], mask=valid[:, None], other=0.0)     # [BC, K]
+            nxt += tl.dot(vnt, kb, input_precision=PREC)
+        S = nxt
+    tl.store(S_OUT + sbase + vi[:, None] * DK_ + ki[None, :], S)
+
+
[email protected]
+def _kda_out(QT, U, M, HB, G, g_stride, NW, eps, OUT, rows, off, H,
+             DK_: tl.constexpr, DV_: tl.constexpr, BT: tl.constexpr, BC: tl.constexpr, KS: tl.constexpr,
+             PREC: tl.constexpr):
+    """Program (sub-chunk, head): read-outs O = QT S0^T + M V' rounded to bf16, then the gated RMSNorm."""
+
+    c = tl.program_id(0)
+    h = tl.program_id(1)
+    t = tl.arange(0, BT)
+    i = tl.arange(0, BC)
+    ks = tl.arange(0, KS)
+    vi = tl.arange(0, DV_)
+    r = c * BT - off + t
+    valid = (r >= 0) & (r < rows)
+    rowbase = (r.to(tl.int64) * H + h) * DK_
+    cb = (c * H + h).to(tl.int64)
+    o = tl.zeros((BT, DV_), dtype=tl.float32)
+    for k0 in tl.static_range(0, DK_, KS):
+        qt = tl.load(QT + rowbase[:, None] + k0 + ks[None, :], mask=valid[:, None], other=0.0)     # [BT, KS]
+        hs = tl.load(HB + cb * DV_ * DK_ + vi[:, None] * DK_ + k0 + ks[None, :])                   # [DV, KS]
+        o += tl.dot(qt, tl.trans(hs), input_precision=PREC)
+    for j in tl.static_range(BT // BC):
+        mq = tl.load(M + cb * BT * BT + t[:, None] * BT + (j * BC + i)[None, :], mask=(t >= j * BC)[:, None],
+                     other=0.0)                                                   # tiles above the diagonal: 0
+        rj = c * BT - off + j * BC + i
+        vn = tl.load(U + ((rj.to(tl.int64) * H + h) * DK_)[:, None] + vi[None, :],
+                     mask=((rj >= 0) & (rj < rows))[:, None], other=0.0)
+        o += tl.dot(mq, vn, input_precision=PREC)
+    y = _bf16(o)
+    rinv = 1.0 / tl.sqrt_rn(tl.sum(y * y, axis=1) / DV_ + eps)
+    yw = tl.load(NW + vi).to(tl.float32)[None, :] * (y * rinv[:, None])
+    gate = tl.load(G + r.to(tl.int64)[:, None] * g_stride + h * DV_ + vi[None, :], mask=valid[:, None], other=0.0)
+    res = yw * (1.0 / (1.0 + tl.exp(-gate.to(tl.float32))))
+    tl.store(OUT + r.to(tl.int64)[:, None] * (H * DV_) + h * DV_ + vi[None, :], _bf16(res).to(tl.bfloat16),
+             mask=valid[:, None])
+
+
+# -- launcher ---------------------------------------------------------------------------------------------------
+PREC = os.environ.get("TF_GLM_KDA_PREC", "tf32x3")      # tl.dot input precision: tf32x3 (~fp32), tf32, ieee
+BV = int(os.environ.get("TF_GLM_KDA_BV", "16"))          # value rows of the state per sequential program
+STATE_ROWS = int(os.environ.get("TF_GLM_KDA_STATE_ROWS", "32"))   # rows per step of the sequential kernel
+KSPLIT = int(os.environ.get("TF_GLM_KDA_KSPLIT", "4"))   # K slices of the 16 x 16 x 128 products (1: one dot)
+_scratch: dict = {}
+
+
+class ChunkScratch:
+    """Intermediates of a prompt chunk of up to ``rows`` rows (one set per head count and device, shared by layers)."""
+
+    def __init__(self, rows: int, heads: int, device) -> None:
+        f32 = torch.float32
+        nc = -(-(rows + CHUNK - 1) // CHUNK)          # room for a short first sub-chunk
+        self.rows, self.nc = rows, nc
+        self.qt = torch.empty((rows, heads, DK), dtype=f32, device=device)
+        self.w = torch.empty((rows, heads, DK), dtype=f32, device=device)
+        self.u = torch.empty((rows, heads, DV), dtype=f32, device=device)
+        self.ke = torch.empty((rows, heads, DK), dtype=f32, device=device)
+        self.m = torch.empty((nc, heads, CHUNK, CHUNK), dtype=f32, device=device)
+        self.l = torch.empty((nc, heads, CHUNK, CHUNK), dtype=f32, device=device)
+        self.t = torch.empty((nc, heads, CHUNK, CHUNK), dtype=f32, device=device)
+        self.gl = torch.empty((nc, heads, DK), dtype=f32, device=device)
+        self.hb = torch.empty((nc, heads, DV, DK), dtype=f32, device=device)
+
+
+def scratch_for(rows: int, heads: int, device) -> ChunkScratch:
+    key = (heads, str(device))
+    s = _scratch.get(key)
+    if s is None or s.rows < rows:
+        s = ChunkScratch(max(rows, CHUNK), heads, device)
+        _scratch[key] = s
+    return s
+
+
+def chain(p: torch.Tensor, b_off: int, a: torch.Tensor, g: torch.Tensor, conv_state: torch.Tensor,
+          conv_w: torch.Tensor, state_in: torch.Tensor, a_log: torch.Tensor, dt_bias: torch.Tensor,
+          norm_w: torch.Tensor, eps: float, lower: float, rows: int, out: torch.Tensor, state_out: torch.Tensor,
+          pos: int = 0, *, prec: str | None = None, bv: int | None = None) -> torch.Tensor:
+    """kda.chain for a prompt chunk in chunked form: projection rows p [q | k | v | ... | b at b_off ...], bf16 gate
+    rows a (decay) and g (output gate), conv state [3, 3 H 128] (read, not shifted), state_in -> state_out
+    [H, 128, 128]; ``pos`` is the first row's absolute position. Writes out[:rows] (bf16 [rows, H * 128])."""
+
+    H = a_log.numel()
+    rows = int(rows)
+    if rows < 1 or p.shape[0] < rows or out.shape[0] < rows:
+        raise ValueError("rows")
+    if conv_w.shape != (3 * H * DK, TAPS) or conv_state.shape[0] != TAPS - 1:
+        raise ValueError("the chunked KDA path is written for 4-tap convolutions of 3 x H x 128 channels")
+    for x in (conv_state, conv_w, state_in, state_out, out, dt_bias, a_log, norm_w):
+        if not x.is_contiguous():
+            raise ValueError("conv state, conv weight, states, out and the per-head weights must be contiguous")
+    if p.stride(1) != 1 or a.stride(1) != 1 or g.stride(1) != 1:
+        raise ValueError("projection and gate rows must be contiguous along the channels")
+    prec = prec or PREC
+    bv = bv or BV
+    off = int(pos) % CHUNK
+    nc = -(-(rows + off) // CHUNK)
+    s = scratch_for(rows, H, p.device)
+    nb = CHUNK // BLOCK
+    _kda_lm[(nc, H, nb)](p, p.stride(0), int(b_off), a, a.stride(0), conv_state, conv_w, a_log, dt_bias, float(lower),
+                         rows, off, H, s.qt, s.l, s.m,
+                         DK_=DK, BT=CHUNK, BC=BLOCK, TAPS_=TAPS, KSPLIT=KSPLIT, PREC=prec, num_warps=4)
+    _kda_solve[(nc, H)](a, a.stride(0), a_log, dt_bias, float(lower), rows, off, H, s.l, s.t, s.gl,
+                        DK_=DK, BT=CHUNK, BC=BLOCK, PREC=prec, num_warps=4)
+    _kda_wu[(nc, H, nb)](p, p.stride(0), int(b_off), a, a.stride(0), conv_state, conv_w, a_log, dt_bias, float(lower),
+                         rows, off, H, s.t, s.gl, s.w, s.u, s.ke,
+                         DK_=DK, BT=CHUNK, BC=BLOCK, TAPS_=TAPS, PREC=prec, num_warps=4)
+    _kda_state[(H, DV // bv)](state_in, state_out, s.w, s.u, s.ke, s.gl, s.hb, rows, off, nc, H,
+                              DK_=DK, DV_=DV, BT=CHUNK, BC=STATE_ROWS, BV=bv, PREC=prec, num_warps=8, num_stages=1)
+    _kda_out[(nc, H)](s.qt, s.u, s.m, s.hb, g, g.stride(0), norm_w, float(eps), out, rows, off, H,
+                      DK_=DK, DV_=DV, BT=CHUNK, BC=BLOCK, KS=32, PREC=prec, num_warps=8)
+    return out[:rows]