GLM-5.3-Flash EXL3 on 2x DGX Spark with TensorFold
Python
Patch 0106: faster prefill at three Sparks - a prompt chunk's sparse latent attention as a CUDA kernel with the Triton kernel's exact instruction sequence
BadAd84931aa0ac504b
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 54a3f69..c81802b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -3,6 +3,20 @@Every change to this recipe, newest first. Each release names the image it serves: `scripts/prepare.sh` pulls`ghcr.io/miaai-lab/glm-5.3-flash-exl3-2x-dgx-sparks-tensorfold` by the digest pinned in `scripts/config.sh`.+## Unreleased++- **A prompt chunk's sparse attention in CUDA at three Sparks** (patch `0106-glm-sparse-onepass-cuda`, by+ [BadAd84](https://github.com/BadAd84)): `sparse_onepass.cu` computes every output of `_sparse_onepass` with the Triton kernel's own+ instruction sequence, read from its PTX (the mma chains and their K order, the online softmax's roundings+ and `ex2.approx`, the p-sum's reduction tree, `div.full`): the same bits under Triton 3.7. Producer warps gather and convert+ the FP8 rows two tiles ahead, q stays in registers, the softmax stays inside a warp, and 384 mma a tile+ instead of 768. FP8 caches with 17-24 heads a rank (22 / 21 at TP=3); 32 heads (TP=2) keep Triton. A+ 2,048-row chunk at 113k on one GB10: 7.98 -> 3.51 ms with recent selections, 8.72 -> 7.30 ms with+ spread ones. Live on three Sparks, cold prefill at 226k 103.58 -> 98.65 s (the first version), then+ 99.61 -> 98.53 s (the balanced warps). Built when the engine starts; under another Triton release+ (`sparse.TRITON_PTX`), or when the build fails, the Triton kernel serves (logged once).+ `TF_GLM_ONEPASS_CUDA=0`: Triton. Applies after `0105`. GPU check: `tools/sparse_onepass_check.py`.+## v1.10 (2026-10-08): the effort line at the tail (opt-in), a kept-state share, and a checked second railImage: `v0.6.0-a1897d591f70` (`sha256:bc34d7d63f978cf601f42863b284bc95a567c50c10e9adb0866a635be568bf5f`), 96 patches (v1.9.1's plus `0096`, `0097`). Tested live on twodiff --git a/CREDITS.md b/CREDITS.mdindex 521996e..10fb7b4 100644--- a/CREDITS.md+++ b/CREDITS.md@@ -139,6 +139,8 @@ checkpoint's ShapleyMcg attribution and the drafter's license).[kindling spark-os](https://github.com/kindlingai/kindling-spark-os) by Matt Mastracci (Kindling AI). Nothing ofdispram ships here: the ranks import the host's client (`python/dispram.py`, GPL-3.0 with a bundling exception)mounted read-only at run time and talk to `dispramd` (AGPL-3.0) over its socket.+- `0106-glm-sparse-onepass-cuda` (a prompt chunk's sparse attention in CUDA, Triton's instruction order):+ by [BadAd84](https://github.com/BadAd84).- `0090-glm-expert-launch-order` (`TF_GLM_EXL3_DEC_ORDER`: the launch order of the expert decode kernel's blocks): byLukasz Raczylo ([lukaszraczylo](https://github.com/lukaszraczylo)), in[PR #95](https://github.com/MiaAI-Lab/GLM-5.3-Flash-EXL3-2x-DGX-Sparks-TensorFold/pull/95).diff --git a/README.md b/README.mdindex 2bace9c..a5ca1b7 100644--- a/README.md+++ b/README.md@@ -522,6 +522,7 @@ sets a value wins: the environment, then `scripts/local.sh`, then `.env`, then t| `TF_ROCE_WAIT_S` | `300` | seconds a RoCE all-gather waits for the other Spark before it fails (1 to 3600; the patch's own default is 20, which a late peer on long prompts outlasted, issue #54); until the engine is built, each gather first meets the peer in an NCCL barrier, so a long first start (kernels compiling) does not run into it || `TF_GLM_MULTI_WINDOW` | `32`, `64` past 4 requests | with `PARALLEL` above 1, the rows of every request's verify window together in a round (16 to 64 in steps of 8): with more requests at once each one's drafts get fewer of them (8 requests' code: 141.2 / 160.3 / 167.0 tok/s at 32 / 48 / 64 rows); past 32 rows `TF_ROCE_MAX_KB` rises with it (64: 1024) unless you set it. Exact at any size || `TF_GLM_MULTI_LONE` | `0` | `1`: with `PARALLEL` above 1, a request decoding alone runs on the one-stream graphs (+0.6-0.9%), but its move to the pool's first rows evicts other conversations' kept prompts there (issues #12, #13); `0`: on the batched ones |+| `TF_GLM_ONEPASS_CUDA` | `1` | patch 0106: a prompt chunk's sparse attention from `sparse_onepass.cu` (the same bits as the Triton kernel under Triton 3.7, whose PTX it reproduces) on FP8 caches with 17-24 heads a rank (three Sparks; two keep Triton), built when the engine starts; `0`: the Triton kernel, which also serves (logged once) under another Triton release or when the build fails || `TF_GLM_CACHE_ENTRIES` | `32` | kept prompt states at most (TensorFold's default is 8); past this count a conversation's earlier (superseded) states go first, then the least recently used, however much of the pool is free (patch `0063`, @Alexbob0); shared-prefix states (a system block) go by recency only, so a new run of an agent still finds its system prompt (patch `0077`, issue #75, @meleesciony). An agent request keeps 1 to 3 (issue #17); each costs ~45 MiB at start, reserved out of the pool's `KV_POOL_GIB` budget (the pool shrinks by it, the estimate does not change), flat in the context length. Symptom of too few: `/health` `kept_prompts` stuck at the count while `pool_free_tokens` is large (issue #84, @jdecker76); see `TF_GLM_CACHE_SHARE_PCT` || `TF_GLM_CACHE_SHARE_PCT` | `0` (off) | make the kept-state count at least this share of the `KV_POOL_GIB` budget (patch `0097`, issue #84 by @jdecker76): on two Sparks at the defaults each state reserves ~91 MiB of a ~7.5 GiB budget, so 32 states already take ~38%: `50` gives ~42 states, the ceiling ~63 (each costs pool tokens), so the pool's tokens, not 32 finished one-shot conversations, decide when a live conversation goes. Any count is cut to three quarters of the budget (logged at start): past that the reservation would exceed the estimate. Set the same on every Spark || `TF_GLM_KEPT_BYTES_GIB` | `0` (no cap) | a byte budget for the kept states together (patch `0089`, by Thomas Wade, [ThomasWadeZ](https://github.com/ThomasWadeZ), PR #65): the device memory they own outside the pool (recurrent state, DFlash2 window copies: hundreds of MB each with long contexts); past it states are dropped in the entry cap's order (not written to the spill tier) and freed blocks go back to the driver. The author runs `4`; `kept_bytes` / `kept_bytes_cap` in `/health` |@@ -627,6 +628,7 @@ applied with `patch -p0` in filename order); `start.sh` rebuilds or re-pulls the| KV pool, kindling | `0087-glm-display-kv-dispram` | `0072`'s span with its reservation half from kindling spark-os's `dispramd` instead of a DRM dumb buffer, which kindling's `nvidia_drm` (no modeset) cannot make; the rest of `0072` runs unchanged (`DISPLAY_KV_BACKEND=dispram`) (by [BadAd84](https://github.com/BadAd84)) | 2032 MiB: +317,440 tokens at `PARALLEL=4` on three Sparks; the display check 53/53 || Prompt | `0001-glm-exl3-prompt-experts`, `0004-glm-prompt-kernels`, `0009-glm-prefill-kernels`, `0020-glm-prompt-experts-order`, `0024-glm-prompt-select-rows`, `0028-glm-lean-prompt-scratch` | EXL3 expert kernels that keep a prompt chunk's rows in L2, launched in a better order; each row's input rotated once; dense attention only where the sparse pass needs it; token selection in blocks of 512 rows; smaller prompt scratch | faster prefill, less memory at 1M || Prompt, indexer | `0086-glm-prompt-scores-loop` | a prompt chunk's indexer scoring (`0009`'s `_scores`) takes one row and 32 pool blocks a program (`SCORE_LOOP`), the row's queries loaded once, instead of 4 rows and one block (`TF_GLM_SCORE_RB`, retired), which reloaded every row's queries for each 64-pool block (by [BadAd84](https://github.com/BadAd84)) | the scoring 36% faster at long context (the part of a cold prefill that grows with it); cold prefill at 226k 138.3 -> 126.6 s; the same bits |+| Prompt, attention | `0106-glm-sparse-onepass-cuda` | a prompt chunk's sparse latent attention as a CUDA kernel (`sparse_onepass.cu`) with the Triton kernel's own instruction sequence (its PTX under Triton 3.7, `sparse.TRITON_PTX`), for FP8 caches and 17-24 heads a rank (TP=3); producer warps gather and convert the rows two tiles ahead, five P.V warps balance the schedulers; built at engine start (`TF_GLM_ONEPASS_CUDA`); under another Triton release, or when the build fails, the Triton kernel serves (by [BadAd84](https://github.com/BadAd84)) | TP=3: cold prefill at 226k 103.6 -> 98.7 s, then -1.1% more; the same bits (Triton 3.7) || Prompt, two Sparks | `0010-glm-hc-split`, `0033-glm-prefill-overlap2`, `0017-glm-overlap-priority`, `0022-glm-overlap-normal-priority`, `0064-glm-split-connect-early` | hyper-connection glue split by rows between the Sparks, exchanges overlapped with the next rows' work (`SPLIT`); the split's send/receive connection opened before the weights and the cache pool (issue #36) | 50k prefill ~1,270 -> ~1,730 tok/s with 0009 and 0020; decode rounds pay ~1.5% || Prompt, KDA | `0012-glm-kda-chunked`, `0014-glm-kda-chunked-gb10`, `0039-glm-kda-chunked-kernel` | the linear-attention layers' prompt chunks in chunked (WY) form, one CUDA kernel (`KDA_CHUNKED`) | 50k prefill 29.3 -> 26.4 s, 149k 91.1 -> 84.5 s (one start each) || Prompt reuse | `0008-glm-prompt-grid`, `0015-glm-shared-prefix`, `0042-glm-prompt-replay`, `0054-glm-image-prompt-reuse`, `0060-glm-keep-thinking`, `0063-glm-kept-cap-superseded-first`, `0071-glm-shared-prefix-copy`, `0077-glm-kept-cap-shared-by-recency`, `0078-glm-take-over-decide-then-copy` | prompt chunks and kept states on a token grid; a shared system prompt's state reused (copied out of the conversation that wrote it, which keeps its own state, by ezoushen, #43); an identical prompt resumes from its kept end state; prompts with pictures resume too, their kept states told apart by each picture's content (by abhicnv007, issue #11); earlier turns' reasoning kept in the prompt (`TF_GLM_CLEAR_THINKING`, by kky42, #23); past the kept-state cap a conversation's superseded states go first (by Alexbob0, #32), and shared-prefix states by recency only, so a new agent run still finds its system prompt (diagnosed and the fix proposed by meleesciony, #75); a fresh conversation after a long one clones only the kept states that stay, not every one first (reserved +14.8 -> +1.4 GiB after 256k, 21 turns; upstream #421) | [Performance](#performance) |@@ -711,6 +713,7 @@ with [sparkDash](https://github.com/MiaAI-Lab/sparkDash) ([Performance](#perform| `tools/needle.py [label] [size]` | hides a passphrase in a ~195k-token prompt (the prompt comes out at ~0.8 x `size` tokens) and checks the model returns it || `tools/toolcheck.py` | makes a tool call with an array parameter and checks it comes back as a JSON array || `tools/display_kv_check.py [--gpu]` | patch 0072's checks, run in the image (`docker run ... --entrypoint python`, see the file): the setting, the span's mapping and unwinding through a fake driver, the carved planes and the pool's copies; with `--gpu`, the real span on a Spark whose display reservation is free |+| `tools/sparse_onepass_check.py [--time]` | patch 0106's checks: `sparse_onepass.cu` against `_sparse_onepass` bit for bit (35k-590k, ragged counts, padding never read, NaN codes, arbitrary scales), a float64 oracle, the routing (32 heads and bf16 stay on Triton), the build at engine start, and the Triton kernel serving when the build fails or Triton is not 3.7; run in the image on one GPU (`docker run --gpus all ... --entrypoint python`, see the file); `--time` prints the old and new paths' times || `tools/pool_pressure.py [size]` | on a fresh server with nothing else sending requests: two conversations of ~`size` tokens (default 30000) take a turn each, others fill the pool, then each takes another turn; exit 1 when a turn resumes less than 90% of its previous prompt, 2 when the kept-prompt cap stops the fill first (a smaller pool runs it faster: `CONTEXT=131072 KV_POOL_GIB=0.5`) || `tools/pool_room_check.py` | patch 0074's checks, run in the image (`docker run ... --entrypoint python`, see the file): the pool's room-making on a CPU arena, what it evicts and moves, and rank 1 replaying the same ops || `tools/test_queued_cancellation.py --source-root DIR` | patch 0073's checks on the CPU, against TensorFold's source with the patches applied (no GPU, no server): requests that wait while every slot is busy and whose client leaves are dropped at once, in queue order; `--expect-stock` before 0073 shows the old wait |diff --git a/patches/0106-glm-sparse-onepass-cuda.patch b/patches/0106-glm-sparse-onepass-cuda.patchnew file mode 100644index 0000000..f0fa272--- /dev/null+++ b/patches/0106-glm-sparse-onepass-cuda.patch@@ -0,0 +1,616 @@+# A prompt chunk's sparse latent attention (latent._sparse_onepass) as a CUDA kernel (sparse_onepass.cu) that computes+# every output with the Triton kernel's own instruction sequence, read from its PTX: the mma chains and their K order,+# the online softmax's roundings and ex2.approx, the p-sum's reduction tree, div.full. Keys as the mma's M side (the+# GB10's mma.sync is operand-symmetric bit for bit), q in registers, softmax inside a warp, producer warps gathering and+# converting the FP8 rows two tiles ahead, five P.V warps balancing the SM's four schedulers. Every output is the Triton+# kernel's bit for bit. FP8 caches and 17-24 heads a rank only (TP=3's 22 / 21: the kernel holds 24 heads in three QK+# warps); TP=2's 32 heads keep Triton. Built / loaded by decode.Engine's constructor like patch 0105's, and like it+# not used (logged once; the Triton kernel serves) under another Triton release than sparse.TRITON_PTX (3.7) or when+# the build fails. TF_GLM_ONEPASS_CUDA=0: the Triton kernel. Applies after patch 0105 (decode.py's start-up loads, and+# sparse.TRITON_PTX). tools/sparse_onepass_check.py.++diff --git tensorfold/families/glm5_next/cuda/decode.py tensorfold/families/glm5_next/cuda/decode.py+--- tensorfold/families/glm5_next/cuda/decode.py++++ tensorfold/families/glm5_next/cuda/decode.py+@@ -202,6 +202,10 @@ class Engine:++ if sparse.prompt_scores_cuda():+ sparse._scores_ext()++ from . import latent++++ if latent.onepass_cuda(): # patch 0106: the prompt chunks' sparse attention, likewise++ latent._onepass_ext()+ self.slots = Slots(w, streams, max_rows)+ self.home = self.st = State(w, capacity, max_rows, caches=self.caches, slots=self.slots)+ self.last_hidden: torch.Tensor | None = None+diff --git tensorfold/families/glm5_next/cuda/latent.py tensorfold/families/glm5_next/cuda/latent.py+--- tensorfold/families/glm5_next/cuda/latent.py++++ tensorfold/families/glm5_next/cuda/latent.py+@@ -706,6 +706,46 @@ ONEPASS_TILE = (32, 32, 1) # heads per program (a rank's 32), keys per+ ONEPASS_LAUNCH = (8, 1, True)++++def onepass_cuda() -> bool:++ """TF_GLM_ONEPASS_CUDA (default on): sparse_onepass on an FP8 cache with the default tile and launch++ (ONEPASS_TILE, ONEPASS_LAUNCH) and 17-24 heads (TP=3's 22 / 21) runs sparse_onepass.cu, which computes every++ output with _sparse_onepass' own instruction sequence (its PTX: the mma chains and their K order, the online++ softmax's roundings, ex2.approx, the p-sum's reduction tree, div.full), so the same bits, with no repeated score++ blocks, the cache rows gathered and converted by producer warps and the P.V work split over five warps so each++ of the SM's four schedulers carries about the same tensor-core work; 0: the Triton kernel. Off as well when the++ extension is not used (another Triton release than sparse.TRITON_PTX, or a failed build or load:++ ``_onepass_ext``). tools/sparse_onepass_check.py."""++ return __import__("os").environ.get("TF_GLM_ONEPASS_CUDA", "1") != "0" and _ONEPASS_FAILED is None++++++_ONEPASS_EXT = None++_ONEPASS_FAILED = None # why sparse_onepass.cu is not used (then _sparse_onepass serves)++++++def _onepass_ext():++ """The extension, built / loaded once; None when it is not used (as patch 0105's ``sparse._scores_ext``)."""++ global _ONEPASS_EXT, _ONEPASS_FAILED++ if _ONEPASS_EXT is None and _ONEPASS_FAILED is None:++ from pathlib import Path++++ from tensorfold.cuda.build import load++++ from . import sparse++++ try:++ if not sparse.triton_matches_ptx():++ raise RuntimeError(f"Triton {triton.__version__}: the kernel reproduces Triton "++ f"{sparse.TRITON_PTX}'s PTX")++ _ONEPASS_EXT = load(name="tensorfold_glm_onepass_v1",++ sources=[str(Path(__file__).parent / "sparse_onepass.cu")],++ extra_cuda_cflags=["-O3"], verbose=False)++ except Exception as exc:++ _ONEPASS_FAILED = f"{type(exc).__name__}: {(str(exc).strip().splitlines() or [''])[-1][:200]}"++ print(f"[tensorfold] sparse_onepass.cu is not used ({_ONEPASS_FAILED}); prompt chunks' sparse attention "++ "runs the Triton kernel", flush=True)++ return _ONEPASS_EXT+++++ def sparse_onepass(qa: torch.Tensor, cache: torch.Tensor, tokens: torch.Tensor, counts: torch.Tensor,+ out: torch.Tensor, scale: float, *, tile: tuple | None = None, launch: tuple | None = None) -> None:+ """sparse_attention for a prompt chunk's rows: one program a row (and head group) walks every selected token in+@@ -721,6 +761,12 @@ def sparse_onepass(qa: torch.Tensor, cache: torch.Tensor, tokens: torch.Tensor,+ hbt, kt, split = tile or ONEPASS_TILE+ warps, stages, prefetch = launch or ONEPASS_LAUNCH+ hbt = max(16, min(hbt, triton.next_power_of_2(H))) # tensor-core tiles need 16 rows++ ext = (_onepass_ext() if fp8 and LW == 512 and 16 < H <= 24 and (hbt, kt, split) == (32, 32, 1)++ and (warps, stages, bool(prefetch)) == (8, 1, True) and tokens.dtype == torch.int32++ and counts.dtype == torch.int32 and onepass_cuda() else None)++ if ext is not None:++ ext.onepass(qa, cache, rs, tokens, counts, out, scale) # patch 0106: the same bits++ return+ _sparse_onepass[(R, triton.cdiv(H, hbt), split)](qa, vals, scl, tokens, counts, out, W=tokens.shape[1], H=H,+ LW=LW, SCALE=scale, HBT=hbt, KTT=kt, SPLIT=split, STAGES=stages,+ PREFETCH=bool(prefetch), RS=rs, FP8=fp8, num_warps=warps,+diff --git tensorfold/families/glm5_next/cuda/sparse_onepass.cu tensorfold/families/glm5_next/cuda/sparse_onepass.cu+new file mode 100644+--- /dev/null++++ tensorfold/families/glm5_next/cuda/sparse_onepass.cu+@@ -0,0 +1,523 @@++// Patch 0106: a prompt chunk's sparse latent attention (latent._sparse_onepass as sparse_onepass launches it by++// default: an FP8 latent cache, 512-wide rows, one program a row for TP=3's 22 / 21 heads, 32-key tiles, 8 warps,++// register prefetch) as a CUDA kernel that computes every output with the Triton kernel's own instruction sequence,++// read from its PTX / GPU IR, so every bit is the same. tools/sparse_onepass_check.py.++//++// The layout below was profiled (ncu PC sampling, a 113k 2,048-row chunk) and tuned with the same bits at every++// step. Against a first version with four P.V warps of 8 latent tiles (2,048-row chunks, "recent" selections at++// 113k and 590k: 0.926 of its time, 3.81 -> 3.53 ms; "spread", DRAM-bound, unchanged), each part measured as a++// paired ratio at 113k: the swizzle (swz: the producers' stores free of bank conflicts) alone 0.994; plus the P.V++// loop bounded by a per-warp tile count the compiler cannot see (pv_tiles) 0.956: then ptxas keeps the loop in++// source order (each m16 tile's ldmatrix one tile ahead, at most 6 mma at a time) instead of front-loading the++// ldmatrix and ending each tile in 21 back-to-back mma on a tensor pipe the QK warp's dependent score chains share++// (cuobjdump; the likely cause, not isolated further); plus five P.V warps sharing the 32 latent tiles++// 6 / 6 / 6 / 7 / 7, 0.927 (8 / 8 / 8 / 8 on the same twelve warps: 0.949).++//++// The Triton kernel, read from its PTX / GPU IR on a GB10 (Triton 3.7, mma layout warpsPerCTA [1, 8], kWidth 2):++// - the tile's 32 cache rows: e4m3 codes -> bf16 (cvt.rn.f16x2.e4m3x2, then cvt.bf16.f16 each), keys past the++// row's count zeros, their scales 1;++// - scores[heads, keys] = mma.sync m16n8k16 bf16 -> fp32 of q (heads past H zero) and the keys, each output one++// chain over the 32 k16 steps in ascending order from +0, k = 16 s .. 16 s + 15 in step s;++// - per element (dot * ks[key]) * SCALE, keys past the count -> -inf;++// - tile_m = max over the keys (any order: max is exact), active = tile_m != -inf, next_m = active ? max(m, tile_m)++// : m, alpha = active ? (m == -inf ? 0 : ex2.approx((m - next_m) * log2e)) : 1 (exp is mul.f32 by 0f3FB8AA3B,++// then ex2.approx.f32, no ftz);++// - p = (key valid and active) ? ex2.approx((score - next_m) * log2e) : 0;++// - o = the mma chain over the two 16-key steps (in order) of bf16(p * ks) and the keys, from o * alpha (Triton++// folds the + into the mma's accumulator);++// - l = fma(l, alpha, sum_k p), the sum in the layout's reduction tree: a lane's keys 2 u, 2 u + 1, then the lanes++// ^ 2, then ^ 1 over a warp's 8 keys, then the four 8-key partials (s0 + s2) + (s1 + s3);++// - out = bf16(div.full.f32(o, l)) for heads below H.++// Every operation below is that one in that order (explicit _rn intrinsics and inline PTX: no contraction or++// reassociation). Two measured facts of the GB10's mma.sync m16n8k16 bf16 let the work be laid out otherwise: it is++// symmetric in its operands bit for bit (keys x q^T gives the transpose of q x keys^T: 0 of 1.2e8 outputs differed)++// and the order of k inside a k16 step does not matter, so the keys are the M side here:++// - 3 QK warps hold q^T (8 heads each) in registers and run both 16-key halves' chains; a warp has its 8 heads'++// whole tile, so the max and the p-sums (the tree above, as lane shuffles ^ 4, ^ 16, ^ 8) never leave it, and++// tile t + 1's chains are issued between tile t's softmax stages;++// - 5 PV warps (o^T = keys^T . P^T over their share of the 32 latent m16 tiles) run a tile behind, from P and++// alpha in shared memory;++// - 4 producer warps gather the cache rows two tiles ahead and convert them into one of three bf16 key-tile buffers:++// exactly, on the integer and bf16 pipes (a code's sign-extended byte, shifted and masked, times 2^120), or by++// Triton's own sequence for a tile holding a NaN code;++// - named barriers hand the tiles and P along; Triton's 768 mma a tile (warps 4-7 repeated 0-3's scores and q's++// fragments were read from shared memory every tile) are 384 (heads padded to 24, not 32).++#include <ATen/cuda/CUDAContext.h>++#include <c10/cuda/CUDAGuard.h>++#include <cuda_bf16.h>++#include <stdint.h>++#include <torch/extension.h>++++namespace {++++constexpr int HQ = 24, LW = 512, KT = 32, NB = 3; // heads kept, latent width, keys a tile, key-tile buffers++constexpr int NV = 5, NQ = 3, NPW = 4; // PV, QK, producer warps (warp roles: see the kernel)++// PV warp v's share of the 32 latent m16 tiles (6 mma a tile each). A warp's scheduler is warp & 3; the QK warps++// (64 mma a tile, latency-bound score chains: ncu put 15% of their time in math-pipe stalls) sit on schedulers 0-2, so++// PV 0-2 take 6 tiles there and PV 3 / 4 (warps 3 and 7, both on scheduler 3) 7 each: 100 / 100 / 100 / 84 mma a++// tile a scheduler, where four PV warps of 8 tiles gave 112 / 112 / 112 / 48++__device__ __forceinline__ constexpr int pv_tiles(int v) { return v < 3 ? 6 : 7; }++constexpr int PV_MAX = 7; // the most tiles a PV warp takes++constexpr int NT = (NV + NQ + NPW) * 32;++constexpr int CH = LW * 2 / 16; // 16-byte chunks of a bf16 latent row (64)++constexpr int BAR_FULL = 1, BAR_EMPTY = 4, BAR_PREADY = 7, BAR_PFREE = 8, BAR_FIN = 9;++constexpr int N_FULL = (NPW + NQ) * 32, N_EMPTY = (NV + NPW) * 32, N_QV = (NQ + NV) * 32;++++__device__ __forceinline__ void mma16816(float (&d)[4], const uint32_t (&a)[4], uint32_t b0, uint32_t b1) {++ asm volatile("mma.sync.aligned.m16n8k16.row.col.f32.bf16.bf16.f32 {%0,%1,%2,%3}, {%4,%5,%6,%7}, {%8,%9}, "++ "{%0,%1,%2,%3};\n"++ : "+f"(d[0]), "+f"(d[1]), "+f"(d[2]), "+f"(d[3])++ : "r"(a[0]), "r"(a[1]), "r"(a[2]), "r"(a[3]), "r"(b0), "r"(b1));++}++++__device__ __forceinline__ void ldsm_x4(uint32_t (&r)[4], unsigned s) {++ asm volatile("ldmatrix.sync.aligned.m8n8.x4.shared.b16 {%0,%1,%2,%3}, [%4];\n"++ : "=r"(r[0]), "=r"(r[1]), "=r"(r[2]), "=r"(r[3])++ : "r"(s));++}++++__device__ __forceinline__ void ldsm_x4_t(uint32_t (&r)[4], unsigned s) {++ asm volatile("ldmatrix.sync.aligned.m8n8.x4.trans.shared.b16 {%0,%1,%2,%3}, [%4];\n"++ : "=r"(r[0]), "=r"(r[1]), "=r"(r[2]), "=r"(r[3])++ : "r"(s));++}++++__device__ __forceinline__ void bar_sync(int id, int n) { asm volatile("bar.sync %0, %1;" ::"r"(id), "r"(n) : "memory"); }++__device__ __forceinline__ void bar_arrive(int id, int n) {++ asm volatile("bar.arrive %0, %1;" ::"r"(id), "r"(n) : "memory");++}++++__device__ __forceinline__ float ex2(float x) {++ float y;++ asm("ex2.approx.f32 %0, %1;" : "=f"(y) : "f"(x));++ return y;++}++++__device__ __forceinline__ float div_full(float a, float b) {++ float y;++ asm("div.full.f32 %0, %1, %2;" : "=f"(y) : "f"(a), "f"(b));++ return y;++}++++__device__ __forceinline__ uint16_t bf16(float x) {++ uint16_t r;++ asm("cvt.rn.bf16.f32 %0, %1;" : "=h"(r) : "f"(x));++ return r;++}++++// Two e4m3 codes (low byte first) -> bf16x2 (low first) by Triton's own instruction sequence (its PTX: the codes to++// f16x2, then cvt.bf16.f16 each): used only for a tile holding a NaN code, whose NaN bits this keeps.++__device__ __forceinline__ uint32_t e4m3x2_bf16x2_tri(uint32_t two) {++ uint32_t r;++ const unsigned short v = (unsigned short)two;++ asm("{\n .reg .b32 a;\n .reg .f16 a<2>;\n .reg .b16 b<2>;\n cvt.rn.f16x2.e4m3x2 a, %1;\n mov.b32 {a0, a1}, a;\n"++ " cvt.bf16.f16 b0, a0;\n cvt.bf16.f16 b1, a1;\n mov.b32 %0, {b0, b1};\n}" : "=r"(r) : "h"(v));++ return r;++}++++// Four e4m3 codes -> two bf16x2 (codes 0, 1 and 2, 3) on the integer and bf16 pipes, exactly for every code but NaN:++// a code's sign-extended 16 bits, shifted left 4 and masked, are the bf16 with its sign, the 4 exponent bits and++// the 3 mantissa bits in place and 2^-120 of the value (a subnormal code a subnormal bf16), then times 2^120 (exact).++__device__ __forceinline__ void e4m3x4_bf16(uint32_t w, uint32_t& lo, uint32_t& hi) {++ uint32_t a, b;++ asm("prmt.b32 %0, %1, %2, %3;" : "=r"(a) : "r"(w), "r"(0u), "r"(0x9180u)); // [sext b1 | sext b0]++ asm("prmt.b32 %0, %1, %2, %3;" : "=r"(b) : "r"(w), "r"(0u), "r"(0xB3A2u)); // [sext b3 | sext b2]++ a = (a << 4) & 0x87F087F0u;++ b = (b << 4) & 0x87F087F0u;++ asm("mul.rn.bf16x2 %0, %1, %2;" : "=r"(lo) : "r"(a), "r"(0x7B807B80u)); // 2^120++ asm("mul.rn.bf16x2 %0, %1, %2;" : "=r"(hi) : "r"(b), "r"(0x7B807B80u));++}++++// a key tile's 16-byte chunk c of key r: c ^ ((r ^ (c >> 3)) & 7). Eight consecutive keys of one chunk (an ldmatrix's++// 8 rows, QK and PV) still fall in eight bank groups; a producer lane stores chunks 2 l and 2 l + 1 of one key, and++// with the (c >> 3) term lanes 0-3 and 4-7 of every quarter-warp land in different bank groups (a plain c ^ (r & 7):++// 2-way conflicts, 37 M of a 113k chunk's 243 M shared-memory wavefronts, ncu)++__device__ __forceinline__ int swz(int r, int c) { return c ^ ((r ^ (c >> 3)) & 7); }++__device__ __forceinline__ int pswz(int r, int c) { return c ^ ((r >> 1) & 3); }++++constexpr float LOG2E = 1.44269502162933349609375f; // 0f3FB8AA3B++++struct Smem {++ uint4 kt[NB][KT * CH]; // 96 KB: key tiles, bf16 [key][64 chunks], swizzled++ uint16_t ps[HQ * KT]; // P [head][key] bf16, 4 chunks a row, chunk-swizzled++ float ks[NB][KT];++ float alpha[HQ];++ float lsum[HQ];++};++++struct Raw {++ uint4 v[8];++ float s[8];++};++++__device__ __forceinline__ void ids_load(const int32_t* __restrict__ row, int n, int tile, int pw, int (&id)[8]) {++#pragma unroll++ for (int i = 0; i < 8; ++i) {++ const int k = tile * KT + pw + 4 * i;++ id[i] = k < n ? row[k] : -1;++ }++}++++__device__ __forceinline__ void raw_load(const uint8_t* __restrict__ LC, int RS, const int (&id)[8], int lane, Raw& r) {++#pragma unroll++ for (int i = 0; i < 8; ++i) {++ const uint8_t* src = LC + (size_t)(id[i] < 0 ? 0 : id[i]) * RS;++ r.v[i] = id[i] < 0 ? make_uint4(0, 0, 0, 0) : *reinterpret_cast<const uint4*>(src + 16 * lane);++ r.s[i] = id[i] < 0 || lane ? 1.0f : *reinterpret_cast<const float*>(src + LW);++ }++}++++__device__ __forceinline__ void convert(const Raw& r, uint4* kt, float* ks, int pw, int lane) {++ uint32_t nan = 0; // bit 7 of a byte: some code of it was 0x7F / 0xFF++#pragma unroll++ for (int i = 0; i < 8; ++i) {++ const uint32_t in[4] = {r.v[i].x, r.v[i].y, r.v[i].z, r.v[i].w};++#pragma unroll++ for (int q = 0; q < 4; ++q) nan |= (in[q] & 0x7F7F7F7Fu) + 0x01010101u;++ }++ if (__any_sync(0xffffffffu, nan & 0x80808080u)) {++#pragma unroll++ for (int i = 0; i < 8; ++i) {++ const int key = pw + 4 * i;++ const uint32_t in[4] = {r.v[i].x, r.v[i].y, r.v[i].z, r.v[i].w};++ uint32_t w[8];++#pragma unroll++ for (int m = 0; m < 8; ++m) w[m] = e4m3x2_bf16x2_tri(in[m >> 1] >> (16 * (m & 1)));++ kt[key * CH + swz(key, 2 * lane)] = make_uint4(w[0], w[1], w[2], w[3]);++ kt[key * CH + swz(key, 2 * lane + 1)] = make_uint4(w[4], w[5], w[6], w[7]);++ if (lane == 0) ks[key] = r.s[i];++ }++ return;++ }++#pragma unroll++ for (int i = 0; i < 8; ++i) {++ const int key = pw + 4 * i;++ const uint32_t in[4] = {r.v[i].x, r.v[i].y, r.v[i].z, r.v[i].w};++ uint32_t w[8];++#pragma unroll++ for (int q = 0; q < 4; ++q) e4m3x4_bf16(in[q], w[2 * q], w[2 * q + 1]);++ kt[key * CH + swz(key, 2 * lane)] = make_uint4(w[0], w[1], w[2], w[3]);++ kt[key * CH + swz(key, 2 * lane + 1)] = make_uint4(w[4], w[5], w[6], w[7]);++ if (lane == 0) ks[key] = r.s[i];++ }++}++++__global__ void __launch_bounds__(NT, 1) onepass_kernel(const __nv_bfloat16* __restrict__ QA,++ const uint8_t* __restrict__ LC, int RS,++ const int32_t* __restrict__ TOK, int W,++ const int32_t* __restrict__ CNT,++ __nv_bfloat16* __restrict__ OUT, int H, float scale) {++ extern __shared__ __align__(16) uint8_t smem_raw[];++ Smem& S = *reinterpret_cast<Smem*>(smem_raw);++ const int r = blockIdx.x;++ const int n = CNT[r];++ if (n <= 0) return;++ const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31, g = lane >> 2, t4 = lane & 3;++ const int ntile = (n + KT - 1) / KT;++ const int32_t* row = TOK + (size_t)r * W;++++ // warps 0-3 PV 0-3, 4-6 QK, 7 PV 4, 8-11 producers++ if (warp >= 8) {++ // ---------------------------------------------------- producers: keys pw + 4 i, 16 B a lane, two tiles ahead++ const int pw = warp - 8;++ Raw A, B;++ int ia[8], ib[8];++ ids_load(row, n, 0, pw, ia);++ ids_load(row, n, 1, pw, ib);++ raw_load(LC, RS, ia, lane, A);++ raw_load(LC, RS, ib, lane, B);++ ids_load(row, n, 2, pw, ia);++ ids_load(row, n, 3, pw, ib);++ int b = 0;++ for (int t = 0; t < ntile; t += 2) {++ if (t >= NB) bar_sync(BAR_EMPTY + b, N_EMPTY);++ convert(A, S.kt[b], S.ks[b], pw, lane);++ bar_arrive(BAR_FULL + b, N_FULL);++ b = b + 1 == NB ? 0 : b + 1;++ if (t + 2 < ntile) {++ raw_load(LC, RS, ia, lane, A);++ ids_load(row, n, t + 4, pw, ia);++ }++ if (t + 1 >= ntile) break;++ if (t + 1 >= NB) bar_sync(BAR_EMPTY + b, N_EMPTY);++ convert(B, S.kt[b], S.ks[b], pw, lane);++ bar_arrive(BAR_FULL + b, N_FULL);++ b = b + 1 == NB ? 0 : b + 1;++ if (t + 3 < ntile) {++ raw_load(LC, RS, ib, lane, B);++ ids_load(row, n, t + 5, pw, ib);++ }++ }++ return;++ }++++ if (warp >= 4 && warp < 7) {++ // ------------------------------------------------- QK warps: heads 8 j .. 8 j + 7 (an n8 tile), all 32 keys++ const int j = warp - 4;++ const int hq = 8 * j + g; // this lane's B column (head)++ uint32_t qf[32][2]; // q^T B fragments: step s, k = 16 s + 2 t (+ 8)++#pragma unroll++ for (int s = 0; s < 32; ++s) {++ const __nv_bfloat16* q = QA + ((size_t)r * H + (hq < H ? hq : 0)) * LW + 16 * s + 2 * t4;++ qf[s][0] = hq < H ? *reinterpret_cast<const uint32_t*>(q) : 0u;++ qf[s][1] = hq < H ? *reinterpret_cast<const uint32_t*>(q + 8) : 0u;++ }++ float m[2] = {-INFINITY, -INFINITY}, l[2] = {0.0f, 0.0f}; // heads 8 j + 2 t, + 1++ const int ar = lane & 15, ac = lane >> 4;++ // QK(t + 1)'s 32 steps are issued between softmax(t)'s stages, so the in-order warp has the score chains'++ // mma in flight while it waits on the softmax's shuffles and ex2 (and the other way round)++ uint32_t a[3][2][4];++ unsigned ktn;++ float acc[2][4], accn[2][4];++#define LOADA(slot, s) \++ { \++ ldsm_x4(a[slot][0], ktn + 16 * (ar * CH + swz(ar, 2 * (s) + ac))); \++ ldsm_x4(a[slot][1], ktn + 16 * ((16 + ar) * CH + swz(16 + ar, 2 * (s) + ac))); \++ }++#define QKSTEP(s) \++ { \++ if ((s) + 2 < 32) LOADA(((s) + 2) % 3, (s) + 2) \++ mma16816(accn[0], a[(s) % 3][0], qf[s][0], qf[s][1]); \++ mma16816(accn[1], a[(s) % 3][1], qf[s][0], qf[s][1]); \++ }++#define QKBEGIN() \++ { \++ for (int i_ = 0; i_ < 2; ++i_) \++ for (int e_ = 0; e_ < 4; ++e_) accn[i_][e_] = 0.0f; \++ LOADA(0, 0) \++ LOADA(1, 1) \++ }++ bar_sync(BAR_FULL + 0, N_FULL);++ ktn = (unsigned)__cvta_generic_to_shared(S.kt[0]);++ QKBEGIN()++#pragma unroll++ for (int s = 0; s < 32; ++s) QKSTEP(s)++#pragma unroll++ for (int i = 0; i < 2; ++i)++#pragma unroll++ for (int e = 0; e < 4; ++e) acc[i][e] = accn[i][e];++ int b = 0;++ for (int t = 0; t < ntile; ++t) {++ const int t0 = t * KT, bn = b + 1 == NB ? 0 : b + 1;++ if (t + 1 < ntile) bar_sync(BAR_FULL + bn, N_FULL);++ // the last tile's "next" scores run on its own buffer and are dropped (no branch in the block below)++ ktn = (unsigned)__cvta_generic_to_shared(S.kt[t + 1 < ntile ? bn : b]);++ QKBEGIN()++#pragma unroll++ for (int s = 0; s < 8; ++s) QKSTEP(s)++ // acc[i][e]: key 16 i + g (e < 2) or 16 i + 8 + g (e >= 2), head 8 j + 2 t + (e & 1)++ float sc[2][4], kk[2][2];++ bool val[2][2];++#pragma unroll++ for (int i = 0; i < 2; ++i)++#pragma unroll++ for (int hi = 0; hi < 2; ++hi) {++ const int key = 16 * i + 8 * hi + g;++ kk[i][hi] = S.ks[b][key];++ val[i][hi] = t0 + key < n;++#pragma unroll++ for (int e = 0; e < 2; ++e)++ sc[i][2 * hi + e] =++ val[i][hi] ? __fmul_rn(__fmul_rn(acc[i][2 * hi + e], kk[i][hi]), scale) : -INFINITY;++ }++ float nm[2], alpha[2];++ bool act[2];++#pragma unroll++ for (int e = 0; e < 2; ++e) {++ float x = fmaxf(fmaxf(sc[0][e], sc[0][2 + e]), fmaxf(sc[1][e], sc[1][2 + e]));++ x = fmaxf(x, __shfl_xor_sync(0xffffffffu, x, 4));++ x = fmaxf(x, __shfl_xor_sync(0xffffffffu, x, 8));++ x = fmaxf(x, __shfl_xor_sync(0xffffffffu, x, 16));++ act[e] = x != -INFINITY;++ nm[e] = act[e] ? fmaxf(m[e], x) : m[e];++ const float a_ = m[e] == -INFINITY ? 0.0f : ex2(__fmul_rn(__fsub_rn(m[e], nm[e]), LOG2E));++ alpha[e] = act[e] ? a_ : 1.0f;++ }++#pragma unroll++ for (int s = 8; s < 16; ++s) QKSTEP(s)++ float p[2][4];++#pragma unroll++ for (int i = 0; i < 2; ++i)++#pragma unroll++ for (int x = 0; x < 4; ++x) {++ const int e = x & 1;++ p[i][x] = val[i][x >> 1] && act[e] ? ex2(__fmul_rn(__fsub_rn(sc[i][x], nm[e]), LOG2E)) : 0.0f;++ }++#pragma unroll++ for (int s = 16; s < 24; ++s) QKSTEP(s)++ // the p sums in Triton's tree: key group w = 2 i + hi (keys 8 w .. 8 w + 7, this lane's key 8 w + g):++ // (p[2u] + p[2u + 1]) over u, then u ^ 2, then u ^ 1 (lanes ^ 4, ^ 16, ^ 8), then (s0 + s2) + (s1 + s3)++ float sw[4][2];++#pragma unroll++ for (int i = 0; i < 2; ++i)++#pragma unroll++ for (int hi = 0; hi < 2; ++hi)++#pragma unroll++ for (int e = 0; e < 2; ++e) {++ float y = p[i][2 * hi + e];++ y = __fadd_rn(y, __shfl_xor_sync(0xffffffffu, y, 4));++ y = __fadd_rn(y, __shfl_xor_sync(0xffffffffu, y, 16));++ y = __fadd_rn(y, __shfl_xor_sync(0xffffffffu, y, 8));++ sw[2 * i + hi][e] = y;++ }++#pragma unroll++ for (int e = 0; e < 2; ++e) {++ const float tot = __fadd_rn(__fadd_rn(sw[0][e], sw[2][e]), __fadd_rn(sw[1][e], sw[3][e]));++ l[e] = __fmaf_rn(l[e], alpha[e], tot);++ m[e] = nm[e];++ }++#pragma unroll++ for (int s = 24; s < 32; ++s) QKSTEP(s)++ if (t > 0) bar_sync(BAR_PFREE, N_QV); // the PV warps have read the previous P and alphas++#pragma unroll++ for (int i = 0; i < 2; ++i)++#pragma unroll++ for (int x = 0; x < 4; ++x) {++ const int h = 8 * j + 2 * t4 + (x & 1), key = 16 * i + 8 * (x >> 1) + g;++ S.ps[h * KT + 8 * pswz(h, key >> 3) + (key & 7)] = bf16(__fmul_rn(p[i][x], kk[i][x >> 1]));++ }++ if (g == 0) {++ S.alpha[8 * j + 2 * t4] = alpha[0];++ S.alpha[8 * j + 2 * t4 + 1] = alpha[1];++ }++ bar_arrive(BAR_PREADY, N_QV);++#pragma unroll++ for (int i = 0; i < 2; ++i)++#pragma unroll++ for (int e = 0; e < 4; ++e) acc[i][e] = accn[i][e];++ b = bn;++ }++#undef QKSTEP++#undef QKBEGIN++#undef LOADA++ if (g == 0) {++ S.lsum[8 * j + 2 * t4] = l[0];++ S.lsum[8 * j + 2 * t4 + 1] = l[1];++ }++ bar_arrive(BAR_FIN, N_QV);++ return;++ }++++ // ------------------------------------------------- PV warps: latent rows 16 tb .. 16 (tb + nt) - 1 (nt m16 tiles)++ const int v = warp < 4 ? warp : 4;++ const int nt = pv_tiles(v);++ int tb = 0;++#pragma unroll++ for (int k = 0; k < NV - 1; ++k) tb += k < v ? pv_tiles(k) : 0;++ float o[PV_MAX][3][4];++#pragma unroll++ for (int i = 0; i < PV_MAX; ++i)++#pragma unroll++ for (int nh = 0; nh < 3; ++nh)++#pragma unroll++ for (int e = 0; e < 4; ++e) o[i][nh][e] = 0.0f;++ const unsigned psb = (unsigned)__cvta_generic_to_shared(S.ps);++ const int vk = (lane & 7) + 8 * (lane >> 4), vc = (lane >> 3) & 1;++ int b = 0;++ for (int t = 0; t < ntile; ++t) {++ const unsigned ktb = (unsigned)__cvta_generic_to_shared(S.kt[b]);++ bar_sync(BAR_PREADY, N_QV);++ uint32_t pb[3][4]; // P^T B fragments: heads 8 nh .., keys 0-15 (0, 1), 16-31++#pragma unroll++ for (int nh = 0; nh < 3; ++nh) {++ const int h = 8 * nh + (lane & 7), c = lane >> 3;++ ldsm_x4(pb[nh], psb + 2 * (h * KT + 8 * pswz(h, c)));++ }++ float al[3][2];++#pragma unroll++ for (int nh = 0; nh < 3; ++nh) {++ al[nh][0] = S.alpha[8 * nh + 2 * t4];++ al[nh][1] = S.alpha[8 * nh + 2 * t4 + 1];++ }++ if (t + 1 < ntile) bar_arrive(BAR_PFREE, N_QV); // the QK warps write the next P only after this++ bool one = true;++#pragma unroll++ for (int nh = 0; nh < 3; ++nh) one = one && al[nh][0] == 1.0f && al[nh][1] == 1.0f;++ if (!__all_sync(0xffffffffu, one)) {++#pragma unroll++ for (int i = 0; i < PV_MAX; ++i)++ if (i < nt)++#pragma unroll++ for (int nh = 0; nh < 3; ++nh)++#pragma unroll++ for (int e = 0; e < 4; ++e) o[i][nh][e] = __fmul_rn(o[i][nh][e], al[nh][e & 1]);++ }++ uint32_t a[2][2][4]; // K^T A fragments, two m16 tiles in flight++#define LOADV(slot, i) \++ { \++ ldsm_x4_t(a[slot][0], ktb + 16 * (vk * CH + swz(vk, 2 * (tb + (i)) + vc))); \++ ldsm_x4_t(a[slot][1], ktb + 16 * ((16 + vk) * CH + swz(16 + vk, 2 * (tb + (i)) + vc))); \++ }++ LOADV(0, 0)++#pragma unroll++ for (int i = 0; i < PV_MAX; ++i) {++ if (i < nt) {++ if (i + 1 < nt) LOADV((i + 1) & 1, i + 1)++#pragma unroll++ for (int nh = 0; nh < 3; ++nh) mma16816(o[i][nh], a[i & 1][0], pb[nh][0], pb[nh][1]);++#pragma unroll++ for (int nh = 0; nh < 3; ++nh) mma16816(o[i][nh], a[i & 1][1], pb[nh][2], pb[nh][3]);++ }++ }++#undef LOADV++ if (t + NB < ntile) bar_arrive(BAR_EMPTY + b, N_EMPTY);++ b = b + 1 == NB ? 0 : b + 1;++ }++ bar_sync(BAR_FIN, N_QV);++ float lv[3][2];++#pragma unroll++ for (int nh = 0; nh < 3; ++nh) {++ lv[nh][0] = S.lsum[8 * nh + 2 * t4];++ lv[nh][1] = S.lsum[8 * nh + 2 * t4 + 1];++ }++ // out[r, h, 16 tb ..] = bf16(o / l): staged as [head][512] in the key-tile buffer no warp reads any more++ uint16_t* st = reinterpret_cast<uint16_t*>(S.kt[ntile % NB]);++#pragma unroll++ for (int i = 0; i < PV_MAX; ++i)++ if (i < nt)++#pragma unroll++ for (int nh = 0; nh < 3; ++nh)++#pragma unroll++ for (int e = 0; e < 4; ++e) {++ const int h = 8 * nh + 2 * t4 + (e & 1), lat = 16 * (tb + i) + g + 8 * (e >> 1);++ st[h * LW + lat] = bf16(div_full(o[i][nh][e], lv[nh][e & 1]));++ }++ __syncwarp();++ for (int c = lane; c < H * 2 * nt; c += 32) {++ const int h = c / (2 * nt), q = c - h * 2 * nt;++ *reinterpret_cast<uint4*>(OUT + ((size_t)r * H + h) * LW + 16 * tb + 8 * q) =++ *reinterpret_cast<const uint4*>(st + h * LW + 16 * tb + 8 * q);++ }++}++++} // namespace++++// latent.sparse_onepass on an FP8 cache: QA [R, H, 512] bf16 (H <= 24), LC the cache's rows (512 e4m3 codes, then++// the row's fp32 scale; RS bytes apart), TOK [R, W] int32 token ids (the first CNT[r] of row r read), CNT [R] int32,++// OUT [R, H, 512] bf16 (rows with CNT 0 left alone), scale the softmax scale. One CTA a row.++void onepass(const at::Tensor& QA, const at::Tensor& LC, int64_t RS, const at::Tensor& TOK, const at::Tensor& CNT,++ at::Tensor OUT, double scale) {++ TORCH_CHECK(QA.is_cuda() && QA.scalar_type() == at::kBFloat16 && OUT.scalar_type() == at::kBFloat16 &&++ LC.element_size() == 1 && TOK.scalar_type() == at::kInt && CNT.scalar_type() == at::kInt,++ "sparse onepass: dtypes");++ TORCH_CHECK(QA.dim() == 3 && QA.size(2) == LW && QA.size(1) <= HQ && QA.is_contiguous() && OUT.is_contiguous() &&++ OUT.sizes() == QA.sizes() && TOK.is_contiguous() && TOK.dim() == 2 && TOK.size(0) == QA.size(0) &&++ CNT.numel() >= QA.size(0) && LC.is_contiguous(), "sparse onepass: shapes");++ TORCH_CHECK(RS % 16 == 0 && RS >= LW + 4, "sparse onepass: an FP8 cache of 16-byte aligned rows");++ const int R = (int)QA.size(0);++ if (R == 0) return;++ const c10::cuda::CUDAGuard guard(QA.device());++ static bool attr = false;++ if (!attr) {++ C10_CUDA_CHECK(cudaFuncSetAttribute(onepass_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize,++ (int)sizeof(Smem)));++ attr = true;++ }++ onepass_kernel<<<R, NT, sizeof(Smem), at::cuda::getCurrentCUDAStream()>>>(++ reinterpret_cast<const __nv_bfloat16*>(QA.data_ptr()), reinterpret_cast<const uint8_t*>(LC.data_ptr()),++ (int)RS, TOK.data_ptr<int32_t>(), (int)TOK.size(1), CNT.data_ptr<int32_t>(),++ reinterpret_cast<__nv_bfloat16*>(OUT.data_ptr()), (int)QA.size(1), (float)scale);++ C10_CUDA_KERNEL_LAUNCH_CHECK();++}++++PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def("onepass", &onepass); }diff --git a/tools/sparse_onepass_check.py b/tools/sparse_onepass_check.pynew file mode 100644index 0000000..c0a0516--- /dev/null+++ b/tools/sparse_onepass_check.py@@ -0,0 +1,301 @@+#!/usr/bin/env python3+"""tools/sparse_onepass_check.py [--time]: patch 0106 - a prompt chunk's sparse latent attention+(latent._sparse_onepass, Triton) as a CUDA kernel (sparse_onepass.cu) for FP8 caches and 17-24 heads a rank (TP=3's+22 / 21) that computes every output with the Triton kernel's own instruction sequence. Run in the image built with+patch 0106, on one GPU:+docker run --rm --gpus all --entrypoint python -v "$PWD/tools/sparse_onepass_check.py:/c.py" <image> /c.py++1. Kernel: the whole [R, H, 512] output (pre-filled with NaN, so rows it must leave alone and slots it never writes+ show) equals the Triton kernel's (latent._sparse_onepass, launched by sparse_onepass with TF_GLM_ONEPASS_CUDA=0)+ bit for bit: 2,048-row prompt chunks, 22 heads (and 21), FP8 latent rows from kv8.quantize_rows, softmax scale+ 1/16, int32 token lists 2,051 wide at positions 35k / 113k / 300k / 590k, two selections ("recent": each row's+ last 2,051 tokens; "spread": 512 random pools below the row), counts 2,048-2,051 with a few short and empty rows;+ ragged counts 0-2,051, 1,024- and 333-row chunks, padding past the counts that must never be read (-1, a row of+ NaN codes, out of range), NaN codes in rows that are read (Triton's NaN bits), and arbitrary (not power-of-two)+ row scales with a non-power-of-two softmax scale, which pin the order of every product in the chain.+2. Oracle: against float64 attention from the dequantized rows (softmax(scale q . k) . k), within bf16 tolerance.+3. The entry point: latent.sparse_onepass launches the CUDA kernel (counted) with TF_GLM_ONEPASS_CUDA=1 and gives the+ bits it gives with =0 (Triton, not launched); 32 heads a rank (TP=2) and a bf16 cache stay on Triton.+4. Start-up: decode.Engine's constructor loads (on a fresh image, builds) the extension before any request for FP8+ caches with DSA layers and the switch on; not with TF_GLM_ONEPASS_CUDA=0, a bf16 cache or no DSA layer (the+ constructor run with stand-ins for what it builds; the loader counted).+5. The extension not used - a failed build or load (the loader raising), or another Triton release than+ sparse.TRITON_PTX (the loader then never called): nothing raised, logged once and not retried, the switch reads off,+ and latent.sparse_onepass gives the Triton kernel's output.+One PASS / FAIL line a check; exits 1 on any FAIL (on an image without the patch: at the first check).++--time: a 2,048-row chunk at 113k and 590k, "recent" and "spread" selections, Triton -> CUDA (CUDA events), 22 and+21 heads (TP=3's ranks); at 32 heads (TP=2) the kernel does not run."""+import os+import statistics+import sys+from types import SimpleNamespace++import torch++from tensorfold.families.glm5_next.cuda import decode, forward, hcsplit, kv8, latent++R, LW, NSEL = 2048, 512, 2051+SCALE = 256 ** -0.5+fails = 0+++def check(ok, msg):+ global fails+ print(("PASS " if ok else "FAIL ") + msg, flush=True)+ fails += not ok+++def ms(fn, n=5):+ fn()+ torch.cuda.synchronize()+ out = []+ for _ in range(3):+ a, b = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)+ a.record()+ for _ in range(n):+ fn()+ b.record()+ torch.cuda.synchronize()+ out.append(a.elapsed_time(b) / n)+ return statistics.median(out)+++class Count:+ """latent's CUDA extension, its ``onepass`` calls counted."""++ def __init__(self, ext):+ self.ext, self.calls = ext, 0++ def onepass(self, *a):+ self.calls += 1+ return self.ext.onepass(*a)+++def selection(kind, P, rows, dev):+ """[rows, 2,051] int32 token lists of rows at positions P .. P + rows - 1 (ascending)."""+ r = torch.arange(rows, device=dev)+ if kind == "recent":+ return (P + r[:, None] - (NSEL - 1) + torch.arange(NSEL, device=dev)[None, :]).to(torch.int32).contiguous()+ out = torch.empty((rows, NSEL), dtype=torch.int32, device=dev)+ for a in range(0, rows, 256):+ b = min(rows, a + 256)+ pools = torch.sort(torch.rand(b - a, P // 4, device=dev).topk(512, dim=1).indices, dim=1).values+ out[a:b, :2048] = (pools[:, :, None] * 4 + torch.arange(4, device=dev)).reshape(b - a, 2048).to(torch.int32)+ out[:, 2048:] = (((P + r) // 4 * 4)[:, None] + torch.arange(3, device=dev)[None, :]).to(torch.int32)+ return out+++def run(qa, cache, tok, counts, scale, cuda):+ os.environ["TF_GLM_ONEPASS_CUDA"] = "1" if cuda else "0"+ out = torch.full_like(qa, float("nan"))+ latent.sparse_onepass(qa, cache, tok, counts, out, scale)+ torch.cuda.synchronize()+ return out+++def compare(name, qa, cache, tok, counts, scale=SCALE):+ ref = run(qa, cache, tok, counts, scale, False)+ out = run(qa, cache, tok, counts, scale, True)+ a, b = ref.view(torch.int16), out.view(torch.int16)+ diff = int((a != b).sum())+ left = int(out[counts == 0].isnan().all()) if bool((counts == 0).any()) else 1+ check(diff == 0 and left == 1, f"{name}: CUDA == Triton bit for bit ({diff} of {out.numel()} differ; rows with "+ f"count 0 left alone: {bool(left)})")+ return ref, out+++def oracle(qa, cache, tok, counts, out, rows, scale):+ """Max |out - float64 attention| / max |attention| over the given rows."""+ codes = cache[:, :LW].contiguous().view(torch.float8_e4m3fn)+ ks = cache[:, LW:LW + 4].contiguous().view(torch.float32)[:, 0]+ worst = 0.0+ for r in rows:+ n = int(counts[r])+ ids = tok[r, :n].long()+ kv = codes[ids].double() * ks[ids].double()[:, None] # [n, 512] dequantized rows+ s = (qa[r].double() @ kv.T) * float(torch.tensor(scale, dtype=torch.float32))+ o = torch.softmax(s, dim=1) @ kv+ worst = max(worst, ((out[r].double() - o).abs().max() / o.abs().max()).item())+ return worst+++def construct(loader, kv, kinds=("dsa",)):+ """decode.Engine's constructor with stand-ins for the buffers, caches, slots and state it builds; ``loader``+ (``module.name``) counted, nothing built. Returns its calls."""+ mod, name = loader+ calls = []+ real = getattr(mod, name)+ saved = [(decode, "Buffers"), (decode, "State"), (forward, "Caches"), (forward, "Slots"), (forward, "index_ring"),+ (hcsplit, "buffer_rows")]+ saved = [(m, a, getattr(m, a)) for m, a in saved]+ stub = SimpleNamespace+ try:+ setattr(mod, name, lambda: calls.append(name))+ decode.Buffers = decode.State = forward.Caches = forward.Slots = lambda *a, **k: stub(rows=1)+ forward.index_ring = lambda *a, **k: 0+ hcsplit.buffer_rows = lambda rows, *a, **k: rows+ os.environ["TF_GLM_L2PF"] = "0" # no L2 prefetch (it reads real weights)+ w = stub(meta={}, layers=[stub(kind=k) for k in kinds], world=3, rank=0, mtp=None, head=stub(n=1),+ cfg=stub(hidden=4096), device=torch.device("cuda"))+ decode.Engine(w, kv=kv)+ finally:+ setattr(mod, name, real)+ for m, a, v in saved:+ setattr(m, a, v)+ return len(calls)+++def main():+ check(hasattr(latent, "onepass_cuda") and hasattr(latent, "_onepass_ext"),+ "patch 0106 applied: latent.onepass_cuda")+ if fails:+ print("1 FAIL", flush=True)+ sys.exit(1)+ dev = torch.device("cuda")+ torch.manual_seed(85)+ ext = latent._onepass_ext()+ timing = "--time" in sys.argv+ cap = 600_000 + R + 8+ cache = kv8.quantize_rows(torch.randn(cap, LW, device=dev))+ for P in (35_000, 113_000, 300_000, 590_000):+ for kind in ("recent", "spread"):+ qa = (torch.randn(R, 22, LW, device=dev) * 2).to(torch.bfloat16)+ tok = selection(kind, P, R, dev)+ counts = (NSEL - torch.randint(0, 4, (R,), device=dev)).to(torch.int32)+ counts[:8] = torch.tensor([0, 1, 5, 31, 32, 33, 100, 0], dtype=torch.int32)+ ref, out = compare(f"P {P} {kind} 22 heads", qa, cache, tok, counts)+ if P == 35_000 and kind == "spread":+ err = oracle(qa, cache, tok, counts, out, [1, 2, 6, 100, 777, 2047], SCALE)+ check(err < 2e-2, f"P {P} {kind}: against float64 attention, max error {err:.2e} of max (bf16 out)")+ P = 113_000+ qa = (torch.randn(R, 21, LW, device=dev) * 2).to(torch.bfloat16)+ tok = selection("spread", P, R, dev)+ counts = torch.full((R,), NSEL, dtype=torch.int32, device=dev)+ compare(f"P {P} spread 21 heads", qa, cache, tok, counts)+ qa = (torch.randn(R, 22, LW, device=dev) * 2).to(torch.bfloat16)+ ragged = torch.randint(0, NSEL + 1, (R,), device=dev).to(torch.int32)+ compare(f"P {P} spread ragged counts 0-2,051", qa, cache, tok, ragged)+ for rows in (1024, 333):+ compare(f"P {P} spread {rows}-row chunk", qa[:rows].contiguous(), cache, tok[:rows].contiguous(),+ ragged[:rows].contiguous())+ # rows past a count are never read: the cache's first and last rows NaN codes, the lists' padding -1 / the last+ # row / out of range (no listed token is row 0)+ poison = cache.clone()+ poison[0, :LW] = 0x7F+ poison[-1, :LW] = 0x7F+ tok2 = torch.where(tok == 0, torch.full_like(tok, 4), tok)+ cut = torch.randint(1, NSEL, (R,), device=dev).to(torch.int32)+ past = torch.arange(NSEL, device=dev)[None, :] >= cut[:, None]+ tok2[past] = torch.tensor([-1, cap - 1, 2 ** 31 - 1], dtype=torch.int32, device=dev)[+ torch.randint(0, 3, (int(past.sum()),), device=dev)]+ ref, out = compare(f"P {P} padding past the counts (-1 / a NaN row / huge)", qa, poison, tok2, cut)+ check(not bool(out.isnan().any()), "padding: no NaN reached an output row")+ # NaN codes in rows that are read (only a NaN input writes one): the outputs that see them carry Triton's NaN bits+ nanc = cache.clone()+ nanc[tok[::7, 100].long(), 5] = 0x7F+ full = torch.full((R,), NSEL, dtype=torch.int32, device=dev)+ ref, out = compare(f"P {P} NaN codes in read rows (Triton's NaN bits)", qa, nanc, tok, full)+ check(bool(ref.isnan().any()), f"NaN codes: the reference has NaN outputs ({int(ref.isnan().sum())})")+ # arbitrary row scales and softmax scale: every product's order pinned+ arb = cache.clone()+ arb[:, LW:LW + 4].view(torch.float32)[:, 0] = torch.rand(arb.shape[0], device=dev) * 3 + 0.1+ for kind in ("recent", "spread"):+ tok = selection(kind, 35_000, R, dev)+ counts = (NSEL - torch.randint(0, 4, (R,), device=dev)).to(torch.int32)+ compare(f"arbitrary row scales, softmax scale 192^-0.5, P 35000 {kind}", qa, arb, tok, counts, 192 ** -0.5)+ # the entry point: launches counted; TP=2's 32 heads and a bf16 cache stay on Triton+ tok = selection("spread", 113_000, R, dev)+ counts = torch.full((R,), NSEL, dtype=torch.int32, device=dev)+ got = {}+ for flag in (True, False):+ counter = Count(ext)+ latent._ONEPASS_EXT = counter+ try:+ got[flag] = (run(qa, cache, tok, counts, SCALE, flag), counter.calls)+ finally:+ latent._ONEPASS_EXT = ext+ same = torch.equal(got[True][0].view(torch.int16), got[False][0].view(torch.int16))+ check(same and got[True][1] == 1 and got[False][1] == 0,+ f"sparse_onepass entry: CUDA {got[True][1]} launch (want 1) / Triton {got[False][1]} (want 0), outputs "+ f"equal {same}")+ for name, q, c in (("32 heads a rank (TP=2)", (torch.randn(R, 32, LW, device=dev)).to(torch.bfloat16), cache),+ ("a bf16 cache", qa, torch.randn(cache.shape[0], LW, device=dev).to(torch.bfloat16))):+ counter = Count(ext)+ latent._ONEPASS_EXT = counter+ try:+ out = run(q, c, tok, counts, SCALE, True)+ ok = not bool(out[counts > 0].isnan().any())+ except Exception as e: # a launch the kernel refuses is a failure of the routing, reported as one+ print(f" {name}: {type(e).__name__}: {str(e)[:200]}")+ ok = False+ finally:+ latent._ONEPASS_EXT = ext+ check(counter.calls == 0 and ok, f"{name}: stays on Triton (CUDA launches {counter.calls}, want 0)")+ os.environ.pop("TF_GLM_ONEPASS_CUDA", None)+ check(latent.onepass_cuda(), "TF_GLM_ONEPASS_CUDA unset: on")+ # start-up+ loader = (latent, "_onepass_ext")+ os.environ["TF_GLM_ONEPASS_CUDA"] = "1"+ check(construct(loader, "fp8") == 1, "Engine(FP8 caches, DSA layers): the extension loaded at start")+ check(construct(loader, "bf16") == 0, "Engine(bf16 caches): not loaded (the kernel is FP8 only)")+ check(construct(loader, "fp8", ("mla",)) == 0, "Engine(no DSA layer): not loaded")+ os.environ["TF_GLM_ONEPASS_CUDA"] = "0"+ check(construct(loader, "fp8") == 0, "TF_GLM_ONEPASS_CUDA=0: not loaded")+ # the extension not used (a failed build or load; another Triton release): logged once, Triton serves+ import contextlib+ import io++ from tensorfold.cuda import build+ from tensorfold.families.glm5_next.cuda import sparse++ tok = selection("spread", 113_000, R, dev)+ counts = torch.full((R,), NSEL, dtype=torch.int32, device=dev)+ ref = run(qa, cache, tok, counts, SCALE, False) # Triton on these inputs+ real_load, real_ptx = build.load, sparse.TRITON_PTX+ for case, ptx, want_tries in (("a failed build", real_ptx, 1), ("another Triton release", "0.0", 0)):+ tries, buf = [], io.StringIO()++ def broken(*a, **k):+ tries.append(1)+ raise RuntimeError("Error building extension 'tensorfold_glm_onepass_v1': nvcc not found")++ build.load, sparse.TRITON_PTX, latent._ONEPASS_EXT, latent._ONEPASS_FAILED = broken, ptx, None, None+ raised = first = second = res = None+ on = True+ try:+ with contextlib.redirect_stdout(buf):+ first, second = latent._onepass_ext(), latent._onepass_ext()+ on = latent.onepass_cuda()+ res = run(qa, cache, tok, counts, SCALE, True)+ except Exception as exc:+ raised = exc+ finally:+ build.load, sparse.TRITON_PTX, latent._ONEPASS_EXT, latent._ONEPASS_FAILED = real_load, real_ptx, ext, None+ logged = buf.getvalue().count("sparse_onepass.cu is not used")+ check(raised is None and first is None and second is None and len(tries) == want_tries and not on+ and logged == 1,+ f"{case}: nothing raised ({raised!r}), logged once ({logged}), loader called {len(tries)} "+ f"(want {want_tries}), the switch reads off ({not on})")+ check(res is not None and torch.equal(res.view(torch.int16), ref.view(torch.int16)),+ f"{case}: sparse_onepass gives the Triton kernel's output")+ if timing and fails == 0:+ for heads in (22, 21):+ qa = (torch.randn(R, heads, LW, device=dev) * 2).to(torch.bfloat16)+ out = torch.empty_like(qa)+ for P in (113_000, 590_000):+ for kind in ("recent", "spread"):+ tok = selection(kind, P, R, dev)+ counts = torch.full((R,), NSEL, dtype=torch.int32, device=dev)+ os.environ["TF_GLM_ONEPASS_CUDA"] = "0"+ t0 = ms(lambda: latent.sparse_onepass(qa, cache, tok, counts, out, SCALE))+ os.environ["TF_GLM_ONEPASS_CUDA"] = "1"+ t1 = ms(lambda: latent.sparse_onepass(qa, cache, tok, counts, out, SCALE))+ print(f"TIME {heads} heads, a 2,048-row chunk at {P} ({kind}): Triton {t0:.3f} -> CUDA {t1:.3f} ms "+ f"({100 * (t1 / t0 - 1):+.1f}%)", flush=True)+ print("ALL PASS" if fails == 0 else f"{fails} FAIL", flush=True)+ sys.exit(1 if fails else 0)+++if __name__ == "__main__":+ main()