GLM-5.3-Flash EXL3 on 2x DGX Spark with TensorFold
Python
diff --git tensorfold/families/glm5_next/cuda/forward.py tensorfold/families/glm5_next/cuda/forward.py
index f09d0dd..cb39952 100644
--- tensorfold/families/glm5_next/cuda/forward.py
+++ tensorfold/families/glm5_next/cuda/forward.py
@@ -429,6 +429,48 @@ def _dsa_latent(a, w: Weights, lc: torch.Tensor, pos_dev: torch.Tensor, b: Buffe
return out_proj(w, b, o, a.o, qmm.group_sums(o, b.xs_ao[:R]), R)
+def dsa_segments(layer: LayerW, w: Weights, lc: torch.Tensor, b: Buffers, R: int, rows, sel=None, index=None, *,
+ select: bool = True) -> torch.Tensor | None:
+ """dsa_block on the latent cache for a multi-stream window (``rows``: segments.SegRows, already set): several
+ streams' rows back to back, each stream's latents (lc), index keys, gates and pooled keys (index: arenas) in
+ its own extent. Each segment's rows get the bits of that segment alone through dsa_block (the projections,
+ absorb and expand keep rows apart; the attention kernels are latent.seg_* / sparse.seg_*). Graphs: one per R
+ covers every position mix. ``select`` False skips the token selection (eager windows with no sparse row:
+ ``rows.any_sparse()``); ``sel``: segments.SelectScratch, needed with an index."""
+
+ c = w.cfg
+ a = layer.dsa
+ if a.absorb is None:
+ raise ValueError("segmented windows need the latent cache (TF_GLM_LATENT=1)")
+ mm(b, b.normed[:R], a.proj, b.xs[:R], b.dp[:R])
+ glue.rmsnorm(b.dp[:R, :c.q_lora], a.q_norm, c.eps, b.qr[:R], b.xs_qr[:R])
+ glue.rmsnorm(b.dp[:R, c.q_lora:], a.kv_norm, c.eps, b.lat[:R], b.xs_lat[:R])
+ HL = a.heads
+ mm(b, b.qr[:R], a.q_b, b.xs_qr[:R], b.q[:R].view(R, HL * c.qk_dim))
+ s = b.lat_s
+ with prof.timed("dsa: latent write"):
+ latent.seg_latent_write(b.lat[:R], lc, rows)
+ tokens = counts = None
+ if index is not None:
+ ik, ig, pk = index
+ ix = a.index
+ with prof.timed("dsa: indexer update"):
+ mm(b, b.normed[:R], ix.kw, b.xs[:R], b.ikr[:R])
+ glue.router(b.normed[:R], ix.gate, b.igr[:R])
+ sparse.seg_index_update(b.ikr[:R, :c.index_dim], b.igr[:R], ix.ln_w, ix.ln_b, ix.ape, ik, ig, pk, rows)
+ if select:
+ with prof.timed("dsa: select tokens"):
+ mm(b, b.qr[:R], ix.qb, b.xs_qr[:R], b.qi[:R])
+ tokens, counts = sparse.seg_select_tokens(b.qi[:R], b.ikr[:R, c.index_dim:], pk, rows, sel)
+ with prof.timed("dsa: absorb"):
+ qa = latent.absorb_q(b.q[:R], a.absorb, s.qa[:R])
+ with prof.timed("dsa: attention"):
+ ol = latent.seg_attention(qa, lc, rows, tokens, counts, s, scale=c.qk_dim ** -0.5, out=s.ol[:R])
+ with prof.timed("dsa: expand"):
+ o = latent.expand_v(ol, a.absorb, b.vn[:R]).view(R, HL * c.v_dim)
+ return out_proj(w, b, o, a.o, qmm.group_sums(o, b.xs_ao[:R]), R)
+
+
def mlp_block(layer: LayerW, w: Weights, b: Buffers, R: int) -> torch.Tensor:
m = layer.mlp
mm(b, b.normed[:R], m.gu, b.xs[:R], b.gu[:R])
diff --git tensorfold/families/glm5_next/cuda/latent.py tensorfold/families/glm5_next/cuda/latent.py
index 3026586..1cecc96 100644
--- tensorfold/families/glm5_next/cuda/latent.py
+++ tensorfold/families/glm5_next/cuda/latent.py
@@ -676,3 +676,114 @@ def sparse_onepass(qa: torch.Tensor, cache: torch.Tensor, tokens: torch.Tensor,
def chunks_for(length: int) -> int:
return triton.cdiv(length, CHUNK)
+
+
+# ------------------------------------------------------------------------------------- multi-stream windows ---
+# A window of several streams' rows back to back ([s1: rows][s2: rows]...), each stream's latents in its own extent
+# of a shared arena [P, LW]: per-row device tables (``segments.SegRows``: position, extent base, dense or sparse)
+# drive the kernels below. Every row keeps the arithmetic, tiles and head blocks of today's single-stream kernels,
+# so a segment's rows get the bits of that segment run alone on its extent (tests/cuda/test_glm_attn_segments.py).
+# Cache reads and writes go through _lat_get / _lat_put (the one place a quantized cache plugs in).
+
[email protected]
+def _lat_get(LC, rows, ok, k, RS: tl.constexpr):
+ """Cache rows ``rows`` (int64 [n]) as a bf16 tile [n, LW]; rows with ok false are not read (zeros)."""
+ return tl.load(LC + rows[:, None] * RS + k[None, :], mask=ok[:, None], other=0).to(tl.bfloat16)
+
+
[email protected]
+def _lat_put(LC, row, k, x, RS: tl.constexpr):
+ """Cache row ``row`` (int64) <- x [LW] (bf16)."""
+ tl.store(LC + row * RS + k, x)
+
+
[email protected]
+def _seg_lat_write(LAT, lat_stride, LC, POS, BASE, LW: tl.constexpr):
+ """Row r -> arena row base[r] + pos[r]."""
+ r = tl.program_id(0)
+ row = tl.load(BASE + r).to(tl.int64) + tl.load(POS + r).to(tl.int64)
+ k = tl.arange(0, LW)
+ _lat_put(LC, row, k, tl.load(LAT + r * lat_stride + k), LW)
+
+
+def seg_latent_write(lat: torch.Tensor, cache: torch.Tensor, rows) -> None:
+ """lat [R, latent] bf16 rows into the arena at each row's base + pos (``rows``: segments.SegRows)."""
+ _seg_lat_write[(lat.shape[0],)](lat, lat.stride(0), cache, rows.pos, rows.base, LW=cache.shape[1], num_warps=4)
+
+
[email protected]
+def _seg_chunks(QA, LC, POS, BASE, SPR, TOK, CNT, PO, PM, PL, R, W: tl.constexpr, H: tl.constexpr,
+ LW: tl.constexpr, CH: tl.constexpr, SCALE: tl.constexpr, HBT: tl.constexpr, KTT: tl.constexpr):
+ """Program (row, head block, chunk): _dense_chunks for a dense row (keys base + 0 .. base + pos[r], its own
+ limit), _sparse_chunks for a sparse one (keys base + its selected tokens, list order): the same tiles, masks and
+ _tile math either way, so a row's partials are those of its single-stream kernel."""
+ r = tl.program_id(0)
+ hb = tl.program_id(1)
+ c = tl.program_id(2)
+ B = tl.load(BASE + r).to(tl.int64)
+ sp = tl.load(SPR + r) != 0
+ n = tl.where(sp, tl.load(CNT + r, mask=sp, other=0), tl.load(POS + r) + 1) # selected tokens, or keys 0 .. pos
+ hh = hb * HBT + tl.arange(0, HBT)
+ hok = hh < H
+ k = tl.arange(0, LW)
+ m = tl.full((HBT,), float("-inf"), tl.float32)
+ l = tl.zeros((HBT,), tl.float32)
+ o = tl.zeros((HBT, LW), tl.float32)
+ if c * CH < n:
+ q = tl.load(QA + (r * H + hh[:, None]) * LW + k[None, :], mask=hok[:, None], other=0).to(tl.bfloat16)
+ for t in range(CH // KTT):
+ idx = c * CH + t * KTT + tl.arange(0, KTT)
+ ok = idx < n
+ tok = tl.load(TOK + r * W + idx, mask=ok & sp, other=0).to(tl.int64)
+ tok = tl.where(sp, tok, idx.to(tl.int64))
+ kv = _lat_get(LC, B + tok, ok, k, LW)
+ m, l, o = _tile(q, kv, m, l, o, ok, SCALE)
+ base = (c * R + r) * H + hh
+ tl.store(PO + base[:, None] * LW + k[None, :], o, mask=hok[:, None])
+ tl.store(PM + base, m, mask=hok)
+ tl.store(PL + base, l, mask=hok)
+
+
+def seg_chunks() -> int:
+ """Chunks a segmented window's rows take: a sparse row's 2,051 selected tokens, a dense row's keys up to
+ SPARSE_FROM - 1 (both 5 of 512); chunks past a row's keys are empty (merged as nothing, the same bits)."""
+ from .sparse import SPARSE_FROM, TOKENS
+
+ return triton.cdiv(max(SPARSE_FROM, TOKENS), CHUNK)
+
+
+SEG_WIDE_ROWS = 8 # segmented windows from this many rows take 32-head tiles (keys read once; fewer programs)
+
+
+def seg_head_block(R: int) -> int:
+ """Heads per program of a segmented window: 16 for a few rows (more programs in flight), a rank's 32 from
+ SEG_WIDE_ROWS (each key tile read once for them). 16- and 32-row tiles give a row the same bits (head_block),
+ so either matches the single-stream kernels' 16 (tests/cuda/test_glm_attn_segments.py checks both)."""
+ return HB_WIDE if R >= SEG_WIDE_ROWS else HB
+
+
+def seg_attention(qa: torch.Tensor, cache: torch.Tensor, rows, tokens: torch.Tensor | None,
+ counts: torch.Tensor | None, s: LatentScratch, *, scale: float, out: torch.Tensor,
+ hb: int | None = None) -> torch.Tensor:
+ """Attention of a segmented window's rows qa [R, H, 512] -> out [R, H, 512]: dense rows over their stream's
+ keys 0 .. pos, sparse rows over their selected tokens (``segments.seg_select``: tokens relative to the stream,
+ counts), each in its own extent of the arena. One chunk pass and one merge for both kinds; a row gets the bits
+ of ``attention`` (dense) or ``sparse_attention`` (sparse) run on its segment alone."""
+ R, H, LW = qa.shape
+ nch = seg_chunks()
+ if nch > s.nch or R > s.rows or LW != s.lw:
+ raise ValueError(f"segmented attention: {R} rows, {nch} chunks, width {LW} past the scratch's "
+ f"{s.rows}, {s.nch}, {s.lw}")
+ if tokens is None: # a window without sparse rows (no index): nothing reads the lists
+ tokens, counts, W = s.dummy, s.dummy, 1
+ else:
+ W = tokens.shape[1]
+ n = nch * R * H
+ hb = seg_head_block(R) if hb is None else hb
+ if hb not in (HB, HB_WIDE):
+ raise ValueError(f"segmented attention: {hb} heads a tile, not {HB} or {HB_WIDE}")
+ _seg_chunks[(R, triton.cdiv(H, hb), nch)](qa, cache, rows.pos, rows.base, rows.sparse, tokens, counts,
+ s.po[:n * LW], s.pm[:n], s.pl[:n], R, W=W, H=H, LW=LW, CH=CHUNK,
+ SCALE=scale, HBT=hb, KTT=KT, num_warps=8, num_stages=chunk_stages())
+ _merge[(R, H)](s.po, s.pm, s.pl, out, s.dummy, R, H=H, LW=LW, NCH=nch, SPARSE=False, num_warps=4)
+ return out
diff --git tensorfold/families/glm5_next/cuda/segments.py tensorfold/families/glm5_next/cuda/segments.py
new file mode 100644
index 0000000..91b3d06
--- /dev/null
+++ tensorfold/families/glm5_next/cuda/segments.py
@@ -0,0 +1,99 @@
+"""Multi-stream decode windows: several streams' rows back to back ([s1: rows][s2: rows]...), each stream's per-token
+DSA state in its own extent of shared arenas (latents [P, 512], index keys and gates [P, 128], pooled keys
+[P / 4 + 2, 128]; extents aligned to EXTENT tokens). ``SegRows`` holds the per-row and per-segment device tables the
+segmented kernels read (latent.seg_*, sparse.seg_*); ``SelectScratch`` the token selection's buffers. Static
+buffers, so one CUDA graph per window size covers every mix of positions and context lengths."""
+
+from __future__ import annotations
+
+from typing import Sequence
+
+import torch
+
+from .sparse import POOL, SPARSE_FROM, TOKENS, split_scratch
+
+MAX_SEGS = 4 # streams a window holds
+EXTENT = 2048 # a stream's extent starts at a multiple of this many tokens (its pooled keys at base / 4)
+
+
+class SegRows:
+ """Device tables of a window of up to ``rows`` rows in up to ``max_segs`` segments, one int32 tensor:
+
+ per row: ``pos`` (the row's position in its stream), ``base`` (its stream's first arena row), ``seg`` (segment
+ index), ``sparse`` (1: past the dense limit, attends to its selected tokens; 0: dense over keys 0 .. pos);
+ per segment: ``seg_start`` (first row), ``seg_rows`` (0: unused), ``seg_pbase`` (pooled-key base, base / 4),
+ ``seg_pools`` (pools its last row sees when it has sparse rows, else 0: what the selection scores)."""
+
+ def __init__(self, rows: int, device, max_segs: int = MAX_SEGS) -> None:
+ self.rows, self.max_segs = rows, max_segs
+ n = 4 * rows + 4 * max_segs
+ pin = torch.cuda.is_available() and torch.device(device).type == "cuda"
+ self.host = torch.zeros((n,), dtype=torch.int32, pin_memory=pin)
+ self.dev = torch.zeros((n,), dtype=torch.int32, device=device)
+ self.pos, self.base, self.seg, self.sparse = (self.dev[i * rows:(i + 1) * rows] for i in range(4))
+ o = 4 * rows
+ self.seg_start, self.seg_rows, self.seg_pbase, self.seg_pools = (
+ self.dev[o + i * max_segs:o + (i + 1) * max_segs] for i in range(4))
+ self.staged = torch.cuda.Event() if pin else None
+ self.R = 0
+ self.segments: list[tuple[int, int, int]] = []
+
+ def fill(self, segments: Sequence[tuple[int, int, int]], *, sparse_from: int | None = SPARSE_FROM):
+ """The host tables for ``segments`` [(base, pos, rows)] in window order (numpy int32, the device layout).
+ ``sparse_from``: the first position that attends sparsely (None: no index, every row dense)."""
+
+ if not 1 <= len(segments) <= self.max_segs:
+ raise ValueError(f"a window of {len(segments)} segments, at most {self.max_segs}")
+ R = sum(n for _, _, n in segments)
+ if R > self.rows:
+ raise ValueError(f"a window of {R} rows, the tables hold {self.rows}")
+ rows, S = self.rows, self.max_segs
+ t = torch.zeros((4 * rows + 4 * S,), dtype=torch.int32).numpy()
+ r = 0
+ for s, (base, pos, n) in enumerate(segments):
+ if n < 1 or pos < 0 or base < 0 or base % EXTENT:
+ raise ValueError(f"segment {s}: base {base} (a multiple of {EXTENT}), position {pos}, {n} rows")
+ for i in range(n):
+ q = pos + i
+ t[r + i] = q
+ t[rows + r + i] = base
+ t[2 * rows + r + i] = s
+ t[3 * rows + r + i] = int(sparse_from is not None and q >= sparse_from)
+ last = pos + n - 1
+ t[4 * rows + s] = r
+ t[4 * rows + S + s] = n
+ t[4 * rows + 2 * S + s] = base // POOL
+ t[4 * rows + 3 * S + s] = (last + 1) // POOL if sparse_from is not None and last >= sparse_from else 0
+ r += n
+ return t, R
+
+ def set(self, segments: Sequence[tuple[int, int, int]], *, sparse_from: int | None = SPARSE_FROM) -> int:
+ """Stage ``segments`` [(base, pos, rows)] into the device tables (a pinned copy, ordered on the current
+ stream like forward.stage's token ids); returns the window's rows."""
+
+ t, R = self.fill(segments, sparse_from=sparse_from)
+ if self.staged is not None:
+ self.staged.synchronize() # the previous copy has left the pinned buffer
+ self.host.numpy()[:] = t
+ self.dev.copy_(self.host, non_blocking=True)
+ if self.staged is not None:
+ self.staged.record()
+ self.R, self.segments = R, list(segments)
+ return R
+
+ def any_sparse(self) -> bool:
+ """Host view of the last ``set``: does any row attend sparsely."""
+ return bool(self.host[3 * self.rows:3 * self.rows + self.R].any())
+
+
+class SelectScratch:
+ """The segmented selection's buffers: fp32 scores [rows, pools] (a stream's pools at most: its largest context
+ / 4), tokens [rows, 2051] int32, counts [rows] int32, the split selection's scratch."""
+
+ def __init__(self, rows: int, max_context: int, device) -> None:
+ self.rows = rows
+ pools = max(1, -(-max_context // POOL))
+ self.scores = torch.empty((rows, pools), dtype=torch.float32, device=device)
+ self.tokens = torch.full((rows, TOKENS), -1, dtype=torch.int32, device=device)
+ self.counts = torch.zeros((rows,), dtype=torch.int32, device=device)
+ self.split = split_scratch(rows, pools, device)
diff --git tensorfold/families/glm5_next/cuda/sparse.py tensorfold/families/glm5_next/cuda/sparse.py
index 73cc902..6cfe91d 100644
--- tensorfold/families/glm5_next/cuda/sparse.py
+++ tensorfold/families/glm5_next/cuda/sparse.py
@@ -13,6 +13,7 @@ TOPK_POOLS = 512
BR = 16
# the first position whose row select_tokens counts (npool > TOPK_POOLS): rows before it keep dense attention
SPARSE_FROM = (TOPK_POOLS + 1) * POOL - 1
+TOKENS = TOPK_POOLS * POOL + POOL - 1 # a sparse row's attended tokens: its 512 pools', then its incomplete pool's
@triton.jit
@@ -163,13 +164,19 @@ def _select_rows(S, OUT, NP, POS, K: tl.constexpr, BLOCK: tl.constexpr, VISIBLE:
def top_pools(scores: torch.Tensor, k: int, pos_dev: torch.Tensor | None = None) -> torch.Tensor:
- """``_top_pools``'s pools in one kernel, ascending, without int64 keys, top-k or sort."""
+ """``_top_pools``'s pools, ascending, without int64 keys, top-k or sort: one program a row, or for a decode
+ window's long rows the split selection (select_split); the same pools either way. ``pos_dev``: the rows sit at
+ pos_dev, pos_dev + 1, .. and the one-program selection reads each row's visible pools only (the same pools)."""
R, NP = scores.shape
if NP < k or not scores.is_contiguous():
return _top_pools(scores, k)
+ if R < SPLIT_ROWS and NP >= SPLIT_FROM: # decode rows at long context: each row across chunk programs
+ return select_split(scores, k)
+ # one program a row (speed only): decode rows past 1,024 scores 4,096 a step, prompt chunks' rows 1,024
+ block, warps = (4096, 8) if R < SPLIT_ROWS and NP > 1024 else (1024, 4)
out = torch.empty((R, k), dtype=torch.int64, device=scores.device)
_select_rows[(R,)](scores, out, NP, pos_dev if pos_dev is not None else scores,
- K=k, BLOCK=1024, VISIBLE=pos_dev is not None, num_warps=4)
+ K=k, BLOCK=block, VISIBLE=pos_dev is not None, num_warps=warps)
return out
@@ -390,3 +397,357 @@ def sparse_attention(q: torch.Tensor, kc: torch.Tensor, vc: torch.Tensor, tokens
_sparse_chunks[(n, H, nch)](q[rows], kc, vc, tokens[rows], counts[rows], po, pm, pl, W=W, H=H, D=D, CH=CH,
SCALE=scale, num_warps=4, num_stages=1)
_sparse_merge[(n, H)](po, pm, pl, out[rows], counts[rows], H=H, D=D, NCH=nch, CH=CH, num_warps=4)
+
+
+# ------------------------------------------------------------------------------------- multi-stream windows ---
+# Segmented windows (latent.py's section of the same name): each stream's index keys and gates in its own extent of
+# shared arenas [P, 128] (token t of the stream at base + t) and its pooled keys at base / 4 + p of [P / 4 + 2, 128];
+# per-row device tables (``segments.SegRows``) give each row its position, base and kind. A row keeps its
+# single-stream arithmetic. Reads and writes of the index caches go through the helpers below.
+
[email protected]
+def _ix_put(IX, row, d, x, D: tl.constexpr):
+ """Index key or gate row ``row`` (int64) <- x [D] as bf16."""
+ tl.store(IX + row * D + d, x.to(tl.bfloat16))
+
+
[email protected]
+def _ix_get(IX, row, d, D: tl.constexpr):
+ """Index key or gate row ``row`` (int64) as fp32 [D]."""
+ return tl.load(IX + row * D + d).to(tl.float32)
+
+
[email protected]
+def _pk_put(PK, row, d, x, D: tl.constexpr):
+ """Pooled key row ``row`` (int64) <- x [D] (fp32) as bf16."""
+ tl.store(PK + row * D + d, x.to(tl.bfloat16))
+
+
[email protected]
+def _pk_get(PK, rows, ok, d, D: tl.constexpr):
+ """Pooled key rows ``rows`` (int64 [n]) as a bf16 tile [n, D]; rows with ok false are zeros."""
+ return tl.load(PK + rows[:, None] * D + d[None, :], mask=ok[:, None], other=0.0).to(tl.bfloat16)
+
+
[email protected]
+def _seg_index_write(KR, k_stride, GR, LNW, LNB, IK, IG, POS, BASE, eps, D: tl.constexpr):
+ """_index_write for row r at its stream's row base[r] + pos[r]."""
+
+ r = tl.program_id(0)
+ row = tl.load(BASE + r).to(tl.int64) + tl.load(POS + r).to(tl.int64)
+ d = tl.arange(0, D)
+ x = tl.load(KR + r * k_stride + d).to(tl.float32)
+ mean = tl.sum(x, axis=0) / D
+ xc = x - mean
+ var = tl.sum(xc * xc, axis=0) / D
+ y = xc / tl.sqrt(var + eps) * tl.load(LNW + d).to(tl.float32) + tl.load(LNB + d).to(tl.float32)
+ _ix_put(IK, row, d, y, D)
+ _ix_put(IG, row, d, tl.load(GR + r * D + d), D)
+
+
[email protected]
+def _seg_pool_keys(IK, IG, APE, PK, POS, BASE, D: tl.constexpr):
+ """Program r: the pool row r completes (pos[r] % 4 == 3), pool p = pos[r] // 4 of its stream, from tokens
+ base + 4p .. base + 4p + 3 into pooled row base / 4 + p: _pool_keys' arithmetic (the pools a single-stream
+ window completes are exactly those its rows end)."""
+
+ r = tl.program_id(0)
+ q = tl.load(POS + r).to(tl.int64)
+ if q % 4 != 3:
+ return
+ B = tl.load(BASE + r).to(tl.int64)
+ t = B + (q // 4) * 4
+ d = tl.arange(0, D)
+ l0 = _ix_get(IG, t + 0, d, D) + tl.load(APE + 0 * D + d).to(tl.float32)
+ l1 = _ix_get(IG, t + 1, d, D) + tl.load(APE + 1 * D + d).to(tl.float32)
+ l2 = _ix_get(IG, t + 2, d, D) + tl.load(APE + 2 * D + d).to(tl.float32)
+ l3 = _ix_get(IG, t + 3, d, D) + tl.load(APE + 3 * D + d).to(tl.float32)
+ m = tl.maximum(tl.maximum(l0, l1), tl.maximum(l2, l3))
+ e0 = tl.exp(l0 - m)
+ e1 = tl.exp(l1 - m)
+ e2 = tl.exp(l2 - m)
+ e3 = tl.exp(l3 - m)
+ s = ((e0 + e1) + e2) + e3
+ k0 = _ix_get(IK, t + 0, d, D)
+ k1 = _ix_get(IK, t + 1, d, D)
+ k2 = _ix_get(IK, t + 2, d, D)
+ k3 = _ix_get(IK, t + 3, d, D)
+ t0 = ((e0 / s).to(tl.bfloat16).to(tl.float32) * k0).to(tl.bfloat16).to(tl.float32)
+ t1 = ((e1 / s).to(tl.bfloat16).to(tl.float32) * k1).to(tl.bfloat16).to(tl.float32)
+ t2 = ((e2 / s).to(tl.bfloat16).to(tl.float32) * k2).to(tl.bfloat16).to(tl.float32)
+ t3 = ((e3 / s).to(tl.bfloat16).to(tl.float32) * k3).to(tl.bfloat16).to(tl.float32)
+ _pk_put(PK, B // 4 + q // 4, d, ((t0 + t1) + t2) + t3, D)
+
+
+def seg_index_update(k_raw: torch.Tensor, gate: torch.Tensor, ln_w: torch.Tensor, ln_b: torch.Tensor,
+ ape: torch.Tensor, ik: torch.Tensor, ig: torch.Tensor, pk: torch.Tensor, rows) -> None:
+ """index_update for a segmented window: each row's index key and gate at its stream's base + pos, then every
+ pool a row completes (``rows``: segments.SegRows)."""
+
+ R = k_raw.shape[0]
+ _seg_index_write[(R,)](k_raw, k_raw.stride(0), gate, ln_w, ln_b, ik, ig, rows.pos, rows.base, 1e-6, D=128,
+ num_warps=1)
+ _seg_pool_keys[(R,)](ik, ig, ape, pk, rows.pos, rows.base, D=128, num_warps=1)
+
+
[email protected]
+def _seg_scores(QI, W, w_stride, PK, OUT, o_stride, POS, SPR, SEG_START, SEG_ROWS, SEG_PBASE, SEG_POOLS, scale,
+ wscale, H: tl.constexpr, HP: tl.constexpr, D: tl.constexpr, BP: tl.constexpr, G: tl.constexpr):
+ """Program (segment, g): pool blocks g, g + G, .. below the segment's pool count (on the device: the pools its
+ last row sees), each block's keys (at the stream's pooled base) loaded once for all the segment's sparse rows;
+ a row's scores are _scores' (its keys masked to its own pools before the dot, as with RB > 1), written for its
+ visible pools only (the ones the selection reads)."""
+
+ s = tl.program_id(0)
+ g = tl.program_id(1)
+ npm = tl.load(SEG_POOLS + s)
+ nr = tl.load(SEG_ROWS + s)
+ r0 = tl.load(SEG_START + s)
+ pbase = tl.load(SEG_PBASE + s).to(tl.int64)
+ d = tl.arange(0, D)
+ hh = tl.arange(0, HP)
+ hok = hh < H
+ for pb in range(g, (npm + BP - 1) // BP, G):
+ p = pb * BP + tl.arange(0, BP)
+ k = _pk_get(PK, pbase + p, p < npm, d, D) # [BP, D]
+ for i in range(nr):
+ r = r0 + i
+ if tl.load(SPR + r) != 0:
+ npool = (tl.load(POS + r) + 1) // 4
+ q = tl.load(QI + (r * H + hh[:, None]) * D + d[None, :], mask=hok[:, None], other=0.0).to(tl.bfloat16)
+ kr = tl.where((p < npool)[:, None], k, 0.0)
+ dots = tl.dot(q, tl.trans(kr)) # [HP, BP] fp32
+ w = tl.load(W + r * w_stride + hh, mask=hok, other=0.0).to(tl.float32) * wscale
+ sc = tl.sum(w[:, None] * tl.maximum(dots * scale, 0.0), axis=0)
+ tl.store(OUT + r * o_stride + p, sc, mask=p < npool)
+
+
[email protected]
+def _seg_select(S, s_stride, POS, SPR, TOK, CNT, W: tl.constexpr, K: tl.constexpr, PL: tl.constexpr,
+ BLOCK: tl.constexpr):
+ """Program r (a sparse row): _select_rows over the row's visible pools, its K pools' tokens written as they are
+ taken (ascending), then _tokens' tail and count; a dense row gets count 0. Every single-stream path scores more
+ columns, but those lie past the row's visible pools, score -inf and have the highest indices: they rank below
+ every visible pool (ties go to the lower pool), so a row with more than K visible pools selects the same ones
+ (sparse._select_prompt)."""
+
+ r = tl.program_id(0).to(tl.int64)
+ if tl.load(SPR + r) == 0:
+ tl.store(CNT + r, 0)
+ return
+ qpos = tl.load(POS + r).to(tl.int64)
+ NP = (qpos + 1) // PL
+ row = S + r * s_stride
+ bins = tl.arange(0, 256)
+ prefix = tl.zeros((), dtype=tl.uint32)
+ fixed = tl.zeros((), dtype=tl.uint32)
+ need = K
+ for p in tl.static_range(4):
+ hist = tl.zeros((256,), dtype=tl.int32)
+ for c in range(0, NP, BLOCK):
+ i = c + tl.arange(0, BLOCK)
+ ok = i < NP
+ u = _order_key(tl.load(row + i, mask=ok, other=0.0))
+ match = ok & ((u & fixed) == prefix)
+ hist += tl.histogram(((u >> (24 - 8 * p)) & 0xFF).to(tl.int32), 256, mask=match)
+ at_or_above = tl.sum(hist, 0) - tl.cumsum(hist, 0) + hist
+ digit = tl.max(tl.where(at_or_above >= need, bins, 0), 0)
+ need -= tl.sum(tl.where(bins > digit, hist, 0), 0)
+ prefix = prefix | (digit.to(tl.uint32) << (24 - 8 * p))
+ fixed = fixed | (tl.full((), 0xFF, tl.uint32) << (24 - 8 * p))
+ written = 0
+ equal_seen = 0
+ j = tl.arange(0, PL)
+ for c in range(0, NP, BLOCK):
+ i = c + tl.arange(0, BLOCK)
+ ok = i < NP
+ u = _order_key(tl.load(row + i, mask=ok, other=0.0))
+ eq = (ok & (u == prefix)).to(tl.int32)
+ take = (ok & (u > prefix)) | ((eq == 1) & (tl.cumsum(eq, 0) - eq + equal_seen < need))
+ t = take.to(tl.int32)
+ slot = (written + tl.cumsum(t, 0) - t).to(tl.int64)
+ tl.store(TOK + r * W + slot[:, None] * PL + j[None, :], (i.to(tl.int64)[:, None] * PL + j[None, :]).to(tl.int32),
+ mask=take[:, None])
+ written += tl.sum(t, 0)
+ equal_seen += tl.sum(eq, 0)
+ jt = tl.arange(0, 4)
+ jok = jt < PL - 1
+ tail = NP * PL + jt
+ tok = jok & (tail <= qpos)
+ tl.store(TOK + r * W + K * PL + jt, tl.where(tok, tail, -1).to(tl.int32), mask=jok)
+ n = K * PL + tl.sum(tok.to(tl.int64), 0)
+ tl.store(CNT + r, tl.where(NP > K, n, 0).to(tl.int32))
+
+
+SEG_SCORE_GRID = 256 # _seg_scores programs a segment (grid stride over its pool blocks): speed only
+SEG_SPLIT = True # seg_select_tokens: the split selection (select_split), else one program a row (_seg_select)
+SEG_SELECT = (4096, 8) # _seg_select's scores a step and warps: speed only (the selection is exact integer logic)
+
+
+def seg_select_tokens(qi: torch.Tensor, wts: torch.Tensor, pk: torch.Tensor, rows, scratch) -> tuple[torch.Tensor,
+ torch.Tensor]:
+ """select_tokens for a segmented window: each sparse row's attended tokens [R, 2051] (relative to its stream,
+ ascending, -1 padded) and counts (0 for dense rows). Scores every segment's pools up to its device-side pool
+ count, so one CUDA graph per window size serves every context length (``scratch``: segments.SelectScratch)."""
+
+ if qi.stride(0) != qi.shape[1] or wts.stride(1) != 1:
+ raise ValueError("seg_select_tokens: index queries must be contiguous rows, weights unit-stride columns")
+ R = qi.shape[0]
+ if R > scratch.rows:
+ raise ValueError(f"seg_select_tokens: {R} rows, the scratch holds {scratch.rows}")
+ H = wts.shape[1]
+ D = qi.shape[1] // H
+ wscale = 1.0 / 5.656854249492381 if H == 32 else H ** -0.5 # select_tokens' constants
+ scores = scratch.scores
+ grid = min(SEG_SCORE_GRID, triton.cdiv(scores.shape[1], 64))
+ _seg_scores[(rows.max_segs, grid)](qi, wts, wts.stride(0), pk, scores, scores.stride(0), rows.pos, rows.sparse,
+ rows.seg_start, rows.seg_rows, rows.seg_pbase, rows.seg_pools, D ** -0.5,
+ wscale, H=H, HP=max(16, triton.next_power_of_2(H)), D=D, BP=64, G=grid,
+ num_warps=4)
+ tokens, counts = scratch.tokens[:R], scratch.counts[:R]
+ if SEG_SPLIT:
+ select_split(scores[:R], TOPK_POOLS, scratch=scratch.split, rows=rows, tokens=tokens, counts=counts)
+ return tokens, counts
+ _seg_select[(R,)](scores, scores.stride(0), rows.pos, rows.sparse, tokens, counts, W=TOKENS, K=TOPK_POOLS,
+ PL=POOL, BLOCK=SEG_SELECT[0], num_warps=SEG_SELECT[1])
+ return tokens, counts
+
+
+# ----------------------------------------------------------------------------------- split top-k selection ---
+# _select_rows' radix select with each row's scores split into CHS-score chunks, one program a (row, chunk), in five
+# launches. Passes 0..3: every program takes the digits so far from the row's total histograms (TOT, integer
+# atomic sums: exact in any order), keeps its chunk's count of scores above them (GT, first differing at an earlier
+# byte) and its chunk's histogram of the next byte (HIST), adding it into the row's total. Step 4 writes the chunk's
+# pools at the offset the earlier chunks' counts give (GT and their last histograms, which step 4 only reads):
+# scores above the K-th best, then ties in pool order. The same K-th best, ties and ascending output as
+# _select_rows: integers only, no floating-point sum order to keep.
+
[email protected]
+def _split_digits(TOT, r, STEPS: tl.constexpr, K: tl.constexpr):
+ """(prefix, fixed, need, last digit) after the first STEPS passes, from the row's total histograms."""
+ bins = tl.arange(0, 256)
+ prefix = tl.zeros((), dtype=tl.uint32)
+ fixed = tl.zeros((), dtype=tl.uint32)
+ need = tl.full((), K, tl.int32)
+ digit = tl.full((), 0, tl.int32)
+ for p in tl.static_range(STEPS):
+ hist = tl.load(TOT + (r * 4 + p) * 256 + bins)
+ at_or_above = tl.sum(hist, 0) - tl.cumsum(hist, 0) + hist
+ digit = tl.max(tl.where(at_or_above >= need, bins, 0), 0)
+ need -= tl.sum(tl.where(bins > digit, hist, 0), 0)
+ prefix = prefix | (digit.to(tl.uint32) << (24 - 8 * p))
+ fixed = fixed | (tl.full((), 0xFF, tl.uint32) << (24 - 8 * p))
+ return prefix, fixed, need, digit
+
+
[email protected]
+def _select_split(S, s_stride, NPC, POS, SPR, TOT, HIST, GT, OUT, TOK, CNT, W: tl.constexpr, K: tl.constexpr,
+ PL: tl.constexpr, CHS: tl.constexpr, CP: tl.constexpr, STEP: tl.constexpr, SEG: tl.constexpr):
+ """Program (row, chunk), STEP 0..3: pass STEP over the chunk; STEP 4: its selected pools, as pool ids OUT[r, :K]
+ (SEG False: NPC scores a row) or (SEG: the row's visible pools, dense rows skipped) as _seg_select's tokens,
+ tail and count. TOT [R, 4, 256] zeroed before step 0; HIST [R, CP, 256], GT [R, CP] int32."""
+
+ r = tl.program_id(0).to(tl.int64)
+ c = tl.program_id(1)
+ if SEG:
+ if tl.load(SPR + r) == 0:
+ if STEP == 4:
+ if c == 0:
+ tl.store(CNT + r, 0)
+ return
+ qpos = tl.load(POS + r).to(tl.int64)
+ NP = (qpos + 1) // PL
+ else:
+ qpos = 0
+ NP = NPC
+ nch = (NP + CHS - 1) // CHS
+ if c >= nch:
+ return
+ bins = tl.arange(0, 256)
+ i = c * CHS + tl.arange(0, CHS)
+ ok = i < NP
+ u = _order_key(tl.load(S + r * s_stride + i, mask=ok, other=0.0))
+ prefix, fixed, need, d = _split_digits(TOT, r, STEP, K)
+ own = HIST + (r * CP + c) * 256
+ if STEP > 0 and STEP < 4: # the chunk's scores above the prefix first at the byte just fixed
+ above = tl.sum(tl.where(bins > d, tl.load(own + bins), 0), 0)
+ if STEP > 1:
+ above += tl.load(GT + r * CP + c)
+ tl.store(GT + r * CP + c, above)
+ if STEP < 4:
+ match = ok & ((u & fixed) == prefix)
+ hist = tl.histogram(((u >> (24 - 8 * STEP)) & 0xFF).to(tl.int32), 256, mask=match)
+ tl.store(own + bins, hist)
+ tl.atomic_add(TOT + (r * 4 + STEP) * 256 + bins, hist)
+ else:
+ ci = tl.arange(0, CP)
+ before = ci < c
+ # earlier chunks: scores above the prefix at bytes 0..2 (GT), at byte 3 and equal to it (their last histograms)
+ last = tl.load(HIST + (r * CP + ci[:, None]) * 256 + bins[None, :], mask=before[:, None], other=0)
+ gt = tl.load(GT + r * CP + ci, mask=before, other=0) + tl.sum(tl.where(bins[None, :] > d, last, 0), 1)
+ equal_seen = tl.sum(tl.sum(tl.where(bins[None, :] == d, last, 0), 1), 0)
+ written = tl.sum(gt, 0) + tl.minimum(equal_seen, need)
+ e = (ok & (u == prefix)).to(tl.int32)
+ take = (ok & (u > prefix)) | ((e == 1) & (tl.cumsum(e, 0) - e + equal_seen < need))
+ t = take.to(tl.int32)
+ slot = (written + tl.cumsum(t, 0) - t).to(tl.int64)
+ if SEG:
+ j = tl.arange(0, PL)
+ tl.store(TOK + r * W + slot[:, None] * PL + j[None, :],
+ (i.to(tl.int64)[:, None] * PL + j[None, :]).to(tl.int32), mask=take[:, None])
+ if c == 0:
+ jt = tl.arange(0, 4)
+ jok = jt < PL - 1
+ tail = NP * PL + jt
+ tok = jok & (tail <= qpos)
+ tl.store(TOK + r * W + K * PL + jt, tl.where(tok, tail, -1).to(tl.int32), mask=jok)
+ n = K * PL + tl.sum(tok.to(tl.int64), 0)
+ tl.store(CNT + r, tl.where(NP > K, n, 0).to(tl.int32))
+ else:
+ tl.store(OUT + r * K + slot, i.to(tl.int64), mask=take)
+
+
+SPLIT_FROM = 8192 # decode windows split rows of at least this many scores (fewer: one program a row)
+SPLIT_ROWS = 64 # ... windows of fewer rows (prompt chunks' hundreds of rows fill the GPU as they are)
+SPLIT_WARPS = 4
+
+
+def split_chunk(np_: int) -> int:
+ """Scores a chunk program takes (speed only): 2,048 up to 16,384 a row, else 4,096."""
+ return 2048 if np_ <= 16384 else 4096
+
+
+def split_chunks(np_: int) -> int:
+ """Chunk programs a row of np_ scores takes (a power of two, the chunk tables' row stride)."""
+ return triton.next_power_of_2(triton.cdiv(np_, split_chunk(np_)))
+
+
+def split_scratch(rows: int, np_: int, device) -> torch.Tensor:
+ """select_split's int32 scratch for rows of np_ scores: totals [rows, 4, 256], then chunk histograms and counts."""
+ return torch.empty((rows * (1024 + split_chunks(np_) * 257),), dtype=torch.int32, device=device)
+
+
+def select_split(scores: torch.Tensor, k: int, *, scratch: torch.Tensor | None = None, rows=None,
+ tokens: torch.Tensor | None = None, counts: torch.Tensor | None = None) -> torch.Tensor | None:
+ """The split selection: top_pools' pools [R, k] (``rows`` None), or with ``rows`` (segments.SegRows) and
+ tokens / counts, seg_select_tokens' per-row output over each sparse row's visible pools. ``scratch``: at least
+ split_scratch(R, NP)'s (allocated when None)."""
+
+ R, NP = scores.shape
+ chs, warps = split_chunk(NP), SPLIT_WARPS
+ cp = split_chunks(NP)
+ if scratch is None or scratch.numel() < R * (1024 + cp * 257):
+ scratch = split_scratch(R, NP, scores.device)
+ tot = scratch[:R * 1024]
+ hist = scratch[R * 1024:R * (1024 + cp * 256)]
+ gt = scratch[R * (1024 + cp * 256):R * (1024 + cp * 257)]
+ tot.zero_()
+ seg = rows is not None
+ out = None if seg else torch.empty((R, k), dtype=torch.int64, device=scores.device)
+ dummy = scratch
+ for step in range(5):
+ _select_split[(R, cp)](scores, scores.stride(0), NP, rows.pos if seg else dummy, rows.sparse if seg else dummy,
+ tot, hist, gt, out if out is not None else dummy, tokens if seg else dummy,
+ counts if seg else dummy, W=TOKENS, K=k, PL=POOL, CHS=chs, CP=cp, STEP=step, SEG=seg,
+ num_warps=warps)
+ return out