Skip to content

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

Python
21.9 KB
Raw Blame
diff --git tensorfold/families/glm5_next/cuda/kda_chunked.py tensorfold/families/glm5_next/cuda/kda_chunked.py
index 0ee9823..09cb28b 100644
--- tensorfold/families/glm5_next/cuda/kda_chunked.py
+++ tensorfold/families/glm5_next/cuda/kda_chunked.py
@@ -18,12 +18,17 @@ decreasing: every l is in (lower, 0) = (-5, 0)):
     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).
+reference row p: e^(G_s - G_j) = e^(G_s - G_p) e^(G_p - G_j). Each exponent is summed outward from its reference
+(forward from p, backward from p, backward from the sub-chunk's end for k e^(G_63 - G)), never taken as a difference
+of G's: all l have one sign, so a partial sum's rounding error is a few ulps of the partial sum itself, while G
+reaches -320 in a sub-chunk and a difference of two G's would carry ulp(320) = 3e-5 into decays near 1 (the first
+version did: 10x the error of kda.cu's chain). For the rows of 16-row block b against earlier blocks p = the
+block's first row (both factors <= 1: errors a few ulps of the decay's own exponent); inside the diagonal tile p =
+the first row of the row's 4-row group (column factors <= e^15 for the rows after p: errors a few ulps of 30). Only
+blocks j <= b are formed. 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: read-outs ~3e-7 relative against float64 on the
+tests' inputs, kda.cu's chain ~1e-7; "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
@@ -47,11 +52,13 @@ import os
 import torch
 import triton
 import triton.language as tl
+from triton.language.extra import libdevice
 
 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)
+BLOCK = 16              # rows of a block inside a sub-chunk (the tiles of L, M and T)
+GROUP = 4               # rows about one reference row inside a diagonal tile
 SCALE = 1.0 / math.sqrt(DK)
 
 
@@ -156,8 +163,13 @@ def chunked_reference(q, k, v, lg, beta, state, pos: int = 0, dtype=torch.float6
     lower_strict = t[:, None] > t[None, :]
     lower_incl = t[:, None] >= t[None, :]
     nb = CHUNK // BLOCK
+    i = torch.arange(BLOCK, device=dev)[None, :, None]
     S = state.to(dtype).clone()                     # [H, V, K]
     out = torch.empty((total, H, DV), dtype=dtype, device=dev)
+
+    def rcumsum(x):
+        return torch.flip(torch.cumsum(torch.flip(x, [1]), 1), [1])
+
     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)
@@ -165,13 +177,25 @@ def chunked_reference(q, k, v, lg, beta, state, pos: int = 0, dtype=torch.float6
         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)
+            lb = lx[:, rs]
+            for g in range(BLOCK // GROUP):                           # the diagonal tile, about each group's row
+                p = g * GROUP
+                fwd = torch.cumsum(torch.where(i > p, lb, 0.0), 1)
+                back = rcumsum(torch.where(i <= p, lb, 0.0)) - lb
+                rf = torch.where((i >= p) & (i < p + GROUP), torch.exp(fwd), 0.0)
+                cf = torch.where(i < p, torch.exp(back), torch.where(i < p + GROUP, torch.exp(-fwd), 0.0))
+                kt = (kx[:, rs] * cf).transpose(1, 2)
+                Akk[:, rs, rs] += mm(kx[:, rs] * rf, kt)
+                Aqk[:, rs, rs] += mm(qx[:, rs] * rf, kt)
+            rf = torch.exp(torch.cumsum(torch.where(i > 0, lb, 0.0), 1))   # earlier blocks, about the block's row 0
+            carry = lb[:, :1]
+            for j in range(b - 1, -1, -1):
+                cs = slice(j * BLOCK, (j + 1) * BLOCK)
+                rev = rcumsum(lx[:, cs])
+                kt = (kx[:, cs] * torch.exp(carry + (rev - lx[:, cs]))).transpose(1, 2)
+                Akk[:, rs, cs] = mm(kx[:, rs] * rf, kt)
+                Aqk[:, rs, cs] = mm(qx[:, rs] * rf, kt)
+                carry = carry + rev[:, :1]
         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)
@@ -185,7 +209,7 @@ def chunked_reference(q, k, v, lg, beta, state, pos: int = 0, dtype=torch.float6
         W = mm(T, bx[:, :, None] * kx * eG)
         U = mm(T, bx[:, :, None] * vx)
         gl = G[:, -1:, :]
-        Ke = kx * torch.exp(gl - G)
+        Ke = kx * torch.exp(rcumsum(lx) - lx)                      # GL - G, summed backward from the end
         Qt = qx * eG
         ST = S.transpose(1, 2)                                      # [H, K, V]
         Vn = U - mms(W, ST)
@@ -217,6 +241,29 @@ def chain_reference(p, b_off, a, g, conv_state, conv_w, state_in, a_log, dt_bias
 
 
 # -- Triton kernels ---------------------------------------------------------------------------------------------
+# The per-row values rounded to bf16 (conv + SiLU, beta) must be kda.cu's bits: a value rounded the other way at a
+# bf16 tie moves a key by 2^-8 in one channel, a beta by 2^-8 of the whole update, far above fp32 noise (and the
+# read-out of a row whose RMSNorm is eps-dominated carries it into the output). kda.cu is built with --fmad=false and
+# uses CUDA's expf and IEEE division: the kernels that compute these values launch with enable_fp_fusion=False and
+# take libdevice's expf (the same algorithm) and div_rn. Triton's interpreter has no libdevice: it takes tl.exp.
+_PRECISE = tl.constexpr(os.environ.get("TRITON_INTERPRET", "0") != "1")
+
+
[email protected]
+def _expf(x):
+    """CUDA's expf (libdevice) on the GPU, tl.exp under the interpreter."""
+    if _PRECISE:
+        return libdevice.exp(x)
+    else:
+        return tl.exp(x)
+
+
[email protected]
+def _sigmoid_f(x):
+    """kda.cu's sigmoidf_: 1 / (1 + expf(-x)), IEEE division."""
+    return tl.math.div_rn(1.0, 1.0 + _expf(-x))
+
+
 @triton.jit
 def _bf16(x):
     """fp32 rounded to bf16 (to nearest even), as fp32: bit arithmetic, so Triton's CPU interpreter (which truncates
@@ -241,14 +288,14 @@ def _conv_act(P, p_stride, CS, CW, r, valid, ch, C3, BT: tl.constexpr, DK_: tl.c
         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))
+    act = tl.math.div_rn(acc, 1.0 + _expf(-acc))
     return _bf16(act)
 
 
 @triton.jit
 def _l2(x):
     ss = tl.sum(x * x, axis=1)
-    return x * (1.0 / tl.sqrt_rn(ss + 1e-6))[:, None]
+    return x * tl.math.div_rn(1.0, tl.sqrt_rn(ss + 1e-6))[:, None]
 
 
 @triton.jit
@@ -282,28 +329,38 @@ def _dot_k(a, b, NS: tl.constexpr, PREC: tl.constexpr):
     return tl.sum(tl.dot(a3, b3, input_precision=PREC), axis=0)
 
 
[email protected]
+def _logdecay(A, a_stride, r, valid, hd, ch, rate, dtb, lower):
+    """The log-decays l of rows r [BC, DK] (in (lower, 0)); 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 * _sigmoid_f(rate * (av.to(tl.float32) + dtb[None, :]))
+    return tl.where(valid[:, None], lg, 0.0)
+
+
 @triton.jit
 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)
+    return carry[None, :] + tl.cumsum(_logdecay(A, a_stride, r, valid, hd, ch, rate, dtb, lower), axis=0)
 
 
 @triton.jit
 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)
+    return tl.where(valid, _bf16(_sigmoid_f(braw)), 0.0)
 
 
 @triton.jit
 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):
+            DK_: tl.constexpr, BT: tl.constexpr, BC: tl.constexpr, GR: 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)."""
+    are zero rows (no decay, no key).
+
+    A decay e^(G_s - G_j) is formed as e^(G_s - G_p) e^(G_p - G_j) about a reference row p, each exponent summed
+    outward from p (its rounding error a few ulps of its own size, never of G's): p = the block's first row for
+    earlier blocks (both factors <= 1: the error is a few ulps of the decay's own exponent), p = the first row of s's
+    GR-row group inside the diagonal tile (column factors <= e^(5 (GR - 1)), errors a few ulps of 10 (GR - 1))."""
 
     c = tl.program_id(0)
     h = tl.program_id(1)
@@ -312,43 +369,52 @@ def _kda_lm(P, p_stride, b_off, A, a_stride, CS, CW, ALOG, DTB, lower, rows, off
     ch = tl.arange(0, DK_)
     C3 = 3 * H * DK_
     hd = h * DK_
-    rate = tl.exp(tl.load(ALOG + h))
+    rate = _expf(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)
+    lb = _logdecay(A, a_stride, r, valid, hd, ch, rate, dtb, lower)
     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, :])
+
+    # the diagonal tile in GR-row groups: rows s of group g about p = the group's first row
+    akk = tl.zeros((BC, BC), dtype=tl.float32)
+    aqk = tl.zeros((BC, BC), dtype=tl.float32)
+    for g in tl.static_range(BC // GR):
+        fwd = tl.cumsum(tl.where(i[:, None] > g * GR, lb, 0.0), axis=0)                          # G_t - G_p, t >= p
+        back = tl.cumsum(tl.where(i[:, None] <= g * GR, lb, 0.0), axis=0, reverse=True) - lb     # G_p - G_t, t < p
+        rf = tl.where(((i >= g * GR) & (i < g * GR + GR))[:, None], tl.exp(fwd), 0.0)
+        cf = tl.where((i < g * GR)[:, None], tl.exp(back), tl.where((i < g * GR + GR)[:, None], tl.exp(-fwd), 0.0))
+        col = tl.trans(k * cf)
+        akk += _dot_k(k * rf, col, KSPLIT, PREC)
+        aqk += _dot_k(q * rf, col, KSPLIT, PREC)
+    tl.store(L + tile + b * BC, tl.where(i[:, None] > i[None, :], beta[:, None] * akk, 0.0))
+    tl.store(M + tile + b * BC, tl.where(i[:, None] >= i[None, :], aqk, 0.0))
+
+    # earlier blocks, nearest first, about p = the block's first row
+    fwd = tl.cumsum(tl.where(i[:, None] > 0, lb, 0.0), axis=0)                                   # G_s - G_p
+    rf = tl.exp(fwd)
     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):
+    carry = _row(lb, i, 0)                                    # G_p - G_t for t = the previous block's last row
+    for jj in range(0, b):
+        j = b - 1 - jj
         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)
+        lj = _logdecay(A, a_stride, rj, vj, hd, ch, rate, dtb, lower)
+        rev = tl.cumsum(lj, axis=0, reverse=True)
         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]
+        col = tl.trans(kj * tl.exp(carry[None, :] + (rev - lj)))                  # e^(G_p - G_t) <= 1, [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))
+        carry += _row(rev, i, 0)
+    # carry = G_p, the running log-decay through the block's first row
+    rowbase = (r.to(tl.int64) * H + h) * DK_
+    tl.store(QT + rowbase[:, None] + ch[None, :], q * tl.exp(carry[None, :] + fwd), mask=valid[:, None])
 
 
 @triton.jit
@@ -380,7 +446,7 @@ def _kda_solve(A, a_stride, ALOG, DTB, lower, rows, off, H, L, T, GL,
         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))
+    rate = _expf(tl.load(ALOG + h))
     dtb = tl.load(DTB + hd + ch)
     carry = tl.zeros((DK_,), dtype=tl.float32)
     for b in range(0, NB):
@@ -390,11 +456,13 @@ def _kda_solve(A, a_stride, ALOG, DTB, lower, rows, off, H, L, T, GL,
 
 
 @triton.jit
-def _kda_wu(P, p_stride, b_off, A, a_stride, CS, CW, ALOG, DTB, lower, rows, off, H, T, GL, W, U, KE,
+def _kda_wu(P, p_stride, b_off, A, a_stride, CS, CW, ALOG, DTB, lower, rows, off, H, T, 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))."""
+    (beta v)_j (the WY / UT transform), and block b's keys decayed to the sub-chunk's end (KE = k e^(GL - G), the
+    exponent summed backward from the end: a few ulps of its own size)."""
 
+    NB: tl.constexpr = BT // BC
     c = tl.program_id(0)
     h = tl.program_id(1)
     b = tl.program_id(2)
@@ -402,24 +470,30 @@ def _kda_wu(P, p_stride, b_off, A, a_stride, CS, CW, ALOG, DTB, lower, rows, off
     ch = tl.arange(0, DK_)
     C3 = 3 * H * DK_
     hd = h * DK_
-    rate = tl.exp(tl.load(ALOG + h))
+    rate = _expf(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_
+    later = tl.zeros((DK_,), dtype=tl.float32)                   # log-decay of the blocks after b, last first
+    for jj in range(0, NB - 1 - b):
+        rj = r0 + (NB - 1 - jj) * BC + i
+        later += tl.sum(_logdecay(A, a_stride, rj, (rj >= 0) & (rj < rows), hd, ch, rate, dtb, lower), axis=0)
     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)
+        lj = _logdecay(A, a_stride, rj, vj, hd, ch, rate, dtb, lower)
+        Gj = carry[None, :] + tl.cumsum(lj, axis=0)
         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])
+        if j == b:
+            ke = kj * tl.exp(later[None, :] + (tl.cumsum(lj, axis=0, reverse=True) - lj))     # GL - G
+            tl.store(KE + rowbase[:, None] + ch[None, :], ke, mask=vb[:, 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)
@@ -491,10 +565,10 @@ def _kda_out(QT, U, M, HB, G, g_stride, NW, eps, OUT, rows, off, H,
                      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)
+    rinv = tl.math.div_rn(1.0, tl.sqrt_rn(tl.sum(y * y, axis=1) * (1.0 / 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))))
+    res = yw * _sigmoid_f(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])
 
@@ -504,6 +578,10 @@ PREC = os.environ.get("TF_GLM_KDA_PREC", "tf32x3")      # tl.dot input precision
 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)
+# (num_warps, num_stages) per kernel. One stage everywhere: GB10 (sm_121) gives a block 99 KiB of shared memory
+# (101,376 B), and pipelined loads of the per-block loops need up to 154 KiB.
+LAUNCH = {"lm": (8, 1), "solve": (4, 1), "wu": (8, 1), "state": (8, 1), "out": (8, 1)}
+_EXACT = dict(enable_fp_fusion=False, enable_reflect_ftz=False)   # kda.cu's arithmetic (see _PRECISE)
 _scratch: dict = {}
 
 
@@ -561,14 +639,19 @@ def chain(p: torch.Tensor, b_off: int, a: torch.Tensor, g: torch.Tensor, conv_st
     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)
+                         DK_=DK, BT=CHUNK, BC=BLOCK, GR=GROUP, TAPS_=TAPS, KSPLIT=KSPLIT, PREC=prec,
+                         num_warps=LAUNCH["lm"][0], num_stages=LAUNCH["lm"][1], **_EXACT)
     _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)
+                        DK_=DK, BT=CHUNK, BC=BLOCK, PREC=prec, num_warps=LAUNCH["solve"][0],
+                        num_stages=LAUNCH["solve"][1], **_EXACT)
     _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)
+                         rows, off, H, s.t, s.w, s.u, s.ke,
+                         DK_=DK, BT=CHUNK, BC=BLOCK, TAPS_=TAPS, PREC=prec, num_warps=LAUNCH["wu"][0],
+                         num_stages=LAUNCH["wu"][1], **_EXACT)
     _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)
+                              DK_=DK, DV_=DV, BT=CHUNK, BC=STATE_ROWS, BV=bv, PREC=prec,
+                              num_warps=LAUNCH["state"][0], num_stages=LAUNCH["state"][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)
+                      DK_=DK, DV_=DV, BT=CHUNK, BC=BLOCK, KS=32, PREC=prec, num_warps=LAUNCH["out"][0],
+                      num_stages=LAUNCH["out"][1], **_EXACT)
     return out[:rows]