diff --git a/CHANGELOG.md b/CHANGELOG.md index e70604aaa3b..f4bdc584b51 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -426,6 +426,10 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - Prompt cache: a state the disk tier recalls within `min_gap` under the rewind point becomes the rewind state, so the store no longer keeps a second copy of the rewind beside it (about 684 MiB less in the RAM tier per rewind turn at 21k tokens, same replies) (#5738). +- CUDA: Ripple-65B-Preview (ricursive) takes the publisher's DFlash2 drafter (`ricursiveAI/Ripple-65B-Preview-DFlash2`) with `--drafter`, with drafted replies equal to plain ones; several streams' shared rounds are priced by times taken at load, and structured output (`response_format`) and forced tool calls are served with the drafter as without it (#2475, fixes #2474). Thanks to @jrb-ai. + +- Ripple-65B-Preview on CUDA serves structured output (`response_format`) and forced tool calls (`tool_choice` `"required"` or a named function): a grammar's rows are drawn on the GPU from a copy with the disallowed tokens at -inf, by the same draw and argmax kernels, and logprob rows read the unmasked logits; a request with no grammar runs the launches it ran before (#5363, fixes #5252). Thanks to @jrb-ai. + ## 1.3.7 diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index 2eb30d1f6a0..e56e77dd768 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -325,7 +325,7 @@ These follow a model's release code or a library's model code for their math, ro - `tools/lfm3/ref64.py` and `zig/kernels/xpu/lfm3.cl`: `modeling_lfm3.py` in [LiquidAI/LFM3-1.7B](https://huggingface.co/LiquidAI/LFM3-1.7B). Copyright Liquid AI, LFM Open License v1.0; see [the license text](LICENSES/LFM-Open-1.0.txt). - `zig/kernels/metal/minimax_m3/glue.metal`: the rounding points of `modeling_minimax_m3_vl.py` in [transformers](https://github.com/huggingface/transformers). - `zig/src/families/ricursive/` (its layer order and rounding points), `zig/kernels/metal/ricursive/glue.metal`, `zig/kernels/cuda/ricursive.cu`, `ricursive.cuh`, `ricursive_prep.cu`, `ricursive_prep.cuh` and `tools/zig/ricursive_reference.py`: `modeling_ricursive.py` in [ricursiveAI/Ripple-65B-Preview](https://huggingface.co/ricursiveAI/Ripple-65B-Preview) at revision `240d5966cbe00f0627c699e59ef58560b60303cf`: the scaled embedding, the value residual, the per-head q/k norms, RoPE on sliding layers only, the fp32 sigmoid gate, the clamped SwiGLU and the four norms a layer. The release's SGLang model `inference/server/model.py` computes the same layers; what is in it alone is its serving (the W4A4 kernels, the capture of hidden states for a drafter), which this family does not take. Copyright ricursiveAI, Apache License 2.0; see [the license text](LICENSES/Apache-2.0.txt). The reference's `--release` and `--release-f64` modes import the release's own `modeling_ricursive.py` from the checkpoint at run time; TensorFold does not include it. -- `zig/src/families/ricursive/dflash2.zig` and `zig/kernels/metal/ricursive/dflash2.metal` (the DFlash2 drafter for ricursiveAI/Ripple-65B-Preview-DFlash2): `DFlash2DraftModel`, `GroupedDynamicCausalConv` and `CandidateSelector` in `dflash/model.py` of [z-lab/dflash](https://github.com/z-lab/dflash) at revision `07ebd93db9f472af339b644bb70221ad8428328a`, MIT License, Copyright © 2026 Z Lab, with its `apply_rotary_pos_emb`'s rounding points; the RMSNorm, rotary cos and sin, and SiLU MLP of the release's `modeling_ricursive.py` above (`RicursiveRMSNorm`, `RicursiveRotaryEmbedding`, `RicursiveMLP`), at the drafter's config. The target's taps are the hidden states `extract_context_feature` in that `model.py` takes (`hidden_states[layer_id + 1]`), here of `modeling_ricursive.py`'s `output_hidden_states`: a tapped layer's output, before the final norm. The NoPE layer is `no_rope_layers` in the drafter's `config.json` ([ricursiveAI/Ripple-65B-Preview-DFlash2](https://huggingface.co/ricursiveAI/Ripple-65B-Preview-DFlash2) at revision `35609b3be3dd08a822b3ba1257c1ea5dd6f87632`, Apache License 2.0); `zig/src/families/ricursive/fixtures/dflash2_config.json` is that `config.json`, unchanged. The 16,384-token draft window is from `inference/server/README.md` in the release above. +- `zig/src/families/ricursive/dflash2.zig`, `zig/src/families/ricursive/cuda_dflash2*.zig`, `zig/kernels/metal/ricursive/dflash2.metal`, `zig/kernels/cuda/ricursive_dflash2.cu`, `zig/kernels/cuda/ricursive_dflash2.cuh` and `zig/kernels/cuda/ricursive_dflash2_attn.cu` (the DFlash2 drafter for ricursiveAI/Ripple-65B-Preview-DFlash2): `DFlash2DraftModel`, `GroupedDynamicCausalConv` and `CandidateSelector` in `dflash/model.py` of [z-lab/dflash](https://github.com/z-lab/dflash) at revision `07ebd93db9f472af339b644bb70221ad8428328a`, MIT License, Copyright © 2026 Z Lab, with its `apply_rotary_pos_emb`'s rounding points; the RMSNorm, rotary cos and sin, and SiLU MLP of the release's `modeling_ricursive.py` above (`RicursiveRMSNorm`, `RicursiveRotaryEmbedding`, `RicursiveMLP`), at the drafter's config. The target's taps are the hidden states `extract_context_feature` in that `model.py` takes (`hidden_states[layer_id + 1]`), here of `modeling_ricursive.py`'s `output_hidden_states`: a tapped layer's output, before the final norm. The NoPE layer is `no_rope_layers` in the drafter's `config.json` ([ricursiveAI/Ripple-65B-Preview-DFlash2](https://huggingface.co/ricursiveAI/Ripple-65B-Preview-DFlash2) at revision `35609b3be3dd08a822b3ba1257c1ea5dd6f87632`, Apache License 2.0); `zig/src/families/ricursive/fixtures/dflash2_config.json` is that `config.json`, unchanged. The 16,384-token draft window is from `inference/server/README.md` in the release above. - `zig/src/vision/qwen_cuda.zig`: `Qwen3_5VisionModel` in transformers. - `zig/src/core/picture/patches_test.zig`: recorded image-processor output data from `Lfm3VlImageProcessor` and `Qwen2VLImageProcessor` in transformers; the processing implementation is described below. - `zig/src/families/flashnext/rotary_config.zig`: `_compute_yarn_parameters` in transformers, for the 64 rotary dims. diff --git a/docs/recipes/ripple-65b-cuda.md b/docs/recipes/ripple-65b-cuda.md index 85353ef653f..962e644f545 100644 --- a/docs/recipes/ripple-65b-cuda.md +++ b/docs/recipes/ripple-65b-cuda.md @@ -8,7 +8,10 @@ read in place from its shards with nothing converted: `99eea4477a001a41b86914e41feb4b2ed86105e5`, 53 GiB): ModelOpt NVFP4 MLPs, attention, embeddings and head in bf16. The bf16 release is refused by name (`RicursiveCudaNeedsNvfp4`): at 121 GiB it does not fit a GB10, and the CUDA -family reads only the NVFP4 MLPs. +family reads only the NVFP4 MLPs. The publisher's DFlash2 drafter, +[`ricursiveAI/Ripple-65B-Preview-DFlash2`](https://huggingface.co/ricursiveAI/Ripple-65B-Preview-DFlash2) (revision +`35609b3be3dd08a822b3ba1257c1ea5dd6f87632`, 7.5 GiB, bf16), drafts with `--drafter`; a drafted reply equals the plain +one. It was brought up on a DGX Spark (GB10, sm_121, 121.7 GiB shared with the host, CUDA 13). The kernels build for sm_80, 86, 89, 120 and 121 and their launches fit each, but only GB10 was run. @@ -19,6 +22,7 @@ sm_80, 86, 89, 120 and 121 and their launches fit each, but only GB10 was run. hf download ricursiveAI/Ripple-65B-Preview-NVFP4 --revision 99eea4477a001a41b86914e41feb4b2ed86105e5 \ --local-dir models/ripple-65b-nvfp4 zig build native -Dnvcc=/usr/local/cuda/bin/nvcc -Dsm=121 +zig build grammar -Dxgrammar=PATH_TO_XGRAMMAR_v0.2.8 # structured output and forced tool calls zig-out/native/bin/tensorfold-native serve models/ripple-65b-nvfp4 --name ripple --port 8888 --context 32768 ``` @@ -26,9 +30,14 @@ At `--context 32768` admission gives eight streams of 2.78 GiB and a 16.0 GiB pr reserve. A stream's caches: 64 of the 80 layers slide over 1,024 keys and keep a 3,072-row ring each; every fifth layer is global and keeps every key, in 512-row pages. +With the drafter (`hf download ricursiveAI/Ripple-65B-Preview-DFlash2 --revision +35609b3be3dd08a822b3ba1257c1ea5dd6f87632 --local-dir models/ripple-65b-dflash2`), add `--drafter +models/ripple-65b-dflash2`. It keeps 10.09 GiB for its weights, scratch and eight streams' rings; at `--context 32768` +admission still gives eight streams (3.01 GiB each), and the prompt cache drops to 11.2 GiB. + Thinking follows the chat template, as on Metal: Ripple writes `` itself when it thinks and answers bare otherwise, and the server files a reply without the block as answer. Its think markers are spelled from several -tokens, so a thinking budget and logprobs are refused by name. +tokens, so a thinking budget is refused by name. Logprobs are served. ## What the family is @@ -46,6 +55,12 @@ the release's `modeling_ricursive.py` as the reference: block, for Ripple's group of 10. - **Serving.** The lane host's shared rounds as CUDA graphs, greedy or sampled draws, copy drafts, verify windows, kept states and the prompt cache. +- **DFlash2 drafter** (`cuda_dflash2*.zig`, `ricursive_dflash2.cu`, `ricursive_dflash2_attn.cu`), in the Metal + drafter's op order and bf16 rounding points. The target writes the residual after layers 1, 20, 39, 58 and 77 into a + 2,064-row tap ring a stream, inside the round graphs. A round runs the 16-row block through the five layers for + every stream in one launch a step: the 4-tap convolution in Metal's rounding order; draft attention that reads each + of the 8 KV heads once for its 10 query heads and all 16 rows; the target's head; a top-32 a row; then the selector + walk on the host. Chain verify only (one draft a stream), as on Metal. **Activations stay bf16**, as on Metal: the engine serves the NVFP4 weights with bf16 activations and fp32 sums, not the publisher's W4A4 kernels. @@ -54,7 +69,9 @@ Every kernel is registered with the kernel contract, with planted controls that GB10 (nvcc 13.3, sm_121): ``` -SUMMARY ricursive: 20 kernels, 20 pass gates 1-4, 0 fail; 24 controls: 24 red as planted, 0 missed +SUMMARY ricursive: 22 kernels, 22 pass gates 1-4, 0 fail; 27 controls: 27 red as planted, 0 missed +SUMMARY ricursive dflash2: 10 kernels, 10 pass gates 1-4, 0 fail; 19 controls: 19 red as planted, 0 missed +SUMMARY ricursive dflash2 attention: 3 kernels, 3 pass gates 1-4, 0 fail; 6 controls: 6 red as planted, 0 missed ``` ## Correctness (GB10) @@ -81,6 +98,20 @@ pick by at most 0.25 nats. - Served replies are bit-identical alone, beside seven other streams and one at a time (greedy and sampled). A conversation sent again, reusing 79 to 81 cached tokens, equals its first reply, and 60 repeats of a reply equal the first. Seeded replies equal their repeats, and streamed text equals the reply sent whole. +- Structured output and forced tool calls draw under the grammar's mask on the GPU: a row's copy with its disallowed + tokens at -inf, through the draw and argmax kernels of a row with no grammar. The first token and a 4-row window + under masks equal the plain draw over the same rows with the other tokens at -inf, greedy and sampled; the model's + rows keep their bits and the logprob rows read them; streams with no grammar in a round beside a masked stream + equal each alone. Served: 11 request forms (`response_format` json_object and json_schema; `guided_json`, + `guided_regex`, `guided_choice` and `guided_grammar`; `structured_outputs` json, json_object, regex, choice and + grammar), greedy and sampled, give valid replies, and tool calls with `tool_choice` `"auto"`, `"required"`, a named + function and a streamed required call agree. The plain dumps and reply hashes above are unchanged. +- With `--drafter`, every reply equals the plain server's at the same seed: 22 of 22, greedy and sampled, at 1, 2 + and 8 streams. Each drafted reply also equals itself alone and with `"draft": false`, and cold 2,048- and + 8,192-token prompts give the plain reply. With the drafter's code built in, the plain engine's logits are unchanged + bit for bit on all 2,586 rows. Structured output and forced tool calls are served with the drafter too: 44 + structured and 5 tool requests equal the plain server's, and 8 structured requests alone, 2 at once and 8 at once + equal it with drafts accepted at each level (158 of 339, 42 of 89 and 149 of 365). ## Measured (GB10, NVFP4 release, `--context 32768`, no other model busy) @@ -93,6 +124,16 @@ at 518-520 tok/s at 2,586 rows. Greedy 256-token essays, thinking off, all strea | 4 | 15.54 | | 8 | 29.93 | +With `--drafter`, 256 tokens, median of 3 (code is a raw text completion, prose a chat reply): one stream from +`tools/bench_openai.py`, eight streams together from `tools/bench_concurrent.py --levels 8` (all eight streams' tokens): + +| reply | 1 stream, plain | 1 stream, drafted | 8 streams, plain | 8 streams, drafted | +|---|---:|---:|---:|---:| +| code, greedy | 5.2 | 26.1 | 37.5 | 124.3 | +| code, sampled (T=1.0) | 4.5 | 18.4 | 30.4 | 72.5 | +| prose, greedy | 4.4 | 10.0 | 32.5 | 58.5 | +| prose, sampled (T=1.0) | 4.0 | 11.2 | 30.4 | 42.7 | + At `--context 131072` admission gives four streams of 8.78 GiB and a 7.1 GiB prompt cache. Cold prompts there (`tools/bench_cache.py --require-cold`), time to first token: 3.76 s at 2,048 tokens (545 tok/s), 15.6 s at 8,192 (524), 68.4 s at 32,768 (479) and 150.7 s at 65,536 (435). Each reply equals its repeat and itself beside a second. @@ -106,11 +147,8 @@ budget. ## Not done -Structured output (`response_format`) and forced tool calls (`tool_choice` `"required"` or a named function) are not -supported on CUDA yet: the server refuses them, because the CUDA family has no masked sampling. Tool calls with -`tool_choice` `"auto"` work. No quality suite was run. Past 131,072 tokens, only the one near-cap prompt above was -run. Only GB10 was run. The publisher's DFlash2 drafter (`ricursiveAI/Ripple-65B-Preview-DFlash2`) is not served -on CUDA yet. +No quality suite was run. Past 131,072 tokens, only the one near-cap prompt above was run. Only GB10 was run. Draft +trees (several drafts a stream) are not done, and the drafter's kernel speed is not tuned. ## Licence diff --git a/tools/zig/ricursive_gate_compare.py b/tools/zig/ricursive_gate_compare.py index d8b14fba2ac..1a3a7a17761 100644 --- a/tools/zig/ricursive_gate_compare.py +++ b/tools/zig/ricursive_gate_compare.py @@ -120,6 +120,11 @@ def run_kl(a: argparse.Namespace) -> int: eng, fed = open_logits(a.engine, a.vocab) if ref.shape[0] > len(ids): ref = ref[: len(ids)] # a causal model: the first rows of a longer run are the shorter run's + if ref_fed is not None: # a kl-format reference says which token it fed after each row: the chat's, as the engine's + ref_fed = ref_fed[: len(ids)] + wrong = np.flatnonzero(np.asarray(ref_fed[:-1]) != np.asarray(ids[1 : len(ref_fed)], dtype=np.uint32)) + if wrong.size: + raise SystemExit(f"the reference's file fed other tokens than the ids at {wrong.size} rows, first row {wrong[0]}") if fed is None and eng.shape[0] > len(ids): eng = eng[: len(ids)] # the same for a raw file, so two reference passes compare over the chat's rows if ref.shape != eng.shape or ref.shape[0] != len(ids): diff --git a/zig/build/cuda_kernels.zig b/zig/build/cuda_kernels.zig index dd3ab1b3b14..ddbcae6a94a 100644 --- a/zig/build/cuda_kernels.zig +++ b/zig/build/cuda_kernels.zig @@ -190,8 +190,10 @@ pub const kernels = [_]Kernel{ // ours: Inkling 2's DSpark drafter glue .{ .name = "inkling2_dspark", .src = "inkling2/dspark", .flags = glue }, .{ .name = "inkling2_dflash2", .src = "inkling2/dflash2", .flags = glue }, // Mini's external DFlash2 block, attention and selector + .{ .name = "ricursive_dflash2_attn", .flags = glue }, // ours: Ripple's DFlash2 draft attention (split over keys, merged) and top-32 .{ .name = "ricursive", .flags = glue }, // ours: Ripple's glue (embed, add-norms, output gate, FFN activation), glue.metal step for step .{ .name = "ricursive_prep", .flags = glue }, // ours: Ripple's attention prep (q/k head norms, RoPE, K and V into rings or pages) + .{ .name = "ricursive_dflash2", .flags = glue }, // ours: Ripple's DFlash2 drafter glue (norms, attention prep, block conv, SiLU), dflash2.metal step for step // ours: Inkling 2's grouped experts, plus Mini's tensor-path epilogue and ascending combine .{ .name = "inkling2_experts", .src = "inkling2/experts", .flags = &.{ "-O3", "--expt-relaxed-constexpr" } }, .{ .name = "inkling2_modelopt", .src = "inkling2/modelopt", .flags = &.{ "-O3", "--expt-relaxed-constexpr" } }, // Mini packed experts on BF16 activations diff --git a/zig/kernels/cuda/contract_ricursive_controls.cuh b/zig/kernels/cuda/contract_ricursive_controls.cuh index 7580e389dfb..baac7698058 100644 --- a/zig/kernels/cuda/contract_ricursive_controls.cuh +++ b/zig/kernels/cuda/contract_ricursive_controls.cuh @@ -1,4 +1,4 @@ -// Planted controls for Ripple's attention prep (ricursive_prep.cu): each keeps one fault its gate must catch. +// Planted controls for Ripple's attention prep (ricursive_prep.cu) and grammar mask (sample.cu), one fault each. // Included by contract_controls_set.cu after contract_controls.cu, whose headers it reuses. @@ -22,3 +22,16 @@ extern "C" __global__ void __launch_bounds__(tf_rcp::NT) tf_ctl_rc_prep_rows( tf_rcp::prep_rows(XQ, XK, XV, inv, qw, kw, Q, KC, VC, rows, heads, kv_heads, pos, nullptr, ring, rope, eps, tab, page, tok, stride, keep); } + +// Gate 3: sample.cu's tf_grammar_mask reading a word's bits from the top (token t at bit 31 - t % 32); shapes go red. +extern "C" __global__ void __launch_bounds__(256) tf_ctl_rc_grammar_mask(__nv_bfloat16* L, unsigned V, const unsigned* BITS, unsigned W) { + const unsigned row = blockIdx.x; + __nv_bfloat16* x = L + static_cast(row) * V; + for (unsigned w = threadIdx.x; w < W; w += blockDim.x) { + const unsigned allowed = BITS[static_cast(row) * W + w]; + for (unsigned b = 0; b < 32u; b++) { + const unsigned t = w * 32u + b; + if (t < V && ((allowed >> (31u - b)) & 1u) == 0u) x[t] = __ushort_as_bfloat16(static_cast(0xFF80u)); + } + } +} diff --git a/zig/kernels/cuda/ricursive.cu b/zig/kernels/cuda/ricursive.cu index c6b35dc64f0..9bfede4d162 100644 --- a/zig/kernels/cuda/ricursive.cu +++ b/zig/kernels/cuda/ricursive.cu @@ -1,4 +1,4 @@ -// Ripple's glue on CUDA: glue.metal step for step (bf16 residual, fp32 sums), and its planted controls. +// Ripple's glue on CUDA: glue.metal step for step (bf16 residual, fp32 sums), dflash2.metal's rc_tap, and controls. #include "ricursive.cuh" @@ -35,10 +35,41 @@ namespace tf_rc { silu_clamp(GU, A, rows, width, limit); \ } +// tap's planted faults, a bit each (the served kernel has none). +constexpr int TAP_COL = 1; // the next tap column +constexpr int TAP_RING = 2; // the ring row one past pos % ring +constexpr int TAP_SWAP = 4; // rows 0 and 1 read each other's residual + +// A drafter's tap: R's row r copied exactly to T[slot][pos % ring][col]; pos, slot a row each, or null: p0 + r, s0. +template +__device__ __forceinline__ void tap(const bf16* __restrict__ R, bf16* __restrict__ T, const int* __restrict__ pos, + const int* __restrict__ slot, int p0, int s0, int rows, int width, int taps, int col, + int ring) { + const int c = blockIdx.x * blockDim.x + threadIdx.x, row = blockIdx.y, chunks = width / 8; + if (c >= chunks || row >= rows) return; + const int src = (K & TAP_SWAP) && rows > 1 && row < 2 ? 1 - row : row; + const int p = pos != nullptr ? pos[row] : p0 + row; + const int s = slot != nullptr ? slot[row] : s0; + const int at = (K & TAP_RING) ? (p + 1) % ring : p % ring; + const int t = (K & TAP_COL) ? (col + 1) % taps : col; + const uint4* in = reinterpret_cast(R + (size_t)src * width); + uint4* out = reinterpret_cast(T + (((size_t)s * ring + at) * taps + t) * width); + out[c] = in[c]; +} + +// Tap: grid (ceil(width / 8 / 256), rows), 256 threads; pos, slot null for a chunk; width % 8 == 0, 16-byte rows. +#define TF_RC_TAP(NAME, K) \ + extern "C" __global__ void __launch_bounds__(NT) \ + NAME(const bf16* __restrict__ R, bf16* __restrict__ T, const int* __restrict__ pos, const int* __restrict__ slot, \ + int p0, int s0, int rows, int width, int taps, int col, int ring) { \ + tap(R, T, pos, slot, p0, s0, rows, width, taps, col, ring); \ + } + TF_RC_EMBED(tf_rc_embed, false) TF_RC_ADD_NORM(tf_rc_add_norm, NORM_ALL) TF_RC_GATE(tf_rc_gate, SIG) TF_RC_SILU_CLAMP(tf_rc_silu_clamp, SILU | LOW) +TF_RC_TAP(tf_rc_tap, 0) // Controls, one a rounding point (each must fail the contract's shapes gate): the served kernel without it. TF_RC_EMBED(tf_rc_ctl_embed_bf16_scale, true) @@ -50,11 +81,16 @@ TF_RC_ADD_NORM(tf_rc_ctl_add_norm_x_lerp, NORM_ALL & ~X_LERP) TF_RC_GATE(tf_rc_ctl_gate_sigmoid, 0) TF_RC_SILU_CLAMP(tf_rc_ctl_silu_round, LOW) TF_RC_SILU_CLAMP(tf_rc_ctl_silu_no_lower, SILU) +// The tap's controls are placement faults (it rounds nothing): a wrong column, ring row or row order. +TF_RC_TAP(tf_rc_ctl_tap_column, TAP_COL) +TF_RC_TAP(tf_rc_ctl_tap_ring, TAP_RING) +TF_RC_TAP(tf_rc_ctl_tap_swap, TAP_SWAP) #undef TF_RC_EMBED #undef TF_RC_ADD_NORM #undef TF_RC_GATE #undef TF_RC_SILU_CLAMP +#undef TF_RC_TAP // Plug-in point: the prep (per-head norm, RoPE, KV-ring write) and attention kernels go below, named tf_rc_*. diff --git a/zig/kernels/cuda/ricursive_dflash2.cu b/zig/kernels/cuda/ricursive_dflash2.cu new file mode 100644 index 00000000000..efe9f58660f --- /dev/null +++ b/zig/kernels/cuda/ricursive_dflash2.cu @@ -0,0 +1,82 @@ +// Ripple's DFlash2 drafter glue on CUDA: dflash2.metal's norm, prep, conv and silu step for step, and planted controls. + +#include "ricursive_dflash2.cuh" + +namespace tf_rcd { + +// Add-norm: grid rows, 256 threads; Y null is norm16's form (R only read); width % 8 == 0, at most 8,192, 16-byte rows. +#define TF_RCD_ADD_NORM(NAME, K) \ + extern "C" __global__ void __launch_bounds__(NT) NAME(bf16* __restrict__ R, const bf16* __restrict__ Y, \ + const bf16* __restrict__ w, bf16* __restrict__ X, int rows, \ + int width, float eps) { \ + add_norm(R, Y, w, X, rows, width, eps); \ + } + +// Prep: grid (ceil((heads + kv_heads) / 8), rows), 256 threads; segs [nsegs] on the device; Q null when heads is 0. +#define TF_RCD_PREP(NAME, K) \ + extern "C" __global__ void __launch_bounds__(NT) \ + NAME(const bf16* __restrict__ X, const bf16* __restrict__ qw, const bf16* __restrict__ kw, \ + const float* __restrict__ inv, const Segment* __restrict__ segs, int nsegs, bf16* __restrict__ Q, int rows, \ + int heads, int kv_heads, int stride, int q_off, int k_off, int v_off, int ring, int rope, float eps) { \ + prep(X, qw, kw, inv, segs, nsegs, Q, rows, heads, kv_heads, stride, q_off, k_off, v_off, ring, rope, eps); \ + } + +// Conv: grid (ceil(width / 256), rows), 256 threads; rows grouped in blocks of `block` (each stream's whole blocks). +#define TF_RCD_CONV(NAME, K) \ + extern "C" __global__ void __launch_bounds__(NT) NAME(const bf16* __restrict__ X, const bf16* __restrict__ D, \ + const bf16* __restrict__ base, bf16* __restrict__ Y, int rows, \ + int width, int block, int groups, int side, int taps) { \ + conv(X, D, base, Y, rows, width, block, groups, side, taps); \ + } + +// SiLU: grid (ceil(width / 256), rows), 256 threads; GU rows are 2 x width (gate | up). +#define TF_RCD_SILU(NAME, K) \ + extern "C" __global__ void __launch_bounds__(NT) NAME(const bf16* __restrict__ GU, bf16* __restrict__ A, int rows, \ + int width) { \ + silu(GU, A, rows, width); \ + } + +TF_RCD_ADD_NORM(tf_rcd_add_norm, NORM_ALL) +TF_RCD_PREP(tf_rcd_prep, PREP_ALL) +TF_RCD_CONV(tf_rcd_conv, CONV_ALL) +TF_RCD_SILU(tf_rcd_silu, GS) + +// Controls (each must fail the contract's shapes gate): the served kernel without one rounding point, or with one edit. +TF_RCD_ADD_NORM(tf_rcd_ctl_add_norm_resid, NORM_ALL & ~RESID) +TF_RCD_ADD_NORM(tf_rcd_ctl_add_norm_x_row, NORM_ALL & ~X_ROW) +TF_RCD_PREP(tf_rcd_ctl_prep_norm_row, PREP_ALL & ~NORM_ROW) +TF_RCD_PREP(tf_rcd_ctl_prep_norm_out, PREP_ALL & ~NORM_OUT) +TF_RCD_PREP(tf_rcd_ctl_prep_cos, PREP_ALL & ~COS) +TF_RCD_PREP(tf_rcd_ctl_prep_sin, PREP_ALL & ~SIN) +TF_RCD_PREP(tf_rcd_ctl_prep_rot_c, PREP_ALL & ~ROT_C) +TF_RCD_PREP(tf_rcd_ctl_prep_rot_s, PREP_ALL & ~ROT_S) +TF_RCD_PREP(tf_rcd_ctl_prep_out, PREP_ALL & ~OUT) +TF_RCD_PREP(tf_rcd_ctl_prep_nope_ropes, PREP_ALL | NOPE_ROPES) +TF_RCD_PREP(tf_rcd_ctl_prep_mask, PREP_ALL | MASK) +TF_RCD_CONV(tf_rcd_ctl_conv_base, CONV_ALL & ~C_BASE) +TF_RCD_CONV(tf_rcd_ctl_conv_add, CONV_ALL & ~C_ADD) +TF_RCD_CONV(tf_rcd_ctl_conv_dyn, CONV_ALL & ~C_DYN) +TF_RCD_CONV(tf_rcd_ctl_conv_two_round, CONV_ALL | TWO_ROUND) +TF_RCD_CONV(tf_rcd_ctl_conv_no_edge, CONV_ALL | NO_EDGE) +TF_RCD_CONV(tf_rcd_ctl_conv_swap, CONV_ALL | SWAP) +TF_RCD_SILU(tf_rcd_ctl_silu_gs, 0) + +// The embed's control, as tf_rc_embed's arguments at scale 1: row r reads table row r, not row ids[r]. +extern "C" __global__ void __launch_bounds__(NT) tf_rcd_ctl_embed_own_row(const unsigned* __restrict__ ids, + const bf16* __restrict__ E, bf16* __restrict__ R, + bf16* __restrict__ V0, int rows, int width, + float scale) { + const int x = blockIdx.x * blockDim.x + threadIdx.x, row = blockIdx.y; + if (x >= width || row >= rows) return; + const size_t at = (size_t)row * width + x; + const bf16 v = __float2bfloat16_rn(__fmul_rn(ld(E + at), scale)); + R[at] = v; + V0[at] = v; +} + +#undef TF_RCD_ADD_NORM +#undef TF_RCD_PREP +#undef TF_RCD_CONV +#undef TF_RCD_SILU + +} // namespace tf_rcd diff --git a/zig/kernels/cuda/ricursive_dflash2.cuh b/zig/kernels/cuda/ricursive_dflash2.cuh new file mode 100644 index 00000000000..f1a07481ed4 --- /dev/null +++ b/zig/kernels/cuda/ricursive_dflash2.cuh @@ -0,0 +1,180 @@ +// Ripple's DFlash2 drafter glue at dflash2.metal's bf16 points (norm, norm16, prep, conv, silu), streams batched. +#pragma once + +#include "ricursive.cuh" + +namespace tf_rcd { + +typedef __nv_bfloat16 bf16; +using tf_rc::bf; +using tf_rc::ld; +using tf_rc::MOST; +using tf_rc::NT; +using tf_rc::point; + +// add_norm's rounding points, a bit each; a control clears one. +constexpr int RESID = 1; // bf16(R + Y): the residual the norm reads +constexpr int X_ROW = 2; // bf16(r * inv) before w +constexpr int NORM_ALL = RESID | X_ROW; + +// A row a block, R in place: R = bf16(R + Y), then X = bf16(w bf16(R inv)); Y null (norm16): X = norm(R), R only read. +template +__device__ __forceinline__ void add_norm(bf16* __restrict__ R, const bf16* __restrict__ Y, const bf16* __restrict__ w, + bf16* __restrict__ X, int rows, int width, float eps) { + __shared__ float part[NT / 32]; + const int row = blockIdx.x, chunks = width / 8; + if (row >= rows) return; + const size_t base = (size_t)row * width; + float r[MOST][8]; + tf_rc::load_row(R + base, chunks, r); + if (Y != nullptr) { + float y[MOST][8]; + tf_rc::load_row(Y + base, chunks, y); + uint4* out = reinterpret_cast(R + base); +#pragma unroll + for (int j = 0; j < MOST; ++j) { + const int c = threadIdx.x + j * NT; + if (c >= chunks) continue; +#pragma unroll + for (int e = 0; e < 8; ++e) r[j][e] = point(__fadd_rn(r[j][e], y[j][e])); + out[c] = tf_common::pack8(r[j]); // stored as bf16 either way: a control changes only what the norm reads + } + } + const float inv = tf_rc::inv_rms(r, part, width, eps); + const uint4* w4 = reinterpret_cast(w); +#pragma unroll + for (int j = 0; j < MOST; ++j) { + const int c = threadIdx.x + j * NT; + if (c >= chunks) continue; + float wv[8], x[8]; + tf_common::unpack8(w4[c], wv); +#pragma unroll + for (int e = 0; e < 8; ++e) x[e] = __fmul_rn(wv[e], point(__fmul_rn(r[j][e], inv))); + reinterpret_cast(X + base)[c] = tf_common::pack8(x); + } +} + +// Head dim 128, a lane's dims lane + 32 j; a warp a (row, head), 8 warps a block. +constexpr int HD = 128, HALF = 64, PER = HD / 32, WARPS = NT / 32; + +// prep's rounding points, a bit each; a control clears one (OUT: the output truncated, not rounded). +constexpr int NORM_ROW = 1; // bf16(v inv) +constexpr int NORM_OUT = 2; // bf16(w that): the normed head +constexpr int COS = 4; // bf16(cos) +constexpr int SIN = 8; // bf16(sin) +constexpr int ROT_C = 16; // bf16(nrm c) +constexpr int ROT_S = 32; // bf16(rot s) +constexpr int OUT = 64; // the stored output, to nearest even +constexpr int PREP_ALL = 127; +// Not rounding points: a control sets one. +constexpr int NOPE_ROPES = 128; // the NoPE layer rotated too +constexpr int MASK = 256; // a key's slot is p & (ring - 1): a power-of-two ring's wrap, in bounds but wrong here + +// One stream's rows in a batched launch: its layer's K and V rings, its first row, and that row's position. +struct Segment { + unsigned long long k, v; + long long begin, pos; +}; + +// A warp a (row, unit): query head `unit` into Q [rows][heads][128], else key head unit - heads into ring row p % ring. +template +__device__ __forceinline__ void prep(const bf16* __restrict__ X, const bf16* __restrict__ qw, const bf16* __restrict__ kw, + const float* __restrict__ inv, const Segment* __restrict__ segs, int nsegs, + bf16* __restrict__ Q, int rows, int heads, int kv_heads, int stride, int q_off, + int k_off, int v_off, int ring, int rope, float eps) { + const int unit = blockIdx.x * WARPS + (threadIdx.x >> 5), lane = threadIdx.x & 31, row = blockIdx.y; + if (unit >= heads + kv_heads || row >= rows) return; // whole warps: the shuffles stay converged + // the row's segment: the last one beginning at or before it (segments are in row order) + int s = 0; + while (s + 1 < nsegs && segs[s + 1].begin <= row) ++s; + const Segment seg = segs[s]; + const long long p = seg.pos + (row - seg.begin); + const long long slot = (K & MASK) ? (p & (ring - 1)) : p % ring; + const size_t kvw = (size_t)kv_heads * HD; + const bool is_q = unit < heads; + const int head = is_q ? unit : unit - heads; + const bf16* src = X + (size_t)row * stride + (is_q ? q_off : k_off) + (size_t)head * HD; + const bf16* w = is_q ? qw : kw; + bf16* y = is_q ? Q + ((size_t)row * heads + head) * HD + : reinterpret_cast(seg.k) + (size_t)slot * kvw + (size_t)head * HD; + // each head bf16(w bf16(v r)), r = 1 / sqrt(sum v^2 / 128 + eps) + float v[PER]; + float sum = 0.0f; +#pragma unroll + for (int j = 0; j < PER; ++j) { + v[j] = ld(src + lane + 32 * j); + sum = __fmaf_rn(v[j], v[j], sum); + } + const float r = tf_common::rms_scale(tf_common::warp_sum(sum), HD, eps); + float n[PER]; +#pragma unroll + for (int j = 0; j < PER; ++j) n[j] = point(__fmul_rn(ld(w + lane + 32 * j), point(__fmul_rn(v[j], r)))); + // rope, rotate-half at p: bf16(bf16(n c) + bf16(rot s)), c and s the bf16 cos and sin of p inv[d % 64] + const bool rotate = rope != 0 || (K & NOPE_ROPES) != 0; + const float position = (float)p; +#pragma unroll + for (int j = 0; j < PER; ++j) { + const int d = lane + 32 * j; + float o = n[j]; + if (rotate) { + const float angle = __fmul_rn(position, inv[d % HALF]); + const float c = point(cosf(angle)), sn = point(sinf(angle)); + const float rot = j < 2 ? -n[j + 2] : n[j - 2]; // d < 64 pairs with d + 64 (negated), else with d - 64 + o = __fadd_rn(point(__fmul_rn(n[j], c)), point(__fmul_rn(rot, sn))); + } + y[d] = (K & OUT) ? __float2bfloat16_rn(o) : __float2bfloat16_rz(o); + } + if (is_q) return; + const bf16* vs = X + (size_t)row * stride + v_off + (size_t)head * HD; + bf16* vd = reinterpret_cast(seg.v) + (size_t)slot * kvw + (size_t)head * HD; +#pragma unroll + for (int j = 0; j < PER; ++j) vd[lane + 32 * j] = vs[lane + 32 * j]; // the value as it is +} + +// conv's rounding points, a bit each; a control clears one. +constexpr int C_BASE = 1; // bf16(base x) +constexpr int C_ADD = 2; // bf16(y + that) +constexpr int C_DYN = 4; // bf16(fma(dyn, x, y)) +constexpr int CONV_ALL = 7; +// Not rounding points: a control sets one. +constexpr int TWO_ROUND = 8; // Qwen's form: bf16(y + bf16(dyn x)) for the fma +constexpr int NO_EDGE = 16; // the block-edge guard dropped: taps reach the block before (never above row 0) +constexpr int SWAP = 32; // base takes the fma and dyn the rounded product + +// z-lab's causal conv, lag t ascending in the block, x = X[r - t]: y = bf16(y + bf16(base_t x)), bf16(fma(dyn_t, x, y)) +template +__device__ __forceinline__ void conv(const bf16* __restrict__ X, const bf16* __restrict__ D, const bf16* __restrict__ base, + bf16* __restrict__ Y, int rows, int width, int block, int groups, int side, int taps) { + const int ch = blockIdx.x * blockDim.x + threadIdx.x, r = blockIdx.y; + if (ch >= width || r >= rows) return; + const int g = ch / (width / groups); + // D rows are [side][tap][group], base [side][tap][width] + const bf16* d = D + (size_t)r * 2 * taps * groups + (size_t)side * taps * groups; + const bf16* bs = base + (size_t)side * taps * width; + float y = 0.0f; + for (int t = 0; t < taps; ++t) { + if ((K & NO_EDGE) ? r < t : r % block < t) break; + const float x = ld(X + (size_t)(r - t) * width + ch); + const float b = ld(bs + (size_t)t * width + ch), dv = ld(d + t * groups + g); + const float lead = (K & SWAP) ? dv : b, fused = (K & SWAP) ? b : dv; + y = point(__fadd_rn(y, point(__fmul_rn(lead, x)))); + y = point((K & TWO_ROUND) ? __fadd_rn(y, bf(__fmul_rn(fused, x))) : __fmaf_rn(fused, x, y)); + } + Y[(size_t)r * width + ch] = __float2bfloat16_rn(y); +} + +constexpr int GS = 1; // silu's rounding point: bf16(g s) before up's product + +// Qwen3's MLP activation on a stacked gate | up row, no clamp: bf16(bf16(g s) u), s = sigmoid(g) from e = exp(-|g|). +template +__device__ __forceinline__ void silu(const bf16* __restrict__ GU, bf16* __restrict__ A, int rows, int width) { + const int x = blockIdx.x * blockDim.x + threadIdx.x, row = blockIdx.y; + if (x >= width || row >= rows) return; + const size_t at = (size_t)row * 2 * width + x; + const float g = ld(GU + at), u = ld(GU + at + width); + const float e = expf(-fabsf(g)), y = __fdiv_rn(1.0f, __fadd_rn(1.0f, e)); + const float s = g < 0.0f ? __fmul_rn(e, y) : y; // e / (1 + e) below 0, which 1 - y would cancel + A[(size_t)row * width + x] = __float2bfloat16_rn(__fmul_rn(point(__fmul_rn(g, s)), u)); +} + +} // namespace tf_rcd diff --git a/zig/kernels/cuda/ricursive_dflash2_attn.cu b/zig/kernels/cuda/ricursive_dflash2_attn.cu new file mode 100644 index 00000000000..ed38e03eedc --- /dev/null +++ b/zig/kernels/cuda/ricursive_dflash2_attn.cu @@ -0,0 +1,277 @@ +// Ripple's DFlash2 draft attention and top-32 on CUDA: dflash2.metal's rc_df_vec, ll_merge_vec, rc_df_topk, controls. + +#include +#include +#include + +#include "common/reduce.cuh" + +// tf_rcda, not tf_rcd: the kernels' extern "C" symbols take that prefix. +namespace tf_rcda { + +typedef __nv_bfloat16 bf16; + +// Head dim 128, a lane's dims 4 lane..4 lane + 3; 16 block rows a stream; 128 keys a chunk (rc_df_vec's blocks). +constexpr int D = 128, PER = 4, BLOCK = 16, CHUNK = 128; +// The partial: 8 warps share the chunk; K then V of 128 keys in dynamic shared memory (64 KiB, opted into at load). +constexpr int NT = 256, WARPS = NT / 32; +// rc_df_topk: 2,048 values a chunk, 1,024 threads, the best 32. +constexpr int TOPN = 2048, TOPT = 1024, TOP = 32; + +// A stream: its layer ring (K, then V a ring further), its block's first position, its lowest visible one, its window. +struct Segment { + unsigned long long ring; + int anchor, from, span, rows; +}; + +// Planted faults (controls only): the partial's key range, the merge's output rounding, the top-32 order and inputs. +enum : int { CAUSAL = 1, FLOOR = 2, NO_BLOCK = 4 }; +enum : int { TRUNC = 1 }; +enum : int { TIES = 1, DROP = 2 }; + +// Row r's lowest key: max(p + 1 - span, from) at p = anchor + r (FLOOR: one key lower). +__device__ __forceinline__ int window_lo(const Segment& g, int r, int f) { + const int lo = max(g.anchor + r + 1 - g.span, g.from) - ((f & FLOOR) != 0 ? 1 : 0); + return max(lo, 0); +} + +// One past the block's last key (NO_BLOCK: the block rows left out; CAUSAL: row r's own position the last). +__device__ __forceinline__ int window_hi(const Segment& g, int r, int f) { + if ((f & NO_BLOCK) != 0) return g.anchor; + if ((f & CAUSAL) != 0) return g.anchor + r + 1; + return g.anchor + BLOCK; +} + +// Grid (kv_heads, streams, cap): a block's 128-key chunk read once for the group's 10 query heads and 16 block rows. +template +__device__ __forceinline__ void attn_part(const bf16* __restrict__ Q, const Segment* __restrict__ segs, + float* __restrict__ PM, float* __restrict__ PL, float* __restrict__ PO, + int kv_heads, int group, int cap, float scale) { + extern __shared__ __align__(16) unsigned char smem[]; + bf16* Ks = reinterpret_cast(smem); + bf16* Vs = Ks + CHUNK * D; + const int kv = blockIdx.x, s = blockIdx.y, z = blockIdx.z; + const int lane = threadIdx.x & 31, w = threadIdx.x >> 5; + const int heads = kv_heads * group; + const Segment g = segs[s]; + const int lo0 = window_lo(g, 0, F); // row 0's window starts lowest + int hi0 = 0; // the union's end: the largest row end + for (int r = 0; r < BLOCK; ++r) hi0 = max(hi0, window_hi(g, r, F)); + // chunk z of stream s is absolute 128-key chunk first + z; rows see max(p + 1 - span, from) to anchor + 16 + const int first = lo0 / CHUNK; + const int base = (first + z) * CHUNK; + const int k0 = max(lo0, base), k1 = min(hi0, base + CHUNK); + if (k0 < k1) { + // the chunk's keys of key head kv, ring row p % rows, 16 bytes a thread a step: read once for the 160 (head, row)s + const bf16* K = reinterpret_cast(g.ring); + const bf16* V = K + (size_t)g.rows * kv_heads * D; + for (int i = threadIdx.x; i < (k1 - k0) * (D / 8); i += NT) { + const int key = k0 + i / (D / 8), part = (i % (D / 8)) * 8; + const size_t at = ((size_t)(key % g.rows) * kv_heads + kv) * D + part; + const int local = (key - base) * D + part; + *reinterpret_cast(Ks + local) = *reinterpret_cast(K + at); + *reinterpret_cast(Vs + local) = *reinterpret_cast(V + at); + } + } + __syncthreads(); + for (int pair = w; pair < group * BLOCK; pair += WARPS) { + const int head = kv * group + pair / BLOCK, r = pair % BLOCK; + // partials: PM the running max, PL the mass, PO the sums; no keys in the chunk: PM -inf, PL 0 + const size_t slot = (((size_t)s * heads + head) * BLOCK + r) * cap + z; + const int from = max(window_lo(g, r, F), base), to = min(window_hi(g, r, F), base + CHUNK); + if (from >= to) { + if (lane == 0) { + PM[slot] = -INFINITY; + PL[slot] = 0.0f; + } + continue; + } + // rc_df_vec: qv = scale * q in fp32 (the softmax scale's rounding point) + const bf16* q = Q + (((size_t)s * BLOCK + r) * heads + head) * D + PER * lane; + float qv[PER], acc[PER]; +#pragma unroll + for (int j = 0; j < PER; ++j) { + qv[j] = __fmul_rn(scale, __bfloat162float(q[j])); + acc[j] = 0.0f; + } + float top = -INFINITY, mass = 0.0f; + for (int i0 = from; i0 < to; i0 += 4) { + float score[4], vr[4][PER]; +#pragma unroll + for (int u = 0; u < 4; ++u) { + const bool live = i0 + u < to; + const int local = ((live ? i0 + u : from) - base) * D + PER * lane; // a key past the end reads `from`, as Metal + const uint2 kb = *reinterpret_cast(Ks + local); + const uint2 vb = *reinterpret_cast(Vs + local); + const __nv_bfloat162* kp = reinterpret_cast(&kb); + const __nv_bfloat162* vp = reinterpret_cast(&vb); + const float2 k01 = __bfloat1622float2(kp[0]), k23 = __bfloat1622float2(kp[1]); + const float2 v01 = __bfloat1622float2(vp[0]), v23 = __bfloat1622float2(vp[1]); + // the lane's 4-term dot (fma explicit), then the warp's butterfly: every lane holds the same score + float d = __fmul_rn(qv[0], k01.x); + d = __fmaf_rn(qv[1], k01.y, d); + d = __fmaf_rn(qv[2], k23.x, d); + d = __fmaf_rn(qv[3], k23.y, d); + const float sc = tf_common::warp_sum(d); + score[u] = live ? sc : -INFINITY; + // a key past the end adds nothing (Metal adds 0 times `from`'s value, NaN where that value is infinite) + vr[u][0] = live ? v01.x : 0.0f; + vr[u][1] = live ? v01.y : 0.0f; + vr[u][2] = live ? v23.x : 0.0f; + vr[u][3] = live ? v23.y : 0.0f; + } + // the group's max (fmaxf: a NaN score is skipped), the old mass and sums rescaled, then each key's weight + const float peak = fmaxf(fmaxf(top, fmaxf(score[0], score[1])), fmaxf(score[2], score[3])); + const float rescale = expf(__fsub_rn(top, peak)); + mass = __fmul_rn(mass, rescale); +#pragma unroll + for (int j = 0; j < PER; ++j) acc[j] = __fmul_rn(acc[j], rescale); +#pragma unroll + for (int u = 0; u < 4; ++u) { + const float wt = expf(__fsub_rn(score[u], peak)); + mass = __fadd_rn(mass, wt); +#pragma unroll + for (int j = 0; j < PER; ++j) acc[j] = __fadd_rn(acc[j], __fmul_rn(wt, vr[u][j])); + } + top = peak; + } + if (lane == 0) { + PM[slot] = top; + PL[slot] = mass; + } + *reinterpret_cast(PO + slot * D + PER * lane) = make_float4(acc[0], acc[1], acc[2], acc[3]); + } +} + +// A warp a (row, head), 8 a block: chunks merged as ll_merge_vec (a NaN mass makes the sums NaN), to bf16 (TRUNC: rz). +template +__device__ __forceinline__ void attn_merge(const float* __restrict__ PM, const float* __restrict__ PL, + const float* __restrict__ PO, bf16* __restrict__ O, int rows, int heads, + int cap) { + const int unit = blockIdx.x * WARPS + (threadIdx.x >> 5); + const int lane = threadIdx.x & 31; + if (unit >= rows * heads) return; + const int row = unit / heads, head = unit % heads; + const int s = row / BLOCK, r = row % BLOCK; + const size_t at = (((size_t)s * heads + head) * BLOCK + r) * cap; + const float* ms = PM + at; + const float* ls = PL + at; + float top = -INFINITY; + for (int b = 0; b < cap; ++b) top = fmaxf(top, ms[b]); + // the max, the masses times exp(max_b - max) where mass > 0, the sums by the same factors where not mass <= 0 + float total = 0.0f; + for (int b = 0; b < cap; ++b) + if (ls[b] > 0.0f) total = __fadd_rn(total, __fmul_rn(ls[b], expf(__fsub_rn(ms[b], top)))); + float acc[PER] = {0.0f, 0.0f, 0.0f, 0.0f}; + for (int b = 0; b < cap; ++b) { + if (ls[b] <= 0.0f) continue; + const float f = expf(__fsub_rn(ms[b], top)); + const float4 o = *reinterpret_cast(PO + (at + b) * D + PER * lane); + acc[0] = __fadd_rn(acc[0], __fmul_rn(f, o.x)); + acc[1] = __fadd_rn(acc[1], __fmul_rn(f, o.y)); + acc[2] = __fadd_rn(acc[2], __fmul_rn(f, o.z)); + acc[3] = __fadd_rn(acc[3], __fmul_rn(f, o.w)); + } + bf16* y = O + ((size_t)row * heads + head) * D + PER * lane; +#pragma unroll + for (int j = 0; j < PER; ++j) { + const float v = __fdiv_rn(acc[j], total); + y[j] = (F & TRUNC) != 0 ? __float2bfloat16_rz(v) : __float2bfloat16_rn(v); + } +} + +// rc_df_before: a first by value, then by the lower id (TIES: the higher id). +template +__device__ __forceinline__ bool before(float a, unsigned ia, float b, unsigned ib) { + return a > b || (a == b && ((F & TIES) != 0 ? ia > ib : ia < ib)); +} + +// Grid (chunks, rows), 1,024 threads: row r's chunk c (L, or IDS: VIN, IIN) sorted; best 32 at (r chunks + c) 32. +template +__device__ __forceinline__ void top32(const bf16* __restrict__ L, const float* __restrict__ VIN, + const unsigned* __restrict__ IIN, int n, int stride, int chunks, + float* __restrict__ VOUT, unsigned* __restrict__ IOUT) { + // padding is (-inf, 0xffffffff); DROP (the merge's control) reads the first 32 inputs, chunk 0's bests, as padding + __shared__ float v[TOPN]; + __shared__ unsigned id[TOPN]; + const int row = blockIdx.y, chunk = blockIdx.x, t = threadIdx.x; + for (int i = t; i < TOPN; i += TOPT) { + const int at = chunk * TOPN + i; + if (at < n && !((F & DROP) != 0 && at < TOP)) { + const size_t src = (size_t)row * stride + at; + v[i] = IDS ? VIN[src] : __bfloat162float(L[src]); + id[i] = IDS ? IIN[src] : (unsigned)at; + } else { + v[i] = -INFINITY; + id[i] = 0xffffffffu; + } + } + __syncthreads(); + for (int k = 2; k <= TOPN; k <<= 1) + for (int j = k >> 1; j > 0; j >>= 1) { + for (int i = t; i < TOPN; i += TOPT) { + const int l = i ^ j; + if (l > i) { + const bool down = (i & k) == 0; // descending runs where the k-bit is clear + const bool swap = down ? before(v[l], id[l], v[i], id[i]) : before(v[i], id[i], v[l], id[l]); + if (swap) { + const float tv = v[i]; + v[i] = v[l]; + v[l] = tv; + const unsigned ti = id[i]; + id[i] = id[l]; + id[l] = ti; + } + } + } + __syncthreads(); + } + if (t < TOP) { + VOUT[((size_t)row * chunks + chunk) * TOP + t] = v[t]; + IOUT[((size_t)row * chunks + chunk) * TOP + t] = id[t]; + } +} + +} // namespace tf_rcda + +#define TF_RCD_ATTN_PART(NAME, F) \ + extern "C" __global__ void __launch_bounds__(tf_rcda::NT) \ + NAME(const tf_rcda::bf16* __restrict__ Q, const tf_rcda::Segment* __restrict__ segs, float* __restrict__ PM, \ + float* __restrict__ PL, float* __restrict__ PO, int kv_heads, int group, int cap, float scale) { \ + tf_rcda::attn_part(Q, segs, PM, PL, PO, kv_heads, group, cap, scale); \ + } + +#define TF_RCD_ATTN_MERGE(NAME, F) \ + extern "C" __global__ void __launch_bounds__(tf_rcda::NT) \ + NAME(const float* __restrict__ PM, const float* __restrict__ PL, const float* __restrict__ PO, \ + tf_rcda::bf16* __restrict__ O, int rows, int heads, int cap) { \ + tf_rcda::attn_merge(PM, PL, PO, O, rows, heads, cap); \ + } + +#define TF_RCD_TOP32_PART(NAME, F) \ + extern "C" __global__ void __launch_bounds__(tf_rcda::TOPT) \ + NAME(const tf_rcda::bf16* __restrict__ L, int n, int stride, int chunks, float* __restrict__ VOUT, \ + unsigned* __restrict__ IOUT) { \ + tf_rcda::top32(L, nullptr, nullptr, n, stride, chunks, VOUT, IOUT); \ + } + +#define TF_RCD_TOP32_MERGE(NAME, F) \ + extern "C" __global__ void __launch_bounds__(tf_rcda::TOPT) \ + NAME(const float* __restrict__ VIN, const unsigned* __restrict__ IIN, int n, int stride, int chunks, \ + float* __restrict__ VOUT, unsigned* __restrict__ IOUT) { \ + tf_rcda::top32(nullptr, VIN, IIN, n, stride, chunks, VOUT, IOUT); \ + } + +TF_RCD_ATTN_PART(tf_rcd_attn_part, 0) +TF_RCD_ATTN_MERGE(tf_rcd_attn_merge, 0) +TF_RCD_TOP32_PART(tf_rcd_top32_part, 0) +TF_RCD_TOP32_MERGE(tf_rcd_top32_merge, 0) + +// Planted controls: causal block, floor a key low, no block rows, truncating merge, higher-id ties, chunk 0 dropped. +TF_RCD_ATTN_PART(tf_rcd_ctl_attn_causal, tf_rcda::CAUSAL) +TF_RCD_ATTN_PART(tf_rcd_ctl_attn_floor, tf_rcda::FLOOR) +TF_RCD_ATTN_PART(tf_rcd_ctl_attn_no_block, tf_rcda::NO_BLOCK) +TF_RCD_ATTN_MERGE(tf_rcd_ctl_attn_merge_trunc, tf_rcda::TRUNC) +TF_RCD_TOP32_PART(tf_rcd_ctl_top32_part_ties, tf_rcda::TIES) +TF_RCD_TOP32_MERGE(tf_rcd_ctl_top32_merge_ties, tf_rcda::TIES) +TF_RCD_TOP32_MERGE(tf_rcd_ctl_top32_merge_drop, tf_rcda::DROP) diff --git a/zig/src/core/contract/measurements/pending_133.zig b/zig/src/core/contract/measurements/pending_133.zig index db15604fd7c..7d3ea0dd26a 100644 --- a/zig/src/core/contract/measurements/pending_133.zig +++ b/zig/src/core/contract/measurements/pending_133.zig @@ -88,6 +88,15 @@ pub const records = [_]Override{ .{ .name = "ricursive tf_rc_add_norm", .usage = .{ .{ .regs = 80, .static = 32, .bound = 256 }, .{ .regs = 79, .static = 32, .bound = 256 }, .{ .regs = 79, .static = 32, .bound = 256 }, .{ .regs = 79, .static = 32, .bound = 256 }, .{ .regs = 79, .static = 32, .bound = 256 } } }, .{ .name = "ricursive tf_rc_gate", .usage = .{ .{ .regs = 15, .static = 0, .bound = 256 }, .{ .regs = 14, .static = 0, .bound = 256 }, .{ .regs = 14, .static = 0, .bound = 256 }, .{ .regs = 14, .static = 0, .bound = 256 }, .{ .regs = 14, .static = 0, .bound = 256 } } }, .{ .name = "ricursive tf_rc_silu_clamp", .usage = .{ .{ .regs = 17, .static = 0, .bound = 256 }, .{ .regs = 18, .static = 0, .bound = 256 }, .{ .regs = 18, .static = 0, .bound = 256 }, .{ .regs = 19, .static = 0, .bound = 256 }, .{ .regs = 19, .static = 0, .bound = 256 } } }, + .{ .name = "ricursive tf_rc_tap", .usage = .{ .{ .regs = 16, .static = 0, .bound = 256 }, .{ .regs = 18, .static = 0, .bound = 256 }, .{ .regs = 18, .static = 0, .bound = 256 }, .{ .regs = 18, .static = 0, .bound = 256 }, .{ .regs = 18, .static = 0, .bound = 256 } } }, + .{ .name = "ricursive_dflash2 tf_rcd_add_norm", .usage = .{ .{ .regs = 63, .static = 32, .bound = 256 }, .{ .regs = 73, .static = 32, .bound = 256 }, .{ .regs = 73, .static = 32, .bound = 256 }, .{ .regs = 76, .static = 32, .bound = 256 }, .{ .regs = 76, .static = 32, .bound = 256 } } }, + .{ .name = "ricursive_dflash2 tf_rcd_conv", .usage = .{ .{ .regs = 25, .static = 0, .bound = 256 }, .{ .regs = 27, .static = 0, .bound = 256 }, .{ .regs = 27, .static = 0, .bound = 256 }, .{ .regs = 24, .static = 0, .bound = 256 }, .{ .regs = 24, .static = 0, .bound = 256 } } }, + .{ .name = "ricursive_dflash2 tf_rcd_prep", .usage = .{ .{ .regs = 32, .static = 0, .bound = 256 }, .{ .regs = 38, .static = 0, .bound = 256 }, .{ .regs = 38, .static = 0, .bound = 256 }, .{ .regs = 35, .static = 0, .bound = 256 }, .{ .regs = 35, .static = 0, .bound = 256 } } }, + .{ .name = "ricursive_dflash2 tf_rcd_silu", .usage = .{ .{ .regs = 19, .static = 0, .bound = 256 }, .{ .regs = 18, .static = 0, .bound = 256 }, .{ .regs = 18, .static = 0, .bound = 256 }, .{ .regs = 18, .static = 0, .bound = 256 }, .{ .regs = 18, .static = 0, .bound = 256 } } }, + .{ .name = "ricursive_dflash2_attn tf_rcd_attn_merge", .usage = .{ .{ .regs = 32, .static = 0, .bound = 256 }, .{ .regs = 36, .static = 0, .bound = 256 }, .{ .regs = 36, .static = 0, .bound = 256 }, .{ .regs = 40, .static = 0, .bound = 256 }, .{ .regs = 40, .static = 0, .bound = 256 } } }, + .{ .name = "ricursive_dflash2_attn tf_rcd_attn_part", .usage = .{ .{ .regs = 58, .static = 0, .bound = 256 }, .{ .regs = 56, .static = 0, .bound = 256 }, .{ .regs = 56, .static = 0, .bound = 256 }, .{ .regs = 60, .static = 0, .bound = 256 }, .{ .regs = 60, .static = 0, .bound = 256 } } }, + .{ .name = "ricursive_dflash2_attn tf_rcd_top32_merge", .usage = .{ .{ .regs = 27, .static = 16384, .bound = 1024 }, .{ .regs = 34, .static = 16384, .bound = 1024 }, .{ .regs = 34, .static = 16384, .bound = 1024 }, .{ .regs = 23, .static = 16384, .bound = 1024 }, .{ .regs = 23, .static = 16384, .bound = 1024 } } }, + .{ .name = "ricursive_dflash2_attn tf_rcd_top32_part", .usage = .{ .{ .regs = 29, .static = 16384, .bound = 1024 }, .{ .regs = 30, .static = 16384, .bound = 1024 }, .{ .regs = 30, .static = 16384, .bound = 1024 }, .{ .regs = 23, .static = 16384, .bound = 1024 }, .{ .regs = 23, .static = 16384, .bound = 1024 } } }, .{ .name = "ricursive_prep tf_rc_prep", .usage = .{ .{ .regs = 32, .static = 0, .bound = 256 }, .{ .regs = 38, .static = 0, .bound = 256 }, .{ .regs = 38, .static = 0, .bound = 256 }, .{ .regs = 36, .static = 0, .bound = 256 }, .{ .regs = 36, .static = 0, .bound = 256 } } }, .{ .name = "ricursive_prep tf_rc_prep_rows", .usage = .{ .{ .regs = 38, .static = 0, .bound = 256 }, .{ .regs = 38, .static = 0, .bound = 256 }, .{ .regs = 38, .static = 0, .bound = 256 }, .{ .regs = 38, .static = 0, .bound = 256 }, .{ .regs = 38, .static = 0, .bound = 256 } } }, .{ .name = "window attention wattn_kernel<128, 8, 2, 8>", .usage = .{ .{ .regs = 222, .static = 0, .bound = 256 }, .{ .regs = 222, .static = 0, .bound = 256 }, .{ .regs = 222, .static = 0, .bound = 256 }, .{ .regs = 218, .static = 0, .bound = 256 }, .{ .regs = 218, .static = 0, .bound = 256 } } }, diff --git a/zig/src/core/contract/registry_joins.zig b/zig/src/core/contract/registry_joins.zig index 1130c98bbd1..b8f7e0e1499 100644 --- a/zig/src/core/contract/registry_joins.zig +++ b/zig/src/core/contract/registry_joins.zig @@ -82,6 +82,8 @@ pub const cuda_pending = @import("mhc_cuda_records.zig").cuda ++ @import("glm_de @import("ricursive_cuda_records.zig").cuda ++ @import("ricursive_prep_records.zig").cuda ++ @import("ricursive_attn_records.zig").cuda ++ + @import("ricursive_dflash2_attn_records.zig").cuda ++ + @import("ricursive_dflash2_records.zig").cuda ++ @import("registry_media.zig").cuda_pending ++ @import("h3_image_cuda_records.zig").records; pub const metal_before = @import("fsr_records.zig").metal ++ diff --git a/zig/src/core/contract/ricursive_cuda_records.zig b/zig/src/core/contract/ricursive_cuda_records.zig index 74512b42d81..ffd8092663a 100644 --- a/zig/src/core/contract/ricursive_cuda_records.zig +++ b/zig/src/core/contract/ricursive_cuda_records.zig @@ -1,4 +1,4 @@ -//! Ripple's CUDA glue (ricursive.cu): its served launches, pending in registry.cuda_pending until nvcc's records land. +//! Ripple's CUDA glue and the drafter's tap (ricursive.cu): its served launches, pending until nvcc's records land. const std = @import("std"); const registry = @import("registry.zig"); @@ -8,6 +8,7 @@ pub const cuda = [_]registry.CudaRecord{ .{ .launch = .{ .name = "ricursive tf_rc_add_norm", .symbol = "tf_rc_add_norm", .image = "ricursive", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 } } }, .{ .launch = .{ .name = "ricursive tf_rc_gate", .symbol = "tf_rc_gate", .image = "ricursive", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 } } }, .{ .launch = .{ .name = "ricursive tf_rc_silu_clamp", .symbol = "tf_rc_silu_clamp", .image = "ricursive", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 } } }, + .{ .launch = .{ .name = "ricursive tf_rc_tap", .symbol = "tf_rc_tap", .image = "ricursive", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 } } }, }; test "Ripple's CUDA glue records: one served launch a symbol, on the ricursive image" { diff --git a/zig/src/core/contract/ricursive_dflash2_attn_records.zig b/zig/src/core/contract/ricursive_dflash2_attn_records.zig new file mode 100644 index 00000000000..b0ecc903aeb --- /dev/null +++ b/zig/src/core/contract/ricursive_dflash2_attn_records.zig @@ -0,0 +1,24 @@ +//! Ripple's DFlash2 draft attention (64 KiB dynamic shared) and top-32 (1,024 threads) on CUDA: their served launches. +const registry = @import("registry.zig"); +const limits = @import("limits.zig"); + +const zero: limits.Usage = .{ .regs = 0, .static = 0, .bound = 0 }; + +/// Usage zero (no nvcc 13.0 record yet); nvcc 13.3's five-SM receipts are in measurements/pending_133.zig. +pub const cuda = [_]registry.CudaRecord{ + .{ .launch = .{ .name = "ricursive_dflash2_attn tf_rcd_attn_part", .symbol = "tf_rcd_attn_part", .image = "ricursive_dflash2_attn", .threads = 256, .dynamic = 65536, .opt_in = true, .min_sm = 80 }, .usage = .{ zero, zero, zero, zero, zero } }, + .{ .launch = .{ .name = "ricursive_dflash2_attn tf_rcd_attn_merge", .symbol = "tf_rcd_attn_merge", .image = "ricursive_dflash2_attn", .threads = 256, .min_sm = 80 }, .usage = .{ zero, zero, zero, zero, zero } }, + .{ .launch = .{ .name = "ricursive_dflash2_attn tf_rcd_top32_part", .symbol = "tf_rcd_top32_part", .image = "ricursive_dflash2_attn", .threads = 1024, .min_sm = 80 }, .usage = .{ zero, zero, zero, zero, zero } }, + .{ .launch = .{ .name = "ricursive_dflash2_attn tf_rcd_top32_merge", .symbol = "tf_rcd_top32_merge", .image = "ricursive_dflash2_attn", .threads = 1024, .min_sm = 80 }, .usage = .{ zero, zero, zero, zero, zero } }, +}; + +test "ricursive DFlash2 attention CUDA: each launch is in the live registry once, at its kernel's threads" { + const std = @import("std"); + const t = std.testing; + for (cuda) |r| { + var found: usize = 0; + for (registry.all_cuda) |active| found += @intFromBool(std.mem.eql(u8, active.launch.name, r.launch.name)); + try t.expectEqual(@as(usize, 1), found); + try t.expectEqual(@as(u32, if (std.mem.indexOf(u8, r.launch.name, "top32") != null) 1024 else 256), r.launch.threads); + } +} diff --git a/zig/src/core/contract/ricursive_dflash2_records.zig b/zig/src/core/contract/ricursive_dflash2_records.zig new file mode 100644 index 00000000000..59b7a5cf8b9 --- /dev/null +++ b/zig/src/core/contract/ricursive_dflash2_records.zig @@ -0,0 +1,21 @@ +//! Ripple's DFlash2 drafter glue on CUDA (ricursive_dflash2.cu), 256 threads each; its embed is tf_rc_embed's record. +const registry = @import("registry.zig"); + +/// Usage zero (no nvcc 13.0 record yet); nvcc 13.3's five-SM receipts are in measurements/pending_133.zig. +pub const cuda = [_]registry.CudaRecord{ + .{ .launch = .{ .name = "ricursive_dflash2 tf_rcd_add_norm", .symbol = "tf_rcd_add_norm", .image = "ricursive_dflash2", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 } } }, + .{ .launch = .{ .name = "ricursive_dflash2 tf_rcd_prep", .symbol = "tf_rcd_prep", .image = "ricursive_dflash2", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 } } }, + .{ .launch = .{ .name = "ricursive_dflash2 tf_rcd_conv", .symbol = "tf_rcd_conv", .image = "ricursive_dflash2", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 } } }, + .{ .launch = .{ .name = "ricursive_dflash2 tf_rcd_silu", .symbol = "tf_rcd_silu", .image = "ricursive_dflash2", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 } } }, +}; + +test "ricursive DFlash2 CUDA: each launch is in the live registry once, at the kernels' 256 threads" { + const std = @import("std"); + const t = std.testing; + for (cuda) |r| { + var found: usize = 0; + for (registry.all_cuda) |active| found += @intFromBool(std.mem.eql(u8, active.launch.name, r.launch.name)); + try t.expectEqual(@as(usize, 1), found); + try t.expectEqual(@as(u32, 256), r.launch.threads); + } +} diff --git a/zig/src/core/lanes/drafted.zig b/zig/src/core/lanes/drafted.zig index ffe69ed2abd..ccc55c1efad 100644 --- a/zig/src/core/lanes/drafted.zig +++ b/zig/src/core/lanes/drafted.zig @@ -138,6 +138,7 @@ pub const Drafted = struct { if (d.copy_match > 0) m.copy_match = d.copy_match; if (d.window_costs.len > 0) m.window_costs = d.window_costs; if (d.lane_costs.len > 0) m.lane_costs = d.lane_costs; + if (d.shared_costs.len > 0) m.shared_costs = d.shared_costs; return m; } diff --git a/zig/src/core/lanes/drafter.zig b/zig/src/core/lanes/drafter.zig index fa39b78d6bb..326bc046053 100644 --- a/zig/src/core/lanes/drafter.zig +++ b/zig/src/core/lanes/drafter.zig @@ -20,6 +20,7 @@ pub const Facts = struct { trees: bool = false, // hold() takes a tree of lanes (Hold.lanes), each lane its parent's rank-r token window_costs: []const Cost = &.{}, // the target's window ms by rows (timed at load), for the depth rule lane_costs: []const Cost = &.{}, // the same for the lane planner (Model.lane_costs) + shared_costs: []const Cost = &.{}, // a shared round's ms by total rows (timed at load), for shared drafts copy_match: i64 = 0, // matching tokens a copy needs beside this drafter's proposals (0: the target's copy_match) tree_nodes: u32 = 0, // hold() without lanes grows its own tree of up to `depth` nodes, at most this many (tree, chances) shared_cap: u32 = 0, // optional shared-round depth cap when tree_nodes exceeds a chain's depth (0: off) diff --git a/zig/src/cuda/kernels.zig b/zig/src/cuda/kernels.zig index 656ad3a509d..c81b11e7fdb 100644 --- a/zig/src/cuda/kernels.zig +++ b/zig/src/cuda/kernels.zig @@ -133,8 +133,10 @@ pub const ernie5_5_hca_attn: []const u8 = if (available) &Blob("fatbin_ernie5_5_ pub const inkling2_rows: []const u8 = if (available) &Blob("fatbin_inkling2_rows").bytes else &.{}; pub const inkling2_dspark: []const u8 = if (available) &Blob("fatbin_inkling2_dspark").bytes else &.{}; pub const inkling2_dflash2: []const u8 = if (available) &Blob("fatbin_inkling2_dflash2").bytes else &.{}; +pub const ricursive_dflash2_attn: []const u8 = if (available) &Blob("fatbin_ricursive_dflash2_attn").bytes else &.{}; pub const ricursive: []const u8 = if (available) &Blob("fatbin_ricursive").bytes else &.{}; pub const ricursive_prep: []const u8 = if (available) &Blob("fatbin_ricursive_prep").bytes else &.{}; +pub const ricursive_dflash2: []const u8 = if (available) &Blob("fatbin_ricursive_dflash2").bytes else &.{}; pub const inkling2_experts: []const u8 = if (available) &Blob("fatbin_inkling2_experts").bytes else &.{}; pub const inkling2_modelopt: []const u8 = if (available) &Blob("fatbin_inkling2_modelopt").bytes else &.{}; pub const inkling2_loop_math: []const u8 = if (available) &Blob("fatbin_inkling2_loop_math").bytes else &.{}; diff --git a/zig/src/families/ricursive/cuda.zig b/zig/src/families/ricursive/cuda.zig index 98b3e097147..06cf8088210 100644 --- a/zig/src/families/ricursive/cuda.zig +++ b/zig/src/families/ricursive/cuda.zig @@ -3,17 +3,31 @@ pub const kernels = @import("cuda_kernels.zig"); pub const prep = @import("cuda_prep.zig"); pub const attn = @import("cuda_attn.zig"); +pub const dflash2_kernels = @import("cuda_dflash2_kernels.zig"); pub const weights = @import("cuda_weights.zig"); pub const model = @import("cuda_model.zig"); pub const backend = @import("cuda_backend.zig"); pub const native = @import("cuda_native.zig"); +pub const dflash2_weights = @import("cuda_dflash2_weights.zig"); +pub const dflash2_select = @import("cuda_dflash2_select.zig"); +pub const dflash2_attn = @import("cuda_dflash2_attn.zig"); +pub const dflash2 = @import("cuda_dflash2.zig"); +pub const dflash2_shared = @import("cuda_dflash2_shared.zig"); +pub const dflash2_config = @import("cuda_dflash2_config.zig"); test { _ = kernels; _ = prep; _ = attn; + _ = dflash2_kernels; _ = weights; _ = model; _ = backend; _ = native; + _ = dflash2_weights; + _ = dflash2_select; + _ = dflash2_attn; + _ = dflash2; + _ = dflash2_shared; + _ = dflash2_config; } diff --git a/zig/src/families/ricursive/cuda_arena.zig b/zig/src/families/ricursive/cuda_arena.zig new file mode 100644 index 00000000000..a95699d37c4 --- /dev/null +++ b/zig/src/families/ricursive/cuda_arena.zig @@ -0,0 +1,105 @@ +//! Ripple's caches on CUDA: every slot's sliding rings and global pages in one buffer, then the page table. +const std = @import("std"); +const cuda = @import("cuda"); +const cfg = @import("config.zig"); +const fwd = @import("cuda_model.zig"); + +const wa = cuda.window_attention; +const Stream = cuda.Stream; +const DeviceBuffer = cuda.DeviceBuffer; +const Config = cfg.Config; +const ring_rows = fwd.ring_rows; +const page_tokens = fwd.page_tokens; +const buffer_align = fwd.buffer_align; + +/// The pages a slot's global layer holds: the context in whole pages. +pub fn pagesOf(context: usize) usize { + return (context + page_tokens - 1) / page_tokens; +} + +/// A layer's caches from slot 0: a sliding layer's rings [slots][ring][kv_heads][128], or (`pg`) a global's pages. +pub const Cache = struct { kc: u64, vc: u64, pg: ?wa.Pages = null }; + +/// One slot's rows of a layer as a snapshot copies them: position p at ring row p % ring_rows, or global row p. +pub const Span = struct { k: u64, v: u64, rows: usize, row_bytes: usize, ring: bool }; + +/// One slot's caches: a sliding layer's K and V rings, a global layer's K and V pages for `context`. +pub fn slotBytes(c: Config, context: usize) usize { + const kvw = c.kvWidth(); + const g = c.globals(); + return (c.layers - g) * 2 * ring_rows * kvw * 2 + g * 2 * pagesOf(context) * page_tokens * kvw * 2; +} + +/// Every slot's caches in one buffer, a layer at a time (each slot's rows, K then V), then the page table. +pub const Arena = struct { + gpa: std.mem.Allocator, + kv: DeviceBuffer, + caches: []Cache, // a layer each, at slot 0 + ids: []i32, // the page table's host copy [slots][per_slot]: the call tables gather its rows + slots: usize, + per_slot: usize, // pages a slot's global layer holds + kvw: usize, + + /// `slots` slots' caches for `context` positions and the int32 table. + pub fn bytes(c: Config, context: usize, slots: usize) usize { + return slots * slotBytes(c, context) + std.mem.alignForward(usize, slots * pagesOf(context) * 4, buffer_align); + } + + /// Zeroed caches (no stale bits under a masked key), the identity table: slot s's page j is page s * per_slot + j. + pub fn init(gpa: std.mem.Allocator, d: *const cuda.Driver, s: Stream, c: Config, context: usize, slots: usize) !Arena { + const kvw = c.kvWidth(); + const per = pagesOf(context); + var kv = try DeviceBuffer.alloc(d, bytes(c, context, slots)); + errdefer kv.free(); + try d.check(d.api.cuMemsetD8Async(kv.ptr, 0, kv.len, s.handle), "cuMemsetD8Async"); + const caches = try gpa.alloc(Cache, c.layers); + errdefer gpa.free(caches); + const ids = try gpa.alloc(i32, slots * per); + errdefer gpa.free(ids); + for (ids, 0..) |*x, i| x.* = @intCast(i); + const table_at = kv.len - std.mem.alignForward(usize, ids.len * 4, buffer_align); + try cuda.copy_source.enqueue(d, kv.ptr + table_at, std.mem.sliceAsBytes(ids), s); + var at: u64 = kv.ptr; + for (caches, 0..) |*cache, i| { + const half: usize = slots * if (c.global[i]) per * page_tokens * kvw * 2 else ring_rows * kvw * 2; + cache.* = .{ .kc = at, .vc = at + half }; + if (c.global[i]) cache.pg = .{ .table = kv.ptr + table_at, .page_elems = page_tokens * kvw, .tokens = page_tokens, .stride = per }; + at += 2 * half; + } + return .{ .gpa = gpa, .kv = kv, .caches = caches, .ids = ids, .slots = slots, .per_slot = per, .kvw = kvw }; + } + + pub fn deinit(a: *Arena) void { + a.gpa.free(a.ids); + a.gpa.free(a.caches); + a.kv.free(); + a.* = undefined; + } + + /// Layer i's caches of one slot as a prompt chunk reads them: its rings, or the pools and its table row (stride 0). + pub fn slotCache(a: *const Arena, i: usize, slot: usize) Cache { + const c = a.caches[i]; + if (c.pg) |pg| { + var row = pg; + row.table += slot * a.per_slot * 4; + row.stride = 0; + return .{ .kc = c.kc, .vc = c.vc, .pg = row }; + } + const ring = ring_rows * a.kvw * 2; + return .{ .kc = c.kc + slot * ring, .vc = c.vc + slot * ring }; + } + + /// Layer i's rows of one slot. + pub fn span(a: *const Arena, i: usize, slot: usize) Span { + const c = a.caches[i]; + const row = a.kvw * 2; + const rows: usize = if (c.pg != null) a.per_slot * page_tokens else ring_rows; + return .{ .k = c.kc + slot * rows * row, .v = c.vc + slot * rows * row, .rows = rows, .row_bytes = row, .ring = c.pg == null }; + } + + /// The V pools' offset from the K pools in bf16 elements: the same in every global layer. + pub fn vOff(a: *const Arena) usize { + for (a.caches) |c| if (c.pg != null) return (c.vc - c.kc) / 2; + return 0; + } +}; diff --git a/zig/src/families/ricursive/cuda_backend.zig b/zig/src/families/ricursive/cuda_backend.zig index ae628c57194..8f7919a44d9 100644 --- a/zig/src/families/ricursive/cuda_backend.zig +++ b/zig/src/families/ricursive/cuda_backend.zig @@ -50,7 +50,7 @@ const Lane = struct { pub const Ripple = struct { gpa: std.mem.Allocator, d: *const cuda.Driver, - m: *const fwd.Model, + m: *fwd.Model, // mutable for setTaps (prepare_features) st: fwd.Seq = .{}, // slot 0's positions when the CLI drives the forward itself (cli/cuda_ricursive.zig) tok: cuda.DeviceBuffer, // int32 drawn tokens: the handle ring, then a round's rows meta: cuda.DeviceBuffer, // a draw's first position minus one, a window each @@ -59,6 +59,8 @@ pub const Ripple = struct { slot_bufs: cuda.DeviceBuffer, // a slot's last-row logits, then its rule, a slot each sample: cuda.Module, draws: cuda.sample.Draws, + mask_fn: cuda.Function, // sample.cu's tf_grammar_mask: structured output's disallowed tokens to -inf + masked: ?cuda.DeviceBuffer = null, // rows under their grammars, then the grammars' bits; the first such row opens it lanes: std.AutoHashMapUnmanaged(*const Stream, Lane) = .empty, free: []bool, // slot i is free next: u64 = 0, @@ -73,7 +75,7 @@ pub const Ripple = struct { return (ring + round_rows) * 4 + round_rows * 16 + word_rows * row_words * 4 + fwd.head_rows * 4 + slots * slotStride(vocab); } - pub fn init(gpa: std.mem.Allocator, d: *const cuda.Driver, m: *const fwd.Model) !Ripple { + pub fn init(gpa: std.mem.Allocator, d: *const cuda.Driver, m: *fwd.Model) !Ripple { const slots = m.arena.slots; const free = try gpa.alloc(bool, slots); errdefer gpa.free(free); @@ -91,7 +93,8 @@ pub const Ripple = struct { var sample = try cuda.Module.load(d, cuda.kernels.sample); errdefer sample.unload(); const draws = try cuda.sample.Draws.resolve(sample); - return .{ .gpa = gpa, .d = d, .m = m, .tok = tok, .meta = meta, .words = words, .picks = picks, .slot_bufs = slot_bufs, .sample = sample, .draws = draws, .free = free }; + const mask_fn = try sample.function("tf_grammar_mask"); + return .{ .gpa = gpa, .d = d, .m = m, .tok = tok, .meta = meta, .words = words, .picks = picks, .slot_bufs = slot_bufs, .sample = sample, .draws = draws, .mask_fn = mask_fn, .free = free }; } pub fn deinit(x: *Ripple) void { @@ -99,6 +102,7 @@ pub const Ripple = struct { while (it.next()) |l| l.rows.deinit(x.gpa); x.lanes.deinit(x.gpa); x.gpa.free(x.free); + if (x.masked) |*b| b.free(); x.sample.unload(); x.slot_bufs.free(); x.picks.free(); @@ -112,7 +116,7 @@ pub const Ripple = struct { return .{ .ptr = x, .vtable = &vtable, .chunk_invariant = true }; // chunk cuts give the same bits } - const vtable: be.Backend.VTable = .{ .prefill = prefill, .prefill_step = prefillStep, .cancel_prefill = cancelPrefill, .first = first, .queue = queue, .read = read, .verify = verify, .keep = keep, .draft = draft, .release = release, .first_row = firstRow, .prompt_rows = true, .reports_fill = true }; + const vtable: be.Backend.VTable = .{ .prefill = prefill, .prefill_step = prefillStep, .cancel_prefill = cancelPrefill, .first = first, .first_masked = firstMasked, .queue = queue, .read = read, .verify = verify, .keep = keep, .draft = draft, .release = release, .first_row = firstRow, .prepare_features = prepareFeatures, .features = features, .prompt_rows = true, .reports_fill = true }; /// The round loop's facts: no draft head; host copies verified in windows up to 16 rows, streams sharing a round. pub fn facts(x: *const Ripple) lanes.Model { @@ -132,8 +136,8 @@ pub const Ripple = struct { return x.tok.ptr + i * 4; } - /// `rows` bf16 logits rows drawn into `out`, row r at `position0 + r` (argmax when greedy). - fn drawRows(x: *Ripple, l: *const Lane, logits: u64, rows: usize, position0: u64, out: u64, meta_at: usize) !void { + /// `rows` bf16 logits rows drawn into `out`, row r at `position0 + r` (argmax when greedy); public for GPU tests. + pub fn drawRows(x: *Ripple, l: *const Lane, logits: u64, rows: usize, position0: u64, out: u64, meta_at: usize) !void { const v = x.m.c.vocab; if (!l.sampled) return x.m.k.argmaxRows(x.m.s, logits, rows, v, v, out); const meta = [4]i32{ @intCast(position0 - 1), 0, 0, 0 }; @@ -142,6 +146,31 @@ pub const Ripple = struct { try x.draws.draw(x.m.s, logits, v, l.rule, mp, 0, out, rows, null, null); } + /// A row's allowed-token words (lanes/grammar.zig: token t at bit t % 32 of word t / 32). + pub fn maskWords(vocab: usize) usize { + return (vocab + 31) / 32; + } + + /// `rows` logits rows copied to row `row` of the grammar scratch, the tokens `masks` disallows at -inf there. + fn maskedRows(x: *Ripple, logits: u64, rows: usize, masks: []const u32, row: usize) !u64 { + const v = x.m.c.vocab; + const nw = maskWords(v); + if (masks.len != rows * nw or row + rows > round_rows) return error.InvalidGrammarMasks; + if (x.masked == null) x.masked = try cuda.DeviceBuffer.alloc(x.d, round_rows * (v * 2 + nw * 4)); + const dst = x.masked.?.ptr + row * v * 2; + const bits = x.masked.?.ptr + round_rows * v * 2 + row * nw * 4; + // the rows at `logits` keep their bits: the logprob rows read them + try x.d.check(x.d.api.cuMemcpyDtoDAsync_v2(dst, logits, rows * v * 2, x.m.s.handle), "cuMemcpyDtoDAsync"); + try x.upload(bits, std.mem.sliceAsBytes(masks)); + var a: cuda.Args = .{}; + a.add(dst); + a.add(@as(u32, @intCast(v))); + a.add(bits); + a.add(@as(u32, @intCast(nw))); + try cuda.launch.launch(x.mask_fn, .{ .grid = .{ .x = @intCast(rows) }, .block = .{ .x = 256 } }, x.m.s, &a); + return dst; + } + /// The stream's caches at `at` for the prompt cache, copied behind the chunk that ends there. pub fn saveState(x: *Ripple, owner: ?*anyopaque, at: u32) !*snap.Saved { const s: *const Stream = @ptrCast(@alignCast(owner orelse return error.NoOwner)); @@ -178,7 +207,6 @@ pub const Ripple = struct { const p = s.prompt(); if (p.len == 0) return error.EmptyPrompt; if (!fits(x.m.context, p.len, @as(usize, s.max_new))) return error.PastContext; - if (s.grammar != null) return error.StructuresUnsupported; const got = try x.lanes.getOrPut(x.gpa, s); if (!got.found_existing) { const slot = x.freeSlot() orelse { @@ -300,11 +328,21 @@ pub const Ripple = struct { /// The prompt's last row drawn at `position`; with logprobs, its row kept for first_row. fn first(ptr: *anyopaque, s: *Stream, position: u64) anyerror!u64 { - const x = self(ptr); + return self(ptr).firstAt(s, position, &.{}); + } + + /// The first token under a grammar: the draw reads the row with its disallowed tokens at -inf. + fn firstMasked(ptr: *anyopaque, s: *Stream, position: u64, mask: []const u32) anyerror!u64 { + if (mask.len == 0) return error.InvalidGrammarMasks; + return self(ptr).firstAt(s, position, mask); + } + + fn firstAt(x: *Ripple, s: *Stream, position: u64, mask: []const u32) !u64 { const l = try x.laneOf(s); if (position != l.len or l.fill != null) return error.PositionMismatch; + const from = if (mask.len == 0) l.last else try x.maskedRows(l.last, 1, mask, 0); const h = x.handle(); - try x.drawRows(l, l.last, 1, position, x.tokAt(h % ring), 0); + try x.drawRows(l, from, 1, position, x.tokAt(h % ring), 0); if (s.logprobs) |k| { try x.draws.logprobRows(x.m.s, l.last, x.m.c.vocab, x.tokAt(h % ring), k, false, x.words.ptr, 1); var w: [row_words]u32 = undefined; @@ -360,7 +398,7 @@ pub const Ripple = struct { for (windows, chains) |w, *c| { if (w.held != 0) return error.NoHeldDrafts; // no draft head: every draft comes from the host if (w.parents != null) return error.ChainsOnly; - if (w.masks.len != 0) return error.StructuresUnsupported; + if (w.masks.len != 0 and w.masks.len != w.rows() * maskWords(v)) return error.InvalidGrammarMasks; const l = try x.laneOf(w.stream); if (w.rows() > max_window) return error.WindowTooWide; if (total + w.rows() > @min(round_rows, x.m.round_rows)) return error.RoundTooWide; @@ -382,7 +420,9 @@ pub const Ripple = struct { const l = x.lanes.getPtr(w.stream).?; const n = l.rows.items.len; const logits = x.m.b.rows + at * v * 2; - try x.drawRows(l, logits, n, w.positions[0], x.tokAt(ring + at), i); + // a grammar's rows are drawn from a copy; the logprob rows below read the model's + const from = if (w.masks.len == 0) logits else try x.maskedRows(logits, n, w.masks, at); + try x.drawRows(l, from, n, w.positions[0], x.tokAt(ring + at), i); if (o.rows.len > 0) { try x.draws.logprobRows(x.m.s, logits, v, x.tokAt(ring + at), w.stream.logprobs.?, false, x.words.ptr + at * row_words * 4, n); scored = true; @@ -434,6 +474,25 @@ pub const Ripple = struct { fn release(ptr: *anyopaque, s: *Stream) void { self(ptr).dropLane(s); } + + /// A drafter's tapped layers, before any stream: each chunk and round writes their rows into its slot's ring after. + fn prepareFeatures(ptr: *anyopaque, taps: []const u32) anyerror!void { + const x = self(ptr); + if (x.lanes.count() != 0) return error.TapsAfterStreams; + try x.m.setTaps(taps); + } + + /// Rows [start, start + count) of a stream's tap ring as Qwen's target gives them; the newest tap_rows are held. + fn features(ptr: *anyopaque, s: *Stream, taps: []const u32, start: u64, count: u32) anyerror!be.Features { + const x = self(ptr); + if (taps.len != x.m.n_taps or !std.mem.eql(u32, taps, x.m.taps[0..x.m.n_taps])) return error.TapsMismatch; + const l = try x.laneOf(s); + // `offset` is the position `start`; the drafter reads position p at row p % tap_rows of the slot's ring + const at = x.m.tapRing(l.slot) orelse return error.NoTaps; + const held_from = l.hi -| fwd.tap_rows; + if (count == 0 or start + count > l.hi or start + count <= held_from) return error.RowsNotHeld; + return .{ .buffer = at, .offset = start, .rows = count, .row_bytes = @intCast(x.m.tapRowBytes()), .space = .device, .dtype = .bf16 }; + } }; test "ricursive cuda backend: the verify reserve past a reply; positions opened for a context" { @@ -451,7 +510,7 @@ test "ricursive cuda backend: windows of 16 rows, a stream a slot, rows a round" var m: fwd.Model = undefined; m.round_rows = round_rows; m.arena.slots = 6; - const x: Ripple = .{ .gpa = std.testing.allocator, .d = undefined, .m = &m, .tok = undefined, .meta = undefined, .words = undefined, .picks = undefined, .slot_bufs = undefined, .sample = undefined, .draws = undefined, .free = &.{} }; + const x: Ripple = .{ .gpa = std.testing.allocator, .d = undefined, .m = &m, .tok = undefined, .meta = undefined, .words = undefined, .picks = undefined, .slot_bufs = undefined, .sample = undefined, .draws = undefined, .mask_fn = undefined, .free = &.{} }; const f = x.facts(); try std.testing.expectEqual(@as(u32, 16), f.exact_width); try std.testing.expectEqual(@as(u32, 6), f.max_streams); @@ -461,6 +520,44 @@ test "ricursive cuda backend: windows of 16 rows, a stream a slot, rows a round" std.testing.refAllDecls(Ripple); } +test "ricursive cuda backend: a grammar row's words cover the vocabulary, a bit a token" { + try std.testing.expectEqual(@as(usize, 3136), Ripple.maskWords(100352)); // the release's logits, 32 tokens a word + try std.testing.expectEqual(@as(usize, 1), Ripple.maskWords(1)); + try std.testing.expectEqual(@as(usize, 2), Ripple.maskWords(33)); + // the grammar scratch holds a round's rows, then their bits: the bits start at a whole 16 bytes + try std.testing.expectEqual(@as(usize, 0), (round_rows * 100352 * 2) % 16); +} + +test "ricursive cuda backend: features name a stream's held tap rows by position; taps before streams" { + const a = std.testing.allocator; + var m: fwd.Model = undefined; + m.c.hidden = 5120; + m.n_taps = 0; + m.tap = null; + var x: Ripple = .{ .gpa = a, .d = undefined, .m = &m, .tok = undefined, .meta = undefined, .words = undefined, .picks = undefined, .slot_bufs = undefined, .sample = undefined, .draws = undefined, .mask_fn = undefined, .free = &.{} }; + defer x.lanes.deinit(a); + var s: Stream = undefined; + const taps = [_]u32{ 1, 20, 39, 58, 77 }; + try std.testing.expectError(error.TapsMismatch, Ripple.features(&x, &s, &taps, 0, 1)); + m.taps[0..5].* = taps; + m.n_taps = 5; + try std.testing.expectError(error.UnknownStream, Ripple.features(&x, &s, &taps, 0, 1)); + try x.lanes.put(a, &s, .{ .slot = 2, .last = 0, .rule = 0, .hi = 3000 }); + try std.testing.expectError(error.NoTaps, Ripple.features(&x, &s, &taps, 2990, 10)); + m.tap = .{ .d = undefined, .ptr = 1 << 20, .len = 0 }; // features reads only the address + const f = try Ripple.features(&x, &s, &taps, 2990, 10); + try std.testing.expectEqual(@as(u64, (1 << 20) + 2 * fwd.tap_rows * 51200), f.buffer); + try std.testing.expectEqual(@as(u64, 2990), f.offset); // a position: the drafter reads row 2990 % 2064 + try std.testing.expectEqual(@as(u32, 51200), f.row_bytes); + try std.testing.expect(f.space == .device and f.dtype == .bf16 and f.rows == 10); + _ = try Ripple.features(&x, &s, &taps, 900, 2048); // the newest rows of a chunk that reaches past the ring's oldest + try std.testing.expectError(error.RowsNotHeld, Ripple.features(&x, &s, &taps, 2995, 10)); // past what was written + try std.testing.expectError(error.RowsNotHeld, Ripple.features(&x, &s, &taps, 0, 936)); // every row overwritten + try std.testing.expectError(error.RowsNotHeld, Ripple.features(&x, &s, &taps, 2990, 0)); + try std.testing.expectError(error.TapsMismatch, Ripple.features(&x, &s, &.{ 1, 20, 39, 58, 76 }, 2990, 10)); + try std.testing.expectError(error.TapsAfterStreams, Ripple.prepareFeatures(&x, &taps)); +} + test { _ = snap; } diff --git a/zig/src/families/ricursive/cuda_dflash2.zig b/zig/src/families/ricursive/cuda_dflash2.zig new file mode 100644 index 00000000000..e33758fec51 --- /dev/null +++ b/zig/src/families/ricursive/cuda_dflash2.zig @@ -0,0 +1,599 @@ +//! Ripple's DFlash2 drafter on CUDA: dflash2.zig's op order over the target's taps, streams batched in 16-row blocks. +const std = @import("std"); +const cuda = @import("cuda"); +const lanes = @import("lanes"); +const spec = @import("dflash2_spec.zig"); +const dw = @import("cuda_dflash2_weights.zig"); +const dk = @import("cuda_dflash2_kernels.zig"); +const da = @import("cuda_dflash2_attn.zig"); +const sel = @import("cuda_dflash2_select.zig"); +const fwd = @import("cuda_model.zig"); +const be = @import("cuda_backend.zig"); +const cfg = @import("config.zig"); + +const dr = lanes.drafter; +const Stream = lanes.Stream; +const Cost = lanes.config.Cost; +const DeviceBuffer = cuda.DeviceBuffer; +const Weight = cuda.qmmf.Weight; + +pub const Config = spec.Config; +const dcfg = @import("cuda_dflash2_config.zig"); // the qualified config and the kernels' gate +pub const gate = dcfg.gate; +pub const readConfig = dcfg.readConfig; + +/// Context rows one absorb pass projects (dflash2.zig's absorb_rows: a prompt chunk's). +pub const absorb_rows = fwd.prompt_rows; +/// Rows a stream's absorb may read from the tap ring: a chunk's (the ring's other 16 hold a verify window). +const held_rows = fwd.prompt_rows; +/// Row runs an absorb pass takes (a stream's rows split at the tap ring's wrap). +const max_pieces = 64; +/// The target's verify windows the sweep times: 1 to 16 rows. +const windows = be.max_window; +const head_dim = dk.head_dim; + +/// Device bytes one stream's rings take: every layer's K and V, ring(l) rows of kv_heads x 128 bf16 each. +pub fn laneBytes(c: *const Config) usize { + var n: usize = 0; + for (0..c.layers) |l| n += @as(usize, c.ring(l)) * c.kv_heads * head_dim * 2 * 2; + return n; +} + +/// Device bytes a stream adds to the target's: its drafter rings and its slot's tap ring (A's, 5 taps). +pub fn streamBytes(c: *const Config, target: cfg.Config) usize { + return laneBytes(c) + fwd.tapBytes(target, spec.max_taps, 1); +} + +/// The scratch's regions: a batch of `streams` blocks, an absorb pass, the segment tables. +const Bufs = struct { + ids: u64 = 0, // u32 [R]: the blocks' tokens, then the sweep's draws + resid: u64 = 0, // bf16 [R, H] + x: u64 = 0, + xc: u64 = 0, + y: u64 = 0, + yc: u64 = 0, + dyn: u64 = 0, // bf16 [R, dyn]: a conv's coefficients + qkv: u64 = 0, // bf16 [R, q + 2 kv] + q: u64 = 0, // bf16 [R, heads, 128]: prep's queries + att: u64 = 0, // bf16 [R, heads, 128]: the attention + gu: u64 = 0, // bf16 [R, 2 ffn] + act: u64 = 0, // bf16 [R, ffn] + logits: u64 = 0, // bf16 [R, vocab] + pm: u64 = 0, // the attention's partials (D's Scratch) + pl: u64 = 0, + po: u64 = 0, + tv: u64 = 0, // the top-32's chunk bests + ti: u64 = 0, + out: u64 = 0, // f32 [R, 32] values, u32 [R, 32] ids, bf16 [R, rank] hidden: one download + part: u64 = 0, // the lane matmul's slice partials + inv: u64 = 0, // f32 [64]: RoPE's inverse frequencies + psegs: u64 = 0, // C's Segment [layers][streams]: a block's prep + asegs: u64 = 0, // D's Segment [layers][streams]: a block's attention + fcx: u64 = 0, // bf16 [A, H]: fc of the tap rows + hctx: u64 = 0, // bf16 [A, H]: normed + kv: u64 = 0, // bf16 [A, 2 kv] + csegs: u64 = 0, // C's Segment [layers][max_pieces]: an absorb's prep +}; + +/// The widest span a layer attends over (the global layer's when there is one). +fn widest(c: *const Config) usize { + var s: usize = 0; + for (0..c.layers) |l| s = @max(s, c.span(l)); + return s; +} + +/// Slice partials the lane matmul needs at a block batch's rows for every projection it runs (0 when none reduces). +fn partBytes(c: *const Config, vocab: usize, clusters: bool, streams: usize) usize { + const h: usize = c.hidden; + const qw = @as(usize, c.heads) * head_dim; + const kvw = @as(usize, c.kv_heads) * head_dim; + const shapes = [_][2]usize{ .{ qw + 2 * kvw, h }, .{ h, qw }, .{ 2 * @as(usize, c.ffn), h }, .{ h, c.ffn }, .{ c.dyn(), h }, .{ vocab, h }, .{ c.rank, h } }; + var most: usize = 0; + for (1..streams + 1) |s| for (shapes) |nk| { + const rows = s * c.block; + const p = cuda.qmmf.planFor(rows, cuda.modelopt.bf16Weight(0, nk[0], nk[1]), clusters); + if (p.reduce) most = @max(most, @as(usize, p.sk) * rows * nk[0] * 4); + }; + return most; +} + +/// The scratch for `streams` blocks at `base` (0: only its bytes), every region on a 256-byte boundary. +fn place(c: *const Config, vocab: usize, clusters: bool, streams: usize, base: u64, b: *Bufs) usize { + const r = streams * c.block; + const a: usize = absorb_rows; + const h: usize = c.hidden; + const qw = @as(usize, c.heads) * head_dim; + const kvw = @as(usize, c.kv_heads) * head_dim; + const attn = da.scratch(.{ .q = 0, .segs = 0, .out = 0, .pm = 0, .pl = 0, .po = 0, .streams = streams, .span = widest(c), .heads = c.heads, .kv_heads = c.kv_heads }); + const tops = da.top32Scratch(.{ .logits = 0, .stride = vocab, .n = vocab, .rows = r, .vals = 0, .ids = 0, .part_vals = 0, .part_ids = 0 }); + const sizes = [_]struct { *u64, usize }{ + .{ &b.ids, r * 4 }, .{ &b.resid, r * h * 2 }, .{ &b.x, r * h * 2 }, + .{ &b.xc, r * h * 2 }, .{ &b.y, r * h * 2 }, .{ &b.yc, r * h * 2 }, + .{ &b.dyn, r * c.dyn() * 2 }, .{ &b.qkv, r * (qw + 2 * kvw) * 2 }, .{ &b.q, r * qw * 2 }, + .{ &b.att, r * qw * 2 }, .{ &b.gu, r * 2 * @as(usize, c.ffn) * 2 }, .{ &b.act, r * @as(usize, c.ffn) * 2 }, + .{ &b.logits, r * vocab * 2 }, .{ &b.pm, attn.max }, .{ &b.pl, attn.max }, + .{ &b.po, attn.values }, .{ &b.tv, tops }, .{ &b.ti, tops }, + .{ &b.out, r * da.top * 8 + r * @as(usize, c.rank) * 2 }, .{ &b.part, partBytes(c, vocab, clusters, streams) }, .{ &b.inv, head_dim / 2 * 4 }, + .{ &b.psegs, c.layers * streams * @sizeOf(dk.Segment) }, .{ &b.asegs, c.layers * streams * @sizeOf(da.Segment) }, .{ &b.fcx, a * h * 2 }, + .{ &b.hctx, a * h * 2 }, .{ &b.kv, a * 2 * kvw * 2 }, .{ &b.csegs, c.layers * max_pieces * @sizeOf(dk.Segment) }, + }; + var at: usize = 0; + for (sizes) |s| { + at = std.mem.alignForward(usize, at, 256); + s[0].* = base + at; + at += s[1]; + } + return at; +} + +/// Device bytes the runtime takes for streams beside its weights: the scratch, each stream's rings and its tap ring. +pub fn runBytes(c: *const Config, target: cfg.Config, clusters: bool, streams: usize) usize { + var b: Bufs = .{}; + return place(c, target.vocab, clusters, streams, 0, &b) + streams * streamBytes(c, target); +} + +/// Device bytes a drafter over `streams` streams takes: B's weights and runBytes (admission's, decision 8). +pub fn openBytes(c: *const Config, target: cfg.Config, clusters: bool, streams: usize) usize { + return dw.deviceBytes(c.*) + runBytes(c, target, clusters, streams); +} + +/// A stream's drafter context: its rings, the positions [from, end) absorbed, its held drafts. +const Lane = struct { + ring: DeviceBuffer, + from: u64 = 0, + end: u64 = 0, + held: [sel.max_slots]u32 = undefined, + held_len: usize = 0, +}; + +/// One absorb run: a stream's rows [pos, pos + rows) at batch row `begin`. +const Piece = struct { lane: *const Lane, begin: usize, pos: u64 }; + +pub const Drafter = struct { + gpa: std.mem.Allocator, + io: std.Io, + m: *const fwd.Model, + w: dw.Weights, + c: Config, + gk: dk.Kernels, + ak: da.Kernels, + clusters: bool, + /// Bytes from a ring's base to each layer's K ring (V follows K a ring further, as D reads it). + layer_at: [spec.max_layers]usize = @splat(0), + lanes: std.AutoHashMapUnmanaged(*Stream, *Lane) = .empty, + pool: std.ArrayList(*Lane) = .empty, + made: usize = 0, + streams: usize = 0, // the blocks the scratch holds + scratch: DeviceBuffer, + b: Bufs = .{}, + host: Host = .{}, + pieces: std.ArrayList(Piece) = .empty, + rows: usize = 0, // the absorb pass's rows so far + step_ms: f64 = 0, + costs: [windows]Cost = undefined, + n_costs: usize = 0, + shared: [windows]Cost = undefined, // every stream's slot w rows: by total rows + n_shared: usize = 0, + + /// Host staging for `streams` blocks. + const Host = struct { + ids: []u32 = &.{}, + psegs: []dk.Segment = &.{}, + asegs: []da.Segment = &.{}, + csegs: []dk.Segment = &.{}, + out: []align(16) u8 = &.{}, + lanes: []*Lane = &.{}, + pending: []u32 = &.{}, + anchors: []u64 = &.{}, + + fn free(h: *Host, gpa: std.mem.Allocator) void { + gpa.free(h.ids); + gpa.free(h.psegs); + gpa.free(h.asegs); + gpa.free(h.csegs); + gpa.free(h.out); + gpa.free(h.lanes); + gpa.free(h.pending); + gpa.free(h.anchors); + h.* = .{}; + } + }; + + /// The drafter in `dir` (B's load: the qualified config, every tensor checked) over target `m`, for `streams`. + pub fn open(gpa: std.mem.Allocator, io: std.Io, m: *const fwd.Model, dir: []const u8, streams: usize) !*Drafter { + const w = try dw.load(gpa, io, m.d, dir, &m.c); + return init(gpa, io, m, w, streams); + } + + /// The runtime over `w` (taken; freed on failure): kernels, scratch and rings for `streams` streams, a block timed. + pub fn init(gpa: std.mem.Allocator, io: std.Io, m: *const fwd.Model, weights: dw.Weights, streams: usize) !*Drafter { + var w = weights; + errdefer w.deinit(); + const c = w.config; + try gate(&c); + if (c.vocab != m.c.vocab or c.hidden != m.c.hidden or c.mask >= c.vocab) return error.UnqualifiedRippleDFlash2; + if (streams == 0 or streams * c.block > 65535) return error.UnsupportedRicursiveDFlash2Shape; + const d = try gpa.create(Drafter); + errdefer gpa.destroy(d); + d.* = .{ .gpa = gpa, .io = io, .m = m, .w = w, .c = c, .gk = undefined, .ak = undefined, .clusters = m.k.lane.clusters, .scratch = undefined }; + var at: usize = 0; + for (0..c.layers) |l| { + d.layer_at[l] = at; + at += @as(usize, c.ring(l)) * c.kv_heads * head_dim * 2 * 2; + } + d.gk = try dk.Kernels.load(m.d); + errdefer d.gk.unload(); + d.ak = try da.Kernels.load(m.d); + errdefer d.ak.unload(); + d.scratch = try DeviceBuffer.alloc(m.d, 0); + errdefer d.freeRun(); + try d.reserve(@intCast(streams)); + try d.warm(); + return d; + } + + /// Lanes, scratch and staging. + fn freeRun(d: *Drafter) void { + d.m.s.synchronize() catch {}; + var it = d.lanes.valueIterator(); + while (it.next()) |l| d.dropLane(l.*); + d.lanes.deinit(d.gpa); + for (d.pool.items) |l| d.dropLane(l); + d.pool.deinit(d.gpa); + d.pieces.deinit(d.gpa); + d.scratch.free(); + d.host.free(d.gpa); + } + + pub fn deinit(d: *Drafter) void { + d.freeRun(); + d.ak.unload(); + d.gk.unload(); + d.w.deinit(); + d.gpa.destroy(d); + } + + /// Scratch for `streams` blocks and a lane for each (the target's slots at most): made once, at open. + pub fn reserve(d: *Drafter, asked: u32) !void { + const streams = @min(@as(usize, asked), d.m.arena.slots); + if (streams > d.streams) { + d.m.s.synchronize() catch {}; + var b: Bufs = .{}; + var next = try DeviceBuffer.alloc(d.m.d, place(&d.c, d.c.vocab, d.clusters, streams, 0, &b)); + errdefer next.free(); + _ = place(&d.c, d.c.vocab, d.clusters, streams, next.ptr, &b); + const inv = dk.inverseFrequencies(d.c.theta); + try cuda.copy_source.enqueue(d.m.d, b.inv, std.mem.sliceAsBytes(&inv), d.m.s); + var h: Host = .{}; + errdefer h.free(d.gpa); + const r = streams * d.c.block; + h.ids = try d.gpa.alloc(u32, r); + h.psegs = try d.gpa.alloc(dk.Segment, d.c.layers * streams); + h.asegs = try d.gpa.alloc(da.Segment, d.c.layers * streams); + h.csegs = try d.gpa.alloc(dk.Segment, d.c.layers * max_pieces); + h.out = try d.gpa.alignedAlloc(u8, .@"16", r * da.top * 8 + r * @as(usize, d.c.rank) * 2); + h.lanes = try d.gpa.alloc(*Lane, streams); + h.pending = try d.gpa.alloc(u32, streams); + h.anchors = try d.gpa.alloc(u64, streams); + try d.pieces.ensureTotalCapacity(d.gpa, max_pieces); + d.scratch.free(); + d.scratch = next; + d.b = b; + d.host.free(d.gpa); + d.host = h; + d.streams = streams; + } + try d.pool.ensureTotalCapacity(d.gpa, streams); + while (d.made < streams) { + var ring = try DeviceBuffer.alloc(d.m.d, laneBytes(&d.c)); + errdefer ring.free(); + try ring.fill8(0, d.m.s.handle); // a key read past a window's end reads a written one, never stale NaN + const l = try d.gpa.create(Lane); + l.* = .{ .ring = ring }; + d.pool.appendAssumeCapacity(l); + d.made += 1; + } + } + + fn dropLane(d: *Drafter, l: *Lane) void { + l.ring.free(); + d.gpa.destroy(l); + } + + fn ringK(d: *const Drafter, l: *const Lane, layer: usize) u64 { + return l.ring.ptr + d.layer_at[layer]; + } + + fn ringV(d: *const Drafter, l: *const Lane, layer: usize) u64 { + return d.ringK(l, layer) + @as(usize, d.c.ring(layer)) * d.c.kv_heads * head_dim * 2; + } + + pub fn drafter(d: *Drafter) dr.Drafter { + return .{ .kind = "DFlash2", .ptr = d, .vtable = &.{ .taps = tapsFn, .facts = factsFn, .open = openFn, .absorb = absorbFn, .hold = holdFn, .held = heldFn, .release = releaseFn } }; + } + + fn cast(ptr: *anyopaque) *Drafter { + return @ptrCast(@alignCast(ptr)); + } + + fn tapsFn(ptr: *anyopaque) []const u32 { + return &cast(ptr).c.taps; + } + + /// Chains of up to block - 1 drafts, a round's streams one batch; the windows' costs once the sweep has run. + pub fn facts(d: *const Drafter) dr.Facts { + const costs = d.costs[0..d.n_costs]; + return .{ .depth = d.c.block - 1, .step_ms = d.step_ms, .plain_guard = true, .batched = true, .stream_bytes = streamBytes(&d.c, d.m.c), .window_costs = costs, .lane_costs = costs, .shared_costs = d.shared[0..d.n_shared] }; + } + + fn factsFn(ptr: *anyopaque) dr.Facts { + return cast(ptr).facts(); + } + + fn openFn(ptr: *anyopaque, s: *Stream) anyerror!void { + const d = cast(ptr); + if (d.lanes.contains(s)) return error.DraftStreamOpen; + if (d.pool.items.len == 0) try d.reserve(@intCast(d.made + 1)); + const l = d.pool.pop() orelse return error.DraftStreamsPastReserve; + errdefer d.pool.appendAssumeCapacity(l); + l.* = .{ .ring = l.ring }; + try d.lanes.put(d.gpa, s, l); + } + + fn releaseFn(ptr: *anyopaque, s: *Stream) void { + const d = cast(ptr); + if (d.lanes.fetchRemove(s)) |e| d.pool.appendAssumeCapacity(e.value); + } + + fn heldFn(ptr: *anyopaque, streams: []const *Stream, out: []const []u32) anyerror!void { + const d = cast(ptr); + for (streams, out) |s, o| { + const l = d.lanes.get(s) orelse return error.DraftStreamUnknown; + if (o.len > l.held_len) return error.DraftHeldFewer; + @memcpy(o, l.held[0..o.len]); + } + } + + /// Rows [start, start + rows) replace the context from `start`; prompt rows past the longest span are skipped. + fn absorbFn(ptr: *anyopaque, items: []const dr.Absorb) anyerror!void { + const d = cast(ptr); + const c = &d.c; + const width: usize = spec.max_taps * @as(usize, c.hidden) * 2; + for (items) |it| { + const l = d.lanes.get(it.stream) orelse return error.DraftStreamUnknown; + if (it.rows != null) return error.DraftTreesUnsupported; // chain verify only (decision 2) + const f = it.features; + if (f.space != .device or f.dtype != .bf16 or f.row_bytes != width) return error.DraftFeaturesUnsupported; + if (it.start > l.end or l.end == 0) l.from = it.start; // the rows before it were restored, not absorbed + const end = it.start + f.rows; + var keep_from = if (it.prompt) @max(it.start, it.stream.prompt_len -| (spec.global_window + c.block)) else it.start; + // a whole prompt pass leaves only its newest rows in the tap ring: older ones are not absorbed + if (f.rows > held_rows) keep_from = @max(keep_from, end - held_rows); + if (keep_from > it.start) l.from = @max(l.from, keep_from); // a long prompt's oldest rows: never absorbed + var at: u64 = keep_from; + while (at < end) { + const row: usize = @intCast((f.offset + (at - it.start)) % fwd.tap_rows); + const n: usize = @intCast(@min(end - at, fwd.tap_rows - row, absorb_rows)); + if (d.rows + n > absorb_rows or d.pieces.items.len == max_pieces) try d.flush(); + // fc of the piece's tap rows straight from the ring, into the pass's rows + try d.m.k.prompt.matmulOut(d.m.s, f.buffer + row * width, width / 2, n, d.w.fc, d.b.fcx + d.rows * c.hidden * 2, .bf16); + d.pieces.appendAssumeCapacity(.{ .lane = l, .begin = d.rows, .pos = at }); + d.rows += n; + at += n; + } + l.end = end; + l.held_len = 0; + } + try d.flush(); + } + + /// The pass's rows: fc's rows normed, then each layer's k and v, k normed and rotated, into every piece's ring. + fn flush(d: *Drafter) !void { + const rows = d.rows; + if (rows == 0) return; + const c = &d.c; + const m = d.m; + const ps = d.pieces.items; + try dk.norm(&d.gk, m.s, .{ .resid = d.b.fcx, .w = d.w.hidden_norm, .x = d.b.hctx, .rows = rows, .width = c.hidden, .eps = c.eps }); + for (0..c.layers) |i| { + const segs = d.host.csegs[i * ps.len ..][0..ps.len]; + for (segs, ps) |*sg, p| sg.* = .{ .k = d.ringK(p.lane, i), .v = d.ringV(p.lane, i), .begin = @intCast(p.begin), .pos = @intCast(p.pos) }; + try dk.checkSegments(segs, rows, c.ring(i)); + } + try cuda.copy_source.enqueue(m.d, d.b.csegs, std.mem.sliceAsBytes(d.host.csegs[0 .. c.layers * ps.len]), m.s); + for (0..c.layers) |i| { + const L = &d.w.layers[i]; + try m.k.prompt.matmulOut(m.s, d.b.hctx, c.hidden, rows, L.kv, d.b.kv, .bf16); + try dk.prep(&d.gk, m.s, .{ .x = d.b.kv, .qw = L.q_norm, .kw = L.k_norm, .inv = d.b.inv, .segs = d.b.csegs + i * ps.len * @sizeOf(dk.Segment), .streams = ps.len, .q = 0, .rows = rows, .kv_heads = c.kv_heads, .at = dk.Layout.context(c.kv_heads), .ring = c.ring(i), .rope = c.rope[i], .eps = c.eps }); + } + d.pieces.clearRetainingCapacity(); + d.rows = 0; + } + + /// y = x W^T over a batch's rows: the lane matmul, as the target's verify rows run it. + fn lane(d: *const Drafter, x: u64, rows: usize, w: Weight, y: u64) !void { + try d.m.k.lane.matmulOut(d.m.s, x, w.k, rows, w, y, .bf16, d.b.part); + } + + /// x through `cv`'s prepare: its coefficients into dyn, side 0 into xc. + fn convPrepare(d: *const Drafter, cv: dw.Conv, rows: usize) !void { + try d.lane(d.b.x, rows, cv.proj, d.b.dyn); + try d.conv(cv, d.b.x, d.b.xc, rows, 0); + } + + fn conv(d: *const Drafter, cv: dw.Conv, in: u64, out: u64, rows: usize, side: usize) !void { + const c = &d.c; + try dk.conv(&d.gk, d.m.s, .{ .x = in, .dyn = d.b.dyn, .base = cv.base, .y = out, .rows = rows, .width = c.hidden, .block = c.block, .groups = c.hidden / c.group, .side = side, .taps = c.conv }); + } + + fn norm(d: *const Drafter, branch: u64, w: u64, rows: usize) !void { + try dk.norm(&d.gk, d.m.s, .{ .resid = d.b.resid, .branch = branch, .w = w, .x = d.b.x, .rows = rows, .width = d.c.hidden, .eps = d.c.eps }); + } + + /// Each stream's block (pending, 15 masks) as encodeBlock, stream j at rows 16 j: each row's top 32 and selector. + fn block(d: *Drafter, ls: []const *Lane, pending: []const u32, anchors: []const u64) !void { + const c = &d.c; + const m = d.m; + const s = m.s; + const nb: usize = c.block; + const rows = ls.len * nb; + const h: usize = c.hidden; + for (ls, pending, 0..) |_, p, j| { + d.host.ids[j * nb] = p; + @memset(d.host.ids[j * nb + 1 ..][0 .. nb - 1], c.mask); + } + for (0..c.layers) |i| for (ls, anchors, 0..) |l, a, j| { + d.host.psegs[i * ls.len + j] = .{ .k = d.ringK(l, i), .v = d.ringV(l, i), .begin = @intCast(j * nb), .pos = @intCast(a) }; + d.host.asegs[i * ls.len + j] = .{ .ring = d.ringK(l, i), .anchor = @intCast(a), .from = @intCast(l.from), .span = @intCast(c.span(i)), .rows = @intCast(c.ring(i)) }; + }; + for (0..c.layers) |i| try dk.checkSegments(d.host.psegs[i * ls.len ..][0..ls.len], rows, c.ring(i)); + try cuda.copy_source.enqueue(m.d, d.b.ids, std.mem.sliceAsBytes(d.host.ids[0..rows]), s); + try cuda.copy_source.enqueue(m.d, d.b.psegs, std.mem.sliceAsBytes(d.host.psegs[0 .. c.layers * ls.len]), s); + try cuda.copy_source.enqueue(m.d, d.b.asegs, std.mem.sliceAsBytes(d.host.asegs[0 .. c.layers * ls.len]), s); + try dk.embed(&m.k.glue, s, d.b.ids, m.w.embed, d.b.resid, d.b.x, rows, h); + for (0..c.layers) |i| { + const L = &d.w.layers[i]; + // input norm (the residual takes the last sublayer's output first, from the second layer on) + try d.norm(if (i > 0) d.b.yc else 0, L.in_norm, rows); + try d.convPrepare(L.attn_conv, rows); + try d.lane(d.b.xc, rows, L.qkv, d.b.qkv); + try dk.prep(&d.gk, s, .{ .x = d.b.qkv, .qw = L.q_norm, .kw = L.k_norm, .inv = d.b.inv, .segs = d.b.psegs + i * ls.len * @sizeOf(dk.Segment), .streams = ls.len, .q = d.b.q, .rows = rows, .kv_heads = c.kv_heads, .at = dk.Layout.block(c.heads, c.kv_heads), .ring = c.ring(i), .rope = c.rope[i], .eps = c.eps }); + try da.attention(&d.ak, s, .{ .q = d.b.q, .segs = d.b.asegs + i * ls.len * @sizeOf(da.Segment), .out = d.b.att, .pm = d.b.pm, .pl = d.b.pl, .po = d.b.po, .streams = ls.len, .span = c.span(i), .heads = c.heads, .kv_heads = c.kv_heads }); + try d.lane(d.b.att, rows, L.o, d.b.y); + // the attention conv's finish (side 1, its prepare's coefficients), then the post-attention norm + try d.conv(L.attn_conv, d.b.y, d.b.yc, rows, 1); + try d.norm(d.b.yc, L.post_norm, rows); + try d.convPrepare(L.mlp_conv, rows); + try d.lane(d.b.xc, rows, L.gate_up, d.b.gu); + try dk.silu(&d.gk, s, d.b.gu, d.b.act, rows, c.ffn); + try d.lane(d.b.act, rows, L.down, d.b.y); + try d.conv(L.mlp_conv, d.b.y, d.b.yc, rows, 1); + } + try d.norm(d.b.yc, d.w.norm, rows); + // every row: the target's head, its top 32, the selector's projection (rows 1-15 of a block are walked) + const vals = d.b.out; + const ids = vals + rows * da.top * 4; + const hid = ids + rows * da.top * 4; + try d.lane(d.b.x, rows, m.w.head, d.b.logits); + try d.lane(d.b.x, rows, d.w.hproj, hid); + try da.top32(&d.ak, s, .{ .logits = d.b.logits, .stride = c.vocab, .n = c.vocab, .rows = rows, .vals = vals, .ids = ids, .part_vals = d.b.tv, .part_ids = d.b.ti }); + } + + /// Each stream's `depth` drafts after `pending` at `position`: one batch of blocks, then B's walk on the host. + fn holdFn(ptr: *anyopaque, items: []const dr.Hold) anyerror!void { + const d = cast(ptr); + const c = &d.c; + if (items.len == 0) return; + if (items.len > d.streams) return error.DraftStreamsPastReserve; + const ls = d.host.lanes[0..items.len]; + for (items, ls, d.host.pending[0..items.len], d.host.anchors[0..items.len]) |it, *l, *p, *a| { + l.* = d.lanes.get(it.stream) orelse return error.DraftStreamUnknown; + if (it.depth == 0 or it.depth > c.block - 1 or it.position == 0) return error.DraftDepth; + const anchor = it.position - 1; + if (l.*.end != anchor) return error.DraftContextGap; + p.* = it.pending; + a.* = anchor; + } + try d.block(ls, d.host.pending[0..items.len], d.host.anchors[0..items.len]); + const rows = items.len * c.block; + const rank: usize = c.rank; + const out = d.host.out[0 .. rows * da.top * 8 + rows * rank * 2]; + try d.m.download(d.b.out, out); + const vals = std.mem.bytesAsSlice(f32, out[0 .. rows * da.top * 4]); + const ids = std.mem.bytesAsSlice(u32, out[rows * da.top * 4 ..][0 .. rows * da.top * 4]); + const hid = std.mem.bytesAsSlice(u16, out[rows * da.top * 8 ..]); + for (items, ls, 0..) |it, l, j| { + const r0 = j * c.block + 1; + const in: sel.Inputs = .{ .top = c.top, .rank = c.rank, .vocab = c.vocab, .values = @alignCast(vals[r0 * da.top ..]), .ids = @alignCast(ids[r0 * da.top ..]), .hidden = @alignCast(hid[r0 * rank ..]), .pred = d.w.pred, .succ = d.w.succ }; + // a row with no candidate (the Metal walk's id past the vocabulary) refuses, as holdFn does there + if (sel.walk(in, it.pending, l.held[0..it.depth]) < it.depth) return error.DraftNonfinite; + l.held_len = it.depth; + } + } + + /// The kernels' first launch, then a block timed on a free lane for the depth rule's price, as dflash2.zig's warm. + fn warm(d: *Drafter) !void { + const l = d.pool.items[0]; + const a = [_]u64{0}; + const p = [_]u32{0}; + const one = [_]*Lane{l}; + var ms: f64 = 0; + for (0..3) |run| { + const t0 = now(d.io); + try d.block(&one, &p, &a); + try d.m.s.synchronize(); + if (run == 2) ms = msSince(d.io, t0); + } + try l.ring.fill8(0, d.m.s.handle); + try d.m.s.synchronize(); + d.step_ms = ms / @as(f64, @floatFromInt(d.c.block - 1)); + } + + /// Verify windows of 1 to 16 rows timed on slot 0 before any stream (Qwen's sweep): median of 3, slot 0 reset. + pub fn timeWindows(d: *Drafter) !void { + if (d.lanes.count() != 0) return error.WindowsAfterStreams; + const m = d.m; + const ids: [windows]u32 = @splat(0); + for (1..windows + 1) |w| { + var ms: [3]f64 = undefined; + for (0..4) |run| { + const t0 = now(d.io); + try m.round(&.{.{ .slot = 0, .p0 = 0, .tokens = w }}, ids[0..w]); + try m.rowLogits(w); + try m.drawRows(w, d.b.ids); + try m.s.synchronize(); + if (run > 0) ms[run - 1] = msSince(d.io, t0); + } + std.mem.sort(f64, &ms, {}, std.sort.asc(f64)); + d.costs[w - 1] = .{ .width = @intCast(w), .ms = ms[1] }; + } + try m.reset(0, windows); + try m.s.synchronize(); + d.n_costs = windows; + std.log.info("Ripple DFlash2 on CUDA: windows of 1 and 16 rows in {d:.2} and {d:.2} ms, a draft {d:.3} ms ({d} streams a batch)", .{ d.costs[0].ms, d.costs[windows - 1].ms, d.step_ms, d.streams }); + } +}; + +pub fn now(io: std.Io) i96 { + return std.Io.Clock.awake.now(io).toNanoseconds(); +} + +pub fn msSince(io: std.Io, t0: i96) f64 { + return @as(f64, @floatFromInt(now(io) - t0)) / 1e6; +} + +const testing = std.testing; + +fn release() !Config { + const target = try cfg.parse(testing.allocator, @embedFile("fixtures/config.json")); + return spec.parse(testing.allocator, @embedFile("fixtures/dflash2_config.json"), &target); +} + +test "ricursive dflash2 cuda: the release's rings, a stream's bytes and the scratch at 1 and 8 streams" { + const c = try release(); + try gate(&c); + try testing.expectEqual(@as(usize, 136_839_168), laneBytes(&c)); // 4 x 4,224 + 16,512 rows of 8 x 128 K and V + const target = try cfg.parse(testing.allocator, @embedFile("fixtures/config.json")); + try testing.expectEqual(laneBytes(&c) + 105_676_800, streamBytes(&c, target)); + var b: Bufs = .{}; + const one = place(&c, c.vocab, true, 1, 0, &b); + const eight = place(&c, c.vocab, true, 8, 0, &b); + // the attention's partials (86.5 MB a stream at the global span) are most of it; the absorb pass is fixed + try testing.expect(one > 86_000_000 and one < 200_000_000); + try testing.expect(eight - one > 7 * 86_000_000 and eight - one < 7 * 100_000_000); + try testing.expectEqual(@as(usize, 0), partBytes(&c, c.vocab, true, 8)); // GB10's clusters: no lane reduce + try testing.expectEqual(dw.deviceBytes(c) + runBytes(&c, target, true, 8), openBytes(&c, target, true, 8)); + try testing.expectEqual(eight + 8 * streamBytes(&c, target), runBytes(&c, target, true, 8)); +} + +test "ricursive dflash2 cuda: the scratch's regions do not overlap and sit on 256-byte boundaries" { + const c = try release(); + var b: Bufs = .{}; + const total = place(&c, c.vocab, false, 3, 4096, &b); + var prev: u64 = 0; + inline for (@typeInfo(Bufs).@"struct".field_names) |name| { + const at = @field(b, name); + try testing.expect(at % 256 == 0 and at >= prev and at <= 4096 + total); + prev = at; + } +} diff --git a/zig/src/families/ricursive/cuda_dflash2_attn.zig b/zig/src/families/ricursive/cuda_dflash2_attn.zig new file mode 100644 index 00000000000..273f7b6f87b --- /dev/null +++ b/zig/src/families/ricursive/cuda_dflash2_attn.zig @@ -0,0 +1,271 @@ +//! Ripple's DFlash2 draft attention and top-32 on CUDA (ricursive_dflash2_attn.cu) at dflash2.metal's rounding points. + +const std = @import("std"); +const cuda = @import("cuda"); + +const Stream = cuda.Stream; +const Function = cuda.Function; + +pub const head_dim = 128; +/// Rows a stream's block holds (DFlash2's block size). +pub const block = 16; +/// Keys a partial covers: rc_df_vec's 128-key blocks. +pub const chunk = 128; +/// The released drafter's heads: 80 query heads over 8 key heads (a group of 10). +pub const heads = 80; +pub const kv_heads = 8; +/// The softmax scale, 1 / sqrt(128) in fp32 (dflash2.zig's). +pub const scale: f32 = 1.0 / @sqrt(@as(f32, head_dim)); +/// The sliding layers' window and the global (NoPE) layers'. +pub const sliding_span = 4096; +pub const global_span = 16384; + +/// tf_rcd_attn_part's and tf_rcd_attn_merge's __launch_bounds__: 8 warps. +pub const attn_threads = 256; +const warps = attn_threads / 32; +/// tf_rcd_attn_part's dynamic shared memory: a chunk's K and V of one key head in bf16 (64 KiB, opted into at load). +pub const part_shared = 2 * chunk * head_dim * 2; +/// rc_df_topk: 1,024 threads sort 2,048 values a chunk and keep 32. +pub const top_threads = 1024; +pub const top_chunk = 2048; +pub const top = 32; +/// The drafter's vocabulary: 49 chunks of 2,048. +pub const vocab = 100352; + +fn int(x: usize) c_int { + return @intCast(x); +} + +fn ceil(n: usize, d: usize) usize { + return (n + d - 1) / d; +} + +pub const Kernels = struct { + mod: cuda.Module, + attn_part: Function, + attn_merge: Function, + top32_part: Function, + top32_merge: Function, + + pub fn load(d: *const cuda.Driver) !Kernels { + if (!cuda.kernels.available) return error.BuiltWithoutKernels; + var mod = try cuda.Module.load(d, cuda.kernels.ricursive_dflash2_attn); + errdefer mod.unload(); + return .{ + .mod = mod, + .attn_part = try partFunction(mod, "tf_rcd_attn_part"), + .attn_merge = try mod.function("tf_rcd_attn_merge"), + .top32_part = try mod.function("tf_rcd_top32_part"), + .top32_merge = try mod.function("tf_rcd_top32_merge"), + }; + } + + pub fn unload(k: *Kernels) void { + k.mod.unload(); + k.* = undefined; + } +}; + +/// An attention partial of the image (the served one or a control), opted into its 64 KiB of dynamic shared memory. +pub fn partFunction(mod: cuda.Module, name: [:0]const u8) !Function { + const f = try mod.function(name); + try f.allowDynamicShared(part_shared); + return f; +} + +/// A stream's slice of a layer: ring [rows][8][128] K then V, p at row p % rows; block at anchor; lowest position from. +pub const Segment = extern struct { + ring: u64, + anchor: i32, + from: i32, + span: i32, + rows: i32, +}; + +/// A layer ring's rows for a window: the window and the block, to 128s (4,224 and 16,512 for the released windows). +pub fn ringRows(span: usize) usize { + return std.mem.alignForward(usize, span + block, chunk); +} + +/// The 128-key chunks a (row, head) holds partials for: a window plus the block, span + 15 keys, from any start. +pub fn chunksFor(span: usize) usize { + return ceil(span + block - 1, chunk) + 1; +} + +/// A layer's attention over streams: q, out [streams 16][heads][128] bf16; segs on the device; pm, pl, po partials. +pub const Attn = struct { + q: u64, + segs: u64, + out: u64, + pm: u64, + pl: u64, + po: u64, + streams: usize, + span: usize, + heads: usize = heads, + kv_heads: usize = kv_heads, + scale: f32 = scale, + + pub fn chunks(p: Attn) usize { + return chunksFor(p.span); + } +}; + +/// The partials' bytes: pm and pl each `max`, po `values`. +pub const Scratch = struct { max: usize, values: usize }; + +pub fn scratch(p: Attn) Scratch { + const slots = p.streams * p.heads * block * p.chunks(); + return .{ .max = slots * 4, .values = slots * head_dim * 4 }; +} + +/// The kernels' shapes: whole groups, grids in CUDA's limits, int32 indices; the caller keeps segs in span and ring. +pub fn admit(p: Attn) !void { + if (p.kv_heads == 0 or p.heads == 0 or p.heads % p.kv_heads != 0) return error.AttnShape; + if (p.streams > 65535 or p.chunks() > 65535 or p.span == 0 or p.span > std.math.maxInt(i32) / 2) return error.AttnShape; + if (p.streams * block * p.heads > std.math.maxInt(i32)) return error.AttnShape; +} + +/// tf_rcd_attn_part: a block a (key head, stream, chunk). +pub fn partGrid(p: Attn) cuda.Dim3 { + return .{ .x = @intCast(p.kv_heads), .y = @intCast(p.streams), .z = @intCast(p.chunks()) }; +} + +/// tf_rcd_attn_merge: a warp a (row, head), 8 a block. +pub fn mergeGrid(p: Attn) cuda.Dim3 { + return .{ .x = @intCast(ceil(p.streams * block * p.heads, warps)), .y = 1, .z = 1 }; +} + +pub fn attention(k: *const Kernels, s: Stream, p: Attn) !void { + return attentionVia(k.attn_part, k.attn_merge, s, p); +} + +/// The two launches on `part` (opted into part_shared) and `merge`: the served kernels or a control in their place. +pub fn attentionVia(part: Function, merge: Function, s: Stream, p: Attn) !void { + if (p.streams == 0) return; + try partVia(part, s, p); + const cap = int(p.chunks()); + var m: cuda.Args = .{}; + for ([_]u64{ p.pm, p.pl, p.po, p.out }) |v| m.add(v); + m.add(int(p.streams * block)); + m.add(int(p.heads)); + m.add(cap); + try cuda.launch.launch(merge, .{ .grid = mergeGrid(p), .block = .{ .x = attn_threads }, .shared = 0 }, s, &m); +} + +/// The partial launch alone (the chunks' maxima, sums and weighted values into pm, pl and po), for timing. +pub fn partVia(part: Function, s: Stream, p: Attn) !void { + if (p.streams == 0) return; + try admit(p); + var a: cuda.Args = .{}; + for ([_]u64{ p.q, p.segs, p.pm, p.pl, p.po }) |v| a.add(v); + a.add(int(p.kv_heads)); + a.add(int(p.heads / p.kv_heads)); + a.add(int(p.chunks())); + a.add(p.scale); + try cuda.launch.launch(part, .{ .grid = partGrid(p), .block = .{ .x = attn_threads }, .shared = part_shared }, s, &a); +} + +/// Each row's best 32 of n bf16 logits: vals, ids [rows][32] by value, then id; part_vals, part_ids the chunks' bests. +pub const Top32 = struct { + logits: u64, + stride: usize, + n: usize = vocab, + rows: usize, + vals: u64, + ids: u64, + part_vals: u64, + part_ids: u64, + + pub fn chunks(p: Top32) usize { + return ceil(p.n, top_chunk); + } +}; + +/// The bytes each of part_vals and part_ids holds. +pub fn top32Scratch(p: Top32) usize { + return p.rows * p.chunks() * top * 4; +} + +/// One merge: the chunks' bests fit one 2,048-value sort (n at most 131,072). +pub fn admitTop32(p: Top32) !void { + if (p.n == 0 or p.stride < p.n or p.chunks() * top > top_chunk) return error.Top32Shape; + if (p.rows > 65535 or p.stride > std.math.maxInt(i32)) return error.Top32Shape; +} + +pub fn top32(k: *const Kernels, s: Stream, p: Top32) !void { + return top32Via(k.top32_part, k.top32_merge, s, p); +} + +/// The part and merge launches on `part` and `merge`: the served kernels or a control in their place. +pub fn top32Via(part: Function, merge: Function, s: Stream, p: Top32) !void { + if (p.rows == 0) return; + try admitTop32(p); + const chunks = p.chunks(); + var a: cuda.Args = .{}; + a.add(p.logits); + a.add(int(p.n)); + a.add(int(p.stride)); + a.add(int(chunks)); + a.add(p.part_vals); + a.add(p.part_ids); + try cuda.launch.launch(part, .{ .grid = .{ .x = @intCast(chunks), .y = @intCast(p.rows), .z = 1 }, .block = .{ .x = top_threads }, .shared = 0 }, s, &a); + var m: cuda.Args = .{}; + m.add(p.part_vals); + m.add(p.part_ids); + m.add(int(chunks * top)); + m.add(int(chunks * top)); + m.add(@as(c_int, 1)); + m.add(p.vals); + m.add(p.ids); + try cuda.launch.launch(merge, .{ .grid = .{ .x = 1, .y = @intCast(p.rows), .z = 1 }, .block = .{ .x = top_threads }, .shared = 0 }, s, &m); +} + +test "rings and chunks: 4,224 and 16,512 rows, 34 and 130 chunks a (row, head), the Segment as the kernel's" { + const t = std.testing; + try t.expectEqual(@as(usize, 4224), ringRows(sliding_span)); + try t.expectEqual(@as(usize, 16512), ringRows(global_span)); + try t.expectEqual(@as(usize, 34), chunksFor(sliding_span)); + try t.expectEqual(@as(usize, 130), chunksFor(global_span)); + // the widest span + 15 keys from the worst start (one past a chunk's first) still fit: 33 chunks, 129 chunks + try t.expect((127 + sliding_span + block - 1 + chunk - 1) / chunk <= chunksFor(sliding_span)); + try t.expect((127 + global_span + block - 1 + chunk - 1) / chunk <= chunksFor(global_span)); + try t.expectEqual(@as(usize, 24), @sizeOf(Segment)); + try t.expectEqual(@as(usize, 8), @offsetOf(Segment, "anchor")); +} + +test "launch geometry and partials: 8 key heads by streams by chunks, a warp a (row, head)" { + const t = std.testing; + const p: Attn = .{ .q = 0, .segs = 0, .out = 0, .pm = 0, .pl = 0, .po = 0, .streams = 8, .span = global_span }; + const g = partGrid(p); + try t.expectEqual(@as(c_uint, 8), g.x); + try t.expectEqual(@as(c_uint, 8), g.y); + try t.expectEqual(@as(c_uint, 130), g.z); + try t.expectEqual(@as(c_uint, 8 * 16 * 80 / 8), mergeGrid(p).x); + // the map's 86.5 MB a stream at 128-key chunks: 80 heads x 16 rows x 130 chunks x 128 fp32 + try t.expectEqual(@as(usize, 80 * 16 * 130 * 128 * 4), scratch(.{ .q = 0, .segs = 0, .out = 0, .pm = 0, .pl = 0, .po = 0, .streams = 1, .span = global_span }).values); + try t.expectEqual(@as(usize, 65536), part_shared); +} + +test "admit: whole groups, a grid CUDA launches, one merge of the top-32" { + const t = std.testing; + var p: Attn = .{ .q = 0, .segs = 0, .out = 0, .pm = 0, .pl = 0, .po = 0, .streams = 8, .span = sliding_span }; + try admit(p); + p.heads = 81; + try t.expectError(error.AttnShape, admit(p)); + p.heads = 80; + p.streams = 70000; + try t.expectError(error.AttnShape, admit(p)); + var q: Top32 = .{ .logits = 0, .stride = vocab, .rows = 128, .vals = 0, .ids = 0, .part_vals = 0, .part_ids = 0 }; + try admitTop32(q); + try t.expectEqual(@as(usize, 49), q.chunks()); + q.n = 131072; + q.stride = q.n; + try admitTop32(q); + q.n = 131073; + q.stride = q.n; + try t.expectError(error.Top32Shape, admitTop32(q)); + q.n = vocab; + q.stride = vocab - 1; + try t.expectError(error.Top32Shape, admitTop32(q)); +} diff --git a/zig/src/families/ricursive/cuda_dflash2_config.zig b/zig/src/families/ricursive/cuda_dflash2_config.zig new file mode 100644 index 00000000000..0bde87fa831 --- /dev/null +++ b/zig/src/families/ricursive/cuda_dflash2_config.zig @@ -0,0 +1,60 @@ +//! Ripple's DFlash2 drafter config on CUDA: #2260's qualified parse of the published config.json, and the CUDA gate. +const std = @import("std"); +const spec = @import("dflash2_spec.zig"); +const dw = @import("cuda_dflash2_weights.zig"); +const dk = @import("cuda_dflash2_kernels.zig"); +const da = @import("cuda_dflash2_attn.zig"); +const cfg = @import("config.zig"); + +const Config = spec.Config; + +/// The kernels' shapes besides the packer's (B's gate): 128-wide heads in D's groups, 16-row blocks, one top-32 merge. +pub fn gate(c: *const Config) !void { + try dw.gate(c); + if (c.block != da.block or c.heads == 0 or c.kv_heads == 0 or c.heads % c.kv_heads != 0) return error.UnsupportedRicursiveDFlash2Shape; + if (c.hidden % 8 != 0 or c.hidden > dk.most_width or c.top != da.top or c.vocab > 64 * da.top_chunk) return error.UnsupportedRicursiveDFlash2Shape; +} + +/// The drafter's config.json in `dir` through PR 2260's qualified parse beside `target`, and the CUDA gate. +pub fn readConfig(gpa: std.mem.Allocator, io: std.Io, dir: []const u8, target: *const cfg.Config) !Config { + const path = try std.fs.path.join(gpa, &.{ dir, "config.json" }); + defer gpa.free(path); + const bytes = try std.Io.Dir.cwd().readFileAlloc(io, path, gpa, .limited(1 << 22)); + defer gpa.free(bytes); + const c = try spec.parse(gpa, bytes, target); + try gate(&c); + return c; +} + +const testing = std.testing; + +fn release() !Config { + const target = try cfg.parse(testing.allocator, @embedFile("fixtures/config.json")); + return spec.parse(testing.allocator, @embedFile("fixtures/dflash2_config.json"), &target); +} + +test "ricursive dflash2 cuda: the gate takes the release and refuses a block D's attention does not hold" { + var c = try release(); + try gate(&c); + c.block = 8; + try testing.expectError(error.UnsupportedRicursiveDFlash2Shape, gate(&c)); + c = try release(); + c.vocab = 64 * da.top_chunk + 1; + try testing.expectError(error.UnsupportedRicursiveDFlash2Shape, gate(&c)); +} + +test "ricursive dflash2 cuda: the config read takes the published drafter and refuses a clamped MLP, as #2260 does" { + var arena: std.heap.ArenaAllocator = .init(testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const target = try cfg.parse(a, @embedFile("fixtures/config.json")); + const published = @embedFile("fixtures/dflash2_config.json"); + const clamped = try std.mem.replaceOwned(u8, a, published, "\"no_rope_layers\"", "\"ffn_clamp_threshold\": 20, \"no_rope_layers\""); + var tmp = testing.tmpDir(.{}); + defer tmp.cleanup(); + const dir = try std.fmt.allocPrint(a, ".zig-cache/tmp/{s}", .{tmp.sub_path}); + try tmp.dir.writeFile(testing.io, .{ .sub_path = "config.json", .data = published }); + _ = try readConfig(testing.allocator, testing.io, dir, &target); + try tmp.dir.writeFile(testing.io, .{ .sub_path = "config.json", .data = clamped }); + try testing.expectError(error.UnqualifiedRippleDFlash2, readConfig(testing.allocator, testing.io, dir, &target)); +} diff --git a/zig/src/families/ricursive/cuda_dflash2_kernels.zig b/zig/src/families/ricursive/cuda_dflash2_kernels.zig new file mode 100644 index 00000000000..d484f774486 --- /dev/null +++ b/zig/src/families/ricursive/cuda_dflash2_kernels.zig @@ -0,0 +1,283 @@ +//! The DFlash2 drafter's glue on CUDA (ricursive_dflash2.cu): dflash2.metal's norm, prep, conv, silu, streams batched. + +const std = @import("std"); +const cuda = @import("cuda"); +const glue = @import("cuda_kernels.zig"); + +const Stream = cuda.Stream; +const Function = cuda.Function; + +/// Threads a block in every launch (ricursive.cuh's NT); prep runs a warp a (row, head). +pub const threads = 256; +const warps = threads / 32; +pub const head_dim = 128; +/// The widest row the add-norm holds (tf_rc's load_row). +pub const most_width = glue.most_width; + +fn int(x: usize) c_int { + return @intCast(x); +} + +fn ceil(n: usize, d: usize) u32 { + return @intCast((n + d - 1) / d); +} + +pub const Kernels = struct { + mod: cuda.Module, + add_norm: Function, + prep: Function, + conv: Function, + silu: Function, + + pub fn load(d: *const cuda.Driver) !Kernels { + if (!cuda.kernels.available) return error.BuiltWithoutKernels; + var mod = try cuda.Module.load(d, cuda.kernels.ricursive_dflash2); + errdefer mod.unload(); + var k: Kernels = undefined; + k.mod = mod; + inline for (@typeInfo(Kernels).@"struct".field_names, @typeInfo(Kernels).@"struct".field_types) |name, T| if (T == Function) { + const sym = "tf_rcd_" ++ name; + @field(k, name) = try mod.function(sym); + }; + return k; + } + + pub fn unload(k: *Kernels) void { + k.mod.unload(); + k.* = undefined; + } +}; + +fn go(f: Function, s: Stream, dims: cuda.Dim3, a: *cuda.Args) !void { + try cuda.launch.launch(f, .{ .grid = dims, .block = .{ .x = threads }, .shared = 0 }, s, a); +} + +/// An elementwise launch's grid: 256 of a row's values a block, a grid row a row (at most 65,535). +fn plane(rows: usize, width: usize) !cuda.Dim3 { + if (rows == 0 or rows > 65535 or width == 0 or width > std.math.maxInt(i32)) return error.UnsupportedShape; + return .{ .x = ceil(width, threads), .y = @intCast(rows) }; +} + +/// The block's residual rows R = E[ids] unscaled: tf_rc_embed at scale 1 (exact); `scratch` takes its second copy. +pub fn embed(rk: *const glue.Kernels, s: Stream, ids: u64, table: u64, resid: u64, scratch: u64, rows: usize, width: usize) !void { + return embedBy(rk.embed, s, ids, table, resid, scratch, rows, width); +} + +/// `embed` through `f`: tf_rc_embed or a control of it. +pub fn embedBy(f: Function, s: Stream, ids: u64, table: u64, resid: u64, scratch: u64, rows: usize, width: usize) !void { + return glue.embedBy(f, s, ids, table, resid, scratch, rows, width, 1.0); +} + +/// One add-norm launch: `branch` 0 is norm16's form (X = norm(R), R only read). +pub const Norm = struct { + resid: u64, // R: the residual (in place with the add), or norm16's bf16 rows + branch: u64 = 0, // Y: added raw, bf16(R + Y) + w: u64, + x: u64, + rows: usize, + width: usize, + eps: f32, +}; + +/// The add-norm's layout: 8-value chunks, at most most_width a row, every pointer 16-byte aligned. +pub fn normLayout(p: Norm) !void { + if (p.width == 0 or p.width % 8 != 0 or p.width > most_width) return error.UnsupportedWidth; + if (p.rows == 0 or p.rows > std.math.maxInt(i32)) return error.UnsupportedShape; + for ([_]u64{ p.resid, p.branch, p.w, p.x }) |v| if (v % 16 != 0) return error.Misaligned; +} + +/// R = bf16(R + Y) with Y, then X = bf16(w bf16(R / rms)): dflash2.metal's rc_df_norm (rc_df_norm16 without Y). +pub fn norm(k: *const Kernels, s: Stream, p: Norm) !void { + return normBy(k.add_norm, s, p); +} + +/// `norm` through `f`: the served kernel or a control of it. +pub fn normBy(f: Function, s: Stream, p: Norm) !void { + try normLayout(p); + var a: cuda.Args = .{}; + for ([_]u64{ p.resid, p.branch, p.w, p.x }) |v| a.add(v); + a.add(int(p.rows)); + a.add(int(p.width)); + a.add(p.eps); + try go(f, s, .{ .x = @intCast(p.rows) }, &a); +} + +/// One stream's rows in a prep launch (the kernel's Segment): its K and V rings, first row and its position; row order. +pub const Segment = extern struct { k: u64, v: u64, begin: i64, pos: i64 }; + +/// Where a row's heads sit in X: a block's q | k | v projections, or a context's k | v (no query heads). +pub const Layout = struct { + heads: usize, + stride: usize, + q_off: usize, + k_off: usize, + v_off: usize, + + /// dflash2.zig's block rows: q (heads), k and v (kv_heads each), 128 wide a head. + pub fn block(heads: usize, kv_heads: usize) Layout { + const qw = heads * head_dim; + const kvw = kv_heads * head_dim; + return .{ .heads = heads, .stride = qw + 2 * kvw, .q_off = 0, .k_off = qw, .v_off = qw + kvw }; + } + + /// dflash2.zig's absorb rows: each layer's k and v of the normed context. + pub fn context(kv_heads: usize) Layout { + const kvw = kv_heads * head_dim; + return .{ .heads = 0, .stride = 2 * kvw, .q_off = 0, .k_off = 0, .v_off = kvw }; + } +}; + +/// One prep launch: segs on the device; inv the 64 fp32 inverse frequencies; q (0 for a context); rope false: NoPE. +pub const Prep = struct { x: u64, qw: u64, kw: u64, inv: u64, segs: u64, streams: usize, q: u64, rows: usize, kv_heads: usize, at: Layout, ring: usize, rope: bool, eps: f32 }; + +/// The launch's own limits (each stream's rows against its ring: checkSegments, before the table's upload). +pub fn admit(p: Prep) !void { + if (p.rows == 0 or p.rows > 65535 or p.streams == 0 or p.streams > p.rows or p.kv_heads == 0) return error.PrepShape; + if (p.ring == 0 or p.ring > std.math.maxInt(i32) or p.at.stride > std.math.maxInt(i32)) return error.PrepShape; + if ((p.at.heads == 0) != (p.q == 0)) return error.MissingOperand; +} + +/// A block of 8 heads across, a row down. +pub fn grid(p: Prep) cuda.Dim3 { + return .{ .x = ceil(p.at.heads + p.kv_heads, warps), .y = @intCast(p.rows), .z = 1 }; +} + +/// Heads normed and rotated (not on the NoPE layer), keys and values into each stream's ring: rc_df_prep, batched. +pub fn prep(k: *const Kernels, s: Stream, p: Prep) !void { + return prepBy(k.prep, s, p); +} + +/// `prep` through `f`: the served kernel or a control of it. +pub fn prepBy(f: Function, s: Stream, p: Prep) !void { + try admit(p); + var a: cuda.Args = .{}; + for ([_]u64{ p.x, p.qw, p.kw, p.inv, p.segs }) |v| a.add(v); + a.add(int(p.streams)); + a.add(p.q); + for ([_]usize{ p.rows, p.at.heads, p.kv_heads, p.at.stride, p.at.q_off, p.at.k_off, p.at.v_off, p.ring }) |v| a.add(int(v)); + a.add(@as(c_int, @intFromBool(p.rope))); + a.add(p.eps); + try go(f, s, grid(p), &a); +} + +/// A launch's segments: the first at row 0, in row order, positions whole, and no stream past its ring's slots. +pub fn checkSegments(segs: []const Segment, rows: usize, ring: usize) !void { + if (segs.len == 0 or segs[0].begin != 0) return error.BadSegments; + for (segs, 0..) |sg, i| { + const end: i64 = if (i + 1 < segs.len) segs[i + 1].begin else @intCast(rows); + if (sg.pos < 0 or end < sg.begin or end > rows or end - sg.begin > ring) return error.BadSegments; + if (end > sg.begin and (sg.k == 0 or sg.v == 0)) return error.BadSegments; + } +} + +/// RoPE's 64 inverse frequencies as dflash2.metal computes them: 1 / fp32(theta^(2i / 128)), in fp32. +pub fn inverseFrequencies(theta: f32) [head_dim / 2]f32 { + var out: [head_dim / 2]f32 = undefined; + for (&out, 0..) |*f, i| { + const e: f64 = @as(f64, @floatFromInt(2 * i)) / head_dim; + const p: f32 = @floatCast(std.math.pow(f64, theta, e)); + f.* = 1.0 / p; + } + return out; +} + +/// One conv launch: `dyn` rows [2][taps][groups], `base` [2][taps][width]; rows in whole blocks of `block` a stream. +pub const Conv = struct { x: u64, dyn: u64, base: u64, y: u64, rows: usize, width: usize, block: usize, groups: usize, side: usize, taps: usize }; + +pub fn convShape(p: Conv) !void { + if (p.groups == 0 or p.width % p.groups != 0 or p.block == 0 or p.side > 1 or p.taps == 0) return error.UnsupportedShape; + if (p.groups > std.math.maxInt(i32) or p.taps > p.block) return error.UnsupportedShape; +} + +/// Y = the dynamic causal conv of X inside each row's block, dflash2.metal's rc_df_conv rounding. +pub fn conv(k: *const Kernels, s: Stream, p: Conv) !void { + return convBy(k.conv, s, p); +} + +/// `conv` through `f`: the served kernel or a control of it. +pub fn convBy(f: Function, s: Stream, p: Conv) !void { + try convShape(p); + const g = try plane(p.rows, p.width); + var a: cuda.Args = .{}; + for ([_]u64{ p.x, p.dyn, p.base, p.y }) |v| a.add(v); + for ([_]usize{ p.rows, p.width, p.block, p.groups, p.side, p.taps }) |v| a.add(int(v)); + try go(f, s, g, &a); +} + +/// A = bf16(bf16(g sigmoid(g)) * u) from stacked gate | up rows, 2 x `width` each (no clamp). +pub fn silu(k: *const Kernels, s: Stream, gu: u64, act: u64, rows: usize, width: usize) !void { + return siluBy(k.silu, s, gu, act, rows, width); +} + +/// `silu` through `f`: the served kernel or a control of it. +pub fn siluBy(f: Function, s: Stream, gu: u64, act: u64, rows: usize, width: usize) !void { + const g = try plane(rows, width); + var a: cuda.Args = .{}; + a.add(gu); + a.add(act); + a.add(int(rows)); + a.add(int(width)); + try go(f, s, g, &a); +} + +test "dflash2 glue geometry: grids, layouts and the norm's limits" { + const t = std.testing; + try t.expectEqual(@as(u32, 20), (try plane(16, 5120)).x); + try t.expectEqual(@as(u32, 160), (try plane(128, 40960)).x); + try t.expectError(error.UnsupportedShape, plane(65536, 5120)); + const b = Layout.block(80, 8); + try t.expectEqual(@as(usize, 12288), b.stride); + try t.expectEqual(@as(usize, 10240), b.k_off); + try t.expectEqual(@as(usize, 11264), b.v_off); + const cx = Layout.context(8); + try t.expectEqual(@as(usize, 2048), cx.stride); + try t.expectEqual(@as(usize, 1024), cx.v_off); + var p: Prep = .{ .x = 16, .qw = 32, .kw = 48, .inv = 64, .segs = 80, .streams = 8, .q = 96, .rows = 128, .kv_heads = 8, .at = b, .ring = 4224, .rope = true, .eps = 1e-6 }; + try admit(p); + try t.expectEqual(@as(u32, 11), grid(p).x); + try t.expectEqual(@as(u32, 128), grid(p).y); + p.at = cx; + try t.expectError(error.MissingOperand, admit(p)); + p.q = 0; + try admit(p); + try t.expectEqual(@as(u32, 1), grid(p).x); + const n: Norm = .{ .resid = 256, .w = 512, .x = 768, .rows = 2048, .width = 5120, .eps = 1e-6 }; + try normLayout(n); + var bad = n; + bad.width = 8200; + try t.expectError(error.UnsupportedWidth, normLayout(bad)); + bad = n; + bad.branch = 1032; + try t.expectError(error.Misaligned, normLayout(bad)); + const cv: Conv = .{ .x = 0, .dyn = 0, .base = 0, .y = 0, .rows = 128, .width = 5120, .block = 16, .groups = 320, .side = 1, .taps = 4 }; + try convShape(cv); + var bc = cv; + bc.side = 2; + try t.expectError(error.UnsupportedShape, convShape(bc)); + bc = cv; + bc.groups = 300; + try t.expectError(error.UnsupportedShape, convShape(bc)); +} + +test "dflash2 prep segments: row order, rows within a ring, the kernel's layout" { + const t = std.testing; + try t.expectEqual(@as(usize, 32), @sizeOf(Segment)); + try t.expectEqual(@as(usize, 16), @offsetOf(Segment, "begin")); + const two = [_]Segment{ .{ .k = 256, .v = 512, .begin = 0, .pos = 4221 }, .{ .k = 1024, .v = 2048, .begin = 16, .pos = 90 } }; + try checkSegments(&two, 32, 4224); + try t.expectError(error.BadSegments, checkSegments(&two, 15, 4224)); // the second stream begins past the rows + try t.expectError(error.BadSegments, checkSegments(&two, 32, 15)); // 16 rows overrun a 15-slot ring + var late = two; + late[0].begin = 1; + try t.expectError(error.BadSegments, checkSegments(&late, 32, 4224)); + var back = two; + back[1].pos = -1; + try t.expectError(error.BadSegments, checkSegments(&back, 32, 4224)); +} + +test "dflash2 RoPE frequencies: dflash2.metal's 1 / pow(theta, 2i / 128) in fp32" { + const f = inverseFrequencies(10000); + try std.testing.expectEqual(@as(f32, 1), f[0]); + try std.testing.expectEqual(@as(f32, 1.0 / @as(f32, @floatCast(std.math.pow(f64, 10000, 0.5)))), f[32]); + for (f[1..], f[0..63]) |next, prev| try std.testing.expect(next < prev); +} diff --git a/zig/src/families/ricursive/cuda_dflash2_select.zig b/zig/src/families/ricursive/cuda_dflash2_select.zig new file mode 100644 index 00000000000..b431c99f087 --- /dev/null +++ b/zig/src/families/ricursive/cuda_dflash2_select.zig @@ -0,0 +1,205 @@ +//! DFlash2's host path selector (rc_df_walk): each draft the best of a row's top 32 by logit plus codebook score. +const std = @import("std"); +const core = @import("core"); + +const bf = core.bf16_round; + +/// Group of products one simd_sum adds; the kernel's partial sums are one per 32 ranks. +const lane_group = 32; + +/// Drafts the walk writes at most: a block's rows after the pending token. +pub const max_slots = 15; + +/// One walk's inputs: the top-32 candidates of each row and the selector's weights, all as the kernels leave them. +pub const Inputs = struct { + top: u32, + rank: u32, + vocab: u32, + values: []const f32, // [slots, top] logits, value descending then id ascending + ids: []const u32, // [slots, top] vocabulary ids; at or past `vocab` is no candidate + hidden: []const u16, // [slots, rank] bf16 bits: the selector's hidden projection of each row + pred: []const u16, // [vocab, rank] bf16 bits: the predecessor codebook + succ: []const u16, // [vocab, rank] bf16 bits: the successor codebook +}; + +/// Drafts after `anchor` into `out` (rows to walk) as rc_df_walk; the count made before a row with no candidate. +pub fn walk(in: Inputs, anchor: u32, out: []u32) usize { + const rank: usize = in.rank; + const top: usize = in.top; + std.debug.assert(rank % lane_group == 0 and rank <= 1024 and in.hidden.len >= out.len * rank); + std.debug.assert(in.values.len >= out.len * top and in.ids.len >= out.len * top); + std.debug.assert(anchor < in.vocab); + var ah: [1024]f32 = undefined; + var prev: usize = anchor; + for (out, 0..) |*o, e| { + const a = in.pred[prev * rank ..][0..rank]; + const h = in.hidden[e * rank ..][0..rank]; + // candidate c scores bf16(logit + bf16(sum_r bf16(A[prev][r] H[e][r]) B[c][r])), a tie to the lower c + for (ah[0..rank], a, h) |*x, p, q| x.* = bf.round32(bf.value(p) * bf.value(q)); + var best: f32 = -std.math.inf(f32); + var pick: usize = 0; + for (0..top) |c| { + const id = in.ids[e * top + c]; + if (id >= in.vocab) continue; + const b = in.succ[@as(usize, id) * rank ..][0..rank]; + var pair: f32 = 0; + var g: usize = 0; + // the 32-rank partials in lane order (simd_sum's own order is the hardware's), then the partials in order + while (g < rank) : (g += lane_group) { + var part: f32 = 0; + for (ah[g..][0..lane_group], b[g..][0..lane_group]) |x, y| part += x * bf.value(y); + pair += part; + } + const s = bf.round32(in.values[e * top + c] + bf.round32(pair)); + if (s > best) { + best = s; + pick = c; + } + } + const id = in.ids[e * top + pick]; + // the chain stops (the Metal walk goes on, and the caller refuses the id) + if (id >= in.vocab) return e; + o.* = id; + prev = id; + } + return out.len; +} + +const testing = std.testing; + +/// rc_df_walk, thread by thread: 256 products, one partial a 32-lane group, thread 0 choosing; the whole chain runs. +fn metalWalk(in: Inputs, anchor: u32, seq: []u32) void { + const rank: usize = in.rank; + var part: [32][32]f32 = undefined; // [group][candidate] + var prev: u32 = anchor; + for (0..seq.len) |e| { + for (0..in.top) |c| { + const cand = in.ids[e * in.top + c]; + const row = @min(cand, in.vocab - 1); + var g: usize = 0; + while (g < rank / 32) : (g += 1) { + var lane_sum: f32 = 0; + for (0..32) |lane| { + const t = g * 32 + lane; + const ahv = bf.round32(bf.value(in.pred[@as(usize, @min(prev, in.vocab - 1)) * rank + t]) * bf.value(in.hidden[e * rank + t])); + lane_sum += ahv * bf.value(in.succ[@as(usize, row) * rank + t]); + } + part[g][c] = lane_sum; + } + } + var best: f32 = -std.math.inf(f32); + var bi: usize = 0; + for (0..in.top) |c| { + var pair: f32 = 0; + for (0..rank / 32) |k| pair += part[k][c]; + const s = bf.round32(in.values[e * in.top + c] + bf.round32(pair)); + if (in.ids[e * in.top + c] < in.vocab and s > best) { + best = s; + bi = c; + } + } + prev = in.ids[e * in.top + bi]; + seq[e] = prev; + } +} + +const Rows = struct { + values: []f32, + ids: []u32, + hidden: []u16, + pred: []u16, + succ: []u16, + + fn free(r: Rows, a: std.mem.Allocator) void { + a.free(r.values); + a.free(r.ids); + a.free(r.hidden); + a.free(r.pred); + a.free(r.succ); + } +}; + +const T_RANK = 256; +const T_TOP = 32; +const T_VOCAB = 300; +const T_SLOTS = 15; + +/// Fixed pseudo-random rows with small bf16 values (so sums are in range); logits coarse so ties occur. +fn rows(a: std.mem.Allocator) !Rows { + var prng: std.Random.DefaultPrng = .init(0x5eed); + const rnd = prng.random(); + const r: Rows = .{ + .values = try a.alloc(f32, T_SLOTS * T_TOP), + .ids = try a.alloc(u32, T_SLOTS * T_TOP), + .hidden = try a.alloc(u16, T_SLOTS * T_RANK), + .pred = try a.alloc(u16, T_VOCAB * T_RANK), + .succ = try a.alloc(u16, T_VOCAB * T_RANK), + }; + for (r.hidden) |*x| x.* = bf.bits(rnd.float(f32) * 2 - 1); + for (r.pred) |*x| x.* = bf.bits(rnd.float(f32) * 2 - 1); + for (r.succ) |*x| x.* = bf.bits(rnd.float(f32) * 2 - 1); + for (0..T_SLOTS) |e| { + for (0..T_TOP) |c| { + r.ids[e * T_TOP + c] = @intCast((e * 7 + c * 9) % T_VOCAB); // distinct within a row + r.values[e * T_TOP + c] = @floatFromInt(@as(i32, 8) - @as(i32, @intCast(c / 4))); // runs of 4 equal logits + } + } + return r; +} + +fn inputs(r: Rows) Inputs { + return .{ .top = T_TOP, .rank = T_RANK, .vocab = T_VOCAB, .values = r.values, .ids = r.ids, .hidden = r.hidden, .pred = r.pred, .succ = r.succ }; +} + +test "ricursive dflash2 walk: fixed rows equal rc_df_walk's transcription, ties included" { + const a = testing.allocator; + const r = try rows(a); + defer r.free(a); + // row 0's candidates 0 and 1 (ids 0 and 9) have one logit and one codebook row: the lower candidate wins the tie + for (0..T_RANK) |k| r.succ[9 * T_RANK + k] = r.succ[0 * T_RANK + k]; + var want: [T_SLOTS]u32 = undefined; + var got: [T_SLOTS]u32 = undefined; + for ([_]u32{ 0, 1, 299 }) |anchor| { + metalWalk(inputs(r), anchor, &want); + try testing.expectEqual(@as(usize, T_SLOTS), walk(inputs(r), anchor, &got)); + try testing.expectEqualSlices(u32, &want, &got); + } + // a walk of fewer rows is the prefix of the longer one + var few: [4]u32 = undefined; + try testing.expectEqual(@as(usize, 4), walk(inputs(r), 0, &few)); + metalWalk(inputs(r), 0, &want); + try testing.expectEqualSlices(u32, want[0..4], &few); +} + +test "ricursive dflash2 walk: equal scores pick the lower candidate" { + const a = testing.allocator; + const r = try rows(a); + defer r.free(a); + // every candidate of row 0 has one id's codebook row and one logit: all scores tie, so candidate 0 is chosen + for (0..T_TOP) |c| { + r.ids[c] = @intCast(10 + c); + r.values[c] = 1; + for (0..T_RANK) |k| r.succ[(10 + c) * T_RANK + k] = r.succ[10 * T_RANK + k]; + } + var out: [1]u32 = undefined; + try testing.expectEqual(@as(usize, 1), walk(inputs(r), 0, &out)); + try testing.expectEqual(@as(u32, 10), out[0]); +} + +test "ricursive dflash2 walk: ids past the vocabulary are skipped, a row with none stops the chain" { + const a = testing.allocator; + const r = try rows(a); + defer r.free(a); + // row 0: the first 31 candidates are no candidate + for (0..T_TOP - 1) |c| r.ids[c] = 0xffffffff; + // row 3: none at all + for (0..T_TOP) |c| r.ids[3 * T_TOP + c] = @intCast(T_VOCAB + c); + var out: [T_SLOTS]u32 = undefined; + try testing.expectEqual(@as(usize, 3), walk(inputs(r), 2, &out)); + try testing.expectEqual(r.ids[T_TOP - 1], out[0]); + // the Metal transcription agrees up to the stop; its row 3 pick is an id the caller refuses + var seq: [T_SLOTS]u32 = undefined; + metalWalk(inputs(r), 2, &seq); + try testing.expectEqualSlices(u32, out[0..3], seq[0..3]); + try testing.expect(seq[3] >= T_VOCAB); +} diff --git a/zig/src/families/ricursive/cuda_dflash2_shared.zig b/zig/src/families/ricursive/cuda_dflash2_shared.zig new file mode 100644 index 00000000000..0e44f15ddb2 --- /dev/null +++ b/zig/src/families/ricursive/cuda_dflash2_shared.zig @@ -0,0 +1,40 @@ +//! Ripple's DFlash2 drafter on CUDA: shared rounds of every admitted stream, timed at load for the depth rule. +const std = @import("std"); +const fwd = @import("cuda_model.zig"); +const be = @import("cuda_backend.zig"); +const dfl = @import("cuda_dflash2.zig"); + +const windows = be.max_window; + +/// Shared rounds of every admitted stream, w rows each (1 to 16): median of 3, priced past the lone sweep's 16 rows. +pub fn time(d: *dfl.Drafter) !void { + const m = d.m; + const n = @min(d.streams, m.arena.slots); + if (n < 2) return; + const chains = try d.gpa.alloc(fwd.Chain, n); + defer d.gpa.free(chains); + const ids = try d.gpa.alloc(u32, n * windows); + defer d.gpa.free(ids); + @memset(ids, 0); + d.n_shared = 0; + for (1..windows + 1) |w| { + if (n * w > m.round_rows) break; + for (chains, 0..) |*c, s| c.* = .{ .slot = s, .p0 = 0, .tokens = w }; + var ms: [3]f64 = undefined; + for (0..4) |run| { + const t0 = dfl.now(d.io); + try m.round(chains, ids[0 .. n * w]); + try m.rowLogits(n * w); + try m.drawRows(n * w, d.b.ids); + try m.s.synchronize(); + if (run > 0) ms[run - 1] = dfl.msSince(d.io, t0); + } + std.mem.sort(f64, &ms, {}, std.sort.asc(f64)); + std.log.info("Ripple DFlash2 on CUDA: a shared round of {d} streams x {d} rows ({d} rows) in {d:.2} ms", .{ n, w, n * w, ms[1] }); + if (n * w <= windows) continue; // the lone stream's sweep prices rounds up to its widest window + d.shared[d.n_shared] = .{ .width = @intCast(n * w), .ms = ms[1] }; + d.n_shared += 1; + } + for (0..n) |s| try m.reset(s, windows); + try m.s.synchronize(); +} diff --git a/zig/src/families/ricursive/cuda_dflash2_weights.zig b/zig/src/families/ricursive/cuda_dflash2_weights.zig new file mode 100644 index 00000000000..b82522dca73 --- /dev/null +++ b/zig/src/families/ricursive/cuda_dflash2_weights.zig @@ -0,0 +1,447 @@ +//! Ripple's DFlash2 drafter weights on CUDA: the bf16 release packed for the lane matmul, values as stored. +const std = @import("std"); +const core = @import("core"); +const cuda = @import("cuda"); +const spec = @import("dflash2_spec.zig"); +const cfg = @import("config.zig"); + +pub const Config = spec.Config; +const Checkpoint = core.checkpoint.Checkpoint; +const Tensor = core.checkpoint.Tensor; +const Weight = cuda.qmmf.Weight; +const DeviceBuffer = cuda.DeviceBuffer; + +/// Bytes a small tensor's device copy starts on (the glue kernels read 16-byte chunks). +const small_align = 256; + +/// Shapes the packer takes: every matmul's k in whole 64s. Rows are padded to 128 by the packer. +pub fn gate(c: *const Config) !void { + if (c.layers == 0 or c.layers > spec.max_layers) return error.UnsupportedRicursiveDFlash2Shape; + const q = @as(usize, c.heads) * cfg.head_dim; + for ([_]usize{ c.hidden, q, c.ffn, @as(usize, c.hidden) * spec.max_taps }) |k| if (k % cuda.qmmf.group != 0) return error.UnsupportedRicursiveDFlash2Shape; + if (c.rank % 32 != 0) return error.UnsupportedRicursiveDFlash2Shape; // the host walk's 32-rank partial sums +} + +fn queryWidth(c: Config) usize { + return @as(usize, c.heads) * cfg.head_dim; +} + +fn kvWidth(c: Config) usize { + return @as(usize, c.kv_heads) * cfg.head_dim; +} + +/// Bytes of one packed bf16 matrix [n, k]: rows padded to whole 128s. +fn packedBytes(n: usize, k: usize) usize { + return cuda.modelopt.padded(n) * k * 2; +} + +/// Bytes of a layer's packed matrices. +fn layerPacked(c: Config) usize { + const h: usize = c.hidden; + const qw = queryWidth(c); + const kv = kvWidth(c); + return packedBytes(qw + 2 * kv, h) + packedBytes(2 * kv, h) + packedBytes(h, qw) + packedBytes(2 * c.ffn, h) + packedBytes(h, c.ffn) + 2 * packedBytes(c.dyn(), h); +} + +/// The small tensors' device image in a fixed order (norm, hidden_norm, each layer's norms, conv bases), 256-aligned. +fn smallBytes(c: Config) usize { + var at: usize = 0; + const sizes = [_]usize{ @as(usize, c.hidden) * 2, @as(usize, c.hidden) * 2 }; + for (sizes) |n| at = std.mem.alignForward(usize, at, small_align) + n; + for (0..c.layers) |_| { + const per = [_]usize{ @as(usize, c.hidden) * 2, @as(usize, c.hidden) * 2, cfg.head_dim * 2, cfg.head_dim * 2, 2 * @as(usize, c.conv) * c.hidden * 2, 2 * @as(usize, c.conv) * c.hidden * 2 }; + for (per) |n| at = std.mem.alignForward(usize, at, small_align) + n; + } + return at; +} + +/// Device bytes `load` puts on the GPU for `c`: each packed matrix and the small image; codebooks stay on the host. +pub fn deviceBytes(c: Config) usize { + return packedBytes(c.hidden, @as(usize, c.hidden) * spec.max_taps) + packedBytes(c.rank, c.hidden) + c.layers * layerPacked(c) + smallBytes(c); +} + +/// A convolution's device weights: its base kernel [2, conv, H] bf16 and the dynamic projection [dyn, H] packed. +pub const Conv = struct { base: u64, proj: Weight }; + +pub const Layer = struct { + qkv: Weight, // bf16 [q + kv + kv, H]: q rows, k rows, v rows + kv: Weight, // bf16 [kv + kv, H]: k rows, v rows (the absorb's projection) + o: Weight, // bf16 [H, q] + gate_up: Weight, // bf16 [2 * ffn, H]: gate rows, then up rows + down: Weight, // bf16 [H, ffn] + attn_conv: Conv, + mlp_conv: Conv, + in_norm: u64, // bf16 [H] + post_norm: u64, + q_norm: u64, // bf16 [128] + k_norm: u64, +}; + +pub const Weights = struct { + gpa: std.mem.Allocator, + config: Config, + fc: Weight, // bf16 [H, 5H] + hproj: Weight, // bf16 [rank, H]: the selector's hidden projection + hidden_norm: u64, // bf16 [H] + norm: u64, + layers: [spec.max_layers]Layer, + pred: []u16, // host, bf16 bits [vocab, rank]: the predecessor codebook + succ: []u16, // host, bf16 bits [vocab, rank]: the successor codebook + buffers: std.ArrayList(DeviceBuffer) = .empty, + bytes: usize = 0, + + pub fn deinit(w: *Weights) void { + for (w.buffers.items) |*b| b.free(); + w.buffers.deinit(w.gpa); + w.gpa.free(w.pred); + w.gpa.free(w.succ); + w.* = undefined; + } +}; + +/// Where `load`'s packed bytes go: device buffers it owns until the Weights take them. +const Device = struct { + d: *const cuda.Driver, + gpa: std.mem.Allocator, + buffers: std.ArrayList(DeviceBuffer) = .empty, + bytes: usize = 0, + + fn put(s: *Device, bytes: []const u8) !u64 { + var b = try DeviceBuffer.fromHost(s.d, bytes); + errdefer b.free(); + try s.buffers.append(s.gpa, b); + s.bytes += bytes.len; + return b.ptr; + } +}; + +/// The small tensors in one host image, each at a 256-byte boundary. +const Small = struct { + bytes: std.ArrayList(u8) = .empty, + + fn put(s: *Small, gpa: std.mem.Allocator, t: Tensor) !usize { + const at = std.mem.alignForward(usize, s.bytes.items.len, small_align); + try s.bytes.appendNTimes(gpa, 0, at - s.bytes.items.len); + try s.bytes.appendSlice(gpa, t.bytes); + return at; + } +}; + +/// bf16 matrices one under another ([sum n, k]) packed as one projection, then handed to `sink`. +fn dense(gpa: std.mem.Allocator, sink: anytype, parts: []const Tensor, k: usize) !Weight { + var n: usize = 0; + for (parts) |p| n += p.bytes.len / 2 / k; + const src = try gpa.alloc(u16, n * k); + defer gpa.free(src); + var at: usize = 0; + for (parts) |p| { + @memcpy(std.mem.sliceAsBytes(src)[at..][0..p.bytes.len], p.bytes); + at += p.bytes.len; + } + const out = try gpa.alloc(u16, cuda.modelopt.padded(n) * k); + defer gpa.free(out); + cuda.qmmf.packBf16(out, src, n, k); + return cuda.modelopt.bf16Weight(try sink.put(std.mem.sliceAsBytes(out)), n, k); +} + +/// The release's tensor, checked by dtype and shape. +fn bf16(ck: *Checkpoint, comptime fmt: []const u8, args: anytype, shape: []const usize) !Tensor { + var buf: [160]u8 = undefined; + return ck.expect(try std.fmt.bufPrint(&buf, fmt, args), .bf16, shape); +} + +/// Every tensor of the release from `ck`, packed and put to `sink` in a fixed order; the codebooks copied to the host. +fn build(gpa: std.mem.Allocator, ck: *Checkpoint, c: Config, sink: anytype) !Weights { + try gate(&c); + const h: usize = c.hidden; + const qw = queryWidth(c); + const kvw = kvWidth(c); + const dyn: usize = c.dyn(); + var w: Weights = .{ .gpa = gpa, .config = c, .fc = undefined, .hproj = undefined, .hidden_norm = 0, .norm = 0, .layers = undefined, .pred = &.{}, .succ = &.{} }; + errdefer w.deinit(); + w.fc = try dense(gpa, sink, &.{try bf16(ck, "fc.weight", .{}, &.{ h, h * spec.max_taps })}, h * spec.max_taps); + w.hproj = try dense(gpa, sink, &.{try bf16(ck, "candidate_selector.hidden_projection.weight", .{}, &.{ c.rank, h })}, h); + var small: Small = .{}; + defer small.bytes.deinit(gpa); + const at_norm = try small.put(gpa, try bf16(ck, "norm.weight", .{}, &.{h})); + const at_hidden = try small.put(gpa, try bf16(ck, "hidden_norm.weight", .{}, &.{h})); + var offsets: [spec.max_layers][6]usize = undefined; + for (w.layers[0..c.layers], offsets[0..c.layers], 0..) |*l, *o, i| { + const q = try bf16(ck, "layers.{d}.self_attn.q_proj.weight", .{i}, &.{ qw, h }); + const k = try bf16(ck, "layers.{d}.self_attn.k_proj.weight", .{i}, &.{ kvw, h }); + const v = try bf16(ck, "layers.{d}.self_attn.v_proj.weight", .{i}, &.{ kvw, h }); + const gate_w = try bf16(ck, "layers.{d}.mlp.gate_proj.weight", .{i}, &.{ c.ffn, h }); + const up_w = try bf16(ck, "layers.{d}.mlp.up_proj.weight", .{i}, &.{ c.ffn, h }); + const a_base = try bf16(ck, "layers.{d}.attention_conv.base_kernel", .{i}, &.{ 2, c.conv, h }); + const m_base = try bf16(ck, "layers.{d}.mlp_conv.base_kernel", .{i}, &.{ 2, c.conv, h }); + l.* = .{ + .qkv = try dense(gpa, sink, &.{ q, k, v }, h), + .kv = try dense(gpa, sink, &.{ k, v }, h), + .o = try dense(gpa, sink, &.{try bf16(ck, "layers.{d}.self_attn.o_proj.weight", .{i}, &.{ h, qw })}, qw), + .gate_up = try dense(gpa, sink, &.{ gate_w, up_w }, h), + .down = try dense(gpa, sink, &.{try bf16(ck, "layers.{d}.mlp.down_proj.weight", .{i}, &.{ h, c.ffn })}, c.ffn), + .attn_conv = .{ .base = 0, .proj = try dense(gpa, sink, &.{try bf16(ck, "layers.{d}.attention_conv.kernel_projection.weight", .{i}, &.{ dyn, h })}, h) }, + .mlp_conv = .{ .base = 0, .proj = try dense(gpa, sink, &.{try bf16(ck, "layers.{d}.mlp_conv.kernel_projection.weight", .{i}, &.{ dyn, h })}, h) }, + .in_norm = 0, + .post_norm = 0, + .q_norm = 0, + .k_norm = 0, + }; + const smalls = [_]Tensor{ + try bf16(ck, "layers.{d}.input_layernorm.weight", .{i}, &.{h}), + try bf16(ck, "layers.{d}.post_attention_layernorm.weight", .{i}, &.{h}), + try bf16(ck, "layers.{d}.self_attn.q_norm.weight", .{i}, &.{cfg.head_dim}), + try bf16(ck, "layers.{d}.self_attn.k_norm.weight", .{i}, &.{cfg.head_dim}), + a_base, + m_base, + }; + for (smalls, o) |x, *at| at.* = try small.put(gpa, x); + } + const base = try sink.put(small.bytes.items); + w.norm = base + at_norm; + w.hidden_norm = base + at_hidden; + for (w.layers[0..c.layers], offsets[0..c.layers]) |*l, o| { + l.in_norm = base + o[0]; + l.post_norm = base + o[1]; + l.q_norm = base + o[2]; + l.k_norm = base + o[3]; + l.attn_conv.base = base + o[4]; + l.mlp_conv.base = base + o[5]; + } + const vr: usize = c.vocab; + const pred = try bf16(ck, "candidate_selector.predecessor_codebook", .{}, &.{ vr, c.rank }); + const succ = try bf16(ck, "candidate_selector.successor_codebook", .{}, &.{ vr, c.rank }); + w.pred = try gpa.alloc(u16, vr * c.rank); + @memcpy(std.mem.sliceAsBytes(w.pred), pred.bytes); + w.succ = try gpa.alloc(u16, vr * c.rank); + @memcpy(std.mem.sliceAsBytes(w.succ), succ.bytes); + return w; +} + +/// The drafter's config.json through #2260's qualified parse beside `target`, every tensor checked, then onto the GPU. +pub fn load(gpa: std.mem.Allocator, io: std.Io, d: *const cuda.Driver, dir: []const u8, target: *const cfg.Config) !Weights { + const path = try std.fs.path.join(gpa, &.{ dir, "config.json" }); + defer gpa.free(path); + const bytes = try std.Io.Dir.cwd().readFileAlloc(io, path, gpa, .limited(1 << 22)); + defer gpa.free(bytes); + const c = try spec.parse(gpa, bytes, target); + var ck = try Checkpoint.openModel(gpa, io, dir); + defer core.checkpoint.cache.close(&ck); + var dev: Device = .{ .d = d, .gpa = gpa }; + errdefer { + for (dev.buffers.items) |*b| b.free(); + dev.buffers.deinit(gpa); + } + var w = try build(gpa, &ck, c, &dev); + w.buffers = dev.buffers; + w.bytes = dev.bytes; + return w; +} + +const testing = std.testing; +const tio = testing.io; + +fn release(a: std.mem.Allocator) !Config { + const target = try cfg.parse(a, @embedFile("fixtures/config.json")); + return spec.parse(a, @embedFile("fixtures/dflash2_config.json"), &target); +} + +test "ricursive dflash2 config: the imported parse reads the release, a wrong one is refused by name" { + const a = testing.allocator; + const target = try cfg.parse(a, @embedFile("fixtures/config.json")); + const bytes = @embedFile("fixtures/dflash2_config.json"); + const c = try spec.parse(a, bytes, &target); + try testing.expectEqualSlices(u32, &.{ 1, 20, 39, 58, 77 }, &c.taps); + try testing.expectEqual(@as(u32, 16), c.block); + try testing.expectEqual(@as(u32, 32), c.top); + try testing.expectEqual(@as(u32, 4224), c.ring(0)); + try testing.expectEqual(@as(u32, 16512), c.ring(4)); + try testing.expect(!c.rope[4] and c.rope[3] and c.global[4] and !c.global[0]); + const other = try std.mem.replaceOwned(u8, a, bytes, "\"block_size\": 16", "\"block_size\": 8"); + defer a.free(other); + try testing.expectError(error.UnqualifiedRippleDFlash2, spec.parse(a, other, &target)); + const not = try std.mem.replaceOwned(u8, a, bytes, "DFlash2DraftModel", "Qwen3ForCausalLM"); + defer a.free(not); + try testing.expectError(error.NotRippleDFlash2, spec.parse(a, not, &target)); +} + +test "ricursive dflash2 weights: the release's device bytes, about 8.08 GB beside 7.97 GB of unfused matrices" { + const c = try release(testing.allocator); + const b = deviceBytes(c); + const kv_copy = c.layers * packedBytes(2 * kvWidth(c), c.hidden); + try testing.expect(b - kv_copy > 7_960_000_000 and b - kv_copy < 8_000_000_000); + try testing.expect(b > 8_070_000_000 and b < 8_110_000_000); +} + +/// A tiny drafter: 2 layers, hidden 128, 2 query heads over 1 key head, whole-128 outputs and a padded one (hproj). +fn tiny() Config { + return .{ .layers = 2, .heads = 2, .kv_heads = 1, .hidden = 128, .ffn = 256, .vocab = 128, .window = 16, .block = 16, .mask = 7, .rank = 64, .top = 32, .group = 4, .conv = 2, .taps = .{ 1, 2, 3, 4, 5 }, .theta = 10000, .eps = 1e-6 }; +} + +const Entry = struct { name: []const u8, shape: []const usize }; + +/// Every tensor `c` names, in the release's names. +fn entries(a: std.mem.Allocator, c: Config) ![]Entry { + var list: std.ArrayList(Entry) = .empty; + const h: usize = c.hidden; + const add = struct { + fn f(l: *std.ArrayList(Entry), al: std.mem.Allocator, comptime fmt: []const u8, args: anytype, shape: []const usize) !void { + try l.append(al, .{ .name = try std.fmt.allocPrint(al, fmt, args), .shape = try al.dupe(usize, shape) }); + } + }.f; + try add(&list, a, "fc.weight", .{}, &.{ h, h * 5 }); + try add(&list, a, "hidden_norm.weight", .{}, &.{h}); + try add(&list, a, "norm.weight", .{}, &.{h}); + try add(&list, a, "candidate_selector.hidden_projection.weight", .{}, &.{ c.rank, h }); + try add(&list, a, "candidate_selector.predecessor_codebook", .{}, &.{ c.vocab, c.rank }); + try add(&list, a, "candidate_selector.successor_codebook", .{}, &.{ c.vocab, c.rank }); + for (0..c.layers) |i| { + try add(&list, a, "layers.{d}.input_layernorm.weight", .{i}, &.{h}); + try add(&list, a, "layers.{d}.post_attention_layernorm.weight", .{i}, &.{h}); + try add(&list, a, "layers.{d}.self_attn.q_norm.weight", .{i}, &.{cfg.head_dim}); + try add(&list, a, "layers.{d}.self_attn.k_norm.weight", .{i}, &.{cfg.head_dim}); + try add(&list, a, "layers.{d}.self_attn.q_proj.weight", .{i}, &.{ queryWidth(c), h }); + try add(&list, a, "layers.{d}.self_attn.k_proj.weight", .{i}, &.{ kvWidth(c), h }); + try add(&list, a, "layers.{d}.self_attn.v_proj.weight", .{i}, &.{ kvWidth(c), h }); + try add(&list, a, "layers.{d}.self_attn.o_proj.weight", .{i}, &.{ h, queryWidth(c) }); + try add(&list, a, "layers.{d}.mlp.gate_proj.weight", .{i}, &.{ c.ffn, h }); + try add(&list, a, "layers.{d}.mlp.up_proj.weight", .{i}, &.{ c.ffn, h }); + try add(&list, a, "layers.{d}.mlp.down_proj.weight", .{i}, &.{ h, c.ffn }); + for ([_][]const u8{ "attention_conv", "mlp_conv" }) |n| { + try add(&list, a, "layers.{d}.{s}.base_kernel", .{ i, n }, &.{ 2, c.conv, h }); + try add(&list, a, "layers.{d}.{s}.kernel_projection.weight", .{ i, n }, &.{ c.dyn(), h }); + } + } + return list.items; +} + +/// A safetensors file of every tensor of `c`, each bf16 with its own pseudo-random bits. +fn writeFixture(a: std.mem.Allocator, dir: std.Io.Dir, c: Config) !void { + const list = try entries(a, c); + var header: std.Io.Writer.Allocating = .init(a); + try header.writer.writeAll("{"); + var at: usize = 0; + for (list, 0..) |e, j| { + var n: usize = 2; + for (e.shape) |x| n *= x; + try header.writer.print("{s}\"{s}\":{{\"dtype\":\"BF16\",\"shape\":[", .{ if (j == 0) "" else ",", e.name }); + for (e.shape, 0..) |x, i| try header.writer.print("{s}{d}", .{ if (i == 0) "" else ",", x }); + try header.writer.print("],\"data_offsets\":[{d},{d}]}}", .{ at, at + n }); + at += n; + } + try header.writer.writeAll("}"); + const hd = header.written(); + const file = try a.alloc(u8, 8 + hd.len + at); + std.mem.writeInt(u64, file[0..8], hd.len, .little); + @memcpy(file[8..][0..hd.len], hd); + var prng: std.Random.DefaultPrng = .init(0xd2); + prng.random().bytes(file[8 + hd.len ..]); + // small finite bf16 everywhere: the sign and a low exponent, the mantissa as drawn + for (std.mem.bytesAsSlice(u16, file[8 + hd.len ..])) |*x| x.* = (x.* & 0x807f) | 0x3c00; + try dir.writeFile(tio, .{ .sub_path = "model.safetensors", .data = file }); +} + +fn tmpPath(a: std.mem.Allocator, tmp: testing.TmpDir) ![]u8 { + const cwd = try std.process.currentPathAlloc(tio, a); + return std.fmt.allocPrint(a, "{s}/.zig-cache/tmp/{s}", .{ cwd, tmp.sub_path }); +} + +/// A sink that keeps what `load` would upload, at fake addresses one 4 KiB apart. +const Recorder = struct { + gpa: std.mem.Allocator, + images: std.ArrayList([]u8) = .empty, + bytes: usize = 0, + + fn put(r: *Recorder, bytes: []const u8) !u64 { + try r.images.append(r.gpa, try r.gpa.dupe(u8, bytes)); + r.bytes += bytes.len; + return (r.images.items.len) << 12; + } + + fn deinit(r: *Recorder) void { + for (r.images.items) |i| r.gpa.free(i); + r.images.deinit(r.gpa); + } + + fn at(r: *const Recorder, ptr: u64) []const u16 { + return @alignCast(std.mem.bytesAsSlice(u16, r.images.items[(ptr >> 12) - 1])); + } +}; + +fn tensorOf(ck: *Checkpoint, comptime fmt: []const u8, args: anytype) !Tensor { + var buf: [160]u8 = undefined; + return ck.get(try std.fmt.bufPrint(&buf, fmt, args)); +} + +test "ricursive dflash2 weights: each fused packing equals its parts packed one by one, the bytes equal the formula" { + var arena: std.heap.ArenaAllocator = .init(testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const c = tiny(); + var tmp = testing.tmpDir(.{}); + defer tmp.cleanup(); + try writeFixture(a, tmp.dir, c); + var ck = try Checkpoint.openModel(testing.allocator, tio, try tmpPath(a, tmp)); + defer ck.close(); + var rec: Recorder = .{ .gpa = testing.allocator }; + defer rec.deinit(); + var w = try build(testing.allocator, &ck, c, &rec); + defer w.deinit(); + try testing.expectEqual(deviceBytes(c), rec.bytes); + const h: usize = c.hidden; + for (w.layers[0..c.layers], 0..) |l, i| { + const q = try tensorOf(&ck, "layers.{d}.self_attn.q_proj.weight", .{i}); + const k = try tensorOf(&ck, "layers.{d}.self_attn.k_proj.weight", .{i}); + const v = try tensorOf(&ck, "layers.{d}.self_attn.v_proj.weight", .{i}); + const g = try tensorOf(&ck, "layers.{d}.mlp.gate_proj.weight", .{i}); + const u = try tensorOf(&ck, "layers.{d}.mlp.up_proj.weight", .{i}); + try expectFused(a, &rec, l.qkv, &.{ q, k, v }, h); + try expectFused(a, &rec, l.kv, &.{ k, v }, h); + try expectFused(a, &rec, l.gate_up, &.{ g, u }, h); + try expectFused(a, &rec, l.o, &.{try tensorOf(&ck, "layers.{d}.self_attn.o_proj.weight", .{i})}, queryWidth(c)); + try expectFused(a, &rec, l.down, &.{try tensorOf(&ck, "layers.{d}.mlp.down_proj.weight", .{i})}, c.ffn); + try expectFused(a, &rec, l.attn_conv.proj, &.{try tensorOf(&ck, "layers.{d}.attention_conv.kernel_projection.weight", .{i})}, h); + try expectFused(a, &rec, l.mlp_conv.proj, &.{try tensorOf(&ck, "layers.{d}.mlp_conv.kernel_projection.weight", .{i})}, h); + // norms and bases are plain bf16 at 256-byte boundaries + try testing.expectEqual(@as(u64, 0), l.in_norm % small_align); + const norm = try tensorOf(&ck, "layers.{d}.input_layernorm.weight", .{i}); + try testing.expectEqualSlices(u8, norm.bytes, smallAt(&rec, l.in_norm)[0..norm.bytes.len]); + const base = try tensorOf(&ck, "layers.{d}.attention_conv.base_kernel", .{i}); + try testing.expectEqualSlices(u8, base.bytes, smallAt(&rec, l.attn_conv.base)[0..base.bytes.len]); + } + try expectFused(a, &rec, w.fc, &.{try tensorOf(&ck, "fc.weight", .{})}, h * 5); + try expectFused(a, &rec, w.hproj, &.{try tensorOf(&ck, "candidate_selector.hidden_projection.weight", .{})}, h); + const pred = try tensorOf(&ck, "candidate_selector.predecessor_codebook", .{}); + try testing.expectEqualSlices(u8, pred.bytes, std.mem.sliceAsBytes(w.pred)); +} + +/// The small image holds the last put; a pointer's bytes start `ptr % 4096`... the recorder's address of that image. +fn smallAt(r: *const Recorder, ptr: u64) []const u8 { + // addresses are image index << 12 plus an offset into the small image, which is the last image + const image = r.images.items[r.images.items.len - 1]; + const base: u64 = r.images.items.len << 12; + return image[ptr - base ..]; +} + +/// A fused weight's packed words equal each part packed on its own and laid one after another. +fn expectFused(a: std.mem.Allocator, r: *const Recorder, wt: Weight, parts: []const Tensor, k: usize) !void { + const got = r.at(wt.codes); + var at: usize = 0; + var rows: usize = 0; + for (parts) |p| { + const n = p.bytes.len / 2 / k; + const src = try a.alloc(u16, n * k); + @memcpy(std.mem.sliceAsBytes(src), p.bytes); + const one = try a.alloc(u16, cuda.modelopt.padded(n) * k); + cuda.qmmf.packBf16(one, src, n, k); + try testing.expectEqualSlices(u16, one, got[at..][0..one.len]); + at += one.len; + rows += n; + } + try testing.expectEqual(got.len, at); + try testing.expectEqual(@as(u32, @intCast(rows)), wt.n); +} + +test "ricursive dflash2 weights: the device loader type-checks" { + _ = &load; +} diff --git a/zig/src/families/ricursive/cuda_kernels.zig b/zig/src/families/ricursive/cuda_kernels.zig index 7f2bb50f27b..80011314b8c 100644 --- a/zig/src/families/ricursive/cuda_kernels.zig +++ b/zig/src/families/ricursive/cuda_kernels.zig @@ -25,6 +25,7 @@ pub const Kernels = struct { add_norm: Function, gate: Function, silu_clamp: Function, + tap: Function, // a drafter's tap: residual rows into a slot's ring (dflash2.metal's rc_tap) // plug-in point: the prep and attention launches, a Function each, tf_rc_ in ricursive.cu pub fn load(d: *const cuda.Driver) !Kernels { @@ -145,6 +146,44 @@ pub fn siluClampBy(f: Function, s: Stream, gu: u64, act: u64, rows: usize, width try go(f, s, grid, &a); } +/// One tf_rc_tap launch: rows into tap column col at ring row pos % ring_rows; chunk: p0 + r of s0; round: pos, slot. +pub const TapRows = struct { + resid: u64, // R [rows, width] bf16 + ring: u64, // the rings from slot 0: [slots][ring_rows][taps][width] bf16 + pos: u64 = 0, // int32 [rows]: a round's positions + slot: u64 = 0, // int32 [rows]: a round's slots + p0: usize = 0, + s0: usize = 0, + rows: usize, + width: usize, + taps: usize, + col: usize, + ring_rows: usize, +}; + +/// tf_rc_tap's layout: 16-byte rows (8 values a thread), a column of the taps, both or neither of pos and slot. +pub fn tapLayout(p: TapRows) !void { + if (p.width == 0 or p.width % 8 != 0) return error.UnsupportedWidth; + if (p.rows == 0 or p.rows > 65535 or p.ring_rows == 0 or p.taps == 0 or p.col >= p.taps) return error.UnsupportedShape; + if ((p.pos == 0) != (p.slot == 0)) return error.MissingOperand; + if (p.pos == 0 and (p.p0 + p.rows > std.math.maxInt(i32) or p.s0 > std.math.maxInt(i32))) return error.UnsupportedShape; + for ([_]u64{ p.resid, p.ring }) |v| if (v % 16 != 0) return error.Misaligned; +} + +/// T[slot][pos % ring_rows][col] = R[r] for each row r: a bf16 copy, no rounding. +pub fn tap(k: *const Kernels, s: Stream, p: TapRows) !void { + return tapBy(k.tap, s, p); +} + +/// `tap` through `f`: the served kernel or a control of it. +pub fn tapBy(f: Function, s: Stream, p: TapRows) !void { + try tapLayout(p); + var a: cuda.Args = .{}; + for ([_]u64{ p.resid, p.ring, p.pos, p.slot }) |v| a.add(v); + for ([_]usize{ p.p0, p.s0, p.rows, p.width, p.taps, p.col, p.ring_rows }) |v| a.add(int(v)); + try go(f, s, .{ .x = ceil(p.width / 8, threads), .y = @intCast(p.rows) }, &a); +} + test "launch geometry: ceilings and the add-norm's layout" { try std.testing.expectEqual(@as(u32, 20), ceil(5120, threads)); try std.testing.expectEqual(@as(u32, 40), ceil(10240, threads)); @@ -169,3 +208,26 @@ test "launch geometry: ceilings and the add-norm's layout" { bad.x = 776; try std.testing.expectError(error.Misaligned, normLayout(bad)); } + +test "launch geometry: the tap's layout" { + const p: TapRows = .{ .resid = 256, .ring = 4096, .rows = 2048, .width = 5120, .taps = 5, .col = 4, .ring_rows = 2064 }; + try tapLayout(p); + try std.testing.expectEqual(@as(u32, 3), ceil(p.width / 8, threads)); // 640 chunks of 8 + var bad = p; + bad.width = 5124; + try std.testing.expectError(error.UnsupportedWidth, tapLayout(bad)); + bad = p; + bad.col = 5; + try std.testing.expectError(error.UnsupportedShape, tapLayout(bad)); + bad = p; + bad.rows = 65536; + try std.testing.expectError(error.UnsupportedShape, tapLayout(bad)); + bad = p; + bad.pos = 512; + try std.testing.expectError(error.MissingOperand, tapLayout(bad)); + bad.slot = 768; + try tapLayout(bad); + bad = p; + bad.ring = 4104; + try std.testing.expectError(error.Misaligned, tapLayout(bad)); +} diff --git a/zig/src/families/ricursive/cuda_model.zig b/zig/src/families/ricursive/cuda_model.zig index 09af6dbd9d8..1934f73ddde 100644 --- a/zig/src/families/ricursive/cuda_model.zig +++ b/zig/src/families/ricursive/cuda_model.zig @@ -1,4 +1,4 @@ -//! Ripple's forward on CUDA: Metal forward.zig's layer order; prompt chunks of one slot, and rounds of rows over slots. +//! Ripple's forward on CUDA: Metal forward.zig's layer order; prompt chunks of a slot, rounds of rows over slots, taps. const std = @import("std"); const cuda = @import("cuda"); const cfg = @import("config.zig"); @@ -12,6 +12,7 @@ const Stream = cuda.Stream; const DeviceBuffer = cuda.DeviceBuffer; const Config = cfg.Config; const Weight = cuda.qmmf.Weight; +const kv_arena = @import("cuda_arena.zig"); // the slots' caches in one buffer /// A prompt forward's rows at most (a chunk). pub const prompt_rows = 2048; @@ -24,7 +25,22 @@ pub const head_rows = 128; /// A one-row round's rows: the round maximum of the CLI and the one-stream backend (one-row chain decode). pub const decode_rows = 1; /// Device offsets start on 256 bytes (the row kernels read 16-byte chunks). -const buffer_align = 256; +pub const buffer_align = 256; +/// A slot's tap ring: a prompt chunk's rows and a 16-row verify window's (position p at row p % tap_rows). +pub const tap_rows = prompt_rows + 16; +/// Tapped layers at most (the Metal family's limit). +pub const max_taps = 16; + +/// The tap rings' bytes for `slots` slots of `taps` tapped layers: tap_rows rows of taps x hidden bf16 a slot. +pub fn tapBytes(c: Config, taps: usize, slots: usize) usize { + return slots * tap_rows * taps * c.hidden * 2; +} + +/// A drafter's tapped layers: 1 to max_taps distinct layers of the model, in the drafter's column order. +pub fn checkTaps(c: Config, layers: []const u32) !void { + if (layers.len == 0 or layers.len > max_taps) return error.UnsupportedRicursiveTaps; + for (layers, 0..) |l, j| if (l >= c.layers or std.mem.indexOfScalar(u32, layers[0..j], l) != null) return error.UnsupportedRicursiveTaps; +} /// prompt: a chunk by the prompt kernels; decode: a round of one chain by the lane matmul and the decode attention. pub const Mode = enum { prompt, decode }; @@ -106,97 +122,11 @@ fn slidingWindow(c: Config) wa.Window { return attn.sliding(c.heads, c.kv_heads, c.window, ring_rows, c.scale()); } -/// The pages a slot's global layer holds: the context in whole pages. -pub fn pagesOf(context: usize) usize { - return (context + page_tokens - 1) / page_tokens; -} - -/// A layer's caches from slot 0: a sliding layer's rings [slots][ring][kv_heads][128], or (`pg`) a global's pages. -pub const Cache = struct { kc: u64, vc: u64, pg: ?wa.Pages = null }; - -/// One slot's rows of a layer as a snapshot copies them: position p at ring row p % ring_rows, or global row p. -pub const Span = struct { k: u64, v: u64, rows: usize, row_bytes: usize, ring: bool }; - -/// One slot's caches: a sliding layer's K and V rings, a global layer's K and V pages for `context`. -pub fn slotBytes(c: Config, context: usize) usize { - const kvw = c.kvWidth(); - const g = c.globals(); - return (c.layers - g) * 2 * ring_rows * kvw * 2 + g * 2 * pagesOf(context) * page_tokens * kvw * 2; -} - -/// Every slot's caches in one buffer, a layer at a time (each slot's rows, K then V), then the page table. -pub const Arena = struct { - gpa: std.mem.Allocator, - kv: DeviceBuffer, - caches: []Cache, // a layer each, at slot 0 - ids: []i32, // the page table's host copy [slots][per_slot]: the call tables gather its rows - slots: usize, - per_slot: usize, // pages a slot's global layer holds - kvw: usize, - - /// `slots` slots' caches for `context` positions and the int32 table. - pub fn bytes(c: Config, context: usize, slots: usize) usize { - return slots * slotBytes(c, context) + std.mem.alignForward(usize, slots * pagesOf(context) * 4, buffer_align); - } - - /// Zeroed caches (no stale bits under a masked key), the identity table: slot s's page j is page s * per_slot + j. - pub fn init(gpa: std.mem.Allocator, d: *const cuda.Driver, s: Stream, c: Config, context: usize, slots: usize) !Arena { - const kvw = c.kvWidth(); - const per = pagesOf(context); - var kv = try DeviceBuffer.alloc(d, bytes(c, context, slots)); - errdefer kv.free(); - try d.check(d.api.cuMemsetD8Async(kv.ptr, 0, kv.len, s.handle), "cuMemsetD8Async"); - const caches = try gpa.alloc(Cache, c.layers); - errdefer gpa.free(caches); - const ids = try gpa.alloc(i32, slots * per); - errdefer gpa.free(ids); - for (ids, 0..) |*x, i| x.* = @intCast(i); - const table_at = kv.len - std.mem.alignForward(usize, ids.len * 4, buffer_align); - try cuda.copy_source.enqueue(d, kv.ptr + table_at, std.mem.sliceAsBytes(ids), s); - var at: u64 = kv.ptr; - for (caches, 0..) |*cache, i| { - const half: usize = slots * if (c.global[i]) per * page_tokens * kvw * 2 else ring_rows * kvw * 2; - cache.* = .{ .kc = at, .vc = at + half }; - if (c.global[i]) cache.pg = .{ .table = kv.ptr + table_at, .page_elems = page_tokens * kvw, .tokens = page_tokens, .stride = per }; - at += 2 * half; - } - return .{ .gpa = gpa, .kv = kv, .caches = caches, .ids = ids, .slots = slots, .per_slot = per, .kvw = kvw }; - } - - pub fn deinit(a: *Arena) void { - a.gpa.free(a.ids); - a.gpa.free(a.caches); - a.kv.free(); - a.* = undefined; - } - - /// Layer i's caches of one slot as a prompt chunk reads them: its rings, or the pools and its table row (stride 0). - pub fn slotCache(a: *const Arena, i: usize, slot: usize) Cache { - const c = a.caches[i]; - if (c.pg) |pg| { - var row = pg; - row.table += slot * a.per_slot * 4; - row.stride = 0; - return .{ .kc = c.kc, .vc = c.vc, .pg = row }; - } - const ring = ring_rows * a.kvw * 2; - return .{ .kc = c.kc + slot * ring, .vc = c.vc + slot * ring }; - } - - /// Layer i's rows of one slot. - pub fn span(a: *const Arena, i: usize, slot: usize) Span { - const c = a.caches[i]; - const row = a.kvw * 2; - const rows: usize = if (c.pg != null) a.per_slot * page_tokens else ring_rows; - return .{ .k = c.kc + slot * rows * row, .v = c.vc + slot * rows * row, .rows = rows, .row_bytes = row, .ring = c.pg == null }; - } - - /// The V pools' offset from the K pools in bf16 elements: the same in every global layer. - fn vOff(a: *const Arena) usize { - for (a.caches) |c| if (c.pg != null) return (c.vc - c.kc) / 2; - return 0; - } -}; +pub const pagesOf = kv_arena.pagesOf; +pub const Cache = kv_arena.Cache; +pub const Span = kv_arena.Span; +pub const slotBytes = kv_arena.slotBytes; +pub const Arena = kv_arena.Arena; /// A round's rows on the host: positions and slots (int32 for the kernels, usize for the plan), the call table. const Host = struct { pos: []i32, slot: []i32, at: []usize, ctab: []i32 }; @@ -246,6 +176,11 @@ pub const Model = struct { graphs: bool = true, /// Captured rounds by row count ([n], n to round_rows), each the layers' launches over the staged rows. execs: []?cuda.graph.Exec, + /// The drafter's tapped layers (setTaps), tap column j the layer taps[j]; none: no ring and no tap launch. + taps: [max_taps]u32 = undefined, + n_taps: usize = 0, + /// Every slot's tap ring, [slots][tap_rows][n_taps][hidden] bf16. + tap: ?DeviceBuffer = null, /// The lane's slice partials of every projection and the head at up to `rows` rows (they reduce below fused_rows). fn partBytes(w: *const wts.Weights, k: *const Kernels, rows: usize) usize { @@ -301,6 +236,7 @@ pub const Model = struct { pub fn deinit(m: *Model) void { m.dropGraphs(); + if (m.tap) |*ring| ring.free(); m.gpa.free(m.execs); m.gpa.free(m.host.ctab); m.gpa.free(m.host.at); @@ -312,6 +248,49 @@ pub const Model = struct { m.* = undefined; } + /// The drafter's tapped layers, before its streams: a zeroed ring a slot; graphs dropped to recapture with taps. + pub fn setTaps(m: *Model, tapped: []const u32) !void { + try checkTaps(m.c, tapped); + try m.s.synchronize(); // no launch still writes an old ring + var ring = try DeviceBuffer.alloc(m.d, tapBytes(m.c, tapped.len, m.arena.slots)); + errdefer ring.free(); + try m.d.check(m.d.api.cuMemsetD8Async(ring.ptr, 0, ring.len, m.s.handle), "cuMemsetD8Async"); + m.dropGraphs(); + if (m.tap) |*old| old.free(); + m.tap = ring; + @memcpy(m.taps[0..tapped.len], tapped); + m.n_taps = tapped.len; + } + + /// A tap ring's row: n_taps x hidden bf16. + pub fn tapRowBytes(m: *const Model) usize { + return m.n_taps * m.c.hidden * 2; + } + + /// A slot's tap ring (position p at row p % tap_rows), null without taps. + pub fn tapRing(m: *const Model, slot: usize) ?u64 { + const ring = m.tap orelse return null; + return ring.ptr + slot * tap_rows * m.tapRowBytes(); + } + + /// A tapped layer i's rows into its tap column: a chunk's at p0 + r of its slot, a round's at staged pos and slot. + fn tapRows(m: *const Model, i: usize, n: usize, pass: Pass) !void { + const ring = m.tap orelse return; + const col = std.mem.indexOfScalar(u32, m.taps[0..m.n_taps], @intCast(i)) orelse return; + var p: glue.TapRows = .{ .resid = m.b.resid, .ring = ring.ptr, .rows = n, .width = m.c.hidden, .taps = m.n_taps, .col = col, .ring_rows = tap_rows }; + switch (pass) { + .chunk => |ch| { + p.p0 = ch.p0; + p.s0 = ch.slot; + }, + .round => { + p.pos = m.b.pos; + p.slot = m.b.slot; + }, + } + try glue.tap(&m.k.glue, m.s, p); + } + /// Zeroes a slot's positions [0, written) (a ring past its rows whole): a fresh arena's bytes, for another stream. pub fn reset(m: *const Model, slot: usize, written: usize) !void { if (slot >= m.arena.slots) return error.NoSuchSlot; @@ -412,6 +391,7 @@ pub const Model = struct { const next = &ls[i + 1]; try glue.addNorm(&k.glue, s, .{ .resid = b.resid, .branch = b.y, .post = l.post_ffn, .next = next.input_norm, .v0 = b.v0, .x = b.x, .vx = b.vx, .rows = n, .width = h, .eps = c.eps, .blend = next.blend }); } else try glue.addNorm(&k.glue, s, .{ .resid = b.resid, .branch = b.y, .post = l.post_ffn, .next = m.w.norm, .x = b.x, .rows = n, .width = h, .eps = c.eps }); + try m.tapRows(i, n, pass); // the summed residual after layer i, as Metal's rc_tap reads it } } @@ -582,6 +562,21 @@ test "ricursive cuda round rows: chains in order, each row its slot's table row; try testing.expectError(error.PastContext, fill(h, &table, per, 4, 1536, &.{.{ .slot = 3, .p0 = 1535, .tokens = 2 }}, 2)); } +test "ricursive cuda taps: 2,064 rows of 5 x 5,120 bf16 a slot; 1 to 16 distinct layers of the model" { + const c = try release(); + try testing.expectEqual(@as(usize, 2064), tap_rows); + try testing.expectEqual(@as(usize, 105_676_800), tapBytes(c, 5, 1)); // 51,200 bytes a row + try testing.expectEqual(@as(usize, 8 * 105_676_800), tapBytes(c, 5, 8)); + try testing.expectEqual(@as(usize, 0), tapBytes(c, 0, 8)); + try checkTaps(c, &.{ 1, 20, 39, 58, 77 }); + try checkTaps(c, &.{@intCast(c.layers - 1)}); + try testing.expectError(error.UnsupportedRicursiveTaps, checkTaps(c, &.{})); + try testing.expectError(error.UnsupportedRicursiveTaps, checkTaps(c, &.{ 1, 20, 1 })); + try testing.expectError(error.UnsupportedRicursiveTaps, checkTaps(c, &.{@intCast(c.layers)})); + const many: [max_taps + 1]u32 = std.simd.iota(u32, max_taps + 1); + try testing.expectError(error.UnsupportedRicursiveTaps, checkTaps(c, &many)); +} + test "ricursive cuda forward type-checks against the kernels' wrappers" { testing.refAllDecls(Model); testing.refAllDecls(Kernels); diff --git a/zig/src/families/ricursive/cuda_native.zig b/zig/src/families/ricursive/cuda_native.zig index 2b17bd165e9..3a378e892eb 100644 --- a/zig/src/families/ricursive/cuda_native.zig +++ b/zig/src/families/ricursive/cuda_native.zig @@ -6,6 +6,8 @@ const wts = @import("cuda_weights.zig"); const fwd = @import("cuda_model.zig"); const be = @import("cuda_backend.zig"); const cfg = @import("config.zig"); +const dfl = @import("cuda_dflash2.zig"); +const dshared = @import("cuda_dflash2_shared.zig"); const snap = be.snap; @@ -16,8 +18,8 @@ pub const max_segments: u32 = 1; pub const prompt_rows: u32 = be.prompt_rows; /// A kept state is the caches through its position and nothing past it (no draft head reads a token on). pub const snap_lookahead: u32 = 0; -pub const takes_drafter = false; -pub const drafter_refusal = "--drafter: Ripple on CUDA loads no drafter yet; serve it without --drafter"; +/// --drafter: the DFlash2 drafter (ricursiveAI/Ripple-65B-Preview-DFlash2) proposes chains the target verifies. +pub const takes_drafter = true; /// `explain` words this family's open refusals too. pub const explains_open = true; /// The server's think block rules: Ripple opens `` itself or answers bare, and its markers take no budget. @@ -31,8 +33,8 @@ pub const gb10_bytes: u64 = @intFromFloat(121.7 * (1 << 30)); /// The server's reading of the room left after the weights; null if unreadable. pub const Room = struct { ctx: *anyopaque, read: *const fn (*anyopaque) ?u64 }; -/// --parallel: the streams made at open (auto: the most that fit, at most a round's rows over 16-row windows). -pub const Options = struct { context: usize, drafts: bool, segments: usize = 1, slide: bool = false, lanes: u32 = 8, lanes_fixed: bool = false, room: ?Room = null }; +/// --parallel: streams made at open (auto: the most that fit, at most round rows / 16); --drafter: the DFlash2 folder. +pub const Options = struct { context: usize, drafts: bool, segments: usize = 1, slide: bool = false, lanes: u32 = 8, lanes_fixed: bool = false, room: ?Room = null, drafter: ?[]const u8 = null }; /// What the native server drives: every stream's caches, allocated at open. pub const Loaded = struct { @@ -47,7 +49,7 @@ pub const Loaded = struct { }; /// The weights, kernels, stream, forward and backend one open owns. -pub const Owned = struct { gpa: std.mem.Allocator, w: wts.Weights, k: fwd.Kernels, s: cuda.Stream, m: fwd.Model, rb: be.Ripple }; +pub const Owned = struct { gpa: std.mem.Allocator, w: wts.Weights, k: fwd.Kernels, s: cuda.Stream, m: fwd.Model, rb: be.Ripple, draft: ?*dfl.Drafter }; /// Device bytes past the weights for the CLI's one stream at `context` positions: scratch, caches, the backend's. pub fn openBytes(w: *const wts.Weights, k: *const fwd.Kernels, context: usize) u64 { @@ -83,17 +85,40 @@ fn fit(room: u64, asked: u32, fixed: bool, plan: anytype) !usize { return n; } -/// The device bytes `n` streams take at `positions`: the forward's scratch for a round, their slots, the backend's. -const Plan = struct { +/// Device bytes of n streams at positions: the round's scratch, slots, the backend's, and a drafter's bytes and rings. +pub const Plan = struct { w: *const wts.Weights, k: *const fwd.Kernels, positions: usize, + drafter: ?dfl.Config = null, - fn bytes(p: Plan, n: usize) !u64 { - return fwd.Model.openBytes(p.w, p.k, p.positions, n, be.round_rows) + be.Ripple.openBytes(p.w.config.vocab, n); + pub fn bytes(p: Plan, n: usize) !u64 { + const draft = if (p.drafter) |c| dfl.openBytes(&c, p.w.config, p.k.lane.clusters, n) else 0; + return fwd.Model.openBytes(p.w, p.k, p.positions, n, be.round_rows) + be.Ripple.openBytes(p.w.config.vocab, n) + draft; } }; +/// The streams open makes in room (fit's count) with the drafter's bytes; each refusal is logged with its sizes. +pub fn admitted(room: u64, asked: u32, fixed: bool, context: usize, plain: Plan, drafter: ?dfl.Config) !usize { + var plan = plain; + plan.drafter = drafter; + return fit(room, asked, fixed, plan) catch |e| { + if (e == error.ParallelPastMemory) { + const most = fit(room, asked, false, plan) catch 0; + std.log.err("--parallel {d} needs {d:.2} GiB at a {d}-token context{s}, and the CUDA memory budget leaves {d:.2} GiB after the weights: {d} stream{s} fit", .{ asked, gib(try plan.bytes(asked)), context, if (drafter != null) " with the DFlash2 drafter" else "", gib(room), most, if (most == 1) "" else "s" }); + } + // a drafter that leaves no room for one stream is refused by name + if (e == error.NoStreamFits) { + if (drafter != null and (fit(room, 1, false, plain) catch 0) > 0) { + std.log.err("--drafter: the DFlash2 drafter needs {d:.2} GiB beside one Ripple stream's {d:.2} GiB at a {d}-token context; the CUDA memory budget leaves {d:.2} GiB after the weights", .{ gib(try plan.bytes(1) - try plain.bytes(1)), gib(try plain.bytes(1)), context, gib(room) }); + return error.DrafterPastMemory; + } + std.log.err("ripple: one stream at a {d}-token context needs {d:.2} GiB of caches and scratch past the weights; the CUDA memory budget leaves {d:.2} GiB", .{ context, gib(try plan.bytes(1)), gib(room) }); + } + return e; + }; +} + /// The checkpoint through the CUDA gate, the kernels and a stream; the forward is made by the caller. fn begin(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: []const u8) !*Owned { const own = try gpa.create(Owned); @@ -104,6 +129,7 @@ fn begin(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: []co own.k = try fwd.Kernels.load(ctx); errdefer own.k.deinit(); own.s = try cuda.Stream.init(ctx.d, false); + own.draft = null; return own; } @@ -146,20 +172,15 @@ pub fn open(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: [ const positions = be.physical(try contextOf(o.context)); const own = try begin(gpa, io, ctx, dir); errdefer abandon(own); - const plan: Plan = .{ .w = &own.w, .k = &own.k, .positions = positions }; - const room = roomOf(o.room); - const n = fit(room, o.lanes, o.lanes_fixed, plan) catch |e| { - if (e == error.ParallelPastMemory) { - const most = fit(room, o.lanes, false, plan) catch 0; - std.log.err("--parallel {d} needs {d:.2} GiB at a {d}-token context, and the CUDA memory budget leaves {d:.2} GiB after the weights: {d} stream{s} fit", .{ o.lanes, gib(try plan.bytes(o.lanes)), o.context, gib(room), most, if (most == 1) "" else "s" }); - } - if (e == error.NoStreamFits) std.log.err("ripple: one stream at a {d}-token context needs {d:.2} GiB of caches and scratch past the weights; the CUDA memory budget leaves {d:.2} GiB", .{ o.context, gib(try plan.bytes(1)), gib(room) }); - return e; - }; + // the drafter's config (refused by name) before the streams, so its bytes are admitted with theirs + const drafter: ?dfl.Config = if (o.drafts and o.drafter != null) try dfl.readConfig(gpa, io, o.drafter.?, &own.w.config) else null; + const plain: Plan = .{ .w = &own.w, .k = &own.k, .positions = positions }; + const n = try admitted(roomOf(o.room), o.lanes, o.lanes_fixed, o.context, plain, drafter); own.m = try fwd.Model.init(gpa, ctx.d, own.s, &own.w, &own.k, positions, n, be.round_rows); errdefer own.m.deinit(); own.rb = try be.Ripple.init(gpa, ctx.d, &own.m); std.log.info("Ripple on CUDA: {d} stream{s} of {d} positions (a {d}-token context and a {d}-row verify reserve), rounds of {d} rows, prompt chunks of {d}", .{ n, if (n == 1) "" else "s", positions, o.context, be.reserve, be.round_rows, fwd.prompt_rows }); + if (drafter) |dc| std.log.info("Ripple on CUDA: {d:.2} GiB kept for the DFlash2 drafter's weights, scratch and {d} streams' rings", .{ gib(dfl.openBytes(&dc, own.w.config, own.k.lane.clusters, n)), n }); return .{ .backend = own.rb.backend(), .facts = own.rb.facts(), @@ -176,6 +197,46 @@ fn release(p: *anyopaque) void { closeOwned(@ptrCast(@alignCast(p))); } +/// The drafter the native host serves through the lane core's Drafted wrapper (Qwen's shape). +pub const Opened = struct { + drafter: lanes.drafter.Drafter, + ctx: *anyopaque, + close: *const fn (*anyopaque) void, + reserve: *const fn (*anyopaque, u32) anyerror!void, + prepare: ?struct { ctx: *anyopaque, run: *const fn (*anyopaque) anyerror!lanes.drafter.Facts, bytes: usize } = null, + first_rows: bool = true, // logprobs: the first token's row from the target, through cuda_drafted.wrap +}; + +/// --drafter's folder over open p's streams, before any stream or graph; served bf16 as published, bits unread. +pub fn openDrafter(gpa: std.mem.Allocator, io: std.Io, p: *anyopaque, dir: []const u8, bits: u8) !Opened { + _ = bits; + const own: *Owned = @ptrCast(@alignCast(p)); + if (own.draft != null or own.rb.lanes.count() != 0) return error.TapsAfterStreams; + own.draft = try dfl.Drafter.open(gpa, io, &own.m, dir, own.m.arena.slots); + return .{ .drafter = own.draft.?.drafter(), .ctx = own, .close = closeDrafter, .reserve = reserveDrafter, .prepare = .{ .ctx = own, .run = calibrateDrafter, .bytes = 0 } }; +} + +fn closeDrafter(p: *anyopaque) void { + const own: *Owned = @ptrCast(@alignCast(p)); + if (own.draft) |d| d.deinit(); + own.draft = null; +} + +fn reserveDrafter(p: *anyopaque, streams: u32) anyerror!void { + const own: *Owned = @ptrCast(@alignCast(p)); + try own.draft.?.reserve(streams); +} + +/// The target's verify windows timed before the first stream, into the drafter's facts (the depth rule's prices). +pub fn calibrateDrafter(p: *anyopaque) anyerror!lanes.drafter.Facts { + const own: *Owned = @ptrCast(@alignCast(p)); + const d = own.draft orelse return error.MissingCalibrationDrafter; + if (own.rb.lanes.count() != 0) return error.WindowsAfterStreams; + try d.timeWindows(); + try dshared.time(d); + return d.facts(); +} + /// Whether a request's caches could start now (the lane host's admission, on its engine thread). pub fn fits(p: *anyopaque, prompt: u32, max_tokens: u32) bool { const own: *const Owned = @ptrCast(@alignCast(p)); @@ -214,12 +275,15 @@ pub fn explain(_: ?*anyopaque, err: anyerror) ?[]const u8 { error.ParallelPastMemory => "--parallel: the CUDA memory budget fits fewer Ripple streams than asked (each stream's caches are allocated at load): lower --parallel or --context, serve --parallel auto, or adjust TENSORFOLD_MEMORY_RESERVE_GIB / TENSORFOLD_CUDA_MEMORY_LIMIT_GB", error.SegmentsUnsupported => "--segments: Ripple on CUDA runs its prompt chunks one after another: serve without --segments", error.NoDraftHead => "Ripple on CUDA has no draft head: drafts come from the prompt's own text only", - error.StructuresUnsupported => "structured output is not built for Ripple on CUDA yet", error.CapturedKernels => "Ripple runs on the engine's own kernels: unset TENSORFOLD_CUDA_KERNELS", error.BuiltWithoutKernels => "this build carries no CUDA kernel images: build with -Dnvcc", error.RicursiveCudaNeedsNvfp4 => "Ripple on CUDA serves the NVFP4 release (ModelOpt W4A16 MLPs, bf16 attention): the BF16 checkpoint's 130 GB do not fit GB10", error.UnsupportedRicursiveCudaShape => "this Ripple checkpoint's shape is not one the CUDA kernels take (group of 2 to 16 query heads in pairs, hidden size at most 8,192, widths in whole 128s)", error.Unimplemented => "Ripple's CUDA global-layer decode is not in this build yet", + error.DrafterPastMemory => "--drafter: the CUDA memory budget fits no Ripple stream beside the DFlash2 drafter's weights and buffers at this context: lower --context, serve without --drafter, or adjust TENSORFOLD_MEMORY_RESERVE_GIB / TENSORFOLD_CUDA_MEMORY_LIMIT_GB", + error.NotRippleDFlash2 => "--drafter: the folder is not a DFlash2 drafter (DFlash2DraftModel); Ripple takes ricursiveAI/Ripple-65B-Preview-DFlash2", + error.UnqualifiedRippleDFlash2 => "--drafter: the folder is not the drafter checked against this Ripple (ricursiveAI/Ripple-65B-Preview-DFlash2's geometry and taps)", + error.UnsupportedRicursiveDFlash2Shape => "--drafter: this DFlash2 drafter's shape is not one Ripple's CUDA drafter kernels take (16-row blocks, whole groups of 128-wide heads, a vocabulary of at most 131,072)", else => null, }; } @@ -231,10 +295,10 @@ test "ricursive cuda native: a reply thinks or answers bare, with no thinking bu } test "ricursive cuda native: every refusal of its own is worded, the rest left to the server" { - for ([_]anyerror{ error.PastContext, error.NoFreeSlot, error.NoStreamFits, error.ParallelPastRound, error.ParallelPastMemory, error.SegmentsUnsupported, error.NoDraftHead, error.StructuresUnsupported, error.CapturedKernels, error.BuiltWithoutKernels, error.RicursiveCudaNeedsNvfp4, error.UnsupportedRicursiveCudaShape, error.Unimplemented }) |e| { + for ([_]anyerror{ error.PastContext, error.NoFreeSlot, error.NoStreamFits, error.ParallelPastRound, error.ParallelPastMemory, error.SegmentsUnsupported, error.NoDraftHead, error.CapturedKernels, error.BuiltWithoutKernels, error.RicursiveCudaNeedsNvfp4, error.UnsupportedRicursiveCudaShape, error.Unimplemented, error.DrafterPastMemory, error.NotRippleDFlash2, error.UnqualifiedRippleDFlash2, error.UnsupportedRicursiveDFlash2Shape }) |e| { try std.testing.expect(explain(null, e) != null); } - for ([_]anyerror{ error.OutOfMemory, error.SamplingUnsupported, error.LogprobsUnsupported, error.WindowTooWide }) |e| { + for ([_]anyerror{ error.OutOfMemory, error.SamplingUnsupported, error.LogprobsUnsupported, error.StructuresUnsupported, error.InvalidGrammarMasks, error.WindowTooWide }) |e| { try std.testing.expect(explain(null, e) == null); } } @@ -292,6 +356,32 @@ test "ricursive cuda native: streams at a context on GB10 by the release's slot try std.testing.expect(try fit(room, 8, false, Slots{ .c = c, .positions = be.physical(262144), .fixed = scratch }) < 8); } +test "ricursive cuda native: the DFlash2 drafter's bytes at 32,768 positions on GB10 and the streams they leave" { + var c = try cfg.parse(std.testing.allocator, @embedFile("fixtures/config.json")); + c.fp4_mlp = true; + const dc = try @import("dflash2_spec.zig").parse(std.testing.allocator, @embedFile("fixtures/dflash2_config.json"), &c); + const room = gb10_bytes - wts.deviceBytes(c); + const Slots = struct { + c: cfg.Config, + positions: usize, + drafter: ?dfl.Config, + fn bytes(p: @This(), n: usize) !u64 { + const draft = if (p.drafter) |d| dfl.openBytes(&d, p.c, true, n) else 0; + return 1_400_000_000 + fwd.Arena.bytes(p.c, p.positions, n) + be.Ripple.openBytes(p.c.vocab, n) + draft; + } + }; + const plain: Slots = .{ .c = c, .positions = be.physical(32768), .drafter = null }; + const drafted: Slots = .{ .c = c, .positions = be.physical(32768), .drafter = dc }; + // 8 streams of a 32k context and the drafter fit GB10 after the target's weights + try std.testing.expectEqual(@as(usize, 8), try fit(room, 8, false, plain)); + try std.testing.expectEqual(@as(usize, 8), try fit(room, 8, false, drafted)); + for (1..9) |n| try std.testing.expectEqual(dfl.openBytes(&dc, c, true, n), try drafted.bytes(n) - try plain.bytes(n)); + // at 128k the drafter's bytes leave one stream fewer + const long_plain: Slots = .{ .c = c, .positions = be.physical(131072), .drafter = null }; + const long_drafted: Slots = .{ .c = c, .positions = be.physical(131072), .drafter = dc }; + try std.testing.expectEqual(try fit(room, 8, false, long_plain) - 1, try fit(room, 8, false, long_drafted)); +} + test "the prompt cache's hooks compile against the store's vtable" { const pc: struct { bytes: *const fn (*anyopaque, u32) u64, save: *const fn (*anyopaque, ?*anyopaque, u32) anyerror!*anyopaque, restore: *const fn (*anyopaque, ?*anyopaque, *anyopaque) anyerror!void, drop: *const fn (*anyopaque, *anyopaque) void } = .{ .bytes = snap_bytes, .save = snap_save, .restore = snap_restore, .drop = snap_drop }; try std.testing.expect(@intFromPtr(pc.save) != 0); diff --git a/zig/src/families/ricursive/dflash2_config.zig b/zig/src/families/ricursive/dflash2_config.zig index 57513bb0048..b5e54a3ae27 100644 --- a/zig/src/families/ricursive/dflash2_config.zig +++ b/zig/src/families/ricursive/dflash2_config.zig @@ -4,9 +4,9 @@ const lane = @import("lanes"); const ck = @import("../../core/checkpoint_metal.zig"); const wts = @import("weights.zig"); const cfg = @import("config.zig"); +const spec = @import("dflash2_spec.zig"); -/// The release's 16,384-token draft window: the global layer's training rows (`inference/server/README.md`). -pub const global_window = 16384; +pub const global_window = spec.global_window; /// Streams a drafted server serves at most: each stream drafts in its own pass, so more tie plain, then trail it. pub const max_streams = 2; @@ -22,129 +22,11 @@ pub fn streams(lanes: u32, named: bool) ?u32 { if (!named) return max_streams; return if (lanes > max_streams) null else @max(lanes, 1); } -/// Layers, tapped target layers and convolution taps this drafter has (the release's). -pub const max_layers = 5; -pub const max_taps = 5; - -pub const Config = struct { - layers: u32, - heads: u32, - kv_heads: u32, - hidden: u32, - ffn: u32, - vocab: u32, - window: u32, // the sliding layers' window - block: u32, - mask: u32, - rank: u32, - top: u32, - group: u32, - conv: u32, // the block convolution's taps - taps: [max_taps]u32, - global: [max_layers]bool = @splat(false), // full attention over the draft window - rope: [max_layers]bool = @splat(true), // false on the NoPE layer - theta: f32, - eps: f32, - - /// Keys a layer sees before a row: the sliding window, or the draft window on the global layer. - pub fn span(c: *const Config, l: usize) u32 { - return if (c.global[l]) global_window else c.window; - } - - /// A layer's ring of keys: its span and a block past it, whole 128-key blocks. - pub fn ring(c: *const Config, l: usize) u32 { - return std.mem.alignForward(u32, c.span(l) + c.block, 128); - } - - /// The coefficients a row's kernel projection writes: [side][tap][group]. - pub fn dyn(c: *const Config) u32 { - return 2 * c.conv * (c.hidden / c.group); - } -}; - -pub const Error = error{ NotRippleDFlash2, UnqualifiedRippleDFlash2 } || std.mem.Allocator.Error; - -/// The drafter's config.json; `target` its Ripple: the published drafter's geometry exactly, or a refusal. -pub fn parse(gpa: std.mem.Allocator, bytes: []const u8, target: *const cfg.Config) Error!Config { - var doc = std.json.parseFromSlice(std.json.Value, gpa, bytes, .{}) catch return error.NotRippleDFlash2; - defer doc.deinit(); - if (doc.value != .object) return error.NotRippleDFlash2; - const o = doc.value.object; - const arch = o.get("architectures") orelse return error.NotRippleDFlash2; - if (arch != .array or arch.array.items.len != 1 or arch.array.items[0] != .string or !std.mem.eql(u8, arch.array.items[0].string, "DFlash2DraftModel")) return error.NotRippleDFlash2; - const d = o.get("dflash_config") orelse return error.NotRippleDFlash2; - if (d != .object) return error.NotRippleDFlash2; - const dc = d.object; - var c: Config = .{ - .layers = try int(o, "num_hidden_layers"), - .heads = try int(o, "num_attention_heads"), - .kv_heads = try int(o, "num_key_value_heads"), - .hidden = try int(o, "hidden_size"), - .ffn = try int(o, "intermediate_size"), - .vocab = try int(o, "vocab_size"), - .window = try int(o, "sliding_window"), - .block = try int(dc, "block_size"), - .mask = try int(dc, "mask_token_id"), - .rank = try int(dc, "selector_rank"), - .top = try int(dc, "selector_top_k"), - .group = try int(dc, "conv_group_size"), - .conv = try int(dc, "conv_kernel_size"), - .taps = undefined, - .theta = try float(o, "rope_theta"), - .eps = try float(o, "rms_norm_eps"), - }; - const taps = dc.get("target_layer_ids") orelse return error.NotRippleDFlash2; - if (taps != .array or taps.array.items.len != max_taps) return error.UnqualifiedRippleDFlash2; - for (taps.array.items, &c.taps) |x, *y| { - if (x != .integer or x.integer < 0 or x.integer >= target.layers) return error.UnqualifiedRippleDFlash2; - y.* = @intCast(x.integer); - } - if (c.layers != max_layers) return error.UnqualifiedRippleDFlash2; - const types = o.get("layer_types") orelse return error.NotRippleDFlash2; - if (types != .array or types.array.items.len != c.layers) return error.UnqualifiedRippleDFlash2; - for (types.array.items, 0..) |x, i| { - if (x != .string) return error.UnqualifiedRippleDFlash2; - if (std.mem.eql(u8, x.string, "full_attention")) c.global[i] = true else if (!std.mem.eql(u8, x.string, "sliding_attention")) return error.UnqualifiedRippleDFlash2; - } - // the NoPE layer: `no_rope_layers` in the drafter's config.json - if (o.get("no_rope_layers")) |nr| { - if (nr != .array) return error.UnqualifiedRippleDFlash2; - for (nr.array.items) |x| { - if (x != .integer or x.integer < 0 or x.integer >= c.layers) return error.UnqualifiedRippleDFlash2; - c.rope[@intCast(x.integer)] = false; - } - } - if (!(try qualified(o, &c, target))) return error.UnqualifiedRippleDFlash2; - return c; -} - -/// The published drafter's shape beside this target, the one the kernels and the release's server were checked at. -fn qualified(o: std.json.ObjectMap, c: *const Config, target: *const cfg.Config) Error!bool { - if ((try int(o, "head_dim")) != cfg.head_dim) return false; - if (o.get("attention_bias")) |b| if (b != .bool or b.bool) return false; - if (o.get("ffn_clamp_threshold")) |x| if (x != .null) return false; // the MLP runs unclamped - const expected = [_]bool{ false, false, false, false, true }; - const roped = [_]bool{ true, true, true, true, false }; - return c.hidden == target.hidden and c.vocab == target.vocab and c.mask < c.vocab and c.heads == 80 and - c.kv_heads == 8 and c.ffn == 40960 and c.window == 4096 and c.block == 16 and c.rank == 256 and c.top == 32 and - c.group == 16 and c.conv == 4 and c.hidden % c.group == 0 and c.theta == 10000 and - std.mem.eql(bool, &c.global, &expected) and std.mem.eql(bool, &c.rope, &roped); -} - -fn int(o: std.json.ObjectMap, k: []const u8) Error!u32 { - const v = o.get(k) orelse return error.NotRippleDFlash2; - if (v != .integer or v.integer <= 0 or v.integer > std.math.maxInt(u32)) return error.NotRippleDFlash2; - return @intCast(v.integer); -} - -fn float(o: std.json.ObjectMap, k: []const u8) Error!f32 { - const v = o.get(k) orelse return error.NotRippleDFlash2; - return switch (v) { - .integer => |i| @floatFromInt(i), - .float => |f| @floatCast(f), - else => error.NotRippleDFlash2, - }; -} +pub const max_layers = spec.max_layers; +pub const max_taps = spec.max_taps; +pub const Config = spec.Config; +pub const Error = spec.Error; +pub const parse = spec.parse; pub const Conv = struct { base: wts.Tensor, proj: wts.Dense }; pub const Layer = struct { @@ -209,50 +91,6 @@ pub fn load(c: *const ck.Checkpoint, f: *const Config) !Weights { return w; } -test "ricursive dflash2: the published drafter's config is qualified beside Ripple, another refused" { - const a = std.testing.allocator; - const target = try cfg.parse(a, @embedFile("fixtures/config.json")); - const bytes = @embedFile("fixtures/dflash2_config.json"); - const c = try parse(a, bytes, &target); - try std.testing.expectEqualSlices(u32, &.{ 1, 20, 39, 58, 77 }, &c.taps); - try std.testing.expectEqual(@as(u32, 4224), c.ring(0)); - try std.testing.expectEqual(@as(u32, 16512), c.ring(4)); - try std.testing.expectEqual(@as(u32, 2560), c.dyn()); - try std.testing.expect(!c.rope[4] and c.rope[3] and c.global[4] and !c.global[0]); - const other = try std.mem.replaceOwned(u8, a, bytes, "\"block_size\": 16", "\"block_size\": 8"); - defer a.free(other); - try std.testing.expectError(error.UnqualifiedRippleDFlash2, parse(a, other, &target)); - const clamped = try std.mem.replaceOwned(u8, a, bytes, "\"no_rope_layers\"", "\"ffn_clamp_threshold\": 20, \"no_rope_layers\""); - defer a.free(clamped); - try std.testing.expectError(error.UnqualifiedRippleDFlash2, parse(a, clamped, &target)); - const not = try std.mem.replaceOwned(u8, a, bytes, "DFlash2DraftModel", "Qwen3ForCausalLM"); - defer a.free(not); - try std.testing.expectError(error.NotRippleDFlash2, parse(a, not, &target)); -} - -test "ricursive dflash2: a drafter beside another target, past its layers or with its layers moved is refused" { - const a = std.testing.allocator; - const target = try cfg.parse(a, @embedFile("fixtures/config.json")); - const bytes = @embedFile("fixtures/dflash2_config.json"); - var wider = target; - wider.hidden = 6144; - try std.testing.expectError(error.UnqualifiedRippleDFlash2, parse(a, bytes, &wider)); - var other_vocab = target; - other_vocab.vocab = 131072; - try std.testing.expectError(error.UnqualifiedRippleDFlash2, parse(a, bytes, &other_vocab)); - const cases = [_][2][]const u8{ - .{ " 77\n ]", " 80\n ]" }, // a tap at the target's layer count - .{ "\"no_rope_layers\": [\n 4\n ]", "\"no_rope_layers\": [\n 3\n ]" }, // the NoPE layer moved - .{ "\"sliding_attention\",\n \"full_attention\"", "\"full_attention\",\n \"sliding_attention\"" }, // the global layer moved - }; - for (cases) |c| { - const changed = try std.mem.replaceOwned(u8, a, bytes, c[0], c[1]); - defer a.free(changed); - try std.testing.expect(!std.mem.eql(u8, changed, bytes)); - try std.testing.expectError(error.UnqualifiedRippleDFlash2, parse(a, changed, &target)); - } -} - test "ricursive dflash2: two streams when --parallel is not named, a named count past two refused" { try std.testing.expectEqual(@as(?u32, max_streams), streams(8, false)); try std.testing.expectEqual(@as(?u32, max_streams), streams(1, false)); diff --git a/zig/src/families/ricursive/dflash2_spec.zig b/zig/src/families/ricursive/dflash2_spec.zig new file mode 100644 index 00000000000..07027561123 --- /dev/null +++ b/zig/src/families/ricursive/dflash2_spec.zig @@ -0,0 +1,173 @@ +//! ricursiveAI's DFlash2 drafter for Ripple: its config as published, parsed and qualified, without Metal for CUDA. +const std = @import("std"); +const cfg = @import("config.zig"); + +/// The release's 16,384-token draft window: the global layer's training rows (`inference/server/README.md`). +pub const global_window = 16384; +/// Layers, tapped target layers and convolution taps this drafter has (the release's). +pub const max_layers = 5; +pub const max_taps = 5; + +pub const Config = struct { + layers: u32, + heads: u32, + kv_heads: u32, + hidden: u32, + ffn: u32, + vocab: u32, + window: u32, // the sliding layers' window + block: u32, + mask: u32, + rank: u32, + top: u32, + group: u32, + conv: u32, // the block convolution's taps + taps: [max_taps]u32, + global: [max_layers]bool = @splat(false), // full attention over the draft window + rope: [max_layers]bool = @splat(true), // false on the NoPE layer + theta: f32, + eps: f32, + + /// Keys a layer sees before a row: the sliding window, or the draft window on the global layer. + pub fn span(c: *const Config, l: usize) u32 { + return if (c.global[l]) global_window else c.window; + } + + /// A layer's ring of keys: its span and a block past it, whole 128-key blocks. + pub fn ring(c: *const Config, l: usize) u32 { + return std.mem.alignForward(u32, c.span(l) + c.block, 128); + } + + /// The coefficients a row's kernel projection writes: [side][tap][group]. + pub fn dyn(c: *const Config) u32 { + return 2 * c.conv * (c.hidden / c.group); + } +}; + +pub const Error = error{ NotRippleDFlash2, UnqualifiedRippleDFlash2 } || std.mem.Allocator.Error; + +/// The drafter's config.json; `target` its Ripple: the published drafter's geometry exactly, or a refusal. +pub fn parse(gpa: std.mem.Allocator, bytes: []const u8, target: *const cfg.Config) Error!Config { + var doc = std.json.parseFromSlice(std.json.Value, gpa, bytes, .{}) catch return error.NotRippleDFlash2; + defer doc.deinit(); + if (doc.value != .object) return error.NotRippleDFlash2; + const o = doc.value.object; + const arch = o.get("architectures") orelse return error.NotRippleDFlash2; + if (arch != .array or arch.array.items.len != 1 or arch.array.items[0] != .string or !std.mem.eql(u8, arch.array.items[0].string, "DFlash2DraftModel")) return error.NotRippleDFlash2; + const d = o.get("dflash_config") orelse return error.NotRippleDFlash2; + if (d != .object) return error.NotRippleDFlash2; + const dc = d.object; + var c: Config = .{ + .layers = try int(o, "num_hidden_layers"), + .heads = try int(o, "num_attention_heads"), + .kv_heads = try int(o, "num_key_value_heads"), + .hidden = try int(o, "hidden_size"), + .ffn = try int(o, "intermediate_size"), + .vocab = try int(o, "vocab_size"), + .window = try int(o, "sliding_window"), + .block = try int(dc, "block_size"), + .mask = try int(dc, "mask_token_id"), + .rank = try int(dc, "selector_rank"), + .top = try int(dc, "selector_top_k"), + .group = try int(dc, "conv_group_size"), + .conv = try int(dc, "conv_kernel_size"), + .taps = undefined, + .theta = try float(o, "rope_theta"), + .eps = try float(o, "rms_norm_eps"), + }; + const taps = dc.get("target_layer_ids") orelse return error.NotRippleDFlash2; + if (taps != .array or taps.array.items.len != max_taps) return error.UnqualifiedRippleDFlash2; + for (taps.array.items, &c.taps) |x, *y| { + if (x != .integer or x.integer < 0 or x.integer >= target.layers) return error.UnqualifiedRippleDFlash2; + y.* = @intCast(x.integer); + } + if (c.layers != max_layers) return error.UnqualifiedRippleDFlash2; + const types = o.get("layer_types") orelse return error.NotRippleDFlash2; + if (types != .array or types.array.items.len != c.layers) return error.UnqualifiedRippleDFlash2; + for (types.array.items, 0..) |x, i| { + if (x != .string) return error.UnqualifiedRippleDFlash2; + if (std.mem.eql(u8, x.string, "full_attention")) c.global[i] = true else if (!std.mem.eql(u8, x.string, "sliding_attention")) return error.UnqualifiedRippleDFlash2; + } + // the NoPE layer: `no_rope_layers` in the drafter's config.json + if (o.get("no_rope_layers")) |nr| { + if (nr != .array) return error.UnqualifiedRippleDFlash2; + for (nr.array.items) |x| { + if (x != .integer or x.integer < 0 or x.integer >= c.layers) return error.UnqualifiedRippleDFlash2; + c.rope[@intCast(x.integer)] = false; + } + } + if (!(try qualified(o, &c, target))) return error.UnqualifiedRippleDFlash2; + return c; +} + +/// The published drafter's shape beside this target, the one the kernels and the release's server were checked at. +fn qualified(o: std.json.ObjectMap, c: *const Config, target: *const cfg.Config) Error!bool { + if ((try int(o, "head_dim")) != cfg.head_dim) return false; + if (o.get("attention_bias")) |b| if (b != .bool or b.bool) return false; + if (o.get("ffn_clamp_threshold")) |x| if (x != .null) return false; // the MLP runs unclamped + const expected = [_]bool{ false, false, false, false, true }; + const roped = [_]bool{ true, true, true, true, false }; + return c.hidden == target.hidden and c.vocab == target.vocab and c.mask < c.vocab and c.heads == 80 and + c.kv_heads == 8 and c.ffn == 40960 and c.window == 4096 and c.block == 16 and c.rank == 256 and c.top == 32 and + c.group == 16 and c.conv == 4 and c.hidden % c.group == 0 and c.theta == 10000 and + std.mem.eql(bool, &c.global, &expected) and std.mem.eql(bool, &c.rope, &roped); +} + +fn int(o: std.json.ObjectMap, k: []const u8) Error!u32 { + const v = o.get(k) orelse return error.NotRippleDFlash2; + if (v != .integer or v.integer <= 0 or v.integer > std.math.maxInt(u32)) return error.NotRippleDFlash2; + return @intCast(v.integer); +} + +fn float(o: std.json.ObjectMap, k: []const u8) Error!f32 { + const v = o.get(k) orelse return error.NotRippleDFlash2; + return switch (v) { + .integer => |i| @floatFromInt(i), + .float => |f| @floatCast(f), + else => error.NotRippleDFlash2, + }; +} + +test "ricursive dflash2: the published drafter's config is qualified beside Ripple, another refused" { + const a = std.testing.allocator; + const target = try cfg.parse(a, @embedFile("fixtures/config.json")); + const bytes = @embedFile("fixtures/dflash2_config.json"); + const c = try parse(a, bytes, &target); + try std.testing.expectEqualSlices(u32, &.{ 1, 20, 39, 58, 77 }, &c.taps); + try std.testing.expectEqual(@as(u32, 4224), c.ring(0)); + try std.testing.expectEqual(@as(u32, 16512), c.ring(4)); + try std.testing.expectEqual(@as(u32, 2560), c.dyn()); + try std.testing.expect(!c.rope[4] and c.rope[3] and c.global[4] and !c.global[0]); + const other = try std.mem.replaceOwned(u8, a, bytes, "\"block_size\": 16", "\"block_size\": 8"); + defer a.free(other); + try std.testing.expectError(error.UnqualifiedRippleDFlash2, parse(a, other, &target)); + const clamped = try std.mem.replaceOwned(u8, a, bytes, "\"no_rope_layers\"", "\"ffn_clamp_threshold\": 20, \"no_rope_layers\""); + defer a.free(clamped); + try std.testing.expectError(error.UnqualifiedRippleDFlash2, parse(a, clamped, &target)); + const not = try std.mem.replaceOwned(u8, a, bytes, "DFlash2DraftModel", "Qwen3ForCausalLM"); + defer a.free(not); + try std.testing.expectError(error.NotRippleDFlash2, parse(a, not, &target)); +} + +test "ricursive dflash2: a drafter beside another target, past its layers or with its layers moved is refused" { + const a = std.testing.allocator; + const target = try cfg.parse(a, @embedFile("fixtures/config.json")); + const bytes = @embedFile("fixtures/dflash2_config.json"); + var wider = target; + wider.hidden = 6144; + try std.testing.expectError(error.UnqualifiedRippleDFlash2, parse(a, bytes, &wider)); + var other_vocab = target; + other_vocab.vocab = 131072; + try std.testing.expectError(error.UnqualifiedRippleDFlash2, parse(a, bytes, &other_vocab)); + const cases = [_][2][]const u8{ + .{ " 77\n ]", " 80\n ]" }, // a tap at the target's layer count + .{ "\"no_rope_layers\": [\n 4\n ]", "\"no_rope_layers\": [\n 3\n ]" }, // the NoPE layer moved + .{ "\"sliding_attention\",\n \"full_attention\"", "\"full_attention\",\n \"sliding_attention\"" }, // the global layer moved + }; + for (cases) |c| { + const changed = try std.mem.replaceOwned(u8, a, bytes, c[0], c[1]); + defer a.free(changed); + try std.testing.expect(!std.mem.eql(u8, changed, bytes)); + try std.testing.expectError(error.UnqualifiedRippleDFlash2, parse(a, changed, &target)); + } +} diff --git a/zig/src/native/cuda.zig b/zig/src/native/cuda.zig index b4dd519a76d..cb5c7b1875e 100644 --- a/zig/src/native/cuda.zig +++ b/zig/src/native/cuda.zig @@ -481,7 +481,7 @@ fn openWith(comptime F: type, a: Allocator, gpa: Allocator, io: std.Io, asked: a .logprobs = served.backend.vtable.first_row != null, .prompt_logprobs = served.backend.vtable.prompt_rows, .penalties = served.backend.penalties, - .structures = served.backend.vtable.first_masked != null, + .structures = if (comptime std.mem.eql(u8, F.model_type, "ricursive")) loaded.backend.vtable.first_masked != null else served.backend.vtable.first_masked != null, .vision = if (@hasField(@TypeOf(loaded), "vision")) vision_offer.offer(loaded.vision, o.vision) else null, .audio = if (@hasField(@TypeOf(loaded), "audio")) vision_offer.audio(loaded.audio) else null, .admit = admit, diff --git a/zig/src/native/cuda_drafted.zig b/zig/src/native/cuda_drafted.zig index 4919af89da5..783e9c26888 100644 --- a/zig/src/native/cuda_drafted.zig +++ b/zig/src/native/cuda_drafted.zig @@ -91,6 +91,8 @@ pub fn wrap(comptime F: type, a: Allocator, gpa: Allocator, io: std.Io, loaded: return null; }; drafted_initialized = true; + // a family whose Opened asks for it serves logprobs' first rows through the wrapper; others keep main's table + if (@hasField(@TypeOf(opened), "first_rows")) h.drafted.first_rows = opened.first_rows; s.source = .{ .kind = opened.drafter.kind, .name = o.drafter_name orelse dir }; s.backend = h.drafted.backend(); s.facts = h.drafted.facts(loaded.facts); @@ -154,3 +156,49 @@ test "--mtp-drafts 0 reaches drafter selection so an MTP refusal does not suppre try std.testing.expect(called); try std.testing.expect(served.held == null); } + +/// A drafter with facts and nothing else: wrap reads its facts and kind before any stream. +const FactsOnly = struct { + fn taps(_: *anyopaque) []const u32 { + return &.{}; + } + fn facts(_: *anyopaque) lanes.drafter.Facts { + return .{ .depth = 1, .step_ms = 1 }; + } + fn close(_: *anyopaque) void {} + fn reserve(_: *anyopaque, _: u32) anyerror!void {} +}; + +fn firstRowServed(comptime rows: ?bool, drafts: bool) !bool { + var vt: lanes.drafter.Drafter.VTable = undefined; + vt.taps = FactsOnly.taps; + vt.facts = FactsOnly.facts; + var drafter: lanes.drafter.Drafter = .{ .ptr = &vt, .vtable = &vt }; + const Opened = if (rows) |r| struct { drafter: lanes.drafter.Drafter, ctx: *anyopaque, close: *const fn (*anyopaque) void, reserve: *const fn (*anyopaque, u32) anyerror!void, first_rows: bool = r } else struct { drafter: lanes.drafter.Drafter, ctx: *anyopaque, close: *const fn (*anyopaque) void, reserve: *const fn (*anyopaque, u32) anyerror!void }; + const F = struct { + pub const model_type = "test"; + pub fn openDrafter(_: Allocator, _: std.Io, p: *anyopaque, _: []const u8, _: u8) !Opened { + return .{ .drafter = @as(*lanes.drafter.Drafter, @ptrCast(@alignCast(p))).*, .ctx = p, .close = FactsOnly.close, .reserve = FactsOnly.reserve }; + } + }; + var target: lanes.fake.Fake = .{ .gpa = std.testing.allocator }; + defer target.deinit(); + const Loaded = struct { backend: lanes.backend.Backend, facts: lanes.Model, stream_bytes: usize, ctx: *anyopaque }; + const loaded: Loaded = .{ .backend = target.backend(), .facts = .{}, .stream_bytes = 0, .ctx = &drafter }; + const o: api.Open = .{ .dir = "target", .model_type = F.model_type, .drafter = "drafter", .drafts = drafts }; + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + var problem: []const u8 = ""; + var served = (try wrap(F, arena.allocator(), std.testing.allocator, std.testing.io, loaded, o, &problem)) orelse return error.TestUnexpectedResult; + defer served.close(std.testing.allocator); + try std.testing.expectEqual(drafts, served.held != null); + return served.backend.vtable.first_row != null; +} + +test "--drafter: a family whose Opened asks for first rows serves logprobs' first row drafted and plain" { + try std.testing.expect(try firstRowServed(true, false)); // plain: the family's own table + try std.testing.expect(try firstRowServed(true, true)); // drafted: the wrapper forwards first_row + // a family that does not ask keeps main's wrapper table, without first_row + try std.testing.expect(!try firstRowServed(null, true)); + try std.testing.expect(try firstRowServed(null, false)); +} diff --git a/zig/src/native/cuda_startup_costs.zig b/zig/src/native/cuda_startup_costs.zig index 6a03509ce9f..56ccf9a7466 100644 --- a/zig/src/native/cuda_startup_costs.zig +++ b/zig/src/native/cuda_startup_costs.zig @@ -22,9 +22,12 @@ pub fn calibrate(s: anytype, gpa: std.mem.Allocator, cfg: *lanes.Config) !void { if (!valid(measured.window_costs) or !valid(measured.lane_costs) or measured.window_costs.len < cfg.family_width or measured.lane_costs.len < cfg.family_width) return error.InvalidWindowMeasurements; + for (measured.shared_costs) |c| if (c.width == 0 or !(c.ms > 0) or !std.math.isFinite(c.ms)) return error.InvalidWindowMeasurements; var facts = s.facts; facts.window_costs = measured.window_costs; facts.lane_costs = measured.lane_costs; + // a sweep's shared rounds price rows past the widest window; without them those rows cost one stream's, scaled + if (measured.shared_costs.len > 0) facts.shared_costs = measured.shared_costs; var arena = std.heap.ArenaAllocator.init(gpa); defer arena.deinit(); const fresh = try lanes.Config.init(arena.allocator(), facts, cfg.family_width, cfg.most_drafts); @@ -56,3 +59,29 @@ pub fn room(a: std.mem.Allocator, prepare: ?Prepare, available: u64, problem: *[ } return available - bytes; } + +test "startup costs: a sweep's shared rounds reach the shared table, and a sweep without them leaves it as it was" { + const a = std.testing.allocator; + const Cost = lanes.config.Cost; + var window: [4]Cost = undefined; + for (&window, 1..) |*c, w| c.* = .{ .width = @intCast(w), .ms = 100 + @as(f64, @floatFromInt(w)) }; + const shared = [_]Cost{ .{ .width = 8, .ms = 106 }, .{ .width = 16, .ms = 110 } }; + const Sweep = struct { + facts: lanes.drafter.Facts, + fn run(p: *anyopaque) anyerror!lanes.drafter.Facts { + return @as(*@This(), @ptrCast(@alignCast(p))).facts; + } + }; + const S = struct { facts: lanes.Model, prepare: ?Prepare }; + for ([_]bool{ true, false }) |with_shared| { + var sweep: Sweep = .{ .facts = .{ .depth = 3, .step_ms = 1, .window_costs = &window, .lane_costs = &window, .shared_costs = if (with_shared) &shared else &.{} } }; + const model: lanes.Model = .{ .exact_width = 4, .batch_rows = 16 }; + var s: S = .{ .facts = model, .prepare = .{ .ctx = &sweep, .run = Sweep.run } }; + var cfg = try lanes.Config.init(a, model, 4, 3); + defer cfg.deinit(a); + try calibrate(&s, a, &cfg); + // past the widest window: the timed shared round, or the widest window scaled by rows + try std.testing.expectApproxEqAbs(@as(f64, if (with_shared) 110 else 104.0 * 16.0 / 4.0), cfg.shared_costs.get(16).?, 1e-9); + try std.testing.expectApproxEqAbs(@as(f64, 103), cfg.shared_costs.get(3).?, 1e-9); + } +} diff --git a/zig/tests/cuda/contract_limits.zig b/zig/tests/cuda/contract_limits.zig index deec3bc78e9..53922ad6298 100644 --- a/zig/tests/cuda/contract_limits.zig +++ b/zig/tests/cuda/contract_limits.zig @@ -44,7 +44,7 @@ pub fn image(name: []const u8) error{UnknownContractImage}![]const u8 { if (std.mem.eql(u8, name, "h3_image_prompt")) return &h3_image_prompt.bytes; 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", "topk_rows", "sparse_index", "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", "experts_mxfp4", "nemo_audio", "moss_image", "glm_vision", "idol", "idol_decoder", "lfm3", "lfm2_moe", "lfm2", "dots_mocr", "muse_glue", "muse_attention", "muse_linear", "muse_experts2", "muse_dflash", "muse_dflash2", "ricursive", "ricursive_prep" }) |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", "topk_rows", "sparse_index", "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", "experts_mxfp4", "nemo_audio", "moss_image", "glm_vision", "idol", "idol_decoder", "lfm3", "lfm2_moe", "lfm2", "dots_mocr", "muse_glue", "muse_attention", "muse_linear", "muse_experts2", "muse_dflash", "muse_dflash2", "ricursive", "ricursive_prep", "ricursive_dflash2", "ricursive_dflash2_attn" }) |n| if (std.mem.eql(u8, name, n)) return @field(kk, n); inline for (.{ "inkling2_attn", "inkling2_pattn", "inkling2_ops", "inkling2_rows", "inkling2_experts", "inkling2_modelopt", "inkling2_loop_math", "inkling2_vision", "inkling2_dspark", "inkling2_dflash2" }) |n| if (std.mem.eql(u8, name, n)) return @field(kk, n); inline for (.{ "moss_image_decoder", "moss_image_encoder", "sparse_attention" }) |n| if (std.mem.eql(u8, name, n)) return @field(kk, n); inline for (.{ "zonos3", "zonos3_codec", "zonos3_encoder", "zonos3_teacher" }) |n| if (std.mem.eql(u8, name, n)) return @field(kk, n); diff --git a/zig/tests/cuda/contract_ricursive.zig b/zig/tests/cuda/contract_ricursive.zig index 4888f49060c..7e03ea6faaf 100644 --- a/zig/tests/cuda/contract_ricursive.zig +++ b/zig/tests/cuda/contract_ricursive.zig @@ -1,4 +1,4 @@ -//! Ripple's CUDA kernels under the contract, with controls (ricursive-contract): glue, attention prep, attention. +//! Ripple's CUDA kernels under the contract, with controls (ricursive-contract): glue, prep, attention, grammar mask. const std = @import("std"); const cuda = @import("cuda"); const core = @import("core"); @@ -7,6 +7,7 @@ const check = @import("check.zig"); const glue = @import("contract_ricursive_glue.zig"); const prep = @import("contract_ricursive_prep.zig"); const attn = @import("contract_ricursive_attn.zig"); +const mask = @import("contract_ricursive_mask.zig"); const g = core.contract.gates; @@ -17,6 +18,7 @@ pub const Set = struct { glue: glue.Set = .{}, prep: *prep.Set = undefined, // its own image, and contract_controls' tf_ctl_rc_prep attn: *attn.Set = undefined, // window_attention's image (WindowAttention owns it), tree_attention's (GlobalDecode) + mask: mask.Set = .{}, // sample's image, and contract_controls' tf_ctl_rc_grammar_mask (prep's module) /// The set, its kernels appended to `list`. pub fn init(gpu: check.Gpu, s: cuda.Stream, a: std.mem.Allocator, list: *std.ArrayList(g.Kernel)) !*Set { @@ -29,10 +31,13 @@ pub const Set = struct { set.prep = try prep.Set.init(gpu, s, a, list); errdefer set.prep.deinit(); set.attn = try attn.Set.init(gpu, s, a, list); + errdefer set.attn.deinit(); + try set.mask.init(gpu, s, set.prep.ctl, a, list); return set; } pub fn deinit(set: *Set) void { + set.mask.deinit(); set.attn.deinit(); set.prep.deinit(); set.glue.deinit(); diff --git a/zig/tests/cuda/contract_ricursive_dflash2.zig b/zig/tests/cuda/contract_ricursive_dflash2.zig new file mode 100644 index 00000000000..dc656e5d99c --- /dev/null +++ b/zig/tests/cuda/contract_ricursive_dflash2.zig @@ -0,0 +1,553 @@ +//! Ripple's DFlash2 drafter glue on CUDA under the contract, with controls: embed, add-norm, prep, conv and silu. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const rc = @import("ricursive_cuda"); +const check = @import("check.zig"); +const rig_ = @import("contract_rig.zig"); +const ref = @import("contract_minimax_glue_ref.zig"); // the family-neutral Gated wrapper and fills + +const c = core.contract.spec; +const g = core.contract.gates; +const df = rc.dflash2_kernels; +const Iv = ref.Iv; +const Sums = ref.Sums; +const Kernels = df.Kernels; +const Function = cuda.Function; +const prep_ = @import("contract_ricursive_dflash2_prep.zig"); // the prep kernel: entries, streams' plan, check +const Prep = prep_.Prep; +const PrepCtl = prep_.PrepCtl; +const prep_entries = prep_.prep_entries; + +const hidden = 5120; +const ffn = 40960; +const vocab = 100352; +const block = 16; // rows a stream's block +const taps = 4; +const group = 16; // channels a dynamic tap weight covers +pub const eps: f32 = 1e-6; +const elementwise: c.Tile = .{ .size = 256, .step = 1, .min = 1 }; + +/// The drafter's rows a launch at width n: a block of 16 a stream, a row, 8 streams' blocks, odd tails. +fn rowsAt(comptime counts: []const usize, n: usize, k: usize) [counts.len]c.Shape { + var out: [counts.len]c.Shape = undefined; + for (counts, &out) |r, *s| s.* = .{ .rows = r, .n = n, .k = k }; + return out; +} + +const block_rows = [_]usize{ 16, 1, 128, 7, 48 }; +const embed_rows = rowsAt(&block_rows, hidden, 1); +const add_rows = rowsAt(&block_rows, hidden, hidden); +const norm16_rows = rowsAt(&.{ 2048, 7, 16, 1 }, hidden, hidden); // the context's rows, a prompt chunk at most +const silu_rows = rowsAt(&block_rows, ffn, 2 * ffn); + +pub fn embedSpec(control: bool) c.Spec { + const name = if (control) "control: cuda ricursive_dflash2 tf_rcd_ctl_embed_own_row, row r reads table row r, not ids[r]" else "cuda ricursive tf_rc_embed at scale 1 (the drafter's unscaled embed; R and its copy)"; + return .{ .name = name, .accum = .none, .depth = ref.noSums, .out = .bf16, .tiles = .{ .{}, elementwise, .{} }, .served = &embed_rows }; +} + +/// R and its copy = E[ids], bits unchanged (x * 1.0f is x, and bf16 of a bf16 is itself), over the whole table. +pub const Embed = struct { + f: Function, + ctl: bool = false, + shape: c.Shape = undefined, + table: []u16 = &.{}, + ids: []u32 = &.{}, + dev: [2]u64 = @splat(0), // the table, the ids + out: [2]u64 = @splat(0), // R, the copy + + pub fn spec(self: *const Embed) c.Spec { + return embedSpec(self.ctl); + } + + pub fn control(self: *const Embed) ?g.Gate { + return if (self.ctl) .shapes else null; + } + + pub fn free(self: *Embed, a: std.mem.Allocator) void { + a.free(self.table); + a.free(self.ids); + self.table = &.{}; + self.ids = &.{}; + } + + /// Rows the ids read in [-1, 1), the rest zero; row 0 reads the last row. Non-finite: NaN, +Inf, -Inf in rows 0-2. + pub fn prepare(self: *Embed, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { + if (shape.rows == 0 or shape.n == 0) return false; + self.free(a); + self.shape = shape; + const n = shape.n; + self.ids = try a.alloc(u32, shape.rows); + for (self.ids, 0..) |*id, r| id.* = if (r == 0) vocab - 1 else rng.uintLessThan(u32, vocab); + self.table = try a.alloc(u16, vocab * n); + @memset(self.table, 0); + for (self.ids) |id| for (self.table[@as(usize, id) * n ..][0..n]) |*v| { + v.* = c.toBf16(rng.float(f32) * 2 - 1); + }; + if (fill == .nonfinite) for ([_]f32{ ref.nan, ref.inf, -ref.inf }, 0..) |x, r| if (r < shape.rows) { + self.table[@as(usize, self.ids[r]) * n + (7 * r + 1) % n] = c.toBf16(x); + }; + self.dev = .{ try ref.input(rig, self.table), try ref.input(rig, self.ids) }; + self.out = .{ try rig.output(shape.rows * n * 2), try rig.output(shape.rows * n * 2) }; + return true; + } + + pub fn run(self: *Embed, rig: *rig_.Rig) !void { + try df.embedBy(self.f, rig.s, self.dev[1], self.dev[0], self.out[0], self.out[1], self.shape.rows, self.shape.n); + } + + pub fn count(self: *const Embed) usize { + return 2 * self.shape.rows * self.shape.n; + } + + /// Exact: each output is its table entry. + pub fn solve(self: *const Embed, _: std.mem.Allocator, _: Sums, out: []Iv) !void { + const n = self.shape.n; + const half = self.shape.rows * n; + for (0..self.shape.rows) |r| for (0..n) |i| { + const v = Iv.of(ref.bf(self.table[@as(usize, self.ids[r]) * n + i])); + out[r * n + i] = v; + out[half + r * n + i] = v; + }; + } +}; + +/// tf_rcd_add_norm's forms: the add (R = bf16(R + Y) in place, then X), and norm16 (X = norm(R), R only read). +pub const NormForm = enum { add, norm16 }; + +/// A control's dropped rounding point (ricursive_dflash2.cuh's add_norm bits). +pub const NormPoint = enum { resid, x_row }; + +/// A thread's fma chain (8 values a chunk, a chunk per 2,048 of the row), the warp's 5 shuffles and the block's 5. +fn normDepth(s: c.Shape) usize { + return 8 * ((s.n + 2047) / 2048) + 10; +} + +pub fn normSpec(f: NormForm, drop: ?NormPoint) c.Spec { + const name = if (drop) |p| switch (p) { + .resid => "control: cuda ricursive_dflash2 tf_rcd_add_norm, the norm reads R + Y before its bf16", + .x_row => "control: cuda ricursive_dflash2 tf_rcd_add_norm without bf16(r / rms)", + } else switch (f) { + .add => "cuda ricursive_dflash2 tf_rcd_add_norm (R = bf16(R + Y) in place, then X = norm(R))", + .norm16 => "cuda ricursive_dflash2 tf_rcd_add_norm as norm16 (X = norm(R), R only read)", + }; + const chunks: c.Tile = .{ .size = 2048, .step = 8, .min = 8 }; // a thread's chunk per 2,048 of the row + const served: []const c.Shape = if (f == .add) &add_rows else &norm16_rows; + return .{ .name = name, .accum = .f32, .depth = normDepth, .out = .bf16, .in_place = f == .add, .tiles = .{ .{}, chunks, .{} }, .served = served, .sums = .{} }; +} + +/// Residual rows as bf16: [-1, 1), one in 64 twenty times larger; stress: integers in [-32, 32]. +fn residual(a: std.mem.Allocator, rng: std.Random, n: usize, fill: g.Fill) ![]u16 { + const x = try a.alloc(u16, n); + for (x, 0..) |*v, i| v.* = c.toBf16(if (fill == .stress) ref.int(rng, -32, 32) else (rng.float(f32) * 2 - 1) * (if (i % 64 == 7) @as(f32, 20) else 1)); + return x; +} + +/// NaN, +Inf and -Inf at known places: a row each, row 3 holding both infinities. +fn plant(x: []u16, rows: usize, n: usize) void { + const at = [_][2]usize{ .{ 0, n / 3 }, .{ 1, n / 2 }, .{ 2, n - 1 }, .{ 3, 0 }, .{ 3, n - 1 } }; + const put = [_]f32{ ref.nan, ref.inf, -ref.inf, ref.inf, -ref.inf }; + for (at, put) |p, v| if (p[0] < rows) { + x[p[0] * n + p[1]] = c.toBf16(v); + }; +} + +/// 1 / rms of a row's values (ranges): an fp32 sum of squares over `depth` roundings, then 1 / sqrt(mean + eps). +fn invRms(s: Sums, x: []const Iv, depth: usize, scratch: []f64, sq: []Iv) Iv { + for (sq, x) |*q, v| { + const lo = @min(@abs(v.lo), @abs(v.hi)); + const hi = @max(@abs(v.lo), @abs(v.hi)); + q.* = .{ .m = v.m * v.m, .lo = if (v.lo <= 0 and v.hi >= 0) 0 else lo * lo, .hi = hi * hi }; + } + const total = s.sum(sq, depth, scratch); + return total.div(Iv.of(@floatFromInt(x.len))).add(Iv.of(eps)).rsqrt(); +} + +/// tf_rcd_add_norm on hidden-wide rows: R and w; Y with the add. +pub const AddNorm = struct { + f: Function, + form: NormForm, + drop: ?NormPoint = null, + shape: c.Shape = undefined, + r: []u16 = &.{}, // R before the launch + y: []u16 = &.{}, + w: []u16 = &.{}, + p: df.Norm = undefined, + + pub const sums = {}; + + pub fn spec(self: *const AddNorm) c.Spec { + return normSpec(self.form, self.drop); + } + + pub fn control(self: *const AddNorm) ?g.Gate { + return if (self.drop != null) .shapes else null; + } + + pub fn free(self: *AddNorm, a: std.mem.Allocator) void { + for ([_]*[]u16{ &self.r, &self.y, &self.w }) |s| { + a.free(s.*); + s.* = &.{}; + } + } + + /// Y in [-2, 2), w in [0.5, 1.5); stress: Y zero (R's integers stay whole); non-finite: in Y with the add, else R. + pub fn prepare(self: *AddNorm, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { + if (shape.rows == 0 or shape.n == 0 or shape.n % 8 != 0 or shape.n > df.most_width) return false; + self.free(a); + self.shape = shape; + const rows = shape.rows; + const n = shape.n; + const add = self.form == .add; + self.r = try residual(a, rng, rows * n, fill); + self.y = try ref.bfs(a, rng, if (add) rows * n else 0, -2, 2); + if (fill == .stress) @memset(self.y, 0); + self.w = try ref.bfs(a, rng, n, 0.5, 1.5); + if (fill == .nonfinite) plant(if (add) self.y else self.r, rows, n); + const bytes = rows * n * 2; + self.p = .{ .resid = 0, .w = try ref.input(rig, self.w), .x = 0, .rows = rows, .width = n, .eps = eps }; + if (add) { + self.p.branch = try ref.input(rig, self.y); + self.p.resid = try rig.output(bytes); // in place: restored before each launch + } else self.p.resid = try ref.input(rig, self.r); + self.p.x = try rig.output(bytes); + return true; + } + + pub fn run(self: *AddNorm, rig: *rig_.Rig) !void { + if (self.form == .add) try ref.restore(rig, self.p.resid, std.mem.sliceAsBytes(self.r)); // every run the same pass + try df.normBy(self.f, rig.s, self.p); + } + + pub fn count(self: *const AddNorm) usize { + const outs: usize = if (self.form == .add) 2 else 1; + return outs * self.shape.rows * self.shape.n; + } + + /// The outputs in the order prepare allocates them: R (with the add), X. + pub fn solve(self: *const AddNorm, a: std.mem.Allocator, s: Sums, out: []Iv) !void { + const n = self.shape.n; + const total = self.shape.rows * n; + const buf = try a.alloc(Iv, 2 * n); + defer a.free(buf); + const scratch = try a.alloc(f64, n); + defer a.free(scratch); + const depth = normDepth(self.shape); + const r = buf[0..n]; + const sq = buf[n..]; + const add = self.form == .add; + const lead: usize = if (add) total else 0; + const out_x = out[lead..][0..total]; + for (0..self.shape.rows) |row| { + const o = row * n; + for (r, self.r[o..][0..n]) |*v, h| v.* = Iv.of(ref.bf(h)); + if (add) { + for (r, self.y[o..][0..n]) |*v, h| v.* = v.add(Iv.of(ref.bf(h))).bf(); + @memcpy(out[o..][0..n], r); + } + const inv = invRms(s, r, depth, scratch, sq); + for (out_x[o..][0..n], r, self.w) |*x, v, w| x.* = Iv.of(ref.bf(w)).mul(v.mul(inv).bf()).bf(); + } + } +}; + +/// The control kernel without point `p` (ricursive_dflash2.cu's tf_rcd_ctl_add_norm_*). +fn normControl(k: *const Kernels, p: NormPoint) !Function { + return switch (p) { + .resid => k.mod.function("tf_rcd_ctl_add_norm_resid"), + .x_row => k.mod.function("tf_rcd_ctl_add_norm_x_row"), + }; +} + +fn prepControl(k: *const Kernels, x: PrepCtl) !Function { + return switch (x) { + .norm_row => k.mod.function("tf_rcd_ctl_prep_norm_row"), + .norm_out => k.mod.function("tf_rcd_ctl_prep_norm_out"), + .cos => k.mod.function("tf_rcd_ctl_prep_cos"), + .sin => k.mod.function("tf_rcd_ctl_prep_sin"), + .rot_c => k.mod.function("tf_rcd_ctl_prep_rot_c"), + .rot_s => k.mod.function("tf_rcd_ctl_prep_rot_s"), + .out => k.mod.function("tf_rcd_ctl_prep_out"), + .nope_ropes => k.mod.function("tf_rcd_ctl_prep_nope_ropes"), + .mask => k.mod.function("tf_rcd_ctl_prep_mask"), + }; +} + +/// A conv control: a rounding point dropped, or an edit (Qwen's two roundings, no block-edge guard, base/dyn swapped). +pub const ConvCtl = enum { base, add, dyn, two_round, no_edge, swap }; + +fn convControl(k: *const Kernels, x: ConvCtl) !Function { + return switch (x) { + .base => k.mod.function("tf_rcd_ctl_conv_base"), + .add => k.mod.function("tf_rcd_ctl_conv_add"), + .dyn => k.mod.function("tf_rcd_ctl_conv_dyn"), + .two_round => k.mod.function("tf_rcd_ctl_conv_two_round"), + .no_edge => k.mod.function("tf_rcd_ctl_conv_no_edge"), + .swap => k.mod.function("tf_rcd_ctl_conv_swap"), + }; +} + +pub const ConvEntry = struct { name: []const u8, side: usize, ctl: ?ConvCtl = null }; + +pub const conv_entries = [_]ConvEntry{ + .{ .name = "cuda ricursive_dflash2 tf_rcd_conv side 0 (4 taps inside each block of 16)", .side = 0 }, + .{ .name = "cuda ricursive_dflash2 tf_rcd_conv side 1", .side = 1 }, + .{ .name = "control: ricursive_dflash2 tf_rcd_conv drops bf16(base x)", .side = 1, .ctl = .base }, + .{ .name = "control: ricursive_dflash2 tf_rcd_conv drops bf16(y + bf16(base x))", .side = 1, .ctl = .add }, + .{ .name = "control: ricursive_dflash2 tf_rcd_conv drops bf16(fma(dyn, x, y))", .side = 1, .ctl = .dyn }, + .{ .name = "control: ricursive_dflash2 tf_rcd_conv rounds dyn x before its add (Qwen's form, not the fma)", .side = 1, .ctl = .two_round }, + .{ .name = "control: ricursive_dflash2 tf_rcd_conv reads across its block's edge", .side = 1, .ctl = .no_edge }, + .{ .name = "control: ricursive_dflash2 tf_rcd_conv puts base in the fma and dyn in the rounded product", .side = 1, .ctl = .swap }, +}; + +/// Rows x width x taps: a block, 8 streams' blocks, two, and a partial block. +const conv_served = [_]c.Shape{ + .{ .rows = 16, .n = hidden, .k = taps }, + .{ .rows = 128, .n = hidden, .k = taps }, + .{ .rows = 32, .n = hidden, .k = taps }, + .{ .rows = 7, .n = hidden, .k = taps }, +}; + +pub fn convSpec(e: ConvEntry) c.Spec { + const rows: c.Tile = .{ .size = block, .step = 1, .min = 1 }; // a block's edge + const chans: c.Tile = .{ .size = 256, .step = group, .min = group }; // a launch block's channels, a group at a time + return .{ .name = e.name, .accum = .none, .depth = ref.noSums, .out = .bf16, .tiles = .{ rows, chans, .{} }, .served = &conv_served }; +} + +/// tf_rcd_conv: x in [-4, 4), dyn in [-0.5, 0.5), base in [-1.5, 1.5); non-finite: x's rows 1-3, row 4's first dyn. +pub const Conv = struct { + f: Function, + entry: ConvEntry, + shape: c.Shape = undefined, + x: []u16 = &.{}, + dyn: []u16 = &.{}, + base: []u16 = &.{}, + p: df.Conv = undefined, + + pub fn spec(self: *const Conv) c.Spec { + return convSpec(self.entry); + } + + pub fn control(self: *const Conv) ?g.Gate { + return if (self.entry.ctl != null) .shapes else null; + } + + pub fn free(self: *Conv, a: std.mem.Allocator) void { + for ([_]*[]u16{ &self.x, &self.dyn, &self.base }) |x| { + a.free(x.*); + x.* = &.{}; + } + } + + pub fn prepare(self: *Conv, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { + if (shape.rows == 0 or shape.n == 0 or shape.n % group != 0 or shape.k != taps) return false; + self.free(a); + self.shape = shape; + const rows = shape.rows; + const n = shape.n; + const groups = n / group; + self.x = try ref.bfs(a, rng, rows * n, -4, 4); + self.dyn = try ref.bfs(a, rng, rows * 2 * taps * groups, -0.5, 0.5); + self.base = try ref.bfs(a, rng, 2 * taps * n, -1.5, 1.5); + if (fill == .nonfinite) { + for ([_]f32{ ref.nan, ref.inf, -ref.inf }, 1..) |v, r| if (r < rows) { + self.x[r * n + (4 * r + 1) % n] = c.toBf16(v); + }; + if (rows > 4) self.dyn[4 * 2 * taps * groups + self.entry.side * taps * groups] = c.toBf16(ref.nan); + } + self.p = .{ .x = try ref.input(rig, self.x), .dyn = try ref.input(rig, self.dyn), .base = try ref.input(rig, self.base), .y = try rig.output(rows * n * 2), .rows = rows, .width = n, .block = block, .groups = groups, .side = self.entry.side, .taps = taps }; + return true; + } + + pub fn run(self: *Conv, rig: *rig_.Rig) !void { + try df.convBy(self.f, rig.s, self.p); + } + + pub fn count(self: *const Conv) usize { + return self.shape.rows * self.shape.n; + } + + /// bf16 products are exact in fp32: base x's one rounding is its bf16, and the fma's is the add's. + pub fn solve(self: *const Conv, _: std.mem.Allocator, _: Sums, out: []Iv) !void { + const n = self.shape.n; + const groups = n / group; + const side = self.entry.side; + for (0..self.shape.rows) |r| for (0..n) |ch| { + const dyn = self.dyn[r * 2 * taps * groups + side * taps * groups ..]; + var y = Iv.of(0); + for (0..taps) |t| { + if (r % block < t) break; + const x = ref.bf(self.x[(r - t) * n + ch]); + const b = ref.bf(self.base[(side * taps + t) * n + ch]); + const d = ref.bf(dyn[t * groups + ch / group]); + y = y.add(Iv.of(b * x).bf()).bf(); + y = Iv.of(d * x).add(y).bf(); + } + out[r * n + ch] = y; + }; + } +}; + +const silu_nan = "a NaN gate or up gives NaN; a -Inf gate gives NaN (-Inf x sigmoid 0); +Inf x up 0 gives NaN"; + +pub fn siluSpec(control: bool) c.Spec { + const name = if (control) "control: cuda ricursive_dflash2 tf_rcd_silu without bf16(g sigmoid(g))" else "cuda ricursive_dflash2 tf_rcd_silu (stacked gate | up, no clamp)"; + return .{ .name = name, .accum = .none, .depth = ref.noSums, .out = .bf16, .nan = .{ .stated = silu_nan }, .tiles = .{ .{}, elementwise, .{} }, .served = &silu_rows }; +} + +/// bf16(bf16(g s) u) from stacked gate | up rows, s from e = exp(-|g|): 1 / (1 + e), times e below 0. +pub const Silu = struct { + f: Function, + ctl: bool = false, + shape: c.Shape = undefined, + gate: []u16 = &.{}, + up: []u16 = &.{}, + dev: u64 = 0, + out: u64 = 0, + + pub fn spec(self: *const Silu) c.Spec { + return siluSpec(self.ctl); + } + + pub fn control(self: *const Silu) ?g.Gate { + return if (self.ctl) .shapes else null; + } + + pub fn free(self: *Silu, a: std.mem.Allocator) void { + a.free(self.gate); + a.free(self.up); + self.gate = &.{}; + self.up = &.{}; + } + + /// Gate in [-24, 24), up in [-4, 4); non-finite: NaN, +Inf and -Inf in gate's rows 0-2, then in up's rows 3-5. + pub fn prepare(self: *Silu, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { + if (shape.rows == 0 or shape.n == 0) return false; + self.free(a); + self.shape = shape; + const rows = shape.rows; + const n = shape.n; + self.gate = try ref.bfs(a, rng, rows * n, -24, 24); + self.up = try ref.bfs(a, rng, rows * n, -4, 4); + if (fill == .nonfinite) { + const put = [_]struct { usize, bool, f32 }{ .{ 0, true, ref.nan }, .{ 1, true, ref.inf }, .{ 2, true, -ref.inf }, .{ 3, false, ref.nan }, .{ 4, false, ref.inf }, .{ 5, false, -ref.inf } }; + for (put) |p| if (p[0] < rows) { + (if (p[1]) self.gate else self.up)[p[0] * n + p[0] + 1] = c.toBf16(p[2]); + }; + } + const both = try a.alloc(u16, 2 * rows * n); + defer a.free(both); + for (0..rows) |r| { + @memcpy(both[2 * r * n ..][0..n], self.gate[r * n ..][0..n]); + @memcpy(both[(2 * r + 1) * n ..][0..n], self.up[r * n ..][0..n]); + } + self.dev = try ref.input(rig, both); + self.out = try rig.output(rows * n * 2); + return true; + } + + pub fn run(self: *Silu, rig: *rig_.Rig) !void { + try df.siluBy(self.f, rig.s, self.dev, self.out, self.shape.rows, self.shape.n); + } + + pub fn count(self: *const Silu) usize { + return self.shape.rows * self.shape.n; + } + + pub fn solve(self: *const Silu, _: std.mem.Allocator, _: Sums, out: []Iv) !void { + for (out, self.gate, self.up) |*o, gh, uh| { + const gv = ref.bf(gh); + const e = Iv.of(-@abs(gv)).exp(); + const y = Iv.of(1).div(Iv.of(1).add(e)); + const s = if (gv < 0) e.mul(y) else y; + o.* = Iv.of(gv).mul(s).bf().mul(Iv.of(ref.bf(uh))).bf(); + } + } +}; + +/// Every registration, on the heap: the gates hold pointers to them. +pub const Set = struct { + gpa: std.mem.Allocator, + rk: rc.kernels.Kernels, // tf_rc_embed's image + k: Kernels, + embeds: [2]ref.Gated(Embed) = undefined, + norms: [2]ref.Gated(AddNorm) = undefined, + norm_ctls: [2]ref.Gated(AddNorm) = undefined, + preps: [prep_entries.len]ref.Gated(Prep) = undefined, + convs: [conv_entries.len]ref.Gated(Conv) = undefined, + silus: [2]ref.Gated(Silu) = undefined, + + /// The set, its kernels appended to `list` (the controls after the kernels they break). + pub fn init(gpu: check.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 rk = try rc.kernels.Kernels.load(gpu.d); + errdefer rk.unload(); + var k = try Kernels.load(gpu.d); + errdefer k.unload(); + set.* = .{ .gpa = gpu.gpa, .rk = rk, .k = k }; + const rig: rig_.Rig = .{ .gpu = gpu, .s = s }; + const kk = &set.k; + set.embeds = .{ + .{ .rig = rig, .k = .{ .f = set.rk.embed } }, + .{ .rig = rig, .k = .{ .f = try kk.mod.function("tf_rcd_ctl_embed_own_row"), .ctl = true } }, + }; + for (&set.norms, std.enums.values(NormForm)) |*x, f| x.* = .{ .rig = rig, .k = .{ .f = kk.add_norm, .form = f } }; + for (&set.norm_ctls, std.enums.values(NormPoint)) |*x, p| x.* = .{ .rig = rig, .k = .{ .f = try normControl(kk, p), .form = .add, .drop = p } }; + for (&set.preps, prep_entries) |*x, e| x.* = .{ .rig = rig, .k = .{ .f = if (e.ctl) |ct| try prepControl(kk, ct) else kk.prep, .entry = e } }; + for (&set.convs, conv_entries) |*x, e| x.* = .{ .rig = rig, .k = .{ .f = if (e.ctl) |ct| try convControl(kk, ct) else kk.conv, .entry = e } }; + set.silus = .{ + .{ .rig = rig, .k = .{ .f = kk.silu } }, + .{ .rig = rig, .k = .{ .f = try kk.mod.function("tf_rcd_ctl_silu_gs"), .ctl = true } }, + }; + for (&set.embeds) |*x| try list.append(a, x.kernel()); + for (&set.norms) |*x| try list.append(a, x.kernel()); + for (&set.norm_ctls) |*x| try list.append(a, x.kernel()); + for (&set.preps) |*x| try list.append(a, x.kernel()); + for (&set.convs) |*x| try list.append(a, x.kernel()); + for (&set.silus) |*x| try list.append(a, x.kernel()); + return set; + } + + pub fn deinit(set: *Set) void { + for (&set.embeds) |*x| x.deinit(); + for (&set.norms) |*x| x.deinit(); + for (&set.norm_ctls) |*x| x.deinit(); + for (&set.preps) |*x| x.deinit(); + for (&set.convs) |*x| x.deinit(); + for (&set.silus) |*x| x.deinit(); + set.k.unload(); + set.rk.unload(); + set.gpa.destroy(set); + } +}; + +/// The drafter glue's gates 1-4 and their controls alone. +pub fn run(gpu: check.Gpu) !void { + const a = gpu.gpa; + var s = try cuda.Stream.init(gpu.d, false); + defer s.deinit(); + var list: std.ArrayList(g.Kernel) = .empty; + defer list.deinit(a); + const set = try Set.init(gpu, s, a, &list); + defer set.deinit(); + var t: g.Tally = .{}; + try g.runAll(a, list.items, 0x726364, &t); + std.debug.print("SUMMARY ricursive dflash2: {d} kernels, {d} pass gates 1-4, {d} fail; {d} controls: {d} red as planted, {d} missed\n", .{ t.kernels, t.passed, t.failed, t.controls, t.caught, t.missed }); + try check.expect(t.problems() == 0, "ricursive-dflash2-contract: {d} gate failures, {d} controls missed", .{ t.failed, t.missed }); +} + +test "dflash2 controls: each prep and conv control registered once" { + var prep = std.EnumSet(PrepCtl).initEmpty(); + for (prep_entries) |e| if (e.ctl) |x| { + try std.testing.expect(!prep.contains(x)); + prep.insert(x); + }; + try std.testing.expectEqual(std.enums.values(PrepCtl).len, prep.count()); + var conv = std.EnumSet(ConvCtl).initEmpty(); + for (conv_entries) |e| if (e.ctl) |x| { + try std.testing.expect(!conv.contains(x)); + conv.insert(x); + }; + try std.testing.expectEqual(std.enums.values(ConvCtl).len, conv.count()); +} diff --git a/zig/tests/cuda/contract_ricursive_dflash2_attn.zig b/zig/tests/cuda/contract_ricursive_dflash2_attn.zig new file mode 100644 index 00000000000..c2519c4b563 --- /dev/null +++ b/zig/tests/cuda/contract_ricursive_dflash2_attn.zig @@ -0,0 +1,583 @@ +//! Ripple's DFlash2 draft attention and top-32 on CUDA under the contract, with controls, and a call's time. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const da = @import("ricursive_cuda").dflash2_attn; +const check = @import("check.zig"); +const rig_ = @import("contract_rig.zig"); +const ref = @import("contract_minimax_glue_ref.zig"); + +const c = core.contract.spec; +const g = core.contract.gates; +const bfr = core.bf16_round; +const sumIn = core.contract.rows.sumIn; +const Iv = ref.Iv; +const Sums = ref.Sums; +const unit = ref.unit; + +const D = da.head_dim; +const heads = da.heads; +const kv_heads = da.kv_heads; +const group = heads / kv_heads; +const block = da.block; +/// Outputs a block row: every head's 128 values (the shape's n). +const width = heads * D; + +fn bf32(h: u16) f32 { + return c.fromBf16(h); +} + +// --- draft attention ------------------------------------------------------------------------------------------------ + +/// A layer kind: sliding (window 4,096, ring 4,224) or global NoPE (16,384, ring 16,512). +pub const Form = enum { sliding, global }; + +fn spanOf(f: Form) usize { + return switch (f) { + .sliding => da.sliding_span, + .global => da.global_span, + }; +} + +/// A registration: the served launches, or a control with one of them replaced by a planted fault of the image. +pub const AttnEntry = struct { name: []const u8, form: Form, part: [:0]const u8 = "tf_rcd_attn_part", merge: [:0]const u8 = "tf_rcd_attn_merge" }; + +pub const attn_entries = [_]AttnEntry{ + .{ .name = "ricursive dflash2 draft attention, sliding window (4,096 keys, ring 4,224)", .form = .sliding }, + .{ .name = "ricursive dflash2 draft attention, global window (16,384 keys, ring 16,512)", .form = .global }, + .{ .name = "control: ricursive dflash2 attention masks the block causally", .form = .sliding, .part = "tf_rcd_ctl_attn_causal" }, + .{ .name = "control: ricursive dflash2 attention's window starts one key low", .form = .sliding, .part = "tf_rcd_ctl_attn_floor" }, + .{ .name = "control: ricursive dflash2 attention leaves the block's own rows out", .form = .sliding, .part = "tf_rcd_ctl_attn_no_block" }, + .{ .name = "control: ricursive dflash2 attention's merge truncates to bf16, not rounding it", .form = .sliding, .merge = "tf_rcd_ctl_attn_merge_trunc" }, +}; + +fn isControl(e: AttnEntry) bool { + return !std.mem.eql(u8, e.part, "tf_rcd_attn_part") or !std.mem.eql(u8, e.merge, "tf_rcd_attn_merge"); +} + +/// Rows: streams; k: stream 0's end (anchor k - 16). 8 streams past a wrapped ring; 1: first block, window edges, wrap. +const sliding_served = [_]c.Shape{ + .{ .rows = 8, .n = width, .k = 20016 }, .{ .rows = 1, .n = width, .k = 16 }, .{ .rows = 1, .n = width, .k = 1000 }, + .{ .rows = 1, .n = width, .k = 4112 }, .{ .rows = 1, .n = width, .k = 9999 }, .{ .rows = 8, .n = width, .k = 5555 }, +}; +const global_served = [_]c.Shape{ .{ .rows = 8, .n = width, .k = 20016 }, .{ .rows = 1, .n = width, .k = 50016 }, .{ .rows = 1, .n = width, .k = 16 } }; + +/// A score's dot: a product and 3 fmas a lane, then 5 butterfly adds (10, with room). +fn attnDepth(_: c.Shape) usize { + return 10 + 128 + da.chunksFor(da.global_span); +} + +fn attnSpec(e: AttnEntry) c.Spec { + return .{ .name = e.name, .accum = .f32, .depth = attnDepth, .out = .bf16, .served = switch (e.form) { + .sliding => &sliding_served, + .global => &global_served, + }, .sums = .{} }; +} + +/// Stream i's block at anchor(0) >> i plus 37 i; odd streams see from a floor above their window's start. +fn anchorOf(k: usize, i: usize) usize { + return ((k - block) >> @intCast(i)) + 37 * i; +} + +fn fromOf(anchor: usize, span: usize, i: usize) usize { + if (i % 2 == 0) return 0; + return if (anchor > span / 2) anchor - span / 2 else anchor / 2; +} + +/// Row r's keys: max(p + 1 - span, from) to anchor + 16, p = anchor + r. +fn keysOf(s: da.Segment, r: usize) struct { lo: usize, hi: usize } { + const lo = @max(@as(i64, s.anchor) + @as(i64, @intCast(r)) + 1 - s.span, s.from); + return .{ .lo = @intCast(@max(lo, 0)), .hi = @intCast(s.anchor + block) }; +} + +/// One layer's call: each stream's ring filled whole (a key read outside its window changes the answer), segs, q, out. +pub const Attn = struct { + entry: AttnEntry, + part: cuda.Function, + merge: cuda.Function, + shape: c.Shape = undefined, + span: usize = 0, + ring_rows: usize = 0, + segs: []da.Segment = &.{}, + q: []u16 = &.{}, + rings: []u16 = &.{}, // stream s's ring at s ring_len: K then V + call: da.Attn = undefined, + + pub const sums = {}; + + pub fn spec(self: *const Attn) c.Spec { + return attnSpec(self.entry); + } + + pub fn control(self: *const Attn) ?g.Gate { + return if (isControl(self.entry)) .shapes else null; + } + + pub fn free(self: *Attn, a: std.mem.Allocator) void { + a.free(self.segs); + self.segs = &.{}; + a.free(self.q); + self.q = &.{}; + a.free(self.rings); + self.rings = &.{}; + } + + fn ringLen(self: *const Attn) usize { + return 2 * self.ring_rows * kv_heads * D; + } + + fn ring(self: *const Attn, s: usize) []const u16 { + return self.rings[s * self.ringLen() ..][0..self.ringLen()]; + } + + pub fn prepare(self: *Attn, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { + if (shape.rows == 0 or shape.rows > 64 or shape.n != width or shape.k < block) return false; + self.free(a); + self.shape = shape; + self.span = spanOf(self.entry.form); + self.ring_rows = da.ringRows(self.span); + const streams = shape.rows; + self.segs = try a.alloc(da.Segment, streams); + for (self.segs, 0..) |*s, i| { + const anchor = anchorOf(shape.k, i); + s.* = .{ .ring = 0, .anchor = @intCast(anchor), .from = @intCast(fromOf(anchor, self.span, i)), .span = @intCast(self.span), .rows = @intCast(self.ring_rows) }; + } + self.q = try a.alloc(u16, streams * block * width); + self.rings = try a.alloc(u16, streams * self.ringLen()); + for (self.q) |*x| x.* = c.toBf16(rng.floatNorm(f32)); + const half = self.ring_rows * kv_heads * D; // K, then V + for (0..streams) |s| { + const r = self.rings[s * self.ringLen() ..][0..self.ringLen()]; + if (fill == .stress) { + // every key the same (each kv head its own vector): every weight exactly 1, the sums integers + const kv: [kv_heads * D]u16 = blk: { + var v: [kv_heads * D]u16 = undefined; + for (&v) |*x| x.* = c.toBf16(rng.floatNorm(f32)); + break :blk v; + }; + for (0..self.ring_rows) |row| @memcpy(r[row * kv_heads * D ..][0 .. kv_heads * D], &kv); + stressValues(r[half..], self.segs[s], self.ring_rows, rng); + } else { + for (r[0..half]) |*x| x.* = c.toBf16(rng.floatNorm(f32)); + // V: half the dims about 1 (outputs well away from 0), half about 0 + for (r[half..], 0..) |*x, i| x.* = c.toBf16(if (i % D < D / 2) 1 + 0.25 * rng.floatNorm(f32) else rng.floatNorm(f32)); + } + } + if (fill == .nonfinite and streams >= 3) { + const at = struct { + fn key(self_: *Attn, s: usize, pos: usize, kv: usize, d: usize, v: bool) *u16 { + const row = pos % self_.ring_rows; + const off = (if (v) self_.ring_rows * kv_heads * D else 0) + (row * kv_heads + kv) * D + d; + return &self_.rings[s * self_.ringLen() + off]; + } + }; + // stream 0: a NaN key in the block (heads 0-9 NaN) + at.key(self, 0, @as(usize, @intCast(self.segs[0].anchor)) + 3, 0, 11, false).* = c.toBf16(ref.nan); + // stream 1: a -inf value (heads 30-39, dim 7, -inf) + at.key(self, 1, @as(usize, @intCast(self.segs[1].anchor)) + 5, 3, 7, true).* = c.toBf16(-ref.inf); + // stream 2: an infinite q (row 4, head 25: every score infinite, NaN) + self.q[((2 * block + 4) * heads + 25) * D + 40] = c.toBf16(ref.inf); + } + for (self.segs, 0..) |*s, i| s.ring = try ref.input(rig, self.ring(i)); + const qd = try ref.input(rig, self.q); + const segs = try ref.input(rig, self.segs); + const out = try rig.output(streams * block * width * 2); + self.call = .{ .q = qd, .segs = segs, .out = out, .pm = 0, .pl = 0, .po = 0, .streams = streams, .span = self.span }; + const sc = da.scratch(self.call); + self.call.pm = try rig.scratch(sc.max); + self.call.pl = try rig.scratch(sc.max); + self.call.po = try rig.scratch(sc.values); + return true; + } + + /// Gate 4's values: odd integers to 255, then negated (+1 on 8): small exact sums, big partials, all exact in fp32. + fn stressValues(v: []u16, s: da.Segment, ring_rows: usize, rng: std.Random) void { + @memset(v, 0); + const lo = keysOf(s, 0).lo; + const n = keysOf(s, 0).hi - lo; + for (0..kv_heads * D) |e| for (0..n) |j| { + const at = ((lo + j) % ring_rows) * kv_heads * D + e; + if (j < n / 2) { + v[at] = c.toBf16(@floatFromInt(2 * rng.uintLessThan(u32, 128) + 1)); + } else if (j < 2 * (n / 2)) { + const mirror = ((lo + j - n / 2) % ring_rows) * kv_heads * D + e; + v[at] = c.toBf16((if (j - n / 2 < 8) @as(f32, 1) else 0) - bf32(v[mirror])); + } else v[at] = c.toBf16(1); + }; + } + + pub fn run(self: *Attn, rig: *rig_.Rig) !void { + try da.attentionVia(self.part, self.merge, rig.s, self.call); + } + + pub fn count(self: *Attn) usize { + return self.shape.rows * block * width; + } + + /// Each (stream, row, head): float64 scores of q scaled in fp32, softmax at the NaN-skipping max; ranges below. + pub fn solve(self: *Attn, a: std.mem.Allocator, how: Sums, out: []Iv) !void { + const most = self.span + block; + const w = try a.alloc(f64, most); + defer a.free(w); + const slab = try a.alloc(f64, if (how.sim != null) D * most else 0); + defer a.free(slab); + const nb: f64 = @floatFromInt(da.chunksFor(self.span)); + const R = self.ring_rows; + const vbase = R * kv_heads * D; + for (self.segs, 0..) |seg, s| { + const ring_ = self.ring(s); + for (0..block) |r| { + const keys = keysOf(seg, r); + const nk = keys.hi - keys.lo; + const row_out = out[(s * block + r) * width ..][0..width]; + // simulated (gate 4's stress, weights 1): each output the mean of its values summed in the accumulator + if (how.sim) |sim| { + // the stress keys are one vector: a group's heads share their weights (all 1), so their outputs + for (0..kv_heads) |kv| { + for (keys.lo..keys.hi, 0..) |p, j| for (ring_[vbase + ((p % R) * kv_heads + kv) * D ..][0..D], 0..) |v, d| { + slab[d * most + j] = bf32(v); + }; + for (0..D) |d| { + const m = sumIn(sim.acc, sim.order, slab[d * most ..][0..nk]) / @as(f64, @floatFromInt(nk)); + for (0..group) |hh| row_out[(kv * group + hh) * D + d] = Iv.of(m); + } + } + continue; + } + for (0..heads) |h| { + const kv = h / group; + var qs: [D]f64 = undefined; + for (&qs, self.q[((s * block + r) * heads + h) * D ..][0..D]) |*x, b| x.* = da.scale * bf32(b); + var top: f64 = -std.math.inf(f64); + var low: f64 = std.math.inf(f64); + var amax: f64 = 0; + for (keys.lo..keys.hi, 0..) |p, j| { + const k = ring_[((p % R) * kv_heads + kv) * D ..][0..D]; + var dot: f64 = 0; + var abs: f64 = 0; + for (qs, k) |x, kb| { + const t = x * bf32(kb); + dot += t; + abs += @abs(t); + } + w[j] = dot; + if (dot > top) top = dot; // fmaxf: a NaN score is never the max + if (dot < low) low = dot; + if (abs > amax) amax = abs; + } + var W: f64 = 0; + for (w[0..nk]) |*x| { + x.* = @exp(x.* - top); + W += x.*; + } + var num: [D]f64 = @splat(0); + var mag: [D]f64 = @splat(0); + var vmax: [D]f64 = @splat(0); + for (keys.lo..keys.hi, 0..) |p, j| for (ring_[vbase + ((p % R) * kv_heads + kv) * D ..][0..D], 0..) |vb, d| { + const v: f64 = bf32(vb); + num[d] += w[j] * v; + mag[d] += w[j] * @abs(v); + vmax[d] = @max(vmax[d], @abs(v)); + }; + // E: the scores' error, the dot's 10 roundings of its terms' size + const E = c.gamma(10, unit) * amax + 0x1p-50 * amax; + // eps: an exp's argument and 2 ulps, 33 deep (own exp, chunk rescales, merge factor) + const eps = @exp(unit * (top - low + 2 * E)) * (1 + 4 * unit) - 1; + // products 34 deep, 128 and merge sums, division: |N/W - m| <= 2 delta mag / (1 - delta) + const delta = @exp(E) * std.math.pow(f64, 1 + eps, 33) * std.math.pow(f64, 1 + unit, 34) * (1 + c.gamma(128, unit)) * (1 + c.gamma(nb, unit)) - 1; + for (row_out[h * D ..][0..D], num, mag, vmax) |*x, nm, mg, vm| { + const m = nm / W; + if (!std.math.isFinite(m)) { + x.* = Iv.of(m); + continue; + } + const dev = if (how.exact) 0 else 2 * delta * (mg / W) / (1 - delta); + const tiny = @as(f64, @floatFromInt(nk)) * 0x1p-140 * (1 + vm) / W; + const B = dev + unit * (@abs(m) + dev) + tiny; + x.* = .{ .m = m, .lo = bfr.bf16(m - B), .hi = bfr.bf16(m + B) }; + } + } + } + } + } +}; + +// --- top-32 --------------------------------------------------------------------------------------------------------- + +pub const TopEntry = struct { name: []const u8, part: [:0]const u8 = "tf_rcd_top32_part", merge: [:0]const u8 = "tf_rcd_top32_merge" }; + +pub const top_entries = [_]TopEntry{ + .{ .name = "ricursive dflash2 top-32 over the vocabulary (49 chunks, then their bests)" }, + .{ .name = "control: ricursive dflash2 top-32 orders ties by the higher id", .part = "tf_rcd_ctl_top32_part_ties", .merge = "tf_rcd_ctl_top32_merge_ties" }, + .{ .name = "control: ricursive dflash2 top-32's merge drops chunk 0's bests", .merge = "tf_rcd_ctl_top32_merge_drop" }, +}; + +/// Rows: the draft rows (15 a stream's block, up to 128); n: the vocabulary. +const top_served = [_]c.Shape{ .{ .rows = 15, .n = da.vocab, .k = 1 }, .{ .rows = 1, .n = da.vocab, .k = 1 }, .{ .rows = 16, .n = da.vocab, .k = 1 }, .{ .rows = 128, .n = da.vocab, .k = 1 } }; + +const P = struct { v: f32, id: u32 }; + +fn first(_: void, a: P, b: P) bool { + return a.v > b.v or (a.v == b.v and a.id < b.id); +} + +/// A 2,048-entry chunk in rc_df_topk's order: a host sort when every value is finite, else its network replayed. +fn sortChunk(buf: []P) void { + for (buf) |x| if (!std.math.isFinite(x.v) and x.id != 0xffffffff) { + var k: usize = 2; + while (k <= da.top_chunk) : (k <<= 1) { + var j = k >> 1; + while (j > 0) : (j >>= 1) for (0..da.top_chunk) |i| { + const l = i ^ j; + if (l <= i) continue; + const swap = if (i & k == 0) first({}, buf[l], buf[i]) else first({}, buf[i], buf[l]); + if (swap) std.mem.swap(P, &buf[i], &buf[l]); + }; + } + return; + }; + std.sort.pdq(P, buf, {}, first); +} + +pub const Top = struct { + entry: TopEntry, + part: cuda.Function, + merge: cuda.Function, + shape: c.Shape = undefined, + l: []u16 = &.{}, + call: da.Top32 = undefined, + + pub fn spec(self: *const Top) c.Spec { + return .{ + .name = self.entry.name, + .accum = .none, + .depth = ref.noSums, + .out = .raw, + .nan = .{ .stated = "finite rows: each chunk's 32 largest, then the chunks' bests' 32 (value desc, id asc) as a host sort gives them; with NaN or infinities: rc_df_topk's sorting network (NaN compares false), replayed bit for bit" }, + .tiles = .{ .{}, .{ .size = da.top_chunk, .step = 1, .min = 1 }, .{} }, + .served = &top_served, + }; + } + + pub fn control(self: *const Top) ?g.Gate { + const served = std.mem.eql(u8, self.entry.part, "tf_rcd_top32_part") and std.mem.eql(u8, self.entry.merge, "tf_rcd_top32_merge"); + return if (served) null else .shapes; + } + + pub fn free(self: *Top, a: std.mem.Allocator) void { + a.free(self.l); + self.l = &.{}; + } + + /// Even rows normal times 4; odd rows 512 levels of 1/16 (ties everywhere, ids must break them). + pub fn prepare(self: *Top, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { + if (shape.rows == 0 or shape.n == 0 or shape.n > da.top_chunk * da.top_chunk / da.top) return false; + self.free(a); + self.shape = shape; + self.l = try a.alloc(u16, shape.rows * shape.n); + for (self.l, 0..) |*x, i| x.* = c.toBf16(if (i / shape.n % 2 == 0) 4 * rng.floatNorm(f32) else @as(f32, @floatFromInt(rng.uintLessThan(u32, 512))) / 16 - 16); + if (fill == .nonfinite) for ([_]f32{ ref.nan, ref.inf, -ref.inf, ref.nan }, 0..) |x, k| { + self.l[(k % shape.rows) * shape.n + (k * 37) % shape.n] = c.toBf16(x); + }; + const logits = try ref.input(rig, self.l); + const vals = try rig.output(shape.rows * da.top * 4); + const ids = try rig.output(shape.rows * da.top * 4); + self.call = .{ .logits = logits, .stride = shape.n, .n = shape.n, .rows = shape.rows, .vals = vals, .ids = ids, .part_vals = 0, .part_ids = 0 }; + self.call.part_vals = try rig.scratch(da.top32Scratch(self.call)); + self.call.part_ids = try rig.scratch(da.top32Scratch(self.call)); + return true; + } + + pub fn run(self: *Top, rig: *rig_.Rig) !void { + try da.top32Via(self.part, self.merge, rig.s, self.call); + } + + pub fn count(self: *Top) usize { + return 2 * self.shape.rows * da.top * 4; + } + + pub fn check(self: *Top, a: std.mem.Allocator, got: []const u8, msg: *[200]u8) !?[]const u8 { + const n = self.shape.n; + const chunks = self.call.chunks(); + const buf = try a.alloc(P, da.top_chunk); + defer a.free(buf); + const bests = try a.alloc(P, da.top_chunk); + defer a.free(bests); + const half = self.shape.rows * da.top * 4; + for (0..self.shape.rows) |r| { + for (bests) |*x| x.* = .{ .v = -std.math.inf(f32), .id = 0xffffffff }; + for (0..chunks) |ch| { + for (buf, 0..) |*x, i| { + const at = ch * da.top_chunk + i; + x.* = if (at < n) .{ .v = bf32(self.l[r * n + at]), .id = @intCast(at) } else .{ .v = -std.math.inf(f32), .id = 0xffffffff }; + } + sortChunk(buf); + @memcpy(bests[ch * da.top ..][0..da.top], buf[0..da.top]); + } + sortChunk(bests); + for (bests[0..da.top], 0..) |want, i| { + const gv = ref.readF32(got, r * da.top + i); + const gi: u32 = @bitCast(ref.readI32(got[half..], r * da.top + i)); + const same = @as(u32, @bitCast(want.v)) == @as(u32, @bitCast(gv)) or (std.math.isNan(want.v) and std.math.isNan(gv)); + if (!same or want.id != gi) return try std.fmt.bufPrint(msg, "row {d} place {d}: ({d}, {d}) where the host has ({d}, {d})", .{ r, i, gv, gi, want.v, want.id }); + } + } + return null; + } +}; + +// --- the set, the runner and the timings --------------------------------------------------------------------------- + +/// The registrations, on the heap: the gates hold pointers to them. +pub const Set = struct { + gpa: std.mem.Allocator, + k: da.Kernels, + attn: [attn_entries.len]ref.Gated(Attn) = undefined, + tops: [top_entries.len]ref.Checked(Top) = undefined, + + /// The set, its kernels appended to `list` (the controls after the kernel they break). + pub fn init(gpu: check.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); + set.* = .{ .gpa = gpu.gpa, .k = try da.Kernels.load(gpu.d) }; + errdefer set.k.unload(); + const mod = set.k.mod; + for (&set.attn, attn_entries) |*x, e| x.* = .{ .rig = .{ .gpu = gpu, .s = s }, .k = .{ .entry = e, .part = try da.partFunction(mod, e.part), .merge = try mod.function(e.merge) } }; + for (&set.tops, top_entries) |*x, e| x.* = .{ .rig = .{ .gpu = gpu, .s = s }, .k = .{ .entry = e, .part = try mod.function(e.part), .merge = try mod.function(e.merge) } }; + for (&set.attn) |*x| try list.append(a, x.kernel()); + for (&set.tops) |*x| try list.append(a, x.kernel()); + return set; + } + + pub fn deinit(set: *Set) void { + for (&set.tops) |*x| x.deinit(); + for (&set.attn) |*x| x.deinit(); + set.k.unload(); + set.gpa.destroy(set); + } +}; + +/// One call (both launches) at full rings, windows whole and wrapped: mean [total, part] ms of 20 calls after 3. +fn timeAttn(gpu: check.Gpu, s: cuda.Stream, k: *const da.Kernels, span: usize, streams: usize) ![2]f64 { + const ring_rows = da.ringRows(span); + const ring_bytes = 2 * ring_rows * kv_heads * D * 2; + var bufs: std.ArrayList(cuda.DeviceBuffer) = .empty; + defer { + for (bufs.items) |*b| b.free(); + bufs.deinit(gpu.gpa); + } + var segs: [8]da.Segment = undefined; + const host = try gpu.gpa.alloc(u16, ring_bytes / 2); + defer gpu.gpa.free(host); + var x: u32 = 0x9e3779b9; + for (host) |*v| { + x ^= x << 13; + x ^= x >> 17; + x ^= x << 5; + v.* = c.toBf16(@as(f32, @floatFromInt(x >> 8)) / 0x1p23 - 1); + } + for (segs[0..streams], 0..) |*sg, i| { + try bufs.append(gpu.gpa, try cuda.DeviceBuffer.fromHost(gpu.d, std.mem.sliceAsBytes(host))); + sg.* = .{ .ring = bufs.items[i].ptr, .anchor = @intCast(100000 + 1000 * i), .from = 0, .span = @intCast(span), .rows = @intCast(ring_rows) }; + } + const q = try gpu.gpa.alloc(u16, streams * block * width); + defer gpu.gpa.free(q); + @memcpy(q, host[0..q.len]); + try bufs.append(gpu.gpa, try cuda.DeviceBuffer.fromHost(gpu.d, std.mem.sliceAsBytes(q))); + try bufs.append(gpu.gpa, try cuda.DeviceBuffer.fromHost(gpu.d, std.mem.sliceAsBytes(segs[0..streams]))); + var call: da.Attn = .{ .q = bufs.items[streams].ptr, .segs = bufs.items[streams + 1].ptr, .out = 0, .pm = 0, .pl = 0, .po = 0, .streams = streams, .span = span }; + const sc = da.scratch(call); + for ([_]usize{ streams * block * width * 2, sc.max, sc.max, sc.values }) |len| try bufs.append(gpu.gpa, try cuda.DeviceBuffer.alloc(gpu.d, len)); + call.out = bufs.items[streams + 2].ptr; + call.pm = bufs.items[streams + 3].ptr; + call.pl = bufs.items[streams + 4].ptr; + call.po = bufs.items[streams + 5].ptr; + for (0..3) |_| try da.attention(k, s, call); + var e0 = try cuda.Event.init(gpu.d, true); + defer e0.deinit(); + var e1 = try cuda.Event.init(gpu.d, true); + defer e1.deinit(); + const calls = 20; + var ms: [2]f64 = undefined; + for (&ms, 0..) |*m, i| { + try e0.record(s); + for (0..calls) |_| if (i == 0) try da.attention(k, s, call) else try da.partVia(k.attn_part, s, call); + try e1.record(s); + try e1.synchronize(); + m.* = @as(f64, try cuda.Event.elapsedMs(e0, e1)) / calls; + } + return ms; +} + +/// The top-32 of `rows` rows of the vocabulary, mean of 20 calls. +fn timeTop32(gpu: check.Gpu, s: cuda.Stream, k: *const da.Kernels, rows: usize) !f64 { + var call: da.Top32 = .{ .logits = 0, .stride = da.vocab, .rows = rows, .vals = 0, .ids = 0, .part_vals = 0, .part_ids = 0 }; + var bufs: [5]cuda.DeviceBuffer = undefined; + var made: usize = 0; + defer for (bufs[0..made]) |*b| b.free(); + for ([_]usize{ rows * da.vocab * 2, rows * da.top * 4, rows * da.top * 4, da.top32Scratch(call), da.top32Scratch(call) }, 0..) |len, i| { + bufs[i] = try cuda.DeviceBuffer.alloc(gpu.d, len); + made += 1; + } + try bufs[0].fill8(0x3f, s.handle); + call.logits = bufs[0].ptr; + call.vals = bufs[1].ptr; + call.ids = bufs[2].ptr; + call.part_vals = bufs[3].ptr; + call.part_ids = bufs[4].ptr; + for (0..3) |_| try da.top32(k, s, call); + var e0 = try cuda.Event.init(gpu.d, true); + defer e0.deinit(); + var e1 = try cuda.Event.init(gpu.d, true); + defer e1.deinit(); + const calls = 20; + try e0.record(s); + for (0..calls) |_| try da.top32(k, s, call); + try e1.record(s); + try e1.synchronize(); + return @as(f64, try cuda.Event.elapsedMs(e0, e1)) / calls; +} + +/// Gates 1-4 of the draft attention and top-32 and their controls, then the timings. +pub fn run(gpu: check.Gpu) !void { + const a = gpu.gpa; + var s = try cuda.Stream.init(gpu.d, false); + defer s.deinit(); + var list: std.ArrayList(g.Kernel) = .empty; + defer list.deinit(a); + const set = try Set.init(gpu, s, a, &list); + defer set.deinit(); + var t: g.Tally = .{}; + try g.runAll(a, list.items, 0x726364, &t); + std.debug.print("SUMMARY ricursive dflash2 attention: {d} kernels, {d} pass gates 1-4, {d} fail; {d} controls: {d} red as planted, {d} missed\n", .{ t.kernels, t.passed, t.failed, t.controls, t.caught, t.missed }); + for ([_]Form{ .sliding, .global }) |f| for ([_]usize{ 1, 8 }) |streams| { + const span = spanOf(f); + const ms = try timeAttn(gpu, s, &set.k, span, streams); + const keys = streams * kv_heads * (span + block - 1); + const kv_mb = @as(f64, @floatFromInt(keys * D * 2 * 2)) / 1e6; + std.debug.print("TIME ricursive dflash2 attention {t} (window {d}) at {d} stream(s), full rings: {d:.3} ms a call (part {d:.3} + merge {d:.3}); K and V read {d:.1} MB, {d:.0} GB/s\n", .{ f, span, streams, ms[0], ms[1], ms[0] - ms[1], kv_mb, kv_mb / ms[0] }); + }; + for ([_]usize{ 15, 128 }) |rows| std.debug.print("TIME ricursive dflash2 top-32 at {d} rows of {d}: {d:.3} ms a call (part + merge)\n", .{ rows, da.vocab, try timeTop32(gpu, s, &set.k, rows) }); + try check.expect(t.problems() == 0, "ricursive-dflash2-attn-contract: {d} gate failures, {d} controls missed", .{ t.failed, t.missed }); +} + +test "the controls: every planted fault of the image registered once, each against a served kernel's shapes" { + const t = std.testing; + const faults = [_][]const u8{ "tf_rcd_ctl_attn_causal", "tf_rcd_ctl_attn_floor", "tf_rcd_ctl_attn_no_block", "tf_rcd_ctl_attn_merge_trunc", "tf_rcd_ctl_top32_part_ties", "tf_rcd_ctl_top32_merge_ties", "tf_rcd_ctl_top32_merge_drop" }; + for (faults) |f| { + var n: usize = 0; + for (attn_entries) |e| n += @intFromBool(std.mem.eql(u8, e.part, f)) + @intFromBool(std.mem.eql(u8, e.merge, f)); + for (top_entries) |e| n += @intFromBool(std.mem.eql(u8, e.part, f)) + @intFromBool(std.mem.eql(u8, e.merge, f)); + try t.expectEqual(@as(usize, 1), n); + } + var controls: usize = 0; + for (attn_entries) |e| controls += @intFromBool(isControl(e)); + try t.expectEqual(@as(usize, 4), controls); + // the rings the brief names, a wrapped ring each, a from-floor above the window start on odd streams + try t.expectEqual(@as(usize, 4224), da.ringRows(spanOf(.sliding))); + try t.expectEqual(@as(usize, 16512), da.ringRows(spanOf(.global))); + try t.expect(anchorOf(sliding_served[0].k, 0) + block > da.ringRows(da.sliding_span)); + try t.expect(anchorOf(global_served[1].k, 0) + block > da.ringRows(da.global_span)); + const a1 = anchorOf(sliding_served[0].k, 1); + try t.expect(fromOf(a1, da.sliding_span, 1) > a1 + 1 - da.sliding_span); +} diff --git a/zig/tests/cuda/contract_ricursive_dflash2_prep.zig b/zig/tests/cuda/contract_ricursive_dflash2_prep.zig new file mode 100644 index 00000000000..1ad7c4d7d61 --- /dev/null +++ b/zig/tests/cuda/contract_ricursive_dflash2_prep.zig @@ -0,0 +1,338 @@ +//! Ripple's DFlash2 drafter prep on CUDA under the contract: its entries, its streams' plan and the Prep kernel. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const rc = @import("ricursive_cuda"); +const rig_ = @import("contract_rig.zig"); +const ref = @import("contract_minimax_glue_ref.zig"); // the family-neutral Gated wrapper and fills + +const c = core.contract.spec; +const g = core.contract.gates; +const df = rc.dflash2_kernels; +const Iv = ref.Iv; +const Sums = ref.Sums; +const Function = cuda.Function; + +const heads = 80; +const kv_heads = 8; +const D = 128; +const kvw = kv_heads * D; +const eps = @import("contract_ricursive_dflash2.zig").eps; +const theta: f32 = 10000; +const sliding_ring = 4224; +const global_ring = 16512; // layer 4's, NoPE +const most_pos = 262144; // positions stay below it + +/// Block rows (q, k and v of 80 query heads) or context rows (k and v only); a sliding layer's ring or the global one. +pub const Mode = enum { block, context }; +pub const Layer = enum { sliding, global }; + +/// A prep control: one rounding point dropped (the output truncated for `out`), or one edit. +pub const PrepCtl = enum { norm_row, norm_out, cos, sin, rot_c, rot_s, out, nope_ropes, mask }; + +pub const PrepEntry = struct { + name: []const u8, + mode: Mode, + layer: Layer, + ctl: ?PrepCtl = null, + + /// The mask control holds the whole ring: its wrong slots stay in the buffer. + fn full(e: PrepEntry) bool { + return if (e.ctl) |x| x == .mask else false; + } +}; + +/// NoPE stores the normed head as it is, so the rotation's points show only on sliding layers. +pub const prep_entries = [_]PrepEntry{ + .{ .name = "cuda ricursive_dflash2 tf_rcd_prep block, sliding (RoPE, 4,224-slot rings)", .mode = .block, .layer = .sliding }, + .{ .name = "cuda ricursive_dflash2 tf_rcd_prep block, global (NoPE, 16,512-slot rings)", .mode = .block, .layer = .global }, + .{ .name = "cuda ricursive_dflash2 tf_rcd_prep context, sliding (k and v only, RoPE)", .mode = .context, .layer = .sliding }, + .{ .name = "cuda ricursive_dflash2 tf_rcd_prep context, global (k and v only, NoPE)", .mode = .context, .layer = .global }, + .{ .name = "control: ricursive_dflash2 tf_rcd_prep drops bf16(x r)", .mode = .block, .layer = .sliding, .ctl = .norm_row }, + .{ .name = "control: ricursive_dflash2 tf_rcd_prep drops bf16(w bf16(x r))", .mode = .block, .layer = .sliding, .ctl = .norm_out }, + .{ .name = "control: ricursive_dflash2 tf_rcd_prep drops bf16(cos)", .mode = .block, .layer = .sliding, .ctl = .cos }, + .{ .name = "control: ricursive_dflash2 tf_rcd_prep drops bf16(sin)", .mode = .block, .layer = .sliding, .ctl = .sin }, + .{ .name = "control: ricursive_dflash2 tf_rcd_prep drops bf16(n c)", .mode = .block, .layer = .sliding, .ctl = .rot_c }, + .{ .name = "control: ricursive_dflash2 tf_rcd_prep drops bf16(rot s)", .mode = .block, .layer = .sliding, .ctl = .rot_s }, + .{ .name = "control: ricursive_dflash2 tf_rcd_prep truncates its output, not rounding it", .mode = .block, .layer = .sliding, .ctl = .out }, + .{ .name = "control: ricursive_dflash2 tf_rcd_prep rotates the NoPE layer", .mode = .block, .layer = .global, .ctl = .nope_ropes }, + .{ .name = "control: ricursive_dflash2 tf_rcd_prep wraps its ring by a power-of-two mask", .mode = .block, .layer = .sliding, .ctl = .mask }, +}; + +fn ringOf(l: Layer) usize { + return if (l == .sliding) sliding_ring else global_ring; +} + +/// Rows x streams x stream 0's first position: wraps of the ring, a row on its last slot, deep and last positions. +fn blockServed(comptime ring: usize) [5]c.Shape { + return .{ + .{ .rows = 16, .n = 1, .k = ring - 3 }, // one stream's block across its ring's wrap + .{ .rows = 1, .n = 1, .k = ring - 1 }, // a row on the ring's last slot + .{ .rows = 128, .n = 8, .k = ring - 3 }, // 8 streams' blocks across their wraps, each a ring further on + .{ .rows = 48, .n = 3, .k = 100_007 }, + .{ .rows = 32, .n = 2, .k = most_pos / ring * ring - 3 }, // the last wrap below 262,144, a stream a ring below it + }; +} + +fn contextServed(comptime ring: usize) [4]c.Shape { + return .{ + .{ .rows = 2048, .n = 1, .k = ring - 3 }, // a prompt chunk's context across the wrap + .{ .rows = 5, .n = 1, .k = most_pos / ring * ring - 3 }, + .{ .rows = 333, .n = 3, .k = 1000 }, // uneven streams: 111 rows each + .{ .rows = 64, .n = 4, .k = ring - 3 }, + }; +} + +const block_sliding = blockServed(sliding_ring); +const block_global = blockServed(global_ring); +const context_sliding = contextServed(sliding_ring); +const context_global = contextServed(global_ring); + +/// A lane's 4 fma steps, the warp's 5 shuffles. +fn prepDepth(_: c.Shape) usize { + return 4 + 5; +} + +pub fn prepSpec(e: PrepEntry) c.Spec { + const served: []const c.Shape = switch (e.mode) { + .block => if (e.layer == .sliding) &block_sliding else &block_global, + .context => if (e.layer == .sliding) &context_sliding else &context_global, + }; + return .{ .name = e.name, .accum = .f32, .depth = prepDepth, .out = .bf16, .served = served, .sums = .{} }; +} + +/// A call's streams: n row runs, stream s k + s rings on (k - s near the end), rings `spacing` apart in one buffer. +pub const Plan = struct { + rows: usize, + streams: usize, + k: usize, + ring: usize, + up: bool, + spacing: usize, + first: usize, + held: usize, + + /// Null when the streams' slots would overlap or a position reach 262,144; `full`: hold the whole ring. + pub fn of(shape: c.Shape, ring: usize, full: bool) ?Plan { + if (shape.rows == 0 or shape.n == 0) return null; + const streams = @min(shape.n, shape.rows); + const most = (shape.rows + streams - 1) / streams; + const spacing = std.mem.alignForward(usize, most, 32); + if (spacing * (streams - 1) + most >= ring) return null; + const reach = (streams - 1) * ring; + const up = shape.k + reach + most <= most_pos; + if (!up and (shape.k < reach or shape.k + most > most_pos)) return null; + const wraps = shape.k % ring + most > ring; + const whole = wraps or full; + return .{ + .rows = shape.rows, + .streams = streams, + .k = shape.k, + .ring = ring, + .up = up, + .spacing = spacing, + .first = if (whole) 0 else shape.k % ring, + .held = spacing * (streams - 1) + if (whole) ring else most, + }; + } + + pub fn len(p: Plan, s: usize) usize { + return p.rows / p.streams + @intFromBool(s < p.rows % p.streams); + } + + pub fn begin(p: Plan, s: usize) usize { + return s * (p.rows / p.streams) + @min(s, p.rows % p.streams); + } + + pub fn pos(p: Plan, s: usize) usize { + return if (p.up) p.k + s * p.ring else p.k - s * p.ring; + } + + /// Row j of stream s: its index among the buffer's held slots. + pub fn slot(p: Plan, s: usize, j: usize) usize { + return s * p.spacing + (p.pos(s) + j) % p.ring - p.first; + } +}; + +/// tf_rcd_prep: q [rows][80][128] (block rows), then the K and V buffers' held slots (unreached ones zero). +pub const Prep = struct { + f: Function, + entry: PrepEntry, + shape: c.Shape = undefined, + plan: Plan = undefined, + at: df.Layout = undefined, + inv: [D / 2]f32 = undefined, + x: []u16 = &.{}, + qw: []u16 = &.{}, + kw: []u16 = &.{}, + segs: []df.Segment = &.{}, + bufs: [2]u64 = @splat(0), // the K and V buffers as allocated + p: df.Prep = undefined, + + pub const sums = {}; + + pub fn spec(self: *const Prep) c.Spec { + return prepSpec(self.entry); + } + + pub fn control(self: *const Prep) ?g.Gate { + return if (self.entry.ctl != null) .shapes else null; + } + + pub fn free(self: *Prep, a: std.mem.Allocator) void { + for ([_]*[]u16{ &self.x, &self.qw, &self.kw }) |x| { + a.free(x.*); + x.* = &.{}; + } + a.free(self.segs); + self.segs = &.{}; + } + + /// Heads in [-3, 3) (one in 9 a tenth the size), weights in [-0.5, 0.5); stress: integers in [-32, 32]. + pub fn prepare(self: *Prep, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { + const ring = ringOf(self.entry.layer); + const plan = Plan.of(shape, ring, self.entry.full()) orelse return false; + self.free(a); + self.shape = shape; + self.plan = plan; + self.at = if (self.entry.mode == .block) df.Layout.block(heads, kv_heads) else df.Layout.context(kv_heads); + self.inv = df.inverseFrequencies(theta); + const rows = shape.rows; + const at = self.at; + self.x = try a.alloc(u16, rows * at.stride); + for (self.x, 0..) |*e, i| { + e.* = c.toBf16(if (fill == .stress) ref.int(rng, -32, 32) else (rng.float(f32) * 6 - 3) * (if (i % at.stride / D % 9 == 4) @as(f32, 0.1) else 1)); + } + if (fill == .nonfinite and rows >= 4) { + const lead = if (at.heads > 0) at.q_off else at.k_off; + self.x[lead + 3] = c.toBf16(ref.nan); // row 0's first head: its every output NaN + self.x[at.stride + at.k_off + D + 9] = c.toBf16(ref.inf); // row 1's second k head: r = 0, so dim 9 (and 73) NaN + self.x[2 * at.stride + at.k_off + 70] = c.toBf16(-ref.inf); // row 2's first k head, in the second half + self.x[3 * at.stride + at.v_off + 2 * D + 5] = c.toBf16(ref.inf); // row 3's third v head: copied as it is + } + self.qw = try ref.bfs(a, rng, D, -0.5, 0.5); + self.kw = try ref.bfs(a, rng, D, -0.5, 0.5); + const q = if (at.heads > 0) try rig.output(rows * at.heads * D * 2) else 0; // gathered in this order: q, k, v + const held = plan.held * kvw * 2; + self.bufs = .{ try rig.output(held), try rig.output(held) }; + self.segs = try a.alloc(df.Segment, plan.streams); + for (self.segs, 0..) |*sg, s| { + const off = (s * plan.spacing) * kvw * 2; + const back = plan.first * kvw * 2; // the rings' slot 0, so slot `first` lands on the buffer's first row + sg.* = .{ .k = self.bufs[0] + off - back, .v = self.bufs[1] + off - back, .begin = @intCast(plan.begin(s)), .pos = @intCast(plan.pos(s)) }; + } + try df.checkSegments(self.segs, rows, ring); + self.p = .{ + .x = try ref.input(rig, self.x), + .qw = try ref.input(rig, self.qw), + .kw = try ref.input(rig, self.kw), + .inv = try ref.input(rig, self.inv[0..]), + .segs = try ref.input(rig, self.segs), + .streams = plan.streams, + .q = q, + .rows = rows, + .kv_heads = kv_heads, + .at = at, + .ring = ring, + .rope = self.entry.layer == .sliding, + .eps = eps, + }; + return true; + } + + pub fn run(self: *Prep, rig: *rig_.Rig) !void { + for (self.bufs) |o| try rig.zero(o, self.plan.held * kvw * 2); // slots no row reaches: zero, as in the reference + try df.prepBy(self.f, rig.s, self.p); + } + + pub fn count(self: *const Prep) usize { + return self.shape.rows * self.at.heads * D + 2 * self.plan.held * kvw; + } + + /// One head's 128 outputs: bf16(w bf16(x r)), then (rope) bf16(bf16(n c) + bf16(rot s)) at the row's bf16 cos, sin. + fn head(s: Sums, x: []const u16, w: []const u16, rope: bool, cs: []const Iv, sn: []const Iv, out: []Iv, scratch: []f64) void { + var sq: [D]Iv = undefined; + var n: [D]Iv = undefined; + for (&sq, x) |*q, v| q.* = Iv.of(ref.bf(v) * ref.bf(v)); // the fma's product, exact + const r = s.sum(&sq, prepDepth(undefined), scratch).div(Iv.of(D)).add(Iv.of(eps)).rsqrt(); + for (&n, x, w) |*o, v, wv| o.* = Iv.of(ref.bf(wv)).mul(Iv.of(ref.bf(v)).mul(r).bf()).bf(); + for (out, 0..) |*o, d| { + if (!rope) { + o.* = n[d]; + continue; + } + const rot = if (d < D / 2) n[d + D / 2].neg() else n[d - D / 2]; + o.* = n[d].mul(cs[d % (D / 2)]).bf().add(rot.mul(sn[d % (D / 2)]).bf()).bf(); + } + } + + /// Every rounding point kept and the ring wrapped by its modulus, whatever the entry: a control must leave these. + pub fn solve(self: *const Prep, _: std.mem.Allocator, s: Sums, out: []Iv) !void { + const plan = self.plan; + const at = self.at; + const qn = self.shape.rows * at.heads * D; + const ks = out[qn..][0 .. plan.held * kvw]; + const vs = out[qn + plan.held * kvw ..]; + @memset(ks, Iv.of(0)); + @memset(vs, Iv.of(0)); + const rope = self.entry.layer == .sliding; + var scratch: [D]f64 = undefined; + var cs: [D / 2]Iv = undefined; + var sn: [D / 2]Iv = undefined; + for (0..plan.streams) |st| for (0..plan.len(st)) |j| { + const r = plan.begin(st) + j; + const position: f32 = @floatFromInt(plan.pos(st) + j); + for (&cs, &sn, self.inv) |*co, *si, f| { + const angle = Iv.of(position * f); // the kernel's fp32 angle, exactly + co.* = angle.trig(false).bf(); + si.* = angle.trig(true).bf(); + } + const t = plan.slot(st, j); + const xr = self.x[r * at.stride ..][0..at.stride]; + for (0..at.heads) |h| head(s, xr[at.q_off + h * D ..][0..D], self.qw, rope, &cs, &sn, out[(r * at.heads + h) * D ..][0..D], &scratch); + for (0..kv_heads) |h| head(s, xr[at.k_off + h * D ..][0..D], self.kw, rope, &cs, &sn, ks[t * kvw + h * D ..][0..D], &scratch); + for (vs[t * kvw ..][0..kvw], xr[at.v_off..][0..kvw]) |*o, v| o.* = Iv.of(ref.bf(v)); + }; + } +}; + +test "dflash2 prep: every served shape and the gates' small forms plan, stream slots apart and positions in range" { + const t = std.testing; + for (prep_entries) |e| { + const spec = prepSpec(e); + const ring = ringOf(e.layer); + var shapes: std.ArrayList(c.Shape) = .empty; + defer shapes.deinit(t.allocator); + try shapes.appendSlice(t.allocator, spec.served); + for ([_][2]usize{ .{ 5, 8 }, .{ 1, 64 } }) |lim| { + var x = spec.served[0]; + x.rows = std.math.clamp(x.rows, lim[0], lim[1]); + try shapes.append(t.allocator, x); + } + var deep = spec.served[0]; + for (spec.served) |x| if (x.k > deep.k) { + deep = x; + }; + deep.rows = @min(deep.rows, 4); + try shapes.append(t.allocator, deep); + for (shapes.items) |shape| { + const p = Plan.of(shape, ring, e.full()) orelse return error.TestUnexpectedResult; + const seen = try t.allocator.alloc(bool, p.held); + defer t.allocator.free(seen); + @memset(seen, false); + var rows: usize = 0; + for (0..p.streams) |s| { + try t.expectEqual(rows, p.begin(s)); + for (0..p.len(s)) |j| { + try t.expect(p.pos(s) + j < most_pos); + const at = p.slot(s, j); + try t.expect(at < p.held and !seen[at]); + seen[at] = true; + } + rows += p.len(s); + } + try t.expectEqual(shape.rows, rows); + if (e.full()) try t.expectEqual(@as(usize, 0), p.first); + } + } +} diff --git a/zig/tests/cuda/contract_ricursive_glue.zig b/zig/tests/cuda/contract_ricursive_glue.zig index e51c8fd8838..6bce0da5912 100644 --- a/zig/tests/cuda/contract_ricursive_glue.zig +++ b/zig/tests/cuda/contract_ricursive_glue.zig @@ -1,4 +1,4 @@ -//! Ripple's CUDA glue under the contract: tf_rc_embed, tf_rc_add_norm (four forms), tf_rc_gate, tf_rc_silu_clamp. +//! Ripple's CUDA glue in the contract: tf_rc_embed, tf_rc_add_norm (4 forms), tf_rc_gate, tf_rc_silu_clamp, tf_rc_tap. const std = @import("std"); const cuda = @import("cuda"); const core = @import("core"); @@ -14,8 +14,9 @@ const Iv = ref.Iv; const Sums = ref.Sums; const Kernels = kern.Kernels; const Function = cuda.Function; +const Tap = @import("contract_ricursive_tap.zig").Tap; // tf_rc_tap's check -const hidden = 5120; +pub const hidden = 5120; const query = 80 * 128; // the output gate's rows: query heads x head dim const intermediate = 40960; const vocab = 100352; @@ -456,6 +457,7 @@ pub const Set = struct { norm_ctls: [5]ref.Gated(AddNorm) = undefined, gates: [2]ref.Gated(Gate) = undefined, silus: [3]ref.Gated(SiluClamp) = undefined, + taps: [5]ref.Checked(Tap) = undefined, /// Every registration over `k`, appended to `list` (each control after the kernel it breaks). pub fn init(set: *Set, gpu: check.Gpu, s: cuda.Stream, k: *const Kernels, a: std.mem.Allocator, list: *std.ArrayList(g.Kernel)) !void { @@ -475,11 +477,19 @@ pub const Set = struct { .{ .rig = rig, .k = .{ .kern = k, .f = try k.mod.function("tf_rc_ctl_silu_round"), .drop = .round } }, .{ .rig = rig, .k = .{ .kern = k, .f = try k.mod.function("tf_rc_ctl_silu_no_lower"), .drop = .lower } }, }; + set.taps = .{ + .{ .rig = rig, .k = .{ .kern = k, .f = k.tap, .form = .chunk } }, + .{ .rig = rig, .k = .{ .kern = k, .f = k.tap, .form = .round } }, + .{ .rig = rig, .k = .{ .kern = k, .f = try k.mod.function("tf_rc_ctl_tap_column"), .form = .round, .fault = .column } }, + .{ .rig = rig, .k = .{ .kern = k, .f = try k.mod.function("tf_rc_ctl_tap_ring"), .form = .round, .fault = .ring } }, + .{ .rig = rig, .k = .{ .kern = k, .f = try k.mod.function("tf_rc_ctl_tap_swap"), .form = .round, .fault = .swap } }, + }; for (&set.embeds) |*x| try list.append(a, x.kernel()); for (&set.norms) |*x| try list.append(a, x.kernel()); for (&set.norm_ctls) |*x| try list.append(a, x.kernel()); for (&set.gates) |*x| try list.append(a, x.kernel()); for (&set.silus) |*x| try list.append(a, x.kernel()); + for (&set.taps) |*x| try list.append(a, x.kernel()); } pub fn deinit(set: *Set) void { @@ -488,5 +498,6 @@ pub const Set = struct { for (&set.norm_ctls) |*x| x.deinit(); for (&set.gates) |*x| x.deinit(); for (&set.silus) |*x| x.deinit(); + for (&set.taps) |*x| x.deinit(); } }; diff --git a/zig/tests/cuda/contract_ricursive_mask.zig b/zig/tests/cuda/contract_ricursive_mask.zig new file mode 100644 index 00000000000..ecc6bfe5cc1 --- /dev/null +++ b/zig/tests/cuda/contract_ricursive_mask.zig @@ -0,0 +1,127 @@ +//! Ripple's grammar mask under the contract: sample.cu's tf_grammar_mask as the backend launches it, and its control. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const rc = @import("ricursive_cuda"); +const check = @import("check.zig"); +const rig_ = @import("contract_rig.zig"); +const ref = @import("contract_minimax_glue_ref.zig"); // the family-neutral Checked wrapper + +const c = core.contract.spec; +const g = core.contract.gates; +const be = rc.backend; + +const vocab = 100352; +const threads = 256; // the backend's block: a thread takes every 256th word of a row +const masked: u16 = 0xFF80; // bf16 -inf + +/// A round's most rows, a full verify window, a first token's row and two short windows, at the vocabulary. +const served = [_]c.Shape{ .{ .rows = be.round_rows, .n = vocab, .k = 1 }, .{ .rows = 16, .n = vocab, .k = 1 }, .{ .rows = 1, .n = vocab, .k = 1 }, .{ .rows = 3, .n = vocab, .k = 1 }, .{ .rows = 7, .n = vocab, .k = 1 } }; + +pub fn maskSpec(control: bool) c.Spec { + const name = if (control) "control: cuda ricursive tf_grammar_mask reading a word's bits from the top (token t at bit 31 - t % 32)" else "cuda ricursive tf_grammar_mask (a row's disallowed tokens to -inf, in place)"; + const rule = "an allowed token keeps its bits, NaN patterns included; a disallowed token is -inf"; + return .{ .name = name, .accum = .none, .depth = ref.noSums, .out = .raw, .in_place = true, .nan = .{ .stated = rule }, .tiles = .{ .{}, .{ .size = 32 * threads, .step = 1, .min = 1 }, .{} }, .served = &served }; +} + +/// Rows of bf16 logits masked in place by each row's allowed-token words (lanes/grammar.zig's bit order). +pub const Mask = struct { + f: cuda.Function, + /// control: each word's bits read from the top + ctl: bool = false, + shape: c.Shape = undefined, + logits: []u16 = &.{}, + bits: []u32 = &.{}, + dev: u64 = 0, // the bits + out: u64 = 0, // the rows + + pub fn spec(self: *const Mask) c.Spec { + return maskSpec(self.ctl); + } + + pub fn control(self: *const Mask) ?g.Gate { + return if (self.ctl) .shapes else null; + } + + pub fn free(self: *Mask, a: std.mem.Allocator) void { + a.free(self.logits); + a.free(self.bits); + self.logits = &.{}; + self.bits = &.{}; + } + + /// Logits in [-30, 30); words all set, all clear or random; non-finite: NaN and -Inf allowed, +Inf disallowed. + pub fn prepare(self: *Mask, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { + if (shape.rows == 0 or shape.n == 0) return false; + self.free(a); + self.shape = shape; + const n = shape.n; + const nw = be.Ripple.maskWords(n); + self.logits = try ref.bfs(a, rng, shape.rows * n, -30, 30); + self.bits = try a.alloc(u32, shape.rows * nw); + for (self.bits) |*w| w.* = switch (rng.uintLessThan(u8, 4)) { + 0 => 0xFFFF_FFFF, + 1 => 0, + else => rng.int(u32), + }; + if (fill == .nonfinite) for ([_]f32{ ref.nan, ref.inf, -ref.inf }, [_]bool{ true, false, true }, 0..) |x, allowed, r| if (r < shape.rows) { + const t = (7 * r + 1) % n; + self.logits[r * n + t] = c.toBf16(x); + const bit = @as(u32, 1) << @intCast(t % 32); + const w = &self.bits[r * nw + t / 32]; + w.* = if (allowed) w.* | bit else w.* & ~bit; + }; + self.dev = try ref.input(rig, self.bits); + self.out = try rig.output(shape.rows * n * 2); // in place: restored before each launch + return true; + } + + pub fn run(self: *Mask, rig: *rig_.Rig) !void { + try ref.restore(rig, self.out, std.mem.sliceAsBytes(self.logits)); + var a: cuda.Args = .{}; + a.add(self.out); + a.add(@as(u32, @intCast(self.shape.n))); + a.add(self.dev); + a.add(@as(u32, @intCast(be.Ripple.maskWords(self.shape.n)))); + try cuda.launch.launch(self.f, .{ .grid = .{ .x = @intCast(self.shape.rows) }, .block = .{ .x = threads } }, rig.s, &a); + } + + pub fn count(self: *const Mask) usize { + return self.shape.rows * self.shape.n * 2; + } + + pub fn check(self: *const Mask, _: std.mem.Allocator, got: []const u8, msg: []u8) !?[]const u8 { + const n = self.shape.n; + const nw = be.Ripple.maskWords(n); + for (0..self.shape.rows) |r| for (0..n) |t| { + const allowed = (self.bits[r * nw + t / 32] >> @intCast(t % 32)) & 1 == 1; + const want: u16 = if (allowed) self.logits[r * n + t] else masked; + const have = std.mem.readInt(u16, got[(r * n + t) * 2 ..][0..2], .little); + if (have != want) return try std.fmt.bufPrint(msg, "row {d} token {d}: {x} where {x} is due", .{ r, t, have, want }); + }; + return null; + } +}; + +/// The registrations, held where the gates point at them (the caller's heap set). +pub const Set = struct { + sample: cuda.Module = undefined, + masks: [2]ref.Checked(Mask) = undefined, + + /// The served launch and its control (from `ctl`, contract_controls' image), appended to `list`. + pub fn init(set: *Set, gpu: check.Gpu, s: cuda.Stream, ctl: cuda.Module, a: std.mem.Allocator, list: *std.ArrayList(g.Kernel)) !void { + set.sample = try cuda.Module.load(gpu.d, cuda.kernels.sample); + errdefer set.sample.unload(); + const rig: rig_.Rig = .{ .gpu = gpu, .s = s }; + set.masks = .{ + .{ .rig = rig, .k = .{ .f = try set.sample.function("tf_grammar_mask") } }, + .{ .rig = rig, .k = .{ .f = try ctl.function("tf_ctl_rc_grammar_mask"), .ctl = true } }, + }; + for (&set.masks) |*x| try list.append(a, x.kernel()); + } + + pub fn deinit(set: *Set) void { + for (&set.masks) |*x| x.deinit(); + set.sample.unload(); + } +}; diff --git a/zig/tests/cuda/contract_ricursive_tap.zig b/zig/tests/cuda/contract_ricursive_tap.zig new file mode 100644 index 00000000000..8f952ca051a --- /dev/null +++ b/zig/tests/cuda/contract_ricursive_tap.zig @@ -0,0 +1,167 @@ +//! Ripple's CUDA tap in the contract: tf_rc_tap's chunks and rounds into the slots' rings, bit for bit, and controls. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const rc = @import("ricursive_cuda"); +const check = @import("check.zig"); +const rig_ = @import("contract_rig.zig"); +const ref = @import("contract_minimax_glue_ref.zig"); // the family-neutral Gated wrapper and fills + +const c = core.contract.spec; +const g = core.contract.gates; +const kern = rc.kernels; +const Kernels = kern.Kernels; +const Function = cuda.Function; + +const hidden = @import("contract_ricursive_glue.zig").hidden; + +const tap_ring = rc.model.tap_rows; // 2,064 rows a slot +const tap_cols = 5; // the drafter's tapped layers (1, 20, 39, 58, 77) +const tap_col = 2; // the column the registrations write +const tap_streams = 4; // a round's streams: row r stream r % 4's, each in one of 5 shuffled slots (the fifth never named) +const tap_apart = tap_ring + 1; // the streams' last positions apart: a ring row further round each +const tap_nan = "a bf16 copy: NaN patterns and both infinities land in the ring as stored"; +const tap_tile: c.Tile = .{ .size = 2048, .step = 8, .min = 8 }; // a block's 256 chunks of 8 values + +/// tf_rc_tap's calls: a prompt chunk (one slot, positions from p0) or a round (a position and a slot a row). +pub const TapForm = enum { chunk, round }; +/// A control's planted fault (ricursive.cu's tap bits). +pub const TapFault = enum { column, ring, swap }; + +/// Chunk: rows x width x the first position, in slot 1 of 2 (slot 0 never named). +const tap_chunk_served = [_]c.Shape{ + .{ .rows = 16, .n = hidden, .k = tap_ring - 8 }, // across the wrap: ring rows 2,056 to 2,063, then 0 to 7 + .{ .rows = 1, .n = hidden, .k = tap_ring - 1 }, + .{ .rows = 333, .n = hidden, .k = 4000 }, + .{ .rows = 2048, .n = hidden, .k = 1000 }, + .{ .rows = 2048, .n = hidden, .k = 262_144 - 2048 }, // the longest context's last chunk +}; + +/// Round: rows x width x the first stream's last position + 1 (the others end 2,065, 4,130 and 6,195 below it). +const tap_round_served = [_]c.Shape{ + .{ .rows = 64, .n = hidden, .k = 4 * tap_ring + 2 }, // verify windows of 16 ending at ring rows 1, 0, 2,063, 2,062 + .{ .rows = 4, .n = hidden, .k = 4 * tap_ring + 2 }, // a decode round: a row a stream + .{ .rows = 7, .n = hidden, .k = 3 * tap_apart + 3 }, // windows of 2, 2, 2 and 1, the last stream's row at position 2 + .{ .rows = 128, .n = hidden, .k = 100_007 }, // the backend's widest round + .{ .rows = 16, .n = hidden, .k = 262_144 }, // the longest context checked +}; + +pub fn tapSpec(form: TapForm, fault: ?TapFault) c.Spec { + const name = if (fault) |f| switch (f) { + .column => "control: cuda ricursive tf_rc_tap into the next tap column", + .ring => "control: cuda ricursive tf_rc_tap one ring row past pos % 2,064", + .swap => "control: cuda ricursive tf_rc_tap with rows 0 and 1 swapped", + } else switch (form) { + .chunk => "cuda ricursive tf_rc_tap, a prompt chunk (one slot from p0) into 2,064-row rings", + .round => "cuda ricursive tf_rc_tap, a round (4 streams' rows, a position and a slot each) into 2,064-row rings", + }; + const served: []const c.Shape = switch (form) { + .chunk => &tap_chunk_served, + .round => &tap_round_served, + }; + return .{ .name = name, .accum = .none, .depth = ref.noSums, .out = .bf16, .nan = .{ .stated = tap_nan }, .tiles = .{ .{}, tap_tile, .{} }, .served = served }; +} + +/// Rows stream i holds in a round of `rows`: rows i, i + 4, ... +fn tapStreamRows(rows: usize, i: usize) usize { + return (rows + tap_streams - 1 - i) / tap_streams; +} + +/// Rows into tap column 2 of 5 at ring row pos % 2,064 of each row's slot, exactly; every other ring row keeps poison. +pub const Tap = struct { + kern: *const Kernels, + f: Function, + form: TapForm, + fault: ?TapFault = null, + shape: c.Shape = undefined, + resid: []u16 = &.{}, + at: []i32 = &.{}, // row r's position + of: []i32 = &.{}, // row r's slot + slots: usize = 0, + dev: [3]u64 = @splat(0), // R, then a round's positions and slots + out: u64 = 0, + + pub fn spec(self: *const Tap) c.Spec { + return tapSpec(self.form, self.fault); + } + + pub fn control(self: *const Tap) ?g.Gate { + return if (self.fault != null) .shapes else null; + } + + pub fn free(self: *Tap, a: std.mem.Allocator) void { + a.free(self.resid); + a.free(self.at); + a.free(self.of); + self.resid = &.{}; + self.at = &.{}; + self.of = &.{}; + } + + /// R in [-4, 4); non-finite: NaN, +Inf and -Inf in its first rows. + pub fn prepare(self: *Tap, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { + const rows = shape.rows; + const n = shape.n; + const round = self.form == .round; + if (rows == 0 or n == 0 or n % 8 != 0) return false; + if (round) { + const most = tapStreamRows(rows, 0); + if (most > tap_ring or shape.k < (tap_streams - 1) * tap_apart + most) return false; + } else if (rows > tap_ring) return false; + self.free(a); + self.shape = shape; + self.resid = try ref.bfs(a, rng, rows * n, -4, 4); + if (fill == .nonfinite) for ([_]f32{ ref.nan, ref.inf, -ref.inf }, 0..) |x, r| if (r < rows) { + self.resid[r * n + (7 * r + 1) % n] = c.toBf16(x); + }; + self.at = try a.alloc(i32, rows); + self.of = try a.alloc(i32, rows); + if (round) { + self.slots = tap_streams + 1; + var ids: [tap_streams + 1]i32 = undefined; + for (&ids, 0..) |*x, i| x.* = @intCast(i); + rng.shuffle(i32, &ids); // stream i in slot ids[i] + for (self.at, self.of, 0..) |*x, *s, r| { + const i = r % tap_streams; + x.* = @intCast(shape.k - i * tap_apart - tapStreamRows(rows, i) + r / tap_streams); + s.* = ids[i]; + } + } else { + self.slots = 2; + for (self.at, self.of, 0..) |*x, *s, r| { + x.* = @intCast(shape.k + r); + s.* = 1; + } + } + self.dev = .{ try ref.input(rig, self.resid), 0, 0 }; + if (round) self.dev[1..].* = .{ try ref.input(rig, self.at), try ref.input(rig, self.of) }; + self.out = try rig.output(self.count() * 2); + return true; + } + + pub fn run(self: *Tap, rig: *rig_.Rig) !void { + const chunk = self.form == .chunk; + try kern.tapBy(self.f, rig.s, .{ .resid = self.dev[0], .ring = self.out, .pos = self.dev[1], .slot = self.dev[2], .p0 = if (chunk) self.shape.k else 0, .s0 = if (chunk) 1 else 0, .rows = self.shape.rows, .width = self.shape.n, .taps = tap_cols, .col = tap_col, .ring_rows = tap_ring }); + } + + pub fn count(self: *const Tap) usize { + return self.slots * tap_ring * tap_cols * self.shape.n; + } + + pub fn check(self: *const Tap, a: std.mem.Allocator, got: []const u8, msg: []u8) !?[]const u8 { + const n = self.shape.n; + const want = try a.alloc(u16, self.count()); + defer a.free(want); + @memset(want, 0xffff); // the output's poison where no row goes + for (self.at, self.of, 0..) |p, s, r| { + const row = (@as(usize, @intCast(s)) * tap_ring + @as(usize, @intCast(p)) % tap_ring) * tap_cols + tap_col; + @memcpy(want[row * n ..][0..n], self.resid[r * n ..][0..n]); + } + const bytes = std.mem.sliceAsBytes(want); + if (got.len != bytes.len) return try std.fmt.bufPrint(msg, "{d} output bytes where {d} are due", .{ got.len, bytes.len }); + const at = std.mem.indexOfDiff(u8, got, bytes) orelse return null; + const e = at / 2; + const row = e / n; + return try std.fmt.bufPrint(msg, "slot {d} ring row {d} column {d} value {d}: {x:0>4} where {x:0>4} is due", .{ row / tap_cols / tap_ring, row / tap_cols % tap_ring, row % tap_cols, e % n, std.mem.readInt(u16, got[e * 2 ..][0..2], .little), want[e] }); + } +}; diff --git a/zig/tests/cuda/main_usage.zig b/zig/tests/cuda/main_usage.zig index d97e88cc96c..ef5c16764c0 100644 --- a/zig/tests/cuda/main_usage.zig +++ b/zig/tests/cuda/main_usage.zig @@ -179,9 +179,12 @@ pub const usage = \\ pocket-contract Nemotron's pocket kernels (learned neurons) through gates 1-4, controls red \\ flashnext-modelopt-contract Flash Next NVFP4's BF16 dense and FP8 MTP-expert downs through gates 1-4 \\ minimax-contract MiniMax-M3.1-Flash's indexer and block-sparse attention through gates 1-4, controls red - \\ ricursive-contract Ripple's glue, attention prep and attention (group 10) through gates 1-4, controls red + \\ ricursive-contract Ripple's glue, attention prep, attention (group 10) and grammar mask through gates 1-4, controls red \\ ripple-forward Ripple's forward rounds (streams, verify windows, mixes) == one-row steps, bit for bit (synthetic) \\ ripple-serve Ripple's lane backend: shared rounds, copied drafts, kept states, logprob rows (synthetic) + \\ ricursive-dflash2-attn-contract Ripple's draft attention and top-32 through gates 1-4, controls red; timings + \\ ricursive-dflash2-contract Ripple's DFlash2 drafter glue (norms, prep, conv, SiLU) through gates 1-4, controls red + \\ ripple-drafted Ripple drafted by DFlash2: drafted == plain at 1, 2 and 8 streams, admission (synthetic) \\ moss-contract [ONLY..] MOSS-Image's own kernels, its decoder's unpack and its encoder's mixer, gates 1-4, controls red \\ idol-decoder-contract Idol's decoders' stem, to_kv, head norms and attention through gates 1-4, controls red \\ idol-contract Idol's denoiser glue and head-64 attention through gates 1-4, controls red diff --git a/zig/tests/cuda/ripple_commands.zig b/zig/tests/cuda/ripple_commands.zig index cc60d2ead9f..6406670f684 100644 --- a/zig/tests/cuda/ripple_commands.zig +++ b/zig/tests/cuda/ripple_commands.zig @@ -6,6 +6,12 @@ const check = @import("check.zig"); pub fn run(gpu: check.Gpu, cmd: []const u8) !bool { if (std.mem.eql(u8, cmd, "ricursive-contract")) { try @import("contract_ricursive.zig").run(gpu); + } else if (std.mem.eql(u8, cmd, "ricursive-dflash2-contract")) { + try @import("contract_ricursive_dflash2.zig").run(gpu); + } else if (std.mem.eql(u8, cmd, "ricursive-dflash2-attn-contract")) { + try @import("contract_ricursive_dflash2_attn.zig").run(gpu); + } else if (std.mem.eql(u8, cmd, "ripple-drafted")) { + try @import("ripple_drafted_tests.zig").run(gpu); } else if (std.mem.eql(u8, cmd, "ripple-forward")) { try @import("ripple_forward_tests.zig").run(gpu); } else if (std.mem.eql(u8, cmd, "ripple-serve")) { diff --git a/zig/tests/cuda/ripple_drafted_tests.zig b/zig/tests/cuda/ripple_drafted_tests.zig new file mode 100644 index 00000000000..cb40643e2a6 --- /dev/null +++ b/zig/tests/cuda/ripple_drafted_tests.zig @@ -0,0 +1,378 @@ +//! Ripple drafted by DFlash2 on CUDA (ripple-drafted): drafted == plain at 1, 2 and 8 streams, masked too; admission. +const std = @import("std"); +const cuda = @import("cuda"); +const lanes = @import("lanes"); +const rc = @import("ricursive_cuda"); +const check = @import("check.zig"); + +const fwd = rc.model; +const wts = rc.weights; +const be = rc.backend; +const nat = rc.native; +const dfl = rc.dflash2; +const dw = rc.dflash2_weights; +const Stream = lanes.Stream; +const Backend = lanes.backend.Backend; +const Weight = cuda.qmmf.Weight; + +const fixture = @import("ripple_forward_tests.zig"); // the release-width target on 10 layers + +/// The streams' prompts: four past the tap ring's wrap, two past the sliding rings' (4,224 rows). +const prompts = [_]usize{ 4500, 37, 2100, 4300, 600, 2070, 1500, 4241 }; +const slots = prompts.len; +const max_new = 40; + +/// The release drafter's geometry at the fixture's vocabulary and an FFN of the target's width, its taps in 10 layers. +fn drafterConfig(vocab: u32) dfl.Config { + var c: dfl.Config = .{ .layers = 5, .heads = 80, .kv_heads = 8, .hidden = 5120, .ffn = 12288, .vocab = vocab, .window = 4096, .block = 16, .mask = vocab - 384, .rank = 256, .top = 32, .group = 16, .conv = 4, .taps = .{ 1, 3, 5, 7, 8 }, .theta = 10000, .eps = 1e-6 }; + c.global[4] = true; + c.rope[4] = false; + return c; +} + +fn bf16(x: f32) u16 { + const b: u32 = @bitCast(x); + return @intCast((b + 0x7fff + ((b >> 16) & 1)) >> 16); +} + +/// Device copies into the drafter's weights, as fixture.build makes the target's. +const Build = struct { + w: *dw.Weights, + d: *const cuda.Driver, + r: std.Random, + + fn put(b: Build, bytes: []const u8) !u64 { + var buf = try cuda.DeviceBuffer.fromHost(b.d, bytes); + errdefer buf.free(); + try b.w.buffers.append(b.w.gpa, buf); + b.w.bytes += bytes.len; + return buf.ptr; + } + + /// `n` bf16 values of magnitude in [2^e, 2^(e+1)), random signs and mantissas. + fn values(b: Build, n: usize, e: i32) ![]u16 { + const v = try b.w.gpa.alloc(u16, n); + const exp: u16 = @intCast((e + 127) << 7); + var bits: u64 = 0; + for (v, 0..) |*x, i| { + if (i % 4 == 0) bits = b.r.int(u64); + x.* = exp | @as(u16, @truncate(bits & 0x807f)); + bits >>= 16; + } + return v; + } + + fn small(b: Build, n: usize, mean: f32, sd: f32) !u64 { + const v = try b.w.gpa.alloc(u16, n); + defer b.w.gpa.free(v); + for (v) |*x| x.* = bf16(mean + sd * b.r.floatNorm(f32)); + return b.put(std.mem.sliceAsBytes(v)); + } + + fn scaleOf(k: usize) i32 { + return -@as(i32, std.math.log2_int(usize, k) / 2) - 1; + } + + /// `src` [n, k] packed for the lane and prompt matmuls. + fn pack(b: Build, src: []const u16, n: usize, k: usize) !Weight { + const out = try b.w.gpa.alloc(u16, cuda.modelopt.padded(n) * k); + defer b.w.gpa.free(out); + cuda.qmmf.packBf16(out, src, n, k); + return cuda.modelopt.bf16Weight(try b.put(std.mem.sliceAsBytes(out)), n, k); + } + + fn dense(b: Build, n: usize, k: usize) !Weight { + const src = try b.values(n * k, scaleOf(k)); + defer b.w.gpa.free(src); + return b.pack(src, n, k); + } + + fn conv(b: Build, c: dfl.Config) !dw.Conv { + return .{ .base = try b.small(2 * @as(usize, c.conv) * c.hidden, 0, 0.2), .proj = try b.dense(c.dyn(), c.hidden) }; + } +}; + +/// Random drafter weights in B's layout: q|k|v and the absorb's k|v from the same k and v rows. +fn buildDrafter(gpu: check.Gpu, c: dfl.Config, seed: u64) !dw.Weights { + const gpa = gpu.gpa; + var w: dw.Weights = .{ .gpa = gpa, .config = c, .fc = undefined, .hproj = undefined, .hidden_norm = 0, .norm = 0, .layers = undefined, .pred = &.{}, .succ = &.{} }; + errdefer w.deinit(); + var prng = std.Random.DefaultPrng.init(seed); + const b: Build = .{ .w = &w, .d = gpu.d, .r = prng.random() }; + const h: usize = c.hidden; + const qw = @as(usize, c.heads) * 128; + const kvw = @as(usize, c.kv_heads) * 128; + w.fc = try b.dense(h, 5 * h); + w.hproj = try b.dense(c.rank, h); + w.hidden_norm = try b.small(h, 1, 0.1); + w.norm = try b.small(h, 1, 0.1); + w.pred = try b.values(@as(usize, c.vocab) * c.rank, -4); + w.succ = try b.values(@as(usize, c.vocab) * c.rank, -4); + for (w.layers[0..c.layers]) |*l| { + const qkv = try b.values((qw + 2 * kvw) * h, Build.scaleOf(h)); + defer gpa.free(qkv); + l.* = .{ + .qkv = try b.pack(qkv, qw + 2 * kvw, h), + .kv = try b.pack(qkv[qw * h ..], 2 * kvw, h), + .o = try b.dense(h, qw), + .gate_up = try b.dense(2 * @as(usize, c.ffn), h), + .down = try b.dense(h, c.ffn), + .attn_conv = try b.conv(c), + .mlp_conv = try b.conv(c), + .in_norm = try b.small(h, 1, 0.1), + .post_norm = try b.small(h, 1, 0.1), + .q_norm = try b.small(128, 1, 0.1), + .k_norm = try b.small(128, 1, 0.1), + }; + } + return w; +} + +fn sampling(j: usize) lanes.Sampling { + return .{ .seed = 0x5eed + j, .temperature = 1.0, .top_p = 0.95, .top_k = 20 }; +} + +/// A test grammar with no end: odd tokens at even steps, even at odd, so a mask at the wrong window row is rejected. +const Parity = struct { + at: u32 = 0, + + fn rules(g: *Parity) lanes.grammar.Rules { + return .{ .ptr = g, .vtable = &.{ .accept = accept, .rollback = rollback, .terminated = terminated, .fill = fill, .drafts = drafts, .free = free } }; + } + + fn cast(ptr: *anyopaque) *Parity { + return @ptrCast(@alignCast(ptr)); + } + + fn allows(at: usize, t: u32) bool { + return (t + at) % 2 == 1; + } + + fn accept(ptr: *anyopaque, t: u32) anyerror!bool { + const g = cast(ptr); + if (!allows(g.at, t)) return false; + g.at += 1; + return true; + } + + fn rollback(ptr: *anyopaque, n: usize) anyerror!void { + cast(ptr).at -= @intCast(n); + } + + fn terminated(_: *anyopaque) bool { + return false; + } + + fn fill(ptr: *anyopaque, words: []u32) anyerror!void { + @memset(words, if (cast(ptr).at % 2 == 0) 0xAAAA_AAAA else 0x5555_5555); + } + + fn drafts(_: *anyopaque, _: []u32) anyerror!usize { + return 0; + } + + fn free(_: *anyopaque) void {} +}; + +/// A run's streams' tokens and its drafts. +const Got = struct { ids: [slots][]const u32 = @splat(&.{}), drafted: u64 = 0, accepted: u64 = 0, rounds: u64 = 0 }; + +/// Streams `which` through one lanes.Engine as the lane host runs them: a prompt chunk between rounds, to max_new. +fn serve(gpu: check.Gpu, a: std.mem.Allocator, cfg: *const lanes.Config, backend: Backend, ids: *const [slots][]u32, which: []const usize, sampled: bool, drafts: bool, under: bool) !Got { + var wall: lanes.backend.WallClock = .{ .io = gpu.io }; + var le = lanes.Engine.init(gpu.gpa, cfg, backend, wall.clock()); + defer le.deinit(); + var ss: [slots]Stream = undefined; + var made: usize = 0; + defer for (ss[0..made]) |*s| s.deinit(gpu.gpa); + var parities: [slots]Parity = @splat(.{}); + var grammars: [slots]lanes.grammar.Constraint = undefined; + for (which, 0..) |j, i| { + if (under) grammars[i] = .init(parities[i].rules(), be.Ripple.maskWords(fixture.config().vocab), null); + ss[i] = try Stream.init(gpu.gpa, .{ .id = "drafted", .prompt = ids[j], .max_new = max_new, .drafts = drafts, .sampling = if (sampled) sampling(j) else null, .grammar = if (under) &grammars[i] else null }); + made += 1; + } + var filling: usize = 0; + var first = true; + while (filling < made or le.activeCount() > 0) { + if (filling < made) { + first = if (try le.fillStream(&ss[filling], first)) blk: { + filling += 1; + break :blk true; + } else false; + } + if (le.activeCount() > 0) try le.step(); + } + var got: Got = .{}; + for (which, ss[0..made]) |j, *s| { + got.ids[j] = try a.dupe(u32, s.emitted()); + got.drafted += s.drafted; + got.accepted += s.accepted; + got.rounds += s.rounds; + } + return got; +} + +/// Each stream of `which` as its reference, token for token; the first difference printed. +fn same(comptime what: []const u8, args: anytype, got: *const Got, want: *const Got, which: []const usize) bool { + var ok = true; + for (which) |j| { + const g = got.ids[j]; + const w = want.ids[j]; + if (g.len == max_new and std.mem.eql(u32, g, w)) continue; + var i: usize = 0; + while (i < @min(g.len, w.len) and g[i] == w[i]) i += 1; + std.debug.print(" DIFF ", .{}); + std.debug.print(what, args); + std.debug.print(": stream {d} (prompt {d}): token {d} of {d} is {d}, want {d}\n", .{ j, prompts[j], i, g.len, if (i < g.len) g[i] else 0, if (i < w.len) w[i] else 0 }); + ok = false; + } + return ok; +} + +fn gib(b: u64) f64 { + return @as(f64, @floatFromInt(b)) / (1 << 30); +} + +pub fn run(gpu: check.Gpu) !void { + var arena = std.heap.ArenaAllocator.init(gpu.gpa); + defer arena.deinit(); + const a = arena.allocator(); + const c = fixture.config(); + try wts.gate(&c); + var s = try cuda.Stream.init(gpu.d, false); + defer s.deinit(); + var w = try fixture.build(gpu, c, 0x7269_7070); + defer w.deinit(); + var k = try fwd.Kernels.load(gpu.ctx); + defer k.deinit(); + var m = try fwd.Model.init(gpu.gpa, gpu.d, s, &w, &k, c.context, slots, be.round_rows); + defer m.deinit(); + var rb = try be.Ripple.init(gpu.gpa, gpu.d, &m); + defer rb.deinit(); + var ids: [slots][]u32 = undefined; + var prng = std.Random.DefaultPrng.init(0x6472_6166); + for (&ids, prompts) |*p, n| { + p.* = try a.alloc(u32, n); + for (p.*) |*t| t.* = prng.random().uintLessThan(u32, @intCast(c.vocab)); + } + const all = [_]usize{ 0, 1, 2, 3, 4, 5, 6, 7 }; + var fails: usize = 0; + + // the references: plain Ripple, no taps, every stream at once + var plain_cfg = try lanes.Config.init(gpu.gpa, rb.facts(), be.max_window, be.max_window - 1); + defer plain_cfg.deinit(gpu.gpa); + const greedy = try serve(gpu, a, &plain_cfg, rb.backend(), &ids, &all, false, false, false); + const sampled = try serve(gpu, a, &plain_cfg, rb.backend(), &ids, &all, true, false, false); + + // the drafter: its bytes past the weights (the scratch, 8 streams' rings, the tap rings setTaps makes) == runBytes + const dc = drafterConfig(@intCast(c.vocab)); + try dfl.gate(&dc); + const weights = try buildDrafter(gpu, dc, 0x6466_6c32); + std.debug.print(" the drafter's weights: {d} bytes ({d} as B packs the release's layout)\n", .{ weights.bytes, dw.deviceBytes(dc) }); + const before = cuda.usage(false).device; + const d = try dfl.Drafter.init(gpu.gpa, gpu.io, &m, weights, slots); + defer d.deinit(); + var dd = try lanes.drafted.Drafted.init(gpu.gpa, rb.backend(), d.drafter()); + defer dd.deinit(); + const grew = cuda.usage(false).device - before; + const want_run = dfl.runBytes(&dc, c, k.lane.clusters, slots); + if (grew == want_run) { + check.pass("ripple-drafted bytes: the drafter's scratch, rings and tap rings for {d} streams take {d} bytes, as admission counts them", .{ slots, grew }); + } else { + std.debug.print("FAIL ripple-drafted bytes: the drafter took {d} bytes past its weights, admission counts {d}\n", .{ grew, want_run }); + fails += 1; + } + + // admission: the drafter's bytes leave fewer streams, as they predict; one that leaves none is refused by name + const plain: nat.Plan = .{ .w = &w, .k = &k, .positions = c.context }; + var drafted_plan = plain; + drafted_plan.drafter = dc; + const room = try drafted_plan.bytes(3) + 1; + var predicted: usize = slots; + while (predicted > 0 and try plain.bytes(predicted) + dfl.openBytes(&dc, c, k.lane.clusters, predicted) > room) predicted -= 1; + const plain_n = try nat.admitted(room, slots, false, c.context, plain, null); + const drafted_n = try nat.admitted(room, slots, false, c.context, plain, dc); + const tight = try plain.bytes(1) + dfl.openBytes(&dc, c, k.lane.clusters, 1) - 1; + const refused = if (nat.admitted(tight, slots, false, c.context, plain, dc)) |_| false else |e| e == error.DrafterPastMemory; + if (drafted_n == predicted and predicted == 3 and plain_n > drafted_n and refused and nat.explain(null, error.DrafterPastMemory) != null) { + check.pass("ripple-drafted admission: {d:.2} GiB of room holds {d} plain streams and {d} with the drafter ({d:.2} GiB at 3), as its bytes predict; {d:.2} GiB refused by name (DrafterPastMemory)", .{ gib(room), plain_n, drafted_n, gib(dfl.openBytes(&dc, c, k.lane.clusters, 3)), gib(tight) }); + } else { + std.debug.print("FAIL ripple-drafted admission: {d} streams with the drafter, {d} predicted, {d} plain; the tight room refused by name: {}\n", .{ drafted_n, predicted, plain_n, refused }); + fails += 1; + } + + // the target's windows timed (the server's calibration), then rounds that always offer drafts + try d.timeWindows(); + var facts = dd.facts(rb.facts()); + facts.plain_guard = false; // a random drafter's drafts would lose to plain rounds; here every round drafts + var cfg = try lanes.Config.init(gpu.gpa, facts, be.max_window, be.max_window - 1); + defer cfg.deinit(gpu.gpa); + + // 1. the drafter loaded (taps on), streams without drafts: plain's tokens + const unused = try serve(gpu, a, &cfg, dd.backend(), &ids, &all, false, false, false); + if (same("loaded, unused", .{}, &unused, &greedy, &all) and unused.drafted == 0) { + check.pass("ripple-drafted unused: {d} streams with the drafter loaded and no drafts == plain, token for token", .{slots}); + } else { + std.debug.print("FAIL ripple-drafted unused: {d} drafts, or tokens differ\n", .{unused.drafted}); + fails += 1; + } + + // 2. drafted == plain at 1, 2 and 8 streams, greedy and sampled + const sets = [_][]const usize{ &.{0}, &.{ 1, 3 }, &all, &.{7}, &.{ 2, 0 }, &all }; + var drafted_all: u64 = 0; + var accepted_all: u64 = 0; + for (sets, 0..) |which, i| { + const keyed = i >= 3; + const got = try serve(gpu, a, &cfg, dd.backend(), &ids, which, keyed, true, false); + const want = if (keyed) &sampled else &greedy; + drafted_all += got.drafted; + accepted_all += got.accepted; + const kind = if (keyed) "sampled" else "greedy"; + if (same("{s} at {d} streams", .{ kind, which.len }, &got, want, which) and got.drafted > 0) { + check.pass("ripple-drafted {s}, {d} stream{s}: == plain, token for token; {d} drafts offered, {d} accepted in {d} rounds", .{ kind, which.len, if (which.len == 1) "" else "s", got.drafted, got.accepted, got.rounds }); + } else { + std.debug.print("FAIL ripple-drafted {s}, {d} streams: {d} drafts offered, or tokens differ\n", .{ kind, which.len, got.drafted }); + fails += 1; + } + } + // a verify kept part of its window (drafts rejected past the pending row's) + if (drafted_all > accepted_all) { + check.pass("ripple-drafted accept count: {d} of {d} drafts accepted ({d:.1}%; a random drafter's, a report not a gate), every rejecting verify keeping part of its window", .{ accepted_all, drafted_all, 100 * @as(f64, @floatFromInt(accepted_all)) / @as(f64, @floatFromInt(@max(drafted_all, 1))) }); + } else { + std.debug.print("FAIL ripple-drafted: no verify rejected a draft ({d} of {d} accepted)\n", .{ accepted_all, drafted_all }); + fails += 1; + } + + // 3. under a grammar's masks: plain replies stay in the grammar; drafted == plain at 1, 2 and 8 streams + const greedy_in = try serve(gpu, a, &plain_cfg, rb.backend(), &ids, &all, false, false, true); + const sampled_in = try serve(gpu, a, &plain_cfg, rb.backend(), &ids, &all, true, false, true); + var inside = true; + var moved: usize = 0; + for ([_]*const Got{ &greedy_in, &sampled_in }, [_]*const Got{ &greedy, &sampled }) |got, free_run| { + for (all) |j| { + inside = inside and got.ids[j].len == max_new; + for (got.ids[j], 0..) |t, i| inside = inside and Parity.allows(i, t); + moved += @intFromBool(!std.mem.eql(u32, got.ids[j], free_run.ids[j])); + } + } + if (inside and moved == 2 * slots) { + check.pass("ripple-drafted grammar, plain: {d} streams greedy and sampled, every token of {d} in its grammar (odd, even, odd, ...), each reply other than the one with no grammar", .{ slots, max_new }); + } else { + std.debug.print("FAIL ripple-drafted grammar, plain: every token in its grammar: {}; {d} of {d} replies differ from those with no grammar\n", .{ inside, moved, 2 * slots }); + fails += 1; + } + for (sets, 0..) |which, i| { + const keyed = i >= 3; + const got = try serve(gpu, a, &cfg, dd.backend(), &ids, which, keyed, true, true); + const want = if (keyed) &sampled_in else &greedy_in; + const kind = if (keyed) "sampled" else "greedy"; + if (same("{s} under a grammar at {d} streams", .{ kind, which.len }, &got, want, which) and got.drafted > 0) { + check.pass("ripple-drafted grammar, {s}, {d} stream{s}: == plain under the same grammar, token for token; {d} drafts offered, {d} accepted in {d} rounds", .{ kind, which.len, if (which.len == 1) "" else "s", got.drafted, got.accepted, got.rounds }); + } else { + std.debug.print("FAIL ripple-drafted grammar, {s}, {d} streams: {d} drafts offered, or tokens differ\n", .{ kind, which.len, got.drafted }); + fails += 1; + } + } + try check.expect(fails == 0, "ripple-drafted: {d} checks differ", .{fails}); +} diff --git a/zig/tests/cuda/ripple_fixture.zig b/zig/tests/cuda/ripple_fixture.zig new file mode 100644 index 00000000000..df587e40f5c --- /dev/null +++ b/zig/tests/cuda/ripple_fixture.zig @@ -0,0 +1,118 @@ +//! Ripple's forward test target: the release's widths on 10 layers, random weights in the loader's layout. +const std = @import("std"); +const cuda = @import("cuda"); +const rc = @import("ricursive_cuda"); +const check = @import("check.zig"); + +const wts = rc.weights; +const Config = @FieldType(wts.Weights, "config"); +const Weight = cuda.qmmf.Weight; + +/// The release's attention and widths, so every lane matmul takes the release's plan (tile, K slices, cluster). +pub fn config() Config { + var c: Config = .{ .hidden = 5120, .intermediate = 12288, .layers = 10, .heads = 80, .kv_heads = 8, .vocab = 16384, .eps = 1e-6, .theta = 10000, .window = 1024, .embed_scale = 71.55417527999327, .clamp = 20, .context = 8192, .fp4_mlp = true }; + for (0..c.layers) |i| c.global[i] = i % 5 == 4; + return c; +} + +/// bf16 bits of x, rounded to nearest even. +fn bf16(x: f32) u16 { + const b: u32 = @bitCast(x); + return @intCast((b + 0x7fff + ((b >> 16) & 1)) >> 16); +} + +const Build = struct { + w: *wts.Weights, + d: *const cuda.Driver, + r: std.Random, + + fn put(b: Build, bytes: []const u8) !u64 { + var buf = try cuda.DeviceBuffer.fromHost(b.d, bytes); + errdefer buf.free(); + try b.w.buffers.append(b.w.gpa, buf); + b.w.bytes += bytes.len; + return buf.ptr; + } + + /// `n` bf16 values of magnitude in [2^e, 2^(e+1)), random signs and mantissas (fast: the release's sizes). + fn values(b: Build, n: usize, e: i32) ![]u16 { + const v = try b.w.gpa.alloc(u16, n); + const exp: u16 = @intCast((e + 127) << 7); + var bits: u64 = 0; + for (v, 0..) |*x, i| { + if (i % 4 == 0) bits = b.r.int(u64); + x.* = exp | @as(u16, @truncate(bits & 0x807f)); + bits >>= 16; + } + return v; + } + + /// A norm's or the embedding's bf16 values, normal with deviation `sd` around `mean`. + fn small(b: Build, n: usize, mean: f32, sd: f32) !u64 { + const v = try b.w.gpa.alloc(u16, n); + defer b.w.gpa.free(v); + for (v) |*x| x.* = bf16(mean + sd * b.r.floatNorm(f32)); + return b.put(std.mem.sliceAsBytes(v)); + } + + /// A bf16 [n, k] projection packed for the lane and prompt matmuls, its values about 1 / sqrt(k). + fn dense(b: Build, n: usize, k: usize) !Weight { + const src = try b.values(n * k, -@as(i32, std.math.log2_int(usize, k) / 2) - 1); + defer b.w.gpa.free(src); + const out = try b.w.gpa.alloc(u16, cuda.modelopt.padded(n) * k); + defer b.w.gpa.free(out); + cuda.qmmf.packBf16(out, src, n, k); + return cuda.modelopt.bf16Weight(try b.put(std.mem.sliceAsBytes(out)), n, k); + } + + /// An NVFP4 [n, k] projection: random nibbles, E4M3 scales of 1 to 3, a global of 1/1024 (about 1 / sqrt(k)). + fn fp4(b: Build, n: usize, k: usize) !Weight { + const gpa = b.w.gpa; + const codes = try gpa.alloc(u8, n * k / 2); + defer gpa.free(codes); + b.r.bytes(codes); + const scales = try gpa.alloc(u8, n * k / 16); + defer gpa.free(scales); + const e4m3 = [_]u8{ 0x38, 0x3c, 0x40, 0x44 }; + b.r.bytes(scales); + for (scales) |*x| x.* = e4m3[x.* & 3]; + const words = try gpa.alloc(u32, cuda.nvfp4.padded(n) / 64 * (k / 64) * 512); + defer gpa.free(words); + const tiles = try gpa.alloc(u8, cuda.nvfp4.padded(n) * (k / 16)); + defer gpa.free(tiles); + cuda.nvfp4.packWords(words, codes, n, k); + cuda.nvfp4.packScales(tiles, scales, n, k); + return cuda.nvfp4.weight(try b.put(std.mem.sliceAsBytes(words)), try b.put(tiles), 1.0 / 1024.0, n, k); + } +}; + +/// Random weights in the loader's layout (cuda_weights.load): q, k and g one projection, NVFP4 MLPs. +pub fn build(gpu: check.Gpu, c: Config, seed: u64) !wts.Weights { + var w: wts.Weights = .{ .gpa = gpu.gpa, .config = c }; + errdefer w.deinit(); + var prng = std.Random.DefaultPrng.init(seed); + const b: Build = .{ .w = &w, .d = gpu.d, .r = prng.random() }; + const h = c.hidden; + const q = c.queryWidth(); + const kv = c.kvWidth(); + w.embed = try b.small(c.vocab * h, 0, 0.02); + w.head = try b.dense(c.vocab, h); + w.norm = try b.small(h, 1, 0.1); + w.layers = try gpu.gpa.alloc(wts.Layer, c.layers); + for (w.layers) |*l| l.* = .{ + .qkg = try b.dense(2 * q + kv, h), + .v = try b.dense(kv, h), + .o = try b.dense(h, q), + .gate = try b.fp4(c.intermediate, h), + .up = try b.fp4(c.intermediate, h), + .down = try b.fp4(h, c.intermediate), + .input_norm = try b.small(h, 1, 0.1), + .post_attn = try b.small(h, 1, 0.1), + .pre_ffn = try b.small(h, 1, 0.1), + .post_ffn = try b.small(h, 1, 0.1), + .q_norm = try b.small(128, 1, 0.1), + .k_norm = try b.small(128, 1, 0.1), + .blend = wts.blendOf(bf16(b.r.float(f32) * 2 - 1)), + }; + return w; +} diff --git a/zig/tests/cuda/ripple_forward_tests.zig b/zig/tests/cuda/ripple_forward_tests.zig index 4b5851ab592..6891ef617e6 100644 --- a/zig/tests/cuda/ripple_forward_tests.zig +++ b/zig/tests/cuda/ripple_forward_tests.zig @@ -1,4 +1,4 @@ -//! Ripple's forward rounds == one-row steps, bit for bit (ripple-forward): streams, verify windows, graphs, reuse. +//! Ripple's forward rounds == one-row steps, bit for bit (ripple-forward): streams, windows, graphs, reuse, taps. const std = @import("std"); const cuda = @import("cuda"); const rc = @import("ricursive_cuda"); @@ -6,117 +6,10 @@ const check = @import("check.zig"); const fwd = rc.model; const wts = rc.weights; -const Config = @FieldType(wts.Weights, "config"); -const Weight = cuda.qmmf.Weight; - -/// The release's attention and widths, so every lane matmul takes the release's plan (tile, K slices, cluster). -pub fn config() Config { - var c: Config = .{ .hidden = 5120, .intermediate = 12288, .layers = 10, .heads = 80, .kv_heads = 8, .vocab = 16384, .eps = 1e-6, .theta = 10000, .window = 1024, .embed_scale = 71.55417527999327, .clamp = 20, .context = 8192, .fp4_mlp = true }; - for (0..c.layers) |i| c.global[i] = i % 5 == 4; - return c; -} - -/// bf16 bits of x, rounded to nearest even. -fn bf16(x: f32) u16 { - const b: u32 = @bitCast(x); - return @intCast((b + 0x7fff + ((b >> 16) & 1)) >> 16); -} - -const Build = struct { - w: *wts.Weights, - d: *const cuda.Driver, - r: std.Random, - - fn put(b: Build, bytes: []const u8) !u64 { - var buf = try cuda.DeviceBuffer.fromHost(b.d, bytes); - errdefer buf.free(); - try b.w.buffers.append(b.w.gpa, buf); - b.w.bytes += bytes.len; - return buf.ptr; - } - - /// `n` bf16 values of magnitude in [2^e, 2^(e+1)), random signs and mantissas (fast: the release's sizes). - fn values(b: Build, n: usize, e: i32) ![]u16 { - const v = try b.w.gpa.alloc(u16, n); - const exp: u16 = @intCast((e + 127) << 7); - var bits: u64 = 0; - for (v, 0..) |*x, i| { - if (i % 4 == 0) bits = b.r.int(u64); - x.* = exp | @as(u16, @truncate(bits & 0x807f)); - bits >>= 16; - } - return v; - } +const fixture = @import("ripple_fixture.zig"); // the release-width target's random weights - /// A norm's or the embedding's bf16 values, normal with deviation `sd` around `mean`. - fn small(b: Build, n: usize, mean: f32, sd: f32) !u64 { - const v = try b.w.gpa.alloc(u16, n); - defer b.w.gpa.free(v); - for (v) |*x| x.* = bf16(mean + sd * b.r.floatNorm(f32)); - return b.put(std.mem.sliceAsBytes(v)); - } - - /// A bf16 [n, k] projection packed for the lane and prompt matmuls, its values about 1 / sqrt(k). - fn dense(b: Build, n: usize, k: usize) !Weight { - const src = try b.values(n * k, -@as(i32, std.math.log2_int(usize, k) / 2) - 1); - defer b.w.gpa.free(src); - const out = try b.w.gpa.alloc(u16, cuda.modelopt.padded(n) * k); - defer b.w.gpa.free(out); - cuda.qmmf.packBf16(out, src, n, k); - return cuda.modelopt.bf16Weight(try b.put(std.mem.sliceAsBytes(out)), n, k); - } - - /// An NVFP4 [n, k] projection: random nibbles, E4M3 scales of 1 to 3, a global of 1/1024 (about 1 / sqrt(k)). - fn fp4(b: Build, n: usize, k: usize) !Weight { - const gpa = b.w.gpa; - const codes = try gpa.alloc(u8, n * k / 2); - defer gpa.free(codes); - b.r.bytes(codes); - const scales = try gpa.alloc(u8, n * k / 16); - defer gpa.free(scales); - const e4m3 = [_]u8{ 0x38, 0x3c, 0x40, 0x44 }; - b.r.bytes(scales); - for (scales) |*x| x.* = e4m3[x.* & 3]; - const words = try gpa.alloc(u32, cuda.nvfp4.padded(n) / 64 * (k / 64) * 512); - defer gpa.free(words); - const tiles = try gpa.alloc(u8, cuda.nvfp4.padded(n) * (k / 16)); - defer gpa.free(tiles); - cuda.nvfp4.packWords(words, codes, n, k); - cuda.nvfp4.packScales(tiles, scales, n, k); - return cuda.nvfp4.weight(try b.put(std.mem.sliceAsBytes(words)), try b.put(tiles), 1.0 / 1024.0, n, k); - } -}; - -/// Random weights in the loader's layout (cuda_weights.load): q, k and g one projection, NVFP4 MLPs. -pub fn build(gpu: check.Gpu, c: Config, seed: u64) !wts.Weights { - var w: wts.Weights = .{ .gpa = gpu.gpa, .config = c }; - errdefer w.deinit(); - var prng = std.Random.DefaultPrng.init(seed); - const b: Build = .{ .w = &w, .d = gpu.d, .r = prng.random() }; - const h = c.hidden; - const q = c.queryWidth(); - const kv = c.kvWidth(); - w.embed = try b.small(c.vocab * h, 0, 0.02); - w.head = try b.dense(c.vocab, h); - w.norm = try b.small(h, 1, 0.1); - w.layers = try gpu.gpa.alloc(wts.Layer, c.layers); - for (w.layers) |*l| l.* = .{ - .qkg = try b.dense(2 * q + kv, h), - .v = try b.dense(kv, h), - .o = try b.dense(h, q), - .gate = try b.fp4(c.intermediate, h), - .up = try b.fp4(c.intermediate, h), - .down = try b.fp4(h, c.intermediate), - .input_norm = try b.small(h, 1, 0.1), - .post_attn = try b.small(h, 1, 0.1), - .pre_ffn = try b.small(h, 1, 0.1), - .post_ffn = try b.small(h, 1, 0.1), - .q_norm = try b.small(128, 1, 0.1), - .k_norm = try b.small(128, 1, 0.1), - .blend = wts.blendOf(bf16(b.r.float(f32) * 2 - 1)), - }; - return w; -} +pub const config = fixture.config; +pub const build = fixture.build; /// A stream: its prompt's length and decode tokens (teacher-forced, so every run feeds the same rows). const Spec = struct { name: []const u8, prompt: usize }; @@ -366,6 +259,192 @@ fn replay(m: *const fwd.Model, r: Replay, toks: []const u32, got: []u8, want: [] return graphVsEager(m, r.what, chains[0..r.chains.len], toks[0..n], got, want); } +/// The tapped layers (columns 0, 1 and 2): sliding, global, sliding. +const tap_layers = [_]u32{ 1, 4, 8 }; + +/// A slot's whole tap ring into `out`. +fn ringOf(m: *const fwd.Model, slot: usize, out: []u8) !void { + try m.download(m.tapRing(slot).?, out[0 .. fwd.tap_rows * m.tapRowBytes()]); +} + +/// Position p's tap column t in a downloaded ring. +fn tapRow(m: *const fwd.Model, ring: []const u8, p: usize, t: usize) []const u8 { + const h2 = m.c.hidden * 2; + return ring[(p % fwd.tap_rows) * m.tapRowBytes() + t * h2 ..][0..h2]; +} + +/// The ring rows that differ between two downloaded rings. +fn ringDiff(m: *const fwd.Model, got: []const u8, want: []const u8) usize { + const row = m.tapRowBytes(); + var n: usize = 0; + for (0..fwd.tap_rows) |r| n += @intFromBool(!std.mem.eql(u8, got[r * row ..][0..row], want[r * row ..][0..row])); + return n; +} + +/// Stream B in a zeroed `slot`: a prompt chunk's last logits, a graph round's and an eager round's (22-token window). +fn plainB(m: *const fwd.Model, x: *const Streams, slot: usize, last: []u8, by_graph: []u8, eager: []u8) !void { + const n = specs[1].prompt; + const t = decodeTokens(1); + try m.reset(slot, m.context); + _ = try prefill(m, slot, x.ids[1][0..n]); + try m.download(m.b.logits, last); + const chain = [_]fwd.Chain{.{ .slot = slot, .p0 = n, .tokens = t }}; + try m.roundAs(&chain, x.ids[1][n..][0..t], .graph); + try roundRows(m, t, by_graph); + try m.roundAs(&chain, x.ids[1][n..][0..t], .exact); + try roundRows(m, t, eager); +} + +/// One-row eager steps of `ids` in `slot` from p0. +fn eagerSteps(m: *const fwd.Model, slot: usize, p0: usize, ids: []const u32) !void { + for (ids, p0..) |id, p| try m.roundAs(&.{.{ .slot = slot, .p0 = p, .tokens = 1 }}, &.{id}, .exact); +} + +/// The drafter's taps (slots zeroed first): tap rows equal the residual after each tapped layer; steps 1 to 5 below. +fn taps(m: *fwd.Model, w: *const wts.Weights, x: *const Streams) !usize { + const a = m.gpa; + const c = m.c; + const v2 = c.vocab * 2; + const h2 = c.hidden * 2; + const t = decodeTokens(1); + var fails: usize = 0; + const bufs = try a.alloc(u8, 2 * (v2 + 2 * t * v2)); + defer a.free(bufs); + const off = .{ bufs[0..v2], bufs[v2..][0 .. t * v2], bufs[v2 + t * v2 ..][0 .. t * v2] }; + const on = .{ bufs[v2 + 2 * t * v2 ..][0..v2], bufs[2 * v2 + 2 * t * v2 ..][0 .. t * v2], bufs[2 * v2 + 3 * t * v2 ..][0 .. t * v2] }; + + // 4 (before): plain logits without taps, the round's graph captured without the tap launches + if (m.tap != null) return error.TapsAlreadySet; + try plainB(m, x, 4, off[0], off[1], off[2]); + + try m.setTaps(&tap_layers); + if (m.captured() != 0) { + std.debug.print("FAIL ripple-forward taps: setTaps left {d} graphs captured\n", .{m.captured()}); + fails += 1; + } + for (0..m.arena.slots) |sl| try m.reset(sl, m.context); + const ring_bytes = fwd.tap_rows * m.tapRowBytes(); + const rings = try a.alloc(u8, 2 * ring_bytes); + defer a.free(rings); + const ring_a = rings[0..ring_bytes]; + const ring_b = rings[ring_bytes..]; + const resid = try a.alloc(u8, fwd.prompt_rows * h2); + defer a.free(resid); + + // 1 and 3: B's prompt (3,066 rows: 2,048, then 1,018 at 2,048 to 3,065, rows 2,048 to 2,063 then 0 to 1,001) + var cut: [tap_layers.len]wts.Weights = undefined; // the model ending at each tapped layer (shared buffers) + for (&cut, tap_layers) |*cw, l| { + cw.* = w.*; + cw.layers = w.layers[0 .. l + 1]; + } + const ids = x.ids[1][0..specs[1].prompt]; + var chunk_bad: usize = 0; + var wrap_bad: usize = 0; + var kept_bad: usize = 0; + var at: usize = 0; + while (at < ids.len) { + const end = @min(ids.len, at + fwd.prompt_rows); + try ringOf(m, 0, ring_a); + try m.prompt(0, at, ids[at..end]); + try ringOf(m, 0, ring_b); + for (0..fwd.tap_rows) |r| { + const named = (r + fwd.tap_rows - at % fwd.tap_rows) % fwd.tap_rows < end - at; + const row = m.tapRowBytes(); + if (!named and !std.mem.eql(u8, ring_a[r * row ..][0..row], ring_b[r * row ..][0..row])) kept_bad += 1; + } + for (&cut, 0..) |*cw, col| { + m.w = cw; + defer m.w = w; + try m.prompt(1 + col, at, ids[at..end]); + try m.download(m.b.resid, resid[0 .. (end - at) * h2]); + for (at..end) |p| if (!std.mem.eql(u8, tapRow(m, ring_b, p, col), resid[(p - at) * h2 ..][0..h2])) { + chunk_bad += 1; + wrap_bad += @intFromBool(p >= fwd.tap_rows); + }; + } + at = end; + } + if (chunk_bad == 0) { + check.pass("ripple-forward taps 1: B's 2 prompt chunks (3,066 rows), layers 1, 4 and 8 == the residual after each layer (eager)", .{}); + } else { + std.debug.print("FAIL ripple-forward taps 1: {d} of {d} tap rows differ from the residual after their layer\n", .{ chunk_bad, ids.len * tap_layers.len }); + fails += 1; + } + var untouched: usize = 0; // slots 4-9: no chunk named them since the reset + for (4..m.arena.slots) |sl| { + try ringOf(m, sl, ring_a); + untouched += @intFromBool(std.mem.indexOfNone(u8, ring_a, &.{0}) != null); + } + if (wrap_bad == 0 and kept_bad == 0 and untouched == 0) { + check.pass("ripple-forward taps 3: positions 2,064 to 3,065 at pos % 2,064; rows 1,002 to 2,047 and other slots' rings untouched", .{}); + } else { + std.debug.print("FAIL ripple-forward taps 3: {d} wrapped rows wrong, {d} unnamed rows changed, {d} other slots' rings written\n", .{ wrap_bad, kept_bad, untouched }); + fails += 1; + } + + // 4 (after): the same logits with taps on, eager and from a graph captured with the tap launches + try plainB(m, x, 4, on[0], on[1], on[2]); + const p_ok = same("taps on: B's prompt", .{}, on[0], off[0]); + const g_ok = sameRows("taps on: graph round", t, v2, on[1], off[1]); + const e_ok = sameRows("taps on: eager round", t, v2, on[2], off[2]); + if (p_ok and g_ok and e_ok) { + check.pass("ripple-forward taps 4: plain logits with taps on == taps off: B's prompt, a {d}-row round eager and from a graph", .{t}); + } else { + std.debug.print("FAIL ripple-forward taps 4: taps change plain logits (same: prompt {d}, graph round {d}, eager round {d})\n", .{ @intFromBool(p_ok), @intFromBool(g_ok), @intFromBool(e_ok) }); + fails += 1; + } + + // 2: two streams, 16 rows each, one across the ring's wrap (2,056 to 2,071), the other at 100 to 115 + var prng = std.Random.DefaultPrng.init(0x7461_7073); + var toks: [3 * 32]u32 = undefined; + for (&toks) |*tk| tk.* = prng.random().uintLessThan(u32, @intCast(c.vocab)); + const lens = [2]usize{ 2056, 100 }; + for ([_]usize{ 5, 7 }) |sl| _ = try prefill(m, sl, x.ids[4][0..lens[0]]); + for ([_]usize{ 6, 8 }) |sl| _ = try prefill(m, sl, x.ids[0][0..lens[1]]); + // the 32-row graph captured first in slots 4 and 9 (positions 0 to 15), then replayed below + try m.reset(4, m.context); + try m.roundAs(&.{ .{ .slot = 4, .p0 = 0, .tokens = 16 }, .{ .slot = 9, .p0 = 0, .tokens = 16 } }, toks[0..32], .graph); + const graphs = m.captured(); + try m.roundAs(&.{ .{ .slot = 7, .p0 = lens[0], .tokens = 16 }, .{ .slot = 8, .p0 = lens[1], .tokens = 16 } }, toks[0..32], .graph); + try eagerSteps(m, 5, lens[0], toks[0..16]); + try eagerSteps(m, 6, lens[1], toks[16..32]); + var round_bad: usize = 0; + for ([_][2]usize{ .{ 7, 5 }, .{ 8, 6 } }) |pair| { + try ringOf(m, pair[0], ring_a); + try ringOf(m, pair[1], ring_b); + round_bad += ringDiff(m, ring_a, ring_b); + } + if (round_bad == 0 and m.captured() == graphs) { + check.pass("ripple-forward taps 2: a 2-stream round of 16 rows a stream from a graph (one across the wrap) == one-row eager steps, whole rings", .{}); + } else { + std.debug.print("FAIL ripple-forward taps 2: {d} ring rows differ; graphs {d} before the replay, {d} after\n", .{ round_bad, graphs, m.captured() }); + fails += 1; + } + + // 5: a verify round at 2,072 and 116 keeps 5 and 11 rows; the next 16-row rounds start at 2,077 and 127 + const p1 = [2]usize{ lens[0] + 16, lens[1] + 16 }; + const kept = [2]usize{ 5, 11 }; + try m.roundAs(&.{ .{ .slot = 7, .p0 = p1[0], .tokens = 16 }, .{ .slot = 8, .p0 = p1[1], .tokens = 16 } }, toks[32..64], .graph); + try m.roundAs(&.{ .{ .slot = 7, .p0 = p1[0] + kept[0], .tokens = 16 }, .{ .slot = 8, .p0 = p1[1] + kept[1], .tokens = 16 } }, toks[64..96], .graph); + try eagerSteps(m, 5, p1[0], toks[32..][0..kept[0]]); + try eagerSteps(m, 5, p1[0] + kept[0], toks[64..80]); + try eagerSteps(m, 6, p1[1], toks[48..][0..kept[1]]); + try eagerSteps(m, 6, p1[1] + kept[1], toks[80..96]); + var keep_bad: usize = 0; + for ([_][2]usize{ .{ 7, 5 }, .{ 8, 6 } }) |pair| { + try ringOf(m, pair[0], ring_a); + try ringOf(m, pair[1], ring_b); + keep_bad += ringDiff(m, ring_a, ring_b); + } + if (keep_bad == 0 and m.captured() == graphs) { + check.pass("ripple-forward taps 5: a verify round keeping 5 and 11 of 16 rows, then the next round at the rejected positions == one-row steps of the kept rows", .{}); + } else { + std.debug.print("FAIL ripple-forward taps 5: {d} ring rows differ; graphs {d}, then {d}\n", .{ keep_bad, graphs, m.captured() }); + fails += 1; + } + return fails; +} + pub fn run(gpu: check.Gpu) !void { const a = gpu.gpa; const c = config(); @@ -485,5 +564,8 @@ pub fn run(gpu: check.Gpu) !void { std.debug.print("FAIL ripple-forward graphs coexist: {d} of {d} replays differ, {d} graphs before and {d} after\n", .{ order, any_order.len, graphs, m.captured() }); fails += 1; } + + // 7. a drafter's taps on the same model (last: setTaps drops the graphs above) + fails += try taps(&m, &w, &x); try check.expect(fails == 0, "ripple-forward: {d} checks differ", .{fails}); } diff --git a/zig/tests/cuda/ripple_mask_tests.zig b/zig/tests/cuda/ripple_mask_tests.zig new file mode 100644 index 00000000000..41ef5601f69 --- /dev/null +++ b/zig/tests/cuda/ripple_mask_tests.zig @@ -0,0 +1,180 @@ +//! Ripple's draws under grammar masks on CUDA (ripple-serve check 7): a masked draw is the plain draw over the cut row. +const std = @import("std"); +const cuda = @import("cuda"); +const lanes = @import("lanes"); +const rc = @import("ricursive_cuda"); +const check = @import("check.zig"); +const serve = @import("ripple_serve_tests.zig"); + +const be = rc.backend; +const Stream = lanes.Stream; +const Window = lanes.backend.Window; +const Verified = lanes.backend.Verified; +const LogRow = lanes.LogprobRow; + +/// A grammar row's kinds: every token allowed, about half of them, five of them, or all but one. +pub const MaskKind = enum { all, half, five, all_but }; + +/// A row of grammar bits over `v` tokens (lanes/grammar.zig: token t at bit t % 32 of word t / 32). +pub fn maskRow(out: []u32, rnd: std.Random, kind: MaskKind, v: usize, not: u32) void { + switch (kind) { + .all => @memset(out, 0xFFFF_FFFF), + .half => for (out) |*w| { + w.* = rnd.int(u32); + }, + .five => { + @memset(out, 0); + for (0..5) |_| { + const t = rnd.uintLessThan(usize, v); + out[t / 32] |= @as(u32, 1) << @intCast(t % 32); + } + }, + .all_but => { + @memset(out, 0xFFFF_FFFF); + out[not / 32] &= ~(@as(u32, 1) << @intCast(not % 32)); + }, + } +} + +/// `src`'s bf16 logits into `dst`, the tokens `mask` disallows at -inf (0xFF80). +fn underMask(dst: []u8, src: []const u8, mask: []const u32) void { + for (0..src.len / 2) |t| { + const allowed = lanes.grammar.allows(mask, t); + dst[2 * t] = if (allowed) src[2 * t] else 0x80; + dst[2 * t + 1] = if (allowed) src[2 * t + 1] else 0xFF; + } +} + +/// The first largest allowed logit's token: the greedy draw under a mask, on the host. +fn firstLargest(row: []const u8, mask: []const u32) u32 { + var best: usize = 0; + var top: f32 = 0; + var found = false; + for (0..row.len / 2) |t| { + if (!lanes.grammar.allows(mask, t)) continue; + const x: f32 = @bitCast((@as(u32, row[2 * t + 1]) << 24) | (@as(u32, row[2 * t]) << 16)); + if (found and !(x > top)) continue; + best = t; + top = x; + found = true; + } + return @intCast(best); +} + +/// Device scratch for check 7: host rows put on the device, and the plain draw's tokens over them. +const Redraw = struct { + rows: cuda.DeviceBuffer, + picks: cuda.DeviceBuffer, + + /// The plain draw (no mask) of stream `s`'s rule over the host rows `bytes`, row 0 at `position0`. + fn draw(d: Redraw, r: serve.Rig, s: *const Stream, bytes: []const u8, position0: u64, out: []u32) !void { + try r.m.s.synchronize(); + try d.rows.upload(0, bytes); + try r.x.drawRows(r.x.lanes.getPtr(s).?, d.rows.ptr, out.len, position0, d.picks.ptr, 0); + try r.m.download(d.picks.ptr, std.mem.sliceAsBytes(out)); + } +}; + +/// Check 7: a stream's first token and a 4-row window under masks == the plain draw over the rows cut to the masks. +pub fn maskedDraws(r: serve.Rig, p: []const u32, plain: *const serve.Trace, sp: ?lanes.Sampling, label: []const u8) !usize { + const v = r.m.c.vocab; + const row_bytes = v * 2; + const nw = be.Ripple.maskWords(v); + const n = p.len; + const win = 4; + const k: u8 = lanes.logprob.max_top; + var prng = std.Random.DefaultPrng.init(0x6d61_736b); + const rnd = prng.random(); + // the model's rows must keep their bits, and the logprob rows must be the unmasked rows' for the token drawn + var redraw: Redraw = .{ .rows = try cuda.DeviceBuffer.alloc(r.x.d, win * row_bytes), .picks = undefined }; + defer redraw.rows.free(); + redraw.picks = try cuda.DeviceBuffer.alloc(r.x.d, win * 4); + defer redraw.picks.free(); + const under = try r.gpa.alloc(u8, win * row_bytes); // the model's rows of the window drawn under masks + defer r.gpa.free(under); + const bare = try r.gpa.alloc(u8, win * row_bytes); // the same window's rows with no mask + defer r.gpa.free(bare); + const cut = try r.gpa.alloc(u8, win * row_bytes); // rows with their disallowed tokens at -inf + defer r.gpa.free(cut); + const masks = try r.gpa.alloc(u32, win * nw); + defer r.gpa.free(masks); + var bad: usize = 0; + var worst: f64 = 0; + + var sm = try Stream.init(r.gpa, .{ .id = "masked", .prompt = p, .max_new = serve.max_new, .sampling = sp, .drafts = false, .logprobs = k }); + defer sm.deinit(r.gpa); + var tm = try serve.Trace.init(r.gpa, v); + defer tm.deinit(r.gpa); + _ = try r.open(&sm); + defer r.b.release(&sm); + + // the first token: every token but the plain draw's allowed, so the draw must change + const m0 = masks[0..nw]; + maskRow(m0, rnd, .all_but, v, plain.tokens[0]); + const t0 = try r.firstUnder(&sm, &tm, m0); + var want1: [1]u32 = undefined; + underMask(cut[0..row_bytes], tm.logits[0], m0); + try redraw.draw(r, &sm, cut[0..row_bytes], n, &want1); + var ok = t0 == want1[0] and t0 != plain.tokens[0] and std.mem.eql(u8, tm.logits[0], plain.logits[0]); + if (sp == null) ok = ok and t0 == firstLargest(tm.logits[0], m0); + ok = serve.rowMatches(serve.Host.init(tm.logits[0]), try r.b.firstRow(&sm), t0, k, false, &worst) and ok; + if (!ok) std.debug.print(" DIFF {s} first token under a mask: drew {d}, the plain draw over the cut row {d}, the plain token {d}\n", .{ label, t0, want1[0], plain.tokens[0] }); + bad += @intFromBool(!ok); + + // the window with no mask, in a second slot: the same pending token and drafts + const drafts = plain.tokens[1..win]; + var pos: [win]u64 = undefined; + for (&pos, 1..) |*q, i| q.* = n + i; + var free_picks: [win]u32 = undefined; + { + var s0 = try Stream.init(r.gpa, .{ .id = "unmasked", .prompt = p, .max_new = serve.max_new, .sampling = sp, .drafts = false }); + defer s0.deinit(r.gpa); + var t0u = try serve.Trace.init(r.gpa, v); + defer t0u.deinit(r.gpa); + _ = try r.open(&s0); + defer r.b.release(&s0); + _ = try r.first(&s0, &t0u); + var dr: [win - 1]u32 = undefined; + const w: Window = .{ .stream = &s0, .pending = t0, .held = 0, .tokens = drafts, .parents = null, .positions = &pos }; + var out = [_]Verified{.{ .sampled = &free_picks, .drafts = &dr }}; + try r.b.verify(&.{w}, &out); + try r.m.download(r.m.b.rows, bare); + } + + // the window under masks: a row of each kind, the last one without the unmasked draw's token + const kinds = [win]MaskKind{ .all, .half, .five, .all_but }; + for (kinds, 0..) |kind, i| maskRow(masks[i * nw ..][0..nw], rnd, kind, v, free_picks[i]); + var picks: [win]u32 = undefined; + var dr: [win - 1]u32 = undefined; + var rows: [win]LogRow = undefined; + const w: Window = .{ .stream = &sm, .pending = t0, .held = 0, .tokens = drafts, .parents = null, .positions = &pos, .masks = masks }; + var out = [_]Verified{.{ .sampled = &picks, .drafts = &dr, .rows = &rows }}; + try r.b.verify(&.{w}, &out); + try r.m.download(r.m.b.rows, under); + for (0..win) |i| underMask(cut[i * row_bytes ..][0..row_bytes], under[i * row_bytes ..][0..row_bytes], masks[i * nw ..][0..nw]); + var want: [win]u32 = undefined; + try redraw.draw(r, &sm, cut, n + 1, &want); + ok = std.mem.eql(u8, under, bare) and std.mem.eql(u32, &picks, &want) and picks[0] == free_picks[0] and picks[win - 1] != free_picks[win - 1]; + worst = 0; + for (rows, picks, 0..) |lr, pick, i| { + const row = under[i * row_bytes ..][0..row_bytes]; + const mask = masks[i * nw ..][0..nw]; + ok = lanes.grammar.allows(mask, pick) and ok; + if (sp == null) ok = ok and pick == firstLargest(row, mask); + ok = serve.rowMatches(serve.Host.init(row), lr, pick, k, false, &worst) and ok; + } + if (!ok) std.debug.print(" DIFF {s} window under masks: drew {any}, the plain draw over the cut rows {any}, with no mask {any}; the model's rows equal: {}\n", .{ label, picks, want, free_picks, std.mem.eql(u8, under, bare) }); + bad += @intFromBool(!ok); + + // a mask of the wrong length is refused by name, before any forward + const short: Window = .{ .stream = &sm, .pending = t0, .held = 0, .tokens = drafts, .parents = null, .positions = &pos, .masks = masks[0 .. masks.len - 1] }; + const refused = if (r.b.verify(&.{short}, &out)) |_| false else |e| e == error.InvalidGrammarMasks; + bad += @intFromBool(!refused); + + if (bad == 0) { + check.pass("ripple-serve {s} draws under grammar masks: stream A's first token and a 4-row window (every token, about half, five tokens, all but the plain one) == the plain draw over the rows with the other tokens at -inf; the model's rows == those with no mask; logprob rows from the unmasked rows ({d} best, worst {e:.2}); a short mask refused", .{ label, k, worst }); + return 0; + } + std.debug.print("FAIL ripple-serve {s} draws under grammar masks: {d} of 3 parts differ\n", .{ label, bad }); + return 1; +} diff --git a/zig/tests/cuda/ripple_serve_tests.zig b/zig/tests/cuda/ripple_serve_tests.zig index 55014f9f94b..8cc074c1fd4 100644 --- a/zig/tests/cuda/ripple_serve_tests.zig +++ b/zig/tests/cuda/ripple_serve_tests.zig @@ -16,6 +16,7 @@ const Verified = lanes.backend.Verified; const LogRow = lanes.LogprobRow; const fixture = @import("ripple_forward_tests.zig"); // the release-width weights on 10 layers +const masks = @import("ripple_mask_tests.zig"); // draws under grammar masks (check 7) const Spec = struct { name: []const u8, prompt: usize }; @@ -34,15 +35,15 @@ const shared = [_]usize{ D, A, E }; /// Draws a stream makes: the first (the prompt's last row), then one a round. const steps = 8; -const max_new = 64; +pub const max_new = 64; const slots = 4; /// Each draw of a stream (the token at prompt length + i) and the bf16 logits it was drawn from. -const Trace = struct { +pub const Trace = struct { tokens: [steps]u32 = undefined, logits: [steps][]u8 = undefined, - fn init(gpa: std.mem.Allocator, vocab: usize) !Trace { + pub fn init(gpa: std.mem.Allocator, vocab: usize) !Trace { var t: Trace = .{}; var made: usize = 0; errdefer for (t.logits[0..made]) |l| gpa.free(l); @@ -53,7 +54,7 @@ const Trace = struct { return t; } - fn deinit(t: *Trace, gpa: std.mem.Allocator) void { + pub fn deinit(t: *Trace, gpa: std.mem.Allocator) void { for (t.logits) |l| gpa.free(l); } }; @@ -74,7 +75,7 @@ fn sameTrace(comptime what: []const u8, args: anytype, got: *const Trace, want: return true; } -const Rig = struct { +pub const Rig = struct { gpa: std.mem.Allocator, m: *fwd.Model, x: *be.Ripple, @@ -85,19 +86,27 @@ const Rig = struct { } /// The prompt pass; the slot the stream took. - fn open(r: Rig, s: *Stream) !usize { + pub fn open(r: Rig, s: *Stream) !usize { try r.b.prefill(s); return r.x.lanes.getPtr(s).?.slot; } /// The first draw and its logits (the prompt's last row, kept in the stream's slot). - fn first(r: Rig, s: *Stream, t: *Trace) !u32 { + pub fn first(r: Rig, s: *Stream, t: *Trace) !u32 { const tok = try r.b.read(try r.b.first(s, s.prompt().len)); t.tokens[0] = tok; try r.m.download(r.x.lanes.getPtr(s).?.last, t.logits[0]); return tok; } + /// The first draw under a grammar row's bits (first_masked), and the row's logits as the model gave them. + pub fn firstUnder(r: Rig, s: *Stream, t: *Trace, mask: []const u32) !u32 { + const tok = try r.b.read(try r.b.vtable.first_masked.?(r.b.ptr, s, s.prompt().len, mask)); + t.tokens[0] = tok; + try r.m.download(r.x.lanes.getPtr(s).?.last, t.logits[0]); + return tok; + } + /// One-row rounds by queue from step `from` (fed `tok`, the draw before it), each draw and its logits into `t`. fn decode(r: Rig, s: *Stream, t: *Trace, from: usize, tok0: u32) !void { var tok = tok0; @@ -116,8 +125,8 @@ const Rig = struct { return slot; } - /// Streams `ss` together: their prompt passes, first draws, then one-row windows by verify and keep (no drafts). - fn together(r: Rig, ss: []const *Stream, ts: []Trace) !void { + /// Streams `ss` together: prompt passes, first draws, one-row verify windows; `under[j]`: stream j's grammar bits. + fn together(r: Rig, ss: []const *Stream, ts: []Trace, under: []const []const u32) !void { const v2 = r.m.c.vocab * 2; var opened: usize = 0; defer for (ss[0..opened]) |s| r.b.release(s); @@ -126,7 +135,7 @@ const Rig = struct { opened += 1; } var pending: [shared.len]u32 = undefined; - for (ss, ts, 0..) |s, *t, j| pending[j] = try r.first(s, t); + for (ss, ts, under, 0..) |s, *t, mk, j| pending[j] = if (mk.len == 0) try r.first(s, t) else try r.firstUnder(s, t, mk); var windows: [shared.len]Window = undefined; var out: [shared.len]Verified = undefined; var pos: [shared.len][1]u64 = undefined; @@ -138,7 +147,7 @@ const Rig = struct { for (1..steps) |i| { for (ss, 0..) |s, j| { pos[j] = .{s.prompt().len + i}; - windows[j] = .{ .stream = s, .pending = pending[j], .held = 0, .tokens = &.{}, .parents = null, .positions = &pos[j] }; + windows[j] = .{ .stream = s, .pending = pending[j], .held = 0, .tokens = &.{}, .parents = null, .positions = &pos[j], .masks = under[j] }; out[j] = .{ .sampled = &sampled[j], .drafts = drafts[j][0..0] }; } try r.b.verify(windows[0..n], out[0..n]); @@ -152,8 +161,8 @@ const Rig = struct { } }; -/// Check 1 and 2: three streams together == each alone (`sp` null: greedy), their slots 0 to 2 against slot 0 alone. -fn sharedRounds(r: Rig, prompts: []const []u32, alone: []const Trace, sp: ?lanes.Sampling, label: []const u8) !usize { +/// Checks 1 and 2: three streams together == each alone (`sp` null: greedy); with `mask`, stream A draws under it. +fn sharedRounds(r: Rig, prompts: []const []u32, alone: []const Trace, sp: ?lanes.Sampling, label: []const u8, mask: []const u32) !usize { var ss: [shared.len]Stream = undefined; var made: usize = 0; defer for (ss[0..made]) |*s| s.deinit(r.gpa); @@ -172,11 +181,21 @@ fn sharedRounds(r: Rig, prompts: []const []u32, alone: []const Trace, sp: ?lanes t.* = try Trace.init(r.gpa, r.m.c.vocab); traced += 1; } - try r.together(&ptrs, &ts); + var under: [shared.len][]const u32 = @splat(&.{}); + if (mask.len != 0) under[std.mem.indexOfScalar(usize, &shared, A).?] = mask; + try r.together(&ptrs, &ts, &under); var bad: usize = 0; for (shared, &ts) |j, *t| { + if (mask.len != 0 and j == A) { + for (t.tokens) |tok| bad += @intFromBool(!lanes.grammar.allows(mask, tok)); + continue; + } if (!sameTrace("{s} stream {s} together vs alone", .{ label, specs[j].name }, t, &alone[j], 0)) bad += 1; } + if (bad == 0 and mask.len != 0) { + check.pass("ripple-serve {s} rounds beside a grammar: streams D and E == each alone, {d} draws and their logits each, with stream A's {d} draws under a mask (each an allowed token)", .{ label, steps, steps }); + return 0; + } if (bad == 0) { check.pass("ripple-serve {s} shared rounds: streams D, A, E ({d}, {d}, {d} prompt tokens) together == each alone, {d} draws and their logits each", .{ label, specs[D].prompt, specs[A].prompt, specs[E].prompt, steps }); return 0; @@ -276,11 +295,11 @@ fn keptStates(r: Rig, name: []const u8, p: []const u32, ats: []const u32, notes: const tol: f64 = 2e-6; /// A float64 log-softmax of one bf16 logits row. -const Host = struct { +pub const Host = struct { vals: []align(1) const u16, lse: f64, - fn init(row: []const u8) Host { + pub fn init(row: []const u8) Host { var h: Host = .{ .vals = std.mem.bytesAsSlice(u16, row), .lse = 0 }; var most = -std.math.inf(f64); for (0..h.vals.len) |i| most = @max(most, h.at(i)); @@ -323,7 +342,7 @@ const Host = struct { }; /// A backend row against the host's: the pick, its best ids exactly, their log probabilities within `tol`. -fn rowMatches(h: Host, row: LogRow, pick: u32, k: u8, ranked: bool, worst: *f64) bool { +pub fn rowMatches(h: Host, row: LogRow, pick: u32, k: u8, ranked: bool, worst: *f64) bool { var ok = row.token == pick and row.count == k; const e0 = @abs(@as(f64, row.logprob) - h.lp(pick)); worst.* = @max(worst.*, e0); @@ -474,11 +493,21 @@ pub fn run(gpu: check.Gpu) !void { } var fails: usize = 0; - fails += try sharedRounds(r, &prompts, &greedy, null, "greedy"); - fails += try sharedRounds(r, &prompts, &sampled, sampling, "sampled (temperature 1, top-p 0.95, top-k 20)"); + fails += try sharedRounds(r, &prompts, &greedy, null, "greedy", &.{}); + fails += try sharedRounds(r, &prompts, &sampled, sampling, "sampled (temperature 1, top-p 0.95, top-k 20)", &.{}); fails += try copiedDrafts(r, prompts[A], &greedy[A]); fails += try keptStates(r, "E", prompts[E], &.{3500}, &.{"past the 3,072-row ring's wrap"}, &greedy[E]); fails += try keptStates(r, "C", prompts[C], &.{ 510, 514 }, &.{ "two rows before a 512-row page edge", "two rows across a 512-row page edge" }, &greedy[C]); fails += try logprobRows(r, prompts[A], &greedy[A], prompts[E][0..300]); + // grammar masks: stream A's draws under them, then D and E in rounds beside a masked A + var of_a = sampling; + of_a.seed +%= A; + fails += try masks.maskedDraws(r, prompts[A], &greedy[A], null, "greedy"); + fails += try masks.maskedDraws(r, prompts[A], &sampled[A], of_a, "sampled"); + const half = try a.alloc(u32, be.Ripple.maskWords(c.vocab)); + defer a.free(half); + masks.maskRow(half, prng.random(), .half, c.vocab, 0); + fails += try sharedRounds(r, &prompts, &greedy, null, "greedy", half); + fails += try sharedRounds(r, &prompts, &sampled, sampling, "sampled", half); try check.expect(fails == 0, "ripple-serve: {d} checks differ", .{fails}); } diff --git a/zig/tests/fixtures/gradient-serving.tsv b/zig/tests/fixtures/gradient-serving.tsv index d20e936de59..e994717a0e1 100644 --- a/zig/tests/fixtures/gradient-serving.tsv +++ b/zig/tests/fixtures/gradient-serving.tsv @@ -95,7 +95,7 @@ zig/src/cuda/experts.zig 5d2cd5aa511b267f7a0800e0c3fd0bb7492ca0e50ed8558c0ee342f 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 50175d41e054e72ecd138d8b7ffdf9e20d0abd79c6e5524e6f9eba649ceeffe0 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), (Hy4-flash images registered); #1295: the six Muse Spark images registered; #3413 (the flashnext_hcn image registered); #4125: the inkling2_attn and inkling2_pattn images registered; the hy4_engram image registered (#4004); #4126: the inkling2_ops and inkling2_rows images registered; #4127: the inkling2_experts and inkling2_vision images registered; Mini ModelOpt and loop-math images registered; #1858: the idol_decoder image registered; #2302: the ricursive and ricursive_prep images registered; #3615: the four zonos3 images registered; #1508: the lfm3 image registered; #5100: the hy4_hc and hy4_ihc_fused images registered; #5042: the experts_mxfp4 image registered; #5202: the ernie5_5_head image registered; #4128: the inkling2_dspark image registered; #5087: the hy4_engram_fp8 image registered; #5442: the tfq4 image registered; #5301: the ernie5_5_mhc image registered; #5109: paged Hy4-flash MLA images registered; #5095: the hy4_index_paged image registered; TFQ5: tfq5 image registered; Engine branch: engine-wave-inkling-cuda-dflash2 +zig/src/cuda/kernels.zig d059c3d0e28b1096d5ffa5a9ddd7e69b3629fad11c58b1621b44e642597ce81f 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), (Hy4-flash images registered); #1295: the six Muse Spark images registered; #3413 (the flashnext_hcn image registered); #4125: the inkling2_attn and inkling2_pattn images registered; the hy4_engram image registered (#4004); #4126: the inkling2_ops and inkling2_rows images registered; #4127: the inkling2_experts and inkling2_vision images registered; Mini ModelOpt and loop-math images registered; #1858: the idol_decoder image registered; #2302: the ricursive and ricursive_prep images registered; #3615: the four zonos3 images registered; #1508: the lfm3 image registered; #5100: the hy4_hc and hy4_ihc_fused images registered; #5042: the experts_mxfp4 image registered; #5202: the ernie5_5_head image registered; #4128: the inkling2_dspark image registered; #5087: the hy4_engram_fp8 image registered; #5442: the tfq4 image registered; #5301: the ernie5_5_mhc image registered; #5109: paged Hy4-flash MLA images registered; #5095: the hy4_index_paged image registered; TFQ5: tfq5 image registered; Engine branch: engine-wave-inkling-cuda-dflash2 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