diff --git a/CHANGELOG.md b/CHANGELOG.md index 95532f5958a..69ec52039d5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,12 +4,12 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel ## Unreleased +- Flash Next on CUDA: `TF_FLASHNEXT_READOUT_FUSED=1` (off by default) runs a prompt pass's BF16 hyper-connection read-out from 768 rows in three launches instead of five, with every output byte the same (#3413, refs #3392). Thanks to @BadAd84. + - Docs: the optimization ledger records the rows-together dense 4-bit stream tile on gfx1151 as `failed` for Nemotron on HIP: its launches got faster, but the draft policy then drafted shallower and two greedy Lightning streams got slower (#3395, refs #3305). Thanks to @gilby. - Docs: the dots.mocr CUDA recipe covers images with `--vision` (14,400 merged image tokens a request by default, set by `--vision-image-tokens`; each lane holds its request's image rows, so fewer lanes fit; JPEG needs libjpeg-turbo 3.1.4.1; video is refused), the oracle's SDPA image references and `stages`, and the `dots-image` and `dots-text` checks; the README and recipe index list CUDA for images and text (#2773, refs #1927). Thanks to @laudney. - - - Flash Next on M5: kept DeltaNet states (as M1-M4 have) and the half-nibble 4-bit converts M3 and M4 use are enabled with tensor units too; one stream measured about 6.5% faster on an M5 Ultra (16 prompts of 512 tokens, main and this PR alternating with one server per arm), tokens equal on 32 of 32 replies (#3271). - LFM3 and Flash Next: LFM3's sampled and grammar-masked row draws and Flash Next's host reference draw call core's one row sampler with the same errors and messages, and an empty Flash Next reference row is refused by name instead of panicking (#2679, refs #2460). Thanks to @jschmied. diff --git a/docs/environment.md b/docs/environment.md index 894b1300ef5..04abee035f0 100644 --- a/docs/environment.md +++ b/docs/environment.md @@ -127,7 +127,7 @@ Direct family readers also refuse malformed values when called without the serve ## Flash Next -Flash Next checks these 33 settings when its engine loads, before any device or checkpoint work: a malformed value +Flash Next checks these 34 settings when its engine loads, before any device or checkpoint work: a malformed value stops the start with the variable, the supplied text and the accepted forms. | Variable | Accepted explicit value | @@ -145,6 +145,7 @@ stops the start with the variable, the supplied text and the accepted forms. | `TF_FLASHNEXT_SHARED_DRAFTS` | Exactly `0` or `1`; default on | | `TF_FLASHNEXT_SHARED_SIDE` | Exactly `0` or `1`; default on | | `TF_FLASHNEXT_HC_FUSE` | Exactly `0` or `1`; default on | +| `TF_FLASHNEXT_READOUT_FUSED` | Exactly `0` or `1`; default off | | `TF_FLASHNEXT_KEEP_LATE` | Exactly `0` or `1`; unset or blank leaves the choice to the loader | | `TF_FLASHNEXT_DECODE_GRAPH` | Exactly `0` or `1`; default off | | `TF_FLASHNEXT_SPLIT_DENSE` | Exactly `0` or `1`; default on: two ranks split the BF16 dense projections | diff --git a/docs/receipts/flashnext-readout-fused/README.md b/docs/receipts/flashnext-readout-fused/README.md new file mode 100644 index 00000000000..be01941a27a --- /dev/null +++ b/docs/receipts/flashnext-readout-fused/README.md @@ -0,0 +1,134 @@ +# Flash Next fused BF16 read-out: main against the branch + +`TF_FLASHNEXT_READOUT_FUSED=1`, off by default, runs a CUDA prompt pass's BF16 hyper-connection read-out, from 768 +rows, in three launches instead of five: the down projection forms the normed rows in shared memory, the up projection +forms them again in its epilogue and mixes the four streams there, and the writeback before it skips its normalize. +Unset or blank is main's chain. + +## Source and environment + +- Main: `41a72fd2578dfbdd73b25663da78d5fc0047bd95`. Branch: this pull request at + `ee13555c8ef095aaeb9da4786b62af1cdf405dbb`, its commits merged with that main; the commits after it change only this + receipt, the changelog line and the docs. +- Each image built the same way from its own commit: the recipe's Zig base image with `tensorfold-native`, its tools + and the fatbins, nvcc 13.3. +- One NVIDIA GB10 (sm_121), Zig 0.17.0, CUDA 13.3. +- Checkpoint `nvidia/Qwen3.8-Flash-Next-FP4-Local`, revision `b9ce18a6887e18c089fdea8509a33e63429a3300`, every arm. + Its read-out weights are BF16 (`input_mix_weight_down` [320, 10240], `input_mix_weight_up` [10240, 320]). +- `--parallel 4`, 131,072-token context, bf16 KV, a fresh server per arm, `--prompt-cache-gib 0` on every speed arm. + A discarded boot of main runs first, so the weights are paged in before M1. +- Arms, in order: M1 (main), U1 (branch, unset), F1 (branch, `1`), M2, F2, U2 (branch, set blank). +- Each arm: cold prompts of 2k, 8k, 32k and 64k tokens at one stream (a salted prompt each, three reps, the median), + `tools/bench_cache.py --require-cold` (its 2,571-token prompt), `tools/bench_openai.py` (greedy, 3 reps), then + `tools/bench_concurrent.py --alone --serial` greedy and at temperature 1.0 with `--seed 1234` (code and chat, 1, 2 + and 4 streams, 256 tokens, 3 reps), `/metrics` around each. `cells.csv` has every cell, `noise-rule.md` every + verdict. + +## Cold prompts + +Seconds to the first token, the median of three salted prompts: + +| prompt | M1 | M2 | U1 | U2 | F1 | F2 | unset against main | `1` against main | +|---|---|---|---|---|---|---|---|---| +| 2k | 1.046 | 1.078 | 1.064 | 1.070 | 1.054 | 1.031 | +0.5%, level | -1.8%, level | +| 8k | 4.009 | 3.992 | 3.984 | 3.996 | 3.865 | 3.854 | -0.3%, level | -3.5%, faster | +| 32k | 15.903 | 16.062 | 16.028 | 16.018 | 15.512 | 15.542 | +0.3%, level | -2.8%, faster | +| 64k | 32.795 | 33.108 | 33.115 | 32.959 | 31.866 | 32.024 | +0.3%, level | -3.1%, faster | +| `bench_cache.py --require-cold`, 2,571 tokens | 1.233 | 1.223 | 1.219 | 1.219 | 1.183 | 1.185 | -0.7%, level | -3.6%, faster | + +Every first request reported 0 cached tokens. The 2k cell is level by the rule: F1's 1.054 s is above M1's 1.046 s. + +## Decode speed and tokens a round + +Aggregate tok/s; tokens a round is the tools' tokens a streamed chunk (a round sends its accepted drafts and one +verified token): + +| invocation, prompt, streams | M1 | M2 | U1 | U2 | F1 | F2 | unset | `1` | tokens a round, every arm | +|---|---|---|---|---|---|---|---|---|---| +| `bench_openai`, code, 1 | 72.6 | 72.0 | 72.2 | 72.1 | 72.1 | 72.1 | -0.2%, level | -0.2%, level | 5.224 | +| `bench_openai`, chat, 1 | 46.6 | 46.4 | 46.5 | 46.4 | 46.4 | 46.4 | -0.1%, level | -0.2%, level | 2.813 | +| greedy, chat, 1 | 46.7 | 46.5 | 46.5 | 46.4 | 46.5 | 46.4 | -0.3%, level | -0.3%, level | 2.813 | +| greedy, chat, 2 | 85.7 | 85.5 | 85.6 | 85.6 | 85.7 | 85.6 | +0.0%, level | +0.1%, level | 2.510 | +| greedy, chat, 4 | 152.6 | 152.3 | 152.6 | 152.1 | 152.3 | 152.2 | -0.1%, level | -0.1%, level | 2.510 | +| greedy, code, 1 | 72.4 | 72.3 | 72.1 | 72.2 | 72.5 | 72.3 | -0.3%, level | +0.1%, level | 5.224 | +| greedy, code, 2 | 138.0 | 137.4 | 137.4 | 137.4 | 137.5 | 137.7 | -0.2%, level | -0.1%, level | 4.830 | +| greedy, code, 4 | 242.4 | 241.3 | 242.1 | 241.5 | 241.2 | 241.4 | -0.0%, level | -0.2%, level | 4.830 | +| temperature 1.0, chat, 1 | 44.6 | 44.4 | 44.5 | 44.4 | 44.4 | 44.5 | -0.1%, level | -0.1%, level | 2.393 | +| temperature 1.0, chat, 2 | 69.5 | 69.0 | 69.3 | 69.0 | 69.3 | 69.4 | -0.1%, level | +0.1%, level | 2.450 | +| temperature 1.0, chat, 4 | 102.9 | 102.7 | 103.0 | 102.7 | 102.9 | 102.6 | +0.0%, level | -0.0%, level | 2.456 | +| temperature 1.0, code, 1 | 70.3 | 69.9 | 70.0 | 69.8 | 69.9 | 70.2 | -0.3%, level | -0.1%, level | 4.571 | +| temperature 1.0, code, 2 | 88.5 | 88.3 | 88.3 | 88.1 | 88.4 | 88.2 | -0.2%, level | -0.1%, level | 3.765 | +| temperature 1.0, code, 4 | 129.2 | 128.5 | 128.8 | 128.7 | 128.9 | 128.7 | -0.1%, level | -0.0%, level | 3.835 | + +The server's `mtp_accepted_total` over `mtp_drafted_total` is the same in all six arms for each invocation: 1,488 of +2,384 (`bench_openai`), 7,934 of 11,682 (greedy) and 8,607 of 11,917 (temperature 1.0). + +## The noise rule + +A cell is slower when both branch runs are under both main runs (for a time: over) and the mean gap is over 1%; it gets +one rerun, and a repeat is a loss. Unset and blank against main: 0 of 19 cells slower. `1` against main: 0 of 19 cells +slower, four faster (8k, 32k and 64k prompts, and `bench_cache.py`'s). No cell needed a rerun. + +## Memory + +The read-out reuses the pass's existing scratch (`hc_part`, `act`, `mixed`, `xsm`); the normed rows' buffer is still +allocated. Every arm logged the same pool: `4 streams at once, 4.11 GiB each at a 131072-token window, of 28.0 GiB left +after a 9.0 GiB reserve`. The container's resident memory after each arm: 4.320 to 4.346 GiB in all six. + +## Kernel contract + +`tf-cuda-test kernel-contract fn_hcn` on the GB10, in the branch's image, exit status 0: + + (filtered) SUMMARY 4 kernels: 4 pass gates 1-4, 0 fail, 0 known findings; 2 controls: 2 red as planted, 0 missed; 0 limit problems; gates 2066 ms, limits 0 ms + +- `fn_hcn_down2`, `fn_hcn_down3`, `fn_hcn_down4` and `fn_hcn_up3` pass gates 1 to 3: every output byte equals the + launches each replaces, planted non-finite rows included, at 768, 769, 1,000, 1,536, 2,053 and 3,072 rows, and five + runs are byte-identical. The replaced launches run on the engine's lane, with qmmf's BF16 prompt tiles loaded as + `TF_FLASHNEXT_PROMPT_BF16` leaves them. Gate 4 does not apply: the kernels declare no sums of their own. +- The two controls go red at gate 3 as planted: rounding the normed rows toward zero differs from byte 0, and gating + the up rows before their bf16 rounding differs from byte 2. +- Gate 5, live on sm_121: each kernel's registers and static shared bytes equal its record (152, 189, 206 and 127 + registers; 0 static shared bytes), within the driver's thread and shared-memory limits. + +## The kernels against the chain + +`tf-cuda-test flashnext-readout-fused`, exit status 0. At 16 row counts from 64 to 3,072, the five launches run on the +plain lane and on the engine's lane, where qmmf's prompt tiles take the up projection from 512 rows and the down +projection from 1,025 rows on 48 SMs. The two give the same bytes, and the fused path gives them too, with each down +tile. Its times on the engine's lane, the medians of 9 x 10 launches, alternated: + +| rows | five launches (us) | fused (us) | +|---|---|---| +| 256 | 224.3 | 251.7 | +| 512 | 346.9 | 325.1 | +| 768 | 590.5 | 406.2 | +| 1,024 | 749.2 | 504.9 | +| 1,536 | 1,091.7 | 667.0 | +| 2,048 | 1,424.0 | 975.2 | +| 3,072 | 2,196.1 | 1,315.5 | + +The fused path is slower at 256 rows; the engine takes it from 768 rows. In a served pass the writeback already carries +the normalize (`TF_FLASHNEXT_HC_FUSE`), so a pass saves less than this table's difference. + +## Off, on and a malformed value + +- U1 (unset) and U2 (`TF_FLASHNEXT_READOUT_FUSED=` empty) take main's chain, and every reply hash their bench files + record equals main's (`exactness.md`). +- `TF_FLASHNEXT_READOUT_FUSED=2` stops the start: `TF_FLASHNEXT_READOUT_FUSED="2": expected 0 or 1 (default 0)`. + +## Exactness + +`exactness.md`: drafted against `"draft": false`, resumed against fresh and concurrent against solo, on main, the +branch unset and the branch set to `1`, each with the prompt cache on and off, plus three long prompts (about 1.5k, 5k +and 15k tokens) at 1 and 4 streams, and the long prompts again with prompt passes of 2,048 and 3,072 rows. Every +equality holds in every arm, and the branch's replies equal main's. + +With passes of 1,000 rows, main itself fails every request: the first, a 1,685-token prompt, ends `CudaFailed` after +`cuMemsetD8Async: CUDA_ERROR_INVALID_VALUE`, and the branch fails the same way, unset or set. Passes of 768 rows fail +the same way on main `d6c4cce602`. That is not this change. + +## Not established + +GB10 and this checkpoint only. Metal and HIP refusing the setting, and a CUDA checkpoint whose read-out is MLX affine +refusing it, are covered by a host test, not run on that hardware or on such a checkpoint. The kernel contract's +records for the four kernels are nvcc 13.3's for sm_80 to sm_121; nvcc 13.0 and 13.2 were not available to compile them. diff --git a/docs/receipts/flashnext-readout-fused/cells.csv b/docs/receipts/flashnext-readout-fused/cells.csv new file mode 100644 index 00000000000..2ca504c7f51 --- /dev/null +++ b/docs/receipts/flashnext-readout-fused/cells.csv @@ -0,0 +1,115 @@ +arm,invocation,prompt,streams,value,tokens_per_round,server_accepted,server_drafted,server_acceptance,cached,failed,unmeasured +M1,ttft,2k,1,1.046,,81,138,0.587,,, +M1,ttft,8k,1,4.009,,81,138,0.587,,, +M1,ttft,32k,1,15.903,,81,138,0.587,,, +M1,ttft,64k,1,32.795,,81,138,0.587,,, +M1,cache,2571 tokens,1,1.2327156758401543,,208,208,1.0,0,, +M1,openai_t0,fibonacci-raw,1,72.61591719903083,5.224,1488,2384,0.6242,,, +M1,openai_t0,gpu-chat-no-think,1,46.584777521638436,2.813,1488,2384,0.6242,,, +M1,conc_t0,code,1,72.4,5.224,7934,11682,0.6792,,0,0 +M1,conc_t0,code,2,138.0,4.83,7934,11682,0.6792,,0,0 +M1,conc_t0,code,4,242.4,4.83,7934,11682,0.6792,,0,0 +M1,conc_t0,chat,1,46.7,2.813,7934,11682,0.6792,,0,0 +M1,conc_t0,chat,2,85.7,2.51,7934,11682,0.6792,,0,0 +M1,conc_t0,chat,4,152.6,2.51,7934,11682,0.6792,,0,0 +M1,conc_t1_s1234,code,1,70.3,4.571,8607,11917,0.7222,,0,0 +M1,conc_t1_s1234,code,2,88.5,3.765,8607,11917,0.7222,,0,0 +M1,conc_t1_s1234,code,4,129.2,3.835,8607,11917,0.7222,,0,0 +M1,conc_t1_s1234,chat,1,44.6,2.393,8607,11917,0.7222,,0,0 +M1,conc_t1_s1234,chat,2,69.5,2.45,8607,11917,0.7222,,0,0 +M1,conc_t1_s1234,chat,4,102.9,2.456,8607,11917,0.7222,,0,0 +U1,ttft,2k,1,1.064,,80,145,0.5517,,, +U1,ttft,8k,1,3.984,,80,145,0.5517,,, +U1,ttft,32k,1,16.028,,80,145,0.5517,,, +U1,ttft,64k,1,33.115,,80,145,0.5517,,, +U1,cache,2571 tokens,1,1.2194375831168145,,208,208,1.0,0,, +U1,openai_t0,fibonacci-raw,1,72.15849839904098,5.224,1488,2384,0.6242,,, +U1,openai_t0,gpu-chat-no-think,1,46.45064668449305,2.813,1488,2384,0.6242,,, +U1,conc_t0,code,1,72.1,5.224,7934,11682,0.6792,,0,0 +U1,conc_t0,code,2,137.4,4.83,7934,11682,0.6792,,0,0 +U1,conc_t0,code,4,242.1,4.83,7934,11682,0.6792,,0,0 +U1,conc_t0,chat,1,46.5,2.813,7934,11682,0.6792,,0,0 +U1,conc_t0,chat,2,85.6,2.51,7934,11682,0.6792,,0,0 +U1,conc_t0,chat,4,152.6,2.51,7934,11682,0.6792,,0,0 +U1,conc_t1_s1234,code,1,70.0,4.571,8607,11917,0.7222,,0,0 +U1,conc_t1_s1234,code,2,88.3,3.765,8607,11917,0.7222,,0,0 +U1,conc_t1_s1234,code,4,128.8,3.835,8607,11917,0.7222,,0,0 +U1,conc_t1_s1234,chat,1,44.5,2.393,8607,11917,0.7222,,0,0 +U1,conc_t1_s1234,chat,2,69.3,2.45,8607,11917,0.7222,,0,0 +U1,conc_t1_s1234,chat,4,103.0,2.456,8607,11917,0.7222,,0,0 +F1,ttft,2k,1,1.054,,70,141,0.4965,,, +F1,ttft,8k,1,3.865,,70,141,0.4965,,, +F1,ttft,32k,1,15.512,,70,141,0.4965,,, +F1,ttft,64k,1,31.866,,70,141,0.4965,,, +F1,cache,2571 tokens,1,1.1830028141848743,,208,208,1.0,0,, +F1,openai_t0,fibonacci-raw,1,72.10274550981792,5.224,1488,2384,0.6242,,, +F1,openai_t0,gpu-chat-no-think,1,46.39852665573804,2.813,1488,2384,0.6242,,, +F1,conc_t0,code,1,72.5,5.224,7934,11682,0.6792,,0,0 +F1,conc_t0,code,2,137.5,4.83,7934,11682,0.6792,,0,0 +F1,conc_t0,code,4,241.2,4.83,7934,11682,0.6792,,0,0 +F1,conc_t0,chat,1,46.5,2.813,7934,11682,0.6792,,0,0 +F1,conc_t0,chat,2,85.7,2.51,7934,11682,0.6792,,0,0 +F1,conc_t0,chat,4,152.3,2.51,7934,11682,0.6792,,0,0 +F1,conc_t1_s1234,code,1,69.9,4.571,8607,11917,0.7222,,0,0 +F1,conc_t1_s1234,code,2,88.4,3.765,8607,11917,0.7222,,0,0 +F1,conc_t1_s1234,code,4,128.9,3.835,8607,11917,0.7222,,0,0 +F1,conc_t1_s1234,chat,1,44.4,2.393,8607,11917,0.7222,,0,0 +F1,conc_t1_s1234,chat,2,69.3,2.45,8607,11917,0.7222,,0,0 +F1,conc_t1_s1234,chat,4,102.9,2.456,8607,11917,0.7222,,0,0 +M2,ttft,2k,1,1.078,,72,146,0.4932,,, +M2,ttft,8k,1,3.992,,72,146,0.4932,,, +M2,ttft,32k,1,16.062,,72,146,0.4932,,, +M2,ttft,64k,1,33.108,,72,146,0.4932,,, +M2,cache,2571 tokens,1,1.222894020145759,,208,208,1.0,0,, +M2,openai_t0,fibonacci-raw,1,71.97469547944286,5.224,1488,2384,0.6242,,, +M2,openai_t0,gpu-chat-no-think,1,46.35473773646017,2.813,1488,2384,0.6242,,, +M2,conc_t0,code,1,72.3,5.224,7934,11682,0.6792,,0,0 +M2,conc_t0,code,2,137.4,4.83,7934,11682,0.6792,,0,0 +M2,conc_t0,code,4,241.3,4.83,7934,11682,0.6792,,0,0 +M2,conc_t0,chat,1,46.5,2.813,7934,11682,0.6792,,0,0 +M2,conc_t0,chat,2,85.5,2.51,7934,11682,0.6792,,0,0 +M2,conc_t0,chat,4,152.3,2.51,7934,11682,0.6792,,0,0 +M2,conc_t1_s1234,code,1,69.9,4.571,8607,11917,0.7222,,0,0 +M2,conc_t1_s1234,code,2,88.3,3.765,8607,11917,0.7222,,0,0 +M2,conc_t1_s1234,code,4,128.5,3.835,8607,11917,0.7222,,0,0 +M2,conc_t1_s1234,chat,1,44.4,2.393,8607,11917,0.7222,,0,0 +M2,conc_t1_s1234,chat,2,69.0,2.45,8607,11917,0.7222,,0,0 +M2,conc_t1_s1234,chat,4,102.7,2.456,8607,11917,0.7222,,0,0 +F2,ttft,2k,1,1.031,,70,141,0.4965,,, +F2,ttft,8k,1,3.854,,70,141,0.4965,,, +F2,ttft,32k,1,15.542,,70,141,0.4965,,, +F2,ttft,64k,1,32.024,,70,141,0.4965,,, +F2,cache,2571 tokens,1,1.1853895969688892,,208,208,1.0,0,, +F2,openai_t0,fibonacci-raw,1,72.13771887165024,5.224,1488,2384,0.6242,,, +F2,openai_t0,gpu-chat-no-think,1,46.37391704020123,2.813,1488,2384,0.6242,,, +F2,conc_t0,code,1,72.3,5.224,7934,11682,0.6792,,0,0 +F2,conc_t0,code,2,137.7,4.83,7934,11682,0.6792,,0,0 +F2,conc_t0,code,4,241.4,4.83,7934,11682,0.6792,,0,0 +F2,conc_t0,chat,1,46.4,2.813,7934,11682,0.6792,,0,0 +F2,conc_t0,chat,2,85.6,2.51,7934,11682,0.6792,,0,0 +F2,conc_t0,chat,4,152.2,2.51,7934,11682,0.6792,,0,0 +F2,conc_t1_s1234,code,1,70.2,4.571,8607,11917,0.7222,,0,0 +F2,conc_t1_s1234,code,2,88.2,3.765,8607,11917,0.7222,,0,0 +F2,conc_t1_s1234,code,4,128.7,3.835,8607,11917,0.7222,,0,0 +F2,conc_t1_s1234,chat,1,44.5,2.393,8607,11917,0.7222,,0,0 +F2,conc_t1_s1234,chat,2,69.4,2.45,8607,11917,0.7222,,0,0 +F2,conc_t1_s1234,chat,4,102.6,2.456,8607,11917,0.7222,,0,0 +U2,ttft,2k,1,1.07,,69,145,0.4759,,, +U2,ttft,8k,1,3.996,,69,145,0.4759,,, +U2,ttft,32k,1,16.018,,69,145,0.4759,,, +U2,ttft,64k,1,32.959,,69,145,0.4759,,, +U2,cache,2571 tokens,1,1.2192225139588118,,208,208,1.0,0,, +U2,openai_t0,fibonacci-raw,1,72.0723325051612,5.224,1488,2384,0.6242,,, +U2,openai_t0,gpu-chat-no-think,1,46.3666039784335,2.813,1488,2384,0.6242,,, +U2,conc_t0,code,1,72.2,5.224,7934,11682,0.6792,,0,0 +U2,conc_t0,code,2,137.4,4.83,7934,11682,0.6792,,0,0 +U2,conc_t0,code,4,241.5,4.83,7934,11682,0.6792,,0,0 +U2,conc_t0,chat,1,46.4,2.813,7934,11682,0.6792,,0,0 +U2,conc_t0,chat,2,85.6,2.51,7934,11682,0.6792,,0,0 +U2,conc_t0,chat,4,152.1,2.51,7934,11682,0.6792,,0,0 +U2,conc_t1_s1234,code,1,69.8,4.571,8607,11917,0.7222,,0,0 +U2,conc_t1_s1234,code,2,88.1,3.765,8607,11917,0.7222,,0,0 +U2,conc_t1_s1234,code,4,128.7,3.835,8607,11917,0.7222,,0,0 +U2,conc_t1_s1234,chat,1,44.4,2.393,8607,11917,0.7222,,0,0 +U2,conc_t1_s1234,chat,2,69.0,2.45,8607,11917,0.7222,,0,0 +U2,conc_t1_s1234,chat,4,102.7,2.456,8607,11917,0.7222,,0,0 diff --git a/docs/receipts/flashnext-readout-fused/exactness.md b/docs/receipts/flashnext-readout-fused/exactness.md new file mode 100644 index 00000000000..c38477d4cac --- /dev/null +++ b/docs/receipts/flashnext-readout-fused/exactness.md @@ -0,0 +1,40 @@ +Main `41a72fd257` and the branch on it at `ee13555c8e`: unset, and `TF_FLASHNEXT_READOUT_FUSED=1`. Each arm booted +fresh with the prompt cache on and again with `--prompt-cache-gib 0`; `--parallel 4`, bf16 KV, a 131,072-token window. + +| check | measure | main | branch, unset | branch, fused | +|---|---|---|---|---| +| 1 | bench_concurrent --serial, code+chat, greedy | 2/2 equal (token_sha256, [256] tok) | 2/2 equal | 2/2 equal | +| 1 | bench_concurrent --serial, code+chat, temperature 1.0 | 8/8 equal (token_sha256, [256] tok) | 8/8 equal | 8/8 equal | +| 1 | bench_concurrent --serial, six golden, greedy | 6/6 equal (token_sha256, [256] tok) | 6/6 equal | 6/6 equal | +| 1 | served_exactness drafts, 8 prompts, cache on | 8/8 equal (token_ids, [256] tok) | 8/8 equal | 8/8 equal | +| 1 | served_exactness drafts, 8 prompts, cache off | 8/8 equal (token_ids, [256] tok) | 8/8 equal | 8/8 equal | +| 1 | serve_check drafted == serial (greedy, t0.8), cache off | 2/2 ok | 2/2 ok | 2/2 ok | +| 2 | served_exactness turns (on) against fresh (off), 5 chats | 7/7 equal; resumed from [13, 16, 16, 13, 24, 18, 3406] of [112, 84, 99, 208, 306, 25, 3459] prompt tokens | 7/7 equal | 7/7 equal | +| 2 | bench_cache repeated/concurrent == first, cache on | 4 equal, 0 unequal; cached [0, 2570, 2570, 2570] | 4 equal, 0 unequal | 4 equal, 0 unequal | +| 3 | bench_concurrent --alone, identical code+chat, 1/2/4, greedy | 42/42 equal, 0 failed | 42/42 equal, 0 failed | 42/42 equal, 0 failed | +| 3 | bench_concurrent --alone, code+chat, 1/2/4, temperature 1.0 | 42/42 equal, 0 failed | 42/42 equal, 0 failed | 42/42 equal, 0 failed | +| 3 | bench_concurrent --alone, six golden distinct, 1/2/4/6, greedy | 13/13 equal, 0 failed | 13/13 equal, 0 failed | 13/13 equal, 0 failed | +| 3 | serve_check together/among-decoders/twice, cache off | 12/12 ok | 12/12 ok | 12/12 ok | + +| check | main | branch, unset | branch, fused | +|---|---|---|---| +| drafted == draft:false | PASS | PASS | PASS | +| resumed == fresh | PASS | PASS | PASS | +| concurrent == solo | PASS | PASS | PASS | + +Replies against main's (same request, same boot kind), unset and fused alike: concurrent alone+serial hashes 16/16; +golden alone+serial hashes 6/6; drafts with the cache on, plain token ids 8/8; with it off 8/8; turns, first token ids +7/7; resumed token ids 7/7. serve_check: 15 ok, 0 FAIL in every arm. + +The golden and drafts prompts are short, so their passes stay under 768 rows and take the chain in every arm. The +fused tiles run on these: + +- Three long prompts (about 1.5k, 5k and 15k tokens), `bench_concurrent --alone --serial` at 1 and 4 streams, greedy, + 128 tokens: 20 reply hashes an arm, 3 distinct, the same 20 in main, unset and fused, with the cache on and off. +- The same long prompts with prompt passes of 2,048 rows and of 3,072 rows (`TF_FLASHNEXT_CHUNK`), 1 and 4 streams: + main and fused record the same 20 hashes each, 0 failed requests. +- With passes of 1,000 rows, every request fails on main and on the branch alike (`CudaFailed`, after + `cuMemsetD8Async: CUDA_ERROR_INVALID_VALUE`), so that size gives no comparison. +- `bench_cache.py --require-cold`'s 2,571-token prompt in the six speed arms: the same 4 reply hashes in all six. +- The speed arms' own replies, greedy and at temperature 1.0 with seed 1234, code and chat, 1, 2 and 4 streams: all 168 + `token_sha256` values of each invocation equal M1's in every arm. diff --git a/docs/receipts/flashnext-readout-fused/noise-rule.md b/docs/receipts/flashnext-readout-fused/noise-rule.md new file mode 100644 index 00000000000..b60492f320c --- /dev/null +++ b/docs/receipts/flashnext-readout-fused/noise-rule.md @@ -0,0 +1,36 @@ +| invocation | prompt | streams | M1 | M2 | U1 | U2 | F1 | F2 | U vs main | F vs main | tokens a round M / U / F | +|---|---|---|---|---|---|---|---|---|---|---|---| +| ttft | 2k | 1 | 1.05 | 1.08 | 1.06 | 1.07 | 1.05 | 1.03 | +0.5% level | -1.8% level | - | +| ttft | 8k | 1 | 4.01 | 3.99 | 3.98 | 4.00 | 3.87 | 3.85 | -0.3% level | -3.5% faster | - | +| ttft | 32k | 1 | 15.90 | 16.06 | 16.03 | 16.02 | 15.51 | 15.54 | +0.3% level | -2.8% faster | - | +| ttft | 64k | 1 | 32.80 | 33.11 | 33.12 | 32.96 | 31.87 | 32.02 | +0.3% level | -3.1% faster | - | +| cache | 2571 tokens | 1 | 1.233 | 1.223 | 1.219 | 1.219 | 1.183 | 1.185 | -0.7% level | -3.6% faster | - | +| openai_t0 | fibonacci-raw | 1 | 72.6 | 72.0 | 72.2 | 72.1 | 72.1 | 72.1 | -0.2% level | -0.2% level | 5.224 / 5.224 / 5.224 | +| openai_t0 | gpu-chat-no-think | 1 | 46.6 | 46.4 | 46.5 | 46.4 | 46.4 | 46.4 | -0.1% level | -0.2% level | 2.813 / 2.813 / 2.813 | +| conc_t0 | chat | 1 | 46.7 | 46.5 | 46.5 | 46.4 | 46.5 | 46.4 | -0.3% level | -0.3% level | 2.813 / 2.813 / 2.813 | +| conc_t0 | chat | 2 | 85.7 | 85.5 | 85.6 | 85.6 | 85.7 | 85.6 | +0.0% level | +0.1% level | 2.510 / 2.510 / 2.510 | +| conc_t0 | chat | 4 | 152.6 | 152.3 | 152.6 | 152.1 | 152.3 | 152.2 | -0.1% level | -0.1% level | 2.510 / 2.510 / 2.510 | +| conc_t0 | code | 1 | 72.4 | 72.3 | 72.1 | 72.2 | 72.5 | 72.3 | -0.3% level | +0.1% level | 5.224 / 5.224 / 5.224 | +| conc_t0 | code | 2 | 138.0 | 137.4 | 137.4 | 137.4 | 137.5 | 137.7 | -0.2% level | -0.1% level | 4.830 / 4.830 / 4.830 | +| conc_t0 | code | 4 | 242.4 | 241.3 | 242.1 | 241.5 | 241.2 | 241.4 | -0.0% level | -0.2% level | 4.830 / 4.830 / 4.830 | +| conc_t1_s1234 | chat | 1 | 44.6 | 44.4 | 44.5 | 44.4 | 44.4 | 44.5 | -0.1% level | -0.1% level | 2.393 / 2.393 / 2.393 | +| conc_t1_s1234 | chat | 2 | 69.5 | 69.0 | 69.3 | 69.0 | 69.3 | 69.4 | -0.1% level | +0.1% level | 2.450 / 2.450 / 2.450 | +| conc_t1_s1234 | chat | 4 | 102.9 | 102.7 | 103.0 | 102.7 | 102.9 | 102.6 | +0.0% level | -0.0% level | 2.456 / 2.456 / 2.456 | +| conc_t1_s1234 | code | 1 | 70.3 | 69.9 | 70.0 | 69.8 | 69.9 | 70.2 | -0.3% level | -0.1% level | 4.571 / 4.571 / 4.571 | +| conc_t1_s1234 | code | 2 | 88.5 | 88.3 | 88.3 | 88.1 | 88.4 | 88.2 | -0.2% level | -0.1% level | 3.765 / 3.765 / 3.765 | +| conc_t1_s1234 | code | 4 | 129.2 | 128.5 | 128.8 | 128.7 | 128.9 | 128.7 | -0.1% level | -0.0% level | 3.835 / 3.835 / 3.835 | + +Server acceptance (mtp_accepted_total over mtp_drafted_total, per invocation): + +- openai_t0: M1 1488/2384 = 0.6242, U1 1488/2384 = 0.6242, F1 1488/2384 = 0.6242, M2 1488/2384 = 0.6242, F2 1488/2384 = 0.6242, U2 1488/2384 = 0.6242 +- conc_t0: M1 7934/11682 = 0.6792, U1 7934/11682 = 0.6792, F1 7934/11682 = 0.6792, M2 7934/11682 = 0.6792, F2 7934/11682 = 0.6792, U2 7934/11682 = 0.6792 +- conc_t1_s1234: M1 8607/11917 = 0.7222, U1 8607/11917 = 0.7222, F1 8607/11917 = 0.7222, M2 8607/11917 = 0.7222, F2 8607/11917 = 0.7222, U2 8607/11917 = 0.7222 + +Memory after each arm (docker stats) and the pool line: + +- M1: 4.33GiB / 123.7GiB; 4 streams at once, 4.11 GiB each at a 131072-token window, of 28.0 GiB left after a 9.0 GiB reserve +- U1: 4.324GiB / 123.7GiB; 4 streams at once, 4.11 GiB each at a 131072-token window, of 28.0 GiB left after a 9.0 GiB reserve +- F1: 4.346GiB / 123.7GiB; 4 streams at once, 4.11 GiB each at a 131072-token window, of 28.0 GiB left after a 9.0 GiB reserve +- M2: 4.32GiB / 123.7GiB; 4 streams at once, 4.11 GiB each at a 131072-token window, of 28.0 GiB left after a 9.0 GiB reserve +- F2: 4.336GiB / 123.7GiB; 4 streams at once, 4.11 GiB each at a 131072-token window, of 28.0 GiB left after a 9.0 GiB reserve +- U2: 4.327GiB / 123.7GiB; 4 streams at once, 4.11 GiB each at a 131072-token window, of 28.0 GiB left after a 9.0 GiB reserve diff --git a/docs/recipes/flash-next-cuda.md b/docs/recipes/flash-next-cuda.md index 952c9d1dd66..f365550ba02 100644 --- a/docs/recipes/flash-next-cuda.md +++ b/docs/recipes/flash-next-cuda.md @@ -95,6 +95,9 @@ its path. - `--no-drafts` serves without the MTP head; `"draft": false` on a request does the same for that request. - `TF_FLASHNEXT_READOUT_ROWS` (default 64, `0` never) is the rows from which the hyper-connection read-out takes the prompt tiles. Same bits either way; `128` keeps 16-stream decode rounds on the row kernels, up to 7% quicker on a GB10. +- `TF_FLASHNEXT_READOUT_FUSED=1` (default off) runs a prompt pass's BF16 hyper-connection read-out, from 768 rows, on + two fused tiles that form the normed rows on chip. Same bits; cold prompts of 8k to 64k tokens 2.8% to 3.5% quicker + on a GB10 with the NVFP4 checkpoint. Metal, HIP and an MLX affine read-out refuse it by name. - `TF_FLASHNEXT_CHUNK` (1 to 16,384, default 3,072) caps the rows of one prompt pass. Every pass reads the weights of every expert its rows route to, so fewer, larger passes cost less a token; but a pass runs to its end, so a stream decoding during a pass waits up to the whole pass for its next token. See diff --git a/zig/build/cuda.zig b/zig/build/cuda.zig index 75cf7b194d8..96a9a4a69a1 100644 --- a/zig/build/cuda.zig +++ b/zig/build/cuda.zig @@ -273,6 +273,7 @@ pub fn hostTests(b: *std.Build, draft_ids: *std.Build.Module, build_options: *st @import("flashnext_glue_host.zig").steps(b, cuda, mods.core, flashnextModule(b, host, .debug, cuda, mods.core, mods.lanes, mods.qwen_vision, mods.api), step); @import("flashnext_scoring_host.zig").steps(b, cuda, mods.core, mods.lanes, flashnextModule(b, host, .debug, cuda, mods.core, mods.lanes, mods.qwen_vision, mods.api), step); b.step("test-pocket-device-host", "Actual pocket device hooks under CUDA ABI failures").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = flashnextModule(b, host, .debug, cuda, mods.core, mods.lanes, mods.qwen_vision, mods.api), .filters = &.{"Learning persistence:"} })).step); + b.step("test-flashnext-readout-fused-host", "The fused read-out's down tile choice and its refusals by name, without a GPU").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = flashnextModule(b, host, .debug, cuda, mods.core, mods.lanes, mods.qwen_vision, mods.api), .filters = &.{"fused read-out:"} })).step); b.step("test-living-host", "Family-neutral learner, saved form and commit gate on host").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = mods.living })).step); const shard_tests = b.createModule(.{ .root_source_file = b.path("zig/src/living_shards_test.zig"), .target = host, .optimize = .debug, .link_libc = true }); shard_tests.addImport("living", mods.living); diff --git a/zig/build/cuda_kernels.zig b/zig/build/cuda_kernels.zig index 9e8947a7280..6dc95046a32 100644 --- a/zig/build/cuda_kernels.zig +++ b/zig/build/cuda_kernels.zig @@ -82,6 +82,7 @@ pub const kernels = [_]Kernel{ .{ .name = "qmm_prefill", .flags = &.{"-O3"} }, .{ .name = "flashnext_fact", .flags = &.{"-O3"} }, // ours: prompt rows on qmm.cu's factored arithmetic .{ .name = "flashnext_hcf", .flags = glue }, // ours: the hyper-connection read-out's prompt tiles, fn_hc's bits + .{ .name = "flashnext_hcn", .flags = glue }, // ours: the BF16 read-out's prompt tiles, the normalize folded in .{ .name = "flashnext_fexp", .flags = &.{"-O3"} }, // ours: prompt pairs' experts on expert_rows' factored arithmetic .{ .name = "w4a8_prefill", .flags = &.{"-O3"} }, // ours: prompt matmuls, int8 activations on MLX affine 4-bit weights .{ .name = "experts", .flags = &.{"-O3"} }, // cuda/experts.py, tensorfold_experts_v7 diff --git a/zig/kernels/cuda/contract_controls_set.cu b/zig/kernels/cuda/contract_controls_set.cu index d5530572242..7b5e05d389b 100644 --- a/zig/kernels/cuda/contract_controls_set.cu +++ b/zig/kernels/cuda/contract_controls_set.cu @@ -7,3 +7,4 @@ #include "contract_nemo_audio_controls.cuh" #include "contract_idol_controls.cuh" #include "contract_embed_controls.cuh" +#include "contract_hcn_controls.cuh" diff --git a/zig/kernels/cuda/contract_hcn_controls.cuh b/zig/kernels/cuda/contract_hcn_controls.cuh new file mode 100644 index 00000000000..b0a844b92ba --- /dev/null +++ b/zig/kernels/cuda/contract_hcn_controls.cuh @@ -0,0 +1,17 @@ +// The fused read-out's planted controls: fn_hcn_down3 rounding toward zero, fn_hcn_up3 gating unrounded up rows. +#pragma once + +#include "flashnext_hcn.cuh" + +extern "C" __global__ void __launch_bounds__(hcn::DN_THREADS) tf_ctl_hcn_down3_rz( + const __nv_bfloat16* __restrict__ H, const float* __restrict__ PSS, const float* __restrict__ SCALE, + const uint2* __restrict__ W, float* __restrict__ PART, int M, int N, int K, int SK, int D, int NC, int SS, float eps) { + hcn::down_body<3, 3, true>(H, PSS, SCALE, W, PART, M, N, K, SK, D, NC, SS, eps); +} + +extern "C" __global__ void __launch_bounds__(256) tf_ctl_hcn_up3_raw( + const __nv_bfloat16* __restrict__ ACT, const uint2* __restrict__ W, const __nv_bfloat16* __restrict__ H, + const float* __restrict__ PSS, const float* __restrict__ SCALE, __nv_bfloat16* __restrict__ MIXED, + float* __restrict__ XSM, int M, int D, int NC, float eps) { + hcn::upmix_body<3, 5, true>(ACT, W, H, PSS, SCALE, MIXED, XSM, M, D, NC, eps); +} diff --git a/zig/kernels/cuda/flashnext_hcn.cu b/zig/kernels/cuda/flashnext_hcn.cu new file mode 100644 index 00000000000..70c2be9a0dd --- /dev/null +++ b/zig/kernels/cuda/flashnext_hcn.cu @@ -0,0 +1,21 @@ +// Flash Next's BF16 read-out prompt tiles: the down at three row tiles and the up+mix (flashnext_hcn.cuh's bodies). +#include "flashnext_hcn.cuh" + +#define HCN_DOWN(NAME, MT) \ + extern "C" __global__ void __launch_bounds__(hcn::DN_THREADS) NAME( \ + const __nv_bfloat16* __restrict__ H, const float* __restrict__ PSS, const float* __restrict__ SCALE, \ + const uint2* __restrict__ W, float* __restrict__ PART, int M, int N, int K, int SK, int D, int NC, int SS, \ + float eps) { \ + hcn::down_body(H, PSS, SCALE, W, PART, M, N, K, SK, D, NC, SS, eps); \ + } + +HCN_DOWN(fn_hcn_down2, 2) +HCN_DOWN(fn_hcn_down3, 3) +HCN_DOWN(fn_hcn_down4, 4) + +extern "C" __global__ void __launch_bounds__(256) fn_hcn_up3(const __nv_bfloat16* __restrict__ ACT, const uint2* __restrict__ W, + const __nv_bfloat16* __restrict__ H, const float* __restrict__ PSS, + const float* __restrict__ SCALE, __nv_bfloat16* __restrict__ MIXED, + float* __restrict__ XSM, int M, int D, int NC, float eps) { + hcn::upmix_body<3, 5>(ACT, W, H, PSS, SCALE, MIXED, XSM, M, D, NC, eps); +} diff --git a/zig/kernels/cuda/flashnext_hcn.cuh b/zig/kernels/cuda/flashnext_hcn.cuh new file mode 100644 index 00000000000..6f432c49c98 --- /dev/null +++ b/zig/kernels/cuda/flashnext_hcn.cuh @@ -0,0 +1,293 @@ +// Flash Next's BF16 read-out on prompt tiles: the normalize folded into the down and the up+mix, the chain's bits. +#pragma once + +#include +#include + +#include "common/fold.cuh" +#include "common/glue_math.cuh" +#include "common/qmm_frag.cuh" + +namespace hcn { +using namespace qmm_frag; +using tf_glue::bf; +using tf_glue::rbf; + +__device__ __forceinline__ float bsig(float x) { return rbf(tf_glue::tf_sigmoid(x)); } + +// fn_hc_normalize2's row scale: the stream's 256-column square sums in order, then tf_common::rms_scale +__device__ __forceinline__ float rinv_of(const float* __restrict__ pss, long long r, int st, int NC, int SS, int D, float eps) { + const float total = tf_common::sum_rn(NC, [&](int c) { return pss[(r * NC + c) * SS + st]; }); + return tf_common::rms_scale(total, D, eps); +} + +// down: [rows, K] normed streams x [N <= 336, K] bf16 weights -> fp32 [rows, N]; 16 MT rows a CTA +constexpr int DN_THREADS = 224; // 7 warps, three n8 tiles each: columns [0, 160) and [160, 336) +constexpr int DN_SPLIT = 20; // n8 tiles of the first column tile +constexpr int DN_SS = 8; // streams at most + +template +struct DnShape { + static constexpr int BM = 16 * MT; + static constexpr int STAGE = BM * 128; + static constexpr int SMEM = STAGES * STAGE + BM * DN_SS * 4; +}; + +// RZ rounds the normed rows toward zero: the kernel contract's planted control, never an engine kernel +template +__device__ __forceinline__ void down_body(const __nv_bfloat16* __restrict__ H, const float* __restrict__ PSS, + const float* __restrict__ SCALE, const uint2* __restrict__ W, + float* __restrict__ PART, int M, int N, int K, int SK, int D, int NC, int SS, + float eps) { + using S = DnShape; + constexpr int BM = S::BM; + extern __shared__ __align__(128) unsigned char buf[]; + float* rinv_s = reinterpret_cast(buf + STAGES * S::STAGE); + const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5, g8 = lane >> 2, t4 = lane & 3; + const int KG = K / 64, per = KG / SK; + const int ct = blockIdx.x & 1, m0 = (blockIdx.x >> 1) * BM; + + for (int i = tid; i < BM * SS; i += DN_THREADS) + rinv_s[(i / SS) * DN_SS + i % SS] = rinv_of(PSS, min(m0 + i / SS, M - 1), i % SS, NC, SS, D, eps); + + const uint2* wp[3]; + bool valid[3]; +#pragma unroll + for (int j = 0; j < 3; ++j) { + const int n8 = ct * DN_SPLIT + warp * 3 + j; + valid[j] = n8 * 8 < N && (ct == 1 || n8 < DN_SPLIT); + wp[j] = W + static_cast(n8 >> 3) * KG * 1024 + (n8 & 7) * 128 + lane; + } + + auto stage = [&](int s) { return buf + s * S::STAGE; }; + auto load = [&](int s, int g) { + unsigned char* p = stage(s); + for (int c = tid; c < BM * 8; c += DN_THREADS) { + const int r = c >> 3, ch = c & 7, row = min(m0 + r, M - 1); + cp16z(p + r * 128 + swz<8>(r, ch) * 16, H + static_cast(row) * K + g * 64 + ch * 8, m0 + r < M); + } + }; + auto loadb = [&](int g, uint2 (&b)[3][4]) { +#pragma unroll + for (int j = 0; j < 3; ++j) +#pragma unroll + for (int kt = 0; kt < 4; ++kt) b[j][kt] = valid[j] ? __ldg(wp[j] + static_cast(g) * 1024 + kt * 32) : make_uint2(0u, 0u); + }; + + float acc[MT][3][4], tot[MT][3][4]; +#pragma unroll + for (int i = 0; i < MT; ++i) +#pragma unroll + for (int j = 0; j < 3; ++j) +#pragma unroll + for (int e = 0; e < 4; ++e) acc[i][j][e] = 0.0f; + +#pragma unroll + for (int s = 0; s < STAGES - 1; ++s) { + if (s < KG) load(s, s); + commit(); + } + uint2 bufa[3][4], bufb[3][4]; + loadb(0, bufa); + + auto body = [&](int it, uint2 (&cur)[3][4], uint2 (&nxt)[3][4]) { + wait(); + __syncthreads(); + const int next = it + STAGES - 1; + if (next < KG) load(next % STAGES, next); + commit(); + if (it + 1 < KG) loadb(it + 1, nxt); + unsigned char* p = stage(it % STAGES); + { + // x = bf16(h * rinv[row, stream] * scale[k]) as fn_hc_normalize2 rounds it, in place + const int s_id = (it * 64) / D; + for (int c = tid; c < BM * 8; c += DN_THREADS) { + const int r = c >> 3, ch = c & 7; + uint4* cell = reinterpret_cast(p + r * 128 + swz<8>(r, ch) * 16); + const uint4 raw = *cell; + const __nv_bfloat16* hv = reinterpret_cast(&raw); + const float rv = rinv_s[r * DN_SS + s_id]; + const float4 sa = __ldg(reinterpret_cast(SCALE + it * 64 + ch * 8)); + const float4 sb = __ldg(reinterpret_cast(SCALE + it * 64 + ch * 8 + 4)); + const float sv[8] = {sa.x, sa.y, sa.z, sa.w, sb.x, sb.y, sb.z, sb.w}; + __nv_bfloat16 o8[8]; +#pragma unroll + for (int i = 0; i < 8; ++i) { + const float v = __fmul_rn(__fmul_rn(bf(hv[i]), rv), sv[i]); + if constexpr (RZ) o8[i] = __float2bfloat16_rz(v); + else o8[i] = __float2bfloat16_rn(v); + } + *cell = *reinterpret_cast(o8); + } + } + __syncthreads(); +#pragma unroll + for (int kt = 0; kt < 4; ++kt) { + uint32_t a[MT][4]; +#pragma unroll + for (int i = 0; i < MT; ++i) { + const int r = i * 16 + (lane & 7) + ((lane >> 3) & 1) * 8; + const int ch = kt * 2 + (lane >> 4); + ldmatrix4(a[i], p + r * 128 + swz<8>(r, ch) * 16); + } +#pragma unroll + for (int j = 0; j < 3; ++j) + if (valid[j]) { +#pragma unroll + for (int i = 0; i < MT; ++i) mma(acc[i][j], a[i], cur[j][kt].x, cur[j][kt].y); + } + } + if ((it + 1) % per == 0) { +#pragma unroll + for (int i = 0; i < MT; ++i) +#pragma unroll + for (int j = 0; j < 3; ++j) +#pragma unroll + for (int e = 0; e < 4; ++e) { + tot[i][j][e] = it + 1 == per ? acc[i][j][e] : __fadd_rn(tot[i][j][e], acc[i][j][e]); + acc[i][j][e] = 0.0f; + } + } + }; + for (int it = 0; it < KG; it += 2) { + body(it, bufa, bufb); + if (it + 1 < KG) body(it + 1, bufb, bufa); + } + wait<0>(); +#pragma unroll + for (int i = 0; i < MT; ++i) +#pragma unroll + for (int j = 0; j < 3; ++j) { + if (!valid[j]) continue; + const int col = (ct * DN_SPLIT + warp * 3 + j) * 8 + 2 * t4; +#pragma unroll + for (int h = 0; h < 2; ++h) { + const int row = m0 + i * 16 + g8 + h * 8; + if (row >= M) continue; + float* dst = PART + static_cast(row) * N + col; + if (col + 1 < N) { + if ((N & 1) == 0) *reinterpret_cast(dst) = make_float2(tot[i][j][2 * h], tot[i][j][2 * h + 1]); + else { + dst[0] = tot[i][j][2 * h]; + dst[1] = tot[i][j][2 * h + 1]; + } + } else if (col < N) dst[0] = tot[i][j][2 * h]; + } + } +} + +// up + mix: act times [4 D, K] bf16 weights, gated onto the normed streams, mixed; a CTA 16 MT rows by 32 columns. +template +struct UpShape { + static constexpr int BM = 16 * MT; + static constexpr int K = KG * 64; + static constexpr int A = BM * K * 2; // act rows, swizzled by 128-byte groups + static constexpr int PARTS = BM * 4 * 32 * 4 + BM * 32 * 4; // each stream's terms, then the mixed rows (on A) + static constexpr int HS = BM * 4 * 32 * 2; // the streams' 32 dimensions of the CTA's rows + static constexpr int RV = BM * 4 * 4; + static constexpr int SMEM = (A > PARTS ? A : PARTS) + HS + RV; +}; + +// RAW gates the up rows before their bf16 rounding: the kernel contract's planted control, never an engine kernel +template +__device__ __forceinline__ void upmix_body(const __nv_bfloat16* __restrict__ ACT, const uint2* __restrict__ W, + const __nv_bfloat16* __restrict__ H, const float* __restrict__ PSS, + const float* __restrict__ SCALE, __nv_bfloat16* __restrict__ MIXED, + float* __restrict__ XSM, int M, int D, int NC, float eps) { + using S = UpShape; + constexpr int BM = S::BM, K = S::K, SS = 4; + extern __shared__ __align__(128) unsigned char buf[]; + unsigned char* As = buf; + constexpr int ABYTES = S::A > S::PARTS ? S::A : S::PARTS; + __nv_bfloat16* Hs = reinterpret_cast<__nv_bfloat16*>(buf + ABYTES); + float* rinv_s = reinterpret_cast(buf + ABYTES + S::HS); + const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5, g8 = lane >> 2, t4 = lane & 3; + const int dt = D / 32; + const int m0 = (blockIdx.x / dt) * BM, d0 = (blockIdx.x % dt) * 32; + const int sw = warp >> 1, q0 = (warp & 1) * 2; + + // this warp's weights: the stream's two n8 tiles, every k16 step, straight from memory + uint2 b[KG][4][2]; + const uint2* wp[2]; +#pragma unroll + for (int j = 0; j < 2; ++j) { + const int c8 = sw * D + d0 + (q0 + j) * 8; + wp[j] = W + static_cast(c8 >> 6) * KG * 1024 + ((c8 >> 3) & 7) * 128 + lane; + } +#pragma unroll + for (int g = 0; g < KG; ++g) +#pragma unroll + for (int kt = 0; kt < 4; ++kt) +#pragma unroll + for (int j = 0; j < 2; ++j) b[g][kt][j] = __ldg(wp[j] + g * 1024 + kt * 32); + + for (int c = tid; c < BM * (K / 8); c += 256) { + const int r = c / (K / 8), cc = c % (K / 8), g = cc >> 3, ch = cc & 7, row = min(m0 + r, M - 1); + cp16z(As + r * (K * 2) + g * 128 + swz<8>(r, ch) * 16, ACT + static_cast(row) * K + cc * 8, m0 + r < M); + } + for (int c = tid; c < BM * SS * 4; c += 256) { + const int r = c / (SS * 4), s = (c >> 2) % SS, q = c & 3, row = min(m0 + r, M - 1); + cp16z(reinterpret_cast(Hs) + ((r * SS + s) * 32 + q * 8) * 2, + H + static_cast(row) * (SS * D) + s * D + d0 + q * 8, m0 + r < M); + } + commit(); + for (int i = tid; i < BM * SS; i += 256) rinv_s[i] = rinv_of(PSS, min(m0 + i / SS, M - 1), i % SS, NC, SS, D, eps); + wait<0>(); + __syncthreads(); + + float acc[MT][2][4]; +#pragma unroll + for (int i = 0; i < MT; ++i) +#pragma unroll + for (int j = 0; j < 2; ++j) +#pragma unroll + for (int e = 0; e < 4; ++e) acc[i][j][e] = 0.0f; +#pragma unroll + for (int g = 0; g < KG; ++g) +#pragma unroll + for (int kt = 0; kt < 4; ++kt) { + uint32_t a[MT][4]; +#pragma unroll + for (int i = 0; i < MT; ++i) { + const int r = i * 16 + (lane & 7) + ((lane >> 3) & 1) * 8; + const int ch = kt * 2 + (lane >> 4); + ldmatrix4(a[i], As + r * (K * 2) + g * 128 + swz<8>(r, ch) * 16); + } +#pragma unroll + for (int j = 0; j < 2; ++j) +#pragma unroll + for (int i = 0; i < MT; ++i) mma(acc[i][j], a[i], b[g][kt][j].x, b[g][kt][j].y); + } + __syncthreads(); // A is dead: its bytes now hold the terms + float* part = reinterpret_cast(As); + float* mixed_s = part + BM * 4 * 32; +#pragma unroll + for (int i = 0; i < MT; ++i) +#pragma unroll + for (int j = 0; j < 2; ++j) +#pragma unroll + for (int e = 0; e < 4; ++e) { + const int rr = i * 16 + g8 + 8 * (e >> 1), dd = (q0 + j) * 8 + 2 * t4 + (e & 1); + const float nv = rbf(__fmul_rn(__fmul_rn(bf(Hs[(rr * SS + sw) * 32 + dd]), rinv_s[rr * SS + sw]), SCALE[sw * D + d0 + dd])); + const float gate = RAW ? bsig(acc[i][j][e]) : bsig(rbf(acc[i][j][e])); + part[(sw * BM + rr) * 32 + dd] = rbf(__fmul_rn(gate, nv)); + } + __syncthreads(); + for (int e = tid; e < BM * 32; e += 256) { + const int rr = e >> 5, dd = e & 31; + float total = 0.0f; +#pragma unroll + for (int s = 0; s < SS; ++s) total = __fadd_rn(total, part[(s * BM + rr) * 32 + dd]); + const float m = rbf(__fdiv_rn(total, static_cast(SS))); + mixed_s[e] = m; + if (m0 + rr < M) MIXED[static_cast(m0 + rr) * D + d0 + dd] = __float2bfloat16_rn(m); + } + __syncthreads(); + if (tid < BM && m0 + tid < M) { + float sum = 0.0f; + for (int k = 0; k < 32; ++k) sum = __fadd_rn(sum, mixed_s[tid * 32 + k]); + XSM[static_cast(m0 + tid) * dt + d0 / 32] = sum; + } +} + +} // namespace hcn diff --git a/zig/src/core/contract/flashnext_tile_records.zig b/zig/src/core/contract/flashnext_tile_records.zig index 9035684c534..326fc0f67d0 100644 --- a/zig/src/core/contract/flashnext_tile_records.zig +++ b/zig/src/core/contract/flashnext_tile_records.zig @@ -29,6 +29,10 @@ pub const cuda = [_]CudaRecord{ .{ .launch = .{ .name = "flashnext_hc fn_hc_writeback_norm_slices", .symbol = "fn_hc_writeback_norm_slices", .image = "flashnext_hc", .threads = 256 }, .usage = .{ .{ .regs = 64, .static = 1296, .bound = 256 }, .{ .regs = 64, .static = 1296, .bound = 256 }, .{ .regs = 64, .static = 1296, .bound = 256 }, .{ .regs = 64, .static = 1296, .bound = 256 }, .{ .regs = 64, .static = 1296, .bound = 256 } } }, .{ .launch = .{ .name = "prompt16 tf_prompt_bf16", .symbol = "tf_prompt_bf16", .image = "prompt16", .threads = 256, .dynamic = 98304, .opt_in = true }, .usage = .{ .{ .regs = 255, .static = 0, .bound = 256 }, .{ .regs = 255, .static = 0, .bound = 256 }, .{ .regs = 255, .static = 0, .bound = 256 }, .{ .regs = 255, .static = 0, .bound = 256 }, .{ .regs = 255, .static = 0, .bound = 256 } } }, .{ .launch = .{ .name = "prompt16 tf_prompt_bf16_f32", .symbol = "tf_prompt_bf16_f32", .image = "prompt16", .threads = 256, .dynamic = 98304, .opt_in = true }, .usage = .{ .{ .regs = 255, .static = 0, .bound = 256 }, .{ .regs = 255, .static = 0, .bound = 256 }, .{ .regs = 255, .static = 0, .bound = 256 }, .{ .regs = 255, .static = 0, .bound = 256 }, .{ .regs = 255, .static = 0, .bound = 256 } } }, + .{ .launch = .{ .name = "flashnext_hcn fn_hcn_down2", .symbol = "fn_hcn_down2", .image = "flashnext_hcn", .threads = 224, .dynamic = 13312 }, .usage = .{ .{ .regs = 162, .static = 0, .bound = 224 }, .{ .regs = 162, .static = 0, .bound = 224 }, .{ .regs = 162, .static = 0, .bound = 224 }, .{ .regs = 152, .static = 0, .bound = 224 }, .{ .regs = 152, .static = 0, .bound = 224 } } }, + .{ .launch = .{ .name = "flashnext_hcn fn_hcn_down3", .symbol = "fn_hcn_down3", .image = "flashnext_hcn", .threads = 224, .dynamic = 19968 }, .usage = .{ .{ .regs = 191, .static = 0, .bound = 224 }, .{ .regs = 191, .static = 0, .bound = 224 }, .{ .regs = 191, .static = 0, .bound = 224 }, .{ .regs = 189, .static = 0, .bound = 224 }, .{ .regs = 189, .static = 0, .bound = 224 } } }, + .{ .launch = .{ .name = "flashnext_hcn fn_hcn_down4", .symbol = "fn_hcn_down4", .image = "flashnext_hcn", .threads = 224, .dynamic = 26624 }, .usage = .{ .{ .regs = 221, .static = 0, .bound = 224 }, .{ .regs = 222, .static = 0, .bound = 224 }, .{ .regs = 222, .static = 0, .bound = 224 }, .{ .regs = 206, .static = 0, .bound = 224 }, .{ .regs = 206, .static = 0, .bound = 224 } } }, + .{ .launch = .{ .name = "flashnext_hcn fn_hcn_up3", .symbol = "fn_hcn_up3", .image = "flashnext_hcn", .threads = 256, .dynamic = 43776 }, .usage = .{ .{ .regs = 126, .static = 0, .bound = 256 }, .{ .regs = 126, .static = 0, .bound = 256 }, .{ .regs = 126, .static = 0, .bound = 256 }, .{ .regs = 127, .static = 0, .bound = 256 }, .{ .regs = 127, .static = 0, .bound = 256 } } }, }; /// nvcc 13.2's records where it compiles these tiles differently from 13.0. diff --git a/zig/src/cuda/kernels.zig b/zig/src/cuda/kernels.zig index b31b4b41419..c1f96bf4533 100644 --- a/zig/src/cuda/kernels.zig +++ b/zig/src/cuda/kernels.zig @@ -46,6 +46,7 @@ pub const qmm: []const u8 = if (available) &Blob("fatbin_qmm").bytes else &.{}; pub const qmm_prefill: []const u8 = if (available) &Blob("fatbin_qmm_prefill").bytes else &.{}; pub const flashnext_fact: []const u8 = if (available) &Blob("fatbin_flashnext_fact").bytes else &.{}; pub const flashnext_hcf: []const u8 = if (available) &Blob("fatbin_flashnext_hcf").bytes else &.{}; +pub const flashnext_hcn: []const u8 = if (available) &Blob("fatbin_flashnext_hcn").bytes else &.{}; pub const flashnext_fexp: []const u8 = if (available) &Blob("fatbin_flashnext_fexp").bytes else &.{}; pub const w4a8_prefill: []const u8 = if (available) &Blob("fatbin_w4a8_prefill").bytes else &.{}; pub const experts: []const u8 = if (available) &Blob("fatbin_experts").bytes else &.{}; diff --git a/zig/src/families/flashnext/cuda_batch.zig b/zig/src/families/flashnext/cuda_batch.zig index e1ce349aa16..d0f693fc858 100644 --- a/zig/src/families/flashnext/cuda_batch.zig +++ b/zig/src/families/flashnext/cuda_batch.zig @@ -200,6 +200,7 @@ pub fn Pass(comptime Tri: type) type { const act = s.act + r0 * low * 2; const xs_act = s.xs_act + r0 * (low / 32) * 4; if (hc_w.down.native != null) { + if (std.meta.eql(keep, HcKeep{}) and hc.promptFused(self, hc_w, n)) return tiles.readoutFused(self.tri, self.k, self.stream, self.s, hc_w, r0, n); try self.tri.hcNormalize(h, pss, hc_w.scale.ptr, norm, eps, n, dims, streams); return hc.readoutNative(self, hc_w, r0, n); } diff --git a/zig/src/families/flashnext/cuda_batch_hc.zig b/zig/src/families/flashnext/cuda_batch_hc.zig index a6ff78fef89..312f9898cc6 100644 --- a/zig/src/families/flashnext/cuda_batch_hc.zig +++ b/zig/src/families/flashnext/cuda_batch_hc.zig @@ -2,6 +2,7 @@ const std = @import("std"); const wt = @import("cuda_prompt_wt.zig"); const parts = @import("cuda_batch_state.zig"); +const tiles = @import("cuda_tiles.zig"); const dims = wt.dims; const streams = wt.streams; @@ -17,10 +18,15 @@ pub fn on() bool { return @import("sys").environment.read(bool, "TF_FLASHNEXT_HC_FUSE", true) catch true; } -/// Whether hc_w's read-out takes its normed rows from the writeback: native, nothing kept, 64 rows or more, our glue. +/// Whether hc_w's read-out takes its normed rows from the writeback: native, nothing kept, 64 rows or more, unfused. pub fn fuses(pass: anytype, hc_w: wt.HcW, n: usize, keep: parts.HcKeep) bool { return n >= 64 and hc_w.down.native != null and std.meta.eql(keep, parts.HcKeep{}) and dims == 2560 and - streams == 4 and pass.tri.writebackOwned() and pass.k.forms.hc_fuse; + streams == 4 and pass.tri.writebackOwned() and pass.k.forms.hc_fuse and !promptFused(pass, hc_w, n); +} + +/// Whether a prompt pass's rows take tiles.readoutFused: the setting, tiles.fused_rows or more, its BF16 shapes. +pub fn promptFused(pass: anytype, hc_w: wt.HcW, n: usize) bool { + return pass.k.forms.readout_fused and pass.hooks.prompt and n >= tiles.fused_rows and tiles.nativeFused(hc_w); } /// The pass's pending writeback with hc_w's normalize in the same launch: the normed rows readoutNative reads. diff --git a/zig/src/families/flashnext/cuda_batch_kernels.zig b/zig/src/families/flashnext/cuda_batch_kernels.zig index 3a401d18f83..65945d0e03f 100644 --- a/zig/src/families/flashnext/cuda_batch_kernels.zig +++ b/zig/src/families/flashnext/cuda_batch_kernels.zig @@ -41,6 +41,7 @@ pub const Forms = struct { in_pass: bool = true, // TF_FLASHNEXT_KEEP_INPASS readout_rows: usize = 64, // TF_FLASHNEXT_READOUT_ROWS (maxInt: never) fact_rows: usize = 64, // TF_FLASHNEXT_FACT_ROWS (maxInt: never) + readout_fused: bool = false, // TF_FLASHNEXT_READOUT_FUSED pub fn resolve() Forms { return .{ @@ -49,6 +50,7 @@ pub const Forms = struct { .in_pass = @import("cuda_lanes_snap.zig").keepInPass(), .readout_rows = @import("cuda_chunk.zig").readoutTileRows(), .fact_rows = @import("cuda_nvfp4_tile.zig").factRows(), + .readout_fused = @import("readout_fused.zig").on(), }; } }; diff --git a/zig/src/families/flashnext/cuda_disk.zig b/zig/src/families/flashnext/cuda_disk.zig index dddedaa7ee5..6ee26f07f05 100644 --- a/zig/src/families/flashnext/cuda_disk.zig +++ b/zig/src/families/flashnext/cuda_disk.zig @@ -121,7 +121,8 @@ pub fn policyOf(c: anytype) [13]u64 { e.chunk, e.busy_chunk, @intFromBool(f.gdn_fused), - @intFromBool(f.hc_fuse), + // TF_FLASHNEXT_HC_FUSE, and TF_FLASHNEXT_READOUT_FUSED in bit 1 (unset leaves the key as it was) + @intFromBool(f.hc_fuse) | @as(u64, @intFromBool(f.readout_fused)) << 1, @intFromBool(f.in_pass), f.readout_rows, f.fact_rows, diff --git a/zig/src/families/flashnext/cuda_launch.zig b/zig/src/families/flashnext/cuda_launch.zig index 4033df76aaa..f7237135973 100644 --- a/zig/src/families/flashnext/cuda_launch.zig +++ b/zig/src/families/flashnext/cuda_launch.zig @@ -24,6 +24,9 @@ pub const qmm = @import("cuda_qmm.zig"); pub const batch_state = @import("cuda_batch_state.zig"); pub const batch_gdn_lanes = @import("cuda_batch_gdn_lanes.zig"); pub const tile_kernels = @import("cuda_tile_kernels.zig"); +/// The prompt tiles' launches, the fused BF16 read-out's among them, which flashnext-readout-fused compares. +pub const tiles = @import("cuda_tiles.zig"); +pub const readout_fused = @import("readout_fused.zig"); pub const gdn = @import("cuda_gdn.zig"); pub const mlp = @import("cuda_mlp.zig"); pub const moe = @import("cuda_moe.zig"); @@ -451,6 +454,8 @@ test { _ = @import("cuda_mtp_graphs_test.zig"); _ = embed; _ = hc; + _ = tiles; + _ = readout_fused; _ = qmm; _ = gdn; _ = mlp; diff --git a/zig/src/families/flashnext/cuda_prompt_wt.zig b/zig/src/families/flashnext/cuda_prompt_wt.zig index 1c7ed4b5124..d94dec71780 100644 --- a/zig/src/families/flashnext/cuda_prompt_wt.zig +++ b/zig/src/families/flashnext/cuda_prompt_wt.zig @@ -524,6 +524,7 @@ pub fn loadHc(gpa: std.mem.Allocator, driver: *cuda.Driver, store: *Store, prefi defer if (inject) gpa.free(inj_w); defer if (inject) gpa.free(inj_s); defer if (inject) gpa.free(inj_b); + try @import("readout_fused.zig").refuse("CUDA with an MLX affine read-out", @import("readout_fused.zig").on()); const k8 = wide / 8; if (words.len != n * k8 * 4) return error.UnexpectedTensor; var down_q = try uploadTiled(gpa, driver, words, scales, biases, n, k8); diff --git a/zig/src/families/flashnext/cuda_tile_kernels.zig b/zig/src/families/flashnext/cuda_tile_kernels.zig index edb68ce9210..4ebebc61026 100644 --- a/zig/src/families/flashnext/cuda_tile_kernels.zig +++ b/zig/src/families/flashnext/cuda_tile_kernels.zig @@ -1,4 +1,4 @@ -//! The prompt tiles' modules (flashnext_fact, _hcf and _fexp): their instances' names, shared bytes and loading. +//! The prompt tiles' modules (flashnext_fact, _hcf, _hcn and _fexp): their instances' names, shared bytes and loading. const cuda = @import("cuda"); /// Prompt rows on qmm.cu's arithmetic (flashnext_fact.cu): 64 x 128 tiles, two groups a stage, the lane tile's bits. @@ -15,6 +15,21 @@ pub const fexp_smem: u32 = 41472; pub const fexp_tile: usize = 64; pub const cubin_fact_fold: [:0]const u8 = "_ZN4fact11fact_kernelILi64ELi128ELi2ELi4ELi3ELi2ELb0ELi2ELb1ELb1ELb1EEEvPK13__nv_bfloat16PKfPKjS3_S3_PvPfiiiiiii"; pub const fact_smem: u32 = 3 * (2 * 64 * 64 + 2 * 128 * 16 + 2 * 2 * 128 * 2 + 2 * 64 * 4); +/// The BF16 read-out's fused prompt tiles (flashnext_hcn.cu): the down in CTAs of 16 * mt rows, the up+mix at mt 3. +pub const hcn_down_names = [_][:0]const u8{ "fn_hcn_down2", "fn_hcn_down3", "fn_hcn_down4" }; +pub const hcn_down_mt = [_]usize{ 2, 3, 4 }; +pub const hcn_up_name: [:0]const u8 = "fn_hcn_up3"; +pub const hcn_up_mt: usize = 3; + +/// hcn::DnShape's shared bytes: three stages of 16 * mt rows of 64 columns, and the rows' scales. +pub fn hcnDownSmem(mt: usize) u32 { + return @intCast(3 * 16 * mt * 128 + 16 * mt * 8 * 4); +} + +/// hcn::UpShape's shared bytes at K = 320: the act rows (later the terms), the streams' columns and the rows' scales. +pub fn hcnUpSmem(mt: usize) u32 { + return @intCast(16 * mt * (640 + 256 + 16)); +} pub const TileKernels = struct { fact_mod: cuda.Module, @@ -23,6 +38,11 @@ pub const TileKernels = struct { hcf_mod: cuda.Module, hcf_down: cuda.Function, hcf_up: cuda.Function, + hcn_mod: cuda.Module, + hcn_down: [hcn_down_names.len]cuda.Function, + hcn_up: cuda.Function, + /// The device's SMs, over which the fused read-out picks its down tile. + sms: usize, fexp_mod: cuda.Module, fexp_up: cuda.Function, fexp_down: cuda.Function, @@ -47,10 +67,24 @@ pub const TileKernels = struct { try k.hcf_down.allowDynamicShared(hcf_down_smem); k.hcf_up = try k.hcf_mod.function(cubin_hcf_up); try k.hcf_up.allowDynamicShared(hcf_up_smem); + k.hcn_mod = try cuda.Module.load(d, cuda.kernels.flashnext_hcn); + errdefer k.hcn_mod.unload(); + for (&k.hcn_down, hcn_down_names, hcn_down_mt) |*f, sym, mt| { + f.* = try k.hcn_mod.function(sym); + try f.allowDynamicShared(hcnDownSmem(mt)); + } + k.hcn_up = try k.hcn_mod.function(hcn_up_name); + try k.hcn_up.allowDynamicShared(hcnUpSmem(hcn_up_mt)); + var dev: c_int = 0; + var sms: c_int = 0; + try d.check(d.api.cuCtxGetDevice(&dev), "cuCtxGetDevice"); + try d.check(d.api.cuDeviceGetAttribute(&sms, .multiprocessor_count, dev), "cuDeviceGetAttribute"); + k.sms = @intCast(@max(sms, 1)); return k; } pub fn unload(k: *TileKernels) void { + k.hcn_mod.unload(); k.hcf_mod.unload(); k.fexp_mod.unload(); k.fact_mod.unload(); diff --git a/zig/src/families/flashnext/cuda_tiles.zig b/zig/src/families/flashnext/cuda_tiles.zig index b62e0e79fd9..bd517194653 100644 --- a/zig/src/families/flashnext/cuda_tiles.zig +++ b/zig/src/families/flashnext/cuda_tiles.zig @@ -1,4 +1,5 @@ //! Prompt rows on tiles keeping #952's bits: the dense matmul (qmm.cu's arithmetic), the read-out and the experts. +const std = @import("std"); const cuda = @import("cuda"); const wt = @import("cuda_prompt_wt.zig"); const parts = @import("cuda_batch_state.zig"); @@ -89,6 +90,75 @@ pub fn readout(tri: anytype, k: *const Kernels, stream: cuda.Stream, s: *Scratch try tri.hcMixH(s.proj, h, rinv, hc_w.scale.ptr, s.mixed + r0 * dims * 2, s.xsm + r0 * (dims / 32) * 4, n, dims, streams); } +/// Rows of a prompt pass from which the BF16 read-out takes the fused tiles (TF_FLASHNEXT_READOUT_FUSED=1). +pub const fused_rows: usize = 768; + +/// Whether readoutFused takes these weights: the BF16 read-out at the shapes flashnext_hcn.cu's tiles are built for. +pub fn nativeFused(hc_w: HcW) bool { + const down = hc_w.down.native orelse return false; + const up = hc_w.up.native orelse return false; + return down.mode == .bf16 and up.mode == .bf16 and down.scale == 1.0 and up.scale == 1.0 and streams == 4 and + dims % 64 == 0 and down.k == wide and down.n == hc_w.n_down and down.n <= 336 and down.n % 2 == 0 and + up.k == low and low == 320 and up.n == wide; +} + +/// The down tile (16 * mt rows a CTA, two CTAs a row tile) whose CTAs take the fewest waves over `sms` times mt. +pub fn pickDown(n: usize, sms: usize) usize { + var best: usize = 0; + var best_cost: usize = std.math.maxInt(usize); + for (tk.hcn_down_mt, 0..) |mt, i| { + const cost = cdiv(cdiv(n, 16 * mt) * 2, @max(sms, 1)) * mt; + if (cost <= best_cost) { + best = i; + best_cost = cost; + } + } + return best; +} + +/// The fused down over rows [0, n) on `f`, a tile of 16 * mt rows: the streams normed on chip, times the BF16 down. +pub fn fusedDown(f: cuda.Function, mt: usize, stream: cuda.Stream, h: u64, pss: u64, scale: u64, down: cuda.qmmf.Weight, part: u64, n: usize, e: f32) !void { + var a: cuda.Args = .{}; + for ([_]u64{ h, pss, scale, down.codes, part }) |v| a.add(v); + for ([_]usize{ n, down.n, down.k, cuda.qmmf.slices(down), dims, dims / 256, streams }) |v| a.add(cint(v)); + a.add(e); + try cuda.launch.launch(f, .{ .grid = .{ .x = @intCast(cdiv(n, 16 * mt) * 2) }, .block = .{ .x = 224 }, .shared = tk.hcnDownSmem(mt) }, stream, &a); +} + +/// The fused up+mix over rows [0, n) on `f`: act times the BF16 up, gated onto the streams normed on chip, mixed. +pub fn fusedUpMix(f: cuda.Function, stream: cuda.Stream, act: u64, up: cuda.qmmf.Weight, h: u64, pss: u64, scale: u64, mixed: u64, xsm: u64, n: usize, e: f32) !void { + const mt = tk.hcn_up_mt; + var b: cuda.Args = .{}; + for ([_]u64{ act, up.codes, h, pss, scale, mixed, xsm }) |v| b.add(v); + for ([_]usize{ n, dims, dims / 256 }) |v| b.add(cint(v)); + b.add(e); + try cuda.launch.launch(f, .{ .grid = .{ .x = @intCast(cdiv(n, 16 * mt) * (dims / 32)) }, .block = .{ .x = 256 }, .shared = tk.hcnUpSmem(mt) }, stream, &b); +} + +/// Rows [r0, r0 + n) of the BF16 read-out in three launches with the five launches' bytes; no normed rows in memory. +pub fn readoutFused(tri: anytype, k: *const Kernels, stream: cuda.Stream, s: *Scratch, hc_w: HcW, r0: usize, n: usize) !void { + const down = hc_w.down.native orelse return error.UnexpectedTensor; + const up = hc_w.up.native orelse return error.UnexpectedTensor; + if (n * hc_w.n_down * 4 > s.hc_part_bytes) return error.UnexpectedTensor; // one slice within hc_part (hcPartRows) + const h = s.h + r0 * wide * 2; + const pss = s.pss + r0 * pss_n * 4; + const act = s.act + r0 * low * 2; + const xs_act = s.xs_act + r0 * (low / 32) * 4; + const inj = if (hc_w.has_inj == 1) s.inj + r0 * streams * 2 else act; + const di = pickDown(n, k.tiles.sms); + try fusedDown(k.tiles.hcn_down[di], tk.hcn_down_mt[di], stream, h, pss, hc_w.scale.ptr, down, s.hc_part, n, eps); + try tri.hcReduceAct(s.hc_part, act, xs_act, inj, 1, n, streams, low, hc_w.n_down, hc_w.has_inj); + try fusedUpMix(k.tiles.hcn_up, stream, act, up, h, pss, hc_w.scale.ptr, s.mixed + r0 * dims * 2, s.xsm + r0 * (dims / 32) * 4, n, eps); +} + +test "fused read-out: the down tile is the one whose waves over 48 SMs cost least" { + try std.testing.expectEqual(@as(usize, 4), tk.hcn_down_mt[pickDown(3072, 48)]); + try std.testing.expectEqual(@as(usize, 3), tk.hcn_down_mt[pickDown(2048, 48)]); + try std.testing.expectEqual(@as(usize, 4), tk.hcn_down_mt[pickDown(1536, 48)]); + try std.testing.expectEqual(@as(usize, 3), tk.hcn_down_mt[pickDown(1024, 48)]); + try std.testing.expectEqual(@as(usize, 2), tk.hcn_down_mt[pickDown(64, 48)]); +} + /// The grouped experts on flashnext_fexp.cu's 64-pair tiles (expert_rows' bits), wn column blocks a CTA. pub fn experts(stream: cuda.Stream, f: cuda.Function, wn: usize, x: u64, x_stride: usize, slot_n: usize, w: u64, kg: usize, nb: usize, plan: cuda.grouped.Plan, out: u64, n: usize, items: usize) !void { var a = cuda.experts.Affine4Experts.argsOf(x, x_stride, slot_n, w, kg, nb, plan, out, n); diff --git a/zig/src/families/flashnext/engine_load.zig b/zig/src/families/flashnext/engine_load.zig index fbe646ddb60..924bda0b4dd 100644 --- a/zig/src/families/flashnext/engine_load.zig +++ b/zig/src/families/flashnext/engine_load.zig @@ -47,6 +47,7 @@ pub fn loadConfigured(gpa: Allocator, io: std.Io, model_dir: []const u8, dump_di try @import("env_validate.zig").startup(); try window.validate(speed_up != null or platform.c.getenv("TF_FLASHNEXT_TP") != null); try load_admission.check(gpa, io, model_dir); + try @import("readout_fused.zig").refuse("Metal", @import("readout_fused.zig").on()); const memory = @import("flashnext_memory"); const weights = try memory.weightBytes(@import("core").checkpoint_host, gpa, io, model_dir); var inventory = try memory.weights_plan.read(@import("core").checkpoint_host.Checkpoint, @import("core").quant.mlx, gpa, io, model_dir); diff --git a/zig/src/families/flashnext/hip/load.zig b/zig/src/families/flashnext/hip/load.zig index 1b3d08dadca..bc9eec1adf3 100644 --- a/zig/src/families/flashnext/hip/load.zig +++ b/zig/src/families/flashnext/hip/load.zig @@ -393,6 +393,7 @@ test "the MTP head's HIP names follow the index's root, so oMLX's top-level mtp. /// One rank's weights (`rank` null: the whole model) from `ck`; rank 0 also holds the MTP head under `mtp_root`. pub fn load(gpa: Allocator, d: *const hip.Runtime, ck: *core.checkpoint.Checkpoint, c: *const config.Config, rank: ?Rank, act: model.Kind, mtp_root: []const u8) !Weights { + try @import("../readout_fused.zig").refuse("HIP", @import("../readout_fused.zig").on()); var w: Weights = .{ .gpa = gpa }; errdefer w.deinit(); const tables: Tables = .{ .ck = ck, .cfg = c }; diff --git a/zig/src/families/flashnext/readout_fused.zig b/zig/src/families/flashnext/readout_fused.zig new file mode 100644 index 00000000000..718b30eed96 --- /dev/null +++ b/zig/src/families/flashnext/readout_fused.zig @@ -0,0 +1,28 @@ +//! TF_FLASHNEXT_READOUT_FUSED: a CUDA prompt pass's BF16 read-out on two fused tiles; other backends refuse it. +const std = @import("std"); + +const name = "TF_FLASHNEXT_READOUT_FUSED"; + +/// The setting as the startup check accepted it: unset, blank or 0 is off. +pub fn on() bool { + // the startup check refused every malformed value already, so a plain default stands here + return @import("sys").environment.read(bool, name, false) catch false; +} + +/// A backend or read-out without the fused tiles stops the start with the setting on rather than taking the chain. +pub fn refuse(what: []const u8, fused: bool) !void { + if (!fused) return; + if (!@import("builtin").is_test) std.log.err("{s}=1: Flash Next on {s} has no fused read-out tiles; unset it or set 0", .{ name, what }); + return error.InvalidEnvironment; +} + +test "fused read-out: on stops Metal, HIP and an affine CUDA read-out, and off starts them" { + try std.testing.expectError(error.InvalidEnvironment, refuse("Metal", true)); + try refuse("HIP", false); + const metal = "try @import(\"readout_fused.zig\").refuse(\"Metal\", @import(\"readout_fused.zig\").on());"; + const hip = "try @import(\"../readout_fused.zig\").refuse(\"HIP\", @import(\"../readout_fused.zig\").on());"; + const affine = "try @import(\"readout_fused.zig\").refuse(\"CUDA with an MLX affine read-out\", @import(\"readout_fused.zig\").on());"; + try std.testing.expect(std.mem.indexOf(u8, @embedFile("engine_load.zig"), metal) != null); + try std.testing.expect(std.mem.indexOf(u8, @embedFile("hip/load.zig"), hip) != null); + try std.testing.expect(std.mem.indexOf(u8, @embedFile("cuda_prompt_wt.zig"), affine) != null); +} diff --git a/zig/src/native/cuda_disk_policy_test.zig b/zig/src/native/cuda_disk_policy_test.zig index 7e40928407a..543c3d26674 100644 --- a/zig/src/native/cuda_disk_policy_test.zig +++ b/zig/src/native/cuda_disk_policy_test.zig @@ -176,6 +176,9 @@ test "disk identity: Flash Next CUDA resolved prompt rows, kernel forms and expe try changed.append(t.allocator, try flashKey(&x, &c)); @field(k.forms, field) = 64; } + k.forms.readout_fused = true; // TF_FLASHNEXT_READOUT_FUSED=1: a prompt pass's BF16 read-out on the fused tiles + try changed.append(t.allocator, try flashKey(&x, &c)); + k.forms.readout_fused = false; k.expert_tile = .{ .mod = undefined, .fns = undefined, .resident = .{ 64, 64 }, .selection = .up }; const up = try flashKey(&x, &c); k.expert_tile.?.selection = .both; // the same grids: the selection alone moves the key @@ -216,7 +219,7 @@ test "disk identity: Flash Next CUDA prompt forms take each setting's value at l const env = @import("sys").env; const Engine = @typeInfo(@FieldType(flash.Cuda, "engine")).pointer.child; const Forms = @FieldType(@FieldType(Engine, "batch_k"), "forms"); - const names = [_][:0]const u8{ "TF_FLASHNEXT_GDN_FUSED", "TF_FLASHNEXT_HC_FUSE", "TF_FLASHNEXT_KEEP_INPASS", "TF_FLASHNEXT_READOUT_ROWS", "TF_FLASHNEXT_FACT_ROWS" }; + const names = [_][:0]const u8{ "TF_FLASHNEXT_GDN_FUSED", "TF_FLASHNEXT_HC_FUSE", "TF_FLASHNEXT_KEEP_INPASS", "TF_FLASHNEXT_READOUT_ROWS", "TF_FLASHNEXT_FACT_ROWS", "TF_FLASHNEXT_READOUT_FUSED" }; for (names) |n| _ = env.unsetenv(n); defer for (names) |n| { _ = env.unsetenv(n); @@ -229,6 +232,8 @@ test "disk identity: Flash Next CUDA prompt forms take each setting's value at l _ = env.setenv("TF_FLASHNEXT_FACT_ROWS", "32", 1); try t.expectEqual(@as(usize, 128), Forms.resolve().readout_rows); try t.expectEqual(@as(usize, 32), Forms.resolve().fact_rows); + _ = env.setenv("TF_FLASHNEXT_READOUT_FUSED", "1", 1); + try t.expect(Forms.resolve().readout_fused); } const nemotron = @import("nemotron"); diff --git a/zig/src/platform/environment.zig b/zig/src/platform/environment.zig index 973c53e67e1..60f26174040 100644 --- a/zig/src/platform/environment.zig +++ b/zig/src/platform/environment.zig @@ -213,6 +213,7 @@ pub const rules = [_]Rule{ .{ .name = "TF_FLASHNEXT_SHARED_DRAFTS", .scope = .flashnext, .kind = .flag, .forms = "0 or 1 (default 1)" }, .{ .name = "TF_FLASHNEXT_SHARED_SIDE", .scope = .flashnext, .kind = .flag, .forms = "0 or 1 (default 1)" }, .{ .name = "TF_FLASHNEXT_HC_FUSE", .scope = .flashnext, .kind = .flag, .forms = "0 or 1 (default 1)" }, + .{ .name = "TF_FLASHNEXT_READOUT_FUSED", .scope = .flashnext, .kind = .flag, .forms = "0 or 1 (default 0)" }, .{ .name = "TF_FLASHNEXT_KEEP_LATE", .scope = .flashnext, .kind = .flag, .forms = "0 or 1 (unset or blank leaves it unset)" }, .{ .name = "TF_FLASHNEXT_DECODE_GRAPH", .scope = .flashnext, .kind = .flag, .forms = "0 or 1 (default 0)" }, .{ .name = "TF_FLASHNEXT_SPLIT_DENSE", .scope = .flashnext, .kind = .flag, .forms = "0 or 1 (default 1)" }, diff --git a/zig/src/platform/environment_flashnext_test.zig b/zig/src/platform/environment_flashnext_test.zig index 84865f5baa4..6553fb344b8 100644 --- a/zig/src/platform/environment_flashnext_test.zig +++ b/zig/src/platform/environment_flashnext_test.zig @@ -33,13 +33,13 @@ fn check(name: []const u8, raw: []const u8, valid: bool) !void { try t.expect(std.mem.endsWith(u8, why.?, e.rule(name).forms)); } -test "Flash Next strict env: the table holds all 33 settings: 22 switches, 9 integers, 1 real, 1 structured" { +test "Flash Next strict env: the table holds all 34 settings: 23 switches, 9 integers, 1 real, 1 structured" { var counts: [4]usize = @splat(0); for (e.rules) |r| if (r.scope == .flashnext) { try t.expect(std.mem.startsWith(u8, r.name, "TF_FLASHNEXT_")); counts[@backingInt(group(r))] += 1; }; - try t.expectEqual([4]usize{ 22, 9, 1, 1 }, counts); + try t.expectEqual([4]usize{ 23, 9, 1, 1 }, counts); } test "Flash Next strict env: unset and blank settings both read as the caller's default" { diff --git a/zig/src/platform/environment_test.zig b/zig/src/platform/environment_test.zig index bbef20a040d..06605e1fc90 100644 --- a/zig/src/platform/environment_test.zig +++ b/zig/src/platform/environment_test.zig @@ -40,6 +40,8 @@ const valid = [_]Case{ .{ .name = "TF_CACHE_EVICT", .raw = "decayed_resume", .n = 1 }, .{ .name = "TF_FLASHNEXT_BATCH_DRAWS", .raw = "0", .n = 0 }, .{ .name = "TF_FLASHNEXT_BATCH_DRAWS", .raw = "1", .n = 1 }, + .{ .name = "TF_FLASHNEXT_READOUT_FUSED", .raw = "0", .n = 0 }, + .{ .name = "TF_FLASHNEXT_READOUT_FUSED", .raw = "1", .n = 1 }, .{ .name = "TENSORFOLD_VIDEO_TOKENS", .raw = "0", .n = 0 }, .{ .name = "TENSORFOLD_VIDEO_TOKENS", .raw = "18446744073709551615", .n = std.math.maxInt(u64) }, .{ .name = "TENSORFOLD_MAX_PDF_PAGES", .raw = "4294967295", .n = std.math.maxInt(u32) }, diff --git a/zig/tests/cuda/contract_flashnext_hcn.zig b/zig/tests/cuda/contract_flashnext_hcn.zig new file mode 100644 index 00000000000..f073dc3bc5a --- /dev/null +++ b/zig/tests/cuda/contract_flashnext_hcn.zig @@ -0,0 +1,273 @@ +//! The fused BF16 read-out's tiles under the contract: each bit-equal to the launches it replaces, with two controls. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const flash = @import("flashnext"); +const tc = @import("check.zig"); +const rig_ = @import("contract_rig.zig"); + +const c = core.contract.spec; +const g = core.contract.gates; +const tiles = flash.tiles; +const tk = flash.tile_kernels; + +const dims = 2560; +const streams = 4; +const wide = dims * streams; +const low = 320; +const n_down = low + streams; +const nc = dims / 256; +const eps: f32 = 1e-6; +const most = 3072; + +pub const Kind = enum { down, up }; +pub const Fault = enum { none, rz, raw }; +pub const Entry = struct { name: []const u8, kind: Kind, di: usize = 1, fault: Fault = .none }; + +pub const entries = [_]Entry{ + .{ .name = "cuda flashnext fn_hcn_down2 (normalize and fp32 down, 32-row tiles)", .kind = .down, .di = 0 }, + .{ .name = "cuda flashnext fn_hcn_down3 (normalize and fp32 down, 48-row tiles)", .kind = .down, .di = 1 }, + .{ .name = "cuda flashnext fn_hcn_down4 (normalize and fp32 down, 64-row tiles)", .kind = .down, .di = 2 }, + .{ .name = "cuda flashnext fn_hcn_up3 (bf16 up, gates and the four-stream mix)", .kind = .up }, + .{ .name = "control: fn_hcn_down3 rounding its normed rows toward zero", .kind = .down, .fault = .rz }, + .{ .name = "control: fn_hcn_up3 gating its up rows before their bf16 rounding", .kind = .up, .fault = .raw }, +}; + +fn noSums(_: c.Shape) usize { + return 0; +} + +pub fn spec(e: Entry) c.Spec { + return .{ + .name = e.name, + .accum = .none, + .depth = noSums, + .out = .raw, + .nan = .{ .stated = "every output byte equal to the launches it replaces, planted non-finite rows included" }, + .replaces = if (e.kind == .down) "fn_hc_normalize, then the qmmf lane's fp32 down" else "the qmmf lane's bf16 up, then fn_hc_dense_mix over fn_hc_normalize's rows", + .served = &.{ .{ .rows = 768, .n = dims, .k = 1 }, .{ .rows = 769, .n = dims, .k = 1 }, .{ .rows = 1000, .n = dims, .k = 1 }, .{ .rows = 1536, .n = dims, .k = 1 }, .{ .rows = 2053, .n = dims, .k = 1 }, .{ .rows = 3072, .n = dims, .k = 1 } }, + }; +} + +pub const Hcn = struct { + rig: rig_.Rig, + entry: Entry, + glue: *const flash.Glue, + lane: *const cuda.qmmf.Lane, + t: *const tk.TileKernels, + ctl: ?cuda.Function = null, + shape: c.Shape = .{ .rows = 0, .n = 0, .k = 0 }, + w: cuda.qmmf.Weight = undefined, + h: u64 = 0, + pss: u64 = 0, + scale: u64 = 0, + act: u64 = 0, + norm: u64 = 0, + up: u64 = 0, + part: u64 = 0, + lens: [2]usize = @splat(0), + outs: [2]u64 = @splat(0), + nout: usize = 0, + base: u64 = 0, + seen: std.ArrayList(u8) = .empty, + msg: [160]u8 = undefined, + + pub fn deinit(self: *Hcn) void { + self.seen.deinit(self.rig.gpu.gpa); + self.rig.deinit(); + } + + const vt = g.hooks(Hcn); + + pub fn kernel(self: *Hcn) g.Kernel { + return .{ .spec = spec(self.entry), .ctx = self, .vt = &vt, .control = if (self.entry.fault == .none) null else .shapes }; + } + + pub fn prepare(self: *Hcn, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + self.rig.reset(); + self.nout = 0; + self.shape = shape; + const m = shape.rows; + if (m == 0 or m > most or shape.n != dims) return false; + const a = self.rig.gpu.gpa; + var prng = std.Random.DefaultPrng.init(seed ^ 0x68636e); + const r = prng.random(); + const h = try a.alloc(u16, m * wide); + defer a.free(h); + for (h) |*x| x.* = c.toBf16(r.float(f32) * 6 - 3); + if (fill == .nonfinite) for (0..m) |row| { + h[row * wide + (row % streams) * dims + 5] = switch (row % 4) { + 0 => 0x7fc1, + 1 => 0x7f80, + 2 => 0xff80, + else => 0x8000, + }; + }; + const pss = try a.alloc(f32, m * nc * streams); + defer a.free(pss); + for (pss) |*x| x.* = 0.5 + r.float(f32) * 2; + const scale = try a.alloc(f32, wide); + defer a.free(scale); + for (scale) |*x| x.* = 0.5 + r.float(f32); + const rows: usize = if (self.entry.kind == .down) n_down else wide; + const k: usize = if (self.entry.kind == .down) wide else low; + const wt = try a.alloc(u16, rows * k); + defer a.free(wt); + const spread: f32 = if (self.entry.kind == .down) 0.04 else 0.4; + for (wt) |*x| x.* = c.toBf16((r.float(f32) * 2 - 1) * spread); + const packed_w = try a.alloc(u16, cuda.nvfp4.padded(rows) * k); + defer a.free(packed_w); + cuda.qmmf.packBf16(packed_w, wt, rows, k); + self.h = try self.rig.input(std.mem.sliceAsBytes(h)); + self.pss = try self.rig.input(std.mem.sliceAsBytes(pss)); + self.scale = try self.rig.input(std.mem.sliceAsBytes(scale)); + self.w = cuda.modelopt.bf16Weight(try self.rig.input(std.mem.sliceAsBytes(packed_w)), rows, k); + self.norm = try self.rig.scratch(m * wide * 2); + if (self.entry.kind == .down) { + try self.out(m * n_down * 4); // the down's fp32 rows + self.part = try self.rig.scratch(8 * m * n_down * 4); + } else { + const act = try a.alloc(u16, m * low); + defer a.free(act); + for (act) |*x| x.* = c.toBf16(r.float(f32) * 2 - 1); + self.act = try self.rig.input(std.mem.sliceAsBytes(act)); + self.up = try self.rig.scratch(m * wide * 2); + try self.out(m * dims * 2); // the mixed rows + try self.out(m * (dims / 32) * 4); // their 32-column sums + } + var total: usize = 0; + for (self.lens[0..self.nout]) |l| total += l; + self.base = try self.rig.scratch(total); + return true; + } + + fn out(self: *Hcn, len: usize) !void { + self.outs[self.nout] = try self.rig.output(len); + self.lens[self.nout] = len; + self.nout += 1; + } + + fn ours(self: *Hcn, o: []const u64) !void { + const m = self.shape.rows; + const s = self.rig.s; + if (self.entry.kind == .down) { + const f = self.ctl orelse self.t.hcn_down[self.entry.di]; + return tiles.fusedDown(f, tk.hcn_down_mt[self.entry.di], s, self.h, self.pss, self.scale, self.w, o[0], m, eps); + } + try tiles.fusedUpMix(self.ctl orelse self.t.hcn_up, s, self.act, self.w, self.h, self.pss, self.scale, o[0], o[1], m, eps); + } + + fn theirs(self: *Hcn, o: []const u64) !void { + const m = self.shape.rows; + const s = self.rig.s; + try self.glue.hcNormalize(s, self.h, self.pss, self.scale, self.norm, eps, m, dims, streams); + if (self.entry.kind == .down) return self.lane.matmulF32(s, self.norm, wide, m, self.w, o[0], self.part); + try self.lane.matmul(s, self.act, low, m, self.w, self.up, 0); + try self.glue.hcDenseMix(s, self.up, self.norm, o[0], o[1], m, dims, streams); + } + + pub fn run(self: *Hcn) !void { + try self.ours(self.outs[0..self.nout]); + try self.rig.s.synchronize(); + } + + /// The scratch the replaced launches write: the outputs' layout back to back, poisoned like them (0xff). + fn baseline(self: *Hcn) ![]const u8 { + var at = self.base; + var o: [2]u64 = undefined; + var total: usize = 0; + for (self.lens[0..self.nout], 0..) |l, i| { + o[i] = at; + at += l; + total += l; + } + const ff = try self.rig.gpu.gpa.alloc(u8, total); + defer self.rig.gpu.gpa.free(ff); + @memset(ff, 0xff); + try (cuda.DeviceBuffer{ .d = self.rig.gpu.d, .ptr = self.base, .len = total }).upload(0, ff); + try self.theirs(o[0..self.nout]); + try self.rig.s.synchronize(); + return self.rig.bytes(self.base, total); + } + + pub fn replaced(self: *Hcn) ![]const u8 { + return self.baseline(); + } + + /// Gate 1's stated rule: the outputs on the planted inputs equal the replaced launches' bytes. + pub fn check(self: *Hcn, gate: g.Gate) !?[]const u8 { + _ = gate; + self.seen.clearRetainingCapacity(); + try self.seen.appendSlice(self.rig.gpu.gpa, try self.rig.outputBytes()); + const want = try self.baseline(); + if (std.mem.eql(u8, self.seen.items, want)) return null; + return try std.fmt.bufPrint(&self.msg, "bytes differ from the replaced launches' from byte {d}", .{std.mem.indexOfDiff(u8, self.seen.items, want).?}); + } + + pub fn count(self: *Hcn) usize { + var total: usize = 0; + for (self.lens[0..self.nout]) |l| total += l; + return total; + } + + pub fn reference(_: *Hcn, _: []f64, _: []f64) !void { + return error.NoFloat64Reference; + } +}; + +/// The kernels, the chain they replace and the controls, on the heap: the gates hold pointers to them. +pub const Set = struct { + gpa: std.mem.Allocator, + glue: flash.Glue, + lane: cuda.qmmf.Lane, + t: tk.TileKernels, + ctl: cuda.Module, + items: [entries.len]Hcn = undefined, + + const controls = struct { + pub const bytes align(16) = @embedFile("fatbin_contract_controls").*; + }; + + /// The set, its kernels appended to `list`, each control after the kernels it breaks. + pub fn init(gpu: tc.Gpu, s: cuda.Stream, a: std.mem.Allocator, list: *std.ArrayList(g.Kernel)) !*Set { + const set = try gpu.gpa.create(Set); + errdefer gpu.gpa.destroy(set); + var glue = try flash.Glue.load(gpu.d); + errdefer glue.deinit(); + var lane = try cuda.qmmf.Lane.load(gpu.d, (try gpu.ctx.capability()) / 10); + errdefer lane.unload(); + var t = try tk.TileKernels.load(gpu.d); + errdefer t.unload(); + var ctl = try cuda.Module.load(gpu.d, &controls.bytes); + errdefer ctl.unload(); + set.* = .{ .gpa = gpu.gpa, .glue = glue, .lane = lane, .t = t, .ctl = ctl }; + try set.lane.loadPrompt(gpu.d); // the engine's lane: qmmf's BF16 prompt tiles (TF_FLASHNEXT_PROMPT_BF16) + const rz = try set.ctl.function("tf_ctl_hcn_down3_rz"); + try rz.allowDynamicShared(tk.hcnDownSmem(3)); + const raw = try set.ctl.function("tf_ctl_hcn_up3_raw"); + try raw.allowDynamicShared(tk.hcnUpSmem(tk.hcn_up_mt)); + for (&set.items, entries) |*x, e| x.* = .{ + .rig = .{ .gpu = gpu, .s = s }, + .entry = e, + .glue = &set.glue, + .lane = &set.lane, + .t = &set.t, + .ctl = switch (e.fault) { + .none => null, + .rz => rz, + .raw => raw, + }, + }; + for (&set.items) |*x| try list.append(a, x.kernel()); + return set; + } + + pub fn deinit(set: *Set) void { + for (&set.items) |*x| x.deinit(); + set.ctl.unload(); + set.t.unload(); + set.lane.unload(); + set.glue.deinit(); + set.gpa.destroy(set); + } +}; diff --git a/zig/tests/cuda/contract_flashnext_more.zig b/zig/tests/cuda/contract_flashnext_more.zig index bb2690a952f..7421a381ae7 100644 --- a/zig/tests/cuda/contract_flashnext_more.zig +++ b/zig/tests/cuda/contract_flashnext_more.zig @@ -8,6 +8,7 @@ const roll_k = @import("contract_flashnext_roll.zig"); const lanes_k = @import("contract_flashnext_lanes.zig"); const wbnorm_k = @import("contract_flashnext_wbnorm.zig"); const topk_k = @import("contract_flashnext_topk.zig"); +const hcn_k = @import("contract_flashnext_hcn.zig"); const flash = @import("flashnext"); const g = core.contract.gates; @@ -25,6 +26,7 @@ pub const Set = struct { glue: flash.Glue, wbnorm: [3]wbnorm_k.WbNorm, mtp: cuda.Module, + hcn: *hcn_k.Set, topk: topk_k.TopK, pub fn init(gpu: tc.Gpu, s: cuda.Stream, a: std.mem.Allocator, kernels: *std.ArrayList(g.Kernel)) !*Set { @@ -47,6 +49,8 @@ pub const Set = struct { errdefer self.glue.deinit(); for (std.enums.values(wbnorm_k.Mode), &self.wbnorm) |mode, *x| x.* = .{ .rig = .{ .gpu = gpu, .s = s }, .mode = mode, .glue = &self.glue }; for (&self.wbnorm) |*x| try kernels.append(a, x.kernel()); + self.hcn = try hcn_k.Set.init(gpu, s, a, kernels); + errdefer self.hcn.deinit(); self.mtp = try cuda.Module.load(gpu.d, cuda.kernels.flashnext_mtp); errdefer self.mtp.unload(); self.topk = .{ .rig = .{ .gpu = gpu, .s = s }, .f = try self.mtp.function("fn_row_topk") }; @@ -59,6 +63,7 @@ pub const Set = struct { self.roll.deinit(); for (&self.lanes) |*x| x.deinit(); for (&self.wbnorm) |*x| x.deinit(); + self.hcn.deinit(); self.topk.deinit(); self.mtp.unload(); self.glue.deinit(); diff --git a/zig/tests/cuda/contract_limits.zig b/zig/tests/cuda/contract_limits.zig index 4c9e7d021b0..45e56838263 100644 --- a/zig/tests/cuda/contract_limits.zig +++ b/zig/tests/cuda/contract_limits.zig @@ -28,6 +28,7 @@ pub fn image(name: []const u8) error{UnknownContractImage}![]const u8 { if (std.mem.eql(u8, name, "fp8_experts")) return kk.fp8_experts; if (std.mem.eql(u8, name, "mla")) return kk.mla; if (std.mem.eql(u8, name, "h3")) return &h3_image.bytes; + if (std.mem.eql(u8, name, "flashnext_hcn")) return kk.flashnext_hcn; inline for (.{ "qwen4_projection", "qwen4_hc", "qwen4_gdn", "qwen4_ple", "gemma4_ple" }) |n| if (std.mem.eql(u8, name, n)) return @field(kk, n); inline for (.{ "tree_round", "act_rows", "gdn_prep", "qk_rows", "norms", "moe", "experts", "qwen36_mtp", "nemotron_attention", "nemotron_route", "nemotron_latent", "qmm_group", "qmm_prefill", "lane_gemv", "prompt16", "qmmf", "ck_experts", "nvfp4_experts", "nvfp4_experts_tile", "nvfp4_experts32", "rank_sum", "prefill_attention", "vit", "embed_rows", "route_rows", "flashnext_gdn", "flashnext_batch", "flashnext_hc", "flashnext_attn", "flashnext_mtp", "qwen_vision", "exl3_linear", "exl3_experts", "exl3_candidate", "experts3", "experts3_prefill", "drama3", "drama3_fp8", "drama3_codec", "glm_mm", "glm_dflash", "glm_glue", "glm_ops", "glm_index", "nemotron_mamba", "sample", "qwen35", "qwen35_bf16_rows", "qwen35_keep", "qwen35_kv8", "w4a8_prefill", "qwen35_draft", "ck_lane", "gdn_train", "train_q4", "train_attn", "flashnext_train", "train", "attn_train", "qwen27_train", "tree_attention", "block_attention", "window_attention", "window_pages", "moe_glue", "dense_rows", "qmm", "flashnext_fact", "flashnext_hcf", "flashnext_fexp", "experts_rows", "nemotron_ops", "minimax_m3", "minimax_m3_attn", "experts_bf16", "nemo_audio", "moss_image", "idol", "lfm2_moe", "lfm2", "dots_mocr", "muse_glue", "muse_attention", "muse_linear", "muse_experts2", "muse_dflash", "muse_dflash2" }) |n| if (std.mem.eql(u8, name, n)) return @field(kk, n); diff --git a/zig/tests/cuda/flashnext_readout_fused.zig b/zig/tests/cuda/flashnext_readout_fused.zig new file mode 100644 index 00000000000..1ff52eb5a2e --- /dev/null +++ b/zig/tests/cuda/flashnext_readout_fused.zig @@ -0,0 +1,181 @@ +//! The fused BF16 read-out (flashnext_hcn.cu) against the five launches it replaces: every output byte, then times. +const std = @import("std"); +const cuda = @import("cuda"); +const flash = @import("flashnext"); +const check = @import("check.zig"); +const rig_ = @import("flashnext_rig.zig"); + +const tiles = flash.tiles; +const tk = flash.tile_kernels; + +const dims = 2560; +const streams = 4; +const wide = streams * dims; +const low = 320; +const n_down = low + streams; +const nc = dims / 256; +const eps: f32 = 1e-6; +const most = 3072; + +const Chain = struct { + r: *rig_.Rig, + g: *const flash.Glue, + lane: *const cuda.qmmf.Lane, + t: *const tk.TileKernels, + wdown: cuda.qmmf.Weight, + wup: cuda.qmmf.Weight, + h: u64, + pss: u64, + scale: u64, + norm: u64, + part: u64, + act: u64, + xs: u64, + inj: u64, + up: u64, + mixed: u64, + xsm: u64, + spart: u64, + rows: usize, + sms: usize, + + /// normalize, the lane's fp32 down, reduce_act, the lane's bf16 up and the dense mix, as readoutNative runs them + fn five(c: *Chain) !void { + const s = c.r.s; + try c.g.hcNormalize(s, c.h, c.pss, c.scale, c.norm, eps, c.rows, dims, streams); + try c.lane.matmulF32(s, c.norm, wide, c.rows, c.wdown, c.part, c.spart); + try c.g.hcReduceAct(s, c.part, c.act, c.xs, c.inj, 1, c.rows, streams, low, n_down, 1); + try c.lane.matmul(s, c.act, low, c.rows, c.wup, c.up, c.spart); + try c.g.hcDenseMix(s, c.up, c.norm, c.mixed, c.xsm, c.rows, dims, streams); + } + + /// the fused down, reduce_act and the fused up+mix, as readoutFused runs them + fn fused(c: *Chain) !void { + const s = c.r.s; + const di = tiles.pickDown(c.rows, c.sms); + try tiles.fusedDown(c.t.hcn_down[di], tk.hcn_down_mt[di], s, c.h, c.pss, c.scale, c.wdown, c.part, c.rows, eps); + try c.g.hcReduceAct(s, c.part, c.act, c.xs, c.inj, 1, c.rows, streams, low, n_down, 1); + try tiles.fusedUpMix(c.t.hcn_up, s, c.act, c.wup, c.h, c.pss, c.scale, c.mixed, c.xsm, c.rows, eps); + } + + fn poison(c: *Chain) !void { + const m = c.rows; + const bufs = [_][2]u64{ .{ c.part, m * n_down * 4 }, .{ c.act, m * low * 2 }, .{ c.xs, m * (low / 32) * 4 }, .{ c.inj, m * streams * 2 }, .{ c.mixed, m * dims * 2 }, .{ c.xsm, m * (dims / 32) * 4 } }; + for (bufs) |b| try (cuda.DeviceBuffer{ .d = c.r.gpu.d, .ptr = b[0], .len = b[1] }).fill8(0xff, c.r.s.handle); + } + + /// The read-out's outputs back to back: the down's fp32 rows, act, its sums, the gates, mixed and its sums. + fn outputs(c: *Chain, a: std.mem.Allocator) ![]u8 { + const m = c.rows; + var all: std.ArrayList(u8) = .empty; + try all.appendSlice(a, std.mem.sliceAsBytes(try c.r.back(f32, c.part, m * n_down))); + try all.appendSlice(a, std.mem.sliceAsBytes(try c.r.back(u16, c.act, m * low))); + try all.appendSlice(a, std.mem.sliceAsBytes(try c.r.back(f32, c.xs, m * (low / 32)))); + try all.appendSlice(a, std.mem.sliceAsBytes(try c.r.back(u16, c.inj, m * streams))); + try all.appendSlice(a, std.mem.sliceAsBytes(try c.r.back(u16, c.mixed, m * dims))); + try all.appendSlice(a, std.mem.sliceAsBytes(try c.r.back(f32, c.xsm, m * (dims / 32)))); + return all.items; + } +}; + +fn median(c: *Chain, comptime f: fn (*Chain) anyerror!void, start: cuda.Event, end: cuda.Event) !f64 { + var t: [9]f64 = undefined; + try f(c); + for (&t) |*x| { + try start.record(c.r.s); + for (0..10) |_| try f(c); + try end.record(c.r.s); + try c.r.s.synchronize(); + x.* = @as(f64, try start.elapsedMs(end)) * 100; + } + std.mem.sort(f64, &t, {}, std.sort.asc(f64)); + return t[t.len / 2]; +} + +pub fn run(gpu: check.Gpu) !void { + var arena: std.heap.ArenaAllocator = .init(gpu.gpa); + defer arena.deinit(); + const a = arena.allocator(); + var prng = std.Random.DefaultPrng.init(0x4c2); + var r = try rig_.Rig.init(gpu, a, prng.random()); + defer r.deinit(); + var g = try flash.Glue.load(gpu.d); + defer g.deinit(); + var lane = try cuda.qmmf.Lane.load(gpu.d, (try gpu.ctx.capability()) / 10); + defer lane.unload(); + // the engine's lane: qmmf's BF16 prompt tiles loaded, as TF_FLASHNEXT_PROMPT_BF16 leaves it (a copy, one module) + var served = lane; + try served.loadPrompt(gpu.d); + var t = try tk.TileKernels.load(gpu.d); + defer t.unload(); + + // bf16 weights in the lane's order, rows padded to 128 with zeros + const pd = try a.alloc(u16, cuda.nvfp4.padded(n_down) * wide); + cuda.qmmf.packBf16(pd, r.bfs(n_down * wide, 0.04), n_down, wide); + const pu = try a.alloc(u16, cuda.nvfp4.padded(wide) * low); + cuda.qmmf.packBf16(pu, r.bfs(wide * low, 0.4), wide, low); + const dh = try r.dev(std.mem.sliceAsBytes(r.bfs(most * wide, 3))); + const dpss = try r.out(most * nc * streams * 4); + var c: Chain = .{ + .r = &r, + .g = &g, + .lane = &served, + .t = &t, + .wdown = cuda.modelopt.bf16Weight(try r.dev(std.mem.sliceAsBytes(pd)), n_down, wide), + .wup = cuda.modelopt.bf16Weight(try r.dev(std.mem.sliceAsBytes(pu)), wide, low), + .h = dh, + .pss = dpss, + .scale = try r.dev(std.mem.sliceAsBytes(r.f32s(wide, 0.5, 1.5))), + .norm = try r.out(most * wide * 2), + .part = try r.out(most * n_down * 4), + .act = try r.out(most * low * 2), + .xs = try r.out(most * (low / 32) * 4), + .inj = try r.out(most * streams * 2), + .up = try r.out(most * wide * 2), + .mixed = try r.out(most * dims * 2), + .xsm = try r.out(most * (dims / 32) * 4), + .spart = try r.out(8 * most * n_down * 4), + .rows = most, + .sms = t.sms, + }; + // the streams' 256-column square sums, as the writeback leaves them for the read-out + try g.hcWriteback(r.s, dh, 0, dpss, 0, 0, 0, 0, most * dims, most, dims, streams, 0, 1, 1, 1); + + // the five launches on the plain lane and on the engine's; SM counts of 1, the device's and 4,096 take each tile + const counts = [_]usize{ 64, 65, 193, 255, 256, 511, 512, 767, 768, 769, 1000, 1024, 1025, 1536, 2053, 3072 }; + for (counts) |m| { + c.rows = m; + var wants: [2][]u8 = undefined; + for ([_]*const cuda.qmmf.Lane{ &lane, &served }, &wants) |l, *want| { + c.lane = l; + try c.poison(); + try c.five(); + want.* = try c.outputs(a); + } + try check.sameBytes("the five launches on the engine's lane against the plain lane", wants[1], wants[0]); + const want = wants[1]; + for ([_]usize{ 1, t.sms, 4096 }) |sms| { + c.sms = sms; + try c.poison(); + try c.fused(); + try check.sameBytes("fused read-out", try c.outputs(a), want); + } + check.pass("readout-fused: {d} rows, down tiles of {d}, {d} and {d} rows: every output byte equals the five launches'", .{ m, 16 * tk.hcn_down_mt[tiles.pickDown(m, 1)], 16 * tk.hcn_down_mt[tiles.pickDown(m, t.sms)], 16 * tk.hcn_down_mt[tiles.pickDown(m, 4096)] }); + } + + c.sms = t.sms; + c.lane = &served; + var start = try cuda.Event.init(gpu.d, true); + defer start.deinit(); + var end = try cuda.Event.init(gpu.d, true); + defer end.deinit(); + for ([_]usize{ 256, 512, 768, 1024, 1536, 2048, 3072 }) |m| { + c.rows = m; + const a1 = try median(&c, Chain.five, start, end); + const b1 = try median(&c, Chain.fused, start, end); + const a2 = try median(&c, Chain.five, start, end); + const b2 = try median(&c, Chain.fused, start, end); + std.debug.print("RESULT readout-fused rows {d}: five launches {d:.1} us, fused {d:.1} us (medians of 9 x 10, alternated)\n", .{ m, (a1 + a2) / 2, (b1 + b2) / 2 }); + } + r.report("readout-fused"); +} diff --git a/zig/tests/cuda/main.zig b/zig/tests/cuda/main.zig index b8cee876459..87a227790ec 100644 --- a/zig/tests/cuda/main.zig +++ b/zig/tests/cuda/main.zig @@ -205,7 +205,7 @@ fn run(gpu: check.Gpu, cmd: []const u8, rest: []const [:0]const u8) !void { if (std.mem.eql(u8, cmd, "flashnext-tp-heads")) return @import("flashnext_tp_heads_tests.zig").run(gpu, try arg(rest, 0)); if (std.mem.eql(u8, cmd, "flashnext-pages")) return @import("contract_fn_pages.zig").run(gpu); if (std.mem.eql(u8, cmd, "flashnext-attn-lanes")) return @import("contract_fn_attn_lanes.zig").run(gpu); - if (std.mem.eql(u8, cmd, "flashnext-readout-cut")) return @import("flashnext_readout_cut.zig").run(gpu); + if (std.mem.startsWith(u8, cmd, "flashnext-readout-")) return if (std.mem.eql(u8, cmd, "flashnext-readout-cut")) @import("flashnext_readout_cut.zig").run(gpu) else if (std.mem.eql(u8, cmd, "flashnext-readout-fused")) @import("flashnext_readout_fused.zig").run(gpu) else error.UnknownCommand; if (std.mem.eql(u8, cmd, "info")) return info(gpu); if (std.mem.eql(u8, cmd, "smoke")) return runtime_tests.smoke(gpu); if (std.mem.eql(u8, cmd, "shared-context")) return runtime_tests.sharedContext(gpu); diff --git a/zig/tests/fixtures/gradient-serving.tsv b/zig/tests/fixtures/gradient-serving.tsv index 8c49a3d42b3..def915d88a9 100644 --- a/zig/tests/fixtures/gradient-serving.tsv +++ b/zig/tests/fixtures/gradient-serving.tsv @@ -93,7 +93,7 @@ zig/src/cuda/experts.zig 8bfc2f15a742cceba87dd7eb8e80f3f1b4e3f7eb323b557eb1bb4bf zig/src/cuda/fp8.zig a9caf312cb451dc95572b493e69ae211dd1e8b5be5b2c48cae3febd5d9327143 raw series patches 65-pr-1024.patch; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate zig/src/cuda/graph.zig 17639aaef0298c934b3f5ad3511925169c096ae57ede8ebee655faa838844f7b raw zig/src/cuda/grouped.zig 5fa1f39394b701eab59383bc7ed214ea3e17652a1229236df49f5281e6e764b5 raw commits e1be0806d; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate -zig/src/cuda/kernels.zig 61868f4cfeeb1394b1f21c95032a7e7aee1ecfc65213f50b9e037591bf7bf0c2 raw main 42735f94f0 (#2335: the mla image registered), f35900e60c (#2709: the dots_mocr image registered), #1630 (the experts_bf16 image registered), #2914 (covers: the release SM check), #1631 (the nemo_audio image registered), #1767 (the idol image registered); #1295: the six Muse Spark images registered +zig/src/cuda/kernels.zig 035a0f6efce81061d63dd8eec74bedccf2a9aadaddfbc75438580c41f0606b88 raw main 42735f94f0 (#2335: the mla image registered), f35900e60c (#2709: the dots_mocr image registered), #1630 (the experts_bf16 image registered), #2914 (covers: the release SM check), #1631 (the nemo_audio image registered), #1767 (the idol image registered); #1295: the six Muse Spark images registered; #3413 (the flashnext_hcn image registered) zig/src/cuda/launch.zig 9ec64848834d82ddcea85a6123e975c95a5ae2bf85c2a71772244794b0bcd705 raw series patches 14-runtime-foundation.patch; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate zig/src/cuda/memory.zig c140f1700e0f257a3ac09b1bfaa4a0d704d1922ccbffc3d453d75be0fef4b617 raw commits 5dcf77d7c, f630f1a90, e9bf05ffd, 881cccaa4, a34cb6ded; series patches 14-runtime-foundation.patch; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate, this change (DeviceBuffer.allocVia allocates through a given hook; alloc is allocVia with the installed one, unchanged) zig/src/cuda/modelopt.zig 648c9ba58197af0ce905f8792383502fc44a52c45d1413fe9e21d28d04c22253 raw @@ -115,7 +115,7 @@ zig/src/cuda/tp_watch.zig 19ed1d12bc56f804b5d207d04226e9f6131a517aaf7aec4c4b2d0b zig/src/cuda/triton.zig 256323865c6a4676b8b75aae9e32d2d9732cf2623efedb9462cf6f95302c3e83 raw zig/src/cuda/vit.zig 72c4301251f50d0f25907f0d8ad03a943281b234c506a455e413627a3ffe09c0 raw zig/src/families/flashnext/cuda_attn.zig 99dfe79f919a8599490f1cdba0bec20d6e73ccbeafe26d5848419a465fdfa0d0 raw -zig/src/families/flashnext/cuda_batch.zig eaf08f697f93041f93d2388b345e90a788398a5cf7bfa7641c63a816c6ac5946 raw main 42ff6c510f (disk states keyed by the resolved prompt passes; serving unchanged); #XXXX: the scratch test's ceiling restated at the 3,072-row default +zig/src/families/flashnext/cuda_batch.zig f1c5ab1478497ab2c0abdf77776dfed36fa9092579d4306e4320a32cfadf6910 raw main 42ff6c510f (disk states keyed by the resolved prompt passes; serving unchanged); #XXXX: the scratch test's ceiling restated at the 3,072-row default, #3413 (TF_FLASHNEXT_READOUT_FUSED's prompt read-out; unchanged when unset) zig/src/families/flashnext/cuda_batch_state.zig 7e940f58ec4ecba11a657983375e3cfec7492989c6246f037759b8051ce70129 raw y and moe_f32 take one spare row for a --tp 2 prompt pass's padded rank block; replies unchanged; #XXXX: the default prompt chunk is 3,072 rows zig/src/families/flashnext/cuda_collective.zig bf475ffb46b3440fcad280f46e34de25cd22b79ed96a0b587d0869e7451d3519 raw adds sumBlock, the in-place FP32 reduce-scatter with sum's peer check, deadline and abort; no served change on its own zig/src/families/flashnext/cuda_compare_main.zig ade014dfec88f0b386076cdc093ea20710d7bf36c33ff566ca2caf472064695b raw main dfd9ac5ef4 (#2585: the TF_FLASHNEXT_* startup check), c274b45cc1 (the check through the flashnext module) @@ -133,7 +133,7 @@ zig/src/families/flashnext/cuda_lanes.zig b72cee919a557e16f001d2c6a7b77602889f6d zig/src/families/flashnext/cuda_lanes_admission_test.zig 4b8052db793ba81f0e73e1b9bd77b1780bbc4fd550d90976d017da47e76faaa2 raw zig/src/families/flashnext/cuda_lanes_load.zig abcfaf795d8c895ef04a01c5fd58c97ff43249a5c6cb3da460f8a23a5d5f9bf3 raw main dfd9ac5ef4 (#2585: TF_FLASHNEXT_* read through platform/environment.zig, malformed text refused at startup; valid values keep their meaning), #3467: after load a shard drops its page cache except the n-gram ranges, and the sweep reaches nested shards; tensors and replies are unchanged, this change (the load's device and io handed to the page pool's arena; paging off: unchanged) zig/src/families/flashnext/cuda_lanes_restore_test.zig f9947521a6d9c7d7380ca1b784a93a43b364c6fa5861cad15efd3538d2b8ceff raw -zig/src/families/flashnext/cuda_launch.zig f8bebb5ed074e6c8ab8cef667cb01fa2bb1a2b2d6a4d3874a92291390278d9f7 raw exports cuda_moe_exchange.zig for its device test; no served change; #2837 (Flash Next TP=2 graph replay) +zig/src/families/flashnext/cuda_launch.zig f056079d88e9295455bf44bed7ed4053e55fdb8579cfdb392c31a4c3af18e73c raw exports cuda_moe_exchange.zig for its device test; no served change; #2837 (Flash Next TP=2 graph replay); #3413 exports cuda_tiles.zig and readout_fused.zig for their tests zig/src/families/flashnext/cuda_media.zig 394601e8a807f5516f501efcaefa6fb3308f392ee322db7296b11c90814f8eea raw zig/src/families/flashnext/cuda_media_test.zig 4292f8f7c8f8bf4efd0dfaaa5a6c63e11568f85534127a0ce9feb0ab0be05120 raw zig/src/families/flashnext/cuda_mix.zig 248a2a86b3f377531f5b713c408ba99f73604510f4afe34ffae52615d5863c2c raw @@ -157,7 +157,7 @@ zig/src/families/flashnext/cuda_prompt.zig 64dfa63d6c9608d04b524689047f3f2bcf193 zig/src/families/flashnext/cuda_prompt_load.zig 334d68cfca85c15c9d986d0c6b4f8f2a38569309b21bdac6d365935d73c115cd raw zig/src/families/flashnext/cuda_prompt_main.zig 2543cd166dc80cd97b1ca1ce930a6150f9d36b52ee231744606f83bf54f0669d raw main dfd9ac5ef4 (#2585: the TF_FLASHNEXT_* startup check), c274b45cc1 (the check through the flashnext module) zig/src/families/flashnext/cuda_prompt_step.zig e04030fb4a4fdb8780704a1bc0b5ba4b786159ab08a927fe32a636a893129d0c raw -zig/src/families/flashnext/cuda_prompt_wt.zig 4885be0ea938cfba80b34fbe9c160d200226761a73f8bd9d785172cbc7cef9bb raw #3467: after load a shard drops its page cache except the n-gram ranges, and the sweep reaches nested shards; tensors and replies are unchanged +zig/src/families/flashnext/cuda_prompt_wt.zig 712eecd6796349dbd0cb0aa1c17465082a27c383c7b849410b252fd74907f709 raw #3467: after load a shard drops its page cache except the n-gram ranges, and the sweep reaches nested shards; tensors and replies are unchanged#3413 (an MLX affine read-out refuses TF_FLASHNEXT_READOUT_FUSED=1 by name; unchanged when unset) zig/src/families/flashnext/cuda_qmm.zig 6d035feb053691cc9750a369c86a5463d41ed942764ad85b861bb628c106dccf raw zig/src/families/flashnext/cuda_rank_engine.zig df6a83bcf80edfd94ac4474dbbc2e73818d40b7532430399af73f2eb95ccfa33 raw zig/src/families/flashnext/cuda_rank_media.zig e5c268c8cf257934bb49fe401ba6213ea8b108258bbfd4d06edb990d568c3c2b raw