diff --git a/CHANGELOG.md b/CHANGELOG.md index 5f792a9b172..c5e13c84c8d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -117,6 +117,8 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - The native server takes `--decode-share X` (0 to under 1) instead of refusing it: while a long prompt fills beside running replies, the replies get X of each fill step's time, the same time share `TENSORFOLD_PREFILL_SHARE` sets from the prompt's side (#1327, for #840). It works on the CUDA, Metal and HIP lane servers; DeepSeek, Spark-X on Metal, Qwen4 and the XPU servers ignore it. No model's prompt chunks change size: the flag can also cap a filling prompt's chunks at 512 rows, but that stays off for every model until it is shown to give the same tokens at any cut. Without the flag nothing changes. Thanks to @javierbits and @simon-lin88. +- MiniMax-M3.1-Flash on Metal: the new `minimax_m3` family serves MiniMax's 428B-A23B model (`minimax_m3_vl`, its own `config.json`) on one 256 GB M5 Ultra, with tools, structured output, thinking on or off, images, the prompt cache, two streams and DFlash2 or DSpark drafts that keep replies equal to plain decoding. It reads two community checkpoints, lossy conversions of MiniMax's NVFP4 release, labelled with their cost against it (mean KL 0.244 on mix34, 0.295 on mix256k); everything from those weights on is exact, with a bf16 key/value cache (147,456 tokens on mix256k, 32,768 on mix34). Measured on the M5 Ultra with DFlash2, one stream decodes 44-58 tokens a second on mix256k. `MINIMAX_LOAD_LIMIT_GB` sets the memory budget and `MINIMAX_DRAFTER` picks the drafter (#1235, for #1519). Thanks to @BobClawblaw. + - [The runbook](RUNBOOK.md#prompt-prefill-share-and-budget) documents `TENSORFOLD_PREFILL_SHARE` and `TENSORFOLD_PREFILL_BUDGET`: what each accepts, its default, and how it trades a long prompt's finish against decoding streams' next rounds. - Flash Next on CUDA drafts a shared round's sampled streams in the batched MTP head pass too, each lane's draft drawn on the host under its own keyed rule from its own row of the pass, the draw its lone pick makes, so drafts and replies are unchanged. On a GB10 at 5 x 131,072, sampled code and chat requests decode 24% and 19% faster in aggregate at 5 streams (15% and 19% at 4), greedy cells and time to first token unchanged, every concurrent reply equal to its lone run. `TF_FLASHNEXT_SAMPLED_HEADS=0` restores drafting those streams one at a time. The parity checker covers sampled and mixed shapes. Receipt: `docs/receipts/flashnext-cuda-sampled-heads/`. diff --git a/README.md b/README.md index 74e635291e7..e5ffce6dee6 100644 --- a/README.md +++ b/README.md @@ -179,6 +179,7 @@ Conversions are explicitly marked: their upstream weights need the linked conver | Gemma 4 31B, MLX 4-bit | `tensorfold pull mlx-community/gemma-4-31B-it-4bit@696d436c404745a59f30e4939a658162b0a9e57f`
`tensorfold pull z-lab/gemma-4-31B-it-DFlash@eabd648301ce28583cc14757912e5e0f84e152e1` | One M5 Mac; M5 Ultra checked. M1-M4 refused. | [Native 31B](docs/recipes/gemma-4-native.md). Name the drafter with `--drafter`; images with `--vision`. | | Gemma 4 12B, converted MLX 4-bit | `hf download google/gemma-4-12B-it --revision 707f0a3b8a3c7ad586ed01e27eafbad8a27dd0f7 --local-dir ~/models/gemma-4-12b-hf`
`hf download google/gemma-4-12B-it-assistant --revision 46d4c6f13f0ac0ad827b915669b8df9b81c64c51 --local-dir ~/models/gemma-4-12b-assistant` | One M5 Mac; converted text weights 6.3 GB, image weights 100 MB, plus assistant/caches. M1-M4 refused. | [Convert and serve](docs/recipes/gemma-4-12b-native.md). Upstream download needs `hf`; conversion needs Python, mlx and mlx-lm. Serving is native. | | Step-5-Preview, converted affine | `hf download stepfun-ai/Step-5-Preview --local-dir ~/models/step5-preview-fp8` | One 256 GB Mac; text 166.9 GiB, MTP adds 2.5 GiB and vision 3.7 GiB. | [Convert and serve](docs/recipes/step-5-preview.md). The documented 256 GB setup serves converted affine weights; converting the upstream FP8 download needs Python and mlx. | +| MiniMax-M3.1-Flash, community affine 3/4-bit | `hf download BobClawblaw/MiniMax-M3.1-Flash-MLX-mix34 --revision 9524999057e0d277d26438606e033e2191fb465c --local-dir ~/models/MiniMax-M3.1-Flash-MLX-mix34`
`hf download BobClawblaw/MiniMax-M3.1-Flash-MLX-mix256k --revision 916e7ca1044f1c3e7566163096243c940327224d --local-dir ~/models/MiniMax-M3.1-Flash-MLX-mix256k` | One 256 GB M5 Ultra; 203.7 GiB (32,768-token window) or 189.2 GiB (147,456), plus caches. | [MiniMax-M3.1-Flash](docs/recipes/minimax-m3.1-flash.md). Set `MINIMAX_LOAD_LIMIT_GB`; images with `--vision`. Community checkpoints: lossy conversions of MiniMax's NVFP4 release (KL 0.244 / 0.295). MiniMax Community License. | | Kolibri-1, block FP8 (research) | `tensorfold pull Aleph-Alpha/Kolibri-1@e52eb4627d11516b0c01de49210ab5a4e4061444` | One NVIDIA GPU; GB10 measured; 74 GB checkpoint. | [Kolibri](docs/recipes/kolibri-1.md). Text only; copy drafts, no EAGLE-3/neural drafter. | | Liquid AI d1-3B, decisions | Not documented yet. | Native CUDA; RAM minimum not published. | [API section below](#serve-flags). `/v1/systemone` and `/v1/decisions`. | | Fish Audio Drama 3, speech | Not documented yet. | Native Metal or CUDA; GB10 measured. | [Release audio instructions](CHANGELOG.md#110), [reference voices and dialogue speakers](docs/drama-http-voices.md). `/v1/audio/speech` with [sampling controls](docs/speech-sampling.md); checkpoint and `codec.pth` required. | diff --git a/docs/recipes/README.md b/docs/recipes/README.md index 80171243888..8d38798aedc 100644 --- a/docs/recipes/README.md +++ b/docs/recipes/README.md @@ -21,6 +21,7 @@ For agent-assisted contributions, read the [TensorFold contributor skill](SKILL. | DeepSeek-V4-Flash | [MLX on a 256 GB Mac, DSpark and MTP drafts](deepseek-v4-flash.md) | | Qwen3.6-35B-A3B | [MLX with MTP drafts, one-GPU CUDA](qwen3.6-moe.md) | | Step-5-Preview | [Native Metal on one 256 GB Mac: 2-bit experts, MTP drafts, images](step-5-preview.md) | +| MiniMax-M3.1-Flash | [Native Metal on one 256 GB Mac: affine 3/4-bit experts, exact bf16 cache, DFlash2 drafts, images](minimax-m3.1-flash.md) | | Kolibri-1 | [Native CUDA, block FP8, research checkpoint](kolibri-1.md) | | LFM2.5-24B-A2B | [Native Metal, MLX 4-bit, shared rounds](lfm2.5-24b-a2b.md) | | Spark-X2.6-4B | [Native CUDA](spark-x2.6-4b-cuda.md), [native Metal, the bf16 release, contexts to 1M](spark-x2.6-4b-metal.md) | diff --git a/docs/recipes/minimax-m3.1-flash.md b/docs/recipes/minimax-m3.1-flash.md new file mode 100644 index 00000000000..9e27f63536b --- /dev/null +++ b/docs/recipes/minimax-m3.1-flash.md @@ -0,0 +1,71 @@ +# MiniMax-M3.1-Flash on Metal (one 256 GB M5 Ultra) + +The `minimax_m3` family serves [MiniMax-M3.1-Flash](https://huggingface.co/MiniMaxAI/MiniMax-M3.1-Flash), a +428B-A23B mixture of experts with block-sparse attention (a lightning indexer picks each row's key blocks) and a +CLIP vision tower, on the lane host: tools, structured output, thinking on or off, images, the prompt cache, two +streams, and drafts from the release's DSpark head or incoai's DFlash2. + +MiniMax's release stores its experts in NVFP4 and the rest in MXFP8; as published it takes about 248 GB, more than a +256 GB Mac can give a model. The family reads MLX-style affine groups instead, from two community checkpoints: +lossy conversions of the release, published with its own `config.json` (`minimax_m3_vl`, the language model under +`text_config`), the MLX `quantization` block in place of the release's, and the drafters' weights: + +| checkpoint | experts | on disk | window on 256 GB | +| --- | --- | ---: | ---: | +| [`BobClawblaw/MiniMax-M3.1-Flash-MLX-mix34`](https://huggingface.co/BobClawblaw/MiniMax-M3.1-Flash-MLX-mix34) | 4-bit (g128) on 26 of 60 layers, 3-bit (g64) on the rest | 203.7 GiB | 32,768 | +| [`BobClawblaw/MiniMax-M3.1-Flash-MLX-mix256k`](https://huggingface.co/BobClawblaw/MiniMax-M3.1-Flash-MLX-mix256k) | 4-bit on 3 layers, 3-bit on the rest | 189.2 GiB | 147,456 | + +Attention, the shared expert, the dense layers and the head are 8-bit in both; both carry the DSpark and DFlash2 +weights. Against the release's own weights (1,024 positions teacher-forced, bf16 cache) the conversion costs a mean KL +of 0.244 (80.7% top-1) on mix34 and 0.295 (78.4%) on mix256k. Everything the engine does from the converted weights on +is exact. The key/value cache is bf16: under the 226 GB limit below its caches fit 150,400 tokens on mix256k and 37,376 +on mix34. The +[serving recipe](https://github.com/BobClawblaw/minimax-m31-flash-mlx-m5-ultra) has the conversion's studies. + +TensorFold's code is Apache-2.0. MiniMax-M3.1-Flash's weights, and these checkpoints made from them, have the MiniMax +Community License: free for non-commercial use; commercial use must show "Built with MiniMax M3.1-Flash" and notify +MiniMax, with its written authorization above US$20 million yearly revenue; its appendix lists prohibited uses. +incoai's DFlash2 drafter, carried in both checkpoints, is Apache-2.0, as its +[model card](https://huggingface.co/incoai/MiniMax-M3.1-Flash-DFlash2/blob/ac07a7c1ecaae26a7ace595756124dca974b432d/README.md) +states at the revision converted (`ac07a7c1`); the release's DSpark head is under MiniMax's licence with the rest. + +## Run + +```sh +hf download BobClawblaw/MiniMax-M3.1-Flash-MLX-mix34 --revision 9524999057e0d277d26438606e033e2191fb465c \ + --local-dir ~/models/MiniMax-M3.1-Flash-MLX-mix34 +MINIMAX_LOAD_LIMIT_GB=226 tensorfold serve ~/models/MiniMax-M3.1-Flash-MLX-mix34 \ + --context 32768 --parallel 2 --prompt-cache-gib 4 --vision +``` + +For mix256k (revision `916e7ca1044f1c3e7566163096243c940327224d`), `--context 147456`. + +- `MINIMAX_LOAD_LIMIT_GB` bounds weights, scratch and caches together. The default (75% of RAM) holds the weights + but no caches, so set it; at 226 a 145,203-token prompt on mix256k peaked at 210 GiB wired. +- The cache takes 135 KiB a token across the 60 layers; `--parallel 2` streams share it. +- `MINIMAX_DRAFTER`: `dflash2` (the default) or `dspark`; any other value is refused. `--no-drafts` decodes plainly. +- Thinking off ends the prompt with ``, as the model does when it chooses not to think. Tool calls use + MiniMax's `]<]minimax[>[` markup, parsed into OpenAI `tool_calls`; `tool_choice: required` or a named tool is + constrained in that markup (xgrammar's `minimax_m3_xml`). +- Images: at most 576 tokens an image (672 x 672, the release processor's `max_pixels`); larger images are scaled + down. Each image is its own tower pass. No video. + +## Checks (Apple M5 Ultra, 256 GB, macOS 27) + +- Four layers against transformers' own model: KL at most 0.005. The full model against an MLX reference at the same + weights: KL 0.015. +- 1,024 rows teacher-forced against the release's NVFP4 weights: mix34 KL 0.244 (80.7% top-1), mix256k 0.295 (78.4%). +- Drafted replies equal plain ones (DFlash2 and DSpark); windows equal one-row steps bit for bit; two streams' + replies equal their runs alone; replies are equal with the prompt cache on and off. +- A needle at 145,203 tokens on mix256k (115 s cold; 210 GiB wired at the peak). The tower against transformers': + relative error 0.030 to fp32 (torch bf16: 0.039). +- Decode with DFlash2, one stream (prose / code / structured / list): mix256k 44.0 / 55.8 / 47.8 / 50.9 tokens a + second, mix34 41.2 / 61.3 / 49.3 / 55.3. Cold prompts on mix256k: 1,478 tokens a second at 8,403 tokens, 1,486 at + 16,598 and 1,484 at 30,929 (4,096-row chunks); 1,379 at 128k before the kernel fixes. +- The family's 50 Metal kernels are registered with the kernel contract: 50 pass gates 1-4. + +## Not covered + +- Only the M5's tensor units were checked; nothing smaller than 256 GB holds the weights. +- The release itself: serving it exactly needs native NVFP4/MXFP8 kernels on Metal and a Mac that holds about 248 GB. +- Video input. diff --git a/zig/build/metal_targets.zig b/zig/build/metal_targets.zig index efa248606d2..5bac04a9b01 100644 --- a/zig/build/metal_targets.zig +++ b/zig/build/metal_targets.zig @@ -329,6 +329,8 @@ pub fn metalTargets(b: *std.Build, target: std.Build.ResolvedTarget, optimize: s .{ .name = "tf-gemma4-bench", .path = "zig/tests/gemma4/bench.zig", .about = "Gemma 4 dense step costs: projections alone by rows against whole forwards" }, .{ .name = "tf-gemma4-no-tensor", .path = "zig/tests/gemma4/no_tensor.zig", .about = "Gemma 4's Metal kernels on a Mac without tensor units: what builds, and the row path's bits" }, .{ .name = "tf-spark-run", .path = "zig/tests/spark25/run.zig", .about = "Spark2.5 on Metal: greedy tokens, every position's logits or a prompt's last logits, for the reference's check" }, + .{ .name = "tf-minimax-run", .path = "zig/tests/minimax_m3/run.zig", .about = "MiniMax-M3.1-Flash greedy tokens, every position's logits or a prompt's last logits, for the reference's check" }, + .{ .name = "tf-minimax-vision", .path = "zig/tests/minimax_m3/vision.zig", .about = "MiniMax-M3.1-Flash's image tower alone: an image's patches and text rows, for tools/vision_ref.py's check" }, .{ .name = "tf-qwen36-row-seam", .path = "zig/tests/qwen36_row_seam.zig", .about = "Model-free fixture: the row projection's bias sums stay fp32 at every width" }, }; for (engine_programs) |p| { diff --git a/zig/kernels/metal/minimax_m3/attention_nax.metal b/zig/kernels/metal/minimax_m3/attention_nax.metal new file mode 100644 index 00000000000..258d4cb01b9 --- /dev/null +++ b/zig/kernels/metal/minimax_m3/attention_nax.metal @@ -0,0 +1,218 @@ +// MiniMax-M3's prompt attention on the tensor units: each row attends the 128-key blocks its bitmap keeps. +#include "../nax.h" +using namespace tfp; + +// Defines: DH, NQ, G (query heads a key head), KVH, WORDS (bitmap words a row and head), SCALE. + +constant constexpr int LD = KVH * DH; +constant constexpr float kMasked = -3.402823466e+38f; +constant constexpr float kLog2e = 1.44269504089f; + +// Row max (MAX) or sum over a fragment's 32 columns into r[0], r[1] (rows home.y, home.y + 8). +template +inline void fold(thread const frag& f, thread float* r) { + TF_UNROLL + for (short h = 0; h < 2; h++) { + const short b = 4 * h; + float t = MAX ? max(max(f[b], f[b + 1]), max(f[b + 2], f[b + 3])) : (f[b] + f[b + 1]) + (f[b + 2] + f[b + 3]); + const float u = simd_shuffle_xor(t, ushort(1)); + t = MAX ? max(t, u) : t + u; + const float w = simd_shuffle_xor(t, ushort(8)); + t = MAX ? max(t, w) : t + w; + r[h] = MAX ? max(r[h], t) : r[h] + t; + } +} + +constant constexpr int RT = 32; // query rows a tile +constant constexpr int NS = DH / 64; // simdgroups a tile, each its own 64 output columns +constant constexpr int KS = 32; // keys a simdgroup a block +constant constexpr int BKT = KS * NS; // keys a block +constant constexpr int PH = BKT < 128 ? BKT : 128; // keys whose probabilities cross threadgroup memory at once +constant constexpr int PP = PH + 8; // the probabilities' row pitch +using PT = float; + +template +inline frag blk(const device T* p, int ld, int r, int c, short2 home) { +#ifndef TF_SIMD_FRAGS + const device T* q = p + (r + home.y) * ld + c + home.x; + return frag(bfloat4(*(const device vec*)q), bfloat4(*(const device vec*)(q + 8 * ld))); +#else + frag f; + if (TR) { + frag_get_t(f, p, ld, r, c, home); + } else { + frag_get(f, p, ld, r, c, home); + } + return f; +#endif +} + +inline frag prob_frag(const threadgroup PT* pt, int r, int c, short2 home) { +#ifndef TF_SIMD_FRAGS + const threadgroup PT* q = pt + (r + home.y) * PP + c + home.x; + return frag(*(const threadgroup vec*)q, *(const threadgroup vec*)(q + 8 * PP)); +#else + frag f; + frag_get(f, pt, PP, r, c, home); + return f; +#endif +} + +inline void prob_put(threadgroup PT* pt, int r, int c, short2 home, thread const frag& s) { +#ifndef TF_SIMD_FRAGS + threadgroup PT* q = pt + (r + home.y) * PP + c + home.x; + *(threadgroup vec*)q = vec(s[0], s[1], s[2], s[3]); + *(threadgroup vec*)(q + 8 * PP) = vec(s[4], s[5], s[6], s[7]); +#else + TF_UNROLL + for (short e = 0; e < 8; e++) pt[(r + home.y + (e >> 2) * 8) * PP + c + home.x + TF_COL(e)] = PT(s[e]); +#endif +} + +// Q, O [R, NQ, DH] at P.y..; K, V the cache; SEL: a row's key head keeps block b; a tile: G heads on RT / G rows. +[[max_total_threads_per_threadgroup(256)]] +[[kernel]] void mm_prompt_attention(const device bfloat* Q [[buffer(0)]], const device bfloat* K [[buffer(1)]], + const device bfloat* V [[buffer(2)]], device bfloat* O [[buffer(3)]], + constant int2& P [[buffer(4)]], const device uint* SEL [[buffer(5)]], + uint sg [[simdgroup_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]], uint3 tg [[threadgroup_position_in_grid]]) { + static_assert(G == 16, "a 16-row fragment is one row's query heads"); + const int R = P.x, p0 = P.y; + const int kv = int(tg.y); + const int r0 = int(tg.x) * (RT / G); + const int t_rows = min(RT / G, R - r0); // positions in the tile + const int qs = NQ * DH; + const device bfloat* q = Q + r0 * qs + kv * G * DH; + const device bfloat* kc = K + kv * DH; + const device bfloat* vc = V + kv * DH + int(sg) * 64; + const short2 home = frag_home(ushort(lane)); + threadgroup PT pt[RT * PP]; + threadgroup float rowmax[NS][RT]; + frag acc[8]; + TF_UNROLL + for (short i = 0; i < 8; i++) acc[i] = frag(0); + float top[4] = {kMasked, kMasked, kMasked, kMasked}, total[4] = {0.0f, 0.0f, 0.0f, 0.0f}; + const int first_pos = p0 + r0, last_pos = p0 + r0 + t_rows - 1; // the tile's last key + const device uint* sel = SEL + long(r0) * KVH * WORDS + kv * WORDS; + for (int kb = 0; kb <= last_pos / BKT; kb++) { + const int ib = kb * BKT / 128; // the index block of these keys + bool any = false; + for (int r = 0; r < t_rows; r++) any = any || ((sel[long(r) * KVH * WORDS + ib / 32] >> (ib % 32)) & 1u); + if (!any) continue; // uniform across the threadgroup: every thread reads the same words + bool kept[4]; + TF_UNROLL + for (short j = 0; j < 4; j++) { + const int rl = (home.y + 8 * j) / G; + kept[j] = rl < t_rows && ((sel[long(rl) * KVH * WORDS + ib / 32] >> (ib % 32)) & 1u); + } + const int kpos = kb * BKT + int(sg) * KS; + const device bfloat* kblk = kc + long(kpos) * LD; + frag s[4]; + TF_UNROLL + for (short i = 0; i < 4; i++) s[i] = frag(0); + for (int d = 0; d < DH / 16; d++) { + const frag k0 = blk(kblk, LD, 0, 16 * d, home); + const frag k1 = blk(kblk, LD, 16, 16 * d, home); + TF_UNROLL + for (short h = 0; h < 2; h++) { // a row past t_rows reads inside the chunk's buffer; its outputs stay unwritten + const frag qf = blk(q + h * qs, DH, 0, 16 * d, home); + mma_16x32(s[2 * h], s[2 * h + 1], qf, k0, k1); + } + } + TF_UNROLL + for (short i = 0; i < 4; i++) { + TF_UNROLL + for (short e = 0; e < 8; e++) { + const int local = 16 * (i >> 1) + home.y + (e >> 2) * 8, row = first_pos + local / G; + const int col = kpos + 16 * (i & 1) + home.x + TF_COL(e); + const bool out = col > row || !kept[2 * (i >> 1) + (e >> 2)]; + s[i][e] = out ? kMasked : s[i][e] * (SCALE * kLog2e); + } + } + float top_new[4] = {top[0], top[1], top[2], top[3]}; + TF_UNROLL + for (short i = 0; i < 4; i++) fold(s[i], top_new + 2 * (i >> 1)); + if (home.x == 0) { + TF_UNROLL + for (short j = 0; j < 4; j++) rowmax[sg][home.y + 8 * j] = top_new[j]; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + TF_UNROLL + for (short j = 0; j < 4; j++) { + for (int t = 0; t < NS; t++) top_new[j] = max(top_new[j], rowmax[t][home.y + 8 * j]); + } + TF_UNROLL + for (short i = 0; i < 4; i++) { + TF_UNROLL + for (short e = 0; e < 8; e++) { + s[i][e] = s[i][e] == kMasked ? 0.0f : fast::exp2(s[i][e] - top_new[2 * (i >> 1) + (e >> 2)]); + } + } + float keep[4]; + TF_UNROLL + for (short j = 0; j < 4; j++) { + keep[j] = top[j] == kMasked ? 0.0f : fast::exp2(top[j] - top_new[j]); + top[j] = top_new[j]; + total[j] = total[j] * keep[j]; + } + TF_UNROLL + for (short i = 0; i < 4; i++) fold(s[i], total + 2 * (i >> 1)); + TF_UNROLL + for (short i = 0; i < 8; i++) { + TF_UNROLL + for (short e = 0; e < 8; e++) acc[i][e] = acc[i][e] * keep[2 * (i >> 2) + (e >> 2)]; + } + for (int ph = 0; ph < BKT / PH; ph++) { + if (ph > 0) threadgroup_barrier(mem_flags::mem_threadgroup); // the phase before has read the tile + if (int(sg) / (PH / KS) == ph) { + TF_UNROLL + for (short i = 0; i < 4; i++) prob_put(pt, 16 * (i >> 1), int(sg) * KS - ph * PH + 16 * (i & 1), home, s[i]); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + for (int kk = 0; kk < PH / 16; kk++) { + const int kp = kb * BKT + ph * PH + 16 * kk; + if (kp > last_pos) break; // keys past the tile's rows: masked, and their cache rows may hold anything + const int valid = min(16, last_pos + 1 - kp); // a value row never written would poison the tile as 0 x NaN + const device bfloat* vblk = vc + long(kp) * LD; + frag v0, v1; + TF_UNROLL + for (short d = 0; d < 4; d += 2) { + if (valid == 16) { + v0 = blk(vblk, LD, 0, 16 * d, home); + v1 = blk(vblk, LD, 0, 16 * d + 16, home); + } else { + frag_get_in(v0, vblk, LD, 0, 16 * d, home, valid, DH); + frag_get_in(v1, vblk, LD, 0, 16 * d + 16, home, valid, DH); + } + TF_UNROLL + for (short h = 0; h < 2; h++) { + const frag pf = prob_frag(pt, 16 * h, 16 * kk, home); + mma_16x32(acc[4 * h + d], acc[4 * h + d + 1], pf, v0, v1); + } + } + } + } + } + // the tile's totals: every simdgroup's partial sums, scaled alike by the shared maxes + threadgroup_barrier(mem_flags::mem_threadgroup); + if (home.x == 0) { + TF_UNROLL + for (short j = 0; j < 4; j++) rowmax[sg][home.y + 8 * j] = total[j]; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + float inv[4]; + TF_UNROLL + for (short j = 0; j < 4; j++) { + float t = 0.0f; + for (int u = 0; u < NS; u++) t += rowmax[u][home.y + 8 * j]; + inv[j] = 1.0f / t; + } + device bfloat* o = O + r0 * qs + kv * G * DH + int(sg) * 64; + TF_UNROLL + for (short i = 0; i < 8; i++) { + TF_UNROLL + for (short e = 0; e < 8; e++) acc[i][e] = acc[i][e] * inv[2 * (i >> 2) + (e >> 2)]; + const int h = i >> 2; + if (h < t_rows) frag_put_in(acc[i], o + h * qs, DH, 0, 16 * (i & 3), home, 16, 64); + } +} diff --git a/zig/kernels/metal/minimax_m3/dflash2.metal b/zig/kernels/metal/minimax_m3/dflash2.metal new file mode 100644 index 00000000000..1b79a38b696 --- /dev/null +++ b/zig/kernels/metal/minimax_m3/dflash2.metal @@ -0,0 +1,195 @@ +// incoai's DFlash2 drafter for MiniMax-M3.1-Flash at SGLang's rounding points (models/dflash.py). +#include +using namespace metal; + +struct df_norm_args { uint rows, width; float eps; uint add; }; + +// Qwen3's RMSNorm: bf16(w * bf16(x * rsqrt(mean(x^2) + eps))). With a.add the residual first takes bf16(R + X). +inline void 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 df_norm(device float* R [[buffer(0)]], const device bfloat* X [[buffer(1)]], + const device bfloat* w [[buffer(2)]], constant 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); + df_norm_row(x, w, a.width, a.eps, out + (size_t)row * a.width, t, n, part); +} + +// The same norm of bf16 rows (fc's output into the context's hidden_norm). +[[kernel]] void df_norm16(const device bfloat* X [[buffer(0)]], const device bfloat* w [[buffer(1)]], + constant 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 df_prep_args { uint rows, heads, kv_heads, pos0, stride, q_off, k_off, v_off, ring; float eps, theta; }; + +// As dspark.metal's mm_draft_prep with Qwen3's head norm and every dim rotated: q heads to Q, k (and v) into the ring. +[[kernel]] void df_prep(const device bfloat* X [[buffer(0)]], const device bfloat* qw [[buffer(1)]], + const device bfloat* kw [[buffer(2)]], constant 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; + 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 df_conv_args { uint rows, width, block, groups, side; }; + +// The grouped two-tap block convolution: Y = bf16(bf16(c_0 x[r]) + bf16(c_1 x[r - 1])), c_t = base + delta by group. +[[kernel]] void df_conv(const device bfloat* X [[buffer(0)]], const device bfloat* D [[buffer(1)]], + const device bfloat* base [[buffer(2)]], constant 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); + const device bfloat* d = D + (size_t)r * 4 * a.groups + a.side * 2 * a.groups; + const float c0 = float(bfloat(float(base[(a.side * 2) * a.width + ch]) + float(d[g]))); + const float c1 = float(bfloat(float(base[(a.side * 2 + 1) * a.width + ch]) + float(d[a.groups + g]))); + float y = float(bfloat(c0 * float(X[(size_t)r * a.width + ch]))); + if (r % a.block >= 1) y = float(bfloat(y + float(bfloat(c1 * float(X[(size_t)(r - 1) * a.width + ch]))))); + Y[(size_t)r * a.width + ch] = bfloat(y); +} + +struct df_act_args { uint rows, width; }; + +// Qwen3's MLP activation on a stacked gate|up row: bf16(bf16(silu(g)) * u). +[[kernel]] void df_silu(const device bfloat* GU [[buffer(0)]], constant 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])); +} + +struct df_topk_args { uint n, stride, chunks, from_ids; }; + +inline bool 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 df_topk(const device bfloat* L [[buffer(0)]], const device float* VIN [[buffer(1)]], + const device uint* IIN [[buffer(2)]], constant 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 ? df_before(v[l], id[l], v[i], id[i]) : 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 df_walk_args { uint slots, rank, top, vocab; }; + +// The selector's greedy path: slot e scores c after p as unary[e][c] + sum_r bf16(A[p][r] H[e][r]) B[c][r]; seq[1 + e]. +[[kernel]] void 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 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 s = UV[e * a.top + c]; + for (uint k = 0; k < a.rank / 32; ++k) s += part[k][c]; + 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/minimax_m3/dspark.metal b/zig/kernels/metal/minimax_m3/dspark.metal new file mode 100644 index 00000000000..c12a1f48394 --- /dev/null +++ b/zig/kernels/metal/minimax_m3/dspark.metal @@ -0,0 +1,197 @@ +// MiniMax-M3.1-Flash's DSpark drafter and the target's taps for it, at ref/dspark.py's rounding points. +#include +using namespace metal; + +struct mm_tap_args { uint rows, width, taps, tap; }; + +// T[(r * taps + tap) * width + i] = bf16(R[r * width + i]): the residual after a tapped layer, in the drafter's order. +[[kernel]] void mm_tap(const device float* R [[buffer(0)]], constant mm_tap_args& a [[buffer(1)]], + device bfloat* T [[buffer(2)]], uint2 p [[thread_position_in_grid]]) { + if (p.x >= a.width || p.y >= a.rows) return; + T[((size_t)p.y * a.taps + a.tap) * a.width + p.x] = bfloat(R[(size_t)p.y * a.width + p.x]); +} + +struct mm_norm16_args { uint rows, width; float eps; }; + +// Gemma's rms norm of bf16 rows: bf16(x * rsqrt(mean(x^2) + eps) * (1 + w)). +[[kernel]] void mm_norm16(const device bfloat* X [[buffer(0)]], const device bfloat* w [[buffer(1)]], + constant mm_norm16_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(x[i]) * inv * (1.0f + float(w[i]))); +} + +struct mm_dprep_args { uint rows, heads, kv_heads, pos0, rotary, stride, q_off, k_off, v_off, ring; float eps, theta; }; + +// q heads normed and rotated to Q; k heads normed and rotated into the ring at (pos0 + row) % ring, v copied beside. +[[kernel]] void mm_draft_prep(const device bfloat* X [[buffer(0)]], const device bfloat* qw [[buffer(1)]], + const device bfloat* kw [[buffer(2)]], constant mm_dprep_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(v[j] * inv * (1.0f + float(w[lane + 32 * j])))); + simdgroup_barrier(mem_flags::mem_threadgroup); + const uint half_r = a.rotary / 2; + for (uint j = 0; j < 4; ++j) { + const uint d = lane + 32 * j; + if (d >= a.rotary) { y[d] = bfloat(nrm[d]); continue; } + const uint i = d % half_r; + const float angle = float(p) * (1.0f / precise::pow(a.theta, float(2 * i) / float(a.rotary))); + const float c = float(bfloat(precise::cos(angle))), s = float(bfloat(precise::sin(angle))); + const float rot = d < half_r ? -nrm[d + half_r] : nrm[d - half_r]; + 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]; +} + +#define TF_UNROLL_4 _Pragma("clang loop unroll(full)") + +struct mm_dvec_args { uint rows, pos0, heads, groups, blocks, first, hi, window, ring; float scale; }; + +// The block's attention partials over 128-key blocks: row r sees from its window's start up to hi. +[[kernel]] void mm_draft_vec(const device bfloat* Q [[buffer(0)]], const device bfloat* K [[buffer(1)]], + const device bfloat* V [[buffer(2)]], constant mm_dvec_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 = p + 1 > a.window ? p + 1 - a.window : 0; + 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 mm_markov_args { uint vocab, rank, step; }; + +// One draft's Markov step: logits[step, v] + w2[v] . w1[seq[step]] (w2 8-bit affine), the best ties to the lower id. +[[kernel]] void mm_markov_step(const device bfloat* L [[buffer(0)]], const device bfloat* W1 [[buffer(1)]], + const device uint* W2 [[buffer(2)]], const device bfloat* S2 [[buffer(3)]], const device bfloat* B2 [[buffer(4)]], + const device uint* seq [[buffer(5)]], constant mm_markov_args& a [[buffer(6)]], device float* best [[buffer(7)]], + device uint* best_id [[buffer(8)]], uint group [[threadgroup_position_in_grid]], + uint t [[thread_position_in_threadgroup]], uint lane [[thread_index_in_simdgroup]], + uint sg [[simdgroup_index_in_threadgroup]]) { + threadgroup float e[256]; + threadgroup float vals[8]; + threadgroup uint ids[8]; + const uint prev = seq[a.step]; + for (uint i = t; i < a.rank; i += 256) e[i] = float(W1[(size_t)prev * a.rank + i]); + threadgroup_barrier(mem_flags::mem_threadgroup); + const uint v = group * 256 + t; + float score = -INFINITY; + if (v < a.vocab) { + const device uint* w = W2 + (size_t)v * (a.rank / 4); + float sum = 0.0f; + for (uint g = 0; g < a.rank / 64; ++g) { + const float s = float(S2[(size_t)v * (a.rank / 64) + g]), b = float(B2[(size_t)v * (a.rank / 64) + g]); + for (uint j = 0; j < 16; ++j) { + const uint word = w[g * 16 + j]; + for (uint k = 0; k < 4; ++k) sum = fma(float(bfloat(s * float((word >> (8 * k)) & 0xffu) + b)), e[g * 64 + j * 4 + k], sum); + } + } + score = float(L[(size_t)a.step * a.vocab + v]) + sum; + } + uint at = v; + for (ushort d = 16; d > 0; d >>= 1) { + const float o = simd_shuffle_xor(score, d); + const uint oi = simd_shuffle_xor(at, d); + if (o > score || (o == score && oi < at)) { score = o; at = oi; } + } + if (lane == 0) { vals[sg] = score; ids[sg] = at; } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (t == 0) { + float b = vals[0]; + uint bi = ids[0]; + for (uint k = 1; k < 8; ++k) if (vals[k] > b || (vals[k] == b && ids[k] < bi)) { b = vals[k]; bi = ids[k]; } + best[group] = b; + best_id[group] = bi; + } +} + +// The step's draft: the best of every threadgroup's best, into seq[step + 1]. +[[kernel]] void mm_markov_pick(const device float* best [[buffer(0)]], const device uint* best_id [[buffer(1)]], + constant uint2& a [[buffer(2)]], device uint* seq [[buffer(3)]], uint t [[thread_position_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]], uint sg [[simdgroup_index_in_threadgroup]]) { + threadgroup float vals[32]; + threadgroup uint ids[32]; + float b = -INFINITY; + uint bi = 0xffffffffu; + for (uint i = t; i < a.x; i += 1024) if (best[i] > b || (best[i] == b && best_id[i] < bi)) { b = best[i]; bi = best_id[i]; } + for (ushort d = 16; d > 0; d >>= 1) { + const float o = simd_shuffle_xor(b, d); + const uint oi = simd_shuffle_xor(bi, d); + if (o > b || (o == b && oi < bi)) { b = o; bi = oi; } + } + if (lane == 0) { vals[sg] = b; ids[sg] = bi; } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (sg != 0) return; + b = vals[lane]; + bi = ids[lane]; + for (ushort d = 16; d > 0; d >>= 1) { + const float o = simd_shuffle_xor(b, d); + const uint oi = simd_shuffle_xor(bi, d); + if (o > b || (o == b && oi < bi)) { b = o; bi = oi; } + } + if (lane == 0) seq[a.y + 1] = bi; +} diff --git a/zig/kernels/metal/minimax_m3/experts.metal b/zig/kernels/metal/minimax_m3/experts.metal new file mode 100644 index 00000000000..c9125eacb0f --- /dev/null +++ b/zig/kernels/metal/minimax_m3/experts.metal @@ -0,0 +1,52 @@ +// A decode window's routed experts, expert by expert: weights read once a window, tf_row_projection_indexed's bits. + +// One threadgroup an (expert, RPS * SG columns): its members 4, 2 then 1 at a time through tf_rp_rows_at. +template +[[max_total_threads_per_threadgroup(64)]] +[[kernel]] void mm_experts_grouped(const device bfloat* X [[buffer(0)]], const device uint32_t* W [[buffer(1)]], + const device bfloat* S [[buffer(2)]], const device bfloat* B [[buffer(3)]], constant int* dims [[buffer(4)]], + device bfloat* OUT [[buffer(5)]], const device uint* G [[buffer(6)]], const device uint* M [[buffer(7)]], + uint sg [[simdgroup_index_in_threadgroup]], uint lane [[thread_index_in_simdgroup]], + uint3 tg [[threadgroup_position_in_grid]]) { + const int K = dims[0], N = dims[1], GS = dims[2], slots = dims[3], repeat = dims[5]; + const int row0 = (int(tg.x) * SG + int(sg)) * RPS; + const uint g = tg.y, groups = G[0]; + if (row0 >= N || g >= groups) return; + const uint expert = G[1 + 2 * g], first = G[2 + 2 * g], end = g + 1 < groups ? G[2 + 2 * (g + 1)] : uint(slots); + const size_t at = size_t(expert) * N + size_t(row0); + const device uint8_t* wr = (const device uint8_t*)W + at * (K * BITS / 8); + const device bfloat* sr = S + at * (K / GS); + const device bfloat* br = B + at * (K / GS); + uint m = first; + #pragma clang loop unroll(disable) + for (; m + 4 <= end; m += 4) { + TfRpRows<4> x; + for (int b = 0; b < 4; b++) x.x[b] = X + size_t(M[m + b] / uint(repeat)) * K; + float acc[4][RPS]; + tf_rp_rows_at(wr, sr, br, x, K, GS, lane, acc); + if (lane == 0) + for (int b = 0; b < 4; b++) + for (int j = 0; j < RPS; j++) OUT[size_t(M[m + b]) * N + row0 + j] = bfloat(acc[b][j]); + } + #pragma clang loop unroll(disable) + for (; m + 2 <= end; m += 2) { + TfRpRows<2> x; + for (int b = 0; b < 2; b++) x.x[b] = X + size_t(M[m + b] / uint(repeat)) * K; + float acc[2][RPS]; + tf_rp_rows_at(wr, sr, br, x, K, GS, lane, acc); + if (lane == 0) + for (int b = 0; b < 2; b++) + for (int j = 0; j < RPS; j++) OUT[size_t(M[m + b]) * N + row0 + j] = bfloat(acc[b][j]); + } + for (; m < end; m++) { + TfRpRows<1> x; + x.x[0] = X + size_t(M[m] / uint(repeat)) * K; + float acc[1][RPS]; + tf_rp_rows_at(wr, sr, br, x, K, GS, lane, acc); + if (lane == 0) + for (int j = 0; j < RPS; j++) OUT[size_t(M[m]) * N + row0 + j] = bfloat(acc[0][j]); + } +} + +template [[host_name("mm_experts_grouped_q3")]] [[kernel]] decltype(mm_experts_grouped<4, 2, 3>) mm_experts_grouped<4, 2, 3>; +template [[host_name("mm_experts_grouped_q4")]] [[kernel]] decltype(mm_experts_grouped<4, 2, 4>) mm_experts_grouped<4, 2, 4>; diff --git a/zig/kernels/metal/minimax_m3/glue.metal b/zig/kernels/metal/minimax_m3/glue.metal new file mode 100644 index 00000000000..ccdd1bd8594 --- /dev/null +++ b/zig/kernels/metal/minimax_m3/glue.metal @@ -0,0 +1,578 @@ +// MiniMax-M3.1-Flash's glue at transformers' rounding points (modeling_minimax_m3_vl.py, bf16 activations). +#include +using namespace metal; + +struct mm_args { uint rows, width, heads, dim, pos, stride, bits, group; float eps, alpha, limit, scale; }; + +// Row r of residual R = dequantized affine embedding row ids[r]: bf16(scale * q + bias), held in fp32. +[[kernel]] void mm_embed(const device uint* ids [[buffer(0)]], const device uint* W [[buffer(1)]], + const device bfloat* S [[buffer(2)]], const device bfloat* B [[buffer(3)]], constant mm_args& a [[buffer(4)]], + device float* R [[buffer(5)]], uint2 p [[thread_position_in_grid]]) { + if (p.x >= a.width || p.y >= a.rows) return; + const size_t row = ids[p.y]; + const uint per = 32 / a.bits, mask = (1u << a.bits) - 1; + const uint word = W[row * (a.width / per) + p.x / per]; + const float q = float((word >> ((p.x % per) * a.bits)) & mask); + const size_t g = row * (a.width / a.group) + p.x / a.group; + R[(size_t)p.y * a.width + p.x] = float(bfloat(float(S[g]) * q + float(B[g]))); +} + +// Gemma's rms norm of fp32 values: bf16(x * rsqrt(mean(x^2) + eps) * (1 + w)), one rounding. +inline void mm_norm_row(const 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(x[i] * inv * (1.0f + float(w[i]))); +} + +[[kernel]] void mm_norm(const device float* R [[buffer(0)]], const device bfloat* w [[buffer(1)]], + constant mm_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]; + mm_norm_row(R + (size_t)row * a.width, w, a.width, a.eps, out + (size_t)row * a.width, t, n, part); +} + +// R = bf16(R + X), then the next norm of R: a sublayer's output into the residual. +[[kernel]] void mm_add_norm(device float* R [[buffer(0)]], const device bfloat* X [[buffer(1)]], + const device bfloat* w [[buffer(2)]], constant mm_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; + 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); + mm_norm_row(x, w, a.width, a.eps, out + (size_t)row * a.width, t, n, part); +} + +// R = bf16(R + X) alone (the last layer's output; the final norm runs on chosen rows). +[[kernel]] void mm_add(device float* R [[buffer(0)]], const device bfloat* X [[buffer(1)]], + constant mm_args& a [[buffer(2)]], uint2 p [[thread_position_in_grid]]) { + if (p.x >= a.width || p.y >= a.rows) return; + const size_t i = (size_t)p.y * a.width + p.x; + R[i] = float(bfloat(R[i] + float(X[i]))); +} + +// The sigmoid of an fp32 value from the precise exp of -|x|; below 0 as e / (1 + e), which 1 - y would cancel. +inline float mm_sigmoid(float x) { + const float e = precise::exp(-fabs(x)), y = 1.0f / (1.0f + e); + return x < 0.0f ? e * y : y; +} + +// torch's clamp: a NaN stays NaN (Metal's min and clamp would give the bound). +inline float mm_clamp(float x, float lo, float hi) { return isnan(x) ? x : clamp(x, lo, hi); } + +// SwiGLU-OAI of a gate|up row in bf16 steps: (clamp(up) + 1) * g * sigmoid(g * alpha), g = min(gate, limit). +[[kernel]] void mm_swiglu(const device bfloat* GU [[buffer(0)]], constant mm_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 * a.stride + p.x; + const float g = mm_clamp(float(GU[at]), -INFINITY, a.limit); + const float u = mm_clamp(float(GU[at + a.width]), -a.limit, a.limit); + const float s = float(bfloat(mm_sigmoid(float(bfloat(g * a.alpha))))); + const float glu = float(bfloat(g * s)); + A[(size_t)p.y * a.width + p.x] = bfloat(float(bfloat(u + 1.0f)) * glu); +} + +// The router's fp32 logits: L[r, e] = sum_d float(X[r, d]) * W[e, d], 8 rows and 8 experts a threadgroup. +[[max_total_threads_per_threadgroup(256)]] +[[kernel]] void mm_router(const device bfloat* X [[buffer(0)]], const device float* W [[buffer(1)]], + constant mm_args& a [[buffer(2)]], device float* L [[buffer(3)]], uint2 tg [[threadgroup_position_in_grid]], + uint t [[thread_index_in_threadgroup]], uint sg [[simdgroup_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]]) { + constexpr uint RB = 8, EB = 8; // rows and experts a threadgroup: each x load serves EB experts + threadgroup float part[EB][RB][8]; + const uint e0 = tg.x * EB, r0 = tg.y * RB, nr = min(RB, a.rows - r0); + float acc[EB][RB]; + for (uint k = 0; k < EB; ++k) + for (uint r = 0; r < RB; ++r) acc[k][r] = 0.0f; + for (uint d = 4 * t; d < a.width; d += 4 * 256) { + float4 wv[EB]; + for (uint k = 0; k < EB; ++k) wv[k] = *(const device float4*)(W + (size_t)(e0 + k) * a.width + d); + for (uint r = 0; r < nr; ++r) { + const float4 xv = float4(*(const device bfloat4*)(X + (size_t)(r0 + r) * a.width + d)); + for (uint k = 0; k < EB; ++k) acc[k][r] += dot(wv[k], xv); + } + } + for (uint k = 0; k < EB; ++k) + for (uint r = 0; r < nr; ++r) { + const float s = simd_sum(acc[k][r]); + if (lane == 0) part[k][r][sg] = s; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (t < nr * EB) { + const uint k = t / nr, r = t % nr; + float s = 0.0f; + for (uint j = 0; j < 8; ++j) s += part[k][r][j]; + L[(size_t)(r0 + r) * a.heads + e0 + k] = s; + } +} + +// A row's pick: sigmoid scores, top-k of score + bias (ties to the lower id), weights = score / their sum. +inline void mm_pick_row(const device float* L, const device float* bias, constant mm_args& a, device int* PICK, + device float* WTS, uint row, uint lane); + +// A simdgroup a row (a threadgroup each). +[[kernel]] void mm_route_pick(const device float* L [[buffer(0)]], const device float* bias [[buffer(1)]], + constant mm_args& a [[buffer(2)]], device int* PICK [[buffer(3)]], device float* WTS [[buffer(4)]], + uint row [[threadgroup_position_in_grid]], uint lane [[thread_index_in_simdgroup]]) { + if (row >= a.rows) return; + mm_pick_row(L, bias, a, PICK, WTS, row, lane); +} + +// A decode window's picks, a simdgroup a row, then its slots by expert as experts.metal reads them (G, M). +[[kernel]] void mm_route_groups(const device float* L [[buffer(0)]], const device float* bias [[buffer(1)]], + constant mm_args& a [[buffer(2)]], device int* PICK [[buffer(3)]], device float* WTS [[buffer(4)]], + device uint* G [[buffer(5)]], device uint* M [[buffer(6)]], uint sg [[simdgroup_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]], uint t [[thread_index_in_threadgroup]]) { + if (sg < a.rows) mm_pick_row(L, bias, a, PICK, WTS, sg, lane); + threadgroup_barrier(mem_flags::mem_device); + if (t != 0) return; + const uint slots = a.rows * a.heads; + uint n = 0, at = 0; + int last = -1; + while (true) { + int next = 0x7fffffff; + for (uint s = 0; s < slots; ++s) if (PICK[s] > last && PICK[s] < next) next = PICK[s]; + if (next == 0x7fffffff) break; + G[1 + 2 * n] = uint(next); + G[2 + 2 * n] = at; + for (uint s = 0; s < slots; ++s) if (PICK[s] == next) M[at++] = s; + last = next; + n += 1; + } + G[0] = n; +} + +inline void mm_pick_row(const device float* L, const device float* bias, constant mm_args& a, device int* PICK, + device float* WTS, uint row, uint lane) { + constexpr uint PER = 8; // experts a lane: a.width <= 256 + float sc[PER], ch[PER]; + uint taken = 0; + for (uint j = 0; j < PER; ++j) { + const uint id = j * 32 + lane; + if (id < a.width) { + sc[j] = mm_sigmoid(L[(size_t)row * a.width + id]); + ch[j] = sc[j] + bias[id]; + } else { + sc[j] = ch[j] = 0.0f; + taken |= 1u << j; + } + } + float w[8]; + for (uint k = 0; k < a.heads; ++k) { + float best = -INFINITY, bw = 0.0f; + uint bid = a.width; + for (uint j = 0; j < PER; ++j) { + const uint id = j * 32 + lane; + if (!(taken & (1u << j)) && (ch[j] > best || (ch[j] == best && id < bid))) { best = ch[j]; bw = sc[j]; bid = id; } + } + for (ushort off = 16; off > 0; off /= 2) { + const float ob = simd_shuffle_xor(best, off), ow = simd_shuffle_xor(bw, off); + const uint oi = simd_shuffle_xor(bid, off); + if (ob > best || (ob == best && oi < bid)) { best = ob; bw = ow; bid = oi; } + } + w[k] = bw; + if (bid % 32 == lane) taken |= 1u << (bid / 32); + if (lane == 0) PICK[row * a.heads + k] = int(bid); + } + if (lane != 0) return; + float total = 0.0f; + for (uint k = 0; k < a.heads; ++k) total += w[k]; + // written in ascending expert id (the combine's order), each weight its own pick's + uint ids[8]; + for (uint k = 0; k < a.heads; ++k) ids[k] = uint(PICK[row * a.heads + k]); + for (uint k = 0; k < a.heads; ++k) w[k] = w[k] / total; + for (uint j = 1; j < a.heads; ++j) + for (uint m = j; m > 0 && ids[m] < ids[m - 1]; --m) { + const uint ti = ids[m]; ids[m] = ids[m - 1]; ids[m - 1] = ti; + const float tw = w[m]; w[m] = w[m - 1]; w[m - 1] = tw; + } + for (uint k = 0; k < a.heads; ++k) { + PICK[row * a.heads + k] = int(ids[k]); + WTS[row * a.heads + k] = w[k]; + } +} + +// transformers' expert loop: picks by id, acc = bf16(acc + bf16(y * w)), then bf16(bf16(acc * scale) + shared). +inline float mm_moe_out(const device bfloat* Y, const device int* pick, const device float* wts, + const device bfloat* shared, constant mm_args& a, uint row, uint i) { + const uint k = a.heads; // the picks are in ascending expert id (mm_pick_row writes them so) + (void)pick; + float acc = 0.0f; + for (uint j = 0; j < k; ++j) { + const uint s = row * k + j; + acc = float(bfloat(acc + float(bfloat(float(Y[(size_t)s * a.width + i]) * wts[s])))); + } + return float(bfloat(float(bfloat(acc * a.scale)) + float(shared[(size_t)row * a.width + i]))); +} + +// R = bf16(R + moe), then the next layer's input norm of R. +[[kernel]] void mm_moe_add_norm(device float* R [[buffer(0)]], const device bfloat* Y [[buffer(1)]], + const device int* pick [[buffer(2)]], const device float* wts [[buffer(3)]], const device bfloat* shared [[buffer(4)]], + const device bfloat* w [[buffer(5)]], constant mm_args& a [[buffer(6)]], device bfloat* out [[buffer(7)]], + 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; + for (uint i = t; i < a.width; i += n) x[i] = float(bfloat(x[i] + mm_moe_out(Y, pick, wts, shared, a, row, i))); + threadgroup_barrier(mem_flags::mem_device); + mm_norm_row(x, w, a.width, a.eps, out + (size_t)row * a.width, t, n, part); +} + +[[kernel]] void mm_moe_add(device float* R [[buffer(0)]], const device bfloat* Y [[buffer(1)]], + const device int* pick [[buffer(2)]], const device float* wts [[buffer(3)]], const device bfloat* shared [[buffer(4)]], + constant mm_args& a [[buffer(5)]], uint2 p [[thread_position_in_grid]]) { + if (p.x >= a.width || p.y >= a.rows) return; + const size_t i = (size_t)p.y * a.width + p.x; + R[i] = float(bfloat(R[i] + mm_moe_out(Y, pick, wts, shared, a, p.y, p.x))); +} + +// A chunk's a.rows picks by expert (at most 256): offsets[e] its first pair, order each expert's pairs ascending. +[[kernel]] void mm_sort(const device int* pick [[buffer(0)]], constant mm_args& a [[buffer(1)]], + device int* offsets [[buffer(2)]], device int* order [[buffer(3)]], uint t [[thread_position_in_threadgroup]], + uint sg [[simdgroup_index_in_threadgroup]], uint lane [[thread_index_in_simdgroup]]) { + constexpr uint E = 256, T = 1024, SGS = T / 32; + threadgroup atomic_int counts[E]; + threadgroup int next[E]; + threadgroup ushort before[SGS][E]; // a 1,024-pair pass: each simdgroup's pairs of an expert, then the pairs ahead + threadgroup ushort got[E]; // the pass's pairs of each expert + if (t < a.width) atomic_store_explicit(&counts[t], 0, memory_order_relaxed); + threadgroup_barrier(mem_flags::mem_threadgroup); + for (uint i = t; i < a.rows; i += T) atomic_fetch_add_explicit(&counts[pick[i]], 1, memory_order_relaxed); + threadgroup_barrier(mem_flags::mem_threadgroup); + if (t == 0) { + int sum = 0; + for (uint e = 0; e < a.width; ++e) { + offsets[e] = sum; + next[e] = sum; + sum += atomic_load_explicit(&counts[e], memory_order_relaxed); + } + } + for (uint i0 = 0; i0 < a.rows; i0 += T) { + for (uint j = t; j < SGS * E; j += T) before[j / E][j % E] = 0; + threadgroup_barrier(mem_flags::mem_threadgroup); + const uint i = i0 + t; + const int e = i < a.rows ? pick[i] : -1; + ushort ahead = 0, same = 0; // the simdgroup's lanes of this expert: below this one, in all + for (ushort l = 0; l < 32; ++l) + if (simd_shuffle(e, l) == e) { + same += 1; + ahead += l < lane ? 1 : 0; + } + if (e >= 0 && ahead + 1 == same) before[sg][e] = same; + threadgroup_barrier(mem_flags::mem_threadgroup); + if (t < a.width) { + ushort run = 0; + for (uint g = 0; g < SGS; ++g) { + const ushort n = before[g][t]; + before[g][t] = run; + run += n; + } + got[t] = run; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (e >= 0) order[next[e] + before[sg][e] + ahead] = int(i); + threadgroup_barrier(mem_flags::mem_threadgroup); + if (t < a.width) next[t] += got[t]; + } +} + +// Y[i] = X[order[i] / a.heads]: each sorted pair's input row (a.width wide). +[[kernel]] void mm_rows_by_order(const device bfloat* X [[buffer(0)]], const device int* order [[buffer(1)]], + constant mm_args& a [[buffer(2)]], device bfloat* Y [[buffer(3)]], uint2 p [[thread_position_in_grid]]) { + if (p.x < a.width && p.y < a.rows) Y[(size_t)p.y * a.width + p.x] = X[(size_t)(order[p.y] / int(a.heads)) * a.width + p.x]; +} + +struct mm_prep_args { uint rows, heads, kv_heads, index_heads, dim, pos, rotary, stride; float eps, theta; }; + +// Normed and rotated q, k and index q, k; the keys, values and index keys into the cache at their slots. +[[kernel]] void mm_prep(const device bfloat* X [[buffer(0)]], const device bfloat* qw [[buffer(1)]], + const device bfloat* kw [[buffer(2)]], const device bfloat* iqw [[buffer(3)]], const device bfloat* ikw [[buffer(4)]], + constant mm_prep_args& a [[buffer(5)]], device bfloat* QN [[buffer(6)]], device bfloat* IQ [[buffer(7)]], + device bfloat* KC [[buffer(8)]], device bfloat* VC [[buffer(9)]], device bfloat* IK [[buffer(10)]], + uint2 tg [[threadgroup_position_in_grid]], uint lane [[thread_index_in_simdgroup]]) { + const uint unit = tg.x, row = tg.y; + const uint nq = a.heads, nk = a.kv_heads, ni = a.index_heads; + if (unit >= nq + nk + ni + 1 || row >= a.rows) return; + const uint D = a.dim; // 128: four values a lane + const device bfloat* src = X + (size_t)row * a.stride; + const device bfloat* w; + device bfloat* y; + const size_t slot = a.pos + row; + const bool key = unit >= nq && unit < nq + nk; + uint head; + if (unit < nq) { + head = unit; + src += (size_t)head * D; + w = qw; + y = QN + ((size_t)row * nq + head) * D; + } else if (key) { + head = unit - nq; + src += (size_t)(nq + head) * D; + w = kw; + y = KC + (slot * nk + head) * D; + } else if (unit < nq + nk + ni) { + head = unit - nq - nk; + src += (size_t)(nq + 2 * nk + head) * D; + w = iqw; + y = IQ + ((size_t)row * ni + head) * D; + } else { + head = 0; + src += (size_t)(nq + 2 * nk + ni) * D; + w = ikw; + y = IK + slot * D; + } + 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) / float(D) + a.eps); + threadgroup float nrm[128]; + for (uint j = 0; j < 4; ++j) nrm[lane + 32 * j] = float(bfloat(v[j] * inv * (1.0f + float(w[lane + 32 * j])))); + simdgroup_barrier(mem_flags::mem_threadgroup); + const uint half_r = a.rotary / 2; + const float position = float(a.pos + row); + float out[4]; + for (uint j = 0; j < 4; ++j) { + const uint d = lane + 32 * j; + if (d >= a.rotary) { out[j] = float(bfloat(nrm[d])); continue; } + const uint i = d % half_r; + const float freq = 1.0f / precise::pow(a.theta, float(2 * i) / float(a.rotary)); + const float angle = position * freq; + const float c = float(bfloat(precise::cos(angle))), s = float(bfloat(precise::sin(angle))); + const float rot = d < half_r ? -nrm[d + half_r] : nrm[d - half_r]; + out[j] = float(bfloat(float(bfloat(nrm[d] * c)) + float(bfloat(rot * s)))); + } + for (uint j = 0; j < 4; ++j) y[lane + 32 * j] = bfloat(out[j]); + if (!key) return; + const device bfloat* vs = X + (size_t)row * a.stride + (size_t)(nq + nk + head) * D; + device bfloat* vd = VC + (slot * nk + head) * D; + for (uint j = 0; j < 4; ++j) vd[lane + 32 * j] = vs[lane + 32 * j]; +} + +struct mm_index_args { uint rows, pos, heads, blocks, first_row; }; + +// torch's max: a NaN wins (Metal's max is fmax and drops it). +inline float mm_max(float x, float y) { return isnan(x) || isnan(y) ? NAN : max(x, y); } + +// Indexer scores: S[row, h, j] = max over block j's keys up to the row of IQ[row, h] . IK[k]; 128 keys by 16 rows. +[[kernel]] void mm_index_scores(const device bfloat* IQ [[buffer(0)]], const device bfloat* IK [[buffer(1)]], + constant mm_index_args& a [[buffer(2)]], device float* S [[buffer(3)]], uint2 tg [[threadgroup_position_in_grid]], + uint t [[thread_index_in_threadgroup]], uint sg [[simdgroup_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]]) { + constexpr uint RB = 16, H = 4, D = 128; + threadgroup bfloat q[RB * H * D]; + threadgroup float part[4][RB * H]; + const uint j = tg.x, r0 = tg.y * RB, nr = min(RB, a.rows - r0); + for (uint i = t; i < nr * H * D; i += 128) q[i] = IQ[(size_t)r0 * H * D + i]; + threadgroup_barrier(mem_flags::mem_threadgroup); + const uint key = j * 128 + t; + const device bfloat* k = IK + (size_t)key * D; + float acc[RB * H]; + for (uint i = 0; i < RB * H; ++i) acc[i] = 0.0f; + const bool any = key <= a.pos + r0 + nr - 1; + if (any) { + for (uint d = 0; d < D; d += 8) { + const float4 k0 = float4(*(const device bfloat4*)(k + d)), k1 = float4(*(const device bfloat4*)(k + d + 4)); + for (uint r = 0; r < nr; ++r) + for (uint h = 0; h < H; ++h) { + const threadgroup bfloat* qq = q + (r * H + h) * D + d; + acc[r * H + h] += dot(k0, float4(*(const threadgroup bfloat4*)qq)) + dot(k1, float4(*(const threadgroup bfloat4*)(qq + 4))); + } + } + } + for (uint r = 0; r < nr; ++r) + for (uint h = 0; h < H; ++h) { + const float v = key <= a.pos + r0 + r ? acc[r * H + h] : -INFINITY; + const float s = simd_any(isnan(v)) ? NAN : simd_max(v); + if (lane == 0) part[sg][r * H + h] = s; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (t < nr * H) { + const float s = mm_max(mm_max(part[0][t], part[1][t]), mm_max(part[2][t], part[3][t])); + S[((size_t)(r0 + t / H) * a.heads + t % H) * a.blocks + j] = s; + } +} + +// A (row, key head)'s kept blocks ascending: all if at most topk, else its own and the best (ties low); and a bitmap. +[[kernel]] void mm_index_select(const device float* S [[buffer(0)]], constant mm_index_args& a [[buffer(1)]], + constant uint& topk [[buffer(2)]], device int* SEL [[buffer(3)]], device uint* BITS [[buffer(4)]], + constant uint& words [[buffer(5)]], uint2 tg [[threadgroup_position_in_grid]], uint lane [[thread_index_in_simdgroup]]) { + const uint row = tg.y, h = tg.x; + if (row >= a.rows) return; + const uint nb = (a.pos + row) / 128 + 1; // blocks the row sees; the last is its own + const device float* s = S + ((size_t)row * a.heads + h) * a.blocks; + device int* out = SEL + ((size_t)row * a.heads + h) * topk; + int list[32]; + uint count = 0; + if (nb <= topk) { + for (uint b = 0; b < nb; ++b) list[count++] = int(b); + } else { + list[count++] = int(nb - 1); + float last_best = INFINITY; // (+Inf, -1): before every block, so +Inf blocks are kept first + int last_id = -1; + for (uint k = 1; k < topk; ++k) { + // the best (score, id) strictly after (last_best, last_id) in the order score desc, id asc + float best = -INFINITY; + uint bid = 0xffffffffu; + for (uint b = lane; b < nb - 1; b += 32) { + const float v = s[b]; + const bool after = v < last_best || (v == last_best && int(b) > last_id); + if (after && (v > best || (v == best && b < bid))) { best = v; bid = b; } + } + for (ushort off = 16; off > 0; off /= 2) { + const float ob = simd_shuffle_xor(best, off); + const uint oi = simd_shuffle_xor(bid, off); + if (ob > best || (ob == best && oi < bid)) { best = ob; bid = oi; } + } + if (bid == 0xffffffffu || best == -INFINITY) break; + list[count++] = int(bid); + last_best = best; + last_id = int(bid); + } + } + if (lane == 0) { + for (uint i = 1; i < count; ++i) + for (uint m = i; m > 0 && list[m] < list[m - 1]; --m) { const int t = list[m]; list[m] = list[m - 1]; list[m - 1] = t; } + for (uint i = 0; i < topk; ++i) out[i] = i < count ? list[i] : -1; + } + if (words == 0) return; + device uint* bits = BITS + ((size_t)row * a.heads + h) * words; + for (uint wd = lane; wd < words; wd += 32) { + uint m = 0; + for (uint i = 0; i < count; ++i) if (uint(list[i]) / 32 == wd) m |= 1u << (uint(list[i]) % 32); + bits[wd] = m; + } +} + +#define TF_UNROLL_4 _Pragma("clang loop unroll(full)") + +struct mm_vec_args { uint rows, pos, heads, groups, topk; float scale; uint sel, all; }; + +// Decode attention partials: a threadgroup a (key head, row, 32-key quarter of a kept block), a simdgroup a query head. +[[kernel]] void mm_decode_vec(const device bfloat* Q [[buffer(0)]], const device bfloat* K [[buffer(1)]], + const device bfloat* V [[buffer(2)]], constant mm_vec_args& a [[buffer(3)]], const device int* SEL [[buffer(4)]], + device float* PM [[buffer(5)]], device float* PL [[buffer(6)]], device float* PO [[buffer(7)]], + 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.topk + z; + const uint p = a.pos + row; + const uint pick = z / 4, quarter = z % 4; + const int block = a.all ? (pick <= p / 128 ? int(pick) : -1) : SEL[((size_t)row * a.groups + kv) * a.sel + pick]; + const uint from = block < 0 ? 0 : uint(block) * 128 + quarter * 32, to = block < 0 ? 0 : min(p + 1, from + 32); + 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; // past the row's position: a masked key (read at the block's first, weight 0) + const size_t key = (size_t)(live ? i0 + u : from), at = key * 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; +} + +// The partials' merge in block order: a simdgroup a (head, row), the row's max first, then its mass and outputs. +[[kernel]] void mm_merge_vec(const device float* PM [[buffer(0)]], const device float* PL [[buffer(1)]], + const device float* PO [[buffer(2)]], constant mm_vec_args& a [[buffer(3)]], device bfloat* O [[buffer(4)]], + uint3 tg [[threadgroup_position_in_grid]], uint lane [[thread_index_in_simdgroup]]) { + const uint head = tg.x, row = tg.y; + const size_t at = (size_t)head * a.rows + row; + const device float* ms = PM + at * a.topk; + const device float* ls = PL + at * a.topk; + float top = -INFINITY; + for (uint b = lane; b < a.topk; b += 32) top = max(top, ms[b]); + top = simd_max(top); + float total = 0.0f; + float4 acc = 0.0f; + for (uint b = 0; b < a.topk; ++b) { + if (ls[b] <= 0.0f) continue; + const float f = fast::exp(ms[b] - top); + total += ls[b] * f; + acc += f * *(const device float4*)(PO + (at * a.topk + b) * 128 + 4 * lane); + } + acc /= total; + *(device bfloat4*)(O + (row * a.heads + head) * 128 + 4 * lane) = bfloat4(acc); +} + +inline bool mm_better(float a, uint ia, float b, uint ib) { + if (isnan(a)) return !isnan(b) || ia < ib; + if (isnan(b)) return false; + return a > b || (a == b && ia < ib); +} + +// The greedy draw: a bf16 logits row's argmax, ties to the lower id, into ids[0]. +[[kernel]] void mm_argmax(const device bfloat* logits [[buffer(0)]], device uint* ids [[buffer(1)]], + constant uint& vocab [[buffer(2)]], uint t [[thread_position_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]], uint sg [[simdgroup_index_in_threadgroup]]) { + threadgroup float vals[32]; + threadgroup uint idxs[32]; + float best = -INFINITY; + uint at = 0xffffffffu; + for (uint i = t; i < vocab; i += 1024) { + const float v = float(logits[i]); + if (mm_better(v, i, best, at)) { best = v; at = i; } + } + for (ushort d = 16; d > 0; d >>= 1) { + const float ov = simd_shuffle_xor(best, d); + const uint oi = simd_shuffle_xor(at, d); + if (mm_better(ov, oi, best, at)) { best = ov; at = oi; } + } + if (lane == 0) { vals[sg] = best; idxs[sg] = at; } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (sg != 0) return; + best = vals[lane]; + at = idxs[lane]; + for (ushort d = 16; d > 0; d >>= 1) { + const float ov = simd_shuffle_xor(best, d); + const uint oi = simd_shuffle_xor(at, d); + if (mm_better(ov, oi, best, at)) { best = ov; at = oi; } + } + if (lane == 0) ids[0] = at; +} + + +// bf16 rows into fp32 ones (n values): an image's rows over their placeholders' embeddings, the tower's pre-norm out. +[[kernel]] void mm_widen(const device bfloat* X [[buffer(0)]], device float* Y [[buffer(1)]], constant uint& n [[buffer(2)]], + uint i [[thread_position_in_grid]]) { + if (i < n) Y[i] = float(X[i]); +} + +// fp32 rows to bf16 ones (n values): the tower's last residual for the projector. +[[kernel]] void mm_narrow(const device float* X [[buffer(0)]], device bfloat* Y [[buffer(1)]], constant uint& n [[buffer(2)]], + uint i [[thread_position_in_grid]]) { + if (i < n) Y[i] = bfloat(X[i]); +} diff --git a/zig/kernels/metal/minimax_m3/index_nax.metal b/zig/kernels/metal/minimax_m3/index_nax.metal new file mode 100644 index 00000000000..045b294969d --- /dev/null +++ b/zig/kernels/metal/minimax_m3/index_nax.metal @@ -0,0 +1,111 @@ +// MiniMax-M3's indexer block scores on the tensor units: S[row, h, b] = max over b's keys of IQ[row, h] . IK[key]. +#include "../nax.h" +using namespace tfp; + +// Defines: DH (128, the index dim), IH (index heads). + +constant constexpr int LD = DH; + +// torch's max: a NaN wins (Metal's max is fmax and drops it). +inline float nmax(float x, float y) { return isnan(x) || isnan(y) ? NAN : max(x, y); } + +// Row max over a fragment's 32 columns into r[0], r[1] (rows home.y, home.y + 8). +inline void fold_max(thread const frag& f, thread float* r) { + TF_UNROLL + for (short h = 0; h < 2; h++) { + const short b = 4 * h; + float t = nmax(nmax(f[b], f[b + 1]), nmax(f[b + 2], f[b + 3])); + t = nmax(t, simd_shuffle_xor(t, ushort(1))); + t = nmax(t, simd_shuffle_xor(t, ushort(8))); + r[h] = nmax(r[h], t); + } +} + +constant constexpr int RT = 32; // query rows a tile +constant constexpr int NS = DH / 64; // simdgroups a tile, each its own 64 output columns +constant constexpr int KS = 32; // keys a simdgroup a block +constant constexpr int BKT = KS * NS; // keys a block + +template +inline frag blk(const device bfloat* p, int ld, int r, int c, short2 home) { +#ifndef TF_SIMD_FRAGS + const device bfloat* q = p + (r + home.y) * ld + c + home.x; + return frag(*(const device bfloat4*)q, *(const device bfloat4*)(q + 8 * ld)); +#else + frag f; + if (TR) { + frag_get_t(f, p, ld, r, c, home); + } else { + frag_get(f, p, ld, r, c, home); + } + return f; +#endif +} + +// IQ [R, IH, DH] at P.y..; IK [slot, DH]; S [R, IH, P.z]. A tile is RT rows of an index head, 64 keys a step. +[[max_total_threads_per_threadgroup(256)]] +[[kernel]] void mm_index_scores_nax(const device bfloat* IQ [[buffer(0)]], const device bfloat* IK [[buffer(1)]], + device float* S [[buffer(2)]], constant int3& P [[buffer(3)]], + uint sg [[simdgroup_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]], uint3 tg [[threadgroup_position_in_grid]]) { + const int R = P.x, p0 = P.y, blocks = P.z; + const int h = int(tg.y); + const int r0 = int(tg.x) * RT; + const int q_rows = min(RT, R - r0); + const int qs = IH * DH; + const device bfloat* q = IQ + r0 * qs + h * DH; + const short2 home = frag_home(ushort(lane)); + threadgroup float rowmax[NS][RT]; + float best[4] = {-INFINITY, -INFINITY, -INFINITY, -INFINITY}; + const int first_pos = p0 + r0, last_pos = p0 + r0 + q_rows - 1; + const int steps = last_pos / BKT + 1; + for (int kb = 0; kb < steps; kb++) { + const int kpos = kb * BKT + int(sg) * KS; + const device bfloat* kblk = IK + long(kpos) * LD; + frag s[4]; + TF_UNROLL + for (short i = 0; i < 4; i++) s[i] = frag(0); + for (int d = 0; d < DH / 16; d++) { + const frag k0 = blk(kblk, LD, 0, 16 * d, home); + const frag k1 = blk(kblk, LD, 16, 16 * d, home); + TF_UNROLL + for (short hh = 0; hh < 2; hh++) { + const frag qf = blk(q, qs, 16 * hh, 16 * d, home); + mma_16x32(s[2 * hh], s[2 * hh + 1], qf, k0, k1); + } + } + TF_UNROLL + for (short i = 0; i < 4; i++) { + TF_UNROLL + for (short e = 0; e < 8; e++) { + const int local = 16 * (i >> 1) + home.y + (e >> 2) * 8, row = first_pos + local; + const int col = kpos + 16 * (i & 1) + home.x + TF_COL(e); + if (col > row) s[i][e] = -INFINITY; // a key past the row (or never written): no part of the block's max + } + } + float m[4] = {-INFINITY, -INFINITY, -INFINITY, -INFINITY}; + TF_UNROLL + for (short i = 0; i < 4; i++) fold_max(s[i], m + 2 * (i >> 1)); + threadgroup_barrier(mem_flags::mem_threadgroup); // the step before has read rowmax + if (home.x == 0) { + TF_UNROLL + for (short j = 0; j < 4; j++) rowmax[sg][home.y + 8 * j] = m[j]; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + TF_UNROLL + for (short j = 0; j < 4; j++) + for (int u = 0; u < NS; u++) best[j] = nmax(best[j], rowmax[u][home.y + 8 * j]); + if (kb % 2 == 1 || kb + 1 == steps) { // a block's two steps done (or its first, when it is the tile's last) + const int b = kb / 2; + if (sg == 0 && home.x == 0 && b < blocks) { + TF_UNROLL + for (short j = 0; j < 4; j++) { + const int local = home.y + 8 * j; + if (local < q_rows) S[(long(r0 + local) * IH + h) * blocks + b] = best[j]; + } + } + TF_UNROLL + for (short j = 0; j < 4; j++) best[j] = -INFINITY; + } + } +} diff --git a/zig/kernels/metal/sources.zig b/zig/kernels/metal/sources.zig index 6e06cb42f98..f5d5861ad88 100644 --- a/zig/kernels/metal/sources.zig +++ b/zig/kernels/metal/sources.zig @@ -168,6 +168,18 @@ pub const core_simd_qmm = @embedFile("core/simd_qmm.metal"); pub const core_simd_qmm_bits = @embedFile("core/simd_qmm_bits.metal"); /// Step-5's glue at StepFun's rounding points: embed, norms, q/k rotation, gate, SwiGLU, residual adds. pub const step5_glue = @embedFile("step5/glue.metal"); +/// MiniMax-M3's glue at transformers' rounding points: norms, rotation, SwiGLU-OAI, router, indexer, decode attention. +pub const minimax_m3_glue = @embedFile("minimax_m3/glue.metal"); +/// MiniMax-M3's prompt attention on the tensor units over each row's kept index blocks. +pub const minimax_m3_attention_nax = @embedFile("minimax_m3/attention_nax.metal"); +/// MiniMax-M3's DSpark drafter (norms, q/k into its context rings, block attention, the Markov chain) and the taps. +pub const minimax_m3_dspark = @embedFile("minimax_m3/dspark.metal"); +/// MiniMax-M3's decode-window experts expert by expert (after core_row_projection: its sums, each weight read once). +pub const minimax_m3_experts = @embedFile("minimax_m3/experts.metal"); +/// incoai's DFlash2 drafter for MiniMax-M3: Qwen3 norms, full RoPE, the block convolution, top-k and the selector. +pub const minimax_m3_dflash2 = @embedFile("minimax_m3/dflash2.metal"); +/// MiniMax-M3's indexer block scores on the tensor units (a prompt chunk's). +pub const minimax_m3_index_nax = @embedFile("minimax_m3/index_nax.metal"); /// Step-5's sparse indexer (summaries, scores, top-k) and its sliding, sparse and dense attention. pub const step5_sparse = @embedFile("step5/sparse.metal"); /// Step-5's prompt attention on the tensor units (a KV group's 16 heads one operand; nax.h inlined at load). diff --git a/zig/src/cli/hub.zig b/zig/src/cli/hub.zig index fe4602429d2..04506527c2c 100644 --- a/zig/src/cli/hub.zig +++ b/zig/src/cli/hub.zig @@ -18,6 +18,7 @@ const titles = [_]struct { model_type: []const u8, title: []const u8 }{ .{ .model_type = "gemma4_unified", .title = "Gemma 4 12B" }, .{ .model_type = "step5_vl", .title = "Step-5-Preview" }, .{ .model_type = "spark2_5", .title = "Spark-X2.6-4B" }, + .{ .model_type = "minimax_m3_vl", .title = "MiniMax-M3.1-Flash" }, .{ .model_type = "lfm2_moe", .title = "LFM2.5-24B-A2B" }, }; diff --git a/zig/src/core/attention_range.zig b/zig/src/core/attention_range.zig index 196d9046d6a..d8cb6bc57f6 100644 --- a/zig/src/core/attention_range.zig +++ b/zig/src/core/attention_range.zig @@ -21,6 +21,13 @@ pub const Form = struct { /// The chains of o's terms p_j v_j and of l's terms p_j, as roundings of their terms' magnitude. num: f64, den: f64, + /// Roundings on a score past its dot (Metal's fp32 SCALE * log2e: 4), and in the final division (fast: 3). + score_round: f64 = 1, + div: f64 = 1, + /// A weight's exp as (a + b |x|) ulps of 2^-23 (Metal's fast::exp: 40 + 2 |x|), in place of fast_exp's. + exp_ulps: ?[2]f64 = null, + /// The scores' max keeps a NaN (Metal's softmax), where @max drops it. + nan_max: bool = false, }; /// An mma k16 step's error in 2^-24 of |acc| + sum |a b|: 17 terms cut at the largest's ulp, then rounded down. @@ -51,8 +58,8 @@ pub fn head(q: []const f64, k: []const f64, v: []const f64, n: usize, d: usize, a += @abs(q[e] * k[j * d + e]); } w[j] = s * scale; - tau[j] = f.score * u * a * @abs(scale) + u * @abs(w[j]); // the score's spread; below, the weight's - m = @max(m, w[j]); + tau[j] = f.score * u * a * @abs(scale) + f.score_round * u * @abs(w[j]); // the score's spread; below, the weight's + m = if (f.nan_max and (std.math.isNan(w[j]) or std.math.isNan(m))) std.math.nan(f64) else @max(m, w[j]); if (std.math.isFinite(tau[j])) dmax = @max(dmax, tau[j]); } var l: f64 = 0; @@ -60,7 +67,7 @@ pub fn head(q: []const f64, k: []const f64, v: []const f64, n: usize, d: usize, var vmax: f64 = 0; for (w[0..n], tau[0..n]) |*p, *t| { const x = (m - p.*) + 2 * dmax; // |the computed s_j - max| at most - var e = t.* + u * x + if (f.fast_exp) (3 + 1.2 * x) * 0x1p-23 else 0x1p-22; + var e = t.* + u * x + if (f.exp_ulps) |c| (c[0] + c[1] * x) * 0x1p-23 else if (f.fast_exp) (3 + 1.2 * x) * 0x1p-23 else 0x1p-22; if (f.chunk_exp) e += 0x1p-22 + u * x; p.* = @exp(p.* - m); l += p.*; @@ -94,7 +101,7 @@ pub fn head(q: []const f64, k: []const f64, v: []const f64, n: usize, d: usize, const e1 = dv / (1 - tmax); const en = (gamma(f.num) + f.p_rel) * r * kappa; const base = @abs(o) + e1 + en; - half[e] = (e1 + en + (gamma(f.den) + u) * base) * (1 + 0x1p-20) + tiny; + half[e] = (e1 + en + (gamma(f.den) + f.div * u) * base) * (1 + 0x1p-20) + tiny; } } diff --git a/zig/src/core/contract.zig b/zig/src/core/contract.zig index 1f6cce169fc..6828c844cc6 100644 --- a/zig/src/core/contract.zig +++ b/zig/src/core/contract.zig @@ -7,6 +7,7 @@ pub const rows = @import("contract/rows.zig"); pub const affine = @import("contract/affine.zig"); pub const dense = @import("contract/dense.zig"); pub const bf16_round = @import("bf16_round.zig"); +pub const attention_range = @import("attention_range.zig"); pub const limits = @import("contract/limits.zig"); pub const registry = @import("contract/registry.zig"); pub const cubin = @import("contract/cubin.zig"); diff --git a/zig/src/core/contract/minimax_draft_records.zig b/zig/src/core/contract/minimax_draft_records.zig new file mode 100644 index 00000000000..f34eea9bebc --- /dev/null +++ b/zig/src/core/contract/minimax_draft_records.zig @@ -0,0 +1,18 @@ +//! MiniMax-M3.1-Flash's draft launches (metal_minimax_draft*.zig): dspark.metal in both builds, and dflash2.metal. +const M = @import("limits.zig").MetalLaunch; +pub const records = [_]M{ + .{ .name = "minimax_m3 draft target mm_tap", .threads = 256, .tg_memory = 0, .m1 = 1024, .m2 = 1024 }, + .{ .name = "minimax_m3 draft target 8 q heads mm_draft_vec", .threads = 256, .tg_memory = 0, .m1 = 1024, .m2 = 1024 }, + .{ .name = "minimax_m3 draft dspark 16 q heads mm_draft_vec", .threads = 512, .tg_memory = 0, .m1 = 1024, .m2 = 1024 }, + .{ .name = "minimax_m3 draft dspark mm_norm16", .threads = 256, .tg_memory = 128, .m1 = 1024, .m2 = 1024 }, + .{ .name = "minimax_m3 draft dspark mm_draft_prep", .threads = 32, .tg_memory = 512, .m1 = 1024, .m2 = 1024 }, + .{ .name = "minimax_m3 draft dspark mm_markov_step", .threads = 256, .tg_memory = 1088, .m1 = 1024, .m2 = 1024 }, + .{ .name = "minimax_m3 draft dspark mm_markov_pick", .threads = 1024, .tg_memory = 256, .m1 = 1024, .m2 = 1024 }, + .{ .name = "minimax_m3 draft dflash2 df_norm", .threads = 256, .tg_memory = 128, .m1 = 1024, .m2 = 1024 }, + .{ .name = "minimax_m3 draft dflash2 df_norm16", .threads = 256, .tg_memory = 128, .m1 = 1024, .m2 = 1024 }, + .{ .name = "minimax_m3 draft dflash2 df_prep", .threads = 32, .tg_memory = 512, .m1 = 1024, .m2 = 1024 }, + .{ .name = "minimax_m3 draft dflash2 df_conv", .threads = 256, .tg_memory = 0, .m1 = 1024, .m2 = 1024 }, + .{ .name = "minimax_m3 draft dflash2 df_silu", .threads = 256, .tg_memory = 0, .m1 = 1024, .m2 = 1024 }, + .{ .name = "minimax_m3 draft dflash2 df_topk", .threads = 1024, .tg_memory = 16384, .m1 = 1024, .m2 = 1024 }, + .{ .name = "minimax_m3 draft dflash2 df_walk", .threads = 256, .tg_memory = 1040, .m1 = 1024, .m2 = 1024 }, +}; diff --git a/zig/src/core/contract/minimax_glue_records.zig b/zig/src/core/contract/minimax_glue_records.zig new file mode 100644 index 00000000000..9de63eb4ac3 --- /dev/null +++ b/zig/src/core/contract/minimax_glue_records.zig @@ -0,0 +1,16 @@ +//! MiniMax-M3.1-Flash's glue launches (zig/tests/contract/metal_minimax_glue.zig). +const M = @import("limits.zig").MetalLaunch; +pub const records = [_]M{ + .{ .name = "minimax_m3 glue embed mm_embed", .threads = 256, .tg_memory = 0, .m1 = 1024, .m2 = 1024 }, + .{ .name = "minimax_m3 glue norm 1024 mm_norm", .threads = 1024, .tg_memory = 128, .m1 = 1024, .m2 = 1024 }, + .{ .name = "minimax_m3 glue norm 256 mm_norm", .threads = 256, .tg_memory = 128, .m1 = 1024, .m2 = 1024 }, + .{ .name = "minimax_m3 glue add_norm 1024 mm_add_norm", .threads = 1024, .tg_memory = 128, .m1 = 1024, .m2 = 1024 }, + .{ .name = "minimax_m3 glue add_norm 256 mm_add_norm", .threads = 256, .tg_memory = 128, .m1 = 1024, .m2 = 1024 }, + .{ .name = "minimax_m3 glue add mm_add", .threads = 256, .tg_memory = 0, .m1 = 1024, .m2 = 1024 }, + .{ .name = "minimax_m3 glue SwiGLU mm_swiglu", .threads = 256, .tg_memory = 0, .m1 = 1024, .m2 = 1024 }, + .{ .name = "minimax_m3 glue moe_add_norm 1024 mm_moe_add_norm", .threads = 1024, .tg_memory = 128, .m1 = 1024, .m2 = 1024 }, + .{ .name = "minimax_m3 glue moe_add mm_moe_add", .threads = 256, .tg_memory = 0, .m1 = 1024, .m2 = 1024 }, + .{ .name = "minimax_m3 glue widen mm_widen", .threads = 256, .tg_memory = 0, .m1 = 1024, .m2 = 1024 }, + .{ .name = "minimax_m3 glue narrow mm_narrow", .threads = 256, .tg_memory = 0, .m1 = 1024, .m2 = 1024 }, + .{ .name = "minimax_m3 glue argmax mm_argmax", .threads = 1024, .tg_memory = 256, .m1 = 1024, .m2 = 1024 }, +}; diff --git a/zig/src/core/contract/minimax_nax_records.zig b/zig/src/core/contract/minimax_nax_records.zig new file mode 100644 index 00000000000..622f90dab7e --- /dev/null +++ b/zig/src/core/contract/minimax_nax_records.zig @@ -0,0 +1,9 @@ +//! MiniMax-M3.1-Flash's nax launches (metal_minimax_nax.zig); the grouped experts reserve 64 threads, as GLM's rows do. +const M = @import("limits.zig").MetalLaunch; +pub const records = [_]M{ + .{ .name = "minimax_m3 nax experts q3 mm_experts_grouped_q3", .threads = 64, .tg_memory = 0, .reserved = 64 }, + .{ .name = "minimax_m3 nax experts q4 mm_experts_grouped_q4", .threads = 64, .tg_memory = 0, .reserved = 64 }, + // tensor ops before the M5 too (nax.h's simdgroup fragments still multiply through mpp): no offline build + .{ .name = "minimax_m3 nax attention mm_prompt_attention", .threads = 64, .tg_memory = 9472, .reserved = 256, .offline = false }, + .{ .name = "minimax_m3 nax index mm_index_scores_nax", .threads = 64, .tg_memory = 256, .reserved = 256, .offline = false }, +}; diff --git a/zig/src/core/contract/minimax_records.zig b/zig/src/core/contract/minimax_records.zig new file mode 100644 index 00000000000..78b459dc0e6 --- /dev/null +++ b/zig/src/core/contract/minimax_records.zig @@ -0,0 +1,7 @@ +//! MiniMax-M3.1-Flash's Metal launches, one file a kernel group. +const std = @import("std"); +pub const records = @import("minimax_glue_records.zig").records ++ @import("minimax_route_records.zig").records ++ @import("minimax_nax_records.zig").records ++ @import("minimax_draft_records.zig").records; + +test "MiniMax-M3.1-Flash's launches fit every Apple family" { + try std.testing.expectEqual(@as(usize, 0), try @import("registry.zig").checkMetal(std.testing.allocator, &records, true)); +} diff --git a/zig/src/core/contract/minimax_route_records.zig b/zig/src/core/contract/minimax_route_records.zig new file mode 100644 index 00000000000..49fe003ec9c --- /dev/null +++ b/zig/src/core/contract/minimax_route_records.zig @@ -0,0 +1,14 @@ +//! MiniMax-M3.1-Flash's route launches (metal_minimax_route*.zig); mm_router reserves the 256 threads it launches. +const M = @import("limits.zig").MetalLaunch; +pub const records = [_]M{ + .{ .name = "minimax_m3 route router mm_router", .threads = 256, .tg_memory = 2048, .reserved = 256 }, + .{ .name = "minimax_m3 route pick mm_route_pick", .threads = 32, .tg_memory = 0, .m1 = 1024, .m2 = 1024 }, + .{ .name = "minimax_m3 route groups mm_route_groups", .threads = 1024, .tg_memory = 0, .m1 = 1024, .m2 = 1024 }, + .{ .name = "minimax_m3 route sort mm_sort", .threads = 1024, .tg_memory = 18944, .m1 = 1024, .m2 = 1024 }, + .{ .name = "minimax_m3 route rows mm_rows_by_order", .threads = 256, .tg_memory = 0, .m1 = 1024, .m2 = 1024 }, + .{ .name = "minimax_m3 route prep mm_prep", .threads = 32, .tg_memory = 512, .m1 = 1024, .m2 = 1024 }, + .{ .name = "minimax_m3 route index scores mm_index_scores", .threads = 128, .tg_memory = 17408, .m1 = 1024, .m2 = 1024 }, + .{ .name = "minimax_m3 route index select mm_index_select", .threads = 32, .tg_memory = 0, .m1 = 1024, .m2 = 1024 }, + .{ .name = "minimax_m3 route decode partials mm_decode_vec", .threads = 512, .tg_memory = 0, .m1 = 1024, .m2 = 1024 }, + .{ .name = "minimax_m3 route decode merge mm_merge_vec", .threads = 32, .tg_memory = 0, .m1 = 928, .m2 = 928 }, +}; diff --git a/zig/src/core/contract/registry.zig b/zig/src/core/contract/registry.zig index 33022358308..bfd8a91131a 100644 --- a/zig/src/core/contract/registry.zig +++ b/zig/src/core/contract/registry.zig @@ -567,10 +567,11 @@ test { const paging = @import("paging_pending.zig"); test { _ = paging; + _ = @import("minimax_records.zig"); } /// The Metal collector keeps measured slots and the restored vision declarations. pub const all_metal = metal ++ @import("delta_slots_records.zig").records ++ @import("flashnext_pending.zig").records ++ @import("simd_pairs_records.zig").records ++ @import("metal_pair_records.zig").records ++ @import("glm_rows_records.zig").records ++ @import("weight_only_records.zig").metal ++ @import("hc_activation_records.zig").metal ++ @import("qwen4_records.zig").metal ++ @import("lfm2_records.zig").records ++ @import("nemotron_experts_records.zig").records ++ @import("nemotron_pages_records.zig").records ++ @import("nemotron_attention_records.zig").records ++ - @import("moss_image_records.zig").records; + @import("moss_image_records.zig").records ++ @import("minimax_records.zig").records; const learning = @import("registry_learning.zig"); pub const gradient_pending = learning.gradient_pending; pub const qwen_learning_pending = learning.qwen_learning_pending; diff --git a/zig/src/families/minimax_m3/backend.zig b/zig/src/families/minimax_m3/backend.zig new file mode 100644 index 00000000000..bc8bd3106f4 --- /dev/null +++ b/zig/src/families/minimax_m3/backend.zig @@ -0,0 +1,528 @@ +//! MiniMax-M3.1-Flash behind the lane engine: a cache a stream; lone steps run ahead, drawn on the GPU into a ring. +const std = @import("std"); +const mtl = @import("metal"); +const lanes = @import("lanes"); +const st = @import("state.zig"); +const fwd = @import("forward.zig"); +const Model = @import("model.zig").Model; +const snapshot = @import("snapshot.zig"); +const row = @import("../step5/backend.zig").row; +const be = lanes.backend; + +/// A stream's longest context, the streams, the caches' bytes; `drafts`: every round a tapped window (no step ahead). +pub const Options = struct { capacity: usize, streams: u32 = 4, budget: u64, drafts: bool = false }; + +/// Widths measure() times: a pending token and a block of drafts. +const max_window = 8; + +/// 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; + +/// A committed step: the token slots below `end` are written when `cb` completes. +const Flight = struct { end: u64, cb: mtl.CommandBuffer }; + +/// The prompt cache's room beside the streams: its kept states fit in `bytes`, never evicting `restoring`. +pub const Room = struct { ctx: *anyopaque, fit: *const fn (ctx: *anyopaque, bytes: u64, restoring: ?*anyopaque, prompt: []const u32) void }; + +pub const Metal = struct { + gpa: std.mem.Allocator, + model: *Model, + options: Options, + scratch: st.Scratch, // decode rounds + prompt: st.Scratch, // prompt chunks + caches: std.AutoHashMapUnmanaged(*lanes.Stream, *st.Cache) = .empty, + follow: ?mtl.ResidencySet.Follow = null, + held: u64 = 0, // bytes the streams' caches hold + room: ?Room = null, // the prompt cache, which takes what the streams leave of the budget + tokens: mtl.Buffer, // u32 [ring] + next: u64 = 0, // the next free token slot + landed: u64 = 0, // slots below it are written + flights: std.ArrayList(Flight) = .empty, + sink: ?be.FeatureSink = null, // a drafting prompt pass's: each chunk's tapped rows as they are made + costs: [max_window]lanes.config.Cost = undefined, // window forward ms by rows, timed by measure() for the depth rule + timed: usize = 0, + values: []f32, // a logits row as f32, for the host twin of the GPU draw + + pub fn init(gpa: std.mem.Allocator, model: *Model, options: Options) !*Metal { + const out = try gpa.create(Metal); + errdefer gpa.destroy(out); + var scratch = try st.Scratch.init(model.device, &model.config, st.batch_rows, options.capacity); + errdefer scratch.deinit(); + var prompt = try st.Scratch.init(model.device, &model.config, st.prompt_rows, options.capacity); + errdefer prompt.deinit(); + const tokens = try model.device.buffer(ring * 4, mtl.ResourceOptions.shared); + errdefer tokens.deinit(); + out.* = .{ .gpa = gpa, .model = model, .options = options, .scratch = scratch, .prompt = prompt, .tokens = tokens, .values = try gpa.alloc(f32, model.config.vocab) }; + return out; + } + + pub fn deinit(self: *Metal) void { + self.drain() catch {}; + self.flights.deinit(self.gpa); + self.tokens.deinit(); + self.gpa.free(self.values); + self.setResident(null); + var it = self.caches.valueIterator(); + while (it.next()) |cache| { + cache.*.deinit(); + self.gpa.destroy(cache.*); + } + self.caches.deinit(self.gpa); + self.scratch.deinit(); + self.prompt.deinit(); + self.gpa.destroy(self); + } + + pub fn setResident(self: *Metal, hook: ?mtl.ResidencySet.Follow) void { + if (self.follow) |f| { + mtl.resident.fields.apply(&self.scratch, f, false); + mtl.resident.fields.apply(&self.prompt, f, false); + } + self.follow = hook; + if (hook) |f| { + mtl.resident.fields.apply(&self.scratch, f, true); + mtl.resident.fields.apply(&self.prompt, f, true); + } + var it = self.caches.valueIterator(); + while (it.next()) |cache| cache.*.setResident(hook); + } + + pub fn createCache(self: *Metal, capacity: usize) !*st.Cache { + const cache = try self.gpa.create(st.Cache); + errdefer self.gpa.destroy(cache); + cache.* = try st.Cache.init(self.model.device, &self.model.config, capacity); + cache.setResident(self.follow); + return cache; + } + + 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 = !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 { + const c = &self.model.config; + var cache = try st.Cache.init(self.model.device, c, 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; + var ts0: std.c.timespec = undefined; + _ = std.c.clock_gettime(.MONOTONIC, &ts0); + try fwd.run(self.model, &self.scratch, &cache, ids[0..rows], .{ .all = true }); + var ts1: std.c.timespec = undefined; + _ = std.c.clock_gettime(.MONOTONIC, &ts1); + if (run == 1) ms = @as(f64, @floatFromInt(ts1.sec - ts0.sec)) * 1e3 + @as(f64, @floatFromInt(ts1.nsec - ts0.nsec)) / 1e6; + } + 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.UnpreparedMiniMaxTaps; + if (count == 0 or start < tp.start or start + count > tp.start + tp.rows) return error.MiniMaxTapsNotHeld; + 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.UnpreparedMiniMaxTaps; + self.sink = sink; + defer self.sink = null; + return prefillFn(ptr, stream); + } + + pub fn backend(self: *Metal) be.Backend { + 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 { + return @ptrCast(@alignCast(ptr)); + } + + fn cacheOf(self: *Metal, stream: *lanes.Stream) !*st.Cache { + return self.caches.get(stream) orelse error.UnknownMiniMaxStream; + } + + fn logits(self: *Metal, cache: *st.Cache) []const u16 { + return cache.logits.slice(u16, self.model.config.vocab); + } + + /// The GPU draw's host twin (lanes' gpu_full): argmax or the keyed race at `position`, a mask's tokens only. + fn draw(self: *Metal, l: []const u16, sampling: ?lanes.Sampling, position: u64, mask: []const u32) !u32 { + const t = sampled(sampling) orelse { // gpu_rule's argmax: the first largest, masked tokens at -inf + var best: ?usize = null; + for (l, 0..) |w, id| { + if (mask.len > 0 and !lanes.grammar.allows(mask, id)) continue; + if (best == null or logit(w) > logit(l[best.?])) best = id; + } + return @intCast(best orelse 0); + }; + for (l, self.values, 0..) |w, *v, id| { + v.* = logit(w); + if (mask.len > 0 and !lanes.grammar.allows(mask, id)) v.* = -std.math.inf(f32); + } + return lanes.gpu_full.draw(self.gpa, self.values, t, @intCast(position), null); + } + + fn sampled(sampling: ?lanes.Sampling) ?lanes.Sampling { + const t = sampling orelse return null; + return if (t.temperature > 0) t else null; + } + + /// `n` consecutive token slots, never wrapping the ring. + fn take(self: *Metal, n: usize) u64 { + if (self.next % ring + n > ring) self.next += ring - self.next % ring; + const h = self.next; + self.next += n; + return h; + } + + fn slotOf(self: *Metal, h: u64) fwd.B { + return .{ .buf = self.tokens, .off = @intCast(h % ring * 4) }; + } + + /// Wait for the oldest step in flight. + fn land(self: *Metal) !void { + const f = self.flights.orderedRemove(0); + defer f.cb.release(); + f.cb.wait(); + if (f.cb.failure()) |msg| { + std.log.err("minimax_m3 step: {s}", .{msg}); + return error.GpuFailed; + } + self.landed = @max(self.landed, f.end); + } + + /// Every step in flight landed: before the host reads caches or logits, or the GPU runs anything else. + fn drain(self: *Metal) !void { + while (self.flights.items.len > 0) try self.land(); + } + + /// Run `ids` at the cache's end in prompt chunks; a stream's pass stops at its chunk starts and reuse marks. + fn feed(self: *Metal, cache: *st.Cache, ids: []const u32, stream: ?*lanes.Stream, images: []const fwd.Span) !void { + const base = cache.len; + var at: usize = 0; + while (at < ids.len) { + var end = @min(ids.len, at + st.prompt_rows); + if (stream) |sm| { + if (sm.isCancelled()) return error.Cancelled; + for (sm.chunks) |x| if (x > base + at and x < base + end) { + end = x - base; + }; + for (sm.reuse.marks) |x| if (x > base + at and x < base + end) { + end = x - base; + }; + } + const s = if (end - at > st.batch_rows) &self.prompt else &self.scratch; + const taps = if (stream != null) s.taps else null; + try fwd.run(self.model, s, cache, ids[at..end], .{ .taps = if (taps) |x| fwd.b(x) else null, .images = images }); + if (taps) |x| { + if (self.sink) |k| try k.take(k.ptr, stream.?, .{ .buffer = @intFromPtr(x.id), .rows = @intCast(end - at), .row_bytes = @intCast(self.tapBytes()), .space = .device, .dtype = .bf16 }, cache.len); + if (base + end == stream.?.prompt().len) { // the prompt's last row, kept for the first draft + const width = self.tapBytes(); + if (cache.last_tap == null) cache.last_tap = try self.model.device.buffer(width, mtl.ResourceOptions.shared); + @memcpy(cache.last_tap.?.slice(u8, width), x.slice(u8, (end - at) * width)[(end - at - 1) * width ..][0..width]); + cache.tap = .{ .buf = cache.last_tap, .start = cache.len + (end - at) - 1, .rows = 1 }; + } + } + 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)); + } + } + + fn prefillFn(ptr: *anyopaque, stream: *lanes.Stream) !void { + const self = cast(ptr); + try self.drain(); + const ids = stream.prompt(); + if (ids.len == 0 or ids.len + stream.max_new > self.options.capacity or self.caches.contains(stream)) return error.InvalidMiniMaxPrompt; + const capacity = ids.len + stream.max_new + 1; + const need = st.cacheBytes(&self.model.config, capacity); + if (self.held + need > self.options.budget) { + std.log.warn("minimax_m3: a {d}-token stream needs {d:.1} GiB of caches; {d:.1} of {d:.1} GiB are held", .{ capacity, gib(need), gib(self.held), gib(self.options.budget) }); + return error.MiniMaxCachesFull; + } + self.held += need; + errdefer self.held -= need; + if (stream.reuse.saved) |saved| { // a state the stream cannot hold beside its caches: freed now, no restore + const snap: *snapshot.Snap = @ptrCast(@alignCast(saved)); + if (self.held + snap.bytes > self.options.budget) snap.free(); + } + // kept states give way first + if (self.room) |r| r.fit(r.ctx, self.options.budget - self.held, stream.reuse.saved, ids); + const cache = try self.createCache(capacity); + errdefer self.gpa.destroy(cache); + errdefer cache.deinit(); + try self.caches.put(self.gpa, stream, cache); // a mark's save finds it there + errdefer _ = self.caches.remove(stream); + stream.cached = 0; + if (stream.reuse.saved) |saved| { // a kept state of this prompt's prefix: the pass starts there + const snap: *const snapshot.Snap = @ptrCast(@alignCast(saved)); + if (snap.at < ids.len) { + if (snapshot.restore(self.model.queue, &self.model.config, snap, cache)) stream.cached = snap.at else |_| stream.reuse_failed = true; + } else stream.reuse_failed = true; + } + var spans: std.ArrayList(fwd.Span) = .empty; + defer spans.deinit(self.gpa); + const rows_buf = try self.encodeImages(stream, cache.len, &spans); + defer if (rows_buf) |b| b.deinit(); + try self.feed(cache, ids[cache.len..], stream, spans.items); + } + + /// The tower's rows of the stream's images past `from` (one before it is in the restored state), a span each. + fn encodeImages(self: *Metal, stream: *const lanes.Stream, from: usize, spans: *std.ArrayList(fwd.Span)) !?mtl.Buffer { + var total: usize = 0; + for (stream.images) |im| { + if (im.at + im.tokens > stream.prompt().len or im.tokens * 4 != im.gh * im.gw) return error.InvalidMiniMaxImage; + if (im.at + im.tokens > from) total += im.tokens; + } + if (total == 0) return null; + const v = self.model.vision orelse return error.NoMiniMaxVision; + const width: usize = self.model.config.hidden; + const buf = try self.model.device.buffer(total * width * 2, mtl.ResourceOptions.private | mtl.ResourceOptions.untracked); + errdefer buf.deinit(); + var done: usize = 0; + for (stream.images) |im| { // one command buffer an image: the tower's host-written tables are one image's + if (im.at + im.tokens <= from) continue; + const span: fwd.Span = .{ .at = im.at, .n = im.tokens, .rows = .{ .buf = buf, .off = done * width * 2 } }; + const cb = self.model.queue.commandBuffer(); + const e = cb.compute(.serial); + try v.encode(e, im.pixels, im.gh, im.gw, span.rows); + e.end(); + cb.commit(); + cb.wait(); + if (cb.failure()) |msg| { + std.log.err("minimax_m3: the image tower failed: {s}", .{msg}); + return error.GpuFailed; + } + try spans.append(self.gpa, span); + done += im.tokens; + } + return buf; + } + + /// A prompt chunk and a decode window once: the first request skips the GPU's first touch. + pub fn warm(self: *Metal) !void { + const c = &self.model.config; + var cache = try st.Cache.init(self.model.device, c, @min(self.options.capacity, st.prompt_rows + st.window_rows)); + defer cache.deinit(); + var ids: [st.prompt_rows]u32 = undefined; + for (&ids, 0..) |*t, i| t.* = @intCast(1000 + i * 37 % 20000); + const n = cache.capacity - st.window_rows; + try self.feed(&cache, ids[0..n], null, &.{}); + try fwd.run(self.model, &self.scratch, &cache, ids[0..st.window_rows], .{ .all = true }); + } + + /// The first token, drawn on the host from the prompt's last row into a fresh slot. + fn firstFn(ptr: *anyopaque, stream: *lanes.Stream, position: u64) !u64 { + return cast(ptr).firstSlot(stream, position, &.{}); + } + + fn firstMaskedFn(ptr: *anyopaque, stream: *lanes.Stream, position: u64, mask: []const u32) !u64 { + return cast(ptr).firstSlot(stream, position, mask); + } + + fn firstSlot(self: *Metal, stream: *lanes.Stream, position: u64, mask: []const u32) !u64 { + try self.drain(); + const cache = try self.cacheOf(stream); + if (position != cache.len) return error.InvalidMiniMaxPosition; + const h = self.take(1); + self.tokens.slice(u32, ring)[h % ring] = try self.draw(self.logits(cache), stream.sampling, position, mask); + return h; + } + + /// A step behind those in flight: its token from the ring or the host, the next drawn into a slot; read() lands it. + fn queueFn(ptr: *anyopaque, stream: *lanes.Stream, f: be.Feed, position: u64) !u64 { + const self = cast(ptr); + const cache = try self.cacheOf(stream); + if (position != cache.len + 1) return error.InvalidMiniMaxPosition; + const in = switch (f) { + .handle => |h| h, + .value => |v| blk: { + if (v >= self.model.config.vocab) return error.InvalidMiniMaxToken; + const h = self.take(1); + self.tokens.slice(u32, ring)[h % ring] = v; + break :blk h; + }, + }; + const out = self.take(1); + const how: @FieldType(fwd.Draw, "how") = if (sampled(stream.sampling)) |t| .{ .sampled = .{ .sampling = t, .position = position } } else .greedy; + var cb: mtl.CommandBuffer = undefined; + try fwd.run(self.model, &self.scratch, cache, &.{0}, .{ .ids = self.slotOf(in), .draw = .{ .how = how, .out = self.slotOf(out) }, .flight = &cb }); + self.flights.append(self.gpa, .{ .end = out + 1, .cb = cb }) catch |err| { + cb.wait(); + cb.release(); + return err; + }; + cache.len += 1; + return out; + } + + fn firstRowFn(ptr: *anyopaque, stream: *lanes.Stream) !lanes.LogprobRow { + const self = cast(ptr); + try self.drain(); + const l = self.logits(try self.cacheOf(stream)); + return row(l, @intCast(argmax(l)), stream.logprobs orelse 0); + } + + /// A slot's token, once the step that writes it has landed (host-fed slots are written at once). + fn readFn(ptr: *anyopaque, handle: u64) !u32 { + const self = cast(ptr); + while (handle >= self.landed and self.flights.items.len > 0) try self.land(); + const token = self.tokens.slice(u32, ring)[handle % ring]; + if (token >= self.model.config.vocab) return error.InvalidMiniMaxToken; + return token; + } + + /// Every window's pending token and drafts in one shared forward, every row drawn and kept until `keep` rolls back. + fn verifyFn(ptr: *anyopaque, windows: []const be.Window, out: []be.Verified) !void { + const self = cast(ptr); + const c = &self.model.config; + const words = (c.vocab + 31) / 32; + if (windows.len != out.len or windows.len > st.batch_rows) return error.InvalidMiniMaxWindows; + try self.drain(); + var segments: [st.batch_rows]fwd.Segment = undefined; + var ids: [st.batch_rows]u32 = undefined; + var total: usize = 0; + for (windows, out, 0..) |w, o, i| { + const rows = w.rows(); + if (rows > st.window_rows or total + rows > st.batch_rows or w.parents != null or w.held != 0 or o.sampled.len != rows or o.drafts.len != rows - 1) return error.UnsupportedMiniMaxWindow; + const cache = try self.cacheOf(w.stream); + for (w.positions, 0..) |p, r| if (p != cache.len + r + 1) return error.InvalidMiniMaxPosition; + segments[i] = .{ .cache = cache, .rows = rows }; + ids[total] = w.pending; + @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, .taps = if (self.scratch.taps) |x| fwd.b(x) else null }); + if (self.scratch.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 * c.vocab); + var base: usize = 0; + for (windows, out, segments[0..windows.len]) |w, o, seg| { + const rows = seg.rows; + seg.cache.len += rows; + @memcpy(o.drafts, w.tokens); + for (0..rows) |r| { + const l = all[(base + r) * c.vocab ..][0..c.vocab]; + const mask = if (w.masks.len >= (r + 1) * words) w.masks[r * words ..][0..words] else &.{}; + o.sampled[r] = try self.draw(l, w.stream.sampling, w.positions[r], mask); + if (o.rows.len == rows) o.rows[r] = row(l, o.sampled[r], w.stream.logprobs orelse 0); + } + // the last kept row's logits are the next first draw's (the lane core keeps every row here) + @memcpy(seg.cache.logits.slice(u16, c.vocab), all[(base + rows - 1) * c.vocab ..][0..c.vocab]); + base += rows; + } + } + + fn keepFn(ptr: *anyopaque, windows: []const be.Window, paths: []const []const u32) !void { + const self = cast(ptr); + try self.drain(); + for (windows, paths) |w, path| { + const cache = try self.cacheOf(w.stream); + for (path, 0..) |r, i| if (r != i) return error.UnsupportedMiniMaxTree; + if (path.len == 0 or path.len > w.rows() or w.rows() > cache.len) return error.UnsupportedMiniMaxWindow; + cache.len = cache.len - w.rows() + path.len; + } + } + + /// No draft head: a request at depth 0 holds nothing; the lane core's copy drafts come as window tokens. + fn draftFn(ptr: *anyopaque, requests: []const be.DraftRequest) !void { + _ = ptr; + for (requests) |r| if (r.depth != 0) return error.MiniMaxHasNoDraftHead; + } + + fn heldFn(_: *anyopaque, _: *lanes.Stream, out: []u32) !void { + if (out.len > 0) return error.MiniMaxDraftsNotHeld; + } + + fn releaseFn(ptr: *anyopaque, stream: *lanes.Stream) void { + const self = cast(ptr); + self.drain() catch |err| std.log.err("minimax_m3: a step in flight failed at release: {s}", .{@errorName(err)}); + if (self.caches.fetchRemove(stream)) |entry| { + self.held -= st.cacheBytes(&self.model.config, entry.value.capacity); + entry.value.deinit(); + self.gpa.destroy(entry.value); + if (self.room) |r| r.fit(r.ctx, self.options.budget - self.held, null, &.{}); + } + } + + /// The prompt cache's Snapshots functions: a stream's caches at a mark, copied on the GPU. + pub fn snapBytes(ptr: *anyopaque, at: u32) u64 { + return snapshot.bytes(&cast(ptr).model.config, at); + } + + pub fn snapSave(ptr: *anyopaque, owner: ?*anyopaque, at: u32) anyerror!*anyopaque { + const self = cast(ptr); + try self.drain(); + const cache = try self.cacheOf(@ptrCast(@alignCast(owner orelse return error.NoStream))); + if (cache.len != at) return error.SnapshotOutOfStep; + const snap = try self.gpa.create(snapshot.Snap); + errdefer self.gpa.destroy(snap); + snap.* = try snapshot.save(self.model.device, self.model.queue, &self.model.config, cache); + return snap; + } + + pub fn snapRestore(_: *anyopaque, _: ?*anyopaque, _: *anyopaque) anyerror!void { + return error.BackendRestores; // the prompt pass restores, before its first chunk + } + + pub fn snapDrop(ptr: *anyopaque, saved: *anyopaque) void { + const snap: *snapshot.Snap = @ptrCast(@alignCast(saved)); + snap.free(); + cast(ptr).gpa.destroy(snap); + } +}; + +fn gib(bytes: u64) f64 { + return @as(f64, @floatFromInt(bytes)) / (1 << 30); +} + +fn logit(word: u16) f32 { + return @bitCast(@as(u32, word) << 16); +} + +fn argmax(l: []const u16) usize { + var best: usize = 0; + for (l, 0..) |w, i| if (logit(w) > logit(l[best])) { + best = i; + }; + return best; +} diff --git a/zig/src/families/minimax_m3/budget.zig b/zig/src/families/minimax_m3/budget.zig new file mode 100644 index 00000000000..5461cb68b86 --- /dev/null +++ b/zig/src/families/minimax_m3/budget.zig @@ -0,0 +1,44 @@ +//! What a MiniMax-M3 load may hold: weights, scratch and every stream's caches under a limit set below the panic line. +const std = @import("std"); +const cfg = @import("config.zig"); +const st = @import("state.zig"); + +/// The default share of RAM: past about 80% wired, macOS stalls until its watchdog restarts the Mac. +pub const default_share = 0.75; +/// Kept free inside the limit for the command buffers, the keepalive and the host. +pub const margin: u64 = 2 << 30; + +/// Bytes for caches: `ram` times the share (or MINIMAX_LOAD_LIMIT_GB, at most the working set), less the rest. +pub fn caches(ram: u64, working_set: u64, text: ?[]const u8, resident: u64) error{BadLoadLimit}!u64 { + var limit: u64 = @intFromFloat(@as(f64, @floatFromInt(ram)) * default_share); + const t = std.mem.trim(u8, text orelse "", " \t"); + if (t.len > 0) { + const gb = std.fmt.parseFloat(f64, t) catch return error.BadLoadLimit; + if (!std.math.isFinite(gb) or gb <= 0) return error.BadLoadLimit; + const most = @min(ram, working_set); + const bytes = gb * 1e9; // compared as a float first: a huge limit would overflow the integer + limit = if (bytes >= @as(f64, @floatFromInt(most))) most else @intFromFloat(bytes); + } + return if (limit > resident + margin) limit - resident - margin else 0; +} + +/// The longest context one stream's caches fit in `bytes`, at most `most`. +pub fn longest(c: *const cfg.Config, bytes: u64, most: usize) usize { + if (st.cacheBytes(c, 1) > bytes) return 0; + var lo: usize = 1; + var hi: usize = most; + while (lo < hi) { + const mid = lo + (hi - lo + 1) / 2; + if (st.cacheBytes(c, mid) <= bytes) lo = mid else hi = mid - 1; + } + return lo; +} + +test "minimax_m3 budget: a share of RAM less the weights, a set limit capped at the working set, bad text refused" { + const gib: u64 = 1 << 30; + try std.testing.expectEqual(@as(u64, 192 * gib - 24 * gib - margin), try caches(256 * gib, 240 * gib, null, 24 * gib)); + try std.testing.expectEqual(@as(u64, 0), try caches(256 * gib, 240 * gib, null, 191 * gib)); + try std.testing.expectEqual(@as(u64, 64 * gib - 24 * gib - margin), try caches(256 * gib, 240 * gib, "68.719476736", 24 * gib)); + try std.testing.expectError(error.BadLoadLimit, caches(256 * gib, 240 * gib, "lots", 24 * gib)); + try std.testing.expectEqual(@as(u64, 240 * gib - 24 * gib - margin), try caches(256 * gib, 240 * gib, "1e30", 24 * gib)); +} diff --git a/zig/src/families/minimax_m3/config.zig b/zig/src/families/minimax_m3/config.zig new file mode 100644 index 00000000000..8c4f2affe75 --- /dev/null +++ b/zig/src/families/minimax_m3/config.zig @@ -0,0 +1,210 @@ +//! MiniMax-M3.1-Flash's shape from the release's config.json (text_config): routed or dense MLP, sparse attention. +const std = @import("std"); + +pub const max_layers = 128; + +/// A layer's attention (block-sparse with the lightning indexer, or dense) and its MLP (routed or dense). +pub const Layer = struct { sparse: bool, moe: bool }; + +pub const Config = struct { + hidden: u32 = 6144, + layers: u32 = 60, + vocab: u32 = 200064, + eps: f32 = 1e-6, + heads: u32 = 64, + kv_heads: u32 = 4, + head_dim: u32 = 128, + /// Rotated dims of each head (and of each index head): the first `rotary`, NeoX halves. + rotary: u32 = 64, + theta: f32 = 1e7, + dense_intermediate: u32 = 12288, + moe_intermediate: u32 = 3072, + shared_intermediate: u32 = 3072, + experts: u32 = 128, + topk: u32 = 4, + routed_scale: f32 = 2.0, + swiglu_alpha: f32 = 1.702, + swiglu_limit: f32 = 7.0, + index_heads: u32 = 4, + index_dim: u32 = 128, + /// Keys an index block pools: the unit of selection. + block: u32 = 128, + /// Blocks a query keeps at most (its own included). + topk_blocks: u32 = 16, + context: u32 = 1048576, + image_token: u32 = 200025, + layer: [max_layers]Layer = undefined, + + pub fn read(gpa: std.mem.Allocator, io: std.Io, dir: []const u8) !Config { + const path = try std.fs.path.join(gpa, &.{ dir, "config.json" }); + defer gpa.free(path); + const bytes = try std.Io.Dir.cwd().readFileAlloc(io, path, gpa, .limited(1 << 22)); + defer gpa.free(bytes); + return parse(gpa, bytes); + } + + /// Key and value width of one token in one layer. + pub fn kvWidth(c: *const Config) u32 { + return c.kv_heads * c.head_dim; + } + + /// Rows of the stacked q | k | v | index q | index k projection. + pub fn qkvRows(c: *const Config) u32 { + return (c.heads + 2 * c.kv_heads) * c.head_dim + (c.index_heads + 1) * c.index_dim; + } + + /// Index blocks a context of `len` keys spans. + pub fn blocks(c: *const Config, len: usize) usize { + return std.math.divCeil(usize, len, c.block) catch unreachable; + } +}; + +fn field(o: std.json.ObjectMap, key: []const u8) !std.json.Value { + return o.get(key) orelse { + std.log.err("minimax_m3: config.json lacks {s}", .{key}); + return error.BadMiniMaxConfig; + }; +} + +fn number(v: std.json.Value) !f64 { + return switch (v) { + .integer => |i| @floatFromInt(i), + .float => |f| f, + else => error.BadMiniMaxConfig, + }; +} + +fn int(o: std.json.ObjectMap, key: []const u8) !u32 { + const v = try field(o, key); + if (v != .integer or v.integer <= 0 or v.integer > std.math.maxInt(u32)) return error.BadMiniMaxConfig; + return @intCast(v.integer); +} + +fn flag(o: std.json.ObjectMap, key: []const u8, want: bool) !void { + const v = try field(o, key); + if (v != .bool or v.bool != want) return error.UnsupportedMiniMaxConfig; +} + +fn says(o: std.json.ObjectMap, key: []const u8, want: []const u8) !void { + const v = try field(o, key); + if (v != .string or !std.mem.eql(u8, v.string, want)) return error.UnsupportedMiniMaxConfig; +} + +/// A per-layer 0/1 list of `layers` entries. +fn perLayer(o: std.json.ObjectMap, key: []const u8, layers: u32, out: []bool) !void { + const v = try field(o, key); + if (v != .array or v.array.items.len != layers) return error.BadMiniMaxConfig; + for (v.array.items, 0..) |x, i| { + if (x != .integer or x.integer < 0 or x.integer > 1) return error.BadMiniMaxConfig; + out[i] = x.integer == 1; + } +} + +pub fn parse(gpa: std.mem.Allocator, bytes: []const u8) !Config { + var doc = try std.json.parseFromSlice(std.json.Value, gpa, bytes, .{}); + defer doc.deinit(); + if (doc.value != .object) return error.BadMiniMaxConfig; + const root = doc.value.object; + try says(root, "model_type", "minimax_m3_vl"); + const text = try field(root, "text_config"); + if (text != .object) return error.BadMiniMaxConfig; + const t = text.object; + var c = Config{}; + c.hidden = try int(t, "hidden_size"); + c.layers = try int(t, "num_hidden_layers"); + c.vocab = try int(t, "vocab_size"); + c.eps = @floatCast(try number(try field(t, "rms_norm_eps"))); + c.heads = try int(t, "num_attention_heads"); + c.kv_heads = try int(t, "num_key_value_heads"); + c.head_dim = try int(t, "head_dim"); + c.rotary = try int(t, "rotary_dim"); + c.theta = @floatCast(try number(try field(t, "rope_theta"))); + c.dense_intermediate = try int(t, "dense_intermediate_size"); + c.moe_intermediate = try int(t, "intermediate_size"); + c.shared_intermediate = try int(t, "shared_intermediate_size"); + c.experts = try int(t, "num_local_experts"); + c.topk = try int(t, "num_experts_per_tok"); + c.routed_scale = @floatCast(try number(try field(t, "routed_scaling_factor"))); + c.swiglu_alpha = @floatCast(try number(try field(t, "swiglu_alpha"))); + c.swiglu_limit = @floatCast(try number(try field(t, "swiglu_limit"))); + c.context = try int(t, "max_position_embeddings"); + if (root.get("image_token_index")) |v| if (v == .integer and v.integer > 0) { + c.image_token = @intCast(v.integer); + }; + if (c.layers > max_layers) return error.BadMiniMaxConfig; + // the release's arithmetic: Gemma norms on every head, sigmoid scores with the correction bias, one shared expert + try flag(t, "use_gemma_norm", true); + try flag(t, "use_qk_norm", true); + try flag(t, "use_routing_bias", true); + try flag(t, "attention_output_gate", false); + try flag(t, "tie_word_embeddings", false); + try says(t, "scoring_func", "sigmoid"); + try says(t, "hidden_act", "swigluoai"); + try says(t, "qk_norm_type", "per_head"); + if ((try int(t, "n_shared_experts")) != 1) return error.UnsupportedMiniMaxConfig; + const sp = try field(t, "sparse_attention_config"); + if (sp != .object) return error.BadMiniMaxConfig; + const s = sp.object; + try flag(s, "use_sparse_attention", true); + try says(s, "sparse_score_type", "max"); + c.index_heads = try int(s, "sparse_num_index_heads"); + c.index_dim = try int(s, "sparse_index_dim"); + c.block = try int(s, "sparse_block_size"); + c.topk_blocks = try int(s, "sparse_topk_blocks"); + // init blocks 0 and one local block (the query's own) are what the selection kernels force + const init = try field(s, "sparse_init_block"); + if (init != .integer or init.integer != 0 or (try int(s, "sparse_local_block")) != 1) return error.UnsupportedMiniMaxAttention; + var sparse: [max_layers]bool = undefined; + var moe: [max_layers]bool = undefined; + var no_value: [max_layers]bool = undefined; + try perLayer(s, "sparse_attention_freq", c.layers, &sparse); + try perLayer(s, "sparse_disable_index_value", c.layers, &no_value); + try perLayer(t, "moe_layer_freq", c.layers, &moe); + for (0..c.layers) |i| { + // the index-value branch is off on every sparse layer of the release; dense attention layers are not built + if (!sparse[i] or !no_value[i]) return error.UnsupportedMiniMaxAttention; + c.layer[i] = .{ .sparse = sparse[i], .moe = moe[i] }; + } + try validate(&c); + return c; +} + +/// The kernels' shape limits: a head in 32 lanes' registers, four index heads (one a key head), 128-key blocks. +pub fn validate(c: *const Config) error{ UnsupportedMiniMaxAttention, UnsupportedMiniMaxExperts }!void { + if (c.head_dim != 128 or c.index_dim != 128 or c.heads % c.kv_heads != 0 or c.heads / c.kv_heads > 32 or + c.index_heads != c.kv_heads or c.index_heads != 4 or c.rotary == 0 or c.rotary > c.head_dim or c.rotary % 2 != 0 or c.block != 128 or + c.topk_blocks == 0 or c.topk_blocks > 32) return error.UnsupportedMiniMaxAttention; + if (c.hidden == 0 or c.hidden % 1024 != 0 or c.experts == 0 or c.experts % 8 != 0 or c.experts > 256 or c.topk == 0 or c.topk > 8 or + c.moe_intermediate % 64 != 0 or c.shared_intermediate % 64 != 0 or c.dense_intermediate % 64 != 0) return error.UnsupportedMiniMaxExperts; +} + +test "minimax_m3 config: the release's shape, three dense layers, every layer sparse" { + const c = try parse(std.testing.allocator, @embedFile("config_fixture.json")); + try std.testing.expectEqual(@as(u32, 60), c.layers); + try std.testing.expect(!c.layer[0].moe and !c.layer[2].moe and c.layer[3].moe and c.layer[59].moe); + try std.testing.expect(c.layer[0].sparse and c.layer[59].sparse); + try std.testing.expectEqual(@as(u32, 64), c.rotary); + try std.testing.expectEqual(@as(u32, 9856), c.qkvRows()); + try std.testing.expectEqual(@as(usize, 17), c.blocks(2049)); + try std.testing.expectEqual(@as(f32, 2.0), c.routed_scale); +} + +test "minimax_m3 config: the flat converted form, softmax scores, init blocks, an index-value branch or a dense layer are refused" { + const fixture = @embedFile("config_fixture.json"); + const Case = struct { from: []const u8, to: []const u8, err: anyerror }; + const cases = [_]Case{ + .{ .from = "\"model_type\": \"minimax_m3_vl\"", .to = "\"model_type\": \"minimax_m3\"", .err = error.UnsupportedMiniMaxConfig }, + .{ .from = "\"scoring_func\": \"sigmoid\"", .to = "\"scoring_func\": \"softmax\"", .err = error.UnsupportedMiniMaxConfig }, + .{ .from = "\"sparse_init_block\": 0", .to = "\"sparse_init_block\": 1", .err = error.UnsupportedMiniMaxAttention }, + .{ .from = "\"sparse_disable_index_value\": [\n 1,", .to = "\"sparse_disable_index_value\": [\n 0,", .err = error.UnsupportedMiniMaxAttention }, + .{ .from = "\"sparse_attention_freq\": [\n 1,", .to = "\"sparse_attention_freq\": [\n 0,", .err = error.UnsupportedMiniMaxAttention }, + .{ .from = "\"head_dim\": 128", .to = "\"head_dim\": 96", .err = error.UnsupportedMiniMaxAttention }, + .{ .from = "\"num_experts_per_tok\": 4", .to = "\"num_experts_per_tok\": 9", .err = error.UnsupportedMiniMaxExperts }, + }; + for (cases) |x| { + const bytes = try std.mem.replaceOwned(u8, std.testing.allocator, fixture, x.from, x.to); + defer std.testing.allocator.free(bytes); + try std.testing.expect(!std.mem.eql(u8, bytes, fixture)); + try std.testing.expectError(x.err, parse(std.testing.allocator, bytes)); + } +} diff --git a/zig/src/families/minimax_m3/config_fixture.json b/zig/src/families/minimax_m3/config_fixture.json new file mode 100644 index 00000000000..f27c332770f --- /dev/null +++ b/zig/src/families/minimax_m3/config_fixture.json @@ -0,0 +1,299 @@ +{ + "architectures": [ + "MiniMaxM3SparseForConditionalGeneration" + ], + "auto_map": { + "AutoConfig": "configuration_minimax_m3_vl.MiniMaxM3VLConfig" + }, + "model_type": "minimax_m3_vl", + "text_config": { + "hidden_size": 6144, + "intermediate_size": 3072, + "num_hidden_layers": 60, + "num_attention_heads": 64, + "num_key_value_heads": 4, + "head_dim": 128, + "vocab_size": 200064, + "max_position_embeddings": 1048576, + "rms_norm_eps": 1e-06, + "use_gemma_norm": true, + "attention_output_gate": false, + "rope_theta": 10000000, + "rotary_dim": 64, + "partial_rotary_factor": 0.5, + "hidden_act": "swigluoai", + "use_qk_norm": true, + "tie_word_embeddings": false, + "dense_intermediate_size": 12288, + "shared_intermediate_size": 3072, + "num_local_experts": 128, + "num_experts_per_tok": 4, + "n_shared_experts": 1, + "scoring_func": "sigmoid", + "use_routing_bias": true, + "moe_layer_freq": [ + 0, + 0, + 0, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1 + ], + "qk_norm_type": "per_head", + "swiglu_alpha": 1.702, + "swiglu_limit": 7.0, + "routed_scaling_factor": 2.0, + "sparse_attention_config": { + "use_sparse_attention": true, + "sparse_index_dim": 128, + "sparse_num_index_heads": 4, + "sparse_topk_blocks": 16, + "sparse_block_size": 128, + "sparse_score_type": "max", + "sparse_init_block": 0, + "sparse_local_block": 1, + "sparse_attention_freq": [ + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1 + ], + "sparse_disable_index_value": [ + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1 + ] + }, + "architectures": [ + "MiniMaxM3SparseForCausalLM" + ] + }, + "vision_config": { + "hidden_size": 1280, + "num_attention_heads": 16, + "num_hidden_layers": 32, + "intermediate_size": 5120, + "patch_size": 14, + "image_size": 672, + "projection_dim": 6144, + "position_embedding_type": "rope", + "rope_mode": "3d", + "rope_theta": 10000.0, + "attention_dropout": 0.0, + "hidden_act": "gelu", + "initializer_factor": 1.0, + "initializer_range": 0.02, + "layer_norm_eps": 1e-05, + "model_type": "clip_vision_model", + "num_channels": 3, + "vocab_size": 32000, + "img_token_compression_config": { + "image_token_compression_method": "patch_merge", + "spatial_merge_size": 2, + "temporal_patch_size": 2 + }, + "vision_segment_max_frames": 4 + }, + "img_token_compression_config": { + "image_token_compression_method": "patch_merge", + "spatial_merge_size": 2, + "temporal_patch_size": 2 + }, + "image_grid_pinpoints": "[(336, 336), (336, 672), (336, 1008), (336, 1344), (336, 1680), (336, 2016), (672, 336), (672, 672), (672, 1008), (672, 1344), (672, 1680), (672, 2016), (1008, 336), (1008, 672), (1008, 1008), (1008, 1344), (1008, 1680), (1008, 2016), (1344, 336), (1344, 672), (1344, 1008), (1344, 1344), (1344, 1680), (1344, 2016), (1680, 336), (1680, 672), (1680, 1008), (1680, 1344), (1680, 1680), (1680, 2016), (2016, 336), (2016, 672), (2016, 1008), (2016, 1344), (2016, 1680), (2016, 2016)]", + "image_seq_length": 576, + "image_token_index": 200025, + "video_token_index": 200026, + "multimodal_projector_bias": true, + "num_reward_heads": 0, + "process_image_mode": "dynamic_res", + "projector_hidden_act": "gelu", + "vision_feature_layer": -1, + "vision_feature_select_strategy": "full", + "torch_dtype": "bfloat16", + "transformers_version": "4.52.4", + "projector_hidden_size": 6144, + "quantization": { + "bits": 8, + "group_size": 64, + "mode": "affine", + "model.layers.3.mlp.switch_mlp.gate_proj": { + "bits": 3, + "group_size": 64 + } + }, + "source": { + "repo": "MiniMaxAI/MiniMax-M3.1-Flash", + "revision": "54e4e69dfc452b1e94a426c24a4fdeeaa8e3ad5e", + "expert_bits": 3, + "expert_group": 64, + "dense_bits": 8, + "dense_group": 64 + } +} diff --git a/zig/src/families/minimax_m3/dflash2.zig b/zig/src/families/minimax_m3/dflash2.zig new file mode 100644 index 00000000000..98d3a7314a4 --- /dev/null +++ b/zig/src/families/minimax_m3/dflash2.zig @@ -0,0 +1,530 @@ +//! incoai's DFlash2 drafter for MiniMax-M3.1-Flash (SGLang's DFlash2DraftModel): 8-row blocks over the target's 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 wts = @import("weights.zig"); +const fwd = @import("forward.zig"); +const Model = @import("model.zig").Model; +const now = @import("dspark.zig").now; + +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; + +/// The drafter's shape from config.json's `dflash2` (tools/convert.py writes it). +pub const Config = struct { + layers: u32 = 5, + heads: u32 = 64, + kv_heads: u32 = 8, + hidden: u32 = 6144, + ffn: u32 = 12288, + window: u32 = 2048, + block: u32 = 8, + mask: u32 = 200061, + rank: u32 = 256, + top: u32 = 32, + group: u32 = 16, + taps: [6]u32 = .{ 5, 16, 26, 37, 47, 58 }, + theta: f32 = 5e6, + eps: f32 = 1e-6, + + /// Ring slots of a layer's context: the window and a block past it, whole 128-key blocks. + pub fn ring(c: *const Config) u32 { + return std.mem.alignForward(u32, c.window + c.block, 128); + } + + pub fn read(gpa: std.mem.Allocator, io: std.Io, dir: []const u8) !?Config { + const path = try std.fs.path.join(gpa, &.{ dir, "config.json" }); + defer gpa.free(path); + const bytes = try std.Io.Dir.cwd().readFileAlloc(io, path, gpa, .limited(1 << 22)); + defer gpa.free(bytes); + var doc = try std.json.parseFromSlice(std.json.Value, gpa, bytes, .{}); + defer doc.deinit(); + const d = doc.value.object.get("dflash2") orelse return null; + if (d != .object) return error.BadDFlash2Config; + const o = d.object; + const int = struct { + fn of(x: std.json.ObjectMap, k: []const u8) !u32 { + const v = x.get(k) orelse return error.BadDFlash2Config; + if (v != .integer or v.integer <= 0) return error.BadDFlash2Config; + return @intCast(v.integer); + } + fn f(x: std.json.ObjectMap, k: []const u8) !f32 { + const v = x.get(k) orelse return error.BadDFlash2Config; + return switch (v) { + .integer => |i| @floatFromInt(i), + .float => |q| @floatCast(q), + else => error.BadDFlash2Config, + }; + } + }; + var c = Config{ + .layers = try int.of(o, "num_hidden_layers"), + .heads = try int.of(o, "num_attention_heads"), + .kv_heads = try int.of(o, "num_key_value_heads"), + .hidden = try int.of(o, "hidden_size"), + .ffn = try int.of(o, "intermediate_size"), + .window = try int.of(o, "sliding_window"), + .block = try int.of(o, "block_size"), + .mask = try int.of(o, "mask_token_id"), + .rank = try int.of(o, "selector_rank"), + .top = try int.of(o, "selector_top_k"), + .group = try int.of(o, "conv_group_size"), + .theta = try int.f(o, "rope_theta"), + .eps = try int.f(o, "rms_norm_eps"), + }; + const taps = o.get("target_layer_ids") orelse return error.BadDFlash2Config; + if (taps != .array or taps.array.items.len != c.taps.len) return error.UnsupportedDFlash2; + for (taps.array.items, &c.taps) |x, *y| { + if (x != .integer or x.integer < 0) return error.BadDFlash2Config; + y.* = @intCast(x.integer); + } + if ((try int.of(o, "head_dim")) != 128 or (try int.of(o, "conv_kernel_size")) != 2 or c.layers > 8 or c.block != 8 or + c.rank != 256 or c.top != 32 or c.heads % c.kv_heads != 0 or c.hidden % c.group != 0) return error.UnsupportedDFlash2; + return c; + } +}; + +/// Rows a block takes (the trained block). +pub const max_block = 8; +/// Context rows one absorb pass projects at most (a prompt chunk's). +const absorb_rows = 2048; + +const Conv = struct { base: wts.Tensor, proj: wts.Linear }; +const Layer = struct { in_norm: wts.Tensor, post_norm: wts.Tensor, q_norm: wts.Tensor, k_norm: wts.Tensor, qkv: wts.Linear, o: wts.Linear, gu: wts.Linear, down: wts.Linear, attn_conv: Conv, mlp_conv: Conv }; + +const Weights = struct { + fc: wts.Linear, + hidden_norm: wts.Tensor, + norm: wts.Tensor, + ctx_kv: wts.Linear, + hproj: wts.Linear, + pred: wts.Tensor, + succ: wts.Tensor, + layers: [8]Layer, +}; + +fn tensor(c: *const ck.Checkpoint, name: []const u8) !wts.Tensor { + const x = try c.get(name); + if (x.dtype != .bf16) return error.UnexpectedDFlash2Tensor; + return x; +} + +fn affine(c: *const ck.Checkpoint, base: []const u8, n: usize, k: usize) !wts.Linear { + var buf: [128]u8 = undefined; + const w = try c.get(try std.fmt.bufPrint(&buf, "{s}.weight", .{base})); + const s = try c.get(try std.fmt.bufPrint(&buf, "{s}.scales", .{base})); + const z = try c.get(try std.fmt.bufPrint(&buf, "{s}.biases", .{base})); + return wts.checkedAffine(w, s, z, 1, n, k); +} + +fn load(ckp: *const ck.Checkpoint, c: *const Config, vocab: usize) !Weights { + const h: usize = c.hidden; + const kvw: usize = c.kv_heads * 128; + const dyn: usize = 4 * (h / c.group); + var w: Weights = .{ + .fc = try affine(ckp, "dflash2.fc", h, h * c.taps.len), + .hidden_norm = try tensor(ckp, "dflash2.hidden_norm.weight"), + .norm = try tensor(ckp, "dflash2.norm.weight"), + .ctx_kv = try affine(ckp, "dflash2.ctx_kv_proj", c.layers * 2 * kvw, h), + .hproj = try affine(ckp, "dflash2.hidden_projection", c.rank, h), + .pred = try tensor(ckp, "dflash2.predecessor_codebook"), + .succ = try tensor(ckp, "dflash2.successor_codebook"), + .layers = undefined, + }; + if (w.pred.count() != vocab * c.rank or w.succ.count() != vocab * c.rank) return error.UnexpectedDFlash2Tensor; + for (w.layers[0..c.layers], 0..) |*l, i| { + var nb: [128]u8 = undefined; + const name = struct { + fn of(buf: []u8, layer: usize, z: []const u8) ![]const u8 { + return std.fmt.bufPrint(buf, "dflash2.layers.{d}.{s}", .{ layer, z }); + } + }.of; + l.* = .{ + .in_norm = try tensor(ckp, try name(&nb, i, "input_layernorm.weight")), + .post_norm = try tensor(ckp, try name(&nb, i, "post_attention_layernorm.weight")), + .q_norm = try tensor(ckp, try name(&nb, i, "self_attn.q_norm.weight")), + .k_norm = try tensor(ckp, try name(&nb, i, "self_attn.k_norm.weight")), + .qkv = try affine(ckp, try name(&nb, i, "self_attn.qkv_proj"), (c.heads + 2 * c.kv_heads) * 128, h), + .o = try affine(ckp, try name(&nb, i, "self_attn.o_proj"), h, c.heads * 128), + .gu = try affine(ckp, try name(&nb, i, "mlp.gate_up_proj"), 2 * @as(usize, c.ffn), h), + .down = try affine(ckp, try name(&nb, i, "mlp.down_proj"), h, c.ffn), + .attn_conv = .{ .base = try tensor(ckp, try name(&nb, i, "attention_conv.base_kernel")), .proj = try affine(ckp, try name(&nb, i, "attention_conv.kernel_projection"), dyn, h) }, + .mlp_conv = .{ .base = try tensor(ckp, try name(&nb, i, "mlp_conv.base_kernel")), .proj = try affine(ckp, try name(&nb, i, "mlp_conv.kernel_projection"), dyn, h) }, + }; + if (l.attn_conv.base.count() != 4 * h or l.mlp_conv.base.count() != 4 * h) return error.UnexpectedDFlash2Tensor; + } + return w; +} + +/// One stream's context: each layer's keys and values for the last positions, a ring of Config.ring() slots. +const Lane = struct { + k: [8]mtl.Buffer, + v: [8]mtl.Buffer, + end: u64 = 0, // context rows absorbed: positions [from, end) + from: u64 = 0, // the first position held (a resumed prompt state's drafter context is not kept) + held: [max_block]u32 = @splat(0), + held_len: u32 = 0, +}; + +const names = [_][:0]const u8{ "df_norm", "df_norm16", "df_prep", "df_conv", "df_silu", "df_topk", "df_walk" }; +const Kernel = enum { norm, norm16, prep, conv, silu, 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", "sums", "vdst", "mdst" }; + +pub const Drafter = struct { + gpa: std.mem.Allocator, + target: *Model, + config: Config, + w: Weights, + pipes: [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, + + pub fn init(gpa: std.mem.Allocator, target: *Model, 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, .w = try load(&target.checkpoint, &config, target.config.vocab), .pipes = undefined }; + const c = &d.config; + if (c.hidden != target.config.hidden) return error.DFlash2ForAnotherTarget; + for (c.taps) |l| if (l >= target.config.layers) return error.DFlash2ForAnotherTarget; + { + const lib = try mtl.Library.fromSource(target.device, ks.minimax_m3_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 (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 h: usize = c.hidden; + const r: usize = max_block; + const qw: usize = c.heads * 128; + const kvw: usize = c.kv_heads * 128; + const nblk: usize = c.ring() / 128 + 1; + const vocab: usize = target.config.vocab; + const chunks: usize = (vocab + 2047) / 2048; + const dyn: usize = 4 * (h / c.group); + const sizes = [fields.len]usize{ r * 4, r * h * 4, r * h * 2, r * h * 2, r * 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, c.heads * r * nblk * 4, c.heads * r * nblk * 4, c.heads * r * nblk * 128 * 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 * c.layers * 2 * kvw * 2, absorb_rows * h * c.taps.len / 32 * 4, 16, 16 }; + 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.gpa.destroy(d); + } + + 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)]; + } + + pub fn setResident(d: *Drafter, hook: ?mtl.ResidencySet.Follow) void { + if (d.follow) |f| { + for (d.s) |x| f.leave(f.ctx, x); + var it = d.lanes.valueIterator(); + while (it.next()) |l| d.laneResident(l.*, f, false); + } + d.follow = hook; + if (hook) |f| { + for (d.s) |x| f.join(f.ctx, x); + 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 { + 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); + } + + /// Device bytes one stream's context takes. + pub fn laneBytes(d: *const Drafter) usize { + const c = &d.config; + return @as(usize, c.layers) * 2 * c.ring() * c.kv_heads * 128 * 2; + } + + pub fn drafter(d: *Drafter) dr.Drafter { + return .{ .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 = d.laneBytes() }; + } + + fn newLane(d: *Drafter) !*Lane { + const l = try d.gpa.create(Lane); + errdefer d.gpa.destroy(l); + l.* = .{ .k = undefined, .v = undefined }; + const bytes = @as(usize, d.config.ring()) * d.config.kv_heads * 128 * 2; + var made: usize = 0; + errdefer for (0..made) |i| { + l.k[i].deinit(); + l.v[i].deinit(); + }; + for (0..d.config.layers) |i| { + 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; + } + if (d.follow) |f| d.laneResident(l, f, true); + return l; + } + + fn dropLane(d: *Drafter, l: *Lane) void { + if (d.follow) |f| d.laneResident(l, f, false); + 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; + const l = try d.newLane(); + errdefer d.dropLane(l); + 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)); + } + + fn project(d: *const Drafter, e: mtl.ComputeEncoder, w: wts.Linear, in: B, out: B, rows: usize) !void { + // a block's rows on the tensor units: each weight (the target head's too) read once for all of them + return fwd.projectRows(e, d.target, d.buf("sums"), w, in, out, rows, 3); + } + + 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, eps: f32, theta: f32 }; + const VArgs = extern struct { rows: u32, pos0: u32, heads: u32, groups: u32, blocks: u32, first: u32, hi: u32, window: u32, ring: u32, scale: f32 }; + const CArgs = extern struct { rows: u32, width: u32, block: u32, groups: u32, side: u32 }; + + /// 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 = c.kv_heads * 128; + try d.project(e, d.w.fc, src, b(d.buf("fcx")), rows); + 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 }); + try d.project(e, d.w.ctx_kv, b(d.buf("hctx")), b(d.buf("kv")), rows); + for (0..c.layers) |i| { + const pa = PArgs{ .rows = @intCast(rows), .heads = 0, .kv_heads = c.kv_heads, .pos0 = @intCast(p0), .stride = c.layers * 2 * kvw, .q_off = 0, .k_off = @intCast(i * 2 * kvw), .v_off = @intCast(i * 2 * kvw + kvw), .ring = c.ring(), .eps = c.eps, .theta = c.theta }; + glue(e, d.pipe(.prep), pa, &.{ b(d.buf("kv")), t(d.w.layers[i].q_norm), t(d.w.layers[i].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`; rows older than a window and a block 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 = c.taps.len * c.hidden * 2; + for (items) |it| { + const l = d.lanes.get(it.stream) orelse return error.DraftStreamUnknown; + 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) 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 -| (c.window + c.block))) else it.start; + var at: u64 = keep_from; + while (at < end) { + const n: usize = @intCast(@min(absorb_rows, end - at)); + try 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 `conv`'s prepare: its coefficients into dyn, side 0 into xc. + fn convPrepare(d: *const Drafter, e: mtl.ComputeEncoder, conv: Conv, n: usize) !void { + const c = &d.config; + try d.project(e, conv.proj, b(d.buf("x")), b(d.buf("dyn")), n); + threads(e, d.pipe(.conv), CArgs{ .rows = @intCast(n), .width = c.hidden, .block = c.block, .groups = c.hidden / c.group, .side = 0 }, &.{ b(d.buf("x")), b(d.buf("dyn")), t(conv.base), A, b(d.buf("xc")) }, .{ c.hidden, n, 1 }); + } + + /// The block [pending, mask x 7] at positions anchor.. through the drafter; seq[1..] its drafts (rows 1-7's path). + 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 = c.heads * 128; + const kvw: usize = c.kv_heads * 128; + 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; + const MArgs = extern struct { rows: u32 = 0, width: u32 = 0, heads: u32 = 0, dim: u32 = 0, pos: u32 = 0, stride: u32 = 0, bits: u32 = 0, group: u32 = 0, eps: f32 = 0, alpha: f32 = 0, limit: f32 = 0, scale: f32 = 0 }; + glue(e, m.pipe(.embed), MArgs{ .rows = @intCast(n), .width = c.hidden, .bits = E.bits, .group = @intCast(E.group) }, &.{ b(d.buf("ids")), bo(E.w, E.w_off), bo(E.scales, E.s_off), bo(E.biases, E.b_off), A, b(d.buf("resid")) }, .{ (h + 255) / 256, n, 1 }, .{ 256, 1, 1 }); + const lo = @max((anchor + 1) -| c.window, l.from); + const hi = anchor + n; + const first = lo / 128; + const blocks = (hi - 1) / 128 - first + 1; + const groups: u32 = c.hidden / c.group; + 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 }); + try d.convPrepare(e, L.attn_conv, n); + try d.project(e, L.qkv, b(d.buf("xc")), b(d.buf("qkv")), n); + const pa = PArgs{ .rows = @intCast(n), .heads = c.heads, .kv_heads = c.kv_heads, .pos0 = @intCast(anchor), .stride = @intCast(qw + 2 * kvw), .q_off = 0, .k_off = @intCast(qw), .v_off = @intCast(qw + kvw), .ring = c.ring(), .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 va = VArgs{ .rows = @intCast(n), .pos0 = @intCast(anchor), .heads = c.heads, .groups = c.kv_heads, .blocks = @intCast(blocks), .first = @intCast(first), .hi = @intCast(hi), .window = c.window, .ring = c.ring(), .scale = 1.0 / @sqrt(128.0) }; + glue(e, m.draft_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 }); + const ma = extern struct { rows: u32, pos: u32, heads: u32, groups: u32, topk: u32, scale: f32, sel: u32, all: u32 }{ .rows = @intCast(n), .pos = 0, .heads = c.heads, .groups = c.kv_heads, .topk = @intCast(blocks), .scale = 0, .sel = 0, .all = 0 }; + glue(e, m.pipe(.merge_vec), ma, &.{ b(d.buf("pm")), b(d.buf("pl")), b(d.buf("po")), A, b(d.buf("attn")) }, .{ c.heads, n, 1 }, .{ 32, 1, 1 }); + try d.project(e, L.o, b(d.buf("attn")), b(d.buf("y")), n); + // the attention conv's finish (side 1, its prepare's coefficients), then the post-attention norm + threads(e, d.pipe(.conv), CArgs{ .rows = @intCast(n), .width = c.hidden, .block = c.block, .groups = groups, .side = 1 }, &.{ b(d.buf("y")), b(d.buf("dyn")), t(L.attn_conv.base), A, b(d.buf("yc")) }, .{ c.hidden, 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 }); + try d.convPrepare(e, L.mlp_conv, n); + try d.project(e, L.gu, b(d.buf("xc")), b(d.buf("gu")), n); + 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 }); + try d.project(e, L.down, b(d.buf("act")), b(d.buf("y")), n); + threads(e, d.pipe(.conv), CArgs{ .rows = @intCast(n), .width = c.hidden, .block = c.block, .groups = groups, .side = 1 }, &.{ b(d.buf("y")), b(d.buf("dyn")), t(L.mlp_conv.base), A, b(d.buf("yc")) }, .{ c.hidden, 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-7: the 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); + try d.project(e, m.weights.head, xr, b(d.buf("logits")), slots); + try d.project(e, d.w.hproj, xr, b(d.buf("hid")), slots); + const vocab: u32 = m.config.vocab; + const chunks: u32 = (vocab + 2047) / 2048; + const TArgs = extern struct { n: u32, stride: u32, chunks: u32, from_ids: u32 }; + glue(e, d.pipe(.topk), TArgs{ .n = vocab, .stride = 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 = 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; + 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); + try 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 >= d.target.config.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 = now(); + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const cb = d.target.queue.commandBuffer(); + const e = cb.compute(.serial); + try d.encodeBlock(e, l, 2, 0); + e.end(); + cb.commit(); + cb.wait(); + if (cb.failure()) |msg| return failed(msg); + if (run == 2) ms = now() - t0; + } + d.step_ms = ms / @as(f64, @floatFromInt(d.config.block - 1)); + } + + fn failed(msg: [*:0]const u8) anyerror { + std.log.err("minimax_m3 DFlash2 drafter: command buffer failed: {s}", .{msg}); + return error.GpuFailed; + } +}; diff --git a/zig/src/families/minimax_m3/dspark.zig b/zig/src/families/minimax_m3/dspark.zig new file mode 100644 index 00000000000..abda7d75e1b --- /dev/null +++ b/zig/src/families/minimax_m3/dspark.zig @@ -0,0 +1,513 @@ +//! MiniMax-M3.1's DSpark drafter (ref/dspark.py): 7-row blocks through five layers over the target's 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 wts = @import("weights.zig"); +const fwd = @import("forward.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; + +/// The drafter's shape from config.json's `dspark` (tools/convert.py writes it). +pub const Config = struct { + layers: u32 = 5, + heads: u32 = 64, + kv_heads: u32 = 4, + hidden: u32 = 6144, + ffn: u32 = 12288, + window: u32 = 4096, + block: u32 = 7, + noise: u32 = 200058, + rank: u32 = 256, + taps: [5]u32 = .{ 3, 17, 31, 45, 59 }, + rotary: u32 = 64, + theta: f32 = 1e7, + eps: f32 = 1e-6, + alpha: f32 = 1.702, + limit: f32 = 7.0, + + /// Ring slots of a layer's context: the window and a block past it, whole 128-key blocks. + pub fn ring(c: *const Config) u32 { + return std.mem.alignForward(u32, c.window + c.block, 128); + } + + pub fn read(gpa: std.mem.Allocator, io: std.Io, dir: []const u8) !?Config { + const path = try std.fs.path.join(gpa, &.{ dir, "config.json" }); + defer gpa.free(path); + const bytes = try std.Io.Dir.cwd().readFileAlloc(io, path, gpa, .limited(1 << 22)); + defer gpa.free(bytes); + var doc = try std.json.parseFromSlice(std.json.Value, gpa, bytes, .{}); + defer doc.deinit(); + const d = doc.value.object.get("dspark") orelse return null; + if (d != .object) return error.BadDSparkConfig; + const o = d.object; + const int = struct { + fn of(x: std.json.ObjectMap, k: []const u8) !u32 { + const v = x.get(k) orelse return error.BadDSparkConfig; + if (v != .integer or v.integer <= 0) return error.BadDSparkConfig; + return @intCast(v.integer); + } + fn f(x: std.json.ObjectMap, k: []const u8) !f32 { + const v = x.get(k) orelse return error.BadDSparkConfig; + return switch (v) { + .integer => |i| @floatFromInt(i), + .float => |q| @floatCast(q), + else => error.BadDSparkConfig, + }; + } + }; + var c = Config{ + .layers = try int.of(o, "num_hidden_layers"), + .heads = try int.of(o, "num_attention_heads"), + .kv_heads = try int.of(o, "num_key_value_heads"), + .hidden = try int.of(o, "hidden_size"), + .ffn = try int.of(o, "dspark_ffn_hidden_size"), + .window = try int.of(o, "sliding_window"), + .block = try int.of(o, "dspark_block_size"), + .noise = try int.of(o, "dspark_noise_token_id"), + .rank = try int.of(o, "dspark_markov_rank"), + .rotary = try int.of(o, "rotary_dim"), + .theta = try int.f(o, "rope_theta"), + .eps = try int.f(o, "rms_norm_eps"), + .alpha = try int.f(o, "swiglu_alpha"), + .limit = try int.f(o, "swiglu_limit"), + }; + const taps = o.get("dspark_target_layer_ids") orelse return error.BadDSparkConfig; + if (taps != .array or taps.array.items.len != c.taps.len) return error.UnsupportedDSpark; + for (taps.array.items, &c.taps) |x, *y| { + if (x != .integer or x.integer < 0) return error.BadDSparkConfig; + y.* = @intCast(x.integer); + } + if ((try int.of(o, "head_dim")) != 128 or c.layers > 8 or c.block > max_block or c.rank != 256 or c.heads % c.kv_heads != 0) return error.UnsupportedDSpark; + return c; + } +}; + +/// Rows a block takes at most (the trained block is 7). +pub const max_block = 8; +/// Context rows one absorb pass projects at most (a prompt chunk's). +const absorb_rows = 2048; + +const Layer = struct { in_norm: wts.Tensor, post_norm: wts.Tensor, q_norm: wts.Tensor, k_norm: wts.Tensor, qkv: wts.Linear, o: wts.Linear, gu: wts.Linear, down: wts.Linear }; + +const Weights = struct { + fc: wts.Linear, + hidden_norm: wts.Tensor, + norm: wts.Tensor, + ctx_kv: wts.Linear, + w1: wts.Tensor, + w2: wts.Linear, + layers: [8]Layer, +}; + +fn tensor(c: *const ck.Checkpoint, name: []const u8) !wts.Tensor { + const x = try c.get(name); + if (x.dtype != .bf16) return error.UnexpectedDSparkTensor; + return x; +} + +fn affine(c: *const ck.Checkpoint, base: []const u8, n: usize, k: usize) !wts.Linear { + var buf: [128]u8 = undefined; + const w = try c.get(try std.fmt.bufPrint(&buf, "{s}.weight", .{base})); + const s = try c.get(try std.fmt.bufPrint(&buf, "{s}.scales", .{base})); + const z = try c.get(try std.fmt.bufPrint(&buf, "{s}.biases", .{base})); + return wts.checkedAffine(w, s, z, 1, n, k); +} + +fn load(ckp: *const ck.Checkpoint, c: *const Config, vocab: usize) !Weights { + const h: usize = c.hidden; + const kvw: usize = c.kv_heads * 128; + var w: Weights = .{ + .fc = try affine(ckp, "dspark.fc", h, h * c.taps.len), + .hidden_norm = try tensor(ckp, "dspark.hidden_norm.weight"), + .norm = try tensor(ckp, "dspark.norm.weight"), + .ctx_kv = try affine(ckp, "dspark.ctx_kv_proj", c.layers * 2 * kvw, h), + .w1 = try tensor(ckp, "dspark.markov_w1.weight"), + .w2 = try affine(ckp, "dspark.markov_w2", vocab, c.rank), + .layers = undefined, + }; + if (w.w1.count() != vocab * c.rank or w.w2.bits != 8 or w.w2.group != 64) return error.UnexpectedDSparkTensor; + for (w.layers[0..c.layers], 0..) |*l, i| { + var pb: [64]u8 = undefined; + var nb: [128]u8 = undefined; + const p = try std.fmt.bufPrint(&pb, "dspark.layers.{d}.", .{i}); + const name = struct { + fn of(buf: []u8, a: []const u8, z: []const u8) ![]const u8 { + return std.fmt.bufPrint(buf, "{s}{s}", .{ a, z }); + } + }.of; + l.* = .{ + .in_norm = try tensor(ckp, try name(&nb, p, "input_layernorm.weight")), + .post_norm = try tensor(ckp, try name(&nb, p, "post_attention_layernorm.weight")), + .q_norm = try tensor(ckp, try name(&nb, p, "self_attn.q_norm.weight")), + .k_norm = try tensor(ckp, try name(&nb, p, "self_attn.k_norm.weight")), + .qkv = try affine(ckp, try name(&nb, p, "self_attn.qkv_proj"), (c.heads + 2 * c.kv_heads) * 128, h), + .o = try affine(ckp, try name(&nb, p, "self_attn.o_proj"), h, c.heads * 128), + .gu = try affine(ckp, try name(&nb, p, "mlp.gate_up_proj"), 2 * @as(usize, c.ffn), h), + .down = try affine(ckp, try name(&nb, p, "mlp.down_proj"), h, c.ffn), + }; + } + return w; +} + +/// One stream's context: each layer's keys and values for the last positions, a ring of Config.ring() slots. +const Lane = struct { + k: [8]mtl.Buffer, + v: [8]mtl.Buffer, + end: u64 = 0, // context rows absorbed: positions [from, end) + from: u64 = 0, // the first position held (a resumed prompt state's drafter context is not kept) + held: [max_block]u32 = @splat(0), + held_len: u32 = 0, +}; + +const names = [_][:0]const u8{ "mm_norm16", "mm_draft_prep", "mm_draft_vec", "mm_markov_step", "mm_markov_pick" }; +const Kernel = enum { norm16, prep, vec, markov_step, markov_pick }; + +/// The drafter's scratch, fields in init's order. +const fields = [_][]const u8{ "ids", "resid", "x", "qkv", "q", "attn", "y", "gu", "act", "logits", "pm", "pl", "po", "best", "best_id", "seq", "fcx", "hctx", "kv", "sums" }; + +pub const Drafter = struct { + gpa: std.mem.Allocator, + target: *Model, + config: Config, + w: Weights, + pipes: [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, + + pub fn init(gpa: std.mem.Allocator, target: *Model, 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, .w = try load(&target.checkpoint, &config, target.config.vocab), .pipes = undefined }; + const c = &d.config; + if (c.hidden != target.config.hidden) return error.DSparkForAnotherTarget; + for (c.taps) |l| if (l >= target.config.layers) return error.DSparkForAnotherTarget; + { + const lib = try mtl.Library.fromSource(target.device, ks.minimax_m3_dspark, .{ .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 (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 h: usize = c.hidden; + const r: usize = max_block; + const qw: usize = c.heads * 128; + const kvw: usize = c.kv_heads * 128; + const nblk: usize = c.ring() / 128 + 1; + const vocab: usize = target.config.vocab; + const sizes = [fields.len]usize{ r * 4, r * h * 4, r * h * 2, r * (qw + 2 * kvw) * 2, r * qw * 2, r * qw * 2, r * h * 2, r * 2 * c.ffn * 2, r * c.ffn * 2, r * vocab * 2, c.heads * r * nblk * 4, c.heads * r * nblk * 4, c.heads * r * nblk * 128 * 4, (vocab + 255) / 256 * 4, (vocab + 255) / 256 * 4, 16 * 4, absorb_rows * h * 2, absorb_rows * h * 2, absorb_rows * c.layers * 2 * kvw * 2, absorb_rows * h * c.taps.len / 32 * 4 }; + 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.gpa.destroy(d); + } + + 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)]; + } + + pub fn setResident(d: *Drafter, hook: ?mtl.ResidencySet.Follow) void { + if (d.follow) |f| { + for (d.s) |x| f.leave(f.ctx, x); + var it = d.lanes.valueIterator(); + while (it.next()) |l| d.laneResident(l.*, f, false); + } + d.follow = hook; + if (hook) |f| { + for (d.s) |x| f.join(f.ctx, x); + 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 { + 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); + } + + /// Device bytes one stream's context takes. + pub fn laneBytes(d: *const Drafter) usize { + const c = &d.config; + return @as(usize, c.layers) * 2 * c.ring() * c.kv_heads * 128 * 2; + } + + pub fn drafter(d: *Drafter) dr.Drafter { + return .{ .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, .step_ms = d.step_ms, .plain_guard = true, .stream_bytes = d.laneBytes() }; + } + + fn newLane(d: *Drafter) !*Lane { + const l = try d.gpa.create(Lane); + errdefer d.gpa.destroy(l); + l.* = .{ .k = undefined, .v = undefined }; + const bytes = @as(usize, d.config.ring()) * d.config.kv_heads * 128 * 2; + var made: usize = 0; + errdefer for (0..made) |i| { + l.k[i].deinit(); + l.v[i].deinit(); + }; + for (0..d.config.layers) |i| { + 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; + } + if (d.follow) |f| d.laneResident(l, f, true); + return l; + } + + fn dropLane(d: *Drafter, l: *Lane) void { + if (d.follow) |f| d.laneResident(l, f, false); + 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; + const l = try d.newLane(); + errdefer d.dropLane(l); + 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 project(d: *const Drafter, e: mtl.ComputeEncoder, w: wts.Linear, in: B, out: B, rows: usize) !void { + // a block's rows on the tensor units: each weight (the target head's too) read once for all of them + return fwd.projectRows(e, d.target, d.buf("sums"), w, in, out, rows, 3); + } + + /// 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 = c.kv_heads * 128; + try d.project(e, d.w.fc, src, b(d.buf("fcx")), rows); + glue(e, d.pipe(.norm16), extern struct { rows: u32, width: u32, eps: f32 }{ .rows = @intCast(rows), .width = c.hidden, .eps = c.eps }, &.{ b(d.buf("fcx")), t(d.w.hidden_norm), A, b(d.buf("hctx")) }, .{ rows, 1, 1 }, .{ 256, 1, 1 }); + try d.project(e, d.w.ctx_kv, b(d.buf("hctx")), b(d.buf("kv")), rows); + for (0..c.layers) |i| { + const pa = PArgs{ .rows = @intCast(rows), .heads = 0, .kv_heads = c.kv_heads, .pos0 = @intCast(p0), .rotary = c.rotary, .stride = c.layers * 2 * kvw, .q_off = 0, .k_off = @intCast(i * 2 * kvw), .v_off = @intCast(i * 2 * kvw + kvw), .ring = c.ring(), .eps = c.eps, .theta = c.theta }; + glue(e, d.pipe(.prep), pa, &.{ b(d.buf("kv")), t(d.w.layers[i].q_norm), t(d.w.layers[i].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`; rows older than a window and a block 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 = c.taps.len * c.hidden * 2; + for (items) |it| { + const l = d.lanes.get(it.stream) orelse return error.DraftStreamUnknown; + 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) 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; + // only the last window (and a block) of a long pass is ever read again + const keep_from = if (it.prompt) @max(it.start, (it.stream.prompt_len -| (c.window + c.block))) else it.start; + var at: u64 = keep_from; + while (at < end) { + const n: usize = @intCast(@min(absorb_rows, end - at)); + try 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); + } + + const PArgs = extern struct { rows: u32, heads: u32, kv_heads: u32, pos0: u32, rotary: u32, stride: u32, q_off: u32, k_off: u32, v_off: u32, ring: u32, eps: f32, theta: f32 }; + const VArgs = extern struct { rows: u32, pos0: u32, heads: u32, groups: u32, blocks: u32, first: u32, hi: u32, window: u32, ring: u32, scale: f32 }; + const MArgs = extern struct { rows: u32 = 0, width: u32 = 0, heads: u32 = 0, dim: u32 = 0, pos: u32 = 0, stride: u32 = 0, bits: u32 = 0, group: u32 = 0, eps: f32 = 0, alpha: f32 = 0, limit: f32 = 0, scale: f32 = 0 }; + + /// The block [pending, noise x (block - 1)] 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 = c.heads * 128; + const kvw: usize = c.kv_heads * 128; + const ids = d.buf("ids").slice(u32, max_block); + ids[0] = pending; + @memset(ids[1..n], c.noise); + d.buf("seq").slice(u32, 16)[0] = pending; + const E = m.weights.embed; + glue(e, m.pipe(.embed), MArgs{ .rows = @intCast(n), .width = c.hidden, .bits = E.bits, .group = @intCast(E.group) }, &.{ b(d.buf("ids")), bo(E.w, E.w_off), bo(E.scales, E.s_off), bo(E.biases, E.b_off), A, b(d.buf("resid")) }, .{ (h + 255) / 256, n, 1 }, .{ 256, 1, 1 }); + const nm = MArgs{ .rows = @intCast(n), .width = c.hidden, .eps = c.eps }; + glue(e, m.pipe(.norm), nm, &.{ b(d.buf("resid")), t(d.w.layers[0].in_norm), A, b(d.buf("x")) }, .{ n, 1, 1 }, .{ 256, 1, 1 }); + const lo = @max((anchor + 1) -| c.window, l.from); + const hi = anchor + n; + const first = lo / 128; + const blocks = (hi - 1) / 128 - first + 1; + for (0..c.layers) |i| { + const L = &d.w.layers[i]; + try d.project(e, L.qkv, b(d.buf("x")), b(d.buf("qkv")), n); + const pa = PArgs{ .rows = @intCast(n), .heads = c.heads, .kv_heads = c.kv_heads, .pos0 = @intCast(anchor), .rotary = c.rotary, .stride = @intCast(qw + 2 * kvw), .q_off = 0, .k_off = @intCast(qw), .v_off = @intCast(qw + kvw), .ring = c.ring(), .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 va = VArgs{ .rows = @intCast(n), .pos0 = @intCast(anchor), .heads = c.heads, .groups = c.kv_heads, .blocks = @intCast(blocks), .first = @intCast(first), .hi = @intCast(hi), .window = c.window, .ring = c.ring(), .scale = 1.0 / @sqrt(128.0) }; + 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 }); + const ma = extern struct { rows: u32, pos: u32, heads: u32, groups: u32, topk: u32, scale: f32, sel: u32, all: u32 }{ .rows = @intCast(n), .pos = 0, .heads = c.heads, .groups = c.kv_heads, .topk = @intCast(blocks), .scale = 0, .sel = 0, .all = 0 }; + glue(e, m.pipe(.merge_vec), ma, &.{ b(d.buf("pm")), b(d.buf("pl")), b(d.buf("po")), A, b(d.buf("attn")) }, .{ c.heads, n, 1 }, .{ 32, 1, 1 }); + try d.project(e, L.o, b(d.buf("attn")), b(d.buf("y")), n); + glue(e, m.pipe(.add_norm), nm, &.{ b(d.buf("resid")), b(d.buf("y")), t(L.post_norm), A, b(d.buf("x")) }, .{ n, 1, 1 }, .{ 256, 1, 1 }); + try d.project(e, L.gu, b(d.buf("x")), b(d.buf("gu")), n); + const act = MArgs{ .rows = @intCast(n), .width = c.ffn, .stride = 2 * c.ffn, .alpha = c.alpha, .limit = c.limit }; + e.setPipeline(m.pipe(.swiglu)); + e.setBuffer(d.buf("gu"), 0, 0); + e.setValue(act, 1); + e.setBuffer(d.buf("act"), 0, 2); + e.dispatchThreads(mtl.Size.of(c.ffn, n, 1), mtl.Size.of(256, 1, 1)); + try d.project(e, L.down, b(d.buf("act")), b(d.buf("y")), n); + const next = if (i + 1 < c.layers) d.w.layers[i + 1].in_norm else d.w.norm; + glue(e, m.pipe(.add_norm), nm, &.{ b(d.buf("resid")), b(d.buf("y")), t(next), A, b(d.buf("x")) }, .{ n, 1, 1 }, .{ 256, 1, 1 }); + } + try d.project(e, m.weights.head, b(d.buf("x")), b(d.buf("logits")), n); + const vocab: u32 = m.config.vocab; + const groups: u32 = (vocab + 255) / 256; + const w2 = d.w.w2; + for (0..n) |j| { + const sa = extern struct { vocab: u32, rank: u32, step: u32 }{ .vocab = vocab, .rank = c.rank, .step = @intCast(j) }; + glue(e, d.pipe(.markov_step), sa, &.{ b(d.buf("logits")), t(d.w.w1), bo(w2.w, w2.w_off), bo(w2.scales, w2.s_off), bo(w2.biases, w2.b_off), b(d.buf("seq")), A, b(d.buf("best")), b(d.buf("best_id")) }, .{ groups, 1, 1 }, .{ 256, 1, 1 }); + glue(e, d.pipe(.markov_pick), [2]u32{ groups, @intCast(j) }, &.{ b(d.buf("best")), b(d.buf("best_id")), A, b(d.buf("seq")) }, .{ 1, 1, 1 }, .{ 1024, 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; + if (it.depth == 0 or it.depth > c.block 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); + try 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 >= d.target.config.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| { + var ts0: std.c.timespec = undefined; + _ = std.c.clock_gettime(.MONOTONIC, &ts0); + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const cb = d.target.queue.commandBuffer(); + const e = cb.compute(.serial); + try d.encodeBlock(e, l, 2, 0); + e.end(); + cb.commit(); + cb.wait(); + if (cb.failure()) |msg| return failed(msg); + var ts1: std.c.timespec = undefined; + _ = std.c.clock_gettime(.MONOTONIC, &ts1); + if (run == 2) ms = @as(f64, @floatFromInt(ts1.sec - ts0.sec)) * 1e3 + @as(f64, @floatFromInt(ts1.nsec - ts0.nsec)) / 1e6; + } + d.step_ms = ms / @as(f64, @floatFromInt(d.config.block)); + } + + fn failed(msg: [*:0]const u8) anyerror { + std.log.err("minimax_m3 drafter: command buffer failed: {s}", .{msg}); + return error.GpuFailed; + } +}; + +pub fn now() 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/minimax_m3/forward.zig b/zig/src/families/minimax_m3/forward.zig new file mode 100644 index 00000000000..141a2d9f4fd --- /dev/null +++ b/zig/src/families/minimax_m3/forward.zig @@ -0,0 +1,402 @@ +//! Rows through every layer in one command buffer: row kernels to 32 rows, tensor-unit matmuls for prompt chunks. +const std = @import("std"); +const mtl = @import("metal"); +const lanes = @import("lanes"); +const cfg = @import("config.zig"); +const st = @import("state.zig"); +const vision = @import("vision.zig"); +const wts = @import("weights.zig"); +const rows = @import("../../core/row_projection.zig"); +const affine_mm = @import("../../core/affine_mm.zig"); +const Model = @import("model.zig").Model; +const Glue = @import("model.zig").Glue; + +/// The glue kernels' constants (glue.metal's mm_args). +const Args = extern struct { rows: u32 = 0, width: u32 = 0, heads: u32 = 0, dim: u32 = 0, pos: u32 = 0, stride: u32 = 0, bits: u32 = 0, group: u32 = 0, eps: f32 = 0, alpha: f32 = 0, limit: f32 = 0, scale: f32 = 0 }; +/// The q, k and index preparation's constants (mm_prep_args). +const PArgs = extern struct { rows: u32, heads: u32, kv_heads: u32, index_heads: u32, dim: u32, pos: u32, rotary: u32, stride: u32, eps: f32, theta: f32 }; +/// The indexer's constants (mm_index_args). +const IArgs = extern struct { rows: u32, pos: u32, heads: u32, blocks: u32, first_row: u32 = 0 }; +/// The decode attention's constants (mm_vec_args). +const VArgs = extern struct { rows: u32, pos: u32, heads: u32, groups: u32, topk: u32, scale: f32, sel: u32, all: u32 }; + +const Enc = struct { + e: mtl.ComputeEncoder, + m: *const Model, + s: *st.Scratch, + + fn glue(x: Enc, g: Glue, args: anytype, bufs: []const B, grid: [3]usize, group: [3]usize, groups: bool) void { + x.e.setPipeline(x.m.pipe(g)); + var slot: usize = 0; + for (bufs) |r| { + if (r.args) x.e.setValue(args, slot) else x.e.setBuffer(r.buf, r.off, slot); + slot += 1; + } + const g3 = mtl.Size.of(grid[0], grid[1], grid[2]); + const t3 = mtl.Size.of(group[0], group[1], group[2]); + if (groups) x.e.dispatchGroups(g3, t3) else x.e.dispatchThreads(g3, t3); + } + + fn project(x: Enc, w: wts.Linear, in: mtl.Buffer, in_off: usize, out: mtl.Buffer, out_off: usize, n_rows: usize) !void { + return projectWith(x.e, x.m, x.s.sums, w, bo(in, in_off), bo(out, out_off), n_rows); + } + + fn experts(x: Enc, w: rows.Experts, in: mtl.Buffer, out: mtl.Buffer, ids: mtl.Buffer, slots: usize) !void { + const call = try rows.callIndexed(&x.m.rows, w, slots, false); + if (w.one.bits == 3 or w.one.bits == 4) { // expert by expert: a weight read once for every row that picked it + x.e.setPipeline(x.m.grouped[if (w.one.bits == 3) 0 else 1]); + for ([_]mtl.Buffer{ in, w.one.w, w.one.scales, w.one.biases }, [_]usize{ 0, w.one.w_off, w.one.s_off, w.one.b_off }, 0..) |r, off, slot| x.e.setBuffer(r, off, slot); + x.e.setValue(call.dims, 4); + x.e.setBuffer(out, 0, 5); + x.e.setBuffer(x.s.groups, 0, 6); + x.e.setBuffer(x.s.members, 0, 7); + x.e.dispatchGroups(mtl.Size.of(call.groups, slots, 1), mtl.Size.of(call.threads, 1, 1)); + return; + } + _ = ids; + x.e.setPipeline(call.pipeline); + x.e.setBuffer(in, 0, 0); + x.e.setBuffer(w.one.w, w.one.w_off, 1); + x.e.setBuffer(w.one.scales, w.one.s_off, 2); + x.e.setBuffer(w.one.biases, w.one.b_off, 3); + x.e.setValue(call.dims, 4); + x.e.setBuffer(out, 0, 5); + x.e.setBuffer(x.s.pick, 0, 6); + x.e.dispatchGroups(mtl.Size.of(call.groups, slots, 1), mtl.Size.of(call.threads, 1, 1)); + } +}; + +/// `w` on `n_rows` rows of `in` into `out`: row kernels to batch_rows, else the tensor units (group sums in `sums`). +pub fn projectWith(e: mtl.ComputeEncoder, m: *const Model, sums: mtl.Buffer, w: wts.Linear, in: B, out: B, n_rows: usize) !void { + return projectRows(e, m, sums, w, in, out, n_rows, st.batch_rows + 1); +} + +/// projectWith with the tensor units from `tensor_from` rows (a drafter's proposals need not keep one-row bits). +pub fn projectRows(e: mtl.ComputeEncoder, m: *const Model, sums: mtl.Buffer, w: wts.Linear, in: B, out: B, n_rows: usize, tensor_from: usize) !void { + if (n_rows >= tensor_from) if (m.mmFor(w)) |p| { + // a prompt chunk: each group's row sums, then the tensor-unit product (each weight read once a chunk) + affine_mm.rowSums(e, p, @intCast(w.group), in, b(sums), @intCast(n_rows), @intCast(w.k)); + affine_mm.dense(e, p, in, b(sums), mat(w), out, @intCast(n_rows)); + return; + }; + const call = try rows.call(&m.rows, w, n_rows, false); + e.setPipeline(call.pipeline); + e.setBuffer(in.buf, in.off, 0); + e.setBuffer(w.w, w.w_off, 1); + e.setBuffer(w.scales, w.s_off, 2); + e.setBuffer(w.biases, w.b_off, 3); + e.setValue(call.dims, 4); + e.setBuffer(out.buf, out.off, 5); + e.dispatchGroups(mtl.Size.of(call.groups, 1, 1), mtl.Size.of(call.threads, 1, 1)); +} + +pub const B = struct { buf: mtl.Buffer = undefined, off: usize = 0, args: bool = false }; +pub fn b(buf: mtl.Buffer) B { + return .{ .buf = buf }; +} +pub fn bo(buf: mtl.Buffer, off: usize) B { + return .{ .buf = buf, .off = off }; +} +pub fn t(x: wts.Tensor) B { + return .{ .buf = x.buffer, .off = x.offset }; +} +pub const A = B{ .args = true }; + +/// A matrix as affine_mm takes it. +fn mat(w: wts.Linear) struct { w: B, s: B, b: B, n: u32, k: u32 } { + return .{ .w = bo(w.w, w.w_off), .s = bo(w.scales, w.s_off), .b = bo(w.biases, w.b_off), .n = @intCast(w.n), .k = @intCast(w.k) }; +} + +/// 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, taps: ?B = null, images: []const Span = &.{} }; + +/// An image's rows (bf16) over prompt positions [at, at + n); attention is causal, so a chunk may end inside one. +pub const Span = struct { at: usize, n: u32, rows: vision.Ref }; + +/// 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 { + how: union(enum) { greedy, sampled: struct { sampling: lanes.Sampling, position: u64 } }, + out: B, +}; + +/// A forward's host encoding and GPU seconds (tf-minimax-run's bench). +pub const Timing = struct { encode: f64 = 0, gpu: f64 = 0 }; + +/// A stream's rows in a forward: the next `rows` of ids at positions cache.len.., its keys and values into its cache. +pub const Segment = struct { cache: *st.Cache, rows: usize }; + +/// One stream's `ids` at positions cache.len.. (len unmoved). +pub fn run(m: *const Model, s: *st.Scratch, cache: *st.Cache, ids: []const u32, out: Out) !void { + return runShared(m, s, &.{.{ .cache = cache, .rows = ids.len }}, ids, out); +} + +/// Several streams' rows in one forward, each segment's attention over its own cache: every row keeps its solo bits. +pub fn runShared(m: *const Model, s: *st.Scratch, segments: []const Segment, ids: []const u32, out: Out) !void { + const c = &m.config; + const n = ids.len; + if (n == 0 or n > s.rows or (out.all and n > st.batch_rows) or (!out.all and segments.len != 1)) return error.MiniMaxRowsExceeded; + var total: usize = 0; + for (segments) |seg| { + if (seg.rows == 0 or seg.cache.len + seg.rows > seg.cache.capacity or seg.cache.capacity > s.context) return error.MiniMaxContextFull; + if (segments.len > 1 and seg.rows > st.window_rows) return error.MiniMaxRowsExceeded; + total += seg.rows; + } + if (total != n) return error.InvalidMiniMaxSegments; + if (out.ids == null) { + for (ids) |id| if (id >= c.vocab) return error.InvalidMiniMaxToken; + @memcpy(s.ids.slice(u32, n), ids); + } + if (out.draw != null and (out.all or segments.len != 1)) return error.InvalidMiniMaxSegments; + const h: usize = c.hidden; + const nr: u32 = @intCast(n); + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const t0 = if (out.timing != null) seconds() else 0; + const cb = m.queue.commandBuffer(); + const x = Enc{ .e = cb.compute(.serial), .m = m, .s = s }; + const W = m.weights; + embed(x, out.ids orelse b(s.ids), n); + if (out.images.len > 0) { + if (segments.len != 1) return error.InvalidMiniMaxSegments; + const p0 = segments[0].cache.len; + for (out.images) |span| { + const lo = @max(span.at, p0); + const hi = @min(span.at + span.n, p0 + n); + if (lo >= hi) continue; + const v = m.vision orelse return error.NoMiniMaxVision; + v.inject(x.e, span.rows.at((lo - span.at) * h * 2), .{ .buf = s.resid, .off = (lo - p0) * h * 4 }, @intCast(hi - lo)); + } + } + const normed = Args{ .rows = nr, .width = c.hidden, .eps = c.eps }; + x.glue(.norm, normed, &.{ b(s.resid), t(W.layers[0].input_norm), A, b(s.x) }, .{ n, 1, 1 }, .{ 1024, 1, 1 }, true); + for (W.layers[0..c.layers], 0..) |l, i| { + try layer(x, segments, l, i, n, if (i + 1 < c.layers) W.layers[i + 1].input_norm else null); + // the residual after a tapped layer, every row, into the drafter's features + if (out.taps) |tb| if (m.tap_at[i] >= 0) { + x.e.setPipeline(m.tap); + x.e.setBuffer(s.resid, 0, 0); + x.e.setValue([4]u32{ nr, c.hidden, m.taps, @intCast(m.tap_at[i]) }, 1); + x.e.setBuffer(tb.buf, tb.off, 2); + x.e.dispatchThreads(mtl.Size.of(c.hidden, n, 1), mtl.Size.of(256, 1, 1)); + }; + } + if (out.all) { + x.glue(.norm, normed, &.{ b(s.resid), t(W.norm), A, b(s.x) }, .{ n, 1, 1 }, .{ 1024, 1, 1 }, true); + try x.project(W.head, s.x, 0, s.logits_all, 0, n); + } else { + x.glue(.norm, normed, &.{ bo(s.resid, (n - 1) * h * 4), t(W.norm), A, b(s.x) }, .{ 1, 1, 1 }, .{ 256, 1, 1 }, true); + try x.project(W.head, s.x, 0, segments[0].cache.logits, 0, 1); + if (out.draw) |d| pick(x, segments[0].cache.logits, d); + } + x.e.end(); + if (out.timing) |tm| tm.encode += seconds() - t0; + cb.commit(); + if (out.flight) |f| { + f.* = cb.retain(); + return; + } + cb.wait(); + if (cb.failure()) |msg| { + std.log.err("minimax_m3 forward: {s}", .{msg}); + return error.GpuFailed; + } + if (out.timing) |tm| tm.gpu += cb.gpuSeconds(); +} + +fn seconds() f64 { + var ts: std.c.timespec = undefined; + _ = std.c.clock_gettime(.MONOTONIC, &ts); + return @as(f64, @floatFromInt(ts.sec)) + @as(f64, @floatFromInt(ts.nsec)) * 1e-9; +} + +/// The draw of one logits row on the GPU into `d.out`: mm_argmax, or the keyed sampler one 1024-thread threadgroup. +fn pick(x: Enc, logits: mtl.Buffer, d: Draw) void { + const e = x.e; + const vocab: u32 = x.m.config.vocab; + switch (d.how) { + .greedy => { + e.setPipeline(x.m.pipe(.argmax)); + e.setBuffer(logits, 0, 0); + e.setBuffer(d.out.buf, d.out.off, 1); + e.setValue(vocab, 2); + }, + .sampled => |sd| { + // the kernels index these by row: one row, padded as Nemotron's launches pad them + const r = lanes.gpu_rule.rule(sd.sampling); + var seeds: [16]u32 = @splat(0); + var positions: [8]u32 = @splat(0); + var cfgs: [32]f32 = @splat(0); + var caps: [8]u32 = @splat(0); + seeds[0..2].* = r.seedHalves(); + positions[0] = @intCast(sd.position); + cfgs[0..4].* = r.cfg(); + caps[0] = r.top_k; + const whole = lanes.gpu_full.fullVocabulary(sd.sampling); + e.setPipeline(if (whole) x.m.sample_full else x.m.sample); + e.setBuffer(logits, 0, 0); + e.setBytes(std.mem.sliceAsBytes(&seeds), 1); + e.setBytes(std.mem.sliceAsBytes(&positions), 2); + e.setBytes(std.mem.sliceAsBytes(&cfgs), 3); + e.setBytes(std.mem.sliceAsBytes(&caps), 4); + e.setBuffer(d.out.buf, d.out.off, 5); + if (whole) { + e.setBuffer(d.out.buf, d.out.off, 6); + e.setValue(vocab, 7); + } + }, + } + e.dispatchGroups(mtl.Size.of(1, 1, 1), mtl.Size.of(1024, 1, 1)); +} + +/// Embeddings of the token ids at `ids` (n of them) into the residual. +fn embed(x: Enc, ids: B, n: usize) void { + const c = &x.m.config; + const E = x.m.weights.embed; + const args = Args{ .rows = @intCast(n), .width = c.hidden, .bits = E.bits, .group = @intCast(E.group) }; + x.glue(.embed, args, &.{ ids, bo(E.w, E.w_off), bo(E.scales, E.s_off), bo(E.biases, E.b_off), A, b(x.s.resid) }, .{ c.hidden, n, 1 }, .{ 256, 1, 1 }, false); +} + +/// Layer `i` on every segment's rows (s.x their input norm); its last add norms the residual by `next`. +fn layer(x: Enc, segments: []const Segment, l: wts.Layer, i: usize, n: usize, next: ?wts.Tensor) !void { + const m = x.m; + const s = x.s; + const c = &m.config; + const h: usize = c.hidden; + const nr: u32 = @intCast(n); + const normed = Args{ .rows = nr, .width = c.hidden, .eps = c.eps }; + try x.project(l.attn.qkv, s.x, 0, s.q, 0, n); + var base: usize = 0; + for (segments) |seg| { + try attention(x, seg.cache, l.attn, i, base, seg.rows); + base += seg.rows; + } + try x.project(l.attn.o, s.o, 0, s.y, 0, n); + x.glue(.add_norm, normed, &.{ b(s.resid), b(s.y), t(l.post_norm), A, b(s.x) }, .{ n, 1, 1 }, .{ 1024, 1, 1 }, true); + switch (l.ffn) { + .dense => |d| { + try mlp(x, d, s.y, n, c.dense_intermediate); + if (next) |w| { + x.glue(.add_norm, normed, &.{ b(s.resid), b(s.y), t(w), A, b(s.x) }, .{ n, 1, 1 }, .{ 1024, 1, 1 }, true); + } else x.glue(.add, Args{ .rows = nr, .width = c.hidden }, &.{ b(s.resid), b(s.y), A }, .{ h, n, 1 }, .{ 256, 1, 1 }, false); + }, + .moe => |e| { + x.glue(.router, Args{ .rows = nr, .width = c.hidden, .heads = c.experts }, &.{ b(s.x), t(e.router), A, b(s.logits32) }, .{ c.experts / 8, (n + 7) / 8, 1 }, .{ 256, 1, 1 }, true); + // a decode window's picks and its slots by expert in one threadgroup; a prompt chunk's picks a row each + if (n > st.batch_rows) { + x.glue(.route_pick, Args{ .rows = nr, .width = c.experts, .heads = c.topk }, &.{ b(s.logits32), t(e.bias), A, b(s.pick), b(s.wts) }, .{ n, 1, 1 }, .{ 32, 1, 1 }, true); + } else x.glue(.route_groups, Args{ .rows = nr, .width = c.experts, .heads = c.topk }, &.{ b(s.logits32), t(e.bias), A, b(s.pick), b(s.wts), b(s.groups), b(s.members) }, .{ 1, 1, 1 }, .{ 32 * n, 1, 1 }, true); + const slots = n * c.topk; + const inter: u32 = c.moe_intermediate; + const act = Args{ .rows = @intCast(slots), .width = inter, .stride = 2 * inter, .alpha = c.swiglu_alpha, .limit = c.swiglu_limit }; + if (n > st.batch_rows) { + try expertsByExpert(x, e, n, act); + } else { + var gu = e.gu; + gu.repeat = c.topk; + try x.experts(gu, s.x, s.egu, s.pick, slots); + x.glue(.swiglu, act, &.{ b(s.egu), A, b(s.ea) }, .{ inter, slots, 1 }, .{ 256, 1, 1 }, false); + try x.experts(e.down, s.ea, s.ey, s.pick, slots); + } + try mlp(x, e.shared, s.shared, n, c.shared_intermediate); + const madd = Args{ .rows = nr, .width = c.hidden, .heads = c.topk, .eps = c.eps, .scale = c.routed_scale }; + if (next) |w| { + x.glue(.moe_add_norm, madd, &.{ b(s.resid), b(s.ey), b(s.pick), b(s.wts), b(s.shared), t(w), A, b(s.x) }, .{ n, 1, 1 }, .{ 1024, 1, 1 }, true); + } else x.glue(.moe_add, madd, &.{ b(s.resid), b(s.ey), b(s.pick), b(s.wts), b(s.shared), A }, .{ h, n, 1 }, .{ 256, 1, 1 }, false); + }, + } +} + +/// A chunk's routed experts by expert (each expert's weights read once): sorted, gate|up, SwiGLU, down back to s.ey. +fn expertsByExpert(x: Enc, e: wts.Moe, n: usize, act: Args) !void { + const c = &x.m.config; + const s = x.s; + const slots: u32 = @intCast(n * c.topk); + const p = x.m.mmFor(e.gu.one) orelse return error.UnsupportedMiniMaxExperts; + const pd = x.m.mmFor(e.down.one) orelse return error.UnsupportedMiniMaxExperts; + const ex: u32 = c.experts; + x.glue(.sort, Args{ .rows = slots, .width = ex }, &.{ b(s.pick), A, b(s.offsets), b(s.order) }, .{ 1, 1, 1 }, .{ 1024, 1, 1 }, true); + x.glue(.rows_by_order, Args{ .rows = slots, .width = c.hidden, .heads = c.topk }, &.{ b(s.x), b(s.order), A, b(s.xs) }, .{ c.hidden, slots, 1 }, .{ 256, 1, 1 }, false); + affine_mm.rowSums(x.e, p, @intCast(e.gu.one.group), b(s.xs), b(s.sums), slots, c.hidden); + affine_mm.gather(x.e, p, b(s.xs), b(s.sums), mat(e.gu.one), b(s.offsets), b(s.egu), slots, ex); + x.glue(.swiglu, act, &.{ b(s.egu), A, b(s.ea) }, .{ c.moe_intermediate, slots, 1 }, .{ 256, 1, 1 }, false); + affine_mm.rowSums(x.e, pd, @intCast(e.down.one.group), b(s.ea), b(s.sums), slots, c.moe_intermediate); + affine_mm.gatherTo(x.e, pd, b(s.ea), b(s.sums), mat(e.down.one), b(s.offsets), b(s.ey), b(s.order), slots, ex); +} + +/// gate|up from s.x, SwiGLU, down into `out`. +fn mlp(x: Enc, w: wts.Mlp, out: mtl.Buffer, n: usize, inter: u32) !void { + const c = &x.m.config; + const s = x.s; + try x.project(w.gu, s.x, 0, s.gate, 0, n); + const act = Args{ .rows = @intCast(n), .width = inter, .stride = 2 * inter, .alpha = c.swiglu_alpha, .limit = c.swiglu_limit }; + x.glue(.swiglu, act, &.{ b(s.gate), A, b(s.act) }, .{ inter, n, 1 }, .{ 256, 1, 1 }, false); + try x.project(w.down, s.act, 0, out, 0, n); +} + +/// One stream's rows base..: q, k, the index pair normed and rotated, the block selection, attention to s.o. +fn attention(x: Enc, cache: *st.Cache, w: wts.Attention, i: usize, base: usize, n: usize) !void { + const c = &x.m.config; + const s = x.s; + const start = cache.len; + const qrow: usize = @as(usize, c.heads) * c.head_dim * 2; // a row's qn and o bytes + const irow: usize = @as(usize, c.index_heads) * c.index_dim * 2; + const qn = bo(s.qn, base * qrow); + const iq = bo(s.iq, base * irow); + const o = bo(s.o, base * qrow); + const nr: u32 = @intCast(n); + const keys = bo(cache.kv, cache.keys(i)); + const values = bo(cache.kv, cache.values(c, i)); + const ikeys = bo(cache.kv, cache.indexKeys(c, i)); + const pa = PArgs{ .rows = nr, .heads = c.heads, .kv_heads = c.kv_heads, .index_heads = c.index_heads, .dim = c.head_dim, .pos = @intCast(start), .rotary = c.rotary, .stride = c.qkvRows(), .eps = c.eps, .theta = c.theta }; + x.glue(.prep, pa, &.{ bo(s.q, base * c.qkvRows() * 2), t(w.q_norm), t(w.k_norm), t(w.iq_norm), t(w.ik_norm), A, qn, iq, keys, values, ikeys }, .{ c.heads + c.kv_heads + c.index_heads + 1, n, 1 }, .{ 32, 1, 1 }, true); + // the selection: every block while a row sees at most topk_blocks of them, else the indexer's best and its own + const nb = c.blocks(start + n); + const prompt = n > st.window_rows; + const sel_at = base * c.kv_heads; + const scores = bo(s.scores, sel_at * c.blocks(s.context) * 4); + const sel = bo(s.sel, sel_at * c.topk_blocks * 4); + const ia = IArgs{ .rows = nr, .pos = @intCast(start), .heads = c.kv_heads, .blocks = @intCast(nb) }; + if (nb <= c.topk_blocks) {} else if (n > st.batch_rows) { // a prompt chunk: the tensor units + x.e.setPipeline(x.m.index_nax); + for ([_]B{ iq, ikeys, scores }, 0..) |r, slot| x.e.setBuffer(r.buf, r.off, slot); + x.e.setValue([3]i32{ @intCast(n), @intCast(start), @intCast(nb) }, 3); + x.e.dispatchGroups(mtl.Size.of((n + 31) / 32, c.index_heads, 1), mtl.Size.of(@as(usize, c.index_dim) / 64 * 32, 1, 1)); + } else x.glue(.index_scores, ia, &.{ iq, ikeys, A, scores }, .{ nb, (n + 15) / 16, 1 }, .{ 128, 1, 1 }, true); + const words: u32 = if (prompt) @intCast(st.selWords(c)) else 0; + const bits = bo(s.bits, if (prompt) sel_at * words * 4 else 0); + const e = x.e; + // rows that see no more than topk_blocks blocks keep them all: decode needs no selection then + const all = !prompt and nb <= c.topk_blocks; + if (!all) { + e.setPipeline(x.m.pipe(.index_select)); + e.setBuffer(scores.buf, scores.off, 0); + e.setValue(ia, 1); + e.setValue(c.topk_blocks, 2); + e.setBuffer(sel.buf, sel.off, 3); + e.setBuffer(bits.buf, bits.off, 4); + e.setValue(words, 5); + e.dispatchGroups(mtl.Size.of(c.kv_heads, n, 1), mtl.Size.of(32, 1, 1)); + } + if (prompt) { // a prompt chunk: a key head's query heads on two rows a tile, over the blocks either row keeps + e.setPipeline(x.m.prompt_attn); + for ([_]B{ qn, keys, values, o, A, bits }, 0..) |r, slot| { + if (r.args) e.setValue([2]i32{ @intCast(n), @intCast(start) }, slot) else e.setBuffer(r.buf, r.off, slot); + } + const per: usize = 32 / (c.heads / c.kv_heads); // rows a tile + e.dispatchGroups(mtl.Size.of((n + per - 1) / per, c.kv_heads, 1), mtl.Size.of(@as(usize, c.head_dim) / 64 * 32, 1, 1)); + return; + } + // decode rows: a key head's query heads a threadgroup over each kept block, then the merge in block order + const va = VArgs{ .rows = nr, .pos = @intCast(start), .heads = c.heads, .groups = c.kv_heads, .topk = c.topk_blocks * 4, .scale = 1.0 / @sqrt(@as(f32, @floatFromInt(c.head_dim))), .sel = c.topk_blocks, .all = @intFromBool(all) }; + e.setPipeline(x.m.pipe(.decode_vec)); + for ([_]B{ qn, keys, values }, 0..) |r, slot| e.setBuffer(r.buf, r.off, slot); + e.setValue(va, 3); + e.setBuffer(sel.buf, sel.off, 4); + for ([_]mtl.Buffer{ s.pm, s.pl, s.po }, 5..) |r, slot| e.setBuffer(r, 0, slot); + e.dispatchGroups(mtl.Size.of(c.kv_heads, n, c.topk_blocks * 4), mtl.Size.of(32, c.heads / c.kv_heads, 1)); + e.setPipeline(x.m.pipe(.merge_vec)); + for ([_]mtl.Buffer{ s.pm, s.pl, s.po }, 0..) |r, slot| e.setBuffer(r, 0, slot); + e.setValue(va, 3); + e.setBuffer(o.buf, o.off, 4); + e.dispatchGroups(mtl.Size.of(c.heads, n, 1), mtl.Size.of(32, 1, 1)); +} diff --git a/zig/src/families/minimax_m3/minimax_m3.zig b/zig/src/families/minimax_m3/minimax_m3.zig new file mode 100644 index 00000000000..fc44aac7906 --- /dev/null +++ b/zig/src/families/minimax_m3/minimax_m3.zig @@ -0,0 +1,22 @@ +//! Native Metal MiniMax-M3.1-Flash (MiniMaxAI): block-sparse GQA with the lightning indexer, 128 routed experts. +pub const config = @import("config.zig"); +pub const weights = @import("weights.zig"); +pub const Model = @import("model.zig").Model; +pub const drafterKind = @import("model.zig").drafterKind; +pub const state = @import("state.zig"); +pub const forward = @import("forward.zig"); +pub const backend = @import("backend.zig"); +pub const budget = @import("budget.zig"); +pub const residency = @import("residency.zig"); +pub const snapshot = @import("snapshot.zig"); +pub const dspark = @import("dspark.zig"); +pub const dflash2 = @import("dflash2.zig"); +pub const vision = @import("vision.zig"); + +test { + _ = config; + _ = state; + _ = budget; + _ = snapshot; + _ = vision; +} diff --git a/zig/src/families/minimax_m3/model.zig b/zig/src/families/minimax_m3/model.zig new file mode 100644 index 00000000000..4ef6245be08 --- /dev/null +++ b/zig/src/families/minimax_m3/model.zig @@ -0,0 +1,241 @@ +//! A native MiniMax-M3.1-Flash model: config, the checkpoint in Metal buffers, its matrices and every pipeline. +const std = @import("std"); +const mtl = @import("metal"); +const ks = @import("kernel_sources"); +const cfg = @import("config.zig"); +const ck = @import("../../core/checkpoint_metal.zig"); +const shards = @import("../../core/checkpoint.zig"); +const rows = @import("../../core/row_projection.zig"); +const affine_mm = @import("../../core/affine_mm.zig"); +const frags = @import("../../core/frags.zig"); +const st = @import("state.zig"); +const weights = @import("weights.zig"); +const vision = @import("vision.zig"); + +/// Nemotron's generated keyed sampler (its vocabulary compiled in; this model's replaces it). +fn sampler() ?ks.nemotron.Kernel { + for (ks.nemotron.all) |k| if (std.mem.eql(u8, k.key, "sample")) return k; + return null; +} + +pub const DrafterKind = enum { dflash2, dspark }; + +/// MINIMAX_DRAFTER: dspark (the release's head) or dflash2 (incoai's, the default); null otherwise, refused at load. +pub fn drafterKind() ?DrafterKind { + const v = std.c.getenv("MINIMAX_DRAFTER") orelse return .dflash2; + return std.meta.stringToEnum(DrafterKind, std.mem.span(v)); +} + +/// A prompt chunk's tensor-unit matmul for one (bits, group) the checkpoint uses. +pub const Mm = struct { bits: u8, group: usize, pipes: affine_mm.Pipes }; + +pub const glue_names = [_][:0]const u8{ "mm_embed", "mm_norm", "mm_add_norm", "mm_add", "mm_swiglu", "mm_router", "mm_route_pick", "mm_moe_add_norm", "mm_moe_add", "mm_sort", "mm_rows_by_order", "mm_prep", "mm_index_scores", "mm_index_select", "mm_decode_vec", "mm_merge_vec", "mm_argmax", "mm_route_groups", "mm_widen", "mm_narrow" }; +pub const Glue = enum { embed, norm, add_norm, add, swiglu, router, route_pick, moe_add_norm, moe_add, sort, rows_by_order, prep, index_scores, index_select, decode_vec, merge_vec, argmax, route_groups, widen, narrow }; + +pub const Model = struct { + gpa: std.mem.Allocator, + device: mtl.Device, + queue: mtl.Queue, + config: cfg.Config, + checkpoint: ck.Checkpoint, + weights: weights.Weights, + glue: [glue_names.len]mtl.Pipeline, + rows: rows.Pipelines, + /// Prompt attention on the tensor units over each row's kept blocks; decode attention is glue's mm_decode_vec. + prompt_attn: mtl.Pipeline, + /// A prompt chunk's indexer block scores on the tensor units (index_nax.metal). + index_nax: mtl.Pipeline, + /// A pipelined step's keyed draws (host twins: lanes' gpu_rule, gpu_full): top-k candidates, whole vocabulary. + sample: mtl.Pipeline, + sample_full: mtl.Pipeline, + mm: [4]Mm = undefined, + mms: usize = 0, + /// The residual's copy into a drafter's taps after a tapped layer (dspark.metal's mm_tap). + tap: mtl.Pipeline, + /// A drafter block's attention over its context ring and itself (dspark.metal's mm_draft_vec, either drafter's). + draft_vec: mtl.Pipeline, + /// A decode window's rows of each expert at 3 and 4 bits (experts.metal), grouped by mm_route_groups. + grouped: [2]mtl.Pipeline, + /// Each layer's place in the drafter's taps, -1 when untapped (no drafter: all -1). + tap_at: [cfg.max_layers]i8 = @splat(-1), + taps: u32 = 0, + /// The image tower (--vision), its shard added to the checkpoint by loadVision. + vision: ?*vision.Vision = null, + + pub fn load(gpa: std.mem.Allocator, io: std.Io, dir: []const u8) !*Model { + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const m = try gpa.create(Model); + errdefer gpa.destroy(m); + m.gpa = gpa; + m.mms = 0; + m.vision = null; + m.config = try cfg.Config.read(gpa, io, dir); + const c = &m.config; + m.device = try mtl.Device.init(); + errdefer m.device.deinit(); + m.queue = try m.device.queue(); + errdefer m.queue.deinit(); + m.checkpoint = ck.Checkpoint.init(gpa); + errdefer m.checkpoint.deinit(); + const files = try shards.shardFiles(gpa, io, dir); + defer shards.freeShardFiles(gpa, files); + // the vision tower's shard stays on disk until loadVision, and the drafter not in use + const skip = if (drafterKind() == DrafterKind.dspark) "model-dflash2.safetensors" else "model-dspark.safetensors"; + for (files) |path| if (!std.mem.endsWith(u8, path, "model-vision.safetensors") and !std.mem.endsWith(u8, path, skip)) try m.checkpoint.addFile(m.device, path, ""); + m.weights = try weights.load(gpa, &m.checkpoint, c); + errdefer m.weights.deinit(gpa); + { + const lib = try mtl.Library.fromSource(m.device, ks.minimax_m3_glue, .{ .language = mtl.CompileOptions.mlx().language, .math_functions = .precise }); + defer lib.deinit(); + var made: usize = 0; + errdefer for (m.glue[0..made]) |p| p.deinit(); + for (glue_names, 0..) |n, i| { + m.glue[i] = try mtl.Pipeline.init(m.device, lib, n, false); + made += 1; + } + } + errdefer for (m.glue) |p| p.deinit(); + m.rows = try rows.Pipelines.load(m.device); + errdefer m.rows.deinit(); + { + const body = try frags.source(m.device, gpa, ks.minimax_m3_attention_nax); + defer gpa.free(body); + const src = try std.fmt.allocPrint(gpa, "#define DH {d}\n#define NQ {d}\n#define G {d}\n#define KVH {d}\n#define WORDS {d}\n#define SCALE {e}f\n{s}", .{ c.head_dim, c.heads, c.heads / c.kv_heads, c.kv_heads, st.selWords(c), 1.0 / @sqrt(@as(f64, @floatFromInt(c.head_dim))), body }); + defer gpa.free(src); + const lib = try mtl.Library.fromSource(m.device, src, mtl.CompileOptions.mlx()); + defer lib.deinit(); + m.prompt_attn = try mtl.Pipeline.init(m.device, lib, "mm_prompt_attention", false); + } + errdefer m.prompt_attn.deinit(); + { + const body = try frags.source(m.device, gpa, ks.minimax_m3_index_nax); + defer gpa.free(body); + const src = try std.fmt.allocPrint(gpa, "#define DH {d}\n#define IH {d}\n{s}", .{ c.index_dim, c.index_heads, body }); + defer gpa.free(src); + const lib = try mtl.Library.fromSource(m.device, src, mtl.CompileOptions.mlx()); + defer lib.deinit(); + m.index_nax = try mtl.Pipeline.init(m.device, lib, "mm_index_scores_nax", false); + } + errdefer m.index_nax.deinit(); + { + const generated = sampler() orelse return error.MiniMaxSamplerMissing; + const v = try std.fmt.allocPrint(gpa, "constexpr int V = {d};", .{c.vocab}); + defer gpa.free(v); + const text = try std.mem.replaceOwned(u8, gpa, generated.source, "constexpr int V = 131072;", v); + defer gpa.free(text); + if (std.mem.indexOf(u8, text, v) == null) return error.MiniMaxSamplerMissing; + const lib = try mtl.Library.fromSource(m.device, text, mtl.CompileOptions.mlx()); + defer lib.deinit(); + m.sample = try mtl.Pipeline.init(m.device, lib, generated.function, false); + } + errdefer m.sample.deinit(); + { + const lib = try mtl.Library.fromSource(m.device, ks.nemotron_sample, mtl.CompileOptions.mlx()); + defer lib.deinit(); + m.sample_full = try mtl.Pipeline.init(m.device, lib, "tf_sample_full", false); + } + errdefer m.sample_full.deinit(); + { + const lib = try mtl.Library.fromSource(m.device, ks.minimax_m3_dspark, mtl.CompileOptions.mlx()); + defer lib.deinit(); + m.tap = try mtl.Pipeline.init(m.device, lib, "mm_tap", false); + errdefer m.tap.deinit(); + m.draft_vec = try mtl.Pipeline.init(m.device, lib, "mm_draft_vec", false); + } + errdefer m.tap.deinit(); + errdefer m.draft_vec.deinit(); + { + const text = try std.mem.concat(gpa, u8, &.{ ks.core_row_projection, "\n", ks.minimax_m3_experts }); + defer gpa.free(text); + const lib = try mtl.Library.fromSource(m.device, text, mtl.CompileOptions.mlx()); + defer lib.deinit(); + m.grouped[0] = try mtl.Pipeline.init(m.device, lib, "mm_experts_grouped_q3", false); + errdefer m.grouped[0].deinit(); + m.grouped[1] = try mtl.Pipeline.init(m.device, lib, "mm_experts_grouped_q4", false); + } + errdefer for (m.grouped) |p| p.deinit(); + errdefer for (m.mm[0..m.mms]) |f| for (f.pipes) |p| p.deinit(); + try m.addMm(m.weights.head); + for (m.weights.layers) |l| { + try m.addMm(l.attn.qkv); + switch (l.ffn) { + .dense => |d| try m.addMm(d.gu), + .moe => |e| { + try m.addMm(e.gu.one); + try m.addMm(e.down.one); + try m.addMm(e.shared.gu); + }, + } + } + return m; + } + + /// Pipelines for `w`'s format, compiled once per format (at most 4). + fn addMm(m: *Model, w: rows.Weights) !void { + if (m.mmFor(w) != null) return; + if (m.mms == m.mm.len) return error.TooManyMiniMaxFormats; + const text = try affine_mm.source(m.device, m.gpa, .{ .bits = w.bits, .group = @intCast(w.group) }); + defer m.gpa.free(text); + const lib = try mtl.Library.fromSource(m.device, text, mtl.CompileOptions.mlx()); + defer lib.deinit(); + var f = Mm{ .bits = w.bits, .group = w.group, .pipes = undefined }; + var made: usize = 0; + errdefer for (f.pipes[0..made]) |p| p.deinit(); + for (affine_mm.names, 0..) |n, i| { + f.pipes[i] = try mtl.Pipeline.init(m.device, lib, n, false); + made += 1; + } + m.mm[m.mms] = f; + m.mms += 1; + } + + /// The tensor-unit pipelines for `w`'s format, if loaded. + pub fn mmFor(m: *const Model, w: rows.Weights) ?affine_mm.Pipes { + for (m.mm[0..m.mms]) |f| if (f.bits == w.bits and f.group == w.group) return f.pipes; + return null; + } + + /// The drafter's layers, in the order its features concatenate them. + pub fn setTaps(m: *Model, layers: []const u32) !void { + m.tap_at = @splat(-1); + for (layers, 0..) |l, i| { + if (l >= m.config.layers or i > 127) return error.BadMiniMaxTaps; + m.tap_at[l] = @intCast(i); + } + m.taps = @intCast(layers.len); + } + + /// The checkpoint's image tower (--vision): its shard into the checkpoint, then the tower over it. + pub fn loadVision(m: *Model, io: std.Io, dir: []const u8) !void { + if (m.vision != null) return; + const path = try std.fs.path.joinZ(m.gpa, &.{ dir, vision.shard }); + defer m.gpa.free(path); + std.Io.Dir.cwd().access(io, path, .{}) catch return error.NoMiniMaxVisionShard; + try m.checkpoint.addFile(m.device, path, ""); + m.vision = try vision.Vision.load(m.gpa, m.device, &m.checkpoint, m.pipe(.widen), m.pipe(.narrow)); + } + + pub fn pipe(m: *const Model, g: Glue) mtl.Pipeline { + return m.glue[@backingInt(g)]; + } + + pub fn deinit(m: *Model) void { + for (m.mm[0..m.mms]) |f| for (f.pipes) |p| p.deinit(); + m.prompt_attn.deinit(); + m.index_nax.deinit(); + m.tap.deinit(); + m.draft_vec.deinit(); + for (m.grouped) |p| p.deinit(); + m.sample.deinit(); + m.sample_full.deinit(); + m.rows.deinit(); + for (m.glue) |p| p.deinit(); + if (m.vision) |v| v.deinit(); + m.weights.deinit(m.gpa); + m.checkpoint.deinit(); + m.queue.deinit(); + m.device.deinit(); + m.gpa.destroy(m); + } +}; diff --git a/zig/src/families/minimax_m3/residency.zig b/zig/src/families/minimax_m3/residency.zig new file mode 100644 index 00000000000..7b61a25187b --- /dev/null +++ b/zig/src/families/minimax_m3/residency.zig @@ -0,0 +1,25 @@ +//! One initial inventory and a stable follow hook for every served MiniMax-M3 cache and saved state. +const std = @import("std"); +const mtl = @import("metal"); +const Resident = mtl.resident.Resident; + +/// Weights and scratches in one residency set for the keepalive, if the 70% limit holds them. +pub fn hold(h: anytype) !void { + var list: std.ArrayList(mtl.Buffer) = .empty; + defer list.deinit(h.gpa); + const m = h.model; + for (m.checkpoint.shards.items) |sh| try list.append(h.gpa, sh.buffer); + if (m.vision) |v| try list.appendSlice(h.gpa, &v.buffers()); + try mtl.resident.fields.append(h.gpa, &list, &h.metal.scratch); + try mtl.resident.fields.append(h.gpa, &list, &h.metal.prompt); + h.resident = try Resident.hold(h.gpa, h.io, m.device, m.queue, list.items, "minimax_m3"); + if (h.resident) |*r| h.metal.setResident(r.follow()); + h.warm = if (h.resident) |*r| r.target() else .{ .queue = m.queue }; +} + +pub fn drop(h: anytype) void { + h.metal.setResident(null); + if (h.resident) |*r| r.deinit(); + h.resident = null; + h.warm = .{ .queue = h.model.queue }; +} diff --git a/zig/src/families/minimax_m3/snapshot.zig b/zig/src/families/minimax_m3/snapshot.zig new file mode 100644 index 00000000000..f7977931efe --- /dev/null +++ b/zig/src/families/minimax_m3/snapshot.zig @@ -0,0 +1,98 @@ +//! A stream's prompt state kept for reuse: every layer's first `at` keys, values and index keys. +const std = @import("std"); +const mtl = @import("metal"); +const cfg = @import("config.zig"); +const st = @import("state.zig"); + +/// One kept state: its bytes on the GPU (private) and the prompt tokens it holds. +pub const Snap = struct { + buf: mtl.Buffer, + at: u32, + bytes: u64, + freed: bool = false, // its storage given back early (a stream needed the room); its entry goes at the pass's report + follow: ?mtl.ResidencySet.Follow = null, + + pub fn free(self: *Snap) void { + if (!self.freed) { + if (self.follow) |f| f.leave(f.ctx, self.buf); + self.buf.deinit(); + } + self.freed = true; + } +}; + +/// One contiguous piece of a cache's kv buffer (offset) and its length. +const Piece = struct { off: usize, len: usize }; + +/// Most pieces a state holds: a layer's keys, values and index keys. +const max_pieces = 3 * cfg.max_layers; + +/// A state's pieces at `at`, in order: every layer's first `at` keys, values and index keys. +fn pieces(c: *const cfg.Config, cache: *const st.Cache, at: usize, out: *std.ArrayList(Piece)) void { + const row: usize = @as(usize, c.kvWidth()) * 2; + for (0..c.layers) |i| { + out.appendAssumeCapacity(.{ .off = cache.keys(i), .len = at * row }); + out.appendAssumeCapacity(.{ .off = cache.values(c, i), .len = at * row }); + out.appendAssumeCapacity(.{ .off = cache.indexKeys(c, i), .len = at * @as(usize, c.index_dim) * 2 }); + } +} + +/// Bytes a state after `at` prompt tokens takes. +pub fn bytes(c: *const cfg.Config, at: usize) u64 { + return @as(u64, c.layers) * at * st.rowBytes(c); +} + +/// Copy `cache`'s state at its length into a new snapshot. +pub fn save(device: mtl.Device, queue: mtl.Queue, c: *const cfg.Config, cache: *const st.Cache) !Snap { + const n = bytes(c, cache.len); + const buf = try device.buffer(@intCast(@max(n, 16)), mtl.ResourceOptions.private); + errdefer buf.deinit(); + try copy(queue, c, cache, buf, true); + if (cache.follow) |f| f.join(f.ctx, buf); + return .{ .buf = buf, .at = @intCast(cache.len), .bytes = n, .follow = cache.follow }; +} + +/// Make `cache` (empty, any capacity past the state) hold `snap`'s state. +pub fn restore(queue: mtl.Queue, c: *const cfg.Config, snap: *const Snap, cache: *st.Cache) !void { + if (snap.freed or snap.at >= cache.capacity) return error.MiniMaxSnapshotGone; + cache.len = snap.at; + errdefer cache.len = 0; + try copy(queue, c, cache, snap.buf, false); +} + +/// The pieces between the cache and a snapshot buffer, one blit pass, waited on. +fn copy(queue: mtl.Queue, c: *const cfg.Config, cache: *const st.Cache, buf: mtl.Buffer, out: bool) !void { + var store: [max_pieces]Piece = undefined; + var list: std.ArrayList(Piece) = .initBuffer(&store); + pieces(c, cache, cache.len, &list); + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const cb = queue.commandBuffer(); + const e = cb.blit(); + var at: usize = 0; + for (list.items) |p| { + if (p.len == 0) continue; + if (out) e.copy(cache.kv, p.off, buf, at, p.len) else e.copy(buf, at, cache.kv, p.off, p.len); + at += p.len; + } + e.end(); + cb.commit(); + cb.wait(); + if (cb.failure()) |msg| { + std.log.err("minimax_m3 prompt state copy: {s}", .{msg}); + return error.GpuFailed; + } +} + +test "minimax_m3 snapshot: a state's bytes match its pieces" { + const c = try cfg.parse(std.testing.allocator, @embedFile("config_fixture.json")); + const cache = st.Cache{ .kv = undefined, .logits = undefined, .capacity = 1 << 20 }; + for ([_]usize{ 5, 128, 2049, 100_003 }) |at| { + var store: [max_pieces]Piece = undefined; + var list: std.ArrayList(Piece) = .initBuffer(&store); + pieces(&c, &cache, at, &list); + var sum: u64 = 0; + for (list.items) |p| sum += p.len; + try std.testing.expectEqual(bytes(&c, at), sum); + } +} diff --git a/zig/src/families/minimax_m3/state.zig b/zig/src/families/minimax_m3/state.zig new file mode 100644 index 00000000000..a6ee87a5296 --- /dev/null +++ b/zig/src/families/minimax_m3/state.zig @@ -0,0 +1,207 @@ +//! A stream's caches (every layer's keys, values and index keys by position), and a window's scratch. +const std = @import("std"); +const mtl = @import("metal"); +const cfg = @import("config.zig"); + +/// Rows one stream's decode window takes at most (a verify window: the pending token and its drafts). +pub const window_rows = 16; +/// Rows a shared decode forward takes at most (several streams' windows, row kernels); more take the prompt path. +pub const batch_rows = 32; +/// Rows a prompt chunk takes at most: each expert's weights are read once a chunk. +pub const prompt_rows = 4096; + +/// Slots of a layer for `capacity` positions: whole index blocks, so a block's reads stay in the layer. +pub fn slots(c: *const cfg.Config, capacity: usize) usize { + return std.mem.alignForward(usize, capacity, c.block); +} + +/// Bytes of one position in one layer: its bf16 key and value heads, and its bf16 index key. +pub fn rowBytes(c: *const cfg.Config) usize { + return (@as(usize, c.kvWidth()) * 2 + c.index_dim) * 2; +} + +/// Bytes a stream of `capacity` positions holds in caches. +pub fn cacheBytes(c: *const cfg.Config, capacity: usize) usize { + return @as(usize, c.vocab) * 2 + @as(usize, c.layers) * slots(c, capacity) * rowBytes(c); +} + +/// A stream's latest tapped rows (positions [start, start + rows) at `off` of `buf`), for its drafter. +pub const Tap = struct { buf: ?mtl.Buffer = null, off: usize = 0, start: u64 = 0, rows: usize = 0 }; + +pub const Cache = struct { + kv: mtl.Buffer, // each layer's keys, values, then index keys, at `layer_at` + logits: mtl.Buffer, + tap: Tap = .{}, + /// The prompt's last tapped row, kept for the first draft (the prompt scratch serves the next pass). + last_tap: ?mtl.Buffer = null, + layer_at: [cfg.max_layers]usize = @splat(0), + capacity: usize, + len: usize = 0, + follow: ?mtl.ResidencySet.Follow = null, + + pub fn setResident(self: *Cache, hook: ?mtl.ResidencySet.Follow) void { + if (self.follow) |f| mtl.resident.fields.apply(self, f, false); + self.follow = hook; + if (hook) |f| mtl.resident.fields.apply(self, f, true); + } + + pub fn init(device: mtl.Device, c: *const cfg.Config, capacity: usize) !Cache { + var out = Cache{ .kv = undefined, .logits = undefined, .capacity = capacity }; + const per = slots(c, capacity) * rowBytes(c); + for (0..c.layers) |i| out.layer_at[i] = i * per; + out.kv = try device.buffer(@max(per * c.layers, 16), mtl.ResourceOptions.private); + errdefer out.kv.deinit(); + out.logits = try device.buffer(@as(usize, c.vocab) * 2, mtl.ResourceOptions.shared); + return out; + } + + pub fn keys(self: *const Cache, l: usize) usize { + return self.layer_at[l]; + } + + pub fn values(self: *const Cache, c: *const cfg.Config, l: usize) usize { + return self.layer_at[l] + slots(c, self.capacity) * c.kvWidth() * 2; + } + + pub fn indexKeys(self: *const Cache, c: *const cfg.Config, l: usize) usize { + return self.layer_at[l] + slots(c, self.capacity) * c.kvWidth() * 2 * 2; + } + + pub fn deinit(self: *Cache) void { + self.setResident(null); + if (self.last_tap) |x| x.deinit(); + self.kv.deinit(); + self.logits.deinit(); + } +}; + +pub const fields = [_][]const u8{ "ids", "resid", "x", "q", "qn", "iq", "o", "y", "shared", "gate", "act", "egu", "ea", "ey", "logits32", "pick", "wts", "xs", "sums", "offsets", "order", "logits_all", "pm", "pl", "po", "scores", "sel", "bits", "groups", "members" }; + +/// A prompt scratch's buffers in another's memory, never live at once (each host is dead before its guest is written). +const shares = .{ .{ "gate", "egu" }, .{ "act", "ea" }, .{ "ey", "xs" }, .{ "scores", "xs" }, .{ "shared", "o" }, .{ "y", "qn" } }; + +fn shared(comptime f: []const u8) bool { + inline for (shares) |pair| if (comptime std.mem.eql(u8, pair[0], f)) return true; + return false; +} + +fn index(comptime f: []const u8) usize { + inline for (fields, 0..) |g, i| if (comptime std.mem.eql(u8, g, f)) return i; + @compileError("no scratch field " ++ f); +} + +/// Bitmap words of a row's selected blocks: the model's whole window (the prompt attention is compiled for it). +pub fn selWords(c: *const cfg.Config) usize { + return std.math.divCeil(usize, c.blocks(c.context), 32) catch unreachable; +} + +/// Bytes of each Scratch buffer for `rows` rows at once over at most `context` positions, in `fields` order. +fn sizes(c: *const cfg.Config, rows: usize, context: usize) [fields.len]usize { + const r: usize = rows; + const prompt = rows > batch_rows; + const h: usize = c.hidden; + const slots_ = r * c.topk; + const qw = r * c.heads * c.head_dim * 2; + const inter: usize = @max(c.dense_intermediate, c.shared_intermediate); + // a prompt chunk's fp32 group sums: groups of 32 at the finest, over the widest input a projection reads + const widest: usize = @max(@max(h, inter), @as(usize, c.heads) * c.head_dim); + const decode = @min(r, batch_rows); + const partials = decode * c.heads * c.topk_blocks * 4 * 4; // decode attention's per-quarter maxima and sums (fp32) + const sums = if (prompt) @max(r * widest, slots_ * @max(h, @as(usize, c.moe_intermediate))) / 32 * 4 else 16; + const nb = c.blocks(context); + const sel_rows = r * c.kv_heads; + var out: [fields.len]usize = .{ + r * 4, r * h * 4, r * h * 2, r * c.qkvRows() * 2, qw, + (r + 32) * c.index_heads * c.index_dim * 2, qw, r * h * 2, r * h * 2, r * 2 * inter * 2, + r * inter * 2, slots_ * 2 * c.moe_intermediate * 2, slots_ * c.moe_intermediate * 2, slots_ * h * 2, r * c.experts * 4, + slots_ * 4, slots_ * 4, if (prompt) slots_ * h * 2 else 16, sums, c.experts * 4, + slots_ * 4, decode * @as(usize, c.vocab) * 2, if (prompt) 16 else partials, if (prompt) 16 else partials, if (prompt) 16 else partials * c.head_dim, + sel_rows * nb * 4, sel_rows * c.topk_blocks * 4, if (r > window_rows) sel_rows * selWords(c) * 4 else 16, (1 + 2 * slots_) * 4, slots_ * 4, + }; + if (prompt) inline for (shares) |pair| { + out[index(pair[1])] = @max(out[index(pair[1])], out[index(pair[0])]); + out[index(pair[0])] = 0; + }; + return out; +} + +/// Bytes a Scratch for `rows` rows over `context` positions holds. +pub fn scratchBytes(c: *const cfg.Config, rows: usize, context: usize) usize { + var total: usize = 0; + for (sizes(c, rows, context)) |n| total += n; + return total; +} + +pub const Scratch = struct { + ids: mtl.Buffer, + resid: mtl.Buffer, // fp32 [rows, hidden], bf16 values: the reference's residual + x: mtl.Buffer, // bf16 normed rows + q: mtl.Buffer, // the stacked projection's rows: q | k | v | index q | index k + qn: mtl.Buffer, // q normed and rotated + iq: mtl.Buffer, // index q normed and rotated + o: mtl.Buffer, + y: mtl.Buffer, // a sublayer's bf16 output [rows, hidden] + shared: mtl.Buffer, + gate: mtl.Buffer, // gate|up rows of a dense or shared MLP + act: mtl.Buffer, + egu: mtl.Buffer, // [rows * topk, 2 * moe_intermediate]: each pick's gate|up + ea: mtl.Buffer, + ey: mtl.Buffer, // [rows * topk, hidden] + logits32: mtl.Buffer, // the router's fp32 logits [rows, experts] + pick: mtl.Buffer, + wts: mtl.Buffer, + xs: mtl.Buffer, // the prompt path: picks' input rows by expert, group sums, each expert's first pair, the pair order + sums: mtl.Buffer, + offsets: mtl.Buffer, + order: mtl.Buffer, + logits_all: mtl.Buffer, // every row's logits of a window + pm: mtl.Buffer, // decode attention's partials by selected block: maxima, sums, outputs + pl: mtl.Buffer, + po: mtl.Buffer, + scores: mtl.Buffer, // the indexer's fp32 block scores [rows, kv_heads, blocks] + sel: mtl.Buffer, // each (row, key head)'s selected blocks ascending, -1 past the last [rows, kv_heads, topk_blocks] + bits: mtl.Buffer, // a prompt chunk's selections as bitmaps [rows, kv_heads, words] + groups: mtl.Buffer, // a decode window's experts picked and each one's first member (experts.metal's G) + members: mtl.Buffer, // the slots by expert (M) + rows: usize, + context: usize, + /// The drafter's tapped rows [rows, taps x hidden] bf16, once a drafter asked for them. + taps: ?mtl.Buffer = null, + + /// Buffers for `rows` rows at once (batch_rows for decode, prompt_rows for prompt chunks) over `context` positions. + pub fn init(device: mtl.Device, c: *const cfg.Config, rows: usize, context: usize) !Scratch { + @setEvalBranchQuota(10000); + const sizes_ = sizes(c, rows, context); + var s: Scratch = undefined; + s.rows = rows; + var made: [fields.len]bool = @splat(false); + errdefer inline for (fields, 0..) |f, i| if (made[i]) @field(s, f).deinit(); + inline for (fields, 0..) |f, i| if (!(s.sharing() and comptime shared(f))) { + @field(s, f) = try device.buffer(sizes_[i], mtl.ResourceOptions.shared); + made[i] = true; + }; + if (s.sharing()) inline for (shares) |pair| { + @field(s, pair[0]) = @field(s, pair[1]); + }; + s.context = context; + s.taps = null; + return s; + } + + /// A prompt scratch: some buffers share another's memory (`shares`). + fn sharing(s: *const Scratch) bool { + return s.rows > batch_rows; + } + + pub fn deinit(s: *Scratch) void { + inline for (fields) |f| if (!(s.sharing() and comptime shared(f))) @field(s, f).deinit(); + if (s.taps) |x| x.deinit(); + } +}; + +test "minimax_m3 state: a position's bytes in every layer, slots by whole blocks" { + const c = cfg.Config{}; + try std.testing.expectEqual(@as(usize, 2304), rowBytes(&c)); + try std.testing.expectEqual(@as(usize, 256), slots(&c, 129)); + try std.testing.expectEqual(@as(usize, 200064 * 2 + 60 * 128 * 2304), cacheBytes(&c, 100)); +} diff --git a/zig/src/families/minimax_m3/vision.zig b/zig/src/families/minimax_m3/vision.zig new file mode 100644 index 00000000000..7db8ce513d3 --- /dev/null +++ b/zig/src/families/minimax_m3/vision.zig @@ -0,0 +1,386 @@ +//! MiniMax-M3's image tower on Metal: patch embedding, 32 CLIP layers with axial RoPE, the merging projector. +const std = @import("std"); +const mtl = @import("metal"); +const ks = @import("kernel_sources"); +const frags = @import("../../core/frags.zig"); +const ck = @import("../../core/checkpoint_metal.zig"); +const vl = @import("../../core/qwen_vl/qwen_vl.zig"); +const picture = @import("../../core/picture/picture.zig"); +const Glue = @import("model.zig").Glue; + +pub const width = 1280; +pub const heads = 16; +pub const head_dim = 80; +pub const depth = 32; +pub const mlp_inter = 5120; +pub const hidden = 6144; // the projector's width and the language model's +pub const merge = 2; +pub const patch_width = 3 * 2 * 14 * 14; // channel by frame by row by column, the conv's own order +const freqs = 13; // each axis's: 2 * ((head_dim / 3) / 2) / 2 +const rotated = 6 * freqs; // 78 of the 80 head dims turn; the last two pass +const theta: f64 = 10000; +const eps: f32 = 1e-5; +pub const max_tokens: u32 = 576; // the processor's max_pixels, 672 x 672: 48 x 48 patches +const max_patches: u32 = max_tokens * merge * merge; +pub const shard = "model-vision.safetensors"; +/// The tokenizer's image markers: the processor writes start, the image's tokens, end (the template the token alone). +pub const image_start: u32 = 200029; +pub const image_end: u32 = 200030; + +/// The processor's settings as the shared Qwen-VL geometry reads them (smart_resize by 28, CLIP's mean and std). +pub const image_config: vl.Config = .{ .depth = depth, .hidden = width, .heads = heads, .intermediate = mlp_inter, .out_hidden = hidden, .patch = 14, .temporal = 2, .merge = merge, .positions = 0, .image_token = 0, .vision_start = 0, .vision_end = 0, .min_pixels = 4 * 28 * 28, .max_pixels = 672 * 672, .rescale = 1.0 / 255.0, .mean = .{ 0.48145466, 0.4578275, 0.40821073 }, .std = .{ 0.26862954, 0.26130258, 0.27577711 } }; + +pub const Ref = struct { + buf: mtl.Buffer, + off: usize = 0, + + pub fn at(r: Ref, n: usize) Ref { + return .{ .buf = r.buf, .off = r.off + n }; + } +}; + +fn ref(t: ck.Tensor) Ref { + return .{ .buf = t.buffer, .off = t.offset }; +} + +/// An image's bytes to patches in merge order: torchvision's antialiased bicubic (the fast processor's), then CLIP's. +pub fn prepare(io: std.Io, gpa: std.mem.Allocator, bytes: []const u8, budget: u32) !vl.geometry.Prepared { + var img = try picture.decode(io, gpa, bytes); + defer img.deinit(gpa); + const c = image_config; + if (budget == 0) return error.ImageTooSmall; + const b = vl.geometry.bounds(c, @min(budget, max_tokens)); + const size = try vl.geometry.smartResize(@intCast(img.height), @intCast(img.width), c.factor(), b[0], b[1]); + const resized = try picture.resample.resize(gpa, .torch, .of(img.pixels, img.width, img.height), size.w, size.h); + defer gpa.free(resized); + const g = [2]u32{ size.h / c.patch, size.w / c.patch }; + const pixels = try vl.geometry.patchify(gpa, .{ .width = size.w, .height = size.h, .pixels = resized }, c); + return .{ .pixels = pixels, .gh = g[0], .gw = g[1], .tokens = g[0] * g[1] / (merge * merge), .hash = picture.identity.withGrid(picture.identity.ofBytes(0x3a3a, bytes), g) }; +} + +/// Head dims moved so the core qkv kernel's pairs (d, d + 40) are MiniMax's (i, i + 39); q . k is unchanged. +fn moved(j: usize) usize { + return if (j < 39) j else if (j == 39) 78 else if (j < 79) j - 1 else 79; +} + +const Layer = struct { ln1_w: Ref, ln1_b: Ref, qkv_w: Ref, qkv_b: Ref, out_w: Ref, out_b: Ref, ln2_w: Ref, ln2_b: Ref, fc1_w: Ref, fc1_b: Ref, fc2_w: Ref, fc2_b: Ref }; + +pub const Vision = struct { + gpa: std.mem.Allocator, + lib: mtl.Library, + gemm: [3][2][2]mtl.Pipeline, // [bf16 nt, f32 nt, f32 nn][M % 64 == 0][N % 128 == 0] + norm: mtl.Pipeline, + qkv: mtl.Pipeline, + softmax: mtl.Pipeline, + heads_: mtl.Pipeline, + gelu: mtl.Pipeline, + residual: mtl.Pipeline, + bias: mtl.Pipeline, + widen: mtl.Pipeline, // the model's glue + narrow: mtl.Pipeline, + stacked: mtl.Buffer, // every layer's q | k | v weights (q, k rows moved) then their biases + scratch: mtl.Buffer, + chunk: u32, // query rows an attention pass scores + patch_w: Ref, // [width, patch_width] fp32, as stored + pre_w: Ref, + pre_b: Ref, + proj: [4][2]Ref, // the projector's linear_1, linear_2, then patch_merge_mlp's: weight, bias + layers: [depth]Layer, + patches: Ref, // [P, patch_width] fp32 + cos: Ref, // [P, head_dim] fp32 + sin: Ref, + x: Ref, // [P, width] fp32: the residual stream + xn: Ref, // [P, width] bf16 + att: Ref, + qkv_rows: Ref, // [P, 3 width] bf16 + q: Ref, // [heads, P, head_dim] fp32 + k: Ref, + v: Ref, + s: Ref, // [heads, chunk, P] fp32 + o: Ref, // [heads, chunk, head_dim] fp32 + mid: Ref, // [P, mlp_inter] bf16 + p1: Ref, // [P, hidden] bf16: the projector's two rows a patch, then [P / 4, hidden] merged + p2: Ref, + + const glue = .{ .{ "norm", "qwv_layer_norm" }, .{ "qkv", "qwv_qkv" }, .{ "softmax", "qwv_softmax" }, .{ "heads_", "qwv_heads" }, .{ "gelu", "qwv_bias_gelu" }, .{ "residual", "qwv_residual" }, .{ "bias", "qwv_bias" } }; + + /// The tower from `c`'s vision shard (already added): the shared Qwen-VL kernels, the q | k | v weights stacked. + pub fn load(gpa: std.mem.Allocator, device: mtl.Device, c: *const ck.Checkpoint, widen: mtl.Pipeline, narrow: mtl.Pipeline) !*Vision { + const v = try gpa.create(Vision); + errdefer gpa.destroy(v); + v.gpa = gpa; + v.widen = widen; + v.narrow = narrow; + const src = try frags.source(device, gpa, ks.core_qwen_vision); + defer gpa.free(src); + v.lib = try mtl.Library.fromSource(device, src, mtl.CompileOptions.mlx()); + errdefer v.lib.deinit(); + var made: usize = 0; + errdefer v.release(made); + for ([_][]const u8{ "bf16_nt", "f32_nt", "f32_nn" }, 0..) |kind, ki| for (0..2) |m| for (0..2) |n| { + var name: [32]u8 = undefined; + v.gemm[ki][m][n] = try mtl.Pipeline.init(device, v.lib, try std.fmt.bufPrint(&name, "qwv_gemm_{s}_{d}{d}", .{ kind, m, n }), false); + made += 1; + }; + inline for (glue) |kv| { + @field(v, kv[0]) = try mtl.Pipeline.init(device, v.lib, kv[1], false); + made += 1; + } + const pre = "vision_tower.vision_model."; + v.patch_w = ref(try get(c, pre ++ "embeddings.patch_embedding.weight", .f32, width * patch_width)); + v.pre_w = ref(try get(c, pre ++ "pre_layrnorm.weight", .bf16, width)); + v.pre_b = ref(try get(c, pre ++ "pre_layrnorm.bias", .bf16, width)); + const projs = [4]struct { []const u8, usize }{ .{ "multi_modal_projector.linear_1", width }, .{ "multi_modal_projector.linear_2", hidden }, .{ "patch_merge_mlp.linear_1", hidden * merge * merge }, .{ "patch_merge_mlp.linear_2", hidden } }; + for (projs, &v.proj) |p, *dst| { + var name: [96]u8 = undefined; + dst[0] = ref(try get(c, try std.fmt.bufPrint(&name, "{s}.weight", .{p[0]}), .bf16, hidden * p[1])); + dst[1] = ref(try get(c, try std.fmt.bufPrint(&name, "{s}.bias", .{p[0]}), .bf16, hidden)); + } + const per = 3 * width * width * 2; + v.stacked = try device.buffer(depth * (per + 3 * width * 2), mtl.ResourceOptions.shared); + errdefer v.stacked.deinit(); + const dst: [*]u16 = @ptrCast(@alignCast(v.stacked.contents())); + for (&v.layers, 0..) |*l, i| { + const at = struct { + fn t(cp: *const ck.Checkpoint, at_layer: usize, name: []const u8, dtype: ck.DType, count: usize) !ck.Tensor { + var b: [128]u8 = undefined; + return get(cp, try std.fmt.bufPrint(&b, pre ++ "encoder.layers.{d}.{s}", .{ at_layer, name }), dtype, count); + } + }.t; + const w_at = i * 3 * width * width; + const b_at = depth * 3 * width * width + i * 3 * width; + for ([_][]const u8{ "q", "k", "v" }, 0..) |which, part| { + var nb: [64]u8 = undefined; + const wt = try at(c, i, try std.fmt.bufPrint(&nb, "self_attn.{s}_proj.weight", .{which}), .bf16, width * width); + const bt = try at(c, i, try std.fmt.bufPrint(&nb, "self_attn.{s}_proj.bias", .{which}), .bf16, width); + const ws: [*]const u16 = @ptrCast(@alignCast(wt.buffer.contents() + wt.offset)); + const bs: [*]const u16 = @ptrCast(@alignCast(bt.buffer.contents() + bt.offset)); + for (0..width) |row| { + const from = if (part == 2) row else row / head_dim * head_dim + moved(row % head_dim); + @memcpy(dst[w_at + (part * width + row) * width ..][0..width], ws[from * width ..][0..width]); + dst[b_at + part * width + row] = bs[from]; + } + } + l.qkv_w = .{ .buf = v.stacked, .off = w_at * 2 }; + l.qkv_b = .{ .buf = v.stacked, .off = b_at * 2 }; + l.ln1_w = ref(try at(c, i, "layer_norm1.weight", .bf16, width)); + l.ln1_b = ref(try at(c, i, "layer_norm1.bias", .bf16, width)); + l.ln2_w = ref(try at(c, i, "layer_norm2.weight", .bf16, width)); + l.ln2_b = ref(try at(c, i, "layer_norm2.bias", .bf16, width)); + l.out_w = ref(try at(c, i, "self_attn.out_proj.weight", .bf16, width * width)); + l.out_b = ref(try at(c, i, "self_attn.out_proj.bias", .bf16, width)); + l.fc1_w = ref(try at(c, i, "mlp.fc1.weight", .bf16, mlp_inter * width)); + l.fc1_b = ref(try at(c, i, "mlp.fc1.bias", .bf16, mlp_inter)); + l.fc2_w = ref(try at(c, i, "mlp.fc2.weight", .bf16, width * mlp_inter)); + l.fc2_b = ref(try at(c, i, "mlp.fc2.bias", .bf16, width)); + } + // the scores take at most 256 MiB: every head's `chunk` query rows by P keys in fp32 + const P: usize = max_patches; + v.chunk = @intCast(std.math.clamp((256 << 20) / (heads * P * 4) / 64 * 64, 64, P)); + const parts = [_]usize{ P * patch_width * 4, P * head_dim * 4, P * head_dim * 4, P * width * 4, P * width * 2, P * width * 2, P * 3 * width * 2, heads * P * head_dim * 4, heads * P * head_dim * 4, heads * P * head_dim * 4, @as(usize, heads) * v.chunk * P * 4, @as(usize, heads) * v.chunk * head_dim * 4, P * mlp_inter * 2, P * hidden * 2, P * hidden * 2 }; + var total: usize = 0; + for (parts) |n| total += std.mem.alignForward(usize, n, 256); + v.scratch = try device.buffer(total, mtl.ResourceOptions.shared | mtl.ResourceOptions.untracked); + errdefer v.scratch.deinit(); + var off: usize = 0; + for ([_]*Ref{ &v.patches, &v.cos, &v.sin, &v.x, &v.xn, &v.att, &v.qkv_rows, &v.q, &v.k, &v.v, &v.s, &v.o, &v.mid, &v.p1, &v.p2 }, parts) |view, n| { + view.* = .{ .buf = v.scratch, .off = off }; + off += std.mem.alignForward(usize, n, 256); + } + return v; + } + + pub fn deinit(v: *Vision) void { + v.scratch.deinit(); + v.stacked.deinit(); + v.release(3 * 2 * 2 + glue.len); + v.lib.deinit(); + v.gpa.destroy(v); + } + + /// The first `n` pipelines in the order `load` makes them. + fn release(v: *Vision, n: usize) void { + var i: usize = 0; + for (&v.gemm) |*a| for (a) |*b| for (b) |p| { + if (i == n) return; + p.deinit(); + i += 1; + }; + inline for (glue) |kv| { + if (i == n) return; + @field(v, kv[0]).deinit(); + i += 1; + } + } + + /// Bytes of the tower's own buffers (beside the checkpoint's shards). + pub fn bytes(v: *const Vision) u64 { + return v.stacked.length() + v.scratch.length(); + } + + /// Buffers to keep resident with the model's (its other weights are in the checkpoint's shards). + pub fn buffers(v: *const Vision) [2]mtl.Buffer { + return .{ v.stacked, v.scratch }; + } + + /// One image's patches ([gh * gw, patch_width] fp32, merge order) to its gh * gw / 4 rows at `out` (bf16, hidden). + pub fn encode(v: *Vision, e: mtl.ComputeEncoder, pixels: []const f32, gh: u32, gw: u32, out: Ref) !void { + const P: u32 = gh * gw; + if (P == 0 or gh % merge != 0 or gw % merge != 0 or pixels.len != @as(usize, P) * patch_width) return error.ImageGrid; + if (P > max_patches) return error.ImageTooLarge; + v.tables(pixels, gh, gw); + v.gemmAt(e, 1, v.patches, v.patch_w, v.x, P, width, patch_width, patch_width, patch_width, width, 1, 0, 0, 0); + v.layerNorm(e, v.x, v.pre_w, v.pre_b, v.xn, P); + v.copy(e, v.widen, v.xn, v.x, P * width); + for (v.layers) |l| v.layer(e, l, P); + // the projector: each patch's rows, then four neighbours' (merge order) as one row of p2 read [P / 4, 4 hidden] + const T = P / (merge * merge); + v.copy(e, v.narrow, v.x, v.xn, P * width); + v.linear(e, v.xn, v.proj[0][0], v.p1, P, hidden, width); + v.gelu_(e, v.p1, v.proj[0][1], P, hidden); + v.linear(e, v.p1, v.proj[1][0], v.p2, P, hidden, hidden); + v.bias_(e, v.p2, v.proj[1][1], P, hidden); + v.linear(e, v.p2, v.proj[2][0], v.p1, T, hidden, merge * merge * hidden); + v.gelu_(e, v.p1, v.proj[2][1], T, hidden); + v.linear(e, v.p1, v.proj[3][0], out, T, hidden, hidden); + v.bias_(e, out, v.proj[3][1], T, hidden); + } + + /// Rows of an encoded image over `n` embedded prompt rows (`dst`, the forward's fp32 residual). + pub fn inject(v: *const Vision, e: mtl.ComputeEncoder, src: Ref, dst: Ref, n: u32) void { + v.copy(e, v.widen, src, dst, n * hidden); + } + + /// The host's part: the patches, and each patch's cos and sin over the moved head dims. + fn tables(v: *Vision, pixels: []const f32, gh: u32, gw: u32) void { + const P: usize = @as(usize, gh) * gw; + @memcpy(@as([*]f32, @ptrCast(@alignCast(v.scratch.contents() + v.patches.off)))[0..pixels.len], pixels); + const cs: [*]f32 = @ptrCast(@alignCast(v.scratch.contents() + v.cos.off)); + const sn: [*]f32 = @ptrCast(@alignCast(v.scratch.contents() + v.sin.off)); + var inv: [freqs]f64 = undefined; + for (&inv, 0..) |*f, i| f.* = 1.0 / std.math.pow(f64, theta, @as(f64, @floatFromInt(2 * i)) / (2 * freqs)); + for (0..P) |i| { + const p = vl.grid.place(i, gw, merge); + const pos = [3]f32{ 0, @floatFromInt(p[0]), @floatFromInt(p[1]) }; // t, h, w: an image is frame 0 + for (0..head_dim / 2) |j| { + // slot j and j + 40 hold MiniMax's dims j and j + 39 (j < 39): axis j / 13, frequency j % 13 + const a: f32 = if (j < rotated / 2) pos[j / freqs] * @as(f32, @floatCast(inv[j % freqs])) else 0; + const c, const s = .{ @cos(a), @sin(a) }; + for ([2]usize{ j, j + head_dim / 2 }) |d| { + cs[i * head_dim + d] = c; + sn[i * head_dim + d] = s; + } + } + } + } + + fn layer(v: *Vision, e: mtl.ComputeEncoder, l: Layer, P: u32) void { + v.layerNorm(e, v.x, l.ln1_w, l.ln1_b, v.xn, P); + v.linear(e, v.xn, l.qkv_w, v.qkv_rows, P, 3 * width, width); + e.setPipeline(v.qkv); + for ([_]Ref{ v.qkv_rows, l.qkv_b, v.cos, v.sin, v.q, v.k, v.v }, 0..) |r, i| e.setBuffer(r.buf, r.off, i); + e.setValue([3]u32{ P, heads, head_dim }, 7); + e.dispatchThreads(mtl.Size.of(head_dim, 3 * heads, P), mtl.Size.of(head_dim, 256 / head_dim, 1)); + var q0: u32 = 0; + while (q0 < P) : (q0 += v.chunk) { + const lc = @min(v.chunk, P - q0); + const stride = @as(usize, P) * head_dim; + v.gemmAt(e, 1, v.q.at(@as(usize, q0) * head_dim * 4), v.k, v.s, lc, P, head_dim, head_dim, head_dim, P, heads, stride, stride, @as(usize, lc) * P); + e.setPipeline(v.softmax); + e.setBuffer(v.s.buf, v.s.off, 0); + e.setValue(P, 1); + e.setValue(1.0 / @sqrt(@as(f32, head_dim)), 2); + e.dispatchGroups(mtl.Size.of(@as(usize, heads) * lc, 1, 1), mtl.Size.of(256, 1, 1)); + v.gemmAt(e, 2, v.s, v.v, v.o, lc, head_dim, P, P, head_dim, head_dim, heads, @as(usize, lc) * P, stride, @as(usize, lc) * head_dim); + e.setPipeline(v.heads_); + e.setBuffer(v.o.buf, v.o.off, 0); + e.setBuffer(v.att.buf, v.att.off, 1); + e.setValue([4]u32{ lc, q0, heads, head_dim }, 2); + e.dispatchThreads(mtl.Size.of(width, lc, 1), mtl.Size.of(256, 1, 1)); + } + v.linear(e, v.att, l.out_w, v.xn, P, width, width); + v.residual_(e, v.xn, l.out_b, P, width); + v.layerNorm(e, v.x, l.ln2_w, l.ln2_b, v.xn, P); + v.linear(e, v.xn, l.fc1_w, v.mid, P, mlp_inter, width); + v.gelu_(e, v.mid, l.fc1_b, P, mlp_inter); + v.linear(e, v.mid, l.fc2_w, v.xn, P, width, mlp_inter); + v.residual_(e, v.xn, l.fc2_b, P, width); + } + + /// y [M, N] = x [M, K] w^T in bf16 with fp32 sums (w as stored, [N, K]). + fn linear(v: *Vision, e: mtl.ComputeEncoder, x: Ref, w: Ref, y: Ref, M: u32, N: u32, K: u32) void { + v.gemmAt(e, 0, x, w, y, M, N, K, K, K, N, 1, 0, 0, 0); + } + + /// tfp::gemm_nax: d [batch, M, N] = a x b (kind 0: bf16 a b^T, 1: fp32 a b^T, 2: fp32 a b), batches `s*` apart. + fn gemmAt(v: *Vision, e: mtl.ComputeEncoder, kind: usize, a: Ref, b: Ref, d: Ref, M: u32, N: u32, K: u32, lda: u32, ldb: u32, ldd: u32, batch: u32, sa: usize, sb: usize, sd: usize) void { + const tn = (N + 127) / 128; + const tm = (M + 63) / 64; + e.setPipeline(v.gemm[kind][@intFromBool(M % 64 == 0)][@intFromBool(N % 128 == 0)]); + e.setBuffer(a.buf, a.off, 0); + e.setBuffer(b.buf, b.off, 1); + var p: [16]i32 = @splat(0); + const vals = [_]usize{ M, N, K, lda, ldb, ldd, tn, tm, 2, K / 256, sa, sb, sd, 0, 0 }; + for (vals, 0..) |x, i| p[i] = @intCast(x); + e.setBytes(std.mem.asBytes(&p), 2); + e.setBuffer(d.buf, d.off, 3); + e.dispatchThreads(mtl.Size.of(@as(usize, tn << 2) * 32, (tm + 3) / 4 * 4, @as(usize, batch) * 2), mtl.Size.of(32, 4, 2)); + } + + fn layerNorm(v: *Vision, e: mtl.ComputeEncoder, x: Ref, w: Ref, b: Ref, y: Ref, rows: u32) void { + e.setPipeline(v.norm); + for ([_]Ref{ x, w, b, y }, 0..) |r, i| e.setBuffer(r.buf, r.off, i); + e.setValue(extern struct { rows: u32, width: u32, eps: f32 }{ .rows = rows, .width = width, .eps = eps }, 4); + e.dispatchGroups(mtl.Size.of(rows, 1, 1), mtl.Size.of(256, 1, 1)); + } + + /// y = gelu(y + b), the exact (erf) GELU. + fn gelu_(v: *Vision, e: mtl.ComputeEncoder, y: Ref, b: Ref, rows: u32, n: u32) void { + e.setPipeline(v.gelu); + e.setBuffer(y.buf, y.off, 0); + e.setBuffer(b.buf, b.off, 1); + e.setValue([2]u32{ n, 1 }, 2); + e.dispatchThreads(mtl.Size.of(n, rows, 1), mtl.Size.of(256, 1, 1)); + } + + fn bias_(v: *Vision, e: mtl.ComputeEncoder, y: Ref, b: Ref, rows: u32, n: u32) void { + e.setPipeline(v.bias); + e.setBuffer(y.buf, y.off, 0); + e.setBuffer(b.buf, b.off, 1); + e.setValue(n, 2); + e.dispatchThreads(mtl.Size.of(n, rows, 1), mtl.Size.of(256, 1, 1)); + } + + /// x += y + b on the residual stream. + fn residual_(v: *Vision, e: mtl.ComputeEncoder, y: Ref, b: Ref, rows: u32, n: u32) void { + e.setPipeline(v.residual); + for ([_]Ref{ v.x, y, b }, 0..) |r, i| e.setBuffer(r.buf, r.off, i); + e.setValue(n, 3); + e.dispatchThreads(mtl.Size.of(n, rows, 1), mtl.Size.of(256, 1, 1)); + } + + fn copy(_: *const Vision, e: mtl.ComputeEncoder, p: mtl.Pipeline, src: Ref, dst: Ref, n: u32) void { + e.setPipeline(p); + e.setBuffer(src.buf, src.off, 0); + e.setBuffer(dst.buf, dst.off, 1); + e.setValue(n, 2); + e.dispatchThreads(mtl.Size.of(n, 1, 1), mtl.Size.of(256, 1, 1)); + } +}; + +fn get(c: *const ck.Checkpoint, name: []const u8, dtype: ck.DType, count: usize) !ck.Tensor { + const t = try c.get(name); + if (t.dtype != dtype or t.count() != count) { + std.log.err("minimax_m3 vision: {s} is not {s}[{d}]", .{ name, @tagName(dtype), count }); + return error.UnexpectedMiniMaxVisionTensor; + } + return t; +} + +test "the moved head dims pair MiniMax's rotary halves and keep every dim once" { + var seen: [head_dim]bool = @splat(false); + for (0..head_dim) |j| seen[moved(j)] = true; + for (seen) |s| try std.testing.expect(s); + for (0..39) |j| try std.testing.expectEqual(moved(j) + 39, moved(j + head_dim / 2)); + try std.testing.expectEqual([2]usize{ 78, 79 }, [2]usize{ moved(39), moved(79) }); +} diff --git a/zig/src/families/minimax_m3/weights.zig b/zig/src/families/minimax_m3/weights.zig new file mode 100644 index 00000000000..fdd15427782 --- /dev/null +++ b/zig/src/families/minimax_m3/weights.zig @@ -0,0 +1,142 @@ +//! The converted MiniMax-M3.1-Flash checkpoint as row-projection matrices: stacked projections, fp32 routers. +const std = @import("std"); +const ck = @import("../../core/checkpoint_metal.zig"); +const rows = @import("../../core/row_projection.zig"); +const cfg = @import("config.zig"); + +pub const Tensor = ck.Tensor; +pub const Linear = rows.Weights; + +/// q | k | v | index q | index k stacked by rows (one launch), o; the four head norms (Gemma's: scaled by 1 + w). +pub const Attention = struct { qkv: Linear, o: Linear, q_norm: Tensor, k_norm: Tensor, iq_norm: Tensor, ik_norm: Tensor }; +/// gate | up stacked by rows. +pub const Mlp = struct { gu: Linear, down: Linear }; +/// The fp32 router [experts, hidden] and its score bias, the experts (gate | up rows each) and the shared expert. +pub const Moe = struct { router: Tensor, bias: Tensor, gu: rows.Experts, down: rows.Experts, shared: Mlp }; +pub const Layer = struct { input_norm: Tensor, post_norm: Tensor, attn: Attention, ffn: union(enum) { dense: Mlp, moe: Moe } }; + +pub const Weights = struct { + embed: Linear, + head: Linear, + norm: Tensor, + layers: []Layer, + + pub fn deinit(w: *Weights, gpa: std.mem.Allocator) void { + gpa.free(w.layers); + } +}; + +fn name(buf: []u8, a: []const u8, b: []const u8) ![]const u8 { + return std.fmt.bufPrint(buf, "{s}{s}", .{ a, b }); +} + +/// `t` is `dtype` with exactly `dims`, its bytes those dims' extent. +fn require(t: Tensor, dtype: ck.DType, dims: []const usize) error{UnexpectedMiniMaxTensor}!void { + if (t.dtype != dtype or t.rank != dims.len or t.rank > t.shape.len) return error.UnexpectedMiniMaxTensor; + if (!std.mem.eql(usize, t.shape[0..t.rank], dims)) return error.UnexpectedMiniMaxTensor; + var bytes: usize = dtype.size(); + for (dims) |n| { + if (n == 0) return error.UnexpectedMiniMaxTensor; + bytes = std.math.mul(usize, bytes, n) catch return error.UnexpectedMiniMaxTensor; + } + if (t.bytes != bytes) return error.UnexpectedMiniMaxTensor; +} + +fn tensor(c: *const ck.Checkpoint, prefix: []const u8, suffix: []const u8, dtype: ck.DType, dims: []const usize) !Tensor { + var buf: [256]u8 = undefined; + const n = try name(&buf, prefix, suffix); + const t = try c.get(n); + require(t, dtype, dims) catch |e| { + std.log.err("minimax_m3: {s} is not {s}{any}", .{ n, @tagName(dtype), dims }); + return e; + }; + return t; +} + +/// An affine [.., n, k] matrix: bits and group read from the stored shapes, which must agree with each other. +fn affine(c: *const ck.Checkpoint, prefix: []const u8, suffix: []const u8, stack: usize, n: usize, k: usize) !Linear { + var buf: [256]u8 = undefined; + const base = try name(&buf, prefix, suffix); + var b2: [256]u8 = undefined; + const w = try c.get(try name(&b2, base, ".weight")); + const s = try c.get(try name(&b2, base, ".scales")); + const z = try c.get(try name(&b2, base, ".biases")); + return checkedAffine(w, s, z, stack, n, k) catch |e| { + std.log.err("minimax_m3: {s} is not an affine [{d}, {d}, {d}] matrix", .{ base, stack, n, k }); + return e; + }; +} + +/// MLX's affine layout: u32 words [.., n, k * bits / 32], bf16 scales and biases [.., n, k / group]. +pub fn checkedAffine(w: Tensor, s: Tensor, z: Tensor, stack: usize, n: usize, k: usize) !Linear { + if (stack == 0 or n == 0 or k == 0 or n > std.math.maxInt(i32) or k > std.math.maxInt(i32)) return error.UnexpectedMiniMaxTensor; + const rank: usize = if (stack == 1) 2 else 3; + if (w.rank != rank or s.rank != rank or z.rank != rank or w.dtype != .u32) return error.UnexpectedMiniMaxTensor; + const words = w.shape[rank - 1]; + const groups = s.shape[rank - 1]; + const wd = [3]usize{ stack, n, words }; + const sd = [3]usize{ stack, n, groups }; + try require(w, .u32, wd[3 - rank ..]); + try require(s, .bf16, sd[3 - rank ..]); + try require(z, .bf16, sd[3 - rank ..]); + const packed_bits = std.math.mul(usize, words, 32) catch return error.UnexpectedMiniMaxTensor; + if (groups == 0 or k % groups != 0 or packed_bits % k != 0 or packed_bits / k > std.math.maxInt(u8)) return error.UnexpectedMiniMaxTensor; + const out = Linear{ .w = w.buffer, .w_off = w.offset, .scales = s.buffer, .s_off = s.offset, .biases = z.buffer, .b_off = z.offset, .n = n, .k = k, .group = k / groups, .bits = @intCast(packed_bits / k) }; + try out.validate(); + return out; +} + +pub fn load(gpa: std.mem.Allocator, c: *const ck.Checkpoint, f: *const cfg.Config) !Weights { + try cfg.validate(f); + const h: usize = f.hidden; + const w = Weights{ + .embed = try affine(c, "model.", "embed_tokens", 1, f.vocab, h), + .head = try affine(c, "", "lm_head", 1, f.vocab, h), + .norm = try tensor(c, "model.", "norm.weight", .bf16, &.{h}), + .layers = try gpa.alloc(Layer, f.layers), + }; + errdefer gpa.free(w.layers); + const qn: usize = f.heads * f.head_dim; + const d: usize = f.head_dim; + for (w.layers, 0..) |*l, i| { + var pb: [64]u8 = undefined; + const p = try std.fmt.bufPrint(&pb, "model.layers.{d}.", .{i}); + var ab: [96]u8 = undefined; + const a = try name(&ab, p, "self_attn"); + l.input_norm = try tensor(c, p, "input_layernorm.weight", .bf16, &.{h}); + l.post_norm = try tensor(c, p, "post_attention_layernorm.weight", .bf16, &.{h}); + l.attn = .{ + .qkv = try affine(c, a, ".qkv_proj", 1, f.qkvRows(), h), + .o = try affine(c, a, ".o_proj", 1, h, qn), + .q_norm = try tensor(c, a, ".q_norm.weight", .bf16, &.{d}), + .k_norm = try tensor(c, a, ".k_norm.weight", .bf16, &.{d}), + .iq_norm = try tensor(c, a, ".index_q_norm.weight", .bf16, &.{f.index_dim}), + .ik_norm = try tensor(c, a, ".index_k_norm.weight", .bf16, &.{f.index_dim}), + }; + var mb: [96]u8 = undefined; + const m = try name(&mb, p, "mlp"); + if (!f.layer[i].moe) { + l.ffn = .{ .dense = .{ + .gu = try affine(c, m, ".gate_up_proj", 1, 2 * @as(usize, f.dense_intermediate), h), + .down = try affine(c, m, ".down_proj", 1, h, f.dense_intermediate), + } }; + continue; + } + const e: usize = f.experts; + var sb: [128]u8 = undefined; + const sh = try name(&sb, m, ".shared_experts"); + var xb: [128]u8 = undefined; + const sw = try name(&xb, m, ".switch_mlp"); + l.ffn = .{ .moe = .{ + .router = try tensor(c, m, ".gate.weight", .f32, &.{ e, h }), + .bias = try tensor(c, m, ".e_score_correction_bias", .f32, &.{e}), + .gu = .{ .one = try affine(c, sw, ".gate_up_proj", e, 2 * @as(usize, f.moe_intermediate), h), .experts = e, .repeat = 1 }, + .down = .{ .one = try affine(c, sw, ".down_proj", e, h, f.moe_intermediate), .experts = e, .repeat = 1 }, + .shared = .{ + .gu = try affine(c, sh, ".gate_up_proj", 1, 2 * @as(usize, f.shared_intermediate), h), + .down = try affine(c, sh, ".down_proj", 1, h, f.shared_intermediate), + }, + } }; + } + return w; +} diff --git a/zig/src/native/metal.zig b/zig/src/native/metal.zig index f9913464736..549593892ab 100644 --- a/zig/src/native/metal.zig +++ b/zig/src/native/metal.zig @@ -51,6 +51,7 @@ pub const families: []const api.Family = &.{ .{ .model_type = "gemma4_unified", .formats = gemma4_widths }, .{ .model_type = "step5_vl", .formats = &.{"mlx-q2g128"} }, .{ .model_type = "spark2_5", .formats = &.{ "bf16", "mlx-q2g64", "mlx-q3g64", "mlx-q4g64", "mlx-q5g64", "mlx-q6g64", "mlx-q8g64" } }, + .{ .model_type = "minimax_m3_vl", .formats = &.{ "mlx-q3g64", "mlx-q8g64" } }, }; /// Gemma 4 31B (gemma4) and 12B (gemma4_unified, its text model): one native family, gemma4.zig's host. @@ -171,7 +172,7 @@ pub fn open(a: Allocator, gpa: Allocator, io: std.Io, o: api.Open, problem: *[]c } if (@import("save_admission.zig").refused(io, o.dir, problem)) return null; if (std.mem.eql(u8, o.model_type, "qwen4") or std.mem.eql(u8, o.model_type, "qwen4_text")) return @import("qwen4_metal.zig").open(a, gpa, io, o, problem); - const dense = std.mem.eql(u8, o.model_type, "qwen3_5") and qwen27Engine(a, io, o.dir); + const dense = std.mem.eql(u8, o.model_type, "qwen3_5") and @import("qwen27_engine.zig").owns(a, io, o.dir); if (try refusal(a, o, dense)) |why| { problem.* = why; return null; @@ -184,14 +185,15 @@ pub fn open(a: Allocator, gpa: Allocator, io: std.Io, o: api.Open, problem: *[]c if (std.mem.eql(u8, o.model_type, "qwen4_exp")) return openFlashNext(a, gpa, io, o, problem); if (std.mem.eql(u8, o.model_type, "glm5_next")) return openGlm(a, gpa, io, o, problem); if (isGemma4(o.model_type)) return @import("gemma4.zig").open(a, gpa, io, o, problem); - if (o.vision != null and !std.mem.eql(u8, o.model_type, "step5_vl")) { - problem.* = try std.fmt.allocPrint(a, "--vision: the native engine reads images for GLM-5.3-Flash, Qwen3.8-27B, Qwen3.8 Flash Next, Gemma 4 and Step-5 only, not {s} checkpoints", .{o.model_type}); + if (o.vision != null and !std.mem.eql(u8, o.model_type, "step5_vl") and !std.mem.eql(u8, o.model_type, "minimax_m3_vl")) { + problem.* = try std.fmt.allocPrint(a, "--vision: the native engine reads images for GLM-5.3-Flash, Qwen3.8-27B, Qwen3.8 Flash Next, Gemma 4, Step-5 and MiniMax-M3.1-Flash only, not {s} checkpoints", .{o.model_type}); return null; } if (std.mem.eql(u8, o.model_type, "glm_moe_dsa")) return openGlmDsa(a, gpa, io, o, problem); if (std.mem.eql(u8, o.model_type, "qwen3_5")) return @import("qwen35.zig").open(a, gpa, io, o, problem); if (std.mem.eql(u8, o.model_type, "step5_vl")) return @import("step5.zig").open(a, gpa, io, o, problem); if (std.mem.eql(u8, o.model_type, "spark2_5")) return @import("spark25.zig").open(a, gpa, io, o, problem); + if (std.mem.eql(u8, o.model_type, "minimax_m3_vl")) return @import("minimax_m3.zig").open(a, gpa, io, o, problem); if (std.mem.eql(u8, o.model_type, "lfm2_moe")) return @import("lfm2_moe.zig").open(a, gpa, io, o, problem); if (!std.mem.eql(u8, o.model_type, "nemotron_h")) { problem.* = try std.fmt.allocPrint(a, "the native engine has no backend for {s} checkpoints yet; the Python engine 0.6.6 may serve them: python -m pip install git+https://github.com/ashhart/TensorFold.git@v0.6.6", .{o.model_type}); @@ -337,33 +339,19 @@ fn refusal(a: Allocator, o: api.Open, dense: bool) !?[]const u8 { if (o.kv8) return "--kv-cache fp8 keeps fp8 caches on CUDA; the Metal engines keep bf16: serve without it"; if (o.prompt_int8) return prompt_int8_refusal; if (o.slide and !std.mem.eql(u8, t, "nemotron_h")) return try std.fmt.allocPrint(a, "--slide: {s} checkpoints do not learn on Macs yet", .{t}); - const one_mac: ?[]const u8 = if (std.mem.eql(u8, t, "nemotron_h")) "Nemotron" 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, "qwen3_5")) null else if (dense) "Qwen3.8-27B" else "Qwen3.5-2B"; + const one_mac: ?[]const u8 = if (std.mem.eql(u8, t, "nemotron_h")) "Nemotron" 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")) 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; if (spill.refusal(o)) |why| return why; if (o.learn == null) return null; // the 27B writes conversation states if (o.learn_conversations and std.mem.eql(u8, t, "qwen3_5") and dense) return null; - const name: []const u8 = if (std.mem.eql(u8, t, "glm_moe_dsa")) "GLM-5.3 (EXLR8)" 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, "qwen3_5")) return null else if (dense) "Qwen3.8-27B" else "Qwen3.5-2B"; + const name: []const u8 = if (std.mem.eql(u8, t, "glm_moe_dsa")) "GLM-5.3 (EXLR8)" 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")) return null else if (dense) "Qwen3.8-27B" else "Qwen3.5-2B"; if (o.learn_conversations) return try std.fmt.allocPrint(a, "{s} keeps conversation states on disk for Qwen3.8-27B, Nemotron, Flash Next and GLM-5.3-Flash: serve {s} without it", .{ spill.flag(o), name }); const or_talks: []const u8 = if (dense) " (Qwen3.8-27B keeps conversation states on disk with --learn-conversations)" else ""; return try std.fmt.allocPrint(a, "--learn learns prompt prefixes for Nemotron, Flash Next and GLM-5.3-Flash only{s}: serve {s} without --learn, --learn-dir or --learn-gib", .{ or_talks, name }); } -/// A qwen3_5 checkpoint opens the 27B engine unless it has the pinned 2B's hidden size or a tied head, which stay on the 2B's. -fn qwen27Engine(a: Allocator, io: std.Io, dir: []const u8) bool { - const path = std.fs.path.join(a, &.{ dir, "config.json" }) catch return true; - const bytes = std.Io.Dir.cwd().readFileAlloc(io, path, a, .limited(16 << 20)) catch return true; - const doc = std.json.parseFromSliceLeaky(std.json.Value, a, bytes, .{}) catch return true; - if (doc != .object) return true; - const text = if (doc.object.get("text_config")) |t| (if (t == .object) t else doc) else doc; - for ([_]std.json.Value{ doc, text }) |o| { - if (o.object.get("tie_word_embeddings")) |v| if (v == .bool and v.bool) return false; - if (o.object.get("hidden_size")) |v| if (v == .integer and v.integer == tf.qwen35.config.hidden) return false; - } - return true; -} - /// Qwen3.8-27B on the lane host: `--parallel` streams in shared rounds, DFlash2 drafts from --drafter for one of them. fn openQwen27(a: Allocator, gpa: Allocator, io: std.Io, o: api.Open, problem: *[]const u8) !?api.Opened { const context = o.context orelse 32768; @@ -506,28 +494,6 @@ test "chip classes from Metal device names" { try std.testing.expectEqual(@as(?u32, null), generation("Apple Mx")); } -test "a qwen3_5 checkpoint opens the 27B engine unless it has the 2B's geometry or a tied head" { - var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); - defer arena.deinit(); - const a = arena.allocator(); - const io = std.testing.io; - var tmp = std.testing.tmpDir(.{}); - defer tmp.cleanup(); - const dir = try std.fmt.allocPrint(a, ".zig-cache/tmp/{s}", .{tmp.sub_path}); - try std.testing.expect(qwen27Engine(a, io, dir)); // no config.json: the 27B's loader explains the refusal - const cases = [_]struct { config: []const u8, big: bool }{ - .{ .config = "{\"model_type\":\"qwen3_5\",\"text_config\":{\"tie_word_embeddings\":true}}", .big = false }, - .{ .config = "{\"model_type\":\"qwen3_5\",\"tie_word_embeddings\":true,\"text_config\":{}}", .big = false }, - .{ .config = "{\"model_type\":\"qwen3_5\",\"tie_word_embeddings\":false,\"text_config\":{\"tie_word_embeddings\":false}}", .big = true }, - .{ .config = "{\"model_type\":\"qwen3_5\",\"hidden_size\":5120}", .big = true }, - .{ .config = "{\"model_type\":\"qwen3_5\",\"text_config\":{\"tie_word_embeddings\":false,\"hidden_size\":2048}}", .big = false }, - }; - for (cases) |c| { - try tmp.dir.writeFile(io, .{ .sub_path = "config.json", .data = c.config }); - try std.testing.expectEqual(c.big, qwen27Engine(a, io, dir)); - } -} - test "--learn is refused for the 27B, the 2B and GLM-5.3 (EXLR8), and not for the families that keep prompt states on disk" { var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); defer arena.deinit(); diff --git a/zig/src/native/minimax_m3.zig b/zig/src/native/minimax_m3.zig new file mode 100644 index 00000000000..6b538cd4c0e --- /dev/null +++ b/zig/src/native/minimax_m3.zig @@ -0,0 +1,233 @@ +//! MiniMax-M3.1-Flash served by the lane host: one-row rounds and copy-drafted windows within the memory budget. +const std = @import("std"); +const mtl = @import("metal"); +const api = @import("engine_api"); +const tf = @import("tensorfold"); +const fl = tf.minimax_m3; +const lanes = tf.lanes; +const Resident = @import("resident.zig").Resident; + +const Host = struct { + gpa: std.mem.Allocator, + io: std.Io, + model: *fl.Model, + metal: *fl.backend.Metal, + draft: ?*fl.dspark.Drafter = null, // the checkpoint's DSpark head (MINIMAX_DRAFTER=dspark), when drafts are on + draft2: ?*fl.dflash2.Drafter = null, // incoai's DFlash2, when the checkpoint has it (the default) + 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, + clock: lanes.backend.WallClock, + core: lanes.Engine, + host: api.LaneHost, + cache: ?api.prompt_cache.Store = null, // kept prompt states, in what the streams' caches leave of the budget + cache_cap: u64 = 0, // --prompt-cache-gib's bytes (the budget when unset) + markers: [3]u32 = undefined, // an image's start, its token and end (--vision): text that spells one stays text + + fn close(ctx: *anyopaque) void { + const h: *Host = @ptrCast(@alignCast(ctx)); + h.host.stop(); + if (h.cache) |*store| store.deinit(); + h.core.deinit(); + if (h.wrap) |*w| w.deinit(); + if (h.draft) |d| d.deinit(); + if (h.draft2) |d| d.deinit(); + h.config.deinit(h.gpa); + fl.residency.drop(h); + h.metal.deinit(); + h.model.deinit(); + h.gpa.destroy(h); + } +}; + +pub fn open(a: std.mem.Allocator, gpa: std.mem.Allocator, io: std.Io, o: api.Open, problem: *[]const u8) !?api.Opened { + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const kind = @import("tensorfold").minimax_m3.drafterKind() orelse { + problem.* = "MINIMAX_DRAFTER names no drafter: give dflash2 or dspark, or unset it for dflash2"; + return null; + }; + const model = fl.Model.load(gpa, io, o.dir) catch |err| { + problem.* = try std.fmt.allocPrint(a, "the native MiniMax-M3 engine cannot load this checkpoint ({s})", .{@errorName(err)}); + return null; + }; + errdefer model.deinit(); + if (o.vision != null) model.loadVision(io, o.dir) catch |err| { + problem.* = try std.fmt.allocPrint(a, "--vision: this MiniMax-M3 checkpoint's image tower cannot load ({s}; {s} holds it)", .{ @errorName(err), fl.vision.shard }); + model.deinit(); + return null; + }; + // refusals that return null free what they hold themselves: errdefer runs only for errors + var ram: u64 = 0; + var len: usize = @sizeOf(u64); + if (std.c.sysctlbyname("hw.memsize", &ram, &len, null, 0) != 0) ram = 0; + const text: ?[]const u8 = if (std.c.getenv("MINIMAX_LOAD_LIMIT_GB")) |v| std.mem.span(v) else null; + const c = &model.config; // the decode window's and the prompt chunk's buffers + const tower: u64 = if (model.vision) |v| v.bytes() else 0; + const scratch: u64 = fl.state.scratchBytes(c, fl.state.batch_rows, c.context) + fl.state.scratchBytes(c, fl.state.prompt_rows, c.context) + tower; + const budget = fl.budget.caches(ram, model.device.maxWorkingSet(), text, model.checkpoint.residentBytes() + scratch) catch { + model.deinit(); + problem.* = "MINIMAX_LOAD_LIMIT_GB is not a load limit: give a number of GB above 0, or unset it for 75% of RAM"; + return null; + }; + const fits = fl.budget.longest(&model.config, budget, model.config.context); + const window: i64 = o.context orelse @intCast(fits); + if (window < 1 or window > fits) { + problem.* = try std.fmt.allocPrint(a, "--context {d}: this Mac's MiniMax-M3 caches fit {d} tokens under its load limit (75% of RAM, or MINIMAX_LOAD_LIMIT_GB)", .{ window, fits }); + model.deinit(); // after the message, so a failed allocation leaves the model to the errdefer + return null; + } + std.log.info("minimax_m3: {d:.1} GiB for caches, context up to {d} tokens", .{ @as(f64, @floatFromInt(budget)) / (1 << 30), window }); + const h = try gpa.create(Host); + errdefer gpa.destroy(h); + h.gpa = gpa; + h.io = io; + h.model = model; + h.resident = null; + const df2 = if (o.drafts and kind == .dflash2) fl.dflash2.Config.read(gpa, io, o.dir) catch |err| { + problem.* = try std.fmt.allocPrint(a, "the checkpoint's DFlash2 config cannot be read ({s})", .{@errorName(err)}); + model.deinit(); + return null; + } else null; + const dspark = if (o.drafts and df2 == null) fl.dspark.Config.read(gpa, io, o.dir) catch |err| { + problem.* = try std.fmt.allocPrint(a, "the checkpoint's DSpark config cannot be read ({s})", .{@errorName(err)}); + model.deinit(); + return null; + } else null; + h.metal = try fl.backend.Metal.init(gpa, model, .{ .capacity = @intCast(window), .streams = @max(o.lanes, 1), .budget = budget, .drafts = dspark != null or df2 != null }); + errdefer h.metal.deinit(); + try h.metal.warm(); + h.draft = null; + h.draft2 = null; + h.wrap = null; + if (df2) |dc| { + try h.metal.measure(); + h.draft2 = try fl.dflash2.Drafter.init(gpa, model, dc); + h.wrap = try lanes.drafted.Drafted.init(gpa, h.metal.backend(), h.draft2.?.drafter()); + } else if (dspark) |dc| { + try h.metal.measure(); // the depth rule prices drafts against the window forward's cost by rows + h.draft = try fl.dspark.Drafter.init(gpa, model, dc); + h.wrap = try lanes.drafted.Drafted.init(gpa, h.metal.backend(), h.draft.?.drafter()); + } + errdefer if (h.wrap) |*w| w.deinit(); + errdefer if (h.draft) |d| d.deinit(); + errdefer if (h.draft2) |d| d.deinit(); + const facts = if (h.wrap) |*w| w.facts(h.metal.facts()) else h.metal.facts(); + h.config = try lanes.Config.init(gpa, facts, fl.state.window_rows, fl.state.window_rows - 1); + errdefer h.config.deinit(gpa); + h.clock = .{ .io = io }; + 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.markers = .{ fl.vision.image_start, model.config.image_token, fl.vision.image_end }; + // the template writes the image token alone: the server adds start and end around each image's rows + const vis: ?api.Vision = if (o.vision) |v| .{ .ctx = h, .prepare = prepareImage, .image_token = h.markers[1], .markers = &h.markers, .wrap = .{ h.markers[0], h.markers[2] }, .part_type = "image", .image_tokens = v.image_tokens, .max_images = v.max_images, .explain = tf.qwen_vl.geometry.problem } else null; + h.host = api.LaneHost.init(gpa, io, &h.core, .{ .lanes = o.lanes, .context_window = @intCast(window), .prefill_step = fl.state.prompt_rows, .structures = true, .logprobs = true, .vision = vis }); + h.cache = null; + h.cache_cap = if (o.prompt_cache_gib) |g| @intFromFloat(g * (1 << 30)) else budget; + if (h.cache_cap > 0) { + const M = fl.backend.Metal; + // prompt chunks change arithmetic with their rows + const rules: api.prompt_cache.Rules = .{ .lookahead = 0, .planned = true, .grid = fl.state.prompt_rows, .min_prompt = 0 }; + h.cache = api.prompt_cache.Store.init(gpa, .{ .ptr = h.metal, .vtable = &.{ .bytes = M.snapBytes, .save = M.snapSave, .restore = M.snapRestore, .drop = M.snapDrop } }, rules, @min(h.cache_cap, budget)); + h.host.cache = &h.cache.?; + h.host.info_.prompt_cache = true; + h.metal.room = .{ .ctx = h, .fit = fitCache }; + } + errdefer if (h.cache) |*store| store.deinit(); + try fl.residency.hold(h); + errdefer fl.residency.drop(h); + h.host.keepalive_target = .{ .ctx = &h.warm, .tick = mtl.keepalive.Target.tick }; + try h.host.start(); + return .{ .engine = h.host.engine(), .close = Host.close, .ctx = h }; +} + +/// Info.vision's prepare (on the HTTP thread): at most the tower's 576 tokens an image. +fn prepareImage(ctx: *anyopaque, a: std.mem.Allocator, bytes: []const u8, max_tokens: u32) anyerror!api.PreparedImage { + const h: *Host = @ptrCast(@alignCast(ctx)); + const p = try fl.vision.prepare(h.io, a, bytes, max_tokens); + return .{ .pixels = p.pixels, .gh = p.gh, .gw = p.gw, .tokens = p.tokens, .hash = p.hash }; +} + +/// Metal.room's fit: the kept states' budget is what the streams leave, at most the cap; the least valuable go first. +fn fitCache(ctx: *anyopaque, bytes: u64, restoring: ?*anyopaque, prompt: []const u32) void { + const h: *Host = @ptrCast(@alignCast(ctx)); + const store = if (h.cache) |*owned| owned else return; + store.budget = @min(h.cache_cap, bytes); + const Left = struct { + s: *const api.prompt_cache.Store, + pub fn fits(l: @This()) bool { + return l.s.held <= l.s.budget; + } + }; + _ = store.giveBack(restoring, prompt, Left{ .s = store }); +} + +const CacheFixture = struct { + live: usize = 0, + fn bytes(_: *anyopaque, at: u32) u64 { + return 100 + at; + } + fn save(ptr: *anyopaque, _: ?*anyopaque, at: u32) !api.prompt_cache.Saved { + const self: *@This() = @ptrCast(@alignCast(ptr)); + const held = try std.testing.allocator.create(u32); + held.* = at; + self.live += 1; + return held; + } + fn restore(_: *anyopaque, _: ?*anyopaque, _: api.prompt_cache.Saved) !void {} + fn drop(ptr: *anyopaque, saved: api.prompt_cache.Saved) void { + const self: *@This() = @ptrCast(@alignCast(ptr)); + std.testing.allocator.destroy(@as(*u32, @ptrCast(@alignCast(saved)))); + self.live -= 1; + } + fn snapshots(self: *@This()) api.prompt_cache.Snapshots { + return .{ .ptr = self, .vtable = &.{ .bytes = bytes, .save = save, .restore = restore, .drop = drop } }; + } +}; + +test "minimax_m3 host: cache callback updates the owned store rather than a temporary value" { + var f: CacheFixture = .{}; + var h: Host = undefined; + h.cache_cap = 500; + h.cache = api.prompt_cache.Store.init(std.testing.allocator, f.snapshots(), .{ .min_prompt = 0 }, 500); + defer h.cache.?.deinit(); + fitCache(&h, 200, null, &.{}); + try std.testing.expectEqual(@as(u64, 200), h.cache.?.budget); + fitCache(&h, 800, null, &.{}); + try std.testing.expectEqual(@as(u64, 500), h.cache.?.budget); +} + +test "minimax_m3 host: cache callback evicts from the real store and preserves the restored entry" { + var f: CacheFixture = .{}; + var h: Host = undefined; + h.cache_cap = 1000; + h.cache = api.prompt_cache.Store.init(std.testing.allocator, f.snapshots(), .{ .min_prompt = 0 }, 1000); + defer h.cache.?.deinit(); + const store = &h.cache.?; + try std.testing.expect(store.keep(&.{ 1, 1, 1, 1, 9 }, 4, null, &.{}, &.{})); + try std.testing.expect(store.keep(&.{ 2, 2, 2, 2, 2, 2, 9 }, 6, null, &.{}, &.{})); + try std.testing.expectEqual(@as(u64, 210), store.held); + const kept = store.entries.items[0].saved; + fitCache(&h, 110, kept, &.{ 1, 1, 1, 1, 9 }); + try std.testing.expectEqual(@as(u64, 110), store.budget); + try std.testing.expectEqual(@as(u64, 104), store.held); + try std.testing.expectEqual(@as(usize, 1), store.entries.items.len); + try std.testing.expect(store.entries.items[0].saved == kept); + try std.testing.expectEqual(@as(usize, 1), f.live); + try std.testing.expectEqual(@as(u64, 1), store.counts.evicted); + fitCache(&h, 110, kept, &.{ 1, 1, 1, 1, 9 }); + try std.testing.expectEqual(@as(u64, 1), store.counts.evicted); + fitCache(&h, 0, null, &.{}); + try std.testing.expectEqual(@as(u64, 0), store.held); + try std.testing.expectEqual(@as(usize, 0), store.entries.items.len); + try std.testing.expectEqual(@as(usize, 0), f.live); + try std.testing.expectEqual(@as(u64, 2), store.counts.evicted); +} + +test "minimax_m3 host: cache callback with no configured cache leaves no state to mutate" { + var h: Host = undefined; + h.cache = null; + fitCache(&h, 0, null, &.{}); + try std.testing.expect(h.cache == null); +} diff --git a/zig/src/native/qwen27_engine.zig b/zig/src/native/qwen27_engine.zig new file mode 100644 index 00000000000..e84e28cc2ce --- /dev/null +++ b/zig/src/native/qwen27_engine.zig @@ -0,0 +1,40 @@ +//! Which engine a qwen3_5 checkpoint opens on Macs: the 27B's, or the pinned 2B's. +const std = @import("std"); +const tf = @import("tensorfold"); +const Allocator = std.mem.Allocator; + +/// The 27B engine, unless the checkpoint has the pinned 2B's hidden size or a tied head (the 2B's engine then). +pub fn owns(a: Allocator, io: std.Io, dir: []const u8) bool { + const path = std.fs.path.join(a, &.{ dir, "config.json" }) catch return true; + const bytes = std.Io.Dir.cwd().readFileAlloc(io, path, a, .limited(16 << 20)) catch return true; + const doc = std.json.parseFromSliceLeaky(std.json.Value, a, bytes, .{}) catch return true; + if (doc != .object) return true; + const text = if (doc.object.get("text_config")) |t| (if (t == .object) t else doc) else doc; + for ([_]std.json.Value{ doc, text }) |o| { + if (o.object.get("tie_word_embeddings")) |v| if (v == .bool and v.bool) return false; + if (o.object.get("hidden_size")) |v| if (v == .integer and v.integer == tf.qwen35.config.hidden) return false; + } + return true; +} + +test "a qwen3_5 checkpoint opens the 27B engine unless it has the 2B's geometry or a tied head" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const io = std.testing.io; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const dir = try std.fmt.allocPrint(a, ".zig-cache/tmp/{s}", .{tmp.sub_path}); + try std.testing.expect(owns(a, io, dir)); // no config.json: the 27B's loader explains the refusal + const cases = [_]struct { config: []const u8, big: bool }{ + .{ .config = "{\"model_type\":\"qwen3_5\",\"text_config\":{\"tie_word_embeddings\":true}}", .big = false }, + .{ .config = "{\"model_type\":\"qwen3_5\",\"tie_word_embeddings\":true,\"text_config\":{}}", .big = false }, + .{ .config = "{\"model_type\":\"qwen3_5\",\"tie_word_embeddings\":false,\"text_config\":{\"tie_word_embeddings\":false}}", .big = true }, + .{ .config = "{\"model_type\":\"qwen3_5\",\"hidden_size\":5120}", .big = true }, + .{ .config = "{\"model_type\":\"qwen3_5\",\"text_config\":{\"tie_word_embeddings\":false,\"hidden_size\":2048}}", .big = false }, + }; + for (cases) |c| { + try tmp.dir.writeFile(io, .{ .sub_path = "config.json", .data = c.config }); + try std.testing.expectEqual(c.big, owns(a, io, dir)); + } +} diff --git a/zig/src/server/chat.zig b/zig/src/server/chat.zig index 41ce3580e78..406e5f03d43 100644 --- a/zig/src/server/chat.zig +++ b/zig/src/server/chat.zig @@ -355,7 +355,7 @@ const Generation = struct { try fresh.append(g.a, t); } const all = try g.visible.extend(g.a, g.srv.text, reply_text.decodeText, fresh.items); - const text = g.stops.visible(all, true); + const text = try @import("tool_minimax.zig").dsml(g.a, g.stops.visible(all, true), g.tools); // MiniMax-M3's calls as DSML if (g.visible.pending()) return; // a character still split across tokens var answer = text; if (g.thinking) { @@ -369,7 +369,7 @@ const Generation = struct { answer = split.answer; } answer = try tool_lfm2.dsml(g.a, answer, g.tools, false); // the answer only, so a call the reasoning mentions is not made - const shown = if (g.calls != null) try reply_text.hideInto(g.a, &g.hidden, answer, false, true) else answer; + const shown = if (g.calls != null) try reply_text.hideInto(g.a, &g.hidden, answer, false, true, reply_text.openersOf(g.srv.markers)) else answer; const vis = reply_text.heldBack(reply_text.streamingVisible(shown), g.calls != null); const copied = @intFromPtr(vis.ptr) >= @intFromPtr(g.hidden.items.ptr) and @intFromPtr(vis.ptr) <= @intFromPtr(g.hidden.items.ptr) + g.hidden.items.len; const delta = g.streamed.after(vis, !copied); @@ -477,7 +477,7 @@ const Generation = struct { const finished_ns = nowNs(g.srv.io); const content_tokens = if (g.ignore_eos) g.collected.items else reply_text.stripTrailing(g.collected.items, g.srv.eos); const raw = try g.srv.text.decode(a, content_tokens); - const visible = g.stops.visible(raw, false); + const visible = try @import("tool_minimax.zig").dsml(a, g.stops.visible(raw, false), g.tools); // closed before the think split, so a call ending an unclosed think block is the answer const close = try g.closeCall(visible); const text = if (close.len > 0) try std.mem.concat(a, u8, &.{ visible, close }) else visible; diff --git a/zig/src/server/prompt.zig b/zig/src/server/prompt.zig index 585e910dee1..d089854b568 100644 --- a/zig/src/server/prompt.zig +++ b/zig/src/server/prompt.zig @@ -43,6 +43,10 @@ pub fn renderIds(srv: *Server, cx: *Cx, messages: Value, tools: []const Value, t error.OutOfMemory => return error.OutOfMemory, error.Template => return cx.fail(.request, "{s}", .{problem}), }; + // MiniMax-M3 thinks adaptively: with thinking off, its reply begins after the `` the prompt ends with + if (!thinking and generation and std.mem.eql(u8, srv.markers.close, @import("reply_text.zig").mm_markers.close)) { + if (srv.text.tokenId(srv.markers.close)) |close| return try std.mem.concat(cx.a, u32, &.{ ids, &.{close} }); + } if (!thinking and generation and ids.len > 0) { const last = try srv.text.decode(cx.a, ids[ids.len - 1 ..]); if (std.mem.eql(u8, @import("reply_text.zig").pyStrip(last), "")) { diff --git a/zig/src/server/reply_text.zig b/zig/src/server/reply_text.zig index 4de95b3898e..2abd4be795b 100644 --- a/zig/src/server/reply_text.zig +++ b/zig/src/server/reply_text.zig @@ -5,8 +5,14 @@ const Allocator = std.mem.Allocator; pub const Markers = struct { open: []const u8, close: []const u8 }; /// Qwen's prompt opens the think block; Gemma 4's reply opens its thought channel. pub const think_markers: Markers = .{ .open = "", .close = "" }; -/// The opener a reply writes itself when its template leaves the think block to it (Kolibri 1's does). +/// MiniMax-M3's adaptive thinking: the reply writes `...` itself, or `` alone. +pub const mm_markers: Markers = .{ .open = "", .close = "" }; +/// The opener a reply writes itself when its template leaves the think block to it (Kolibri 1's and MiniMax-M3's do). const think_open = ""; + +fn openerOf(m: Markers) []const u8 { + return if (std.mem.eql(u8, m.close, mm_markers.close)) "" else think_open; +} pub const channel_markers: Markers = .{ .open = "<|channel>thought", .close = "" }; /// (opener, closer) of a tool call's markup: Qwen's, Gemma 4's, DeepSeek-V4's DSML block, LFM2's, V4.1's spaced DSML. pub const calls = [_][2][]const u8{ @@ -16,15 +22,28 @@ pub const calls = [_][2][]const u8{ .{ "<|tool_call_start|>", "<|tool_call_end|>" }, .{ "<\u{ff5c}DSML\u{ff5c} calls>", "" }, }; -/// Each opener's payload lead: Gemma 4's ``call:`` (26B: ``:``), DSML's invoke; ```` and LFM2 have none. +/// Each opener's payload lead: Gemma 4's ``call:`` (26B: ``:``), DSML's invoke; the other openers have none. const leads = [calls.len][]const []const u8{ &.{}, &.{ "call:", ":" }, &.{"<\u{ff5c}DSML\u{ff5c}invoke"}, &.{}, &.{"<\u{ff5c}DSML\u{ff5c} invoke"} }; +/// The call openers a stream watches for, with their payload leads. +pub const Openers = struct { calls: []const [2][]const u8, leads: []const []const []const u8 }; +pub const shared_openers: Openers = .{ .calls = &calls, .leads = &leads }; +/// MiniMax-M3's servers also watch for its own block, which tool_minimax.zig rewrites as DSML once it closes. +const mm_calls = calls ++ [_][2][]const u8{.{ "]<]minimax[>[", "]<]minimax[>[" }}; +const mm_leads = leads ++ [_][]const []const u8{&.{}}; +const mm_openers: Openers = .{ .calls = &mm_calls, .leads = &mm_leads }; + +/// The openers for a server's markers: MiniMax-M3's block only where the markers are MiniMax-M3's. +pub fn openersOf(m: Markers) Openers { + return if (std.mem.eql(u8, m.close, mm_markers.close)) mm_openers else shared_openers; +} + /// Whether the text after an opener is a call's payload, may still become one, or is prose that names the opener. -fn payloadOf(rest: []const u8, which: usize, finished: bool) enum { call, wait, prose } { - if (leads[which].len == 0) return .call; +fn payloadOf(rest: []const u8, o: Openers, which: usize, finished: bool) enum { call, wait, prose } { + if (o.leads[which].len == 0) return .call; const body = std.mem.trimStart(u8, rest, " \t\r\n"); - for (leads[which]) |lead| if (std.mem.startsWith(u8, body, lead)) return .call; - if (!finished) for (leads[which]) |lead| if (std.mem.startsWith(u8, lead, body)) return .wait; + for (o.leads[which]) |lead| if (std.mem.startsWith(u8, body, lead)) return .call; + if (!finished) for (o.leads[which]) |lead| if (std.mem.startsWith(u8, lead, body)) return .wait; return .prose; } @@ -97,6 +116,7 @@ pub fn splitThinkingTokens(a: Allocator, decode: anytype, ctx: anytype, full: [] /// As `splitThinking`, but the close marker is the model's own close token: the reasoning ends at that token's bytes. pub fn splitThinkingAt(a: Allocator, full: []const u8, finished: bool, m: Markers, close: Close) Allocator.Error!Split { + const o = openersOf(m); var text = full; var at: ?usize = switch (close) { .spelled, .pending => null, @@ -114,7 +134,7 @@ pub fn splitThinkingAt(a: Allocator, full: []const u8, finished: bool, m: Marker }; if (!finished) { var held = @max(partialTag(text, m.open), partialTag(text, m.close)); - for (calls) |c| held = @max(held, partialTag(text, c[0])); + for (o.calls) |c| held = @max(held, partialTag(text, c[0])); return .{ .reasoning = "", .answer = text[0 .. text.len - held] }; } return .{ .reasoning = "", .answer = text }; @@ -125,12 +145,12 @@ pub fn splitThinkingAt(a: Allocator, full: []const u8, finished: bool, m: Marker const trimmed = trimNewlines(rest); shift = m.open.len + (rest.len - trimmed.len); text = trimmed; - } else if (std.mem.startsWith(u8, text, think_open)) { - const rest = text[think_open.len..]; + } else if (std.mem.startsWith(u8, text, openerOf(m))) { + const rest = text[openerOf(m).len..]; const trimmed = trimNewlines(rest); - shift = think_open.len + (rest.len - trimmed.len); + shift = openerOf(m).len + (rest.len - trimmed.len); text = trimmed; - } else if (!finished and std.mem.startsWith(u8, think_open, text)) { + } else if (!finished and std.mem.startsWith(u8, openerOf(m), text)) { return .{ .reasoning = "", .answer = "" }; // held while the reply may still be writing that opener } if (at) |v| at = if (v >= shift) v - shift else null; @@ -146,20 +166,20 @@ pub fn splitThinkingAt(a: Allocator, full: []const u8, finished: bool, m: Marker // the close token's bytes are not where the text says: the whole text is reasoning } var call: ?usize = null; - for (calls) |c| if (find(text, c[0])) |at_call| { + for (o.calls) |c| if (find(text, c[0])) |at_call| { if (call == null or at_call < call.?) call = at_call; }; if (call) |at_call| { // a call written before the block closes: held while the block may still close, the answer if the reply ends if (!finished) return .{ .reasoning = text[0..at_call], .answer = "" }; - for (calls) |c| if (std.mem.startsWith(u8, text[at_call..], c[0]) and find(text[at_call..], c[1]) != null) + for (o.calls) |c| if (std.mem.startsWith(u8, text[at_call..], c[0]) and find(text[at_call..], c[1]) != null) return .{ .reasoning = text[0..at_call], .answer = text[at_call..] }; return .{ .reasoning = text, .answer = "" }; } var held: usize = 0; if (!finished) { held = partialTag(text, m.close); - for (calls) |c| held = @max(held, partialTag(text, c[0])); + for (o.calls) |c| held = @max(held, partialTag(text, c[0])); } return .{ .reasoning = text[0 .. text.len - held], .answer = "" }; } @@ -167,19 +187,20 @@ pub fn splitThinkingAt(a: Allocator, full: []const u8, finished: bool, m: Marker /// Hides tool-call blocks and partial opening tags while streaming, so calls arrive as deltas instead. pub fn hideToolCalls(a: Allocator, text: []const u8, finished: bool) Allocator.Error![]const u8 { var out: std.ArrayList(u8) = .empty; - return hideInto(a, &out, text, finished, false); + return hideInto(a, &out, text, finished, false, shared_openers); } -/// ``hideToolCalls`` into ``out`` (cleared first); text without a call block comes back as a slice of ``text``. -pub fn hideInto(a: Allocator, out: *std.ArrayList(u8), text: []const u8, finished: bool, defer_closed: bool) Allocator.Error![]const u8 { +/// ``hideToolCalls`` into ``out`` (cleared first) for openers ``o``; text without a call block is a slice of ``text``. +pub fn hideInto(a: Allocator, out: *std.ArrayList(u8), text: []const u8, finished: bool, defer_closed: bool, o: Openers) Allocator.Error![]const u8 { out.clearRetainingCapacity(); var pos: usize = 0; - var next: [calls.len]?usize = undefined; // each opener at or after `pos`, searched again only once `pos` passes it - for (calls, &next) |c, *n| n.* = findTag(text, 0, c[0]); + var next_buf: [mm_calls.len]?usize = undefined; // each opener at or after `pos`, searched again only once `pos` passes it + const next = next_buf[0..o.calls.len]; + for (o.calls, next) |c, *n| n.* = findTag(text, 0, c[0]); while (true) { var start: ?usize = null; var which: usize = 0; - for (calls, &next, 0..) |c, *n, i| { + for (o.calls, next, 0..) |c, *n, i| { if (n.* != null and n.*.? < pos) n.* = findTag(text, pos, c[0]); if (n.*) |at| if (start == null or at < start.?) { start = at; @@ -189,7 +210,7 @@ pub fn hideInto(a: Allocator, out: *std.ArrayList(u8), text: []const u8, finishe if (start == null) { const tail = text[pos..]; var held: usize = 0; - if (!finished) for (calls) |c| { + if (!finished) for (o.calls) |c| { held = @max(held, partialTag(tail, c[0])); }; if (pos == 0) return text[0 .. text.len - held]; @@ -197,8 +218,8 @@ pub fn hideInto(a: Allocator, out: *std.ArrayList(u8), text: []const u8, finishe return out.items; } try out.appendSlice(a, text[pos..start.?]); - const after = start.? + calls[which][0].len; - switch (payloadOf(text[after..], which, finished)) { + const after = start.? + o.calls[which][0].len; + switch (payloadOf(text[after..], o, which, finished)) { .call => {}, .wait => return out.items, .prose => { @@ -207,14 +228,14 @@ pub fn hideInto(a: Allocator, out: *std.ArrayList(u8), text: []const u8, finishe continue; }, } - const end = findTag(text, after, calls[which][1]) orelse { + const end = findTag(text, after, o.calls[which][1]) orelse { // a finished reply's envelope that never closed is text, as tool_parse.parse keeps it in the content if (finished) try out.appendSlice(a, text[start.?..]); return out.items; }; // Final parsing may retain this envelope, so later prose must not overtake it. if (defer_closed) return out.items; - pos = end + calls[which][1].len; + pos = end + o.calls[which][1].len; } } @@ -230,7 +251,7 @@ pub fn finishedProse(a: Allocator, text: []const u8) Allocator.Error![]const u8 // attachCalls has not yet decided whether to strip the reply's content. if (pyLstrip(text).len != text.len) return text[0..0]; var out: std.ArrayList(u8) = .empty; - const prose = try hideInto(a, &out, text, true, true); + const prose = try hideInto(a, &out, text, true, true, shared_openers); return if (prose.len != text.len) prose[0..pyRstrip(prose).len] else prose; } @@ -520,3 +541,28 @@ test "an opener the reply names in prose keeps the text after it, streamed and w // a finished reply's unclosed envelope is text, as tool_parse.parse keeps it in the content try std.testing.expectEqualStrings("a {\"name\"", try finishedProse(a, "a {\"name\"")); } + +test "reply text: MiniMax-M3's adaptive think block, written by the reply or skipped with its close alone" { + const a = std.testing.allocator; + const full = try splitThinking(a, "17 * 23 = 391.391", true, mm_markers); + try std.testing.expectEqualStrings("17 * 23 = 391.", full.reasoning); + try std.testing.expectEqualStrings("391", full.answer); + const bare = try splitThinking(a, "Hello there", true, mm_markers); + try std.testing.expectEqualStrings("", bare.reasoning); + try std.testing.expectEqualStrings("Hello there", bare.answer); + const held = try splitThinking(a, "[]<]minimax[>[")) |end| { + if (text.tokenId(if (minimax) reply_text.mm_markers.close else "")) |end| { const lead = try text.encode(a, "\n", false); const trail = try text.encode(a, "\n\n", false); srv.think_close = try std.mem.concat(a, u32, &.{ lead, &.{end}, trail }); diff --git a/zig/src/server/tool_grammar.zig b/zig/src/server/tool_grammar.zig index b34e7d7c516..c7d9d8c5a5d 100644 --- a/zig/src/server/tool_grammar.zig +++ b/zig/src/server/tool_grammar.zig @@ -12,7 +12,7 @@ const Cx = errors.Cx; const Allocator = std.mem.Allocator; /// The template's call envelope, with XML parameters or JSON arguments. -pub const Style = enum { xml, json, gemma, glm }; +pub const Style = enum { xml, json, gemma, glm, minimax }; const probe = "tfprobe_fn"; const key = "tfprobe_k"; @@ -26,6 +26,7 @@ const value_blanks = 32; /// The style of `rendered`, a turn that calls `probe` with {key: "v"}; null: markup this grammar does not write. pub fn style(rendered: []const u8) ?Style { if (std.mem.indexOf(u8, rendered, "<|tool_call>call:" ++ probe ++ "{") != null) return .gemma; + if (std.mem.indexOf(u8, rendered, mm ++ "") != null) return .minimax; const at = std.mem.lastIndexOf(u8, rendered, "") orelse return null; const text = rendered[at..]; if (std.mem.indexOf(u8, text, "") != null and std.mem.indexOf(u8, text, "") != null) return .xml; @@ -34,6 +35,9 @@ pub fn style(rendered: []const u8) ?Style { return null; } +/// MiniMax-M3's prefix: one call block around every invoke, each argument an element (xgrammar's minimax_m3_xml). +const mm = "]<]minimax[>["; + /// The grammar for a reply that must call one of `tools`: one call, or (`parallel`) one or more, then the end. pub fn structure(srv: *Server, cx: *Cx, tools: []const Value, parallel: bool, thinking: bool) errors.Refused!api.Structure { const probe_turn = (try json.parse(cx.a, "[{\"role\": \"user\", \"content\": \"x\"}, {\"role\": \"assistant\", \"content\": \"\", \"tool_calls\": [{\"id\": \"call_0\", \"type\": \"function\", \"function\": {\"name\": \"" ++ probe ++ "\", \"arguments\": {\"" ++ key ++ "\": \"v\"}}}]}]")).ok; @@ -54,6 +58,14 @@ pub fn build(a: Allocator, s: Style, tools: []const Value, parallel: bool) Alloc for (tools, calls) |t, *c| c.* = try call(a, s, try tool_specs.toolName(a, t), try parameters(a, t)); const one: Value = if (calls.len == 1) calls[0] else try node(a, "or", &.{.{ "elements", .{ .array = calls } }}); const ws = try node(a, "regex", &.{.{ "pattern", .{ .string = blanks } }}); + if (s == .minimax) { // one block: its invokes back to back, as the template writes parallel calls + var inner: std.ArrayList(Value) = .empty; + try inner.appendSlice(a, &.{ ws, try constant(a, mm ++ "\n"), one }); + if (parallel) try inner.append(a, try node(a, "star", &.{.{ "content", one }})); + try inner.appendSlice(a, &.{ try constant(a, mm ++ ""), ws }); + const block = try node(a, "sequence", &.{.{ "elements", .{ .array = inner.items } }}); + return json.stringify(a, try node(a, "structural_tag", &.{.{ "format", block }}), .{ .ascii = false, .compact = true }); + } var parts: std.ArrayList(Value) = .empty; try parts.appendSlice(a, &.{ ws, one }); if (parallel) try parts.append(a, try node(a, "star", &.{.{ "content", try node(a, "sequence", &.{.{ "elements", try list(a, &.{ ws, one }) }}) }})); @@ -85,6 +97,10 @@ fn call(a: Allocator, s: Style, name: []const u8, schema: Value) Allocator.Error try whole.put(a, "required", try list(a, &.{ .{ .string = "name" }, .{ .string = "arguments" } })); break :blk try list(a, &.{ try constant(a, ""), ws, try arguments(a, .{ .object = whole }, "json"), ws, try constant(a, "") }); }, + .minimax => try list(a, &.{ + try constant(a, try std.fmt.allocPrint(a, mm ++ "", .{name})), try arguments(a, schema, "minimax_m3_xml"), + try constant(a, mm ++ "\n"), + }), // GLM's template writes NAMEKV... with no blanks: xgrammar's glm_xml .glm => try list(a, &.{ try constant(a, try std.fmt.allocPrint(a, "{s}", .{name})), try arguments(a, schema, "glm_xml"), @@ -129,6 +145,18 @@ test "the probe call's markup picks the style" { try std.testing.expectEqual(Style.json, style("\n{\"name\": \"tfprobe_fn\", \"arguments\": {\"tfprobe_k\": \"v\"}}\n").?); try std.testing.expectEqual(Style.gemma, style("<|tool_call>call:tfprobe_fn{tfprobe_k:<|\"|>v<|\"|>}").?); try std.testing.expectEqual(Style.glm, style("tfprobe_fntfprobe_kv").?); + try std.testing.expectEqual(Style.minimax, style("" ++ mm ++ "\n" ++ mm ++ "" ++ mm ++ "v" ++ mm ++ "" ++ mm ++ "\n" ++ mm ++ "").?); +} + +test "MiniMax-M3's grammar: one call block, invokes in minimax_m3_xml, more of them only with parallel calls" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const tools = (try json.parse(a, "[{\"type\": \"function\", \"function\": {\"name\": \"get_weather\", \"parameters\": {\"type\": \"object\", \"properties\": {\"city\": {\"type\": \"string\"}}, \"required\": [\"city\"]}}}]")).ok; + const single = try build(a, .minimax, tools.array, false); + for ([_][]const u8{ "\\n", "", "minimax_m3_xml", "\\n", "" }) |text| try std.testing.expect(std.mem.indexOf(u8, single, text) != null); + try std.testing.expect(std.mem.indexOf(u8, single, "\"type\":\"star\"") == null); + try std.testing.expect(std.mem.indexOf(u8, try build(a, .minimax, tools.array, true), "\"type\":\"star\"") != null); } test "a required call's grammar names every offered tool and its schema; one call without parallel" { diff --git a/zig/src/server/tool_minimax.zig b/zig/src/server/tool_minimax.zig new file mode 100644 index 00000000000..224ed475035 --- /dev/null +++ b/zig/src/server/tool_minimax.zig @@ -0,0 +1,145 @@ +//! MiniMax-M3's tool calls (`]<]minimax[>[`-prefixed XML) rewritten as DeepSeek-V4's DSML, which the parser reads. +const std = @import("std"); +const json = @import("json"); +const tool_params = @import("tool_params.zig"); +const reply_text = @import("reply_text.zig"); +const Value = json.Value; +const Allocator = std.mem.Allocator; + +pub const ns = "]<]minimax[>["; +pub const open = ns ++ ""; +pub const close = ns ++ ""; +const dsml_open = reply_text.calls[2][0]; +const dsml_close = reply_text.calls[2][1]; + +/// `text` with each complete, well-formed MiniMax call block as a DSML block typed by the tools' schemas. +pub fn dsml(a: Allocator, text: []const u8, tools: []const Value) Allocator.Error![]const u8 { + if (tools.len == 0 or std.mem.indexOf(u8, text, open) == null) return text; + const schemas = try tool_params.schemas(a, tools); + var out: std.ArrayList(u8) = .empty; + var pos: usize = 0; + while (std.mem.indexOfPos(u8, text, pos, open)) |s| { + const e = std.mem.indexOfPos(u8, text, s + open.len, close) orelse break; + try out.appendSlice(a, text[pos..s]); + if (try block(a, text[s + open.len .. e], &schemas)) |b| try out.appendSlice(a, b) else try out.appendSlice(a, text[s .. e + close.len]); + pos = e + close.len; + } + try out.appendSlice(a, text[pos..]); + return out.items; +} + +/// An element `nsinner ns` at `at` (same-named children nest): its tag, inner text and end. +const Element = struct { tag: []const u8, inner: []const u8, end: usize }; + +fn element(text: []const u8, at: usize) ?Element { + if (!std.mem.startsWith(u8, text[at..], ns ++ "<")) return null; + const t0 = at + ns.len + 1; + const gt = std.mem.indexOfScalarPos(u8, text, t0, '>') orelse return null; + const tag = text[t0..gt]; + if (tag.len == 0 or tag[0] == '/') return null; + var opener_buf: [256]u8 = undefined; + var closer_buf: [256]u8 = undefined; + const opener = std.fmt.bufPrint(&opener_buf, ns ++ "<{s}>", .{tag}) catch return null; + const closer = std.fmt.bufPrint(&closer_buf, ns ++ "", .{tag}) catch return null; + var depth: usize = 1; + var p = gt + 1; + while (true) { + const c = std.mem.indexOfPos(u8, text, p, closer) orelse return null; + const o = std.mem.indexOfPos(u8, text, p, opener); + if (o != null and o.? < c) { + depth += 1; + p = o.? + opener.len; + continue; + } + depth -= 1; + if (depth == 0) return .{ .tag = tag, .inner = text[gt + 1 .. c], .end = c + closer.len }; + p = c + closer.len; + } +} + +/// An element's value: nested `item`s an array, other nested tags an object, else a scalar by its schema. +fn value(a: Allocator, inner: []const u8, schema: tool_params.Schema) Allocator.Error!?Value { + const lead = inner.len - std.mem.trimStart(u8, inner, " \t\r\n").len; + if (!std.mem.startsWith(u8, inner[lead..], ns ++ "<")) return try tool_params.decode(a, inner, schema, false); + var items: std.ArrayList(Value) = .empty; + const obj = try json.newObject(a); + var all_items = true; + var p = lead; + while (p < inner.len) { + const rest = std.mem.trimStart(u8, inner[p..], " \t\r\n"); + p = inner.len - rest.len; + if (p == inner.len) break; + const el = element(inner, p) orelse return null; + p = el.end; + const is_item = std.mem.eql(u8, el.tag, "item"); + all_items = all_items and is_item; + const sub: Value = if (schema.value == .object) (if (is_item) schema.value.get("items") else if (schema.value.get("properties")) |props| (if (props == .object) props.get(el.tag) else null) else null) orelse .{ .object = try json.newObject(a) } else .{ .object = try json.newObject(a) }; + const v = (try value(a, el.inner, .{ .value = sub, .root = schema.root })) orelse return null; + if (is_item) try items.append(a, v); + try obj.put(a, el.tag, v); + } + return if (all_items and items.items.len > 0) .{ .array = items.items } else .{ .object = obj }; +} + +/// One block's invokes as DSML, or null when anything in it is not a well-formed invoke. +fn block(a: Allocator, body: []const u8, schemas: *const tool_params.Schemas) Allocator.Error!?[]const u8 { + const invoke = ns ++ ""; + var out: std.ArrayList(u8) = .empty; + try out.appendSlice(a, dsml_open); + var p: usize = 0; + var calls: usize = 0; + while (true) { + const rest = std.mem.trimStart(u8, body[p..], " \t\r\n"); + p = body.len - rest.len; + if (p == body.len) break; + if (!std.mem.startsWith(u8, rest, invoke)) return null; + const n0 = p + invoke.len; + const q = std.mem.indexOfPos(u8, body, n0, "\">") orelse return null; + const e = std.mem.indexOfPos(u8, body, q + 2, invoke_end) orelse return null; + const name = body[n0..q]; + try out.print(a, "\n<\u{ff5c}DSML\u{ff5c}invoke name=\"{s}\">", .{name}); + var k = q + 2; + while (true) { + const r = std.mem.trimStart(u8, body[k..e], " \t\r\n"); + k = e - r.len; + if (k == e) break; + const el = element(body[0..e], k) orelse return null; + k = el.end; + const v = (try value(a, el.inner, try tool_params.schemaOf(schemas, name, el.tag, a))) orelse return null; + if (v == .string) { + try out.print(a, "<\u{ff5c}DSML\u{ff5c}parameter name=\"{s}\" string=\"true\">{s}", .{ el.tag, v.string }); + } else { + const spelled = json.stringify(a, v, .{}) catch return error.OutOfMemory; + try out.print(a, "<\u{ff5c}DSML\u{ff5c}parameter name=\"{s}\" string=\"false\">{s}", .{ el.tag, spelled }); + } + } + try out.appendSlice(a, ""); + p = e + invoke_end.len; + calls += 1; + } + if (calls == 0) return null; + try out.appendSlice(a, "\n" ++ dsml_close); + return out.items; +} + +test "tool_minimax: the template's calls as DSML, typed by the schema, nested items as arrays" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const tools = (try json.parse(a, + \\[{"type":"function","function":{"name":"get_weather","parameters":{"type":"object","properties":{"city":{"type":"string"},"days":{"type":"integer"},"tags":{"type":"array","items":{"type":"string"}}}}}}] + )).ok; + const text = "Checking." ++ open ++ "\n" ++ ns ++ "" ++ ns ++ "Paris" ++ ns ++ "" ++ ns ++ "3" ++ ns ++ "" ++ ns ++ "" ++ ns ++ "a" ++ ns ++ "" ++ ns ++ "b" ++ ns ++ "" ++ ns ++ "" ++ ns ++ "\n" ++ close; + const got = try dsml(a, text, tools.array); + const parsed = try @import("tool_parse.zig").parse(a, got, tools.array, null); + try std.testing.expectEqualStrings("Checking.", parsed.content); + const call = parsed.calls.?[0]; + const args = (try json.parse(a, call.get("function").?.get("arguments").?.string)).ok; + try std.testing.expectEqualStrings("Paris", args.get("city").?.string); + try std.testing.expectEqualStrings("3", args.get("days").?.int); + try std.testing.expectEqualStrings("b", args.get("tags").?.array[1].string); + // a block still being written stays as written + const partial = "x" ++ open ++ ns ++ ""; + try std.testing.expectEqualStrings(partial, try dsml(a, partial, tools.array)); +} diff --git a/zig/src/tensorfold.zig b/zig/src/tensorfold.zig index 59afec13204..23655fbcbe1 100644 --- a/zig/src/tensorfold.zig +++ b/zig/src/tensorfold.zig @@ -58,6 +58,7 @@ pub const qwen35 = @import("families/qwen3_5/qwen3_5.zig"); pub const gemma4 = @import("families/gemma4/gemma4.zig"); pub const step5 = @import("families/step5/step5.zig"); pub const spark25_metal = @import("families/spark25/metal.zig"); +pub const minimax_m3 = @import("families/minimax_m3/minimax_m3.zig"); pub const lfm2_moe = @import("families/lfm2_moe/lfm2_moe.zig"); pub const flashnext_pack = @import("families/flashnext/pack.zig"); @@ -87,6 +88,7 @@ test { _ = @import("families/qwen3_5/backend.zig"); _ = @import("families/step5/step5.zig"); _ = @import("families/spark25/metal.zig"); + _ = @import("families/minimax_m3/minimax_m3.zig"); _ = @import("families/lfm2_moe/config.zig"); _ = @import("families/lfm2_moe/backend.zig"); _ = @import("families/lfm2_moe/state.zig"); diff --git a/zig/tests/contract/metal_limits.zig b/zig/tests/contract/metal_limits.zig index a8a0549b48c..796ed74d6bf 100644 --- a/zig/tests/contract/metal_limits.zig +++ b/zig/tests/contract/metal_limits.zig @@ -61,6 +61,10 @@ fn launchOf(a: std.mem.Allocator, device: mtl.Device, d: limits.MetalLaunch) !La if (std.mem.startsWith(u8, d.name, "metal lfm2 ")) return .{ .decl = d, .function = fun, .here = sources.lfm2, .pre_m5 = sources.lfm2 }; if (std.mem.startsWith(u8, d.name, "nemotron paged ")) return pagedLaunch(a, device, d, fun); if (std.mem.startsWith(u8, d.name, "nemotron attention ")) return attentionLaunch(a, device, d, fun); + if (std.mem.startsWith(u8, d.name, "minimax_m3 ")) { + const t = try @import("metal_minimax.zig").limitsText(a, device, d.name); + return .{ .decl = d, .function = fun, .here = t.here, .pre_m5 = t.pre_m5 }; + } if (std.mem.startsWith(u8, d.name, "drama3 ")) { const text_d3 = try @import("metal_drama3.zig").source(a, d.name); return .{ .decl = d, .function = fun, .here = text_d3, .pre_m5 = text_d3 }; diff --git a/zig/tests/contract/metal_main.zig b/zig/tests/contract/metal_main.zig index 2d1aab5e15b..b32e2baa9e2 100644 --- a/zig/tests/contract/metal_main.zig +++ b/zig/tests/contract/metal_main.zig @@ -19,6 +19,7 @@ const glm_eh_k = @import("metal_glm_eh.zig"); const glm_rows_k = @import("metal_glm_rows.zig"); const pair_k = @import("metal_pair.zig"); const pair_controls = @import("metal_pair_controls.zig"); +const minimax_k = @import("metal_minimax.zig"); const flash_pool = @import("metal_flashnext_pool.zig"); const flash = @import("metal_flashnext.zig"); @@ -383,6 +384,9 @@ pub fn main(init: std.process.Init) !u8 { var nemotron_unroll: @import("metal_nemotron_unroll.zig").Suite = .{ .a = a, .device = device, .queue = queue, .kernels = &kernels }; defer nemotron_unroll.deinit(); try nemotron_unroll.collect(o.only); + var minimax: minimax_k.Suite = .{ .a = a, .device = device, .queue = queue, .kernels = &kernels }; + defer minimax.deinit(); + try minimax.collect(o.only); const weight_only = @import("metal_weight_only.zig"); const weight_source = try weight_only.text(a); defer a.free(weight_source); diff --git a/zig/tests/contract/metal_minimax.zig b/zig/tests/contract/metal_minimax.zig new file mode 100644 index 00000000000..101f15acd29 --- /dev/null +++ b/zig/tests/contract/metal_minimax.zig @@ -0,0 +1,37 @@ +//! MiniMax-M3.1-Flash's Metal kernels under the contract: glue, routing, the tensor-unit kernels and the drafters. +const std = @import("std"); +const mtl = @import("metal"); +const contract = @import("contract"); + +const g = contract.gates; +const groups = .{ @import("metal_minimax_glue.zig"), @import("metal_minimax_route.zig"), @import("metal_minimax_nax.zig"), @import("metal_minimax_draft.zig") }; + +/// A launch's two texts: this GPU's and the pre-M5 one (equal unless the source includes nax.h). +pub const Texts = struct { here: []const u8, pre_m5: []const u8 }; + +pub const Suite = struct { + a: std.mem.Allocator, + device: mtl.Device, + queue: mtl.Queue, + kernels: *std.ArrayList(g.Kernel), + glue: groups[0].Suite = undefined, + route: groups[1].Suite = undefined, + nax: groups[2].Suite = undefined, + draft: groups[3].Suite = undefined, + + pub fn collect(s: *Suite, only: ?[]const u8) !void { + inline for (.{ "glue", "route", "nax", "draft" }) |f| { + @field(s, f) = .{ .a = s.a, .device = s.device, .queue = s.queue, .kernels = s.kernels }; + try @field(s, f).collect(only); + } + } + pub fn deinit(s: *Suite) void { + inline for (.{ "glue", "route", "nax", "draft" }) |f| @field(s, f).deinit(); + } +}; + +/// Gate 5's texts for a `minimax_m3 ` registration: the group whose launches it names compiles it. +pub fn limitsText(a: std.mem.Allocator, device: mtl.Device, name: []const u8) !Texts { + inline for (groups) |grp| if (try grp.limitsText(a, device, name)) |t| return t; + return error.UnknownLaunch; +} diff --git a/zig/tests/contract/metal_minimax_draft.zig b/zig/tests/contract/metal_minimax_draft.zig new file mode 100644 index 00000000000..13076c77de4 --- /dev/null +++ b/zig/tests/contract/metal_minimax_draft.zig @@ -0,0 +1,406 @@ +//! MiniMax-M3.1-Flash's drafter kernels under the contract: norms and taps here, the rest in metal_minimax_draft_*.zig. +const std = @import("std"); +const mtl = @import("metal"); +const contract = @import("contract"); +const sources = @import("kernel_sources"); +const rig_ = @import("rig.zig"); +const attn = @import("metal_minimax_draft_attn.zig"); +const pick = @import("metal_minimax_draft_pick.zig"); +const walk = @import("metal_minimax_draft_walk.zig"); +const act = @import("metal_minimax_draft_act.zig"); + +const c = contract.spec; +const g = contract.gates; +const Texts = @import("metal_minimax.zig").Texts; + +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)); +} + +/// The builds as dspark.zig, model.zig and dflash2.zig compile them: DSpark's, the target's (MLX's options), DFlash2's. +pub const Build = enum { dspark, target, dflash2 }; + +pub fn pipeline(device: mtl.Device, b: Build, name: []const u8) !mtl.Pipeline { + const text = if (b == .dflash2) sources.minimax_m3_dflash2 else sources.minimax_m3_dspark; + const opts: mtl.CompileOptions = if (b == .target) mtl.CompileOptions.mlx() else .{ .language = mtl.CompileOptions.mlx().language, .math_functions = .precise }; + const lib = try mtl.Library.fromSource(device, text, opts); + defer lib.deinit(); + return mtl.Pipeline.init(device, lib, name, false); +} + +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)); +} + +/// Gate 4's norm rows (the rows family's): 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 Suite = struct { + a: std.mem.Allocator, + device: mtl.Device, + queue: mtl.Queue, + kernels: *std.ArrayList(g.Kernel), + owned: std.ArrayList(Owned) = .empty, + + const Owned = struct { ctx: *anyopaque, free: *const fn (*anyopaque, std.mem.Allocator) void }; + + pub fn add(s: *Suite, comptime T: type, only: ?[]const u8, v: T.Variant) !void { + if (only) |o| if (std.mem.indexOf(u8, T.spec(v).name, o) == null) return; + const t = try s.a.create(T); + errdefer s.a.destroy(t); + t.* = try T.init(s.a, s.device, s.queue, v); + const free = struct { + fn f(p: *anyopaque, a: std.mem.Allocator) void { + const x: *T = @ptrCast(@alignCast(p)); + x.deinit(); + a.destroy(x); + } + }.f; + try s.owned.append(s.a, .{ .ctx = t, .free = free }); + try s.kernels.append(s.a, t.kernel()); + } + + pub fn collect(s: *Suite, only: ?[]const u8) !void { + for (std.enums.values(Norm.Variant)) |v| try s.add(Norm, only, v); + for (std.enums.values(Tap.Variant)) |v| try s.add(Tap, only, v); + try act.collect(s, only); + try attn.collect(s, only); + try pick.collect(s, only); + try walk.collect(s, only); + } + pub fn deinit(s: *Suite) void { + for (s.owned.items) |o| o.free(o.ctx, s.a); + s.owned.deinit(s.a); + } +}; + +/// Gate 5's texts: a `minimax_m3 draft ` registration compiles dflash2.metal when it names dflash2, else dspark.metal. +pub fn limitsText(a: std.mem.Allocator, device: mtl.Device, name: []const u8) !?Texts { + _ = a; + _ = device; + if (!std.mem.startsWith(u8, name, "minimax_m3 draft ")) return null; + const text = if (std.mem.indexOf(u8, name, " dflash2 ") != null) sources.minimax_m3_dflash2 else sources.minimax_m3_dspark; + return .{ .here = text, .pre_m5 = text }; +} + +// --- mm_norm16, df_norm16, df_norm: rms norms of a row, 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; +} + +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"; + +pub const Norm = struct { + /// DSpark's Gemma norm of bf16 rows; DFlash2's Qwen3 norm of bf16 or fp32 rows, or of bf16(R + X) written to R. + pub const Variant = enum { mm_norm16, df_norm16, df_norm, df_norm_add }; + a: std.mem.Allocator, + rig: rig_.Rig, + pipe: mtl.Pipeline, + v: Variant, + 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 { + // DFlash2's df_norm: the draft block's 8 rows; the bf16 norms: a context absorb's fc rows (2,048), and a few + const block: []const c.Shape = &.{.{ .rows = 8, .n = 1, .k = 6144 }}; + const context: []const c.Shape = &.{ .{ .rows = 2048, .n = 1, .k = 6144 }, .{ .rows = 7, .n = 1, .k = 6144 } }; + return .{ + .name = switch (v) { + .mm_norm16 => "minimax_m3 draft dspark mm_norm16", + .df_norm16 => "minimax_m3 draft dflash2 df_norm16", + .df_norm => "minimax_m3 draft dflash2 df_norm fp32 rows", + .df_norm_add => "minimax_m3 draft dflash2 df_norm bf16(R + X) rows", + }, + .accum = .f32, + .depth = normDepth, + // the mean's division, + eps, precise rsqrt (2), x * inv, then (1 + w) and its product, or w's product + .ops = if (v == .mm_norm16) 7 else 6, + // Qwen3's bf16(x * inv) before w's product + .mids = if (v == .mm_norm16) 0 else 1, + .out = .bf16, + .tiles = .{ .{ .size = 1 }, .{}, .{ .size = 256, .step = 1, .min = 1 } }, + .served = if (v == .df_norm or v == .df_norm_add) block else context, // n unused + .sums = .{ .bf16 = 0, .why = norm_why }, + }; + } + + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, v: Variant) !Norm { + const name = switch (v) { + .mm_norm16 => "mm_norm16", + .df_norm16 => "df_norm16", + .df_norm, .df_norm_add => "df_norm", + }; + return .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .pipe = try pipeline(device, if (v == .mm_norm16) .dspark else .dflash2, name), .v = v }; + } + 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 .{ .spec = spec(t.v), .ctx = t, .vt = &vt }; + } + const vt = g.hooks(Norm); + + fn fp32Rows(t: *const Norm) bool { + return t.v == .df_norm or t.v == .df_norm_add; + } + + 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 == .df_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 == .df_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) { + .mm_norm16, .df_norm16 => c.fromBf16(b), + .df_norm => r, + .df_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 = 1e-6, .add = @intFromBool(t.v == .df_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); + if (t.v == .mm_norm16) p.e.setValue(extern struct { rows: u32, width: u32, eps: f32 }{ .rows = args.rows, .width = args.width, .eps = args.eps }, 2) else 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(f32, 1e-6)); + } + + 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 x: f64 = t.x[r * k + i]; + const y = if (t.v == .mm_norm16) x * s * (1 + w) else w * (x * 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 }); + } +}; + +// --- mm_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 { dspark_taps, dflash2_taps }; + a: std.mem.Allocator, + rig: rig_.Rig, + pipe: mtl.Pipeline, + v: Variant, + shape: c.Shape = undefined, + r: []f32 = &.{}, + old: []u16 = &.{}, + in: rig_.Ref = undefined, + out: rig_.Ref = undefined, + + /// Rows: positions; n: the hidden width; k: the taps (DSpark 5, DFlash2 6); the other taps' slots stay put. + pub fn spec(v: Variant) c.Spec { + const taps: usize = if (v == .dspark_taps) 5 else 6; + return .{ + .name = if (v == .dspark_taps) "minimax_m3 draft target mm_tap 5 taps" else "minimax_m3 draft target mm_tap 6 taps", + .accum = .none, + .depth = noSums, + .out = .bf16, + .tiles = .{ .{ .size = 1 }, .{ .size = 256, .step = 1, .min = 1 }, .{} }, + // a decode window and a prompt chunk's rows (4,096 launch the same grid; 512 keep the float64 arrays small) + .served = if (taps == 5) &.{ .{ .rows = 8, .n = 6144, .k = 5 }, .{ .rows = 512, .n = 6144, .k = 5 } } else &.{ .{ .rows = 8, .n = 6144, .k = 6 }, .{ .rows = 512, .n = 6144, .k = 6 } }, + }; + } + + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, v: Variant) !Tap { + return .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .pipe = try pipeline(device, .target, "mm_tap"), .v = v }; + } + 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 .{ .spec = spec(t.v), .ctx = t, .vt = &vt }; + } + const vt = g.hooks(Tap); + + 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.shape = shape; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + t.r = try t.a.alloc(f32, shape.rows * shape.n); + for (t.r) |*v| v.* = (rng.float(f32) * 2 - 1) * 64; + if (fill == .nonfinite) for ([_]f32{ nan, inf, -inf }, 0..) |v, i| { + t.r[(i * 7) % t.r.len] = 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.* = if (slot == t.tap()) t.r[r * n + i % n] else c.fromBf16(t.old[i]); + m.* = 0; + } + } +}; diff --git a/zig/tests/contract/metal_minimax_draft_act.zig b/zig/tests/contract/metal_minimax_draft_act.zig new file mode 100644 index 00000000000..027ad2465c4 --- /dev/null +++ b/zig/tests/contract/metal_minimax_draft_act.zig @@ -0,0 +1,221 @@ +//! DFlash2's activation (df_silu) and grouped block convolution (df_conv) under the contract. +const std = @import("std"); +const mtl = @import("metal"); +const contract = @import("contract"); +const rig_ = @import("rig.zig"); +const d = @import("metal_minimax_draft.zig"); + +const c = contract.spec; +const g = contract.gates; +const bf = d.bf; +const noSums = d.noSums; +const pipeline = d.pipeline; +const fillBf = d.fillBf; +const nan = d.nan; +const inf = d.inf; + +pub fn collect(s: *d.Suite, only: ?[]const u8) !void { + try s.add(Silu, only, .df_silu); + for (std.enums.values(Conv.Variant)) |v| try s.add(Conv, only, v); +} + +// --- df_silu: Qwen3's SiLU of the gate times up, at its bf16 points ----------------------------------------------- + +pub const Silu = struct { + pub const Variant = enum { df_silu }; + a: std.mem.Allocator, + rig: rig_.Rig, + pipe: mtl.Pipeline, + 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 = "minimax_m3 draft dflash2 df_silu", + .accum = .none, + .depth = noSums, + // precise exp (2 ulps), the add, the division, the sigmoid's own 1 - y (1), g * s, then * up + .ops = 6, + .mids = 1, + .out = .bf16, + .tiles = .{ .{ .size = 1 }, .{ .size = 256, .step = 1, .min = 1 }, .{} }, + .served = &.{ .{ .rows = 8, .n = 12288, .k = 1 }, .{ .rows = 1, .n = 12288, .k = 1 } }, + }; + } + + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, _: Variant) !Silu { + return .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .pipe = try pipeline(device, .dflash2, "df_silu") }; + } + 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 .{ .spec = spec(.df_silu), .ctx = t, .vt = &vt }; + } + 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.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; + } + } +}; + +// --- df_conv: the grouped two-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 }; + const block = 8; + const group = 16; + a: std.mem.Allocator, + rig: rig_.Rig, + pipe: mtl.Pipeline, + v: Variant, + 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). + pub fn spec(v: Variant) c.Spec { + return .{ + .name = if (v == .side0) "minimax_m3 draft dflash2 df_conv side 0" else "minimax_m3 draft dflash2 df_conv side 1", + .accum = .none, + .depth = noSums, + .out = .bf16, + .tiles = .{ .{ .size = 8, .step = 1, .min = 1 }, .{ .size = 256, .step = 16, .min = 16 }, .{} }, + .served = &.{ .{ .rows = 8, .n = 6144, .k = 2 }, .{ .rows = 16, .n = 6144, .k = 2 } }, + }; + } + + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, v: Variant) !Conv { + return .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .pipe = try pipeline(device, .dflash2, "df_conv"), .v = v }; + } + 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 .{ .spec = spec(t.v), .ctx = t, .vt = &vt }; + } + const vt = g.hooks(Conv); + + fn groups(t: *const Conv) usize { + return t.shape.n / group; + } + fn side(t: *const Conv) usize { + return @backingInt(t.v); + } + + 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 % group != 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 * 4 * t.groups()); + t.base = try t.a.alloc(u16, 4 * 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 * 4 + t.side() * 2) * 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([5]u32{ @intCast(t.shape.rows), @intCast(t.shape.n), block, @intCast(t.groups()), @intCast(t.side()) }, 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; + } + + pub fn reference(t: *Conv, want: []f64, mag: []f64) !void { + const n = t.shape.n; + const gs = t.groups(); + const s = t.side(); + for (want, mag, 0..) |*w, *m, i| { + const r = i / n; + const ch = i % n; + const gi = ch / group; + const dyn = t.d[r * 4 * gs + s * 2 * gs ..]; + const c0 = bf(@as(f64, c.fromBf16(t.base[s * 2 * n + ch])) + c.fromBf16(dyn[gi])); + const c1 = bf(@as(f64, c.fromBf16(t.base[(s * 2 + 1) * n + ch])) + c.fromBf16(dyn[gs + gi])); + var y = bf(c0 * c.fromBf16(t.x[i])); + if (r % block >= 1) y = bf(y + bf(c1 * c.fromBf16(t.x[i - n]))); + w.* = y; + m.* = 0; + } + } +}; diff --git a/zig/tests/contract/metal_minimax_draft_attn.zig b/zig/tests/contract/metal_minimax_draft_attn.zig new file mode 100644 index 00000000000..83265187223 --- /dev/null +++ b/zig/tests/contract/metal_minimax_draft_attn.zig @@ -0,0 +1,548 @@ +//! The drafters' attention under the contract: mm_draft_prep, df_prep (norms, rotary, the ring) and mm_draft_vec. +const std = @import("std"); +const mtl = @import("metal"); +const contract = @import("contract"); +const rig_ = @import("rig.zig"); +const d = @import("metal_minimax_draft.zig"); + +const c = contract.spec; +const g = contract.gates; +const Range = d.Range; +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, only: ?[]const u8) !void { + for (std.enums.values(Prep.Variant)) |v| try s.add(Prep, only, v); + for (std.enums.values(Vec.Variant)) |v| try s.add(Vec, only, v); +} + +/// A drafter's attention geometry (dspark.zig's and dflash2.zig's Config, the checkpoint's values). +const Geo = struct { heads: u32, kv: u32, window: u32, block: u32, rotary: u32, theta: f32 }; +const dspark_geo = Geo{ .heads = 64, .kv = 4, .window = 4096, .block = 7, .rotary = 64, .theta = 1e7 }; +const dflash2_geo = Geo{ .heads = 64, .kv = 8, .window = 2048, .block = 8, .rotary = 128, .theta = 5e6 }; + +fn ring(x: Geo) u32 { + return std.mem.alignForward(u32, x.window + x.block, 128); +} + +/// 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)) }; + const k0 = @ceil(lo / std.math.pi); + var k = k0; + while (k * std.math.pi <= hi) : (k += 1) { + if (@mod(k, 2) == 0) r.hi = 1 else r.lo = -1; + } + return r; +} + +// --- mm_draft_prep, df_prep: q and k heads normed and rotated (k into the ring), v copied beside ------------------- + +pub const Prep = struct { + /// Each drafter's own: a draft block near the ring's wrap or past 257k positions, and a 2,048-row context absorb. + pub const Variant = enum { dspark_block, dspark_far, dspark_context, dflash2_block, dflash2_far, dflash2_context }; + a: std.mem.Allocator, + rig: rig_.Rig, + pipe: mtl.Pipeline, + v: Variant, + 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 dspark(v: Variant) bool { + return @backingInt(v) < 3; + } + fn geo(t: *const Prep) Geo { + return if (dspark(t.v)) dspark_geo else dflash2_geo; + } + fn heads(t: *const Prep) u32 { + return if (t.v == .dspark_context or t.v == .dflash2_context) 0 else t.geo().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) { + .dspark_block => "minimax_m3 draft dspark mm_draft_prep block", + .dspark_far => "minimax_m3 draft dspark mm_draft_prep block past 257k", + .dspark_context => "minimax_m3 draft dspark mm_draft_prep context", + .dflash2_block => "minimax_m3 draft dflash2 df_prep block", + .dflash2_far => "minimax_m3 draft dflash2 df_prep block past 257k", + .dflash2_context => "minimax_m3 draft dflash2 df_prep context", + }, + .accum = .f32, + .depth = prepDepth, + .out = .bf16, + .tiles = .{ .{ .size = 1 }, .{}, .{} }, + .served = switch (v) { + inline else => |w| comptime prepServed(w), + }, + .sums = .{ .bf16 = 0, .why = d.norm_why }, + }; + } + fn prepServed(comptime v: Variant) []const c.Shape { + const x = if (dspark(v)) dspark_geo else dflash2_geo; + const shapes: []const c.Shape = if (v == .dspark_context or v == .dflash2_context) &.{ .{ .rows = 2048, .n = x.kv, .k = 128 }, .{ .rows = 5, .n = x.kv, .k = 128 } } else &.{ .{ .rows = x.block, .n = x.heads + x.kv, .k = 128 }, .{ .rows = 1, .n = x.heads + x.kv, .k = 128 } }; + return shapes; + } + /// 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) !Prep { + const p = if (dspark(v)) try d.pipeline(device, .dspark, "mm_draft_prep") else try d.pipeline(device, .dflash2, "df_prep"); + return .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .pipe = p, .v = v }; + } + 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 .{ .spec = spec(t.v), .ctx = t, .vt = &vt }; + } + 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 + const r = ring(t.geo()); + return if (t.v == .dspark_far or t.v == .dflash2_far) 61 * r - 3 else r - 3; + } + /// X's row: q heads, then k, then v (a block); a context's kv rows hold layer 1 of 5's k and v. + fn layout(t: *const Prep) struct { stride: usize, q: usize, k: usize, v: usize } { + const kvw: usize = t.geo().kv * 128; + const qw: usize = t.heads() * 128; + return if (t.heads() == 0) .{ .stride = 5 * 2 * kvw, .q = 0, .k = 2 * kvw, .v = 3 * 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, ring(t.geo())) * t.geo().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() + t.geo().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 x = t.geo(); + 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 rows: u32 = @intCast(t.shape.rows); + if (dspark(t.v)) { + p.e.setValue(extern struct { rows: u32, heads: u32, kv_heads: u32, pos0: u32, rotary: u32, stride: u32, q_off: u32, k_off: u32, v_off: u32, ring: u32, eps: f32, theta: f32 }{ .rows = rows, .heads = t.heads(), .kv_heads = x.kv, .pos0 = t.pos0(), .rotary = x.rotary, .stride = @intCast(l.stride), .q_off = @intCast(l.q), .k_off = @intCast(l.k), .v_off = @intCast(l.v), .ring = ring(x), .eps = 1e-6, .theta = x.theta }, 3); + } else { + p.e.setValue(extern struct { rows: u32, heads: u32, kv_heads: u32, pos0: u32, stride: u32, q_off: u32, k_off: u32, v_off: u32, ring: u32, eps: f32, theta: f32 }{ .rows = rows, .heads = t.heads(), .kv_heads = x.kv, .pos0 = t.pos0(), .stride = @intCast(l.stride), .q_off = @intCast(l.q), .k_off = @intCast(l.k), .v_off = @intCast(l.v), .ring = ring(x), .eps = 1e-6, .theta = x.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) % ring(t.geo()); + return sz[0] + (slot * t.geo().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 x = t.geo(); + 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(f32, 1e-6)); + // 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); + if (x.rotary == 64) { + nrm[j] = bf(v * inv * (1 + wv)); + nr[j] = Range.point(v * inv * (1 + wv)).fp32(e_inv / u + 3).bf16(); + } else { + nrm[j] = bf(wv * bf(v * inv)); + nr[j] = Range.point(v * inv).fp32(e_inv / u + 1).bf16().mul(Range.point(wv)).bf16(); + } + } + const p: u32 = t.pos0() + @as(u32, @intCast(row)); + const half = x.rotary / 2; + for (0..128) |j| { + if (j >= x.rotary) { + want[j] = nrm[j]; + low[j] = nr[j].lo; + high[j] = nr[j].hi; + continue; + } + const i = j % half; + const e = f32r(@as(f64, @floatFromInt(2 * i)) / @as(f64, @floatFromInt(x.rotary))); + const freq = std.math.pow(f64, x.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 < half) -nrm[j + half] else nrm[j - half]; + const rr = if (j < half) nr[j + half].neg() else nr[j - half]; + 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 }); + } +}; + +// --- mm_draft_vec: a block's attention partials over 128-key blocks of the ring -------------------------------------- + +pub const Vec = struct { + /// DSpark's own build at its geometry, and the target's build at DFlash2's (dflash2.zig calls model.zig's). + pub const Variant = enum { dspark, target }; + a: std.mem.Allocator, + rig: rig_.Rig, + pipe: mtl.Pipeline, + v: Variant, + 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 geo(t: *const Vec) Geo { + return if (t.v == .dspark) dspark_geo else dflash2_geo; + } + + /// Rows: the block's positions; n: q heads; k: the window (the checkpoint's, and a short one with partial blocks). + pub fn spec(v: Variant) c.Spec { + return .{ + .name = if (v == .dspark) "minimax_m3 draft dspark mm_draft_vec 16 q heads a kv head" else "minimax_m3 draft target mm_draft_vec 8 q heads a kv head", + .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) { + .dspark => &.{ .{ .rows = dspark_geo.block, .n = dspark_geo.heads, .k = dspark_geo.window }, .{ .rows = dspark_geo.block, .n = dspark_geo.heads, .k = 300 } }, + .target => &.{ .{ .rows = dflash2_geo.block, .n = dflash2_geo.heads, .k = dflash2_geo.window }, .{ .rows = dflash2_geo.block, .n = dflash2_geo.heads, .k = 300 } }, + }, + .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) !Vec { + return .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .pipe = try d.pipeline(device, if (v == .dspark) .dspark else .target, "mm_draft_vec"), .v = v }; + } + 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 .{ .spec = spec(t.v), .ctx = t, .vt = &vt }; + } + const vt = g.hooks(Vec); + + const Plan = struct { anchor: u32, hi: u32, first: u32, blocks: u32 }; + /// The block's anchor past 61 rings, with row 0's window starting 3 keys before a 128-key block's end. + fn plan(t: *const Vec) Plan { + const w: u32 = @intCast(t.shape.k); + const lo0 = (61 * ring(t.geo()) - w) / 128 * 128 + 125; + const anchor = lo0 + w - 1; + const hi = anchor + @as(u32, @intCast(t.shape.rows)); + return .{ .anchor = anchor, .hi = hi, .first = lo0 / 128, .blocks = (hi - 1) / 128 - lo0 / 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 { + const x = t.geo(); + if (shape.rows == 0 or shape.n != x.heads or shape.k == 0 or shape.k > x.window) 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 kvn: usize = @as(usize, ring(x)) * x.kv * 128; + t.q = try t.a.alloc(u16, shape.rows * x.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 = ring(x); + // 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) * x.kv * 128 + 3] = c.toBf16(d.nan); + t.q[(1 * x.heads + 5) * 128 + 9] = c.toBf16(d.inf); + t.val[((p.hi - 1) % r) * x.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 x = t.geo(); + 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); + e.e.setValue(extern struct { rows: u32, pos0: u32, heads: u32, groups: u32, blocks: u32, first: u32, hi: u32, window: u32, ring: u32, scale: f32 }{ .rows = @intCast(t.shape.rows), .pos0 = p.anchor, .heads = x.heads, .groups = x.kv, .blocks = p.blocks, .first = p.first, .hi = p.hi, .window = @intCast(t.shape.k), .ring = ring(x), .scale = t.scale() }, 3); + for (t.outs, 4..) |o, i| e.e.setBuffer(o.buf, o.off, i); + e.e.dispatchGroups(mtl.Size.of(x.kv, t.shape.rows, p.blocks), mtl.Size.of(32, x.heads / x.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 x = t.geo(); + const p = t.plan(); + const n = t.slots(); + const r: usize = ring(x); + const G = x.heads / x.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..x.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 = if (pos + 1 > t.shape.k) pos + 1 - t.shape.k else 0; + 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) * x.kv * 128 + kv * 128; + var abs: f64 = 0; + var sum: f64 = 0; + for (0..128) |j| { + terms[j] = sc * c.fromBf16(t.q[(row * x.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) * x.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_minimax_draft_pick.zig b/zig/tests/contract/metal_minimax_draft_pick.zig new file mode 100644 index 00000000000..d3dd337f119 --- /dev/null +++ b/zig/tests/contract/metal_minimax_draft_pick.zig @@ -0,0 +1,389 @@ +//! DSpark's picks under the contract (mm_markov_step, mm_markov_pick), each by its rule; DFlash2's are in _walk.zig. +const std = @import("std"); +const mtl = @import("metal"); +const contract = @import("contract"); +const rig_ = @import("rig.zig"); +const d = @import("metal_minimax_draft.zig"); + +const c = contract.spec; +const g = contract.gates; +const bf = d.bf; +const u = c.unit(.f32); +const Sim = struct { c.Accum, g.Order }; + +pub fn collect(s: *d.Suite, only: ?[]const u8) !void { + try s.add(MarkovStep, only, .dspark); + try s.add(MarkovPick, only, .dspark); +} + +/// The lexicographic order the kernels' reductions keep: the larger value, the lower id on ties (NaN compares false). +fn before(v: f64, id: u32, w: f64, wid: u32) bool { + return v > w or (v == w and id < wid); +} + +// --- mm_markov_step: logits[step] + w2[v] . w1[prev] (w2 8-bit affine), each 256-id group's best ---------------- + +pub const MarkovStep = struct { + pub const Variant = enum { dspark }; + const prev_id = 37; + a: std.mem.Allocator, + rig: rig_.Rig, + pipe: mtl.Pipeline, + shape: c.Shape = undefined, + fill: g.Fill = .random, + l: []u16 = &.{}, + w1: []u16 = &.{}, + w2: []u32 = &.{}, + s2: []u16 = &.{}, + b2: []u16 = &.{}, + seq: [8]u32 = undefined, + ins: [6]rig_.Ref = undefined, + outs: [2]rig_.Ref = undefined, + msg: [200]u8 = undefined, + + /// Rows: the block's logits rows (the step reads row rows - 2); n: the vocabulary; k: the Markov rank. + pub fn spec(_: Variant) c.Spec { + return .{ + .name = "minimax_m3 draft dspark mm_markov_step", + .accum = .f32, + .depth = rankDepth, + .out = .f32, + .nan = .{ .stated = "each group's best follows its lane order (a NaN keeps its own place and loses where it is met); ids within near ties of the float64 scores" }, + .tiles = .{ .{}, .{ .size = 256, .step = 1, .min = 1 }, .{} }, + .served = &.{ .{ .rows = 7, .n = 1000, .k = 256 }, .{ .rows = 7, .n = 200064, .k = 256 } }, + }; + } + /// The rank's fma chain, plus the logit's add. + fn rankDepth(s: c.Shape) usize { + return s.k + 1; + } + + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, _: Variant) !MarkovStep { + return .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .pipe = try d.pipeline(device, .dspark, "mm_markov_step") }; + } + pub fn deinit(t: *MarkovStep) void { + t.free(); + t.rig.deinit(); + t.pipe.deinit(); + } + fn free(t: *MarkovStep) void { + inline for (.{ "l", "w1", "w2", "s2", "b2" }) |f| { + t.a.free(@field(t, f)); + @field(t, f) = &.{}; + } + } + pub fn kernel(t: *MarkovStep) g.Kernel { + return .{ .spec = spec(.dspark), .ctx = t, .vt = &vt }; + } + const vt = g.hooks(MarkovStep); + + fn groups(t: *const MarkovStep) usize { + return (t.shape.n + 255) / 256; + } + fn step(t: *const MarkovStep) usize { + return t.shape.rows - 2; + } + + pub fn prepare(t: *MarkovStep, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.rows < 2 or shape.rows > 8 or shape.n == 0 or shape.k != 256) 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 v = shape.n; + const k = shape.k; + t.l = try t.a.alloc(u16, shape.rows * v); + t.w1 = try t.a.alloc(u16, (prev_id + 1) * k); + t.w2 = try t.a.alloc(u32, v * k / 4); + t.s2 = try t.a.alloc(u16, v * k / 64); + t.b2 = try t.a.alloc(u16, v * k / 64); + d.fillBf(rng, t.l, -8, 8); + d.fillBf(rng, t.w1, -1, 1); + for (t.w2) |*w| w.* = rng.int(u32); + d.fillBf(rng, t.s2, 0.001, 0.02); + d.fillBf(rng, t.b2, -1.5, 1.5); + if (fill == .stress) { + // q - 128 exactly, w1 integers mirrored about the middle: fp32 sums exact, scores small, bf16 sums wrong + @memset(t.s2, c.toBf16(1)); + @memset(t.b2, c.toBf16(-128)); + const e = t.w1[prev_id * k ..][0..k]; + for (0..k / 2) |r| { + const x: f32 = @floatFromInt(64 + rng.uintLessThan(u32, 64)); + e[r] = c.toBf16(x); + e[k / 2 + r] = c.toBf16(-x + (if (r < 3) @as(f32, @floatFromInt(rng.uintLessThan(u32, 3))) - 1 else 0)); + } + for (0..v) |id| for (0..k / 8) |j| { + t.w2[id * k / 4 + k / 8 + j] = t.w2[id * k / 4 + j]; // the second half's codes repeat the first's + }; + for (t.l) |*x| x.* = c.toBf16(@floatFromInt(rng.uintLessThan(u32, 64))); + } + if (fill == .nonfinite) for ([_]f32{ d.nan, d.inf, -d.inf, d.nan }, [_]usize{ 3, 300, 517, 1000 }) |x, id| { + if (id < v) t.l[t.step() * v + id] = c.toBf16(x); + }; + @memset(&t.seq, 0); + t.seq[t.step()] = prev_id; + t.ins[0] = try t.rig.input(std.mem.sliceAsBytes(t.l)); + t.ins[1] = try t.rig.input(std.mem.sliceAsBytes(t.w1)); + t.ins[2] = try t.rig.input(std.mem.sliceAsBytes(t.w2)); + t.ins[3] = try t.rig.input(std.mem.sliceAsBytes(t.s2)); + t.ins[4] = try t.rig.input(std.mem.sliceAsBytes(t.b2)); + t.ins[5] = try t.rig.input(std.mem.sliceAsBytes(&t.seq)); + t.outs[0] = try t.rig.output(t.groups() * 4); + t.outs[1] = try t.rig.output(t.groups() * 4); + return true; + } + + pub fn run(t: *MarkovStep) !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([3]u32{ @intCast(t.shape.n), @intCast(t.shape.k), @intCast(t.step()) }, 6); + p.e.setBuffer(t.outs[0].buf, t.outs[0].off, 7); + p.e.setBuffer(t.outs[1].buf, t.outs[1].off, 8); + p.e.dispatchGroups(mtl.Size.of(t.groups(), 1, 1), mtl.Size.of(256, 1, 1)); + try t.rig.finish(p); + } + + pub fn count(t: *MarkovStep) usize { + return 2 * t.groups(); + } + + /// Id v's float64 score and its bound (`sim`: the rank's sum in that accumulator and order instead). + fn score(t: *const MarkovStep, v: usize, sim: ?Sim) struct { f64, f64 } { + const k = t.shape.k; + var terms: [256]f64 = undefined; + var abs: f64 = 0; + var sum: f64 = 0; + var spread: f64 = 0; + for (0..k) |r| { + const sv: f64 = c.fromBf16(t.s2[v * k / 64 + r / 64]); + const bv: f64 = c.fromBf16(t.b2[v * k / 64 + r / 64]); + const q: f64 = @floatFromInt((t.w2[v * k / 4 + r / 4] >> @intCast(8 * (r % 4))) & 0xff); + const e: f64 = c.fromBf16(t.w1[prev_id * k + r]); + // bf16(s q + b) from an fp32 product and add (or one fma): either rounding's bf16 + const lo = bf(d.f32r(d.f32r(sv * q) + bv)); + const hi = bf(sv * q + bv); + terms[r] = lo * e; + sum += terms[r]; + abs += @abs(terms[r]); + spread += @abs(hi - lo) * @abs(e); + } + const logit: f64 = c.fromBf16(t.l[t.step() * t.shape.n + v]); + const s = if (sim) |o| contract.rows.sumIn(o[0], o[1], &terms) else sum; + const exact = t.fill == .stress and sim == null; + return .{ logit + s, if (exact) 0 else c.gamma(@floatFromInt(k + 1), u) * (@abs(logit) + abs) + spread }; + } + + const Pick = struct { v: f64, id: u32 }; + /// A group's pick by the kernel's own order: each simdgroup's xor butterfly, then thread 0 over the 8 parts. + fn replay(scores: []const f64, base: usize, n: usize) Pick { + var parts: [8]Pick = undefined; + for (&parts, 0..) |*part, sg| { + var lane: [32]Pick = undefined; + for (&lane, 0..) |*l, i| { + const v = base + sg * 32 + i; + l.* = .{ .v = if (v < n) scores[v - base] else -std.math.inf(f64), .id = @intCast(v) }; + } + var dist: usize = 16; + while (dist > 0) : (dist /= 2) { + const old = lane; + for (&lane, 0..) |*l, i| { + const o = old[i ^ dist]; + if (before(o.v, o.id, l.v, l.id)) l.* = o; + } + } + part.* = lane[0]; + } + var b = parts[0]; + for (parts[1..]) |p| if (before(p.v, p.id, b.v, b.id)) { + b = p; + }; + return b; + } + + fn groupScores(t: *const MarkovStep, gi: usize, sim: ?Sim, scores: *[256]f64, bnd: *[256]f64) void { + for (0..256) |i| { + const v = gi * 256 + i; + if (v >= t.shape.n) break; + scores[i], bnd[i] = t.score(v, sim); + } + } + + fn outputs(t: *MarkovStep, out: []f64, allow: ?[]f64, sim: ?Sim) void { + const ng = t.groups(); + var scores: [256]f64 = undefined; + var bnd: [256]f64 = undefined; + for (0..ng) |gi| { + t.groupScores(gi, sim, &scores, &bnd); + const p = replay(&scores, gi * 256, t.shape.n); + out[gi] = p.v; + out[ng + gi] = @as(f32, @bitCast(p.id)); + if (allow) |al| { + al[gi] = bnd[p.id - gi * 256] + 0x1p-149; + al[ng + gi] = 0; + } + } + } + + pub fn reference(t: *MarkovStep, want: []f64, mag: []f64) !void { + t.outputs(want, null, null); + @memset(mag, 0); + } + pub fn bounds(t: *MarkovStep, _: []const f64, _: []const f64, allow: []f64) !void { + const want = try t.a.alloc(f64, t.count()); + defer t.a.free(want); + t.outputs(want, allow, null); + } + pub fn simulate(t: *MarkovStep, acc: c.Accum, order: g.Order, out: []f64) !void { + t.outputs(out, null, .{ acc, order }); + } + + /// Each group's best: its id in the group, its value within its id's bound, and the replay's pick or a near tie. + pub fn check(t: *MarkovStep, _: g.Gate) !?[]const u8 { + const ng = t.groups(); + const best = std.mem.bytesAsSlice(f32, t.rig.bytes(t.outs[0], ng * 4)); + const ids = std.mem.bytesAsSlice(u32, t.rig.bytes(t.outs[1], ng * 4)); + var scores: [256]f64 = undefined; + var bnd: [256]f64 = undefined; + for (0..ng) |gi| { + t.groupScores(gi, null, &scores, &bnd); + const want = replay(&scores, gi * 256, t.shape.n); + const id = ids[gi]; + if (id < gi * 256 or id >= @min(gi * 256 + 256, t.shape.n)) return try std.fmt.bufPrint(&t.msg, "group {d}'s best id {d} is outside it", .{ gi, id }); + const at = id - gi * 256; + const w = want.id - gi * 256; + const got: f64 = best[gi]; + if (std.math.isNan(want.v) or std.math.isNan(got) or std.math.isInf(want.v) or id == want.id) { + if (id != want.id or c.classOf(got) != c.classOf(want.v)) return try std.fmt.bufPrint(&t.msg, "group {d} picks {d} ({d}) where the replay picks {d} ({d})", .{ gi, id, got, want.id, want.v }); + } else if (!(scores[at] >= scores[w] - bnd[at] - bnd[w])) return try std.fmt.bufPrint(&t.msg, "group {d} picks {d} ({d}), not within a near tie of {d} ({d})", .{ gi, id, scores[at], want.id, want.v }); + if (std.math.isFinite(got) and !(@abs(got - scores[at]) <= bnd[at] + 0x1p-149)) return try std.fmt.bufPrint(&t.msg, "group {d}'s best {d} is off its id's score {d}", .{ gi, got, scores[at] }); + } + return null; + } +}; + +// --- mm_markov_pick: the best of every group's best into seq[step + 1], bit for bit ------------------------------- + +pub const MarkovPick = struct { + pub const Variant = enum { dspark }; + a: std.mem.Allocator, + rig: rig_.Rig, + pipe: mtl.Pipeline, + n: usize = 0, + best: []f32 = &.{}, + ids: []u32 = &.{}, + old: [16]u32 = undefined, + ins: [2]rig_.Ref = undefined, + out: rig_.Ref = undefined, + msg: [200]u8 = undefined, + const at = 5; + + /// Rows unused; n: the groups (782 for the vocabulary, and edges about 1,024 threads). + pub fn spec(_: Variant) c.Spec { + return .{ + .name = "minimax_m3 draft dspark mm_markov_pick", + .accum = .none, + .depth = d.noSums, + .out = .raw, + .nan = .{ .stated = "the 1,024 threads' strided bests, then their xor butterflies, as Metal compares (a NaN compares false), replayed on the host bit for bit" }, + .tiles = .{ .{}, .{ .size = 1024, .step = 1, .min = 1 }, .{} }, + .served = &.{ .{ .rows = 1, .n = 782, .k = 1 }, .{ .rows = 1, .n = 4, .k = 1 } }, + }; + } + + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, _: Variant) !MarkovPick { + return .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .pipe = try d.pipeline(device, .dspark, "mm_markov_pick") }; + } + pub fn deinit(t: *MarkovPick) void { + t.a.free(t.best); + t.a.free(t.ids); + t.rig.deinit(); + t.pipe.deinit(); + } + pub fn kernel(t: *MarkovPick) g.Kernel { + return .{ .spec = spec(.dspark), .ctx = t, .vt = &vt }; + } + const vt = g.hooks(MarkovPick); + + pub fn prepare(t: *MarkovPick, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.n == 0) return false; + t.rig.reset(); + t.a.free(t.best); + t.a.free(t.ids); + t.n = shape.n; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + t.best = try t.a.alloc(f32, shape.n); + t.ids = try t.a.alloc(u32, shape.n); + // coarse values, so ties between groups occur and the lower id must win + for (t.best, t.ids, 0..) |*b, *i, k| { + b.* = @floatFromInt(rng.uintLessThan(u32, 40)); + i.* = @intCast(k * 256 + rng.uintLessThan(u32, 256)); + } + if (fill == .nonfinite) for ([_]f32{ d.nan, d.inf, -d.inf }, [_]usize{ 0, 2, 3 }) |v, k| { + if (k < shape.n) t.best[k] = v; + }; + for (&t.old) |*o| o.* = rng.int(u32); + t.ins[0] = try t.rig.input(std.mem.sliceAsBytes(t.best)); + t.ins[1] = try t.rig.input(std.mem.sliceAsBytes(t.ids)); + t.out = try t.rig.output(t.old.len * 4); + return true; + } + + pub fn run(t: *MarkovPick) !void { + @memcpy(t.rig.bytes(t.out, t.old.len * 4), std.mem.sliceAsBytes(&t.old)); + 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([2]u32{ @intCast(t.n), at }, 2); + p.e.setBuffer(t.out.buf, t.out.off, 3); + p.e.dispatchGroups(mtl.Size.of(1, 1, 1), mtl.Size.of(1024, 1, 1)); + try t.rig.finish(p); + } + + pub fn count(t: *MarkovPick) usize { + return t.old.len * 4; + } + pub fn reference(_: *MarkovPick, _: []f64, _: []f64) !void { + return error.CheckedByItsOwnRule; + } + + const P = struct { v: f32, id: u32 }; + fn better(o: P, b: P) bool { + return o.v > b.v or (o.v == b.v and o.id < b.id); + } + fn butterfly(lane: *[32]P) void { + var dist: usize = 16; + while (dist > 0) : (dist /= 2) { + const old = lane.*; + for (lane, 0..) |*l, i| if (better(old[i ^ dist], l.*)) { + l.* = old[i ^ dist]; + }; + } + } + + pub fn check(t: *MarkovPick, _: g.Gate) !?[]const u8 { + var th: [1024]P = undefined; + for (&th, 0..) |*x, i| { + x.* = .{ .v = -std.math.inf(f32), .id = 0xffffffff }; + var k = i; + while (k < t.n) : (k += 1024) { + if (better(.{ .v = t.best[k], .id = t.ids[k] }, x.*)) x.* = .{ .v = t.best[k], .id = t.ids[k] }; + } + } + var firsts: [32]P = undefined; + for (0..32) |sg| { + butterfly(th[sg * 32 ..][0..32]); + firsts[sg] = th[sg * 32]; + } + butterfly(&firsts); + var want = t.old; + want[at + 1] = firsts[0].id; + const got = t.rig.bytes(t.out, t.count()); + if (!std.mem.eql(u8, got, std.mem.sliceAsBytes(&want))) return try std.fmt.bufPrint(&t.msg, "seq differs from the host's replay ({d} groups): {d} where it picks {d}", .{ t.n, std.mem.bytesAsSlice(u32, got)[at + 1], want[at + 1] }); + return null; + } +}; diff --git a/zig/tests/contract/metal_minimax_draft_walk.zig b/zig/tests/contract/metal_minimax_draft_walk.zig new file mode 100644 index 00000000000..95c1ac0582a --- /dev/null +++ b/zig/tests/contract/metal_minimax_draft_walk.zig @@ -0,0 +1,372 @@ +//! DFlash2's picks under the contract: the chunked top-k (df_topk) and the greedy walk (df_walk), each by its rule. +const std = @import("std"); +const mtl = @import("metal"); +const contract = @import("contract"); +const rig_ = @import("rig.zig"); +const d = @import("metal_minimax_draft.zig"); + +const c = contract.spec; +const g = contract.gates; +const bf = d.bf; +const u = c.unit(.f32); +const Sim = struct { c.Accum, g.Order }; + +pub fn collect(s: *d.Suite, only: ?[]const u8) !void { + for (std.enums.values(TopK.Variant)) |v| try s.add(TopK, only, v); + try s.add(Walk, only, .dflash2); +} + +// --- 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, + shape: c.Shape = undefined, + fill: g.Fill = .random, + 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 => "minimax_m3 draft dflash2 df_topk logits", + .bests => "minimax_m3 draft dflash2 df_topk 98 chunks' bests", + .last => "minimax_m3 draft dflash2 df_topk 2 chunks' bests", + }, + .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 = 7, .n = 200064, .k = 1 }}, + .bests => &.{.{ .rows = 7, .n = 98 * 32, .k = 1 }}, + .last => &.{.{ .rows = 7, .n = 64, .k = 1 }}, + }, + }; + } + + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, v: Variant) !TopK { + return .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .pipe = try d.pipeline(device, .dflash2, "df_topk"), .v = v }; + } + 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 .{ .spec = spec(t.v), .ctx = t, .vt = &vt }; + } + 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; + t.fill = fill; + 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 % 200064); + 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; + } +}; + +// --- df_walk: the selector's greedy path through each slot's top candidates ----------------------------------- + +pub const Walk = struct { + pub const Variant = enum { dflash2 }; + /// The vocabulary only bounds ids (and clamps B's row); 8,192 rows keep A and B small. + const vocab = 8192; + const top = 32; + a: std.mem.Allocator, + rig: rig_.Rig, + pipe: mtl.Pipeline, + shape: c.Shape = undefined, + fill: g.Fill = .random, + uv: []f32 = &.{}, + ui: []u32 = &.{}, + h: []u16 = &.{}, + pa: []u16 = &.{}, + pb: []u16 = &.{}, + seq: [8]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 = "minimax_m3 draft dflash2 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 = 7, .n = top, .k = 256 }, .{ .rows = 1, .n = top, .k = 256 } }, + }; + } + /// 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) !Walk { + return .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .pipe = try d.pipeline(device, .dflash2, "df_walk") }; + } + 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 .{ .spec = spec(.dflash2), .ctx = t, .vt = &vt }; + } + 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 > 7 or shape.n != top or shape.k != 256) 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 candidate scores after `prev` in float64 (or with the rank's sum simulated) and their bounds. + 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: [257]f64 = undefined; + for (0..top) |cnd| { + const id = t.ui[e * top + cnd]; + const row = @min(id, vocab - 1); + var abs: f64 = @abs(t.uv[e * top + cnd]); + var sum: f64 = t.uv[e * top + cnd]; + terms[k] = t.uv[e * top + cnd]; + 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]); + } + out[cnd] = if (sim) |o| contract.rows.sumIn(o[0], o[1], terms[0 .. k + 1]) else sum; + bnd[cnd] = if (t.fill == .stress or sim != null) 0 else c.gamma(15, u) * abs; + } + } + + /// 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) [8]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; + } +}; diff --git a/zig/tests/contract/metal_minimax_glue.zig b/zig/tests/contract/metal_minimax_glue.zig new file mode 100644 index 00000000000..9ffc8165abd --- /dev/null +++ b/zig/tests/contract/metal_minimax_glue.zig @@ -0,0 +1,569 @@ +//! MiniMax-M3.1-Flash's glue under the contract: embedding, SwiGLU-OAI, argmax and the tower's copies (adds: _rows). +const std = @import("std"); +const mtl = @import("metal"); +const contract = @import("contract"); +const sources = @import("kernel_sources"); +const rig_ = @import("rig.zig"); +const rows_k = @import("metal_minimax_glue_rows.zig"); + +const c = contract.spec; +const g = contract.gates; +const Texts = @import("metal_minimax.zig").Texts; + +pub const source = sources.minimax_m3_glue; + +/// MiniMax-M3.1-Flash's served widths (its config): the residual, the experts' and the dense layers' SwiGLU, the tower. +pub const hidden = 6144; +pub const moe_inter = 3072; +pub const dense_inter = 12288; +pub const topk = 4; +pub const vocab = 200064; +pub const tower = 1280; + +/// glue.metal's argument block (forward.zig's Args). +pub const MArgs = extern struct { rows: u32 = 0, width: u32 = 0, heads: u32 = 0, dim: u32 = 0, pos: u32 = 0, stride: u32 = 0, bits: u32 = 0, group: u32 = 0, eps: f32 = 0, alpha: f32 = 0, limit: f32 = 0, scale: f32 = 0 }; + +pub fn noSums(_: c.Shape) usize { + return 0; +} + +/// A value as fp32 then bf16 rounds it (to nearest even, twice): an fp32 step on exact inputs, then the bf16 point. +pub fn bf(v: f64) f64 { + return c.fromBf16(c.toBf16(@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 `e` either way. + pub fn widen(a: Range, e: f64) Range { + return .{ .lo = a.lo - e, .hi = a.hi + e }; + } + pub fn bf16(a: Range) Range { + return .{ .lo = bf(a.lo), .hi = bf(a.hi) }; + } + /// Times an exact value of either sign. + pub fn times(a: Range, v: f64) Range { + return .{ .lo = @min(a.lo * v, a.hi * v), .hi = @max(a.lo * v, a.hi * v) }; + } +}; + +/// 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)); +} + +/// One of glue.metal's kernels, compiled as model.zig compiles it (MLX's language, precise math functions). +pub fn pipeline(device: mtl.Device, name: []const u8) !mtl.Pipeline { + const lib = try mtl.Library.fromSource(device, source, .{ .language = mtl.CompileOptions.mlx().language, .math_functions = .precise }); + defer lib.deinit(); + return mtl.Pipeline.init(device, lib, name, false); +} + +pub const planted = [_]f32{ std.math.nan(f32), std.math.inf(f32), -std.math.inf(f32) }; + +// --- mm_embed: an 8-bit affine row, bf16(scale * q + bias) held in fp32 ------------------------------------------- + +/// Table rows the test's ids index (the gates need distinct rows, not a 200k vocabulary). +const table = 48; +const ebits = 8; +const egroup = 64; + +pub const Embed = struct { + a: std.mem.Allocator, + rig: rig_.Rig, + pipe: mtl.Pipeline, + shape: c.Shape = undefined, + ids: []u32 = &.{}, + words: []u32 = &.{}, + s: []u16 = &.{}, + b: []u16 = &.{}, + ins: [4]rig_.Ref = undefined, + out: rig_.Ref = undefined, + + /// Rows: tokens; n: the hidden width (k unused). The embedding is the checkpoint's 8-bit groups of 64. + pub fn spec() c.Spec { + return .{ + .name = "metal minimax_m3 glue mm_embed q8 g64", + .accum = .none, + .depth = noSums, + .out = .f32, + .tiles = .{ .{}, .{ .size = 256, .step = 64, .min = 64 }, .{} }, + .served = &.{ .{ .rows = 32, .n = hidden, .k = 1 }, .{ .rows = 4096, .n = hidden, .k = 1 }, .{ .rows = 1, .n = hidden, .k = 1 } }, + }; + } + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue) !Embed { + return .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .pipe = try pipeline(device, "mm_embed") }; + } + pub fn deinit(t: *Embed) void { + t.free(); + t.rig.deinit(); + t.pipe.deinit(); + } + fn free(t: *Embed) void { + inline for (.{ "ids", "words", "s", "b" }) |f| { + t.a.free(@field(t, f)); + @field(t, f) = &.{}; + } + } + pub fn kernel(t: *Embed) g.Kernel { + return .{ .spec = spec(), .ctx = t, .vt = &vt }; + } + 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.n == 0 or shape.n % egroup != 0) return false; + t.rig.reset(); + t.free(); + t.shape = shape; + const n = shape.n; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + t.ids = try t.a.alloc(u32, shape.rows); + for (t.ids, 0..) |*v, r| v.* = if (r < 4) @intCast(r) else rng.uintLessThan(u32, table); + t.words = try t.a.alloc(u32, table * n / 4); + for (t.words) |*v| v.* = rng.int(u32); + t.s = try t.a.alloc(u16, table * n / egroup); + t.b = try t.a.alloc(u16, table * n / egroup); + // MLX's affine groups: a positive scale, the bias the group's least value + for (t.s, t.b) |*s, *b| { + const sc = 0.001 + rng.float(f32) * 0.02; + s.* = c.toBf16(sc); + b.* = c.toBf16(-sc * (rng.float(f32) * 255)); + } + if (fill == .nonfinite) { + const gpr = n / egroup; + t.s[0 * gpr] = c.toBf16(planted[0]); + t.b[1 * gpr] = c.toBf16(planted[1]); + t.b[2 * gpr] = c.toBf16(planted[2]); + t.s[3 * gpr] = c.toBf16(planted[1]); + if (gpr > 1) t.b[3 * gpr + 1] = c.toBf16(planted[2]); + } + t.ins[0] = try t.rig.input(std.mem.sliceAsBytes(t.ids)); + t.ins[1] = try t.rig.input(std.mem.sliceAsBytes(t.words)); + t.ins[2] = try t.rig.input(std.mem.sliceAsBytes(t.s)); + t.ins[3] = try t.rig.input(std.mem.sliceAsBytes(t.b)); + t.out = try t.rig.output(shape.rows * n * 4); + return true; + } + + pub fn run(t: *Embed) !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(MArgs{ .rows = @intCast(t.shape.rows), .width = @intCast(t.shape.n), .bits = ebits, .group = egroup }, 4); + p.e.setBuffer(t.out.buf, t.out.off, 5); + 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; + } + + /// Element (r, j)'s scale times its code, and its bias. + fn parts(t: *Embed, r: usize, j: usize) [2]f64 { + const n = t.shape.n; + const row = t.ids[r]; + const q: f64 = @floatFromInt((t.words[(row * n + j) / 4] >> @intCast((j % 4) * 8)) & 0xff); + const gi = row * (n / egroup) + j / egroup; + return .{ @as(f64, c.fromBf16(t.s[gi])) * q, c.fromBf16(t.b[gi]) }; + } + + pub fn reference(t: *Embed, want: []f64, mag: []f64) !void { + for (want, mag, 0..) |*w, *m, i| { + const p = t.parts(i / t.shape.n, i % t.shape.n); + w.* = bf(p[0] + p[1]); + m.* = 0; + } + } + + /// The scale-and-add in fp32 (fused or not, the compiler's choice): two roundings at most, then the bf16 point. + pub fn intervals(t: *Embed, low: []f64, high: []f64) !void { + for (low, high, 0..) |*l, *h, i| { + const p = t.parts(i / t.shape.n, i % t.shape.n); + const e = c.unit(.f32) * (@abs(p[0]) + 2 * @abs(p[0] + p[1])) + 0x1p-149; + const r = Range.point(p[0] + p[1]).widen(e).bf16(); + l.* = r.lo; + h.* = r.hi; + } + } + + pub fn bounds(t: *Embed, 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)) spread(w, .{ .lo = lo, .hi = hi }) else 0; + } +}; + +// --- mm_swiglu: SwiGLU-OAI in bf16 steps, (clamp(up) + 1) * g * sigmoid(g * alpha), g = min(gate, limit) ----------- + +const alpha: f32 = 1.702; +const limit: f32 = 7.0; +const u32_ulp = 0x1p-24; + +fn sigmoid(x: f64) f64 { + return 1 / (1 + @exp(-x)); +} + +/// mm_sigmoid's fp32 error: 1 / (1 + exp(-|x|)) within 8 ulps; below zero exp(-|x|) (4) times that, rounded (1). +fn sigmoidRange(x: f64) Range { + const s = sigmoid(x); + const e = @as(f64, if (x >= 0) 8 else 13) * u32_ulp * s; + return .{ .lo = @max(0, s - e), .hi = s + e }; +} + +/// torch's clamp: NaN stays NaN. +fn clampNan(v: f64, lo: f64, hi: f64) f64 { + return if (std.math.isNan(v)) v else std.math.clamp(v, lo, hi); +} + +pub const Swiglu = struct { + a: std.mem.Allocator, + rig: rig_.Rig, + pipe: mtl.Pipeline, + shape: c.Shape = undefined, + gu: []u16 = &.{}, + in: rig_.Ref = undefined, + out: rig_.Ref = undefined, + + /// Rows: slots or tokens; n: the SwiGLU width (gate|up rows twice as wide). + pub fn spec() c.Spec { + return .{ + .name = "metal minimax_m3 glue mm_swiglu (SwiGLU-OAI, alpha 1.702, limit 7)", + .accum = .none, + .depth = noSums, + .out = .bf16, + .tiles = .{ .{}, .{ .size = 256, .step = 1, .min = 1 }, .{} }, + // a window's 32 x 4 expert slots, a prompt chunk's 4,096 x 4, the shared expert's and dense layers' rows + .served = &.{ .{ .rows = 128, .n = moe_inter, .k = 1 }, .{ .rows = 16384, .n = moe_inter, .k = 1 }, .{ .rows = 32, .n = dense_inter, .k = 1 }, .{ .rows = 1, .n = moe_inter, .k = 1 } }, + }; + } + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue) !Swiglu { + return .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .pipe = try pipeline(device, "mm_swiglu") }; + } + pub fn deinit(t: *Swiglu) void { + t.a.free(t.gu); + t.rig.deinit(); + t.pipe.deinit(); + } + pub fn kernel(t: *Swiglu) g.Kernel { + return .{ .spec = spec(), .ctx = t, .vt = &vt }; + } + const vt = g.hooks(Swiglu); + + pub fn prepare(t: *Swiglu, 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.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 the limit and deep into the sigmoid's tail, ups past the clamp on both sides + for (0..shape.rows) |r| { + for (t.gu[r * 2 * n ..][0..n]) |*v| v.* = c.toBf16(rng.float(f32) * 48 - 32); + for (t.gu[r * 2 * n + n ..][0..n]) |*v| v.* = c.toBf16(rng.float(f32) * 20 - 10); + } + if (fill == .nonfinite) for (0..@min(shape.rows, 6)) |r| { + const at = r * 2 * n + (if (r < 3) 0 else n) + (r * 7) % n; + t.gu[at] = c.toBf16(planted[r % 3]); + }; + 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: *Swiglu) !void { + const n: u32 = @intCast(t.shape.n); + const p = t.rig.begin(); + p.e.setPipeline(t.pipe); + p.e.setBuffer(t.in.buf, t.in.off, 0); + p.e.setValue(MArgs{ .rows = @intCast(t.shape.rows), .width = n, .stride = 2 * n, .alpha = alpha, .limit = limit }, 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: *Swiglu) usize { + return t.shape.rows * t.shape.n; + } + + /// Output i's clamped gate, bf16(alpha g), and bf16(clamp(up) + 1). + fn parts(t: *Swiglu, i: usize) [3]f64 { + const n = t.shape.n; + const r = i / n; + const j = i % n; + const gate: f64 = c.fromBf16(t.gu[r * 2 * n + j]); + const up: f64 = c.fromBf16(t.gu[r * 2 * n + n + j]); + const gl = if (std.math.isNan(gate)) gate else @min(gate, limit); + return .{ gl, bf(gl * alpha), bf(clampNan(up, -limit, limit) + 1) }; + } + + pub fn reference(t: *Swiglu, want: []f64, mag: []f64) !void { + for (want, mag, 0..) |*w, *m, i| { + const p = t.parts(i); + w.* = bf(p[2] * bf(p[0] * bf(sigmoid(p[1])))); + m.* = 0; + } + } + + pub fn intervals(t: *Swiglu, low: []f64, high: []f64) !void { + for (low, high, 0..) |*l, *h, i| { + const p = t.parts(i); + const r = sigmoidRange(p[1]).bf16().times(p[0]).bf16().times(p[2]).bf16(); + l.* = r.lo; + h.* = r.hi; + } + } + + pub fn bounds(t: *Swiglu, 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)) spread(w, .{ .lo = lo, .hi = hi }) else 0; + } +}; + +// --- mm_widen and mm_narrow: the tower's copies between bf16 and fp32 rows ----------------------------------------- + +pub const Copy = struct { + a: std.mem.Allocator, + rig: rig_.Rig, + pipe: mtl.Pipeline, + narrow: bool, + total: usize = 0, + x: []u8 = &.{}, + in: rig_.Ref = undefined, + out: rig_.Ref = undefined, + + /// Rows: the tower's patches (2,304 at most) or an image's rows; n: their width. The kernel sees rows * n values. + pub fn spec(narrow: bool) c.Spec { + return .{ + .name = if (narrow) "metal minimax_m3 glue mm_narrow fp32 to bf16" else "metal minimax_m3 glue mm_widen bf16 to fp32", + .accum = .none, + .depth = noSums, + .out = if (narrow) .bf16 else .f32, + .tiles = .{ .{}, .{ .size = 256, .step = 1, .min = 1 }, .{} }, + .served = &.{ .{ .rows = 16, .n = tower, .k = 1 }, .{ .rows = 2304, .n = tower, .k = 1 }, .{ .rows = 576, .n = hidden, .k = 1 } }, + }; + } + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, narrow: bool) !Copy { + return .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .pipe = try pipeline(device, if (narrow) "mm_narrow" else "mm_widen"), .narrow = narrow }; + } + pub fn deinit(t: *Copy) void { + t.a.free(t.x); + t.rig.deinit(); + t.pipe.deinit(); + } + pub fn kernel(t: *Copy) g.Kernel { + return .{ .spec = spec(t.narrow), .ctx = t, .vt = &vt }; + } + const vt = g.hooks(Copy); + + pub fn prepare(t: *Copy, 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.x); + t.total = shape.rows * shape.n; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + if (t.narrow) { + const x = try t.a.alloc(f32, t.total); + // full fp32 mantissas and round-to-even halves; normal values only (Apple GPUs flush fp32 subnormals) + for (x, 0..) |*v, i| v.* = if (i % 5 == 0) c.fromBf16((rng.int(u16) & 0x477f) | 0x0080) * (1 + 0x1p-8) else (rng.float(f32) * 2 - 1) * 64; + if (fill == .nonfinite) for (planted, 0..) |v, i| { + x[i * 3 % t.total] = v; + }; + t.x = std.mem.sliceAsBytes(x); + } else { + const x = try t.a.alloc(u16, t.total); + for (x) |*v| v.* = rng.int(u16); + for (x) |*v| if (std.math.isNan(c.fromBf16(v.*)) or std.math.isInf(c.fromBf16(v.*))) { + v.* = 0x3f80; + }; + if (fill == .nonfinite) for (planted, 0..) |v, i| { + x[i * 3 % t.total] = c.toBf16(v); + }; + t.x = std.mem.sliceAsBytes(x); + } + t.in = try t.rig.input(t.x); + t.out = try t.rig.output(t.total * @as(usize, if (t.narrow) 2 else 4)); + return true; + } + + pub fn run(t: *Copy) !void { + const p = t.rig.begin(); + p.e.setPipeline(t.pipe); + p.e.setBuffer(t.in.buf, t.in.off, 0); + p.e.setBuffer(t.out.buf, t.out.off, 1); + p.e.setValue(@as(u32, @intCast(t.total)), 2); + p.e.dispatchThreads(mtl.Size.of(t.total, 1, 1), mtl.Size.of(256, 1, 1)); + try t.rig.finish(p); + } + + pub fn count(t: *Copy) usize { + return t.total; + } + + pub fn reference(t: *Copy, want: []f64, mag: []f64) !void { + for (want, mag, 0..) |*w, *m, i| { + w.* = if (t.narrow) bf(std.mem.bytesAsSlice(f32, t.x)[i]) else c.fromBf16(std.mem.bytesAsSlice(u16, t.x)[i]); + m.* = 0; + } + } +}; + +// --- mm_argmax: the greedy draw over a bf16 logits row, ties to the lower id --------------------------------------- + +/// mm_better: NaN beats any number (the lower id among NaNs), else the larger value, ties to the lower id. +fn better(v: f32, i: usize, best: f32, at: usize) bool { + if (std.math.isNan(v)) return !std.math.isNan(best) or i < at; + if (std.math.isNan(best)) return false; + return v > best or (v == best and i < at); +} + +pub const Argmax = struct { + a: std.mem.Allocator, + rig: rig_.Rig, + pipe: mtl.Pipeline, + logits: []u16 = &.{}, + in: rig_.Ref = undefined, + out: rig_.Ref = undefined, + msg: [160]u8 = undefined, + + /// n: the vocabulary (rows and k unused: one row a launch). + pub fn spec() c.Spec { + return .{ + .name = "metal minimax_m3 glue mm_argmax", + .accum = .none, + .depth = noSums, + .out = .raw, + .nan = .{ .stated = "a NaN logit wins (the lowest id among NaNs), as torch.argmax takes NaN as the largest; else ties to the lower id" }, + .tiles = .{ .{}, .{ .size = 1024, .step = 1, .min = 1 }, .{} }, + .served = &.{.{ .rows = 1, .n = vocab, .k = 1 }}, + }; + } + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue) !Argmax { + return .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .pipe = try pipeline(device, "mm_argmax") }; + } + pub fn deinit(t: *Argmax) void { + t.a.free(t.logits); + t.rig.deinit(); + t.pipe.deinit(); + } + pub fn kernel(t: *Argmax) g.Kernel { + return .{ .spec = spec(), .ctx = t, .vt = &vt }; + } + const vt = g.hooks(Argmax); + + pub fn prepare(t: *Argmax, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.n == 0) return false; + t.rig.reset(); + t.a.free(t.logits); + t.logits = try t.a.alloc(u16, shape.n); + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + // few distinct values, so the largest is tied many times over + for (t.logits) |*v| v.* = c.toBf16(@as(f32, @floatFromInt(rng.uintLessThan(u32, 64))) / 4 - 8); + if (fill == .nonfinite) { + const n = shape.n; + t.logits[n / 3] = c.toBf16(planted[1]); + t.logits[n / 2] = c.toBf16(planted[0]); + t.logits[n - 1] = c.toBf16(planted[0]); + t.logits[0] = c.toBf16(planted[2]); + } + t.in = try t.rig.input(std.mem.sliceAsBytes(t.logits)); + t.out = try t.rig.output(4); + return true; + } + + pub fn run(t: *Argmax) !void { + const p = t.rig.begin(); + p.e.setPipeline(t.pipe); + p.e.setBuffer(t.in.buf, t.in.off, 0); + p.e.setBuffer(t.out.buf, t.out.off, 1); + p.e.setValue(@as(u32, @intCast(t.logits.len)), 2); + p.e.dispatchGroups(mtl.Size.of(1, 1, 1), mtl.Size.of(1024, 1, 1)); + try t.rig.finish(p); + } + + pub fn count(_: *Argmax) usize { + return 1; + } + pub fn reference(_: *Argmax, _: []f64, _: []f64) !void { + return error.CheckedByItsOwnRule; + } + + pub fn check(t: *Argmax, _: g.Gate) !?[]const u8 { + var best: f32 = -std.math.inf(f32); + var at: usize = std.math.maxInt(u32); + for (t.logits, 0..) |v, i| if (better(c.fromBf16(v), i, best, at)) { + best = c.fromBf16(v); + at = i; + }; + const got = std.mem.bytesToValue(u32, t.rig.bytes(t.out, 4)); + if (got != at) return try std.fmt.bufPrint(&t.msg, "drew id {d} where the rule picks {d} of {d}", .{ got, at, t.logits.len }); + return null; + } +}; + +pub const Suite = struct { + a: std.mem.Allocator, + device: mtl.Device, + queue: mtl.Queue, + kernels: *std.ArrayList(g.Kernel), + embed: ?*Embed = null, + swiglu: ?*Swiglu = null, + copies: std.ArrayList(*Copy) = .empty, + argmax: ?*Argmax = null, + rows: rows_k.Suite = undefined, + + fn wanted(only: ?[]const u8, name: []const u8) bool { + const o = only orelse return true; + return std.mem.indexOf(u8, name, o) != null; + } + + fn one(s: *Suite, comptime T: type, only: ?[]const u8) !?*T { + if (!wanted(only, T.spec().name)) return null; + const x = try s.a.create(T); + x.* = try T.init(s.a, s.device, s.queue); + try s.kernels.append(s.a, x.kernel()); + return x; + } + + pub fn collect(s: *Suite, only: ?[]const u8) !void { + s.embed = try s.one(Embed, only); + s.swiglu = try s.one(Swiglu, only); + for ([_]bool{ false, true }) |narrow| { + if (!wanted(only, Copy.spec(narrow).name)) continue; + const x = try s.a.create(Copy); + x.* = try Copy.init(s.a, s.device, s.queue, narrow); + try s.copies.append(s.a, x); + try s.kernels.append(s.a, x.kernel()); + } + s.argmax = try s.one(Argmax, only); + s.rows = .{ .a = s.a, .device = s.device, .queue = s.queue, .kernels = s.kernels }; + try s.rows.collect(only); + } + pub fn deinit(s: *Suite) void { + if (s.embed) |x| x.deinit(); + if (s.swiglu) |x| x.deinit(); + for (s.copies.items) |x| x.deinit(); + s.copies.deinit(s.a); + if (s.argmax) |x| x.deinit(); + s.rows.deinit(); + } +}; + +/// Gate 5's texts for this group's registrations (`minimax_m3 glue ...`): glue.metal as is, on every chip. +pub fn limitsText(_: std.mem.Allocator, _: mtl.Device, name: []const u8) !?Texts { + if (!std.mem.startsWith(u8, name, "minimax_m3 glue ")) return null; + return .{ .here = source, .pre_m5 = source }; +} diff --git a/zig/tests/contract/metal_minimax_glue_rows.zig b/zig/tests/contract/metal_minimax_glue_rows.zig new file mode 100644 index 00000000000..74abd4f9b62 --- /dev/null +++ b/zig/tests/contract/metal_minimax_glue_rows.zig @@ -0,0 +1,337 @@ +//! glue.metal's residual adds and norms under the contract; a kernel writing both outputs registers once for each. +const std = @import("std"); +const mtl = @import("metal"); +const contract = @import("contract"); +const rig_ = @import("rig.zig"); +const glue = @import("metal_minimax_glue.zig"); + +const c = contract.spec; +const g = contract.gates; +const bf = glue.bf; +const MArgs = glue.MArgs; +const hidden = glue.hidden; +const topk = glue.topk; + +const eps: f32 = 1e-6; +const scale: f32 = 2.0; // routed_scaling_factor + +const Kind = enum { norm, add, add_norm, moe_add, moe_add_norm }; + +const Case = struct { + kind: Kind, + /// Threads a row's threadgroup (the norms; the adds alone run 256-thread groups over the grid). + threads: u32 = 256, + /// Which output is checked: the normed rows, or the residual. + normed: bool, + name: []const u8, +}; + +const cases = [_]Case{ + .{ .kind = .norm, .threads = 1024, .normed = true, .name = "metal minimax_m3 glue mm_norm 1024 threads" }, + .{ .kind = .norm, .threads = 256, .normed = true, .name = "metal minimax_m3 glue mm_norm 256 threads" }, + .{ .kind = .add, .normed = false, .name = "metal minimax_m3 glue mm_add residual" }, + .{ .kind = .add_norm, .threads = 1024, .normed = false, .name = "metal minimax_m3 glue mm_add_norm 1024 threads residual" }, + .{ .kind = .add_norm, .threads = 1024, .normed = true, .name = "metal minimax_m3 glue mm_add_norm 1024 threads normed" }, + .{ .kind = .add_norm, .threads = 256, .normed = true, .name = "metal minimax_m3 glue mm_add_norm 256 threads normed" }, + .{ .kind = .moe_add, .normed = false, .name = "metal minimax_m3 glue mm_moe_add top 4 residual" }, + .{ .kind = .moe_add_norm, .threads = 1024, .normed = false, .name = "metal minimax_m3 glue mm_moe_add_norm top 4 residual" }, + .{ .kind = .moe_add_norm, .threads = 1024, .normed = true, .name = "metal minimax_m3 glue mm_moe_add_norm top 4 normed" }, +}; + +/// A thread's strided squares, the simd_sum tree, then the threadgroup's partials in turn. +fn depthOf(comptime threads: usize) fn (c.Shape) usize { + return struct { + fn f(s: c.Shape) usize { + return (s.n + threads - 1) / threads + 5 + threads / 32; + } + }.f; +} + +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"; + +fn spec(v: Case) c.Spec { + const k: usize = if (v.kind == .moe_add or v.kind == .moe_add_norm) topk else 1; + // a decode window's rows first (the edges run at it), then a prompt chunk's and one row (the last row's norm) + const served: []const c.Shape = switch (k) { + 1 => &.{ .{ .rows = 32, .n = hidden, .k = 1 }, .{ .rows = 4096, .n = hidden, .k = 1 }, .{ .rows = 1, .n = hidden, .k = 1 } }, + else => &.{ .{ .rows = 32, .n = hidden, .k = topk }, .{ .rows = 4096, .n = hidden, .k = topk }, .{ .rows = 1, .n = hidden, .k = topk } }, + }; + var s: c.Spec = .{ + .name = v.name, + .accum = .none, + .depth = glue.noSums, + .out = .f32, + .in_place = true, + .tiles = .{ .{}, .{ .size = 256, .step = 32, .min = 32 }, .{} }, + .served = served, + }; + if (v.normed) { + s.accum = .f32; + s.depth = if (v.threads == 1024) depthOf(1024) else depthOf(256); + // the mean's division, + eps, rsqrt, x * inv, 1 + w and the product + s.ops = 8; + s.out = .bf16; + s.in_place = false; + s.tiles[1] = .{ .size = v.threads, .step = 32, .min = 32 }; + s.sums = .{ .bf16 = 0, .why = norm_why }; + } + return s; +} + +pub const Rows = struct { + a: std.mem.Allocator, + rig: rig_.Rig, + pipe: mtl.Pipeline, + v: Case, + shape: c.Shape = undefined, + fill: g.Fill = .random, + r0: []f32 = &.{}, + x: []u16 = &.{}, + w: []u16 = &.{}, + y: []u16 = &.{}, + wts: []f32 = &.{}, + shared: []u16 = &.{}, + pick: []i32 = &.{}, + resid: rig_.Ref = undefined, + out: rig_.Ref = undefined, + ins: [5]rig_.Ref = undefined, + + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, v: Case) !Rows { + const name = switch (v.kind) { + .norm => "mm_norm", + .add => "mm_add", + .add_norm => "mm_add_norm", + .moe_add => "mm_moe_add", + .moe_add_norm => "mm_moe_add_norm", + }; + return .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .pipe = try glue.pipeline(device, name), .v = v }; + } + pub fn deinit(t: *Rows) void { + t.free(); + t.rig.deinit(); + t.pipe.deinit(); + } + fn free(t: *Rows) void { + inline for (.{ "r0", "x", "w", "y", "wts", "shared", "pick" }) |f| { + t.a.free(@field(t, f)); + @field(t, f) = &.{}; + } + } + pub fn kernel(t: *Rows) g.Kernel { + return .{ .spec = spec(t.v), .ctx = t, .vt = &vt }; + } + const vt = blk: { + var h = g.hooks(Rows); + h.overlap = overlap; + break :blk h; + }; + /// The residual is read and written in place where it is the checked output. + fn overlap(ctx: *anyopaque) bool { + const t: *Rows = @ptrCast(@alignCast(ctx)); + return t.v.kind != .norm and !t.v.normed; + } + + fn moe(t: *const Rows) bool { + return t.v.kind == .moe_add or t.v.kind == .moe_add_norm; + } + fn hasNorm(t: *const Rows) bool { + return t.v.kind == .norm or t.v.kind == .add_norm or t.v.kind == .moe_add_norm; + } + + pub fn prepare(t: *Rows, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.rows == 0 or shape.n == 0 or shape.k != @as(usize, if (t.moe()) topk else 1)) return false; + t.rig.reset(); + t.free(); + t.shape = shape; + t.fill = fill; + const rows = shape.rows; + const n = shape.n; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + t.r0 = try t.a.alloc(f32, rows * n); + t.w = try t.a.alloc(u16, n); + t.x = try t.a.alloc(u16, if (t.v.kind == .add or t.v.kind == .add_norm) rows * n else 0); + const slots: usize = if (t.moe()) rows * topk else 0; + t.y = try t.a.alloc(u16, slots * n); + t.wts = try t.a.alloc(f32, slots); + t.pick = try t.a.alloc(i32, slots); + t.shared = try t.a.alloc(u16, if (t.moe()) rows * n else 0); + if (fill == .stress) { + // integers whose squares sum exactly in fp32 (at most 6,144 x 1,600) and overflow fp16 in any order + for (t.r0) |*v| v.* = @floatFromInt(@as(i32, @intCast(20 + rng.uintLessThan(u32, 21))) * (if (rng.boolean()) @as(i32, 1) else -1)); + @memset(t.w, 0); + @memset(t.x, 0); + @memset(t.y, 0); + @memset(t.shared, 0); + for (t.wts) |*v| v.* = 0.25; + } else { + for (t.r0) |*v| v.* = (rng.float(f32) * 2 - 1) * 4; + for (t.w) |*v| v.* = c.toBf16(rng.float(f32) - 0.5); + for (t.x) |*v| v.* = c.toBf16((rng.float(f32) * 2 - 1) * 2); + for (t.y) |*v| v.* = c.toBf16((rng.float(f32) * 2 - 1) * 2); + for (t.shared) |*v| v.* = c.toBf16((rng.float(f32) * 2 - 1) * 2); + // bf16-sized routing weights summing to about 1 a row, as mm_pick_row leaves them + for (t.wts) |*v| v.* = 0.05 + rng.float(f32) * 0.4; + } + for (t.pick, 0..) |*p, s| p.* = @intCast((s % topk) * 31 + 3); + if (fill == .nonfinite) { + // a row each, one row holding both infinities, in the residual; then the added terms' own + const at = [_][2]usize{ .{ 0, 1 }, .{ 1, 2 }, .{ 2, 3 }, .{ 3, 4 }, .{ 3, 5 } }; + const vals = [_]f32{ glue.planted[0], glue.planted[1], glue.planted[2], glue.planted[1], glue.planted[2] }; + for (at, vals) |p, v| if (p[0] < rows and p[1] < n) { + t.r0[p[0] * n + p[1]] = v; + }; + if (rows > 4 and n > 7) { + if (t.x.len > 0) t.x[4 * n + 6] = c.toBf16(glue.planted[0]); + if (t.moe()) { + t.y[(4 * topk + 1) * n + 6] = c.toBf16(glue.planted[1]); + t.wts[4 * topk + 2] = glue.planted[2]; + t.shared[4 * n + 7] = c.toBf16(glue.planted[0]); + } + } + } + // the residual buffer: the checked output, or working memory restored before each run + const rbytes = std.mem.sliceAsBytes(t.r0); + t.resid = if (t.v.kind == .norm) try t.rig.input(rbytes) else if (t.v.normed) try t.rig.scratch(rbytes.len) else try t.rig.output(rbytes.len); + if (t.hasNorm()) t.out = if (t.v.normed) try t.rig.output(rows * n * 2) else try t.rig.scratch(rows * n * 2); + t.ins[0] = try t.rig.input(std.mem.sliceAsBytes(t.w)); + if (t.x.len > 0) t.ins[1] = try t.rig.input(std.mem.sliceAsBytes(t.x)); + if (t.moe()) { + t.ins[1] = try t.rig.input(std.mem.sliceAsBytes(t.y)); + t.ins[2] = try t.rig.input(std.mem.sliceAsBytes(t.pick)); + t.ins[3] = try t.rig.input(std.mem.sliceAsBytes(t.wts)); + t.ins[4] = try t.rig.input(std.mem.sliceAsBytes(t.shared)); + } + return true; + } + + pub fn run(t: *Rows) !void { + if (t.v.kind != .norm) @memcpy(t.rig.bytes(t.resid, t.r0.len * 4), std.mem.sliceAsBytes(t.r0)); + const rows = t.shape.rows; + const n = t.shape.n; + const args = MArgs{ .rows = @intCast(rows), .width = @intCast(n), .heads = topk, .eps = eps, .scale = scale }; + const p = t.rig.begin(); + const e = p.e; + e.setPipeline(t.pipe); + e.setBuffer(t.resid.buf, t.resid.off, 0); + switch (t.v.kind) { + .norm => { + e.setBuffer(t.ins[0].buf, t.ins[0].off, 1); + e.setValue(args, 2); + e.setBuffer(t.out.buf, t.out.off, 3); + }, + .add => { + e.setBuffer(t.ins[1].buf, t.ins[1].off, 1); + e.setValue(args, 2); + }, + .add_norm => { + e.setBuffer(t.ins[1].buf, t.ins[1].off, 1); + e.setBuffer(t.ins[0].buf, t.ins[0].off, 2); + e.setValue(args, 3); + e.setBuffer(t.out.buf, t.out.off, 4); + }, + .moe_add, .moe_add_norm => { + for (1..5) |i| e.setBuffer(t.ins[i].buf, t.ins[i].off, i); + if (t.v.kind == .moe_add) { + e.setValue(args, 5); + } else { + e.setBuffer(t.ins[0].buf, t.ins[0].off, 5); + e.setValue(args, 6); + e.setBuffer(t.out.buf, t.out.off, 7); + } + }, + } + if (t.hasNorm()) { + e.dispatchGroups(mtl.Size.of(rows, 1, 1), mtl.Size.of(t.v.threads, 1, 1)); + } else e.dispatchThreads(mtl.Size.of(n, rows, 1), mtl.Size.of(256, 1, 1)); + try t.rig.finish(p); + } + + pub fn count(t: *Rows) usize { + return t.shape.rows * t.shape.n; + } + + /// The routed experts' sum at transformers' points (bf16 after each product and each add), scaled, plus the shared. + fn moeOut(t: *const Rows, r: usize, i: usize) f64 { + const n = t.shape.n; + var acc: f64 = 0; + for (0..topk) |j| { + const s = r * topk + j; + acc = bf(acc + bf(@as(f64, c.fromBf16(t.y[s * n + i])) * t.wts[s])); + } + return bf(bf(acc * scale) + c.fromBf16(t.shared[r * n + i])); + } + + /// Element i's residual after the kernel's add (each step one fp32 rounding of exact values, then its bf16 point). + fn residAt(t: *const Rows, i: usize) f64 { + const x0: f64 = t.r0[i]; + return switch (t.v.kind) { + .norm => x0, + .add, .add_norm => bf(x0 + c.fromBf16(t.x[i])), + .moe_add, .moe_add_norm => bf(x0 + t.moeOut(i / t.shape.n, i % t.shape.n)), + }; + } + + /// Row r's residual into `xs`, and its squares into `sq`. + fn row(t: *const Rows, r: usize, xs: []f64, sq: []f64) void { + for (xs, sq, 0..) |*x, *q, j| { + x.* = t.residAt(r * t.shape.n + j); + q.* = x.* * x.*; + } + } + + fn normed(t: *const Rows, x: f64, j: usize, ss: f64) f64 { + const inv = 1 / @sqrt(ss / @as(f64, @floatFromInt(t.shape.n)) + @as(f64, eps)); + return x * inv * (1 + @as(f64, c.fromBf16(t.w[j]))); + } + + pub fn reference(t: *Rows, want: []f64, mag: []f64) !void { + const n = t.shape.n; + const buf = try t.a.alloc(f64, 2 * n); + defer t.a.free(buf); + for (0..t.shape.rows) |r| { + t.row(r, buf[0..n], buf[n..]); + var ss: f64 = 0; + for (buf[n..]) |q| ss += q; + for (buf[0..n], 0..) |x, j| { + const i = r * n + j; + want[i] = if (t.v.normed) t.normed(x, j, ss) else x; + // the sum's relative error moves the output by as much again at most + mag[i] = if (t.v.normed and std.math.isFinite(want[i])) @abs(want[i]) else 0; + } + } + } + + pub fn simulate(t: *Rows, acc: c.Accum, order: g.Order, out: []f64) !void { + const n = t.shape.n; + const buf = try t.a.alloc(f64, 2 * n); + defer t.a.free(buf); + for (0..t.shape.rows) |r| { + t.row(r, buf[0..n], buf[n..]); + const ss = contract.rows.sumIn(acc, order, buf[n..]); + for (buf[0..n], 0..) |x, j| out[r * n + j] = bf(t.normed(x, j, ss)); + } + } +}; + +pub const Suite = struct { + a: std.mem.Allocator, + device: mtl.Device, + queue: mtl.Queue, + kernels: *std.ArrayList(g.Kernel), + tests: std.ArrayList(*Rows) = .empty, + + pub fn collect(s: *Suite, only: ?[]const u8) !void { + for (cases) |v| { + if (only) |o| if (std.mem.indexOf(u8, v.name, o) == null) continue; + const x = try s.a.create(Rows); + x.* = try Rows.init(s.a, s.device, s.queue, v); + try s.tests.append(s.a, x); + try s.kernels.append(s.a, x.kernel()); + } + } + pub fn deinit(s: *Suite) void { + for (s.tests.items) |x| x.deinit(); + s.tests.deinit(s.a); + } +}; diff --git a/zig/tests/contract/metal_minimax_nax.zig b/zig/tests/contract/metal_minimax_nax.zig new file mode 100644 index 00000000000..9467529dc37 --- /dev/null +++ b/zig/tests/contract/metal_minimax_nax.zig @@ -0,0 +1,274 @@ +//! MiniMax-M3.1-Flash's decode experts (experts.metal) and its tensor-unit suite (attention, index: _nax_attn.zig). +const std = @import("std"); +const mtl = @import("metal"); +const tf = @import("tensorfold"); +const contract = @import("contract"); +const sources = @import("kernel_sources"); +const rig_ = @import("rig.zig"); +const attn = @import("metal_minimax_nax_attn.zig"); + +const c = contract.spec; +const g = contract.gates; +const Affine = contract.affine.Affine; +const row = tf.row_projection; +const Texts = @import("metal_minimax.zig").Texts; + +/// The release's shape (config.zig's defaults are MiniMax-M3.1-Flash's config.json). +pub const config: tf.minimax_m3.config.Config = .{}; +const st = tf.minimax_m3.state; + +pub const Suite = struct { + a: std.mem.Allocator, + device: mtl.Device, + queue: mtl.Queue, + kernels: *std.ArrayList(g.Kernel), + grouped: std.ArrayList(*Grouped) = .empty, + index: ?*attn.Index = null, + prompt: ?*attn.Prompt = null, + + pub fn collect(s: *Suite, only: ?[]const u8) !void { + for (grouped_forms) |f| { + if (!wanted(only, f.name)) continue; + const x = try s.a.create(Grouped); + x.* = try Grouped.init(s.a, s.device, s.queue, f); + try s.grouped.append(s.a, x); + try s.kernels.append(s.a, x.kernel()); + } + if (wanted(only, attn.Index.spec().name)) { + s.index = try s.a.create(attn.Index); + s.index.?.* = try attn.Index.init(s.a, s.device, s.queue); + try s.kernels.append(s.a, s.index.?.kernel()); + } + if (wanted(only, attn.Prompt.spec().name)) { + s.prompt = try s.a.create(attn.Prompt); + s.prompt.?.* = try attn.Prompt.init(s.a, s.device, s.queue); + try s.kernels.append(s.a, s.prompt.?.kernel()); + } + } + pub fn deinit(s: *Suite) void { + for (s.grouped.items) |x| { + x.deinit(); + s.a.destroy(x); + } + s.grouped.deinit(s.a); + if (s.index) |x| { + x.deinit(); + s.a.destroy(x); + } + if (s.prompt) |x| { + x.deinit(); + s.a.destroy(x); + } + } +}; + +fn wanted(only: ?[]const u8, name: []const u8) bool { + const o = only orelse return true; + return std.mem.indexOf(u8, name, o) != null; +} + +/// Gate 5's texts for `minimax_m3 nax ` launches as model.zig builds them, nax.h inlined (fragments before the M5). +pub fn limitsText(a: std.mem.Allocator, device: mtl.Device, name: []const u8) !?Texts { + if (!std.mem.startsWith(u8, name, "minimax_m3 nax ")) return null; + if (std.mem.indexOf(u8, name, " experts ") != null) { + const text = try expertsText(a); + return .{ .here = text, .pre_m5 = text }; + } + const head = if (std.mem.indexOf(u8, name, " attention ") != null) try attn.promptHead(a) else try attn.indexHead(a); + const body_src = if (std.mem.indexOf(u8, name, " attention ") != null) sources.minimax_m3_attention_nax else sources.minimax_m3_index_nax; + const body = try std.mem.replaceOwned(u8, a, body_src, "#include \"../nax.h\"", sources.nax); + const pre = try std.mem.concat(a, u8, &.{ head, "#define TF_SIMD_FRAGS 1\n", body }); + return .{ .here = if (device.tensorUnits()) try std.mem.concat(a, u8, &.{ head, body }) else pre, .pre_m5 = pre }; +} + +fn expertsText(a: std.mem.Allocator) ![]u8 { + return std.mem.concat(a, u8, &.{ sources.core_row_projection, "\n", sources.minimax_m3_experts }); +} + +fn expertsPipeline(a: std.mem.Allocator, device: mtl.Device, name: []const u8) !mtl.Pipeline { + const text = try expertsText(a); + defer a.free(text); + return rig_.pipeline(device, text, name); +} + +fn noSums(_: c.Shape) usize { + return 0; +} + +/// Picks of `tokens` tokens, `topk` distinct experts each out of `experts`; a few hot experts take most slots. +fn picks(a: std.mem.Allocator, tokens: usize, topk: usize, experts: u32, seed: u64) ![]i32 { + const ids = try a.alloc(i32, tokens * topk); + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + for (0..tokens) |t| for (0..topk) |j| { + var e: u32 = if (rng.boolean()) rng.uintLessThan(u32, @min(experts, 3)) else rng.uintLessThan(u32, experts); + while (std.mem.indexOfScalar(i32, ids[t * topk ..][0..j], @intCast(e)) != null) e = (e + 1) % experts; + ids[t * topk + j] = @intCast(e); + }; + return ids; +} + +/// The host's expert groups: G[0] the experts picked, then (id, first member) by id; M the slots by expert, in order. +fn hostGroups(a: std.mem.Allocator, ids: []const i32) !struct { g: []u32, m: []u32 } { + const gs = try a.alloc(u32, 1 + 2 * ids.len); + errdefer a.free(gs); + const ms = try a.alloc(u32, ids.len); + var n: u32 = 0; + var at: u32 = 0; + var last: i64 = -1; + while (true) { + var next: i64 = std.math.maxInt(i64); + for (ids) |e| if (e > last and e < next) { + next = e; + }; + if (next == std.math.maxInt(i64)) break; + gs[1 + 2 * n] = @intCast(next); + gs[2 + 2 * n] = at; + for (ids, 0..) |e, s| if (e == next) { + ms[at] = @intCast(s); + at += 1; + }; + last = next; + n += 1; + } + gs[0] = n; + return .{ .g = gs, .m = ms }; +} + +// --- mm_experts_grouped: each picked expert's rows read once a window, tf_rp_rows_at's sums ---------------------- + +/// The checkpoints' expert formats: 3-bit groups of 64, and the 4-bit groups of 128 on their chosen layers. +const Form = struct { bits: u8, group: usize, name: []const u8 }; +const grouped_forms = [_]Form{ + .{ .bits = 3, .group = 64, .name = "metal minimax_m3 mm_experts_grouped_q3 g64" }, + .{ .bits = 4, .group = 128, .name = "metal minimax_m3 mm_experts_grouped_q4 g128" }, +}; + +/// As tf_row_projection_indexed (Ornith's q27_rows_extra): 16-input pieces, a lane's pieces in turn, a simd_sum. +fn rowDepth(s: c.Shape) usize { + return 16 + 3 * ((s.k + 511) / 512) + 8; +} + +/// Slot s reads token s / topk and expert ids[s] of `experts` stacked matrices; members 4, 2 then 1 at a time. +pub const Grouped = struct { + /// Matrices stacked in the test: enough for distinct picks and empty experts, small enough for float64. + const experts = 6; + const topk = 4; + a: std.mem.Allocator, + rig: rig_.Rig, + pipe: mtl.Pipeline, + form: Form, + f: ?Affine = null, + ids: []i32 = &.{}, + refs: [7]rig_.Ref = undefined, + out: rig_.Ref = undefined, + dims: [6]i32 = undefined, + + /// Rows: a window's tokens; n and k: one expert's matrix. + pub fn spec(f: Form) c.Spec { + const gu = config.moe_intermediate * 2; + return .{ + .name = f.name, + .accum = .f32, + .depth = rowDepth, + .out = .bf16, + .tiles = .{ .{ .size = 4 }, .{ .size = 8, .step = 8, .min = 8 }, .{ .size = 512, .step = f.group, .min = f.group } }, + // gate|up at one token and a drafted window, down at the widest; one token first (gate 4 replays 4 slots) + .served = &.{ .{ .rows = 1, .n = gu, .k = config.hidden }, .{ .rows = st.window_rows, .n = gu, .k = config.hidden }, .{ .rows = st.batch_rows, .n = config.hidden, .k = config.moe_intermediate } }, + }; + } + + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, f: Form) !Grouped { + const fun = if (f.bits == 3) "mm_experts_grouped_q3" else "mm_experts_grouped_q4"; + return .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .pipe = try expertsPipeline(a, device, fun), .form = f }; + } + pub fn deinit(t: *Grouped) void { + t.drop(); + t.rig.deinit(); + t.pipe.deinit(); + } + fn drop(t: *Grouped) void { + if (t.f) |f| f.deinit(); + t.f = null; + t.a.free(t.ids); + t.ids = &.{}; + t.rig.reset(); + } + pub fn kernel(t: *Grouped) g.Kernel { + return .{ .spec = spec(t.form), .ctx = t, .vt = &vt }; + } + const vt = g.hooks(Grouped); + + pub fn prepare(t: *Grouped, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + t.drop(); + if (shape.rows == 0 or shape.k % t.form.group != 0) return false; + (row.Weights{ .w = undefined, .scales = undefined, .biases = undefined, .n = shape.n, .k = shape.k, .group = t.form.group, .bits = t.form.bits }).validate() catch return false; + // every expert in one family: rows [e n, (e + 1) n) are expert e's + const f = try Affine.init(t.a, .{ .rows = shape.rows, .n = experts * shape.n, .k = shape.k }, t.form.bits, t.form.group); + t.f = f; + try f.fill(fill, seed); + const words = try t.a.alloc(u32, experts * shape.n * shape.k * t.form.bits / 32); + defer t.a.free(words); + f.words(words); + t.ids = try picks(t.a, shape.rows, topk, experts, seed +% 1); + const grp = try hostGroups(t.a, t.ids); + defer t.a.free(grp.g); + defer t.a.free(grp.m); + t.dims = .{ @intCast(shape.k), @intCast(shape.n), @intCast(t.form.group), @intCast(t.ids.len), experts, topk }; + t.refs[0] = try t.rig.input(std.mem.sliceAsBytes(f.x)); + t.refs[1] = try t.rig.input(std.mem.sliceAsBytes(words)); + t.refs[2] = try t.rig.input(std.mem.sliceAsBytes(f.scales)); + t.refs[3] = try t.rig.input(std.mem.sliceAsBytes(f.biases)); + t.refs[4] = try t.rig.input(std.mem.sliceAsBytes(&t.dims)); + t.refs[5] = try t.rig.input(std.mem.sliceAsBytes(grp.g)); + t.refs[6] = try t.rig.input(std.mem.sliceAsBytes(grp.m)); + t.out = try t.rig.output(t.count() * 2); + return true; + } + + pub fn run(t: *Grouped) !void { + const n: usize = @intCast(t.dims[1]); + const p = t.rig.begin(); + const e = p.e; + e.setPipeline(t.pipe); + for (t.refs[0..5], 0..) |r, i| e.setBuffer(r.buf, r.off, i); + e.setBuffer(t.out.buf, t.out.off, 5); + e.setBuffer(t.refs[5].buf, t.refs[5].off, 6); + e.setBuffer(t.refs[6].buf, t.refs[6].off, 7); + // as forward.zig's experts(): (columns / (RPS * SG), slots) groups of 64 threads + e.dispatchGroups(mtl.Size.of(n / (row.columns * row.groups), t.ids.len, 1), mtl.Size.of(32 * row.groups, 1, 1)); + try t.rig.finish(p); + } + + pub fn count(t: *Grouped) usize { + return t.ids.len * @as(usize, @intCast(t.dims[1])); + } + + /// Slot s's family: its token's row of x over its expert's matrix (slices of the whole family, nothing copied). + fn slot(t: *Grouped, s: usize) Affine { + var v = t.f.?; + const n = v.shape.n / experts; + const k = v.shape.k; + const m: usize = @intCast(t.ids[s]); + v.shape = .{ .rows = 1, .n = n, .k = k }; + v.x = v.x[(s / topk) * k ..][0..k]; + v.codes = v.codes[m * n * k ..][0 .. n * k]; + v.scales = v.scales[m * n * (k / v.group) ..][0 .. n * (k / v.group)]; + v.biases = v.biases[m * n * (k / v.group) ..][0 .. n * (k / v.group)]; + return v; + } + + pub fn reference(t: *Grouped, want: []f64, mag: []f64) !void { + const n: usize = @intCast(t.dims[1]); + for (0..t.ids.len) |s| try t.slot(s).reference(want[s * n ..][0..n], mag[s * n ..][0..n]); + } + + pub fn simulate(t: *Grouped, acc: c.Accum, order: g.Order, out: []f64) !void { + const n: usize = @intCast(t.dims[1]); + for (0..t.ids.len) |s| try t.slot(s).simulate(acc, order, out[s * n ..][0..n]); + } +}; + +test { + _ = attn; +} diff --git a/zig/tests/contract/metal_minimax_nax_attn.zig b/zig/tests/contract/metal_minimax_nax_attn.zig new file mode 100644 index 00000000000..8047c507ee9 --- /dev/null +++ b/zig/tests/contract/metal_minimax_nax_attn.zig @@ -0,0 +1,471 @@ +//! MiniMax-M3.1-Flash's prompt kernels on the tensor units (index_nax.metal, attention_nax.metal), as model.zig builds. +const std = @import("std"); +const mtl = @import("metal"); +const tf = @import("tensorfold"); +const contract = @import("contract"); +const ar = contract.attention_range; +const sources = @import("kernel_sources"); +const rig_ = @import("rig.zig"); +const nax = @import("metal_minimax_nax.zig"); + +const c = contract.spec; +const g = contract.gates; +const cfg = nax.config; +const st = tf.minimax_m3.state; +const dh: usize = cfg.head_dim; +const block: usize = cfg.block; +const words = st.selWords(&cfg); +const scale: f64 = 1.0 / @sqrt(@as(f64, @floatFromInt(cfg.head_dim))); +const nan16 = 0x7fc0; + +/// model.zig's header for attention_nax.metal. +pub fn promptHead(a: std.mem.Allocator) ![]u8 { + return std.fmt.allocPrint(a, "#define DH {d}\n#define NQ {d}\n#define G {d}\n#define KVH {d}\n#define WORDS {d}\n#define SCALE {e}f\n", .{ cfg.head_dim, cfg.heads, cfg.heads / cfg.kv_heads, cfg.kv_heads, words, scale }); +} + +/// model.zig's header for index_nax.metal. +pub fn indexHead(a: std.mem.Allocator) ![]u8 { + return std.fmt.allocPrint(a, "#define DH {d}\n#define IH {d}\n", .{ cfg.index_dim, cfg.index_heads }); +} + +/// A source as the engine builds it on this GPU: defines, then frags.source's text. +fn pipeline(a: std.mem.Allocator, device: mtl.Device, head: []const u8, text: []const u8, name: []const u8) !mtl.Pipeline { + const body = try tf.frags.source(device, a, text); + defer a.free(body); + const src = try std.mem.concat(a, u8, &.{ head, body }); + defer a.free(src); + return rig_.pipeline(device, src, name); +} + +fn bf(v: f64) f64 { + return c.fromBf16(c.toBf16(@floatCast(v))); +} + +/// Random bf16 values in [-r, r). +fn fillRandom(rng: std.Random, out: []u16, r: f32) void { + for (out) |*v| v.* = c.toBf16((rng.float(f32) * 2 - 1) * r); +} + +/// An mma k16 step's error in 2^-24 of |acc| + sum |a b|. +const mma_step = ar.mma_step; + +// --- mm_index_scores_nax: S[row, h, b] = max over b's keys up to the row of IQ[row, h] . IK[key] ---------------- + +/// The score's dot: DH / 16 mma steps of 16 products, each step's error against the running sum. +fn indexDepth(_: c.Shape) usize { + return 2 * mma_step * (cfg.index_dim / 16); +} + +pub const Index = struct { + const ih: usize = cfg.index_heads; + const di: usize = cfg.index_dim; + const rt = 32; // a tile's query rows + a: std.mem.Allocator, + rig: rig_.Rig, + pipe: mtl.Pipeline, + rows: usize = 0, + p0: usize = 0, + q: []u16 = &.{}, + k: []u16 = &.{}, + /// Each kept output's index in S: blocks up to the tile's last row's (later blocks stay unwritten). + kept: std.ArrayList(u32) = .empty, + shown: std.ArrayList(u8) = .empty, + refs: [3]rig_.Ref = undefined, + out: rig_.Ref = undefined, + + /// An accumulator and order gate 4 replays the dots in. + const Sim = struct { a: c.Accum, o: g.Order }; + + /// Rows: a prompt chunk's rows; n: the index dim; k: the chunk's first position. + pub fn spec() c.Spec { + return .{ + .name = "metal minimax_m3 mm_index_scores_nax index heads 4 dim 128", + .accum = .f32, + .depth = indexDepth, + .out = .f32, + .tiles = .{ .{ .size = rt }, .{}, .{ .size = block, .step = 1, .min = 1 } }, + // a chunk past the 16 blocks a row keeps, a whole 4,096-row chunk from the start, one deep in the window + .served = &.{ .{ .rows = 33, .n = di, .k = 2048 }, .{ .rows = st.prompt_rows, .n = di, .k = 0 }, .{ .rows = 512, .n = di, .k = 30720 } }, + }; + } + + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue) !Index { + const head = try indexHead(a); + defer a.free(head); + return .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .pipe = try pipeline(a, device, head, sources.minimax_m3_index_nax, "mm_index_scores_nax") }; + } + pub fn deinit(t: *Index) void { + t.a.free(t.q); + t.a.free(t.k); + t.kept.deinit(t.a); + t.shown.deinit(t.a); + t.rig.deinit(); + t.pipe.deinit(); + } + pub fn kernel(t: *Index) g.Kernel { + return .{ .spec = spec(), .ctx = t, .vt = &vt }; + } + const vt = blk: { + var h = g.hooks(Index); + h.output = output; + break :blk h; + }; + + fn blocks(t: *const Index) usize { + return (t.p0 + t.rows + block - 1) / block; + } + + pub fn prepare(t: *Index, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.rows == 0 or shape.n != di) return false; + t.rig.reset(); + t.a.free(t.q); + t.a.free(t.k); + t.rows = shape.rows; + t.p0 = shape.k; + const pad = std.mem.alignForward(usize, t.rows, rt); // a tile reads all its 32 rows + const slots = std.mem.alignForward(usize, t.p0 + t.rows, block); // whole index blocks, as Cache.slots + t.q = try t.a.alloc(u16, pad * ih * di); + t.k = try t.a.alloc(u16, slots * di); + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + fillRandom(rng, t.q, 2); + fillRandom(rng, t.k, 2); + // rows past the chunk and keys past its last position hold anything: NaN here, which no kept output may see + @memset(t.q[t.rows * ih * di ..], nan16); + @memset(t.k[(t.p0 + t.rows) * di ..], nan16); + switch (fill) { + .random => {}, + .nonfinite => { + const at = [_]usize{ (0 * ih + 0) * di + 3, (1 * ih + 1) * di, (2 * ih + 2) * di + 5 }; + for (at, [_]f32{ std.math.nan(f32), std.math.inf(f32), -std.math.inf(f32) }) |i, v| if (i < t.rows * ih * di) { + t.q[i] = c.toBf16(v); + }; + t.k[(t.p0 + 2) * di + 1] = c.toBf16(std.math.nan(f32)); + }, + .stress => { + // integer dots exact in fp32 in any order; a key's halves cancel but for 8 nudged queries: small scores + const h = di / 2; + for (0..t.rows * ih) |r| for (0..h) |d| { + const x: f32 = @floatFromInt(1 + rng.uintLessThan(u32, 255)); + t.q[r * di + d] = c.toBf16(x); + t.q[r * di + h + d] = c.toBf16(x + @as(f32, @floatFromInt(@intFromBool(d < 8)))); + }; + for (0..t.p0 + t.rows) |key| for (0..h) |d| { + const y: f32 = @floatFromInt(1 + rng.uintLessThan(u32, 255)); + t.k[key * di + d] = c.toBf16(y); + t.k[key * di + h + d] = c.toBf16(-y); + }; + }, + } + t.kept.clearRetainingCapacity(); + for (0..t.rows) |r| { + const tile_last = @min((r / rt) * rt + rt - 1, t.rows - 1); + const last_block = (t.p0 + tile_last) / block; + for (0..ih) |hh| for (0..last_block + 1) |b| try t.kept.append(t.a, @intCast((r * ih + hh) * t.blocks() + b)); + } + t.refs[0] = try t.rig.input(std.mem.sliceAsBytes(t.q)); + t.refs[1] = try t.rig.input(std.mem.sliceAsBytes(t.k)); + t.refs[2] = try t.rig.input(std.mem.asBytes(&[3]i32{ @intCast(t.rows), @intCast(t.p0), @intCast(t.blocks()) })); + t.out = try t.rig.output(t.rows * ih * t.blocks() * 4); + return true; + } + + pub fn run(t: *Index) !void { + const p = t.rig.begin(); + p.e.setPipeline(t.pipe); + for (t.refs[0..2], 0..) |r, i| p.e.setBuffer(r.buf, r.off, i); + p.e.setBuffer(t.out.buf, t.out.off, 2); + p.e.setBuffer(t.refs[2].buf, t.refs[2].off, 3); + // as forward.zig: (rows / 32, index heads) groups, 32 threads a 64-column simdgroup + p.e.dispatchGroups(mtl.Size.of((t.rows + rt - 1) / rt, ih, 1), mtl.Size.of(di / 64 * 32, 1, 1)); + try t.rig.finish(p); + } + + /// The written scores only: each row's blocks up to its tile's last. + fn output(ctx: *anyopaque) anyerror![]const u8 { + const t: *Index = @ptrCast(@alignCast(ctx)); + const all = try t.rig.outputBytes(); + t.shown.clearRetainingCapacity(); + for (t.kept.items) |i| try t.shown.appendSlice(t.a, all[i * 4 ..][0..4]); + return t.shown.items; + } + + pub fn count(t: *Index) usize { + return t.kept.items.len; + } + + fn dot(t: *const Index, r: usize, hh: usize, key: usize, acc: ?Sim) [2]f64 { + var terms: [di]f64 = undefined; + var mag: f64 = 0; + var sum: f64 = 0; + for (&terms, 0..) |*x, d| { + x.* = @as(f64, c.fromBf16(t.q[(r * ih + hh) * di + d])) * c.fromBf16(t.k[key * di + d]); + sum += x.*; + mag += @abs(x.*); + } + if (acc) |s| sum = contract.rows.sumIn(s.a, s.o, &terms); + return .{ sum, mag }; + } + + /// Kept output i's max (NaN if any dot is NaN, -Inf when the block holds no key up to the row) and its terms' size. + fn one(t: *const Index, i: u32, acc: ?Sim) [2]f64 { + const per = ih * t.blocks(); + const r = i / per; + const hh = (i % per) / t.blocks(); + const b = i % t.blocks(); + const pos = t.p0 + r; + var best = -std.math.inf(f64); + var mag: f64 = 0; + var key = b * block; + while (key < (b + 1) * block and key <= pos) : (key += 1) { + const s = t.dot(r, hh, key, acc); + if (std.math.isNan(s[0]) or std.math.isNan(best)) best = std.math.nan(f64) else best = @max(best, s[0]); + if (std.math.isFinite(s[1])) mag = @max(mag, s[1]); + } + return .{ best, mag }; + } + + pub fn reference(t: *Index, want: []f64, mag: []f64) !void { + for (t.kept.items, want, mag) |i, *w, *m| { + const o = t.one(i, null); + w.* = o[0]; + m.* = o[1]; + } + } + + pub fn simulate(t: *Index, acc: c.Accum, order: g.Order, out: []f64) !void { + for (t.kept.items, out) |i, *o| o.* = t.one(i, Sim{ .a = acc, .o = order })[0]; + } +}; + +// --- mm_prompt_attention: softmax over the kept blocks' keys up to each row, bf16 out ---------------------------- + +/// The range's fp32 arithmetic: mma scores, fp32 SCALE * log2e, fast exp2, 64-key blocks; P multiplies V as bf16. +fn form(n: usize) ar.Form { + const blocks: f64 = @floatFromInt(n / 64 + 2); + return .{ .score = @as(f64, @floatFromInt(dh / 16)) * mma_step + 2, .fast_exp = true, .chunk_exp = false, .p_rel = 0x1p-8, .num = mma_step * 4 + blocks + 2, .den = blocks + 6, .score_round = 4, .nan_max = true }; +} + +/// Gate 4's keys: the first 1,024 score high (their probabilities exactly 1), every other key scores far below. +const stress_on = 1024; + +pub const Prompt = struct { + const nq: usize = cfg.heads; + const kvh: usize = cfg.kv_heads; + const grp: usize = cfg.heads / cfg.kv_heads; + const per = 2; // positions a tile: 32 rows of 16 query heads + a: std.mem.Allocator, + rig: rig_.Rig, + pipe: mtl.Pipeline, + rows: usize = 0, + p0: usize = 0, + fill: g.Fill = .random, + q: []u16 = &.{}, + k: []u16 = &.{}, + v: []u16 = &.{}, + sel: []u32 = &.{}, + half: []f64 = &.{}, + refs: [5]rig_.Ref = undefined, + out: rig_.Ref = undefined, + + /// Rows: a prompt chunk's rows; n: the head dim; k: the chunk's first position. + pub fn spec() c.Spec { + return .{ + .name = "metal minimax_m3 mm_prompt_attention 64 heads over 4, kept 128-key blocks", + .accum = .f32, + .depth = indexDepth, + .out = .bf16, + .tiles = .{ .{ .size = per }, .{}, .{ .size = block, .step = 1, .min = 1 } }, + // the shortest prompt chunk with selection, a chunk from the start, one deep in the window + .served = &.{ .{ .rows = st.window_rows + 1, .n = dh, .k = 2100 }, .{ .rows = 256, .n = dh, .k = 0 }, .{ .rows = 64, .n = dh, .k = 32704 } }, + .sums = .{ .exact = true }, + }; + } + + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue) !Prompt { + const h = try promptHead(a); + defer a.free(h); + return .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .pipe = try pipeline(a, device, h, sources.minimax_m3_attention_nax, "mm_prompt_attention") }; + } + fn free(t: *Prompt) void { + for ([_][]u16{ t.q, t.k, t.v }) |x| t.a.free(x); + t.a.free(t.sel); + t.a.free(t.half); + t.q = &.{}; + t.k = &.{}; + t.v = &.{}; + t.sel = &.{}; + t.half = &.{}; + } + pub fn deinit(t: *Prompt) void { + t.free(); + t.rig.deinit(); + t.pipe.deinit(); + } + pub fn kernel(t: *Prompt) g.Kernel { + return .{ .spec = spec(), .ctx = t, .vt = &vt }; + } + const vt = g.hooks(Prompt); + + fn keptBlock(t: *const Prompt, r: usize, kv: usize, b: usize) bool { + return (t.sel[(r * kvh + kv) * words + b / 32] >> @intCast(b % 32)) & 1 != 0; + } + + /// index_select's bitmap: a row keeps its own block and up to 15 earlier ones (all of them while it sees 16). + fn select(t: *Prompt, rng: std.Random) void { + @memset(t.sel, 0); + for (0..t.rows) |r| for (0..kvh) |kv| { + const nb = (t.p0 + r) / block + 1; + const at = t.sel[(r * kvh + kv) * words ..][0..words]; + const set = struct { + fn f(s: []u32, b: usize) void { + s[b / 32] |= @as(u32, 1) << @intCast(b % 32); + } + }.f; + set(at, nb - 1); + if (t.fill == .stress) { + for (0..@min(nb - 1, stress_on / block)) |b| set(at, b); + continue; + } + if (nb <= cfg.topk_blocks) { + for (0..nb) |b| set(at, b); + continue; + } + var kept: usize = 1; + while (kept < cfg.topk_blocks) { + const b = rng.uintLessThan(usize, nb - 1); + if ((at[b / 32] >> @intCast(b % 32)) & 1 != 0) continue; + set(at, b); + kept += 1; + } + }; + } + + pub fn prepare(t: *Prompt, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.rows == 0 or shape.n != dh) return false; + if (fill == .stress and shape.k < stress_on) return false; + t.rig.reset(); + t.free(); + t.rows = shape.rows; + t.p0 = shape.k; + t.fill = fill; + const pad = std.mem.alignForward(usize, t.rows, per); // a tile's second row is read past an odd chunk + const slots = std.mem.alignForward(usize, t.p0 + t.rows, block); + const kw = kvh * dh; + t.q = try t.a.alloc(u16, pad * nq * dh); + t.k = try t.a.alloc(u16, slots * kw); + t.v = try t.a.alloc(u16, slots * kw); + t.sel = try t.a.alloc(u32, pad * kvh * words); + t.half = try t.a.alloc(f64, t.count()); + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + fillRandom(rng, t.q, 3); + fillRandom(rng, t.k, 3); + fillRandom(rng, t.v, 2); + t.select(rng); + switch (fill) { + .random => {}, + .nonfinite => { + // in the rows' own block, which every row keeps; keys at and after p0 + 2 are seen by rows 2 on + for ([_]usize{ 3, 1 * dh, 2 * dh + 5 }, [_]f32{ std.math.nan(f32), std.math.inf(f32), -std.math.inf(f32) }, 0..) |at, x, r| if (r < t.rows) { + t.q[r * nq * dh + (r * grp + 1) * dh + at % dh] = c.toBf16(x); + }; + t.v[t.p0 * kw + 0 * dh + 5] = c.toBf16(std.math.inf(f32)); + t.v[t.p0 * kw + 1 * dh + 6] = c.toBf16(std.math.nan(f32)); + t.k[(t.p0 + 2) * kw + 2 * dh] = c.toBf16(std.math.nan(f32)); + }, + .stress => { + // keys of 3s or -3s: the first 1,024 score high, the rest probability 0; values cancel but for 8 nudged + @memset(t.q, c.toBf16(3)); + for (0..t.p0 + t.rows) |key| @memset(t.k[key * kw ..][0..kw], c.toBf16(if (key < stress_on) 3 else -3)); + for (0..stress_on / 2) |key| for (0..kw) |e| { + const x: f32 = @floatFromInt(1 + rng.uintLessThan(u32, 255)); + t.v[key * kw + e] = c.toBf16(x); + t.v[(key + stress_on / 2) * kw + e] = c.toBf16(-x + @as(f32, @floatFromInt(@intFromBool(key < 8)))); + }; + }, + } + // cache rows past the chunk's last position hold anything: NaN here, which the kernel must never read in + @memset(t.k[(t.p0 + t.rows) * kw ..], nan16); + @memset(t.v[(t.p0 + t.rows) * kw ..], nan16); + t.refs[0] = try t.rig.input(std.mem.sliceAsBytes(t.q)); + t.refs[1] = try t.rig.input(std.mem.sliceAsBytes(t.k)); + t.refs[2] = try t.rig.input(std.mem.sliceAsBytes(t.v)); + t.refs[3] = try t.rig.input(std.mem.asBytes(&[2]i32{ @intCast(t.rows), @intCast(t.p0) })); + t.refs[4] = try t.rig.input(std.mem.sliceAsBytes(t.sel)); + t.out = try t.rig.output(t.count() * 2); + return true; + } + + pub fn run(t: *Prompt) !void { + const p = t.rig.begin(); + p.e.setPipeline(t.pipe); + for (t.refs[0..3], 0..) |r, i| p.e.setBuffer(r.buf, r.off, i); + p.e.setBuffer(t.out.buf, t.out.off, 3); + p.e.setBuffer(t.refs[3].buf, t.refs[3].off, 4); + p.e.setBuffer(t.refs[4].buf, t.refs[4].off, 5); + // as forward.zig: (rows / 2, key heads) groups, 32 threads a 64-column simdgroup + p.e.dispatchGroups(mtl.Size.of((t.rows + per - 1) / per, kvh, 1), mtl.Size.of(dh / 64 * 32, 1, 1)); + try t.rig.finish(p); + } + + pub fn count(t: *Prompt) usize { + return t.rows * nq * dh; + } + + /// Each row's key heads over their kept keys up to the row: float64's outputs and their ranges. + pub fn reference(t: *Prompt, want: []f64, mag: []f64) !void { + @memset(mag, 0); + const most = (t.p0 + t.rows) * dh; + const buf = try t.a.alloc(f64, 2 * most + 2 * (t.p0 + t.rows) + 2 * dh); + defer t.a.free(buf); + const ks = buf[0..most]; + const vs = buf[most .. 2 * most]; + const w = buf[2 * most ..][0 .. t.p0 + t.rows]; + const tau = buf[2 * most + t.p0 + t.rows ..][0 .. t.p0 + t.rows]; + const qv = buf[buf.len - 2 * dh ..][0..dh]; + const hf = buf[buf.len - dh ..]; + for (0..t.rows) |r| for (0..kvh) |kv| { + var n: usize = 0; + for (0..t.p0 + r + 1) |key| { + if (!t.keptBlock(r, kv, key / block)) continue; + for (0..dh) |e| { + ks[n * dh + e] = c.fromBf16(t.k[(key * kvh + kv) * dh + e]); + vs[n * dh + e] = c.fromBf16(t.v[(key * kvh + kv) * dh + e]); + } + n += 1; + } + for (0..grp) |gh| { + const hq = kv * grp + gh; + for (qv, 0..) |*x, e| x.* = c.fromBf16(t.q[(r * nq + hq) * dh + e]); + const at = (r * nq + hq) * dh; + ar.head(qv, ks, vs, n, dh, scale, form(n), w, tau, want[at..][0..dh], hf); + @memcpy(t.half[at..][0..dh], hf); + } + }; + } + + /// The range's half width plus the output's bf16 rounding; gate 4's exact sums allow the rounding alone. + pub fn bounds(t: *Prompt, want: []const f64, _: []const f64, allow: []f64) !void { + for (allow, want, t.half) |*l, w, h| { + if (t.fill == .stress) { + l.* = c.boundExact(spec(), w); + } else if (!std.math.isFinite(w)) { + l.* = 0; + } else if (!std.math.isFinite(h)) { + l.* = std.math.floatMax(f64); // scores too far apart for the range's first order: any finite value + } else l.* = h + 0x1p-8 * (@abs(w) + h) + 0x1p-133; + } + } + + /// Gate 4: the outputs if P x V's sum of the 1,024 values ran in `acc`. + pub fn simulate(t: *Prompt, acc: c.Accum, order: g.Order, out: []f64) !void { + var terms: [stress_on]f64 = undefined; + const kw = kvh * dh; + for (0..t.rows) |r| for (0..nq) |hq| for (0..dh) |e| { + const col = (hq / grp) * dh + e; + for (&terms, 0..) |*x, key| x.* = c.fromBf16(t.v[key * kw + col]); + out[(r * nq + hq) * dh + e] = bf(contract.rows.sumIn(acc, order, &terms) / stress_on); + }; + } +}; diff --git a/zig/tests/contract/metal_minimax_route.zig b/zig/tests/contract/metal_minimax_route.zig new file mode 100644 index 00000000000..8c035631265 --- /dev/null +++ b/zig/tests/contract/metal_minimax_route.zig @@ -0,0 +1,572 @@ +//! MiniMax-M3.1-Flash's router logits and picks under the contract; the rest of routing: metal_minimax_route_*.zig. +const std = @import("std"); +const mtl = @import("metal"); +const contract = @import("contract"); +const sources = @import("kernel_sources"); +const rig_ = @import("rig.zig"); + +const c = contract.spec; +const g = contract.gates; +const Texts = @import("metal_minimax.zig").Texts; +const sort = @import("metal_minimax_route_sort.zig"); +const attn = @import("metal_minimax_route_attn.zig"); + +/// MiniMax-M3.1-Flash's config (config_fixture.json) and the engine's row limits (state.zig). +pub const hidden = 6144; +pub const experts = 128; +pub const topk = 4; +pub const heads = 64; +pub const kv_heads = 4; +pub const head_dim = 128; +pub const index_heads = 4; +pub const rotary = 64; +pub const theta: f32 = 1e7; +pub const eps: f32 = 1e-6; +pub const block = 128; +pub const topk_blocks = 16; +/// Rows a shared decode forward takes at most (the router's picks by route_groups); more take the prompt path. +pub const batch_rows = 32; +pub const prompt_rows = 4096; +/// The longest window the recipes serve: 262,144 tokens, 2,048 index blocks. +pub const context_blocks = 2048; + +/// mm_args (glue.metal). +pub const Args = extern struct { rows: u32 = 0, width: u32 = 0, heads: u32 = 0, dim: u32 = 0, pos: u32 = 0, stride: u32 = 0, bits: u32 = 0, group: u32 = 0, eps: f32 = 0, alpha: f32 = 0, limit: f32 = 0, scale: f32 = 0 }; + +/// One glue.metal kernel compiled as model.zig compiles the library (MLX's language, precise math). +pub fn gluePipe(device: mtl.Device, name: []const u8) !mtl.Pipeline { + const lib = try mtl.Library.fromSource(device, sources.minimax_m3_glue, .{ .language = mtl.CompileOptions.mlx().language, .math_functions = .precise }); + defer lib.deinit(); + return mtl.Pipeline.init(device, lib, name, false); +} + +pub fn noSums(_: c.Shape) usize { + return 0; +} + +/// A value as fp32 then bf16 round it (to nearest even, twice). +pub fn bf(v: f64) f64 { + return c.fromBf16(c.toBf16(@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 mul(a: Range, b: Range) Range { + const p = [_]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])) }; + } + /// Both ranges positive. + pub fn div(a: Range, b: Range) Range { + return .{ .lo = a.lo / b.hi, .hi = a.hi / b.lo }; + } +}; + +/// 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 nan32 = std.math.nan(f32); +pub const inf32 = std.math.inf(f32); + +// --- mm_router: fp32 logits of bf16 rows against the fp32 router matrix, 8 rows and 8 experts a threadgroup ------- + +/// A lane's float4 dots over its k / 1,024 steps (four roundings and the add each), a simd_sum, then 8 simdgroups. +fn routerDepth(s: c.Shape) usize { + return 5 * ((s.k + 1023) / 1024) + 5 + 8; +} + +pub const Router = struct { + a: std.mem.Allocator, + rig: rig_.Rig, + pipe: mtl.Pipeline, + shape: c.Shape = undefined, + x: []u16 = &.{}, + w: []f32 = &.{}, + ins: [2]rig_.Ref = undefined, + out: rig_.Ref = undefined, + + /// Rows: tokens; n: experts; k: the hidden width. + pub fn spec() c.Spec { + return .{ + .name = "metal minimax_m3 mm_router experts 128 hidden 6144", + .accum = .f32, + .depth = routerDepth, + .out = .f32, + .tiles = .{ .{ .size = 8 }, .{ .size = 8, .step = 8, .min = 8 }, .{ .size = 1024, .step = 4, .min = 4 } }, + // a shared decode forward (32 rows), one row, a 4,096-row prompt chunk + .served = &.{ .{ .rows = batch_rows, .n = experts, .k = hidden }, .{ .rows = 1, .n = experts, .k = hidden }, .{ .rows = prompt_rows, .n = experts, .k = hidden } }, + }; + } + + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue) !Router { + return .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .pipe = try gluePipe(device, "mm_router") }; + } + pub fn deinit(t: *Router) void { + t.a.free(t.x); + t.a.free(t.w); + t.rig.deinit(); + t.pipe.deinit(); + } + pub fn kernel(t: *Router) g.Kernel { + return .{ .spec = spec(), .ctx = t, .vt = &vt }; + } + const vt = g.hooks(Router); + + pub fn prepare(t: *Router, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.rows == 0 or shape.n % 8 != 0 or shape.n == 0 or shape.k % 4 != 0 or shape.k == 0) return false; + t.rig.reset(); + t.a.free(t.x); + t.a.free(t.w); + t.shape = shape; + const k = shape.k; + t.x = try t.a.alloc(u16, shape.rows * k); + t.w = try t.a.alloc(f32, shape.n * k); + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + for (t.x, 0..) |*v, i| v.* = c.toBf16((rng.float(f32) * 2 - 1) * (if (i % 64 == 7) @as(f32, 20) else 1)); + for (t.w) |*v| v.* = (rng.float(f32) * 2 - 1) * 0.05; + switch (fill) { + .random => {}, + .nonfinite => { + const at = [_][2]usize{ .{ 0, k / 3 }, .{ 1, k / 2 }, .{ 2, k - 1 }, .{ 3, 0 }, .{ 3, k - 1 } }; + const put = [_]f32{ nan32, inf32, -inf32, inf32, -inf32 }; + for (at, put) |p, v| if (p[0] < shape.rows) { + t.x[p[0] * k + p[1]] = c.toBf16(v); + }; + if (shape.rows > 4) t.w[1 * k + 5] = nan32; // expert 1 is NaN for every row + }, + .stress => { + // integer terms, the second half mirroring the first (8 nudged by one): partials near 2^20, small sums + const h = k / 2; + for (0..shape.rows) |r| for (0..h) |i| { + const v: f32 = @floatFromInt(1 + rng.uintLessThan(u32, 64)); + t.x[r * k + i] = c.toBf16(v); + t.x[r * k + h + i] = c.toBf16(v + @as(f32, if (i < 8) 1 else 0)); + }; + for (0..shape.n) |e| for (0..h) |i| { + const w: f32 = @floatFromInt(1 + rng.uintLessThan(u32, 7)); + t.w[e * k + i] = w; + t.w[e * k + h + i] = -w; + }; + }, + } + t.ins[0] = try t.rig.input(std.mem.sliceAsBytes(t.x)); + t.ins[1] = try t.rig.input(std.mem.sliceAsBytes(t.w)); + t.out = try t.rig.output(shape.rows * shape.n * 4); + return true; + } + + pub fn run(t: *Router) !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(Args{ .rows = @intCast(t.shape.rows), .width = @intCast(t.shape.k), .heads = @intCast(t.shape.n) }, 2); + p.e.setBuffer(t.out.buf, t.out.off, 3); + p.e.dispatchGroups(mtl.Size.of(t.shape.n / 8, (t.shape.rows + 7) / 8, 1), mtl.Size.of(256, 1, 1)); + try t.rig.finish(p); + } + + pub fn count(t: *Router) usize { + return t.shape.rows * t.shape.n; + } + + fn terms(t: *Router, r: usize, e: usize, out: []f64) void { + const k = t.shape.k; + for (out, 0..) |*o, d| o.* = @as(f64, c.fromBf16(t.x[r * k + d])) * t.w[e * k + d]; + } + + pub fn reference(t: *Router, want: []f64, mag: []f64) !void { + const buf = try t.a.alloc(f64, t.shape.k); + defer t.a.free(buf); + for (0..t.shape.rows) |r| for (0..t.shape.n) |e| { + t.terms(r, e, buf); + var s: f64 = 0; + var m: f64 = 0; + for (buf) |v| { + s += v; + m += @abs(v); + } + want[r * t.shape.n + e] = s; + mag[r * t.shape.n + e] = if (std.math.isFinite(m)) m else 0; + }; + } + + pub fn simulate(t: *Router, acc: c.Accum, order: g.Order, out: []f64) !void { + const buf = try t.a.alloc(f64, t.shape.k); + defer t.a.free(buf); + for (0..t.shape.rows) |r| for (0..t.shape.n) |e| { + t.terms(r, e, buf); + out[r * t.shape.n + e] = contract.rows.sumIn(acc, order, buf); + }; + } +}; + +// --- mm_route_pick and mm_route_groups: sigmoid scores, top 4 of score + bias, weights = score / their sum --------- + +/// Picks a row's experts in descending score + bias (ties to the lower id), never one whose choice is NaN. +fn hostPicks(scores: []const f64, bias: []const f32, out: *[topk]u32) void { + var used: [experts]bool = @splat(false); + for (out) |*o| { + var best: usize = experts; + var bv: f64 = -std.math.inf(f64); + for (scores, 0..) |s, i| { + const ch = s + bias[i]; + if (used[i] or std.math.isNan(ch)) continue; + if (best == experts or ch > bv) { + best = i; + bv = ch; + } + } + used[best] = true; + o.* = @intCast(best); + } + std.mem.sort(u32, out, {}, std.sort.asc(u32)); +} + +/// The kernel's sigmoid in float64: y = 1 / (1 + e^-|x|), e^-|x| y for x < 0; an infinity scores 1 or 0. +fn sigmoid(x: f64) f64 { + if (std.math.isNan(x)) return x; + const e = @exp(-@abs(x)); + const y = 1 / (1 + e); + return if (x < 0) e * y else y; +} + +/// Its fp32 spread: precise exp (4 ulps), the add, the division (3 ulps), and e y's rounding for x < 0. +fn sigmoidRange(x: f64) Range { + if (std.math.isInf(x)) return Range.point(if (x > 0) 1 else 0); + const e = Range.point(@exp(-@abs(x))).fp32(4); + const den = e.add(Range.point(1)).fp32(1); + const y = Range.point(1).div(den).fp32(3); + return if (x < 0) e.mul(y).fp32(1) else y; +} + +pub const Pick = struct { + a: std.mem.Allocator, + rig: rig_.Rig, + pipe: mtl.Pipeline, + /// mm_route_groups: one threadgroup picks every row, then lists the slots by expert (experts.metal's G and M). + groups: bool, + rows: usize = 0, + logits: []f32 = &.{}, + bias: []f32 = &.{}, + ins: [2]rig_.Ref = undefined, + /// The weights first (gate 4 reads them as fp32), then the picks, then G and M for route_groups. + outs: [4]rig_.Ref = undefined, + msg: [200]u8 = undefined, + + pub fn spec(groups: bool) c.Spec { + return .{ + .name = if (groups) "metal minimax_m3 mm_route_groups experts 128 top 4 sigmoid, slots by expert" else "metal minimax_m3 mm_route_pick experts 128 top 4 sigmoid", + .accum = .f32, + .depth = pickDepth, + .out = .f32, + .nan = .{ .stated = "the picks equal the host's top 4 of score + bias, ties to the lower id; a NaN logit's expert is never picked, +Inf scores 1 and -Inf 0; each weight lies in float64's range through its fp32 steps" }, + .tiles = .{ if (groups) .{ .size = batch_rows } else .{}, .{}, .{} }, + .served = if (groups) + &.{ .{ .rows = batch_rows, .n = topk, .k = experts }, .{ .rows = 16, .n = topk, .k = experts }, .{ .rows = 1, .n = topk, .k = experts } } + else + &.{ .{ .rows = prompt_rows, .n = topk, .k = experts }, .{ .rows = batch_rows + 1, .n = topk, .k = experts } }, + // the weights divide by a sum of 4 scores in (0, 1]; fp16 and bf16 sums miss it at the weights' fp32 output + .sums = .{ .exact = false }, + }; + } + + fn pickDepth(_: c.Shape) usize { + return topk; + } + + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, groups: bool) !Pick { + return .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .pipe = try gluePipe(device, if (groups) "mm_route_groups" else "mm_route_pick"), .groups = groups }; + } + pub fn deinit(t: *Pick) void { + t.a.free(t.logits); + t.a.free(t.bias); + t.rig.deinit(); + t.pipe.deinit(); + } + pub fn kernel(t: *Pick) g.Kernel { + return .{ .spec = spec(t.groups), .ctx = t, .vt = &vt }; + } + const vt = g.hooks(Pick); + + /// Logits and biases from small discrete sets: exact ties occur, and distinct choices differ by far more than fp32. + fn row(rng: std.Random, z: []f32) void { + for (z) |*v| v.* = @as(f32, @floatFromInt(rng.intRangeAtMost(i32, -40, 40))) / 8; + } + + /// Whether row r's distinct choices stay at least 1e-4 apart (else the host's float64 order may differ from fp32). + fn separated(t: *Pick, r: usize) bool { + var ch: [experts]f64 = undefined; + for (&ch, 0..) |*v, i| v.* = sigmoid(t.logits[r * experts + i]) + t.bias[i]; + for (0..experts) |i| for (i + 1..experts) |j| { + const same = t.logits[r * experts + i] == t.logits[r * experts + j] and t.bias[i] == t.bias[j]; + if (!same and @abs(ch[i] - ch[j]) < 1e-4) return false; + }; + return true; + } + + pub fn prepare(t: *Pick, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.rows == 0 or shape.n != topk or shape.k != experts) return false; + if (t.groups and shape.rows > batch_rows) return false; + t.rig.reset(); + t.a.free(t.logits); + t.a.free(t.bias); + t.rows = shape.rows; + t.logits = try t.a.alloc(f32, shape.rows * experts); + t.bias = try t.a.alloc(f32, experts); + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + // the release's correction biases are small; a few experts share one value so ties reach the picks + for (t.bias) |*v| v.* = @as(f32, @floatFromInt(rng.intRangeAtMost(i32, -3, 3))) / 32; + for (0..shape.rows) |r| { + const z = t.logits[r * experts ..][0..experts]; + var tries: usize = 0; + while (true) : (tries += 1) { + row(rng, z); + if (fill == .stress) { + // four leaders far above the rest at one logit each: the weights' sum is 4 scores of 0.99... + for (z) |*v| v.* = -6; + for (0..topk) |k| z[(r * 7 + k * 29) % experts] = 5 + @as(f32, @floatFromInt(k)) / 8; + } + if (fill == .stress or t.separated(r) or tries > 64) break; + } + } + if (fill == .nonfinite) { + // NaN on row 0's expert 3 (never picked), +Inf on row 1's expert 9 (scores 1), -Inf on half of row 2 (0) + const puts = [_][3]usize{ .{ 0, 3, 0 }, .{ 1, 9, 1 }, .{ 2, 0, 2 } }; + for (puts) |p| if (p[0] < shape.rows) { + const z = t.logits[p[0] * experts ..][0..experts]; + switch (p[2]) { + 0 => z[p[1]] = nan32, + 1 => z[p[1]] = inf32, + else => for (0..experts / 2) |i| { + z[i] = -inf32; + }, + } + }; + } + t.ins[0] = try t.rig.input(std.mem.sliceAsBytes(t.logits)); + t.ins[1] = try t.rig.input(std.mem.sliceAsBytes(t.bias)); + const slots = shape.rows * topk; + t.outs[0] = try t.rig.output(slots * 4); + t.outs[1] = try t.rig.output(slots * 4); + if (t.groups) { + t.outs[2] = try t.rig.output((1 + 2 * experts) * 4); + t.outs[3] = try t.rig.output(slots * 4); + } + return true; + } + + pub fn run(t: *Pick) !void { + const p = t.rig.begin(); + const e = p.e; + e.setPipeline(t.pipe); + e.setBuffer(t.ins[0].buf, t.ins[0].off, 0); + e.setBuffer(t.ins[1].buf, t.ins[1].off, 1); + e.setValue(Args{ .rows = @intCast(t.rows), .width = experts, .heads = topk }, 2); + e.setBuffer(t.outs[1].buf, t.outs[1].off, 3); + e.setBuffer(t.outs[0].buf, t.outs[0].off, 4); + if (t.groups) { + e.setBuffer(t.outs[2].buf, t.outs[2].off, 5); + e.setBuffer(t.outs[3].buf, t.outs[3].off, 6); + e.dispatchGroups(mtl.Size.of(1, 1, 1), mtl.Size.of(32 * t.rows, 1, 1)); + } else e.dispatchGroups(mtl.Size.of(t.rows, 1, 1), mtl.Size.of(32, 1, 1)); + try t.rig.finish(p); + } + + /// The weights; the picks, G and M are checked by `check`. + pub fn count(t: *Pick) usize { + return t.rows * topk; + } + + fn scores(t: *Pick, r: usize, out: *[experts]f64) void { + for (out, 0..) |*s, i| s.* = sigmoid(t.logits[r * experts + i]); + } + + /// Row r's picks (ascending id), and its weights from the 4 scores' sum `total`. + fn rowRef(t: *Pick, r: usize, ids: *[topk]u32, total: ?f64, out: []f64) void { + var s: [experts]f64 = undefined; + t.scores(r, &s); + hostPicks(&s, t.bias, ids); + var sum: f64 = 0; + for (ids) |i| sum += s[i]; + for (out[0..topk], ids) |*w, i| w.* = s[i] / (total orelse sum); + } + + pub fn reference(t: *Pick, want: []f64, mag: []f64) !void { + for (0..t.rows) |r| { + var ids: [topk]u32 = undefined; + t.rowRef(r, &ids, null, want[r * topk ..][0..topk]); + } + for (mag, want) |*m, w| m.* = @abs(w); + } + + pub fn intervals(t: *Pick, low: []f64, high: []f64) !void { + for (0..t.rows) |r| { + var s: [experts]f64 = undefined; + t.scores(r, &s); + var ids: [topk]u32 = undefined; + hostPicks(&s, t.bias, &ids); + var ranges: [topk]Range = undefined; + var sum = Range.point(0); + for (&ranges, ids) |*v, i| { + v.* = sigmoidRange(t.logits[r * experts + i]); + sum = sum.add(v.*); + } + sum = sum.fp32(c.gamma(topk, c.unit(.f32)) / c.unit(.f32)); + for (ranges, 0..) |v, k| { + const w = if (sum.lo > 0) v.div(sum).fp32(3) else Range.point(0); + low[r * topk + k] = w.lo; + high[r * topk + k] = w.hi; + } + } + } + + pub fn bounds(t: *Pick, 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.* = spread(w, .{ .lo = lo, .hi = hi }); + } + + pub fn simulate(t: *Pick, acc: c.Accum, order: g.Order, out: []f64) !void { + for (0..t.rows) |r| { + var s: [experts]f64 = undefined; + t.scores(r, &s); + var ids: [topk]u32 = undefined; + hostPicks(&s, t.bias, &ids); + var picked: [topk]f64 = undefined; + for (&picked, ids) |*v, i| v.* = s[i]; + t.rowRef(r, &ids, contract.rows.sumIn(acc, order, &picked), out[r * topk ..][0..topk]); + } + } + + /// The picks bit for bit, every weight in its range, and route_groups' G and M as experts.metal reads them. + pub fn check(t: *Pick, _: g.Gate) !?[]const u8 { + const slots = t.rows * topk; + const picks = std.mem.bytesAsSlice(i32, t.rig.bytes(t.outs[1], slots * 4)); + const wts = std.mem.bytesAsSlice(f32, t.rig.bytes(t.outs[0], slots * 4)); + const lim = try t.a.alloc(f64, 2 * slots); + defer t.a.free(lim); + try t.intervals(lim[0..slots], lim[slots..]); + var all = try t.a.alloc(u32, slots); + defer t.a.free(all); + for (0..t.rows) |r| { + var s: [experts]f64 = undefined; + t.scores(r, &s); + var ids: [topk]u32 = undefined; + hostPicks(&s, t.bias, &ids); + for (ids, 0..) |id, k| { + const at = r * topk + k; + all[at] = id; + if (picks[at] != @as(i32, @intCast(id))) return try std.fmt.bufPrint(&t.msg, "row {d}'s pick {d} is expert {d} where the host picks {d}", .{ r, k, picks[at], id }); + const w: f64 = wts[at]; + if (!(w >= lim[at] and w <= lim[slots + at])) return try std.fmt.bufPrint(&t.msg, "row {d}'s weight {d} is {e:.8} outside [{e:.8}, {e:.8}]", .{ r, k, w, lim[at], lim[slots + at] }); + } + } + if (!t.groups) return null; + // G: the experts picked, ascending, each with its first member in M; M: the slots by expert, ascending + const gw = std.mem.bytesAsSlice(u32, t.rig.bytes(t.outs[2], (1 + 2 * experts) * 4)); + const mw = std.mem.bytesAsSlice(u32, t.rig.bytes(t.outs[3], slots * 4)); + var n: u32 = 0; + var at: u32 = 0; + for (0..experts) |e| { + var first = true; + for (all, 0..) |id, sl| if (id == e) { + if (first) { + if (gw[1 + 2 * n] != e or gw[2 + 2 * n] != at) return try std.fmt.bufPrint(&t.msg, "G's group {d} is ({d}, {d}) where the host has ({d}, {d})", .{ n, gw[1 + 2 * n], gw[2 + 2 * n], e, at }); + n += 1; + first = false; + } + if (mw[at] != sl) return try std.fmt.bufPrint(&t.msg, "M[{d}] is slot {d} where the host has {d}", .{ at, mw[at], sl }); + at += 1; + }; + } + if (gw[0] != n) return try std.fmt.bufPrint(&t.msg, "G counts {d} experts where the host has {d}", .{ gw[0], n }); + return null; + } +}; + +pub const Suite = struct { + a: std.mem.Allocator, + device: mtl.Device, + queue: mtl.Queue, + kernels: *std.ArrayList(g.Kernel), + router: ?*Router = null, + picks: std.ArrayList(*Pick) = .empty, + rest: sort.Group = .{}, + attn: attn.Group = .{}, + + fn wanted(only: ?[]const u8, name: []const u8) bool { + const o = only orelse return true; + return std.mem.indexOf(u8, name, o) != null; + } + + pub fn collect(s: *Suite, only: ?[]const u8) !void { + if (wanted(only, Router.spec().name)) { + s.router = try s.a.create(Router); + s.router.?.* = try Router.init(s.a, s.device, s.queue); + try s.kernels.append(s.a, s.router.?.kernel()); + } + for ([_]bool{ false, true }) |groups| { + if (!wanted(only, Pick.spec(groups).name)) continue; + const x = try s.a.create(Pick); + x.* = try Pick.init(s.a, s.device, s.queue, groups); + try s.picks.append(s.a, x); + try s.kernels.append(s.a, x.kernel()); + } + try s.rest.collect(s.a, s.device, s.queue, only, s.kernels); + try s.attn.collect(s.a, s.device, s.queue, only, s.kernels); + } + pub fn deinit(s: *Suite) void { + if (s.router) |x| { + x.deinit(); + s.a.destroy(x); + } + for (s.picks.items) |x| { + x.deinit(); + s.a.destroy(x); + } + s.picks.deinit(s.a); + s.rest.deinit(s.a); + s.attn.deinit(s.a); + } +}; + +/// Gate 5's texts for this group's registrations (`minimax_m3 route ...`): glue.metal as model.zig compiles it. +pub fn limitsText(a: std.mem.Allocator, device: mtl.Device, name: []const u8) !?Texts { + _ = a; + _ = device; + if (!std.mem.startsWith(u8, name, "minimax_m3 route ")) return null; + return .{ .here = sources.minimax_m3_glue, .pre_m5 = sources.minimax_m3_glue }; +} + +test "the host's picks: top 4 of score + bias ascending, ties to the lower id, NaN never" { + var s: [experts]f64 = @splat(0.1); + const b: [experts]f32 = @splat(0); + s[9] = 0.9; + s[3] = std.math.nan(f64); + s[70] = 0.5; + s[40] = 0.5; + var ids: [topk]u32 = undefined; + hostPicks(&s, &b, &ids); + try std.testing.expectEqualSlices(u32, &.{ 0, 9, 40, 70 }, &ids); +} diff --git a/zig/tests/contract/metal_minimax_route_attn.zig b/zig/tests/contract/metal_minimax_route_attn.zig new file mode 100644 index 00000000000..0b148a01206 --- /dev/null +++ b/zig/tests/contract/metal_minimax_route_attn.zig @@ -0,0 +1,468 @@ +//! MiniMax-M3.1-Flash's q/k preparation (mm_prep) and the indexer's decode scores (mm_index_scores) under the contract. +const std = @import("std"); +const mtl = @import("metal"); +const contract = @import("contract"); +const rig_ = @import("rig.zig"); +const r = @import("metal_minimax_route.zig"); +const sel = @import("metal_minimax_route_sort.zig"); +const decode = @import("metal_minimax_route_decode.zig"); + +const c = contract.spec; +const g = contract.gates; +const Range = r.Range; +const bf = r.bf; +const D = r.head_dim; +const u = 0x1p-24; + +// --- mm_prep: each head's Gemma norm and NeoX rotary of its first 64 dims; keys, values and index keys cached ------ + +/// mm_prep_args (glue.metal). +const PArgs = extern struct { rows: u32, heads: u32, kv_heads: u32, index_heads: u32, dim: u32, pos: u32, rotary: u32, stride: u32, eps: f32, theta: f32 }; + +/// A row's projection: q heads, k heads, v heads, index q heads, the index key (config.qkvRows()). +const stride = (r.heads + 2 * r.kv_heads + r.index_heads + 1) * D; +/// Heads a row prepares: q, k, index q and the index key (the values are copied with the keys). +const units = r.heads + r.kv_heads + r.index_heads + 1; + +/// Four squares a lane in one fma chain, then simd_sum's five levels. +fn prepDepth(_: c.Shape) usize { + return 4 + 5; +} + +pub const Prep = struct { + a: std.mem.Allocator, + rig: rig_.Rig, + pipe: mtl.Pipeline, + rows: usize = 0, + pos: usize = 0, + x: []u16 = &.{}, + w: [4][D]u16 = undefined, + ins: [5]rig_.Ref = undefined, + /// QN and IQ (the outputs gate 4 reads), then the caches' slots as scratch: KC, VC, IK. + outs: [2]rig_.Ref = undefined, + cache: [3]rig_.Ref = undefined, + msg: [240]u8 = undefined, + + /// Rows: query rows; n: query heads; k: the first row's position (its cache slot). + pub fn spec() c.Spec { + return .{ + .name = "metal minimax_m3 mm_prep q/k norms and rotary, 64 + 4 + 4 + 1 heads of 128", + .accum = .f32, + .depth = prepDepth, + .out = .bf16, + .nan = .{ .stated = "every output in float64's range through the kernel's fp32 steps and bf16 points (NaN where float64 gives NaN), the values copied bit for bit, the caches' slots before the first row untouched" }, + .tiles = .{ .{ .size = 16 }, .{}, .{} }, + // a decode window near the longest window, one row, a prompt chunk, a row at position 0 + .served = &.{ .{ .rows = 16, .n = r.heads, .k = 262000 }, .{ .rows = 1, .n = r.heads, .k = 131071 }, .{ .rows = r.prompt_rows, .n = r.heads, .k = 8192 }, .{ .rows = 1, .n = r.heads, .k = 0 } }, + }; + } + + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue) !Prep { + return .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .pipe = try r.gluePipe(device, "mm_prep") }; + } + pub fn deinit(t: *Prep) void { + t.a.free(t.x); + t.rig.deinit(); + t.pipe.deinit(); + } + pub fn kernel(t: *Prep) g.Kernel { + return .{ .spec = spec(), .ctx = t, .vt = &vt }; + } + const vt = g.hooks(Prep); + + pub fn prepare(t: *Prep, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.rows == 0 or shape.n != r.heads) return false; + t.rig.reset(); + t.a.free(t.x); + t.rows = shape.rows; + t.pos = shape.k; + t.x = try t.a.alloc(u16, shape.rows * stride); + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + for (t.x, 0..) |*v, i| v.* = c.toBf16(switch (fill) { + // integers whose squares sum exactly in fp32 and pass fp16's range in any order + .stress => @as(f32, @floatFromInt(rng.intRangeAtMost(i32, 32, 96))) * @as(f32, if (rng.boolean()) 1 else -1), + else => (rng.float(f32) * 2 - 1) * (if (i % 64 == 7) @as(f32, 12) else 1), + }); + for (&t.w) |*w| for (w) |*v| { + v.* = c.toBf16(rng.float(f32) - 0.5); + }; + if (fill == .nonfinite) { + // NaN in row 0's q head 0, +Inf in row 1's key head 1 (rotated), -Inf in row 2's index key (unrotated) + const put = [_][2]usize{ .{ 0, 5 }, .{ 1, (r.heads + 1) * D + 3 }, .{ 2, (r.heads + 2 * r.kv_heads + r.index_heads) * D + 100 }, .{ 3, (r.heads + r.kv_heads + 2) * D + 9 } }; + const val = [_]f32{ r.nan32, r.inf32, -r.inf32, r.nan32 }; + for (put, val) |p, v| if (p[0] < shape.rows) { + t.x[p[0] * stride + p[1]] = c.toBf16(v); + }; + } + t.ins[0] = try t.rig.input(std.mem.sliceAsBytes(t.x)); + for (1..5) |i| t.ins[i] = try t.rig.input(std.mem.sliceAsBytes(&t.w[i - 1])); + t.outs[0] = try t.rig.output(shape.rows * r.heads * D * 2); + t.outs[1] = try t.rig.output(shape.rows * r.index_heads * D * 2); + const slots = t.pos + shape.rows; + t.cache[0] = try t.rig.scratch(slots * r.kv_heads * D * 2); + t.cache[1] = try t.rig.scratch(slots * r.kv_heads * D * 2); + t.cache[2] = try t.rig.scratch(slots * D * 2); + return true; + } + + pub fn run(t: *Prep) !void { + const p = t.rig.begin(); + const e = p.e; + e.setPipeline(t.pipe); + for (t.ins, 0..) |ref, i| e.setBuffer(ref.buf, ref.off, i); + e.setValue(PArgs{ .rows = @intCast(t.rows), .heads = r.heads, .kv_heads = r.kv_heads, .index_heads = r.index_heads, .dim = D, .pos = @intCast(t.pos), .rotary = r.rotary, .stride = stride, .eps = r.eps, .theta = r.theta }, 5); + e.setBuffer(t.outs[0].buf, t.outs[0].off, 6); + e.setBuffer(t.outs[1].buf, t.outs[1].off, 7); + e.setBuffer(t.cache[0].buf, t.cache[0].off, 8); + e.setBuffer(t.cache[1].buf, t.cache[1].off, 9); + e.setBuffer(t.cache[2].buf, t.cache[2].off, 10); + e.dispatchGroups(mtl.Size.of(units, t.rows, 1), mtl.Size.of(32, 1, 1)); + try t.rig.finish(p); + } + + /// QN and IQ; the caches' slots are checked by `check`. + pub fn count(t: *Prep) usize { + return t.rows * (r.heads + r.index_heads) * D; + } + + /// Unit `unit` of row `row`: its source offset in the row and its norm weight. + fn unitOf(unit: usize) struct { src: usize, w: usize } { + if (unit < r.heads) return .{ .src = unit * D, .w = 0 }; + if (unit < r.heads + r.kv_heads) return .{ .src = unit * D, .w = 1 }; + if (unit < r.heads + r.kv_heads + r.index_heads) return .{ .src = (unit + r.kv_heads) * D, .w = 2 }; + return .{ .src = (r.heads + 2 * r.kv_heads + r.index_heads) * D, .w = 3 }; + } + + /// One unit's outputs: float64 at the kernel's bf16 points (`sumsq`: gate 4's sum of squares), and each's range. + fn unitRef(t: *Prep, row: usize, unit: usize, sumsq: ?f64, point: *[D]f64, range: ?*[D]Range) void { + const o = unitOf(unit); + const v = t.x[row * stride + o.src ..][0..D]; + const w = &t.w[o.w]; + var s: f64 = 0; + for (v) |x| s += @as(f64, c.fromBf16(x)) * c.fromBf16(x); + if (sumsq) |x| s = x; + const inv = 1 / @sqrt(s / D + r.eps); + // the sum's chain (all terms positive, so relative), the eps add, precise rsqrt (2 ulps), the two products + const rel = 0.5 * (c.gamma(@floatFromInt(prepDepth(.{ .rows = 1, .n = 1, .k = 1 })), u) + u) + 2 * u + 3 * u + u; + var nrm: [D]f64 = undefined; + var nr: [D]Range = undefined; + for (0..D) |d| { + const x: f64 = c.fromBf16(v[d]); + const gain = 1 + @as(f64, c.fromBf16(w[d])); + nrm[d] = bf(x * inv * gain); + const val = x * inv * gain; + nr[d] = if (std.math.isFinite(val)) (Range{ .lo = val - rel * @abs(val), .hi = val + rel * @abs(val) }).bf16() else Range.point(val); + } + const half_r = r.rotary / 2; + const position: f64 = @floatFromInt(t.pos + row); + for (0..D) |d| { + if (d >= r.rotary) { + point[d] = nrm[d]; + if (range) |rg| rg[d] = nr[d]; + continue; + } + const i = d % half_r; + const freq = 1 / std.math.pow(f64, r.theta, @as(f64, @floatFromInt(2 * i)) / r.rotary); + const angle = position * freq; + const cs = bf(@cos(angle)); + const sn = bf(@sin(angle)); + const rot = if (d < half_r) -nrm[d + half_r] else nrm[d - half_r]; + point[d] = bf(bf(nrm[d] * cs) + bf(rot * sn)); + if (range) |rg| { + // precise pow (16 ulps) and the division, the fp32 angle, precise cos and sin (4 ulps), bf16 points + const f = Range.point(freq).fp32(17); + const ang = (Range{ .lo = position * f.lo, .hi = position * f.hi }).fp32(1); + const rr = if (d < half_r) Range{ .lo = -nr[d + half_r].hi, .hi = -nr[d + half_r].lo } else nr[d - half_r]; + const a1 = Range.mul(nr[d], trig(ang, false).fp32(4).bf16()).fp32(1).bf16(); + const a2 = Range.mul(rr, trig(ang, true).fp32(4).bf16()).fp32(1).bf16(); + rg[d] = a1.add(a2).fp32(1).bf16(); + } + } + } + + pub fn reference(t: *Prep, want: []f64, mag: []f64) !void { + var pt: [D]f64 = undefined; + for (0..t.rows) |row| for (0..r.heads + r.index_heads) |h| { + const unit = if (h < r.heads) h else h + r.kv_heads; + t.unitRef(row, unit, null, &pt, null); + @memcpy(want[outAt(t.rows, row, h)..][0..D], &pt); + }; + for (mag, want) |*m, w| m.* = if (std.math.isFinite(w)) @abs(w) else 0; + } + + /// Where row `row`'s head `h` (q heads, then index q heads) lies among the outputs. + fn outAt(rows: usize, row: usize, h: usize) usize { + return if (h < r.heads) (row * r.heads + h) * D else rows * r.heads * D + (row * r.index_heads + h - r.heads) * D; + } + + pub fn bounds(t: *Prep, want: []const f64, _: []const f64, allow: []f64) !void { + var pt: [D]f64 = undefined; + var rg: [D]Range = undefined; + for (0..t.rows) |row| for (0..r.heads + r.index_heads) |h| { + t.unitRef(row, if (h < r.heads) h else h + r.kv_heads, null, &pt, &rg); + const at = outAt(t.rows, row, h); + for (0..D) |d| allow[at + d] = if (std.math.isFinite(want[at + d])) r.spread(want[at + d], rg[d]) else 0; + }; + } + + pub fn simulate(t: *Prep, acc: c.Accum, order: g.Order, out: []f64) !void { + var sq: [D]f64 = undefined; + var pt: [D]f64 = undefined; + for (0..t.rows) |row| for (0..r.heads + r.index_heads) |h| { + const unit = if (h < r.heads) h else h + r.kv_heads; + const v = t.x[row * stride + unitOf(unit).src ..][0..D]; + for (&sq, v) |*s, x| s.* = @as(f64, c.fromBf16(x)) * c.fromBf16(x); + t.unitRef(row, unit, contract.rows.sumIn(acc, order, &sq), &pt, null); + @memcpy(out[outAt(t.rows, row, h)..][0..D], &pt); + }; + } + + /// Whether bf16 `got` lies in `rg` (NaN where float64 gives NaN, infinities by value). + fn holds(point: f64, rg: Range, got: f64) bool { + if (std.math.isNan(point)) return std.math.isNan(got); + if (std.math.isInf(point)) return got == point; + return got >= rg.lo and got <= rg.hi; + } + + pub fn check(t: *Prep, _: g.Gate) !?[]const u8 { + const nk = r.kv_heads; + const qn = t.rig.bytes(t.outs[0], t.rows * r.heads * D * 2); + const iq = t.rig.bytes(t.outs[1], t.rows * r.index_heads * D * 2); + const kc = t.rig.bytes(t.cache[0], (t.pos + t.rows) * nk * D * 2); + const vc = t.rig.bytes(t.cache[1], (t.pos + t.rows) * nk * D * 2); + const ik = t.rig.bytes(t.cache[2], (t.pos + t.rows) * D * 2); + var pt: [D]f64 = undefined; + var rg: [D]Range = undefined; + for (0..t.rows) |row| { + const slot = t.pos + row; + for (0..units) |unit| { + t.unitRef(row, unit, null, &pt, &rg); + const got = if (unit < r.heads) + qn[(row * r.heads + unit) * D * 2 ..] + else if (unit < r.heads + nk) + kc[(slot * nk + unit - r.heads) * D * 2 ..] + else if (unit < units - 1) + iq[(row * r.index_heads + unit - r.heads - nk) * D * 2 ..] + else + ik[slot * D * 2 ..]; + for (0..D) |d| { + const v = c.read(.bf16, got, d); + if (!holds(pt[d], rg[d], v)) return try std.fmt.bufPrint(&t.msg, "row {d} (position {d}) unit {d} dim {d} is {e:.6} outside [{e:.6}, {e:.6}] (float64 {e:.6})", .{ row, slot, unit, d, v, rg[d].lo, rg[d].hi, pt[d] }); + } + } + for (0..nk) |h| { + const want = std.mem.sliceAsBytes(t.x[row * stride + (r.heads + nk + h) * D ..][0..D]); + if (!std.mem.eql(u8, vc[(slot * nk + h) * D * 2 ..][0 .. D * 2], want)) return try std.fmt.bufPrint(&t.msg, "row {d}'s value head {d} is not its projection's bits", .{ row, h }); + } + } + // the slot before the first row keeps the rig's pattern: nothing writes past the chunk's own slots + if (t.pos > 0) for ([_][]const u8{ kc[(t.pos - 1) * nk * D * 2 ..][0 .. nk * D * 2], vc[(t.pos - 1) * nk * D * 2 ..][0 .. nk * D * 2], ik[(t.pos - 1) * D * 2 ..][0 .. D * 2] }) |b| { + for (b) |x| if (x != 0xa5) return try std.fmt.bufPrint(&t.msg, "a cache slot before position {d} was written", .{t.pos}); + }; + return null; + } +}; + +/// cos (or sin) over an angle's range: the ends, and +-1 where the range holds a peak. +fn trig(a: Range, sine: bool) Range { + const f = struct { + fn of(x: f64, s: bool) f64 { + return if (s) @sin(x) else @cos(x); + } + }; + var lo = @min(f.of(a.lo, sine), f.of(a.hi, sine)); + var hi = @max(f.of(a.lo, sine), f.of(a.hi, sine)); + // peaks of cos at k pi (sin: k pi + pi / 2): +1 for even k, -1 for odd + const shift: f64 = if (sine) std.math.pi / 2.0 else 0; + var k = @ceil((a.lo - shift) / std.math.pi); + while (k * std.math.pi + shift <= a.hi) : (k += 1) { + if (@mod(k, 2) == 0) hi = 1 else lo = -1; + } + return .{ .lo = lo - 0x1p-149, .hi = hi + 0x1p-149 }; +} + +// --- mm_index_scores: each (row, index head, block)'s max of q . k over the block's keys up to the row ----------- + +/// Each key's 16 steps of two float4 dots (four roundings each), their add and the running add. +fn scoreDepth(_: c.Shape) usize { + return 16 * 10; +} + +pub const Scores = struct { + a: std.mem.Allocator, + rig: rig_.Rig, + pipe: mtl.Pipeline, + rows: usize = 0, + blocks: usize = 0, + pos: usize = 0, + q: []u16 = &.{}, + k: []u16 = &.{}, + ins: [2]rig_.Ref = undefined, + out: rig_.Ref = undefined, + + /// Rows: decode rows; n: the index blocks their keys span; k: the index head dim. + pub fn spec() c.Spec { + return .{ + .name = "metal minimax_m3 mm_index_scores index heads 4 of 128, blocks of 128", + .accum = .f32, + .depth = scoreDepth, + .out = .f32, + .tiles = .{ .{ .size = 16 }, .{}, .{} }, + // decode windows (the prompt path's scores are the tensor units'): 64 blocks, the longest window, 17, 300 + .served = &.{ .{ .rows = 16, .n = 64, .k = D }, .{ .rows = 16, .n = r.context_blocks, .k = D }, .{ .rows = 1, .n = r.topk_blocks + 1, .k = D }, .{ .rows = r.batch_rows, .n = 300, .k = D } }, + }; + } + + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue) !Scores { + return .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .pipe = try r.gluePipe(device, "mm_index_scores") }; + } + pub fn deinit(t: *Scores) void { + t.a.free(t.q); + t.a.free(t.k); + t.rig.deinit(); + t.pipe.deinit(); + } + pub fn kernel(t: *Scores) g.Kernel { + return .{ .spec = spec(), .ctx = t, .vt = &vt }; + } + const vt = g.hooks(Scores); + + pub fn prepare(t: *Scores, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.rows == 0 or shape.rows > r.batch_rows or shape.k != D) return false; + const pos = sel.startOf(shape.rows, shape.n) orelse return false; + t.rig.reset(); + t.a.free(t.q); + t.a.free(t.k); + t.rows = shape.rows; + t.blocks = shape.n; + t.pos = pos; + const keys = shape.n * r.block; + t.q = try t.a.alloc(u16, shape.rows * r.index_heads * D); + t.k = try t.a.alloc(u16, keys * D); + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + if (fill == .stress) { + // integers, each vector's second half mirroring its first (8 nudged): partials near 2^18, small dots + const h = D / 2; + for (0..shape.rows * r.index_heads) |v| for (0..h) |i| { + const x: f32 = @floatFromInt(1 + rng.uintLessThan(u32, 64)); + t.q[v * D + i] = c.toBf16(x); + t.q[v * D + h + i] = c.toBf16(x + @as(f32, if (i < 8) 1 else 0)); + }; + for (0..keys) |j| for (0..h) |i| { + const x: f32 = @floatFromInt(1 + rng.uintLessThan(u32, 64)); + t.k[j * D + i] = c.toBf16(x); + t.k[j * D + h + i] = c.toBf16(-x); + }; + } else { + // never zero: an infinity times a key's value is +-Inf, not NaN + for (t.q) |*v| v.* = c.toBf16((0.05 + rng.float(f32)) * @as(f32, if (rng.boolean()) 1 else -1)); + for (t.k) |*v| v.* = c.toBf16((0.05 + rng.float(f32)) * @as(f32, if (rng.boolean()) 1 else -1)); + } + if (fill == .nonfinite) { + // NaN in row 0's head 0, +Inf in row 1's head 1, -Inf in row 2's head 2; NaN in one key of block 0 + const put = [_]f32{ r.nan32, r.inf32, -r.inf32 }; + for (put, 0..) |v, i| if (i < shape.rows) { + t.q[(i * r.index_heads + i) * D + 3] = c.toBf16(v); + }; + t.k[17 * D + 40] = c.toBf16(r.nan32); + } + 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.out = try t.rig.output(t.count() * 4); + return true; + } + + pub fn run(t: *Scores) !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(sel.IArgs{ .rows = @intCast(t.rows), .pos = @intCast(t.pos), .heads = r.index_heads, .blocks = @intCast(t.blocks) }, 2); + p.e.setBuffer(t.out.buf, t.out.off, 3); + p.e.dispatchGroups(mtl.Size.of(t.blocks, (t.rows + 15) / 16, 1), mtl.Size.of(128, 1, 1)); + try t.rig.finish(p); + } + + pub fn count(t: *Scores) usize { + return t.rows * r.index_heads * t.blocks; + } + + fn term(t: *Scores, row: usize, h: usize, key: usize, d: usize) f64 { + return @as(f64, c.fromBf16(t.q[(row * r.index_heads + h) * D + d])) * c.fromBf16(t.k[key * D + d]); + } + + /// Each output from each live key's dot (`sum` over its terms): the max (NaN if any is), and the largest magnitude. + fn each(t: *Scores, sum: anytype, want: []f64, mag: ?[]f64) void { + var terms: [D]f64 = undefined; + for (0..t.rows) |row| for (0..r.index_heads) |h| for (0..t.blocks) |j| { + var best = -std.math.inf(f64); + var m: f64 = 0; + const last = @min((j + 1) * r.block, t.pos + row + 1); + var key = j * r.block; + while (key < last) : (key += 1) { + var a: f64 = 0; + for (&terms, 0..) |*x, d| { + x.* = t.term(row, h, key, d); + a += @abs(x.*); + } + const s = sum.of(&terms); + best = if (std.math.isNan(s) or std.math.isNan(best)) std.math.nan(f64) else @max(best, s); + if (std.math.isFinite(a)) m = @max(m, a); + } + const at = (row * r.index_heads + h) * t.blocks + j; + want[at] = best; + if (mag) |x| x[at] = m; + }; + } + + const Exact = struct { + fn of(_: Exact, v: []const f64) f64 { + var s: f64 = 0; + for (v) |x| s += x; + return s; + } + }; + + pub fn reference(t: *Scores, want: []f64, mag: []f64) !void { + t.each(Exact{}, want, mag); + } + + pub fn simulate(t: *Scores, acc: c.Accum, order: g.Order, out: []f64) !void { + const In = struct { + acc: c.Accum, + order: g.Order, + fn of(x: @This(), v: []const f64) f64 { + return contract.rows.sumIn(x.acc, x.order, v); + } + }; + t.each(In{ .acc = acc, .order = order }, out, null); + } +}; + +/// This file's and the decode file's kernels in the suite. +pub const Group = struct { + prep: ?*Prep = null, + scores: ?*Scores = null, + decode: decode.Group = .{}, + + pub fn collect(s: *Group, a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, only: ?[]const u8, kernels: *std.ArrayList(g.Kernel)) !void { + inline for (.{ .{ "prep", Prep }, .{ "scores", Scores } }) |e| { + if (only == null or std.mem.indexOf(u8, e[1].spec().name, only.?) != null) { + const x = try a.create(e[1]); + x.* = try e[1].init(a, device, queue); + @field(s, e[0]) = x; + try kernels.append(a, x.kernel()); + } + } + try s.decode.collect(a, device, queue, only, kernels); + } + pub fn deinit(s: *Group, a: std.mem.Allocator) void { + inline for (.{ "prep", "scores" }) |f| if (@field(s, f)) |x| { + x.deinit(); + a.destroy(x); + }; + s.decode.deinit(a); + } +}; diff --git a/zig/tests/contract/metal_minimax_route_decode.zig b/zig/tests/contract/metal_minimax_route_decode.zig new file mode 100644 index 00000000000..6d88394acf5 --- /dev/null +++ b/zig/tests/contract/metal_minimax_route_decode.zig @@ -0,0 +1,268 @@ +//! MiniMax-M3.1-Flash's decode attention (mm_decode_vec, mm_merge_vec) under the contract, in attention_range's range. +const std = @import("std"); +const mtl = @import("metal"); +const contract = @import("contract"); +const ar = contract.attention_range; +const rig_ = @import("rig.zig"); +const r = @import("metal_minimax_route.zig"); +const sel = @import("metal_minimax_route_sort.zig"); + +const c = contract.spec; +const g = contract.gates; +const D = r.head_dim; +const G = r.heads / r.kv_heads; +/// Partials a (head, row): four quarters of each kept block. +const parts = r.topk_blocks * 4; + +/// mm_vec_args (glue.metal). +const VArgs = extern struct { rows: u32, pos: u32, heads: u32, groups: u32, topk: u32, scale: f32, sel: u32, all: u32 }; + +/// fp32 roundings: a score 10, 10 fast::exps a weight, o's and l's chains (8 rescales, 64 partials), a fast division. +const score_ops = 10; +const num_ops = 8 * 9 + 2 * parts + 2; +const den_ops = 8 * 5 + 2 * parts + 2; + +const form: ar.Form = .{ .score = score_ops, .fast_exp = false, .chunk_exp = false, .p_rel = 0, .num = num_ops, .den = den_ops, .div = 3, .exp_ulps = .{ 4 * 10, 2 } }; + +pub const Decode = struct { + a: std.mem.Allocator, + rig: rig_.Rig, + part: mtl.Pipeline, + merge: mtl.Pipeline, + rows: usize = 0, + blocks: usize = 0, + pos: usize = 0, + all: bool = false, + stress: bool = false, + q: []u16 = &.{}, + k: []u16 = &.{}, + v: []u16 = &.{}, + picks: []i32 = &.{}, + ins: [4]rig_.Ref = undefined, + scratch: [3]rig_.Ref = undefined, + out: rig_.Ref = undefined, + point: []f64 = &.{}, + half: []f64 = &.{}, + + /// Rows: decode rows; n: the index blocks their keys span (every block kept while at most 16); k: the head dim. + pub fn spec() c.Spec { + return .{ + .name = "metal minimax_m3 mm_decode_vec + mm_merge_vec 64/4 heads of 128, top 16 blocks", + .accum = .f32, + .depth = depth, + .ops = 4, + .out = .bf16, + .tiles = .{ .{ .size = 16 }, .{}, .{} }, + // every block kept (gate 4's), the 147,456-token window, past 16 blocks, 32 shared rows, one row at key 0 + .served = &.{ .{ .rows = 16, .n = r.topk_blocks, .k = D }, .{ .rows = 16, .n = 1152, .k = D }, .{ .rows = 1, .n = r.topk_blocks + 1, .k = D }, .{ .rows = r.batch_rows, .n = 300, .k = D }, .{ .rows = 1, .n = 1, .k = D } }, + }; + } + + fn depth(_: c.Shape) usize { + return num_ops; + } + + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue) !Decode { + const part = try r.gluePipe(device, "mm_decode_vec"); + errdefer part.deinit(); + return .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .part = part, .merge = try r.gluePipe(device, "mm_merge_vec") }; + } + fn free(t: *Decode) void { + inline for (.{ "q", "k", "v", "picks" }) |f| { + t.a.free(@field(t, f)); + @field(t, f) = &.{}; + } + t.a.free(t.point); + t.a.free(t.half); + t.point = &.{}; + t.half = &.{}; + } + pub fn deinit(t: *Decode) void { + t.free(); + t.rig.deinit(); + t.part.deinit(); + t.merge.deinit(); + } + pub fn kernel(t: *Decode) g.Kernel { + return .{ .spec = spec(), .ctx = t, .vt = &vt }; + } + const vt = g.hooks(Decode); + + const ld = r.kv_heads * D; + + pub fn prepare(t: *Decode, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.rows == 0 or shape.rows > r.batch_rows or shape.k != D) return false; + const pos = sel.startOf(shape.rows, shape.n) orelse return false; + t.rig.reset(); + t.free(); + t.rows = shape.rows; + t.blocks = shape.n; + t.pos = pos; + t.all = shape.n <= r.topk_blocks; + t.stress = fill == .stress; + const keys = shape.n * r.block; + t.q = try t.a.alloc(u16, shape.rows * r.heads * D); + t.k = try t.a.alloc(u16, keys * ld); + t.v = try t.a.alloc(u16, keys * ld); + t.picks = try t.a.alloc(i32, shape.rows * r.kv_heads * r.topk_blocks); + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + for (t.q) |*x| x.* = c.toBf16(rng.float(f32) * 2 - 1); + for (t.k) |*x| x.* = c.toBf16(rng.float(f32) * 2 - 1); + for (t.v) |*x| x.* = c.toBf16(rng.float(f32) * 2 - 1); + if (fill == .stress) { + // keys alike (weights exactly 1), integer values: a 2,000-key sum is exact in fp32 and passes fp16's range + for (0..keys) |j| @memcpy(t.k[j * ld ..][0..ld], t.k[0..ld]); + for (0..keys) |j| for (0..ld) |e| { + t.v[j * ld + e] = c.toBf16(@floatFromInt(1 + (j * 7 + e * 13) % 250)); + }; + } + // a row keeps its own block and up to 15 earlier ones (a few rows fewer: -1 past them), ascending + for (0..shape.rows) |row| for (0..r.kv_heads) |h| { + const list = t.picks[(row * r.kv_heads + h) * r.topk_blocks ..][0..r.topk_blocks]; + @memset(list, -1); + const own = (pos + row) / r.block; + const want: usize = if (row % 5 == 3) 9 else r.topk_blocks; + var n: usize = 0; + list[n] = @intCast(own); + n += 1; + while (n < @min(want, own + 1)) { + const b: i32 = @intCast(rng.uintLessThan(usize, own)); + if (std.mem.indexOfScalar(i32, list[0..n], b) == null) { + list[n] = b; + n += 1; + } + } + std.mem.sort(i32, list[0..n], {}, std.sort.asc(i32)); + }; + if (fill == .nonfinite) { + // NaN in row 0's head 0; +Inf in row 1's own value (key head 1, dim 7); -Inf in row 2's (key head 2, dim 9) + t.q[3] = c.toBf16(r.nan32); + if (shape.rows > 1) t.v[(pos + 1) * ld + 1 * D + 7] = c.toBf16(r.inf32); + if (shape.rows > 2) t.v[(pos + 2) * ld + 2 * D + 9] = c.toBf16(-r.inf32); + } + for ([_][]const u8{ std.mem.sliceAsBytes(t.q), std.mem.sliceAsBytes(t.k), std.mem.sliceAsBytes(t.v), std.mem.sliceAsBytes(t.picks) }, &t.ins) |b, *ref| ref.* = try t.rig.input(b); + const slots = r.heads * shape.rows * parts; + t.scratch[0] = try t.rig.scratch(slots * 4); + t.scratch[1] = try t.rig.scratch(slots * 4); + t.scratch[2] = try t.rig.scratch(slots * D * 4); + t.out = try t.rig.output(t.count() * 2); + t.point = try t.a.alloc(f64, t.count()); + t.half = try t.a.alloc(f64, t.count()); + try t.ranges(); + return true; + } + + fn args(t: *const Decode) VArgs { + const scale: f32 = @floatCast(1 / @sqrt(@as(f64, D))); + return .{ .rows = @intCast(t.rows), .pos = @intCast(t.pos), .heads = r.heads, .groups = r.kv_heads, .topk = parts, .scale = scale, .sel = r.topk_blocks, .all = @intFromBool(t.all) }; + } + + pub fn run(t: *Decode) !void { + const p = t.rig.begin(); + const e = p.e; + e.setPipeline(t.part); + for (t.ins[0..3], 0..) |ref, i| e.setBuffer(ref.buf, ref.off, i); + e.setValue(t.args(), 3); + e.setBuffer(t.ins[3].buf, t.ins[3].off, 4); + for (t.scratch, 5..) |ref, i| e.setBuffer(ref.buf, ref.off, i); + e.dispatchGroups(mtl.Size.of(r.kv_heads, t.rows, parts), mtl.Size.of(32, G, 1)); + e.setPipeline(t.merge); + for (t.scratch, 0..) |ref, i| e.setBuffer(ref.buf, ref.off, i); + e.setValue(t.args(), 3); + e.setBuffer(t.out.buf, t.out.off, 4); + e.dispatchGroups(mtl.Size.of(r.heads, t.rows, 1), mtl.Size.of(32, 1, 1)); + try t.rig.finish(p); + } + + pub fn count(t: *Decode) usize { + return t.rows * r.heads * D; + } + + /// Row `row`, key head `kv`'s kept keys in block order (the merge's). + fn kept(t: *const Decode, row: usize, kv: usize, out: *std.ArrayList(usize)) !void { + out.clearRetainingCapacity(); + const p = t.pos + row; + for (0..r.topk_blocks) |i| { + const b: i64 = if (t.all) (if (i <= p / r.block) @intCast(i) else -1) else t.picks[(row * r.kv_heads + kv) * r.topk_blocks + i]; + if (b < 0) continue; + const from: usize = @intCast(b * r.block); + for (from..@min(p + 1, from + r.block)) |key| try out.append(t.a, key); + } + } + + /// Every output's float64 point and half-range, from the kept keys of its (row, head). + fn ranges(t: *Decode) !void { + var keys: std.ArrayList(usize) = .empty; + defer keys.deinit(t.a); + const scale: f64 = t.args().scale; + var qf: [D]f64 = undefined; + for (0..t.rows) |row| for (0..r.kv_heads) |kv| { + try t.kept(row, kv, &keys); + const n = keys.items.len; + const kf = try t.a.alloc(f64, 2 * n * D + 2 * n); + defer t.a.free(kf); + const vf = kf[n * D .. 2 * n * D]; + for (keys.items, 0..) |key, j| for (0..D) |e| { + kf[j * D + e] = c.fromBf16(t.k[key * ld + kv * D + e]); + vf[j * D + e] = c.fromBf16(t.v[key * ld + kv * D + e]); + }; + for (0..G) |gi| { + const hd = kv * G + gi; + for (&qf, 0..) |*x, e| x.* = c.fromBf16(t.q[(row * r.heads + hd) * D + e]); + const at = (row * r.heads + hd) * D; + ar.head(&qf, kf[0 .. n * D], vf, n, D, scale, form, kf[2 * n * D ..][0..n], kf[2 * n * D + n ..][0..n], t.point[at..][0..D], t.half[at..][0..D]); + } + }; + } + + pub fn reference(t: *Decode, want: []f64, mag: []f64) !void { + @memcpy(want, t.point); + for (mag, want) |*m, w| m.* = if (std.math.isFinite(w)) @abs(w) else 0; + } + + pub fn intervals(t: *Decode, low: []f64, high: []f64) !void { + for (low, high, t.point, t.half) |*l, *h, p, hf| { + l.* = if (std.math.isFinite(p)) r.bf(p - hf) else 0; + h.* = if (std.math.isFinite(p)) r.bf(p + hf) else 0; + } + } + + pub fn bounds(t: *Decode, want: []const f64, _: []const f64, allow: []f64) !void { + for (allow, want, t.point, t.half) |*l, w, p, hf| l.* = if (std.math.isFinite(w)) r.spread(w, .{ .lo = r.bf(p - hf), .hi = r.bf(p + hf) }) else 0; + } + + /// Gate 4's sums: every weight is 1, so o is V's column sum over the kept keys' count, rounded once. + pub fn simulate(t: *Decode, acc: c.Accum, order: g.Order, out: []f64) !void { + var keys: std.ArrayList(usize) = .empty; + defer keys.deinit(t.a); + for (0..t.rows) |row| for (0..r.kv_heads) |kv| { + try t.kept(row, kv, &keys); + const col = try t.a.alloc(f64, keys.items.len); + defer t.a.free(col); + for (0..D) |e| { + for (keys.items, col) |key, *x| x.* = c.fromBf16(t.v[key * ld + kv * D + e]); + const o = contract.rows.sumIn(acc, order, col) / @as(f64, @floatFromInt(keys.items.len)); + for (0..G) |gi| out[(row * r.heads + kv * G + gi) * D + e] = o; + } + }; + } +}; + +pub const Group = struct { + decode: ?*Decode = null, + + pub fn collect(s: *Group, a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, only: ?[]const u8, kernels: *std.ArrayList(g.Kernel)) !void { + if (only != null and std.mem.indexOf(u8, Decode.spec().name, only.?) == null) return; + const x = try a.create(Decode); + x.* = try Decode.init(a, device, queue); + s.decode = x; + try kernels.append(a, x.kernel()); + } + pub fn deinit(s: *Group, a: std.mem.Allocator) void { + if (s.decode) |x| { + x.deinit(); + a.destroy(x); + } + } +}; diff --git a/zig/tests/contract/metal_minimax_route_sort.zig b/zig/tests/contract/metal_minimax_route_sort.zig new file mode 100644 index 00000000000..04b6e26cac1 --- /dev/null +++ b/zig/tests/contract/metal_minimax_route_sort.zig @@ -0,0 +1,378 @@ +//! MiniMax-M3.1-Flash's mm_sort, mm_rows_by_order and mm_index_select under the contract, each by its own rule. +const std = @import("std"); +const mtl = @import("metal"); +const contract = @import("contract"); +const rig_ = @import("rig.zig"); +const r = @import("metal_minimax_route.zig"); + +const c = contract.spec; +const g = contract.gates; +const Args = r.Args; + +// --- mm_sort: a prompt chunk's picks by expert, each expert's in slot order --------------------------------------- + +pub const Sort = struct { + a: std.mem.Allocator, + rig: rig_.Rig, + pipe: mtl.Pipeline, + slots: usize = 0, + picks: []i32 = &.{}, + in: rig_.Ref = undefined, + offsets: rig_.Ref = undefined, + order: rig_.Ref = undefined, + msg: [200]u8 = undefined, + + /// Rows: slots (4 a token); n: experts. + pub fn spec() c.Spec { + return .{ + .name = "metal minimax_m3 mm_sort experts 128", + .accum = .none, + .depth = r.noSums, + .out = .raw, + .nan = .{ .stated = "the host's stable sort: offsets its exclusive prefix counts, order each expert's slots ascending inside its own offsets" }, + .tiles = .{ .{ .size = 1024, .step = 4, .min = 4 * (r.batch_rows + 1) }, .{}, .{} }, + // the prompt path's chunks: 33 rows (past a shared decode forward) to 4,096 + .served = &.{ .{ .rows = r.prompt_rows * r.topk, .n = r.experts, .k = 1 }, .{ .rows = (r.batch_rows + 1) * r.topk, .n = r.experts, .k = 1 } }, + }; + } + + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue) !Sort { + return .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .pipe = try r.gluePipe(device, "mm_sort") }; + } + pub fn deinit(t: *Sort) void { + t.a.free(t.picks); + t.rig.deinit(); + t.pipe.deinit(); + } + pub fn kernel(t: *Sort) g.Kernel { + return .{ .spec = spec(), .ctx = t, .vt = &vt }; + } + const vt = g.hooks(Sort); + + pub fn prepare(t: *Sort, shape: c.Shape, _: g.Fill, seed: u64) !bool { + if (shape.rows == 0 or shape.rows % r.topk != 0 or shape.n != r.experts) return false; + t.rig.reset(); + t.a.free(t.picks); + t.slots = shape.rows; + t.picks = try t.a.alloc(i32, shape.rows); + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + // each token's 4 distinct experts; a few hot experts take most tokens, so empty and crowded experts both occur + for (0..shape.rows / r.topk) |tok| { + var used: [r.experts]bool = @splat(false); + for (t.picks[tok * r.topk ..][0..r.topk]) |*p| { + var e: u32 = if (rng.boolean()) rng.uintLessThan(u32, 12) else rng.uintLessThan(u32, r.experts); + while (used[e]) e = (e + 1) % r.experts; + used[e] = true; + p.* = @intCast(e); + } + } + t.in = try t.rig.input(std.mem.sliceAsBytes(t.picks)); + t.offsets = try t.rig.output(r.experts * 4); + t.order = try t.rig.output(shape.rows * 4); + return true; + } + + pub fn run(t: *Sort) !void { + const p = t.rig.begin(); + p.e.setPipeline(t.pipe); + p.e.setBuffer(t.in.buf, t.in.off, 0); + p.e.setValue(Args{ .rows = @intCast(t.slots), .width = r.experts }, 1); + p.e.setBuffer(t.offsets.buf, t.offsets.off, 2); + p.e.setBuffer(t.order.buf, t.order.off, 3); + p.e.dispatchGroups(mtl.Size.of(1, 1, 1), mtl.Size.of(1024, 1, 1)); + try t.rig.finish(p); + } + + pub fn count(t: *Sort) usize { + return (r.experts + t.slots) * 4; + } + pub fn reference(_: *Sort, _: []f64, _: []f64) !void { + return error.CheckedByItsOwnRule; + } + + pub fn check(t: *Sort, _: g.Gate) !?[]const u8 { + const offs = std.mem.bytesAsSlice(i32, t.rig.bytes(t.offsets, r.experts * 4)); + const order = std.mem.bytesAsSlice(i32, t.rig.bytes(t.order, t.slots * 4)); + var want: [r.experts + 1]i32 = @splat(0); + for (t.picks) |e| want[@intCast(e + 1)] += 1; + for (1..r.experts + 1) |e| want[e] += want[e - 1]; + for (0..r.experts) |e| if (offs[e] != want[e]) return try std.fmt.bufPrint(&t.msg, "expert {d}'s offset is {d} where the host counts {d}", .{ e, offs[e], want[e] }); + var i: usize = 0; + for (0..r.experts) |e| for (t.picks, 0..) |p, slot| if (p == e) { + if (order[i] != slot) return try std.fmt.bufPrint(&t.msg, "order[{d}] = {d} where the host's stable sort gives slot {d} (expert {d})", .{ i, order[i], slot, e }); + i += 1; + }; + return null; + } +}; + +// --- mm_rows_by_order: each sorted slot's token row, bit for bit -------------------------------------------------- + +pub const RowsByOrder = struct { + a: std.mem.Allocator, + rig: rig_.Rig, + pipe: mtl.Pipeline, + shape: c.Shape = undefined, + x: []u16 = &.{}, + order: []i32 = &.{}, + ins: [2]rig_.Ref = undefined, + out: rig_.Ref = undefined, + msg: [200]u8 = undefined, + + /// Rows: sorted slots (4 a token); n: the hidden width. + pub fn spec() c.Spec { + return .{ + .name = "metal minimax_m3 mm_rows_by_order top 4", + .accum = .none, + .depth = r.noSums, + .out = .raw, + .nan = .{ .stated = "each sorted slot's row is its token's input row, bit for bit" }, + .tiles = .{ .{ .size = 4, .step = 4, .min = 4 }, .{ .size = 256, .step = 1, .min = 1 }, .{} }, + .served = &.{ .{ .rows = 1024 * r.topk, .n = r.hidden, .k = 1 }, .{ .rows = r.prompt_rows * r.topk, .n = r.hidden, .k = 1 }, .{ .rows = (r.batch_rows + 1) * r.topk, .n = r.hidden, .k = 1 } }, + }; + } + + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue) !RowsByOrder { + return .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .pipe = try r.gluePipe(device, "mm_rows_by_order") }; + } + pub fn deinit(t: *RowsByOrder) void { + t.a.free(t.x); + t.a.free(t.order); + t.rig.deinit(); + t.pipe.deinit(); + } + pub fn kernel(t: *RowsByOrder) g.Kernel { + return .{ .spec = spec(), .ctx = t, .vt = &vt }; + } + const vt = g.hooks(RowsByOrder); + + pub fn prepare(t: *RowsByOrder, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.rows == 0 or shape.rows % r.topk != 0 or shape.n == 0) return false; + t.rig.reset(); + t.a.free(t.x); + t.a.free(t.order); + t.shape = shape; + const tokens = shape.rows / r.topk; + t.x = try t.a.alloc(u16, tokens * shape.n); + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + for (t.x) |*v| v.* = rng.int(u16); + if (fill == .nonfinite) for ([_]f32{ r.nan32, r.inf32, -r.inf32 }, 0..) |v, i| { + t.x[i] = c.toBf16(v); + }; + t.order = try t.a.alloc(i32, shape.rows); + for (t.order, 0..) |*o, i| o.* = @intCast(i); + rng.shuffle(i32, t.order); + t.ins[0] = try t.rig.input(std.mem.sliceAsBytes(t.x)); + t.ins[1] = try t.rig.input(std.mem.sliceAsBytes(t.order)); + t.out = try t.rig.output(shape.rows * shape.n * 2); + return true; + } + + pub fn run(t: *RowsByOrder) !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(Args{ .rows = @intCast(t.shape.rows), .width = @intCast(t.shape.n), .heads = r.topk }, 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: *RowsByOrder) usize { + return t.shape.rows * t.shape.n * 2; + } + pub fn reference(_: *RowsByOrder, _: []f64, _: []f64) !void { + return error.CheckedByItsOwnRule; + } + + pub fn check(t: *RowsByOrder, _: g.Gate) !?[]const u8 { + const n = t.shape.n; + const got = t.rig.bytes(t.out, t.count()); + for (t.order, 0..) |o, i| { + const tok: usize = @intCast(@divTrunc(o, r.topk)); + if (!std.mem.eql(u8, got[i * n * 2 ..][0 .. n * 2], std.mem.sliceAsBytes(t.x[tok * n ..][0..n]))) return try std.fmt.bufPrint(&t.msg, "sorted slot {d} is not token {d}'s row", .{ i, tok }); + } + return null; + } +}; + +// --- mm_index_select: each (row, key head)'s kept blocks ascending, and the prompt's bitmap ----------------------- + +/// mm_index_args (glue.metal). +pub const IArgs = extern struct { rows: u32, pos: u32, heads: u32, blocks: u32, first_row: u32 = 0 }; + +/// A row's position past `pos`: the last row ends 7 keys short of block `blocks`' end (blocks(pos + rows) = blocks). +pub fn startOf(rows: usize, blocks: usize) ?usize { + const end = blocks * r.block - 7; + if (end < rows or blocks == 0) return null; + return end - rows; +} + +pub const Select = struct { + a: std.mem.Allocator, + rig: rig_.Rig, + pipe: mtl.Pipeline, + shape: c.Shape = undefined, + pos: usize = 0, + scores: []f32 = &.{}, + in: rig_.Ref = undefined, + sel: rig_.Ref = undefined, + bits: rig_.Ref = undefined, + msg: [200]u8 = undefined, + + /// Rows: query rows; n: the index blocks the chunk's keys span; k: bitmap words a (row, head) (0: decode). + pub fn spec() c.Spec { + return .{ + .name = "metal minimax_m3 mm_index_select top 16 blocks, key heads 4", + .accum = .none, + .depth = r.noSums, + .out = .raw, + .nan = .{ .stated = "the host's selection: every block while a row sees at most 16, else its own block and the best 15 by score (ties to the lower block, +Inf first), NaN and -Inf never kept; ascending, -1 past the count; the bitmap marks the same blocks" }, + .tiles = .{ .{ .size = 32 }, .{}, .{} }, + // decode windows at the longest window and just past 16 blocks; prompt chunks with their bitmaps + .served = &.{ .{ .rows = 16, .n = r.context_blocks, .k = 0 }, .{ .rows = 1, .n = r.topk_blocks + 1, .k = 0 }, .{ .rows = r.prompt_rows, .n = r.context_blocks, .k = r.context_blocks / 32 }, .{ .rows = 64, .n = 5, .k = r.context_blocks / 32 }, .{ .rows = 200, .n = 300, .k = 10 } }, + }; + } + + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue) !Select { + return .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .pipe = try r.gluePipe(device, "mm_index_select") }; + } + pub fn deinit(t: *Select) void { + t.a.free(t.scores); + t.rig.deinit(); + t.pipe.deinit(); + } + pub fn kernel(t: *Select) g.Kernel { + return .{ .spec = spec(), .ctx = t, .vt = &vt }; + } + const vt = g.hooks(Select); + + pub fn prepare(t: *Select, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + const pos = startOf(shape.rows, shape.n) orelse return false; + if (shape.rows == 0 or shape.k * 32 < shape.n and shape.k != 0) return false; + t.rig.reset(); + t.a.free(t.scores); + t.shape = shape; + t.pos = pos; + t.scores = try t.a.alloc(f32, shape.rows * r.kv_heads * shape.n); + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + // scores from a small set, so ties are common and the lower block must win them + for (t.scores) |*v| v.* = @as(f32, @floatFromInt(rng.intRangeAtMost(i32, -64, 64))) / 8; + if (fill == .nonfinite) { + const put = [_]f32{ r.nan32, r.inf32, -r.inf32, r.nan32, -r.inf32 }; + for (put, 0..) |v, i| if (i < shape.rows) { + const row = t.scores[(i * r.kv_heads + i % r.kv_heads) * shape.n ..][0..shape.n]; + row[(i * 37) % shape.n] = v; + row[0] = v; + }; + } + t.in = try t.rig.input(std.mem.sliceAsBytes(t.scores)); + t.sel = try t.rig.output(shape.rows * r.kv_heads * r.topk_blocks * 4); + t.bits = try t.rig.output(@max(shape.rows * r.kv_heads * shape.k, 1) * 4); + return true; + } + + pub fn run(t: *Select) !void { + const p = t.rig.begin(); + const e = p.e; + e.setPipeline(t.pipe); + e.setBuffer(t.in.buf, t.in.off, 0); + e.setValue(IArgs{ .rows = @intCast(t.shape.rows), .pos = @intCast(t.pos), .heads = r.kv_heads, .blocks = @intCast(t.shape.n) }, 1); + e.setValue(@as(u32, r.topk_blocks), 2); + e.setBuffer(t.sel.buf, t.sel.off, 3); + e.setBuffer(t.bits.buf, t.bits.off, 4); + e.setValue(@as(u32, @intCast(t.shape.k)), 5); + e.dispatchGroups(mtl.Size.of(r.kv_heads, t.shape.rows, 1), mtl.Size.of(32, 1, 1)); + try t.rig.finish(p); + } + + pub fn count(t: *Select) usize { + return t.shape.rows * r.kv_heads * (r.topk_blocks + t.shape.k) * 4; + } + pub fn reference(_: *Select, _: []f64, _: []f64) !void { + return error.CheckedByItsOwnRule; + } + + /// Whether (v, b) comes before (w, d) in the selection's order: score descending, then block ascending. + fn before(v: f32, b: usize, w: f32, d: usize) bool { + return v > w or (v == w and b < d); + } + + /// Row `row`, head `h`'s kept blocks, ascending; the count. + fn hostList(t: *Select, row: usize, h: usize, out: *[r.topk_blocks]i32) usize { + const nb = (t.pos + row) / r.block + 1; + if (nb <= r.topk_blocks) { + for (0..nb) |b| out[b] = @intCast(b); + return nb; + } + const s = t.scores[(row * r.kv_heads + h) * t.shape.n ..][0..t.shape.n]; + var n: usize = 1; + out[0] = @intCast(nb - 1); + var taken: [r.context_blocks]bool = @splat(false); + while (n < r.topk_blocks) : (n += 1) { + var best: ?usize = null; + for (0..nb - 1) |b| { + if (taken[b] or std.math.isNan(s[b]) or s[b] == -std.math.inf(f32)) continue; + if (best == null or before(s[b], b, s[best.?], best.?)) best = b; + } + const b = best orelse break; + taken[b] = true; + out[n] = @intCast(b); + } + std.mem.sort(i32, out[0..n], {}, std.sort.asc(i32)); + return n; + } + + pub fn check(t: *Select, _: g.Gate) !?[]const u8 { + const rows = t.shape.rows; + const words = t.shape.k; + const sel = std.mem.bytesAsSlice(i32, t.rig.bytes(t.sel, rows * r.kv_heads * r.topk_blocks * 4)); + const bits = std.mem.bytesAsSlice(u32, t.rig.bytes(t.bits, @max(rows * r.kv_heads * words, 1) * 4)); + for (0..rows) |row| for (0..r.kv_heads) |h| { + var list: [r.topk_blocks]i32 = undefined; + const n = t.hostList(row, h, &list); + const at = (row * r.kv_heads + h) * r.topk_blocks; + for (0..r.topk_blocks) |i| { + const want: i32 = if (i < n) list[i] else -1; + if (sel[at + i] != want) return try std.fmt.bufPrint(&t.msg, "row {d} head {d}'s kept block {d} is {d} where the host keeps {d}", .{ row, h, i, sel[at + i], want }); + } + for (0..words) |wd| { + var m: u32 = 0; + for (list[0..n]) |b| if (@as(usize, @intCast(b)) / 32 == wd) { + m |= @as(u32, 1) << @intCast(@as(usize, @intCast(b)) % 32); + }; + const got = bits[(row * r.kv_heads + h) * words + wd]; + if (got != m) return try std.fmt.bufPrint(&t.msg, "row {d} head {d}'s bitmap word {d} is {x} where the host has {x}", .{ row, h, wd, got, m }); + } + }; + return null; + } +}; + +/// This file's kernels in the suite. +pub const Group = struct { + sort: ?*Sort = null, + rows: ?*RowsByOrder = null, + select: ?*Select = null, + + pub fn collect(s: *Group, a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, only: ?[]const u8, kernels: *std.ArrayList(g.Kernel)) !void { + inline for (.{ .{ "sort", Sort }, .{ "rows", RowsByOrder }, .{ "select", Select } }) |e| { + if (only == null or std.mem.indexOf(u8, e[1].spec().name, only.?) != null) { + const x = try a.create(e[1]); + x.* = try e[1].init(a, device, queue); + @field(s, e[0]) = x; + try kernels.append(a, x.kernel()); + } + } + } + pub fn deinit(s: *Group, a: std.mem.Allocator) void { + inline for (.{ "sort", "rows", "select" }) |f| if (@field(s, f)) |x| { + x.deinit(); + a.destroy(x); + }; + } +}; diff --git a/zig/tests/minimax_m3/run.zig b/zig/tests/minimax_m3/run.zig new file mode 100644 index 00000000000..a5ca1027afb --- /dev/null +++ b/zig/tests/minimax_m3/run.zig @@ -0,0 +1,196 @@ +//! MiniMax-M3.1-Flash on real weights: greedy tokens, every position's logits or forced steps (usage). +const std = @import("std"); +const mtl = @import("metal"); +const tf = @import("tensorfold"); +const fl = tf.minimax_m3; + +const usage = + \\tf-minimax-run greedy the prompt in chunks, then n one-row steps' tokens + \\tf-minimax-run logits 16-row windows from 0; bf16 logits [tokens, vocab] + \\tf-minimax-run prompt the prompt in chunks; the last row's bf16 logits + \\tf-minimax-run forced , then cont's tokens a step; bf16 logits before each + \\tf-minimax-run exact cont's tokens as one-row steps and as 16-row windows + \\ after the prompt: every row's logits bit for bit + \\tf-minimax-run bench the prompt, then n one-row steps: wall, encode, GPU ms + \\ +; + +pub fn main(init: std.process.Init) !void { + const args = try init.minimal.args.toSlice(init.arena.allocator()); + if (args.len != 5) { + std.debug.print("{s}", .{usage}); + return error.ExpectedModelTokensModeArg; + } + const gpa = init.gpa; + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const bytes = try std.Io.Dir.cwd().readFileAlloc(init.io, args[2], gpa, .limited(64 << 20)); + defer gpa.free(bytes); + const ids = try std.json.parseFromSlice([]u32, gpa, bytes, .{}); + defer ids.deinit(); + const prompt = ids.value; + if (prompt.len == 0) return error.EmptyPrompt; + const mode = args[3]; + const room: usize = if (std.mem.eql(u8, mode, "greedy") or std.mem.eql(u8, mode, "bench")) try std.fmt.parseInt(usize, args[4], 10) else 4096; + const context = prompt.len + room + 1; + const m = try fl.Model.load(gpa, init.io, args[1]); + defer m.deinit(); + const c = &m.config; + var forced: ?std.json.Parsed([]u32) = null; + defer if (forced) |f| f.deinit(); + var forced_out: []const u8 = ""; + if (std.mem.eql(u8, mode, "forced")) { + const comma = std.mem.indexOfScalar(u8, args[4], ',') orelse return error.ExpectedContCommaOut; + const text = try std.Io.Dir.cwd().readFileAlloc(init.io, args[4][0..comma], gpa, .limited(1 << 20)); + defer gpa.free(text); + forced = try std.json.parseFromSlice([]u32, gpa, text, .{}); + forced_out = args[4][comma + 1 ..]; + } + const steps: usize = if (std.mem.eql(u8, mode, "greedy") or std.mem.eql(u8, mode, "bench")) room else if (forced) |f| f.value.len else 0; + var cache = try fl.state.Cache.init(m.device, c, prompt.len + steps + 1); + defer cache.deinit(); + if (prompt.len + steps + 1 > context) return error.ContextTooShort; + var small = try fl.state.Scratch.init(m.device, c, fl.state.batch_rows, context); + defer small.deinit(); + var wide = try fl.state.Scratch.init(m.device, c, fl.state.prompt_rows, context); + defer wide.deinit(); + const vocab: usize = c.vocab; + var t0 = now(); + if (std.mem.eql(u8, mode, "logits")) { + const out = try gpa.alloc(u16, prompt.len * vocab); + defer gpa.free(out); + var at: usize = 0; + while (at < prompt.len) { + const n = @min(prompt.len - at, fl.state.window_rows); + try fl.forward.run(m, &small, &cache, prompt[at..][0..n], .{ .all = true }); + @memcpy(out[at * vocab ..][0 .. n * vocab], small.logits_all.slice(u16, n * vocab)); + cache.len += n; + at += n; + } + try std.Io.Dir.cwd().writeFile(init.io, .{ .sub_path = args[4], .data = std.mem.sliceAsBytes(out) }); + std.debug.print("minimax logits: {d} rows in {d} ms\n", .{ prompt.len, (now() - t0) / std.time.ns_per_ms }); + return; + } + if (std.mem.eql(u8, mode, "exact")) { + const text = try std.Io.Dir.cwd().readFileAlloc(init.io, args[4], gpa, .limited(1 << 20)); + defer gpa.free(text); + const cont = try std.json.parseFromSlice([]u32, gpa, text, .{}); + defer cont.deinit(); + const toks = cont.value; + var scache = try fl.state.Cache.init(m.device, c, prompt.len + toks.len + 1); + defer scache.deinit(); + var wcache = try fl.state.Cache.init(m.device, c, prompt.len + toks.len + 1); + defer wcache.deinit(); + try feed(m, &small, &wide, &scache, prompt); + try feed(m, &small, &wide, &wcache, prompt); + const one = try gpa.alloc(u16, toks.len * vocab); + defer gpa.free(one); + for (toks, 0..) |tok, i| { + try fl.forward.run(m, &small, &scache, &.{tok}, .{ .all = true }); + @memcpy(one[i * vocab ..][0..vocab], small.logits_all.slice(u16, vocab)); + scache.len += 1; + } + const width = fl.state.window_rows; + var differ: usize = 0; + var at: usize = 0; + while (at < toks.len) { + const n = @min(toks.len - at, width); + try fl.forward.run(m, &small, &wcache, toks[at..][0..n], .{ .all = true }); + for (0..n) |r| { + if (!std.mem.eql(u16, one[(at + r) * vocab ..][0..vocab], small.logits_all.slice(u16, n * vocab)[r * vocab ..][0..vocab])) { + differ += 1; + if (differ <= 4) std.debug.print("row {d} (window row {d}) differs\n", .{ at + r, r }); + } + } + wcache.len += n; + at += n; + } + std.debug.print("minimax exact at {d}: {d} of {d} rows' logits differ between one-row steps and windows\n", .{ prompt.len, differ, toks.len }); + return; + } + if (std.mem.eql(u8, mode, "prompt")) { // a first pass pages the weights in: the second is the one timed + try feed(m, &small, &wide, &cache, prompt); + cache.len = 0; + t0 = now(); + } + try feed(m, &small, &wide, &cache, prompt); + const ttft = (now() - t0); + if (std.mem.eql(u8, mode, "prompt")) { + try std.Io.Dir.cwd().writeFile(init.io, .{ .sub_path = args[4], .data = std.mem.sliceAsBytes(cache.logits.slice(u16, vocab)) }); + std.debug.print("minimax prompt: {d} tokens in {d} ms ({d:.0} tok/s)\n", .{ prompt.len, ttft / std.time.ns_per_ms, @as(f64, @floatFromInt(prompt.len)) * 1e9 / @as(f64, @floatFromInt(ttft)) }); + return; + } + if (forced) |f| { + const out = try gpa.alloc(u16, f.value.len * vocab); + defer gpa.free(out); + for (f.value, 0..) |tok, i| { + @memcpy(out[i * vocab ..][0..vocab], cache.logits.slice(u16, vocab)); + if (i + 1 == f.value.len) break; + try fl.forward.run(m, &small, &cache, &.{tok}, .{}); + cache.len += 1; + } + try std.Io.Dir.cwd().writeFile(init.io, .{ .sub_path = forced_out, .data = std.mem.sliceAsBytes(out) }); + return; + } + if (std.mem.eql(u8, mode, "bench")) { + const n = try std.fmt.parseInt(usize, args[4], 10); + var tm: fl.forward.Timing = .{}; + t0 = now(); + for (0..n) |_| { + try fl.forward.run(m, &small, &cache, &.{argmax(cache.logits.slice(u16, vocab))}, .{ .timing = &tm }); + cache.len += 1; + } + const wall = @as(f64, @floatFromInt(now() - t0)) / 1e6 / @as(f64, @floatFromInt(n)); + const per = 1e3 / @as(f64, @floatFromInt(n)); + std.debug.print("minimax bench at {d}: {d:.3} ms a step wall, {d:.3} encode, {d:.3} GPU\n", .{ prompt.len, wall, tm.encode * per, tm.gpu * per }); + return; + } + if (!std.mem.eql(u8, mode, "greedy")) { + std.debug.print("{s}", .{usage}); + return error.UnknownMode; + } + const picks = try gpa.alloc(u32, steps); + defer gpa.free(picks); + t0 = now(); + for (picks, 0..) |*p, i| { + p.* = argmax(cache.logits.slice(u16, vocab)); + if (i + 1 == steps) break; + try fl.forward.run(m, &small, &cache, &.{p.*}, .{}); + cache.len += 1; + } + const decode = (now() - t0); + var w: std.Io.Writer.Allocating = .init(gpa); + defer w.deinit(); + try std.json.Stringify.value(picks, .{}, &w.writer); + std.debug.print("{s}\n", .{w.written()}); + std.debug.print("minimax greedy: prompt {d} tokens {d} ms, {d} steps {d:.1} tok/s\n", .{ prompt.len, ttft / std.time.ns_per_ms, steps, @as(f64, @floatFromInt(steps - 1)) * 1e9 / @as(f64, @floatFromInt(decode)) }); +} + +/// The prompt in prompt_rows chunks (the tensor-unit path past 16 rows), as the backend feeds it. +fn feed(m: *const fl.Model, small: *fl.state.Scratch, wide: *fl.state.Scratch, cache: *fl.state.Cache, ids: []const u32) !void { + var at: usize = 0; + while (at < ids.len) { + const n = @min(ids.len - at, fl.state.prompt_rows); + try fl.forward.run(m, if (n > fl.state.batch_rows) wide else small, cache, ids[at..][0..n], .{}); + cache.len += n; + at += n; + } +} + +fn now() u64 { + var ts: std.c.timespec = undefined; + _ = std.c.clock_gettime(.MONOTONIC, &ts); + return @as(u64, @intCast(ts.sec)) * std.time.ns_per_s + @as(u64, @intCast(ts.nsec)); +} + +fn argmax(l: []const u16) u32 { + var best: usize = 0; + for (l, 0..) |x, i| if (logit(x) > logit(l[best])) { + best = i; + }; + return @intCast(best); +} + +fn logit(word: u16) f32 { + return @bitCast(@as(u32, word) << 16); +} diff --git a/zig/tests/minimax_m3/vision.zig b/zig/tests/minimax_m3/vision.zig new file mode 100644 index 00000000000..a953ef69018 --- /dev/null +++ b/zig/tests/minimax_m3/vision.zig @@ -0,0 +1,76 @@ +//! MiniMax-M3.1-Flash's image tower alone (its shard, not the 200 GiB model): an image's patches and text rows. +const std = @import("std"); +const mtl = @import("metal"); +const tf = @import("tensorfold"); +const ks = @import("kernel_sources"); +const fl = tf.minimax_m3; +const ck = tf.checkpoint_metal; + +const usage = + \\tf-minimax-vision pixels.bin ([P, 1176] fp32, merge order), grid.txt (h w), + \\ rows.bin ([P / 4, 6144] bf16): tools/vision_ref.py's outputs + \\ +; + +pub fn main(init: std.process.Init) !void { + const args = try init.minimal.args.toSlice(init.arena.allocator()); + if (args.len != 4) { + std.debug.print("{s}", .{usage}); + return error.ExpectedModelImageOut; + } + const gpa = init.gpa; + const io = init.io; + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const device = try mtl.Device.init(); + defer device.deinit(); + const queue = try device.queue(); + defer queue.deinit(); + var c = ck.Checkpoint.init(gpa); + defer c.deinit(); + const shard = try std.fs.path.joinZ(gpa, &.{ args[1], fl.vision.shard }); + defer gpa.free(shard); + try c.addFile(device, shard, ""); + const lib = try mtl.Library.fromSource(device, ks.minimax_m3_glue, .{ .language = mtl.CompileOptions.mlx().language, .math_functions = .precise }); + defer lib.deinit(); + const widen = try mtl.Pipeline.init(device, lib, "mm_widen", false); + defer widen.deinit(); + const narrow = try mtl.Pipeline.init(device, lib, "mm_narrow", false); + defer narrow.deinit(); + const v = try fl.vision.Vision.load(gpa, device, &c, widen, narrow); + defer v.deinit(); + const bytes = try std.Io.Dir.cwd().readFileAlloc(io, args[2], gpa, .limited(64 << 20)); + defer gpa.free(bytes); + const p = try fl.vision.prepare(io, gpa, bytes, fl.vision.max_tokens); + defer gpa.free(p.pixels); + const rows = try device.buffer(@as(usize, p.tokens) * fl.vision.hidden * 2, mtl.ResourceOptions.shared); + defer rows.deinit(); + var t0: u64 = 0; + for (0..2) |pass| { // the second pass is timed: the first pages the weights in + if (pass == 1) t0 = now(); + const cb = queue.commandBuffer(); + const e = cb.compute(.serial); + try v.encode(e, p.pixels, p.gh, p.gw, .{ .buf = rows }); + e.end(); + cb.commit(); + cb.wait(); + if (cb.failure()) |msg| { + std.log.err("the tower failed: {s}", .{msg}); + return error.GpuFailed; + } + } + const ms = @as(f64, @floatFromInt(now() - t0)) / 1e6; + var dir = try std.Io.Dir.cwd().createDirPathOpen(io, args[3], .{}); + defer dir.close(io); + try dir.writeFile(io, .{ .sub_path = "pixels.bin", .data = std.mem.sliceAsBytes(p.pixels) }); + try dir.writeFile(io, .{ .sub_path = "rows.bin", .data = rows.slice(u8, @as(usize, p.tokens) * fl.vision.hidden * 2) }); + var text: [32]u8 = undefined; + try dir.writeFile(io, .{ .sub_path = "grid.txt", .data = try std.fmt.bufPrint(&text, "{d} {d}\n", .{ p.gh, p.gw }) }); + std.debug.print("minimax vision: {d} x {d} patches, {d} tokens in {d:.1} ms\n", .{ p.gh, p.gw, p.tokens, ms }); +} + +fn now() u64 { + var ts: std.c.timespec = undefined; + _ = std.c.clock_gettime(.MONOTONIC, &ts); + return @as(u64, @intCast(ts.sec)) * std.time.ns_per_s + @as(u64, @intCast(ts.nsec)); +}