diff --git a/CHANGELOG.md b/CHANGELOG.md index eb8a59824f8..b6e1ae2c608 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,8 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel ## Unreleased +- Ripple-65B-Preview on Metal: `--drafter` takes the publisher's DFlash2 drafter (`ricursiveAI/Ripple-65B-Preview-DFlash2`) beside either release, with drafted replies equal to plain ones; with the drafter the server opens two streams unless `--parallel` is named, and refuses a named `--parallel` above 2 (#2260, fixes #2259). Thanks to @BobClawblaw. + - MiniMax-M3 on CUDA: `TF_MINIMAX_GRAPHS=1` (opt-in) runs the decode verify window from one CUDA graph, re-recorded with each round's arguments and updated in place, so every kernel sees the same arguments as the eager path and tokens are unchanged (#4610). - Server: `POST /v1/prompt_cache/flush` takes an optional `retain` count that keeps the most recently used prompt states in RAM and on disk; without it the flush is unchanged (#4856). diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index f1d1cade953..bb3efe49a8f 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -333,6 +333,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/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-metal.md b/docs/recipes/ripple-65b-metal.md index 038d7d0f8a8..559694a0b54 100644 --- a/docs/recipes/ripple-65b-metal.md +++ b/docs/recipes/ripple-65b-metal.md @@ -11,6 +11,11 @@ converted: - [`ricursiveAI/Ripple-65B-Preview`](https://huggingface.co/ricursiveAI/Ripple-65B-Preview) (revision `240d5966cbe00f0627c699e59ef58560b60303cf`, 121 GiB): the bf16 release, the exact model. +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 for either release with `--drafter`; a drafted +reply equals the plain one bit for bit. + It was brought up on an M5 Ultra (256 GB); other Macs are untested. Prompts run on Metal 4 tensor units, so it needs an M5 or later: M1 to M4 Macs are refused by name at load. Other `ricursive` checkpoints, and either release quantized any other way, are refused by name. @@ -26,6 +31,13 @@ zig-out/native/bin/tensorfold-native serve models/ripple-65b-nvfp4 --name ripple --context 262144 --parallel 2 ``` +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 takes 7.7 GiB (its weights and its rings). With the drafter the server opens two +streams when `--parallel` is not named and refuses a named `--parallel` above 2 by name: each stream's block is its +own pass through the drafter, so at four streams drafted ties plain except on lists, and at seven it is slower on +every kind (the table under the drafter's speed below). + The bf16 release serves the same way from its own directory. A stream's caches take 16.75 GiB at 262,144 tokens: 64 of the 80 layers slide over 1,024 keys and keep a 3,072-slot ring each (the window and a 2,048-row prompt chunk); every fifth layer is global and keeps every key, in bf16. Under the default load limit (75% of RAM) a 256 GB @@ -55,6 +67,16 @@ model computes the same layers): - **Attention.** Prompt chunks on the tensor units over the sliding ring or every key (`attention_nax.metal`); decode rows over key blocks at absolute positions, so a row's bits never depend on the rows beside it. - **Serving.** The lane host's shared rounds, greedy or `tf_sample_full` draws, copy drafts, the prompt cache. +- **DFlash2 drafter** (`dflash2.zig`, `kernels/metal/ricursive/dflash2.metal`), as z-lab's `DFlash2DraftModel` + (`dflash/model.py`) defines it, with the release's own RMSNorm, rotary and SiLU MLP (`modeling_ricursive.py`), the + NoPE layer of the drafter's `config.json` (`no_rope_layers: [4]`) and the draft window of ricursiveAI's + `inference/server/README.md`. The target writes the residual after layers 1, 20, 39, 58 and 77; the drafter folds + the five into one row (`fc`, then a norm) and keeps its five layers' keys and values from it, in bf16 rings: four + layers slide over 4,096 keys, the fifth (NoPE) over the release's 16,384-key draft window. A round runs a 16-row block + (the pending token and 15 masks) through its layers, each with its causal convolutions (4 taps, per-row kernels) + around attention and the MLP, reads the target's head on the 15 mask rows, keeps each row's 32 best tokens, and walks + them with the selector's codebooks (rank 256) to the draft. The lane core verifies each draft in one target window, so + a reply equals the plain one; the drafter only changes how many tokens a round keeps. **Activations stay bf16.** The publisher serves the NVFP4 release with SGLang's `flashinfer_cutlass`, which also quantizes activations to fp4 (W4A4). TensorFold does not run reduced-precision activations, so the engine serves the @@ -64,11 +86,14 @@ publisher's W4A4 kernels. Every kernel is registered with the kernel contract (`zig/tests/contract/metal_ricursive*.zig`, the roll call in `contracts.zig`): the glue, decode and prompt attention for both layer kinds, the NVFP4 row kernels, dequantization and GEMM, and llama's row projections, merge, argmax and GEMM again at Ripple's shapes (every reduction it runs: k 5,120, -10,240 for the attention output and 40,960). Fifteen planted controls each edit one kernel's source, and each must turn -its gate red. `tf-kernel-contract --only ricursive` on the M5 Ultra: +10,240 for the attention output and 40,960). The DFlash2 drafter adds its own kernels (the target's tap, the +drafter's embedding, norms, conv, rotation, attention, SiLU, top-k and walk), llama's row projections and GEMM at the +drafter's shapes, and the full-vocabulary sampler. Twenty-five planted controls (ten of them in the drafter's kernels) +each edit one kernel's source, and each must turn its gate red. `tf-kernel-contract --only ricursive` on the M5 Ultra +(23 Nov 2026): ``` -SUMMARY 46 kernels: 46 pass gates 1-4, 0 fail, 0 known findings; 15 controls: 15 red as planted, 0 missed; 0 limit problems; gates 645430 ms, limits 140 ms +SUMMARY 75 kernels: 75 pass gates 1-4, 0 fail, 0 known findings; 25 controls: 25 red as planted, 0 missed; 0 limit problems; gates 874094 ms, limits 505 ms ``` ## Correctness (M5 Ultra, 4 Nov 2026) @@ -156,14 +181,62 @@ against 7.5 s cold, with the same reply as on a restarted server. back exactly; the cold prompts take 273 s and 790 s to the first token. The bf16 release found it too, at 120k and 258k tokens. +With the DFlash2 drafter (5 Nov 2026, the NVFP4 release, the same settings plus `--drafter`; speed run with no other +model busy; a local build of `a869c4f32`): + +| streams | prose | code | structured | list | first token | a round | +|---:|---:|---:|---:|---:|---:|---:| +| 1 | 15.5 | 27.5 | 17.8 | 19.8 | 0.53-0.65 s | 131.2 ms | +| 2 | 22.5 | 37.7 | 26.6 | 40.6 | 0.82-0.98 s | 166.2 ms | + +1.5 to 2.7 times one plain stream, 1.2 to 2.16 times two. A round keeps 2.65 tokens on average with one stream (48% of +its drafted tokens accepted) and 2.65 with two (56%). The drafted serving checks equal the plain ones: drafted == plain +12/12 in the drafts suite and 12/12 under structured output, seeded sampling 9/9, the soak 60/60, concurrent 12/12, +structured 18/18, tools 5/5, and a resumed turn equal to the cold one (0.59 s against 7.8 s). + +Past two streams the drafter gains little (6 Nov 2026, the NVFP4 release, `--context 262144 --parallel 7`, one local +build of `e1d719275` with and without `--drafter`, no other model busy; tokens a second, all streams together): + +| streams | prose | code | structured | list | a round | +|---:|---:|---:|---:|---:|---:| +| 4, plain | 32.6 | 31.8 | 31.1 | 32.5 | 126.2 ms | +| 4, drafted | 30.3 | 32.0 | 31.3 | 43.1 | 277.6 ms | +| 7, plain | 43.2 | 42.9 | 41.6 | 43.4 | 165.5 ms | +| 7, drafted | 40.2 | 34.7 | 22.9 | 34.1 | 406.4 ms | + +Each stream's block is its own pass through the drafter, so a round grows with the streams while the tokens it keeps +fall (2.35 tokens a round at four, 1.89 at seven). At four it ties plain except on lists; at seven it is slower on +every kind. With `--drafter`, the server opens two streams unless `--parallel` is named, and refuses a named +`--parallel` above 2 by name. + +With the bf16 release (6 Nov 2026, `--context 262144 --parallel 2`, greedy 256-token replies, no other model busy; one +local build of `b7ff7854f` with and without `--drafter`): + +| streams | prose | code | structured | list | first token | a round | +|---:|---:|---:|---:|---:|---:|---:| +| 1, plain | 6.4 | 6.4 | 6.4 | 6.4 | 0.52-1.20 s | 157.2 ms | +| 1, drafted | 13.4 | 30.7 | 13.3 | 18.7 | 0.39-1.06 s | 154.0 ms | + +2.1 to 4.8 times plain with one stream; a round keeps 2.93 tokens. Drafted == plain 12/12 beside the bf16 release. + +Two drafted streams beside the bf16 release do not decode together on a 256 GB M5 Ultra. With the drafter the server +keeps 129.5 GiB wired beside 60.5 GiB of caches, and macOS reports memory pressure as soon as it has loaded (22% free, +against 27% for the plain server); the engine then admits a stream only when none runs. A second request waits for the +first reply (queued 5.4 to 14.0 s in the server's log), so the two-stream ruler cells measured one stream at a time, +with first tokens of 3.24 to 7.98 s; they are left out of the table. Plain, two bf16 streams decode together (13.4 to +13.7 tokens a second in all, 0.79 to 1.78 s to the first token). + ## Not done No quality suite was run. Contexts past 258,039 tokens were not run, so `--context` stops at 262,144 and refuses the card's 1M by name. Ripple's think markers are spelled from several tokens, not one each, so a thinking budget -(which forces a close) and logprobs (which cut the reply at its close token) are refused by name, and a reply's -`reasoning_tokens` reads 0. The family has no draft head: drafts come only from the lane core's copies. No images: +(which forces a close) is refused by name, and a reply's `reasoning_tokens` reads 0. Logprobs are served, with +`--drafter` too: on the NVFP4 release with the drafter (23 Nov 2026), a greedy and a seeded sampled request with +`top_logprobs: 3` gave the same tokens and rows with drafting on (3.58 and 3.56 tokens a round) and off. No images: Ripple has no vision tower. Only the M5's tensor units were checked; M1 to M4 Macs are refused at load, and smaller -RAM is untested. The publisher's DFlash2 drafter (`ricursiveAI/Ripple-65B-Preview-DFlash2`) is not served yet. +RAM is untested. Beside the bf16 release the drafter was checked for drafted == plain and one stream's speed only (two +drafted streams run one at a time there, see above); its structured output, seeded sampling, soak and resumed turns were +run beside the NVFP4 release. ## Licence diff --git a/zig/kernels/metal/ricursive/dflash2.metal b/zig/kernels/metal/ricursive/dflash2.metal new file mode 100644 index 00000000000..2229ae299f6 --- /dev/null +++ b/zig/kernels/metal/ricursive/dflash2.metal @@ -0,0 +1,273 @@ +// Ripple's DFlash2 drafter (z-lab's DFlash2DraftModel) and the target's taps: 16-row blocks over 5 tapped layers. +#include +using namespace metal; + +#define TF_UNROLL_4 _Pragma("clang loop unroll(full)") + +// The target's residual after a tapped layer, every row, into the features: row r's tap `at` of `taps`. +struct rc_tap_args { uint rows, width, taps, at; }; + +[[kernel]] void rc_tap(const device bfloat* R [[buffer(0)]], constant rc_tap_args& a [[buffer(1)]], + device bfloat* F [[buffer(2)]], uint2 p [[thread_position_in_grid]]) { + if (p.x >= a.width || p.y >= a.rows) return; + F[((size_t)p.y * a.taps + a.at) * a.width + p.x] = R[(size_t)p.y * a.width + p.x]; +} + +struct rc_df_norm_args { uint rows, width; float eps; uint add; }; + +// RicursiveRMSNorm at rms_norm_eps, bf16(w * bf16(x * rsqrt(mean(x^2) + eps))); a.add first takes bf16(R + X). +inline void rc_df_norm_row(device float* x, const device bfloat* w, uint width, float eps, device bfloat* out, + uint t, uint n, threadgroup float* part) { + float sum = 0.0f; + for (uint i = t; i < width; i += n) sum = fma(x[i], x[i], sum); + sum = simd_sum(sum); + if (t % 32 == 0) part[t / 32] = sum; + threadgroup_barrier(mem_flags::mem_threadgroup); + float total = 0.0f; + for (uint s = 0; s < n / 32; ++s) total += part[s]; + const float inv = precise::rsqrt(total / float(width) + eps); + for (uint i = t; i < width; i += n) out[i] = bfloat(float(w[i]) * float(bfloat(x[i] * inv))); +} + +[[kernel]] void rc_df_norm(device float* R [[buffer(0)]], const device bfloat* X [[buffer(1)]], + const device bfloat* w [[buffer(2)]], constant rc_df_norm_args& a [[buffer(3)]], device bfloat* out [[buffer(4)]], + uint row [[threadgroup_position_in_grid]], uint t [[thread_position_in_threadgroup]], + uint n [[threads_per_threadgroup]]) { + threadgroup float part[32]; + device float* x = R + (size_t)row * a.width; + if (a.add) + for (uint i = t; i < a.width; i += n) x[i] = float(bfloat(x[i] + float(X[(size_t)row * a.width + i]))); + threadgroup_barrier(mem_flags::mem_device); + rc_df_norm_row(x, w, a.width, a.eps, out + (size_t)row * a.width, t, n, part); +} + +// The embedded block into the fp32 residual: R row r = E[ids[r]] (the target's table, unscaled, as z-lab embeds). +[[kernel]] void rc_df_embed(const device uint* ids [[buffer(0)]], const device bfloat* E [[buffer(1)]], + constant rc_df_norm_args& a [[buffer(2)]], device float* R [[buffer(3)]], uint2 p [[thread_position_in_grid]]) { + if (p.x >= a.width || p.y >= a.rows) return; + R[(size_t)p.y * a.width + p.x] = float(E[(size_t)ids[p.y] * a.width + p.x]); +} + +// The same norm of bf16 rows (fc's output into the context's hidden_norm). +[[kernel]] void rc_df_norm16(const device bfloat* X [[buffer(0)]], const device bfloat* w [[buffer(1)]], + constant rc_df_norm_args& a [[buffer(2)]], device bfloat* out [[buffer(3)]], uint row [[threadgroup_position_in_grid]], + uint t [[thread_position_in_threadgroup]], uint n [[threads_per_threadgroup]]) { + threadgroup float part[32]; + const device bfloat* x = X + (size_t)row * a.width; + float sum = 0.0f; + for (uint i = t; i < a.width; i += n) sum = fma(float(x[i]), float(x[i]), sum); + sum = simd_sum(sum); + if (t % 32 == 0) part[t / 32] = sum; + threadgroup_barrier(mem_flags::mem_threadgroup); + float total = 0.0f; + for (uint s = 0; s < n / 32; ++s) total += part[s]; + const float inv = precise::rsqrt(total / float(a.width) + a.eps); + for (uint i = t; i < a.width; i += n) out[(size_t)row * a.width + i] = bfloat(float(w[i]) * float(bfloat(float(x[i]) * inv))); +} + +struct rc_df_prep_args { uint rows, heads, kv_heads, pos0, stride, q_off, k_off, v_off, ring, rope; float eps, theta; }; + +// Per-head RicursiveRMSNorm, RicursiveRotaryEmbedding's bf16 tables unless a.rope is 0, z-lab's rotation points. +[[kernel]] void rc_df_prep(const device bfloat* X [[buffer(0)]], const device bfloat* qw [[buffer(1)]], + const device bfloat* kw [[buffer(2)]], constant rc_df_prep_args& a [[buffer(3)]], device bfloat* Q [[buffer(4)]], + device bfloat* K [[buffer(5)]], device bfloat* V [[buffer(6)]], uint2 tg [[threadgroup_position_in_grid]], + uint lane [[thread_index_in_simdgroup]]) { + const uint unit = tg.x, row = tg.y; + if (unit >= a.heads + a.kv_heads || row >= a.rows) return; + const bool is_q = unit < a.heads; + const uint head = is_q ? unit : unit - a.heads; + const device bfloat* src = X + (size_t)row * a.stride + (is_q ? a.q_off : a.k_off) + (size_t)head * 128; + const device bfloat* w = is_q ? qw : kw; + const uint p = a.pos0 + row; + const size_t slot = p % a.ring; + device bfloat* y = is_q ? Q + ((size_t)row * a.heads + head) * 128 : K + (slot * a.kv_heads + head) * 128; + float v[4]; + float sum = 0.0f; + for (uint j = 0; j < 4; ++j) { + v[j] = float(src[lane + 32 * j]); + sum = fma(v[j], v[j], sum); + } + const float inv = precise::rsqrt(simd_sum(sum) / 128.0f + a.eps); + threadgroup float nrm[128]; + for (uint j = 0; j < 4; ++j) nrm[lane + 32 * j] = float(bfloat(float(w[lane + 32 * j]) * float(bfloat(v[j] * inv)))); + simdgroup_barrier(mem_flags::mem_threadgroup); + for (uint j = 0; j < 4; ++j) { + const uint d = lane + 32 * j; + if (a.rope == 0) { + y[d] = bfloat(nrm[d]); + continue; + } + const uint i = d % 64; + const float angle = float(p) * (1.0f / precise::pow(a.theta, float(2 * i) / 128.0f)); + const float c = float(bfloat(precise::cos(angle))), s = float(bfloat(precise::sin(angle))); + const float rot = d < 64 ? -nrm[d + 64] : nrm[d - 64]; + y[d] = bfloat(float(bfloat(nrm[d] * c)) + float(bfloat(rot * s))); + } + if (is_q) return; + const device bfloat* vs = X + (size_t)row * a.stride + a.v_off + (size_t)head * 128; + device bfloat* vd = V + (slot * a.kv_heads + head) * 128; + for (uint j = 0; j < 4; ++j) vd[lane + 32 * j] = vs[lane + 32 * j]; +} + +struct rc_df_conv_args { uint rows, width, block, groups, side, taps; }; + +// z-lab's dynamic causal conv, per tap t in the block: y = bf16(y + bf16(base_t x[r-t])), y = bf16(y + dyn_t x[r-t]). +[[kernel]] void rc_df_conv(const device bfloat* X [[buffer(0)]], const device bfloat* D [[buffer(1)]], + const device bfloat* base [[buffer(2)]], constant rc_df_conv_args& a [[buffer(3)]], device bfloat* Y [[buffer(4)]], + uint2 p [[thread_position_in_grid]]) { + if (p.x >= a.width || p.y >= a.rows) return; + const uint ch = p.x, r = p.y, g = ch / (a.width / a.groups); + // a row's dynamic kernel: [side][tap][group] + const device bfloat* d = D + (size_t)r * 2 * a.taps * a.groups + a.side * a.taps * a.groups; + const device bfloat* bs = base + (size_t)a.side * a.taps * a.width; + float y = 0.0f; + for (uint t = 0; t < a.taps; ++t) { + if (r % a.block < t) break; + const float x = float(X[(size_t)(r - t) * a.width + ch]); + y = float(bfloat(y + float(bfloat(float(bs[(size_t)t * a.width + ch]) * x)))); + y = float(bfloat(fma(float(d[t * a.groups + g]), x, y))); + } + Y[(size_t)r * a.width + ch] = bfloat(y); +} + +struct rc_df_act_args { uint rows, width; }; + +// RicursiveMLP's activation (silu, no clamp) on a stacked gate|up row: bf16(bf16(silu(g)) * u). +[[kernel]] void rc_df_silu(const device bfloat* GU [[buffer(0)]], constant rc_df_act_args& a [[buffer(1)]], + device bfloat* A [[buffer(2)]], uint2 p [[thread_position_in_grid]]) { + if (p.x >= a.width || p.y >= a.rows) return; + const size_t at = (size_t)p.y * 2 * a.width + p.x; + const float g = float(GU[at]); + const float e = precise::exp(-fabs(g)), y = 1.0f / (1.0f + e); + const float s = g < 0.0f ? e * y : y; // e / (1 + e) below 0, which 1 - y would cancel + A[(size_t)p.y * a.width + p.x] = bfloat(float(bfloat(g * s)) * float(GU[at + a.width])); +} + +// The first eight are llama's ll_vec_args, which ll_merge_vec reads; then the block's end, window, ring and floor. +struct rc_df_vec_args { uint rows, pos0, heads, groups, blocks, chunk, first; float scale; uint hi, window, ring, floor; }; + +// A block's attention, a (key head, row, 128-key block) a threadgroup: keys max(p + 1 - window, floor) to hi. +[[kernel]] void rc_df_vec(const device bfloat* Q [[buffer(0)]], const device bfloat* K [[buffer(1)]], + const device bfloat* V [[buffer(2)]], constant rc_df_vec_args& a [[buffer(3)]], device float* PM [[buffer(4)]], + device float* PL [[buffer(5)]], device float* PO [[buffer(6)]], uint3 tg [[threadgroup_position_in_grid]], + uint g [[simdgroup_index_in_threadgroup]], uint lane [[thread_index_in_simdgroup]]) { + const uint kv = tg.x, row = tg.y, z = tg.z; + const uint G = a.heads / a.groups, head = kv * G + g; + const size_t slot = ((size_t)head * a.rows + row) * a.blocks + z; + const uint p = a.pos0 + row; + const uint lo = max(p + 1 > a.window ? p + 1 - a.window : 0, a.floor); + const uint block = a.first + z; + const uint from = max(lo, block * 128), to = min(a.hi, block * 128 + 128); + if (from >= to) { + if (lane == 0) { PM[slot] = -INFINITY; PL[slot] = 0.0f; } + return; + } + const size_t ld = (size_t)a.groups * 128; + const float4 qv = a.scale * float4(*(const device bfloat4*)(Q + ((size_t)row * a.heads + head) * 128 + 4 * lane)); + float4 acc = 0.0f; + float top = -INFINITY, mass = 0.0f; + for (uint i0 = from; i0 < to; i0 += 4) { + float score[4]; + float4 vr[4]; + TF_UNROLL_4 + for (uint u = 0; u < 4; ++u) { + const bool live = i0 + u < to; + const size_t at = (size_t)((live ? i0 + u : from) % a.ring) * ld + kv * 128 + 4 * lane; + vr[u] = float4(*(const device bfloat4*)(V + at)); + const float sc = simd_sum(dot(qv, float4(*(const device bfloat4*)(K + at)))); + score[u] = live ? sc : -INFINITY; + } + const float peak = max(max(top, max(score[0], score[1])), max(score[2], score[3])); + const float rescale = fast::exp(top - peak); + mass *= rescale; + acc *= rescale; + TF_UNROLL_4 + for (uint u = 0; u < 4; ++u) { + const float w = fast::exp(score[u] - peak); + mass += w; + acc += w * vr[u]; + } + top = peak; + } + if (lane == 0) { PM[slot] = top; PL[slot] = mass; } + *(device float4*)(PO + slot * 128 + 4 * lane) = acc; +} + +struct rc_df_topk_args { uint n, stride, chunks, from_ids; }; + +inline bool rc_df_before(float a, uint ia, float b, uint ib) { return a > b || (a == b && ia < ib); } + +// The best 32 of a row's 2048-value chunk (value desc, id asc) by a bitonic sort, out at (r * chunks + c) * 32. +[[kernel]] void rc_df_topk(const device bfloat* L [[buffer(0)]], const device float* VIN [[buffer(1)]], + const device uint* IIN [[buffer(2)]], constant rc_df_topk_args& a [[buffer(3)]], device float* VOUT [[buffer(4)]], + device uint* IOUT [[buffer(5)]], uint2 tg [[threadgroup_position_in_grid]], uint t [[thread_index_in_threadgroup]]) { + threadgroup float v[2048]; + threadgroup uint id[2048]; + const uint row = tg.y, chunk = tg.x; + for (uint i = t; i < 2048; i += 1024) { + const uint at = chunk * 2048 + i; + if (at < a.n) { + const size_t src = (size_t)row * a.stride + at; + v[i] = a.from_ids ? VIN[src] : float(L[src]); + id[i] = a.from_ids ? IIN[src] : at; + } else { + v[i] = -INFINITY; + id[i] = 0xffffffffu; + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + for (uint k = 2; k <= 2048; k <<= 1) + for (uint j = k >> 1; j > 0; j >>= 1) { + for (uint i = t; i < 2048; i += 1024) { + const uint l = i ^ j; + if (l > i) { + const bool down = (i & k) == 0; // descending runs where the k-bit is clear + const bool swap = down ? rc_df_before(v[l], id[l], v[i], id[i]) : rc_df_before(v[i], id[i], v[l], id[l]); + if (swap) { + const float tv = v[i]; v[i] = v[l]; v[l] = tv; + const uint ti = id[i]; id[i] = id[l]; id[l] = ti; + } + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + } + if (t < 32) { + VOUT[((size_t)row * a.chunks + chunk) * 32 + t] = v[t]; + IOUT[((size_t)row * a.chunks + chunk) * 32 + t] = id[t]; + } +} + +struct rc_df_walk_args { uint slots, rank, top, vocab; }; + +// z-lab's CandidateSelector, greedy: slot e scores c after p as bf16(unary + bf16(sum_r bf16(A[p][r]H[e][r]) B[c][r])). +[[kernel]] void rc_df_walk(const device float* UV [[buffer(0)]], const device uint* UI [[buffer(1)]], + const device bfloat* H [[buffer(2)]], const device bfloat* A [[buffer(3)]], const device bfloat* B [[buffer(4)]], + constant rc_df_walk_args& a [[buffer(5)]], device uint* seq [[buffer(6)]], uint t [[thread_position_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]], uint sg [[simdgroup_index_in_threadgroup]]) { + threadgroup float part[8][32]; + threadgroup uint prev; + if (t == 0) prev = seq[0]; + threadgroup_barrier(mem_flags::mem_threadgroup); + for (uint e = 0; e < a.slots; ++e) { + const float ah = float(bfloat(float(A[(size_t)prev * a.rank + t]) * float(H[(size_t)e * a.rank + t]))); + for (uint c = 0; c < a.top; ++c) { + const uint cand = UI[e * a.top + c]; + const float s = simd_sum(ah * float(B[(size_t)min(cand, a.vocab - 1) * a.rank + t])); + if (lane == 0) part[sg][c] = s; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (t == 0) { + float best = -INFINITY; + uint bi = 0; + for (uint c = 0; c < a.top; ++c) { + float pair = 0.0f; + for (uint k = 0; k < a.rank / 32; ++k) pair += part[k][c]; + const float s = float(bfloat(UV[e * a.top + c] + float(bfloat(pair)))); + if (UI[e * a.top + c] < a.vocab && s > best) { best = s; bi = c; } + } + prev = UI[e * a.top + bi]; + seq[1 + e] = prev; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + } +} diff --git a/zig/kernels/metal/sources.zig b/zig/kernels/metal/sources.zig index d782e403730..8586e92ddc7 100644 --- a/zig/kernels/metal/sources.zig +++ b/zig/kernels/metal/sources.zig @@ -277,6 +277,8 @@ pub const ricursive_fp4 = @embedFile("ricursive/fp4.metal"); pub const ricursive_fp4_gemm = gemm_nax ++ @embedFile("ricursive/fp4_gemm.metal"); /// Ripple's prompt attention on the tensor units (llama's kernel over a window, keys in a ring; nax.h inlined at load). pub const ricursive_attention_nax = @embedFile("ricursive/attention_nax.metal"); +/// Ripple's DFlash2 drafter (norms, head prep, K-tap block convolution, block attention, selector) and its taps. +pub const ricursive_dflash2 = @embedFile("ricursive/dflash2.metal"); /// The kernel contract's planted controls: one kernel breaking each gate (zig/tests/contract/). pub const core_contract_controls = @embedFile("core/contract_controls.metal"); diff --git a/zig/src/core/contract/ricursive_records.zig b/zig/src/core/contract/ricursive_records.zig index 6dd4c1e6508..12abf34aece 100644 --- a/zig/src/core/contract/ricursive_records.zig +++ b/zig/src/core/contract/ricursive_records.zig @@ -1,4 +1,4 @@ -//! Ripple-65B's Metal launches (metal_ricursive*.zig): its glue, its prompt attention and the draw it runs. +//! Ripple-65B's Metal launches (metal_ricursive*.zig): its glue, prompt attention, the draw and DFlash2's kernels. const M = @import("limits.zig").MetalLaunch; pub const records = [_]M{ .{ .name = "ricursive glue rc_embed", .threads = 256, .tg_memory = 0, .m1 = 1024, .m2 = 1024 }, @@ -24,4 +24,16 @@ pub const records = [_]M{ .{ .name = "ricursive fp4 gemm rc_fp4_gemm_10", .threads = 256, .tg_memory = 0, .reserved = 256, .offline = false }, .{ .name = "ricursive fp4 gemm rc_fp4_gemm_11", .threads = 256, .tg_memory = 0, .reserved = 256, .offline = false }, .{ .name = "ricursive sample tf_sample_full", .threads = 1024, .tg_memory = 9760, .reserved = 1024, .m1 = 1024, .m2 = 1024 }, + // dflash2.metal: the target's tap and the DFlash2 drafter's kernels + .{ .name = "ricursive dflash2 rc_tap", .threads = 256, .tg_memory = 0, .m1 = 1024, .m2 = 1024 }, + .{ .name = "ricursive dflash2 rc_df_norm", .threads = 256, .tg_memory = 128, .m1 = 1024, .m2 = 1024 }, + .{ .name = "ricursive dflash2 rc_df_norm16", .threads = 256, .tg_memory = 128, .m1 = 1024, .m2 = 1024 }, + .{ .name = "ricursive dflash2 rc_df_embed", .threads = 256, .tg_memory = 0, .m1 = 1024, .m2 = 1024 }, + .{ .name = "ricursive dflash2 rc_df_prep", .threads = 32, .tg_memory = 512, .m1 = 1024, .m2 = 1024 }, + .{ .name = "ricursive dflash2 rc_df_conv", .threads = 256, .tg_memory = 0, .m1 = 1024, .m2 = 1024 }, + .{ .name = "ricursive dflash2 rc_df_silu", .threads = 256, .tg_memory = 0, .m1 = 1024, .m2 = 1024 }, + // a simdgroup for each of a key head's 10 query heads + .{ .name = "ricursive dflash2 rc_df_vec", .threads = 320, .tg_memory = 0, .m1 = 1024, .m2 = 1024 }, + .{ .name = "ricursive dflash2 rc_df_topk", .threads = 1024, .tg_memory = 16384, .m1 = 1024, .m2 = 1024 }, + .{ .name = "ricursive dflash2 rc_df_walk", .threads = 256, .tg_memory = 1040, .m1 = 1024, .m2 = 1024 }, }; diff --git a/zig/src/core/lanes/lanes.zig b/zig/src/core/lanes/lanes.zig index e32b7299864..2bed7691557 100644 --- a/zig/src/core/lanes/lanes.zig +++ b/zig/src/core/lanes/lanes.zig @@ -50,6 +50,7 @@ pub const logprob = @import("logprob.zig"); pub const grammar = @import("grammar.zig"); pub const grammar_time = @import("grammar_time.zig"); pub const grammar_fake = @import("grammar_fake.zig"); // a stand-in libtfgrammar for tests +pub const drafted_fixture = @import("drafted_test.zig"); // its fake drafter and prompts, for a family's wrapper tests pub const Engine = engine.Engine; pub const Config = config.Config; diff --git a/zig/src/families/ricursive/backend.zig b/zig/src/families/ricursive/backend.zig index e6ab291a347..4a8f940eb9c 100644 --- a/zig/src/families/ricursive/backend.zig +++ b/zig/src/families/ricursive/backend.zig @@ -11,8 +11,11 @@ const row = @import("../step5/backend.zig").row; const gpu_full = lanes.gpu_full; const be = lanes.backend; -/// The longest context a stream may take, the streams at once, and the bytes every stream's caches may hold. -pub const Options = struct { capacity: usize, streams: u32 = 4, budget: u64 }; +/// A stream's longest context, the streams at once, the caches' bytes, and a drafter's context bytes a stream. +pub const Options = struct { capacity: usize, streams: u32 = 4, budget: u64, drafts: bool = false, drafter_bytes: u64 = 0 }; + +/// Window widths the depth rule prices (a pending token and up to 15 drafts). +const max_window = st.window_rows; /// Token slots a stream's handles point at: drawn tokens and host-fed ones (no command in flight reads a fresh one). const ring = 4096; @@ -38,6 +41,9 @@ pub const Metal = struct { landed: u64 = 0, // slots below it are written flights: std.ArrayList(Flight) = .empty, values: []f32, // a logits row as f32, for the host twin of the GPU draw + sink: ?be.FeatureSink = null, // a drafted prompt pass: each chunk's taps to the drafter as it lands + costs: [max_window]lanes.config.Cost = undefined, // window ms by rows, for the depth rule (measure) + timed: usize = 0, pub fn init(gpa: std.mem.Allocator, model: *Model, options: Options) !*Metal { const out = try gpa.create(Metal); @@ -91,13 +97,77 @@ pub const Metal = struct { return cache; } + /// The ledger's bytes for a stream of `capacity` (budget.charge), held from admission to release. + pub fn charge(self: *const Metal, stream: *const lanes.Stream, capacity: usize) u64 { + return budget.charge(&self.model.config, capacity, stream.drafts, self.options.drafter_bytes); + } + pub fn facts(self: *const Metal) lanes.Model { // rows are independent in every decode kernel, so any width, alone or beside other streams, gives one-row bits - return .{ .exact_width = st.window_rows, .gpu_tokens = true, .hidden_rows = true, .batch_rows = st.batch_rows, .mtp = false, .speculate = false, .speculate_early = false, .drafts = 1, .max_streams = self.options.streams, .streams_exact = true }; + return .{ .exact_width = st.window_rows, .gpu_tokens = !self.options.drafts, .hidden_rows = true, .batch_rows = st.batch_rows, .mtp = false, .speculate = false, .speculate_early = false, .drafts = 1, .max_streams = self.options.streams, .streams_exact = true, .window_costs = self.costs[0..self.timed] }; + } + + /// A window of each width 1..max_window at position 0 on a throwaway cache, the second of two runs timed. + pub fn measure(self: *Metal) !void { + var cache = try st.Cache.init(self.model.device, &self.model.config, 256); + defer cache.deinit(); + var ids: [max_window]u32 = undefined; + for (&ids, 0..) |*x, i| x.* = @intCast(1000 + i * 7919 % 50000); + for (1..max_window + 1) |rows| { + var ms: f64 = 0; + for (0..2) |run| { + cache.len = 0; + const t0 = msNow(); + try fwd.run(self.model, &self.scratch, &cache, ids[0..rows], .{ .all = true }); + if (run == 1) ms = msNow() - t0; + } + self.costs[rows - 1] = .{ .width = @intCast(rows), .ms = ms }; + } + self.timed = max_window; + } + + /// A tapped row's bytes: every tap's hidden row, bf16. + fn tapBytes(self: *const Metal) usize { + return @as(usize, self.model.taps) * self.model.config.hidden * 2; + } + + /// The drafter's layers: both scratches keep their rows from now on. + fn prepareFn(ptr: *anyopaque, taps: []const u32) !void { + const self = cast(ptr); + try self.model.setTaps(taps); + if (self.scratch.taps != null) return; + const opts = mtl.ResourceOptions.shared; + const decode = try self.model.device.buffer(st.batch_rows * self.tapBytes(), opts); + errdefer decode.deinit(); + const prompt = try self.model.device.buffer(st.prompt_rows * self.tapBytes(), opts); + self.scratch.taps = decode; + self.prompt.taps = prompt; + if (self.follow) |f| { + f.join(f.ctx, decode); + f.join(f.ctx, prompt); + } + } + + /// Rows [start, start + count) of the stream's latest tapped rows, on the device. + fn featuresFn(ptr: *anyopaque, stream: *lanes.Stream, taps: []const u32, start: u64, count: u32) !be.Features { + const self = cast(ptr); + const tp = (try self.cacheOf(stream)).tap; + if (taps.len != self.model.taps or tp.buf == null) return error.UnpreparedRicursiveTaps; + if (count == 0 or start < tp.start or start + count > tp.start + tp.rows) return error.RicursiveTapsNotHeld; + const width = self.tapBytes(); + return .{ .buffer = @intFromPtr(tp.buf.?.id), .offset = tp.off + (start - tp.start) * width, .rows = count, .row_bytes = @intCast(width), .space = .device, .dtype = .bf16 }; + } + + fn prefillFeaturesFn(ptr: *anyopaque, stream: *lanes.Stream, taps: []const u32, sink: be.FeatureSink) !void { + const self = cast(ptr); + if (taps.len != self.model.taps) return error.UnpreparedRicursiveTaps; + self.sink = sink; + defer self.sink = null; + return prefillFn(ptr, stream); } pub fn backend(self: *Metal) be.Backend { - return .{ .ptr = self, .vtable = &.{ .prefill = prefillFn, .first = firstFn, .first_masked = firstMaskedFn, .queue = queueFn, .read = readFn, .verify = verifyFn, .keep = keepFn, .draft = draftFn, .release = releaseFn, .first_row = firstRowFn, .held = heldFn } }; + return .{ .ptr = self, .vtable = &.{ .prefill = prefillFn, .prepare_features = prepareFn, .features = featuresFn, .prefill_features = prefillFeaturesFn, .first = firstFn, .first_masked = firstMaskedFn, .queue = queueFn, .read = readFn, .verify = verifyFn, .keep = keepFn, .draft = draftFn, .release = releaseFn, .first_row = firstRowFn, .held = heldFn } }; } fn cast(ptr: *anyopaque) *Metal { @@ -179,13 +249,29 @@ pub const Metal = struct { }; } const s = if (end - at > st.batch_rows) &self.prompt else &self.scratch; - try fwd.run(self.model, s, cache, ids[at..end], .{}); + const taps = if (stream != null) s.taps else null; + try fwd.run(self.model, s, cache, ids[at..end], .{ .taps = if (taps) |x| .{ .buf = x } else null }); + if (taps) |x| try self.keepTaps(cache, stream.?, x, end - at, base + end == stream.?.prompt().len); cache.len += end - at; at = end; if (stream) |sm| if (std.mem.indexOfScalar(u32, sm.reuse.marks, @intCast(cache.len)) != null) if (sm.reuse.hook) |k| k.at(k.ptr, sm, @intCast(cache.len)); } } + /// A drafted prompt chunk's taps: to the drafter as they land, the prompt's last row kept for the first draft. + fn keepTaps(self: *Metal, cache: *st.Cache, stream: *lanes.Stream, x: mtl.Buffer, rows: usize, last: bool) !void { + const width = self.tapBytes(); + if (self.sink) |k| try k.take(k.ptr, stream, .{ .buffer = @intFromPtr(x.id), .rows = @intCast(rows), .row_bytes = @intCast(width), .space = .device, .dtype = .bf16 }, cache.len); + cache.tap = .{ .buf = x, .start = cache.len, .rows = rows }; + if (!last) return; + if (cache.last_tap == null) { + cache.last_tap = try self.model.device.buffer(width, mtl.ResourceOptions.shared); + if (cache.follow) |f| f.join(f.ctx, cache.last_tap.?); + } + @memcpy(cache.last_tap.?.slice(u8, width), x.slice(u8, rows * width)[(rows - 1) * width ..][0..width]); + cache.tap = .{ .buf = cache.last_tap, .start = cache.len + rows - 1, .rows = 1 }; + } + fn prefillFn(ptr: *anyopaque, stream: *lanes.Stream) !void { const self = cast(ptr); try self.drain(); @@ -193,14 +279,14 @@ pub const Metal = struct { if (ids.len == 0 or ids.len + stream.max_new > self.options.capacity or self.caches.contains(stream)) return error.InvalidRicursivePrompt; if (stream.images.len > 0) return error.RicursiveHasNoImageTower; const capacity = ids.len + stream.max_new + 1; - const need = st.cacheBytes(&self.model.config, capacity); - // the stream's caches fit before anything is made; kept states trim first + const need = self.charge(stream, capacity); + // the stream's caches (and its drafter ring) fit before anything is made; kept states trim first const Admit = struct { m: *Metal, stream: *lanes.Stream, ids: []const u32, pub fn growth(_: *const @This()) u64 { - return 0; // no drafter: a stream's caches are all it takes + return 0; // the drafter ring is in the stream's charge, held until release } pub fn shed(_: *const @This(), _: u64) void {} pub fn restoreBytes(a: *const @This()) u64 { @@ -220,7 +306,7 @@ pub const Metal = struct { }; const admit: Admit = .{ .m = self, .stream = stream, .ids = ids }; budget.admitStream(&self.ledger, need, &admit) catch |err| { - if (err == error.LaneMemory) std.log.warn("ricursive: a {d}-token stream needs {d:.1} GiB of caches; {d:.1} of {d:.1} GiB are held", .{ capacity, gib(need + admit.growth()), gib(self.ledger.held), gib(self.ledger.limit) }); + if (err == error.LaneMemory) std.log.warn("ricursive: a {d}-token stream needs {d:.1} GiB of caches; {d:.1} of {d:.1} GiB are held", .{ capacity, gib(need), gib(self.ledger.held), gib(self.ledger.limit) }); return err; // LaneMemory: the lane host queues the stream until another finishes, or fails it alone }; errdefer { // as releaseFn: the bytes back and the prompt cache's room fitted to them (admission trimmed it) @@ -230,9 +316,10 @@ pub const Metal = struct { const cache = try self.createCache(capacity); errdefer self.gpa.destroy(cache); errdefer cache.deinit(); + cache.charge = need; try self.caches.put(self.gpa, stream, cache); // a mark's save finds it there errdefer _ = self.caches.remove(stream); - // the kept states may use what the stream's growth copy and the slot's old cache gave back + // the kept states fitted to what the stream's charge (its caches and any drafter ring) leaves if (self.room) |r| r.fit(r.ctx, self.ledger.left(), stream.reuse.saved, ids); stream.cached = 0; if (stream.reuse.saved) |saved| { // a kept state of this prompt's prefix: the pass starts there @@ -335,7 +422,15 @@ pub const Metal = struct { @memcpy(ids[total + 1 ..][0..w.tokens.len], w.tokens); total += rows; } - try fwd.runShared(self.model, &self.scratch, segments[0..windows.len], ids[0..total], .{ .all = true }); + const taps = self.scratch.taps; + try fwd.runShared(self.model, &self.scratch, segments[0..windows.len], ids[0..total], .{ .all = true, .taps = if (taps) |x| .{ .buf = x } else null }); + if (taps) |x| { + var at: usize = 0; + for (segments[0..windows.len]) |seg| { + seg.cache.tap = .{ .buf = x, .off = at * self.tapBytes(), .start = seg.cache.len, .rows = seg.rows }; + at += seg.rows; + } + } const all = self.scratch.logits_all.slice(u16, total * vocab); var base: usize = 0; for (windows, out, segments[0..windows.len]) |w, o, seg| { @@ -379,7 +474,7 @@ pub const Metal = struct { const self = cast(ptr); self.drain() catch |err| std.log.err("ricursive: a step in flight failed at release: {s}", .{@errorName(err)}); if (self.caches.fetchRemove(stream)) |entry| { - self.ledger.give(st.cacheBytes(&self.model.config, entry.value.capacity)); + self.ledger.give(entry.value.charge); entry.value.deinit(); self.gpa.destroy(entry.value); if (self.room) |r| r.fit(r.ctx, self.ledger.left(), null, &.{}); @@ -428,3 +523,9 @@ fn argmax(l: []const u16) usize { }; return best; } + +fn msNow() f64 { + var ts: std.c.timespec = undefined; + _ = std.c.clock_gettime(.MONOTONIC, &ts); + return @as(f64, @floatFromInt(ts.sec)) * 1e3 + @as(f64, @floatFromInt(ts.nsec)) / 1e6; +} diff --git a/zig/src/families/ricursive/budget.zig b/zig/src/families/ricursive/budget.zig index a7b51364c7b..768ca181468 100644 --- a/zig/src/families/ricursive/budget.zig +++ b/zig/src/families/ricursive/budget.zig @@ -8,6 +8,11 @@ pub const Ledger = llama.Ledger; pub const caches = llama.caches; pub const admitStream = llama.admitStream; +/// A stream's ledger bytes from admission to release: its caches, and its drafter ring if it drafts. +pub fn charge(c: *const cfg.Config, capacity: usize, drafts: bool, ring: u64) u64 { + return st.cacheBytes(c, capacity) + (if (drafts) ring else 0); +} + /// The longest context whose stream (its caches and logits row) fits in `bytes`, at most `most`. pub fn longest(c: *const cfg.Config, bytes: u64, most: usize) usize { if (st.cacheBytes(c, 2) > bytes) return 0; @@ -20,6 +25,29 @@ pub fn longest(c: *const cfg.Config, bytes: u64, most: usize) usize { return lo; } +/// The longest context whose first stream fits in `bytes` with its drafter ring (`ring`; 0 without a drafter). +pub fn longestDrafted(c: *const cfg.Config, bytes: u64, ring: u64, most: usize) usize { + return if (ring > bytes) 0 else longest(c, bytes - ring, most); +} + +test "ricursive budget: a drafter's first ring bounds the context, C + D fits the window and C + D - 1 does not" { + const gpa = std.testing.allocator; + const c = try cfg.parse(gpa, @embedFile("fixtures/config.json")); + const dflash2 = @import("dflash2.zig"); + const dcfg = try @import("dflash2_config.zig").parse(gpa, @embedFile("fixtures/dflash2_config.json"), &c); + const ring: u64 = dflash2.Drafter.laneBytes(&dcfg); + const n: usize = 262144; + const caches_n = st.cacheBytes(&c, n + 1); // a stream of the whole window: its caches and its logits row + // automatic sizing takes the longest that fits; --context n is refused past it: both read this bound + try std.testing.expectEqual(n, longestDrafted(&c, caches_n + ring, ring, n)); + try std.testing.expect(longestDrafted(&c, caches_n + ring - 1, ring, n) < n); + // without a drafter the bound is the caches' alone, as before + try std.testing.expectEqual(n, longestDrafted(&c, caches_n, 0, n)); + try std.testing.expect(longestDrafted(&c, caches_n - 1, 0, n) < n); + try std.testing.expectEqual(longest(&c, caches_n + ring - 1, n), longestDrafted(&c, caches_n + ring - 1, 0, n)); + try std.testing.expectEqual(@as(usize, 0), longestDrafted(&c, ring - 1, ring, n)); +} + test "ricursive budget: a 262,144-token stream's caches fit 17 GiB, not 16" { const c = try cfg.parse(std.testing.allocator, @embedFile("fixtures/config.json")); const gib: u64 = 1 << 30; diff --git a/zig/src/families/ricursive/contracts.zig b/zig/src/families/ricursive/contracts.zig index 5c4ebe4e27c..e9cf9c7082b 100644 --- a/zig/src/families/ricursive/contracts.zig +++ b/zig/src/families/ricursive/contracts.zig @@ -5,6 +5,7 @@ const ks = @import("kernel_sources"); const cfg = @import("config.zig"); const model = @import("model.zig"); const st = @import("state.zig"); +const df = @import("dflash2.zig"); const frags = @import("../../core/frags.zig"); /// Ripple-65B, the family's one qualified checkpoint. @@ -19,8 +20,15 @@ pub const attention_name = "rc_prompt_attention"; pub const sample_name = "tf_sample_full"; pub const fp4_names = model.fp4_names; pub const fp4_gemm_names = [_][]const u8{ "rc_fp4_gemm_00", "rc_fp4_gemm_01", "rc_fp4_gemm_10", "rc_fp4_gemm_11" }; -/// Every pipeline model.zig builds: glue, llama's row kernels and GEMMs, attention, the draw and the NVFP4 MLP's. -pub const pipelines = glue_names.len + llama_names.len + gemm_names.len + 2 + fp4_names.len + fp4_gemm_names.len; +/// dflash2.metal's pipelines: the target's tap (model.zig's setTaps), then the drafter's (dflash2.zig's). +pub const dflash2_names = blk: { + var out: [df.kernel_names.len + 1][]const u8 = undefined; + out[0] = "rc_tap"; + for (df.kernel_names, 1..) |n, i| out[i] = n; + break :blk out; +}; +/// Every pipeline the family builds: glue, llama's row kernels and GEMMs, attention, the draw, NVFP4's and DFlash2's. +pub const pipelines = glue_names.len + llama_names.len + gemm_names.len + 2 + fp4_names.len + fp4_gemm_names.len + dflash2_names.len; /// The glue's text as model.zig builds it. pub fn glueSource(a: std.mem.Allocator) ![]u8 { @@ -54,6 +62,11 @@ pub fn fp4Library(device: mtl.Device, src: []const u8) !mtl.Library { return mtl.Library.fromSource(device, src, .{ .language = mtl.CompileOptions.mlx().language, .math_functions = .precise }); } +/// dflash2.metal's library as dflash2.zig and setTaps compile it: MLX's language, precise math functions. +pub fn dflash2Library(device: mtl.Device, src: []const u8) !mtl.Library { + return mtl.Library.fromSource(device, src, .{ .language = mtl.CompileOptions.mlx().language, .math_functions = .precise }); +} + /// The NVFP4 GEMM's text: nax.h inlined for this GPU (model.zig's build), or as a GPU without tensor units takes it. pub fn fp4GemmSource(device: mtl.Device, a: std.mem.Allocator, units: bool) ![]u8 { if (units) return frags.source(device, a, ks.ricursive_fp4_gemm); @@ -62,7 +75,7 @@ pub fn fp4GemmSource(device: mtl.Device, a: std.mem.Allocator, units: bool) ![]u /// Every pipeline the family runs appears among the registrations' functions. pub fn requireComplete(functions: []const []const u8) !void { - inline for (.{ glue_names, llama_names, gemm_names, [_][]const u8{ attention_name, sample_name }, fp4_names, fp4_gemm_names }) |list| for (list) |name| { + inline for (.{ glue_names, llama_names, gemm_names, [_][]const u8{ attention_name, sample_name }, fp4_names, fp4_gemm_names, dflash2_names }) |list| for (list) |name| { var seen = false; for (functions) |f| if (std.mem.eql(u8, f, name)) { seen = true; @@ -74,7 +87,7 @@ pub fn requireComplete(functions: []const []const u8) !void { test "ricursive contracts: the roll call wants every pipeline" { var all: [pipelines][]const u8 = undefined; var i: usize = 0; - inline for (.{ glue_names, llama_names, gemm_names, [_][]const u8{ attention_name, sample_name }, fp4_names, fp4_gemm_names }) |list| for (list) |name| { + inline for (.{ glue_names, llama_names, gemm_names, [_][]const u8{ attention_name, sample_name }, fp4_names, fp4_gemm_names, dflash2_names }) |list| for (list) |name| { all[i] = name; i += 1; }; diff --git a/zig/src/families/ricursive/dflash2.zig b/zig/src/families/ricursive/dflash2.zig new file mode 100644 index 00000000000..93a7cdeee93 --- /dev/null +++ b/zig/src/families/ricursive/dflash2.zig @@ -0,0 +1,454 @@ +//! ricursiveAI's DFlash2 drafter for Ripple on Metal (z-lab's DFlash2DraftModel): 16-row blocks over 5 target taps. +const std = @import("std"); +const mtl = @import("metal"); +const lanes = @import("lanes"); +const ks = @import("kernel_sources"); +const ck = @import("../../core/checkpoint_metal.zig"); +const shards = @import("../../core/checkpoint.zig"); +const cfg = @import("config.zig"); +const fwd = @import("forward.zig"); +const dc = @import("dflash2_config.zig"); +const Model = @import("model.zig").Model; + +const dr = lanes.drafter; +const Stream = lanes.Stream; +const B = fwd.B; +const b = fwd.b; +const bo = fwd.bo; +const t = fwd.t; +const A = fwd.A; +pub const Config = dc.Config; + +/// Rows a block takes (the trained block). +pub const max_block = 16; +/// Context rows one absorb pass projects at most (a prompt chunk's). +const absorb_rows = 2048; +/// A key block of the draft attention, and the most a row's window spans (the global layer's ring). +const key_block = 128; +const max_key_blocks = dc.global_window / key_block + 2; + +/// One stream's context: each layer's keys and values for the last positions, a ring of Config.ring(layer) slots. +const Lane = struct { + k: [dc.max_layers]mtl.Buffer, + v: [dc.max_layers]mtl.Buffer, + made: bool = false, // the ring is made at the stream's first absorb or hold, after the target admitted its charge + end: u64 = 0, // context rows absorbed: positions [from, end) + from: u64 = 0, // the first position held (a resumed prompt's drafter context starts there) + held: [max_block]u32 = @splat(0), + held_len: u32 = 0, +}; + +/// The drafter's pipelines, in `Kernel` order (the contract's roll call reads them). +pub const kernel_names = [_][:0]const u8{ "rc_df_norm", "rc_df_norm16", "rc_df_embed", "rc_df_prep", "rc_df_conv", "rc_df_silu", "rc_df_vec", "rc_df_topk", "rc_df_walk" }; +const Kernel = enum { norm, norm16, embed, prep, conv, silu, vec, topk, walk }; + +/// The drafter's scratch, fields in init's order. +const fields = [_][]const u8{ "ids", "resid", "x", "xc", "dyn", "qkv", "q", "attn", "y", "yc", "gu", "act", "logits", "pm", "pl", "po", "tv", "ti", "tv2", "ti2", "uv", "ui", "hid", "seq", "fcx", "hctx", "kv" }; + +const NArgs = extern struct { rows: u32, width: u32, eps: f32, add: u32 }; +const PArgs = extern struct { rows: u32, heads: u32, kv_heads: u32, pos0: u32, stride: u32, q_off: u32, k_off: u32, v_off: u32, ring: u32, rope: u32, eps: f32, theta: f32 }; +const VArgs = extern struct { rows: u32, pos0: u32, heads: u32, groups: u32, blocks: u32, chunk: u32, first: u32, scale: f32, hi: u32, window: u32, ring: u32, floor: u32 }; +const CArgs = extern struct { rows: u32, width: u32, block: u32, groups: u32, side: u32, taps: u32 }; + +pub const Drafter = struct { + gpa: std.mem.Allocator, + target: *Model, + config: Config, + checkpoint: ck.Checkpoint, + w: dc.Weights, + pipes: [kernel_names.len]mtl.Pipeline, + lanes: std.AutoHashMapUnmanaged(*Stream, *Lane) = .empty, + follow: ?mtl.ResidencySet.Follow = null, + step_ms: f64 = 0, + s: [fields.len]mtl.Buffer = undefined, + + /// The drafter's config.json, checked against `target` before any weight is read. + 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 << 20)); + defer gpa.free(bytes); + return dc.parse(gpa, bytes, target); + } + + pub fn init(gpa: std.mem.Allocator, io: std.Io, target: *Model, dir: []const u8, config: Config) !*Drafter { + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const d = try gpa.create(Drafter); + errdefer gpa.destroy(d); + d.* = .{ .gpa = gpa, .target = target, .config = config, .checkpoint = ck.Checkpoint.init(gpa), .w = undefined, .pipes = undefined }; + errdefer d.checkpoint.deinit(); + const files = try shards.shardFiles(gpa, io, dir); + defer shards.freeShardFiles(gpa, files); + for (files) |path| try d.checkpoint.addFile(target.device, path, ""); + d.w = try dc.load(&d.checkpoint, &d.config); + { + const lib = try mtl.Library.fromSource(target.device, ks.ricursive_dflash2, .{ .language = mtl.CompileOptions.mlx().language, .math_functions = .precise }); + defer lib.deinit(); + var made: usize = 0; + errdefer for (d.pipes[0..made]) |p| p.deinit(); + for (kernel_names, 0..) |n, i| { + d.pipes[i] = try mtl.Pipeline.init(target.device, lib, n, false); + made += 1; + } + } + errdefer for (d.pipes) |p| p.deinit(); + const sizes = scratchSizes(&d.config); + var made: usize = 0; + errdefer for (d.s[0..made]) |x| x.deinit(); + for (sizes, 0..) |n, i| { + d.s[i] = try target.device.buffer(n, mtl.ResourceOptions.shared); + made += 1; + } + try d.warm(); + return d; + } + + pub fn deinit(d: *Drafter) void { + d.setResident(null); + var it = d.lanes.valueIterator(); + while (it.next()) |l| d.dropLane(l.*); + d.lanes.deinit(d.gpa); + for (d.s) |x| x.deinit(); + for (d.pipes) |p| p.deinit(); + d.checkpoint.deinit(); + d.gpa.destroy(d); + } + + /// Bytes of the scratch, in `fields` order. + fn scratchSizes(c: *const Config) [fields.len]usize { + const h: usize = c.hidden; + const r: usize = max_block; + const qw: usize = @as(usize, c.heads) * cfg.head_dim; + const kvw: usize = @as(usize, c.kv_heads) * cfg.head_dim; + const vocab: usize = c.vocab; + const chunks: usize = (vocab + 2047) / 2048; + const parts: usize = @as(usize, c.heads) * r * max_key_blocks; + return .{ r * 4, r * h * 4, r * h * 2, r * h * 2, r * c.dyn() * 2, r * (qw + 2 * kvw) * 2, r * qw * 2, r * qw * 2, r * h * 2, r * h * 2, r * 2 * c.ffn * 2, r * c.ffn * 2, r * vocab * 2, parts * 4, parts * 4, parts * cfg.head_dim * 4, r * chunks * 32 * 4, r * chunks * 32 * 4, r * 64 * 4, r * 64 * 4, r * 32 * 4, r * 32 * 4, r * c.rank * 2, 16 * 4, absorb_rows * h * 2, absorb_rows * h * 2, absorb_rows * 2 * kvw * 2 }; + } + + /// Device bytes the drafter holds beside its weights: the scratch. + pub fn fixedBytes(c: *const Config) usize { + var n: usize = 0; + for (scratchSizes(c)) |x| n += x; + return n; + } + + /// Device bytes one stream's context takes. + 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 * cfg.head_dim * 2 * 2; + return n; + } + + fn buf(d: *const Drafter, comptime f: []const u8) mtl.Buffer { + inline for (fields, 0..) |n, i| if (comptime std.mem.eql(u8, n, f)) return d.s[i]; + @compileError("no drafter buffer " ++ f); + } + + fn pipe(d: *const Drafter, k: Kernel) mtl.Pipeline { + return d.pipes[@backingInt(k)]; + } + + /// The weights' shards and the scratch, for the host's residency set. + pub fn buffers(d: *const Drafter, gpa: std.mem.Allocator, list: *std.ArrayList(mtl.Buffer)) !void { + for (d.checkpoint.shards.items) |sh| try list.append(gpa, sh.buffer); + try list.appendSlice(gpa, &d.s); + } + + pub fn setResident(d: *Drafter, hook: ?mtl.ResidencySet.Follow) void { + if (d.follow) |f| { + var it = d.lanes.valueIterator(); + while (it.next()) |l| d.laneResident(l.*, f, false); + } + d.follow = hook; + if (hook) |f| { + var it = d.lanes.valueIterator(); + while (it.next()) |l| d.laneResident(l.*, f, true); + } + } + + fn laneResident(d: *const Drafter, l: *const Lane, f: mtl.ResidencySet.Follow, on: bool) void { + if (!l.made) return; + for (0..d.config.layers) |i| for ([_]mtl.Buffer{ l.k[i], l.v[i] }) |x| if (on) f.join(f.ctx, x) else f.leave(f.ctx, x); + } + + 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).config.taps; + } + + fn factsFn(ptr: *anyopaque) dr.Facts { + const d = cast(ptr); + return .{ .depth = d.config.block - 1, .step_ms = d.step_ms, .plain_guard = true, .stream_bytes = laneBytes(&d.config) }; + } + + /// A lane with its ring made (warm's). + fn newLane(d: *Drafter) !*Lane { + const l = try d.gpa.create(Lane); + errdefer d.gpa.destroy(l); + l.* = .{ .k = undefined, .v = undefined }; + try d.makeRing(l); + return l; + } + + /// The lane's ring buffers, once; a failure leaves none made. + fn makeRing(d: *Drafter, l: *Lane) !void { + if (l.made) return; + var made: usize = 0; + errdefer for (0..made) |i| { + l.k[i].deinit(); + l.v[i].deinit(); + }; + for (0..d.config.layers) |i| { + const bytes = @as(usize, d.config.ring(i)) * d.config.kv_heads * cfg.head_dim * 2; + l.k[i] = try d.target.device.buffer(bytes, mtl.ResourceOptions.private); + l.v[i] = d.target.device.buffer(bytes, mtl.ResourceOptions.private) catch |e| { + l.k[i].deinit(); + return e; + }; + made += 1; + } + l.made = true; + if (d.follow) |f| d.laneResident(l, f, true); + } + + fn dropLane(d: *Drafter, l: *Lane) void { + if (d.follow) |f| d.laneResident(l, f, false); + if (l.made) for (0..d.config.layers) |i| { + l.k[i].deinit(); + l.v[i].deinit(); + }; + d.gpa.destroy(l); + } + + fn openFn(ptr: *anyopaque, s: *Stream) anyerror!void { + const d = cast(ptr); + if (d.lanes.contains(s)) return error.DraftStreamOpen; + // no ring yet: on the streamed prompt pass this runs before the target admits the stream's charge + const l = try d.gpa.create(Lane); + errdefer d.gpa.destroy(l); + l.* = .{ .k = undefined, .v = undefined }; + 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.dropLane(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]); + } + } + + fn glue(e: mtl.ComputeEncoder, p: mtl.Pipeline, args: anytype, bufs: []const B, grid: [3]usize, group: [3]usize) void { + e.setPipeline(p); + for (bufs, 0..) |r, slot| if (r.args) e.setValue(args, slot) else e.setBuffer(r.buf, r.off, slot); + e.dispatchGroups(mtl.Size.of(grid[0], grid[1], grid[2]), mtl.Size.of(group[0], group[1], group[2])); + } + + fn threads(e: mtl.ComputeEncoder, p: mtl.Pipeline, args: anytype, bufs: []const B, grid: [3]usize) void { + e.setPipeline(p); + for (bufs, 0..) |r, slot| if (r.args) e.setValue(args, slot) else e.setBuffer(r.buf, r.off, slot); + e.dispatchThreads(mtl.Size.of(grid[0], grid[1], grid[2]), mtl.Size.of(256, 1, 1)); + } + + /// y = x W^T over `rows` rows, `ldy` apart: the target's row kernels to 32 rows, its GEMM past them. + fn project(d: *const Drafter, e: mtl.ComputeEncoder, w: @import("weights.zig").Dense, in: B, out: B, rows: usize, ldy: usize) void { + fwd.denseRows(e, d.target, w, in, out.buf, out.off, rows, ldy); + } + + /// The context rows [p0, p0 + rows) from `src` (taps x hidden bf16 each) into every layer's ring. + fn absorbRows(d: *const Drafter, e: mtl.ComputeEncoder, l: *const Lane, src: B, p0: u64, rows: usize) void { + const c = &d.config; + const kvw: usize = @as(usize, c.kv_heads) * cfg.head_dim; + d.project(e, d.w.fc, src, b(d.buf("fcx")), rows, c.hidden); + glue(e, d.pipe(.norm16), NArgs{ .rows = @intCast(rows), .width = c.hidden, .eps = c.eps, .add = 0 }, &.{ b(d.buf("fcx")), t(d.w.hidden_norm), A, b(d.buf("hctx")) }, .{ rows, 1, 1 }, .{ 256, 1, 1 }); + for (0..c.layers) |i| { + const L = &d.w.layers[i]; + // each layer's k and v of the normed taps, k normed and rotated, into the layer's ring + d.project(e, L.k, b(d.buf("hctx")), b(d.buf("kv")), rows, 2 * kvw); + d.project(e, L.v, b(d.buf("hctx")), bo(d.buf("kv"), kvw * 2), rows, 2 * kvw); + const pa = PArgs{ .rows = @intCast(rows), .heads = 0, .kv_heads = c.kv_heads, .pos0 = @intCast(p0), .stride = @intCast(2 * kvw), .q_off = 0, .k_off = 0, .v_off = @intCast(kvw), .ring = c.ring(i), .rope = @intFromBool(c.rope[i]), .eps = c.eps, .theta = c.theta }; + glue(e, d.pipe(.prep), pa, &.{ b(d.buf("kv")), t(L.q_norm), t(L.k_norm), A, b(d.buf("q")), b(l.k[i]), b(l.v[i]) }, .{ c.kv_heads, rows, 1 }, .{ 32, 1, 1 }); + } + } + + /// 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.config; + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const cb = d.target.queue.commandBuffer(); + const e = cb.compute(.serial); + const width: usize = dc.max_taps * @as(usize, c.hidden) * 2; + for (items) |it| { + const l = d.lanes.get(it.stream) orelse return error.DraftStreamUnknown; + try d.makeRing(l); + 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 src = mtl.Buffer{ .id = @ptrFromInt(f.buffer) }; + const end = it.start + f.rows; + const keep_from = if (it.prompt) @max(it.start, it.stream.prompt_len -| (dc.global_window + c.block)) else it.start; + 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 n: usize = @intCast(@min(absorb_rows, end - at)); + d.absorbRows(e, l, bo(src, f.offset + @as(usize, @intCast(at - it.start)) * width), at, n); + at += n; + } + l.end = end; + l.held_len = 0; + } + e.end(); + cb.commit(); + cb.wait(); + if (cb.failure()) |msg| return failed(msg); + } + + /// x (n rows, the sublayer's normed input) through `cv`'s prepare: its coefficients into dyn, side 0 into xc. + fn convPrepare(d: *const Drafter, e: mtl.ComputeEncoder, cv: dc.Conv, n: usize) void { + const c = &d.config; + d.project(e, cv.proj, b(d.buf("x")), b(d.buf("dyn")), n, c.dyn()); + d.conv(e, cv, b(d.buf("x")), b(d.buf("xc")), n, 0); + } + + fn conv(d: *const Drafter, e: mtl.ComputeEncoder, cv: dc.Conv, in: B, out: B, n: usize, side: u32) void { + const c = &d.config; + threads(e, d.pipe(.conv), CArgs{ .rows = @intCast(n), .width = c.hidden, .block = c.block, .groups = c.hidden / c.group, .side = side, .taps = c.conv }, &.{ in, b(d.buf("dyn")), t(cv.base), A, out }, .{ c.hidden, n, 1 }); + } + + /// The block [pending, mask x 15] at positions anchor.. through the drafter; seq[1..] its drafts. + fn encodeBlock(d: *const Drafter, e: mtl.ComputeEncoder, l: *const Lane, pending: u32, anchor: u64) void { + const c = &d.config; + const m = d.target; + const n: usize = c.block; + const h: usize = c.hidden; + const qw: usize = @as(usize, c.heads) * cfg.head_dim; + const kvw: usize = @as(usize, c.kv_heads) * cfg.head_dim; + const stride = qw + 2 * kvw; + const ids = d.buf("ids").slice(u32, max_block); + ids[0] = pending; + @memset(ids[1..n], c.mask); + d.buf("seq").slice(u32, 16)[0] = pending; + const E = m.weights.embed; + threads(e, d.pipe(.embed), NArgs{ .rows = @intCast(n), .width = c.hidden, .eps = 0, .add = 0 }, &.{ b(d.buf("ids")), bo(E.buf, E.off), A, b(d.buf("resid")) }, .{ h, n, 1 }); + const hi = anchor + n; + 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) + glue(e, d.pipe(.norm), NArgs{ .rows = @intCast(n), .width = c.hidden, .eps = c.eps, .add = @intFromBool(i > 0) }, &.{ b(d.buf("resid")), b(d.buf("yc")), t(L.in_norm), A, b(d.buf("x")) }, .{ n, 1, 1 }, .{ 256, 1, 1 }); + d.convPrepare(e, L.attn_conv, n); + d.project(e, L.q, b(d.buf("xc")), b(d.buf("qkv")), n, stride); + d.project(e, L.k, b(d.buf("xc")), bo(d.buf("qkv"), qw * 2), n, stride); + d.project(e, L.v, b(d.buf("xc")), bo(d.buf("qkv"), (qw + kvw) * 2), n, stride); + const pa = PArgs{ .rows = @intCast(n), .heads = c.heads, .kv_heads = c.kv_heads, .pos0 = @intCast(anchor), .stride = @intCast(stride), .q_off = 0, .k_off = @intCast(qw), .v_off = @intCast(qw + kvw), .ring = c.ring(i), .rope = @intFromBool(c.rope[i]), .eps = c.eps, .theta = c.theta }; + glue(e, d.pipe(.prep), pa, &.{ b(d.buf("qkv")), t(L.q_norm), t(L.k_norm), A, b(d.buf("q")), b(l.k[i]), b(l.v[i]) }, .{ c.heads + c.kv_heads, n, 1 }, .{ 32, 1, 1 }); + const span = c.span(i); + const lo = @max((anchor + 1) -| span, l.from); + const first = lo / key_block; + const blocks = (hi - 1) / key_block - first + 1; + const va = VArgs{ .rows = @intCast(n), .pos0 = @intCast(anchor), .heads = c.heads, .groups = c.kv_heads, .blocks = @intCast(blocks), .chunk = key_block, .first = @intCast(first), .scale = 1.0 / @sqrt(@as(f32, cfg.head_dim)), .hi = @intCast(hi), .window = span, .ring = c.ring(i), .floor = @intCast(l.from) }; + glue(e, d.pipe(.vec), va, &.{ b(d.buf("q")), b(l.k[i]), b(l.v[i]), A, b(d.buf("pm")), b(d.buf("pl")), b(d.buf("po")) }, .{ c.kv_heads, n, blocks }, .{ 32, c.heads / c.kv_heads, 1 }); + glue(e, m.ll(.merge_vec), va, &.{ b(d.buf("pm")), b(d.buf("pl")), b(d.buf("po")), A, b(d.buf("attn")) }, .{ c.heads, n, 1 }, .{ 1024, 1, 1 }); + d.project(e, L.o, b(d.buf("attn")), b(d.buf("y")), n, h); + // the attention conv's finish (side 1, its prepare's coefficients), then the post-attention norm + d.conv(e, L.attn_conv, b(d.buf("y")), b(d.buf("yc")), n, 1); + glue(e, d.pipe(.norm), NArgs{ .rows = @intCast(n), .width = c.hidden, .eps = c.eps, .add = 1 }, &.{ b(d.buf("resid")), b(d.buf("yc")), t(L.post_norm), A, b(d.buf("x")) }, .{ n, 1, 1 }, .{ 256, 1, 1 }); + d.convPrepare(e, L.mlp_conv, n); + d.project(e, L.gate, b(d.buf("xc")), b(d.buf("gu")), n, 2 * c.ffn); + d.project(e, L.up, b(d.buf("xc")), bo(d.buf("gu"), @as(usize, c.ffn) * 2), n, 2 * c.ffn); + threads(e, d.pipe(.silu), extern struct { rows: u32, width: u32 }{ .rows = @intCast(n), .width = c.ffn }, &.{ b(d.buf("gu")), A, b(d.buf("act")) }, .{ c.ffn, n, 1 }); + d.project(e, L.down, b(d.buf("act")), b(d.buf("y")), n, h); + d.conv(e, L.mlp_conv, b(d.buf("y")), b(d.buf("yc")), n, 1); + } + glue(e, d.pipe(.norm), NArgs{ .rows = @intCast(n), .width = c.hidden, .eps = c.eps, .add = 1 }, &.{ b(d.buf("resid")), b(d.buf("yc")), t(d.w.norm), A, b(d.buf("x")) }, .{ n, 1, 1 }, .{ 256, 1, 1 }); + // rows 1-15: the target's head, each row's top 32 (three passes of 2048), the selector's projection and path + const slots = n - 1; + const xr = bo(d.buf("x"), h * 2); + d.project(e, m.weights.head, xr, b(d.buf("logits")), slots, c.vocab); + d.project(e, d.w.hproj, xr, b(d.buf("hid")), slots, c.rank); + const chunks: u32 = (c.vocab + 2047) / 2048; + const TArgs = extern struct { n: u32, stride: u32, chunks: u32, from_ids: u32 }; + glue(e, d.pipe(.topk), TArgs{ .n = c.vocab, .stride = c.vocab, .chunks = chunks, .from_ids = 0 }, &.{ b(d.buf("logits")), b(d.buf("tv")), b(d.buf("ti")), A, b(d.buf("tv")), b(d.buf("ti")) }, .{ chunks, slots, 1 }, .{ 1024, 1, 1 }); + const second: u32 = (chunks * 32 + 2047) / 2048; + glue(e, d.pipe(.topk), TArgs{ .n = chunks * 32, .stride = chunks * 32, .chunks = second, .from_ids = 1 }, &.{ b(d.buf("logits")), b(d.buf("tv")), b(d.buf("ti")), A, b(d.buf("tv2")), b(d.buf("ti2")) }, .{ second, slots, 1 }, .{ 1024, 1, 1 }); + glue(e, d.pipe(.topk), TArgs{ .n = second * 32, .stride = second * 32, .chunks = 1, .from_ids = 1 }, &.{ b(d.buf("logits")), b(d.buf("tv2")), b(d.buf("ti2")), A, b(d.buf("uv")), b(d.buf("ui")) }, .{ 1, slots, 1 }, .{ 1024, 1, 1 }); + const WArgs = extern struct { slots: u32, rank: u32, top: u32, vocab: u32 }; + glue(e, d.pipe(.walk), WArgs{ .slots = @intCast(slots), .rank = c.rank, .top = c.top, .vocab = c.vocab }, &.{ b(d.buf("uv")), b(d.buf("ui")), b(d.buf("hid")), t(d.w.pred), t(d.w.succ), A, b(d.buf("seq")) }, .{ 1, 1, 1 }, .{ c.rank, 1, 1 }); + } + + /// Each stream's `depth` drafts after `pending` at `position`: a whole block each (its rows see each other). + fn holdFn(ptr: *anyopaque, items: []const dr.Hold) anyerror!void { + const d = cast(ptr); + const c = &d.config; + for (items) |it| { + const l = d.lanes.get(it.stream) orelse return error.DraftStreamUnknown; + try d.makeRing(l); + 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; + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const cb = d.target.queue.commandBuffer(); + const e = cb.compute(.serial); + d.encodeBlock(e, l, it.pending, anchor); + e.end(); + cb.commit(); + cb.wait(); + if (cb.failure()) |msg| return failed(msg); + const seq = d.buf("seq").slice(u32, 16); + for (seq[1..][0..it.depth], l.held[0..it.depth]) |x, *y| { + if (x >= c.vocab) return error.DraftNonfinite; + y.* = x; + } + l.held_len = it.depth; + } + } + + /// The pipelines' first launch, then a block timed (the depth rule prices a draft at a block's time over its rows). + fn warm(d: *Drafter) !void { + const l = try d.newLane(); + defer d.dropLane(l); + var ms: f64 = 0; + for (0..3) |run| { + const t0 = msNow(); + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const cb = d.target.queue.commandBuffer(); + const e = cb.compute(.serial); + d.encodeBlock(e, l, 2, 0); + e.end(); + cb.commit(); + cb.wait(); + if (cb.failure()) |msg| return failed(msg); + if (run == 2) ms = msNow() - t0; + } + d.step_ms = ms / @as(f64, @floatFromInt(d.config.block - 1)); + } + + fn failed(msg: [*:0]const u8) anyerror { + std.log.err("ricursive DFlash2 drafter: command buffer failed: {s}", .{msg}); + return error.GpuFailed; + } +}; + +fn msNow() f64 { + var ts: std.c.timespec = undefined; + _ = std.c.clock_gettime(.MONOTONIC, &ts); + return @as(f64, @floatFromInt(ts.sec)) * 1e3 + @as(f64, @floatFromInt(ts.nsec)) / 1e6; +} diff --git a/zig/src/families/ricursive/dflash2_charge_test.zig b/zig/src/families/ricursive/dflash2_charge_test.zig new file mode 100644 index 00000000000..b7442749a77 --- /dev/null +++ b/zig/src/families/ricursive/dflash2_charge_test.zig @@ -0,0 +1,242 @@ +//! A --drafter server's memory plan: one charge a stream from admission to release, its drafter ring made after it. +const std = @import("std"); +const lanes = @import("lanes"); +const cfg = @import("config.zig"); +const st = @import("state.zig"); +const budget = @import("budget.zig"); +const dc = @import("dflash2_config.zig"); +const fixture = lanes.drafted_fixture; +const be = lanes.backend; +const dr = lanes.drafter; +const Stream = lanes.Stream; + +const gpa = std.testing.allocator; + +/// The lanes fake as Ripple's target: each prompt pass admits the stream's charge as backend.prefillFn does. +const Target = struct { + fake: lanes.fake.Fake, + c: *const cfg.Config, + ring: u64, + ledger: budget.Ledger, + charges: std.AutoHashMapUnmanaged(*Stream, u64) = .empty, + live: u64 = 0, // bytes made: caches at admission, rings when the drafter makes them + peak: u64 = 0, + vt: be.Backend.VTable = undefined, + + fn deinit(t: *Target) void { + t.charges.deinit(gpa); + t.fake.deinit(); + } + + fn backend(t: *Target) be.Backend { + var b = t.fake.backend(); + t.vt = b.vtable.*; + t.vt.prefill = prefill; + t.vt.prefill_features = prefillFeatures; + t.vt.release = release; + b.vtable = &t.vt; + return b; + } + + fn of(ptr: *anyopaque) *Target { + const f: *lanes.fake.Fake = @ptrCast(@alignCast(ptr)); + return @fieldParentPtr("fake", f); + } + + fn made(t: *Target, bytes: u64) !void { + t.live += bytes; + t.peak = @max(t.peak, t.live); + try std.testing.expect(t.live <= t.ledger.held and t.ledger.held <= t.ledger.limit); + } + + /// The whole prompt pass (a stream drafting off): its charge admitted, then the fake's pass. + fn prefill(ptr: *anyopaque, s: *Stream) anyerror!void { + try of(ptr).admitted(s); + try of(ptr).fake.backend().vtable.prefill(ptr, s); + } + + /// The streamed pass (a stream drafting on): its charge admitted, the fake's pass, then its rows to the drafter. + fn prefillFeatures(ptr: *anyopaque, s: *Stream, taps: []const u32, sink: be.FeatureSink) anyerror!void { + const t = of(ptr); + try t.admitted(s); + try t.fake.backend().vtable.prefill(ptr, s); + const n: u32 = @intCast(s.prompt().len); + try sink.take(sink.ptr, s, try t.fake.backend().vtable.features.?(ptr, s, taps, 0, n), 0); + } + + /// The stream's charge taken as backend.prefillFn takes it, and its caches made. + fn admitted(t: *Target, s: *Stream) !void { + const capacity = s.prompt().len + s.max_new + 1; + const need = budget.charge(t.c, capacity, s.drafts, t.ring); + const Admit = struct { + pub fn growth(_: *const @This()) u64 { + return 0; + } + pub fn shed(_: *const @This(), _: u64) void {} + pub fn restoreBytes(_: *const @This()) u64 { + return 0; + } + pub fn dropRestore(_: *const @This()) void {} + pub fn trim(_: *const @This(), _: u64) void {} + pub fn prepare(_: *const @This()) !void {} + }; + try budget.admitStream(&t.ledger, need, &Admit{}); + try t.charges.put(gpa, s, need); + try t.made(st.cacheBytes(t.c, capacity)); + } + + fn release(ptr: *anyopaque, s: *Stream) void { + const t = of(ptr); + if (t.charges.fetchRemove(s)) |kv| { + t.ledger.give(kv.value); // the same bytes admission took + t.live -= kv.value - (if (s.drafts) t.ring else 0); + } + t.fake.backend().vtable.release(ptr, s); + } +}; + +/// The fake drafter with Ripple's ring rule: none at open, made at the stream's first absorb or hold. +const Rings = struct { + inner: fixture.FakeDrafter = .{}, + t: *Target, + rings: std.AutoHashMapUnmanaged(*Stream, void) = .empty, + vt: dr.Drafter.VTable = undefined, + + fn deinit(r: *Rings) void { + r.rings.deinit(gpa); + r.inner.deinit(); + } + + fn drafter(r: *Rings) dr.Drafter { + var d = r.inner.drafter(); + r.vt = d.vtable.*; + r.vt.absorb = absorb; + r.vt.hold = hold; + r.vt.release = release; + d.vtable = &r.vt; + return d; + } + + fn of(ptr: *anyopaque) *Rings { + const f: *fixture.FakeDrafter = @ptrCast(@alignCast(ptr)); + return @fieldParentPtr("inner", f); + } + + fn make(r: *Rings, s: *Stream) !void { + if (r.rings.contains(s)) return; + try std.testing.expect(r.t.charges.contains(s)); // the target admitted the stream's charge first + try r.rings.put(gpa, s, {}); + try r.t.made(r.t.ring); + } + + fn absorb(ptr: *anyopaque, items: []const dr.Absorb) anyerror!void { + const r = of(ptr); + for (items) |it| try r.make(it.stream); + return r.inner.drafter().vtable.absorb(ptr, items); + } + + fn hold(ptr: *anyopaque, items: []const dr.Hold) anyerror!void { + const r = of(ptr); + for (items) |it| try r.make(it.stream); + return r.inner.drafter().vtable.hold(ptr, items); + } + + fn release(ptr: *anyopaque, s: *Stream) void { + const r = of(ptr); + if (r.rings.remove(s)) r.t.live -= r.t.ring; + r.inner.drafter().vtable.release(ptr, s); + } +}; + +/// A Ripple config and its drafter's ring, and a stream's caches at the fixture prompt's capacity. +const Plan = struct { c: cfg.Config, ring: u64, caches: u64 }; + +const max_new = 40; + +fn plan() !Plan { + const c = try cfg.parse(gpa, @embedFile("fixtures/config.json")); + const d = try dc.parse(gpa, @embedFile("fixtures/dflash2_config.json"), &c); + const ring: u64 = @import("dflash2.zig").Drafter.laneBytes(&d); + return .{ .c = c, .ring = ring, .caches = st.cacheBytes(&c, fixture.p1.len + max_new + 1) }; +} + +/// The wrapper's prompt pass for `streams` under `limit`: each one's outcome, in order, none released between them. +fn admit(p: *const Plan, limit: u64, drafts: []const bool, out: []anyerror!void) !struct { held: u64, peak: u64, rings: usize } { + var t: Target = .{ .fake = .{ .gpa = gpa }, .c = &p.c, .ring = p.ring, .ledger = .{ .limit = limit } }; + defer t.deinit(); + var r: Rings = .{ .t = &t }; + defer r.deinit(); + var w = try dc.wrap(gpa, t.backend(), r.drafter()); + defer w.deinit(); + const b = w.backend(); + var ss: [2]Stream = undefined; + for (drafts, 0..) |on, i| ss[i] = try Stream.init(gpa, .{ .id = "s", .prompt = &fixture.p1, .max_new = max_new, .eos = &.{96}, .drafts = on }); + defer for (ss[0..drafts.len]) |*s| s.deinit(gpa); + for (ss[0..drafts.len], out) |*s, *o| o.* = b.vtable.prefill(b.ptr, s); + const held = t.ledger.held; + const peak = t.peak; + const rings = r.rings.count(); + for (ss[0..drafts.len]) |*s| b.vtable.release(b.ptr, s); + try std.testing.expectEqual(@as(u64, 0), t.ledger.held); // every charge given back as taken + try std.testing.expectEqual(@as(u64, 0), t.live); + return .{ .held = held, .peak = peak, .rings = rings }; +} + +test "two drafting streams are charged their rings too: the second waits when both do not fit" { + const p = try plan(); + const one = p.caches + p.ring; + var out: [2]anyerror!void = undefined; + // room for one drafting stream and a second's caches, not its ring: the second is refused, not admitted short + const got = try admit(&p, 2 * one - 1, &.{ true, true }, &out); + try out[0]; + try std.testing.expectError(error.LaneMemory, out[1]); + try std.testing.expectEqual(one, got.held); // the first stream's ring stays in the ledger after its admission + try std.testing.expectEqual(@as(usize, 1), got.rings); + try std.testing.expect(got.peak <= 2 * one - 1); + // with room for both, both hold their caches and rings + const both = try admit(&p, 2 * one, &.{ true, true }, &out); + try out[0]; + try out[1]; + try std.testing.expectEqual(2 * one, both.held); + try std.testing.expectEqual(@as(usize, 2), both.rings); +} + +test "a stream with drafting off is charged its caches only: it fits exactly where a drafting one does not" { + const p = try plan(); + var out: [1]anyerror!void = undefined; + const off = try admit(&p, p.caches, &.{false}, &out); + try out[0]; + try std.testing.expectEqual(p.caches, off.held); + try std.testing.expectEqual(@as(usize, 0), off.rings); + _ = try admit(&p, p.caches + p.ring - 1, &.{true}, &out); + try std.testing.expectError(error.LaneMemory, out[0]); + const on = try admit(&p, p.caches + p.ring, &.{true}, &out); + try out[0]; + try std.testing.expectEqual(p.caches + p.ring, on.held); +} + +test "the streamed prompt pass makes a drafter ring only after the target admitted the stream's charge" { + const p = try plan(); + var out: [2]anyerror!void = undefined; + // Rings.make checks the charge is held before a ring is made, and Target.made that nothing made passes the ledger + const got = try admit(&p, 2 * (p.caches + p.ring), &.{ true, false }, &out); + try out[0]; + try out[1]; + try std.testing.expectEqual(@as(usize, 1), got.rings); + try std.testing.expectEqual(2 * p.caches + p.ring, got.peak); +} + +test "Ripple's drafter opens a stream with no ring: its buffers wait for the first absorb or hold" { + var d: @import("dflash2.zig").Drafter = undefined; + d.gpa = gpa; + d.lanes = .empty; + d.follow = null; + defer d.lanes.deinit(gpa); + var s = try Stream.init(gpa, .{ .id = "s", .prompt = &fixture.p1, .max_new = max_new, .eos = &.{96} }); + defer s.deinit(gpa); + const x = d.drafter(); + try x.vtable.open(x.ptr, &s); + try std.testing.expect(!d.lanes.get(&s).?.made); + x.vtable.release(x.ptr, &s); + try std.testing.expectEqual(@as(usize, 0), d.lanes.count()); +} diff --git a/zig/src/families/ricursive/dflash2_config.zig b/zig/src/families/ricursive/dflash2_config.zig new file mode 100644 index 00000000000..57513bb0048 --- /dev/null +++ b/zig/src/families/ricursive/dflash2_config.zig @@ -0,0 +1,263 @@ +//! ricursiveAI's DFlash2 drafter for Ripple (Ripple-65B-Preview-DFlash2): its config and bf16 weights as published. +const std = @import("std"); +const lane = @import("lanes"); +const ck = @import("../../core/checkpoint_metal.zig"); +const wts = @import("weights.zig"); +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; +/// 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; + +/// The --drafter server's backend: it advertises logprobs, so the wrapper must offer Ripple's first-token row. +pub fn wrap(gpa: std.mem.Allocator, target: lane.backend.Backend, drafter: lane.drafter.Drafter) !lane.drafted.Drafted { + var w = try lane.drafted.Drafted.init(gpa, target, drafter); + w.first_rows = true; + return w; +} + +/// Streams a drafted server opens: a named --parallel up to `max_streams`, else `max_streams`; null refuses more. +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 Conv = struct { base: wts.Tensor, proj: wts.Dense }; +pub const Layer = struct { + in_norm: wts.Tensor, + post_norm: wts.Tensor, + q_norm: wts.Tensor, + k_norm: wts.Tensor, + q: wts.Dense, + k: wts.Dense, + v: wts.Dense, + o: wts.Dense, + gate: wts.Dense, + up: wts.Dense, + down: wts.Dense, + attn_conv: Conv, + mlp_conv: Conv, +}; + +pub const Weights = struct { + fc: wts.Dense, // the taps' concatenation into the hidden width + hidden_norm: wts.Tensor, + norm: wts.Tensor, + hproj: wts.Dense, // the selector's hidden projection + pred: wts.Tensor, + succ: wts.Tensor, + layers: [max_layers]Layer, +}; + +/// Every tensor the release stores, each at its exact shape in bf16. +pub fn load(c: *const ck.Checkpoint, f: *const Config) !Weights { + const h: usize = f.hidden; + const kvw: usize = @as(usize, f.kv_heads) * cfg.head_dim; + const qw: usize = @as(usize, f.heads) * cfg.head_dim; + var w: Weights = .{ + .fc = try wts.dense(c, "", "fc.weight", h, h * max_taps), + .hidden_norm = try wts.get(c, "", "hidden_norm.weight", &.{h}), + .norm = try wts.get(c, "", "norm.weight", &.{h}), + .hproj = try wts.dense(c, "", "candidate_selector.hidden_projection.weight", f.rank, h), + .pred = try wts.get(c, "", "candidate_selector.predecessor_codebook", &.{ f.vocab, f.rank }), + .succ = try wts.get(c, "", "candidate_selector.successor_codebook", &.{ f.vocab, f.rank }), + .layers = undefined, + }; + for (&w.layers, 0..) |*l, i| { + var nb: [32]u8 = undefined; + const p = try std.fmt.bufPrint(&nb, "layers.{d}.", .{i}); + l.* = .{ + .in_norm = try wts.get(c, p, "input_layernorm.weight", &.{h}), + .post_norm = try wts.get(c, p, "post_attention_layernorm.weight", &.{h}), + .q_norm = try wts.get(c, p, "self_attn.q_norm.weight", &.{cfg.head_dim}), + .k_norm = try wts.get(c, p, "self_attn.k_norm.weight", &.{cfg.head_dim}), + .q = try wts.dense(c, p, "self_attn.q_proj.weight", qw, h), + .k = try wts.dense(c, p, "self_attn.k_proj.weight", kvw, h), + .v = try wts.dense(c, p, "self_attn.v_proj.weight", kvw, h), + .o = try wts.dense(c, p, "self_attn.o_proj.weight", h, qw), + .gate = try wts.dense(c, p, "mlp.gate_proj.weight", f.ffn, h), + .up = try wts.dense(c, p, "mlp.up_proj.weight", f.ffn, h), + .down = try wts.dense(c, p, "mlp.down_proj.weight", h, f.ffn), + .attn_conv = .{ .base = try wts.get(c, p, "attention_conv.base_kernel", &.{ 2, f.conv, h }), .proj = try wts.dense(c, p, "attention_conv.kernel_projection.weight", f.dyn(), h) }, + .mlp_conv = .{ .base = try wts.get(c, p, "mlp_conv.base_kernel", &.{ 2, f.conv, h }), .proj = try wts.dense(c, p, "mlp_conv.kernel_projection.weight", f.dyn(), h) }, + }; + } + 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)); + try std.testing.expectEqual(@as(?u32, 1), streams(1, true)); + try std.testing.expectEqual(@as(?u32, 2), streams(2, true)); + try std.testing.expectEqual(@as(?u32, null), streams(3, true)); + try std.testing.expectEqual(@as(?u32, null), streams(8, true)); +} diff --git a/zig/src/families/ricursive/dflash2_rows_test.zig b/zig/src/families/ricursive/dflash2_rows_test.zig new file mode 100644 index 00000000000..bcde55bc167 --- /dev/null +++ b/zig/src/families/ricursive/dflash2_rows_test.zig @@ -0,0 +1,52 @@ +//! A --drafter server's logprobs: each token's row, drafting on or off, is the one the plain target gives. +const std = @import("std"); +const lanes = @import("lanes"); +const dc = @import("dflash2_config.zig"); +const fixture = lanes.drafted_fixture; +const Row = lanes.LogprobRow; + +const gpa = std.testing.allocator; + +const Run = struct { tokens: []u32, rows: []Row, drafted: u64 }; + +/// A stream asking for 3 logprobs a token: through the host's wrapper with drafting `drafts`, or on the bare target. +fn run(wrapped: bool, drafts: bool, sampling: ?lanes.sampling.Sampling) !Run { + var target: lanes.fake.Fake = .{ .gpa = gpa }; + defer target.deinit(); + var head: fixture.FakeDrafter = .{}; + defer head.deinit(); + var w = try dc.wrap(gpa, target.backend(), head.drafter()); + defer w.deinit(); + var cfg = try lanes.Config.init(gpa, if (wrapped) w.facts(fixture.base()) else fixture.base(), 16, 15); + defer cfg.deinit(gpa); + var clock: lanes.fake.FixedClock = .{}; + var engine = lanes.Engine.init(gpa, &cfg, if (wrapped) w.backend() else target.backend(), clock.clock()); + defer engine.deinit(); + var s = try lanes.Stream.init(gpa, .{ .id = "s", .prompt = &fixture.p1, .max_new = 40, .eos = &.{96}, .sampling = sampling, .drafts = drafts, .logprobs = 3 }); + defer s.deinit(gpa); + try engine.addStream(&s); + while (engine.activeCount() > 0) try engine.step(); + try std.testing.expectEqual(s.emitted().len, s.rows.items.len); + return .{ .tokens = try gpa.dupe(u32, s.emitted()), .rows = try gpa.dupe(Row, s.rows.items), .drafted = s.drafted }; +} + +test "a drafter server answers logprobs with drafting on and off, row for row the plain target's" { + for ([_]?lanes.sampling.Sampling{ null, fixture.sampled }) |sampling| { + const plain = try run(false, false, sampling); + defer gpa.free(plain.tokens); + defer gpa.free(plain.rows); + for ([_]bool{ true, false }) |drafts| { + const got = try run(true, drafts, sampling); + defer gpa.free(got.tokens); + defer gpa.free(got.rows); + try std.testing.expectEqual(drafts, got.drafted > 0); + try std.testing.expectEqualSlices(u32, plain.tokens, got.tokens); + for (plain.rows, got.rows) |p, d| { + try std.testing.expectEqual(p.token, d.token); + try std.testing.expectEqual(p.logprob, d.logprob); + try std.testing.expectEqualSlices(u32, p.ids[0..p.count], d.ids[0..d.count]); + try std.testing.expectEqualSlices(f32, p.logprobs[0..p.count], d.logprobs[0..d.count]); + } + } + } +} diff --git a/zig/src/families/ricursive/fixtures/dflash2_config.json b/zig/src/families/ricursive/fixtures/dflash2_config.json new file mode 100644 index 00000000000..f712f33ad91 --- /dev/null +++ b/zig/src/families/ricursive/fixtures/dflash2_config.json @@ -0,0 +1,65 @@ +{ + "architectures": [ + "DFlash2DraftModel" + ], + "attention_bias": false, + "attention_dropout": 0.0, + "bos_token_id": 100257, + "dflash_config": { + "block_size": 16, + "conv_group_size": 16, + "conv_kernel_size": 4, + "mask_token_id": 100278, + "selector_rank": 256, + "selector_top_k": 32, + "target_layer_ids": [ + 1, + 20, + 39, + 58, + 77 + ] + }, + "draft_vocab_size": 100352, + "dtype": "bfloat16", + "eos_token_id": [ + 100265, + 100257 + ], + "head_dim": 128, + "hidden_act": "silu", + "hidden_size": 5120, + "initializer_range": 0.02, + "intermediate_size": 40960, + "is_causal": false, + "layer_types": [ + "sliding_attention", + "sliding_attention", + "sliding_attention", + "sliding_attention", + "full_attention" + ], + "max_position_embeddings": 131072, + "max_window_layers": 5, + "model_type": "qwen3", + "no_rope_layers": [ + 4 + ], + "num_attention_heads": 80, + "num_hidden_layers": 5, + "num_key_value_heads": 8, + "num_target_layers": 80, + "pad_token_id": 100277, + "rms_norm_eps": 1e-06, + "rope_parameters": { + "rope_theta": 10000.0, + "rope_type": "default" + }, + "rope_theta": 10000.0, + "sliding_window": 4096, + "tie_word_embeddings": false, + "transformers_version": "5.12.1", + "use_cache": true, + "use_sliding_window": true, + "vocab_size": 100352 +} diff --git a/zig/src/families/ricursive/forward.zig b/zig/src/families/ricursive/forward.zig index dc77e1370af..c3c8fedaa6f 100644 --- a/zig/src/families/ricursive/forward.zig +++ b/zig/src/families/ricursive/forward.zig @@ -23,16 +23,16 @@ const VArgs = extern struct { rows: u32, pos: u32, heads: u32, groups: u32, bloc const every_key = std.math.maxInt(i32); pub const B = struct { buf: mtl.Buffer = undefined, off: usize = 0, args: bool = false }; -fn b(buf: mtl.Buffer) B { +pub fn b(buf: mtl.Buffer) B { return .{ .buf = buf }; } -fn bo(buf: mtl.Buffer, off: usize) B { +pub fn bo(buf: mtl.Buffer, off: usize) B { return .{ .buf = buf, .off = off }; } -fn t(x: wts.Tensor) B { +pub fn t(x: wts.Tensor) B { return .{ .buf = x.buffer, .off = x.offset }; } -const A = B{ .args = true }; +pub const A = B{ .args = true }; const Enc = struct { e: mtl.ComputeEncoder, @@ -49,31 +49,8 @@ const Enc = struct { if (groups) x.e.dispatchGroups(g3, t3) else x.e.dispatchThreads(g3, t3); } - /// y [rows, d.n] (rows `ldy` apart, at byte `out_off`) = x W^T: the GEMM a prompt chunk, the row kernels a window. fn dense(x: Enc, d: wts.Dense, in: B, out: mtl.Buffer, out_off: usize, n_rows: usize, ldy: usize) void { - const e = x.e; - if (n_rows <= st.batch_rows) { - // the variant holding the rows in registers: 1, 2, 4, 8, 16 or 32 - const v: @import("model.zig").Llama = if (n_rows <= 1) .matvec_1 else if (n_rows <= 2) .matvec_2 else if (n_rows <= 4) .matvec_4 else if (n_rows <= 8) .matvec_8 else if (n_rows <= 16) .matvec_16 else .matvec_32; - e.setPipeline(x.m.ll(v)); - e.setBuffer(in.buf, in.off, 0); - e.setBuffer(d.buf, d.off, 1); - e.setValue(MArgs{ .rows = @intCast(n_rows), .n = @intCast(d.n), .k = @intCast(d.k), .ldy = @intCast(ldy) }, 2); - e.setBuffer(out, out_off, 3); - e.dispatchGroups(mtl.Size.of((d.n + 7) / 8, 1, 1), mtl.Size.of(256, 1, 1)); - return; - } - const tn = (d.n + 127) / 128; - const tm = (n_rows + 63) / 64; - e.setPipeline(x.m.gemm[@intFromBool(n_rows % 64 == 0)][@intFromBool(d.n % 128 == 0)]); - e.setBuffer(in.buf, in.off, 0); - e.setBuffer(d.buf, d.off, 1); - var p: [16]i32 = @splat(0); - const vals = [_]usize{ n_rows, d.n, d.k, d.k, d.k, ldy, tn, tm, 2, d.k / 256, 0, 0, 0, 0, 0 }; - for (vals, 0..) |v, i| p[i] = @intCast(v); - e.setBytes(std.mem.asBytes(&p), 2); - e.setBuffer(out, out_off, 3); - e.dispatchThreads(mtl.Size.of(@as(usize, tn << 2) * 32, (tm + 3) / 4 * 4, 2), mtl.Size.of(32, 4, 2)); + denseRows(x.e, x.m, d, in, out, out_off, n_rows, ldy); } /// An MLP projection: bf16, or NVFP4 rows; a prompt chunk dequantizes exactly, then the GEMM applies the global. @@ -127,8 +104,34 @@ const Enc = struct { } }; -/// All rows' logits or the last's; ids on the GPU; the last row drawn on the GPU; committed unwaited into `flight`. -pub const Out = struct { all: bool = false, timing: ?*Timing = null, ids: ?B = null, draw: ?Draw = null, flight: ?*mtl.CommandBuffer = null }; +/// y [rows, d.n] (rows `ldy` apart, at byte `out_off`) = x W^T: the GEMM past 32 rows, the row kernels to 32. +pub fn denseRows(e: mtl.ComputeEncoder, m: *const Model, d: wts.Dense, in: B, out: mtl.Buffer, out_off: usize, n_rows: usize, ldy: usize) void { + if (n_rows <= st.batch_rows) { + // the variant holding the rows in registers: 1, 2, 4, 8, 16 or 32 + const v: @import("model.zig").Llama = if (n_rows <= 1) .matvec_1 else if (n_rows <= 2) .matvec_2 else if (n_rows <= 4) .matvec_4 else if (n_rows <= 8) .matvec_8 else if (n_rows <= 16) .matvec_16 else .matvec_32; + e.setPipeline(m.ll(v)); + e.setBuffer(in.buf, in.off, 0); + e.setBuffer(d.buf, d.off, 1); + e.setValue(MArgs{ .rows = @intCast(n_rows), .n = @intCast(d.n), .k = @intCast(d.k), .ldy = @intCast(ldy) }, 2); + e.setBuffer(out, out_off, 3); + e.dispatchGroups(mtl.Size.of((d.n + 7) / 8, 1, 1), mtl.Size.of(256, 1, 1)); + return; + } + const tn = (d.n + 127) / 128; + const tm = (n_rows + 63) / 64; + e.setPipeline(m.gemm[@intFromBool(n_rows % 64 == 0)][@intFromBool(d.n % 128 == 0)]); + e.setBuffer(in.buf, in.off, 0); + e.setBuffer(d.buf, d.off, 1); + var p: [16]i32 = @splat(0); + const vals = [_]usize{ n_rows, d.n, d.k, d.k, d.k, ldy, tn, tm, 2, d.k / 256, 0, 0, 0, 0, 0 }; + for (vals, 0..) |v, i| p[i] = @intCast(v); + e.setBytes(std.mem.asBytes(&p), 2); + e.setBuffer(out, out_off, 3); + e.dispatchThreads(mtl.Size.of(@as(usize, tn << 2) * 32, (tm + 3) / 4 * 4, 2), mtl.Size.of(32, 4, 2)); +} + +/// All rows' logits or the last's, ids or draws on the GPU, committed into `flight`; `taps`: a drafter's features. +pub const Out = struct { all: bool = false, timing: ?*Timing = null, ids: ?B = null, draw: ?Draw = null, flight: ?*mtl.CommandBuffer = null, taps: ?B = null }; /// A GPU draw of the last row's logits: argmax, or the keyed sampler at `position` (lanes' gpu_rule and gpu_full). pub const Draw = struct { @@ -174,7 +177,14 @@ pub fn runShared(m: *const Model, s: *st.Scratch, segments: []const Segment, ids const ea = Args{ .rows = @intCast(n), .width = @intCast(h), .scale = c.embed_scale }; x.glue(m.pipe(.embed), ea, &.{ out.ids orelse b(s.ids), bo(W.embed.buf, W.embed.off), A, b(s.resid), b(s.v0) }, .{ h, n, 1 }, .{ 256, 1, 1 }, false); x.addNorm(n, null, W.layers[0].input_norm, W.layers[0].attn.blend); - for (W.layers, 0..) |l, i| try layer(x, segments, l, i, n, if (i + 1 < W.layers.len) W.layers[i + 1] else null); + for (W.layers, 0..) |l, i| { + try layer(x, segments, l, i, n, if (i + 1 < W.layers.len) W.layers[i + 1] else null); + // a tapped layer's residual before the final norm: z-lab's `hidden_states[layer + 1]` (extract_context_feature) + if (out.taps) |tb| if (m.tap_at[i] >= 0) { + const ta = [4]u32{ @intCast(n), @intCast(h), m.taps, @intCast(m.tap_at[i]) }; + x.glue(m.tap.?, ta, &.{ b(s.resid), A, tb }, .{ h, n, 1 }, .{ 256, 1, 1 }, false); + }; + } if (out.all) { x.dense(W.head, b(s.x), s.logits_all, 0, n, c.vocab); } else { diff --git a/zig/src/families/ricursive/model.zig b/zig/src/families/ricursive/model.zig index 4109af6e93a..a28fe2e542d 100644 --- a/zig/src/families/ricursive/model.zig +++ b/zig/src/families/ricursive/model.zig @@ -37,6 +37,10 @@ pub const Model = struct { fp4: ?Fp4 = null, /// RoPE's inverse frequencies: fp32 [head_dim / 2]. inv: mtl.Buffer, + /// A drafter's taps: each layer's place in its features (-1 untapped), their count, and the copy (dflash2.metal). + tap_at: [cfg.max_layers]i8 = @splat(-1), + taps: u32 = 0, + tap: ?mtl.Pipeline = null, pub fn load(gpa: std.mem.Allocator, io: std.Io, dir: []const u8) !*Model { const pool = mtl.objc.Pool.push(); @@ -44,6 +48,9 @@ pub const Model = struct { const m = try gpa.create(Model); errdefer gpa.destroy(m); m.gpa = gpa; + m.tap_at = @splat(-1); + m.taps = 0; + m.tap = null; m.config = try cfg.Config.read(gpa, io, dir); m.device = try mtl.Device.init(); errdefer m.device.deinit(); @@ -107,7 +114,25 @@ pub const Model = struct { return m.llama[@backingInt(g)]; } + /// The drafter's layers, in the order its features concatenate them; the copy compiled once. + pub fn setTaps(m: *Model, layers: []const u32) !void { + if (layers.len == 0 or layers.len > 16) return error.UnsupportedRicursiveTaps; + var at: [cfg.max_layers]i8 = @splat(-1); + for (layers, 0..) |l, i| { + if (l >= m.config.layers or at[l] >= 0) return error.UnsupportedRicursiveTaps; + at[l] = @intCast(i); + } + if (m.tap == null) { + const lib = try mtl.Library.fromSource(m.device, ks.ricursive_dflash2, .{ .language = mtl.CompileOptions.mlx().language, .math_functions = .precise }); + defer lib.deinit(); + m.tap = try mtl.Pipeline.init(m.device, lib, "rc_tap", false); + } + m.tap_at = at; + m.taps = @intCast(layers.len); + } + pub fn deinit(m: *Model) void { + if (m.tap) |p| p.deinit(); m.inv.deinit(); if (m.fp4) |*f| f.deinit(); for (m.gemm) |row| for (row) |p| p.deinit(); diff --git a/zig/src/families/ricursive/ricursive.zig b/zig/src/families/ricursive/ricursive.zig index 2f00b7e37a6..e1de5b3cffd 100644 --- a/zig/src/families/ricursive/ricursive.zig +++ b/zig/src/families/ricursive/ricursive.zig @@ -8,6 +8,8 @@ pub const backend = @import("backend.zig"); pub const budget = @import("budget.zig"); pub const snapshot = @import("snapshot.zig"); pub const contracts = @import("contracts.zig"); +pub const dflash2 = @import("dflash2.zig"); +pub const dflash2_config = @import("dflash2_config.zig"); test { _ = config; @@ -16,4 +18,7 @@ test { _ = budget; _ = snapshot; _ = contracts; + _ = dflash2_config; + _ = @import("dflash2_rows_test.zig"); + _ = @import("dflash2_charge_test.zig"); } diff --git a/zig/src/families/ricursive/state.zig b/zig/src/families/ricursive/state.zig index 736dbc93c30..6657d0a0955 100644 --- a/zig/src/families/ricursive/state.zig +++ b/zig/src/families/ricursive/state.zig @@ -58,6 +58,10 @@ pub const Cache = struct { capacity: usize, len: usize = 0, follow: ?mtl.ResidencySet.Follow = null, + /// The latest tapped rows a drafter may absorb: positions [start, start + rows), in a scratch's or last_tap. + tap: Tap = .{}, + last_tap: ?mtl.Buffer = null, // the prompt's last row's taps, kept for the first draft + charge: u64 = 0, // the ledger's bytes for the stream (Metal.charge), given back as taken pub fn setResident(self: *Cache, hook: ?mtl.ResidencySet.Follow) void { if (self.follow) |f| mtl.resident.fields.apply(self, f, false); @@ -91,9 +95,12 @@ pub const Cache = struct { self.setResident(null); self.kv.deinit(); self.logits.deinit(); + if (self.last_tap) |x| x.deinit(); } }; +pub const Tap = struct { buf: ?mtl.Buffer = null, off: usize = 0, start: usize = 0, rows: usize = 0 }; + pub const fields = [_][]const u8{ "ids", "resid", "v0", "x", "vx", "q", "g", "qn", "att", "y", "gu", "act", "logits_all", "pm", "pl", "po", "wq" }; /// Bytes of each Scratch buffer for `rows` rows at once, in `fields` order. @@ -137,6 +144,7 @@ pub const Scratch = struct { pl: mtl.Buffer, po: mtl.Buffer, wq: mtl.Buffer, // a prompt chunk's NVFP4 projection as bf16 (its global left to the GEMM) + taps: ?mtl.Buffer = null, // with a drafter: every row's tapped residuals (bf16 [rows, taps, hidden]) rows: usize, /// Buffers for `rows` rows at once (batch_rows for decode, prompt_rows for prompt chunks). @@ -150,11 +158,13 @@ pub const Scratch = struct { made += 1; } s.rows = rows; + s.taps = null; return s; } pub fn deinit(s: *Scratch) void { inline for (fields) |f| @field(s, f).deinit(); + if (s.taps) |x| x.deinit(); } }; diff --git a/zig/src/families/ricursive/weights.zig b/zig/src/families/ricursive/weights.zig index 636acf6f3ba..2603195ffee 100644 --- a/zig/src/families/ricursive/weights.zig +++ b/zig/src/families/ricursive/weights.zig @@ -59,7 +59,7 @@ fn require(t: Tensor, dtype: @TypeOf(t.dtype), dims: []const usize) error{Unexpe } /// The bf16 tensor `prefix ++ suffix` of exactly `dims`. -fn get(c: *const ck.Checkpoint, prefix: []const u8, suffix: []const u8, dims: []const usize) !Tensor { +pub fn get(c: *const ck.Checkpoint, prefix: []const u8, suffix: []const u8, dims: []const usize) !Tensor { return getAs(c, prefix, suffix, .bf16, dims); } @@ -89,7 +89,7 @@ fn proj(c: *const ck.Checkpoint, f: *const cfg.Config, prefix: []const u8, compt } /// The release's bf16 [n, k] matrix in place: k whole 256s for the GEMM's steps, 8-byte aligned for the row kernel. -fn dense(c: *const ck.Checkpoint, prefix: []const u8, suffix: []const u8, n: usize, k: usize) !Dense { +pub fn dense(c: *const ck.Checkpoint, prefix: []const u8, suffix: []const u8, n: usize, k: usize) !Dense { const w = try get(c, prefix, suffix, &.{ n, k }); if (k % 256 != 0 or w.offset % 8 != 0) { std.log.err("ricursive: {s}{s} at byte {d}: the row kernels need 8-byte rows of whole 256s", .{ prefix, suffix, w.offset }); diff --git a/zig/src/native/metal.zig b/zig/src/native/metal.zig index c5e81f395fc..7ebb3010bb1 100644 --- a/zig/src/native/metal.zig +++ b/zig/src/native/metal.zig @@ -295,7 +295,7 @@ fn refusal(a: Allocator, o: api.Open, dense: bool) !?[]const u8 { if (o.prompt_int8) return prompt_int8_refusal; if (!learners.supports(t)) if (try o.slideRefusal(a, "Macs")) |why| return why; if (@import("qwen27_mtp.zig").refusal(o.mtp_drafts, o.mtp_confidence, o.drafter != null, std.mem.eql(u8, t, "qwen3_5") and dense)) |why| return why; - if (o.drafter != null and !dense and !isGemma4(t) and !std.mem.eql(u8, t, "llama") and !std.mem.eql(u8, t, "qwen3_5_moe") and !std.mem.eql(u8, t, "flint") and !std.mem.eql(u8, t, "glm5_next") and !std.mem.eql(u8, t, "inkling2_loop")) return "--drafter is supported for Qwen3.8-27B-class checkpoints (qwen3_5 with its own output head), Qwen3.5-MoE (qwen3_5_moe), GLM-5.3-Flash (glm5_next), Gemma 4 dense, Flint (DFlash2 on M5), Inkling 2 Mini (DSpark) and Llama (a smaller Llama on the same tokenizer)"; + if (o.drafter != null and !dense and !isGemma4(t) and !std.mem.eql(u8, t, "llama") and !std.mem.eql(u8, t, "qwen3_5_moe") and !std.mem.eql(u8, t, "flint") and !std.mem.eql(u8, t, "glm5_next") and !std.mem.eql(u8, t, "inkling2_loop") and !std.mem.eql(u8, t, "ricursive")) return "--drafter is supported for Qwen3.8-27B-class checkpoints (qwen3_5 with its own output head), Qwen3.5-MoE (qwen3_5_moe), GLM-5.3-Flash (glm5_next), Gemma 4 dense, Flint (DFlash2 on M5), Inkling 2 Mini (DSpark), Llama (a smaller Llama on the same tokenizer) and Ripple (its DFlash2 drafter)"; const one_mac: ?[]const u8 = if (std.mem.eql(u8, t, "nemotron_h")) "Nemotron" else if (std.mem.eql(u8, t, "nemotron_h_puzzle")) "Nemotron 3.5 Bolt" else if (std.mem.eql(u8, t, "lfm2_moe")) "LFM2.5-24B-A2B" else if (isGemma4(t)) "Gemma 4" else if (std.mem.eql(u8, t, "step5_vl")) "Step-5" else if (std.mem.eql(u8, t, "spark2_5")) "Spark-X2.6" else if (std.mem.eql(u8, t, "minimax_m3_vl")) "MiniMax-M3.1-Flash" else if (std.mem.eql(u8, t, "qwen3_5_moe")) "Qwen3.5-MoE" else if (std.mem.eql(u8, t, "llama")) "Llama" else if (std.mem.eql(u8, t, "flint")) "Flint" else if (std.mem.eql(u8, t, "unlimited-ocr")) "Unlimited-OCR-2" else if (std.mem.eql(u8, t, "ricursive")) "Ripple" else if (!std.mem.eql(u8, t, "qwen3_5")) null else if (dense) "Qwen3.8-27B" else "Qwen3.5-2B"; if (o.speed_up != null) if (one_mac) |name| return try std.fmt.allocPrint(a, "--speed-up joins two Macs for Flash Next, GLM-5.3-Flash and GLM-5.3 only: serve {s} without it", .{name}); if (o.recall and std.mem.eql(u8, t, "qwen4_exp")) return recall_refusal; diff --git a/zig/src/native/ricursive.zig b/zig/src/native/ricursive.zig index 4b95b112a7a..07c5a326f9c 100644 --- a/zig/src/native/ricursive.zig +++ b/zig/src/native/ricursive.zig @@ -12,6 +12,8 @@ const Host = struct { io: std.Io, model: *fr.Model, metal: *fr.backend.Metal, + draft: ?*fr.dflash2.Drafter = null, // --drafter: the publisher's DFlash2 drafter, reading the target's taps + wrap: ?lanes.drafted.Drafted = null, warm: mtl.keepalive.Target = undefined, // the residency set's, or the bare queue's, for the lane host's idle ticker resident: ?Resident = null, // weights and scratch kept wired between requests, when they fit the 70% limit config: lanes.Config, @@ -28,6 +30,8 @@ const Host = struct { h.core.deinit(); h.config.deinit(h.gpa); drop(h); + if (h.wrap) |*w| w.deinit(); + if (h.draft) |d| d.deinit(); h.metal.deinit(); h.model.deinit(); h.gpa.destroy(h); @@ -35,6 +39,11 @@ const Host = struct { }; pub fn open(a: std.mem.Allocator, gpa: std.mem.Allocator, io: std.Io, o: api.Open, problem: *[]const u8) !?api.Opened { + const drafted = o.drafts and o.drafter != null; + const lanes_n: u32 = if (drafted) fr.dflash2_config.streams(o.lanes, o.lanes_fixed) orelse { + problem.* = try std.fmt.allocPrint(a, "--drafter with --parallel {d}: Ripple's DFlash2 drafter is served with up to {d} streams; each stream drafts in its own pass, so past that it ties plain decode on most replies and then falls behind it; lower --parallel, or serve without --drafter", .{ o.lanes, fr.dflash2_config.max_streams }); + return null; + } else o.lanes; const pool = mtl.objc.Pool.push(); defer pool.pop(); const model = fr.Model.load(gpa, io, o.dir) catch |err| { @@ -47,45 +56,66 @@ pub fn open(a: std.mem.Allocator, gpa: std.mem.Allocator, io: std.Io, o: api.Ope return null; }; errdefer model.deinit(); + const draft = try loadDrafter(a, gpa, io, o, model, problem) orelse if (drafted) { + model.deinit(); + return null; + } else null; + errdefer if (draft) |d| d.deinit(); var ram: u64 = 0; var len: usize = @sizeOf(u64); if (std.c.sysctlbyname("hw.memsize", &ram, &len, null, 0) != 0) ram = 0; // the decode window's and the prompt chunk's buffers - const scratch: u64 = fr.state.scratchBytes(&model.config, fr.state.batch_rows) + fr.state.scratchBytes(&model.config, fr.state.prompt_rows); + var scratch: u64 = fr.state.scratchBytes(&model.config, fr.state.batch_rows) + fr.state.scratchBytes(&model.config, fr.state.prompt_rows); + // a drafter's weights and scratch, and the target's tapped rows for it + if (draft) |d| scratch += d.checkpoint.residentBytes() + fr.dflash2.Drafter.fixedBytes(&d.config) + (fr.state.batch_rows + fr.state.prompt_rows) * fr.dflash2_config.max_taps * model.config.hidden * 2; const budget = try fr.budget.caches(ram, model.device.maxWorkingSet(), null, model.checkpoint.residentBytes() + scratch); const most: usize = @min(model.config.context, fr.state.max_capacity); - const fits = fr.budget.longest(&model.config, budget, most); + // with a drafter, the first stream's ring is held beside its caches: the window fits both + const lane_bytes: u64 = if (draft) |d| fr.dflash2.Drafter.laneBytes(&d.config) else 0; + const fits = fr.budget.longestDrafted(&model.config, budget, lane_bytes, most); if (o.context) |asked| if (asked > fr.config.max_context) { problem.* = try std.fmt.allocPrint(a, "--context {d}: the native Ripple engine is checked to {d} tokens; longer contexts are refused until a run at that length qualifies them", .{ asked, fr.config.max_context }); + if (draft) |d| d.deinit(); model.deinit(); return null; }; const window: i64 = o.context orelse @intCast(@min(fits, fr.config.max_context)); if (window < 1 or window > fits) { + const beside: []const u8 = if (draft != null) " and a stream's drafter ring" else ""; problem.* = if (o.context) |asked| - try std.fmt.allocPrint(a, "--context {d}: this Mac's Ripple caches fit {d} tokens beside the weights under its load limit (75% of RAM)", .{ asked, fits }) + try std.fmt.allocPrint(a, "--context {d}: this Mac's Ripple caches fit {d} tokens beside the weights{s} under its load limit (75% of RAM)", .{ asked, fits, beside }) else - try a.dupe(u8, "this Mac's load limit (75% of RAM) leaves no room for a Ripple stream's caches beside the weights"); + try std.fmt.allocPrint(a, "this Mac's load limit (75% of RAM) leaves no room for a Ripple stream's caches beside the weights{s}", .{beside}); + if (draft) |d| d.deinit(); model.deinit(); // after the message, so a failed allocation leaves the model to the errdefer return null; } std.log.info("ricursive: {d:.1} GiB for caches, context up to {d} tokens ({d:.2} GiB a full stream)", .{ @as(f64, @floatFromInt(budget)) / (1 << 30), window, @as(f64, @floatFromInt(fr.state.cacheBytes(&model.config, @intCast(window + 1)))) / (1 << 30) }); - const streams: u32 = @max(o.lanes, 1); + const streams: u32 = @max(lanes_n, 1); const h = try gpa.create(Host); errdefer gpa.destroy(h); h.gpa = gpa; h.io = io; h.model = model; h.resident = null; - h.metal = try fr.backend.Metal.init(gpa, model, .{ .capacity = @intCast(window), .streams = streams, .budget = budget }); + h.draft = null; + h.wrap = null; + h.metal = try fr.backend.Metal.init(gpa, model, .{ .capacity = @intCast(window), .streams = streams, .budget = budget, .drafts = draft != null, .drafter_bytes = lane_bytes }); errdefer h.metal.deinit(); try h.metal.warm(); - h.config = try lanes.Config.init(gpa, h.metal.facts(), fr.state.window_rows, fr.state.window_rows - 1); + if (draft) |d| { + try h.metal.measure(); // the depth rule prices drafts against the window forward's cost by rows + h.wrap = try fr.dflash2_config.wrap(gpa, h.metal.backend(), d.drafter()); + h.draft = d; + } + errdefer if (h.wrap) |*w| w.deinit(); + const facts = if (h.wrap) |*w| w.facts(h.metal.facts()) else h.metal.facts(); + h.config = try lanes.Config.init(gpa, facts, fr.state.window_rows, fr.state.window_rows - 1); errdefer h.config.deinit(gpa); h.clock = .{ .io = io }; - h.core = lanes.Engine.init(gpa, &h.config, h.metal.backend(), h.clock.clock()); + h.core = lanes.Engine.init(gpa, &h.config, if (h.wrap) |*w| w.backend() else h.metal.backend(), h.clock.clock()); errdefer h.core.deinit(); - h.host = api.LaneHost.init(gpa, io, &h.core, .{ .lanes = o.lanes, .context_window = @intCast(window), .prefill_step = fr.state.prompt_rows, .structures = true, .logprobs = true }); + h.host = api.LaneHost.init(gpa, io, &h.core, .{ .lanes = lanes_n, .context_window = @intCast(window), .prefill_step = fr.state.prompt_rows, .draft_sources = .{ .drafter = if (draft != null) .{ .kind = "DFlash2 drafter", .name = o.drafter_name orelse o.drafter.? } else null }, .structures = true, .logprobs = true }); h.host.info_.reasoning_optional = true; // Ripple writes `` itself when it thinks, and answers bare otherwise h.host.info_.thinking_budget = false; // its think markers are spelled, not one token each: no close can be forced h.cache = null; @@ -116,12 +146,17 @@ fn hold(h: *Host) !void { try list.append(h.gpa, m.inv); try mtl.resident.fields.append(h.gpa, &list, &h.metal.scratch); try mtl.resident.fields.append(h.gpa, &list, &h.metal.prompt); + if (h.draft) |d| try d.buffers(h.gpa, &list); h.resident = try Resident.hold(h.gpa, h.io, m.device, m.queue, list.items, "ricursive"); - if (h.resident) |*r| h.metal.setResident(r.follow()); + if (h.resident) |*r| { + h.metal.setResident(r.follow()); + if (h.draft) |d| d.setResident(r.follow()); + } h.warm = if (h.resident) |*r| r.target() else .{ .queue = m.queue }; } fn drop(h: *Host) void { + if (h.draft) |d| d.setResident(null); h.metal.setResident(null); if (h.resident) |*r| r.deinit(); h.resident = null; @@ -141,3 +176,23 @@ fn fitCache(ctx: *anyopaque, bytes: u64, restoring: ?*anyopaque, prompt: []const }; _ = store.giveBack(restoring, prompt, Left{ .s = store }); } + +/// --drafter's DFlash2 drafter for this target, loaded and warmed; null with `problem` set when it is refused. +fn loadDrafter(a: std.mem.Allocator, gpa: std.mem.Allocator, io: std.Io, o: api.Open, model: *fr.Model, problem: *[]const u8) !?*fr.dflash2.Drafter { + if (!o.drafts) return null; + const dir = o.drafter orelse return null; + const c = fr.dflash2.Drafter.readConfig(gpa, io, dir, &model.config) catch |err| { + problem.* = switch (err) { + error.NotRippleDFlash2 => try std.fmt.allocPrint(a, "--drafter: {s} is not a DFlash2 drafter (DFlash2DraftModel); Ripple takes ricursiveAI/Ripple-65B-Preview-DFlash2", .{dir}), + error.UnqualifiedRippleDFlash2 => try std.fmt.allocPrint(a, "--drafter: {s} is not the drafter checked against this Ripple (ricursiveAI/Ripple-65B-Preview-DFlash2's geometry and taps)", .{dir}), + else => try std.fmt.allocPrint(a, "--drafter: {s}'s config.json cannot be read ({s})", .{ dir, @errorName(err) }), + }; + return null; + }; + const d = fr.dflash2.Drafter.init(gpa, io, model, dir, c) catch |err| { + problem.* = try std.fmt.allocPrint(a, "--drafter: the DFlash2 drafter in {s} cannot load ({s}); it is served bf16, as published", .{ dir, @errorName(err) }); + return null; + }; + std.log.info("ricursive drafter: {s}: DFlash2, {d} layers, bf16, {d:.2} GiB of weights, {d}-row blocks over layers {any}", .{ dir, c.layers, @as(f64, @floatFromInt(d.checkpoint.residentBytes())) / (1 << 30), c.block, c.taps }); + return d; +} diff --git a/zig/tests/contract/metal_ricursive_all.zig b/zig/tests/contract/metal_ricursive_all.zig index 41c47bbde3f..8f8b96758f9 100644 --- a/zig/tests/contract/metal_ricursive_all.zig +++ b/zig/tests/contract/metal_ricursive_all.zig @@ -1,4 +1,4 @@ -//! Ripple's registrations as one set: its kernels (NVFP4 too) and controls, llama's, the draw; and the roll call. +//! Ripple's registrations as one set: its kernels (NVFP4, DFlash2 too) and controls, llama's, the draw; the roll call. const std = @import("std"); const mtl = @import("metal"); const contract = @import("contract"); @@ -10,6 +10,7 @@ const sample = @import("metal_ricursive_sample.zig"); const fp4 = @import("metal_ricursive_fp4.zig"); const fp4_gemm = @import("metal_ricursive_fp4_gemm.zig"); const controls = @import("metal_ricursive_controls.zig"); +const dflash2 = @import("metal_ricursive_dflash2.zig"); const llama = @import("metal_llama.zig"); const dense = @import("metal_llama_dense.zig"); const llama_attention = @import("metal_llama_attention.zig"); @@ -18,9 +19,10 @@ const g = contract.gates; const family = rc.family; const R = rc.R; -/// The label Ripple's registrations of llama's pipelines carry, and those at o_proj's reduction. +/// The label Ripple's registrations of llama's pipelines carry, those at o_proj's reduction, and its DFlash2 drafter's. const label = "ricursive llama"; const o_label = label ++ " o"; +const draft_label = label ++ " dflash2"; const matvec_rows = [_]u32{ 1, 2, 4, 8, 16, 32 }; fn wanted(only: ?[]const u8, name: []const u8) bool { @@ -56,6 +58,21 @@ fn oGemmShapes(am: bool, an: bool) [2]c.Shape { const merge_shapes = [_]c.Shape{ .{ .rows = 16, .n = R.heads, .k = 544 }, .{ .rows = 16, .n = R.heads, .k = 9 } }; const argmax_shapes = [_]c.Shape{.{ .rows = 1, .n = 1, .k = R.vocab }}; +/// The drafter's one new reduction, fc's 25,600 (an absorb to 32 rows); its o_proj's 10,240 is the target's. +fn draftMatvecShapes(per: u32) [2]c.Shape { + const k = R.hidden * dflash2.D.taps; + return .{ .{ .rows = per, .n = 1024, .k = k }, .{ .rows = per, .n = R.hidden, .k = k } }; +} + +/// fc's GEMM over a 2,048-row absorb (its 64-row tiles repeat) and a ragged one; its 5,120 outputs are whole tiles. +fn draftGemmShapes(am: bool) [2]c.Shape { + const k = R.hidden * dflash2.D.taps; + return if (am) .{ .{ .rows = 64, .n = 1024, .k = k }, .{ .rows = 128, .n = 1024, .k = k } } else .{ .{ .rows = 33, .n = 1024, .k = k }, .{ .rows = 100, .n = 1024, .k = k } }; +} + +/// The drafter's merge over a sliding layer's most blocks (34) and the global layer's (130). +const draft_merge_shapes = [_]c.Shape{ .{ .rows = 16, .n = R.heads, .k = 34 }, .{ .rows = 16, .n = R.heads, .k = 130 } }; + /// The probes made for a run, freed together. pub const Set = struct { point: std.ArrayList(*rc.Pointwise) = .empty, @@ -71,9 +88,12 @@ pub const Set = struct { fp4_matvec: std.ArrayList(*fp4.Matvec) = .empty, fp4_dequant: std.ArrayList(*fp4.Dequant) = .empty, fp4_gemm: std.ArrayList(*fp4_gemm.Gemm) = .empty, + dflash2: dflash2.Suite = .{}, pub fn deinit(s: *Set, a: std.mem.Allocator) void { + s.dflash2.deinit(a); inline for (@typeInfo(Set).@"struct".field_names) |f| { + if (comptime std.mem.eql(u8, f, "dflash2")) continue; const list = &@field(s, f); for (list.items) |p| { p.deinit(); @@ -166,6 +186,8 @@ pub const Set = struct { if (wanted(only, sample.spec().name)) try keep(a, &s.sample, try sample.Sample.init(a, device, queue), kernels); try s.collectFp4(a, device, queue, tensor, kernels, only, &functions); try s.collectO(a, device, queue, tensor, kernels, only); + try s.collectDraft(a, device, queue, tensor, kernels, only); + try s.dflash2.collect(.{ .a = a, .device = device, .queue = queue, .kernels = kernels, .only = only }, &functions); try family.requireComplete(functions.items); try s.plant(a, device, queue, tensor, kernels, only); } @@ -213,10 +235,44 @@ pub const Set = struct { } } + /// llama's pipelines at the shapes only the DFlash2 drafter runs them at (already on the roll call above). + fn collectDraft(s: *Set, a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, tensor: bool, kernels: *std.ArrayList(g.Kernel), only: ?[]const u8) !void { + var buf: [64]u8 = undefined; + for (matvec_rows, family.llama_names[0..matvec_rows.len]) |per, fun| { + if (!wanted(only, try std.fmt.bufPrint(&buf, "{s} {s}", .{ draft_label, fun }))) continue; + var m = try dense.Matvec.init(a, device, queue, per, .none); + m.retarget(draft_label, draftMatvecShapes(per)) catch |err| { + m.deinit(); + return err; + }; + try keep(a, &s.matvec, m, kernels); + } + // fc's 5,120 outputs are whole 128-column tiles: only the forms with `an` run + for ([_]bool{ false, true }) |am| { + if (!tensor or !wanted(only, try std.fmt.bufPrint(&buf, "{s} ll_gemm_{d}1", .{ draft_label, @intFromBool(am) }))) continue; + var m = try dense.Gemm.init(a, device, queue, am, true, .none); + m.retarget(draft_label, draftGemmShapes(am)) catch |err| { + m.deinit(); + return err; + }; + try keep(a, &s.gemm, m, kernels); + } + if (wanted(only, draft_label ++ " ll_merge_vec")) { + var m = try llama_attention.MergeVec.init(a, device, queue, .none); + m.name = draft_label ++ " ll_merge_vec"; + m.served = &draft_merge_shapes; + try keep(a, &s.merge, m, kernels); + } + } + /// Each control: its kernel built with one planted fault, registered beside the kernels. fn plant(s: *Set, a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, tensor: bool, kernels: *std.ArrayList(g.Kernel), only: ?[]const u8) !void { for (std.enums.values(controls.Mutation)) |m| { if (m == .none or !wanted(only, m.name())) continue; + if (m.dflash2()) { + try s.dflash2.plant(.{ .a = a, .device = device, .queue = queue, .kernels = kernels, .only = only }, m); + continue; + } switch (m) { .embed_own_row => try keep(a, &s.point, try rc.Pointwise.init(a, device, queue, .embed, m), kernels), .gate_early_round => try keep(a, &s.point, try rc.Pointwise.init(a, device, queue, .gate, m), kernels), @@ -234,14 +290,15 @@ pub const Set = struct { .fp4_gemm_no_global => if (tensor) { try keep(a, &s.fp4_gemm, try fp4_gemm.Gemm.init(a, device, queue, false, false, m), kernels); }, - .none => unreachable, + .none, .df_tap_next_slot, .df_norm_half_mean, .df_norm16_no_weight, .df_embed_own_row, .df_prep_ropes_nope, .df_conv_three_taps, .df_silu_no_negative, .df_vec_no_floor, .df_topk_ascending, .df_walk_from_pending => unreachable, } } } }; -/// Gate 5's texts for `ricursive ` launches: the glue, the draw, or the attention (nax.h inlined; fragments pre-M5). +/// Gate 5's texts for `ricursive ` launches: the glue, DFlash2's, the draw, or the attention (nax.h inlined pre-M5). pub fn limitsText(a: std.mem.Allocator, device: mtl.Device, name: []const u8) !struct { here: []const u8, pre_m5: []const u8 } { + if (std.mem.startsWith(u8, name, "ricursive dflash2 ")) return .{ .here = sources.ricursive_dflash2, .pre_m5 = sources.ricursive_dflash2 }; if (std.mem.indexOf(u8, name, " attention ") != null) { const head = try family.attentionHeader(a); const body = try std.mem.replaceOwned(u8, a, sources.ricursive_attention_nax, "#include \"../nax.h\"", sources.nax); diff --git a/zig/tests/contract/metal_ricursive_controls.zig b/zig/tests/contract/metal_ricursive_controls.zig index 5061837c076..074b80a3621 100644 --- a/zig/tests/contract/metal_ricursive_controls.zig +++ b/zig/tests/contract/metal_ricursive_controls.zig @@ -3,6 +3,7 @@ const std = @import("std"); const mtl = @import("metal"); const contract = @import("contract"); const tf = @import("tensorfold"); +const ks = @import("kernel_sources"); const family = tf.ricursive.contracts; pub const Mutation = enum { @@ -22,6 +23,21 @@ pub const Mutation = enum { fp4_global_late, fp4_dequant_unscaled, fp4_gemm_no_global, + df_tap_next_slot, + df_norm_half_mean, + df_norm16_no_weight, + df_embed_own_row, + df_prep_ropes_nope, + df_conv_three_taps, + df_silu_no_negative, + df_vec_no_floor, + df_topk_ascending, + df_walk_from_pending, + + /// A control of the DFlash2 drafter's kernels (dflash2.metal), planted by metal_ricursive_dflash2.zig. + pub fn dflash2(m: Mutation) bool { + return @backingInt(m) >= @backingInt(Mutation.df_tap_next_slot); + } pub fn name(m: Mutation) []const u8 { return switch (m) { @@ -41,6 +57,16 @@ pub const Mutation = enum { .fp4_global_late => "control: metal ricursive fp4 matvec, the global applied after the sum rounds to bf16", .fp4_dequant_unscaled => "control: metal ricursive fp4 dequant, a block's values left without its scale", .fp4_gemm_no_global => "control: metal ricursive fp4 gemm, the sums never take the global", + .df_tap_next_slot => "control: metal ricursive dflash2 tap, the residual lands in the next tap's slot", + .df_norm_half_mean => "control: metal ricursive dflash2 norm, the mean of squares is halved", + .df_norm16_no_weight => "control: metal ricursive dflash2 norm16, the weight is never applied", + .df_embed_own_row => "control: metal ricursive dflash2 embed, row r reads table row r, not row ids[r]", + .df_prep_ropes_nope => "control: metal ricursive dflash2 prep, the NoPE layer's q and k are rotated too", + .df_conv_three_taps => "control: metal ricursive dflash2 conv, the fourth tap is dropped", + .df_silu_no_negative => "control: metal ricursive dflash2 silu, a negative gate takes its magnitude's sigmoid", + .df_vec_no_floor => "control: metal ricursive dflash2 vec, each row also sees the keys below the floor", + .df_topk_ascending => "control: metal ricursive dflash2 topk, the sort runs ascending", + .df_walk_from_pending => "control: metal ricursive dflash2 walk, every slot scores after the pending token", }; } @@ -69,6 +95,16 @@ pub const Mutation = enum { .fp4_global_late => .{ .from = "bfloat(sum * a.global)", .to = "bfloat(float(bfloat(sum)) * a.global)" }, .fp4_dequant_unscaled => .{ .from = "D[at * 4 + c] = bfloat4(w[c]);", .to = "D[at * 4 + c] = bfloat4(w[c] / rc_e4m3(S[at]));" }, .fp4_gemm_no_global => .{ .from = "acc[i][j] *= global;", .to = "acc[i][j] *= 1.0f;" }, + .df_tap_next_slot => .{ .from = "F[((size_t)p.y * a.taps + a.at) * a.width + p.x]", .to = "F[((size_t)p.y * a.taps + a.at + 1) * a.width + p.x]" }, + .df_norm_half_mean => .{ .from = "precise::rsqrt(total / float(width) + eps)", .to = "precise::rsqrt(total / float(2 * width) + eps)" }, + .df_norm16_no_weight => .{ .from = "bfloat(float(w[i]) * float(bfloat(float(x[i]) * inv)))", .to = "bfloat(float(bfloat(float(x[i]) * inv)))" }, + .df_embed_own_row => .{ .from = "float(E[(size_t)ids[p.y] * a.width + p.x])", .to = "float(E[(size_t)p.y * a.width + p.x])" }, + .df_prep_ropes_nope => .{ .from = "if (a.rope == 0) {", .to = "if (false) {" }, + .df_conv_three_taps => .{ .from = "for (uint t = 0; t < a.taps; ++t) {", .to = "for (uint t = 0; t + 1 < a.taps; ++t) {" }, + .df_silu_no_negative => .{ .from = "const float s = g < 0.0f ? e * y : y;", .to = "const float s = y;" }, + .df_vec_no_floor => .{ .from = "max(p + 1 > a.window ? p + 1 - a.window : 0, a.floor)", .to = "p + 1 > a.window ? p + 1 - a.window : 0" }, + .df_topk_ascending => .{ .from = "const bool down = (i & k) == 0;", .to = "const bool down = (i & k) != 0;" }, + .df_walk_from_pending => .{ .from = "prev = UI[e * a.top + bi];\n seq[1 + e] = prev;", .to = "seq[1 + e] = UI[e * a.top + bi];" }, }; } }; @@ -91,6 +127,13 @@ pub fn glueLibrary(device: mtl.Device, a: std.mem.Allocator, m: Mutation) !mtl.L return mtl.Library.fromSource(device, src, .{ .language = mtl.CompileOptions.mlx().language, .math_functions = .precise }); } +/// dflash2.metal as dflash2.zig and model.zig's setTaps compile it, with the control's edit. +pub fn dflash2Library(device: mtl.Device, a: std.mem.Allocator, m: Mutation) !mtl.Library { + const src = try apply(a, ks.ricursive_dflash2, m); + defer a.free(src); + return family.dflash2Library(device, src); +} + /// A spec's name and control for a probe built with `m`. pub fn mark(k: contract.gates.Kernel, m: Mutation) contract.gates.Kernel { var out = k; diff --git a/zig/tests/contract/metal_ricursive_dflash2.zig b/zig/tests/contract/metal_ricursive_dflash2.zig new file mode 100644 index 00000000000..0f53f9eb91b --- /dev/null +++ b/zig/tests/contract/metal_ricursive_dflash2.zig @@ -0,0 +1,534 @@ +//! Ripple's DFlash2 drafter kernels (dflash2.metal) under the contract: norms, embed and taps here, the rest in _*.zig. +const std = @import("std"); +const mtl = @import("metal"); +const tf = @import("tensorfold"); +const contract = @import("contract"); +const rig_ = @import("rig.zig"); +const controls = @import("metal_ricursive_controls.zig"); +const attn = @import("metal_ricursive_dflash2_attn.zig"); +const act = @import("metal_ricursive_dflash2_act.zig"); +const pick = @import("metal_ricursive_dflash2_pick.zig"); + +const c = contract.spec; +const g = contract.gates; +const family = tf.ricursive.contracts; +const dc = tf.ricursive.dflash2_config; +pub const Mutation = controls.Mutation; + +pub fn noSums(_: c.Shape) usize { + return 0; +} + +/// A value as fp32 then bf16 rounds it (to nearest even, twice). +pub fn bf(v: f64) f64 { + return c.fromBf16(c.toBf16(@floatCast(v))); +} + +/// A value as fp32 rounds it. +pub fn f32r(v: f64) f64 { + return @as(f32, @floatCast(v)); +} + +/// A value's spread through fp32 steps and bf16 rounding points. +pub const Range = struct { + lo: f64, + hi: f64, + pub fn point(v: f64) Range { + return .{ .lo = v, .hi = v }; + } + /// Each end moved by `ulps` fp32 roundings of its own size. + pub fn fp32(a: Range, ulps: f64) Range { + const u = ulps * c.unit(.f32); + return .{ .lo = a.lo - u * @abs(a.lo) - 0x1p-149, .hi = a.hi + u * @abs(a.hi) + 0x1p-149 }; + } + pub fn bf16(a: Range) Range { + return .{ .lo = bf(a.lo), .hi = bf(a.hi) }; + } + pub fn add(a: Range, b: Range) Range { + return .{ .lo = a.lo + b.lo, .hi = a.hi + b.hi }; + } + pub fn neg(a: Range) Range { + return .{ .lo = -a.hi, .hi = -a.lo }; + } + pub fn mul(a: Range, b: Range) Range { + const p = [4]f64{ a.lo * b.lo, a.lo * b.hi, a.hi * b.lo, a.hi * b.hi }; + return .{ .lo = @min(@min(p[0], p[1]), @min(p[2], p[3])), .hi = @max(@max(p[0], p[1]), @max(p[2], p[3])) }; + } +}; + +/// The allowance a range gives about `want`: the farther end. +pub fn spread(want: f64, r: Range) f64 { + return @max(@abs(want - r.lo), @abs(r.hi - want)); +} + +pub const nan = std.math.nan(f32); +pub const inf = std.math.inf(f32); + +/// Random bf16 bits in [lo, hi). +pub fn fillBf(rng: std.Random, out: []u16, lo: f32, hi: f32) void { + for (out) |*v| v.* = c.toBf16(lo + rng.float(f32) * (hi - lo)); +} + +pub const norm_why = "a bf16 output follows the sum of squares as ss^-1/2: a bf16 sum's error is a few output ulps"; + +/// The published drafter's geometry beside Ripple-65B (dflash2_config.zig's qualified check). +pub const D = struct { + pub const hidden: u32 = @intCast(family.ripple.hidden); + pub const vocab: u32 = @intCast(family.ripple.vocab); + pub const heads: u32 = 80; + pub const kv: u32 = 8; + pub const ffn: u32 = 40960; + pub const window: u32 = 4096; + pub const global: u32 = dc.global_window; + pub const block: u32 = 16; + pub const rank: u32 = 256; + pub const top: u32 = 32; + pub const group: u32 = 16; + pub const conv: u32 = 4; + pub const taps: u32 = dc.max_taps; + pub const theta: f32 = 10000; + pub const eps: f32 = 1e-6; + /// The longest context the engine serves (ricursive's --context cap): positions stay below it. + pub const context: u32 = 262144; + + /// A layer's ring: its span and a block past it, whole 128-key blocks (Config.ring). + pub fn ring(span: u32) u32 { + return std.mem.alignForward(u32, span + block, 128); + } +}; + +/// dflash2.metal's pipeline `name`, built with the control's edit. +pub fn pipeline(device: mtl.Device, a: std.mem.Allocator, name: [:0]const u8, m: Mutation) !mtl.Pipeline { + const lib = try controls.dflash2Library(device, a, m); + defer lib.deinit(); + return mtl.Pipeline.init(device, lib, name, false); +} + +/// What a probe's registration needs: the run's allocator, GPU, the kernel list and the --only filter. +pub const Ctx = struct { a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, kernels: *std.ArrayList(g.Kernel), only: ?[]const u8 }; + +/// The drafter's probes, freed together. +pub const Suite = struct { + owned: std.ArrayList(Owned) = .empty, + + const Owned = struct { ctx: *anyopaque, free: *const fn (*anyopaque, std.mem.Allocator) void }; + + /// T's probe for `v` built with `m`, kept and registered when its name holds `only`. + pub fn add(s: *Suite, x: Ctx, comptime T: type, v: T.Variant, m: Mutation) !void { + const name = if (m == .none) T.spec(v).name else m.name(); + if (x.only) |o| if (std.mem.indexOf(u8, name, o) == null) return; + const t = try x.a.create(T); + t.* = T.init(x.a, x.device, x.queue, v, m) catch |err| { + x.a.destroy(t); + return err; + }; + const free = struct { + fn f(p: *anyopaque, a: std.mem.Allocator) void { + const y: *T = @ptrCast(@alignCast(p)); + y.deinit(); + a.destroy(y); + } + }.f; + s.owned.append(x.a, .{ .ctx = t, .free = free }) catch |err| { + free(t, x.a); + return err; + }; + try x.kernels.append(x.a, t.kernel()); + } + + /// Every kernel's registrations; dflash2.metal's pipelines go on the roll call. + pub fn collect(s: *Suite, x: Ctx, functions: *std.ArrayList([]const u8)) !void { + for (family.dflash2_names) |n| try functions.append(x.a, n); + try s.add(x, Tap, .tap, .none); + for (std.enums.values(Norm.Variant)) |v| try s.add(x, Norm, v, .none); + try s.add(x, Embed, .embed, .none); + try attn.collect(s, x); + try act.collect(s, x); + try pick.collect(s, x); + } + + /// One control: its kernel built with the planted fault, at the variant the fault shows in. + pub fn plant(s: *Suite, x: Ctx, m: Mutation) !void { + switch (m) { + .df_tap_next_slot => try s.add(x, Tap, .tap, m), + .df_norm_half_mean => try s.add(x, Norm, .norm_add, m), + .df_norm16_no_weight => try s.add(x, Norm, .norm16, m), + .df_embed_own_row => try s.add(x, Embed, .embed, m), + .df_prep_ropes_nope => try s.add(x, attn.Prep, .global_block, m), + .df_conv_three_taps => try s.add(x, act.Conv, .side1, m), + .df_silu_no_negative => try s.add(x, act.Silu, .silu, m), + .df_vec_no_floor => try s.add(x, attn.Vec, .floor, m), + .df_topk_ascending => try s.add(x, pick.TopK, .logits, m), + .df_walk_from_pending => try s.add(x, pick.Walk, .walk, m), + else => return error.NotADflash2Control, + } + } + + pub fn deinit(s: *Suite, a: std.mem.Allocator) void { + for (s.owned.items) |o| o.free(o.ctx, a); + s.owned.deinit(a); + } +}; + +// --- rc_df_norm, rc_df_norm16: the release's RMSNorm of fp32 rows (bf16(R + X) first) or bf16 rows, 256 threads --- + +/// Each thread's fma chain over width / 256 inputs, a 5-level simd_sum, then the 8 simdgroups' parts in turn. +fn normDepth(s: c.Shape) usize { + return (s.k + 255) / 256 + 5 + 8; +} + +/// Gate 4's norm rows: integers in [-32, 32], so fp32 sums of squares are exact in any order. +fn stressRows(rng: std.Random, x: []f32) void { + for (x) |*v| v.* = @as(f32, @floatFromInt(rng.uintLessThan(u32, 65))) - 32; +} + +pub const Norm = struct { + /// The block's norms of the fp32 residual (layer 0's input, then each after bf16(R + X)); the context's bf16 rows. + pub const Variant = enum { norm, norm_add, norm16 }; + a: std.mem.Allocator, + rig: rig_.Rig, + pipe: mtl.Pipeline, + v: Variant, + m: Mutation, + shape: c.Shape = undefined, + /// The rows as the norm reads them (after the add), the fp32 residual before it, X and w as bf16. + x: []f32 = &.{}, + r0: []f32 = &.{}, + xb: []u16 = &.{}, + w: []u16 = &.{}, + res: rig_.Ref = undefined, + ins: [2]rig_.Ref = undefined, + out: rig_.Ref = undefined, + + pub fn spec(v: Variant) c.Spec { + // the draft block's 16 rows; fc's rows of a context absorb (2,048), and a few + const block: []const c.Shape = &.{.{ .rows = D.block, .n = 1, .k = D.hidden }}; + const context: []const c.Shape = &.{ .{ .rows = 2048, .n = 1, .k = D.hidden }, .{ .rows = 7, .n = 1, .k = D.hidden } }; + return .{ + .name = switch (v) { + .norm => "ricursive dflash2 rc_df_norm fp32 rows", + .norm_add => "ricursive dflash2 rc_df_norm bf16(R + X) rows", + .norm16 => "ricursive dflash2 rc_df_norm16", + }, + .accum = .f32, + .depth = normDepth, + // the mean's division, + eps, precise rsqrt (2), x * inv, then w's product + .ops = 6, + // bf16(x * inv) before w's product + .mids = 1, + .out = .bf16, + .tiles = .{ .{ .size = 1 }, .{}, .{ .size = 256, .step = 1, .min = 1 } }, + .served = if (v == .norm16) context else block, // n unused + .sums = .{ .bf16 = 0, .why = norm_why }, + }; + } + + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, v: Variant, m: Mutation) !Norm { + return .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .pipe = try pipeline(device, a, if (v == .norm16) "rc_df_norm16" else "rc_df_norm", m), .v = v, .m = m }; + } + pub fn deinit(t: *Norm) void { + t.free(); + t.rig.deinit(); + t.pipe.deinit(); + } + fn free(t: *Norm) void { + inline for (.{ "x", "r0", "xb", "w" }) |f| { + t.a.free(@field(t, f)); + @field(t, f) = &.{}; + } + } + pub fn kernel(t: *Norm) g.Kernel { + return controls.mark(.{ .spec = spec(t.v), .ctx = t, .vt = &vt }, t.m); + } + const vt = g.hooks(Norm); + + fn fp32Rows(t: *const Norm) bool { + return t.v != .norm16; + } + + pub fn prepare(t: *Norm, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.rows == 0 or shape.k == 0) return false; + t.rig.reset(); + t.free(); + t.shape = shape; + const n = shape.rows * shape.k; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + t.x = try t.a.alloc(f32, n); + t.r0 = try t.a.alloc(f32, n); + t.xb = try t.a.alloc(u16, n); + t.w = try t.a.alloc(u16, shape.k); + fillBf(rng, t.w, -0.5, 0.5); + for (t.r0) |*v| v.* = (rng.float(f32) * 2 - 1) * (if (rng.uintLessThan(u32, 64) == 7) @as(f32, 20) else 1); + fillBf(rng, t.xb, -2, 2); + if (fill == .stress) { + stressRows(rng, t.r0); + for (t.xb, t.r0) |*b, r| b.* = if (t.v == .norm_add) 0 else c.toBf16(r); + } + if (fill == .nonfinite) { + const at = [_][2]usize{ .{ 0, shape.k / 3 }, .{ 1, shape.k / 2 }, .{ 2, shape.k - 1 }, .{ 3, 0 }, .{ 3, shape.k - 1 } }; + const put = [_]f32{ nan, inf, -inf, inf, -inf }; + for (at, put) |p, v| if (p[0] < shape.rows) { + const i = p[0] * shape.k + p[1]; + if (t.v == .norm) t.r0[i] = v else t.xb[i] = c.toBf16(v); + }; + } + for (t.x, t.r0, t.xb) |*x, r, b| x.* = switch (t.v) { + .norm16 => c.fromBf16(b), + .norm => r, + .norm_add => @floatCast(bf(@as(f32, r + c.fromBf16(b)))), + }; + if (t.fp32Rows()) t.res = try t.rig.scratch(n * 4); + t.ins[0] = try t.rig.input(std.mem.sliceAsBytes(t.xb)); + t.ins[1] = try t.rig.input(std.mem.sliceAsBytes(t.w)); + t.out = try t.rig.output(n * 2); + return true; + } + + pub fn run(t: *Norm) !void { + const n = t.shape.rows * t.shape.k; + if (t.fp32Rows()) @memcpy(t.rig.bytes(t.res, n * 4), std.mem.sliceAsBytes(t.r0)); + const p = t.rig.begin(); + p.e.setPipeline(t.pipe); + const args = extern struct { rows: u32, width: u32, eps: f32, add: u32 }{ .rows = @intCast(t.shape.rows), .width = @intCast(t.shape.k), .eps = D.eps, .add = @intFromBool(t.v == .norm_add) }; + if (t.fp32Rows()) { + p.e.setBuffer(t.res.buf, t.res.off, 0); + p.e.setBuffer(t.ins[0].buf, t.ins[0].off, 1); + p.e.setBuffer(t.ins[1].buf, t.ins[1].off, 2); + p.e.setValue(args, 3); + p.e.setBuffer(t.out.buf, t.out.off, 4); + } else { + p.e.setBuffer(t.ins[0].buf, t.ins[0].off, 0); + p.e.setBuffer(t.ins[1].buf, t.ins[1].off, 1); + p.e.setValue(args, 2); + p.e.setBuffer(t.out.buf, t.out.off, 3); + } + p.e.dispatchGroups(mtl.Size.of(t.shape.rows, 1, 1), mtl.Size.of(256, 1, 1)); + try t.rig.finish(p); + if (!t.fp32Rows()) return; + // R as the run left it: the rows the norm read, bit for bit (a NaN as a NaN) + const got = std.mem.bytesAsSlice(f32, t.rig.bytes(t.res, n * 4)); + for (got, t.x) |gv, want| if (!(@as(u32, @bitCast(gv)) == @as(u32, @bitCast(want)) or (std.math.isNan(gv) and std.math.isNan(want)))) return error.ResidualRowsDiffer; + } + + pub fn count(t: *Norm) usize { + return t.shape.rows * t.shape.k; + } + + const Sim = struct { c.Accum, g.Order }; + + fn inv(t: *const Norm, row: usize, acc: ?Sim) !f64 { + const k = t.shape.k; + const sq = try t.a.alloc(f64, k); + defer t.a.free(sq); + for (sq, t.x[row * k ..][0..k]) |*s, x| s.* = @as(f64, x) * x; + var ss: f64 = 0; + for (sq) |s| ss += s; + if (acc) |o| ss = contract.rows.sumIn(o[0], o[1], sq); + return 1 / @sqrt(ss / @as(f64, @floatFromInt(k)) + @as(f64, D.eps)); + } + + fn outputs(t: *Norm, out: []f64, mag: ?[]f64, acc: ?Sim) !void { + const k = t.shape.k; + for (0..t.shape.rows) |r| { + const s = try t.inv(r, acc); + for (0..k) |i| { + const w: f64 = c.fromBf16(t.w[i]); + const y = w * (@as(f64, t.x[r * k + i]) * s); + out[r * k + i] = y; + if (mag) |m| m[r * k + i] = if (std.math.isFinite(y)) @abs(y) / 2 else 0; // y ~ ss^-1/2 + } + } + } + + pub fn reference(t: *Norm, want: []f64, mag: []f64) !void { + try t.outputs(want, mag, null); + } + pub fn simulate(t: *Norm, acc: c.Accum, order: g.Order, out: []f64) !void { + try t.outputs(out, null, .{ acc, order }); + } +}; + +// --- rc_df_embed: the block's ids through the target's table into the fp32 residual, unscaled -------------------- + +pub const Embed = struct { + pub const Variant = enum { embed }; + /// Table rows the probe holds: ids only index it. + const table = 64; + a: std.mem.Allocator, + rig: rig_.Rig, + pipe: mtl.Pipeline, + m: Mutation, + shape: c.Shape = undefined, + e: []u16 = &.{}, + ids: []u32 = &.{}, + ins: [2]rig_.Ref = undefined, + out: rig_.Ref = undefined, + + /// Rows: the block's positions; n: the hidden width (k unused). + pub fn spec(_: Variant) c.Spec { + return .{ + .name = "ricursive dflash2 rc_df_embed", + .accum = .none, + .depth = noSums, + .out = .f32, + .tiles = .{ .{}, .{ .size = 256, .step = 1, .min = 1 }, .{} }, + .served = &.{.{ .rows = D.block, .n = D.hidden, .k = 1 }}, + }; + } + + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, _: Variant, m: Mutation) !Embed { + return .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .pipe = try pipeline(device, a, "rc_df_embed", m), .m = m }; + } + pub fn deinit(t: *Embed) void { + t.a.free(t.e); + t.a.free(t.ids); + t.rig.deinit(); + t.pipe.deinit(); + } + pub fn kernel(t: *Embed) g.Kernel { + return controls.mark(.{ .spec = spec(.embed), .ctx = t, .vt = &vt }, t.m); + } + const vt = g.hooks(Embed); + + pub fn prepare(t: *Embed, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.rows == 0 or shape.rows > table or shape.n == 0) return false; + t.rig.reset(); + t.a.free(t.e); + t.a.free(t.ids); + t.e = &.{}; + t.ids = &.{}; + t.shape = shape; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + t.e = try t.a.alloc(u16, table * shape.n); + fillBf(rng, t.e, -2, 2); + t.ids = try t.a.alloc(u32, shape.rows); + // no row reads its own table row + for (t.ids, 0..) |*id, i| id.* = @intCast((i * 5 + 3) % table); + if (fill == .nonfinite) for ([_]f32{ nan, inf, -inf }, 0..) |v, r| { + if (r < shape.rows) t.e[t.ids[r] * shape.n + (r * 7) % shape.n] = c.toBf16(v); + }; + t.ins[0] = try t.rig.input(std.mem.sliceAsBytes(t.ids)); + t.ins[1] = try t.rig.input(std.mem.sliceAsBytes(t.e)); + t.out = try t.rig.output(t.count() * 4); + return true; + } + + pub fn run(t: *Embed) !void { + const p = t.rig.begin(); + p.e.setPipeline(t.pipe); + p.e.setBuffer(t.ins[0].buf, t.ins[0].off, 0); + p.e.setBuffer(t.ins[1].buf, t.ins[1].off, 1); + p.e.setValue(extern struct { rows: u32, width: u32, eps: f32, add: u32 }{ .rows = @intCast(t.shape.rows), .width = @intCast(t.shape.n), .eps = 0, .add = 0 }, 2); + p.e.setBuffer(t.out.buf, t.out.off, 3); + p.e.dispatchThreads(mtl.Size.of(t.shape.n, t.shape.rows, 1), mtl.Size.of(256, 1, 1)); + try t.rig.finish(p); + } + + pub fn count(t: *Embed) usize { + return t.shape.rows * t.shape.n; + } + + pub fn reference(t: *Embed, want: []f64, mag: []f64) !void { + const n = t.shape.n; + for (want, mag, 0..) |*w, *m, i| { + w.* = c.fromBf16(t.e[t.ids[i / n] * n + i % n]); + m.* = 0; + } + } +}; + +// --- rc_tap: the target's residual after a tapped layer, as bf16, into its slot among the taps ------------------- + +pub const Tap = struct { + pub const Variant = enum { tap }; + a: std.mem.Allocator, + rig: rig_.Rig, + pipe: mtl.Pipeline, + m: Mutation, + shape: c.Shape = undefined, + r: []u16 = &.{}, + old: []u16 = &.{}, + in: rig_.Ref = undefined, + out: rig_.Ref = undefined, + + /// Rows: positions; n: the hidden width; k: the taps; the other taps' slots stay put. + pub fn spec(_: Variant) c.Spec { + return .{ + .name = "ricursive dflash2 rc_tap", + .accum = .none, + .depth = noSums, + .out = .bf16, + .tiles = .{ .{ .size = 1 }, .{ .size = 256, .step = 1, .min = 1 }, .{} }, + // a decode window's rows and a prompt chunk's + .served = &.{ .{ .rows = D.block, .n = D.hidden, .k = D.taps }, .{ .rows = 2048, .n = D.hidden, .k = D.taps } }, + }; + } + + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, _: Variant, m: Mutation) !Tap { + return .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .pipe = try pipeline(device, a, "rc_tap", m), .m = m }; + } + pub fn deinit(t: *Tap) void { + t.a.free(t.r); + t.a.free(t.old); + t.rig.deinit(); + t.pipe.deinit(); + } + pub fn kernel(t: *Tap) g.Kernel { + return controls.mark(.{ .spec = spec(.tap), .ctx = t, .vt = &vt }, t.m); + } + const vt = g.hooks(Tap); + + /// The tap written: the next to last, so a slot past it is still inside the features. + fn tap(t: *const Tap) usize { + return t.shape.k - 2; + } + + pub fn prepare(t: *Tap, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.rows == 0 or shape.n == 0 or shape.k < 2) return false; + t.rig.reset(); + t.a.free(t.r); + t.a.free(t.old); + t.r = &.{}; + t.old = &.{}; + t.shape = shape; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + t.r = try t.a.alloc(u16, shape.rows * shape.n); + fillBf(rng, t.r, -64, 64); + if (fill == .nonfinite) for ([_]f32{ nan, inf, -inf }, 0..) |v, i| { + t.r[(i * 7) % t.r.len] = c.toBf16(v); + }; + t.old = try t.a.alloc(u16, t.count()); + fillBf(rng, t.old, -1, 1); + t.in = try t.rig.input(std.mem.sliceAsBytes(t.r)); + t.out = try t.rig.output(t.count() * 2); + return true; + } + + pub fn run(t: *Tap) !void { + @memcpy(t.rig.bytes(t.out, t.count() * 2), std.mem.sliceAsBytes(t.old)); + const p = t.rig.begin(); + p.e.setPipeline(t.pipe); + p.e.setBuffer(t.in.buf, t.in.off, 0); + p.e.setValue([4]u32{ @intCast(t.shape.rows), @intCast(t.shape.n), @intCast(t.shape.k), @intCast(t.tap()) }, 1); + p.e.setBuffer(t.out.buf, t.out.off, 2); + p.e.dispatchThreads(mtl.Size.of(t.shape.n, t.shape.rows, 1), mtl.Size.of(256, 1, 1)); + try t.rig.finish(p); + } + + pub fn count(t: *Tap) usize { + return t.shape.rows * t.shape.k * t.shape.n; + } + + pub fn reference(t: *Tap, want: []f64, mag: []f64) !void { + const n = t.shape.n; + for (want, mag, 0..) |*w, *m, i| { + const r = i / (t.shape.k * n); + const slot = i / n % t.shape.k; + w.* = c.fromBf16(if (slot == t.tap()) t.r[r * n + i % n] else t.old[i]); + m.* = 0; + } + } +}; diff --git a/zig/tests/contract/metal_ricursive_dflash2_act.zig b/zig/tests/contract/metal_ricursive_dflash2_act.zig new file mode 100644 index 00000000000..a9967961e31 --- /dev/null +++ b/zig/tests/contract/metal_ricursive_dflash2_act.zig @@ -0,0 +1,230 @@ +//! The drafter's activation (rc_df_silu) and grouped four-tap block convolution (rc_df_conv) under the contract. +const std = @import("std"); +const mtl = @import("metal"); +const contract = @import("contract"); +const rig_ = @import("rig.zig"); +const controls = @import("metal_ricursive_controls.zig"); +const d = @import("metal_ricursive_dflash2.zig"); + +const c = contract.spec; +const g = contract.gates; +const D = d.D; +const Mutation = d.Mutation; +const bf = d.bf; +const fillBf = d.fillBf; +const nan = d.nan; +const inf = d.inf; + +pub fn collect(s: *d.Suite, x: d.Ctx) !void { + try s.add(x, Silu, .silu, .none); + for (std.enums.values(Conv.Variant)) |v| try s.add(x, Conv, v, .none); +} + +// --- rc_df_silu: the release's SiLU of the gate times up, at its bf16 points --------------------------------------- + +pub const Silu = struct { + pub const Variant = enum { silu }; + a: std.mem.Allocator, + rig: rig_.Rig, + pipe: mtl.Pipeline, + m: Mutation, + shape: c.Shape = undefined, + gu: []u16 = &.{}, + in: rig_.Ref = undefined, + out: rig_.Ref = undefined, + + /// Rows: positions; n: the ffn width (k unused). + pub fn spec(_: Variant) c.Spec { + return .{ + .name = "ricursive dflash2 rc_df_silu", + .accum = .none, + .depth = d.noSums, + // precise exp (2 ulps), the add, the division, the sigmoid's own e * y (1), g * s, then * up + .ops = 6, + .mids = 1, + .out = .bf16, + .tiles = .{ .{ .size = 1 }, .{ .size = 256, .step = 1, .min = 1 }, .{} }, + .served = &.{.{ .rows = D.block, .n = D.ffn, .k = 1 }}, + }; + } + + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, _: Variant, m: Mutation) !Silu { + return .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .pipe = try d.pipeline(device, a, "rc_df_silu", m), .m = m }; + } + pub fn deinit(t: *Silu) void { + t.a.free(t.gu); + t.rig.deinit(); + t.pipe.deinit(); + } + pub fn kernel(t: *Silu) g.Kernel { + return controls.mark(.{ .spec = spec(.silu), .ctx = t, .vt = &vt }, t.m); + } + const vt = g.hooks(Silu); + + pub fn prepare(t: *Silu, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.rows == 0 or shape.n == 0) return false; + t.rig.reset(); + t.a.free(t.gu); + t.gu = &.{}; + t.shape = shape; + const n = shape.n; + t.gu = try t.a.alloc(u16, shape.rows * 2 * n); + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + // gates past +-20 reach silu's flat ends; ups both signs + for (0..shape.rows) |r| { + fillBf(rng, t.gu[r * 2 * n ..][0..n], -24, 24); + fillBf(rng, t.gu[r * 2 * n + n ..][0..n], -4, 4); + } + if (fill == .nonfinite) for ([_]f32{ nan, inf, -inf, nan, inf, -inf }, 0..) |v, i| { + const r = i % shape.rows; + t.gu[r * 2 * n + (if (i < 3) 0 else n) + (i * 7) % n] = c.toBf16(v); + }; + t.in = try t.rig.input(std.mem.sliceAsBytes(t.gu)); + t.out = try t.rig.output(shape.rows * n * 2); + return true; + } + + pub fn run(t: *Silu) !void { + const p = t.rig.begin(); + p.e.setPipeline(t.pipe); + p.e.setBuffer(t.in.buf, t.in.off, 0); + p.e.setValue([2]u32{ @intCast(t.shape.rows), @intCast(t.shape.n) }, 1); + p.e.setBuffer(t.out.buf, t.out.off, 2); + p.e.dispatchThreads(mtl.Size.of(t.shape.n, t.shape.rows, 1), mtl.Size.of(256, 1, 1)); + try t.rig.finish(p); + } + + pub fn count(t: *Silu) usize { + return t.shape.rows * t.shape.n; + } + + pub fn reference(t: *Silu, want: []f64, mag: []f64) !void { + const n = t.shape.n; + for (want, mag, 0..) |*w, *m, i| { + const r = i / n; + const gate: f64 = c.fromBf16(t.gu[r * 2 * n + i % n]); + w.* = gate / (1 + @exp(-gate)) * c.fromBf16(t.gu[r * 2 * n + n + i % n]); + m.* = 0; + } + } +}; + +// --- rc_df_conv: the grouped four-tap block convolution, exact at its bf16 points ----------------------------------- + +pub const Conv = struct { + /// Side 0 (the sublayer input's prepare) and side 1 (its output), each with its own taps of base and the deltas. + pub const Variant = enum { side0, side1 }; + a: std.mem.Allocator, + rig: rig_.Rig, + pipe: mtl.Pipeline, + v: Variant, + m: Mutation, + shape: c.Shape = undefined, + x: []u16 = &.{}, + d: []u16 = &.{}, + base: []u16 = &.{}, + ins: [3]rig_.Ref = undefined, + out: rig_.Ref = undefined, + + /// Rows: block positions; n: the hidden width (groups of 16 channels); k: the taps. + pub fn spec(v: Variant) c.Spec { + return .{ + .name = if (v == .side0) "ricursive dflash2 rc_df_conv side 0" else "ricursive dflash2 rc_df_conv side 1", + .accum = .none, + .depth = d.noSums, + .out = .bf16, + .tiles = .{ .{ .size = D.block, .step = 1, .min = 1 }, .{ .size = 256, .step = D.group, .min = D.group }, .{} }, + .served = &.{.{ .rows = D.block, .n = D.hidden, .k = D.conv }}, + }; + } + + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, v: Variant, m: Mutation) !Conv { + return .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .pipe = try d.pipeline(device, a, "rc_df_conv", m), .v = v, .m = m }; + } + pub fn deinit(t: *Conv) void { + t.free(); + t.rig.deinit(); + t.pipe.deinit(); + } + fn free(t: *Conv) void { + inline for (.{ "x", "d", "base" }) |f| { + t.a.free(@field(t, f)); + @field(t, f) = &.{}; + } + } + pub fn kernel(t: *Conv) g.Kernel { + return controls.mark(.{ .spec = spec(t.v), .ctx = t, .vt = &vt }, t.m); + } + const vt = g.hooks(Conv); + + fn groups(t: *const Conv) usize { + return t.shape.n / D.group; + } + fn side(t: *const Conv) usize { + return @backingInt(t.v); + } + /// Row r's coefficient delta for (side, tap, group): dyn's [side][tap][group] layout. + fn delta(t: *const Conv, r: usize, s: usize, tap: usize, gi: usize) f64 { + const k = t.shape.k; + return c.fromBf16(t.d[((r * 2 + s) * k + tap) * t.groups() + gi]); + } + + pub fn prepare(t: *Conv, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.rows == 0 or shape.n == 0 or shape.n % D.group != 0 or shape.k == 0) return false; + t.rig.reset(); + t.free(); + t.shape = shape; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + t.x = try t.a.alloc(u16, shape.rows * shape.n); + t.d = try t.a.alloc(u16, shape.rows * 2 * shape.k * t.groups()); + t.base = try t.a.alloc(u16, 2 * shape.k * shape.n); + fillBf(rng, t.x, -4, 4); + fillBf(rng, t.d, -0.5, 0.5); + fillBf(rng, t.base, -1.5, 1.5); + if (fill == .nonfinite) for ([_]f32{ nan, inf, -inf }, 0..) |v, i| { + t.x[(1 + i) * shape.n + 5 * i] = c.toBf16(v); + t.d[((i * 2 + t.side()) * shape.k) * t.groups() % t.d.len] = c.toBf16(v); + }; + t.ins[0] = try t.rig.input(std.mem.sliceAsBytes(t.x)); + t.ins[1] = try t.rig.input(std.mem.sliceAsBytes(t.d)); + t.ins[2] = try t.rig.input(std.mem.sliceAsBytes(t.base)); + t.out = try t.rig.output(shape.rows * shape.n * 2); + return true; + } + + pub fn run(t: *Conv) !void { + const p = t.rig.begin(); + p.e.setPipeline(t.pipe); + for (t.ins, 0..) |r, i| p.e.setBuffer(r.buf, r.off, i); + p.e.setValue([6]u32{ @intCast(t.shape.rows), @intCast(t.shape.n), D.block, @intCast(t.groups()), @intCast(t.side()), @intCast(t.shape.k) }, 3); + p.e.setBuffer(t.out.buf, t.out.off, 4); + p.e.dispatchThreads(mtl.Size.of(t.shape.n, t.shape.rows, 1), mtl.Size.of(256, 1, 1)); + try t.rig.finish(p); + } + + pub fn count(t: *Conv) usize { + return t.shape.rows * t.shape.n; + } + + /// z-lab's order per tap inside the block: y = bf16(y + bf16(base x[r - t])), then y = bf16(y + delta x[r - t]). + pub fn reference(t: *Conv, want: []f64, mag: []f64) !void { + const n = t.shape.n; + const s = t.side(); + for (want, mag, 0..) |*w, *m, i| { + const r = i / n; + const ch = i % n; + const gi = ch / D.group; + var y: f64 = 0; + for (0..t.shape.k) |tap| { + if (r % D.block < tap) break; + const x: f64 = c.fromBf16(t.x[i - tap * n]); + y = bf(y + bf(@as(f64, c.fromBf16(t.base[(s * t.shape.k + tap) * n + ch])) * x)); + y = bf(y + t.delta(r, s, tap, gi) * x); + } + w.* = y; + m.* = 0; + } + } +}; diff --git a/zig/tests/contract/metal_ricursive_dflash2_attn.zig b/zig/tests/contract/metal_ricursive_dflash2_attn.zig new file mode 100644 index 00000000000..86f24670bbf --- /dev/null +++ b/zig/tests/contract/metal_ricursive_dflash2_attn.zig @@ -0,0 +1,539 @@ +//! The drafter's attention under the contract: rc_df_prep (head norms, rotary or NoPE, the ring) and rc_df_vec. +const std = @import("std"); +const mtl = @import("metal"); +const contract = @import("contract"); +const rig_ = @import("rig.zig"); +const controls = @import("metal_ricursive_controls.zig"); +const d = @import("metal_ricursive_dflash2.zig"); + +const c = contract.spec; +const g = contract.gates; +const D = d.D; +const Range = d.Range; +const Mutation = d.Mutation; +const bf = d.bf; +const f32r = d.f32r; +const u = c.unit(.f32); +const Sim = struct { c.Accum, g.Order }; + +pub fn collect(s: *d.Suite, x: d.Ctx) !void { + for (std.enums.values(Prep.Variant)) |v| try s.add(x, Prep, v, .none); + for (std.enums.values(Vec.Variant)) |v| try s.add(x, Vec, v, .none); +} + +/// cos over [lo, hi] (sin as cos(x - pi/2)): the ends' values, or +-1 where an extremum falls inside. +fn cosRange(lo: f64, hi: f64) Range { + if (hi - lo >= 2 * std.math.pi) return .{ .lo = -1, .hi = 1 }; + var r = Range{ .lo = @min(@cos(lo), @cos(hi)), .hi = @max(@cos(lo), @cos(hi)) }; + var k = @ceil(lo / std.math.pi); + while (k * std.math.pi <= hi) : (k += 1) { + if (@mod(k, 2) == 0) r.hi = 1 else r.lo = -1; + } + return r; +} + +/// The last position before the served context's end at 3 keys before a wrap of `ring`. +fn farPos(ring: u32) u32 { + return D.context / ring * ring - 3; +} + +// --- rc_df_prep: q and k heads normed and rotated (or not, on the NoPE layer), k and v into the ring ------------- + +pub const Prep = struct { + /// A block on a sliding layer near the ring's wrap or past 261k positions, on the global NoPE layer; and absorbs. + pub const Variant = enum { sliding_block, sliding_far, global_block, sliding_context, global_context }; + a: std.mem.Allocator, + rig: rig_.Rig, + pipe: mtl.Pipeline, + v: Variant, + m: Mutation, + shape: c.Shape = undefined, + fill: g.Fill = .random, + x: []u16 = &.{}, + qw: []u16 = &.{}, + kw: []u16 = &.{}, + old: []u16 = &.{}, + ins: [3]rig_.Ref = undefined, + outs: [3]rig_.Ref = undefined, + + fn context(v: Variant) bool { + return v == .sliding_context or v == .global_context; + } + fn global(t: *const Prep) bool { + return t.v == .global_block or t.v == .global_context; + } + fn ring(t: *const Prep) u32 { + return D.ring(if (t.global()) D.global else D.window); + } + fn heads(t: *const Prep) u32 { + return if (context(t.v)) 0 else D.heads; + } + + /// Rows: positions; n: the heads launched (q then kv); k: the head dim. + pub fn spec(v: Variant) c.Spec { + return .{ + .name = switch (v) { + .sliding_block => "ricursive dflash2 rc_df_prep sliding block", + .sliding_far => "ricursive dflash2 rc_df_prep sliding block past 261k", + .global_block => "ricursive dflash2 rc_df_prep NoPE block", + .sliding_context => "ricursive dflash2 rc_df_prep sliding context", + .global_context => "ricursive dflash2 rc_df_prep NoPE context", + }, + .accum = .f32, + .depth = prepDepth, + .out = .bf16, + .tiles = .{ .{ .size = 1 }, .{}, .{} }, + .served = if (context(v)) &.{ .{ .rows = 2048, .n = D.kv, .k = 128 }, .{ .rows = 5, .n = D.kv, .k = 128 } } else &.{ .{ .rows = D.block, .n = D.heads + D.kv, .k = 128 }, .{ .rows = 1, .n = D.heads + D.kv, .k = 128 } }, + .sums = .{ .bf16 = 0, .why = d.norm_why }, + }; + } + /// Each lane's 4 fmas, then a 5-level simd_sum. + fn prepDepth(_: c.Shape) usize { + return 9; + } + + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, v: Variant, m: Mutation) !Prep { + return .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .pipe = try d.pipeline(device, a, "rc_df_prep", m), .v = v, .m = m }; + } + pub fn deinit(t: *Prep) void { + t.free(); + t.rig.deinit(); + t.pipe.deinit(); + } + fn free(t: *Prep) void { + inline for (.{ "x", "qw", "kw", "old" }) |f| { + t.a.free(@field(t, f)); + @field(t, f) = &.{}; + } + } + pub fn kernel(t: *Prep) g.Kernel { + return controls.mark(.{ .spec = spec(t.v), .ctx = t, .vt = &vt }, t.m); + } + const vt = g.hooks(Prep); + + fn pos0(t: *const Prep) u32 { + if (t.fill == .stress) return 0; // gate 4 at positions 0-3: the rotation's own spread stays far under a sum's + return if (t.v == .sliding_far) farPos(t.ring()) else t.ring() - 3; + } + fn rope(t: *const Prep) bool { + return !t.global(); + } + /// X's row as dflash2.zig lays it: a block's q, k and v heads; a context's k and v projections. + fn layout(t: *const Prep) struct { stride: usize, q: usize, k: usize, v: usize } { + const kvw: usize = D.kv * 128; + const qw: usize = t.heads() * 128; + return if (t.heads() == 0) .{ .stride = 2 * kvw, .q = 0, .k = 0, .v = kvw } else .{ .stride = qw + 2 * kvw, .q = 0, .k = qw, .v = qw + kvw }; + } + fn sizes(t: *const Prep) [3]usize { + const ringed: usize = @as(usize, t.ring()) * D.kv * 128; + return .{ @max(1, t.shape.rows * t.heads() * 128), ringed, ringed }; + } + + pub fn prepare(t: *Prep, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.rows == 0 or shape.n != t.heads() + D.kv or shape.k != 128) return false; + t.rig.reset(); + t.free(); + t.shape = shape; + t.fill = fill; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + const l = t.layout(); + t.x = try t.a.alloc(u16, shape.rows * l.stride); + d.fillBf(rng, t.x, -3, 3); + if (fill == .stress) for (t.x) |*v| { + v.* = c.toBf16(@as(f32, @floatFromInt(rng.uintLessThan(u32, 65))) - 32); + }; + if (fill == .nonfinite) for ([_]f32{ d.nan, d.inf, -d.inf, d.inf }, 0..) |v, i| { + // a q head (or a context's k head) a value each, then a k head's + const r = i % shape.rows; + const at = if (i < 2) l.q + (if (t.heads() == 0) l.k else 0) + 5 + 31 * i else l.k + 128 + 7 * i; + t.x[r * l.stride + at] = c.toBf16(v); + }; + t.qw = try t.a.alloc(u16, 128); + t.kw = try t.a.alloc(u16, 128); + d.fillBf(rng, t.qw, -0.5, 0.5); + d.fillBf(rng, t.kw, -0.5, 0.5); + const sz = t.sizes(); + t.old = try t.a.alloc(u16, sz[0] + sz[1] + sz[2]); + d.fillBf(rng, t.old, -1, 1); + t.ins[0] = try t.rig.input(std.mem.sliceAsBytes(t.x)); + t.ins[1] = try t.rig.input(std.mem.sliceAsBytes(t.qw)); + t.ins[2] = try t.rig.input(std.mem.sliceAsBytes(t.kw)); + for (&t.outs, sz) |*o, n| o.* = try t.rig.output(n * 2); + return true; + } + + pub fn run(t: *Prep) !void { + const sz = t.sizes(); + var at: usize = 0; + for (t.outs, sz) |o, n| { + @memcpy(t.rig.bytes(o, n * 2), std.mem.sliceAsBytes(t.old[at..][0..n])); + at += n; + } + const l = t.layout(); + const p = t.rig.begin(); + p.e.setPipeline(t.pipe); + for (t.ins, 0..) |r, i| p.e.setBuffer(r.buf, r.off, i); + const Args = extern struct { rows: u32, heads: u32, kv_heads: u32, pos0: u32, stride: u32, q_off: u32, k_off: u32, v_off: u32, ring: u32, rope: u32, eps: f32, theta: f32 }; + p.e.setValue(Args{ .rows = @intCast(t.shape.rows), .heads = t.heads(), .kv_heads = D.kv, .pos0 = t.pos0(), .stride = @intCast(l.stride), .q_off = @intCast(l.q), .k_off = @intCast(l.k), .v_off = @intCast(l.v), .ring = t.ring(), .rope = @intFromBool(t.rope()), .eps = D.eps, .theta = D.theta }, 3); + for (t.outs, 4..) |o, i| p.e.setBuffer(o.buf, o.off, i); + p.e.dispatchGroups(mtl.Size.of(t.shape.n, t.shape.rows, 1), mtl.Size.of(32, 1, 1)); + try t.rig.finish(p); + } + + pub fn count(t: *Prep) usize { + const sz = t.sizes(); + return sz[0] + sz[1] + sz[2]; + } + + /// Where head (row, unit)'s outputs land: its q row, or its ring slot's k (v beside it, in the third buffer). + fn dest(t: *const Prep, row: usize, unit: usize) usize { + const sz = t.sizes(); + const h = t.heads(); + if (unit < h) return (row * h + unit) * 128; + const slot = (t.pos0() + row) % t.ring(); + return sz[0] + (slot * D.kv + unit - h) * 128; + } + + /// One head's 128 outputs: float64 at the kernel's rounding points (fp32's angle), and the range fp32 allows. + fn head(t: *const Prep, row: usize, unit: usize, sim: ?Sim, want: *[128]f64, low: *[128]f64, high: *[128]f64) void { + const l = t.layout(); + const is_q = unit < t.heads(); + const src = t.x[row * l.stride + (if (is_q) l.q + unit * 128 else l.k + (unit - t.heads()) * 128) ..][0..128]; + const w = if (is_q) t.qw else t.kw; + var sq: [128]f64 = undefined; + var ss: f64 = 0; + for (&sq, src) |*s, b| { + s.* = @as(f64, c.fromBf16(b)) * c.fromBf16(b); + ss += s.*; + } + if (sim) |o| ss = contract.rows.sumIn(o[0], o[1], &sq); + const inv = 1 / @sqrt(ss / 128 + @as(f64, D.eps)); + // the sum's chain (none for gate 4's exact sums), + eps and precise rsqrt's 2 ulps, halved through ss^-1/2 + const e_inv = (if (t.fill == .stress or sim != null) 0 else c.gamma(9, u)) / 2 + 3 * u; + var nrm: [128]f64 = undefined; + var nr: [128]Range = undefined; + for (src, w, 0..) |b, wb, j| { + const v: f64 = c.fromBf16(b); + const wv: f64 = c.fromBf16(wb); + nrm[j] = bf(wv * bf(v * inv)); + nr[j] = Range.point(v * inv).fp32(e_inv / u + 1).bf16().mul(Range.point(wv)).bf16(); + } + if (!t.rope()) { + want.* = nrm; + for (nr, low, high) |r, *lo, *hi| { + lo.* = r.lo; + hi.* = r.hi; + } + return; + } + const p: u32 = t.pos0() + @as(u32, @intCast(row)); + for (0..128) |j| { + const i = j % 64; + const e = f32r(@as(f64, @floatFromInt(2 * i)) / 128); + const freq = std.math.pow(f64, D.theta, e); + const angle = f32r(@as(f64, @floatFromInt(p)) * f32r(1 / f32r(freq))); + // precise pow (16 ulps), the reciprocal (2.5), the product (1); then precise cos and sin (4 ulps of 1) + const exact = @as(f64, @floatFromInt(p)) / freq; + const da = exact * 19.5 * u + 0x1p-149; + const cr = cosRange(exact - da, exact + da); + const sr = cosRange(exact - da - std.math.pi / 2.0, exact + da - std.math.pi / 2.0); + const cs = (Range{ .lo = cr.lo - 0x1p-22, .hi = cr.hi + 0x1p-22 }).bf16(); + const sn = (Range{ .lo = sr.lo - 0x1p-22, .hi = sr.hi + 0x1p-22 }).bf16(); + const rot = if (j < 64) -nrm[j + 64] else nrm[j - 64]; + const rr = if (j < 64) nr[j + 64].neg() else nr[j - 64]; + want[j] = bf(bf(nrm[j] * bf(@cos(angle))) + bf(rot * bf(@sin(angle)))); + const y = nr[j].mul(cs).bf16().add(rr.mul(sn).bf16()).fp32(1).bf16(); + low[j] = y.lo; + high[j] = y.hi; + } + } + + fn all(t: *Prep, want: []f64, low: ?[]f64, high: ?[]f64, sim: ?Sim) void { + const sz = t.sizes(); + for (want, t.old) |*w, o| w.* = c.fromBf16(o); + if (low) |lo| @memcpy(lo, want); + if (high) |hi| @memcpy(hi, want); + const l = t.layout(); + for (0..t.shape.rows) |row| for (0..t.shape.n) |unit| { + var hw: [128]f64 = undefined; + var hl: [128]f64 = undefined; + var hh: [128]f64 = undefined; + t.head(row, unit, sim, &hw, &hl, &hh); + const at = t.dest(row, unit); + @memcpy(want[at..][0..128], &hw); + if (low) |lo| @memcpy(lo[at..][0..128], &hl); + if (high) |hi| @memcpy(hi[at..][0..128], &hh); + if (unit < t.heads()) continue; + const vs = t.x[row * l.stride + l.v + (unit - t.heads()) * 128 ..][0..128]; + for (want[at + sz[1] ..][0..128], vs, 0..) |*w, b, j| { + w.* = c.fromBf16(b); + if (low) |lo| lo[at + sz[1] + j] = w.*; + if (high) |hi| hi[at + sz[1] + j] = w.*; + } + }; + } + + pub fn reference(t: *Prep, want: []f64, mag: []f64) !void { + t.all(want, null, null, null); + @memset(mag, 0); + } + pub fn intervals(t: *Prep, low: []f64, high: []f64) !void { + const want = try t.a.alloc(f64, t.count()); + defer t.a.free(want); + t.all(want, low, high, null); + } + pub fn bounds(t: *Prep, want: []const f64, _: []const f64, allow: []f64) !void { + const buf = try t.a.alloc(f64, 2 * t.count()); + defer t.a.free(buf); + try t.intervals(buf[0..t.count()], buf[t.count()..]); + for (allow, want, buf[0..t.count()], buf[t.count()..]) |*l, w, lo, hi| l.* = if (std.math.isFinite(w)) d.spread(w, .{ .lo = lo, .hi = hi }) else 0; + } + pub fn simulate(t: *Prep, acc: c.Accum, order: g.Order, out: []f64) !void { + t.all(out, null, null, .{ acc, order }); + } +}; + +// --- rc_df_vec: a block's attention partials over 128-key blocks of a layer's ring -------------------------------- + +pub const Vec = struct { + /// A sliding layer, the global layer, and the global layer over a resumed prompt's context (keys from a floor). + pub const Variant = enum { sliding, global, floor }; + a: std.mem.Allocator, + rig: rig_.Rig, + pipe: mtl.Pipeline, + v: Variant, + m: Mutation, + shape: c.Shape = undefined, + fill: g.Fill = .random, + q: []u16 = &.{}, + k: []u16 = &.{}, + val: []u16 = &.{}, + old: []f32 = &.{}, + ins: [3]rig_.Ref = undefined, + outs: [3]rig_.Ref = undefined, + + fn ring(t: *const Vec) u32 { + return D.ring(if (t.v == .sliding) D.window else D.global); + } + + /// Rows: the block's positions; n: q heads; k: the window (the layer's, and a short one with partial blocks). + pub fn spec(v: Variant) c.Spec { + return .{ + .name = switch (v) { + .sliding => "ricursive dflash2 rc_df_vec sliding layer", + .global => "ricursive dflash2 rc_df_vec global layer", + .floor => "ricursive dflash2 rc_df_vec global layer above a floor", + }, + .accum = .f32, + .depth = vecDepth, + .out = .f32, + .nan = .{ .stated = "a NaN score is skipped by the running max (Metal's max, as fmax) and makes the block's mass and output NaN" }, + .tiles = .{ .{ .size = 1 }, .{}, .{} }, + .served = switch (v) { + .sliding => &.{ .{ .rows = D.block, .n = D.heads, .k = D.window }, .{ .rows = D.block, .n = D.heads, .k = 300 } }, + .global, .floor => &.{ .{ .rows = D.block, .n = D.heads, .k = D.global }, .{ .rows = D.block, .n = D.heads, .k = 1300 } }, + }, + .sums = .{ .f16 = 100, .bf16 = 100 }, + }; + } + /// A score's: q's scale, a lane's 4-term dot, a 5-level simd_sum. + fn vecDepth(_: c.Shape) usize { + return 10; + } + + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, v: Variant, m: Mutation) !Vec { + return .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .pipe = try d.pipeline(device, a, "rc_df_vec", m), .v = v, .m = m }; + } + pub fn deinit(t: *Vec) void { + t.free(); + t.rig.deinit(); + t.pipe.deinit(); + } + fn free(t: *Vec) void { + inline for (.{ "q", "k", "val", "old" }) |f| { + t.a.free(@field(t, f)); + @field(t, f) = &.{}; + } + } + pub fn kernel(t: *Vec) g.Kernel { + return controls.mark(.{ .spec = spec(t.v), .ctx = t, .vt = &vt }, t.m); + } + const vt = g.hooks(Vec); + + const Plan = struct { anchor: u32, hi: u32, floor: u32, first: u32, blocks: u32 }; + /// The anchor near the context's end, row 0's window from 3 keys before a block's end, the floor 1,000 keys in. + fn plan(t: *const Vec) Plan { + const w: u32 = @intCast(t.shape.k); + const lo0 = (farPos(t.ring()) + 3 - w) / 128 * 128 + 125; + const anchor = lo0 + w - 1; + const hi = anchor + @as(u32, @intCast(t.shape.rows)); + const floor: u32 = if (t.v == .floor) lo0 + 1000 else 0; + const lo = @max(lo0, floor); + return .{ .anchor = anchor, .hi = hi, .floor = floor, .first = lo / 128, .blocks = (hi - 1) / 128 - lo / 128 + 1 }; + } + fn slots(t: *const Vec) usize { + return t.shape.n * t.shape.rows * t.plan().blocks; + } + fn scale(t: *const Vec) f32 { + return if (t.fill == .stress) 1 else 1.0 / @sqrt(128.0); + } + + pub fn prepare(t: *Vec, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.rows == 0 or shape.rows > D.block or shape.n != D.heads or shape.k > t.ring() - D.block) return false; + if (t.v == .floor and shape.k <= 1000) return false; // the floor lies inside row 0's window + t.rig.reset(); + t.free(); + t.shape = shape; + t.fill = fill; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + const kvn: usize = @as(usize, t.ring()) * D.kv * 128; + t.q = try t.a.alloc(u16, shape.rows * D.heads * 128); + t.k = try t.a.alloc(u16, kvn); + t.val = try t.a.alloc(u16, kvn); + d.fillBf(rng, t.q, -3, 3); + d.fillBf(rng, t.k, -3, 3); + d.fillBf(rng, t.val, -2, 2); + if (fill == .stress) { + // big products, mirrored halves (k negated, a few nudged): partials near 2^20, scores in the hundreds + for (0..t.q.len / 128) |h| for (0..64) |j| { + const qv: f32 = @floatFromInt(64 + rng.uintLessThan(u32, 64)); + t.q[h * 128 + j] = c.toBf16(qv); + t.q[h * 128 + 64 + j] = c.toBf16(qv); + }; + for (0..kvn / 128) |h| for (0..64) |j| { + const kv: f32 = @floatFromInt(64 + rng.uintLessThan(u32, 64)); + const nudge: f32 = if (j < 2) @floatFromInt(@as(i32, @intCast(rng.uintLessThan(u32, 3))) - 1) else 0; + t.k[h * 128 + j] = c.toBf16(kv); + t.k[h * 128 + 64 + j] = c.toBf16(-kv + nudge); + }; + for (t.val) |*v| v.* = c.toBf16(@as(f32, @floatFromInt(rng.uintLessThan(u32, 9))) - 4); + } + if (fill == .nonfinite) { + const p = t.plan(); + const r: usize = t.ring(); + // a key's NaN component, +inf in a query, -inf in a value (keys of the last block, kv head 0) + t.k[((p.hi - 2) % r) * D.kv * 128 + 3] = c.toBf16(d.nan); + t.q[(1 * D.heads + 5) * 128 + 9] = c.toBf16(d.inf); + t.val[((p.hi - 1) % r) * D.kv * 128 + 2] = c.toBf16(-d.inf); + } + t.old = try t.a.alloc(f32, t.slots() * 128); + for (t.old) |*o| o.* = rng.float(f32); + t.ins[0] = try t.rig.input(std.mem.sliceAsBytes(t.q)); + t.ins[1] = try t.rig.input(std.mem.sliceAsBytes(t.k)); + t.ins[2] = try t.rig.input(std.mem.sliceAsBytes(t.val)); + t.outs[0] = try t.rig.output(t.slots() * 4); + t.outs[1] = try t.rig.output(t.slots() * 4); + t.outs[2] = try t.rig.output(t.slots() * 128 * 4); + return true; + } + + pub fn run(t: *Vec) !void { + @memcpy(t.rig.bytes(t.outs[2], t.slots() * 128 * 4), std.mem.sliceAsBytes(t.old)); + const p = t.plan(); + const e = t.rig.begin(); + e.e.setPipeline(t.pipe); + for (t.ins, 0..) |r, i| e.e.setBuffer(r.buf, r.off, i); + const Args = extern struct { rows: u32, pos0: u32, heads: u32, groups: u32, blocks: u32, chunk: u32, first: u32, scale: f32, hi: u32, window: u32, ring: u32, floor: u32 }; + e.e.setValue(Args{ .rows = @intCast(t.shape.rows), .pos0 = p.anchor, .heads = D.heads, .groups = D.kv, .blocks = p.blocks, .chunk = 128, .first = p.first, .scale = t.scale(), .hi = p.hi, .window = @intCast(t.shape.k), .ring = t.ring(), .floor = p.floor }, 3); + for (t.outs, 4..) |o, i| e.e.setBuffer(o.buf, o.off, i); + e.e.dispatchGroups(mtl.Size.of(D.kv, t.shape.rows, p.blocks), mtl.Size.of(32, D.heads / D.kv, 1)); + try t.rig.finish(e); + } + + pub fn count(t: *Vec) usize { + return t.slots() * 130; + } + + const Out = struct { want: []f64, allow: ?[]f64 = null, sim: ?Sim = null }; + + /// Every slot's (m, l, o) in float64 (fmax's NaN rule), and its allowance: spread, fast exp, the sums' chains. + fn outputs(t: *Vec, o: Out) !void { + const p = t.plan(); + const n = t.slots(); + const r: usize = t.ring(); + const G = D.heads / D.kv; + const sc: f64 = t.scale(); + for (o.want[2 * n ..], t.old) |*w, v| w.* = v; + if (o.allow) |al| @memset(al, 0); + var s: [128]f64 = undefined; + var e: [128]f64 = undefined; + var terms: [128]f64 = undefined; + for (0..D.heads) |h| for (0..t.shape.rows) |row| for (0..p.blocks) |z| { + const slot = (h * t.shape.rows + row) * p.blocks + z; + const pos = p.anchor + row; + const lo = @max(if (pos + 1 > t.shape.k) pos + 1 - t.shape.k else 0, p.floor); + const blk = p.first + z; + const from = @max(lo, blk * 128); + const to = @min(p.hi, blk * 128 + 128); + if (from >= to) { + o.want[slot] = -std.math.inf(f64); + o.want[n + slot] = 0; + continue; + } + const kv = h / G; + const keys = to - from; + var m: f64 = -std.math.inf(f64); + var least: f64 = std.math.inf(f64); + var big_e: f64 = 0; + for (0..keys) |i| { + const at = ((from + i) % r) * D.kv * 128 + kv * 128; + var abs: f64 = 0; + var sum: f64 = 0; + for (0..128) |j| { + terms[j] = sc * c.fromBf16(t.q[(row * D.heads + h) * 128 + j]) * c.fromBf16(t.k[at + j]); + sum += terms[j]; + abs += @abs(terms[j]); + } + s[i] = if (o.sim) |q| contract.rows.sumIn(q[0], q[1], &terms) else sum; + e[i] = if (t.fill == .stress) 0 else c.gamma(10, u) * abs; + big_e = @max(big_e, e[i]); + if (!std.math.isNan(s[i])) { + m = @max(m, s[i]); + least = @min(least, s[i]); + } + } + var l: f64 = 0; + var wabs: [128]f64 = @splat(0); + var po: [128]f64 = @splat(0); + var vmax: [128]f64 = @splat(0); + for (0..keys) |i| { + const w = @exp(s[i] - m); + l += w; + const at = ((from + i) % r) * D.kv * 128 + kv * 128; + for (&po, &wabs, 0..) |*y, *wa, j| { + const vv: f64 = c.fromBf16(t.val[at + j]); + y.* += w * vv; + wa.* += w * @abs(vv); + vmax[j] = @max(vmax[j], @abs(vv)); + } + } + o.want[slot] = m; + o.want[n + slot] = l; + for (po, 0..) |y, j| o.want[2 * n + slot * 128 + j] = y; + const al = o.allow orelse continue; + const steps: f64 = @floatFromInt((keys + 3) / 4); + const range = if (std.math.isFinite(m - least)) m - least else 0; + const rel = (@exp(2 * big_e) - 1) + (3 + 4 * range + 5 * steps) * u + c.gamma(@as(f64, @floatFromInt(keys)) + steps, u); + // Metal flushes subnormals: a weight or product under 2^-126 may be 0 + const flush = @as(f64, @floatFromInt(keys)) * 0x1p-126; + al[slot] = big_e + 0x1p-149; + al[n + slot] = rel * l + flush; + for (wabs, vmax, 0..) |wa, vm, j| al[2 * n + slot * 128 + j] = rel * wa + flush * (1 + vm); + }; + } + + pub fn reference(t: *Vec, want: []f64, mag: []f64) !void { + try t.outputs(.{ .want = want }); + @memset(mag, 0); + } + pub fn bounds(t: *Vec, _: []const f64, _: []const f64, allow: []f64) !void { + const want = try t.a.alloc(f64, t.count()); + defer t.a.free(want); + try t.outputs(.{ .want = want, .allow = allow }); + } + pub fn simulate(t: *Vec, acc: c.Accum, order: g.Order, out: []f64) !void { + try t.outputs(.{ .want = out, .sim = .{ acc, order } }); + } +}; diff --git a/zig/tests/contract/metal_ricursive_dflash2_pick.zig b/zig/tests/contract/metal_ricursive_dflash2_pick.zig new file mode 100644 index 00000000000..1aa9604d017 --- /dev/null +++ b/zig/tests/contract/metal_ricursive_dflash2_pick.zig @@ -0,0 +1,385 @@ +//! The drafter's picks under the contract: the chunked top-k (rc_df_topk) and the greedy walk (rc_df_walk), by rule. +const std = @import("std"); +const mtl = @import("metal"); +const contract = @import("contract"); +const rig_ = @import("rig.zig"); +const controls = @import("metal_ricursive_controls.zig"); +const d = @import("metal_ricursive_dflash2.zig"); + +const c = contract.spec; +const g = contract.gates; +const D = d.D; +const Mutation = d.Mutation; +const bf = d.bf; +const u = c.unit(.f32); +const Sim = struct { c.Accum, g.Order }; + +pub fn collect(s: *d.Suite, x: d.Ctx) !void { + for (std.enums.values(TopK.Variant)) |v| try s.add(x, TopK, v, .none); + try s.add(x, Walk, .walk, .none); +} + +/// The block's draft slots: rows 1-15 go through the head, the top-k and the walk. +const slots = D.block - 1; +/// dflash2.zig's passes: each 2,048-value chunk's best 32, then the chunks' bests twice more. +const chunks1 = (D.vocab + 2047) / 2048; +const chunks2 = (chunks1 * 32 + 2047) / 2048; + +// --- rc_df_topk: each 2,048-value chunk's best 32 (value desc, id asc) by a bitonic sort -------------------------- + +pub const TopK = struct { + /// The first pass over a row's logits, then the two passes over the chunks' bests (ids carried). + pub const Variant = enum { logits, bests, last }; + a: std.mem.Allocator, + rig: rig_.Rig, + pipe: mtl.Pipeline, + v: Variant, + m: Mutation, + shape: c.Shape = undefined, + l: []u16 = &.{}, + vin: []f32 = &.{}, + iin: []u32 = &.{}, + ins: [3]rig_.Ref = undefined, + outs: [2]rig_.Ref = undefined, + msg: [200]u8 = undefined, + + /// Rows: the draft slots; n: the values a row (k unused). + pub fn spec(v: Variant) c.Spec { + return .{ + .name = switch (v) { + .logits => "ricursive dflash2 rc_df_topk logits", + .bests => std.fmt.comptimePrint("ricursive dflash2 rc_df_topk {d} chunks' bests", .{chunks1}), + .last => std.fmt.comptimePrint("ricursive dflash2 rc_df_topk {d} chunk's bests", .{chunks2}), + }, + .accum = .none, + .depth = d.noSums, + .out = .raw, + .nan = .{ .stated = "finite rows: each chunk's 32 largest (value desc, id asc) as a host sort gives them; with NaN or infinities: the sorting network as Metal compares (NaN compares false), replayed bit for bit" }, + .tiles = .{ .{}, .{ .size = 2048, .step = 1, .min = 1 }, .{} }, + .served = switch (v) { + .logits => &.{.{ .rows = slots, .n = D.vocab, .k = 1 }}, + .bests => &.{.{ .rows = slots, .n = chunks1 * 32, .k = 1 }}, + .last => &.{.{ .rows = slots, .n = chunks2 * 32, .k = 1 }}, + }, + }; + } + + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, v: Variant, m: Mutation) !TopK { + return .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .pipe = try d.pipeline(device, a, "rc_df_topk", m), .v = v, .m = m }; + } + pub fn deinit(t: *TopK) void { + t.free(); + t.rig.deinit(); + t.pipe.deinit(); + } + fn free(t: *TopK) void { + inline for (.{ "l", "vin", "iin" }) |f| { + t.a.free(@field(t, f)); + @field(t, f) = &.{}; + } + } + pub fn kernel(t: *TopK) g.Kernel { + return controls.mark(.{ .spec = spec(t.v), .ctx = t, .vt = &vt }, t.m); + } + const vt = g.hooks(TopK); + + fn chunks(t: *const TopK) usize { + return (t.shape.n + 2047) / 2048; + } + fn fromIds(t: *const TopK) bool { + return t.v != .logits; + } + + pub fn prepare(t: *TopK, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.rows == 0 or shape.n == 0) return false; + t.rig.reset(); + t.free(); + t.shape = shape; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + const n = shape.rows * shape.n; + t.l = try t.a.alloc(u16, if (t.fromIds()) 1 else n); + t.vin = try t.a.alloc(f32, if (t.fromIds()) n else 1); + t.iin = try t.a.alloc(u32, if (t.fromIds()) n else 1); + // coarse logits, so equal values occur and ids must break the ties + for (t.l) |*x| x.* = c.toBf16(@as(f32, @floatFromInt(rng.uintLessThan(u32, 512))) / 16 - 16); + for (t.vin) |*x| x.* = @as(f32, @floatFromInt(rng.uintLessThan(u32, 512))) / 16 - 16; + for (t.iin, 0..) |*x, i| x.* = @intCast((i % shape.n) * 61 % D.vocab); + if (fill == .nonfinite) for ([_]f32{ d.nan, d.inf, -d.inf, d.nan }, 0..) |x, k| { + const i = (k % shape.rows) * shape.n + (k * 37) % shape.n; + if (t.fromIds()) t.vin[i] = x else t.l[i] = c.toBf16(x); + }; + t.ins[0] = try t.rig.input(std.mem.sliceAsBytes(t.l)); + t.ins[1] = try t.rig.input(std.mem.sliceAsBytes(t.vin)); + t.ins[2] = try t.rig.input(std.mem.sliceAsBytes(t.iin)); + t.outs[0] = try t.rig.output(shape.rows * t.chunks() * 32 * 4); + t.outs[1] = try t.rig.output(shape.rows * t.chunks() * 32 * 4); + return true; + } + + pub fn run(t: *TopK) !void { + const p = t.rig.begin(); + p.e.setPipeline(t.pipe); + for (t.ins, 0..) |r, i| p.e.setBuffer(r.buf, r.off, i); + p.e.setValue([4]u32{ @intCast(t.shape.n), @intCast(t.shape.n), @intCast(t.chunks()), @intFromBool(t.fromIds()) }, 3); + p.e.setBuffer(t.outs[0].buf, t.outs[0].off, 4); + p.e.setBuffer(t.outs[1].buf, t.outs[1].off, 5); + p.e.dispatchGroups(mtl.Size.of(t.chunks(), t.shape.rows, 1), mtl.Size.of(1024, 1, 1)); + try t.rig.finish(p); + } + + pub fn count(t: *TopK) usize { + return 2 * t.shape.rows * t.chunks() * 32 * 4; + } + pub fn reference(_: *TopK, _: []f64, _: []f64) !void { + return error.CheckedByItsOwnRule; + } + + 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); + } + + pub fn check(t: *TopK, _: g.Gate) !?[]const u8 { + const vals = std.mem.bytesAsSlice(f32, t.rig.bytes(t.outs[0], t.count() / 2)); + const ids = std.mem.bytesAsSlice(u32, t.rig.bytes(t.outs[1], t.count() / 2)); + const buf = try t.a.alloc(P, 2048); + defer t.a.free(buf); + for (0..t.shape.rows) |r| for (0..t.chunks()) |ch| { + var finite = true; + for (buf, 0..) |*x, i| { + const at = ch * 2048 + i; + x.* = if (at < t.shape.n) .{ .v = if (t.fromIds()) t.vin[r * t.shape.n + at] else c.fromBf16(t.l[r * t.shape.n + at]), .id = if (t.fromIds()) t.iin[r * t.shape.n + at] else @intCast(at) } else .{ .v = -std.math.inf(f32), .id = 0xffffffff }; + if (at < t.shape.n and !std.math.isFinite(x.v)) finite = false; + } + if (finite) std.sort.pdq(P, buf, {}, first) else { + var k: usize = 2; + while (k <= 2048) : (k <<= 1) { + var j = k >> 1; + while (j > 0) : (j >>= 1) for (0..2048) |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]); + }; + } + } + const o = (r * t.chunks() + ch) * 32; + for (buf[0..32], vals[o..][0..32], ids[o..][0..32], 0..) |want, gv, gi, i| { + if ((@as(u32, @bitCast(want.v)) != @as(u32, @bitCast(gv)) and !(std.math.isNan(want.v) and std.math.isNan(gv))) or want.id != gi) + return try std.fmt.bufPrint(&t.msg, "row {d} chunk {d} place {d}: ({d}, {d}) where the host has ({d}, {d})", .{ r, ch, i, gv, gi, want.v, want.id }); + } + }; + return null; + } +}; + +// --- rc_df_walk: the selector's greedy path through each slot's top candidates ---------------------------------- + +pub const Walk = struct { + pub const Variant = enum { walk }; + /// The vocabulary only bounds ids (and clamps B's row); 8,192 rows keep A and B small. + const vocab = 8192; + const top = D.top; + /// seq: the pending token, a slot's draft each, and a tail the kernel must leave alone. + const seq_len = 20; + a: std.mem.Allocator, + rig: rig_.Rig, + pipe: mtl.Pipeline, + m: Mutation, + shape: c.Shape = undefined, + fill: g.Fill = .random, + uv: []f32 = &.{}, + ui: []u32 = &.{}, + h: []u16 = &.{}, + pa: []u16 = &.{}, + pb: []u16 = &.{}, + seq: [seq_len]u32 = undefined, + ins: [5]rig_.Ref = undefined, + out: rig_.Ref = undefined, + msg: [200]u8 = undefined, + + /// Rows: the draft slots; n: candidates a slot; k: the selector's rank. + pub fn spec(_: Variant) c.Spec { + return .{ + .name = "ricursive dflash2 rc_df_walk", + .accum = .f32, + .depth = walkDepth, + .out = .raw, + .nan = .{ .stated = "each slot takes the first candidate with the largest score (a NaN never wins; ids past the vocabulary are skipped), within near ties of float64, and walks on from the id it took" }, + .tiles = .{ .{}, .{}, .{} }, + .served = &.{ .{ .rows = slots, .n = top, .k = D.rank }, .{ .rows = 1, .n = top, .k = D.rank } }, + }; + } + /// A product, a 5-level simd_sum, the 8 simdgroups' parts in turn after the unary score. + fn walkDepth(_: c.Shape) usize { + return 15; + } + + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, _: Variant, m: Mutation) !Walk { + return .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .pipe = try d.pipeline(device, a, "rc_df_walk", m), .m = m }; + } + pub fn deinit(t: *Walk) void { + t.free(); + t.rig.deinit(); + t.pipe.deinit(); + } + fn free(t: *Walk) void { + inline for (.{ "uv", "ui", "h", "pa", "pb" }) |f| { + t.a.free(@field(t, f)); + @field(t, f) = &.{}; + } + } + pub fn kernel(t: *Walk) g.Kernel { + return controls.mark(.{ .spec = spec(.walk), .ctx = t, .vt = &vt }, t.m); + } + const vt = g.hooks(Walk); + + pub fn prepare(t: *Walk, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.rows == 0 or shape.rows > slots or shape.n != top or shape.k != D.rank) return false; + t.rig.reset(); + t.free(); + t.shape = shape; + t.fill = fill; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + const k = shape.k; + const s = shape.rows; + t.uv = try t.a.alloc(f32, s * top); + t.ui = try t.a.alloc(u32, s * top); + t.h = try t.a.alloc(u16, s * k); + t.pa = try t.a.alloc(u16, vocab * k); + t.pb = try t.a.alloc(u16, vocab * k); + for (t.uv) |*x| x.* = rng.float(f32) * 4 - 2; + for (0..s) |e| { + // distinct candidates, the last two past the vocabulary (the top-k's padding and the vocabulary's end) + for (t.ui[e * top ..][0..top], 0..) |*x, cnd| x.* = @intCast((e * 977 + cnd * 251) % vocab); + t.ui[e * top + top - 1] = 0xffffffff; + t.ui[e * top + top - 2] = vocab; + } + d.fillBf(rng, t.h, -1, 1); + d.fillBf(rng, t.pa, -1, 1); + d.fillBf(rng, t.pb, -1, 1); + if (fill == .stress) { + // A integers times H = 1 (exact bf16 products), B's halves mirrored: partials near 2^21, small scores + @memset(t.h, c.toBf16(1)); + for (0..vocab) |r| for (0..k / 2) |j| { + t.pa[r * k + j] = c.toBf16(@floatFromInt(@as(i32, @intCast(rng.uintLessThan(u32, 256))) - 128)); + t.pa[r * k + k / 2 + j] = t.pa[r * k + j]; + const b: f32 = @floatFromInt(64 + rng.uintLessThan(u32, 64)); + t.pb[r * k + j] = c.toBf16(b); + t.pb[r * k + k / 2 + j] = c.toBf16(-b + (if (j < 4) @as(f32, @floatFromInt(rng.uintLessThan(u32, 3))) - 1 else 0)); + }; + for (t.uv) |*x| x.* = @floatFromInt(rng.uintLessThan(u32, 8)); + } + if (fill == .nonfinite) { + t.uv[0 * top + 3] = d.nan; + if (s > 1) t.uv[1 * top + 5] = d.inf; + if (s > 2) t.uv[2 * top + 7] = -d.inf; + } + @memset(&t.seq, 0); + t.seq[0] = 1234; + t.ins[0] = try t.rig.input(std.mem.sliceAsBytes(t.uv)); + t.ins[1] = try t.rig.input(std.mem.sliceAsBytes(t.ui)); + t.ins[2] = try t.rig.input(std.mem.sliceAsBytes(t.h)); + t.ins[3] = try t.rig.input(std.mem.sliceAsBytes(t.pa)); + t.ins[4] = try t.rig.input(std.mem.sliceAsBytes(t.pb)); + t.out = try t.rig.output(t.seq.len * 4); + return true; + } + + pub fn run(t: *Walk) !void { + @memcpy(t.rig.bytes(t.out, t.seq.len * 4), std.mem.sliceAsBytes(&t.seq)); + const p = t.rig.begin(); + p.e.setPipeline(t.pipe); + for (t.ins, 0..) |r, i| p.e.setBuffer(r.buf, r.off, i); + p.e.setValue([4]u32{ @intCast(t.shape.rows), @intCast(t.shape.k), top, vocab }, 5); + p.e.setBuffer(t.out.buf, t.out.off, 6); + p.e.dispatchGroups(mtl.Size.of(1, 1, 1), mtl.Size.of(t.shape.k, 1, 1)); + try t.rig.finish(p); + } + + pub fn count(t: *Walk) usize { + return t.seq.len * 4; + } + + /// Slot e's bf16(unary + bf16(pair)) after `prev` (pair in float64 or simulated); bounds add two bf16 roundings. + fn scores(t: *const Walk, e: usize, prev: u32, sim: ?Sim, out: *[top]f64, bnd: *[top]f64) void { + const k = t.shape.k; + var terms: [D.rank]f64 = undefined; + for (0..top) |cnd| { + const id = t.ui[e * top + cnd]; + const row = @min(id, vocab - 1); + var abs: f64 = 0; + var sum: f64 = 0; + for (0..k) |r| { + const ah = bf(@as(f64, c.fromBf16(t.pa[@as(usize, prev) * k + r])) * c.fromBf16(t.h[e * k + r])); + terms[r] = ah * c.fromBf16(t.pb[@as(usize, row) * k + r]); + sum += terms[r]; + abs += @abs(terms[r]); + } + const pair = if (sim) |o| contract.rows.sumIn(o[0], o[1], terms[0..k]) else sum; + const unary = t.uv[e * top + cnd]; + out[cnd] = bf(unary + bf(pair)); + const err = c.gamma(15, u) * abs; + bnd[cnd] = if (t.fill == .stress or sim != null) 0 else err + 0x1p-7 * (@abs(unary) + 2 * (abs + err)); + } + } + + /// The kernel's choice on float64 scores: the first candidate strictly above all before it, valid ids only. + fn choose(t: *const Walk, e: usize, s: *const [top]f64) usize { + var best = -std.math.inf(f64); + var bi: usize = 0; + for (0..top) |cnd| if (t.ui[e * top + cnd] < vocab and s[cnd] > best) { + best = s[cnd]; + bi = cnd; + }; + return bi; + } + + fn walk(t: *Walk, sim: ?Sim) [seq_len]u32 { + var seq = t.seq; + var s: [top]f64 = undefined; + var b: [top]f64 = undefined; + for (0..t.shape.rows) |e| { + t.scores(e, seq[e], sim, &s, &b); + seq[1 + e] = t.ui[e * top + t.choose(e, &s)]; + } + return seq; + } + + /// Raw outputs: the seq buffer's bytes as the replay leaves them (gate 4's stress has no near ties). + pub fn reference(t: *Walk, want: []f64, mag: []f64) !void { + const seq = t.walk(null); + for (want, std.mem.sliceAsBytes(&seq)) |*w, byte| w.* = @floatFromInt(byte); + @memset(mag, 0); + } + pub fn simulate(t: *Walk, acc: c.Accum, order: g.Order, out: []f64) !void { + const seq = t.walk(.{ acc, order }); + for (out, std.mem.sliceAsBytes(&seq)) |*w, byte| w.* = @floatFromInt(byte); + } + pub fn bounds(_: *Walk, _: []const f64, _: []const f64, allow: []f64) !void { + @memset(allow, 0); + } + + /// Each slot's id: a candidate tied near float64's choice (it, off finite scores), the walk going on from it. + pub fn check(t: *Walk, _: g.Gate) !?[]const u8 { + const got = std.mem.bytesAsSlice(u32, t.rig.bytes(t.out, t.count())); + if (got[0] != t.seq[0]) return try std.fmt.bufPrint(&t.msg, "seq[0] changed", .{}); + for (t.seq[t.shape.rows + 1 ..], got[t.shape.rows + 1 ..]) |w, x| if (w != x) return try std.fmt.bufPrint(&t.msg, "it wrote past its slots", .{}); + var s: [top]f64 = undefined; + var b: [top]f64 = undefined; + for (0..t.shape.rows) |e| { + t.scores(e, got[e], null, &s, &b); + const w = t.choose(e, &s); + const id = got[1 + e]; + const cand = for (0..top) |cnd| { + if (t.ui[e * top + cnd] == id) break cnd; + } else return try std.fmt.bufPrint(&t.msg, "slot {d} took {d}, not one of its candidates", .{ e, id }); + if (cand == w) continue; + if (!std.math.isFinite(s[w]) or !std.math.isFinite(s[cand]) or id >= vocab or !(s[cand] >= s[w] - b[cand] - b[w])) + return try std.fmt.bufPrint(&t.msg, "slot {d} took candidate {d} ({d}) where float64 takes {d} ({d})", .{ e, cand, s[cand], w, s[w] }); + } + return null; + } +};