diff --git a/CHANGELOG.md b/CHANGELOG.md index 000a385d21e..b4462e74767 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,13 +4,157 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel ## Unreleased +- Flash Next on Metal: `TF_FN_GX_SHARED=1` (opt-in) routes eligible shared rounds through the existing bit-preserving grouped expert kernels; off keeps per-pair launches (#4834). + +- Metal: the two pairs of u32 copy kernels build from one source, with the kernels unchanged (#4740). Thanks @jschmied. + + + +- CUDA and HIP: one core gate decides `--vision` at startup: `--vision` on a checkpoint without a vision tower is refused as "--vision given but this checkpoint has no vision tower", on Qwen3.5 on HIP (which served text) and Flash Next on CUDA too; LFM2 on CUDA loads its tower only with `--vision`; a cluster model's `"vision"` that is not true or false is refused, and the System One picture refusal now says to start with `--vision` (#3456). Thanks to @jschmied. + +- Qwen 3.5 diagnostics: large output files are written in chunks of at most 256 MiB, with the same bytes in the same order (#4296). + + + +- Lanes: window-cost tables are measured in interleaved sweeps and saved tables are repaired at startup inside a fixed time budget; a table with no valid timing is refused. Tokens unchanged (#4755). + +- Drama 3 on CUDA: semantic guidance (`--cfg-gamma` and the other guidance flags) now works, as it does on Metal (#4153). Thanks @plotarmordev. + + + +- Server: `TENSORFOLD_PRIORITY_AGE_MS` (default 0, unchanged order) lets a background request that has waited that long start before foreground work, without letting any request wait forever (#4833) + +- MiniMax-M3 on Metal: shared decode rounds of 12 to 32 rows are timed at load instead of priced at 2x and 4x the 8-row window, so window choice uses measured costs; tokens are unchanged, and a `--context` under 256 tokens leaves those rounds untimed instead of failing to open the model (#3120). + + + +- Tools: `tools/exact_restarts.py` checks the exact path end to end, comparing token ids across fresh restarts, `--parallel` levels, busy versus alone requests, and drafting on versus off (#4574). + +- Gemma 4 on CUDA (assistant and DFlash drafters) and one more MoE family's CUDA loader: loading now refuses a checkpoint with tensors the engine never binds, each scoped to its own directory or prefix (#4566). + +- Flash Next on CUDA: `TF_FLASHNEXT_GDN_CHAIN_TPR=1` runs short verify windows (under 64 rows) on the existing two-threads-a-row GDN chain kernel, which keeps the same bits with one shuffle level instead of five; off by default until the GB10 measurements (#4484). + + + +- CUDA qmmf: `TF_QMMF_HALF_BN=1` uses half-column (32-wide) tiles for FP4, FP8 and FP8-group GEMVs on GPUs with many SMs, splitting only along output columns so each output keeps its accumulation; GB10 behaviour is unchanged when off (#4533). + +- Inkling 2 Mini: native serving on CUDA (one rank, NVFP4 and MXFP8 experts) and Metal, with kernel contracts on both (#4387). + +- Flash Next on Metal: `--ssd-experts GIB` now fits an oversized SSD expert pool to the load ceiling instead of refusing the load; nothing changes without the flag (#4811). + +- Metal on M5: 5-bit and 6-bit group-64 checkpoints get split-plane storage and register-direct lane kernels (#4419). Thanks @gilby. + +- Qwen3.5/3.8 on CUDA: `TF_Q35_GROUP_PROJ=1` runs same-input projections (MLP gate+up, GDN qkv+z and a+b, attention q+k+v) as segments of one qmmf launch, each keeping its own split-K and K-slice accumulation, so every output is computed exactly as by its own launch; off by default (#4515). + +- Drama 3: the GB10 check script passes again after #4144. A PCM-only difference within one 16-bit step is reported, and every exact check still has to pass (#4463). Thanks @plotarmordev. + +- GLM-5.3-Flash on Metal: the rows-store staging permit is now sized from the model's whole image at the window, so deep saves past 1 GiB are kept and a restarted server resumes instead of prefilling again (#4216). Thanks @devopsfortunato. + +- Inkling 2 on HIP: attention kernels under the kernel contract (#4633). + +- Qwen3.6-35B-A3B on Metal: the text-only checkpoint serves on the routed expert path, `--vision` refuses it by name, and `tf-qwen27-run --stages DIR` writes each layer's stream for a float64 comparison (#3239). Thanks to @cshintov. + +- Metal Qwen3.8-27B with MTP drafts: `TF_Q27_MTP_GPU_PICK=1` runs each MTP absorb in one command buffer and picks draft tokens on the GPU, removing two blocking waits per absorb and the CPU pass over the vocabulary; off by default (#4570). + +- Idol: octree and decode-trace allocation failures now unwind cleanly and free what they hold, with successful output unchanged (#4304). + +- Idol runs end to end natively on M5 Metal: `tf-idol-generate` takes one preprocessed picture through DINOv3, the FLUX.2 VAE, the denoiser's 50 guided steps and both decoders to a 3DGS PLY and camera. On an M5 Ultra it is 29.1 s against 95.4 s for the SDK's IdolPipeline on MPS (excluding its preprocess), the denoiser 27.5 s against 93.9 s, at a 2.71 GB peak footprint against 12.88 GB. Given the SDK's starting and VAE noise the PLY's points sit as close to the SDK's as sampling resolves, and the camera's angles within 0.006 rad (#1780, after #1773, #1774 and #1775, for #1757). Thanks to @jayleaton. + +- Flash Next on CUDA: the MTP draft rows' best value, first id and log-sum-exp run over 32 one-warp blocks a row in place of one 1024-thread block, with the same bytes (#4632). + +- Desktop: the app typecheck passes again after two engine types were restored (#4829). + +- GLM on CUDA: a prefill cancelled between chunks keeps its completed shared-cache prefix (#4694). + +- Ling-3.0-tiny on ARM CPUs: an exact decoder for the published 4-bit GGUF, built and launched on aarch64 Linux (#4266). + +- DFlash2 drafter on CUDA: `TF_DFLASH_QL_SPAN=1` reads only the vocabulary span the drafter uses from an NVFP4 or FP8 target lm_head, and `TF_DFLASH_GRAPH=1` captures the drafter's hold and absorb steps in CUDA graphs; target outputs and accepted tokens are unchanged; both off by default (#4516). + +- Flint on Metal: a shared round's sampled rows draw in one launch instead of one serial launch a row, with the same tokens (#4780). + +- HIP Qwen: use the policy prompt step on lone RDNA 3.5 iGPUs while preserving admitted streams and requested prompt caches (#4207). Thanks to @AbrahamCete. + +- MOSS-Image contract: the reference for `tf_me_conv` now follows fp32 `expf` overflow, so its sums check no longer fails on inputs near -89 (#4794). + +- HIP decode: multi-row rounds weigh each slot's rows from one read of their values (#4754). + +- H3 on Macs: long image renders give way to live speech on the GPU (#4650). + +- GLM TP=2 decode on CUDA: `TF_GLM_WIDE_EXPERT_TILE=1` runs routed-expert down for decode windows wider than 16 rows with the 64-pair factored tile that matches gate-up, keeping each output's K order; off by default (#4565). + +- Qwen 3.5 on Metal: `TF_QWEN35_CHUNK` sets the prefill chunk size for measurement; the default stays 128 rows (#3762). + +- CUDA: Ripple-65B-Preview (ricursive) serves on the native engine from the publisher's NVFP4 release as published, with prompt chunks and decode, lane rounds as CUDA graphs, greedy and sampled draws, kept states and the prompt cache; the bf16 release is refused by name, and structured output and forced tool calls are refused until masked sampling lands (#2302, fixes #2300). Thanks to @jrb-ai. + +- GLM-5.3-Flash on CUDA: with `--learn-conversations`, conversation states are kept on disk through the rows store, so after an eviction or a restart the next turn reads its state back instead of prefilling the whole conversation; at TP>1 every rank's part goes to rank 0's disk, so a state is read back on every rank or none (#1411, fixes #1312). Thanks to @wojo. + +- Qwen on Metal: with `TF_Q27_KV_GROW=` (a multiple of 16; 0 or unset is off) a serve's K/V slots start at that many rows, grow as their streams do and give the rows back when a stream ends, and drafter tap rings grow the same way; replies are byte-identical with it on or off (#1896). Thanks to @grantoverton. + +- LFM3 on Metal: warm turns, so a tool loop whose re-rendered history changes mid-conversation re-prefills only from the first changed token, with outputs identical to a fresh run (#4585). + +- GLM, MiniMax and Nemotron on CUDA: each is placed by `--tp`, `--rank`, `--master` and `--master-port`, and `--master` with `--master-port` sets `NCCL_COMM_ID` when it is unset (a different one refuses); `TF_GLM_RANK`/`TF_GLM_WORLD`, `TF_MINIMAX_RANK`/`TF_MINIMAX_WORLD` and `TF_NEMOTRON_RANK`/`TF_NEMOTRON_WORLD` still work as aliases until 1.3.1, with a start-up warning, and a flag and an alias that differ refuse (#2919, part of #2560). Thanks to @laudney. + +- Gemma 4 on Metal: a new stream's prompt fills one chunk per call at the same chunk cuts as before, with other streams' decode rounds running between chunks, so a long prompt no longer freezes their replies; a cancel between chunks keeps the last finished chunk, and a drafting stream's drafter takes each chunk's tapped rows as it lands (#3025, fixes #3021). + +- Qwen3.5/3.8 on CUDA: `TF_QWEN35_ATTN_ALL_ROWS=1` sends multi-row BF16 decode windows to the existing rows attention kernel at every context length (it already matches the one-row kernel's score and reduction order), removing the dead second launch below 8K; off by default (#4496). + +- Tests: a GB10 check compares Qwen CUDA prompts run in one pass against 512-row capped cuts with a second stream live, byte for byte and over the next 64 greedy tokens (#4586). + +- Flash Next on Metal: `TF_FLASHNEXT_BATCH_GDN_WIDE=1` runs 8- and 16-row batch segments on the existing non-replay GDN kernel instead of the recorded pipe; off by default until the M3 and M5 checks (#4489). + +- Host status: the lane host's status read copies a snapshot the engine thread publishes, so a monitoring client polling the status no longer holds the lock every decode round takes; a torn read retries and the round waits for no reader (#3200). + +- Qwen3.8-27B family on Metal: tied embedding heads are accepted, binding the output projection to the embedding weights; small tied Qwen shapes still wait for their own size qualification (#4519). + +- Server: `tensorfold capabilities --json` now lists `TENSORFOLD_PARALLEL` and the other environment variables `serve` honours, so the desktop app's Engine variables page accepts them (#4588, fixes #3684). + +- Tests: host tests record where capped prompt chunks cut while another stream is live, family by family (#4579). + +- Tests: the lone-driver third-prompt test no longer hangs when its poller is descheduled (#4783). + +- Lanes: the opt-in shared price log also covers the shared-drafts grant path (#4686). Thanks @eXsoR65. + +- Qwen3.8-27B on Metal: Macs with tensor units that are not Ultras (an M5 Max, for example) now take 8-bit prompt chunks in row blocks, one dispatch for many 16-row windows, as Ultras already did, instead of re-reading the weights for every 16-row window; Ultras are unchanged (#3280, refs #2851). Thanks to @scchumbletech. + +- Metal: Nemotron, Qwen3.8-27B and LFM2 build their prompt pick kernels from one source, with tokens unchanged (#4739). Thanks @jschmied. + +- Draft depth: a lone stream with a fixed-block drafter, such as Inkling 2 Mini's DSpark, is now priced for the full block it runs, as shared rounds already were, so single requests propose full blocks (#4457). Thanks @gilby. + +- Docs: the runbook says GLM-5.3-Flash on Metal shares 16 rows between streams, so drafts fill only the rows left over (#4722). Thanks @SashaMIT. + +- Docs: the credits say the native CUDA engine serves EXL3 packs (#4743). Thanks @Bizuayeu. + +- Metal: Nemotron's offline build uses the shared expert kernel sources, and two duplicate files are gone; the kernels are unchanged (#4738). Thanks @jschmied. + +- Docs: a plan for Inkling 2 Mini on CUDA and Metal in slices a contributor can claim (#4274). Thanks @akol1. + +- Docs: the Flash Next HIP recipe adds the measured four-rank serve path and fixes its receipt link (#4669). Thanks @timmyit. + +- Desktop: the app changelog lists the Room, Kanban and saved-bot changes (#4376). Thanks @garvrao80. + +- Speech: Drama 3 voice startup and listing move into one module, and speech sampling can take a caller's defaults and top-k ceiling; existing limits are unchanged (#4609). Thanks @BobClawblaw. + +- Tests: the CUDA Idol decoders' contract reference rounds tiled attention's P to fp16 at each 64-key tile's running maximum, as the kernel and torch's CUDA flash and memory-efficient attention do, instead of at the final maximum, which went red at 16x1000x65 on an RTX 5090; a host test checks it against an fp32 online-softmax simulation, and the decoder self attention's gate 4 computes its alike keys' outputs once instead of for all 8,192 tokens (#4508, after #1858). Thanks to @AIFlowML. + +- Docs: the optimization ledger's cells catch up with PRs that landed since it was last updated (#4580). Thanks @jschmied. + +- Unlimited-OCR-2: a cancelled request now stops before image encoding, between images and between decoder prefill chunks instead of running the whole prefill; uncancelled replies are unchanged (#4528). + +- Lane host: under stepped prefill, a waiting stream no longer pins its kept prompt state, so another stream's cache can't be allocated past the budget; an evicted state is looked up again before the first call. Tokens unchanged (#4751). + +- Tests: a per-template tool-call conformance test renders tool definitions, round-trips calls and results, keeps multi-call order and rejects malformed calls for every chat template family we ship (#4555). + +- Server web fetches: hostname lookup now uses the shared bounded resolver, so a request's deadline holds even when the system lookup is slow, and long answer lists are read while they arrive (#4551). + +- Qwen 3.5 and 3.8: one EOS rule for every family reader, and qwen27 now reads `generation_config.json`, so its stop tokens match the served set on the ten configs that declare `<|im_end|>` (#4678). Thanks @devopsfortunato. + +- Nemotron on CUDA: `TF_NEMOTRON_WIDE_ROUNDS=1` (opt-in) runs decode rounds of up to 16 streams; +2% to +6% at 16 streams on a GB10, tokens unchanged; off changes nothing. + - macOS: the native server links `memcpy` from libSystem again (Hy4-flash config parsing no longer pulls in compiler-rt), and two macOS-only tests match current behaviour. - Metal: the row projection picks its narrow or wide kernel per chip (generation plus Pro/Max/Ultra), so an M5 Max no longer runs 8-row and wider windows on the kernel that is slower there; M5 Ultra and unlisted chips are unchanged, tokens unchanged (refs #3396). Thanks to @Spectre056 for the M5 Max measurements. - Metal: a stream whose setup fails partway no longer leaves the prompt cache smaller by its bytes in Llama, Ripple, Spark2.5, Flint, Step-5 and MiniMax-M3. - - - CUDA: `TF_CUDA_POOL_AFTER_WARMUP=1` (opt-in) sizes dense Qwen3.5's still-empty KV page pool again after warm-up, from the free memory then measured under the same reserve and cap, so pages the first plan held back for warm-up become KV capacity; `/memory` reports the decision; tokens are unchanged, and other modes keep today's pool (#4591). - Gemma 4 on CUDA: `TF_GEMMA4_ARGMAX_GRAPH=1` (opt-in) captures the greedy verify round's argmax in the target graph, skips the token download greedy rounds never read and uploads per-forward metadata from pinned memory; same kernel and inputs, so tokens are unchanged (#4616). @@ -22,8 +166,6 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - Lanes: drafted lone streams in families that opt in to copy pricing are priced as in 1.3.3 again; up to 2.5% faster at 4 code streams on M3 and M5 Ultra with the DFlash2 drafter, level elsewhere, tokens unchanged. - Lane host: score requests and server shutdown wait on their own conditions, so neither can hang when a timed waiter on a shared condition times out with a wake pending. - - - Flash Next on Metal: `TF_FN_GX_GATEUP_MB2=1` (opt-in) decodes each expert's gate/up weights once for two rows; about 2% faster at 4 code streams on an M5 Ultra, tokens unchanged (refs #1486). - Docs: AGENTS.md, CONTRIBUTING.md and the ATC instructions say what installing ATC does and pin it to a tag, explain what a public check-in sends, and have agents ask before one: without the human's yes they pass `--local` (#4235). Thanks to @squirtymcgirt. @@ -49,6 +191,7 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - Qwen3.5/3.8 on CUDA: `TF_Q35_DFLASH_ABSORB_BATCH=1` (opt-in) absorbs a DFlash2 round's streams in one pass, reading the drafter's weights once a round; about 1-2% faster at 4 streams on GB10, tokens unchanged. + ## 1.3.4 - Lanes: #3728's lone-stream copy pricing applies only to a family that opts in and serves without a model drafter (Qwen3.5/3.8 on HIP with copies only), so copies-only decode on AMD Strix Halo keeps 1.3.3's speed, while streams with a model drafter price their drafts as before; tokens are unchanged. diff --git a/RUNBOOK.md b/RUNBOOK.md index 517ce83d678..452b9a795c5 100644 --- a/RUNBOOK.md +++ b/RUNBOOK.md @@ -112,6 +112,7 @@ Omit `--parallel` to use `auto`, which asks for up to eight streams as memory an Use `--parallel N` for an explicit cap; the engine refuses a count it cannot fit. Read the startup capacity line, such as `8 streams at once` on CUDA, for the accepted count. For example, `--parallel 4` keeps at most four requests active while the fifth and later requests wait. +On Metal, a GLM-5.3-Flash shared round holds 16 rows, one per active stream. Drafts fill only the rows left over: 8 spare rows at 8 streams, none at 16, so drafting speeds up fewer streams as the stream count rises. Replies are the same tokens either way. See #4311 for the measurements. Completing or cancelling an active request frees its slot; cancelling a waiting request removes it from the queue. Leave the server running and check it from another terminal: diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index 41dddc6123e..e78c64b2b7e 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -332,7 +332,7 @@ These follow a model's release code or a library's model code for their math, ro - `tools/lfm3/ref64.py` and `zig/kernels/xpu/lfm3.cl`: `modeling_lfm3.py` in [LiquidAI/LFM3-1.7B](https://huggingface.co/LiquidAI/LFM3-1.7B). Copyright Liquid AI, LFM Open License v1.0; see [the license text](LICENSES/LFM-Open-1.0.txt). - `zig/kernels/metal/minimax_m3/glue.metal`: the rounding points of `modeling_minimax_m3_vl.py` in [transformers](https://github.com/huggingface/transformers). -- `zig/src/families/ricursive/` (its layer order and rounding points), `zig/kernels/metal/ricursive/glue.metal` and `tools/zig/ricursive_reference.py`: `modeling_ricursive.py` in [ricursiveAI/Ripple-65B-Preview](https://huggingface.co/ricursiveAI/Ripple-65B-Preview) at revision `240d5966cbe00f0627c699e59ef58560b60303cf`: the scaled embedding, the value residual, the per-head q/k norms, RoPE on sliding layers only, the fp32 sigmoid gate, the clamped SwiGLU and the four norms a layer. The release's SGLang model `inference/server/model.py` computes the same layers; what is in it alone is its serving (the W4A4 kernels, the capture of hidden states for a drafter), which this family does not take. Copyright ricursiveAI, Apache License 2.0; see [the license text](LICENSES/Apache-2.0.txt). The reference's `--release` mode imports the release's own `modeling_ricursive.py` from the checkpoint at run time; TensorFold does not include it. +- `zig/src/families/ricursive/` (its layer order and rounding points), `zig/kernels/metal/ricursive/glue.metal`, `zig/kernels/cuda/ricursive.cu`, `ricursive.cuh`, `ricursive_prep.cu`, `ricursive_prep.cuh` and `tools/zig/ricursive_reference.py`: `modeling_ricursive.py` in [ricursiveAI/Ripple-65B-Preview](https://huggingface.co/ricursiveAI/Ripple-65B-Preview) at revision `240d5966cbe00f0627c699e59ef58560b60303cf`: the scaled embedding, the value residual, the per-head q/k norms, RoPE on sliding layers only, the fp32 sigmoid gate, the clamped SwiGLU and the four norms a layer. The release's SGLang model `inference/server/model.py` computes the same layers; what is in it alone is its serving (the W4A4 kernels, the capture of hidden states for a drafter), which this family does not take. Copyright ricursiveAI, Apache License 2.0; see [the license text](LICENSES/Apache-2.0.txt). The reference's `--release` and `--release-f64` modes import the release's own `modeling_ricursive.py` from the checkpoint at run time; TensorFold does not include it. - `zig/src/vision/qwen_cuda.zig`: `Qwen3_5VisionModel` in transformers. - `zig/src/core/picture/patches_test.zig`: recorded image-processor output data from `Lfm3VlImageProcessor` and `Qwen2VLImageProcessor` in transformers; the processing implementation is described below. - `zig/src/families/flashnext/rotary_config.zig`: `_compute_yarn_parameters` in transformers, for the 64 rotary dims. @@ -567,6 +567,30 @@ those files. `tiny_config.json` and the tensor tables `0a57c72e4e5b68aafe1d983dbb62980344a5fcd7`, a randomly initialised model whose model card names that release as its base model and states no licence; no weights are included. `tools/zig/inkling2_fixtures.py` rebuilds all of these files. +## Inkling 2 Mini fixtures and loop references + +`mini_config.json`, `mini_model_header.txt` and `mini_mtp_header.txt` in +`zig/src/families/inkling2/fixtures/` come from the 2026-11-20 published snapshot of +[thinkingmachines/Inkling-2-Mini at `ed40e7da625f594fc9c4990f5f66be24873c22d7`](https://huggingface.co/thinkingmachines/Inkling-2-Mini), under the Apache License 2.0 +stated on its model card (see [the license text](LICENSES/Apache-2.0.txt)). The public model API supplied that full revision and last-modified time 2026-11-20T22:55:20Z. The fixture config differs from the supplied published `config.json` only by its explicit `_fixture_provenance` annotation; after excluding that annotation, every checkpoint config field matches. The folded tables contain only metadata from the model and MTP safetensors +headers, no tensor data or weights. `tools/zig/inkling2_fixtures.py` rebuilds all three from the Mini release, or from its +extracted headers, with the same revision annotation. No revision was derived from fixture digests. + +`release_chat_template.jinja` and `release_tokenizer_config.json` in the same folder are byte-identical copies of that +revision's `chat_template.jinja` and `tokenizer_config.json`, under the same license. + +The Mini loop host/reference implementations in `zig/src/families/inkling2/loop.zig`, `loop_model.zig`, `loop_engine.zig`, +`loop_math_cuda.zig`, the CUDA and Metal loop kernels and the stored-expert implementations in `modelopt.zig` and +`zig/kernels/cuda/inkling2/modelopt.cu` are independent TensorFold implementations of the supplied math-only Mini +specification. Its primary reference is huggingface/transformers PR #51050 at head `6173a2f6`: the Mini configuration and +forward pass in `models/inkling2_loop/modular_inkling2_loop.py` and `modeling_inkling2_loop.py`, with the temporary +NVFP4/MXFP8 expert dequantization in `core_model_loading.py` and the checkpoint mappings in `conversion_mapping.py`. +ModelOpt here names the checkpoint format and that Transformers arithmetic; no NVIDIA Model Optimizer source was used or +vendored. The specification also records Neywa-Labs/mlx-vlm at `fd6404fb` as its second reading of the loop and DSpark +implementation (`mlx_vlm/models/inkling2/` and `mlx_vlm/speculative/drafters/inkling2_dspark/`). Transformers is Apache-2.0; +mlx-vlm is MIT (see [`LICENSES/MIT.txt`](LICENSES/MIT.txt)). No reference source code is vendored. The supplied materials +give only these two abbreviated reference heads, not their full commit SHAs. + ## Inkling 2 attention kernels `zig/kernels/cuda/inkling2/attention.cu`, `zig/kernels/cuda/inkling2/prompt_attention.cu` and @@ -585,3 +609,13 @@ these layers of Hugging Face transformers' `src/transformers/models/inkling2/mod `Inkling2NormedEmbedding`, `Inkling2BlockAttentionResidual`, `Inkling2ShortConvolution`, `Inkling2DynamicShortConvolution`, `Inkling2TopKRouter`, `Inkling2SoftcappedSwiGLU` and `Inkling2Softcap`. The kernels are TensorFold's own. + +## Inkling 2 expert and vision kernels + +`zig/kernels/cuda/inkling2/experts.cu` and `zig/src/families/inkling2/experts.zig` run `Inkling2Experts` from Hugging +Face transformers' `src/transformers/models/inkling2/modeling_inkling2.py` at commit `109a7d19bf66` +([huggingface/transformers](https://github.com/huggingface/transformers), Apache-2.0) on main's EXL3 grouped-expert +arithmetic. `zig/kernels/cuda/inkling2/vision.cu` and `zig/src/families/inkling2/vision.zig` compute the same file's +vision tower: `Inkling2VisionEmbeddings`, `Inkling2VisionRotaryEmbedding`, `Inkling2VisionAttention`, +`Inkling2VisionMLP` and `Inkling2VisionMerger`. `zig/src/families/inkling2/image.zig` follows `Inkling2ImageProcessor` +in `image_processing_inkling2.py` at the same commit for its 40-pixel patches and the tower's input tables. diff --git a/app/CHANGELOG.md b/app/CHANGELOG.md index d96ef06a356..29a8ec779e2 100644 --- a/app/CHANGELOG.md +++ b/app/CHANGELOG.md @@ -14,6 +14,18 @@ current source and are awaiting a packaged Desktop release. [#3357](https://github.com/ashhart/TensorFold/pull/3357) - Rooms show completed tickets out of the total. An agent can release its own idle ticket claim so another seat can take it. [#3698](https://github.com/ashhart/TensorFold/pull/3698) ยท [#4081](https://github.com/ashhart/TensorFold/pull/4081) +- Room health shows the Room's worktree path and Git branch. + [#3463](https://github.com/ashhart/TensorFold/pull/3463) +- Room settings save when you select **Supervisor** or apply the **Supervised build** preset. + [#3472](https://github.com/ashhart/TensorFold/pull/3472) +- Use **Details** to view and edit a Kanban ticket's title, description, type, priority and effort. + Archived tickets can be restored. [#3464](https://github.com/ashhart/TensorFold/pull/3464) +- Moving a parked ticket to **Ready** clears its assignee so another Room seat can take it. + [#3469](https://github.com/ashhart/TensorFold/pull/3469) +- New Solo and Room ticket worker chats appear in the sidebar as soon as they're created. + [#3461](https://github.com/ashhart/TensorFold/pull/3461) +- Each saved bot can have its own reasoning effort. Bots without a saved effort use the app default. + [#3500](https://github.com/ashhart/TensorFold/pull/3500) - **Replay as new task** accepts one launch at a time, so a second click during a launch creates no duplicate task. [#3848](https://github.com/ashhart/TensorFold/pull/3848) - **Export Run** waits for a preview that matches the selected run, mode and redaction settings diff --git a/app/electron/agent/engine/hub.ts b/app/electron/agent/engine/hub.ts index a588b0f5707..5ecfcc922a1 100644 --- a/app/electron/agent/engine/hub.ts +++ b/app/electron/agent/engine/hub.ts @@ -176,6 +176,7 @@ export interface PreflightContext extends HubDeps { installedRevision?: (repo: string) => Promise drafterFor: (repo: string) => string | null cachedBytes: (repo: string) => Promise + freeDiskBytes: () => Promise now?: () => number } diff --git a/app/electron/agent/engine/model-hub.ts b/app/electron/agent/engine/model-hub.ts index 7d0baa52b95..4f19f1c16a6 100644 --- a/app/electron/agent/engine/model-hub.ts +++ b/app/electron/agent/engine/model-hub.ts @@ -17,6 +17,7 @@ interface ModelHubOptions { installed: () => Promise installedRevision: (repo: string) => Promise cacheDir: () => string + memory: () => { limit: number; budget: number; limitFor?: (modelType: string | null) => { bytes: number; basis: string } } } const OFFLINE = /^(1|true|yes|on)$/i diff --git a/build.zig b/build.zig index fc206807364..f4a3d30d864 100644 --- a/build.zig +++ b/build.zig @@ -72,6 +72,7 @@ pub fn build(b: *std.Build) void { @import("zig/build/tokenizer_host.zig").steps(b); @import("zig/build/cluster_host.zig").steps(b); @import("zig/build/lane_halt_host.zig").steps(b); + @import("zig/build/lane_status_host.zig").steps(b); @import("zig/build/cache_replay.zig").steps(b); @import("zig/build/dsv41_shared.zig").steps(b); @import("zig/build/dsv41_cuda.zig").steps(b); @@ -159,6 +160,7 @@ pub fn build(b: *std.Build) void { for ([_][]const u8{ "noise", "schedule" }) |name| { test_step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = b.createModule(.{ .root_source_file = b.path(b.fmt("zig/src/families/moss_image/{s}.zig", .{name})), .target = target }) })).step); } + @import("zig/build/metal_cost_host.zig").compile(b, draft_ids); const cost_cases = b.addTest(.{ .root_module = b.createModule(.{ .root_source_file = b.path("zig/cost_rule_cases.zig"), .target = target, @@ -289,6 +291,7 @@ pub fn build(b: *std.Build) void { @import("zig/build/save_guard.zig").wire(b); @import("zig/build/cpu_contract.zig").steps(b, test_step); @import("zig/build/bf16_round.zig").wire(b, test_step); + @import("zig/build/chunked_write.zig").wire(b, test_step); @import("zig/build/qwen35_layers.zig").wire(b, test_step); @import("zig/build/dev_tools.zig").wire(b, target); @import("zig/build/profile.zig").wire(b, test_step); diff --git a/docs/api.md b/docs/api.md index e96b374b412..9140250a706 100644 --- a/docs/api.md +++ b/docs/api.md @@ -647,6 +647,8 @@ whole first, in arrival order, as 0.3.6.2 did. Background work waits behind foreground requests. An active background request yields when a foreground request needs its lane or memory, then restarts with already-delivered tokens suppressed. +`TENSORFOLD_PRIORITY_AGE_MS` above 0 lets a background request queued for at least that many milliseconds go before +foreground work. Prefix, disk-read, lane and memory admission checks are unchanged. Session-title requests are also treated as background work. The serve flags `--top-p`, `--top-k` and `--min-p` set the server's defaults for the request fields of the same @@ -1453,7 +1455,9 @@ store for each model and build. That store takes the place of `--learn`'s store with the flag neither reads nor writes the prefix files a plain `--learn` server keeps, and they stay on disk until the cap below needs their room. After a restart, a crash or an eviction from RAM, the next turn reads the latest state back instead of reading the conversation again from its first token. Qwen3.8-27B, Nemotron, Flash Next and GLM-5.3-Flash on -one Mac, and Nemotron, the Qwen3.5 hybrids and Flash Next on CUDA, keep them; other engines refuse the flag at startup. +one Mac, and Nemotron, the Qwen3.5 hybrids, Flash Next and GLM-5.3-Flash on CUDA keep them; other engines refuse the +flag at startup. GLM-5.3-Flash on CUDA across ranks writes every rank's part to rank 0's disk, so a state is read back +on every rank or on none; it takes neither `--spill-gib` nor `--checkpoint-slots`. The engine stages an owned copy between rounds, and an I/O thread writes and fsyncs it. Staging has a 1 GiB byte permit and at most eight jobs. Qwen3.8-27B widens the permit to one whole state at its `--context`, with none of its rows on diff --git a/docs/credits.md b/docs/credits.md index 483e4be3816..36e54f53ce2 100644 --- a/docs/credits.md +++ b/docs/credits.md @@ -159,7 +159,8 @@ row-invariant linear, grouped experts and the 27B and Flash Next packs ([cuda/exl3](https://github.com/ashhart/TensorFold/tree/v0.6.6/src/tensorfold/cuda/exl3), [exl3.md](https://github.com/ashhart/TensorFold/blob/v0.6.6/docs/recipes/exl3.md)). The native EXL3 decoder (`zig/src/core/exl3_format.zig`, `exl3_projection.zig`) follows the format notes from #42, and the EXLR8 codebook -that serves GLM-5.3 builds on that decoder. The native engine does not serve EXL3 packs yet. +that serves GLM-5.3 builds on that decoder. The native CUDA engine serves EXL3 packs too: GLM-5.3-Flash's routed +experts, Qwen3.5's `mul1` and `mcg` checkpoints, and Muse Spark Open's 1.8-bit pack. ## More Python engine work diff --git a/docs/design/inkling-2-mini.md b/docs/design/inkling-2-mini.md new file mode 100644 index 00000000000..a168fe87ebb --- /dev/null +++ b/docs/design/inkling-2-mini.md @@ -0,0 +1,127 @@ +# Inkling 2 Mini on CUDA and Metal: a plan in claimable slices + +The maintainer agreed this plan and its gate on 2026-11-21 in pull request #4274's discussion. The maintainers are building the host slices and all three backends themselves for the next release; a contributor who wants a slice says which one in that discussion before starting, so nothing is built twice. +It splits the work into slices small enough for one contributor each. +#4265 proposes the same model on HIP; the host slices below are shared with it and should have one owner. + +## Decisions + +Answered by the maintainer in #4274's discussion on 2026-11-21; answer 2 carries the later correction. + +1. Inkling 2 Mini is wanted on CUDA, Metal and HIP, as one plan with #4265, with the host slices shared. +2. The contract for the routed experts is the reference pull request's arithmetic: the stored NVFP4 and MXFP8 weights decoded in registers, bf16 activations, FP32 sums, with the per-expert NVFP4 factor rounded to bf16 as it loads. The activation quantization `hf_quant_config.json` declares is not pinned down by the file itself and can come later as an opt-in with its own quality gate. +3. sm_12x first, with the stored FP4 and FP8 arithmetic. Older chips can follow as their own pull request. +4. Metal starts from the original checkpoint (BF16 dense weights, the stored experts, the drafter file), so all three backends run the same weights. +5. The loop lives in the `inkling2` family. +6. The gate under "Gate" is agreed. The speed bar: decode no slower than a standard server on the same machine, with and without the drafter. +7. No separate issues for now: the maintainers are building the host slices and all three backends in parallel themselves for the next release. A contributor who wants a slice says which one in the discussion before starting. + +## What main has + +On main `72ebe5f6e`: + +- `zig/src/families/inkling2` is Inkling 2 Small's host package (#3578): config, weight names, layer plan, chat template and tokenizer tests. It accepts `inkling2` only, so Mini's `inkling2_loop` is refused. +- CUDA has Inkling 2's attention kernels (#4125) and glue kernels (#4126) under the kernel contract. +- Open for Small on CUDA: expert and vision kernels (#4127), drafter kernels (#4128), the reply split (#4124) and the EXL3 loader (#3612). +- Metal has no Inkling 2 kernel. It has NVFP4 code for Drama 3 and an attention residual for Kimi K3; whether either fits Inkling 2 is not established here. +- No backend serves Inkling 2 end to end. + +## What Mini is + +From `thinkingmachines/Inkling-2-Mini` (Apache-2.0), `config.json` and the model card as published on 2026-11-20: + +- 26.4B parameters, text and images in, text out. One 19.5 GB safetensors file and a 0.64 GB drafter file. +- 24 layers of weights, hidden 2,304. Layers 6 to 17 run three passes, so a token makes 48 layer visits. +- Layers 5, 11, 17 and 23 see the whole context; the other 20 slide over 1,024 tokens. 24 query heads and 8 key heads of 128. +- 128 routed experts of 1,152 a layer, 8 a token, no shared expert. NVFP4 in layers 0 to 19 and MXFP8 in layers 20 to 23; everything else is BF16 apart from a few FP32 tensors. +- A vision tower of 23 layers, 1,024 wide, patch 20 with a 2 by 2 merge. +- A DSpark drafter in `mtp.safetensors`: 3 layers, blocks of 8 tokens, taps at visits 5, 23, 41 and 48. +- The tokenizer and chat template are the same files as Small's, as #4265 reports. + +What Mini adds over Small is the loop: a cache slot per visit, rank-64 gates on the core layers' inputs in passes 2 and 3, and learned cross-pass queries over the previous pass. + +Memory, estimated from the config and not measured: + +- The global layers are visited 8 times. With 8 key heads of 128 in BF16 that is 32 KiB a token: 4 GiB at 128K and 32 GiB at 1M. +- The sliding layers are visited 40 times; their rings hold about 160 MiB a stream. +- So one GPU or one Mac holds the model, and no slice below needs more than one rank. + +## Upstream references + +- The loop's reference code is not released: it is in Transformers' open pull request huggingface/transformers#51050 (head `6173a2f6` on 2026-11-20), on top of the released `inkling2` model. +- That pull request dequantizes the NVFP4 and MXFP8 experts on load and marks this as temporary. Its arithmetic is the experts' contract: stored weights decoded in registers, bf16 activations, FP32 sums. +- SGLang's open pull request sgl-project/sglang#51926 runs the experts with the activation quantization `hf_quant_config.json` declares, which is not the contract and is at most a later opt-in comparison. As reported in this plan's review, its rounding differs between its SM100-series and SM120 paths; neither point is checked here. If the opt-in is built, H3, C3 and M3 name the path and its rounding points. +- llama.cpp merged the model on 2026-11-20 (ggml-org/llama.cpp#32694), so it is one candidate for the standard server on both backends. vLLM is another on NVIDIA. +- No speed for a DGX Spark or for Apple silicon was found published; the receipt's baseline has to be measured on the claimant's machine. + +## Slices + +Each slice is one pull request with its own tests. "Needs" names what must land first. + +### Host, shared by CUDA, Metal and HIP + +| Slice | What | Needs | +|---|---|---| +| H1 | `families/inkling2` accepts `inkling2_loop`: parses `loop_config`, refuses `is_varloop`, builds the visit plan (layer, pass, cache slot, message sources) and counts drafter taps by visit. Small's tests pass unchanged. This is #4265's first slice. | none | +| H2 | Names for the controller and cross-pass tensors, and each layer's expert precision read from Mini's headers, with fixtures from the published config and a tiny checkpoint. | H1 | +| H3 | The loop's arithmetic written down: where each value rounds and the order of every sum for the gates and the cross-pass message, a float64 model, and single-change probes that turn the host tests red. It covers a message that reads two blocks of the previous pass, which Mini's core has and the tiny checkpoint's does not. | H1 | +| H4 | The drafter's host side: `mtp.safetensors` names and shapes against Mini's header, and its four taps mapped to visits and cache slots. Taps 5, 23 and 41 are the inputs to zero-based decoder visits 5, 23 and 41; tap 48 is the post-final-norm output, not a cache slot. | H1 | + +### CUDA + +| Slice | What | Needs | +|---|---|---| +| C1 | Mini's shapes on Small's kernels: served shapes, tiles and limit records for hidden 2,304 and experts of 1,152. | #4126 to #4128 | +| C2 | The loop kernels (gates and cross-pass message attention) under the kernel contract. | H3 | +| C3 | The routed experts as stored, NVFP4 and MXFP8, on sm_12x, with the stored weights decoded in registers, bf16 activations and FP32 sums. Older chips follow as their own pull request. | none | +| C4 | The engine at one rank, text only: 48 KV and conv slots in the pool and in prompt-cache snapshots, the lane adapter, admission and the family registration. Images are refused until C6. | H2, C1 to C3 | +| C5 | DSpark: the checkpoint's drafter on #4128's kernels, with taps by visit, through the shared lane rounds. Drafted output equals plain decode, and decode with it is no slower than without. | C4, H4, #4128 | +| C6 | Images on #4127's vision kernels at Mini's tower shape. | C4, #4127 | +| C7 | The served receipt, the recipe page and the family's optimization ledger cells. | C4 | + +### Metal + +| Slice | What | Needs | +|---|---|---| +| M1 | Sliding and global attention with the sink, the relative bias, log scaling and the L2 clips, on the arithmetic reference #4125 follows. A prompt path for M5 and one for earlier chips. | none | +| M2 | Glue kernels: embedding, the block attention residual, the short convolutions (static and input-dependent), the router, soft-capped SwiGLU and the pick. | none | +| M3 | The routed experts as stored: NVFP4 and MXFP8 decoded in registers, bf16 activations, FP32 sums. | none | +| M4 | The loop kernels under the kernel contract. | H3 | +| M5 | The engine, text only: 48 slots, the lane adapter, admission by memory class and the family registration. Starts from the original checkpoint. | H2, M1 to M4 | +| M6 | DSpark: the drafter's kernels under the kernel contract, then the drafter through the shared lane rounds. MiniMax M3 has the one DSpark drafter on Metal to adapt (`families/minimax_m3/dspark.zig`); Kimi K3's Metal adapter refuses external draft heads. Same checks as C5. | M5, H4 | +| M7 | Images: the vision tower and projector. | M5 | +| M8 | The served receipt, the recipe page and the ledger cells. | M5 | + +H1 to H3, M1 and M2 can start now. C1 waits on Small's stack; C3 and M3 run the bf16-activation arithmetic and have no other dependency. + +## DSpark + +DSpark support is part of the plan on both backends, not an extra: H4, C5 and M6 carry it, and C7 and M8 fill the family's DSpark cell in the optimization ledger. +The engine slices C4 and M5 land first without it, so plain decode exists as the reference the drafter is checked against. +The drafter taps by zero-based decoder visit: 5, 23 and 41 are the inputs to those visits, and 48 is the output after the final norm, not a cache slot. + +## Gate + +The gate is agreed; the speed bar below is its threshold. + +- **Kernels:** each backend's full kernel-contract `SUMMARY` with every planted control red, on the chips named in the pull request. +- **Same-engine exactness,** on the tiny checkpoint and on the released one, greedy and sampled: drafted equals `"draft": false`, a resumed prompt equals a fresh one, and concurrent equals solo. Seams are checked at every pass boundary, for KV, conv state and final logits. +- **Fidelity:** teacher-forced histories against the reference huggingface/transformers#51050, with every top-token difference and its margin recorded. +- **Speed:** a served receipt as CONTRIBUTING describes (decode with and without the drafter, cold first token at one and four streams, cold 2k, 8k, 32k and 64k prompts, peak memory), against a standard server on the same machine. The bar: decode no slower than that server, with and without the drafter. +- **Refusals:** `is_varloop`, `--loops` (Dory's pass-count override), audio parts, and images before the vision slice, each with a test. + +The tiny checkpoint `hf-internal-testing/tiny-inkling2-mini` at revision `ee242a48af34ff0729518f4ac28cfcb847e470ab` has 18 decoder layers, a loop core of layers 6 to 11, and no drafter: its config declares no `mtp_config` and its files ship no `mtp.safetensors`. It covers plain, resumed and concurrent decode. It cannot cover drafted-versus-plain, and with one core block it cannot cover the two-source message case. Draft parity therefore runs on the original checkpoint with its bundled `mtp.safetensors`, recording proposal and acceptance counts. + +## Hardware + +Each claimant states the chips they can run. The plan needs at least one sm_12x GPU (the model card names one DGX Spark, sm_121) and one Mac with 32 GB or more; an M5 and an earlier chip are both needed for M1. +The maintainers run device tests on a GB10, M5 and M3 Ultras, and a gfx1151. +The author of this plan can run one GB10 (DGX Spark, sm_121) and one M4 Max with 128 GiB, and has asked in #4274's discussion for H3, with C3 as the fallback; neither starts before the maintainer confirms. +That covers the CUDA slices on sm_121 and the earlier-chip side of the Metal slices. It leaves two gaps for other testers: an M5 for the tensor-unit prompt path, and any CUDA chip other than sm_121. + +## Related + +- #3476: Inkling 2 Small on CUDA, with the maintainer's answers on the family's shape and on the attention reference. +- #4265: Inkling 2 Mini on HIP. +- #3578, #4124 to #4128, #3612: Small's host package, kernels, reply split and EXL3 loader. +- #3723: a looped model on the qwen3_5 CUDA engine. diff --git a/docs/environment.md b/docs/environment.md index ce95584186e..ea44573afd3 100644 --- a/docs/environment.md +++ b/docs/environment.md @@ -13,6 +13,7 @@ Diagnostics quote and escape the supplied text so it cannot create another termi | `TENSORFOLD_PARALLEL` | Whole count 1 through 4096, or `auto` (`auto` = 8); default: what `--parallel` says. Read only when `--parallel` is not on the command line, so the flag wins; blank keeps the default; other values are refused at server startup | | `TENSORFOLD_PRESSURE_CACHE_PERCENT` | Whole percentage 0 through 100; default 50 | | `TENSORFOLD_PREFIX_WAIT_MS` | Whole milliseconds 0 through 4294967295; zero disables waiting; default 60000 | +| `TENSORFOLD_PRIORITY_AGE_MS` | Whole milliseconds 0 through 4294967295; default 0. Above 0, a background request queued for at least this long may be admitted before foreground requests. Eligibility, memory and lane limits still apply; 0 keeps foreground-first FIFO | | `TENSORFOLD_PULL_CONNECT_SECONDS` | Whole seconds 1 through 4294967295; how long `pull` waits for a connection to the hub, the storage host or the proxy; default 30 | | `TENSORFOLD_PULL_STALL_SECONDS` | Whole seconds 1 through 4294967295; how long `pull` waits for the next byte before it resumes the file with a range request (at most 3 times); default 60 | | `TENSORFOLD_RESTORE_PREFETCH` | Whole unsigned 64-bit count, capped at 65536; zero disables reading ahead; default 2 | @@ -34,9 +35,12 @@ Diagnostics quote and escape the supplied text so it cannot create another termi | `TF_MTP_DRAFTS` | Whole u32 count, clamped to 1 through the drafter's window less one; existing depth when unset | | `TF_TIMING` | Exactly `0` or `1`; default off (each call's wall time on stderr while set) | | `TF_NO_TREES` | Exactly `0` or `1`; default off. `1` keeps the CUDA drafter's chains only, and retains precedence over `TF_DRAFT_NODES` | +| `TF_DFLASH_QL_SPAN` | Exactly `0` or `1`; default off. `1` drafts a ModelOpt NVFP4 or FP8 head over the DFlash2 vocabulary spans; other head formats stay whole | +| `TF_DFLASH_GRAPH` | Exactly `0` or `1`; default off. `1` replays DFlash2 holds and live absorbs from CUDA graphs, with the same kernels and arguments in the same order | | `TF_MTP_TREES` | Exactly `0` or `1`; default off (1 turns the MTP drafter's trees on) | | `TF_MTP_BATCH` | Exactly `0` or `1`; default on. `0` keeps one stream at a time | | `TF_QWEN_KEEP_LATE` | Exactly `0` or `1`; default off | +| `TF_Q35_GROUP_PROJ` | Exactly `0` or `1`, read when a ModelOpt checkpoint loads on CUDA (sm_90 or newer); default off. `1` runs Qwen 3.5 same-input decode projections (MLP gate and up, GDN `in_proj_qkv` and `in_proj_z`, `in_proj_a` and `in_proj_b`, attention q, k and v) as one launch per group, each projection with its own tile and K slices, so outputs keep their bits | | `TF_QWEN_KV_PAGE_TEST` | Whole page size from 1 to 2147483647; unset off. Each cache's own buffer reads through a table of n-position pages in reverse order (checks) | | `TF_QWEN_POOL_LOG` | Exactly `0` or `1`; default off (the pool's census after a prompt pass) | | `TF_COST_KEY_TRACE` | Exactly `0` or `1`; default off (each cost key's parts on stderr) | @@ -47,7 +51,8 @@ Diagnostics quote and escape the supplied text so it cannot create another termi | `TENSORFOLD_HIP_MEMORY_LIMIT_GB` | A positive finite GiB amount whose byte count fits a 64-bit size | | `TF_DSPINE_WINDOW` | Qwen3.8-27B on CUDA with a DSpine `--drafter`: whole row count 16 through 8192 that narrows the drafter's sliding window; it must be at least the block (16) and at most the checkpoint's own `sliding_window`, else the drafter is refused when it opens; unset or blank keeps the checkpoint's (8192 for tencent/Qwen3.8-27B-DSpine-b16) | | `TF_DRAFT_NODES` | Whole native-size nonnegative count, capped by the drafter's window; zero disables trees | -| `TF_QMMF_HALF_BELOW` | Whole native-size nonnegative block count; zero disables half tiles; default 96 | +| `TF_QMMF_HALF_BELOW` | Whole native-size nonnegative block count; zero disables half tiles; default 96, or two blocks per SM with `TF_QMMF_HALF_BN=1` | +| `TF_QMMF_HALF_BN` | Exactly `0` or `1`, read when a CUDA lane loads; default off. `1` also gives FP4, FP8 and FP8G decode calls of 16 rows or fewer the 32-column half tile, below `TF_QMMF_HALF_BELOW` blocks (default two per SM, so 340 on 170 SMs and 96 on 48). Columns split, never K, so every output keeps its bits | | `TF_HY4_MEM_FLOOR_GIB` | Whole GiB of MemAvailable below which `tf-hy4-cuda-generate`'s loader stops; default 10 | | `TENSORFOLD_PROMPT_CACHE_KEEP_OTHERS` | Exactly `0` or `1`, checked when the CUDA backend starts; default off ([profiles](profiles.md)) | | `TF_PROMPT_INTERMEDIATE` | Exactly `0` or `1`, checked when the CUDA backend starts; default off. `1` keeps Flash Next's ladder of intermediate prompt-cache checkpoints under a long prompt's history | @@ -56,6 +61,7 @@ Diagnostics quote and escape the supplied text so it cannot create another termi | `TENSORFOLD_UNIFIED_HOST_COUNTS` | Exactly `0` or `1`, checked when the CUDA backend starts. An integrated GPU on Linux admits against `/proc/meminfo` with `1` and against the CUDA pool with `0`; unset, it reads the pool under WSL2 (`WSL_DISTRO_NAME` set) and `/proc/meminfo` otherwise ([Windows](WINDOWS.md)) | | `TF_HEAD_GEOMETRY` | Whole native-size nonnegative geometry count in the head benchmark | | `TF_ROCE_GID_INDEX` | Whole index 0 through 2147483647; unset searches for a RoCE v2 IPv4 GID | +| `TF_QWEN35_ATTN_ALL_ROWS` | Qwen3.8 on CUDA: exactly `0` or `1`; unset, empty or `0` keeps the current BF16 decode attention launches. `1` uses the existing rows kernel at every context length and skips the separate partial launch for decode windows wider than one row. The kernel contract compares output bytes against the original dual-launch path | | `TF_QWEN35_CHUNK_SOLO` | Qwen 3.5/3.6/3.8 on CUDA: 4096 or 8192 rows a foreground prompt pass while no other stream decodes (a background warm pass keeps 4096); unset, empty or 4096 is off, with main's scratch. Checked when the model loads, with the family's own message | | `TF_GEMMA4_CHUNK_SOLO` | Gemma 4 on CUDA: a multiple of 512 from 512 through 4096; unset, empty or 512 is off. Checked when the model loads, with the family's own message | | `TF_GEMMA4_ARGMAX_GRAPH` | Gemma 4 on CUDA: exactly `0` or `1`; default off. `1` captures a greedy verify round's argmax (the same `tf_round_bf16_argmax` over the same logits) in the target forward's graph, skips the drawn-token download no greedy entry reads, and stages each forward's ids, positions and slots in pinned memory; target tokens keep their bits | @@ -83,20 +89,25 @@ Diagnostics quote and escape the supplied text so it cannot create another termi | `TF_GLM_WORLD` | GLM-5.3-Flash on CUDA: a whole rank count from 1 through 4294967295, set with `TF_GLM_RANK`; unset with it gives one rank | | `TF_NEMOTRON_RANK` | Nemotron 3.5 Super on CUDA: a whole rank index from 0 through 4294967295, set with `TF_NEMOTRON_WORLD`; unset with it gives one rank | | `TF_NEMOTRON_WORLD` | Nemotron 3.5 Super on CUDA: a whole rank count from 1 through 4294967295, set with `TF_NEMOTRON_RANK`; unset with it gives one rank | +| `TF_NEMOTRON_WIDE_ROUNDS` | Exactly `0` or `1`, checked when the CUDA backend starts; default off. `1` lets Nemotron's shared rounds hold 16 streams and 32 rows on GB10 (one rank, non-latent, not Bolt, no `--precision checkpoint`, no bf16 experts, no Sliding Weights or saved lessons; refused with a log line naming why), each row's bits as in two 16-row rounds; a lone stream's window is unchanged | | `TF_MINIMAX_RANK` | MiniMax-M3.1-Flash on CUDA: a whole rank index, 0 or 1 at two ranks, set with `TF_MINIMAX_WORLD`; unset with it gives one rank | | `TF_MINIMAX_WORLD` | MiniMax-M3.1-Flash on CUDA: a whole rank count, 2 at CUDA, set with `TF_MINIMAX_RANK`; unset with it gives one rank | | `TF_PROMPT_ROWS` | Native serving: a multiple of 16 from 128 through 2048; unset keeps the chip/family default | | `TF_ANE_COLUMNS` | Whole u32 count; zero disables the experimental share; default zero | +| `TF_LFM3_METAL_WARM_TURNS` | Exactly `0` or `1`; default off. Uses one-row LFM3 Metal prefill even with caching disabled. A prompt cache enables background warm turns. | | `TF_METAL4` | Metal: exactly `0` or `1`; `1` sends a family's GPU work through Metal 4 (macOS 26 and later) where the family supports it: the same kernels in the same order, with Metal 4's command queue, allocators, argument tables and barriers, and bit-identical outputs; `0` keeps Metal 3. DeepSeek-V4.1 defaults to `1` where the Mac has Metal 4 (its device test rigs to `0`); Macs without it stay on Metal 3 | | `TF_DSV41_ROUND_PROF` | DeepSeek-V4.1 on Metal: exactly `0` or `1`; `1` logs decode rounds' host milliseconds (first encode to last wait) and GPU milliseconds by rows, every 1,024 rounds; default 0 | | `TF_METAL4_TIMELINE` | Metal 4: a whole round count, default 0; `n` puts a GPU timestamp at every stage (between barriers) of `n` rounds of each kind a family names, after 8 warm ones, and logs their time by kernel and the longest stages. DeepSeek-V4.1 names its decode rounds by rows. Stamps cost GPU time, so stamped rounds read a little long | | `TF_FLASHNEXT_SCALE_INDEX` | Flash Next on Metal: exactly `0` or `1`; default 1, where the 4-bit expert kernels (decode, grouped and prompt gathers) read each group's scale and bias through a 16-bit index into its tensor's table of pairs, the same values from fewer weight bytes, and the routed experts' stored scales and biases are not kept in memory; `0` keeps and reads the stored arrays; ignored with `--ssd-experts` | | `TF_FLASHNEXT_GROUPED_ROWS` | Flash Next on Metal without tensor units: `0`, or the rows (`1` through `32`) from which a decode window runs its 4-bit experts grouped by expert, with the same output bits; default 5; ignored with `--ssd-experts` and in speed-up mode | | `TF_FN_GX_GATEUP_MB2` | Flash Next on Metal, grouped experts only: exactly `0` or `1`; `1` has gate/up decode an expert's 4-bit weights once for two rows, with each row's arithmetic and order unchanged; default 0 | +| `TF_FN_GX_SHARED` | Flash Next on Metal without tensor units: exactly `0` or `1`; `1` uses the existing grouped kernels for eligible shared-round 4-bit/group-32 experts with the per-row kernels' output bits; default 0 keeps per-pair launches; the existing row threshold applies | | `TF_QWEN27_SHARED_PREFIX` | Qwen3.8-27B on Metal before M5: exactly `0` or `1`; `0` keeps cached keys on the tail attention kernel; unset or blank is `1` | | `TF_QWEN27_SLOT_RESUME` | Qwen3.8-27B on Metal: exactly `0` or `1`; `0` stops slot 0 resuming a later prompt; unset or blank keeps it on | | `TF_QWEN27_METAL_KV_PAGES` | Qwen3.8-27B on Metal: exactly `0` or `1`; `1` puts keys and values in core-pool pages (refused on Macs with tensor units); unset or blank is `0` | +| `TF_Q27_MTP_GPU_PICK` | Qwen3.8-27B with `--mtp-drafts` on Metal: exactly `0` or `1`; `1` runs each MTP absorb on one command buffer and picks drafts on the GPU; unset or blank is `0` | | `TF_QWEN27_JOIN` | Qwen3.8-27B on Metal before M5: exactly `0` or `1`; `1` runs a window's rows in pairs over the keys below it in the decode tail attention (same replies); unset or blank is `1` | +| `TF_QWEN27_TIED_HEAD` | Dense Qwen on Metal: exactly `0` or `1`; `1` lets a checkpoint with a tied head load on the 27B engine, its head read from the embedding (one Mac, no draft head, qualified shapes only); unset or blank is `0` | | `TF_QWEN35_METAL_KV_PAGES` | Qwen 3.5 on Metal: exactly `0` or `1`; `1` puts the streams' keys and values in core-pool pages; unset or blank is `0` | | `GLM_EHPROJ_NAX` | GLM-5.3-Flash on Metal: exactly `0` or `1`; `0` serves the MTP head's prompt eh_proj on the scalar kernel; default 1, the tile kernel where it builds | | `TF_DSV41_SMALL` | DeepSeek-V4.1 on Metal: exactly `0` or `1`; `1` reads the checkpoint's config at its own small shapes (the served smoke test's tiny model); default 0 | @@ -166,7 +177,7 @@ Windows uses the same proxy routes and timeout settings through native asynchron ## Flash Next -Flash Next checks these 37 settings when its engine loads, before any device or checkpoint work: a malformed value +Flash Next checks these 39 settings when its engine loads, before any device or checkpoint work: a malformed value stops the start with the variable, the supplied text and the accepted forms. | Variable | Accepted explicit value | @@ -177,7 +188,9 @@ stops the start with the variable, the supplied text and the accepted forms. | `TF_FLASHNEXT_KEEP_INPASS` | Exactly `0` or `1`; default on | | `TF_FLASHNEXT_FIRST_EARLY` | Exactly `0` or `1`; default on | | `TF_FLASHNEXT_GPU_TOPK` | Exactly `0` or `1`; default on | +| `TF_FLASHNEXT_BATCH_GDN_WIDE` | Exactly `0` or `1`; default off. Metal batch segments of 8 or 16 rows use non-replay GDN when enabled | | `TF_FLASHNEXT_GDN_FUSED` | Exactly `0` or `1`; default on | +| `TF_FLASHNEXT_GDN_CHAIN_TPR` | Exactly `0` or `1`; default off: opt into the two-thread reduction for ordinary recurrence rows below 64 | | `TF_FLASHNEXT_GDN_LANES` | Exactly `0` or `1`; default on | | `TF_FLASHNEXT_BATCH_HEADS` | Exactly `0` or `1`; default on | | `TF_FLASHNEXT_SAMPLED_HEADS` | Exactly `0` or `1`; default on | diff --git a/docs/kernel-contract.md b/docs/kernel-contract.md index fff125983f9..c4d244bfe6f 100644 --- a/docs/kernel-contract.md +++ b/docs/kernel-contract.md @@ -208,6 +208,30 @@ enabled on RDNA3.5 for single-round `K <= 1024` plans), whose rows past an item' `item_rows = 0` byte for byte when the largest item holds 3 or 4 rows. Its controls run over items one row short and go red at gate 3. +HIP's shared-row decode score (`plan_rows.hip`: q fp32, d = 256, spans of 16,384 keys or more, launches of more than +one row) replaces `tf_plan_score256_*` byte for byte with two launches on its grid, a block a plan row. First +`tf_plan_lone_score256_*` scores the rows of one-row slots as `tf_plan_score256_*` does, at its occupancy, and its other +blocks leave. Then `tf_plan_rows_score256_*`, counted from each multi-row slot's `first`, has the block of every second +row score that row and the next of the same slot from one read of the keys; the other blocks leave, so a chunk never +crosses a slot. Its registrations run both head groups (16 over 2, 24 over 4) and both cache kinds as one operator, on +launches of 1 to 64 rows: slots of 3, 1, 4 and 2 rows one position apart (at the span's end, mid-span, across a block's +first key, at the span's start), and 5 and 7 slots of one row each, over spans of 16,384 to 262,144 keys with NaN and +infinite keys that some rows of a chunk see and others do not. Its controls go red at gate 3: one leads the chunks over +the whole launch (every slot's `first` 0 and its count every row), so a chunk crosses a slot, and one launches the +chunks alone, so no launch scores the rows of one-row slots. A row scored by both launches gets the same bits from +each, so no control can show it; each kernel's own exit test keeps the two sets apart. + +HIP's shared-row decode values (`plan_rows.hip`, under the same conditions with at most 8 query heads a block) replace +`tf_plan_apply_*` byte for byte with two launches on its grid. `tf_plan_lone_apply_*` weighs the rows of one-row slots +as `tf_plan_apply_*` does, and `tf_plan_rows_apply_*` has the block of every fourth row of a multi-row slot, counted +from its `first`, weigh up to four rows of that slot from one read of each 128-key tile's values. Each row sums only +its own keys in key order; a key past them is left out, not weighed 0, so a NaN or infinite value there cannot reach +the row. Its registrations take fp32 scores and stats as inputs and run both head groups and both cache kinds on the +score's launches (slots of 3, 1, 4, 2 and 6 rows, and 5 and 7 one-row slots), with NaN and infinite values at the key +only a slot's last row weighs, at the key past all its rows and at scattered keys, and NaN and infinite scores and a +NaN max at gate 1. Gate 4 weighs every key 1, 1/2 or 1/4 and sums integer values. Its controls go red at gate 3: one +leads the chunks over the whole launch, and one launches the chunks alone. + The HIP relu^2 replacement retains every non-finite plant and checks both unfused bytes and every independent float64 output class. No inherited infinity discrepancy is accepted. The paired launch retains every table plant and checks both members' separate-launch bytes and every @@ -414,17 +438,14 @@ HIP also checks the router over the rows a checkpoint already holds in bf16 (`tf form), bit-equal to the fp32-rows router it replaces at 1 to 16 rows, with both kinds' non-finite plants through gate 1 and the exact sums of gate 4. -Metal also checks Idol's denoiser (`metal_idol*.zig`): its fp16 projections and GELU form, the split-K fp32 rows, -`id_gemm32` (true fp32 sums: the NAX fp32 path in its place is a control gate 4 must catch), the LayerNorms, RePo's -angles, the heads, the elementwise steps and the attention's four forms, each at idol-sdk's fp16 points (19 controls). -Its decoders' own kernels (`metal_idol_decoder*.zig`) are checked too: the point embedding, the stem's fp16 cast, -`to_kv`, the heads' RMS norm, the attention's four forms (P V as fp16 P hi + lo) and its fp32 short form. Each is checked -at idol-sdk's fp32 and fp16 points, with 15 controls. One drops P's lo half and must go red on heads built so that O is -P's fp16 remainder alone. -Its image encoder (`metal_idol_vae*.zig`, FLUX.2's VAE encoder in fp32) registers its convolutions (direct, implicit -GEMM and Winograd), GroupNorm's passes, the 512-wide attention and the condition rows against float64 (12 controls). -Metal also checks Idol's DINOv3 encoder (`metal_idol_dino*.zig`): its bf16 projections, LayerNorm and final F.layer_norm, -the RoPE heads, LayerScale with the residual, SwiGLU and the attention, each at transformers' bf16 points (11 controls). +Metal also checks Idol (`metal_idol*.zig`, each part's controls in [its recipe](recipes/idol.md)): the denoiser's fp16 +projections and GELU form, split-K fp32 rows, LayerNorms, RePo's angles, heads, elementwise steps and four attention +forms at idol-sdk's fp16 points, and `id_gemm32`'s true fp32 sums, where the NAX fp32 path is a gate-4 control (19 +controls); the decoders' point embedding, fp16 stem cast, `to_kv`, RMS-normed heads and attention, P V as fp16 P hi + +lo, which a control without the lo half must fail on heads whose O is that remainder alone (15); the FLUX.2 VAE +encoder's convolutions (direct, implicit GEMM, Winograd), GroupNorm, 512-wide attention and condition rows in fp32 +against float64 (12); and DINOv3's bf16 projections, LayerNorms, RoPE heads, LayerScale, SwiGLU and attention at +transformers' bf16 points (11). HIP also checks the DeltaNet prompt recurrence at half a value head a block (`tf_gdn_prompt_128`, its y and state), bit-equal to the plain window scan `gated_delta_tile` on the same tokens. @@ -444,6 +465,26 @@ and 8 waves, each against float64 at deepseek_v41's indexer wk and Engram wkv (a terms of 4096 times it stay integers under 2^24 where fp16 overflows. Two controls: rot_in reading the next block's suh, and the linear reading its input rows one row late. +HIP also checks Inkling 2's attention at Mini's 24 query and 8 key heads (`inkling2/attention.hip`, +`contract_inkling2*.zig`, records in `hip_records_inkling2.zig`; `tf-hip-kernel-contract image inkling2`). It does not +match #4125's CUDA bits; it keeps CUDA's rounding points and is held to the same float64 reference +(`core.contract.inkling2_attn_ref`, with HIP's scalar fp32 chains): `tf_ink2_prep` (sliding and global, tau at n_floor +8,192), `tf_ink2_rel_table`, and the chunked attention and its merge on sliding layers (`tf_ink2_attn`) and global ones +(`tf_ink2_attn_fold`) to 1M keys on a ring that wraps. Every P is rounded to bf16 before its sum and P V, the sink enters +last as a raw logit and the merge takes the raw gate's sigmoid, rounding once. The split launch (a block a 1,024-key +sub-chunk) and the prompt launch (`tf_ink2_attn_prompt`: 8 pairs a block share one LDS stage while the next tile loads +into registers, 37,120 bytes or 36.25 KiB) are bit-equal to the fold, and three streams in one launch are bit-equal to +each stream alone, at its row and cache offsets (prep, sliding, fold and split). The float64 bound allows P's bf16 +rounding either way, so two exact cases pin it (sliding and fold): rows below position 64 with q 0, no sink, a gate +whose sigmoid is 1 and integer values, and biases drawn so each bf16(exp2f) is certain, where every sum is exact in +fp32 and each output must equal bf16(fp32(sum P v / sum P)) bit for bit. Eight controls go red at `shapes`: a bias one +distance late, no sink, one q a bf16 step up (prompt), a window one key long, the sink and gate given after their +sigmoid (as #4387's glue did), tau off, a table read one column late, and a prep writing one stream's keys into +another's slots. `attend()` refuses a ring that is not whole 64-key tiles or is shorter than the window plus the +call's rows less one, a call with no streams (only one stream takes the prompt kernel), and partial buffers holding +fewer than rows x heads x stride partials. It does not refuse a global position past the ring, since the contract's +4,096-slot ring over 1M keys wraps on purpose: the engine glue keeps a global layer's positions inside its ring. + On gfx12, HIP also checks the WMMA dense tile (`dense_wmma12_gemm`, both block geometries, fp32 and BF16 out). The small block meets its depth-k bound. The big block (64-deep K steps over swizzled LDS rows) replaces the 32-deep block it was before #2245's second lever, byte for byte: gate 3 runs a frozen copy of that block (`tf_ref_wmma12_k32`, in the @@ -485,6 +526,15 @@ Ornith-1.5-122B's routed block on Metal registers the experts' decode rows with (`q27_rows_extra`, 4 and 8 bits), the router's softmax and top-k with renormalized bf16 weights (`q27_route`: picks equal to the host's, each weight within float64's range at its bf16 points), the tensor units' expert sort and gather (bit for bit), the experts' SwiGLU, and the weighted combine with the gated shared expert (in place and from its slot). +The same kernels register at Qwen3.6-35B-A3B's served widths (experts of 512 over 2,048). +qwen27's attention registers at the 27B's 24 query heads over 4 and the 35B-A3B's 16 over 2: a round's rows through the +engine's own plan and launcher against float64 attention, prompt rows through the prompt kernel on every chip that +builds it (`attention_prompt_sg` before the M5), and attention_io's packing, append and keep checked bit for bit (keep +a second time on the caches the first left). A plan check shows the decode shapes plan prefix_1 to _6 for chains and +_2 to _6 for trees, and a tree over two tail chunks. Its known finding: before the M5 a masked key's zero probability +times an infinite value gives NaN in P V. Its controls: a row seeing one key past its own, the one-Mac merge dropping +a round's later tail chunks, the prompt kernel losing its bounded last step, and an append one row late. prefix_5 and +_6 have no launch record yet: past 256 threads they need a reserved thread count before M1 and M2 can admit them. GLM's Metal window projections register narrow and wide rows at 2, 3, 4, 5, 6 and 8 bits, plus both gathered paths. Independent FP64 linear cases accompany byte replacements against frozen pre-window-optimization kernels. The gathered SwiGLU keeps its predecessor's clipped BF16 output and nonfinite rules; gate/up taps qualify its dots separately. diff --git a/docs/optimization-ledger.md b/docs/optimization-ledger.md index 7f71867bcf0..ba21f2e1051 100644 --- a/docs/optimization-ledger.md +++ b/docs/optimization-ledger.md @@ -26,7 +26,7 @@ Shared helpers that hold the cross-family parts: - `zig/src/core/profile.zig` and [profiles](profiles.md): the `--profile` switch registry. - `zig/src/core/contract/` and the [kernel contract](kernel-contract.md): the gates a new or ported kernel passes. - `zig/src/core/prompt_tail.zig`: the last layer's kept tile ([#2229]) and the chunks nothing reads ([#2432]). -- `zig/src/core/state_walk.zig`: one walk for kept prompt states. Not on main yet: it is on [#2215]. +- `zig/src/core/state_walk.zig`: one walk for kept prompt states ([#2215]). Flash Next CUDA sampled reductions: one check in top-k and batched verify/draft completions prepared (#2920); CUDA candidate bytes, parity and served/speed qualification are pending. @@ -49,55 +49,56 @@ last two hold the families with only a Metal, HIP or scoring backend. | Optimization | q3.5 | fnext | glm | gem4 | nemo | | --- | --- | --- | --- | --- | --- | -| 1. Prompt tail | done [#2229] | yes | yes | open [#2432] | open [#2432] | +| 1. Prompt tail | done [#2229] | yes | yes | done [#2432] | done [#2432] | | 2. Paged KV | done C[#1750] M[#1294] | done [#1169] | done [#1163] | done [#1619] | done C[#935] M[#1537] | | 3. Prompt store | done [#1357] | yes (host store) | done [#1732] | done [#1883] | yes C open M[#1850] | | 4. iGPU states | done [#2113] | doneยน | yes | doneยน | doneยน | -| 5. State walk | open C[#2392] | open C[#2392] | open [#2215] | open C[#2392] | open C[#2392] | +| 5. State walk | open C[#2392] | open C[#2392] | done [#2215] | open C[#2392] | open C[#2392] | | 6. KV ledger | done [#2127] | done [#2127] | done [#2127] | done [#2127] | done [#2127] | | 7. Host KV tier | yes | open [#1501] | done [#1795] | yes | yes | -| 8. Disk cache | done C[#1358] | done C[#1359] M[#519] | done Mยน open C[#1411] | open C[#3135] | done C[#1413] Mยน | +| 8. Disk cache | done C[#1358] | done C[#1359] M[#519] | done Mยน open C[#1411] | done C[#3135] | done C[#1413] Mยน | | 9. FP8 KV | done [#886] | yes | doneยน | yes | yes | | 10. FP4/FP8 decode | yes | yes | yes | no (affine) | yes | | 11. Fused proj. | done [#1783] | doneยน | doneยน | done [#1783] | done [#1783] | | 12. Add + norm | done H[#2099] | no (bound <1 %) | yes | doneยน | done [#796] | -| 13. MoE grouped | done [#605] | done [#1351], open M[#2784] | done [#864]; paired C experiment (REV25 E1) | no (dense) | done [#558] | +| 13. MoE grouped | done [#605] | done [#1351] M[#2784] | done [#864]; paired C experiment (REV25 E1) | no (dense) | done [#558] | | 14. CUDA graphs | doneยน | done [#1786] | open [#2279] | done [#1174] | done [#615] | -| 15. MTP | done [#1562]; yes C [#2485] (dense) | done [#1925] | done [#1585]; wide C open [#2257] | done [#1385] | done [#997] | +| 15. MTP | done [#1562]; dense C done [#3582] | done [#1925] | done [#1585]; wide C done [#2257] | done [#1385] | done [#997] | | 16. DFlash(2) | done [#1465] | yes | done C[#979], open M[#3152] | done Cยน M[#879] | yes | | 17. DSpark | yes | yes | yes | yes | yes | -| 18. Copy drafts | done [#1477] | done [#468] | done [#2146]; wide C open [#2257] | done [#2022] | done [#1974] | -| 19. Shared drafts | done [#1562] | no (null [#1762]) | done [#1779]; cap C open [#2257] | done [#1779] | done [#768] | +| 18. Copy drafts | done [#1477] | done [#468] | done [#2146]; wide C done [#2257] | done [#2022] | done [#1974] | +| 19. Shared drafts | done [#1562] | no (null [#1762]) | done [#1779]; cap C done [#2257] | done [#1779] | done [#768] | | 20. Solo chunks | yes | done C[#1733] M[#2167] | done [#1823] | done C[#2391] | yes | | 21. Read-ahead | done [#1928] | no (row 22) | done [#1616] | done [#1928] | done [#2033] | | 22. Direct load | done [#2282] | done [#1901] | yes | done [#2282] | done [#458] | | 23. Page drop | done [#1884] | done [#1880] | done [#600] | done [#1884] | done [#1884] | | 24. L2 prefetch | failed [#2014] | no (null) | done [#2162] | no (null) | failed [#2014] | | 25. TP ranks | done H[#655] | done C[#1771] H[#817] | done [#855] | yes | doneยน | -| 26. Pipeline | open [#2115] | yes | yes | yes | yes | +| 26. Pipeline | done [#2115] | yes | yes | yes | yes | | 27. Profiles | done [#1944] | done [#1944] | done [#1959] | done [#1944] | done [#2061] | -| 28. Scale index | ? | done M[#2760], open M[#2805] | ? | ? | ? | +| 28. Scale index | ? | done M[#2760] M[#2805] | ? | ? | ? | | 29. DSpine | done C[#2633] | no (no drafter) | no (no drafter) | no (no drafter) | no (no drafter) | | 30. Small-kernel fusion | ? | failed H[#1603] | ? | ? | ? | | 31. Stream-tile prefetch | ? | failed H[#1603] | ? | ? | ? | | 32. Filled-item prompt grid | ? | failed H[#1603] | ? | ? | ? | -| 33. Dependent launches | ? | ? | open [#3652] | ? | ? | +| 33. Dependent launches | ? | ? | doneยน [#3652] | ? | ? | | 34. Rows together | ? | ? (oQ4e dense is 5โ€“8 bits) | no (no HIP) | no (no HIP) | failed H[#3305] | | 35. FP8 KV prefill waits | failed C[#3741] | ? | ? | ? | ? | | 36. Qwen normalization and head | failed C[#3741] | ? | ? | ? | ? | | 37. Text metadata uploads | failed C[#3741] | ? | ? | ? | ? | | 38. Greedy readback | ? | ? | ? | ? | ? | +| 39. Drafted rows share the walk | open H[#4673] | ? | ? | ? | ? | | Optimization | kol1 | spk25 | dory | mm3 | dsv41 | | --- | --- | --- | --- | --- | --- | | 1. Prompt tail | yes | yes | yes | yes | yes | | 2. Paged KV | done [#1620] | done [#1653] | done [#1284] | yes | yes (own pool) | -| 3. Prompt store | done [#1755] | done [#1756] | open [#2430] | yes | yes | +| 3. Prompt store | done [#1755] | done [#1756] | done [#2430] | yes | yes | | 4. iGPU states | doneยน | doneยน | doneยน | doneยน | yes | | 5. State walk | yes | yes | yes | yes | yes | | 6. KV ledger | done [#2127] | done [#2127] | done [#2127] | yes | yes | | 7. Host KV tier | yes | yes | yes | yes | yes | -| 8. Disk cache | yes | open [#3135] | open [#3135] | yes | doneยน | +| 8. Disk cache | yes | done [#3135] | done [#3135] | yes | doneยน | | 9. FP8 KV | yes | yes | yes | yes | no (FP8 by design) | | 10. FP4/FP8 decode | failed [#1448] | no (bf16) | yes | no (EXL3) | yes | | 11. Fused proj. | doneยน | done [#1783] | yes | doneยน | doneยน | @@ -108,15 +109,15 @@ last two hold the families with only a Metal, HIP or scoring backend. | 16. DFlash(2) | yes | yes | yes | doneยน | yes | | 17. DSpark | yes | yes | yes | doneยน | done [#1751] | | 18. Copy drafts | done [#2022] | done [#2022] | done [#2022] | done [#2022] | doneยน | -| 19. Shared drafts | no (copies) | no (copies) | no (copies) | open [#1426] | doneยน (opt-in) | -| 20. Solo chunks | yes | yes | yes | yes | open M[#2950] | +| 19. Shared drafts | no (copies) | no (copies) | no (copies) | done [#1426] | doneยน (opt-in) | +| 20. Solo chunks | yes | yes | yes | yes | done M[#2950] | | 21. Read-ahead | done [#2033] | done [#2033] | yes | done [#2033] | done [#2033] | -| 22. Direct load | yes | open [#2449] | open [#2449] | yes | open [#1924] | +| 22. Direct load | yes | done [#2449] | done [#2449] | yes | open [#1924] | | 23. Page drop | done [#1884] | done [#1884] | done [#1884] | done [#1884] | done [#1884] | | 24. L2 prefetch | yes | yes | yes | yes | doneยน | | 25. TP ranks | yes | no (4B) | yes | done [#1388] | doneยน | | 26. Pipeline | yes | no (4B) | yes | yes | yes | -| 27. Profiles | done [#1944] | done [#1944] | open [#2306] | yes | yes | +| 27. Profiles | done [#1944] | done [#1944] | done [#2306] | yes | yes | | 28. Scale index | ? | ? | ? | ? | ? | | 29. DSpine | no (no drafter) | no (no drafter) | no (no drafter) | no (no drafter) | no (no drafter) | | 30. Small-kernel fusion | ? | ? | ? | ? | ? | @@ -128,12 +129,13 @@ last two hold the families with only a Metal, HIP or scoring backend. | 36. Qwen normalization and head | ? | ? | ? | ? | ? | | 37. Text metadata uploads | ? | ? | ? | ? | ? | | 38. Greedy readback | ? | ? | ? | ? | ? | +| 39. Drafted rows share the walk | ? | ? | ? | ? | ? | | Optimization | lfm2m | lfm3 | qwen4 | ling | | --- | --- | --- | --- | --- | -| 1. Prompt tail | no (no CUDA) | no (no CUDA) | no (n/a) | no (no engine) | -| 2. Paged KV | open [#1503] | yes | yes | yes | -| 3. Prompt store | open [#1503] | yes | yes | yes | +| 1. Prompt tail | yes | no (no CUDA) | no (n/a) | no (no engine) | +| 2. Paged KV | done C[#1503] | yes | yes | yes | +| 3. Prompt store | done C[#1503] | yes | yes | yes | | 4. iGPU states | yes | yes | yes | yes | | 5. State walk | yes | yes | yes | yes | | 6. KV ledger | yes | yes | yes | yes | @@ -151,7 +153,7 @@ last two hold the families with only a Metal, HIP or scoring backend. | 18. Copy drafts | done Mยน | done X[#1696] | doneยน | yes | | 19. Shared drafts | done [#1779] | no (no head) | no (no head) | yes | | 20. Solo chunks | yes | yes | yes | yes | -| 21. Read-ahead | no (no CUDA) | yes | yes | yes | +| 21. Read-ahead | yes | yes | yes | yes | | 22. Direct load | yes | yes | yes | yes | | 23. Page drop | done M[#1885] | yes | done [#1887] | yes | | 24. L2 prefetch | yes | yes | yes | yes | @@ -169,11 +171,12 @@ last two hold the families with only a Metal, HIP or scoring backend. | 36. Qwen normalization and head | ? | ? | ? | ? | | 37. Text metadata uploads | ? | ? | ? | ? | | 38. Greedy readback | ? | ? | ? | ? | +| 39. Drafted rows share the walk | ? | ? | ? | ? | q3.5 `qwen3_5` (C, M, H, X), fnext `flashnext` (C, M, H), glm `glm` (C, M), gem4 `gemma4` (C, M, X), nemo `nemotron` (C, M, H, X), kol1 `kolibri1` (C), spk25 `spark25` (C, M), dory `dory` (C), mm3 `minimax_m3` (C, M), dsv41 `deepseek_v41` (its own CUDA binary, not the release's CUDA server; -M), lfm2m `lfm2_moe` (M; C on [#1492]), lfm3 `lfm3` (X; C on [#1508]), qwen4 `qwen4` (C, M), +M), lfm2m `lfm2_moe` (C, M), lfm3 `lfm3` (X; C on [#1508]), qwen4 `qwen4` (C, M), ling `ling` (host package only, no engine yet; CUDA plan in [#850]). | Optimization | q27 | lfm2 | llama | step5 | @@ -192,7 +195,7 @@ ling `ling` (host package only, no engine yet; CUDA plan in [#850]). | 12. Add + norm | done Mยน | doneยน | doneยน | yes | | 13. MoE grouped | done [#1125] | no (dense) | no (dense) | doneยน | | 14. CUDA graphs | no (Metal) | no (scores) | no (Metal) | no (Metal) | -| 15. MTP | open M[#2464] | no (scores) | no (no head) | doneยน | +| 15. MTP | done M[#2464] | no (scores) | no (no head) | doneยน | | 16. DFlash(2) | done [#578] | no (scores) | yes | yes | | 17. DSpark | yes | no (scores) | yes | yes | | 18. Copy drafts | doneยน | no (scores) | done Mยน | done Mยน | @@ -216,6 +219,7 @@ ling `ling` (host package only, no engine yet; CUDA plan in [#850]). | 36. Qwen normalization and head | ? | ? | ? | ? | | 37. Text metadata uploads | ? | ? | ? | ? | | 38. Greedy readback | ? | ? | ? | ? | +| 39. Drafted rows share the walk | ? | ? | ? | ? | | Optimization | gdsa | kimi | qwen3 | | --- | --- | --- | --- | @@ -257,6 +261,7 @@ ling `ling` (host package only, no engine yet; CUDA plan in [#850]). | 36. Qwen normalization and head | ? | ? | ? | | 37. Text metadata uploads | ? | ? | ? | | 38. Greedy readback | ? | ? | ? | +| 39. Drafted rows share the walk | ? | ? | ? | q27 `qwen27` (M: Qwen3.8-27B and Qwen3.5-MoE), lfm2 `lfm2` (C: LFM2-VL, scores decisions and writes no text), llama `llama` (M), step5 `step5` (M), gdsa `glm_dsa` (M), kimi `kimi_k3` (M, native serving on [#2221]), @@ -312,6 +317,7 @@ below; these are estimates for planning a port, not results. | 36. Qwen normalization and head | none | none | none | CUDA qwen3_5: โˆ’0.519 % median paired gain (separate absolute medians 0.8619 โ†’ 0.8659 s TTFT) | | 37. Text metadata uploads | none | none | none | CUDA qwen3_5: โˆ’0.037 % median paired gain (separate absolute medians 15.2475 โ†’ 15.2418 tok/s) | | 38. Greedy readback | none | none | none | CUDA dots.mocr: +1.200 % median paired gain (separate absolute medians 64.6319 โ†’ 65.4191 tok/s) | +| 39. Drafted rows share the walk | none | medium | none | HIP qwen3_5: decode at one stream with drafts at 131K-258K, score half +1.0โ€“5.1 %, values' half +0.4โ€“6.9 % more | ## The optimizations @@ -429,7 +435,7 @@ below; these are estimates for planning a port, not results. 15. **MTP drafts.** The checkpoint's own MTP head drafts tokens that the target verifies in one pass, with the same replies as serial decode. `--mtp-drafts` and `--mtp-confidence` size the drafts on Nemotron and GLM. - GLM CUDA's proposed 32-row prices, three-draft shared MTP cap and wider copy windows are tracked in [#2257]. + GLM CUDA's 32-row prices, three-draft shared MTP cap and wider copy windows landed in [#2257]. The TP=2 receipt on two GB10s compares main 52427c023e with an earlier revision of the proposed branch: one-stream code 55.4 to 73.7 tok/s (+33.1%), two-stream chat +3.2%, one-stream chat +1.0%, two-stream code +1.3%, prefill within 0.3% and replies 52/0/0 equal/unequal/unverified. The receipt does not identify the drafter mode, so it qualifies @@ -642,6 +648,18 @@ below; these are estimates for planning a port, not results. | --- | --- | --- | | dots_mocr | +1.200 % median paired gain (separate absolute medians 64.6319 โ†’ 65.4191 tok/s) at one greedy stream, but โˆ’0.68 % paired at four greedy streams (absolute 52.61 โ†’ 52.26 tok/s a stream); tokens equal on all 196 paired requests | [#3741], one GB10 (SM121); no SM120 round met the clock criteria, so that timing is inconclusive | +39. **Drafted rows share the walk.** A decode round's drafted rows of one stream sit at consecutive positions and + read the same keys and values. On HIP at d = 256 over spans of 16,384 keys or more, a multi-row round scores a + slot's rows in chunks of two from one read of the keys ([#4673]) and weighs them in chunks of four from one read of + the values ([#3811]'s second half), each row keeping its sums and their order, so the bits are unchanged. One-row + rounds keep their kernels, and a second launch keeps one-row slots at the one-row kernels' occupancy. The depth rule + weighs timed rounds, so faster multi-row rounds can change how deep a stream drafts. + + | Family | Gain (measured) | Where | + | --- | --- | --- | + | qwen3_5 (35B-A3B) | score half +0.96 % to +3.27 % decode at one stream with drafts at 131,072 and 258,048 kept tokens; the values' half +3.86 % to +6.94 % on top of it; `"draft": false` and four streams without drafts level; tokens equal | [#4673] and [#3811], gfx1151 | + | qwen3_5 (27B) | score half +2.59 % to +5.11 %; the values' half +0.43 % to +4.91 % on top of it; the same checks | [#4673] and [#3811], gfx1151 | + [#458]: https://github.com/ashhart/TensorFold/pull/458 [#468]: https://github.com/ashhart/TensorFold/pull/468 [#519]: https://github.com/ashhart/TensorFold/pull/519 @@ -695,7 +713,6 @@ below; these are estimates for planning a port, not results. [#1465]: https://github.com/ashhart/TensorFold/pull/1465 [#1477]: https://github.com/ashhart/TensorFold/pull/1477 [#1490]: https://github.com/ashhart/TensorFold/issues/1490 -[#1492]: https://github.com/ashhart/TensorFold/pull/1492 [#1501]: https://github.com/ashhart/TensorFold/pull/1501 [#1503]: https://github.com/ashhart/TensorFold/pull/1503 [#1508]: https://github.com/ashhart/TensorFold/pull/1508 @@ -793,6 +810,7 @@ below; these are estimates for planning a port, not results. [#2375]: https://github.com/ashhart/TensorFold/pull/2375 [#2633]: https://github.com/ashhart/TensorFold/pull/2633 [#2634]: https://github.com/ashhart/TensorFold/pull/2634 +[#3582]: https://github.com/ashhart/TensorFold/pull/3582 [#3652]: https://github.com/ashhart/TensorFold/issues/3652 [#2784]: https://github.com/ashhart/TensorFold/pull/2784 [#2950]: https://github.com/ashhart/TensorFold/pull/2950 @@ -805,3 +823,5 @@ below; these are estimates for planning a port, not results. [#2941]: https://github.com/ashhart/TensorFold/issues/2941 [#2971]: https://github.com/ashhart/TensorFold/pull/2971 [#3741]: https://github.com/ashhart/TensorFold/issues/3741 +[#3811]: https://github.com/ashhart/TensorFold/issues/3811 +[#4673]: https://github.com/ashhart/TensorFold/pull/4673 diff --git a/docs/profiles.md b/docs/profiles.md index 9f95b2ae3bf..2b54701868e 100644 --- a/docs/profiles.md +++ b/docs/profiles.md @@ -51,8 +51,9 @@ Coverage includes: with `TENSORFOLD_DORY_KV_PAGES=0` it refuses to load, by both names. With the switch unset, the startup line shows `TENSORFOLD_DORY_KV_PAGES=1 (arithmetic, TF_KV_SHARE)` and kept states carry the same identity as `=1`. - Every CUDA family whose host prompt cache the CUDA host builds (Nemotron, Nemotron Omni, GLM, MiniMax M3, Qwen3.5 - dense/MoE, Flash Next, Kolibri-1, Gemma 4, Spark2.5, Dory, LFM2.5-24B-A2B, Muse Spark Open): `TENSORFOLD_PROMPT_CACHE_KEEP_OTHERS`, - exact `1` only. + dense/MoE, Flash Next, Kolibri-1, Gemma 4, Spark2.5, Dory, LFM2.5-24B-A2B, Muse Spark Open, Ripple, + Inkling 2 Mini): + `TENSORFOLD_PROMPT_CACHE_KEEP_OTHERS`, exact `1` only. - Flash Next on CUDA: `TF_FLASHNEXT_KV_PAGES`, `TF_FLASHNEXT_KV_PAGES_ALL`. - Dory on CUDA: `TENSORFOLD_DORY_KV_PAGES`, full-attention caches in pool pages unless it is exactly `0`; unset, every stream's caches are contiguous and made at open. @@ -266,7 +267,7 @@ gathers whose stride exceeds the ceiling. `TF_TP_MAILBOX_MAX_KB` still sizes the is the smaller of the two limits. Changing the relay ceiling does not resize those slots or change gathered bytes. This setting is read directly by the TP parser, outside the profile registry. Invalid values refuse by name, and -relay ranks must agree on the value. GLM uses its actual `TF_GLM_WORLD` and rank for relay validation, so a four-rank +relay ranks must agree on the value. GLM uses its actual world (`--tp`, or `TF_GLM_WORLD`) and rank for relay validation, so a four-rank GLM run does not also need `TF_TP_WORLD=4`. With `TF_GLM_ROCE_MULTI=1`, a relay outside four ranks is refused before weights load. The relay remains opt-in through `TF_TP_ROCE_RELAY=1`; mesh, two-rank paths and all-reduce routing keep their defaults. diff --git a/docs/receipts/gfx1201-flashnext-tp4-6fc30cf0b/README.md b/docs/receipts/gfx1201-flashnext-tp4-6fc30cf0b/README.md index df94cf78921..3f1ecc19e47 100644 --- a/docs/receipts/gfx1201-flashnext-tp4-6fc30cf0b/README.md +++ b/docs/receipts/gfx1201-flashnext-tp4-6fc30cf0b/README.md @@ -25,7 +25,7 @@ This receipt does not qualify other model families, other checkpoints, other wor | cold prefill 8,192 | 1,358 tok/s | 1,165 tok/s | +16.6% | | cold prefill 32,768 | 1,263 tok/s | 1,079 tok/s | +17.1% | -Reading, in the measured scope only: the world pays on cold prefill (the prompt work splits across ranks), is neutral to slightly negative on 4-stream decode aggregate, and leaves single-stream decode unchanged. The earlier tp 2 receipt (`v1.2.7-399`, in #3608 until it lands) measured 121.2 tok/s decode and 1,191/1,121/1,058 tok/s prefill on two of the same cards; it crosses commits and is context, not a comparison โ€” the control column above is the clean one. +Reading, in the measured scope only: the world pays on cold prefill (the prompt work splits across ranks), is neutral to slightly negative on 4-stream decode aggregate, and leaves single-stream decode unchanged. The earlier tp 2 receipt (`v1.2.7-399`, [gfx1201-flashnext-tp2-f8dacd77](../gfx1201-flashnext-tp2-f8dacd77/README.md)) measured 121.2 tok/s decode and 1,191/1,121/1,058 tok/s prefill on two of the same cards; it crosses commits and is context, not a comparison โ€” the control column above is the clean one. ## Cold prefill diff --git a/docs/receipts/gfx1201-flashnext-tp4-6fc30cf0b/SHA256SUMS b/docs/receipts/gfx1201-flashnext-tp4-6fc30cf0b/SHA256SUMS index 065e6725867..3b4eb560d19 100644 --- a/docs/receipts/gfx1201-flashnext-tp4-6fc30cf0b/SHA256SUMS +++ b/docs/receipts/gfx1201-flashnext-tp4-6fc30cf0b/SHA256SUMS @@ -1,4 +1,4 @@ -2ba52b42affe92fe9ffd9f7f805288e55774dc3d29e64fea9e279a0a110b3c25 README.md +709a58be82fe1242ca424d304bb632e16d520fa260e4243f3db2f6e8f4052909 README.md 8f90599307b361433ed746e1fe8010db3136b93736a84c4da2ec2c183cadfe4e system.txt 9e5d3d2ba820464b34ede50b07859ad0836e664c3feacd9e94f7a5f4026b74ed provenance.json 1eac188a0078c9bd3e52d32d430405ee277d29d6987e158a3765f467cb4735ec checkpoints.json diff --git a/docs/recipes/README.md b/docs/recipes/README.md index c4eb3b45c29..63ad83ce94c 100644 --- a/docs/recipes/README.md +++ b/docs/recipes/README.md @@ -37,7 +37,8 @@ For agent-assisted contributions, read the [TensorFold contributor skill](SKILL. | Recursive Flint | [Native Metal, the publisher's affine 4-bit export, reasoning and tool calls](flint.md) | | Unlimited-OCR-2 | [Native Metal, the bf16 release: page images to structured text, 131k context](unlimited-ocr-metal.md) | | Muse Spark Open | [EXL3 on CUDA, two-rank DGX Spark, plain decode](muse-spark.md) | -| Ripple-65B-Preview | [Native Metal, the publisher's NVFP4 and bf16 releases](ripple-65b-metal.md) | +| Ripple-65B-Preview | [Native CUDA, the publisher's NVFP4 release](ripple-65b-cuda.md), [native Metal, the publisher's NVFP4 and bf16 releases](ripple-65b-metal.md) | +| Ling-3.0-tiny | [Native CPU on aarch64 Linux, the Q4_K_M GGUF, exact greedy decode from token IDs](ling-3.0-tiny-cpu.md) | [Persisted serving-state identities](persisted-serving-keys.md) lists the disk owners, their compatibility keys and stale-state host checks. diff --git a/docs/recipes/cuda.md b/docs/recipes/cuda.md index f9e9f23bc0f..3e9f385487c 100644 --- a/docs/recipes/cuda.md +++ b/docs/recipes/cuda.md @@ -173,10 +173,10 @@ Each engine defines its own serial reference. A verify row uses the same group o rounding as that row alone. Attention partitions depend on absolute key position; router ties use a stable ID order. Recurrent commits replay the accepted path with the same update routine. -Native CUDA has tensor-parallel serving as well as one-GPU paths. GLM's recorded TP=2 and TP=3 setups use -`TF_GLM_RANK`, `TF_GLM_WORLD` and `NCCL_COMM_ID`; see [native GLM placement](glm-5.3-flash-cuda.md#run). -Other families take `--tp`, `--rank` and `--master` only where their native options support ranks; for example, -[Super VL](nemotron-3.5-super-vl.md) serves on one or two GB10s. A rank option is not universal family support. +Native CUDA has tensor-parallel serving as well as one-GPU paths. GLM, MiniMax and Nemotron take +`--tp`, `--rank`, `--master` and `--master-port` (see [native GLM placement](glm-5.3-flash-cuda.md#run)); their +`TF_*_RANK` and `TF_*_WORLD` variables are aliases for one release (the start-up warning names the release that refuses them). Other families take the flags only where their native +options support ranks; for example, [Super VL](nemotron-3.5-super-vl.md) serves on one or two GB10s. A rank option is not universal family support. The following transport and two-rank reduction notes describe Python 0.6.6. In that engine, @jayleaton's [#219](https://github.com/ashhart/TensorFold/pull/219) gave the communicator its transport interface diff --git a/docs/recipes/drama3-cuda/cfg-mix-gb10.sh b/docs/recipes/drama3-cuda/cfg-mix-gb10.sh new file mode 100755 index 00000000000..38684be4318 --- /dev/null +++ b/docs/recipes/drama3-cuda/cfg-mix-gb10.sh @@ -0,0 +1,11 @@ +#!/bin/sh +# d3_cfg_mix's kernel contract on a DGX Spark (GB10, sm_121) with Zig 0.17.0 and CUDA 13.0's nvcc on PATH: +# sh docs/recipes/drama3-cuda/cfg-mix-gb10.sh +# Gates 1-4, the planted gamma - 1 control (must go red) and the limits check; exits with tf-cuda-test's status. +set -eu +nvcc=$(command -v nvcc) +echo "commit $(git rev-parse HEAD)" +"$nvcc" --version | tail -n 1 +zig build install fatbins kernel-contract-fatbins -Dsm=121 -Dnvcc="$nvcc" -Doptimize=ReleaseFast --prefix zig-out/sm121 +zig build -Dgpu=spark -Dnvcc="$nvcc" --prefix zig-out/sm121 +exec zig-out/sm121/bin/tf-cuda-test kernel-contract d3_cfg_mix diff --git a/docs/recipes/flash-next-hip.md b/docs/recipes/flash-next-hip.md index a4eca3bb5ae..c9a2c36d858 100644 --- a/docs/recipes/flash-next-hip.md +++ b/docs/recipes/flash-next-hip.md @@ -5,13 +5,15 @@ The integrated-GPU platform (gfx1151, Strix Halo) has its own section in the MLX [Native HIP on a Strix Halo iGPU](qwen3.8-flash-next.md#native-hip-on-a-strix-halo-igpu), which this page does not repeat. -Discrete gfx12 cards are covered here by one receipt, -[docs/receipts/gfx1201-flashnext-tp2-f8dacd77](../receipts/gfx1201-flashnext-tp2-f8dacd77/README.md): -two Radeon AI PRO R9700s (gfx1201, 32 GiB each) at `--tp 2`, one host, with -`Qwen3.8-Flash-Next-MLX-oQ2-MTP` at `0a1bf6fa` โ€” decode at `--parallel 4 --context 4096` (121.2 tok/s, -`bench_openai` fibonacci-raw) and cold prefill at `--parallel 1 --context 40960` -(1,191/1,121/1,058 tok/s at 2k/8k/32k tokens), both with `--prompt-cache-gib 0`, every `alone` and -`serial` comparison equal. What follows is that measured path only. +Discrete gfx12 cards are covered here by two receipts, +[docs/receipts/gfx1201-flashnext-tp2-f8dacd77](../receipts/gfx1201-flashnext-tp2-f8dacd77/README.md) and +[docs/receipts/gfx1201-flashnext-tp4-6fc30cf0b](../receipts/gfx1201-flashnext-tp4-6fc30cf0b/README.md): +two Radeon AI PRO R9700s (gfx1201, 32 GiB each) at `--tp 2` and four of them at `--tp 4`, one host, +with `Qwen3.8-Flash-Next-MLX-oQ2-MTP` at `0a1bf6fa` โ€” decode at `--parallel 4 --context 4096` (121.2 and +122.9 tok/s, `bench_openai` fibonacci-raw) and cold prefill at `--parallel 1 --context 40960` +(1,191/1,121/1,058 and 1,412/1,358/1,263 tok/s at 2k/8k/32k tokens), all with `--prompt-cache-gib 0`, every +`alone` and `serial` comparison equal. The world-4 receipt also carries a world-2 control on the same binary +that isolates the world effect. What follows is those measured paths only. ## Two-rank serve path @@ -30,6 +32,25 @@ HIP_VISIBLE_DEVICES= tensorfold-native serve TensorFold/Qwen3.8-Flash-Next (`rocm-smi --showmeminfo vram --csv`) and pin it with `HIP_VISIBLE_DEVICES`, not by trusting an index. - The weights take 27.3 GiB per rank at `--tp 2`. -Not measured by that receipt: other card counts, `--tp 4`/`--tp 8`, multi-host ranks, other checkpoints -or revisions, other context or parallel windows, fp8 KV, and drafter checkpoints. A host build does not -establish checkpoint fidelity, qualify later `main` commits, or qualify other gfx12 variants. +## Four-rank serve path + +```bash +# ranks 1-3 (do not serve HTTP) +HIP_VISIBLE_DEVICES= tensorfold-native serve TensorFold/Qwen3.8-Flash-Next-MLX-oQ2-MTP@0a1bf6faa0a2f16a314da889e8e6c80226455dbf --tp 4 --rank R --master 127.0.0.1 --prompt-cache-gib 0 --parallel 4 --context 4096 +# rank 0 (serves HTTP) +HIP_VISIBLE_DEVICES= tensorfold-native serve TensorFold/Qwen3.8-Flash-Next-MLX-oQ2-MTP@0a1bf6faa0a2f16a314da889e8e6c80226455dbf --tp 4 --rank 0 --master 127.0.0.1 --port 8092 --prompt-cache-gib 0 --parallel 4 --context 4096 +``` + +- Measured at `v1.2.7-1722-g6fc30cf0b` on four R9700s, one rank per card + ([gfx1201-flashnext-tp4-6fc30cf0b](../receipts/gfx1201-flashnext-tp4-6fc30cf0b/README.md)): decode 122.9 tok/s, + concurrent code 123.8/242.0 and chat 103.5/205.2 tok/s at 1/4 streams, cold prefill 1,412/1,358/1,263 tok/s. +- A world-2 control on the same binary, cards and flags isolates the world: +15.8/+16.6/+17.1% on cold prefill, + +1.4% on single-stream decode, and โˆ’3.0% on 4-stream code aggregate. World 4 is the prefill choice; it is not + a decode-throughput choice. +- HIP admission is geometry-gated: heads, experts and vocabulary must split evenly over the world + (`flashnext/hip/native.zig`). World 4 admitted cleanly for this checkpoint. +- The device holds 15.74 GiB per rank at the decode window (15.72 GiB at the prefill window). + +Not measured by those receipts: other card counts, `--tp 8`, worlds other than 2 and 4, multi-host ranks, +other checkpoints or revisions, other context or parallel windows, fp8 KV, and drafter checkpoints. A host +build does not establish checkpoint fidelity, qualify later `main` commits, or qualify other gfx12 variants. diff --git a/docs/recipes/fluid-subgraph-residency.md b/docs/recipes/fluid-subgraph-residency.md index a838aca36c6..016e59d9f72 100644 --- a/docs/recipes/fluid-subgraph-residency.md +++ b/docs/recipes/fluid-subgraph-residency.md @@ -1,5 +1,7 @@ # Exact Fluid Subgraph Residency +On Flash Next Metal, `--ssd-experts GIB` is an upper bound. If its original startup plan exceeds the unchanged load ceiling, the loader tries the largest smaller whole-slot pool that fits, retaining capacity for one full layer's expert union. It includes metadata, existing allocations, sessions/cache and the pack-construction peak. A pool that already fits keeps its exact size; a minimum pool that cannot fit is still refused. The startup log reports a reduced pool. Stored weights, context, prompt chunks and token arithmetic remain unchanged; smaller pools can require more SSD reads. Physical fit and speed require device qualification. + [Fluid Subgraph Residency](../design/fluid-subgraph-residency.md) is TensorFold's implementation of published techniques from EdgeMoE, MoE-Infinity, Fiddler and Fate. Slotstream is an outside comparison only. The native phase covers Flash Next (`qwen4_exp`) on one Metal device. Other families, backends and the paired speed-up path refuse these options. ## Serve stored experts from SSD diff --git a/docs/recipes/glm-5.3-flash-cuda.md b/docs/recipes/glm-5.3-flash-cuda.md index 5c6f3d5e977..bc2627e8696 100644 --- a/docs/recipes/glm-5.3-flash-cuda.md +++ b/docs/recipes/glm-5.3-flash-cuda.md @@ -7,27 +7,30 @@ NVIDIA's FP4-Local checkpoint as stored and from XSFP4, which keeps FP4-Local's Jammed XSFP4, in [1.2.3](../../CHANGELOG.md#123) ([#2041](https://github.com/ashhart/TensorFold/pull/2041)), holds those experts at block 32 in the `csf0_v1` form and loads the same way. Jammed XSFP4 NZ5, in [1.2.10](../../CHANGELOG.md#1210) ([#2894](https://github.com/ashhart/TensorFold/pull/2894)), is Jammed XSFP4 refitted with E2M1's -0 code read as +5 (`NVFP4_NZ5`) and loads the same way. Rank 0 serves HTTP and the other ranks follow its steps, with MTP drafts, concurrent streams and kept prompt states. -The [Python 0.6.6 recipe](glm-5.3-flash.md) and its `--tp`, `--rank` and `--master` flags belong to the frozen engine. +The [Python 0.6.6 recipe](glm-5.3-flash.md) belongs to the frozen engine; the native server takes the same `--tp`, `--rank` +and `--master` flags. ## Run -`TF_GLM_RANK` of `TF_GLM_WORLD` places each rank, and `NCCL_COMM_ID` names rank 0's address and port on the link -between the hosts ([placement](../multi-rank-receipts.md)). Give every rank the same arguments: before the weights load +`--rank` of `--tp` places each rank, and `--master` with `--master-port` names rank 0's address and port on the link +between the hosts; they become NCCL's root (`NCCL_COMM_ID`, which may be set instead, and must match when both are) +([placement](../multi-rank-receipts.md)). `TF_GLM_RANK` and `TF_GLM_WORLD` still place a rank as aliases of `--rank` and `--tp` for one release; the start-up warning names the release that refuses them +with the flag to use; a flag and an alias that differ refuse. Give every rank the same arguments: before the weights load the ranks compare their settings, model and build, and name the field and rank that differ. `--context` takes a positive limit for GLM. On two GB10s, with 192.0.2.1 as rank 0's address on their direct link: ```bash tensorfold pull nvidia/GLM-5.3-Flash-NVFP4@423acf37583782c51c142d145aef733d72943d93 # on rank 1 -TF_GLM_RANK=1 TF_GLM_WORLD=2 NCCL_COMM_ID=192.0.2.1:29583 \ - tensorfold serve nvidia/GLM-5.3-Flash-NVFP4 --context 245760 --parallel 1 +tensorfold serve nvidia/GLM-5.3-Flash-NVFP4 --tp 2 --rank 1 --master 192.0.2.1 --master-port 29583 \ + --context 245760 --parallel 1 # on rank 0 (192.0.2.1) -TF_GLM_RANK=0 TF_GLM_WORLD=2 NCCL_COMM_ID=192.0.2.1:29583 \ - tensorfold serve nvidia/GLM-5.3-Flash-NVFP4 --context 245760 --parallel 1 +tensorfold serve nvidia/GLM-5.3-Flash-NVFP4 --tp 2 --rank 0 --master 192.0.2.1 --master-port 29583 \ + --context 245760 --parallel 1 ``` Set `NCCL_SOCKET_IFNAME` and `NCCL_IB_HCA` for the link between the hosts as NCCL documents them. Each rank keeps a -TCP line to rank 0 on the port after `NCCL_COMM_ID`'s (29584 here), opened before NCCL: a rank that fails, refuses or +TCP line to rank 0 on the port after the root's (29584 here), opened before NCCL: a rank that fails, refuses or dies stops the others. The contributed runs read that revision. The repository's later commit `da920bb0`, which declares the MTP layer as @@ -243,7 +246,7 @@ default, 4 to 1024); larger ones, reductions and exchanges stay on NCCL. On the cold 64K prompts in 36.5 s and decode at 73.1 / 60.8 tok/s (code / chat, temperature 0) with the relay off, and 36.7 s and 75.3 / 62.7 tok/s with it on (#2569). -`TF_GLM_WORLD=3` places a third rank the same way. From 1.1.2 the uneven KDA input projections of TP=3 (22, 21 and +`--tp 3` places a third rank the same way. From 1.1.2 the uneven KDA input projections of TP=3 (22, 21 and 21 heads) run instead of being refused; TP=3 device qualification is pending ([#1067](https://github.com/ashhart/TensorFold/issues/1067)). How a prompt's rows reach the other ranks (`TF_GLM_PREFILL_REDUCE`) and the RoCE gathers (`TF_ROCE`: on at two ranks, `TF_ROCE=1` at three or more) are in diff --git a/docs/recipes/idol-generate.md b/docs/recipes/idol-generate.md new file mode 100644 index 00000000000..69a825ea285 --- /dev/null +++ b/docs/recipes/idol-generate.md @@ -0,0 +1,120 @@ +# Idol end to end on Metal + +See [Idol on Metal](idol.md) for the checkpoint, encoders and decoders. + +## End to end + +`tf-idol-generate` (`zig/tests/idol_generate.zig`) chains the pieces above, from one preprocessed picture to a PLY: + +1. DINOv3's feature1; +2. the VAE's feature2; +3. the denoiser's condition and its 50 guided steps; +4. the octree and Gaussian decoders; +5. the PLY and the camera. + +Each model is loaded when its stage starts and freed when it ends. Background removal and cropping (BiRefNet, the SDK's +`preprocess`) are not ported, so the input is the picture `preprocess` returns, as float32 `pixels` [3, 1024, 1024] or +`image` [1024, 1024, 3] that `idol_case.py dino` or `vae` writes; either name in the other layout is refused. + +```sh +zig build tf-idol-generate -Dcpu=apple_m1 +zig-out/bin/tf-idol-generate WEIGHTS KLEIN/vae DINO case/vae.safetensors out/ # seed 42, 50 steps, cfg 3, 262,144 +zig-out/bin/tf-idol-generate WEIGHTS KLEIN/vae DINO case/vae.safetensors out/ --noise case/vae.safetensors +zig-out/bin/tf-idol-generate WEIGHTS KLEIN/vae DINO - out/ --features dino.safetensors --features vae.safetensors +``` + +Noise: + +- **The starting noise** is `torch.Generator("cpu").manual_seed(seed)`'s randn: [8192, 16], then [5], as + `idol_case.py case` draws it. The tool reimplements torch's mt19937 and its Box-Muller (`torch_rng.zig`). The + camera's 5 values are bit-equal to torch's, which `torch_rng.zig`'s test pins for seed 42. 28 of the 131,072 latent + values are 1 ulp off on the Mac, from torch's float cos and sin (glibc's put 5,854 up to 3 ulps off). +- **The VAE posterior's noise and the octree's draws** come from native seeded generators. +- **`--noise FILE`** gives the posterior's noise (`noise`, as `idol_case.py vae` records it). If FILE also holds + `latent` and `camera`, they replace the starting noise. + +It writes `generate.ply`, `camera.json`, `start.f32`, `sample.f32` and `tf-idol-generate.json`, each stage's seconds. + +### Measured + +Setup: + +- The avocado example and the same M5 Ultra and torch 2.13. +- Seed 42, 50 steps, guidance 3, 262,144 Gaussians. +- The SDK runs its own `IdolPipeline.__call__` on MPS once (`optimize` is CUDA-only), each stage timed by wrapping + the SDK's methods with `torch.mps.synchronize()`. Its PLY is byte-identical to an earlier run. +- Ours runs twice, each in a fresh process. The weights were in the page cache both times, so cold and warm differ + only by the process. + +| stage | ours, cold | ours, warm | SDK, MPS | +| --- | ---: | ---: | ---: | +| load (all models) | 0.67 s | 0.67 s | 2.11 s (and 2.75 s of imports) | +| preprocess (BiRefNet) | not ported | not ported | 0.51 s | +| DINOv3 | 0.158 s | 0.155 s | 0.275 s | +| VAE | 0.245 s | 0.241 s | 0.119 s | +| condition | 0.072 s | 0.071 s | in the sampling | +| denoise, 50 steps x 2 | 27.49 s | 27.50 s | 93.89 s | +| octree | 0.145 s | 0.143 s | 0.612 s | +| Gaussian decoder (+ activation) | 0.222 s (+ 0.001) | 0.222 s (+ 0.001) | 0.491 s (+ 0.013) | +| PLY and camera | 0.004 s | 0.004 s | 0.018 s | +| total | 29.09 s | 29.07 s | 100.81 s (95.41 s generating, less preprocess) | + +Memory, the whole process under `/usr/bin/time -l`: + +| | peak footprint | max RSS | GPU | +| --- | ---: | ---: | --- | +| ours | 2.71 GB | 1.94 GB | 2.40 GB Metal allocated at most | +| SDK | 12.88 GB | 6.20 GB | 5.01 GB MPS allocated, 12.64 GB driver (sampled) | + +### Quality + +The PLYs cannot be equal: + +- **Starting noise:** the SDK draws it from MPS's generator after the VAE's draw, which cannot be reproduced natively. +- **VAE posterior noise:** MPS's generator too, drawn in bf16. +- **The octree's draws:** torch's multinomial and jitter in the SDK, a native generator here. One count's difference + changes the topology from that level down. +- **The denoiser:** fp16 over 50 guided steps, and our encoders are not bit-equal to the SDK's. + +The starting noise matters most. With the same features, the SDK's own sample from MPS noise and its sample from the +CPU-seeded noise have cosine 0.479. Their PLYs are as far apart as ours is from the SDK's. + +So the PLYs are compared as distributions. Statistics are per PLY: xyz in PLY units, opacity and scale activated. The +NN columns, against the SDK's pipeline PLY, are: + +- the mean symmetric nearest-neighbour distance between 4,096 points sampled from each; +- the same over all 262,144 points. + +Two independent 4,096-point samples of the SDK's own PLY lie 0.00896 apart. + +| run | xyz std | opacity mean (q50) | scale q50 | NN, sampled | NN, all points | +| --- | --- | --- | --- | ---: | ---: | +| SDK pipeline | 0.189, 0.078, 0.304 | 0.885 (0.9986) | 0.00096 | 0.00906 | 0 | +| ours, native noise | 0.176, 0.073, 0.320 | 0.423 (0.181) | 0.00113 | 0.04623 | 0.0365 | +| ours, SDK's VAE noise | 0.176, 0.074, 0.320 | 0.425 (0.186) | 0.00113 | 0.04627 | 0.0366 | +| ours, SDK's VAE and starting noise | 0.189, 0.079, 0.304 | 0.887 (0.9986) | 0.00096 | 0.00922 | 0.00166 | +| SDK, same features, CPU-seeded noise | 0.176, 0.074, 0.319 | 0.422 (0.179) | 0.00113 | 0.04617 | 0.0368 | + +The table shows: + +- **Every PLY:** 262,144 Gaussians, all finite. +- **The SDK's VAE noise alone** changes little: the starting noise still differs. +- **With both of the SDK's noises:** our sample has cosine 0.99835 to the SDK's. The PLYs are as close as the sampling + can resolve: 0.00922 against the 0.00896 baseline, 0.0017 over all points. The camera is yaw 1.6956, pitch 0.5397 + and fov 0.1094, against 1.7006, 0.5413 and 0.1096. +- **Repeat:** our cold and warm PLYs are byte-identical. + +### Parity chain + +This run gives the SDK's own recorded feature1 and feature2 (`--features`) and the CPU-seeded noise. The SDK's +reference is the same features and noise: the `idol_case.py case` sample, and its `decode` PLY. + +- **Sample:** cosine 0.999991 to the SDK's. +- **Camera:** its latent's 5 values within 0.0022 of the SDK's. +- **PLY** against the SDK's decode of its own sample: + - mean NN 0.00981 between 4,096-point samples (the baseline 0.00944); + - 0.0018 over all points; + - xyz mean 6e-5 apart. + +From the picture, our encoders move the sample to cosine 0.99437 with native VAE noise. With the SDK's noise, they +move it to 0.99953. The PLY stays 0.0021 over all points from the SDK's decode. diff --git a/docs/recipes/idol.md b/docs/recipes/idol.md index 30aca2b3872..503919775be 100644 --- a/docs/recipes/idol.md +++ b/docs/recipes/idol.md @@ -482,3 +482,5 @@ The avocado example, the same machine and torch as above (`ATTN_BACKEND=sdpa`): (median of 10 warm; its first 0.385 s): 2.2x. Load 0.2 to 0.6 s. - **Memory**: 2.28 GB peak process footprint (`/usr/bin/time -l`, `tf-idol-dino` with the case's feature rows), the bf16 weights 1.68 GB of it. The SDK's MPS encode holds 2.24 GB of MPS driver memory. + +See [end-to-end generation](idol-generate.md). diff --git a/docs/recipes/ling-3.0-tiny-cpu.md b/docs/recipes/ling-3.0-tiny-cpu.md new file mode 100644 index 00000000000..d2b281d4572 --- /dev/null +++ b/docs/recipes/ling-3.0-tiny-cpu.md @@ -0,0 +1,106 @@ +# Ling-3.0-tiny on the CPU + +This page describes the native Zig engine running inclusionAI's Ling-3.0-tiny (`bailingmoe3`) on a CPU, aimed at +aarch64 Linux boards. Ling-3.0-tiny has 24 layers: 18 of KDA linear attention (16 heads, a 4-tap convolution and a +recurrent state) and an MLA layer every fourth layer (16 heads, a 512-wide latent cache), one dense SwiGLU layer, then +23 layers of 128 routed experts (8 a token, grouped sigmoid routing) beside a shared expert. Token IDs in, greedy +token IDs out: there is no server, tokenizer or sampling here yet. + +## Weights + +The engine reads the community Q4_K_M GGUF published with the model: `Ling-3.0-tiny-Q4_K_M.gguf` from +`inclusionAI/Ling-3.0-tiny-GGUF`, 4,823,894,944 bytes, with 272 Q4_K, 33 Q6_K, 6 Q5_0 and 215 F32 tensors. Another +publisher's file has the same name and a different size; only this one has been checked. The reader refuses a file +whose metadata, tensor names, shapes or kinds differ from this geometry. + +```bash +hf download inclusionAI/Ling-3.0-tiny-GGUF Ling-3.0-tiny-Q4_K_M.gguf --local-dir ~/models +``` + +The file is mapped read-only. Weights stay in their 4-bit blocks and are decoded block by block inside each +projection, never expanded to an F32 model. + +## Build + +With Zig 0.17.0, natively on the board: + +```bash +zig build tf-ling-cpu-decode +``` + +or from a Mac, for any aarch64 Linux board: + +```bash +zig build tf-ling-cpu-decode -Dtarget=aarch64-linux-gnu +``` + +Optionally, on boards with ARM dot-product support (check `grep -o asimddp /proc/cpuinfo` on the board), add +`-Dcpu=baseline+dotprod` (or the board's CPU model); the measured table below has both builds: + +```bash +zig build tf-ling-cpu-decode -Dtarget=aarch64-linux-gnu -Dcpu=baseline+dotprod +``` + +Either way the tool is `zig-out/bin/ling-cpu-decode`, built ReleaseSafe whatever `-Doptimize` says; copy it to the +board from a Mac. `-Dtarget=aarch64-linux-musl` gives a static binary. + +## Run + +```bash +ling-cpu-decode ~/models/Ling-3.0-tiny-Q4_K_M.gguf "$PROMPT_IDS" 32 4 +``` + +The arguments are the GGUF, the prompt's token IDs separated by commas (`PROMPT_IDS=ID,ID,...`), the number of tokens +to generate, and the thread count (1 to 8, default 1). The output has this shape: + +``` +model opened in S s, 4 threads, exact +prefill P tokens in S s (R tokens/s) +generated: ID ID ID ... +decode 32 tokens in S s (R tokens/s), finish length +``` + +Decoding stops early, with `finish stop`, at the GGUF's end-of-sequence tokens. A prompt and its generated tokens fit +in 4,096 positions. The tool does not tokenize: take the IDs from any tokenizer for Ling-3.0-tiny, for example +llama.cpp's `llama-tokenize` on the same file. + +- **Exact.** Every projection equals a scalar block-decode reference bit for bit, and threads split output rows or + whole experts only, so 1 to 8 threads give the same token IDs. Activations round to BF16 where the reference + model does. +- **Prompt rows.** The prompt runs 8 rows a call; whole, chunked and one-row prompts give the same logits. +- **Threads.** Persistent workers share each projection's rows and each token's eight routed experts, so more threads + help up to the number of fast cores. Rows are claimed in chunks, so a slower core takes fewer, but an expert on a + slow core is still waited for: start with the count of the board's fastest cores and try one more or fewer. Workers + spin between projections and sleep only when idle, so while decoding each thread keeps a core busy; leave a core + free if the board has other work. On Linux, when the process may run on at least as many CPUs as threads, each + thread is pinned to one of the first allowed CPUs in order, so the allowed set decides which cores do the work. On a + board with mixed cores, run it under `taskset -c LIST` with `LIST` set to the fast cores (on the Qualcomm board + measured below, `taskset -c 0,3,5,7` with 4 threads); the cores with the highest + `/sys/devices/system/cpu/cpu*/cpufreq/cpuinfo_max_freq` are the fast ones. + +- **More threads than cores.** Because workers spin, a thread count above the cores they run on is much slower, not a + little: 8 threads held to 4 cores decoded at 0.7 tokens a second, against 5.1 with 4 threads. + +## Measured + +On an eight-core Qualcomm board (four fast cores, dot product, no i8mm), `taskset -c 0,3,5,7`, with the 37-token prompt +whose IDs are in the PR description and 32 generated tokens. Each figure is from a run timed by the tool on an otherwise +idle board. The model opens in under a tenth of a second, so the first-token time is the prompt. + +One run each; every run below generated the same 32 IDs: + +| Build | Threads | Decode tokens/s | First token s | +| --- | --- | --- | --- | +| baseline | 1 | 1.68 | 34.8 | +| baseline | 4 | 5.01 | 5.3 | +| baseline | 8 | 0.71 | 14.6 | +| `+dotprod` | 1 | 1.95 | 11.5 | +| `+dotprod` | 4 | 5.08 | 5.8 | +| `+dotprod` | 8 | 0.73 | 14.5 | + +## Checks + +`zig build test-ling-cpu-host` runs the reader, kernel and forward checks on any host: decoded blocks against the +independent FP64 source definition, projections against expanded weights at 1 to 8 threads, and the forward on a +small synthetic model, whose whole, chunked and one-row prompts at 1, 2, 3, 4 and 8 threads give the same bytes; the +workers' rows and experts are also checked against the one-thread bytes at those thread counts. diff --git a/docs/recipes/minimax-h3-image-metal.md b/docs/recipes/minimax-h3-image-metal.md index 7aa8c41cf6d..1fea4fd92db 100644 --- a/docs/recipes/minimax-h3-image-metal.md +++ b/docs/recipes/minimax-h3-image-metal.md @@ -269,19 +269,22 @@ samples. A separate 16-byte generation in `/tmp/tensorfold-speech.lock.stamp` de between lock polls. Missing, malformed or inaccessible signals invalidate timings; uncoordinated forwards do too. Both processes must use this protocol; an old speech binary cannot certify clean timings. Speech remains best-effort on filesystem errors: if both publishing and invalidating a generation fail, a short request can remain unobserved. -Speech waits for its shared hold only behind a render's exclusive probe, which lasts microseconds and never spans GPU -work, so it never synthesizes unprotected. The prompt encoder (`tf-h3-image-prompt`, the server's first stage) waits +Speech releases its hold when the engine's work ends, before the reply goes to the client, so a slow client never +holds a render back. It opens the lock without following symlinks and creates it only when absent; behind an +exclusive hold longer than a second (a render's probes last microseconds) it synthesizes without the hold rather +than wait. A command buffer that fails is reported only after every buffer committed with it has completed. +The prompt encoder (`tf-h3-image-prompt`, the server's first stage) waits before each pass with three queued, and the decoder (`tf-h3-image-decoder`, its last) before each batch of tiles; both print the seconds they waited. ### Speech contention receipt, 12 November 2026 Apple M5 Ultra, 256 GiB RAM, macOS 27.0 (26A425), Zig 0.17.0, ReleaseFast with `-Dcpu=apple_m1`. -The branch's isolated Drama 3 NVFP4 server served the Capri catalog in `synth.json`, CFG 1.5 with paired submission, +The branch's isolated Drama 3 NVFP4 server served a voice catalog in `synth.json`, CFG 1.5 with paired submission, one lane and context 8192. The live release server was not changed. More than 170 GiB was free before loading. The client timed from sending each HTTP request until reading the first two PCM bytes, not response headers. -The reference cache was warmed before starting `tf-h3-image MODEL_DIR CASE OUT free`. The case was card 35's +The reference cache was warmed before starting `tf-h3-image MODEL_DIR CASE OUT free`. The case was a 4096-square, seed-42, 24-text-row case (SHA-256 `af4f85f19ebeb4e4af5beada167d8e8fd00bf1b880541b88a60c0a2b5b6dd66b`). Five sequential requests, seeds 42โ€“46, used `stream=true` and `response_format="pcm"`: @@ -307,7 +310,7 @@ not a cold-start guarantee. Generation checks now bracket the complete wall inte ### Five voice notes during a resident render, 13 November 2026 Same machine, speech server and client, built from `b82e132` and served on port 18899; `tf-h3-image-server` drew -card 34's prompt at 4096x4096, seed 42. The server's first request after start, with its reference rows still unbuilt +a prompt at 4096x4096, seed 42. The server's first request after start, with its reference rows still unbuilt in memory, reached first PCM in 2.879 s idle; the next took 0.414 s. Five notes then went out 15 s apart during the render, all HTTP 200 with the render running at the start and end of each: @@ -321,7 +324,7 @@ render, all HTTP 200 with the render running at the start and end of each: Steps 1-3, 5 and 6 waited 2.27-3.21 s each and reported `timing_valid=false`; step 4 waited zero and reported `true`, with 10.04 s on the GPU like the others. The render resumed after each wait and exited 0; its latent matched -card 34's `t2i-4096.latent.f32` and its rows the 12 November baseline (`b3726693...`) byte-for-byte. The prompt +the uncoordinated `t2i-4096.latent.f32` and its rows the 12 November baseline (`b3726693...`) byte-for-byte. The prompt encoder and decoder are too short at this spacing to catch a note; `test-h3-image-server` has speech arrive during each stage. The isolated server was stopped afterward; the live release server was not changed. @@ -439,6 +442,36 @@ Before the workload, `nice -n 10 zig build test test-golden` exited zero in 89.6 exited zero in 3.27 s. That regression retains card 49's mid-encoder, refiner, decoder and denoising waits and byte-identical output checks. The measured ReleaseFast executable rebuild also exited zero. +### Large resident renders and a live speech server, 14-15 November 2026 + +The render gives way only to a speech server that publishes the same lock: updating `tf-h3-image-server` alone +cannot make an older speech process announce a request, and `timing_valid=true` cannot detect a speech process +that does not take part. To check a live deployment during a real request: + +- Attempt a nonblocking exclusive `flock` on `/tmp/tensorfold-speech.lock` from a separate process every 20 ms; + contention means speech holds it. +- Compare `/tmp/tensorfold-speech.lock.stamp` before and after the request. The coordinated server writes it even + when acquiring the speech hold fails. Across users the lock needs mode 0644, the stamp 0666 and length 16. +- Time the complete audio response, not only first PCM: a streamed HTTP 200 can still miss a caller's deadline. + +Apple M5 Ultra, 256 GiB, macOS 27.0, Zig 0.17.0, `tf-h3-image-server` built with +`zig build tf-h3-image-server -Dcpu=apple_m1 -Doptimize=ReleaseFast`, rendering 5472x3072 (seed 2201, 183 prompt +tokens; six steps of 11-12 s each). Each voice request used `model="fishaudio/drama-3"` and the public input "The +little boat crossed the harbor before the sun came up, and the gulls were quiet over the water while the fishermen +coiled their nets along the pier." (618,496 PCM bytes), sent after the render's `drawn on` line. + +With a speech server that did not publish the lock, the streamed reply completed in **72.854 s** (first PCM 18.856 s) +while the render ran; 776 probes found no hold, the stamp never changed and all six steps reported zero wait. +With the speech server publishing the lock and the same renderer executable (same SHA-256), five voice notes sent +after step 2 of consecutive renders completed in **9.397, 9.538, 9.774, 9.769 and 9.676 s**, each an M4A including +transport and encoding; 76-93 of every 93-111 probes found a hold and the generation changed each time. + +That server replayed 17 resident requests (eight 5472x3072, six 3072x5472, three 4096x4096) in one process, with a +streamed voice request at the start of each: 17/17 HTTP 200, first PCM 1.061-2.224 s, complete body 5.484-9.421 s. +The image logs recorded 183.28 s of waits and 25 of 102 steps with `timing_valid=false`. All 17 final latents and +PNGs matched the uncoordinated run's by SHA-256. These are contention measurements, not a speech-free throughput +comparison. + ## Gates, fixed before any run These are the bounds `tf-h3-image` checks (`picture.gates`). It exits 1 when one fails, and 2 when the case holds no diff --git a/docs/recipes/minimax-m3.1-flash-cuda.md b/docs/recipes/minimax-m3.1-flash-cuda.md index 0b4aab588a9..86b0b091c42 100644 --- a/docs/recipes/minimax-m3.1-flash-cuda.md +++ b/docs/recipes/minimax-m3.1-flash-cuda.md @@ -35,22 +35,23 @@ rank, the vocabulary split 782 and 781 blocks. ## Run The family is admitted only as it was run: on GB10 (sm_121) at two ranks. Any other GPU is refused -(`MiniMaxM3RequiresSm121`), and so is one rank or any other world (`MiniMaxM3RequiresTwoRanks`). `TF_MINIMAX_RANK` -(0 or 1) of `TF_MINIMAX_WORLD=2` places each rank, and `NCCL_COMM_ID` names rank 0's address and port on the link -between the hosts. With 192.0.2.1 as rank 0's address on their direct link, the same folder on both: +(`MiniMaxM3RequiresSm121`), and so is one rank or any other world (`MiniMaxM3RequiresTwoRanks`). `--rank` +(0 or 1) of `--tp 2` places each rank, and `--master` with `--master-port` names rank 0's address and port on the link +between the hosts (NCCL's root, `NCCL_COMM_ID`). `TF_MINIMAX_RANK` and `TF_MINIMAX_WORLD` still place a rank as aliases of `--rank` and `--tp` for one release; the start-up warning names the release that refuses them +with the flag to use; a flag and an alias that differ refuse. With 192.0.2.1 as rank 0's address on their direct link, the same folder on both: ```bash export NCCL_RUNTIME_CONNECT=0 NCCL_CUMEM_ENABLE=0 NCCL_CUMEM_HOST_ENABLE=0 # on GB10 pairs # on rank 1 -TF_MINIMAX_RANK=1 TF_MINIMAX_WORLD=2 NCCL_COMM_ID=192.0.2.1:29581 TENSORFOLD_MEMORY_RESERVE_GIB=3 \ - tensorfold serve ~/models/mm-exl3 --context 32768 --parallel 2 --prompt-cache-gib 3 --vision +TENSORFOLD_MEMORY_RESERVE_GIB=3 tensorfold serve ~/models/mm-exl3 --tp 2 --rank 1 --master 192.0.2.1 \ + --master-port 29581 --context 32768 --parallel 2 --prompt-cache-gib 3 --vision # on rank 0 (192.0.2.1) -TF_MINIMAX_RANK=0 TF_MINIMAX_WORLD=2 NCCL_COMM_ID=192.0.2.1:29581 TENSORFOLD_MEMORY_RESERVE_GIB=3 \ - tensorfold serve ~/models/mm-exl3 --context 32768 --parallel 2 --prompt-cache-gib 3 --vision +TENSORFOLD_MEMORY_RESERVE_GIB=3 tensorfold serve ~/models/mm-exl3 --tp 2 --rank 0 --master 192.0.2.1 \ + --master-port 29581 --context 32768 --parallel 2 --prompt-cache-gib 3 --vision ``` Set `NCCL_SOCKET_IFNAME` and `NCCL_IB_HCA` for the link as NCCL documents them; each rank keeps a TCP line to rank 0 -on the port after `NCCL_COMM_ID`'s, so a rank that fails stops the others. On two ranks the layers' small gathers go by +on the port after the root's, so a rank that fails stops the others. On two ranks the layers' small gathers go by RoCE writes (as GLM's); `TF_ROCE=0` leaves them to NCCL and `TF_ROCE_MAX_KB` caps a rank's bytes. - The key/value cache is bf16, exact; a token takes 75 KiB a rank at TP=2 across the 60 layers (keys and values of the diff --git a/docs/recipes/nemotron-3.5-super-vl.md b/docs/recipes/nemotron-3.5-super-vl.md index 88c161f5341..8e55ae9ebff 100644 --- a/docs/recipes/nemotron-3.5-super-vl.md +++ b/docs/recipes/nemotron-3.5-super-vl.md @@ -51,15 +51,16 @@ too) and computes it for rank 0's jobs. The ranks meet over NCCL, which the engi ```bash # on rank 1 -TF_NEMOTRON_RANK=1 TF_NEMOTRON_WORLD=2 NCCL_COMM_ID=192.0.2.1:29741 \ - tensorfold serve /models/NVIDIA-Nemotron-3.5-Super-VL-120B-A12B-NVFP4 +tensorfold serve /models/NVIDIA-Nemotron-3.5-Super-VL-120B-A12B-NVFP4 --tp 2 --rank 1 --master 192.0.2.1 --master-port 29741 # on rank 0 (192.0.2.1) -TF_NEMOTRON_RANK=0 TF_NEMOTRON_WORLD=2 NCCL_COMM_ID=192.0.2.1:29741 \ - tensorfold serve /models/NVIDIA-Nemotron-3.5-Super-VL-120B-A12B-NVFP4 --name super --vision --host 0.0.0.0 +tensorfold serve /models/NVIDIA-Nemotron-3.5-Super-VL-120B-A12B-NVFP4 --tp 2 --rank 0 --master 192.0.2.1 --master-port 29741 \ + --name super --vision --host 0.0.0.0 ``` +`TF_NEMOTRON_RANK` and `TF_NEMOTRON_WORLD` still place a rank as aliases of `--rank` and `--tp` for one release; the start-up warning names the release that refuses them +with the flag to use; a flag and an alias that differ refuse. Set `NCCL_SOCKET_IFNAME` and `NCCL_IB_HCA` for the link between the hosts as NCCL documents them. Rank 1 keeps a TCP -line to rank 0 on the port after `NCCL_COMM_ID`'s (29742 here), opened before NCCL. Before any weight loads, both ranks +line to rank 0 on the port after the root's (29742 here), opened before NCCL. Before any weight loads, both ranks check that they run the same build, model, cut and precision and the same checkpoint layout: config.json, the index, and each shard's name, size and header. While the weights load, each rank reads and hashes every byte of every shard it holds (sha256), and checks each file against its Hugging Face blob name, which is its sha256, when the folder is a diff --git a/docs/recipes/persisted-serving-keys.md b/docs/recipes/persisted-serving-keys.md index 8227679621a..8f1af9170eb 100644 --- a/docs/recipes/persisted-serving-keys.md +++ b/docs/recipes/persisted-serving-keys.md @@ -55,7 +55,7 @@ grids, and whether a captured set runs with which entries on our glue. `TF_FLASH keyed through the profile rows. Its draft, window, round, graph, lane-parts (`TF_FLASHNEXT_LANE_PARTS`), load-thread, I/O and dense-split settings and `TF_FLASHNEXT_KV_PAGE_TEST` are not keyed: kept states come only from prompt passes, which those settings either never reach, reach with the same launches or the same kernels addressing pages, or refuse for disk at `--tp 2`. -Nemotron on CUDA keys `--precision checkpoint`'s math, the expert ranks of `TF_NEMOTRON_WORLD`, a ModelOpt +Nemotron on CUDA keys `--precision checkpoint`'s math, the expert ranks of `--tp` (or `TF_NEMOTRON_WORLD`), a ModelOpt checkpoint's NVFP4 decode warps and lane half-tile threshold, the experts' resident grids and, with a captured set, the attention variant `--context` picks by its chunk count. Its pages, poison fill, carveout, segments, graph log and trace, and the context on our own glue, are not keyed: they place memory, fill pages before use, log, run only passes that diff --git a/docs/recipes/qwen3.8-flash-next.md b/docs/recipes/qwen3.8-flash-next.md index 7efd6d3f8d7..abaee548781 100644 --- a/docs/recipes/qwen3.8-flash-next.md +++ b/docs/recipes/qwen3.8-flash-next.md @@ -71,6 +71,8 @@ row. Every (row, expert) pair keeps the per-row kernels' sums, so replies keep t or fewer, which is every prose round, are untouched. `TF_FLASHNEXT_GROUPED_ROWS` sets the first grouped width (`1` through `32`; `0` turns grouping off); it does nothing with tensor units, `--ssd-experts` or speed-up mode. +Shared target rounds keep per-pair expert launches by default. `TF_FN_GX_SHARED=1` routes eligible shared rounds through the same grouped kernels under the same row threshold and 4-bit/group-32 restrictions; `0` is the default. Tensor-unit Macs, SSD experts and speed-up mode do not use these kernels. + The prefill path uses sparse selected-key attention, fused hyper-connections and n-gram lookups, stacked DeltaNet projections and sorted expert rows. It submits bounded groups of layers to limit live workspace. Compatible prefill matmul kernels check against MLX; unsupported paths use MLX's kernels. diff --git a/docs/recipes/ripple-65b-cuda.md b/docs/recipes/ripple-65b-cuda.md new file mode 100644 index 00000000000..85353ef653f --- /dev/null +++ b/docs/recipes/ripple-65b-cuda.md @@ -0,0 +1,117 @@ +# Ripple-65B-Preview, CUDA + +This recipe covers text generation with ricursiveAI's Ripple-65B-Preview (model_type `ricursive`; see +[the Metal recipe](ripple-65b-metal.md) for the model) on the CUDA engine. One release is served as published, +read in place from its shards with nothing converted: + +- [`ricursiveAI/Ripple-65B-Preview-NVFP4`](https://huggingface.co/ricursiveAI/Ripple-65B-Preview-NVFP4) (revision + `99eea4477a001a41b86914e41feb4b2ed86105e5`, 53 GiB): ModelOpt NVFP4 MLPs, attention, embeddings and head in bf16. + +The bf16 release is refused by name (`RicursiveCudaNeedsNvfp4`): at 121 GiB it does not fit a GB10, and the CUDA +family reads only the NVFP4 MLPs. + +It was brought up on a DGX Spark (GB10, sm_121, 121.7 GiB shared with the host, CUDA 13). The kernels build for +sm_80, 86, 89, 120 and 121 and their launches fit each, but only GB10 was run. + +## Build and serve + +```sh +hf download ricursiveAI/Ripple-65B-Preview-NVFP4 --revision 99eea4477a001a41b86914e41feb4b2ed86105e5 \ + --local-dir models/ripple-65b-nvfp4 +zig build native -Dnvcc=/usr/local/cuda/bin/nvcc -Dsm=121 +zig-out/native/bin/tensorfold-native serve models/ripple-65b-nvfp4 --name ripple --port 8888 --context 32768 +``` + +At `--context 32768` admission gives eight streams of 2.78 GiB and a 16.0 GiB prompt cache, after a 12.2 GiB +reserve. A stream's caches: 64 of the 80 layers slide over 1,024 keys and keep a 3,072-row ring each; every fifth +layer is global and keeps every key, in 512-row pages. + +Thinking follows the chat template, as on Metal: Ripple writes `` itself when it thinks and answers bare +otherwise, and the server files a reply without the block as answer. Its think markers are spelled from several +tokens, so a thinking budget and logprobs are refused by name. + +## What the family is + +`zig/src/families/ricursive/cuda*.zig` and `zig/kernels/cuda/ricursive*.cu`, with the same layer math as Metal and +the release's `modeling_ricursive.py` as the reference: + +- **Projections.** NVFP4 MLPs on the `.nvfp4` W4A16 lane (nibbles and E4M3 scales repacked at load, the fp32 global + per tensor; `input_scale` is not used); attention projections, embeddings and head in bf16 through `qmmf`. Q, K and + the gate share one projection; V reads the value-residual blend. +- **Glue** (`ricursive.cu`): the embedding scale in fp32, the add-and-norm with the value-residual lerp, the gate + (bf16 sigmoid before the multiply) and the clamped SwiGLU. `ricursive_prep.cu` does the Q/K norm, RoPE (bf16 cos + and sin tables; none on the global layers) and the K/V write into a ring or pages in one kernel. +- **Attention.** Sliding decode on `tf_window_decode_tc` over each layer's ring; global decode on the paged + `tree_attention` kernels; prompt chunks on the window kernel (paged for the global layers) with two query heads a + block, for Ripple's group of 10. +- **Serving.** The lane host's shared rounds as CUDA graphs, greedy or sampled draws, copy drafts, verify windows, + kept states and the prompt cache. + +**Activations stay bf16**, as on Metal: the engine serves the NVFP4 weights with bf16 activations and fp32 sums, not +the publisher's W4A4 kernels. + +Every kernel is registered with the kernel contract, with planted controls that each must turn its gate red. On +GB10 (nvcc 13.3, sm_121): + +``` +SUMMARY ricursive: 20 kernels, 20 pass gates 1-4, 0 fail; 24 controls: 24 red as planted, 0 missed +``` + +## Correctness (GB10) + +`tools/zig/ricursive_reference.py` (from the Metal PR) on the Spark's CPU, teacher-forced over the same 2,586-token +chat as the Metal recipe, against the NVFP4 release's own passes: + +| engine logits | against | mean KL | top-1 | +|---|---|---:|---:| +| 2,048-row prompt chunks | the float64 pass | 0.00069 | 98.72% | +| 2,048-row prompt chunks | the `--bf16-points` pass | 0.00078 | 98.84% | +| one-row decode | the float64 pass | 0.00076 | 98.92% | +| one-row decode | the `--bf16-points` pass | 0.00080 | 99.07% | +| `--bf16-points` pass (no engine) | the float64 pass | 0.00073 | 98.96% | + +The engine sits as close to the float64 pass as the bf16-rounded reference does (Metal: 0.00069 prompt, 0.00107 +decode). The float64 pass equals the release's own `modeling_ricursive.py` run in float64 on the same weights +(`--release-f64`: top-1 100%, largest KL 0.0005). Every engine miss is a near-tie: the reference leads the engine's +pick by at most 0.25 nats. + +- Prompt chunks of 2,048, 1,000 and 333 rows give bit-identical logits on all 2,586 rows; no non-finite logit. +- A greedy 128-token reply equals the float64 pass's argmax token for token. +- With graphs on and with `--eager`, every dump and reply hash equals the first run's bit for bit. +- Served replies are bit-identical alone, beside seven other streams and one at a time (greedy and sampled). A + conversation sent again, reusing 79 to 81 cached tokens, equals its first reply, and 60 repeats of a reply equal the + first. Seeded replies equal their repeats, and streamed text equals the reply sent whole. + +## Measured (GB10, NVFP4 release, `--context 32768`, no other model busy) + +One stream decodes at 248.3 ms a token (4.03 tok/s); each step reads all 53 GiB of weights. Prompts run +at 518-520 tok/s at 2,586 rows. Greedy 256-token essays, thinking off, all streams together: + +| streams | tok/s | +|---:|---:| +| 1 | 4.03 | +| 4 | 15.54 | +| 8 | 29.93 | + +At `--context 131072` admission gives four streams of 8.78 GiB and a 7.1 GiB prompt cache. Cold prompts there +(`tools/bench_cache.py --require-cold`), time to first token: 3.76 s at 2,048 tokens (545 tok/s), 15.6 s at 8,192 +(524), 68.4 s at 32,768 (479) and 150.7 s at 65,536 (435). Each reply equals its repeat and itself beside a second. +A 114,528-token prompt with a random four-word passphrase a third of the way in: the reply names it, first token +after 300.5 s (381 tok/s). + +At `--context 262144`, the cap `config.zig` sets, admission gives two streams of 16.75 GiB and a 5.3 GiB prompt +cache. A 258,331-token prompt with a random four-word passphrase a third of the way in: the reply names it, first +token after 919.1 s (281 tok/s). The prompt cache keeps no state of that prompt: one is 16.0 GiB, over the 5.3 GiB +budget. + +## Not done + +Structured output (`response_format`) and forced tool calls (`tool_choice` `"required"` or a named function) are not +supported on CUDA yet: the server refuses them, because the CUDA family has no masked sampling. Tool calls with +`tool_choice` `"auto"` work. No quality suite was run. Past 131,072 tokens, only the one near-cap prompt above was +run. Only GB10 was run. The publisher's DFlash2 drafter (`ricursiveAI/Ripple-65B-Preview-DFlash2`) is not served +on CUDA yet. + +## Licence + +Ripple-65B-Preview and its NVFP4 release are published under Apache-2.0 at the revisions measured here. diff --git a/docs/run-guide.md b/docs/run-guide.md index d0de4f54cbd..3b270539ddc 100644 --- a/docs/run-guide.md +++ b/docs/run-guide.md @@ -131,10 +131,10 @@ The binary's `capabilities --json` response lists its supported flags and platfo | `--drafter-bits 0\|4` | Drafter weight precision where the model offers a choice: 4 bits (the default), or 0 to keep bf16. Qwen3.8-27B on CUDA takes 4 only. | | `--record DIR` | Write each stream's committed tokens, positions and tapped rows under DIR, for drafter training. CUDA Nemotron only; a single stream runs through the lane rounds, and recording stops below 25 GiB free disk. | | `--keep-warm SECONDS` | Keep the Metal GPU active while idle for this long after a request, default 900; zero disables it. | -| `--cfg-gamma GAMMA` | Metal Drama speech: semantic guidance strength, finite 1โ€“5; 0/default disables it. Only reference-conditioned requests are guided. Enabled replies report `X-Cfg-Gamma`; codec heads stay conditional. | -| `--cfg-allow-request-gamma` | Metal Drama speech: allow a finite 1โ€“5 `X-Cfg-Gamma` request header; invalid values return 400 before engine submission. Without this opt-in, the server's gamma is fixed. | -| `--cfg-force-guided` | With an enabled Metal Drama guidance policy, exercise the unconditional state even at gamma 1. The semantic mix at 1 remains exact conditional-logit identity. | -| `--cfg-batched` | With enabled Metal Drama guidance, submit both independent backbone states in one command buffer rather than separate submissions. Weights are shared; extra state is included in admission. Not vectorized batching. | +| `--cfg-gamma GAMMA` | Drama speech on Metal and CUDA: semantic guidance strength, finite 1โ€“5; 0/default disables it. Only reference-conditioned requests are guided. Enabled replies report `X-Cfg-Gamma`; codec heads stay conditional. | +| `--cfg-allow-request-gamma` | Drama speech on Metal and CUDA: allow a finite 1โ€“5 `X-Cfg-Gamma` request header; invalid values return 400 before engine submission. Without this opt-in, the server's gamma is fixed. | +| `--cfg-force-guided` | With an enabled Drama guidance policy, exercise the unconditional state even at gamma 1. The semantic mix at 1 remains exact conditional-logit identity. | +| `--cfg-batched` | With enabled Drama guidance, run both independent backbone states without a host wait between them: one command buffer on Metal, two streams joined by events on CUDA, rather than separate submissions. Weights are shared; extra state is included in admission. Not vectorized batching. | | `--silence-floor-dbfs DBFS` | Drama speech only: explicit frame-power floor for the silence guard, with no default floor. Calibrate below quiet intended speech using public or built-in speech. | | `--silence-seconds SECONDS` | Drama speech only: stop after this continuous duration below the explicit floor, retaining audio and reporting `silence`. Unset by default: off; calibrate above intentional pauses. | | `--silence-onset-s SECONDS` | Drama speech only: with the silence guard on, stop once this many seconds run below its floor while the synthesis has voiced less than `--silence-onset-voiced-s`, retaining audio and reporting `silence`. Off unless given; must be below `--silence-seconds`. | diff --git a/docs/vision.md b/docs/vision.md index fbcfe945414..a0d1f9c2e6f 100644 --- a/docs/vision.md +++ b/docs/vision.md @@ -159,6 +159,9 @@ that read images: GLM-5.3-Flash, Qwen3.8-27B, Qwen3.8 Flash Next, Gemma 4 [31B](recipes/gemma-4-native.md#images) and [12B](recipes/gemma-4-12b-native.md#images) and Step-5-Preview on one Mac, GLM-5.3-Flash on [CUDA ranks](recipes/glm-5.3-flash-cuda.md#requests) and Nemotron 3.5 Super VL on CUDA. Other native engines refuse the flag at startup. +On CUDA and HIP a tower loads only with `--vision`, d1-3B's pictures included; a checkpoint with a tower starts +text-only without it. `--vision` on a checkpoint without a tower is refused at startup as "--vision given but this + checkpoint has no vision tower" (core's gate, `zig/src/core/engine_vision.zig`), on Qwen3.5 HIP too. The CLI accepts explicit image budgets from 16 to 262,144 tokens; each engine still applies its own limits and memory admission. - Images arrive as `image_url` data URLs in user messages and tool results. With `--vision-urls` (it needs diff --git a/tools/exact_receipt.py b/tools/exact_receipt.py new file mode 100644 index 00000000000..154b6568faf --- /dev/null +++ b/tools/exact_receipt.py @@ -0,0 +1,263 @@ +"""Collection and comparison helpers for tools/exact_restarts.py's public exact receipt.""" +import hashlib +import json +import re +import time +import urllib.error +import urllib.request +from concurrent.futures import ThreadPoolExecutor + +PUBLIC = re.compile(r"[A-Za-z0-9_.:+@-]{1,128}\Z") + + +def public_id(value, field): + """A caller-supplied public identifier, never a path, address, account or free-form text.""" + if not isinstance(value, str) or not PUBLIC.fullmatch(value) or "@" in value or value.startswith("~"): + raise ValueError(f"--{field}-id must be a public identifier without paths, accounts or whitespace") + return value + + +def token_sha256(ids): + return hashlib.sha256(json.dumps(ids, separators=(",", ":")).encode()).hexdigest() + + +def first_diff(a, b): + for i, (x, y) in enumerate(zip(a, b)): + if x != y: + return i + return min(len(a), len(b)) if len(a) != len(b) else None + + +def comparison(kind, prompt, left_id, left, right_id, right): + pos = first_diff(left["token_ids"], right["token_ids"]) + return {"kind": kind, "prompt": prompt, "reference_request": left_id, "candidate_request": right_id, + "reference_token_ids_json_sha256": left["token_ids_json_sha256"], + "candidate_token_ids_json_sha256": right["token_ids_json_sha256"], + "first_diff": pos, "equal": pos is None} + + +def compare_results(reference, candidate, kind): + """Compare candidate-request keys; a restart candidate may be a focused subset of the first run.""" + left = reference.get("results", reference) + right = candidate.get("results", candidate) + return [comparison(kind, v["prompt"], k, left[k], k, v) for k, v in right.items() if k in left] + + +def result(request, item, sampling, stop, streams, draft, phase, peer, ids, cached, finish, wall, round_wall, + drafted, accepted): + return {"request": request, "prompt": item["name"], "sampling": sampling, "stop": stop, "streams": streams, + "draft": draft, "phase": phase, "peer": peer, "token_ids": ids, + "token_ids_json_sha256": token_sha256(ids), "token_count": len(ids), "cached_tokens": cached, + "finish_reason": finish, "wall_seconds": wall, "round_wall_seconds": round_wall, + "drafted_tokens": drafted, "accepted_tokens": accepted} + + +def request_body(item, tokens, sampling, stop, seed, draft, followup=False, reply=""): + sampled = sampling == "seeded" + body = {"model": "served", "max_tokens": tokens, "temperature": 0.8 if sampled else 0, + "top_p": 0.95 if sampled else 1, "top_k": 20 if sampled else 0, "min_p": 0, + "ignore_eos": stop == "budget", "return_token_ids": True, "draft": draft, "stream": False} + if sampled: + body["seed"] = seed + if item["kind"] == "chat": + messages = [{"role": "user", "content": item["prompt"]}] + if followup: + messages += [{"role": "assistant", "content": reply}, + {"role": "user", "content": item.get("followup", "Continue.")}] + body["messages"] = messages + elif isinstance(item["prompt"], list): + suffix = (reply + item["followup_token_ids"]) if followup else [] + body["prompt"] = item["prompt"] + suffix + else: + body["prompt"] = item["prompt"] + (("\n" + reply + "\n" + item.get("followup", "Continue.")) + if followup else "") + return body + + +def request_name(item, sampling, stop, streams, draft, phase, peer): + return "/".join((item["name"], sampling, stop, f"s{streams}", "draft" if draft else "plain", phase, + f"peer{peer}")) + + +def fetch(base, spec, api_key, timeout): + body, request = spec["body"], spec["request"] + path = "/v1/chat/completions" if "messages" in body else "/v1/completions" + req = urllib.request.Request(base + path, data=json.dumps(body).encode(), + headers={"Content-Type": "application/json"}) + if api_key: + req.add_header("Authorization", f"Bearer {api_key}") + started = time.perf_counter() + try: + with urllib.request.urlopen(req, timeout=timeout) as response: + reply = json.load(response) + wall = time.perf_counter() - started + runtime = reply.get("tensorfold") or {} + if runtime.get("drafts") is not body["draft"]: + raise ValueError("reply did not acknowledge the requested draft mode") + ids = reply.get("tensorfold", {}).get("token_ids") + usage = reply.get("usage") or {} + cached = (usage.get("prompt_tokens_details") or {}).get("cached_tokens") + prompt = usage.get("prompt_tokens") + if not isinstance(ids, list) or any(type(x) is not int or x < 0 or x >= 2**32 for x in ids): + raise ValueError("reply carried no valid tensorfold.token_ids") + if type(cached) is not int or type(prompt) is not int or not 0 <= cached <= prompt: + raise ValueError("reply carried no valid cached/prompt token counts") + if usage.get("completion_tokens") != len(ids): + raise ValueError("reply completion token count did not match tensorfold.token_ids") + choice = (reply.get("choices") or [{}])[0] + finish = choice.get("finish_reason") + if finish not in ("stop", "length"): + raise ValueError("reply carried no valid finish reason") + speculative = reply.get("speculative") or {} + content = ((choice.get("message") or {}).get("content") if "messages" in body else choice.get("text")) or "" + return {"ok": True, "ids": ids, "cached": cached, "prompt": prompt, "finish": finish, "wall": wall, + "drafted": speculative.get("drafted") or 0, "accepted": speculative.get("accepted") or 0, + "content": content} + except urllib.error.HTTPError as e: + return {"ok": False, "request": request, "reason": f"HTTP {e.code}"} + except (urllib.error.URLError, TimeoutError, OSError): + return {"ok": False, "request": request, "reason": "request transport failure"} + except (ValueError, TypeError, KeyError, IndexError, json.JSONDecodeError) as e: + reason = str(e) if isinstance(e, ValueError) and str(e).startswith("reply ") else "invalid response" + return {"ok": False, "request": request, "reason": reason} + + +def spec_for(item, args, sampling, stop, streams, draft, phase, peer, followup=False, reply=""): + tokens = len(item["expected_token_ids"]) if stop == "budget" else args.eos_tokens + return {"request": request_name(item, sampling, stop, streams, draft, phase, peer), "item": item, + "sampling": sampling, "stop": stop, "streams": streams, "draft": draft, "phase": phase, "peer": peer, + "budget": tokens, "body": request_body(item, tokens, sampling, stop, args.seed, draft, followup, reply)} + + +def check_result(out, value): + request, ids, item = value["request"], value["token_ids"], value["_item"] + if not ids: + out["failures"].append({"request": request, "reason": "empty reply makes equality vacuous"}) + expected = "length" if value["stop"] == "budget" else "stop" + if value["finish_reason"] != expected: + out["failures"].append({"request": request, + "reason": f"finish {value['finish_reason']}; expected {expected} for {value['stop']}"}) + if value["stop"] == "budget" and value["token_count"] != value["_budget"]: + out["failures"].append({"request": request, "reason": "token-budget stop returned the wrong token count"}) + if value["phase"] in ("cold", "fresh") and value["cached_tokens"] != 0: + out["failures"].append({"request": request, "reason": "cold/fresh request reused cached tokens"}) + if value["phase"] in ("warm", "resumed") and value["cached_tokens"] == 0: + out["failures"].append({"request": request, "reason": "cache miss on warm/resumed request"}) + if value["draft"] and value["drafted_tokens"] <= 0: + out["failures"].append({"request": request, "reason": "drafting was not observed in this request"}) + if not value["draft"] and value["drafted_tokens"] != 0: + out["failures"].append({"request": request, "reason": "plain request performed draft work"}) + source = value["sampling"] == "greedy" and value["stop"] == "budget" and value["streams"] == 1 \ + and not value["draft"] and value["phase"] == "cold" + if source and ids != item["expected_token_ids"]: + out["failures"].append({"request": request, "reason": "recorded greedy window not reproduced"}) + + +def perform_round(out, base, specs, args): + started = time.perf_counter() + with ThreadPoolExecutor(max_workers=len(specs)) as pool: + replies = list(pool.map(lambda s: fetch(base, s, args.api_key, args.timeout), specs)) + round_wall = time.perf_counter() - started + out["rounds"].append({"request_ids": [s["request"] for s in specs], "streams": len(specs), + "round_wall_seconds": round_wall}) + made = {} + for spec, reply in zip(specs, replies): + if not reply["ok"]: + out["failures"].append({"request": spec["request"], "reason": reply["reason"]}) + continue + value = result(spec["request"], spec["item"], spec["sampling"], spec["stop"], spec["streams"], + spec["draft"], spec["phase"], spec["peer"], reply["ids"], reply["cached"], + reply["finish"], reply["wall"], round_wall, reply["drafted"], reply["accepted"]) + value["_budget"], value["_item"], value["content"] = spec["budget"], spec["item"], reply["content"] + value["prompt_tokens"] = reply["prompt"] + check_result(out, value) + out["results"][spec["request"]] = value + made[spec["peer"]] = value + return made + + +def pair_phase(out, kind, left, right, peers): + for peer in peers: + if peer in left and peer in right: + out["comparisons"].append(comparison(kind, left[peer]["prompt"], left[peer]["request"], left[peer], + right[peer]["request"], right[peer])) + if kind == "fresh_vs_resumed" and left[peer]["prompt_tokens"] != right[peer]["prompt_tokens"]: + out["failures"].append({"request": right[peer]["request"], + "reason": "fresh and resumed prompt token counts differ"}) + + +def run_matrix(base, prompts, args, fresh_base=None): + """All exact cells on a cache-enabled base and a separate cache-disabled fresh reference.""" + out = {"results": {}, "comparisons": [], "failures": [], "rounds": []} + streams = sorted(set(args.streams)) + drafts = [False] if "draft" in args.skip else [False, True] + for sampling in args.sampling: + for stop in args.stops: + for draft in drafts: + for count in streams: + for item in prompts: + qualified = sampling == "greedy" and stop == "budget" and not draft and count == 1 + initial, repeated = ("cold", "warm") if qualified else ("first", "repeat") + initial_specs = [spec_for(item, args, sampling, stop, count, draft, initial, peer) + for peer in range(count)] + first = perform_round(out, base, initial_specs, args) + repeat_specs = [spec_for(item, args, sampling, stop, count, draft, repeated, peer) + for peer in range(count)] + repeat = perform_round(out, base, repeat_specs, args) + pair_phase(out, "cold_vs_warm" if qualified else "repeatability", first, repeat, range(count)) + if count != 1 or 0 not in first: + continue + reply = first[0]["token_ids"] if isinstance(item["prompt"], list) else first[0]["content"] + fresh_spec = spec_for(item, args, sampling, stop, 1, draft, "fresh", 0, True, reply) + resumed_spec = spec_for(item, args, sampling, stop, 1, draft, "resumed", 0, True, reply) + if fresh_base is None: + out["failures"].append({"request": fresh_spec["request"], + "reason": "cache-disabled fresh endpoint was not supplied"}) + continue + fresh = perform_round(out, fresh_base, [fresh_spec], args) + resumed = perform_round(out, base, [resumed_spec], args) + pair_phase(out, "fresh_vs_resumed", fresh, resumed, [0]) + if sampling == "seeded" and not draft and 0 in first: + other = spec_for(item, args, sampling, stop, 1, False, "seed-control", 0) + other["body"]["seed"] = args.seed + 1 + changed = perform_round(out, base, [other], args) + if 0 in changed and first[0]["token_ids"] == changed[0]["token_ids"]: + out["failures"].append({"request": other["request"], + "reason": "changed seed gave identical tokens; seed unproven"}) + add_cross_cell_comparisons(out) + cases = [{"prompt": p["name"], "recording_sha256": p["recording_sha256"], + "near_tie_offset": p["near_tie_offset"], "source_position": p.get("source_position")} for p in prompts] + out["coverage"] = {"streams": streams, "sampling": args.sampling, "stops": args.stops, "draft": drafts, + "phases": ["cold", "warm", "first", "repeat", "fresh", "resumed", "seed-control"], + "near_tie_cases": cases, "fresh_reference": "cache-disabled" if fresh_base else "missing"} + return out + + +def add_cross_cell_comparisons(out): + results = out["results"] + for key, value in list(results.items()): + if value["draft"]: + plain = key.replace("/draft/", "/plain/") + if plain in results: + out["comparisons"].append(comparison("drafted_vs_plain", value["prompt"], plain, results[plain], + key, value)) + if value["streams"] > 1: + solo = key.replace(f"/s{value['streams']}/", "/s1/").replace(f"/peer{value['peer']}", "/peer0") + if solo in results: + out["comparisons"].append(comparison("solo_vs_concurrent", value["prompt"], solo, results[solo], + key, value)) + + +def public_matrix(matrix): + """Drop raw token ids and reply text; retain only the public hashes and counted/timed metadata.""" + requests = {k: {key: v for key, v in value.items() if not key.startswith("_") and key != "content" + and key != "token_ids"} for k, value in matrix["results"].items()} + return {**{k: v for k, v in matrix.items() if k != "results"}, "requests": requests} + + +def binary_sha256(path): + digest = hashlib.sha256() + with open(path, "rb") as f: + for chunk in iter(lambda: f.read(1 << 20), b""): + digest.update(chunk) + return "sha256:" + digest.hexdigest() diff --git a/tools/exact_restarts.py b/tools/exact_restarts.py new file mode 100644 index 00000000000..5478b1349f0 --- /dev/null +++ b/tools/exact_restarts.py @@ -0,0 +1,351 @@ +"""Public exact receipts for restart, serial/tree, stream, sampling, stop and fresh/resumed conformance.""" + +import argparse +import json +import subprocess +import sys +import time +import urllib.error +import urllib.request +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path + +PROMPTS = Path(__file__).with_name("bench_prompts.json") +READY_S = 300 + + +class ServerFailed(Exception): + """The server did not come up: the harness refuses to compare anything.""" + + +def load_prompts(path=PROMPTS): + return [p for p in json.loads(path.read_text()) if isinstance(p.get("name"), str)] + + +def request_ids(base, item, tokens, api_key=None, timeout=600): + """One request's reply tokens: the ids under `tensorfold`, not the text.""" + body = {"model": "served", "max_tokens": tokens, "temperature": 0, "seed": 1, + "ignore_eos": True, "return_token_ids": True} + if item["kind"] == "chat": + url, body["messages"] = base + "/v1/chat/completions", [{"role": "user", "content": item["prompt"]}] + else: + url, body["prompt"] = base + "/v1/completions", item["prompt"] + req = urllib.request.Request(url, data=json.dumps(body).encode(), + headers={"Content-Type": "application/json"}) + if api_key: + req.add_header("Authorization", f"Bearer {api_key}") + with urllib.request.urlopen(req, timeout=timeout) as resp: + reply = json.load(resp) + ids = reply.get("tensorfold", {}).get("token_ids") + if not isinstance(ids, list): + raise RuntimeError(f"{item['name']}: reply carried no tensorfold.token_ids") + return ids + + +def collect(base, prompts, tokens, busy=0, api_key=None): + """Every prompt's ids; `busy` extra copies of each request in flight beside it, each checked.""" + out = {} + def one(item): + with ThreadPoolExecutor(max_workers=busy + 1) as pool: + runs = [pool.submit(request_ids, base, item, tokens, api_key) for _ in range(busy + 1)] + ids = [f.result() for f in runs] # a peer's error fails the run too + head = ids[0] + for peer in ids[1:]: + pos = first_diff(head, peer) + if pos is not None: + raise RuntimeError(f"{item['name']}: a busy peer's reply differed at token {pos}") + return head + for item in prompts: + out[item["name"]] = one(item) + return out + + +def first_diff(a, b): + for i, (x, y) in enumerate(zip(a, b)): + if x != y: + return i + return min(len(a), len(b)) if len(a) != len(b) else None + + +def compare(named, runs): + """`runs`: {label: {name: ids}} โ€” first-diff position per prompt per pair, plus flip counts.""" + labels = list(runs) + rows, flips = [], 0 + for name in named: + base = runs[labels[0]].get(name) + for label in labels[1:]: + pos = None if base is None else first_diff(base, runs[label].get(name, [])) + rows.append({"prompt": name, "pair": f"{labels[0]} vs {label}", "first_diff": pos}) + flips += pos is not None + return {"rows": rows, "flips": flips, "total": len(rows)} + + +class Server: + """A launched server: argv once per scenario, stopped by terminate.""" + + def __init__(self, argv, port): + self.argv, self.port, self.process = argv, port, None + + def __enter__(self): + self.process = subprocess.Popen(self.argv, stdout=subprocess.DEVNULL, + stderr=subprocess.PIPE, text=True) + deadline = time.monotonic() + READY_S + while time.monotonic() < deadline: + if self.process.poll() is not None: + tail = (self.process.stderr.read() or "")[-2000:] + raise ServerFailed(f"server exited {self.process.returncode}: {tail}") + try: + urllib.request.urlopen(f"http://127.0.0.1:{self.port}/v1/models", timeout=1).close() + return self + except (urllib.error.URLError, OSError): + time.sleep(0.25) + self.stop() + raise ServerFailed(f"server not ready within {READY_S}s") + + def __exit__(self, *exc): + self.stop() + return False + + def stop(self): + if self.process is not None and self.process.poll() is None: + self.process.terminate() + try: + self.process.wait(timeout=30) + except subprocess.TimeoutExpired: + self.process.kill() + self.process.wait() + if self.process is not None and self.process.stderr is not None: + self.process.stderr.close() + + +def serve_argv(bin_path, model, port, parallel=None, drafter=None, cache_disabled=False): + argv = [bin_path, "serve", model, "--host", "127.0.0.1", "--port", str(port)] + if parallel: + argv += ["--parallel", str(parallel)] + if drafter: + argv += ["--drafter", drafter] + if cache_disabled: + argv += ["--prompt-cache-gib", "0"] + return argv + + +def scenario(args, label, parallel=None, drafter=None, busy=0): + """One fresh server (or the --base one), all prompts collected once.""" + prompts = load_prompts(Path(args.prompts)) + base = args.base or f"http://127.0.0.1:{args.port}" + if args.base: + return {label: collect(base, prompts, args.tokens, busy, args.api_key)} + with Server(serve_argv(args.bin, args.model, args.port, parallel, drafter), args.port): + return {label: collect(base, prompts, args.tokens, busy, args.api_key)} + + +def empty_matrix(args): + return {"results": {}, "comparisons": [], "failures": [], "rounds": [], + "coverage": {"streams": sorted(set(args.streams)), "sampling": args.sampling, "stops": args.stops}} + + +def main(): + import exact_receipt as rc + + ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + ap.add_argument("--bin", default="zig-out/native/bin/tensorfold-native") + ap.add_argument("--candidate-bin", help="second binary: compare identical requests across binaries") + ap.add_argument("--model", help="served model directory (required without --base)") + ap.add_argument("--base", help="reuse this running server instead of launching (no restarts then)") + ap.add_argument("--drafter", help="draft model used by launched servers") + ap.add_argument("--fresh-base", help="attached cache-disabled endpoint for fresh follow-up references") + ap.add_argument("--port", type=int, default=8080) + ap.add_argument("--fresh-port", type=int, default=8081) + ap.add_argument("--tokens", type=int, default=64) + ap.add_argument("--eos-tokens", type=int, default=256, help="EOS cell budget; a length stop fails that cell") + ap.add_argument("--seed", type=int, default=7) + ap.add_argument("--streams", type=int, nargs="+", default=[1, 4, 8]) + ap.add_argument("--sampling", nargs="+", choices=["greedy", "seeded"], default=["greedy", "seeded"]) + ap.add_argument("--stops", nargs="+", choices=["budget", "eos"], default=["budget", "eos"]) + ap.add_argument("--prompts", help="qualified prompts from an earlier near-tie selection") + ap.add_argument("--recording", help="raw-logit recording; select near-tie token prefixes in this command") + ap.add_argument("--near-tie-cases", type=int, default=8) + ap.add_argument("--lookback", type=int, default=8) + ap.add_argument("--near-tie-tokens", type=int, default=32) + ap.add_argument("--api-key", default=None) + ap.add_argument("--timeout", type=int, default=600) + ap.add_argument("--output", default="exact-receipt.json") + ap.add_argument("--build-id", help="public attached-server build id; launched binaries default to their SHA-256") + ap.add_argument("--candidate-build-id", help="public candidate build id override") + ap.add_argument("--checkpoint-id", required=True, help="public checkpoint id, never a model path") + ap.add_argument("--checkpoint-sha256", required=True, help="public aggregate checkpoint content SHA-256") + ap.add_argument("--drafter-id", help="public draft checkpoint id") + ap.add_argument("--drafter-sha256", help="public aggregate draft checkpoint content SHA-256") + ap.add_argument("--family", required=True, help="public model family id") + ap.add_argument("--quant", required=True, help="public quantization id") + ap.add_argument("--skip", action="append", default=[], choices=["restart", "parallel", "busy", "draft"]) + args = ap.parse_args() + if not args.base and not args.model: + ap.error("--model is required without --base") + if args.base and not args.build_id: + ap.error("--build-id is required with --base") + if args.base and args.candidate_bin: + ap.error("--candidate-bin cannot be combined with --base") + if bool(args.prompts) == bool(args.recording): + ap.error("exactly one of --prompts and --recording is required") + if min(args.tokens, args.eos_tokens, args.timeout, args.near_tie_cases, args.near_tie_tokens, + *args.streams) <= 0 or args.lookback < 0: + ap.error("case/token budgets, timeout and stream counts must be positive; lookback nonnegative") + if not 1 <= args.port <= 65535 or not 1 <= args.fresh_port <= 65535 or args.port == args.fresh_port: + ap.error("base and fresh ports must be distinct valid TCP ports") + if "parallel" in args.skip or "busy" in args.skip: + args.streams = [1] + + def digest(value, field): + if len(value) != 64 or any(c not in "0123456789abcdef" for c in value): + ap.error(f"--{field} must be 64 lowercase hexadecimal characters") + + try: + for field in ("checkpoint", "family", "quant"): + rc.public_id(getattr(args, field + "_id") if field == "checkpoint" else getattr(args, field), field) + for field in ("build", "candidate-build", "drafter"): + value = getattr(args, field.replace("-", "_") + "_id") + if value: + rc.public_id(value, field) + except ValueError as e: + ap.error(str(e)) + digest(args.checkpoint_sha256, "checkpoint-sha256") + if bool(args.drafter_id) != bool(args.drafter_sha256): + ap.error("--drafter-id and --drafter-sha256 must be supplied together") + if args.drafter_sha256: + digest(args.drafter_sha256, "drafter-sha256") + + import hashlib + import draft_divergence as dd + + try: + if args.recording: + raw = Path(args.recording).read_bytes() + recording = json.loads(raw) + if not isinstance(recording, dict): + raise ValueError("recording must be a JSON object") + recording_sha = hashlib.sha256(raw).hexdigest() + if recording.get("identity", {}).get("checkpoint") not in (None, args.checkpoint_id): + ap.error("recording checkpoint identity differs from --checkpoint-id") + selected = dd.select_prompts(recording, args.near_tie_cases, args.lookback, args.near_tie_tokens) + prompts = [{"name": case["id"], "kind": "completion", "prompt": case["prompt"], + "expected_token_ids": case["tokens"], "near_tie_offset": case["near_tie_offset"], + "near_tie": case["top2"][case["near_tie_offset"]], "recording_sha256": recording_sha, + "source_position": case["source_position"], "recorded_margin": case["margin"], + "bf16_spacing": case["bf16_spacing"], "followup_token_ids": [case["tokens"][-1]]} + for case in selected] + else: + prompts = json.loads(Path(args.prompts).read_text()) + if not isinstance(prompts, list) or not prompts: + raise ValueError("the prompt set must be a nonempty array") + names = set() + for item in prompts: + if not isinstance(item, dict) or item.get("name") in names: + raise ValueError("every prompt needs a unique public name") + rc.public_id(item["name"], "prompt") + names.add(item["name"]) + if item.get("kind") not in ("chat", "completion"): + raise ValueError("each prompt needs kind chat/completion") + if not isinstance(item.get("prompt"), (str, list)) or not item["prompt"]: + raise ValueError("each prompt needs text or token IDs") + if isinstance(item["prompt"], list): + dd.ids(item["prompt"]) + item["followup_token_ids"] = item.get("followup_token_ids", [item["expected_token_ids"][-1]]) + dd.ids(item["followup_token_ids"]) + expected = dd.ids(item.get("expected_token_ids")) + offset = item.get("near_tie_offset") + if type(offset) is not int or not 0 <= offset < len(expected): + raise ValueError("invalid near-tie offset") + digest(item.get("recording_sha256", ""), "prompt recording_sha256") + tie = dd.top2(item.get("near_tie"), item["near_tie"].get("position", 0)) + if not dd.near(tie) or tie["ids"][0] != expected[offset]: + raise ValueError("near-tie evidence is not aligned with the expected greedy window") + except (ValueError, KeyError, IndexError, TypeError, json.JSONDecodeError) as e: + ap.error(f"invalid near-tie input: {e}") + + def execute(label, bin_path=None, focused=False): + run_args = args + if focused: + run_args = argparse.Namespace(**vars(args)) + run_args.streams, run_args.sampling, run_args.stops = [1], ["greedy"], ["budget"] + run_args.skip = [*args.skip, "draft"] + try: + if run_args.base: + return rc.run_matrix(run_args.base, prompts, run_args, run_args.fresh_base) + argv = serve_argv(bin_path, run_args.model, run_args.port, max(run_args.streams), run_args.drafter) + fresh_argv = serve_argv(bin_path, run_args.model, run_args.fresh_port, max(run_args.streams), + run_args.drafter, cache_disabled=True) + with Server(argv, run_args.port), Server(fresh_argv, run_args.fresh_port): + base = f"http://127.0.0.1:{run_args.port}" + fresh = f"http://127.0.0.1:{run_args.fresh_port}" + return rc.run_matrix(base, prompts, run_args, fresh) + except (ServerFailed, OSError): + matrix = empty_matrix(run_args) + matrix["failures"].append({"request": f"runtime:{label}", "reason": "server launch or readiness failed"}) + return matrix + + report = {"schema": 1, "status": "fail", "family": args.family, "quant": args.quant, + "checkpoint_id": args.checkpoint_id, "checkpoint_sha256": args.checkpoint_sha256, + "identity_source": "operator public IDs and content hashes; not server attested", + "token_hash_encoding": "sha256(compact JSON token ID array)", "builds": {}, "runs": {}, + "comparisons": [], "failures": [], "not_run": [], "flips": 0, "total": 0} + if args.drafter_id: + report["drafter"] = {"id": args.drafter_id, "sha256": args.drafter_sha256} + + def fold(label, matrix, internal=True): + report["runs"][label] = rc.public_matrix(matrix) + if internal: + report["comparisons"] += [{**r, "runtime": label} for r in matrix["comparisons"]] + report["failures"] += [{**r, "runtime": label} for r in matrix["failures"]] + + def build_identity(matrix, path, supplied): + if supplied: + return supplied + try: + return rc.binary_sha256(path) + except OSError: + if any(f["reason"] == "server launch or readiness failed" for f in matrix["failures"]): + return None + raise + + if args.base: + fold("attached", execute("attached")) + report["builds"]["attached"] = args.build_id + if "restart" not in args.skip: + report["not_run"].append("restart: attached server cannot be restarted") + else: + reference = execute("reference", args.bin) + fold("reference", reference) + report["builds"]["reference"] = build_identity(reference, args.bin, args.build_id) + if args.candidate_bin: + candidate = execute("candidate", args.candidate_bin) + fold("candidate", candidate) + report["builds"]["candidate"] = build_identity(candidate, args.candidate_bin, args.candidate_build_id) + report["comparisons"] += [{**r, "runtime": "reference_vs_candidate"} + for r in rc.compare_results(reference, candidate, "cross_binary")] + if "restart" not in args.skip: + restarted = execute("restart", args.bin, focused=True) + fold("restart", restarted, internal=False) + report["comparisons"] += [{**r, "runtime": "restart"} + for r in rc.compare_results(reference, restarted, "restart")] + + primary = "attached" if args.base else "reference" + report["coverage"] = report["runs"][primary]["coverage"] + + report["rows"] = report["comparisons"] + report["flips"] = sum(r["first_diff"] is not None for r in report["comparisons"]) + report["total"] = len(report["comparisons"]) + report["status"] = "pass" if report["total"] and not report["flips"] and not report["failures"] else "fail" + Path(args.output).write_text(json.dumps(report, indent=2, sort_keys=True) + "\n") + for row in report["comparisons"]: + mark = "identical" if row["first_diff"] is None else f"FLIP at {row['first_diff']}" + print(f"{row['kind']:24s} {row['candidate_request']} {mark}") + for failure in report["failures"]: + print(f"FAIL {failure['runtime']} {failure['request']}: {failure['reason']}") + tail = f"; not run: {report['not_run']}" if report["not_run"] else "" + print(f"receipt {report['status']}: flips {report['flips']}/{report['total']}{tail}") + return 0 if report["status"] == "pass" else 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/test_exact_receipt.py b/tools/test_exact_receipt.py new file mode 100644 index 00000000000..894654cc9cf --- /dev/null +++ b/tools/test_exact_receipt.py @@ -0,0 +1,321 @@ +"""The cross-backend exact receipt catches each planted divergence without recording private request data.""" +import contextlib +import io +import hashlib +import json +import sys +import tempfile +import threading +import time +import unittest +import urllib.request +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path +from unittest.mock import patch + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE)) +import exact_receipt as rc # noqa: E402 +import exact_restarts as er # noqa: E402 + +PROMPT = {"name": "near-tie", "kind": "chat", "prompt": "Choose one and explain.", + "followup": "Now give the other one.", "expected_token_ids": list(range(8)), + "near_tie_offset": 0, "recording_sha256": "a" * 64, + "near_tie": {"ids": [0, 1], "logits": [16.0, 15.9375], "position": 0}} + +TEXT_PROMPT = {"name": "text", "kind": "completion", "prompt": "Question?", "followup": "Continue.", + "expected_token_ids": list(range(8)), "near_tie_offset": 0, "recording_sha256": "a" * 64, + "near_tie": {"ids": [0, 1], "logits": [16.0, 15.9375], "position": 0}} +BASE = [11, 12, 13, 14, 15, 16] + + +def public(body, cached=0, ignore_seed=False): + sampled = body.get("temperature", 0) != 0 + budget = body.get("ignore_eos", False) + count = body["max_tokens"] if budget else min(4, body["max_tokens"]) + salt = 0 if ignore_seed else body.get("seed", 0) if sampled else 0 + ids = [(i + salt) % 97 for i in range(count)] + return {"ids": ids, "finish": "length" if budget else "stop", "cached": cached, + "text": "public reply"} + + +class Fake(ThreadingHTTPServer): + daemon_threads = True + + def __init__(self, fault=None, disabled=False): + super().__init__(("127.0.0.1", 0), Handler) + self.fault, self.active, self.seen, self.lock = fault, 0, {}, threading.Lock() + self.cache_disabled = disabled + self.requests = [] + @property + def url(self): + return f"http://127.0.0.1:{self.server_port}" + + +class Handler(BaseHTTPRequestHandler): + def log_message(self, *_): + pass + + def reply(self, status, value): + data = json.dumps(value).encode() + self.send_response(status) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(data))) + self.end_headers() + self.wfile.write(data) + + def do_GET(self): # noqa: N802 + self.reply(200, {"data": [{"id": "public-model"}]}) + + def do_POST(self): # noqa: N802 + body = json.loads(self.rfile.read(int(self.headers["Content-Length"]))) + server = self.server + server.requests.append(body) + messages = body.get("messages") or [] + key = json.dumps(messages, sort_keys=True) + with server.lock: + server.seen[key] = server.seen.get(key, 0) + 1 + arrival = server.seen[key] + server.active += 1 + time.sleep(0.005) + with server.lock: + concurrent = server.active > 1 + server.active -= 1 + if server.fault == "request_error" and body.get("draft") is False: + return self.reply(500, {"error": {"message": "private details never enter a receipt"}}) + prefix_seen = len(messages) > 1 and server.seen.get(json.dumps(messages[:1], sort_keys=True), 0) > 0 + out = public(body, 0 if server.cache_disabled else 9 if arrival > 1 or prefix_seen else 0, + server.fault == "seed_ignored") + ids = out["ids"][:] + if server.fault == "warm" and len(messages) <= 1 and arrival > 1: + ids[0] += 100 + if server.fault == "resumed" and len(messages) > 1: + ids[1] += 100 + if server.fault == "draft" and body.get("draft") is True: + ids[2] += 100 + if server.fault == "source" and not messages and body.get("draft") is False: + ids[0] += 100 + if server.fault == "concurrent" and concurrent: + ids[3] += 100 + if server.fault == "empty": + ids = [] + if server.fault == "cached" and out["cached"] > 0: + out["cached"] = 0 + if server.fault == "eos_finish" and not body.get("ignore_eos"): + out["finish"] = "length" + if server.fault == "budget_finish" and body.get("ignore_eos"): + out["finish"] = "stop" + drafted = 0 if server.fault == "no_draft" or (not body["draft"] and server.fault != "plain_drafts") else 3 + acknowledged = body["draft"] if server.fault != "bad_draft_ack" else not body["draft"] + choice = {"finish_reason": out["finish"]} + if messages: + choice["message"] = {"content": out["text"]} + else: + choice["text"] = out["text"] + response = {"choices": [choice], + "tensorfold": {"token_ids": ids, "drafts": acknowledged, "token_sha256": hashlib.sha256( + json.dumps(ids, separators=(",", ":")).encode()).hexdigest()}, + "speculative": {"drafted": drafted, "accepted": min(2, drafted)}, + "usage": {"prompt_tokens": 9, "completion_tokens": len(ids), + "prompt_tokens_details": {"cached_tokens": out["cached"]}}} + self.reply(200, response) + + +class Running: + def __init__(self, fault=None, disabled=False): + self.server = Fake(fault, disabled) + self.thread = threading.Thread(target=self.server.serve_forever, daemon=True) + + def __enter__(self): + self.thread.start() + return self.server.url + + def __exit__(self, *exc): + self.server.shutdown() + self.server.server_close() + self.thread.join() + + +def invoke(url, fresh, fault, tmp, full=False, stops=("budget",), item=PROMPT): + prompts = Path(tmp) / "prompts.json" + output = Path(tmp) / f"{fault}.json" + prompts.write_text(json.dumps([item])) + argv = ["exact_restarts.py", "--base", url, "--fresh-base", fresh, "--prompts", str(prompts), + "--output", str(output), "--build-id", "public-build", "--checkpoint-id", "public-checkpoint", + "--checkpoint-sha256", "b" * 64, "--family", "public-family", "--quant", "public-quant", + "--tokens", "8", "--eos-tokens", "8", "--skip", "restart"] + if not full: + argv += ["--streams", "1", "4", "--sampling", "greedy", "--stops", *stops] + with patch.object(sys, "argv", argv), contextlib.redirect_stdout(io.StringIO()): + code = er.main() + return code, json.loads(output.read_text()) + + +class ReceiptTests(unittest.TestCase): + def matrix(self, fault=None, full=False, stops=("budget",)): + with tempfile.TemporaryDirectory() as tmp, Running(fault) as url, Running(disabled=True) as fresh: + return invoke(url, fresh, fault or "clean", tmp, full, stops) + + def test_clean_receipt_covers_the_whole_matrix_and_has_no_private_data(self): + code, report = self.matrix(full=True) + self.assertEqual(code, 0, report["failures"]) + self.assertEqual(report["status"], "pass") + self.assertEqual(report["coverage"]["streams"], [1, 4, 8]) + self.assertEqual(report["coverage"]["sampling"], ["greedy", "seeded"]) + self.assertEqual(report["coverage"]["stops"], ["budget", "eos"]) + self.assertEqual(report["coverage"]["draft"], [False, True]) + self.assertTrue(report["runs"]["attached"]["rounds"]) + self.assertTrue(all(r["round_wall_seconds"] > 0 for r in report["runs"]["attached"]["rounds"])) + text = json.dumps(report) + for private in ("127.0.0.1", "http://", str(HERE), "public reply", "private details"): + self.assertNotIn(private, text) + kinds = {r["kind"] for r in report["comparisons"]} + self.assertTrue({"cold_vs_warm", "fresh_vs_resumed", "drafted_vs_plain", "solo_vs_concurrent"} <= kinds) + + def test_text_completion_followup_includes_the_first_reply(self): + base_runner, fresh_runner = Running(), Running(disabled=True) + with tempfile.TemporaryDirectory() as tmp, base_runner as url, fresh_runner as fresh: + code, report = invoke(url, fresh, "clean", tmp, item=TEXT_PROMPT) + requests = base_runner.server.requests + fresh_runner.server.requests + self.assertEqual(code, 0, report["failures"]) + followups = [body["prompt"] for body in requests if body.get("prompt", "").endswith("Continue.")] + self.assertEqual(followups, ["Question?\npublic reply\nContinue."] * 4) + + def test_warm_and_resumed_divergences_name_the_exact_requests(self): + for fault, kind in (("warm", "cold_vs_warm"), ("resumed", "fresh_vs_resumed")): + with self.subTest(fault=fault): + code, report = self.matrix(fault) + self.assertEqual(code, 1) + rows = [r for r in report["comparisons"] if r["kind"] == kind and r["first_diff"] is not None] + self.assertTrue(rows) + self.assertIn("near-tie", rows[0]["candidate_request"]) + + def test_draft_and_concurrent_divergences_fail(self): + for fault, kind in (("draft", "drafted_vs_plain"), ("concurrent", "solo_vs_concurrent")): + with self.subTest(fault=fault): + code, report = self.matrix(fault) + self.assertEqual(code, 1) + self.assertTrue(any(r["kind"] == kind and r["first_diff"] is not None + for r in report["comparisons"])) + + def test_cache_stop_empty_and_request_faults_fail_by_request(self): + cases = (("cached", "cache"), ("empty", "empty"), ("request_error", "HTTP 500")) + for fault, reason in cases: + with self.subTest(fault=fault): + code, report = self.matrix(fault) + self.assertEqual(code, 1) + self.assertTrue(any(reason in r["reason"] and "near-tie" in r["request"] + for r in report["failures"])) + for fault, stop in (("eos_finish", "eos"), ("budget_finish", "budget")): + with self.subTest(fault=fault): + code, report = self.matrix(fault, stops=(stop,)) + self.assertEqual(code, 1) + self.assertTrue(any("finish" in r["reason"] for r in report["failures"])) + + def test_drafting_that_never_ran_is_not_a_pass(self): + code, report = self.matrix("no_draft") + self.assertEqual(code, 1) + self.assertTrue(any("drafting was not observed" in r["reason"] for r in report["failures"])) + + def recording(self, fault=None): + rows = [{"ids": [i, 99], "logits": [16.0, 15.9375] if i == 0 else [10.0, 0.0], + "position": i + 2} for i in range(8)] + recording = {"schema": 1, "identity": {"checkpoint": "public-checkpoint"}, + "traces": [{"name": "raw", "prompt": [1, 2], "tokens": list(range(8)), "top2": rows}]} + with tempfile.TemporaryDirectory() as tmp, Running(fault) as url, Running(disabled=True) as fresh: + source, output = Path(tmp) / "recording.json", Path(tmp) / "report.json" + source.write_text(json.dumps(recording)) + argv = ["exact_restarts.py", "--base", url, "--fresh-base", fresh, "--recording", str(source), + "--output", str(output), "--build-id", "public-build", "--checkpoint-id", "public-checkpoint", + "--checkpoint-sha256", "b" * 64, "--family", "public-family", "--quant", "public-quant", + "--streams", "1", "--sampling", "greedy", "--stops", "budget", "--near-tie-cases", "1", + "--lookback", "0", "--near-tie-tokens", "8", "--skip", "restart", "--skip", "draft"] + with patch.object(sys, "argv", argv), contextlib.redirect_stdout(io.StringIO()): + code = er.main() + return code, json.loads(output.read_text()) + + def test_raw_recording_selection_and_source_reproduction_gate(self): + code, report = self.recording() + self.assertEqual(code, 0, report["failures"]) + self.assertEqual(report["coverage"]["near_tie_cases"][0]["prompt"], "raw:0") + self.assertTrue(all("token_ids" not in row for row in report["runs"]["attached"]["requests"].values())) + code, report = self.recording("source") + self.assertEqual(code, 1) + self.assertTrue(any("recorded greedy window" in r["reason"] for r in report["failures"])) + + def test_acknowledgement_plain_drafting_and_ignored_seed_faults(self): + for fault, reason in (("bad_draft_ack", "acknowledge"), ("plain_drafts", "plain request")): + with self.subTest(fault=fault): + code, report = self.matrix(fault) + self.assertEqual(code, 1) + self.assertTrue(any(reason in r["reason"] for r in report["failures"])) + code, report = self.matrix("seed_ignored", full=True) + self.assertEqual(code, 1) + self.assertTrue(any("changed seed" in r["reason"] for r in report["failures"])) + + def test_pair_of_binaries_produces_cross_binary_receipt_without_paths(self): + base_runner, fresh_runner = Running(), Running(disabled=True) + with tempfile.TemporaryDirectory() as tmp, base_runner as base_url, fresh_runner as fresh_url: + one, two = Path(tmp) / "one.bin", Path(tmp) / "two.bin" + one.write_bytes(b"one") + two.write_bytes(b"two") + prompts, output = Path(tmp) / "prompts.json", Path(tmp) / "report.json" + prompts.write_text(json.dumps([PROMPT])) + calls = [] + + class Launched: + def __init__(self, argv, port): + calls.append(argv) + self.port = port + + def __enter__(self): + base_runner.server.seen.clear() + fresh_runner.server.seen.clear() + return self + + def __exit__(self, *exc): + return False + + argv = ["exact_restarts.py", "--bin", str(one), "--candidate-bin", str(two), "--model", "public-model", + "--port", str(base_runner.server.server_port), "--fresh-port", + str(fresh_runner.server.server_port), + "--prompts", str(prompts), "--output", str(output), "--checkpoint-id", "public-checkpoint", + "--checkpoint-sha256", "b" * 64, "--family", "public-family", "--quant", "public-quant", + "--streams", "1", "--sampling", "greedy", "--stops", "budget", "--skip", "restart", + "--skip", "draft"] + with patch.object(er, "Server", Launched), patch.object(sys, "argv", argv), \ + contextlib.redirect_stdout(io.StringIO()): + code = er.main() + report_text = output.read_text() + report = json.loads(report_text) + self.assertEqual(code, 0, report["failures"]) + self.assertEqual(set(report["builds"]), {"reference", "candidate"}) + self.assertNotEqual(report["builds"]["reference"], report["builds"]["candidate"]) + self.assertTrue(any(r["kind"] == "cross_binary" for r in report["comparisons"])) + self.assertEqual(sum("--prompt-cache-gib" in argv for argv in calls), 2) + self.assertNotIn(str(tmp), report_text) + + def test_cross_binary_greedy_seeded_eos_and_budget_flips_are_found(self): + for sampling in ("greedy", "seeded"): + for stop in ("budget", "eos"): + with self.subTest(sampling=sampling, stop=stop): + req = f"near-tie/{sampling}/{stop}/s1/plain/cold/peer0" + result = rc.result(req, PROMPT, sampling, stop, 1, False, "cold", 0, + BASE, 0, "length" if stop == "budget" else "stop", 0.1, 0.1, 0, 0) + other = dict(result, token_ids=BASE[:2] + [999] + BASE[3:]) + other["token_ids_json_sha256"] = rc.token_sha256(other["token_ids"]) + rows = rc.compare_results({req: result}, {req: other}, "binary") + self.assertEqual(rows[0]["first_diff"], 2) + self.assertEqual(rows[0]["candidate_request"], req) + + def test_identity_and_hash_rules(self): + self.assertEqual(rc.token_sha256([1, 2, 3]), hashlib.sha256(b"[1,2,3]").hexdigest()) + for value in ("public-build", "sha256:abc123", "Qwen3.8-27B_Q4"): + self.assertEqual(rc.public_id(value, "build"), value) + for value in ("root/private/model", "host/name", "user@example.com", "white space", "~model"): + with self.subTest(value=value), self.assertRaises(ValueError): + rc.public_id(value, "checkpoint") + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/test_exact_restarts.py b/tools/test_exact_restarts.py new file mode 100644 index 00000000000..3c543fe79c5 --- /dev/null +++ b/tools/test_exact_restarts.py @@ -0,0 +1,172 @@ +"""tools/exact_restarts.py low-level checks against a stub server scripting its own token_ids.""" +import contextlib +import hashlib +import io +import json +import sys +import tempfile +import threading +import urllib.error +import unittest +from http.server import BaseHTTPRequestHandler, HTTPServer +from pathlib import Path +from unittest.mock import patch + +sys.path.insert(0, str(Path(__file__).parent)) +import exact_restarts as er # noqa: E402 + +BASE_IDS = list(range(100, 116)) +FAILING_BINARY = b"#!/bin/sh\nexit 1\n" +PROMPT = {"name": "p", "kind": "completion", "prompt": "x"} +RECEIPT_PROMPT = {"name": "near-tie", "kind": "chat", "prompt": "Choose one and explain.", + "followup": "Now give the other one.", "expected_token_ids": list(range(8)), + "near_tie_offset": 0, "recording_sha256": "a" * 64, + "near_tie": {"ids": [0, 1], "logits": [16.0, 15.9375], "position": 0}} + + +class Stub(BaseHTTPRequestHandler): + ids = [] + + def do_POST(self): # noqa: N802 (the library's name) + self.rfile.read(int(self.headers["Content-Length"])) + data = json.dumps({"tensorfold": {"token_ids": Stub.ids}}).encode() + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.end_headers() + self.wfile.write(data) + + def do_GET(self): # noqa: N802 + self.send_response(200) + self.end_headers() + + def log_message(self, *a): + pass + + +class ExactRestartTests(unittest.TestCase): + def setUp(self): + self.httpd = HTTPServer(("127.0.0.1", 0), Stub) + self.thread = threading.Thread(target=self.httpd.serve_forever, daemon=True) + self.thread.start() + self.base = f"http://127.0.0.1:{self.httpd.server_port}" + + def tearDown(self): + self.httpd.shutdown() + self.httpd.server_close() + self.thread.join() + + def collect(self): + return er.collect(self.base, [PROMPT], 16) + + def test_identical_runs_report_no_flip(self): + Stub.ids = BASE_IDS + runs = {"a": self.collect(), "b": self.collect()} + part = er.compare(["p"], runs) + self.assertEqual(part["flips"], 0) + self.assertIsNone(part["rows"][0]["first_diff"]) + + def test_one_token_flip_is_found_at_its_position(self): + for pos in (0, 7, 15): + with self.subTest(pos=pos): + Stub.ids = BASE_IDS + first = self.collect() + flipped = BASE_IDS.copy() + flipped[pos] += 1000 + Stub.ids = flipped + part = er.compare(["p"], {"a": first, "b": self.collect()}) + self.assertEqual(part["flips"], 1) + self.assertEqual(part["rows"][0]["first_diff"], pos) + + def test_shorter_run_flips_at_the_first_missing_position(self): + Stub.ids = BASE_IDS + first = self.collect() + Stub.ids = BASE_IDS[:9] + part = er.compare(["p"], {"a": first, "b": self.collect()}) + self.assertEqual(part["rows"][0]["first_diff"], 9) + + def test_server_that_fails_to_start_is_named(self): + bad = er.Server([sys.executable, "-c", "import sys; sys.exit(3)"], port=1) + with self.assertRaisesRegex(er.ServerFailed, "exited 3"): + bad.__enter__() + bad.stop() + + def test_request_ids_reads_the_tensorfold_block(self): + Stub.ids = BASE_IDS[:4] + self.assertEqual(er.request_ids(self.base, PROMPT, 4), BASE_IDS[:4]) + + def test_a_busy_peer_error_fails_the_run(self): + calls = [] + + def fake(base, item, tokens, api_key=None, timeout=600): + calls.append(1) + if len(calls) > 1: + raise urllib.error.HTTPError(base, 500, "peer failed", {}, None) + return BASE_IDS + + with patch.object(er, "request_ids", fake): + with self.assertRaisesRegex(urllib.error.HTTPError, "peer failed"): + er.collect("http://127.0.0.1:1", [PROMPT], 16, busy=3) + + def test_a_busy_peer_with_different_tokens_fails_the_run(self): + calls = [] + + def fake(base, item, tokens, api_key=None, timeout=600): + calls.append(1) + return BASE_IDS if len(calls) == 1 else BASE_IDS[:3] + [999] + BASE_IDS[4:] + + with patch.object(er, "request_ids", fake): + with self.assertRaisesRegex(RuntimeError, "busy peer"): + er.collect("http://127.0.0.1:1", [PROMPT], 16, busy=3) + + def test_fresh_server_disables_prompt_cache(self): + argv = er.serve_argv("binary", "model", 8081, 8, "draft", cache_disabled=True) + self.assertEqual(argv[-2:], ["--prompt-cache-gib", "0"]) + self.assertIn("--parallel", argv) + self.assertIn("--drafter", argv) + + def launch_failure_receipt(self, candidate=False, existing=False): + with tempfile.TemporaryDirectory() as tmp: + missing = Path(tmp) / "reference.bin" + prompts, output = Path(tmp) / "prompts.json", Path(tmp) / "report.json" + if existing: + missing.write_bytes(FAILING_BINARY) + missing.chmod(0o755) + prompts.write_text(json.dumps([RECEIPT_PROMPT])) + argv = ["exact_restarts.py", "--bin", str(missing), "--model", "public-model", + "--prompts", str(prompts), "--output", str(output), + "--checkpoint-id", "public-checkpoint", "--checkpoint-sha256", "b" * 64, + "--family", "public-family", "--quant", "public-quant", "--streams", "1", + "--sampling", "greedy", "--stops", "budget", "--skip", "restart", "--skip", "draft"] + if candidate: + argv += ["--candidate-bin", str(Path(tmp) / "missing-candidate.bin"), + "--build-id", "public-reference"] + with patch.object(sys, "argv", argv), contextlib.redirect_stdout(io.StringIO()): + code = er.main() + return code, json.loads(output.read_text()) + + def test_missing_reference_binary_writes_failure_receipt(self): + code, report = self.launch_failure_receipt() + self.assertEqual(code, 1) + self.assertEqual(report["status"], "fail") + self.assertEqual(report["builds"], {"reference": None}) + self.assertEqual(report["failures"], [{"request": "runtime:reference", "runtime": "reference", + "reason": "server launch or readiness failed"}]) + + def test_missing_candidate_binary_writes_failure_receipt(self): + code, report = self.launch_failure_receipt(candidate=True) + self.assertEqual(code, 1) + self.assertEqual(report["status"], "fail") + self.assertEqual(report["builds"], {"reference": "public-reference", "candidate": None}) + self.assertIn({"request": "runtime:candidate", "runtime": "candidate", + "reason": "server launch or readiness failed"}, report["failures"]) + + def test_existing_binary_launch_failure_keeps_its_hash(self): + code, report = self.launch_failure_receipt(existing=True) + self.assertEqual(code, 1) + self.assertEqual(report["status"], "fail") + expected = "sha256:" + hashlib.sha256(FAILING_BINARY).hexdigest() + self.assertEqual(report["builds"], {"reference": expected}) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/zig/drama3_compact_gb10.sh b/tools/zig/drama3_compact_gb10.sh index 2f63e445e01..c8a5ff72d0f 100755 --- a/tools/zig/drama3_compact_gb10.sh +++ b/tools/zig/drama3_compact_gb10.sh @@ -25,12 +25,34 @@ run() { # TREE MODEL NAME [ARGS...]: greedy codes into NAME.codes, stderr into N run "$main_tree" "$fp8" fp8-main run "$root" "$fp8" fp8-head cmp "$out/fp8-main.codes" "$out/fp8-head.codes" -run "$root" "$compact" compact --codec "$codec" --replay 1 +# --replay 1 gates frames, graph, poison/reset and chunk 1 vs 1; main's CUDA codec may differ at chunk 4 or 16 (below) +replay() { # NAME [ARGS...]: exact checks pass; codec PCM differences stay within replay.zig's bound + name=$1 + shift + run "$root" "$compact" "$name" --codec "$codec" --replay 1 "$@" && return + "$root/tools/zig/drama3_replay_gate.sh" "$out/$name.log" +} +replay compact-replay # a pruned checkpoint compacts only the layers that dropped experts: NVFP4 in all 40 and at least one compact router -grep -q 'routed experts NVFP4 in 40 of 40 layers; compact routers in [1-9][0-9]* of 40 layers' "$out/compact.log" +grep -q 'routed experts NVFP4 in 40 of 40 layers; compact routers in [1-9][0-9]* of 40 layers' "$out/compact-replay.log" +replay compact-batched-replay --max-rows 64 +# the codec chunk never changes the frames; the PCM it changes is information, in 16-bit steps against chunk 1 +for chunk in 1 4 16; do + run "$root" "$compact" "compact-$chunk" --codec "$codec" --first-chunk "$chunk" --chunk "$chunk" --pcm-out "$out/compact-$chunk.pcm" + cmp "$out/compact-1.codes" "$out/compact-$chunk.codes" +done +for chunk in 4 16; do # one command each, so a missing or short PCM stops the run under set -e + python3 - "$out/compact-1.pcm" "$out/compact-$chunk.pcm" >"$out/pcm-$chunk.txt" <<'EOF' +import array, math, sys +a, b = (array.array('h', open(p, 'rb').read()) for p in sys.argv[1:]) +assert len(a) == len(b), (len(a), len(b)) +d = [x - y for x, y in zip(a, b)] +print(f'max abs {max(map(abs, d))}, RMS {math.sqrt(sum(x * x for x in d) / len(d)):.4f} over {len(d)} samples') +EOF +done # batched prefill is gated within its own capacity: cross-capacity frames may differ near a tie (docs/drama3-prefill.md) -run "$root" "$compact" compact-batched --codec "$codec" --max-rows 64 --replay 1 -cmp -s "$out/compact.codes" "$out/compact-batched.codes" && capacity=equal || capacity=differ +run "$root" "$compact" compact-batched --codec "$codec" --max-rows 64 +cmp -s "$out/compact-1.codes" "$out/compact-batched.codes" && capacity=equal || capacity=differ # gates 1-4 and the unmasked control; the word matches no limits record, so the pending one waits for the audit below "$root/zig-out/bin/tf-cuda-test" kernel-contract 'compact router' >"$out/contract.log" 2>&1 status=0 @@ -42,9 +64,11 @@ status=0 "$nvcc" --version | tail -n 1 for f in "$fp8" "$compact" "$codec"; do echo "input $f: $(find "$f" -name '*.safetensors' -o -name '*.pth' | sort | xargs cat | sha256sum | cut -d' ' -f1)"; done echo "PASS fp8 greedy codes byte-identical to $base: $(sha256sum "$out/fp8-head.codes" | cut -d' ' -f1)" - echo "PASS compact $(grep -o 'routed experts held.*' "$out/compact.log")" - echo "PASS compact decode and replay: $(tail -n 1 "$out/compact.log")" - echo "PASS compact batched prefill (64 rows) decode and replay: $(tail -n 1 "$out/compact-batched.log")" + echo "PASS compact $(grep -o 'routed experts held.*' "$out/compact-replay.log")" + echo "PASS compact replay exact through PCM chunk 1 vs 1, then: $(tail -n 1 "$out/compact-replay.log")" + echo "PASS compact batched prefill (64 rows) replay exact through PCM chunk 1 vs 1, then: $(tail -n 1 "$out/compact-batched-replay.log")" + echo "PASS compact decode at codec chunk 1, frames byte-identical at chunks 4 and 16: $(tail -n 1 "$out/compact-1.log")" + for chunk in 4 16; do echo "INFO compact PCM at codec chunk $chunk against 1, 16-bit steps: $(cat "$out/pcm-$chunk.txt")"; done echo "INFO compact codes at 1 and 64 prompt rows $capacity" grep '^(filtered) SUMMARY' "$out/contract.log" grep '^RECORD drama3 d3_router_compact:' "$out/limits.log" diff --git a/tools/zig/drama3_replay_gate.sh b/tools/zig/drama3_replay_gate.sh new file mode 100755 index 00000000000..3f6ecaf5168 --- /dev/null +++ b/tools/zig/drama3_replay_gate.sh @@ -0,0 +1,11 @@ +#!/bin/sh +# Accept replay.zig's bounded PCM-only outcome after checking every chunk line. +log=$1 +tail -n 1 "$log" | grep -qx 'error: ReplayPcmOnly' || exit 1 +awk -v step=3.052e-5 ' + /^Drama replay PCM only/ { + n = "[0-9]\\.[0-9][0-9][0-9]e-?[0-9]+" + if ($0 !~ "^Drama replay PCM only: codec chunk (4|16) against 1, max abs " n ", RMS " n "; every exact check passed$" || $12 + 0 > step) bad = 1 + lines++ + } + END { exit bad || !lines }' "$log" diff --git a/tools/zig/drama3_replay_gate_test.py b/tools/zig/drama3_replay_gate_test.py new file mode 100644 index 00000000000..93016e83be1 --- /dev/null +++ b/tools/zig/drama3_replay_gate_test.py @@ -0,0 +1,85 @@ +"""drama3_replay_gate.sh: only replay.zig's PCM-only outcome, after every exact check, passes; any other stop fails.""" +import subprocess +import tempfile +import unittest +from pathlib import Path + +GATE = Path(__file__).resolve().parents[2] / "tools/zig/drama3_replay_gate.sh" +SIZES = {1: "{ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }", 4: "{ 4, 4, 4, 4, 1 }", 16: "{ 16, 1 }"} +EVERY_DECODE = (1, 1, 4, 16, 1) + + +def pcm_only(chunk: int, max_abs: str = "3.052e-5") -> str: + return (f"Drama replay PCM only: codec chunk {chunk} against 1, max abs {max_abs}, RMS 4.317e-6; " + "every exact check passed") + + +def log(*chunks: int, last: str = "error: ReplayMismatch", info: tuple[str, ...] = ()) -> list[str]: + """replay.zig's report: one codec line per decode reached, any outcome lines, then the run's last line.""" + return [f"codec requested {c}, actual sizes {SIZES[c]}" for c in chunks] + list(info) + [last] + + +def gate(lines: list[str]) -> int: + with tempfile.NamedTemporaryFile("w", suffix=".log") as f: + f.write("\n".join(lines) + "\n") + f.flush() + return subprocess.run(["sh", str(GATE), f.name]).returncode + + +class ReplayGateTests(unittest.TestCase): + def test_chunk_4_pcm_only_passes(self): + self.assertEqual(gate(log(*EVERY_DECODE, last="error: ReplayPcmOnly", info=(pcm_only(4),))), 0) + + def test_chunk_16_pcm_only_passes(self): + self.assertEqual(gate(log(*EVERY_DECODE, last="error: ReplayPcmOnly", info=(pcm_only(16),))), 0) + + def test_chunk_4_and_16_pcm_only_passes(self): + self.assertEqual(gate(log(*EVERY_DECODE, last="error: ReplayPcmOnly", info=(pcm_only(4), pcm_only(16)))), 0) + + def test_fork_frame_mismatch_after_chunk_16_fails(self): + """Igor's fixture on #4463: PCM differed at chunk 4/16, then a forked frame differed (replay.zig frame loop).""" + self.assertNotEqual(gate(log(1, 1, 4, 16)), 0) + + def test_frame_mismatch_fails(self): + self.assertNotEqual(gate(log(1)), 0) + + def test_chunk_1_pcm_mismatch_fails(self): + self.assertNotEqual(gate(log(1, 1)), 0) + + def test_fork_lane_pcm_mismatch_fails(self): + self.assertNotEqual(gate(log(*EVERY_DECODE)), 0) + + def test_pcm_only_error_without_its_line_fails(self): + self.assertNotEqual(gate(log(*EVERY_DECODE, last="error: ReplayPcmOnly")), 0) + + def test_pcm_only_line_before_another_error_fails(self): + self.assertNotEqual(gate(log(*EVERY_DECODE, last="error: BadCodecChunk", info=(pcm_only(4),))), 0) + + def test_chunk_1_pcm_only_line_fails(self): + self.assertNotEqual(gate(log(*EVERY_DECODE, last="error: ReplayPcmOnly", info=(pcm_only(1),))), 0) + + def test_malformed_pcm_only_line_fails(self): + for line in (pcm_only(4).replace(", RMS 4.317e-6", ""), pcm_only(4).replace("max abs 3.052e-5", "max abs x"), + pcm_only(4) + " extra"): + with self.subTest(line=line): + self.assertNotEqual(gate(log(*EVERY_DECODE, last="error: ReplayPcmOnly", info=(line,))), 0) + + def test_pcm_past_reported_bound_fails(self): + for max_abs in ("3.053e-5", "2.500e-1", "1.000e0", "1.200e3"): + with self.subTest(max_abs=max_abs): + self.assertNotEqual(gate(log(*EVERY_DECODE, last="error: ReplayPcmOnly", info=(pcm_only(16, max_abs),))), 0) + + def test_bad_chunk_4_before_a_bounded_chunk_16_fails(self): + """Ash's case on #4463: the last PCM line is in bounds, the one before it is not.""" + for max_abs in ("nan", "inf", "2.500e-1"): + with self.subTest(max_abs=max_abs): + lines = log(*EVERY_DECODE, last="error: ReplayPcmOnly", info=(pcm_only(4, max_abs), pcm_only(16))) + self.assertNotEqual(gate(lines), 0) + + def test_nonfinite_rms_fails(self): + lines = log(*EVERY_DECODE, last="error: ReplayPcmOnly", info=(pcm_only(4).replace("RMS 4.317e-6", "RMS nan"), pcm_only(16))) + self.assertNotEqual(gate(lines), 0) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/zig/drama_guidance_check.py b/tools/zig/drama_guidance_check.py index 4d106c94cb1..73672bff1a8 100644 --- a/tools/zig/drama_guidance_check.py +++ b/tools/zig/drama_guidance_check.py @@ -3,6 +3,7 @@ import json import os from pathlib import Path +import re import sys from drama_reference_cache_check import TEXTS, serve @@ -12,13 +13,15 @@ MODES = {"plain": [], "separate": CFG, "paired": [*CFG, "--cfg-batched"]} # One row a chunk, and chunks longer than a reference so a voice's later requests resume its cached reference. ROWS = (1, 64) +# The concurrent lanes: text index and gamma each. +LANES = {"lane-a": (3, "3"), "lane-b": (4, "1.5")} def plan(voice): - """(step, voice, text, headers) per fixed text and gamma, then two guided lanes at once.""" + """(step, voice, text, headers) per fixed text and gamma, each lane alone, then the lanes at once.""" steps = [(f"t{t}-g{g}", voice, TEXTS[t], {"X-Cfg-Gamma": g}) for t in range(3) for g in GAMMAS] - return [*steps, [("lane-a", voice, TEXTS[3], {"X-Cfg-Gamma": "3"}), - ("lane-b", voice, TEXTS[4], {"X-Cfg-Gamma": "1.5"})]] + lanes = [(name, voice, TEXTS[t], {"X-Cfg-Gamma": g}) for name, (t, g) in LANES.items()] + return [*steps, *[(f"solo-{name}", *rest) for name, *rest in lanes], lanes] def require_reference(voices, voice): @@ -28,8 +31,16 @@ def require_reference(voices, voice): raise SystemExit(f"--voice {voice!r} must name a catalog voice with a reference in {voices}") +def revision(value): + """REPO@COMMIT: the checkpoint's Hugging Face commit as the hub API reports it, never a branch such as main.""" + repo, _, commit = value.rpartition("@") + if not repo or not re.fullmatch(r"[0-9a-f]{40}", commit): + raise argparse.ArgumentTypeError(f"{value!r} is not REPO@COMMIT with the full 40-hex commit sha") + return {"repo": repo, "commit": commit} + + def verdict(runs): - """Per prefill size: PCM everywhere, paired equals separate, gamma 1 is plain, gamma above 1 differs, cache hit.""" + """Per prefill size: PCM, paired equals separate, gamma 1 is plain, above 1 differs, lanes equal solo, cache hit.""" problems = [] for rows, modes in runs.items(): separate, paired, plain = modes["separate"], modes["paired"], modes["plain"] @@ -49,6 +60,9 @@ def verdict(runs): if guided[mixed]["sha256"] == guided[name]["sha256"]: problems.append(f"rows={rows} {mixed}: {mode} PCM equals gamma 1, so guidance changed nothing") for mode in ("separate", "paired"): + guided = modes[mode]["replies"] + problems += [f"rows={rows} {name}: {mode} concurrent PCM differs from its solo run" for name in LANES + if guided[name]["sha256"] != guided[f"solo-{name}"]["sha256"]] if modes[mode]["cache_hits"] == 0: problems.append(f"rows={rows}: {mode} never resumed a cached reference") return problems @@ -63,6 +77,8 @@ def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--bin", type=Path, required=True, help="tensorfold-native built with this change (CUDA)") parser.add_argument("--checkpoint", type=Path, required=True, help="fishaudio/drama-3 checkpoint directory") + parser.add_argument("--revision", type=revision, required=True, + help="REPO@COMMIT the checkpoint was downloaded at, e.g. fishaudio/drama-3@<40-hex sha>") parser.add_argument("--voices", type=Path, required=True, help="voice catalog directory for --voices") parser.add_argument("--voice", required=True, help="a catalog voice in --voices whose reference has over 64 rows") parser.add_argument("--out", type=Path, required=True, help="new directory for server logs and results.json") @@ -80,7 +96,8 @@ def main(): runs[rows] = {mode: run_mode(args, env, flags, args.out / f"server-rows{rows}-{mode}.log", plain if mode == "plain" else steps) for mode, flags in MODES.items()} problems = verdict(runs) - result = {"pass": not problems, "problems": problems, "runs": runs} + result = {"pass": not problems, "problems": problems, + "checkpoint": {"path": str(args.checkpoint), **args.revision}, "runs": runs} (args.out / "results.json").write_text(json.dumps(result, indent=2) + "\n") print(json.dumps({"pass": result["pass"], "problems": problems}, indent=2)) return 0 if not problems else 1 diff --git a/tools/zig/inkling2_fixtures.py b/tools/zig/inkling2_fixtures.py index 21af5106f97..ac0465d7e4a 100644 --- a/tools/zig/inkling2_fixtures.py +++ b/tools/zig/inkling2_fixtures.py @@ -1,4 +1,4 @@ -"""Rebuild zig/src/families/inkling2/fixtures from the Inkling 2 Small release and tiny-random/inkling-2.""" +"""Rebuild zig/src/families/inkling2/fixtures from the Small, tiny-random and Mini checkpoint inputs.""" import argparse import hashlib import json @@ -10,6 +10,19 @@ FIXTURES = ROOT / "zig/src/families/inkling2/fixtures" RELEASE = "thinkingmachines/Inkling-2-Small@2ad1157016e1aac77b6ff1b770e7c05229403134" TINY = "tiny-random/inkling-2@0a57c72e4e5b68aafe1d983dbb62980344a5fcd7" +MINI_RELEASE = "thinkingmachines/Inkling-2-Mini" +MINI_REVISION = "ed40e7da625f594fc9c4990f5f66be24873c22d7" +MINI_PROVENANCE = { + "release": MINI_RELEASE, + "revision": MINI_REVISION, + "revision_status": "full revision supplied separately; every checkpoint config field matches", + "published": "2026-11-20", + "license": "apache-2.0", +} +MINI_HEADER_PROVENANCE = ( + f"release={MINI_RELEASE} revision={MINI_REVISION} " + "published=2026-11-20 license=apache-2.0" +) PINS = {"transformers": "5.20.0", "tokenizers": "0.23.3", "jinja2": "3.1.6"} MERGES = 1500 @@ -46,13 +59,35 @@ def dump(value, depth=0): def read_header(path): - """The tensors of a safetensors file as {name: (dtype tag, shape)}, read from its first bytes only.""" - with open(path, "rb") as f: - (length,) = struct.unpack("> shifts) & np.uint32((1 << bits) - 1) + values = values.reshape(*q.shape[:-1], -1).astype(F) + grouped = values.reshape(*values.shape[:-1], -1, group) + return (grouped * s[..., None] + b[..., None]).reshape(values.shape) + + +class Model: + def __init__(self, ckpt: Checkpoint): + c = ckpt.config + self.ck = ckpt + self.layers = c["num_hidden_layers"] + self.hidden = c["hidden_size"] + self.vocab = c["vocab_size"] + self.eps = c["rms_norm_eps"] + self.types = c["layer_types"] + self.k_heads, self.v_heads = c["linear_num_key_heads"], c["linear_num_value_heads"] + self.k_dim, self.v_dim = c["linear_key_head_dim"], c["linear_value_head_dim"] + self.heads, self.kv_heads, self.head_dim = c["num_attention_heads"], c["num_key_value_heads"], c["head_dim"] + rope = c["rope_parameters"] + self.rotary = int(self.head_dim * rope["partial_rotary_factor"]) + self.theta = float(rope["rope_theta"]) + self.experts, self.top_k = c["num_experts"], c["num_experts_per_tok"] + + def p(self, layer, rest): + return f"{self.ck.prefix}layers.{layer}.{rest}" + + def embed(self, ids): + return self.ck.dense(self.ck.prefix + "embed_tokens", rows=mx.array(np.asarray(ids, np.int32))) + + def mixer(self, layer, xs, positions): + """xs: the stream rows of one or more independent runs, each [T, hidden]; returns their mixer outputs.""" + norm = self.ck.vector(self.p(layer, "input_layernorm.weight")) + normed = [rms(x, norm, self.eps) for x in xs] + if self.types[layer] == "linear_attention": + return self.gdn(layer, normed) + return self.attention(layer, normed, positions) + + def gdn(self, layer, xs): + m = lambda n: self.ck.dense(self.p(layer, f"linear_attn.{n}")) + wqkv, wz, wa, wb, wo = m("in_proj_qkv"), m("in_proj_z"), m("in_proj_a"), m("in_proj_b"), m("out_proj") + conv = self.ck.vector(self.p(layer, "linear_attn.conv1d.weight"))[:, :, 0] # [channels, kernel] + a_log = self.ck.vector(self.p(layer, "linear_attn.A_log")) + dt_bias = self.ck.vector(self.p(layer, "linear_attn.dt_bias")) + gain = self.ck.vector(self.p(layer, "linear_attn.norm.weight")) + kd, vd, hk, hv = self.k_dim, self.v_dim, self.k_heads, self.v_heads + key = kd * hk + out = [] + for x in xs: + t = x.shape[0] + qkv = x @ wqkv.T + z = (x @ wz.T).reshape(t, hv, vd) + g = np.exp(-np.exp(a_log) * softplus(x @ wa.T + dt_bias)) + beta = sigmoid(x @ wb.T) + padded = np.concatenate([np.zeros((conv.shape[1] - 1, qkv.shape[1])), qkv]) + mixed = sum(padded[j:j + t] * conv[:, j] for j in range(conv.shape[1])) + mixed = silu(mixed) + q = mixed[:, :key].reshape(t, hk, kd) + k = mixed[:, key:2 * key].reshape(t, hk, kd) + v = mixed[:, 2 * key:].reshape(t, hv, vd) + q = rms(q, None, 1e-6) * kd ** -1.0 + k = rms(k, None, 1e-6) * kd ** -0.5 + y = rms(delta_rule(q, k, v, g, beta), gain, self.eps) * silu(z) + out.append(y.reshape(t, hv * vd) @ wo.T) + return out + + def rope(self, x, positions): + half = self.rotary // 2 + freq = self.theta ** (-np.arange(half, dtype=F) * 2.0 / self.rotary) + angle = np.asarray(positions, F)[:, None] * freq[None, :] + cos, sin = np.cos(angle)[:, None, :], np.sin(angle)[:, None, :] + x1, x2 = x[..., :half], x[..., half:self.rotary] + return np.concatenate([x1 * cos - x2 * sin, x1 * sin + x2 * cos, x[..., self.rotary:]], axis=-1) + + def attention(self, layer, xs, positions): + m = lambda n: self.ck.dense(self.p(layer, f"self_attn.{n}")) + wq, wk, wv, wo = m("q_proj"), m("k_proj"), m("v_proj"), m("o_proj") + qn = self.ck.vector(self.p(layer, "self_attn.q_norm.weight")) + kn = self.ck.vector(self.p(layer, "self_attn.k_norm.weight")) + h, kvh, d = self.heads, self.kv_heads, self.head_dim + out = [] + for x in xs: + t = x.shape[0] + qg = (x @ wq.T).reshape(t, h, 2 * d) + q, gate = qg[..., :d], qg[..., d:].reshape(t, h * d) + k = (x @ wk.T).reshape(t, kvh, d) + v = (x @ wv.T).reshape(t, kvh, d) + q = self.rope(rms(q, qn, self.eps), positions) + k = self.rope(rms(k, kn, self.eps), positions) + k, v = np.repeat(k, h // kvh, axis=1), np.repeat(v, h // kvh, axis=1) + scores = np.einsum("thd,shd->hts", q, k) * d ** -0.5 + scores = np.where(np.tril(np.ones((t, t), bool))[None], scores, -np.inf) + scores = np.exp(scores - scores.max(axis=-1, keepdims=True)) + scores /= scores.sum(axis=-1, keepdims=True) + o = np.einsum("hts,shd->thd", scores, v).reshape(t, h * d) + out.append((o * sigmoid(gate)) @ wo.T) + return out + + def route(self, logits): + """Top-k experts per row (ties to the lower id), their renormalized weights, the k-th/(k+1)-th gap.""" + order = np.argsort(-logits, axis=-1, kind="stable") + picks = order[:, :self.top_k] + top = np.take_along_axis(logits, picks, axis=-1) + weights = np.exp(top - top[:, :1]) + weights /= weights.sum(axis=-1, keepdims=True) + nxt = np.take_along_axis(logits, order[:, self.top_k:self.top_k + 1], axis=-1)[:, 0] + return picks, weights, top[:, -1] - nxt + + def moe(self, layer, xs): + """xs: stream rows after the mixer; returns each run's MLP output and per-row routing (picks, k/k+1 gap).""" + norm = self.ck.vector(self.p(layer, "post_attention_layernorm.weight")) + sizes = [x.shape[0] for x in xs] + x = rms(np.concatenate(xs), norm, self.eps) + logits = x @ self.ck.dense(self.p(layer, "mlp.gate")).T + picks, weights, gap = self.route(logits) + y = np.zeros_like(x) + base = self.p(layer, "mlp.switch_mlp") + for e in np.unique(picks): + rows, slot = np.nonzero(picks == e) + g = self.ck.dense(f"{base}.gate_proj", index=int(e)) + u = self.ck.dense(f"{base}.up_proj", index=int(e)) + dn = self.ck.dense(f"{base}.down_proj", index=int(e)) + xe = x[rows] + y[rows] += weights[rows, slot][:, None] * ((silu(xe @ g.T) * (xe @ u.T)) @ dn.T) + s = lambda n: self.ck.dense(self.p(layer, f"mlp.shared_expert.{n}")) + shared = (silu(x @ s("gate_proj").T) * (x @ s("up_proj").T)) @ s("down_proj").T + y += sigmoid(x @ self.ck.dense(self.p(layer, "mlp.shared_expert_gate")).T) * shared + cuts = np.cumsum(sizes)[:-1] + return np.split(y, cuts), np.split(picks, cuts), np.split(gap, cuts) + + def final(self, x): + return rms(x, self.ck.vector(self.ck.prefix + "norm.weight"), self.eps) + + def head(self, xs, chunk=16384): + """Logits for each run's rows, the head dequantized a vocab chunk at a time.""" + sizes = [x.shape[0] for x in xs] + x = np.concatenate(xs) + out = np.empty((x.shape[0], self.vocab)) + for at in range(0, self.vocab, chunk): + rows = mx.arange(at, min(at + chunk, self.vocab)) + out[:, at:at + chunk] = x @ self.ck.dense("language_model.lm_head", rows=rows).T + return np.split(out, np.cumsum(sizes)[:-1]) diff --git a/tools/zig/qwen36_mlx_stages.py b/tools/zig/qwen36_mlx_stages.py new file mode 100644 index 00000000000..d68ea1d9295 --- /dev/null +++ b/tools/zig/qwen36_mlx_stages.py @@ -0,0 +1,96 @@ +"""mlx_lm's staged references for qwen3_5_moe, in the layout families/qwen3_5/stages.zig writes (see USAGE).""" +from __future__ import annotations + +USAGE = """The rows follow mlx_lm's generate_step: the prompt but its last token in one call, then one-row steps +feeding the last prompt token and every teacher token but the last; logits are each step's row. The decoder layer +runs its own ops unchanged and records the stream after the mixer and after the MLP. + + python tools/zig/qwen36_mlx_stages.py --snapshot SNAP --ids ids.json --reference ref.json --out DIR""" + +import argparse +import json +from pathlib import Path + +import mlx.core as mx +import numpy as np +from mlx_lm import load +from mlx_lm.models import qwen3_5 +from mlx_lm.models.cache import make_prompt_cache + +RECORD: list | None = None + + +def decoder_call(self, x, mask=None, cache=None): + if self.is_linear: + r = self.linear_attn(self.input_layernorm(x), mask, cache) + else: + r = self.self_attn(self.input_layernorm(x), mask, cache) + h = x + r + out = h + self.mlp(self.post_attention_layernorm(h)) + if RECORD is not None: + RECORD.append((h, out)) + return out + + +def raw(x): + x = x.astype(mx.bfloat16) + mx.eval(x) + return np.array(x.view(mx.uint16)).reshape(-1, x.shape[-1]) + + +def main(): + global RECORD + ap = argparse.ArgumentParser(description=__doc__ + "\n\n" + USAGE, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("--snapshot", type=Path, required=True) + ap.add_argument("--ids", type=Path, required=True) + ap.add_argument("--reference", type=Path, required=True) + ap.add_argument("--out", type=Path, required=True) + args = ap.parse_args() + prompt = json.loads(args.ids.read_text()) + reference = json.loads(args.reference.read_text()) + + qwen3_5.DecoderLayer.__call__ = decoder_call + model, _ = load(str(args.snapshot)) + text = model.language_model.model + layers = len(text.layers) + names = ["embed"] + [f"l{l:02d}.{k}" for l in range(layers) for k in ("mixer", "block")] + ["final"] + planes = {n: [] for n in names + ["logits"]} + cache = make_prompt_cache(model) + if len(prompt) < 2: + raise SystemExit("the prompt needs two tokens: one prefill call, then the steps") + calls = [prompt[:-1], [prompt[-1]]] + [[t] for t in reference[:-1]] + picks = [] + for step, ids in enumerate(calls): + tokens = mx.array(ids)[None] + RECORD = [] + logits = model(tokens, cache=cache) + mx.eval(logits, [c.state for c in cache]) + planes["embed"].append(raw(text.embed_tokens(tokens))) + for l, (h, out) in enumerate(RECORD): + planes[f"l{l:02d}.mixer"].append(raw(h)) + planes[f"l{l:02d}.block"].append(raw(out)) + planes["final"].append(raw(text.norm(RECORD[-1][1]))) + if step > 0: + last = logits[:, -1, :] + planes["logits"].append(raw(last)) + logprobs = last - mx.logsumexp(last, keepdims=True) + picks.append(int(mx.argmax(logprobs, axis=-1).item())) + RECORD = None + args.out.mkdir(parents=True, exist_ok=True) + stages = [] + for n, chunks in planes.items(): + data = np.concatenate(chunks) + data.tofile(args.out / f"{n}.bf16") + stages.append({"name": n, "width": int(data.shape[1]), "rows": int(data.shape[0])}) + total = len(prompt) + len(reference) - 1 + index = {"version": 1, "dtype": "bf16", "layers": layers, "hidden": stages[0]["width"], + "vocab": stages[-1]["width"], "stages": stages, "positions": list(range(total)), + "logit_positions": list(range(len(prompt) - 1, total)), + "mlx": mx.__version__, "greedy_picks_equal_reference": picks == reference, "picks": picks} + (args.out / "index.json").write_text(json.dumps(index)) + print(json.dumps({"picks_equal_reference": picks == reference, + "differ_at": [i for i, (a, b) in enumerate(zip(picks, reference)) if a != b]})) + + +if __name__ == "__main__": + main() diff --git a/tools/zig/qwen36_stage_ref.py b/tools/zig/qwen36_stage_ref.py new file mode 100644 index 00000000000..7f74b223290 --- /dev/null +++ b/tools/zig/qwen36_stage_ref.py @@ -0,0 +1,227 @@ +"""Staged references for qwen3_5_moe: engine stage dumps against a float64 forward of the same checkpoint.""" +from __future__ import annotations + +USAGE = """Each engine directory holds what families/qwen3_5/stages.zig writes (or qwen36_mlx_stages.py): one bf16 +file per stage (embed, lNN.mixer, lNN.block, final, logits) and index.json with every row's cache position. + local float64 of one stage fed the engine's own bf16 input to it: that stage's error alone. + chained float64 from the token ids: the accumulated error. +Per stage and engine: the worst row's relative error and its worst element in bf16 steps of the row's largest value. +At the asked teacher positions: every contender's logit in float64, chained and fed each engine's final norm. + + python tools/zig/qwen36_stage_ref.py --snapshot SNAP --ids ids.json --reference ref.json \\ + --engine metal=DIR --engine mlx=DIR --positions 24,39,44,54 --out stages.json""" + +import argparse +import json +import sys +import time +from pathlib import Path + +import numpy as np + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from qwen36_f64 import Checkpoint, Model # noqa: E402 + + +def stage_names(layers): + names = ["embed"] + for l in range(layers): + names += [f"l{l:02d}.mixer", f"l{l:02d}.block"] + return names + ["final", "logits"] + + +def bf16(raw): + return (raw.astype(np.uint32) << 16).view(np.float32).astype(np.float64) + + +class Dump: + """One engine's stage directory; refuses a missing stage, a wrong shape or rows at other positions.""" + + def __init__(self, name, path: Path, layers, hidden, vocab, positions, logit_positions): + self.name, self.path = name, path + index = json.loads((path / "index.json").read_text()) + if (index.get("version"), index.get("dtype")) != (1, "bf16"): + raise SystemExit(f"{name}: index version {index.get('version')} / {index.get('dtype')} is not 1 / bf16") + if (index["layers"], index["hidden"], index["vocab"]) != (layers, hidden, vocab): + raise SystemExit(f"{name}: shape {index['layers']}/{index['hidden']}/{index['vocab']} is not the model's") + # Logits may cover more rows (a one-row-step engine has every row's); the teacher rows are taken from them. + have = {p: i for i, p in enumerate(index["logit_positions"])} + if len(have) != len(index["logit_positions"]): + raise SystemExit(f"{name}: logit positions repeat") + if index["positions"] != positions or any(p not in have for p in logit_positions): + raise SystemExit(f"{name}: rows are not positions {positions[0]}..{positions[-1]} / logits {logit_positions[0]}..") + self.logit_rows = np.array([have[p] for p in logit_positions]) + listed = {s["name"]: s for s in index["stages"]} + if len(listed) != len(index["stages"]) or sorted(listed) != sorted(stage_names(layers)): + raise SystemExit(f"{name}: stages differ from {len(stage_names(layers))} expected, once each") + # Every plane's shape from the model and the positions, never from the stage's own entry. + want = {n: (len(have), vocab) if n == "logits" else (len(positions), hidden) for n in listed} + for n, s in listed.items(): + if (s["rows"], s["width"]) != want[n]: + raise SystemExit(f"{name}: {n} is {s['rows']}x{s['width']}, not {want[n][0]}x{want[n][1]}") + self.rows = {n: w[0] for n, w in want.items()} + self.width = {n: w[1] for n, w in want.items()} + # An engine whose own pick is not its logits' first maximum (mlx_lm argmaxes its log-probabilities) lists it. + self.picks = np.array(index["picks"]) if "picks" in index else None + + def get(self, stage): + raw = np.fromfile(self.path / f"{stage}.bf16", dtype=np.uint16) + if raw.size != self.rows[stage] * self.width[stage]: + raise SystemExit(f"{self.name}: {stage}.bf16 has {raw.size} values") + rows = bf16(raw.reshape(self.rows[stage], self.width[stage])) + return rows[self.logit_rows] if stage == "logits" else rows + + +def step(v): + """A bf16 step at |v|: 2^(exponent - 7).""" + v = np.maximum(np.abs(v), np.finfo(np.float32).tiny) + return np.exp2(np.floor(np.log2(v)) - 7) + + +def measure(engine, ref, rows_of_interest): + """Per row: ||e - r|| / ||r|| and max|e - r| in bf16 steps of max|r|; the worst row and the asked rows.""" + diff = engine - ref + rel = np.linalg.norm(diff, axis=1) / np.maximum(np.linalg.norm(ref, axis=1), 1e-300) + steps = np.abs(diff).max(axis=1) / step(np.abs(ref).max(axis=1)) + worst = int(np.argmax(rel)) + return { + "max_rel": float(rel.max()), "median_rel": float(np.median(rel)), "worst_row": worst, + "max_steps": float(steps.max()), "median_steps": float(np.median(steps)), + "rows": {str(k): {"rel": float(rel[r]), "steps": float(steps[r])} for k, r in rows_of_interest.items()}, + } + + +def outliers(engine, local, gap, factor=5.0, most=8): + """Rows whose MLP error is `factor` times the median, with the float64 router's k-th/(k+1)-th gap.""" + rel = np.linalg.norm(engine - local, axis=1) / np.linalg.norm(local, axis=1) + rows = np.nonzero(rel > factor * np.median(rel))[0] + rows = rows[np.argsort(-rel[rows])][:most] + return [[int(r), float(rel[r]), float(gap[r])] for r in rows] + + +def top1_summary(chained, picks): + """Float64 top two and margin per position; per engine, where it picks another token and how far below (steps).""" + order = np.argsort(-chained, axis=1, kind="stable")[:, :2] + top = np.take_along_axis(chained, order, axis=1) + margin = top[:, 0] - top[:, 1] + out = {"f64_margin_steps": [float(x) for x in margin / step(top[:, 0])], "engines": {}} + for name, pick in picks.items(): + pick = np.asarray(pick) + wrong = np.nonzero(pick != order[:, 0])[0] + out["engines"][name] = { + "matches_f64": int(len(pick) - len(wrong)), "of": len(pick), + "other": [[int(p), int(pick[p]), int(order[p, 0]), + float((top[p, 0] - chained[p, pick[p]]) / step(top[p, 0]))] for p in wrong]} + return out + + +def contenders(teacher, dumps, logits, reference_token): + ids = {int(reference_token)} + for d in dumps: + ids.update(int(i) for i in np.argsort(-logits[d.name][teacher], kind="stable")[:2]) + return sorted(ids) + + +def main(): + ap = argparse.ArgumentParser(description=__doc__ + "\n\n" + USAGE, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("--snapshot", type=Path, required=True) + ap.add_argument("--ids", type=Path, required=True) + ap.add_argument("--reference", type=Path, required=True, help="teacher tokens; every one but the last is fed") + ap.add_argument("--engine", action="append", default=[], help="NAME=DIR, repeatable") + ap.add_argument("--logits", action="append", default=[], + help="NAME=FILE: an engine's bf16 logits for every fed row (tf-qwen35-cuda step), top-1 only") + ap.add_argument("--positions", default="24,39,44,54", help="teacher positions to report in full") + ap.add_argument("--out", type=Path, required=True) + ap.add_argument("--layers", type=int, default=0, help="stop after this many layers (a quick check)") + args = ap.parse_args() + + prompt = json.loads(args.ids.read_text()) + reference = json.loads(args.reference.read_text()) + tokens = prompt + reference[:-1] + positions = list(range(len(tokens))) + logit_positions = positions[len(prompt) - 1:] + asked = [int(p) for p in args.positions.split(",") if p] + asked_rows = {p: len(prompt) - 1 + p for p in asked} + + t0 = time.time() + model = Model(Checkpoint(args.snapshot)) + layers = args.layers or model.layers + dumps = [] + for spec in args.engine: + name, _, path = spec.partition("=") + dumps.append(Dump(name, Path(path), model.layers, model.hidden, model.vocab, positions, logit_positions)) + if not dumps: + raise SystemExit("no --engine") + + result = {"tokens": len(tokens), "prompt": len(prompt), "engines": [d.name for d in dumps], "stages": {}, + "routing": {}, "teacher": {}} + + def record(stage, local, chained): + rows = {p: p for p in asked} if stage == "logits" else asked_rows + result["stages"][stage] = { + d.name: {"local": measure(d.get(stage), local[i], rows), + "chained": measure(d.get(stage), chained, rows)} for i, d in enumerate(dumps)} + + x = model.embed(tokens) + record("embed", [x] * len(dumps), x) + prev = {d.name: d.get("embed") for d in dumps} + for layer in range(layers): + mixed = model.mixer(layer, [x] + [prev[d.name] for d in dumps], positions) + h = x + mixed[0] + local = [prev[d.name] + mixed[1 + i] for i, d in enumerate(dumps)] + name = f"l{layer:02d}.mixer" + record(name, local, h) + after = {d.name: d.get(name) for d in dumps} + y, picks, gap = model.moe(layer, [h] + [after[d.name] for d in dumps]) + x = h + y[0] + local = [after[d.name] + y[1 + i] for i, d in enumerate(dumps)] + name = f"l{layer:02d}.block" + record(name, local, x) + result["routing"][f"l{layer:02d}"] = { + "chained_gap": {str(p): float(gap[0][r]) for p, r in asked_rows.items()}, + **{d.name: {"rows_with_other_picks": int((np.sort(picks[1 + i], 1) != np.sort(picks[0], 1)).any(1).sum()), + "asked_other_picks": {str(p): bool((np.sort(picks[1 + i][r]) != np.sort(picks[0][r])).any()) + for p, r in asked_rows.items()}, + "outliers": outliers(d.get(name), local[i], gap[1 + i])} + for i, d in enumerate(dumps)}} + prev = {d.name: d.get(name) for d in dumps} + print(f"layer {layer} {time.time() - t0:.0f}s", file=sys.stderr, flush=True) + + if layers == model.layers: + final = model.final(x) + record("final", [model.final(prev[d.name]) for d in dumps], final) + engine_final = {d.name: d.get("final") for d in dumps} + lp = np.array(logit_positions) + heads = model.head([final[lp]] + [engine_final[d.name][lp] for d in dumps]) + record("logits", heads[1:], heads[0]) + logits = {d.name: d.get("logits") for d in dumps} + for p in asked: + ids = contenders(p, dumps, logits, reference[p]) + chained = heads[0][p] + best = np.argsort(-chained, kind="stable")[:3] + result["teacher"][str(p)] = { + "reference_token": int(reference[p]), + "f64_chained_top3": [[int(i), float(chained[i])] for i in best], + "contenders": {str(i): { + "f64_chained": float(chained[i]), + **{f"f64_from_{d.name}_final": float(heads[1 + k][p][i]) for k, d in enumerate(dumps)}, + **{d.name: float(logits[d.name][p][i]) for d in dumps}} for i in ids}, + "top2": {d.name: [int(i) for i in np.argsort(-logits[d.name][p], kind="stable")[:2]] for d in dumps}, + } + picks = {d.name: d.picks if d.picks is not None else np.argmax(logits[d.name], 1) for d in dumps} + for spec in args.logits: + name, _, path = spec.partition("=") + raw = np.fromfile(path, dtype=np.uint16) + if raw.size != len(tokens) * model.vocab: + raise SystemExit(f"{name}: {path} is not {len(tokens)} rows of {model.vocab} logits") + picks[name] = np.argmax(bf16(raw.reshape(len(tokens), model.vocab)[lp]), 1) + picks["reference"] = np.array(reference) + result["top1"] = top1_summary(heads[0], picks) + + result["seconds"] = time.time() - t0 + args.out.write_text(json.dumps(result, indent=1)) + print(f"wrote {args.out} in {result['seconds']:.0f}s", file=sys.stderr) + + +if __name__ == "__main__": + main() diff --git a/tools/zig/qwen36_stage_ref_test.py b/tools/zig/qwen36_stage_ref_test.py new file mode 100644 index 00000000000..c383fb07d33 --- /dev/null +++ b/tools/zig/qwen36_stage_ref_test.py @@ -0,0 +1,156 @@ +"""The float64 reference's pieces against mlx's own ops, and the staged comparer's refusals and planted errors.""" +import json +import tempfile +import unittest +from pathlib import Path + +try: + import mlx.core as mx + from mlx_lm.models.gated_delta import gated_delta_ops +except ImportError: + raise unittest.SkipTest("mlx and mlx_lm are not installed") +import numpy as np + +from qwen36_f64 import Checkpoint, Model, delta_rule, rms +from qwen36_stage_ref import Dump, bf16, measure, stage_names, step + + +def tiny_checkpoint(bits, out_rows=8, width=128, group=64): + """A Checkpoint whose one tensor `w` is mlx-quantized from random weights, without a snapshot on disk.""" + ck = Checkpoint.__new__(Checkpoint) + ck.bits, ck.group, ck.widths = bits, group, {} + w = mx.random.normal((out_rows, width), key=mx.random.key(bits)).astype(mx.bfloat16) + q, s, b = mx.quantize(w, group_size=group, bits=bits) + ck.shards = {"w.weight": q, "w.scales": s, "w.biases": b} + return ck, mx.dequantize(q, s, b, group_size=group, bits=bits).astype(mx.float32) + + +class ReferenceOpsTest(unittest.TestCase): + def test_dequantize_matches_mlx_for_every_width(self): + for bits in (4, 8): + ck, want = tiny_checkpoint(bits) + got = ck.dense("w") + # mlx dequantizes in bf16; ours is exact, so they agree to one bf16 step of each value. + np.testing.assert_allclose(got, np.array(want), rtol=2 ** -8, atol=1e-6) + np.testing.assert_array_equal(ck.dense("w", rows=mx.array([3, 1])), got[[3, 1]]) + + def test_rope_matches_mlx_fast_rope(self): + m = Model.__new__(Model) + m.rotary, m.theta = 64, 1e7 + x = np.random.default_rng(0).standard_normal((5, 2, 256)) + got = m.rope(x, np.arange(7, 12)) + want = mx.fast.rope(mx.array(x.transpose(1, 0, 2), mx.float32)[None], 64, traditional=False, base=1e7, + scale=1.0, offset=7) + np.testing.assert_allclose(got, np.array(want)[0].transpose(1, 0, 2), atol=2e-5) + + def test_delta_rule_matches_mlx_ops(self): + rng = np.random.default_rng(1) + t, hk, hv, d = 6, 2, 4, 16 + q, k = rng.standard_normal((t, hk, d)), rng.standard_normal((t, hk, d)) + v = rng.standard_normal((t, hv, d)) + g, beta = rng.uniform(0.5, 1.0, (t, hv)), rng.uniform(0.0, 1.0, (t, hv)) + f = lambda a: mx.array(a, mx.float32)[None] + want, _ = gated_delta_ops(f(q), f(k), f(v), f(g), f(beta)) + np.testing.assert_allclose(delta_rule(q, k, v, g, beta), np.array(want)[0], atol=1e-4) + + def test_route_breaks_ties_to_the_lower_id_and_renormalizes(self): + m = Model.__new__(Model) + m.top_k = 2 + picks, weights, gap = m.route(np.array([[1.0, 3.0, 3.0, 3.0]])) + np.testing.assert_array_equal(picks, [[1, 2]]) + np.testing.assert_allclose(weights, [[0.5, 0.5]]) + self.assertEqual(gap[0], 0.0) + + def test_rms(self): + x = np.array([[3.0, 4.0]]) + np.testing.assert_allclose(rms(x, np.array([2.0, 1.0]), 0.0), [[3 / np.sqrt(12.5) * 2, 4 / np.sqrt(12.5)]]) + + +def write_dump(path: Path, layers, hidden, vocab, rows, logits, positions=None, names=None, shapes=None, + logit_positions=None, version=1): + """Logits row i holds bf16(i); `shapes` overrides a stage's (rows, width) so only the shape check can refuse it.""" + path.mkdir(parents=True, exist_ok=True) + stages = [] + for n in names or stage_names(layers): + count, width = (shapes or {}).get(n, (logits, vocab) if n == "logits" else (rows, hidden)) + data = np.zeros((count, width), np.uint16) + if n == "logits": + data[:] = (np.arange(count, dtype=np.float32).view(np.uint32) >> 16).astype(np.uint16)[:, None] + data.tofile(path / f"{n}.bf16") + stages.append({"name": n, "width": width, "rows": count}) + index = {"version": version, "dtype": "bf16", "layers": layers, "hidden": hidden, "vocab": vocab, + "stages": stages, "positions": positions if positions is not None else list(range(rows)), + "logit_positions": logit_positions if logit_positions is not None else list(range(rows - logits, rows))} + (path / "index.json").write_text(json.dumps(index)) + + +class ComparerTest(unittest.TestCase): + def test_dump_refuses_other_shapes_positions_and_names(self): + with tempfile.TemporaryDirectory() as tmp: + good = Path(tmp) / "good" + write_dump(good, 2, 4, 6, 5, 2) + args = (2, 4, 6, list(range(5)), [3, 4]) + self.assertEqual(Dump("e", good, *args).get("l01.block").shape, (5, 4)) + # Each case's files agree with its own index, so only the check against the model can refuse it. + cases = { + "layers": dict(layers=3), "positions": dict(positions=[0, 1, 2, 4, 5]), + "names": dict(names=stage_names(2)[:-1]), "repeated": dict(names=stage_names(2) + ["final"]), + "version": dict(version=2), "repeated logits": dict(logit_positions=[3, 3]), + } + for n in ("embed", "l00.mixer", "l01.block", "final", "logits"): + rows, width = (2, 6) if n == "logits" else (5, 4) + for bad in ((rows, 1), (rows + 1, width), (rows - 1, width), (rows, width * 2)): + cases[f"{n} {bad}"] = dict(shapes={n: bad}) + for label, change in cases.items(): + path = Path(tmp) / label + kw = dict(layers=2, hidden=4, vocab=6, rows=5, logits=2) | change + write_dump(path, **kw) + with self.assertRaises(SystemExit, msg=label): + Dump("e", path, *args) + (good / "final.bf16").write_bytes(b"\0" * 6) + with self.assertRaises(SystemExit): + Dump("e", good, *args).get("final") + + def test_every_row_logits_give_the_teacher_rows_and_a_missing_row_is_refused(self): + with tempfile.TemporaryDirectory() as tmp: + every = Path(tmp) / "every" + write_dump(every, 1, 4, 6, 5, 5) # one-row steps: logits at positions 0..4 + got = Dump("e", every, 1, 4, 6, list(range(5)), [3, 4]).get("logits") + np.testing.assert_array_equal(got[:, 0], [3.0, 4.0]) + with self.assertRaises(SystemExit): + Dump("e", Path(tmp) / "every", 1, 4, 6, list(range(5)), [4, 5]) + + def test_step_is_bf16_spacing_at_every_exponent(self): + for e in range(-100, 100): + for mant in (1.0, 1.5, 1.9921875): + v = mant * 2.0 ** e + self.assertEqual(step(np.array([v]))[0], 2.0 ** (e - 7)) + self.assertEqual(step(np.array([-v]))[0], 2.0 ** (e - 7)) + + def test_a_planted_step_is_found_on_every_row(self): + rng = np.random.default_rng(2) + ref = bf16(rng.integers(0x3f00, 0x4100, (6, 8), dtype=np.uint16)) + for row in range(6): + for col in range(8): + for k in (1, 3): + engine = ref.copy() + engine[row, col] += k * step(np.abs(ref[row]).max(keepdims=True))[0] + m = measure(engine, ref, {"r": row}) + self.assertEqual(m["worst_row"], row) + self.assertAlmostEqual(m["max_steps"], k) + self.assertAlmostEqual(m["rows"]["r"]["steps"], k) + self.assertEqual(measure(ref, ref, {})["max_steps"], 0.0) + + def test_final_is_the_normed_head_input_not_the_residual(self): + # a non-unit final norm (gains far from 1, rows far from unit RMS): a residual labelled final cannot pass + rng = np.random.default_rng(3) + residual = rng.standard_normal((6, 64)) * 7.0 + gain = rng.uniform(0.2, 3.0, 64) + final = rms(residual, gain, 1e-6) + self.assertLess(measure(final.copy(), final, {})["max_rel"], 1e-12) + self.assertGreater(measure(residual, final, {})["max_rel"], 0.5) + self.assertGreater(measure(rms(residual, None, 1e-6), final, {})["max_rel"], 0.1) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/zig/ricursive_gate_compare.py b/tools/zig/ricursive_gate_compare.py new file mode 100644 index 00000000000..d8b14fba2ac --- /dev/null +++ b/tools/zig/ricursive_gate_compare.py @@ -0,0 +1,266 @@ +"""Ripple's engine logits against ricursive_reference.py's: KL, top-1, worst rows, identical dumps, a greedy reply.""" + +from __future__ import annotations + +import argparse +import json +import os +import sys +from pathlib import Path + +import numpy as np + +USAGE = """ +Logits files are bf16 bits [rows][vocab]. The reference writes them raw, with no header. The engine's `tensorfold kl +--dump` writes u32 rows, u32 vocab, then a record a row: the token fed next (u32) and the row's logits. Either is read +(the format is told from the file size); row r is the distribution of token r + 1 given tokens 0..r. + + ricursive_gate_compare.py finite FILE... [--ids ids.json] (non-finite logits, distinct top-1 tokens, hits on the next token) + ricursive_gate_compare.py kl REF ENGINE --ids ids.json [--max-kl X --min-top1 Y] [--out report.json] + (a REF with more rows than ids, as one run over prompt + reply gives, is read for its first rows) + ricursive_gate_compare.py same FILE FILE... [--vocab N] (every row's logits bit for bit equal to the first file's) + ricursive_gate_compare.py reply REF REPLY.json --prompt-len P (REF over prompt + reply: argmax of row P-1+i is reply[i]) + ricursive_gate_compare.py join IDS.json REPLY.json OUT.json (the prompt's ids followed by the reply's) + ricursive_gate_compare.py split IDS.json PROMPT.json --prompt N (the first N ids to PROMPT.json; the rest on stdout, comma + separated, for `tensorfold kl --gold`) +""" + +HEADER = 8 # a kl dump's u32 rows and u32 vocab + + +def bf16_to_f32(bits: np.ndarray) -> np.ndarray: + return (bits.astype(np.uint32) << 16).view(np.float32) + + +def log_softmax(x: np.ndarray) -> np.ndarray: + x = x.astype(np.float64) + m = x.max(-1, keepdims=True) + return x - m - np.log(np.exp(x - m).sum(-1, keepdims=True)) + + +def read_ids(path: str) -> list[int]: + data = json.loads(Path(path).read_text()) + if isinstance(data, dict): + data = data.get("ids", data.get("tokens")) + return [int(t) for t in data] + + +def open_logits(path: str, vocab: int) -> tuple[np.ndarray, np.ndarray | None]: + """The file's logits as a [rows, vocab] uint16 view, and the fed tokens when it is a kl dump.""" + size = os.path.getsize(path) + rec = 4 + 2 * vocab + raw = size > 0 and size % (2 * vocab) == 0 + kl = size > HEADER and (size - HEADER) % rec == 0 + if raw == kl: + raise SystemExit(f"{path}: {size} bytes is neither [rows, {vocab}] raw bf16 nor a kl dump of that vocabulary") + if raw: + rows = size // (2 * vocab) + return np.memmap(path, dtype=" dict: + """Per row KL(ref || engine) over the whole vocabulary in float64, both greedy picks, and the worst rows.""" + rows = ref.shape[0] + kl = np.zeros(rows) + agree = np.zeros(rows, dtype=bool) + ref_top = np.zeros((rows, 3), dtype=np.int64) + eng_top = np.zeros((rows, 3), dtype=np.int64) + ref_lp = np.zeros((rows, 3)) + eng_lp = np.zeros((rows, 3)) + finite = np.ones(rows, dtype=bool) + lead = np.zeros(rows) # the reference's logprob lead of its top-1 over the engine's top-1 (0 where they agree) + for lo in range(0, rows, chunk): + hi = min(rows, lo + chunk) + r, e = bf16_to_f32(np.asarray(ref[lo:hi])), bf16_to_f32(np.asarray(eng[lo:hi])) + finite[lo:hi] = np.isfinite(e).all(-1) + lp, lq = log_softmax(r), log_softmax(e) + kl[lo:hi] = (np.exp(lp) * (lp - lq)).sum(-1) + ref_top[lo:hi] = np.argsort(-lp, axis=-1, kind="stable")[:, :3] + eng_top[lo:hi] = np.argsort(-lq, axis=-1, kind="stable")[:, :3] + ref_lp[lo:hi] = np.take_along_axis(lp, ref_top[lo:hi], -1) + eng_lp[lo:hi] = np.take_along_axis(lq, eng_top[lo:hi], -1) + agree[lo:hi] = ref_top[lo:hi, 0] == eng_top[lo:hi, 0] + at = np.arange(hi - lo) + lead[lo:hi] = lp[at, ref_top[lo:hi, 0]] - lp[at, eng_top[lo:hi, 0]] + worst = [] + for r in np.argsort(-np.nan_to_num(kl, nan=np.inf), kind="stable")[:top]: + worst.append({ + "row": int(r), + "next_token": ids[r + 1] if r + 1 < len(ids) else None, + "kl": float(kl[r]), + "same_top1": bool(agree[r]), + "reference": [[int(t), round(float(p), 4)] for t, p in zip(ref_top[r], ref_lp[r])], + "engine": [[int(t), round(float(p), 4)] for t, p in zip(eng_top[r], eng_lp[r])], + "reference_margin": round(float(ref_lp[r, 0] - ref_lp[r, 1]), 4), + }) + return { + "rows": rows, + "kl_mean": float(kl.mean()), + "kl_median": float(np.median(kl)), + "kl_p99": float(np.percentile(kl, 99)), + "kl_max": float(kl.max()), + "top1_agreement": float(agree.mean()), + "top1_misses": int((~agree).sum()), + "nonfinite_rows": int((~finite).sum()), + "miss_leads": sorted(round(float(m), 4) for m in lead[~agree]), + "worst": worst, + } + + +def run_kl(a: argparse.Namespace) -> int: + ids = read_ids(a.ids) + ref, ref_fed = open_logits(a.ref, a.vocab) + eng, fed = open_logits(a.engine, a.vocab) + if ref.shape[0] > len(ids): + ref = ref[: len(ids)] # a causal model: the first rows of a longer run are the shorter run's + if fed is None and eng.shape[0] > len(ids): + eng = eng[: len(ids)] # the same for a raw file, so two reference passes compare over the chat's rows + if ref.shape != eng.shape or ref.shape[0] != len(ids): + raise SystemExit(f"shapes differ: reference {ref.shape}, engine {eng.shape}, {len(ids)} ids") + if fed is not None: # a kl dump says which token it fed after each row: the chat's next one, but for the last row + wrong = np.flatnonzero(np.asarray(fed[:-1]) != np.asarray(ids[1:], dtype=np.uint32)) + if wrong.size: + raise SystemExit(f"the engine's file fed other tokens than the ids at {wrong.size} rows, first row {wrong[0]}") + rep = compare(ref, eng, ids, a.top) + print(f"{rep['rows']} rows: mean KL {rep['kl_mean']:.5f}, median {rep['kl_median']:.5f}, p99 {rep['kl_p99']:.4f}, " + f"max {rep['kl_max']:.4f}; top-1 {100 * rep['top1_agreement']:.2f}% ({rep['top1_misses']} misses); " + f"{rep['nonfinite_rows']} rows with a non-finite engine logit") + print(f"the {len(rep['worst'])} worst rows (row, next token, KL, reference and engine top 3 as token:logprob, margin):") + for w in rep["worst"]: + ref3 = " ".join(f"{t}:{p}" for t, p in w["reference"]) + eng3 = " ".join(f"{t}:{p}" for t, p in w["engine"]) + print(f" row {w['row']}, next {w['next_token']}, KL {w['kl']:.4f}, reference [{ref3}], engine [{eng3}], " + f"margin {w['reference_margin']}{'' if w['same_top1'] else ', TOP-1 DIFFERS'}") + leads = np.array(rep["miss_leads"]) + if leads.size: # a miss where the reference itself barely prefers its pick is a near tie, not an error + print(f"top-1 misses by the reference's lead of its pick over the engine's: {int((leads < 0.1).sum())} under " + f"0.1, {int((leads < 0.5).sum())} under 0.5, the largest {leads.max():.4f} (nats)") + if a.out: + Path(a.out).write_text(json.dumps(rep, indent=1)) + bad = rep["nonfinite_rows"] > 0 or not rep["kl_mean"] == rep["kl_mean"] + if a.max_kl is not None and not rep["kl_mean"] <= a.max_kl: + print(f"FAIL: mean KL {rep['kl_mean']:.5f} is above {a.max_kl}") + bad = True + if a.min_top1 is not None and not rep["top1_agreement"] >= a.min_top1: + print(f"FAIL: top-1 {100 * rep['top1_agreement']:.2f}% is below {100 * a.min_top1:.2f}%") + bad = True + return 1 if bad else 0 + + +def run_finite(a: argparse.Namespace) -> int: + """A first look at a dump before any reference exists: a broken engine shows as NaNs, one token, or no hits.""" + ids = read_ids(a.ids) if a.ids else None + status = 0 + for path in a.files: + logits, _ = open_logits(path, a.vocab) + bad, top = 0, [] + for lo in range(0, logits.shape[0], 64): + x = bf16_to_f32(np.asarray(logits[lo:lo + 64])) + bad += int((~np.isfinite(x).all(-1)).sum()) + top.append(x.argmax(-1)) + top = np.concatenate(top) + text = f"{path}: {logits.shape[0]} rows, {bad} with a non-finite logit, {len(set(top.tolist()))} distinct top-1 tokens" + if ids is not None and len(ids) == len(top): + text += f", top-1 is the next token at {100 * np.mean(top[:-1] == np.array(ids[1:])):.1f}% of rows" + print(text) + status |= int(bad > 0) + return status + + +def run_same(a: argparse.Namespace) -> int: + base, _ = open_logits(a.files[0], a.vocab) + status = 0 + for path in a.files[1:]: + other, _ = open_logits(path, a.vocab) + if other.shape != base.shape: + print(f"{path}: {other.shape[0]} rows, not {base.shape[0]}") + status = 1 + continue + differ = [r for r in range(base.shape[0]) if not np.array_equal(base[r], other[r])] + if not differ: + print(f"{path}: all {base.shape[0]} rows bit-identical to {a.files[0]}") + continue + status = 1 + first = differ[0] + print(f"{path}: {len(differ)} of {base.shape[0]} rows differ from {a.files[0]}; first row {first} " + f"({int((base[first] != other[first]).sum())} of {a.vocab} logits)") + return status + + +def read_reply(path: str) -> list[int]: + return read_ids(path) # a plain list, or the run command's --report (its "tokens") + + +def run_reply(a: argparse.Namespace) -> int: + reply = read_reply(a.reply) + ref, _ = open_logits(a.ref, a.vocab) + need = a.prompt_len - 1 + len(reply) + if ref.shape[0] < need: + raise SystemExit(f"the reference has {ref.shape[0]} rows, the prompt and reply need {need}") + lp = log_softmax(bf16_to_f32(np.asarray(ref[a.prompt_len - 1:need]))) + pick = lp.argmax(-1) + miss = [i for i, t in enumerate(reply) if int(pick[i]) != t] + print(f"greedy reply of {len(reply)} tokens: {len(reply) - len(miss)} equal the float64 pass's argmax") + for i in miss[:5]: + print(f" reply token {i}: engine {reply[i]} (reference logprob {lp[i, reply[i]]:.4f}), " + f"reference {int(pick[i])} ({lp[i, pick[i]]:.4f}), margin {lp[i, pick[i]] - lp[i, reply[i]]:.4f}") + return 1 if miss else 0 + + +def run_join(a: argparse.Namespace) -> int: + ids = read_ids(a.ids) + read_reply(a.reply) + Path(a.out).write_text(json.dumps(ids)) + print(f"{len(ids)} ids to {a.out}") + return 0 + + +def run_split(a: argparse.Namespace) -> int: + ids = read_ids(a.ids) + Path(a.prompt_out).write_text(json.dumps(ids[: a.prompt])) + print(",".join(str(t) for t in ids[a.prompt:])) + return 0 + + +def main(argv: list[str] | None = None) -> int: + ap = argparse.ArgumentParser(description=__doc__, epilog=USAGE, formatter_class=argparse.RawDescriptionHelpFormatter) + sub = ap.add_subparsers(dest="cmd", required=True) + kl = sub.add_parser("kl") + kl.add_argument("ref") + kl.add_argument("engine") + kl.add_argument("--ids", required=True) + kl.add_argument("--top", type=int, default=10) + kl.add_argument("--max-kl", type=float, help="exit 1 if the mean KL is above this") + kl.add_argument("--min-top1", type=float, help="exit 1 if the top-1 agreement (0 to 1) is below this") + kl.add_argument("--out", default="") + fin = sub.add_parser("finite") + fin.add_argument("files", nargs="+") + fin.add_argument("--ids", default="") + same = sub.add_parser("same") + same.add_argument("files", nargs="+") + reply = sub.add_parser("reply") + reply.add_argument("ref") + reply.add_argument("reply") + reply.add_argument("--prompt-len", type=int, required=True) + join = sub.add_parser("join") + join.add_argument("ids") + join.add_argument("reply") + join.add_argument("out") + split = sub.add_parser("split") + split.add_argument("ids") + split.add_argument("prompt_out") + split.add_argument("--prompt", type=int, required=True) + for p in (kl, fin, same, reply): + p.add_argument("--vocab", type=int, default=100352) + a = ap.parse_args(argv) + return {"kl": run_kl, "finite": run_finite, "same": run_same, "reply": run_reply, "join": run_join, "split": run_split}[a.cmd](a) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/zig/ricursive_gate_ids.py b/tools/zig/ricursive_gate_ids.py new file mode 100644 index 00000000000..9f34d97d8e4 --- /dev/null +++ b/tools/zig/ricursive_gate_ids.py @@ -0,0 +1,100 @@ +"""The Ripple gate's chat as token ids: the release's chat template over a fixed text, cut to an exact length.""" + +from __future__ import annotations + +import argparse +import json +import sys +from pathlib import Path +from typing import Callable + +USAGE = """ +The Metal check's 2,586-token chat is not in the repository, so this builds one of the same length: a system turn, a +user turn holding the text's first 300 words, a fixed assistant turn, and a last user turn holding as many of the next +words as make the whole prompt, generation prompt included, exactly --length tokens. The tokens come from the release's +tokenizer.json and chat_template.jinja (needs `tokenizers` and `jinja2`); nothing else is read. + + ricursive_gate_ids.py MODEL_DIR --text FILE --out ids.json [--length 2586] +""" + +SYSTEM = "You are a careful technical assistant." +FIRST = "Summarise this passage in one sentence:\n\n" +ANSWER = "The passage describes how a model is served and checked." +LAST = "Now list every number in this passage, with what it measures:\n\n" +FILLERS = (" a", " the", " of", " and") + + +def messages(head: str, tail: str) -> list[dict]: + return [ + {"role": "system", "content": SYSTEM}, + {"role": "user", "content": FIRST + head}, + {"role": "assistant", "content": ANSWER}, + {"role": "user", "content": LAST + tail}, + ] + + +def fit(count: Callable[[list[dict]], int], text: str, length: int) -> list[dict]: + """The chat whose `count` is exactly `length`: the last user turn takes the most words that fit, then filler.""" + words = text.split() + head, rest = " ".join(words[:300]), words[300:] + if count(messages(head, "")) > length: + raise SystemExit(f"the fixed turns alone are over {length} tokens") + if count(messages(head, " ".join(rest))) < length: + raise SystemExit(f"the text holds too few words for {length} tokens") + lo, hi = 0, len(rest) # the most words k with count <= length; count never falls as words are added + while lo < hi: + mid = (lo + hi + 1) // 2 + if count(messages(head, " ".join(rest[:mid]))) <= length: + lo = mid + else: + hi = mid - 1 + tail = " ".join(rest[:lo]) + for filler in FILLERS: + for extra in range(5): + chat = messages(head, tail + filler * extra) + if count(chat) == length: + return chat + raise SystemExit(f"no filler reached exactly {length} tokens after {lo} words") + + +def load_renderer(model_dir: Path) -> Callable[[list[dict]], str]: + """The release's chat template as a function of the messages, with the generation prompt added.""" + from jinja2.sandbox import ImmutableSandboxedEnvironment + + def refuse(message: str) -> None: + raise ValueError(message) + + config = json.loads((model_dir / "tokenizer_config.json").read_text()) if (model_dir / "tokenizer_config.json").exists() else {} + special = {k: (v.get("content") if isinstance(v, dict) else v) or "" for k, v in config.items() if k in ("bos_token", "eos_token")} + env = ImmutableSandboxedEnvironment(trim_blocks=True, lstrip_blocks=True) + env.globals["raise_exception"] = refuse + template = env.from_string((model_dir / "chat_template.jinja").read_text()) + return lambda chat: template.render(messages=chat, add_generation_prompt=True, **special) + + +def main(argv: list[str] | None = None) -> int: + ap = argparse.ArgumentParser(description=__doc__, epilog=USAGE, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("model_dir") + ap.add_argument("--text", required=True) + ap.add_argument("--out", required=True) + ap.add_argument("--length", type=int, default=2586) + a = ap.parse_args(argv) + from tokenizers import Tokenizer + + model = Path(a.model_dir) + tok = Tokenizer.from_file(str(model / "tokenizer.json")) + render = load_renderer(model) + + def encode(chat: list[dict]) -> list[int]: + return tok.encode(render(chat), add_special_tokens=False).ids + + chat = fit(lambda c: len(encode(c)), Path(a.text).read_text(), a.length) + ids = encode(chat) + Path(a.out).write_text(json.dumps(ids)) + print(f"{len(ids)} ids to {a.out}; first {ids[:4]}, last {ids[-4:]}") + print("the prompt ends: " + repr(render(chat)[-60:])) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/zig/ricursive_gate_test.py b/tools/zig/ricursive_gate_test.py new file mode 100644 index 00000000000..7fa50ed73d0 --- /dev/null +++ b/tools/zig/ricursive_gate_test.py @@ -0,0 +1,190 @@ +"""The Ripple gate tools on synthetic files: KL, top-1, worst rows, identical dumps, replies, an exact-length chat.""" + +from __future__ import annotations + +import contextlib +import io +import json +import os +import tempfile +import unittest +from pathlib import Path + +import ricursive_gate_ids as ids_tool + +try: + import numpy as np +except ImportError: # the root pytest job installs pytest and PyYAML only + np = None +if np is not None: + import ricursive_gate_compare as cmp + +VOCAB, ROWS = 50, 12 + + +def bf16(x: np.ndarray) -> np.ndarray: + return (x.astype(np.float32).view(np.uint32) >> 16).astype(np.uint16) + + +def f32(bits: np.ndarray) -> np.ndarray: + return (bits.astype(np.uint32) << 16).view(np.float32) + + +def run(*argv: str) -> tuple[int, str]: + out = io.StringIO() + with contextlib.redirect_stdout(out): + code = cmp.main(list(argv)) + return code, out.getvalue() + + +@unittest.skipIf(np is None, "numpy is not installed") +class CompareTests(unittest.TestCase): + def setUp(self): + folder = tempfile.TemporaryDirectory() + self.addCleanup(folder.cleanup) + self.dir = Path(folder.name) + rng = np.random.default_rng(1) + self.ref = bf16(rng.normal(0, 3, (ROWS, VOCAB))) + self.eng = self.ref.copy() + self.eng[3] = bf16(rng.normal(0, 3, VOCAB)) # row 3 is another distribution + self.ids = [int(t) for t in rng.integers(0, VOCAB, ROWS)] + (self.dir / "ids.json").write_text(json.dumps(self.ids)) + + def raw(self, name: str, bits: np.ndarray) -> str: + path = self.dir / name + bits.astype(" str: + path = self.dir / name + with open(path, "wb") as f: + f.write(np.array([bits.shape[0], bits.shape[1]], dtype=" float: + p, q = f32(self.ref[r]).astype(np.float64), f32(self.eng[r]).astype(np.float64) + p, q = p - np.log(np.exp(p).sum()), q - np.log(np.exp(q).sum()) + return float((np.exp(p) * (p - q)).sum()) + + def test_kl_matches_the_formula_for_both_formats(self): + fed = self.ids[1:] + [0] + for eng in (self.raw("e.bin", self.eng), self.kl_dump("e.kl", self.eng, fed)): + code, text = run("kl", self.raw("r.bin", self.ref), eng, "--ids", str(self.dir / "ids.json"), + "--vocab", str(VOCAB), "--out", str(self.dir / "rep.json")) + rep = json.loads((self.dir / "rep.json").read_text()) + self.assertEqual(code, 0) + self.assertAlmostEqual(rep["kl_mean"], self.expected_kl(3) / ROWS, places=9) + self.assertEqual(rep["worst"][0]["row"], 3) + self.assertAlmostEqual(rep["worst"][0]["kl"], self.expected_kl(3), places=9) + self.assertEqual(rep["worst"][0]["next_token"], self.ids[4]) + self.assertIn("worst rows", text) + same = float(np.mean(f32(self.ref).argmax(-1) == f32(self.eng).argmax(-1))) + self.assertAlmostEqual(rep["top1_agreement"], same) + + def test_pass_rule_flags_kl_and_nonfinite_logits(self): + args = ("--ids", str(self.dir / "ids.json"), "--vocab", str(VOCAB)) + ref = self.raw("r.bin", self.ref) + eng = self.raw("e.bin", self.eng) + self.assertEqual(run("kl", ref, eng, *args, "--max-kl", "10")[0], 0) + code, text = run("kl", ref, eng, *args, "--max-kl", "0.0001") + self.assertEqual(code, 1) + self.assertIn("FAIL", text) + bad = self.eng.copy() + bad[5, 2] = 0x7FC0 # a bf16 NaN + self.assertEqual(run("kl", ref, self.raw("n.bin", bad), *args)[0], 1) + + def test_a_dump_that_fed_other_tokens_is_refused(self): + dump = self.kl_dump("e.kl", self.eng, [t + 1 for t in self.ids]) + with self.assertRaises(SystemExit): + run("kl", self.raw("r.bin", self.ref), dump, "--ids", str(self.dir / "ids.json"), "--vocab", str(VOCAB)) + + def test_same_finds_the_first_differing_row(self): + a = self.raw("a.bin", self.ref) + self.assertEqual(run("same", a, self.raw("b.bin", self.ref), "--vocab", str(VOCAB))[0], 0) + code, text = run("same", a, self.raw("c.bin", self.eng), "--vocab", str(VOCAB)) + self.assertEqual(code, 1) + self.assertIn("1 of 12 rows differ", text) + self.assertIn("first row 3", text) + + def test_reply_equal_and_not(self): + prompt = 5 + ref = self.ref + reply = [int(f32(ref[prompt - 1 + i]).argmax()) for i in range(4)] + path = self.dir / "reply.json" + path.write_text(json.dumps({"tokens": reply})) # the run command's report + self.assertEqual(run("reply", self.raw("r.bin", ref), str(path), "--prompt-len", str(prompt), "--vocab", str(VOCAB))[0], 0) + reply[2] = (reply[2] + 1) % VOCAB + path.write_text(json.dumps(reply)) + code, text = run("reply", self.raw("r.bin", ref), str(path), "--prompt-len", str(prompt), "--vocab", str(VOCAB)) + self.assertEqual(code, 1) + self.assertIn("3 equal", text) + self.assertIn("reply token 2", text) + + def test_a_longer_reference_is_read_for_its_first_rows(self): + longer = np.concatenate([self.ref, self.ref[:3]]) + code, _ = run("kl", self.raw("r.bin", longer), self.raw("e.bin", self.eng), "--ids", str(self.dir / "ids.json"), + "--vocab", str(VOCAB), "--out", str(self.dir / "rep.json")) + self.assertEqual(json.loads((self.dir / "rep.json").read_text())["rows"], ROWS) + self.assertEqual(code, 0) + + def test_finite_reports_nan_rows_and_next_token_hits(self): + good = self.raw("g.bin", self.ref) + code, text = run("finite", good, "--vocab", str(VOCAB), "--ids", str(self.dir / "ids.json")) + self.assertEqual(code, 0) + self.assertIn("0 with a non-finite logit", text) + hits = 100 * np.mean(f32(self.ref).argmax(-1)[:-1] == np.array(self.ids[1:])) + self.assertIn(f"{hits:.1f}%", text) + bad = self.ref.copy() + bad[4, 0] = 0x7F80 # bf16 +inf + code, text = run("finite", self.raw("b.bin", bad), "--vocab", str(VOCAB)) + self.assertEqual(code, 1) + self.assertIn("1 with a non-finite logit", text) + + def test_split_writes_the_prompt_and_prints_the_rest(self): + code, text = run("split", str(self.dir / "ids.json"), str(self.dir / "p.json"), "--prompt", "2") + self.assertEqual(code, 0) + self.assertEqual(json.loads((self.dir / "p.json").read_text()), self.ids[:2]) + self.assertEqual(text.strip(), ",".join(map(str, self.ids[2:]))) + + def test_join(self): + (self.dir / "reply.json").write_text(json.dumps({"tokens": [7, 8]})) + run("join", str(self.dir / "ids.json"), str(self.dir / "reply.json"), str(self.dir / "all.json")) + self.assertEqual(json.loads((self.dir / "all.json").read_text()), self.ids + [7, 8]) + + +class IdsTests(unittest.TestCase): + def count(self, chat): # a stand-in tokenizer: a token a word, two for a long word, and four a turn + return sum(sum(2 if len(w) > 3 else 1 for w in m["content"].split()) + 4 for m in chat) + 3 + + def test_fit_is_exact_and_deterministic(self): + text = " ".join(f"w{i}" for i in range(2000)) + for length in (1500, 1501, 1502, 1503): + chat = ids_tool.fit(self.count, text, length) + self.assertEqual(self.count(chat), length) + self.assertEqual(chat, ids_tool.fit(self.count, text, length)) + + def test_fit_refuses_a_short_text_and_long_fixed_turns(self): + with self.assertRaises(SystemExit): + ids_tool.fit(self.count, " ".join(["w"] * 400), 2586) + with self.assertRaises(SystemExit): + ids_tool.fit(self.count, " ".join(["w"] * 2000), 100) + + def test_the_release_template_renders_the_chat(self): + try: + import jinja2 # noqa: F401 + except ImportError: + self.skipTest("jinja2 is not installed") + folder = tempfile.TemporaryDirectory() + self.addCleanup(folder.cleanup) + (Path(folder.name) / "chat_template.jinja").write_text( + "{% for m in messages %}<|im_start|>{{ m.role }}\n{{ m.content }}<|im_end|>\n{% endfor %}" + "{% if add_generation_prompt %}<|im_start|>assistant\n{% endif %}") + text = ids_tool.load_renderer(Path(folder.name))(ids_tool.messages("a b", "c d")) + self.assertTrue(text.startswith("<|im_start|>system\n")) + self.assertTrue(text.endswith("<|im_start|>assistant\n")) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/zig/ricursive_reference.py b/tools/zig/ricursive_reference.py index c6aa7b0c10d..91dab02f3f2 100644 --- a/tools/zig/ricursive_reference.py +++ b/tools/zig/ricursive_reference.py @@ -8,11 +8,12 @@ import torch from safetensors import safe_open -USAGE = """usage: ricursive_reference.py MODEL_DIR tokens.json out.bin [--bf16-points | --release] +USAGE = """usage: ricursive_reference.py MODEL_DIR tokens.json out.bin [--bf16-points | --release | --release-f64] writes raw bf16 logits [positions, vocab]; an NVFP4 release's MLPs are its exact dequantized values (default) float64: bf16 weights cast up exactly, the release's arithmetic, one rounding at the end --bf16-points float64 rounded to bf16 at every point the release's bf16 forward rounds - --release the checkpoint's own modeling_ricursive.py layers in bf16 (bf16 releases only)""" + --release the checkpoint's own modeling_ricursive.py layers in bf16 (bf16 releases only) + --release-f64 those layers in float64, an NVFP4 release's MLPs as their exact dequantized values""" def bf16_once(x: np.ndarray) -> np.ndarray: @@ -50,7 +51,7 @@ def tensor(name): t0 = time.time() with torch.no_grad(): - h = release(model_dir, cfg, tensor, ids) if mode == "--release" else exact(cfg, tensor, ids, mode == "--bf16-points", index) + h = release(model_dir, cfg, tensor, ids, mode == "--release-f64") if mode.startswith("--release") else exact(cfg, tensor, ids, mode == "--bf16-points", index) head = tensor("lm_head.weight").to(h.dtype) with open(out, "wb") as f: for s in range(0, n, 64): @@ -133,8 +134,8 @@ def rotate(x): return norm(x, w("model.norm.weight")) -def release(model_dir, cfg, tensor, ids): - """The checkpoint's own decoder layers and norms in bf16, each layer's weights loaded alone.""" +def release(model_dir, cfg, tensor, ids, f64=False): + """The checkpoint's own decoder layers and norms in bf16 (or float64), each layer's weights loaded alone.""" sys.path.insert(0, model_dir) # its modeling file imports configuration_ricursive as a package sibling pkg = importlib.util.spec_from_file_location("ricursive_release", f"{model_dir}/modeling_ricursive.py", submodule_search_locations=[model_dir]) @@ -149,16 +150,16 @@ def release(model_dir, cfg, tensor, ids): sys.modules[spec_m.name] = mod spec_m.loader.exec_module(mod) config = conf.RicursiveConfig.from_pretrained(model_dir) - bf = torch.bfloat16 + bf = torch.float64 if f64 else torch.bfloat16 n = len(ids) - x = tensor("model.embed_tokens.weight")[torch.tensor(ids)].unsqueeze(0) * config.embed_scale + x = tensor("model.embed_tokens.weight")[torch.tensor(ids)].unsqueeze(0).to(bf) * config.embed_scale v0 = x position_ids = torch.arange(n).unsqueeze(0) t0 = time.time() for i in range(config.num_hidden_layers): layer = mod.RicursiveDecoderLayer(config, i).to(bf) prefix = f"model.layers.{i}." - state = {k[len(prefix):]: tensor(k) for k in index_names(model_dir, prefix)} + state = layer_state(tensor, index_names(model_dir, prefix), prefix, f64) layer.load_state_dict(state, strict=True) x = layer(x, position_ids=position_ids, value_residual=v0)[0] print(f"layer {i + 1} of {config.num_hidden_layers}, {time.time() - t0:.0f} s", flush=True) @@ -167,11 +168,23 @@ def release(model_dir, cfg, tensor, ids): return final(x)[0] +def layer_state(tensor, names, prefix, f64): + """A layer's weights by module name; in float64 an NVFP4 weight is its exact values and its scales are dropped.""" + have = set(names) + state = {} + for k in names: + if f64 and k.endswith((".weight_scale", ".weight_scale_2", ".input_scale")): + continue + nv = f64 and f"{k}_scale" in have + state[k[len(prefix):]] = nvfp4(tensor(k), tensor(f"{k}_scale"), tensor(f"{k}_scale_2")) if nv else tensor(k) + return state + + def index_names(model_dir, prefix): return [k for k in json.load(open(f"{model_dir}/model.safetensors.index.json"))["weight_map"] if k.startswith(prefix)] if __name__ == "__main__": - if len(sys.argv) not in (4, 5) or sys.argv[4:] not in ([], ["--bf16-points"], ["--release"]): + if len(sys.argv) not in (4, 5) or sys.argv[4:] not in ([], ["--bf16-points"], ["--release"], ["--release-f64"]): sys.exit(USAGE) main(*sys.argv[1:4], mode=sys.argv[4] if len(sys.argv) > 4 else "") diff --git a/tools/zig/test_drama_guidance_check.py b/tools/zig/test_drama_guidance_check.py index 412860989bb..9c691f8d987 100644 --- a/tools/zig/test_drama_guidance_check.py +++ b/tools/zig/test_drama_guidance_check.py @@ -1,4 +1,5 @@ -"""The guidance check's verdict and voice requirement, without a server or GPU.""" +"""The guidance check's verdict, voice requirement and pinned revision, without a server or GPU.""" +import argparse import copy import json from pathlib import Path @@ -9,7 +10,8 @@ def replies(names): - return {name: {"sha256": name, "bytes": 4, "first_audio_s": 0.1, "total_s": 0.2} for name in names} + return {name: {"sha256": name.removeprefix("solo-"), "bytes": 4, "first_audio_s": 0.1, "total_s": 0.2} + for name in names} def matching(): @@ -26,8 +28,15 @@ def test_equal_pcm_passes(self): def test_paired_that_differs_from_separate_fails(self): runs = matching() - runs[64]["paired"]["replies"]["lane-b"]["sha256"] = "other" - self.assertEqual(check.verdict(runs), ["rows=64 lane-b: paired PCM differs from separate"]) + runs[64]["paired"]["replies"]["t1-g3"]["sha256"] = "other" + self.assertEqual(check.verdict(runs), ["rows=64 t1-g3: paired PCM differs from separate"]) + + def test_a_concurrent_lane_that_differs_from_its_solo_run_fails(self): + runs = matching() + runs[1]["separate"]["replies"]["lane-a"]["sha256"] = "other" + runs[1]["paired"]["replies"]["lane-a"]["sha256"] = "other" + self.assertEqual(check.verdict(runs), ["rows=1 lane-a: separate concurrent PCM differs from its solo run", + "rows=1 lane-a: paired concurrent PCM differs from its solo run"]) def test_gamma_one_that_differs_from_plain_fails(self): runs = matching() @@ -74,5 +83,15 @@ def test_only_a_reference_backed_catalog_voice_is_accepted(self): check.require_reference(voices, voice) +class RevisionTests(unittest.TestCase): + def test_only_a_full_commit_sha_pins_a_checkpoint(self): + commit = "b2b5ee998034b2975720906c815e7fb0e9f007bd" + repo = "fishaudio/drama-3" + self.assertEqual(check.revision(f"{repo}@{commit}"), {"repo": repo, "commit": commit}) + for value in (f"{repo}@main", f"{repo}@{commit[:8]}", f"{repo}@{commit.upper()}", commit, f"@{commit}"): + with self.assertRaises(argparse.ArgumentTypeError, msg=value): + check.revision(value) + + if __name__ == "__main__": unittest.main() diff --git a/web/tests/test_server_access.py b/web/tests/test_server_access.py index 6cd4026cb23..a977f7a9983 100644 --- a/web/tests/test_server_access.py +++ b/web/tests/test_server_access.py @@ -3,8 +3,8 @@ from fastapi.testclient import TestClient from server_fixtures import _client, _echo, _mock -from tensorfold_web import engine as engine_mod from tensorfold_web import cli +from tensorfold_web import engine as engine_mod from tensorfold_web import settings as settings_mod from tensorfold_web.catalog import Catalog from tensorfold_web.engine import Engine, rates_from_counters diff --git a/zig/build/chunked_write.zig b/zig/build/chunked_write.zig new file mode 100644 index 00000000000..b1ba764de70 --- /dev/null +++ b/zig/build/chunked_write.zig @@ -0,0 +1,9 @@ +//! Registers the chunked-writer host tests as `test-chunked-write`. +const std = @import("std"); + +pub fn wire(b: *std.Build, parent: *std.Build.Step) void { + const tests = b.addTest(.{ .root_module = b.createModule(.{ .root_source_file = b.path("zig/src/core/chunked_write_test_file.zig"), .target = b.graph.host }) }); + const step = b.step("test-chunked-write", "Bounded chunked output writes: cap respected, order preserved, the old one-shot path fails the enforcing sink"); + step.dependOn(&b.addRunArtifact(tests).step); + parent.dependOn(step); +} diff --git a/zig/build/cuda.zig b/zig/build/cuda.zig index 672632eb411..3c5162e4524 100644 --- a/zig/build/cuda.zig +++ b/zig/build/cuda.zig @@ -98,10 +98,12 @@ pub fn targets(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.bu const mods = family(b, target, optimize, cuda, draft_ids); const cli = b.createModule(.{ .root_source_file = b.path("zig/src/cli/cuda_main.zig"), .target = target, .optimize = optimize, .link_libc = true, .strip = strip }); const native = engines(b, target, optimize, cuda, mods.core, mods.lanes, mods.nemotron, mods.heat, mods.qwen35, mods.qwen_vision); - for ([_]struct { []const u8, *std.Build.Module }{ .{ "cuda", cuda }, .{ "core", mods.core }, .{ "lanes", mods.lanes }, .{ "nemotron", mods.nemotron }, .{ "dory", native.engines.import_table.get("dory").? }, .{ "cluster", @import("cluster_cuda.zig").module(b, target, optimize, mods.lanes, mods.core, native.canon, native.verbs) } }) |m| cli.addImport(m[0], m[1]); + for ([_]struct { []const u8, *std.Build.Module }{ .{ "cuda", cuda }, .{ "core", mods.core }, .{ "lanes", mods.lanes }, .{ "nemotron", mods.nemotron }, .{ "dory", native.engines.import_table.get("dory").? }, .{ "cluster", @import("cluster_cuda.zig").module(b, target, optimize, mods.lanes, mods.core, native.canon, native.verbs) }, .{ "ricursive_cuda", native.engines.import_table.get("ricursive_cuda").? } }) |m| cli.addImport(m[0], m[1]); cli.addOptions("build_options", build_options); cli.addImport("checkpoint_cli", checkpointCli(b, target, optimize, strip, native.engines, mods.core)); - b.installArtifact(b.addExecutable(.{ .name = "tensorfold", .root_module = cli })); + const cli_exe = b.addExecutable(.{ .name = "tensorfold", .root_module = cli }); + b.installArtifact(cli_exe); + b.step("compile-cuda-cli", "Compile the CUDA tensorfold CLI without executing a GPU").dependOn(&cli_exe.step); const runner = b.createModule(.{ .root_source_file = b.path("zig/tests/cuda/main.zig"), .target = target, .optimize = optimize, .link_libc = true, .strip = strip }); const dump_options = b.addOptions(); dump_options.addOption(bool, "enabled", opts.test_dump); @@ -129,7 +131,7 @@ pub fn targets(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.bu @import("minimax_cuda.zig").targets(b, target, optimize, strip, cuda, mods.core, mods.lanes, runner); @import("inkling2.zig").targets(b, target, optimize, strip, cuda, mods.core, mods.lanes, runner); @import("idol_cuda.zig").targets(b, target, optimize, strip, cuda, mods.core, runner); - for ([_]struct { []const u8, *std.Build.Module }{ .{ "kolibri1", kolibri1Module(b, target, optimize, cuda, mods.core, mods.lanes) }, .{ "dory", @import("dory.zig").module(b, target, optimize, cuda, mods.core, mods.lanes) } }) |m| runner.addImport(m[0], m[1]); + for ([_]struct { []const u8, *std.Build.Module }{ .{ "kolibri1", kolibri1Module(b, target, optimize, cuda, mods.core, mods.lanes) }, .{ "dory", @import("dory.zig").module(b, target, optimize, cuda, mods.core, mods.lanes) }, .{ "ricursive_cuda", @import("ricursive_cuda.zig").module(b, target, optimize, cuda, mods.core, mods.lanes) } }) |m| runner.addImport(m[0], m[1]); runner.addImport("gemma4_cuda", @import("gemma4_cuda.zig").module(b, target, optimize, cuda, mods.core, mods.lanes)); runner.addImport("spark25", @import("spark25.zig").module(b, target, optimize, cuda, mods.core, mods.lanes)); // the served family and its engine, for the dots runner @@ -320,6 +322,7 @@ pub fn hostTests(b: *std.Build, draft_ids: *std.Build.Module, build_options: *st b.step("test-qwen-grants-host", "Qwen MTP head-cost and copy grants without a GPU").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = mods.qwen35, .filters = &.{"shared head costs:"} })).step); b.step("test-nemotron-grants-host", "Nemotron shared head-cost and copy grants without a GPU").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = mods.nemotron, .filters = &.{"Nemotron shared prices:"} })).step); b.step("test-nemotron-cuda-steps-host", "Nemotron CUDA's stepped prompt pass on the lanes, stopped before GPU work").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = mods.nemotron, .filters = &.{"nemotron cuda steps:"} })).step); + b.step("test-nemotron-wide-walk-host", "A 32-row Nemotron wide round through every row limit, without a GPU").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = mods.nemotron, .filters = &.{ "wide round walk:", "wide rounds:" } })).step); @import("rows_host.zig").tests(b, native_modules.api, step); const native = native_modules.engines; const prompt_rows = b.addRunArtifact(b.addTest(.{ .root_module = native, .filters = &.{ "CUDA startup:", "Qwen prompt rows:", "slide admission: cuda" } })); diff --git a/zig/build/cuda_contract_host.zig b/zig/build/cuda_contract_host.zig index 7b9349049f5..257060d9167 100644 --- a/zig/build/cuda_contract_host.zig +++ b/zig/build/cuda_contract_host.zig @@ -52,6 +52,15 @@ pub fn steps(b: *std.Build, host: std.Build.ResolvedTarget, cuda: *std.Build.Mod step.dependOn(&qsa_contract.step); flash_contract.dependOn(&qsa_contract.step); @import("cuda_window_host.zig").contracts(b, host, cuda, mods.core, step); + const moss_contract = b.addRunArtifact(b.addTest(.{ .root_module = b.createModule(.{ + .root_source_file = b.path("zig/tests/cuda/contract_moss_image_ref.zig"), + .target = host, + .optimize = .debug, + .link_libc = true, + .imports = &.{ .{ .name = "cuda", .module = cuda }, .{ .name = "core", .module = mods.core } }, + }) })); + b.step("test-moss-contract-host", "MOSS-Image contract references' float64 silu against fp32 expf, no GPU").dependOn(&moss_contract.step); + step.dependOn(&moss_contract.step); const reference_step = b.step("test-cuda-reference", "CUDA's FP64 comparison with CPU-only readback (no GPU)"); const projection_step = b.step("test-cuda-projection-fixture", "Projection fixture dispatch controls with CPU-only CUDA calls"); for ([_]std.builtin.OptimizeMode{ .debug, .fast }) |mode| { diff --git a/zig/build/cuda_engines.zig b/zig/build/cuda_engines.zig index 22f3c2d1f78..158f61eb95b 100644 --- a/zig/build/cuda_engines.zig +++ b/zig/build/cuda_engines.zig @@ -64,6 +64,7 @@ pub fn engines(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.bu const api = qwen35.import_table.get("engine_api").?; // family()'s, so the server and qwen3_5 share one const canon = canonModule(b, target, optimize); const verbs = @import("tp.zig").verbsModule(b, target, optimize); + const glm = glmCudaShared(b, target, optimize, cuda, core, lanes, heat, api, canon, verbs); const mod = b.createModule(.{ .root_source_file = b.path("zig/src/native/cuda.zig"), .target = target, @@ -78,7 +79,8 @@ pub fn engines(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.bu .{ .name = "lfm2", .module = lfm2Module(b, target, optimize, cuda, core) }, .{ .name = "core", .module = core }, .{ .name = "flashnext", .module = flashnextModule(b, target, optimize, cuda, core, lanes, qwen_vision, api) }, - .{ .name = "glm_cuda", .module = glmCudaShared(b, target, optimize, cuda, core, lanes, heat, api, canon, verbs) }, + .{ .name = "glm_cuda", .module = glm }, + .{ .name = "mesh", .module = glm.import_table.get("mesh").? }, // the launch resolver's, GLM's one instance .{ .name = "qwen3_cuda", .module = qwen3Module(b, target, optimize, cuda, core, lanes, api) }, .{ .name = "minimax_m3_cuda", .module = @import("minimax_cuda.zig").module(b, target, optimize, cuda, core, lanes) }, .{ .name = "qwen35", .module = qwen35 }, @@ -86,10 +88,12 @@ pub fn engines(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.bu .{ .name = "gemma4_cuda", .module = @import("gemma4_cuda.zig").module(b, target, optimize, cuda, core, lanes) }, .{ .name = "spark25", .module = @import("spark25.zig").module(b, target, optimize, cuda, core, lanes) }, .{ .name = "lfm2_moe_cuda", .module = @import("lfm2_moe_cuda.zig").module(b, target, optimize, cuda, core, lanes) }, + .{ .name = "inkling2", .module = @import("inkling2.zig").module(b, target, optimize, cuda, core, lanes) }, .{ .name = "dory", .module = @import("dory.zig").module(b, target, optimize, cuda, core, lanes) }, .{ .name = "woof", .module = @import("woof.zig").module(b, target, optimize, core) }, .{ .name = "dots_mocr_cuda", .module = @import("dots_mocr_cuda.zig").module(b, target, optimize, cuda, core, lanes, @import("cuda_dense.zig").module(b, target, optimize, cuda, core, lanes)) }, .{ .name = "muse_spark", .module = @import("muse.zig").moduleOver(b, target, optimize, cuda, core, lanes, @import("tp.zig").moduleWith(b, target, optimize, cuda, verbs)) }, + .{ .name = "ricursive_cuda", .module = @import("ricursive_cuda.zig").module(b, target, optimize, cuda, core, lanes) }, }, }); mod.addImport("qwen4", @import("qwen4.zig").module(b, target, optimize, core)); diff --git a/zig/build/cuda_family_host.zig b/zig/build/cuda_family_host.zig index 1046ed10c47..fac6adb107b 100644 --- a/zig/build/cuda_family_host.zig +++ b/zig/build/cuda_family_host.zig @@ -24,6 +24,7 @@ pub fn steps(b: *std.Build, cuda: *std.Build.Module, mods: anytype, step: *std.B @import("minimax_cuda.zig").hostTests(b, host, cuda, mods.core, mods.lanes, step); @import("idol_cuda.zig").hostTests(b, cuda, mods.core, step); @import("inkling2.zig").hostTests(b, host, cuda, mods.core, mods.lanes, step); + @import("ricursive_cuda.zig").hostTests(b, host, cuda, mods.core, mods.lanes, step); @import("cuda_groups_host.zig").host(b, cuda, mods, step); const prefill = b.addRunArtifact(b.addTest(.{ .root_module = mods.qwen35, .filters = &.{ "Qwen stepped prefill:", "Qwen whole prefill:", "Qwen prefill opening:", "a yielded pass keeps its completed prefix", "MTP suffix filtering", "MTP tap boundary", "partial tap capture", "qwen3_5 prompt tail:" } })); b.step("test-qwen35-prefill-host", "Stepped, whole, opening and interrupted prompt lifecycle without devices").dependOn(&prefill.step); diff --git a/zig/build/cuda_kernels.zig b/zig/build/cuda_kernels.zig index 2af39b4855f..e5e96219b6a 100644 --- a/zig/build/cuda_kernels.zig +++ b/zig/build/cuda_kernels.zig @@ -166,6 +166,12 @@ pub const kernels = [_]Kernel{ .{ .name = "inkling2_pattn", .src = "inkling2/prompt_attention", .flags = &.{"-O3"} }, // ours: Inkling 2's global-layer prompt attention .{ .name = "inkling2_ops", .src = "inkling2/ops", .flags = glue }, // ours: Inkling 2's residual mix, convs, router, SwiGLU .{ .name = "inkling2_rows", .src = "inkling2/rows", .flags = glue }, // ours: Inkling 2's router row dots on prompt rows + .{ .name = "ricursive", .flags = glue }, // ours: Ripple's glue (embed, add-norms, output gate, FFN activation), glue.metal step for step + .{ .name = "ricursive_prep", .flags = glue }, // ours: Ripple's attention prep (q/k head norms, RoPE, K and V into rings or pages) + .{ .name = "inkling2_experts", .src = "inkling2/experts", .flags = &.{ "-O3", "--expt-relaxed-constexpr" } }, // ours: Inkling 2's grouped experts + .{ .name = "inkling2_modelopt", .src = "inkling2/modelopt", .flags = &.{ "-O3", "--expt-relaxed-constexpr" } }, // Mini packed experts on BF16 activations + .{ .name = "inkling2_loop_math", .src = "inkling2/loop_math", .flags = &.{"-O3"} }, // Mini residuals, cross-pass messages, gates and split QKV + .{ .name = "inkling2_vision", .src = "inkling2/vision", .flags = glue }, // ours: Inkling 2's vision tower glue and attention .{ .name = "glm_quant", .flags = torch_ops }, // ours: GLM's draft-only weight quantizers, torch at load in the Python family .{ .name = "exl3_linear", .flags = &.{ "-O3", "--expt-relaxed-constexpr" } }, // exl3/linear.cu's device code, tensorfold_exl3_linear_v5 .{ .name = "exl3_experts", .flags = &.{ "-O3", "--expt-relaxed-constexpr" } }, // exl3/experts.cu's device code, tensorfold_exl3_experts diff --git a/zig/build/drama3_host.zig b/zig/build/drama3_host.zig index 73967f6074d..b12ef53bbb2 100644 --- a/zig/build/drama3_host.zig +++ b/zig/build/drama3_host.zig @@ -26,7 +26,7 @@ pub fn native(b: *std.Build, step: *std.Build.Step, family: *std.Build.Module, c if (family.import_table.get("metal")) |runtime| mod.addImport("metal", runtime); if (cuda) |c| mod.addImport("cuda", c); step.dependOn(&b.addObject(.{ .name = name, .root_module = mod }).step); - const tests = b.addTest(.{ .root_module = mod, .filters = &.{ "native silence guard:", "drama reference cache:", "drama admission:", "drama voice encode:" } }); + const tests = b.addTest(.{ .root_module = mod, .filters = &.{ "native silence guard:", "drama reference cache:", "drama voice encode:", "drama admission:" } }); step.dependOn(&b.addRunArtifact(tests).step); } diff --git a/zig/build/drama3_metal.zig b/zig/build/drama3_metal.zig index fcd8ad861aa..3d385d62275 100644 --- a/zig/build/drama3_metal.zig +++ b/zig/build/drama3_metal.zig @@ -40,6 +40,8 @@ pub fn metallib(b: *std.Build, metal_std: []const u8) std.Build.LazyPath { const cc = b.addSystemCommand(&.{ "xcrun", "-sdk", "macosx", "metal", b.fmt("-std={s}", .{metal_std}), "-fmetal-math-mode=safe", "-fmetal-math-fp32-functions=precise" }); cc.addPrefixedDirectoryArg("-I", b.path(dir)); cc.addFileInput(b.path(dir ++ "/d3_common.h")); + // codec.metal includes the shared u32 copy macros; a change there must rebuild its .air. + if (std.mem.eql(u8, name, "codec.metal")) cc.addFileInput(b.path("zig/kernels/metal/core/copy_u32.metal")); cc.addArg("-c"); cc.addFileArg(b.path(b.fmt("{s}/{s}", .{ dir, name }))); cc.addArg("-o"); diff --git a/zig/build/flashnext_batch_host.zig b/zig/build/flashnext_batch_host.zig index fa5bc89351b..13316a2dc58 100644 --- a/zig/build/flashnext_batch_host.zig +++ b/zig/build/flashnext_batch_host.zig @@ -1,6 +1,14 @@ //! Source and lane regressions with a recording Metal boundary, no shader compiler or GPU work. const std = @import("std"); pub fn tests(b: *std.Build, all: *std.Build.Step) void { + const admission = b.addRunArtifact(b.addTest(.{ .root_module = b.createModule(.{ .root_source_file = b.path("zig/flashnext_load_admission_cases.zig"), .target = b.graph.host, .link_libc = true }) })); + b.step("test-flashnext-load-admission", "CPU-only Flash Next runtime quantization admission").dependOn(&admission.step); + all.dependOn(&admission.step); + const review = b.addRunArtifact(b.addTest(.{ .root_module = b.createModule(.{ .root_source_file = b.path("zig/flashnext_ssd_review_test.zig"), .target = b.graph.host, .link_libc = true }) })); + b.step("test-flashnext-ssd-review-host", "SSD startup, cache and ownership regressions without a device").dependOn(&review.step); + all.dependOn(&review.step); + const metadata = b.addRunArtifact(b.addTest(.{ .root_module = b.createModule(.{ .root_source_file = b.path("zig/flashnext_ssd_review_test.zig"), .target = b.graph.host, .link_libc = true }), .filters = &.{"REV99 slot metadata"} })); + b.step("test-flashnext-ssd-metadata-host", "Forecast accounting preserves legacy pool receipt bytes").dependOn(&metadata.step); const rope = b.addRunArtifact(b.addTest(.{ .root_module = b.createModule(.{ .root_source_file = b.path("zig/src/families/flashnext/rope_refusal_test.zig"), .target = b.graph.host }) })); b.step("test-flashnext-rope-host", "The Metal/HIP config reader refuses scaled RoPE and keeps plain configs' rotary").dependOn(&rope.step); all.dependOn(&rope.step); @@ -9,6 +17,10 @@ pub fn tests(b: *std.Build, all: *std.Build.Step) void { all.dependOn(&fused_split.step); const memory = b.createModule(.{ .root_source_file = b.path("zig/src/families/flashnext/load_memory.zig"), .target = b.graph.host }); b.step("test-flashnext-memory-host", "Flash Next allocation floor and working-set refusal without shaders").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = memory })).step); + const bounded = b.createModule(.{ .root_source_file = b.path("zig/flashnext_ssd_budget_test.zig"), .target = b.graph.host, .link_libc = true }); + const bounded_run = b.addRunArtifact(b.addTest(.{ .root_module = bounded })); + b.step("test-flashnext-ssd-budget-host", "Refused SSD pools fit the unchanged ceiling with whole-layer capacity").dependOn(&bounded_run.step); + all.dependOn(&bounded_run.step); const metal = b.createModule(.{ .root_source_file = b.path("zig/flashnext_recording_metal.zig"), .target = b.graph.host }); const sources = b.createModule(.{ .root_source_file = b.path("zig/kernels/metal/sources.zig") }); const empty = b.addWriteFiles().add("flashnext-test-empty.zig", "pub const bytes = \"\";\n"); @@ -21,6 +33,7 @@ pub fn tests(b: *std.Build, all: *std.Build.Step) void { b.step("test-flashnext-single-session-host", "Single-slot backend admission and owned-snapshot restoration without a GPU").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = root, .filters = &.{"Flash Next constraint:"} })).step); b.step("test-flashnext-fsr-owner-host", "Actual FSR route/demand/forecast and failure ownership with a recording device").dependOn(&fsr_owner.step); all.dependOn(&fsr_owner.step); + b.step("test-flashnext-gx-shared-host", "Opt-in grouped shared rounds preserve the existing per-window gates without shaders").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = root, .filters = &.{"shared rounds opt into grouped experts"} })).step); const schedule_metal = b.createModule(.{ .root_source_file = b.path("zig/src/metal/metal.zig"), .target = b.graph.host }); const schedule = b.createModule(.{ .root_source_file = b.path("zig/flashnext_schedule_tests.zig"), .target = b.graph.host, .link_libc = true, .imports = &.{ .{ .name = "metal", .module = schedule_metal }, .{ .name = "kernel_sources", .module = sources }, .{ .name = "lanes", .module = lanes }, .{ .name = "fabric", .module = fabric } } }); if (b.graph.host.result.os.tag == .macos) schedule.linkSystemLibrary("objc", .{}); diff --git a/zig/build/gemma4_host.zig b/zig/build/gemma4_host.zig index 14bd54f2dce..12da787e857 100644 --- a/zig/build/gemma4_host.zig +++ b/zig/build/gemma4_host.zig @@ -32,6 +32,12 @@ pub fn tests(b: *std.Build, sources: *std.Build.Module) *std.Build.Step { const head_run = b.addRunArtifact(b.addTest(.{ .root_module = head_root })); head_run.has_side_effects = true; b.step("test-gemma4-prompt-head-host", "Last prompt-row and decode projection bindings against synthetic layer logits").dependOn(&head_run.step); + // Metal's prompt pass a chunk a call (#3021): its cuts, a decode between chunks, a drafter's taps, on a fake + const step_lanes = b.createModule(.{ .root_source_file = b.path("zig/src/core/lanes/lanes.zig"), .target = b.graph.host, .link_libc = true }); + const steps_root = b.createModule(.{ .root_source_file = b.path("zig/src/families/gemma4/prefill_steps.zig"), .target = b.graph.host, .imports = &.{.{ .name = "lanes", .module = step_lanes }} }); + const steps_run = b.addRunArtifact(b.addTest(.{ .root_module = steps_root, .filters = &.{"Gemma Metal steps:"} })); + steps_run.has_side_effects = true; + b.step("test-gemma4-metal-steps-host", "Gemma 4 Metal's stepped prompt pass on a recording fake, no GPU").dependOn(&steps_run.step); return family_step; } diff --git a/zig/build/glm_family_host.zig b/zig/build/glm_family_host.zig index aaa34c9ea3b..7c570d32de4 100644 --- a/zig/build/glm_family_host.zig +++ b/zig/build/glm_family_host.zig @@ -5,6 +5,7 @@ pub fn steps(b: *std.Build, cuda: *std.Build.Module, glm: *std.Build.Module, mod // GLM CUDA's startup watcher (named phases, a warning while NCCL init or a load blocks), from cuda.zig's room b.step("test-startup-watch-host", "Blocked startup phase warnings without a driver or communicator").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = cuda, .filters = &.{"startup watcher:"} })).step); const host = b.graph.host; + @import("glm_wide_expert_host.zig").steps(b, cuda, glm, mods.core, step); const pdl = b.addRunArtifact(b.addTest(.{ .root_module = glm, .filters = &.{"GLM PDL policy:"} })); b.step("test-glm-pdl-policy-host", "GLM PDL environment and compute-capability launch policy without a GPU").dependOn(&pdl.step); step.dependOn(&pdl.step); diff --git a/zig/build/glm_wide_expert_host.zig b/zig/build/glm_wide_expert_host.zig new file mode 100644 index 00000000000..2401b1fb71a --- /dev/null +++ b/zig/build/glm_wide_expert_host.zig @@ -0,0 +1,12 @@ +//! GLM wide expert production dispatch and strict counted environment checks without CUDA. +const std = @import("std"); +pub fn steps(b: *std.Build, cuda: *std.Build.Module, glm: *std.Build.Module, core: *std.Build.Module, all: *std.Build.Step) void { + const root = b.createModule(.{ .root_source_file = b.path("zig/glm_wide_expert_host.zig"), .target = b.graph.host, .optimize = .debug, .link_libc = true, .imports = &.{ .{ .name = "glm", .module = glm }, .{ .name = "glm_cuda", .module = glm }, .{ .name = "cuda", .module = cuda }, .{ .name = "core", .module = core } } }); + const run = b.addRunArtifact(b.addTest(.{ .root_module = root })); + b.step("test-glm-wide-expert-host", "Actual expert down dispatch and byte contract fixtures without a GPU").dependOn(&run.step); + all.dependOn(&run.step); + const env = b.addRunArtifact(b.addTest(.{ .root_module = glm, .filters = &.{ "GLM strict env:", "GLM cost identity:" } })); + env.has_side_effects = true; + b.step("test-glm-wide-expert-env-host", "Count every GLM environment row and exercise the wide expert reader").dependOn(&env.step); + all.dependOn(&env.step); +} diff --git a/zig/build/hip.zig b/zig/build/hip.zig index 1df64746c45..5f2fed3ec87 100644 --- a/zig/build/hip.zig +++ b/zig/build/hip.zig @@ -311,7 +311,7 @@ fn checksExe(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.buil .target = target, .optimize = optimize, .link_libc = true, - .imports = &.{ .{ .name = "hip", .module = e.hip }, .{ .name = "qwen3_5", .module = e.family }, .{ .name = "lanes", .module = e.lanes }, .{ .name = "npy", .module = b.createModule(.{ .root_source_file = b.path("zig/npy_from_core.zig"), .target = target, .optimize = optimize, .imports = &.{.{ .name = "core", .module = e.hip.import_table.get("core").? }} }) } }, + .imports = &.{ .{ .name = "hip", .module = e.hip }, .{ .name = "core", .module = e.hip.import_table.get("core").? }, .{ .name = "qwen3_5", .module = e.family }, .{ .name = "lanes", .module = e.lanes }, .{ .name = "npy", .module = b.createModule(.{ .root_source_file = b.path("zig/npy_from_core.zig"), .target = target, .optimize = optimize, .imports = &.{.{ .name = "core", .module = e.hip.import_table.get("core").? }} }) } }, }) }); } fn clefExe(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, e: Engine) *std.Build.Step.Compile { @@ -501,6 +501,8 @@ const groups = [_]Source{ .{ .path = "qwen_vision.hip", .strict = true }, .{ .path = "draft/draft.hip" }, .{ .path = "exl3/exl3.hip" }, + .{ .path = "decode/plan_rows.hip" }, + .{ .path = "inkling2/attention.hip", .strict = true }, }; /// What the group sources include, so an edit to one rebuilds them. const headers = [_][]const u8{ @@ -511,7 +513,7 @@ const headers = [_][]const u8{ "tiles/gemm.hpp", "tiles/gemm_kp.hpp", "tiles/matrix_gemm.hpp", "tiles/matrix_item.hpp", "tiles/plan.hpp", "tiles/stream.hpp", "flashnext/streams.hpp", "flashnext/ngram.hpp", "flashnext/indexer.hpp", "flashnext/sparse.hpp", "ops/nemotron_moe.hpp", "quant/bf16_decoder.hpp", "quant/dense_tiles.hpp", "tiles/wmma12_gemm.hpp", "tiles/wmma12_gemm_k32_ref.hpp", "ops/columns.hpp", "columns_controls.hpp", "ops/vision.hpp", - "ops/dense_text.hpp", "ops/vl_position.hpp", "flashnext/sparse_lanes.hpp", "tiles/wmma12_step.hpp", + "ops/dense_text.hpp", "ops/vl_position.hpp", "flashnext/sparse_lanes.hpp", "tiles/wmma12_step.hpp", "inkling2/tile.hpp", }; /// The flags of the kernels' first build: no contraction, wave32 on RDNA, C++20. const flags = [_][]const u8{ "-D__HIP_PLATFORM_AMD__=1", "-DUSE_ROCM=1", "-DHIPBLAS_V2", "-fPIC", "-DCUDA_HAS_FP16=1", "-DHIP_ENABLE_WARP_SYNC_BUILTINS=1", "-std=c++20", "-fno-gpu-rdc", "-mno-wavefrontsize64", "-ffp-contract=off" }; diff --git a/zig/build/hip_contract.zig b/zig/build/hip_contract.zig index fc39a8c866c..12b277c4ef2 100644 --- a/zig/build/hip_contract.zig +++ b/zig/build/hip_contract.zig @@ -46,6 +46,18 @@ pub fn steps(b: *std.Build, o: Options) void { }) })); b.step("test-lighton-hip-contract-host", "Independent LightOn HIP contract references without a device").dependOn(&lighton_ref.step); o.test_step.dependOn(&lighton_ref.step); + const ink_plan = b.addRunArtifact(b.addTest(.{ .root_module = inkling2(b, b.graph.host, .Debug, o.host) })); + const ink_layout = b.addRunArtifact(b.addTest(.{ .root_module = b.createModule(.{ + .root_source_file = b.path("zig/tests/hip/contract_inkling2_fill.zig"), + .target = b.graph.host, + .optimize = .Debug, + .imports = &.{ .{ .name = "core", .module = o.host.import_table.get("core").? }, .{ .name = "inkling2_hip", .module = inkling2(b, b.graph.host, .Debug, o.host) } }, + }) })); + const ink_step = b.step("test-inkling2-hip-host", "Inkling 2's HIP attention plan and contract layouts without a device"); + for ([_]*std.Build.Step{ &ink_plan.step, &ink_layout.step }) |st| { + ink_step.dependOn(st); + o.test_step.dependOn(st); + } const source = b.path("zig/kernels/hip/contract_controls.hip"); const own = hip.compile(b, o.hipcc, o.arch, source, "contract_controls.hsaco"); const exe = runner(b, o.target, o.optimize, o.gpu, o.lighton_gpu, controls(b, o.arch, own)); @@ -81,6 +93,12 @@ pub fn steps(b: *std.Build, o: Options) void { b.step("check-hip-kernel-contract-host", "Compile the complete HIP contract registry with inert kernels").dependOn(&host_runner.step); } +/// Inkling 2's HIP attention launches over the HIP backend `hip_mod`. +fn inkling2(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, hip_mod: *std.Build.Module) *std.Build.Module { + const root = b.path("zig/src/families/inkling2/hip_attention.zig"); + return b.createModule(.{ .root_source_file = root, .target = target, .optimize = optimize, .imports = &.{.{ .name = "hip", .module = hip_mod }} }); +} + /// The controls' code object as the `hip_controls` module (empty without hipcc). fn controls(b: *std.Build, arch: []const u8, object: ?std.Build.LazyPath) *std.Build.Module { const files = b.addWriteFiles(); @@ -119,6 +137,7 @@ fn runner( .{ .name = "hip_controls", .module = ctl }, .{ .name = "glm_ocr_ops", .module = ocr_ops }, .{ .name = "lighton_ocr", .module = lighton_mod }, + .{ .name = "inkling2_hip", .module = inkling2(b, target, optimize, hip_mod) }, .{ .name = "qwen_hip_vision", .module = @import("lighton_hip.zig").vision(b, target, optimize, hip_mod, hip_mod.import_table.get("core").?, lighton_mod.import_table.get("lanes").?, lighton_mod.import_table.get("hip_serve").?) }, }, }) }); diff --git a/zig/build/host_ci.zig b/zig/build/host_ci.zig index 2c6747d399b..f973ad9b148 100644 --- a/zig/build/host_ci.zig +++ b/zig/build/host_ci.zig @@ -171,10 +171,14 @@ const linux_host = [_][]const u8{ "test-flashnext-proposal-pack-host", "test-flashnext-rotary-bound-host", "test-flashnext-single-session-host", + "test-flashnext-ssd-budget-host", + "test-flashnext-ssd-review-host", + "test-flashnext-load-admission", "test-flashnext-vision-contracts-host", "test-flashnext-vision-memory-host", "test-gemma4-config", "test-gemma4-load-parts-host", + "test-gemma4-metal-steps-host", "test-gemma4-owners-host", "test-gemma4-prompt-head-host", "test-glm-dflash-host", @@ -282,7 +286,6 @@ const macos_adapters = [_][]const u8{ "test-drama-metal-quant-host", "test-exl3", "test-flashnext-driver-host", - "test-flashnext-load-admission", "test-flashnext-pack-cache", "test-gguf-linux-compile", "test-h3-modulation-bf16", @@ -317,6 +320,9 @@ const macos_deepseek = [_][]const u8{ }; const macos_fast = [_][]const u8{ + "test-flashnext-load-admission", + "test-flashnext-ssd-budget-host", + "test-flashnext-ssd-review-host", "check-qwen27-speed-host", "test-cluster-membership-host", "test-glm-disk-charge-host", diff --git a/zig/build/inkling2_host.zig b/zig/build/inkling2_host.zig index 423dd15b0fc..21e7aa23356 100644 --- a/zig/build/inkling2_host.zig +++ b/zig/build/inkling2_host.zig @@ -4,9 +4,31 @@ const std = @import("std"); fn module(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, root: []const u8) *std.Build.Module { const m = b.createModule(.{ .root_source_file = b.path(root), .target = target, .optimize = optimize, .link_libc = true }); const dir = "zig/src/core/"; - m.addImport("tokenizer", b.createModule(.{ .root_source_file = b.path(dir ++ "tokenizer/tokenizer.zig"), .target = target, .optimize = optimize, .link_libc = true })); - m.addImport("safetensors", b.createModule(.{ .root_source_file = b.path(dir ++ "safetensors.zig"), .target = target, .optimize = optimize, .link_libc = true })); + const tokenizer = b.createModule(.{ .root_source_file = b.path(dir ++ "tokenizer/tokenizer.zig"), .target = target, .optimize = optimize, .link_libc = true }); + m.addImport("tokenizer", tokenizer); + const core = b.createModule(.{ .root_source_file = b.path(dir ++ "root.zig"), .target = target, .optimize = optimize, .link_libc = true }); + core.addImport("gpu_memory", @import("gpu_memory.zig").module(b, target)); + core.addImport("tokenizer", tokenizer); + core.addImport("living", b.createModule(.{ .root_source_file = b.path("zig/src/living/living.zig"), .target = target, .optimize = optimize, .link_libc = true })); + m.addImport("core", core); m.addImport("template", b.createModule(.{ .root_source_file = b.path(dir ++ "template/template.zig"), .target = target, .optimize = optimize, .link_libc = true })); + m.addImport("inkling2_metal", b.createModule(.{ .root_source_file = b.path("zig/kernels/metal/inkling2_sources.zig"), .target = target, .optimize = optimize })); + const metal = b.createModule(.{ .root_source_file = b.path("zig/src/metal/metal.zig"), .target = target, .optimize = optimize }); + if (target.result.os.tag == .macos) { + metal.linkFramework("Metal", .{}); + metal.linkFramework("Foundation", .{}); + metal.linkSystemLibrary("objc", .{}); + } + m.addImport("metal", metal); + m.addImport("kernel_sources", b.createModule(.{ .root_source_file = b.path("zig/kernels/metal/sources.zig"), .target = target, .optimize = optimize })); + const inkling2_metal_ref = b.createModule(.{ .root_source_file = b.path("zig/src/families/inkling2/metal/ref.zig"), .target = target, .optimize = optimize }); + inkling2_metal_ref.addImport("metal", m.import_table.get("metal").?); + m.addImport("inkling2_metal_ref", inkling2_metal_ref); + m.addImport("inkling2_glue_plan", b.createModule(.{ .root_source_file = b.path("zig/src/families/inkling2/metal/glue_plan.zig"), .target = target, .optimize = optimize })); + m.addImport("inkling2_loop_plan", b.createModule(.{ .root_source_file = b.path("zig/src/families/inkling2/metal/loop_plan.zig"), .target = target, .optimize = optimize })); + const lanes = b.createModule(.{ .root_source_file = b.path(dir ++ "lanes/lanes.zig"), .target = target, .optimize = optimize, .link_libc = true }); + m.addImport("lanes", lanes); + m.addImport("engine_api", b.createModule(.{ .root_source_file = b.path(dir ++ "engine_api.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{.{ .name = "lanes", .module = lanes }} })); return m; } @@ -14,4 +36,15 @@ pub fn tests(b: *std.Build, target: std.Build.ResolvedTarget, test_step: *std.Bu const run = b.addRunArtifact(b.addTest(.{ .root_module = module(b, target, .Debug, "zig/src/families/inkling2/host_test.zig") })); b.step("test-inkling2-host", "Inkling 2 family package: config, weight map, layer plan, chat template and tokenizer").dependOn(&run.step); test_step.dependOn(&run.step); + + // The metal module reaches Darwin-only std.c, so this test runs on macOS only, like main's Metal steps. + if (target.result.os.tag == .macos) { + const metal_run = b.addRunArtifact(b.addTest(.{ .root_module = module(b, target, .Debug, "zig/src/inkling2_metal_host_test.zig") })); + b.step("test-inkling2-metal-host", "Inkling 2 Mini Metal launch plans and arithmetic references").dependOn(&metal_run.step); + test_step.dependOn(&metal_run.step); + } + const native = b.addObject(.{ .name = "inkling2-native", .root_module = module(b, target, .Debug, "zig/inkling2_native_compile.zig") }); + _ = native.getEmittedBin(); + b.step("compile-inkling2-native-host", "Analyze the actual Inkling 2 Mini native opener without shaders or devices").dependOn(&native.step); + test_step.dependOn(&native.step); } diff --git a/zig/build/kernel_contract.zig b/zig/build/kernel_contract.zig index 5c3948dc47b..99e325c737d 100644 --- a/zig/build/kernel_contract.zig +++ b/zig/build/kernel_contract.zig @@ -28,6 +28,20 @@ pub fn hostTests(b: *std.Build, family: *std.Build.Step) void { }) })); b.step("test-qwen27-paged-contract-host", "Paged prompt source controls, shuffled pages and boundary witnesses without a device").dependOn(&q27_pages.step); step.dependOn(&q27_pages.step); + const inkling_controls = b.addRunArtifact(b.addTest(.{ .root_module = b.createModule(.{ + .root_source_file = b.path("zig/tests/contract/metal_inkling2_controls_host.zig"), + .target = b.graph.host, + .optimize = .debug, + .imports = &.{ + .{ .name = "contract", .module = module(b, b.graph.host, .debug) }, + .{ .name = "inkling2_metal", .module = b.createModule(.{ .root_source_file = b.path("zig/kernels/metal/inkling2_sources.zig") }) }, + .{ .name = "inkling2_glue_plan", .module = b.createModule(.{ .root_source_file = b.path("zig/src/families/inkling2/metal/glue_plan.zig") }) }, + .{ .name = "inkling2_loop_plan", .module = b.createModule(.{ .root_source_file = b.path("zig/src/families/inkling2/metal/loop_plan.zig") }) }, + .{ .name = "inkling2_runtime_plan", .module = b.createModule(.{ .root_source_file = b.path("zig/src/families/inkling2/metal/runtime_plan.zig") }) }, + }, + }) })); + b.step("test-inkling2-controls-host", "Inkling 2 Mini source controls plant one fault without a Metal compiler").dependOn(&inkling_controls.step); + step.dependOn(&inkling_controls.step); const mapping_stub = b.createModule(.{ .root_source_file = b.path("zig/tests/contract/metal_mapping_host.zig") }); const llama_controls = b.addRunArtifact(b.addTest(.{ .root_module = b.createModule(.{ .root_source_file = b.path("zig/tests/contract/metal_llama_controls.zig"), @@ -57,19 +71,23 @@ pub fn hostTests(b: *std.Build, family: *std.Build.Step) void { .{ .name = "metal", .module = mapping_stub }, .{ .name = "kernel_sources", .module = mapping_stub }, } }); - const mapping = b.addRunArtifact(b.addTest(.{ .root_module = b.createModule(.{ + const mapping_root = b.createModule(.{ .root_source_file = b.path("zig/tests/contract/metal_mapping_test.zig"), .target = b.graph.host, .optimize = .debug, .imports = &.{ .{ .name = "contract", .module = module(b, b.graph.host, .debug) }, + .{ .name = "inkling2_metal", .module = b.createModule(.{ .root_source_file = b.path("zig/kernels/metal/inkling2_sources.zig") }) }, .{ .name = "metal", .module = mapping_stub }, .{ .name = "tensorfold", .module = mapping_tf }, .{ .name = "kernel_sources", .module = mapping_stub }, }, - }) })); + }); + const mapping = b.addRunArtifact(b.addTest(.{ .root_module = mapping_root })); mapping.has_side_effects = true; b.step("test-metal-launch-map-host", "Every registered Metal launch maps without a device or shader compiler").dependOn(&mapping.step); + const dspark_mapping = b.addRunArtifact(b.addTest(.{ .root_module = mapping_root, .filters = &.{"Metal launch map: every DSpark"} })); + b.step("test-inkling2-launch-map-host", "Every Inkling DSpark launch resolves without other families' device checks").dependOn(&dspark_mapping.step); step.dependOn(&mapping.step); const precision = b.addRunArtifact(b.addTest(.{ .root_module = b.createModule(.{ .root_source_file = b.path("zig/src/core/attention_precision.zig"), @@ -134,6 +152,9 @@ pub fn metal(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.buil @import("rotary_sweep.zig").steps(b, target, metal_mod); const image = @import("h3_image_contract.zig").sources(b); @import("ling_forward.zig").steps(b, target, optimize, metal_mod, sources, kimi_metallib); + const inkling2_metal = engine.import_table.get("inkling2_metal").?; + const inkling2_glue_plan = engine.import_table.get("inkling2_glue_plan").?; + const inkling2_loop_plan = engine.import_table.get("inkling2_loop_plan").?; const exe = b.addExecutable(.{ .name = "tf-kernel-contract", .root_module = b.createModule(.{ .root_source_file = b.path("zig/tests/contract/metal_main.zig"), .target = target, @@ -151,6 +172,10 @@ pub fn metal(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.buil .{ .name = "ling_metal", .module = b.createModule(.{ .root_source_file = b.path("zig/kernels/metal/ling/sources.zig") }) }, .{ .name = "ling_route", .module = b.createModule(.{ .root_source_file = b.path("zig/src/families/ling/route.zig") }) }, .{ .name = "masked_sources", .module = b.createModule(.{ .root_source_file = b.path("zig/masked_value_sources.zig"), .imports = &.{.{ .name = "kernel_sources", .module = sources }} }) }, + .{ .name = "inkling2_metal", .module = inkling2_metal }, + .{ .name = "inkling2_glue_plan", .module = inkling2_glue_plan }, + .{ .name = "inkling2_loop_plan", .module = inkling2_loop_plan }, + .{ .name = "inkling2_runtime_plan", .module = b.createModule(.{ .root_source_file = b.path("zig/src/families/inkling2/metal/runtime_plan.zig") }) }, }, }) }); const install = b.addInstallArtifact(exe, .{}); diff --git a/zig/build/lane_halt_host.zig b/zig/build/lane_halt_host.zig index 72a12f2d463..5b2308768f5 100644 --- a/zig/build/lane_halt_host.zig +++ b/zig/build/lane_halt_host.zig @@ -4,6 +4,9 @@ const std = @import("std"); pub fn steps(b: *std.Build) void { const lanes = b.createModule(.{ .root_source_file = b.path("zig/src/core/lanes/lanes.zig"), .target = b.graph.host, .optimize = .debug, .link_libc = true }); b.step("test-lone-copy-host", "Lone-copy pricing and all existing lane depth/verification regressions without devices").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = lanes })).step); + b.step("test-metal-cost-host", "Metal window timing and retained-price healing without devices").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = lanes, .filters = &.{"Metal window prices:"} })).step); + b.step("test-metal-cost-review-host", "Warm-budget and tile-edge regression controls without devices").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = lanes, .filters = &.{"Metal review:"} })).step); + @import("metal_cost_host.zig").steps(b, lanes); const api = b.createModule(.{ .root_source_file = b.path("zig/src/core/engine_api.zig"), .target = b.graph.host, .optimize = .debug, .link_libc = true, .imports = &.{.{ .name = "lanes", .module = lanes }} }); const interrupted = b.createModule(.{ .root_source_file = b.path("zig/src/core/lane_host_interrupted_test.zig"), .target = b.graph.host, .optimize = .debug, .link_libc = true, .imports = &.{.{ .name = "lanes", .module = lanes }} }); b.step("test-lane-interrupted-host", "Interrupted prompt retention and clean retries without devices").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = interrupted, .filters = &.{"interrupted prefill:"} })).step); @@ -14,6 +17,7 @@ pub fn steps(b: *std.Build) void { const explore = b.createModule(.{ .root_source_file = b.path("zig/src/core/lane_host_explore_test.zig"), .target = b.graph.host, .optimize = .debug, .link_libc = true, .imports = &.{.{ .name = "lanes", .module = lanes }} }); explore.addOptions("explore_options", seeds); b.step("test-lane-explore-host", "Lane host invariants under seeded arrivals, cancels, room and pressure, without devices").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = explore, .filters = &.{"explore:"} })).step); + b.step("test-lanes-sampler-launch-host", "A Metal sampler launch of many rows binds each row's one-row bytes, without devices").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = lanes, .filters = &.{"sampler launch:"} })).step); b.step("test-lane-invariance-host", "Batch-composition token, stop and RNG-position invariance with a fake target").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = lanes, .filters = &.{"lane invariance:"} })).step); const safe_lanes = b.createModule(.{ .root_source_file = b.path("zig/src/core/lanes/lanes.zig"), .target = b.graph.host, .optimize = .safe, .link_libc = true }); const strand = b.createModule(.{ .root_source_file = b.path("zig/src/core/lane_host_strand_test.zig"), .target = b.graph.host, .optimize = .safe, .link_libc = true, .imports = &.{.{ .name = "lanes", .module = safe_lanes }} }); diff --git a/zig/build/lane_status_host.zig b/zig/build/lane_status_host.zig new file mode 100644 index 00000000000..3e4b6d28574 --- /dev/null +++ b/zig/build/lane_status_host.zig @@ -0,0 +1,10 @@ +//! CPU check for issue 3200: a status read holds no lane-host lock, so a monitoring client cannot stall a decode round. +const std = @import("std"); + +pub fn steps(b: *std.Build) void { + const lanes = b.createModule(.{ .root_source_file = b.path("zig/src/core/lanes/lanes.zig"), .target = b.graph.host, .optimize = .debug, .link_libc = true }); + const api = b.createModule(.{ .root_source_file = b.path("zig/src/core/engine_api.zig"), .target = b.graph.host, .optimize = .debug, .link_libc = true, .imports = &.{.{ .name = "lanes", .module = lanes }} }); + const lock = b.createModule(.{ .root_source_file = b.path("zig/src/core/lane_host_status_lock_test.zig"), .target = b.graph.host, .optimize = .debug, .link_libc = true, .imports = &.{.{ .name = "lanes", .module = lanes }} }); + b.step("test-lane-status-host", "A status read parks without the lane host's lock (issue 3200)").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = lock, .filters = &.{"status:"} })).step); + _ = api; +} diff --git a/zig/build/ling_host.zig b/zig/build/ling_host.zig index 5706cc8e41c..a89ddee5fd0 100644 --- a/zig/build/ling_host.zig +++ b/zig/build/ling_host.zig @@ -1,4 +1,4 @@ -//! Ling family host checks: config, weight map, fixtures and synth JSON. No CUDA, no Metal, no GPU. +//! Ling family host checks: config, weight map, fixtures, synth JSON and the CPU GGUF reader. No GPU. const std = @import("std"); pub fn tests(b: *std.Build, target: std.Build.ResolvedTarget, test_step: *std.Build.Step) void { @@ -9,4 +9,28 @@ pub fn tests(b: *std.Build, target: std.Build.ResolvedTarget, test_step: *std.Bu const run = b.addRunArtifact(b.addTest(.{ .root_module = root })); b.step("test-ling-host", "Ling family package: config, names, tiny fixtures, synth JSON, grouped routing, KDA mixer, MLA RoPE and mixer").dependOn(&run.step); test_step.dependOn(&run.step); + const weights = b.createModule(.{ .root_source_file = b.path("zig/src/core/cpu_weights.zig"), .target = target }); + const cpu = b.createModule(.{ + .root_source_file = b.path("zig/src/families/ling/cpu.zig"), + .target = target, + .imports = &.{.{ .name = "core", .module = weights }}, + }); + const cpu_run = b.addRunArtifact(b.addTest(.{ .root_module = cpu })); + b.step("test-ling-cpu-host", "Ling CPU GGUF reader: names, views, metadata refusals, exact Q4_K/Q6_K/Q5_0 decode and projections").dependOn(&cpu_run.step); + test_step.dependOn(&cpu_run.step); + const release_weights = b.createModule(.{ .root_source_file = b.path("zig/src/core/cpu_weights.zig"), .target = target, .optimize = .ReleaseSafe }); + const release_cpu = b.createModule(.{ + .root_source_file = b.path("zig/src/families/ling/cpu.zig"), + .target = target, + .optimize = .ReleaseSafe, + .imports = &.{.{ .name = "core", .module = release_weights }}, + }); + const decode = b.addExecutable(.{ .name = "ling-cpu-decode", .root_module = b.createModule(.{ + .root_source_file = b.path("zig/tests/ling_cpu_decode.zig"), + .target = target, + .optimize = .ReleaseSafe, + .imports = &.{.{ .name = "ling_cpu", .module = release_cpu }}, + }) }); + b.step("tf-ling-cpu-decode", "Greedy Ling-3.0-tiny decode on the CPU from the Q4_K_M GGUF and prompt token IDs") + .dependOn(&b.addInstallArtifact(decode, .{}).step); } diff --git a/zig/build/metal_cost_host.zig b/zig/build/metal_cost_host.zig new file mode 100644 index 00000000000..8bf258e5cee --- /dev/null +++ b/zig/build/metal_cost_host.zig @@ -0,0 +1,28 @@ +//! Execute the real family timing policies without loading Metal devices or shaders. +const std = @import("std"); +pub fn steps(b: *std.Build, lanes: *std.Build.Module) void { + const metal = b.createModule(.{ .root_source_file = b.path("zig/src/metal/metal.zig"), .target = b.graph.host }); + inline for (.{ "nemotron", "glm" }) |family| { + const m = b.createModule(.{ .root_source_file = b.path("zig/" ++ family ++ "_metal_timing_host.zig"), .target = b.graph.host, .optimize = .debug, .link_libc = true, .imports = &.{ .{ .name = "lanes", .module = lanes }, .{ .name = "metal", .module = metal } } }); + b.step("test-" ++ family ++ "-metal-timing-host", "Actual " ++ family ++ " timing-controller host tests").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = m })).step); + } +} + +pub fn compile(b: *std.Build, draft_ids: *std.Build.Module) void { + const target = if (b.graph.host.result.os.tag == .macos) b.graph.host else b.resolveTargetQuery(.{ .cpu_arch = .aarch64, .os_tag = .macos }); + const metal = b.createModule(.{ .root_source_file = b.path("zig/src/metal/metal.zig"), .target = target, .link_libc = true }); + const lanes = b.createModule(.{ .root_source_file = b.path("zig/src/core/lanes/lanes.zig"), .target = target, .link_libc = true }); + const living = b.createModule(.{ .root_source_file = b.path("zig/src/living/living.zig"), .target = target, .link_libc = true }); + const sources = b.createModule(.{ .root_source_file = b.path("zig/kernels/metal/sources.zig") }); + const fabric = b.createModule(.{ .root_source_file = b.path("zig/src/fabric/fabric.zig"), .target = target, .link_libc = true, .imports = &.{.{ .name = "verbs", .module = @import("tp.zig").verbsModule(b, target, .debug) }} }); + const engine = b.createModule(.{ .root_source_file = b.path("zig/src/tensorfold.zig"), .target = target, .optimize = .debug, .link_libc = true, .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "lanes", .module = lanes }, .{ .name = "living", .module = living }, .{ .name = "kernel_sources", .module = sources }, .{ .name = "fabric", .module = fabric }, .{ .name = "nemotron_draft_ids", .module = draft_ids } } }); + _ = @import("qwen27.zig").engineModules(b, target, metal, sources, engine); + engine.addImport("engram_hash_core", b.createModule(.{ .root_source_file = b.path("zig/src/families/deepseek_v41/engram_hash.zig"), .target = target })); + const empty = b.addWriteFiles().add("cost-compile-only.metallib", ""); + sources.addImport("nemotron_packed_metallib", @import("metal_targets.zig").embedded(b, empty, "nemotron_packed.metallib")); + const api = b.createModule(.{ .root_source_file = b.path("zig/src/core/engine_api.zig"), .target = target, .link_libc = true, .imports = &.{.{ .name = "lanes", .module = lanes }} }); + const root = b.createModule(.{ .root_source_file = b.path("zig/metal_cost_compile.zig"), .target = target, .optimize = .debug, .link_libc = true, .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "tensorfold", .module = engine }, .{ .name = "engine_api", .module = api } } }); + const object = b.addObject(.{ .name = "metal-cost-adapters", .root_module = root }); + _ = object.getEmittedBin(); + b.step("check-metal-cost-adapters-host", "Compile actual Metal cost adapter bodies as a Darwin object without linking or GPU execution").dependOn(&object.step); +} diff --git a/zig/build/metal_image_programs.zig b/zig/build/metal_image_programs.zig index 132cb30609c..05d1a8f4171 100644 --- a/zig/build/metal_image_programs.zig +++ b/zig/build/metal_image_programs.zig @@ -18,4 +18,5 @@ pub const rows = [_]Program{ .{ .name = "tf-idol-decode", .path = "zig/tests/idol_decode.zig", .about = "Idol's octree and Gaussian decoders on a reference case: each level, the rows and the PLY gated, then timed" }, .{ .name = "tf-idol-vae", .path = "zig/tests/idol_vae.zig", .about = "Idol's image encoder on a reference case: its condition rows gated against float64 beside the SDK's, then timed" }, .{ .name = "tf-idol-dino", .path = "zig/tests/idol_dino.zig", .about = "Idol's DINOv3 image encoder on a reference case: feature1 and each block gated against torch's, then timed" }, + .{ .name = "tf-idol-generate", .path = "zig/tests/idol_generate.zig", .about = "Idol end to end: one preprocessed picture to a 3DGS PLY and camera through both encoders, the denoiser and the decoders, timed by stage" }, }; diff --git a/zig/build/metal_server.zig b/zig/build/metal_server.zig index a7ecdee845e..45e4e3d4ed9 100644 --- a/zig/build/metal_server.zig +++ b/zig/build/metal_server.zig @@ -87,7 +87,9 @@ pub fn nativeServer(b: *std.Build, target: std.Build.ResolvedTarget, optimize: s golden_build.step(b, target, server_tests, api, tokenizer, template, engines); engines.addImport("lanes", api.import_table.get("lanes").?); b.step("test-draft-metal-host", "Metal draft source metadata without devices").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = engines, .filters = &.{"draft sources:"} })).step); + b.step("test-qwen35-chunk-startup-metal-host", "Qwen3.5 Metal startup refuses bad TF_QWEN35_CHUNK before checkpoint load").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = engines, .filters = &.{"qwen35 startup: TF_QWEN35_CHUNK refuses before the checkpoint loader runs"} })).step); b.step("test-drafter-skip-metal-host", "Counted shared draft skips without device execution").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = engine, .filters = &.{"zero grant:"} })).step); + b.step("test-gemma4-metal-vtable-host", "Gemma 4 Metal steps its prompt passes (#3021), without devices").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = engine, .filters = &.{"Gemma Metal steps:"} })).step); b.step("test-uocr", "Unlimited-OCR-2's tests (its kernels compile on this GPU)").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = engine, .filters = &.{"uocr:"} })).step); const embed_host = b.step("test-qwen3-metal-host", "Qwen3 Metal embedding geometry, batch bounds and native refusals without GPU work"); const embed_air = b.addSystemCommand(&.{ "xcrun", "-sdk", "macosx", "metal", b.fmt("-std={s}", .{mlxMetalStd(b)}), "-fno-fast-math", "-c" }); @@ -100,7 +102,16 @@ pub fn nativeServer(b: *std.Build, target: std.Build.ResolvedTarget, optimize: s const flint_draft_host = b.step("test-flint-draft-host", "Flint draft config, taps and first-token metadata without devices"); for ([_]*std.Build.Module{ engine, api.import_table.get("lanes").? }) |module| flint_draft_host.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = module, .filters = &.{"Flint DFlash2"} })).step); - b.step("test-native", "The Metal engines module's host-side tests").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = engines })).step); + const native_tests = b.step("test-native", "The Metal engines module's host-side tests"); + native_tests.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = engines })).step); + const capabilities = b.createModule(.{ .root_source_file = b.path("zig/src/native/inkling2_capabilities_test.zig"), .target = target, .optimize = .Debug, .link_libc = true }); + for (engines.import_table.keys(), engines.import_table.values()) |name, module| capabilities.addImport(name, module); + capabilities.addImport("native_metal", engines); + const capability_run = b.addRunArtifact(b.addTest(.{ .root_module = capabilities })); + const capability_step = b.step("test-inkling2-metal-capabilities", "Inkling native Metal checkpoint-format capabilities"); + capability_step.dependOn(&capability_run.step); + native_tests.dependOn(capability_step); + test_step.?.dependOn(&capability_run.step); const reuse = b.addExecutable(.{ .name = "tf-flashnext-reuse", .root_module = b.createModule(.{ .root_source_file = b.path("zig/tests/flashnext_reuse.zig"), .target = target, diff --git a/zig/build/metal_source_lists.zig b/zig/build/metal_source_lists.zig index fc9646dffaf..29099917e5b 100644 --- a/zig/build/metal_source_lists.zig +++ b/zig/build/metal_source_lists.zig @@ -1,8 +1,8 @@ /// Our Metal sources, compiled into one metallib that executables embed. pub const kernels = [_][]const u8{ "zig/kernels/metal/runtime_tests.metal", - "zig/kernels/metal/nemotron_expert_up.metal", - "zig/kernels/metal/nemotron_expert_down.metal", + "zig/kernels/metal/nemotron/expert_up.metal", + "zig/kernels/metal/nemotron/expert_down.metal", "zig/kernels/metal/nemotron/add_norm_moe_xs.metal", // for the hand-authored <4096,512,1> (add_norm_moe_xs_bolt) instantiation }; diff --git a/zig/build/metal_targets.zig b/zig/build/metal_targets.zig index 7e3a1470207..f54ed54cfe6 100644 --- a/zig/build/metal_targets.zig +++ b/zig/build/metal_targets.zig @@ -99,6 +99,7 @@ pub fn metalTargets(b: *std.Build, target: std.Build.ResolvedTarget, optimize: s // The engines registry: the families this platform's binaries serve; the CLI reads it for models/info/pull. const api = b.createModule(.{ .root_source_file = b.path("zig/src/core/engine_api.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{.{ .name = "lanes", .module = mods.lanes }} }); + mods.engine.addImport("engine_api", api); const engines = b.createModule(.{ .root_source_file = b.path("zig/src/native/metal.zig"), .target = target, @@ -107,6 +108,9 @@ pub fn metalTargets(b: *std.Build, target: std.Build.ResolvedTarget, optimize: s .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "engine_api", .module = api }, .{ .name = "tensorfold", .module = mods.engine } }, }); engines.addImport("living", mods.living); + engines.addImport("kernel_sources", mods.sources); + inline for ([_][]const u8{ "inkling2_metal", "inkling2_metal_ref", "inkling2_glue_plan", "inkling2_loop_plan" }) |name| + engines.addImport(name, mods.engine.import_table.get(name).?); const drama3_lib = drama3_build.metallib(b, metal_std); b.getInstallStep().dependOn(&b.addInstallFile(drama3_lib, "lib/drama3.metallib").step); const drama3_embed = if (shaders) drama3_lib else no_shaders; @@ -210,15 +214,6 @@ pub fn metalTargets(b: *std.Build, target: std.Build.ResolvedTarget, optimize: s .link_libc = true, }) }); test_step.dependOn(&b.addRunArtifact(pack_cases).step); - const load_admission_cases = b.addTest(.{ .root_module = b.createModule(.{ - .root_source_file = b.path("zig/flashnext_load_admission_cases.zig"), - .target = target, - .optimize = optimize, - .link_libc = true, - }) }); - const load_admission_run = b.addRunArtifact(load_admission_cases); - b.step("test-flashnext-load-admission", "CPU-only Flash Next runtime quantization admission").dependOn(&load_admission_run.step); - test_step.dependOn(&load_admission_run.step); const pack_cache_cases = b.addTest(.{ .root_module = b.createModule(.{ .root_source_file = b.path("zig/flashnext_pack_cache_cases.zig"), .target = target, @@ -470,6 +465,11 @@ pub fn metalEngineModules(b: *std.Build, target: std.Build.ResolvedTarget, optim const fabric = b.createModule(.{ .root_source_file = b.path("zig/src/fabric/fabric.zig"), .target = target, .optimize = optimize, .link_libc = true }); fabric.addImport("verbs", @import("tp.zig").verbsModule(b, target, optimize)); const sources = b.createModule(.{ .root_source_file = b.path("zig/kernels/metal/sources.zig") }); + const inkling2_metal = b.createModule(.{ .root_source_file = b.path("zig/kernels/metal/inkling2_sources.zig"), .target = target, .optimize = optimize }); + const inkling2_metal_ref = b.createModule(.{ .root_source_file = b.path("zig/src/families/inkling2/metal/ref.zig"), .target = target, .optimize = optimize }); + inkling2_metal_ref.addImport("metal", metal); + const inkling2_glue_plan = b.createModule(.{ .root_source_file = b.path("zig/src/families/inkling2/metal/glue_plan.zig"), .target = target, .optimize = optimize }); + const inkling2_loop_plan = b.createModule(.{ .root_source_file = b.path("zig/src/families/inkling2/metal/loop_plan.zig"), .target = target, .optimize = optimize }); // Living Weights' family-neutral learner, which Nemotron's lessons and the server's view of them share const living = b.createModule(.{ .root_source_file = b.path("zig/src/living/living.zig"), .target = target, .optimize = optimize, .link_libc = true }); const engine = b.createModule(.{ @@ -479,6 +479,10 @@ pub fn metalEngineModules(b: *std.Build, target: std.Build.ResolvedTarget, optim .link_libc = true, .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "kernel_sources", .module = sources }, .{ .name = "nemotron_draft_ids", .module = draft_ids }, .{ .name = "lanes", .module = lanes }, .{ .name = "fabric", .module = fabric }, .{ .name = "living", .module = living } }, }); + engine.addImport("inkling2_metal", inkling2_metal); + engine.addImport("inkling2_metal_ref", inkling2_metal_ref); + engine.addImport("inkling2_glue_plan", inkling2_glue_plan); + engine.addImport("inkling2_loop_plan", inkling2_loop_plan); engine.addImport("engram_hash_core", b.createModule(.{ .root_source_file = b.path("zig/src/families/deepseek_v41/engram_hash.zig"), .target = target, .optimize = optimize })); engine.addImport("config_number", b.createModule(.{ .root_source_file = b.path("zig/src/families/deepseek_v41/config_number.zig") })); return .{ .metal = metal, .lanes = lanes, .fabric = fabric, .sources = sources, .engine = engine, .living = living, .qwen27 = qwen27_build.engineModules(b, target, metal, sources, engine) }; @@ -494,8 +498,12 @@ pub fn distMetalServer(b: *std.Build, target: std.Build.ResolvedTarget, draft_id m.metal.addLibraryPath(b.graph.cwdRelativePath(b.pathJoin(&.{ sdk, "usr/lib" }))); m.metal.addSystemIncludePath(b.graph.cwdRelativePath(b.pathJoin(&.{ sdk, "usr/include" }))); const api = b.createModule(.{ .root_source_file = b.path("zig/src/core/engine_api.zig"), .target = target, .optimize = .fast, .link_libc = true, .imports = &.{.{ .name = "lanes", .module = m.lanes }} }); + m.engine.addImport("engine_api", api); const engines = b.createModule(.{ .root_source_file = b.path("zig/src/native/metal.zig"), .target = target, .optimize = .fast, .link_libc = true, .imports = &.{ .{ .name = "metal", .module = m.metal }, .{ .name = "engine_api", .module = api }, .{ .name = "tensorfold", .module = m.engine } } }); engines.addImport("living", m.living); + engines.addImport("kernel_sources", m.sources); + inline for ([_][]const u8{ "inkling2_metal", "inkling2_metal_ref", "inkling2_glue_plan", "inkling2_loop_plan" }) |name| + engines.addImport(name, m.engine.import_table.get(name).?); drama3_build.addNative(b, target, .fast, m.metal, engines, drama3_build.metallib(b, mlxMetalStd(b))); engines.addImport("kimi_k3", kimiModule(b, target, .fast, m.metal, m.engine, m.lanes)); engines.addImport("kimi_metallib", embedded(b, kimiMetallib(b, &flags), "kimi.metallib")); diff --git a/zig/build/minimax_cuda.zig b/zig/build/minimax_cuda.zig index 8c597ab0a34..e83a76e3478 100644 --- a/zig/build/minimax_cuda.zig +++ b/zig/build/minimax_cuda.zig @@ -34,4 +34,8 @@ pub fn hostTests(b: *std.Build, host: std.Build.ResolvedTarget, cuda: *std.Build const hold = b.addRunArtifact(b.addTest(.{ .root_module = b.createModule(.{ .root_source_file = b.path("zig/src/families/minimax_m3/hold_batch.zig"), .target = host, .optimize = .debug }) })); b.step("test-minimax-m3-hold-host", "MiniMax-M3 Metal drafters' stacked hold layout, no GPU").dependOn(&hold.step); all.dependOn(&hold.step); + // the Metal backend's timed rounds as lane facts: no device code, so it runs beside the family's other host tests + const costs = b.addRunArtifact(b.addTest(.{ .root_module = b.createModule(.{ .root_source_file = b.path("zig/src/families/minimax_m3/round_costs.zig"), .target = host, .optimize = .debug, .imports = &.{.{ .name = "lanes", .module = lanes }} }) })); + b.step("test-minimax-m3-costs-host", "MiniMax-M3 Metal's timed round widths as the lanes price them, no GPU").dependOn(&costs.step); + all.dependOn(&costs.step); } diff --git a/zig/build/qwen27.zig b/zig/build/qwen27.zig index 7d512b681ff..258762bbff3 100644 --- a/zig/build/qwen27.zig +++ b/zig/build/qwen27.zig @@ -24,8 +24,11 @@ pub fn engineModules(b: *std.Build, target: std.Build.ResolvedTarget, metal: *st var index: []const u8 = ""; for (parts) |part| { _ = files.addCopyFile(b.path(b.fmt("zig/kernels/metal/qwen27/{s}.metal", .{part})), b.fmt("{s}.metal", .{part})); - index = b.fmt("{s}pub const {s} = @embedFile(\"{s}.metal\");\n", .{ index, part, part }); + // The prompt kernels' pick comes from core: its macro heads attention_prompt. + const head = if (std.mem.eql(u8, part, "attention_prompt")) "@embedFile(\"prompt_pick.metal\") ++ " else ""; + index = b.fmt("{s}pub const {s} = {s}@embedFile(\"{s}.metal\");\n", .{ index, part, head, part }); } + _ = files.addCopyFile(b.path("zig/kernels/metal/core/prompt_pick.metal"), "prompt_pick.metal"); _ = files.addCopyFile(b.path("zig/kernels/metal/core/deltanet.metal"), "gdn.metal"); _ = files.addCopyFile(b.path("zig/kernels/metal/core/deltanet_slots.metal"), "gdn_slots.metal"); const bf16_topk = b.createModule(.{ .root_source_file = b.path("zig/src/core/bf16_topk.zig"), .target = target, .optimize = .ReleaseSafe }); @@ -102,7 +105,7 @@ pub fn targets(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.bu const qwen_core = b.createModule(.{ .root_source_file = b.path("zig/qwen27_core.zig"), .target = target, .optimize = .ReleaseSafe, .link_libc = true, .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "tokenizer", .module = b.createModule(.{ .root_source_file = b.path("zig/src/core/tokenizer/tokenizer.zig"), .target = target, .optimize = .ReleaseSafe, .link_libc = true }) } } }); const qwen27 = b.createModule(.{ .root_source_file = b.path("zig/src/families/qwen27/qwen27.zig"), .target = target, .optimize = .ReleaseSafe, .link_libc = true, .imports = &.{ .{ .name = "core", .module = qwen_core }, .{ .name = "metal", .module = metal } } }); for ([_]struct { []const u8, *std.Build.Module }{ .{ "core", qwen_core }, .{ "core_lane", core_lane }, .{ "core_row", core_row }, .{ "bf16_topk", s.bf16_topk }, .{ "bf16_topk_gpu", s.bf16_topk_gpu }, .{ "tree_round", s.tree_round }, .{ "tree_round_gpu", s.tree_round_gpu }, .{ "tree_commit_gpu", s.tree_commit }, .{ "draft_ops", s.draft_ops }, .{ "kernel_sources", sources } }) |m| qwen_core.addImport(m[0], m[1]); - for ([_]struct { []const u8, *std.Build.Module }{ .{ "core_lane", core_lane }, .{ "qwen_runtime_sources", s.runtime_sources }, .{ "core_delta", s.delta }, .{ "qwen_gdn_source", s.gdn_source }, .{ "kernel_sources", sources } }) |m| qwen27.addImport(m[0], m[1]); + for ([_]struct { []const u8, *std.Build.Module }{ .{ "core_lane", core_lane }, .{ "qwen_runtime_sources", s.runtime_sources }, .{ "core_delta", s.delta }, .{ "qwen_gdn_source", s.gdn_source }, .{ "kernel_sources", sources }, .{ "bf16_topk", s.bf16_topk } }) |m| qwen27.addImport(m[0], m[1]); for ([_]*std.Build.Module{ s.bf16_topk, s.tree_round, s.draft_ops }) |m| test_step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = m })).step); const family: []const std.Build.Module.Import = &.{ .{ .name = "qwen27", .module = qwen27 }, .{ .name = "core", .module = qwen_core }, .{ .name = "metal", .module = metal } }; @@ -124,7 +127,8 @@ pub fn targets(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.bu _ = program(b, "tf-qwen27-widths", "Build the projections at every oQ width before tensor units: float64, row windows, mixed stacks, embedding", "zig/tests/qwen27/widths.zig", target, false, engine_only); _ = program(b, "tf-qwen27-dflash-refine", "Build the drafter refinement probe (top-1 by block position, masked versus given)", "zig/tests/qwen27/dflash_refine.zig", target, false, engine_only); - const api = b.createModule(.{ .root_source_file = b.path("zig/src/core/engine_api.zig"), .target = target, .optimize = .ReleaseSafe, .link_libc = true, .imports = &.{.{ .name = "lanes", .module = lanes }} }); + // the engine's own engine_api when it has one, so a tool importing both holds the file in one module + const api = engine.import_table.get("engine_api") orelse b.createModule(.{ .root_source_file = b.path("zig/src/core/engine_api.zig"), .target = target, .optimize = .ReleaseSafe, .link_libc = true, .imports = &.{.{ .name = "lanes", .module = lanes }} }); const host = b.createModule(.{ .root_source_file = b.path("zig/src/native/qwen27_served.zig"), .target = target, .optimize = .ReleaseSafe, .link_libc = true, .imports = &.{ .{ .name = "engine_api", .module = api }, .{ .name = "metal", .module = metal }, .{ .name = "tensorfold", .module = engine } } }); const served: []const std.Build.Module.Import = &.{ .{ .name = "tensorfold", .module = engine }, .{ .name = "metal", .module = metal }, .{ .name = "engine_api", .module = api }, .{ .name = "qwen27_served", .module = host } }; _ = program(b, "tf-qwen27-speed-served", "Build long secondary-slot prompt and shared drafting checks", "zig/tests/qwen27/speed_served.zig", target, false, served); diff --git a/zig/build/qwen27_host.zig b/zig/build/qwen27_host.zig index fc94f0bd218..15d417a603f 100644 --- a/zig/build/qwen27_host.zig +++ b/zig/build/qwen27_host.zig @@ -14,7 +14,12 @@ pub fn tests(b: *std.Build, test_step: *std.Build.Step) void { b.step("test-qwen27-pass-metrics-host", "Pass timing and forwarding allocator without a GPU").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = metrics })).step); const mtp_flags = b.addRunArtifact(b.addTest(.{ .root_module = b.createModule(.{ .root_source_file = b.path("zig/src/native/qwen27_mtp_flags.zig"), .target = b.graph.host }) })); test_step.dependOn(&mtp_flags.step); - b.step("test-qwen27-mtp-flags-host", "--mtp-drafts and --mtp-confidence refusals on a Mac without a GPU").dependOn(&mtp_flags.step); + const mtp_topk = b.createModule(.{ .root_source_file = b.path("zig/src/core/bf16_topk.zig"), .target = b.graph.host }); + const mtp_pick = b.addRunArtifact(b.addTest(.{ .root_module = b.createModule(.{ .root_source_file = b.path("zig/src/families/qwen27/mtp_pick.zig"), .target = b.graph.host, .imports = &.{.{ .name = "bf16_topk", .module = mtp_topk }} }) })); + test_step.dependOn(&mtp_pick.step); + const mtp_host = b.step("test-qwen27-mtp-flags-host", "--mtp-drafts refusals, the GPU pick's tie rule and the fused absorb's order without a GPU"); + mtp_host.dependOn(&mtp_flags.step); + mtp_host.dependOn(&mtp_pick.step); const window = b.createModule(.{ .root_source_file = b.path("zig/src/native/qwen27_window.zig"), .target = b.graph.host }); const taps = b.createModule(.{ .root_source_file = b.path("zig/src/families/qwen27/tap_gather.zig"), .target = b.graph.host }); const pricing_lanes = b.createModule(.{ .root_source_file = b.path("zig/src/core/lanes/lanes.zig"), .target = b.graph.host }); @@ -97,6 +102,8 @@ pub fn compileHost(b: *std.Build, metal: *std.Build.Module, engine: *std.Build.M b.step("test-qwen27-reply-cache-host", "Served reply keeps retain a reusable history within the cache caps").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = host, .filters = &.{ "qwen27 reply cache:", "a reply's end keeps its prompt's born" } })).step); const startup_test = b.addTest(.{ .root_module = host, .filters = &.{"qwen27 startup:"} }); const startup_step = b.step("test-qwen27-startup-host", "Startup draft stream counts and suffixes without a GPU"); + const costs = b.createModule(.{ .root_source_file = b.path("zig/src/native/qwen27_costs.zig"), .target = b.graph.host, .link_libc = true, .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "tensorfold", .module = engine } } }); + startup_step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = costs, .filters = &.{"qwen27 startup:"} })).step); for ([_]?[]const u8{ null, "1" }) |value| { const run = b.addRunArtifact(startup_test); if (value) |v| run.setEnvironmentVariable("TF_Q27_DRAFT_SLOTS", v) else run.removeEnvironmentVariable("TF_Q27_DRAFT_SLOTS"); diff --git a/zig/build/request_access_host.zig b/zig/build/request_access_host.zig new file mode 100644 index 00000000000..09c3e757228 --- /dev/null +++ b/zig/build/request_access_host.zig @@ -0,0 +1,14 @@ +//! Request-driven web access regressions use canned DNS and pure URL/address/redirect policies. +const std = @import("std"); +pub fn steps(b: *std.Build, all: *std.Build.Step) void { + const one = b.createModule(.{ .root_source_file = b.path("zig/request_access_host.zig"), .target = b.graph.host, .optimize = .debug, .link_libc = true }); + const regression = b.addRunArtifact(b.addTest(.{ .root_module = one, .filters = &.{"request access audit:"} })); + regression.has_side_effects = true; + b.step("test-request-access-host", "Actual web client DNS deadline and queue admission without network").dependOn(®ression.step); + all.dependOn(®ression.step); + const policy = b.createModule(.{ .root_source_file = b.path("zig/request_access_policy_host.zig"), .target = b.graph.host, .optimize = .debug, .link_libc = true }); + const names = &.{ "public addresses only", "redirect locations resolve against the page", "a link whose ends are a newline", "a tab or newline wrapped inside", "a link that only replaces the query", "a relative link's dot segments", "request lines stay plain", "local and private names are refused", "security: cloud platform virtual", "security: request credentials", "security: an unschedulable fetch" }; + const rules = b.addRunArtifact(b.addTest(.{ .root_module = policy, .filters = names })); + b.step("test-request-access-policy-host", "Existing web URL, address, origin and redirect policies without network").dependOn(&rules.step); + all.dependOn(&rules.step); +} diff --git a/zig/build/residency_host.zig b/zig/build/residency_host.zig index ce870335006..aee7efdd993 100644 --- a/zig/build/residency_host.zig +++ b/zig/build/residency_host.zig @@ -15,6 +15,7 @@ pub fn steps(b: *std.Build) void { const api = b.createModule(.{ .root_source_file = b.path("zig/src/core/engine_api.zig"), .target = b.graph.host, .link_libc = true, .imports = &.{.{ .name = "lanes", .module = lanes }} }); const fit = b.createModule(.{ .root_source_file = b.path("zig/src/native/cache_fit.zig"), .target = b.graph.host, .link_libc = true, .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "engine_api", .module = api } } }); b.step("test-cache-fit-host", "Prompt-cache budgets, load ceilings and host memory counts without devices").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = fit })).step); + b.step("test-cache-maximum-host", "Automatic cache maximum with and without OS readings").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = fit, .filters = &.{"cache maximum:"} })).step); const fabric = b.createModule(.{ .root_source_file = b.path("zig/src/fabric/fabric.zig"), .target = b.graph.host, .link_libc = true }); fabric.addImport("verbs", @import("tp.zig").verbsModule(b, b.graph.host, .debug)); const sources = b.createModule(.{ .root_source_file = b.path("zig/kernels/metal/sources.zig") }); diff --git a/zig/build/ricursive_cuda.zig b/zig/build/ricursive_cuda.zig new file mode 100644 index 00000000000..d2a73446985 --- /dev/null +++ b/zig/build/ricursive_cuda.zig @@ -0,0 +1,18 @@ +//! Ripple's CUDA backend in the build: its module for tf-cuda-test and the native server, and its host regressions. +const std = @import("std"); + +/// The Ripple CUDA family over the runtime, the core and the lane core. +pub fn module(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, cuda: *std.Build.Module, core: *std.Build.Module, lanes: *std.Build.Module) *std.Build.Module { + const m = b.createModule(.{ .root_source_file = b.path("zig/src/families/ricursive/cuda.zig"), .target = target, .optimize = optimize, .link_libc = true }); + m.addImport("cuda", cuda); + m.addImport("core", core); + m.addImport("lanes", lanes); + return m; +} + +/// The family's host regressions (launch geometry, layout, names, packing, admission) in `all`. +pub fn hostTests(b: *std.Build, host: std.Build.ResolvedTarget, cuda: *std.Build.Module, core: *std.Build.Module, lanes: *std.Build.Module, all: *std.Build.Step) void { + const run = b.addRunArtifact(b.addTest(.{ .root_module = module(b, host, .debug, cuda, core, lanes) })); + b.step("test-ricursive-cuda-host", "Ripple's CUDA backend host regressions (no GPU work)").dependOn(&run.step); + all.dependOn(&run.step); +} diff --git a/zig/build/server.zig b/zig/build/server.zig index 12af7e0ae2d..c8f7e67d5a3 100644 --- a/zig/build/server.zig +++ b/zig/build/server.zig @@ -3,6 +3,7 @@ const std = @import("std"); /// The web launcher uses fake PATH tools and no model, network or device. pub fn webHostTests(b: *std.Build, all: *std.Build.Step) void { + @import("request_access_host.zig").steps(b, all); const tests = b.addTest(.{ .root_module = b.createModule(.{ .root_source_file = b.path("zig/src/server/web_cli.zig"), .target = b.graph.host, @@ -161,6 +162,10 @@ pub fn toolHostTests(b: *std.Build, parser: *std.Build.Module, server: *std.Buil deepseek.has_side_effects = true; all.dependOn(&deepseek.step); b.step("test-server-deepseek-chat-host", "Native DeepSeek prompt goldens, provenance and missing-template HTTP refusal").dependOn(&deepseek.step); + const inkling = b.addRunArtifact(b.addTest(.{ .root_module = server, .filters = &.{ "Inkling 2 reply:", "Inkling 2 parse:" } })); + inkling.has_side_effects = true; + all.dependOn(&inkling.step); + b.step("test-server-inkling2-reply-host", "Inkling 2 native reply split, tools and default-model isolation without devices").dependOn(&inkling.step); const quoted = b.addRunArtifact(b.addTest(.{ .root_module = server, .filters = &.{"quoted markers:"} })); quoted.has_side_effects = true; // reads TF_TOKENIZER_DIRS on every run b.step("test-quoted-markers-host", "Quoted added-token spellings through the chat route with TF_TOKENIZER_DIRS' tokenizers").dependOn("ed.step); diff --git a/zig/cost_rule_cases.zig b/zig/cost_rule_cases.zig index a9a2a43aa07..3b30fcb3670 100644 --- a/zig/cost_rule_cases.zig +++ b/zig/cost_rule_cases.zig @@ -5,20 +5,3 @@ test { _ = @import("src/core/lanes/cost_rule.zig"); _ = @import("src/core/lanes/cost_cache.zig"); } - -test "Nemotron initial and drift passes share interleaved head sampling; the 27B remains headless" { - const source = @embedFile("src/families/nemotron/timing.zig"); - const start = std.mem.indexOf(u8, source, "pub fn measure(").?; - const end = std.mem.indexOfPos(u8, source, start, "/// Windows past").?; - const body = source[start..end]; - try std.testing.expect(std.mem.indexOf(u8, body, "measure(windows, heads, &ms, head_ms, false)") != null); - try std.testing.expect(std.mem.indexOf(u8, body, "measure(windows, heads, &ms, head_ms, true)") != null); - try std.testing.expect(std.mem.indexOf(u8, body, "if (b.head != null) &head[0] else null") != null); - try std.testing.expect(std.mem.indexOf(u8, body, "drifted(&head, &r.head)") != null); - try std.testing.expect(std.mem.indexOf(u8, body, "fastest(heads") == null); - const qwen = @embedFile("src/native/qwen27_lanes.zig"); - const costs = @embedFile("src/native/qwen27_costs.zig"); // the 27B's window timing moved here with #1686 - try std.testing.expect(std.mem.indexOf(u8, costs, "cost_rule.fastest(timer, i)") != null); - try std.testing.expect(std.mem.indexOf(u8, qwen, "cost_rule.measure(") == null); - try std.testing.expect(std.mem.indexOf(u8, costs, "cost_rule.measure(") == null); -} diff --git a/zig/dense_serving_test.zig b/zig/dense_serving_test.zig index 57f1499bc9f..6bfdfd2b9cf 100644 --- a/zig/dense_serving_test.zig +++ b/zig/dense_serving_test.zig @@ -18,8 +18,8 @@ test "dense serving: owned CUDA images retain their reviewed lane and decode byt try std.testing.expectEqualStrings("8780fd710be3ce2f04e53fa1e69eb062809d3bec6391d9bd49983d0588e374d0", &hash(group)); // #2825 hoists copy addresses before the K loop; copy order and math match prefill_kernel. try std.testing.expectEqualStrings("e3724114b87cae6f6f761b2f86357f05b1693d84a0233e4d58ce46349fa853f6", &hash(@embedFile("kernels/cuda/qmm_prefill.cu"))); - // join variant's tf_q35_attn_rows_join for shared pages keeps SASS; #4706 adds TF_QWEN_PDL prologues (default off) - try std.testing.expectEqualStrings("12cb39dc09ba9e00fec8837739091cc2f305092043b0c92e23e0300c987c9ad3", &hash(@embedFile("kernels/cuda/qwen35.cu"))); + // KIA14 adds all_rows (false keeps selection/arithmetic); #4706 adds default-off TF_QWEN_PDL prologues + try std.testing.expectEqualStrings("79e97b0992f82e891ff8a80cdad68b534e07606b98feef3dffe25101477c99e1", &hash(@embedFile("kernels/cuda/qwen35.cu"))); // #1879's bytes: a comment names cuda_scratch.zig, where max_chunks moved; the code is unchanged try std.testing.expectEqualStrings("f9e4a040cf219aac8db211df25d264dba390fce4a7e8da45557652c6ff0f28ba", &hash(@embedFile("kernels/cuda/qwen35.cuh"))); // 67711a6aa7's bytes: the opt-in DSpine draft kernels (#2633); default serving unchanged diff --git a/zig/flashnext_batch_tests.zig b/zig/flashnext_batch_tests.zig index ea73dd3d949..dc93a1b6384 100644 --- a/zig/flashnext_batch_tests.zig +++ b/zig/flashnext_batch_tests.zig @@ -1,4 +1,5 @@ test { + _ = @import("src/families/flashnext/gx.zig"); _ = @import("src/families/flashnext/backend.zig"); _ = @import("src/families/flashnext/single_session_test.zig"); } diff --git a/zig/flashnext_load_guard_test.zig b/zig/flashnext_load_guard_test.zig new file mode 100644 index 00000000000..8a6b5a30d4e --- /dev/null +++ b/zig/flashnext_load_guard_test.zig @@ -0,0 +1,80 @@ +//! Source wiring guard: all load entries reach the final selected-settings admission before construction. +const std = @import("std"); + +const Sources = struct { + loader: []const u8 = @embedFile("src/families/flashnext/engine_load.zig"), + engine: []const u8 = @embedFile("src/families/flashnext/engine.zig"), + single: []const u8 = @embedFile("src/native/flashnext_host.zig"), + batch: []const u8 = @embedFile("src/native/flashnext_batch_host.zig"), +}; + +fn has(source: []const u8, text: []const u8) bool { + return std.mem.indexOf(u8, source, text) != null; +} + +/// A delegation-only entry must not gain a second statement that can bypass the guarded callee. +fn delegates(source: []const u8, entry: []const u8, call: []const u8) bool { + const start = std.mem.indexOf(u8, source, entry) orelse return false; + const sig = std.mem.indexOfPos(u8, source, start, "!*Engine {") orelse return false; + const begin = sig + "!*Engine {".len; + const end = @min(std.mem.indexOfPos(u8, source, begin, "\n }") orelse source.len, std.mem.indexOfPos(u8, source, begin, "\n}") orelse source.len); + if (end == source.len) return false; + return std.mem.eql(u8, std.mem.trim(u8, source[begin..end], " \r\n\t"), call); +} + +pub fn guarded(s: Sources) bool { + if (!delegates(s.engine, "pub fn load(", "return loadWith(gpa, io, model_dir, dump_dir, null);")) return false; + if (!has(s.engine, "pub const loadWith = @import(\"engine_load.zig\").loadWith;")) return false; + if (!has(s.engine, "pub const loadConfigured = @import(\"engine_load.zig\").loadConfigured;")) return false; + if (!delegates(s.loader, "pub fn loadWith(", "return loadConfigured(gpa, io, model_dir, dump_dir, speed_up, .{});")) return false; + const start = std.mem.indexOf(u8, s.loader, "pub fn loadConfigured(") orelse return false; + const source = s.loader[start..]; + const priced = std.mem.indexOf(u8, source, "const startup = try memory.budgetLiveFor(weights, selected.capacity, inventory, extra, existing, selected.sibling(paired));") orelse return false; + const guard = std.mem.indexOf(u8, source, "const load_limit = memory.admitBudget(limit, startup, route.needs_build) catch |err| {") orelse return false; + if (priced >= guard or !has(source[0..priced], "var selected = window;")) return false; + if (has(source[0..guard], "return ")) return false; + if (!has(source[guard..], "return err;")) return false; + if (!has(source[guard..], ".window = selected, .load_limit = load_limit")) return false; + for ([_][]const u8{ "gpa.create(Engine)", "device.queue()", "r.compile(", "r.sel =", "pack_cache.ensure(" }) |name| { + const at = std.mem.indexOf(u8, source, name) orelse return false; + if (guard >= at) return false; + } + const pack_at = std.mem.indexOf(u8, source, "pack_cache.ensure(").?; + if (pack_at >= std.mem.indexOf(u8, source, "gpa.create(Engine)").?) return false; + if (pack_at >= std.mem.indexOf(u8, source, "device.queue()").?) return false; + for ([_][]const u8{ s.single, s.batch }) |body| { + if (!has(body, "withCache(settings, cache_gib)")) return false; + if (!has(body, "const eng = try fx.Engine.loadConfigured(gpa, io, dir, dump,")) return false; + if (!has(body, "budget_settings);")) return false; + } + return true; +} + +test "Flash Next memory: guard controls reject missing admission, early construction and entry bypasses" { + const a = std.testing.allocator; + try std.testing.expect(guarded(.{})); + const Source = struct { field: []const u8, before: []const u8, after: []const u8 }; + const cases = [_]Source{ + .{ .field = "loader", .before = "memory.admitBudget(", .after = "uncheckedBudget(" }, + .{ .field = "loader", .before = "const startup = try memory.budgetLiveFor(weights, selected.capacity,", .after = "const startup = try memory.budgetLiveFor(weights, window.capacity," }, + .{ .field = "loader", .before = "var selected = window;", .after = "return finishLoadUnchecked();\n var selected = window;" }, + .{ .field = "loader", .before = "const extra = try", .after = "const early = try device.queue();\n const extra = try" }, + .{ .field = "loader", .before = "return err;", .after = "return finishLoadUnchecked();" }, + .{ .field = "loader", .before = ".window = selected, .load_limit = load_limit", .after = ".window = window, .load_limit = 0" }, + .{ .field = "loader", .before = "return loadConfigured(", .after = "return unguardedLoad(" }, + .{ .field = "engine", .before = "return loadWith(", .after = "return unguardedLoad(" }, + .{ .field = "engine", .before = ").loadWith;", .after = ").unguardedLoad;" }, + .{ .field = "engine", .before = ").loadConfigured;", .after = ").unguardedLoad;" }, + .{ .field = "single", .before = "fx.Engine.loadConfigured(", .after = "fx.Engine.loadWith(" }, + .{ .field = "batch", .before = "fx.Engine.loadConfigured(", .after = "fx.Engine.loadWith(" }, + }; + inline for (cases) |c| { + var inputs: Sources = .{}; + const original = @field(inputs, c.field); + try std.testing.expect(has(original, c.before)); + const changed = try std.mem.replaceOwned(u8, a, original, c.before, c.after); + defer a.free(changed); + @field(inputs, c.field) = changed; + try std.testing.expect(!guarded(inputs)); + } +} diff --git a/zig/flashnext_memory_checkpoint_test.zig b/zig/flashnext_memory_checkpoint_test.zig index 581cbac6696..4bbfded56ee 100644 --- a/zig/flashnext_memory_checkpoint_test.zig +++ b/zig/flashnext_memory_checkpoint_test.zig @@ -28,22 +28,7 @@ test "Flash Next memory: weight stats deduplicate indexed shards, read a folder' } test "Flash Next memory: the loader guards every entry before compilation, packs or buffers" { - const source = @embedFile("src/families/flashnext/engine_load.zig"); - const entry = std.mem.indexOf(u8, source, "pub fn loadConfigured(").?; - const guard = std.mem.indexOfPos(u8, source, entry, "memory.admitBudget(") orelse return error.MissingBudgetGuard; - for ([_][]const u8{ "gpa.create(Engine)", "device.queue()", "r.compile(", "r.sel =", "pack_cache.ensure(" }) |name| - try std.testing.expect(guard < std.mem.indexOfPos(u8, source, entry, name).?); - const pack_at = std.mem.indexOfPos(u8, source, entry, "pack_cache.ensure(").?; - try std.testing.expect(pack_at < std.mem.indexOfPos(u8, source, entry, "gpa.create(Engine)").?); - try std.testing.expect(pack_at < std.mem.indexOfPos(u8, source, entry, "device.queue()").?); - try std.testing.expect(std.mem.indexOf(u8, source, "memory.budgetLiveFor(weights, window.capacity, inventory, extra, existing, window.sibling(paired))") != null); - try std.testing.expect(std.mem.indexOf(u8, source, "memory.admitBudget(limit, startup, route.needs_build)") != null); - const single = @embedFile("src/native/flashnext_host.zig"); - const batch = @embedFile("src/native/flashnext_batch_host.zig"); - for ([_][]const u8{ single, batch }) |body| { - try std.testing.expect(std.mem.indexOf(u8, body, "fx.Engine.loadConfigured(") != null); - try std.testing.expect(std.mem.indexOf(u8, body, "withCache(settings, cache_gib)") != null); - } + try std.testing.expect(@import("flashnext_load_guard_test.zig").guarded(.{})); const allocator = @embedFile("src/families/flashnext/replay_run.zig"); try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, allocator, "r.device.buffer(")); try std.testing.expectEqual(@as(usize, 3), std.mem.count(u8, allocator, "try r.allocate(")); diff --git a/zig/flashnext_ssd_budget_test.zig b/zig/flashnext_ssd_budget_test.zig new file mode 100644 index 00000000000..0add7179005 --- /dev/null +++ b/zig/flashnext_ssd_budget_test.zig @@ -0,0 +1,71 @@ +//! Existing memory and FSR formulas must admit a bounded pool where the requested maximum was refused. +const std = @import("std"); +const t = std.testing; +const memory = @import("flashnext_memory"); +const layout = @import("src/families/flashnext/fsr_layout.zig"); +const Settings = @import("src/families/flashnext/window_config.zig").Settings; +const GiB = memory.GiB; +const Ctx = struct { limit: u64, existing: u64 = 0, extra: u64 = 0, needs_build: bool = false, paired: bool = false }; +const inventory: memory.weights_plan.Inventory = .{ .raw = 110 * GiB, .routed = 80 * GiB, .ple = 24 * GiB, .expert_parts = @splat(256 * 1024) }; +const settings: Settings = .{ .capacity = 65568, .ssd_experts = 8 * GiB, .ple_on_ssd = true }; + +fn budget(inv: memory.weights_plan.Inventory, s: Settings, ctx: Ctx) !memory.Budget { + const p = try layout.of(inv, s); + var resident = inv; + resident.raw = p.raw; + return memory.budgetLiveFor(0, s.capacity, resident, ctx.extra + ctx.existing + p.extra, ctx.existing, s.sibling(ctx.paired)); +} + +fn fit(inv: memory.weights_plan.Inventory, s: Settings, ctx: Ctx) !Settings { + if (@hasDecl(layout, "fit")) return layout.fit(inv, s, ctx); + return s; +} + +test "SSD budget: a refused maximum becomes the largest admitted complete-demand pool" { + const before = try budget(inventory, settings, .{ .limit = 0 }); + const ctx: Ctx = .{ .limit = before.steady - 3 * GiB }; + try t.expectError(error.FlashNextMemoryShortfall, memory.admitBudget(ctx.limit, before, false)); + const next = try fit(inventory, settings, ctx); + try t.expect(next.ssd_experts.? < settings.ssd_experts.?); + const p = (try layout.of(inventory, next)).pool.?; + try t.expect(p.slots >= 512); + const after = try budget(inventory, next, ctx); + try t.expectEqual(ctx.limit, try memory.admitBudget(ctx.limit, after, false)); + var wider = next; + wider.ssd_experts = next.ssd_experts.? + p.stride; + try t.expectError(error.FlashNextMemoryShortfall, memory.admitBudget(ctx.limit, try budget(inventory, wider, ctx), false)); + try t.expectEqual(settings.capacity, next.capacity); + try t.expectEqual(settings.factor, next.factor); + try t.expectEqual(settings.ple_on_ssd, next.ple_on_ssd); +} + +test "SSD budget: exact slot boundary counts existing allocations, sessions and requested cache" { + var smaller = settings; + const p = (try layout.of(inventory, settings)).pool.?; + smaller.ssd_experts = 768 * p.stride; + var ctx: Ctx = .{ .limit = 0, .existing = GiB, .extra = 2 * GiB }; + ctx.limit = (try budget(inventory, smaller, ctx)).steady; + const next = try fit(inventory, settings, ctx); + try t.expectEqual(smaller.ssd_experts, next.ssd_experts); + ctx.limit -= 1; + const one_less = try fit(inventory, settings, ctx); + try t.expectEqual(@as(?u64, 767 * p.stride), one_less.ssd_experts); +} + +test "SSD budget: admitted settings, no expert request and impossible fits retain their old policy" { + const before = try budget(inventory, settings, .{ .limit = 0 }); + try t.expectEqualDeep(settings, try fit(inventory, settings, .{ .limit = before.steady })); + var exact = settings; + exact.ssd_experts = settings.ssd_experts.? + 17; + try t.expectEqualDeep(exact, try fit(inventory, exact, .{ .limit = std.math.maxInt(u64) })); + var in_memory = settings; + in_memory.ssd_experts = null; + try t.expectEqualDeep(in_memory, try fit(inventory, in_memory, .{ .limit = 1 })); + try t.expectEqualDeep(settings, try fit(inventory, settings, .{ .limit = 1 })); + try t.expectEqualDeep(settings, try fit(inventory, settings, .{ .limit = 1, .paired = true })); + var cold = inventory; + cold.source = 80 * GiB; + cold.decode = GiB; + cold.prompt = GiB; + try t.expectEqualDeep(settings, try fit(cold, settings, .{ .limit = before.steady, .needs_build = true })); +} diff --git a/zig/flashnext_ssd_review_test.zig b/zig/flashnext_ssd_review_test.zig new file mode 100644 index 00000000000..f6ce52a27c6 --- /dev/null +++ b/zig/flashnext_ssd_review_test.zig @@ -0,0 +1,145 @@ +//! Reviewed SSD pool boundaries and ownership, with actual shared formulas and a recording allocator. +const std = @import("std"); +const t = std.testing; +const memory = @import("flashnext_memory"); +const layout = @import("src/families/flashnext/fsr_layout.zig"); +const Settings = @import("src/families/flashnext/window_config.zig").Settings; +const GiB = memory.GiB; +const Ctx = struct { limit: u64, existing: u64 = 0, extra: u64 = 0, needs_build: bool = false, paired: bool = false, rotary_growth: u64 = 0 }; +const inventory: memory.weights_plan.Inventory = .{ .raw = 110 * GiB, .routed = 80 * GiB, .ple = 24 * GiB, .expert_parts = @splat(256 * 1024) }; +const settings: Settings = .{ .capacity = 65568, .ssd_experts = 8 * GiB, .ple_on_ssd = true }; + +fn budget(s: Settings, ctx: Ctx) !memory.Budget { + const p = try layout.of(inventory, s); + var resident = inventory; + resident.raw = p.raw; + return memory.budgetLiveFor(0, s.capacity, resident, ctx.extra + ctx.existing + p.extra, ctx.existing, s.sibling(ctx.paired)); +} + +test "REV99 SSD budget runs in all and the Linux host shard" { + const build = @embedFile("build/flashnext_batch_host.zig"); + const ci = @embedFile("build/host_ci.zig"); + try t.expect(std.mem.indexOf(u8, ci, "\"test-flashnext-ssd-budget-host\"") != null); + try t.expect(std.mem.indexOf(u8, build, "all.dependOn(&bounded_run.step)") != null); +} + +test "REV99 automatic cache includes unfaulted allocated pool pages" { + const cache = @import("src/native/flashnext_cache_budget.zig"); + try t.expectEqual(@as(u64, 0), try cache.automatic(24 * GiB, 15 * GiB, 22 * GiB)); + try t.expectEqual(@as(u64, 2 * GiB), try cache.automatic(24 * GiB, 15 * GiB, 20 * GiB)); + try t.expectEqual(@as(u64, 3 * GiB), try cache.automatic(24 * GiB, 19 * GiB, 12 * GiB)); +} + +test "REV99 native automatic pool budget uses the allocated-page ceiling before its receipt" { + const source = @embedFile("src/native/flashnext_cache_setup.zig"); + try t.expect(std.mem.indexOf(u8, source, "flashnext_cache_budget.zig") != null); + try t.expect(std.mem.indexOf(u8, source, "budgetUnderMaximum") != null); + try t.expect(std.mem.indexOf(u8, source, "gib == null") != null); +} + +test "REV99 fitted placement reprices caller and existing charges before the final budget" { + const source = @embedFile("src/families/flashnext/engine_load.zig"); + const placed = std.mem.indexOf(u8, source, "placement = try @import(\"fsr_layout.zig\").of(source_inventory,") orelse return error.TestUnexpectedResult; + const charged = std.mem.indexOfPos(u8, source, placed, "base_extra = try std.math.add") orelse return error.TestUnexpectedResult; + const priced = std.mem.indexOfPos(u8, source, placed, "plain = try memory.budgetLiveFor") orelse return error.TestUnexpectedResult; + try t.expect(charged < priced); +} + +test "REV99 a refused tensor-unit pool retains rotary headroom when a smaller pool permits it" { + var exact = settings; + const p = (try layout.of(inventory, exact)).pool.?; + exact.ssd_experts = 768 * p.stride; + var ctx: Ctx = .{ .limit = 0, .rotary_growth = 33028 }; + ctx.limit = (try budget(exact, ctx)).steady; + const fitted = try layout.fit(inventory, settings, ctx); + try t.expectEqual(@as(?u64, 767 * p.stride), fitted.ssd_experts); + try t.expect((try budget(fitted, ctx)).steady + ctx.rotary_growth <= ctx.limit); + try t.expectEqualDeep(exact, try layout.fit(inventory, exact, ctx)); // an admitted request stays exact +} + +const fsr = @import("src/core/fsr/arena.zig"); +const Source = struct { + pub fn fileSize(_: @This(), _: usize) !u64 { + return 4096; + } + pub fn readAt(_: @This(), _: usize, out: []u8, _: u64) !usize { + @memset(out, 0); + return out.len; + } +}; +fn measured(slots: usize) !usize { + var peak: @import("src/core/rows_peak_allocator.zig").Peak = .{ .child = t.allocator }; + const A = fsr.Arena(Source); + const span: @import("src/core/fsr/reader.zig").Span = .{ .file = 0, .offset = 0, .length = 4 }; + const experts: [16]A.Expert = @splat(@splat(span)); + var raw: [9][32]u8 = undefined; + var slabs: [9][]u8 = undefined; + for (&slabs, &raw) |*slab, *bytes| slab.* = bytes[0 .. slots * 4]; + var map: [16]i32 = undefined; + var arena = try A.initMapped(peak.allocator(), .{}, &experts, @splat(4), slabs, &map); + const bytes = peak.live; + arena.deinit(); + try t.expectEqual(@as(usize, 0), peak.live); + return bytes; +} + +test "REV99 slot metadata covers actual demand and forecast job allocations" { + const plan = layout.plan; + const small = try plan.pool(4 * 36, @splat(4), 16, 4); + const large = try plan.pool(8 * 36, @splat(4), 16, 4); + const small_live = try measured(4); + const large_live = try measured(8); + const small_forecast = if (@hasDecl(layout.plan, "forecastJobs")) try plan.forecastJobs(9, small.slots) else 0; + const large_forecast = if (@hasDecl(layout.plan, "forecastJobs")) try plan.forecastJobs(9, large.slots) else 0; + try t.expect(large.metadata + large_forecast - small.metadata - small_forecast >= large_live - small_live); + const placement = try layout.of(inventory, settings); + try t.expect(placement.forecast > 0 and placement.forecast <= placement.extra); + try t.expectEqual(@as(u64, 1 << 20), placement.extra); +} + +const Buffer = struct { + r: *Recording, + pub fn deinit(b: @This()) void { + b.r.live -= 1; + b.r.freed += 1; + } +}; +const Recording = struct { + live: usize = 0, + freed: usize = 0, + calls: usize = 0, + kept: usize = 0, + fail_at: usize, + pub fn allocate(r: *@This(), _: usize) !Buffer { + r.calls += 1; + r.live += 1; + return .{ .r = r }; + } + pub fn keep(r: *@This(), _: Buffer) !void { + if (r.calls == r.fail_at) return error.OutOfMemory; + r.kept += 1; + } + fn close(r: *@This()) void { + r.live -= r.kept; + r.freed += r.kept; + r.kept = 0; + } +}; + +test "REV99 every failed slab registration releases only its unowned buffer" { + const own = @import("src/families/flashnext/fsr_buffer.zig"); + for ([_]usize{ 3, 9 }) |count| for (1..count + 1) |fail_at| { + var r: Recording = .{ .fail_at = fail_at }; + for (0..count) |_| _ = own.allocate(&r, 4096) catch break; + const unowned = r.live - r.kept; + r.close(); + try t.expectEqual(@as(usize, 0), unowned); + try t.expectEqual(@as(usize, 0), r.live); + try t.expectEqual(r.calls, r.freed); + }; +} + +test "REV99 expert and PLE slabs share the checked ownership handoff" { + const source = @embedFile("src/families/flashnext/fsr_storage.zig"); + try t.expectEqual(@as(usize, 2), std.mem.count(u8, source, "@import(\"fsr_buffer.zig\").allocate(r, n)")); +} diff --git a/zig/gemma4_shared_affine_test.zig b/zig/gemma4_shared_affine_test.zig index c1baf895b8b..a2d4e96e35f 100644 --- a/zig/gemma4_shared_affine_test.zig +++ b/zig/gemma4_shared_affine_test.zig @@ -115,8 +115,8 @@ test "landed Metal source bytes are pinned without shader compilation" { { var hash: [32]u8 = undefined; std.crypto.hash.sha2.Sha256.hash(ks.core_lane_projection, &hash, .{}); - // Packed affine lanes with producer sums, prompt row blocks, inline sums and the 8-bit reg layout. - try std.testing.expectEqualStrings("d921d9a938d3c4f1fe5a1c89ddfd135d96845055bee1721080ba82fef7a9f8e3", &std.fmt.bytesToHex(hash, .lower)); + // Packed affine lanes with producer sums, prompt row blocks, inline sums and 4/5/6/8-bit reg layouts. + try std.testing.expectEqualStrings("b3d9a4c3532ebeba38d69de37e74ba3a7ebcfe5cc342bda08a867e441b35bab1", &std.fmt.bytesToHex(hash, .lower)); } } test "released lane parameters and conservative scratch size" { @@ -206,3 +206,39 @@ test "gemma4 widths: real Gemma row encoder keeps mixed pitches across 16 row ch try std.testing.expectError(error.InvalidOutputStride, family_weights.layout(cfg.unified12b, bad).validate()); } } + +test "split-plane regBlock5 and regBlock6 match every coordinate's 5- and 6-bit tile code" { + var t5: [320]u32 = undefined; + for (&t5, 0..) |*v, i| v.* = @as(u32, @intCast(i)) *% 0x9e3779b9 +% 0x51d0_0005; + var o5: [320]u32 = undefined; + lane.regBlock5(&t5, &o5); + for (0..32) |ln| for (0..8) |w| for (0..8) |j| { + const col = ((ln >> 1) & 3) + 4 * ((ln >> 4) & 1) + 8 * (w >> 1); + const k = 4 * (ln & 1) + 8 * ((ln >> 3) & 1) + 32 * (w & 1) + (j & 1) * 2 + ((j >> 1) & 1) * 16 + (j >> 2); + const bit = k * 5; + const sh: u5 = @intCast(bit & 31); + var want = t5[col * 10 + (bit >> 5)] >> sh; + if (@as(usize, sh) + 5 > 32) want |= t5[col * 10 + (bit >> 5) + 1] << @intCast(32 - @as(usize, sh)); + want &= 31; + const lo4 = (o5[(w >> 2) * 128 + ln * 4 + (w & 3)] >> @intCast(4 * j)) & 15; + const hi1 = (o5[256 + 2 * ln + (w >> 2)] >> @intCast(16 * (j >> 2) + 4 * (w & 3) + (j & 3))) & 1; + try std.testing.expectEqual(want, lo4 | (hi1 << 4)); + }; + + var t6: [384]u32 = undefined; + for (&t6, 0..) |*v, i| v.* = @as(u32, @intCast(i)) *% 0x7f4a7c15 +% 0x51d0_0006; + var o6: [384]u32 = undefined; + lane.regBlock6(&t6, &o6); + for (0..32) |ln| for (0..8) |w| for (0..8) |j| { + const col = ((ln >> 1) & 3) + 4 * ((ln >> 4) & 1) + 8 * (w >> 1); + const k = 4 * (ln & 1) + 8 * ((ln >> 3) & 1) + 32 * (w & 1) + (j & 1) * 2 + ((j >> 1) & 1) * 16 + (j >> 2); + const bit = k * 6; + const sh: u5 = @intCast(bit & 31); + var want = t6[col * 12 + (bit >> 5)] >> sh; + if (@as(usize, sh) + 6 > 32) want |= t6[col * 12 + (bit >> 5) + 1] << @intCast(32 - @as(usize, sh)); + want &= 63; + const lo4 = (o6[(w >> 2) * 128 + ln * 4 + (w & 3)] >> @intCast(4 * j)) & 15; + const hi2 = (o6[256 + 4 * ln + (w >> 1)] >> @intCast(16 * (j >> 2) + 8 * (w & 1) + 2 * (j & 3))) & 3; + try std.testing.expectEqual(want, lo4 | (hi2 << 4)); + }; +} diff --git a/zig/glm_image_cache_host.zig b/zig/glm_image_cache_host.zig index a8201e1a5ef..3763d3082ac 100644 --- a/zig/glm_image_cache_host.zig +++ b/zig/glm_image_cache_host.zig @@ -394,3 +394,107 @@ test "GLM image cache: suffix encoding wire and actual splice dispatch preserve try peer.take(0, none); try t.expectEqual(@as(usize, 0), peer.rowCount()); } + +/// Echo rank zero's reduction locally. The chunk control and the cache go through their serving paths. +const CancelWire = struct { + fn broadcast(_: u64, _: u64, _: usize, _: cuda.nccl.DataType, _: c_int, _: cuda.nccl.Comm, _: cuda.abi.Stream) callconv(.c) c_int { + return 0; + } + fn reduce(_: u64, _: u64, _: usize, _: cuda.nccl.DataType, _: cuda.nccl.RedOp, _: cuda.nccl.Comm, _: cuda.abi.Stream) callconv(.c) c_int { + return 0; + } + fn download(dst: ?*anyopaque, src: u64, n: usize) callconv(.c) c_int { + @memcpy(@as([*]u8, @ptrCast(dst.?))[0..n], @as([*]const u8, @ptrFromInt(src))[0..n]); + return 0; + } + fn device(d: *cuda.abi.Device) callconv(.c) c_int { + d.* = 0; + return 0; + } + fn attribute(out: *c_int, _: cuda.abi.DeviceAttribute, _: cuda.abi.Device) callconv(.c) c_int { + out.* = 0; + return 0; + } +}; + +fn checkInterruptedPrefix(planned: []const u32) !void { + var c: Cache = .{}; + try c.init(); + defer c.deinit(); + var d = Device.driver(); + d.api.cuDeviceGetAttribute = CancelWire.attribute; + d.api.cuCtxGetDevice = CancelWire.device; + d.api.cuMemcpyDtoH_v2 = CancelWire.download; + cuda.download_stage.forget(); + defer cuda.download_stage.forget(); + defer { + cuda.copy_source.synchronizeStream(&d, null) catch {}; + cuda.copy_source.dropSpares(&d, cuda.copy_source.current()); + } + var lib: cuda.nccl.Library = .{ .lib = undefined, .api = undefined }; + lib.api.ncclBroadcast = CancelWire.broadcast; + lib.api.ncclAllReduce = CancelWire.reduce; + var word: f64 = 0; + var wire_buffer: [10000]u8 = undefined; + var wire_ids: [2049]u32 = undefined; + c.e.d = &d; + c.e.stream = .{ .d = &d, .handle = null }; + c.e.lib = &lib; + c.e.comm = null; + c.e.dropped = .empty; + c.e.announce = 0; + c.e.share.rank = 0; + c.e.share.world = 2; + c.e.settings = .{}; + c.e.m.glue.put_words = .{ .d = &d, .handle = null }; + c.e.heat_gate.bands = null; + c.e.prompt_profs = @splat(null); + c.e.profiling_prompt = null; + c.e.prompt_logprobs = null; + c.e.drafter = null; + c.e.l2pf = null; + c.e.images = null; + c.e.pair = null; + c.e.shared_buf = .{ .d = &d, .ptr = @intFromPtr(&word), .len = @sizeOf(f64), .borrowed = true }; + var seq: @TypeOf(c.e.cur.*) = .{ .st = undefined }; + c.e.seqs = .empty; + try c.e.seqs.append(a, &seq); + defer c.e.seqs.deinit(a); + var link: glm.follow.Link = .{ + .d = &d, + .lib = &lib, + .comm = null, + .stream = c.e.stream, + .ids = &wire_ids, + .gpa = a, + .wait = true, + .buf = .{ .d = &d, .ptr = @intFromPtr(&wire_buffer), .len = wire_buffer.len, .borrowed = true }, + }; + var back: glm.lanes.Lanes = .{ .x = .{ .e = &c.e, .link = &link } }; + defer back.deinit(); + const ids: [N]u32 = @splat(17); + var s = try lanes.Stream.init(a, .{ .id = "cancelled", .prompt = &ids, .max_new = 8 }); + defer s.deinit(a); + const lane = try back.claim(&s); + lane.fill = 2048; + lane.marks = try a.dupe(u32, planned); + c.model.words = .{ 31, 47 }; + try t.expect(s.reuse.hook == null); + try t.expectEqual(@as(u32, 0), try c.begin(&s)); + const b = back.backend(); + try b.vtable.cancel_prefill.?(b.ptr, &s); + try t.expectEqual(@as(usize, 1), c.model.live); + c.model.words = .{ 0, 0 }; + var retry = try lanes.Stream.init(a, .{ .id = "retry", .prompt = &ids, .max_new = 8 }); + defer retry.deinit(a); + try t.expectEqual(@as(u32, 2048), try c.begin(&retry)); + try t.expectEqual([2]u64{ 31, 47 }, c.model.words); +} + +test "GLM shared cache: cancellation before a scheduled mark preserves the completed prefix for retry" { + try checkInterruptedPrefix(&.{6144}); +} + +test "GLM shared cache: cancellation without scheduled marks preserves the completed prefix for retry" { + try checkInterruptedPrefix(&.{}); +} diff --git a/zig/glm_metal_timing_host.zig b/zig/glm_metal_timing_host.zig new file mode 100644 index 00000000000..3c19251b1f9 --- /dev/null +++ b/zig/glm_metal_timing_host.zig @@ -0,0 +1,4 @@ +//! Actual family timing policies with host recording clocks. +test { + _ = @import("src/families/glm/timing.zig"); +} diff --git a/zig/glm_wide_expert_host.zig b/zig/glm_wide_expert_host.zig new file mode 100644 index 00000000000..65acd2709f9 --- /dev/null +++ b/zig/glm_wide_expert_host.zig @@ -0,0 +1,85 @@ +//! The actual GLM expert dispatch at a recording CUDA boundary, with no device arithmetic. +const std = @import("std"); +const cuda = @import("cuda"); +const glm = @import("glm"); +const cell = @import("tests/cuda/contract_glm_wide_expert.zig"); +const t = std.testing; +const Rec = struct { + var id: usize = 0; + var grid: u32 = 0; + var threads: u32 = 0; + var shared: u32 = 0; + var values: [14]u64 = undefined; + fn arg(comptime T: type, p: ?[*]?*anyopaque, i: usize) T { + return @as(*const T, @ptrCast(@alignCast(p.?[i].?))).*; + } + fn launch(f: cuda.abi.Function, gx: c_uint, _: c_uint, _: c_uint, bx: c_uint, _: c_uint, _: c_uint, smem: c_uint, _: cuda.abi.Stream, p: ?[*]?*anyopaque, _: ?[*]?*anyopaque) callconv(.c) c_int { + id = @intFromPtr(f); + grid = gx; + threads = bx; + shared = smem; + for (0..14) |i| values[i] = switch (i) { + 0, 3, 4, 7, 8, 9, 10 => arg(u64, p, i), + 12 => @as(u32, @bitCast(arg(f32, p, i))), + 13 => @as(u32, @bitCast(arg(i32, p, i))), + else => @intCast(arg(i32, p, i)), + }; + return 0; + } + fn function(d: *cuda.Driver, n: usize) cuda.Function { + return .{ .d = d, .handle = @ptrFromInt(n) }; + } +}; +fn kernels(d: *cuda.Driver) glm.experts.Kernels { + var k: glm.experts.Kernels = undefined; + k.b32 = null; + k.wide_tile = false; + k.nvfp4.warps = 4; + for (&k.nvfp4.fns, 0..) |*f, i| f.* = Rec.function(d, i + 1); + for (&k.nvfp4.fact_fns, 0..) |*f, i| f.* = Rec.function(d, 20 + i); + for (&k.nvfp4.prompt_fns, 0..) |*f, i| f.* = Rec.function(d, 30 + i); + k.nvfp4.resident = @splat(100000); + return k; +} +fn dispatch(rows: usize, on: bool, fact: bool, prompt: bool, which: glm.experts.Which) !void { + var d: cuda.Driver = undefined; + d.api.cuLaunchKernel = Rec.launch; + var k = kernels(&d); + k.wide_tile = on; + const plan: glm.experts.Plan = .{ .route = .{ .items = 60, .counts = 70, .members = 80, .rank = 90, .hist = 100 }, .slots = 2, .experts = 2, .prompt = prompt, .fact = fact }; + const layer: cuda.experts.Layer = .{ .format = .nvfp4, .up = 20, .down = 30, .up_scale = 40, .down_scale = 50, .width = 512, .dims = 4096, .experts = 1 }; + try glm.experts.run(&k, .{ .d = &d, .handle = null }, which, layer, plan, 10, if (which == .gate_up) 4096 else 512, rows, 110, 1); + const wide = on and rows > 16 and fact and !prompt and which == .down_f32; + const want: usize = if (prompt) (if (which == .gate_up) 31 else 32) else if (fact and which == .gate_up) 20 else if (wide) 21 else 2; + try t.expectEqual(want, Rec.id); + if (which == .down_f32 and !prompt) { + try t.expectEqual([14]u64{ 10, 512, 0, 30, 50, 16, 128, 60, 70, 80, 110, 4096, 0, 1 }, Rec.values); + try t.expectEqual(@as(u32, if (wide) 256 else 128), Rec.threads); + try t.expectEqual(@as(u32, if (wide) 34816 else 0), Rec.shared); + const items = glm.experts.maxItems(rows * 2, 2, if (wide) 64 else 16); + try t.expectEqual(@as(u32, @intCast(if (wide) items * 16 else (items * 128 + 3) / 4)), Rec.grid); + } +} +test "GLM wide expert: sixteen keeps old down, seventeen24and32 take matching fact down only when enabled" { + for ([_]usize{ 16, 17, 24, 32 }) |rows| for ([_]bool{ false, true }) |on| try dispatch(rows, on, true, false, .down_f32); +} +test "GLM wide expert: classic down, fact gateup and prompt keep their original dispatch" { + for ([_]usize{ 16, 17, 24, 32 }) |rows| for ([_]bool{ false, true }) |on| { + try dispatch(rows, on, false, false, .down_f32); + try dispatch(rows, on, true, false, .gate_up); + try dispatch(rows, on, true, true, .down); + }; +} +test "GLM wide expert: byte cells include finite and forced nonfinite everywidth plus corruption control" { + const spec = cell.spec(); + try t.expectEqual(@as(usize, 8), spec.served.len); + var suite = cell.Suite{ .ks = undefined, .cells = undefined }; + for (&suite.cells, 0..) |*p, i| { + p.* = .{ .rig = undefined, .ks = &suite.ks, .nonfinite = i == 1, .corrupt = i == 2 }; + } + for (suite.cells[0..2]) |*p| { + const k = p.kernel(); + try t.expect(k.control == null and k.spec.replaces != null); + } + try t.expect(suite.cells[1].nonfinite and suite.cells[2].kernel().control == .shapes); +} diff --git a/zig/inkling2_native_compile.zig b/zig/inkling2_native_compile.zig new file mode 100644 index 00000000000..0d09fb133c1 --- /dev/null +++ b/zig/inkling2_native_compile.zig @@ -0,0 +1,4 @@ +//! Analyze the actual Inkling 2 Mini native opener without loading a device or checkpoint. +export fn compileInkling2Native() usize { + return @intFromPtr(&@import("src/inkling2_native.zig").open); +} diff --git a/zig/kernels/cuda/contract_controls_set.cu b/zig/kernels/cuda/contract_controls_set.cu index 9469c0ea90a..29d0a35f8cd 100644 --- a/zig/kernels/cuda/contract_controls_set.cu +++ b/zig/kernels/cuda/contract_controls_set.cu @@ -11,3 +11,4 @@ // Idol decoders: controls for rounding, sums and exceptional values. #include "contract_controls_idol_decoder.cuh" #include "contract_qwen3_asr_controls.cuh" +#include "contract_ricursive_controls.cuh" diff --git a/zig/kernels/cuda/contract_ricursive_controls.cuh b/zig/kernels/cuda/contract_ricursive_controls.cuh new file mode 100644 index 00000000000..7580e389dfb --- /dev/null +++ b/zig/kernels/cuda/contract_ricursive_controls.cuh @@ -0,0 +1,24 @@ +// Planted controls for Ripple's attention prep (ricursive_prep.cu): each keeps one fault its gate must catch. + +// Included by contract_controls_set.cu after contract_controls.cu, whose headers it reuses. + +// Gate 3: ricursive_prep.cu's tf_rc_prep keeping only the rounding points in `keep`; the shapes gate must go red. +#include "ricursive_prep.cuh" + +extern "C" __global__ void __launch_bounds__(tf_rcp::NT) tf_ctl_rc_prep( + const tf_rcp::Rows XQ, const tf_rcp::Rows XK, const tf_rcp::Rows XV, const float* inv, const __nv_bfloat16* qw, + const __nv_bfloat16* kw, __nv_bfloat16* Q, __nv_bfloat16* KC, __nv_bfloat16* VC, int rows, int heads, int kv_heads, int pos, + int ring, int rope, float eps, const int* tab, long long page, int tok, int keep) { + tf_rcp::prep(XQ, XK, XV, inv, qw, kw, Q, KC, VC, rows, heads, kv_heads, pos, ring, rope, eps, tab, page, tok, keep); +} + +// Gate 3: tf_rc_prep_rows with each row's slot dropped (all rows in stream 0's cache), `keep` as above; shapes go red. +extern "C" __global__ void __launch_bounds__(tf_rcp::NT) tf_ctl_rc_prep_rows( + const tf_rcp::Rows XQ, const tf_rcp::Rows XK, const tf_rcp::Rows XV, const float* inv, const __nv_bfloat16* qw, + const __nv_bfloat16* kw, __nv_bfloat16* Q, __nv_bfloat16* KC, __nv_bfloat16* VC, int rows, int heads, int kv_heads, + const int* pos, const int* slot, int ring, int rope, float eps, const int* tab, long long page, int tok, int stride, + int keep) { + (void)slot; // the planted fault: no row's own stream + tf_rcp::prep_rows(XQ, XK, XV, inv, qw, kw, Q, KC, VC, rows, heads, kv_heads, pos, nullptr, ring, rope, eps, tab, page, + tok, stride, keep); +} diff --git a/zig/kernels/cuda/flashnext_mtp.cu b/zig/kernels/cuda/flashnext_mtp.cu index a6f6c047c6c..010e1b45322 100644 --- a/zig/kernels/cuda/flashnext_mtp.cu +++ b/zig/kernels/cuda/flashnext_mtp.cu @@ -69,6 +69,62 @@ extern "C" __global__ void __launch_bounds__(1024) fn_row_best(const __nv_bfloat } } +// fn_row_best's first pass, block (row, warp) as its warp: part [rows, 32, 2] = each warp's best and id bits. +extern "C" __global__ void __launch_bounds__(32) fn_row_best_max(const __nv_bfloat16* __restrict__ L, int V, long long ld, + float* __restrict__ part) { + using namespace fn_mtp; + const int r = blockIdx.x, warp = blockIdx.y, lane = threadIdx.x; + const __nv_bfloat16* row = L + static_cast(r) * ld; + float v = -CUDART_INF_F; + int at = 0x7fffffff; + for (int i = warp * 32 + lane; i < V; i += 1024) { + const float x = __bfloat162float(row[i]); + if (x > v) { + v = x; + at = i; + } + } + for (int o = 16; o; o >>= 1) better(v, at, __shfl_xor_sync(0xffffffffu, v, o), __shfl_xor_sync(0xffffffffu, at, o)); + if (lane == 0) { + part[(r * 32 + warp) * 2 + 0] = v; + part[(r * 32 + warp) * 2 + 1] = __int_as_float(at); + } +} + +// fn_row_best's second pass, same bits: warp sums into sums [rows, 32]; a row's last block (done = 0) folds them. +extern "C" __global__ void __launch_bounds__(32) fn_row_best_sum(const __nv_bfloat16* __restrict__ L, int V, long long ld, + const float* __restrict__ part, float* sums, + unsigned int* done, float* __restrict__ out) { + using namespace fn_mtp; + const int r = blockIdx.x, warp = blockIdx.y, lane = threadIdx.x; + const __nv_bfloat16* row = L + static_cast(r) * ld; + float v = part[(r * 32 + lane) * 2 + 0]; + int at = __float_as_int(part[(r * 32 + lane) * 2 + 1]); + for (int o = 16; o; o >>= 1) better(v, at, __shfl_xor_sync(0xffffffffu, v, o), __shfl_xor_sync(0xffffffffu, at, o)); + const float m = __shfl_sync(0xffffffffu, v, 0); + const int top_at = __shfl_sync(0xffffffffu, at, 0); + float sum = 0.0f; + for (int i = warp * 32 + lane; i < V; i += 1024) sum += expf(__bfloat162float(row[i]) - m); + for (int o = 16; o; o >>= 1) sum += __shfl_xor_sync(0xffffffffu, sum, o); + unsigned int ticket = 0; + if (lane == 0) { + sums[r * 32 + warp] = sum; + __threadfence(); + ticket = atomicAdd(&done[r], 1u); + } + if (__shfl_sync(0xffffffffu, ticket, 0) != 31u) return; + __threadfence(); + sum = reinterpret_cast(sums)[r * 32 + lane]; + for (int o = 16; o; o >>= 1) sum += __shfl_xor_sync(0xffffffffu, sum, o); + if (lane == 0) { + out[r * 4 + 0] = m; + out[r * 4 + 1] = m + logf(sum); + out[r * 4 + 2] = __int_as_float(top_at); + out[r * 4 + 3] = 0.0f; + done[r] = 0u; + } +} + namespace fn_mtp { // A bf16 value's order as an unsigned key (larger value, larger key); -0 as +0, so equal values tie as drawRow's do. static __device__ __forceinline__ unsigned int order_key(unsigned short u) { diff --git a/zig/kernels/cuda/inkling2/experts.cu b/zig/kernels/cuda/inkling2/experts.cu new file mode 100644 index 00000000000..cd0b81c7803 --- /dev/null +++ b/zig/kernels/cuda/inkling2/experts.cu @@ -0,0 +1,393 @@ +// Inkling 2's grouped expert projections: exl3_grouped.cuh's arithmetic per output, launched without empty tiles. +#include +#include +#include + +#include "exl3_decode.cuh" +#include "common/fp_pairs.cuh" + +namespace ink2x { +using namespace tf_exl3; + +constexpr int ITEM_THREADS = 1024; + +// tf_ink2x_group's arguments: tf_exl3_group's lists, plus items (u, first, count), runs of at most `per` members. +struct GroupArgs { + const int* pick; // int32 [rows * slots] + int* uids; // int32 [nexp_max] + int* ucount; // int32 [1] + int* members; // int32 [nexp_max, maxm] + int* items; // int32 [3 * max items] (per > 0) + int* nitems; // int32 [1] (per > 0) + int rows, slots, experts, maxm, per, pad; // pad: -1 after each expert's members up to maxm +}; + +// One projection; z, k, n, p, sk, maxm and slots as GroupedArgs has them. +struct WideArgs { + const half* x0; // fp16 [P, K], the rotated gate (or down) inputs + const half* x1; // fp16 [P, K], the rotated up inputs + const long long* tp0; // int64 [E], one trellis pointer per expert + const long long* tp1; + const int* k2_0; // int32 [E], half-bits a value + const int* k2_1; + const int* uids; // int32 [nexp_max], distinct routed experts in id order + const int* items; // int32 [3 * max items], (u, first member, count); null: item u is expert u, maxm <= 16 MT + const int* nitems; // int32 [1]: the items, or the group's count when items is null + const int* members; // int32 [nexp_max, maxm], row * 32 + slot + float* z; // fp32 partials, [(mat * sk + split) * P + p] * N + col + int k, n, p, sk, maxm, slots; +}; + +// A warp's k tiles for MT member tiles in grouped_body's order per output; words and inputs travel a tile ahead. +template +struct Tiles { + static constexpr int TW = tile_words(), LW = lane_words(); + uint32_t nx[NT][LW]; + + __device__ __forceinline__ void first(const uint32_t* tb, int nkt, int lane) { + if (nkt > 0) +#pragma unroll + for (int j = 0; j < NT; ++j) ldg_lane_words(tb + j * TW, lane, nx[j]); + } + + __device__ __forceinline__ static void xload(const half* (&xr)[MT][2], const bool (&ok)[MT][2], int mts, int k, + uint32_t (&a)[MT][4]) { +#pragma unroll + for (int m = 0; m < MT; ++m) { + const bool o0 = m < mts && ok[m][0], o1 = m < mts && ok[m][1]; + a[m][0] = o0 ? *reinterpret_cast(xr[m][0] + k) : 0u; + a[m][1] = o1 ? *reinterpret_cast(xr[m][1] + k) : 0u; + a[m][2] = o0 ? *reinterpret_cast(xr[m][0] + k + 8) : 0u; + a[m][3] = o1 ? *reinterpret_cast(xr[m][1] + k + 8) : 0u; + } + } + + __device__ __forceinline__ void run(const uint32_t* tb, size_t kstride, int kt0, int nkt, const half* (&xr)[MT][2], + const bool (&ok)[MT][2], int mts, int lane, float (&acc)[MT][NT][2][4]) { + uint32_t xa[MT][4]; + if (nkt > 0) xload(xr, ok, mts, kt0 * 16, xa); + for (int i = 0; i < nkt; ++i) { + uint32_t w[NT][LW], a[MT][4]; +#pragma unroll + for (int j = 0; j < NT; ++j) +#pragma unroll + for (int l = 0; l < LW; ++l) w[j][l] = nx[j][l]; +#pragma unroll + for (int m = 0; m < MT; ++m) +#pragma unroll + for (int c = 0; c < 4; ++c) a[m][c] = xa[m][c]; + if (i + 1 < nkt) { +#pragma unroll + for (int j = 0; j < NT; ++j) ldg_lane_words(tb + (size_t)(i + 1) * kstride + j * TW, lane, nx[j]); + xload(xr, ok, mts, (kt0 + i + 1) * 16, xa); + } +#pragma unroll + for (int j = 0; j < NT; ++j) { + uint32_t b0[2], b1[2]; + decode_lane(w[j], lane, b0, b1); +#pragma unroll + for (int m = 0; m < MT; ++m) + if (m < mts) { + mma16816(acc[m][j][0], a[m], b0); + mma16816(acc[m][j][1], a[m], b1); + } + } + } + } +}; + +// This lane's member-row input pointers (rows_sh filled and synced). +template +__device__ __forceinline__ void member_rows(const half* X, int k, const int* rows_sh, int mts, int g, int t, + const half* (&xr)[MT][2], bool (&ok)[MT][2]) { +#pragma unroll + for (int m = 0; m < MT; ++m) { + const int r0 = m < mts ? rows_sh[16 * m + g] : -1, r1 = m < mts ? rows_sh[16 * m + g + 8] : -1; + xr[m][0] = X + (size_t)(r0 < 0 ? 0 : r0) * k + 2 * t; + xr[m][1] = X + (size_t)(r1 < 0 ? 0 : r1) * k + 2 * t; + ok[m][0] = r0 >= 0; + ok[m][1] = r1 >= 0; + } +} + +// Program (n block, item, mat * sk + split): 16 MT members by W_q over the split's K; SEQ: warps add in turn. +template +__device__ __forceinline__ void wide_body(const WideArgs a) { + const int nblock = blockIdx.x, item = blockIdx.y; + if (item >= a.nitems[0]) return; + int u = item, first = 0, cnt = a.maxm; + if (a.items) { + u = a.items[3 * item]; + first = a.items[3 * item + 1]; + cnt = a.items[3 * item + 2]; + } + const int split = blockIdx.z % a.sk, mat = blockIdx.z / a.sk; + const half* X = mat ? a.x1 : a.x0; + const int e = a.uids[u]; + const uint32_t* T = reinterpret_cast(mat ? a.tp1[e] : a.tp0[e]); + const int k2 = mat ? a.k2_1[e] : a.k2_0[e]; + const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31; + const int g = lane >> 2, t = lane & 3; + const int ntiles = a.n >> 4; + const int per_warp = (a.k >> 4) / a.sk / W; + const int kt0 = split * (per_warp * W) + warp * per_warp; + const int nt0 = nblock * NT; + + __shared__ int rows_sh[16 * MT]; + for (int m = threadIdx.x; m < 16 * MT; m += W * 32) { + const int code = m < cnt ? a.members[(size_t)u * a.maxm + first + m] : -1; + rows_sh[m] = code >= 0 ? (code >> 5) * a.slots + (code & 31) : -1; + } + float acc[MT][NT][2][4]; +#pragma unroll + for (int m = 0; m < MT; ++m) +#pragma unroll + for (int i = 0; i < NT; ++i) +#pragma unroll + for (int h = 0; h < 2; ++h) +#pragma unroll + for (int c = 0; c < 4; ++c) acc[m][i][h][c] = 0.f; + + int mts = 0; + switch (k2) { // the first k tile's words are in flight before the members' rows are read +#define TF_INK2X_CASE(K2_) \ + case K2_: { \ + Tiles tl; \ + const size_t kstride = (size_t)ntiles * tile_words(); \ + const uint32_t* tb = T + (size_t)kt0 * kstride + (size_t)nt0 * tile_words(); \ + tl.first(tb, per_warp, lane); \ + __syncthreads(); \ + if (!a.items) \ + while (cnt > 0 && rows_sh[cnt - 1] < 0) --cnt; \ + mts = (cnt + 15) >> 4; \ + if (mts == 0) return; \ + const half* xr[MT][2]; \ + bool ok[MT][2]; \ + member_rows(X, a.k, rows_sh, mts, g, t, xr, ok); \ + tl.run(tb, kstride, kt0, per_warp, xr, ok, mts, lane, acc); \ + break; \ + } + TF_INK2X_CASE(2) + TF_INK2X_CASE(3) + TF_INK2X_CASE(4) + TF_INK2X_CASE(5) + TF_INK2X_CASE(6) + TF_INK2X_CASE(7) + TF_INK2X_CASE(8) +#undef TF_INK2X_CASE + default: + __trap(); + } + + __shared__ __align__(16) float red[SEQ ? 1 : W][16][NT * 16]; +#pragma unroll + for (int m = 0; m < MT; ++m) { + if (m >= mts) break; + if (m) __syncthreads(); // the last tile's sums are read + for (int w = SEQ ? 0 : warp; w < (SEQ ? W : warp + 1); ++w) { + if (w == warp) +#pragma unroll + for (int i = 0; i < NT; ++i) +#pragma unroll + for (int h = 0; h < 2; ++h) { + const int col = i * 16 + h * 8 + 2 * t; + float* p0 = &red[SEQ ? 0 : warp][g][col]; + float* p1 = &red[SEQ ? 0 : warp][g + 8][col]; + if (!SEQ || w == 0) { + p0[0] = acc[m][i][h][0]; + p0[1] = acc[m][i][h][1]; + p1[0] = acc[m][i][h][2]; + p1[1] = acc[m][i][h][3]; + } else { + p0[0] += acc[m][i][h][0]; + p0[1] += acc[m][i][h][1]; + p1[0] += acc[m][i][h][2]; + p1[1] += acc[m][i][h][3]; + } + } + if (SEQ) __syncthreads(); + } + if (!SEQ) __syncthreads(); + for (int idx = threadIdx.x; idx < 16 * NT * 16; idx += W * 32) { + const int row = idx / (NT * 16), col = idx % (NT * 16); + const int r = rows_sh[16 * m + row]; + if (r < 0) continue; + float s = red[0][row][col]; +#pragma unroll + for (int w = 1; w < (SEQ ? 1 : W); ++w) s += red[w][row][col]; + a.z[(((size_t)mat * a.sk + split) * a.p + r) * a.n + nt0 * 16 + col] = s; + } + } +} + +// Exclusive sum over the block of one value a thread (ITEM_THREADS threads); `tot` gets the total. +__device__ __forceinline__ int block_scan(int v, int* part, int& tot) { + const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5; + int inc = v; +#pragma unroll + for (int o = 1; o < 32; o <<= 1) { + const int x = __shfl_up_sync(0xffffffffu, inc, o); + if (lane >= o) inc += x; + } + if (lane == 31) part[warp] = inc; + __syncthreads(); + if (warp == 0) { + const int w = part[lane]; + int sum = w; +#pragma unroll + for (int o = 1; o < 32; o <<= 1) { + const int x = __shfl_up_sync(0xffffffffu, sum, o); + if (lane >= o) sum += x; + } + part[lane] = sum - w; + if (lane == 31) part[32] = sum; + } + __syncthreads(); + tot = part[32]; + const int r = part[warp] + inc - v; + __syncthreads(); + return r; +} + +} // namespace ink2x + +// tf_exl3_group's lists and the item list in O(pairs): warp w counts, then places, its 32nd of the pairs in order. +extern "C" __global__ void __launch_bounds__(ink2x::ITEM_THREADS) tf_ink2x_group(const ink2x::GroupArgs a) { + extern __shared__ int sh[]; + __shared__ int part[33]; + const int E = a.experts, n = a.rows * a.slots; + uint16_t* wc = reinterpret_cast(sh); // [32][E]: a warp's pairs of each expert, then its first rank + int* cnt = sh + 16 * E; + int* uidx = cnt + E; + const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5; + const int span = (n + 31) / 32, lo = warp * span, hi = min(n, lo + span); + const unsigned below = (1u << lane) - 1u; + for (int i = threadIdx.x; i < 32 * E; i += ink2x::ITEM_THREADS) wc[i] = 0; + __syncthreads(); + for (int i0 = lo; i0 < hi; i0 += 32) { + const int i = i0 + lane; + const int e = i < hi ? a.pick[i] : -1; + const unsigned m = __match_any_sync(0xffffffffu, e); + if (e >= 0 && e < E && (m & below) == 0) wc[warp * E + e] += __popc(m); + } + __syncthreads(); + int has = 0, k = 0, c = 0; + const int e = threadIdx.x; + if (e < E) { + for (int w = 0; w < 32; ++w) { + const int t = wc[w * E + e]; + wc[w * E + e] = c; + c += t; + } + cnt[e] = c; + has = c > 0; + k = a.per > 0 ? (c + a.per - 1) / a.per : 0; + } + int nu, ni; + const int u = ink2x::block_scan(has, part, nu); + int it = ink2x::block_scan(k, part, ni); + if (e < E) { + uidx[e] = u; + if (has) { + a.uids[u] = e; + for (int j = 0; j < k; ++j, ++it) { + a.items[3 * it] = u; + a.items[3 * it + 1] = j * a.per; + a.items[3 * it + 2] = min(a.per, c - j * a.per); + } + } + } + if (threadIdx.x == 0) { + a.ucount[0] = nu; + if (a.per > 0) a.nitems[0] = ni; + } + __syncthreads(); + for (int i0 = lo; i0 < hi; i0 += 32) { + const int i = i0 + lane; + const int pe = i < hi ? a.pick[i] : -1; + const unsigned m = __match_any_sync(0xffffffffu, pe); + if (pe >= 0 && pe < E) { + const int rank = wc[warp * E + pe] + __popc(m & below); + a.members[(size_t)uidx[pe] * a.maxm + rank] = (i / a.slots) * 32 + i % a.slots; + } + __syncwarp(); + if (pe >= 0 && pe < E && (m & below) == 0) wc[warp * E + pe] += __popc(m); + __syncwarp(); + } + if (a.pad) // -1 after each expert's members, as tf_exl3_group leaves them + for (int x = threadIdx.x; x < E; x += ink2x::ITEM_THREADS) + if (cnt[x] > 0) + for (int j = cnt[x]; j < a.maxm; ++j) a.members[(size_t)uidx[x] * a.maxm + j] = -1; +} + +// Decode rows and short windows: 128 columns and 16 members a block (grouped_body's tile), warp sums apart. +extern "C" __global__ void __launch_bounds__(128) tf_ink2x_rows(const ink2x::WideArgs a) { + ink2x::wide_body(a); +} + +// Prompt chunks: 64 columns and 32 members a block, one sum buffer. +extern "C" __global__ void __launch_bounds__(128) tf_ink2x_wide(const ink2x::WideArgs a) { + ink2x::wide_body(a); +} + +namespace ink2m { + +__device__ __forceinline__ float bf(uint16_t u) { return __uint_as_float(static_cast(u) << 16); } +__device__ __forceinline__ uint16_t tobf(float f) { return __bfloat16_as_ushort(__float2bfloat16_rn(f)); } + +struct CombineArgs { + const uint16_t* experts; // bf16 [rows * slots, H] + const int* pick; + const float* weights; + uint16_t* out; // bf16 [rows, H] + int rows, h, slots; +}; + +struct TensorActArgs { + const uint16_t* gateup; // bf16 [P, 2 * M], adjacent gate and up projections + uint16_t* out; // bf16 [P, M] + int n; +}; + + +__device__ __forceinline__ float cap(float x, float c) { return c * tanhf(x / c); } + +} // namespace ink2m + + +// Tensor-core gate/up rows are interleaved; keep the scalar baseline's softcapped SwiGLU arithmetic. +extern "C" __global__ void __launch_bounds__(256) tf_ink2moe_tensor_act(const ink2m::TensorActArgs a) { + const int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i >= a.n) return; + const float gate = ink2m::bf(a.gateup[2 * (size_t)i]); + const float up = ink2m::bf(a.gateup[2 * (size_t)i + 1]); + const float g = ink2m::cap(gate, 4.0f); + const float u = ink2m::cap(up, 25.0f); + const float sigmoid = 1.0f / (1.0f + expf(-gate)); + const float activated = g * sigmoid * u; + a.out[i] = ink2m::tobf(activated); +} + +// One output element: route in ascending expert id, independent of the router's selection order. +extern "C" __global__ void __launch_bounds__(256) tf_ink2moe_combine(const ink2m::CombineArgs a) { + const int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i >= a.rows * a.h) return; + const int row = i / a.h, col = i % a.h; + float total = 0.0f; + uint32_t seen = 0; + for (int n = 0; n < a.slots; ++n) { + int best = -1, id = 0; + for (int s = 0; s < a.slots; ++s) { + if (seen & (1u << s)) continue; + const int e = a.pick[row * a.slots + s]; + if (best < 0 || e < id) { + best = s; + id = e; + } + } + seen |= 1u << best; + const float out = ink2m::bf(a.experts[(size_t)(row * a.slots + best) * a.h + col]); + total = __fadd_rn(total, __fmul_rn(a.weights[row * a.slots + best], out)); + } + a.out[i] = ink2m::tobf(total); +} diff --git a/zig/kernels/cuda/inkling2/loop_math.cu b/zig/kernels/cuda/inkling2/loop_math.cu new file mode 100644 index 00000000000..824ec095042 --- /dev/null +++ b/zig/kernels/cuda/inkling2/loop_math.cu @@ -0,0 +1,285 @@ +// Inkling 2 Mini: raw block residuals, two-bank messages, rank-64 gates and three-input QKV projection. +#include +#include + +namespace ink2l { + +constexpr int kRank = 64; +constexpr int kMaxBlocks = 8; +constexpr int kMaxQueries = 3; + +__device__ __forceinline__ float bf(uint16_t u) { return __uint_as_float(static_cast(u) << 16); } +__device__ __forceinline__ uint16_t tobf(float f) { return __bfloat16_as_ushort(__float2bfloat16_rn(f)); } +__device__ __forceinline__ float bfr(float f) { return bf(tobf(f)); } + +__device__ __forceinline__ float warpSum(float v) { + for (int o = 16; o > 0; o >>= 1) v += __shfl_xor_sync(0xffffffffu, v, o); + return v; +} + +// Every call has the same reduction tree: lanes' strided chains, each warp's butterfly, then warp 0 over partials. +template +__device__ __forceinline__ void blockSums(float (&v)[N], float* sh) { + const int lane = threadIdx.x & 31, w = threadIdx.x >> 5, nw = blockDim.x >> 5; + for (int i = 0; i < N; ++i) v[i] = warpSum(v[i]); + __syncthreads(); + if (lane == 0) + for (int i = 0; i < N; ++i) sh[i * 32 + w] = v[i]; + __syncthreads(); + for (int i = 0; i < N; ++i) { + const float t = lane < nw ? sh[i * 32 + lane] : 0.0f; + v[i] = __shfl_sync(0xffffffffu, warpSum(t), 0); + } +} + +// A14(a): Mini's queried residual and message dot products scale after the dot, by binary32(1 / 48). +__device__ __forceinline__ float queryScale(int c) { + return c == 2304 ? 1.0f / 48.0f : rsqrtf(static_cast(c)); +} + +__device__ __forceinline__ void softmax2(float l0, float l1, float* w) { + const float m = fmaxf(l0, l1); + const float e0 = expf(l0 - m), e1 = expf(l1 - m); + const float d = __fadd_rn(e0, e1); + w[0] = __fdiv_rn(e0, d); + w[1] = __fdiv_rn(e1, d); +} + +struct ArArgs { + const uint16_t* blocks[kMaxBlocks]; // bf16 [rows, C], one completed state a pointer + const void* partial; // the final source, BF16 or FP32 according to partial_bf16 + const float* query; // fp32 [nq, C] + float* out; // fp32 [nq, rows, C], deliberately neither normalized nor rounded + int n_blocks, partial_bf16, nq, rows, C; + float eps; +}; + +// The AR half of Small's residual mix, without its fused RMSNorm. Needed before Mini's controller, not just after it. +__device__ void ar(const ArArgs a) { + __shared__ float sh[32 * (1 + kMaxQueries)]; + __shared__ float wts[kMaxQueries][kMaxBlocks + 1]; + __shared__ float rr[kMaxBlocks + 1]; + const size_t row = blockIdx.x; + const int n = a.n_blocks + 1; + auto entry = [&](int j, int c) -> float { + if (j < a.n_blocks) return bf(a.blocks[j][row * a.C + c]); + return a.partial_bf16 ? bf(static_cast(a.partial)[row * a.C + c]) + : static_cast(a.partial)[row * a.C + c]; + }; + for (int j = 0; j < n; ++j) { + float ss[1] = {0.0f}; + for (int c = threadIdx.x; c < a.C; c += blockDim.x) { + const float x = entry(j, c); + ss[0] = __fmaf_rn(x, x, ss[0]); + } + blockSums<1>(ss, sh); + if (threadIdx.x == 0) rr[j] = rsqrtf(__fadd_rn(__fdiv_rn(ss[0], static_cast(a.C)), a.eps)); + } + __syncthreads(); + for (int j = 0; j < n; ++j) { + float dots[kMaxQueries] = {0.0f, 0.0f, 0.0f}; + for (int c = threadIdx.x; c < a.C; c += blockDim.x) { + const float normalized = __fmul_rn(entry(j, c), rr[j]); + for (int q = 0; q < a.nq; ++q) + dots[q] = __fmaf_rn(a.query[static_cast(q) * a.C + c], normalized, dots[q]); + } + blockSums(dots, sh); + if (threadIdx.x == 0) + for (int q = 0; q < a.nq; ++q) wts[q][j] = __fmul_rn(dots[q], queryScale(a.C)); + } + __syncthreads(); + if (threadIdx.x < a.nq) { + float* l = wts[threadIdx.x]; + float m = -INFINITY, d = 0.0f; + for (int j = 0; j < n; ++j) m = fmaxf(m, l[j]); + for (int j = 0; j < n; ++j) d = __fadd_rn(d, expf(l[j] - m)); + for (int j = 0; j < n; ++j) l[j] = __fdiv_rn(expf(l[j] - m), d); + } + __syncthreads(); + for (int q = 0; q < a.nq; ++q) { + float* out = a.out + (static_cast(q) * a.rows + row) * a.C; + for (int c = threadIdx.x; c < a.C; c += blockDim.x) { + float h = 0.0f; + for (int j = 0; j < n; ++j) { + const float z = __fmul_rn(entry(j, c), rr[j]); + h = __fmaf_rn(wts[q][j], z, h); + } + out[c] = h; + } + } +} + +} // namespace ink2l + +extern "C" __global__ void __launch_bounds__(512) tf_ink2_loop_ar(const ink2l::ArArgs a) { + ink2l::ar(a); +} + +namespace ink2l { + +// One block handles one token and role, sharing each bank's normalization across all 12 core queries. +__device__ void messages(const uint16_t* __restrict__ bank0, const uint16_t* __restrict__ bank1, + const float* __restrict__ qm, const float* __restrict__ qkv, + float* __restrict__ out, int rows, int core_layers, int c, float eps) { + __shared__ float sh[2 * 32]; + __shared__ float inv[2], w[2]; + const size_t row = blockIdx.x; + const int role = blockIdx.y; // q, k, v, mlp + const uint16_t* banks[2] = {bank0 + row * c, bank1 + row * c}; + const float* role_queries = role == 0 || role == 3 ? qm : qkv; + const int odd = role == 3 || role == 2; + float ss[2] = {0.0f, 0.0f}; + for (int i = threadIdx.x; i < c; i += blockDim.x) { + const float x0 = bf(banks[0][i]), x1 = bf(banks[1][i]); + ss[0] = __fmaf_rn(x0, x0, ss[0]); + ss[1] = __fmaf_rn(x1, x1, ss[1]); + } + blockSums<2>(ss, sh); + if (threadIdx.x == 0) { + inv[0] = rsqrtf(__fadd_rn(__fdiv_rn(ss[0], static_cast(c)), eps)); + inv[1] = rsqrtf(__fadd_rn(__fdiv_rn(ss[1], static_cast(c)), eps)); + } + __syncthreads(); + for (int j = 0; j < core_layers; ++j) { + const float* query = role_queries + static_cast(2 * j + odd) * c; + float dots[2] = {0.0f, 0.0f}; + for (int i = threadIdx.x; i < c; i += blockDim.x) { + const float q = query[i]; + const float b0 = __fmul_rn(bf(banks[0][i]), inv[0]); + const float b1 = __fmul_rn(bf(banks[1][i]), inv[1]); + dots[0] = __fmaf_rn(q, b0, dots[0]); + dots[1] = __fmaf_rn(q, b1, dots[1]); + } + blockSums<2>(dots, sh); + if (threadIdx.x == 0) + softmax2(__fmul_rn(dots[0], queryScale(c)), __fmul_rn(dots[1], queryScale(c)), w); + __syncthreads(); + // Plane-major [core][role][rows][c]: the gates read each role's rows as one contiguous plane. + float* dst = out + ((static_cast(j) * 4 + role) * rows + row) * static_cast(c); + for (int i = threadIdx.x; i < c; i += blockDim.x) { + const float b0 = __fmul_rn(bf(banks[0][i]), inv[0]); + const float b1 = __fmul_rn(bf(banks[1][i]), inv[1]); + const float m0 = __fmul_rn(w[0], b0), m1 = __fmul_rn(w[1], b1); + dst[i] = __fadd_rn(m0, m1); + } + } +} + +// One gate a block. A shared BF16 zeta is the sole bottleneck output; forget/gain stay FP32 through tanh (A7(a)). +__device__ void gate(const float* __restrict__ h, const float* __restrict__ m, + const uint16_t* __restrict__ down, const uint16_t* __restrict__ forget, + const uint16_t* __restrict__ gain, float* __restrict__ out, + int c, float eps) { + __shared__ float sh[2 * 32]; + __shared__ float inv_h, inv_m; + __shared__ uint16_t zeta[kRank]; + const size_t row = blockIdx.x; + const float* hr = h + row * c; + const float* mr = m + row * c; + float ss[2] = {0.0f, 0.0f}; + for (int i = threadIdx.x; i < c; i += blockDim.x) { + ss[0] = __fmaf_rn(hr[i], hr[i], ss[0]); + ss[1] = __fmaf_rn(mr[i], mr[i], ss[1]); + } + blockSums<2>(ss, sh); + if (threadIdx.x == 0) { + inv_h = rsqrtf(__fadd_rn(__fdiv_rn(ss[0], static_cast(c)), eps)); + inv_m = rsqrtf(__fadd_rn(__fdiv_rn(ss[1], static_cast(c)), eps)); + } + __syncthreads(); + // Pair ranks to reuse each normalized input, but keep every dot's 256-thread chains and two-level reduction tree. + for (int r = 0; r < kRank; r += 2) { + float acc[2] = {0.0f, 0.0f}; + const uint16_t* d0 = down + static_cast(r) * (2 * c); + const uint16_t* d1 = d0 + 2 * c; + for (int i = threadIdx.x; i < 2 * c; i += blockDim.x) { + const bool message = i >= c; + const float x = message ? mr[i - c] : hr[i]; + const float n = bfr(__fmul_rn(x, message ? inv_m : inv_h)); + acc[0] = __fmaf_rn(bf(d0[i]), n, acc[0]); + acc[1] = __fmaf_rn(bf(d1[i]), n, acc[1]); + } + blockSums<2>(acc, sh); + if (threadIdx.x == 0) { + zeta[r] = tobf(acc[0]); + zeta[r + 1] = tobf(acc[1]); + } + } + __syncthreads(); + float* dst = out + row * c; + for (int i = threadIdx.x; i < c; i += blockDim.x) { + const uint16_t* f = forget + static_cast(i) * kRank; + const uint16_t* g = gain + static_cast(i) * kRank; + float sf = 0.0f, sg = 0.0f; + for (int r = 0; r < kRank; ++r) { + const float z = bf(zeta[r]); + sf = __fmaf_rn(bf(f[r]), z, sf); + sg = __fmaf_rn(bf(g[r]), z, sg); + } + const float fg = tanhf(sf), gg = tanhf(sg); + // The reference's four FP32 rounding steps, kept explicit so contraction cannot erase any of them. + const float keep = __fsub_rn(1.0f, fg); + const float old = __fmul_rn(keep, hr[i]); + const float added = __fmul_rn(gg, mr[i]); + dst[i] = __fadd_rn(old, added); + } +} + +} // namespace ink2l + +extern "C" __global__ void __launch_bounds__(256) + tf_ink2_loop_messages(const uint16_t* __restrict__ bank0, const uint16_t* __restrict__ bank1, + const float* __restrict__ qm, const float* __restrict__ qkv, float* __restrict__ out, + int rows, int core_layers, int c, float eps) { + ink2l::messages(bank0, bank1, qm, qkv, out, rows, core_layers, c, eps); +} + +extern "C" __global__ void __launch_bounds__(256) + tf_ink2_loop_gate(const float* __restrict__ h, const float* __restrict__ m, const uint16_t* __restrict__ down, + const uint16_t* __restrict__ forget, const uint16_t* __restrict__ gain, float* __restrict__ out, + int rows, int c, float eps) { + (void)rows; + ink2l::gate(h, m, down, forget, gain, out, c, eps); +} + +// Mini QKV launch uses three independently normalized inputs; other kernels and cache/partial layouts are unchanged. +extern "C" __global__ void __launch_bounds__(256) + tf_ink2_loop_project_qkv(const uint16_t* __restrict__ uq, const uint16_t* __restrict__ uk, + const uint16_t* __restrict__ uv, const uint16_t* __restrict__ wq, + const uint16_t* __restrict__ wk, const uint16_t* __restrict__ wv, + uint16_t* __restrict__ raw_q, uint16_t* __restrict__ raw_k, + uint16_t* __restrict__ raw_v, int rows, int c, int q_width, int kv_width) { + constexpr int kRows = 16, kOutputs = 16, kSlice = 32; + __shared__ uint16_t sx[kRows * kSlice], sw[kOutputs * kSlice]; + const int role = blockIdx.z; // q=0, k=1, v=2 + const int width = role == 0 ? q_width : kv_width; + const int row0 = static_cast(blockIdx.x) * kRows; + const int j0 = static_cast(blockIdx.y) * kOutputs; + if (j0 >= width) return; + const uint16_t* x = role == 0 ? uq : role == 1 ? uk : uv; + const uint16_t* w = role == 0 ? wq : role == 1 ? wk : wv; + const int tr = threadIdx.x / kOutputs, tj = threadIdx.x % kOutputs; + const int row = row0 + tr, j = j0 + tj; + float sum = 0.0f; + // A block reuses each normalized tile for 16 outputs and each weight tile for 16 prompt rows. + for (int k0 = 0; k0 < c; k0 += kSlice) { + for (int e = threadIdx.x; e < kRows * kSlice; e += blockDim.x) { + const int r = e / kSlice, k = k0 + e % kSlice; + sx[e] = row0 + r < rows && k < c ? x[static_cast(row0 + r) * c + k] : 0; + sw[e] = j0 + r < width && k < c ? w[static_cast(j0 + r) * c + k] : 0; + } + __syncthreads(); + for (int k = 0; k < kSlice && k0 + k < c; ++k) + sum = __fmaf_rn(ink2l::bf(sx[tr * kSlice + k]), ink2l::bf(sw[tj * kSlice + k]), sum); + __syncthreads(); + } + uint16_t* out = role == 0 ? raw_q : role == 1 ? raw_k : raw_v; + if (row < rows && j < width) out[static_cast(row) * width + j] = ink2l::tobf(sum); +} + +// Global dynamic taps: dot in FP32, store as BF16, and widen to FP32 before the convolution. +extern "C" __global__ void __launch_bounds__(256) + tf_ink2_loop_round_bf16(const float* __restrict__ in, float* __restrict__ out, long long n) { + const long long i = static_cast(blockIdx.x) * blockDim.x + threadIdx.x; + if (i < n) out[i] = ink2l::bf(ink2l::tobf(in[i])); +} diff --git a/zig/kernels/cuda/inkling2/modelopt.cu b/zig/kernels/cuda/inkling2/modelopt.cu new file mode 100644 index 00000000000..2f8a4c40bd7 --- /dev/null +++ b/zig/kernels/cuda/inkling2/modelopt.cu @@ -0,0 +1,204 @@ +// Mini routed experts: checkpoint NVFP4/MXFP8 codes decode to BF16 mma fragments; no activation quantization. +#include +#include +#include "experts.cuh" + +namespace ink2o { + +struct Weight { + const uint8_t* codes; + const uint8_t* scales; + const float* amax; + const float* den; + long long E, N, K; + int G, format, row0, row_step; +}; + +__device__ __forceinline__ float e2m1(uint32_t n) { + const uint32_t s = (n & 8) ? 0x80000000u : 0; + const uint32_t e = (n >> 1) & 3, m = n & 1; + if (!e) return __uint_as_float(s | (m ? 0x3f000000u : 0)); + return __uint_as_float(s | ((e + 126) << 23) | (m << 22)); +} + +__device__ __forceinline__ float e4m3(uint32_t n) { + const uint32_t s = (n & 128) ? 0x80000000u : 0; + const uint32_t e = (n >> 3) & 15, m = n & 7; + if (e == 15 && m == 7) return __uint_as_float(s | 0x7fc00000u); + if (!e) return (s ? -1.f : 1.f) * (float)m * 0.001953125f; + return __uint_as_float(s | ((e + 120) << 23) | (m << 20)); +} + +__device__ __forceinline__ float e8m0(uint32_t n) { + if (n == 0) return 0x1p-127f; + return __uint_as_float(n << 23); +} + +__device__ __forceinline__ float bf(float x) { return __bfloat162float(__float2bfloat16_rn(x)); } +__device__ __forceinline__ __nv_bfloat16 decoded(const Weight& w, long long e, long long row, long long col) { + const long long z = e * w.N * w.K + row * w.K + col; + const uint32_t nib = w.format ? w.codes[z] : ((w.codes[z / 2] >> ((col & 1) * 4)) & 15); + float v; + if (w.format) { + v = __fmul_rn(e4m3(nib), e8m0(w.scales[z / w.G])); + } else { + const float outer = __fdiv_rn(bf(__ldg(w.amax + e)), bf(__ldg(w.den))); + v = __fmul_rn(__fmul_rn(e2m1(nib), e4m3(w.scales[z / w.G])), outer); + } + return __float2bfloat16_rn(v); +} + +// One uint4 is eight BF16 weights in the fragment layout of experts_bf16.cu. +__device__ __forceinline__ uint4 ld_w(const Weight& w, long long e, int cb, int g, int lane, int j) { + const int row = w.row0 + w.row_step * (cb * 32 + 8 * j + (lane >> 2)), col = g * 32 + 4 * (lane & 3); + uint16_t h[8]; +#pragma unroll + for (int i = 0; i < 8; ++i) { + const int c = col + (i & 3) + 16 * (i >> 2); + h[i] = __bfloat16_as_ushort(decoded(w, e, row, c)); + } + uint4 o; + o.x = h[0] | (uint32_t)h[1] << 16; + o.y = h[2] | (uint32_t)h[3] << 16; + o.z = h[4] | (uint32_t)h[5] << 16; + o.w = h[6] | (uint32_t)h[7] << 16; + return o; +} + +template +__device__ __forceinline__ void body(const __nv_bfloat16* __restrict__ X, int x_stride, int slots, Weight w, + int KG, int NB, const int* __restrict__ items, const int* __restrict__ item_count, + const int* __restrict__ members, void* __restrict__ out, int N, int skip) { + const int lane = threadIdx.x & 31, gq = lane >> 2, t = lane & 3; + const int units = __ldg(item_count) * NB; + for (int unit = blockIdx.x * WARPS + (threadIdx.x >> 5); unit < units; unit += gridDim.x * WARPS) { + const int it = unit / NB, cb = unit - it * NB; + const int e = __ldg(items + 3 * it), first = __ldg(items + 3 * it + 1), cnt = __ldg(items + 3 * it + 2); + if (e == skip) continue; + for (int r0 = 0; r0 < cnt; r0 += 16 * RT) { + bool v[RT][2]; + int pr[RT][2]; + const __nv_bfloat16* x[RT][2]; +#pragma unroll + for (int r = 0; r < RT; ++r) +#pragma unroll + for (int h = 0; h < 2; ++h) { + const int i = r0 + 16 * r + gq + 8 * h; + v[r][h] = i < cnt; + pr[r][h] = v[r][h] ? __ldg(members + first + i) : 0; + x[r][h] = X + (size_t)(slots ? pr[r][h] / slots : pr[r][h]) * x_stride + 4 * t; + } + float acc[1][RT][NTW][4]; +#pragma unroll + for (int r = 0; r < RT; ++r) +#pragma unroll + for (int j = 0; j < NTW; ++j) acc[0][r][j][0] = acc[0][r][j][1] = acc[0][r][j][2] = acc[0][r][j][3] = 0.f; + const uint2 zero = make_uint2(0u, 0u); + for (int g = 0; g < KG; ++g) { + uint4 ww[NTW]; +#pragma unroll + for (int j = 0; j < NTW; ++j) ww[j] = ld_w(w, e, cb, g, lane, j); +#pragma unroll + for (int r = 0; r < RT; ++r) { + uint2 xa[2], xb[2]; +#pragma unroll + for (int q = 0; q < 2; ++q) { + xa[q] = v[r][0] ? __ldg(reinterpret_cast(x[r][0] + 32 * g + 16 * q)) : zero; + xb[q] = v[r][1] ? __ldg(reinterpret_cast(x[r][1] + 32 * g + 16 * q)) : zero; + } +#pragma unroll + for (int q = 0; q < 2; ++q) +#pragma unroll + for (int j = 0; j < NTW; ++j) + mma(acc[0][r][j], xa[q].x, xb[q].x, xa[q].y, xb[q].y, q ? ww[j].z : ww[j].x, q ? ww[j].w : ww[j].y); + } + } +#pragma unroll + for (int r = 0; r < RT; ++r) + epilogue<3, 1, RT>(acc, r, out, N, cb * COLS + 2 * t, pr[r][0], pr[r][1], v[r][0], v[r][1], 0.f); + } + } +} + +__device__ __forceinline__ void act(const __nv_bfloat16* __restrict__ gate, const __nv_bfloat16* __restrict__ up, + __nv_bfloat16* __restrict__ out, int n, float gate_cap, float up_cap) { + const int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i >= n) return; + const float raw = __bfloat162float(gate[i]); + const float g = gate_cap * tanhf(raw / gate_cap); + const float u = up_cap * tanhf(__bfloat162float(up[i]) / up_cap); + // ฯƒ(raw) is its own FP32 rounding before the two left-to-right products (ยง6.4). + const float sigmoid = 1.f / (1.f + expf(-raw)); + const float a = g * sigmoid * u; + out[i] = __float2bfloat16_rn(a); +} + +__device__ __forceinline__ void combine(const int32_t* __restrict__ pick, const float* __restrict__ wts, + const __nv_bfloat16* __restrict__ ey, __nv_bfloat16* __restrict__ out, + int rows, int hidden, int slots, int experts) { + const int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i >= rows * hidden) return; + const int r = i / hidden, h = i - r * hidden; + float total = 0.f; + uint32_t seen = 0; + for (int n = 0; n < slots; ++n) { + int best = -1; + int32_t id = 0; + for (int s = 0; s < slots; ++s) { + if (seen & (1u << s)) continue; + const int32_t expert = pick[r * slots + s]; + if (expert < 0 || expert >= experts) continue; + if (best < 0 || expert < id) { + best = s; + id = expert; + } + } + if (best < 0) break; + seen |= 1u << best; + const int pair = r * slots + best; + const float term = __fmul_rn(__ldg(wts + pair), __bfloat162float(ey[pair * hidden + h])); + total = __fadd_rn(total, term); + } + out[i] = __float2bfloat16_rn(total); +} + +} // namespace ink2o + +// Pair indices are row * slots + slot. Items hold a physical expert ID, a global member offset and a count. +extern "C" __global__ void __launch_bounds__(32) tf_ink2moe_plan(const int32_t* __restrict__ pick, + int* __restrict__ items, int* __restrict__ members, int* __restrict__ item_count, + int rows, int slots, int experts, int tile) { + if (blockIdx.x || threadIdx.x) return; + const int pairs = rows * slots; + int used = 0, at = 0; + for (int e = 0; e < experts; ++e) { + const int first = used; + for (int pair = 0; pair < pairs; ++pair) { + if (pick[pair] == e) members[used++] = pair; + } + const int count = used - first; + for (int off = 0; off < count; off += tile) { + items[3 * at] = e; + items[3 * at + 1] = first + off; + items[3 * at + 2] = (count - off < tile) ? count - off : tile; + ++at; + } + } + *item_count = at; +} + +#define TF_INK2_MOE(NAME, RT) \ + extern "C" __global__ void __launch_bounds__(128) NAME(const __nv_bfloat16* __restrict__ X, int x_stride, int slots, \ + ink2o::Weight w, int KG, int NB, const int* __restrict__ items, const int* __restrict__ item_count, \ + const int* __restrict__ members, void* __restrict__ out, int N, int skip) { \ + ink2o::body(X, x_stride, slots, w, KG, NB, items, item_count, members, out, N, skip); \ + } +TF_INK2_MOE(tf_ink2moe_up, 1) +TF_INK2_MOE(tf_ink2moe_prompt_up, 4) +extern "C" __global__ void __launch_bounds__(256) tf_ink2moe_act(const __nv_bfloat16* g, const __nv_bfloat16* u, __nv_bfloat16* o, int n, float gc, float uc) { + ink2o::act(g, u, o, n, gc, uc); +} +extern "C" __global__ void __launch_bounds__(256) tf_ink2moe_combine(const int32_t* p, const float* w, const __nv_bfloat16* e, + __nv_bfloat16* o, int rows, int hidden, int slots, int experts) { + ink2o::combine(p, w, e, o, rows, hidden, slots, experts); +} diff --git a/zig/kernels/cuda/inkling2/ops.cu b/zig/kernels/cuda/inkling2/ops.cu index 2e26fc6892c..648eb50686d 100644 --- a/zig/kernels/cuda/inkling2/ops.cu +++ b/zig/kernels/cuda/inkling2/ops.cu @@ -3,7 +3,6 @@ #include #include #include - #include "exl3_decode.cuh" namespace ink2o { @@ -97,10 +96,20 @@ extern "C" __global__ void __launch_bounds__(512) tf_ink2_mix(const MixArgs a) { return a.partial_bf16 ? bf(reinterpret_cast(sp)[i]) : reinterpret_cast(sp)[i]; }; if (a.query) { - // every block's sums in one pass and one reduction: each sum adds in the order it did block by block - float v[kV]; + // Normalize each source before its query dot; both passes retain the declared strided/shuffle reduction. + float ss[kMaxBlocks + 1] = {}; + for (int c0 = 0; c0 < C; c0 += kMixCols) { + mixStage(a, row, c0, sb, sp); + for (int i = threadIdx.x; i < kMixCols && c0 + i < C; i += blockDim.x) { #pragma unroll - for (int i = 0; i < kV; ++i) v[i] = 0.0f; + for (int j = 0; j < kMaxBlocks + 1; ++j) + if (j < n) { const float x = entry(j, i); ss[j] += x * x; } + } + __syncthreads(); + } + blockSums(ss, sh); + if (threadIdx.x == 0) for (int j = 0; j < n; ++j) rr[j] = rsqrtf(ss[j] / C + 1e-6f); __syncthreads(); + float v[kV] = {}; for (int c0 = 0; c0 < C; c0 += kMixCols) { mixStage(a, row, c0, sb, sp); for (int i = threadIdx.x; i < kMixCols && c0 + i < C; i += blockDim.x) { @@ -109,26 +118,18 @@ extern "C" __global__ void __launch_bounds__(512) tf_ink2_mix(const MixArgs a) { #pragma unroll for (int q = 0; q < kMaxQueries; ++q) qc[q] = q < a.nq ? a.query[static_cast(q) * C + c] : 0.0f; #pragma unroll - for (int j = 0; j < kMaxBlocks + 1; ++j) { - if (j < n) { - const float x = entry(j, i); - v[j * (1 + kMaxQueries)] += x * x; + for (int j = 0; j < kMaxBlocks + 1; ++j) if (j < n) { + const float normalized = entry(j, i) * rr[j]; #pragma unroll - for (int q = 0; q < kMaxQueries; ++q) - if (q < a.nq) v[j * (1 + kMaxQueries) + 1 + q] += x * qc[q]; - } + for (int q = 0; q < kMaxQueries; ++q) + if (q < a.nq) v[j * (1 + kMaxQueries) + 1 + q] += qc[q] * normalized; } } - __syncthreads(); // the next slice overwrites the staged one + __syncthreads(); } blockSums(v, sh); - if (threadIdx.x == 0) - for (int j = 0; j < n; ++j) { - const float r = rsqrtf(v[j * (1 + kMaxQueries)] / C + 1e-6f); - rr[j] = r; - for (int q = 0; q < a.nq; ++q) - wts[q][j] = v[j * (1 + kMaxQueries) + 1 + q] * r * rsqrtf(static_cast(C)); - } + if (threadIdx.x == 0) for (int j = 0; j < n; ++j) for (int q = 0; q < a.nq; ++q) wts[q][j] = + v[j * (1 + kMaxQueries) + 1 + q] * rsqrtf(static_cast(C)); __syncthreads(); if (threadIdx.x < a.nq) { float* l = wts[threadIdx.x]; @@ -199,18 +200,19 @@ extern "C" __global__ void __launch_bounds__(512) tf_ink2_mix_rows(const MixArgs }; if (a.query) { for (int j = 0; j < n; ++j) { - float v[1 + kMaxQueries] = {0.0f, 0.0f, 0.0f, 0.0f}; + float ss[1] = {0.0f}; + for (int c = threadIdx.x; c < C; c += blockDim.x) { const float x = entry(j, c); ss[0] += x * x; } + blockSums<1>(ss, sh); if (threadIdx.x == 0) rr[j] = rsqrtf(ss[0] / C + 1e-6f); + } + __syncthreads(); + for (int j = 0; j < n; ++j) { + float dots[kMaxQueries] = {0.0f, 0.0f, 0.0f}; for (int c = threadIdx.x; c < C; c += blockDim.x) { - const float x = entry(j, c); - v[0] += x * x; - for (int q = 0; q < a.nq; ++q) v[1 + q] += x * a.query[static_cast(q) * C + c]; - } - blockSums<1 + kMaxQueries>(v, sh); - const float r = rsqrtf(v[0] / C + 1e-6f); - if (threadIdx.x == 0) { - rr[j] = r; - for (int q = 0; q < a.nq; ++q) wts[q][j] = v[1 + q] * r * rsqrtf(static_cast(C)); + const float normalized = entry(j, c) * rr[j]; for (int q = 0; q < a.nq; ++q) + dots[q] += a.query[static_cast(q) * C + c] * normalized; } + blockSums(dots, sh); + if (threadIdx.x == 0) for (int q = 0; q < a.nq; ++q) wts[q][j] = dots[q] * rsqrtf(static_cast(C)); } __syncthreads(); if (threadIdx.x < a.nq) { diff --git a/zig/kernels/cuda/inkling2/vision.cu b/zig/kernels/cuda/inkling2/vision.cu new file mode 100644 index 00000000000..5b0468bb4a7 --- /dev/null +++ b/zig/kernels/cuda/inkling2/vision.cu @@ -0,0 +1,203 @@ +// Inkling 2's vision tower glue: patch rows to the sequence, axial rotary, layer-scaled residuals, full attention. +#include +#include + +#include "prefill_attention.cuh" + +namespace ink2v { + +using namespace tf_prefill_attention; + +constexpr int kWidth = 1024; // the tower's hidden size +constexpr int kHeads = 16; +constexpr int kDim = 64; +constexpr int kPairs = kDim / 2; +constexpr int kThreads = 256; + +__device__ __forceinline__ float bf(__nv_bfloat16 v) { return __bfloat162float(v); } + +__device__ __forceinline__ __nv_bfloat16 tobf(float v) { return __float2bfloat16_rn(v); } + +// prefill_attention.cu's vision_kernel body (v1.2.7, verbatim): 16 query rows a warp, 64-key tiles, online softmax. +template +__device__ __forceinline__ void attend(const __nv_bfloat16* __restrict__ qkv, __nv_bfloat16* __restrict__ out, int W, int HO, + float scale) { + static_assert(D % 16 == 0, "whole 16-dim steps"); + constexpr int C = D / 8, RS = C + 1, K16 = D / 16, NT = BN / 8, THREADS = 32 * WARPS; + extern __shared__ uint4 smem[]; + const int warp = threadIdx.x / 32, lane = threadIdx.x % 32, g = lane / 4, qd = lane % 4, mt = lane / 8; + const int head = blockIdx.y, wrow = (blockIdx.x * WARPS + warp) * 16, last = W - 1, tiles = (W + BN - 1) / BN; + const int64_t stride = 3LL * HO * D; + const __nv_bfloat16* __restrict__ q = qkv + head * D; + const __nv_bfloat16* __restrict__ kc = qkv + (HO + head) * D; + const __nv_bfloat16* __restrict__ vc = qkv + (2 * HO + head) * D; + auto stage = [&](int t) { // tile t's K rows then V rows into buffer t % 2 + uint4* dst = smem + (t & 1) * 2 * BN * RS; + for (int i = threadIdx.x; i < 2 * BN * C; i += THREADS) { + const int kv = i / (BN * C), r = (i / C) % BN, c = i % C, key = t * BN + r; + const bool in = key < W; + cp16z(dst + (kv * BN + r) * RS + c, (kv ? vc : kc) + (int64_t)(in ? key : 0) * stride + c * 8, in); + } + commit(); + }; + uint32_t qa[K16][4]; + const int r0 = wrow + g, r1 = r0 + 8; + { + const uint32_t* q0 = reinterpret_cast(q + (int64_t)min(r0, last) * stride); + const uint32_t* q1 = reinterpret_cast(q + (int64_t)min(r1, last) * stride); +#pragma unroll + for (int k = 0; k < K16; ++k) { + qa[k][0] = r0 < W ? q0[8 * k + qd] : 0u; + qa[k][1] = r1 < W ? q1[8 * k + qd] : 0u; + qa[k][2] = r0 < W ? q0[8 * k + qd + 4] : 0u; + qa[k][3] = r1 < W ? q1[8 * k + qd + 4] : 0u; + } + } + float o[C][4]; +#pragma unroll + for (int i = 0; i < C; ++i) o[i][0] = o[i][1] = o[i][2] = o[i][3] = 0.0f; + float m0 = -INFINITY, m1 = -INFINITY, l0 = 0.0f, l1 = 0.0f; + stage(0); + for (int t = 0; t < tiles; ++t) { + cp_wait<0>(); + __syncthreads(); // tile t landed, and every warp is done with tile t - 1 + if (t + 1 < tiles) stage(t + 1); + const uint4* ks = smem + (t & 1) * 2 * BN * RS; + const uint4* vs = ks + BN * RS; + float sc[NT][4]; +#pragma unroll + for (int k = 0; k < K16; ++k) { +#pragma unroll + for (int n = 0; n < NT; n += 2) { + uint32_t b[4]; + ldmatrix4(b, ks + (8 * (n + mt / 2) + lane % 8) * RS + 2 * k + mt % 2); + if (k == 0) { + mma0(sc[n], qa[k], b[0], b[1]); + mma0(sc[n + 1], qa[k], b[2], b[3]); + } else { + mma(sc[n], qa[k], b[0], b[1]); + mma(sc[n + 1], qa[k], b[2], b[3]); + } + } + } + const int kb = t * BN + 2 * qd; + float tm0 = -INFINITY, tm1 = -INFINITY; +#pragma unroll + for (int n = 0; n < NT; ++n) { + const int c = kb + 8 * n; + sc[n][0] = c <= last ? __fmul_rn(sc[n][0], scale) : -INFINITY; + sc[n][1] = c + 1 <= last ? __fmul_rn(sc[n][1], scale) : -INFINITY; + sc[n][2] = c <= last ? __fmul_rn(sc[n][2], scale) : -INFINITY; + sc[n][3] = c + 1 <= last ? __fmul_rn(sc[n][3], scale) : -INFINITY; + tm0 = fmaxf(tm0, fmaxf(sc[n][0], sc[n][1])); + tm1 = fmaxf(tm1, fmaxf(sc[n][2], sc[n][3])); + } + for (int x = 1; x <= 2; x *= 2) { + tm0 = fmaxf(tm0, __shfl_xor_sync(0xffffffffu, tm0, x)); + tm1 = fmaxf(tm1, __shfl_xor_sync(0xffffffffu, tm1, x)); + } + const bool act0 = tm0 != -INFINITY, act1 = tm1 != -INFINITY; + const float n0 = act0 ? fmaxf(m0, tm0) : m0, n1 = act1 ? fmaxf(m1, tm1) : m1; + const float a0 = act0 ? (m0 == -INFINITY ? 0.0f : texp(__fsub_rn(m0, n0))) : 1.0f; + const float a1 = act1 ? (m1 == -INFINITY ? 0.0f : texp(__fsub_rn(m1, n1))) : 1.0f; + float c0[NT], c1[NT]; +#pragma unroll + for (int n = 0; n < NT; ++n) { + const int c = kb + 8 * n; + sc[n][0] = act0 && c <= last ? texp(__fsub_rn(sc[n][0], n0)) : 0.0f; + sc[n][1] = act0 && c + 1 <= last ? texp(__fsub_rn(sc[n][1], n0)) : 0.0f; + sc[n][2] = act1 && c <= last ? texp(__fsub_rn(sc[n][2], n1)) : 0.0f; + sc[n][3] = act1 && c + 1 <= last ? texp(__fsub_rn(sc[n][3], n1)) : 0.0f; + c0[n] = __fadd_rn(sc[n][0], sc[n][1]); + c1[n] = __fadd_rn(sc[n][2], sc[n][3]); + } + l0 = __fmaf_rn(l0, a0, rowsum(c0)); + l1 = __fmaf_rn(l1, a1, rowsum(c1)); + m0 = n0; + m1 = n1; +#pragma unroll + for (int i = 0; i < C; ++i) { + o[i][0] = __fmul_rn(o[i][0], a0); + o[i][1] = __fmul_rn(o[i][1], a0); + o[i][2] = __fmul_rn(o[i][2], a1); + o[i][3] = __fmul_rn(o[i][3], a1); + } +#pragma unroll + for (int j = 0; j < NT / 2; ++j) { // 16-key chunks, in key order for every output tile + const uint32_t pa[4] = {pack(sc[2 * j][0], sc[2 * j][1]), pack(sc[2 * j][2], sc[2 * j][3]), + pack(sc[2 * j + 1][0], sc[2 * j + 1][1]), pack(sc[2 * j + 1][2], sc[2 * j + 1][3])}; +#pragma unroll + for (int i = 0; i < C; i += 2) { + uint32_t b[4]; + ldmatrix4t(b, vs + (16 * j + 8 * (mt % 2) + lane % 8) * RS + i + mt / 2); + mma(o[i], pa, b[0], b[1]); + mma(o[i + 1], pa, b[2], b[3]); + } + } + } +#pragma unroll + for (int i = 0; i < C; ++i) { + const int d = 8 * i + 2 * qd; + if (r0 < W) + *reinterpret_cast(out + ((int64_t)r0 * HO + head) * D + d) = + pack(tdiv(o[i][0], l0), tdiv(o[i][1], l0)); + if (r1 < W) + *reinterpret_cast(out + ((int64_t)r1 * HO + head) * D + d) = + pack(tdiv(o[i][2], l1), tdiv(o[i][3], l1)); + } +} + +} // namespace ink2v + +using namespace ink2v; + +// Block a head and 128 rows: every row of one picture over all its rows (no mask), q | k | v heads of qkv [W, 3 H 64]. +extern "C" __global__ void __launch_bounds__(256) tf_ink2v_attention(const __nv_bfloat16* __restrict__ qkv, + __nv_bfloat16* __restrict__ out, int W, int HO, + float scale) { + attend(qkv, out, W, HO, scale); +} + +// Block a sequence row: row 0 the class token bf16(cls + cls_pos), row r the patch r - 1 plus its resampled position. +extern "C" __global__ void __launch_bounds__(kThreads) tf_ink2v_embed(const __nv_bfloat16* __restrict__ pe, + const __nv_bfloat16* __restrict__ table, + const uint32_t* __restrict__ taps, + const float* __restrict__ wts, + const __nv_bfloat16* __restrict__ cls, + const __nv_bfloat16* __restrict__ cls_pos, + __nv_bfloat16* __restrict__ x) { + const int r = blockIdx.x; + for (int c = threadIdx.x; c < kWidth; c += kThreads) { + float v; + if (r == 0) { + v = __fadd_rn(bf(cls[c]), bf(cls_pos[c])); + } else { + const int p = r - 1; + float s = 0.0f; + for (int t = 0; t < 4; ++t) s = __fadd_rn(s, __fmul_rn(bf(table[(int64_t)taps[p * 4 + t] * kWidth + c]), wts[p * 4 + t])); + v = __fadd_rn(bf(pe[(int64_t)p * kWidth + c]), bf(tobf(s))); + } + x[(int64_t)r * kWidth + c] = tobf(v); + } +} + +// Block a row: q and k of qkv [rows, 3 H 64] turned in place, pair j by cos, sin [rows][32]; fp32 as torch, then bf16. +extern "C" __global__ void __launch_bounds__(kThreads) tf_ink2v_rope(__nv_bfloat16* __restrict__ qkv, const float* __restrict__ cs, + const float* __restrict__ sn) { + const int r = blockIdx.x; + for (int i = threadIdx.x; i < 2 * kHeads * kPairs; i += kThreads) { + const int j = i % kPairs; + __nv_bfloat16* p = qkv + (int64_t)r * 3 * kWidth + (i / kPairs) * kDim + 2 * j; + const float c = cs[r * kPairs + j], s = sn[r * kPairs + j], a = bf(p[0]), b = bf(p[1]); + p[0] = tobf(__fadd_rn(__fmul_rn(a, c), __fmul_rn(-b, s))); + p[1] = tobf(__fadd_rn(__fmul_rn(b, c), __fmul_rn(a, s))); + } +} + +// x [count] = bf16(x + bf16(gamma[i % width] y)): the layer-scaled residual add of an attention or MLP output. +extern "C" __global__ void __launch_bounds__(kThreads) tf_ink2v_scale_add(__nv_bfloat16* __restrict__ x, const __nv_bfloat16* __restrict__ y, + const __nv_bfloat16* __restrict__ gamma, int64_t count) { + const int64_t i = (int64_t)blockIdx.x * kThreads + threadIdx.x; + if (i >= count) return; + x[i] = tobf(__fadd_rn(bf(x[i]), bf(tobf(__fmul_rn(bf(gamma[i % kWidth]), bf(y[i])))))); +} diff --git a/zig/kernels/cuda/nemotron_ops.cu b/zig/kernels/cuda/nemotron_ops.cu index 8323808a536..0eb61b66570 100644 --- a/zig/kernels/cuda/nemotron_ops.cu +++ b/zig/kernels/cuda/nemotron_ops.cu @@ -41,7 +41,7 @@ __device__ __forceinline__ int scan128(int v, int* total) { extern "C" __global__ void __launch_bounds__(128) tf_plan_routed(const int* __restrict__ picks, int rows, int slots, int routed, int E, int T, int* __restrict__ members, int* __restrict__ items, int* __restrict__ counts) { - __shared__ int pk[16 * 8]; + __shared__ int pk[32 * 8]; // rows <= 32 (a wide shared round), slots <= 8 const int tid = threadIdx.x, P = rows * slots; for (int p = tid; p < P; p += blockDim.x) pk[p] = p % slots < routed ? picks[p] : -1; __syncthreads(); @@ -309,12 +309,15 @@ extern "C" __global__ void tf_splice_rows(__nv_bfloat16* __restrict__ H, const _ for (int i = threadIdx.x; i < D; i += blockDim.x) H[r * D + i] = F[static_cast(s) * D + i]; } +// Parts of a batched draft or shared round at most: cuda_kernels.zig's parts. +constexpr int PARTS = 16; + // A batched draft's rows: each part's rows of `a` (wa bytes a row) and `b` (wb bytes a row) to dst_a and dst_b. struct GatherRows { - const void* a[8]; - const void* b[8]; - int rows[8]; - int row0[8]; + const void* a[PARTS]; + const void* b[PARTS]; + int rows[PARTS]; + int row0[PARTS]; int wa; int wb; }; @@ -323,8 +326,8 @@ struct GatherRows { extern "C" __global__ void tf_nemo_gather_rows(const GatherRows g, void* __restrict__ dst_a, void* __restrict__ dst_b) { const int r = blockIdx.x; int k = 0; - while (k < 8 && !(r >= g.row0[k] && r < g.row0[k] + g.rows[k])) ++k; - if (k == 8) return; + while (k < PARTS && !(r >= g.row0[k] && r < g.row0[k] + g.rows[k])) ++k; + if (k == PARTS) return; const int at = r - g.row0[k]; const char* sa = static_cast(g.a[k]) + (size_t)at * g.wa; char* da = static_cast(dst_a) + (size_t)r * g.wa; @@ -337,8 +340,8 @@ extern "C" __global__ void tf_nemo_gather_rows(const GatherRows g, void* __restr // A span's last row: each part's source a/b row moved to dst row k, ascending k with a barrier between rows. struct LastRows { - const void* a[8]; - const void* b[8]; + const void* a[PARTS]; + const void* b[PARTS]; }; // One block: row k's sources to dst row k in order, so a row that is another part's destination is read before written. @@ -356,10 +359,10 @@ extern "C" __global__ void tf_nemo_gather_last(const LastRows g, void* __restric // A level's rows: each part's token and probability to its own buffers at tok_at/prob_at, one row a part. struct ScatterRows { - unsigned* tok[8]; - float* prob[8]; - int rows[8]; - int row0[8]; + unsigned* tok[PARTS]; + float* prob[PARTS]; + int rows[PARTS]; + int row0[PARTS]; int tok_at; int prob_at; }; @@ -368,8 +371,8 @@ struct ScatterRows { extern "C" __global__ void tf_nemo_scatter_rows(const unsigned* __restrict__ TOK, const float* __restrict__ PROB, const ScatterRows g) { const int r = blockIdx.x; int k = 0; - while (k < 8 && !(r >= g.row0[k] && r < g.row0[k] + g.rows[k])) ++k; - if (k == 8 || threadIdx.x != 0) return; + while (k < PARTS && !(r >= g.row0[k] && r < g.row0[k] + g.rows[k])) ++k; + if (k == PARTS || threadIdx.x != 0) return; const int at = r - g.row0[k]; g.tok[k][g.tok_at + at] = TOK[r]; if (g.prob[k] != nullptr) g.prob[k][g.prob_at + at] = PROB[r]; diff --git a/zig/kernels/cuda/qmmf.cu b/zig/kernels/cuda/qmmf.cu index 20452d9f6e1..c58b7b14321 100644 --- a/zig/kernels/cuda/qmmf.cu +++ b/zig/kernels/cuda/qmmf.cu @@ -197,6 +197,18 @@ template __global__ void qmmf_kernel template __global__ void qmmf_kernel(const __nv_bfloat16* __restrict__, const unsigned char* __restrict__, const uint8_t* __restrict__, float, void* __restrict__, float* __restrict__, int, int, int, int, int, int, int); template __global__ void qmmf_kernel(const __nv_bfloat16* __restrict__, const unsigned char* __restrict__, const uint8_t* __restrict__, float, void* __restrict__, float* __restrict__, int, int, int, int, int, int, int); template __global__ void qmmf_kernel(const __nv_bfloat16* __restrict__, const unsigned char* __restrict__, const uint8_t* __restrict__, float, void* __restrict__, float* __restrict__, int, int, int, int, int, int, int); +// TF_QMMF_HALF_BN: FP4, FP8 and FP8G half tiles, their n8 tiles 0-3 or 4-7 and those columns' scales. +#define HALF_N(MODE, F32, CLUSTER) \ + template __global__ void qmmf_kernel( \ + const __nv_bfloat16* __restrict__, const unsigned char* __restrict__, const uint8_t* __restrict__, float, \ + void* __restrict__, float* __restrict__, int, int, int, int, int, int, int); +#define HALF_N_ALL(MODE) \ + HALF_N(MODE, false, false) HALF_N(MODE, false, true) HALF_N(MODE, true, false) HALF_N(MODE, true, true) +HALF_N_ALL(FP4) +HALF_N_ALL(FP8) +HALF_N_ALL(FP8G) +#undef HALF_N_ALL +#undef HALF_N template __global__ void qmmf_kernel(const __nv_bfloat16* __restrict__, const unsigned char* __restrict__, const uint8_t* __restrict__, float, void* __restrict__, float* __restrict__, int, int, int, int, int, int, int); template __global__ void qmmf_kernel(const __nv_bfloat16* __restrict__, const unsigned char* __restrict__, const uint8_t* __restrict__, float, void* __restrict__, float* __restrict__, int, int, int, int, int, int, int); @@ -259,6 +271,68 @@ BF16_K32(false) BF16_K32(true) #undef BF16_K32 +// A grouped launch's projection: weights, output, scale, shape, K slices, first block (qmmf_group.zig Seg). +struct GroupSeg { + const unsigned char* w; + const uint8_t* bs; + void* out; + float scale; + int N, SK, npad, first, tiles; +}; +struct GroupSegs { + GroupSeg s[4]; + int count, pad; +}; + +// Same-input projections in one launch: a block is one tile and slice of one projection, summed as its own launch. +template +__device__ __forceinline__ void qmmf_group_body(const __nv_bfloat16* __restrict__ x, const GroupSegs& segs, int M, + int K) { + constexpr int BM = 16, WM = 1, WN = 4, STAGES = 4; + constexpr bool F32 = false, FUSE = false; + qmm_frag::grid_launch(); // a dependent launch, as qmmf_kernel + int si = 0; + for (int i = 1; i < segs.count; ++i) si = static_cast(blockIdx.x) >= segs.s[i].first ? i : si; + const GroupSeg& seg = segs.s[si]; + const unsigned char* __restrict__ w = seg.w; + const uint8_t* __restrict__ bs = seg.bs; + void* __restrict__ out = seg.out; + float* __restrict__ part = nullptr; + const float scale = seg.scale; + const int N = seg.N, SK = seg.SK, ldx = K, group = 1; + [[maybe_unused]] const int npad = seg.npad; + const int local = static_cast(blockIdx.x) - seg.first, slice = local % SK, tile = local / SK; + if (tile >= seg.tiles) { // a block past the projection's tiles: only its cluster's two barriers + if constexpr (CLUSTER) { +#if __CUDA_ARCH__ >= 900 + auto cluster = cooperative_groups::this_cluster(); + cluster.sync(); + cluster.sync(); +#endif + } + return; + } +#define TF_QMMF_WFIRST +#define TF_QMMF_GROUP +#include "qmmf_body.cuh" +#undef TF_QMMF_GROUP +#undef TF_QMMF_WFIRST +} + +#define TF_QMMF_GROUP_ENTRY(NAME, MODE, BN, CLUSTER) \ +extern "C" __global__ void __launch_bounds__(128) NAME(const __nv_bfloat16* x, const GroupSegs segs, int M, int K) { \ + qmmf_group_body(x, segs, M, K); \ +} +TF_QMMF_GROUP_ENTRY(tf_qmmf_group_fp4, FP4, 64, false) +TF_QMMF_GROUP_ENTRY(tf_qmmf_group_fp4_c, FP4, 64, true) +TF_QMMF_GROUP_ENTRY(tf_qmmf_group_fp8, FP8, 64, false) +TF_QMMF_GROUP_ENTRY(tf_qmmf_group_fp8_c, FP8, 64, true) +TF_QMMF_GROUP_ENTRY(tf_qmmf_group_bf16, BF16, 64, false) +TF_QMMF_GROUP_ENTRY(tf_qmmf_group_bf16_c, BF16, 64, true) +TF_QMMF_GROUP_ENTRY(tf_qmmf_group_bf16_half, BF16, 32, false) +TF_QMMF_GROUP_ENTRY(tf_qmmf_group_bf16_half_c, BF16, 32, true) +#undef TF_QMMF_GROUP_ENTRY + template __global__ void reduce_kernel(const float* __restrict__, void* __restrict__, long long, int, float); template __global__ void reduce_kernel(const float* __restrict__, void* __restrict__, long long, int, float); diff --git a/zig/kernels/cuda/qmmf_body.cuh b/zig/kernels/cuda/qmmf_body.cuh index f3dc2ee6cf8..0ff9ecd3b2e 100644 --- a/zig/kernels/cuda/qmmf_body.cuh +++ b/zig/kernels/cuda/qmmf_body.cuh @@ -18,8 +18,14 @@ #else const int KG = K / GS, slice_groups = KG / SK, per = FUSE ? KG : slice_groups; #endif +#ifdef TF_QMMF_GROUP + // a grouped launch's block: its projection's tile and K slice, as that projection's own launch numbers them + const int2 at = tile_of(tile, M, N, BM, BN, group); + const int m0 = at.x, n0 = at.y, g0 = slice * per; +#else const int2 at = tile_of(blockIdx.x, M, N, BM, BN, group); const int m0 = at.x, n0 = at.y, slice = FUSE ? 0 : blockIdx.z, g0 = slice * per; +#endif #ifndef TF_QMMF_STRIDED [[maybe_unused]] uint64_t* ready = reinterpret_cast(buf + STAGES * T::STAGE); // K32 has no barriers @@ -282,7 +288,12 @@ cluster.sync(); if (slice == 0) { for (int peer = 1; peer < SK; ++peer) { +#ifdef TF_QMMF_GROUP + // the tile's slices sit side by side in the cluster, slice 0 first + const float* theirs = cluster.map_shared_rank(mine, cluster.block_rank() - slice + peer); +#else const float* theirs = cluster.map_shared_rank(mine, peer); +#endif #pragma unroll for (int i = 0; i < T::MT; ++i) #pragma unroll diff --git a/zig/kernels/cuda/qwen35.cu b/zig/kernels/cuda/qwen35.cu index fa65456fcea..e309a302fdd 100644 --- a/zig/kernels/cuda/qwen35.cu +++ b/zig/kernels/cuda/qwen35.cu @@ -554,18 +554,18 @@ extern "C" __global__ void __launch_bounds__(128) tf_q35_attn_partial(Geo geo, c extern "C" __global__ void __launch_bounds__(256) tf_q35_attn_rows(Geo geo, const __nv_bfloat16* __restrict__ Q, const Seg* __restrict__ segs, const int* __restrict__ rowseg, const Ancestor* __restrict__ rowanc, int layer, const int* __restrict__ P, float scale, int total, - float* __restrict__ PM, float* __restrict__ PL, float* __restrict__ PO) { + float* __restrict__ PM, float* __restrict__ PL, float* __restrict__ PO, bool all_rows) { extern __shared__ __align__(16) uint4 attn_tiles[]; - tf_q35_tc::attn_rows<4, tf_q35_tc::Bf16Tiles<256>>({attn_tiles, nullptr, nullptr, nullptr}, geo, Q, segs, rowseg, rowanc, layer, P, scale, total, PM, PL, PO); + tf_q35_tc::attn_rows<4, tf_q35_tc::Bf16Tiles<256>>({attn_tiles, nullptr, nullptr, nullptr}, geo, Q, segs, rowseg, rowanc, layer, P, scale, total, PM, PL, PO, all_rows); } // tf_q35_attn_rows for a forward whose streams share pages (cuda_cache.anyShares): rows on one page run join. extern "C" __global__ void __launch_bounds__(256) tf_q35_attn_rows_join(Geo geo, const __nv_bfloat16* __restrict__ Q, const Seg* __restrict__ segs, const int* __restrict__ rowseg, const Ancestor* __restrict__ rowanc, int layer, const int* __restrict__ P, float scale, int total, - float* __restrict__ PM, float* __restrict__ PL, float* __restrict__ PO) { + float* __restrict__ PM, float* __restrict__ PL, float* __restrict__ PO, bool all_rows) { extern __shared__ __align__(16) uint4 attn_tiles[]; - tf_q35_tc::attn_rows<4, tf_q35_tc::Bf16Tiles<256>, true>({attn_tiles, nullptr, nullptr, nullptr}, geo, Q, segs, rowseg, rowanc, layer, P, scale, total, PM, PL, PO); + tf_q35_tc::attn_rows<4, tf_q35_tc::Bf16Tiles<256>, true>({attn_tiles, nullptr, nullptr, nullptr}, geo, Q, segs, rowseg, rowanc, layer, P, scale, total, PM, PL, PO, all_rows); } extern "C" __global__ void __launch_bounds__(128) tf_q35_attn_partial_whole(Geo geo, const __nv_bfloat16* __restrict__ Q, const Seg* __restrict__ segs, @@ -579,7 +579,7 @@ extern "C" __global__ void __launch_bounds__(128) tf_q35_attn_partial_whole(Geo extern "C" __global__ void __launch_bounds__(256) tf_q35_attn_rows_whole(Geo geo, const __nv_bfloat16* __restrict__ Q, const Seg* __restrict__ segs, const int* __restrict__ rowseg, const Ancestor* __restrict__ rowanc, int layer, const int* __restrict__ P, float scale, int total, - float* __restrict__ PM, float* __restrict__ PL, float* __restrict__ PO) { + float* __restrict__ PM, float* __restrict__ PL, float* __restrict__ PO, bool all_rows) { extern __shared__ __align__(16) uint4 attn_tiles[]; - tf_q35_tc::attn_rows<4, tf_q35_tc::WholeBf16Tiles<256>>({attn_tiles, nullptr, nullptr, nullptr}, geo, Q, segs, rowseg, rowanc, layer, P, scale, total, PM, PL, PO); + tf_q35_tc::attn_rows<4, tf_q35_tc::WholeBf16Tiles<256>>({attn_tiles, nullptr, nullptr, nullptr}, geo, Q, segs, rowseg, rowanc, layer, P, scale, total, PM, PL, PO, all_rows); } diff --git a/zig/kernels/cuda/qwen35_attn_tc.cuh b/zig/kernels/cuda/qwen35_attn_tc.cuh index e5dfbaa4b4c..ca3c5995438 100644 --- a/zig/kernels/cuda/qwen35_attn_tc.cuh +++ b/zig/kernels/cuda/qwen35_attn_tc.cuh @@ -225,7 +225,7 @@ template // JOIN: another stream's row __device__ __forceinline__ void attn_rows(TileStore store, Geo geo, const __nv_bfloat16* __restrict__ Q, const Seg* __restrict__ segs, const int* __restrict__ rowseg, const Ancestor* __restrict__ rowanc, int layer, const int* __restrict__ P, float scale, int total, - float* __restrict__ PM, float* __restrict__ PL, float* __restrict__ PO) { + float* __restrict__ PM, float* __restrict__ PL, float* __restrict__ PO, bool all_rows = false) { constexpr int LINES = 16 * MT, WARPS = 2 * MT, NT = HD / 8 / WARPS; __shared__ __align__(16) __nv_bfloat16 pt[LINES][TK + 8]; __shared__ float red[2][LINES], alpha[LINES]; @@ -237,12 +237,12 @@ __device__ __forceinline__ void attn_rows(TileStore store, Geo geo, const __nv_b const int tid = threadIdx.x, warp = tid >> 5, lane = tid & 31, g = lane >> 2, qd = lane & 3; const int c = blockIdx.y, h = blockIdx.z, m0 = blockIdx.x * RB; if (c >= MAXCH) return; - // the group's rows of long streams (a short stream's rows are attn_one's) + // Long streams, or every stream under the exact all-length opt-in. if (tid < RB) { const int m = m0 + tid; r_seg[tid] = -1; if constexpr (JOIN) r_p0[tid] = -1; - if (m < total && !past_rows(P, m) && segs[rowseg[m]].len >= GROUP_LEN) { + if (m < total && !past_rows(P, m) && (all_rows || segs[rowseg[m]].len >= GROUP_LEN)) { const Seg sg = segs[rowseg[m]]; const Ancestor anc = rowanc[m]; const int keys = sg.len + rows_seen(anc), ck = chunk_keys(keys); diff --git a/zig/kernels/cuda/ricursive.cu b/zig/kernels/cuda/ricursive.cu new file mode 100644 index 00000000000..c6b35dc64f0 --- /dev/null +++ b/zig/kernels/cuda/ricursive.cu @@ -0,0 +1,61 @@ +// Ripple's glue on CUDA: glue.metal step for step (bf16 residual, fp32 sums), and its planted controls. + +#include "ricursive.cuh" + +namespace tf_rc { + +// Embed: grid (ceil(width / 256), rows), 256 threads; ids are u32. +#define TF_RC_EMBED(NAME, BF_SCALE) \ + extern "C" __global__ void __launch_bounds__(NT) NAME(const unsigned* __restrict__ ids, const bf16* __restrict__ E, \ + bf16* __restrict__ R, bf16* __restrict__ V0, int rows, int width, \ + float scale) { \ + embed(ids, E, R, V0, rows, width, scale); \ + } + +// Add-norm: grid rows, 256 threads; Y null skips the add, V0 null the lerp; width % 8 == 0, <= 8,192, 16-byte rows. +#define TF_RC_ADD_NORM(NAME, K) \ + extern "C" __global__ void __launch_bounds__(NT) \ + NAME(bf16* __restrict__ R, const bf16* __restrict__ Y, const bf16* __restrict__ w_post, \ + const bf16* __restrict__ w_next, const bf16* __restrict__ V0, bf16* __restrict__ X, bf16* __restrict__ VX, \ + int rows, int width, float eps, float blend) { \ + add_norm(R, Y, w_post, w_next, V0, X, VX, rows, width, eps, blend); \ + } + +// Gate: grid (ceil(width / 256), rows), 256 threads, A in place. +#define TF_RC_GATE(NAME, K) \ + extern "C" __global__ void __launch_bounds__(NT) NAME(bf16* __restrict__ A, const bf16* __restrict__ G, int rows, \ + int width) { \ + gate(A, G, rows, width); \ + } + +// SiLU-clamp: grid (ceil(width / 256), rows), 256 threads; GU rows are 2 x width (gate | up). +#define TF_RC_SILU_CLAMP(NAME, K) \ + extern "C" __global__ void __launch_bounds__(NT) NAME(const bf16* __restrict__ GU, bf16* __restrict__ A, int rows, \ + int width, float limit) { \ + silu_clamp(GU, A, rows, width, limit); \ + } + +TF_RC_EMBED(tf_rc_embed, false) +TF_RC_ADD_NORM(tf_rc_add_norm, NORM_ALL) +TF_RC_GATE(tf_rc_gate, SIG) +TF_RC_SILU_CLAMP(tf_rc_silu_clamp, SILU | LOW) + +// Controls, one a rounding point (each must fail the contract's shapes gate): the served kernel without it. +TF_RC_EMBED(tf_rc_ctl_embed_bf16_scale, true) +TF_RC_ADD_NORM(tf_rc_ctl_add_norm_y_row, NORM_ALL & ~Y_ROW) +TF_RC_ADD_NORM(tf_rc_ctl_add_norm_y_out, NORM_ALL & ~Y_OUT) +TF_RC_ADD_NORM(tf_rc_ctl_add_norm_resid, NORM_ALL & ~RESID) +TF_RC_ADD_NORM(tf_rc_ctl_add_norm_x_row, NORM_ALL & ~X_ROW) +TF_RC_ADD_NORM(tf_rc_ctl_add_norm_x_lerp, NORM_ALL & ~X_LERP) +TF_RC_GATE(tf_rc_ctl_gate_sigmoid, 0) +TF_RC_SILU_CLAMP(tf_rc_ctl_silu_round, LOW) +TF_RC_SILU_CLAMP(tf_rc_ctl_silu_no_lower, SILU) + +#undef TF_RC_EMBED +#undef TF_RC_ADD_NORM +#undef TF_RC_GATE +#undef TF_RC_SILU_CLAMP + +// Plug-in point: the prep (per-head norm, RoPE, KV-ring write) and attention kernels go below, named tf_rc_*. + +} // namespace tf_rc diff --git a/zig/kernels/cuda/ricursive.cuh b/zig/kernels/cuda/ricursive.cuh new file mode 100644 index 00000000000..8ac92f8030e --- /dev/null +++ b/zig/kernels/cuda/ricursive.cuh @@ -0,0 +1,163 @@ +// Ripple's CUDA glue: glue.metal's rc_embed, rc_add_norm, rc_gate and rc_silu_clamp at the same rounding points. +#pragma once + +#include +#include +#include + +#include "common/act.cuh" +#include "common/reduce.cuh" + +namespace tf_rc { + +typedef __nv_bfloat16 bf16; + +constexpr int NT = 256; // threads a block in every glue launch +constexpr int MOST = 4; // 8-value chunks a thread holds in add_norm: rows up to 8,192 wide + +__device__ __forceinline__ float bf(float x) { return __bfloat162float(__float2bfloat16_rn(x)); } +__device__ __forceinline__ float ld(const bf16* p) { return __bfloat162float(*p); } + +// A rounding point: bf16 when K keeps P; a control's K drops it. +template +__device__ __forceinline__ float point(float x) { return (K & P) ? bf(x) : x; } + +// add_norm's rounding points, a bit each; a control clears one. +constexpr int Y_ROW = 1; // bf16(y * inv): Y's norm before w_post +constexpr int Y_OUT = 2; // bf16(w_post * that): the normed branch +constexpr int RESID = 4; // bf16(r + normed): the residual the next norm reads +constexpr int X_ROW = 8; // bf16(r * inv): R's norm before w_next +constexpr int X_LERP = 16; // the lerp reads X as stored (bf16), not the fp32 product +constexpr int NORM_ALL = Y_ROW | Y_OUT | RESID | X_ROW | X_LERP; + +constexpr int SIG = 1; // gate: bf16(sigmoid(g)), the release's fp32 sigmoid then bf16 +constexpr int SILU = 1; // silu_clamp: bf16(silu(g)) +constexpr int LOW = 2; // silu_clamp: up's lower clamp (not a rounding point; the Metal family's control drops it) + +// R and V0 row r = bf16(E[ids[r]] * scale), the fp32 scale; BF_SCALE (a control) rounds the scale to bf16 first. +template +__device__ __forceinline__ void embed(const unsigned* __restrict__ ids, const bf16* __restrict__ E, bf16* __restrict__ R, + bf16* __restrict__ V0, int rows, int width, float scale) { + const int x = blockIdx.x * blockDim.x + threadIdx.x, row = blockIdx.y; + if (x >= width || row >= rows) return; + const size_t at = (size_t)row * width + x; + const bf16 v = __float2bfloat16_rn(__fmul_rn(ld(E + (size_t)ids[row] * width + x), BF_SCALE ? bf(scale) : scale)); + R[at] = v; + V0[at] = v; +} + +// torch.lerp on bf16 (its vectorized form): fma(w, e - s, s) below one half, else fma(w - 1, e - s, e); unrounded. +__device__ __forceinline__ float lerp(float s, float e, float w) { + const float d = __fsub_rn(e, s); + return fabsf(w) < 0.5f ? __fmaf_rn(w, d, s) : __fmaf_rn(__fsub_rn(w, 1.0f), d, e); +} + +// A thread's chunks t + j NT of a row's 8-value chunks, zeros past the row. +__device__ __forceinline__ void load_row(const bf16* __restrict__ p, int chunks, float (&v)[MOST][8]) { + const uint4* q = reinterpret_cast(p); +#pragma unroll + for (int j = 0; j < MOST; ++j) { + const int c = threadIdx.x + j * NT; + if (c < chunks) { + tf_common::unpack8(q[c], v[j]); + } else { +#pragma unroll + for (int e = 0; e < 8; ++e) v[j][e] = 0.0f; + } + } +} + +// A row's fp32 sum of squares (each thread's fma chain, then the block's tree) into 1 / sqrt(mean + eps). +__device__ __forceinline__ float inv_rms(const float (&v)[MOST][8], float* part, int width, float eps) { + float s = 0.0f; +#pragma unroll + for (int j = 0; j < MOST; ++j) +#pragma unroll + for (int e = 0; e < 8; ++e) s = __fmaf_rn(v[j][e], v[j][e], s); + return tf_common::rms_scale(tf_common::block_sum_tree(s, part, NT / 32), width, eps); +} + +// A row a block, R in place: R = bf16(R + bf16(w_post bf16(Y inv))); X = bf16(w_next bf16(R inv)); VX = lerp(V0, X). +template +__device__ __forceinline__ void add_norm(bf16* __restrict__ R, const bf16* __restrict__ Y, const bf16* __restrict__ w_post, + const bf16* __restrict__ w_next, const bf16* __restrict__ V0, bf16* __restrict__ X, + bf16* __restrict__ VX, int rows, int width, float eps, float blend) { + __shared__ float part[NT / 32]; + const int row = blockIdx.x, chunks = width / 8; + if (row >= rows) return; + const size_t base = (size_t)row * width; + float r[MOST][8]; + load_row(R + base, chunks, r); + if (Y != nullptr) { + float y[MOST][8]; + load_row(Y + base, chunks, y); + const float inv = inv_rms(y, part, width, eps); + const uint4* w4 = reinterpret_cast(w_post); + uint4* out = reinterpret_cast(R + base); +#pragma unroll + for (int j = 0; j < MOST; ++j) { + const int c = threadIdx.x + j * NT; + if (c >= chunks) continue; + float w[8]; + tf_common::unpack8(w4[c], w); +#pragma unroll + for (int e = 0; e < 8; ++e) { + const float normed = point(__fmul_rn(w[e], point(__fmul_rn(y[j][e], inv)))); + r[j][e] = point(__fadd_rn(r[j][e], normed)); + } + out[c] = tf_common::pack8(r[j]); + } + } + const float inv = inv_rms(r, part, width, eps); + const uint4* w4 = reinterpret_cast(w_next); +#pragma unroll + for (int j = 0; j < MOST; ++j) { + const int c = threadIdx.x + j * NT; + if (c >= chunks) continue; + float w[8], x[8]; + tf_common::unpack8(w4[c], w); +#pragma unroll + for (int e = 0; e < 8; ++e) x[e] = __fmul_rn(w[e], point(__fmul_rn(r[j][e], inv))); + const uint4 xs = tf_common::pack8(x); + reinterpret_cast(X + base)[c] = xs; + if (V0 == nullptr) continue; + float s[8], e8[8]; + tf_common::unpack8(reinterpret_cast(V0 + base)[c], s); + if (K & X_LERP) { + tf_common::unpack8(xs, e8); + } else { +#pragma unroll + for (int e = 0; e < 8; ++e) e8[e] = x[e]; + } +#pragma unroll + for (int e = 0; e < 8; ++e) s[e] = lerp(s[e], e8[e], blend); + reinterpret_cast(VX + base)[c] = tf_common::pack8(s); + } +} + +// The attention's output gate in place: A = bf16(A bf16(sigmoid(G))), G the bf16 g_proj rows. +template +__device__ __forceinline__ void gate(bf16* __restrict__ A, const bf16* __restrict__ G, int rows, int width) { + const int x = blockIdx.x * blockDim.x + threadIdx.x, row = blockIdx.y; + if (x >= width || row >= rows) return; + const size_t i = (size_t)row * width + x; + const float s = point(tf_common::sigmoid_rn(ld(G + i))); + A[i] = __float2bfloat16_rn(__fmul_rn(ld(A + i), s)); +} + +// The FFN on a stacked gate | up row: gate at most limit, up within +-limit, then bf16(bf16(silu(g)) u). +template +__device__ __forceinline__ void silu_clamp(const bf16* __restrict__ GU, bf16* __restrict__ A, int rows, int width, float limit) { + const int x = blockIdx.x * blockDim.x + threadIdx.x, row = blockIdx.y; + if (x >= width || row >= rows) return; + const size_t at = (size_t)row * 2 * width + x; + const float g0 = ld(GU + at), u0 = ld(GU + at + width); + // a comparison is false for a NaN, so it passes both clamps as torch.clamp keeps it + const float g = g0 > limit ? limit : g0; + const float hi = u0 > limit ? limit : u0; + const float u = (K & LOW) && u0 < -limit ? -limit : hi; + const float silu = point(tf_common::silu_rn(g)); + A[(size_t)row * width + x] = __float2bfloat16_rn(__fmul_rn(silu, u)); +} + +} // namespace tf_rc diff --git a/zig/kernels/cuda/ricursive_prep.cu b/zig/kernels/cuda/ricursive_prep.cu new file mode 100644 index 00000000000..b15f6366f5e --- /dev/null +++ b/zig/kernels/cuda/ricursive_prep.cu @@ -0,0 +1,23 @@ +// Ripple's attention prep on CUDA: the Metal family's rc_prep step for step, every rounding point kept. + +#include "ricursive_prep.cuh" + +// q and k heads normed (w, not 1 + w), NeoX-rotated if rope != 0; k and v at ring slot (pos + row) % ring, or in pages. +extern "C" __global__ void __launch_bounds__(tf_rcp::NT) + tf_rc_prep(const tf_rcp::Rows XQ, const tf_rcp::Rows XK, const tf_rcp::Rows XV, const float* __restrict__ inv, + const __nv_bfloat16* __restrict__ qw, const __nv_bfloat16* __restrict__ kw, __nv_bfloat16* __restrict__ Q, + __nv_bfloat16* __restrict__ KC, __nv_bfloat16* __restrict__ VC, int rows, int heads, int kv_heads, int pos, + int ring, int rope, float eps, const int* __restrict__ tab, long long page, int tok) { + tf_rcp::prep(XQ, XK, XV, inv, qw, kw, Q, KC, VC, rows, heads, kv_heads, pos, ring, rope, eps, tab, page, tok, tf_rcp::ALL); +} + +// tf_rc_prep with row r at pos[r] of stream slot[r] (device int32, so graphs replay new values); tf_rc_prep's bits. +extern "C" __global__ void __launch_bounds__(tf_rcp::NT) + tf_rc_prep_rows(const tf_rcp::Rows XQ, const tf_rcp::Rows XK, const tf_rcp::Rows XV, const float* __restrict__ inv, + const __nv_bfloat16* __restrict__ qw, const __nv_bfloat16* __restrict__ kw, + __nv_bfloat16* __restrict__ Q, __nv_bfloat16* __restrict__ KC, __nv_bfloat16* __restrict__ VC, int rows, + int heads, int kv_heads, const int* __restrict__ pos, const int* __restrict__ slot, int ring, int rope, + float eps, const int* __restrict__ tab, long long page, int tok, int stride) { + tf_rcp::prep_rows(XQ, XK, XV, inv, qw, kw, Q, KC, VC, rows, heads, kv_heads, pos, slot, ring, rope, eps, tab, page, tok, + stride, tf_rcp::ALL); +} diff --git a/zig/kernels/cuda/ricursive_prep.cuh b/zig/kernels/cuda/ricursive_prep.cuh new file mode 100644 index 00000000000..f60864a9e51 --- /dev/null +++ b/zig/kernels/cuda/ricursive_prep.cuh @@ -0,0 +1,119 @@ +// Ripple's attention prep (Metal ricursive/glue.metal's rc_prep) step for step; `keep`: its bf16 rounding points. +#pragma once + +#include +#include +#include "common/reduce.cuh" + +// tf_rcp, not tf_rc_prep: the kernel's extern "C" symbol takes that name. +namespace tf_rcp { + +typedef __nv_bfloat16 bf16; + +// Head dim 128, a lane's dims lane + 32 j; a warp a (head, row), 8 warps a block. +constexpr int D = 128, HALF = 64, PER = D / 32, WARPS = 8, NT = 32 * WARPS; + +// rc_prep's rounding points: x r, w times that, cos, sin, and the stored output (dropped: truncated, not rounded). +enum : int { NORM_ROW = 1, NORM_OUT = 2, COS = 4, SIN = 8, OUT = 16 }; +constexpr int ALL = 31; + +__device__ __forceinline__ float bf(float v) { return __bfloat162float(__float2bfloat16_rn(v)); } + +// v rounded to bf16 where `keep` holds the point p (a constant in the served kernel, so the test folds away). +__device__ __forceinline__ float point(float v, int keep, int p) { return (keep & p) != 0 ? bf(v) : v; } + +// The output as stored: to nearest even, or its fp32 bits' top half where `keep` drops OUT. +__device__ __forceinline__ bf16 store(float v, int keep) { + return (keep & OUT) != 0 ? __float2bfloat16_rn(v) : __float2bfloat16_rz(v); +} + +// One projection's output rows: its first row and the elements between rows (V is its own projection). +struct Rows { + const bf16* x; + int stride; + __device__ __forceinline__ const bf16* at(int row, int head) const { return x + (size_t)row * stride + (size_t)head * D; } +}; + +// A warp's unit of row `row` at position p: query head `unit` into Q, else key head unit - heads and its value at `at`. +__device__ __forceinline__ void unit_at(const Rows XQ, const Rows XK, const Rows XV, const float* __restrict__ inv, + const bf16* __restrict__ qw, const bf16* __restrict__ kw, bf16* __restrict__ Q, + bf16* __restrict__ KC, bf16* __restrict__ VC, int heads, int unit, int lane, int row, + int p, size_t at, int rope, float eps, int keep) { + const bool q = unit < heads; + const int head = q ? unit : unit - heads; + const bf16* src = q ? XQ.at(row, head) : XK.at(row, head); + const bf16* w = q ? qw : kw; + bf16* y = q ? Q + ((size_t)row * heads + head) * D : KC + at + (size_t)head * D; + float x[PER]; + float sum = 0.0f; // bf16(w bf16(x r)), r = rsqrt(sum x^2 / 128 + eps); intrinsics and fma: the same under any flags +#pragma unroll + for (int j = 0; j < PER; ++j) { + x[j] = __bfloat162float(src[lane + 32 * j]); + sum = fmaf(x[j], x[j], sum); + } + const float r = rsqrtf(__fadd_rn(__fdiv_rn(tf_common::warp_sum(sum), (float)D), eps)); +#pragma unroll + for (int j = 0; j < PER; ++j) { + const float wv = __bfloat162float(w[lane + 32 * j]); + x[j] = point(__fmul_rn(wv, point(__fmul_rn(x[j], r), keep, NORM_ROW)), keep, NORM_OUT); + } + const float position = (float)p; +#pragma unroll + for (int j = 0; j < PER; ++j) { + const int d = lane + 32 * j; + float v = x[j]; + if (rope != 0) { + const float angle = __fmul_rn(position, inv[d % HALF]); + const float c = point(cosf(angle), keep, COS), s = point(sinf(angle), keep, SIN); + const float other = j < 2 ? -x[j ^ 2] : x[j ^ 2]; // d < 64 pairs with d + 64 (negated), else with d - 64 + v = __fadd_rn(__fmul_rn(x[j], c), __fmul_rn(other, s)); + } + y[d] = store(v, keep); + } + if (q) return; + const bf16* vs = XV.at(row, head); + bf16* vd = VC + at + (size_t)head * D; +#pragma unroll + for (int j = 0; j < PER; ++j) vd[lane + 32 * j] = vs[lane + 32 * j]; // the value as it is +} + +// One stream's rows at pos + row: keys and values at ring slot (pos + row) % ring, or row p % tok of page tab[p / tok]. +__device__ __forceinline__ void prep(const Rows XQ, const Rows XK, const Rows XV, const float* __restrict__ inv, + const bf16* __restrict__ qw, const bf16* __restrict__ kw, bf16* __restrict__ Q, + bf16* __restrict__ KC, bf16* __restrict__ VC, int rows, int heads, int kv_heads, + int pos, int ring, int rope, float eps, const int* __restrict__ tab, long long page, + int tok, int keep) { + const int unit = blockIdx.x * (blockDim.x >> 5) + (threadIdx.x >> 5); + const int lane = threadIdx.x & 31; + const int row = blockIdx.y; + if (unit >= heads + kv_heads || row >= rows) return; // whole warps: unit_at's shuffles stay converged + const size_t kvw = (size_t)kv_heads * D; + const int p = pos + row; + // the key's cache row: its ring slot, or its page's row (an address only: the numerics are the ring's) + const size_t at = tab != nullptr ? (size_t)tab[p / tok] * (size_t)page + (size_t)(p % tok) * kvw + : (size_t)(p % ring) * kvw; + unit_at(XQ, XK, XV, inv, qw, kw, Q, KC, VC, heads, unit, lane, row, p, at, rope, eps, keep); +} + +// Row r at pos[r] of stream slot[r] (null: stream 0): ring row slot * ring + p % ring, or tab[slot * stride + p / tok]. +__device__ __forceinline__ void prep_rows(const Rows XQ, const Rows XK, const Rows XV, const float* __restrict__ inv, + const bf16* __restrict__ qw, const bf16* __restrict__ kw, bf16* __restrict__ Q, + bf16* __restrict__ KC, bf16* __restrict__ VC, int rows, int heads, int kv_heads, + const int* __restrict__ pos, const int* __restrict__ slot, int ring, int rope, + float eps, const int* __restrict__ tab, long long page, int tok, int stride, + int keep) { + const int unit = blockIdx.x * (blockDim.x >> 5) + (threadIdx.x >> 5); + const int lane = threadIdx.x & 31; + const int row = blockIdx.y; + if (unit >= heads + kv_heads || row >= rows) return; // whole warps: unit_at's shuffles stay converged + const size_t kvw = (size_t)kv_heads * D; + const int p = pos[row]; + const size_t s = slot != nullptr ? (size_t)slot[row] : 0; + // the key's cache row: its stream's ring slot, or its page's row by the stream's row of the table + const size_t at = tab != nullptr + ? (size_t)tab[s * (size_t)stride + (size_t)(p / tok)] * (size_t)page + (size_t)(p % tok) * kvw + : (s * (size_t)ring + (size_t)(p % ring)) * kvw; + unit_at(XQ, XK, XV, inv, qw, kw, Q, KC, VC, heads, unit, lane, row, p, at, rope, eps, keep); +} + +} // namespace tf_rcp diff --git a/zig/kernels/cuda/window_attention.cu b/zig/kernels/cuda/window_attention.cu index c90859146dd..95764803eb9 100644 --- a/zig/kernels/cuda/window_attention.cu +++ b/zig/kernels/cuda/window_attention.cu @@ -574,6 +574,10 @@ template __global__ void tf_window_prompt::wattn_kernel<128, 8, 4, 8>(const __nv template __global__ void tf_window_prompt::wattn_kernel<128, 8, 8, 8>(const __nv_bfloat16* __restrict__, const __nv_bfloat16* __restrict__, const __nv_bfloat16* __restrict__, __nv_bfloat16* __restrict__, int, int, int, int, int, float, int, int); +// Ripple's group 10 (no multiple of 4): two query heads a block, so 64 rows a block; each warp's arithmetic as above. +template __global__ void tf_window_prompt::wattn_kernel<128, 8, 2, 8>(const __nv_bfloat16* __restrict__, + const __nv_bfloat16* __restrict__, const __nv_bfloat16* __restrict__, __nv_bfloat16* __restrict__, int, int, int, + int, int, float, int, int); // Kolibri-1's full layers' prompt rows over pages: head dim 128, eight warps, four or eight query heads a block. #define TF_WATTN_PG(NAME, HPC) \ @@ -586,3 +590,5 @@ template __global__ void tf_window_prompt::wattn_kernel<128, 8, 8, 8>(const __nv TF_WATTN_PG(tf_window_prompt_h4_pg, 4) TF_WATTN_PG(tf_window_prompt_h8_pg, 8) +// Ripple's global layers over pages: two query heads a block. +TF_WATTN_PG(tf_window_prompt_h2_pg, 2) diff --git a/zig/kernels/hip/decode/plan.hip b/zig/kernels/hip/decode/plan.hip index d6b2a8a754e..aadb2943670 100644 --- a/zig/kernels/hip/decode/plan.hip +++ b/zig/kernels/hip/decode/plan.hip @@ -11,22 +11,6 @@ __device__ __forceinline__ float wave_sum(float x) { return __shfl(x, 0, 32); } -// x from lane ^ M of its 16-lane row (M < 16): a DPP row_xmask move, all lanes active. -template -__device__ __forceinline__ float row_xor(float x) { - return __builtin_bit_cast(float, __builtin_amdgcn_mov_dpp(__builtin_bit_cast(int, x), 0x160 + M, 0xf, 0xf, false)); -} - -// wave_sum's folds, own value then partner's at xor 16, 8, 4, 2, 1, without LDS: every lane ends with the sum. -__device__ __forceinline__ float wave_sum_dpp(float x) { - const int w = __builtin_bit_cast(int, x); - x += __builtin_bit_cast(float, __builtin_amdgcn_permlanex16(w, w, 0x76543210u, 0xfedcba98u, false, false)); - x += row_xor<8>(x); - x += row_xor<4>(x); - x += row_xor<2>(x); - return x + row_xor<1>(x); -} - // Row r's keys (already rotated, fp32) and values (the activation kind) into its slot's pages at its position. __device__ void plan_kv_write_body(const float* keys, const void* values, int kind, int rows, int kv_heads, int d, PlanArgs plan, int layer) { @@ -56,42 +40,8 @@ __device__ void plan_kv_write_act_body(const void* keys, const void* values, int cache[to] = static_cast(values)[i]; } -// Query heads a block takes together: they share a KV head, so its keys and values are read once for all of them. -constexpr int kMaxGroup = 16; - -// Keys a wave scores on long spans and on short ones: their loads go out together, each head's query read once. -constexpr int kScoreKeys = 4; +// Keys a wave scores on short spans (kScoreKeys on long ones, plan.hpp). constexpr int kScoreKeysShort = 2; -// Steps of its waves' keys a long-span block walks at d = 256 (launches/plan.zig's score_steps). -constexpr int kScoreSteps = 8; -// load() of a 16-bit cache element as a global load: a flat load also counts on lgkmcnt, which LDS reads wait on. -__device__ __forceinline__ float cache_load(const void* p, int kind, long long i) { - const uint16_t bits = ((const __attribute__((address_space(1))) uint16_t*)p)[i]; - return kind == 1 ? __half2float(__ushort_as_half(bits)) : bf16_to_float(bits); -} - -// A wave's KEYS keys from key0 at d = 256 into k, lane l taking elements l + 32 i; keys past `visible` are not loaded. -template -__device__ __forceinline__ void score_fetch(float (&k)[KEYS][8], const void* keys, int kind, const unsigned* pages, - unsigned pool, int kv, int key0, int visible, int lane) { -#pragma unroll - for (int j = 0; j < KEYS; ++j) { - if (key0 + j >= visible) break; - const long long base = page_at(pages, pool, kv, key0 + j, 256); -#pragma unroll - for (int i = 0; i < 8; ++i) k[j][i] = cache_load(keys, kind, base + lane + i * 32); - } -} - -// Lane 0's KEYS scores of a head from `at`: one 16-byte store when `whole` (aligned rows, span a multiple of KEYS). -template -__device__ __forceinline__ void score_store(float* at, const float (&sc)[KEYS], bool whole, int key0, int span) { - if (whole && KEYS == 4) { - *reinterpret_cast(at) = make_float4(sc[0], sc[1 % KEYS], sc[2 % KEYS], sc[3 % KEYS]); - } else { - for (int j = 0; j < KEYS; ++j) if (key0 + j < span) at[j] = sc[j]; - } -} // score_keys over a plan's rows: a warp scores KEYS keys for each of the block's heads; q fp32 or of kind QKIND. template @@ -155,134 +105,6 @@ __device__ void plan_score_body(const void* __restrict__ q, float* __restrict__ } } -// plan_score_body on long spans at d = 256 (tf_plan_score256_*): no element tests, kScoreSteps steps a block. -template -__device__ void plan_score256_body(const void* __restrict__ q, float* __restrict__ scores, int span, int heads, - int kv_heads, int d, float scale, PlanArgs plan, int layer) { - constexpr int KEYS = kScoreKeys, STEPS = kScoreSteps; - extern __shared__ float qs[]; // the block's query heads, group * d - const int batch = blockIdx.z, group = heads / gridDim.y, head0 = blockIdx.y * group; - const long long q0 = (static_cast(batch) * heads + head0) * d; - for (int i = threadIdx.x; i < group * d; i += blockDim.x) qs[i] = load(q, QKIND, q0 + i); // kind 0: q fp32 - __syncthreads(); - const int visible = min(plan.pos[batch] + 1, span); - const int lane = threadIdx.x & 31; - const unsigned long long* desc = plan_desc(plan, plan.slot[batch]); - float* __restrict__ rows = scores + (static_cast(batch) * heads + head0) * span; - const void* keys = reinterpret_cast(desc[plan_first(layer)]); - const unsigned* pages = plan_pages(plan, desc); - const unsigned pool = plan.pool; - const int kv = head0 / (heads / kv_heads); - const int stride = (blockDim.x >> 5) * KEYS; // keys a step of the block - const int first = blockIdx.x * STEPS * stride + (threadIdx.x >> 5) * KEYS; - const bool whole = (span % KEYS) == 0 && (reinterpret_cast(rows) & 15) == 0; - float kreg[KEYS][8] = {}; - score_fetch(kreg, keys, KIND, pages, pool, kv, first, visible, lane); -#pragma unroll 1 - for (int step = 0; step < STEPS; ++step) { - const int key0 = first + step * stride; - if (key0 >= span) break; // the same for the whole wave - float next[KEYS][8] = {}; - score_fetch(next, keys, KIND, pages, pool, kv, step + 1 < STEPS ? key0 + stride : span, visible, lane); - if (key0 >= visible) { // the wave's keys are all past the row's: -INFINITY wherever the span has them - float none[KEYS]; - for (int j = 0; j < KEYS; ++j) none[j] = -INFINITY; - for (int g = 0; lane == 0 && g < group; ++g) { - score_store(rows + key0 + static_cast(g) * span, none, whole, key0, span); - } - } else { -#pragma unroll - for (int g = 0; g < kMaxGroup; ++g) { - if (g < group) { // the same for the whole block, so every lane reaches the folds - float qv[8]; -#pragma unroll - for (int i = 0; i < 8; ++i) qv[i] = qs[g * 256 + lane + i * 32]; - float dot[KEYS]; -#pragma unroll - for (int j = 0; j < KEYS; ++j) { - float partial = 0.f; -#pragma unroll - for (int i = 0; i < 8; ++i) partial += qv[i] * kreg[j][i]; - dot[j] = wave_sum_dpp(partial); - } - if (lane == 0) { - float sc[KEYS]; -#pragma unroll - for (int j = 0; j < KEYS; ++j) sc[j] = key0 + j < visible ? dot[j] * scale : -INFINITY; - score_store(rows + key0 + static_cast(g) * span, sc, whole, key0, span); - } - } - } - } - __builtin_memcpy(kreg, next, sizeof(kreg)); - } -} - -// apply_values over a plan's rows: a 128-key tile of the block's heads, weights worked once a block, in its order. -template -__device__ void plan_apply_body(const float* __restrict__ scores, const float* __restrict__ stats, - float* __restrict__ partials, int span, int heads, int kv_heads, int d, - PlanArgs plan, int layer) { - __shared__ float weights[kMaxGroup * 128]; - const int batch = blockIdx.z; - const int visible = min(plan.pos[batch] + 1, span); - const int tile = blockIdx.x; - const int group = heads / gridDim.y; - const int head0 = blockIdx.y * group; - const long long first = static_cast(batch) * heads + head0; - const int lane = threadIdx.x; - const int key0 = tile * 128; - if (key0 >= visible) { // a tile past the keys in use adds zero - if (lane < d) { - for (int g = 0; g < group; ++g) partials[((first + g) * gridDim.x + tile) * d + lane] = 0.f; - } - return; - } - const int stop = min(key0 + 128, visible); - for (int i = threadIdx.x; i < group * 128; i += blockDim.x) { - const long long h = first + i / 128; - const int key = key0 + i % 128; - if (key < stop) weights[i] = expf(scores[h * span + key] - stats[h * 2]) / stats[h * 2 + 1]; - } - __syncthreads(); - if (lane >= d) return; - const unsigned long long* desc = plan_desc(plan, plan.slot[batch]); - const void* values = reinterpret_cast(desc[plan_second(layer)]); - const unsigned* table = plan_pages(plan, desc); - const int kv = head0 / (heads / kv_heads); - float acc[kMaxGroup] = {}; - // a page at a time: its table entry is read once, and the keys are summed in order - for (int key = key0; key < stop;) { - const int edge = min((key / kPageTokens + 1) * kPageTokens, stop); - const long long slot0 = page_row(table[key / kPageTokens], plan.pool, kv, 0, d) + lane; - // eight values loaded ahead, then summed in key order: the loads overlap, the sums are the same - for (; key + 8 <= edge; key += 8) { - float ahead[8]; -#pragma unroll - for (int u = 0; u < 8; ++u) - ahead[u] = load(values, KIND, slot0 + static_cast((key + u) % kPageTokens) * d); -#pragma unroll - for (int u = 0; u < 8; ++u) { -#pragma unroll - for (int g = 0; g < kMaxGroup; ++g) { - if (g < group) acc[g] += weights[g * 128 + key + u - key0] * ahead[u]; - } - } - } - for (; key < edge; ++key) { - const float value = load(values, KIND, slot0 + static_cast(key % kPageTokens) * d); -#pragma unroll - for (int g = 0; g < kMaxGroup; ++g) { - if (g < group) acc[g] += weights[g * 128 + key - key0] * value; - } - } - } -#pragma unroll - for (int g = 0; g < kMaxGroup; ++g) { - if (g < group) partials[((first + g) * gridDim.x + tile) * d + lane] = acc[g]; - } -} - constexpr int kAttendThreads = 1024; constexpr int kAttendSpan = 4096; // keys the one-block walk holds constexpr int kAttendTile = 128; diff --git a/zig/kernels/hip/decode/plan.hpp b/zig/kernels/hip/decode/plan.hpp index 7e3af96b47b..c776c0853d4 100644 --- a/zig/kernels/hip/decode/plan.hpp +++ b/zig/kernels/hip/decode/plan.hpp @@ -3,6 +3,7 @@ #include #include "decode/pages.hpp" +#include "ops/common.hpp" // A lane round's plan in device memory: no stream state is a launch argument, so one launch or graph serves any. struct PlanArgs { @@ -28,3 +29,188 @@ __device__ __forceinline__ int plan_second(int layer) { return 3 + 2 * layer; } __device__ __forceinline__ const unsigned* plan_pages(const PlanArgs& p, const unsigned long long* desc) { return reinterpret_cast(desc + p.pages); } + +// The d = 256 long-span score's pieces and the values' walk body (plan.hip's and plan_rows.hip's kernels). +namespace { + +// x from lane ^ M of its 16-lane row (M < 16): a DPP row_xmask move, all lanes active. +template +__device__ __forceinline__ float row_xor(float x) { + return __builtin_bit_cast(float, __builtin_amdgcn_mov_dpp(__builtin_bit_cast(int, x), 0x160 + M, 0xf, 0xf, false)); +} + +// wave_sum's folds, own value then partner's at xor 16, 8, 4, 2, 1, without LDS: every lane ends with the sum. +__device__ __forceinline__ float wave_sum_dpp(float x) { + const int w = __builtin_bit_cast(int, x); + x += __builtin_bit_cast(float, __builtin_amdgcn_permlanex16(w, w, 0x76543210u, 0xfedcba98u, false, false)); + x += row_xor<8>(x); + x += row_xor<4>(x); + x += row_xor<2>(x); + return x + row_xor<1>(x); +} + +// Query heads a block takes together: they share a KV head, so its keys and values are read once for all of them. +constexpr int kMaxGroup = 16; + +// Keys a wave scores on long spans (plan.hip's kScoreKeysShort on short ones): their loads go out together. +constexpr int kScoreKeys = 4; +// Steps of its waves' keys a long-span block walks at d = 256 (launches/plan.zig's score_steps). +constexpr int kScoreSteps = 8; +// load() of a 16-bit cache element as a global load: a flat load also counts on lgkmcnt, which LDS reads wait on. +__device__ __forceinline__ float cache_load(const void* p, int kind, long long i) { + const uint16_t bits = ((const __attribute__((address_space(1))) uint16_t*)p)[i]; + return kind == 1 ? __half2float(__ushort_as_half(bits)) : bf16_to_float(bits); +} + +// A wave's KEYS keys from key0 at d = 256 into k, lane l taking elements l + 32 i; keys past `visible` are not loaded. +template +__device__ __forceinline__ void score_fetch(float (&k)[KEYS][8], const void* keys, int kind, const unsigned* pages, + unsigned pool, int kv, int key0, int visible, int lane) { +#pragma unroll + for (int j = 0; j < KEYS; ++j) { + if (key0 + j >= visible) break; + const long long base = page_at(pages, pool, kv, key0 + j, 256); +#pragma unroll + for (int i = 0; i < 8; ++i) k[j][i] = cache_load(keys, kind, base + lane + i * 32); + } +} + +// Lane 0's KEYS scores of a head from `at`: one 16-byte store when `whole` (aligned rows, span a multiple of KEYS). +template +__device__ __forceinline__ void score_store(float* at, const float (&sc)[KEYS], bool whole, int key0, int span) { + if (whole && KEYS == 4) { + *reinterpret_cast(at) = make_float4(sc[0], sc[1 % KEYS], sc[2 % KEYS], sc[3 % KEYS]); + } else { + for (int j = 0; j < KEYS; ++j) if (key0 + j < span) at[j] = sc[j]; + } +} + +// plan_score_body on long spans at d = 256 (tf_plan_score256_*): no element tests, kScoreSteps steps a block. +template +__device__ void plan_score256_body(const void* __restrict__ q, float* __restrict__ scores, int span, int heads, + int kv_heads, int d, float scale, PlanArgs plan, int layer) { + constexpr int KEYS = kScoreKeys, STEPS = kScoreSteps; + extern __shared__ float qs[]; // the block's query heads, group * d + const int batch = blockIdx.z, group = heads / gridDim.y, head0 = blockIdx.y * group; + const long long q0 = (static_cast(batch) * heads + head0) * d; + for (int i = threadIdx.x; i < group * d; i += blockDim.x) qs[i] = load(q, QKIND, q0 + i); // kind 0: q fp32 + __syncthreads(); + const int visible = min(plan.pos[batch] + 1, span); + const int lane = threadIdx.x & 31; + const unsigned long long* desc = plan_desc(plan, plan.slot[batch]); + float* __restrict__ rows = scores + (static_cast(batch) * heads + head0) * span; + const void* keys = reinterpret_cast(desc[plan_first(layer)]); + const unsigned* pages = plan_pages(plan, desc); + const unsigned pool = plan.pool; + const int kv = head0 / (heads / kv_heads); + const int stride = (blockDim.x >> 5) * KEYS; // keys a step of the block + const int first = blockIdx.x * STEPS * stride + (threadIdx.x >> 5) * KEYS; + const bool whole = (span % KEYS) == 0 && (reinterpret_cast(rows) & 15) == 0; + float kreg[KEYS][8] = {}; + score_fetch(kreg, keys, KIND, pages, pool, kv, first, visible, lane); +#pragma unroll 1 + for (int step = 0; step < STEPS; ++step) { + const int key0 = first + step * stride; + if (key0 >= span) break; // the same for the whole wave + float next[KEYS][8] = {}; + score_fetch(next, keys, KIND, pages, pool, kv, step + 1 < STEPS ? key0 + stride : span, visible, lane); + if (key0 >= visible) { // the wave's keys are all past the row's: -INFINITY wherever the span has them + float none[KEYS]; + for (int j = 0; j < KEYS; ++j) none[j] = -INFINITY; + for (int g = 0; lane == 0 && g < group; ++g) { + score_store(rows + key0 + static_cast(g) * span, none, whole, key0, span); + } + } else { +#pragma unroll + for (int g = 0; g < kMaxGroup; ++g) { + if (g < group) { // the same for the whole block, so every lane reaches the folds + float qv[8]; +#pragma unroll + for (int i = 0; i < 8; ++i) qv[i] = qs[g * 256 + lane + i * 32]; + float dot[KEYS]; +#pragma unroll + for (int j = 0; j < KEYS; ++j) { + float partial = 0.f; +#pragma unroll + for (int i = 0; i < 8; ++i) partial += qv[i] * kreg[j][i]; + dot[j] = wave_sum_dpp(partial); + } + if (lane == 0) { + float sc[KEYS]; +#pragma unroll + for (int j = 0; j < KEYS; ++j) sc[j] = key0 + j < visible ? dot[j] * scale : -INFINITY; + score_store(rows + key0 + static_cast(g) * span, sc, whole, key0, span); + } + } + } + } + __builtin_memcpy(kreg, next, sizeof(kreg)); + } +} + +// apply_values over a plan's rows: a 128-key tile of the block's heads, weights worked once a block, in its order. +template +__device__ void plan_apply_body(const float* __restrict__ scores, const float* __restrict__ stats, + float* __restrict__ partials, int span, int heads, int kv_heads, int d, + PlanArgs plan, int layer) { + __shared__ float weights[kMaxGroup * 128]; + const int batch = blockIdx.z; + const int visible = min(plan.pos[batch] + 1, span); + const int tile = blockIdx.x; + const int group = heads / gridDim.y; + const int head0 = blockIdx.y * group; + const long long first = static_cast(batch) * heads + head0; + const int lane = threadIdx.x; + const int key0 = tile * 128; + if (key0 >= visible) { // a tile past the keys in use adds zero + if (lane < d) { + for (int g = 0; g < group; ++g) partials[((first + g) * gridDim.x + tile) * d + lane] = 0.f; + } + return; + } + const int stop = min(key0 + 128, visible); + for (int i = threadIdx.x; i < group * 128; i += blockDim.x) { + const long long h = first + i / 128; + const int key = key0 + i % 128; + if (key < stop) weights[i] = expf(scores[h * span + key] - stats[h * 2]) / stats[h * 2 + 1]; + } + __syncthreads(); + if (lane >= d) return; + const unsigned long long* desc = plan_desc(plan, plan.slot[batch]); + const void* values = reinterpret_cast(desc[plan_second(layer)]); + const unsigned* table = plan_pages(plan, desc); + const int kv = head0 / (heads / kv_heads); + float acc[kMaxGroup] = {}; + // a page at a time: its table entry is read once, and the keys are summed in order + for (int key = key0; key < stop;) { + const int edge = min((key / kPageTokens + 1) * kPageTokens, stop); + const long long slot0 = page_row(table[key / kPageTokens], plan.pool, kv, 0, d) + lane; + // eight values loaded ahead, then summed in key order: the loads overlap, the sums are the same + for (; key + 8 <= edge; key += 8) { + float ahead[8]; +#pragma unroll + for (int u = 0; u < 8; ++u) + ahead[u] = load(values, KIND, slot0 + static_cast((key + u) % kPageTokens) * d); +#pragma unroll + for (int u = 0; u < 8; ++u) { +#pragma unroll + for (int g = 0; g < kMaxGroup; ++g) { + if (g < group) acc[g] += weights[g * 128 + key + u - key0] * ahead[u]; + } + } + } + for (; key < edge; ++key) { + const float value = load(values, KIND, slot0 + static_cast(key % kPageTokens) * d); +#pragma unroll + for (int g = 0; g < kMaxGroup; ++g) { + if (g < group) acc[g] += weights[g * 128 + key - key0] * value; + } + } + } +#pragma unroll + for (int g = 0; g < kMaxGroup; ++g) { + if (g < group) partials[((first + g) * gridDim.x + tile) * d + lane] = acc[g]; + } +} + +} // namespace diff --git a/zig/kernels/hip/decode/plan_rows.hip b/zig/kernels/hip/decode/plan_rows.hip new file mode 100644 index 00000000000..65d9bd29c9a --- /dev/null +++ b/zig/kernels/hip/decode/plan_rows.hip @@ -0,0 +1,231 @@ +// A round's multi-row slots scored and weighed from one read of their keys and values, the others alone (d 256). + +#include "ops/common.hpp" +#include "decode/plan.hpp" + +namespace { + +// Rows of one slot a block scores (launches/plan.zig's score_rows): their queries share the block's LDS. +constexpr int kRows = 2; + +// A row's place in its slot's list when that slot lists more than one row, else -1: the row is scored alone. +__device__ __forceinline__ int plan_shared_at(const PlanArgs& plan, int batch) { + const int slot = plan.slot[batch], at = batch - plan.first[slot], count = plan.count[slot]; + return count > 1 && at >= 0 && at < count ? at : -1; +} + +// plan_score256_body (plan.hpp) for a row that scores alone: its bits and its block's LDS are tf_plan_score256_*'s. +template +__device__ void plan_lone_score256_body(const float* __restrict__ q, float* __restrict__ scores, int span, int heads, + int kv_heads, int d, float scale, PlanArgs plan, int layer) { + if (plan_shared_at(plan, blockIdx.z) >= 0) return; // tf_plan_rows_score256_* scores it + plan_score256_body(q, scores, span, heads, kv_heads, d, scale, plan, layer); +} + +// plan_score256_body on a chunk of a multi-row slot's rows: the keys read once, each row's dots in the tree's order. +template +__device__ void plan_rows_score256_body(const float* __restrict__ q, float* __restrict__ scores, int span, int heads, + int kv_heads, int d, float scale, PlanArgs plan, int layer) { + constexpr int KEYS = kScoreKeys, STEPS = kScoreSteps; + extern __shared__ float qs[]; // the chunk's rows' query heads of the block, rows * group * d + const int batch = blockIdx.z, slot = plan.slot[batch], at = plan_shared_at(plan, batch); + if (at < 0 || at % kRows != 0) return; // a row scored alone, or the chunk's first row's block scores it + const int rows = min(min(kRows, plan.count[slot] - at), static_cast(gridDim.z) - batch); + const int group = heads / gridDim.y, head0 = blockIdx.y * group; + for (int i = threadIdx.x; i < rows * group * 256; i += blockDim.x) { + const int r = i / (group * 256); + qs[i] = q[(static_cast(batch + r) * heads + head0) * 256 + (i - r * group * 256)]; + } + __syncthreads(); + int most = 0; + for (int r = 0; r < rows; ++r) most = max(most, min(plan.pos[batch + r] + 1, span)); + const int lane = threadIdx.x & 31; + const unsigned long long* desc = plan_desc(plan, slot); + const void* keys = reinterpret_cast(desc[plan_first(layer)]); + const unsigned* pages = plan_pages(plan, desc); + const unsigned pool = plan.pool; + const int kv = head0 / (heads / kv_heads); + const int stride = (blockDim.x >> 5) * KEYS; // keys a step of the block + const int first = blockIdx.x * STEPS * stride + (threadIdx.x >> 5) * KEYS; + float kreg[KEYS][8] = {}; + score_fetch(kreg, keys, KIND, pages, pool, kv, first, most, lane); +#pragma unroll 1 + for (int step = 0; step < STEPS; ++step) { + const int key0 = first + step * stride; + if (key0 >= span) break; // the same for the whole wave + float next[KEYS][8] = {}; + score_fetch(next, keys, KIND, pages, pool, kv, step + 1 < STEPS ? key0 + stride : span, most, lane); +#pragma unroll 1 + for (int r = 0; r < rows; ++r) { + const int visible = min(plan.pos[batch + r] + 1, span); + float* __restrict__ out = scores + (static_cast(batch + r) * heads + head0) * span; + const bool whole = (span % KEYS) == 0 && (reinterpret_cast(out) & 15) == 0; + if (key0 >= visible) { // the wave's keys are all past the row's: -INFINITY wherever the span has them + float none[KEYS]; + for (int j = 0; j < KEYS; ++j) none[j] = -INFINITY; + for (int g = 0; lane == 0 && g < group; ++g) { + score_store(out + key0 + static_cast(g) * span, none, whole, key0, span); + } + } else { +#pragma unroll + for (int g = 0; g < kMaxGroup; ++g) { + if (g < group) { // the same for the whole block, so every lane reaches the folds + float qv[8]; +#pragma unroll + for (int i = 0; i < 8; ++i) qv[i] = qs[(r * group + g) * 256 + lane + i * 32]; + float dot[KEYS]; +#pragma unroll + for (int j = 0; j < KEYS; ++j) { + float partial = 0.f; +#pragma unroll + for (int i = 0; i < 8; ++i) partial += qv[i] * kreg[j][i]; + dot[j] = wave_sum_dpp(partial); + } + if (lane == 0) { + float sc[KEYS]; +#pragma unroll + for (int j = 0; j < KEYS; ++j) sc[j] = key0 + j < visible ? dot[j] * scale : -INFINITY; + score_store(out + key0 + static_cast(g) * span, sc, whole, key0, span); + } + } + } + } + } + __builtin_memcpy(kreg, next, sizeof(kreg)); + } +} + +// Rows of one slot (launches/plan.zig's apply_rows) and query heads at most a values block takes: 16 KiB of weights. +constexpr int kApplyRows = 4, kApplyHeads = 8; + +// plan_apply_body (plan.hpp) for a row that applies alone: its bits and its block's LDS are tf_plan_apply_*'s. +template +__device__ void plan_lone_apply_body(const float* __restrict__ scores, const float* __restrict__ stats, + float* __restrict__ partials, int span, int heads, int kv_heads, int d, + PlanArgs plan, int layer) { + if (plan_shared_at(plan, blockIdx.z) >= 0) return; // tf_plan_rows_apply_* applies it + plan_apply_body(scores, stats, partials, span, heads, kv_heads, d, plan, layer); +} + +// N values from tile key `at` on into each row's and head's sum, a key at a time; MASK: only keys before a row's stop. +template +__device__ __forceinline__ void rows_add(float (&acc)[kApplyRows][kApplyHeads], const float* weights, + const float (&v)[N], int at, const int (&stop)[kApplyRows], int key, int rows, + int group) { +#pragma unroll + for (int r = 0; r < kApplyRows; ++r) { + if (r < rows) { +#pragma unroll + for (int u = 0; u < N; ++u) { + if (!MASK || key + u < stop[r]) { // a key past the row's own is left out, as the tree leaves it +#pragma unroll + for (int g = 0; g < kApplyHeads; ++g) { + if (g < group) acc[r][g] += weights[(r * kApplyHeads + g) * 128 + at + u] * v[u]; + } + } + } + } + } +} + +// plan_apply_body on a chunk of a multi-row slot's rows: the values read once, each row's sums in the tree's order. +template +__device__ __forceinline__ void plan_rows_apply_body(const float* __restrict__ scores, const float* __restrict__ stats, + float* __restrict__ partials, int span, int heads, int kv_heads, + int d, PlanArgs plan, int layer) { + __shared__ float weights[kApplyRows * kApplyHeads * 128]; // the chunk's rows' weights, (row, head, tile key) + const int batch = blockIdx.z, slot = plan.slot[batch], at = plan_shared_at(plan, batch); + if (at < 0 || at % kApplyRows != 0) return; // a row applied alone, or the chunk's first row's block applies it + const int rows = min(min(kApplyRows, plan.count[slot] - at), static_cast(gridDim.z) - batch); + const int tile = blockIdx.x, group = heads / gridDim.y, head0 = blockIdx.y * group; + const long long first = static_cast(batch) * heads + head0; + const int lane = threadIdx.x; + const int key0 = tile * 128; + // a row's keys of the tile end at its stop, key0 when the tile is past them: the tree adds none and writes zero + int stop[kApplyRows]; + int least = key0 + 128, most = key0; +#pragma unroll + for (int r = 0; r < kApplyRows; ++r) { + stop[r] = r < rows ? max(key0, min(key0 + 128, min(plan.pos[batch + r] + 1, span))) : key0; + if (r < rows) least = min(least, stop[r]); + most = max(most, stop[r]); + } + if (most == key0) { // a tile past every row's keys adds zero + if (lane < d) { + for (int r = 0; r < rows; ++r) { + for (int g = 0; g < group; ++g) { + partials[((first + r * heads + g) * gridDim.x + tile) * d + lane] = 0.f; + } + } + } + return; + } + for (int i = threadIdx.x; i < rows * group * 128; i += blockDim.x) { + const int r = i / (group * 128), g = i / 128 % group, key = key0 + i % 128; + const long long h = first + r * heads + g; + if (key < min(plan.pos[batch + r] + 1, span)) { + const float w = expf(scores[h * span + key] - stats[h * 2]) / stats[h * 2 + 1]; + weights[(r * kApplyHeads + g) * 128 + i % 128] = w; + } + } + __syncthreads(); + if (lane >= d) return; + const unsigned long long* desc = plan_desc(plan, slot); + const void* values = reinterpret_cast(desc[plan_second(layer)]); + const unsigned* table = plan_pages(plan, desc); + const int kv = head0 / (heads / kv_heads); + float acc[kApplyRows][kApplyHeads] = {}; + // plan_apply_body's walk, a page at a time and eight values ahead, up to the chunk's furthest key + for (int key = key0; key < most;) { + const int edge = min((key / kPageTokens + 1) * kPageTokens, most); + const long long slot0 = page_row(table[key / kPageTokens], plan.pool, kv, 0, d) + lane; + for (; key + 8 <= edge; key += 8) { + float ahead[8]; +#pragma unroll + for (int u = 0; u < 8; ++u) + ahead[u] = cache_load(values, KIND, slot0 + static_cast((key + u) % kPageTokens) * d); + if (key + 8 <= least) { // every row of the chunk adds all eight + rows_add<8, false>(acc, weights, ahead, key - key0, stop, key, rows, group); + } else { + rows_add<8, true>(acc, weights, ahead, key - key0, stop, key, rows, group); + } + } + for (; key < edge; ++key) { + const float value[1] = {cache_load(values, KIND, slot0 + static_cast(key % kPageTokens) * d)}; + rows_add<1, true>(acc, weights, value, key - key0, stop, key, rows, group); + } + } +#pragma unroll + for (int r = 0; r < kApplyRows; ++r) { + if (r < rows) { +#pragma unroll + for (int g = 0; g < kApplyHeads; ++g) { + if (g < group) partials[((first + r * heads + g) * gridDim.x + tile) * d + lane] = acc[r][g]; + } + } + } +} + +} // namespace + +extern "C" { + +// tf_plan_score256_*'s arguments and grid: _lone_ scores the rows that score alone, _rows_ the multi-row slots' chunks. +#define TF_PLAN_ROWS_SCORE256(Name, Body, KIND) __global__ void __launch_bounds__(128) Name(const float* q, \ + float* scores, int span, int heads, int kv_heads, int d, float scale, PlanArgs plan, int layer) { \ + Body(q, scores, span, heads, kv_heads, d, scale, plan, layer); } +TF_PLAN_ROWS_SCORE256(tf_plan_lone_score256_f16, plan_lone_score256_body, 1) +TF_PLAN_ROWS_SCORE256(tf_plan_lone_score256_bf16, plan_lone_score256_body, 2) +TF_PLAN_ROWS_SCORE256(tf_plan_rows_score256_f16, plan_rows_score256_body, 1) +TF_PLAN_ROWS_SCORE256(tf_plan_rows_score256_bf16, plan_rows_score256_body, 2) + +// tf_plan_apply_*'s arguments and grid (at most kApplyHeads heads a block for _rows_): _lone_ the rows applied alone. +#define TF_PLAN_ROWS_APPLY(Name, Body, KIND) __global__ void __launch_bounds__(256) Name(const float* scores, \ + const float* stats, float* partials, int span, int heads, int kv_heads, int d, PlanArgs plan, int layer) { \ + Body(scores, stats, partials, span, heads, kv_heads, d, plan, layer); } +TF_PLAN_ROWS_APPLY(tf_plan_lone_apply_f16, plan_lone_apply_body, 1) +TF_PLAN_ROWS_APPLY(tf_plan_lone_apply_bf16, plan_lone_apply_body, 2) +TF_PLAN_ROWS_APPLY(tf_plan_rows_apply_f16, plan_rows_apply_body, 1) +TF_PLAN_ROWS_APPLY(tf_plan_rows_apply_bf16, plan_rows_apply_body, 2) + +} // extern "C" diff --git a/zig/kernels/hip/inkling2/attention.hip b/zig/kernels/hip/inkling2/attention.hip new file mode 100644 index 00000000000..1967dcd136a --- /dev/null +++ b/zig/kernels/hip/inkling2/attention.hip @@ -0,0 +1,164 @@ +// Inkling 2 attention on HIP: q/k/v/rel prep, the relative-bias table, chunked attention and the ordered merge. +#include "inkling2/tile.hpp" + +using ink2::Seg; +using ink2::Tile; + +namespace ink2 { + +// L2 clip of one head vector held 4 values a lane: scale down to `thr` when longer, as Inkling2L2Clip. +__device__ __forceinline__ void clip(float* x, float thr) { + const float norm = sqrtf(waveSum(x[0] * x[0] + x[1] * x[1] + x[2] * x[2] + x[3] * x[3])); + const float f = fminf(thr / (norm + 1e-6f), 1.0f); + for (int i = 0; i < 4; ++i) x[i] *= f; +} + +} // namespace ink2 + +// Per row and head: q = clip(q * q_scale) (* tau), rel = clip(rel * rel_scale) (* tau), k = clip(k), v = rms(v). +extern "C" __global__ void __launch_bounds__(32) + tf_ink2_prep(const uint16_t* __restrict__ q_raw, const uint16_t* __restrict__ k_raw, + const uint16_t* __restrict__ v_raw, const uint16_t* __restrict__ rel_raw, + const uint16_t* __restrict__ q_scale, const uint16_t* __restrict__ rel_scale, + const int* __restrict__ rpos, const int* __restrict__ rseg, const Seg* __restrict__ segs, + uint16_t* __restrict__ q_out, uint16_t* __restrict__ rel_out, uint16_t* __restrict__ kc, + uint16_t* __restrict__ vc, int heads, int kv_heads, int ring, int global, float qk_clip, + float rel_clip, float floor_pos, float alpha, float eps) { + using namespace ink2; + const int row = blockIdx.x, y = blockIdx.y, lane = threadIdx.x; + const int pos = rpos[row]; + const float tau = global ? 1.0f + alpha * logf(fmaxf(static_cast(pos + 1) / floor_pos, 1.0f)) : 1.0f; + float x[4]; + if (y < heads) { + const size_t rh = static_cast(row) * heads + y; + for (int i = 0; i < 4; ++i) x[i] = bf(q_raw[rh * kDim + lane * 4 + i]) * bf(q_scale[y * kDim + lane * 4 + i]); + clip(x, qk_clip); + for (int i = 0; i < 4; ++i) q_out[rh * kDim + lane * 4 + i] = global ? tobf(bf(tobf(x[i])) * tau) : tobf(x[i]); + float r = lane < kRel ? bf(rel_raw[rh * kRel + lane]) * bf(rel_scale[y * kRel + lane]) : 0.0f; + const float norm = sqrtf(waveSum(r * r)); + r *= fminf(rel_clip / (norm + 1e-6f), 1.0f); + if (lane < kRel) rel_out[rh * kRel + lane] = global ? tobf(bf(tobf(r)) * tau) : tobf(r); + return; + } + const bool key = y < heads + kv_heads; + const int h = key ? y - heads : y - heads - kv_heads; + const uint16_t* src = (key ? k_raw : v_raw) + (static_cast(row) * kv_heads + h) * kDim; + for (int i = 0; i < 4; ++i) x[i] = bf(src[lane * 4 + i]); + if (key) { + clip(x, qk_clip); + } else { + const float r = rsqrtf(waveSum(x[0] * x[0] + x[1] * x[1] + x[2] * x[2] + x[3] * x[3]) / kDim + eps); + for (int i = 0; i < 4; ++i) x[i] *= r; + } + const Seg s = segs[rseg[row]]; + uint16_t* dst = (key ? kc : vc) + s.off + (static_cast(h) * ring + pos % ring) * kDim; + for (int i = 0; i < 4; ++i) dst[lane * 4 + i] = tobf(x[i]); +} + +// tab[row, head, d] = bf16(rel[row, head, :] . proj[:, d]) for d < 1024, fp32 sums in tap order (rel_logits_proj). +extern "C" __global__ void __launch_bounds__(256) + tf_ink2_rel_table(const uint16_t* __restrict__ rel, const uint16_t* __restrict__ proj, + uint16_t* __restrict__ tab) { + using namespace ink2; + const size_t rh = blockIdx.x; + float r[kRel]; + for (int j = 0; j < kRel; ++j) r[j] = bf(rel[rh * kRel + j]); + for (int d = threadIdx.x; d < kExtent; d += blockDim.x) { + float acc = 0.0f; + for (int j = 0; j < kRel; ++j) acc += r[j] * bf(proj[j * kExtent + d]); + tab[rh * kExtent + d] = tobf(acc); + } +} + +// Sliding layers (a chunk a block) and split global calls (a sub-chunk a block, `chunks` partials a row and head). +extern "C" __global__ void __launch_bounds__(ink2::kWaves * 32) + tf_ink2_attn(const uint16_t* __restrict__ q, const uint16_t* __restrict__ kc, const uint16_t* __restrict__ vc, + const uint16_t* __restrict__ tab, const Seg* __restrict__ segs, const Tile* __restrict__ tiles, + float* __restrict__ part_o, float2* __restrict__ part_ml, int heads, int kv_heads, int ring, + int window, int chunk, int c0, int chunks, float scale, int split) { + using namespace ink2; + __shared__ uint32_t ks[kKeys * kKRow]; + __shared__ uint4 vs[kKeys * kVRow / 4]; + __shared__ float qs[kWaves * kDim]; + const Tile t = tiles[blockIdx.x]; + attnTile({q, kc, vc, tab, part_o, part_ml}, segs[t.seg], t.m0, blockIdx.y, blockIdx.z, + {heads, kv_heads, ring, window, chunk, c0, chunks, split}, scale, ks, + reinterpret_cast(vs), qs); +} + +// Global layers a chunk a block, its sub-chunks folded in order (several streams' rows: no partial a sub-chunk). +extern "C" __global__ void __launch_bounds__(ink2::kWaves * 32) + tf_ink2_attn_fold(const uint16_t* __restrict__ q, const uint16_t* __restrict__ kc, + const uint16_t* __restrict__ vc, const uint16_t* __restrict__ tab, const Seg* __restrict__ segs, + const Tile* __restrict__ tiles, float* __restrict__ part_o, float2* __restrict__ part_ml, + int heads, int kv_heads, int ring, int chunk, int c0, int chunks, float scale) { + using namespace ink2; + __shared__ uint32_t ks[kKeys * kKRow]; + __shared__ uint4 vs[kKeys * kVRow / 4]; + __shared__ float qs[kWaves * kDim]; + const Tile t = tiles[blockIdx.x]; + attnTile({q, kc, vc, tab, part_o, part_ml}, segs[t.seg], t.m0, blockIdx.y, blockIdx.z, + {heads, kv_heads, ring, 0, chunk, c0, chunks, 0}, scale, ks, + reinterpret_cast(vs), qs); +} + +// One stream's prompt rows on a global layer: 8 pairs a block share each K/V tile, the next one loading meanwhile. +extern "C" __global__ void __launch_bounds__(ink2::kPromptWaves * 32) + tf_ink2_attn_prompt(const uint16_t* __restrict__ q, const uint16_t* __restrict__ kc, + const uint16_t* __restrict__ vc, const uint16_t* __restrict__ tab, + const Seg* __restrict__ segs, float* __restrict__ part_o, float2* __restrict__ part_ml, + int heads, int kv_heads, int ring, int chunk, int c0, int chunks, float scale) { + using namespace ink2; + __shared__ uint32_t ks[kKeys * kKRow]; + __shared__ uint4 vs[kKeys * kVRow / 4]; + __shared__ float qs[kPromptWaves * kDim]; + const Seg s = segs[0]; + const int m0 = static_cast(blockIdx.x) * kPromptWaves; + if (m0 >= s.n * (heads / kv_heads)) return; + attnTile({q, kc, vc, tab, part_o, part_ml}, s, m0, blockIdx.y, blockIdx.z, + {heads, kv_heads, ring, 0, chunk, c0, chunks, 0}, scale, ks, + reinterpret_cast(vs), qs); +} + +// Per (row, head): chunks folded in order (subs > 1: sub-chunks first), then the RAW sink logit and RAW gate's sigmoid. +extern "C" __global__ void __launch_bounds__(ink2::kDim) + tf_ink2_merge(const float* __restrict__ part_o, const float2* __restrict__ part_ml, + const uint16_t* __restrict__ sink, const uint16_t* __restrict__ gate, const int* __restrict__ rpos, + uint16_t* __restrict__ out, int heads, int window, int chunk, int c0, int chunks, int subs) { + using namespace ink2; + const size_t rh = blockIdx.x; + const int row = static_cast(rh / heads), d = threadIdx.x; + const int pos = rpos[row]; + const int lo = window > 0 ? max(0, pos - window + 1) : 0; + float mm = -INFINITY, ll = 0.0f, o = 0.0f; + for (int c = lo / chunk; c <= pos / chunk; ++c) { + float2 ml; + float po; + if (subs > 1) { + float M = -INFINITY, L = 0.0f, O = 0.0f; + const int last = min(subs - 1, (pos - c * chunk) / kSub); + for (int u = 0; u <= last; ++u) { + const size_t at = rh * chunks + (c - c0) * subs + u; + const float2 sm = part_ml[at]; + float a, b; + fold(M, L, sm.x, sm.y, a, b); + O = O * a + part_o[at * kDim + d] * b; + } + ml = make_float2(M, L); + po = O; + } else { + const size_t at = rh * chunks + (c - (window > 0 ? lo / chunk : c0)); + ml = part_ml[at]; + po = part_o[at * kDim + d]; + } + float a, b; + fold(mm, ll, ml.x, ml.y, a, b); + o = o * a + po * b; + } + const float sk = bf(sink[rh]) * kLog2e; + const float mf = fmaxf(mm, sk); + const float a = exp2f(mm - mf); + const float y = o * a / (ll * a + exp2f(sk - mf)); + const float gv = bf(gate[rh * kDim + d]); + out[rh * kDim + d] = tobf(y * (1.0f / (1.0f + expf(-gv)))); +} diff --git a/zig/kernels/hip/inkling2/tile.hpp b/zig/kernels/hip/inkling2/tile.hpp new file mode 100644 index 00000000000..569a876f7c1 --- /dev/null +++ b/zig/kernels/hip/inkling2/tile.hpp @@ -0,0 +1,234 @@ +#pragma once + +// Inkling 2's attention tile on HIP: a wave a (row, head) pair, shared K/V tiles, the same steps on every path. + +#include +#include +#include + +namespace ink2 { + +constexpr int kDim = 128; +constexpr int kRel = 16; +constexpr int kExtent = 1024; +constexpr int kKeys = 64; +constexpr int kSub = 1024; +constexpr int kWaves = 4; // pairs a block on the decode paths (tiles of 4 pairs) +constexpr int kPromptWaves = 8; // pairs a block on one stream's prompt rows +constexpr int kKRow = kDim / 2 + 1; // dwords a K row in LDS: the pad dword puts lane i's row in bank i +constexpr int kVRow = kDim / 2; // dwords a V row: a wave reads one row's consecutive dwords +constexpr float kLog2e = 1.4426950408889634f; + +// One stream's rows in a call: rows row0..row0+n-1 sit at positions p0..p0+n-1; `off` is its cache's element offset. +struct Seg { + int row0; + int n; + int p0; + int pad; + long long off; +}; + +// A block's pairs: segment `seg`, pairs m0.. of it (pair m is row m / group, head m % group of the key head). +struct Tile { + int seg; + int m0; +}; + +__device__ __forceinline__ float bf(uint16_t u) { return __uint_as_float(static_cast(u) << 16); } +__device__ __forceinline__ float lo16(uint32_t w) { return __uint_as_float(w << 16); } +__device__ __forceinline__ float hi16(uint32_t w) { return __uint_as_float(w & 0xffff0000u); } + +// Round to nearest even; NaN to 0x7fc0. +__device__ __forceinline__ uint16_t tobf(float f) { + if (f != f) return 0x7fc0; + const uint32_t u = __float_as_uint(f); + return static_cast((u + 0x7fffu + ((u >> 16) & 1u)) >> 16); +} + +// An xor butterfly over the wave: every lane ends with the same bits (each add is commutative). +__device__ __forceinline__ float waveSum(float v) { + for (int o = 16; o > 0; o >>= 1) v += __shfl_xor(v, o); + return v; +} + +__device__ __forceinline__ float waveMax(float v) { + for (int o = 16; o > 0; o >>= 1) v = fmaxf(v, __shfl_xor(v, o)); + return v; +} + +// A part (m, l) into a running (mm, ll); a, b scale old and new sums. Each product and sum rounds once. +__device__ __forceinline__ void fold(float& mm, float& ll, float m, float l, float& a, float& b) { + const float mn = fmaxf(mm, m); + a = exp2f(mm - mn); + b = exp2f(m - mn); + ll = ll * a + l * b; + mm = mn; +} + +// The call's buffers and geometry, as the launch passes them. +struct Ptrs { + const uint16_t* q; + const uint16_t* kc; + const uint16_t* vc; + const uint16_t* tab; + float* part_o; + float2* part_ml; +}; + +struct Geo { + int heads, kv_heads, ring, window, chunk, c0, chunks, split; +}; + +// A K/V tile's 16-byte pieces a thread holds: keys kt..kt+63 of a key head, zeros outside [k_lo, k_hi]. +template +struct Stage { + static constexpr int kPer = kKeys * (kDim / 8) / THREADS; + uint4 k[kPer], v[kPer]; + + __device__ __forceinline__ void load(const uint16_t* kc, const uint16_t* vc, size_t head_base, int ring, int kt, + int k_lo, int k_hi) { + const size_t slot0 = static_cast(kt % ring); + for (int i = 0; i < kPer; ++i) { + const int e = static_cast(threadIdx.x) + i * THREADS; + const int key = e >> 4, col = (e & 15) * 8; + const int kp = kt + key; + k[i] = v[i] = make_uint4(0u, 0u, 0u, 0u); + if (kp >= k_lo && kp <= k_hi) { + const size_t at = head_base + (slot0 + key) * kDim + col; + k[i] = *reinterpret_cast(kc + at); + v[i] = *reinterpret_cast(vc + at); + } + } + } + + __device__ __forceinline__ void store(uint32_t* ks, uint32_t* vs) const { + for (int i = 0; i < kPer; ++i) { + const int e = static_cast(threadIdx.x) + i * THREADS; + const int key = e >> 4, c4 = (e & 15) * 4; + uint32_t* kr = ks + key * kKRow + c4; + kr[0] = k[i].x; + kr[1] = k[i].y; + kr[2] = k[i].z; + kr[3] = k[i].w; + *reinterpret_cast(vs + key * kVRow + c4) = v[i]; + } + } +}; + +// A key's score in log2 units: (q.k / sqrt(128) + bias at its distance) log2e when live, else -inf. +__device__ __forceinline__ float score(float dot, int kp, int live_lo, int live_hi, int pos, const uint16_t* trow, + float scale) { + if (kp < live_lo || kp > live_hi) return -INFINITY; + const int d = pos - kp; + const float bias = d < kExtent ? bf(trow[d]) : 0.0f; + return (dot * scale + bias) * kLog2e; +} + +// One wave's pair over the tile in LDS: its live keys live_lo..live_hi, an online max, P rounded to bf16 for l and P.V. +__device__ __forceinline__ void tileStep(const uint32_t* ks, const uint32_t* vs, const float* qw, int kt, int live_lo, + int live_hi, int pos, const uint16_t* trow, float scale, float& m, float& l, + float* acc) { + const int lane = static_cast(threadIdx.x) & 31; + const uint32_t* ra = ks + lane * kKRow; + const uint32_t* rb = ks + (lane + 32) * kKRow; + const float2* q2 = reinterpret_cast(qw); + float da = 0.0f, db = 0.0f; + for (int j = 0; j < kDim / 2; ++j) { + const float2 x = q2[j]; + const uint32_t a = ra[j], b = rb[j]; + da += x.x * lo16(a); + da += x.y * hi16(a); + db += x.x * lo16(b); + db += x.y * hi16(b); + } + const float sa = score(da, kt + lane, live_lo, live_hi, pos, trow, scale); + const float sb = score(db, kt + lane + 32, live_lo, live_hi, pos, trow, scale); + const float mn = fmaxf(m, waveMax(fmaxf(sa, sb))); + const float mu = mn == -INFINITY ? 0.0f : mn; + const float alpha = exp2f(m - mu); + m = mn; + const float pa = bf(tobf(exp2f(sa - mu))), pb = bf(tobf(exp2f(sb - mu))); + l = l * alpha + waveSum(pa + pb); + for (int i = 0; i < 4; ++i) acc[i] *= alpha; + const uint32_t* vcol = vs + 2 * lane; + for (int j = live_lo - kt; j <= live_hi - kt; ++j) { + const int from = __float_as_int(j < 32 ? pa : pb); + const float p = __int_as_float(__builtin_amdgcn_readlane(from, j & 31)); + const uint32_t v0 = vcol[j * kVRow], v1 = vcol[j * kVRow + 1]; + acc[0] += p * lo16(v0); + acc[1] += p * hi16(v0); + acc[2] += p * lo16(v1); + acc[3] += p * hi16(v1); + } +} + +// WAVES pairs m0.. of segment s, key head kvh, block z (FOLD: a global chunk); PIPE loads the next tile meanwhile. +template +__device__ __forceinline__ void attnTile(Ptrs p, const Seg s, int m0, int kvh, int z, Geo g, float scale, + uint32_t* ks, uint32_t* vs, float* qs) { + const int group = g.heads / g.kv_heads; + const int total = s.n * group; + const int tile_hi = s.p0 + min(m0 + WAVES - 1, total - 1) / group; + const int tile_lo = g.window > 0 ? max(0, s.p0 + m0 / group - g.window + 1) : 0; + const int subs = g.chunk / kSub; + int c, sub = 0; + if (g.split) { + c = g.c0 + z / subs; + sub = z % subs; + } else { + c = (g.window > 0 ? tile_lo / g.chunk : g.c0) + z; + } + const int b_lo = c * g.chunk + sub * kSub, b_hi = b_lo + (g.split ? kSub : g.chunk) - 1; + if (b_lo > tile_hi || b_hi < tile_lo) return; + // a wave's pair: uniform values, so the P.V loop's bounds and readlane's lane sit in scalar registers + const int w = __builtin_amdgcn_readfirstlane(static_cast(threadIdx.x) >> 5); + const int lane = static_cast(threadIdx.x) & 31; + const int mr = m0 + w; + const bool ok = mr < total; + const int lr = ok ? mr / group : 0; + const int pos = ok ? s.p0 + lr : -1; + const int lo = g.window > 0 ? max(0, pos - g.window + 1) : 0; + const size_t prow = static_cast(s.row0 + lr) * g.heads + kvh * group + (ok ? mr % group : 0); + float* qw = qs + w * kDim; + for (int i = 0; i < 4; ++i) qw[lane * 4 + i] = ok ? bf(p.q[prow * kDim + lane * 4 + i]) : 0.0f; + const uint16_t* trow = p.tab + prow * kExtent; + const size_t head_base = s.off + static_cast(kvh) * g.ring * kDim; + const int part = FOLD ? kSub : b_hi - b_lo + 1; + const int k_lo = max(b_lo, tile_lo), k_hi = min(b_hi, tile_hi); + const int first = k_lo & ~(kKeys - 1); + const int n_tiles = (k_hi - first) / kKeys + 1; + float m = -INFINITY, l = 0.0f, acc[4] = {0.0f, 0.0f, 0.0f, 0.0f}; + float M = -INFINITY, L = 0.0f, O[4] = {0.0f, 0.0f, 0.0f, 0.0f}; + Stage st; + if (PIPE) st.load(p.kc, p.vc, head_base, g.ring, first, k_lo, k_hi); + for (int it = 0; it < n_tiles; ++it) { + const int kt = first + it * kKeys; + const int s_lo = b_lo + (kt - b_lo) / part * part, s_hi = s_lo + part - 1; + if (FOLD && kt == s_lo) { + m = -INFINITY; + l = 0.0f; + for (int i = 0; i < 4; ++i) acc[i] = 0.0f; + } + __syncthreads(); // every wave is past the previous tile + if (!PIPE) st.load(p.kc, p.vc, head_base, g.ring, kt, k_lo, k_hi); + st.store(ks, vs); + __syncthreads(); + if (PIPE && it + 1 < n_tiles) st.load(p.kc, p.vc, head_base, g.ring, kt + kKeys, k_lo, k_hi); + const int live_lo = max(max(lo, s_lo), kt), live_hi = min(min(pos, s_hi), kt + kKeys - 1); + if (ok) tileStep(ks, vs, qw, kt, live_lo, live_hi, pos, trow, scale, m, l, acc); + if (FOLD && ok && s_lo <= pos && (kt + kKeys > s_hi || it == n_tiles - 1)) { + float a, b; + fold(M, L, m, l, a, b); + for (int i = 0; i < 4; ++i) O[i] = O[i] * a + acc[i] * b; + } + } + // a chunk outside the row's keys stores nothing: its slot is a neighbour (row, head)'s (hip_attention.partialSlot) + if (!ok || c < lo / g.chunk || c > pos / g.chunk || b_lo > pos) return; + const size_t at = g.split ? prow * g.chunks + (c - g.c0) * subs + sub + : prow * g.chunks + (c - (g.window > 0 ? lo / g.chunk : g.c0)); + if (lane == 0) p.part_ml[at] = FOLD ? make_float2(M, L) : make_float2(m, l); + const float4 o4 = FOLD ? make_float4(O[0], O[1], O[2], O[3]) : make_float4(acc[0], acc[1], acc[2], acc[3]); + *reinterpret_cast(p.part_o + at * kDim + lane * 4) = o4; +} + +} // namespace ink2 diff --git a/zig/kernels/metal/core/copy_u32.metal b/zig/kernels/metal/core/copy_u32.metal new file mode 100644 index 00000000000..5aa27b1bf15 --- /dev/null +++ b/zig/kernels/metal/core/copy_u32.metal @@ -0,0 +1,11 @@ +// u32 copies, dst[i] = src[i]: TF_COPY_U32 for a grid of exactly n threads, TF_COPY_U32_N for any grid over n. +#define TF_COPY_U32(NAME) \ + kernel void NAME(const device uint* src [[buffer(0)]], device uint* dst [[buffer(1)]], \ + uint i [[thread_position_in_grid]]) { \ + dst[i] = src[i]; \ + } +#define TF_COPY_U32_N(NAME) \ + kernel void NAME(const device uint* src [[buffer(0)]], device uint* dst [[buffer(1)]], \ + constant uint& n [[buffer(2)]], uint i [[thread_position_in_grid]]) { \ + if (i < n) dst[i] = src[i]; \ + } diff --git a/zig/kernels/metal/core/lane_order.metal b/zig/kernels/metal/core/lane_order.metal index 5e9e6760998..d74d0fb4b75 100644 --- a/zig/kernels/metal/core/lane_order.metal +++ b/zig/kernels/metal/core/lane_order.metal @@ -13,3 +13,71 @@ kernel void tf_lane_order(device uint* W [[buffer(0)]], uint t [[thread_index_in // codes a0 a2 c0 c2 a1 a3 c1 c3, low nibble first b[t] = (a & 0xFu) | ((a >> 4) & 0xF0u) | ((c & 0xFu) << 8) | ((c << 4) & 0xF000u) | (((a >> 4) & 0xFu) << 16) | (((a >> 8) & 0xF0u) << 16) | (((c >> 4) & 0xFu) << 24) | (((c >> 8) & 0xF0u) << 24); } + +inline uint tf_extract_tile_code(const threadgroup uint* tiled, uint row_words, uint col, uint k, uint bits) { + const uint b = k * bits, idx = col * row_words + (b >> 5), sh = b & 31; + uint v = tiled[idx] >> sh; + if (sh + bits > 32) v |= tiled[idx + 1] << (32 - sh); + return v & ((1u << bits) - 1u); +} + +inline uint tf_reg_coord_k(uint lane, uint w, uint j) { + const uint k0 = 4 * (lane & 1) + 8 * ((lane >> 3) & 1) + 32 * (w & 1); + return k0 + (j & 1) * 2 + ((j >> 1) & 1) * 16 + (j >> 2); +} + +inline uint tf_reg_coord_col(uint lane, uint w) { + return ((lane >> 1) & 3) + 4 * ((lane >> 4) & 1) + 8 * (w >> 1); +} + +// Split-plane (4+1) in-place rewrite for 5-bit g64: words 0..255 low nibbles in regBlock order, 256..319 high bits. +kernel void tf_lane_order_q5(device uint* W [[buffer(0)]], uint t [[thread_index_in_threadgroup]], uint block [[threadgroup_position_in_grid]]) { + threadgroup uint tiled[320]; + device uint* b = W + (size_t)block * 320; + tiled[t] = b[t]; + if (t < 64) tiled[256 + t] = b[256 + t]; + threadgroup_barrier(mem_flags::mem_threadgroup); + const uint lane = (t >> 2) & 31, w = 4 * (t >> 7) + (t & 3), col = tf_reg_coord_col(lane, w); + uint lo4 = 0u; + for (uint j = 0; j < 8; j++) lo4 |= (tf_extract_tile_code(tiled, 10, col, tf_reg_coord_k(lane, w, j), 5) & 0xFu) << (4 * j); + b[t] = lo4; + if (t < 64) { + const uint hl = t >> 1, hp = t & 1; + uint hi_w = 0u; + for (uint s = 0; s < 4; s++) { + const uint hw = 4 * hp + s, hcol = tf_reg_coord_col(hl, hw); + for (uint j = 0; j < 4; j++) { + const uint b0 = (tf_extract_tile_code(tiled, 10, hcol, tf_reg_coord_k(hl, hw, j), 5) >> 4) & 1u; + const uint b1 = (tf_extract_tile_code(tiled, 10, hcol, tf_reg_coord_k(hl, hw, j + 4), 5) >> 4) & 1u; + hi_w |= (b0 << (4 * s + j)) | (b1 << (16 + 4 * s + j)); + } + } + b[256 + t] = hi_w; + } +} + +// Split-plane (4+2) rewrite for 6-bit g64: words 0..255 low nibbles in regBlock order, 256..383 high 2-bit pairs. +kernel void tf_lane_order_q6(device uint* W [[buffer(0)]], uint t [[thread_index_in_threadgroup]], uint block [[threadgroup_position_in_grid]]) { + threadgroup uint tiled[384]; + device uint* b = W + (size_t)block * 384; + tiled[t] = b[t]; + if (t < 128) tiled[256 + t] = b[256 + t]; + threadgroup_barrier(mem_flags::mem_threadgroup); + const uint lane = (t >> 2) & 31, w = 4 * (t >> 7) + (t & 3), col = tf_reg_coord_col(lane, w); + uint lo4 = 0u; + for (uint j = 0; j < 8; j++) lo4 |= (tf_extract_tile_code(tiled, 12, col, tf_reg_coord_k(lane, w, j), 6) & 0xFu) << (4 * j); + b[t] = lo4; + if (t < 128) { + const uint hl = t >> 2, p = t & 3, hcol = tf_reg_coord_col(hl, 2 * p); + uint hi_w = 0u; + for (uint s = 0; s < 2; s++) { + const uint hw = 2 * p + s; + for (uint j = 0; j < 4; j++) { + const uint c0 = (tf_extract_tile_code(tiled, 12, hcol, tf_reg_coord_k(hl, hw, j), 6) >> 4) & 3u; + const uint c1 = (tf_extract_tile_code(tiled, 12, hcol, tf_reg_coord_k(hl, hw, j + 4), 6) >> 4) & 3u; + hi_w |= (c0 << (8 * s + 2 * j)) | (c1 << (16 + 8 * s + 2 * j)); + } + } + b[256 + t] = hi_w; + } +} diff --git a/zig/kernels/metal/core/lane_projection.metal b/zig/kernels/metal/core/lane_projection.metal index f8d2d071a83..c39e166b053 100644 --- a/zig/kernels/metal/core/lane_projection.metal +++ b/zig/kernels/metal/core/lane_projection.metal @@ -322,29 +322,46 @@ uint group_id [[simdgroup_index_in_threadgroup]],uint lane [[thread_index_in_sim } #endif -#if (TF_BITS == 4 || TF_BITS == 8) && defined(TF_REG) -// A lane's codes for one group (4-bit: two quads; 8-bit: the same codes a byte each), metadata quads and row sums. +#if (TF_BITS == 4 || TF_BITS == 5 || TF_BITS == 6 || TF_BITS == 8) && defined(TF_REG) +// A lane's codes (4/8-bit: two/four quads; 5/6-bit split-plane: low nibbles + hi plane), metadata quads and sums. #if TF_BITS == 8 struct tf_reg_load { uint4 w[4]; uint4 q0, q1; float x0, x1; }; -constant constexpr int TF_REG_QUADS = 4; -#define TF_REG_CODES(wl, g) {wl[(size_t)(g) * 128], wl[(size_t)(g) * 128 + 32], wl[(size_t)(g) * 128 + 64], wl[(size_t)(g) * 128 + 96]} +constant constexpr int TF_REG_STRIDE = 128; +#define TF_REG_CODES(wg, lane) {wg[lane], wg[32 + lane], wg[64 + lane], wg[96 + lane]} #else -struct tf_reg_load { uint4 w0, w1, q0, q1; float x0, x1; }; -constant constexpr int TF_REG_QUADS = 2; -#define TF_REG_CODES(wl, g) wl[(size_t)(g) * 64], wl[(size_t)(g) * 64 + 32] +constant constexpr int TF_REG_STRIDE = TF_BITS == 6 ? 96 : TF_BITS == 5 ? 80 : 64; +struct tf_reg_load { + uint4 w0, w1; +#if TF_BITS == 5 + uint2 h; +#elif TF_BITS == 6 + uint4 h; +#endif + uint4 q0, q1; + float x0, x1; +}; +#if TF_BITS == 5 +#define TF_REG_CODES(wg, lane) wg[lane], wg[32 + lane], ((const device uint2*)(wg + 64))[lane] +#elif TF_BITS == 6 +#define TF_REG_CODES(wg, lane) wg[lane], wg[32 + lane], wg[64 + lane] +#else +#define TF_REG_CODES(wg, lane) wg[lane], wg[32 + lane] +#endif #endif -inline tf_reg_load tf_reg_fetch(const device uint4* wl, const device uint4* sbv, const device float* XS, int g, int n, int m, int stride) { - return {TF_REG_CODES(wl, g), sbv[((size_t)g * TF_N + n) / 4], sbv[((size_t)g * TF_N + n + 16) / 4], XS[g * stride + m], XS[g * stride + m + 8]}; +inline tf_reg_load tf_reg_fetch(const device uint4* wt, const device uint4* sbv, const device float* XS, int g, int n, int m, int stride, int lane) { + const device uint4* wg = wt + (size_t)g * TF_REG_STRIDE; + return {TF_REG_CODES(wg, lane), sbv[((size_t)g * TF_N + n) / 4], sbv[((size_t)g * TF_N + n + 16) / 4], XS[g * stride + m], XS[g * stride + m + 8]}; } #if TF_INLINE_SUMS -inline tf_reg_load tf_reg_fetch_tg(const device uint4* wl, const device uint4* sbv, const threadgroup float* XT, int g, int first, int n, int m) { - return {TF_REG_CODES(wl, g), sbv[((size_t)g * TF_N + n) / 4], sbv[((size_t)g * TF_N + n + 16) / 4], XT[(g - first) * 16 + m], XT[(g - first) * 16 + m + 8]}; +inline tf_reg_load tf_reg_fetch_tg(const device uint4* wt, const device uint4* sbv, const threadgroup float* XT, int g, int first, int n, int m, int lane) { + const device uint4* wg = wt + (size_t)g * TF_REG_STRIDE; + return {TF_REG_CODES(wg, lane), sbv[((size_t)g * TF_N + n) / 4], sbv[((size_t)g * TF_N + n + 16) / 4], XT[(g - first) * 16 + m], XT[(g - first) * 16 + m + 8]}; } #endif -// tf_lane's arithmetic with codes unpacked straight into tensor-op registers: every word equals tf_lane_pair's. +// tf_lane's arithmetic with codes unpacked straight into tensor-op registers (4, 4+1, 4+2, and 8-bit). [[kernel]] void tf_lane_reg(const device bfloat* X [[buffer(0)]], const device uint4* W [[buffer(1)]], const device bfloat* SB [[buffer(2)]], const device int* mdims [[buffer(3)]], device TF_OUT* Y [[buffer(4)]], const device float* XS [[buffer(5)]], uint sgi [[simdgroup_index_in_threadgroup]], uint lanei [[thread_index_in_simdgroup]], uint2 tg [[threadgroup_position_in_grid]]) { @@ -363,7 +380,7 @@ inline tf_reg_load tf_reg_fetch_tg(const device uint4* wl, const device uint4* s auto cb = op.template get_right_input_cooperative_tensor(); auto P = op.template get_destination_cooperative_tensor, metal::remove_addrspace_t, float>(); thread half2* b2 = (thread half2*)&cb[0]; - const device uint4* wl = W + (size_t)tile * KG * 32 * TF_REG_QUADS + lane; + const device uint4* wt = W + (size_t)tile * KG * TF_REG_STRIDE; const device uint4* sbv = (const device uint4*)SB; const half2 bias = half2(1024.0h); float C[16]; @@ -377,9 +394,9 @@ inline tf_reg_load tf_reg_fetch_tg(const device uint4* wl, const device uint4* s simdgroup_barrier(mem_flags::mem_threadgroup); for (int p = lane; p < (last - first) * M; p += 32) XT[(p / M) * 16 + p % M] = tf_lane_xsum(X, p % M, first + p / M, M); simdgroup_barrier(mem_flags::mem_threadgroup); -#define TF_REG_FETCH(g) tf_reg_fetch_tg(wl, sbv, XT, g, first, n0 + nb, mb) +#define TF_REG_FETCH(g) tf_reg_fetch_tg(wt, sbv, XT, g, first, n0 + nb, mb, lane) #else -#define TF_REG_FETCH(g) tf_reg_fetch(wl, sbv, XS, g, n0 + nb, mb, stride) +#define TF_REG_FETCH(g) tf_reg_fetch(wt, sbv, XS, g, n0 + nb, mb, stride, lane) #endif if (first < last) next = TF_REG_FETCH(first); for (int g = first; g < last; g++) { @@ -396,10 +413,24 @@ inline tf_reg_load tf_reg_fetch_tg(const device uint4* wl, const device uint4* s #else // 1024 + code as fp16 bits, codes (0,4) (1,5) (2,6) (3,7) of a word; subtracting 1024 is exact const uint word = w < 4 ? cur.w0[w] : cur.w1[w - 4], lo = word & 0x0F0F0F0Fu, hi = (word >> 4) & 0x0F0F0F0Fu; +#if TF_BITS == 5 + const uint hh = cur.h[w >> 2] >> (4 * (w & 3)); + b2[e] = as_type((lo & 0x00FF00FFu) | ((hh & 0x00010001u) << 4) | 0x64006400u) - bias; + b2[e + 1] = as_type((hi & 0x00FF00FFu) | ((hh & 0x00020002u) << 3) | 0x64006400u) - bias; + b2[e + 8] = as_type(((lo >> 8) & 0x00FF00FFu) | ((hh & 0x00040004u) << 2) | 0x64006400u) - bias; + b2[e + 9] = as_type(((hi >> 8) & 0x00FF00FFu) | ((hh & 0x00080008u) << 1) | 0x64006400u) - bias; +#elif TF_BITS == 6 + const uint hh = cur.h[w >> 1] >> (8 * (w & 1)); + b2[e] = as_type((lo & 0x00FF00FFu) | ((hh & 0x00030003u) << 4) | 0x64006400u) - bias; + b2[e + 1] = as_type((hi & 0x00FF00FFu) | ((hh & 0x000C000Cu) << 2) | 0x64006400u) - bias; + b2[e + 8] = as_type(((lo >> 8) & 0x00FF00FFu) | (hh & 0x00300030u) | 0x64006400u) - bias; + b2[e + 9] = as_type(((hi >> 8) & 0x00FF00FFu) | ((hh & 0x00C000C0u) >> 2) | 0x64006400u) - bias; +#else b2[e] = as_type((lo & 0x00FF00FFu) | 0x64006400u) - bias; b2[e + 1] = as_type((hi & 0x00FF00FFu) | 0x64006400u) - bias; b2[e + 8] = as_type(((lo >> 8) & 0x00FF00FFu) | 0x64006400u) - bias; b2[e + 9] = as_type(((hi >> 8) & 0x00FF00FFu) | 0x64006400u) - bias; +#endif #endif } if (g + 1 < last) next = TF_REG_FETCH(g + 1); diff --git a/zig/kernels/metal/core/prompt_pick.metal b/zig/kernels/metal/core/prompt_pick.metal new file mode 100644 index 00000000000..67436d3d201 --- /dev/null +++ b/zig/kernels/metal/core/prompt_pick.metal @@ -0,0 +1,8 @@ +// Kernel NAME: after a prompt's non-finite scan, the finite (grids 0-2) or masked (3-5) grids; clears the flag. +#define TF_PROMPT_PICK(NAME) \ + [[kernel]] void NAME(device atomic_uint* flag [[buffer(0)]], constant uint* grid [[buffer(1)]], \ + device uint* grids [[buffer(2)]]) { \ + const bool masked = atomic_load_explicit(flag, memory_order_relaxed) != 0; \ + atomic_store_explicit(flag, 0u, memory_order_relaxed); \ + for (int i = 0; i < 3; i++) { grids[i] = masked ? 0u : grid[i]; grids[3 + i] = masked ? grid[i] : 0u; } \ + } diff --git a/zig/kernels/metal/drama3/codec.metal b/zig/kernels/metal/drama3/codec.metal index 97ab5237049..cf2596da239 100644 --- a/zig/kernels/metal/drama3/codec.metal +++ b/zig/kernels/metal/drama3/codec.metal @@ -1,5 +1,6 @@ // Drama 3's codec (Fish S2 modded DAC) in fp32: the GEMM and the glue between them, time-major [rows, channels]. #include "d3_common.h" +#include "../core/copy_u32.metal" struct GemmArgs { uint rows, o, cin, ldx, ldy; @@ -330,7 +331,4 @@ inline float erfc_pos(float z) { } // Move n 4-byte words (carried rows of a staging buffer, through a scratch copy when they overlap). -[[max_total_threads_per_threadgroup(256)]] kernel void c_copy(device const uint* src [[buffer(0)]], device uint* dst [[buffer(1)]], constant uint& n [[buffer(2)]], - uint i [[thread_position_in_grid]]) { - if (i < n) dst[i] = src[i]; -} +[[max_total_threads_per_threadgroup(256)]] TF_COPY_U32_N(c_copy) diff --git a/zig/kernels/metal/gemma4/lane_projection.metal b/zig/kernels/metal/gemma4/lane_projection.metal index 301d604c57b..ea77391624e 100644 --- a/zig/kernels/metal/gemma4/lane_projection.metal +++ b/zig/kernels/metal/gemma4/lane_projection.metal @@ -273,11 +273,31 @@ uint group_id [[simdgroup_index_in_threadgroup]],uint lane [[thread_index_in_sim } #endif -#if TF_BITS == 4 && defined(TF_REG) -struct tf_reg_load { uint4 w0, w1, q0, q1; float x0, x1; }; // a lane's codes, its two metadata quads and its two row sums for one group +#if (TF_BITS == 4 || TF_BITS == 5 || TF_BITS == 6) && defined(TF_REG) +constant constexpr int TF_REG_STRIDE = TF_BITS == 6 ? 96 : TF_BITS == 5 ? 80 : 64; -inline tf_reg_load tf_reg_fetch_w(const device uint4* wl, const device uint4* sbv, int g, int n) { - return {wl[(size_t)g * 64], wl[(size_t)g * 64 + 32], sbv[((size_t)g * TF_N + n) / 4], sbv[((size_t)g * TF_N + n + 16) / 4], 0.0f, 0.0f}; +struct tf_reg_load { + uint4 w0, w1; +#if TF_BITS == 5 + uint2 h; +#elif TF_BITS == 6 + uint4 h; +#endif + uint4 q0, q1; + float x0, x1; +}; + +inline tf_reg_load tf_reg_fetch_w(const device uint4* wt, const device uint4* sbv, int g, int n, int lane) { + const device uint4* wg = wt + (size_t)g * TF_REG_STRIDE; + return { + wg[lane], wg[32 + lane], +#if TF_BITS == 5 + ((const device uint2*)(wg + 64))[lane], +#elif TF_BITS == 6 + wg[64 + lane], +#endif + sbv[((size_t)g * TF_N + n) / 4], sbv[((size_t)g * TF_N + n + 16) / 4], 0.0f, 0.0f + }; } template @@ -287,8 +307,8 @@ inline void tf_reg_sums(thread tf_reg_load& l, XSP XS, int g, int m, int stride) } template -inline tf_reg_load tf_reg_fetch(const device uint4* wl, const device uint4* sbv, XSP XS, int g, int n, int m, int stride) { - tf_reg_load l = tf_reg_fetch_w(wl, sbv, g, n); +inline tf_reg_load tf_reg_fetch(const device uint4* wt, const device uint4* sbv, XSP XS, int g, int n, int m, int stride, int lane) { + tf_reg_load l = tf_reg_fetch_w(wt, sbv, g, n, lane); tf_reg_sums(l, XS, g, m, stride); return l; } @@ -298,7 +318,7 @@ inline tf_reg_load tf_reg_fetch(const device uint4* wl, const device uint4* sbv, #endif // TF_FUSED (Fused in lane_projection.zig): a family's prologue makes the row and its sums under the first weight fetch. -// tf_lane's arithmetic with codes unpacked straight into tensor-op registers: every word equals tf_lane_pair's. +// tf_lane's arithmetic with codes unpacked straight into tensor-op registers: 4-bit, 4+1 5-bit, 4+2 6-bit. [[kernel]] void tf_lane_reg(const device bfloat* X [[buffer(0)]], const device uint4* W [[buffer(1)]], const device bfloat* SB [[buffer(2)]], const device int* mdims [[buffer(3)]], device TF_OUT* Y [[buffer(4)]], const device float* XS [[buffer(5)]], #ifdef TF_FUSED @@ -322,11 +342,11 @@ inline tf_reg_load tf_reg_fetch(const device uint4* wl, const device uint4* sbv, const int first = TF_G0 + (ks * TF_GN) / TF_SK, last = TF_G0 + ((ks + 1) * TF_GN) / TF_SK; constexpr auto desc = matmul2d_descriptor(16, NT, GS, false, true, false, matmul2d_descriptor::mode::multiply); matmul2d op; - const device uint4* wl = W + (size_t)tile * KG * 64 + lane; + const device uint4* wt = W + (size_t)tile * KG * TF_REG_STRIDE; const device uint4* sbv = (const device uint4*)SB; tf_reg_load next = {}; #ifdef TF_FUSED - if (first < last) next = tf_reg_fetch_w(wl, sbv, first, n0 + nb); // the first weights fly while the prologue runs + if (first < last) next = tf_reg_fetch_w(wt, sbv, first, n0 + nb, lane); // first weights fly while prologue runs const tf_fused fa = {A0, A1, A2, A3, A4, A5, O0, O1, F, I}; threadgroup bfloat xs[TF_XROWS > 0 ? TF_XROWS * TF_K : 1]; threadgroup float xsum[KG + 16]; // one row's sums; the 16 past the end feed the discarded rows' lanes @@ -355,7 +375,7 @@ inline tf_reg_load tf_reg_fetch(const device uint4* wl, const device uint4* sbv, #ifdef TF_FUSED if (first < last) tf_reg_sums(next, xsp, first, mb, stride); #else - if (first < last) next = tf_reg_fetch(wl, sbv, xsp, first, n0 + nb, mb, stride); // main's order, unfused + if (first < last) next = tf_reg_fetch(wt, sbv, xsp, first, n0 + nb, mb, stride, lane); // main's order, unfused #endif for (int g = first; g < last; g++) { const tf_reg_load cur = next; @@ -363,12 +383,26 @@ inline tf_reg_load tf_reg_fetch(const device uint4* wl, const device uint4* sbv, // 1024 + code as fp16 bits, codes (0,4) (1,5) (2,6) (3,7) of a word; subtracting 1024 is exact const uint word = w < 4 ? cur.w0[w] : cur.w1[w - 4], lo = word & 0x0F0F0F0Fu, hi = (word >> 4) & 0x0F0F0F0Fu; const int e = 16 * (w & 1) + 2 * (w >> 1); +#if TF_BITS == 5 + const uint hh = cur.h[w >> 2] >> (4 * (w & 3)); + b2[e] = as_type((lo & 0x00FF00FFu) | ((hh & 0x00010001u) << 4) | 0x64006400u) - bias; + b2[e + 1] = as_type((hi & 0x00FF00FFu) | ((hh & 0x00020002u) << 3) | 0x64006400u) - bias; + b2[e + 8] = as_type(((lo >> 8) & 0x00FF00FFu) | ((hh & 0x00040004u) << 2) | 0x64006400u) - bias; + b2[e + 9] = as_type(((hi >> 8) & 0x00FF00FFu) | ((hh & 0x00080008u) << 1) | 0x64006400u) - bias; +#elif TF_BITS == 6 + const uint hh = cur.h[w >> 1] >> (8 * (w & 1)); + b2[e] = as_type((lo & 0x00FF00FFu) | ((hh & 0x00030003u) << 4) | 0x64006400u) - bias; + b2[e + 1] = as_type((hi & 0x00FF00FFu) | ((hh & 0x000C000Cu) << 2) | 0x64006400u) - bias; + b2[e + 8] = as_type(((lo >> 8) & 0x00FF00FFu) | (hh & 0x00300030u) | 0x64006400u) - bias; + b2[e + 9] = as_type(((hi >> 8) & 0x00FF00FFu) | ((hh & 0x00C000C0u) >> 2) | 0x64006400u) - bias; +#else b2[e] = as_type((lo & 0x00FF00FFu) | 0x64006400u) - bias; b2[e + 1] = as_type((hi & 0x00FF00FFu) | 0x64006400u) - bias; b2[e + 8] = as_type(((lo >> 8) & 0x00FF00FFu) | 0x64006400u) - bias; b2[e + 9] = as_type(((hi >> 8) & 0x00FF00FFu) | 0x64006400u) - bias; +#endif } - if (g + 1 < last) next = tf_reg_fetch(wl, sbv, xsp, g + 1, n0 + nb, mb, stride); + if (g + 1 < last) next = tf_reg_fetch(wt, sbv, xsp, g + 1, n0 + nb, mb, stride, lane); auto x = a.slice(g * GS, 0); op.run(x, cb, P); for (int j = 0; j < 4; j++) { diff --git a/zig/kernels/metal/glm_glue.metal b/zig/kernels/metal/glm_glue.metal index 3109a4ca0bf..17585efa8cd 100644 --- a/zig/kernels/metal/glm_glue.metal +++ b/zig/kernels/metal/glm_glue.metal @@ -518,10 +518,7 @@ kernel void glm_streams(const device bfloat* h [[buffer(0)]], device bfloat* x [ } // dst[i] = src[i] for n u32 values (a pick becoming the next window's token or the MTP head's input). -kernel void glm_copy_u32(const device uint* src [[buffer(0)]], device uint* dst [[buffer(1)]], - constant uint& n [[buffer(2)]], uint i [[thread_position_in_grid]]) { - if (i < n) dst[i] = src[i]; -} +TF_COPY_U32_N(glm_copy_u32) // The prompt's routing: each row's top experts and weights in the decode route's arithmetic, one simdgroup a row. template diff --git a/zig/kernels/metal/inkling2/attention.metal b/zig/kernels/metal/inkling2/attention.metal new file mode 100644 index 00000000000..cc4aa7a79f7 --- /dev/null +++ b/zig/kernels/metal/inkling2/attention.metal @@ -0,0 +1,170 @@ +//! Inkling 2 Mini's scalar attention preparation, chunk decode and ordered sink/gate merge. +#include +using namespace metal; +#pragma METAL fp contract(off) + +constant constexpr uint D = 128, REL = 16, EXTENT = 1024; +constant constexpr float LOG2E = 1.4426950408889634f; + +struct InkSeg { + int row0, n, p0, pad; + long off; +}; +struct InkPrepArgs { + uint heads, kv_heads, ring, global; + float qk_clip, rel_clip, floor_pos, alpha, eps; +}; +struct InkAttnArgs { + uint heads, kv_heads, ring, window, chunk, c0, chunks; + float scale; +}; +struct InkMergeArgs { + uint heads, window, chunk, c0, chunks, subs; +}; + +inline float ink_warp_sum(float v) { + for (uint o = 16; o; o >>= 1) v += simd_shuffle_xor(v, ushort(o)); + return v; +} +inline float ink_clip_factor(float ss, float threshold) { + return fmin(threshold / (precise::sqrt(ss) + 1e-6f), 1.0f); +} + +// One 32-thread group handles a row and head; independent q/k/v and relative rows keep their first BF16 rounding. +[[max_total_threads_per_threadgroup(32)]] +kernel void tf_ink2_prep(const device bfloat* q_raw [[buffer(0)]], const device bfloat* k_raw [[buffer(1)]], + const device bfloat* v_raw [[buffer(2)]], const device bfloat* rel_raw [[buffer(3)]], + const device bfloat* q_scale [[buffer(4)]], const device bfloat* rel_scale [[buffer(5)]], + const device int* rpos [[buffer(6)]], const device int* rseg [[buffer(7)]], + const device InkSeg* segs [[buffer(8)]], device bfloat* q_out [[buffer(9)]], + device bfloat* rel_out [[buffer(10)]], device bfloat* kc [[buffer(11)]], device bfloat* vc [[buffer(12)]], + constant InkPrepArgs& a [[buffer(13)]], uint2 tg [[threadgroup_position_in_grid]], + uint lane [[thread_index_in_threadgroup]]) { + const uint row = tg.x, unit = tg.y, pos = uint(rpos[row]); + const float tau = a.global ? 1.0f + a.alpha * precise::log(max(float(pos + 1) / a.floor_pos, 1.0f)) : 1.0f; + float x[4]; + if (unit < a.heads) { + const size_t rh = size_t(row) * a.heads + unit; + for (uint i = 0; i < 4; ++i) x[i] = float(q_raw[rh * D + lane * 4 + i]) * float(q_scale[unit * D + lane * 4 + i]); + float ss = ((x[0] * x[0] + x[1] * x[1]) + x[2] * x[2]) + x[3] * x[3]; + const float f = ink_clip_factor(ink_warp_sum(ss), a.qk_clip); + for (uint i = 0; i < 4; ++i) { + x[i] *= f; + const bfloat once = bfloat(x[i]); + q_out[rh * D + lane * 4 + i] = a.global ? bfloat(float(once) * tau) : once; + } + const float r = lane < REL ? float(rel_raw[rh * REL + lane]) * float(rel_scale[unit * REL + lane]) : 0.0f; + const float rf = ink_clip_factor(ink_warp_sum(r * r), a.rel_clip); + if (lane < REL) { + const bfloat once = bfloat(r * rf); + rel_out[rh * REL + lane] = a.global ? bfloat(float(once) * tau) : once; + } + return; + } + const bool key = unit < a.heads + a.kv_heads; + const uint h = key ? unit - a.heads : unit - a.heads - a.kv_heads; + const device bfloat* src = (key ? k_raw : v_raw) + (size_t(row) * a.kv_heads + h) * D; + for (uint i = 0; i < 4; ++i) x[i] = float(src[lane * 4 + i]); + float scale; + if (key) { + const float ss = ((x[0] * x[0] + x[1] * x[1]) + x[2] * x[2]) + x[3] * x[3]; + scale = ink_clip_factor(ink_warp_sum(ss), a.qk_clip); + } else { + const float ss = ((x[0] * x[0] + x[1] * x[1]) + x[2] * x[2]) + x[3] * x[3]; + scale = precise::rsqrt(ink_warp_sum(ss) / float(D) + a.eps); + } + const InkSeg s = segs[rseg[row]]; + device bfloat* dst = (key ? kc : vc) + s.off + (size_t(h) * a.ring + pos % a.ring) * D; + for (uint i = 0; i < 4; ++i) dst[lane * 4 + i] = bfloat(x[i] * scale); +} + +// The bf16 relative-bias table, one fp32 accumulation in projection tap order. +[[max_total_threads_per_threadgroup(256)]] +kernel void tf_ink2_rel_table(const device bfloat* rel [[buffer(0)]], const device bfloat* proj [[buffer(1)]], + device bfloat* tab [[buffer(2)]], uint rh [[threadgroup_position_in_grid]], uint t [[thread_index_in_threadgroup]]) { + float r[REL]; + for (uint j = 0; j < REL; ++j) r[j] = float(rel[rh * REL + j]); + for (uint d = t; d < EXTENT; d += 256) { + float acc = 0.0f; + for (uint j = 0; j < REL; ++j) acc += r[j] * float(proj[j * EXTENT + d]); + tab[rh * EXTENT + d] = bfloat(acc); + } +} + +// A (row, head, key chunk) a simdgroup. Every P is bf16 before both its denominator add and P.V product. +[[max_total_threads_per_threadgroup(32)]] +kernel void tf_ink2_attn_scalar(const device bfloat* q [[buffer(0)]], const device bfloat* kc [[buffer(1)]], + const device bfloat* vc [[buffer(2)]], const device bfloat* tab [[buffer(3)]], + const device InkSeg* segs [[buffer(4)]], device float* part_o [[buffer(5)]], device float2* part_ml [[buffer(6)]], + const device int* rpos [[buffer(7)]], const device int* rseg [[buffer(8)]], constant InkAttnArgs& a [[buffer(9)]], + uint2 tg [[threadgroup_position_in_grid]], uint lane [[thread_index_in_simdgroup]]) { + const uint rh = tg.x, row = rh / a.heads, h = rh % a.heads, group = a.heads / a.kv_heads, kvh = h / group; + const uint pos = uint(rpos[row]); + const uint lo = a.window && pos + 1 > a.window ? pos + 1 - a.window : 0; + const uint first = a.window ? lo / a.chunk : a.c0; + const uint c = first + tg.y; + if (c > pos / a.chunk || (a.window && c < lo / a.chunk)) return; + const uint from = max(lo, c * a.chunk), to = min(pos + 1, (c + 1) * a.chunk); + const InkSeg s = segs[rseg[row]]; + const size_t head = s.off + size_t(kvh) * a.ring * D; + const size_t prow = rh; + float acc[4] = {0.0f, 0.0f, 0.0f, 0.0f}; + float top = -INFINITY, total = 0.0f; + for (uint kp = from; kp < to; ++kp) { + const size_t at = head + size_t(kp % a.ring) * D; + float4 qv = float4(*(const device bfloat4*)(q + prow * D + lane * 4)); + float4 kv = float4(*(const device bfloat4*)(kc + at + lane * 4)); + const float dot_score = ink_warp_sum(dot(qv, kv)); + const uint distance = pos - kp; + const float bias = distance < EXTENT ? float(tab[prow * EXTENT + distance]) : 0.0f; + const float score = (dot_score * a.scale + bias) * LOG2E; + const float next = max(top, score), a0 = precise::exp2(top - next), b0 = precise::exp2(score - next); + const bfloat p = bfloat(b0); + total = total * a0 + float(p); + for (uint i = 0; i < 4; ++i) acc[i] = acc[i] * a0 + float(p) * float(vc[at + lane * 4 + i]); + top = next; + } + const size_t slot = size_t(prow) * a.chunks + tg.y; + if (lane == 0) part_ml[slot] = float2(top, total); + for (uint i = 0; i < 4; ++i) part_o[slot * D + lane * 4 + i] = acc[i]; +} + +// Fold chunks and any sub-chunks in order, add the sink logit, apply the gate, round once to bf16. +[[max_total_threads_per_threadgroup(128)]] +kernel void tf_ink2_merge(const device float* part_o [[buffer(0)]], const device float2* part_ml [[buffer(1)]], + const device bfloat* sink [[buffer(2)]], const device bfloat* gate [[buffer(3)]], const device int* rpos [[buffer(4)]], + device bfloat* out [[buffer(5)]], constant InkMergeArgs& a [[buffer(6)]], uint rh [[threadgroup_position_in_grid]], + uint d [[thread_index_in_threadgroup]]) { + const uint row = rh / a.heads, pos = uint(rpos[row]); + const uint lo = a.window && pos + 1 > a.window ? pos + 1 - a.window : 0; + float mm = -INFINITY, ll = 0.0f, o = 0.0f; + for (uint c = lo / a.chunk; c <= pos / a.chunk; ++c) { + float cm, cl, co; + if (a.subs > 1) { + float sm = -INFINITY, sl = 0.0f, so = 0.0f; + const uint last = min(a.subs - 1, (pos - c * a.chunk) / 1024); + for (uint u = 0; u <= last; ++u) { + const size_t at = size_t(rh) * a.chunks + (c - a.c0) * a.subs + u; + const float2 ml = part_ml[at]; + const float mn = max(sm, ml.x); + const float x = precise::exp2(sm - mn), y = precise::exp2(ml.x - mn); + sl = sl * x + ml.y * y; + so = so * x + part_o[at * D + d] * y; + sm = mn; + } + cm = sm; cl = sl; co = so; + } else { + const size_t at = size_t(rh) * a.chunks + c - (a.window ? lo / a.chunk : a.c0); + const float2 ml = part_ml[at]; + cm = ml.x; cl = ml.y; co = part_o[at * D + d]; + } + const float mn = max(mm, cm), x = precise::exp2(mm - mn), y = precise::exp2(cm - mn); + ll = ll * x + cl * y; + o = o * x + co * y; + mm = mn; + } + const float sk = float(sink[rh]) * LOG2E, mf = max(mm, sk), a0 = precise::exp2(mm - mf); + const float y = o * a0 / (ll * a0 + precise::exp2(sk - mf)); + const float gv = float(gate[rh * D + d]); + out[rh * D + d] = bfloat(y * (1.0f / (1.0f + precise::exp(-gv)))); +} diff --git a/zig/kernels/metal/inkling2/attention_sources.zig b/zig/kernels/metal/inkling2/attention_sources.zig new file mode 100644 index 00000000000..1aac8a107e1 --- /dev/null +++ b/zig/kernels/metal/inkling2/attention_sources.zig @@ -0,0 +1,5 @@ +//! Shader texts; the prompt's fragment helpers are inline so both chip paths use the same resolver. + +pub const attention = @embedFile("attention.metal"); +pub const prompt_attention = @embedFile("../nax.h") ++ @embedFile("prompt_attention.metal"); +pub const prompt_attention_pre_m5 = "#define TF_SIMD_FRAGS 1\n" ++ prompt_attention; diff --git a/zig/kernels/metal/inkling2/dspark.metal b/zig/kernels/metal/inkling2/dspark.metal new file mode 100644 index 00000000000..01ee835290d --- /dev/null +++ b/zig/kernels/metal/inkling2/dspark.metal @@ -0,0 +1,239 @@ +#include +using namespace metal; +#pragma METAL fp contract(off) + +constant uint DSP_H = 2304; +constant uint DSP_Q = 3072; +constant uint DSP_KV = 1024; +constant uint DSP_HEAD = 128; +constant uint DSP_RANK = 256; +constant uint DSP_RNN = 768; +constant float DSP_EPS = 1e-6f; +constant float DSP_SCALE = 0x1.6a09e6p-7f; + +struct DsparkPositionArgs { uint base; }; +struct DsparkContextArgs { uint base, rows, ring; }; +struct DsparkAttentionArgs { uint committed, ring, local, from; }; +struct DsparkTokenArgs { uint token; }; +struct DsparkResidualArgs { uint init; }; +struct DsparkCountArgs { uint count; }; +struct DsparkBaseArgs { uint rows, vocab; }; + +kernel void tf_ink2_dspark_init_rows(const device bfloat* anchor [[buffer(0)]], const device bfloat* mask [[buffer(1)]], device bfloat* rows [[buffer(2)]], uint row [[threadgroup_position_in_grid]], uint t [[thread_position_in_threadgroup]]) { + for (uint d = t; d < DSP_H; d += 256) { + const device bfloat* src = row == 0 ? anchor : mask; + rows[row * DSP_H + d] = src[d]; + } +} + +kernel void tf_ink2_dspark_fuse_taps(const device bfloat* taps [[buffer(0)]], const device bfloat* fuse_weight [[buffer(1)]], const device bfloat* norm_weight [[buffer(2)]], device bfloat* c [[buffer(3)]], device bfloat* newest_f [[buffer(4)]], constant DsparkCountArgs& a [[buffer(5)]], uint group [[threadgroup_position_in_grid]], uint t [[thread_position_in_threadgroup]]) { + const uint fusion = group / a.count, row = group % a.count; + threadgroup float alpha[4]; + threadgroup float scale; + if (t == 0) { + float scores[4]; + float peak = -INFINITY; + for (uint j = 0; j < 4; ++j) { scores[j] = float(fuse_weight[fusion * 4 + j]); peak = max(peak, scores[j]); } + float sum = 0.0f; + for (uint j = 0; j < 4; ++j) { scores[j] = exp(scores[j] - peak); sum += scores[j]; } + for (uint j = 0; j < 4; ++j) alpha[j] = float(bfloat(scores[j] / sum)); + float square = 0.0f; + for (uint d = 0; d < DSP_H; ++d) { + float mixed = 0.0f; + for (uint j = 0; j < 4; ++j) mixed += alpha[j] * float(taps[(row * 4 + j) * DSP_H + d]); + square += mixed * mixed; + } + scale = rsqrt(square / float(DSP_H) + DSP_EPS); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + for (uint d = t; d < DSP_H; d += 256) { + float mixed = 0.0f; + for (uint j = 0; j < 4; ++j) mixed += alpha[j] * float(taps[(row * 4 + j) * DSP_H + d]); + const bfloat out = bfloat(mixed * scale * float(norm_weight[fusion * DSP_H + d])); + c[(fusion * a.count + row) * DSP_H + d] = out; + if (fusion == 3 && row + 1 == a.count) newest_f[d] = out; + } +} + +static inline float dspark_rope_angle(uint d, uint position) { + const uint pair = d % 64; + const float frequency = pow(1e6f, -float(pair) / 64.0f); + return float(position) * frequency; +} + +kernel void tf_ink2_dspark_block_qkv(const device bfloat* q_raw [[buffer(0)]], const device bfloat* k_raw [[buffer(1)]], const device bfloat* v_raw [[buffer(2)]], const device bfloat* q_weight [[buffer(3)]], const device bfloat* k_weight [[buffer(4)]], device bfloat* q [[buffer(5)]], device bfloat* k [[buffer(6)]], device bfloat* v [[buffer(7)]], constant DsparkPositionArgs& a [[buffer(8)]], uint group [[threadgroup_position_in_grid]], uint d [[thread_position_in_threadgroup]]) { + const uint row = group / 40, work = group % 40; + threadgroup float scale; + if (work < 32 && d == 0) { + float sum = 0.0f; + if (work < 24) { + const uint h = work; + for (uint i = 0; i < DSP_HEAD; ++i) { const float x = float(q_raw[row * DSP_Q + h * DSP_HEAD + i]); sum += x * x; } + } else { + const uint h = work - 24; + for (uint i = 0; i < DSP_HEAD; ++i) { const float x = float(k_raw[row * DSP_KV + h * DSP_HEAD + i]); sum += x * x; } + } + scale = rsqrt(sum / float(DSP_HEAD) + DSP_EPS); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (work >= 32) { + const uint h = work - 32; + v[row * DSP_KV + h * DSP_HEAD + d] = v_raw[row * DSP_KV + h * DSP_HEAD + d]; + return; + } + const bool query = work < 24; + const uint h = query ? work : work - 24; + const uint at = row * (query ? DSP_Q : DSP_KV) + h * DSP_HEAD + d; + const float x = float(bfloat(float(query ? q_raw[at] : k_raw[at]) * scale * float(query ? q_weight[d] : k_weight[d]))); + const uint partner = d < 64 ? d + 64 : d - 64; + const uint other_at = row * (query ? DSP_Q : DSP_KV) + h * DSP_HEAD + partner; + const float other = float(bfloat(float(query ? q_raw[other_at] : k_raw[other_at]) * scale * float(query ? q_weight[partner] : k_weight[partner]))); + const float angle = dspark_rope_angle(d, a.base + row); + const float cs = cos(angle), sn = sin(angle); + const float rotated = d < 64 ? x * cs - other * sn : other * sn + x * cs; + if (query) q[at] = bfloat(rotated); else k[at] = bfloat(rotated); +} + +kernel void tf_ink2_dspark_context_kv(const device bfloat* k_raw [[buffer(0)]], const device bfloat* v_raw [[buffer(1)]], const device bfloat* weight [[buffer(2)]], device bfloat* keys [[buffer(3)]], device bfloat* values [[buffer(4)]], constant DsparkContextArgs& a [[buffer(5)]], uint group [[threadgroup_position_in_grid]], uint d [[thread_position_in_threadgroup]]) { + const uint row = group / 8, h = group % 8; + threadgroup float scale; + if (d == 0) { + float sum = 0.0f; + for (uint i = 0; i < DSP_HEAD; ++i) { const float x = float(k_raw[row * DSP_KV + h * DSP_HEAD + i]); sum += x * x; } + scale = rsqrt(sum / float(DSP_HEAD) + DSP_EPS); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + const uint position = a.base + row; + const uint at = (position % a.ring) * DSP_KV + h * DSP_HEAD + d; + const uint src = row * DSP_KV + h * DSP_HEAD + d; + const uint partner = d < 64 ? d + 64 : d - 64; + const float x = float(bfloat(float(k_raw[src]) * scale * float(weight[d]))); + const float other = float(bfloat(float(k_raw[row * DSP_KV + h * DSP_HEAD + partner]) * scale * float(weight[partner]))); + const float angle = dspark_rope_angle(d, position); + const float cs = cos(angle), sn = sin(angle); + keys[at] = bfloat(d < 64 ? x * cs - other * sn : other * sn + x * cs); + values[at] = v_raw[src]; +} + +static inline float dspark_attention_score(const device bfloat* q, const device bfloat* k, uint q_at, uint k_at) { + float dot = 0.0f; + for (uint d = 0; d < DSP_HEAD; ++d) dot += float(q[q_at + d]) * float(k[k_at + d]); + return dot * DSP_SCALE; +} + +kernel void tf_ink2_dspark_attention(const device bfloat* q [[buffer(0)]], const device bfloat* block_k [[buffer(1)]], const device bfloat* block_v [[buffer(2)]], const device bfloat* context_k [[buffer(3)]], const device bfloat* context_v [[buffer(4)]], device float* scores [[buffer(5)]], device bfloat* out [[buffer(6)]], constant DsparkAttentionArgs& a [[buffer(7)]], uint group [[threadgroup_position_in_grid]], uint d [[thread_position_in_threadgroup]]) { + const uint row = group / 24, h = group % 24, kv = h / 3; + const uint q_at = row * DSP_Q + h * DSP_HEAD; + const uint out_at = q_at + d; + const uint first = max(a.from, a.local && a.committed > 1024 ? a.committed - 1024 : 0); + const uint retained = a.committed - first; + const uint count = retained + 8; + const uint score_at = group * count; + threadgroup float peak, denominator; + if (d == 0) { + float m = -INFINITY; + for (uint j = 0; j < retained; ++j) { + const uint position = first + j; + const float s = dspark_attention_score(q, context_k, q_at, (position % a.ring) * DSP_KV + kv * DSP_HEAD); + scores[score_at + j] = s; + m = max(m, s); + } + for (uint j = 0; j < 8; ++j) { + const float s = dspark_attention_score(q, block_k, q_at, j * DSP_KV + kv * DSP_HEAD); + scores[score_at + retained + j] = s; + m = max(m, s); + } + float sum = 0.0f; + for (uint j = 0; j < count; ++j) sum += exp(scores[score_at + j] - m); + peak = m; + denominator = sum; + } + threadgroup_barrier(mem_flags::mem_threadgroup | mem_flags::mem_device); + float value = 0.0f; + for (uint j = 0; j < retained; ++j) { + const uint position = first + j; + const uint v_at = (position % a.ring) * DSP_KV + kv * DSP_HEAD + d; + value += (exp(scores[score_at + j] - peak) / denominator) * float(context_v[v_at]); + } + for (uint j = 0; j < 8; ++j) { + const uint v_at = (j * DSP_KV + kv * DSP_HEAD) + d; + value += (exp(scores[score_at + retained + j] - peak) / denominator) * float(block_v[v_at]); + } + out[out_at] = bfloat(value); +} + +kernel void tf_ink2_dspark_residual_norm(const device bfloat* x [[buffer(0)]], const device bfloat* residual [[buffer(1)]], const device bfloat* weight [[buffer(2)]], device bfloat* new_residual [[buffer(3)]], device bfloat* normalized [[buffer(4)]], constant DsparkResidualArgs& a [[buffer(5)]], uint row [[threadgroup_position_in_grid]], uint t [[thread_position_in_threadgroup]]) { + threadgroup float scale; + if (t == 0) { + float sum = 0.0f; + for (uint d = 0; d < DSP_H; ++d) { + const uint at = row * DSP_H + d; + const float v = a.init ? float(x[at]) : float(x[at]) + float(residual[at]); + sum += v * v; + } + scale = rsqrt(sum / float(DSP_H) + DSP_EPS); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + for (uint n = 0; n < 9; ++n) { + const uint d = n * 256 + t; + const uint at = row * DSP_H + d; + const float sigma = a.init ? float(x[at]) : float(x[at]) + float(residual[at]); + new_residual[at] = bfloat(sigma); + normalized[at] = bfloat(sigma * scale * float(weight[d])); + } +} + +kernel void tf_ink2_dspark_swiglu(const device bfloat* g [[buffer(0)]], const device bfloat* u [[buffer(1)]], device bfloat* out [[buffer(2)]], constant DsparkCountArgs& a [[buffer(3)]], uint i [[thread_position_in_grid]]) { + if (i >= a.count) return; + const float gate = float(g[i]); + out[i] = bfloat((gate / (1.0f + exp(-gate))) * float(u[i])); +} + +kernel void tf_ink2_dspark_kappa(const device bfloat* y [[buffer(0)]], const device bfloat* f [[buffer(1)]], const device bfloat* weight [[buffer(2)]], const device bfloat* bias [[buffer(3)]], device float* out [[buffer(4)]], constant DsparkCountArgs& a [[buffer(5)]], uint i [[thread_position_in_grid]]) { + const uint row = i / DSP_RNN, channel = i % DSP_RNN; + if (row >= a.count) return; + float sum = 0.0f; + for (uint d = 0; d < DSP_H; ++d) sum += float(y[row * DSP_H + d]) * float(weight[channel * 5120 + 512 + d]); + for (uint d = 0; d < DSP_H; ++d) sum += float(f[d]) * float(weight[channel * 5120 + 2816 + d]); + sum += float(bias[channel]); + out[i] = sum; +} + +kernel void tf_ink2_dspark_recurrent(const device bfloat* state [[buffer(0)]], const device bfloat* kappa [[buffer(1)]], const device bfloat* rnn_weight [[buffer(2)]], const device bfloat* markov [[buffer(3)]], device bfloat* z [[buffer(4)]], device bfloat* next_state [[buffer(5)]], device bfloat* lambda [[buffer(6)]], constant DsparkTokenArgs& a [[buffer(7)]], uint i [[thread_position_in_grid]]) { + if (i >= DSP_RANK) return; + float values[3]; + for (uint part = 0; part < 3; ++part) { + const uint channel = part * DSP_RANK + i; + float sum = 0.0f; + for (uint d = 0; d < DSP_RANK; ++d) sum += float(state[d]) * float(rnn_weight[channel * 5120 + d]); + for (uint d = 0; d < DSP_RANK; ++d) sum += float(markov[uint64_t(a.token) * DSP_RANK + d]) * float(rnn_weight[channel * 5120 + 256 + d]); + sum += float(kappa[channel]); + const bfloat rounded = bfloat(sum); + z[channel] = rounded; + values[part] = float(rounded); + } + const bfloat gamma = bfloat(1.0f / (1.0f + exp(-values[0]))); + const bfloat candidate = bfloat(tanh(values[1])); + const bfloat keep = bfloat(1.0f - float(gamma)); + const bfloat left = bfloat(float(gamma) * float(state[i])); + const bfloat right = bfloat(float(keep) * float(candidate)); + next_state[i] = bfloat(float(left) + float(right)); + lambda[i] = bfloat(tanh(values[2])); +} + +kernel void tf_ink2_dspark_base(const device bfloat* unembed [[buffer(0)]], const device bfloat* y [[buffer(1)]], device bfloat* out [[buffer(2)]], constant DsparkBaseArgs& a [[buffer(3)]], uint i [[thread_position_in_grid]]) { + if (i >= a.rows * a.vocab) return; + const uint row = i / a.vocab, id = i % a.vocab; + float dot = 0.0f; + for (uint d = 0; d < DSP_H; ++d) dot += float(unembed[id * DSP_H + d]) * float(y[row * DSP_H + d]); + out[i] = bfloat(dot); +} + +kernel void tf_ink2_dspark_logits(const device bfloat* base [[buffer(0)]], const device bfloat* phi [[buffer(1)]], const device bfloat* beta [[buffer(2)]], const device bfloat* lambda [[buffer(3)]], device bfloat* out [[buffer(4)]], constant DsparkCountArgs& a [[buffer(5)]], uint i [[thread_position_in_grid]]) { + if (i >= a.count) return; + float dot = 0.0f; + for (uint d = 0; d < DSP_RANK; ++d) dot += float(phi[i * DSP_RANK + d]) * float(lambda[d]); + const bfloat bias = bfloat(float(beta[i]) + dot); + const bfloat logit = bfloat(float(base[i]) + float(bias)); + out[i] = bfloat(30.0f * tanh(float(logit) / 30.0f)); +} diff --git a/zig/kernels/metal/inkling2/dspark_sources.zig b/zig/kernels/metal/inkling2/dspark_sources.zig new file mode 100644 index 00000000000..c9cddfd2917 --- /dev/null +++ b/zig/kernels/metal/inkling2/dspark_sources.zig @@ -0,0 +1,3 @@ +//! Mini DSpark's arithmetic shader and its ten Metal library entry points. + +pub const dspark = @embedFile("dspark.metal"); diff --git a/zig/kernels/metal/inkling2/experts.metal b/zig/kernels/metal/inkling2/experts.metal new file mode 100644 index 00000000000..b1ba70059cf --- /dev/null +++ b/zig/kernels/metal/inkling2/experts.metal @@ -0,0 +1,171 @@ +// Inkling 2 Mini M3: packed weight decode in registers, BF16 activations, FP32 reductions. +#include +using namespace metal; +#pragma METAL fp contract(off) + +struct Ink2MatrixArgs { uint k, n, topk, experts; }; +struct Ink2DecodeArgs { uint rows, k; }; + +inline float ink2_e2m1(uint code) { + const float magnitude[8] = {0.0f, 0.5f, 1.0f, 1.5f, 2.0f, 3.0f, 4.0f, 6.0f}; + const float v = magnitude[code & 7u]; + return (code & 8u) ? -v : v; +} + +inline float ink2_e4m3(uint code) { + const uint exp = (code >> 3u) & 15u, mant = code & 7u; + if (exp == 15u && mant == 7u) return NAN; + const float v = exp ? ldexp(1.0f + float(mant) * 0.125f, int(exp) - 7) + : float(mant) * (1.0f / 512.0f); + return (code & 0x80u) ? -v : v; +} + +inline float ink2_phi(device const float* amax, device const float* denominator, uint expert) { + // Loader casts both globals to BF16 before the dequantization operation. + return precise::divide(float(bfloat(amax[expert])), float(bfloat(denominator[0]))); +} + +inline float ink2_nv_weight(uchar packed, uint column, uchar scale, float phi) { + const uint code = (column & 1u) ? uint(packed >> 4u) : uint(packed & 15u); + const float inner = ink2_e2m1(code) * ink2_e4m3(scale); + return float(bfloat(inner * phi)); +} + +inline float ink2_mx_weight(uchar value, uchar scale) { + const float w = ldexp(ink2_e4m3(value), int(scale) - 127); + // E4M3 times a power of two is exactly representable in BF16, still round explicitly. + return float(bfloat(w)); +} + +inline float ink2_dot_nv(device const uchar* w, device const uchar* scales, + device const bfloat* x, float phi, uint k) { + float sum = 0.0f; + for (uint c = 0; c < k; ++c) + sum += ink2_nv_weight(w[c / 2u], c, scales[c / 16u], phi) * float(x[c]); + return sum; +} + +inline float ink2_dot_mx(device const uchar* w, device const uchar* scales, + device const bfloat* x, uint k) { + float sum = 0.0f; + for (uint c = 0; c < k; ++c) + sum += ink2_mx_weight(w[c], scales[c / 32u]) * float(x[c]); + return sum; +} + +inline float ink2_cap(float x, float cap) { + return cap * precise::tanh(precise::divide(x, cap)); +} + +inline bfloat ink2_act(float gate_dot, float up_dot) { + const float gate = float(bfloat(gate_dot)), up = float(bfloat(up_dot)); + const float left = ink2_cap(gate, 4.0f) * precise::divide(1.0f, 1.0f + precise::exp(-gate)); + // Both GEMM results round before the softcapped SwiGLU; sigmoid uses the rounded gate. + return bfloat(left * ink2_cap(up, 25.0f)); +} + +[[kernel, max_total_threads_per_threadgroup(32)]] void tf_ink2_nvfp4_gu( + device const bfloat* X [[buffer(0)]], device const uchar* W [[buffer(1)]], + device const uchar* S [[buffer(2)]], device const float* amax [[buffer(3)]], + device const float* denominator [[buffer(4)]], device const int* ids [[buffer(5)]], + device bfloat* Y [[buffer(6)]], constant Ink2MatrixArgs& a [[buffer(7)]], + uint group [[threadgroup_position_in_grid]], uint lane [[thread_index_in_threadgroup]]) { + const uint token = group / a.topk, expert = uint(ids[group]); + const ulong expert_w = ulong(expert) * 2u * a.n * (a.k / 2u); + const ulong expert_s = ulong(expert) * 2u * a.n * (a.k / 16u); + const float phi = ink2_phi(amax, denominator, expert); + for (uint n = lane; n < a.n; n += 32u) { + const uint gr = 2u * n, ur = gr + 1u; + const float g = ink2_dot_nv(W + expert_w + ulong(gr) * (a.k / 2u), + S + expert_s + ulong(gr) * (a.k / 16u), X + ulong(token) * a.k, phi, a.k); + const float u = ink2_dot_nv(W + expert_w + ulong(ur) * (a.k / 2u), + S + expert_s + ulong(ur) * (a.k / 16u), X + ulong(token) * a.k, phi, a.k); + Y[group * a.n + n] = ink2_act(g, u); + } +} + +[[kernel, max_total_threads_per_threadgroup(32)]] void tf_ink2_mxfp8_gu( + device const bfloat* X [[buffer(0)]], device const uchar* W [[buffer(1)]], + device const uchar* S [[buffer(2)]], device const int* ids [[buffer(3)]], + device bfloat* Y [[buffer(4)]], constant Ink2MatrixArgs& a [[buffer(5)]], + uint group [[threadgroup_position_in_grid]], uint lane [[thread_index_in_threadgroup]]) { + const uint token = group / a.topk, expert = uint(ids[group]); + const ulong expert_w = ulong(expert) * 2u * a.n * a.k; + const ulong expert_s = ulong(expert) * 2u * a.n * (a.k / 32u); + for (uint n = lane; n < a.n; n += 32u) { + const uint gr = 2u * n, ur = gr + 1u; + const float g = ink2_dot_mx(W + expert_w + ulong(gr) * a.k, + S + expert_s + ulong(gr) * (a.k / 32u), X + ulong(token) * a.k, a.k); + const float u = ink2_dot_mx(W + expert_w + ulong(ur) * a.k, + S + expert_s + ulong(ur) * (a.k / 32u), X + ulong(token) * a.k, a.k); + Y[group * a.n + n] = ink2_act(g, u); + } +} + +[[kernel, max_total_threads_per_threadgroup(32)]] void tf_ink2_nvfp4_down( + device const bfloat* X [[buffer(0)]], device const uchar* W [[buffer(1)]], + device const uchar* S [[buffer(2)]], device const float* amax [[buffer(3)]], + device const float* denominator [[buffer(4)]], device const int* ids [[buffer(5)]], + device bfloat* Y [[buffer(6)]], constant Ink2MatrixArgs& a [[buffer(7)]], + uint group [[threadgroup_position_in_grid]], uint lane [[thread_index_in_threadgroup]]) { + const uint expert = uint(ids[group]); + const ulong expert_w = ulong(expert) * a.n * (a.k / 2u); + const ulong expert_s = ulong(expert) * a.n * (a.k / 16u); + const float phi = ink2_phi(amax, denominator, expert); + for (uint n = lane; n < a.n; n += 32u) + Y[group * a.n + n] = bfloat(ink2_dot_nv(W + expert_w + ulong(n) * (a.k / 2u), + S + expert_s + ulong(n) * (a.k / 16u), X + ulong(group) * a.k, phi, a.k)); +} + +[[kernel, max_total_threads_per_threadgroup(32)]] void tf_ink2_mxfp8_down( + device const bfloat* X [[buffer(0)]], device const uchar* W [[buffer(1)]], + device const uchar* S [[buffer(2)]], device const int* ids [[buffer(3)]], + device bfloat* Y [[buffer(4)]], constant Ink2MatrixArgs& a [[buffer(5)]], + uint group [[threadgroup_position_in_grid]], uint lane [[thread_index_in_threadgroup]]) { + const uint expert = uint(ids[group]); + const ulong expert_w = ulong(expert) * a.n * a.k; + const ulong expert_s = ulong(expert) * a.n * (a.k / 32u); + for (uint n = lane; n < a.n; n += 32u) + Y[group * a.n + n] = bfloat(ink2_dot_mx(W + expert_w + ulong(n) * a.k, + S + expert_s + ulong(n) * (a.k / 32u), X + ulong(group) * a.k, a.k)); +} + +// Weight decode helpers unpack checkpoint bytes and never quantize an activation. +[[kernel, max_total_threads_per_threadgroup(32)]] void tf_ink2_nvfp4_quantize( + device const uchar* W [[buffer(0)]], device const uchar* S [[buffer(1)]], + device const float* amax [[buffer(2)]], device const float* denominator [[buffer(3)]], + device bfloat* Y [[buffer(4)]], constant Ink2DecodeArgs& a [[buffer(5)]], + uint group [[threadgroup_position_in_grid]], uint lane [[thread_index_in_threadgroup]]) { + const uint at = group * 32u + lane; + if (at >= a.rows * a.k) return; + const uint row = at / a.k, col = at % a.k; + const float phi = ink2_phi(amax, denominator, 0); + Y[at] = bfloat(ink2_nv_weight(W[row * (a.k / 2u) + col / 2u], col, + S[row * (a.k / 16u) + col / 16u], phi)); +} + +[[kernel, max_total_threads_per_threadgroup(32)]] void tf_ink2_mxfp8_quantize( + device const uchar* W [[buffer(0)]], device const uchar* S [[buffer(1)]], + device bfloat* Y [[buffer(2)]], constant Ink2DecodeArgs& a [[buffer(3)]], + uint group [[threadgroup_position_in_grid]], uint lane [[thread_index_in_threadgroup]]) { + const uint at = group * 32u + lane; + if (at >= a.rows * a.k) return; + const uint row = at / a.k, col = at % a.k; + Y[at] = bfloat(ink2_mx_weight(W[at], S[row * (a.k / 32u) + col / 32u])); +} + +[[kernel, max_total_threads_per_threadgroup(32)]] void tf_ink2_combine( + device const bfloat* down [[buffer(0)]], device const int* ids [[buffer(1)]], + device const float* weights [[buffer(2)]], device bfloat* Y [[buffer(3)]], + constant Ink2MatrixArgs& a [[buffer(4)]], uint group [[threadgroup_position_in_grid]], + uint lane [[thread_index_in_threadgroup]]) { + // Outer expert order, not route-slot order, fixes the reference's accumulation order. + for (uint n = lane; n < a.n; n += 32u) { + float sum = 0.0f; + for (uint expert = 0; expert < a.experts; ++expert) + for (uint slot = 0; slot < a.topk; ++slot) + if (uint(ids[group * a.topk + slot]) == expert) + sum += weights[group * a.topk + slot] * float(down[(group * a.topk + slot) * a.n + n]); + Y[group * a.n + n] = bfloat(sum); + } +} diff --git a/zig/kernels/metal/inkling2/experts_sources.zig b/zig/kernels/metal/inkling2/experts_sources.zig new file mode 100644 index 00000000000..56ae6e1c0db --- /dev/null +++ b/zig/kernels/metal/inkling2/experts_sources.zig @@ -0,0 +1,2 @@ +//! Inkling 2 Mini's M3 packed-weight expert kernels; activations stay BF16 throughout. +pub const experts = @embedFile("experts.metal"); diff --git a/zig/kernels/metal/inkling2/glue.metal b/zig/kernels/metal/inkling2/glue.metal new file mode 100644 index 00000000000..79e3a71a743 --- /dev/null +++ b/zig/kernels/metal/inkling2/glue.metal @@ -0,0 +1,225 @@ +#include +#pragma METAL fp contract(off) +using namespace metal; + +// Inkling 2 Mini glue. Every reduction is FP32; bfloat stores round nearest-even. +constant float INKLING_EPS = 1e-6f; +constant float INKLING_AR_SCALE = 0x1.555556p-6f; // binary32(1 / 48) + +inline float ink_sigmoid(float x) { + const float e = precise::exp(-fabs(x)); + return x < 0.0f ? precise::divide(e, 1.0f + e) : precise::divide(1.0f, 1.0f + e); +} +inline float ink_cap(float x, float c) { + return c * precise::tanh(precise::divide(x, c)); +} +inline float ink_value(const device bfloat* blocks, const device float* partial, + uint source, uint sources, uint d) { + return source + 1 == sources ? partial[d] : float(blocks[size_t(source) * 2304 + d]); +} + +struct InkEmbedArgs { uint rows; }; +[[max_total_threads_per_threadgroup(256)]] +kernel void tf_inkling2_embed_norm( + const device uint* ids [[buffer(0)]], const device bfloat* table [[buffer(1)]], + const device bfloat* weight [[buffer(2)]], device bfloat* out [[buffer(3)]], + constant InkEmbedArgs& a [[buffer(4)]], uint t [[thread_position_in_threadgroup]], + uint row [[threadgroup_position_in_grid]], uint lane [[thread_index_in_simdgroup]]) { + if (row >= a.rows) return; + const device bfloat* x = table + size_t(ids[row]) * 2304; + float part = 0.0f; + for (uint d = t; d < 2304; d += 256) { const float v = float(x[d]); part += v * v; } + threadgroup float red[8], inverse; + const float reduced = simd_sum(part); + if (lane == 0) red[t / 32] = reduced; + threadgroup_barrier(mem_flags::mem_threadgroup); + if (t == 0) { + float total = 0.0f; + for (uint j = 0; j < 8; ++j) total += red[j]; + inverse = precise::rsqrt(precise::divide(total, 2304.0f) + INKLING_EPS); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + for (uint d = t; d < 2304; d += 256) + out[size_t(row) * 2304 + d] = bfloat(float(weight[d]) * (float(x[d]) * inverse)); +} + +struct InkARArgs { uint sources, queries; }; +[[max_total_threads_per_threadgroup(256)]] +kernel void tf_inkling2_ar( + const device bfloat* blocks [[buffer(0)]], const device float* partial [[buffer(1)]], + const device float* queries [[buffer(2)]], device float* out [[buffer(3)]], + constant InkARArgs& a [[buffer(4)]], uint t [[thread_position_in_threadgroup]], + uint q [[threadgroup_position_in_grid]], uint lane [[thread_index_in_simdgroup]]) { + if (q >= a.queries || a.sources == 0 || a.sources > 5) return; + threadgroup float red[2 * 5 * 8], means[5], weights[5]; + for (uint s = 0; s < a.sources; ++s) { + float ss = 0.0f; + for (uint d = t; d < 2304; d += 256) { + const float x = ink_value(blocks, partial, s, a.sources, d); + ss += x * x; + } + const float reduced = simd_sum(ss); + if (lane == 0) red[s * 8 + t / 32] = reduced; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (t == 0) for (uint s = 0; s < a.sources; ++s) { + float ss = 0.0f; + for (uint j = 0; j < 8; ++j) ss += red[s * 8 + j]; + means[s] = precise::rsqrt(precise::divide(ss, 2304.0f) + INKLING_EPS); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + threadgroup float* dots = red + 40; + for (uint s = 0; s < a.sources; ++s) { + float dot = 0.0f; + for (uint d = t; d < 2304; d += 256) { + const float z = ink_value(blocks, partial, s, a.sources, d) * means[s]; + dot += queries[size_t(q) * 2304 + d] * z; + } + const float reduced = simd_sum(dot); + if (lane == 0) dots[s * 8 + t / 32] = reduced; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (t == 0) { + float peak = -INFINITY; + for (uint s = 0; s < a.sources; ++s) { + float dot = 0.0f; + for (uint j = 0; j < 8; ++j) dot += dots[s * 8 + j]; + weights[s] = dot * INKLING_AR_SCALE; + peak = max(peak, weights[s]); + } + float den = 0.0f; + for (uint s = 0; s < a.sources; ++s) { weights[s] = precise::exp(weights[s] - peak); den += weights[s]; } + for (uint s = 0; s < a.sources; ++s) weights[s] = precise::divide(weights[s], den); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + for (uint d = t; d < 2304; d += 256) { + float acc = 0.0f; + for (uint s = 0; s < a.sources; ++s) + acc += weights[s] * (ink_value(blocks, partial, s, a.sources, d) * means[s]); + out[size_t(q) * 2304 + d] = acc; + } +} + +struct InkConvArgs { uint rows, channels; }; +kernel void tf_inkling2_conv_static( + const device bfloat* taps [[buffer(0)]], const device bfloat* weight [[buffer(1)]], + device bfloat* out [[buffer(2)]], constant InkConvArgs& a [[buffer(3)]], + uint2 at [[thread_position_in_grid]]) { + const uint c = at.x, r = at.y; + if (c >= a.channels || r >= a.rows) return; + float sum = float(taps[size_t(r + 3) * a.channels + c]); + for (uint tap = 0; tap < 4; ++tap) + sum += float(weight[c * 4 + tap]) * float(taps[size_t(r + tap) * a.channels + c]); + out[size_t(r) * a.channels + c] = bfloat(precise::divide(sum, precise::sqrt(5.0f))); +} + +kernel void tf_inkling2_conv_dynamic( + const device bfloat* taps [[buffer(0)]], const device bfloat* input [[buffer(1)]], + const device bfloat* static_w [[buffer(2)]], const device bfloat* projection [[buffer(3)]], + device bfloat* out [[buffer(4)]], constant InkConvArgs& a [[buffer(5)]], + uint t [[thread_position_in_threadgroup]], uint r [[threadgroup_position_in_grid]]) { + if (r >= a.rows) return; + threadgroup float projected[32]; + if (t < 32) { + float dot = 0.0f; + for (uint d = 0; d < 2304; ++d) + dot += float(projection[size_t(t) * 2304 + d]) * float(input[size_t(r) * 2304 + d]); + projected[t] = float(bfloat(dot)); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + for (uint c = t; c < a.channels; c += 256) { + float sum = float(taps[size_t(r + 3) * a.channels + c]); + for (uint lag = 0; lag < 4; ++lag) { + const float w = float(static_w[lag * a.channels + c]) + projected[4 * (c / 128) + lag]; + sum += w * float(taps[size_t(r + 3 - lag) * a.channels + c]); + } + out[size_t(r) * a.channels + c] = bfloat(precise::divide(sum, 3.0f)); + } +} + +struct InkRouteArgs { uint rows; }; +kernel void tf_inkling2_router( + const device bfloat* x [[buffer(0)]], const device bfloat* weight [[buffer(1)]], + const device float* bias [[buffer(2)]], device uint* ids [[buffer(3)]], + device float* weights [[buffer(4)]], constant InkRouteArgs& a [[buffer(5)]], + uint t [[thread_position_in_threadgroup]], uint row [[threadgroup_position_in_grid]]) { + if (row >= a.rows) return; + threadgroup float scores[128], chosen[8]; + threadgroup uint picked[8]; + if (t < 128) { + float dot = 0.0f; + for (uint d = 0; d < 2304; ++d) + dot += float(weight[size_t(t) * 2304 + d]) * float(x[size_t(row) * 2304 + d]); + scores[t] = ink_sigmoid(dot); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (t == 0) { + bool used[128] = {}; + for (uint j = 0; j < 8; ++j) { + uint best = 128; + for (uint e = 0; e < 128; ++e) if (!used[e]) { + if (best == 128 || scores[e] + bias[e] > scores[best] + bias[best]) best = e; + } + used[best] = true; picked[j] = best; chosen[j] = scores[best]; + } + // Combining, including the denominator, is in ascending expert index. + for (uint j = 1; j < 8; ++j) { + uint id = picked[j]; float score = chosen[j]; uint k = j; + while (k > 0 && picked[k - 1] > id) { picked[k] = picked[k - 1]; chosen[k] = chosen[k - 1]; --k; } + picked[k] = id; chosen[k] = score; + } + float den = 1e-20f; + for (uint j = 0; j < 8; ++j) den += chosen[j]; + for (uint j = 0; j < 8; ++j) { + ids[row * 8 + j] = picked[j]; + weights[row * 8 + j] = precise::divide(chosen[j], den) * 8.0f; + } + } +} + +struct InkActArgs { uint rows, width; }; +kernel void tf_inkling2_swiglu( + const device bfloat* gu [[buffer(0)]], device bfloat* out [[buffer(1)]], + constant InkActArgs& a [[buffer(2)]], uint2 at [[thread_position_in_grid]]) { + const uint j = at.x, r = at.y; + if (j >= a.width || r >= a.rows) return; + const float g = float(gu[(size_t(r) * a.width + j) * 2]); + const float u = float(gu[(size_t(r) * a.width + j) * 2 + 1]); + out[size_t(r) * a.width + j] = bfloat(ink_cap(g, 4.0f) * ink_sigmoid(g) * ink_cap(u, 25.0f)); +} + +struct InkLogitArgs { uint rows, vocab; }; +kernel void tf_inkling2_logits( + const device bfloat* h [[buffer(0)]], const device bfloat* unembed [[buffer(1)]], + device float* out [[buffer(2)]], constant InkLogitArgs& a [[buffer(3)]], + uint2 at [[thread_position_in_grid]]) { + const uint v = at.x, r = at.y; + if (v >= a.vocab || r >= a.rows) return; + float dot = 0.0f; + for (uint d = 0; d < 2304; ++d) + dot += float(unembed[size_t(v) * 2304 + d]) * float(h[size_t(r) * 2304 + d]); + // A9(a): unembedding rounds to bf16 before it widens for softcap30. + out[size_t(r) * a.vocab + v] = ink_cap(float(bfloat(dot)), 30.0f); +} + +struct InkExpertArgs { uint rows, channels; }; +kernel void tf_inkling2_expert_pick( + const device bfloat* experts [[buffer(0)]], const device uint* ids [[buffer(1)]], + device bfloat* out [[buffer(2)]], constant InkExpertArgs& a [[buffer(3)]], + uint3 at [[thread_position_in_grid]]) { + const uint j = at.x, d = at.y, r = at.z; + if (j >= 8 || d >= a.channels || r >= a.rows) return; + out[(size_t(r) * 8 + j) * a.channels + d] = experts[(size_t(r) * 128 + ids[r * 8 + j]) * a.channels + d]; +} + +kernel void tf_inkling2_expert_combine( + const device bfloat* picked [[buffer(0)]], const device float* weights [[buffer(1)]], + device bfloat* out [[buffer(2)]], constant InkExpertArgs& a [[buffer(3)]], + uint2 at [[thread_position_in_grid]]) { + const uint d = at.x, r = at.y; + if (d >= a.channels || r >= a.rows) return; + float acc = 0.0f; + for (uint j = 0; j < 8; ++j) + acc += weights[r * 8 + j] * float(picked[(size_t(r) * 8 + j) * a.channels + d]); + out[size_t(r) * a.channels + d] = bfloat(acc); +} diff --git a/zig/kernels/metal/inkling2/glue_sources.zig b/zig/kernels/metal/inkling2/glue_sources.zig new file mode 100644 index 00000000000..b0e00911c06 --- /dev/null +++ b/zig/kernels/metal/inkling2/glue_sources.zig @@ -0,0 +1,2 @@ +//! Inkling 2 Mini's embedding, residual, convolution, routing and output glue. +pub const glue = @embedFile("glue.metal"); diff --git a/zig/kernels/metal/inkling2/loop.metal b/zig/kernels/metal/inkling2/loop.metal new file mode 100644 index 00000000000..fce6e866f6b --- /dev/null +++ b/zig/kernels/metal/inkling2/loop.metal @@ -0,0 +1,136 @@ +#include +#pragma METAL fp contract(off) +using namespace metal; + +// Cross-pass dots use fixed-order FP32 accumulation and SIMD reductions; no BF16 value accumulates. +constant float INKLING_LOOP_EPS = 1e-6f; +constant float INKLING_LOOP_SCALE = 0x1.555556p-6f; // binary32(1 / 48) +constant uint INKLING_LOOP_H = 2304; +constant uint INKLING_LOOP_RANK = 64; +constant uint INKLING_LOOP_MESSAGES = 48; + +struct InkLoopArgs { uint rows; }; + +kernel void tf_inkling2_loop_messages( + const device bfloat* bank0 [[buffer(0)]], const device bfloat* bank1 [[buffer(1)]], + const device float* q_mlp [[buffer(2)]], const device float* kv [[buffer(3)]], + device float* out [[buffer(4)]], constant InkLoopArgs& a [[buffer(5)]], + uint t [[thread_position_in_threadgroup]], uint work [[threadgroup_position_in_grid]], + uint lane [[thread_index_in_simdgroup]]) { + const uint row = work / INKLING_LOOP_MESSAGES; + const uint entry = work - row * INKLING_LOOP_MESSAGES; + if (row >= a.rows) return; + const uint layer = entry / 4; + const uint role = entry - 4 * layer; + const device float* queries = (role == 0 || role == 3) ? q_mlp : kv; + // q/mlp and k/v occupy even/odd rows respectively. + const device float* query = queries + size_t(2 * layer + (role >= 2 ? 1 : 0)) * INKLING_LOOP_H; + const device bfloat* banks[2] = { bank0 + size_t(row) * INKLING_LOOP_H, + bank1 + size_t(row) * INKLING_LOOP_H }; + threadgroup float sums[2 * 8], inverse[2], dots[2 * 8], weights[2]; + for (uint s = 0; s < 2; ++s) { + float ss = 0.0f; + for (uint d = t; d < INKLING_LOOP_H; d += 256) { + const float x = float(banks[s][d]); + ss += x * x; + } + const float reduced = simd_sum(ss); + if (lane == 0) sums[s * 8 + t / 32] = reduced; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (t == 0) for (uint s = 0; s < 2; ++s) { + float ss = 0.0f; + for (uint j = 0; j < 8; ++j) ss += sums[s * 8 + j]; + inverse[s] = precise::rsqrt(precise::divide(ss, 2304.0f) + INKLING_LOOP_EPS); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + for (uint s = 0; s < 2; ++s) { + float dot = 0.0f; + for (uint d = t; d < INKLING_LOOP_H; d += 256) { + const float beta = float(banks[s][d]) * inverse[s]; + dot += query[d] * beta; + } + const float reduced = simd_sum(dot); + if (lane == 0) dots[s * 8 + t / 32] = reduced; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (t == 0) { + float logits[2]; + float peak = -INFINITY; + for (uint s = 0; s < 2; ++s) { + float dot = 0.0f; + for (uint j = 0; j < 8; ++j) dot += dots[s * 8 + j]; + weights[s] = dot * INKLING_LOOP_SCALE; + logits[s] = weights[s]; + peak = max(peak, logits[s]); + } + float den = 0.0f; + for (uint s = 0; s < 2; ++s) { + weights[s] = precise::exp(logits[s] - peak); + den += weights[s]; + } + for (uint s = 0; s < 2; ++s) weights[s] = precise::divide(weights[s], den); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + for (uint d = t; d < INKLING_LOOP_H; d += 256) { + const float beta0 = float(banks[0][d]) * inverse[0]; + const float beta1 = float(banks[1][d]) * inverse[1]; + out[(size_t(row) * INKLING_LOOP_MESSAGES + entry) * INKLING_LOOP_H + d] = + weights[0] * beta0 + weights[1] * beta1; + } +} + +kernel void tf_inkling2_loop_gates( + const device float* h [[buffer(0)]], const device float* m [[buffer(1)]], + const device bfloat* down [[buffer(2)]], const device bfloat* forget [[buffer(3)]], + const device bfloat* gain [[buffer(4)]], device float* out [[buffer(5)]], + constant InkLoopArgs& a [[buffer(6)]], uint t [[thread_position_in_threadgroup]], + uint row [[threadgroup_position_in_grid]], uint lane [[thread_index_in_simdgroup]]) { + if (row >= a.rows) return; + const device float* inputs[2] = { h + size_t(row) * INKLING_LOOP_H, + m + size_t(row) * INKLING_LOOP_H }; + threadgroup float sums[2 * 8], inverse[2], zeta[INKLING_LOOP_RANK]; + threadgroup bfloat normalized[2 * INKLING_LOOP_H]; + for (uint s = 0; s < 2; ++s) { + float ss = 0.0f; + for (uint d = t; d < INKLING_LOOP_H; d += 256) { + const float x = inputs[s][d]; + ss += x * x; + } + const float reduced = simd_sum(ss); + if (lane == 0) sums[s * 8 + t / 32] = reduced; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (t == 0) for (uint s = 0; s < 2; ++s) { + float ss = 0.0f; + for (uint j = 0; j < 8; ++j) ss += sums[s * 8 + j]; + inverse[s] = precise::rsqrt(precise::divide(ss, 2304.0f) + INKLING_LOOP_EPS); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + for (uint d = t; d < INKLING_LOOP_H; d += 256) { + normalized[d] = bfloat(h[size_t(row) * INKLING_LOOP_H + d] * inverse[0]); + normalized[INKLING_LOOP_H + d] = bfloat(m[size_t(row) * INKLING_LOOP_H + d] * inverse[1]); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (t < INKLING_LOOP_RANK) { + float dot = 0.0f; + for (uint d = 0; d < 2 * INKLING_LOOP_H; ++d) + dot += float(down[size_t(t) * (2 * INKLING_LOOP_H) + d]) * float(normalized[d]); + zeta[t] = float(bfloat(dot)); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + for (uint d = t; d < INKLING_LOOP_H; d += 256) { + float fdot = 0.0f, gdot = 0.0f; + for (uint r = 0; r < INKLING_LOOP_RANK; ++r) { + fdot += float(forget[size_t(d) * INKLING_LOOP_RANK + r]) * zeta[r]; + gdot += float(gain[size_t(d) * INKLING_LOOP_RANK + r]) * zeta[r]; + } + const float f = precise::tanh(fdot); + const float g = precise::tanh(gdot); + // Four separately rounded binary32 steps; do not fold these into one expression. + const float keep = 1.0f - f; + const float left = keep * h[size_t(row) * INKLING_LOOP_H + d]; + const float right = g * m[size_t(row) * INKLING_LOOP_H + d]; + out[size_t(row) * INKLING_LOOP_H + d] = left + right; + } +} diff --git a/zig/kernels/metal/inkling2/loop_sources.zig b/zig/kernels/metal/inkling2/loop_sources.zig new file mode 100644 index 00000000000..3e1345c1a82 --- /dev/null +++ b/zig/kernels/metal/inkling2/loop_sources.zig @@ -0,0 +1,2 @@ +//! Inkling 2 Mini's cross-pass message and rank-64 gate shaders. +pub const loop = @embedFile("loop.metal"); diff --git a/zig/kernels/metal/inkling2/prompt_attention.metal b/zig/kernels/metal/inkling2/prompt_attention.metal new file mode 100644 index 00000000000..06f4459bd7e --- /dev/null +++ b/zig/kernels/metal/inkling2/prompt_attention.metal @@ -0,0 +1,145 @@ +//! Inkling 2 Mini's prompt attention; attention_sources prepends the tensor-fragment helpers. +#include +using namespace metal; +#pragma METAL fp contract(off) + +constant constexpr uint D = 128, EXTENT = 1024, KEYS = 64, PAIRS = 128; +constant constexpr float LOG2E = 1.4426950408889634f; +struct InkPromptSeg { int row0, n, p0, pad; long off; }; +struct InkPromptArgs { uint heads, kv_heads, ring, chunk, c0, chunks; float scale; }; + +inline size_t ink_prompt_rh(const InkPromptSeg& s, uint heads, uint group, uint kvh, uint pair) { + return (size_t(s.row0) + pair / group) * heads + kvh * group + pair % group; +} + +inline void ink_fold(float& mm, float& ll, float m, float l, float& a, float& b) { + const float mn = max(mm, m); + a = precise::exp2(mm - mn); + b = precise::exp2(m - mn); + ll = ll * a + l * b; + mm = mn; +} +inline void ink_rows(thread const tfp::frag* s, thread float (&r)[2], bool maximum) { + for (uint f = 0; f < 4; ++f) for (uint h = 0; h < 2; ++h) { + const uint b = 4 * h; + float v = maximum ? max(max(s[f][b], s[f][b + 1]), max(s[f][b + 2], s[f][b + 3])) + : (s[f][b] + s[f][b + 1]) + (s[f][b + 2] + s[f][b + 3]); + const float x = simd_shuffle_xor(v, ushort(1)); + v = maximum ? max(v, x) : v + x; + const float y = simd_shuffle_xor(v, ushort(8)); + v = maximum ? max(v, y) : v + y; + r[h] = maximum ? max(r[h], v) : r[h] + v; + } +} + +// 128 (row, head) pairs and one key head/chunk a 256-thread group; each simdgroup owns 16 pairs. +[[max_total_threads_per_threadgroup(256)]] +kernel void tf_ink2_attn_prompt(const device bfloat* q [[buffer(0)]], const device bfloat* kc [[buffer(1)]], + const device bfloat* vc [[buffer(2)]], const device bfloat* tab [[buffer(3)]], + const device InkPromptSeg* segs [[buffer(4)]], device float* part_o [[buffer(5)]], device float2* part_ml [[buffer(6)]], + constant InkPromptArgs& a [[buffer(7)]], uint3 tg [[threadgroup_position_in_grid]], + uint sg [[simdgroup_index_in_threadgroup]], uint lane [[thread_index_in_simdgroup]], uint t [[thread_index_in_threadgroup]]) { + threadgroup bfloat ks[KEYS * D], vs[KEYS * D]; + const InkPromptSeg s = segs[0]; + const uint group = a.heads / a.kv_heads, total = uint(s.n) * group, m0 = tg.x * PAIRS; + if (m0 >= total) return; + const uint kvh = tg.y, c = a.c0 + tg.z, b_lo = c * a.chunk; + const uint tile_hi = uint(s.p0) + min(m0 + PAIRS - 1, total - 1) / group; + if (b_lo > tile_hi) return; + const uint k_hi = min(b_lo + a.chunk - 1, tile_hi), m = m0 + 16 * sg; + const short2 home = tfp::frag_home(ushort(lane)); + const uint row_a = m + uint(home.y), row_b = row_a + 8; + const uint pair_a = min(row_a, total - 1), pair_b = min(row_b, total - 1); + const device bfloat* qb0 = q + ink_prompt_rh(s, a.heads, group, kvh, pair_a) * D; + const device bfloat* qb1 = q + ink_prompt_rh(s, a.heads, group, kvh, pair_b) * D; + const size_t hb = s.off + size_t(kvh) * a.ring * D; + tfp::frag acc[8], out[8]; + for (uint d = 0; d < 8; ++d) { acc[d] = tfp::frag(0); out[d] = tfp::frag(0); } + float top[2] = {-INFINITY, -INFINITY}, mass[2] = {0.0f, 0.0f}; + float upper[2] = {-INFINITY, -INFINITY}, whole[2] = {0.0f, 0.0f}; + for (uint kt = b_lo; kt <= k_hi; kt += KEYS) { + const uint tile_end = min(kt + KEYS, k_hi + 1); + for (uint e = t; e < KEYS * D; e += 256) { + const uint key = e / D, col = e % D, kp = kt + key; + const bool live = kp < tile_end; + const size_t at = hb + size_t((live ? kp : kt) % a.ring) * D + col; + ks[e] = live ? kc[at] : bfloat(0); + vs[e] = live ? vc[at] : bfloat(0); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if ((kt - b_lo) % 1024 == 0) { + for (uint d = 0; d < 8; ++d) acc[d] = tfp::frag(0); + top[0] = top[1] = -INFINITY; mass[0] = mass[1] = 0.0f; + } + tfp::frag score[4] = {tfp::frag(0), tfp::frag(0), tfp::frag(0), tfp::frag(0)}; + if (m < total && kt <= uint(s.p0) + min(m + 15, total - 1) / group) { + for (uint d = 0; d < 8; ++d) { + tfp::frag qa, kb0, kb1, kb2, kb3; + tfp::frag_get_rows(qa, qb0, qb1, 16 * d, home, row_a < total, row_b < total); + tfp::frag_get_t(kb0, ks, D, 0, 16 * d, home); + tfp::frag_get_t(kb1, ks, D, 16, 16 * d, home); + tfp::frag_get_t(kb2, ks, D, 32, 16 * d, home); + tfp::frag_get_t(kb3, ks, D, 48, 16 * d, home); + tfp::mma_16x32(score[0], score[1], qa, kb0, kb1); + tfp::mma_16x32(score[2], score[3], qa, kb2, kb3); + } + float peak[2] = {top[0], top[1]}; + const uint sub_lo = b_lo + ((kt - b_lo) / 1024) * 1024, sub_hi = sub_lo + 1023; + for (uint f = 0; f < 4; ++f) for (uint e = 0; e < 8; ++e) { + const uint row = m + uint(home.y) + (e >> 2) * 8, col = uint(home.x) + TF_COL(e), kp = kt + 16 * f + col; + const uint lr = row < total ? row / group : 0, pos = uint(s.p0) + lr; + const size_t prow = ink_prompt_rh(s, a.heads, group, kvh, row); + const bool live = row < total && kp <= pos && kp >= sub_lo && kp <= sub_hi; + const uint distance = live ? pos - kp : 0; + const float bias = live && distance < EXTENT ? float(tab[prow * EXTENT + distance]) : 0.0f; + score[f][e] = live ? (score[f][e] * a.scale + bias) * LOG2E : -INFINITY; + } + ink_rows(score, peak, true); + float keep[2]; + for (uint h = 0; h < 2; ++h) { + const float mu = peak[h] == -INFINITY ? 0.0f : peak[h]; + keep[h] = precise::exp2(top[h] - mu); + top[h] = peak[h]; mass[h] *= keep[h]; + } + tfp::frag p[4]; + for (uint f = 0; f < 4; ++f) for (uint e = 0; e < 8; ++e) { + const float mu = peak[e >> 2] == -INFINITY ? 0.0f : peak[e >> 2]; + p[f][e] = bfloat(precise::exp2(score[f][e] - mu)); + } + // Reduce the rounded P, not its pre-bf16 exponential. + tfp::frag rounded[4]; + for (uint f = 0; f < 4; ++f) for (uint e = 0; e < 8; ++e) rounded[f][e] = float(p[f][e]); + ink_rows(rounded, mass, false); + for (uint d = 0; d < 8; ++d) for (uint e = 0; e < 8; ++e) acc[d][e] *= keep[e >> 2]; + for (uint f = 0; f < 4; ++f) for (uint d = 0; d < 8; d += 2) { + tfp::frag v0, v1; + tfp::frag_get(v0, vs, D, 16 * f, 16 * d, home); + tfp::frag_get(v1, vs, D, 16 * f, 16 * d + 16, home); + tfp::mma_16x32(acc[d], acc[d + 1], p[f], v0, v1); + } + } + const bool fold_now = (kt - b_lo) % 1024 == 960 || kt + KEYS > k_hi; + if (fold_now && m < total) for (uint h = 0; h < 2; ++h) { + if (top[h] == -INFINITY) continue; + float x, y; + ink_fold(upper[h], whole[h], top[h], mass[h], x, y); + for (uint d = 0; d < 8; ++d) for (uint e = 4 * h; e < 4 * h + 4; ++e) out[d][e] = out[d][e] * x + acc[d][e] * y; + } + threadgroup_barrier(mem_flags::mem_threadgroup); // no simdgroup reads ks/vs when the next tile overwrites them + } + if (m >= total) return; + for (uint d = 0; d < 8; ++d) for (uint e = 0; e < 8; ++e) { + const uint row = m + uint(home.y) + (e >> 2) * 8, col = uint(home.x) + TF_COL(e); + if (row >= total) continue; + const uint pos = uint(s.p0) + row / group; + if (b_lo > pos) continue; + const size_t prow = ink_prompt_rh(s, a.heads, group, kvh, row); + part_o[(prow * a.chunks + c - a.c0) * D + 16 * d + col] = out[d][e]; + } + if (home.x == 0) for (uint h = 0; h < 2; ++h) { + const uint row = m + uint(home.y) + 8 * h; + if (row >= total || b_lo > uint(s.p0) + row / group) continue; + const size_t prow = ink_prompt_rh(s, a.heads, group, kvh, row); + part_ml[prow * a.chunks + c - a.c0] = float2(upper[h], whole[h]); + } +} diff --git a/zig/kernels/metal/inkling2/runtime.metal b/zig/kernels/metal/inkling2/runtime.metal new file mode 100644 index 00000000000..e77123891b9 --- /dev/null +++ b/zig/kernels/metal/inkling2/runtime.metal @@ -0,0 +1,28 @@ +#include +using namespace metal; +#pragma METAL fp contract(off) +struct InkRuntimeArgs { uint count, boundary; }; +kernel void tf_ink2_copy_bf16(const device bfloat* x [[buffer(0)]], device bfloat* y [[buffer(1)]], constant InkRuntimeArgs& a [[buffer(2)]], uint i [[thread_position_in_grid]]) { + if (i < a.count) y[i] = x[i]; +} +kernel void tf_ink2_copy_f32(const device float* x [[buffer(0)]], device float* y [[buffer(1)]], constant InkRuntimeArgs& a [[buffer(2)]], uint i [[thread_position_in_grid]]) { + if (i < a.count) y[i] = x[i]; +} +kernel void tf_ink2_widen(const device bfloat* x [[buffer(0)]], device float* y [[buffer(1)]], constant InkRuntimeArgs& a [[buffer(2)]], uint i [[thread_position_in_grid]]) { + if (i < a.count) y[i] = float(x[i]); +} +kernel void tf_ink2_attention_partial(const device bfloat* p [[buffer(0)]], const device bfloat* x [[buffer(1)]], device bfloat* blocks [[buffer(2)]], device float* t [[buffer(3)]], constant InkRuntimeArgs& a [[buffer(4)]], uint i [[thread_position_in_grid]]) { + if (i >= a.count) return; + const uint row = i / 2304, d = i % 2304; + t[i] = a.boundary ? float(x[i]) : float(p[i]) + float(x[i]); + if (a.boundary) blocks[row * 4 * 2304 + (a.boundary - 1) * 2304 + d] = p[i]; +} +kernel void tf_ink2_mlp_partial(const device float* t [[buffer(0)]], const device bfloat* x [[buffer(1)]], device bfloat* p [[buffer(2)]], constant InkRuntimeArgs& a [[buffer(3)]], uint i [[thread_position_in_grid]]) { + if (i < a.count) p[i] = bfloat(t[i] + float(x[i])); +} + +kernel void tf_ink2_capture_tap(const device bfloat* x [[buffer(0)]], device bfloat* y [[buffer(1)]], constant InkRuntimeArgs& a [[buffer(2)]], uint i [[thread_position_in_grid]]) { + if (i >= a.count) return; + const uint row = i / 2304, d = i % 2304; + y[row * 4 * 2304 + a.boundary * 2304 + d] = x[i]; +} diff --git a/zig/kernels/metal/inkling2/runtime_sources.zig b/zig/kernels/metal/inkling2/runtime_sources.zig new file mode 100644 index 00000000000..e987c44855e --- /dev/null +++ b/zig/kernels/metal/inkling2/runtime_sources.zig @@ -0,0 +1,2 @@ +//! Inkling 2 Mini's copy, widening and partial-residual shaders. +pub const runtime = @embedFile("runtime.metal"); diff --git a/zig/kernels/metal/inkling2_sources.zig b/zig/kernels/metal/inkling2_sources.zig new file mode 100644 index 00000000000..f105ac0f3a2 --- /dev/null +++ b/zig/kernels/metal/inkling2_sources.zig @@ -0,0 +1,10 @@ +//! Mini Metal shaders for the family and kernel contract, rooted beside nax.h for prompt-header package scope. + +pub const attention = @import("inkling2/attention_sources.zig").attention; +pub const prompt_attention = @import("inkling2/attention_sources.zig").prompt_attention; +pub const prompt_attention_pre_m5 = @import("inkling2/attention_sources.zig").prompt_attention_pre_m5; +pub const glue = @import("inkling2/glue_sources.zig").glue; +pub const experts = @import("inkling2/experts_sources.zig").experts; +pub const loop = @import("inkling2/loop_sources.zig").loop; +pub const runtime = @import("inkling2/runtime_sources.zig").runtime; +pub const inkling2_dspark = @import("inkling2/dspark_sources.zig").dspark; diff --git a/zig/kernels/metal/lfm2/prompt_masked.zig b/zig/kernels/metal/lfm2/prompt_masked.zig index 1e9ca129170..e3cf9bc3900 100644 --- a/zig/kernels/metal/lfm2/prompt_masked.zig +++ b/zig/kernels/metal/lfm2/prompt_masked.zig @@ -7,7 +7,7 @@ pub const source = blk: { var body = edit(original[begin..], "void lfm2_attn_nax(", "void lfm2_attn_masked("); body = edit(body, "mma_16x32(o[0], o[1], pb[h], v0, v1);", "lfm2_masked_pv(o[0], o[1], pb[h], v0, v1, home, j0 + 16 * h, count0, count1);"); body = edit(body, "mma_16x32(o[2], o[3], pb[h], v2, v3);", "lfm2_masked_pv(o[2], o[3], pb[h], v2, v3, home, j0 + 16 * h, count0, count1);"); - break :blk original ++ @embedFile("prompt_masked.h") ++ "[[max_total_threads_per_threadgroup(128)]]\n" ++ body ++ @embedFile("prompt_pick.metal"); + break :blk original ++ @embedFile("prompt_masked.h") ++ "[[max_total_threads_per_threadgroup(128)]]\n" ++ body ++ @embedFile("../core/prompt_pick.metal") ++ @embedFile("prompt_pick.metal"); }; fn edit(comptime text: []const u8, comptime from: []const u8, comptime to: []const u8) []const u8 { if (std.mem.count(u8, text, from) != 1) @compileError("LFM2 masked prompt source no longer matches"); diff --git a/zig/kernels/metal/lfm2/prompt_pick.metal b/zig/kernels/metal/lfm2/prompt_pick.metal index 90269747f54..20c5db180b6 100644 --- a/zig/kernels/metal/lfm2/prompt_pick.metal +++ b/zig/kernels/metal/lfm2/prompt_pick.metal @@ -12,9 +12,4 @@ if (simd_any(exceptional) && tid % 32 == 0) atomic_fetch_or_explicit(flag, 1u, memory_order_relaxed); } [[max_total_threads_per_threadgroup(1)]] -[[kernel]] void lfm2_prompt_pick(device atomic_uint* flag [[buffer(0)]], constant uint* grid [[buffer(1)]], - device uint* grids [[buffer(2)]]) { - const bool masked = atomic_load_explicit(flag, memory_order_relaxed) != 0; - atomic_store_explicit(flag, 0u, memory_order_relaxed); - for (uint i = 0; i < 3; i++) { grids[i] = masked ? 0u : grid[i]; grids[3 + i] = masked ? grid[i] : 0u; } -} +TF_PROMPT_PICK(lfm2_prompt_pick) diff --git a/zig/kernels/metal/nemotron/prompt_masked.zig b/zig/kernels/metal/nemotron/prompt_masked.zig index 59b86a49e26..6676a638cff 100644 --- a/zig/kernels/metal/nemotron/prompt_masked.zig +++ b/zig/kernels/metal/nemotron/prompt_masked.zig @@ -3,7 +3,7 @@ const std = @import("std"); const paged = @import("paged.zig"); pub const original = @embedFile("../prefill/attention_nax.metal"); const helpers = @embedFile("prompt_masked.h"); -const picker = @embedFile("prompt_pick.metal"); +const picker = @embedFile("../core/prompt_pick.metal") ++ @embedFile("prompt_pick.metal"); pub const tags = paged.prefill_tags; fn edit(comptime text: []const u8, comptime from: []const u8, comptime to: []const u8, comptime count: usize) []const u8 { diff --git a/zig/kernels/metal/nemotron/prompt_pick.metal b/zig/kernels/metal/nemotron/prompt_pick.metal index 7b0d37d83b9..a536cc3a1d1 100644 --- a/zig/kernels/metal/nemotron/prompt_pick.metal +++ b/zig/kernels/metal/nemotron/prompt_pick.metal @@ -15,9 +15,4 @@ } [[max_total_threads_per_threadgroup(1)]] -[[kernel]] void nemotron_prompt_pick(device atomic_uint* flag [[buffer(0)]], constant uint* grid [[buffer(1)]], - device uint* grids [[buffer(2)]]) { - const bool masked = atomic_load_explicit(flag, memory_order_relaxed) != 0; - atomic_store_explicit(flag, 0u, memory_order_relaxed); - for (int i = 0; i < 3; i++) { grids[i] = masked ? 0u : grid[i]; grids[3 + i] = masked ? grid[i] : 0u; } -} +TF_PROMPT_PICK(nemotron_prompt_pick) diff --git a/zig/kernels/metal/nemotron_expert_down.metal b/zig/kernels/metal/nemotron_expert_down.metal deleted file mode 100644 index 2380827429e..00000000000 --- a/zig/kernels/metal/nemotron_expert_down.metal +++ /dev/null @@ -1,84 +0,0 @@ -// Generated by tools/zig/gen_nemotron_metal.py from rows.py (down projection); do not edit. -#include -using namespace metal; -typedef bfloat bfloat16_t; -typedef half float16_t; - -inline float tf_load16(const device bfloat* x, thread float* xt) { - float sum = 0.0f; - for (int i = 0; i < 16; i += 4) { - const bfloat a = x[i], b = x[i + 1], c = x[i + 2], d = x[i + 3]; - sum += float(bfloat(float(bfloat(float(bfloat(float(a) + float(b))) + float(c))) + float(d))); - xt[i] = float(a); xt[i + 1] = float(b) / 16.0f; xt[i + 2] = float(c) / 256.0f; xt[i + 3] = float(d) / 4096.0f; - } - return sum; -} -inline float tf_qdot16(const device uint8_t* w, const thread float* xt, float scale, float bias, float sum) { - const device uint16_t* ws = (const device uint16_t*)w; - float accum = 0.0f; - for (int i = 0; i < 4; i++) - accum += (xt[4 * i] * (ws[i] & 0x000f) + xt[4 * i + 1] * (ws[i] & 0x00f0) + - xt[4 * i + 2] * (ws[i] & 0x0f00) + xt[4 * i + 3] * (ws[i] & 0xf000)); - return scale * accum + sum * bias; -} -template -inline void tf_rowdot(const device uint8_t* w, const device bfloat* sc, const device bfloat* bi, - const device bfloat* x, uint lane, thread float* acc) { - constexpr int KB = K / 2; - constexpr int KG = K / GS; - constexpr int FULL = K / 512 * 512; - w += lane * 8; - sc += lane / (GS / 16); - bi += lane / (GS / 16); - x += lane * 16; - for (int j = 0; j < RPS; j++) acc[j] = 0.0f; - for (int k0 = 0; k0 < FULL; k0 += 512) { - float xt[16]; - const float sum = tf_load16(x, xt); - for (int j = 0; j < RPS; j++) acc[j] += tf_qdot16(w + j * KB, xt, float(sc[j * KG]), float(bi[j * KG]), sum); - w += 256; sc += 512 / GS; bi += 512 / GS; x += 512; - } - if (FULL < K && int(lane) < (K - FULL) / 16) { - float xt[16]; - const float sum = tf_load16(x, xt); - for (int j = 0; j < RPS; j++) acc[j] += tf_qdot16(w + j * KB, xt, float(sc[j * KG]), float(bi[j * KG]), sum); - } - for (int j = 0; j < RPS; j++) acc[j] = simd_sum(acc[j]); -} -template -[[kernel]] void custom_kernel_nemotron_rows_expert_down_7cd919f2cf068abd__1856_2688_64_4_2_bfloat16_t_uint32_t_int32_t_int32_t_int32_t_int32_tc_uint32_t_bfloat16_t_bfloat16_t_bfloat16_t( - const device bfloat16_t* X [[buffer(0)]], - const device uint32_t* UIDS [[buffer(1)]], - const device int32_t* START [[buffer(2)]], - const device int32_t* COUNT [[buffer(3)]], - const device int32_t* MEMBERS [[buffer(4)]], - const constant int32_t* UCOUNT [[buffer(5)]], - const device uint32_t* W [[buffer(6)]], - const device bfloat16_t* S [[buffer(7)]], - const device bfloat16_t* B [[buffer(8)]], - device bfloat16_t* Y [[buffer(9)]], - uint simdgroup_index_in_threadgroup [[simdgroup_index_in_threadgroup]], - uint thread_index_in_simdgroup [[thread_index_in_simdgroup]], - uint3 threadgroup_position_in_grid [[threadgroup_position_in_grid]]) { - - const uint lane = thread_index_in_simdgroup; - const int u = int(threadgroup_position_in_grid.z); - if (u >= UCOUNT[0]) return; - const size_t e = size_t(UIDS[u]); - const int row0 = (int(threadgroup_position_in_grid.y) * SG + int(simdgroup_index_in_threadgroup)) * RPS; - const size_t at = e * N + size_t(row0); - const int first = START[u], last = START[u] + COUNT[u]; - - #pragma clang loop unroll(disable) - for (int m = first; m < last; m++) { - const int p = MEMBERS[m]; - float acc[RPS]; - tf_rowdot((const device uint8_t*)W + at * (K / 2), S + at * (K / GS), B + at * (K / GS), - X + size_t(p) * K, lane, acc); - if (lane == 0) - for (int j = 0; j < RPS; j++) Y[size_t(p) * N + row0 + j] = bfloat(acc[j]); - } - -} - -template [[host_name("custom_kernel_nemotron_rows_expert_down_7cd919f2cf068abd__1856_2688_64_4_2_bfloat16_t_uint32_t_int32_t_int32_t_int32_t_int32_tc_uint32_t_bfloat16_t_bfloat16_t_bfloat16_t")]] [[kernel]] decltype(custom_kernel_nemotron_rows_expert_down_7cd919f2cf068abd__1856_2688_64_4_2_bfloat16_t_uint32_t_int32_t_int32_t_int32_t_int32_tc_uint32_t_bfloat16_t_bfloat16_t_bfloat16_t<1856, 2688, 64, 4, 2>) custom_kernel_nemotron_rows_expert_down_7cd919f2cf068abd__1856_2688_64_4_2_bfloat16_t_uint32_t_int32_t_int32_t_int32_t_int32_tc_uint32_t_bfloat16_t_bfloat16_t_bfloat16_t<1856, 2688, 64, 4, 2>; diff --git a/zig/kernels/metal/nemotron_expert_up.metal b/zig/kernels/metal/nemotron_expert_up.metal deleted file mode 100644 index 9d04d09bc63..00000000000 --- a/zig/kernels/metal/nemotron_expert_up.metal +++ /dev/null @@ -1,87 +0,0 @@ -// Generated by tools/zig/gen_nemotron_metal.py from rows.py (up projection); do not edit. -#include -using namespace metal; -typedef bfloat bfloat16_t; -typedef half float16_t; - -inline float tf_load16(const device bfloat* x, thread float* xt) { - float sum = 0.0f; - for (int i = 0; i < 16; i += 4) { - const bfloat a = x[i], b = x[i + 1], c = x[i + 2], d = x[i + 3]; - sum += float(bfloat(float(bfloat(float(bfloat(float(a) + float(b))) + float(c))) + float(d))); - xt[i] = float(a); xt[i + 1] = float(b) / 16.0f; xt[i + 2] = float(c) / 256.0f; xt[i + 3] = float(d) / 4096.0f; - } - return sum; -} -inline float tf_qdot16(const device uint8_t* w, const thread float* xt, float scale, float bias, float sum) { - const device uint16_t* ws = (const device uint16_t*)w; - float accum = 0.0f; - for (int i = 0; i < 4; i++) - accum += (xt[4 * i] * (ws[i] & 0x000f) + xt[4 * i + 1] * (ws[i] & 0x00f0) + - xt[4 * i + 2] * (ws[i] & 0x0f00) + xt[4 * i + 3] * (ws[i] & 0xf000)); - return scale * accum + sum * bias; -} -template -inline void tf_rowdot(const device uint8_t* w, const device bfloat* sc, const device bfloat* bi, - const device bfloat* x, uint lane, thread float* acc) { - constexpr int KB = K / 2; - constexpr int KG = K / GS; - constexpr int FULL = K / 512 * 512; - w += lane * 8; - sc += lane / (GS / 16); - bi += lane / (GS / 16); - x += lane * 16; - for (int j = 0; j < RPS; j++) acc[j] = 0.0f; - for (int k0 = 0; k0 < FULL; k0 += 512) { - float xt[16]; - const float sum = tf_load16(x, xt); - for (int j = 0; j < RPS; j++) acc[j] += tf_qdot16(w + j * KB, xt, float(sc[j * KG]), float(bi[j * KG]), sum); - w += 256; sc += 512 / GS; bi += 512 / GS; x += 512; - } - if (FULL < K && int(lane) < (K - FULL) / 16) { - float xt[16]; - const float sum = tf_load16(x, xt); - for (int j = 0; j < RPS; j++) acc[j] += tf_qdot16(w + j * KB, xt, float(sc[j * KG]), float(bi[j * KG]), sum); - } - for (int j = 0; j < RPS; j++) acc[j] = simd_sum(acc[j]); -} -template -[[kernel]] void custom_kernel_nemotron_rows_expert_up_3c904b6b27dccc2b__2688_1856_64_4_2_6_bfloat16_t_uint32_t_int32_t_int32_t_int32_t_int32_tc_uint32_t_bfloat16_t_bfloat16_t_bfloat16_t( - const device bfloat16_t* X [[buffer(0)]], - const device uint32_t* UIDS [[buffer(1)]], - const device int32_t* START [[buffer(2)]], - const device int32_t* COUNT [[buffer(3)]], - const device int32_t* MEMBERS [[buffer(4)]], - const constant int32_t* UCOUNT [[buffer(5)]], - const device uint32_t* W [[buffer(6)]], - const device bfloat16_t* S [[buffer(7)]], - const device bfloat16_t* B [[buffer(8)]], - device bfloat16_t* ACT [[buffer(9)]], - uint simdgroup_index_in_threadgroup [[simdgroup_index_in_threadgroup]], - uint thread_index_in_simdgroup [[thread_index_in_simdgroup]], - uint3 threadgroup_position_in_grid [[threadgroup_position_in_grid]]) { - - const uint lane = thread_index_in_simdgroup; - const int u = int(threadgroup_position_in_grid.z); - if (u >= UCOUNT[0]) return; - const size_t e = size_t(UIDS[u]); - const int row0 = (int(threadgroup_position_in_grid.y) * SG + int(simdgroup_index_in_threadgroup)) * RPS; - const size_t at = e * N + size_t(row0); - const int first = START[u], last = START[u] + COUNT[u]; - - #pragma clang loop unroll(disable) - for (int m = first; m < last; m++) { - const int p = MEMBERS[m]; - float acc[RPS]; - tf_rowdot((const device uint8_t*)W + at * (K / 2), S + at * (K / GS), B + at * (K / GS), - X + size_t(p / TOPK) * K, lane, acc); - if (lane == 0) - for (int j = 0; j < RPS; j++) { - const float h = metal::max(float(bfloat(acc[j])), 0.0f); - ACT[size_t(p) * N + row0 + j] = bfloat(h * h); - } - } - -} - -template [[host_name("custom_kernel_nemotron_rows_expert_up_3c904b6b27dccc2b__2688_1856_64_4_2_6_bfloat16_t_uint32_t_int32_t_int32_t_int32_t_int32_tc_uint32_t_bfloat16_t_bfloat16_t_bfloat16_t")]] [[kernel]] decltype(custom_kernel_nemotron_rows_expert_up_3c904b6b27dccc2b__2688_1856_64_4_2_6_bfloat16_t_uint32_t_int32_t_int32_t_int32_t_int32_tc_uint32_t_bfloat16_t_bfloat16_t_bfloat16_t<2688, 1856, 64, 4, 2, 6>) custom_kernel_nemotron_rows_expert_up_3c904b6b27dccc2b__2688_1856_64_4_2_6_bfloat16_t_uint32_t_int32_t_int32_t_int32_t_int32_tc_uint32_t_bfloat16_t_bfloat16_t_bfloat16_t<2688, 1856, 64, 4, 2, 6>; diff --git a/zig/kernels/metal/nemotron_glue.metal b/zig/kernels/metal/nemotron_glue.metal index 76f2967d9e1..1e16c8fb40c 100644 --- a/zig/kernels/metal/nemotron_glue.metal +++ b/zig/kernels/metal/nemotron_glue.metal @@ -163,11 +163,7 @@ kernel void tf_copy_rows(const device bfloat* src [[buffer(0)]], } // u32 values from one buffer to another (window ids into a shared round's ids): grid (n). -kernel void tf_copy_u32(const device uint* src [[buffer(0)]], - device uint* dst [[buffer(1)]], - uint i [[thread_position_in_grid]]) { - dst[i] = src[i]; -} +TF_COPY_U32(tf_copy_u32) // lane_qmm's split-K partials summed in slice order, as the coop kernel reduces, then rounded to bf16: grid (N, M). kernel void tf_coop_combine(const device float* part [[buffer(0)]], diff --git a/zig/kernels/metal/prefill/fn_prompt.metal b/zig/kernels/metal/prefill/fn_prompt.metal index ac5bc07b9f4..1a3a3849223 100644 --- a/zig/kernels/metal/prefill/fn_prompt.metal +++ b/zig/kernels/metal/prefill/fn_prompt.metal @@ -120,9 +120,7 @@ inline float pf_rinv(const device float* ssp, int r, int s, int nt, int streams, for (int i = 0; i < 8; i++) YD[(size_t(row) * SLOTS + k) * D + c + i] = DS[size_t(slot) * D + c + i]; } -[[kernel]] void pf_copy(const device uint* S [[buffer(0)]], device uint* T [[buffer(1)]], uint i [[thread_position_in_grid]]) { - T[i] = S[i]; -} +TF_COPY_U32(pf_copy) // DeltaNet prompt chunk in 3 launches (q4_gdn_step): conv/norms/gates, per-simdgroup recurrence, gated RMS norm. inline float pf_fsig(float x) { return 1.0f / (1.0f + metal::exp(-x)); } diff --git a/zig/kernels/metal/qwen27/attention_prompt.metal b/zig/kernels/metal/qwen27/attention_prompt.metal index 104c416a37d..e6a4015e027 100644 --- a/zig/kernels/metal/qwen27/attention_prompt.metal +++ b/zig/kernels/metal/qwen27/attention_prompt.metal @@ -207,12 +207,8 @@ kernel void q27_attn_prompt_scan(device const Q27AttnReadPtrs* caches [[buffer(0 if (simd_any(inf != 0) && lane == 0) atomic_fetch_or_explicit(flag, 1u, memory_order_relaxed); } -// The indirect grids: q27_attn_prompt's if the scan found nothing, else the masked kernel's; clears the flag. -kernel void q27_attn_prompt_pick(device atomic_uint* flag [[buffer(0)]], constant uint* grid [[buffer(1)]], device uint* grids [[buffer(2)]]) { - const bool masked = atomic_load_explicit(flag, memory_order_relaxed) != 0; - atomic_store_explicit(flag, 0u, memory_order_relaxed); - for (int i = 0; i < 3; i++) { grids[i] = masked ? 0u : grid[i]; grids[3 + i] = masked ? grid[i] : 0u; } -} +// The indirect grids: q27_attn_prompt's if the scan found nothing, else the masked kernel's (core/prompt_pick.metal). +TF_PROMPT_PICK(q27_attn_prompt_pick) // A packed row's chunks merged in key order, normalized and written as the row's head output. kernel void q27_attn_prompt_merge(device const float* PO [[buffer(0)]], device const float* PM [[buffer(1)]], device const float* PL [[buffer(2)]], diff --git a/zig/kernels/metal/qwen27/paged.zig b/zig/kernels/metal/qwen27/paged.zig index 19b29c1d074..d04d421cbd2 100644 --- a/zig/kernels/metal/qwen27/paged.zig +++ b/zig/kernels/metal/qwen27/paged.zig @@ -77,7 +77,7 @@ fn prompt(comptime text: []const u8) []const u8 { /// The prompt kernels and the scan picking between them: each scanned key's values through stream 0's table. pub const attention_prompt = blk: { - var s = prompt(@embedFile("attention_prompt.metal")); + var s = prompt(@embedFile("../core/prompt_pick.metal") ++ @embedFile("attention_prompt.metal")); s = edit(s, "caches[0].values + (int64_t)tg.x * args.value_stride;", "caches[0].values;", 1); s = edit(s, "(v + (int64_t)key * PD + lane * 8)", "(v + (int64_t)(tf_paged_row(caches[0].table, uint(key), caches[0].page_bytes, tg.x, PD) / 2) + lane * 8)", 1); break :blk s; diff --git a/zig/kernels/metal/sources.zig b/zig/kernels/metal/sources.zig index 3548e332f0c..d782e403730 100644 --- a/zig/kernels/metal/sources.zig +++ b/zig/kernels/metal/sources.zig @@ -1,5 +1,7 @@ //! Metal kernel sources the engine compiles at run time, embedded in the executable. +const std = @import("std"); + /// DeepSeek-V4.1's sources live beside their kernels: users say sources.dsv41.NAME. pub const dsv41 = @import("deepseek_v41/sources.zig"); @@ -36,6 +38,8 @@ pub const gemma4_glue = @embedFile("gemma4/glue.metal"); pub const gemma4_fused = @embedFile("gemma4/fused.metal"); /// Gemma 4 prompt attention on the tensor units (families/gemma4/kernels.zig). pub const gemma4_prompt_attention = @embedFile("gemma4/prompt_attention.metal"); +/// The u32 copy kernels' macros (core/copy_u32.metal), ahead of the glue that instantiates them. +pub const core_copy_u32 = @embedFile("core/copy_u32.metal"); /// The prefill GEMM template and its one kernel macro, ahead of every family's gemm_nax instantiations. const gemm_nax = @embedFile("prefill/gemm_nax.metal") ++ @embedFile("prefill/gemm_nax_kernel.metal"); /// gemm_nax and the image towers' shared glue: bf16 rounding, threadgroup sum and max, row softmax. @@ -56,7 +60,7 @@ pub const lfm3_projection_dual = @embedFile("lfm3/projectiondual.metal"); pub const lfm3_projection = @embedFile("lfm3/projection.metal"); /// Our glue kernels around them: embedding, MLX's RMS arithmetic, argmax, layout moves. -pub const nemotron_glue = @embedFile("nemotron_glue.metal"); +pub const nemotron_glue = core_copy_u32 ++ @embedFile("nemotron_glue.metal"); pub const core_row_projection = @embedFile("core/row_projection.metal"); pub const core_row_projection_legacy = @embedFile("core/row_projection_legacy.metal"); pub const core_binned_projection = @embedFile("core/binned_projection.metal"); @@ -106,7 +110,7 @@ pub const flashnext_qmm6 = @embedFile("prefill/qmm6_nax.metal") ++ @embedFile("p /// Flash Next's prompt products at any MLX width (WB and WG defined before it; nax.h inlined at load). pub const flashnext_qmmw = @embedFile("prefill/qmmw_nax.metal"); /// Flash Next prompt-chunk glue: hyper-connection pieces, router rows, top-k, the expert sort, gathers and scatters. -pub const flashnext_prompt = @embedFile("prefill/fn_prompt.metal"); +pub const flashnext_prompt = core_copy_u32 ++ @embedFile("prefill/fn_prompt.metal"); /// Flash Next block selection in GPU-side rounds: per-row metadata from the arena and pooling at absolute blocks. pub const flashnext_select = @embedFile("prefill/fn_select.metal"); /// Flash Next indexer pooling at an image stream's block positions (the standard frame on the shared sessions). @@ -155,7 +159,7 @@ pub const flashnext_gx_mb2 = @embedFile("decode/fn_gx_mb2.metal"); /// GLM-5.3-Flash's decode kernels from our Python family (tools/zig/gen_glm_kernels.py). pub const glm = @import("glm/kernels.zig"); /// GLM-5.3-Flash's glue: MLX's arithmetic where the Python family calls MLX ops; selection, argmax, small steps. -pub const glm_glue = @embedFile("glm_glue.metal"); +pub const glm_glue = core_copy_u32 ++ @embedFile("glm_glue.metal"); /// Its products at the widths the generated kernels do not read, after core_row_projection (glm/wide.zig). pub const glm_rows = @embedFile("glm_rows.metal"); pub const glm_gather = @embedFile("glm_gather.metal"); @@ -290,7 +294,13 @@ pub const drama3 = struct { pub const nvfp4 = @embedFile("drama3/nvfp4.metal"); pub const guidance = @embedFile("drama3/guidance.metal"); pub const sample = @embedFile("drama3/sample.metal"); - pub const codec = @embedFile("drama3/codec.metal"); + /// codec.metal with its core/copy_u32.metal include inlined, as the offline compiler reads it. + pub const codec = blk: { + const text = @embedFile("drama3/codec.metal"); + const include = "#include \"../core/copy_u32.metal\"\n"; + const at = std.mem.indexOf(u8, text, include).?; + break :blk text[0..at] ++ core_copy_u32 ++ text[at + include.len ..]; + }; }; pub const core_weight_only_body = @embedFile("core/weight_only.h"); @@ -311,3 +321,6 @@ pub const glm_draft_topk = @embedFile("glm_draft_topk.metal"); pub const glm_draft_accept = @embedFile("glm_draft_accept.metal"); /// GLM-5.3-Flash's DFlash2 inline follow: copies accepted tap rows into the drafter ring ahead of its block. pub const glm_draft_follow = @embedFile("glm_draft_follow.metal"); + +/// Inkling 2 Mini's runtime helpers, the exact source compiled by its model and kernel contract. +pub const inkling2_runtime = @embedFile("inkling2/runtime.metal"); diff --git a/zig/metal_cost_compile.zig b/zig/metal_cost_compile.zig new file mode 100644 index 00000000000..e28ed5fe631 --- /dev/null +++ b/zig/metal_cost_compile.zig @@ -0,0 +1,17 @@ +//! Force every native timing branch to compile; this object never executes or links Metal. +const std = @import("std"); +const tf = @import("tensorfold"); +const qwen = @import("src/native/qwen27_lanes.zig"); + +export fn qwenCostCompile(b: *qwen.Metal, io: *std.Io) u8 { + @import("src/native/qwen27_costs.zig").measure(b, io.*) catch return 1; + return 0; +} +export fn nemoCostCompile(b: *tf.nemotron.backend.Metal, io: *std.Io) u8 { + tf.nemotron.timing.measure(b, io.*) catch return 1; + return 0; +} +export fn glmCostCompile(sl: *tf.glm.slots.Slots, gpa: *std.mem.Allocator, io: *std.Io) u8 { + _ = tf.glm.timing.measure(sl, gpa.*, io.*) catch return 1; + return 0; +} diff --git a/zig/nemotron_metal_timing_host.zig b/zig/nemotron_metal_timing_host.zig new file mode 100644 index 00000000000..a3f5e04236d --- /dev/null +++ b/zig/nemotron_metal_timing_host.zig @@ -0,0 +1,4 @@ +//! Actual family timing policies with host recording clocks. +test { + _ = @import("src/families/nemotron/timing.zig"); +} diff --git a/zig/qwen27_core.zig b/zig/qwen27_core.zig index 916ceeaa248..d0c8ab7ec66 100644 --- a/zig/qwen27_core.zig +++ b/zig/qwen27_core.zig @@ -3,6 +3,8 @@ pub const checkpoint = @import("src/core/checkpoint.zig"); pub const gguf = @import("src/core/gguf.zig"); pub const checkpoint_metal = @import("src/core/checkpoint_metal.zig"); pub const safetensors = @import("src/core/safetensors.zig"); +/// The shard file cache checkpoint_metal.zig reaches through `core`, as the engine's own core exports it. +pub const checkpoint_file_cache = @import("src/core/checkpoint_file_cache.zig"); pub const Checkpoint = checkpoint.Checkpoint; pub const npy = @import("src/core/npy.zig"); pub const tokenizer = @import("tokenizer"); @@ -11,6 +13,8 @@ pub const qwen_vl = @import("src/core/qwen_vl/qwen_vl.zig"); pub const segments = @import("src/core/segments.zig"); pub const prompt_tail = @import("src/core/prompt_tail.zig"); +/// Staged references: the qwen3_5 forward's stages and their on-disk layout (tools/zig/qwen36_stage_ref.py). +pub const qwen35_stages = @import("src/families/qwen3_5/stages.zig"); pub const checkpoint_host = checkpoint; pub const lane_projection = @import("core_lane"); diff --git a/zig/qwen27_quant_test.zig b/zig/qwen27_quant_test.zig index a5b361c5d0a..ede401d1407 100644 --- a/zig/qwen27_quant_test.zig +++ b/zig/qwen27_quant_test.zig @@ -134,7 +134,7 @@ test "qwen27 quant: preparation skips projections that cannot take a decode lane } const wide_formats = [_]lane_projection.Format{ - .{ .bits = 8, .group = 64 }, .{ .bits = 6, .group = 32 }, .{ .bits = 5, .group = 64 }, + .{ .bits = 8, .group = 64 }, .{ .bits = 6, .group = 32 }, .{ .bits = 5, .group = 32 }, .{ .bits = 3, .group = 32 }, .{ .bits = 2, .group = 64 }, .{ .bits = 8, .group = 128 }, }; @@ -189,10 +189,17 @@ test "qwen27 quant: each non-reg whole prompt is one projection dispatch" { k.long_prompt = false; r.count = 0; try k.quant(r.encoder(), p, ref, producer, ref, ref, 2048); - try t.expectEqual(@as(usize, 128), r.count); - for (r.launches[0..r.count]) |call| { - try t.expectEqual(@as(u32, 16), call.rows); - try t.expectEqual(@as(usize, 1), call.grid.height); + // Tensor units take the row blocks a dispatch at every width; elsewhere 16 rows a dispatch. + if (r.device().tensorUnits()) { + try t.expectEqual(@as(usize, 1), r.count); + try t.expectEqual(@as(u32, 2048), r.launches[0].rows); + try t.expectEqual(@as(usize, (2048 + 15) / 16), r.launches[0].grid.height); + } else { + try t.expectEqual(@as(usize, 128), r.count); + for (r.launches[0..r.count]) |call| { + try t.expectEqual(@as(u32, 16), call.rows); + try t.expectEqual(@as(usize, 1), call.grid.height); + } } }; } @@ -352,3 +359,27 @@ test "qwen27 quant: norm and MLP compile XS only on tensor units and pad only it try t.expectEqual(@as(u32, 6), k.cache.count()); try t.expectEqual(@as(usize, 6), r.libraries); } + +test "qwen27 quant: 5-bit and 6-bit g64 use reg lane keys with 128/2048 row capacity and producer sums" { + for ([_]u8{ 5, 6 }) |bits| { + var r: mtl.Record = .{}; + var k = quant.Kernels{ .allocator = a, .device = r.device(), .long_prompt = true }; + defer k.deinit(); + var p = matrix(&r, 64); + p.bits = bits; + p.group = 64; + const ref = quant.Ref{ .buffer = r.virtual() }; + const sums: quant.Sums = .{ .ref = ref, .stride = 2080 }; + try k.prepareDecode(p); + try k.quant(r.encoder(), p, ref, sums, ref, ref, 128); + try t.expectEqual(@as(usize, 1), r.count); + try t.expectEqual(@as(u32, 128), r.launches[0].rows); + try t.expectEqual(@as(i32, 2080), r.launches[0].stride); + k.prompt = true; + r.count = 0; + try k.quant(r.encoder(), p, ref, sums, ref, ref, 2048); + try t.expectEqual(@as(usize, 1), r.count); + try t.expectEqual(@as(u32, 2048), r.launches[0].rows); + try t.expectEqual(@as(u32, 2), k.lanes.count()); + } +} diff --git a/zig/qwen27_speed_core.zig b/zig/qwen27_speed_core.zig index 49c70e2b9bc..152e6892abd 100644 --- a/zig/qwen27_speed_core.zig +++ b/zig/qwen27_speed_core.zig @@ -3,6 +3,7 @@ pub const tree_slots = @import("src/core/tree_slots.zig"); pub const recurrent_workspace = @import("src/core/recurrent_workspace.zig"); pub const gpu_profile = @import("src/core/gpu_profile.zig"); pub const checkpoint_host = @import("src/core/checkpoint.zig"); +pub const qwen35_stages = @import("src/families/qwen3_5/stages.zig"); pub const draft_ops = struct { pub const Ref = struct { buf: @import("metal").Buffer, off: usize = 0 }; diff --git a/zig/qwen35_draft_frame_host.zig b/zig/qwen35_draft_frame_host.zig index c3f042015df..0a0be850906 100644 --- a/zig/qwen35_draft_frame_host.zig +++ b/zig/qwen35_draft_frame_host.zig @@ -276,6 +276,7 @@ fn actualFrame(block: usize) !void { test { _ = @import("qwen35_draft_equality.zig"); + _ = @import("qwen35_draft_graphs_host.zig"); } test "Draft frames: combined target rows above capacity refuse before even settling an earlier round" { @@ -395,3 +396,47 @@ test "Draft frames: an EXL3 head's span views plan their K split as the whole he try std.testing.expect(F.x3_tail_at <= 248032 and F.x3_tail_at + v.tail.n == w.n); } } + +test "Draft frames: a ModelOpt head's span views read the whole head's tiles on its K slices" { + const Q = cuda.qmmf; + const S = q.draft.frame.ql_span; + const n = 248320; + const k = 5120; + const kg = k / 64; + const fp4 = cuda.nvfp4.weight(0x10000, 0x8000000000, 2.5, n, k); + const fp8 = cuda.modelopt.fp8Weight(0x10000, 0.5, n, k); + for ([_]cuda.qlinear.Weight{ .{ .nvfp4 = fp4 }, .{ .fp8 = fp8 } }) |w| { + const whole = switch (w) { + .nvfp4, .fp8 => |x| x, + else => unreachable, + }; + const v = S.views(w, 98304, 248000, n).?; + const first = switch (v.first) { + .nvfp4, .fp8 => |x| x, + else => unreachable, + }; + const tail = switch (v.tail) { + .nvfp4, .fp8 => |x| x, + else => unreachable, + }; + const bytes: usize = if (whole.mode == .fp4) 64 * 64 / 2 else 64 * 64; + for (0..tail.n / 64) |t| for (0..kg) |g| { + try std.testing.expectEqual(whole.codes + ((248000 / 64 + t) * kg + g) * bytes, tail.codes + (t * kg + g) * bytes); + if (whole.mode == .fp4) try std.testing.expectEqual(whole.scales + ((248000 / 64 + t) * kg + g) * 256, tail.scales + (t * kg + g) * 256); + }; + try std.testing.expectEqual(whole.codes, first.codes); + try std.testing.expectEqual(whole.scale, tail.scale); + for (1..Q.fused_rows) |m| for ([_]bool{ false, true }) |cl| { + try std.testing.expectEqual(Q.planFor(m, whole, cl), Q.planFor(m, first, cl)); + try std.testing.expectEqual(Q.planFor(m, whole, cl), Q.planFor(m, tail, cl)); + }; + } + try std.testing.expectEqual(@as(u32, 8), Q.splitK(320, k)); // unpinned, the tail would sum eight slices + var scaled = fp8; + scaled.act = 1.5; + try std.testing.expect(S.views(.{ .fp8 = scaled }, 98304, 248000, n) == null); + try std.testing.expect(S.views(.{ .bf16 = cuda.modelopt.bf16Weight(0x10000, n, k) }, 98304, 248000, n) == null); + try std.testing.expect(S.views(.{ .nvfp4 = fp4 }, 98304, 248032, n) == null); + try std.testing.expect(S.views(.{ .nvfp4 = cuda.nvfp4.weight(0x10000, 0x20000, 1, n - 64, k) }, 98304, 248000, n) == null); + try std.testing.expect(!S.enabled()); +} diff --git a/zig/qwen35_draft_graphs_host.zig b/zig/qwen35_draft_graphs_host.zig new file mode 100644 index 00000000000..5f9d60d53bb --- /dev/null +++ b/zig/qwen35_draft_graphs_host.zig @@ -0,0 +1,238 @@ +//! A recording driver compares DFlash2 graph replays with the eager launches, byte for byte, without a device. +const std = @import("std"); +const cuda = @import("cuda"); +const q = @import("qwen35"); +const T = std.testing; +const G = q.draft.graphs; +const abi = cuda.abi; + +const taps_id = 20; +const rope_id = 21; +const ring_id = 22; +const rows_id = 23; +const tap_rows_bytes = @sizeOf(q.draft.TapRows); + +const Call = struct { + f: usize, + geometry: [6]c_uint, + data: [512]u8 = @splat(0), + + fn of(f: abi.Function, geometry: [6]c_uint, args: ?[*]?*anyopaque) Call { + var c: Call = .{ .f = @intFromPtr(f), .geometry = geometry }; + const sizes: []const usize = switch (c.f) { + taps_id => &.{ 8, 4, 8, 4, 8 }, + rows_id => &.{ 8, 4, 8, tap_rows_bytes, 4, 8 }, + rope_id => &.{ 8, 8, 8, 4, 4, 8, 4, 4 }, + ring_id => &.{ 8, 8, 8, 8, 4, 8, 4 }, + else => &.{}, + }; + var at: usize = 0; + for (sizes, 0..) |n, i| { + @memcpy(c.data[at..][0..n], @as([*]const u8, @ptrCast(args.?[i].?))[0..n]); + at += n; + } + return c; + } +}; + +const Fake = struct { + var eager: [64]Call = undefined; + var eager_n: usize = 0; + var nodes: [64]Call = undefined; + var node_n: usize = 0; + var ran: [64]Call = undefined; + var ran_n: usize = 0; + var capturing = false; + var launches: usize = 0; + var exec_drops: usize = 0; + var refuse = false; + + fn reset() void { + eager_n = 0; + node_n = 0; + ran_n = 0; + capturing = false; + launches = 0; + exec_drops = 0; + refuse = false; + } + fn launch(f: abi.Function, x: c_uint, y: c_uint, z: c_uint, bx: c_uint, by: c_uint, bz: c_uint, _: c_uint, _: abi.Stream, args: ?[*]?*anyopaque, _: ?[*]?*anyopaque) callconv(.c) abi.Result { + const c = Call.of(f, .{ x, y, z, bx, by, bz }, args); + if (capturing) { + nodes[node_n] = c; + node_n += 1; + } else { + eager[eager_n] = c; + eager_n += 1; + } + return abi.success; + } + fn begin(_: abi.Stream, _: abi.CaptureMode) callconv(.c) abi.Result { + capturing = true; + node_n = 0; + return abi.success; + } + fn end(_: abi.Stream, g: *abi.Graph) callconv(.c) abi.Result { + capturing = false; + g.* = @ptrFromInt(1); + return abi.success; + } + fn getNodes(_: abi.Graph, out: ?[*]abi.GraphNode, n: *usize) callconv(.c) abi.Result { + if (out) |o| for (0..node_n) |i| { + o[i] = @ptrFromInt(i + 1); + }; + n.* = node_n; + return abi.success; + } + fn getParams(node: abi.GraphNode, p: *abi.KernelNodeParams) callconv(.c) abi.Result { + p.func = @ptrFromInt(nodes[@intFromPtr(node) - 1].f); + return abi.success; + } + fn instantiate(out: *abi.GraphExec, _: abi.Graph, _: u64) callconv(.c) abi.Result { + if (refuse) return 800; + out.* = @ptrFromInt(1); + return abi.success; + } + fn setParams(_: abi.GraphExec, node: abi.GraphNode, p: *const abi.KernelNodeParams) callconv(.c) abi.Result { + nodes[@intFromPtr(node) - 1] = Call.of(p.func, .{ p.grid_x, p.grid_y, p.grid_z, p.block_x, p.block_y, p.block_z }, p.params); + return abi.success; + } + fn graphLaunch(_: abi.GraphExec, _: abi.Stream) callconv(.c) abi.Result { + @memcpy(ran[0..node_n], nodes[0..node_n]); + ran_n = node_n; + launches += 1; + return abi.success; + } + fn dropExec(_: abi.GraphExec) callconv(.c) abi.Result { + exec_drops += 1; + return abi.success; + } + fn dropGraph(_: abi.Graph) callconv(.c) abi.Result { + return abi.success; + } +}; + +extern "c" fn setenv(name: [*:0]const u8, value: [*:0]const u8, overwrite: c_int) c_int; +extern "c" fn unsetenv(name: [*:0]const u8) c_int; + +fn function(d: *const cuda.Driver, id: usize) cuda.Function { + return .{ .d = d, .handle = @ptrFromInt(id) }; +} +fn weight() cuda.qlinear.Affine4 { + return .{ .w = 1, .s = 2, .b = 3, .n = 256, .k = 256, .npad = 256 }; +} +fn holdBody(d: anytype, streams: usize, contexts: []const *q.draft.Ctx) !?u64 { + _ = contexts; + try d.e.run(function(d.e.d, taps_id), .{ streams, 1, 1 }, .{ 256, 1, 1 }, .{ @as(u64, 7), @as(c_int, 1), @as(c_longlong, 2), @as(c_int, 3), @as(u64, 4) }); + return 0x5000; +} + +test "Draft frames: a DFlash2 graph replays the eager launches with this round's arguments" { + var driver: cuda.Driver = undefined; + driver.api.cuLaunchKernel = Fake.launch; + driver.api.cuStreamBeginCapture_v2 = Fake.begin; + driver.api.cuStreamEndCapture = Fake.end; + driver.api.cuGraphGetNodes = Fake.getNodes; + driver.api.cuGraphKernelNodeGetParams_v2 = Fake.getParams; + driver.api.cuGraphInstantiateWithFlags = Fake.instantiate; + driver.api.cuGraphExecKernelNodeSetParams_v2 = Fake.setParams; + driver.api.cuGraphLaunch = Fake.graphLaunch; + driver.api.cuGraphExecDestroy = Fake.dropExec; + driver.api.cuGraphDestroy = Fake.dropGraph; + var e: q.engine.Engine = undefined; + e.kit = null; + e.scratch_rows = q.engine.grid_rows; + e.d = &driver; + e.g.hidden = 256; + e.stream = .{ .d = &driver, .handle = null }; + e.learning = null; + e.pockets.layers = &.{}; + inline for (@typeInfo(@TypeOf(e.fns)).@"struct".field_names) |name| @field(e.fns, name) = function(&driver, 10); + e.affine = .{ + .group_fn = function(&driver, 10), + .mlp128_fn = function(&driver, 10), + .gemv_fn = function(&driver, 10), + .verify_fn = function(&driver, 10), + .verify64_fn = function(&driver, 10), + .verify128_fn = function(&driver, 10), + .split_fn = function(&driver, 10), + .seg_fn = function(&driver, 10), + .many_fn = function(&driver, 10), + .prefill_fn = function(&driver, 10), + .prefill22_fn = function(&driver, 10), + .prefill_many_fn = function(&driver, 10), + .words_fn = function(&driver, 10), + .scales_fn = function(&driver, 10), + .gemv_blocks = 0, + .split = null, + .pdl = false, + .wide_verify = false, + }; + var d: q.draft.Draft = undefined; + d.gpa = T.allocator; + d.e = &e; + d.projection_role = .proposal; + d.frame_streams = 1; + d.graphs = .{ .on = true }; + defer d.graphs.deinit(T.allocator); + d.c = .{ .hidden = 256, .intermediate = 256, .layers = 2, .vocab = 256, .heads = 2, .kv_heads = 1, .head_dim = 128, .block = 8, .mask = 255, .window = 2048, .group = 16, .rank = 2, .topk = 2, .eps = 1e-6, .theta = 10000000, .taps = @splat(0), .n_taps = 1 }; + inline for (@typeInfo(@TypeOf(d.fns)).@"struct".field_names) |name| @field(d.fns, name) = function(&driver, 10); + d.fns.gather_taps = function(&driver, taps_id); + d.fns.gather_rows = function(&driver, rows_id); + d.fns.norm_rope = function(&driver, rope_id); + d.fns.ring_put = function(&driver, ring_id); + var layer: @TypeOf(d.w.layers[0]) = undefined; + inline for (@typeInfo(@TypeOf(layer)).@"struct".field_names, @typeInfo(@TypeOf(layer)).@"struct".field_types) |name, F| { + @field(layer, name) = if (F == cuda.qlinear.Affine4) weight() else 1; + } + layer.k.n = 128; + layer.v.n = 128; + var pair = [2]@TypeOf(layer){ layer, layer }; + pair[1].k_norm = 2; + d.w.layers = &pair; + d.w.fc = weight(); + d.w.hidden_norm = 1; + const measured = try d.layout(false); + d.scratch = .{ .d = &driver, .ptr = 0x100000, .len = measured }; + _ = try d.layout(true); + var first: q.draft.Ctx = .{ .ring = .{ .d = &driver, .ptr = 0x400000, .len = 1 } }; + var later: q.draft.Ctx = .{ .ring = .{ .d = &driver, .ptr = 0x800000, .len = 1 } }; + try T.expect(setenv("TF_DFLASH_GRAPH", "1", 1) == 0); + defer _ = unsetenv("TF_DFLASH_GRAPH"); + const kept = [_]u32{ 0, 2, 3 }; + for ([_]?[]const u32{ null, &kept }) |rs| { + Fake.reset(); + try G.absorbRows(&d, &later, 0x9000, 4242, 3, rs); + const want = Fake.eager[0..Fake.eager_n]; + try T.expect(try G.absorb(&d, &first, 0x7000, 17, 3, rs, false)); + try T.expect(try G.absorb(&d, &later, 0x9000, 4242, 3, rs, false)); + try T.expectEqual(want.len, Fake.ran_n); + for (want, Fake.ran[0..Fake.ran_n]) |w, r| { + try T.expectEqual(w.f, r.f); + try T.expectEqualSlices(c_uint, &w.geometry, &r.geometry); + try T.expectEqualSlices(u8, &w.data, &r.data); + } + try T.expectEqual(@as(usize, 2), Fake.launches); + } + try T.expect(!try G.absorb(&d, &later, 0x9000, 1, 3, null, true)); + try T.expect(!try G.absorb(&d, &later, 0x9000, 1, 17, null, false)); + const contexts = [_]*q.draft.Ctx{&later}; + Fake.reset(); + try T.expectEqual(@as(?u64, 0x5000), try G.hold(&d, 1, &contexts, true, holdBody)); + try T.expectEqual(@as(usize, 0), Fake.eager_n); + try T.expectEqual(@as(?u64, 0x5000), try G.hold(&d, 1, &contexts, true, holdBody)); + try T.expectEqual(@as(usize, 1), Fake.node_n); + try T.expectEqual(@as(usize, 2), Fake.launches); + _ = try G.hold(&d, 1, &contexts, false, holdBody); + try T.expectEqual(@as(usize, 2), d.graphs.holds.count()); + d.graphs.clear(T.allocator); + try T.expectEqual(@as(usize, 4), Fake.exec_drops); // two holds and both absorb variants + try T.expectEqual(@as(usize, 0), d.graphs.holds.count() + d.graphs.absorbs.count()); + Fake.refuse = true; + try T.expect(!try G.absorb(&d, &later, 0x9000, 5, 3, null, false)); + try T.expect(!d.graphs.on); + try T.expectEqual(@as(usize, 0), d.graphs.absorbs.count()); + Fake.reset(); + try T.expectEqual(@as(?u64, 0x5000), try G.hold(&d, 1, &contexts, true, holdBody)); + try T.expectEqual(@as(usize, 1), Fake.eager_n); // off after a refusal: the kernels run eagerly +} diff --git a/zig/qwen35_layers_host.zig b/zig/qwen35_layers_host.zig index b55030b5723..90e5047f6e4 100644 --- a/zig/qwen35_layers_host.zig +++ b/zig/qwen35_layers_host.zig @@ -179,7 +179,7 @@ const sources = .{ .{ "src/families/qwen3_5/cuda_modelopt.zig", 1 }, .{ "src/families/qwen3_5/cuda_quant_admission_test.zig", 1 }, .{ "src/families/qwen3_5/pocket_shards_test.zig", 1 }, - .{ "src/families/qwen27/config_test.zig", 2 }, // with #1125's Ornith-1.5-122B (qwen3_5_moe) + .{ "src/families/qwen27/config_test.zig", 3 }, // with #1125's Ornith-1.5-122B and Qwen3.6-35B-A3B (qwen3_5_moe) .{ "src/families/qwen27/weights_test.zig", 1 }, .{ "qwen35_formats_host.zig", 1 }, }; @@ -248,6 +248,31 @@ fn config(a: std.mem.Allocator, file: []const u8, text: []const u8) !?Real { return .{ .file = file, .json = try a.dupe(u8, text), .tower = tower, .layers = @intCast(n.integer) }; } +/// Qwen3.6-35B-A3B's config (qwen27/config_test.zig's `a3b_json`): 40 layers over a 2,048 hidden width. +pub fn a3b(a: std.mem.Allocator) !Real { + for (try reals(a)) |r| if (r.layers == 40 and r.tower.get("hidden_size").?.integer == 2048) return r; + return error.NoA3bConfig; +} + +test "qwen35 layers: Qwen3.6-35B-A3B, every fourth of 40 through Metal's 27B and HIP, refused by the others" { + var arena: std.heap.ArenaAllocator = .init(t.allocator); + defer arena.deinit(); + const r = try a3b(arena.allocator()); + const want = std.EnumArray(Backend, Outcome).init(.{ + .metal27 = .every(4, 40), + .hip = .every(4, 40), + .metal2b = .{ .refused = error.UnsupportedQwenConfig }, + .cuda = .{ .refused = error.UnsupportedActivation }, + .xpu = .{ .refused = error.UnsupportedQwenShape }, + }); + for (std.enums.values(Backend)) |b| { + const now = entry(b, r.json); + errdefer std.debug.print("{s}: {any}\n", .{ @tagName(b), now }); + const w = want.get(b); + if (w == .pattern) try t.expect(Outcome.same(w, now)) else try t.expect(now == .refused and now.refused == w.refused); + } +} + test "qwen35 layers: real configs, each entry point admits the pattern its old rule read, by the shared reader" { var arena: std.heap.ArenaAllocator = .init(t.allocator); defer arena.deinit(); @@ -267,7 +292,7 @@ test "qwen35 layers: real configs, each entry point admits the pattern its old r relaxed += @intFromBool(now == .pattern and was == .refused); } } - try t.expectEqual(@as(usize, 21), admitted); // (config, backend) pairs, with #2046's and LightOnOCR-3's HIP BF16 and #1125's Ornith + try t.expectEqual(@as(usize, 23), admitted); // (config, backend) pairs, with #2046's and LightOnOCR-3's HIP BF16, #1125's Ornith and the 35B-A3B try t.expectEqual(@as(usize, 0), relaxed); // none of the repo's configs is one the table newly admits } diff --git a/zig/qwen35_modelopt_host.zig b/zig/qwen35_modelopt_host.zig index b88c5c0b405..75622239102 100644 --- a/zig/qwen35_modelopt_host.zig +++ b/zig/qwen35_modelopt_host.zig @@ -67,15 +67,45 @@ test "CT admission: small real index config and safetensors preserve mixed store const cuda = @import("cuda"); const Engine = @import("src/families/qwen3_5/cuda_engine.zig").Engine; const Recorded = struct { + const Call = struct { + id: usize, + grid: u32, + input: u64, + rows: c_int, + k: c_int, + segs: cuda.qmmf_group.Segs, + }; var count: usize = 0; var id: usize = 0; var input: u64 = 0; - fn launch(f: cuda.abi.Function, _: c_uint, _: c_uint, _: c_uint, _: c_uint, _: c_uint, _: c_uint, _: c_uint, _: cuda.abi.Stream, args: ?[*]?*anyopaque, _: ?[*]?*anyopaque) callconv(.c) cuda.abi.Result { + var calls: [8]Call = undefined; + fn record(f: cuda.abi.Function, grid: c_uint, args: ?[*]?*anyopaque) cuda.abi.Result { + const call_id = @intFromPtr(f); + const call_input = @as(*const u64, @ptrCast(@alignCast(args.?[0].?))).*; + calls[count] = .{ + .id = call_id, + .grid = grid, + .input = call_input, + .rows = 0, + .k = 0, + .segs = std.mem.zeroes(cuda.qmmf_group.Segs), + }; + if (call_id == 10 or call_id == 11) { + calls[count].segs = @as(*const cuda.qmmf_group.Segs, @ptrCast(@alignCast(args.?[1].?))).*; + calls[count].rows = @as(*const c_int, @ptrCast(@alignCast(args.?[2].?))).*; + calls[count].k = @as(*const c_int, @ptrCast(@alignCast(args.?[3].?))).*; + } count += 1; - id = @intFromPtr(f); - input = @as(*const u64, @ptrCast(@alignCast(args.?[0].?))).*; + id = call_id; + input = call_input; return 0; } + fn launch(f: cuda.abi.Function, gx: c_uint, _: c_uint, _: c_uint, _: c_uint, _: c_uint, _: c_uint, _: c_uint, _: cuda.abi.Stream, args: ?[*]?*anyopaque, _: ?[*]?*anyopaque) callconv(.c) cuda.abi.Result { + return record(f, gx, args); + } + fn launchEx(c: *const cuda.abi.LaunchConfig, f: cuda.abi.Function, args: ?[*]?*anyopaque, _: ?[*]?*anyopaque) callconv(.c) cuda.abi.Result { + return record(f, c.grid_x, args); + } fn copy(_: u64, _: ?*const anyopaque, _: usize) callconv(.c) cuda.abi.Result { return 0; } @@ -88,6 +118,7 @@ fn function(d: *const cuda.Driver, id: usize) cuda.Function { } fn fullKernels(d: *cuda.Driver) modelopt.Kernels { d.api.cuLaunchKernel = Recorded.launch; + d.api.cuLaunchKernelEx = Recorded.launchEx; d.api.cuMemcpyHtoD_v2 = Recorded.copy; d.api.cuStreamSynchronize = Recorded.sync; var out: modelopt.Kernels = .{ .lane = undefined, .prompt = undefined, .pack = undefined, .embed = undefined }; @@ -201,6 +232,86 @@ fn projection(mode: cuda.qmmf.Mode, n: u32, k: u32) @import("src/families/qwen3_ } }; } +test "full mode: production mixed GDN dispatch makes two grouped launches" { + var d: cuda.Driver = undefined; + var e: Engine = undefined; + e.d = &d; + e.stream = .{ .d = &d, .handle = null }; + e.kit = null; + e.int8 = .{}; + e.affine.split = null; + e.affine.pdl = false; + e.xs = 0; + e.tables.ptr = 0; + e.mo = fullKernels(&d); + e.mo.?.lane.clusters = true; + e.mo.?.lane.pdl = false; + e.mo.?.lane.fuse_split_n = 0; + e.mo.?.lane.half_below = cuda.qmmf.half_below_default; + var grouped: cuda.qmmf_group.Group = .{ .fns = undefined }; + for (&grouped.fns) |*set| for (set) |*f| { + f.* = function(&d, 2); + }; + grouped.fns[1][1] = function(&d, 10); + grouped.fns[3][1] = function(&d, 11); + e.mo.?.group = grouped; + var ls = [4]@import("src/families/qwen3_5/cuda_engine.zig").Proj{ + projection(.fp8, 10240, 5120), + projection(.fp8, 6144, 5120), + projection(.bf16, 48, 5120), + projection(.bf16, 48, 5120), + }; + const codes = [_]u64{ 0x1100, 0x1200, 0x1300, 0x1400 }; + ls[0].ql.fp8.codes = codes[0]; + ls[1].ql.fp8.codes = codes[1]; + ls[2].ql.bf16.codes = codes[2]; + ls[3].ql.bf16.codes = codes[3]; + const outs = [_]u64{ 0x2100, 0x2200, 0x2300, 0x2400 }; + for ([_]usize{ 1, 16 }) |rows| { + Recorded.count = 0; + try e.projManyPrompt(&ls, 0x5000, &outs, rows, false); + try t.expectEqual(@as(usize, 2), Recorded.count); + const ids = [_]usize{ 10, 11 }; + const grids = [_]u32{ 512, 32 }; + const slices = [_]c_int{ 2, 8 }; + const widths = [_][2]c_int{ .{ 10240, 6144 }, .{ 48, 48 } }; + for (0..2) |i| { + const call = Recorded.calls[i]; + try t.expectEqual(ids[i], call.id); + try t.expectEqual(grids[i], call.grid); + try t.expectEqual(@as(u64, 0x5000), call.input); + try t.expectEqual(@as(c_int, @intCast(rows)), call.rows); + try t.expectEqual(@as(c_int, 5120), call.k); + try t.expectEqual(@as(c_int, 2), call.segs.count); + for (0..2) |j| { + try t.expectEqual(widths[i][j], call.segs.s[j].n); + try t.expectEqual(slices[i], call.segs.s[j].sk); + try t.expectEqual(codes[2 * i + j], call.segs.s[j].w); + try t.expectEqual(outs[2 * i + j], call.segs.s[j].out); + } + } + } + e.mo.?.group = null; + Recorded.count = 0; + try e.projManyPrompt(&ls, 0x5000, &outs, 1, false); + try t.expectEqual(@as(usize, 4), Recorded.count); + for (Recorded.calls[0..Recorded.count]) |call| try t.expectEqual(@as(usize, 2), call.id); + e.mo.?.group = grouped; + var bad = ls; + bad[3].ql.bf16.n = 6400; + bad[3].ql.bf16.npad = @intCast(cuda.modelopt.padded(6400)); + Recorded.count = 0; + try e.projManyPrompt(&bad, 0x5000, &outs, 1, false); + try t.expectEqual(@as(usize, 4), Recorded.count); + for (Recorded.calls[0..Recorded.count]) |call| try t.expectEqual(@as(usize, 2), call.id); + var aliased = outs; + aliased[2] = aliased[0]; + Recorded.count = 0; + try e.projManyPrompt(&ls, 0x5000, &aliased, 1, false); + try t.expectEqual(@as(usize, 4), Recorded.count); + for (Recorded.calls[0..Recorded.count]) |call| try t.expectEqual(@as(usize, 2), call.id); +} + test "ModelOpt partials: real reservations cover every 27B projection below the fused boundary" { var d: cuda.Driver = undefined; var e: Engine = undefined; diff --git a/zig/qwen35_rules_host.zig b/zig/qwen35_rules_host.zig index 725dcb4541b..b52c8d74bde 100644 --- a/zig/qwen35_rules_host.zig +++ b/zig/qwen35_rules_host.zig @@ -108,7 +108,27 @@ test "qwen35 rules: real configs, each entry point admits what main admitted, an try t.expectEqual(was, now); admitted += @intFromBool(now); }; - try t.expectEqual(@as(usize, 44), admitted); // (config, backend) pairs whose tower passes the rows + try t.expectEqual(@as(usize, 46), admitted); // (config, backend) pairs whose tower passes the rows, the 35B-A3B's two with them +} + +test "qwen35 rules: Qwen3.6-35B-A3B, admitted by Metal's 27B and HIP as on main, the others keep their refusal" { + var arena: std.heap.ArenaAllocator = .init(t.allocator); + defer arena.deinit(); + const r = try layers_host.a3b(arena.allocator()); + // no hidden_act: CUDA and the 2B require it, Metal's 27B and HIP read it only when present + const want = std.EnumArray(rules.Backend, ?anyerror).init(.{ + .metal27 = null, + .hip = null, + .metal2b = error.UnsupportedQwenConfig, + .cuda = error.UnsupportedActivation, + }); + for (std.enums.values(rules.Backend)) |b| { + const was = old.run(b, r.tower); + const now = entry(b, r.json); + errdefer std.debug.print("{s}: old {any}, now {any}\n", .{ @tagName(b), was, now }); + try t.expectEqual(std.meta.isError(was), std.meta.isError(now)); + if (want.get(b)) |e| try t.expectError(e, now) else try now; + } } test "qwen35 rules: every row and value through every entry point admits as main did, refused by the row's word" { @@ -202,7 +222,7 @@ test "qwen35 rules: a head count of 0 is refused by name at every entry point, b } }; errdefer std.debug.print("cases {any}, without head_dim {d}\n", .{ cases.values, derived }); - // four zeros on each admitted base: CUDA 7, Metal 27B 8, Metal 2B 1, HIP 18 (13 of all without head_dim) - try t.expectEqual([_]usize{ 4 * 7, 4 * 8, 4 * 1, 4 * 18 }, cases.values); - try t.expectEqual(@as(usize, 13), derived); + // four zeros on each admitted base: CUDA 7, Metal 27B 10, Metal 2B 1, HIP 20 (15 of all without head_dim) + try t.expectEqual([_]usize{ 4 * 7, 4 * 10, 4 * 1, 4 * 20 }, cases.values); + try t.expectEqual(@as(usize, 15), derived); } diff --git a/zig/request_access_host.zig b/zig/request_access_host.zig new file mode 100644 index 00000000000..a999345ef40 --- /dev/null +++ b/zig/request_access_host.zig @@ -0,0 +1,3 @@ +test { + _ = @import("src/server/cortheon/web_deadline_test.zig"); +} diff --git a/zig/request_access_policy_host.zig b/zig/request_access_policy_host.zig new file mode 100644 index 00000000000..a8d4d468608 --- /dev/null +++ b/zig/request_access_policy_host.zig @@ -0,0 +1,3 @@ +test { + _ = @import("src/server/cortheon/web.zig"); +} diff --git a/zig/src/cli/cuda_kl.zig b/zig/src/cli/cuda_kl.zig index 4d3a98bb8b6..25fcb135759 100644 --- a/zig/src/cli/cuda_kl.zig +++ b/zig/src/cli/cuda_kl.zig @@ -35,39 +35,61 @@ fn logSoftmax(row: []const u8, out: []f64) void { for (out) |*o| o.* -= z; } -fn download(gpa: std.mem.Allocator, e: *nemotron.Engine, ptr: u64, len: usize) ![]u8 { - const host = try gpa.alloc(u8, len); - errdefer gpa.free(host); - try e.ops().download(host, ptr); - try e.stream.synchronize(); - return host; +/// An engine's logits rows in order: row(i) gives row i's bf16 logits, step(i, t) feeds token t after it. +pub const Source = struct { + ctx: *anyopaque, + vocab: usize, + row: *const fn (ctx: *anyopaque, i: usize, out: []u8) anyerror!void, + step: *const fn (ctx: *anyopaque, i: usize, t: u32) anyerror!void, +}; + +/// The usage refusal before any GPU work: a prompt and exactly one of --dump and --against. +pub fn refused(prompt: []const u32, dump: ?[]const u8, against: ?[]const u8) bool { + if ((dump == null) != (against == null) and prompt.len != 0) return false; + std.debug.print("kl: give --tokens and one of --dump FILE or --against FILE\n", .{}); + return true; } +const Nemotron = struct { + fn row(ctx: *anyopaque, i: usize, out: []u8) anyerror!void { + const e: *nemotron.Engine = @ptrCast(@alignCast(ctx)); + try e.ops().download(out, if (i == 0) e.b.p_logits else e.b.logits); + try e.stream.synchronize(); + } + fn step(ctx: *anyopaque, _: usize, t: u32) anyerror!void { + const e: *nemotron.Engine = @ptrCast(@alignCast(ctx)); + _ = try e.step(t, null); + } +}; + /// `dump`: `n` rows after `prompt` into the file, fed `feed` then greedy. `against`: the file's tokens fed, row by row. pub fn run(gpa: std.mem.Allocator, io: std.Io, e: *nemotron.Engine, prompt: []const u32, feed: []const u32, n: usize, dump: ?[]const u8, against: ?[]const u8) !u8 { - if ((dump == null) == (against == null) or prompt.len == 0) { - std.debug.print("kl: give --tokens and one of --dump FILE or --against FILE\n", .{}); - return 2; - } - const v = e.c.vocab; - const rec = recordBytes(v); + if (refused(prompt, dump, against)) return 2; _ = try e.prefill(prompt, null, null); + return compare(gpa, io, .{ .ctx = e, .vocab = e.c.vocab, .row = Nemotron.row, .step = Nemotron.step }, prompt.len, feed, n, dump, against); +} + +/// `src`'s rows after a `prompt_len`-token prompt: `dump` writes `n`, fed `feed` then greedy; `against` feeds the file. +pub fn compare(gpa: std.mem.Allocator, io: std.Io, src: Source, prompt_len: usize, feed: []const u32, n: usize, dump: ?[]const u8, against: ?[]const u8) !u8 { + const v = src.vocab; + const rec = recordBytes(v); + const row = try gpa.alloc(u8, v * 2); + defer gpa.free(row); if (dump) |path| { const buf = try gpa.alloc(u8, header_bytes + n * rec); defer gpa.free(buf); std.mem.writeInt(u32, buf[0..4], @intCast(n), .little); std.mem.writeInt(u32, buf[4..8], @intCast(v), .little); for (0..n) |i| { - const row = try download(gpa, e, if (i == 0) e.b.p_logits else e.b.logits, v * 2); - defer gpa.free(row); + try src.row(src.ctx, i, row); const t: u32 = if (i < feed.len) feed[i] else @intCast(argmax(row, v)); const at = header_bytes + i * rec; std.mem.writeInt(u32, buf[at..][0..4], t, .little); @memcpy(buf[at + 4 ..][0 .. v * 2], row); - if (i + 1 < n) _ = try e.step(t, null); + if (i + 1 < n) try src.step(src.ctx, i, t); } try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = path, .data = buf }); - std.debug.print("RESULT kl dump: {d} rows ({d} fed) after a {d}-token prompt to {s}\n", .{ n, @min(n, feed.len), prompt.len, path }); + std.debug.print("RESULT kl dump: {d} rows ({d} fed) after a {d}-token prompt to {s}\n", .{ n, @min(n, feed.len), prompt_len, path }); return 0; } const ref = try std.Io.Dir.cwd().readFileAlloc(io, against.?, gpa, .limited(1 << 34)); @@ -89,8 +111,7 @@ pub fn run(gpa: std.mem.Allocator, io: std.Io, e: *nemotron.Engine, prompt: []co const at = header_bytes + i * rec; const t = std.mem.readInt(u32, ref[at..][0..4], .little); const want = ref[at + 4 ..][0 .. v * 2]; - const row = try download(gpa, e, if (i == 0) e.b.p_logits else e.b.logits, v * 2); - defer gpa.free(row); + try src.row(src.ctx, i, row); logSoftmax(want, lp); logSoftmax(row, lq); var kl: f64 = 0; @@ -105,7 +126,7 @@ pub fn run(gpa: std.mem.Allocator, io: std.Io, e: *nemotron.Engine, prompt: []co if (!same and first_diff == null) first_diff = i; nll[0] -= lp[t]; nll[1] -= lq[t]; - if (i + 1 < rows) _ = try e.step(t, null); + if (i + 1 < rows) try src.step(src.ctx, i, t); } const r: f64 = @floatFromInt(rows); std.debug.print("RESULT kl: {d} rows, mean KL {e:.3} nats, max {e:.3} at row {d}; top-1 {d} of {d}; first differs at {?d}; mean NLL of the fed tokens {d:.4} (reference) {d:.4} (this run)\n", .{ rows, kl_sum / r, kl_max, kl_at, top1, rows, first_diff, nll[0] / r, nll[1] / r }); diff --git a/zig/src/cli/cuda_main.zig b/zig/src/cli/cuda_main.zig index a99fda7943c..ae4ee3b3b08 100644 --- a/zig/src/cli/cuda_main.zig +++ b/zig/src/cli/cuda_main.zig @@ -16,6 +16,7 @@ const lanes_cli = @import("cuda_lanes.zig"); const segments_cli = @import("cuda_segments.zig"); const train_check = @import("cuda_train_check.zig"); const dory_cli = @import("cuda_dory.zig"); +const ricursive_cli = @import("cuda_ricursive.zig"); const decode = nemotron.decode; const usage = @@ -35,7 +36,7 @@ const usage = \\ tensorfold rounds MODEL --tokens ID,... [--max-tokens N] (GPU ms a serial and a window graph round) \\ tensorfold check-draws MODEL FIXTURES_DIR (MTP draws against the lane fixtures) \\ tensorfold shared-widths MODEL PROMPTS.json --streams N [--max-tokens N] [sampling as run] - \\ (N streams' continuations as shared windows of varying splits against serial, 2 <= N <= 8) + \\ (N streams' continuations as shared windows of varying splits against serial, 2 <= N <= 8; 16 wide) \\ tensorfold check-kernels MODEL (lane_gemv and the forked MoE against the kernels they replace, real weights) \\ tensorfold train-check MODEL (Sliding Weights' gradients against the forward by finite differences) \\ tensorfold check-precision MODEL --tokens ID,... --dump DIR (ModelOpt projections against fp64 and NVIDIA's math) @@ -43,6 +44,7 @@ const usage = \\ tensorfold digest MODEL (every byte of the checkpoint hashed, as a tensor-parallel rank checks it at load) \\ tensorfold kl MODEL --tokens ID,... [--gold ID,...] [--max-tokens N] (--dump FILE | --against FILE) [--precision P] \\ (logits rows to FILE, fed --gold then greedy; or FILE's tokens fed: KL, top-1 and NLL against its rows) + \\ [--gold-file PATH] [--chunk ROWS] (a Ripple checkpoint: every prompt row's logits, the prompt in chunks of ROWS) \\ tensorfold widths MODEL --tokens ID,... [--max-tokens N] [--eager] [sampling as run] \\ (every verify width, 1-32 for a latent MoE else 1-16, against serial decoding, a wrong draft every third window) \\ tensorfold models @@ -101,6 +103,13 @@ pub fn main(init: std.process.Init) !u8 { } else if (std.mem.eql(u8, a, "--gold")) { opts.gold = try parseIds(gpa, value); i += 1; + } else if (std.mem.eql(u8, a, "--gold-file")) { + gpa.free(opts.gold); + opts.gold = try segments_cli.readIds(gpa, init.io, value); + i += 1; + } else if (std.mem.eql(u8, a, "--chunk")) { + opts.chunk = try std.fmt.parseInt(usize, value, 10); + i += 1; } else if (std.mem.eql(u8, a, "--precision")) { opts.math = std.meta.stringToEnum(nemotron.Precision, value) orelse return error.BadPrecision; i += 1; @@ -207,10 +216,25 @@ pub fn main(init: std.process.Init) !u8 { const s: ?lanes.Sampling = if (opts.sampling.temperature > 0) opts.sampling else null; return dory_cli.run(gpa, init.io, &ctx, opts.model, .{ .tokens = opts.tokens, .max_tokens = opts.max_tokens, .loops = opts.loops, .context = opts.context, .drafts = opts.drafts, .graphs = opts.graphs, .stop_eos = opts.stop_eos, .sampling = s }); } + if (ricursive_cli.wants(gpa, init.io, opts.model)) { + if (kernels != null or opts.sampling.temperature > 0 or opts.loops != null) { + std.debug.print("Ripple on CUDA runs greedily on its own kernels: --kernels native, temperature 0, no --loops\n", .{}); + return 2; + } + const ro: ricursive_cli.Options = .{ .tokens = opts.tokens, .gold = opts.gold, .max_tokens = opts.max_tokens, .context = opts.context, .stop_eos = opts.stop_eos, .report = opts.report, .chunk = opts.chunk, .dump = opts.dump, .against = opts.against, .graphs = opts.graphs }; + if (std.mem.eql(u8, args[1], "run")) return ricursive_cli.run(gpa, init.io, &ctx, opts.model, ro); + if (std.mem.eql(u8, args[1], "kl")) return ricursive_cli.klRun(gpa, init.io, &ctx, opts.model, ro); + std.debug.print("Ripple on CUDA takes run and kl so far\n", .{}); + return 2; + } if (opts.loops != null) { std.debug.print("--loops sets a Dory checkpoint's recurrent passes: {s} is not one\n", .{opts.model}); return 2; } + if (opts.chunk != null) { + std.debug.print("--chunk forwards a Ripple prompt in chunks: {s} is not a Ripple checkpoint\n", .{opts.model}); + return 2; + } const env = init.environ_map; var carve: ?cuda.Carveout = null; if (try cuda.carveout.requested(opts.carveout, env.get("TF_CUDA_CARVEOUT"), env.get("TF_CUDA_CARVEOUT_MIB"))) |bytes| { @@ -233,13 +257,14 @@ pub fn main(init: std.process.Init) !u8 { const segments = opts.segments orelse @as(usize, @intCast((try settings.parse("TF_CUDA_SEGMENTS", init.environ_map.get("TF_CUDA_SEGMENTS"))) orelse 1)); // a rank past 0 of a tensor-parallel latent MoE holds expert shares and serves rank 0's jobs, whatever the command if (init.environ_map.get("TF_NEMOTRON_RANK")) |r| if (!std.mem.eql(u8, r, "0")) { - nemotron.worker.serve(gpa, init.io, &ctx, opts.model, opts.math) catch |err| { + nemotron.worker.serve(gpa, init.io, &ctx, opts.model, opts.math, null) catch |err| { cuda.tp_watch.fail(@errorName(err)); // rank 0 stops with this rank's error std.log.err("expert rank stopped: {s}", .{@errorName(err)}); std.c._exit(1); // a stream may still wait on rank 0: a normal exit would join it }; return 0; }; + _ = try @import("sys").environment.read(bool, "TF_NEMOTRON_WIDE_ROUNDS", false); // a malformed switch refuses; unset or 0, main's const engine = nemotron.Engine.init(gpa, init.io, &ctx, opts.model, kernels, .{ .context = opts.context, .mtp = mtp, .graphs = graphs, .sampling = sampling, .segments = segments, .carveout = if (carve) |*c| c else null, .precision = opts.math }) catch |err| { cuda.tp_watch.fail(@errorName(err)); // the other ranks stop with this error return err; @@ -303,6 +328,7 @@ const Options = struct { costs: ?[]f64 = null, segments: ?usize = null, loops: ?usize = null, // a Dory checkpoint's recurrent passes (run only) + chunk: ?usize = null, // kl on a Ripple checkpoint: every prompt row's logits, the prompt in chunks of this many rows counts: Counts = .{ .items = .{ 1, 2, 3, 4 }, .len = 4 }, repeat: usize = 3, streams: usize = 4, diff --git a/zig/src/cli/cuda_ricursive.zig b/zig/src/cli/cuda_ricursive.zig new file mode 100644 index 00000000000..aaace2eda1f --- /dev/null +++ b/zig/src/cli/cuda_ricursive.zig @@ -0,0 +1,195 @@ +//! `tensorfold run` and `kl` on a Ripple checkpoint: the CUDA forward driven directly, one stream; --eager: no graphs. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const rc = @import("ricursive_cuda"); +const kl = @import("cuda_kl.zig"); + +const fwd = rc.model; + +/// The checkpoint at `dir` is a Ripple one: its config.json names model_type ricursive. +pub fn wants(gpa: std.mem.Allocator, io: std.Io, dir: []const u8) bool { + const path = std.fs.path.join(gpa, &.{ dir, "config.json" }) catch return false; + defer gpa.free(path); + const text = std.Io.Dir.cwd().readFileAlloc(io, path, gpa, .limited(1 << 22)) catch return false; + defer gpa.free(text); + const Head = struct { model_type: []const u8 = "" }; + const head = std.json.parseFromSlice(Head, gpa, text, .{ .ignore_unknown_fields = true }) catch return false; + defer head.deinit(); + return std.mem.eql(u8, head.value.model_type, rc.native.model_type); +} + +pub const Options = struct { + tokens: []const u32, + gold: []const u32 = &.{}, + max_tokens: usize, + context: ?usize, + stop_eos: bool = true, + report: ?[]const u8 = null, + chunk: ?usize = null, // kl: every prompt row's logits, the prompt in chunks of this many rows + dump: ?[]const u8 = null, + against: ?[]const u8 = null, + graphs: bool = true, // decode rounds as CUDA graphs; false: eager launches +}; + +fn open(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: []const u8, context: ?usize) !*rc.native.Owned { + const own = try rc.native.openOwned(gpa, io, ctx, dir, context orelse @intCast(rc.native.default_context), null); + std.debug.print("Ripple on CUDA: {d}-token context, prompt chunks of {d} rows\n", .{ own.m.context, fwd.prompt_rows }); + return own; +} + +/// The prompt from position 0 in chunks of up to 2,048 rows, its last row through the head. +fn prefill(m: *const fwd.Model, st: *fwd.Seq, ids: []const u32) !void { + st.len = 0; + var at: usize = 0; + while (at < ids.len) { + const end = @min(ids.len, at + fwd.prompt_rows); + try m.forward(st, ids[at..end], .prompt); + if (end == ids.len) try m.head(end - at - 1); + at = end; + } +} + +/// The greedy token of the head's last row. +fn greedy(own: *rc.native.Owned) !u32 { + try own.m.draw(own.rb.tok.ptr); + var out: [1]u32 = undefined; + try own.m.download(own.rb.tok.ptr, std.mem.sliceAsBytes(&out)); + return out[0]; +} + +fn seconds(io: std.Io, since: std.Io.Timestamp) f64 { + return @as(f64, @floatFromInt(since.durationTo(std.Io.Timestamp.now(io, .awake)).nanoseconds)) / 1e9; +} + +/// A greedy reply: the prompt's chunks, then one-row decode steps; the output line and --report as Nemotron's run. +pub fn run(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: []const u8, o: Options) !u8 { + if (o.tokens.len == 0) return error.NoPromptTokens; + const own = try open(gpa, io, ctx, dir, o.context); + defer rc.native.closeOwned(own); + const m = &own.m; + m.graphs = o.graphs; + const st = &own.rb.st; + const c = own.w.config; + const count = @max(1, @min(o.max_tokens, m.context -| o.tokens.len)); + var out: std.ArrayList(u32) = .empty; + defer out.deinit(gpa); + const t0 = std.Io.Timestamp.now(io, .awake); + try prefill(m, st, o.tokens); + try out.append(gpa, try greedy(own)); + const prefill_seconds = seconds(io, t0); + const t1 = std.Io.Timestamp.now(io, .awake); + while (out.items.len < count) { + const t = out.items[out.items.len - 1]; + if (o.stop_eos and c.isEos(t)) break; + try m.forward(st, &.{t}, .decode); + try m.head(0); + try out.append(gpa, try greedy(own)); + } + const decode_seconds = seconds(io, t1); + var digest: [32]u8 = undefined; + const text = try core.ids_json.write(gpa, out.items); + defer gpa.free(text); + std.crypto.hash.sha2.Sha256.hash(text, &digest, .{}); + const hex = std.fmt.bytesToHex(digest, .lower); + const steps: f64 = @floatFromInt(@max(1, out.items.len - 1)); + const ms = decode_seconds * 1e3 / steps; + std.debug.print("tokens {d} sha {s} prefill {d:.4}s decode {d:.4}s {d:.3} ms/token {d:.2} tok/s prompt {d:.1} tok/s\n", .{ out.items.len, hex[0..12], prefill_seconds, decode_seconds, ms, 1e3 / ms, @as(f64, @floatFromInt(o.tokens.len)) / prefill_seconds }); + if (o.report) |path| { + const report = .{ + .engine = "zig-cuda", + .model_type = rc.native.model_type, + .prompt_tokens = o.tokens, + .tokens = out.items, + .token_sha256 = hex, + .prefill_seconds = prefill_seconds, + .decode_seconds = decode_seconds, + .ms_per_token = ms, + .tokens_per_second = 1e3 / ms, + .prompt_tokens_per_second = @as(f64, @floatFromInt(o.tokens.len)) / prefill_seconds, + .drafts = false, + .graphs = m.captured() > 0, // a decode round replayed a graph + .max_len = m.context, + }; + const json = try std.json.Stringify.valueAlloc(gpa, report, .{}); + defer gpa.free(json); + try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = path, .data = json }); + } + return 0; +} + +/// kl's rows after a prefill: row 0 the prompt's last, then one-row decode steps. +const Decode = struct { + m: *const fwd.Model, + st: *fwd.Seq, + + fn row(p: *anyopaque, _: usize, out: []u8) anyerror!void { + const x: *Decode = @ptrCast(@alignCast(p)); + try x.m.download(x.m.b.logits, out); + } + + fn step(p: *anyopaque, _: usize, t: u32) anyerror!void { + const x: *Decode = @ptrCast(@alignCast(p)); + try x.m.forward(x.st, &.{t}, .decode); + try x.m.head(0); + } +}; + +/// kl's rows of a whole prompt teacher-forced: row i after ids[0..i+1], the prompt forwarded in chunks of `chunk` rows. +const Chunks = struct { + m: *const fwd.Model, + st: *fwd.Seq, + ids: []const u32, + chunk: usize, + base: usize = 0, // the current forward's first row + done: usize = 0, // rows forwarded + head_at: ?usize = null, // the forward's row in `rows`' first slot + + fn row(p: *anyopaque, i: usize, out: []u8) anyerror!void { + const x: *Chunks = @ptrCast(@alignCast(p)); + if (i >= x.done) { + const end = @min(x.ids.len, x.done + x.chunk); + try x.m.forward(x.st, x.ids[x.done..end], .prompt); + x.base = x.done; + x.done = end; + x.head_at = null; + } + const r = i - x.base; + const v = x.m.c.vocab; + if (x.head_at == null or r < x.head_at.? or r >= x.head_at.? + fwd.head_rows) { + const r0 = r - r % fwd.head_rows; + try x.m.headRows(r0, @min(fwd.head_rows, x.done - x.base - r0)); + x.head_at = r0; + } + try x.m.download(x.m.b.rows + (r - x.head_at.?) * v * 2, out); + } + + /// The prompt's own tokens only: a reference whose tokens differ is another prompt. + fn step(p: *anyopaque, i: usize, t: u32) anyerror!void { + const x: *Chunks = @ptrCast(@alignCast(p)); + if (i + 1 >= x.ids.len or x.ids[i + 1] != t) return error.TokenMismatch; + } +}; + +/// --chunk ROWS: every prompt row's logits; else the last prompt row and `max_tokens - 1` decode rows (--gold, greedy). +pub fn klRun(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: []const u8, o: Options) !u8 { + if (kl.refused(o.tokens, o.dump, o.against)) return 2; + if (o.chunk) |c| if (c == 0 or c > fwd.prompt_rows) { + std.debug.print("--chunk {d}: prompt rows a forward, 1 to {d}\n", .{ c, fwd.prompt_rows }); + return 2; + }; + const own = try open(gpa, io, ctx, dir, o.context); + defer rc.native.closeOwned(own); + const m = &own.m; + m.graphs = o.graphs; + const st = &own.rb.st; + const vocab = own.w.config.vocab; + if (o.chunk) |c| { + st.len = 0; + var src: Chunks = .{ .m = m, .st = st, .ids = o.tokens, .chunk = c }; + return kl.compare(gpa, io, .{ .ctx = &src, .vocab = vocab, .row = Chunks.row, .step = Chunks.step }, 1, o.tokens[1..], o.tokens.len, o.dump, o.against); + } + try prefill(m, st, o.tokens); + var src: Decode = .{ .m = m, .st = st }; + return kl.compare(gpa, io, .{ .ctx = &src, .vocab = vocab, .row = Decode.row, .step = Decode.step }, o.tokens.len, o.gold, o.max_tokens, o.dump, o.against); +} diff --git a/zig/src/cli/cuda_shared_checks.zig b/zig/src/cli/cuda_shared_checks.zig index 2bc28e95d24..114000edc61 100644 --- a/zig/src/cli/cuda_shared_checks.zig +++ b/zig/src/cli/cuda_shared_checks.zig @@ -10,7 +10,7 @@ const max_rows = nemotron.state.max_rows; /// Compare serial streams with shared windows of varying splits and kept-row lengths. pub fn widths(gpa: std.mem.Allocator, io: std.Io, e: *nemotron.Engine, path: []const u8, streams: usize, count: usize, sampling: ?lanes.Sampling) !u8 { - if (streams < 2 or streams > max_streams) return error.BadStreams; + if (streams < 2 or streams > nemotron.wide.streams(e.c)) return error.BadStreams; // 8 with the switch off var prompts = try lanes_cli.readPrompts(gpa, io, path); defer prompts.deinit(); const ids = prompts.value.map.values(); @@ -40,15 +40,13 @@ pub fn widths(gpa: std.mem.Allocator, io: std.Io, e: *nemotron.Engine, path: []c while (true) : (round += 1) { var parts: [max_streams]nemotron.engine.Shared = undefined; var n: usize = 0; - var room: usize = nemotron.state.windowRows(e.c); + var room: usize = nemotron.state.sharedRows(e.c); // 17-32-row rounds with TF_NEMOTRON_WIDE_ROUNDS var waiting: usize = 0; for (0..streams) |k| waiting += @intFromBool(at[k] + 1 < refs[k].items.len); for (0..streams) |k| { if (at[k] + 1 >= refs[k].items.len) continue; waiting -= 1; - const cap = room - waiting; // at least a row for each stream after this one - const width = 1 + (round * 7 + k * 5 + round / 3) % cap; // uneven splits come round in turn - const rows = @min(width, refs[k].items.len - 1 - at[k]); + const rows = nemotron.wide.checkRows(round, k, room, waiting, nemotron.state.windowRows(e.c), refs[k].items.len - 1 - at[k]); @memcpy(bufs[k][0..rows], refs[k].items[at[k]..][0..rows]); keep[k] = rows; if ((round + k) % 3 == 2 and rows > 2) { // a wrong draft: the rows from it on read a token serial never fed diff --git a/zig/src/cli/info.zig b/zig/src/cli/info.zig index 35de28f6559..b78ce2a607a 100644 --- a/zig/src/cli/info.zig +++ b/zig/src/cli/info.zig @@ -377,9 +377,9 @@ test "info prices a Qwen3.8-27B start from serve's charge: context, streams and const past = try price27(a, io, dir, 4096, .{ .context = 300000 }); try std.testing.expectEqual(@as(u8, 1), past.code); try std.testing.expect(has(past.text, "--context 300000 is outside this Qwen checkpoint's 1 to 262,144 tokens")); - // a shape the engine refuses (16 query heads over 2 KV heads) keeps the floor + // a shape the engine refuses (20 query heads over 2 KV heads) keeps the floor try tmp.dir.writeFile(io, .{ .sub_path = "config.json", .data = - \\{"model_type":"qwen3_5","hidden_size":5120,"intermediate_size":17408,"num_hidden_layers":64,"vocab_size":248320,"num_attention_heads":16,"num_key_value_heads":2,"head_dim":256,"linear_num_key_heads":16,"linear_num_value_heads":48,"linear_key_head_dim":128,"linear_value_head_dim":128,"linear_conv_kernel_dim":4,"rms_norm_eps":0.000001,"partial_rotary_factor":0.25,"rope_theta":10000000,"full_attention_interval":4,"max_position_embeddings":262144,"eos_token_id":248046} + \\{"model_type":"qwen3_5","hidden_size":5120,"intermediate_size":17408,"num_hidden_layers":64,"vocab_size":248320,"num_attention_heads":20,"num_key_value_heads":2,"head_dim":256,"linear_num_key_heads":16,"linear_num_value_heads":48,"linear_key_head_dim":128,"linear_value_head_dim":128,"linear_conv_kernel_dim":4,"rms_norm_eps":0.000001,"partial_rotary_factor":0.25,"rope_theta":10000000,"full_attention_interval":4,"max_position_embeddings":262144,"eos_token_id":248046} }); const refused = try price27(a, io, dir, 4096, .{}); try std.testing.expectEqual(@as(u8, 0), refused.code); diff --git a/zig/src/cluster/config.zig b/zig/src/cluster/config.zig index 231f8322db0..61db06ccd3a 100644 --- a/zig/src/cluster/config.zig +++ b/zig/src/cluster/config.zig @@ -344,7 +344,9 @@ fn models(a: Allocator, v: ?Value, probs: *Problems) ![]Model { if (str(o.get("mla"))) |split| { if (std.mem.eql(u8, split, "heads")) m.mla = .heads else if (std.mem.eql(u8, split, "streams")) m.mla = .streams else if (!std.mem.eql(u8, split, "auto")) probs.add("models.{s}.mla: \"heads\", \"streams\" or \"auto\"", .{id}); } - if (o.get("vision")) |b| m.vision = b == .bool and b.bool; + if (o.get("vision")) |b| { + if (b == .bool) m.vision = b.bool else probs.add("models.{s}.vision: true or false", .{id}); + } if (o.get("memory")) |mem| if (mem == .object) if (num(mem.object.get("margin_gb"))) |g| { m.margin = @intFromFloat(g * @as(f64, @floatFromInt(node.gib))); }; diff --git a/zig/src/cluster/config_test.zig b/zig/src/cluster/config_test.zig index c7b726dee42..6e20643db0f 100644 --- a/zig/src/cluster/config_test.zig +++ b/zig/src/cluster/config_test.zig @@ -104,6 +104,7 @@ test "every broken file names what to change" { try check(head ++ four ++ "\"models\":{\"k\":{\"path\":\"/m\",\"mode\":\"disaggregated\",\"prefill\":[\"c1\"],\"decode\":[\"c1\",\"zz\"]}}}", &.{ "both a prefill and a decode", "\"zz\" is not a node" }); try check(head ++ four ++ "\"models\":{\"k\":{\"path\":\"/m\",\"mode\":\"disaggregated\"}}}", &.{"needs \"prefill\" and \"decode\""}); try check(head ++ four ++ "\"models\":{\"k\":{\"nodes\":[\"m9\"],\"parallel\":{\"tensor\":\"many\"}}}}", &.{ "path: required", "\"m9\" is not a node", "or \"auto\"" }); + try check(head ++ four ++ "\"models\":{\"k\":{\"path\":\"/m\",\"nodes\":[\"c1\"],\"vision\":\"yes\"}}}", &.{"vision: true or false"}); try check("{\"cluster\":1}", &.{ "schema: must be", "nodes: at least one" }); try check("not json", &.{"not JSON"}); } diff --git a/zig/src/core/checkpoint_metal.zig b/zig/src/core/checkpoint_metal.zig index 599acac2bb0..95e69ffdda6 100644 --- a/zig/src/core/checkpoint_metal.zig +++ b/zig/src/core/checkpoint_metal.zig @@ -2,8 +2,8 @@ const std = @import("std"); const platform = @import("sys"); const mtl = @import("metal"); -const st = @import("safetensors.zig"); -const file_cache = @import("checkpoint_file_cache.zig"); +const st = @import("core").safetensors; +const file_cache = @import("core").checkpoint_file_cache; pub const DType = st.DType; diff --git a/zig/src/core/checkpoint_weights.zig b/zig/src/core/checkpoint_weights.zig index e6544d7d271..4238f7e7d44 100644 --- a/zig/src/core/checkpoint_weights.zig +++ b/zig/src/core/checkpoint_weights.zig @@ -1,10 +1,17 @@ -//! Header-based admission bytes for the text side and optional RADIO tower, including mixed shards. +//! Header-based admission bytes for the text side and an optional vision tower, including mixed shards. const std = @import("std"); const ck = @import("checkpoint.zig"); const st = @import("safetensors.zig"); +/// Tower and projector prefixes: RADIO's, then Qwen-VL's, Gemma 4's, LFM2-VL's, LightOn's, DeepSeek's and GLM's. +const vision_prefixes = [_][]const u8{ + "vision_model.", "vision_projector.", "mlp1.", "model.visual.", "visual.", + "vision_tower.", "model.vision_tower.", "vision_embedder.", "embed_vision.", "model.vision_model.", + "model.vision_encoder.", "model.vision_projection.", "vision.", +}; + pub fn visionTensor(name: []const u8) bool { - for ([_][]const u8{ "vision_model.", "vision_projector.", "mlp1." }) |p| + for (vision_prefixes) |p| if (std.mem.startsWith(u8, name, p)) return true; return false; } @@ -50,3 +57,10 @@ test "text admission excludes RADIO tensors even in a shared shard" { try std.testing.expectEqual(@as(u64, 8), try count(a, io, dir, false)); try std.testing.expectEqual(@as(u64, 24), try count(a, io, dir, true)); } + +test "every family's tower prefix is a vision tensor, and no text tensor of theirs is" { + for ([_][]const u8{ "model.visual.blocks.0.attn.qkv.weight", "vision_tower.blocks.0.norm1.weight", "vision.blocks.3.mlp.w1.weight", "model.vision_model.embeddings.patch_embedding.weight", "model.vision_tower.vision_model.post_layernorm.weight", "vision_embedder.patch_dense.weight", "model.vision_encoder.patch_conv.weight" }) |n| + try std.testing.expect(visionTensor(n)); + for ([_][]const u8{ "model.language_model.embed_tokens.weight", "language_model.model.layers.0.mlp.gate_proj.weight", "model.layers.0.self_attn.q_proj.weight", "backbone.layers.0.mixer.in_proj.weight", "lm_head.weight", "model.embed_tokens.weight", "mtp.layers.0.eh_proj.weight", "model.multi_modal_projector.linear_1.weight" }) |n| + try std.testing.expect(!visionTensor(n)); +} diff --git a/zig/src/core/chunked_write.zig b/zig/src/core/chunked_write.zig new file mode 100644 index 00000000000..b973eccffee --- /dev/null +++ b/zig/src/core/chunked_write.zig @@ -0,0 +1,36 @@ +//! XNU rejects individual writes larger than INT_MAX. +const std = @import("std"); + +/// Upper bound for a single write request, well under XNU's INT_MAX cap. +pub const max_write_bytes: usize = 1 << 28; // 256 MiB + +comptime { + std.debug.assert(max_write_bytes < std.math.maxInt(c_int)); +} + +/// Write bounded chunks; sink errors pass through, and a nonempty write with a zero cap refuses. +pub fn writeChunked(sink: anytype, bytes: []const u8, cap: usize) !void { + if (cap == 0 and bytes.len > 0) return error.ZeroWriteCap; + var at: usize = 0; + while (at < bytes.len) { + const n = @min(bytes.len - at, cap); + try sink.writeAll(bytes[at..][0..n]); + at += n; + } +} + +/// Write `bytes` to `sub_path` in bounded chunks; write errors pass through. +pub fn writeFileChunked(io: std.Io, dir: std.Io.Dir, sub_path: []const u8, bytes: []const u8) !void { + var file = try dir.createFile(io, sub_path, .{}); + defer file.close(io); + const FileSink = struct { + file: std.Io.File, + io: std.Io, + + fn writeAll(self: *@This(), chunk: []const u8) !void { + try self.file.writeStreamingAll(self.io, chunk); + } + }; + var sink = FileSink{ .file = file, .io = io }; + try writeChunked(&sink, bytes, max_write_bytes); +} diff --git a/zig/src/core/chunked_write_test_file.zig b/zig/src/core/chunked_write_test_file.zig new file mode 100644 index 00000000000..264709920f6 --- /dev/null +++ b/zig/src/core/chunked_write_test_file.zig @@ -0,0 +1,79 @@ +//! Regression tests for bounded output writes. +const std = @import("std"); +const cw = @import("chunked_write.zig"); + +const testing = std.testing; + +const LimitedSink = struct { + buf: std.ArrayList(u8), + cap: usize, + + const WriteError = error{ OutOfMemory, WriteTooLarge, ZeroWriteCap }; + + pub fn writeAll(self: *LimitedSink, bytes: []const u8) WriteError!void { + if (bytes.len > self.cap) return error.WriteTooLarge; + try self.buf.appendSlice(testing.allocator, bytes); + } +}; + +test "a zero cap refuses a nonempty buffer without progress" { + const zero = 0; + var sink = LimitedSink{ .buf = .empty, .cap = zero }; + defer sink.buf.deinit(testing.allocator); + + var data: [4]u8 = .{ 1, 2, 3, 4 }; + try testing.expectError(error.ZeroWriteCap, cw.writeChunked(&sink, &data, zero)); + try testing.expectEqual(@as(usize, 0), sink.buf.items.len); // no write happened + // an empty buffer is fine at a zero cap: nothing to write, nothing to refuse + try cw.writeChunked(&sink, &.{}, zero); + try testing.expectEqual(@as(usize, 0), sink.buf.items.len); +} + +test "chunked writes respect the cap and preserve order" { + const cap = 64; // injected cap: the test never allocates the production 256 MiB + var sink = LimitedSink{ .buf = .empty, .cap = cap }; + defer sink.buf.deinit(testing.allocator); + + var data: [cap + 1]u8 = undefined; + for (&data, 0..) |*b, i| b.* = @truncate(i * 31 + 7); + + try cw.writeChunked(&sink, &data, cap); + try testing.expectEqual(data.len, sink.buf.items.len); + try testing.expect(std.mem.eql(u8, sink.buf.items, &data)); +} + +test "a sink-refused request fails through the writer without flattening" { + var sink = LimitedSink{ .buf = .empty, .cap = 16 }; + defer sink.buf.deinit(testing.allocator); + + var big: [33]u8 = undefined; + @memset(&big, 1); + try testing.expectError(error.WriteTooLarge, cw.writeChunked(&sink, &big, 32)); +} + +test "empty and exact-cap buffers pass through" { + var sink = LimitedSink{ .buf = .empty, .cap = 16 }; + defer sink.buf.deinit(testing.allocator); + + try cw.writeChunked(&sink, "", 16); + try testing.expectEqual(@as(usize, 0), sink.buf.items.len); + + const exact = [_]u8{ 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9 }; + try cw.writeChunked(&sink, &exact, 16); + try testing.expect(std.mem.eql(u8, sink.buf.items, &exact)); +} + +test "writeFileChunked round-trips through the real file path" { + var single: std.Io.Threaded = .init_single_threaded; + defer single.deinit(); + const io = single.io(); + + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const data = "bounded file output"; + try cw.writeFileChunked(io, tmp.dir, "cw-roundtrip.bin", data); + + const result = try tmp.dir.readFileAlloc(io, "cw-roundtrip.bin", testing.allocator, .limited(data.len + 1)); + defer testing.allocator.free(result); + try testing.expectEqualSlices(u8, data, result); +} diff --git a/zig/src/core/contract.zig b/zig/src/core/contract.zig index 858b4d03117..d4528b8ed4b 100644 --- a/zig/src/core/contract.zig +++ b/zig/src/core/contract.zig @@ -1,5 +1,6 @@ //! The kernel contract every GPU kernel's test registers with: its spec, the gates and the input families. pub const delta_slots_ref = @import("contract/delta_slots_ref.zig"); +pub const inkling2_attn_ref = @import("contract/inkling2_attn_ref.zig"); pub const delta_slots_records = @import("contract/delta_slots_records.zig"); pub const spec = @import("contract/contract.zig"); pub const gates = @import("contract/gates.zig"); @@ -11,6 +12,10 @@ pub const dense = @import("contract/dense.zig"); pub const bf16_round = @import("bf16_round"); pub const attention_range = @import("attention_range.zig"); pub const limits = @import("contract/limits.zig"); +pub const inkling2_glue_metal_records = @import("contract/inkling2_glue_metal_records.zig"); +pub const inkling2_dspark_metal_records = @import("contract/inkling2_dspark_metal_records.zig"); +pub const inkling2_loop_metal_records = @import("contract/inkling2_loop_metal_records.zig"); +pub const inkling2_runtime_metal_records = @import("contract/inkling2_runtime_metal_records.zig"); pub const lane_q8 = @import("contract/lane_q8_records.zig"); pub const q27_prompt = @import("contract/qwen27_prompt_records.zig"); pub const registry = @import("contract/registry.zig"); @@ -68,6 +73,7 @@ test { _ = cubin; _ = hsaco; _ = hip_records; + _ = inkling2_attn_ref; _ = @import("contract/hip_records_qwen3.zig"); _ = @import("contract/hip_records_families.zig"); _ = @import("contract/fakes.zig"); diff --git a/zig/src/core/contract/fakes.zig b/zig/src/core/contract/fakes.zig index 1e761d9339e..e344775cfe7 100644 --- a/zig/src/core/contract/fakes.zig +++ b/zig/src/core/contract/fakes.zig @@ -156,6 +156,25 @@ test "correct CPU kernels pass gates 1-4 and every planted fault goes red at its try std.testing.expectEqual(@as(usize, 0), t.problems()); } +test "initialization failures are tallied and later kernels and controls still run" { + const a = std.testing.allocator; + var f = Fake{ .a = a, .op = .sum }; + defer f.deinit(); + const missing: g.Kernel = .{ .spec = spec("missing library", .sum), .ctx = undefined, .vt = undefined, .init_error = error.NoFunction }; + const missed_control: g.Kernel = .{ .spec = spec("missing control library", .sum), .ctx = undefined, .vt = undefined, .control = .shapes, .init_error = error.NoFunction }; + g.quiet = true; + defer g.quiet = false; + var t: g.Tally = .{}; + try g.runAll(a, &.{ missing, missed_control, f.kernel("after missing library", null) }, 0x5eed, &t); + try std.testing.expectEqual(@as(usize, 2), t.kernels); + try std.testing.expectEqual(@as(usize, 1), t.failed); + try std.testing.expectEqual(@as(usize, 1), t.passed); + try std.testing.expectEqual(@as(usize, 1), t.controls); + try std.testing.expectEqual(@as(usize, 1), t.missed); + try std.testing.expectEqual(@as(usize, 2), t.problems()); + try std.testing.expect(f.runs > 0); +} + test "a tail fault passes at whole tiles: the edges are what catch it" { const a = std.testing.allocator; var f = Fake{ .a = a, .op = .sum, .fault = .tail }; diff --git a/zig/src/core/contract/flashnext_cuda_records.zig b/zig/src/core/contract/flashnext_cuda_records.zig index a562ae82ab3..61f3becf288 100644 --- a/zig/src/core/contract/flashnext_cuda_records.zig +++ b/zig/src/core/contract/flashnext_cuda_records.zig @@ -30,6 +30,8 @@ pub const cuda = [_]CudaRecord{ .{ .launch = .{ .name = "flashnext_attn fn_qsa_scores", .symbol = "fn_qsa_scores", .image = "flashnext_attn", .threads = 256 }, .usage = .{ .{ .regs = 40, .static = 4096, .bound = 256 }, .{ .regs = 46, .static = 4096, .bound = 256 }, .{ .regs = 46, .static = 4096, .bound = 256 }, .{ .regs = 48, .static = 4096, .bound = 256 }, .{ .regs = 48, .static = 4096, .bound = 256 } } }, .{ .launch = .{ .name = "flashnext_batch fn_qsa_select", .symbol = "fn_qsa_select", .image = "flashnext_batch", .threads = 1024 }, .usage = .{ .{ .regs = 32, .static = 1168, .bound = 1024 }, .{ .regs = 50, .static = 1168, .bound = 1024 }, .{ .regs = 50, .static = 1168, .bound = 1024 }, .{ .regs = 44, .static = 1168, .bound = 1024 }, .{ .regs = 40, .static = 1168, .bound = 1024 } } }, .{ .launch = .{ .name = "flashnext_mtp fn_row_best", .symbol = "fn_row_best", .image = "flashnext_mtp", .threads = 1024 }, .usage = .{ .{ .regs = 17, .static = 392, .bound = 1024 }, .{ .regs = 17, .static = 392, .bound = 1024 }, .{ .regs = 17, .static = 392, .bound = 1024 }, .{ .regs = 21, .static = 392, .bound = 1024 }, .{ .regs = 21, .static = 392, .bound = 1024 } } }, + .{ .launch = .{ .name = "flashnext_mtp fn_row_best_max", .symbol = "fn_row_best_max", .image = "flashnext_mtp", .threads = 32 }, .usage = .{ .{ .regs = 38, .static = 0, .bound = 32 }, .{ .regs = 36, .static = 0, .bound = 32 }, .{ .regs = 36, .static = 0, .bound = 32 }, .{ .regs = 31, .static = 0, .bound = 32 }, .{ .regs = 31, .static = 0, .bound = 32 } } }, + .{ .launch = .{ .name = "flashnext_mtp fn_row_best_sum", .symbol = "fn_row_best_sum", .image = "flashnext_mtp", .threads = 32 }, .usage = .{ .{ .regs = 27, .static = 0, .bound = 32 }, .{ .regs = 27, .static = 0, .bound = 32 }, .{ .regs = 27, .static = 0, .bound = 32 }, .{ .regs = 36, .static = 0, .bound = 32 }, .{ .regs = 36, .static = 0, .bound = 32 } } }, .{ .launch = .{ .name = "flashnext_hc fn_shared_scatter", .symbol = "fn_shared_scatter", .image = "flashnext_hc", .threads = 256 }, .usage = .{ .{ .regs = 12, .static = 0, .bound = 0 }, .{ .regs = 12, .static = 0, .bound = 0 }, .{ .regs = 12, .static = 0, .bound = 0 }, .{ .regs = 14, .static = 0, .bound = 0 }, .{ .regs = 14, .static = 0, .bound = 0 } } }, .{ .launch = .{ .name = "flashnext_hc fn_shared_swiglu", .symbol = "fn_shared_swiglu", .image = "flashnext_hc", .threads = 256 }, .usage = .{ .{ .regs = 17, .static = 0, .bound = 0 }, .{ .regs = 18, .static = 0, .bound = 0 }, .{ .regs = 18, .static = 0, .bound = 0 }, .{ .regs = 18, .static = 0, .bound = 0 }, .{ .regs = 18, .static = 0, .bound = 0 } } }, .{ .launch = .{ .name = "flashnext_batch fn_ep_picks", .symbol = "fn_ep_picks", .image = "flashnext_batch", .threads = 256 }, .usage = .{ .{ .regs = 10, .static = 0, .bound = 0 }, .{ .regs = 10, .static = 0, .bound = 0 }, .{ .regs = 10, .static = 0, .bound = 0 }, .{ .regs = 14, .static = 0, .bound = 0 }, .{ .regs = 14, .static = 0, .bound = 0 } } }, diff --git a/zig/src/core/contract/gates.zig b/zig/src/core/contract/gates.zig index a815417a16b..eed00563a16 100644 --- a/zig/src/core/contract/gates.zig +++ b/zig/src/core/contract/gates.zig @@ -19,6 +19,8 @@ pub const Kernel = struct { ctx: *anyopaque, vt: *const VTable, control: ?Gate = null, + /// An initialization error to tally without reading ctx or vt. + init_error: ?anyerror = null, }; /// The hooks a kernel's test gives the harness; the harness owns no device memory. @@ -351,6 +353,18 @@ pub fn one(a: std.mem.Allocator, which: Gate, k: Kernel, seed: u64) !Verdict { /// Gates 1-4 on each kernel, and each control at its own gate (which must fail). pub fn runAll(a: std.mem.Allocator, kernels: []const Kernel, seed: u64, t: *Tally) !void { for (kernels) |k| { + if (k.init_error) |err| { + if (k.control) |gate| { + t.controls += 1; + t.missed += 1; + if (!quiet) std.debug.print("CONTROL ERROR {s}: {t} at {t}, so it proves nothing\n", .{ k.spec.name, err, gate }); + } else { + t.kernels += 1; + t.failed += 1; + if (!quiet) std.debug.print("FAIL init {s}: {t}\n", .{ k.spec.name, err }); + } + continue; + } defer if (k.vt.release) |free| free(k.ctx); const s = std.hash.Wyhash.hash(seed, k.spec.name); if (k.control) |g| { diff --git a/zig/src/core/contract/hip_records.zig b/zig/src/core/contract/hip_records.zig index 8165561207e..aa54b825869 100644 --- a/zig/src/core/contract/hip_records.zig +++ b/zig/src/core/contract/hip_records.zig @@ -494,7 +494,7 @@ const own_records = [own_count]Record{ }, }, } ++ @import("hip_records_pair.zig").records ++ @import("hip_records_prompt.zig").records ++ @import("hip_records_draft.zig").records ++ @import("hip_records_exl3.zig").records ++ - @import("hip_records_score.zig").records ++ @import("hip_records_embed.zig").records ++ @import("hip_records_tail.zig").records ++ @import("hip_records_tap.zig").records ++ @import("hip_records_sparse.zig").records; + @import("hip_records_score.zig").records ++ @import("hip_records_score_rows.zig").records ++ @import("hip_records_apply_rows.zig").records ++ @import("hip_records_embed.zig").records ++ @import("hip_records_tail.zig").records ++ @import("hip_records_tap.zig").records ++ @import("hip_records_sparse.zig").records; pub const records = own_records ++ @import("hip_records_stream.zig").records ++ @import("hip_records_router.zig").records ++ @import("hip_records_item.zig").records ++ @import("hip_records_qwen3.zig").records ++ @import("hip_records_columns.zig").records ++ diff --git a/zig/src/core/contract/hip_records_apply_rows.zig b/zig/src/core/contract/hip_records_apply_rows.zig new file mode 100644 index 00000000000..d503eb0031f --- /dev/null +++ b/zig/src/core/contract/hip_records_apply_rows.zig @@ -0,0 +1,38 @@ +//! Gate 5's records of plan_rows.hip's values kernels: a multi-row launch's rows applied alone, and its slots' chunks. +const limits = @import("limits.zig"); +const Record = @import("hip_records.zig").Record; + +const U = limits.HipUsage; + +/// 256 threads, the weights in static LDS: kMaxGroup heads of one row alone, kApplyRows rows of kApplyHeads in a chunk. +fn rowsApply(comptime symbol: []const u8, usage: [limits.rdna.len]U) Record { + const name = "planned walk " ++ symbol; + return .{ .launch = .{ .name = name, .symbol = symbol, .image = "plan_rows", .threads = 256 }, .usage = usage }; +} + +pub const records = [4]Record{ + rowsApply("tf_plan_lone_apply_f16", .{ + .{ .vgprs = 42, .sgprs = 44, .lds = 8192, .private = 0, .bound = 256, .wave = 32 }, + .{ .vgprs = 42, .sgprs = 44, .lds = 8192, .private = 0, .bound = 256, .wave = 32 }, + .{ .vgprs = 42, .sgprs = 44, .lds = 8192, .private = 0, .bound = 256, .wave = 32 }, + .{ .vgprs = 42, .sgprs = 44, .lds = 8192, .private = 0, .bound = 256, .wave = 32 }, + }), + rowsApply("tf_plan_lone_apply_bf16", .{ + .{ .vgprs = 42, .sgprs = 44, .lds = 8192, .private = 0, .bound = 256, .wave = 32 }, + .{ .vgprs = 42, .sgprs = 44, .lds = 8192, .private = 0, .bound = 256, .wave = 32 }, + .{ .vgprs = 42, .sgprs = 44, .lds = 8192, .private = 0, .bound = 256, .wave = 32 }, + .{ .vgprs = 42, .sgprs = 44, .lds = 8192, .private = 0, .bound = 256, .wave = 32 }, + }), + rowsApply("tf_plan_rows_apply_f16", .{ + .{ .vgprs = 81, .sgprs = 61, .lds = 16384, .private = 0, .bound = 256, .wave = 32 }, + .{ .vgprs = 81, .sgprs = 61, .lds = 16384, .private = 0, .bound = 256, .wave = 32 }, + .{ .vgprs = 81, .sgprs = 61, .lds = 16384, .private = 0, .bound = 256, .wave = 32 }, + .{ .vgprs = 81, .sgprs = 60, .lds = 16384, .private = 0, .bound = 256, .wave = 32 }, + }), + rowsApply("tf_plan_rows_apply_bf16", .{ + .{ .vgprs = 81, .sgprs = 61, .lds = 16384, .private = 0, .bound = 256, .wave = 32 }, + .{ .vgprs = 81, .sgprs = 61, .lds = 16384, .private = 0, .bound = 256, .wave = 32 }, + .{ .vgprs = 81, .sgprs = 61, .lds = 16384, .private = 0, .bound = 256, .wave = 32 }, + .{ .vgprs = 81, .sgprs = 60, .lds = 16384, .private = 0, .bound = 256, .wave = 32 }, + }), +}; diff --git a/zig/src/core/contract/hip_records_families.zig b/zig/src/core/contract/hip_records_families.zig index 6db017bdc6e..caa7a236a57 100644 --- a/zig/src/core/contract/hip_records_families.zig +++ b/zig/src/core/contract/hip_records_families.zig @@ -4,6 +4,7 @@ const Record = @import("hip_records.zig").Record; pub const records = .{ @import("hip_records_glm_ocr.zig").records, + @import("hip_records_inkling2.zig").records, @import("hip_records_joint.zig").records, @import("hip_records_lighton_ocr.zig").records, @import("hip_records_qwen_vision.zig").records, @@ -20,6 +21,7 @@ pub const all = join: { test "HIP record counts stay pinned in their owning files" { const hip = @import("hip_records.zig"); const counts = .{ + @import("hip_records_apply_rows.zig").records.len, @import("hip_records_columns.zig").records.len, @import("hip_records_dense_text.zig").records.len, @import("hip_records_draft.zig").records.len, @@ -27,6 +29,7 @@ test "HIP record counts stay pinned in their owning files" { @import("hip_records_exl3.zig").records.len, @import("hip_records_gdn.zig").records.len, @import("hip_records_glm_ocr.zig").records.len, + @import("hip_records_inkling2.zig").records.len, @import("hip_records_item.zig").records.len, @import("hip_records_joint.zig").records.len, @import("hip_records_lighton_ocr.zig").records.len, @@ -37,6 +40,7 @@ test "HIP record counts stay pinned in their owning files" { @import("hip_records_relu2_widths.zig").records.len, @import("hip_records_router.zig").records.len, @import("hip_records_score.zig").records.len, + @import("hip_records_score_rows.zig").records.len, @import("hip_records_skew.zig").records.len, @import("hip_records_sparse.zig").records.len, @import("hip_records_stream_plain.zig").records.len, diff --git a/zig/src/core/contract/hip_records_inkling2.zig b/zig/src/core/contract/hip_records_inkling2.zig new file mode 100644 index 00000000000..639d64ed1f5 --- /dev/null +++ b/zig/src/core/contract/hip_records_inkling2.zig @@ -0,0 +1,23 @@ +//! Inkling 2's HIP attention launches (the inkling2 image), re-derived from the code objects for all four chips. +const std = @import("std"); +const hip_records = @import("hip_records.zig"); +const limits = @import("limits.zig"); +const Record = hip_records.Record; + +fn launch(comptime symbol: []const u8, threads: u32) limits.HipLaunch { + return .{ .name = "inkling2 " ++ symbol, .symbol = symbol, .image = "inkling2", .threads = threads }; +} + +pub const records = [6]Record{ + .{ .launch = launch("tf_ink2_prep", 32), .usage = .{ .{ .vgprs = 20, .sgprs = 46, .lds = 0, .private = 0, .bound = 32, .wave = 32 }, .{ .vgprs = 20, .sgprs = 46, .lds = 0, .private = 0, .bound = 32, .wave = 32 }, .{ .vgprs = 20, .sgprs = 46, .lds = 0, .private = 0, .bound = 32, .wave = 32 }, .{ .vgprs = 19, .sgprs = 46, .lds = 0, .private = 0, .bound = 32, .wave = 32 } } }, + .{ .launch = launch("tf_ink2_rel_table", 256), .usage = .{ .{ .vgprs = 49, .sgprs = 14, .lds = 0, .private = 0, .bound = 256, .wave = 32 }, .{ .vgprs = 54, .sgprs = 18, .lds = 0, .private = 0, .bound = 256, .wave = 32 }, .{ .vgprs = 54, .sgprs = 14, .lds = 0, .private = 0, .bound = 256, .wave = 32 }, .{ .vgprs = 54, .sgprs = 14, .lds = 0, .private = 0, .bound = 256, .wave = 32 } } }, + .{ .launch = launch("tf_ink2_attn", 128), .usage = .{ .{ .vgprs = 101, .sgprs = 50, .lds = 35072, .private = 0, .bound = 128, .wave = 32 }, .{ .vgprs = 101, .sgprs = 50, .lds = 35072, .private = 0, .bound = 128, .wave = 32 }, .{ .vgprs = 101, .sgprs = 50, .lds = 35072, .private = 0, .bound = 128, .wave = 32 }, .{ .vgprs = 101, .sgprs = 52, .lds = 35072, .private = 0, .bound = 128, .wave = 32 } } }, + .{ .launch = launch("tf_ink2_attn_fold", 128), .usage = .{ .{ .vgprs = 109, .sgprs = 46, .lds = 35072, .private = 0, .bound = 128, .wave = 32 }, .{ .vgprs = 109, .sgprs = 43, .lds = 35072, .private = 0, .bound = 128, .wave = 32 }, .{ .vgprs = 109, .sgprs = 43, .lds = 35072, .private = 0, .bound = 128, .wave = 32 }, .{ .vgprs = 108, .sgprs = 43, .lds = 35072, .private = 0, .bound = 128, .wave = 32 } } }, + .{ .launch = launch("tf_ink2_attn_prompt", 256), .usage = .{ .{ .vgprs = 88, .sgprs = 43, .lds = 37120, .private = 0, .bound = 256, .wave = 32 }, .{ .vgprs = 88, .sgprs = 43, .lds = 37120, .private = 0, .bound = 256, .wave = 32 }, .{ .vgprs = 88, .sgprs = 43, .lds = 37120, .private = 0, .bound = 256, .wave = 32 }, .{ .vgprs = 88, .sgprs = 43, .lds = 37120, .private = 0, .bound = 256, .wave = 32 } } }, + .{ .launch = launch("tf_ink2_merge", 128), .usage = .{ .{ .vgprs = 18, .sgprs = 32, .lds = 0, .private = 0, .bound = 128, .wave = 32 }, .{ .vgprs = 18, .sgprs = 32, .lds = 0, .private = 0, .bound = 128, .wave = 32 }, .{ .vgprs = 18, .sgprs = 32, .lds = 0, .private = 0, .bound = 128, .wave = 32 }, .{ .vgprs = 15, .sgprs = 38, .lds = 0, .private = 0, .bound = 128, .wave = 32 } } }, +}; + +test "Inkling 2 HIP launch records cover prep, the table, each attention path and the merge on all served chips" { + try std.testing.expectEqual(@as(usize, 6), records.len); + try std.testing.expectEqual(@as(usize, 0), try hip_records.check(std.testing.allocator, &records, false)); +} diff --git a/zig/src/core/contract/hip_records_score_rows.zig b/zig/src/core/contract/hip_records_score_rows.zig new file mode 100644 index 00000000000..8ade2c924be --- /dev/null +++ b/zig/src/core/contract/hip_records_score_rows.zig @@ -0,0 +1,38 @@ +//! Gate 5's records of plan_rows.hip's kernels: a multi-row launch's rows that score alone, and its slots' chunks. +const limits = @import("limits.zig"); +const Record = @import("hip_records.zig").Record; + +const U = limits.HipUsage; + +/// 128 threads, the queries of `rows` rows of at most kMaxGroup heads of 256 in dynamic LDS. +fn rowsScore(comptime symbol: []const u8, comptime rows: u32, usage: [limits.rdna.len]U) Record { + const name = "planned walk " ++ symbol; + return .{ .launch = .{ .name = name, .symbol = symbol, .image = "plan_rows", .threads = 128, .dynamic = rows * 16 * 256 * 4 }, .usage = usage }; +} + +pub const records = [4]Record{ + rowsScore("tf_plan_lone_score256_f16", 1, .{ + .{ .vgprs = 108, .sgprs = 77, .lds = 0, .private = 0, .bound = 128, .wave = 32 }, + .{ .vgprs = 108, .sgprs = 77, .lds = 0, .private = 0, .bound = 128, .wave = 32 }, + .{ .vgprs = 108, .sgprs = 77, .lds = 0, .private = 0, .bound = 128, .wave = 32 }, + .{ .vgprs = 108, .sgprs = 77, .lds = 0, .private = 0, .bound = 128, .wave = 32 }, + }), + rowsScore("tf_plan_lone_score256_bf16", 1, .{ + .{ .vgprs = 108, .sgprs = 77, .lds = 0, .private = 0, .bound = 128, .wave = 32 }, + .{ .vgprs = 108, .sgprs = 77, .lds = 0, .private = 0, .bound = 128, .wave = 32 }, + .{ .vgprs = 108, .sgprs = 77, .lds = 0, .private = 0, .bound = 128, .wave = 32 }, + .{ .vgprs = 108, .sgprs = 77, .lds = 0, .private = 0, .bound = 128, .wave = 32 }, + }), + rowsScore("tf_plan_rows_score256_f16", 2, .{ + .{ .vgprs = 115, .sgprs = 95, .lds = 0, .private = 0, .bound = 128, .wave = 32 }, + .{ .vgprs = 115, .sgprs = 95, .lds = 0, .private = 0, .bound = 128, .wave = 32 }, + .{ .vgprs = 115, .sgprs = 95, .lds = 0, .private = 0, .bound = 128, .wave = 32 }, + .{ .vgprs = 115, .sgprs = 95, .lds = 0, .private = 0, .bound = 128, .wave = 32 }, + }), + rowsScore("tf_plan_rows_score256_bf16", 2, .{ + .{ .vgprs = 115, .sgprs = 95, .lds = 0, .private = 0, .bound = 128, .wave = 32 }, + .{ .vgprs = 115, .sgprs = 95, .lds = 0, .private = 0, .bound = 128, .wave = 32 }, + .{ .vgprs = 115, .sgprs = 95, .lds = 0, .private = 0, .bound = 128, .wave = 32 }, + .{ .vgprs = 115, .sgprs = 95, .lds = 0, .private = 0, .bound = 128, .wave = 32 }, + }), +}; diff --git a/zig/src/core/contract/inkling2_attention_metal_records.zig b/zig/src/core/contract/inkling2_attention_metal_records.zig new file mode 100644 index 00000000000..14a887d12dd --- /dev/null +++ b/zig/src/core/contract/inkling2_attention_metal_records.zig @@ -0,0 +1,15 @@ +//! Inkling 2 Mini attention launches; prompt tensor ops have no ahead-of-time M1/M2 translator. +const std = @import("std"); +const M = @import("limits.zig").MetalLaunch; +pub const records = [_]M{ + .{ .name = "metal inkling2 attention prep tf_ink2_prep", .threads = 32, .tg_memory = 0, .reserved = 32 }, + .{ .name = "metal inkling2 attention relative table tf_ink2_rel_table", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "metal inkling2 attention scalar tf_ink2_attn_scalar", .threads = 32, .tg_memory = 0, .reserved = 32 }, + .{ .name = "metal inkling2 attention merge tf_ink2_merge", .threads = 128, .tg_memory = 0, .reserved = 128 }, + .{ .name = "metal inkling2 prompt m5 tf_ink2_attn_prompt", .threads = 256, .tg_memory = 32768, .reserved = 256, .offline = false }, + .{ .name = "metal inkling2 prompt pre-m5 tf_ink2_attn_prompt", .threads = 256, .tg_memory = 32768, .reserved = 256, .offline = false }, +}; + +test "Inkling 2 Metal launches respect their resource declarations" { + try std.testing.expectEqual(@as(usize, 0), try @import("registry.zig").checkMetal(std.testing.allocator, &records, true)); +} diff --git a/zig/tests/cuda/contract_inkling2_attn_ref.zig b/zig/src/core/contract/inkling2_attn_ref.zig similarity index 51% rename from zig/tests/cuda/contract_inkling2_attn_ref.zig rename to zig/src/core/contract/inkling2_attn_ref.zig index 6fde5cee62a..e69b48464ad 100644 --- a/zig/tests/cuda/contract_inkling2_attn_ref.zig +++ b/zig/src/core/contract/inkling2_attn_ref.zig @@ -1,27 +1,24 @@ -//! Inkling 2's attention in float64, each device rounding point named: the fixed reference of the attn contract. +//! Inkling 2's attention in float64, each device rounding point named: the fixed reference of the attn contracts. const std = @import("std"); -const core = @import("core"); - -const contract = core.contract; -const c = contract.spec; -const sumIn = contract.rows.sumIn; +const c = @import("contract.zig"); +const gates = @import("gates.zig"); +const sumIn = @import("rows.zig").sumIn; pub const D = 128; -pub const heads = 24; // a TP=2 rank's query heads +pub const heads = 24; // a call's default query heads: CUDA's served Small rank (TP=2); a Call names its own pub const kv = 4; // and its key heads pub const group = heads / kv; pub const extent = 1024; // rel_extent: the bias covers distances 0..1023 pub const d_rel = 16; pub const qk_clip: f64 = 22.627416997969522; // config.json qk_l2_clip_threshold pub const rel_clip: f64 = 8.0; -pub const floor_pos: f64 = 128000; // log_scaling_n_floor +pub const floor_pos: f64 = 128000; // Small's log_scaling_n_floor (Mini's is 8,192: tauAt) pub const alpha: f64 = 0.1; // log_scaling_alpha pub const eps: f64 = 1e-6; // rms_norm_eps pub const scale: f64 = 0.08838834764831845; // 128^-1/2; the device's fp32 constant is within 2^-24 of it pub const max_keys = 4096 + extent; // distinct keys a row's reference walks: ring slots, then the biased distances const u: f64 = 0x1p-24; // fp32 unit roundoff -const u_mma: f64 = 0x1p-23; // a tensor-core add: its adders may truncate const u_bf: f64 = 0x1p-8; // bf16 unit roundoff (8 significant bits) const log2e: f64 = 1.4426950408889634; @@ -57,11 +54,28 @@ pub fn clipFactor(x: []const f64, thr: f64) f64 { return minNum(thr / (@sqrt(ss) + 1e-6), 1); } -/// The log-scaling factor of a global layer's q and rel at position `pos`: 1 + alpha ln(max((pos + 1) / floor, 1)). +/// The log-scaling factor of a global layer's q and rel at position `pos` with Small's floor. pub fn tau(pos: usize) f64 { - return 1 + alpha * @log(@max(@as(f64, @floatFromInt(pos + 1)) / floor_pos, 1)); + return tauAt(pos, floor_pos); +} + +/// The log-scaling factor at `pos` for a model's n_floor: 1 + alpha ln(max((pos + 1) / floor, 1)). +pub fn tauAt(pos: usize, floor: f64) f64 { + return 1 + alpha * @log(@max(@as(f64, @floatFromInt(pos + 1)) / floor, 1)); } +/// A backend's fp32 chains: adds in a q.k dot and in a 64-key tile of a row's P.V sum, and each add's unit roundoff. +pub const Chain = struct { + dot: f64, + tile: f64, + unit: f64, + + /// 8 chained mma (k16) a dot, 4 a tile and its rescale; a tensor-core add may truncate (2^-23). + pub const cuda: Chain = .{ .dot = 8 * 17, .tile = 4 * 17 + 1, .unit = 0x1p-23 }; + /// HIP's scalar IEEE adds: 128 a dot from 0, a tile's 64 keys after its rescale. + pub const hip: Chain = .{ .dot = 128, .tile = 64 + 1, .unit = u }; +}; + /// One attention call's host inputs as the device holds them (bf16 bits) and where its rows sit. pub const Call = struct { q: []const u16, // [rows][heads][D]: prep's clipped q (tau-scaled on a global layer) @@ -75,14 +89,21 @@ pub const Call = struct { ring: usize, window: usize, // 0: a global layer, every key from 0 exact: bool = false, // gate 4's rows: every p is 1 and every sum an integer below 2^24 + heads: usize = heads, // the call's query heads, then its key heads (GQA groups of heads / kv) + kv: usize = kv, + chain: Chain = .cuda, + + fn groupSize(call: *const Call) usize { + return call.heads / call.kv; + } - /// The fp32 sums' longest chain at a row: 4 mma (k16) a 64-key tile and its rescale, then the folds. + /// The fp32 sums' longest chain at a row: a 64-key tile's adds and its rescale (`chain.tile`), then the folds. fn depth(call: *const Call, pos: usize) f64 { const global = call.window == 0; const tiles: f64 = if (global) 16 else 4; // a block's tiles: a 1,024-key sub-chunk, or a 256-key chunk const chunks: f64 = @floatFromInt(if (global) pos / 16384 + 1 else 5); const subs: f64 = if (global) 16 else 0; - return tiles * (4 * 17 + 1) + 2 * (subs + chunks) + 8; + return tiles * call.chain.tile + 2 * (subs + chunks) + 8; } /// Rescales a key's weight meets (exp2f within 2 ulp, then a product): in-tile, sub-chunk and chunk folds. @@ -92,7 +113,7 @@ pub const Call = struct { } fn keyRow(call: *const Call, which: []const u16, st: usize, kvh: usize, slot: usize) []const u16 { - return which[((st * kv + kvh) * call.ring + slot) * D ..][0..D]; + return which[((st * call.kv + kvh) * call.ring + slot) * D ..][0..D]; } }; @@ -117,7 +138,7 @@ pub const Keys = struct { for (0..@min(call.ring, last + 1)) |slot| ks.add(slot, @floatFromInt((last - slot) / call.ring + 1), 0); near = last + 1; } - const tab = call.tab[(r * heads + h) * extent ..][0..extent]; + const tab = call.tab[(r * call.heads + h) * extent ..][0..extent]; for (near..pos + 1) |p| ks.add(p % call.ring, 1, if (pos - p < extent) bf(tab[pos - p]) else 0); } @@ -141,10 +162,10 @@ fn sigmoid(g: f64) f64 { pub fn row(call: *const Call, r: usize, h: usize, ks: *Keys, want: []f64, tol: []f64) void { ks.gather(call, r, h); const st = call.stream[r]; - const kvh = h / group; + const kvh = h / call.groupSize(); const pos = call.pos[r]; - const qr = call.q[(r * heads + h) * D ..][0..D]; - const z = bf(call.sink[r * heads + h]); + const qr = call.q[(r * call.heads + h) * D ..][0..D]; + const z = bf(call.sink[r * call.heads + h]); var most = z; for (0..ks.n) |i| { const kr = call.keyRow(call.k, st, kvh, ks.slot[i]); @@ -154,11 +175,11 @@ pub fn row(call: *const Call, r: usize, h: usize, ks: *Keys, want: []f64, tol: [ dot += bf(qv) * bf(kv_); // bf16 x bf16: exact in fp32, so the mma's 128 products are exact abs += @abs(bf(qv) * bf(kv_)); } - ks.s[i] = dot * scale + ks.bias[i]; // fp32 on the device: dot by 8 chained k16 mma, then scale, bias, log2e - ks.e[i] = abs * scale * 136 * u_mma + (@abs(dot * scale) + @abs(ks.bias[i])) * 6 * u; + ks.s[i] = dot * scale + ks.bias[i]; // fp32 on the device: the dot's chain (`chain.dot`), then scale, bias, log2e + ks.e[i] = abs * scale * call.chain.dot * call.chain.unit + (@abs(dot * scale) + @abs(ks.bias[i])) * 6 * u; most = maxNan(most, ks.s[i]); } - const chain = call.depth(pos) * u_mma + call.rescales(pos) * 0x1p-22; // fp32 sums and the folds' exp2f factors + const chain = call.depth(pos) * call.chain.unit + call.rescales(pos) * 0x1p-22; // fp32 sums and the folds' exp2f factors var l: f64 = @exp(z - most); // the sink: one extra logit with no value (eager_attention_forward) for (0..ks.n) |i| { ks.w[i] = @exp(ks.s[i] - most) * ks.mult[i]; @@ -167,7 +188,7 @@ pub fn row(call: *const Call, r: usize, h: usize, ks: *Keys, want: []f64, tol: [ } const p0 = @exp(z - most); const e0 = (@abs(z) * 3 + (most - z)) * u + 0x1p-22 + chain; // the sink's logit times log2e, then exp2f in fp32 - const gate = call.gate[(r * heads + h) * D ..][0..D]; + const gate = call.gate[(r * call.heads + h) * D ..][0..D]; for (0..D) |d| { var num: f64 = 0; for (0..ks.n) |i| num += ks.w[i] * bf(call.keyRow(call.v, st, kvh, ks.slot[i])[d]); @@ -188,15 +209,15 @@ pub fn row(call: *const Call, r: usize, h: usize, ks: *Keys, want: []f64, tol: [ } /// Row r, head h with every sum in `acc` and `order` over the keys one by one (gate 4), output rounded to bf16. -pub fn simulate(call: *const Call, r: usize, h: usize, acc: c.Accum, order: contract.gates.Order, p: []f64, col: []f64, out: []f64) void { +pub fn simulate(call: *const Call, r: usize, h: usize, acc: c.Accum, order: gates.Order, p: []f64, col: []f64, out: []f64) void { const st = call.stream[r]; - const kvh = h / group; + const kvh = h / call.groupSize(); const pos = call.pos[r]; const lo = if (call.window > 0) (pos + 1) -| call.window else 0; const n = pos + 1 - lo; - const qr = call.q[(r * heads + h) * D ..][0..D]; - const tab = call.tab[(r * heads + h) * extent ..][0..extent]; - const z = bf(call.sink[r * heads + h]); + const qr = call.q[(r * call.heads + h) * D ..][0..D]; + const tab = call.tab[(r * call.heads + h) * extent ..][0..extent]; + const z = bf(call.sink[r * call.heads + h]); var most = z; for (p[0..n], lo..) |*x, kp| { var dot: f64 = 0; @@ -206,7 +227,7 @@ pub fn simulate(call: *const Call, r: usize, h: usize, acc: c.Accum, order: cont } for (p[0..n]) |*x| x.* = @exp(x.* - most); const l = sumIn(acc, order, p[0..n]) + @exp(z - most); - const gate = call.gate[(r * heads + h) * D ..][0..D]; + const gate = call.gate[(r * call.heads + h) * D ..][0..D]; for (out, 0..) |*o, d| { for (col[0..n], p[0..n], lo..) |*x, w, kp| x.* = w * bf(call.keyRow(call.v, st, kvh, kp % call.ring)[d]); const y = sumIn(acc, order, col[0..n]) / l * sigmoid(bf(gate[d])); @@ -223,3 +244,99 @@ test "rn rounds once to nearest even and keeps bf16 values" { try std.testing.expectEqual(@as(f64, 1), minNum(std.math.nan(f64), 1)); try std.testing.expectEqual(@as(f64, 1), tau(127998)); } + +test "a call carries its rank's heads, key heads and chains; tau takes the model's floor" { + try std.testing.expectEqual(@as(f64, 1), tauAt(8191, 8192)); + try std.testing.expectApproxEqAbs(1 + 0.1 * @log(2.0), tauAt(16383, 8192), 1e-15); + try std.testing.expectEqual(tau(300000), tauAt(300000, floor_pos)); + const call: Call = .{ .q = &.{}, .k = &.{}, .v = &.{}, .tab = &.{}, .sink = &.{}, .gate = &.{}, .pos = &.{}, .stream = &.{}, .ring = 4096, .window = 0 }; + try std.testing.expectEqual(@as(usize, heads), call.heads); + try std.testing.expectEqual(@as(usize, kv), call.kv); + try std.testing.expectEqual(Chain.cuda, call.chain); + try std.testing.expect(Chain.hip.unit < Chain.cuda.unit and Chain.hip.tile < Chain.cuda.tile); +} + +fn pinned(i: usize, m: usize) u16 { + const x: f32 = @floatFromInt(@as(i64, @intCast((i * 37 + m) % 29)) - 14); + return c.toBf16(x * 0.0625); +} + +test "CUDA's defaults keep the bits the reference had in zig/tests/cuda (#4125)" { + var q: [heads * D]u16 = undefined; + var k: [kv * 128 * D]u16 = undefined; + var v: [kv * 128 * D]u16 = undefined; + var tab: [heads * extent]u16 = undefined; + var sink: [heads]u16 = undefined; + var gate: [heads * D]u16 = undefined; + for ([_][]u16{ &q, &k, &v, &tab, &gate, &sink }, 1..) |x, m| for (x, 0..) |*e, i| { + e.* = pinned(i, m); + }; + var pos = [_]usize{100}; + var st = [_]usize{0}; + const want = [2][4]u64{ .{ 0xbfc6dd62d3109c22, 0xbfbd967537eb01a7, 0x3f64049c6441daa5, 0x3f584dec199b1a8c }, .{ 0xbfc2ef9685604c58, 0xbfbd36245440324a, 0x3f617d0618cb7670, 0x3f579dc3fed2449e } }; + for ([_]usize{ 0, 32 }, want) |window, bits_| { + const call: Call = .{ .q = &q, .k = &k, .v = &v, .tab = &tab, .sink = &sink, .gate = &gate, .pos = &pos, .stream = &st, .ring = 128, .window = window }; + var ks: Keys = .{}; + var w: [D]f64 = undefined; + var t: [D]f64 = undefined; + row(&call, 0, 13, &ks, &w, &t); + const got = [4]u64{ @bitCast(w[0]), @bitCast(w[77]), @bitCast(t[0]), @bitCast(t[77]) }; + try std.testing.expectEqualSlices(u64, &bits_, &got); + } +} + +// bits from the base file (5c1fea67f:zig/tests/cuda/contract_inkling2_attn_ref.zig) on these inputs +test "CUDA's defaults keep the base bits past the extent, on a full window, the exact branch, gate 4 and tau" { + const a = std.testing.allocator; + const ring = 128; + const q = try a.alloc(u16, 2 * heads * D); + defer a.free(q); + const k = try a.alloc(u16, kv * ring * D); + defer a.free(k); + const v = try a.alloc(u16, k.len); + defer a.free(v); + const tab = try a.alloc(u16, 2 * heads * extent); + defer a.free(tab); + const sink = try a.alloc(u16, 2 * heads); + defer a.free(sink); + const gate = try a.alloc(u16, 2 * heads * D); + defer a.free(gate); + for ([_][]u16{ q, k, v, tab, gate, sink }, 1..) |x, m| for (x, 0..) |*e, i| { + e.* = pinned(i, m); + }; + q[(1 * heads + 13) * D + 3] = c.toBf16(std.math.nan(f32)); + sink[1 * heads + 7] = c.toBf16(std.math.inf(f32)); + const st = [_]usize{ 0, 0 }; + const Case = struct { pos: [2]usize, window: usize, exact: bool, r: usize, h: usize, bits: ?[4]u64 }; + const cases = [_]Case{ + .{ .pos = .{ 5000, 5001 }, .window = 0, .exact = false, .r = 0, .h = 13, .bits = .{ 0xbfc94c2fe7b239f9, 0xbfbbd5eb445673c4, 0x3f65377f773ff541, 0x3f571c5526af1cd6 } }, + .{ .pos = .{ 2000, 2001 }, .window = 1024, .exact = false, .r = 0, .h = 5, .bits = .{ 0x3fc15c3191d15f7c, 0x3fd77f821709cc70, 0x3f5c6a56e75e29fd, 0x3f735aa88f30c395 } }, + .{ .pos = .{ 300, 301 }, .window = 1024, .exact = true, .r = 0, .h = 0, .bits = .{ 0xbfc56a13a38f6bbf, 0xbfc0eaa55736282d, 0x3f456b149c7b1678, 0x3f40eb7056f63eb7 } }, + .{ .pos = .{ 300, 301 }, .window = 0, .exact = false, .r = 1, .h = 13, .bits = null }, // a NaN q: want and tol NaN + .{ .pos = .{ 300, 301 }, .window = 0, .exact = false, .r = 1, .h = 7, .bits = null }, // a +inf sink: want and tol NaN + }; + const ks = try a.create(Keys); + defer a.destroy(ks); + for (cases) |cs| { + const call: Call = .{ .q = q, .k = k, .v = v, .tab = tab, .sink = sink, .gate = gate, .pos = &cs.pos, .stream = &st, .ring = ring, .window = cs.window, .exact = cs.exact }; + var w: [D]f64 = undefined; + var t: [D]f64 = undefined; + row(&call, cs.r, cs.h, ks, &w, &t); + if (cs.bits) |b| { + try std.testing.expectEqualSlices(u64, &b, &.{ @bitCast(w[0]), @bitCast(w[77]), @bitCast(t[0]), @bitCast(t[77]) }); + } else for (w, t) |x, y| try std.testing.expect(std.math.isNan(x) and std.math.isNan(y)); + } + const p = try a.alloc(f64, 5001); + defer a.free(p); + const col = try a.alloc(f64, 5001); + defer a.free(col); + const sp = [_]usize{ 5000, 5001 }; + const call: Call = .{ .q = q, .k = k, .v = v, .tab = tab, .sink = sink, .gate = gate, .pos = &sp, .stream = &st, .ring = ring, .window = 0 }; + var o: [D]f64 = undefined; + simulate(&call, 0, 12, .f32, .sequential, p, col, &o); + try std.testing.expectEqualSlices(u64, &.{ 0x3fd4c00000000000, 0xbfc2200000000000 }, &.{ @bitCast(o[0]), @bitCast(o[77]) }); + simulate(&call, 0, 12, .bf16, .pairwise, p, col, &o); + try std.testing.expectEqualSlices(u64, &.{ 0x3fd4e00000000000, 0xbfc2000000000000 }, &.{ @bitCast(o[0]), @bitCast(o[77]) }); + for ([_]usize{ 127999, 128000, 300000, 1048575 }, [_]u64{ 0x3ff0000000000000, 0x3ff00000d1b6e1a9, 0x3ff15ce10ac9824d, 0x3ff35d741b82a5cf }) |pos, b| + try std.testing.expectEqual(b, @as(u64, @bitCast(tau(pos)))); +} diff --git a/zig/src/core/contract/inkling2_cuda_records.zig b/zig/src/core/contract/inkling2_cuda_records.zig index a448fb73d8d..b24f4ea1efe 100644 --- a/zig/src/core/contract/inkling2_cuda_records.zig +++ b/zig/src/core/contract/inkling2_cuda_records.zig @@ -1,7 +1,8 @@ //! Inkling 2's CUDA kernels: their compile records, one file per kernel group. const attn = @import("inkling2_attn_records.zig"); const ops = @import("inkling2_ops_records.zig"); +const experts = @import("inkling2_experts_records.zig"); -pub const cuda = attn.cuda ++ ops.cuda; -pub const cuda_132 = attn.cuda_132 ++ ops.cuda_132; -pub const cuda_133 = attn.cuda_133 ++ ops.cuda_133; +pub const cuda = attn.cuda ++ ops.cuda ++ experts.cuda; +pub const cuda_132 = attn.cuda_132 ++ ops.cuda_132 ++ experts.cuda_132; +pub const cuda_133 = attn.cuda_133 ++ ops.cuda_133 ++ experts.cuda_133; diff --git a/zig/src/core/contract/inkling2_dspark_metal_records.zig b/zig/src/core/contract/inkling2_dspark_metal_records.zig new file mode 100644 index 00000000000..a4cb19399da --- /dev/null +++ b/zig/src/core/contract/inkling2_dspark_metal_records.zig @@ -0,0 +1,15 @@ +//! Mini DSpark Metal launches (zig/tests/contract/metal_inkling2_dspark.zig). +const M = @import("limits.zig").MetalLaunch; +pub const records = [_]M{ + .{ .name = "metal inkling2 dspark init_rows tf_ink2_dspark_init_rows", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "metal inkling2 dspark fuse_taps tf_ink2_dspark_fuse_taps", .threads = 256, .tg_memory = 32, .reserved = 256 }, + .{ .name = "metal inkling2 dspark block_qkv tf_ink2_dspark_block_qkv", .threads = 128, .tg_memory = 16, .reserved = 128 }, + .{ .name = "metal inkling2 dspark context_kv tf_ink2_dspark_context_kv", .threads = 128, .tg_memory = 16, .reserved = 128 }, + .{ .name = "metal inkling2 dspark attention tf_ink2_dspark_attention", .threads = 128, .tg_memory = 16, .reserved = 128 }, + .{ .name = "metal inkling2 dspark residual_norm tf_ink2_dspark_residual_norm", .threads = 256, .tg_memory = 16, .reserved = 256 }, + .{ .name = "metal inkling2 dspark swiglu tf_ink2_dspark_swiglu", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "metal inkling2 dspark kappa tf_ink2_dspark_kappa", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "metal inkling2 dspark recurrent tf_ink2_dspark_recurrent", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "metal inkling2 dspark base tf_ink2_dspark_base", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "metal inkling2 dspark logits tf_ink2_dspark_logits", .threads = 256, .tg_memory = 0, .reserved = 256 }, +}; diff --git a/zig/src/core/contract/inkling2_experts_metal_records.zig b/zig/src/core/contract/inkling2_experts_metal_records.zig new file mode 100644 index 00000000000..357a1ca88b0 --- /dev/null +++ b/zig/src/core/contract/inkling2_experts_metal_records.zig @@ -0,0 +1,22 @@ +//! Inkling 2 Mini M3 scalar Metal launches; 32 reserved threads avoid unmeasured M1/M2 receipts. +const std = @import("std"); +const M = @import("limits.zig").MetalLaunch; + +pub const records = [_]M{ + .{ .name = "metal inkling2 experts tf_ink2_nvfp4_gu", .threads = 32, .tg_memory = 0, .reserved = 32 }, + .{ .name = "metal inkling2 experts tf_ink2_nvfp4_down", .threads = 32, .tg_memory = 0, .reserved = 32 }, + .{ .name = "metal inkling2 experts tf_ink2_mxfp8_gu", .threads = 32, .tg_memory = 0, .reserved = 32 }, + .{ .name = "metal inkling2 experts tf_ink2_mxfp8_down", .threads = 32, .tg_memory = 0, .reserved = 32 }, + .{ .name = "metal inkling2 experts tf_ink2_nvfp4_quantize", .threads = 32, .tg_memory = 0, .reserved = 32 }, + .{ .name = "metal inkling2 experts tf_ink2_mxfp8_quantize", .threads = 32, .tg_memory = 0, .reserved = 32 }, + .{ .name = "metal inkling2 experts tf_ink2_combine", .threads = 32, .tg_memory = 0, .reserved = 32 }, +}; + +test "Inkling2 expert launches carry no fabricated M1/M2 compile receipts" { + for (records) |record| { + try std.testing.expectEqual(@as(u32, 0), record.m1); + try std.testing.expectEqual(@as(u32, 0), record.m2); + try std.testing.expectEqual(record.threads, record.reserved); + try std.testing.expect(std.mem.startsWith(u8, record.name, "metal inkling2 experts ")); + } +} diff --git a/zig/src/core/contract/inkling2_experts_records.zig b/zig/src/core/contract/inkling2_experts_records.zig new file mode 100644 index 00000000000..20b0945515a --- /dev/null +++ b/zig/src/core/contract/inkling2_experts_records.zig @@ -0,0 +1,27 @@ +//! Inkling 2's inkling2_experts, inkling2_vision images: every SM's compile records (nvcc 13.0, 13.2, 13.3). +const registry = @import("registry.zig"); + +/// nvcc 13.0's usage (nvcc -cubin per SM at the images' flags); 13.2 pending, 13.3 in measurements/pending_133.zig. +pub const cuda = [_]registry.CudaRecord{ + .{ .launch = .{ .name = "inkling2_experts tf_ink2x_group", .symbol = "tf_ink2x_group", .image = "inkling2_experts", .threads = 1024, .dynamic = 27648, .min_sm = 80 }, .usage = .{ .{ .regs = 28, .static = 144, .bound = 1024 }, .{ .regs = 36, .static = 144, .bound = 1024 }, .{ .regs = 36, .static = 144, .bound = 1024 }, .{ .regs = 35, .static = 144, .bound = 1024 }, .{ .regs = 35, .static = 144, .bound = 1024 } }, .later_pending = true }, + .{ .launch = .{ .name = "inkling2_experts tf_ink2x_rows", .symbol = "tf_ink2x_rows", .image = "inkling2_experts", .threads = 128, .min_sm = 80 }, .usage = .{ .{ .regs = 156, .static = 32832, .bound = 128 }, .{ .regs = 156, .static = 32832, .bound = 128 }, .{ .regs = 156, .static = 32832, .bound = 128 }, .{ .regs = 144, .static = 32832, .bound = 128 }, .{ .regs = 144, .static = 32832, .bound = 128 } }, .later_pending = true }, + .{ .launch = .{ .name = "inkling2_experts tf_ink2x_wide", .symbol = "tf_ink2x_wide", .image = "inkling2_experts", .threads = 128, .min_sm = 80 }, .usage = .{ .{ .regs = 167, .static = 4224, .bound = 128 }, .{ .regs = 165, .static = 4224, .bound = 128 }, .{ .regs = 165, .static = 4224, .bound = 128 }, .{ .regs = 128, .static = 4224, .bound = 128 }, .{ .regs = 128, .static = 4224, .bound = 128 } }, .later_pending = true }, + .{ .launch = .{ .name = "inkling2_vision tf_ink2v_attention", .symbol = "tf_ink2v_attention", .image = "inkling2_vision", .threads = 256, .dynamic = 36864, .min_sm = 80 }, .usage = .{ .{ .regs = 132, .static = 0, .bound = 256 }, .{ .regs = 132, .static = 0, .bound = 256 }, .{ .regs = 132, .static = 0, .bound = 256 }, .{ .regs = 120, .static = 0, .bound = 256 }, .{ .regs = 120, .static = 0, .bound = 256 } }, .later_pending = true }, + .{ .launch = .{ .name = "inkling2_vision tf_ink2v_embed", .symbol = "tf_ink2v_embed", .image = "inkling2_vision", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 32, .static = 0, .bound = 256 }, .{ .regs = 39, .static = 0, .bound = 256 }, .{ .regs = 39, .static = 0, .bound = 256 }, .{ .regs = 30, .static = 0, .bound = 256 }, .{ .regs = 30, .static = 0, .bound = 256 } }, .later_pending = true }, + .{ .launch = .{ .name = "inkling2_vision tf_ink2v_rope", .symbol = "tf_ink2v_rope", .image = "inkling2_vision", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 20, .static = 0, .bound = 256 }, .{ .regs = 20, .static = 0, .bound = 256 }, .{ .regs = 20, .static = 0, .bound = 256 }, .{ .regs = 14, .static = 0, .bound = 256 }, .{ .regs = 14, .static = 0, .bound = 256 } }, .later_pending = true }, + .{ .launch = .{ .name = "inkling2_vision tf_ink2v_scale_add", .symbol = "tf_ink2v_scale_add", .image = "inkling2_vision", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 11, .static = 0, .bound = 256 }, .{ .regs = 11, .static = 0, .bound = 256 }, .{ .regs = 11, .static = 0, .bound = 256 }, .{ .regs = 12, .static = 0, .bound = 256 }, .{ .regs = 12, .static = 0, .bound = 256 } }, .later_pending = true }, + .{ .launch = .{ .name = "inkling2_modelopt tf_ink2moe_plan", .symbol = "tf_ink2moe_plan", .image = "inkling2_modelopt", .threads = 32, .min_sm = 80 }, .usage = .{ .{ .regs = 46, .static = 0, .bound = 32 }, .{ .regs = 45, .static = 0, .bound = 32 }, .{ .regs = 45, .static = 0, .bound = 32 }, .{ .regs = 44, .static = 0, .bound = 32 }, .{ .regs = 44, .static = 0, .bound = 32 } }, .later_pending = true }, + .{ .launch = .{ .name = "inkling2_modelopt tf_ink2moe_up", .symbol = "tf_ink2moe_up", .image = "inkling2_modelopt", .threads = 128, .min_sm = 80 }, .usage = .{ .{ .regs = 96, .static = 0, .bound = 128 }, .{ .regs = 96, .static = 0, .bound = 128 }, .{ .regs = 96, .static = 0, .bound = 128 }, .{ .regs = 102, .static = 0, .bound = 128 }, .{ .regs = 102, .static = 0, .bound = 128 } }, .later_pending = true }, + .{ .launch = .{ .name = "inkling2_modelopt tf_ink2moe_prompt_up", .symbol = "tf_ink2moe_prompt_up", .image = "inkling2_modelopt", .threads = 128, .min_sm = 80 }, .usage = .{ .{ .regs = 180, .static = 0, .bound = 128 }, .{ .regs = 180, .static = 0, .bound = 128 }, .{ .regs = 180, .static = 0, .bound = 128 }, .{ .regs = 168, .static = 0, .bound = 128 }, .{ .regs = 168, .static = 0, .bound = 128 } }, .later_pending = true }, + .{ .launch = .{ .name = "inkling2_modelopt tf_ink2moe_act", .symbol = "tf_ink2moe_act", .image = "inkling2_modelopt", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 17, .static = 0, .bound = 256 }, .{ .regs = 18, .static = 0, .bound = 256 }, .{ .regs = 18, .static = 0, .bound = 256 }, .{ .regs = 18, .static = 0, .bound = 256 }, .{ .regs = 18, .static = 0, .bound = 256 } }, .later_pending = true }, + .{ .launch = .{ .name = "inkling2_modelopt tf_ink2moe_combine", .symbol = "tf_ink2moe_combine", .image = "inkling2_modelopt", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 19, .static = 0, .bound = 256 }, .{ .regs = 20, .static = 0, .bound = 256 }, .{ .regs = 20, .static = 0, .bound = 256 }, .{ .regs = 27, .static = 0, .bound = 256 }, .{ .regs = 27, .static = 0, .bound = 256 } }, .later_pending = true }, + .{ .launch = .{ .name = "inkling2_loop_math tf_ink2_loop_ar", .symbol = "tf_ink2_loop_ar", .image = "inkling2_loop_math", .threads = 512, .min_sm = 80 }, .usage = .{ .{ .regs = 32, .static = 656, .bound = 512 }, .{ .regs = 40, .static = 656, .bound = 512 }, .{ .regs = 40, .static = 656, .bound = 512 }, .{ .regs = 40, .static = 656, .bound = 512 }, .{ .regs = 40, .static = 656, .bound = 512 } }, .later_pending = true }, + .{ .launch = .{ .name = "inkling2_loop_math tf_ink2_loop_messages", .symbol = "tf_ink2_loop_messages", .image = "inkling2_loop_math", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 26, .static = 272, .bound = 256 }, .{ .regs = 28, .static = 272, .bound = 256 }, .{ .regs = 28, .static = 272, .bound = 256 }, .{ .regs = 32, .static = 272, .bound = 256 }, .{ .regs = 36, .static = 272, .bound = 256 } }, .later_pending = true }, + .{ .launch = .{ .name = "inkling2_loop_math tf_ink2_loop_gate", .symbol = "tf_ink2_loop_gate", .image = "inkling2_loop_math", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 32, .static = 392, .bound = 256 }, .{ .regs = 40, .static = 392, .bound = 256 }, .{ .regs = 40, .static = 392, .bound = 256 }, .{ .regs = 36, .static = 392, .bound = 256 }, .{ .regs = 36, .static = 392, .bound = 256 } }, .later_pending = true }, + .{ .launch = .{ .name = "inkling2_loop_math tf_ink2_loop_project_qkv", .symbol = "tf_ink2_loop_project_qkv", .image = "inkling2_loop_math", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 30, .static = 2048, .bound = 256 }, .{ .regs = 35, .static = 2048, .bound = 256 }, .{ .regs = 35, .static = 2048, .bound = 256 }, .{ .regs = 42, .static = 2048, .bound = 256 }, .{ .regs = 42, .static = 2048, .bound = 256 } }, .later_pending = true }, + .{ .launch = .{ .name = "inkling2_loop_math tf_ink2_loop_round_bf16", .symbol = "tf_ink2_loop_round_bf16", .image = "inkling2_loop_math", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 10, .static = 0, .bound = 256 }, .{ .regs = 10, .static = 0, .bound = 256 }, .{ .regs = 10, .static = 0, .bound = 256 }, .{ .regs = 10, .static = 0, .bound = 256 }, .{ .regs = 10, .static = 0, .bound = 256 } }, .later_pending = true }, +}; +/// nvcc 13.2's, where it differs: none measured (no 13.2 compiler), so later_pending keeps every launch pending. +pub const cuda_132 = [_]registry.Override{}; +/// nvcc 13.3's: none here, as later_pending reads 13.3 from measurements/pending_133.zig (all seven launches). +pub const cuda_133 = [_]registry.Override{}; diff --git a/zig/src/core/contract/inkling2_glue_metal_records.zig b/zig/src/core/contract/inkling2_glue_metal_records.zig new file mode 100644 index 00000000000..e0013f02bae --- /dev/null +++ b/zig/src/core/contract/inkling2_glue_metal_records.zig @@ -0,0 +1,13 @@ +//! Inkling 2 Mini glue launches (zig/tests/contract/metal_inkling2_glue.zig). +const M = @import("limits.zig").MetalLaunch; +pub const records = [_]M{ + .{ .name = "metal inkling2 glue embed_norm tf_inkling2_embed_norm", .threads = 256, .tg_memory = 48, .reserved = 256 }, + .{ .name = "metal inkling2 glue ar tf_inkling2_ar", .threads = 256, .tg_memory = 368, .reserved = 256 }, + .{ .name = "metal inkling2 glue conv_static tf_inkling2_conv_static", .threads = 32, .tg_memory = 0, .reserved = 32 }, + .{ .name = "metal inkling2 glue conv_dynamic tf_inkling2_conv_dynamic", .threads = 256, .tg_memory = 128, .reserved = 256 }, + .{ .name = "metal inkling2 glue router tf_inkling2_router", .threads = 256, .tg_memory = 576, .reserved = 256 }, + .{ .name = "metal inkling2 glue swiglu tf_inkling2_swiglu", .threads = 32, .tg_memory = 0, .reserved = 32 }, + .{ .name = "metal inkling2 glue logits tf_inkling2_logits", .threads = 32, .tg_memory = 0, .reserved = 32 }, + .{ .name = "metal inkling2 glue expert_pick tf_inkling2_expert_pick", .threads = 32, .tg_memory = 0, .reserved = 32 }, + .{ .name = "metal inkling2 glue expert_combine tf_inkling2_expert_combine", .threads = 32, .tg_memory = 0, .reserved = 32 }, +}; diff --git a/zig/src/core/contract/inkling2_loop_metal_records.zig b/zig/src/core/contract/inkling2_loop_metal_records.zig new file mode 100644 index 00000000000..8f32f1a7ab5 --- /dev/null +++ b/zig/src/core/contract/inkling2_loop_metal_records.zig @@ -0,0 +1,6 @@ +//! Inkling 2 Mini loop launches (zig/tests/contract/metal_inkling2_loop.zig). +const M = @import("limits.zig").MetalLaunch; +pub const records = [_]M{ + .{ .name = "metal inkling2 loop messages tf_inkling2_loop_messages", .threads = 256, .tg_memory = 144, .reserved = 256 }, + .{ .name = "metal inkling2 loop gates tf_inkling2_loop_gates", .threads = 256, .tg_memory = 9552, .reserved = 256 }, +}; diff --git a/zig/src/core/contract/inkling2_ops_records.zig b/zig/src/core/contract/inkling2_ops_records.zig index e5ce0103f66..ca64067c034 100644 --- a/zig/src/core/contract/inkling2_ops_records.zig +++ b/zig/src/core/contract/inkling2_ops_records.zig @@ -4,7 +4,7 @@ const registry = @import("registry.zig"); /// nvcc 13.0's usage (nvcc -cubin per SM at the images' flags), the compiler of the release fatbins; 13.2 pending. pub const cuda = [_]registry.CudaRecord{ .{ .launch = .{ .name = "inkling2 ops tf_ink2_embed", .symbol = "tf_ink2_embed", .image = "inkling2_ops", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 21, .static = 128, .bound = 256 }, .{ .regs = 19, .static = 128, .bound = 256 }, .{ .regs = 19, .static = 128, .bound = 256 }, .{ .regs = 22, .static = 128, .bound = 256 }, .{ .regs = 22, .static = 128, .bound = 256 } } }, - .{ .launch = .{ .name = "inkling2 ops tf_ink2_mix", .symbol = "tf_ink2_mix", .image = "inkling2_ops", .threads = 512, .min_sm = 80 }, .usage = .{ .{ .regs = 76, .static = 45712, .bound = 512 }, .{ .regs = 76, .static = 45712, .bound = 512 }, .{ .regs = 76, .static = 45712, .bound = 512 }, .{ .regs = 76, .static = 45712, .bound = 512 }, .{ .regs = 76, .static = 45712, .bound = 512 } } }, + .{ .launch = .{ .name = "inkling2 ops tf_ink2_mix", .symbol = "tf_ink2_mix", .image = "inkling2_ops", .threads = 512, .min_sm = 80 }, .usage = .{ .{ .regs = 64, .static = 45712, .bound = 512 }, .{ .regs = 62, .static = 45712, .bound = 512 }, .{ .regs = 62, .static = 45712, .bound = 512 }, .{ .regs = 72, .static = 45712, .bound = 512 }, .{ .regs = 72, .static = 45712, .bound = 512 } } }, .{ .launch = .{ .name = "inkling2 ops tf_ink2_mix_rows", .symbol = "tf_ink2_mix_rows", .image = "inkling2_ops", .threads = 512, .min_sm = 80 }, .usage = .{ .{ .regs = 32, .static = 656, .bound = 512 }, .{ .regs = 40, .static = 656, .bound = 512 }, .{ .regs = 40, .static = 656, .bound = 512 }, .{ .regs = 40, .static = 656, .bound = 512 }, .{ .regs = 40, .static = 656, .bound = 512 } } }, .{ .launch = .{ .name = "inkling2 ops tf_ink2_rowdot", .symbol = "tf_ink2_rowdot", .image = "inkling2_ops", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 32, .static = 0, .bound = 256 }, .{ .regs = 40, .static = 0, .bound = 256 }, .{ .regs = 40, .static = 0, .bound = 256 }, .{ .regs = 38, .static = 0, .bound = 256 }, .{ .regs = 38, .static = 0, .bound = 256 } } }, .{ .launch = .{ .name = "inkling2 ops tf_ink2_topk", .symbol = "tf_ink2_topk", .image = "inkling2_ops", .threads = 512, .min_sm = 80 }, .usage = .{ .{ .regs = 24, .static = 384, .bound = 512 }, .{ .regs = 23, .static = 384, .bound = 512 }, .{ .regs = 23, .static = 384, .bound = 512 }, .{ .regs = 36, .static = 384, .bound = 512 }, .{ .regs = 36, .static = 384, .bound = 512 } } }, diff --git a/zig/src/core/contract/inkling2_runtime_metal_records.zig b/zig/src/core/contract/inkling2_runtime_metal_records.zig new file mode 100644 index 00000000000..4f1a7ffc40f --- /dev/null +++ b/zig/src/core/contract/inkling2_runtime_metal_records.zig @@ -0,0 +1,10 @@ +//! Inkling 2 Mini runtime helper launches (zig/tests/contract/metal_inkling2_runtime.zig). +const M = @import("limits.zig").MetalLaunch; +pub const records = [_]M{ + .{ .name = "metal inkling2 runtime copy_bf16 tf_ink2_copy_bf16", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "metal inkling2 runtime copy_f32 tf_ink2_copy_f32", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "metal inkling2 runtime widen tf_ink2_widen", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "metal inkling2 runtime attention_partial tf_ink2_attention_partial", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "metal inkling2 runtime mlp_partial tf_ink2_mlp_partial", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "metal inkling2 runtime capture_tap tf_ink2_capture_tap", .threads = 256, .tg_memory = 0, .reserved = 256 }, +}; diff --git a/zig/src/core/contract/measurements/pending_133.zig b/zig/src/core/contract/measurements/pending_133.zig index c89f898270c..56af8cdf40d 100644 --- a/zig/src/core/contract/measurements/pending_133.zig +++ b/zig/src/core/contract/measurements/pending_133.zig @@ -5,6 +5,13 @@ pub const records = [_]Override{ .{ .name = "exl3_experts tf_exl3_grouped_0", .usage = .{ .{ .regs = 128, .static = 32832, .bound = 0 }, .{ .regs = 128, .static = 32832, .bound = 0 }, .{ .regs = 128, .static = 32832, .bound = 0 }, .{ .regs = 158, .static = 32832, .bound = 0 }, .{ .regs = 158, .static = 32832, .bound = 0 } } }, .{ .name = "exl3_experts tf_exl3_grouped_1", .usage = .{ .{ .regs = 128, .static = 32832, .bound = 0 }, .{ .regs = 128, .static = 32832, .bound = 0 }, .{ .regs = 128, .static = 32832, .bound = 0 }, .{ .regs = 158, .static = 32832, .bound = 0 }, .{ .regs = 158, .static = 32832, .bound = 0 } } }, .{ .name = "exl3_experts tf_exl3_grouped_2", .usage = .{ .{ .regs = 128, .static = 32832, .bound = 0 }, .{ .regs = 128, .static = 32832, .bound = 0 }, .{ .regs = 128, .static = 32832, .bound = 0 }, .{ .regs = 148, .static = 32832, .bound = 0 }, .{ .regs = 148, .static = 32832, .bound = 0 } } }, + .{ .name = "inkling2_experts tf_ink2x_group", .usage = .{ .{ .regs = 28, .static = 144, .bound = 1024 }, .{ .regs = 36, .static = 144, .bound = 1024 }, .{ .regs = 36, .static = 144, .bound = 1024 }, .{ .regs = 35, .static = 144, .bound = 1024 }, .{ .regs = 35, .static = 144, .bound = 1024 } } }, + .{ .name = "inkling2_experts tf_ink2x_rows", .usage = .{ .{ .regs = 156, .static = 32832, .bound = 128 }, .{ .regs = 156, .static = 32832, .bound = 128 }, .{ .regs = 156, .static = 32832, .bound = 128 }, .{ .regs = 144, .static = 32832, .bound = 128 }, .{ .regs = 144, .static = 32832, .bound = 128 } } }, + .{ .name = "inkling2_experts tf_ink2x_wide", .usage = .{ .{ .regs = 167, .static = 4224, .bound = 128 }, .{ .regs = 165, .static = 4224, .bound = 128 }, .{ .regs = 165, .static = 4224, .bound = 128 }, .{ .regs = 128, .static = 4224, .bound = 128 }, .{ .regs = 128, .static = 4224, .bound = 128 } } }, + .{ .name = "inkling2_vision tf_ink2v_attention", .usage = .{ .{ .regs = 132, .static = 0, .bound = 256 }, .{ .regs = 132, .static = 0, .bound = 256 }, .{ .regs = 132, .static = 0, .bound = 256 }, .{ .regs = 128, .static = 0, .bound = 256 }, .{ .regs = 128, .static = 0, .bound = 256 } } }, + .{ .name = "inkling2_vision tf_ink2v_embed", .usage = .{ .{ .regs = 32, .static = 0, .bound = 256 }, .{ .regs = 39, .static = 0, .bound = 256 }, .{ .regs = 39, .static = 0, .bound = 256 }, .{ .regs = 30, .static = 0, .bound = 256 }, .{ .regs = 30, .static = 0, .bound = 256 } } }, + .{ .name = "inkling2_vision tf_ink2v_rope", .usage = .{ .{ .regs = 20, .static = 0, .bound = 256 }, .{ .regs = 20, .static = 0, .bound = 256 }, .{ .regs = 20, .static = 0, .bound = 256 }, .{ .regs = 14, .static = 0, .bound = 256 }, .{ .regs = 14, .static = 0, .bound = 256 } } }, + .{ .name = "inkling2_vision tf_ink2v_scale_add", .usage = .{ .{ .regs = 11, .static = 0, .bound = 256 }, .{ .regs = 11, .static = 0, .bound = 256 }, .{ .regs = 11, .static = 0, .bound = 256 }, .{ .regs = 12, .static = 0, .bound = 256 }, .{ .regs = 12, .static = 0, .bound = 256 } } }, .{ .name = "exl3_grouped tf_ctl_exl3_grouped_old_0", .usage = .{ .{ .regs = 128, .static = 32832, .bound = 0 }, .{ .regs = 128, .static = 32832, .bound = 0 }, .{ .regs = 128, .static = 32832, .bound = 0 }, .{ .regs = 127, .static = 32832, .bound = 0 }, .{ .regs = 127, .static = 32832, .bound = 0 } } }, .{ .name = "exl3_grouped tf_ctl_exl3_grouped_old_1", .usage = .{ .{ .regs = 128, .static = 32832, .bound = 0 }, .{ .regs = 128, .static = 32832, .bound = 0 }, .{ .regs = 128, .static = 32832, .bound = 0 }, .{ .regs = 128, .static = 32832, .bound = 0 }, .{ .regs = 128, .static = 32832, .bound = 0 } } }, .{ .name = "exl3_grouped tf_ctl_exl3_grouped_old_2", .usage = .{ .{ .regs = 128, .static = 32832, .bound = 0 }, .{ .regs = 128, .static = 32832, .bound = 0 }, .{ .regs = 128, .static = 32832, .bound = 0 }, .{ .regs = 128, .static = 32832, .bound = 0 }, .{ .regs = 128, .static = 32832, .bound = 0 } } }, @@ -68,4 +75,12 @@ pub const records = [_]Override{ .{ .name = "mla tf_mla_rope", .usage = .{ .{ .regs = 26, .static = 0, .bound = 32 }, .{ .regs = 26, .static = 0, .bound = 32 }, .{ .regs = 26, .static = 0, .bound = 32 }, .{ .regs = 22, .static = 0, .bound = 32 }, .{ .regs = 22, .static = 0, .bound = 32 } } }, .{ .name = "mla tf_mla_gate", .usage = .{ .{ .regs = 16, .static = 0, .bound = 0 }, .{ .regs = 16, .static = 0, .bound = 0 }, .{ .regs = 16, .static = 0, .bound = 0 }, .{ .regs = 12, .static = 0, .bound = 0 }, .{ .regs = 12, .static = 0, .bound = 0 } } }, .{ .name = "exl3_experts tf_exl3_plan_finish_after", .usage = .{ .{ .regs = 40, .static = 0, .bound = 0 }, .{ .regs = 40, .static = 0, .bound = 0 }, .{ .regs = 40, .static = 0, .bound = 0 }, .{ .regs = 40, .static = 0, .bound = 0 }, .{ .regs = 40, .static = 0, .bound = 0 } } }, + .{ .name = "ricursive tf_rc_embed", .usage = .{ .{ .regs = 14, .static = 0, .bound = 256 }, .{ .regs = 14, .static = 0, .bound = 256 }, .{ .regs = 14, .static = 0, .bound = 256 }, .{ .regs = 14, .static = 0, .bound = 256 }, .{ .regs = 14, .static = 0, .bound = 256 } } }, + .{ .name = "ricursive tf_rc_add_norm", .usage = .{ .{ .regs = 80, .static = 32, .bound = 256 }, .{ .regs = 79, .static = 32, .bound = 256 }, .{ .regs = 79, .static = 32, .bound = 256 }, .{ .regs = 79, .static = 32, .bound = 256 }, .{ .regs = 79, .static = 32, .bound = 256 } } }, + .{ .name = "ricursive tf_rc_gate", .usage = .{ .{ .regs = 15, .static = 0, .bound = 256 }, .{ .regs = 14, .static = 0, .bound = 256 }, .{ .regs = 14, .static = 0, .bound = 256 }, .{ .regs = 14, .static = 0, .bound = 256 }, .{ .regs = 14, .static = 0, .bound = 256 } } }, + .{ .name = "ricursive tf_rc_silu_clamp", .usage = .{ .{ .regs = 17, .static = 0, .bound = 256 }, .{ .regs = 18, .static = 0, .bound = 256 }, .{ .regs = 18, .static = 0, .bound = 256 }, .{ .regs = 19, .static = 0, .bound = 256 }, .{ .regs = 19, .static = 0, .bound = 256 } } }, + .{ .name = "ricursive_prep tf_rc_prep", .usage = .{ .{ .regs = 32, .static = 0, .bound = 256 }, .{ .regs = 38, .static = 0, .bound = 256 }, .{ .regs = 38, .static = 0, .bound = 256 }, .{ .regs = 36, .static = 0, .bound = 256 }, .{ .regs = 36, .static = 0, .bound = 256 } } }, + .{ .name = "ricursive_prep tf_rc_prep_rows", .usage = .{ .{ .regs = 38, .static = 0, .bound = 256 }, .{ .regs = 38, .static = 0, .bound = 256 }, .{ .regs = 38, .static = 0, .bound = 256 }, .{ .regs = 38, .static = 0, .bound = 256 }, .{ .regs = 38, .static = 0, .bound = 256 } } }, + .{ .name = "window attention wattn_kernel<128, 8, 2, 8>", .usage = .{ .{ .regs = 222, .static = 0, .bound = 256 }, .{ .regs = 222, .static = 0, .bound = 256 }, .{ .regs = 222, .static = 0, .bound = 256 }, .{ .regs = 218, .static = 0, .bound = 256 }, .{ .regs = 218, .static = 0, .bound = 256 } } }, + .{ .name = "window attention tf_window_prompt_h2_pg", .usage = .{ .{ .regs = 222, .static = 0, .bound = 256 }, .{ .regs = 222, .static = 0, .bound = 256 }, .{ .regs = 222, .static = 0, .bound = 256 }, .{ .regs = 231, .static = 0, .bound = 256 }, .{ .regs = 231, .static = 0, .bound = 256 } } }, }; diff --git a/zig/src/core/contract/registry.zig b/zig/src/core/contract/registry.zig index 7f7e8b0a4b2..bfd934a42f2 100644 --- a/zig/src/core/contract/registry.zig +++ b/zig/src/core/contract/registry.zig @@ -245,7 +245,7 @@ pub fn usageFor(r: CudaRecord, release: ?limits.Nvcc) [limits.sms.len]U { } return u; } -/// Restored Qwen launches retain a pending entry wherever a compiler receipt is absent. +/// Restored Qwen launches, and Ripple's unmeasured ones, retain a pending entry wherever a compiler receipt is absent. pub const cuda_pending = joins.cuda_pending; /// Gate 5's planted CUDA controls: a launch past its __launch_bounds__, one needing more registers than a block has. pub const cuda_controls = [_]CudaRecord{ @@ -298,8 +298,14 @@ pub const metal = joins.metal_before ++ [_]M{ .{ .name = "simd_qmm_bits tf_sqw_mma_q3_16_4_1", .threads = 512, .tg_memory = 16384, .adapts = true, .m1 = 512, .m2 = 512 }, .{ .name = "simd_qmm_bits tf_sqw_mma_q6_16_4_1", .threads = 512, .tg_memory = 16384, .adapts = true, .m1 = 512, .m2 = 512 }, .{ .name = "simd_qmm_bits tf_sqw_mma_q8_16_4_1", .threads = 512, .tg_memory = 16384, .adapts = true, .m1 = 224, .m2 = 224 }, + .{ .name = "lane order q5 tf_lane_order_q5", .threads = 256, .tg_memory = 1280, .m1 = 1024, .m2 = 1024 }, + .{ .name = "lane order q6 tf_lane_order_q6", .threads = 256, .tg_memory = 1536, .m1 = 1024, .m2 = 1024 }, .{ .name = "lane projection q6 g32 sk1 tf_lane", .threads = 32, .tg_memory = 3072, .offline = false }, .{ .name = "lane projection q6 g32 sk4 tf_lane", .threads = 128, .tg_memory = 10240, .offline = false }, + .{ .name = "lane projection q5 g64 reg sk1 tf_lane_reg", .threads = 32, .tg_memory = 0, .offline = false }, + .{ .name = "lane projection q5 g64 reg sk8 tf_lane_reg", .threads = 256, .tg_memory = 14336, .offline = false }, + .{ .name = "lane projection q6 g64 reg sk1 tf_lane_reg", .threads = 32, .tg_memory = 0, .offline = false }, + .{ .name = "lane projection q6 g64 reg sk8 tf_lane_reg", .threads = 256, .tg_memory = 14336, .offline = false }, .{ .name = "tile_qmm q4 tf_tile_qmm_q4", .threads = 128, .tg_memory = 11008, .reserved = 128 }, .{ .name = "tile_qmm grouped q4 tf_tile_qmm_grouped_q4", .threads = 128, .tg_memory = 11008, .reserved = 128 }, .{ .name = "tile_qmm grouped glu q4 tf_tile_qmm_grouped_glu_q4", .threads = 128, .tg_memory = 11008, .reserved = 128 }, diff --git a/zig/src/core/contract/registry_joins.zig b/zig/src/core/contract/registry_joins.zig index eb242206640..2789e452181 100644 --- a/zig/src/core/contract/registry_joins.zig +++ b/zig/src/core/contract/registry_joins.zig @@ -59,6 +59,9 @@ pub const cuda_pending = @import("qwen_whole_records.zig").records ++ @import("weight_only_records.zig").cuda ++ @import("hc_activation_records.zig").cuda ++ @import("qwen4_records.zig").cuda ++ + @import("ricursive_cuda_records.zig").cuda ++ + @import("ricursive_prep_records.zig").cuda ++ + @import("ricursive_attn_records.zig").cuda ++ @import("registry_media.zig").cuda_pending ++ @import("registry_media.zig").cuda_tma_pending ++ @import("h3_image_cuda_records.zig").records; @@ -104,6 +107,12 @@ pub const all_metal = @import("penalties_records.zig").records ++ @import("qwen27_moe_records.zig").records ++ @import("qwen27_prompt_records.zig").records ++ @import("affine_gather_records.zig").records ++ + @import("inkling2_attention_metal_records.zig").records ++ + @import("inkling2_glue_metal_records.zig").records ++ + @import("inkling2_experts_metal_records.zig").records ++ + @import("inkling2_loop_metal_records.zig").records ++ + @import("inkling2_runtime_metal_records.zig").records ++ + @import("inkling2_dspark_metal_records.zig").records ++ @import("flint_records.zig").records ++ @import("hy4_records.zig").metal ++ @import("uocr_records.zig").records ++ @@ -149,4 +158,10 @@ test { _ = @import("mla_cuda_records.zig"); _ = @import("h3_image_cuda_records.zig"); _ = @import("inkling2_cuda_records.zig"); + _ = @import("inkling2_attention_metal_records.zig"); + _ = @import("inkling2_glue_metal_records.zig"); + _ = @import("inkling2_experts_metal_records.zig"); + _ = @import("inkling2_loop_metal_records.zig"); + _ = @import("inkling2_runtime_metal_records.zig"); + _ = @import("inkling2_dspark_metal_records.zig"); } diff --git a/zig/src/core/contract/registry_media.zig b/zig/src/core/contract/registry_media.zig index 6ba9b54d42c..a7a975d3b7a 100644 --- a/zig/src/core/contract/registry_media.zig +++ b/zig/src/core/contract/registry_media.zig @@ -66,10 +66,13 @@ pub const cuda = [_]CudaRecord{ .{ .launch = .{ .name = "fp8_experts prompt down f32", .symbol = "_ZN14tf_fp8_experts24fp8_expert_prompt_kernelILi1ELi0ELi4ELi4EEEvPK13__nv_bfloat16iiPK5uint4PKfiiPKiSA_SA_Pvifi", .image = "fp8_experts", .threads = 128 }, .usage = .{ .{ .regs = 197, .static = 32768, .bound = 128 }, .{ .regs = 197, .static = 32768, .bound = 128 }, .{ .regs = 197, .static = 32768, .bound = 128 }, .{ .regs = 221, .static = 32768, .bound = 128 }, .{ .regs = 221, .static = 32768, .bound = 128 } } }, .{ .launch = .{ .name = "fp8_experts prompt down bf16", .symbol = "_ZN14tf_fp8_experts24fp8_expert_prompt_kernelILi1ELi3ELi4ELi4EEEvPK13__nv_bfloat16iiPK5uint4PKfiiPKiSA_SA_Pvifi", .image = "fp8_experts", .threads = 128 }, .usage = .{ .{ .regs = 197, .static = 32768, .bound = 128 }, .{ .regs = 197, .static = 32768, .bound = 128 }, .{ .regs = 197, .static = 32768, .bound = 128 }, .{ .regs = 221, .static = 32768, .bound = 128 }, .{ .regs = 221, .static = 32768, .bound = 128 } } }, }; -/// Drama 3's compact-checkpoint router, unmeasured: the GB10 check runs its contract and prints its RECORD. + +/// Launches still owed nvcc receipts; qualification refuses each SM until its receipt lands. pub const cuda_pending = [_]CudaRecord{ + // Drama 3's compact-checkpoint router, unmeasured: the GB10 check runs its contract and prints its RECORD. .{ .launch = .{ .name = "drama3 d3_router_compact", .symbol = "d3_router_compact", .image = "drama3", .threads = 256 }, .usage = @import("registry.zig").none }, - .{ .launch = .{ .name = "drama3 d3_cfg_mix", .symbol = "d3_cfg_mix", .image = "drama3", .threads = 256 }, .usage = @import("registry.zig").none }, + // GB10 (sm_121, nvcc 13.0) by docs/recipes/drama3-cuda/cfg-mix-gb10.sh; no __launch_bounds__, so 1024 fit. + .{ .launch = .{ .name = "drama3 d3_cfg_mix", .symbol = "d3_cfg_mix", .image = "drama3", .threads = 256 }, .usage = .{ .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 12, .static = 0, .bound = 0 } }, .later_pending = true }, }; /// The picture's TMA products (h3_int8_tma.cuh): sm_120's and sm_121's usage from the five-SM limits job diff --git a/zig/src/core/contract/ricursive_attn_records.zig b/zig/src/core/contract/ricursive_attn_records.zig new file mode 100644 index 00000000000..5fd0ce4f5e7 --- /dev/null +++ b/zig/src/core/contract/ricursive_attn_records.zig @@ -0,0 +1,14 @@ +//! Ripple's prompt attention on CUDA: window_attention.cu's two-heads-a-block instances, for kernel-contract-limits. +const registry = @import("registry.zig"); +const limits = @import("limits.zig"); + +/// nvcc 13.0's usage, the compiler of the release fatbins: not yet measured (every value 0). +pub const cuda = [_]registry.CudaRecord{ + .{ .launch = .{ .name = "window attention wattn_kernel<128, 8, 2, 8>", .symbol = "_ZN16tf_window_prompt12wattn_kernelILi128ELi8ELi2ELi8EEEvPK13__nv_bfloat16S3_S3_PS1_iiiiifii", .image = "window_attention", .threads = 256, .dynamic = 65536, .opt_in = true }, .usage = .{ .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 } } }, + .{ .launch = .{ .name = "window attention tf_window_prompt_h2_pg", .symbol = "tf_window_prompt_h2_pg", .image = "window_attention", .threads = 256, .dynamic = 65536, .opt_in = true }, .usage = .{ .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 } } }, +}; + +test "Ripple's prompt attention: unmeasured records cannot pass a compiled resource check" { + const t = @import("std").testing; + for (cuda) |r| try t.expectEqual(limits.sms.len, try registry.checkCuda(t.allocator, &.{r}, true)); +} diff --git a/zig/src/core/contract/ricursive_cuda_records.zig b/zig/src/core/contract/ricursive_cuda_records.zig new file mode 100644 index 00000000000..74512b42d81 --- /dev/null +++ b/zig/src/core/contract/ricursive_cuda_records.zig @@ -0,0 +1,19 @@ +//! Ripple's CUDA glue (ricursive.cu): its served launches, pending in registry.cuda_pending until nvcc's records land. +const std = @import("std"); +const registry = @import("registry.zig"); + +/// The glue's launches, 256 threads each; usage zero (no compiled record yet): gate 5 refuses them until filled. +pub const cuda = [_]registry.CudaRecord{ + .{ .launch = .{ .name = "ricursive tf_rc_embed", .symbol = "tf_rc_embed", .image = "ricursive", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 } } }, + .{ .launch = .{ .name = "ricursive tf_rc_add_norm", .symbol = "tf_rc_add_norm", .image = "ricursive", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 } } }, + .{ .launch = .{ .name = "ricursive tf_rc_gate", .symbol = "tf_rc_gate", .image = "ricursive", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 } } }, + .{ .launch = .{ .name = "ricursive tf_rc_silu_clamp", .symbol = "tf_rc_silu_clamp", .image = "ricursive", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 } } }, +}; + +test "Ripple's CUDA glue records: one served launch a symbol, on the ricursive image" { + for (cuda, 0..) |r, i| { + try std.testing.expect(std.mem.startsWith(u8, r.launch.symbol, "tf_rc_")); + try std.testing.expectEqualStrings("ricursive", r.launch.image); + for (cuda[i + 1 ..]) |o| try std.testing.expect(!std.mem.eql(u8, r.launch.symbol, o.launch.symbol)); + } +} diff --git a/zig/src/core/contract/ricursive_prep_records.zig b/zig/src/core/contract/ricursive_prep_records.zig new file mode 100644 index 00000000000..6f7f181bdd7 --- /dev/null +++ b/zig/src/core/contract/ricursive_prep_records.zig @@ -0,0 +1,19 @@ +//! Ripple's CUDA attention prep: one stream's rows, or each row at its own position and stream; a warp a head. +const registry = @import("registry.zig"); + +/// Usage zero (no nvcc 13.0 record yet); nvcc 13.3's five-SM receipts are in measurements/pending_133.zig. +pub const cuda = [_]registry.CudaRecord{ + .{ .launch = .{ .name = "ricursive_prep tf_rc_prep", .symbol = "tf_rc_prep", .image = "ricursive_prep", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 } } }, + .{ .launch = .{ .name = "ricursive_prep tf_rc_prep_rows", .symbol = "tf_rc_prep_rows", .image = "ricursive_prep", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 } } }, +}; + +test "ricursive prep CUDA: its launch is in the live registry once, at the kernel's 256 threads" { + const std = @import("std"); + const t = std.testing; + for (cuda) |r| { + var found: usize = 0; + for (registry.all_cuda) |active| found += @intFromBool(std.mem.eql(u8, active.launch.name, r.launch.name)); + try t.expectEqual(@as(usize, 1), found); + try t.expectEqual(@as(u32, 256), r.launch.threads); + } +} diff --git a/zig/src/core/cpu_weights.zig b/zig/src/core/cpu_weights.zig new file mode 100644 index 00000000000..428478b0cca --- /dev/null +++ b/zig/src/core/cpu_weights.zig @@ -0,0 +1,5 @@ +//! Shared mapped weight formats and exact value decoders without an engine or graphics backend. +pub const safetensors = @import("safetensors.zig"); +pub const bf16_round = @import("bf16_round"); +pub const gguf = @import("gguf.zig"); +pub const gguf_source_reference = @import("gguf_repack_ref.zig"); diff --git a/zig/src/core/engine_api.zig b/zig/src/core/engine_api.zig index 2f8dd66fa73..50f2fd9b498 100644 --- a/zig/src/core/engine_api.zig +++ b/zig/src/core/engine_api.zig @@ -46,6 +46,9 @@ pub const VideoOffer = vision_types.VideoOffer; pub const VisionOpen = vision_types.VisionOpen; pub const ImageShare = vision_types.ImageShare; pub const Size = vision_types.Size; +pub const visionGate = vision_types.gate; +pub const visionDeclared = vision_types.declared; +pub const visionWords = vision_types.words; pub const ocr = @import("engine_ocr.zig"); pub const SpeechRequest = @import("speech_api.zig").SpeechRequest; @@ -300,6 +303,9 @@ pub const Open = struct { execution_witness: bool = false, // --execution-witness: an engine on a supported path attests it (Info.witness) rank: u32 = 0, given: Given = .{}, + /// The build's release (rank aliases retire by it) and where `tp` came from, for the start-up line. + release: []const u8 = "", + launch_from: []const u8 = "", master: []const u8 = "", master_port: u16 = 29551, /// --policy: the engine's policy as `key=value,...`; empty: its defaults. @@ -517,5 +523,6 @@ pub const save_guard = @import("save_guard"); test { _ = @import("engine_api_test.zig"); + _ = vision_types; _ = @import("engine_capabilities.zig"); } diff --git a/zig/src/core/engine_vision.zig b/zig/src/core/engine_vision.zig index 1f0ae2720c7..32daef60ec6 100644 --- a/zig/src/core/engine_vision.zig +++ b/zig/src/core/engine_vision.zig @@ -92,3 +92,48 @@ pub const VideoOffer = struct { /// --vision's limits (``Open.vision``); image_tokens_set: the flag given; image_share: --vision-image-share's value. pub const VisionOpen = struct { image_tokens: u32 = 4096, image_tokens_set: bool = false, max_images: u32 = 4, video_tokens: u32 = 16384, max_videos: u32 = 2, max_frames: u32 = 256, image_share: ImageShare = .request }; + +/// --vision against the checkpoint: given without a tower, refused by name; a tower without it stays unread. +pub fn gate(requested: bool, tower: bool) error{VisionWithoutTower}!bool { + if (requested and !tower) return error.VisionWithoutTower; + return requested; +} + +/// Whether config.json's bytes name a vision_config other than null; JSON that does not parse counts as one. +pub fn declared(a: Allocator, config: []const u8) bool { + const doc = std.json.parseFromSlice(std.json.Value, a, config, .{}) catch return true; + defer doc.deinit(); + if (doc.value != .object) return true; + const vc = doc.value.object.get("vision_config") orelse return false; + return vc != .null; +} + +/// The gate's words for `model` ("this LFM2 checkpoint"): one format in every family; null for any other error. +pub fn words(comptime model: []const u8, err: anyerror) ?[]const u8 { + return switch (err) { + error.VisionWithoutTower => "--vision given but " ++ model ++ " has no vision tower", + error.VisionNotLoaded => model ++ " has a vision tower; pass --vision to load it", + else => null, + }; +} + +test "the gate refuses --vision without a tower by name and leaves a tower unread without --vision" { + try std.testing.expectError(error.VisionWithoutTower, gate(true, false)); + try std.testing.expect(try gate(true, true)); + try std.testing.expect(!try gate(false, true)); + try std.testing.expect(!try gate(false, false)); + const m = "this X checkpoint"; + try std.testing.expectEqualStrings("--vision given but this X checkpoint has no vision tower", words(m, error.VisionWithoutTower).?); + try std.testing.expectEqualStrings("this X checkpoint has a vision tower; pass --vision to load it", words(m, error.VisionNotLoaded).?); + try std.testing.expect(words(m, error.OutOfMemory) == null); +} + +test "a vision_config is declared unless absent or null" { + const a = std.testing.allocator; + try std.testing.expect(declared(a, "{\"vision_config\":{\"depth\":2}}")); + try std.testing.expect(declared(a, "{\"vision_config\":[]}")); + try std.testing.expect(declared(a, "{\"vision_config\":\"x\"}")); + try std.testing.expect(!declared(a, "{\"vision_config\":null}")); + try std.testing.expect(!declared(a, "{\"text_config\":{}}")); + try std.testing.expect(declared(a, "not json")); +} diff --git a/zig/src/core/fsr/plan.zig b/zig/src/core/fsr/plan.zig index b0d9d4b5ade..4a3e9a6e99c 100644 --- a/zig/src/core/fsr/plan.zig +++ b/zig/src/core/fsr/plan.zig @@ -94,3 +94,8 @@ test "FSR plan spends available slots and charges the full native storage path" try std.testing.expectEqual(@as(u64, 152), try pleRows(1, 160, 6, 32)); try std.testing.expectError(error.InvalidPleRecipe, pleRows(1, 160, 7, 32)); } + +/// Forecast tickets are itemized within the caller's reserved owner allowance, outside the legacy plan receipt. +pub fn forecastJobs(comptime count: usize, slots: usize) !u64 { + return std.math.mul(u64, slots, @sizeOf(arena.ArenaOf(void, count).Job)); +} diff --git a/zig/src/core/gguf_repack.zig b/zig/src/core/gguf_repack.zig index 4b5b9fe05bf..9ac9379a3a5 100644 --- a/zig/src/core/gguf_repack.zig +++ b/zig/src/core/gguf_repack.zig @@ -1,6 +1,7 @@ //! Compact affine codes with FP32 metadata, written from the GGUF block-layout definitions for the ten plain quants. const std = @import("std"); const blocks = @import("gguf_repack_blocks.zig"); +pub const validate = blocks.validate; pub const Kind = @import("gguf_tensor.zig").Kind; pub const Format = struct { bits: u8, group: usize }; pub fn format(kind: Kind) !Format { diff --git a/zig/src/core/lane_cache_queue.zig b/zig/src/core/lane_cache_queue.zig index 22c6c923620..7a8852782c7 100644 --- a/zig/src/core/lane_cache_queue.zig +++ b/zig/src/core/lane_cache_queue.zig @@ -27,6 +27,12 @@ const Snapshot = struct { } fn protect(out: *Snapshot, h: *LaneHost, current: *Job, job: *Job) !void { + if (job.lent) |serial| if (job != current) { // the very state it resumes at its first call, however long another + for (h.cache.?.entries.items) |e| if (e.serial == serial and !e.expired) { + if (std.mem.indexOfScalar(*const pc.Entry, out.entries.items, e) == null) try out.entries.append(h.gpa, e); + return; + }; + }; for (h.cache.?.by_position.items) |e| if (!e.expired and h.cache.?.usable(e.at, job.request.chunks) and extends(current, job, e)) { @@ -142,7 +148,7 @@ fn extends(current: *const Job, job: *const Job, e: *const pc.Entry) bool { const r = job.request; if (e.salt != r.cacheSalt()) return false; if (job == current or r.promptOnly() or r.prompt_logprobs != null or r.untaught) return false; - if (job.started and job.entry == null) return false; + if (job.started and job.entry == null and job.lent == null) return false; // a lent state stays protected const key = job.cacheKey(); if (e.at >= key.len or e.tokens.len == 0 or e.tokens.len > key.len) return false; if (!@import("cache_images.zig").equal(e.images, r.images, @intCast(e.tokens.len))) return false; @@ -224,3 +230,31 @@ test "queued cache: one snapshot protects each job's deepest usable prefix inclu test { _ = @import("lane_cache_promise_test.zig"); } + +test "queued cache: a lent job's own state stays protected when a longer prefix is kept after it lent" { + const Fake = @import("prompt_cache_fake.zig").Fake; + const a = std.testing.allocator; + var f: Fake = .{ .gpa = a }; + var store = pc.Store.init(a, f.snapshots(), .{ .min_prompt = 0 }, 1000); + defer store.deinit(); + const words = [_]u32{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 }; + _ = f.pass(&store, words[0..8], .{}); + try std.testing.expect(store.keepBorn(&words, 8, 8, null, &.{}, &.{})); + const lent = store.entries.items[0]; + var h: LaneHost = undefined; + h.cache = &store; + h.frame_key = null; + h.decoded_rows = false; + h.gpa = a; + const request: @import("engine_api.zig").Request = .{ .prompt = &words, .max_tokens = 1 }; + var current: Job = .{ .host = &h, .id = 1, .request = &request, .sink = undefined }; + var waiting: Job = .{ .host = &h, .id = 2, .request = &request, .sink = undefined, .started = true, .lent = lent.serial }; + // another pass keeps a longer prefix of the same prompt before the lent job's first call + _ = f.pass(&store, words[0..12], .{}); + try std.testing.expect(store.keepBorn(&words, 12, 12, null, &.{}, &.{})); + var snapshot: Snapshot = .{}; + defer snapshot.entries.deinit(a); + try snapshot.protect(&h, ¤t, &waiting); + try std.testing.expectEqual(@as(usize, 1), snapshot.entries.items.len); + try std.testing.expectEqual(lent, @constCast(snapshot.entries.items[0])); // the state it resumes, not the longer one +} diff --git a/zig/src/core/lane_halt.zig b/zig/src/core/lane_halt.zig index f2cbe4e8ba4..c983288a613 100644 --- a/zig/src/core/lane_halt.zig +++ b/zig/src/core/lane_halt.zig @@ -5,7 +5,7 @@ const LaneHost = @import("lane_host.zig").LaneHost; /// `LaneHost.halt`: the engine thread stops at the next round boundary; what is left fails with `reason`. pub fn halt(h: *LaneHost, reason: []const u8) void { h.mutex.lockUncancelable(h.io); - h.closing = true; + h.closing.store(true, .release); h.halt_reason = reason; h.wake.broadcast(h.io); h.unlock(); @@ -22,6 +22,7 @@ pub fn haltAll(h: *LaneHost, reason: []const u8) void { h.admitted = .empty; h.filling.clearRetainingCapacity(); // a job still filling is admitted: it fails below, its lane freed h.unlock(); + @import("lane_host_status.zig").noteLive(h); // empty before any terminal job or stream is deinitialized if (queued.items.len + jobs.items.len > 0) std.log.warn("lane host: stopping at a round boundary: {d} running and {d} queued request(s) end ({s})", .{ jobs.items.len, queued.items.len, reason }); for (jobs.items) |job| { if (job.started and !job.stream.finished) h.core.discard(&job.stream); diff --git a/zig/src/core/lane_host.zig b/zig/src/core/lane_host.zig index 8187cf58406..527498514b3 100644 --- a/zig/src/core/lane_host.zig +++ b/zig/src/core/lane_host.zig @@ -46,22 +46,17 @@ pub const LaneHost = struct { admitted: std.ArrayList(*Job) = .empty, filling: std.ArrayList(*Job) = .empty, // admitted jobs whose prompt is still going in, a chunk a round, oldest first cancels: std.ArrayList(Id) = .empty, - closing: bool = false, - stale: bool = false, // the learner's last step: a put-back has not reached the device, so replies are refused + closing: std.atomic.Value(bool) = .init(false), + stale: std.atomic.Value(bool) = .init(false), // the learner's last step: a put-back has not reached the device, so replies are refused + st: @import("lane_host_status.zig").State = .{}, /// `halt`'s reason: what is left finishes failed with it (null: a stop cancels what is left) halt_reason: ?[]const u8 = null, thread: ?std.Thread = null, decoded: std.ArrayList(status.Mark) = .empty, // tokens a round landed, for the 2 s decode rate - prefill_rate: f64 = 0, - prefill_at: i96 = 0, - live_tokens: std.ArrayList(u32) = .empty, /// A Metal engine's keepalive target, set by the family that owns the queue; null keeps the ticker off. keepalive_target: ?api.keepalive.Target = null, - live_generated: u64 = 0, lone: ?api.Lone = null, // the backend's driver for a lone greedy stream; null: every stream in the lane core lone_job: ?*Job = null, // the job that driver holds now - cache_status: ?api.Status.PromptCache = null, // published under mutex; HTTP threads never read the store - disk_status: ?api.Status.DiskCache = null, // published under mutex beside it cache_at: i64 = 0, // wall-clock ms of the last full cache and disk copy (republished at 1 Hz at most) cache: ?*pc.Store = null, // kept prompt states (engine thread only); the backend restores and saves them recall: ?*lanes.recall_store.Store = null, // Recall's record: drafts from earlier requests (lane_host_recall.zig) @@ -87,6 +82,7 @@ pub const LaneHost = struct { srpt: @import("lane_host_srpt.zig").Srpt = .{}, // TENSORFOLD_PREFILL_ORDER=srpt: less work left goes first decode_cap: bool = false, // --decode-share given by flag (the env never opts in): a chunk-invariant family may cap prefix: @import("lane_host_prefix.zig").Wait = .{}, // a request's wait for a cut another prompt is filling + priority_age_ns: i96 = 0, // a background request older than this may precede foreground work (0: FIFO) finals: std.ArrayList(usize) = .empty, pressure: ?@import("memory_pressure.zig").Governor = null, // OS memory pressure (lane_host_pressure.zig); null: off activity: ?@import("lane_activity.zig").Activity = null, // owned work scopes for a backend's watchdog; null: off @@ -106,7 +102,7 @@ pub const LaneHost = struct { pub fn init(gpa: Allocator, io: std.Io, core: *lanes.Engine, info_: Info) LaneHost { var shown = info_.ofLanes(); shown.draft_sources = shown.draft_sources.ofLanes(core.cfg, shown.lanes); - return .{ .gpa = gpa, .io = io, .core = core, .info_ = shown, .share = fill.decodeShare.resolved(info_.decode_share, info_.default_decode_share), .decode_cap = fill.decodeShare.capped(info_.decode_share, info_.default_decode_share), .prefix = .fromEnv(), .pressure = .fromEnv(), .srpt = .fromEnv(), .kv = ledger.of(info_) }; + return .{ .gpa = gpa, .io = io, .core = core, .info_ = shown, .share = fill.decodeShare.resolved(info_.decode_share, info_.default_decode_share), .decode_cap = fill.decodeShare.capped(info_.decode_share, info_.default_decode_share), .prefix = .fromEnv(), .priority_age_ns = @import("lane_host_admit.zig").ageFromEnv(), .pressure = .fromEnv(), .srpt = .fromEnv(), .kv = ledger.of(info_) }; } /// A paged family's pool counts in this host's ledger, the only test its promises pass (#1943); before `start`. @@ -144,7 +140,7 @@ pub const LaneHost = struct { h.filling.deinit(h.gpa); h.cancels.deinit(h.gpa); h.decoded.deinit(h.gpa); - h.live_tokens.deinit(h.gpa); + @import("lane_host_status.zig").freeSlots(h); h.pieces.deinit(h.gpa); h.finals.deinit(h.gpa); lane_trace.drop(&h.trace); @@ -214,11 +210,12 @@ pub const LaneHost = struct { // written before the lock: a trace line never holds the host's mutex (a refused request's line stays alone) if (h.trace) |t| t.line(.{ .t0_ns = job.submitted, .t1_ns = job.submitted, .kind = .submit, .id = id, .rows_to = request.prompt.len }); h.mutex.lockUncancelable(h.io); + defer @import("lane_host_status.zig").publish(h); // a reader sees the queue at once, after the unlock below defer h.unlock(); - const unavailable = h.closing or (if (h.health) |source| !source.read(source.ctx) else false); - if (unavailable or h.stale or pressure.refuses(h)) { + const unavailable = h.closing.load(.acquire) or (if (h.health) |source| !source.read(source.ctx) else false); + if (unavailable or h.stale.load(.acquire) or pressure.refuses(h)) { h.gpa.destroy(job); - return if (unavailable) error.Closed else if (h.stale) error.Stale else error.MemoryPressure; + return if (unavailable) error.Closed else if (h.stale.load(.acquire)) error.Stale else error.MemoryPressure; } // foreground before background, each in arrival order (the Python job queue's priority) var at = h.queued.items.len; @@ -253,7 +250,7 @@ pub const LaneHost = struct { const job: *Job = @ptrCast(@alignCast(ctx)); job.host.lock(); defer job.host.unlock(); - return job.host.closing or std.mem.indexOfScalar(Id, job.host.cancels.items, job.id) != null; + return job.host.closing.load(.acquire) or std.mem.indexOfScalar(Id, job.host.cancels.items, job.id) != null; } /// A background pass's yield hook: a foreground request waits, a prompt fills or a stream decodes (under the lock). @@ -274,10 +271,10 @@ pub const LaneHost = struct { const until: std.Io.Timeout = .{ .deadline = .fromNow(h.io, .{ .raw = .fromNanoseconds(h.warm_quiet), .clock = .awake }) }; h.lock(); defer h.unlock(); - while (!h.closing and !@import("lane_host_warm.zig").otherWork(h, job) and std.mem.indexOfScalar(Id, h.cancels.items, job.id) == null) { + while (!h.closing.load(.acquire) and !@import("lane_host_warm.zig").otherWork(h, job) and std.mem.indexOfScalar(Id, h.cancels.items, job.id) == null) { h.wake.waitTimeout(h.io, &h.mutex, until) catch |e| return e == error.Timeout; } - h.load.yields += @intFromBool(!h.closing and std.mem.indexOfScalar(Id, h.cancels.items, job.id) == null); // foreground work came + h.load.yields += @intFromBool(!h.closing.load(.acquire) and std.mem.indexOfScalar(Id, h.cancels.items, job.id) == null); // foreground work came return false; } @@ -297,6 +294,7 @@ pub const LaneHost = struct { h.send(job); if (!job.stream.finished) return false; h.remove(job); + @import("lane_host_status.zig").publish(h); // the job left the list before the event const reason: Reason = switch (job.stream.reason) { .length => .length, .cancelled => .cancelled, @@ -334,6 +332,7 @@ pub const LaneHost = struct { } pub fn lock(h: *LaneHost) void { + if (@import("lane_host_status.zig").takeEngineLock(h)) return; h.mutex.lockUncancelable(h.io); } @@ -413,7 +412,7 @@ pub const LaneHost = struct { if (!r.promptOnly() and r.max_tokens == 0 and h.info_.warm_turns) return @import("lane_host_warm.zig").pass(h, job, began); if (!r.promptOnly() and lone.fits(h, job)) return lone.run(h, job, began, false); if (h.core.fills()) { - h.filling.append(h.gpa, job) catch return h.drop(job, "out of memory"); + h.filling.append(h.gpa, job.lending()) catch return h.drop(job, "out of memory"); // its kept state lent until its first call return true; } load.calling(h, job); @@ -455,11 +454,12 @@ pub const LaneHost = struct { const done = std.Io.Clock.awake.now(h.io).toNanoseconds(); job.fill_on.store(false, .release); // the pass reported: status readers stop counting this fill h.lock(); - if (done > began) h.prefill_rate = @as(f64, @floatFromInt(job.request.prompt.len - job.stream.cached)) / (@as(f64, @floatFromInt(done - began)) / 1e9); - h.prefill_at = done; + if (done > began) h.st.prefill_rate = @as(f64, @floatFromInt(job.request.prompt.len - job.stream.cached)) / (@as(f64, @floatFromInt(done - began)) / 1e9); + h.st.prefill_at = done; job.prefilled = done; load.credit(h, job); h.unlock(); + @import("lane_host_status.zig").publish(h); // the fill ends here rows_host.prefilled(h, job.request.prompt.len - job.stream.cached, done - began); job.reported(); if (h.cache) |store| { @@ -537,7 +537,7 @@ pub const LaneHost = struct { ends.deliverPending(h); status.noteLive(h); h.lock(); - if (h.closing) { + if (h.closing.load(.acquire)) { const left = h.queued.items.len + h.admitted.items.len; h.unlock(); if (h.lesson_open) { diff --git a/zig/src/core/lane_host_admit.zig b/zig/src/core/lane_host_admit.zig index c9117928fe9..053ab5e1c26 100644 --- a/zig/src/core/lane_host_admit.zig +++ b/zig/src/core/lane_host_admit.zig @@ -1,4 +1,5 @@ //! Which queued request a lane host admits next: the head, or one behind a head that waits for pool room. +const std = @import("std"); const LaneHost = @import("lane_host.zig").LaneHost; const Job = LaneHost.Job; const lanes = @import("lanes"); @@ -12,13 +13,14 @@ const Wait = @import("wait_reason.zig").Wait; pub fn pick(h: *LaneHost) ?usize { if (pressure.holds(h)) return hold(h, .memory_pressure); // under memory pressure nothing starts or is read ahead if (h.disk.holding()) return null; // a flush waits for the requests in flight: nothing starts or is read ahead - if (!h.stale) fetch.queue(h); // disk states read ahead for queued requests, a lane free or not + if (!h.stale.load(.acquire)) fetch.queue(h); // disk states read ahead for queued requests, a lane free or not // a stale device takes no reply: `learn.refuse` ends the queued ones instead - if (h.stale) return hold(h, .engine_unavailable); + if (h.stale.load(.acquire)) return hold(h, .engine_unavailable); if (h.queued.items.len == 0 or h.admitted.items.len >= @min(h.info_.lanes, h.memory_lanes orelse h.info_.lanes)) return hold(h, .engine_busy); prefix.release(h); // requests whose awaited cut is in (or will not come) go on first + const now: i96 = if (h.priority_age_ns > 0) std.Io.Clock.awake.now(h.io).toNanoseconds() else 0; while (true) { // a request that waits for a cut another prompt is filling stays queued, passed over - const at = choose(h) orelse return null; + const at = chooseAt(h, now) orelse return null; if (!prefix.waits(h, h.queued.items[at])) return at; h.queued.items[at].wait_reason = .prefix_cut; } @@ -49,10 +51,11 @@ pub fn holds(h: *LaneHost) bool { } /// The head, or one behind a head that waits for pool room, passing over prefix and read waiters. -fn choose(h: *LaneHost) ?usize { - const first = for (h.queued.items, 0..) |j, i| { +fn chooseAt(h: *LaneHost, now: i96) ?usize { + const ordinary = for (h.queued.items, 0..) |j, i| { j.wait_reason = passedFor(h, j) orelse break i; } else return null; + const first = promoted(h, now, ordinary); if (h.info_.admit == null and !ledger.priced(h)) return first; // alone: the whole pool is free (kept prefixes give their blocks back); a ledger counts leases, not live streams if (if (ledger.priced(h)) !ledger.outstanding(h) else h.core.activeCount() == 0) return first; @@ -61,15 +64,19 @@ fn choose(h: *LaneHost) ?usize { const room: Wait = if (ledger.priced(h)) .ledger_bytes else .pool_room; head.wait_reason = room; if (head.waits_since == null) head.waits_since = h.admissions; + const rest = if (h.priority_age_ns <= 0) first + 1 else 0; // it waits on the streams admitted before it waited: while one runs, later requests that fit go first; then none do for (h.admitted.items) |j| if (j.seq < head.waits_since.?) { - for (h.queued.items[first + 1 ..], first + 1..) |j2, i| { + for (h.queued.items[rest..], rest..) |j2, i| { + if (i == first) continue; j2.wait_reason = passedFor(h, j2) orelse if (fits(h, j2)) return i else room; } return null; }; // the rest stay behind the head that waits for room - for (h.queued.items[first + 1 ..]) |j2| j2.wait_reason = passedFor(h, j2) orelse room; + for (h.queued.items[rest..], rest..) |j2, i| { + if (i != first) j2.wait_reason = passedFor(h, j2) orelse room; + } return null; } @@ -80,6 +87,24 @@ fn fits(h: *const LaneHost, job: *const Job) bool { return a.fits(a.ctx, @intCast(job.request.prompt.len), job.request.max_tokens); } +/// The oldest eligible background job past the opt-in age that came before the ordinary head, else that head. +fn promoted(h: *LaneHost, now: i96, ordinary: usize) usize { + if (h.priority_age_ns <= 0) return ordinary; + // only one submitted before the head may pass it: later arrivals never do, so every request is reached in time + const head = h.queued.items[ordinary].submitted; + for (h.queued.items[ordinary..], ordinary..) |j, i| { + if (!j.request.background or now - j.submitted < h.priority_age_ns or j.submitted >= head) continue; + j.wait_reason = passedFor(h, j) orelse return i; + } + return ordinary; +} + +/// TENSORFOLD_PRIORITY_AGE_MS in nanoseconds; 0 keeps foreground-first FIFO. +pub fn ageFromEnv() i96 { + const ms = @import("sys").environment.read(u32, "TENSORFOLD_PRIORITY_AGE_MS", 0) catch return 0; + return @as(i96, ms) * std.time.ns_per_ms; +} + /// Whether to admit several at once: prompts batch (beside chunked fills up to many_rows), two wait, two lanes free. pub fn batches(h: *LaneHost) bool { if (!h.core.batchesPrompts()) return false; @@ -135,3 +160,95 @@ pub fn many(h: *LaneHost) bool { } return took; } + +fn testEvent(_: *anyopaque, _: @import("engine_api.zig").Id, _: *const @import("engine_api.zig").Event) void {} + +fn testJob(h: *LaneHost, request: *const @import("engine_api.zig").Request, submitted: i96) Job { + return .{ .host = h, .id = 1, .request = request, .sink = .{ .ctx = h, .event = testEvent }, .submitted = submitted }; +} + +test "priority aging: default FIFO, threshold, prefix holds and pool room" { + const a = std.testing.allocator; + var cfg = try lanes.Config.init(a, .{}, 1, 0); + defer cfg.deinit(a); + var core: lanes.Engine = undefined; + core.cfg = &cfg; + core.live = .empty; + defer core.live.deinit(a); + var h = LaneHost.init(a, std.testing.io, &core, .{ .lanes = 2 }); + defer h.queued.deinit(a); + defer h.admitted.deinit(a); + const foreground: @import("engine_api.zig").Request = .{ .prompt = &.{ 1, 2, 3 }, .max_tokens = 1 }; + const background: @import("engine_api.zig").Request = .{ .prompt = &.{ 4, 5, 6 }, .max_tokens = 1, .background = true }; + const long_prompt: [64]u32 = @splat(7); + const long: @import("engine_api.zig").Request = .{ .prompt = &long_prompt, .max_tokens = 1, .background = true }; + var first = testJob(&h, &foreground, 95 * std.time.ns_per_s); + var aged = testJob(&h, &background, 60 * std.time.ns_per_s); + var young = testJob(&h, &background, 90 * std.time.ns_per_s); + try h.queued.append(a, &first); + try h.queued.append(a, &aged); + try h.queued.append(a, &young); + const now = 100 * std.time.ns_per_s; + h.priority_age_ns = 30 * std.time.ns_per_s; + try std.testing.expectEqual(@as(?usize, 1), chooseAt(&h, now)); + h.priority_age_ns = 0; + try std.testing.expectEqual(@as(?usize, 0), chooseAt(&h, now)); + h.priority_age_ns = 50 * std.time.ns_per_s; + try std.testing.expectEqual(@as(?usize, 0), chooseAt(&h, now)); + h.priority_age_ns = 30 * std.time.ns_per_s; + aged.prefix.leader = &first; + try std.testing.expectEqual(@as(?usize, 0), chooseAt(&h, now)); + aged.prefix.leader = null; + var running = testJob(&h, &foreground, 0); + var stream: lanes.Stream = undefined; + stream.finished = false; + try core.live.append(a, &stream); + try h.admitted.append(a, &running); + h.admissions = 1; + var unused: u8 = 0; + h.info_.admit = .{ .ctx = &unused, .fits = struct { + fn fits(_: *anyopaque, prompt: u32, _: u32) bool { + return prompt < 64; + } + }.fits }; + aged.request = &long; + try std.testing.expectEqual(@as(?usize, 0), chooseAt(&h, now)); + h.queued.clearRetainingCapacity(); + try h.queued.append(a, &aged); + try std.testing.expectEqual(@as(?usize, null), chooseAt(&h, now)); +} + +test "priority aging: a foreground head behind a steady stream of aged backgrounds is admitted within a bound" { + const a = std.testing.allocator; + var cfg = try lanes.Config.init(a, .{}, 1, 0); + defer cfg.deinit(a); + var core: lanes.Engine = undefined; + core.cfg = &cfg; + core.live = .empty; + defer core.live.deinit(a); + var h = LaneHost.init(a, std.testing.io, &core, .{ .lanes = 2 }); + defer h.queued.deinit(a); + defer h.admitted.deinit(a); + h.priority_age_ns = 30 * std.time.ns_per_s; + const foreground: @import("engine_api.zig").Request = .{ .prompt = &.{ 1, 2, 3 }, .max_tokens = 1 }; + const background: @import("engine_api.zig").Request = .{ .prompt = &.{ 4, 5, 6 }, .max_tokens = 1, .background = true }; + // the head arrives at 100 s; two backgrounds were already waiting, and more keep arriving after it + var head = testJob(&h, &foreground, 100 * std.time.ns_per_s); + var jobs: [64]Job = undefined; + for (&jobs, 0..) |*j, i| j.* = testJob(&h, &background, if (i < 2) (90 + @as(i96, @intCast(i))) * std.time.ns_per_s else (100 + @as(i96, @intCast(i))) * std.time.ns_per_s); + try h.queued.append(a, &head); + var next: usize = 0; + while (next < 4) : (next += 1) try h.queued.append(a, &jobs[next]); + var picks: usize = 0; + const admitted = while (picks < 32) : (picks += 1) { + // every queued background is past the threshold by now; a fresh aged one replaces each one admitted + const now = (200 + @as(i96, @intCast(picks))) * std.time.ns_per_s; + const at = chooseAt(&h, now).?; + if (h.queued.items[at] == &head) break picks + 1; + _ = h.queued.orderedRemove(at); + try h.queued.append(a, &jobs[next]); + next += 1; + } else 0; + // the two that came before it, then the head itself: never any of those that came after + try std.testing.expectEqual(@as(usize, 3), admitted); +} diff --git a/zig/src/core/lane_host_admit_borrow_test.zig b/zig/src/core/lane_host_admit_borrow_test.zig new file mode 100644 index 00000000000..46080172214 --- /dev/null +++ b/zig/src/core/lane_host_admit_borrow_test.zig @@ -0,0 +1,163 @@ +//! Filling streams admitted together: none holds its kept state borrowed while another's first call makes room. +const std = @import("std"); +const lanes = @import("lanes"); +const api = @import("engine_api.zig"); +const pc = @import("prompt_cache.zig"); +const a = std.testing.allocator; + +const Box = struct { + done: std.atomic.Value(bool) = .init(false), + fn event(ctx: *anyopaque, _: api.Id, e: *const api.Event) void { + const b: *Box = @ptrCast(@alignCast(ctx)); + if (e.* == .finished) b.done.store(true, .release); + } + fn wait(b: *Box) !void { + const began = std.Io.Clock.awake.now(std.testing.io).toNanoseconds(); + while (!b.done.load(.acquire)) { + if (std.Io.Clock.awake.now(std.testing.io).toNanoseconds() - began > 2 * std.time.ns_per_s) return error.RequestTimedOut; + std.Io.sleep(std.testing.io, .fromMilliseconds(1), .awake) catch {}; + } + } +}; + +/// Two prompts with kept states (a, b) and one without (miss), shorter than b past b's kept rows. +const pa = [_]u32{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }; +const pb: [40]u32 = blk: { // long past its kept state: the shorter miss fills first + var x: [40]u32 = undefined; + for (&x, 21..) |*v, i| v.* = @intCast(i); + break :blk x; +}; +const miss = [_]u32{ 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52 }; + +/// What the passes' first calls saw. +const Seen = struct { + firsts: usize = 0, + resumed: usize = 0, + beside: u32 = 0, // the most borrowers another prompt's kept state had while a pass made its first call + filling: usize = 0, // admitted fills when the first of the first calls ran +}; + +const Snaps = struct { + f: *lanes.fake.Fake, + store: *pc.Store = undefined, + host: ?*api.LaneHost = null, + seen: Seen = .{}, + fn of(ctx: *anyopaque) *Snaps { + return @ptrCast(@alignCast(ctx)); + } + fn bytes(_: *anyopaque, _: u32) u64 { + return 1; + } + fn save(ctx: *anyopaque, owner: ?*anyopaque, at: u32) !pc.Saved { + return of(ctx).f.save(@ptrCast(@alignCast(owner.?)), at); + } + fn restore(_: *anyopaque, _: ?*anyopaque, _: pc.Saved) !void { + return error.BackendRestores; + } + fn drop(ctx: *anyopaque, saved: pc.Saved) void { + of(ctx).f.drop(saved); + } + /// A pass's first call, where a backend opens its cache and makes room: no other kept state may be pinned. + fn hook(ctx: *anyopaque, s: *lanes.Stream, filled: usize) void { + const x = of(ctx); + if (filled != 0) return; + if (x.seen.firsts == 0) x.seen.filling = x.host.?.filling.items.len; + x.seen.firsts += 1; + if (s.reuse.saved != null) { + s.cached = s.reuse.at; // the backend restores in its first call + x.seen.resumed += 1; + } + for ([_][]const u32{ &pa, &pb }) |other| if (!std.mem.eql(u32, s.prompt()[0..4], other[0..4])) { + if (x.store.find(other, &.{}, &.{})) |e| x.seen.beside = @max(x.seen.beside, e.borrowers); + }; + } +}; + +fn host(core: *lanes.Engine, store: *pc.Store, n: u32) api.LaneHost { + var h = api.LaneHost.init(a, std.testing.io, core, .{ .lanes = n }); + h.cache = store; + return h; +} + +/// `a` and `b` kept one at a time, then `queued` submitted together before a two-lane host starts. +fn run(queued: []const []const u32) !Seen { + var cfg = try lanes.Config.init(a, .{ .exact_width = 8, .gpu_tokens = true, .hidden_rows = true }, 8, 7); + defer cfg.deinit(a); + var target: lanes.fake.Fake = .{ .gpa = a, .prefill_chunks = 4 }; + defer target.deinit(); + var clock: lanes.fake.FixedClock = .{}; + var core = lanes.Engine.init(a, &cfg, target.stepped(), clock.clock()); + defer core.deinit(); + var snaps: Snaps = .{ .f = &target }; + var store = pc.Store.init(a, .{ .ptr = &snaps, .vtable = &.{ .bytes = Snaps.bytes, .save = Snaps.save, .restore = Snaps.restore, .drop = Snaps.drop } }, .{ .min_prompt = 0 }, 1000); + defer store.deinit(); + snaps.store = &store; + { + var h = host(&core, &store, 1); + try h.start(); + defer h.stop(); + for ([_][]const u32{ &pa, &pb }, 1..) |p, id| { + const r: api.Request = .{ .prompt = p, .max_tokens = 2, .history_len = 8 }; + var box: Box = .{}; + try h.engine().submit(id, &r, .{ .ctx = &box, .event = Box.event }); + try box.wait(); + } + } + target.prefill_hook = Snaps.hook; + target.prefill_hook_ctx = &snaps; + var h = host(&core, &store, 2); + snaps.host = &h; + var reqs: [2]api.Request = undefined; + var boxes: [2]Box = .{ .{}, .{} }; + for (queued, reqs[0..queued.len], boxes[0..queued.len], 3..) |p, *r, *box, id| { + r.* = .{ .prompt = p, .max_tokens = 2, .history_len = 8 }; + try h.engine().submit(id, r, .{ .ctx = box, .event = Box.event }); // queued before the host starts + } + try h.start(); + defer h.stop(); + for (boxes[0..queued.len]) |*box| try box.wait(); + return snaps.seen; +} + +test "streams admitted together hold no kept state borrowed while another's first call makes room" { + const seen = try run(&.{ &pa, &pb }); + try std.testing.expectEqual(@as(usize, 2), seen.resumed); // both resumed their kept states, borrowed again at their calls + try std.testing.expectEqual(@as(u32, 0), seen.beside); +} + +test "a cache miss queued ahead of a hit opens with the hit's kept state unpinned" { + const seen = try run(&.{ &miss, &pb }); + try std.testing.expectEqual(@as(usize, 2), seen.firsts); + try std.testing.expectEqual(@as(usize, 1), seen.resumed); // the hit still resumes + try std.testing.expectEqual(@as(u32, 0), seen.beside); // the old admission hold let the miss admit the hit borrowed beside it +} + +test "a prompt queued behind a hit not yet begun is admitted with it: no new admission wait" { + const seen = try run(&.{ &pb, &miss }); + try std.testing.expectEqual(@as(usize, 2), seen.filling); // both admitted before either's first call, as on main + try std.testing.expectEqual(@as(u32, 0), seen.beside); +} + +test "the store borrows an entry again by its serial, and not once it has expired" { + var target: lanes.fake.Fake = .{ .gpa = a }; + defer target.deinit(); + var snaps: Snaps = .{ .f = &target }; + var store = pc.Store.init(a, .{ .ptr = &snaps, .vtable = &.{ .bytes = Snaps.bytes, .save = Snaps.save, .restore = Snaps.restore, .drop = Snaps.drop } }, .{ .min_prompt = 0 }, 1000); + defer store.deinit(); + var x: u8 = 0; + const e = try a.create(pc.Entry); + e.* = .{ .tokens = try a.dupe(u32, &pa), .at = 8, .saved = &x, .bytes = 1, .born = 12, .used = 0, .last = &.{}, .serial = 7 }; + try store.entries.append(a, e); + defer { + a.free(e.tokens); + a.destroy(e); + store.entries.clearRetainingCapacity(); + } + try std.testing.expect(store.reborrow(8) == null); // no entry has that serial + try std.testing.expectEqual(e, store.reborrow(7).?); + try std.testing.expectEqual(@as(u32, 1), e.borrowers); + e.borrowers = 0; + e.expired = true; // gone from lookups: a lent job fills from the start instead + try std.testing.expect(store.reborrow(7) == null); + try std.testing.expectEqual(@as(u32, 0), e.borrowers); +} diff --git a/zig/src/core/lane_host_backlog.zig b/zig/src/core/lane_host_backlog.zig index bd6c786696a..34d9c555de5 100644 --- a/zig/src/core/lane_host_backlog.zig +++ b/zig/src/core/lane_host_backlog.zig @@ -23,7 +23,7 @@ pub fn step(h: *LaneHost) void { h.lock(); defer h.unlock(); // an arrival or a cancel signals `wake`; a queued request that cannot be admitted no longer spins the loop - if (h.cancels.items.len == 0 and !h.closing) h.wake.waitTimeout(h.io, &h.mutex, .{ .duration = .{ .raw = .fromMilliseconds(2), .clock = .awake } }) catch {}; + if (h.cancels.items.len == 0 and !h.closing.load(.acquire)) h.wake.waitTimeout(h.io, &h.mutex, .{ .duration = .{ .raw = .fromMilliseconds(2), .clock = .awake } }) catch {}; } /// Holds and releases the admitted jobs' streams by their readers' unread tokens, at `at` (null: the clock's now). diff --git a/zig/src/core/lane_host_end.zig b/zig/src/core/lane_host_end.zig index 29b67148793..9076b72245d 100644 --- a/zig/src/core/lane_host_end.zig +++ b/zig/src/core/lane_host_end.zig @@ -148,6 +148,7 @@ pub fn closeAll(h: *LaneHost) void { h.admitted = .empty; h.filling.clearRetainingCapacity(); h.unlock(); + @import("lane_host_status.zig").noteLive(h); // empty before any terminal job or stream is deinitialized defer queued.deinit(h.gpa); defer admitted.deinit(h.gpa); for (admitted.items) |job| { @@ -182,6 +183,7 @@ pub fn requeue(h: *LaneHost, job: *Job) bool { return true; } job.fill_on.store(false, .release); // off the lists before the teardown a status reader could have walked into + @import("lane_host_status.zig").publish(h); // the fill ends here job.reported(); if (job.stream.grammar) |g| g.deinit(h.gpa); // the next admission compiles its own job.stream.deinit(h.gpa); @@ -192,6 +194,7 @@ pub fn requeue(h: *LaneHost, job: *Job) bool { job.reached = 0; job.cache_promise = .{}; job.entry = null; // looked up again at its next admission + job.lent = null; h.gpa.free(job.marks); job.marks = &.{}; h.gpa.free(job.key); diff --git a/zig/src/core/lane_host_fill.zig b/zig/src/core/lane_host_fill.zig index 290796d8785..c307bd2757f 100644 --- a/zig/src/core/lane_host_fill.zig +++ b/zig/src/core/lane_host_fill.zig @@ -229,7 +229,10 @@ fn fillAt(h: *LaneHost, at: usize) void { }; return; }; + // a backend restores a kept state in its pass's first call: the store gets it back now, not at the pass's end + if (first and restoreSettled(&job.stream)) job.reported(); load.progress(h, job); + @import("lane_host_status.zig").publish(h); // a reader sees the rows this chunk added if (h.trace != null) line.rows_to = if (done) job.stream.prompt_len else job.stream.fill_at.load(.monotonic); if (!done) return; _ = h.filling.orderedRemove(at); @@ -241,9 +244,12 @@ fn fillAt(h: *LaneHost, at: usize) void { _ = h.deliver(job); } +pub const restoreSettled = @import("lane_job.zig").restoreSettled; + /// Fill `at`'s next call: the rows it advanced (all it had, if it left the list); no progress shown spends any budget. pub fn step(h: *LaneHost, at: usize) u64 { const job = h.filling.items[at]; + job.reborrow(); // a first call's kept state borrowed again first: its rows are counted from what it resumes const before = remaining(h, job); fillAt(h, took(h, at)); // the call can finish, cancel or requeue the job: it is read again only while it is still filling @@ -256,6 +262,7 @@ pub fn step(h: *LaneHost, at: usize) u64 { /// A long prompt's step, timed while its share owes decoders a part of it; its rows as `step` counts them. fn longStep(h: *LaneHost, at: usize) u64 { + h.filling.items[at].reborrow(); // as step's: its share and srpt read the rows it has left after it const decoding = runnable(h) > 0; if (h.srpt.on) return srptStep(h, at, decoding); // an engine default shares only while the prompt has the threshold's rows left; the flag shares every long prompt diff --git a/zig/src/core/lane_host_health_test.zig b/zig/src/core/lane_host_health_test.zig index 06b978a9fe9..b1ca5ad922c 100644 --- a/zig/src/core/lane_host_health_test.zig +++ b/zig/src/core/lane_host_health_test.zig @@ -35,11 +35,11 @@ test "an unhealthy backend fails health and refuses a request before queue admis engine.status(&status, &.{}); try std.testing.expect(status.healthy); const request: Request = .{ .prompt = &.{1}, .max_tokens = 1 }; - host.stale = true; + host.stale.store(true, .release); engine.status(&status, &.{}); try std.testing.expect(!status.healthy); try std.testing.expectError(error.Stale, engine.submit(1, &request, .{ .ctx = &health, .event = Health.event })); - host.stale = false; + host.stale.store(false, .release); health.available = false; engine.status(&status, &.{}); try std.testing.expect(!status.healthy); diff --git a/zig/src/core/lane_host_learn.zig b/zig/src/core/lane_host_learn.zig index a61ecfd1a23..5aafe5a458d 100644 --- a/zig/src/core/lane_host_learn.zig +++ b/zig/src/core/lane_host_learn.zig @@ -8,10 +8,10 @@ pub fn submit(ctx: *anyopaque, request: *const api.LearnRequest, sink: api.Learn const h: *LaneHost = @ptrCast(@alignCast(ctx)); h.mutex.lockUncancelable(h.io); defer h.unlock(); - if (h.closing) return error.Closed; + if (h.closing.load(.acquire)) return error.Closed; if (h.learner == null) return error.Unsupported; if (request.audit != null and !h.learner.?.read_only_audit) return error.Unsupported; - if (request.audit != null and h.stale) return error.Busy; + if (request.audit != null and h.stale.load(.acquire)) return error.Busy; h.lessons.append(h.gpa, .{ .request = request, .sink = sink }) catch return error.Busy; h.wake.signal(h.io); } @@ -20,7 +20,7 @@ pub fn submit(ctx: *anyopaque, request: *const api.LearnRequest, sink: api.Learn pub fn refuse(h: *LaneHost) void { while (true) { h.lock(); - if (!h.stale or h.queued.items.len == 0) return h.unlock(); + if (!h.stale.load(.acquire) or h.queued.items.len == 0) return h.unlock(); const job = h.queued.orderedRemove(0); h.unlock(); h.finish(job, .failed, api.stale_message); @@ -39,7 +39,7 @@ pub fn step(h: *LaneHost) void { if (!h.lesson_open) { h.mutex.lockUncancelable(h.io); const lesson = h.lessons.orderedRemove(0); - const blocked = lesson.request.audit != null and h.stale; + const blocked = lesson.request.audit != null and h.stale.load(.acquire); h.unlock(); if (blocked) { const failed: api.LearnEvent = .{ .done = .{ .message = "AuditUnresolved" } }; @@ -56,6 +56,6 @@ pub fn step(h: *LaneHost) void { h.lesson_open = !s.done; // learn requests still come in, so the learner can try the put-back again; replies wait for it h.mutex.lockUncancelable(h.io); - h.stale = s.stale; + h.stale.store(s.stale, .release); h.unlock(); } diff --git a/zig/src/core/lane_host_lend_test.zig b/zig/src/core/lane_host_lend_test.zig new file mode 100644 index 00000000000..4080f9bb191 --- /dev/null +++ b/zig/src/core/lane_host_lend_test.zig @@ -0,0 +1,97 @@ +//! A lent kept state evicted before its job's first call: the job is looked up again and counted from what it fills. +const std = @import("std"); +const lanes = @import("lanes"); +const api = @import("engine_api.zig"); +const pc = @import("prompt_cache.zig"); +const fill = @import("lane_host_fill.zig"); +const a = std.testing.allocator; + +const Box = struct { + done: std.atomic.Value(bool) = .init(false), + fn event(ctx: *anyopaque, _: api.Id, e: *const api.Event) void { + if (e.* == .finished) @as(*Box, @ptrCast(@alignCast(ctx))).done.store(true, .release); + } + fn wait(b: *Box) !void { + const began = std.Io.Clock.awake.now(std.testing.io).toNanoseconds(); + while (!b.done.load(.acquire)) { + if (std.Io.Clock.awake.now(std.testing.io).toNanoseconds() - began > 2 * std.time.ns_per_s) return error.RequestTimedOut; + std.Io.sleep(std.testing.io, .fromMilliseconds(1), .awake) catch {}; + } + } +}; + +const Snaps = struct { + f: *lanes.fake.Fake, + fn of(ctx: *anyopaque) *Snaps { + return @ptrCast(@alignCast(ctx)); + } + fn bytes(_: *anyopaque, _: u32) u64 { + return 1; + } + fn save(ctx: *anyopaque, owner: ?*anyopaque, at: u32) !pc.Saved { + return of(ctx).f.save(@ptrCast(@alignCast(owner.?)), at); + } + fn restore(_: *anyopaque, _: ?*anyopaque, _: pc.Saved) !void { + return error.BackendRestores; + } + fn drop(ctx: *anyopaque, saved: pc.Saved) void { + of(ctx).f.drop(saved); + } + /// A backend's first call restores what the stream was offered. + fn hook(_: *anyopaque, s: *lanes.Stream, filled: usize) void { + if (filled == 0 and s.reuse.saved != null) s.cached = s.reuse.at; + } +}; + +const prompt = [_]u32{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 }; + +test "a lent state evicted before the first call: the job fills cold, marks and promise planned again, counted" { + var cfg = try lanes.Config.init(a, .{ .exact_width = 8, .gpu_tokens = true, .hidden_rows = true }, 8, 7); + defer cfg.deinit(a); + var target: lanes.fake.Fake = .{ .gpa = a, .prefill_chunks = 4 }; + defer target.deinit(); + var clock: lanes.fake.FixedClock = .{}; + var core = lanes.Engine.init(a, &cfg, target.stepped(), clock.clock()); + defer core.deinit(); + var snaps: Snaps = .{ .f = &target }; + var store = pc.Store.init(a, .{ .ptr = &snaps, .vtable = &.{ .bytes = Snaps.bytes, .save = Snaps.save, .restore = Snaps.restore, .drop = Snaps.drop } }, .{ .min_prompt = 0 }, 1000); + defer store.deinit(); + const req: api.Request = .{ .prompt = &prompt, .max_tokens = 2, .history_len = 16 }; + { // the prompt's state kept at 16 + var h = api.LaneHost.init(a, std.testing.io, &core, .{ .lanes = 1 }); + h.cache = &store; + try h.start(); + defer h.stop(); + var box: Box = .{}; + try h.engine().submit(1, &req, .{ .ctx = &box, .event = Box.event }); + try box.wait(); + } + target.prefill_hook = Snaps.hook; + target.prefill_hook_ctx = &snaps; + var h = api.LaneHost.init(a, std.testing.io, &core, .{ .lanes = 1 }); // its steps run on this thread + h.cache = &store; + defer h.stop(); + var box: Box = .{}; + try h.engine().submit(2, &req, .{ .ctx = &box, .event = Box.event }); + try std.testing.expect(h.admitOne()); + const job = h.filling.items[0]; + try std.testing.expect(job.lent != null); // admitted on the kept state, lent back until its first call + try std.testing.expectEqual(@as(u32, 16), job.stream.reuse.at); + try std.testing.expectEqual(@as(usize, 0), job.marks.len); // a resumed pass keeps nothing up to its state + // evicted before its first call + const e = for (store.entries.items) |x| { + if (x.serial == job.lent.?) break x; + } else return error.NotKept; + store.remove(std.mem.indexOfScalar(*pc.Entry, store.entries.items, e).?); + const rows = fill.step(&h, 0); + // its first call filled from the start: the step counts the rows it ran, not none + try std.testing.expect(rows != std.math.maxInt(u64)); + try std.testing.expectEqual(@as(u64, job.stream.fill_at.load(.monotonic)), rows); + try std.testing.expectEqual(@as(u32, 0), job.stream.reuse.at); + try std.testing.expect(job.load.sure and job.load.hint == 0); // the load ledger counts its chunks + try std.testing.expect(std.mem.indexOfScalar(u32, job.marks, 16) != null); // a cold pass keeps its state again + try std.testing.expect(job.cache_promise.slots > 0); // and is promised the room for it + try h.start(); // the rest of the request on the lane thread + try box.wait(); + try std.testing.expectEqual(@as(usize, 1), store.entries.items.len); // kept again at 16 +} diff --git a/zig/src/core/lane_host_live_chunk_test.zig b/zig/src/core/lane_host_live_chunk_test.zig new file mode 100644 index 00000000000..a127311daa8 --- /dev/null +++ b/zig/src/core/lane_host_live_chunk_test.zig @@ -0,0 +1,109 @@ +//! A long prompt beside a live stream: split at the cap, the same tokens as one pass, the gap between rounds one chunk. +const std = @import("std"); +const lanes = @import("lanes"); +const api = @import("engine_api.zig"); +const LaneHost = @import("lane_host.zig").LaneHost; +const fill = @import("lane_host_fill.zig"); +const ends = @import("lane_host_end.zig"); +const t = std.testing; + +const long_rows = 12288; +const live_tokens = 64; +const long_tokens = 8; + +/// Each request's tokens as the host delivered them. +const Sink = struct { + live: [live_tokens]u32 = undefined, + long: [long_tokens]u32 = undefined, + live_n: usize = 0, + long_n: usize = 0, + + fn event(ctx: *anyopaque, id: api.Id, e: *const api.Event) void { + const s: *Sink = @ptrCast(@alignCast(ctx)); + if (e.* != .tokens) return; + for (e.tokens) |token| { + if (id == 1) { + s.live[s.live_n] = token; + s.live_n += 1; + } else { + s.long[s.long_n] = token; + s.long_n += 1; + } + } + } + + fn done(s: *const Sink) bool { + return s.live_n == live_tokens and s.long_n == long_tokens; + } +}; + +const Run = struct { sink: Sink = .{}, widest: u64 = 0, steps: usize = 0, rounds_during: usize = 0 }; + +/// The host's loop by hand: a live stream decoding, then a 12,288-row prompt; `share` is --decode-share. +fn twoStreams(share: ?f64, out: *Run) !void { + const gpa = t.allocator; + var cfg = try lanes.Config.init(gpa, .{ .exact_width = 8, .gpu_tokens = true, .hidden_rows = true }, 8, 7); + defer cfg.deinit(gpa); + var target: lanes.fake.Fake = .{ .gpa = gpa, .prefill_chunks = 1 }; + defer target.deinit(); + var clock: lanes.fake.FixedClock = .{}; + var core = lanes.Engine.init(gpa, &cfg, target.stepped(), clock.clock()); + defer core.deinit(); + core.backend.chunk_invariant = true; + var host = LaneHost.init(gpa, t.io, &core, .{ .lanes = 4, .decode_share = share }); + defer { + ends.closeAll(&host); + host.stop(); + } + const sink: api.Sink = .{ .ctx = &out.sink, .event = Sink.event }; + const live: api.Request = .{ .prompt = &.{ 3, 1, 4, 1 }, .max_tokens = live_tokens, .drafts = false }; + try host.engine().submit(1, &live, sink); + try t.expect(host.admitOne()); + while (host.filling.items.len > 0) fill.run(&host); + var prompt: [long_rows]u32 = undefined; + for (&prompt, 0..) |*token, i| token.* = @intCast(i % 89 + 2); + const long: api.Request = .{ .prompt = &prompt, .max_tokens = long_tokens, .drafts = false }; + try host.engine().submit(2, &long, sink); + try t.expect(host.admitOne()); + var visits: usize = 0; + while (!out.sink.done()) : (visits += 1) { + if (visits == 4096) return error.RunNeverEnded; + host.share.debt_ns = 0; // the round below paid the last step's debt + const job = if (host.filling.items.len > 0) host.filling.items[0] else null; + const before = if (job) |j| j.stream.fill_at.load(.monotonic) else 0; + const filling = job != null; + fill.run(&host); + if (filling) { + const open = host.filling.items.len > 0; + const after = if (open) host.filling.items[0].stream.fill_at.load(.monotonic) else long_rows; + out.widest = @max(out.widest, after - before); + out.steps += 1; + } + try core.sweep(); + ends.deliverPending(&host); + if (core.activeCount() == 0) continue; + if (filling and host.filling.items.len > 0) out.rounds_during += 1; + try core.step(); + } +} + +test "a long prompt beside a live stream splits at the cap, with the tokens of the unsplit pass" { + var whole: Run = .{}; + try twoStreams(null, &whole); + var split: Run = .{}; + try twoStreams(0.5, &split); + try t.expectEqual(@as(u64, long_rows), whole.widest); // no flag: today's one pass + try t.expectEqual(@as(usize, 1), whole.steps); + try t.expectEqual(@as(u32, 512), fill.decode_cap_rows); // the cap these cases pin, written out so a change shows here + try t.expectEqual(@as(u64, 512), split.widest); + try t.expectEqual(@as(usize, long_rows / 512), split.steps); + try t.expectEqualSlices(u32, &whole.sink.live, &split.sink.live); + try t.expectEqualSlices(u32, &whole.sink.long, &split.sink.long); +} + +test "the live stream gets a round after every chunk but the last: its gap is one chunk" { + var split: Run = .{}; + try twoStreams(0.5, &split); + try t.expectEqual(split.steps - 1, split.rounds_during); + try t.expect(split.widest <= 512); +} diff --git a/zig/src/core/lane_host_load.zig b/zig/src/core/lane_host_load.zig index 4f6c725b092..33b55bde7de 100644 --- a/zig/src/core/lane_host_load.zig +++ b/zig/src/core/lane_host_load.zig @@ -78,11 +78,14 @@ pub fn publish(h: *LaneHost) void { /// A prompt pass starts and its fill shows, a new attempt from zero: a requeued job's repeated work counts again. pub fn began(h: *LaneHost, job: *Job) void { - h.lock(); - defer h.unlock(); // its publish sees the pass and its fill together: a blocking prefill may unlock no more - const hint = job.stream.fill_at.load(.monotonic); - job.load = .{ .on = true, .hint = hint, .sure = hint == 0 }; - job.fill_on.store(true, .release); // status readers count the fill from here until the pass reports + { + h.lock(); + defer h.unlock(); // its publish sees the pass and its fill together: a blocking prefill may unlock no more + const hint = job.stream.fill_at.load(.monotonic); + job.load = .{ .on = true, .hint = hint, .sure = hint == 0 }; + job.fill_on.store(true, .release); // status readers count the fill from here until the pass reports + } + @import("lane_host_status.zig").publish(h); // a reader sees the fill start at once } /// A backend prompt call for `job` starts now (engine thread). diff --git a/zig/src/core/lane_host_lone.zig b/zig/src/core/lane_host_lone.zig index 44b3f97a85f..b6da0e1166c 100644 --- a/zig/src/core/lane_host_lone.zig +++ b/zig/src/core/lane_host_lone.zig @@ -24,7 +24,7 @@ pub fn reclaim(h: *LaneHost) void { const lone = h.lone orelse return; if (!lone.resumes) return; // a driver that only opens streams would prefill this one again h.lock(); - const idle = h.admitted.items.len == 1 and h.queued.items.len == 0 and h.filling.items.len == 0 and !h.foregroundWaiting() and h.cancels.items.len == 0 and !h.closing; + const idle = h.admitted.items.len == 1 and h.queued.items.len == 0 and h.filling.items.len == 0 and !h.foregroundWaiting() and h.cancels.items.len == 0 and !h.closing.load(.acquire); const job = if (idle) h.admitted.items[0] else null; h.unlock(); const j = job orelse return; @@ -60,7 +60,7 @@ pub fn run(h: *LaneHost, job: *Job, began: i96, resumed: bool) bool { host.lock(); defer host.unlock(); // a reader `limit` behind hands its stream back: the host holds it until its client reads - return host.foregroundWaiting() or host.cancels.items.len > 0 or host.closing or backlog.behind(host, host.lone_job.?); + return host.foregroundWaiting() or host.cancels.items.len > 0 or host.closing.load(.acquire) or backlog.behind(host, host.lone_job.?); } fn prefillYield(ctx: *anyopaque) bool { if (!yield(ctx)) return false; diff --git a/zig/src/core/lane_host_lone_test.zig b/zig/src/core/lane_host_lone_test.zig index 07fcca8e1a4..1656a59e252 100644 --- a/zig/src/core/lane_host_lone_test.zig +++ b/zig/src/core/lane_host_lone_test.zig @@ -310,14 +310,17 @@ const LogBox = struct { } } - fn wait(b: *@This()) Reason { - while (true) { + /// The reply's end within a minute: a stall fails by name here, not at the step's 20-minute bound. + fn wait(b: *@This()) !Reason { + const deadline = std.Io.Clock.awake.now(std.testing.io).toNanoseconds() + 60 * std.time.ns_per_s; + while (std.Io.Clock.awake.now(std.testing.io).toNanoseconds() < deadline) { b.mutex.lockUncancelable(std.testing.io); const d = b.done; b.mutex.unlock(std.testing.io); if (d) |r| return r; std.Io.sleep(std.testing.io, .fromMilliseconds(1), .awake) catch {}; } + return error.ReplyNeverFinished; } fn deinit(b: *@This()) void { @@ -326,20 +329,55 @@ const LogBox = struct { } }; +/// The fake target holding shared rounds at a gate: no lane frees, so a queued request stays queued until it opens. +const Gated = struct { + target: lanes.fake.Fake = .{ .gpa = gpa }, + vtable: lanes.backend.Backend.VTable = undefined, + held: std.Io.Event = .unset, // a shared round waits at the gate + open: std.Io.Event = .unset, + + fn backend(g: *Gated) lanes.backend.Backend { + var b = g.target.backend(); + g.vtable = b.vtable.*; + g.vtable.verify = verify; + b.vtable = &g.vtable; + return b; + } + + fn verify(ptr: *anyopaque, windows: []const lanes.backend.Window, out: []lanes.backend.Verified) anyerror!void { + const g: *Gated = @fieldParentPtr("target", @as(*lanes.fake.Fake, @ptrCast(@alignCast(ptr)))); + if (windows.len >= 2 and !g.open.isSet()) { + g.held.set(std.testing.io); + g.open.waitUncancelable(std.testing.io); + } + return g.target.backend().vtable.verify(ptr, windows, out); + } +}; + +/// `e` set within `seconds`, else a named failure: no wait in these tests runs to the step's bound. +fn within(e: *std.Io.Event, seconds: i64) !void { + const deadline = std.Io.Clock.awake.now(std.testing.io).toNanoseconds() + seconds * std.time.ns_per_s; + while (!e.isSet()) { + if (std.Io.Clock.awake.now(std.testing.io).toNanoseconds() >= deadline) return error.GateNeverReached; + e.waitTimeout(std.testing.io, .{ .duration = .{ .raw = .fromMilliseconds(10), .clock = .awake } }) catch {}; + } +} + test "lone driver: a third tiny prompt at two lanes starts within two rounds and shares later rounds" { const Wait = @import("wait_reason.zig").Wait; var costs: [16]lanes.config.Cost = undefined; for (&costs, 1..) |*c, w| c.* = .{ .width = @intCast(w), .ms = 5.0 + 0.8 * @as(f64, @floatFromInt(w)) }; var cfg = try draftedConfig(&costs); defer cfg.deinit(gpa); - var target: lanes.fake.Fake = .{ .gpa = gpa }; - defer target.deinit(); + var gated: Gated = .{}; + defer gated.target.deinit(); + const target = gated.backend(); var clock: lanes.fake.FixedClock = .{}; - var core = lanes.Engine.init(gpa, &cfg, target.backend(), clock.clock()); + var core = lanes.Engine.init(gpa, &cfg, target, clock.clock()); defer core.deinit(); var host = LaneHost.init(gpa, std.testing.io, &core, .{ .lanes = 2 }); // its opening waits for A, B and C: a fake reply takes microseconds and could otherwise end before B arrives - var driver: Lone = .{ .be = target.backend(), .hold_open = true }; + var driver: Lone = .{ .be = target, .hold_open = true }; host.lone = .{ .ctx = &driver, .run = Lone.run, .resumes = true }; try host.start(); defer host.stop(); @@ -364,25 +402,30 @@ test "lone driver: a third tiny prompt at two lanes starts within two rounds and try host.engine().submit(3, &rc, .{ .ctx = &c, .event = LogBox.event }); driver.open.set(std.testing.io); - // A and B hold both lanes; C waits with a named reason; the loop waits on the state alone, not a time bound. - while (true) { + // A and B's first shared round waits at the gate: both lanes held, C queued alone, whenever this thread runs. + try within(&gated.held, 60); + { host.mutex.lockUncancelable(std.testing.io); - const reason: ?Wait = if (host.queued.items.len > 0) host.queued.items[0].wait_reason else null; - host.mutex.unlock(std.testing.io); - if (reason == .engine_busy) break; - std.Io.sleep(std.testing.io, .fromMilliseconds(1), .awake) catch {}; + defer host.mutex.unlock(std.testing.io); + try std.testing.expectEqual(@as(usize, 1), host.queued.items.len); + try std.testing.expectEqual(@as(Id, 3), host.queued.items[0].id); + try std.testing.expectEqual(Wait.engine_busy, host.queued.items[0].wait_reason); } - host.mutex.lockUncancelable(std.testing.io); - try std.testing.expect(host.queued.items.len > 0); - try std.testing.expectEqual(Wait.engine_busy, host.queued.items[0].wait_reason); - host.mutex.unlock(std.testing.io); - // A fourth request joins behind C and must not pass it. + // A fourth request joins behind C (submit queues it under the host's lock) and must not pass it. try host.engine().submit(4, &rd, .{ .ctx = &d, .event = LogBox.event }); - try std.testing.expectEqual(Reason.length, a.wait()); - try std.testing.expectEqual(Reason.length, c.wait()); - try std.testing.expectEqual(Reason.length, d.wait()); - try std.testing.expectEqual(Reason.length, b.wait()); + { + host.mutex.lockUncancelable(std.testing.io); + defer host.mutex.unlock(std.testing.io); + try std.testing.expectEqual(@as(usize, 2), host.queued.items.len); + try std.testing.expectEqual(@as(Id, 3), host.queued.items[0].id); + try std.testing.expectEqual(@as(Id, 4), host.queued.items[1].id); + } + gated.open.set(std.testing.io); + try std.testing.expectEqual(Reason.length, try a.wait()); + try std.testing.expectEqual(Reason.length, try c.wait()); + try std.testing.expectEqual(Reason.length, try d.wait()); + try std.testing.expectEqual(Reason.length, try b.wait()); try std.testing.expect(c.stats.queued_seconds > 0); try std.testing.expect(c.stats.rounds > 0); try std.testing.expect(c.order < d.order); @@ -433,8 +476,8 @@ test "lone driver: a stream it hands back after tokens of its own goes on from t driver.paused.waitUncancelable(std.testing.io); try host.engine().submit(2, &rb, .{ .ctx = &b, .event = LogBox.event }); driver.go.set(std.testing.io); // its next check sees B waiting: A goes back to the lane core mid-reply - try std.testing.expectEqual(Reason.length, a.wait()); - try std.testing.expectEqual(Reason.length, b.wait()); + try std.testing.expectEqual(Reason.length, try a.wait()); + try std.testing.expectEqual(Reason.length, try b.wait()); try std.testing.expect(driver.resumed >= 1 and driver.commits >= 5); try expectRule(&ra, a.tokens.items); try expectRule(&rb, b.tokens.items); diff --git a/zig/src/core/lane_host_rows.zig b/zig/src/core/lane_host_rows.zig index bfeaf32aa2b..8c64c81da06 100644 --- a/zig/src/core/lane_host_rows.zig +++ b/zig/src/core/lane_host_rows.zig @@ -16,7 +16,7 @@ pub fn drain(ctx: *anyopaque) void { pub fn drainThread(h: *LaneHost) void { h.lock(); - h.closing = true; + h.closing.store(true, .release); h.wake.broadcast(h.io); h.unlock(); if (h.thread) |t| t.join(); @@ -28,7 +28,7 @@ pub fn ask(ctx: *anyopaque, a: *api.ImprintAsk) bool { const h: *LaneHost = @ptrCast(@alignCast(ctx)); h.lock(); defer h.unlock(); - if (h.closing or (a.op == .flush and h.cache == null) or !h.disk.push(h.gpa, a)) return false; // no store: 501 + if (h.closing.load(.acquire) or (a.op == .flush and h.cache == null) or !h.disk.push(h.gpa, a)) return false; // no store: 501 h.wake.signal(h.io); return true; } @@ -70,7 +70,7 @@ pub fn ready(h: *LaneHost) bool { const store = h.cache orelse return false; const r = store.disk orelse return false; if (!rows.write.ready(r)) return false; - if (h.queued.items.len > 0 or h.admitted.items.len > 0 or h.cancels.items.len > 0 or h.closing) return false; + if (h.queued.items.len > 0 or h.admitted.items.len > 0 or h.cancels.items.len > 0 or h.closing.load(.acquire)) return false; return !r.sync_writes or h.disk.quiet(h.admissions, std.Io.Clock.awake.now(h.io).toNanoseconds()); } diff --git a/zig/src/core/lane_host_score.zig b/zig/src/core/lane_host_score.zig index 6e804923315..4a4576ca57f 100644 --- a/zig/src/core/lane_host_score.zig +++ b/zig/src/core/lane_host_score.zig @@ -57,7 +57,7 @@ pub fn decide(ctx: *anyopaque, d: *api.Decision) error{ Failed, Refused }!void { fn put(h: *LaneHost, ask: *Ask) error{Failed}!void { h.lock(); defer h.unlock(); - if (h.closing) return error.Failed; + if (h.closing.load(.acquire)) return error.Failed; h.scores.asks.append(h.gpa, ask) catch return error.Failed; h.wake.broadcast(h.io); while (!ask.done) h.scores.answered.waitUncancelable(h.io, &h.mutex); @@ -81,7 +81,7 @@ pub fn answer(h: *LaneHost) void { for (list) |a| { // a drain's deadline stops the queue: the started score finishes, the rest fail without running h.lock(); - const closing = h.closing; + const closing = h.closing.load(.acquire); h.unlock(); if (closing) { a.failed = true; @@ -123,7 +123,7 @@ pub fn answer(h: *LaneHost) void { /// Questions left when the engine stops: each fails. pub fn close(h: *LaneHost) void { h.lock(); - h.closing = true; + h.closing.store(true, .release); for (h.scores.asks.items) |a| { a.failed = true; a.done = true; diff --git a/zig/src/core/lane_host_score_exit_test.zig b/zig/src/core/lane_host_score_exit_test.zig index fed2be91e9f..c3362756083 100644 --- a/zig/src/core/lane_host_score_exit_test.zig +++ b/zig/src/core/lane_host_score_exit_test.zig @@ -9,7 +9,7 @@ fn failAfterAsk(ptr: *anyopaque) anyerror!void { const h: *LaneHost = @ptrCast(@alignCast(ptr)); h.lock(); defer h.unlock(); - while (h.scores.asks.items.len == 0 and !h.closing) h.wake.waitUncancelable(h.io, &h.mutex); + while (h.scores.asks.items.len == 0 and !h.closing.load(.acquire)) h.wake.waitUncancelable(h.io, &h.mutex); return error.InjectedInitializationFailure; } fn neverScore(_: *anyopaque, _: []const u32, _: []const u32, _: []f64, _: bool) anyerror!f64 { diff --git a/zig/src/core/lane_host_score_test.zig b/zig/src/core/lane_host_score_test.zig index 693af5e0c1e..39f06932d4e 100644 --- a/zig/src/core/lane_host_score_test.zig +++ b/zig/src/core/lane_host_score_test.zig @@ -73,7 +73,7 @@ const Closer = struct { calls += 1; const h = host.?; h.lock(); - h.closing = true; + h.closing.store(true, .release); h.unlock(); @memset(logits, 1); return 0; diff --git a/zig/src/core/lane_host_stale_test.zig b/zig/src/core/lane_host_stale_test.zig index 92afb7204c7..980fa22ff5b 100644 --- a/zig/src/core/lane_host_stale_test.zig +++ b/zig/src/core/lane_host_stale_test.zig @@ -72,7 +72,7 @@ const Seen = struct { fn waitStale(host: *LaneHost, want: bool) !void { for (0..5000) |_| { host.mutex.lockUncancelable(std.testing.io); - const s = host.stale; + const s = host.stale.load(.acquire); host.mutex.unlock(std.testing.io); if (s == want) return; std.Io.sleep(std.testing.io, .fromMilliseconds(1), .awake) catch {}; diff --git a/zig/src/core/lane_host_status.zig b/zig/src/core/lane_host_status.zig index 954f5871c7a..46e2ec18ece 100644 --- a/zig/src/core/lane_host_status.zig +++ b/zig/src/core/lane_host_status.zig @@ -8,31 +8,153 @@ const LaneHost = @import("lane_host.zig").LaneHost; pub const Mark = struct { at: i96, tokens: u64 }; const window_ns: i96 = 2 * std.time.ns_per_s; -/// Engine.status: the counts, read under the host's lock. +/// Engine.status: the counts, copied from the engine thread's published snapshot without the host's lock (issue 3200). pub fn read(ctx: *anyopaque, out: *api.Status, stream_tokens: []u32) void { const h: *LaneHost = @ptrCast(@alignCast(ctx)); - h.mutex.lockUncancelable(h.io); - defer h.mutex.unlock(h.io); - const now = std.Io.Clock.awake.now(h.io).toNanoseconds(); + var s: Snapshot = undefined; + var n: usize = 0; + var now: i96 = undefined; var tokens: u64 = 0; - for (h.decoded.items) |m| { - if (m.at >= now - window_ns) tokens += m.tokens; + while (true) { + n = 0; + const v1 = h.st.seq.load(.acquire); + if (v1 % 2 != 0) { + std.atomic.spinLoopHint(); + continue; + } + s = h.st.snap; + const slot = s.slot; + _ = h.st.readers[slot].fetchAdd(1, .acq_rel); + if (h.st.seq.load(.acquire) != v1) { + _ = h.st.readers[slot].fetchSub(1, .acq_rel); + continue; + } + now = std.Io.Clock.awake.now(h.io).toNanoseconds(); + tokens = 0; + for (h.st.decode_slots[slot].items) |m| { + if (m.at >= now - window_ns) tokens += m.tokens; + } + if (s.live_len > 0) { + const buf = h.st.live_slots[slot].items; + n = @min(stream_tokens.len, s.live_len); + @memcpy(stream_tokens[0..n], buf[0..n]); + } + const stable = h.st.seq.load(.acquire) == v1; + _ = h.st.readers[slot].fetchSub(1, .acq_rel); + if (stable) break; } - const n = @min(stream_tokens.len, h.live_tokens.items.len); - @memcpy(stream_tokens[0..n], h.live_tokens.items[0..n]); out.* = .{ - .healthy = !h.closing and !h.stale and (if (h.health) |source| source.read(source.ctx) else true), - .running = @intCast(h.admitted.items.len), - .waiting = @intCast(h.queued.items.len), + .healthy = !h.closing.load(.acquire) and !h.stale.load(.acquire) and (if (h.health) |source| source.read(source.ctx) else true), + .running = @intCast(s.running), + .waiting = @intCast(s.waiting), .decode_tokens_per_second = @as(f64, @floatFromInt(tokens)) / 2.0, - .prefill_tokens_per_second = if (now - h.prefill_at <= window_ns) h.prefill_rate else 0, + .prefill_tokens_per_second = if (now - s.prefill_at <= window_ns) s.prefill_rate else 0, .streams = n, - .generation_tokens = h.live_generated, - .prompt_cache = h.cache_status, - .disk = h.disk_status, + .generation_tokens = s.generation_tokens, + .prompt_cache = s.cache_status, + .disk = s.disk_status, .fsr = if (h.fsr) |source| source.read(source.ctx) else null, + .fill_prompt_tokens = s.fill_prompt_tokens, + .fill_tokens_left = s.fill_tokens_left, + .fill_unknown = s.fill_unknown, + .fill_run = s.fill_run, }; - fillTotals(h, out); +} + +/// The lane host's status state: the published snapshot, its seqlock, the live slots and the round-wait counter. +pub const State = struct { + snap: Snapshot = .{}, + seq: std.atomic.Value(u32) = .init(0), // odd while the engine thread publishes + live_slots: [2]std.ArrayList(u32) = .{ .empty, .empty }, + decode_slots: [2]std.ArrayList(Mark) = .{ .empty, .empty }, + readers: [2]std.atomic.Value(u32) = .{ .init(0), .init(0) }, // registered before slot access; writers drain their target + live_tokens: std.ArrayList(u32) = .empty, + live_generated: u64 = 0, + cache_status: ?api.Status.PromptCache = null, + disk_status: ?api.Status.DiskCache = null, + round_waits: std.atomic.Value(u64) = .init(0), + engine_id: std.Thread.Id = 0, + engine_running: std.atomic.Value(bool) = .init(false), + prefill_rate: f64 = 0, + prefill_at: i96 = 0, +}; + +/// The engine thread's id, so its lock acquisitions can be told from the others'. +pub fn engineStart(h: *LaneHost) void { + h.st.engine_id = std.Thread.getCurrentId(); + h.st.engine_running.store(true, .release); +} + +/// Takes the host's lock for the engine thread and counts a wait; false when the caller must lock. +pub fn takeEngineLock(h: *LaneHost) bool { + if (!h.st.engine_running.load(.acquire) or std.Thread.getCurrentId() != h.st.engine_id) return false; + if (h.mutex.tryLock()) return true; + _ = h.st.round_waits.fetchAdd(1, .monotonic); + h.mutex.lockUncancelable(h.io); + return true; +} + +/// Frees the status state when the host stops. +pub fn freeSlots(h: *LaneHost) void { + h.st.seq.store(h.st.seq.load(.monotonic) | 1, .release); // teardown admits no new slot readers + for (&h.st.readers) |*readers| while (readers.load(.acquire) != 0) std.atomic.spinLoopHint(); + h.st.live_tokens.deinit(h.gpa); + for (&h.st.live_slots) |*slot| slot.deinit(h.gpa); + for (&h.st.decode_slots) |*slot| slot.deinit(h.gpa); + h.st.snap = .{}; + h.st.seq.store(h.st.seq.load(.monotonic) +% 1, .release); // a late reader sees the empty terminal snapshot +} + +/// The lane host's status state: the published snapshot, its seqlock, the live slots and the round-wait counter. +pub const Snapshot = struct { + slot: usize = 0, + live_len: usize = 0, + running: usize = 0, + waiting: usize = 0, + prefill_rate: f64 = 0, + prefill_at: i96 = 0, + generation_tokens: u64 = 0, + cache_status: ?api.Status.PromptCache = null, + disk_status: ?api.Status.DiskCache = null, + fill_prompt_tokens: ?u32 = null, + fill_tokens_left: ?u32 = null, + fill_unknown: bool = false, + fill_run: u64 = 0, +}; + +/// Publishes the snapshot for the next read; the caller holds no lock (issue 3200). +pub fn publish(h: *LaneHost) void { + h.lock(); + defer h.unlock(); + var tmp: api.Status = .{}; + fillTotals(h, &tmp); + const slot = (h.st.snap.slot + 1) % 2; + h.st.seq.store(h.st.seq.load(.monotonic) | 1, .release); // odd: a reader retries + while (h.st.readers[slot].load(.acquire) != 0) std.atomic.spinLoopHint(); + var len: usize = 0; + if (h.st.live_tokens.items.len > 0) { + h.st.live_slots[slot].clearRetainingCapacity(); + h.st.live_slots[slot].appendSlice(h.gpa, h.st.live_tokens.items) catch {}; + len = h.st.live_slots[slot].items.len; + } + h.st.decode_slots[slot].clearRetainingCapacity(); + h.st.decode_slots[slot].appendSlice(h.gpa, h.decoded.items) catch {}; + h.st.snap = .{ + .slot = slot, + .live_len = len, + .running = h.admitted.items.len, + .waiting = h.queued.items.len, + .prefill_rate = h.st.prefill_rate, + .prefill_at = h.st.prefill_at, + .generation_tokens = h.st.live_generated, + .cache_status = h.st.cache_status, + .disk_status = h.st.disk_status, + .fill_prompt_tokens = tmp.fill_prompt_tokens, + .fill_tokens_left = tmp.fill_tokens_left, + .fill_unknown = tmp.fill_unknown, + .fill_run = tmp.fill_run, + }; + h.st.seq.store(h.st.seq.load(.monotonic) +% 1, .release); // even: the copy is stable } /// A job whose prompt pass has not reported yet is filling; the engine thread publishes that with `fill_on`. @@ -65,42 +187,48 @@ fn fillTotals(h: *LaneHost, out: *api.Status) void { /// `n` tokens delivered now; marks older than the window drop. pub fn noteDecoded(h: *LaneHost, n: usize, first: bool) void { - const now = std.Io.Clock.awake.now(h.io).toNanoseconds(); - h.mutex.lockUncancelable(h.io); - defer h.unlock(); - var keep: usize = 0; - for (h.decoded.items) |m| { - if (m.at < now - window_ns) continue; - h.decoded.items[keep] = m; - keep += 1; + { + const now = std.Io.Clock.awake.now(h.io).toNanoseconds(); + h.mutex.lockUncancelable(h.io); + defer h.mutex.unlock(h.io); + var keep: usize = 0; + for (h.decoded.items) |m| { + if (m.at < now - window_ns) continue; + h.decoded.items[keep] = m; + keep += 1; + } + h.decoded.shrinkRetainingCapacity(keep); + h.decoded.append(h.gpa, .{ .at = now, .tokens = n }) catch {}; + @import("lane_host_load.zig").decoded(h, n, first); } - h.decoded.shrinkRetainingCapacity(keep); - h.decoded.append(h.gpa, .{ .at = now, .tokens = n }) catch {}; - @import("lane_host_load.zig").decoded(h, n, first); + publish(h); } /// Each started stream's context and generated tokens, for the next status read. pub fn noteLive(h: *LaneHost) void { - h.mutex.lockUncancelable(h.io); - defer h.unlock(); - h.live_tokens.clearRetainingCapacity(); - h.live_generated = 0; - const now_ms = @import("rows_io.zig").wallMs(); - if (h.cache) |s| { - if (h.cache_status == null or now_ms - h.cache_at >= 1000) { // the full copies at 1 Hz at most - h.cache_status = snap.PromptCache(s); - h.disk_status = snap.Disk(s); - h.cache_at = now_ms; + { + h.mutex.lockUncancelable(h.io); + defer h.mutex.unlock(h.io); + h.st.live_tokens.clearRetainingCapacity(); + h.st.live_generated = 0; + const now_ms = @import("rows_io.zig").wallMs(); + if (h.cache) |s| { + if (h.st.cache_status == null or now_ms - h.cache_at >= 1000) { // the full copies at 1 Hz at most + h.st.cache_status = snap.PromptCache(s); + h.st.disk_status = snap.Disk(s); + h.cache_at = now_ms; + } else { + h.st.cache_status.?.states = s.entries.items.len; // /metrics reads these every round, as before + h.st.cache_status.?.bytes = s.held + s.spare(); + } } else { - h.cache_status.?.states = s.entries.items.len; // /metrics reads these every round, as before - h.cache_status.?.bytes = s.held + s.spare(); + h.st.cache_status = null; + h.st.disk_status = null; } - } else { - h.cache_status = null; - h.disk_status = null; + for (h.admitted.items) |job| if (job.started) { + h.st.live_tokens.append(h.gpa, @intCast(job.stream.context.items.len)) catch {}; + h.st.live_generated += @intCast(job.stream.emitted().len); + }; } - for (h.admitted.items) |job| if (job.started) { - h.live_tokens.append(h.gpa, @intCast(job.stream.context.items.len)) catch {}; - h.live_generated += @intCast(job.stream.emitted().len); - }; + publish(h); } diff --git a/zig/src/core/lane_host_status_lock_test.zig b/zig/src/core/lane_host_status_lock_test.zig new file mode 100644 index 00000000000..0b1a35e001c --- /dev/null +++ b/zig/src/core/lane_host_status_lock_test.zig @@ -0,0 +1,267 @@ +//! A status read must never wait for another status read (issue 3200): a slow source read holds no lock. +const std = @import("std"); +const lanes = @import("lanes"); +const api = @import("engine_api.zig"); +const LaneHost = @import("lane_host.zig").LaneHost; +const Event = api.Event; +const Request = api.Request; + +/// A health source the test parks the reader inside: `read` signals `entered`, then waits for `release`. +const Gate = struct { + entered: std.atomic.Value(bool) = .init(false), + release: std.atomic.Value(bool) = .init(false), + calls: std.atomic.Value(u32) = .init(0), + + fn read(ctx: *anyopaque) bool { + const g: *Gate = @ptrCast(@alignCast(ctx)); + if (g.calls.fetchAdd(1, .monotonic) != 0) return true; // only the first read parks + g.entered.store(true, .release); + // auto-release: under the old code the caller holds the host's lock here, so nothing else can set `release` + var ms: usize = 0; + while (!g.release.load(.acquire) and ms < 1500) : (ms += 1) + std.Io.sleep(std.testing.io, .fromMilliseconds(1), .awake) catch {}; + return true; + } +}; + +const Tally = struct { + tokens: std.atomic.Value(usize) = .init(0), + done: std.atomic.Value(bool) = .init(false), + + fn event(ctx: *anyopaque, id: api.Id, e: *const Event) void { + _ = id; + const t: *@This() = @ptrCast(@alignCast(ctx)); + switch (e.*) { + .tokens => |toks| _ = t.tokens.fetchAdd(toks.len, .monotonic), + .finished => t.done.store(true, .release), + else => {}, + } + } +}; + +test "status: a read parked in a slow source read does not block the next read" { + const gpa = std.testing.allocator; + var cfg = try lanes.Config.init(gpa, .{ .exact_width = 8, .gpu_tokens = true, .hidden_rows = true }, 8, 7); + defer cfg.deinit(gpa); + var target: lanes.fake.Fake = .{ .gpa = gpa }; + defer target.deinit(); + var clock: lanes.fake.FixedClock = .{}; + var core = lanes.Engine.init(gpa, &cfg, target.stepped(), clock.clock()); + defer core.deinit(); + var gate: Gate = .{}; + var host = LaneHost.init(gpa, std.testing.io, &core, .{ .lanes = 2 }); + host.health = .{ .ctx = &gate, .read = Gate.read }; + try host.start(); + defer host.stop(); + + // The reader's first status read parks inside health.read: a dashboard polling a slow backend counter. + const Reader = struct { + fn run(engine: api.Engine, gated: *Gate) void { + _ = gated; + var status: api.Status = .{}; + var stream_tokens: [8]u32 = undefined; + engine.status(&status, &stream_tokens); // parks inside the gate's read + engine.status(&status, &stream_tokens); // one more read after the release + } + }; + var reader = try std.Thread.spawn(.{}, Reader.run, .{ host.engine(), &gate }); + defer reader.join(); + + var waited: usize = 0; + while (!gate.entered.load(.acquire) and waited < 2000) : (waited += 1) + std.Io.sleep(std.testing.io, .fromMilliseconds(1), .awake) catch {}; + try std.testing.expect(gate.entered.load(.acquire)); // the reader is parked inside health.read + + // The next read must not wait for it: the reader holds no host lock. + var status: api.Status = .{}; + var stream_tokens: [8]u32 = undefined; + const began = std.Io.Clock.awake.now(std.testing.io).toNanoseconds(); + host.engine().status(&status, &stream_tokens); + const waited_ns = std.Io.Clock.awake.now(std.testing.io).toNanoseconds() - began; + try std.testing.expect(waited_ns < 200 * std.time.ns_per_ms); // it returned while the reader was parked + try std.testing.expect(status.healthy); // and it read a whole snapshot + + gate.release.store(true, .release); + + // The request still runs and finishes normally. + var tally: Tally = .{}; + const prompt = [_]u32{ 3, 1, 4, 1, 5, 9, 2, 6 }; + var request: Request = .{ .prompt = &prompt, .max_tokens = 64 }; + _ = try host.engine().submit(1, &request, .{ .ctx = &tally, .event = Tally.event }); + var deadline: usize = 0; + while (!tally.done.load(.acquire) and deadline < 8000) : (deadline += 1) + std.Io.sleep(std.testing.io, .fromMilliseconds(2), .awake) catch {}; + try std.testing.expect(tally.done.load(.acquire)); // the request finishes normally + try std.testing.expect(tally.tokens.load(.monotonic) >= 8); // with its tokens +} + +/// A health source every read pays for: the shape of a backend counter that costs the reader time. +const Slow = struct { + fn read(ctx: *anyopaque) bool { + _ = ctx; + std.Io.sleep(std.testing.io, .fromMilliseconds(2), .awake) catch {}; + return true; + } +}; + +test "status: a reader hammering the status during rounds never makes the round wait" { + const gpa = std.testing.allocator; + var cfg = try lanes.Config.init(gpa, .{ .exact_width = 8, .gpu_tokens = true, .hidden_rows = true }, 8, 7); + defer cfg.deinit(gpa); + var target: lanes.fake.Fake = .{ .gpa = gpa }; + defer target.deinit(); + var clock: lanes.fake.FixedClock = .{}; + var core = lanes.Engine.init(gpa, &cfg, target.stepped(), clock.clock()); + defer core.deinit(); + var host = LaneHost.init(gpa, std.testing.io, &core, .{ .lanes = 2 }); + host.health = .{ .ctx = &host, .read = Slow.read }; + try host.start(); + defer host.stop(); + + var tally: Tally = .{}; + const prompt = [_]u32{ 3, 1, 4, 1, 5, 9, 2, 6 }; + var request: Request = .{ .prompt = &prompt, .max_tokens = 64 }; + _ = try host.engine().submit(1, &request, .{ .ctx = &tally, .event = Tally.event }); + + // Wait for the request to be running: the baseline counts only the readers' waits. + var status: api.Status = .{}; + var stream_tokens: [8]u32 = undefined; + var waited: usize = 0; + while (waited < 4000) : (waited += 1) { + host.engine().status(&status, &stream_tokens); + if (status.running > 0) break; + std.Io.sleep(std.testing.io, .fromMilliseconds(2), .awake) catch {}; + } + const baseline = host.st.round_waits.load(.monotonic); + + // Four monitoring clients poll the status as fast as they can while the round runs. + const Hammer = struct { + fn run(engine: api.Engine, stop: *std.atomic.Value(bool)) void { + var s: api.Status = .{}; + var buf: [8]u32 = undefined; + while (!stop.load(.acquire)) engine.status(&s, &buf); + } + }; + var stop = std.atomic.Value(bool).init(false); + var hammers: [4]std.Thread = undefined; + for (&hammers) |*t| t.* = try std.Thread.spawn(.{}, Hammer.run, .{ host.engine(), &stop }); + defer { + stop.store(true, .release); + for (hammers) |t| t.join(); + } + + var deadline: usize = 0; + while (!tally.done.load(.acquire) and deadline < 10000) : (deadline += 1) + std.Io.sleep(std.testing.io, .fromMilliseconds(2), .awake) catch {}; + try std.testing.expect(tally.done.load(.acquire)); // the request finished under the hammering + try std.testing.expectEqual(baseline, host.st.round_waits.load(.monotonic)); // and no round waited for a reader +} + +test "status: idle decode marks expire individually at read time" { + const gpa = std.testing.allocator; + var cfg = try lanes.Config.init(gpa, .{ .exact_width = 8, .gpu_tokens = true, .hidden_rows = true }, 8, 7); + defer cfg.deinit(gpa); + var target: lanes.fake.Fake = .{ .gpa = gpa }; + defer target.deinit(); + var clock: lanes.fake.FixedClock = .{}; + var core = lanes.Engine.init(gpa, &cfg, target.stepped(), clock.clock()); + defer core.deinit(); + var host = LaneHost.init(gpa, std.testing.io, &core, .{ .lanes = 2 }); + defer host.stop(); + + const status = @import("lane_host_status.zig"); + status.noteDecoded(&host, 4, false); + host.decoded.items[0].at -= std.time.ns_per_s; // stagger the two marks' expiry inside the rolling window + status.noteDecoded(&host, 4, false); + var value: api.Status = .{}; + host.engine().status(&value, &.{}); + try std.testing.expectEqual(@as(f64, 4), value.decode_tokens_per_second); + + std.Io.sleep(std.testing.io, .fromMilliseconds(1100), .awake) catch {}; + host.engine().status(&value, &.{}); + try std.testing.expectEqual(@as(f64, 2), value.decode_tokens_per_second); // only the older mark expired + + std.Io.sleep(std.testing.io, .fromMilliseconds(1100), .awake) catch {}; + host.engine().status(&value, &.{}); + try std.testing.expectEqual(@as(f64, 0), value.decode_tokens_per_second); +} + +test "status: a registered slot reader holds off its next writer" { + const gpa = std.testing.allocator; + var cfg = try lanes.Config.init(gpa, .{ .exact_width = 8, .gpu_tokens = true, .hidden_rows = true }, 8, 7); + defer cfg.deinit(gpa); + var target: lanes.fake.Fake = .{ .gpa = gpa }; + defer target.deinit(); + var clock: lanes.fake.FixedClock = .{}; + var core = lanes.Engine.init(gpa, &cfg, target.stepped(), clock.clock()); + defer core.deinit(); + var host = LaneHost.init(gpa, std.testing.io, &core, .{ .lanes = 2 }); + defer host.stop(); + const status = @import("lane_host_status.zig"); + + try host.st.live_tokens.append(gpa, 42); + status.publish(&host); + const registered = host.st.snap.slot; + _ = host.st.readers[registered].fetchAdd(1, .acq_rel); + var first_done = std.atomic.Value(bool).init(false); + var finished = std.atomic.Value(bool).init(false); + const Writer = struct { + fn run(h: *LaneHost, first: *std.atomic.Value(bool), done: *std.atomic.Value(bool)) void { + @import("lane_host_status.zig").publish(h); + first.store(true, .release); + @import("lane_host_status.zig").publish(h); // this targets the registered slot and must wait + done.store(true, .release); + } + }; + var writer = try std.Thread.spawn(.{}, Writer.run, .{ &host, &first_done, &finished }); + var waited: usize = 0; + while (!first_done.load(.acquire) and waited < 2000) : (waited += 1) + std.Io.sleep(std.testing.io, .fromMilliseconds(1), .awake) catch {}; + std.Io.sleep(std.testing.io, .fromMilliseconds(2), .awake) catch {}; + const completed_first = first_done.load(.acquire); + const finished_before_release = finished.load(.acquire); + _ = host.st.readers[registered].fetchSub(1, .acq_rel); + writer.join(); + try std.testing.expect(completed_first); + try std.testing.expect(!finished_before_release); + try std.testing.expect(finished.load(.acquire)); + try std.testing.expectEqual(@as(u32, 0), host.st.readers[registered].load(.acquire)); +} + +test "status: terminal close publishes no queued or live work" { + const gpa = std.testing.allocator; + var cfg = try lanes.Config.init(gpa, .{ .exact_width = 8, .gpu_tokens = true, .hidden_rows = true }, 8, 7); + defer cfg.deinit(gpa); + var target: lanes.fake.Fake = .{ .gpa = gpa }; + defer target.deinit(); + var clock: lanes.fake.FixedClock = .{}; + var core = lanes.Engine.init(gpa, &cfg, target.stepped(), clock.clock()); + defer core.deinit(); + var host = LaneHost.init(gpa, std.testing.io, &core, .{ .lanes = 2 }); + defer host.stop(); + const status = @import("lane_host_status.zig"); + + var tally: Tally = .{}; + const request: Request = .{ .prompt = &.{ 3, 1, 4 }, .max_tokens = 1 }; + _ = try host.engine().submit(1, &request, .{ .ctx = &tally, .event = Tally.event }); + try host.st.live_tokens.append(gpa, 17); + host.st.live_generated = 3; + status.publish(&host); + var value: api.Status = .{}; + var buf: [1]u32 = undefined; + host.engine().status(&value, &buf); + try std.testing.expectEqual(@as(u32, 1), value.waiting); + try std.testing.expectEqual(@as(usize, 1), value.streams); + + @import("lane_host_end.zig").closeAll(&host); + host.engine().status(&value, &buf); + try std.testing.expectEqual(@as(u32, 0), value.running); + try std.testing.expectEqual(@as(u32, 0), value.waiting); + try std.testing.expectEqual(@as(usize, 0), value.streams); + try std.testing.expectEqual(@as(u64, 0), value.generation_tokens); + try std.testing.expectEqual(@as(?u32, null), value.fill_prompt_tokens); + try std.testing.expectEqual(@as(?u32, null), value.fill_tokens_left); + try std.testing.expect(!value.fill_unknown); + try std.testing.expectEqual(@as(u64, 0), value.fill_run); + try std.testing.expect(tally.done.load(.acquire)); +} diff --git a/zig/src/core/lane_host_step_borrow_test.zig b/zig/src/core/lane_host_step_borrow_test.zig new file mode 100644 index 00000000000..e8a9a3dd7ed --- /dev/null +++ b/zig/src/core/lane_host_step_borrow_test.zig @@ -0,0 +1,100 @@ +//! A stepped pass's restored prompt-cache entry goes back to the store after its first call, not at the pass's end. +const std = @import("std"); +const lanes = @import("lanes"); +const api = @import("engine_api.zig"); +const pc = @import("prompt_cache.zig"); +const fill = @import("lane_host_fill.zig"); +const a = std.testing.allocator; + +const Box = struct { + reason: api.Reason = .failed, + done: std.atomic.Value(bool) = .init(false), + fn event(ctx: *anyopaque, _: api.Id, e: *const api.Event) void { + const b: *Box = @ptrCast(@alignCast(ctx)); + if (e.* == .finished) { + b.reason = e.finished.reason; + b.done.store(true, .release); + } + } + fn wait(b: *Box) !api.Reason { + const began = std.Io.Clock.awake.now(std.testing.io).toNanoseconds(); + while (!b.done.load(.acquire)) { + if (std.Io.Clock.awake.now(std.testing.io).toNanoseconds() - began > 2 * std.time.ns_per_s) return error.RequestTimedOut; + std.Io.sleep(std.testing.io, .fromMilliseconds(1), .awake) catch {}; + } + return b.reason; + } +}; + +const Snaps = struct { + f: *lanes.fake.Fake, + store: *pc.Store = undefined, + prompt: []const u32 = &.{}, + at_second: ?u32 = null, // the entry's borrowers when the pass makes its second call + fn of(ctx: *anyopaque) *Snaps { + return @ptrCast(@alignCast(ctx)); + } + fn bytes(_: *anyopaque, _: u32) u64 { + return 1; + } + fn save(ctx: *anyopaque, owner: ?*anyopaque, at: u32) !pc.Saved { + return of(ctx).f.save(@ptrCast(@alignCast(owner.?)), at); + } + fn restore(_: *anyopaque, _: ?*anyopaque, _: pc.Saved) !void { + return error.BackendRestores; + } + fn drop(ctx: *anyopaque, saved: pc.Saved) void { + of(ctx).f.drop(saved); + } + /// The fake target's step: a real backend restores in its first call (cached set there), then each chunk. + fn hook(ctx: *anyopaque, s: *lanes.Stream, filled: usize) void { + const x = of(ctx); + if (s.reuse.saved == null and filled == 0) return; + if (filled == 0) s.cached = s.reuse.at; + if (filled == 1) if (x.store.find(x.prompt, &.{}, &.{})) |e| { + x.at_second = e.borrowers; + }; + } +}; + +test "a stepped pass gives its restored entry back after its first call" { + var cfg = try lanes.Config.init(a, .{ .exact_width = 8, .gpu_tokens = true, .hidden_rows = true }, 8, 7); + defer cfg.deinit(a); + var target: lanes.fake.Fake = .{ .gpa = a, .prefill_chunks = 4 }; + defer target.deinit(); + var clock: lanes.fake.FixedClock = .{}; + var core = lanes.Engine.init(a, &cfg, target.stepped(), clock.clock()); + defer core.deinit(); + const prompt = [_]u32{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }; + var snaps: Snaps = .{ .f = &target, .prompt = &prompt }; + var store = pc.Store.init(a, .{ .ptr = &snaps, .vtable = &.{ .bytes = Snaps.bytes, .save = Snaps.save, .restore = Snaps.restore, .drop = Snaps.drop } }, .{ .min_prompt = 0 }, 1000); + defer store.deinit(); + var host = api.LaneHost.init(a, std.testing.io, &core, .{ .lanes = 1 }); + host.cache = &store; + snaps.store = &store; + try host.start(); + defer host.stop(); + const first: api.Request = .{ .prompt = &prompt, .max_tokens = 2, .history_len = 8 }; + var first_box: Box = .{}; + try host.engine().submit(1, &first, .{ .ctx = &first_box, .event = Box.event }); + _ = try first_box.wait(); + target.prefill_hook = Snaps.hook; + target.prefill_hook_ctx = &snaps; + var second_box: Box = .{}; + try host.engine().submit(2, &first, .{ .ctx = &second_box, .event = Box.event }); + _ = try second_box.wait(); + try std.testing.expectEqual(@as(?u32, 0), snaps.at_second); // no longer pinned while the pass's later chunks run +} + +test "a pass's lookup is reported once its restore is settled: restored, refused, or none offered" { + var saved: u8 = 0; + const prompt = [_]u32{ 1, 2, 3 }; + var s = try lanes.Stream.init(a, .{ .id = "s", .prompt = &prompt, .max_new = 1, .reuse = .{ .saved = &saved, .at = 2 } }); + defer s.deinit(a); + try std.testing.expect(!fill.restoreSettled(&s)); // not yet restored: the entry stays borrowed + s.cached = 2; + try std.testing.expect(fill.restoreSettled(&s)); + s.cached = 0; + s.reuse_failed = true; + try std.testing.expect(fill.restoreSettled(&s)); +} diff --git a/zig/src/core/lane_host_strand_test.zig b/zig/src/core/lane_host_strand_test.zig index d635e0f9dc0..f05d52ccf4a 100644 --- a/zig/src/core/lane_host_strand_test.zig +++ b/zig/src/core/lane_host_strand_test.zig @@ -382,7 +382,7 @@ const Rig = struct { fn setStale(r: *Rig, on: bool) void { r.host.lock(); defer r.host.unlock(); - r.host.stale = on; + r.host.stale.store(on, .release); } fn setFailRound(r: *Rig, on: bool) void { diff --git a/zig/src/core/lane_host_test.zig b/zig/src/core/lane_host_test.zig index b941f8f07e8..46d3c8fb1bd 100644 --- a/zig/src/core/lane_host_test.zig +++ b/zig/src/core/lane_host_test.zig @@ -336,18 +336,18 @@ test "a learn request steps while the engine idles, its events in order; a host host.learner = .{ .ctx = &fake, .begin = FakeLearner.begin, .step = FakeLearner.step, .abort = FakeLearner.abort }; try std.testing.expectError(error.Unsupported, host.engine().learn(&audit, refused.sink())); host.learner.?.read_only_audit = true; - host.stale = true; + host.stale.store(true, .release); try std.testing.expectError(error.Busy, host.engine().learn(&audit, refused.sink())); - host.stale = false; + host.stale.store(false, .release); var stale_audit: LearnBox = .{}; defer stale_audit.tags.deinit(gpa); try host.engine().learn(&audit, stale_audit.sink()); - host.stale = true; + host.stale.store(true, .release); @import("lane_host_learn.zig").step(&host); stale_audit.wait(); try std.testing.expectEqualSlices(std.meta.Tag(api.LearnEvent), &.{.done}, stale_audit.tags.items); - try std.testing.expect(host.stale and fake.examples == 0); - host.stale = false; + try std.testing.expect(host.stale.load(.acquire) and fake.examples == 0); + host.stale.store(false, .release); try host.start(); defer host.stop(); var box: LearnBox = .{}; diff --git a/zig/src/core/lane_host_tests.zig b/zig/src/core/lane_host_tests.zig index df12be6a355..207204e8188 100644 --- a/zig/src/core/lane_host_tests.zig +++ b/zig/src/core/lane_host_tests.zig @@ -6,6 +6,9 @@ test { _ = @import("lane_halt_test.zig"); _ = @import("lane_host_end_test.zig"); _ = @import("lane_host_score_test.zig"); + _ = @import("lane_host_step_borrow_test.zig"); + _ = @import("lane_host_admit_borrow_test.zig"); + _ = @import("lane_host_lend_test.zig"); _ = @import("lane_review_test.zig"); _ = @import("lane_init_test.zig"); _ = @import("lane_failure_review_test.zig"); @@ -35,6 +38,7 @@ test { } test { + _ = @import("lane_host_live_chunk_test.zig"); _ = @import("lane_wait_reason_test.zig"); _ = @import("wait_reason.zig"); } diff --git a/zig/src/core/lane_host_warm_test.zig b/zig/src/core/lane_host_warm_test.zig index 89bf574ef2b..1effc5338c2 100644 --- a/zig/src/core/lane_host_warm_test.zig +++ b/zig/src/core/lane_host_warm_test.zig @@ -39,6 +39,24 @@ const Box = struct { } }; +const FakeSnaps = struct { + fn bytes(_: *anyopaque, at: u32) u64 { + return 64 + 4 * @as(u64, at); + } + fn save(ptr: *anyopaque, owner: ?*anyopaque, at: u32) anyerror!prompt_cache.Saved { + const f: *lanes.fake.Fake = @ptrCast(@alignCast(ptr)); + return f.save(@ptrCast(@alignCast(owner.?)), at); + } + fn restore(_: *anyopaque, _: ?*anyopaque, _: prompt_cache.Saved) anyerror!void { + return error.BackendRestores; + } + fn drop(ptr: *anyopaque, saved: prompt_cache.Saved) void { + const f: *lanes.fake.Fake = @ptrCast(@alignCast(ptr)); + f.drop(saved); + } +}; +const fake_snap_vtable: prompt_cache.Snapshots.VTable = .{ .bytes = FakeSnaps.bytes, .save = FakeSnaps.save, .restore = FakeSnaps.restore, .drop = FakeSnaps.drop }; + /// Chunks the fake ran for prompt-only streams. const WarmChunks = struct { n: std.atomic.Value(usize) = .init(0), @@ -190,23 +208,6 @@ test "a warm pass its cache keeps nothing of runs no chunk: no planned mark, and test "a warm_usable store keeps a warm pass's grid mark but not its end off the grid; without it, the end too" { const gpa = std.testing.allocator; - const pc = api.prompt_cache; - const Snaps = struct { - fn bytes(_: *anyopaque, at: u32) u64 { - return 64 + 4 * @as(u64, at); - } - fn save(ptr: *anyopaque, owner: ?*anyopaque, at: u32) anyerror!pc.Saved { - const f: *lanes.fake.Fake = @ptrCast(@alignCast(ptr)); - return f.save(@ptrCast(@alignCast(owner.?)), at); - } - fn restore(_: *anyopaque, _: ?*anyopaque, _: pc.Saved) anyerror!void { - return error.BackendRestores; - } - fn drop(ptr: *anyopaque, saved: pc.Saved) void { - const f: *lanes.fake.Fake = @ptrCast(@alignCast(ptr)); - f.drop(saved); - } - }; for ([_]bool{ true, false }) |usable| { var cfg = try lanes.Config.init(gpa, .{ .exact_width = 8, .gpu_tokens = true, .hidden_rows = true }, 8, 7); defer cfg.deinit(gpa); @@ -216,7 +217,7 @@ test "a warm_usable store keeps a warm pass's grid mark but not its end off the var core = lanes.Engine.init(gpa, &cfg, target.backend(), clock.clock()); defer core.deinit(); // dots.mocr's rules, scaled down: a grid of 4 and no request starts, so only multiples of 4 resume - var store = pc.Store.init(gpa, .{ .ptr = &target, .vtable = &.{ .bytes = Snaps.bytes, .save = Snaps.save, .restore = Snaps.restore, .drop = Snaps.drop } }, .{ .planned = true, .grid = 4, .warm = .on, .warm_usable = usable }, 400); + var store = prompt_cache.Store.init(gpa, .{ .ptr = &target, .vtable = &fake_snap_vtable }, .{ .planned = true, .grid = 4, .warm = .on, .warm_usable = usable }, 400); defer store.deinit(); var host = LaneHost.init(gpa, std.testing.io, &core, .{ .lanes = 2, .warm_turns = true }); host.cache = &store; @@ -241,23 +242,6 @@ test "a warm_usable store keeps a warm pass's grid mark but not its end off the test "a one-snapshot store keeps the warm pass's usable mark over an unusable end; the next request resumes the mark" { const gpa = std.testing.allocator; - const pc = api.prompt_cache; - const Snaps = struct { - fn bytes(_: *anyopaque, at: u32) u64 { - return 64 + 4 * @as(u64, at); - } - fn save(ptr: *anyopaque, owner: ?*anyopaque, at: u32) anyerror!pc.Saved { - const f: *lanes.fake.Fake = @ptrCast(@alignCast(ptr)); - return f.save(@ptrCast(@alignCast(owner.?)), at); - } - fn restore(_: *anyopaque, _: ?*anyopaque, _: pc.Saved) anyerror!void { - return error.BackendRestores; - } - fn drop(ptr: *anyopaque, saved: pc.Saved) void { - const f: *lanes.fake.Fake = @ptrCast(@alignCast(ptr)); - f.drop(saved); - } - }; for ([_]bool{ true, false }) |usable| { var cfg = try lanes.Config.init(gpa, .{ .exact_width = 8, .gpu_tokens = true, .hidden_rows = true }, 8, 7); defer cfg.deinit(gpa); @@ -270,7 +254,7 @@ test "a one-snapshot store keeps the warm pass's usable mark over an unusable en // The 128-row cut and 192-row warm end, scaled to a grid of 4: the end at 6 is off it. // A budget of one snapshot (88 B) fits either state, never both. - var store = pc.Store.init(gpa, .{ .ptr = &target, .vtable = &.{ .bytes = Snaps.bytes, .save = Snaps.save, .restore = Snaps.restore, .drop = Snaps.drop } }, .{ .planned = true, .grid = 4, .warm = .on, .warm_usable = usable }, 100); + var store = prompt_cache.Store.init(gpa, .{ .ptr = &target, .vtable = &fake_snap_vtable }, .{ .planned = true, .grid = 4, .warm = .on, .warm_usable = usable }, 100); defer store.deinit(); var host = LaneHost.init(gpa, std.testing.io, &core, .{ .lanes = 2, .warm_turns = true }); host.cache = &store; @@ -486,3 +470,71 @@ test "a warm pass gives way to a request still filling its prompt: no quiet wait try std.testing.expectEqual(@as(usize, @intFromBool(quiet == 0)), behind.chunks.load(.monotonic)); } } + +test "a re-rendered tool history restores its rewind row and matches a fresh reply" { + const gpa = std.testing.allocator; + var cfg = try lanes.Config.init(gpa, .{ .exact_width = 8, .gpu_tokens = true, .hidden_rows = true }, 8, 7); + defer cfg.deinit(gpa); + var target: lanes.fake.Fake = .{ .gpa = gpa }; + defer target.deinit(); + var clock: lanes.fake.FixedClock = .{}; + var core = lanes.Engine.init(gpa, &cfg, target.backend(), clock.clock()); + defer core.deinit(); + var store = prompt_cache.Store.init(gpa, .{ .ptr = &target, .vtable = &fake_snap_vtable }, .{ .chunk = 1, .min_prompt = 0, .warm = .waits }, 8192); + defer store.deinit(); + + const Reply = struct { + box: Box = .{}, + ids: [4]u32 = undefined, + cached: u32 = 0, + + fn event(ctx: *anyopaque, id: Id, e: *const Event) void { + const reply: *@This() = @ptrCast(@alignCast(ctx)); + switch (e.*) { + .prefilled => |count| reply.cached = count, + .tokens => |ids| @memcpy(reply.ids[reply.box.tokens..][0..ids.len], ids), + else => {}, + } + Box.event(&reply.box, id, e); + } + }; + + // The follow-up omits the assistant's reasoning, retaining the tool call and adding its result. + const predicted = [_]u32{ 1, 2, 3, 4, 70, 71, 80, 81, 9 }; + const rendered = [_]u32{ 1, 2, 3, 4, 80, 81, 9, 90, 91, 10 }; + const diff: u32 = @intCast(std.mem.indexOfDiff(u32, &predicted, &rendered).?); + const warm: Request = .{ + .prompt = &predicted, + .max_tokens = 0, + .background = true, + .history_len = predicted.len, + .rewind_len = diff, + .born = 2, + .decode_spans = &.{.{ 2, 8 }}, + }; + const next: Request = .{ .prompt = &rendered, .max_tokens = 4, .decode_spans = &.{.{ 2, 6 }} }; + var warm_reply: Reply = .{}; + var fresh_reply: Reply = .{}; + for ([_]?*prompt_cache.Store{ &store, null }, [_]*Reply{ &warm_reply, &fresh_reply }) |cache, reply| { + var host = LaneHost.init(gpa, std.testing.io, &core, .{ .lanes = 1 }); + host.decoded_rows = true; + host.cache = cache; + host.advertiseCache(cache); + try host.start(); + defer host.stop(); + if (cache != null) { + var box: Box = .{}; + try host.engine().submit(1, &warm, .{ .ctx = &box, .event = Box.event }); + try std.testing.expectEqual(Reason.length, box.wait()); + const continued = predicted ++ [_]u32{90}; + const kept = store.find(&continued, &.{}, warm.decode_spans) orelse return error.WarmEndMissing; + try std.testing.expectEqual(@as(u32, predicted.len), kept.at); + } + try host.engine().submit(2, &next, .{ .ctx = reply, .event = Reply.event }); + try std.testing.expectEqual(Reason.length, reply.box.wait()); + try std.testing.expectEqual(reply.ids.len, reply.box.tokens); + } + try std.testing.expectEqual(diff, warm_reply.cached); + try std.testing.expectEqual(@as(u32, 0), fresh_reply.cached); + try std.testing.expectEqualSlices(u32, &fresh_reply.ids, &warm_reply.ids); +} diff --git a/zig/src/core/lane_job.zig b/zig/src/core/lane_job.zig index 29f43a9dd5a..c394a98a792 100644 --- a/zig/src/core/lane_job.zig +++ b/zig/src/core/lane_job.zig @@ -33,6 +33,7 @@ pub const Job = struct { load: @import("lane_host_load.zig").Pass = .{}, // this attempt's prompt pass in the load ledger prefilled: ?i96 = null, entry: ?*pc.Entry = null, // the kept state the backend restores, until its prompt pass reports + lent: ?u64 = null, // a filling job's kept state (its serial), given back until its first call borrows it again cache_promise: @import("prompt_cache_reserve.zig").Room = .{}, // net room for this pass, until kept or ended marks: []const u32 = &.{}, // where the pass keeps states (gpa-owned) frame: u32 = 0, // exact family frame, before its compact cache-word hash @@ -87,4 +88,32 @@ pub const Job = struct { const ok = !job.stream.reuse_failed and job.stream.cached == e.at; if (job.stream.reuse_failed or ok) store.resumedWithReason(e, job.cacheKey(), if (ok) null else job.stream.reuse_error orelse error.RestoreRejected) else store.release(e); } + + /// Into the fill queue: its kept state goes back to the store until its first call, so none is pinned meanwhile. + pub fn lending(job: *Job) *Job { + const e = job.entry orelse return job; + const store = job.host.cache orelse return job; + if (e.serial == 0) return job; // not the index's (it numbers every entry it adds): the borrow stays + job.lent = e.serial; + job.entry = null; + store.release(e); + return job; + } + + /// Its first call: the kept state borrowed again; evicted while it waited, the pass fills from the start (exact). + pub fn reborrow(job: *Job) void { + const serial = job.lent orelse return; + job.lent = null; + const store = job.host.cache orelse return; + if (store.reborrow(serial)) |e| { + job.entry = e; + return; + } + @import("lane_stream.zig").lookAgain(job.host, job); // gone since: marks, promise and fill as a fresh admission's + } }; + +/// Whether a stream's kept state is restored or refused (or none was offered): its lookup can be reported. +pub fn restoreSettled(s: *const lanes.Stream) bool { + return s.reuse.saved == null or s.reuse_failed or s.cached > 0; +} diff --git a/zig/src/core/lane_projection.zig b/zig/src/core/lane_projection.zig index b43bf48e4a5..df35e60ce34 100644 --- a/zig/src/core/lane_projection.zig +++ b/zig/src/core/lane_projection.zig @@ -8,7 +8,7 @@ pub const frags = @import("frags.zig"); pub const affine_mm = @import("affine_mm.zig"); pub const weight_layout = "u32[ceil(N/32)][K/group][32][group*bits/32], low-bit-first codes, columns past N zero"; -pub const reg_layout = "u32[N/32][K/64][2][32 lanes][4] 4-bit codes, regBlock order"; +pub const reg_layout = "u32[N/32][K/64][(bits==4?256:bits==5?320:bits==6?384:512)] reg_layout order"; pub const metadata_layout = "bf16[K/group][N][scale,bias]"; pub const Output = enum { bf16, f32 }; @@ -35,7 +35,7 @@ pub const Layout = struct { /// Prepared sums reuse owned scratch; callers serialize all encodes using this projection until GPU completion. precompute_sums: bool = false, cooperative: bool = false, - /// 4-bit g64 codes in reg_layout, unpacked into tensor-op registers; every word equals the cooperative kernel's. + /// 4-, 5-, 6-, or 8-bit g64 codes in reg_layout, unpacked into tensor-op registers. reg: bool = false, /// Row capacity for reg layouts and opted-in row blocks; cooperative and scalar layouts take 16. rows: usize = reg_rows, @@ -49,7 +49,9 @@ pub const Layout = struct { pub fn validate(l: Layout) !void { try l.format.validate(); if (l.cooperative and l.format.bits != 4) return error.UnsupportedCooperativeFormat; - if (l.reg and (l.cooperative or (l.format.bits != 4 and l.format.bits != 8) or l.format.group != 64 or !l.precompute_sums)) return error.UnsupportedRegFormat; + const b = l.format.bits; + const reg_bits = b == 4 or b == 5 or b == 6 or b == 8; + if (l.reg and (l.cooperative or !reg_bits or l.format.group != 64 or !l.precompute_sums)) return error.UnsupportedRegFormat; if ((l.cooperative or l.reg) and l.n % 32 != 0) return error.InvalidShape; if (l.y_stride) |s| if (s < l.n or s > std.math.maxInt(i32) / 16) return error.InvalidOutputStride; if (l.n == 0 or l.n % 16 != 0 or l.k == 0 or l.k % l.format.group != 0 or @@ -175,7 +177,65 @@ pub fn regBlock(tiled: *const [256]u32, out: *[256]u32) void { } } -pub const Order = struct { w: Ref, n: usize, k: usize }; +/// Split-plane (4+1) reg_layout for one 32x64 5-bit block: words 0..255 low nibbles, 256..319 high bits. +pub fn regBlock5(tiled: *const [320]u32, out: *[320]u32) void { + regSplitBlock(5, tiled, out); +} + +/// Split-plane (4+2) reg_layout for one 32x64 6-bit block: words 0..255 low nibbles, 256..383 high pairs. +pub fn regBlock6(tiled: *const [384]u32, out: *[384]u32) void { + regSplitBlock(6, tiled, out); +} + +fn regSplitBlock(comptime bits: u8, tiled: []const u32, out: []u32) void { + const hi_bits = bits - 4; + const row_words = 2 * bits; + for (0..256) |t| { + const lane = (t >> 2) & 31; + const col = regCoordCol(lane, 4 * (t >> 7) + (t & 3)); + var lo4: u32 = 0; + for (0..8) |j| lo4 |= (extractTileCode(tiled, row_words, col, regCoordK(lane, 4 * (t >> 7) + (t & 3), j), bits) & 15) << @intCast(4 * j); + out[t] = lo4; + } + const slots = 4 / hi_bits; + const mask = (@as(u32, 1) << hi_bits) - 1; + for (0..64 * hi_bits) |t| { + const hl = t >> hi_bits; + const p = t & ((1 << hi_bits) - 1); + var hi_w: u32 = 0; + for (0..slots) |s| { + const hw = slots * p + s; + const hcol = regCoordCol(hl, hw); + for (0..4) |j| { + const c0 = (extractTileCode(tiled, row_words, hcol, regCoordK(hl, hw, j), bits) >> 4) & mask; + const c1 = (extractTileCode(tiled, row_words, hcol, regCoordK(hl, hw, j + 4), bits) >> 4) & mask; + const sh: u5 = @intCast(s * 4 * hi_bits + j * hi_bits); + hi_w |= (c0 << sh) | (c1 << (@as(u5, 16) + sh)); + } + } + out[256 + t] = hi_w; + } +} + +fn regCoordCol(lane: usize, w: usize) usize { + return ((lane >> 1) & 3) + 4 * ((lane >> 4) & 1) + 8 * (w >> 1); +} + +fn regCoordK(lane: usize, w: usize, j: usize) usize { + const k0 = 4 * (lane & 1) + 8 * ((lane >> 3) & 1) + 32 * (w & 1); + return k0 + (j & 1) * 2 + ((j >> 1) & 1) * 16 + (j >> 2); +} + +fn extractTileCode(tiled: []const u32, row_words: usize, col: usize, k: usize, comptime bits: u8) u32 { + const bit = k * bits; + const idx = col * row_words + (bit >> 5); + const sh: u5 = @intCast(bit & 31); + var v = tiled[idx] >> sh; + if (@as(usize, sh) + bits > 32) v |= tiled[idx + 1] << @intCast(32 - @as(usize, sh)); + return v & ((@as(u32, 1) << @intCast(bits)) - 1); +} + +pub const Order = struct { w: Ref, n: usize, k: usize, bits: u8 = 4 }; /// Rewrites host-visible tile-order 8-bit g64 words in place into the 8-bit reg layout (the 4-bit reg order, bytes). pub fn regOrder8(words: []u32, n: usize, k: usize) !void { @@ -199,6 +259,8 @@ pub fn regOrder8(words: []u32, n: usize, k: usize) !void { /// The reg_layout rewrite on the GPU: one library and queue for any number of runs. pub const RegOrder = struct { pipe: mtl.Pipeline, + pipe5: mtl.Pipeline, + pipe6: mtl.Pipeline, queue: mtl.Queue, pub fn init(device: mtl.Device) !RegOrder { @@ -206,26 +268,41 @@ pub const RegOrder = struct { defer lib.deinit(); const pipe = try mtl.Pipeline.init(device, lib, "tf_lane_order", false); errdefer pipe.deinit(); - return .{ .pipe = pipe, .queue = try device.queue() }; + const pipe5 = try mtl.Pipeline.init(device, lib, "tf_lane_order_q5", false); + errdefer pipe5.deinit(); + const pipe6 = try mtl.Pipeline.init(device, lib, "tf_lane_order_q6", false); + errdefer pipe6.deinit(); + return .{ .pipe = pipe, .pipe5 = pipe5, .pipe6 = pipe6, .queue = try device.queue() }; } pub fn deinit(o: RegOrder) void { o.pipe.deinit(); + o.pipe5.deinit(); + o.pipe6.deinit(); o.queue.deinit(); } - /// Rewrites tile-order 4-bit g64 words in place into reg_layout and waits; once per weight, before any reg encode. + /// Rewrites tile-order 4-, 5-, or 6-bit g64 words in place into reg_layout and waits; once per weight. pub fn run(o: RegOrder, jobs: []const Order) !void { for (jobs) |j| { + if (j.bits != 4 and j.bits != 5 and j.bits != 6) return error.UnsupportedRegFormat; if (j.n == 0 or j.n % 32 != 0 or j.k == 0 or j.k % 64 != 0) return error.InvalidShape; - try checkRef(j.w, j.n * j.k / 2, 4); + try checkRef(j.w, j.n * j.k * j.bits / 8, 4); } const pool = mtl.objc.Pool.push(); defer pool.pop(); const cb = o.queue.commandBuffer(); const e = cb.compute(.concurrent); - e.setPipeline(o.pipe); + var active: u8 = 0; for (jobs) |j| { + if (j.bits != active) { + e.setPipeline(switch (j.bits) { + 5 => o.pipe5, + 6 => o.pipe6, + else => o.pipe, + }); + active = j.bits; + } e.setBuffer(j.w.buf, j.w.off, 0); e.dispatchGroups(mtl.Size.of(j.n / 32 * (j.k / 64), 1, 1), mtl.Size.of(256, 1, 1)); } @@ -503,7 +580,14 @@ test "reg order puts every code in the tensor op's right-input register for its var bad = Layout{ .n = 64, .k = 256, .format = .{ .bits = 4, .group = 64 }, .reg = true }; try std.testing.expectError(error.UnsupportedRegFormat, bad.validate()); bad.precompute_sums = true; - try bad.validate(); - bad.format.group = 128; + for ([_]u8{ 4, 5, 6, 8 }) |bits| { + bad.format.bits = bits; + try bad.validate(); + } + for ([_]u8{ 2, 3 }) |bits| { + bad.format.bits = bits; + try std.testing.expectError(error.UnsupportedRegFormat, bad.validate()); + } + bad.format = .{ .bits = 4, .group = 128 }; try std.testing.expectError(error.UnsupportedRegFormat, bad.validate()); } diff --git a/zig/src/core/lane_review_test.zig b/zig/src/core/lane_review_test.zig index a660b00eb32..7e968512667 100644 --- a/zig/src/core/lane_review_test.zig +++ b/zig/src/core/lane_review_test.zig @@ -138,7 +138,7 @@ test "halt transfers queued and admitted jobs when every subsequent allocation f try engine.submit(2, &request, .{ .ctx = &box, .event = Box.event }); try host.admitted.append(host.gpa, host.queued.pop().?); failing.fail_index = failing.alloc_index; - host.closing = true; + host.closing.store(true, .release); @import("lane_halt.zig").haltAll(&host, "drain deadline"); try std.testing.expectEqual(@as(usize, 2), box.finished); try std.testing.expectEqual(@as(usize, 0), host.queued.items.len + host.admitted.items.len); diff --git a/zig/src/core/lane_rounds.zig b/zig/src/core/lane_rounds.zig index 6a40762df2f..bc34801c774 100644 --- a/zig/src/core/lane_rounds.zig +++ b/zig/src/core/lane_rounds.zig @@ -71,7 +71,7 @@ fn round(h: *LaneHost, rd: Rounds) bool { defer refused.deinit(h.gpa); h.lock(); // a stale device takes no reply (`learn.refuse` ends the queued ones), as in the default loop - if (!h.stale and h.queued.items.len > 0 and h.admitted.items.len < h.info_.lanes and !pressure.holds(h) and !h.disk.holding()) { + if (!h.stale.load(.acquire) and h.queued.items.len > 0 and h.admitted.items.len < h.info_.lanes and !pressure.holds(h) and !h.disk.holding()) { rd.vtable.begin_admit(rd.ctx); var free = h.info_.lanes - h.admitted.items.len; var i: usize = 0; @@ -110,7 +110,7 @@ fn round(h: *LaneHost, rd: Rounds) bool { const behind: Rounds.Wait = rest orelse if (pressure.holds(h)) .memory_pressure else .engine_busy; for (h.queued.items[@min(i, h.queued.items.len)..]) |job| job.wait_reason = behind; } else { - const why: Rounds.Wait = if (h.stale) .engine_unavailable else if (pressure.holds(h)) .memory_pressure else .engine_busy; + const why: Rounds.Wait = if (h.stale.load(.acquire)) .engine_unavailable else if (pressure.holds(h)) .memory_pressure else .engine_busy; for (h.queued.items) |job| job.wait_reason = why; } h.unlock(); @@ -304,7 +304,7 @@ pub fn run(h: *LaneHost, rd: Rounds) void { @import("lane_host_score.zig").answer(h); learn.refuse(h); h.lock(); - if (h.closing) { + if (h.closing.load(.acquire)) { const left = h.queued.items.len + h.admitted.items.len; h.unlock(); if (h.lesson_open) { diff --git a/zig/src/core/lane_stream.zig b/zig/src/core/lane_stream.zig index fc2c58c9335..043ebe0250f 100644 --- a/zig/src/core/lane_stream.zig +++ b/zig/src/core/lane_stream.zig @@ -27,12 +27,7 @@ pub fn open(h: *LaneHost, job: *Job) bool { job.key[0] = 0x8000_0000 | @as(u32, @truncate(std.hash.Wyhash.hash(f, std.mem.asBytes(&job.key[0])) & 0x7fff_ffff)); } }; - if (h.cache) |store| if (!r.promptOnly() and r.prompt_logprobs == null and !r.untaught) if (@import("lane_cache_queue.zig").lookup(h, job)) |l| { - job.entry = l.entry; - job.kept0 = store.counts.kept; - job.marks = l.marks; - reuse = .{ .saved = if (l.entry) |e| e.saved else null, .at = if (l.entry) |e| e.at else 0, .marks = l.marks, .hook = .{ .ptr = job, .at = Job.kept, .interrupted = Job.interrupted } }; - } else |_| {}; + if (h.cache != null and !r.promptOnly() and r.prompt_logprobs == null and !r.untaught) reuse = kept(h, job); if (h.proposers) |ps| { job.custom = ps.make(ps.ctx, h.gpa, r.prompt, r.eos) catch return !h.drop(job, "the drafter could not start"); } else job.proposer = lanes.SuffixLookup.init(h.gpa, .{ .min_match = h.min_match }) catch return !h.drop(job, "the drafter could not start"); @@ -86,3 +81,26 @@ pub fn open(h: *LaneHost, job: *Job) bool { job.began = std.Io.Clock.awake.now(h.io).toNanoseconds(); return true; } + +/// The job's kept state looked up: its entry borrowed, its marks and promise planned from what it resumes. +fn kept(h: *LaneHost, job: *Job) lanes.stream.Reuse { + const store = h.cache.?; + const l = @import("lane_cache_queue.zig").lookup(h, job) catch return .{}; + job.entry = l.entry; + job.kept0 = store.counts.kept; + job.marks = l.marks; + return .{ .saved = if (l.entry) |e| e.saved else null, .at = if (l.entry) |e| e.at else 0, .marks = l.marks, .hook = .{ .ptr = job, .at = Job.kept, .interrupted = Job.interrupted } }; +} + +/// A lent state gone at the job's first call: looked up again as at admission, with its fill and load hint. +pub fn lookAgain(h: *LaneHost, job: *Job) void { + h.gpa.free(job.marks); + job.marks = &.{}; + job.cache_promise = .{}; + job.stream.reuse = kept(h, job); + job.stream.fill_at.store(job.stream.reuse.at, .monotonic); + h.lock(); + defer h.unlock(); + job.load.hint = job.stream.reuse.at; + job.load.sure = job.load.hint == 0; +} diff --git a/zig/src/core/lane_thread.zig b/zig/src/core/lane_thread.zig index 9e062776489..581d44cbf96 100644 --- a/zig/src/core/lane_thread.zig +++ b/zig/src/core/lane_thread.zig @@ -1,8 +1,9 @@ //! An engine thread that fails initialization closes admission and ends all queued work. pub fn start(h: anytype) bool { + @import("lane_host_status.zig").engineStart(h); // the engine thread's id, for its counted lock waits if (h.on_thread) |t| t.run(t.ctx) catch |e| { h.lock(); - h.closing = true; + h.closing.store(true, .release); h.halt_reason = @errorName(e); h.wake.broadcast(h.io); h.unlock(); diff --git a/zig/src/core/lane_wait_reason_test.zig b/zig/src/core/lane_wait_reason_test.zig index 26bb1c35954..65469a904f8 100644 --- a/zig/src/core/lane_wait_reason_test.zig +++ b/zig/src/core/lane_wait_reason_test.zig @@ -200,9 +200,9 @@ test "wait reason ledger: publishing the ledger reads stored reasons and never a try std.testing.expectEqual(@as(u32, 3), at(ledger.read().requests.?, .engine_busy)); // an admission attempt decides the reason; the publishes after it only read it rig.host.lock(); - rig.host.stale = true; + rig.host.stale.store(true, .release); try std.testing.expect(admit.pick(&rig.host) == null); - rig.host.stale = false; + rig.host.stale.store(false, .release); rig.host.unlock(); for (0..8) |_| { rig.host.lock(); diff --git a/zig/src/core/lanes/backend.zig b/zig/src/core/lanes/backend.zig index 45e8366ab1e..38b57f855cc 100644 --- a/zig/src/core/lanes/backend.zig +++ b/zig/src/core/lanes/backend.zig @@ -87,6 +87,8 @@ pub const Backend = struct { first_before_draft: bool = false, /// A single-slot target lets its asynchronous keep progress between host steps before drafting again. defer_lone_draft: bool = false, + /// Commit a fully accepted lone chain; Inkling 2 Mini needs this transaction commit. + keep_full_lone: bool = false, /// Every draw (first, queue and verify rows) takes `Stream.penalties` from the reply's tokens; wrappers copy it. penalties: bool = false, /// Prompt fill gives the same tokens at any chunk cut, so --decode-share may cap its chunk rows; wrappers copy it. diff --git a/zig/src/core/lanes/cost_context.zig b/zig/src/core/lanes/cost_context.zig new file mode 100644 index 00000000000..2809b1d4f45 --- /dev/null +++ b/zig/src/core/lanes/cost_context.zig @@ -0,0 +1,8 @@ +//! Leave room for a full calibration sweep before a tight scratch context needs another prefill. +const std = @import("std"); + +pub fn promptRows(capacity: usize, widest: usize, sweep: usize) usize { + std.debug.assert(capacity > widest); + const room = capacity - widest; + return @min(192, room -| @min(sweep, room - 1)); +} diff --git a/zig/src/core/lanes/cost_rule.zig b/zig/src/core/lanes/cost_rule.zig index af3b67f27f5..77c08e88c76 100644 --- a/zig/src/core/lanes/cost_rule.zig +++ b/zig/src/core/lanes/cost_rule.zig @@ -24,11 +24,16 @@ pub fn fastest(ctx: anytype, i: usize) !f64 { } /// Retime both entries around a dip up to twice, retaining their faster values. -pub fn smooth(ctx: anytype, ms: []f64) !void { +pub fn smoothSerial(ctx: anytype, ms: []f64) !void { + return smoothSerialSynced(ctx, ms, Local{}, true); +} + +/// Both ranks repair the leader's dips in serial order, regardless of their own clocks. +fn smoothSerialSynced(ctx: anytype, ms: []f64, agree: anytype, lead: bool) !void { for (0..2) |_| { var dipped = false; for (1..ms.len) |i| { - if (ms[i] >= ms[i - 1] * (1 - dip)) continue; + if (!try agree.decide(lead and !(ms[i] >= ms[i - 1] * (1 - dip)))) continue; ms[i - 1] = @min(ms[i - 1], try fastest(ctx, i - 1)); ms[i] = @min(ms[i], try fastest(ctx, i)); dipped = true; @@ -37,6 +42,104 @@ pub fn smooth(ctx: anytype, ms: []f64) !void { } } +/// One warm pass and seven interleaved measured passes; observers run once per width spread across the passes. +pub fn interleaveWidths(windows: anytype, observer: anytype, ms: []f64, keep: bool) !void { + for (0..ms.len) |i| _ = try windows.time(i); + if (!keep) @memset(ms, std.math.inf(f64)); + for (0..reps) |pass| { + for (0..ms.len) |slot| { + const i = if (pass % 2 == 0) ms.len - 1 - slot else slot; + const m = &ms[i]; + const measured = try windows.time(i); + if (measured > 0 and std.math.isFinite(measured)) m.* = @min(m.*, measured); + if (i % reps == pass) try observer.afterWidth(i); + } + } + for (ms) |m| if (!(m > 0) or !std.math.isFinite(m)) return error.InvalidWindowCost; +} + +pub const NoObserver = struct { + pub fn afterWidth(_: *@This(), _: usize) !void {} +}; + +pub fn measureWindows(windows: anytype, ms: []f64, keep: bool) !void { + var observer: NoObserver = .{}; + try interleaveWidths(windows, &observer, ms, keep); +} + +/// Time each width to completion, then repair dips serially; a stateful scratch timer keeps its original order. +pub fn serialWindows(windows: anytype, ms: []f64) !void { + return serialWindowsSynced(windows, ms, Local{}, true); +} + +/// Paired serial timing: both ranks complete each width and take only the leader's dip repairs. +pub fn serialWindowsSynced(windows: anytype, ms: []f64, agree: anytype, lead: bool) !void { + for (ms, 0..) |*m, i| m.* = try fastest(windows, i); + try smoothSerialSynced(windows, ms, agree, lead); +} + +/// Retime a high local outlier or both sides of a dip, never changing a real step to an interpolated value. +pub fn repairAt(ms: []const f64, i: usize) bool { + return repairGrid(ms, null, i); +} + +fn coordinate(widths: ?[]const u32, i: usize) f64 { + return @floatFromInt(if (widths) |w| w[i] else i + 1); +} + +pub fn repairGrid(ms: []const f64, widths: ?[]const u32, i: usize) bool { + const value = ms[i]; + if (!(value > 0) or !std.math.isFinite(value)) return true; + if (i > 0 and value < ms[i - 1] * (1 - dip)) return true; + if (i + 1 < ms.len and ms[i + 1] < value * (1 - dip)) return true; + if (ms.len < 3) return false; + const left = if (i == 0) 1 else if (i + 1 == ms.len) i - 2 else i - 1; + const right = if (i == 0) 2 else if (i + 1 == ms.len) i - 1 else i + 1; + const ratio = (coordinate(widths, i) - coordinate(widths, left)) / (coordinate(widths, right) - coordinate(widths, left)); + const predicted = ms[left] + (ms[right] - ms[left]) * ratio; + return predicted > 0 and value > predicted * (1 + dip); +} + +const Local = struct { + pub fn decide(_: @This(), mine: bool) !bool { + return mine; + } +}; + +/// At most one extra warm read per width: at most one eighth of the initial window timing calls. +pub fn smooth(ctx: anytype, ms: []f64) !void { + return smoothSynced(ctx, ms, Local{}, true); +} + +/// Both ranks retime the same entries; the leader alone selects them from its table. +pub fn smoothSynced(ctx: anytype, ms: []f64, agree: anytype, lead: bool) !void { + return smoothGrid(ctx, ms, null, agree, lead); +} + +pub fn smoothWidths(ctx: anytype, ms: []f64, widths: []const u32) !void { + std.debug.assert(ms.len == widths.len); + return smoothGrid(ctx, ms, widths, Local{}, true); +} + +fn smoothGrid(ctx: anytype, ms: []f64, widths: ?[]const u32, agree: anytype, lead: bool) !void { + var remaining = ms.len; + while (remaining > 0) { + remaining -= 1; + const i = remaining; + if (!try agree.decide(lead and repairGrid(ms, widths, i))) continue; + const measured = try ctx.time(i); + if (measured > 0 and std.math.isFinite(measured)) ms[i] = if (ms[i] > 0 and std.math.isFinite(ms[i])) @min(ms[i], measured) else measured; + } +} + +pub const context = @import("cost_context.zig"); + +pub const warm_prices = @import("metal_cost_heal.zig"); + +pub fn healWindows(timer: anytype, ms: []f64, widths: []const u32, cursor: *u64) !warm_prices.Stats { + return warm_prices.local(timer, ms, widths, cursor); +} + /// True when any entry is more than `drift` from the reference's, or the reference has another shape. pub fn drifted(ms: []const f64, reference: []const f64) bool { if (ms.len != reference.len) return true; @@ -105,7 +208,7 @@ pub fn measure(windows: anytype, heads: anytype, ms: []f64, head_ms: ?*f64, keep } }; var observer: Observer = .{ .heads = heads, .enabled = head_ms != null }; - try measureWidths(windows, &observer, ms, keep); + try interleaveWidths(windows, &observer, ms, keep); if (head_ms) |h| h.* = if (keep) @min(h.*, observer.best) else observer.best; } @@ -149,14 +252,14 @@ test "a dip times both entries again and keeps the faster values; a real dip sta var next = [_]usize{ 0, 0 }; const s: Script = .{ .runs = &.{ &first, &second }, .next = &next }; var ms = [_]f64{ 6.5, 6 }; - try smooth(s, &ms); + try smoothSerial(s, &ms); try std.testing.expectEqualSlices(f64, &.{ 4, 6 }, &ms); const slow: [16]f64 = @splat(6.5); const fast: [16]f64 = @splat(6); var real_next = [_]usize{ 0, 0 }; const real: Script = .{ .runs = &.{ &slow, &fast }, .next = &real_next }; var kept = [_]f64{ 6.5, 6 }; - try smooth(real, &kept); + try smoothSerial(real, &kept); try std.testing.expectEqualSlices(f64, &.{ 6.5, 6 }, &kept); try std.testing.expectEqual(@as(usize, 16), real_next[0]); } @@ -242,5 +345,7 @@ test "a probe refuses non-finite and non-positive head references" { test { _ = @import("cost_rule_test.zig"); + _ = @import("metal_cost_rule_test.zig"); + _ = @import("metal_cost_review_test.zig"); _ = @import("cuda_cost_rule_test.zig"); } diff --git a/zig/src/core/lanes/cost_rule_test.zig b/zig/src/core/lanes/cost_rule_test.zig index db12b53a32a..9b34caa931a 100644 --- a/zig/src/core/lanes/cost_rule_test.zig +++ b/zig/src/core/lanes/cost_rule_test.zig @@ -47,10 +47,14 @@ test "the head is sampled once between widths and keeps the pass minimum" { try std.testing.expectEqual(@as(f64, 0.34), head); try std.testing.expectEqual(@as(usize, 3), s.head_calls); try std.testing.expectEqual(@as(usize, 24), s.window_calls); - for (0..3) |width| { - const start = width * (rule.reps + 2); - for (s.events[start .. start + rule.reps + 1]) |event| try std.testing.expectEqual(@as(u8, @intCast(width)), event); - try std.testing.expectEqual(@as(u8, 255), s.events[start + rule.reps + 1]); + var window: usize = 0; + for (s.events[0..s.count]) |event| { + if (event == 255) continue; + const pass = window / 3; + const slot = window % 3; + const index = if (pass > 0 and pass % 2 == 1) 2 - slot else slot; + try std.testing.expectEqual(@as(u8, @intCast(index)), event); + window += 1; } } diff --git a/zig/src/core/lanes/cuda_cost_rule_test.zig b/zig/src/core/lanes/cuda_cost_rule_test.zig index dedd3308d69..a5df47ea6af 100644 --- a/zig/src/core/lanes/cuda_cost_rule_test.zig +++ b/zig/src/core/lanes/cuda_cost_rule_test.zig @@ -88,7 +88,7 @@ fn shared(s: *Script, raw: *Raw, keep: bool) !void { var chains: rule.ChainLevel(Script.Chains) = .{ .timer = .{ .s = s } }; try rule.measureWidths(windows, &chains, raw.verify[1..], keep); if (!keep) raw.verify[0] = 0; - try rule.smooth(windows, raw.verify[1..]); + try rule.smoothSerial(windows, raw.verify[1..]); const level = chains.level(); raw.level = if (keep) @min(raw.level, level) else level; } diff --git a/zig/src/core/lanes/depth.zig b/zig/src/core/lanes/depth.zig index 221f6be568c..9048dc58e5d 100644 --- a/zig/src/core/lanes/depth.zig +++ b/zig/src/core/lanes/depth.zig @@ -136,19 +136,24 @@ pub const Rule = struct { try table.put(r.gpa, drafts, if (before) |b| b + r.k.cost_rate * (ms - b) else ms); } + fn draftHeadMs(r: *const Rule, drafts: i64) f64 { + const steps: f64 = if (r.k.fixed_draft_block) @floatFromInt(if (drafts > 0) r.most_drafts else 0) else @floatFromInt(drafts); + return r.mtp_step_ms * steps; + } + /// Measured round time when there is one, else the load-time forward cost plus head steps. pub fn roundCost(r: *Rule, drafts: i64, who: ?Who) !?f64 { const table = try r.costs(who); if (table.get(drafts)) |v| return v; const forward = r.family_costs.get(drafts + 1) orelse return null; - var modeled = forward + r.mtp_step_ms * @as(f64, @floatFromInt(drafts)); + var modeled = forward + r.draftHeadMs(drafts); if (r.plain_guard) { // untimed: its model plus the least time a row of a timed round took beyond its model var least: ?f64 = null; for (table.slots, 0..) |slot, d| { const ms = slot orelse continue; const fc = r.family_costs.get(@intCast(d + 1)) orelse continue; - const beyond = (ms - fc - r.mtp_step_ms * @as(f64, @floatFromInt(d))) / @as(f64, @floatFromInt(d + 1)); + const beyond = (ms - fc - r.draftHeadMs(@intCast(d))) / @as(f64, @floatFromInt(d + 1)); least = if (least) |l| (if (beyond < l) beyond else l) else beyond; } const floor = least orelse 0.0; diff --git a/zig/src/core/lanes/depth_test.zig b/zig/src/core/lanes/depth_test.zig index 9fc1327fb38..c0fc5c4cccb 100644 --- a/zig/src/core/lanes/depth_test.zig +++ b/zig/src/core/lanes/depth_test.zig @@ -168,3 +168,31 @@ test "a granted hold stays only while its stream's expected drafts pay for the v try rule.payHolds(&whos, false, &out); try std.testing.expectEqualSlices(i64, &.{ 0, 0, 2, 0 }, &out); // a probe after a grant of none keeps its hold } + +test "fixed_draft_block prices full block head cost in lone roundCost" { + const gpa = std.testing.allocator; + var family: Table = .{}; + defer family.deinit(gpa); + try family.put(gpa, 1, 20.0); + try family.put(gpa, 2, 22.0); + try family.put(gpa, 8, 30.0); + var shared: Table = .{}; + defer shared.deinit(gpa); + var rule: Rule = .{ + .gpa = gpa, + .k = .{ .fixed_draft_block = true }, + .prior = &.{0.8}, + .most_drafts = 7, + .family_costs = &family, + .shared_costs = &shared, + .mtp_step_ms = 1.0, + .plain_guard = true, + .node_probabilities = false, + .batch_rows = 8, + }; + defer rule.deinit(); + try std.testing.expectApproxEqAbs(@as(f64, 20.0), (try rule.roundCost(0, null)).?, 1e-9); + try std.testing.expectApproxEqAbs(@as(f64, 29.0), (try rule.roundCost(1, null)).?, 1e-9); + try rule.observeCost(1, 29.0, false, null); + try std.testing.expectApproxEqAbs(@as(f64, 37.0), (try rule.roundCost(7, null)).?, 1e-9); +} diff --git a/zig/src/core/lanes/drafted.zig b/zig/src/core/lanes/drafted.zig index 1add37d6b45..a5f98256654 100644 --- a/zig/src/core/lanes/drafted.zig +++ b/zig/src/core/lanes/drafted.zig @@ -72,7 +72,7 @@ pub const Drafted = struct { }; pub fn backend(x: *Drafted) be.Backend { const planned = if (x.drafter.proposal_head) |service| service.mode != .legacy and x.drafter.vtable.hold_planned != null and x.drafter.vtable.clear_proposals != null else false; - return .{ .proposal_head = x.drafter.proposal_head, .ptr = x, .round_observer = x.target.round_observer, .first_before_draft = x.target.first_before_draft, .penalties = x.target.penalties, .chunk_invariant = x.target.chunk_invariant, .warm_images = x.target.warm_images, .vtable = vtableFor(planned, x.target.vtable.prefill_step != null and x.target.vtable.reports_fill and x.target.vtable.features != null, x.target.vtable.cancel_prefill != null, x.first_rows) }; + return .{ .proposal_head = x.drafter.proposal_head, .ptr = x, .round_observer = x.target.round_observer, .first_before_draft = x.target.first_before_draft, .keep_full_lone = x.target.keep_full_lone, .penalties = x.target.penalties, .chunk_invariant = x.target.chunk_invariant, .warm_images = x.target.warm_images, .vtable = vtableFor(planned, x.target.vtable.prefill_step != null and x.target.vtable.reports_fill and x.target.vtable.features != null, x.target.vtable.cancel_prefill != null, x.first_rows) }; } const cancellable: [4]be.Backend.VTable = blk: { diff --git a/zig/src/core/lanes/drafted_role_test.zig b/zig/src/core/lanes/drafted_role_test.zig index 7c28f3ddab6..ff096e26f30 100644 --- a/zig/src/core/lanes/drafted_role_test.zig +++ b/zig/src/core/lanes/drafted_role_test.zig @@ -38,9 +38,11 @@ test "the drafter wrapper sees the committed callback before its first hold" { defer head.deinit(); var backend = target.backend(); backend.first_before_draft = true; + backend.keep_full_lone = true; var wrapped = try Drafted.init(gpa, backend, head.drafter()); defer wrapped.deinit(); try std.testing.expect(wrapped.backend().first_before_draft); + try std.testing.expect(wrapped.backend().keep_full_lone); var cfg = try Config.init(gpa, wrapped.facts(base()), 16, 15); defer cfg.deinit(gpa); var clock: fake.FixedClock = .{}; diff --git a/zig/src/core/lanes/engine.zig b/zig/src/core/lanes/engine.zig index ffa1e29f0d2..cdd10f432d1 100644 --- a/zig/src/core/lanes/engine.zig +++ b/zig/src/core/lanes/engine.zig @@ -217,7 +217,7 @@ pub const Engine = struct { const tokens = try win.tokens(e, windows[0], out[0]); const parents = try win.rowParents(e, windows[0]); const o = try e.conclude(s, plan, out[0].sampled, out[0].rows, tokens, parents, windows[0].positions); - if (o.path.len < rows or plan.parents != null) try e.backend.keep(&windows, &.{o.path}); + if (o.path.len < rows or plan.parents != null or e.backend.keep_full_lone) try e.backend.keep(&windows, &.{o.path}); const held_levels = s.held_levels; const timed_copy = e.cfg.family_mtp and s.drafts and @import("lone_copy.zig").records(e, s, plan.kind); const verified: ?f64 = if (timed_copy) e.clock.elapsedMs(.cost) else null; diff --git a/zig/src/core/lanes/fake.zig b/zig/src/core/lanes/fake.zig index 4f68632ce70..aa74f50fa01 100644 --- a/zig/src/core/lanes/fake.zig +++ b/zig/src/core/lanes/fake.zig @@ -92,6 +92,8 @@ pub const Fake = struct { image_rows: usize = 0, // image rows fed (`image_words`): the rows a tower had to make gpu_charge: ?f64 = null, // each verify and step charges its streams this many GPU seconds, as a timed backend does head_accepts: ?usize = null, // head drafts a round right before one wrong (null: one in five wrong) + keep_calls: usize = 0, // backend keep calls, including fully accepted lone windows when opted in + full_keeps: usize = 0, // of those, windows kept whole (every row accepted): main never makes these pub fn deinit(x: *Fake) void { var it = x.lanes.valueIterator(); @@ -479,7 +481,9 @@ pub const Fake = struct { fn keep(ptr: *anyopaque, windows: []const be.Window, paths: []const []const u32) anyerror!void { const x = self(ptr); + x.keep_calls += 1; for (windows, paths) |w, path| { + if (path.len == w.rows()) x.full_keeps += 1; const l = x.lane(w.stream); l.history.shrinkRetainingCapacity(l.base); for (path) |r| try l.history.append(x.gpa, l.rows.items[r]); diff --git a/zig/src/core/lanes/gpu_launch_test.zig b/zig/src/core/lanes/gpu_launch_test.zig new file mode 100644 index 00000000000..3bf88a801d0 --- /dev/null +++ b/zig/src/core/lanes/gpu_launch_test.zig @@ -0,0 +1,68 @@ +//! A Metal sampler launch of several rows binds each row's settings as that row's own one-row launch did. +const std = @import("std"); +const rule = @import("gpu_rule.zig"); +const Sampling = @import("sampling.zig").Sampling; +const t = std.testing; + +const settings = [_]Sampling{ + .{ .seed = 1234, .temperature = 1.0, .top_k = 20, .top_p = 0.95 }, + .{ .seed = 7, .temperature = 0.7, .top_k = 1 }, + .{ .seed = 9, .temperature = 1.3, .top_k = 1024, .top_p = 0.5 }, + .{ .seed = 11, .temperature = 1.0, .top_k = 1025, .top_p = 1.0 }, + .{ .seed = 13, .temperature = 1.0, .top_k = 0, .top_p = 0.95 }, + .{ .seed = 23, .temperature = 0.9, .top_k = 40, .top_p = 0.9, .min_p = 0.05 }, + .{ .seed = 25, .temperature = 1e-7, .top_k = 20, .top_p = 0.95 }, + .{ .seed = 27, .temperature = 100.0, .top_k = 0, .top_p = 0.8, .min_p = 0.5 }, +}; + +/// Main's one-row binding in Flint's pick: row 0 of arrays padded to 8 rows, as Nemotron's launches pad them. +const OneRow = struct { seeds: [16]u32, positions: [8]u32, cfgs: [32]f32, caps: [8]u32 }; + +fn mainOneRow(s: Sampling, position: u64) OneRow { + const r = rule.rule(s); + var o: OneRow = .{ .seeds = @splat(0), .positions = @splat(0), .cfgs = @splat(0), .caps = @splat(0) }; + o.seeds[0..2].* = r.seedHalves(); + o.positions[0] = @intCast(position); + o.cfgs[0..4].* = r.cfg(); + o.caps[0] = r.top_k; + return o; +} + +test "sampler launch: a one-row launch binds exactly main's one-row bytes, in Flint's 32-row launch type" { + for (settings, 0..) |s, i| { + const position: u64 = 4096 + 17 * i; + const want = mainOneRow(s, position); + var l: rule.Launch(32) = .{}; + l.put(s, position); + const n = l.padded(); + try t.expectEqual(@as(usize, 8), n); + try t.expectEqualSlices(u8, std.mem.sliceAsBytes(&want.seeds), std.mem.sliceAsBytes(l.seeds[0 .. 2 * n])); + try t.expectEqualSlices(u8, std.mem.sliceAsBytes(&want.positions), std.mem.sliceAsBytes(l.positions[0..n])); + try t.expectEqualSlices(u8, std.mem.sliceAsBytes(&want.cfgs), std.mem.sliceAsBytes(l.cfgs[0 .. 4 * n])); + try t.expectEqualSlices(u8, std.mem.sliceAsBytes(&want.caps), std.mem.sliceAsBytes(l.caps[0..n])); + } +} + +test "sampler launch: many rows bind each row's settings at its own index, zeros past the last" { + var prng = std.Random.DefaultPrng.init(32); + const r = prng.random(); + for ([_]usize{ 1, 2, 7, 8, 9, 31, 32 }) |rows| { + var many: rule.Launch(32) = .{}; + var picks: [32]struct { s: Sampling, position: u64 } = undefined; + for (picks[0..rows], 0..) |*p, i| { + p.* = .{ .s = settings[r.uintLessThan(usize, settings.len)], .position = 4096 + 3 * i }; + p.s.seed = r.int(u64); + many.put(p.s, p.position); + } + try t.expectEqual(@max(rows, 8), many.padded()); + for (picks[0..rows], 0..) |p, i| { + const one = mainOneRow(p.s, p.position); + try t.expectEqualSlices(u32, one.seeds[0..2], many.seeds[2 * i ..][0..2]); + try t.expectEqual(one.positions[0], many.positions[i]); + try t.expectEqualSlices(u8, std.mem.sliceAsBytes(one.cfgs[0..4]), std.mem.sliceAsBytes(many.cfgs[4 * i ..][0..4])); + try t.expectEqual(one.caps[0], many.caps[i]); + } + for (rows..32) |i| try t.expectEqual(@as(u32, 0), many.positions[i] | many.caps[i] | many.seeds[2 * i] | many.seeds[2 * i + 1]); + for (many.cfgs[4 * rows ..]) |f| try t.expectEqual(@as(u32, 0), @as(u32, @bitCast(f))); + } +} diff --git a/zig/src/core/lanes/gpu_rule.zig b/zig/src/core/lanes/gpu_rule.zig index 71d634bd0b2..ac556643727 100644 --- a/zig/src/core/lanes/gpu_rule.zig +++ b/zig/src/core/lanes/gpu_rule.zig @@ -146,6 +146,33 @@ pub fn lanesSum(lanes: *const [1024]f32) f32 { return z; } +/// The Metal samplers' per-row settings for up to `max` rows, as one launch binds them (rows past the last zero). +pub fn Launch(comptime max: usize) type { + comptime std.debug.assert(max >= 8); + return struct { + seeds: [2 * max]u32 = @splat(0), + positions: [max]u32 = @splat(0), + cfgs: [4 * max]f32 = @splat(0), + caps: [max]u32 = @splat(0), + rows: usize = 0, + + /// The next row: its seed halves, position, cfg row and top_k. + pub fn put(l: *@This(), s: Sampling, position: u64) void { + const r = rule(s); + l.seeds[2 * l.rows ..][0..2].* = r.seedHalves(); + l.positions[l.rows] = @intCast(position); + l.cfgs[4 * l.rows ..][0..4].* = r.cfg(); + l.caps[l.rows] = r.top_k; + l.rows += 1; + } + + /// The rows a launch binds: at least 8, as every Metal sampler launch pads them. + pub fn padded(l: *const @This()) usize { + return @max(l.rows, 8); + } + }; +} + test "the rule once: its values, and the Metal cfg row and seed halves it packs" { const s: Sampling = .{ .seed = 1 << 63 | 5, .temperature = 0.5, .top_k = 7, .top_p = 0.9, .min_p = 0.05 }; const r = rule(s); diff --git a/zig/src/core/lanes/lanes.zig b/zig/src/core/lanes/lanes.zig index 792f65732cd..e32b7299864 100644 --- a/zig/src/core/lanes/lanes.zig +++ b/zig/src/core/lanes/lanes.zig @@ -81,6 +81,7 @@ test { _ = @import("open_trace_test.zig"); _ = @import("recorder_test.zig"); _ = @import("gpu_full_test.zig"); + _ = @import("gpu_launch_test.zig"); _ = @import("drafted_test.zig"); _ = @import("drafter_depth_sweep_test.zig"); _ = @import("drafted_chances_test.zig"); diff --git a/zig/src/core/lanes/metal_cost_heal.zig b/zig/src/core/lanes/metal_cost_heal.zig new file mode 100644 index 00000000000..fc3f0d8a261 --- /dev/null +++ b/zig/src/core/lanes/metal_cost_heal.zig @@ -0,0 +1,169 @@ +//! Plan warm probes before scratch setup; retain only measured, consistent lower prices. +const std = @import("std"); +pub const budget_ms: f64 = 200; +const cooldown: u64 = 1 << 63; +pub const Stats = struct { reads: u32 = 0, ms: f64 = 0, lowered: u32 = 0 }; +pub const Turn = struct { + value: u64 = 0, + attempted: bool = false, + + pub fn preferredShared(turn: Turn) bool { + return turn.value % 2 == 1; + } + + pub fn order(turn: Turn) [2]bool { + const shared = turn.preferredShared(); + return .{ shared, !shared }; + } + + pub fn next(turn: Turn) u64 { + return turn.value +% 1; + } +}; + +pub const Local = struct { + pub fn decide(_: @This(), mine: bool) !bool { + return mine; + } +}; + +pub fn valid(ms: []const f64, widths: []const u32) bool { + if (ms.len == 0 or ms.len != widths.len) return false; + for (ms, widths, 0..) |m, w, i| { + if (!(m > 0) or !std.math.isFinite(m) or w == 0) return false; + if (i > 0 and w <= widths[i - 1]) return false; + } + return true; +} + +pub const Plan = struct { + at: [3]usize = undefined, + n: usize = 0, + fn add(p: *Plan, i: usize) void { + for (p.at[0..p.n]) |old| if (old == i) return; + if (p.n < p.at.len) { + p.at[p.n] = i; + p.n += 1; + } + } + pub fn widest(p: Plan, widths: []const u32) u32 { + var rows: u32 = 0; + for (p.at[0..p.n]) |i| rows = @max(rows, widths[i]); + return rows; + } +}; + +/// Empty means no scratch setup; the rotating entry comes first, followed by the narrower and wider edges. +pub fn select(ms: []const f64, widths: []const u32, cursor: u64) Plan { + var p: Plan = .{}; + if (!valid(ms, widths) or ms[ms.len - 1] >= budget_ms) return p; + const raw = cursor & ~cooldown; + const position = raw % widths.len; + var rotating: usize = @intCast(position); + while (ms[rotating] >= budget_ms) rotating = (rotating + 1) % widths.len; + p.add(rotating); + const tile = 16 * (1 + (position % 3 + (raw / widths.len) % 3) % 3); + var below: usize = 0; + var above = widths.len - 1; + for (widths, 0..) |w, i| { + if (w <= tile) below = i; + if (w > tile) { + above = i; + break; + } + } + p.add(below); + p.add(above); + var fits: Plan = .{}; + var estimate: f64 = 0; + for (p.at[0..p.n]) |i| if (estimate + ms[i] <= budget_ms) { + fits.add(i); + estimate += ms[i]; + }; + return fits; +} + +/// Skip one warm turn after setup leaves too little time for the rotating read. +pub fn admit(ms: []const f64, widths: []const u32, cursor: *u64) bool { + if (cursor.* & cooldown != 0) { + cursor.* &= ~cooldown; + return false; + } + return select(ms, widths, cursor.*).n != 0; +} + +fn kind(comptime T: type) type { + return switch (@typeInfo(T)) { + .pointer => |p| p.child, + else => T, + }; +} + +fn charge(timer: anytype, stats: *Stats, measured: f64) void { + if (comptime @hasDecl(kind(@TypeOf(timer)), "elapsedMs")) { + stats.ms = timer.elapsedMs(); + if (!(stats.ms >= 0) or !std.math.isFinite(stats.ms)) stats.ms = budget_ms; + } else stats.ms += if (measured > 0 and std.math.isFinite(measured)) measured else budget_ms; +} + +/// Three bit-encoded indices replace one collective per table entry per slot. +fn broadcast(p: Plan, len: usize, agree: anytype, lead: bool) !Plan { + var selected: Plan = .{}; + for (0..3) |slot| { + const mine = if (lead and slot < p.n) p.at[slot] + 1 else 0; + var value: usize = 0; + var bit: usize = 1; + while (bit <= len) : (bit *= 2) { + if (try agree.decide(lead and mine & bit != 0)) value |= bit; + } + if (value > 0 and value <= len) selected.add(value - 1); + } + return selected; +} + +/// Setup and each complete read count against elapsed wall time; one unexpected slow operation can overrun it. +pub fn prepared(timer: anytype, ms: []f64, widths: []const u32, cursor: *u64, floor: f64, agree: anytype, lead: bool) !Stats { + var stats: Stats = .{}; + if (comptime @hasDecl(kind(@TypeOf(timer)), "start")) timer.start(); + const mine = if (lead and admit(ms, widths, cursor)) select(ms, widths, cursor.*) else Plan{}; + if (!try agree.decide(lead and mine.n > 0)) return stats; + const selected = try broadcast(mine, ms.len, agree, lead); + if (comptime @hasDecl(kind(@TypeOf(timer)), "prepare")) try timer.prepare(selected, widths); + if (comptime @hasDecl(kind(@TypeOf(timer)), "elapsedMs")) charge(timer, &stats, 0); + for (selected.at[0..selected.n]) |i| { + if (comptime @hasDecl(kind(@TypeOf(timer)), "elapsedMs")) charge(timer, &stats, 0); + if (!try agree.decide(lead and stats.ms + ms[i] <= budget_ms)) break; + const measured = try timer.time(i); + stats.reads += 1; + charge(timer, &stats, measured); + if (!lead or !(measured > 0) or !std.math.isFinite(measured) or measured >= ms[i]) continue; + var predecessor = floor; + for (ms[0..i]) |m| predecessor = @max(predecessor, m); + if (measured < predecessor) continue; + ms[i] = measured; + stats.lowered += 1; + } + if (lead) { + cursor.* = (cursor.* +% 1) & ~cooldown; + if (stats.reads == 0) cursor.* |= cooldown; + } + return stats; +} + +pub fn synced(timer: anytype, ms: []f64, widths: []const u32, cursor: *u64, agree: anytype, lead: bool) !Stats { + return prepared(timer, ms, widths, cursor, 0, agree, lead); +} + +pub fn local(timer: anytype, ms: []f64, widths: []const u32, cursor: *u64) !Stats { + return synced(timer, ms, widths, cursor, Local{}, true); +} + +test "Metal window prices: cooldown leaves the rotating entry and tile edges unchanged" { + const ms: [7]f64 = @splat(10); + const widths = [_]u32{ 1, 16, 17, 32, 33, 48, 49 }; + for (0..3 * widths.len) |raw| { + const plain = select(&ms, &widths, raw); + const flagged = select(&ms, &widths, @as(u64, raw) | cooldown); + try std.testing.expectEqualSlices(usize, plain.at[0..plain.n], flagged.at[0..flagged.n]); + } +} diff --git a/zig/src/core/lanes/metal_cost_review_test.zig b/zig/src/core/lanes/metal_cost_review_test.zig new file mode 100644 index 00000000000..8661cfc0bc1 --- /dev/null +++ b/zig/src/core/lanes/metal_cost_review_test.zig @@ -0,0 +1,250 @@ +//! Request budgets and measured-only table consistency over recording warm-load clocks. +const std = @import("std"); +const rule = @import("cost_rule.zig"); +const warm = rule.warm_prices; +const t = std.testing; +const Timer = struct { + setups: usize = 0, + setup_ms: f64 = 0, + wall: f64 = 0, + value: f64 = 10, + seen: [8]usize = undefined, + n: usize = 0, + pub fn prepare(s: *@This(), _: anytype, _: []const u32) !void { + s.setups += 1; + s.wall += s.setup_ms; + } + pub fn elapsedMs(s: *@This()) f64 { + return s.wall; + } + pub fn time(s: *@This(), i: usize) !f64 { + s.seen[s.n] = i; + s.n += 1; + s.wall += s.value; + return s.value; + } +}; +fn prepared(timer: *Timer, ms: []f64, widths: []const u32, cursor: *u64) !warm.Stats { + if (comptime @hasDecl(warm, "prepared")) return warm.prepared(timer, ms, widths, cursor, 0, warm.Local{}, true); + // The incoming consumers set up before invoking the budgeted policy. + try timer.prepare({}, widths); + return rule.healWindows(timer, ms, widths, cursor); +} + +test "Metal review: no-fit warm load does no setup or reads and leaves its cursor" { + var timer: Timer = .{}; + var ms = [_]f64{ 10, 210 }; + var cursor: u64 = 17; + _ = try prepared(&timer, &ms, &.{ 1, 64 }, &cursor); + try t.expectEqual(@as(usize, 0), timer.setups); + try t.expectEqual(@as(usize, 0), timer.n); + try t.expectEqual(@as(u64, 17), cursor); +} + +test "Metal review: a useful 150ms entry is not starved by a discarded widest warm-up" { + var timer: Timer = .{ .value = 140 }; + var ms = [_]f64{150}; + var cursor: u64 = 0; + const stats = try prepared(&timer, &ms, &.{64}, &cursor); + try t.expectEqual(@as(f64, 140), ms[0]); + try t.expectEqual(@as(usize, 1), timer.n); + try t.expectEqual(@as(u32, 1), stats.lowered); +} + +test "Metal review: setup overrun cools down and advances to the next width" { + var timer: Timer = .{ .setup_ms = 195 }; + var ms = [_]f64{ 10, 20 }; + var cursor: u64 = 0; + _ = try prepared(&timer, &ms, &.{ 1, 2 }, &cursor); + try t.expectEqual(@as(usize, 1), timer.setups); + try t.expectEqual(@as(usize, 0), timer.n); + var skipped: Timer = .{ .setup_ms = 195 }; + _ = try prepared(&skipped, &ms, &.{ 1, 2 }, &cursor); + try t.expectEqual(@as(usize, 0), skipped.setups); + var next: Timer = .{}; + _ = try prepared(&next, &ms, &.{ 1, 2 }, &cursor); + try t.expectEqual(@as(usize, 1), next.seen[0]); +} + +test "Metal review: real 16/17 32/33 48/49 pairs run narrower first" { + var widths: [64]u32 = undefined; + for (&widths, 0..) |*w, i| w.* = @intCast(i + 1); + for ([_]u64{ 0, 1, 2 }) |phase| { + var timer: Timer = .{}; + var ms: [64]f64 = @splat(11); + var cursor = phase; + _ = try rule.healWindows(&timer, &ms, &widths, &cursor); + const edge: usize = @intCast(16 * (1 + phase)); + const calls = timer.seen[0..timer.n]; + const narrow = std.mem.indexOfScalar(usize, calls, edge - 1); + const wider = std.mem.indexOfScalar(usize, calls, edge); + try t.expect(narrow != null and wider != null); + try t.expect(narrow.? < wider.?); + } +} + +test "Metal review: partial healing cannot undercut an unhealed predecessor" { + var timer: Timer = .{ .value = 10 }; + var ms = [_]f64{ 10.8, 11.8, 12.8, 13.8 }; + var cursor: u64 = 1; + _ = try rule.healWindows(&timer, &ms, &.{ 1, 2, 3, 4 }, &cursor); + for (1..ms.len) |i| try t.expect(ms[i] >= ms[i - 1]); +} + +test "Metal review: zero and nonfinite samples cannot erase seven good readings" { + const Bad = struct { + calls: usize = 0, + invalid: f64, + pub fn time(s: *@This(), _: usize) !f64 { + s.calls += 1; + return if (s.calls == 4) s.invalid else 10; + } + }; + for ([_]f64{ 0, -1, std.math.nan(f64), std.math.inf(f64) }) |bad| { + var timer: Bad = .{ .invalid = bad }; + var ms: [1]f64 = undefined; + try rule.measureWindows(&timer, &ms, false); + try t.expectEqual(@as(f64, 10), ms[0]); + } +} + +test "Metal review: both entries in a two-wide high plateau are retimed" { + var timer: Timer = .{}; + var ms = [_]f64{ 10, 10, 10.5, 10.5, 10, 10 }; + try rule.smooth(&timer, &ms); + try t.expectEqualSlices(f64, &.{ 10, 10, 10, 10, 10, 10 }, &ms); +} + +test "Metal review: shared17 cannot heal below the live narrow16 price" { + var timer: Timer = .{ .value = 10 }; + var ms = [_]f64{ 13, 14 }; + var cursor: u64 = 0; + if (comptime @hasDecl(warm, "prepared")) { + _ = try warm.prepared(&timer, &ms, &.{ 17, 18 }, &cursor, 12, warm.Local{}, true); + } else _ = try rule.healWindows(&timer, &ms, &.{ 17, 18 }, &cursor); + try t.expectEqualSlices(f64, &.{ 13, 14 }, &ms); +} + +test "Metal review: clamped edge pairs contain only the available boundary widths" { + if (comptime @hasDecl(warm, "select")) { + const p = warm.select(&.{ 10, 11, 12 }, &.{ 17, 18, 19 }, 0); + try t.expectEqual(@as(usize, 1), p.n); + try t.expectEqual(@as(u32, 17), p.widest(&.{ 17, 18, 19 })); + const q = warm.select(&.{ 10, 11 }, &.{ 15, 16 }, 1); + try t.expectEqual(@as(usize, 1), q.n); + try t.expectEqual(@as(usize, 1), q.at[0]); + } +} + +test "Metal review: repair uses real coordinates on exponentially spaced prices" { + const WidthTimer = struct { + calls: usize = 0, + pub fn time(s: *@This(), i: usize) !f64 { + s.calls += 1; + return 10 + @as(f64, @floatFromInt(([_]u32{ 4, 8, 16, 32, 64, 128 })[i])); + } + }; + const widths = [_]u32{ 4, 8, 16, 32, 64, 128 }; + var ms = [_]f64{ 14, 18, 26, 42, 74, 138 }; + var timer: WidthTimer = .{}; + if (comptime @hasDecl(rule, "smoothWidths")) try rule.smoothWidths(&timer, &ms, &widths) else try rule.smooth(&timer, &ms); + try t.expectEqual(@as(usize, 0), timer.calls); + ms[3] *= 1.1; + if (comptime @hasDecl(rule, "smoothWidths")) try rule.smoothWidths(&timer, &ms, &widths) else try rule.smooth(&timer, &ms); + try t.expectEqual(@as(f64, 42), ms[3]); +} + +test "Metal review: each width's head observation spans the interleaved passes" { + const Observer = struct { + timer: *Timer, + before_end: usize = 0, + pub fn afterWidth(o: *@This(), _: usize) !void { + if (o.timer.n < 7) o.before_end += 1; + } + }; + var timer: Timer = .{}; + var observer: Observer = .{ .timer = &timer }; + var ms: [1]f64 = undefined; + try rule.interleaveWidths(&timer, &observer, &ms, false); + try t.expectEqual(@as(usize, 1), observer.before_end); +} + +test "Metal review: Qwen tight-context cold timing work stays below a twenty-percent increase" { + const Sweep = struct { + capacity: usize, + prompt: usize, + offset: usize = 0, + refills: usize = 0, + rows: usize = 0, + pub fn time(s: *@This(), i: usize) !f64 { + const width = i + 1; + if (s.offset == 0 or s.offset + width > s.capacity) { + s.offset = s.prompt; + s.rows += s.prompt; + s.refills += 1; + } + s.rows += width; + s.offset += 1; + return 10 + @as(f64, @floatFromInt(width)); + } + }; + for ([_]usize{ 16, 32, 64 }) |width| for ([_]usize{ width + 1, 128, 256, 16384 }) |capacity| { + if (capacity <= width) continue; + var baseline: Sweep = .{ .capacity = capacity, .prompt = @min(192, capacity - width) }; + var candidate: Sweep = .{ .capacity = capacity, .prompt = rule.context.promptRows(capacity, width, width + 5) }; + for (0..5) |_| { + _ = try baseline.time(width - 1); + _ = try candidate.time(width - 1); + } + var old: [64]f64 = undefined; + var now: [64]f64 = undefined; + var observer: rule.NoObserver = .{}; + try rule.measureWidths(&baseline, &observer, old[0..width], false); + try rule.measureWindows(&candidate, now[0..width], false); + try rule.smooth(&candidate, now[0..width]); + try t.expect(candidate.rows * 100 <= baseline.rows * 120); + try t.expect(candidate.refills * candidate.prompt * 100 <= baseline.refills * baseline.prompt * 120); + std.debug.print("Metal cold context width={d} capacity={d} prompt={d}/{d} refills={d}/{d} work_rows={d}/{d}\n", .{ width, capacity, baseline.prompt, candidate.prompt, baseline.refills, candidate.refills, baseline.rows, candidate.rows }); + }; +} + +test "Metal review: the rotating 150ms width cannot be starved by an earlier edge" { + var timer: Timer = .{ .value = 140 }; + var ms = [_]f64{ 100, 150 }; + var cursor: u64 = 1; + _ = try rule.healWindows(&timer, &ms, &.{ 1, 64 }, &cursor); + try t.expectEqual(@as(f64, 140), ms[1]); + try t.expectEqual(@as(usize, 1), timer.n); + try t.expectEqual(@as(usize, 1), timer.seen[0]); +} + +test "Metal review: no valid measured pass refuses a fresh table" { + const Invalid = struct { + pub fn time(_: @This(), _: usize) !f64 { + return 0; + } + }; + var ms: [2]f64 = undefined; + try t.expectError(error.InvalidWindowCost, rule.measureWindows(Invalid{}, &ms, false)); +} + +test "Metal review: setup and edges leave every rotating width reachable" { + const lone = [_]u32{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 20, 24, 28, 31, 33 }; + var shared: [48]u32 = undefined; + for (&shared, 17..) |*w, i| w.* = @intCast(i); + for ([_][]const u32{ &.{ 4, 8, 16, 32, 64, 128 }, &lone, &shared }) |widths| { + var values: [48]f64 = @splat(50); + values[widths.len - 1] = 150; + const ms = values[0..widths.len]; + var cursor: u64 = 0; + for (0..widths.len) |i| { + var timer: Timer = .{ .setup_ms = 1, .value = if (i == widths.len - 1) 150 else 50 }; + _ = try prepared(&timer, ms, widths, &cursor); + try t.expect(timer.n > 0); + try t.expectEqual(i, timer.seen[0]); + } + const phase0 = warm.select(ms, widths, 0); + const phase1 = warm.select(ms, widths, widths.len); + try t.expect(!std.mem.eql(usize, phase0.at[0..phase0.n], phase1.at[0..phase1.n])); + } +} diff --git a/zig/src/core/lanes/metal_cost_rule_test.zig b/zig/src/core/lanes/metal_cost_rule_test.zig new file mode 100644 index 00000000000..d2455327e44 --- /dev/null +++ b/zig/src/core/lanes/metal_cost_rule_test.zig @@ -0,0 +1,154 @@ +//! Fake GPU time exposes width-local slow stretches without changing the target arithmetic. +const std = @import("std"); +const rule = @import("cost_rule.zig"); +const Timer = struct { + calls: usize = 0, + total: f64 = 0, + slow: bool = false, + pub fn time(t: *@This(), i: usize) !f64 { + const noisy = t.slow and t.calls >= 30 * 8 and t.calls < 31 * 8; + const value = truth(i) * (if (noisy) @as(f64, 1.08) else 1); + t.calls += 1; + t.total += value; + return value; + } +}; +fn truth(i: usize) f64 { + const width = i + 1; + return 10 + 0.5 * @as(f64, @floatFromInt(width)) + @as(f64, if (width > 16) 2 else 0) + + @as(f64, if (width > 32) 3 else 0) + @as(f64, if (width > 48) 4 else 0); +} + +test "Metal window prices: interleaved minima survive one whole-width slow stretch" { + var timer: Timer = .{ .slow = true }; + var ms: [64]f64 = undefined; + try rule.measure(&timer, &timer, &ms, null, false); + try rule.smooth(&timer, &ms); + for (ms, 0..) |m, i| try std.testing.expectApproxEqRel(truth(i), m, 0.01); + var baseline: f64 = 0; + for (0..64) |i| baseline += 8 * truth(i); + try std.testing.expect(timer.total <= baseline * 1.2); + std.debug.print("Metal timing fake: baseline_ms={d:.3} measured_ms={d:.3} calls={d} increase_pct={d:.3}\n", .{ baseline, timer.total, timer.calls, 100 * (timer.total / baseline - 1) }); +} + +test "Metal window prices: a high outlier below the dip threshold is retimed and real tile steps survive" { + var timer: Timer = .{}; + var ms: [64]f64 = undefined; + for (&ms, 0..) |*m, i| m.* = truth(i); + ms[8] *= 1.04; + try rule.smooth(&timer, &ms); + for (ms, 0..) |m, i| try std.testing.expectApproxEqAbs(truth(i), m, 1e-9); + for ([_]usize{ 16, 32, 48 }) |i| try std.testing.expect(ms[i] > ms[i - 1] + 1); + try std.testing.expect(timer.calls <= ms.len); +} + +test "Metal window prices: a bad saved table heals across bounded warm loads without raising costs" { + const cache = @import("cost_cache.zig"); + const a = std.testing.allocator; + const io = std.testing.io; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const dir = try tmp.dir.realPathFileAlloc(io, ".", a); + defer a.free(dir); + const key = cache.buildKey("same-binary", &.{"same-shape"}); + const cursor_key = cache.buildKey(&key, &.{"metal-heal-v1"}); + var original: [64]f64 = undefined; + var widths: [64]u32 = undefined; + for (&original, &widths, 0..) |*m, *w, i| { + m.* = truth(i) * 1.08; + w.* = @intCast(i + 1); + } + cache.saveAt([64]f64, a, io, key, original, dir); + var maximum_ms: f64 = 0; + var maximum_reads: usize = 0; + for (0..64) |_| { + var kept = cache.loadAt([64]f64, a, io, key, dir).?; + var cursor = cache.loadAt(u64, a, io, cursor_key, dir) orelse 0; + var timer: Timer = .{}; + // Today's cache-hit branch returns the saved table; the shared healing policy is added with the fix. + if (comptime @hasDecl(rule, "healWindows")) _ = try rule.healWindows(&timer, &kept, &widths, &cursor); + for (kept, original) |m, before| try std.testing.expect(m <= before); + try std.testing.expect(timer.total <= 200); + try std.testing.expect(timer.calls <= 7); + maximum_ms = @max(maximum_ms, timer.total); + maximum_reads = @max(maximum_reads, timer.calls); + cache.saveAt([64]f64, a, io, key, kept, dir); + cache.saveAt(u64, a, io, cursor_key, cursor, dir); + } + const healed = cache.loadAt([64]f64, a, io, key, dir).?; + for (healed, 0..) |m, i| try std.testing.expectApproxEqRel(truth(i), m, 0.01); + try std.testing.expectEqual(@as(u64, 64), cache.loadAt(u64, a, io, cursor_key, dir).?); + std.debug.print("Metal healing fake: loads=64 max_forward_ms={d:.3} max_reads={d} remaining_error_pct=0\n", .{ maximum_ms, maximum_reads }); +} + +test "Metal window prices: paired warm probes follow identical calls despite different clocks and saved state" { + const a = std.testing.allocator; + const Wire = struct { + bits: std.ArrayList(bool) = .empty, + at: usize = 0, + lead: bool = true, + pub fn decide(w: *@This(), mine: bool) !bool { + if (w.lead) { + try w.bits.append(a, mine); + return mine; + } + const bit = w.bits.items[w.at]; + w.at += 1; + return bit; + } + }; + const Reads = struct { + calls: std.ArrayList(usize) = .empty, + scale: f64, + pub fn time(r: *@This(), i: usize) !f64 { + try r.calls.append(a, i); + return truth(i) * r.scale; + } + }; + var wire: Wire = .{}; + defer wire.bits.deinit(a); + var lead: Reads = .{ .scale = 1 }; + defer lead.calls.deinit(a); + var peer: Reads = .{ .scale = 2 }; + defer peer.calls.deinit(a); + var ms: [64]f64 = undefined; + var unused: [64]f64 = @splat(0); + var widths: [64]u32 = undefined; + for (&ms, &widths, 0..) |*m, *w, i| { + m.* = truth(i) * 1.08; + w.* = @intCast(i + 1); + } + var cursor: u64 = 31; + var peer_cursor: u64 = 0; + _ = try rule.warm_prices.synced(&lead, &ms, &widths, &cursor, &wire, true); + wire.lead = false; + _ = try rule.warm_prices.synced(&peer, &unused, &widths, &peer_cursor, &wire, false); + try std.testing.expectEqualSlices(usize, lead.calls.items, peer.calls.items); + try std.testing.expect(lead.calls.items.len > 1); + try std.testing.expectEqual(wire.bits.items.len, wire.at); + try std.testing.expectEqual(@as(u64, 32), cursor); + try std.testing.expectEqual(@as(u64, 0), peer_cursor); +} + +test "Metal window prices: stateful Qwen cold timing restores the serial saved-table oracle" { + const Stateful = struct { + calls: usize = 0, + pub fn time(t: *@This(), i: usize) !f64 { + const value = truth(i) + @as(f64, @floatFromInt(t.calls)); + t.calls += 1; + return value; + } + }; + var timer: Stateful = .{}; + var ms: [16]f64 = undefined; + try rule.serialWindows(&timer, &ms); + var expected: [16]f64 = undefined; + for (&expected, 0..) |*m, i| m.* = truth(i) + @as(f64, @floatFromInt(8 * i + 1)); + try std.testing.expectEqualSlices(f64, &expected, &ms); + try std.testing.expectEqual(@as(usize, 16 * 8), timer.calls); + const old_reference: [16]f64 = @splat(1); + try std.testing.expect(rule.drifted(&ms, &old_reference)); + try rule.again(&timer, &ms); + try std.testing.expectEqualSlices(f64, &expected, &ms); + try std.testing.expectEqual(@as(usize, 2 * 16 * 8), timer.calls); +} diff --git a/zig/src/core/lanes/price_log_test.zig b/zig/src/core/lanes/price_log_test.zig index 62cf8678d88..f4ebe6041f2 100644 --- a/zig/src/core/lanes/price_log_test.zig +++ b/zig/src/core/lanes/price_log_test.zig @@ -58,6 +58,65 @@ test "shared price log: a round line has its trial, rows, time, each stream's dr try t.expectEqualStrings("shared price: round streams=2 sampled=0 trial=1 rows=3 ms=15.000 head=0.000 forward=13.000 plain=3.000 row=1.000 drafts=1,0 depths=0,- accept=0.625/0.500,-", out.written()); } +test "shared price log: a shared-drafts round line carries every stream's depth and acceptance" { + var table = try costs(); + defer table.deinit(a); + var r = rule(&table); + defer r.deinit(); + var rates = [_]f64{ 0.625, 0.5 }; + const streams = [_]Stream{ .{ .depth = .{ .p = &rates } }, .{ .depth = .{ .p = &rates } } }; + const plans = [_]Plan{ .{ .stream = &streams[0] }, .{ .stream = &streams[1] } }; + const windows = [_]Window{ .{ .n = 2 }, .{ .n = 2 } }; + var out: std.Io.Writer.Allocating = .init(a); + defer out.deinit(); + try log.line(&out.writer, &r, &plans, &windows, .{ .trial = false, .sampled = false, .ms = 15.25, .head_ms = 0.5, .heads = &.{ 0, 1 }, .depths = &.{ 1, 1 } }); + try t.expectEqualStrings("shared price: round streams=2 sampled=0 trial=0 rows=4 ms=15.250 head=0.500 forward=14.000 plain=- row=- drafts=1,1 depths=1,1 accept=0.625/0.500,0.625/0.500", out.written()); +} + +test "shared price log: the shared-drafts path reads the flag and leaves the plain price unobserved" { + const Cfg = @import("config.zig"); + const Engine = @import("engine.zig").Engine; + const S = @import("stream.zig").Stream; + const fake = @import("fake.zig"); + const Drafted = @import("drafted.zig").Drafted; + const fixtures = @import("drafted_test.zig"); + const Suffix = @import("proposer.zig").SuffixLookup; + defer _ = sys.env.unsetenv(log.name); + for ([_]?[:0]const u8{ null, "1" }) |raw| { + if (raw) |v| try t.expectEqual(@as(c_int, 0), sys.env.setenv(log.name, v, 1)) else _ = sys.env.unsetenv(log.name); + var target: fake.Fake = .{ .gpa = a }; + defer target.deinit(); + var head: fixtures.FakeDrafter = .{ .facts_ = .{ .depth = 6, .step_ms = 0.5, .plain_guard = false, .batched = true, .prior = &.{ 0.9, 0.8, 0.7 } } }; + defer head.deinit(); + var strict: fixtures.Strict = .{ .inner = target.backend() }; + defer strict.deinit(); + var wrapped = try Drafted.init(a, strict.backend(), head.drafter()); + defer wrapped.deinit(); + var conf = try Cfg.Config.init(a, wrapped.facts(fixtures.base()), 16, 15); + defer conf.deinit(a); + var clock: fake.FixedClock = .{}; + var core = Engine.init(a, &conf, wrapped.backend(), clock.clock()); + defer core.deinit(); + var streams: [2]S = undefined; + var proposers: [2]Suffix = undefined; + for (&streams, &proposers) |*s, *p| { + p.* = try Suffix.init(a, .{ .min_match = 4 }); + s.* = try S.init(a, .{ .id = "log", .prompt = &fixtures.p1, .max_new = 80, .eos = &.{96}, .proposer = p.proposer() }); + try core.addStream(s); + } + defer for (&streams, &proposers) |*s, *p| { + s.deinit(a); + p.deinit(); + }; + try t.expectEqual(@as(?bool, null), core.price_log); + try core.step(); + try t.expect(core.shared_rounds > 0); + try t.expect(head.holds > 0); + try t.expectEqual(@as(?bool, raw != null), core.price_log); + try t.expectEqual(@as(usize, 0), core.rule.shared_price.buckets.items.len); + } +} + const Env = struct { raw: []const u8, pub fn get(v: Env, name: []const u8) ?[]const u8 { diff --git a/zig/src/core/lanes/recorder.zig b/zig/src/core/lanes/recorder.zig index b752f459d7d..6625017c115 100644 --- a/zig/src/core/lanes/recorder.zig +++ b/zig/src/core/lanes/recorder.zig @@ -239,7 +239,7 @@ pub const Recorded = struct { pub fn backend(x: *Recorded) be.Backend { const v = x.inner.vtable; x.table = .{ .prefill = prefill, .prefill_step = if (v.prefill_step != null) prefillStep else null, .cancel_prefill = if (v.cancel_prefill != null) cancelPrefill else null, .prefill_many = if (v.prefill_many != null) prefillMany else null, .first = first, .queue = queue, .read = read, .verify = verify, .keep = keep, .draft = draft, .draft_capacity = if (v.draft_capacity != null) draftCapacity else null, .proposal_draft = if (v.proposal_draft != null) plannedDraft else null, .clear_proposals = if (v.clear_proposals != null) clearProposals else null, .unspeculate = if (v.unspeculate != null) unspeculate else null, .probabilities = if (v.probabilities != null) probabilities else null, .tree = if (v.tree != null) tree else null, .alternatives = if (v.alternatives != null) alternatives else null, .prepare_features = if (v.prepare_features != null) prepareFeatures else null, .features = features, .first_row = if (v.first_row != null) firstRow else null, .first_masked = if (v.first_masked != null) firstMasked else null, .score = if (v.score != null) score else null, .held = if (v.held != null) held else null, .prompt_rows = v.prompt_rows, .release = release }; - return .{ .proposal_head = x.inner.proposal_head, .ptr = x, .round_observer = x.inner.round_observer, .vtable = &x.table, .first_before_draft = x.inner.first_before_draft, .penalties = x.inner.penalties, .chunk_invariant = x.inner.chunk_invariant, .warm_images = x.inner.warm_images }; + return .{ .proposal_head = x.inner.proposal_head, .ptr = x, .round_observer = x.inner.round_observer, .vtable = &x.table, .first_before_draft = x.inner.first_before_draft, .keep_full_lone = x.inner.keep_full_lone, .penalties = x.inner.penalties, .chunk_invariant = x.inner.chunk_invariant, .warm_images = x.inner.warm_images }; } fn of(p: *anyopaque) *Recorded { diff --git a/zig/src/core/lanes/recorder_test.zig b/zig/src/core/lanes/recorder_test.zig index e0d48b2640e..43bb3b004f2 100644 --- a/zig/src/core/lanes/recorder_test.zig +++ b/zig/src/core/lanes/recorder_test.zig @@ -270,7 +270,7 @@ test "a target that gives no rows cannot be recorded" { try std.testing.expectError(error.NoFeatures, rec.Recorded.init(.{ .ptr = &target, .vtable = &table }, &recorder)); } -test "recorded backend preserves both values of first_before_draft, penalties and chunk invariance" { +test "recorded backend preserves first-before-draft, penalties, chunk invariance and lone keep" { var target: fake.Fake = .{ .gpa = gpa }; defer target.deinit(); var tmp = std.testing.tmpDir(.{}); @@ -283,10 +283,12 @@ test "recorded backend preserves both values of first_before_draft, penalties an inner.first_before_draft = enabled; inner.penalties = enabled; inner.chunk_invariant = enabled; + inner.keep_full_lone = enabled; var recorded = try rec.Recorded.init(inner, &recorder); try std.testing.expectEqual(enabled, recorded.backend().first_before_draft); try std.testing.expectEqual(enabled, recorded.backend().penalties); try std.testing.expectEqual(enabled, recorded.backend().chunk_invariant); + try std.testing.expectEqual(enabled, recorded.backend().keep_full_lone); } } diff --git a/zig/src/core/lanes/rollback_test.zig b/zig/src/core/lanes/rollback_test.zig index 683d0c40a9f..7599ee690ec 100644 --- a/zig/src/core/lanes/rollback_test.zig +++ b/zig/src/core/lanes/rollback_test.zig @@ -157,6 +157,29 @@ test "rollback: heads landing no draft, some or all commit the one-token decode, }; } +test "rollback: fully accepted lone keep is opt-in and preserves main's default call count" { + // main keeps a window only when part of it was rejected or cut (max_new ends the last one short) + var partial: [2]usize = undefined; + for ([_]bool{ false, true }, 0..) |enabled, i| { + const r = try Rig.create(every, 0); + defer r.destroy(); + r.engine.backend.keep_full_lone = enabled; + const s = try r.open(0, .{ .prompt = &p1, .max_new = 24 }); + try r.engine.addStream(s); + _ = try r.finish(); + try expectFresh(.{ .prompt = &p1, .max_new = 24 }, s); + partial[i] = r.target.keep_calls - r.target.full_keeps; + if (enabled) { + try expect(r.target.full_keeps > 0); + } else { + // off: never a whole fully accepted lone window, so every keep is one main's rule makes + try std.testing.expectEqual(@as(usize, 0), r.target.full_keeps); + } + } + // the opt-in adds whole-window keeps only: the partial keeps main makes are the same calls + try std.testing.expectEqual(partial[0], partial[1]); +} + /// Steps of the uncancelled run of `reqs`, which bound where a cancel can land. fn stepsOf(accepts: ?usize, reqs: []const Req) !usize { const r = try Rig.create(accepts, 0); diff --git a/zig/src/core/lanes/shared_round.zig b/zig/src/core/lanes/shared_round.zig index 4d4572547df..67c954269fd 100644 --- a/zig/src/core/lanes/shared_round.zig +++ b/zig/src/core/lanes/shared_round.zig @@ -98,11 +98,12 @@ fn runPriced(e: *Engine, entries: []*Stream, comptime independent: bool, comptim for (budgets) |d| steps = if (e.cfg.draft_streams and depth.pricedBatched()) @max(steps, d - 1) else steps + @max(0, d - 1); const ms = e.clock.elapsedMs(.overhead) - e.cfg.draft_step_ms * @as(f64, @floatFromInt(steps)); try trail.event(e, &.{ f("ev", str("overhead")), f("streams", int(plans.len)), f("rows", int(total)), f("ms", ev.bits(ms)) }); + // the log covers both grant paths; only the plain guard's price observes them + const head_ms = e.rule.pricedHeadMs(budgets); + if (try price_log.enabled(e)) try price_log.round(e, plans, windows, .{ .trial = calibration, .sampled = sampled, .ms = ms, .head_ms = head_ms, .heads = heads.items, .depths = budgets }); if (independent) { var plain = total == plans.len; for (budgets) |d| plain = plain and d == 0; - const head_ms = e.rule.pricedHeadMs(budgets); - if (try price_log.enabled(e)) try price_log.round(e, plans, windows, .{ .trial = calibration, .sampled = sampled, .ms = ms, .head_ms = head_ms, .heads = heads.items, .depths = budgets }); try e.rule.observeSharedPrice(@intCast(plans.len), total, ms, sampled, head_ms, plain, calibration); } try e.rule.observeOverhead(@intCast(plans.len), total, ms, sampled, e.rule.headMs(budgets)); diff --git a/zig/src/core/profile.zig b/zig/src/core/profile.zig index 39ea907baf5..9131634a82d 100644 --- a/zig/src/core/profile.zig +++ b/zig/src/core/profile.zig @@ -39,6 +39,7 @@ pub const Switch = enum { TF_NEMOTRON_METAL_KV_PAGES, TF_QWEN27_METAL_KV_PAGES, TF_QWEN35_METAL_KV_PAGES, + TF_Q27_MTP_GPU_PICK, slide_learn_mode, TF_DSV41_EXPERT_TOPP, TF_DSV41_NUCLEUS, @@ -143,7 +144,7 @@ const nemotron: []const []const u8 = &.{ "nemotron_h", "nemotron_h_omni" }; const slide_cuda: []const []const u8 = &.{ "nemotron_h", "nemotron_h_omni", "qwen3_5" }; const flash: []const []const u8 = &.{"qwen4_exp"}; /// The CUDA families whose host prompt cache the generic CUDA host builds (cuda_keep_others_test.zig checks the list). -pub const cuda_cache: []const []const u8 = &.{ "nemotron_h", "nemotron_h_omni", "glm5_next", "minimax_m3_vl", "qwen3_5", "qwen3_5_moe", "qwen4_exp", "kolibri1", "gemma4", "gemma4_unified", "spark2_5", "dory", "lfm2_moe", "muse_spark" }; +pub const cuda_cache: []const []const u8 = &.{ "nemotron_h", "nemotron_h_omni", "glm5_next", "minimax_m3_vl", "qwen3_5", "qwen3_5_moe", "qwen4_exp", "kolibri1", "gemma4", "gemma4_unified", "spark2_5", "dory", "lfm2_moe", "muse_spark", "ricursive", "inkling2_loop" }; pub const entries = [_]Entry{ .{ .id = .TF_CUDA_POOL_AFTER_WARMUP, .families = &.{"qwen3_5"}, .class = .experimental, .syntax = .one, .report_values = &.{"1"}, .effect = "Size an idle device KV pool after Qwen DFlash2 warm-up", .evidence = "Default off; host sizing checks; device capacity and token checks required" }, @@ -182,6 +183,7 @@ pub const entries = [_]Entry{ .{ .id = .TF_NEMOTRON_METAL_KV_PAGES, .families = &.{"nemotron_h"}, .backend = "metal", .class = .identical, .syntax = .one, .effect = "Only exact 1 puts keys and values in the core pool's pages; unset, whole caches made at open", .evidence = "#1537" }, .{ .id = .TF_QWEN27_METAL_KV_PAGES, .families = &.{"qwen3_5"}, .backend = "metal", .class = .arithmetic, .syntax = .one, .effect = "Only exact 1 puts the 27B's keys and values in core-pool pages; refused on Macs with tensor units", .evidence = "#2370; class until a main-against-branch token-hash run on a Mac without tensor units" }, .{ .id = .TF_QWEN35_METAL_KV_PAGES, .families = qwen, .backend = "metal", .class = .arithmetic, .syntax = .one, .effect = "Only exact 1 puts the streams' keys and values in core-pool pages; unset, whole caches at load", .evidence = "#2370; class until a main-against-branch token-hash run" }, + .{ .id = .TF_Q27_MTP_GPU_PICK, .families = &.{"qwen3_5"}, .backend = "metal", .class = .arithmetic, .syntax = .one, .effect = "Only exact 1 fuses the 27B MTP absorb into one command buffer and picks drafts on the GPU", .evidence = "class until a draft-on against draft-off token-hash run on a Mac without tensor units" }, .{ .id = .TF_DSV41_EXPERT_TOPP, .families = &.{"deepseek_v41"}, .class = .experimental, .syntax = .present, .effect = "Expert top-p routing mass", .evidence = "#2370" }, .{ .id = .TF_DSV41_NUCLEUS, .families = &.{"deepseek_v41"}, .class = .arithmetic, .syntax = .present, .effect = "Nucleus candidate count", .evidence = "#2370" }, .{ .id = .TF_DSV41_CONTEXT, .families = &.{"deepseek_v41"}, .class = .arithmetic, .syntax = .present, .effect = "Slot position limit", .evidence = "#2370" }, diff --git a/zig/src/core/prompt_cache.zig b/zig/src/core/prompt_cache.zig index 549dfa015eb..c2aa44b0a14 100644 --- a/zig/src/core/prompt_cache.zig +++ b/zig/src/core/prompt_cache.zig @@ -102,6 +102,7 @@ pub const Entry = struct { expired: bool = false, // hidden from lookups immediately, reclaimed only at safe host boundaries removed_as: @import("prompt_cache_miss.zig").Reason = .evicted, // what the removal ring records when this entry goes borrowers: u32 = 0, // outstanding lookups: released by resumed or release, never evicted while borrowed + serial: u64 = 0, // the store's count when it was kept: names it while no lookup borrows it (reborrow) ext: std.ArrayList(*Entry) = .empty, // live extensions born no earlier own: []u32 = &.{}, // the kept prompt's one copy, which `tokens` and at first `last` slice (empty: they own theirs) }; @@ -126,6 +127,7 @@ pub const Store = struct { most: usize = std.math.maxInt(usize), // states kept at most: a family's snapshot slots, one a state held: u64 = 0, clock: u64 = 0, + serials: u64 = 0, // entries kept so far: the next one's serial entries: std.ArrayList(*Entry) = .empty, by_position: std.ArrayList(*Entry) = .empty, // nonowning, longest first; equal positions retain insertion order counts: Counts = .{}, @@ -201,6 +203,16 @@ pub const Store = struct { return false; } + /// The live entry `serial` names, borrowed again; null when it has been evicted or expired since. + pub fn reborrow(s: *Store, serial: u64) ?*Entry { + if (serial == 0) return null; // no entry the index holds has it: an unnumbered one is never lent + for (s.entries.items) |e| if (e.serial == serial and !e.expired) { + e.borrowers += 1; + return e; + }; + return null; + } + /// Whether an outstanding lookup still borrows `saved`'s state: the family spares it while restoring. pub fn borrowed(s: *Store, saved: Saved) bool { for (s.entries.items) |e| if (e.saved == saved and !e.expired and e.borrowers > 0) return true; diff --git a/zig/src/core/prompt_cache_index.zig b/zig/src/core/prompt_cache_index.zig index 63e0f2b5e42..b568589e489 100644 --- a/zig/src/core/prompt_cache_index.zig +++ b/zig/src/core/prompt_cache_index.zig @@ -21,6 +21,8 @@ pub fn add(s: *pc.Store, entry: *pc.Entry) !void { try s.entries.ensureUnusedCapacity(s.gpa, 1); try s.by_position.ensureUnusedCapacity(s.gpa, 1); s.entries.appendAssumeCapacity(entry); + s.serials += 1; // every entry the store holds is named by its own serial, never 0 (Store.reborrow) + entry.serial = s.serials; s.by_position.insertAssumeCapacity(below(s, entry.at), entry); // after every state as long: insertion order } diff --git a/zig/src/core/root.zig b/zig/src/core/root.zig index 9a428624b74..294bb26e702 100644 --- a/zig/src/core/root.zig +++ b/zig/src/core/root.zig @@ -2,6 +2,7 @@ pub const startup_receipt = @import("profile").startup_receipt; pub const benchmark_group = @import("benchmark_group.zig"); +pub const chunked_write = @import("chunked_write.zig"); pub const weight_only = @import("weight_only.zig"); pub const profile = @import("profile"); pub const safetensors = @import("safetensors.zig"); @@ -14,6 +15,7 @@ pub const digest_cache = @import("digest_cache.zig"); pub const checkpoint_identity = @import("checkpoint_identity.zig"); pub const checkpoint_read_ahead = @import("checkpoint_read_ahead.zig"); pub const checkpoint = @import("checkpoint.zig"); +pub const checkpoint_file_cache = @import("checkpoint_file_cache.zig"); pub const dfloat11_config = @import("dfloat11_config.zig"); pub const checkpoint_fixture = @import("checkpoint_fixture.zig"); pub const dfloat11_fixtures = @import("dfloat11_fixtures.zig"); diff --git a/zig/src/core/rows_all_test.zig b/zig/src/core/rows_all_test.zig index 1aabfff8efa..2e5aeb96fc6 100644 --- a/zig/src/core/rows_all_test.zig +++ b/zig/src/core/rows_all_test.zig @@ -15,6 +15,7 @@ test { _ = @import("rows_stage_test.zig"); _ = @import("rows_select_test.zig"); _ = @import("rows_recall_select_test.zig"); + _ = @import("rows_serial_test.zig"); _ = @import("rows_fallback_test.zig"); _ = @import("rows_charge_test.zig"); _ = @import("rows_pool_select_test.zig"); diff --git a/zig/src/core/rows_pool_select_test.zig b/zig/src/core/rows_pool_select_test.zig index b15e756c8a0..beab09be119 100644 --- a/zig/src/core/rows_pool_select_test.zig +++ b/zig/src/core/rows_pool_select_test.zig @@ -86,3 +86,115 @@ test "restore selection: pooled buffers trim only when supported and never steal s.release(borrowed); } } + +test "restore selection: a pool without trim reads into the spare storage an eviction leaves, as a keep would" { + var tmp = t.tmpDir(.{}); + defer tmp.cleanup(); + const dir = try tmp.dir.realPathFileAlloc(t.io, ".", a); + defer a.free(dir); + var prompt: [64]u32 = undefined; + for (&prompt, 0..) |*token, i| token.* = @intCast(100 + i); + const rules: pc.Rules = .{ .min_prompt = 0, .min_gap = 1, .lookahead = 1 }; + { + var f: Fake = .{ .gpa = a, .at = 20, .sum = fresh(prompt[0..20]) }; + var table = f.pooled().vtable.*; + table.rows = &Image.api; + const family: pc.Snapshots = .{ .ptr = &f, .vtable = &table }; + const r = try rows.Rows.open(a, family, options(dir)); + defer r.deinit(); + var s = pc.Store.init(a, family, rules, 1000); + defer s.deinit(); + s.disk = r; + try t.expect(s.keep(&prompt, 20, null, &.{}, &.{})); + while (rows.write.step(r)) {} + } + var f: Fake = .{ .gpa = a, .at = 5, .sum = fresh(prompt[0..5]) }; + var table = f.pooled().vtable.*; + table.rows = &Image.api; + table.trim = null; + const family: pc.Snapshots = .{ .ptr = &f, .vtable = &table }; + const r = try rows.Rows.open(a, family, options(dir)); + defer r.deinit(); + var s = pc.Store.init(a, family, rules, 240); + defer s.deinit(); + try t.expect(s.keep(&prompt, 5, null, &.{}, &.{})); + const borrowed = s.entries.items[0]; + borrowed.borrowers = 1; + prompt[0] = 999; + f.at = 30; // another conversation's state: its storage, once evicted, can take the read (120 >= 110) + f.sum = fresh(prompt[0..30]); + try t.expect(s.keep(&prompt, 30, null, &.{}, &.{})); + prompt[0] = 100; + s.disk = r; + try t.expectEqual(.disk, rows.read.resumable(&s, &prompt, &.{}, &.{}).from); + const restored = rows.read.recall(&s, &prompt, 64, &.{}, &.{}, borrowed).?; + try t.expectEqual(@as(u32, 20), restored.at); + try t.expectEqual(@as(u64, 1), r.counts.reads); + try t.expectEqual(@as(u64, 1), s.counts.evicted); + try t.expect(s.held + s.spare() <= s.budget); + try family.vtable.restore(family.ptr, null, restored.saved); + try t.expectEqual(fresh(&prompt), f.pass(&s, &prompt, .{ .from = restored.at })); + s.release(borrowed); +} + +/// A disk read into new storage, whatever spare storage the pool holds. +const Fresh = struct { + const api: rows.Image = .{ .parts = Image.parts, .gather = Image.gather, .blank = blank, .scatter = Image.scatter }; + fn blank(ptr: *anyopaque, at: u32) !pc.Saved { + const f: *Fake = @ptrCast(@alignCast(ptr)); + const previous = f.at; + f.at = at; + defer f.at = previous; + return f.snapshots().vtable.save(ptr, null, at); + } +}; + +test "restore selection: a pool that also trims reads a disk state only within its budget, whatever it reuses" { + var tmp = t.tmpDir(.{}); + defer tmp.cleanup(); + const dir = try tmp.dir.realPathFileAlloc(t.io, ".", a); + defer a.free(dir); + var prompt: [64]u32 = undefined; + for (&prompt, 0..) |*token, i| token.* = @intCast(100 + i); + const rules: pc.Rules = .{ .min_prompt = 0, .min_gap = 1, .lookahead = 1 }; + { + var f: Fake = .{ .gpa = a, .at = 20, .sum = fresh(prompt[0..20]) }; + var table = f.pooled().vtable.*; + table.rows = &Image.api; + const family: pc.Snapshots = .{ .ptr = &f, .vtable = &table }; + const r = try rows.Rows.open(a, family, options(dir)); + defer r.deinit(); + var s = pc.Store.init(a, family, rules, 1000); + defer s.deinit(); + s.disk = r; + try t.expect(s.keep(&prompt, 20, null, &.{}, &.{})); + while (rows.write.step(r)) {} + } + var f: Fake = .{ .gpa = a, .at = 5, .sum = fresh(prompt[0..5]) }; + var table = f.pooled().vtable.*; + table.rows = &Fresh.api; + try t.expect(table.reuses != null and table.trim != null); + const family: pc.Snapshots = .{ .ptr = &f, .vtable = &table }; + const r = try rows.Rows.open(a, family, options(dir)); + defer r.deinit(); + var s = pc.Store.init(a, family, rules, 240); + defer s.deinit(); + try t.expect(s.keep(&prompt, 5, null, &.{}, &.{})); + const borrowed = s.entries.items[0]; + borrowed.borrowers = 1; + prompt[0] = 999; + f.at = 30; // another conversation's state: once evicted, its spare storage is one the family says takes the read + f.sum = fresh(prompt[0..30]); + try t.expect(s.keep(&prompt, 30, null, &.{}, &.{})); + prompt[0] = 100; + s.disk = r; + try t.expectEqual(.disk, rows.read.resumable(&s, &prompt, &.{}, &.{}).from); + const restored = rows.read.recall(&s, &prompt, 64, &.{}, &.{}, borrowed).?; + try t.expectEqual(@as(u32, 20), restored.at); + try t.expectEqual(@as(u64, 1), r.counts.reads); + try t.expectEqual(@as(u64, 1), s.counts.evicted); + try t.expect(s.held + s.spare() <= s.budget); // the spare storage was trimmed for the new storage, not left over it + try family.vtable.restore(family.ptr, null, restored.saved); + try t.expectEqual(fresh(&prompt), f.pass(&s, &prompt, .{ .from = restored.at })); + s.release(borrowed); +} diff --git a/zig/src/core/rows_read.zig b/zig/src/core/rows_read.zig index 244367d3af2..129a86b2202 100644 --- a/zig/src/core/rows_read.zig +++ b/zig/src/core/rows_read.zig @@ -51,10 +51,10 @@ fn one(r: *Rows, name: Name, kind: file.Kind, ext: []const u8, at: u32, ranges: return o.trailer.payload + o.trailer.meta + @sizeOf(file.Trailer); } -/// Whether a family refused what a file holds (words that differ, a size or a range that does not fit its blank). +/// Whether a family refused what a file holds (words that differ, of another world or layout; a size or range unfit). fn refused(err: anyerror) bool { return switch (err) { - error.SnapshotSize, error.BadKeptRange, error.DiskWords, error.KeptWordsDiffer => true, + error.SnapshotSize, error.BadKeptRange, error.DiskWords, error.KeptWordsDiffer, error.DiskWorld, error.DiskLayout => true, else => false, }; } @@ -128,9 +128,9 @@ fn attempt(s: *pc.Store, prompt: []const u32, born: u32, starts: []const u32, sp const name = candidate.name; const bytes = r.blankBytes(candidate.at); if (bytes > s.budget or s.most == 0) return have; - if (!ready(s, bytes)) present(r, chosen) catch |err| return failed(before, candidate.at, err, have); // nothing goes to make room for a state whose file is gone + if (!ready(s, candidate.at, bytes)) present(r, chosen) catch |err| return failed(before, candidate.at, err, have); // nothing goes to make room for a state whose file is gone if (r.spill != .off) r.touch(chosen); // the newest: the spills that make room for it push older states off first - while (!ready(s, bytes)) { + while (!ready(s, candidate.at, bytes)) { if (s.family.vtable.trim) |trim| { const spare = s.spare(); trim(s.family.ptr, s.budget -| s.held -| bytes); @@ -165,8 +165,11 @@ fn attempt(s: *pc.Store, prompt: []const u32, born: u32, starts: []const u32, sp return e; } -fn ready(s: *const pc.Store, bytes: u64) bool { +fn ready(s: *const pc.Store, at: u32, bytes: u64) bool { if (s.held > s.budget or s.entries.items.len >= s.most) return false; + const f = s.family.vtable; + // a pool without trim reads into spare storage that takes the state, as a keep would + if (f.trim == null) if (f.reuses) |reuses| if (reuses(s.family.ptr, at)) return true; const room = s.budget - s.held; const spare = s.spare(); return spare <= room and bytes <= room - spare; diff --git a/zig/src/core/rows_refusal_test.zig b/zig/src/core/rows_refusal_test.zig index 5b298996e9b..668a9884cee 100644 --- a/zig/src/core/rows_refusal_test.zig +++ b/zig/src/core/rows_refusal_test.zig @@ -84,6 +84,8 @@ const cases = [_]Case{ .{ .piece = .shared, .err = error.BadKeptRange, .mine = false, .other = false }, .{ .piece = .own, .err = error.DiskWords, .mine = false, .other = true }, // the state's own file .{ .piece = .own, .err = error.KeptWordsDiffer, .mine = false, .other = true }, + .{ .piece = .own, .err = error.DiskWorld, .mine = false, .other = true }, // written by another number of ranks + .{ .piece = .own, .err = error.DiskLayout, .mine = false, .other = true }, // or in another layout .{ .piece = .own, .err = error.ScatterFailed, .mine = true, .other = true }, // a link failing: the disk is fine .{ .piece = .shared, .err = error.OutOfMemory, .mine = true, .other = true }, }; diff --git a/zig/src/core/rows_select.zig b/zig/src/core/rows_select.zig index d6ac457847a..cb82666a458 100644 --- a/zig/src/core/rows_select.zig +++ b/zig/src/core/rows_select.zig @@ -56,12 +56,15 @@ fn capacity(s: *const pc.Store, have: ?*pc.Entry) ?u64 { var protected: usize = 0; const f = s.family.vtable; for (s.entries.items) |e| { - if (e == have or e.borrowers > 0) protected += 1 else if (f.spare == null or f.trim != null) { + if (e == have or e.borrowers > 0) protected += 1 else if (f.spare == null or f.trim != null or f.reuses != null) { reclaimable +|= e.bytes; } } + if (protected >= s.most) return null; + // a pool that reuses spare storage without trimming it (GLM's snapshot pages): a read takes spare or evicted pages + if (f.reuses != null and f.trim == null) return s.spare() +| reclaimable; const fixed = (s.held -| reclaimable) +| if (f.trim == null) s.spare() else 0; - if (protected >= s.most or fixed > s.budget) return null; + if (fixed > s.budget) return null; return s.budget - fixed; } diff --git a/zig/src/core/rows_serial_test.zig b/zig/src/core/rows_serial_test.zig new file mode 100644 index 00000000000..24fc401ff80 --- /dev/null +++ b/zig/src/core/rows_serial_test.zig @@ -0,0 +1,58 @@ +//! States read back from disk are numbered like kept ones: a lent one is borrowed again, never another. +const std = @import("std"); +const pc = @import("prompt_cache.zig"); +const rows = @import("rows_store.zig"); +const fake = @import("rows_fake.zig"); +const t = std.testing; +const a = t.allocator; +const rules: pc.Rules = .{ .min_prompt = 0, .min_gap = 1, .lookahead = 1 }; + +fn options(root: []const u8) rows.Options { + return .{ .sync_writes = true, .root = root, .identity = 171, .cap = 1 << 26, .floor = 0, .daily = 1 << 28, .lookahead = 1 }; +} + +test "rows serial: two states read back from disk carry their own serials, and a reborrow takes exactly the one lent" { + var tmp = t.tmpDir(.{}); + defer tmp.cleanup(); + const dir = try tmp.dir.realPathFileAlloc(t.io, ".", a); + defer a.free(dir); + var pa: [2000]u32 = undefined; + for (&pa, 0..) |*token, i| token.* = @intCast(17 + i * 3); + var pb: [2000]u32 = undefined; + for (&pb, 0..) |*token, i| token.* = @intCast(29 + i * 7); + var f: fake.Fake = .{ .gpa = a, .prompt = &pa, .at = 1400 }; + { // both prompts' states on disk, from a store that has gone + const r = try rows.Rows.open(a, f.snapshots(), options(dir)); + defer r.deinit(); + var s = pc.Store.init(a, f.snapshots(), rules, 1 << 30); + defer s.deinit(); + s.disk = r; + for ([_][]const u32{ &pa, &pb }) |p| { + f.prompt = p; + try t.expect(s.keep(p, 1400, null, &.{}, &.{})); + while (rows.write.step(r)) {} + } + } + const r = try rows.Rows.open(a, f.snapshots(), options(dir)); + defer r.deinit(); + var s = pc.Store.init(a, f.snapshots(), rules, 1 << 30); + defer s.deinit(); + s.disk = r; + var read: [2]*pc.Entry = undefined; + for ([_][]const u32{ &pa, &pb }, &read) |p, *e| { // each read back by its own lookup, then lent (released) + f.prompt = p; + const l = try s.lookup(a, p, 0, &.{}, &.{}, &.{}); + defer a.free(l.marks); + e.* = l.entry orelse return error.NotReadBack; + s.release(e.*); + } + try t.expect(read[0].serial != 0 and read[1].serial != 0 and read[0].serial != read[1].serial); + try t.expect(s.reborrow(0) == null); // no entry is unnumbered, and none is lent as one + try t.expectEqual(read[1], s.reborrow(read[1].serial).?); + s.release(read[1]); + // the lent one evicted while the other stays: its reborrow finds nothing, never the other + const serial = read[1].serial; + s.remove(std.mem.indexOfScalar(*pc.Entry, s.entries.items, read[1]).?); + try t.expect(s.reborrow(serial) == null); + try t.expectEqual(@as(u32, 0), read[0].borrowers); +} diff --git a/zig/src/core/rows_test.zig b/zig/src/core/rows_test.zig index e809569c9cb..d14a8c2b7b1 100644 --- a/zig/src/core/rows_test.zig +++ b/zig/src/core/rows_test.zig @@ -247,16 +247,18 @@ fn gridRequest(a: Allocator, s: *pc.Store, f: *Fake, p: []const u32, history: u3 return .{ .from = plan.from, .sum = f.sum }; } -test "a grid family's requests name no chunk starts: its states go to disk on the grid and resume after a restart" { +/// A grid family's states through one writer (`sync`: the test's thread, else the I/O worker), read after a restart. +fn gridRoundTrip(sync: bool, tag: []const u8) !void { const gpa = std.testing.allocator; var arena: std.heap.ArenaAllocator = .init(gpa); defer arena.deinit(); const a = arena.allocator(); var buf: [128]u8 = undefined; - const dir = root(&buf, "grid"); + const dir = root(&buf, tag); defer rmTree(dir); const grid: pc.Rules = .{ .lookahead = 1, .min_prompt = 0, .min_gap = 1, .planned = true, .grid = 512 }; var o = options(dir); + o.sync_writes = sync; o.planned = true; o.grid = 512; const p = try prompt(a, 0, 5, 1300); // the engine cuts its chunks on the grid: 512 and 1024 @@ -268,7 +270,7 @@ test "a grid family's requests name no chunk starts: its states go to disk on th defer s.deinit(); s.disk = r; _ = try gridRequest(a, &s, &f, p, 1200); - drain(r); + _ = rows.write.drain(r, rows.write.nowNs() + 3 * std.time.ns_per_s); // the worker publishes the states try std.testing.expect(r.states.items.len > 0); for (r.states.items) |st| { try std.testing.expectEqual(@as(u32, 0), st.at % 512); @@ -289,6 +291,14 @@ test "a grid family's requests name no chunk starts: its states go to disk on th try std.testing.expectEqual(@as(u64, 1), r.counts.reads); } +test "a grid family's requests name no chunk starts: its states go to disk on the grid and resume after a restart" { + try gridRoundTrip(true, "grid"); +} + +test "a grid family's chunk starts reach the I/O worker's writes as well, the writer GLM's store uses" { + try gridRoundTrip(false, "grid-worker"); +} + test "an entry evicted before its write leaves the queue; once written, an eviction costs nothing" { const gpa = std.testing.allocator; var arena: std.heap.ArenaAllocator = .init(gpa); diff --git a/zig/src/core/tokenizer/eos.zig b/zig/src/core/tokenizer/eos.zig index 16d26121364..54edf832c9d 100644 --- a/zig/src/core/tokenizer/eos.zig +++ b/zig/src/core/tokenizer/eos.zig @@ -8,30 +8,17 @@ pub fn appendId(a: Allocator, out: *std.ArrayList(u32), id: u32, vocab: usize) ! if (std.mem.indexOfScalar(u32, out.items, id) == null) try out.append(a, id); } -/// Where a family takes config.json's ids from; generation_config.json's are added after them in every order. -pub const Order = enum { - /// The root's ids; text_config's only when the root gave none. - text_if_root_empty, - /// The root's, text_config's and generation_config.json's, all of them. - every_source, - /// The root's key whenever it exists (a root `null` or `[]` hides text_config's), else text_config's. - root_key_else_text, -}; - -/// One family's EOS rule: the order, whether nested arrays hold more ids, the most ids, and whether none is refused. +/// One family's EOS rule: whether nested arrays hold more ids, the most ids, and whether none is refused. pub const Policy = struct { - order: Order, nested: bool, max: ?usize, required: bool, }; /// `resolve`'s rule: the served stop set (server/hf_text.zig), dots_mocr, dory and kolibri1. -pub const served: Policy = .{ .order = .text_if_root_empty, .nested = false, .max = null, .required = false }; -/// Qwen3.5's HIP loader (families/qwen3_5/config_checks.zig): every source, at most 8 ids. -pub const qwen35_hip: Policy = .{ .order = .every_source, .nested = true, .max = 8, .required = true }; -/// qwen27 on Metal (families/qwen27/config.zig): root key else text_config, then generation, at most 8 ids. -pub const qwen27_metal: Policy = .{ .order = .root_key_else_text, .nested = true, .max = 8, .required = true }; +pub const served: Policy = .{ .nested = false, .max = null, .required = false }; +/// Qwen 3.5's readers (qwen3_5/config_checks.zig, qwen27/config.zig): nested ids, at most 8, at least one. +pub const qwen35: Policy = .{ .nested = true, .max = 8, .required = true }; /// BadEosValue: not a null, an id or an id array (a family names it); BadEos: an id at or past the vocabulary. pub const BufferError = error{ BadEos, BadEosValue, TooManyEos, MissingEos }; @@ -81,21 +68,10 @@ const Ids = struct { if (doc.object.get("eos_token_id")) |v| try s.add(v, false); } + /// One rule for every family: the root's ids, text_config's only when the root gave none, then generation's. fn gather(s: *Ids, root: Value, text: Value, generation: Value) Error!void { - switch (s.policy.order) { - .text_if_root_empty => { - try s.field(root); - if (s.list.items.len == 0) try s.field(text); - }, - .every_source => { - try s.field(root); - try s.field(text); - }, - .root_key_else_text => if (root == .object and root.object.contains("eos_token_id")) - try s.field(root) - else - try s.field(text), - } + try s.field(root); + if (s.list.items.len == 0) try s.field(text); try s.field(generation); if (s.policy.required and s.list.items.len == 0) return error.MissingEos; } diff --git a/zig/src/core/tokenizer/eos_policy_test.zig b/zig/src/core/tokenizer/eos_policy_test.zig index 39c33f1cae7..b87c78d0bb6 100644 --- a/zig/src/core/tokenizer/eos_policy_test.zig +++ b/zig/src/core/tokenizer/eos_policy_test.zig @@ -2,32 +2,33 @@ const std = @import("std"); const eos = @import("eos.zig"); const t = std.testing; +const Value = std.json.Value; /// config.json (with any text_config inside), generation_config.json ("" for none), and each policy's answer. -const Case = struct { config: []const u8, generation: []const u8, served: []const u8, hip: []const u8, metal: []const u8 }; +const Case = struct { config: []const u8, generation: []const u8, served: []const u8, qwen35: []const u8 }; -// Answers are "1,3" for ids in order, "-" for none, or an error name. +// Answers are "1,3" for ids in order, "-" for none, or an error name; one precedence for both policies. const cases = [_]Case{ - .{ .config = "{\"eos_token_id\":1,\"text_config\":{\"eos_token_id\":2}}", .generation = "{\"eos_token_id\":[3]}", .served = "1,3", .hip = "1,2,3", .metal = "1,3" }, - .{ .config = "{\"text_config\":{\"eos_token_id\":2}}", .generation = "", .served = "2", .hip = "2", .metal = "2" }, - // a root null or [] hides text_config on qwen27 Metal only - .{ .config = "{\"eos_token_id\":null,\"text_config\":{\"eos_token_id\":2}}", .generation = "", .served = "2", .hip = "2", .metal = "MissingEos" }, - .{ .config = "{\"eos_token_id\":[],\"text_config\":{\"eos_token_id\":2}}", .generation = "", .served = "2", .hip = "2", .metal = "MissingEos" }, - .{ .config = "{\"eos_token_id\":[1,1]}", .generation = "", .served = "1", .hip = "1", .metal = "1" }, - .{ .config = "{\"eos_token_id\":[1,2,3,4,5,6,7,8]}", .generation = "{\"eos_token_id\":8}", .served = "1,2,3,4,5,6,7,8", .hip = "1,2,3,4,5,6,7,8", .metal = "1,2,3,4,5,6,7,8" }, - .{ .config = "{\"eos_token_id\":[1,2,3,4,5,6,7,8]}", .generation = "{\"eos_token_id\":9}", .served = "1,2,3,4,5,6,7,8,9", .hip = "TooManyEos", .metal = "TooManyEos" }, - .{ .config = "{\"eos_token_id\":[[1,2]]}", .generation = "", .served = "BadEosValue", .hip = "1,2", .metal = "1,2" }, - .{ .config = "{\"eos_token_id\":[1,null]}", .generation = "", .served = "1", .hip = "1", .metal = "1" }, - .{ .config = "{\"eos_token_id\":\"1\"}", .generation = "", .served = "BadEosValue", .hip = "BadEosValue", .metal = "BadEosValue" }, - .{ .config = "{\"eos_token_id\":1.0}", .generation = "", .served = "BadEosValue", .hip = "BadEosValue", .metal = "BadEosValue" }, - .{ .config = "{\"eos_token_id\":-1}", .generation = "", .served = "BadEosValue", .hip = "BadEosValue", .metal = "BadEosValue" }, - .{ .config = "{\"eos_token_id\":4294967296}", .generation = "", .served = "BadEosValue", .hip = "BadEosValue", .metal = "BadEosValue" }, - .{ .config = "{\"eos_token_id\":[1,true]}", .generation = "", .served = "BadEosValue", .hip = "BadEosValue", .metal = "BadEosValue" }, - .{ .config = "{\"eos_token_id\":10}", .generation = "", .served = "BadEos", .hip = "BadEos", .metal = "BadEos" }, - .{ .config = "{}", .generation = "{\"eos_token_id\":3}", .served = "3", .hip = "3", .metal = "3" }, - .{ .config = "{}", .generation = "{\"eos_token_id\":[9,10]}", .served = "BadEos", .hip = "BadEos", .metal = "BadEos" }, - .{ .config = "{}", .generation = "", .served = "-", .hip = "MissingEos", .metal = "MissingEos" }, - .{ .config = "{}", .generation = "{\"eos_token_id\":null}", .served = "-", .hip = "MissingEos", .metal = "MissingEos" }, + .{ .config = "{\"eos_token_id\":1,\"text_config\":{\"eos_token_id\":2}}", .generation = "{\"eos_token_id\":[3]}", .served = "1,3", .qwen35 = "1,3" }, + .{ .config = "{\"text_config\":{\"eos_token_id\":2}}", .generation = "", .served = "2", .qwen35 = "2" }, + // a root null or [] gives no ids of its own, so the tower's are the ones the rule takes + .{ .config = "{\"eos_token_id\":null,\"text_config\":{\"eos_token_id\":2}}", .generation = "", .served = "2", .qwen35 = "2" }, + .{ .config = "{\"eos_token_id\":[],\"text_config\":{\"eos_token_id\":2}}", .generation = "", .served = "2", .qwen35 = "2" }, + .{ .config = "{\"eos_token_id\":[1,1]}", .generation = "", .served = "1", .qwen35 = "1" }, + .{ .config = "{\"eos_token_id\":[1,2,3,4,5,6,7,8]}", .generation = "{\"eos_token_id\":8}", .served = "1,2,3,4,5,6,7,8", .qwen35 = "1,2,3,4,5,6,7,8" }, + .{ .config = "{\"eos_token_id\":[1,2,3,4,5,6,7,8]}", .generation = "{\"eos_token_id\":9}", .served = "1,2,3,4,5,6,7,8,9", .qwen35 = "TooManyEos" }, + .{ .config = "{\"eos_token_id\":[[1,2]]}", .generation = "", .served = "BadEosValue", .qwen35 = "1,2" }, + .{ .config = "{\"eos_token_id\":[1,null]}", .generation = "", .served = "1", .qwen35 = "1" }, + .{ .config = "{\"eos_token_id\":\"1\"}", .generation = "", .served = "BadEosValue", .qwen35 = "BadEosValue" }, + .{ .config = "{\"eos_token_id\":1.0}", .generation = "", .served = "BadEosValue", .qwen35 = "BadEosValue" }, + .{ .config = "{\"eos_token_id\":-1}", .generation = "", .served = "BadEosValue", .qwen35 = "BadEosValue" }, + .{ .config = "{\"eos_token_id\":4294967296}", .generation = "", .served = "BadEosValue", .qwen35 = "BadEosValue" }, + .{ .config = "{\"eos_token_id\":[1,true]}", .generation = "", .served = "BadEosValue", .qwen35 = "BadEosValue" }, + .{ .config = "{\"eos_token_id\":10}", .generation = "", .served = "BadEos", .qwen35 = "BadEos" }, + .{ .config = "{}", .generation = "{\"eos_token_id\":3}", .served = "3", .qwen35 = "3" }, + .{ .config = "{}", .generation = "{\"eos_token_id\":[9,10]}", .served = "BadEos", .qwen35 = "BadEos" }, + .{ .config = "{}", .generation = "", .served = "-", .qwen35 = "MissingEos" }, + .{ .config = "{}", .generation = "{\"eos_token_id\":null}", .served = "-", .qwen35 = "MissingEos" }, }; /// Ids as the fixture spells them. @@ -39,17 +40,54 @@ fn spell(a: std.mem.Allocator, ids: []const u32) ![]const u8 { } /// The policy's answer as the fixture spells it. -fn answer(a: std.mem.Allocator, policy: eos.Policy, root: std.json.Value, generation: std.json.Value) ![]const u8 { +fn answer(a: std.mem.Allocator, policy: eos.Policy, root: Value, generation: Value) ![]const u8 { const text = if (root.object.get("text_config")) |v| v else root; var buf: [16]u32 = undefined; return spell(a, eos.collect(buf[0..], policy, root, text, generation, 10) catch |e| return @errorName(e)); } -fn parse(a: std.mem.Allocator, text: []const u8) !std.json.Value { - return if (text.len == 0) .null else std.json.parseFromSliceLeaky(std.json.Value, a, text, .{}); +fn parse(a: std.mem.Allocator, text: []const u8) !Value { + return if (text.len == 0) .null else std.json.parseFromSliceLeaky(Value, a, text, .{}); } -test "EOS policies: each fixture's ids or refusal under served, Qwen3.5 HIP and qwen27 Metal" { +/// The tower the fixture nests, or the root itself when it is flat. +fn tower(root: Value) Value { + return if (root.object.get("text_config")) |v| v else root; +} + +// Planted controls: each is a deliberately wrong reader, so the test names the answer the real rule must not give. + +/// Ignores generation_config.json (its document left out). +fn noGeneration(buf: []u32, root: Value, text: Value, vocab: usize) eos.BufferError![]const u32 { + return eos.collect(buf, eos.qwen35, root, text, .null, vocab); +} + +/// Stops at the root and never falls through to the tower (the retired root-key rule). +fn rootOnly(buf: []u32, root: Value, vocab: usize) eos.BufferError![]const u32 { + return eos.collect(buf, eos.qwen35, root, .null, .null, vocab); +} + +/// Reads the tower in place of the root even when the root gave ids. +fn towerOnly(buf: []u32, text: Value, generation: Value, vocab: usize) eos.BufferError![]const u32 { + return eos.collect(buf, eos.qwen35, .null, text, generation, vocab); +} + +/// Unions every source (the retired union rule), each id once, at most 8. +fn unionSources(buf: []u32, root: Value, text: Value, generation: Value, vocab: usize) eos.BufferError![]const u32 { + var n: usize = 0; + for ([_]Value{ root, text, generation }) |src| { + var part: [8]u32 = undefined; + for (try eos.collect(part[0..], eos.qwen35, src, .null, .null, vocab)) |id| { + if (std.mem.indexOfScalar(u32, buf[0..n], id) != null) continue; + if (n == 8) return error.TooManyEos; + buf[n] = id; + n += 1; + } + } + return buf[0..n]; +} + +test "EOS policies: each fixture's ids or refusal under served and Qwen 3.5" { var arena: std.heap.ArenaAllocator = .init(t.allocator); defer arena.deinit(); const a = arena.allocator(); @@ -58,8 +96,7 @@ test "EOS policies: each fixture's ids or refusal under served, Qwen3.5 HIP and const gen = try parse(a, c.generation); errdefer std.debug.print("config {s} generation {s}\n", .{ c.config, c.generation }); try t.expectEqualStrings(c.served, try answer(a, eos.served, root, gen)); - try t.expectEqualStrings(c.hip, try answer(a, eos.qwen35_hip, root, gen)); - try t.expectEqualStrings(c.metal, try answer(a, eos.qwen27_metal, root, gen)); + try t.expectEqualStrings(c.qwen35, try answer(a, eos.qwen35, root, gen)); } } @@ -79,7 +116,48 @@ test "EOS policies: resolve is the served policy, every malformed value named Ba test "EOS policies: a source that is not an object is a malformed value under every policy" { var buf: [8]u32 = undefined; - const root: std.json.Value = .{ .object = .empty }; - for ([_]eos.Policy{ eos.served, eos.qwen35_hip, eos.qwen27_metal }) |p| + const root: Value = .{ .object = .empty }; + for ([_]eos.Policy{ eos.served, eos.qwen35 }) |p| try t.expectError(error.BadEosValue, eos.collect(&buf, p, root, root, .{ .integer = 1 }, 10)); } + +test "one rule: a root null or [] gives the tower's ids, the root-only control refuses them" { + var arena: std.heap.ArenaAllocator = .init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var real: [16]u32 = undefined; + var control: [16]u32 = undefined; + const spellings = [_][]const u8{ + "{\"eos_token_id\":null,\"text_config\":{\"eos_token_id\":2}}", + "{\"eos_token_id\":[],\"text_config\":{\"eos_token_id\":2}}", + }; + for (spellings) |raw| { + const root = try parse(a, raw); + // the rule: the root gave nothing, so the tower's id is the stop token, as the served reader gives + try t.expectEqualSlices(u32, &.{2}, try eos.collect(&real, eos.qwen35, root, tower(root), .null, 10)); + try t.expectEqualSlices(u32, &.{2}, try eos.resolve(a, root, .null, 10)); + // the planted control stops at the present root key, so it names the family's MissingEos instead + try t.expectError(error.MissingEos, rootOnly(&control, root, 10)); + } +} + +test "one rule: the root's ids win over the tower's, and every planted control differs from them" { + var arena: std.heap.ArenaAllocator = .init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var real: [16]u32 = undefined; + var towered: [16]u32 = undefined; + var unioned: [16]u32 = undefined; + var nogen: [16]u32 = undefined; + const root = try parse(a, "{\"eos_token_id\":1,\"text_config\":{\"eos_token_id\":2}}"); + const gen = try parse(a, "{\"eos_token_id\":[3]}"); + const ids = try eos.collect(&real, eos.qwen35, root, tower(root), gen, 10); + try t.expectEqualSlices(u32, &.{ 1, 3 }, ids); + try t.expectEqualSlices(u32, ids, try eos.resolve(a, root, gen, 10)); + // the tower in place of the root: 2 where the rule has 1 + try t.expectEqualSlices(u32, &.{ 2, 3 }, try towerOnly(&towered, tower(root), gen, 10)); + // the union: the tower's id joins where the rule stops at the root's + try t.expectEqualSlices(u32, &.{ 1, 2, 3 }, try unionSources(&unioned, root, tower(root), gen, 10)); + // without generation_config.json the served id 3 is missing + try t.expectEqualSlices(u32, &.{1}, try noGeneration(&nogen, root, tower(root), 10)); +} diff --git a/zig/src/cuda/kernels.zig b/zig/src/cuda/kernels.zig index adc58505802..bf53d71117e 100644 --- a/zig/src/cuda/kernels.zig +++ b/zig/src/cuda/kernels.zig @@ -116,6 +116,12 @@ pub const inkling2_attn: []const u8 = if (available) &Blob("fatbin_inkling2_attn pub const inkling2_pattn: []const u8 = if (available) &Blob("fatbin_inkling2_pattn").bytes else &.{}; pub const inkling2_ops: []const u8 = if (available) &Blob("fatbin_inkling2_ops").bytes else &.{}; pub const inkling2_rows: []const u8 = if (available) &Blob("fatbin_inkling2_rows").bytes else &.{}; +pub const ricursive: []const u8 = if (available) &Blob("fatbin_ricursive").bytes else &.{}; +pub const ricursive_prep: []const u8 = if (available) &Blob("fatbin_ricursive_prep").bytes else &.{}; +pub const inkling2_experts: []const u8 = if (available) &Blob("fatbin_inkling2_experts").bytes else &.{}; +pub const inkling2_modelopt: []const u8 = if (available) &Blob("fatbin_inkling2_modelopt").bytes else &.{}; +pub const inkling2_loop_math: []const u8 = if (available) &Blob("fatbin_inkling2_loop_math").bytes else &.{}; +pub const inkling2_vision: []const u8 = if (available) &Blob("fatbin_inkling2_vision").bytes else &.{}; pub const glm_quant: []const u8 = if (available) &Blob("fatbin_glm_quant").bytes else &.{}; pub const glm_vision: []const u8 = if (available) &Blob("fatbin_glm_vision").bytes else &.{}; pub const glm_mm: []const u8 = if (available) &Blob("fatbin_glm_mm").bytes else &.{}; diff --git a/zig/src/cuda/qmmf.zig b/zig/src/cuda/qmmf.zig index e515a93a52d..bf22ac87377 100644 --- a/zig/src/cuda/qmmf.zig +++ b/zig/src/cuda/qmmf.zig @@ -103,15 +103,15 @@ fn symbol( } /// The 16-row tile at 32 columns a block (MXFP8 and BF16): plain, then with a cluster. -fn halfSymbol(comptime mode: Mode, comptime cluster: bool, comptime wide: bool) [:0]const u8 { +pub fn halfSymbol(comptime mode: Mode, comptime cluster: bool, comptime wide: bool) [:0]const u8 { const name = "_ZN7tf_qmmf11qmmf_kernelILi{d}ELi16ELi32ELi1ELi4ELi4ELb{d}ELb{d}ELb0EEEvPK13__nv_bfloat16PKhS5_fPvPfiiiiiii"; return std.fmt.comptimePrint(name, .{ @backingInt(mode), @intFromBool(wide), @intFromBool(cluster) }); } /// Dynamic shared bytes of the half tile: a stage holds half the weights (and scales) of the 64-column tile's. pub fn halfShared(mode: Mode) u32 { - const w: u32 = if (mode == .bf16) 32 * group * 2 else 32 * group; - const s: u32 = if (mode == .mxfp8) 32 * 2 else 0; + const w: u32 = if (mode == .bf16) 32 * group * 2 else if (mode == .fp4) 32 * group / 2 else 32 * group; + const s: u32 = if (mode == .mxfp8) 32 * 2 else if (mode == .fp4 or mode == .fp8g) 32 * 4 else 0; const stage = (16 * group * 2 + w + s + 127) / 128 * 128; const partials = 1 * 1 * 4 * threads * 4; return @max(4 * stage, partials); @@ -183,6 +183,7 @@ pub const Lane = struct { f32_fns: [modes.len][7]Function, reduce: [2]Function, // by Out half: [2][2][2]Function, // by halfModeIndex, Out, then plain / cluster + half_n: ?@import("qmmf_half.zig").Set = null, // TF_QMMF_HALF_BN: FP4, FP8 and FP8G half tiles too half_below: usize = half_below_default, shared_down: [4]Function = undefined, /// Output columns from which this lane fuses a split-K cluster call; 0 keeps its original schedule. @@ -226,6 +227,7 @@ pub const Lane = struct { l.fuse_s[mi][oi][bi] = f; }; l.half_below = try halfBelow(); + try @import("qmmf_half.zig").apply(&l, d); return l; } @@ -295,8 +297,9 @@ pub const Lane = struct { const hm = halfModeIndex(w.mode); // fuse_split_n: a cluster call this wide on the fused form (row tile 64: the fused instance), one block a tile const fs = l.fuse_split_n != 0 and p.cluster and w.n >= l.fuse_split_n and hm != null; - const half = hm != null and p.bm == 16 and !p.fused and !fs and rows_t * ((w.n + bn - 1) / bn) * p.sk < l.half_below; - const f = if (k32) l.prompt_k32.?[@backingInt(out)] else if (prompt) l.prompt.?[@backingInt(out)][@intFromBool(p.fused)] else if (half) l.half[hm.?][@backingInt(out)][@intFromBool(p.cluster)] else if (fs) (if (p.bm == 64) set[6] else l.fuse_s[hm.?][@backingInt(out)][@intFromBool(p.bm == 32)]) else if (p.fused) set[6] else set[ti * 2 + @intFromBool(p.cluster)]; + const hn = if (l.half_n != null) @import("qmmf_half.zig").index(w.mode) else null; + const half = (hm != null or hn != null) and p.bm == 16 and !p.fused and !fs and rows_t * ((w.n + bn - 1) / bn) * p.sk < l.half_below; + const f = if (k32) l.prompt_k32.?[@backingInt(out)] else if (prompt) l.prompt.?[@backingInt(out)][@intFromBool(p.fused)] else if (half) (if (hm) |i| l.half[i] else l.half_n.?[hn.?])[@backingInt(out)][@intFromBool(p.cluster)] else if (fs) (if (p.bm == 64) set[6] else l.fuse_s[hm.?][@backingInt(out)][@intFromBool(p.bm == 32)]) else if (p.fused) set[6] else set[ti * 2 + @intFromBool(p.cluster)]; const cols: usize = if (prompt) 128 else if (half) 32 else bn; const band = @max(1, @min(rows_t, (12 << 20) / (bm * w.k * 2))); var args: launch_.Args = .{}; diff --git a/zig/src/cuda/qmmf_group.zig b/zig/src/cuda/qmmf_group.zig new file mode 100644 index 00000000000..65cc9a4603d --- /dev/null +++ b/zig/src/cuda/qmmf_group.zig @@ -0,0 +1,165 @@ +//! Same-input lane projections in one qmmf launch, each keeping its own tile, K slices and cluster sum (qmmf.cu). +const std = @import("std"); +const q = @import("qmmf.zig"); +const launch_ = @import("launch.zig"); +const Function = @import("module.zig").Function; +const Stream = @import("stream.zig").Stream; + +/// Projections a launch takes, and the decode rows (one 16-row tile) it serves. +pub const most = 4; +pub const max_rows = 16; + +/// qmmf.cu GroupSeg: one projection's weights, output, scale, shape, K slices and first block. +pub const Seg = extern struct { w: u64 = 0, bs: u64 = 0, out: u64 = 0, scale: f32 = 0, n: i32 = 0, sk: i32 = 1, npad: i32 = 0, first: i32 = 0, tiles: i32 = 0 }; +pub const Segs = extern struct { s: [most]Seg = @splat(.{}), count: i32 = 0, pad: i32 = 0 }; + +comptime { + std.debug.assert(@sizeOf(Seg) == 48 and @sizeOf(Segs) == 200); +} + +/// The instance a group takes: its mode and column tile (64, or the 32-column half tile). +pub const Kind = enum { fp4, fp8, bf16, bf16_half }; +const kinds = [4]Kind{ .fp4, .fp8, .bf16, .bf16_half }; + +const symbols = [4][2][:0]const u8{ + .{ "tf_qmmf_group_fp4", "tf_qmmf_group_fp4_c" }, + .{ "tf_qmmf_group_fp8", "tf_qmmf_group_fp8_c" }, + .{ "tf_qmmf_group_bf16", "tf_qmmf_group_bf16_c" }, + .{ "tf_qmmf_group_bf16_half", "tf_qmmf_group_bf16_half_c" }, +}; + +fn shared(kind: Kind) u32 { + return switch (kind) { + .fp4 => q.sharedBytes(.fp4, 16), + .fp8 => q.sharedBytes(.fp8, 16), + .bf16 => q.sharedBytes(.bf16, 16), + .bf16_half => q.halfShared(.bf16), + }; +} + +/// One grouped launch: its instance, cluster width (the widest K split), blocks and projections. +pub const Shape = struct { kind: Kind, cluster: u32, blocks: u32, segs: Segs }; + +/// The grouped launch of `ws` into `outs` over `m` rows, or null where any projection's own launch differs in form. +pub fn plan(l: q.Lane, ws: []const q.Weight, outs: []const u64, m: usize) ?Shape { + if (ws.len < 2 or ws.len > most or ws.len != outs.len or m == 0 or m > max_rows) return null; + if (!l.clusters or l.fuse_split_n != 0) return null; // pre-sm_90 slices meet in reduce_kernel; fused calls differ + const mode = ws[0].mode; + if (mode != .fp4 and mode != .fp8 and mode != .bf16) return null; + var half: ?bool = null; + var widest: u32 = 1; + for (ws, 0..) |w, i| { + if (w.mode != mode or w.k != ws[0].k or w.k % q.group != 0 or w.n == 0) return null; + for (outs[i + 1 ..]) |o| if (o == outs[i]) return null; + const p = q.planFor(m, w, l.clusters); + if (p.bm != 16 or p.fused or p.reduce or p.cluster != (p.sk > 1) or l.usesPrompt(m, w)) return null; + // matmulOut's own choice: half tiles for small BF16 grids + const h = q.halfModeIndex(w.mode) != null and ((w.n + 63) / 64) * p.sk < l.half_below; + if (half) |prev| if (prev != h) return null; + half = h; + widest = @max(widest, p.sk); + } + const cols: u32 = if (half.?) 32 else 64; + var segs: Segs = .{ .count = @intCast(ws.len) }; + var first: u32 = 0; + for (ws, outs, 0..) |w, o, i| { + const sk = q.slices(w); + const tiles = (w.n + cols - 1) / cols; + segs.s[i] = .{ .w = w.codes, .bs = w.scales, .out = o, .scale = w.scale, .n = @intCast(w.n), .sk = @intCast(sk), .npad = @intCast(w.npad), .first = @intCast(first), .tiles = @intCast(tiles) }; + first += (tiles * sk + widest - 1) / widest * widest; // a cluster never spans two projections + } + const kind: Kind = switch (mode) { + .fp4 => .fp4, + .fp8 => .fp8, + else => if (half.?) .bf16_half else .bf16, + }; + return .{ .kind = kind, .cluster = widest, .blocks = first, .segs = segs }; +} + +/// The grouped instances, from the lane's module. +pub const Group = struct { + fns: [4][2]Function, + + pub fn load(l: *const q.Lane) !Group { + var g: Group = undefined; + for (symbols, &g.fns, kinds) |pair, *fs, kind| for (pair, fs) |name, *f| { + f.* = try l.mod.function(name); + try f.allowDynamicShared(shared(kind)); + }; + return g; + } + + /// The planned launch over x [m, k] bf16 (rows k apart); `pdl` as the lane's. + pub fn launch(g: Group, s: Stream, x: u64, m: usize, k: usize, sh: Shape, pdl: bool) !void { + var args: launch_.Args = .{}; + args.add(x); + args.add(sh.segs); + args.add(@as(i32, @intCast(m))); + args.add(@as(i32, @intCast(k))); + try launch_.launch(g.fns[std.mem.indexOfScalar(Kind, &kinds, sh.kind).?][@intFromBool(sh.cluster > 1)], .{ + .grid = .{ .x = sh.blocks }, + .block = .{ .x = 128 }, + .shared = shared(sh.kind), + .cluster = if (sh.cluster > 1) .{ .x = sh.cluster, .y = 1, .z = 1 } else null, + .pdl = pdl, + }, s, &args); + } +}; + +fn testLane(clusters: bool) q.Lane { + return .{ .mod = undefined, .fns = undefined, .f32_fns = undefined, .reduce = undefined, .half = undefined, .clusters = clusters }; +} + +fn weight(mode: q.Mode, n: u32, k: u32) q.Weight { + return .{ .mode = mode, .codes = 0x1000 * @as(u64, n), .scales = 0, .scale = 0.5, .n = n, .k = k, .npad = (n + 127) / 128 * 128 }; +} + +test "grouped projections: the served Qwen3.8-27B groups keep each projection's slices, tiles and blocks" { + const t = std.testing; + const l = testLane(true); + const outs = [_]u64{ 0x10, 0x20, 0x30, 0x40 }; + for (1..max_rows + 1) |m| { + // MLP gate + up, NVFP4: one slice each, 272 + 272 blocks, no cluster + const mlp = plan(l, &.{ weight(.fp4, 17408, 5120), weight(.fp4, 17408, 5120) }, outs[0..2], m).?; + try t.expect(mlp.kind == .fp4 and mlp.cluster == 1 and mlp.blocks == 544 and mlp.segs.s[1].first == 272); + // GDN qkv + z, FP8: two slices each, 320 + 192 blocks in clusters of 2 + const gdn = plan(l, &.{ weight(.fp8, 10240, 5120), weight(.fp8, 6144, 5120) }, outs[0..2], m).?; + try t.expect(gdn.kind == .fp8 and gdn.cluster == 2 and gdn.blocks == 512 and gdn.segs.s[1].sk == 2); + // GDN a + b, BF16 heads: half tiles as their own launches, 8 slices, 16 + 16 blocks + const ab = plan(l, &.{ weight(.bf16, 48, 5120), weight(.bf16, 48, 5120) }, outs[0..2], m).?; + try t.expect(ab.kind == .bf16_half and ab.cluster == 8 and ab.blocks == 32 and ab.segs.s[0].tiles == 2); + // attention q + k + v, FP8: q one slice (192 blocks), k and v 8 slices (128 each); clusters of 8 by projection + const qkv = plan(l, &.{ weight(.fp8, 12288, 5120), weight(.fp8, 1024, 5120), weight(.fp8, 1024, 5120) }, outs[0..3], m).?; + try t.expect(qkv.cluster == 8 and qkv.blocks == 448 and qkv.segs.count == 3); + try t.expectEqual(@as(i32, 1), qkv.segs.s[0].sk); + try t.expectEqual(@as(i32, 8), qkv.segs.s[2].sk); + try t.expectEqual(@as(i32, 320), qkv.segs.s[2].first); + } + // 193 one-slice tiles round up to 200 blocks so the 8-slice projection's clusters start on a cluster + const pad = plan(l, &.{ weight(.fp4, 12352, 4096), weight(.fp4, 200, 4096) }, outs[0..2], 3).?; + try t.expect(pad.cluster == 8 and pad.segs.s[0].tiles == 193 and pad.segs.s[1].first == 200 and pad.blocks == 232); +} + +test "grouped projections refuse what their own launches would run another way" { + const t = std.testing; + const l = testLane(true); + const outs = [_]u64{ 0x10, 0x20, 0x30, 0x40, 0x50 }; + const gate = weight(.fp4, 17408, 5120); + try t.expect(plan(l, &.{ gate, gate }, outs[0..2], 17) == null); // a 32-row tile + try t.expect(plan(l, &.{ gate, gate }, outs[0..2], 0) == null); + try t.expect(plan(l, &.{gate}, outs[0..1], 1) == null); + try t.expect(plan(l, &.{ gate, gate, gate, gate, gate }, outs[0..5], 1) == null); + try t.expect(plan(l, &.{ gate, gate }, &.{ 0x10, 0x10 }, 1) == null); // one output twice + try t.expect(plan(l, &.{ gate, weight(.fp8, 17408, 5120) }, outs[0..2], 1) == null); // two modes + try t.expect(plan(l, &.{ gate, weight(.fp4, 17408, 4096) }, outs[0..2], 1) == null); // two inputs' widths + try t.expect(plan(l, &.{ weight(.fp8g, 1024, 5120), weight(.fp8g, 1024, 5120) }, outs[0..2], 1) == null); + try t.expect(plan(testLane(false), &.{ gate, gate }, outs[0..2], 1) == null); // slices meet in reduce_kernel + var fused = testLane(true); + fused.fuse_split_n = 1; + try t.expect(plan(fused, &.{ gate, gate }, outs[0..2], 1) == null); + // BF16: a half-tile projection and a 64-column one are two instances + try t.expect(plan(l, &.{ weight(.bf16, 48, 5120), weight(.bf16, 12288, 5120) }, outs[0..2], 1) == null); + var no_half = testLane(true); + no_half.half_below = 0; + try t.expect(plan(no_half, &.{ weight(.bf16, 48, 5120), weight(.bf16, 48, 5120) }, outs[0..2], 1).?.kind == .bf16); +} diff --git a/zig/src/cuda/qmmf_half.zig b/zig/src/cuda/qmmf_half.zig new file mode 100644 index 00000000000..8b09a8df945 --- /dev/null +++ b/zig/src/cuda/qmmf_half.zig @@ -0,0 +1,116 @@ +//! TF_QMMF_HALF_BN=1: 32-column half tiles for FP4, FP8 and FP8G too, below two blocks an SM by default (opt-in). +const std = @import("std"); +const q = @import("qmmf.zig"); +const abi = @import("abi.zig"); +const Driver = @import("driver.zig").Driver; +const Function = @import("module.zig").Function; + +/// The formats this adds; MXFP8 and BF16 keep their own half tiles (Lane.half). +pub const modes = [_]q.Mode{ .fp4, .fp8, .fp8g }; + +/// Per added format, Out, then plain / cluster. +pub const Set = [modes.len][2][2]Function; + +pub fn index(mode: q.Mode) ?usize { + return std.mem.indexOfScalar(q.Mode, &modes, mode); +} + +/// The switch; default off, which leaves every lane's tiles and threshold as before. +pub fn on() !bool { + return @import("sys").environment.read(bool, "TF_QMMF_HALF_BN", false); +} + +/// The block count below which a 16-row call halves its tiles: TF_QMMF_HALF_BELOW when set, else two blocks an SM. +pub fn below(sms: usize) !usize { + return @import("sys").environment.read(usize, "TF_QMMF_HALF_BELOW", 2 * sms); +} + +/// The added instances from the lane's module. +pub fn load(l: *const q.Lane) !Set { + var set: Set = undefined; + inline for (modes, 0..) |mode, mi| inline for (.{ false, true }, 0..) |wide, oi| inline for (.{ false, true }, 0..) |cl, ci| { + const f = try l.mod.function(q.halfSymbol(mode, cl, wide)); + try f.allowDynamicShared(q.halfShared(mode)); + set[mi][oi][ci] = f; + }; + return set; +} + +/// With the switch on: the added instances, and the threshold from the current device's SM count. +pub fn apply(l: *q.Lane, d: *const Driver) !void { + if (!try on()) return; + const set = try load(l); + var dev: abi.Device = 0; + try d.check(d.api.cuCtxGetDevice(&dev), "cuCtxGetDevice"); + var sms: c_int = 0; + try d.check(d.api.cuDeviceGetAttribute(&sms, .multiprocessor_count, dev), "cuDeviceGetAttribute"); + l.half_n = set; + l.half_below = try below(@intCast(@max(sms, 1))); +} + +test "half tiles for FP4, FP8 and FP8G: qmmf.cu's names and shared bytes, and the 16-row calls that take them" { + const t = std.testing; + try t.expectEqualStrings("_ZN7tf_qmmf11qmmf_kernelILi0ELi16ELi32ELi1ELi4ELi4ELb0ELb0ELb0EEEvPK13__nv_bfloat16PKhS5_fPvPfiiiiiii", q.halfSymbol(.fp4, false, false)); + try t.expectEqualStrings("_ZN7tf_qmmf11qmmf_kernelILi3ELi16ELi32ELi1ELi4ELi4ELb1ELb1ELb0EEEvPK13__nv_bfloat16PKhS5_fPvPfiiiiiii", q.halfSymbol(.fp8g, true, true)); + // Tile::SMEM: four stages of x (2048), half the weights and half the scales + try t.expectEqual(@as(u32, 12800), q.halfShared(.fp4)); // 2048 + 1024 + 128 + try t.expectEqual(@as(u32, 16384), q.halfShared(.fp8)); // 2048 + 2048 + try t.expectEqual(@as(u32, 16896), q.halfShared(.fp8g)); // 2048 + 2048 + 128 + try t.expectEqual(@as(u32, 16896), q.halfShared(.mxfp8)); // unchanged: 2048 + 2048 + 64 + try t.expectEqual(@as(u32, 24576), q.halfShared(.bf16)); // unchanged + try t.expectEqual(@as(?usize, 0), index(.fp4)); + try t.expectEqual(@as(?usize, 2), index(.fp8g)); + try t.expectEqual(@as(?usize, null), index(.mxfp8)); + try t.expectEqual(@as(?usize, null), index(.bf16)); + + const Mock = struct { + var id: usize = 0; + var grid: c_uint = 0; + var smem: u32 = 0; + fn run(f: abi.Function, gx: c_uint, _: c_uint, _: c_uint, _: c_uint, _: c_uint, _: c_uint, sm: c_uint, _: abi.Stream, _: ?[*]?*anyopaque, _: ?[*]?*anyopaque) callconv(.c) abi.Result { + id = @intFromPtr(f.?); + grid = gx; + smem = sm; + return 0; + } + }; + var d: Driver = undefined; + d.api.cuLaunchKernel = Mock.run; + var l: q.Lane = undefined; + l.clusters = true; + l.pdl = false; + l.fuse_split_n = 0; + l.prompt = null; + l.half_n = null; + l.half_below = 340; // two blocks an SM on 170 SMs + for (&l.fns, 0..) |*set, mi| for (set, 0..) |*f, i| { + f.* = .{ .d = &d, .handle = @ptrFromInt(1000 + 10 * mi + i) }; + }; + var added: Set = undefined; + for (&added, 0..) |*a, mi| for (a, 0..) |*o, oi| for (o, 0..) |*f, ci| { + f.* = .{ .d = &d, .handle = @ptrFromInt(2000 + 100 * mi + 10 * oi + ci) }; + }; + const s: @import("stream.zig").Stream = .{ .d = &d, .handle = null }; + // one K slice (8 groups), 16 column tiles: the plain launch, so cuLaunchKernel + for ([_]q.Mode{ .fp4, .fp8, .fp8g }, 0..) |mode, mi| for ([_]usize{ 1, 16 }) |rows| { + const w: q.Weight = .{ .mode = mode, .codes = 1, .scales = 2, .n = 1024, .k = 512, .npad = 1024 }; + l.half_n = null; // off: the 64-column 16-row tile, as before + try l.matmul(s, 3, 512, rows, w, 4, 0); + try t.expectEqual(1000 + 10 * @as(usize, @backingInt(mode)), Mock.id); + try t.expectEqual(@as(c_uint, 16), Mock.grid); + try t.expectEqual(q.sharedBytes(mode, 16), Mock.smem); + l.half_n = added; // on: the half tile, twice the blocks + try l.matmul(s, 3, 512, rows, w, 4, 0); + try t.expectEqual(2000 + 100 * mi, Mock.id); + try t.expectEqual(@as(c_uint, 32), Mock.grid); + try t.expectEqual(q.halfShared(mode), Mock.smem); + // 17 rows take the 32-row tile either way; a grid at the threshold stays on 64 columns + try l.matmul(s, 3, 512, 17, w, 4, 0); + try t.expectEqual(1000 + 10 * @as(usize, @backingInt(mode)) + 2, Mock.id); + var wide = w; + wide.n = 340 * 64; + wide.npad = 340 * 64; + try l.matmul(s, 3, 512, rows, wide, 4, 0); + try t.expectEqual(1000 + 10 * @as(usize, @backingInt(mode)), Mock.id); + }; +} diff --git a/zig/src/cuda/rendezvous.zig b/zig/src/cuda/rendezvous.zig new file mode 100644 index 00000000000..e9da6b15d21 --- /dev/null +++ b/zig/src/cuda/rendezvous.zig @@ -0,0 +1,58 @@ +//! NCCL's root for a family over hosts: --master and --master-port become NCCL_COMM_ID when it is unset. +const std = @import("std"); +const env = @import("sys").env; + +/// NCCL's root from --master and --master-port when NCCL_COMM_ID is unset; first in `open`, before the liveness line. +pub fn fromMaster(o: anytype, lookup: anytype, out: anytype) !void { + if (o.tp <= 1) return; + const master = o.master orelse return; // without --master, NCCL_COMM_ID stays required as today (NoCommId) + var buf: [320]u8 = undefined; + const want = std.fmt.bufPrintSentinel(&buf, "{s}:{d}", .{ master, o.master_port }, 0) catch return error.MasterTooLong; + if (lookup.get("NCCL_COMM_ID")) |have| { + if (!std.mem.eql(u8, have, want)) return error.RendezvousDisagree; + return; + } + out.put("NCCL_COMM_ID", want); +} + +/// The process environment, for `rendezvous` outside tests: NCCL's own variable, the only one it reads. +pub const Process = struct { + pub fn get(_: Process, _: [:0]const u8) ?[]const u8 { + return if (std.c.getenv("NCCL_COMM_ID")) |v| std.mem.span(v) else null; + } + pub fn put(_: Process, name: [:0]const u8, value: [:0]const u8) void { + _ = env.setenv(name, value, 1); + } +}; + +test "the rendezvous sets NCCL_COMM_ID from --master once, keeps an equal one, refuses a different one" { + const Fake = struct { + have: ?[]const u8 = null, + set: ?[]const u8 = null, + buf: [64]u8 = undefined, + pub fn get(f: *@This(), _: [:0]const u8) ?[]const u8 { + return f.have; + } + pub fn put(f: *@This(), _: [:0]const u8, v: [:0]const u8) void { + @memcpy(f.buf[0..v.len], v); + f.set = f.buf[0..v.len]; + } + }; + const O = struct { tp: u32, master: ?[]const u8, master_port: u16 }; + var f: Fake = .{}; + try fromMaster(O{ .tp = 2, .master = "192.0.2.7", .master_port = 29583 }, &f, &f); + try std.testing.expectEqualStrings("192.0.2.7:29583", f.set.?); + f = .{ .have = "192.0.2.7:29583" }; + try fromMaster(O{ .tp = 2, .master = "192.0.2.7", .master_port = 29583 }, &f, &f); + try std.testing.expect(f.set == null); + f = .{ .have = "192.0.2.8:29583" }; + try std.testing.expectError(error.RendezvousDisagree, fromMaster(O{ .tp = 2, .master = "192.0.2.7", .master_port = 29583 }, &f, &f)); + f = .{}; + var long: [400]u8 = undefined; + @memset(&long, 'h'); + try std.testing.expectError(error.MasterTooLong, fromMaster(O{ .tp = 2, .master = &long, .master_port = 29583 }, &f, &f)); + f = .{}; + try fromMaster(O{ .tp = 1, .master = "192.0.2.7", .master_port = 29583 }, &f, &f); + try fromMaster(O{ .tp = 2, .master = null, .master_port = 29583 }, &f, &f); + try std.testing.expect(f.set == null); +} diff --git a/zig/src/cuda/root.zig b/zig/src/cuda/root.zig index b5cddb21199..a00354ee677 100644 --- a/zig/src/cuda/root.zig +++ b/zig/src/cuda/root.zig @@ -37,6 +37,8 @@ pub const aot = @import("aot.zig"); pub const kernels = @import("kernels.zig"); pub const qmmf_shared = @import("qmmf_shared.zig"); pub const qmmf = @import("qmmf.zig"); +pub const qmmf_group = @import("qmmf_group.zig"); +pub const qmmf_half = @import("qmmf_half.zig"); pub const fp8 = @import("fp8.zig"); pub const mxfp8 = @import("mxfp8.zig"); pub const exlr8 = @import("exlr8.zig"); @@ -65,6 +67,7 @@ pub const rank_scatter = @import("rank_scatter.zig"); pub const relay_plan = @import("relay_plan.zig"); pub const tp_group = @import("tp_group.zig"); pub const tp_watch = @import("tp_watch.zig"); +pub const rendezvous = @import("rendezvous.zig"); pub const startup_log = @import("startup_log.zig"); pub const startup_watch = @import("startup_watch.zig"); pub const p2p_report = @import("p2p_report.zig"); @@ -132,6 +135,8 @@ test { _ = segments; _ = @import("qmmf.zig"); _ = @import("qmmf_shared.zig"); + _ = @import("qmmf_group.zig"); + _ = @import("qmmf_half.zig"); _ = @import("fp8.zig"); _ = @import("mxfp8.zig"); _ = carveout; @@ -143,6 +148,7 @@ test { _ = @import("modelopt.zig"); _ = @import("ck.zig"); _ = @import("tp_watch.zig"); + _ = @import("rendezvous.zig"); _ = @import("shared_test.zig"); _ = @import("tree_attention.zig"); _ = @import("block_attention.zig"); diff --git a/zig/src/cuda_dense/native.zig b/zig/src/cuda_dense/native.zig index b59d1118404..a2c3d09bc5e 100644 --- a/zig/src/cuda_dense/native.zig +++ b/zig/src/cuda_dense/native.zig @@ -111,8 +111,9 @@ fn WithTower(comptime R: type, comptime T: type) type { return C.loaded(Loaded, try C.open(gpa, io, ctx, dir, kernels, o)); } - /// The tower's device bytes beside the text weights: its weights, its largest image's scratch, its workspace. - pub fn visionBytes(a: std.mem.Allocator, io: std.Io, dir: []const u8) !u64 { + /// The tower's device bytes on rank 0, which holds it: its weights, its largest image's scratch, its workspace. + pub fn visionBytes(a: std.mem.Allocator, io: std.Io, dir: []const u8, rank: u32, _: u32) !u64 { + if (rank != 0) return 0; return try T.weightBytes(a, io, dir) + try T.openBytes(a, io, dir); } diff --git a/zig/src/cuda_dense/native_test.zig b/zig/src/cuda_dense/native_test.zig index 7922cc29728..44315a31df9 100644 --- a/zig/src/cuda_dense/native_test.zig +++ b/zig/src/cuda_dense/native_test.zig @@ -55,7 +55,7 @@ test "a recipe with a tower adds exactly the vision decls and fields the host re inline for (.{ "precision", "kv8", "prompt_int8", "loops", "rank", "drafter" }) |f| try std.testing.expect(!@hasField(V.Options, f)); inline for (.{ "layout", "engine_paged", "free_streams", "target" }) |f| try std.testing.expect(@hasField(V.Loaded, f)); try std.testing.expect(!@hasDecl(N, "default_image_tokens") and !@hasDecl(N, "visionBytes") and !@hasField(N.Loaded, "vision")); - try std.testing.expectEqual(@as(u64, (5 << 20) + (3 << 16)), try V.visionBytes(std.testing.allocator, std.testing.io, "")); + try std.testing.expectEqual(@as(u64, (5 << 20) + (3 << 16)), try V.visionBytes(std.testing.allocator, std.testing.io, "", 0, 1)); try std.testing.expectEqual(@as(?u64, 1 << 20), try V.textWeightBytes(std.testing.allocator, std.testing.io, "")); } diff --git a/zig/src/cuda_dense/offer_test.zig b/zig/src/cuda_dense/offer_test.zig index 2c3be00f121..243933005a6 100644 --- a/zig/src/cuda_dense/offer_test.zig +++ b/zig/src/cuda_dense/offer_test.zig @@ -47,7 +47,8 @@ test "the host counts the tower's bytes with --vision on rank 0, none without it const a = t.allocator; const io = t.io; const with: api.Open = .{ .dir = "", .model_type = "tiny_dense", .vision = .{} }; - try t.expectEqual(try V.visionBytes(a, io, ""), try offer.weightBytes(V, a, io, with)); + try t.expectEqual(try V.visionBytes(a, io, "", 0, 1), try offer.weightBytes(V, a, io, with)); + try t.expectEqual(@as(u64, 0), try V.visionBytes(a, io, "", 1, 2)); // another rank holds no tower try t.expectEqual(@as(u64, 0), try offer.weightBytes(V, a, io, .{ .dir = "", .model_type = "tiny_dense" })); try t.expectEqual(@as(u64, 0), try offer.weightBytes(N, a, io, with)); } diff --git a/zig/src/families/dots_mocr/cuda_tower_test.zig b/zig/src/families/dots_mocr/cuda_tower_test.zig index ac5ece4eafa..0b628990ffc 100644 --- a/zig/src/families/dots_mocr/cuda_tower_test.zig +++ b/zig/src/families/dots_mocr/cuda_tower_test.zig @@ -65,7 +65,7 @@ test "dots tower bytes: weights 2,524,194,816 on the device, the scratch and wor const open = 57600 * 39592 + 256 + (32 << 20); try t.expectEqual(@as(u64, 2_314_053_888), open); try t.expectEqual(@as(u64, open), try Tower.openBytes(a, io, d.path)); - try t.expectEqual(@as(u64, 2_524_194_816 + open), try native.visionBytes(a, io, d.path)); + try t.expectEqual(@as(u64, 2_524_194_816 + open), try native.visionBytes(a, io, d.path, 0, 1)); var bare = try Dir.init(false, null); // no shards: nothing to count defer bare.deinit(); try t.expectError(error.FileNotFound, Tower.weightBytes(a, io, bare.path)); diff --git a/zig/src/families/drama3/replay.zig b/zig/src/families/drama3/replay.zig index 44520d9885f..99057ee8da6 100644 --- a/zig/src/families/drama3/replay.zig +++ b/zig/src/families/drama3/replay.zig @@ -29,6 +29,21 @@ pub fn Replay(comptime d3: type) type { if (!std.mem.eql(u8, a, b)) return error.ReplayMismatch; } + /// A codec chunk's PCM against chunk 1's, kept while the exact checks run on. + const PcmDiff = struct { chunk: usize, max_abs: f64, rms: f64 }; + + fn pcmDiff(chunk: usize, want: []const f32, got: []const f32) ?PcmDiff { + if (std.mem.eql(u8, std.mem.sliceAsBytes(want), std.mem.sliceAsBytes(got))) return null; + var max_abs: f64 = 0; + var sum: f64 = 0; + for (want, got) |w, g| { + const d: f64 = w - g; + max_abs = @max(max_abs, @abs(d)); + sum += d * d; + } + return .{ .chunk = chunk, .max_abs = max_abs, .rms = @sqrt(sum / @as(f64, @floatFromInt(want.len))) }; + } + fn audio(t: *d3.tts.Tts, out: []f32, n: usize, chunk: usize, report: bool) !void { try reset(t); var sink: Audio = .{ .out = out }; @@ -51,7 +66,7 @@ pub fn Replay(comptime d3: type) type { std.debug.print("codec requested {d}, actual sizes {any}\n", .{ chunk, sink.sizes[0..sink.calls] }); } - /// Fails on the first mismatch; ``report`` prints each chunk's codec sizes and the pass line (CLI receipt). + /// Exact checks fail first; a chunk 4/16 PCM difference alone is ReplayPcmOnly. ``report``: the CLI receipt. pub fn verify( gpa: std.mem.Allocator, io: std.Io, @@ -76,9 +91,12 @@ pub fn Replay(comptime d3: type) type { const replay = try e.generate(io, rows, smp, 17, true, 1); defer gpa.free(replay.frames); try equal(std.mem.sliceAsBytes(baseline.frames), std.mem.sliceAsBytes(replay.frames)); - for ([_]usize{ 1, 4, 16 }) |chunk| { + try audio(t, other, replay.frames.len, 1, report); + try equal(std.mem.sliceAsBytes(pcm), std.mem.sliceAsBytes(other)); + var diffs: [2]?PcmDiff = undefined; + for ([_]usize{ 4, 16 }, &diffs) |chunk, *diff| { try audio(t, other, replay.frames.len, chunk, report); - try equal(std.mem.sliceAsBytes(pcm), std.mem.sliceAsBytes(other)); + diff.* = pcmDiff(chunk, pcm, other); } const second = try e.fork(); defer second.destroy(); @@ -96,6 +114,13 @@ pub fn Replay(comptime d3: type) type { } try audio(second_tts, other, baseline.frames.len, 1, report); try equal(std.mem.sliceAsBytes(pcm), std.mem.sliceAsBytes(other)); + var pcm_only = false; + for (diffs) |diff| if (diff) |d| { + pcm_only = true; + if (report) std.debug.print("Drama replay PCM only: codec chunk {d} against 1, max abs {e:.3}, RMS {e:.3}; every exact check passed\n", .{ d.chunk, d.max_abs, d.rms }); + if (!(d.max_abs <= 1.0 / 32768.0)) return error.ReplayPcmBound; + }; + if (pcm_only) return error.ReplayPcmOnly; if (!report) return; std.debug.print("Drama replay passed: eager/graphs, poison/reset, codec chunks and interleaved state\n", .{}); } diff --git a/zig/src/families/drama3/replay_test.zig b/zig/src/families/drama3/replay_test.zig index 1a8e59c8ceb..194a5957241 100644 --- a/zig/src/families/drama3/replay_test.zig +++ b/zig/src/families/drama3/replay_test.zig @@ -9,6 +9,8 @@ const Fake = struct { pub const Engine = struct { a: std.mem.Allocator, forced: usize = 17, + frame: i32 = 1, + fork_frame: i32 = 1, frames_out: u64 = 0, c: struct { ids: struct { eos: i32 = -1 } = .{} } = .{}, pub fn generate(e: *@This(), _: std.Io, _: []const model.Frame, _: Sampling, limit: usize, _: bool, _: usize) !struct { frames: []model.Frame } { @@ -22,6 +24,7 @@ const Fake = struct { pub fn fork(e: *@This()) !*@This() { const f = try e.a.create(@This()); f.* = e.*; + f.frame = e.fork_frame; return f; } pub fn destroy(e: *@This()) void { @@ -29,8 +32,8 @@ const Fake = struct { } pub fn prefill(_: *@This(), _: []const model.Frame, _: ?*anyopaque) !void {} pub fn frameStep(_: *@This(), _: Sampling, _: bool, _: ?*anyopaque) !void {} - pub fn download(_: *@This(), _: u64, out: []u8) !void { - const f: model.Frame = @splat(1); + pub fn download(e: *@This(), _: u64, out: []u8) !void { + const f: model.Frame = @splat(e.frame); @memcpy(out, std.mem.asBytes(&f)); } }; @@ -45,14 +48,17 @@ const Fake = struct { max_chunk: usize = 16, saw16: bool = false, saw_tail: bool = false, + /// A four- or sixteen-frame decode's sample; chunk 1 decodes write 0. + pcm4: f32 = 0, + pcm16: f32 = 0, pub fn flush(t: *@This(), from: usize, to: usize, sink: anytype) !void { - const zero: [16 * 2048]f32 = @splat(0); var at = from; while (at < to) { const n = @min(t.max_chunk, to - at); t.saw16 = t.saw16 or n == 16; t.saw_tail = t.saw_tail or (from == 16 and n == 1); - try sink.audio(sink.ctx, zero[0 .. n * 2048]); + const pcm: [16 * 2048]f32 = @splat(if (n == 16) t.pcm16 else if (n == 4) t.pcm4 else 0); + try sink.audio(sink.ctx, pcm[0 .. n * 2048]); at += n; } } @@ -83,3 +89,24 @@ test "drama replay: actually decodes a sixteen-frame chunk and its one-frame tai try Replay.verify(e.a, std.testing.io, &e, &t, &.{}, .{}, false); try std.testing.expect(t.saw16 and t.saw_tail); } +test "drama replay: a codec chunk 16 PCM difference is PCM-only once every exact check passed" { + var e: Fake.Engine = .{ .a = std.testing.allocator }; + var t: Fake.tts.Tts = .{ .a = std.testing.allocator, .pcm16 = 1.0 / 32768.0 }; + try std.testing.expectError(error.ReplayPcmOnly, Replay.verify(e.a, std.testing.io, &e, &t, &.{}, .{}, false)); +} +test "drama replay: an over-limit chunk 4 PCM difference fails despite in-bound chunk 16" { + var e: Fake.Engine = .{ .a = std.testing.allocator }; + var t: Fake.tts.Tts = .{ .a = std.testing.allocator, .pcm4 = 0.25, .pcm16 = 1.0 / 32768.0 }; + try std.testing.expectError(error.ReplayPcmBound, Replay.verify(e.a, std.testing.io, &e, &t, &.{}, .{}, false)); +} + +test "drama replay: an over-limit chunk 16 PCM difference fails" { + var e: Fake.Engine = .{ .a = std.testing.allocator }; + var t: Fake.tts.Tts = .{ .a = std.testing.allocator, .pcm16 = 0.25 }; + try std.testing.expectError(error.ReplayPcmBound, Replay.verify(e.a, std.testing.io, &e, &t, &.{}, .{}, false)); +} +test "drama replay: a forked frame mismatch fails behind a codec chunk 16 PCM difference" { + var e: Fake.Engine = .{ .a = std.testing.allocator, .fork_frame = 2 }; + var t: Fake.tts.Tts = .{ .a = std.testing.allocator, .pcm16 = 0.25 }; + try std.testing.expectError(error.ReplayMismatch, Replay.verify(e.a, std.testing.io, &e, &t, &.{}, .{}, false)); +} diff --git a/zig/src/families/flashnext/batch_forward.zig b/zig/src/families/flashnext/batch_forward.zig index 58731b1e82f..9593a71e46c 100644 --- a/zig/src/families/flashnext/batch_forward.zig +++ b/zig/src/families/flashnext/batch_forward.zig @@ -3,6 +3,7 @@ const std = @import("std"); const mtl = @import("metal"); const fz = @import("replay.zig"); const variants = @import("variants.zig"); +const gx_mod = @import("gx.zig"); const Session = @import("session.zig").Session; const Engine = @import("engine.zig").Engine; const Buf = fz.Buf; @@ -74,7 +75,12 @@ pub fn encode(e: *Engine, segs: []const Seg, rows: usize, ids: Buf, masks: ?*con r.rows = g.rows; const ins = [_]Buf{ v.p, sl.cs[0], sl.so[0], l.conv, l.alog, l.dt, l.norm, t.eps, g.s.m.t.rows }; const outs = [_]Buf{ v.gout, sl.cs[1], sl.so[1] }; - if (r.gdn_pipe) |pipe| fz.gdn_step.step(r, pipe, &ins, &outs, 0, 48) else try r.callAs("q4_gdn@gdn", if (r.gdn_step and g.rows > 1) 8 else g.rows, &ins, &outs); + const wide = if (g.rows == 8 or g.rows == 16) r.batch_gdn_wide else null; + if (wide orelse r.gdn_pipe) |pipe| { + fz.gdn_step.step(r, pipe, &ins, &outs, 0, 48); + } else { + try r.callAs("q4_gdn@gdn", if (r.gdn_step and g.rows > 1) 8 else g.rows, &ins, &outs); + } } } else { try r.call("q4_attn_prep@att", &.{ t.p, t.pos8, l.qn, l.kn, l.iqn, t.eps, t.log2base }, &.{ t.q, t.kout, t.iq }); @@ -90,7 +96,7 @@ pub fn encode(e: *Engine, segs: []const Seg, rows: usize, ids: Buf, masks: ?*con try m.hcProject(t.h[cur], l.mhc, "qa_hc_down@mhc", "qa_hc_up@mhc", t.inj_m); try r.router("q4_router_float@moe", t.mixed, l.router, t.rows, t.lg, rows); if (r.fsr) |stream| try stream.prepare(r, i, t.lg, t.rows, t.pick, t.wts, rows, t.mixed, if (i + 1 < fz.LAYERS) m.layers[i + 1].router else null, @import("fsr_runtime.zig").guarded(l.xw)); - if (l.xw) |w| try variants.experts(r, "qa_expert_gateup@moe.gate", "qa_expert_down_y@moe.down", t.mixed, t.lg, l.ex, t.act, t.pick, t.wts, t.rows, t.ydown, w) else try r.experts("qa_expert_gateup@moe.gate", "qa_expert_down_y@moe.down", t.mixed, t.lg, l.ex, t.act, t.pick, t.wts, t.rows, t.ydown); + if (gx_mod.sharedGroups(r, l.xw, rows, r.gx_shared)) r.gx.?.encode(r, t.mixed, t.lg, l.ex, t.act, t.pick, t.wts, t.rows, t.ydown, rows) else if (l.xw) |w| try variants.experts(r, "qa_expert_gateup@moe.gate", "qa_expert_down_y@moe.down", t.mixed, t.lg, l.ex, t.act, t.pick, t.wts, t.rows, t.ydown, w) else try r.experts("qa_expert_gateup@moe.gate", "qa_expert_down_y@moe.down", t.mixed, t.lg, l.ex, t.act, t.pick, t.wts, t.rows, t.ydown); if (r.fsr) |stream| try stream.after(r); } try m.grouped(t.h[cur], t.h[1 - cur]); diff --git a/zig/src/families/flashnext/cuda_batch.zig b/zig/src/families/flashnext/cuda_batch.zig index d0f693fc858..2cbc4547fa0 100644 --- a/zig/src/families/flashnext/cuda_batch.zig +++ b/zig/src/families/flashnext/cuda_batch.zig @@ -325,7 +325,8 @@ pub fn Pass(comptime Tri: type) type { a.add(gv); a.add(ggb); a.add(state); - if (rows >= 64) { + const form = gdn.chainForm(rows, state_out, self.k.forms.gdn_chain_tpr); + if (form == .chain_tpr) { // two threads a state row (fn_gdn_chain_tpr), fn_gdn_rows' bits; in place without a rollback copy a.add(if (state_out != 0) state_out else state); a.add(cint(rows)); @@ -335,7 +336,7 @@ pub fn Pass(comptime Tri: type) type { if (state_out != 0) a.add(state_out); a.add(cint(rows)); a.add(ys); - try cuda.launch.launch(if (state_out != 0) g.chain_to else g.chain, .{ .grid = .{ .x = h.nv, .y = gdn.dv / 16 }, .block = .{ .x = 128 } }, self.stream, &a); + try cuda.launch.launch(if (form == .chain_to) g.chain_to else g.chain, .{ .grid = .{ .x = h.nv, .y = gdn.dv / 16 }, .block = .{ .x = 128 } }, self.stream, &a); } pub fn attnBlock(self: *Self, lw: *const Layer, ai: usize) !void { diff --git a/zig/src/families/flashnext/cuda_batch_kernels.zig b/zig/src/families/flashnext/cuda_batch_kernels.zig index 65945d0e03f..26f34d3d8ea 100644 --- a/zig/src/families/flashnext/cuda_batch_kernels.zig +++ b/zig/src/families/flashnext/cuda_batch_kernels.zig @@ -37,6 +37,7 @@ pub const Gdn = struct { /// The prompt pass's kernel forms, each switch read once at load: the pass and the disk key read these. pub const Forms = struct { gdn_fused: bool = true, // TF_FLASHNEXT_GDN_FUSED + gdn_chain_tpr: bool = false, // TF_FLASHNEXT_GDN_CHAIN_TPR hc_fuse: bool = true, // TF_FLASHNEXT_HC_FUSE in_pass: bool = true, // TF_FLASHNEXT_KEEP_INPASS readout_rows: usize = 64, // TF_FLASHNEXT_READOUT_ROWS (maxInt: never) @@ -46,6 +47,7 @@ pub const Forms = struct { pub fn resolve() Forms { return .{ .gdn_fused = @import("cuda_gdn_fused.zig").on(), + .gdn_chain_tpr = @import("cuda_gdn.zig").chainTpr(), .hc_fuse = @import("cuda_batch_hc.zig").on(), .in_pass = @import("cuda_lanes_snap.zig").keepInPass(), .readout_rows = @import("cuda_chunk.zig").readoutTileRows(), diff --git a/zig/src/families/flashnext/cuda_disk.zig b/zig/src/families/flashnext/cuda_disk.zig index 6ee26f07f05..3ba452793da 100644 --- a/zig/src/families/flashnext/cuda_disk.zig +++ b/zig/src/families/flashnext/cuda_disk.zig @@ -120,7 +120,8 @@ pub fn policyOf(c: anytype) [13]u64 { // TF_FLASHNEXT_CHUNK_SOLO and _CHUNK as resolved: a pass's rows alone, and beside a decoding stream e.chunk, e.busy_chunk, - @intFromBool(f.gdn_fused), + // TF_FLASHNEXT_GDN_FUSED, and TF_FLASHNEXT_GDN_CHAIN_TPR in bit 1 (unset leaves the key as it was) + @intFromBool(f.gdn_fused) | @as(u64, @intFromBool(f.gdn_chain_tpr)) << 1, // TF_FLASHNEXT_HC_FUSE, and TF_FLASHNEXT_READOUT_FUSED in bit 1 (unset leaves the key as it was) @intFromBool(f.hc_fuse) | @as(u64, @intFromBool(f.readout_fused)) << 1, @intFromBool(f.in_pass), diff --git a/zig/src/families/flashnext/cuda_gdn.zig b/zig/src/families/flashnext/cuda_gdn.zig index d72e983ce79..9eb79e3ba49 100644 --- a/zig/src/families/flashnext/cuda_gdn.zig +++ b/zig/src/families/flashnext/cuda_gdn.zig @@ -16,6 +16,18 @@ pub const proj_width: usize = conv_dim + nv * dv + 2 * nv; pub const value_dim: usize = nv * dv; pub const groups: usize = value_dim / qmm.group; +pub const ChainForm = enum { chain, chain_to, chain_tpr }; + +/// The ordinary recurrence kernel for these rows, rollback destination and TF_FLASHNEXT_GDN_CHAIN_TPR setting. +pub fn chainForm(rows: usize, state_out: u64, chain_tpr: bool) ChainForm { + return if (rows >= 64 or chain_tpr) .chain_tpr else if (state_out != 0) .chain_to else .chain; +} + +/// Whether ordinary recurrence rows below 64 opt into fn_gdn_chain_tpr; default off. +pub fn chainTpr() bool { + return @import("sys").environment.read(bool, "TF_FLASHNEXT_GDN_CHAIN_TPR", false) catch false; +} + const symbol: [:0]const u8 = "flashnext_gdn_chain"; const toBf16 = @import("core").bf16_round.bits; diff --git a/zig/src/families/flashnext/cuda_images.zig b/zig/src/families/flashnext/cuda_images.zig index f7a105265d5..4297746bc2e 100644 --- a/zig/src/families/flashnext/cuda_images.zig +++ b/zig/src/families/flashnext/cuda_images.zig @@ -80,7 +80,8 @@ pub const Vision = struct { return switch (err) { error.BadImageLimits, error.BadImageCount => "image count or row budget exceeds the configured limits", error.BadImageGrid, error.BadImagePatches, error.BadImagePlaceholders => "image rows do not match the prompt placeholders", - error.NoVisionTower, error.BadVisionWidth, error.UnsupportedQwenVision => "unsupported Flash Next Qwen-VL tower configuration", + error.NoVisionTower => @import("engine_api").visionWords("this Flash Next checkpoint", error.VisionWithoutTower), + error.BadVisionWidth, error.UnsupportedQwenVision => "unsupported Flash Next Qwen-VL tower configuration", else => core.qwen_vl.geometry.problem(err), }; } diff --git a/zig/src/families/flashnext/cuda_lanes.zig b/zig/src/families/flashnext/cuda_lanes.zig index ad470b8cef0..bc96b84e5bb 100644 --- a/zig/src/families/flashnext/cuda_lanes.zig +++ b/zig/src/families/flashnext/cuda_lanes.zig @@ -103,8 +103,8 @@ pub fn Namespace(comptime Tri: type) type { return bytes.placementWeightBytes(gpa, io, dir, world, rank, drafts); } pub const worlds = bytes.worlds; // refused by name before admission and open, which take no others - pub fn visionBytes(a: std.mem.Allocator, io: std.Io, dir: []const u8) !u64 { - return bytes.visionBytes(a, io, dir); + pub fn visionBytes(a: std.mem.Allocator, io: std.Io, dir: []const u8, rank: u32, world: u32) !u64 { + return bytes.visionBytes(a, io, dir, rank, world); } pub fn healthy(ptr: *anyopaque) bool { @@ -571,6 +571,7 @@ pub fn Namespace(comptime Tri: type) type { _ = @import("cuda_lanes_restore_test.zig").Cases(Cuda, Cuda.open, snaps.restore, dropLane); _ = @import("cuda_lanes_admission_test.zig").Cases(Cuda, Cuda.open, dropLane); _ = @import("cuda_score.zig").CapabilityCases(Cuda); + _ = @import("cuda_lanes_vision_test.zig").Cases(@This()); } test "a bad TF_FLASHNEXT_CHUNK, _CHUNK_SOLO or TF_FLASHNEXT_LOAD_THREADS is refused at load before the loader takes a stream, a module or a buffer" { diff --git a/zig/src/families/flashnext/cuda_lanes_bytes.zig b/zig/src/families/flashnext/cuda_lanes_bytes.zig index 4de283cbb14..6044b73eccc 100644 --- a/zig/src/families/flashnext/cuda_lanes_bytes.zig +++ b/zig/src/families/flashnext/cuda_lanes_bytes.zig @@ -40,8 +40,9 @@ pub const worlds = struct { }; /// The tower's weights and one call's scratch, which rank zero holds beside the text weights with --vision. -pub fn visionBytes(a: std.mem.Allocator, io: std.Io, dir: []const u8) !u64 { +pub fn visionBytes(a: std.mem.Allocator, io: std.Io, dir: []const u8, rank: u32, _: u32) !u64 { + if (rank != 0) return 0; const v = @import("qwen_vision"); - const c = ((try v.Settings.read(a, io, dir)) orelse return error.NoVisionTower).tower; + const c = ((try v.Settings.read(a, io, dir)) orelse return 0).tower; // no tower: open refuses --vision by name return v.Tower.weightBytes(c) + v.Tower.scratchBytes(c, v.max_patches); } diff --git a/zig/src/families/flashnext/cuda_lanes_explain.zig b/zig/src/families/flashnext/cuda_lanes_explain.zig index 51035bc9878..e6f732a84c1 100644 --- a/zig/src/families/flashnext/cuda_lanes_explain.zig +++ b/zig/src/families/flashnext/cuda_lanes_explain.zig @@ -8,6 +8,7 @@ pub fn open(err: anyerror) ?[]const u8 { error.FlashNextRanksOnCapturedGlue => "--tp 2 runs Flash Next's own glue, not a captured set: set TENSORFOLD_CUDA_KERNELS=native, or serve on one GPU", error.BadFlashNextKvPages, error.BadFlashNextPageTest, error.FlashNextPagesUnsupported, error.UnsupportedCheckpoint => explain(err), error.UnsupportedLearningFormat, error.TrainingOnCapturedGlue => explain(err), + error.VisionWithoutTower => @import("engine_api").visionWords("this Flash Next checkpoint", err), else => null, }; } diff --git a/zig/src/families/flashnext/cuda_lanes_load.zig b/zig/src/families/flashnext/cuda_lanes_load.zig index 5ad7e03cda5..7acec9e38c3 100644 --- a/zig/src/families/flashnext/cuda_lanes_load.zig +++ b/zig/src/families/flashnext/cuda_lanes_load.zig @@ -10,6 +10,8 @@ const images = @import("cuda_images.zig"); pub fn open(comptime F: type, gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: []const u8, captured: ?[]const u8, o: F.Options) !F.Loaded { try @import("env_validate.zig").startup(); if (o.vision) |v| try @import("qwen_vision").media.checkLimits(v); + // --vision on a checkpoint without a tower refuses by name (core's gate) before a stream or a weight loads + if (o.vision != null) _ = try @import("engine_api").visionGate(true, try @import("qwen_vision").Settings.read(gpa, io, dir) != null); var load_cache = @import("core").checkpoint.cache.Load.begin(io, o.tp > 1); defer load_cache.deinit(); const Cuda = F.Cuda; diff --git a/zig/src/families/flashnext/cuda_lanes_vision_test.zig b/zig/src/families/flashnext/cuda_lanes_vision_test.zig new file mode 100644 index 00000000000..39309ffac54 --- /dev/null +++ b/zig/src/families/flashnext/cuda_lanes_vision_test.zig @@ -0,0 +1,24 @@ +//! --vision at Flash Next's CUDA open: refused by name by core's gate before the loader touches the driver. +const std = @import("std"); +const cuda = @import("cuda"); + +pub fn Cases(comptime F: type) type { + return struct { + test "--vision on a checkpoint without a vision tower is refused by name before a stream, a module or a buffer" { + const a = std.testing.allocator; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "config.json", .data = "{\"model_type\":\"qwen3_5_moe\"}" }); + const dir = try tmp.dir.realPathFileAlloc(std.testing.io, ".", a); + defer a.free(dir); + // every driver entry point undefined: the refusal must come before the first call + var driver: cuda.Driver = undefined; + const ctx: cuda.Context = .{ .d = &driver, .device = 0, .handle = null }; + const o: F.Options = .{ .vision = .{ .image_tokens = 4096, .max_images = 4 }, .context = 4096, .drafts = true }; + try std.testing.expectError(error.VisionWithoutTower, F.open(a, std.testing.io, &ctx, dir, null, o)); + const words = @import("cuda_lanes_explain.zig").open(error.VisionWithoutTower).?; + try std.testing.expectEqualStrings("--vision given but this Flash Next checkpoint has no vision tower", words); + try std.testing.expectEqual(@as(u64, 0), try @import("cuda_lanes_bytes.zig").visionBytes(a, std.testing.io, dir, 0, 1)); + } + }; +} diff --git a/zig/src/families/flashnext/cuda_mtp.zig b/zig/src/families/flashnext/cuda_mtp.zig index d81114959af..ffc7f15cea8 100644 --- a/zig/src/families/flashnext/cuda_mtp.zig +++ b/zig/src/families/flashnext/cuda_mtp.zig @@ -212,6 +212,9 @@ pub const Head = struct { service: lanes.proposal_head.Service, module: cuda.Module, best_fn: cuda.Function, + /// fn_row_best_max and fn_row_best_sum: fn_row_best's passes over 32 blocks a row (best and split_bytes scratch). + split_fns: [2]cuda.Function, + split: ?cuda.DeviceBuffer, draw_batch: @import("cuda_draw_batch.zig").Batch, topk_fn: cuda.Function, // fn_row_topk: a row's top_k candidates as drawRow ranks them (cuda_mtp_draw.zig) @@ -262,6 +265,12 @@ pub const Head = struct { h.module = try cuda.Module.load(driver, cuda.kernels.flashnext_mtp); errdefer h.module.unload(); h.best_fn = try h.module.function("fn_row_best"); + h.split_fns = .{ try h.module.function("fn_row_best_max"), try h.module.function("fn_row_best_sum") }; + const zeros = try gpa.alloc(u8, split_bytes); + defer gpa.free(zeros); + @memset(zeros, 0); // the per-row counters start, and are left, at 0 + h.split = try cuda.DeviceBuffer.fromHost(driver, zeros); + errdefer h.split.?.free(); h.topk_fn = try h.module.function("fn_row_topk"); h.draw_batch = try @import("cuda_draw_batch.zig").Batch.init(gpa, driver, batch_on, h.ids.len); return h; @@ -274,6 +283,7 @@ pub const Head = struct { pub fn deinit(h: *Head) void { h.draw_batch.deinit(h.gpa); + if (h.split) |*b| b.free(); h.module.unload(); h.draft.free(); h.artifact.deinit(); @@ -300,6 +310,28 @@ pub const Head = struct { _ = try pass.lane(input, sums, h.draft, out, pass.s.dummy, rows, 1); } + fn bestSplit(h: *const Head, stream: cuda.Stream, scratch: u64, scores: u64, v: usize, ld: usize, rows: usize, out: u64) !void { + const part = scratch; + const sums = part + round_rows * 32 * 8; + const done = sums + round_rows * 32 * 4; + const grid: cuda.launch.Dim3 = .{ .x = @intCast(rows), .y = 32 }; + var a: cuda.Args = .{}; + a.add(scores); + a.add(cint(v)); + a.add(@as(c_longlong, @intCast(ld))); + a.add(part); + try cuda.launch.launch(h.split_fns[0], .{ .grid = grid, .block = .{ .x = 32 } }, stream, &a); + var b: cuda.Args = .{}; + b.add(scores); + b.add(cint(v)); + b.add(@as(c_longlong, @intCast(ld))); + b.add(part); + b.add(sums); + b.add(done); + b.add(out); + try cuda.launch.launch(h.split_fns[1], .{ .grid = grid, .block = .{ .x = 32 } }, stream, &b); + } + /// Each of `rows` rows' `k` best of its first `v` values (fn_row_topk): bf16 bits to out_v, columns to out_c. pub fn topk(h: *const Head, stream: cuda.Stream, scores: u64, v: usize, ld: usize, rows: usize, k: usize, out_v: u64, out_c: u64) !void { var a: cuda.Args = .{}; @@ -312,8 +344,9 @@ pub const Head = struct { try cuda.launch.launch(h.topk_fn, .{ .grid = .{ .x = @intCast(rows) }, .block = .{ .x = 1024 } }, stream, &a); } - /// fn_row_best over `rows` rows of `v` scores `ld` apart: [rows, 4] fp32 at `out` (best, log-sum-exp, id bits). + /// fn_row_best over `rows` rows of `v` scores `ld` apart into [rows, 4] fp32 at `out`; split up to round_rows rows. pub fn best(h: *const Head, stream: cuda.Stream, scores: u64, v: usize, ld: usize, rows: usize, out: u64) !void { + if (h.split) |b| if (rows > 0 and rows <= round_rows) return h.bestSplit(stream, b.ptr, scores, v, ld, rows, out); var a: cuda.Args = .{}; a.add(scores); a.add(cint(v)); @@ -323,6 +356,9 @@ pub const Head = struct { } }; +/// The split best's scratch: each warp's best and id bits, its exponent sum, then a counter a row (round_rows rows). +pub const split_bytes: usize = round_rows * 32 * 8 + round_rows * 32 * 4 + round_rows * 4; + /// Device bytes the head's weights take beyond the main model's; `fp8`: block-FP8 routed experts (headFp8). pub fn headBytes(fp8: bool) usize { const weights = 3 * wt.moe_w * dims; @@ -331,7 +367,7 @@ pub fn headBytes(fp8: bool) usize { const experts = wt.experts_n * routed + nvfp4; const attn = (wt.proj_n + dims) * dims / 2 * 5 / 4; const draft = 79_591 * dims / 2 * 5 / 4; - return experts + attn + draft + 2 * dims * dims / 2 * 5 / 4 + @import("cuda_draw_batch.zig").bytes + @import("cuda_draft_draw.zig").scoreBytes(79_591); + return experts + attn + draft + 2 * dims * dims / 2 * 5 / 4 + @import("cuda_draw_batch.zig").bytes + @import("cuda_draft_draw.zig").scoreBytes(79_591) + split_bytes; } pub const Pick = @import("cuda_mtp_draft.zig").Pick; @@ -342,7 +378,8 @@ pub const check = @import("cuda_mtp_check.zig").check; test "the head's bytes: NVFP4 experts as before, FP8 routed experts a byte a weight and their f32 block scales" { const before = (wt.experts_n + 1) * 3 * wt.moe_w * dims / 2 * 5 / 4 + (wt.proj_n + dims) * dims / 2 * 5 / 4 + 79_591 * dims / 2 * 5 / 4 + 2 * dims * dims / 2 * 5 / 4; - try std.testing.expectEqual(before + @import("cuda_draw_batch.zig").bytes + @import("cuda_draft_draw.zig").scoreBytes(79_591), headBytes(false)); + try std.testing.expectEqual(@as(usize, 24_832), split_bytes); + try std.testing.expectEqual(before + @import("cuda_draw_batch.zig").bytes + @import("cuda_draft_draw.zig").scoreBytes(79_591) + split_bytes, headBytes(false)); // an expert's three projections: 640 x 2560 bytes and 5 x 20 scales each, against 5/8 of a byte a weight try std.testing.expectEqual(wt.experts_n * (3 * (640 * 2560 + 5 * 20 * 4) - 3 * 640 * 2560 * 5 / 8), headBytes(true) - headBytes(false)); } diff --git a/zig/src/families/flashnext/cuda_mtp_nonfinite_fixture.zig b/zig/src/families/flashnext/cuda_mtp_nonfinite_fixture.zig index d8baa94dcb9..ff4283e46de 100644 --- a/zig/src/families/flashnext/cuda_mtp_nonfinite_fixture.zig +++ b/zig/src/families/flashnext/cuda_mtp_nonfinite_fixture.zig @@ -186,6 +186,7 @@ pub fn headIds(d: *cuda.Driver, ids: []const u32) !mtp.Head { h.service = try @import("lanes").proposal_head.Service.legacy(gpa, &h.artifact); h.draw_batch = .{ .scores = .{ .d = d, .ptr = 0xA000, .len = @import("cuda_draft_draw.zig").scoreBytes(ids.len) }, .device = .{ .d = d, .ptr = 0x9000, .len = @import("cuda_draw_batch.zig").bytes }, .host = &Device.batch_host, .on = true }; h.best_fn = .{ .d = d, .handle = @ptrFromInt(1) }; + h.split = null; h.topk_fn = .{ .d = d, .handle = @ptrFromInt(2) }; return h; } diff --git a/zig/src/families/flashnext/engine_load.zig b/zig/src/families/flashnext/engine_load.zig index a97c386faaa..739b305db47 100644 --- a/zig/src/families/flashnext/engine_load.zig +++ b/zig/src/families/flashnext/engine_load.zig @@ -47,32 +47,49 @@ pub fn loadConfigured(gpa: Allocator, io: std.Io, model_dir: []const u8, dump_di try @import("env_validate.zig").startup(); try window.validate(speed_up != null or platform.c.getenv("TF_FLASHNEXT_TP") != null); try load_admission.check(gpa, io, model_dir); + var selected = window; try @import("readout_fused.zig").refuse("Metal", @import("readout_fused.zig").on()); try @import("fused_split.zig").refuse("Metal", try @import("fused_split.zig").on()); const memory = @import("flashnext_memory"); const weights = try memory.weightBytes(@import("core").checkpoint_host, gpa, io, model_dir); var inventory = try memory.weights_plan.read(@import("core").checkpoint_host.Checkpoint, @import("core").quant.mlx, gpa, io, model_dir); - const placement = try @import("fsr_layout.zig").of(inventory, window); + const source_inventory = inventory; + var placement = try @import("fsr_layout.zig").of(inventory, selected); inventory.raw = placement.raw; const home = if (platform.c.getenv("HOME")) |v| std.mem.span(v) else ""; const route = try @import("pack_route.zig").plan(gpa, io, model_dir, dump_dir, home); defer route.deinit(gpa); const paired = speed_up != null or platform.c.getenv("TF_FLASHNEXT_TP") != null; - const requested = try std.math.add(u64, try std.math.add(u64, window.startup_extra, placement.extra), if (paired) fz.Tp2.startupBytes() else 0); + var requested = try std.math.add(u64, try std.math.add(u64, selected.startup_extra, placement.extra), if (paired) fz.Tp2.startupBytes() else 0); const pool = mtl.objc.Pool.push(); defer pool.pop(); const device = try mtl.Device.init(); errdefer device.deinit(); const existing = device.allocated(); - const base_extra = try std.math.add(u64, requested, existing); - const plain = try memory.budgetLiveFor(weights, window.capacity, inventory, base_extra, existing, window.sibling(paired)); + var base_extra = try std.math.add(u64, requested, existing); + var plain = try memory.budgetLiveFor(weights, selected.capacity, inventory, base_extra, existing, selected.sibling(paired)); const ram = std.process.totalSystemMemory() catch null; const limit_text: ?[]const u8 = if (platform.c.getenv("FLASHNEXT_LOAD_LIMIT_GB")) |v| std.mem.span(v) else null; - const limit = try memory.ceiling(ram, device.maxWorkingSet(), limit_text); const cache = @import("rotary_cache.zig"); + var pool_fitted = false; + const limit = try memory.ceiling(ram, device.maxWorkingSet(), limit_text); + if (plain.forPhase(route.needs_build) > limit and selected.ssd_experts != null and !paired) { + const fitted = try @import("fsr_layout.zig").fit(source_inventory, selected, .{ .limit = limit, .existing = existing, .extra = selected.startup_extra, .needs_build = route.needs_build, .paired = paired, .rotary_growth = if (device.tensorUnits()) cache.growth else 0 }); + if (fitted.ssd_experts != selected.ssd_experts) { + std.log.info("flash next: requested SSD expert maximum {d} bytes exceeds the load ceiling; using {d} bytes", .{ selected.ssd_experts.?, fitted.ssd_experts.? }); + selected = fitted; + pool_fitted = true; + placement = try @import("fsr_layout.zig").of(source_inventory, selected); + inventory.raw = placement.raw; + requested = try std.math.add(u64, try std.math.add(u64, selected.startup_extra, placement.extra), if (paired) fz.Tp2.startupBytes() else 0); + base_extra = try std.math.add(u64, requested, existing); + plain = try memory.budgetLiveFor(weights, selected.capacity, inventory, base_extra, existing, selected.sibling(paired)); + } + } const rotary_enabled = cache.fits(device.tensorUnits(), plain.steady, limit) and plain.forPhase(route.needs_build) <= limit; + if (pool_fitted and device.tensorUnits() and !rotary_enabled) std.log.warn("flash next: minimum SSD pool leaves no rotary-cache room; learned states use the scalar rotary identity", .{}); const extra = try std.math.add(u64, base_extra, if (rotary_enabled) cache.growth else 0); - const startup = try memory.budgetLiveFor(weights, window.capacity, inventory, extra, existing, window.sibling(paired)); + const startup = try memory.budgetLiveFor(weights, selected.capacity, inventory, extra, existing, selected.sibling(paired)); const load_limit = memory.admitBudget(limit, startup, route.needs_build) catch |err| { if (err == error.FlashNextMemoryShortfall) { const need = startup.forPhase(route.needs_build); @@ -82,7 +99,7 @@ pub fn loadConfigured(gpa: Allocator, io: std.Io, model_dir: []const u8, dump_di return err; }; if (placement.pool) |p| std.log.info("flash next FSR plan: {d} expert slots, {d} stored bytes/slot, {d} pool bytes, {d} metadata bytes, {d} unused tail bytes; steady {d} bytes, ceiling {d}; uncached pread", .{ p.slots, p.stride, p.slabs, p.metadata + placement.extra, p.unused, startup.steady, load_limit }); - if (window.ple_on_ssd) std.log.info("flash next FSR plan: PLE rows on SSD, bounded staging charge {d} bytes; uncached pread", .{placement.ple.?}); + if (selected.ple_on_ssd) std.log.info("flash next FSR plan: PLE rows on SSD, bounded staging charge {d} bytes; uncached pread", .{placement.ple.?}); // Pack construction has no engine buffers or numerical pipelines live beside its host work. const built_dir = if (route.needs_build) try pack_cache.ensure(gpa, io, model_dir, route.root.?, route.identity, PackBuilder{}) else null; defer if (built_dir) |dir| gpa.free(dir); @@ -93,7 +110,7 @@ pub fn loadConfigured(gpa: Allocator, io: std.Io, model_dir: []const u8, dump_di e.copy = true; e.copy_min = 3; e.copy_long = 6; - e.segments = window.staggered(); + e.segments = selected.staggered(); e.mark_taps = true; e.pair_min = tp_settings.pairMin(if (platform.c.getenv("FZ_PAIR_MIN")) |v| std.mem.span(v) else null, PAIR_MIN); // rank 1 takes rank 0's e.call_log = platform.c.getenv("FZ_CALL_LOG") != null; @@ -112,7 +129,7 @@ pub fn loadConfigured(gpa: Allocator, io: std.Io, model_dir: []const u8, dump_di const arena = e.arena_state.allocator(); const r = try arena.create(Run); - r.* = .{ .arena = arena, .device = device, .queue = try device.queue(), .window = window, .load_limit = load_limit, .rotary_enabled = rotary_enabled }; + r.* = .{ .arena = arena, .device = device, .queue = try device.queue(), .window = selected, .load_limit = load_limit, .rotary_enabled = rotary_enabled }; return @import("load_prefix.zig").build(*Engine, r, Construction{ .e = e, .io = io, @@ -153,6 +170,9 @@ fn finishLoad(context: Construction, r: *Run) !*Engine { r.gdn_pipe = try fz.gdn_step.compile(r, false); if (v[0] == '2') r.gdn_kept = try fz.gdn_step.compile(r, true); // GPU-side rounds keep one state a layer } + if (r.tp == null and try platform.environment.read(bool, "TF_FLASHNEXT_BATCH_GDN_WIDE", false)) { + r.batch_gdn_wide = r.gdn_pipe orelse try fz.gdn_step.compile(r, false); + } const index_file = try r.mapFile(try std.fmt.allocPrintSentinel(arena, "{s}/model.safetensors.index.json", .{model_dir}, 0)); if (index_file.size > index_format.max_bytes) return error.BadIndex; @@ -425,6 +445,7 @@ fn finishLoad(context: Construction, r: *Run) !*Engine { r.gx = try @import("gx.zig").init(r, grouped_rows, gateup_mb2); std.log.info("flash next: grouped experts from {d} rows{s}", .{ r.gx.?.min_rows, if (gateup_mb2) ", gate/up MB=2" else "" }); } + r.gx_shared = try platform.environment.read(bool, "TF_FN_GX_SHARED", false); if (r.sb_index) std.log.info("flash next: {d} expert tensors' scales and biases indexed, at most {d} pairs each", .{ r.sbix.count(), r.sb_pairs }); if (platform.c.getenv("FZ_SKIP")) |v| r.skip = try std.fmt.parseInt(u32, std.mem.span(v), 10); // dev: knock-outs by Run.class bit // GPU-gated lanes at this probability product: 0.4 without tensor units (FZ_GATE=tau sets it, FZ_GATE=off none) diff --git a/zig/src/families/flashnext/fsr_buffer.zig b/zig/src/families/flashnext/fsr_buffer.zig new file mode 100644 index 00000000000..d44aca50c9d --- /dev/null +++ b/zig/src/families/flashnext/fsr_buffer.zig @@ -0,0 +1,7 @@ +//! Ownership transfers to the run only after its held-buffer registration succeeds. +pub fn allocate(r: anytype, n: usize) !@TypeOf(r.allocate(n) catch unreachable) { + const b = try r.allocate(n); + errdefer b.deinit(); + try r.keep(b); + return b; +} diff --git a/zig/src/families/flashnext/fsr_layout.zig b/zig/src/families/flashnext/fsr_layout.zig index d49df4760dd..63ed2909cdc 100644 --- a/zig/src/families/flashnext/fsr_layout.zig +++ b/zig/src/families/flashnext/fsr_layout.zig @@ -1,8 +1,9 @@ //! Whole-path residency prices computed before device buffers or checkpoint payloads are loaded. const std = @import("std"); pub const plan = @import("../../core/fsr/plan.zig"); -const prompt = @import("flashnext_memory").prompt; -pub const Plan = struct { pool: ?plan.Pool = null, ple: ?u64 = null, raw: u64, extra: u64 = 0 }; +const memory = @import("flashnext_memory"); +const prompt = memory.prompt; +pub const Plan = struct { pool: ?plan.Pool = null, ple: ?u64 = null, raw: u64, extra: u64 = 0, forecast: u64 = 0 }; pub fn of(inventory: anytype, settings: anytype) !Plan { var p: Plan = .{ .raw = inventory.raw, .extra = if (settings.ssd_experts != null or settings.ple_on_ssd or settings.fsr_trace != null) 1024 * 1024 else 0 }; @@ -11,6 +12,8 @@ pub fn of(inventory: anytype, settings: anytype) !Plan { p.pool = try plan.pool(bytes, inventory.expert_parts, 49 * 512, 512); // Bounded demand IDs, forecast logits/routes and metadata for the source descriptor owner. p.extra = 1024 * 1024; + p.forecast = try plan.forecastJobs(9, p.pool.?.slots); // a subset of the prepaid owner allowance + if (p.forecast > p.extra) return error.ExpertMetadataTooLarge; } if (settings.ple_on_ssd) { p.ple = try std.math.add(u64, try plan.pleRows(prompt.PMAX * 16, 160, 8, 32), 128 * 3 * 32); @@ -18,3 +21,44 @@ pub fn of(inventory: anytype, settings: anytype) !Plan { p.raw = try plan.resident(inventory.raw, inventory.routed, inventory.ple, p.pool, p.ple); return p; } + +/// Only a refused maximum shrinks; every admitted setting and every impossible fit keeps its original policy. +pub fn fit(inventory: anytype, settings: anytype, context: anytype) !@TypeOf(settings) { + if (context.paired or settings.ssd_experts == null) return settings; + const current = try of(inventory, settings); + if ((try budget(inventory, settings, context)).forPhase(context.needs_build) <= context.limit) return settings; + const pool = current.pool.?; + var next = settings; + next.ssd_experts = try std.math.mul(u64, 512, pool.stride); + var growth: u64 = if (@hasField(@TypeOf(context), "rotary_growth")) context.rotary_growth else 0; + if (!try fits(inventory, next, context, growth)) { + if (!try fits(inventory, next, context, 0)) return settings; + growth = 0; // the complete-demand minimum still admits when the optional cache cannot fit + } + var lo: usize = 512; + var hi = pool.slots; + while (lo < hi) { + const mid = lo + (hi - lo + 1) / 2; + next.ssd_experts = try std.math.mul(u64, mid, pool.stride); + if (try fits(inventory, next, context, growth)) + lo = mid + else + hi = mid - 1; + } + next.ssd_experts = try std.math.mul(u64, lo, pool.stride); + return next; +} + +fn budget(inventory: anytype, settings: anytype, context: anytype) !memory.Budget { + const p = try of(inventory, settings); + var resident = inventory; + resident.raw = p.raw; + const extra = try std.math.add(u64, context.extra, try std.math.add(u64, context.existing, p.extra)); + return memory.budgetLiveFor(0, settings.capacity, resident, extra, context.existing, settings.sibling(context.paired)); +} + +fn fits(inventory: anytype, settings: anytype, context: anytype, growth: u64) !bool { + var b = try budget(inventory, settings, context); + b.steady = try std.math.add(u64, b.steady, growth); + return b.forPhase(context.needs_build) <= context.limit; +} diff --git a/zig/src/families/flashnext/fsr_storage.zig b/zig/src/families/flashnext/fsr_storage.zig index 3f93aafaba9..81885a7fa58 100644 --- a/zig/src/families/flashnext/fsr_storage.zig +++ b/zig/src/families/flashnext/fsr_storage.zig @@ -57,8 +57,7 @@ pub const Pool = struct { var buffers: [9]fz.Buf = undefined; for (&buffers, &slabs, experts.strides) |*buffer, *slab, stride| { const n = try std.math.mul(usize, p.slots, stride); - buffer.* = .{ .b = try r.allocate(n) }; - try r.keep(buffer.b); + buffer.* = .{ .b = try @import("fsr_buffer.zig").allocate(r, n) }; slab.* = buffer.b.contents()[0..n]; } const map: fz.Buf = .{ .b = try r.buffer(experts.spans.len * 4) }; @@ -88,8 +87,7 @@ pub const Ple = struct { var slabs: [3][]u8 = undefined; for (&buffers, &slabs, 0..) |*buffer, *slab, i| { const n = try std.math.mul(usize, maximum, shards[0].parts[i].length / shards[0].rows); - buffer.* = .{ .b = try r.allocate(n) }; - try r.keep(buffer.b); + buffer.* = .{ .b = try @import("fsr_buffer.zig").allocate(r, n) }; slab.* = buffer.b.contents()[0..n]; } return .{ diff --git a/zig/src/families/flashnext/gx.zig b/zig/src/families/flashnext/gx.zig index 19751406b5b..9d0bebc3e8a 100644 --- a/zig/src/families/flashnext/gx.zig +++ b/zig/src/families/flashnext/gx.zig @@ -72,6 +72,17 @@ pub const Gx = struct { } }; +/// One replay window's existing grouped-kernel gate; the shared-round opt-in does not change it. +pub fn windowGroups(r: *const Run, w: ?variants.Experts, rows: usize) bool { + const g = r.gx orelse return false; + return rows >= g.min_rows and r.tp == null and w != null and applies(w.?); +} + +/// A shared round groups only under TF_FN_GX_SHARED's explicit opt-in and the same window gates. +pub fn sharedGroups(r: *const Run, w: ?variants.Experts, rows: usize, enabled: bool) bool { + return enabled and windowGroups(r, w, rows); +} + /// The grouped kernels read 4-bit group 32 routed and shared experts, gate/up and down. pub fn applies(w: variants.Experts) bool { const four = [4]usize{ 4, 32, 4, 32 }; @@ -104,3 +115,23 @@ test "the grouped kernels take 4-bit group 32 experts only" { try std.testing.expect(applies(.{ .gu = .{ 4, 32, 4, 32 }, .down = .{ 4, 32, 4, 32 } })); try std.testing.expect(!applies(.{ .gu = .{ 6, 32, 6, 32 }, .down = .{ 4, 32, 4, 32 } })); } + +test "shared rounds opt into grouped experts without changing the single-window gate" { + const w: variants.Experts = .{ .gu = .{ 4, 32, 4, 32 }, .down = .{ 4, 32, 4, 32 } }; + var g: Gx = undefined; + g.min_rows = 5; + var r: Run = undefined; + r.gx = &g; + r.tp = null; + try std.testing.expect(windowGroups(&r, w, 6)); + try std.testing.expect(!sharedGroups(&r, w, 6, false)); + try std.testing.expect(sharedGroups(&r, w, 6, true)); + try std.testing.expect(!windowGroups(&r, w, 4)); + try std.testing.expect(!sharedGroups(&r, w, 4, true)); + try std.testing.expect(!sharedGroups(&r, .{ .gu = .{ 6, 32, 6, 32 }, .down = .{ 4, 32, 4, 32 } }, 6, true)); + r.tp = @ptrFromInt(128); + try std.testing.expect(!sharedGroups(&r, w, 6, true)); + r.tp = null; + r.gx = null; + try std.testing.expect(!sharedGroups(&r, w, 6, true)); +} diff --git a/zig/src/families/flashnext/hip/engine.zig b/zig/src/families/flashnext/hip/engine.zig index a4ce6a3f592..b4a499a78fe 100644 --- a/zig/src/families/flashnext/hip/engine.zig +++ b/zig/src/families/flashnext/hip/engine.zig @@ -32,10 +32,8 @@ pub const Options = struct { want: usize = 1, }; -/// Whether the smaller chunk admits more of `want` streams than the larger's in `room`, after the `slots` bytes. -pub fn narrows(room: u64, slots: u64, larger: u64, smaller: u64, per: u64, want: u64) bool { - return @min(want, (room -| slots -| smaller) / per) > @min(want, (room -| slots -| larger) / per); -} +/// The fallback rule every HIP family shares: whether the smaller chunk admits more of the streams asked for. +pub const narrows = hip.policy.narrows; /// Bytes of the pinned staging a forward's uploads and n-gram rows go through. const staging_bytes = 64 << 20; diff --git a/zig/src/families/flashnext/replay_model.zig b/zig/src/families/flashnext/replay_model.zig index 6802f3939d8..48e54542107 100644 --- a/zig/src/families/flashnext/replay_model.zig +++ b/zig/src/families/flashnext/replay_model.zig @@ -348,7 +348,7 @@ pub const Model = struct { try r.router("q4_router_float@moe", t.mixed, L.router, t.rows, t.lg, rows); if (r.fsr) |stream| try stream.prepare(r, i, t.lg, t.rows, t.pick, t.wts, rows, t.mixed, if (i + 1 < LAYERS) m.layers[i + 1].router else null, @import("fsr_runtime.zig").guarded(L.xw)); r.tp_layer = true; - const by_expert = if (r.gx) |g| rows >= g.min_rows and r.tp == null and L.xw != null and gx_mod.applies(L.xw.?) else false; + const by_expert = gx_mod.windowGroups(r, L.xw, rows); if (by_expert) r.gx.?.encode(r, t.mixed, t.lg, L.ex, t.act, t.pick, t.wts, t.rows, t.ydown, rows) else if (L.xw) |w| try variants.experts(r, "qa_expert_gateup@moe.gate", "qa_expert_down_y@moe.down", t.mixed, t.lg, L.ex, t.act, t.pick, t.wts, t.rows, t.ydown, w) else try r.experts("qa_expert_gateup@moe.gate", "qa_expert_down_y@moe.down", t.mixed, t.lg, L.ex, t.act, t.pick, t.wts, t.rows, t.ydown); if (r.fsr) |stream| try stream.after(r); r.tp_layer = false; diff --git a/zig/src/families/flashnext/replay_run.zig b/zig/src/families/flashnext/replay_run.zig index 0b7914b472f..01840332309 100644 --- a/zig/src/families/flashnext/replay_run.zig +++ b/zig/src/families/flashnext/replay_run.zig @@ -114,6 +114,7 @@ pub const Run = struct { lane_pipes: std.AutoHashMapUnmanaged(u64, mtl.Pipeline) = .empty, wide_pipes: lane_w.Cache = .empty, // lane products at other widths than 6/32 (lane_w.zig) lane_shape: std.AutoHashMapUnmanaged(*Variant, [3]usize) = .empty, // recorded lane kernels' N, K, SK + batch_gdn_wide: ?mtl.Pipeline = null, gdn_pipe: ?mtl.Pipeline = null, // the DeltaNet window step on fz_gdn (gdn.zig) when set gdn_kept: ?mtl.Pipeline = null, // GPU-side rounds: fz_gdn keeping one state a layer, kept rows replayed (gdn.zig) tree: ?*@import("tree.zig").Tree = null, // the tree window decode is running, if any (tree.zig) @@ -121,6 +122,7 @@ pub const Run = struct { head_md1: ?Buf = null, // a gated head step's one-row dims, in place of the head's own head_draw: ?@import("sample.zig").HeadDraw = null, // a sampled reply's head step drafts by its keyed rule gx: ?*@import("gx.zig").Gx = null, // windows from its min_rows on the grouped experts (TF_FLASHNEXT_GROUPED_ROWS) + gx_shared: bool = false, // shared rounds opt into grouped experts (TF_FN_GX_SHARED) xnew_header: []const u8 = "", tp: ?*Tp2 = null, // TP=2 across two Macs (tp.zig): the target layers' experts split by id, outputs exchanged tp_layer: bool = false, // the experts being encoded are a target layer's (the MTP head keeps all of its own) diff --git a/zig/src/families/flint/forward.zig b/zig/src/families/flint/forward.zig index 2180950f1d0..8b1ad7e72f8 100644 --- a/zig/src/families/flint/forward.zig +++ b/zig/src/families/flint/forward.zig @@ -154,7 +154,19 @@ pub fn runShared(m: *const Model, s: *st.Scratch, segments: []const Segment, ids if (out.all) { x.glue(.norm, normed, &.{ b(s.resid), t(W.norm), A, b(s.x) }, .{ n, 1, 1 }, .{ 256, 1, 1 }, true); try x.project(W.head, s.x, 0, s.logits_all, 0, n); - for (out.draws, 0..) |d, i| if (d) |pick_| pick(x, bo(s.logits_all, i * c.vocab * 2), pick_); + var i: usize = 0; + while (i < out.draws.len) : (i += 1) { + const d = out.draws[i] orelse continue; + if (d.how == .greedy) { + pick(x, bo(s.logits_all, i * c.vocab * 2), d); + continue; + } + // sampled rows in a run share one launch, a threadgroup a row: each row's bits are its launch alone's + var j = i + 1; + while (j < out.draws.len and follows(d, out.draws[j], j - i)) j += 1; + sampleRows(x, bo(s.logits_all, i * c.vocab * 2), out.draws[i..j]); + i = j - 1; + } } 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); @@ -183,43 +195,46 @@ pub fn seconds() f64 { /// The draw of one logits row on the GPU into `d.out`: fl_argmax, or the keyed sampler one 1024-thread threadgroup. fn pick(x: Enc, logits: B, d: Draw) void { + if (d.how == .sampled) return sampleRows(x, logits, &[_]?Draw{d}); const e = x.e; - const vocab: u32 = x.m.config.vocab; - switch (d.how) { - .greedy => { - e.setPipeline(x.m.pipe(.argmax)); - e.setBuffer(logits.buf, logits.off, 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.buf, logits.off, 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.setPipeline(x.m.pipe(.argmax)); + e.setBuffer(logits.buf, logits.off, 0); + e.setBuffer(d.out.buf, d.out.off, 1); + e.setValue(@as(u32, x.m.config.vocab), 2); e.dispatchGroups(mtl.Size.of(1, 1, 1), mtl.Size.of(1024, 1, 1)); } +/// Whether `next` draws with `first`'s sampler into the slot `k` after first's, so one launch draws both. +fn follows(first: Draw, next: ?Draw, k: usize) bool { + const d = next orelse return false; + if (d.how != .sampled) return false; + const whole = lanes.gpu_full.fullVocabulary(first.how.sampled.sampling); + return lanes.gpu_full.fullVocabulary(d.how.sampled.sampling) == whole and d.out.buf.id == first.out.buf.id and d.out.off == first.out.off + 4 * k; +} + +/// Sampled draws of consecutive logits rows into consecutive slots: the keyed sampler, a 1024-thread threadgroup a row. +fn sampleRows(x: Enc, logits: B, ds: []const ?Draw) void { + const e = x.e; + const first = ds[0].?; + // the kernels index every setting by row; one row pads to 8, as Nemotron's launches pad them + var l: lanes.gpu_rule.Launch(st.batch_rows) = .{}; + for (ds) |d| l.put(d.?.how.sampled.sampling, d.?.how.sampled.position); + const n = l.padded(); + const whole = lanes.gpu_full.fullVocabulary(first.how.sampled.sampling); + e.setPipeline(if (whole) x.m.sample_full else x.m.sample); + e.setBuffer(logits.buf, logits.off, 0); + e.setBytes(std.mem.sliceAsBytes(l.seeds[0 .. 2 * n]), 1); + e.setBytes(std.mem.sliceAsBytes(l.positions[0..n]), 2); + e.setBytes(std.mem.sliceAsBytes(l.cfgs[0 .. 4 * n]), 3); + e.setBytes(std.mem.sliceAsBytes(l.caps[0..n]), 4); + e.setBuffer(first.out.buf, first.out.off, 5); + if (whole) { + e.setBuffer(first.out.buf, first.out.off, 6); + e.setValue(@as(u32, x.m.config.vocab), 7); + } + e.dispatchGroups(mtl.Size.of(ds.len, 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; diff --git a/zig/src/families/gemma4/backend.zig b/zig/src/families/gemma4/backend.zig index 416afe6bd86..6a6c5a287d5 100644 --- a/zig/src/families/gemma4/backend.zig +++ b/zig/src/families/gemma4/backend.zig @@ -8,6 +8,7 @@ const fwd = @import("forward.zig"); const prompt = @import("prompt.zig"); const snapshot = @import("snapshot.zig"); const Model = @import("model.zig").Model; +const steps = @import("prefill_steps.zig"); const draw = @import("../qwen3_5/backend.zig").draw; const be = lanes.backend; @@ -21,6 +22,10 @@ pub const Metal = struct { /// Prompt chunks' activations: 512 rows on core affine_mm and the tensor-unit attention. prompt_scratch: prompt.Scratch, caches: std.AutoHashMapUnmanaged(*lanes.Stream, *st.Cache) = .empty, + /// Prompt passes a chunk a call (prefill_step) between rounds, by stream. + fills: std.AutoHashMapUnmanaged(*lanes.Stream, Fill) = .empty, + /// Prompt chunks run on `prompt_scratch`: a stepped chunk's tapped rows there are current while this matches. + prompt_gen: u64 = 0, follow: ?mtl.ResidencySet.Follow = null, /// Forwards run on `scratch`: a stream's tapped rows there are current while its tap's gen matches. gen: u64 = 0, @@ -52,6 +57,12 @@ pub const Metal = struct { self.gpa.destroy(cache.*); } self.caches.deinit(self.gpa); + var fills = self.fills.valueIterator(); + while (fills.next()) |f| { + f.spans.deinit(self.gpa); + if (f.rows) |b| b.deinit(); + } + self.fills.deinit(self.gpa); self.scratch.deinit(); self.prompt_scratch.deinit(); self.gpa.destroy(self); @@ -124,7 +135,7 @@ pub const Metal = struct { } 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 } }; + return .{ .ptr = self, .vtable = &.{ .prefill = prefillFn, .prefill_step = prefillStepFn, .cancel_prefill = cancelPrefillFn, .reports_fill = true, .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 } }; } fn cast(ptr: *anyopaque) *Metal { @@ -175,7 +186,13 @@ pub const Metal = struct { /// 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 t = (try self.cacheOf(stream)).tap; + const cache = try self.cacheOf(stream); + const t = cache.tap; + // a stepped prompt's latest chunk (prefillStepFn), while no other prompt chunk has rewritten the prompt scratch + const c = cache.chunk_tap; + const in_tap = t.buf != null and steps.holds(.{ .start = t.start, .rows = t.rows, .gen = t.gen }, self.gen, start, count); + if (!in_tap and taps.len == self.model.taps and c.buf != null and steps.holds(.{ .start = c.start, .rows = c.rows, .gen = c.gen }, self.prompt_gen, start, count)) + return .{ .buffer = @intFromPtr(c.buf.?.id), .offset = c.off + (start - c.start) * self.tapBytes(), .rows = count, .row_bytes = @intCast(self.tapBytes()), .space = .device, .dtype = .bf16 }; if (taps.len != self.model.taps or t.buf == null) return error.UnpreparedGemmaTaps; if (t.gen) |g| if (g != self.gen) return error.StaleGemmaTaps; if (count == 0 or start < t.start or start + count > t.start + t.rows) return error.GemmaTapsNotHeld; @@ -183,7 +200,54 @@ pub const Metal = struct { return .{ .buffer = @intFromPtr(t.buf.?.id), .offset = t.off + (start - t.start) * width, .rows = count, .row_bytes = @intCast(width), .space = .device, .dtype = .bf16 }; } + /// A stream's prompt pass in progress (prefill_step): its next row, its images' rows and their spans. + const Fill = struct { pass: steps.Fill, spans: std.ArrayList(prompt.Span) = .empty, rows: ?mtl.Buffer = null }; + + /// One chunk's work for `steps.step`: the pass, the drafter's rows (a sink, or `later` via featuresFn), marks. + const Run = struct { + m: *Metal, + cache: *st.Cache, + spans: []const prompt.Span, + sink: ?be.FeatureSink, + later: bool, + + pub fn run(r: Run, stream: *lanes.Stream, at: usize, end: usize) !void { + const self = r.m; + const ids = stream.prompt(); + try prompt.run(self.model, &self.prompt_scratch, r.cache, ids[at..end], r.spans); + self.prompt_gen += 1; + if (r.sink != null or r.later) { + const width = self.tapBytes(); + const rows = self.prompt_scratch.taps.?; + if (r.sink) |k| try k.take(k.ptr, stream, .{ .buffer = @intFromPtr(rows.id), .rows = @intCast(end - at), .row_bytes = @intCast(width), .space = .device, .dtype = .bf16 }, at); + // a stepped pass's rows stay in the prompt scratch until the next chunk runs: featuresFn serves them + if (r.later) r.cache.chunk_tap = .{ .buf = rows, .start = at, .rows = end - at, .gen = self.prompt_gen }; + if (end == ids.len) { // the prompt's last row, kept for the first draft; the scratch may be reused + const last = try self.model.device.buffer(width, mtl.ResourceOptions.shared | mtl.ResourceOptions.untracked); + r.cache.setLastTap(last); + @memcpy(last.slice(u8, width), rows.slice(u8, st.chunk_rows * width)[(end - 1 - at) * width ..][0..width]); + r.cache.tap = .{ .buf = last, .start = ids.len - 1, .rows = 1 }; + } + } + lanes.prefill_widths.completed(self.gpa, stream, end - at); + if (end == ids.len) @memcpy(r.cache.logits.slice(u16, cfg.vocab), self.prompt_scratch.logits.slice(u16, cfg.vocab)); + } + + pub fn keep(_: Run, stream: *lanes.Stream, at: u32) void { + if (stream.reuse.hook) |k| k.at(k.ptr, stream, at); + } + }; + fn prefillWith(self: *Metal, stream: *lanes.Stream, sink: ?be.FeatureSink) !void { + const f = try self.opening(stream); + errdefer self.drop(stream); + const r: Run = .{ .m = self, .cache = try self.cacheOf(stream), .spans = f.spans.items, .sink = sink, .later = false }; + while (!try steps.step(r, stream, &f.pass, st.chunk_rows, f.spans.items, false)) {} + self.closing(stream); + } + + /// The stream's cache made (a kept state restored into it) and its images encoded: its pass from `cache.len`. + fn opening(self: *Metal, stream: *lanes.Stream) !*Fill { const ids = stream.prompt(); if (ids.len == 0 or ids.len + stream.max_new > self.options.capacity or self.caches.contains(stream)) return error.InvalidGemmaPrompt; const capacity = @min(self.options.capacity, (ids.len + stream.max_new + st.max_rows + 63) / 64 * 64); @@ -203,39 +267,48 @@ pub const Metal = struct { if (snapshot.restore(self.gpa, self.model.queue, snap, cache)) stream.cached = snap.at else |_| stream.reuse_failed = true; } else stream.reuse_failed = true; } - var spans: std.ArrayList(prompt.Span) = .empty; - defer spans.deinit(self.gpa); - const rows_buf = try self.encodeImages(stream, cache.len, &spans); - defer if (rows_buf) |b| b.deinit(); - var at: usize = cache.len; - while (at < ids.len) { - if (stream.isCancelled()) return error.Cancelled; - var end = @min(ids.len, at + st.chunk_rows); - // planned chunk starts and kept marks cut a chunk (resumed and fresh passes cut alike past them) - for ([_][]const u32{ stream.chunks, stream.reuse.marks }) |cuts| for (cuts) |x| if (x > at and x < end) { - end = x; - }; - // an image's rows see each other on sliding layers: no cut inside one (before it, or past it when it leads) - for (spans.items) |span| if (span.at < end and span.at + span.n > end) { - end = if (span.at > at) span.at else span.at + span.n; - }; - try prompt.run(self.model, &self.prompt_scratch, cache, ids[at..end], spans.items); - if (sink) |k| { - const width = self.tapBytes(); - const rows = self.prompt_scratch.taps.?; - try k.take(k.ptr, stream, .{ .buffer = @intFromPtr(rows.id), .rows = @intCast(end - at), .row_bytes = @intCast(width), .space = .device, .dtype = .bf16 }, at); - if (end == ids.len) { // the prompt's last row, kept for the first draft (another prompt may reuse the scratch) - const last = try self.model.device.buffer(width, mtl.ResourceOptions.shared | mtl.ResourceOptions.untracked); - cache.setLastTap(last); - @memcpy(last.slice(u8, width), rows.slice(u8, st.chunk_rows * width)[(end - 1 - at) * width ..][0..width]); - cache.tap = .{ .buf = last, .start = ids.len - 1, .rows = 1 }; - } - } - lanes.prefill_widths.completed(self.gpa, stream, end - at); - at = end; - if (std.mem.indexOfScalar(u32, stream.reuse.marks, @intCast(cache.len)) != null) if (stream.reuse.hook) |k| k.at(k.ptr, stream, @intCast(cache.len)); + var f: Fill = .{ .pass = .{ .at = cache.len } }; + errdefer f.spans.deinit(self.gpa); + f.rows = try self.encodeImages(stream, cache.len, &f.spans); + errdefer if (f.rows) |b| b.deinit(); + try self.fills.put(self.gpa, stream, f); + stream.fill_at.store(@intCast(cache.len), .monotonic); // what the restore kept: 0 when none + return self.fills.getPtr(stream).?; + } + + /// The pass is over, or the stream left mid-pass: its images' rows and spans freed. + fn closing(self: *Metal, stream: *lanes.Stream) void { + var entry = self.fills.fetchRemove(stream) orelse return; + entry.value.spans.deinit(self.gpa); + if (entry.value.rows) |b| b.deinit(); + } + + /// A pass that failed: its fill and its cache go, as the whole pass's error left them. + fn drop(self: *Metal, stream: *lanes.Stream) void { + self.closing(stream); + if (self.caches.fetchRemove(stream)) |entry| { + entry.value.deinit(); + self.gpa.destroy(entry.value); } - @memcpy(cache.logits.slice(u16, cfg.vocab), self.prompt_scratch.logits.slice(u16, cfg.vocab)); + } + + /// One chunk a call at the whole pass's cuts (`max_rows` is never set: this family declares no chunk_invariant). + fn prefillStepFn(ptr: *anyopaque, stream: *lanes.Stream, _: u32) !bool { + const self = cast(ptr); + const f = self.fills.getPtr(stream) orelse try self.opening(stream); + errdefer self.drop(stream); + // a drafting stream's wrapper absorbs each chunk after the call (featuresFn): its marks keep at the next call + const later = stream.drafts and self.prompt_scratch.taps != null; + const r: Run = .{ .m = self, .cache = try self.cacheOf(stream), .spans = f.spans.items, .sink = null, .later = later }; + const done = try steps.step(r, stream, &f.pass, st.chunk_rows, f.spans.items, later); + if (done) self.closing(stream); + return done; + } + + /// The host cancels between chunks: the last landed chunk's state is kept (no prompt work runs). + fn cancelPrefillFn(ptr: *anyopaque, stream: *lanes.Stream) !void { + const self = cast(ptr); + if (self.fills.get(stream)) |f| stream.keepInterruptedPrefill(@intCast(f.pass.at)); } /// The stream's images from `from` on through the tower into one buffer of rows (null: none), a span each. @@ -396,6 +469,7 @@ pub const Metal = struct { fn releaseFn(ptr: *anyopaque, stream: *lanes.Stream) void { const self = cast(ptr); + self.closing(stream); // a stream that left mid-pass if (self.caches.fetchRemove(stream)) |entry| { entry.value.deinit(); self.gpa.destroy(entry.value); @@ -411,6 +485,14 @@ const mask_words = (cfg.vocab + 31) / 32; const Pick = @import("tree_round_gpu").contract.Pick; +test "Gemma Metal steps: the backend steps its prompt passes, reports their fill and keeps a cancelled one's chunks" { + var b: Metal = undefined; + const v = b.backend().vtable; + // the lane host fills it a chunk a round (open.zig fills); the drafted wrapper steps too (features, reports_fill) + try std.testing.expect(v.prefill_step != null and v.reports_fill and v.cancel_prefill != null and v.features != null); + try std.testing.expect(!b.backend().chunk_invariant); // the host never caps its chunks (lane_host_fill.zig capRows) +} + test "zero grant: Gemma Metal assistant and DFlash retain tapped context through a long skip" { var b: Metal = undefined; b.options = .{ .capacity = 512, .streams = 16 }; diff --git a/zig/src/families/gemma4/cuda_assistant_weights.zig b/zig/src/families/gemma4/cuda_assistant_weights.zig index 37f37b56689..2d8053222e0 100644 --- a/zig/src/families/gemma4/cuda_assistant_weights.zig +++ b/zig/src/families/gemma4/cuda_assistant_weights.zig @@ -272,9 +272,21 @@ pub fn load(gpa: std.mem.Allocator, io: std.Io, d: *const cuda.Driver, s: cuda.S l.post_feedforward = try x.vector(try name(&buf, i, "post_feedforward_layernorm.weight"), hid); l.scalar = try x.vector(try name(&buf, i, "layer_scalar"), 1); } + try refuseLeftovers(&ck, error.UnusedAssistantTensors); // the assistant's own directory is bound here alone return w; } +/// `ck` names `get`/`expect` never took, refused with up to five named. +pub fn refuseLeftovers(ck: *const core.checkpoint.Checkpoint, comptime err: anyerror) !void { + var n: usize = 0; + for (ck.files.items) |*f| for (f.names.keys()) |k| { + if (ck.used.contains(k)) continue; + if (n < 5 and !@import("builtin").is_test) std.log.err("unused checkpoint tensor {s}", .{k}); + n += 1; + }; + if (n != 0) return err; +} + const fixture = @embedFile("fixtures/assistant_config.json"); test "the 12B's assistant is admitted against the 12B, and refused against the 31B" { @@ -321,3 +333,25 @@ test "a group quantizes as MLX's affine 4-bit: every value within half a step" { try std.testing.expect(@abs(q * bf(scale) + bf(bias) - bf(v)) <= @abs(bf(scale)) * 0.51); } } + +test "a stray assistant tensor refuses; a complete directory loads" { + const fix = core.checkpoint_fixture; + const a = std.testing.allocator; + const io = std.testing.io; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const data: [4]u16 = @splat(0x3f80); + const entries = [_]fix.Entry{ + .{ .name = "model.norm.weight", .dtype = "BF16", .shape = &.{4}, .bytes = std.mem.sliceAsBytes(&data) }, + .{ .name = "model.stray.weight", .dtype = "BF16", .shape = &.{4}, .bytes = std.mem.sliceAsBytes(&data) }, + }; + try fix.write(a, io, tmp.dir, "model.safetensors", &entries); + const dir = try std.fmt.allocPrint(a, ".zig-cache/tmp/{s}", .{tmp.sub_path}); + defer a.free(dir); + var ck = try core.checkpoint.Checkpoint.openModel(a, io, dir); + defer ck.close(); + _ = try ck.expect("model.norm.weight", .bf16, &.{4}); + try std.testing.expectError(error.UnusedAssistantTensors, refuseLeftovers(&ck, error.UnusedAssistantTensors)); + _ = try ck.expect("model.stray.weight", .bf16, &.{4}); + try refuseLeftovers(&ck, error.UnusedAssistantTensors); +} diff --git a/zig/src/families/gemma4/cuda_dflash.zig b/zig/src/families/gemma4/cuda_dflash.zig index bbe3a813bcf..81146a0cceb 100644 --- a/zig/src/families/gemma4/cuda_dflash.zig +++ b/zig/src/families/gemma4/cuda_dflash.zig @@ -114,7 +114,8 @@ const Weights = struct { }; fn load(gpa: std.mem.Allocator, io: std.Io, d: *const cuda.Driver, s: cuda.Stream, k: *const kern.Kernels, dir: []const u8, c: *const Config, w: *Weights) !void { - var ck = try core.checkpoint.Checkpoint.openModel(gpa, io, dir); + // the draft shares the model's directory: index only its own roots so `model.`/`vision_` names never count + var ck = try core.checkpoint.Checkpoint.openModelPrefixes(gpa, io, dir, &.{ "fc.", "hidden_norm.", "norm.", "layers." }); defer core.checkpoint.cache.close(&ck); var x: aw.Loader = .{ .gpa = gpa, .d = d, .s = s, .k = k, .ck = &ck, .bufs = &w.buffers }; const h = c.hidden; @@ -142,6 +143,18 @@ fn load(gpa: std.mem.Allocator, io: std.Io, d: *const cuda.Driver, s: cuda.Strea l.q_norm = try x.vector(try name(&buf, i, "self_attn.q_norm.weight"), dim); l.k_norm = try x.vector(try name(&buf, i, "self_attn.k_norm.weight"), dim); } + try refuseLeftovers(&ck, error.UnusedDFlashTensors); +} + +/// `ck` names `get`/`expect` never took, refused with up to five named. +pub fn refuseLeftovers(ck: *const core.checkpoint.Checkpoint, comptime err: anyerror) !void { + var n: usize = 0; + for (ck.files.items) |*f| for (f.names.keys()) |k| { + if (ck.used.contains(k)) continue; + if (n < 5 and !@import("builtin").is_test) std.log.err("unused checkpoint tensor {s}", .{k}); + n += 1; + }; + if (n != 0) return err; } /// One stream's context: each layer's keys then values, [kv heads, capacity, 128] bf16; the chain it holds. diff --git a/zig/src/families/gemma4/cuda_dflash_test.zig b/zig/src/families/gemma4/cuda_dflash_test.zig index 648e78da867..974ee1a4f49 100644 --- a/zig/src/families/gemma4/cuda_dflash_test.zig +++ b/zig/src/families/gemma4/cuda_dflash_test.zig @@ -2,6 +2,7 @@ const std = @import("std"); const cfg = @import("cuda_config.zig"); const dfl = @import("cuda_dflash.zig"); +const core = @import("core"); const stock = \\{"architectures":["DFlashDraftModel"],"dflash_config":{"mask_token_id":4,"target_layer_ids":[1,12,23,35,46,57]},"block_size":16, @@ -23,3 +24,29 @@ test "a zero, negative or oversized count is a bad config, not a trap" { try refused("\"sliding_window\":2048", "\"sliding_window\":0"); try refused("\"mask_token_id\":4", "\"mask_token_id\":-4"); } + +test "a stray draft tensor refuses; the shared dir's model and vision names never index" { + const fixture = @import("core").checkpoint_fixture; + const a = std.testing.allocator; + const io = std.testing.io; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const data: [4]u16 = @splat(0x3f80); + const entries = [_]fixture.Entry{ + .{ .name = "fc.weight", .dtype = "BF16", .shape = &.{4}, .bytes = std.mem.sliceAsBytes(&data) }, + .{ .name = "layers.0.self_attn.q_proj.weight", .dtype = "BF16", .shape = &.{4}, .bytes = std.mem.sliceAsBytes(&data) }, + .{ .name = "model.embed_tokens.weight", .dtype = "BF16", .shape = &.{4}, .bytes = std.mem.sliceAsBytes(&data) }, + .{ .name = "vision_tower.patch_embedder.input_proj.weight", .dtype = "BF16", .shape = &.{4}, .bytes = std.mem.sliceAsBytes(&data) }, + .{ .name = "layers.1.stray.weight", .dtype = "BF16", .shape = &.{4}, .bytes = std.mem.sliceAsBytes(&data) }, + }; + try fixture.write(a, io, tmp.dir, "model.safetensors", &entries); + const dir = try std.fmt.allocPrint(a, ".zig-cache/tmp/{s}", .{tmp.sub_path}); + defer a.free(dir); + var ck = try core.checkpoint.Checkpoint.openModelPrefixes(a, io, dir, &.{ "fc.", "hidden_norm.", "norm.", "layers." }); + defer ck.close(); + _ = try ck.expect("fc.weight", .bf16, &.{4}); + _ = try ck.expect("layers.0.self_attn.q_proj.weight", .bf16, &.{4}); + try std.testing.expectError(error.UnusedDFlashTensors, dfl.refuseLeftovers(&ck, error.UnusedDFlashTensors)); + _ = try ck.expect("layers.1.stray.weight", .bf16, &.{4}); + try dfl.refuseLeftovers(&ck, error.UnusedDFlashTensors); // model./vision_ names never indexed: nothing left over +} diff --git a/zig/src/families/gemma4/prefill_steps.zig b/zig/src/families/gemma4/prefill_steps.zig new file mode 100644 index 00000000000..68d880e8060 --- /dev/null +++ b/zig/src/families/gemma4/prefill_steps.zig @@ -0,0 +1,50 @@ +//! Gemma 4 Metal's prompt pass a chunk a call (#3021): today's cuts, a chunk a step, marks after the drafter's absorb. +const std = @import("std"); +const lanes = @import("lanes"); +const Stream = lanes.Stream; + +/// A chunk from `at`: `rows` at most, cut at planned starts and kept marks, never inside an image's span. +pub fn chunkEnd(len: usize, at: usize, rows: usize, chunks: []const u32, marks: []const u32, spans: anytype) usize { + var end = @min(len, at + rows); + // planned chunk starts and kept marks cut a chunk (resumed and fresh passes cut alike past them) + for ([_][]const u32{ chunks, marks }) |cuts| for (cuts) |x| if (x > at and x < end) { + end = x; + }; + // an image's rows see each other on sliding layers: no cut inside one (before it, or past it when it leads) + for (spans) |span| if (span.at < end and span.at + span.n > end) { + end = if (span.at > at) span.at else span.at + span.n; + }; + return end; +} + +/// A stream's pass in progress: its next chunk's first row, and a mark kept once its drafter has absorbed the chunk. +pub const Fill = struct { at: usize, mark: ?u32 = null }; + +/// One chunk of `s` from `f.at` through `r` (`run`, `keep`); `later` keeps marks at the next call. True once all in. +pub fn step(r: anytype, s: *Stream, f: *Fill, rows: usize, spans: anytype, later: bool) !bool { + if (f.mark) |m| r.keep(s, m); // the drafter absorbed the last chunk: the state kept there carries its context + f.mark = null; + if (s.isCancelled()) return error.Cancelled; + const len = s.prompt().len; + const end = chunkEnd(len, f.at, rows, s.chunks, s.reuse.marks, spans); + try r.run(s, f.at, end); + s.fill_at.store(@intCast(end), .monotonic); + f.at = end; + if (std.mem.indexOfScalar(u32, s.reuse.marks, @intCast(end)) != null) { + if (later and end < len) f.mark = @intCast(end) else r.keep(s, @intCast(end)); + } + return end == len; +} + +/// Rows a tap holds: `rows` from `start`, written at generation `gen` (null: current until rewritten by the stream). +pub const Held = struct { start: u64 = 0, rows: usize = 0, gen: ?u64 = null }; + +/// Whether `h` holds [start, start + count) and nothing has overwritten it since (its generation is `now`). +pub fn holds(h: Held, now: u64, start: u64, count: u32) bool { + if (h.gen) |g| if (g != now) return false; + return count > 0 and start >= h.start and start + count <= h.start + h.rows; +} + +test { + _ = @import("prefill_steps_test.zig"); +} diff --git a/zig/src/families/gemma4/prefill_steps_test.zig b/zig/src/families/gemma4/prefill_steps_test.zig new file mode 100644 index 00000000000..93a01c1d098 --- /dev/null +++ b/zig/src/families/gemma4/prefill_steps_test.zig @@ -0,0 +1,258 @@ +//! Gemma 4 Metal's stepped prompt pass on a recording fake: today's cuts, a decode between chunks, every chunk's taps. +const std = @import("std"); +const lanes = @import("lanes"); +const steps = @import("prefill_steps.zig"); +const be = lanes.backend; +const t = std.testing; +const gpa = t.allocator; + +const Span = struct { at: usize, n: usize }; +const Event = union(enum) { chunk: struct { id: u8, at: usize, end: usize }, keep: u32, decode: u8, absorb: struct { start: u64, rows: u32 } }; + +/// The cuts of main's whole loop (backend.zig before #3021), copied as they were: every stepped pass must equal them. +fn mainCuts(a: std.mem.Allocator, len: usize, from: usize, rows: usize, chunks: []const u32, marks: []const u32, spans: []const Span) ![][2]usize { + var out: std.ArrayList([2]usize) = .empty; + var at = from; + while (at < len) { + var end = @min(len, at + rows); + for ([_][]const u32{ chunks, marks }) |cuts| for (cuts) |x| if (x > at and x < end) { + end = x; + }; + for (spans) |span| if (span.at < end and span.at + span.n > end) { + end = if (span.at > at) span.at else span.at + span.n; + }; + try out.append(a, .{ at, end }); + at = end; + } + return out.toOwnedSlice(a); +} + +/// Records each chunk run and each kept mark, as Run does on the device. +const Rec = struct { + log: *std.ArrayList(Event), + pub fn run(r: Rec, s: *lanes.Stream, at: usize, end: usize) !void { + try r.log.append(gpa, .{ .chunk = .{ .id = s.id[0], .at = at, .end = end } }); + } + pub fn keep(r: Rec, _: *lanes.Stream, at: u32) void { + r.log.append(gpa, .{ .keep = at }) catch @panic("out of memory"); + } +}; + +/// A 1,300-token prompt: a planned start at 700, a kept mark at 900, an image over the 512-row cut (480..580). +const prompt_len = 1300; +const planned = [_]u32{700}; +const kept = [_]u32{900}; +const images = [_]Span{.{ .at = 480, .n = 100 }}; + +fn stream(prompt: []const u32, id: []const u8) !lanes.Stream { + return lanes.Stream.init(gpa, .{ .id = id, .prompt = prompt, .max_new = 4, .chunks = &planned, .reuse = .{ .marks = &kept } }); +} + +test "Gemma Metal steps: one call runs one chunk at today's cut, and the calls' chunks are the whole loop's" { + var ids: [prompt_len]u32 = undefined; + for (&ids, 0..) |*x, i| x.* = @intCast(i % 97 + 3); + const want = try mainCuts(gpa, prompt_len, 0, 512, &planned, &kept, &images); + defer gpa.free(want); + try t.expectEqualSlices([2]usize, &.{ .{ 0, 480 }, .{ 480, 700 }, .{ 700, 900 }, .{ 900, 1300 } }, want); + for ([_]bool{ false, true }) |later| { // the whole pass (Run with a sink) and a drafting stream's steps + var s = try stream(&ids, "s"); + defer s.deinit(gpa); + var log: std.ArrayList(Event) = .empty; + defer log.deinit(gpa); + var f: steps.Fill = .{ .at = 0 }; + for (want, 0..) |w, i| { + const before = log.items.len; + const done = try steps.step(Rec{ .log = &log }, &s, &f, 512, &images, later); + try t.expectEqual(i + 1 == want.len, done); + const ran = for (log.items[before..]) |e| { + if (e == .chunk) break e.chunk; + } else return error.NoChunk; + try t.expectEqual(w, [2]usize{ ran.at, ran.end }); // exactly today's chunk + var n: usize = 0; + for (log.items[before..]) |e| n += @intFromBool(e == .chunk); + try t.expectEqual(@as(usize, 1), n); // and only one a call + try t.expectEqual(@as(u32, @intCast(w[1])), s.fill_at.load(.monotonic)); + } + // the mark at 900 is kept before the chunk after it in both: with `later` at that next call's start + try t.expectEqual(@as(usize, 5), log.items.len); + try t.expectEqual(Event{ .keep = 900 }, log.items[3]); + } + // a resumed pass from the planned start at 700 cuts as the whole loop does from there + const resumed = try mainCuts(gpa, prompt_len, 700, 512, &planned, &kept, &images); + defer gpa.free(resumed); + var s = try stream(&ids, "s"); + defer s.deinit(gpa); + var log: std.ArrayList(Event) = .empty; + defer log.deinit(gpa); + var f: steps.Fill = .{ .at = 700 }; + while (!try steps.step(Rec{ .log = &log }, &s, &f, 512, &images, false)) {} + var got: std.ArrayList([2]usize) = .empty; + defer got.deinit(gpa); + for (log.items) |e| if (e == .chunk) try got.append(gpa, .{ e.chunk.at, e.chunk.end }); + try t.expectEqualSlices([2]usize, resumed, got.items); +} + +/// The lanes fake with Gemma's stepping in front: its prompt passes a chunk a call at `rows` (4 here), logged. +const Gem = struct { + fake: lanes.fake.Fake, + inner: be.Backend = undefined, + fills: std.AutoHashMapUnmanaged(*lanes.Stream, steps.Fill) = .empty, + log: std.ArrayList(Event) = .empty, + held: std.AutoHashMapUnmanaged(*lanes.Stream, steps.Held) = .empty, + prompt_gen: u64 = 0, + vt: be.Backend.VTable = undefined, + + var current: *Gem = undefined; + const rows = 4; + + fn init(x: *Gem) be.Backend { + current = x; + x.inner = x.fake.backend(); + x.vt = x.inner.vtable.*; + x.vt.prefill_step = prefillStep; + x.vt.reports_fill = true; + x.vt.queue = queue; + x.vt.verify = verify; + x.vt.features = features; + return .{ .ptr = x.inner.ptr, .vtable = &x.vt }; + } + + fn deinit(x: *Gem) void { + x.fills.deinit(gpa); + x.held.deinit(gpa); + x.log.deinit(gpa); + x.fake.deinit(); + } + + const Run = struct { + pub fn run(_: Run, s: *lanes.Stream, at: usize, end: usize) !void { + const x = current; + x.prompt_gen += 1; + try x.held.put(gpa, s, .{ .start = at, .rows = end - at, .gen = x.prompt_gen }); // the scratch's rows + try x.log.append(gpa, .{ .chunk = .{ .id = s.id[0], .at = at, .end = end } }); + } + pub fn keep(_: Run, _: *lanes.Stream, at: u32) void { + current.log.append(gpa, .{ .keep = at }) catch @panic("out of memory"); + } + }; + + fn prefillStep(ptr: *anyopaque, s: *lanes.Stream, _: u32) anyerror!bool { + const x = current; + const got = try x.fills.getOrPut(gpa, s); + if (!got.found_existing) got.value_ptr.* = .{ .at = 0 }; + const done = try steps.step(Run{}, s, got.value_ptr, rows, &[_]Span{}, s.drafts); + if (done) { + _ = x.fills.remove(s); + try x.inner.vtable.prefill(ptr, s); // the fake's own state: its tokens follow the whole prompt + } + return done; + } + + fn queue(ptr: *anyopaque, s: *lanes.Stream, feed: be.Feed, position: u64) anyerror!u64 { + try current.log.append(gpa, .{ .decode = s.id[0] }); + return current.inner.vtable.queue(ptr, s, feed, position); + } + + fn verify(ptr: *anyopaque, windows: []const be.Window, out: []be.Verified) anyerror!void { + for (windows) |w| try current.log.append(gpa, .{ .decode = w.stream.id[0] }); + return current.inner.vtable.verify(ptr, windows, out); + } + + /// featuresFn's rule: the latest chunk's rows, while no later chunk has rewritten the scratch. + fn features(_: *anyopaque, s: *lanes.Stream, _: []const u32, start: u64, count: u32) anyerror!be.Features { + const x = current; + const h = x.held.get(s) orelse return error.GemmaTapsNotHeld; + if (!steps.holds(h, x.prompt_gen, start, count)) return error.GemmaTapsNotHeld; + return .{ .buffer = h.start, .rows = count, .row_bytes = 2, .space = .host, .dtype = .bf16 }; + } +}; + +test "Gemma Metal steps: another stream decodes between two chunks of a long prompt" { + var costs: [16]lanes.config.Cost = undefined; + for (&costs, 1..) |*c, w| c.* = .{ .width = @intCast(w), .ms = 5.0 + 0.8 * @as(f64, @floatFromInt(w)) }; + var cfg = try lanes.config.Config.init(gpa, .{ .exact_width = 16, .gpu_tokens = true, .window_costs = &costs, .hidden_rows = true, .batch_rows = 32, .max_streams = 8 }, 16, 15); + defer cfg.deinit(gpa); + var gem: Gem = .{ .fake = .{ .gpa = gpa } }; + defer gem.deinit(); + var clock: lanes.fake.FixedClock = .{}; + var engine = lanes.Engine.init(gpa, &cfg, gem.init(), clock.clock()); + defer engine.deinit(); + try t.expect(engine.fills()); // the lane host steps this backend's prompts (lane_host_fill.zig), as it steps CUDA's + const short = [_]u32{ 5, 6, 7 }; + const long = [_]u32{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }; + var a = try lanes.Stream.init(gpa, .{ .id = "a", .prompt = &short, .max_new = 20, .drafts = false }); + defer a.deinit(gpa); + var b = try lanes.Stream.init(gpa, .{ .id = "b", .prompt = &long, .max_new = 4, .drafts = false }); + defer b.deinit(gpa); + while (!try engine.fillStream(&a, gem.fake.prefill_count == 0)) {} + var first = true; + while (!try engine.fillStream(&b, first)) { + first = false; + try engine.step(); // stream a's round between b's chunks + } + // b's three chunks, each followed by a's decode before the next + var seen: [3]usize = undefined; + var n: usize = 0; + for (gem.log.items, 0..) |e, i| if (e == .chunk and e.chunk.id == 'b') { + seen[n] = i; + n += 1; + }; + try t.expectEqual(@as(usize, 3), n); + for (seen[0..2], seen[1..3]) |from, to| { + const between = for (gem.log.items[from..to]) |e| { + if (e == .decode and e.decode == 'a') break true; + } else false; + try t.expect(between); + } + while (engine.activeCount() > 0) try engine.step(); +} + +/// A drafter that records the rows it absorbs and the chunk each came from (Features.buffer: the chunk's start). +const Head = struct { + log: *std.ArrayList(Event), + fn drafter(x: *Head) lanes.drafter.Drafter { + return .{ .ptr = x, .vtable = &.{ .taps = taps, .facts = facts, .open = open, .absorb = absorb, .hold = hold, .held = held, .release = release } }; + } + fn taps(_: *anyopaque) []const u32 { + return &.{ 3, 7 }; + } + fn facts(_: *anyopaque) lanes.drafter.Facts { + return .{ .depth = 2, .step_ms = 0.5 }; + } + fn open(_: *anyopaque, _: *lanes.Stream) anyerror!void {} + fn absorb(ptr: *anyopaque, items: []const lanes.drafter.Absorb) anyerror!void { + const x: *Head = @ptrCast(@alignCast(ptr)); + for (items) |it| { + try t.expectEqual(it.start, it.features.buffer); // the rows came from the chunk that starts there + try x.log.append(gpa, .{ .absorb = .{ .start = it.start, .rows = it.features.rows } }); + } + } + fn hold(_: *anyopaque, _: []const lanes.drafter.Hold) anyerror!void {} + fn held(_: *anyopaque, _: []const *lanes.Stream, out: []const []u32) anyerror!void { + for (out) |o| @memset(o, 0); + } + fn release(_: *anyopaque, _: *lanes.Stream) void {} +}; + +test "Gemma Metal steps: a drafter absorbs every chunk's tapped rows, and a mark keeps after its chunk's absorb" { + var gem: Gem = .{ .fake = .{ .gpa = gpa } }; + defer gem.deinit(); + var head: Head = .{ .log = &gem.log }; + var wrapped = try lanes.drafted.Drafted.init(gpa, gem.init(), head.drafter()); + defer wrapped.deinit(); + const backend = wrapped.backend(); + try t.expect(backend.vtable.prefill_step != null); // the wrapper steps: the target steps, reports fill, serves taps + const long = [_]u32{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }; + var s = try lanes.Stream.init(gpa, .{ .id = "d", .prompt = &long, .max_new = 4, .reuse = .{ .marks = &.{8} } }); + defer s.deinit(gpa); + defer backend.vtable.release(backend.ptr, &s); + while (!try backend.vtable.prefill_step.?(backend.ptr, &s, 0)) {} + const want = [_]Event{ + .{ .chunk = .{ .id = 'd', .at = 0, .end = 4 } }, .{ .absorb = .{ .start = 0, .rows = 4 } }, + .{ .chunk = .{ .id = 'd', .at = 4, .end = 8 } }, .{ .absorb = .{ .start = 4, .rows = 4 } }, + .{ .keep = 8 }, // the state at 8 is kept once the drafter holds rows 4..8: its context comes with it + .{ .chunk = .{ .id = 'd', .at = 8, .end = 12 } }, .{ .absorb = .{ .start = 8, .rows = 3 } }, // the last: later + }; + try t.expectEqual(want.len, gem.log.items.len); + for (want, gem.log.items) |w, g| try t.expectEqual(w, g); +} diff --git a/zig/src/families/gemma4/state.zig b/zig/src/families/gemma4/state.zig index 671752c0ce2..599c9b6d4b1 100644 --- a/zig/src/families/gemma4/state.zig +++ b/zig/src/families/gemma4/state.zig @@ -31,6 +31,8 @@ pub const Cache = struct { logits: mtl.Buffer, /// The drafter's rows: the prompt's last (in `last_tap`), then each verify's in the scratch. tap: Tap = .{}, + /// A stepped prompt's latest chunk of tapped rows, in the prompt scratch (its gen: the backend's prompt_gen). + chunk_tap: Tap = .{}, last_tap: ?mtl.Buffer = null, follow: ?mtl.ResidencySet.Follow = null, diff --git a/zig/src/families/gemma4/weights.zig b/zig/src/families/gemma4/weights.zig index 365fcacd375..0854ea0171a 100644 --- a/zig/src/families/gemma4/weights.zig +++ b/zig/src/families/gemma4/weights.zig @@ -27,9 +27,9 @@ pub const Linear = struct { /// The row path's weights (a chip without tensor units): the checkpoint's arrays as stored. raw: ?rowp.Weights = null, - /// The reg kernel's width, which reads the group sums its input's kernel wrote; others sum their input themselves. + /// The reg kernel's widths (4-, 5-, or 6-bit g64 on whole tiles), reading group sums from the input kernel. pub fn reg(x: Linear) bool { - return std.meta.eql(x.format, fast); + return x.format.group == cfg.group and x.n % 32 == 0 and (x.format.bits == 4 or x.format.bits == 5 or x.format.bits == 6); } /// `rows` of x [rows, k] through a general-unpack pipeline, which takes 16 rows an encode: y's rows y_stride apart. @@ -362,7 +362,7 @@ fn stack(gpa: std.mem.Allocator, device: mtl.Device, r: Src, owned: *std.ArrayLi return s; } -/// MLX affine words, scales and biases [x.n, x.k] at x's width in the lane layout (reg order at 4/64). +/// MLX affine words, scales and biases [x.n, x.k] at x's width in the lane layout (reg order at 4/5/6-bit g64). pub fn packArrays(gpa: std.mem.Allocator, device: mtl.Device, owned: *std.ArrayList(mtl.Buffer), geo: cfg.Geometry, words: []const u32, scales: []const u16, biases: []const u16, x: Linear) !Linear { if (!device.tensorUnits()) return packRows(gpa, device, owned, words, scales, biases, x); const l = layout(geo, x); @@ -371,7 +371,7 @@ pub fn packArrays(gpa: std.mem.Allocator, device: mtl.Device, owned: *std.ArrayL const sb = try device.buffer(l.metadataElements() * 2, shared); errdefer sb.deinit(); try lane.pack(l, words, scales, biases, wb.slice(u32, l.weightWords()), sb.slice(u16, l.metadataElements())); - if (l.reg) try lane.regOrder(device, &.{.{ .w = .{ .buf = wb }, .n = x.n, .k = x.k }}); + if (l.reg) try lane.regOrder(device, &.{.{ .w = .{ .buf = wb }, .n = x.n, .k = x.k, .bits = x.format.bits }}); try owned.ensureUnusedCapacity(gpa, 2); owned.appendAssumeCapacity(wb); owned.appendAssumeCapacity(sb); diff --git a/zig/src/families/glm/cuda.zig b/zig/src/families/glm/cuda.zig index b2ad60c6f0c..394e488e33e 100644 --- a/zig/src/families/glm/cuda.zig +++ b/zig/src/families/glm/cuda.zig @@ -44,6 +44,8 @@ pub const native = @import("cuda_native.zig"); pub const snapshots = @import("cuda_snapshots.zig"); pub const kv_host = @import("cuda_kv_host.zig"); pub const pdl = @import("cuda_pdl.zig"); +pub const disk_image = @import("cuda_disk_image.zig"); +pub const disk_ranks = @import("cuda_disk_ranks.zig"); test { _ = lane_costs; @@ -74,6 +76,8 @@ test { _ = prompt_solo; _ = @import("cuda_l2pf.zig"); _ = prompt_pair; + _ = @import("cuda_disk_image.zig"); + _ = @import("cuda_disk_ranks_test.zig"); _ = experts; _ = exl3; _ = vision; diff --git a/zig/src/families/glm/cuda_disk_image.zig b/zig/src/families/glm/cuda_disk_image.zig new file mode 100644 index 00000000000..ce6bfc18760 --- /dev/null +++ b/zig/src/families/glm/cuda_disk_image.zig @@ -0,0 +1,322 @@ +//! A GLM kept state's disk image on one rank: its parts at a position, and where each image byte sits in its lease. +const std = @import("std"); +const cuda = @import("cuda"); +const st_mod = @import("cuda_state.zig"); +const sparse = @import("cuda_sparse.zig"); +const Config = @import("config.zig").Config; +const pages = @import("cuda_snapshot_pages.zig"); +const State = st_mod.State; +const window_rows = st_mod.window_rows; + +/// The image's first bytes: the format, the position, the head's rows, both ring bases, the KDA copy bits, the layout. +pub const Words = struct { + at: u64, + mtp_len: u64, + base: u64, + mtp_base: u64, + cur: u64, + world: u64, // the ranks that wrote it + layout: Layout = .unsplit, + owner: u64 = no_owner, // the rank holding its latent rows alone (split layouts); unsplit: no_owner + + pub const count = 9; + pub const bytes: u64 = count * 8; + const format: u64 = 1; + + /// Which rows each rank's image holds: unsplit, every rank every row (the only layout written so far). + pub const Layout = enum(u64) { unsplit = 0, _ }; + pub const no_owner: u64 = std.math.maxInt(u64); + + pub fn encode(w: Words) [count]u64 { + return .{ format, w.at, w.mtp_len, w.base, w.mtp_base, w.cur, w.world, @backingInt(w.layout), w.owner }; + } + + /// Words read back, refused by name unless this format at `at`, written by `world` ranks in this server's `layout`. + pub fn decode(x: [count]u64, at: u32, world: u32, layout: Layout) !Words { + if (x[0] != format or x[1] != at) return error.DiskWords; + if (x[6] != world) return error.DiskWorld; + const l: Layout = @fromBackingInt(@intCast(x[7])); + if (l != layout) return error.DiskLayout; + if (if (l == .unsplit) x[8] != no_owner else x[8] >= world) return error.DiskLayout; + return .{ .at = x[1], .mtp_len = x[2], .base = x[3], .mtp_base = x[4], .cur = x[5], .world = x[6], .layout = l, .owner = x[8] }; + } +}; + +/// A part as the rows store takes it: `row` bytes for each `per` tokens from position 0, or the state's own (row 0). +pub const Part = struct { bytes: u64, row: u32 = 0, per: u32 = 1 }; + +/// `len` image bytes from `img`: the words, `lease` bytes into the state's lease, or zeros the lease does not hold. +pub const Seg = struct { img: u64, len: u64, from: union(enum) { words, lease: u64, zeros } }; + +/// What a rank's kept state holds, read from a sequence of the engine (its addresses are not used past here). +pub const Shape = struct { + prefix: u64, // the sequence's own fields before its caches: KDA conv and states, a window's saved rows + tail: u64, // its fields after them: the head's position and first-draft row + layers: u32, // DSA layers, whose rows are shared by position + latent: u32, // a latent row's bytes + scales: bool, // fp8 latent rows: a 4-byte scale each + ring_rows: u32, + ring_row: u32, + pk_rows: u32, + pooled_row: u32, + capacity: u32, + head: bool, // the MTP head's caches are kept (drafting) + window: u64, // the prefix's bytes before a verify window's rows (its KDA projections and saves, read by its keep) + draft: u64, // the tail's bytes before the first-draft row (written at a prompt pass's end) + + pub fn of(st: *const State, c: *const Config, capacity: usize, head: bool) !Shape { + if (st.rings.len == 0) return error.SnapshotShape; + const base = st.arena.buf.ptr; + const first = if (st.table != 0) st.rings[0] else if (st.caches.len > 0) st.caches[0].lc else st.mtp_caches.lc; + const end = if (st.table != 0) st.table else base + st.arena.buf.len; + if (first < base or st.mtp_pos_dev < first or end < st.mtp_pos_dev) return error.SnapshotShape; + if (st.proj < base or first < st.proj or st.prompt_hidden < st.mtp_pos_dev or end < st.prompt_hidden) return error.SnapshotShape; + const fp8 = st.mtp_caches.ls != 0; + return .{ + .window = st.proj - base, + .draft = st.prompt_hidden - st.mtp_pos_dev, + .prefix = first - base, + .tail = end - st.mtp_pos_dev, + .layers = @intCast(st.caches.len), + .latent = c.kv_lora * @as(u32, if (fp8) 1 else 2), + .scales = fp8, + .ring_rows = @intCast(st.ring_rows), + .ring_row = @intCast(st.ring_row), + .pk_rows = @intCast(capacity / sparse.pool + 2), + .pooled_row = c.i_dim * 2, + .capacity = @intCast(capacity), + .head = head, + }; + } + + /// Rows the image keeps of the head's caches at `at`: a verify window past it, as the cache charges a state. + pub fn headRows(sh: Shape, at: u32) u32 { + return @min(sh.capacity, at + window_rows); + } +}; + +/// One cache's parts in the lease's order, for `n` rows: latent, scales, the two index rings, the pooled keys. +fn cache(sh: Shape, n: u64) [5]u64 { + return .{ + n * sh.latent, + if (sh.scales) n * 4 else 0, + @min(n, sh.ring_rows) * sh.ring_row, + @min(n, sh.ring_rows) * sh.ring_row, + @min(n / sparse.pool + 2, sh.pk_rows) * sh.pooled_row, + }; +} + +/// The longest state an image holds: the capacity's whole pools (`parts` takes no other position). +pub fn longest(sh: Shape) u32 { + return sh.capacity - sh.capacity % sparse.pool; +} + +/// The image at `at` (a chunk start): the words, the prefix, each DSA layer's rows, the head's caches, the tail. +pub fn parts(sh: Shape, at: u32, out: *std.ArrayList(Part), a: std.mem.Allocator) !void { + if (at == 0 or at % sparse.pool != 0 or at > sh.capacity) return error.SnapshotShape; + try out.appendSlice(a, &.{ .{ .bytes = Words.bytes }, .{ .bytes = sh.prefix } }); + const pooled: u64 = at / sparse.pool; + for (0..sh.layers) |_| { + const c = cache(sh, at); + try out.append(a, .{ .bytes = c[0], .row = sh.latent }); + if (sh.scales) try out.append(a, .{ .bytes = c[1], .row = 4 }); + try out.appendSlice(a, &.{ .{ .bytes = c[2] }, .{ .bytes = c[3] } }); + // whole pools are rows by position; the pool past them and the spare row stay the state's own + try out.appendSlice(a, &.{ .{ .bytes = pooled * sh.pooled_row, .row = sh.pooled_row, .per = sparse.pool }, .{ .bytes = c[4] - pooled * sh.pooled_row } }); + } + if (sh.head) for (cache(sh, sh.headRows(at))) |n| if (n > 0) try out.append(a, .{ .bytes = n }); + try out.append(a, .{ .bytes = sh.tail }); +} + +/// The image's segments in order for a state at `at` whose head holds `mtp_len` rows (0 without a head). +pub fn segments(sh: Shape, at: u32, mtp_len: u64, out: *std.ArrayList(Seg), a: std.mem.Allocator) !void { + if (sh.head and mtp_len > sh.headRows(at)) return error.SnapshotShape; + var img: u64 = Words.bytes; + var lease: u64 = 0; + try out.append(a, .{ .img = 0, .len = Words.bytes, .from = .words }); + const f = front(sh, at); + try out.append(a, .{ .img = img, .len = f, .from = .{ .lease = 0 } }); + img += f; + lease += f; + if (sh.head) for (cache(sh, sh.headRows(at)), cache(sh, mtp_len)) |full, held| { + if (held > 0) try out.append(a, .{ .img = img, .len = held, .from = .{ .lease = lease } }); + if (full > held) try out.append(a, .{ .img = img + held, .len = full - held, .from = .zeros }); + img += full; + lease += held; + }; + if (sh.tail > 0) try out.append(a, .{ .img = img, .len = sh.tail, .from = .{ .lease = lease } }); +} + +/// The image bytes after the words that sit in the lease as in the image: the prefix and every DSA layer's parts. +pub fn front(sh: Shape, at: u32) u64 { + var n: u64 = sh.prefix; + for (0..sh.layers) |_| for (cache(sh, at)) |x| { + n += x; + }; + return n; +} + +/// The lease bytes of a state at `at` whose head holds `mtp_len` rows (layout.Plan's length for it). +pub fn leaseBytes(sh: Shape, at: u32, mtp_len: u64) u64 { + var n: u64 = sh.prefix + sh.tail; + for (0..sh.layers) |_| for (cache(sh, at)) |x| { + n += x; + }; + if (sh.head) for (cache(sh, mtp_len)) |x| { + n += x; + }; + return n; +} + +/// Rank 0's image bytes at `at` (its head counted at a verify window past `at`). +pub fn imageBytes(sh: Shape, at: u32) u64 { + var n: u64 = Words.bytes + front(sh, at) + sh.tail; + if (sh.head) for (cache(sh, sh.headRows(at))) |x| { + n += x; + }; + return n; +} + +/// `len` bytes at `off` of rank `rank`'s image; `shared`: past rank 0's prefix, the same bytes every rank holds. +pub const Piece = struct { rank: u32, off: u64, len: u64, shared: bool }; + +/// The store's image at `at`: rank 0's, then each other rank's prefix (rank 0's bytes stand for all the rest). +pub fn storeParts(sh: Shape, prefixes: []const u64, at: u32, out: *std.ArrayList(Part), a: std.mem.Allocator) !void { + try parts(sh, at, out, a); + for (prefixes[1..]) |p| try out.append(a, .{ .bytes = p }); +} + +/// Store image bytes [off, off + len) split by rank: rank 0's image, then rank r's prefix after its words. +pub fn route(sh: Shape, prefixes: []const u64, at: u32, off: u64, len: u64, out: *std.ArrayList(Piece), a: std.mem.Allocator) !void { + const own = Words.bytes + sh.prefix; // rank 0's bytes no other rank holds + var start: u64 = 0; // the section's first store byte + for (prefixes, 0..) |p, r| { + const size = if (r == 0) imageBytes(sh, at) else p; + defer start += size; + const lo = @max(off, start); + const hi = @min(off + len, start + size); + if (lo >= hi) continue; + if (r > 0) { + try out.append(a, .{ .rank = @intCast(r), .off = Words.bytes + lo - start, .len = hi - lo, .shared = false }); + continue; + } + if (lo < own) try out.append(a, .{ .rank = 0, .off = lo, .len = @min(hi, own) - lo, .shared = false }); + if (hi > own) try out.append(a, .{ .rank = 0, .off = @max(lo, own), .len = hi - @max(lo, own), .shared = true }); + } + if (off + len > start) return error.SnapshotShape; +} + +/// `len` store image bytes at `off`. +pub const Span = struct { off: u64, len: u64 }; + +/// Store image bytes no prompt pass to `at` writes: each rank's window rows, pools past the whole ones, the draft row. +pub fn unwritten(sh: Shape, prefixes: []const u64, windows: []const u64, at: u32, mtp_len: u64, out: *std.ArrayList(Span), a: std.mem.Allocator) !void { + if (windows.len != prefixes.len or windows.len == 0 or windows[0] != sh.window) return error.SnapshotShape; + if (sh.head and mtp_len > sh.headRows(at)) return error.SnapshotShape; + var img: u64 = Words.bytes + sh.prefix; + try out.append(a, .{ .off = Words.bytes + sh.window, .len = sh.prefix - sh.window }); + for (0..sh.layers) |_| { + const c = cache(sh, at); + const whole = at / sparse.pool * sh.pooled_row; + img += c[0] + c[1] + c[2] + c[3]; + try out.append(a, .{ .off = img + whole, .len = c[4] - whole }); + img += c[4]; + } + if (sh.head) { + const full = cache(sh, sh.headRows(at)); + const held = cache(sh, mtp_len)[4]; + const whole = mtp_len / sparse.pool * sh.pooled_row; + img += full[0] + full[1] + full[2] + full[3]; + try out.append(a, .{ .off = img + whole, .len = held - whole }); // past `held`, the image's zeros + img += full[4]; + } + try out.append(a, .{ .off = img + sh.draft, .len = sh.tail - sh.draft }); + img += sh.tail; + for (prefixes[1..], windows[1..]) |p, w| { + if (w > p) return error.SnapshotShape; + try out.append(a, .{ .off = img + w, .len = p - w }); // a rank's section is its prefix alone + img += p; + } +} + +/// Zeros `spans` of `bytes`, store image bytes from `from`, where they overlap. +pub fn clear(spans: []const Span, from: u64, bytes: []u8) void { + for (spans) |s| { + const lo = @max(s.off, from); + const hi = @min(s.off + s.len, from + bytes.len); + if (lo < hi) @memset(bytes[@intCast(lo - from)..@intCast(hi - from)], 0); + } +} + +/// Copies between `host` and image bytes [off, off + host.len) of a lease: out (lease to host) or in. +pub const Copy = struct { + d: *const cuda.Driver, + pool: *const pages.Pool, + lease: *const pages.Lease, + segs: []const Seg, + words: *[Words.count]u64, + + pub fn run(c: Copy, off: u64, host: []u8, out: bool) !void { + const end = off + host.len; + for (c.segs) |s| { + const lo = @max(off, s.img); + const hi = @min(end, s.img + s.len); + if (lo >= hi) continue; + const h = host[@intCast(lo - off)..][0..@intCast(hi - lo)]; + switch (s.from) { + .words => { + const w = std.mem.asBytes(c.words)[@intCast(lo - s.img)..][0..h.len]; + if (out) @memcpy(h, w) else @memcpy(w, h); + }, + .zeros => if (out) @memset(h, 0), + .lease => |at| try c.leased(at + (lo - s.img), h, out), + } + } + } + + /// `len` device bytes at `src` into image bytes from `off`, queued on `stream`: no host copy (a link's buffer). + pub fn fromDevice(c: Copy, off: u64, src: u64, len: u64, stream: cuda.abi.Stream) !void { + const arena = c.pool.arena orelse return error.NoSnapshotRoom; + const end = off + len; + for (c.segs) |s| { + const lo = @max(off, s.img); + const hi = @min(end, s.img + s.len); + if (lo >= hi) continue; + const at = switch (s.from) { + .words => return error.SnapshotShape, // the words go with the seal, from the host + .zeros => continue, + .lease => |x| x + (lo - s.img), + }; + if (at + (hi - lo) > c.lease.ids.items.len * pages.page) return error.SnapshotSize; + var done: u64 = 0; + while (done < hi - lo) { + const x = at + done; + const n = @min(hi - lo - done, pages.page - x % pages.page); + const dev = arena.ptr() + @as(u64, c.lease.ids.items[@intCast(x / pages.page)]) * pages.page + x % pages.page; + try c.d.check(c.d.api.cuMemcpyDtoDAsync_v2(dev, src + (lo - off) + done, @intCast(n), stream), "cuMemcpyDtoDAsync"); + done += n; + } + } + } + + /// Lease bytes from `at`, a page at a time (each page is a run of the snapshot arena). + fn leased(c: Copy, at: u64, host: []u8, out: bool) !void { + const arena = c.pool.arena orelse return error.NoSnapshotRoom; + if (at + host.len > c.lease.ids.items.len * pages.page) return error.SnapshotSize; + var done: usize = 0; + while (done < host.len) { + const x = at + done; + const n = @min(host.len - done, pages.page - x % pages.page); + const dev = arena.ptr() + @as(u64, c.lease.ids.items[@intCast(x / pages.page)]) * pages.page + x % pages.page; + const p = host[done..][0..n]; + if (out) { + try cuda.memory.download(c.d, dev, p); // staged through the pinned buffer on an integrated GPU + } else try c.d.check(c.d.api.cuMemcpyHtoD_v2(dev, p.ptr, n), "cuMemcpyHtoD"); + done += n; + } + } +}; + +test { + _ = @import("cuda_disk_image_test.zig"); +} diff --git a/zig/src/families/glm/cuda_disk_image_test.zig b/zig/src/families/glm/cuda_disk_image_test.zig new file mode 100644 index 00000000000..9b2e7c6d812 --- /dev/null +++ b/zig/src/families/glm/cuda_disk_image_test.zig @@ -0,0 +1,411 @@ +//! GLM's disk image on a driver whose device memory is host memory: sizes against the snapshot plan, a round trip. +const std = @import("std"); +const cuda = @import("cuda"); +const weights = @import("cuda_weights.zig"); +const shard = @import("cuda_shard.zig"); +const image = @import("cuda_disk_image.zig"); +const State = @import("cuda_state.zig").State; +const Plan = @import("cuda_snapshot_layout.zig").Plan; +const pages = @import("cuda_snapshot_pages.zig"); +const expect = std.testing.expect; +const expectEqual = std.testing.expectEqual; +const expectError = std.testing.expectError; + +/// Device addresses are host addresses: allocations from the page allocator, copies and fills as memcpy and memset. +pub const H = struct { + var held: [16]struct { ptr: u64 = 0, len: usize = 0 } = @splat(.{}); + fn bytes(p: u64, n: usize) []u8 { + return @as([*]u8, @ptrFromInt(p))[0..n]; + } + fn alloc(out: *u64, n: usize) callconv(.c) cuda.abi.Result { + const m = std.heap.page_allocator.alloc(u8, n) catch return 2; + for (&held) |*h| if (h.ptr == 0) { + h.* = .{ .ptr = @intFromPtr(m.ptr), .len = n }; + out.* = h.ptr; + return 0; + }; + std.heap.page_allocator.free(m); + return 2; + } + fn free(p: u64) callconv(.c) cuda.abi.Result { + for (&held) |*h| if (h.ptr == p) { + std.heap.page_allocator.free(bytes(h.ptr, h.len)); + h.* = .{}; + return 0; + }; + return 1; + } + fn set(p: u64, v: u8, n: usize) callconv(.c) cuda.abi.Result { + @memset(bytes(p, n), v); + return 0; + } + fn dtod(dst: u64, src: u64, n: usize, _: cuda.abi.Stream) callconv(.c) cuda.abi.Result { + @memcpy(bytes(dst, n), bytes(src, n)); + return 0; + } + fn dtoh(dst: ?*anyopaque, src: u64, n: usize) callconv(.c) cuda.abi.Result { + @memcpy(@as([*]u8, @ptrCast(dst.?))[0..n], bytes(src, n)); + return 0; + } + fn htod(dst: u64, src: ?*const anyopaque, n: usize) callconv(.c) cuda.abi.Result { + @memcpy(bytes(dst, n), @as([*]const u8, @ptrCast(src.?))[0..n]); + return 0; + } + fn wait(_: cuda.abi.Stream) callconv(.c) cuda.abi.Result { + return 0; + } + fn contextDevice(out: *cuda.abi.Device) callconv(.c) cuda.abi.Result { + out.* = 0; + return 0; + } + fn deviceAttribute(out: *c_int, _: cuda.abi.DeviceAttribute, _: cuda.abi.Device) callconv(.c) cuda.abi.Result { + out.* = 0; // a discrete card: cuda.memory.download copies straight to the host + return 0; + } + pub fn driver() cuda.Driver { + var d: cuda.Driver = undefined; + d.api.cuMemAlloc_v2 = alloc; + d.api.cuMemFree_v2 = free; + d.api.cuMemsetD8_v2 = set; + d.api.cuMemcpyDtoDAsync_v2 = dtod; + d.api.cuMemcpyDtoH_v2 = dtoh; + d.api.cuMemcpyHtoD_v2 = htod; + d.api.cuStreamSynchronize = wait; + d.api.cuCtxGetDevice = contextDevice; + d.api.cuDeviceGetAttribute = deviceAttribute; + return d; + } +}; + +pub const capacity = 6144; // past the index rings' 4,096 rows, so a state at the end holds a full ring + +/// TP=2 rank 0's shapes on KDA, DSA, KDA, DSA layers. +pub const Model = struct { + layers: [4]weights.Layer, + w: weights.Weights, + + pub fn init(m: *Model) !void { + for (&m.layers, [_]bool{ false, true, false, true }) |*l, mla| l.mixer = if (mla) .{ .mla = undefined } else .{ .kda = undefined }; + m.w = undefined; + m.w.config = .{}; + m.w.share = try shard.Share.of(&m.w.config, 0, 2); + m.w.layers = &m.layers; + } +}; + +test "GLM disk image: the lease bytes the image counts are the snapshot plan's, at each position and head length" { + var m: Model = undefined; + try m.init(); + var d = H.driver(); + for ([_]bool{ false, true }) |kv8| { + var st = try State.initFormat(std.testing.allocator, &d, &m.w, capacity, kv8); + defer st.deinit(); + for ([_]bool{ false, true }) |head| { + const sh = try image.Shape.of(&st, &m.w.config, capacity, head); + for ([_]u32{ 2048, 4096, 6144 }) |at| { + for ([_]u64{ at - 1, at, sh.headRows(at) }) |mtp| { + const plan = try Plan.init(&st, &m.w.config, at, if (head) mtp else null, 0); + try expectEqual(@as(u64, plan.len), image.leaseBytes(sh, at, if (head) mtp else 0)); + } + } + } + } +} + +test "GLM disk image: the longest state is a position the store's parts take, so the staging floor prices it" { + var m: Model = undefined; + try m.init(); + var d = H.driver(); + const a = std.testing.allocator; + // capacities off and on a pool's edge: rows.attach prices `longest` and falls back to its default on an error + for ([_]usize{ capacity, capacity + 1, capacity + 3 }) |cap| { + var st = try State.initFormat(a, &d, &m.w, cap, false); + defer st.deinit(); + const sh = try image.Shape.of(&st, &m.w.config, cap, true); + const at = image.longest(sh); + try expect(at <= cap and cap - at < 4 and at % 4 == 0); + var parts: std.ArrayList(image.Part) = .empty; + defer parts.deinit(a); + try image.storeParts(sh, &.{ sh.prefix, sh.prefix }, at, &parts, a); + try expect(parts.items.len > 0); + try expectError(error.SnapshotShape, image.storeParts(sh, &.{ sh.prefix, sh.prefix }, at + 4, &parts, a)); + } +} + +test "GLM disk image: the store's rows are by position from 0 in whole blocks; rings, pools in progress and the head are its own" { + var m: Model = undefined; + try m.init(); + var d = H.driver(); + var st = try State.initFormat(std.testing.allocator, &d, &m.w, capacity, true); + defer st.deinit(); + const sh = try image.Shape.of(&st, &m.w.config, capacity, true); + const a = std.testing.allocator; + var list: std.ArrayList(image.Part) = .empty; + defer list.deinit(a); + var segs: std.ArrayList(image.Seg) = .empty; + defer segs.deinit(a); + const at: u32 = 6144; + try image.parts(sh, at, &list, a); + try image.segments(sh, at, at, &segs, a); + var total: u64 = 0; + var rows: usize = 0; + for (list.items) |p| { + total += p.bytes; + if (p.row == 0) continue; + rows += 1; + try expect(256 % p.per == 0); + try expectEqual(@as(u64, at / p.per) * p.row, p.bytes); // a pooled part counts the whole pools alone + } + try expectEqual(@as(usize, 3 * 2), rows); // each DSA layer's latent rows, scales and whole pools + const last = segs.items[segs.items.len - 1]; + try expectEqual(total, last.img + last.len); + try expectEqual(@as(u64, 2 * 256), list.items[7].bytes); // layer 0's pools past `at`: the spare rows + try expectError(error.SnapshotShape, image.segments(sh, at, sh.headRows(at) + 1, &segs, a)); +} + +test "GLM disk image: a kept state's image read out of its lease restores every planned byte into another sequence" { + var m: Model = undefined; + try m.init(); + var d = H.driver(); + const a = std.testing.allocator; + const c = &m.w.config; + var st = try State.initFormat(a, &d, &m.w, capacity, false); + defer st.deinit(); + for (H.bytes(st.arena.buf.ptr, st.arena.buf.len), 0..) |*b, i| b.* = @truncate(i *% 31 +% 7); + var pool = try pages.Pool.init(a, &d, 64 << 20, false); + defer pool.deinit(); + const stream: cuda.Stream = .{ .d = &d, .handle = null }; + const at: u32 = 2048; + const mtp: u64 = at - 1; // a head one row behind: its last image row is not in the lease + const sh = try image.Shape.of(&st, c, capacity, true); + const plan = try Plan.init(&st, c, at, mtp, 0); + var kept = try pool.take(plan.len); + defer pool.give(&kept); + try pool.move(stream, &kept, &plan, true); + var segs: std.ArrayList(image.Seg) = .empty; + defer segs.deinit(a); + try image.segments(sh, at, mtp, &segs, a); + const last = segs.items[segs.items.len - 1]; + const img = try a.alloc(u8, @intCast(last.img + last.len)); + defer a.free(img); + var words = (image.Words{ .at = at, .mtp_len = mtp, .base = 0, .mtp_base = 0, .cur = 0b10, .world = 2 }).encode(); + const out: image.Copy = .{ .d = &d, .pool = &pool, .lease = &kept, .segs = segs.items, .words = &words }; + const cut = [_]u64{ 0, 1000, plan.len / 2, img.len }; // the store asks for ranges, not the whole image + for (cut[0..3], cut[1..]) |lo, hi| try out.run(lo, img[@intCast(lo)..@intCast(hi)], true); + for (segs.items) |s| if (s.from == .zeros) for (img[@intCast(s.img)..][0..@intCast(s.len)]) |b| try expectEqual(@as(u8, 0), b); + // a blank state as a disk read takes it (room for the head's whole window), filled from the image + var blank = try pool.take(@intCast(image.leaseBytes(sh, at, sh.headRows(at)))); + defer pool.give(&blank); + var back: [image.Words.count]u64 = undefined; + const in: image.Copy = .{ .d = &d, .pool = &pool, .lease = &blank, .segs = segs.items, .words = &back }; + try in.run(0, img, false); + const w = try image.Words.decode(back, at, 2, .unsplit); + try expectEqual(mtp, w.mtp_len); + try expectEqual(@as(u64, 0b10), w.cur); + try expectError(error.DiskWords, image.Words.decode(back, at + 2048, 2, .unsplit)); + var fresh = try State.initFormat(a, &d, &m.w, capacity, false); + defer fresh.deinit(); + const into = try Plan.init(&fresh, c, at, w.mtp_len, 0); + try expectEqual(plan.len, into.len); + try pool.move(stream, &blank, &into, false); + for (plan.parts[0..plan.count], into.parts[0..into.count]) |x, y| { + try std.testing.expectEqualSlices(u8, H.bytes(x.live, x.len), H.bytes(y.live, y.len)); + } +} + +test "GLM disk image: the store's image is rank 0's then each other rank's prefix, and routes every byte once" { + var m: Model = undefined; + try m.init(); + var d = H.driver(); + const a = std.testing.allocator; + var st = try State.initFormat(a, &d, &m.w, capacity, true); + defer st.deinit(); + const sh = try image.Shape.of(&st, &m.w.config, capacity, true); + const at: u32 = 4096; + const prefixes = [_]u64{ sh.prefix, sh.prefix - 4096, sh.prefix + 512 }; // TP=3: heads one by one + var list: std.ArrayList(image.Part) = .empty; + defer list.deinit(a); + try image.storeParts(sh, &prefixes, at, &list, a); + var total: u64 = 0; + for (list.items) |p| total += p.bytes; + try expectEqual(image.imageBytes(sh, at) + prefixes[1] + prefixes[2], total); + var pieces: std.ArrayList(image.Piece) = .empty; + defer pieces.deinit(a); + var seen: [3]u64 = .{ 0, 0, 0 }; + var shared: u64 = 0; + const cuts = [_]u64{ 0, 40, image.Words.bytes + sh.prefix - 8, image.imageBytes(sh, at) + 100, total }; // ranges across the seams + for (cuts[0 .. cuts.len - 1], cuts[1..]) |lo, hi| { + pieces.clearRetainingCapacity(); + try image.route(sh, &prefixes, at, lo, hi - lo, &pieces, a); + var n: u64 = 0; + for (pieces.items) |p| { + n += p.len; + seen[p.rank] += p.len; + if (p.shared) shared += p.len; + if (p.rank > 0) try expect(p.off >= image.Words.bytes and p.off + p.len <= image.Words.bytes + prefixes[p.rank] and !p.shared); + if (p.shared) try expect(p.rank == 0 and p.off >= image.Words.bytes + sh.prefix); + } + try expectEqual(hi - lo, n); + } + try expectEqual(image.imageBytes(sh, at), seen[0]); + try expectEqual(prefixes[1], seen[1]); + try expectEqual(prefixes[2], seen[2]); + try expectEqual(image.imageBytes(sh, at) - image.Words.bytes - sh.prefix, shared); + try expectError(error.SnapshotShape, image.route(sh, &prefixes, at, total - 4, 8, &pieces, a)); +} + +/// The fields of an engine the kept-state functions read, over a host-memory driver. +const Fake = struct { + gpa: std.mem.Allocator, + d: *const cuda.Driver, + stream: cuda.Stream, + c: @import("config.zig").Config, + cur: struct { st: State, in_head: usize = 0 }, + capacity: usize = capacity, + mtp: bool = true, + snaps: std.AutoHashMapUnmanaged(u64, @import("cuda_engine_types.zig").Snap) = .empty, + snap_pages: ?pages.Pool = null, + share_pages: bool = false, +}; + +test "GLM disk image: a disk read's blank state is refused until sealed, and its seal checks the words" { + const snaps = @import("cuda_snapshots.zig"); + var m: Model = undefined; + try m.init(); + var d = H.driver(); + const a = std.testing.allocator; + var e: Fake = .{ .gpa = a, .d = &d, .stream = .{ .d = &d, .handle = null }, .c = m.w.config, .cur = .{ .st = try State.initFormat(a, &d, &m.w, capacity, false) } }; + defer e.cur.st.deinit(); + e.snap_pages = try pages.Pool.init(a, &d, 256 << 20, false); + defer e.snap_pages.?.deinit(); + try e.snaps.ensureTotalCapacity(a, 8); + defer e.snaps.deinit(a); + const at: u32 = 2048; + try snaps.blankAs(&e, 7, at); + defer { + var s = e.snaps.get(7).?; + snaps.free(&e, &s); + } + try expectError(error.StateKept, snaps.blankAs(&e, 7, at)); + try expectError(error.UnsealedState, snaps.restore(&e, 7)); + try expectError(error.DiskWords, snaps.seal(&e, 7, at + @import("cuda_state.zig").window_rows + 1, .{ 0, 0 }, 0)); // a head past its verify window + try expectError(error.DiskWords, snaps.seal(&e, 7, at, .{ 0, 0 }, @as(u64, 1) << @intCast(e.cur.st.cur.len))); // a copy bit no layer has + try expectError(error.DiskWords, snaps.seal(&e, 7, at - 1, .{ at + 1, 0 }, 0)); // a main ring based past the state + try expectError(error.DiskWords, snaps.seal(&e, 7, at - 1, .{ 0, at }, 0)); // a head ring based past its rows + try snaps.seal(&e, 7, at - 1, .{ 3, 5 }, 0b01); + const s = e.snaps.get(7).?; + const sh = try image.Shape.of(&e.cur.st, &e.c, capacity, true); + try expectEqual(image.leaseBytes(sh, at, at - 1), @as(u64, s.len)); + try expectEqual(@as(usize, at - 1), s.mtp_len); + try expectEqual([2]usize{ 3, 5 }, s.bases); + try std.testing.expectEqualSlices(u1, &.{ 1, 0 }, s.cur); + try expectError(error.StateKept, snaps.seal(&e, 7, at, .{ 0, 0 }, 0)); + const far: u32 = capacity - 1024; // a state past the rings' rows + const back: u32 = far - @as(u32, @intCast(e.cur.st.ring_rows)); // the least base whose ring still holds its rows + try snaps.blankAs(&e, 8, far); + defer { + var held = e.snaps.get(8).?; + snaps.free(&e, &held); + } + try expectError(error.DiskWords, snaps.seal(&e, 8, far, .{ back - 1, back }, 0)); // a main ring too far back + try expectError(error.DiskWords, snaps.seal(&e, 8, far, .{ back, back - 1 }, 0)); // a head ring too far back + try snaps.seal(&e, 8, far, .{ back, back }, 0); + try snaps.blankAs(&e, 9, far); + defer { + var held = e.snaps.get(9).?; + snaps.free(&e, &held); + } + try snaps.seal(&e, 9, 0, .{ back, 0 }, 0); // no head rows yet (as without drafts): the main ring holds the state's rows +} + +test "GLM disk image: the words record the world, the layout and the owner, and a read refuses another by name" { + const at: u32 = 4096; + const w: image.Words = .{ .at = at, .mtp_len = 7, .base = 1, .mtp_base = 2, .cur = 0b1, .world = 3 }; + const x = w.encode(); + try expectEqual(@as(u64, 72), image.Words.bytes); + try expectEqual(@as(usize, image.Words.bytes), @sizeOf(@TypeOf(x))); + // an unsplit state: every rank holds every row, so no rank owns it + try std.testing.expectEqualSlices(u64, &.{ 3, 0, image.Words.no_owner }, x[6..]); + try expectEqual(w, try image.Words.decode(x, at, 3, .unsplit)); + try expectError(error.DiskWorld, image.Words.decode(x, at, 2, .unsplit)); // written by three ranks, read by two + try expectError(error.DiskWorld, image.Words.decode(x, at, 4, .unsplit)); + const split: image.Words.Layout = @fromBackingInt(@intCast(1)); + try expectError(error.DiskLayout, image.Words.decode(x, at, 3, split)); // this server splits, the image does not + var y = x; + y[7] = 1; // an image of a split layout read unsplit + try expectError(error.DiskLayout, image.Words.decode(y, at, 3, .unsplit)); + const owned = try image.Words.decode(y[0..8].* ++ [1]u64{2}, at, 3, split); + try expectEqual(@as(u64, 2), owned.owner); + try expectError(error.DiskLayout, image.Words.decode(y, at, 3, split)); // a split image names an owner rank + try expectError(error.DiskLayout, image.Words.decode(y[0..8].* ++ [1]u64{3}, at, 3, split)); + y = x; + y[8] = 0; // an unsplit image that names an owner + try expectError(error.DiskLayout, image.Words.decode(y, at, 3, .unsplit)); + y = x; + y[0] = 2; // the format comes first: a format this server does not read is DiskWords, whatever its layout + try expectError(error.DiskWords, image.Words.decode(y, at, 2, .unsplit)); +} + +/// A state's store image at `at` for two ranks, rank 1's prefix a copy of rank 0's: what the load's probe gathers. +fn storeImage(a: std.mem.Allocator, d: *const cuda.Driver, pool: *pages.Pool, st: *const State, c: *const @import("config.zig").Config, sh: image.Shape, at: u32, mtp: u64) ![]u8 { + const plan = try Plan.init(st, c, at, mtp, 0); + var kept = try pool.take(plan.len); + defer pool.give(&kept); + try pool.move(.{ .d = d, .handle = null }, &kept, &plan, true); + var segs: std.ArrayList(image.Seg) = .empty; + defer segs.deinit(a); + try image.segments(sh, at, mtp, &segs, a); + const own = image.imageBytes(sh, at); + const out = try a.alloc(u8, @intCast(own + sh.prefix)); + errdefer a.free(out); + @memset(out[0..image.Words.bytes], 0); // the words are not the probe's question + const copy: image.Copy = .{ .d = d, .pool = pool, .lease = &kept, .segs = segs.items, .words = undefined }; + try copy.run(image.Words.bytes, out[image.Words.bytes..@intCast(own)], true); + @memcpy(out[@intCast(own)..], out[image.Words.bytes..][0..@intCast(sh.prefix)]); + return out; +} + +test "GLM disk image: the probe's hash leaves out what a prompt pass does not write, whatever the slot ran before" { + var m: Model = undefined; + try m.init(); + var d = H.driver(); + const a = std.testing.allocator; + const c = &m.w.config; + var st = try State.initFormat(a, &d, &m.w, capacity, false); + defer st.deinit(); + for (H.bytes(st.arena.buf.ptr, st.arena.buf.len), 0..) |*b, i| b.* = @truncate(i *% 31 +% 7); + var pool = try pages.Pool.init(a, &d, 64 << 20, false); + defer pool.deinit(); + const at: u32 = 2048; + const mtp: u64 = at - 1; // the head a row behind: its last pool unfinished + const sh = try image.Shape.of(&st, c, capacity, true); + const prefixes = [_]u64{ sh.prefix, sh.prefix }; + var loose: std.ArrayList(image.Span) = .empty; + defer loose.deinit(a); + try image.unwritten(sh, &prefixes, &.{ sh.window, sh.window }, at, mtp, &loose, a); + try expectError(error.SnapshotShape, image.unwritten(sh, &prefixes, &.{ sh.window + 1, sh.window }, at, mtp, &loose, a)); + const before = try storeImage(a, &d, &pool, &st, c, sh, at, mtp); + defer a.free(before); + // what load's timed windows leave in the slot: a window's rows, keys past `at`'s whole pools, the first-draft row + const row = c.i_dim * 2; + const pool_rows = @import("cuda_sparse.zig").pool; + @memset(H.bytes(st.proj, st.caches[0].lc - st.proj), 0xa5); + for (st.caches) |x| @memset(H.bytes(x.pk + at / pool_rows * row, 2 * row), 0xa5); + @memset(H.bytes(st.mtp_caches.pk + mtp / pool_rows * row, 2 * row), 0xa5); + @memset(H.bytes(st.prompt_hidden, c.hidden * 2), 0xa5); + const after = try storeImage(a, &d, &pool, &st, c, sh, at, mtp); + defer a.free(after); + try expect(!std.mem.eql(u8, before, after)); // the image carries them: hashed whole, two loads named two stores + image.clear(loose.items, 0, before); + image.clear(loose.items, 0, after); + try std.testing.expectEqualSlices(u8, before, after); + // what the prompt writes still names the store: a KDA state, a whole pool's keys + for ([_]u64{ st.conv, st.caches[1].pk }) |p| { + H.bytes(p, 1)[0] ^= 1; + defer H.bytes(p, 1)[0] ^= 1; + const changed = try storeImage(a, &d, &pool, &st, c, sh, at, mtp); + defer a.free(changed); + image.clear(loose.items, 0, changed); + try expect(!std.mem.eql(u8, before, changed)); + } +} diff --git a/zig/src/families/glm/cuda_disk_ranks.zig b/zig/src/families/glm/cuda_disk_ranks.zig new file mode 100644 index 00000000000..5d63d7d1f0f --- /dev/null +++ b/zig/src/families/glm/cuda_disk_ranks.zig @@ -0,0 +1,250 @@ +//! A GLM kept state's disk image across ranks: rank 0's engine thread leases, fills, reads and seals each rank's copy. +const std = @import("std"); +const cuda = @import("cuda"); +const follow = @import("cuda_follow.zig"); +const image = @import("cuda_disk_image.zig"); +const snapshots = @import("cuda_snapshots.zig"); +const Engine = @import("cuda_engine.zig").Engine; + +/// Rank 0 at TP: its follow link, set by Link.lead, cleared by its deinit; null: one rank, every op local. +pub var link: ?*follow.Link = null; + +/// A disk step's op (Header.flags); its id is `a`, its image offset `seed`, its bytes `depth`, its rank `top_k`. +pub const Op = enum(u32) { blank = 1, rows, take, seal, prefixes }; +const kind = @backingInt(follow.Kind.disk); // each op crosses the follow link as a disk step, its bytes as the ids + +/// This rank's image shape (every sequence of the engine has the same). +pub fn shape(e: *const Engine) !image.Shape { + return image.Shape.of(&e.cur.st, &e.c, e.capacity, e.mtp); +} + +/// The words of a kept state on this rank: its position, head rows, ring bases, KDA copy bits and layout (unsplit). +pub fn wordsOf(e: *const Engine, id: u64) !image.Words { + const s = e.snaps.get(id) orelse return error.NoKeptState; + if (s.cur.len > 64) return error.SnapshotShape; + var cur: u64 = 0; + for (s.cur, 0..) |b, i| cur |= @as(u64, b) << @intCast(i); + return .{ .at = s.pos, .mtp_len = s.mtp_len, .base = s.bases[0], .mtp_base = s.bases[1], .cur = cur, .world = e.share.world }; +} + +/// Bytes [off, off + host.len) of this rank's image of `id`, out (lease to host) or in; unsealed: before its head only. +pub fn copy(e: *Engine, id: u64, off: u64, host: []u8, out: bool) !void { + const H = struct { + host: []u8, + out: bool, + fn run(h: @This(), c: image.Copy, at: u64) !void { + return c.run(at, h.host, h.out); + } + }; + return through(e, id, off, host.len, H{ .host = host, .out = out }); +} + +/// `len` device bytes at `src` into this rank's image of `id` from `off`, queued on `stream` (the caller waits). +pub fn copyDevice(e: *Engine, id: u64, off: u64, src: u64, len: u64, stream: cuda.Stream) !void { + const D = struct { + src: u64, + len: u64, + stream: cuda.Stream, + fn run(x: @This(), c: image.Copy, at: u64) !void { + return c.fromDevice(at, x.src, x.len, x.stream.handle); + } + }; + return through(e, id, off, len, D{ .src = src, .len = len, .stream = stream }); +} + +/// `how.run` on the image of `id` for `len` bytes from `off`, refused past an unsealed state's words and front. +fn through(e: *Engine, id: u64, off: u64, len: u64, how: anytype) !void { + const s = e.snaps.get(id) orelse return error.NoKeptState; + const sh = try shape(e); + const at: u32 = @intCast(s.pos); + if (s.len == 0 and off + len > image.Words.bytes + image.front(sh, at)) return error.DiskOrder; + var segs: std.ArrayList(image.Seg) = .empty; + defer segs.deinit(e.gpa); + try image.segments(sh, at, s.mtp_len, &segs, e.gpa); + var w = (try wordsOf(e, id)).encode(); + const pool = if (e.snap_pages) |*p| p else return error.NoSnapshotCache; + try how.run(image.Copy{ .d = e.d, .pool = pool, .lease = &s.lease, .segs = segs.items, .words = &w }, off); +} + +/// Rank 0's link at TP, else null (one rank: every op is local). +fn leader(e: *Engine) ?follow.Leader { + return .{ .e = e, .link = link orelse return null }; +} + +/// Rank 0: whether the other ranks sleep on their lines (no stream), and putting them back to sleep after disk steps. +pub fn asleep(e: *Engine) bool { + return if (leader(e)) |x| x.link.asleep else false; +} + +pub fn rest(e: *Engine) !void { + if (leader(e)) |x| try x.idle(); +} + +/// Rank 0: a new id leased at `at` on every rank (rank 0 first: the ranks' pools match, so theirs cannot fail apart). +pub fn blank(e: *Engine, at: u32) !u64 { + if (e.next_snap > std.math.maxInt(u32)) return error.SnapshotIdLimit; + const id = e.next_snap; + try snapshots.blankAs(e, id, at); + e.next_snap += 1; + // a failed step: rank 0's lease goes back, and its id is dropped at the next step (another rank may hold it) + errdefer snapshots.drop(e, id); + if (leader(e)) |x| try x.disk(.{ .kind = kind, .flags = @backingInt(Op.blank), .a = id, .seed = at }, &.{}); + return id; +} + +/// A piece's rank in a `rows` step for the bytes every rank holds: each rank's image at `off` past its own prefix. +pub const every: u32 = std.math.maxInt(u32); + +/// Bytes for rank `to`'s image at `off`, or for every rank's (`every`: `off` less rank 0's prefix, each adds its own). +pub const Piece = struct { to: u32, off: u64, bytes: []const u8 }; + +/// Rank 0 at TP: `pieces` into every rank's image of `id`, each step a table (4 words a piece) and one broadcast. +pub fn rows(e: *Engine, id: u64, pieces: []const Piece) !void { + const x = leader(e) orelse return error.NoRank; + const stage = std.mem.sliceAsBytes(x.link.ids); // the bytes on the host, then in the link's buffer after its header + var table: std.ArrayList(u32) = .empty; + defer table.deinit(e.gpa); + var i: usize = 0; + var done: usize = 0; // bytes of pieces[i] in earlier steps (a piece longer than the link goes in parts) + while (i < pieces.len) { + table.clearRetainingCapacity(); + var n: usize = 0; + while (i < pieces.len and n < stage.len and table.items.len + 4 <= x.link.ids.len) { + const p = pieces[i]; + const k = @min(p.bytes.len - done, stage.len - n); + const off = p.off + done; + try table.appendSlice(e.gpa, &.{ @truncate(off), @intCast(off >> 32), @intCast(k), p.to }); + @memcpy(stage[n..][0..k], p.bytes[done..][0..k]); + n += k; + done += k; + if (done == p.bytes.len) { + i += 1; + done = 0; + } + } + try x.disk(.{ .kind = kind, .flags = @backingInt(Op.rows), .a = id, .depth = @intCast(n) }, table.items); + try x.link.stream.synchronize(); // the table's broadcasts read the buffer the bytes go to + try x.link.buf.upload(64, stage[0..n]); + try x.link.from(0, n); + try place(e, id, table.items, x.link.buf.ptr + 64, x.link.stream); + } +} + +/// A `rows` step's pieces for this rank, copied from `src` (the link's buffer) and waited for: the next step reuses it. +fn place(e: *Engine, id: u64, table: []const u32, src: u64, stream: cuda.Stream) !void { + const me: u32 = @intCast(e.share.rank); + const own = (try shape(e)).prefix; + var at: u64 = 0; + var i: usize = 0; + while (i < table.len) : (i += 4) { + const off = @as(u64, table[i]) | @as(u64, table[i + 1]) << 32; + const len: u64 = table[i + 2]; + if (table[i + 3] == every) try copyDevice(e, id, off + own, src + at, len, stream) else if (table[i + 3] == me) try copyDevice(e, id, off, src + at, len, stream); + at += len; + } + try stream.synchronize(); +} + +/// A `rows` step's table checked against its bytes and the link before a follower joins the broadcast. +fn fits(ids: []const u32, depth: u32, room: usize) !void { + if (ids.len % 4 != 0 or depth > room) return error.BadStep; + var n: u64 = 0; + var i: usize = 0; + while (i < ids.len) : (i += 4) n += ids[i + 2]; + if (n != depth) return error.BadStep; +} + +/// Rank 0: rank `rank`'s image bytes of `id` from `off` into `out`. +pub fn take(e: *Engine, rank: u32, id: u64, off: u64, out: []u8) !void { + if (rank == 0) return copy(e, id, off, out, true); + const x = leader(e) orelse return error.NoRank; + const room = x.link.ids.len * 4; + var done: usize = 0; + while (done < out.len) { + const n = @min(room, out.len - done); + try x.disk(.{ .kind = kind, .flags = @backingInt(Op.take), .a = id, .seed = off + done, .depth = @intCast(n), .top_k = rank }, &.{}); + try x.link.from(rank, n); + try x.link.buf.download(64, out[done..][0..n]); + done += n; + } +} + +/// Rank 0: each other rank's bytes of `id` past its prefix (`each`) equal to `shared`, but for `loose` (zeros there). +pub fn same(e: *Engine, id: u64, each: []const u64, shared: []const u8, loose: []const image.Span, theirs: []u8) !void { + for (each[1..], 1..) |q, r| { + try take(e, @intCast(r), id, image.Words.bytes + q, theirs); + image.clear(loose, 0, theirs); + if (!std.mem.eql(u8, shared, theirs)) return error.RanksDiffer; + } +} + +/// Words read back for a state at `at`: refused by name unless this server's world and layout (unsplit) wrote them. +pub fn decode(e: *const Engine, x: [image.Words.count]u64, at: u32) !image.Words { + return image.Words.decode(x, at, @intCast(e.share.world), .unsplit); +} + +/// Rank 0: every rank's blank `id` sealed with `w` (its head's rows, ring bases and KDA copy bits). +pub fn seal(e: *Engine, id: u64, w: image.Words) !void { + try snapshots.seal(e, id, w.mtp_len, .{ w.base, w.mtp_base }, w.cur); + if (leader(e)) |x| { + const words = w.encode(); + try x.disk(.{ .kind = kind, .flags = @backingInt(Op.seal), .a = id }, std.mem.bytesAsSlice(u32, std.mem.sliceAsBytes(&words))); + } +} + +/// Rank 0: every rank's prefix bytes in rank order (what it holds alone), and where its window rows begin in it. +pub fn prefixes(e: *Engine, out: []u64, windows: []u64) !void { + const sh = try shape(e); + if (windows.len != out.len) return error.NoRank; + const x = leader(e) orelse { + if (out.len != 1) return error.NoRank; + out[0] = sh.prefix; + windows[0] = sh.window; + return; + }; + try x.disk(.{ .kind = kind, .flags = @backingInt(Op.prefixes) }, &.{}); + try gather(x.link, e, sh.prefix, out); + try gather(x.link, e, sh.window, windows); +} + +fn gather(l: *follow.Link, e: *const Engine, mine: u64, out: []u64) !void { + try @import("cuda_ranks.zig").gather(u64, l.d, l.lib, l.comm, l.stream, e.share.rank, mine, out); +} + +/// A rank other than 0: rank 0's disk step on this rank's copy of its state. +pub fn step(e: *Engine, l: *follow.Link, h: follow.Header, ids: []const u32) !void { + if (h.flags < @backingInt(Op.blank) or h.flags > @backingInt(Op.prefixes)) return error.BadStep; + const op: Op = @fromBackingInt(h.flags); + const rank: u32 = @intCast(e.share.rank); + switch (op) { + .blank => try snapshots.blankAs(e, h.a, @intCast(h.seed)), + .seal => { + if (ids.len != image.Words.count * 2) return error.BadStep; + var x: [image.Words.count]u64 = undefined; + @memcpy(std.mem.sliceAsBytes(&x), std.mem.sliceAsBytes(ids)); + const w = try decode(e, x, @intCast((e.snaps.get(h.a) orelse return error.NoKeptState).pos)); + try snapshots.seal(e, h.a, w.mtp_len, .{ w.base, w.mtp_base }, w.cur); + }, + .rows => { + try fits(ids, h.depth, l.buf.len - 64); + try l.from(0, h.depth); + try place(e, h.a, ids, l.buf.ptr + 64, l.stream); + }, + .take => { + if (h.depth > l.ids.len * 4) return error.BadStep; + if (h.top_k == rank) { + const host = std.mem.sliceAsBytes(l.ids)[0..h.depth]; + try copy(e, h.a, h.seed, host, true); + try l.buf.uploadAsync(64, host, l.stream.handle); + } + try l.from(h.top_k, h.depth); + }, + .prefixes => { + var out: [64]u64 = undefined; + if (e.share.world > out.len) return error.BadStep; + const sh = try shape(e); + try gather(l, e, sh.prefix, out[0..e.share.world]); + try gather(l, e, sh.window, out[0..e.share.world]); + }, + } +} diff --git a/zig/src/families/glm/cuda_disk_ranks_test.zig b/zig/src/families/glm/cuda_disk_ranks_test.zig new file mode 100644 index 00000000000..b2db547e0b5 --- /dev/null +++ b/zig/src/families/glm/cuda_disk_ranks_test.zig @@ -0,0 +1,294 @@ +//! GLM disk steps across ranks on host memory and a fake link: a failed blank, byte order, refusals, shared bytes. +const std = @import("std"); +const cuda = @import("cuda"); +const ranks = @import("cuda_disk_ranks.zig"); +const image = @import("cuda_disk_image.zig"); +const follow = @import("cuda_follow.zig"); +const snapshots = @import("cuda_snapshots.zig"); +const pages = @import("cuda_snapshot_pages.zig"); +const fixture = @import("cuda_disk_image_test.zig"); +const State = @import("cuda_state.zig").State; +const Seq = @import("cuda_engine_types.zig").Seq; +const Engine = @import("cuda_engine.zig").Engine; +const t = std.testing; + +/// The link's kernel and NCCL: the put kernel records each step's header; a broadcast fails, or brings a rank's bytes. +const Wire = struct { + var fail = false; + var odd: c_int = 0; // a rank whose bytes differ from rank 0's (0: none) + var sent: [8]follow.Header = undefined; + var steps: usize = 0; + var casts: usize = 0; + + fn reset() void { + fail = false; + odd = 0; + steps = 0; + casts = 0; + } + fn byte(i: usize) u8 { + return @truncate(i *% 13 +% 5); + } + fn put(_: cuda.abi.Function, _: c_uint, _: c_uint, _: c_uint, _: c_uint, _: c_uint, _: c_uint, _: c_uint, _: cuda.abi.Stream, params: ?[*]?*anyopaque, _: ?[*]?*anyopaque) callconv(.c) cuda.abi.Result { + const w: *align(1) const follow.Words = @ptrCast(params.?[2].?); + if (steps < sent.len) @memcpy(std.mem.asBytes(&sent[steps]), std.mem.sliceAsBytes(w.w[0..16])); + steps += 1; + return 0; + } + fn broadcast(_: cuda.abi.DevicePtr, dst: cuda.abi.DevicePtr, n: usize, _: cuda.nccl.DataType, root: c_int, _: cuda.nccl.Comm, _: cuda.abi.Stream) callconv(.c) cuda.nccl.Result { + if (fail) return 1; + casts += 1; + if (root != 0) for (@as([*]u8, @ptrFromInt(dst))[0..n], 0..) |*b, i| { + b.* = byte(i) ^ @intFromBool(root == odd); + }; + return 0; + } + fn device(out: *cuda.abi.Device) callconv(.c) cuda.abi.Result { + out.* = 0; + return 0; + } + fn attribute(out: *c_int, _: cuda.abi.DeviceAttribute, _: cuda.abi.Device) callconv(.c) cuda.abi.Result { + out.* = 0; // a discrete card: a download copies straight to the host + return 0; + } +}; + +/// A TP=2 engine's rank 0 over host memory (the fields the disk steps read), its snapshot pool and its link. +const Rig = struct { + m: fixture.Model, + d: cuda.Driver, + lib: cuda.nccl.Library, + seq: Seq, + e: *Engine, + buf: [64 + 64 * 4]u8 align(8), // the link's device buffer: header, then ids + ids: [64]u32, + link: follow.Link, + + fn init(x: *Rig) !void { + const a = t.allocator; + Wire.reset(); + try x.m.init(); + x.d = fixture.H.driver(); + x.d.api.cuLaunchKernel = Wire.put; + x.d.api.cuLaunchKernelEx = @import("cuda_pdl.zig").forwardEx(Wire.put); // GLM's launches go through cuda_pdl + x.d.api.cuCtxGetDevice = Wire.device; + x.d.api.cuDeviceGetAttribute = Wire.attribute; + x.lib = .{ .lib = undefined, .api = undefined }; + x.lib.api.ncclBroadcast = Wire.broadcast; + x.seq = .{ .st = try State.initFormat(a, &x.d, &x.m.w, fixture.capacity, false) }; + errdefer x.seq.st.deinit(); + const e = try a.create(Engine); + e.gpa = a; + e.d = &x.d; + e.c = x.m.w.config; + e.share = x.m.w.share; + e.cur = &x.seq; + e.capacity = fixture.capacity; + e.mtp = true; + e.slot = 0; + e.stream = .{ .d = &x.d, .handle = null }; + e.m.glue.put_words = .{ .d = &x.d, .handle = null }; + e.share_pages = false; + e.next_snap = 1; + e.announce = 0; + e.snaps = .empty; + e.dropped = .empty; + e.snap_pages = null; + x.e = e; + errdefer x.free(); + try e.snaps.ensureTotalCapacity(a, 8); + try e.dropped.ensureTotalCapacity(a, 9); + e.snap_pages = try pages.Pool.init(a, &x.d, 256 << 20, false); + x.link = .{ .d = &x.d, .lib = &x.lib, .comm = null, .stream = e.stream, .buf = .{ .d = &x.d, .ptr = @intFromPtr(&x.buf), .len = x.buf.len, .borrowed = true }, .ids = &x.ids, .gpa = a, .wait = false }; + } + + fn free(x: *Rig) void { + const e = x.e; + var it = e.snaps.valueIterator(); + while (it.next()) |s| snapshots.free(e, s); + e.snaps.deinit(e.gpa); + e.dropped.deinit(e.gpa); + if (e.snap_pages) |*p| p.deinit(); + e.gpa.destroy(e); + } + + fn deinit(x: *Rig) void { + ranks.link = null; + x.free(); + x.seq.st.deinit(); + } +}; + +const disk = @backingInt(follow.Kind.disk); + +fn op(o: ranks.Op) u32 { + return @backingInt(o); +} + +test "GLM disk ranks: a blank whose step fails on the link gives rank 0's lease back, and the next step drops it" { + var x: Rig = undefined; + try x.init(); + defer x.deinit(); + ranks.link = &x.link; + const pool = &x.e.snap_pages.?; + const all = pool.spare(); + Wire.fail = true; + try t.expectError(error.NcclFailed, ranks.blank(x.e, 2048)); + try t.expectEqual(@as(u32, 0), x.e.snaps.count()); + try t.expectEqual(all, pool.spare()); + try t.expectEqualSlices(u32, &.{1}, x.e.dropped.items); // the step may have reached the others: they drop it + Wire.reset(); + const id = try ranks.blank(x.e, 2048); + try t.expectEqual(@as(u64, 2), id); // the dropped id is not used again + try t.expectEqual(@as(usize, 2), Wire.steps); + try t.expectEqual(@backingInt(follow.Kind.drop), Wire.sent[0].kind); + try t.expectEqual(@as(u32, 1), Wire.sent[0].n); + try t.expectEqual(disk, Wire.sent[1].kind); + try t.expectEqual(op(.blank), Wire.sent[1].flags); + try t.expectEqual(id, Wire.sent[1].a); + try t.expect(pool.spare() < all); +} + +test "GLM disk ranks: rank 0's link carries the disk steps at TP only, and its deinit leaves none behind" { + var x: Rig = undefined; + try x.init(); + defer x.deinit(); + var l = x.link; + l.ids = try t.allocator.alloc(u32, 4); + l.lead(true, 1); // one rank: every op stays local + try t.expect(l.asleep and ranks.link == null); + l.lead(false, 2); + try t.expect(!l.asleep and ranks.link == &l); + var other = x.link; + other.ids = try t.allocator.alloc(u32, 4); + other.deinit(); // another link's end leaves rank 0's + try t.expect(ranks.link == &l); + l.deinit(); + try t.expect(ranks.link == null); +} + +test "GLM disk ranks: a blank state takes bytes past its words and front only once sealed" { + var x: Rig = undefined; + try x.init(); + defer x.deinit(); + const at: u32 = 2048; + const id = try ranks.blank(x.e, at); // one rank: no link + const front: usize = @intCast(image.Words.bytes + image.front(try ranks.shape(x.e), at)); + const buf = try t.allocator.alloc(u8, front + 64); + defer t.allocator.free(buf); + @memset(buf, 0); + try ranks.copy(x.e, id, 0, buf[0..front], false); + try t.expectError(error.DiskOrder, ranks.copy(x.e, id, front - 8, buf[0..16], false)); // across the front + try t.expectError(error.DiskOrder, ranks.copy(x.e, id, front, buf[0..1], true)); // read out, too + try snapshots.seal(x.e, id, at - 1, .{ 0, 0 }, 0); + try ranks.copy(x.e, id, front - 8, buf[0..16], false); + try ranks.copy(x.e, id, front, buf[0..1], true); +} + +test "GLM disk ranks: a follower refuses a disk step rank 0 does not send, before its states or the link" { + var x: Rig = undefined; + try x.init(); + defer x.deinit(); + x.e.share.rank = 1; + const room = x.link.ids.len * 4; + const bad = [_]struct { h: follow.Header, n: usize }{ + .{ .h = .{ .kind = disk, .flags = 0 }, .n = 0 }, // no op + .{ .h = .{ .kind = disk, .flags = op(.prefixes) + 1 }, .n = 0 }, // past the last op + .{ .h = .{ .kind = disk, .flags = op(.seal), .a = 1 }, .n = 1 }, // words of another length + .{ .h = .{ .kind = disk, .flags = op(.rows), .a = 1, .depth = 8 }, .n = 3 }, // a table of part pieces + .{ .h = .{ .kind = disk, .flags = op(.rows), .a = 1, .depth = 9 }, .n = 4 }, // pieces of other bytes than the step's + .{ .h = .{ .kind = disk, .flags = op(.rows), .a = 1, .depth = @intCast(room + 1) }, .n = 0 }, // past the link + .{ .h = .{ .kind = disk, .flags = op(.take), .a = 1, .depth = @intCast(room + 1), .top_k = 0 }, .n = 0 }, // past the link + }; + x.ids[0..4].* = .{ image.Words.bytes, 0, 8, 1 }; // one piece of 8 bytes for rank 1 + for (bad) |b| try t.expectError(error.BadStep, ranks.step(x.e, &x.link, b.h, x.ids[0..b.n])); + x.e.share.world = 65; // more ranks than a gather holds + try t.expectError(error.BadStep, ranks.step(x.e, &x.link, .{ .kind = disk, .flags = op(.prefixes) }, &.{})); + try t.expectEqual(@as(u32, 0), x.e.snaps.count()); + try t.expectEqual(@as(usize, 0), Wire.casts); +} + +test "GLM disk ranks: each other rank's shared bytes come from past its own prefix and must equal rank 0's" { + var x: Rig = undefined; + try x.init(); + defer x.deinit(); + ranks.link = &x.link; + const prefixes = [_]u64{ 4096, 1024, 2048 }; // TP=3: each rank's own bytes first + var shared: [100]u8 = undefined; + for (&shared, 0..) |*b, i| b.* = Wire.byte(i); + var theirs: [100]u8 = undefined; + try ranks.same(x.e, 7, &prefixes, &shared, &.{}, &theirs); + try t.expectEqual(@as(usize, 2), Wire.steps); + for (Wire.sent[0..2], 1..) |h, r| { + try t.expectEqual(op(.take), h.flags); + try t.expectEqual(@as(u64, 7), h.a); + try t.expectEqual(@as(u32, @intCast(r)), h.top_k); + try t.expectEqual(image.Words.bytes + prefixes[r], h.seed); + try t.expectEqual(@as(u32, theirs.len), h.depth); + } + // bytes a prompt pass does not write are left out: rank 0's as zeros, each other rank's whatever it holds there + const loose = [_]image.Span{.{ .off = 10, .len = 20 }}; + image.clear(&loose, 0, &shared); + try t.expectError(error.RanksDiffer, ranks.same(x.e, 7, &prefixes, &shared, &.{}, &theirs)); + try ranks.same(x.e, 7, &prefixes, &shared, &loose, &theirs); + Wire.odd = 2; + try t.expectError(error.RanksDiffer, ranks.same(x.e, 7, &prefixes, &shared, &loose, &theirs)); +} + +test "GLM disk ranks: rank 0 sends a block's pieces for every rank in as few steps as the link holds, and copies the shared ones itself" { + var x: Rig = undefined; + try x.init(); + defer x.deinit(); + ranks.link = &x.link; + const at: u32 = 2048; + const id = try ranks.blank(x.e, at); + const own = (try ranks.shape(x.e)).prefix; + var bytes: [440]u8 = undefined; + for (&bytes, 0..) |*b, i| b.* = Wire.byte(i); + const w = image.Words.bytes; + const pieces = [_]ranks.Piece{ + .{ .to = ranks.every, .off = w + 16, .bytes = bytes[0..100] }, // every rank's, past its own prefix + .{ .to = 1, .off = w + 8, .bytes = bytes[100..140] }, + .{ .to = 2, .off = w, .bytes = bytes[140..440] }, // longer than the link's room (256 bytes) with the rest + }; + try ranks.rows(x.e, id, &pieces); + try t.expectEqual(@as(usize, 3), Wire.steps); // the blank, then two rows steps for the 440 bytes + const want = [_]struct { depth: u32, n: u32 }{ .{ .depth = 256, .n = 12 }, .{ .depth = 184, .n = 4 } }; + for (Wire.sent[1..3], want) |h, g| { + try t.expectEqual(disk, h.kind); + try t.expectEqual(op(.rows), h.flags); + try t.expectEqual(id, h.a); + try t.expectEqual(g.depth, h.depth); + try t.expectEqual(g.n, h.n); + } + var got: [100]u8 = undefined; + try ranks.copy(x.e, id, own + w + 16, &got, true); // rank 0's own copy of the shared bytes + try t.expectEqualSlices(u8, bytes[0..100], &got); + try t.expectEqualSlices(u8, bytes[256..440], x.buf[64..][0..184]); // the last step's bytes went out whole +} + +test "GLM disk ranks: a follower copies its pieces and the shared ones from the step's broadcast, and no other rank's" { + var x: Rig = undefined; + try x.init(); + defer x.deinit(); + x.e.share.rank = 1; + const at: u32 = 2048; + try snapshots.blankAs(x.e, 3, at); + const own = (try ranks.shape(x.e)).prefix; + const w = image.Words.bytes; + var before: [64]u8 = undefined; + try ranks.copy(x.e, 3, w, &before, true); + for (x.buf[64..][0..100], 0..) |*b, i| b.* = Wire.byte(i); // the bytes as rank 0's broadcast leaves them + const table = [_]u32{ w + 4, 0, 50, ranks.every, w + 8, 0, 30, 1, w, 0, 20, 2 }; + @memcpy(x.ids[0..table.len], &table); + try ranks.step(x.e, &x.link, .{ .kind = disk, .flags = op(.rows), .a = 3, .depth = 100 }, x.ids[0..table.len]); + var got: [50]u8 = undefined; + try ranks.copy(x.e, 3, own + w + 4, &got, true); + try t.expectEqualSlices(u8, x.buf[64..][0..50], &got); + try ranks.copy(x.e, 3, w + 8, got[0..30], true); + try t.expectEqualSlices(u8, x.buf[64 + 50 ..][0..30], got[0..30]); + var after: [64]u8 = undefined; + try ranks.copy(x.e, 3, w, &after, true); + try t.expectEqualSlices(u8, before[0..8], after[0..8]); // rank 2's piece at w did not land here + try t.expectEqual(@as(usize, 1), Wire.casts); +} diff --git a/zig/src/families/glm/cuda_engine.zig b/zig/src/families/glm/cuda_engine.zig index 8a12f93a821..f69e7f72e7d 100644 --- a/zig/src/families/glm/cuda_engine.zig +++ b/zig/src/families/glm/cuda_engine.zig @@ -284,10 +284,10 @@ pub const Engine = struct { const freeProfs = @import("cuda_engine_prof.zig").freeProfs; /// The serving group, its RoCE wires open: the main stream's and the boundary's gathers take its route now. - pub fn installGroup(e: *Engine, g: *cuda.tp_group.Group) void { + pub fn installGroup(e: *Engine, g: *cuda.tp_group.Group, from: []const u8) void { e.group = g; e.backend.group = g; - std.log.info("[tensorfold] glm: rank {d} of {d} sums through the {t} collective (RoCE gathers {s})", .{ g.rank, g.world, e.collective.kind(), if (g.fast != null or g.multi != null) "on" else "off" }); + std.log.info("[tensorfold] glm: rank {d} of {d} ({s}) sums through the {t} collective (RoCE gathers {s})", .{ g.rank, g.world, from, e.collective.kind(), if (g.fast != null or g.multi != null) "on" else "off" }); } pub fn exchange(e: *const Engine) fw.Exchange { diff --git a/zig/src/families/glm/cuda_env_test.zig b/zig/src/families/glm/cuda_env_test.zig index 16f3953edf9..cf54528635f 100644 --- a/zig/src/families/glm/cuda_env_test.zig +++ b/zig/src/families/glm/cuda_env_test.zig @@ -18,6 +18,7 @@ const switches = [_]Name{ .{ .name = "TF_GLM_DSEL", .default = true }, .{ .name = "TF_GLM_DSCORES", .default = true }, .{ .name = "TF_GLM_MOE_DIRECT" }, + .{ .name = "TF_GLM_WIDE_EXPERT_TILE" }, }; const counts = [_][:0]const u8{"TF_GLM_DFLASH2_LOG"}; const reals = [_][:0]const u8{"TF_GLM_DRAFT_CONFIDENCE"}; @@ -129,6 +130,7 @@ test "GLM strict env: the actual readers and the open's check keep defaults, 0 a .{ .name = "TF_GLM_HOST_CACHE", .read = @import("cuda_snapshot_pages.zig").onHost }, .{ .name = "TF_GLM_VISION_HOST", .read = @import("cuda_vision_weights.zig").onHost }, .{ .name = "TF_GLM_PROF", .read = @import("cuda_prof.zig").Prof.wanted }, + .{ .name = "TF_GLM_WIDE_EXPERT_TILE", .read = @import("cuda_experts.zig").wideExpertTile }, }; const startup = @import("cuda_env.zig").startup; for (cases) |c| { diff --git a/zig/src/families/glm/cuda_experts.zig b/zig/src/families/glm/cuda_experts.zig index 701680d06f6..077326c7e0b 100644 --- a/zig/src/families/glm/cuda_experts.zig +++ b/zig/src/families/glm/cuda_experts.zig @@ -18,6 +18,7 @@ pub const Kernels = struct { nvfp4: cuda.experts.Nvfp4Experts, b32: ?cuda.experts32.Nvfp4b32Experts, // loaded for a csf0_v1 checkpoint alone (wantsBlock32) router: cuda.grouped.Router, + wide_tile: bool = false, // TF_GLM_WIDE_EXPERT_TILE: matching 64-pair down on factored decode windows fact: u64 = 0, // bit r - 1: a decode window of r rows on NVFP4's factored tiles (the same bits); load timing picks them by width (cuda_lane_costs) /// Whether a decode window of `rows` runs on the factored tiles; past 64 rows, as 64 do. @@ -28,11 +29,12 @@ pub const Kernels = struct { /// `plans`: the loaded experts module (its plan kernels); `block32`: block 32's image too, for these values. pub fn load(d: *const cuda.Driver, plans: cuda.Module, sms: u32, block32: ?cuda.experts32.Values) !Kernels { + const wide_tile = try wideExpertTile(); var nvfp4 = try cuda.experts.Nvfp4Experts.load(d, sms); errdefer nvfp4.unload(); var b32: ?cuda.experts32.Nvfp4b32Experts = if (block32) |v| try cuda.experts32.Nvfp4b32Experts.load(d, sms, v) else null; errdefer if (b32) |*x| x.unload(); - return .{ .nvfp4 = nvfp4, .b32 = b32, .router = try cuda.grouped.Router.resolve(plans) }; + return .{ .nvfp4 = nvfp4, .b32 = b32, .router = try cuda.grouped.Router.resolve(plans), .wide_tile = wide_tile }; } pub fn unload(k: *Kernels) void { @@ -71,7 +73,9 @@ pub fn run(ks: *const Kernels, stream: cuda.Stream, which: Which, l: cuda.expert const pairs = rows * plan.slots; if (plan.prompt) return g.prompt(stream, epi, in, l, plan.route, out, maxItems(pairs, plan.experts, staged_tile), pairs, staged_tile, skip); if (plan.fact) { - // gate-up reads two matrices a K tile and gains from the factored tiles; down is short and keeps the waves + if (ks.wide_tile and rows > tile and epi == .down_f32 and l.format == .nvfp4) + return cuda.experts.Nvfp4Experts.runFact(&ks.nvfp4, stream, epi, in, l, plan.route, out, maxItems(pairs, plan.experts, staged_tile), skip); + // Gate-up keeps its factored tile; other down calls retain the original waves. if (epi == .up and !l.relu2) return cuda.experts.Nvfp4Experts.runFact(&ks.nvfp4, stream, epi, in, l, plan.route, out, maxItems(pairs, plan.experts, staged_tile), skip); return cuda.experts_waves.run(&ks.nvfp4, stream, epi, in, l, plan.route, out, maxItems(pairs, plan.experts, tile), skip); } @@ -134,3 +138,8 @@ test "plan sizes as the Python family's" { try std.testing.expectEqual(@as(usize, staged_tile), cuda.experts.promptTile(.nvfp4)); try std.testing.expectEqual(@as(usize, 128), pair_tile); } + +/// Read once before expert modules load; every rank's startup also validates the shared GLM scope. +pub fn wideExpertTile() !bool { + return @import("sys").environment.read(bool, "TF_GLM_WIDE_EXPERT_TILE", false); +} diff --git a/zig/src/families/glm/cuda_follow.zig b/zig/src/families/glm/cuda_follow.zig index 1e8724243b5..3561a154bb5 100644 --- a/zig/src/families/glm/cuda_follow.zig +++ b/zig/src/families/glm/cuda_follow.zig @@ -16,7 +16,7 @@ const sparse = @import("cuda_sparse.zig"); const prompt_pair = @import("cuda_prompt_pair.zig"); const Engine = engine.Engine; -pub const Kind = enum(u32) { begin = 1, prefill, verify, keep, draft, end, drop, release, chunk, shared, image, block, many, redraw, idle, snapshots, pool, form, cuts }; +pub const Kind = enum(u32) { begin = 1, prefill, verify, keep, draft, end, drop, release, chunk, shared, image, block, many, redraw, idle, snapshots, pool, form, cuts, disk }; /// One step as it crosses: 64 bytes, then `n` u32 ids. pub const Header = extern struct { @@ -67,7 +67,14 @@ pub const Link = struct { return .{ .d = d, .lib = lib, .comm = comm, .stream = stream, .buf = buf, .ids = try gpa.alloc(u32, max_ids), .gpa = gpa, .wait = wait }; } + /// Rank 0, before it serves: whether the other ranks begin asleep; at TP its kept states' disk steps cross here. + pub fn lead(l: *Link, asleep: bool, world: usize) void { + l.asleep = asleep; + if (world > 1) @import("cuda_disk_ranks.zig").link = l; + } + pub fn deinit(l: *Link) void { + if (@import("cuda_disk_ranks.zig").link == l) @import("cuda_disk_ranks.zig").link = null; l.gpa.free(l.ids); l.buf.free(); } @@ -114,6 +121,14 @@ pub const Link = struct { try l.lib.check(l.lib.api.ncclBroadcast(ptr, ptr, bytes, .u8, 0, l.comm, l.stream.handle), "ncclBroadcast"); } + /// `bytes` after the header from rank `root` into every rank's buffer (a disk step's take: cuda_disk_ranks). + pub fn from(l: *Link, root: u32, bytes: usize) !void { + if (bytes == 0) return; + if (64 + bytes > l.buf.len) return error.TooManyIds; + try l.lib.check(l.lib.api.ncclBroadcast(l.buf.ptr + 64, l.buf.ptr + 64, bytes, .u8, @intCast(root), l.comm, l.stream.handle), "ncclBroadcast"); + try l.stream.synchronize(); + } + /// Other ranks: the next step and its ids (valid until the next receive). pub fn receive(l: *Link) !struct { h: Header, ids: []const u32 } { try l.bcast(first_bytes); @@ -329,6 +344,14 @@ pub const Leader = struct { x.e.m.experts.fact = forms; } + /// A kept state's disk step (cuda_disk_ranks): its op and ids to every rank. + pub fn disk(x: Leader, h: Header, ids: []const u32) !void { + try x.flush(); + var hh = h; + hh.kind = @backingInt(Kind.disk); + try x.send(hh, ids); + } + /// The other ranks leave their loops. pub fn end(x: Leader) !void { try x.send(.{ .kind = @backingInt(Kind.end) }, &.{}); @@ -363,7 +386,7 @@ pub fn follow(e: *Engine, link: *Link) !void { const step = try link.receive(); const h = step.h; const kind: Kind = @fromBackingInt(@intCast(h.kind)); - if (kind != .end and kind != .drop and kind != .shared and kind != .block and kind != .many and kind != .idle and kind != .snapshots and kind != .pool and kind != .form) try e.bind(h.slot); + if (kind != .end and kind != .drop and kind != .shared and kind != .block and kind != .many and kind != .idle and kind != .snapshots and kind != .pool and kind != .form and kind != .disk) try e.bind(h.slot); e.prompt_logprobs = if (promptRows(h)) .{} else null; e.structured = structuredStep(h); // rank 0 alone masks them switch (kind) { @@ -442,6 +465,7 @@ pub fn follow(e: *Engine, link: *Link) !void { e.share_pages = h.flags & 1 != 0; // TF_KV_SHARE on rank 0: a kept state leaves the shared store's pages out try @import("cuda_snapshots.zig").agree(e, h.a); }, + .disk => try @import("cuda_disk_ranks.zig").step(e, link, h, step.ids), .drop => for (step.ids) |id| e.dropState(id), .release => e.release(h.slot), .idle => cuda.tp_watch.sleep(e.io), diff --git a/zig/src/families/glm/cuda_lane_cost_measure.zig b/zig/src/families/glm/cuda_lane_cost_measure.zig index cecfb80d04b..dc98ac51d24 100644 --- a/zig/src/families/glm/cuda_lane_cost_measure.zig +++ b/zig/src/families/glm/cuda_lane_cost_measure.zig @@ -50,7 +50,7 @@ pub fn measure(timer: anytype, block: bool, pin: ?bool) !Kept { if (block) return k; for (&k.ms, forms[0], forms[1], 0..) |*m, classic, factored, i| m.* = if (on(k.fact, i)) factored else classic; } - try rule.smooth(w, &k.ms); + try rule.smoothSerial(w, &k.ms); const chain = [2]f64{ try rule.fastest(d, levels[0]), try rule.fastest(d, levels[1]) }; k.step_ms = @max(0, (chain[1] - chain[0]) / @as(f64, @floatFromInt(levels[1] - levels[0]))); return k; diff --git a/zig/src/families/glm/cuda_lane_costs.zig b/zig/src/families/glm/cuda_lane_costs.zig index b69018198ab..b857eec35fb 100644 --- a/zig/src/families/glm/cuda_lane_costs.zig +++ b/zig/src/families/glm/cuda_lane_costs.zig @@ -170,13 +170,14 @@ fn keyShape(e: *const engine.Engine, sm: usize, driver: c_int, shape: []u8, pin: const hex = std.fmt.bytesToHex(e.checkpoint_digest, .lower); const draft_hex = std.fmt.bytesToHex(if (e.drafter) |dr| dr.checkpoint_digest else @as([32]u8, @splat(0)), .lower); const tail: []const u8 = if (pin) |f| (if (f) " form factored" else " form classic") else ""; - return std.fmt.bufPrint(shape, "sm{d} cuda{d} ranks{d} {s} drafter{d}/{d}/{s} layers{d} l2{d}/{d}/{d}/{d}/{d} warps{d} kda{d} mm{d} bits{d}/{d} kv8{d} pages{d} host{d} roce{d} p2p{s}/{s}/{s} pad{d} pdl{d} dsel{d} wide{d}{s}", .{ + return std.fmt.bufPrint(shape, "sm{d} cuda{d} ranks{d} {s} drafter{d}/{d}/{s} layers{d} l2{d}/{d}/{d}/{d}/{d} warps{d} kda{d} mm{d} bits{d}/{d} kv8{d} pages{d} host{d} roce{d} p2p{s}/{s}/{s} pad{d} pdl{d} dsel{d} wide{d}{s}{s}", .{ sm, driver, e.share.world, hex[0..], @intFromBool(e.drafter != null), if (e.drafter) |dr| dr.bits else @as(u8, 0), draft_hex[0..], set.layers, @intFromBool(set.l2pf.on), @intFromBool(set.l2pf.named), set.l2pf.mb, set.l2pf.ctas, set.l2pf.pace_gbps, e.m.experts.nvfp4.warps, @intFromBool(set.kda_wide), @intFromBool(set.tiled), set.dense_bits, set.head_bits, @intFromBool(set.kv8), @intFromBool(set.pages), set.kv_host, @intFromBool(set.roce_multi), sys.getenv("NCCL_P2P_LEVEL") orelse "", sys.getenv("NCCL_MIN_NCHANNELS") orelse "", sys.getenv("NCCL_MAX_NCHANNELS") orelse "", - @intFromBool(set.kda_pad), @intFromBool(e.m.mm.pdl), @intFromBool(e.m.dsel), @intFromBool(set.roce_wide), tail, + @intFromBool(set.kda_pad), @intFromBool(e.m.mm.pdl), @intFromBool(e.m.dsel), @intFromBool(set.roce_wide), if (e.m.experts.wide_tile) " expertTile64" else "", + tail, }); } @@ -265,13 +266,14 @@ test "GLM cost identity: the consumed key includes drafter precision and all tim e.m.experts.nvfp4.warps = 4; e.m.mm.pdl = true; e.m.dsel = true; + e.m.experts.wide_tile = false; var dr: dflash.Drafter = undefined; dr.bits = 4; dr.checkpoint_digest = @splat(2); e.drafter = &dr; var base: [512]u8 = undefined; const before = try keyShape(&e, 121, 13000, &base, null); - for (0..15) |which| { + for (0..16) |which| { const original = e.settings; switch (which) { 0 => dr.bits = 0, @@ -289,6 +291,7 @@ test "GLM cost identity: the consumed key includes drafter precision and all tim 12 => e.m.mm.pdl = false, 13 => e.m.dsel = false, 14 => e.settings.roce_wide = true, + 15 => e.m.experts.wide_tile = true, else => unreachable, } var changed: [512]u8 = undefined; @@ -301,6 +304,7 @@ test "GLM cost identity: the consumed key includes drafter precision and all tim e.m.experts.nvfp4.warps = 4; e.m.mm.pdl = true; e.m.dsel = true; + e.m.experts.wide_tile = false; } // a named form only ends the identity, so the race's key stays as it was var classic: [512]u8 = undefined; @@ -357,6 +361,7 @@ test "GLM cost identity: a record kept at one named form is not reused at the ot e.m.experts.nvfp4.warps = 4; e.m.mm.pdl = true; e.m.dsel = true; + e.m.experts.wide_tile = false; e.drafter = null; var shapes: [2][512]u8 = undefined; var keys: [2][32]u8 = undefined; diff --git a/zig/src/families/glm/cuda_lanes.zig b/zig/src/families/glm/cuda_lanes.zig index 37eedcc152a..c38cfbeb047 100644 --- a/zig/src/families/glm/cuda_lanes.zig +++ b/zig/src/families/glm/cuda_lanes.zig @@ -266,10 +266,11 @@ pub const Lanes = struct { const self = of(ptr); const l = self.lanes.getPtr(s) orelse return; const at = l.fill orelse return; - if (at <= s.cached or s.reuse.hook == null) return; - try self.x.bind(l.slot); + if (at <= s.cached) return; var keeps: share_mod.Keeps = undefined; - _ = self.x.chunk(s.prompt(), at, false, null, .{ .ptr = null, .check = cancelNow }, self.marksOf(s, &keeps)) catch |err| { + const marks = self.marksOf(s, &keeps) orelse return; + try self.x.bind(l.slot); + _ = self.x.chunk(s.prompt(), at, false, null, .{ .ptr = null, .check = cancelNow }, marks) catch |err| { if (err == error.Cancelled) return; return err; }; diff --git a/zig/src/families/glm/cuda_native.zig b/zig/src/families/glm/cuda_native.zig index d3ee01332fa..5015f7c4b51 100644 --- a/zig/src/families/glm/cuda_native.zig +++ b/zig/src/families/glm/cuda_native.zig @@ -1,4 +1,4 @@ -//! GLM-5.3-Flash NVFP4 native CUDA at TP over processes (TF_GLM_RANK, NCCL_COMM_ID): rank 0 serves, others follow. +//! GLM-5.3-Flash NVFP4 native CUDA at TP over processes (--tp, --rank, NCCL's root): rank 0 serves, others follow. const std = @import("std"); const cuda = @import("cuda"); @@ -53,6 +53,11 @@ pub const Options = struct { drafter_bits: u8 = 4, // --drafter-bits: 4 (default) or 0 (bf16) mtp_confidence: ?f64 = null, // --mtp-confidence: rank 0's lanes stop an MTP chain where its chance falls under it learn_conversations: bool = false, // --learn-conversations: refused with TF_GLM_REQUEST_STARTS=1 (cuda_env) + rank: u32 = 0, // the launch's, resolved from --tp/--rank and TF_GLM_* (native/cuda_launch.zig) + tp: u32 = 1, + master: ?[]const u8 = null, + master_port: u16 = 29551, + launch_from: []const u8 = "", }; /// --drafter: DFlash2 (incoai/GLM-5.3-Flash-DFlash2, Apache-2.0 weights) drafts instead of the MTP head. pub const takes_drafter = true; @@ -130,33 +135,9 @@ pub fn kvPool(p: *anyopaque) ?kv.Source { return .{ .pool = &pages.pool, .page_tokens = @import("cuda_state.zig").page_rows }; } -/// This rank's place: TF_GLM_RANK of TF_GLM_WORLD (both, or neither for a refusal that names them). -pub const Place = struct { rank: usize, world: usize }; - -pub fn place() !Place { - const settings = @import("sys").environment; - const r = (try settings.read(?u64, "TF_GLM_RANK", null)) orelse return error.NoRank; - const w = (try settings.read(?u64, "TF_GLM_WORLD", null)) orelse return error.NoRank; - return checked(.{ .rank = @intCast(r), .world = @intCast(w) }); -} - -/// A place the family serves: a rank inside its world, and at most `ranks.max_world` ranks. -fn checked(p: Place) !Place { - if (p.world < 1 or p.rank >= p.world) return error.NoRank; - if (p.world > ranks.max_world) return error.TooManyRanks; - return p; -} - -/// Bytes this rank's weights take at most: the checkpoint (TF_GLM_LAYERS: the tensors read) times its largest share. -pub fn weightShare(a: std.mem.Allocator, io: std.Io, dir: []const u8, total: u64, drafts: bool) u64 { - const p = place() catch return total; - const path = std.fs.path.join(a, &.{ dir, "config.json" }) catch return total; - const text = std.Io.Dir.cwd().readFileAlloc(io, path, a, .limited(1 << 24)) catch return total; - const c = config.parse(a, text) catch return total; - const f = (shard.Share.of(&c, p.rank, p.world) catch return total).part(&c); - const whole = @import("cuda_thin_bytes.zig").count(a, io, dir, total, ranks.environment("TF_GLM_LAYERS"), c.layers, drafts and c.mtp > 0); - return @intCast(@as(u128, whole) * f[0] / f[1]); -} +const place_mod = @import("cuda_native_place.zig"); +pub const Place = place_mod.Place; +pub const weightShare = place_mod.weightShare; /// Slots for `context` plus a verify window, a multiple of 64 so the sparse pool keeps the AOT set. pub fn capacity(context: usize) usize { @@ -198,7 +179,8 @@ pub fn open(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: [ _ = kernels; // our own kernels: a captured set is not used try @import("cuda_env.zig").startup(); try @import("cuda_env.zig").requestStartsAlone(o.learn_conversations); // before any rank opens - const p = try place(); + try cuda.rendezvous.fromMaster(o, cuda.rendezvous.Process{}, cuda.rendezvous.Process{}); // NCCL's root, before anything reads it + const p = try place_mod.place(o); const roce_bytes = try roceBytes((@import("sys").environment.Process{}).get("TF_ROCE_MAX_KB")); if (p.world > 1 and std.c.getenv("NCCL_COMM_ID") == null) return error.NoCommId; var problem: []const u8 = ""; @@ -206,6 +188,7 @@ pub fn open(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: [ std.log.err("{s}", .{problem}); return err; }; + ranks.wirePieces(&set, p.world, &ranks.environment); try @import("cuda_roce_multi.zig").validate(p.world, p.rank, set.roce_multi); set.kv8 = o.kv8; if (share_mod.moved((@import("sys").environment.Process{}).get("TF_GLM_KV_SHARE") orelse "")) return error.GlmKvShareMoved; // before any rank opens @@ -331,7 +314,7 @@ fn finishRank(a: OpenArgs) !Loaded { errdefer if (own.group.fast) |f| f.deinit(); try @import("cuda_roce_multi.zig").open(gpa, io, ctx.d, &own.group, set.roce_multi); // three ranks or more, likewise errdefer if (own.group.multi) |m| m.deinit(m.ctx); - own.e.installGroup(&own.group); + own.e.installGroup(&own.group, o.launch_from); own.link = try follow.Link.init(gpa, ctx.d, &own.group.lib, own.group.comm, own.e.stream, try linkCapacity(cap, o.vision)); errdefer own.link.deinit(); try @import("cuda_prompt_logprobs.zig").prepare(own.e); @@ -368,7 +351,7 @@ fn finishRank(a: OpenArgs) !Loaded { // Rank 0 alone reads these: TF_GLM_PROMPT_STEPS=0 passes prompts whole, TF_GLM_SHARED=0 runs windows alone. const steps = try @import("sys").environment.value(bool, "TF_GLM_PROMPT_STEPS", ranks.environment("TF_GLM_PROMPT_STEPS"), true); const shared = try @import("sys").environment.value(bool, "TF_GLM_SHARED", ranks.environment("TF_GLM_SHARED"), true); - own.link.asleep = cuda.tp_watch.open(); // the other ranks begin asleep (follow): the first step wakes them + own.link.lead(cuda.tp_watch.open(), p.world); // the other ranks begin asleep (follow): the first step wakes them own.lanes = .{ .x = .{ .e = own.e, .link = &own.link }, .whole = !steps, .alone = !shared, .mtp_confidence = o.mtp_confidence }; const extra: u64 = (if (o.drafter != null) dflash.ring_bytes else 0) + if (own.e.images) |v| v.streamBytes() else @as(usize, 0); own.layout = if (set.pages) try pages_mod.layout(gpa, own.e, extra) else null; @@ -510,8 +493,10 @@ fn release(own: *Owned) void { pub fn explain(_: ?*anyopaque, err: anyerror) ?[]const u8 { return switch (err) { error.BadRoceCap => "TF_ROCE_MAX_KB: give an integer from 1 through 4194303 KiB, or unset it for 4096 KiB", - error.NoRank => "GLM-5.3-Flash runs at TP over hosts: set TF_GLM_RANK and TF_GLM_WORLD on every host (WORLD 1: one GPU, with TF_GLM_LAYERS for a thin model)", - error.NoCommId => "GLM-5.3-Flash's ranks meet over NCCL: with TF_GLM_WORLD 2 or more, set NCCL_COMM_ID to rank 0's address:port on every host", + error.NoRank => "GLM-5.3-Flash runs at TP over hosts: launch every host with --tp and a --rank below it (--tp 1: one GPU, with TF_GLM_LAYERS for a thin model)", + error.NoCommId => "GLM-5.3-Flash's ranks meet over NCCL: above one rank, give --master (rank 0's address) or set NCCL_COMM_ID to rank 0's address:port on every host", + error.RendezvousDisagree => "NCCL_COMM_ID differs from --master:--master-port: give one of them, or equal values", + error.MasterTooLong => "--master: too long for NCCL's root address (host:port in 320 bytes); give rank 0's address", error.RankMismatch => "the ranks' settings differ (each rank's log names the one): start them alike", error.Fp8OnPages => "--kv-cache fp8 keeps a window per stream: unset TF_KV_PAGES, or set it to auto or off", error.BadKvShare => "TF_KV_SHARE: give how many states the prompt store over the KV pages keeps, or 0 or unset for off", @@ -523,7 +508,7 @@ pub fn explain(_: ?*anyopaque, err: anyerror) ?[]const u8 { error.BadCopyPolicy => "TF_GLM_COPIES: expected 0 or 1 for verified root/context copies", error.InvalidEnvironment => "a TF_GLM_* setting is malformed: the error line before this one names it, its value and the accepted form", error.GlmKvHostNeedsPages => "TF_GLM_KV_HOST keeps the KV pool's pages in host memory: set TF_KV_PAGES=on (and --kv-cache bf16) as well", - error.TooManyRanks => std.fmt.comptimePrint("GLM-5.3-Flash on CUDA runs on at most {d} ranks: set TF_GLM_WORLD to {d} or fewer", .{ ranks.max_world, ranks.max_world }), + error.TooManyRanks => std.fmt.comptimePrint("GLM-5.3-Flash on CUDA runs on at most {d} ranks: launch with --tp {d} or fewer", .{ ranks.max_world, ranks.max_world }), error.NotModelOpt, error.UnsupportedQuant => "GLM-5.3-Flash on CUDA reads ModelOpt NVFP4, MIXED_PRECISION and EXL3 mcg checkpoints (the log names what config.json has)", error.UnreadableExl3 => "an EXL3 routed expert is not an mcg trellis of 1 to 8 bits with its marker and fp16 scales (the log names the tensor)", error.UnreadableFormat => "a projection is stored in a format GLM-5.3-Flash on CUDA does not read (the log names its module, recipe and tensors)", @@ -531,11 +516,8 @@ pub fn explain(_: ?*anyopaque, err: anyerror) ?[]const u8 { }; } -test "a place inside its world of at most 16 ranks serves; a larger world is refused by name" { - try std.testing.expectEqual(Place{ .rank = 15, .world = 16 }, try checked(.{ .rank = 15, .world = 16 })); - try std.testing.expectError(error.TooManyRanks, checked(.{ .rank = 0, .world = 17 })); - try std.testing.expectError(error.NoRank, checked(.{ .rank = 2, .world = 2 })); - try std.testing.expect(explain(null, error.TooManyRanks) != null); +test { + _ = place_mod; } test "a checkpoint refused for its format, at the entry or by the loader, is explained" { diff --git a/zig/src/families/glm/cuda_native_place.zig b/zig/src/families/glm/cuda_native_place.zig new file mode 100644 index 00000000000..13dd0cd8dc8 --- /dev/null +++ b/zig/src/families/glm/cuda_native_place.zig @@ -0,0 +1,39 @@ +//! A GLM rank's place from its resolved launch (native/cuda_launch.zig), its weight share and NCCL's rendezvous. +const std = @import("std"); +const config = @import("config.zig"); +const shard = @import("cuda_shard.zig"); +const ranks = @import("cuda_ranks.zig"); + +pub const Place = struct { rank: usize, world: usize }; + +/// This rank's place: `o.rank` of `o.tp`, as the launch resolved them (an empty `launch_from`: none was given). +pub fn place(o: anytype) !Place { + if (o.launch_from.len == 0) return error.NoRank; + return checked(.{ .rank = o.rank, .world = o.tp }); +} + +/// A place the family serves: a rank inside its world, and at most `ranks.max_world` ranks. +pub fn checked(p: Place) !Place { + if (p.world < 1 or p.rank >= p.world) return error.NoRank; + if (p.world > ranks.max_world) return error.TooManyRanks; + return p; +} + +/// Bytes this rank's weights take at most: the checkpoint (TF_GLM_LAYERS: the tensors read) times its largest share. +pub fn weightShare(a: std.mem.Allocator, io: std.Io, dir: []const u8, total: u64, drafts: bool, rank: u32, world: u32) u64 { + const p = checked(.{ .rank = rank, .world = world }) catch return total; + const path = std.fs.path.join(a, &.{ dir, "config.json" }) catch return total; + const text = std.Io.Dir.cwd().readFileAlloc(io, path, a, .limited(1 << 24)) catch return total; + const c = config.parse(a, text) catch return total; + const f = (shard.Share.of(&c, p.rank, p.world) catch return total).part(&c); + const whole = @import("cuda_thin_bytes.zig").count(a, io, dir, total, ranks.environment("TF_GLM_LAYERS"), c.layers, drafts and c.mtp > 0); + return @intCast(@as(u128, whole) * f[0] / f[1]); +} + +test "a place inside its world of at most 16 ranks serves; a larger world is refused by name" { + try std.testing.expectEqual(Place{ .rank = 15, .world = 16 }, try checked(.{ .rank = 15, .world = 16 })); + try std.testing.expectError(error.TooManyRanks, checked(.{ .rank = 0, .world = 17 })); + try std.testing.expectError(error.NoRank, checked(.{ .rank = 2, .world = 2 })); + try std.testing.expectEqual(Place{ .rank = 1, .world = 3 }, try place(.{ .rank = @as(u32, 1), .tp = @as(u32, 3), .launch_from = "--tp" })); + try std.testing.expectError(error.NoRank, place(.{ .rank = @as(u32, 0), .tp = @as(u32, 1), .launch_from = "" })); +} diff --git a/zig/src/families/glm/cuda_ranks.zig b/zig/src/families/glm/cuda_ranks.zig index bf7f4f6ef4a..1d042545254 100644 --- a/zig/src/families/glm/cuda_ranks.zig +++ b/zig/src/families/glm/cuda_ranks.zig @@ -123,8 +123,6 @@ pub const Settings = struct { problem.* = "TF_GLM_OVERLAP_PIECES: 1 to 8"; return error.BadSetting; } - } else if (s.solo and s.roce_multi and wireOpens(get)) { - s.pieces = 8; // TF_GLM_CHUNK_SOLO=4096 with TF_GLM_ROCE_MULTI=1: solo's doubled passes on the wire } if (get("TF_GLM_INDEX_SPLIT")) |v| { s.index_split = std.fmt.parseInt(u32, v, 10) catch { @@ -218,10 +216,16 @@ pub fn ownRoce(s: Settings, world: usize) bool { return !(s.roce_multi and world >= 3); } -/// Whether TF_GLM_ROCE_MULTI's wire opens at TF_GLM_WORLD: three ranks or more (cuda_roce_multi); TP=2 stays on NCCL. -fn wireOpens(get: *const fn ([:0]const u8) ?[]const u8) bool { - const v = get("TF_GLM_WORLD") orelse return false; - return (std.fmt.parseInt(usize, v, 10) catch 0) >= 3; +/// TF_GLM_CHUNK_SOLO with TF_GLM_ROCE_MULTI at three ranks or more (the wire opens; TP=2 stays on NCCL): 8 pieces. +pub fn wirePieces(s: *Settings, world: usize, comptime get: *const fn ([:0]const u8) ?[]const u8) void { + const set = if (get("TF_GLM_OVERLAP_PIECES")) |v| std.mem.trim(u8, v, " \t\r\n").len > 0 else false; // blank: unset, as `read` + if (!set and s.solo and s.roce_multi and world >= 3) s.pieces = 8; +} + +/// The tools' form (tf-cuda-test): the world from TF_GLM_WORLD, their input as it always was, not their own arguments. +pub fn toolPieces(s: *Settings, comptime get: *const fn ([:0]const u8) ?[]const u8) void { + const v = get("TF_GLM_WORLD") orelse return; + wirePieces(s, std.fmt.parseInt(usize, v, 10) catch return, get); } /// What every rank must agree on, as bytes the communicator carries. @@ -552,3 +556,33 @@ test "TF_GLM_PAIR_EXPERTS: off by default, 0 or 1, and every rank must agree" { const all = [_]Fingerprint{ Fingerprint.of(2, 0, on, 8192, true, @splat(0), @splat(0), @splat(0)), Fingerprint.of(2, 1, .{}, 8192, true, @splat(0), @splat(0), @splat(0)) }; try std.testing.expectEqual(Mismatch{ .field = .pair_experts, .rank = 1 }, mismatch(&all).?); } + +test "wire pieces: a blank override is unset; the tools' form takes its world from TF_GLM_WORLD" { + const Reader = struct { + fn at(key: [:0]const u8, world: ?[]const u8, pieces: ?[]const u8) ?[]const u8 { + if (std.mem.eql(u8, key, "TF_GLM_CHUNK_SOLO")) return "4096"; + if (std.mem.eql(u8, key, "TF_GLM_ROCE_MULTI")) return "1"; + if (std.mem.eql(u8, key, "TF_GLM_WORLD")) return world; + if (std.mem.eql(u8, key, "TF_GLM_OVERLAP_PIECES")) return pieces; + return null; + } + fn blank(key: [:0]const u8) ?[]const u8 { + return at(key, null, " "); + } + fn three(key: [:0]const u8) ?[]const u8 { + return at(key, "3", null); + } + fn none(key: [:0]const u8) ?[]const u8 { + return at(key, null, null); + } + }; + var s: Settings = .{ .solo = true, .roce_multi = true, .pieces = 3 }; + wirePieces(&s, 3, Reader.blank); + try std.testing.expectEqual(@as(u32, 8), s.pieces); + s.pieces = 3; + toolPieces(&s, Reader.three); + try std.testing.expectEqual(@as(u32, 8), s.pieces); + s.pieces = 3; + toolPieces(&s, Reader.none); + try std.testing.expectEqual(@as(u32, 3), s.pieces); +} diff --git a/zig/src/families/glm/cuda_ranks_test.zig b/zig/src/families/glm/cuda_ranks_test.zig index 170dca616e0..739f8d2639d 100644 --- a/zig/src/families/glm/cuda_ranks_test.zig +++ b/zig/src/families/glm/cuda_ranks_test.zig @@ -383,9 +383,16 @@ test "TF_GLM_OVERLAP_PIECES: unset, 8 under TF_GLM_CHUNK_SOLO=4096 with TF_GLM_R } }; var problem: []const u8 = ""; - try std.testing.expectEqual(@as(u32, 8), (try Settings.read(Reader.both, &problem)).pieces); - try std.testing.expectEqual(@as(u32, 3), (try Settings.read(Reader.bothTwo, &problem)).pieces); - try std.testing.expectEqual(@as(u32, 3), (try Settings.read(Reader.bothSet, &problem)).pieces); + // the wire opens at three ranks or more: the launch's world, given to wirePieces (TF_GLM_WORLD is an alias of --tp) + var at3 = try Settings.read(Reader.both, &problem); + ranks.wirePieces(&at3, 3, Reader.both); + try std.testing.expectEqual(@as(u32, 8), at3.pieces); + var at2 = try Settings.read(Reader.both, &problem); + ranks.wirePieces(&at2, 2, Reader.both); + try std.testing.expectEqual(@as(u32, 3), at2.pieces); + var set = try Settings.read(Reader.bothSet, &problem); + ranks.wirePieces(&set, 3, Reader.bothSet); + try std.testing.expectEqual(@as(u32, 3), set.pieces); try std.testing.expectEqual(@as(u32, 3), (try Settings.read(Reader.solo, &problem)).pieces); try std.testing.expectEqual(@as(u32, 3), (try Settings.read(Reader.wire, &problem)).pieces); try std.testing.expectEqual(@as(u32, 3), (try Settings.read(Reader.soloNarrow, &problem)).pieces); diff --git a/zig/src/families/glm/cuda_share.zig b/zig/src/families/glm/cuda_share.zig index ad4ec25ea7c..7966bcc0974 100644 --- a/zig/src/families/glm/cuda_share.zig +++ b/zig/src/families/glm/cuda_share.zig @@ -152,5 +152,6 @@ pub const Keeps = struct { /// The same content key names lookup and every completed or interrupted keep. pub fn marks(e: *engine.Engine, slot: u32, s: *const Stream, at: []const u32, keeps: *Keeps) ?engine.Marks { keeps.* = .{ .e = e, .slot = slot, .prompt = cacheKey(s) orelse return null, .images = s.images }; - return if (at.len == 0) null else .{ .at = at, .ctx = keeps, .call = Keeps.at, .interrupted = Keeps.at }; + // A cancellation can keep its last completed cut even when no later mark was scheduled. + return .{ .at = at, .ctx = keeps, .call = Keeps.at, .interrupted = Keeps.at }; } diff --git a/zig/src/families/glm/cuda_snapshot_pages.zig b/zig/src/families/glm/cuda_snapshot_pages.zig index 2e48cb6d4df..2b6f8040e26 100644 --- a/zig/src/families/glm/cuda_snapshot_pages.zig +++ b/zig/src/families/glm/cuda_snapshot_pages.zig @@ -19,7 +19,7 @@ const Arena = union(enum) { device: cuda.DeviceBuffer, host: struct { buf: cuda.HostBuffer, ptr: u64 }, - fn ptr(a: Arena) u64 { + pub fn ptr(a: Arena) u64 { return switch (a) { .device => |b| b.ptr, .host => |h| h.ptr, diff --git a/zig/src/families/glm/cuda_snapshots.zig b/zig/src/families/glm/cuda_snapshots.zig index bf8a9d7b6ce..8986ea83638 100644 --- a/zig/src/families/glm/cuda_snapshots.zig +++ b/zig/src/families/glm/cuda_snapshots.zig @@ -64,8 +64,42 @@ pub fn keepAs(e: anytype, id: u64) !void { } } +/// A disk read's state: `at`'s pages leased under rank 0's id on each rank, refused by `restore` until `seal`. +pub fn blankAs(e: anytype, id: u64, at: usize) !void { + if (e.snaps.contains(id)) return error.StateKept; + const pool = if (e.snap_pages) |*p| p else return error.NoSnapshotCache; + var lease = try pool.take(bytes(e, at)); + errdefer pool.give(&lease); + const cur = try e.gpa.alloc(u1, e.cur.st.cur.len); + @memset(cur, 0); + e.snaps.putAssumeCapacityNoClobber(id, .{ .lease = lease, .len = 0, .pos = at, .mtp_len = 0, .cur = cur, .bases = .{ 0, 0 } }); +} + +/// Whether an index ring of `rows` rows based at `base` holds every row up to `len`, as the image's ring bytes do. +fn ringHolds(base: usize, len: usize, rows: usize) bool { + return base <= len and len - base <= rows; +} + +/// A blank state made whole from its image's words (its bytes are in or follow): a restore takes it from here. +pub fn seal(e: anytype, id: u64, mtp_len: usize, bases: [2]usize, cur: u64) !void { + const s = e.snaps.getPtr(id) orelse return error.NoKeptState; + if (s.len != 0) return error.StateKept; + if (s.cur.len > 64 or (s.cur.len < 64 and cur >> @intCast(s.cur.len) != 0)) return error.DiskWords; + const head = if (e.mtp) @min(e.capacity, s.pos + @import("cuda_state.zig").window_rows) else 0; + if (mtp_len > head) return error.DiskWords; + const rows = e.cur.st.ring_rows; + if (!ringHolds(bases[0], s.pos, rows) or !ringHolds(bases[1], mtp_len, rows)) return error.DiskWords; + const n = try layout.Plan.size(&e.cur.st, &e.c, e.capacity, s.pos, if (e.mtp) mtp_len else null, s.shared); + if (n == 0 or n > s.lease.ids.items.len * pages.page) return error.SnapshotSize; + for (s.cur, 0..) |*b, i| b.* = @intCast(cur >> @intCast(i) & 1); + s.len = n; + s.mtp_len = mtp_len; + s.bases = bases; +} + pub fn restore(e: anytype, id: u64) !void { const s = e.snaps.getPtr(id) orelse return error.NoKeptState; + if (s.len == 0) return error.UnsealedState; const pool = if (e.snap_pages) |*p| p else return error.NoSnapshotCache; // the kept state's own parity picks the half a live-half keep carries; the slot's dead half stays as it is const plan = try layout.Plan.initFor(&e.cur.st, &e.c, s.pos, if (e.mtp) s.mtp_len else null, s.shared, s.cur); diff --git a/zig/src/families/glm/timing.zig b/zig/src/families/glm/timing.zig index fc0716bd703..b6ce85ff348 100644 --- a/zig/src/families/glm/timing.zig +++ b/zig/src/families/glm/timing.zig @@ -26,14 +26,37 @@ pub fn measure(sl: *Slots, gpa: std.mem.Allocator, io: std.Io) !?Costs { var shape: [96]u8 = undefined; const parts = [_][]const u8{ "glm-metal-pair", std.mem.span(e.device.name()), try std.fmt.bufPrint(&shape, "{d}/{d}/{d}/{d}/{d}/{d}", .{ e.c.layers, e.c.hidden, e.c.experts, e.c.tp, e.c.inter[1] - e.c.inter[0], @intFromBool(e.hasMtp()) }) }; const key = if (lead) lanes.cost_cache.key(gpa, io, &parts) catch null else null; - const kept = if (key) |k| lanes.cost_cache.load(Costs, gpa, io, k) else null; - if (!try e.agree(kept == null)) { // rank 0's word: both Macs time, or neither does - if (kept) |c| report(c, "kept"); - return kept; - } + var kept = if (key) |k| lanes.cost_cache.load(Costs, gpa, io, k) else null; + if (kept) |table| for (table.window, 0..) |w, i| { + if (w.width != i + 1 or !(w.ms > 0) or !std.math.isFinite(w.ms)) { + kept = null; + break; + } + }; + const cold = try e.agree(kept == null); // the leader decides whether both ranks measure or heal var scratch: Scratch = .{ .sl = sl, .io = io }; + defer if (scratch.started) sl.release(0); + if (!cold) { + var costs: Costs = if (kept) |c| c else undefined; + var values: [st.max_rows]f64 = @splat(0); + var widths: [st.max_rows]u32 = undefined; + for (&widths, 0..) |*w, i| w.* = @intCast(i + 1); + if (lead) for (costs.window, &values) |w, *m| { + m.* = w.ms; + }; + const cursor_key = if (key) |k| lanes.cost_cache.buildKey(&k, &.{"metal-heal-v2"}) else null; + var cursor: u64 = if (cursor_key) |k| lanes.cost_cache.load(u64, gpa, io, k) orelse 0 else 0; + const before = cursor; + var timer: WarmTimer = .{ .s = &scratch, .wall = .{ .io = io } }; + const stats = try cost_rule.warm_prices.prepared(&timer, &values, &widths, &cursor, 0, Agree{ .slots = sl }, lead); + if (!lead) return null; + for (&costs.window, values) |*w, m| w.ms = m; + if (stats.lowered > 0) if (key) |k| lanes.cost_cache.save(Costs, gpa, io, k, costs); + if (cursor != before) if (cursor_key) |k| lanes.cost_cache.save(u64, gpa, io, k, cursor); + report(costs, "checked"); + return costs; + } try scratch.start(); - defer sl.release(0); const ref_key = lanes.cost_cache.referenceKey(&parts); const reference = if (lead) lanes.cost_cache.load(Timed, gpa, io, ref_key) else null; const t = try schedule(WindowTimer{ .s = &scratch }, HeadTimer{ .s = &scratch }, Agree{ .slots = sl }, lead, e.hasMtp(), reference); @@ -49,17 +72,17 @@ fn report(c: Costs, how: []const u8) void { std.log.info("glm: the pair's windows ({s}): {d:.2} {d:.2} {d:.2} {d:.2} {d:.2} ms at 1-5 rows, {d:.2} at 16, a head step {d:.2} ms", .{ how, c.window[0].ms, c.window[1].ms, c.window[2].ms, c.window[3].ms, c.window[4].ms, c.window[15].ms, c.head_ms }); } -/// The same calls on both Macs whatever their clocks read: rank 0's dip or drift alone decides a second pass. +/// Both ranks follow the leader's selected repair reads and drift retries, regardless of their own clocks. pub fn schedule(windows: anytype, heads: anytype, agree: anytype, lead: bool, head: bool, reference: ?Timed) !Timed { for (0..warm) |_| _ = try windows.time(st.max_rows - 1); var t: Timed = .{ .window = undefined, .head = .{ 0, 0 } }; - for (&t.window, 0..) |*m, i| m.* = try cost_rule.fastest(windows, i); + try measureWindows(windows, &t.window, false, agree, lead); if (head) for (&t.head, 0..) |*h, i| { h.* = try cost_rule.fastest(heads, i); }; const drifted = if (reference) |r| cost_rule.drifted(&t.window, &r.window) else false; - if (try agree.decide(lead and (dipped(&t.window) or drifted))) { - try cost_rule.again(windows, &t.window); + if (try agree.decide(lead and drifted)) { + try measureWindows(windows, &t.window, true, agree, lead); if (head) for (&t.head, 0..) |*h, i| { h.* = @min(h.*, try cost_rule.fastest(heads, i)); }; @@ -67,9 +90,13 @@ pub fn schedule(windows: anytype, heads: anytype, agree: anytype, lead: bool, he return t; } -fn dipped(ms: []const f64) bool { - for (ms[1..], ms[0 .. ms.len - 1]) |m, before| if (m < before * (1 - cost_rule.dip)) return true; - return false; +fn measureWindows(windows: anytype, ms: []f64, keep: bool, agree: anytype, lead: bool) !void { + if (keep) try cost_rule.again(windows, ms) else try cost_rule.serialWindowsSynced(windows, ms, agree, lead); + var invalid = false; + for (ms) |m| if (!(m > 0) or !std.math.isFinite(m)) { + invalid = true; + }; + if (try agree.decide(lead and invalid)) return error.InvalidWindowCost; } /// The depth rule's table: window ms by width, and a head level's ms from the two chains. @@ -92,10 +119,12 @@ const Scratch = struct { sl: *Slots, io: std.Io, tokens: [prompt_len]u32 = undefined, + started: bool = false, fn start(s: *Scratch) !void { for (&s.tokens, 0..) |*t, i| t.* = @intCast(1000 + i * 7919 % 50000); try s.sl.begin(0, &s.tokens, true); + s.started = true; var at: u32 = 0; while (at < prompt_len) { const n = s.sl.chunkRows(at, prompt_len); @@ -133,6 +162,25 @@ const WindowTimer = struct { } }; +const WarmTimer = struct { + s: *Scratch, + wall: lanes.backend.WallClock, + pub fn start(t: *WarmTimer) void { + t.wall.clock().start(); + } + pub fn elapsedMs(t: *WarmTimer) f64 { + return t.wall.clock().elapsedMs(.cost); + } + pub fn prepare(t: *WarmTimer, _: anytype, _: []const u32) !void { + try t.s.start(); + } + pub fn time(t: *WarmTimer, i: usize) !f64 { + const ms = try (WindowTimer{ .s = t.s }).time(i); + try t.s.sl.flush(); + return ms; + } +}; + const HeadTimer = struct { s: *Scratch, pub fn time(t: HeadTimer, i: usize) !f64 { @@ -150,18 +198,26 @@ const HeadTimer = struct { const Script = struct { calls: *std.ArrayList(usize), dip: ?usize = null, + invalid: bool = false, pub fn time(s: Script, i: usize) !f64 { try s.calls.append(std.testing.allocator, i); + if (s.invalid) return 0; return 10 + @as(f64, @floatFromInt(i)) - @as(f64, if (s.dip == i) 3 else 0); } }; -const Fixed = struct { - answer: bool, - asked: *?bool, - pub fn decide(f: Fixed, mine: bool) !bool { - f.asked.* = mine; - return f.answer; +const Decisions = struct { + bits: std.ArrayList(bool) = .empty, + at: usize = 0, + lead: bool = true, + pub fn decide(d: *Decisions, mine: bool) !bool { + if (d.lead) { + try d.bits.append(std.testing.allocator, mine); + return mine; + } + const result = d.bits.items[d.at]; + d.at += 1; + return result; } }; @@ -169,17 +225,99 @@ test "both Macs make the same timing calls, and only rank 0's word starts a seco const gpa = std.testing.allocator; var runs: [2]std.ArrayList(usize) = .{ .empty, .empty }; defer for (&runs) |*r| r.deinit(gpa); - // rank 0 reads a dip at 3 rows; rank 1's clock reads nothing odd but follows rank 0's word + var decisions: Decisions = .{}; + defer decisions.bits.deinit(gpa); + const reference: Timed = .{ .window = @splat(100), .head = .{ 100, 100 } }; for ([_]bool{ true, false }, &runs) |lead, *calls| { - var asked: ?bool = null; + decisions.lead = lead; const w: Script = .{ .calls = calls, .dip = if (lead) 3 else null }; - const t = try schedule(w, w, Fixed{ .answer = true, .asked = &asked }, lead, true, null); - try std.testing.expectEqual(lead, asked.?); - try std.testing.expect(t.window[0] == 10 and t.head[1] > t.head[0]); + const timed = try schedule(w, w, &decisions, lead, true, if (lead) reference else null); + try std.testing.expect(timed.window[0] == 10 and timed.head[1] > timed.head[0]); } try std.testing.expectEqualSlices(usize, runs[0].items, runs[1].items); - // warm-up, 16 widths and 2 head chains of 1 + 7 runs each, then the same again for the second pass - try std.testing.expectEqual(@as(usize, warm + 2 * (st.max_rows + 2) * (1 + cost_rule.reps)), runs[0].items.len); + const full = warm + 2 * (st.max_rows + 2) * (1 + cost_rule.reps); + try std.testing.expectEqual(full + 4 * (1 + cost_rule.reps), runs[0].items.len); + try std.testing.expectEqual(decisions.bits.items.len, decisions.at); +} + +test "GLM cold timing: stateful windows match the serial oracle on both ranks, including drift retry" { + const Stateful = struct { + calls: *std.ArrayList(usize), + lead: bool, + head: bool = false, + + pub fn time(s: @This(), i: usize) !f64 { + const at = s.calls.items.len; + try s.calls.append(std.testing.allocator, i + if (s.head) st.max_rows else @as(usize, 0)); + const width: f64 = @floatFromInt(i); + return (if (s.lead) 10 + width else 600 - 32 * width) + @as(f64, @floatFromInt(at)); + } + }; + const gpa = std.testing.allocator; + for ([_]bool{ false, true }) |retry| for ([_]bool{ false, true }) |head| { + var runs: [2]std.ArrayList(usize) = .{ .empty, .empty }; + defer for (&runs) |*r| r.deinit(gpa); + var decisions: Decisions = .{}; + defer decisions.bits.deinit(gpa); + const reference: Timed = .{ .window = @splat(1), .head = .{ 1, 1 } }; + for ([_]bool{ true, false }, &runs) |lead, *calls| { + decisions.lead = lead; + const windows: Stateful = .{ .calls = calls, .lead = lead }; + const heads: Stateful = .{ .calls = calls, .lead = lead, .head = true }; + const timed = try schedule(windows, heads, &decisions, lead, head, if (lead and retry) reference else null); + if (lead) for (timed.window, 0..) |ms, i| { + const expected = 10 + @as(f64, @floatFromInt(i + warm + 8 * i + 1)); + try std.testing.expectEqual(expected, ms); + }; + } + try std.testing.expectEqualSlices(usize, runs[0].items, runs[1].items); + try std.testing.expectEqual(decisions.bits.items.len, decisions.at); + var at: usize = 0; + for (0..warm) |_| { + try std.testing.expectEqual(st.max_rows - 1, runs[0].items[at]); + at += 1; + } + for (0..@as(usize, if (retry) 2 else 1)) |_| { + for (0..st.max_rows) |i| for (0..8) |_| { + try std.testing.expectEqual(i, runs[0].items[at]); + at += 1; + }; + if (head) for (0..2) |i| for (0..8) |_| { + try std.testing.expectEqual(st.max_rows + i, runs[0].items[at]); + at += 1; + }; + } + try std.testing.expectEqual(at, runs[0].items.len); + }; +} + +fn invalidClocks(bad_leader: bool) !void { + const gpa = std.testing.allocator; + var runs: [2]std.ArrayList(usize) = .{ .empty, .empty }; + defer for (&runs) |*r| r.deinit(gpa); + var decisions: Decisions = .{}; + defer decisions.bits.deinit(gpa); + for ([_]bool{ true, false }, &runs) |lead, *calls| { + decisions.lead = lead; + const w: Script = .{ .calls = calls, .invalid = lead == bad_leader }; + if (bad_leader) { + try std.testing.expectError(error.InvalidWindowCost, schedule(w, w, &decisions, lead, false, null)); + } else { + const timed = try schedule(w, w, &decisions, lead, false, null); + if (lead) try std.testing.expectEqual(@as(f64, 10), timed.window[0]); + } + if (lead) try std.testing.expect(decisions.bits.items.len > 0); + } + try std.testing.expectEqualSlices(usize, runs[0].items, runs[1].items); + try std.testing.expectEqual(decisions.bits.items.len, decisions.at); +} + +test "paired timing: an invalid leader clock stops both ranks after the same measured sweep" { + try invalidClocks(true); +} + +test "paired timing: an invalid follower clock cannot stop a valid leader's schedule" { + try invalidClocks(false); } test "the table holds every width and a head level's ms from the two chains" { @@ -190,6 +328,74 @@ test "the table holds every width and a head level's ms from the two chains" { try std.testing.expectEqual(@as(u32, 16), c.window[15].width); try std.testing.expectEqual(@as(f64, 55), c.window[15].ms); try std.testing.expectEqual(@as(f64, 0.5), c.head_ms); - try std.testing.expect(dipped(&.{ 10, 13, 12.5, 16 })); - try std.testing.expect(!dipped(&.{ 10, 13, 12.7, 16 })); + try std.testing.expect(cost_rule.repairAt(&.{ 10, 13, 12.5, 16 }, 2)); + try std.testing.expect(!cost_rule.repairAt(&.{ 10, 13, 12.7, 16 }, 2)); +} + +test "paired warm timing: setup overrun, cooldown, then next rotating read" { + const Timer = struct { + script: Script, + setup_ms: f64, + elapsed: f64 = 0, + plans: usize = 0, + first: ?usize = null, + + pub fn prepare(t: *@This(), plan: cost_rule.warm_prices.Plan, _: []const u32) !void { + t.plans += 1; + t.first = plan.at[0]; + t.elapsed = t.setup_ms; + } + + pub fn elapsedMs(t: *@This()) f64 { + return t.elapsed; + } + + pub fn time(t: *@This(), i: usize) !f64 { + const ms = try t.script.time(i); + t.elapsed += ms; + return ms; + } + }; + const gpa = std.testing.allocator; + var runs: [2]std.ArrayList(usize) = .{ .empty, .empty }; + defer for (&runs) |*r| r.deinit(gpa); + var cursors: [2]u64 = @splat(0); + var values = [2][3]f64{ .{ 10, 11, 12 }, .{ 0, 0, 0 } }; + var decisions: Decisions = .{}; + defer decisions.bits.deinit(gpa); + const widths = [_]u32{ 1, 16, 17 }; + for (0..3) |turn| { + decisions.bits.clearRetainingCapacity(); + decisions.at = 0; + for ([_]bool{ true, false }, 0..) |lead, rank| { + decisions.lead = lead; + runs[rank].clearRetainingCapacity(); + var timer: Timer = .{ + .script = .{ .calls = &runs[rank] }, + .setup_ms = if (lead and turn == 0) 195 else 1, + }; + const stats = try cost_rule.warm_prices.prepared( + &timer, + &values[rank], + &widths, + &cursors[rank], + 0, + &decisions, + lead, + ); + try std.testing.expectEqual(@as(usize, if (turn == 1) 0 else 1), timer.plans); + const first: ?usize = switch (turn) { + 0 => 0, + 1 => null, + else => 1, + }; + try std.testing.expectEqual(first, timer.first); + try std.testing.expectEqual(@as(u32, if (turn == 2) 2 else 0), stats.reads); + if (lead and turn == 0) try std.testing.expectEqual(@as(f64, 195), stats.ms); + } + try std.testing.expectEqual(decisions.bits.items.len, decisions.at); + try std.testing.expectEqualSlices(usize, runs[0].items, runs[1].items); + if (turn == 2) try std.testing.expectEqualSlices(usize, &.{ 1, 2 }, runs[0].items); + } + try std.testing.expectEqual([2]u64{ 2, 0 }, cursors); } diff --git a/zig/src/families/h3/h3.zig b/zig/src/families/h3/h3.zig index 8e732f633f7..e9ca45262a6 100644 --- a/zig/src/families/h3/h3.zig +++ b/zig/src/families/h3/h3.zig @@ -521,6 +521,8 @@ pub const Model = struct { self.stamps.?.clock = mtl.counters.sampleClocks(self.device); } try self.next(&pass); + var queued: gpu_turn.Queue(mtl.CommandBuffer, 4) = .{}; + errdefer queued.drain() catch {}; const enc = &pass.enc; // a first frame's rows enter like video rows on every pass and are never stepped const media = self.text + self.condition; @@ -529,25 +531,20 @@ pub const Model = struct { self.rowsIn(enc.*, self.video_latents, self.w_video_in, self.b_video_in, self.video, self.video_in, media + self.audio); try self.lap(&pass, "rows in"); // Keep blocks queued to hide host wake-up latency without submitting the entire forward ahead of speech. - var queued: [3]mtl.CommandBuffer = undefined; - var n: usize = 0; const routed = step + self.routed_steps >= self.adaln.len / self.rows; for (0..self.blocks.len) |index| { try block.run(self, &pass, index, routed); const t = self.give_way orelse continue; pass.enc.end(); pass.cb.commit(); - if (n == queued.len) { - pass.gpu += try finish(queued[0]); - std.mem.copyForwards(mtl.CommandBuffer, queued[0 .. n - 1], queued[1..n]); - n -= 1; - } - queued[n] = pass.cb; - n += 1; + try queued.add(pass.cb, 3); self.paused += gpu_turn.yield(t.io, t.at); try self.next(&pass); } - for (queued[0..n]) |cb| pass.gpu += try finish(cb); + try queued.drain(); + pass.gpu += queued.gpu; + // speech that began while the last blocks drained goes before the final norm and output heads are committed + if (self.give_way) |t| self.paused += gpu_turn.yield(t.io, t.at); const last = self.blocks[self.blocks.len - 1].tables; // Only the stepped rows are ever read: prompt rows are re-copied into x each step and head_norm skips them. const skip = media * hidden * 2; @@ -571,7 +568,6 @@ pub const Model = struct { pass.enc.end(); pass.cb.commit(); pass.gpu += try finish(pass.cb); - if (self.give_way) |t| self.paused += gpu_turn.yield(t.io, t.at); if (video_velocity.len > 0) @memcpy(video_velocity, self.video_velocity.slice(f32, video_velocity.len)); if (audio_velocity.len > 0) @memcpy(audio_velocity, self.audio_velocity.slice(f32, audio_velocity.len)); const wall = mtl.clock.seconds() - started; diff --git a/zig/src/families/h3/prompt.zig b/zig/src/families/h3/prompt.zig index 6cafc9b4285..2812a0b1cbb 100644 --- a/zig/src/families/h3/prompt.zig +++ b/zig/src/families/h3/prompt.zig @@ -83,47 +83,31 @@ pub const Runner = struct { r.queue.deinit(); } - /// Command buffers committed in order, each a few layers' work; `finish` waits for the last and checks them all. + /// Command buffers committed in order, each a few layers' work; `finish` waits for them all and checks them. const Passes = struct { - list: [80]mtl.CommandBuffer = undefined, - n: usize = 0, + done: gpu_turn.Queue(mtl.CommandBuffer, 80) = .{}, + cb: mtl.CommandBuffer = undefined, give_way: ?gpu_turn.Turn, paused: f64 = 0, - /// Passes ahead of the host before the next waits for speech: enough to hide its wake-up. - const queued = 3; + /// Passes ahead of the host while it waits for speech: enough to hide its wake-up. + const queued = 2; - fn next(p: *Passes, q: mtl.Queue) !mtl.ComputeEncoder { - if (p.n == p.list.len) return error.H3TooManyPasses; - if (p.give_way) |t| { - if (p.n >= queued) try check(p.list[p.n - queued]); - p.paused += gpu_turn.yield(t.io, t.at); - } - p.list[p.n] = q.commandBuffer(); - p.n += 1; - return p.list[p.n - 1].compute(.serial); + fn next(p: *Passes, q: mtl.Queue) mtl.ComputeEncoder { + if (p.give_way) |t| p.paused += gpu_turn.yield(t.io, t.at); + p.cb = q.commandBuffer(); + return p.cb.compute(.serial); } - fn commit(p: *Passes, e: mtl.ComputeEncoder) void { + fn commit(p: *Passes, e: mtl.ComputeEncoder) !void { e.end(); - p.list[p.n - 1].commit(); + p.cb.commit(); + try p.done.add(p.cb, if (p.give_way == null) 80 else queued); } fn finish(p: *Passes) !f64 { - var gpu: f64 = 0; - for (p.list[0..p.n]) |cb| { - try check(cb); - gpu += cb.gpuSeconds(); - } - return gpu; - } - - fn check(cb: mtl.CommandBuffer) !void { - cb.wait(); - if (cb.failure()) |msg| { - std.log.err("h3 prompt: a pass failed on the GPU: {s}", .{msg}); - return error.GpuFailed; - } + try p.done.drain(); + return p.done.gpu; } }; @@ -158,7 +142,7 @@ pub const Runner = struct { defer pool.pop(); var passes: Passes = .{ .give_way = r.give_way }; for (w.layers, 0..) |l, li| { - const e = try passes.next(r.queue); + const e = passes.next(r.queue); const k = &r.k; k.norm(e, s.at(.x), l.norm1, s.at(.xn), T, H, g.eps, .qwen); k.gemm(e, s.at(.xn), l.q, null, s.at(.q), T, qh.row, H); @@ -175,7 +159,7 @@ pub const Runner = struct { k.gemm(e, s.at(.act), l.down, null, s.at(.y), T, H, g.ffn); k.add(e, s.at(.x), s.at(.y), T * H); if (n > 0 and li < 3) k.scatterAdd(e, s.at(.x), .{ .buffer = s.buf, .offset = s.at(.deep).offset + li * n * H * 2 }, s.at(.pads), n, H); - passes.commit(e); + try passes.commit(e); } r.gpu = try passes.finish(); r.paused = passes.paused; @@ -200,7 +184,7 @@ pub const Runner = struct { defer pool.pop(); var passes: Passes = .{ .give_way = r.give_way }; const k = &r.k; - var e = try passes.next(r.queue); + var e = passes.next(r.queue); k.gemm(e, s.at(.in), w.cond_w, w.cond_b, s.at(.x), T, H, g.text); // the fused rows hold each head's q, k and v together: 384 values a head, q at 0, k at 128, v at 256 const fused: Heads = .{ .count = g.heads, .row = 3 * inner, .head = 3 * D }; @@ -220,11 +204,11 @@ pub const Runner = struct { k.glu(e, s.at(.wide), value, s.at(.act), T, g.mlp, 2 * g.mlp, 2 * g.mlp, .h3); k.gemm(e, s.at(.act), b.fc2, null, s.at(.y), T, H, g.mlp); k.add(e, s.at(.x), s.at(.y), T * H); - passes.commit(e); - e = try passes.next(r.queue); + try passes.commit(e); + e = passes.next(r.queue); } k.norm(e, s.at(.x), w.final_norm, s.at(.out), T, H, g.final_eps, .h3); - passes.commit(e); + try passes.commit(e); r.gpu = try passes.finish(); r.paused = passes.paused; @memcpy(out, s.slice(u16, .out, T * H)); diff --git a/zig/src/families/hy4_flash/cuda_model.zig b/zig/src/families/hy4_flash/cuda_model.zig index a6f4c24f012..d84768916d1 100644 --- a/zig/src/families/hy4_flash/cuda_model.zig +++ b/zig/src/families/hy4_flash/cuda_model.zig @@ -236,6 +236,8 @@ pub const Model = struct { // The layer is on the device: its mapped shard pages (and page cache) would otherwise stay resident. ck.release(); } + // the checkpoint's last read: `ck` is this open's own โ€” a name never taken is a stray tensor + try @import("loader.zig").finishCuda(ck, cfg.value); std.debug.print("all layers: device {d:.2} GiB, MemAvailable {d:.2} GiB\n", .{ gib(self.own.bytes), gib(memAvailable()) }); self.weight_bytes = self.own.bytes; self.scratch = try self.allocScratch(); @@ -369,7 +371,10 @@ pub const Model = struct { const shard = try shardOf(a, io, dir, table_name); // The config's per-layer row count, so a wrong or repacked table fails here and not mid-forward. const rows_expected = try t.engramRows(@intCast(i + 1)); - eng = .{ .w = w, .table = try direct.openDirect(a, shard, table_name, map, hash, rows_expected) }; + var table = try direct.openDirect(a, shard, table_name, map, hash, rows_expected); + errdefer table.close(); + try ck.skip(table_name); + eng = .{ .w = w, .table = table }; } return .{ .engram = eng, .attention = att, .feed = feed }; } diff --git a/zig/src/families/hy4_flash/host_tests.zig b/zig/src/families/hy4_flash/host_tests.zig index 996eec1919c..e117a5990a1 100644 --- a/zig/src/families/hy4_flash/host_tests.zig +++ b/zig/src/families/hy4_flash/host_tests.zig @@ -2,6 +2,7 @@ const std = @import("std"); const core = @import("core"); const engram = @import("engram.zig"); const engram_rows = @import("engram_rows.zig"); +const loader = @import("loader.zig"); test { _ = @import("config.zig"); @@ -10,6 +11,7 @@ test { _ = @import("index_groups.zig"); _ = @import("rope.zig"); _ = @import("rank_weights.zig"); + _ = @import("cuda_model.zig"); _ = @import("index_recall.zig"); _ = @import("forward.zig"); _ = @import("exl3_weights.zig"); @@ -56,3 +58,112 @@ test "Engram gathers the selected affine rows in token and head order" { } try std.testing.expectError(error.BadEngramOutput, table.gather(a, &.{window0}, out[1..])); } + +const auxiliary_data = [2]u8{ 0, 0 }; +const auxiliary_entries = [_]core.checkpoint_fixture.Entry{ + .{ .name = "model.norm.weight", .dtype = "BF16", .shape = &.{1}, .bytes = &auxiliary_data }, + .{ .name = "model.layers.0.self_attn.compressed_indexer.token_key_projection.weight", .dtype = "U32", .shape = &.{1}, .bytes = &auxiliary_wide_data }, + .{ .name = "model.layers.0.self_attn.compressed_indexer.token_key_projection.scales", .dtype = "BF16", .shape = &.{1}, .bytes = &auxiliary_data }, + .{ .name = "model.layers.0.self_attn.compressed_indexer.token_key_projection.biases", .dtype = "BF16", .shape = &.{1}, .bytes = &auxiliary_data }, + .{ .name = "model.layers.0.self_attn.compressed_indexer.query_projection.weight", .dtype = "U32", .shape = &.{1}, .bytes = &auxiliary_wide_data }, + .{ .name = "model.layers.0.self_attn.compressed_indexer.query_projection.scales", .dtype = "BF16", .shape = &.{1}, .bytes = &auxiliary_data }, + .{ .name = "model.layers.0.self_attn.compressed_indexer.query_projection.biases", .dtype = "BF16", .shape = &.{1}, .bytes = &auxiliary_data }, + .{ .name = "model.layers.0.self_attn.compressed_indexer.head_weight_projection.weight", .dtype = "U32", .shape = &.{1}, .bytes = &auxiliary_wide_data }, + .{ .name = "model.layers.0.self_attn.compressed_indexer.head_weight_projection.scales", .dtype = "BF16", .shape = &.{1}, .bytes = &auxiliary_data }, + .{ .name = "model.layers.0.self_attn.compressed_indexer.head_weight_projection.biases", .dtype = "BF16", .shape = &.{1}, .bytes = &auxiliary_data }, + .{ .name = "model.layers.0.self_attn.compressed_indexer.key_value_projection.weight", .dtype = "F32", .shape = &.{1}, .bytes = &auxiliary_wide_data }, + .{ .name = "model.layers.0.self_attn.compressed_indexer.key_gate_projection.weight", .dtype = "F32", .shape = &.{1}, .bytes = &auxiliary_wide_data }, + .{ .name = "model.layers.0.self_attn.compressed_indexer.intra_group_ape", .dtype = "F32", .shape = &.{1}, .bytes = &auxiliary_wide_data }, + .{ .name = "model.layers.0.self_attn.compressed_indexer.key_norm.weight", .dtype = "F32", .shape = &.{1}, .bytes = &auxiliary_wide_data }, + .{ .name = "model.layers.0.self_attn.compressed_indexer.token_key_norm.weight", .dtype = "BF16", .shape = &.{1}, .bytes = &auxiliary_data }, + .{ .name = "model.dfly_layers.final_norm.weight", .dtype = "BF16", .shape = &.{1}, .bytes = &auxiliary_data }, + .{ .name = "model.dfly_layers.confidence_head.proj.weight", .dtype = "BF16", .shape = &.{1}, .bytes = &auxiliary_data }, + .{ .name = "model.dfly_layers.confidence_head.proj.bias", .dtype = "BF16", .shape = &.{1}, .bytes = &auxiliary_data }, + .{ .name = "model.dfly_layers.mtp_fusion.enorm.weight", .dtype = "BF16", .shape = &.{1}, .bytes = &auxiliary_data }, + .{ .name = "model.dfly_layers.mtp_fusion.hnorm.weight", .dtype = "BF16", .shape = &.{1}, .bytes = &auxiliary_data }, + .{ .name = "model.dfly_layers.mtp_fusion.gate", .dtype = "BF16", .shape = &.{1}, .bytes = &auxiliary_data }, + .{ .name = "model.dfly_layers.mtp_fusion.eh_proj.weight", .dtype = "BF16", .shape = &.{1}, .bytes = &auxiliary_data }, + .{ .name = "model.dfly_layers.hidden_correction.embed_norm.weight", .dtype = "BF16", .shape = &.{1}, .bytes = &auxiliary_data }, + .{ .name = "model.dfly_layers.hidden_correction.hidden_norm.weight", .dtype = "BF16", .shape = &.{1}, .bytes = &auxiliary_data }, + .{ .name = "model.dfly_layers.hidden_correction.gate_proj.weight", .dtype = "BF16", .shape = &.{1}, .bytes = &auxiliary_data }, + .{ .name = "model.dfly_layers.hidden_correction.up_proj.weight", .dtype = "BF16", .shape = &.{1}, .bytes = &auxiliary_data }, + .{ .name = "model.dfly_layers.hidden_correction.down_proj.weight", .dtype = "BF16", .shape = &.{1}, .bytes = &auxiliary_data }, + .{ .name = "model.dfly_layers.0.input_layernorm.weight", .dtype = "BF16", .shape = &.{1}, .bytes = &auxiliary_data }, + .{ .name = "model.dfly_layers.0.post_attention_layernorm.weight", .dtype = "BF16", .shape = &.{1}, .bytes = &auxiliary_data }, + .{ .name = "model.dfly_layers.0.self_attn.post_proj_norm.weight", .dtype = "BF16", .shape = &.{1}, .bytes = &auxiliary_data }, + .{ .name = "model.dfly_layers.0.self_attn.q_a_layernorm.weight", .dtype = "BF16", .shape = &.{1}, .bytes = &auxiliary_data }, + .{ .name = "model.dfly_layers.0.self_attn.kv_a_layernorm.weight", .dtype = "BF16", .shape = &.{1}, .bytes = &auxiliary_data }, + .{ .name = "model.dfly_layers.0.self_attn.q_a_proj.weight", .dtype = "BF16", .shape = &.{1}, .bytes = &auxiliary_data }, + .{ .name = "model.dfly_layers.0.self_attn.q_b_proj.weight", .dtype = "BF16", .shape = &.{1}, .bytes = &auxiliary_data }, + .{ .name = "model.dfly_layers.0.self_attn.kv_a_proj_with_mqa.weight", .dtype = "BF16", .shape = &.{1}, .bytes = &auxiliary_data }, + .{ .name = "model.dfly_layers.0.self_attn.kv_b_proj.weight", .dtype = "BF16", .shape = &.{1}, .bytes = &auxiliary_data }, + .{ .name = "model.dfly_layers.0.self_attn.linear_gate.weight", .dtype = "BF16", .shape = &.{1}, .bytes = &auxiliary_data }, + .{ .name = "model.dfly_layers.0.self_attn.o_proj.weight", .dtype = "BF16", .shape = &.{1}, .bytes = &auxiliary_data }, + .{ .name = "model.dfly_layers.0.self_attn.learnable_sink_param", .dtype = "BF16", .shape = &.{1}, .bytes = &auxiliary_data }, + .{ .name = "model.dfly_layers.0.mlp.gate_proj.weight", .dtype = "BF16", .shape = &.{1}, .bytes = &auxiliary_data }, + .{ .name = "model.dfly_layers.0.mlp.up_proj.weight", .dtype = "BF16", .shape = &.{1}, .bytes = &auxiliary_data }, + .{ .name = "model.dfly_layers.0.mlp.down_proj.weight", .dtype = "BF16", .shape = &.{1}, .bytes = &auxiliary_data }, + .{ .name = "vit.embeddings.patch_embedding.weight", .dtype = "BF16", .shape = &.{1}, .bytes = &auxiliary_data }, +}; + +const auxiliary_wide_data = [4]u8{ 0, 0, 0, 0 }; + +test "the CUDA loader owns complete auxiliary tensors but refuses a stray" { + const fixture = core.checkpoint_fixture; + const a = std.testing.allocator; + const io = std.testing.io; + const parsed = try @import("config.zig").parse(a, @embedFile("config_fixture.json")); + defer parsed.deinit(); + var model = parsed.value; + model.text_config.num_hidden_layers = 1; + model.text_config.layer_types = &.{.deepseek_sparse_attention}; + model.text_config.mlp_layer_types = &.{.dense}; + model.text_config.engram_layer_ids = &.{}; + model.dfly_num_hidden_layers = 1; + model.dfly_target_index_layer = &.{0}; + model.dfly_target_kv_layers = &.{0}; + for ([_]bool{ false, true }) |with_stray| { + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var entries: std.ArrayList(fixture.Entry) = .empty; + defer entries.deinit(a); + try entries.appendSlice(a, &auxiliary_entries); + if (with_stray) try entries.append(a, .{ .name = "model.dfly_layers.stray.weight", .dtype = "BF16", .shape = &.{1}, .bytes = &auxiliary_data }); + try fixture.write(a, io, tmp.dir, "model.safetensors", entries.items); + const dir = try std.fmt.allocPrint(a, ".zig-cache/tmp/{s}", .{tmp.sub_path}); + defer a.free(dir); + var ck = try core.Checkpoint.openModel(a, io, dir); + defer ck.close(); + _ = try ck.expect("model.norm.weight", .bf16, &.{1}); + if (with_stray) { + try std.testing.expectError(error.UnusedHy4Tensors, loader.finishCuda(&ck, model)); + } else { + try loader.finishCuda(&ck, model); + } + } +} + +test "a direct Engram table loads, while a stray hy4 tensor refuses at the checkpoint's last read site" { + const fixture = @import("core").checkpoint_fixture; + const a = std.testing.allocator; + const io = std.testing.io; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const data: [4]u16 = @splat(0x3f80); + const table_name = "model.layers.0.engram_layer.multi_head_embedding.embedding.weight"; + const entries = [_]fixture.Entry{ + .{ .name = "model.norm.weight", .dtype = "BF16", .shape = &.{4}, .bytes = std.mem.sliceAsBytes(&data) }, + .{ .name = table_name, .dtype = "BF16", .shape = &.{ 1, 4 }, .bytes = std.mem.sliceAsBytes(&data) }, + .{ .name = "model.stray.weight", .dtype = "BF16", .shape = &.{4}, .bytes = std.mem.sliceAsBytes(&data) }, + }; + try fixture.write(a, io, tmp.dir, "model.safetensors", &entries); + const dir = try std.fmt.allocPrint(a, ".zig-cache/tmp/{s}", .{tmp.sub_path}); + defer a.free(dir); + var ck = try core.Checkpoint.openModel(a, io, dir); + defer ck.close(); + _ = try ck.expect("model.norm.weight", .bf16, &.{4}); + try ck.skip(table_name); // openDirect owns the read; only its exact table name is outside the used-set audit. + try std.testing.expectError(error.UnusedHy4Tensors, @import("loader.zig").refuseLeftovers(&ck, error.UnusedHy4Tensors)); + _ = try ck.expect("model.stray.weight", .bf16, &.{4}); + try @import("loader.zig").refuseLeftovers(&ck, error.UnusedHy4Tensors); +} diff --git a/zig/src/families/hy4_flash/loader.zig b/zig/src/families/hy4_flash/loader.zig index 4e1ee7964b1..77ac35f61b6 100644 --- a/zig/src/families/hy4_flash/loader.zig +++ b/zig/src/families/hy4_flash/loader.zig @@ -81,3 +81,32 @@ const Validation = struct { _ = try self.checkpoint.expect(name, dtype, shape); } }; + +const CudaOwnership = struct { + checkpoint: *core.Checkpoint, + + pub fn expect(self: *CudaOwnership, name: []const u8, format: weights.DType, shape: []const usize) !void { + _ = format; + _ = shape; + _ = try self.checkpoint.stored(name); // Exact-name ownership when present; no new admission requirement. + } +}; + +/// Finish the CUDA target's checkpoint after its layers have been read. +pub fn finishCuda(ck: *core.Checkpoint, model: config.Model) !void { + var ownership: CudaOwnership = .{ .checkpoint = ck }; + // Only the names matter here; four bits keeps the shared enumerator's logical dimensions valid. + try weights.checkCudaAuxiliary(&ownership, model, 4); + try refuseLeftovers(ck, error.UnusedHy4Tensors); +} + +/// `ck` names `get` never took, refused with up to five named. +pub fn refuseLeftovers(ck: *const core.Checkpoint, comptime err: anyerror) !void { + var n: usize = 0; + for (ck.files.items) |*f| for (f.names.keys()) |k| { + if (ck.used.contains(k)) continue; + if (n < 5 and !@import("builtin").is_test) std.log.err("unused checkpoint tensor {s}", .{k}); + n += 1; + }; + if (n != 0) return err; +} diff --git a/zig/src/families/hy4_flash/weights.zig b/zig/src/families/hy4_flash/weights.zig index bd54995199c..dcd2da4de58 100644 --- a/zig/src/families/hy4_flash/weights.zig +++ b/zig/src/families/hy4_flash/weights.zig @@ -41,6 +41,20 @@ fn checkLayerNorms(weights: anytype, layer: []const u8, t: config.Text) !void { try expect(weights, layer, "self_attn.kv_a_layernorm", ".weight", .bf16, &.{t.kv_lora_rank}); } +fn checkCompressedIndexer(weights: anytype, layer: []const u8, t: config.Text, affine: Affine) !void { + const c = t.compressed_indexer_head_dim; + const num_heads = t.compressed_indexer_num_attention_heads; + const prefix = "self_attn.compressed_indexer."; + try affine.check(weights, layer, prefix ++ "token_key_projection", &.{ c, t.hidden_size }); + try affine.check(weights, layer, prefix ++ "query_projection", &.{ @as(usize, num_heads) * c, t.q_lora_rank }); + try affine.check(weights, layer, prefix ++ "head_weight_projection", &.{ num_heads, t.hidden_size }); + try expect(weights, layer, prefix, "key_value_projection.weight", .f32, &.{ c, c }); + try expect(weights, layer, prefix, "key_gate_projection.weight", .f32, &.{ c, c }); + try expect(weights, layer, prefix, "intra_group_ape", .f32, &.{ t.compressed_indexer_compress_ratio, c }); + try expect(weights, layer, prefix, "key_norm.weight", .f32, &.{c}); + try expect(weights, layer, prefix, "token_key_norm.weight", .bf16, &.{c}); +} + fn affineMlp(weights: anytype, layer: []const u8, comptime mlp: []const u8, affine: Affine, h: usize, inner: usize) !void { try affine.check(weights, layer, mlp ++ "gate_proj", &.{ inner, h }); try affine.check(weights, layer, mlp ++ "up_proj", &.{ inner, h }); @@ -107,17 +121,7 @@ pub fn check(weights: anytype, model: config.Model, bits: u8) !void { try expect(weights, layer, hc, "hc_scale", .f32, &.{2}); } if (t.layer_types[index] == .deepseek_sparse_attention) { - const c = t.compressed_indexer_head_dim; - const num_heads = t.compressed_indexer_num_attention_heads; - const prefix = "self_attn.compressed_indexer."; - try affine.check(weights, layer, prefix ++ "token_key_projection", &.{ c, h }); - try affine.check(weights, layer, prefix ++ "query_projection", &.{ @as(usize, num_heads) * c, t.q_lora_rank }); - try affine.check(weights, layer, prefix ++ "head_weight_projection", &.{ num_heads, h }); - try expect(weights, layer, prefix, "key_value_projection.weight", .f32, &.{ c, c }); - try expect(weights, layer, prefix, "key_gate_projection.weight", .f32, &.{ c, c }); - try expect(weights, layer, prefix, "intra_group_ape", .f32, &.{ t.compressed_indexer_compress_ratio, c }); - try expect(weights, layer, prefix, "key_norm.weight", .f32, &.{c}); - try expect(weights, layer, prefix, "token_key_norm.weight", .bf16, &.{c}); + try checkCompressedIndexer(weights, layer, t, affine); } if (t.mlp_layer_types[index] == .sparse) { const expert = t.n_routed_experts; @@ -144,6 +148,20 @@ pub fn check(weights: anytype, model: config.Model, bits: u8) !void { try checkDraft(weights, model); } +/// Names the CUDA target deliberately leaves to the indexer, vision and DFly2 consumers. +pub fn checkCudaAuxiliary(weights: anytype, model: config.Model, bits: u8) !void { + const t = model.text_config; + const affine: Affine = .{ .bits = bits, .group_size = 64 }; + for (0..t.num_hidden_layers) |index| { + if (t.layer_types[index] != .deepseek_sparse_attention) continue; + var prefix_buffer: [56]u8 = undefined; + const layer = try std.fmt.bufPrint(&prefix_buffer, "model.layers.{d}.", .{index}); + try checkCompressedIndexer(weights, layer, t, affine); + } + try expect(weights, "vit.embeddings.", "patch_embedding.weight", "", .bf16, &.{ model.vision_config.hidden_size, 3, model.vision_config.patch_size, model.vision_config.patch_size }); + try checkDraft(weights, model); +} + fn checkDraft(weights: anytype, model: config.Model) !void { const t = model.text_config; const h = t.hidden_size; diff --git a/zig/src/families/idol/cuda.zig b/zig/src/families/idol/cuda.zig index 89bcad40c4f..423d0e88f19 100644 --- a/zig/src/families/idol/cuda.zig +++ b/zig/src/families/idol/cuda.zig @@ -31,5 +31,7 @@ test { _ = decode_reference; _ = config; _ = host; + _ = @import("octree.zig"); + _ = @import("decode_trace.zig"); _ = reference; } diff --git a/zig/src/families/idol/decode.zig b/zig/src/families/idol/decode.zig index 20a1eb7ea3c..aae3c659661 100644 --- a/zig/src/families/idol/decode.zig +++ b/zig/src/families/idol/decode.zig @@ -2,25 +2,12 @@ const std = @import("std"); const dc = @import("decoder_config.zig"); const octree = @import("octree.zig"); +const trace_state = @import("decode_trace.zig"); const gs = @import("gaussian.zig"); pub const Timing = struct { octree: f64 = 0, octree_gpu: f64 = 0, gaussian: f64 = 0, gaussian_gpu: f64 = 0, activation: f64 = 0 }; -/// Each level's parents and their counts, kept when a caller asks (for comparing a run's topology). -pub const Trace = struct { - parents: [dc.max_level][]const [3]u32 = @splat(&.{}), - counts: [dc.max_level][]const u32 = @splat(&.{}), - probs: [dc.max_level][]const f32 = @splat(&.{}), - - pub fn deinit(t: *Trace, gpa: std.mem.Allocator) void { - for (t.parents, t.counts, t.probs) |p, c, q| { - gpa.free(p); - gpa.free(c); - gpa.free(q); - } - t.* = .{}; - } -}; +pub const Trace = trace_state.Trace; pub const Result = struct { anchors: []f32, @@ -42,7 +29,7 @@ fn clock(t: anytype) f64 { /// The anchors for `points` points: each level's probabilities on the GPU, its split on the host. pub fn anchors(gpa: std.mem.Allocator, t: anytype, points: usize, draws: *octree.Draws, trace: ?*Trace, time: *Timing) ![]f32 { - var level: octree.Level = .{ .coords = try gpa.dupe([3]u32, &.{.{ 0, 0, 0 }}), .counts = try gpa.dupe(u32, &.{@intCast(points)}) }; + var level = try octree.root(gpa, points); defer { gpa.free(level.coords); gpa.free(level.counts); @@ -60,11 +47,13 @@ pub fn anchors(gpa: std.mem.Allocator, t: anytype, points: usize, draws: *octree const started = clock(t); octree.softmax(probs); const next = try octree.descend(gpa, level, probs, @intCast(l), draws, null); + errdefer { + gpa.free(next.coords); + gpa.free(next.counts); + } time.octree += clock(t) - started; if (trace) |tr| { - tr.parents[l - 1] = try gpa.dupe([3]u32, level.coords); - tr.counts[l - 1] = try gpa.dupe(u32, level.counts); - tr.probs[l - 1] = try gpa.dupe(f32, probs); + try trace_state.capture(tr, gpa, l - 1, level, probs); } gpa.free(level.coords); gpa.free(level.counts); diff --git a/zig/src/families/idol/decode_trace.zig b/zig/src/families/idol/decode_trace.zig new file mode 100644 index 00000000000..e6543053ed4 --- /dev/null +++ b/zig/src/families/idol/decode_trace.zig @@ -0,0 +1,46 @@ +//! Optional per-level decode topology, independent of the device decoder. +const std = @import("std"); +const dc = @import("decoder_config.zig"); +const octree = @import("octree.zig"); + +/// Each level's parents and their counts, kept when a caller asks (for comparing a run's topology). +pub const Trace = struct { + parents: [dc.max_level][]const [3]u32 = @splat(&.{}), + counts: [dc.max_level][]const u32 = @splat(&.{}), + probs: [dc.max_level][]const f32 = @splat(&.{}), + + pub fn deinit(t: *Trace, gpa: std.mem.Allocator) void { + for (t.parents, t.counts, t.probs) |p, c, q| { + gpa.free(p); + gpa.free(c); + gpa.free(q); + } + t.* = .{}; + } +}; + +pub fn capture(t: *Trace, gpa: std.mem.Allocator, index: usize, level: octree.Level, probs: []const f32) !void { + const parents = try gpa.dupe([3]u32, level.coords); + errdefer gpa.free(parents); + const counts = try gpa.dupe(u32, level.counts); + errdefer gpa.free(counts); + const probs_copy = try gpa.dupe(f32, probs); + t.parents[index] = parents; + t.counts[index] = counts; + t.probs[index] = probs_copy; +} + +test "trace capture leaves the failed level empty and balances allocations" { + const level: octree.Level = .{ .coords = &.{.{ 0, 0, 0 }}, .counts = &.{1} }; + const probs = [_]f32{1}; + for (0..3) |fail_at| { + var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{ .fail_index = fail_at }); + var trace: Trace = .{}; + defer trace.deinit(std.testing.allocator); + try std.testing.expectError(error.OutOfMemory, capture(&trace, failing.allocator(), 0, level, &probs)); + try std.testing.expectEqual(@as(usize, 0), trace.parents[0].len); + try std.testing.expectEqual(@as(usize, 0), trace.counts[0].len); + try std.testing.expectEqual(@as(usize, 0), trace.probs[0].len); + try std.testing.expectEqual(failing.allocated_bytes, failing.freed_bytes); + } +} diff --git a/zig/src/families/idol/idol.zig b/zig/src/families/idol/idol.zig index 685a51a9690..3887c3fc70c 100644 --- a/zig/src/families/idol/idol.zig +++ b/zig/src/families/idol/idol.zig @@ -19,6 +19,10 @@ pub const vae_kernels = @import("vae_kernels.zig"); pub const vae_weights = @import("vae_weights.zig"); /// Its DINOv3 ViT-H+/16 image encoder: an image to feature1. pub const dino = @import("dino.zig"); +/// The picture tf-idol-generate reads, in both encoders' layouts. +pub const picture = @import("picture.zig"); +/// torch's CPU generator, for the starting noise. +pub const torch_rng = @import("torch_rng.zig"); pub const Model = model.Model; pub const Condition = model.Condition; pub const Timing = model.Timing; @@ -42,4 +46,6 @@ test { _ = vae_kernels; _ = vae_weights; _ = dino; + _ = picture; + _ = torch_rng; } diff --git a/zig/src/families/idol/octree.zig b/zig/src/families/idol/octree.zig index f473137a89d..b0146218948 100644 --- a/zig/src/families/idol/octree.zig +++ b/zig/src/families/idol/octree.zig @@ -161,6 +161,12 @@ pub const Level = struct { counts: []const u32, }; +pub fn root(gpa: std.mem.Allocator, points: usize) !Level { + const coords = try gpa.dupe([3]u32, &.{.{ 0, 0, 0 }}); + errdefer gpa.free(coords); + return .{ .coords = coords, .counts = try gpa.dupe(u32, &.{@intCast(points)}) }; +} + /// The 8 children of every parent, split by probs and draws, kept where they got points (parent-major, i + 2j + 4k). pub fn descend(gpa: std.mem.Allocator, parents: Level, probs: []const f32, level: u5, draws: *Draws, splits: ?[]u32) !Level { std.debug.assert(probs.len == parents.coords.len * P); @@ -180,7 +186,10 @@ pub fn descend(gpa: std.mem.Allocator, parents: Level, probs: []const f32, level try counts.append(gpa, m); } } - return .{ .coords = try coords.toOwnedSlice(gpa), .counts = try counts.toOwnedSlice(gpa) }; + const owned_coords = try coords.toOwnedSlice(gpa); + errdefer gpa.free(owned_coords); + const owned_counts = try counts.toOwnedSlice(gpa); + return .{ .coords = owned_coords, .counts = owned_counts }; } /// The anchors: each leaf repeated by its count, (coords + jitter) / 2^level, fp32 [points, 3]. @@ -254,3 +263,19 @@ test "descend packs children parent-major in i + 2j + 4k order; anchors land ins try std.testing.expect(pts[p * 3 + ax] >= c / 4 and pts[p * 3 + ax] < (c + 1) / 4); }; } + +test "descend frees finalized coordinates when count finalization fails" { + const parents: Level = .{ .coords = &.{.{ 0, 0, 0 }}, .counts = &.{1} }; + var probs: [P]f32 = @splat(0); + probs[0] = 1; + var d: Draws = .{ .native = std.Random.DefaultPrng.init(1) }; + var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{ .fail_index = 3, .resize_fail_index = 0 }); + try std.testing.expectError(error.OutOfMemory, descend(failing.allocator(), parents, &probs, 2, &d, null)); + try std.testing.expectEqual(failing.allocated_bytes, failing.freed_bytes); +} + +test "root releases coordinates when counts allocation fails" { + var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{ .fail_index = 1 }); + try std.testing.expectError(error.OutOfMemory, root(failing.allocator(), 1)); + try std.testing.expectEqual(failing.allocated_bytes, failing.freed_bytes); +} diff --git a/zig/src/families/idol/picture.zig b/zig/src/families/idol/picture.zig new file mode 100644 index 00000000000..9144956c4ab --- /dev/null +++ b/zig/src/families/idol/picture.zig @@ -0,0 +1,83 @@ +//! The picture tf-idol-generate encodes: float32 `pixels` [3, 1024, 1024] (DINOv3's CHW) or `image` [1024, 1024, 3]. +const std = @import("std"); +const safetensors = @import("../../core/safetensors.zig"); + +/// The picture's side, the 1,024 x 1,024 IdolPipeline.preprocess returns. +pub const side = 1024; +pub const chw = [_]usize{ 3, side, side }; +pub const hwc = [_]usize{ side, side, 3 }; + +pub const Error = error{ BadPixels, BadImage, MissingPicture, OutOfMemory }; + +/// The picture as [0] CHW and [1] HWC; each name must hold exactly its own layout (an HWC `pixels` is refused). +pub fn layouts(a: std.mem.Allocator, pixels: ?safetensors.Tensor, image: ?safetensors.Tensor) Error![2][]f32 { + const n = 3 * side * side; + if (pixels) |t| if (!t.is(.f32, &chw)) return error.BadPixels; + if (pixels == null) if (image) |t| if (!t.is(.f32, &hwc)) return error.BadImage; + const given = pixels orelse image orelse return error.MissingPicture; + const planar = try a.alloc(f32, n); + errdefer a.free(planar); + const packed_ = try a.alloc(f32, n); + errdefer a.free(packed_); + const src = try a.alloc(f32, n); + defer a.free(src); + @memcpy(std.mem.sliceAsBytes(src), given.bytes); + if (pixels != null) { + @memcpy(planar, src); + for (0..side * side) |i| for (0..3) |c| { + packed_[i * 3 + c] = src[c * side * side + i]; + }; + } else { + @memcpy(packed_, src); + for (0..side * side) |i| for (0..3) |c| { + planar[c * side * side + i] = src[i * 3 + c]; + }; + } + return .{ planar, packed_ }; +} + +/// What `layouts` refused, for the user. +pub fn explain(e: Error) []const u8 { + return switch (e) { + error.BadPixels => "`pixels` must be float32 [3, 1024, 1024] (channels first)", + error.BadImage => "`image` must be float32 [1024, 1024, 3] (channels last)", + error.MissingPicture => "holds neither `pixels` [3, 1024, 1024] nor `image` [1024, 1024, 3]", + error.OutOfMemory => "out of memory", + }; +} + +fn tensor(bytes: []const u8, dtype: safetensors.DType, shape: []const usize) safetensors.Tensor { + var t: safetensors.Tensor = .{ .dtype = dtype, .rank = @intCast(shape.len), .shape = @splat(0), .bytes = bytes }; + @memcpy(t.shape[0..shape.len], shape); + return t; +} + +test "a picture is read in its own layout, and the other layout's shape is refused under either name" { + const a = std.testing.allocator; + const values = try a.alloc(f32, 3 * side * side); + defer a.free(values); + for (values, 0..) |*v, i| v.* = @floatFromInt(i % 4093); + const bytes = std.mem.sliceAsBytes(values); + + // pixels as CHW: [0] is the tensor itself, and [1] is its transpose + const ok = try layouts(a, tensor(bytes, .f32, &chw), null); + defer for (ok) |x| a.free(x); + try std.testing.expectEqualSlices(f32, values, ok[0]); + const at = 5 * side + 7; + for (0..3) |c| try std.testing.expectEqual(values[c * side * side + at], ok[1][at * 3 + c]); + + // the same values as image (HWC) give the same pair back the other way + const back = try layouts(a, null, tensor(std.mem.sliceAsBytes(ok[1]), .f32, &hwc)); + defer for (back) |x| a.free(x); + try std.testing.expectEqualSlices(f32, ok[0], back[0]); + try std.testing.expectEqualSlices(f32, ok[1], back[1]); + + // 3,145,728 values in the wrong layout, or the wrong dtype, are refused rather than read + try std.testing.expectError(error.BadPixels, layouts(a, tensor(bytes, .f32, &hwc), null)); + try std.testing.expectError(error.BadPixels, layouts(a, tensor(bytes, .f32, &.{3 * side * side}), null)); + try std.testing.expectError(error.BadPixels, layouts(a, tensor(bytes[0 .. bytes.len / 2], .bf16, &chw), null)); + try std.testing.expectError(error.BadImage, layouts(a, null, tensor(bytes, .f32, &chw))); + // a malformed pixels is not passed over for a well-formed image + try std.testing.expectError(error.BadPixels, layouts(a, tensor(bytes, .f32, &hwc), tensor(bytes, .f32, &hwc))); + try std.testing.expectError(error.MissingPicture, layouts(a, null, null)); +} diff --git a/zig/src/families/idol/torch_rng.zig b/zig/src/families/idol/torch_rng.zig new file mode 100644 index 00000000000..b89acd66ab2 --- /dev/null +++ b/zig/src/families/idol/torch_rng.zig @@ -0,0 +1,114 @@ +//! torch's CPU generator and its float32 randn, so the denoiser's starting noise is torch.Generator("cpu")'s. +const std = @import("std"); + +/// torch's CPU generator: mt19937 seeded as CPUGeneratorImpl seeds it. +pub const TorchCpu = struct { + s: [624]u32, + i: usize = 624, + /// normal_distribution's cached second sample + spare: ?f64 = null, + + pub fn init(seed: u64) TorchCpu { + var g: TorchCpu = .{ .s = undefined }; + g.s[0] = @truncate(seed); + for (1..624) |j| g.s[j] = 1812433253 *% (g.s[j - 1] ^ (g.s[j - 1] >> 30)) +% @as(u32, @intCast(j)); + return g; + } + + fn next(g: *TorchCpu) u32 { + if (g.i >= 624) { + for (0..624) |k| { + const y = (g.s[k] & 0x80000000) | (g.s[(k + 1) % 624] & 0x7fffffff); + g.s[k] = g.s[(k + 397) % 624] ^ (y >> 1) ^ (if (y & 1 != 0) @as(u32, 0x9908b0df) else 0); + } + g.i = 0; + } + var y = g.s[g.i]; + g.i += 1; + y ^= y >> 11; + y ^= (y << 7) & 0x9d2c5680; + y ^= (y << 15) & 0xefc60000; + return y ^ (y >> 18); + } + + fn uniform(g: *TorchCpu) f32 { + return @as(f32, @floatFromInt(g.next() & 0xffffff)) * 0x1p-24; + } + + /// normal_fill_16: Box-Muller on 8 pairs in place; theta is rounded to float as torch's scalar_t is. + fn fill16(d: *[16]f32) void { + for (0..8) |j| { + const r = @sqrt(-2 * logf(1 - d[j])); + const theta: f32 = @floatCast(2.0 * std.math.pi * @as(f64, d[j + 8])); + d[j] = r * @as(f32, @floatCast(@cos(@as(f64, theta)))); + d[j + 8] = r * @as(f32, @floatCast(@sin(@as(f64, theta)))); + } + } + + /// torch.randn(out.len, generator=g) for float32: normal_fill from 16 values on, else normal_distribution. + pub fn randn(g: *TorchCpu, out: []f32) void { + if (out.len >= 16) { + for (out) |*v| v.* = g.uniform(); + var i: usize = 0; + while (i + 16 <= out.len) : (i += 16) fill16(out[i..][0..16]); + if (out.len % 16 != 0) { + const tail = out[out.len - 16 ..][0..16]; + for (tail) |*v| v.* = g.uniform(); + fill16(tail); + } + return; + } + for (out) |*v| v.* = @floatCast(g.normal()); + } + + fn normal(g: *TorchCpu) f64 { + if (g.spare) |s| { + g.spare = null; + return s; + } + const u_1 = g.uniform53(); + const u_2 = g.uniform53(); + const r = @sqrt(-2 * std.math.log1p(-u_2)); + const theta = 2 * std.math.pi * u_1; + g.spare = r * @sin(theta); + return r * @cos(theta); + } + + fn uniform53(g: *TorchCpu) f64 { + const hi: u64 = g.next(); + const lo: u64 = g.next(); + return @as(f64, @floatFromInt(((hi << 32) | lo) & ((1 << 53) - 1))) * 0x1p-53; + } +}; + +extern "c" fn logf(x: f32) f32; + +fn bits(x: f32) u32 { + return @bitCast(x); +} + +/// Bits from torch 2.5.1+cpu, x86-64 Linux, ATEN_CPU_CAPABILITY=default (the scalar path the Mac runs). +const produced = "g = torch.Generator('cpu').manual_seed(42); torch.randn([8192, 16], generator=g), then [5]"; + +test "seed 42's [8192, 16] then [5] draws match torch's" { + _ = produced; + const a = std.testing.allocator; + const latent = try a.alloc(f32, 8192 * 16); + defer a.free(latent); + var g = TorchCpu.init(42); + g.randn(latent); + var camera: [5]f32 = undefined; + g.randn(&camera); + // the camera (normal_distribution, no float libm): bit-equal, on AVX2 torch too + const want = [5]u32{ 0x3fb5a113, 0xbf66bf0d, 0xbf991081, 0x3f1039dc, 0xbf1e8dff }; + for (camera, want) |x, w| try std.testing.expectEqual(w, bits(x)); + // the latent within 3 ulps: torch's float logf, cosf and sinf are libm's (5,854 of 131,072 differ on glibc) + const ends = [8]u32{ 0x3ff6a527, 0x3fbe5f54, 0x3f669567, 0xc006c0dd, 0xbf829062, 0x3e5e3715, 0x3f1d4a81, 0xbf31a466 }; + for (ends, 0..) |w, k| { + const x = latent[if (k < 4) k else latent.len - 8 + k]; + try std.testing.expect(@abs(@as(i64, bits(x)) - @as(i64, w)) <= 3); + } + var sum: f64 = 0; + for (latent) |x| sum += x; + try std.testing.expectApproxEqAbs(22.993049482419792, sum, 1e-4); +} diff --git a/zig/src/families/inkling2/config.zig b/zig/src/families/inkling2/config.zig index b4143603140..9d30527e4d8 100644 --- a/zig/src/families/inkling2/config.zig +++ b/zig/src/families/inkling2/config.zig @@ -1,9 +1,12 @@ -//! Inkling 2 Small's shape from config.json (inkling2), refusing every layout the engine does not run. +//! Inkling 2 Small and Mini shapes from config.json, refusing every layout the engine does not run. const std = @import("std"); /// The most backbone layers the plan tables hold (Inkling 2 Small has 48). pub const max_layers = 128; +/// The most scheduled layer visits the visit-plan table holds. +pub const max_visits = max_layers * 8; + /// Every sixth layer attends over the whole context; the reference derives its layer types the same way. pub const global_every = 6; @@ -37,6 +40,14 @@ pub const Why = struct { /// One attention geometry: sliding layers read the `swa_*` keys, global layers the plain ones. pub const Heads = struct { q: u32, kv: u32, dim: u32 }; +/// The fixed loop schedule: all layers once, then only the core on each later pass. +pub const Loop = struct { + core_start: u32, // inclusive physical layer id + core_end: u32, // exclusive physical layer id + passes: u32, + gate_rank: u32, +}; + pub const Text = struct { hidden: u32, layers: u32, @@ -61,6 +72,13 @@ pub const Text = struct { up_cap: f32, logit_cap: f32, max_context: u32, + loop: ?Loop, + + /// The number of scheduled layer visits; a drafter target equal to this is the final norm. + pub fn visitCount(c: *const Text) u32 { + const l = c.loop orelse return c.layers; + return c.layers + (l.passes - 1) * (l.core_end - l.core_start); + } pub fn heads(c: *const Text, i: u32) Heads { return if (isGlobal(i)) c.global else c.local; @@ -72,7 +90,7 @@ pub const Text = struct { } }; -/// The draft head's shape (mtp_config); the target taps are indices into the backbone, `layers` meaning the final norm. +/// The draft head's shape (mtp_config); target taps are visit ids, with `visitCount` meaning the final norm. pub const Mtp = struct { layers: u32, q_heads: u32, @@ -133,6 +151,15 @@ fn int(o: std.json.ObjectMap, key: []const u8, why: *Why) !u32 { return @intCast(v.integer); } +fn index(o: std.json.ObjectMap, key: []const u8, why: *Why) !u32 { + const v = try get(o, key, why); + if (v != .integer or v.integer < 0 or v.integer > std.math.maxInt(u32)) { + why.set("config.json's {s} is not a non-negative whole number", .{key}); + return error.BadConfig; + } + return @intCast(v.integer); +} + fn float(o: std.json.ObjectMap, key: []const u8, why: *Why) !f32 { const v = try get(o, key, why); const x: f64 = switch (v) { @@ -192,8 +219,33 @@ fn layerTypes(o: std.json.ObjectMap, layers: u32, why: *Why) !void { } } +fn parseLoop(o: std.json.ObjectMap, layers: u32, block: u32, why: *Why) !Loop { + const l: Loop = .{ + .core_start = try index(o, "core_start", why), + .core_end = try int(o, "core_end", why), + .passes = try int(o, "num_passes", why), + .gate_rank = try int(o, "gate_rank", why), + }; + try fixed(o, "is_varloop", false, why); + if (l.core_start == 0 or l.core_start >= l.core_end or l.core_end > layers) { + why.set("loop_config core range {d}..{d} must start after layer 0, be nonempty and fit inside the {d} physical layers", .{ l.core_start, l.core_end, layers }); + return error.Layout; + } + if (l.core_start % block != 0 or l.core_end % block != 0 or l.core_start != block or l.core_end + block != layers) { + why.set("loop_config core_start and core_end must be multiples of the {d}-layer attention-residual block, leaving its first and last blocks outside the loop", .{block}); + return error.Layout; + } + const visits = @as(u64, layers) + @as(u64, l.passes - 1) * @as(u64, l.core_end - l.core_start); + if (visits > max_visits) { + why.set("loop_config makes {d} layer visits: the plan tables hold {d}", .{ visits, max_visits }); + return error.Layout; + } + return l; +} + fn parseText(o: std.json.ObjectMap, why: *Why) !Text { var t: Text = undefined; + t.loop = null; t.hidden = try int(o, "hidden_size", why); t.layers = try int(o, "num_hidden_layers", why); t.vocab = try int(o, "vocab_size", why); @@ -261,6 +313,7 @@ fn parseText(o: std.json.ObjectMap, why: *Why) !Text { return error.Unsupported; }; try layerTypes(o, t.layers, why); + if (o.get("loop_config")) |_| t.loop = try parseLoop(try object(o, "loop_config", why), t.layers, t.block, why); return t; } @@ -311,7 +364,7 @@ fn parseMtp(o: std.json.ObjectMap, t: *const Text, why: *Why) !Mtp { m.local[@intCast(e.integer)] = true; } for (taps.array.items) |e| { - if (e != .integer or e.integer < 0 or e.integer > t.layers) { + if (e != .integer or e.integer < 0 or e.integer > t.visitCount()) { why.set("mtp_config's target_layer_ids names a layer the backbone does not have", .{}); return error.Layout; } @@ -349,15 +402,26 @@ pub fn parse(gpa: std.mem.Allocator, json: []const u8, why: *Why) !Config { } const o = parsed.value.object; const arch = o.get("architectures"); - const ok = arch != null and arch.? == .array and arch.?.array.items.len == 1 and arch.?.array.items[0] == .string and - std.mem.eql(u8, arch.?.array.items[0].string, "Inkling2ForConditionalGeneration"); - if (!ok or !std.mem.eql(u8, text(o, "model_type") orelse "", "inkling2")) { - why.set("not an Inkling 2 checkpoint: architectures Inkling2ForConditionalGeneration, model_type inkling2", .{}); + const arch_ok = arch != null and arch.? == .array and arch.?.array.items.len == 1 and arch.?.array.items[0] == .string; + const arch_name: []const u8 = if (arch_ok) arch.?.array.items[0].string else ""; + const model_name = text(o, "model_type") orelse ""; + const small = std.mem.eql(u8, arch_name, "Inkling2ForConditionalGeneration") and std.mem.eql(u8, model_name, "inkling2"); + const looped = std.mem.eql(u8, arch_name, "Inkling2LoopForConditionalGeneration") and std.mem.eql(u8, model_name, "inkling2_loop"); + if (!small and !looped) { + why.set("not an Inkling 2 checkpoint: Small or Mini model_type and architectures must match", .{}); return error.NotInkling2; } try fixed(o, "tie_word_embeddings", false, why); try quantization(o, why); const t = try parseText(try object(o, "text_config", why), why); + if (looped and t.loop == null) { + why.set("inkling2_loop requires text_config.loop_config", .{}); + return error.BadConfig; + } + if (small and t.loop != null) { + why.set("loop_config requires the inkling2_loop model and architecture", .{}); + return error.Unsupported; + } const eos = try int(o, "eos_token_id", why); if (eos >= t.vocab) { why.set("eos_token_id is not a token of the {d}-token vocabulary", .{t.vocab}); diff --git a/zig/src/families/inkling2/config_test.zig b/zig/src/families/inkling2/config_test.zig index 3d24d543b66..a8ad85ab3c7 100644 --- a/zig/src/families/inkling2/config_test.zig +++ b/zig/src/families/inkling2/config_test.zig @@ -5,6 +5,7 @@ const config = @import("config.zig"); const t = std.testing; pub const real = @embedFile("fixtures/config.json"); pub const tiny = @embedFile("fixtures/tiny_config.json"); +pub const mini = @embedFile("fixtures/mini_config.json"); fn refused(json: []const u8, from: []const u8, to: []const u8, want: anyerror, says: []const u8) !void { if (std.mem.count(u8, json, from) != 1) return error.EditAnchor; @@ -46,6 +47,40 @@ test "Inkling 2 Small's config.json parses: 48 layers, 8 global, 384 experts, 8 try t.expectEqualSlices(bool, &.{ true, true, false, true, true }, m.local[0..5]); } +test "Inkling 2 Mini's config.json parses: 24 weight layers, 48 visits and four drafter taps" { + var why: config.Why = .{}; + const c = try config.parse(t.allocator, mini, &why); + try t.expectEqual(@as(u32, 2304), c.text.hidden); + try t.expectEqual(@as(u32, 24), c.text.layers); + try t.expectEqual(@as(u32, 48), c.text.visitCount()); + try t.expectEqual(config.Heads{ .q = 24, .kv = 8, .dim = 128 }, c.text.global); + try t.expectEqual(@as(u32, 8192), c.text.log_floor); + try t.expectEqual(@as(u32, 128), c.text.experts); + try t.expectEqual(@as(u32, 1152), c.text.expert_inter); + try t.expectEqual(@as(f32, 8), c.text.route_scale); + const loop = c.text.loop.?; + try t.expectEqual(@as(u32, 6), loop.core_start); + try t.expectEqual(@as(u32, 18), loop.core_end); + try t.expectEqual(@as(u32, 3), loop.passes); + try t.expectEqual(@as(u32, 64), loop.gate_rank); + try t.expectEqual(@as(u32, 2304), c.vision.text_hidden); + const m = c.mtp.?; + try t.expectEqual(@as(u32, 3), m.layers); + try t.expectEqual(@as(u32, 9216), m.inter); + try t.expectEqualSlices(u32, &.{ 5, 23, 41, 48 }, m.taps[0..m.taps_n]); + try t.expectEqualSlices(bool, &.{ true, false, true }, m.local[0..3]); +} + +test "loop layouts the engine does not run are refused by their config key" { + try refused(mini, "\"is_varloop\": false", "\"is_varloop\": true", error.Unsupported, "is_varloop must be false"); + try refused(mini, "\"core_start\": 6", "\"core_start\": 0", error.Layout, "must start after layer 0"); + try refused(mini, "\"core_start\": 6", "\"core_start\": 7", error.Layout, "multiples of the 6-layer"); + try refused(mini, "\"core_end\": 18", "\"core_end\": 24", error.Layout, "multiples of the 6-layer"); + try refused(mini, "\"core_end\": 18,", "\"core_end\": 30,", error.Layout, "fit inside the 24 physical layers"); + try refused(mini, "Inkling2LoopForConditionalGeneration", "Inkling2ForConditionalGeneration", error.NotInkling2, "model_type and architectures must match"); + try refused(mini, "\"model_type\": \"inkling2_loop\"", "\"model_type\": \"inkling2\"", error.NotInkling2, "model_type and architectures must match"); +} + test "tiny-random's config.json parses: 12 layers, 96 experts, width 128, no quantization_config" { var why: config.Why = .{}; const c = try config.parse(t.allocator, tiny, &why); diff --git a/zig/src/families/inkling2/cuda_native.zig b/zig/src/families/inkling2/cuda_native.zig new file mode 100644 index 00000000000..6bb3b8d7fe0 --- /dev/null +++ b/zig/src/families/inkling2/cuda_native.zig @@ -0,0 +1,220 @@ +//! Inkling 2 Mini's complete one-rank, text-only CUDA engine and checkpoint/snapshot admission. +const std = @import("std"); +const cuda = @import("cuda"); +const lanes = @import("lanes"); +const core = @import("core"); +const config = @import("config.zig"); +const plan_ = @import("plan.zig"); +const loop = @import("loop.zig"); +const engine = @import("loop_engine.zig"); +const backend = @import("loop_backend.zig"); + +pub const model_type = "inkling2_loop"; +pub const formats: []const []const u8 = &.{"modelopt-mixed"}; +pub const default_context: i64 = 1_048_576; +pub const max_segments: u32 = 1; +pub const prompt_rows: u32 = engine.prompt_rows; +pub const window_rows: u32 = engine.window_rows; +pub const explains_open = true; + +pub const VisionOptions = struct { image_tokens: u32, max_images: u32 }; +pub const Room = struct { ctx: *anyopaque, read: *const fn (*anyopaque) ?u64 }; +pub const Options = struct { + context: usize, + drafts: bool, + segments: usize = 1, + slide: bool = false, + vision: ?VisionOptions = null, + precision: ?enum { full } = null, + room: ?Room = null, + drafter: ?[]const u8 = null, + tp: usize = 1, + rank: usize = 0, + master: ?[]const u8 = null, + master_port: u16 = 29551, +}; + +pub const Owned = struct { + gpa: std.mem.Allocator, + admission: loop.Admission, + kernels: engine.Kernels, + stream: cuda.Stream, + weights: @import("loop_weights.zig").Weights, + model: engine.Model, + backend: backend.Backend, +}; + +pub const Loaded = struct { + backend: lanes.backend.Backend, + facts: lanes.Model, + rows: u32, + stream_bytes: usize, + free_streams: u32 = 1, + ctx: *anyopaque, + deinit: *const fn (*anyopaque) void, + reserve: *const fn (*anyopaque, u32) anyerror!void = reserve, + target: *Owned, +}; + +fn own(ptr: *anyopaque) *Owned { + return @ptrCast(@alignCast(ptr)); +} + +fn release(p: *anyopaque) void { + const o = own(p); + o.stream.synchronize() catch {}; + o.backend.deinit(); + o.stream.deinit(); + o.model.deinit(); + o.kernels.deinit(); + o.weights.deinit(); + const gpa = o.gpa; + gpa.destroy(o); +} + +/// The server's stream count: a cache slot each, past the one allocated at load. +fn reserve(p: *anyopaque, streams: u32) anyerror!void { + return own(p).backend.reserve(streams); +} + +pub fn fits(p: *anyopaque, prompt: u32, max_tokens: u32) bool { + const o: *const Owned = @ptrCast(@alignCast(p)); + return o.admission.fits(prompt, max_tokens) and o.backend.admits(prompt, max_tokens); +} + +pub fn open(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: []const u8, kernels: ?[]const u8, o: Options) !Loaded { + if (kernels != null) return error.Inkling2CapturedKernels; + if (o.segments != 1 or o.tp != 1 or o.rank != 0) return error.Inkling2LoopOneRankOnly; + if (o.vision != null) return error.Inkling2LoopTextOnly; + if (o.drafter != null) return error.Inkling2DSparkPending; + const path = try std.fs.path.join(gpa, &.{ dir, "config.json" }); + defer gpa.free(path); + const bytes = try std.Io.Dir.cwd().readFileAlloc(io, path, gpa, .limited(1 << 20)); + defer gpa.free(bytes); + var why: config.Why = .{}; + const c = config.parse(gpa, bytes, &why) catch |err| { + std.log.err("Inkling 2 Mini config refused: {s}", .{why.text()}); + return err; + }; + try loop.validateLoad(&c, 1, false); + if (o.context == 0 or o.context > c.text.max_context or o.context > std.math.maxInt(u32)) return error.BadLoopCache; + var ck = try core.Checkpoint.openModel(gpa, io, dir); + defer ck.close(); + try ck.skip("model.visual."); // The checkpoint carries Small's tower; text-only Mini never loads or executes it. + var precisions: [config.max_layers]plan_.Precision = undefined; + @memset(&precisions, .nvfp4); + var header_arena = std.heap.ArenaAllocator.init(gpa); + defer header_arena.deinit(); + var merged: core.safetensors.Header = .empty; + for (ck.files.items) |file| try @import("names.zig").merge(header_arena.allocator(), &merged, file.names); + try @import("names.zig").precisions(merged, c.text.layers, &precisions); + const p = try plan_.build(&c.text, precisions[0..c.text.layers]); + var w = try @import("loop_weights.zig").load(gpa, ctx.d, &ck, &c, p); + errdefer w.deinit(); + if (ck.unused() != 0) return error.UnusedCheckpointTensor; + ck.release(); + var k = try engine.Kernels.load(ctx); + errdefer k.deinit(); + var stream = try cuda.Stream.init(ctx.d, true); + errdefer stream.deinit(); + var m = try engine.Model.init(gpa, ctx.d, stream, &w, o.context); + errdefer m.deinit(); + var be = try backend.Backend.init(gpa, ctx.d, &m, &k, stream); + errdefer be.deinit(); + const out = try gpa.create(Owned); + errdefer gpa.destroy(out); + out.* = .{ .gpa = gpa, .admission = .{ .context = @intCast(o.context) }, .kernels = k, .stream = stream, .weights = w, .model = m, .backend = be }; + // The value copies above own pointers to their old stack homes; retarget the live model/backend now. + out.model.w = &out.weights; + out.backend.m = &out.model; + out.backend.k = &out.kernels; + return .{ .backend = out.backend.backend(), .facts = out.backend.facts(), .rows = window_rows, .stream_bytes = backend.streamBytes(&out.model), .ctx = out, .deinit = release, .target = out }; +} + +pub fn snap_bytes(ptr: *anyopaque, at: u32) u64 { + return own(ptr).model.snapshotBytes(at); +} + +pub fn snap_save(ptr: *anyopaque, owner: ?*anyopaque, at: u32) anyerror!*anyopaque { + return @ptrCast(try own(ptr).backend.saveState(owner, at)); +} + +pub fn snap_restore(ptr: *anyopaque, owner: ?*anyopaque, saved: *anyopaque) anyerror!void { + return own(ptr).backend.restoreState(owner, @ptrCast(@alignCast(saved))); +} + +pub fn snap_drop(ptr: *anyopaque, saved: *anyopaque) void { + own(ptr).backend.dropState(@ptrCast(@alignCast(saved))); +} + +pub fn explain(_: ?*anyopaque, err: anyerror) ?[]const u8 { + return switch (err) { + error.Inkling2LoopOneRankOnly => "Inkling 2 Mini runs at one CUDA rank with one segment; TP and multi-segment modes are refused", + error.Inkling2LoopTextOnly => "Inkling 2 Mini is text-only on CUDA: images and --vision are refused", + error.Inkling2DSparkPending => "the Mini DSpark drafter has names and taps but no native draft engine in this build", + error.Inkling2CapturedKernels => "Inkling 2 Mini runs the engine's own kernels: unset TENSORFOLD_CUDA_KERNELS", + error.Inkling2TooManyStreams => "Inkling 2 Mini on CUDA holds at most 16 streams: lower --parallel", + error.StructuresUnsupported, error.ChainsOnly => "Inkling 2 Mini serves only unconstrained, non-branching text drafts", + else => null, + }; +} + +test "Mini native registration and refusal wording are explicit" { + try std.testing.expectEqualStrings("inkling2_loop", model_type); + try std.testing.expect(max_segments == 1 and prompt_rows == 2048 and window_rows == 16); + try std.testing.expectEqual(16, engine.max_slots); // the stream cap explain() names + for ([_]anyerror{ error.Inkling2LoopOneRankOnly, error.Inkling2LoopTextOnly, error.Inkling2DSparkPending, error.Inkling2CapturedKernels, error.Inkling2TooManyStreams }) |err| { + try std.testing.expect(explain(null, err) != null); + } +} + +test "the complete prompt snapshot hooks match the store vtable" { + const pc: struct { + bytes: *const fn (*anyopaque, u32) u64, + save: *const fn (*anyopaque, ?*anyopaque, u32) anyerror!*anyopaque, + restore: *const fn (*anyopaque, ?*anyopaque, *anyopaque) anyerror!void, + drop: *const fn (*anyopaque, *anyopaque) void, + } = .{ .bytes = snap_bytes, .save = snap_save, .restore = snap_restore, .drop = snap_drop }; + try std.testing.expect(@intFromPtr(pc.save) != 0); +} + +test "stream_bytes is what an extra stream's slot and lane buffers allocate, 806,408 bytes past the cache on Mini" { + const Record = struct { // a DeviceBuffer hook that hands out addresses and sums what is asked + bytes: usize = 0, + next: u64 = 1 << 32, + fn alloc(ctx: *anyopaque, len: usize) ?u64 { + const r: *@This() = @ptrCast(@alignCast(ctx)); + r.bytes += len; + r.next += std.mem.alignForward(u64, len, 512); + return r.next; + } + fn free(_: *anyopaque, _: u64) bool { + return true; + } + }; + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + var why: config.Why = .{}; + var w: @import("loop_weights.zig").Weights = undefined; + w.c = try config.parse(arena.allocator(), @import("config_test.zig").mini, &why); + var precisions: [24]plan_.Precision = @splat(.nvfp4); + w.p = try plan_.build(&w.c.text, &precisions); + var m: engine.Model = undefined; + m.d = @ptrFromInt(0x1000); // never called: the hook answers every allocation + m.w = &w; + m.layout = try loop.CacheLayout.init(&w.c.text, &w.p, 8192); + var b: backend.Backend = undefined; + b.d = m.d; + b.m = &m; + b.held = 1; + var rec: Record = .{}; + const before = cuda.memory.currentHook(); + cuda.memory.setHook(.{ .ctx = &rec, .alloc = Record.alloc, .free = Record.free }); + defer cuda.memory.setHook(before); + var slot = try m.newSlot(); + defer for ([2]*cuda.DeviceBuffer{ &slot.cache, &slot.sites }) |x| x.free(); + try b.slotBuffers(2); // the second stream's lane buffers; the first already holds its own + defer for (&b.slot[1]) |*x| x.free(); + try std.testing.expectEqual(@as(u64, rec.bytes), backend.streamBytes(&m)); + try std.testing.expectEqual(@as(u64, 48 * 4 * 32 + 200_058 * 4 + 32), backend.streamBytes(&m) - m.layout.bytes); +} diff --git a/zig/src/families/inkling2/experts.zig b/zig/src/families/inkling2/experts.zig new file mode 100644 index 00000000000..2d0d017d95f --- /dev/null +++ b/zig/src/families/inkling2/experts.zig @@ -0,0 +1,148 @@ +//! Inkling 2's routed experts: the family's grouping and grouped projections, main's rotation and combine. +const std = @import("std"); +const cuda = @import("cuda"); +const ops = @import("ops.zig"); + +const ex = cuda.exl3_experts; + +/// The two SwiGLU softcaps (config.json mlp_gate_softcap, mlp_up_softcap). +pub const Caps = struct { gate: f32, up: f32 }; + +/// Calls of at least this many rows take an item list (runs of one expert's members), not one item an expert. +pub const listed_from = 17; +/// Calls of at least this many rows take the prompt kernel (32 members by 64 columns a block). +pub const wide_from = 512; + +/// main's experts module beside the family's grouped projections. +pub const Kernels = struct { + main: ex.Experts, + mod: cuda.Module, + group: cuda.Function, + rows: cuda.Function, + wide: cuda.Function, + + pub fn load(d: *const cuda.Driver) !Kernels { + var main = try ex.Experts.load(d); + errdefer main.unload(); + var mod = try cuda.Module.load(d, cuda.kernels.inkling2_experts); + errdefer mod.unload(); + return .{ + .main = main, + .mod = mod, + .group = try mod.function("tf_ink2x_group"), + .rows = try mod.function("tf_ink2x_rows"), + .wide = try mod.function("tf_ink2x_wide"), + }; + } + + pub fn unload(k: *Kernels) void { + k.mod.unload(); + k.main.unload(); + } +}; + +fn i32d(v: usize) i32 { + return @intCast(v); +} + +fn align256(n: usize) usize { + return (n + 255) / 256 * 256; +} + +/// Items at most a call of `rows` rows lists: runs of 16 members, plus one partial run a distinct expert. +fn maxItems(l: ex.Layer, rows: usize, slots: usize) usize { + const p = rows * slots; + return (p + 15) / 16 + @min(p, l.experts); +} + +/// main's scratch, then the item count and the item list (three int32 an item). +pub fn scratchBytes(l: ex.Layer, rows: usize, slots: usize) !usize { + return try ex.scratchBytes(l, rows, slots) + 256 + align256(maxItems(l, rows, slots) * 12); +} + +/// Where the item count sits in scratch laid out by ex.scratch over scratchBytes(); the list follows 256 bytes on. +fn itemsAt(l: ex.Layer, sc: ex.Scratch) u64 { + return sc.members + align256(@min(sc.rows * sc.slots, l.experts) * sc.rows * 4); +} + +/// exl3_experts.Experts.run's launches in its order: the family's grouped projections, ops.cu's tf_ink2_gateup. +pub fn run(e: *const Kernels, k: *const ops.Kernels, s: cuda.Stream, l: ex.Layer, caps: Caps, x: u64, x_stride: usize, x_dtype: ex.DType, pick: u64, wts: u64, rows: usize, out: u64, sc: ex.Scratch) !void { + const d = l.dims; + const w = l.width; + const slots = sc.slots; + if (rows < 1 or rows > sc.rows or slots < 1 or slots > 32) return error.BadExperts; + if (l.experts < 1 or l.experts > 512 or l.codebook != .mul1 or l.gu_stride != 0) return error.BadExperts; + const g_sk = try ex.plan(d, w, true); + const d_sk = try ex.plan(w, d, false); + const p = rows * slots; + const maxu = @min(p, l.experts); + + const listed = rows >= listed_from; + const wide = rows >= wide_from; + const per: usize = if (wide) 32 else 16; + const at = itemsAt(l, sc); + var a: cuda.Args = .{}; + for ([_]u64{ pick, sc.ids, sc.count, sc.members, at + 256, at }) |v| a.add(v); + for ([_]usize{ rows, slots, l.experts, rows, if (listed) per else 0, @intFromBool(!listed) }) |v| a.add(i32d(v)); + const shared: u32 = @intCast(l.experts * (32 * 2 + 2 * 4)); // per-warp uint16 counts, then counts and places + try cuda.launch.launch(e.group, .{ .grid = .{ .x = 1 }, .block = .{ .x = 1024 }, .shared = shared }, s, &a); + const items: u64 = if (listed) at + 256 else 0; + const count: u64 = if (listed) at else sc.count; + const gy: u32 = @intCast(if (listed) (p + per - 1) / per + maxu else maxu); + const f = if (wide) e.wide else e.rows; + const cols: usize = if (wide) 64 else 128; + + var r: cuda.Args = .{}; + r.add(x); + r.add(i32d(x_stride)); + r.add(@as(i32, @backingInt(x_dtype))); + for ([_]u64{ pick, l.suh_g, l.suh_u, sc.xg, sc.xu }) |v| r.add(v); + for ([_]usize{ d, slots, l.experts }) |v| r.add(i32d(v)); + const rot: cuda.Dim3 = .{ .x = @intCast(p), .y = @intCast(d / 128), .z = 2 }; + try cuda.launch.launch(e.main.rot_in, .{ .grid = rot, .block = .{ .x = 32 } }, s, &r); + + var g: cuda.Args = .{}; + for ([_]u64{ sc.xg, sc.xu, l.gate, l.up, l.gate_k2, l.up_k2, sc.ids }) |v| g.add(v); + for ([_]u64{ items, count, sc.members, sc.z }) |v| g.add(v); + for ([_]usize{ d, w, p, g_sk, rows, slots }) |v| g.add(i32d(v)); + const gu: cuda.Dim3 = .{ .x = @intCast(w / cols), .y = gy, .z = @intCast(2 * g_sk) }; + try cuda.launch.launch(f, .{ .grid = gu, .block = .{ .x = 128 } }, s, &g); + + try ops.gateup(k, s, .{ .z = sc.z, .pick = pick, .svh_g = l.svh_g, .svh_u = l.svh_u, .suh_d = l.suh_d, .xd = sc.xd, .p = i32d(p), .n = i32d(w), .sk = i32d(g_sk), .experts = i32d(l.experts), .gate_cap = caps.gate, .up_cap = caps.up }); + + var dn: cuda.Args = .{}; + for ([_]u64{ sc.xd, sc.xd, l.down, l.down, l.down_k2, l.down_k2, sc.ids }) |v| dn.add(v); + for ([_]u64{ items, count, sc.members, sc.z }) |v| dn.add(v); + for ([_]usize{ w, d, p, d_sk, rows, slots }) |v| dn.add(i32d(v)); + const down: cuda.Dim3 = .{ .x = @intCast(d / cols), .y = gy, .z = @intCast(d_sk) }; + try cuda.launch.launch(f, .{ .grid = down, .block = .{ .x = 128 } }, s, &dn); + + var cb: cuda.Args = .{}; + for ([_]u64{ sc.z, pick, l.svh_d, sc.y, wts, out }) |v| cb.add(v); + for ([_]usize{ p, d, d_sk, l.experts, slots }) |v| cb.add(i32d(v)); + const comb: cuda.Dim3 = .{ .x = @intCast(rows), .y = @intCast(d / 128) }; + try cuda.launch.launch(e.main.down_combine, .{ .grid = comb, .block = .{ .x = @intCast(32 * slots) } }, s, &cb); +} + +test "experts: Inkling's expert shapes have built tiles (gate/up 4608 -> 2304 whole and a rank's 1152, down back)" { + try std.testing.expectEqual(@as(u32, 4), try ex.plan(4608, 2304, true)); + try std.testing.expectEqual(@as(u32, 4), try ex.plan(4608, 1152, true)); + _ = try ex.plan(2304, 4608, false); + _ = try ex.plan(1152, 4608, false); +} + +test "experts: the item list sits past main's scratch and holds a 2,048-row call's items" { + var l = std.mem.zeroes(ex.Layer); + l.experts = 384; + l.dims = 4608; + l.width = 1152; + l.codebook = .mul1; + const bytes = try scratchBytes(l, 2048, 8); + const sc = try ex.scratch(0, l, 2048, 8); + const at = itemsAt(l, sc); + try std.testing.expectEqual(@as(u64, try ex.scratchBytes(l, 2048, 8)), at); + try std.testing.expectEqual(@as(usize, 16384 / 16 + 384), maxItems(l, 2048, 8)); + try std.testing.expect(at + 256 + maxItems(l, 2048, 8) * 12 <= bytes); + // the kernels' column blocks: the rows kernel 128 columns, the wide one 64, of a rank's 1152 and the 4608 width + try std.testing.expect(1152 % 128 == 0 and 4608 % 128 == 0); +} diff --git a/zig/src/families/inkling2/fixtures/mini_config.json b/zig/src/families/inkling2/fixtures/mini_config.json new file mode 100644 index 00000000000..71dca9f656e --- /dev/null +++ b/zig/src/families/inkling2/fixtures/mini_config.json @@ -0,0 +1,129 @@ +{ + "_fixture_provenance": { + "release": "thinkingmachines/Inkling-2-Mini", + "revision": "ed40e7da625f594fc9c4990f5f66be24873c22d7", + "revision_status": "full revision supplied separately; every checkpoint config field matches", + "published": "2026-11-20", + "license": "apache-2.0" + }, + "dtype": "bfloat16", + "architectures": [ + "Inkling2LoopForConditionalGeneration" + ], + "model_type": "inkling2_loop", + "eos_token_id": 200006, + "text_config": { + "model_type": "inkling2_loop_text", + "model_max_length": 1048576, + "torch_dtype": "bfloat16", + "hidden_size": 2304, + "num_hidden_layers": 24, + "vocab_size": 201024, + "num_attention_heads": 24, + "num_key_value_heads": 8, + "head_dim": 128, + "d_rel": 16, + "rel_extent": 1024, + "q_bias": false, + "o_bias": false, + "log_scaling_n_floor": 8192, + "log_scaling_alpha": 0.1, + "rms_norm_eps": 1e-06, + "use_value_norm_no_gamma": true, + "qk_l2_clip_threshold": 22.627416997969522, + "rel_l2_clip_threshold": 8.0, + "local_layer_ids": [ + 0, + 1, + 2, + 3, + 4, + 6, + 7, + 8, + 9, + 10, + 12, + 13, + 14, + 15, + 16, + 18, + 19, + 20, + 21, + 22 + ], + "sconv_kernel_size": 4, + "unpadded_vocab_size": 200058, + "final_logit_softcapping": 30.0, + "swa_head_dim": 128, + "swa_num_attention_heads": 24, + "swa_num_key_value_heads": 8, + "sliding_window_size": 1024, + "n_layers_per_attn_res_block": 6, + "attn_res_normalize_values": true, + "n_routed_experts": 128, + "num_experts_per_tok": 8, + "n_shared_experts": 0, + "intermediate_size": 1152, + "mlp_gate_softcap": 4.0, + "mlp_up_softcap": 25.0, + "route_scale": 8.0, + "use_gate_bias": true, + "loop_config": { + "core_start": 6, + "core_end": 18, + "num_passes": 3, + "gate_rank": 64, + "is_varloop": false + } + }, + "vision_config": { + "model_type": "inkling2_vision", + "text_hidden_size": 2304, + "temporal_patch_size": 2, + "native_patch_size": 20, + "adapter_merge_size": 2, + "projection_hidden_dim": 4096, + "projector_bias": false, + "hidden_size": 1024, + "num_hidden_layers": 23, + "num_attention_heads": 16, + "mlp_ratio": 4.0, + "posemb_grid_size": 32, + "layer_norm_eps": 1e-05 + }, + "mtp_config": { + "hidden_size": 2304, + "num_hidden_layers": 3, + "num_attention_heads": 24, + "num_key_value_heads": 8, + "head_dim": 128, + "intermediate_size": 9216, + "max_position_embeddings": 1048576, + "torch_dtype": "bfloat16", + "q_bias": false, + "o_bias": false, + "rms_norm_eps": 1e-06, + "rope_theta": 1000000.0, + "local_layer_ids": [ + 0, + 2 + ], + "sliding_window_size": 1024, + "block_size": 8, + "markov_rank": 256, + "markov_head_type": "rnn_hidden", + "target_layer_ids": [ + 5, + 23, + 41, + 48 + ] + }, + "quantization_config": { + "quant_method": "modelopt", + "quant_algo": "NVFP4" + } +} diff --git a/zig/src/families/inkling2/fixtures/mini_model_header.txt b/zig/src/families/inkling2/fixtures/mini_model_header.txt new file mode 100644 index 00000000000..0ec22c72d2b --- /dev/null +++ b/zig/src/families/inkling2/fixtures/mini_model_header.txt @@ -0,0 +1,86 @@ +inkling2-mini-model 1244 dfcec4225659aceabe432e4daadb4e6291f3718e2015d412f97f60200de32141 release=thinkingmachines/Inkling-2-Mini revision=ed40e7da625f594fc9c4990f5f66be24873c22d7 published=2026-11-20 license=apache-2.0 +model.llm.attn_res.attn_queries.{L} F32 2304 0-3,5-9,11-15,17-21 +model.llm.attn_res.attn_queries.{L} F32 3x2304 4,10,16,22 +model.llm.attn_res.mlp_queries.{L} F32 2304 0-23 +model.llm.attn_res.output_query F32 2304 +model.llm.embed.weight BF16 201024x2304 +model.llm.embed_norm.weight BF16 2304 +model.llm.layers.{L}.attn.attn_sink_proj.weight BF16 24x2304 0-23 +model.llm.layers.{L}.attn.gate_attn.weight BF16 3072x2304 0-23 +model.llm.layers.{L}.attn.k_sconv.static_w BF16 4x1024 5,11,17,23 +model.llm.layers.{L}.attn.k_sconv.weight BF16 1024x1x4 0-4,6-10,12-16,18-22 +model.llm.layers.{L}.attn.k_sconv.weight_proj BF16 32x2304 5,11,17,23 +model.llm.layers.{L}.attn.q_l2_clip.scale BF16 24x128 0-23 +model.llm.layers.{L}.attn.rel_l2_clip.scale BF16 24x16 0-23 +model.llm.layers.{L}.attn.rel_logits_proj.proj BF16 16x1024 0-23 +model.llm.layers.{L}.attn.v_sconv.static_w BF16 4x1024 5,11,17,23 +model.llm.layers.{L}.attn.v_sconv.weight BF16 1024x1x4 0-4,6-10,12-16,18-22 +model.llm.layers.{L}.attn.v_sconv.weight_proj BF16 32x2304 5,11,17,23 +model.llm.layers.{L}.attn.wk_dv.weight BF16 1024x2304 0-23 +model.llm.layers.{L}.attn.wo_ud.weight BF16 2304x3072 0-23 +model.llm.layers.{L}.attn.wq_du.weight BF16 3072x2304 0-23 +model.llm.layers.{L}.attn.wr_du.weight BF16 384x2304 0-23 +model.llm.layers.{L}.attn.wv_dv.weight BF16 1024x2304 0-23 +model.llm.layers.{L}.attn_norm.weight BF16 2304 0-4,6-10,12-16,18-22 +model.llm.layers.{L}.attn_sconv.weight BF16 2304x1x4 0-23 +model.llm.layers.{L}.controllers.attn.down_weight BF16 64x4608 6-17 +model.llm.layers.{L}.controllers.attn.forget_weight BF16 2304x64 6-17 +model.llm.layers.{L}.controllers.attn.gain_weight BF16 2304x64 6-17 +model.llm.layers.{L}.controllers.k.down_weight BF16 64x4608 6-17 +model.llm.layers.{L}.controllers.k.forget_weight BF16 2304x64 6-17 +model.llm.layers.{L}.controllers.k.gain_weight BF16 2304x64 6-17 +model.llm.layers.{L}.controllers.mlp.down_weight BF16 64x4608 6-17 +model.llm.layers.{L}.controllers.mlp.forget_weight BF16 2304x64 6-17 +model.llm.layers.{L}.controllers.mlp.gain_weight BF16 2304x64 6-17 +model.llm.layers.{L}.controllers.v.down_weight BF16 64x4608 6-17 +model.llm.layers.{L}.controllers.v.forget_weight BF16 2304x64 6-17 +model.llm.layers.{L}.controllers.v.gain_weight BF16 2304x64 6-17 +model.llm.layers.{L}.k_input_norm.weight BF16 2304 5,11,17,23 +model.llm.layers.{L}.mlp.experts.w13_weight F8_E4M3 128x2304x2304 20-23 +model.llm.layers.{L}.mlp.experts.w13_weight U8 128x2304x1152 0-19 +model.llm.layers.{L}.mlp.experts.w13_weight_amax F32 128 0-19 +model.llm.layers.{L}.mlp.experts.w13_weight_outer_scale_denominator F32 1 0-19 +model.llm.layers.{L}.mlp.experts.w13_weight_scale F8_E4M3 128x2304x144 0-19 +model.llm.layers.{L}.mlp.experts.w13_weight_scale U8 128x2304x72 20-23 +model.llm.layers.{L}.mlp.experts.w2_weight F8_E4M3 128x2304x1152 20-23 +model.llm.layers.{L}.mlp.experts.w2_weight U8 128x2304x576 0-19 +model.llm.layers.{L}.mlp.experts.w2_weight_amax F32 128 0-19 +model.llm.layers.{L}.mlp.experts.w2_weight_outer_scale_denominator F32 1 0-19 +model.llm.layers.{L}.mlp.experts.w2_weight_scale F8_E4M3 128x2304x72 0-19 +model.llm.layers.{L}.mlp.experts.w2_weight_scale U8 128x2304x36 20-23 +model.llm.layers.{L}.mlp.gate.bias F32 128 0-23 +model.llm.layers.{L}.mlp.gate.weight BF16 128x2304 0-23 +model.llm.layers.{L}.mlp_norm.weight BF16 2304 0-23 +model.llm.layers.{L}.mlp_sconv.weight BF16 2304x1x4 0-23 +model.llm.layers.{L}.q_input_norm.weight BF16 2304 5,11,17,23 +model.llm.layers.{L}.v_input_norm.weight BF16 2304 5,11,17,23 +model.llm.middle_cycle_cross_pass_kv_queries F32 24x2304 +model.llm.middle_cycle_cross_pass_queries F32 24x2304 +model.llm.norm.weight BF16 2304 +model.llm.unembed.weight BF16 201024x2304 +model.visual.backbone.embeddings.class_embedding BF16 1024 +model.visual.backbone.embeddings.cls_position_embedding BF16 1024 +model.visual.backbone.embeddings.patch_embedding.weight BF16 1024x1200 +model.visual.backbone.embeddings.position_embedding BF16 1024x1024 +model.visual.backbone.layers.{L}.ln_1.bias BF16 1024 0-22 +model.visual.backbone.layers.{L}.ln_1.weight BF16 1024 0-22 +model.visual.backbone.layers.{L}.ln_2.bias BF16 1024 0-22 +model.visual.backbone.layers.{L}.ln_2.weight BF16 1024 0-22 +model.visual.backbone.layers.{L}.ls_1.gamma BF16 1024 0-22 +model.visual.backbone.layers.{L}.ls_2.gamma BF16 1024 0-22 +model.visual.backbone.layers.{L}.mlp.c_fc.bias BF16 4096 0-22 +model.visual.backbone.layers.{L}.mlp.c_fc.weight BF16 4096x1024 0-22 +model.visual.backbone.layers.{L}.mlp.c_proj.bias BF16 1024 0-22 +model.visual.backbone.layers.{L}.mlp.c_proj.weight BF16 1024x4096 0-22 +model.visual.backbone.layers.{L}.self_attn.k_proj.bias BF16 1024 0-22 +model.visual.backbone.layers.{L}.self_attn.k_proj.weight BF16 1024x1024 0-22 +model.visual.backbone.layers.{L}.self_attn.out_proj.bias BF16 1024 0-22 +model.visual.backbone.layers.{L}.self_attn.out_proj.weight BF16 1024x1024 0-22 +model.visual.backbone.layers.{L}.self_attn.q_proj.bias BF16 1024 0-22 +model.visual.backbone.layers.{L}.self_attn.q_proj.weight BF16 1024x1024 0-22 +model.visual.backbone.layers.{L}.self_attn.v_proj.bias BF16 1024 0-22 +model.visual.backbone.layers.{L}.self_attn.v_proj.weight BF16 1024x1024 0-22 +model.visual.backbone.ln_pre.bias BF16 1024 +model.visual.backbone.ln_pre.weight BF16 1024 +model.visual.proj_in.weight BF16 4096x4096 +model.visual.proj_out.weight BF16 2304x4096 diff --git a/zig/src/families/inkling2/fixtures/mini_mtp_header.txt b/zig/src/families/inkling2/fixtures/mini_mtp_header.txt new file mode 100644 index 00000000000..1f02401ebcb --- /dev/null +++ b/zig/src/families/inkling2/fixtures/mini_mtp_header.txt @@ -0,0 +1,25 @@ +inkling2-mini-mtp 54 f962cd87735ebbd1af0639f7513f99eed98b61d8a30b083fb33fc1bb1c3a70d1 release=thinkingmachines/Inkling-2-Mini revision=ed40e7da625f594fc9c4990f5f66be24873c22d7 published=2026-11-20 license=apache-2.0 +fuse_weight BF16 4x4 +layers.{L}.dflare_norm.weight BF16 2304 0-2 +layers.{L}.input_layernorm.weight BF16 2304 0-2 +layers.{L}.mlp.down_proj.weight BF16 2304x9216 0-2 +layers.{L}.mlp.gate_proj.weight BF16 9216x2304 0-2 +layers.{L}.mlp.up_proj.weight BF16 9216x2304 0-2 +layers.{L}.post_attention_layernorm.weight BF16 2304 0-2 +layers.{L}.self_attn.k_norm.weight BF16 128 0-2 +layers.{L}.self_attn.k_norm_ctx.weight BF16 128 0-2 +layers.{L}.self_attn.k_proj.weight BF16 1024x2304 0-2 +layers.{L}.self_attn.k_proj_ctx.weight BF16 1024x2304 0-2 +layers.{L}.self_attn.o_proj.weight BF16 2304x3072 0-2 +layers.{L}.self_attn.q_norm.weight BF16 128 0-2 +layers.{L}.self_attn.q_proj.weight BF16 3072x2304 0-2 +layers.{L}.self_attn.v_proj.weight BF16 1024x2304 0-2 +layers.{L}.self_attn.v_proj_ctx.weight BF16 1024x2304 0-2 +markov_head.dflare_norm.weight BF16 2304 +markov_head.hidden_out.bias BF16 2304 +markov_head.hidden_out.weight BF16 2304x256 +markov_head.markov_w1.weight BF16 201024x256 +markov_head.rnn_proj.bias BF16 768 +markov_head.rnn_proj.weight BF16 768x5120 +mask_embed BF16 2304 +norm.weight BF16 2304 diff --git a/zig/src/families/inkling2/fixtures/release_chat_template.jinja b/zig/src/families/inkling2/fixtures/release_chat_template.jinja new file mode 100644 index 00000000000..cae99e08917 --- /dev/null +++ b/zig/src/families/inkling2/fixtures/release_chat_template.jinja @@ -0,0 +1,137 @@ +{%- set effort_map = {"none": 0.0, "minimal": 0.1, "low": 0.2, "medium": 0.7, "high": 0.9, "xhigh": 0.99, "max": 0.99} -%} +{%- set role_token = {"user": "<|message_user|>", "assistant": "<|message_model|>", "system": "<|message_system|>", "tool": "<|message_tool|>"} -%} + +{%- macro emit_thinking_effort() -%} + {%- set eff = reasoning_effort if reasoning_effort is defined and reasoning_effort is not none else 0.9 -%} + {%- if eff is string -%} + {%- set key = eff | trim -%} + {%- if key not in effort_map -%} + {{- raise_exception("Unknown reasoning_effort: " ~ eff) -}} + {%- endif -%} + {%- set num = effort_map[key] -%} + {%- else -%} + {%- set num = eff | float -%} + {%- endif -%} + {%- if num < 0.0 or num > 0.99 -%} + {{- raise_exception("reasoning_effort must be in [0.0, 0.99]") -}} + {%- endif -%} + {{- "<|message_system|><|content_text|>Thinking effort level: " -}} + {%- if num == 0.0 -%}0{%- else -%}{{ num }}{%- endif -%} + {{- "<|end_message|>" -}} +{%- endmacro -%} + +{%- if tools -%} + {%- set tool_state = namespace(specs=[]) -%} + {%- for tool in tools -%} + {%- set fn = tool.function if tool.function is defined else tool -%} + {%- set spec = { + "description": (fn.description if fn.description is defined and fn.description else ""), + "name": fn.name, + "parameters": (fn.parameters if fn.parameters is defined and fn.parameters else {}), + "type": (tool.type if tool.type is defined and tool.type else "function"), + } -%} + {%- set tool_state.specs = tool_state.specs + [spec] -%} + {%- endfor -%} + {{- "<|message_system|>tool_declare<|content_xml|>" -}} + {{- tool_state.specs | tojson(sort_keys=true, separators=(",", ":")) -}} + {{- "<|end_message|>" -}} +{%- endif -%} + +{%- set state = namespace(effort_emitted=false) -%} +{%- for message in messages -%} + {%- if message.role not in role_token -%} + {{- raise_exception("Unknown message role: " ~ message.role) -}} + {%- endif -%} + {%- if not state.effort_emitted and message.role != "system" -%} + {{- emit_thinking_effort() -}} + {%- set state.effort_emitted = true -%} + {%- endif -%} + + {%- set header = namespace(text=role_token[message.role]) -%} + {%- if message.role == "tool" -%} + {%- if message.name is defined and message.name -%} + {%- set header.text = header.text ~ message.name -%} + {%- elif message.tool_call_id is defined and message.tool_call_id -%} + {%- for prev in messages -%} + {%- if prev.role == "assistant" and prev.tool_calls -%} + {%- for tc in prev.tool_calls -%} + {%- if tc.id is defined and tc.id == message.tool_call_id and tc.function.name is defined -%} + {%- set header.text = header.text ~ tc.function.name -%} + {%- endif -%} + {%- endfor -%} + {%- endif -%} + {%- endfor -%} + {%- endif -%} + {%- elif message.role == "assistant" and message.name is defined and message.name -%} + {%- set header.text = header.text ~ message.name -%} + {%- endif -%} + {%- set rtok = header.text -%} + {%- set rendered -%} + + {%- if message.role == "assistant" and message.reasoning_content is defined and message.reasoning_content -%} + {{- rtok ~ "<|content_thinking|>" ~ message.reasoning_content ~ "<|end_message|>" -}} + {%- endif -%} + + {%- if message.content is string and (message.content or not (message.role == "assistant" and (message.tool_calls or message.reasoning_content))) -%} + {{- rtok ~ "<|content_text|>" ~ message.content ~ "<|end_message|>" -}} + {%- elif message.content -%} + {%- for part in message.content -%} + {%- if part is string -%} + {{- rtok ~ "<|content_text|>" ~ part ~ "<|end_message|>" -}} + {%- elif part.type is not defined or part.type in ("text", "input_text") -%} + {%- set text_part = (part.text if part.text is defined and part.text is string else "") -%} + {{- rtok ~ "<|content_text|>" ~ text_part ~ "<|end_message|>" -}} + {%- elif part.type in ("image", "input_image", "image_url") -%} + {%- if message.role not in ("user", "tool") -%} + {{- raise_exception("Image content is only supported for user and tool messages") -}} + {%- endif -%} + {{- rtok ~ "<|content_image|><|unused_200054|><|end_message|>" -}} + {%- elif part.type in ("audio", "input_audio", "audio_url") -%} + {{- raise_exception("Inkling 2 does not accept audio input") -}} + {%- else -%} + {{- raise_exception("Unsupported content part type: " ~ part.type) -}} + {%- endif -%} + {%- endfor -%} + {%- endif -%} + + {%- if message.role == "assistant" and message.tool_calls -%} + {%- for tc in message.tool_calls -%} + {%- set fn = tc.function -%} + {%- if fn.name is not defined or fn.name is not string -%} + {{- raise_exception("tool call function name must be a string") -}} + {%- endif -%} + {%- if message.name is defined and message.name and message.name != fn.name -%} + {{- raise_exception("assistant name " ~ message.name ~ " does not match its tool call " ~ fn.name) -}} + {%- endif -%} + {%- set args = fn.arguments if fn.arguments is defined and fn.arguments else {} -%} + {%- if args is string -%} + {{- raise_exception("tool call arguments must be a parsed object, not a JSON string; canonicalize upstream") -}} + {%- endif -%} + {%- if args is not mapping -%} + {{- raise_exception("tool call arguments must be an object") -}} + {%- endif -%} + {{- "<|message_model|>" ~ fn.name ~ "<|content_invoke_tool_json|>" -}} + {{- '{"name":' ~ (fn.name | tojson(sort_keys=true, separators=(",", ":"))) ~ ',"args":' -}} + {{- "{" -}} + {%- for key, value in args | dictsort(case_sensitive=true) -%} + {{- (key | tojson) ~ ":" ~ (value | tojson(separators=(",", ":"))) -}} + {%- if not loop.last -%},{%- endif -%} + {%- endfor -%} + {{- "}}<|end_message|>" -}} + {%- endfor -%} + {%- endif -%} + + {%- if message.role == "assistant" -%} + {{- "<|content_model_end_sampling|>" -}} + {%- endif -%} + {%- endset -%} + {%- if message.role == "assistant" -%} + {%- generation -%}{{- rendered -}}{%- endgeneration -%} + {%- else -%} + {{- rendered -}} + {%- endif -%} +{%- endfor -%} + +{%- if not state.effort_emitted -%} + {{- emit_thinking_effort() -}} +{%- endif -%} diff --git a/zig/src/families/inkling2/fixtures/release_tokenizer_config.json b/zig/src/families/inkling2/fixtures/release_tokenizer_config.json new file mode 100644 index 00000000000..abf8fb60451 --- /dev/null +++ b/zig/src/families/inkling2/fixtures/release_tokenizer_config.json @@ -0,0 +1,548 @@ +{ + "tokenizer_class": "PreTrainedTokenizerFast", + "model_max_length": 1048576, + "clean_up_tokenization_spaces": false, + "fix_mistral_regex": false, + "extra_special_tokens": { + "endoftext": "<|endoftext|>", + "message_user": "<|message_user|>", + "message_model": "<|message_model|>", + "message_system": "<|message_system|>", + "message_tool": "<|message_tool|>", + "content_text": "<|content_text|>", + "content_image": "<|content_image|>", + "content_model_end_sampling": "<|content_model_end_sampling|>", + "content_thinking": "<|content_thinking|>", + "end_message": "<|end_message|>", + "content_tool_error": "<|content_tool_error|>", + "content_xml": "<|content_xml|>", + "begin_of_text": "<|begin_of_text|>", + "content_invoke_tool_json": "<|content_invoke_tool_json|>", + "content_invoke_tool_text": "<|content_invoke_tool_text|>" + }, + "added_tokens_decoder": { + "199998": { + "content": "<|unused|>", + "single_word": false, + "lstrip": false, + "rstrip": false, + "normalized": false, + "special": true + }, + "199999": { + "content": "<|endoftext|>", + "single_word": false, + "lstrip": false, + "rstrip": false, + "normalized": false, + "special": true + }, + "200000": { + "content": "<|message_user|>", + "single_word": false, + "lstrip": false, + "rstrip": false, + "normalized": false, + "special": true + }, + "200001": { + "content": "<|message_model|>", + "single_word": false, + "lstrip": false, + "rstrip": false, + "normalized": false, + "special": true + }, + "200002": { + "content": "<|message_system|>", + "single_word": false, + "lstrip": false, + "rstrip": false, + "normalized": false, + "special": true + }, + "200003": { + "content": "<|message_tool|>", + "single_word": false, + "lstrip": false, + "rstrip": false, + "normalized": false, + "special": true + }, + "200004": { + "content": "<|content_text|>", + "single_word": false, + "lstrip": false, + "rstrip": false, + "normalized": false, + "special": true + }, + "200005": { + "content": "<|content_image|>", + "single_word": false, + "lstrip": false, + "rstrip": false, + "normalized": false, + "special": true + }, + "200006": { + "content": "<|content_model_end_sampling|>", + "single_word": false, + "lstrip": false, + "rstrip": false, + "normalized": false, + "special": true + }, + "200007": { + "content": "<|unused_200007|>", + "single_word": false, + "lstrip": false, + "rstrip": false, + "normalized": false, + "special": true + }, + "200008": { + "content": "<|content_thinking|>", + "single_word": false, + "lstrip": false, + "rstrip": false, + "normalized": false, + "special": true + }, + "200009": { + "content": "<|unused_200009|>", + "single_word": false, + "lstrip": false, + "rstrip": false, + "normalized": false, + "special": true + }, + "200010": { + "content": "<|end_message|>", + "single_word": false, + "lstrip": false, + "rstrip": false, + "normalized": false, + "special": true + }, + "200011": { + "content": "<|unused_200011|>", + "single_word": false, + "lstrip": false, + "rstrip": false, + "normalized": false, + "special": true + }, + "200012": { + "content": "<|unused_200012|>", + "single_word": false, + "lstrip": false, + "rstrip": false, + "normalized": false, + "special": true + }, + "200013": { + "content": "<|unused_200013|>", + "single_word": false, + "lstrip": false, + "rstrip": false, + "normalized": false, + "special": true + }, + "200014": { + "content": "<|unused_200014|>", + "single_word": false, + "lstrip": false, + "rstrip": false, + "normalized": false, + "special": true + }, + "200015": { + "content": "<|unused_200015|>", + "single_word": false, + "lstrip": false, + "rstrip": false, + "normalized": false, + "special": true + }, + "200016": { + "content": "<|unused_200016|>", + "single_word": false, + "lstrip": false, + "rstrip": false, + "normalized": false, + "special": true + }, + "200017": { + "content": "<|unused_200017|>", + "single_word": false, + "lstrip": false, + "rstrip": false, + "normalized": false, + "special": true + }, + "200018": { + "content": "<|unused_200018|>", + "single_word": false, + "lstrip": false, + "rstrip": false, + "normalized": false, + "special": true + }, + "200019": { + "content": "<|unused_200019|>", + "single_word": false, + "lstrip": false, + "rstrip": false, + "normalized": false, + "special": true + }, + "200020": { + "content": "<|unused_200020|>", + "single_word": false, + "lstrip": false, + "rstrip": false, + "normalized": false, + "special": true + }, + "200021": { + "content": "<|unused_200021|>", + "single_word": false, + "lstrip": false, + "rstrip": false, + "normalized": false, + "special": true + }, + "200022": { + "content": "<|content_tool_error|>", + "single_word": false, + "lstrip": false, + "rstrip": false, + "normalized": false, + "special": true + }, + "200023": { + "content": "<|unused_200023|>", + "single_word": false, + "lstrip": false, + "rstrip": false, + "normalized": false, + "special": true + }, + "200024": { + "content": "<|content_xml|>", + "single_word": false, + "lstrip": false, + "rstrip": false, + "normalized": false, + "special": true + }, + "200025": { + "content": "<|unused_200025|>", + "single_word": false, + "lstrip": false, + "rstrip": false, + "normalized": false, + "special": true + }, + "200026": { + "content": "<|unused_200026|>", + "single_word": false, + "lstrip": false, + "rstrip": false, + "normalized": false, + "special": true + }, + "200027": { + "content": "<|unused_200027|>", + "single_word": false, + "lstrip": false, + "rstrip": false, + "normalized": false, + "special": true + }, + "200028": { + "content": "<|begin_of_text|>", + "single_word": false, + "lstrip": false, + "rstrip": false, + "normalized": false, + "special": true + }, + "200029": { + "content": "<|unused_200029|>", + "single_word": false, + "lstrip": false, + "rstrip": false, + "normalized": false, + "special": true + }, + "200030": { + "content": "<|unused_200030|>", + "single_word": false, + "lstrip": false, + "rstrip": false, + "normalized": false, + "special": true + }, + "200031": { + "content": "<|unused_200031|>", + "single_word": false, + "lstrip": false, + "rstrip": false, + "normalized": false, + "special": true + }, + "200032": { + "content": "<|unused_200032|>", + "single_word": false, + "lstrip": false, + "rstrip": false, + "normalized": false, + "special": true + }, + "200033": { + "content": "<|unused_200033|>", + "single_word": false, + "lstrip": false, + "rstrip": false, + "normalized": false, + "special": true + }, + "200034": { + "content": "<|unused_200034|>", + "single_word": false, + "lstrip": false, + "rstrip": false, + "normalized": false, + "special": true + }, + "200035": { + "content": "<|unused_200035|>", + "single_word": false, + "lstrip": false, + "rstrip": false, + "normalized": false, + "special": true + }, + "200036": { + "content": "<|unused_200036|>", + "single_word": false, + "lstrip": false, + "rstrip": false, + "normalized": false, + "special": true + }, + "200037": { + "content": "<|unused_200037|>", + "single_word": false, + "lstrip": false, + "rstrip": false, + "normalized": false, + "special": true + }, + "200038": { + "content": "<|unused_200038|>", + "single_word": false, + "lstrip": false, + "rstrip": false, + "normalized": false, + "special": true + }, + "200039": { + "content": "<|unused_200039|>", + "single_word": false, + "lstrip": false, + "rstrip": false, + "normalized": false, + "special": true + }, + "200040": { + "content": "<|unused_200040|>", + "single_word": false, + "lstrip": false, + "rstrip": false, + "normalized": false, + "special": true + }, + "200041": { + "content": "<|unused_200041|>", + "single_word": false, + "lstrip": false, + "rstrip": false, + "normalized": false, + "special": true + }, + "200042": { + "content": "<|unused_200042|>", + "single_word": false, + "lstrip": false, + "rstrip": false, + "normalized": false, + "special": true + }, + "200043": { + "content": "<|unused_200043|>", + "single_word": false, + "lstrip": false, + "rstrip": false, + "normalized": false, + "special": true + }, + "200044": { + "content": "<|unused_200044|>", + "single_word": false, + "lstrip": false, + "rstrip": false, + "normalized": false, + "special": true + }, + "200045": { + "content": "<|unused_200045|>", + "single_word": false, + "lstrip": false, + "rstrip": false, + "normalized": false, + "special": true + }, + "200046": { + "content": "<|unused_200046|>", + "single_word": false, + "lstrip": false, + "rstrip": false, + "normalized": false, + "special": true + }, + "200047": { + "content": "<|unused_200047|>", + "single_word": false, + "lstrip": false, + "rstrip": false, + "normalized": false, + "special": true + }, + "200048": { + "content": "<|unused_200048|>", + "single_word": false, + "lstrip": false, + "rstrip": false, + "normalized": false, + "special": true + }, + "200049": { + "content": "<|content_invoke_tool_json|>", + "single_word": false, + "lstrip": false, + "rstrip": false, + "normalized": false, + "special": true + }, + "200050": { + "content": "<|unused_200050|>", + "single_word": false, + "lstrip": false, + "rstrip": false, + "normalized": false, + "special": true + }, + "200051": { + "content": "<|unused_200051|>", + "single_word": false, + "lstrip": false, + "rstrip": false, + "normalized": false, + "special": true + }, + "200052": { + "content": "<|unused_200052|>", + "single_word": false, + "lstrip": false, + "rstrip": false, + "normalized": false, + "special": true + }, + "200053": { + "content": "<|unused_200053|>", + "single_word": false, + "lstrip": false, + "rstrip": false, + "normalized": false, + "special": true + }, + "200054": { + "content": "<|unused_200054|>", + "single_word": false, + "lstrip": false, + "rstrip": false, + "normalized": false, + "special": true + }, + "200055": { + "content": "<|unused_200055|>", + "single_word": false, + "lstrip": false, + "rstrip": false, + "normalized": false, + "special": true + }, + "200056": { + "content": "<|unused_200056|>", + "single_word": false, + "lstrip": false, + "rstrip": false, + "normalized": false, + "special": true + }, + "200057": { + "content": "<|content_invoke_tool_text|>", + "single_word": false, + "lstrip": false, + "rstrip": false, + "normalized": false, + "special": true + } + }, + "response_template": { + "defaults": { + "role": "assistant" + }, + "start_anchor_pattern": "<\\|end_message\\|>|<\\|content_model_end_sampling\\|>", + "fields": { + "reasoning_content": { + "open_pattern": "(?:<\\|message_model\\|>[^<]*)?<\\|content_thinking\\|>", + "close": "<|end_message|>", + "repeats": true, + "join": "", + "content": "text", + "content_args": { + "strip": false + } + }, + "content": { + "open_pattern": "(?:<\\|message_model\\|>[^<]*)?<\\|content_(?:text|tool_error|invoke_tool_text)\\|>", + "close": "<|end_message|>", + "repeats": true, + "join": "", + "content": "text", + "content_args": { + "strip": false + } + }, + "tool_calls": { + "open_pattern": "(?:<\\|message_model\\|>[^<]*)?<\\|content_invoke_tool_json\\|>", + "close": "<|end_message|>", + "repeats": true, + "content": "json", + "transform": { + "type": "function", + "function": { + "name": "{content.name}", + "arguments": "{content.args}" + } + } + } + } + }, + "eos_token": "<|content_model_end_sampling|>", + "pad_token": "<|endoftext|>" +} diff --git a/zig/src/families/inkling2/hip_attention.zig b/zig/src/families/inkling2/hip_attention.zig new file mode 100644 index 00000000000..091c54610a2 --- /dev/null +++ b/zig/src/families/inkling2/hip_attention.zig @@ -0,0 +1,247 @@ +//! Inkling 2's attention on HIP (zig/kernels/hip/inkling2): the launch plan's geometry and the four launches. +const std = @import("std"); +const hip = @import("hip"); + +pub const head_dim = 128; +pub const d_rel = 16; +pub const extent = 1024; +/// Keys a K/V tile holds (tile.hpp kKeys); a ring holds whole tiles. +pub const tile_keys = 64; +/// (row, head) pairs a decode block holds, one wave each (kWaves), and a prompt block's (kPromptWaves). +pub const tile_pairs = 4; +pub const prompt_pairs = 8; +/// Key chunks: a chunk is one block's keys; rows fold their chunks in order, so a row's bits never depend on its call. +pub const sliding_chunk = 256; +pub const global_chunk = 16384; +/// A global chunk's keys fold in sub-chunks of this many: small calls run each in its own block (tile.hpp kSub). +pub const global_sub = 1024; +pub const subs = global_chunk / global_sub; +/// Most rows a call splits its global chunks for. +pub const split_rows = 64; + +/// One stream's rows in a call (tile.hpp's Seg): rows row0.. at positions p0.., its caches `off` elements in. +pub const Seg = extern struct { row0: i32, n: i32, p0: i32, pad: i32 = 0, off: i64 }; +/// A decode block's (row, head) pairs: segment `seg`, pairs m0..m0+3 of it (tile.hpp's Tile). +pub const Tile = extern struct { seg: i32, m0: i32 }; + +/// A layer's cache shape: `window` 0 is a global layer; `ring` slots a key head (a multiple of 64). +pub const Layer = struct { + window: u32, + ring: u32, + chunk: u32, + tau: bool, + + pub fn sliding(window: u32, rows: u32) Layer { + return .{ .window = window, .ring = ringFor(window, rows), .chunk = sliding_chunk, .tau = false }; + } + + /// The engine keeps a global layer's positions inside its ring; the contract's 4,096-slot ring wraps on purpose. + pub fn global(capacity: u32) Layer { + return .{ .window = 0, .ring = @intCast(std.mem.alignForward(usize, capacity, tile_keys)), .chunk = global_chunk, .tau = true }; + } + + /// Bytes of one stream's K (or V) cache with `kv` key heads: [kv][ring][128] bf16, as #4125's and #4387's. + pub fn cacheBytes(l: Layer, kv: usize) usize { + return @as(usize, l.ring) * kv * head_dim * 2; + } +}; + +/// A layer's caches (addresses): K and V rows. +pub const Cache = struct { k: u64, v: u64 }; + +/// Sliding ring slots: the window plus a call's rows less one, so a chunk never overwrites keys it still reads. +pub fn ringFor(window: u32, rows: u32) u32 { + return @intCast(std.mem.alignForward(usize, @as(usize, window) + rows - 1, tile_keys)); +} + +/// The decode tiles of a call's segments, `group` query heads a key head; returns how many were written. +pub fn tiles(segs: []const Seg, group: u32, out: []Tile) error{TooManyTiles}!usize { + var n: usize = 0; + for (segs, 0..) |s, i| { + var m: usize = 0; + while (m < @as(usize, @intCast(s.n)) * group) : (m += tile_pairs) { + if (n == out.len) return error.TooManyTiles; + out[n] = .{ .seg = @intCast(i), .m0 = @intCast(m) }; + n += 1; + } + } + return n; +} + +/// Tiles of `rows` rows in one segment; a call's total is at most the sum over its segments. +pub fn tileCount(rows: usize, group: u32) usize { + return std.math.divCeil(usize, rows * group, tile_pairs) catch unreachable; +} + +/// Chunks a call addresses: up to its last position's. +pub fn chunks(last_pos: usize, chunk: u32) u32 { + return @intCast(last_pos / chunk + 1); +} + +/// Scratch bytes of a call: the bias table (bf16) and the partials (fp32 sums plus each chunk's max and total). +pub fn tableBytes(rows: usize, heads: u32) usize { + return rows * heads * extent * 2; +} + +pub fn partialBytes(rows: usize, heads: u32, n_chunks: u32) usize { + return rows * heads * n_chunks * (head_dim * 4 + 8); +} + +/// The inkling2 image's launches (hip.kernels.Group.inkling2). +pub const Kernels = struct { + mod: hip.Module, + prep: hip.Function, + rel_table: hip.Function, + attn: hip.Function, + attn_fold: hip.Function, + attn_prompt: hip.Function, + merge: hip.Function, + + pub fn load(r: *const hip.Runtime, image: []align(8) const u8) !Kernels { + if (image.len == 0) return error.BuiltWithoutKernels; + var mod = try hip.Module.load(r, image); + errdefer mod.unload(); + return .{ + .mod = mod, + .prep = try mod.function("tf_ink2_prep"), + .rel_table = try mod.function("tf_ink2_rel_table"), + .attn = try mod.function("tf_ink2_attn"), + .attn_fold = try mod.function("tf_ink2_attn_fold"), + .attn_prompt = try mod.function("tf_ink2_attn_prompt"), + .merge = try mod.function("tf_ink2_merge"), + }; + } + + pub fn unload(k: *Kernels) void { + k.mod.unload(); + k.* = undefined; + } +}; + +/// The constants tf_ink2_prep takes from config.json (Mini: qk 22.63, rel 8, floor 8,192, alpha 0.1). +pub const Prep = struct { qk_clip: f32, rel_clip: f32, floor: f32, alpha: f32, eps: f32 }; + +/// The rows' device inputs and outputs (addresses); row arrays are `rows` long, the caches the layer's. +pub const Rows = struct { + rows: u32, + heads: u32, + kv_heads: u32, + pos: u64, + seg_of: u64, + segs: u64, + tiles: u64, + n_tiles: u32, + last_pos: u32, // the call's latest row position (a global layer's chunks run to it) + streams: u32, // segments in `segs`, stated by every caller: only one stream's rows take the prompt kernel +}; + +fn int(x: anytype) c_int { + return @intCast(x); +} + +fn go(f: hip.Function, s: hip.Stream, grid: hip.launch.Dim3, threads: u32, a: *hip.launch.Args) !void { + try hip.launch.launch(f, .{ .grid = grid, .block = .{ .x = threads } }, s, a); +} + +fn addAll(a: *hip.launch.Args, values: anytype) !void { + inline for (values) |v| try a.add(v); +} + +/// q, rel (per head) and k, v (per key head, written at slot pos % ring of the row's segment) from the projections. +pub fn prep(k: *const Kernels, s: hip.Stream, r: Rows, l: Layer, c: Prep, raw: [4]u64, scales: [2]u64, q: u64, rel: u64, kv: Cache) !void { + var a: hip.launch.Args = .{}; + for (raw) |v| try a.add(v); + for (scales) |v| try a.add(v); + for ([_]u64{ r.pos, r.seg_of, r.segs, q, rel, kv.k, kv.v }) |v| try a.add(v); + try addAll(&a, .{ int(r.heads), int(r.kv_heads), int(l.ring), int(@intFromBool(l.tau)) }); + try addAll(&a, .{ c.qk_clip, c.rel_clip, c.floor, c.alpha, c.eps }); + try go(k.prep, s, .{ .x = r.rows, .y = r.heads + 2 * r.kv_heads }, 32, &a); +} + +/// The bias table of each (row, head): its rel vector against the layer's rel_logits_proj [16][1024]. +pub fn relTable(k: *const Kernels, s: hip.Stream, r: Rows, rel: u64, proj: u64, tab: u64) !void { + var a: hip.launch.Args = .{}; + try addAll(&a, .{ rel, proj, tab }); + try go(k.rel_table, s, .{ .x = r.rows * r.heads }, 256, &a); +} + +/// Chunk partials (`slots` of 520 bytes held), then the ordered merge; sink and gate RAW (no glue sigmoid: #4387). +pub fn attend(k: *const Kernels, s: hip.Stream, r: Rows, l: Layer, stride: u32, slots: usize, q: u64, kv: Cache, tab: u64, part_o: u64, part_ml: u64, sink: u64, gate: u64, out: u64) !void { + try ringFits(l, r.rows); + if (r.streams == 0) return error.Inkling2Streams; + if (slotsFor(l, r.last_pos + 1) > stride) return error.Inkling2Partials; + if (slots < @as(usize, r.rows) * r.heads * stride) return error.Inkling2PartialRoom; + const scale: f32 = 1.0 / @sqrt(@as(f32, head_dim)); + const threads = tile_pairs * 32; + var a: hip.launch.Args = .{}; + for ([_]u64{ q, kv.k, kv.v, tab, r.segs }) |v| try a.add(v); + var slots_rh = stride; // partials a row and head + var per: u32 = 1; // partials a chunk: its sub-chunks' when split + if (l.window > 0) { + try addAll(&a, .{ r.tiles, part_o, part_ml }); + for ([_]u32{ r.heads, r.kv_heads, l.ring, l.window, l.chunk, 0, stride }) |v| try a.add(int(v)); + try addAll(&a, .{ scale, int(0) }); + try go(k.attn, s, .{ .x = r.n_tiles, .y = r.kv_heads, .z = tileChunks(r.heads / r.kv_heads, l) }, threads, &a); + } else if (split(r, stride, slots)) { + // every sub-chunk of `stride` chunks (past the rows return at once), so graphs replay by stride + per = subs; + slots_rh = stride * subs; + try addAll(&a, .{ r.tiles, part_o, part_ml }); + for ([_]u32{ r.heads, r.kv_heads, l.ring, 0, l.chunk, 0, slots_rh }) |v| try a.add(int(v)); + try addAll(&a, .{ scale, int(1) }); + try go(k.attn, s, .{ .x = r.n_tiles, .y = r.kv_heads, .z = slots_rh }, threads, &a); + } else if (r.streams == 1) { // one stream's rows: 8 pairs a block share each K/V tile, the fold's bits + try addAll(&a, .{ part_o, part_ml }); + for ([_]u32{ r.heads, r.kv_heads, l.ring, l.chunk, 0, stride }) |v| try a.add(int(v)); + try a.add(scale); + const blocks = std.math.divCeil(u32, r.rows * (r.heads / r.kv_heads), prompt_pairs) catch unreachable; + try go(k.attn_prompt, s, .{ .x = blocks, .y = r.kv_heads, .z = stride }, prompt_pairs * 32, &a); + } else { // a block a chunk, its sub-chunks folded in order + try addAll(&a, .{ r.tiles, part_o, part_ml }); + for ([_]u32{ r.heads, r.kv_heads, l.ring, l.chunk, 0, stride }) |v| try a.add(int(v)); + try a.add(scale); + try go(k.attn_fold, s, .{ .x = r.n_tiles, .y = r.kv_heads, .z = stride }, threads, &a); + } + var b: hip.launch.Args = .{}; + for ([_]u64{ part_o, part_ml, sink, gate, r.pos, out }) |v| try b.add(v); + for ([_]u32{ r.heads, l.window, l.chunk, 0, slots_rh, per }) |v| try b.add(int(v)); + try go(k.merge, s, .{ .x = r.rows * r.heads }, head_dim, &b); +} + +/// The ring the tiles assume: whole 64-key tiles (Stage::load never wraps one), and a window plus the rows less one. +pub fn ringFits(l: Layer, rows: u32) error{ Inkling2RingTiles, Inkling2RingShort }!void { + if (l.ring == 0 or l.ring % tile_keys != 0) return error.Inkling2RingTiles; + if (@as(u64, l.window) + rows > @as(u64, l.ring) + 1) return error.Inkling2RingShort; +} + +/// Whether a global call runs a block a sub-chunk: few rows, and partials for every row, head and sub-chunk. +pub fn split(r: Rows, stride: u32, slots: usize) bool { + return r.rows <= split_rows and @as(usize, r.rows) * r.heads * stride * subs <= slots; +} + +/// Chunks a sliding tile's keys span at most: its rows (4 pairs over `group` heads) plus the window before them. +pub fn tileChunks(group: u32, l: Layer) u32 { + return ((tile_pairs - 1) / group + l.window) / l.chunk + 2; +} + +/// Partials a (row, head) needs on a layer for positions below `context`: a sliding row's window, every global chunk. +pub fn slotsFor(l: Layer, context: usize) u32 { + if (l.window > 0) return (l.window - 1) / l.chunk + 2; + return chunks(context - 1, l.chunk); +} + +/// The key chunk block `z` of a tile reads (tile.hpp): a sliding tile counts from its first row's first key. +pub fn tileChunk(l: Layer, first_pos: usize, z: usize) usize { + return if (l.window > 0) ((first_pos + 1) -| l.window) / l.chunk + z else z; +} + +/// The partial slot chunk `c` of a row at `pos` is stored in; null outside the row's keys (stores nothing). +pub fn partialSlot(l: Layer, c: usize, pos: usize) ?usize { + const lo = if (l.window > 0) (pos + 1) -| l.window else 0; + if (c < lo / l.chunk or c > pos / l.chunk) return null; + return c - lo / l.chunk; +} + +test { + _ = @import("hip_attention_test.zig"); +} diff --git a/zig/src/families/inkling2/hip_attention_test.zig b/zig/src/families/inkling2/hip_attention_test.zig new file mode 100644 index 00000000000..582ca8f577f --- /dev/null +++ b/zig/src/families/inkling2/hip_attention_test.zig @@ -0,0 +1,172 @@ +//! Inkling 2's HIP attention plan without a GPU: tiles, chunks, partial slots and the launches a mock runtime records. +const std = @import("std"); +const hip = @import("hip"); +const k = @import("hip_attention.zig"); +const t = std.testing; + +test "inkling2 hip: tiles hold 4 pairs, cover each segment's pairs, and never span two streams" { + var out: [16]k.Tile = undefined; + const segs = [_]k.Seg{ .{ .row0 = 0, .n = 3, .p0 = 0, .off = 0 }, .{ .row0 = 3, .n = 1, .p0 = 900, .off = 1 << 20 } }; + const n = try k.tiles(&segs, 3, &out); + try t.expectEqual(@as(usize, 4), n); + try t.expectEqualSlices(k.Tile, &.{ .{ .seg = 0, .m0 = 0 }, .{ .seg = 0, .m0 = 4 }, .{ .seg = 0, .m0 = 8 }, .{ .seg = 1, .m0 = 0 } }, out[0..4]); + try t.expectError(error.TooManyTiles, k.tiles(&segs, 3, out[0..3])); + try t.expectEqual(@as(usize, 1536), k.tileCount(2048, 3)); + try t.expectEqual(@as(usize, 24), @sizeOf(k.Seg)); +} + +test "inkling2 hip: rings hold whole tiles, scratch and chunks at Mini's 1M context" { + try t.expectEqual(@as(u32, 64), k.chunks(1048575, k.global_chunk)); + try t.expectEqual(@as(usize, 24 * 64 * 520), k.partialBytes(1, 24, 64)); + try t.expectEqual(@as(usize, 100663296), k.tableBytes(2048, 24)); + const s = k.Layer.sliding(1024, 2048); + try t.expectEqual(@as(u32, 3072), s.ring); + try t.expectEqual(@as(usize, 3072 * 8 * 256), s.cacheBytes(8)); + try t.expectEqual(@as(u32, 131136), k.Layer.global(131073).ring); +} + +test "inkling2 hip: every chunk a row reads has a partial slot, and a tile's blocks reach its last row's chunk" { + const l = k.Layer.sliding(1024, 2048); + for ([_]usize{ 0, 1, 255, 256, 1023, 1024, 1025, 5000, 70001 }) |pos| { + const lo = (pos + 1) -| l.window; + for (lo / l.chunk..pos / l.chunk + 1) |c| try t.expect(k.partialSlot(l, c, pos).? < k.slotsFor(l, pos + 1)); + try t.expectEqual(@as(?usize, null), k.partialSlot(l, pos / l.chunk + 1, pos)); + // a tile from this row onward: its last pair's row sits (tile_pairs - 1) / group rows later + for ([_]u32{ 1, 3, 6 }) |group| { + const last = pos + (k.tile_pairs - 1) / group; + try t.expect(last / l.chunk < k.tileChunk(l, pos, k.tileChunks(group, l))); + } + } + const g = k.Layer.global(1 << 20); + try t.expectEqual(@as(u32, 64), k.slotsFor(g, 1 << 20)); + try t.expectEqual(@as(?usize, 63), k.partialSlot(g, 63, (1 << 20) - 1)); +} + +const Mock = struct { + var grids: [8][3]u32 = undefined; + var blocks: [8]u32 = undefined; + var which: [8]usize = undefined; + var count: usize = 0; + fn launch(f: hip.abi.Function, gx: c_uint, gy: c_uint, gz: c_uint, bx: c_uint, _: c_uint, _: c_uint, _: c_uint, _: hip.abi.Stream, _: ?[*]?*anyopaque, _: ?[*]?*anyopaque) callconv(.c) hip.abi.Result { + grids[count] = .{ gx, gy, gz }; + blocks[count] = bx; + which[count] = @intFromPtr(f); + count += 1; + return 0; + } +}; + +fn mocked(r: *const hip.Runtime) k.Kernels { + const fun = struct { + fn of(rt: *const hip.Runtime, i: usize) hip.Function { + return .{ .r = rt, .handle = @ptrFromInt(i) }; + } + }; + return .{ .mod = .{ .r = r, .handle = null }, .prep = fun.of(r, 1), .rel_table = fun.of(r, 2), .attn = fun.of(r, 3), .attn_fold = fun.of(r, 4), .attn_prompt = fun.of(r, 5), .merge = fun.of(r, 6) }; +} + +test "inkling2 hip: the dispatcher picks split, fold or prompt by rows, streams and partial room" { + var r: hip.Runtime = undefined; + r.api.hipModuleLaunchKernel = Mock.launch; + const kern = mocked(&r); + const s: hip.Stream = .{ .r = &r, .handle = @ptrFromInt(32) }; + const no: k.Cache = .{ .k = 0, .v = 0 }; + var row: k.Rows = .{ .rows = 1, .heads = 24, .kv_heads = 8, .pos = 0, .seg_of = 0, .segs = 0, .tiles = 0, .n_tiles = 1, .last_pos = 1048575, .streams = 1 }; + const g = k.Layer.global(1048576); + Mock.count = 0; + try k.prep(&kern, s, row, g, .{ .qk_clip = 22.63, .rel_clip = 8, .floor = 8192, .alpha = 0.1, .eps = 1e-6 }, .{ 0, 0, 0, 0 }, .{ 0, 0 }, 0, 0, no); + try k.relTable(&kern, s, row, 0, 0, 0); + const all = 24 * 64 * k.subs; + try k.attend(&kern, s, row, g, 64, all, 0, no, 0, 0, 0, 0, 0, 0); // split: a block a sub-chunk + try t.expectError(error.Inkling2Partials, k.attend(&kern, s, row, g, 63, all, 0, no, 0, 0, 0, 0, 0, 0)); + try t.expectEqual(@as(usize, 4), Mock.count); + try t.expectEqual([3]u32{ 1, 40, 1 }, Mock.grids[0]); + try t.expectEqual([3]u32{ 24, 1, 1 }, Mock.grids[1]); + try t.expectEqual([3]u32{ 1, 8, 64 * k.subs }, Mock.grids[2]); + try t.expectEqual([4]u32{ 32, 256, 128, 128 }, Mock.blocks[0..4].*); + try t.expectEqual([4]usize{ 1, 2, 3, 6 }, Mock.which[0..4].*); + Mock.count = 0; + try k.attend(&kern, s, row, g, 64, all - 1, 0, no, 0, 0, 0, 0, 0, 0); // one stream, no room: the prompt kernel + row.rows = 130; + row.streams = 2; + row.n_tiles = 98; + try k.attend(&kern, s, row, g, 64, 130 * 24 * 64, 0, no, 0, 0, 0, 0, 0, 0); // two streams, too many rows: the fold + try t.expectEqual([4]usize{ 5, 6, 4, 6 }, Mock.which[0..4].*); + try t.expectEqual([3]u32{ 1, 8, 64 }, Mock.grids[0]); + try t.expectEqual(@as(u32, 256), Mock.blocks[0]); + try t.expectEqual([3]u32{ 98, 8, 64 }, Mock.grids[2]); + Mock.count = 0; + const sl = k.Layer.sliding(1024, 2048); + try k.attend(&kern, s, row, sl, k.slotsFor(sl, 1), 130 * 24 * k.slotsFor(sl, 1), 0, no, 0, 0, 0, 0, 0, 0); + try t.expectEqual([3]u32{ 98, 8, 6 }, Mock.grids[0]); + try t.expectEqual(@as(usize, 3), Mock.which[0]); +} + +const ring_rows: k.Rows = .{ .rows = 4, .heads = 24, .kv_heads = 8, .pos = 0, .seg_of = 0, .segs = 0, .tiles = 0, .n_tiles = 1, .last_pos = 5000, .streams = 1 }; + +test "inkling2 hip: attend refuses a ring that is not whole 64-key tiles, and launches nothing" { + var r: hip.Runtime = undefined; + r.api.hipModuleLaunchKernel = Mock.launch; + const kern = mocked(&r); + const s: hip.Stream = .{ .r = &r, .handle = @ptrFromInt(32) }; + var g = k.Layer.global(8192); + g.ring = 8191; + Mock.count = 0; + try t.expectError(error.Inkling2RingTiles, k.attend(&kern, s, ring_rows, g, 1, 0, 0, .{ .k = 0, .v = 0 }, 0, 0, 0, 0, 0, 0)); + try t.expectEqual(@as(usize, 0), Mock.count); + g.ring = 8192; + try k.attend(&kern, s, ring_rows, g, 1, 4 * 24, 0, .{ .k = 0, .v = 0 }, 0, 0, 0, 0, 0, 0); + try t.expectEqual(@as(usize, 2), Mock.count); +} + +test "inkling2 hip: attend refuses a sliding ring shorter than the window plus the call's rows less one" { + var r: hip.Runtime = undefined; + r.api.hipModuleLaunchKernel = Mock.launch; + const kern = mocked(&r); + const s: hip.Stream = .{ .r = &r, .handle = @ptrFromInt(32) }; + var l = k.Layer.sliding(1024, 4); + try t.expectEqual(@as(u32, 1088), l.ring); + l.ring = 1024; // whole tiles, but four rows' new keys overwrite keys the first row still reads + Mock.count = 0; + try t.expectError(error.Inkling2RingShort, k.attend(&kern, s, ring_rows, l, k.slotsFor(l, 1), 0, 0, .{ .k = 0, .v = 0 }, 0, 0, 0, 0, 0, 0)); + try t.expectEqual(@as(usize, 0), Mock.count); + l.ring = 1088; + try k.attend(&kern, s, ring_rows, l, k.slotsFor(l, 1), 4 * 24 * k.slotsFor(l, 1), 0, .{ .k = 0, .v = 0 }, 0, 0, 0, 0, 0, 0); + try t.expectEqual(@as(usize, 2), Mock.count); +} + +test "inkling2 hip: a multi-stream call never takes the one-stream prompt kernel; zero streams is refused" { + var r: hip.Runtime = undefined; + r.api.hipModuleLaunchKernel = Mock.launch; + const kern = mocked(&r); + const s: hip.Stream = .{ .r = &r, .handle = @ptrFromInt(32) }; + const g = k.Layer.global(1048576); + var row: k.Rows = .{ .rows = 70, .heads = 24, .kv_heads = 8, .pos = 0, .seg_of = 0, .segs = 0, .tiles = 0, .n_tiles = 53, .last_pos = 1048575, .streams = 0 }; + const room = 70 * 24 * 64; // a partial a chunk: no room to split + Mock.count = 0; + try t.expectError(error.Inkling2Streams, k.attend(&kern, s, row, g, 64, room, 0, .{ .k = 0, .v = 0 }, 0, 0, 0, 0, 0, 0)); + try t.expectEqual(@as(usize, 0), Mock.count); + row.streams = 3; + try k.attend(&kern, s, row, g, 64, room, 0, .{ .k = 0, .v = 0 }, 0, 0, 0, 0, 0, 0); + try t.expectEqual([2]usize{ 4, 6 }, Mock.which[0..2].*); // the fold over the tiles, then the merge +} + +test "inkling2 hip: attend refuses partial buffers smaller than rows x heads x stride, before any launch" { + var r: hip.Runtime = undefined; + r.api.hipModuleLaunchKernel = Mock.launch; + const kern = mocked(&r); + const s: hip.Stream = .{ .r = &r, .handle = @ptrFromInt(32) }; + const sl = k.Layer.sliding(1024, 2048); + const stride = k.slotsFor(sl, 1); + const row: k.Rows = .{ .rows = 16, .heads = 24, .kv_heads = 8, .pos = 0, .seg_of = 0, .segs = 0, .tiles = 0, .n_tiles = 12, .last_pos = 4095, .streams = 2 }; + Mock.count = 0; + try t.expectError(error.Inkling2PartialRoom, k.attend(&kern, s, row, sl, stride, 16 * 24 * stride - 1, 0, .{ .k = 0, .v = 0 }, 0, 0, 0, 0, 0, 0)); + const g = k.Layer.global(1048576); + var one = row; + one.streams = 1; + try t.expectError(error.Inkling2PartialRoom, k.attend(&kern, s, one, g, 64, 16 * 24 * 64 - 1, 0, .{ .k = 0, .v = 0 }, 0, 0, 0, 0, 0, 0)); + try t.expectEqual(@as(usize, 0), Mock.count); + try k.attend(&kern, s, row, sl, stride, 16 * 24 * stride, 0, .{ .k = 0, .v = 0 }, 0, 0, 0, 0, 0, 0); + try k.attend(&kern, s, one, g, 64, 16 * 24 * 64, 0, .{ .k = 0, .v = 0 }, 0, 0, 0, 0, 0, 0); + try t.expectEqual([4]usize{ 3, 6, 5, 6 }, Mock.which[0..4].*); +} diff --git a/zig/src/families/inkling2/host_test.zig b/zig/src/families/inkling2/host_test.zig index 4f8b47e83b3..5caed096fef 100644 --- a/zig/src/families/inkling2/host_test.zig +++ b/zig/src/families/inkling2/host_test.zig @@ -5,6 +5,9 @@ test { _ = @import("names.zig"); _ = @import("names_test.zig"); _ = @import("plan.zig"); + _ = @import("loop.zig"); + _ = @import("loop_model.zig"); + _ = @import("loop_model_test.zig"); _ = @import("prompt.zig"); _ = @import("template_test.zig"); _ = @import("tokenizer_test.zig"); diff --git a/zig/src/families/inkling2/image.zig b/zig/src/families/inkling2/image.zig new file mode 100644 index 00000000000..9b62e00d518 --- /dev/null +++ b/zig/src/families/inkling2/image.zig @@ -0,0 +1,242 @@ +//! Inkling 2's image processor on the host: Inkling2ImageProcessor's 40-pixel patches and the tower's input tables. +const std = @import("std"); +const core = @import("core"); + +const picture = core.picture; +const b16 = core.bf16_round; + +pub const side = 40; // pixels a decoder token covers: the native 20-pixel patch, 2 x 2 merged +pub const patch = 20; +pub const merge = 2; +pub const grid = 32; // the learned position table's side +pub const patch_width = 3 * patch * patch; // a native patch's inputs: row, column, channel +pub const pairs = 32; // rotary pairs a 64-wide head: 16 by column, then 16 by row +const theta: f32 = 10000; +const pad: f32 = -1; // pixels outside the picture, on the 0-255 scale +const mean: f32 = 0.5 * 255.0; // the fused mean and std (0.5 each, rescale 1/255) as fp32 +const std_: f32 = 0.5 * 255.0; + +/// The release's placeholder: one per decoder image token, its rows replaced by the tower's. +pub const image_token: u32 = 200054; +/// The chat template's marker ahead of an image's placeholders. +pub const image_marker = "<|content_image|>"; + +/// One picture: its normalized patches ([tokens][40][40][3] fp32, the processor's pixel_values) and its grid. +pub const Prepared = struct { + pixels: []f32, + rows: u32, + cols: u32, + + pub fn tokens(p: Prepared) u32 { + return p.rows * p.cols; + } + + pub fn deinit(p: *Prepared, a: std.mem.Allocator) void { + a.free(p.pixels); + p.* = undefined; + } +}; + +/// Decoder tokens a picture of `w` x `h` pixels takes: no resize, one per 40-pixel cell of the padded grid. +pub fn tokensFor(w: usize, h: usize) usize { + return ((h + side - 1) / side) * ((w + side - 1) / side); +} + +/// PNG, JPEG or WebP bytes as the processor reads them: EXIF-oriented, alpha over its 8-pixel checkerboard. +pub fn decode(io: std.Io, a: std.mem.Allocator, bytes: []const u8, limits: picture.Limits) picture.Error!picture.Rgb { + const s = switch (picture.sniff(bytes)) { + .png => try picture.png.decodeWithLimits(a, bytes, limits), + .jpeg => try picture.jpeg.decodeWithLimits(io, a, bytes, limits), + .webp => try picture.webp.decodeWithLimits(io, a, bytes, limits), + .unknown => return error.Invalid, + }; + defer a.free(s.data); + if (s.channels != 4) return picture.finish(a, s); + // orient the alpha with the colours (finish on a 4-channel copy keeps it), then composite + const rgba = try a.alloc(u8, s.width * s.height * 4); + defer a.free(rgba); + const turned = orient4(s, rgba); + const out = try a.alloc(u8, turned.w * turned.h * 3); + for (0..turned.h) |y| for (0..turned.w) |x| { + const px = rgba[(y * turned.w + x) * 4 ..][0..4]; + const bg: u32 = if ((y / 8 + x / 8) % 2 == 0) 204 else 153; + for (out[(y * turned.w + x) * 3 ..][0..3], px[0..3]) |*c, v| c.* = over(v, px[3], bg); + }; + return .{ .width = turned.w, .height = turned.h, .pixels = out }; +} + +/// The processor's composite: (c * alpha + bg * (255 - alpha) + 127) // 255 in integers. +pub fn over(c: u8, alpha: u8, bg: u32) u8 { + return @intCast((@as(u32, c) * alpha + bg * (255 - alpha) + 127) / 255); +} + +/// picture.finish's transpose of 4-channel samples into `out`. +fn orient4(s: picture.Samples, out: []u8) struct { w: usize, h: usize } { + const o = if (s.orientation >= 2 and s.orientation <= 8) s.orientation else 1; + const w, const h = if (o >= 5) .{ s.height, s.width } else .{ s.width, s.height }; + for (0..h) |y| for (0..w) |x| { + const sx, const sy = switch (o) { + 2 => .{ s.width - 1 - x, y }, + 3 => .{ s.width - 1 - x, s.height - 1 - y }, + 4 => .{ x, s.height - 1 - y }, + 5 => .{ y, x }, + 6 => .{ y, s.height - 1 - x }, + 7 => .{ s.width - 1 - y, s.height - 1 - x }, + 8 => .{ s.width - 1 - y, x }, + else => .{ x, y }, + }; + @memcpy(out[(y * w + x) * 4 ..][0..4], s.data[(sy * s.width + sx) * 4 ..][0..4]); + }; + return .{ .w = w, .h = h }; +} + +/// RGB rows to the processor's pixel_values: padded with -1 to the 40-pixel grid, (v - 127.5) / 127.5 in fp32. +pub fn patches(a: std.mem.Allocator, img: picture.Rgb) !Prepared { + const rows: u32 = @intCast((img.height + side - 1) / side); + const cols: u32 = @intCast((img.width + side - 1) / side); + const px = try a.alloc(f32, @as(usize, rows) * cols * side * side * 3); + for (0..rows) |r| for (0..cols) |c| for (0..side) |y| for (0..side) |x| { + const iy = r * side + y; + const ix = c * side + x; + const at = ((((r * cols + c) * side + y) * side) + x) * 3; + for (0..3) |ch| { + const v: f32 = if (iy < img.height and ix < img.width) @floatFromInt(img.pixels[(iy * img.width + ix) * 3 + ch]) else pad; + px[at + ch] = (v - mean) / std_; + } + }; + return .{ .pixels = px, .rows = rows, .cols = cols }; +} + +/// Bytes to patches: decode, then patches; refuses pictures over `max_tokens`. +pub fn prepare(io: std.Io, a: std.mem.Allocator, bytes: []const u8, max_tokens: u32) !Prepared { + var img = try decode(io, a, bytes, .{}); + defer img.deinit(a); + if (tokensFor(img.width, img.height) > max_tokens) return error.ImageTooLarge; + return patches(a, img); +} + +/// The words for a refusal of prepare's own. +pub fn explain(err: anyerror) ?[]const u8 { + return switch (err) { + error.ImageTooLarge => "image too large for the tower's limit (one token per 40 x 40 pixels, no resize)", + error.Invalid => picture.problem(error.Invalid), + error.Oversized => picture.problem(error.Oversized), + error.Animated => picture.problem(error.Animated), + else => picture.decoderProblem(err), + }; +} + +/// Native patches a picture holds: 4 a token, in merge order (token raster, then the 2 x 2 block raster). +pub fn patchCount(p: Prepared) usize { + return @as(usize, p.tokens()) * merge * merge; +} + +/// A merge-order patch's (row, column) on the native patch grid. +pub fn place(i: usize, cols: u32) [2]usize { + const t = i / (merge * merge); + const in = i % (merge * merge); + return .{ t / cols * merge + in / merge, t % cols * merge + in % merge }; +} + +/// The patch embedding's input rows as bf16 bits: [patches][row][column][channel] (the tower's reshape). +pub fn patchRows(p: Prepared, out: []u16) void { + for (0..patchCount(p)) |i| { + const t = i / (merge * merge); + const my = i % (merge * merge) / merge; + const mx = i % merge; + for (0..patch) |y| for (0..patch) |x| for (0..3) |ch| { + const v = p.pixels[((t * side + my * patch + y) * side + mx * patch + x) * 3 + ch]; + out[i * patch_width + (y * patch + x) * 3 + ch] = b16.bits(v); + }; + } +} + +/// One axis's two bilinear taps and weights (torch's align_corners=False interpolation, edge taps clamped). +const Taps = struct { t: [2]u32, w: [2]f32 }; + +fn axis(index: usize, size: usize) Taps { + const src = (@as(f32, @floatFromInt(index)) + 0.5) * @as(f32, grid) / @as(f32, @floatFromInt(size)) - 0.5; + const fl = @floor(src); + var out: Taps = undefined; + for (0..2) |o| { + const raw = @as(i64, @intFromFloat(fl)) + @as(i64, @intCast(o)); + out.t[o] = @intCast(std.math.clamp(raw, 0, grid - 1)); + out.w[o] = @max(1 - @abs(src - fl - @as(f32, @floatFromInt(o))), 0); + } + return out; +} + +/// Each patch's four position-table rows and fp32 weights (h0 w0, h0 w1, h1 w0, h1 w1), as the tower resamples. +pub fn positionTaps(p: Prepared, taps: []u32, weights: []f32) void { + const H = @as(usize, p.rows) * merge; + const W = @as(usize, p.cols) * merge; + for (0..patchCount(p)) |i| { + const rc = place(i, p.cols); + const h = axis(rc[0], H); + const w = axis(rc[1], W); + for (0..2) |a| for (0..2) |b| { + taps[i * 4 + a * 2 + b] = h.t[a] * grid + w.t[b]; + weights[i * 4 + a * 2 + b] = h.w[a] * w.w[b]; + }; + } +} + +/// Rotary cos and sin a sequence row ([rows][32] fp32): row 0 the class token at (0, 0), patch i at its place + 1. +pub fn rotary(p: Prepared, cs: []f32, sn: []f32, on: bool) void { + var inv: [pairs / 2]f32 = undefined; + for (&inv, 0..) |*f, i| f.* = 1.0 / std.math.pow(f32, theta, @as(f32, @floatFromInt(2 * i)) / @as(f32, pairs)); + for (0..patchCount(p) + 1) |r| { + const rc: [2]usize = if (r == 0) .{ 0, 0 } else blk: { + const q = place(r - 1, p.cols); + break :blk .{ q[0] + 1, q[1] + 1 }; + }; + for (0..pairs) |j| { + const pos: f32 = @floatFromInt(if (j < pairs / 2) rc[1] else rc[0]); + const ang = pos * inv[j % (pairs / 2)]; + cs[r * pairs + j] = if (on) @cos(ang) else 1; + sn[r * pairs + j] = if (on) @sin(ang) else 0; + } + } +} + +test "tokens: one per 40-pixel cell, padded up" { + try std.testing.expectEqual(@as(usize, 15), tokensFor(200, 120)); + try std.testing.expectEqual(@as(usize, 117), tokensFor(333, 517)); + try std.testing.expectEqual(@as(usize, 2), tokensFor(37, 45)); +} + +test "checkerboard composite as the processor rounds it" { + try std.testing.expectEqual(@as(u8, 10), over(10, 255, 204)); + try std.testing.expectEqual(@as(u8, 204), over(10, 0, 204)); + try std.testing.expectEqual(@as(u8, (100 * 128 + 153 * 127 + 127) / 255), over(100, 128, 153)); +} + +test "merge order and bilinear taps against torch's interpolation formula" { + try std.testing.expectEqual([2]usize{ 0, 1 }, place(1, 5)); + try std.testing.expectEqual([2]usize{ 1, 0 }, place(2, 5)); + try std.testing.expectEqual([2]usize{ 0, 2 }, place(4, 5)); + try std.testing.expectEqual([2]usize{ 2, 0 }, place(20, 5)); + // a 6-patch axis on the 32 grid: src = (i + 0.5) * 32 / 6 - 0.5 + const a0 = axis(0, 6); + try std.testing.expectEqual([2]u32{ 2, 3 }, a0.t); + try std.testing.expectApproxEqAbs(@as(f32, 0.8333333), a0.w[0], 1e-6); + const e = axis(0, 64); // src -0.25: floor -1 clamped to 0 twice, weights 0.25 and 0.75 + try std.testing.expectEqual([2]u32{ 0, 0 }, e.t); + try std.testing.expectEqual([2]f32{ 0.25, 0.75 }, e.w); +} + +test "patches: padding reads -1 on the 0-255 scale, the patch rows reorder by 20-pixel blocks" { + const a = std.testing.allocator; + var px: [41 * 3]u8 = @splat(0); + px[40 * 3] = 255; + var p = try patches(a, .{ .width = 41, .height = 1, .pixels = &px }); + defer p.deinit(a); + try std.testing.expectEqual(@as(u32, 2), p.cols); + try std.testing.expectEqual(@as(f32, -1), p.pixels[0]); + try std.testing.expectEqual(@as(f32, (-1 - 127.5) / 127.5), p.pixels[3 * side]); + try std.testing.expectEqual(@as(f32, 1), p.pixels[side * side * 3]); + const rows = try a.alloc(u16, patchCount(p) * patch_width); + defer a.free(rows); + patchRows(p, rows); + try std.testing.expectEqual(b16.bits(1), rows[4 * patch_width]); // token 1's first patch, pixel (0, 0) +} diff --git a/zig/src/families/inkling2/inkling2.zig b/zig/src/families/inkling2/inkling2.zig index 556bca61b13..f311dc17d35 100644 --- a/zig/src/families/inkling2/inkling2.zig +++ b/zig/src/families/inkling2/inkling2.zig @@ -1,12 +1,28 @@ //! Inkling 2 Small (model_type inkling2) on CUDA: config, chat, reply split, admission, kernels, EXL3 weights, forward. +pub const image = @import("image.zig"); +pub const vision = @import("vision.zig"); pub const kernels = @import("kernels.zig"); pub const ops = @import("ops.zig"); +pub const experts = @import("experts.zig"); +pub const modelopt = @import("modelopt.zig"); +pub const loop = @import("loop.zig"); +pub const loop_model = @import("loop_model.zig"); +pub const loop_math_cuda = @import("loop_math_cuda.zig"); +pub const native = @import("cuda_native.zig"); /// config.json's name in the release. pub const model_type = "inkling2"; test { + _ = image; + _ = vision; _ = kernels; _ = ops; + _ = experts; + _ = modelopt; + _ = native; + _ = loop; + _ = loop_model; + _ = loop_math_cuda; } diff --git a/zig/src/families/inkling2/loop.zig b/zig/src/families/inkling2/loop.zig new file mode 100644 index 00000000000..a7a12d62c4d --- /dev/null +++ b/zig/src/families/inkling2/loop.zig @@ -0,0 +1,168 @@ +//! Inkling 2 Mini's loop host layout: 48 private visit caches, whole-state snapshots and one-rank admission. +const std = @import("std"); +const config = @import("config.zig"); +const plan_ = @import("plan.zig"); + +pub fn validateLoad(c: *const config.Config, rank: usize, images: bool) !void { + if (rank != 1) return error.Inkling2LoopOneRankOnly; + if (images) return error.Inkling2LoopTextOnly; + const lp = c.text.loop orelse return error.Inkling2LoopRequired; + if (lp.gate_rank != 64) return error.UnsupportedLoopGateRank; +} + +pub const SnapshotSlot = struct { + kv_offset: u64, + kv_bytes: u64, + conv_offset: u64, + conv_bytes: u64, +}; + +/// A stream or a saved prompt owns the same complete layout: no visit shares KV or convolution state with another. +pub const CacheLayout = struct { + slots: [config.max_visits]SnapshotSlot, + n: u32, + bytes: u64, + + pub fn init(c: *const config.Text, p: *const plan_.Plan, context: u32) !CacheLayout { + if (context == 0 or context > c.max_context or p.n_visits != c.visitCount()) return error.BadLoopCache; + var out: CacheLayout = undefined; + out.n = p.n_visits; + out.bytes = 0; + const conv_values = 3 * (2 * @as(u64, c.local.kv * c.local.dim) + 2 * @as(u64, c.hidden)); + for (p.visits[0..p.n_visits], 0..) |visit, i| { + const layer = p.layers[visit.layer]; + const rows: u32 = @intCast(@min(2048, context)); + const tokens = if (layer.kind == .global) + std.mem.alignForward(u32, context, 64) + else + std.mem.alignForward(u32, c.window + rows - 1, 64); + const kv = try std.math.mul(u64, tokens, 2 * @as(u64, layer.heads.kv * layer.heads.dim * 2)); + // The recurrence rounds each site then widens its complete state to FP32 before the FMAs. + const conv = try std.math.mul(u64, conv_values, 4); + out.slots[i] = .{ .kv_offset = out.bytes, .kv_bytes = kv, .conv_offset = 0, .conv_bytes = conv }; + out.bytes = try std.math.add(u64, out.bytes, kv); + } + var conv_offset = out.bytes; + for (out.slots[0..out.n]) |*slot| { + slot.conv_offset = conv_offset; + conv_offset = try std.math.add(u64, conv_offset, slot.conv_bytes); + } + out.bytes = conv_offset; + return out; + } + + pub fn at(l: *const CacheLayout, visit: u32) SnapshotSlot { + return l.slots[visit]; + } +}; + +/// The serial lane adapter's admission rule. One request occupies one complete 48-visit stream. +pub const Admission = struct { + context: u32, + + pub fn fits(a: Admission, prompt: u32, max_tokens: u32) bool { + return prompt <= a.context and max_tokens <= a.context - prompt; + } +}; + +/// A prompt-cache save or restore copies every byte of this layout, including all four convolution recurrences. +pub fn snapshotBytes(l: *const CacheLayout) u64 { + return l.bytes; +} + +pub const Snapshot = struct { + bytes: []u8, + + pub fn save(gpa: std.mem.Allocator, state: []const u8, l: *const CacheLayout) !Snapshot { + if (state.len != l.bytes) return error.BadLoopSnapshot; + return .{ .bytes = try gpa.dupe(u8, state) }; + } + + pub fn restore(s: *const Snapshot, state: []u8, l: *const CacheLayout) !void { + if (s.bytes.len != l.bytes or state.len != l.bytes) return error.BadLoopSnapshot; + @memcpy(state, s.bytes); + } + + pub fn deinit(s: *Snapshot, gpa: std.mem.Allocator) void { + gpa.free(s.bytes); + s.* = undefined; + } +}; + +test "a saved prompt restores every visit byte and owns its copy" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + var why: config.Why = .{}; + const c = try config.parse(arena.allocator(), @import("config_test.zig").mini, &why); + var prec: [24]plan_.Precision = @splat(.nvfp4); + const p = try plan_.build(&c.text, &prec); + const layout = try CacheLayout.init(&c.text, &p, 1); + const state = try std.testing.allocator.alloc(u8, @intCast(layout.bytes)); + defer std.testing.allocator.free(state); + for (state, 0..) |*v, i| v.* = @truncate(i * 29 + 7); + var saved = try Snapshot.save(std.testing.allocator, state, &layout); + defer saved.deinit(std.testing.allocator); + @memset(state, 0xa5); + try saved.restore(state, &layout); + try std.testing.expectEqualSlices(u8, saved.bytes, state); + try std.testing.expectError(error.BadLoopSnapshot, Snapshot.save(std.testing.allocator, state[0 .. state.len - 1], &layout)); +} + +test "Mini has 48 independent KV and convolution slots and a whole-state snapshot" { + const config_test = @import("config_test.zig"); + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var why: config.Why = .{}; + const c = try config.parse(a, config_test.mini, &why); + var prec: [24]plan_.Precision = @splat(.nvfp4); + const p = try plan_.build(&c.text, &prec); + const layout = try CacheLayout.init(&c.text, &p, 1_048_576); + try std.testing.expectEqual(@as(u32, 48), layout.n); + try std.testing.expectEqual(@as(u64, 3072 * 2 * 8 * 128 * 2), layout.at(0).kv_bytes); + try std.testing.expectEqual(@as(u64, 1_048_576 * 2 * 8 * 128 * 2), layout.at(5).kv_bytes); + try std.testing.expectEqual(@as(u64, 34_866_888_704), layout.bytes); + try std.testing.expectEqual(layout.bytes, snapshotBytes(&layout)); + try std.testing.expect((Admission{ .context = 8192 }).fits(8000, 192)); + try std.testing.expectEqual(@as(u64, 79_872), layout.at(0).conv_bytes); +} + +test "Mini loop load is one-rank text-only with rank-64 gated controllers" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + var why: config.Why = .{}; + const c = try config.parse(arena.allocator(), @import("config_test.zig").mini, &why); + try validateLoad(&c, 1, false); + try std.testing.expectError(error.Inkling2LoopOneRankOnly, validateLoad(&c, 2, false)); + try std.testing.expectError(error.Inkling2LoopTextOnly, validateLoad(&c, 1, true)); +} + +test "pass two resets and only completed passes with a successor capture message banks" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + var why: config.Why = .{}; + const c = try config.parse(arena.allocator(), @import("config_test.zig").mini, &why); + var prec: [24]plan_.Precision = @splat(.nvfp4); + const p = try plan_.build(&c.text, &prec); + const lp = c.text.loop.?; + var banks: u32 = 0; + for (p.visits[0..p.n_visits]) |visit| { + if (visit.pass == 2 and visit.layer == lp.core_start) try std.testing.expect(visit.hasMessages()); + if (visit.pass > 0 and visit.pass < lp.passes and visit.layer + 1 == lp.core_end) banks += 1; + } + try std.testing.expectEqual(lp.passes - 1, banks); +} + +test "pass snapshots and rollback layout cover every visit" { + const config_test = @import("config_test.zig"); + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + var why: config.Why = .{}; + const c = try config.parse(arena.allocator(), config_test.mini, &why); + var precisions: [24]plan_.Precision = @splat(.nvfp4); + const p = try plan_.build(&c.text, &precisions); + const layout = try CacheLayout.init(&c.text, &p, 4096); + try std.testing.expectEqual(@as(u32, 48), layout.n); + try std.testing.expect(layout.at(17).kv_offset != layout.at(29).kv_offset); + try std.testing.expectEqual(@as(u64, layout.at(46).conv_offset + layout.at(46).conv_bytes), layout.at(47).conv_offset); +} diff --git a/zig/src/families/inkling2/loop_backend.zig b/zig/src/families/inkling2/loop_backend.zig new file mode 100644 index 00000000000..4834266e850 --- /dev/null +++ b/zig/src/families/inkling2/loop_backend.zig @@ -0,0 +1,346 @@ +//! Inkling 2 Mini lane execution and snapshot adapter. +const std = @import("std"); +const cuda = @import("cuda"); +const lanes = @import("lanes"); +const engine = @import("loop_engine.zig"); +const ops = @import("ops.zig"); + +const Model = engine.Model; +const Kernels = engine.Kernels; +const prompt_rows = engine.prompt_rows; +const window_rows = engine.window_rows; +const token_ring = 1024; + +const Lane = struct { + len: usize = 0, + fill: ?usize = null, + base: usize = 0, + rows: std.ArrayList(u32) = .empty, + last: u64, + rule: u64, + sampled: bool = false, +}; + +/// The bytes a slot's lane buffers ask for: a vocabulary row of last logits and a sampling rule. +pub fn laneAllocs(vocab: u32) [2]usize { + return .{ @as(usize, vocab) * 4, @sizeOf(cuda.sample.Rule) }; +} + +/// The device bytes each served stream holds: its model slot (engine.slotAllocs) and its lane buffers. +pub fn streamBytes(m: *const Model) u64 { + const slot = engine.slotAllocs(&m.layout, m.w.p.n_visits); + const lane = laneAllocs(m.w.c.text.unpadded_vocab); + return slot[0] + slot[1] + lane[0] + lane[1]; +} + +pub const Backend = struct { + gpa: std.mem.Allocator, + d: *const cuda.Driver, + m: *Model, + k: *const Kernels, + s: cuda.Stream, + lanes_: [engine.max_slots]?Lane = @splat(null), + streams: [engine.max_slots]?*lanes.Stream = @splat(null), // the stream each model slot holds + tokens: cuda.DeviceBuffer, + logits16: cuda.DeviceBuffer, + meta: cuda.DeviceBuffer, + slot: [engine.max_slots][2]cuda.DeviceBuffer = undefined, // each slot's last prompt logits and sampling rule + next: u64 = 0, + held: usize = 0, // slots with buffers + + const be = lanes.backend; + + pub fn init(gpa: std.mem.Allocator, d: *const cuda.Driver, m: *Model, k: *const Kernels, s: cuda.Stream) !Backend { + const v = m.w.c.text.unpadded_vocab; + var tokens = try cuda.DeviceBuffer.alloc(d, (token_ring + window_rows) * 4); + errdefer tokens.free(); + var logits16 = try cuda.DeviceBuffer.alloc(d, window_rows * v * 2); + errdefer logits16.free(); + var meta = try cuda.DeviceBuffer.alloc(d, 16); + errdefer meta.free(); + var b: Backend = .{ .gpa = gpa, .d = d, .m = m, .k = k, .s = s, .tokens = tokens, .logits16 = logits16, .meta = meta }; + try b.slotBuffers(m.n_slots); + return b; + } + + /// Each model slot's own last-logits and rule buffers, up to `n`. + pub fn slotBuffers(b: *Backend, n: usize) !void { + const sizes = laneAllocs(b.m.w.c.text.unpadded_vocab); + for (0..n) |i| { + if (i < b.held) continue; + var last = try cuda.DeviceBuffer.alloc(b.d, sizes[0]); + errdefer last.free(); + b.slot[i] = .{ last, try cuda.DeviceBuffer.alloc(b.d, sizes[1]) }; + b.held = i + 1; + } + } + + /// The server's stream count: one model slot and its buffers per stream. + pub fn reserve(b: *Backend, streams: u32) !void { + if (streams > engine.max_slots) return error.Inkling2TooManyStreams; + try b.m.addSlots(b.s, streams); + try b.slotBuffers(streams); + } + + pub fn deinit(b: *Backend) void { + for (&b.lanes_) |*x| if (x.*) |*l| l.rows.deinit(b.gpa); + for (b.slot[0..b.held]) |*pair| for (pair) |*x| x.free(); + b.meta.free(); + b.logits16.free(); + b.tokens.free(); + b.* = undefined; + } + + pub fn backend(b: *Backend) be.Backend { + return .{ .ptr = b, .vtable = &vtable }; + } + + pub fn facts(_: *const Backend) lanes.Model { + return .{ .exact_width = window_rows, .gpu_tokens = false, .mtp = false, .speculate = false, .hidden_rows = true, .batch_rows = prompt_rows, .max_streams = 1, .streams_exact = true }; + } + + pub fn admits(b: *const Backend, prompt: usize, max_new: usize) bool { + return b.freeSlot() != null and prompt <= b.m.context and max_new <= b.m.context - prompt; + } + + fn freeSlot(b: *const Backend) ?usize { + for (b.streams[0..@min(b.m.n_slots, b.held)], 0..) |x, i| if (x == null) return i; + return null; + } + + fn slotOf(b: *const Backend, s: *const lanes.Stream) ?usize { + for (b.streams, 0..) |x, i| if (x == s) return i; + return null; + } + + /// The device buffer holding `s`'s last prompt logits. + pub fn lastOf(b: *const Backend, s: *const lanes.Stream) !u64 { + const i = b.slotOf(s) orelse return error.UnknownStream; + return b.lanes_[i].?.last; + } + + fn self(ptr: *anyopaque) *Backend { + return @ptrCast(@alignCast(ptr)); + } + + fn upload(b: *Backend, dst: u64, bytes: []const u8) !void { + try cuda.copy_source.enqueue(b.d, dst, bytes, b.s); + } + + /// `s`'s lane, its model slot selected for the calls that follow. + fn laneOf(b: *Backend, s: *const lanes.Stream) !*Lane { + const i = b.slotOf(s) orelse return error.UnknownStream; + if (i >= b.m.n_slots) return error.UnknownStream; + b.m.slot = i; + return if (b.lanes_[i]) |*l| l else error.UnknownStream; + } + + fn resumeSaved(b: *Backend, s: *lanes.Stream) usize { + const saved = s.reuse.saved orelse return 0; + const k: *const Model.Saved = @ptrCast(@alignCast(saved)); + if (k.at != s.reuse.at or k.at == 0 or k.at >= s.prompt().len) { + s.reuse_failed = true; + return 0; + } + b.m.restore(b.s, k) catch { + s.reuse_failed = true; + return 0; + }; + s.cached = k.at; + return k.at; + } + + fn opening(b: *Backend, s: *lanes.Stream) !*Lane { + const prompt = s.prompt(); + if (prompt.len == 0) return error.EmptyPrompt; + if (prompt.len > b.m.context or s.max_new > b.m.context - prompt.len) return error.PastContext; + if (b.slotOf(s) == null) { + const i = b.freeSlot() orelse return error.NoFreeSlot; + b.lanes_[i] = .{ .last = b.slot[i][0].ptr, .rule = b.slot[i][1].ptr }; + b.streams[i] = s; + } + const l = try b.laneOf(s); + l.sampled = false; + if (cuda.sample.ruleFor(s.sampling)) |r| { + try b.upload(l.rule, std.mem.asBytes(&r)); + l.sampled = true; + } + l.len = 0; + try b.m.reset(b.s); + const at = b.resumeSaved(s); + l.len = at; + l.fill = at; + s.fill_at.store(@intCast(at), .monotonic); + return l; + } + + fn chunk(b: *Backend, s: *lanes.Stream, l: *Lane) !bool { + const prompt = s.prompt(); + const at = l.fill.?; + if (s.isCancelled()) return error.Cancelled; + var end = @min(prompt.len, (at / prompt_rows + 1) * prompt_rows); + for (s.reuse.marks) |mark| { + if (mark > at and mark < end) end = mark; + } + const done = end == prompt.len; + try b.m.forward(b.k, b.s, prompt[at..end], at, end - at - 1, @intFromBool(done), false); + if (done) try b.d.check(b.d.api.cuMemcpyDtoDAsync_v2(l.last, b.m.s.logits, b.m.w.c.text.unpadded_vocab * 4, b.s.handle), "cuMemcpyDtoDAsync"); + l.len = end; + l.fill = if (done) null else end; + s.fill_at.store(@intCast(end), .monotonic); + if (s.reuse.hook) |hook| if (std.mem.indexOfScalar(u32, s.reuse.marks, @intCast(end)) != null) + hook.at(hook.ptr, s, @intCast(end)); + return done; + } + + fn handle(b: *Backend) usize { + const h = b.next; + b.next += 1; + return @intCast(h % token_ring); + } + + fn drawRows(b: *Backend, l: *const Lane, logits: u64, rows: usize, position0: u64, at: usize) !void { + const v = b.m.w.c.text.unpadded_vocab; + if (!l.sampled) return ops.top1(&b.k.glue, b.s, logits, rows, v, v, 0, b.m.s.t + at * 4, b.tokens.ptr + at * 4); + try ops.tobf(&b.k.glue, b.s, logits, rows, v, v, b.logits16.ptr, v, 0, v); + const metadata = [4]i32{ @intCast(position0 - 1), 0, 0, 0 }; + try b.upload(b.meta.ptr, std.mem.asBytes(&metadata)); + try b.k.draws.draw(b.s, b.logits16.ptr, v, l.rule, b.meta.ptr, 0, b.tokens.ptr + at * 4, rows, null, null); + } + + fn read(ptr: *anyopaque, h: u64) anyerror!u32 { + const b = self(ptr); + if (h >= b.next or b.next - h > token_ring) return error.NoSuchToken; + var out: [1]u32 = undefined; + try b.s.synchronize(); + try b.tokens.download(@intCast((h % token_ring) * 4), std.mem.sliceAsBytes(&out)); + return out[0]; + } + + const vtable: be.Backend.VTable = .{ + .prefill = prefill, + .prefill_step = prefillStep, + .first = first, + .first_masked = firstMasked, + .queue = queue, + .read = read, + .verify = verify, + .keep = keep, + .draft = draft, + .release = release, + .reports_fill = true, + }; + + fn prefill(ptr: *anyopaque, s: *lanes.Stream) anyerror!void { + const b = self(ptr); + const l = try b.opening(s); + errdefer release(ptr, s); + while (!try b.chunk(s, l)) {} + } + + fn prefillStep(ptr: *anyopaque, s: *lanes.Stream, _: u32) anyerror!bool { + const b = self(ptr); + const going = if (b.slotOf(s)) |i| b.lanes_[i].?.fill != null else false; + const l = if (going) try b.laneOf(s) else try b.opening(s); + errdefer release(ptr, s); + return b.chunk(s, l); + } + + fn first(ptr: *anyopaque, s: *lanes.Stream, position: u64) anyerror!u64 { + const b = self(ptr); + const l = try b.laneOf(s); + if (position != l.len or l.fill != null) return error.PositionMismatch; + const h = b.next; + try b.drawRows(l, l.last, 1, position, b.handle()); + return h; + } + + fn firstMasked(_: *anyopaque, _: *lanes.Stream, _: u64, _: []const u32) anyerror!u64 { + return error.StructuresUnsupported; + } + + fn feed(b: *Backend, value: be.Feed) !u32 { + return switch (value) { + .value => |v| v, + .handle => |h| read(b, h), + }; + } + + fn queue(ptr: *anyopaque, s: *lanes.Stream, value: be.Feed, position: u64) anyerror!u64 { + const b = self(ptr); + const l = try b.laneOf(s); + const token = try b.feed(value); + if (position != l.len + 1) return error.PositionMismatch; + try b.m.forward(b.k, b.s, &.{token}, l.len, 0, 1, false); + l.len += 1; + const h = b.next; + try b.drawRows(l, b.m.s.logits, 1, position, b.handle()); + return h; + } + + fn verify(ptr: *anyopaque, windows: []const be.Window, out: []be.Verified) anyerror!void { + const b = self(ptr); + if (windows.len != 1 or out.len != 1) return error.OneStreamOnly; + const w = windows[0]; + if (w.held != 0) return error.NoHeldDrafts; + if (w.parents != null) return error.ChainsOnly; + if (w.masks.len != 0) return error.StructuresUnsupported; + const l = try b.laneOf(w.stream); + const n = w.rows(); + if (n == 0 or n > window_rows) return error.WindowTooWide; + l.base = l.len; + l.rows.clearRetainingCapacity(); + try l.rows.append(b.gpa, w.pending); + try l.rows.appendSlice(b.gpa, w.tokens); + for (w.positions, 0..) |position, i| if (position != l.base + i + 1) return error.PositionMismatch; + try b.m.forward(b.k, b.s, l.rows.items, l.base, 0, n, true); + try b.drawRows(l, b.m.s.logits, n, w.positions[0], token_ring); + var got: [window_rows]u32 = undefined; + try b.s.synchronize(); + try b.tokens.download(token_ring * 4, std.mem.sliceAsBytes(got[0..n])); + @memcpy(out[0].sampled[0..n], got[0..n]); + @memcpy(out[0].drafts[0 .. n - 1], l.rows.items[1..n]); + l.len = l.base + n; + } + + fn keep(ptr: *anyopaque, windows: []const be.Window, paths: []const []const u32) anyerror!void { + const b = self(ptr); + if (windows.len != 1 or paths.len != 1) return error.OneStreamOnly; + const l = try b.laneOf(windows[0].stream); + const path = paths[0]; + if (path.len == 0 or path.len > l.rows.items.len) return error.EmptyPath; + for (path, 0..) |row, i| if (row != i) return error.ChainsOnly; + try b.m.rewind(b.k, b.s, path.len); + l.len = l.base + path.len; + } + + fn draft(_: *anyopaque, requests: []const be.DraftRequest) anyerror!void { + for (requests) |r| if (r.depth != 0 or r.lanes != null) return error.NoDraftHead; + } + + pub fn saveState(b: *Backend, owner: ?*anyopaque, at: u32) !*Model.Saved { + const s: *const lanes.Stream = @ptrCast(@alignCast(owner orelse return error.NoOwner)); + const l = try b.laneOf(s); + if ((l.fill orelse l.len) != at) return error.NotAtMark; + return b.m.save(b.s, at); + } + + pub fn restoreState(b: *Backend, owner: ?*anyopaque, saved: *const Model.Saved) !void { + const s: *const lanes.Stream = @ptrCast(@alignCast(owner orelse return error.NoOwner)); + const l = try b.laneOf(s); + try b.m.restore(b.s, saved); + l.len = saved.at; + } + + pub fn dropState(b: *Backend, saved: *Model.Saved) void { + b.m.drop(b.s, saved); + } + + fn release(ptr: *anyopaque, s: *lanes.Stream) void { + const b = self(ptr); + const i = b.slotOf(s) orelse return; + if (b.lanes_[i]) |*l| l.rows.deinit(b.gpa); + b.lanes_[i] = null; + b.streams[i] = null; + } +}; diff --git a/zig/src/families/inkling2/loop_engine.zig b/zig/src/families/inkling2/loop_engine.zig new file mode 100644 index 00000000000..c04446872e6 --- /dev/null +++ b/zig/src/families/inkling2/loop_engine.zig @@ -0,0 +1,591 @@ +//! One-rank, text-only Inkling 2 Mini: the complete 48-visit CUDA forward. +const std = @import("std"); +const cuda = @import("cuda"); +const config = @import("config.zig"); +const loop = @import("loop.zig"); +const weights_ = @import("loop_weights.zig"); +const ops = @import("ops.zig"); +const attention = @import("kernels.zig"); +const modelopt = @import("modelopt.zig"); +const loop_math = @import("loop_math_cuda.zig"); + +pub const prompt_rows: usize = 2048; +pub const window_rows: usize = 16; + +pub const Kernels = struct { + glue: ops.Kernels, + attn: attention.Kernels, + moe: modelopt.Kernels, + loop: loop_math.Kernels, + sample_mod: cuda.Module, + draws: cuda.sample.Draws, + + pub fn load(ctx: *const cuda.Context) !Kernels { + const d = ctx.d; + var glue = try ops.Kernels.load(d); + errdefer glue.unload(); + var attn = try attention.Kernels.load(d); + errdefer attn.unload(); + const sms: usize = @intCast(try ctx.attribute(.multiprocessor_count)); + var moe = try modelopt.Kernels.load(d, sms); + errdefer moe.unload(); + var lm = try loop_math.Kernels.load(d); + errdefer lm.unload(); + var sample_mod = try cuda.Module.load(d, cuda.kernels.sample); + errdefer sample_mod.unload(); + return .{ + .glue = glue, + .attn = attn, + .moe = moe, + .loop = lm, + .sample_mod = sample_mod, + .draws = try cuda.sample.Draws.resolve(sample_mod), + }; + } + + pub fn deinit(k: *Kernels) void { + k.sample_mod.unload(); + k.loop.unload(); + k.moe.unload(); + k.attn.unload(); + k.glue.unload(); + k.* = undefined; + } +}; + +const Scratch = struct { + ids: u64, + pos: u64, + seg_of: u64, + segs: u64, + tiles: u64, + blocks: [ops.max_blocks]u64 = @splat(0), + partial_a: u64, + partial_b: u64, + prelude: u64, + bank0: u64, + bank1: u64, + raw: u64, // three FP32 AR/gate rows per token + messages: u64, // four FP32 message rows per token + normalized: u64, // three BF16 rows per token + t: u64, + q_raw: u64, + rel_raw: u64, + sink: u64, + gate: u64, + k_raw: u64, + v_raw: u64, + k_conv: u64, + v_conv: u64, + k_dynamic: u64, + v_dynamic: u64, + q_prepared: u64, + rel_prepared: u64, + rel_table: u64, + part_o: u64, + part_ml: u64, + attn_heads: u64, + attn_out: u64, + route_scores: u64, + route_pick: u64, + route_weights: u64, + moe_out: u64, + moe_scratch: u64, + hidden: u64, + logits: u64, + backup: u64, + hist: u64, +}; + +/// A stream's state (every visit's K/V rows and conv states, its rewind sites); at most `max_slots`, one in use. +const Slot = struct { cache: cuda.DeviceBuffer, sites: cuda.DeviceBuffer }; +pub const max_slots = 16; + +/// The bytes a slot's allocations ask for: the cache layout and four rewind sites a visit. +pub fn slotAllocs(layout: *const loop.CacheLayout, n_visits: u32) [2]usize { + return .{ @intCast(layout.bytes), @as(usize, n_visits) * 4 * @sizeOf(ops.RewindSite) }; +} + +pub const Model = struct { + gpa: std.mem.Allocator, + d: *const cuda.Driver, + w: *const weights_.Weights, + context: usize, + layout: loop.CacheLayout, + slots: [max_slots]Slot = undefined, + n_slots: usize = 0, + slot: usize = 0, // the slot forwards, snapshots and rewinds use; forwards share the scratch + recorded: ?usize = null, // the slot whose window `backup` and `hist` hold + s: Scratch = undefined, + buffers: std.ArrayList(cuda.DeviceBuffer) = .empty, + + fn slotBase(m: *const Model) u64 { + return m.slots[m.slot].cache.ptr; + } + + /// Allocates slots until `n` exist, each with zeroed conv states and its own rewind sites. + pub fn addSlots(m: *Model, s: cuda.Stream, n: usize) !void { + if (n > max_slots) return error.TooManySlots; + const keep = m.slot; + defer m.slot = keep; + const kv: usize = @as(usize, m.w.c.text.local.kv) * m.w.c.text.local.dim; + var sites: [config.max_visits * 4]ops.RewindSite = undefined; + while (m.n_slots < n) { + var slot = try m.newSlot(); + errdefer for ([2]*cuda.DeviceBuffer{ &slot.sites, &slot.cache }) |b| b.free(); + m.slots[m.n_slots] = slot; + m.slot = m.n_slots; + for (0..m.w.p.n_visits) |v| for (0..4) |site| { + const c = if (site < 2) kv else m.w.c.text.hidden; + const hist = m.histOf(@intCast(v), site) - m.s.hist; + sites[v * 4 + site] = .{ .state = m.convOf(@intCast(v), site), .hist = @intCast(hist), .backup = @intCast(m.backupOf(@intCast(v), site)), .c = @intCast(c) }; + }; + try m.upload(s, slot.sites.ptr, std.mem.sliceAsBytes(sites[0 .. m.w.p.n_visits * 4])); + try m.reset(s); + try s.synchronize(); + m.n_slots += 1; + } + } + + /// A slot's two allocations, sized by slotAllocs: its cache and its rewind-site table. + pub fn newSlot(m: *const Model) !Slot { + const sizes = slotAllocs(&m.layout, m.w.p.n_visits); + var cache = try cuda.DeviceBuffer.alloc(m.d, sizes[0]); + errdefer cache.free(); + return .{ .cache = cache, .sites = try cuda.DeviceBuffer.alloc(m.d, sizes[1]) }; + } + + fn alloc(m: *Model, bytes: usize) !u64 { + var b = try cuda.DeviceBuffer.alloc(m.d, @max(bytes, 256)); + errdefer b.free(); + try m.buffers.append(m.gpa, b); + return b.ptr; + } + + fn upload(m: *const Model, s: cuda.Stream, dst: u64, bytes: []const u8) !void { + try cuda.copy_source.enqueue(m.d, dst, bytes, s); + } + + fn copy(m: *const Model, s: cuda.Stream, dst: u64, src: u64, bytes: usize) !void { + try m.d.check(m.d.api.cuMemcpyDtoDAsync_v2(dst, src, bytes, s.handle), "cuMemcpyDtoDAsync"); + } + + fn zeros(m: *const Model, s: cuda.Stream, ptr: u64, bytes: usize) !void { + try m.d.check(m.d.api.cuMemsetD8Async(ptr, 0, bytes, s.handle), "cuMemsetD8Async"); + } + + fn layerGeometry(m: *const Model, layer: u32) attention.Layer { + return if (config.isGlobal(layer)) + attention.Layer.global(@intCast(m.context)) + else + attention.Layer.sliding(m.w.c.text.window, @intCast(@min(prompt_rows, m.context))); + } + + fn cacheOf(m: *const Model, visit: u32) attention.Cache { + const slot = m.layout.at(visit); + const base = m.slotBase() + slot.kv_offset; + return .{ .k = base, .v = base + slot.kv_bytes / 2 }; + } + + fn convOf(m: *const Model, visit: u32, site: usize) u64 { + const c = m.w.c.text; + const kv: usize = @as(usize, c.local.kv) * c.local.dim; + const h: usize = c.hidden; + const widths = [4]usize{ kv, kv, h, h }; + var at = m.slotBase() + m.layout.at(visit).conv_offset; + for (0..site) |i| at += 3 * widths[i] * 4; + return at; + } + + fn histOf(m: *const Model, visit: u32, site: usize) u64 { + const c = m.w.c.text; + const kv: usize = @as(usize, c.local.kv) * c.local.dim; + const h: usize = c.hidden; + const widths = [4]usize{ kv, kv, h, h }; + var at = m.s.hist + visit * window_rows * (2 * kv + 2 * h) * 4; + for (0..site) |i| at += window_rows * widths[i] * 4; + return at; + } + + fn backupOf(m: *const Model, visit: u32, site: usize) usize { + return m.convOf(visit, site) - (m.slotBase() + m.layout.at(0).conv_offset); + } + + pub fn init(gpa: std.mem.Allocator, d: *const cuda.Driver, s: cuda.Stream, w: *const weights_.Weights, context: usize) !Model { + const layout = try loop.CacheLayout.init(&w.c.text, &w.p, @intCast(context)); + var m: Model = .{ + .gpa = gpa, + .d = d, + .w = w, + .context = context, + .layout = layout, + }; + errdefer m.deinitBuffers(); + const c = w.c.text; + const h: usize = c.hidden; + const q: usize = @as(usize, c.global.q) * c.global.dim; + const kv: usize = @as(usize, c.local.kv) * c.local.dim; + const rows = prompt_rows; + const rel_rows = rows * c.global.q * attention.extent; + const local = attention.Layer.sliding(c.window, @intCast(@min(prompt_rows, context))); + const global = attention.Layer.global(@intCast(context)); + const local_slots = attention.slotsFor(local, context); + const global_slots = attention.slotsFor(global, context); + const part_slots = @max(rows * c.local.q * local_slots, rows * c.global.q * global_slots); + const hist_values = @as(usize, w.p.n_visits) * (2 * kv + 2 * h) * window_rows; + m.s = .{ + .ids = try m.alloc(rows * 4), + .pos = try m.alloc(rows * 4), + .seg_of = try m.alloc(rows * 4), + .segs = try m.alloc(@sizeOf(attention.Seg)), + .tiles = try m.alloc(128 * @sizeOf(attention.Tile)), + .partial_a = try m.alloc(rows * h * 2), + .partial_b = try m.alloc(rows * h * 2), + .prelude = try m.alloc(rows * h * 2), + .bank0 = try m.alloc(rows * h * 2), + .bank1 = try m.alloc(rows * h * 2), + .raw = try m.alloc(3 * rows * h * 4), + .messages = try m.alloc(4 * rows * h * 4), + .normalized = try m.alloc(3 * rows * h * 2), + .t = try m.alloc(rows * h * 4), + .q_raw = try m.alloc(rows * q * 2), + .rel_raw = try m.alloc(rows * c.global.q * c.d_rel * 2), + .sink = try m.alloc(rows * c.global.q * 2), + .gate = try m.alloc(rows * q * 2), + .k_raw = try m.alloc(rows * kv * 2), + .v_raw = try m.alloc(rows * kv * 2), + .k_conv = try m.alloc(rows * kv * 2), + .v_conv = try m.alloc(rows * kv * 2), + .k_dynamic = try m.alloc(rows * c.global.kv * config.conv_taps * 4), + .v_dynamic = try m.alloc(rows * c.global.kv * config.conv_taps * 4), + .q_prepared = try m.alloc(rows * q * 2), + .rel_prepared = try m.alloc(rows * c.global.q * c.d_rel * 2), + .rel_table = try m.alloc(rel_rows * 2), + .part_o = try m.alloc(part_slots * attention.head_dim * 4), + .part_ml = try m.alloc(part_slots * 8), + .attn_heads = try m.alloc(rows * q * 2), + .attn_out = try m.alloc(rows * h * 2), + .route_scores = try m.alloc(rows * c.experts * 4), + .route_pick = try m.alloc(rows * c.experts * 4), + .route_weights = try m.alloc(rows * c.experts * 4), + .moe_out = try m.alloc(rows * h * 2), + .moe_scratch = try m.alloc(try modelopt.scratchBytes(rows, c.topk, h, c.expert_inter)), + .hidden = try m.alloc(rows * h * 2), + .logits = try m.alloc(window_rows * c.unpadded_vocab * 4), + .backup = try m.alloc(layout.bytes - layout.at(0).conv_offset), + .hist = try m.alloc(hist_values * 4), + }; + for (0..ops.max_blocks) |i| m.s.blocks[i] = try m.alloc(rows * h * 2); + try m.addSlots(s, 1); + return m; + } + + fn deinitBuffers(m: *Model) void { + for (m.buffers.items) |*b| b.free(); + m.buffers.deinit(m.gpa); + } + + pub fn deinit(m: *Model) void { + m.deinitBuffers(); + for (m.slots[0..m.n_slots]) |*slot| for ([2]*cuda.DeviceBuffer{ &slot.sites, &slot.cache }) |b| b.free(); + m.* = undefined; + } + + pub fn reset(m: *const Model, s: cuda.Stream) !void { + try m.zeros(s, m.slotBase() + m.layout.at(0).conv_offset, m.layout.bytes - m.layout.at(0).conv_offset); + } + + pub fn rewind(m: *const Model, k: *const Kernels, s: cuda.Stream, kept: usize) !void { + if (kept > window_rows) return error.WindowTooWide; + if (m.recorded != m.slot) return error.RewindOfAnotherSlot; + try ops.rewind(&k.glue, s, m.slots[m.slot].sites.ptr, m.w.p.n_visits * 4, m.w.c.text.hidden, m.s.backup, m.s.hist, 0, 0, kept); + } + + fn arBlocks(m: *const Model, blocks: []const u64, partial: u64, query: u64, out: u64, nq: usize, partial_bf16: bool, rows: usize) loop_math.ArArgs { + var a: loop_math.ArArgs = .{ + .partial = partial, + .query = query, + .out = out, + .n_blocks = @intCast(blocks.len), + .partial_bf16 = @intFromBool(partial_bf16), + .nq = @intCast(nq), + .rows = @intCast(rows), + .c = @intCast(m.w.c.text.hidden), + .eps = m.w.c.text.eps, + }; + for (blocks, 0..) |b, i| a.blocks[i] = b; + return a; + } + + fn mixArgs(m: *const Model, blocks: []const u64, partial: u64, query: u64, norms: [3]u64, out: u64, nq: usize, partial_bf16: bool, rows: usize) ops.MixArgs { + var a: ops.MixArgs = .{ + .partial = partial, + .query = query, + .out = out, + .n_blocks = @intCast(blocks.len), + .partial_bf16 = @intFromBool(partial_bf16), + .nq = @intCast(nq), + .rows = @intCast(rows), + .c = @intCast(m.w.c.text.hidden), + .eps = m.w.c.text.eps, + }; + for (blocks, 0..) |b, i| a.blocks[i] = b; + a.norm = norms; + return a; + } + + /// One prompt chunk or one decode window. `record` retains every convolution input for exact prefix rollback. + pub fn forward(m: *Model, k: *const Kernels, s: cuda.Stream, tokens: []const u32, p0: usize, head0: usize, heads: usize, record: bool) !void { + const c = m.w.c.text; + const rows = tokens.len; + const h: usize = c.hidden; + if (rows == 0 or rows > prompt_rows or p0 + rows > m.context or (!record and heads > window_rows) or head0 + heads > rows) + return error.BadLoopRows; + if (record and rows > window_rows) return error.WindowTooWide; + var ids: [prompt_rows]i32 = undefined; + var pos: [prompt_rows]i32 = undefined; + var seg_of: [prompt_rows]i32 = @splat(0); + for (tokens, 0..) |token, i| { + ids[i] = @intCast(token); + pos[i] = @intCast(p0 + i); + } + try m.upload(s, m.s.ids, std.mem.sliceAsBytes(ids[0..rows])); + try m.upload(s, m.s.pos, std.mem.sliceAsBytes(pos[0..rows])); + try m.upload(s, m.s.seg_of, std.mem.sliceAsBytes(seg_of[0..rows])); + const seg: attention.Seg = .{ .row0 = 0, .n = @intCast(rows), .p0 = @intCast(p0), .off = 0 }; + try m.upload(s, m.s.segs, std.mem.asBytes(&seg)); + m.recorded = if (record) m.slot else null; + if (record) try m.copy(s, m.s.backup, m.slotBase() + m.layout.at(0).conv_offset, m.layout.bytes - m.layout.at(0).conv_offset); + + try ops.embed(&k.glue, s, m.s.ids, rows, m.w.embed, m.w.embed_norm, m.s.partial_a, h, c.eps); + var partial = m.s.partial_a; + var next = m.s.partial_b; + var n_blocks: usize = 0; + const lp = c.loop.?; + + for (m.w.p.visits[0..m.w.p.n_visits]) |visit| { + const layer = m.w.p.at(visit.layer); + const lw = &m.w.layers[visit.layer]; + if (visit.pass >= 2 and visit.layer == lp.core_start) { + try m.copy(s, partial, m.s.prelude, rows * h * 2); + n_blocks = 1; // block zero is the embedding; later passes never inherit completed blocks + } + const messages = visit.hasMessages(); + if (messages) { + const core_j = visit.layer - lp.core_start; + try loop_math.messages(&k.loop, s, m.s.bank0, m.s.bank1, m.w.cross_qm + 2 * core_j * h * 4, m.w.cross_kv + 2 * core_j * h * 4, m.s.messages, rows, 1, h, c.eps); + } + const nq: usize = if (layer.kind == .global) 3 else 1; + const query = m.w.attn_queries[visit.layer]; + const blocks = m.s.blocks[0..n_blocks]; + const raw_stride = rows * h * 4; + const norm_stride = rows * h * 2; + if (messages) { + if (nq == 3) { + try loop_math.ar(&k.loop, s, m.arBlocks(blocks, partial, query, m.s.raw, 3, true, rows)); + } else { + // A sliding layer stores one query; each gated role gets its own AR result from that query. + for (0..3) |role| try loop_math.ar(&k.loop, s, m.arBlocks(blocks, partial, query, m.s.raw + role * raw_stride, 1, true, rows)); + } + for (0..3) |role| { + const ctl = lw.controllers[role]; + try loop_math.gate(&k.loop, s, m.s.raw + role * raw_stride, m.s.messages + role * raw_stride, ctl.down, ctl.forget, ctl.gain, m.s.raw + role * raw_stride, rows, h, c.eps); + const norms = [3]u64{ lw.attn.norms[role], lw.attn.norms[role], lw.attn.norms[role] }; + try ops.mix(&k.glue, s, m.mixArgs(&.{}, m.s.raw + role * raw_stride, 0, norms, m.s.normalized + role * norm_stride, 1, false, rows)); + } + } else { + try ops.mix(&k.glue, s, m.mixArgs(blocks, partial, query, lw.attn.norms, m.s.normalized, nq, true, rows)); + } + const u_q = m.s.normalized; + const u_k = if (layer.kind == .global or messages) m.s.normalized + norm_stride else u_q; + const u_v = if (layer.kind == .global or messages) m.s.normalized + 2 * norm_stride else u_q; + const q_width: usize = @as(usize, layer.heads.q) * layer.heads.dim; + const kv_width: usize = @as(usize, layer.heads.kv) * layer.heads.dim; + try loop_math.projectQkv(&k.loop, s, u_q, u_k, u_v, lw.attn.wq, lw.attn.wk, lw.attn.wv, m.s.q_raw, m.s.k_raw, m.s.v_raw, rows, h, q_width, kv_width); + try ops.rowdot(&k.glue, s, u_q, lw.attn.wr, m.s.rel_raw, rows, layer.heads.q * c.d_rel, h, true, false); + try ops.rowdot(&k.glue, s, u_q, lw.attn.gate, m.s.gate, rows, q_width, h, true, false); + try ops.rowdot(&k.glue, s, u_q, lw.attn.sink, m.s.sink, rows, layer.heads.q, h, true, false); + + const geometry = m.layerGeometry(visit.layer); + const cache = m.cacheOf(visit.cache_slot); + const dynamic = layer.kind == .global; + for (0..2) |kind| { + const input = if (kind == 0) u_k else u_v; + const dyn_out = if (kind == 0) m.s.k_dynamic else m.s.v_dynamic; + if (dynamic) { + try ops.rowdot(&k.glue, s, input, if (kind == 0) lw.attn.k_dynamic else lw.attn.v_dynamic, dyn_out, rows, layer.heads.kv * config.conv_taps, h, false, false); + try loop_math.roundBf16(&k.loop, s, dyn_out, dyn_out, rows * layer.heads.kv * config.conv_taps); + } + try ops.conv(&k.glue, s, .{ + .x = if (kind == 0) m.s.k_raw else m.s.v_raw, + .state = m.convOf(visit.cache_slot, kind), + .w = if (kind == 0) lw.attn.k_conv else lw.attn.v_conv, + .dyn = if (dynamic) dyn_out else 0, + .out = if (kind == 0) m.s.k_conv else m.s.v_conv, + .hist = if (record) m.histOf(visit.cache_slot, kind) else 0, + .x_bf16 = 1, + .heads = @intCast(layer.heads.kv), + .c = @intCast(kv_width), + .rows = @intCast(rows), + .mode = 0, + }, 1); + } + var tiles: [128]attention.Tile = undefined; + const n_tiles = try attention.tiles(&.{seg}, layer.heads.q / layer.heads.kv, &tiles); + try m.upload(s, m.s.tiles, std.mem.sliceAsBytes(tiles[0..n_tiles])); + const stride = attention.slotsFor(geometry, m.context); + const part_capacity = prompt_rows * layer.heads.q * stride; + const r: attention.Rows = .{ + .rows = @intCast(rows), + .heads = layer.heads.q, + .kv_heads = layer.heads.kv, + .pos = m.s.pos, + .seg_of = m.s.seg_of, + .segs = m.s.segs, + .tiles = m.s.tiles, + .n_tiles = @intCast(n_tiles), + .last_pos = @intCast(p0 + rows - 1), + }; + const prep: attention.Prep = .{ .qk_clip = c.qk_clip, .rel_clip = c.rel_clip, .floor = @floatFromInt(c.log_floor), .alpha = c.log_alpha, .eps = c.eps }; + try attention.prep(&k.attn, s, r, geometry, prep, .{ m.s.q_raw, m.s.k_conv, m.s.v_conv, m.s.rel_raw }, .{ lw.attn.q_scale, lw.attn.rel_scale }, m.s.q_prepared, m.s.rel_prepared, cache); + try attention.relTable(&k.attn, s, r, m.s.rel_prepared, lw.attn.rel_proj, m.s.rel_table); + try attention.attend(&k.attn, s, r, geometry, stride, part_capacity, m.s.q_prepared, cache, m.s.rel_table, m.s.part_o, m.s.part_ml, m.s.sink, m.s.gate, m.s.attn_heads); + try ops.rowdot(&k.glue, s, m.s.attn_heads, lw.attn.wo, m.s.attn_out, rows, h, q_width, true, false); + + if (layer.boundary) { + try m.copy(s, m.s.blocks[n_blocks], partial, rows * h * 2); + n_blocks += 1; + } + try ops.conv(&k.glue, s, .{ + .x = m.s.attn_out, + .state = m.convOf(visit.cache_slot, 2), + .w = lw.attn_conv, + .base = if (layer.boundary) 0 else partial, + .resid = m.s.t, + .hist = if (record) m.histOf(visit.cache_slot, 2) else 0, + .x_bf16 = 1, + .c = @intCast(h), + .rows = @intCast(rows), + .mode = 1, + }, 1); + + const mlp_query = m.w.mlp_queries[visit.layer]; + const mlp_blocks = m.s.blocks[0..n_blocks]; + if (messages) { + try loop_math.ar(&k.loop, s, m.arBlocks(mlp_blocks, m.s.t, mlp_query, m.s.raw, 1, false, rows)); + const ctl = lw.controllers[3]; + try loop_math.gate(&k.loop, s, m.s.raw, m.s.messages + 3 * raw_stride, ctl.down, ctl.forget, ctl.gain, m.s.raw, rows, h, c.eps); + try ops.mix(&k.glue, s, m.mixArgs(&.{}, m.s.raw, 0, .{ lw.mlp_norm, lw.mlp_norm, lw.mlp_norm }, m.s.normalized, 1, false, rows)); + } else { + try ops.mix(&k.glue, s, m.mixArgs(mlp_blocks, m.s.t, mlp_query, .{ lw.mlp_norm, lw.mlp_norm, lw.mlp_norm }, m.s.normalized, 1, false, rows)); + } + try ops.rowdot(&k.glue, s, m.s.normalized, lw.router, m.s.route_scores, rows, c.experts, h, false, true); + try ops.topk(&k.glue, s, m.s.route_scores, lw.router_bias, m.s.route_pick, m.s.route_weights, rows, c.experts, c.topk, c.route_scale); + try modelopt.run(&k.moe, s, lw.experts, .{ .gate = c.gate_cap, .up = c.up_cap }, m.s.normalized, h, m.s.route_pick, m.s.route_weights, rows, c.topk, m.s.moe_out, m.s.moe_scratch); + try ops.conv(&k.glue, s, .{ + .x = m.s.moe_out, + .state = m.convOf(visit.cache_slot, 3), + .w = lw.mlp_conv, + .resid = m.s.t, + .out = next, + .hist = if (record) m.histOf(visit.cache_slot, 3) else 0, + .x_bf16 = 1, + .c = @intCast(h), + .rows = @intCast(rows), + .mode = 2, + }, 1); + std.mem.swap(u64, &partial, &next); + + if (visit.layer + 1 == lp.core_start) try m.copy(s, m.s.prelude, partial, rows * h * 2); + if (visit.pass > 0 and visit.pass < lp.passes and visit.layer + 1 == lp.core_end) { + try m.copy(s, m.s.bank0, m.s.blocks[n_blocks - 1], rows * h * 2); + try m.copy(s, m.s.bank1, partial, rows * h * 2); + } + } + + if (heads == 0) return; + try ops.mix(&k.glue, s, m.mixArgs(m.s.blocks[0..n_blocks], partial, m.w.output_query, .{ m.w.norm, m.w.norm, m.w.norm }, m.s.hidden, 1, true, rows)); + try ops.rowdot(&k.glue, s, m.s.hidden + head0 * h * 2, m.w.unembed, m.s.logits, heads, c.unpadded_vocab, h, false, false); + try loop_math.roundBf16(&k.loop, s, m.s.logits, m.s.logits, heads * c.unpadded_vocab); + try ops.softcap(&k.glue, s, m.s.logits, heads * c.unpadded_vocab, c.logit_cap); + } + + pub const Saved = struct { + at: u32, + visits: u32, + passes: u32, + hidden: u32, + buf: cuda.DeviceBuffer, + }; + + /// Compact bytes for all valid K/V rows and every convolution state of all 48 visits. + pub fn snapshotBytes(m: *const Model, at: usize) u64 { + var bytes = m.layout.bytes - m.layout.at(0).conv_offset; + for (0..m.w.p.n_visits) |v| { + const layer = m.w.p.at(m.w.p.visits[v].layer); + const global = layer.kind == .global; + const count = if (global) at else @min(at, m.w.c.text.window - 1); + const row = @as(u64, layer.heads.kv) * layer.heads.dim * 2; + bytes += 2 * count * row; + } + return bytes; + } + + fn copyState(m: *const Model, s: cuda.Stream, saved: *const Saved, out: bool) !void { + const at: usize = saved.at; + var off: usize = 0; + for (0..m.w.p.n_visits) |v| { + const visit = m.w.p.visits[v]; + const layer = m.w.p.at(visit.layer); + const geometry = m.layerGeometry(visit.layer); + const rb = @as(usize, layer.heads.dim) * 2; // the caches are head-major: [kv head][ring][dim] + const global = layer.kind == .global; + const count = if (global) at else @min(at, m.w.c.text.window - 1); + const first = at - count; + const cache = m.cacheOf(visit.cache_slot); + for ([2]u64{ cache.k, cache.v }) |k_or_v| for (0..layer.heads.kv) |head| { + const base = k_or_v + head * geometry.ring * rb; + var pos = first; + while (pos < at) { + const row = pos % geometry.ring; + const n = @min(at - pos, geometry.ring - row); + const dev = base + row * rb; + const src = if (out) dev else saved.buf.ptr + off; + const dst = if (out) saved.buf.ptr + off else dev; + try m.copy(s, dst, src, n * rb); + off += n * rb; + pos += n; + } + }; + } + const conv = m.slotBase() + m.layout.at(0).conv_offset; + const bytes = m.layout.bytes - m.layout.at(0).conv_offset; + try m.copy(s, if (out) saved.buf.ptr + off else conv, if (out) conv else saved.buf.ptr + off, bytes); + } + + pub fn save(m: *const Model, s: cuda.Stream, at: u32) !*Saved { + if (at == 0 or at > m.context) return error.NotAtMark; + const gpa = m.gpa; + const saved = try gpa.create(Saved); + errdefer gpa.destroy(saved); + const lp = m.w.c.text.loop.?; + saved.* = .{ .at = at, .visits = m.w.p.n_visits, .passes = lp.passes, .hidden = m.w.c.text.hidden, .buf = try cuda.DeviceBuffer.alloc(m.d, @intCast(@max(snapshotBytes(m, at), 256))) }; + errdefer saved.buf.free(); + try m.copyState(s, saved, true); + return saved; + } + + pub fn restore(m: *const Model, s: cuda.Stream, saved: *const Saved) !void { + const lp = m.w.c.text.loop.?; + if (saved.visits != m.w.p.n_visits or saved.passes != lp.passes or saved.hidden != m.w.c.text.hidden) + return error.StateOfAnotherModel; + if (saved.at == 0 or saved.at > m.context or saved.buf.len < snapshotBytes(m, saved.at)) return error.BadLoopSnapshot; + try m.copyState(s, saved, false); + } + + pub fn drop(m: *const Model, s: cuda.Stream, saved: *Saved) void { + s.synchronize() catch {}; + saved.buf.free(); + m.gpa.destroy(saved); + } +}; diff --git a/zig/src/families/inkling2/loop_math_cuda.zig b/zig/src/families/inkling2/loop_math_cuda.zig new file mode 100644 index 00000000000..9a0d4cc4b63 --- /dev/null +++ b/zig/src/families/inkling2/loop_math_cuda.zig @@ -0,0 +1,158 @@ +//! Inkling 2 Mini loop math (inkling2/loop_math.cu): raw AR, two-bank messages, rank-64 gates and split QKV inputs. +const std = @import("std"); +const cuda = @import("cuda"); + +pub const rank = 64; +pub const max_blocks = 8; +pub const max_queries = 3; + +/// loop_math.cu's ArArgs, field for field. `out[q][row][c]` is FP32 AR output before any controller or RMSNorm. +pub const ArArgs = extern struct { + blocks: [max_blocks]u64 = @splat(0), // BF16 [rows][c], each a completed block state + partial: u64, // BF16 when partial_bf16 != 0, otherwise FP32; always the final AR source + query: u64, // FP32 [nq][c] + out: u64, // FP32 [nq][rows][c] + n_blocks: i32, + partial_bf16: i32, + nq: i32, + rows: i32, + c: i32, + eps: f32, +}; + +pub const Kernels = struct { + mod: cuda.Module, + ar_fn: cuda.Function, + messages_fn: cuda.Function, + gate_fn: cuda.Function, + project_qkv_fn: cuda.Function, + round_bf16_fn: cuda.Function, + + pub fn load(d: *const cuda.Driver) !Kernels { + if (!cuda.kernels.available) return error.BuiltWithoutKernels; + var mod = try cuda.Module.load(d, cuda.kernels.inkling2_loop_math); + errdefer mod.unload(); + return .{ + .mod = mod, + .ar_fn = try mod.function("tf_ink2_loop_ar"), + .messages_fn = try mod.function("tf_ink2_loop_messages"), + .gate_fn = try mod.function("tf_ink2_loop_gate"), + .project_qkv_fn = try mod.function("tf_ink2_loop_project_qkv"), + .round_bf16_fn = try mod.function("tf_ink2_loop_round_bf16"), + }; + } + + pub fn unload(k: *Kernels) void { + k.mod.unload(); + k.* = undefined; + } +}; + +fn int(x: anytype) i32 { + return @intCast(x); +} + +fn go(f: cuda.Function, s: cuda.Stream, grid: cuda.Dim3, threads: u32, a: *cuda.Args) !void { + try cuda.launch.launch(f, .{ .grid = grid, .block = .{ .x = threads } }, s, a); +} + +/// Unnormalized block attention residual. No scratch; nq <= 3 and at most 8 completed blocks plus `partial`. +pub fn ar(k: *const Kernels, s: cuda.Stream, a: ArArgs) !void { + if (a.n_blocks < 0 or a.n_blocks > max_blocks or a.nq <= 0 or a.nq > max_queries or a.rows <= 0 or a.c <= 0) + return error.Inkling2LoopArShape; + var args: cuda.Args = .{}; + args.add(a); + try go(k.ar_fn, s, .{ .x = @intCast(a.rows) }, 512, &args); +} + +/// Messages: BF16 banks, even/odd qm/kv FP32 queries/output; row-local q/k/v/mlp, no scratch/position/mask/cache. +pub fn messages( + k: *const Kernels, + s: cuda.Stream, + bank0_bf16: u64, + bank1_bf16: u64, + queries_qm_f32: u64, + queries_kv_f32: u64, + out_f32: u64, + rows: usize, + core_layers: usize, + c: usize, + eps: f32, +) !void { + if (rows == 0 or core_layers == 0 or c == 0) return error.Inkling2LoopMessageShape; + var a: cuda.Args = .{}; + for ([_]u64{ bank0_bf16, bank1_bf16, queries_qm_f32, queries_kv_f32, out_f32 }) |v| a.add(v); + for ([_]i32{ int(rows), int(core_layers), int(c) }) |v| a.add(v); + a.add(eps); + try go(k.messages_fn, s, .{ .x = @intCast(rows), .y = 4 }, 256, &a); +} + +/// Controller: BF16 D[64][2c]/F/G[c][64] and down I/O; FP32 F/G dots/tanh/four-step output; pre-offset msg, no scratch. +pub fn gate( + k: *const Kernels, + s: cuda.Stream, + state_f32: u64, + message_f32: u64, + down_bf16: u64, + forget_bf16: u64, + gain_bf16: u64, + out_f32: u64, + rows: usize, + c: usize, + eps: f32, +) !void { + if (rows == 0 or c == 0) return error.Inkling2LoopGateShape; + var a: cuda.Args = .{}; + for ([_]u64{ state_f32, message_f32, down_bf16, forget_bf16, gain_bf16, out_f32 }) |v| a.add(v); + for ([_]i32{ int(rows), int(c) }) |v| a.add(v); + a.add(eps); + try go(k.gate_fn, s, .{ .x = @intCast(rows) }, 256, &a); +} + +/// Mini QKV: normalized BF16 uq/uk/uv, query-side u_q; per-visit K/V conv/cache, then wo/post-conv; no history. +pub fn projectQkv( + k: *const Kernels, + s: cuda.Stream, + u_q: u64, + u_k: u64, + u_v: u64, + wq: u64, + wk: u64, + wv: u64, + raw_q: u64, + raw_k: u64, + raw_v: u64, + rows: usize, + c: usize, + q_width: usize, + kv_width: usize, +) !void { + if (rows == 0 or c == 0 or q_width == 0 or kv_width == 0) return error.Inkling2LoopQkvShape; + var a: cuda.Args = .{}; + for ([_]u64{ u_q, u_k, u_v, wq, wk, wv, raw_q, raw_k, raw_v }) |v| a.add(v); + for ([_]i32{ int(rows), int(c), int(q_width), int(kv_width) }) |v| a.add(v); + try go(k.project_qkv_fn, s, .{ .x = @intCast((rows + 15) / 16), .y = @intCast((@max(q_width, kv_width) + 15) / 16), .z = 3 }, 256, &a); +} + +/// BF16-round FP32 then widen, preserving section 6.3 unlike rowdot(false); in/out may alias, no scratch, n=0 no-op. +pub fn roundBf16(k: *const Kernels, s: cuda.Stream, in_f32: u64, out_f32: u64, n: usize) !void { + if (n == 0) return; + var a: cuda.Args = .{}; + for ([_]u64{ in_f32, out_f32 }) |v| a.add(v); + a.add(@as(i64, @intCast(n))); + try go(k.round_bf16_fn, s, .{ .x = @intCast((n + 255) / 256) }, 256, &a); +} + +test "loop math argument ABI and message role offsets" { + try std.testing.expectEqual(@as(usize, 112), @sizeOf(ArArgs)); + const c = 2304; + const j = 7; + const row = 3; + const core_layers = 12; + const base = ((row * core_layers + j) * 4) * c; + for ([_]usize{ 0, 1, 2, 3 }, 0..) |role, i| { + const at = base + role * c; + const queries = @as(usize, 2 * j + @as(usize, @intFromBool(i == 2 or i == 3))) * c; + try std.testing.expect(at >= base and queries < 24 * c); + } +} diff --git a/zig/src/families/inkling2/loop_model.zig b/zig/src/families/inkling2/loop_model.zig new file mode 100644 index 00000000000..c56b1ce7a2e --- /dev/null +++ b/zig/src/families/inkling2/loop_model.zig @@ -0,0 +1,464 @@ +//! f64 Mini: f32 sums/combine ascend (A12), bf16 experts/acts (A1/A2), f32 F/G (A7), postdot scale (A14); casts round. +const std = @import("std"); +const bf = @import("bf16_round"); + +pub const hidden_size = 2304; +pub const gate_rank = 64; +pub const physical_layers = 24; +pub const core_start = 6; +pub const core_end = 18; +pub const core_layers = core_end - core_start; +pub const num_passes = 3; +pub const visit_count = 48; +pub const message_roles = 4; +pub const rms_eps = 1e-6; + +pub const ShapeError = error{BadShape}; +pub const VisitError = error{BadVisit}; +pub const DriverError = error{ BadShape, BadVisit, BadDriverState, BadSequence }; + +fn narrow32(v: f64) f32 { + return @floatCast(v); +} + +fn widen32(v: f32) f64 { + return @floatCast(v); +} + +/// One round to nearest-even bf16; the returned f64 is exactly that bf16 value. +pub fn bf16(v: f64) f64 { + return bf.bf16(v); +} + +/// rho(x), with an f32 ordered sum of squares and the specified f32 mean/rsqrt/multiply. +pub fn rms(x: []const f64, eps: f64, out: []f64) ShapeError!void { + if (x.len == 0 or out.len != x.len or !std.math.isFinite(eps) or eps < 0) return error.BadShape; + var squares: f32 = 0; + for (x) |v| { + const a = narrow32(v); + squares += a * a; + } + const mean = squares / @as(f32, @floatFromInt(x.len)); + const inverse: f32 = 1 / @sqrt(mean + narrow32(eps)); + for (x, out) |v, *o| o.* = widen32(narrow32(v) * inverse); +} + +/// N_w(x): no bf16 rounding between rho and the weight product, one bf16 rounding at the end. +pub fn weightedRms(x: []const f64, weight: []const f64, eps: f64, out: []f64, scratch: []f64) ShapeError!void { + if (weight.len != x.len or scratch.len != x.len) return error.BadShape; + try rms(x, eps, scratch); + for (scratch, weight, out) |v, w, *o| o.* = bf16(widen32(narrow32(w) * narrow32(v))); +} + +/// binary32(1/sqrt(H)); in particular Mini's value is binary32(1/48), not a double scale. +pub fn residualScale(hidden: usize) ShapeError!f32 { + if (hidden == 0) return error.BadShape; + return narrow32(1 / @sqrt(@as(f64, @floatFromInt(hidden)))); +} + +fn normalizeSources(states: []const f64, partial: []const f64, eps: f64, normalized: []f64) ShapeError!usize { + if (partial.len == 0 or states.len % partial.len != 0) return error.BadShape; + const h = partial.len; + const count = states.len / h + 1; + if (normalized.len != count * h) return error.BadShape; + for (0..count - 1) |i| try rms(states[i * h ..][0..h], eps, normalized[i * h ..][0..h]); + try rms(partial, eps, normalized[(count - 1) * h ..][0..h]); + return count; +} + +fn retrieve(normalized: []const f64, query: []const f64, out: []f64, weights: []f64) ShapeError!void { + if (query.len == 0 or out.len != query.len or normalized.len % query.len != 0) return error.BadShape; + const h = query.len; + const count = normalized.len / h; + if (count == 0 or weights.len != count) return error.BadShape; + const scale = try residualScale(h); + var top: f32 = -std.math.inf(f32); + for (0..count) |i| { + var dot: f32 = 0; + for (query, normalized[i * h ..][0..h]) |q, v| dot += narrow32(q) * narrow32(v); + const logit = dot * scale; + weights[i] = widen32(logit); + top = @max(top, logit); + } + var denominator: f32 = 0; + for (weights) |*w| { + const d = narrow32(w.* - widen32(top)); + const e = @exp(d); + w.* = widen32(e); + denominator += e; + } + @memset(out, 0); + for (0..count) |i| { + const weight = narrow32(weights[i]) / denominator; + for (out, normalized[i * h ..][0..h]) |*o, v| { + const a = narrow32(o.*); + o.* = widen32(a + weight * narrow32(v)); + } + } +} + +/// AR_Q(S,p): states[S][H], queries/out[Q][H] row-major; empty S okay, partial last, normalize before attention. +pub fn attentionResidual(gpa: std.mem.Allocator, states: []const f64, partial: []const f64, queries: []const f64, query_rows: usize, eps: f64, out: []f64) !void { + if (partial.len == 0 or query_rows == 0 or states.len % partial.len != 0) return error.BadShape; + const h = partial.len; + if (queries.len != query_rows * h or out.len != queries.len) return error.BadShape; + const count = states.len / h + 1; + const normalized = try gpa.alloc(f64, count * h); + defer gpa.free(normalized); + const weights = try gpa.alloc(f64, count); + defer gpa.free(weights); + _ = try normalizeSources(states, partial, eps, normalized); + for (0..query_rows) |q| try retrieve(normalized, queries[q * h ..][0..h], out[q * h ..][0..h], weights); +} + +pub const MessageRole = enum(u2) { q = 0, k = 1, v = 2, mlp = 3 }; + +/// The previous pass's B_12 and P_18. No embedding, prelude, or current-pass state is included. +pub const MessageBank = struct { + block: []const f64, + partial: []const f64, +}; + +/// Both checkpoint tensors in their stored row-major layouts: 24 rows by H. +pub const MessageQueries = struct { + q_mlp: []const f64, + kv: []const f64, + + /// Core j uses row 2j for q/k and row 2j+1 for mlp/v, in their respective tensors. + pub fn row(q: MessageQueries, core: usize, role: MessageRole, hidden: usize) ShapeError![]const f64 { + if (core >= core_layers or hidden == 0 or q.q_mlp.len != 2 * core_layers * hidden or q.kv.len != 2 * core_layers * hidden) return error.BadShape; + const odd: usize = @intFromBool(role == .mlp or role == .v); + const row_index = 2 * core + odd; + const source = if (role == .q or role == .mlp) q.q_mlp else q.kv; + return source[row_index * hidden ..][0..hidden]; + } +}; + +fn bankNormalized(gpa: std.mem.Allocator, bank: MessageBank, eps: f64) ![]f64 { + if (bank.block.len == 0 or bank.partial.len != bank.block.len) return error.BadShape; + const normalized = try gpa.alloc(f64, 2 * bank.block.len); + errdefer gpa.free(normalized); + try rms(bank.block, eps, normalized[0..bank.block.len]); + try rms(bank.partial, eps, normalized[bank.block.len..]); + return normalized; +} + +/// One of the 48 cross-pass messages. Its bank values and output are binary32 values held in f64. +pub fn crossPassMessage(gpa: std.mem.Allocator, bank: MessageBank, query: []const f64, eps: f64, out: []f64) !void { + if (query.len != bank.block.len or out.len != query.len) return error.BadShape; + const normalized = try bankNormalized(gpa, bank, eps); + defer gpa.free(normalized); + var weights: [2]f64 = undefined; + try retrieve(normalized, query, out, &weights); +} + +/// All messages in [core layer][q,k,v,mlp][H] order. Queries are shared by passes two and three. +pub fn crossPassMessages(gpa: std.mem.Allocator, bank: MessageBank, queries: MessageQueries, eps: f64, out: []f64) !void { + const h = bank.block.len; + if (h == 0 or bank.partial.len != h or out.len != core_layers * message_roles * h) return error.BadShape; + const normalized = try bankNormalized(gpa, bank, eps); + defer gpa.free(normalized); + var weights: [2]f64 = undefined; + const roles = [_]MessageRole{ .q, .k, .v, .mlp }; + for (0..core_layers) |j| for (roles, 0..) |role, r| { + const query = try queries.row(j, role, h); + const at = (j * message_roles + r) * h; + try retrieve(normalized, query, out[at..][0..h], &weights); + }; +} + +/// Mini's rank-64 controller, represented with smaller ranks too for inexpensive host probes. +pub const GateWeights = struct { + down: []const f64, // [rank][2H], with the h half before the message half + forget: []const f64, // [H][rank] + gain: []const f64, // [H][rank] + rank: usize, +}; + +fn gateDot(row: []const f64, values: []const f64) f32 { + var sum: f32 = 0; + for (row, values) |w, v| sum += narrow32(w) * narrow32(v); + return sum; +} + +/// G(h,m) = (1-f)*h + g*m. The joined norm and bottleneck are bf16; F/G stay f32 (A7). +pub fn messageGate(gpa: std.mem.Allocator, h: []const f64, m: []const f64, w: GateWeights, eps: f64, out: []f64) !void { + const width = h.len; + if (width == 0 or m.len != width or out.len != width or w.rank == 0) return error.BadShape; + if (w.down.len != w.rank * 2 * width or w.forget.len != width * w.rank or w.gain.len != width * w.rank) return error.BadShape; + const joined = try gpa.alloc(f64, 2 * width); + defer gpa.free(joined); + const zeta = try gpa.alloc(f64, w.rank); + defer gpa.free(zeta); + try rms(h, eps, joined[0..width]); + try rms(m, eps, joined[width..]); + for (joined) |*v| v.* = bf16(v.*); + for (0..w.rank) |r| zeta[r] = bf16(widen32(gateDot(w.down[r * 2 * width ..][0 .. 2 * width], joined))); + for (0..width) |i| { + const forget = std.math.tanh(gateDot(w.forget[i * w.rank ..][0..w.rank], zeta)); + const gain = std.math.tanh(gateDot(w.gain[i * w.rank ..][0..w.rank], zeta)); + const keep: f32 = 1 - forget; + const left = keep * narrow32(h[i]); + const right = gain * narrow32(m[i]); + out[i] = widen32(left + right); + } +} + +pub const AttentionKind = enum { sliding, global }; + +/// One row of the fixed 48-visit schedule. cache_slot is visit numbering; reference_slot is HF's. +pub const Visit = struct { + index: u8, + layer: u8, + pass: u8, // zero outside the core, one-based inside it + cache_slot: u8, + reference_slot: u8, + kind: AttentionKind, + boundary: bool, + has_messages: bool, + ar_queries: u8, + attention_sources: u8, + mlp_sources: u8, +}; + +pub fn visit(index: usize) VisitError!Visit { + if (index >= visit_count) return error.BadVisit; + const layer: u8 = if (index < core_start) + @intCast(index) + else if (index < 42) + @intCast(core_start + (index - core_start) % core_layers) + else + @intCast(index - 24); + const pass: u8 = if (index >= 18 and index < 42) @intCast(1 + (index - core_start) / core_layers) else if (index >= core_start and index < 18) 1 else 0; + const reference: u8 = if (pass >= 2) @intCast(24 + (@as(usize, pass) - 2) * core_layers + layer - core_start) else layer; + const global = (@as(usize, layer) + 1) % 6 == 0; + const boundary = layer % 6 == 0; + const blocks: u8 = (layer + 5) / 6; + return .{ + .index = @intCast(index), + .layer = layer, + .pass = pass, + .cache_slot = @intCast(index), + .reference_slot = reference, + .kind = if (global) .global else .sliding, + .boundary = boundary, + .has_messages = pass >= 2, + .ar_queries = if (layer == 0) 0 else if (global) 3 else 1, + .attention_sources = if (layer == 0) 0 else blocks + 1, + .mlp_sources = blocks + 1 + @intFromBool(boundary), + }; +} + +pub const Sources = struct { + blocks: []const f64, // [completed block][H] + partial: []const f64, // p before attention, or unrounded t before the MLP +}; + +/// Residual/block only; caller attention/conv/MoE. Visit: begin->attentionSources->afterAttention->mlpSources->finish. +pub const Driver = struct { + gpa: std.mem.Allocator, + hidden: usize, + storage: []f64, // blocks[4H], prelude snapshot[2H], bank[2H], p[H], t[H] + block_count: usize, + next: usize, + phase: enum { ready, attention, mlp }, + active: Visit, + have_snapshot: bool, + + pub fn init(gpa: std.mem.Allocator, embedding: []const f64) !Driver { + if (embedding.len == 0) return error.BadShape; + const h = embedding.len; + const storage = try gpa.alloc(f64, 10 * h); + @memset(storage, 0); + for (embedding, storage[8 * h .. 9 * h]) |v, *p| p.* = bf16(v); + return .{ .gpa = gpa, .hidden = h, .storage = storage, .block_count = 0, .next = 0, .phase = .ready, .active = undefined, .have_snapshot = false }; + } + + pub fn deinit(d: *Driver) void { + d.gpa.free(d.storage); + d.* = undefined; + } + + fn blocks(d: *Driver) []f64 { + return d.storage[0 .. d.block_count * d.hidden]; + } + + fn partial(d: *Driver) []f64 { + return d.storage[8 * d.hidden .. 9 * d.hidden]; + } + + fn work(d: *Driver) []f64 { + return d.storage[9 * d.hidden .. 10 * d.hidden]; + } + + /// Applies the pass reset before visits 18 and 30, after saving that previous pass's two bank states. + pub fn begin(d: *Driver, index: usize) DriverError!Visit { + if (index >= visit_count) return error.BadVisit; + if (d.phase != .ready or d.next != index) return error.BadSequence; + if (index == core_start) { + if (d.block_count != 1) return error.BadDriverState; + @memcpy(d.storage[4 * d.hidden .. 5 * d.hidden], d.partial()); + @memcpy(d.storage[5 * d.hidden .. 6 * d.hidden], d.blocks()); + d.have_snapshot = true; + } + if (index == 18 or index == 30) { + if (!d.have_snapshot or d.block_count != 3) return error.BadDriverState; + @memcpy(d.storage[6 * d.hidden .. 7 * d.hidden], d.storage[2 * d.hidden .. 3 * d.hidden]); + @memcpy(d.storage[7 * d.hidden .. 8 * d.hidden], d.partial()); + @memcpy(d.partial(), d.storage[4 * d.hidden .. 5 * d.hidden]); + @memcpy(d.storage[0..d.hidden], d.storage[5 * d.hidden .. 6 * d.hidden]); + d.block_count = 1; + } + d.active = visit(index) catch return error.BadVisit; + d.phase = .attention; + return d.active; + } + + pub fn attentionSources(d: *Driver) DriverError!Sources { + if (d.phase != .attention) return error.BadSequence; + return .{ .blocks = d.blocks(), .partial = d.partial() }; + } + + /// Saves p as a completed boundary block, then forms f32 t without rounding it to bf16. + pub fn afterAttention(d: *Driver, attention: []const f64) DriverError!void { + if (d.phase != .attention) return error.BadSequence; + if (attention.len != d.hidden) return error.BadShape; + if (d.active.boundary) { + if (d.block_count == 4) return error.BadDriverState; + @memcpy(d.storage[d.block_count * d.hidden ..][0..d.hidden], d.partial()); + d.block_count += 1; + for (d.work(), attention) |*t, a| t.* = widen32(narrow32(a)); + } else { + for (d.work(), d.partial(), attention) |*t, p, a| t.* = widen32(narrow32(p) + narrow32(a)); + } + d.phase = .mlp; + } + + /// AR's second call sees the extended block list and t, not bf16(t). + pub fn mlpSources(d: *Driver) DriverError!Sources { + if (d.phase != .mlp) return error.BadSequence; + return .{ .blocks = d.blocks(), .partial = d.work() }; + } + + /// p_out = bf16(t + f32(post-MLP-convolution output)); the residual itself is never gated. + pub fn finish(d: *Driver, mlp: []const f64) DriverError!void { + if (d.phase != .mlp) return error.BadSequence; + if (mlp.len != d.hidden) return error.BadShape; + for (d.partial(), d.work(), mlp) |*p, t, o| p.* = bf16(widen32(narrow32(t) + narrow32(o))); + d.phase = .ready; + d.next += 1; + } + + /// Raw B_12 and P_18 of the immediately previous pass; valid until the next pass reset. + pub fn messageBank(d: *Driver) DriverError!MessageBank { + if (d.phase == .ready or !d.active.has_messages) return error.BadDriverState; + return .{ .block = d.storage[6 * d.hidden .. 7 * d.hidden], .partial = d.storage[7 * d.hidden .. 8 * d.hidden] }; + } + + /// The five final AR sources after visit 47: four completed blocks and P_24. + pub fn finalSources(d: *Driver) DriverError!Sources { + if (d.phase != .ready or d.next != visit_count or d.block_count != 4) return error.BadDriverState; + return .{ .blocks = d.blocks(), .partial = d.partial() }; + } +}; + +pub fn e2m1(code: u8) f64 { + const table = [_]f64{ 0, 0.5, 1, 1.5, 2, 3, 4, 6 }; + const magnitude = table[code & 7]; + return std.math.copysign(magnitude, if (code & 8 != 0) @as(f64, -1) else @as(f64, 1)); +} + +/// OCP E4M3FN, including its subnormals and sole NaN encodings. +pub fn e4m3(code: u8) f64 { + const negative = code & 0x80 != 0; + const exponent: u8 = (code >> 3) & 0xf; + const mantissa: u8 = code & 7; + if (exponent == 15 and mantissa == 7) return std.math.nan(f64); + const magnitude = if (exponent == 0) + std.math.ldexp(@as(f64, @floatFromInt(mantissa)), -9) + else + std.math.ldexp(1 + @as(f64, @floatFromInt(mantissa)) / 8, @as(i32, exponent) - 7); + return if (negative) -magnitude else magnitude; +} + +/// A2(a): both source f32 scalars are cast to bf16 before one binary32 division. +pub fn nvfp4OuterFactor(amax: f64, denominator: f64) f64 { + const a = narrow32(bf16(amax)); + const d = narrow32(bf16(denominator)); + return widen32(a / d); +} + +fn nvWeight(code: u8, scale: u8, factor: f32) f64 { + const inner = narrow32(e2m1(code) * e4m3(scale)); // the E2M1*E4M3 product is exact + return bf16(widen32(inner * factor)); +} + +pub fn nvfp4ReferenceWeight(code: u8, scale: u8, amax: f64, denominator: f64) f64 { + return nvWeight(code, scale, narrow32(nvfp4OuterFactor(amax, denominator))); +} + +/// Decode one packed NVFP4 row: low nibble is the even input, one E4M3 scale per 16 inputs. +pub fn nvfp4ReferenceRow(codes: []const u8, scales: []const u8, amax: f64, denominator: f64, out: []f64) ShapeError!void { + if (out.len == 0 or out.len % 16 != 0 or codes.len != out.len / 2 or scales.len != out.len / 16) return error.BadShape; + const factor = narrow32(nvfp4OuterFactor(amax, denominator)); + for (out, 0..) |*v, c| { + const packed_byte = codes[c / 2]; + const code = if (c % 2 == 0) packed_byte & 0xf else packed_byte >> 4; + v.* = nvWeight(code, scales[c / 16], factor); + } +} + +pub fn mxfp8Scale(scale: u8) f64 { + return std.math.ldexp(@as(f64, 1), @as(i32, scale) - 127); +} + +pub fn mxfp8ReferenceWeight(code: u8, scale: u8) f64 { + return bf16(e4m3(code) * mxfp8Scale(scale)); +} + +/// Decode one MXFP8 row using the stored per-row exponent for each group of 32 input columns (A4). +pub fn mxfp8ReferenceRow(codes: []const u8, scales: []const u8, out: []f64) ShapeError!void { + if (out.len == 0 or out.len % 32 != 0 or codes.len != out.len or scales.len != out.len / 32) return error.BadShape; + for (out, codes, 0..) |*v, code, c| v.* = mxfp8ReferenceWeight(code, scales[c / 32]); +} + +/// A bf16 reference GEMM output, with ascending f32 accumulation and no activation quantization. +pub fn expertProjection(weights: []const f64, x: []const f64, rows: usize, out: []f64) ShapeError!void { + if (rows == 0 or x.len == 0 or out.len != rows or weights.len != rows * x.len) return error.BadShape; + for (0..rows) |r| { + var sum: f32 = 0; + for (weights[r * x.len ..][0..x.len], x) |w, v| sum += narrow32(w) * narrow32(v); + out[r] = bf16(widen32(sum)); + } +} + +fn softcap32(x: f32, cap: f32) f32 { + return cap * std.math.tanh(x / cap); +} + +/// bf16(softcap4(g) * sigmoid(g) * softcap25(u)), evaluated left to right in f32. +pub fn expertActivation(gate: f64, up: f64) f64 { + const g = narrow32(gate); + const sigmoid: f32 = 1 / (1 + @exp(-g)); + const act = softcap32(g, 4) * sigmoid * softcap32(narrow32(up), 25); + return bf16(widen32(act)); +} + +/// Combine f32 from zero by ascending id, not route order (A12); expert_outputs [route][H], ids/route_weights [route]. +pub fn combineExperts(expert_count: usize, ids: []const u32, route_weights: []const f64, expert_outputs: []const f64, hidden: usize, out: []f64) ShapeError!void { + if (expert_count == 0 or hidden == 0 or ids.len != route_weights.len or expert_outputs.len != ids.len * hidden or out.len != hidden) return error.BadShape; + @memset(out, 0); + for (0..expert_count) |e| { + var found = false; + for (ids, 0..) |id, r| if (id == e) { + if (found) return error.BadShape; + found = true; + const weight = narrow32(route_weights[r]); + for (out, expert_outputs[r * hidden ..][0..hidden]) |*sum, value| { + const term = weight * narrow32(value); + sum.* = widen32(narrow32(sum.*) + term); + } + } else if (id >= expert_count) return error.BadShape; + } + for (out) |*v| v.* = bf16(v.*); +} diff --git a/zig/src/families/inkling2/loop_model_test.zig b/zig/src/families/inkling2/loop_model_test.zig new file mode 100644 index 00000000000..ee0bcf64dab --- /dev/null +++ b/zig/src/families/inkling2/loop_model_test.zig @@ -0,0 +1,214 @@ +const std = @import("std"); +const model = @import("loop_model.zig"); + +const Driver = model.Driver; +const GateWeights = model.GateWeights; +const MessageBank = model.MessageBank; +const MessageQueries = model.MessageQueries; +const attentionResidual = model.attentionResidual; +const bf16 = model.bf16; +const combineExperts = model.combineExperts; +const crossPassMessage = model.crossPassMessage; +const crossPassMessages = model.crossPassMessages; +const e2m1 = model.e2m1; +const e4m3 = model.e4m3; +const expertActivation = model.expertActivation; +const expertProjection = model.expertProjection; +const hidden_size = model.hidden_size; +const messageGate = model.messageGate; +const mxfp8ReferenceRow = model.mxfp8ReferenceRow; +const mxfp8ReferenceWeight = model.mxfp8ReferenceWeight; +const mxfp8Scale = model.mxfp8Scale; +const nvfp4OuterFactor = model.nvfp4OuterFactor; +const nvfp4ReferenceRow = model.nvfp4ReferenceRow; +const nvfp4ReferenceWeight = model.nvfp4ReferenceWeight; +const residualScale = model.residualScale; +const rms = model.rms; +const visit = model.visit; +const visit_count = model.visit_count; +const weightedRms = model.weightedRms; + +fn widen32(v: f32) f64 { + return @floatCast(v); +} + +fn expectClose(actual: f64, expected: f64, tolerance: f64) !void { + try std.testing.expectApproxEqAbs(expected, actual, tolerance); +} + +test "norm scale and weighted RMS's sole final bf16 rounding" { + const x = [_]f64{ 3, 4, 0, 0 }; + var out: [4]f64 = undefined; + var scratch: [4]f64 = undefined; + try rms(&x, 0, &out); + try std.testing.expectEqual(@as(f64, widen32(@as(f32, 1.2))), out[0]); + try std.testing.expectEqual(@as(f64, widen32(@as(f32, 1.6))), out[1]); + try weightedRms(&x, &.{ 2, 0.5, 1, 1 }, 0, &out, &scratch); + // Hand: rho=[1.2,1.6,0,0], then [2.4,0.8,0,0]. BF16(0.8) is 0.80078125. + try std.testing.expectEqualSlices(f64, &.{ 2.40625, 0.80078125, 0, 0 }, &out); +} + +test "attention residual normalizes values and applies binary32 inverse-root-H after its dot" { + const state = [_]f64{ 3, 4, 0, 0 }; + const partial = [_]f64{ 0, 10, 0, 0 }; + const query = [_]f64{ 1, 0, 0, 0 }; + var out: [4]f64 = undefined; + try attentionResidual(std.testing.allocator, &state, &partial, &query, 1, 0, &out); + // rho(S)=[1.2,1.6,0,0], rho(p)=[0,2,0,0], logits .6 and zero; w0=1/(1+exp(-.6)), output=w0*rho(S)+(1-w0)*rho(p). + const w0 = 1 / (1 + @exp(@as(f64, -0.6))); + try expectClose(out[0], 1.2 * w0, 2e-7); + try expectClose(out[1], 1.6 * w0 + 2 * (1 - w0), 2e-7); + try std.testing.expectEqual(@as(u32, 0x3caaaaab), @as(u32, @bitCast(try residualScale(hidden_size)))); +} + +test "message bank normalizes exactly its two states and checkpoint query rows are role-interleaved" { + const a = [_]f64{ 3, 4, 0, 0 }; + const p = [_]f64{ 0, 10, 0, 0 }; + var out: [4]f64 = undefined; + try crossPassMessage(std.testing.allocator, .{ .block = &a, .partial = &p }, &.{ 1, 0, 0, 0 }, 0, &out); + const w0 = 1 / (1 + @exp(@as(f64, -0.6))); + try expectClose(out[0], 1.2 * w0, 2e-7); + try expectClose(out[1], 1.6 * w0 + 2 * (1 - w0), 2e-7); + + var q_rows: [24]f64 = undefined; + var kv_rows: [24]f64 = undefined; + for (&q_rows, 0..) |*v, i| v.* = @floatFromInt(i); + for (&kv_rows, 0..) |*v, i| v.* = @floatFromInt(100 + i); + const queries: MessageQueries = .{ .q_mlp = &q_rows, .kv = &kv_rows }; + try std.testing.expectEqual(@as(f64, 4), (try queries.row(2, .q, 1))[0]); + try std.testing.expectEqual(@as(f64, 5), (try queries.row(2, .mlp, 1))[0]); + try std.testing.expectEqual(@as(f64, 104), (try queries.row(2, .k, 1))[0]); + try std.testing.expectEqual(@as(f64, 105), (try queries.row(2, .v, 1))[0]); + + var messages: [visit_count]f64 = undefined; + const one_bank: MessageBank = .{ .block = &.{3}, .partial = &.{4} }; + try crossPassMessages(std.testing.allocator, one_bank, queries, 0, &messages); + for (messages) |message| try std.testing.expectEqual(@as(f64, 1), message); +} + +test "rank gate rounds both joined norms and its down projection before f32 forget and gain" { + const h = [_]f64{ 3, 4, 0, 0 }; + const m = [_]f64{ 0, 10, 0, 0 }; + const weights: GateWeights = .{ + .down = &.{ 0.5, 1.5, 0, 0, 0.5, 1.0078125, 0, 0 }, + .forget = &.{ 1, 0, 0, 0 }, + .gain = &.{ 0, 1, 0, 0 }, + .rank = 1, + }; + var out: [4]f64 = undefined; + try messageGate(std.testing.allocator, &h, &m, weights, 0, &out); + // bf16 rho(h)=[1.203125,1.6015625,0,0], rho(m)=[0,2,0,0]; D*n=5.01953125 rounds to z=5.03125 (else 5.0). + const z: f32 = 5.03125; + const a: f32 = std.math.tanh(z); + const expected0: f32 = (1 - a) * 3; + const expected1: f32 = 4 + a * 10; + try std.testing.expectEqual(@as(f64, widen32(expected0)), out[0]); + try std.testing.expectEqual(@as(f64, widen32(expected1)), out[1]); + try std.testing.expectEqualSlices(f64, &.{ 0, 0 }, out[2..4]); +} + +test "48 visits reset from the prelude and bank B12 plus final partial of only the previous pass" { + var driver = try Driver.init(std.testing.allocator, &.{7}); + defer driver.deinit(); + const zero = [_]f64{0}; + for (0..visit_count) |v| { + _ = try driver.begin(v); + if (v == 6 or v == 18 or v == 30) { + const src = try driver.attentionSources(); + try std.testing.expectEqual(@as(usize, 1), src.blocks.len); + try std.testing.expectEqual(@as(f64, 7), src.blocks[0]); + try std.testing.expectEqual(@as(f64, 21), src.partial[0]); // sum of attention deltas 1...6 + } + if (v == 18) { + const bank = try driver.messageBank(); + try std.testing.expectEqual(@as(f64, 57), bank.block[0]); // sum 7...12 + try std.testing.expectEqual(@as(f64, 93), bank.partial[0]); // sum 13...18 + } else if (v == 30) { + const bank = try driver.messageBank(); + try std.testing.expectEqual(@as(f64, 129), bank.block[0]); // sum 19...24 + try std.testing.expectEqual(@as(f64, 165), bank.partial[0]); // sum 25...30 + } + const delta = [_]f64{@floatFromInt(v + 1)}; + try driver.afterAttention(&delta); + try driver.finish(&zero); + } + const final = try driver.finalSources(); + // Pass 3 supplies the last two core blocks. BF16 rounds the final exact sum 273 to even 272. + try std.testing.expectEqualSlices(f64, &.{ 7, 21, 201, 237 }, final.blocks); + try std.testing.expectEqual(@as(f64, 272), final.partial[0]); +} + +test "visit table preserves layer kinds, AR counts, private visit slots and reference slots" { + const expected = [_]struct { index: usize, layer: u8, pass: u8, reference: u8, messages: bool, ar: u8, attn: u8, mlp: u8 }{ + .{ .index = 0, .layer = 0, .pass = 0, .reference = 0, .messages = false, .ar = 0, .attn = 0, .mlp = 2 }, + .{ .index = 5, .layer = 5, .pass = 0, .reference = 5, .messages = false, .ar = 3, .attn = 2, .mlp = 2 }, + .{ .index = 6, .layer = 6, .pass = 1, .reference = 6, .messages = false, .ar = 1, .attn = 2, .mlp = 3 }, + .{ .index = 17, .layer = 17, .pass = 1, .reference = 17, .messages = false, .ar = 3, .attn = 4, .mlp = 4 }, + .{ .index = 18, .layer = 6, .pass = 2, .reference = 24, .messages = true, .ar = 1, .attn = 2, .mlp = 3 }, + .{ .index = 29, .layer = 17, .pass = 2, .reference = 35, .messages = true, .ar = 3, .attn = 4, .mlp = 4 }, + .{ .index = 30, .layer = 6, .pass = 3, .reference = 36, .messages = true, .ar = 1, .attn = 2, .mlp = 3 }, + .{ .index = 41, .layer = 17, .pass = 3, .reference = 47, .messages = true, .ar = 3, .attn = 4, .mlp = 4 }, + .{ .index = 42, .layer = 18, .pass = 0, .reference = 18, .messages = false, .ar = 1, .attn = 4, .mlp = 5 }, + .{ .index = 47, .layer = 23, .pass = 0, .reference = 23, .messages = false, .ar = 3, .attn = 5, .mlp = 5 }, + }; + for (expected) |e| { + const v = try visit(e.index); + try std.testing.expectEqual(e.layer, v.layer); + try std.testing.expectEqual(e.pass, v.pass); + try std.testing.expectEqual(e.reference, v.reference_slot); + try std.testing.expectEqual(@as(u8, @intCast(e.index)), v.cache_slot); + try std.testing.expectEqual(e.messages, v.has_messages); + try std.testing.expectEqual(e.ar, v.ar_queries); + try std.testing.expectEqual(e.attn, v.attention_sources); + try std.testing.expectEqual(e.mlp, v.mlp_sources); + } + try std.testing.expectError(error.BadVisit, visit(48)); +} + +test "NVFP4 uses bf16 amax and denominator and low nibble before high nibble" { + // 2689 rounds to bf16 2688, so the reference factor is exactly one rather than 2689/2688. + try std.testing.expectEqual(@as(f64, 1), nvfp4OuterFactor(2689, 2688)); + try std.testing.expectEqual(@as(f64, 1.5), nvfp4ReferenceWeight(3, 0x38, 2689, 2688)); + var row: [16]f64 = undefined; + var codes: [8]u8 = @splat(0); + codes[0] = 0xb3; + const scales = [_]u8{0x38}; + try nvfp4ReferenceRow(&codes, &scales, 2689, 2688, &row); + try std.testing.expectEqual(@as(f64, 1.5), row[0]); + try std.testing.expectEqual(@as(f64, -1.5), row[1]); + try std.testing.expectEqual(@as(f64, 0x1p-9), e4m3(1)); + try std.testing.expectEqual(@as(f64, -0.0), e2m1(8)); +} + +test "MXFP8 exponent is UE8M0 and each stored scale covers one row's 32 inputs" { + try std.testing.expectEqual(@as(f64, 8), mxfp8Scale(130)); + try std.testing.expectEqual(@as(f64, 12), mxfp8ReferenceWeight(0x3c, 130)); // 1.5 * 2^3 + var codes: [64]u8 = @splat(0); + codes[0] = 0x38; // one + codes[31] = 0x3c; // 1.5, still group zero + codes[32] = 0x3c; // group one + var out: [64]f64 = undefined; + try mxfp8ReferenceRow(&codes, &.{ 130, 129 }, &out); + try std.testing.expectEqual(@as(f64, 8), out[0]); + try std.testing.expectEqual(@as(f64, 12), out[31]); + try std.testing.expectEqual(@as(f64, 6), out[32]); +} + +test "expert projection and softcapped SwiGLU have no activation quantization" { + var projected: [2]f64 = undefined; + try expertProjection(&.{ 1, 2, -1, 0.5 }, &.{ 3, 4 }, 2, &projected); + try std.testing.expectEqualSlices(f64, &.{ 11, -1 }, &projected); + const g: f32 = 1; + const expected: f32 = 4 * std.math.tanh(g / 4) * (1 / (1 + @exp(-g))) * (25 * std.math.tanh(g / 25)); + try std.testing.expectEqual(@as(f64, bf16(widen32(expected))), expertActivation(1, 1)); +} + +test "expert sum is ascending id even when f32 route-order association gives another bf16 result" { + const ids = [_]u32{ 2, 1, 0 }; + const weights = [_]f64{ 1, 1, 1 }; + // Route order gives -1 + 2^-24 + 1 = 2^-24 in f32; ascending id gives (1 + 2^-24) - 1 = 0 by a tie to even. + const outputs = [_]f64{ -1, 0x1p-24, 1 }; + var out: [1]f64 = undefined; + try combineExperts(3, &ids, &weights, &outputs, 1, &out); + try std.testing.expectEqual(@as(f64, 0), out[0]); +} diff --git a/zig/src/families/inkling2/loop_weights.zig b/zig/src/families/inkling2/loop_weights.zig new file mode 100644 index 00000000000..7bc6263c0fa --- /dev/null +++ b/zig/src/families/inkling2/loop_weights.zig @@ -0,0 +1,228 @@ +//! Inkling 2 Mini's text checkpoint on one CUDA rank. Every scheduled visit shares these physical layer weights. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const config = @import("config.zig"); +const plan_ = @import("plan.zig"); +const modelopt = @import("modelopt.zig"); + +pub const Controller = struct { + down: u64, + forget: u64, + gain: u64, +}; + +pub const Attention = struct { + wq: u64, + wk: u64, + wv: u64, + wr: u64, + wo: u64, + gate: u64, + sink: u64, + q_scale: u64, + rel_scale: u64, + rel_proj: u64, + k_conv: u64, + v_conv: u64, + k_dynamic: u64 = 0, + v_dynamic: u64 = 0, + /// Sliding layers use entry zero for q, k and v. Global layers use the three separate norms. + norms: [3]u64, +}; + +/// Controller order is q, k, v and MLP, matching loop_math_cuda.messages' message layout. +pub const Layer = struct { + attn: Attention, + attn_conv: u64, + mlp_norm: u64, + mlp_conv: u64, + router: u64, + router_bias: u64, + experts: modelopt.Layer, + controllers: [4]Controller, +}; + +pub const Weights = struct { + gpa: std.mem.Allocator, + c: config.Config, + p: plan_.Plan, + embed: u64 = 0, + embed_norm: u64 = 0, + norm: u64 = 0, + unembed: u64 = 0, + output_query: u64 = 0, + attn_queries: []u64 = &.{}, + mlp_queries: []u64 = &.{}, + cross_qm: u64 = 0, + cross_kv: u64 = 0, + layers: []Layer = &.{}, + buffers: std.ArrayList(cuda.DeviceBuffer) = .empty, + bytes: usize = 0, + + pub fn deinit(w: *Weights) void { + for (w.buffers.items) |*b| b.free(); + w.buffers.deinit(w.gpa); + w.gpa.free(w.layers); + w.gpa.free(w.attn_queries); + w.gpa.free(w.mlp_queries); + w.* = undefined; + } +}; + +/// All text tensors occupy one aligned device arena; expert uploads use this same bump allocator. +const Loader = struct { + w: *Weights, + arena: cuda.DeviceBuffer, + used: usize = 0, + + pub fn alloc(l: *Loader, len: usize) !u64 { + const at = std.mem.alignForward(usize, l.used, 256); + const end = try std.math.add(usize, at, len); + if (end > l.arena.len) return error.LoopWeightsOverflow; + l.used = end; + l.w.bytes += len; + return l.arena.ptr + at; + } + + fn put(l: *Loader, bytes: []const u8) !u64 { + const p = try l.alloc(bytes.len); + try l.arena.upload(p - l.arena.ptr, bytes); + return p; + } + + fn tensor(l: *Loader, ck: *core.Checkpoint, comptime fmt: []const u8, args: anytype, dtype: core.safetensors.DType, dims: []const usize) !u64 { + var buf: [256]u8 = undefined; + const name = try std.fmt.bufPrint(&buf, fmt, args); + return l.put((try ck.expect(name, dtype, dims)).bytes); + } +}; + +fn checkpointBytes(ck: *const core.Checkpoint) !usize { + var total: usize = 0; + for (ck.files.items) |file| for (file.names.keys(), file.names.values()) |name, entry| { + if (!std.mem.startsWith(u8, name, "model.llm.")) continue; + const padded = std.mem.alignForward(usize, entry.end - entry.begin, 256); + total = try std.math.add(usize, total, padded); + }; + return total; +} + +fn controllers(l: *Loader, ck: *core.Checkpoint, c: *const config.Text, i: u32, rank: u32, out: *[4]Controller) !void { + const h: usize = c.hidden; + const names = [4][]const u8{ "attn", "k", "v", "mlp" }; + for (names, out) |role, *g| { + var prefix: [160]u8 = undefined; + const p = try std.fmt.bufPrint(&prefix, "model.llm.layers.{d}.controllers.{s}", .{ i, role }); + var down: [224]u8 = undefined; + var forget: [224]u8 = undefined; + var gain: [224]u8 = undefined; + g.* = .{ + .down = try l.put((try ck.expect(try std.fmt.bufPrint(&down, "{s}.down_weight", .{p}), .bf16, &.{ rank, 2 * h })).bytes), + .forget = try l.put((try ck.expect(try std.fmt.bufPrint(&forget, "{s}.forget_weight", .{p}), .bf16, &.{ h, rank })).bytes), + .gain = try l.put((try ck.expect(try std.fmt.bufPrint(&gain, "{s}.gain_weight", .{p}), .bf16, &.{ h, rank })).bytes), + }; + } +} + +/// Load every text tensor, including all four controller triplets and both cross-pass query matrices. +pub fn load(gpa: std.mem.Allocator, d: *const cuda.Driver, ck: *core.Checkpoint, c: *const config.Config, p: plan_.Plan) !Weights { + if (c.text.loop == null) return error.Inkling2LoopRequired; + var formats: [config.max_layers]modelopt.Format = undefined; + for (p.layers[0..c.text.layers], 0..) |layer, k| { + formats[k] = switch (layer.precision) { + .nvfp4 => .nvfp4, + .mxfp8 => .mxfp8, + }; + } + const total = try checkpointBytes(ck); + var arena = try cuda.DeviceBuffer.alloc(d, @max(total, 256)); + var w: Weights = .{ .gpa = gpa, .c = c.*, .p = p }; + errdefer w.deinit(); + w.buffers.append(gpa, arena) catch |err| { + arena.free(); + return err; + }; + w.layers = try gpa.alloc(Layer, c.text.layers); + w.attn_queries = try gpa.alloc(u64, c.text.layers); + w.mlp_queries = try gpa.alloc(u64, c.text.layers); + var l: Loader = .{ .w = &w, .arena = arena }; + const h: usize = c.text.hidden; + w.embed = try l.tensor(ck, "model.llm.embed.weight", .{}, .bf16, &.{ c.text.vocab, h }); + w.embed_norm = try l.tensor(ck, "model.llm.embed_norm.weight", .{}, .bf16, &.{h}); + w.norm = try l.tensor(ck, "model.llm.norm.weight", .{}, .bf16, &.{h}); + w.unembed = try l.tensor(ck, "model.llm.unembed.weight", .{}, .bf16, &.{ c.text.vocab, h }); + w.output_query = try l.tensor(ck, "model.llm.attn_res.output_query", .{}, .f32, &.{h}); + w.cross_qm = try l.tensor(ck, "model.llm.middle_cycle_cross_pass_queries", .{}, .f32, &.{ 2 * (c.text.loop.?.core_end - c.text.loop.?.core_start), h }); + w.cross_kv = try l.tensor(ck, "model.llm.middle_cycle_cross_pass_kv_queries", .{}, .f32, &.{ 2 * (c.text.loop.?.core_end - c.text.loop.?.core_start), h }); + + for (w.layers, 0..) |*layer, k| { + const i: u32 = @intCast(k); + const L = .{i}; + const hd = c.text.heads(i); + const q: usize = @as(usize, hd.q) * hd.dim; + const kv: usize = @as(usize, hd.kv) * hd.dim; + w.mlp_queries[k] = try l.tensor(ck, "model.llm.attn_res.mlp_queries.{d}", L, .f32, &.{h}); + if (i == 0) { + w.attn_queries[k] = 0; + } else if (config.isGlobal(i)) { + w.attn_queries[k] = try l.tensor(ck, "model.llm.attn_res.attn_queries.{d}", .{i - 1}, .f32, &.{ 3, h }); + } else { + w.attn_queries[k] = try l.tensor(ck, "model.llm.attn_res.attn_queries.{d}", .{i - 1}, .f32, &.{h}); + } + const A = struct { + fn put(loader: *Loader, checkpoint: *core.Checkpoint, comptime fmt: []const u8, args: anytype, dims: []const usize) !u64 { + return loader.tensor(checkpoint, fmt, args, .bf16, dims); + } + }; + layer.attn = .{ + .wq = try A.put(&l, ck, "model.llm.layers.{d}.attn.wq_du.weight", L, &.{ q, h }), + .wk = try A.put(&l, ck, "model.llm.layers.{d}.attn.wk_dv.weight", L, &.{ kv, h }), + .wv = try A.put(&l, ck, "model.llm.layers.{d}.attn.wv_dv.weight", L, &.{ kv, h }), + .wr = try A.put(&l, ck, "model.llm.layers.{d}.attn.wr_du.weight", L, &.{ @as(usize, hd.q) * c.text.d_rel, h }), + .wo = try A.put(&l, ck, "model.llm.layers.{d}.attn.wo_ud.weight", L, &.{ h, q }), + .gate = try A.put(&l, ck, "model.llm.layers.{d}.attn.gate_attn.weight", L, &.{ q, h }), + .sink = try A.put(&l, ck, "model.llm.layers.{d}.attn.attn_sink_proj.weight", L, &.{ hd.q, h }), + .q_scale = try A.put(&l, ck, "model.llm.layers.{d}.attn.q_l2_clip.scale", L, &.{ hd.q, hd.dim }), + .rel_scale = try A.put(&l, ck, "model.llm.layers.{d}.attn.rel_l2_clip.scale", L, &.{ hd.q, c.text.d_rel }), + .rel_proj = try A.put(&l, ck, "model.llm.layers.{d}.attn.rel_logits_proj.proj", L, &.{ c.text.d_rel, c.text.extent(i) }), + .k_conv = undefined, + .v_conv = undefined, + .norms = undefined, + }; + inline for ([2][]const u8{ "k", "v" }, 0..) |kind, j| { + const conv = if (config.isGlobal(i)) + try A.put(&l, ck, "model.llm.layers.{d}.attn." ++ kind ++ "_sconv.static_w", L, &.{ config.conv_taps, kv }) + else + try A.put(&l, ck, "model.llm.layers.{d}.attn." ++ kind ++ "_sconv.weight", L, &.{ kv, 1, config.conv_taps }); + if (j == 0) layer.attn.k_conv = conv else layer.attn.v_conv = conv; + if (config.isGlobal(i)) { + const dyn = try A.put(&l, ck, "model.llm.layers.{d}.attn." ++ kind ++ "_sconv.weight_proj", L, &.{ @as(usize, hd.kv) * config.conv_taps, h }); + if (j == 0) layer.attn.k_dynamic = dyn else layer.attn.v_dynamic = dyn; + } + const norm = if (config.isGlobal(i)) + try A.put(&l, ck, "model.llm.layers.{d}." ++ kind ++ "_input_norm.weight", L, &.{h}) + else if (j == 0) + try A.put(&l, ck, "model.llm.layers.{d}.attn_norm.weight", L, &.{h}) + else + layer.attn.norms[1]; // a sliding layer's k and v share one attn_norm upload + layer.attn.norms[j + 1] = norm; + } + layer.attn.norms[0] = if (config.isGlobal(i)) + try A.put(&l, ck, "model.llm.layers.{d}.q_input_norm.weight", L, &.{h}) + else + layer.attn.norms[1]; + layer.attn_conv = try A.put(&l, ck, "model.llm.layers.{d}.attn_sconv.weight", L, &.{ h, 1, config.conv_taps }); + layer.mlp_norm = try A.put(&l, ck, "model.llm.layers.{d}.mlp_norm.weight", L, &.{h}); + layer.mlp_conv = try A.put(&l, ck, "model.llm.layers.{d}.mlp_sconv.weight", L, &.{ h, 1, config.conv_taps }); + layer.router = try A.put(&l, ck, "model.llm.layers.{d}.mlp.gate.weight", L, &.{ c.text.experts, h }); + layer.router_bias = try l.tensor(ck, "model.llm.layers.{d}.mlp.gate.bias", L, .f32, &.{c.text.experts}); + var prefix: [96]u8 = undefined; + layer.experts = try modelopt.load(&l, ck, try std.fmt.bufPrint(&prefix, "model.llm.layers.{d}.mlp.experts.", L), formats[k], c.text.experts, h, c.text.expert_inter); + @memset(&layer.controllers, .{ .down = 0, .forget = 0, .gain = 0 }); + const lp = c.text.loop.?; + if (i >= lp.core_start and i < lp.core_end) try controllers(&l, ck, &c.text, i, lp.gate_rank, &layer.controllers); + } + if (ck.unused() != 0) return error.UnusedCheckpointTensor; + return w; +} diff --git a/zig/src/families/inkling2/metal/attention.zig b/zig/src/families/inkling2/metal/attention.zig new file mode 100644 index 00000000000..8b5b4c8f39b --- /dev/null +++ b/zig/src/families/inkling2/metal/attention.zig @@ -0,0 +1,92 @@ +//! Real Metal pipeline loading and encoder dispatch for Inkling 2 Mini attention. +const std = @import("std"); +const mtl = @import("metal"); +const src = @import("inkling2_metal"); +pub const planning = @import("attention_plan.zig"); + +pub const Ref = struct { buf: mtl.Buffer, off: usize = 0 }; +pub const Cache = struct { k: Ref, v: Ref }; +pub const RowMeta = struct { pos: Ref, seg_of: Ref, segs: Ref }; + +pub const Kernels = struct { + scalar_lib: mtl.Library, + prompt_lib: mtl.Library, + prep: mtl.Pipeline, + rel_table: mtl.Pipeline, + decode: mtl.Pipeline, + merge: mtl.Pipeline, + prompt: mtl.Pipeline, + units: bool, + + pub fn init(a: std.mem.Allocator, device: mtl.Device) !Kernels { + var scalar_lib = try mtl.Library.fromSource(device, src.attention, mtl.CompileOptions.mlx()); + errdefer scalar_lib.deinit(); + const units = device.tensorUnits(); + const prompt_src = try a.dupe(u8, if (units) src.prompt_attention else src.prompt_attention_pre_m5); + defer a.free(prompt_src); + var prompt_lib = try mtl.Library.fromSource(device, prompt_src, mtl.CompileOptions.mlx()); + errdefer prompt_lib.deinit(); + var pipes: [5]mtl.Pipeline = undefined; + var made: usize = 0; + errdefer for (pipes[0..made]) |pipe| pipe.deinit(); + for ([_]mtl.Library{ scalar_lib, scalar_lib, scalar_lib, scalar_lib, prompt_lib }, [_][]const u8{ "tf_ink2_prep", "tf_ink2_rel_table", "tf_ink2_attn_scalar", "tf_ink2_merge", "tf_ink2_attn_prompt" }, &pipes) |lib, name, *pipe| { + pipe.* = try mtl.Pipeline.init(device, lib, name, false); + made += 1; + } + return .{ .scalar_lib = scalar_lib, .prompt_lib = prompt_lib, .prep = pipes[0], .rel_table = pipes[1], .decode = pipes[2], .merge = pipes[3], .prompt = pipes[4], .units = units }; + } + pub fn deinit(k: *Kernels) void { + k.prompt.deinit(); + k.merge.deinit(); + k.decode.deinit(); + k.rel_table.deinit(); + k.prep.deinit(); + k.prompt_lib.deinit(); + k.scalar_lib.deinit(); + k.* = undefined; + } +}; + +fn bind(e: mtl.ComputeEncoder, refs: []const Ref, first: usize) void { + for (refs, first..) |r, slot| e.setBuffer(r.buf, r.off, slot); +} + +/// raw holds independent q/k/v rows followed by q-side relative rows; gated sliding visits never infer K or V from Q. +pub fn prep(k: *const Kernels, e: mtl.ComputeEncoder, r: planning.Rows, l: planning.Layer, c: planning.Prep, meta: RowMeta, raw: [4]Ref, scales: [2]Ref, q: Ref, rel: Ref, kv: Cache) void { + e.setPipeline(k.prep); + bind(e, &raw, 0); + bind(e, &scales, 4); + bind(e, &.{ meta.pos, meta.seg_of, meta.segs, q, rel, kv.k, kv.v }, 6); + e.setValue(planning.PrepArgs{ .heads = r.heads, .kv_heads = r.kv_heads, .ring = l.ring, .global = @intFromBool(l.tau), .qk_clip = c.qk_clip, .rel_clip = c.rel_clip, .floor_pos = c.floor, .alpha = c.alpha, .eps = c.eps }, 13); + e.dispatchGroups(mtl.Size.of(r.rows, r.heads + 2 * r.kv_heads, 1), mtl.Size.of(32, 1, 1)); +} + +pub fn relTable(k: *const Kernels, e: mtl.ComputeEncoder, r: planning.Rows, rel: Ref, proj: Ref, tab: Ref) void { + e.setPipeline(k.rel_table); + bind(e, &.{ rel, proj, tab }, 0); + e.dispatchGroups(mtl.Size.of(r.rows * r.heads, 1, 1), mtl.Size.of(256, 1, 1)); +} + +pub fn attend(k: *const Kernels, e: mtl.ComputeEncoder, r: planning.Rows, l: planning.Layer, stride: u32, slots: usize, meta: RowMeta, q: Ref, kv: Cache, tab: Ref, part_o: Ref, part_ml: Ref, sink: Ref, gate: Ref, out: Ref) !void { + const launch = try planning.attend(r, l, stride, slots); + const scale: f32 = 1.0 / @sqrt(@as(f32, planning.head_dim)); + if (launch.path == .decode) { + e.setPipeline(k.decode); + bind(e, &.{ q, kv.k, kv.v, tab, meta.segs, part_o, part_ml, meta.pos, meta.seg_of }, 0); + e.setValue(planning.AttnArgs{ .heads = r.heads, .kv_heads = r.kv_heads, .ring = l.ring, .window = l.window, .chunk = l.chunk, .c0 = 0, .chunks = launch.partials_rh, .scale = scale }, 9); + } else { + e.setPipeline(k.prompt); + bind(e, &.{ q, kv.k, kv.v, tab, meta.segs, part_o, part_ml }, 0); + e.setValue(planning.PromptArgs{ .heads = r.heads, .kv_heads = r.kv_heads, .ring = l.ring, .chunk = l.chunk, .c0 = 0, .chunks = launch.partials_rh, .scale = scale }, 7); + } + e.dispatchGroups(mtl.Size.of(launch.grid[0], launch.grid[1], launch.grid[2]), mtl.Size.of(launch.threads, 1, 1)); + e.barrier(); + e.setPipeline(k.merge); + bind(e, &.{ part_o, part_ml, sink, gate, meta.pos, out }, 0); + e.setValue(planning.MergeArgs{ .heads = r.heads, .window = l.window, .chunk = l.chunk, .c0 = 0, .chunks = launch.partials_rh, .subs = launch.subs }, 6); + e.dispatchGroups(mtl.Size.of(launch.merge_grid[0], 1, 1), mtl.Size.of(planning.merge_threads, 1, 1)); +} + +test { + _ = @import("attention_plan.zig"); +} diff --git a/zig/src/families/inkling2/metal/attention_plan.zig b/zig/src/families/inkling2/metal/attention_plan.zig new file mode 100644 index 00000000000..6688dc8d7a0 --- /dev/null +++ b/zig/src/families/inkling2/metal/attention_plan.zig @@ -0,0 +1,98 @@ +//! Pure host geometry and ABI declarations for Inkling 2 Mini Metal attention. +const std = @import("std"); + +pub const head_dim = 128; +pub const d_rel = 16; +pub const extent = 1024; +pub const tile_keys = 64; +pub const sliding_chunk = 256; +pub const global_chunk = 16384; +pub const global_sub = 1024; +pub const subs = global_chunk / global_sub; +pub const split_rows = 64; +pub const prompt_pairs = 128; +pub const prompt_threads = 256; +pub const decode_threads = 32; +pub const merge_threads = head_dim; + +pub const Seg = extern struct { row0: i32, n: i32, p0: i32, pad: i32 = 0, off: i64 }; +pub const PrepArgs = extern struct { + heads: u32, + kv_heads: u32, + ring: u32, + global: u32, + qk_clip: f32, + rel_clip: f32, + floor_pos: f32, + alpha: f32, + eps: f32, +}; +pub const AttnArgs = extern struct { heads: u32, kv_heads: u32, ring: u32, window: u32, chunk: u32, c0: u32, chunks: u32, scale: f32 }; +pub const MergeArgs = extern struct { heads: u32, window: u32, chunk: u32, c0: u32, chunks: u32, subs: u32 = 1 }; +pub const PromptArgs = extern struct { heads: u32, kv_heads: u32, ring: u32, chunk: u32, c0: u32, chunks: u32, scale: f32 }; +comptime { + if (@sizeOf(Seg) != 24 or @sizeOf(PrepArgs) != 36 or @sizeOf(AttnArgs) != 32) @compileError("Inkling attention ABI drift"); + if (@sizeOf(MergeArgs) != 24 or @sizeOf(PromptArgs) != 28) @compileError("Inkling prompt ABI drift"); +} + +pub const Layer = struct { + window: u32, + ring: u32, + chunk: u32, + tau: bool, + pub fn sliding(window: u32, rows: u32) Layer { + return .{ .window = window, .ring = ringFor(window, rows), .chunk = sliding_chunk, .tau = false }; + } + pub fn global(capacity: u32) Layer { + return .{ .window = 0, .ring = @intCast(std.mem.alignForward(usize, capacity, tile_keys)), .chunk = global_chunk, .tau = true }; + } + pub fn cacheBytes(l: Layer, kv: usize) usize { + return @as(usize, l.ring) * kv * head_dim * 2; + } +}; +pub const Prep = struct { qk_clip: f32 = 22.627416997969522, rel_clip: f32 = 8, floor: f32 = 8192, alpha: f32 = 0.1, eps: f32 = 1e-6 }; +pub const Rows = struct { rows: u32, heads: u32 = 24, kv_heads: u32 = 8, last_pos: u32, streams: u32 = 1 }; + +pub fn ringFor(window: u32, rows: u32) u32 { + return @intCast(std.mem.alignForward(usize, @as(usize, window) + rows - 1, tile_keys)); +} +pub fn chunks(last_pos: usize, chunk: u32) u32 { + return @intCast(last_pos / chunk + 1); +} +pub fn slotsFor(l: Layer, context: usize) u32 { + if (l.window > 0) return (l.window - 1) / l.chunk + 2; + return chunks(context - 1, l.chunk); +} +pub fn split(r: Rows, stride: u32, slots: usize) bool { + return r.rows <= split_rows and @as(usize, r.rows) * r.heads * stride * subs <= slots; +} +pub fn usePrompt(r: Rows, l: Layer, stride: u32, slots: usize) bool { + return l.window == 0 and r.streams == 1 and !split(r, stride, slots); +} +pub fn partialSlot(l: Layer, c: usize, pos: usize) ?usize { + const lo = if (l.window > 0) (pos + 1) -| l.window else 0; + if (c < lo / l.chunk or c > pos / l.chunk) return null; + return c - lo / l.chunk; +} +pub fn tableBytes(rows: usize, heads: u32) usize { + return rows * heads * extent * 2; +} +pub fn partialBytes(rows: usize, heads: u32, n_chunks: u32) usize { + return rows * heads * n_chunks * (head_dim * 4 + 8); +} + +pub const Path = enum { decode, prompt }; +pub const Launch = struct { path: Path, grid: [3]u32, threads: u32, merge_grid: [3]u32, partials_rh: u32, subs: u32 = 1 }; +pub fn attend(r: Rows, l: Layer, stride: u32, slots: usize) error{Inkling2Partials}!Launch { + if (slotsFor(l, @as(usize, r.last_pos) + 1) > stride) return error.Inkling2Partials; + const merge_grid = [3]u32{ r.rows * r.heads, 1, 1 }; + if (usePrompt(r, l, stride, slots)) { + const blocks = std.math.divCeil(u32, r.rows * (r.heads / r.kv_heads), prompt_pairs) catch unreachable; + return .{ .path = .prompt, .grid = .{ blocks, r.kv_heads, stride }, .threads = prompt_threads, .merge_grid = merge_grid, .partials_rh = stride }; + } + return .{ .path = .decode, .grid = .{ r.rows * r.heads, stride, 1 }, .threads = decode_threads, .merge_grid = merge_grid, .partials_rh = stride }; +} + +test { + _ = @import("attention_test.zig"); +} diff --git a/zig/src/families/inkling2/metal/attention_test.zig b/zig/src/families/inkling2/metal/attention_test.zig new file mode 100644 index 00000000000..3a8e73a3deb --- /dev/null +++ b/zig/src/families/inkling2/metal/attention_test.zig @@ -0,0 +1,63 @@ +//! Host-only Mini window, ring, tau and dispatch/ABI checks; no Metal import. +const std = @import("std"); +const p = @import("attention_plan.zig"); +const t = std.testing; + +fn tau(pos: usize) f64 { + return 1 + 0.1 * @log(@max(@as(f64, @floatFromInt(pos + 1)) / 8192, 1)); +} + +test "inkling2 metal ABI matches the shaders" { + try t.expectEqual(@as(usize, 24), @sizeOf(p.Seg)); + try t.expectEqual(@as(usize, 36), @sizeOf(p.PrepArgs)); + try t.expectEqual(@as(usize, 24), @sizeOf(p.MergeArgs)); + try t.expectEqual(@as(usize, 28), @sizeOf(p.PromptArgs)); + try t.expectEqual(@as(u32, 24), (p.Rows{ .rows = 1, .last_pos = 0 }).heads); + try t.expectEqual(@as(u32, 8), (p.Rows{ .rows = 1, .last_pos = 0 }).kv_heads); + try t.expectEqual(@as(f32, 8192), (p.Prep{}).floor); +} + +test "inkling2 metal Mini ring and window boundaries" { + try t.expectEqual(@as(u32, 1024), p.ringFor(1024, 1)); + try t.expectEqual(@as(u32, 1088), p.ringFor(1024, 2)); + try t.expectEqual(@as(u32, 3072), p.Layer.sliding(1024, 2048).ring); + const l = p.Layer.sliding(1024, 1); + try t.expectEqual(@as(u32, 5), p.slotsFor(l, 1048576)); + try t.expectEqual(@as(?usize, 3), p.partialSlot(l, 3, 1023)); + try t.expectEqual(@as(?usize, null), p.partialSlot(l, 4, 1023)); + try t.expectEqual(@as(?usize, 4), p.partialSlot(l, 4, 1024)); + try t.expectEqual(@as(?usize, 3), p.partialSlot(l, 7, 2047)); + try t.expectEqual(@as(usize, 1023), @as(usize, 8191) % 1024); + try t.expectEqual(@as(usize, 0), @as(usize, 8192) % 8192); +} + +test "inkling2 metal tau starts strictly above its 8192 floor" { + try t.expectEqual(@as(f64, 1), tau(0)); + try t.expectEqual(@as(f64, 1), tau(8191)); + try t.expect(tau(8192) > 1); + try t.expectApproxEqAbs(1 + 0.1 * @log(@as(f64, 2)), tau(16383), 1e-15); +} + +test "inkling2 metal decode and prompt dispatch geometry" { + const sl = p.Layer.sliding(1024, 8); + const sr = p.Rows{ .rows = 8, .last_pos = 4095, .streams = 2 }; + const sd = try p.attend(sr, sl, 5, 8 * 24 * 5); + try t.expectEqual(p.Path.decode, sd.path); + try t.expectEqual([3]u32{ 192, 5, 1 }, sd.grid); + try t.expectEqual([3]u32{ 192, 1, 1 }, sd.merge_grid); + try t.expectEqual(@as(u32, 32), sd.threads); + const gl = p.Layer.global(1048576); + const one = p.Rows{ .rows = 1, .last_pos = 1048575 }; + const gd = try p.attend(one, gl, 64, 24 * 64 * p.subs - 1); + try t.expectEqual(p.Path.prompt, gd.path); + try t.expectEqual([3]u32{ 1, 8, 64 }, gd.grid); + try t.expectEqual(@as(u32, 256), gd.threads); + const streamed = p.Rows{ .rows = 1, .last_pos = 1048575, .streams = 2 }; + const scalar = try p.attend(streamed, gl, 64, 0); + try t.expectEqual(p.Path.decode, scalar.path); + try t.expectEqual([3]u32{ 24, 64, 1 }, scalar.grid); + try t.expectError(error.Inkling2Partials, p.attend(streamed, gl, 63, 0)); + const prompt = try p.attend(.{ .rows = 130, .last_pos = 20000 }, gl, 2, 130 * 24 * 2); + try t.expectEqual(p.Path.prompt, prompt.path); + try t.expectEqual([3]u32{ 4, 8, 2 }, prompt.grid); // ceil(130 * 3 / 128) +} diff --git a/zig/src/families/inkling2/metal/backend.zig b/zig/src/families/inkling2/metal/backend.zig new file mode 100644 index 00000000000..b7faf6dab82 --- /dev/null +++ b/zig/src/families/inkling2/metal/backend.zig @@ -0,0 +1,468 @@ +//! Inkling 2 Mini behind the lane engine: independent visit state and exact copy-window rollback. +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 cfg = @import("../config.zig"); +const be = lanes.backend; + +pub const Options = struct { capacity: usize, streams: u32 = 4, budget: u64 }; +const ring = 4096; + +/// The prompt cache gets the bytes left by live streams and never evicts the state being restored. +pub const Room = struct { ctx: *anyopaque, fit: *const fn (ctx: *anyopaque, bytes: u64, restoring: ?*anyopaque, prompt: []const u32) void }; + +/// Mini's DSpark ABI is fixed: four visit taps in checkpoint order. +pub fn validateTaps(c: *const cfg.Config, taps: []const u32) !void { + const mtp = c.mtp orelse return error.UnsupportedInkling2Taps; + const expected = [_]u32{ 5, 23, 41, 48 }; + if (mtp.taps_n != expected.len or !std.mem.eql(u32, mtp.taps[0..mtp.taps_n], &expected) or !std.mem.eql(u32, taps, &expected)) + return error.UnsupportedInkling2Taps; +} + +pub const Metal = struct { + gpa: std.mem.Allocator, + model: *Model, + options: Options, + scratch: st.Scratch, + prompt: st.Scratch, + caches: std.AutoHashMapUnmanaged(*lanes.Stream, *st.Cache) = .empty, + held: u64 = 0, + room: ?Room = null, + tokens: []u32, + next: u64 = 0, + values: []f32, + prepared: bool = false, + sink: ?be.FeatureSink = null, + tap_gen: u64 = 0, + + 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, st.batch_rows); + errdefer scratch.deinit(); + var prompt = try st.Scratch.init(model.device, st.prompt_rows); + errdefer prompt.deinit(); + const tokens = try gpa.alloc(u32, ring); + errdefer gpa.free(tokens); + const values = try gpa.alloc(f32, model.config.text.unpadded_vocab); + out.* = .{ .gpa = gpa, .model = model, .options = options, .scratch = scratch, .prompt = prompt, .tokens = tokens, .values = values }; + return out; + } + + pub fn deinit(self: *Metal) void { + 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.free(self.tokens); + self.gpa.free(self.values); + self.gpa.destroy(self); + } + + 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, capacity, &self.model.weight_plan); + return cache; + } + + pub fn facts(self: *const Metal) lanes.Model { + return .{ .exact_width = st.window_rows, .gpu_tokens = false, .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 }; + } + + fn prepareFn(ptr: *anyopaque, taps: []const u32) !void { + const self = cast(ptr); + try validateTaps(&self.model.config, taps); + if (self.prepared) return; + const device = self.model.device; + const decode = self.scratch.taps orelse try device.buffer(st.captureBytes(st.batch_rows), mtl.ResourceOptions.shared); + errdefer if (self.scratch.taps == null) decode.deinit(); + const prompt = self.prompt.taps orelse try device.buffer(st.captureBytes(st.prompt_rows), mtl.ResourceOptions.shared); + errdefer if (self.prompt.taps == null) prompt.deinit(); + self.scratch.taps = decode; + self.prompt.taps = prompt; + self.prepared = true; + } + + fn featuresFn(ptr: *anyopaque, stream: *lanes.Stream, taps: []const u32, start: u64, count: u32) !be.Features { + const self = cast(ptr); + try validateTaps(&self.model.config, taps); + if (!self.prepared) return error.UnpreparedInkling2Taps; + const tp = (try self.cacheOf(stream)).tap; + const buf = tp.buf orelse return error.Inkling2TapsNotHeld; + const off = try st.featureOffset(tp, start, count, self.tap_gen); + return .{ .buffer = @intFromPtr(buf.id), .offset = off, .rows = count, .row_bytes = @intCast(st.feature_row_bytes), .space = .device, .dtype = .bf16 }; + } + + fn prefillFeaturesFn(ptr: *anyopaque, stream: *lanes.Stream, taps: []const u32, sink: be.FeatureSink) !void { + const self = cast(ptr); + try validateTaps(&self.model.config, taps); + if (!self.prepared) return error.UnpreparedInkling2Taps; + self.sink = sink; + defer self.sink = null; + return prefillFn(ptr, stream); + } + + fn nextTapGeneration(self: *Metal) u64 { + self.tap_gen +%= 1; + return self.tap_gen; + } + + pub fn backend(self: *Metal) be.Backend { + return .{ .keep_full_lone = true, .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.UnknownInklingStream; + } + + fn vocab(self: *const Metal) usize { + return self.model.config.text.unpadded_vocab; + } + + fn logits(self: *Metal, cache: *st.Cache) []const f32 { + return cache.logits.slice(f32, self.vocab()); + } + + fn draw(self: *Metal, l: []const f32, sampling: ?lanes.Sampling, position: u64, mask: []const u32) !u32 { + const t = sampled(sampling) orelse { + var best: ?usize = null; + for (l, 0..) |w, id| { + if (mask.len > 0 and !lanes.grammar.allows(mask, id)) continue; + if (best == null or w > l[best.?]) best = id; + } + return @intCast(best orelse return error.InklingEmptyTokenMask); + }; + const values = if (mask.len == 0) l else blk: { + for (l, self.values, 0..) |w, *v, id| v.* = if (lanes.grammar.allows(mask, id)) w else -std.math.inf(f32); + break :blk self.values; + }; + return lanes.gpu_full.draw(self.gpa, 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; + } + + fn take(self: *Metal) u64 { + const h = self.next; + self.next += 1; + return h; + } + + fn put(self: *Metal, token: u32) u64 { + const h = self.take(); + self.tokens[h % ring] = token; + return h; + } + + fn feed(self: *Metal, cache: *st.Cache, ids: []const u32, stream: ?*lanes.Stream) !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 capture = self.prepared and stream != null; + if (capture) _ = self.nextTapGeneration(); + const taps: ?st.Ref = if (capture) .{ .buf = s.taps.? } else null; + try fwd.run(self.model, s, cache, ids[at..end], .{ .taps = taps }); + if (capture) { + const rows = end - at; + if (self.sink) |k| try k.take(k.ptr, stream.?, .{ + .buffer = @intFromPtr(s.taps.?.id), + .offset = 0, + .rows = @intCast(rows), + .row_bytes = @intCast(st.feature_row_bytes), + .space = .device, + .dtype = .bf16, + }, @intCast(cache.len)); + if (base + end == stream.?.prompt().len) { + if (cache.last_tap == null) { + cache.last_tap = try self.model.device.buffer(st.feature_row_bytes, mtl.ResourceOptions.shared); + if (cache.follow) |f| f.join(f.ctx, cache.last_tap.?); + } + const bytes = s.taps.?.slice(u8, rows * st.feature_row_bytes); + @memcpy(cache.last_tap.?.slice(u8, st.feature_row_bytes), bytes[(rows - 1) * st.feature_row_bytes ..][0..st.feature_row_bytes]); + cache.tap = .{ .buf = cache.last_tap, .start = @intCast(cache.len + rows - 1), .rows = 1 }; + } + } + cache.len += end - at; + if (stream) |sm| lanes.prefill_widths.completed(self.gpa, sm, 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); + const ids = stream.prompt(); + if (ids.len == 0 or ids.len + stream.max_new > self.options.capacity or self.caches.contains(stream)) return error.InvalidInklingPrompt; + if (stream.images.len > 0) return error.InklingHasNoImageTower; + const need = st.cacheBytes(ids.len + stream.max_new); + if (self.held + need > self.options.budget) { + std.log.warn("inkling2_loop: a stream needs {d:.1} GiB of state; {d:.1} of {d:.1} GiB are held", .{ gib(need), gib(self.held), gib(self.options.budget) }); + return error.InklingStateFull; + } + self.held += need; + errdefer self.held -= need; + if (self.room) |r| r.fit(r.ctx, self.options.budget - self.held, stream.reuse.saved, ids); + const cache = try self.createCache(ids.len + stream.max_new); + errdefer self.gpa.destroy(cache); + errdefer cache.deinit(); + try self.caches.put(self.gpa, stream, cache); + errdefer _ = self.caches.remove(stream); + stream.cached = 0; + if (stream.reuse.saved) |saved| { + const snap: *const snapshot.Snap = @ptrCast(@alignCast(saved)); + if (snap.at < ids.len) { + if (snapshot.restore(cache, self.model.queue, snap)) stream.cached = @intCast(snap.at) else |_| stream.reuse_failed = true; + } else stream.reuse_failed = true; + } + try self.feed(cache, ids[cache.len..], stream); + } + + pub fn warm(self: *Metal) !void { + var cache = try st.Cache.init(self.model.device, st.prompt_rows + st.window_rows, &self.model.weight_plan); + defer cache.deinit(); + var ids: [st.prompt_rows]u32 = undefined; + for (&ids, 0..) |*t, i| t.* = @intCast(1000 + i * 37 % 20000); + try self.feed(&cache, &ids, null); + try fwd.run(self.model, &self.scratch, &cache, ids[0..st.window_rows], .{ .all = true }); + } + + 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 { + const cache = try self.cacheOf(stream); + if (position != cache.len or cache.pending != null) return error.InvalidInklingPosition; + return self.put(try self.draw(self.logits(cache), stream.sampling, position, mask)); + } + + fn queueFn(ptr: *anyopaque, stream: *lanes.Stream, what: be.Feed, position: u64) !u64 { + const self = cast(ptr); + const cache = try self.cacheOf(stream); + if (position != cache.len + 1 or cache.pending != null) return error.InvalidInklingPosition; + const token = switch (what) { + .handle => |h| try self.read(h), + .value => |v| v, + }; + if (token >= self.vocab()) return error.InvalidInklingToken; + const generation = if (self.prepared) self.nextTapGeneration() else 0; + const taps: ?st.Ref = if (self.prepared) .{ .buf = self.scratch.taps.? } else null; + try fwd.run(self.model, &self.scratch, cache, &.{token}, .{ .taps = taps }); + if (self.prepared) cache.tap = .{ .buf = self.scratch.taps, .start = @intCast(cache.len), .rows = 1, .gen = generation }; + cache.len += 1; + return self.put(try self.draw(self.logits(cache), stream.sampling, position, &.{})); + } + + fn read(self: *Metal, handle: u64) !u32 { + if (handle >= self.next) return error.InvalidInklingTokenHandle; + const token = self.tokens[handle % ring]; + if (token >= self.vocab()) return error.InvalidInklingToken; + return token; + } + + fn readFn(ptr: *anyopaque, handle: u64) !u32 { + return cast(ptr).read(handle); + } + + fn firstRowFn(ptr: *anyopaque, stream: *lanes.Stream) !lanes.LogprobRow { + const self = cast(ptr); + const l = self.logits(try self.cacheOf(stream)); + return firstLogprobRow(l, self.tokens, self.next, stream.logprobs orelse 0); + } + + fn verifyFn(ptr: *anyopaque, windows: []const be.Window, out: []be.Verified) !void { + const self = cast(ptr); + const words = maskWords(self.model.config.text.vocab); + if (windows.len != out.len or windows.len > st.batch_rows) return error.InvalidInklingWindows; + var segments: [st.batch_rows]fwd.Segment = undefined; + var ids: [st.batch_rows]u32 = undefined; + var total: usize = 0; + var begun: usize = 0; + errdefer for (segments[0..begun]) |seg| seg.cache.rollback(self.model.queue) catch {}; + for (windows, out, 0..) |w, o, i| { + const rows = w.rows(); + if (rows == 0 or 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 or w.positions.len != rows) return error.UnsupportedInklingWindow; + if (w.masks.len != 0 and w.masks.len != rows * words) return error.InvalidInklingMasks; + const cache = try self.cacheOf(w.stream); + if (cache.pending != null) return error.InklingWindowAlreadyOpen; + for (w.positions, 0..) |p, r| if (p != cache.len + r + 1) return error.InvalidInklingPosition; + segments[i] = .{ .cache = cache, .rows = rows }; + ids[total] = w.pending; + @memcpy(ids[total + 1 ..][0..w.tokens.len], w.tokens); + total += rows; + } + for (segments[0..windows.len]) |seg| { + try seg.cache.begin(self.model.queue, seg.rows); + begun += 1; + } + const generation = if (self.prepared) self.nextTapGeneration() else 0; + const taps: ?st.Ref = if (self.prepared) .{ .buf = self.scratch.taps.? } else null; + try fwd.runShared(self.model, &self.scratch, segments[0..windows.len], ids[0..total], .{ .all = true, .taps = taps }); + const all = self.scratch.logits_all.slice(f32, total * self.vocab()); + var base: usize = 0; + for (windows, out, segments[0..windows.len]) |w, o, seg| { + if (self.prepared) seg.cache.tap = .{ .buf = self.scratch.taps, .off = base * st.feature_row_bytes, .start = @intCast(seg.cache.len), .rows = seg.rows, .gen = generation }; + @memcpy(o.drafts, w.tokens); + for (0..seg.rows) |r| { + const l = all[(base + r) * self.vocab() ..][0..self.vocab()]; + const mask = maskRow(w.masks, words, r); + o.sampled[r] = try self.draw(l, w.stream.sampling, w.positions[r], mask); + if (o.rows.len == seg.rows) o.rows[r] = logprobRow(l, o.sampled[r], w.stream.logprobs orelse 0); + } + @memcpy(seg.cache.logits.slice(f32, self.vocab()), all[(base + seg.rows - 1) * self.vocab() ..][0..self.vocab()]); + base += seg.rows; + } + } + + fn keepFn(ptr: *anyopaque, windows: []const be.Window, paths: []const []const u32) !void { + const self = cast(ptr); + if (windows.len != paths.len) return error.InvalidInklingWindows; + for (windows, paths) |w, path| { + const cache = try self.cacheOf(w.stream); + for (path, 0..) |r, i| if (r != i) return error.UnsupportedInklingTree; + if (path.len == 0 or path.len > w.rows() or cache.pending == null or cache.pending.? != w.rows()) return error.UnsupportedInklingWindow; + try cache.commit(self.model.queue, path.len); + } + } + + fn draftFn(ptr: *anyopaque, requests: []const be.DraftRequest) !void { + _ = ptr; + for (requests) |r| if (r.depth != 0 or r.lanes != null or r.plan != null) return error.InklingHasNoDraftHead; + } + + fn heldFn(_: *anyopaque, _: *lanes.Stream, out: []u32) !void { + if (out.len > 0) return error.InklingDraftsNotHeld; + } + + fn releaseFn(ptr: *anyopaque, stream: *lanes.Stream) void { + const self = cast(ptr); + if (self.caches.fetchRemove(stream)) |entry| { + const cache = entry.value; + if (cache.pending != null) cache.rollback(self.model.queue) catch |err| std.log.err("inkling2_loop rollback at release: {s}", .{@errorName(err)}); + self.held -= st.cacheBytes(cache.capacity); + cache.deinit(); + self.gpa.destroy(cache); + if (self.room) |r| r.fit(r.ctx, self.options.budget - self.held, null, &.{}); + } + } + + pub fn snapBytes(ptr: *anyopaque, at: u32) u64 { + _ = ptr; + return snapshot.bytes(at); + } + + pub fn snapSave(ptr: *anyopaque, owner: ?*anyopaque, at: u32) anyerror!*anyopaque { + const self = cast(ptr); + const cache = try self.cacheOf(@ptrCast(@alignCast(owner orelse return error.NoStream))); + if (cache.len != at or cache.pending != null) 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, cache); + return snap; + } + + pub fn snapRestore(_: *anyopaque, _: ?*anyopaque, _: *anyopaque) anyerror!void { + return error.BackendRestores; + } + + pub fn snapDrop(ptr: *anyopaque, saved: *anyopaque) void { + const snap: *snapshot.Snap = @ptrCast(@alignCast(saved)); + snap.free(); + cast(ptr).gpa.destroy(snap); + } +}; + +/// A grammar mask's words a row: a bit a token of the tokenizer's vocabulary, padding included. +fn maskWords(vocab: u32) usize { + return (@as(usize, vocab) + 31) / 32; +} + +/// Row `r` of a window's masks, or none where the window has none. +fn maskRow(masks: []const u32, words: usize, r: usize) []const u32 { + return if (masks.len == 0) &.{} else masks[r * words ..][0..words]; +} + +test "a window's masks step by the padded vocabulary's words" { + const words = maskWords(201024); + try std.testing.expectEqual(@as(usize, 6282), words); + var masks: [3 * 6282]u32 = @splat(0); + masks[2 * 6282] = 1; + try std.testing.expectEqual(@as(usize, 0), maskRow(&.{}, words, 2).len); + try std.testing.expectEqual(@as(u32, 0), maskRow(&masks, words, 1)[0]); + try std.testing.expect(lanes.grammar.allows(maskRow(&masks, words, 2), 0)); + try std.testing.expect(!lanes.grammar.allows(maskRow(&masks, words, 1), 0)); +} + +fn gib(bytes: u64) f64 { + return @as(f64, @floatFromInt(bytes)) / (1 << 30); +} + +fn firstLogprobRow(l: []const f32, tokens: []const u32, next: usize, count: u8) lanes.LogprobRow { + std.debug.assert(tokens.len == ring and next > 0); + return logprobRow(l, tokens[(next - 1) % ring], count); +} + +fn logprobRow(l: []const f32, pick: u32, count: u8) lanes.LogprobRow { + const top = lanes.logprob.max_top; + var most: f64 = -std.math.inf(f64); + for (l) |w| most = @max(most, w); + var sum: f64 = 0; + for (l) |w| sum += @exp(@as(f64, w) - most); + const lse: f32 = @floatCast(most + @log(sum)); + var r: lanes.LogprobRow = .{ .token = pick, .logprob = l[pick] - lse, .count = 0 }; + var filled: usize = 0; + for (l, 0..) |w, id| { + if (filled == top and w <= r.logprobs[top - 1] + lse) continue; + var at = @min(filled, top - 1); + while (at > 0 and w > r.logprobs[at - 1] + lse) : (at -= 1) { + r.ids[at] = r.ids[at - 1]; + r.logprobs[at] = r.logprobs[at - 1]; + } + r.ids[at] = @intCast(id); + r.logprobs[at] = w - lse; + filled = @min(filled + 1, top); + } + r.count = @min(count, top); + return r; +} + +test "sampled first-token logprob uses the last written handle, not argmax" { + const logits = [_]f32{ 0, -1, -2, -3 }; + var tokens: [ring]u32 = @splat(0); + tokens[2] = 3; + const row = firstLogprobRow(&logits, &tokens, 3, 0); + try std.testing.expectEqual(@as(u32, 3), row.token); + try std.testing.expect(std.math.isFinite(row.logprob)); + const lse = @log(@as(f64, 1) + @exp(-@as(f64, 1)) + @exp(-@as(f64, 2)) + @exp(-@as(f64, 3))); + try std.testing.expectApproxEqAbs(@as(f32, -3) - @as(f32, @floatCast(lse)), row.logprob, 1e-6); +} diff --git a/zig/src/families/inkling2/metal/dspark.zig b/zig/src/families/inkling2/metal/dspark.zig new file mode 100644 index 00000000000..cb13f807e10 --- /dev/null +++ b/zig/src/families/inkling2/metal/dspark.zig @@ -0,0 +1,270 @@ +//! Inkling 2 Mini DSpark: committed target features, three-layer proposal blocks, folded Markov logits. +const std = @import("std"); +const mtl = @import("metal"); +const lanes = @import("lanes"); +const gpu_rule = lanes.gpu_rule; +const ck = @import("../../../core/checkpoint_metal.zig"); +const Model = @import("model.zig").Model; +const fwd = @import("forward.zig"); +const glue = @import("glue.zig"); +const k = @import("dspark_kernels.zig"); +const weight_loader = @import("dspark_weights.zig"); +const state = @import("dspark_state.zig"); + +const dr = lanes.drafter; +const Stream = lanes.Stream; +const Ref = k.Ref; +const tap_list = [_]u32{ 5, 23, 41, 48 }; + +fn at(buf: mtl.Buffer, off: usize) Ref { + return .{ .buf = buf, .off = off }; +} +fn r(t: ck.Tensor) Ref { + return .{ .buf = t.buffer, .off = t.offset }; +} +fn failed(cb: mtl.CommandBuffer, what: []const u8) !void { + cb.wait(); + if (cb.failure()) |msg| { + std.log.err("inkling2_loop DSpark {s}: {s}", .{ what, msg }); + return error.GpuFailed; + } +} + +pub const Drafter = struct { + gpa: std.mem.Allocator, + target: *const Model, + weights: weight_loader.Loaded, + pipelines: k.Pipelines, + scratch: state.Scratch, + scores: ?mtl.Buffer = null, + capacity: usize = 1, + contexts: std.AutoHashMapUnmanaged(*Stream, state.Lane) = .empty, + + pub fn init(gpa: std.mem.Allocator, io: std.Io, device: mtl.Device, target: *const Model, drafter_dir: []const u8) !*Drafter { + _ = io; // Native factory convention; Checkpoint.addFile uses platform file calls. + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const d = try gpa.create(Drafter); + errdefer gpa.destroy(d); + d.* = .{ + .gpa = gpa, + .target = target, + .weights = weight_loader.load(gpa, target, drafter_dir) catch |err| return err, + .pipelines = undefined, + .scratch = undefined, + }; + errdefer d.weights.deinit(); + d.pipelines = try k.Pipelines.load(device); + errdefer d.pipelines.deinit(); + d.scratch = try state.Scratch.init(device); + errdefer d.scratch.deinit(); + return d; + } + + pub fn deinit(d: *Drafter) void { + var it = d.contexts.valueIterator(); + while (it.next()) |lane| lane.deinit(); + d.contexts.deinit(d.gpa); + if (d.scores) |scores| scores.deinit(); + d.scratch.deinit(); + d.pipelines.deinit(); + d.weights.deinit(); + d.gpa.destroy(d); + } + + pub fn fixedBytes(d: *const Drafter) u64 { + return d.weights.fixedBytes() + state.scratchBytes(); + } + + pub fn scoreBytes(capacity: usize) u64 { + return state.scoreBytes(capacity); + } + + pub fn streamBytes(capacity: usize) u64 { + return state.laneBytes(capacity); + } + + /// The selected target window fixes every new lane's global ring and the shared attention score allocation. + pub fn setContext(d: *Drafter, window: u32) !void { + const capacity: usize = @intCast(window); + if (capacity == 0 or capacity > 1048576) return error.DSparkLaneGeometry; + if (d.contexts.count() != 0) return error.DSparkContextActive; + const scores = try d.target.device.buffer(@intCast(state.scoreBytes(capacity)), mtl.ResourceOptions.private); + if (d.scores) |old| old.deinit(); + d.scores = scores; + d.capacity = capacity; + } + + 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(_: *anyopaque) []const u32 { + return &tap_list; + } + + fn factsFn(ptr: *anyopaque) dr.Facts { + const d = cast(ptr); + return .{ .depth = 7, .step_ms = 0, .plain_guard = true, .stream_bytes = @intCast(state.laneBytes(d.capacity)) }; + } + + fn openFn(ptr: *anyopaque, stream: *Stream) anyerror!void { + const d = cast(ptr); + if (d.contexts.contains(stream)) return error.DraftStreamOpen; + const lane = try state.Lane.init(d.target.device, d.capacity); + errdefer { + var owned = lane; + owned.deinit(); + } + try d.contexts.put(d.gpa, stream, lane); + } + + fn releaseFn(ptr: *anyopaque, stream: *Stream) void { + const d = cast(ptr); + if (d.contexts.fetchRemove(stream)) |entry| { + var lane = entry.value; + lane.deinit(); + } + } + + fn heldFn(ptr: *anyopaque, streams: []const *Stream, out: []const []u32) anyerror!void { + const d = cast(ptr); + for (streams, out) |stream, tokens| { + const lane = d.contexts.getPtr(stream) orelse return error.DraftStreamUnknown; + if (tokens.len > lane.held_len) return error.DraftHeldFewer; + @memcpy(tokens, lane.held[0..tokens.len]); + } + } + + fn absorbRows(d: *Drafter, e: mtl.ComputeEncoder, lane: *const state.Lane, taps: Ref, start: u64, rows: usize) void { + const n: u32 = @intCast(rows); + k.fuseTaps(&d.pipelines, e, taps, r(d.weights.weights.fuse), at(d.weights.dflare, 0), at(d.scratch.fused, 0), at(lane.newest, 0), n); + for (d.weights.weights.layers, 0..) |layer, i| { + const c = at(d.scratch.fused, i * rows * state.hidden * 2); + fwd.dense(d.target, e, layer.k_ctx, c, at(d.scratch.ck, 0), rows); + fwd.dense(d.target, e, layer.v_ctx, c, at(d.scratch.cv, 0), rows); + k.commitContext(&d.pipelines, e, at(d.scratch.ck, 0), at(d.scratch.cv, 0), r(layer.k_norm_ctx), at(lane.k[i], 0), at(lane.v[i], 0), @intCast(start), n, @intCast(lane.rings[i])); + } + } + + fn absorbFn(ptr: *anyopaque, items: []const dr.Absorb) anyerror!void { + const d = cast(ptr); + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + if (items.len == 0) return; + const cb = d.target.queue.commandBuffer(); + const e = cb.compute(.serial); + const row_bytes = 4 * state.hidden * 2; + for (items) |item| { + const lane = d.contexts.getPtr(item.stream) orelse return error.DraftStreamUnknown; + const features = item.features; + if (features.space != .device or features.dtype != .bf16 or features.row_bytes != row_bytes) return error.DraftFeaturesUnsupported; + if (item.rows != null) return error.TreesNotBuilt; + if (features.rows == 0 or features.rows > 1048576) return error.DraftFeaturesUnsupported; + if (item.start < lane.end) return error.DraftContextGap; + if (item.start > lane.end) lane.from = item.start; + const end = item.start + features.rows; + if (end > 1048576) return error.DraftContextGap; + const source = mtl.Buffer{ .id = @ptrFromInt(features.buffer) }; + var position = item.start; + while (position < end) { + const rows: usize = @intCast(@min(state.absorb_rows, end - position)); + const offset = features.offset + @as(usize, @intCast(position - item.start)) * row_bytes; + d.absorbRows(e, lane, at(source, offset), position, rows); + position += rows; + } + lane.end = end; + lane.held_len = 0; + } + e.end(); + cb.commit(); + try failed(cb, "absorb"); + } + + fn encodeBlock(d: *Drafter, e: mtl.ComputeEncoder, lane: *const state.Lane, pending: u32, anchor: u64) void { + const s = &d.scratch; + s.ids.slice(u32, 1)[0] = pending; + glue.embedNorm(&d.target.glue, e, at(s.ids, 0), r(d.target.weights.embed), r(d.target.weights.embed_norm), at(s.x, 0), 1); + k.initializeRows(&d.pipelines, e, at(s.x, 0), r(d.weights.weights.mask), at(s.x, 0)); + k.residualNorm(&d.pipelines, e, at(s.x, 0), at(s.resid, 0), r(d.weights.weights.layers[0].input_norm), at(s.resid, 0), at(s.x, 0), 8, true); + for (d.weights.weights.layers, 0..) |layer, i| { + fwd.dense(d.target, e, layer.q, at(s.x, 0), at(s.q_raw, 0), 8); + fwd.dense(d.target, e, layer.k, at(s.x, 0), at(s.k_raw, 0), 8); + fwd.dense(d.target, e, layer.v, at(s.x, 0), at(s.v_raw, 0), 8); + k.blockQkv(&d.pipelines, e, at(s.q_raw, 0), at(s.k_raw, 0), at(s.v_raw, 0), r(layer.q_norm), r(layer.k_norm), at(s.q, 0), at(s.kb, 0), at(s.vb, 0), @intCast(anchor)); + k.attend(&d.pipelines, e, at(s.q, 0), at(s.kb, 0), at(s.vb, 0), at(lane.k[i], 0), at(lane.v[i], 0), at(d.scores.?, 0), at(s.attn, 0), @intCast(lane.end), @intCast(lane.rings[i]), i != 1, @intCast(lane.from)); + fwd.dense(d.target, e, layer.o, at(s.attn, 0), at(s.y, 0), 8); + k.residualNorm(&d.pipelines, e, at(s.y, 0), at(s.resid, 0), r(layer.post_norm), at(s.next_resid, 0), at(s.x, 0), 8, false); + fwd.dense(d.target, e, layer.gate, at(s.x, 0), at(s.gate, 0), 8); + fwd.dense(d.target, e, layer.up, at(s.x, 0), at(s.up, 0), 8); + k.swiglu(&d.pipelines, e, at(s.gate, 0), at(s.up, 0), at(s.act, 0), 8 * state.intermediate); + fwd.dense(d.target, e, layer.down, at(s.act, 0), at(s.y, 0), 8); + const next_norm = if (i + 1 < d.weights.weights.layers.len) d.weights.weights.layers[i + 1].input_norm else d.weights.weights.norm; + k.residualNorm(&d.pipelines, e, at(s.y, 0), at(s.next_resid, 0), r(next_norm), at(s.resid, 0), at(s.x, 0), 8, false); + } + k.base(&d.pipelines, e, r(d.target.weights.unembed), at(s.x, state.hidden * 2), at(s.base, 0), 7, state.vocabulary); + k.kappa(&d.pipelines, e, at(s.x, state.hidden * 2), at(lane.newest, 0), r(d.weights.weights.rnn), r(d.weights.weights.rnn_bias), at(s.kappa, 0), 7); + } + + fn recurrent(d: *Drafter, e: mtl.ComputeEncoder, step: usize, previous: u32, second_bank: bool) void { + const s = &d.scratch; + const current = if (second_bank) s.next_state else s.state; + const next = if (second_bank) s.state else s.next_state; + k.recurrentStep(&d.pipelines, e, at(current, 0), at(s.kappa, step * 3 * state.rank * 4), r(d.weights.weights.rnn), r(d.weights.weights.markov_w1), at(s.z, 0), at(next, 0), at(s.lambda, 0), previous); + k.finalLogits(&d.pipelines, e, at(s.base, step * state.vocabulary * 2), at(d.weights.phi, 0), at(d.weights.beta, 0), at(s.lambda, 0), at(s.logits, 0)); + } + + fn holdFn(ptr: *anyopaque, items: []const dr.Hold) anyerror!void { + const d = cast(ptr); + for (items) |item| { + const lane = d.contexts.getPtr(item.stream) orelse return error.DraftStreamUnknown; + if (item.depth == 0 or item.position == 0) return error.DraftDepth; + const anchor = item.position - 1; + if (lane.end != anchor) return error.DraftContextGap; + const depth: usize = @min(item.depth, 7); + @memset(d.scratch.state.slice(u16, state.rank), 0); + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const cb = d.target.queue.commandBuffer(); + const e = cb.compute(.serial); + d.encodeBlock(e, lane, item.pending, anchor); + d.recurrent(e, 0, item.pending, false); + e.end(); + cb.commit(); + try failed(cb, "block"); + const values = try d.gpa.alloc(f32, state.vocabulary); + defer d.gpa.free(values); + var previous = item.pending; + var second_bank = false; + for (0..depth) |step| { + if (step != 0) { + second_bank = !second_bank; + const next_cb = d.target.queue.commandBuffer(); + const next_e = next_cb.compute(.serial); + d.recurrent(next_e, step, previous, second_bank); + next_e.end(); + next_cb.commit(); + try failed(next_cb, "recurrent step"); + } + const raw = d.scratch.logits.slice(u16, state.vocabulary); + for (raw, values) |bits, *value| value.* = @bitCast(@as(u32, bits) << 16); + const base_position = std.math.cast(u32, item.position) orelse return error.DraftDepth; + const position = std.math.add(u32, base_position, @intCast(step)) catch return error.DraftDepth; + previous = try gpu_rule.sample(d.gpa, values, item.sampling, position, null); + if (previous >= state.vocabulary) return error.DraftNonfinite; + lane.held[step] = previous; + } + lane.held_len = @intCast(depth); + } + } +}; + +test "Mini taps and block depth match checkpoint section eight" { + try std.testing.expectEqualSlices(u32, &.{ 5, 23, 41, 48 }, &tap_list); + try std.testing.expectEqual(@as(u32, 48), tap_list[3]); + try std.testing.expectEqual(@as(u64, 768 * 1032), Drafter.scoreBytes(1024)); +} diff --git a/zig/src/families/inkling2/metal/dspark_fold.zig b/zig/src/families/inkling2/metal/dspark_fold.zig new file mode 100644 index 00000000000..04b5a787a05 --- /dev/null +++ b/zig/src/families/inkling2/metal/dspark_fold.zig @@ -0,0 +1,103 @@ +//! One-time binary64 folding of DSpark's rank-256 hidden head into the target unembedding. +const std = @import("std"); +const bf = @import("bf16_round"); + +pub const hidden = 2304; +pub const rank = 256; +pub const vocabulary = 201024; + +pub fn value(h: u16) f64 { + const x: f32 = @bitCast(@as(u32, h) << 16); + return x; +} + +/// The reference's binary64 dot, rounded once through binary32 to BF16. +pub fn dot(u: []const f64, w: []const f64) u16 { + std.debug.assert(u.len == w.len); + var sum: f64 = 0; + for (u, w) |x, y| sum += x * y; + return bf.bits(@floatCast(sum)); +} + +const Work = struct { + unembed: []const u16, + hidden_w: []const f64, + hidden_b: []const f64, + phi: []u16, + beta: []u16, + begin: usize, + end: usize, + + fn run(w: *const Work) void { + var u: [hidden]f64 = undefined; + for (w.begin..w.end) |v| { + for (&u, w.unembed[v * hidden ..][0..hidden]) |*x, h| x.* = value(h); + for (0..rank) |r| w.phi[v * rank + r] = dot(&u, w.hidden_w[r * hidden ..][0..hidden]); + w.beta[v] = dot(&u, w.hidden_b); + } + } +}; + +/// ฮฆ[v,r] = bf16(f32(f64(U[v]) ยท f64(hidden_out[:,r]))), ฮฒ[v] likewise for its bias. +pub fn fold( + a: std.mem.Allocator, + unembed: []const u16, + hidden_weight: []const u16, + hidden_bias: []const u16, + phi: []u16, + beta: []u16, +) !void { + const v = beta.len; + if (unembed.len != v * hidden or hidden_weight.len != hidden * rank or hidden_bias.len != hidden or phi.len != v * rank or v == 0) + return error.DSparkFoldShape; + const hw = try a.alloc(f64, hidden * rank); + defer a.free(hw); + const hb = try a.alloc(f64, hidden); + defer a.free(hb); + for (hidden_weight, 0..) |h, i| hw[(i % rank) * hidden + i / rank] = value(h); + for (hb, hidden_bias) |*x, h| x.* = value(h); + + const count = @min(@as(usize, 8), v); + const chunk = (v + count - 1) / count; + var work: [8]Work = undefined; + var threads: [8]?std.Thread = @splat(null); + for (0..count) |i| { + const begin = @min(i * chunk, v); + const end = @min(begin + chunk, v); + work[i] = .{ .unembed = unembed, .hidden_w = hw, .hidden_b = hb, .phi = phi, .beta = beta, .begin = begin, .end = end }; + threads[i] = std.Thread.spawn(.{}, Work.run, .{&work[i]}) catch null; + if (threads[i] == null) work[i].run(); + } + for (threads) |thread| if (thread) |t| t.join(); +} + +test "the binary64 fold does not collapse a discriminating binary32 intermediate" { + var u: [4]f64 = @splat(0); + u[0] = 1; + u[1] = 0x1p-8; + u[2] = 0x1p-24; + u[3] = 0x1p-24; + const w: [4]f64 = @splat(1); + const got = bf.value(dot(&u, &w)); + try std.testing.expectEqual(@as(f32, 1.0078125), got); + var sum: f32 = 0; + for (u, w) |x, y| sum += @as(f32, @floatCast(x * y)); + try std.testing.expectEqual(@as(f32, 1), bf.value(bf.bits(sum))); +} + +test "fold checks every published shape" { + var u: [hidden]u16 = @splat(0); + var w: [hidden * rank]u16 = @splat(0); + var p: [rank]u16 = undefined; + var b: [1]u16 = undefined; + try std.testing.expectError(error.DSparkFoldShape, fold(std.testing.allocator, &.{}, &w, &u, &p, &b)); + try fold(std.testing.allocator, &u, &w, &u, &p, &b); + for (p) |x| try std.testing.expectEqual(@as(u16, 0), x); + try std.testing.expectEqual(@as(u16, 0), b[0]); + u[1] = bf.bits(1); + w[rank + 2] = bf.bits(1); // hidden row 1, rank column 2 in the checkpoint's row-major layout + try fold(std.testing.allocator, &u, &w, &u, &p, &b); + try std.testing.expectEqual(bf.bits(1), p[2]); + try std.testing.expectEqual(bf.bits(1), b[0]); + for (p, 0..) |x, r| if (r != 2) try std.testing.expectEqual(@as(u16, 0), x); +} diff --git a/zig/src/families/inkling2/metal/dspark_kernels.zig b/zig/src/families/inkling2/metal/dspark_kernels.zig new file mode 100644 index 00000000000..4c7126c6ad9 --- /dev/null +++ b/zig/src/families/inkling2/metal/dspark_kernels.zig @@ -0,0 +1,224 @@ +//! Mini DSpark's fixed-shape arithmetic: Metal entry points and exact launch ABIs. +const std = @import("std"); +const mtl = @import("metal"); +const sources = @import("inkling2_metal"); + +pub const hidden: u32 = 2304; +pub const query_width: u32 = 3072; +pub const kv_width: u32 = 1024; +pub const block_rows: u32 = 8; +pub const rank: u32 = 256; +pub const rnn_width: u32 = 768; +pub const intermediate: u32 = 9216; +pub const vocab: u32 = 200058; +pub const Ref = @import("inkling2_metal_ref").Ref; +pub const PositionArgs = extern struct { base: u32 }; +pub const ContextArgs = extern struct { base: u32, rows: u32, ring: u32 }; +pub const AttentionArgs = extern struct { committed: u32, ring: u32, local: u32, from: u32 }; +pub const TokenArgs = extern struct { token: u32 }; +pub const CountArgs = extern struct { count: u32 }; +pub const BaseArgs = extern struct { rows: u32, vocab: u32 }; + +/// Round through binary32 and nearest-even BF16, returning an exactly representable FP64 value. +pub fn roundBf16(v: anytype) f64 { + const x: f32 = @floatCast(v); + const bits: u32 = @bitCast(x); + const rounded: u16 = if (std.math.isNan(x)) @truncate((bits >> 16) | 0x40) else @truncate((bits +% 0x7fff +% ((bits >> 16) & 1)) >> 16); + const value: f32 = @bitCast(@as(u32, rounded) << 16); + return value; +} + +/// Rotate-half RoPE partner is d+64 below the midpoint and d-64 above it. +pub fn ropeRotateHalf(x: f32, other: f32, d: u32, angle: f32) f32 { + return if (d < 64) x * @cos(angle) - other * @sin(angle) else other * @sin(angle) + x * @cos(angle); +} + +/// Every recurrent blend operation rounds independently to model precision. +pub fn recurrentBlend(gamma: f32, candidate: f32, previous: f32) f64 { + const keep: f32 = @floatCast(roundBf16(@as(f32, 1.0 - gamma))); + const left: f32 = @floatCast(roundBf16(@as(f32, gamma * previous))); + const right: f32 = @floatCast(roundBf16(@as(f32, keep * candidate))); + return roundBf16(@as(f32, left + right)); +} + +/// Folded bias and base each round before the target-style softcap. +pub fn foldedLogit(base_value: f32, beta: f32, dot: f32) f64 { + const bias: f32 = @floatCast(roundBf16(@as(f32, beta + dot))); + const logit: f32 = @floatCast(roundBf16(@as(f32, base_value + bias))); + return roundBf16(@as(f32, 30.0) * std.math.tanh(logit / @as(f32, 30.0))); +} +pub const ResidualArgs = extern struct { init: u32 }; + +pub const Kind = enum { + init_rows, + fuse_taps, + block_qkv, + context_kv, + attention, + residual_norm, + swiglu, + kappa, + recurrent, + base, + logits, + + pub fn symbol(k: Kind) []const u8 { + return switch (k) { + .init_rows => "tf_ink2_dspark_init_rows", + .fuse_taps => "tf_ink2_dspark_fuse_taps", + .block_qkv => "tf_ink2_dspark_block_qkv", + .context_kv => "tf_ink2_dspark_context_kv", + .attention => "tf_ink2_dspark_attention", + .residual_norm => "tf_ink2_dspark_residual_norm", + .swiglu => "tf_ink2_dspark_swiglu", + .kappa => "tf_ink2_dspark_kappa", + .recurrent => "tf_ink2_dspark_recurrent", + .base => "tf_ink2_dspark_base", + .logits => "tf_ink2_dspark_logits", + }; + } + pub fn label(k: Kind) []const u8 { + return switch (k) { + inline else => |v| std.fmt.comptimePrint("metal inkling2 dspark {s} {s}", .{ @tagName(v), comptime v.symbol() }), + }; + } +}; + +pub const Pipelines = struct { + init_rows: mtl.Pipeline, + fuse_taps: mtl.Pipeline, + block_qkv: mtl.Pipeline, + context_kv: mtl.Pipeline, + attention: mtl.Pipeline, + residual_norm: mtl.Pipeline, + swiglu: mtl.Pipeline, + kappa: mtl.Pipeline, + recurrent: mtl.Pipeline, + base: mtl.Pipeline, + logits: mtl.Pipeline, + + pub fn load(device: mtl.Device) !Pipelines { + return loadSource(device, sources.inkling2_dspark); + } + pub fn loadSource(device: mtl.Device, text: []const u8) !Pipelines { + const lib = try mtl.Library.fromSource(device, text, mtl.CompileOptions.mlx()); + defer lib.deinit(); + var out: Pipelines = undefined; + var loaded: usize = 0; + errdefer inline for (@typeInfo(Pipelines).@"struct".field_names, 0..) |name, i| { + if (loaded > i) @field(out, name).deinit(); + }; + inline for (@typeInfo(Pipelines).@"struct".field_names, 0..) |name, i| { + @field(out, name) = try mtl.Pipeline.init(device, lib, @as(Kind, @fromBackingInt(@intCast(i))).symbol(), false); + loaded += 1; + } + return out; + } + pub fn deinit(p: *Pipelines) void { + inline for (@typeInfo(Pipelines).@"struct".field_names) |name| @field(p, name).deinit(); + p.* = undefined; + } +}; + +fn bind(e: mtl.ComputeEncoder, refs: []const Ref) void { + for (refs, 0..) |r, slot| e.setBuffer(r.buf, r.off, slot); +} +fn groups(e: mtl.ComputeEncoder, count: usize, width: usize) void { + e.dispatchGroups(mtl.Size.of(count, 1, 1), mtl.Size.of(width, 1, 1)); +} +fn threads(e: mtl.ComputeEncoder, count: usize, width: usize) void { + e.dispatchThreads(mtl.Size.of(count, 1, 1), mtl.Size.of(width, 1, 1)); +} + +/// Row zero copies the target's normalized anchor; the other seven rows copy the raw mask embedding. +pub fn initializeRows(p: *const Pipelines, e: mtl.ComputeEncoder, anchor: Ref, mask_embed: Ref, out: Ref) void { + e.setPipeline(p.init_rows); + bind(e, &.{ anchor, mask_embed, out }); + groups(e, block_rows, 256); +} + +/// Input taps are [row][tap][H], output c is [fusion][row][H], and newest_f is one [H] row. +pub fn fuseTaps(p: *const Pipelines, e: mtl.ComputeEncoder, taps: Ref, fuse_weight: Ref, norm_weight: Ref, c: Ref, newest_f: Ref, rows: u32) void { + std.debug.assert(rows > 0); + e.setPipeline(p.fuse_taps); + bind(e, &.{ taps, fuse_weight, norm_weight, c, newest_f }); + e.setValue(CountArgs{ .count = rows }, 5); + groups(e, 4 * @as(usize, rows), 256); +} + +/// Raw projections become per-head RMS-normalized rotate-half Q/K and an unchanged BF16 V. +pub fn blockQkv(p: *const Pipelines, e: mtl.ComputeEncoder, q_raw: Ref, k_raw: Ref, v_raw: Ref, q_norm: Ref, k_norm: Ref, q: Ref, k: Ref, v: Ref, base_position: u32) void { + e.setPipeline(p.block_qkv); + bind(e, &.{ q_raw, k_raw, v_raw, q_norm, k_norm, q, k, v }); + e.setValue(PositionArgs{ .base = base_position }, 8); + groups(e, 8 * 40, 128); +} + +/// Context K/V is written at absolute-position modulo ring_capacity for committed rows only. +pub fn commitContext(p: *const Pipelines, e: mtl.ComputeEncoder, k_raw: Ref, v_raw: Ref, k_norm_ctx: Ref, keys: Ref, values: Ref, base_position: u32, rows: u32, ring_capacity: u32) void { + std.debug.assert(rows > 0 and ring_capacity > 0); + e.setPipeline(p.context_kv); + bind(e, &.{ k_raw, v_raw, k_norm_ctx, keys, values }); + e.setValue(ContextArgs{ .base = base_position, .rows = rows, .ring = ring_capacity }, 5); + groups(e, @as(usize, rows) * 8, 128); +} + +/// Scores is FP32 scratch sized 8*24*(retained_context+8); global layers retain all context. +pub fn attend(p: *const Pipelines, e: mtl.ComputeEncoder, q: Ref, block_k: Ref, block_v: Ref, context_k: Ref, context_v: Ref, scores: Ref, out: Ref, committed: u32, ring_capacity: u32, local: bool, from: u32) void { + std.debug.assert(ring_capacity > 0 and from <= committed); + e.setPipeline(p.attention); + bind(e, &.{ q, block_k, block_v, context_k, context_v, scores, out }); + e.setValue(AttentionArgs{ .committed = committed, .ring = ring_capacity, .local = @intFromBool(local), .from = from }, 7); + groups(e, 8 * 24, 128); +} + +/// Normalization consumes the FP32 residual sum, independently of the rounded BF16 residual store. +pub fn residualNorm(p: *const Pipelines, e: mtl.ComputeEncoder, x: Ref, residual: Ref, weight: Ref, new_residual: Ref, normalized: Ref, rows: u32, init: bool) void { + std.debug.assert(rows > 0); + e.setPipeline(p.residual_norm); + bind(e, &.{ x, residual, weight, new_residual, normalized }); + e.setValue(ResidualArgs{ .init = @intFromBool(init) }, 5); + groups(e, rows, 256); +} + +/// Gate and up projections are BF16 rows with 9216 entries; only this SwiGLU product is stored here. +pub fn swiglu(p: *const Pipelines, e: mtl.ComputeEncoder, gate: Ref, up: Ref, out: Ref, count: u32) void { + std.debug.assert(count == 8 * intermediate); + e.setPipeline(p.swiglu); + bind(e, &.{ gate, up, out }); + e.setValue(CountArgs{ .count = count }, 3); + threads(e, count, 256); +} + +/// Kappa is FP32 [rows][768], using RNN columns 512..2815 for y and 2816..5119 for newest_f. +pub fn kappa(p: *const Pipelines, e: mtl.ComputeEncoder, y: Ref, newest_f: Ref, rnn_weight: Ref, rnn_bias: Ref, out: Ref, rows: u32) void { + std.debug.assert(rows > 0 and rows <= 7); + e.setPipeline(p.kappa); + bind(e, &.{ y, newest_f, rnn_weight, rnn_bias, out }); + e.setValue(CountArgs{ .count = rows }, 5); + threads(e, @as(usize, rows) * rnn_width, 256); +} + +/// One recurrent step writes rounded Z, the next BF16 state and BF16 lambda for rows 1..7 in turn. +pub fn recurrentStep(p: *const Pipelines, e: mtl.ComputeEncoder, state: Ref, kappa_row: Ref, rnn_weight: Ref, markov_w1: Ref, z: Ref, next_state: Ref, lambda: Ref, previous_token: u32) void { + e.setPipeline(p.recurrent); + bind(e, &.{ state, kappa_row, rnn_weight, markov_w1, z, next_state, lambda }); + e.setValue(TokenArgs{ .token = previous_token }, 7); + threads(e, rank, 256); +} + +/// Raw U*y rows round once to BF16, with no target unembedding softcap. +pub fn base(p: *const Pipelines, e: mtl.ComputeEncoder, unembed: Ref, y: Ref, out: Ref, rows: u32, vocabulary_count: u32) void { + std.debug.assert(rows > 0 and vocabulary_count > 0 and vocabulary_count <= vocab); + e.setPipeline(p.base); + bind(e, &.{ unembed, y, out }); + e.setValue(BaseArgs{ .rows = rows, .vocab = vocabulary_count }, 3); + threads(e, @as(usize, rows) * vocabulary_count, 256); +} +/// Folded Phi/beta correction and target-style 30 tanh softcap, restricted to Mini's 200058 logits. +pub fn finalLogits(p: *const Pipelines, e: mtl.ComputeEncoder, base_values: Ref, phi: Ref, beta: Ref, lambda: Ref, out: Ref) void { + e.setPipeline(p.logits); + bind(e, &.{ base_values, phi, beta, lambda, out }); + e.setValue(CountArgs{ .count = vocab }, 5); + threads(e, vocab, 256); +} diff --git a/zig/src/families/inkling2/metal/dspark_kernels_test.zig b/zig/src/families/inkling2/metal/dspark_kernels_test.zig new file mode 100644 index 00000000000..b72660d3aa2 --- /dev/null +++ b/zig/src/families/inkling2/metal/dspark_kernels_test.zig @@ -0,0 +1,154 @@ +//! Host-only FP64 witnesses for Mini DSpark rounding, pairing, reach and launch contracts. +const std = @import("std"); +const k = @import("dspark_kernels.zig"); +const records = @import("core").contract.inkling2_dspark_metal_records.records; +const shader = @import("inkling2_metal").inkling2_dspark; +const t = std.testing; + +fn near(want: f64, got: f64) !void { + try t.expectApproxEqAbs(want, got, 1e-10); +} +fn bf(v: anytype) f64 { + const x: f32 = @floatCast(v); + const bits: u32 = @bitCast(x); + const rounded: u16 = if (std.math.isNan(x)) @truncate((bits >> 16) | 0x40) else @truncate((bits +% 0x7fff +% ((bits >> 16) & 1)) >> 16); + const out: f32 = @bitCast(@as(u32, rounded) << 16); + return out; +} +fn f32v(v: f64) f64 { + return @as(f32, @floatCast(v)); +} + +test "DSpark symbols, records, ABIs and disabled contraction are exact" { + for (std.enums.values(k.Kind), records) |kind, record| { + try t.expectEqualStrings(kind.label(), record.name); + try t.expectEqual(@as(usize, 1), std.mem.count(u8, shader, kind.symbol())); + const width: u32 = switch (kind) { + .block_qkv, .context_kv, .attention => 128, + else => 256, + }; + try t.expectEqual(width, record.threads); + try t.expectEqual(record.threads, record.reserved); + const threadgroup: u32 = switch (kind) { + .fuse_taps => 32, + .block_qkv, .context_kv, .attention, .residual_norm => 16, + else => 0, + }; + try t.expectEqual(threadgroup, record.tg_memory); + } + try t.expectEqual(@as(usize, 4), @sizeOf(k.PositionArgs)); + try t.expectEqual(@as(usize, 12), @sizeOf(k.ContextArgs)); + try t.expectEqual(@as(usize, 16), @sizeOf(k.AttentionArgs)); + try t.expectEqual(@as(usize, 4), @sizeOf(k.ResidualArgs)); + try t.expectEqual(@as(usize, 4), @sizeOf(k.TokenArgs)); + try t.expectEqual(@as(usize, 4), @sizeOf(k.CountArgs)); + try t.expectEqual(@as(usize, 8), @sizeOf(k.BaseArgs)); + try t.expect(std.mem.indexOf(u8, shader, "#pragma METAL fp contract(off)") != null); + try t.expect(std.mem.indexOf(u8, shader, "DSP_SCALE = 0x1.6a09e6p-7f") != null); +} + +test "raw base projection rounds the dot without applying target softcap" { + const unembed: [k.hidden]f32 = @splat(1); + const y: [k.hidden]f32 = @splat(1); + var dot: f32 = 0; + for (unembed, y) |u, v| dot += u * v; + try near(2304, bf(dot)); + try near(30, bf(30.0 * std.math.tanh(dot / 30.0))); + try t.expect(std.mem.indexOf(u8, shader, "kernel void tf_ink2_dspark_base") != null); +} + +test "fusion rounds each softmax alpha through BF16 before ordered FP32 taps" { + const weights = [_]f64{ 0, 0.5, -0.25, 2 }; + const taps = [_]f64{ 303.2126159667969, -170.3546905517578, 454.9715576171875, -93.47307586669922 }; + var expv: [4]f64 = undefined; + var den: f64 = 0; + for (weights, 0..) |w, j| { + expv[j] = @exp(w - 2); + den += expv[j]; + } + var rounded: f32 = 0; + var raw: f32 = 0; + for (0..4) |j| { + const a = f32v(expv[j] / f32v(den)); + const alpha: f32 = @floatCast(bf(a)); + rounded += alpha * @as(f32, @floatCast(taps[j])); + raw += @as(f32, @floatCast(a)) * @as(f32, @floatCast(taps[j])); + } + try t.expect(bf(rounded) != bf(raw)); + var ordered: f32 = 0; + for (0..4) |j| ordered += @as(f32, @floatCast(bf(f32v(expv[j] / f32v(den))))) * @as(f32, @floatCast(taps[j])); + try t.expectEqual(ordered, rounded); +} + +test "residual normalized output sees sigma rather than rounded BF16 storage" { + const x: f32 = 1.0; + const res: f32 = 0.00390625; + const sigma: f32 = x + res; + const stored = bf(sigma); + const weight = 0.0; + const scale: f32 = 1.00390625; + const from_sigma = bf(sigma * scale); + const from_store = bf(@as(f32, @floatCast(stored)) * scale); + try t.expect(from_sigma != from_store); + try near(@as(f64, weight) + 1, 1.0); +} + +test "rotate-half RoPE pairs d with d plus 64 at absolute positions" { + const x = [_]f64{ 1, 2 }; + const angle = std.math.pi / 2.0; + const first = x[0] * @cos(angle) - x[1] * @sin(angle); + const second = x[0] * @sin(angle) + x[1] * @cos(angle); + try near(-2, first); + try near(1, second); + try t.expect(@abs(second - (-1)) > 1); + try t.expect(@abs(k.ropeRotateHalf(1, 2, 0, @floatCast(angle)) - @as(f32, @floatCast(first))) < 2e-6); + try t.expect(@abs(k.ropeRotateHalf(2, 1, 64, @floatCast(angle)) - @as(f32, @floatCast(second))) < 2e-6); +} + +test "local reach starts at committed minus 1024 without crossing a restored lower bound" { + const committed: usize = 1027; + const from: usize = 5; + const local_first = @max(from, committed - 1024); + const global_first = from; + try t.expectEqual(@as(usize, 5), local_first); + try t.expectEqual(@as(usize, 1022 + 8), committed - local_first + 8); + try t.expectEqual(committed - from + 8, committed - global_first + 8); + for (0..8) |row| { + const position = 5000 + row; + try t.expectEqual(position, 5000 + row); + } +} + +test "recurrence rounds z activations and every state operation through BF16" { + const gamma: f32 = @floatCast(bf(@as(f32, 0.431640625))); + const candidate: f32 = @floatCast(bf(@as(f32, 0.030029296875))); + const previous: f32 = -14.5625; + const keep: f32 = @floatCast(bf(1.0 - gamma)); + const left: f32 = @floatCast(bf(gamma * previous)); + const right: f32 = @floatCast(bf(keep * candidate)); + const stepped = bf(left + right); + const unrounded = bf(@as(f32, gamma) * previous + (1.0 - @as(f32, gamma)) * candidate); + try t.expect(stepped != unrounded); + try near(stepped, bf(@as(f32, left + right))); + try near(stepped, k.recurrentBlend(gamma, candidate, previous)); + const z = bf(@as(f32, 0.33333334)); + const lambda = bf(std.math.tanh(z)); + try near(lambda, bf(std.math.tanh(z))); +} + +test "folded correction rounds bias then logits before the thirty softcap" { + const beta: f32 = 0.125; + const dot: f32 = 0.0001; + const base: f32 = 40.0; + const bias: f32 = @floatCast(bf(beta + dot)); + const logit: f32 = @floatCast(bf(base + bias)); + const capped = bf(30.0 * std.math.tanh(logit / 30.0)); + const uncapped = bf(@as(f32, 30.0) * @as(f32, @floatCast(std.math.tanh(logit / 30.0)))); + try near(capped, uncapped); + try near(capped, k.foldedLogit(base, beta, dot)); + const no_bias_round: f32 = @floatCast(bf(base + (beta + dot))); + try t.expect(logit != no_bias_round); + try t.expect(@abs(capped) < @abs(logit)); + const saturated = bf(30.0 * std.math.tanh(@as(f64, 1000) / 30.0)); + try t.expect(saturated <= 30 and saturated > 29.9); +} diff --git a/zig/src/families/inkling2/metal/dspark_state.zig b/zig/src/families/inkling2/metal/dspark_state.zig new file mode 100644 index 00000000000..eb20bd1cd6d --- /dev/null +++ b/zig/src/families/inkling2/metal/dspark_state.zig @@ -0,0 +1,159 @@ +//! Fixed eight-row DSpark scratch and committed-only per-stream context rings. +const std = @import("std"); +const mtl = @import("metal"); + +pub const hidden = 2304; +pub const query = 3072; +pub const kv = 1024; +pub const intermediate = 9216; +pub const rank = 256; +pub const vocabulary = 200058; +pub const block = 8; +pub const absorb_rows = 64; +pub const local_ring = std.mem.alignForward(usize, 1024 + block, 128); + +const fields = [_][]const u8{ + "ids", "resid", "next_resid", "x", "y", "q_raw", "k_raw", "v_raw", "q", "kb", "vb", "attn", + "gate", "up", "act", "base", "fused", "ck", "cv", "kappa", "state", "next_state", "z", "lambda", + "logits", +}; + +fn sizes() [fields.len]usize { + const r = block; + const a = absorb_rows; + const b = 2; + return .{ + r * 4, r * hidden * b, r * hidden * b, r * hidden * b, r * hidden * b, + r * query * b, r * kv * b, r * kv * b, r * query * b, r * kv * b, + r * kv * b, r * query * b, r * intermediate * b, r * intermediate * b, r * intermediate * b, + (r - 1) * 201024 * b, 4 * a * hidden * b, a * kv * b, a * kv * b, (r - 1) * 3 * rank * 4, + rank * b, rank * b, rank * b, rank * b, vocabulary * b, + }; +} + +pub fn scratchBytes() usize { + var bytes: usize = 0; + for (sizes()) |n| bytes += n; + return bytes; +} + +pub const Scratch = struct { + ids: mtl.Buffer, + resid: mtl.Buffer, + next_resid: mtl.Buffer, + x: mtl.Buffer, + y: mtl.Buffer, + q_raw: mtl.Buffer, + k_raw: mtl.Buffer, + v_raw: mtl.Buffer, + q: mtl.Buffer, + kb: mtl.Buffer, + vb: mtl.Buffer, + attn: mtl.Buffer, + gate: mtl.Buffer, + up: mtl.Buffer, + act: mtl.Buffer, + base: mtl.Buffer, + fused: mtl.Buffer, + ck: mtl.Buffer, + cv: mtl.Buffer, + kappa: mtl.Buffer, + state: mtl.Buffer, + next_state: mtl.Buffer, + z: mtl.Buffer, + lambda: mtl.Buffer, + logits: mtl.Buffer, + + pub fn init(device: mtl.Device) !Scratch { + @setEvalBranchQuota(10_000); + const ns = sizes(); + var s: Scratch = undefined; + var made: usize = 0; + errdefer inline for (fields, 0..) |f, i| if (i < made) @field(s, f).deinit(); + inline for (fields, 0..) |f, i| { + @field(s, f) = try device.buffer(@max(ns[i], 16), mtl.ResourceOptions.shared); + made += 1; + } + return s; + } + + pub fn deinit(s: *Scratch) void { + inline for (fields) |f| @field(s, f).deinit(); + s.* = undefined; + } +}; +pub fn globalRing(capacity: usize) usize { + return std.mem.alignForward(usize, capacity, 128); +} + +pub fn scoreBytes(capacity: usize) u64 { + return @as(u64, 8 * 24 * 4) * (capacity + block); +} + +/// Two sliding layers hold two fixed K/V rings; layer 1 holds two global K/V rings. +pub fn laneFixedBytes() u64 { + return 2 * 2 * local_ring * kv * 2 + hidden * 2; +} + +pub fn laneTokenBytes() u64 { + return 2 * kv * 2; +} + +pub fn laneBytes(capacity: usize) u64 { + return laneFixedBytes() + globalRing(capacity) * laneTokenBytes(); +} + +pub const Lane = struct { + k: [3]mtl.Buffer, + v: [3]mtl.Buffer, + rings: [3]usize, + newest: mtl.Buffer, + from: u64 = 0, + end: u64 = 0, + held: [7]u32 = @splat(0), + held_len: u32 = 0, + + pub fn init(device: mtl.Device, capacity: usize) !Lane { + if (capacity == 0 or capacity > 1048576) return error.DSparkLaneGeometry; + var l: Lane = .{ .k = undefined, .v = undefined, .rings = .{ local_ring, globalRing(capacity), local_ring }, .newest = undefined }; + var made: usize = 0; + errdefer { + for (0..made) |i| { + l.k[i].deinit(); + l.v[i].deinit(); + } + } + for (l.rings, 0..) |ring, i| { + const bytes = ring * kv * 2; + l.k[i] = try device.buffer(bytes, mtl.ResourceOptions.private); + l.v[i] = device.buffer(bytes, mtl.ResourceOptions.private) catch |err| { + l.k[i].deinit(); + return err; + }; + made += 1; + } + l.newest = try device.buffer(hidden * 2, mtl.ResourceOptions.private); + return l; + } + + pub fn deinit(l: *Lane) void { + l.newest.deinit(); + for (0..3) |i| { + l.k[i].deinit(); + l.v[i].deinit(); + } + l.* = undefined; + } +}; + +comptime { + if (local_ring != 1152 or laneTokenBytes() != 4096) @compileError("DSpark ring geometry drift"); +} + +test "DSpark stream accounting includes sliding, global and shared attention scratch" { + try std.testing.expectEqual(@as(u64, 9_437_184 + 4608), laneFixedBytes()); + try std.testing.expectEqual(laneFixedBytes() + 128 * 4096, laneBytes(1)); + try std.testing.expectEqual(laneFixedBytes() + 1152 * 4096, laneBytes(1025)); + try std.testing.expectEqual(@as(u64, 768 * 1032), scoreBytes(1024)); + // Ring and scores bytes are reserved with the target cache before the lane opens. +} diff --git a/zig/src/families/inkling2/metal/dspark_weights.zig b/zig/src/families/inkling2/metal/dspark_weights.zig new file mode 100644 index 00000000000..00082911738 --- /dev/null +++ b/zig/src/families/inkling2/metal/dspark_weights.zig @@ -0,0 +1,174 @@ +//! Validated mtp.safetensors weights and the one-time folded Markov output head. +const std = @import("std"); +const mtl = @import("metal"); +const ck = @import("../../../core/checkpoint_metal.zig"); +const cfg = @import("../config.zig"); +const Model = @import("model.zig").Model; +const fold = @import("dspark_fold.zig"); + +pub const hidden = 2304; +pub const query = 3072; +pub const kv = 1024; +pub const intermediate = 9216; +pub const rank = 256; +pub const vocabulary = 201024; + +pub const Layer = struct { + dflare: ck.Tensor, + input_norm: ck.Tensor, + post_norm: ck.Tensor, + q_norm: ck.Tensor, + k_norm: ck.Tensor, + k_norm_ctx: ck.Tensor, + q: ck.Tensor, + k: ck.Tensor, + v: ck.Tensor, + k_ctx: ck.Tensor, + v_ctx: ck.Tensor, + o: ck.Tensor, + gate: ck.Tensor, + up: ck.Tensor, + down: ck.Tensor, +}; + +pub const Weights = struct { + fuse: ck.Tensor, + mask: ck.Tensor, + norm: ck.Tensor, + markov_norm: ck.Tensor, + hidden_out: ck.Tensor, + hidden_bias: ck.Tensor, + markov_w1: ck.Tensor, + rnn: ck.Tensor, + rnn_bias: ck.Tensor, + layers: [3]Layer, +}; + +pub const Loaded = struct { + checkpoint: ck.Checkpoint, + weights: Weights, + dflare: mtl.Buffer, // four H-wide rows: three layers, then the Markov head + phi: mtl.Buffer, // [201024,256] BF16, folded once in binary64 + beta: mtl.Buffer, // [201024] BF16 + + pub fn deinit(l: *Loaded) void { + l.beta.deinit(); + l.phi.deinit(); + l.dflare.deinit(); + l.checkpoint.deinit(); + l.* = undefined; + } + + pub fn fixedBytes(l: *const Loaded) u64 { + return l.checkpoint.residentBytes() + l.dflare.length() + l.phi.length() + l.beta.length(); + } +}; + +fn require(t: ck.Tensor, dims: []const usize, _: []const u8) !ck.Tensor { + if (t.dtype != .bf16 or t.rank != dims.len) { + return error.DSparkTensorShape; + } + var count: usize = 1; + for (dims, 0..) |d, i| { + if (t.shape[i] != d) { + return error.DSparkTensorShape; + } + count = std.math.mul(usize, count, d) catch return error.DSparkTensorShape; + } + if (t.bytes != count * 2) return error.DSparkTensorShape; + return t; +} + +fn get(c: *const ck.Checkpoint, name: []const u8, dims: []const usize) !ck.Tensor { + const t = c.get(name) catch { + std.log.err("DSpark mtp.safetensors is missing {s}", .{name}); + return error.DSparkMissingTensor; + }; + return require(t, dims, name); +} + +fn admit(c: *const cfg.Config) !void { + const m = c.mtp orelse return error.DSparkNotConfigured; + if (m.layers != 3 or m.q_heads != 24 or m.kv_heads != 8 or m.head_dim != 128 or m.inter != intermediate or + m.window != 1024 or m.block != 8 or m.rank != rank or m.rope_theta != 1e6 or m.taps_n != 4 or + !m.local[0] or m.local[1] or !m.local[2] or !std.mem.eql(u32, m.taps[0..4], &.{ 5, 23, 41, 48 })) + return error.UnsupportedDSparkConfig; +} + +fn layer(c: *const ck.Checkpoint, i: usize) !Layer { + var b: [128]u8 = undefined; + const g = struct { + fn layerTensor(cp: *const ck.Checkpoint, buf: []u8, i_: usize, suffix: []const u8, dims: []const usize) !ck.Tensor { + const name = try std.fmt.bufPrint(buf, "layers.{d}.{s}", .{ i_, suffix }); + return get(cp, name, dims); + } + }.layerTensor; + return .{ + .dflare = try g(c, &b, i, "dflare_norm.weight", &.{hidden}), + .input_norm = try g(c, &b, i, "input_layernorm.weight", &.{hidden}), + .post_norm = try g(c, &b, i, "post_attention_layernorm.weight", &.{hidden}), + .q_norm = try g(c, &b, i, "self_attn.q_norm.weight", &.{128}), + .k_norm = try g(c, &b, i, "self_attn.k_norm.weight", &.{128}), + .k_norm_ctx = try g(c, &b, i, "self_attn.k_norm_ctx.weight", &.{128}), + .q = try g(c, &b, i, "self_attn.q_proj.weight", &.{ query, hidden }), + .k = try g(c, &b, i, "self_attn.k_proj.weight", &.{ kv, hidden }), + .v = try g(c, &b, i, "self_attn.v_proj.weight", &.{ kv, hidden }), + .k_ctx = try g(c, &b, i, "self_attn.k_proj_ctx.weight", &.{ kv, hidden }), + .v_ctx = try g(c, &b, i, "self_attn.v_proj_ctx.weight", &.{ kv, hidden }), + .o = try g(c, &b, i, "self_attn.o_proj.weight", &.{ hidden, query }), + .gate = try g(c, &b, i, "mlp.gate_proj.weight", &.{ intermediate, hidden }), + .up = try g(c, &b, i, "mlp.up_proj.weight", &.{ intermediate, hidden }), + .down = try g(c, &b, i, "mlp.down_proj.weight", &.{ hidden, intermediate }), + }; +} + +pub fn load(gpa: std.mem.Allocator, target: *const Model, dir: []const u8) !Loaded { + try admit(&target.config); + var checkpoint = ck.Checkpoint.init(gpa); + errdefer checkpoint.deinit(); + const path: [:0]u8 = if (std.mem.endsWith(u8, dir, ".safetensors")) + try std.fmt.allocPrintSentinel(gpa, "{s}", .{dir}, 0) + else + try std.fmt.allocPrintSentinel(gpa, "{s}/mtp.safetensors", .{dir}, 0); + defer gpa.free(path); + checkpoint.addFile(target.device, path, "") catch |err| { + std.log.err("DSpark cannot open {s}: {s}", .{ path, @errorName(err) }); + return error.DSparkMissingFile; + }; + const c = &checkpoint; + var layers: [3]Layer = undefined; + for (&layers, 0..) |*l, i| l.* = try layer(c, i); + const weights: Weights = .{ + .fuse = try get(c, "fuse_weight", &.{ 4, 4 }), + .mask = try get(c, "mask_embed", &.{hidden}), + .norm = try get(c, "norm.weight", &.{hidden}), + .markov_norm = try get(c, "markov_head.dflare_norm.weight", &.{hidden}), + .hidden_out = try get(c, "markov_head.hidden_out.weight", &.{ hidden, rank }), + .hidden_bias = try get(c, "markov_head.hidden_out.bias", &.{hidden}), + .markov_w1 = try get(c, "markov_head.markov_w1.weight", &.{ vocabulary, rank }), + .rnn = try get(c, "markov_head.rnn_proj.weight", &.{ 3 * rank, 2 * hidden + 2 * rank }), + .rnn_bias = try get(c, "markov_head.rnn_proj.bias", &.{3 * rank}), + .layers = layers, + }; + const dflare = try target.device.buffer(4 * hidden * 2, mtl.ResourceOptions.shared); + errdefer dflare.deinit(); + const dflare_packed = dflare.slice(u16, 4 * hidden); + for (weights.layers, 0..) |l, i| @memcpy(dflare_packed[i * hidden ..][0..hidden], l.dflare.host(u16)); + @memcpy(dflare_packed[3 * hidden ..][0..hidden], weights.markov_norm.host(u16)); + const phi = try target.device.buffer(vocabulary * rank * 2, mtl.ResourceOptions.shared); + errdefer phi.deinit(); + const beta = try target.device.buffer(vocabulary * 2, mtl.ResourceOptions.shared); + errdefer beta.deinit(); + try fold.fold(gpa, target.weights.unembed.host(u16), weights.hidden_out.host(u16), weights.hidden_bias.host(u16), phi.slice(u16, vocabulary * rank), beta.slice(u16, vocabulary)); + return .{ .checkpoint = checkpoint, .weights = weights, .dflare = dflare, .phi = phi, .beta = beta }; +} + +test "a misshapen DSpark tensor has a named refusal" { + if (comptime @import("builtin").os.tag != .macos) return error.SkipZigTest; + var t: ck.Tensor = .{ .buffer = undefined, .offset = 0, .bytes = 8, .dtype = .bf16, .rank = 1 }; + t.shape[0] = 4; + _ = try require(t, &.{4}, "witness"); + try std.testing.expectError(error.DSparkTensorShape, require(t, &.{ 2, 2 }, "witness")); + t.dtype = .f32; + try std.testing.expectError(error.DSparkTensorShape, require(t, &.{4}, "witness")); +} diff --git a/zig/src/families/inkling2/metal/experts.zig b/zig/src/families/inkling2/metal/experts.zig new file mode 100644 index 00000000000..268ca0398ea --- /dev/null +++ b/zig/src/families/inkling2/metal/experts.zig @@ -0,0 +1,124 @@ +//! Real Metal dispatch for Inkling 2 Mini's M3 NVFP4/MXFP8 routed experts. +const std = @import("std"); +const mtl = @import("metal"); +const src = @import("inkling2_metal"); +const plan = @import("experts_plan.zig"); + +pub const Ref = struct { buf: mtl.Buffer, off: usize = 0 }; +pub const Format = plan.Format; +pub const Call = plan.Call; +pub const Operation = enum { nvfp4_gu, nvfp4_down, mxfp8_gu, mxfp8_down, nvfp4_quantize, mxfp8_quantize, combine }; + +pub const function_names = [_][:0]const u8{ + "tf_ink2_nvfp4_gu", + "tf_ink2_nvfp4_down", + "tf_ink2_mxfp8_gu", + "tf_ink2_mxfp8_down", + "tf_ink2_nvfp4_quantize", + "tf_ink2_mxfp8_quantize", + "tf_ink2_combine", +}; + +pub const Pipelines = struct { + entries: [function_names.len]mtl.Pipeline, + + pub fn load(device: mtl.Device) !Pipelines { + return loadSource(device, src.experts); + } + + pub fn loadSource(device: mtl.Device, text: []const u8) !Pipelines { + const lib = try mtl.Library.fromSource(device, text, mtl.CompileOptions.mlx()); + defer lib.deinit(); + var out: Pipelines = undefined; + var made: usize = 0; + errdefer for (out.entries[0..made]) |pipe| pipe.deinit(); + for (function_names, 0..) |name, i| { + out.entries[i] = try mtl.Pipeline.init(device, lib, name, false); + made += 1; + if (out.entries[i].maxThreads() < 32) return error.ExpertThreads; + } + return out; + } + + pub fn deinit(p: *Pipelines) void { + for (p.entries) |pipe| pipe.deinit(); + } + + fn get(p: *const Pipelines, op: Operation) mtl.Pipeline { + return p.entries[@backingInt(op)]; + } +}; + +fn args(c: Call) plan.MatrixArgs { + return .{ .k = c.k, .n = c.n, .topk = c.topk, .experts = c.experts }; +} + +fn launch(p: *const Pipelines, e: mtl.ComputeEncoder, op: Operation, groups: u32) void { + e.setPipeline(p.get(op)); + e.dispatchGroups(mtl.Size.of(groups, 1, 1), mtl.Size.of(32, 1, 1)); +} + +/// Packed NVFP4 GU: X [rows,k], ids [rows,topk], Y [rows*topk,n]. +pub fn nvfp4Gu(p: *const Pipelines, e: mtl.ComputeEncoder, x: Ref, w: Ref, scales: Ref, amax: Ref, denominator: Ref, ids: Ref, out: Ref, c: Call) !void { + if (c.format != .nvfp4) return error.WrongExpertFormat; + try plan.check(c); + for ([_]Ref{ x, w, scales, amax, denominator, ids, out }, 0..) |b, i| e.setBuffer(b.buf, b.off, i); + e.setValue(args(c), 7); + launch(p, e, .nvfp4_gu, plan.geometry(c).groups); +} + +/// Packed MXFP8 GU with UE8M0 scales per row/block32. +pub fn mxfp8Gu(p: *const Pipelines, e: mtl.ComputeEncoder, x: Ref, w: Ref, scales: Ref, ids: Ref, out: Ref, c: Call) !void { + if (c.format != .mxfp8) return error.WrongExpertFormat; + try plan.check(c); + for ([_]Ref{ x, w, scales, ids, out }, 0..) |b, i| e.setBuffer(b.buf, b.off, i); + e.setValue(args(c), 5); + launch(p, e, .mxfp8_gu, plan.geometry(c).groups); +} + +pub fn nvfp4Down(p: *const Pipelines, e: mtl.ComputeEncoder, act: Ref, w: Ref, scales: Ref, amax: Ref, denominator: Ref, ids: Ref, out: Ref, c: Call) !void { + if (c.format != .nvfp4) return error.WrongExpertFormat; + try plan.check(c); + for ([_]Ref{ act, w, scales, amax, denominator, ids, out }, 0..) |b, i| e.setBuffer(b.buf, b.off, i); + e.setValue(args(c), 7); + launch(p, e, .nvfp4_down, plan.geometry(c).groups); +} + +pub fn mxfp8Down(p: *const Pipelines, e: mtl.ComputeEncoder, act: Ref, w: Ref, scales: Ref, ids: Ref, out: Ref, c: Call) !void { + if (c.format != .mxfp8) return error.WrongExpertFormat; + try plan.check(c); + for ([_]Ref{ act, w, scales, ids, out }, 0..) |b, i| e.setBuffer(b.buf, b.off, i); + e.setValue(args(c), 5); + launch(p, e, .mxfp8_down, plan.geometry(c).groups); +} + +/// Decode one expert matrix to BF16, not an activation quantization operation. +pub fn nvfp4Quantize(p: *const Pipelines, e: mtl.ComputeEncoder, w: Ref, scales: Ref, amax: Ref, denominator: Ref, out: Ref, rows: u32, k: u32) !void { + if (k == 0 or k % 16 != 0 or rows == 0) return error.BadExpertBlock; + for ([_]Ref{ w, scales, amax, denominator, out }, 0..) |b, i| e.setBuffer(b.buf, b.off, i); + e.setValue(plan.DecodeArgs{ .rows = rows, .k = k }, 5); + launch(p, e, .nvfp4_quantize, (rows * k + 31) / 32); +} + +pub fn mxfp8Quantize(p: *const Pipelines, e: mtl.ComputeEncoder, w: Ref, scales: Ref, out: Ref, rows: u32, k: u32) !void { + if (k == 0 or k % 32 != 0 or rows == 0) return error.BadExpertBlock; + for ([_]Ref{ w, scales, out }, 0..) |b, i| e.setBuffer(b.buf, b.off, i); + e.setValue(plan.DecodeArgs{ .rows = rows, .k = k }, 3); + launch(p, e, .mxfp8_quantize, (rows * k + 31) / 32); +} + +/// Sum per-token BF16 down outputs in ascending expert index and round once to BF16. +pub fn combine(p: *const Pipelines, e: mtl.ComputeEncoder, down: Ref, ids: Ref, weights: Ref, out: Ref, c: Call) !void { + try plan.check(c); + for ([_]Ref{ down, ids, weights, out }, 0..) |b, i| e.setBuffer(b.buf, b.off, i); + e.setValue(args(c), 4); + // Combine has one group per token, rather than one per route pair. + launch(p, e, .combine, c.rows); +} + +pub fn gu(p: *const Pipelines, e: mtl.ComputeEncoder, x: Ref, w: Ref, scales: Ref, nv_globals: ?struct { amax: Ref, denominator: Ref }, ids: Ref, out: Ref, c: Call) !void { + switch (c.format) { + .nvfp4 => if (nv_globals) |g| return nvfp4Gu(p, e, x, w, scales, g.amax, g.denominator, ids, out, c) else return error.MissingNvfp4Globals, + .mxfp8 => return mxfp8Gu(p, e, x, w, scales, ids, out, c), + } +} diff --git a/zig/src/families/inkling2/metal/experts_plan.zig b/zig/src/families/inkling2/metal/experts_plan.zig new file mode 100644 index 00000000000..6b98f9fe18a --- /dev/null +++ b/zig/src/families/inkling2/metal/experts_plan.zig @@ -0,0 +1,102 @@ +//! Pure M3 layout, decode and activation math shared by the host and its scalar tests. +const std = @import("std"); + +pub const hidden: u32 = 2304; +pub const intermediate: u32 = 1152; +pub const expert_count: u32 = 128; +pub const top_k: u32 = 8; + +pub const Format = enum { + nvfp4, + mxfp8, + + pub fn block(f: Format) u32 { + return if (f == .nvfp4) 16 else 32; + } + pub fn codeBytes(f: Format, k: u32) u32 { + return if (f == .nvfp4) k / 2 else k; + } +}; + +pub const Call = struct { + rows: u32, + k: u32, + n: u32, + experts: u32 = expert_count, + topk: u32 = top_k, + format: Format, +}; + +pub const Geometry = struct { + groups: u32, + threads: u32 = 32, +}; + +pub fn geometry(c: Call) Geometry { + return .{ .groups = c.rows * c.topk }; +} + +pub fn check(c: Call) !void { + if (c.rows == 0 or c.k == 0 or c.n == 0 or c.experts == 0 or c.topk == 0 or c.topk > c.experts) + return error.BadExpertShape; + if (c.k % c.format.block() != 0 or (c.format == .nvfp4 and c.k % 2 != 0)) + return error.BadExpertBlock; +} + +pub fn formatForLayer(layer: u32) !Format { + if (layer < 20) return .nvfp4; + if (layer < 24) return .mxfp8; + return error.BadExpertLayer; +} + +pub fn roundBf16(v: f32) f32 { + const bits: u32 = @bitCast(v); + const rounded: u16 = if (std.math.isNan(v)) + @truncate((bits >> 16) | 0x40) + else + @truncate((bits +% 0x7fff +% ((bits >> 16) & 1)) >> 16); + return @bitCast(@as(u32, rounded) << 16); +} + +pub fn e2m1(code: u8) f32 { + const values = [_]f32{ 0, 0.5, 1, 1.5, 2, 3, 4, 6 }; + const v = values[code & 7]; + return if (code & 8 != 0) -v else v; +} + +pub fn e4m3(code: u8) f32 { + const exponent = (code >> 3) & 15; + const mantissa = code & 7; + if (exponent == 15 and mantissa == 7) return std.math.nan(f32); + const value = if (exponent == 0) + @as(f32, @floatFromInt(mantissa)) / 512.0 + else + std.math.ldexp(@as(f32, 1) + @as(f32, @floatFromInt(mantissa)) / 8.0, @as(i32, exponent) - 7); + return if (code & 0x80 != 0) -value else value; +} + +pub fn phi(amax: f32, denominator: f32) f32 { + return roundBf16(amax) / roundBf16(denominator); +} + +pub fn nvWeight(codes: u8, column: u32, scale: u8, factor: f32) f32 { + const code = if (column & 1 != 0) codes >> 4 else codes & 15; + return roundBf16(e2m1(code) * e4m3(scale) * factor); +} + +pub fn mxWeight(value: u8, scale: u8) f32 { + return roundBf16(std.math.ldexp(e4m3(value), @as(i32, scale) - 127)); +} + +pub fn softcap(x: f32, cap: f32) f32 { + return @floatCast(@as(f64, cap) * std.math.tanh(@as(f64, x) / @as(f64, cap))); +} + +/// Inputs are the two already-BF16-rounded GU results; the result rounds once at the end. +pub fn swiglu(gate: f32, up: f32) f32 { + const left = softcap(gate, 4) * (1 / (1 + std.math.exp(-gate))); + return roundBf16(left * softcap(up, 25)); +} + +pub const MatrixArgs = extern struct { k: u32, n: u32, topk: u32, experts: u32 }; +pub const DecodeArgs = extern struct { rows: u32, k: u32 }; diff --git a/zig/src/families/inkling2/metal/experts_test.zig b/zig/src/families/inkling2/metal/experts_test.zig new file mode 100644 index 00000000000..4ae2612b76f --- /dev/null +++ b/zig/src/families/inkling2/metal/experts_test.zig @@ -0,0 +1,144 @@ +//! Host-only M3 format, layout, BF16-rounding and dispatch-geometry tests. +const std = @import("std"); +const p = @import("experts_plan.zig"); + +fn bf16Chain(terms: []const f32, stride: usize, first: usize) f32 { + var sum: f32 = 0; + var i = first; + while (i < terms.len) : (i += stride) sum = p.roundBf16(sum + p.roundBf16(terms[i])); + return sum; +} + +fn bf16Halves(terms: []const f32) f32 { + if (terms.len == 0) return 0; + if (terms.len == 1) return p.roundBf16(terms[0]); + const mid = terms.len / 2; + return p.roundBf16(bf16Halves(terms[0..mid]) + bf16Halves(terms[mid..])); +} + +fn bf16Strided(terms: []const f32) f32 { + var lanes: [32]f32 = @splat(0); + for (&lanes, 0..) |*lane, i| lane.* = bf16Chain(terms, 32, i); + return bf16Halves(&lanes); +} + +test "Mini layer formats and dimensions are a clean cut at layer 20" { + for (0..20) |layer| try std.testing.expectEqual(p.Format.nvfp4, try p.formatForLayer(@intCast(layer))); + for (20..24) |layer| try std.testing.expectEqual(p.Format.mxfp8, try p.formatForLayer(@intCast(layer))); + try std.testing.expectError(error.BadExpertLayer, p.formatForLayer(24)); + try std.testing.expectEqual(@as(u32, 2304), p.hidden); + try std.testing.expectEqual(@as(u32, 1152), p.intermediate); + try std.testing.expectEqual(@as(u32, 128), p.expert_count); + try std.testing.expectEqual(@as(u32, 8), p.top_k); +} + +test "every E2M1 code decodes low/high nibble and signed zero" { + const magnitude = [_]f32{ 0, 0.5, 1, 1.5, 2, 3, 4, 6 }; + for (0..16) |code| { + const want = if (code & 8 != 0) -magnitude[code & 7] else magnitude[code & 7]; + try std.testing.expectEqual(want, p.e2m1(@intCast(code))); + } + const byte: u8 = 0xa7; // low 7 = 6, high 10 = -1 + try std.testing.expectEqual(@as(f32, 6), p.nvWeight(byte, 0, 0x38, 1)); + try std.testing.expectEqual(@as(f32, -1), p.nvWeight(byte, 1, 0x38, 1)); + try std.testing.expectEqual(@as(f32, 0), p.e2m1(8)); +} + +test "all E4M3 values match the independent half-bit decode" { + for (0..256) |raw| { + const code: u8 = @intCast(raw); + const h: f16 = @bitCast(@as(u16, code & 0x7f) << 7); + const magnitude = @as(f32, h) * 256; + const want = if ((code & 0x80) != 0) -magnitude else magnitude; + const got = p.e4m3(code); + // E4M3FN reserves 0x7f for NaN; the half-bit helper alone does not encode that case. + if ((code & 0x7f) == 0x7f) { + try std.testing.expect(std.math.isNan(got)); + } else try std.testing.expectEqual(want, got); + } +} + +test "NVFP4 globals round to BF16 before one FP32 division" { + const amax: f32 = @bitCast(@as(u32, 0x3f80_8001)); + const den: f32 = @bitCast(@as(u32, 0x4534_0001)); + const rounded_den = p.roundBf16(den); + try std.testing.expect(den != rounded_den); + try std.testing.expectEqual(p.roundBf16(amax) / rounded_den, p.phi(amax, den)); + try std.testing.expect(p.phi(amax, den) != amax / den); // A2: the reference rounds both loader inputs. + const raw = p.e2m1(7) * p.e4m3(0x40) * p.phi(amax, den); + try std.testing.expectEqual(p.roundBf16(raw), p.nvWeight(7, 0, 0x40, p.phi(amax, den))); +} + +test "every MXFP8 value and UE8M0 exponent is exactly BF16 decoded" { + for ([_]u8{ 0, 1, 126, 127, 128, 129, 254, 255 }) |scale| for (0..256) |raw| { + const code: u8 = @intCast(raw); + const want = std.math.ldexp(p.e4m3(code), @as(i32, scale) - 127); + if (std.math.isNan(want)) { + try std.testing.expect(std.math.isNan(p.mxWeight(code, scale))); + } else try std.testing.expectEqual(p.roundBf16(want), p.mxWeight(code, scale)); + }; +} + +test "GU BF16 round precedes cap sigmoid cap and final BF16 activation" { + const raw_gate: f32 = -10; + const raw_up: f32 = -9.4; + const g = p.roundBf16(raw_gate); + const u = p.roundBf16(raw_up); + const capped_g: f64 = 4 * std.math.tanh(@as(f64, g) / 4); + const sigmoid: f64 = 1 / (1 + @exp(-@as(f64, g))); + const capped_u: f64 = 25 * std.math.tanh(@as(f64, u) / 25); + const wide = capped_g * sigmoid * capped_u; + try std.testing.expectEqual(@as(f32, @floatCast(@import("bf16_round").bf16(wide))), p.swiglu(g, u)); + try std.testing.expect(p.swiglu(raw_gate, raw_up) != p.swiglu(g, u)); +} + +test "combine route control overflows slot order while ascending experts remain finite" { + const values = [_]f32{ 1, 2, 3, 4, 5, 6, 7, 8 }; + const weights = [_]f32{ 0x1p127, 0x1p126, -0x1p127 / 3.0, 0.25, -0.2, 1.0 / 3.0, -2.0 / 7.0, 0.375 }; + var terms: [8]f32 = undefined; + for (&terms, values, weights) |*term, value, weight| term.* = value * weight; + var route_sum: f32 = 0; + for (terms) |term| route_sum += term; + try std.testing.expect(std.math.isInf(route_sum) and route_sum > 0); + + const ids = [_]i32{ 2, 0, 1, 7, 3, 6, 4, 5 }; + var expert_sum: f32 = 0; + for (0..8) |expert| for (0..8) |slot| if (ids[slot] == expert) { + expert_sum += terms[slot]; + }; + try std.testing.expect(std.math.isFinite(expert_sum) and expert_sum > 0); +} + +test "eight-term combine stress separates FP32 and BF16 in every contract order" { + const terms = [_]f32{ 1024, 1, 1, 1, 1, 1, 1, -1029 }; + var forward: f32 = 0; + var reverse: f32 = 0; + for (terms) |term| forward += term; + for (1..terms.len + 1) |n| reverse += terms[terms.len - n]; + try std.testing.expectEqual(@as(f32, 1), forward); + try std.testing.expectEqual(@as(f32, 1), reverse); + + const reduced = [_]f32{ bf16Chain(&terms, 1, 0), bf16Halves(&terms), bf16Strided(&terms) }; + for (reduced) |sum| try std.testing.expectEqual(@as(f32, -8), sum); + const exact_allowance = (3 * 0x1p-24 + 0x1p-8) + 0x1p-38; + try std.testing.expect(9.0 / exact_allowance >= 100); +} + +test "launch geometry is 32 scalar threads and validates block/layout edges" { + const nv = p.Call{ .rows = 3, .k = 2304, .n = 1152, .format = .nvfp4 }; + try p.check(nv); + try std.testing.expectEqual(@as(u32, 24), p.geometry(nv).groups); + try std.testing.expectEqual(@as(u32, 32), p.geometry(nv).threads); + const mx = p.Call{ .rows = 1, .k = 1152, .n = 2304, .format = .mxfp8 }; + try p.check(mx); + var bad = nv; + bad.k = 17; + try std.testing.expectError(error.BadExpertBlock, p.check(bad)); + bad = nv; + bad.topk = 129; + try std.testing.expectError(error.BadExpertShape, p.check(bad)); + try std.testing.expectEqual(@as(usize, 16), @sizeOf(p.MatrixArgs)); + try std.testing.expectEqual(@as(usize, 8), @sizeOf(p.DecodeArgs)); + try std.testing.expectEqual(@as(usize, 0), @offsetOf(p.MatrixArgs, "k")); + try std.testing.expectEqual(@as(usize, 12), @offsetOf(p.MatrixArgs, "experts")); +} diff --git a/zig/src/families/inkling2/metal/forward.zig b/zig/src/families/inkling2/metal/forward.zig new file mode 100644 index 00000000000..afb7382ba5f --- /dev/null +++ b/zig/src/families/inkling2/metal/forward.zig @@ -0,0 +1,348 @@ +//! Mini's whole 48-visit forward, encoded entirely on Metal for prompt chunks and decode. +const std = @import("std"); +const mtl = @import("metal"); +const ck = @import("../../../core/checkpoint_metal.zig"); +const layer_plan = @import("../plan.zig"); +const ap = @import("attention_plan.zig"); +const attention = @import("attention.zig"); +const glue = @import("glue.zig"); +const experts = @import("experts.zig"); +const loop = @import("loop.zig"); +const state = @import("state.zig"); +const model_file = @import("model.zig"); +const Model = model_file.Model; + +pub const Ref = state.Ref; +pub const Segment = struct { cache: *state.Cache, rows: usize }; +pub const Options = struct { + all: bool = false, + ids: ?Ref = null, + flight: ?*mtl.CommandBuffer = null, + taps: ?state.Ref = null, +}; + +pub const FinalPlan = struct { work_rows: usize, logits_rows: usize, logits_row: usize, capture_rows: usize }; + +/// Features normalize all rows; without full logits, only the last unembeds. taps=null preserves the original plan. +pub fn finalPlan(rows: usize, all: bool, taps: bool) FinalPlan { + std.debug.assert(rows > 0); + return .{ + .work_rows = if (all or taps) rows else 1, + .logits_rows = if (all) rows else 1, + .logits_row = if (!all and taps) rows - 1 else 0, + .capture_rows = if (taps) rows else 0, + }; +} + +const RArgs = extern struct { count: u32, boundary: u32 = 0 }; +const NormArgs = extern struct { rows: u32, width: u32, heads: u32 = 0, bits: u32 = 0, group: u32 = 0, eps: f32 }; +const DenseArgs = extern struct { rows: u32, n: u32, k: u32, ldy: u32 }; + +fn r(t: ck.Tensor) Ref { + return .{ .buf = t.buffer, .off = t.offset }; +} +fn at(buf: mtl.Buffer, off: usize) Ref { + return .{ .buf = buf, .off = off }; +} +fn row(buf: mtl.Buffer, i: usize, row_bytes: usize) Ref { + return at(buf, i * row_bytes); +} +fn a(x_: Ref) attention.Ref { + return .{ .buf = x_.buf, .off = x_.off }; +} +fn x(x_: Ref) experts.Ref { + return .{ .buf = x_.buf, .off = x_.off }; +} +fn l(x_: Ref) loop.Ref { + return .{ .buf = x_.buf, .off = x_.off }; +} +fn arRow(s: *state.Scratch, role: usize, rows: usize, i: usize, gated: bool) Ref { + return at(if (gated) s.gated else s.ar, (role * rows + i) * state.hidden * 4); +} +fn messageRow(s: *state.Scratch, core: usize, role: usize, i: usize) Ref { + return at(s.messages, ((i * state.message_entries + core * 4 + role) * state.hidden) * 4); +} + +fn runtime(m: *const Model, e: mtl.ComputeEncoder, op: model_file.RuntimeOp, refs: []const Ref, count: usize, boundary: usize) void { + e.setPipeline(m.runtime[@backingInt(op)]); + for (refs, 0..) |r_, i| e.setBuffer(r_.buf, r_.off, i); + e.setValue(RArgs{ .count = @intCast(count), .boundary = @intCast(boundary) }, refs.len); + e.dispatchThreads(mtl.Size.of(count, 1, 1), mtl.Size.of(256, 1, 1)); +} + +fn copyBf16(m: *const Model, e: mtl.ComputeEncoder, from: Ref, to: Ref, count: usize) void { + runtime(m, e, .copy_bf16, &.{ from, to }, count, 0); +} +fn captureTap(m: *const Model, e: mtl.ComputeEncoder, from: Ref, to: Ref, rows: usize, channel: usize) void { + std.debug.assert(channel < state.feature_taps); + runtime(m, e, .capture_tap, &.{ from, to }, rows * state.hidden, channel); +} +fn widen(m: *const Model, e: mtl.ComputeEncoder, from: Ref, to: Ref, count: usize) void { + runtime(m, e, .widen, &.{ from, to }, count, 0); +} + +fn norm(m: *const Model, e: mtl.ComputeEncoder, input: Ref, weight: ck.Tensor, out: Ref, rows: usize) void { + e.setPipeline(m.norm); + e.setBuffer(input.buf, input.off, 0); + e.setBuffer(weight.buffer, weight.offset, 1); + e.setValue(NormArgs{ .rows = @intCast(rows), .width = state.hidden, .eps = 1e-6 }, 2); + e.setBuffer(out.buf, out.off, 3); + e.dispatchGroups(mtl.Size.of(rows, 1, 1), mtl.Size.of(256, 1, 1)); +} + +/// Every projection uses the shared BF16 matvec's FP32 reduction and one BF16 store. +pub fn dense(m: *const Model, e: mtl.ComputeEncoder, weight: ck.Tensor, input: Ref, out: Ref, rows: usize) void { + const k = weight.shape[weight.rank - 1]; + const n = weight.shape[weight.rank - 2]; + var base: usize = 0; + while (base < rows) { + const left = rows - base; + const take: usize = if (left >= 32) 32 else if (left >= 16) 16 else if (left >= 8) 8 else if (left >= 4) 4 else if (left >= 2) 2 else 1; + const variant: usize = switch (take) { + 1 => 0, + 2 => 1, + 4 => 2, + 8 => 3, + 16 => 4, + 32 => 5, + else => unreachable, + }; + e.setPipeline(m.dense[variant]); + e.setBuffer(input.buf, input.off + base * k * 2, 0); + e.setBuffer(weight.buffer, weight.offset, 1); + e.setValue(DenseArgs{ .rows = @intCast(take), .n = @intCast(n), .k = @intCast(k), .ldy = @intCast(n) }, 2); + e.setBuffer(out.buf, out.off + base * n * 2, 3); + e.dispatchGroups(mtl.Size.of((n + 7) / 8, 1, 1), mtl.Size.of(256, 1, 1)); + base += take; + } +} + +/// One row because M2's AR ABI is [sources,H] -> [queries,H]. Batch composition never mixes rows. +fn residual(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, queries: ck.Tensor, sources: usize, rows: usize) void { + for (0..rows) |i| glue.ar(&m.glue, e, at(s.blocks, i * state.block_slots * state.hidden * 2), row(s.partial, i, state.hidden * 4), r(queries), row(s.mlp_ar, i, state.hidden * 4), @intCast(sources), 1); +} + +fn bankAndReset(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, rows: usize) void { + for (0..rows) |i| { + // The second completed block of the previous pass is B12; its final p is P18. + copyBf16(m, e, at(s.blocks, (i * state.block_slots + 2) * state.hidden * 2), row(s.bank0, i, state.hidden * 2), state.hidden); + } + copyBf16(m, e, at(s.p, 0), at(s.bank1, 0), rows * state.hidden); + loop.crossPassMessageAttention(&m.loop, e, l(at(s.bank0, 0)), l(at(s.bank1, 0)), l(r(m.weights.cross_queries)), l(r(m.weights.cross_kv_queries)), l(at(s.messages, 0)), @intCast(rows)); + // The prelude p is restored, but every visit's KV and convolution state remains live. + copyBf16(m, e, at(s.prelude, 0), at(s.p, 0), rows * state.hidden); +} + +fn prepareAttentionInputs(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, v: *const layer_plan.Visit, rows: usize) void { + const lp = m.weight_plan.at(v.layer); + const w = &m.weights.layers[v.layer]; + if (v.layer == 0) { + widen(m, e, at(s.p, 0), at(s.ar, 0), rows * state.hidden); + } else { + const q = m.weights.attn_queries[v.layer - 1]; + for (0..lp.attn_queries) |role| { + const query = at(q.buffer, q.offset + role * state.hidden * 4); + for (0..rows) |i| glue.ar(&m.glue, e, at(s.blocks, i * state.block_slots * state.hidden * 2), row(s.partial, i, state.hidden * 4), query, arRow(s, role, rows, i, false), lp.attn_sources, 1); + } + } + if (v.hasMessages()) { + const controllers = w.controllers.?; + const core = v.layer - 6; + for (0..3) |role| for (0..rows) |i| { + const c = controllers[role]; + const source_role = if (lp.kind == .local) 0 else role; + loop.gates(&m.loop, e, l(arRow(s, source_role, rows, i, false)), l(messageRow(s, core, role, i)), l(r(c.down)), l(r(c.forget)), l(r(c.gain)), l(arRow(s, role, rows, i, true)), 1); + }; + } + const gated = v.hasMessages(); + // An ungated local visit has exactly one AR result and one norm result; Q/K/V alias. + if (!gated and lp.kind == .local) { + norm(m, e, arRow(s, 0, rows, 0, false), w.attn.q_norm, at(s.q_norm, 0), rows); + } else { + norm(m, e, arRow(s, 0, rows, 0, gated), w.attn.q_norm, at(s.q_norm, 0), rows); + norm(m, e, arRow(s, 1, rows, 0, gated), w.attn.k_norm, at(s.k_norm, 0), rows); + norm(m, e, arRow(s, 2, rows, 0, gated), w.attn.v_norm, at(s.v_norm, 0), rows); + } +} + +fn staticPostConv(m: *const Model, e: mtl.ComputeEncoder, cache: *state.Cache, slot: usize, conv_state: usize, raw: Ref, weight: ck.Tensor, out: Ref, base: usize, rows: usize) void { + const channels = state.convWidth(conv_state); + const taps = cache.staged(slot, conv_state, 0); + copyBf16(m, e, cache.history(slot, conv_state), taps, 3 * channels); + copyBf16(m, e, at(raw.buf, raw.off + base * channels * 2), cache.staged(slot, conv_state, 3), rows * channels); + glue.convStatic(&m.glue, e, taps, r(weight), at(out.buf, out.off + base * channels * 2), @intCast(rows), @intCast(channels)); +} + +fn attendSegments(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, v: *const layer_plan.Visit, segments: []const Segment) !void { + var base: usize = 0; + for (segments, 0..) |seg, si| { + const rows = seg.rows; + const cache = seg.cache; + const layer0 = cache.attentionLayer(&m.weight_plan, v.cache_slot, rows); + const layer = ap.Layer{ .window = layer0.window, .ring = @intCast(cache.ring(v.cache_slot)), .chunk = layer0.chunk, .tau = layer0.tau }; + const start = cache.len; + const rr = ap.Rows{ .rows = @intCast(rows), .heads = 24, .kv_heads = 8, .last_pos = @intCast(start + rows - 1), .streams = 1 }; + const prep = ap.Prep{ .qk_clip = m.config.text.qk_clip, .rel_clip = m.config.text.rel_clip, .floor = @floatFromInt(m.config.text.log_floor), .alpha = m.config.text.log_alpha, .eps = m.config.text.eps }; + const meta = attention.RowMeta{ + .pos = a(at(s.pos, base * 4)), + .seg_of = a(at(s.seg_of, base * 4)), + .segs = a(at(s.segs, si * @sizeOf(ap.Seg))), + }; + const kv = attention.Cache{ .k = a(cache.keys(v.cache_slot)), .v = a(cache.values(v.cache_slot)) }; + try convInputForAttention(m, e, s, cache, v, base, rows, true); + try convInputForAttention(m, e, s, cache, v, base, rows, false); + attention.prep(&m.attention, e, rr, layer, prep, meta, .{ a(at(s.q_raw, base * state.query_width * 2)), a(at(s.k_conv, base * state.kv_width * 2)), a(at(s.v_conv, base * state.kv_width * 2)), a(at(s.rel_raw, base * state.rel_width * 2)) }, .{ a(r(m.weights.layers[v.layer].attn.q_scale)), a(r(m.weights.layers[v.layer].attn.rel_scale)) }, a(at(s.q_prep, base * state.query_width * 2)), a(at(s.rel_prep, base * state.rel_width * 2)), kv); + attention.relTable(&m.attention, e, rr, a(at(s.rel_prep, base * state.rel_width * 2)), a(r(m.weights.layers[v.layer].attn.rel_projection)), a(at(s.rel_tab, base * 24 * ap.extent * 2))); + try attention.attend(&m.attention, e, rr, layer, state.max_attention_stride, 0, meta, a(at(s.q_prep, base * state.query_width * 2)), kv, a(at(s.rel_tab, base * 24 * ap.extent * 2)), a(at(s.part_o, base * 24 * state.max_attention_stride * ap.head_dim * 4)), a(at(s.part_ml, base * 24 * state.max_attention_stride * 8)), a(at(s.sink, base * 24 * 2)), a(at(s.gate, base * state.query_width * 2)), a(at(s.att, base * state.query_width * 2))); + base += rows; + } +} + +fn convInputForAttention(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, cache: *state.Cache, v: *const layer_plan.Visit, base: usize, rows: usize, key: bool) !void { + const lp = m.weight_plan.at(v.layer); + const w = &m.weights.layers[v.layer]; + const raw = if (key) at(s.k_conv, base * state.kv_width * 2) else at(s.v_conv, base * state.kv_width * 2); + const projected = if (key) at(s.k_raw, base * state.kv_width * 2) else at(s.v_raw, base * state.kv_width * 2); + const normalized = if (key) at(s.k_norm, 0) else if (v.hasMessages() or lp.kind == .global) at(s.v_norm, 0) else at(s.q_norm, 0); + const taps = cache.staged(v.cache_slot, if (key) 0 else 1, 0); + copyBf16(m, e, cache.history(v.cache_slot, if (key) 0 else 1), taps, 3 * state.kv_width); + copyBf16(m, e, projected, cache.staged(v.cache_slot, if (key) 0 else 1, 3), rows * state.kv_width); + switch (if (key) w.attn.k_conv else w.attn.v_conv) { + .static => |weight| glue.convStatic(&m.glue, e, taps, r(weight), raw, @intCast(rows), state.kv_width), + .dynamic => |d| glue.convDynamic(&m.glue, e, taps, at(normalized.buf, normalized.off + base * state.hidden * 2), r(d.static_w), r(d.projection), raw, @intCast(rows), state.kv_width), + } +} + +fn routedExperts(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, layer: usize, rows: usize) !void { + const w = &m.weights.layers[layer]; + const precision: experts.Format = switch (m.weight_plan.at(@intCast(layer)).precision) { + .nvfp4 => .nvfp4, + .mxfp8 => .mxfp8, + }; + const gu_call = experts.Call{ .rows = @intCast(rows), .k = state.hidden, .n = state.intermediate, .format = precision }; + const down_call = experts.Call{ .rows = @intCast(rows), .k = state.intermediate, .n = state.hidden, .format = precision }; + if (precision == .nvfp4) { + try experts.gu(&m.experts, e, x(at(s.mlp_normed, 0)), x(r(w.gu.weight)), x(r(w.gu.scale)), .{ .amax = x(r(w.gu.amax.?)), .denominator = x(r(w.gu.denominator.?)) }, x(at(s.route_ids, 0)), x(at(s.gu, 0)), gu_call); + } else { + try experts.gu(&m.experts, e, x(at(s.mlp_normed, 0)), x(r(w.gu.weight)), x(r(w.gu.scale)), null, x(at(s.route_ids, 0)), x(at(s.gu, 0)), gu_call); + } + switch (precision) { + .nvfp4 => try experts.nvfp4Down(&m.experts, e, x(at(s.gu, 0)), x(r(w.down.weight)), x(r(w.down.scale)), x(r(w.down.amax.?)), x(r(w.down.denominator.?)), x(at(s.route_ids, 0)), x(at(s.down, 0)), down_call), + .mxfp8 => try experts.mxfp8Down(&m.experts, e, x(at(s.gu, 0)), x(r(w.down.weight)), x(r(w.down.scale)), x(at(s.route_ids, 0)), x(at(s.down, 0)), down_call), + } + try experts.combine(&m.experts, e, x(at(s.down, 0)), x(at(s.route_ids, 0)), x(at(s.route_weights, 0)), x(at(s.mlp_out, 0)), down_call); +} + +fn visit(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, v: *const layer_plan.Visit, segments: []const Segment, rows: usize, taps: ?state.Ref) !void { + const lp = m.weight_plan.at(v.layer); + const gated = v.hasMessages(); + if (taps) |to| { + const channel: ?usize = switch (v.cache_slot) { + 5 => 0, + 23 => 1, + 41 => 2, + else => null, + }; + if (channel) |ch| captureTap(m, e, at(s.p, 0), to, rows, ch); + } + if (v.pass > 1 and v.layer == 6) bankAndReset(m, e, s, rows); + const w = &m.weights.layers[v.layer]; + // The running BF16 p is the partial AR source before attention replaces it with t. + widen(m, e, at(s.p, 0), at(s.partial, 0), rows * state.hidden); + prepareAttentionInputs(m, e, s, v, rows); + const knorm = if (gated or lp.kind == .global) at(s.k_norm, 0) else at(s.q_norm, 0); + const vnorm = if (gated or lp.kind == .global) at(s.v_norm, 0) else at(s.q_norm, 0); + dense(m, e, w.attn.wq, at(s.q_norm, 0), at(s.q_raw, 0), rows); + dense(m, e, w.attn.wk, knorm, at(s.k_raw, 0), rows); + dense(m, e, w.attn.wv, vnorm, at(s.v_raw, 0), rows); + dense(m, e, w.attn.wr, at(s.q_norm, 0), at(s.rel_raw, 0), rows); + dense(m, e, w.attn.sink, at(s.q_norm, 0), at(s.sink, 0), rows); + dense(m, e, w.attn.gate, at(s.q_norm, 0), at(s.gate, 0), rows); + try attendSegments(m, e, s, v, segments); + dense(m, e, w.attn.wo, at(s.att, 0), at(s.attn_dense, 0), rows); + var base: usize = 0; + for (segments) |seg| { + staticPostConv(m, e, seg.cache, v.cache_slot, 2, at(s.attn_dense, 0), w.attn_conv, at(s.attn_conv, 0), base, seg.rows); + base += seg.rows; + } + runtime(m, e, .attention_partial, &.{ at(s.p, 0), at(s.attn_conv, 0), at(s.blocks, 0), at(s.partial, 0) }, rows * state.hidden, if (lp.boundary) lp.blocks_in + 1 else 0); + residual(m, e, s, m.weights.mlp_queries[v.layer], lp.mlp_sources, rows); + if (gated) { + const c = w.controllers.?[3]; + const core = v.layer - 6; + for (0..rows) |i| loop.gates(&m.loop, e, l(row(s.mlp_ar, i, state.hidden * 4)), l(messageRow(s, core, 3, i)), l(r(c.down)), l(r(c.forget)), l(r(c.gain)), l(row(s.mlp_gated, i, state.hidden * 4)), 1); + norm(m, e, at(s.mlp_gated, 0), w.mlp_norm, at(s.mlp_normed, 0), rows); + } else norm(m, e, at(s.mlp_ar, 0), w.mlp_norm, at(s.mlp_normed, 0), rows); + glue.router(&m.glue, e, at(s.mlp_normed, 0), r(w.router_weight), r(w.router_bias), at(s.route_ids, 0), at(s.route_weights, 0), @intCast(rows)); + try routedExperts(m, e, s, v.layer, rows); + base = 0; + for (segments) |seg| { + staticPostConv(m, e, seg.cache, v.cache_slot, 3, at(s.mlp_out, 0), w.mlp_conv, at(s.mlp_conv, 0), base, seg.rows); + base += seg.rows; + } + runtime(m, e, .mlp_partial, &.{ at(s.partial, 0), at(s.mlp_conv, 0), at(s.p, 0) }, rows * state.hidden, 0); + if (v.cache_slot == 5) copyBf16(m, e, at(s.p, 0), at(s.prelude, 0), rows * state.hidden); +} + +fn commitFullHistories(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, segments: []const Segment) void { + _ = s; + for (segments) |seg| for (0..state.visit_slots) |slot| for (0..state.conv_states) |cs| { + copyBf16(m, e, seg.cache.staged(slot, cs, seg.rows), seg.cache.history(slot, cs), 3 * state.convWidth(cs)); + }; +} + +pub fn run(m: *const Model, s: *state.Scratch, cache: *state.Cache, ids: []const u32, options: Options) !void { + return runShared(m, s, &.{.{ .cache = cache, .rows = ids.len }}, ids, options); +} + +pub fn runShared(m: *const Model, s: *state.Scratch, segments: []const Segment, ids: []const u32, options: Options) !void { + const rows = ids.len; + if (rows == 0 or rows > s.rows or segments.len == 0 or segments.len > state.max_segments or (!options.all and segments.len != 1)) return error.Inkling2RowsExceeded; + var total: usize = 0; + var base: usize = 0; + for (segments, 0..) |seg, si| { + if (seg.rows == 0 or seg.rows > state.max_rows or seg.cache.len + seg.rows > seg.cache.capacity) return error.Inkling2ContextFull; + if (seg.rows > state.window_rows and seg.cache.pending != null) return error.Inkling2CacheTransaction; + if (seg.cache.pending) |pending| if (pending != seg.rows) return error.Inkling2CacheTransaction; + total += seg.rows; + for (0..seg.rows) |i| { + s.pos.slice(i32, rows)[base + i] = @intCast(seg.cache.len + i); + s.seg_of.slice(i32, rows)[base + i] = 0; + } + s.segs.slice(ap.Seg, state.max_segments)[si] = .{ .row0 = 0, .n = @intCast(seg.rows), .p0 = @intCast(seg.cache.len), .off = 0 }; + base += seg.rows; + } + if (total != rows) return error.Inkling2Segments; + if (options.ids == null) { + for (ids) |id| if (id >= m.config.text.vocab) return error.Inkling2Token; + @memcpy(s.ids.slice(u32, rows), ids); + } + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const cb = m.queue.commandBuffer(); + const e = cb.compute(.serial); + glue.embedNorm(&m.glue, e, options.ids orelse at(s.ids, 0), r(m.weights.embed), r(m.weights.embed_norm), at(s.p, 0), @intCast(rows)); + for (m.weight_plan.visits[0..m.weight_plan.n_visits]) |*v| try visit(m, e, s, v, segments, rows, options.taps); + widen(m, e, at(s.p, 0), at(s.partial, 0), rows * state.hidden); + const final = finalPlan(rows, options.all, options.taps != null); + for (0..final.work_rows) |j| { + const i = if (final.work_rows == rows) j else rows - 1; + glue.ar(&m.glue, e, at(s.blocks, i * state.block_slots * state.hidden * 2), row(s.partial, i, state.hidden * 4), r(m.weights.output_query), row(s.mlp_ar, j, state.hidden * 4), m.weight_plan.final_sources, 1); + } + norm(m, e, at(s.mlp_ar, 0), m.weights.norm, at(s.mlp_normed, 0), final.work_rows); + if (options.taps) |to| captureTap(m, e, at(s.mlp_normed, 0), to, final.capture_rows, 3); + const logits = if (options.all) at(s.logits_all, 0) else at(segments[0].cache.logits, 0); + glue.logits(&m.glue, e, at(s.mlp_normed, final.logits_row * state.hidden * 2), r(m.weights.unembed), logits, @intCast(final.logits_rows), m.config.text.unpadded_vocab); + commitFullHistories(m, e, s, segments); + e.end(); + cb.commit(); + if (options.flight) |flight| { + flight.* = cb.retain(); + return; + } + cb.wait(); + if (cb.failure()) |msg| { + std.log.err("inkling2_loop forward: {s}", .{msg}); + return error.GpuFailed; + } +} diff --git a/zig/src/families/inkling2/metal/glue.zig b/zig/src/families/inkling2/metal/glue.zig new file mode 100644 index 00000000000..dd74a1735a5 --- /dev/null +++ b/zig/src/families/inkling2/metal/glue.zig @@ -0,0 +1,146 @@ +//! Inkling 2 Mini glue on Metal: the production shader and its real encoder dispatches. +const std = @import("std"); +const mtl = @import("metal"); +const sources = @import("inkling2_metal"); +pub const plan = @import("inkling2_glue_plan"); + +pub const hidden: u32 = 2304; +pub const experts: u32 = 128; +pub const intermediate: u32 = 1152; +pub const top: u32 = 8; +pub const Ref = @import("inkling2_metal_ref").Ref; +const unit = mtl.Size.of(32, 1, 1); + +pub const Pipelines = struct { + embed_norm: mtl.Pipeline, + ar: mtl.Pipeline, + conv_static: mtl.Pipeline, + conv_dynamic: mtl.Pipeline, + router: mtl.Pipeline, + swiglu: mtl.Pipeline, + logits: mtl.Pipeline, + expert_pick: mtl.Pipeline, + expert_combine: mtl.Pipeline, + + pub fn load(device: mtl.Device) !Pipelines { + return loadSource(device, sources.glue); + } + pub fn loadSource(device: mtl.Device, text: []const u8) !Pipelines { + const lib = try mtl.Library.fromSource(device, text, mtl.CompileOptions.mlx()); + defer lib.deinit(); + var pipes: [9]mtl.Pipeline = undefined; + var made: usize = 0; + errdefer for (pipes[0..made]) |pipe| pipe.deinit(); + for ([_][]const u8{ + "tf_inkling2_embed_norm", + "tf_inkling2_ar", + "tf_inkling2_conv_static", + "tf_inkling2_conv_dynamic", + "tf_inkling2_router", + "tf_inkling2_swiglu", + "tf_inkling2_logits", + "tf_inkling2_expert_pick", + "tf_inkling2_expert_combine", + }, &pipes) |name, *pipe| { + pipe.* = try mtl.Pipeline.init(device, lib, name, false); + made += 1; + } + return .{ + .embed_norm = pipes[0], + .ar = pipes[1], + .conv_static = pipes[2], + .conv_dynamic = pipes[3], + .router = pipes[4], + .swiglu = pipes[5], + .logits = pipes[6], + .expert_pick = pipes[7], + .expert_combine = pipes[8], + }; + } + pub fn deinit(p: *Pipelines) void { + inline for (@typeInfo(Pipelines).@"struct".field_names) |name| @field(p, name).deinit(); + } +}; + +const EmbedArgs = extern struct { rows: u32 }; +pub fn embedNorm(p: *const Pipelines, e: mtl.ComputeEncoder, ids: Ref, table: Ref, weight: Ref, out: Ref, rows: u32) void { + std.debug.assert(rows > 0); + e.setPipeline(p.embed_norm); + inline for (.{ ids, table, weight, out }, 0..) |r, i| e.setBuffer(r.buf, r.off, i); + e.setValue(EmbedArgs{ .rows = rows }, 4); + e.dispatchGroups(mtl.Size.of(rows, 1, 1), mtl.Size.of(256, 1, 1)); +} + +const ARArgs = extern struct { sources: u32, queries: u32 }; +/// sources = completed BF16 blocks plus one unrounded F32 partial; output is one FP32 row per query. +pub fn ar(p: *const Pipelines, e: mtl.ComputeEncoder, blocks: Ref, partial: Ref, queries: Ref, out: Ref, sources_: u32, queries_: u32) void { + std.debug.assert(sources_ > 0 and sources_ <= 5 and queries_ > 0 and queries_ <= 3); + e.setPipeline(p.ar); + inline for (.{ blocks, partial, queries, out }, 0..) |r, i| e.setBuffer(r.buf, r.off, i); + e.setValue(ARArgs{ .sources = sources_, .queries = queries_ }, 4); + e.dispatchGroups(mtl.Size.of(queries_, 1, 1), mtl.Size.of(256, 1, 1)); +} + +const ConvArgs = extern struct { rows: u32, channels: u32 }; +/// taps contains three old rows followed by `rows` current BF16 inputs. +pub fn convStatic(p: *const Pipelines, e: mtl.ComputeEncoder, taps: Ref, weight: Ref, out: Ref, rows: u32, channels: u32) void { + std.debug.assert(rows > 0 and channels > 0); + e.setPipeline(p.conv_static); + inline for (.{ taps, weight, out }, 0..) |r, i| e.setBuffer(r.buf, r.off, i); + e.setValue(ConvArgs{ .rows = rows, .channels = channels }, 3); + e.dispatchThreads(mtl.Size.of(channels, rows, 1), unit); +} + +/// Dynamic static_w is [lag][channel], the opposite orientation to static convolution taps. +pub fn convDynamic(p: *const Pipelines, e: mtl.ComputeEncoder, taps: Ref, input: Ref, static_w: Ref, projection: Ref, out: Ref, rows: u32, channels: u32) void { + std.debug.assert(rows > 0 and channels > 0 and channels <= 1024); + e.setPipeline(p.conv_dynamic); + inline for (.{ taps, input, static_w, projection, out }, 0..) |r, i| e.setBuffer(r.buf, r.off, i); + e.setValue(ConvArgs{ .rows = rows, .channels = channels }, 5); + e.dispatchGroups(mtl.Size.of(rows, 1, 1), mtl.Size.of(256, 1, 1)); +} + +const RouteArgs = extern struct { rows: u32 }; +/// Router IDs and weights are sorted by ascending expert index for the deterministic expert sum. +pub fn router(p: *const Pipelines, e: mtl.ComputeEncoder, x: Ref, weight: Ref, bias: Ref, ids: Ref, weights: Ref, rows: u32) void { + std.debug.assert(rows > 0); + e.setPipeline(p.router); + inline for (.{ x, weight, bias, ids, weights }, 0..) |r, i| e.setBuffer(r.buf, r.off, i); + e.setValue(RouteArgs{ .rows = rows }, 5); + e.dispatchGroups(mtl.Size.of(rows, 1, 1), mtl.Size.of(256, 1, 1)); +} + +const ActArgs = extern struct { rows: u32, width: u32 }; +pub fn swiglu(p: *const Pipelines, e: mtl.ComputeEncoder, gu: Ref, out: Ref, rows: u32, width: u32) void { + std.debug.assert(rows > 0 and width > 0); + e.setPipeline(p.swiglu); + inline for (.{ gu, out }, 0..) |r, i| e.setBuffer(r.buf, r.off, i); + e.setValue(ActArgs{ .rows = rows, .width = width }, 2); + e.dispatchThreads(mtl.Size.of(width, rows, 1), unit); +} + +const LogitArgs = extern struct { rows: u32, vocab: u32 }; +pub fn logits(p: *const Pipelines, e: mtl.ComputeEncoder, h: Ref, unembed: Ref, out: Ref, rows: u32, vocab: u32) void { + std.debug.assert(rows > 0 and vocab > 0 and vocab <= 200058); + e.setPipeline(p.logits); + inline for (.{ h, unembed, out }, 0..) |r, i| e.setBuffer(r.buf, r.off, i); + e.setValue(LogitArgs{ .rows = rows, .vocab = vocab }, 3); + e.dispatchThreads(mtl.Size.of(vocab, rows, 1), unit); +} + +const ExpertArgs = extern struct { rows: u32, channels: u32 }; +pub fn expertPick(p: *const Pipelines, e: mtl.ComputeEncoder, all: Ref, ids: Ref, out: Ref, rows: u32, channels: u32) void { + std.debug.assert(rows > 0 and channels > 0); + e.setPipeline(p.expert_pick); + inline for (.{ all, ids, out }, 0..) |r, i| e.setBuffer(r.buf, r.off, i); + e.setValue(ExpertArgs{ .rows = rows, .channels = channels }, 3); + e.dispatchThreads(mtl.Size.of(8, channels, rows), unit); +} + +pub fn expertCombine(p: *const Pipelines, e: mtl.ComputeEncoder, picked: Ref, weights: Ref, out: Ref, rows: u32, channels: u32) void { + std.debug.assert(rows > 0 and channels > 0); + e.setPipeline(p.expert_combine); + inline for (.{ picked, weights, out }, 0..) |r, i| e.setBuffer(r.buf, r.off, i); + e.setValue(ExpertArgs{ .rows = rows, .channels = channels }, 3); + e.dispatchThreads(mtl.Size.of(channels, rows, 1), unit); +} diff --git a/zig/src/families/inkling2/metal/glue_plan.zig b/zig/src/families/inkling2/metal/glue_plan.zig new file mode 100644 index 00000000000..9cebaffe0ca --- /dev/null +++ b/zig/src/families/inkling2/metal/glue_plan.zig @@ -0,0 +1,250 @@ +//! Pure Inkling 2 Mini glue launch shapes and independent FP64 arithmetic. +const std = @import("std"); + +pub const hidden = 2304; +pub const expert_count = 128; +pub const intermediate = 1152; +pub const top_k = 8; +pub const ar_scale: f64 = @as(f32, @bitCast(@as(u32, 0x3caaaaab))); + +pub const Kind = enum { + embed_norm, + ar, + conv_static, + conv_dynamic, + router, + swiglu, + logits, + expert_pick, + expert_combine, + + pub fn symbol(k: Kind) []const u8 { + return switch (k) { + .embed_norm => "tf_inkling2_embed_norm", + .ar => "tf_inkling2_ar", + .conv_static => "tf_inkling2_conv_static", + .conv_dynamic => "tf_inkling2_conv_dynamic", + .router => "tf_inkling2_router", + .swiglu => "tf_inkling2_swiglu", + .logits => "tf_inkling2_logits", + .expert_pick => "tf_inkling2_expert_pick", + .expert_combine => "tf_inkling2_expert_combine", + }; + } + pub fn label(k: Kind) []const u8 { + return switch (k) { + .embed_norm => "metal inkling2 glue embed_norm tf_inkling2_embed_norm", + .ar => "metal inkling2 glue ar tf_inkling2_ar", + .conv_static => "metal inkling2 glue conv_static tf_inkling2_conv_static", + .conv_dynamic => "metal inkling2 glue conv_dynamic tf_inkling2_conv_dynamic", + .router => "metal inkling2 glue router tf_inkling2_router", + .swiglu => "metal inkling2 glue swiglu tf_inkling2_swiglu", + .logits => "metal inkling2 glue logits tf_inkling2_logits", + .expert_pick => "metal inkling2 glue expert_pick tf_inkling2_expert_pick", + .expert_combine => "metal inkling2 glue expert_combine tf_inkling2_expert_combine", + }; + } +}; + +pub const Call = struct { rows: usize, n: usize, k: usize }; +pub fn valid(kind: Kind, c: Call) bool { + const key_depth: usize = if (kind == .expert_combine) top_k else 4; + const max_width: usize = if (kind == .conv_dynamic) 1024 else hidden; + if (c.rows == 0 or c.rows > 64) return false; + return switch (kind) { + .embed_norm => c.k == hidden and c.n == hidden, + .router => c.k == hidden and c.n == top_k, + .logits => c.k == hidden and c.n > 0 and c.n <= 200058, + .ar => c.k == hidden and c.n == hidden and c.rows >= 2 and c.rows <= 5, + .conv_static, .conv_dynamic, .expert_combine => c.k == key_depth and c.n > 0 and c.n <= max_width, + .swiglu => c.k == 2 and c.n > 0 and c.n <= intermediate, + .expert_pick => c.k == top_k and c.n > 0 and c.n <= hidden, + }; +} +pub fn count(kind: Kind, c: Call) usize { + const copies: usize = if (kind == .expert_pick) top_k else 1; + return c.rows * c.n * copies; +} + +pub fn roundBf16(v: anytype) f64 { + const x: f32 = @floatCast(v); + const bits: u32 = @bitCast(x); + const rounded: u16 = if (std.math.isNan(x)) + @truncate((bits >> 16) | 0x40) + else + @truncate((bits +% 0x7fff +% ((bits >> 16) & 1)) >> 16); + const value: f32 = @bitCast(@as(u32, rounded) << 16); + return value; +} +pub fn cap(x: f64, c: f64) f64 { + return c * std.math.tanh(x / c); +} +pub fn sigmoid(x: f64) f64 { + return 1 / (1 + std.math.exp(-x)); +} + +/// One normalized BF16 embedding result, before its final BF16 store. +pub fn embedValue(x: []const f32, weight: []const f32, d: usize) f64 { + var ss: f64 = 0; + for (x) |v| ss += @as(f64, v) * v; + const inv = 1 / @sqrt(ss / @as(f64, @floatFromInt(x.len)) + 1e-6); + return @as(f64, weight[d]) * (@as(f64, x[d]) * inv); +} + +/// Accumulation alternatives for the AR host model. Null means the independent FP64 oracle. +pub const ArAccum = enum { none, f32, f16, bf16 }; +pub const ArOrder = enum { sequential, pairwise, strided }; +pub const ArSum = struct { accum: ArAccum, order: ArOrder }; + +fn arRound(v: f64, accum: ArAccum) f64 { + return switch (accum) { + .none => v, + .f32 => @as(f32, @floatCast(v)), + .f16 => @as(f16, @floatCast(v)), + .bf16 => roundBf16(v), + }; +} +fn arChain(terms: []const f64, sim: ArSum, stride: usize, first: usize) f64 { + var total: f64 = 0; + var i = first; + while (i < terms.len) : (i += stride) total = arRound(total + arRound(terms[i], sim.accum), sim.accum); + return total; +} +fn arHalves(terms: []const f64, sim: ArSum) f64 { + if (terms.len == 0) return 0; + if (terms.len == 1) return arRound(terms[0], sim.accum); + const mid = terms.len / 2; + return arRound(arHalves(terms[0..mid], sim) + arHalves(terms[mid..], sim), sim.accum); +} +fn arSumIn(terms: []const f64, sim: ?ArSum) f64 { + if (sim) |s| return switch (s.order) { + .sequential => arChain(terms, s, 1, 0), + .pairwise => arHalves(terms, s), + .strided => blk: { + var lanes: [32]f64 = @splat(0); + for (&lanes, 0..) |*lane, i| lane.* = arChain(terms, s, 32, i); + break :blk arHalves(&lanes, s); + }, + }; + var total: f64 = 0; + for (terms) |term| total += term; + return total; +} + +/// Squares for one AR RMS reduction, optionally under a precision/order model. +pub fn arSourceSquares(blocks: []const f32, partial: []const f32, sources: usize, s: usize, sim: ?ArSum) f64 { + var terms: [hidden]f64 = undefined; + for (&terms, 0..) |*term, d| { + const x = if (s + 1 == sources) partial[d] else blocks[s * hidden + d]; + term.* = @as(f64, x) * x; + } + return arSumIn(&terms, sim); +} + +/// One normalized AR query dot. Its terms are in ascending hidden-coordinate order. +pub fn arQueryDot(blocks: []const f32, partial: []const f32, queries: []const f32, sources: usize, q: usize, s: usize, inverse: f64, sim: ?ArSum) f64 { + var terms: [hidden]f64 = undefined; + for (&terms, 0..) |*term, d| { + const x = if (s + 1 == sources) partial[d] else blocks[s * hidden + d]; + term.* = @as(f64, queries[q * hidden + d]) * (@as(f64, x) * inverse); + } + return arSumIn(&terms, sim); +} + +/// AR with explicitly modeled reductions; non-reduction arithmetic remains FP64. +pub fn blockResidualIn(blocks: []const f32, partial: []const f32, queries: []const f32, sources: usize, q: usize, sim: ?ArSum, out: []f64) void { + var inv: [5]f64 = undefined; + var weight: [5]f64 = undefined; + var peak = -std.math.inf(f64); + for (0..sources) |s| { + const ss = arSourceSquares(blocks, partial, sources, s, sim); + inv[s] = 1 / @sqrt(ss / hidden + 1e-6); + const dot = arQueryDot(blocks, partial, queries, sources, q, s, inv[s], sim); + weight[s] = dot * ar_scale; + peak = @max(peak, weight[s]); + } + var den_terms: [5]f64 = undefined; + for (0..sources) |s| { + den_terms[s] = std.math.exp(weight[s] - peak); + weight[s] = den_terms[s]; + } + const den = arSumIn(den_terms[0..sources], sim); + var terms: [5]f64 = undefined; + for (0..hidden) |d| { + for (0..sources) |s| { + const x = if (s + 1 == sources) partial[d] else blocks[s * hidden + d]; + terms[s] = weight[s] / den * (@as(f64, x) * inv[s]); + } + out[d] = arSumIn(terms[0..sources], sim); + } +} + +/// AR over BF16 blocks widened to f32 and an unrounded f32 partial. FP64 is only the oracle. +pub fn blockResidual(blocks: []const f32, partial: []const f32, queries: []const f32, sources: usize, q: usize, out: []f64) void { + blockResidualIn(blocks, partial, queries, sources, q, null, out); +} + +pub fn staticConv(taps: []const f32, weight: []const f32, channels: usize, r: usize, c: usize) f64 { + var sum: f64 = taps[(r + 3) * channels + c]; + for (0..4) |tap| sum += @as(f64, weight[c * 4 + tap]) * taps[(r + tap) * channels + c]; + return sum / @sqrt(5.0); +} + +pub fn dynamicConv(taps: []const f32, input: []const f32, static_w: []const f32, projection: []const f32, channels: usize, r: usize, c: usize) f64 { + var sum: f64 = taps[(r + 3) * channels + c]; + for (0..4) |lag| { + var dot: f64 = 0; + for (0..hidden) |d| dot += @as(f64, projection[(4 * (c / 128) + lag) * hidden + d]) * input[r * hidden + d]; + const w = @as(f64, static_w[lag * channels + c]) + roundBf16(dot); + sum += w * taps[(r + 3 - lag) * channels + c]; + } + return sum / 3; +} + +pub const Route = struct { ids: [top_k]u32, weights: [top_k]f64 }; +pub fn route(x: []const f32, matrix: []const f32, bias: []const f32) Route { + var score: [expert_count]f64 = undefined; + var used: [expert_count]bool = @splat(false); + var out: Route = undefined; + for (0..expert_count) |e| { + var dot: f64 = 0; + for (0..hidden) |d| dot += @as(f64, matrix[e * hidden + d]) * x[d]; + score[e] = sigmoid(dot); + } + for (0..top_k) |j| { + var best: ?usize = null; + for (0..expert_count) |e| if (!used[e]) { + if (best == null or score[e] + bias[e] > score[best.?] + bias[best.?]) best = e; + }; + out.ids[j] = @intCast(best.?); + out.weights[j] = score[best.?]; + used[best.?] = true; + } + std.mem.sort(u32, &out.ids, {}, std.sort.asc(u32)); + // Recover scores after sorting IDs, not route-order positions. + var den: f64 = 1e-20; + for (out.ids, 0..) |id, j| { + out.weights[j] = score[id]; + den += score[id]; + } + for (&out.weights) |*w| w.* = w.* / den * 8; + return out; +} + +pub fn swiglu(gate: f32, up: f32) f64 { + return cap(gate, 4) * sigmoid(gate) * cap(up, 25); +} +pub fn logit(h: []const f32, unembed: []const f32, v: usize) f64 { + var dot: f64 = 0; + for (0..hidden) |d| dot += @as(f64, unembed[v * hidden + d]) * h[d]; + return cap(roundBf16(dot), 30); +} +pub fn combine(picked: []const f32, weights: []const f32, channels: usize, d: usize) f64 { + var sum: f64 = 0; + for (0..top_k) |j| sum += @as(f64, weights[j]) * picked[j * channels + d]; + return sum; +} + +pub fn pick(all_experts: []const f32, ids: []const u32, channels: usize, row: usize, j: usize, d: usize) f32 { + return all_experts[(row * expert_count + ids[row * top_k + j]) * channels + d]; +} diff --git a/zig/src/families/inkling2/metal/glue_test.zig b/zig/src/families/inkling2/metal/glue_test.zig new file mode 100644 index 00000000000..f1480f33b33 --- /dev/null +++ b/zig/src/families/inkling2/metal/glue_test.zig @@ -0,0 +1,199 @@ +//! Host-only proof of Mini's glue formulas, source inventory and shape admission. +const std = @import("std"); +const p = @import("inkling2_glue_plan"); +const records = @import("core").contract.inkling2_glue_metal_records.records; +const shader = @import("inkling2_metal").glue; +const c = @import("core").contract.spec; +const t = std.testing; + +fn near(want: f64, got: f64) !void { + try t.expectApproxEqAbs(want, got, 1e-10); +} + +test "glue entries have one shader, symbol, unique launch record and honest scalar reservation" { + for (std.enums.values(p.Kind), records) |kind, record| { + try t.expectEqualStrings(kind.label(), record.name); + try t.expectEqual(@as(usize, 1), std.mem.count(u8, shader, kind.symbol())); + try t.expectEqual(record.threads, record.reserved); + } + try t.expect(std.mem.indexOf(u8, shader, "#pragma METAL fp contract(off)") != null); + try t.expect(std.mem.indexOf(u8, shader, "INKLING_AR_SCALE = 0x1.555556p-6f") != null); + try t.expectEqual(@as(u32, 256), records[@backingInt(p.Kind.conv_dynamic)].threads); + try t.expectEqual(@as(u32, 128), records[@backingInt(p.Kind.conv_dynamic)].tg_memory); +} + +test "shape admission fixes Mini's hidden and routed dimensions" { + try t.expect(p.valid(.embed_norm, .{ .rows = 4, .n = p.hidden, .k = p.hidden })); + try t.expect(!p.valid(.ar, .{ .rows = 6, .n = p.hidden, .k = p.hidden })); + try t.expect(!p.valid(.router, .{ .rows = 1, .n = 8, .k = 128 })); + try t.expect(!p.valid(.conv_dynamic, .{ .rows = 1, .n = 2304, .k = 4 })); + try t.expect(!p.valid(.swiglu, .{ .rows = 1, .n = p.intermediate + 1, .k = 2 })); + try t.expect(p.valid(.logits, .{ .rows = 1, .n = 200058, .k = p.hidden })); + try t.expectEqual(@as(usize, 8 * 1152), p.count(.expert_pick, .{ .rows = 1, .n = 1152, .k = 8 })); +} + +test "embedding uses one FP32 RMS, weighted product and final BF16 rounding" { + var x: [p.hidden]f32 = @splat(1); + var w: [p.hidden]f32 = @splat(2); + try near(@as(f64, 2) / @sqrt(@as(f64, 1) + 1e-6), p.embedValue(&x, &w, 17)); + x[3] = 3; + try t.expect(p.embedValue(&x, &w, 3) != 2); + try t.expectEqual(@as(f64, 1), p.roundBf16(1.003)); +} + +test "AR normalizes each source, scales learned FP32 query dots after reduction and softmaxes" { + const a = t.allocator; + const blocks = try a.alloc(f32, p.hidden); + defer a.free(blocks); + var partial: [p.hidden]f32 = @splat(2); + var queries: [p.hidden]f32 = @splat(0); + @memset(blocks, 1); + const out = try a.alloc(f64, p.hidden); + defer a.free(out); + p.blockResidual(blocks, &partial, &queries, 2, 0, out); + const expected = (1 / @sqrt(@as(f64, 1) + 1e-6) + 2 / @sqrt(@as(f64, 4) + 1e-6)) / 2; + try near(expected, out[0]); + try near(expected, out[1]); + queries[0] = 48; + p.blockResidual(blocks, &partial, &queries, 2, 0, out); + // The first dot is 48/sqrt(2304+eps), multiplied by 1/48 only after that dot. + try t.expect(out[0] < 1.1 and out[0] > 0.9); + try t.expectEqual(p.ar_scale, @as(f64, @as(f32, @bitCast(@as(u32, 0x3caaaaab))))); +} + +test "AR query logits use each normalized source before softmax" { + var blocks: [p.hidden]f32 = @splat(0); + var partial: [p.hidden]f32 = @splat(0); + var queries: [p.hidden]f32 = @splat(0); + var out: [p.hidden]f64 = undefined; + blocks[0] = 1; + partial[1] = 1; + queries[0] = 1; + p.blockResidual(&blocks, &partial, &queries, 2, 0, &out); + const inv = 1 / @sqrt(@as(f64, 1) / p.hidden + 1e-6); + const first = 1 / (1 + @exp(-inv * p.ar_scale)); + try near(first * inv, out[0]); + try near((1 - first) * inv, out[1]); +} + +test "AR FP32 query-dot model distinguishes partial precision and order" { + const blocks: [0]f32 = .{}; + var partial: [p.hidden]f32 = @splat(1); + var queries: [p.hidden]f32 = @splat(0.1); + const sequential = p.arQueryDot(&blocks, &partial, &queries, 1, 0, 0, 1, .{ .accum = .f32, .order = .sequential }); + var expected: f32 = 0; + for (0..p.hidden) |d| expected += queries[d] * partial[d]; + try t.expectEqual(@as(f64, expected), sequential); + + const pairwise = p.arQueryDot(&blocks, &partial, &queries, 1, 0, 0, 1, .{ .accum = .f32, .order = .pairwise }); + try t.expect(pairwise != sequential); + const bf16 = p.arQueryDot(&blocks, &partial, &queries, 1, 0, 0, 1, .{ .accum = .bf16, .order = .sequential }); + var lowered: f64 = 0; + for (0..p.hidden) |d| { + const term = p.roundBf16(@as(f64, queries[d]) * partial[d]); + lowered = p.roundBf16(lowered + term); + } + try t.expectEqual(lowered, bf16); + try t.expect(bf16 != sequential); +} + +test "AR integer stress meets the exact FP32 gate and rejects lower-precision sums" { + const sources = 4; + var blocks: [(sources - 1) * p.hidden]f32 = undefined; + for (0..sources - 1) |s| @memset(blocks[s * p.hidden ..][0..p.hidden], if (s % 2 == 0) 256 else -256); + var partial: [p.hidden]f32 = @splat(-256); + var queries: [2 * p.hidden]f32 = undefined; + for (0..2) |query_row| { + const row = queries[query_row * p.hidden ..][0..p.hidden]; + for (0..p.hidden / 2) |d| { + const v: f32 = @floatFromInt(1 + d % 64); + row[d] = v; + row[p.hidden / 2 + d] = (if (d < 8) @as(f32, 1) else 0) - v; + } + } + var want: [2 * p.hidden]f64 = undefined; + for (0..2) |q| p.blockResidualIn(&blocks, &partial, &queries, sources, q, null, want[q * p.hidden ..][0..p.hidden]); + const spec: c.Spec = .{ .name = "AR stress", .accum = .f32, .depth = undefined, .ops = 96, .out = .f32, .served = &.{} }; + var margins = [_]f64{ std.math.inf(f64), std.math.inf(f64) }; + for ([_]p.ArOrder{ .sequential, .pairwise, .strided }) |order| { + for ([_]p.ArAccum{ .f32, .f16, .bf16 }, 0..) |accum, ai| { + var got: [2 * p.hidden]f64 = undefined; + for (0..2) |q| p.blockResidualIn(&blocks, &partial, &queries, sources, q, .{ .accum = accum, .order = order }, got[q * p.hidden ..][0..p.hidden]); + var most: f64 = 0; + for (want, got) |w, g| { + const miss = if (g == w) 0 else if (std.math.isFinite(g) or !std.math.isFinite(w)) @abs(g - w) / c.boundExact(spec, w) else std.math.inf(f64); + most = @max(most, miss); + } + if (ai == 0) try t.expect(most <= 1) else margins[ai - 1] = @min(margins[ai - 1], most); + } + } + try t.expect(margins[0] >= 100); + try t.expect(margins[1] >= 100); +} + +test "static convolution's stored tap three is current and carries the residual input" { + const taps = [_]f32{ 1, 2, 3, 4 }; + const weights = [_]f32{ 10, 20, 30, 40 }; + // This addresses channel zero at output row zero with one channel. + try near((1 * 10 + 2 * 20 + 3 * 30 + 4 * 40 + 4) / @as(f64, @sqrt(5.0)), p.staticConv(&taps, &weights, 1, 0, 0)); +} + +test "dynamic convolution rounds 32 projections to BF16 and uses lag zero for current" { + var taps: [7]f32 = @splat(0); + var input: [p.hidden]f32 = @splat(0); + var projection: [32 * p.hidden]f32 = @splat(0); + taps[3] = 2; // r=0, c=0, current + input[0] = 1; + projection[0] = 1; + const static_w = [_]f32{ 5, 0, 0, 0 }; + // lag zero: (5 + BF16(1))*current + current, all divided by three. + try near(@as(f64, 14.0) / 3, p.dynamicConv(&taps, &input, &static_w, &projection, 1, 0, 0)); + try t.expect(p.dynamicConv(&taps, &input, &static_w, &projection, 1, 0, 0) != p.staticConv(&taps, &static_w, 1, 0, 0)); +} + +test "router bias affects top-8 only; sigmoid weights normalize to eight after ascending IDs" { + var x: [p.hidden]f32 = @splat(0); + var matrix: [p.expert_count * p.hidden]f32 = @splat(0); + var bias: [p.expert_count]f32 = @splat(0); + for (120..128) |e| bias[e] = 1; + matrix[127 * p.hidden] = 1; + x[0] = 1; + const r = p.route(&x, &matrix, &bias); + for (r.ids, 0..) |id, j| try t.expectEqual(@as(u32, @intCast(120 + j)), id); + var sum: f64 = 0; + for (r.weights) |w| sum += w; + try near(8, sum); + try t.expect(r.weights[7] > r.weights[0]); + bias[127] = -1; + const changed = p.route(&x, &matrix, &bias); + try t.expect(changed.ids[7] != 127); +} + +test "interleaved SwiGLU caps gate and up separately with one BF16 activation store" { + try near(p.cap(3, 4) * p.sigmoid(3) * p.cap(7, 25), p.swiglu(3, 7)); + try t.expect(p.swiglu(40, 100) < 100); + try near(16.5, p.roundBf16(p.swiglu(3, 7))); +} + +test "A9(a) rounds the BF16 unembed before widening to the FP32 softcap30" { + var h: [p.hidden]f32 = @splat(0); + var u: [p.hidden]f32 = @splat(0); + h[0] = 1; + u[0] = 60; + try near(30 * std.math.tanh(@as(f64, 2)), p.logit(&h, &u, 0)); + u[0] = 1.003; + try near(p.cap(p.roundBf16(1.003), 30), p.logit(&h, &u, 0)); + try t.expect(p.logit(&h, &u, 0) != p.cap(1.003, 30)); +} + +test "expert pick uses sorted IDs and combine accumulates those experts from FP32 zero" { + var all: [p.expert_count]f32 = undefined; + for (&all, 0..) |*v, e| v.* = @floatFromInt(e); + const ids = [_]u32{ 2, 7, 11, 19, 40, 61, 90, 127 }; + try t.expectEqual(@as(f32, 90), p.pick(&all, &ids, 1, 0, 6, 0)); + var picked: [8]f32 = undefined; + for (&picked, 0..) |*v, j| v.* = @floatFromInt(ids[j]); + const weights = [_]f32{ 0, 0, 0, 0, 0, 0, 1, 0 }; + try near(90, p.combine(&picked, &weights, 1, 0)); + try near(2 * p.sigmoid(-3), p.sigmoid(-3) * 2); +} diff --git a/zig/src/families/inkling2/metal/host_test.zig b/zig/src/families/inkling2/metal/host_test.zig new file mode 100644 index 00000000000..8598da235d9 --- /dev/null +++ b/zig/src/families/inkling2/metal/host_test.zig @@ -0,0 +1,18 @@ +//! Host-only Inkling 2 Mini Metal launch plans and scalar arithmetic references. +const serving = if (@import("builtin").os.tag.isDarwin()) @import("serving_test.zig") else struct {}; + +test { + _ = @import("attention_test.zig"); + _ = @import("glue_test.zig"); + _ = @import("experts_test.zig"); + _ = @import("loop_test.zig"); + _ = @import("runtime_test.zig"); + _ = @import("runtime_kernels_test.zig"); + _ = @import("dspark_kernels_test.zig"); + _ = @import("dspark_fold.zig"); + _ = @import("dspark_weights.zig"); + _ = @import("dspark_state.zig"); + _ = @import("dspark.zig"); + _ = @import("backend.zig"); + _ = serving; +} diff --git a/zig/src/families/inkling2/metal/loop.zig b/zig/src/families/inkling2/metal/loop.zig new file mode 100644 index 00000000000..ebd3588eedf --- /dev/null +++ b/zig/src/families/inkling2/metal/loop.zig @@ -0,0 +1,55 @@ +//! Inkling 2 Mini cross-pass messages and message gates: real Metal dispatches. +const std = @import("std"); +const mtl = @import("metal"); +const sources = @import("inkling2_metal"); +pub const plan = @import("inkling2_loop_plan"); + +pub const hidden: u32 = plan.hidden; +pub const rank: u32 = plan.rank; +pub const message_entries: u32 = plan.message_entries; +pub const Ref = struct { buf: mtl.Buffer, off: usize = 0 }; +pub const RowsArgs = plan.RowsArgs; + +pub const Pipelines = struct { + messages: mtl.Pipeline, + gates: mtl.Pipeline, + + pub fn load(device: mtl.Device) !Pipelines { + return loadSource(device, sources.loop); + } + pub fn loadSource(device: mtl.Device, text: []const u8) !Pipelines { + const lib = try mtl.Library.fromSource(device, text, mtl.CompileOptions.mlx()); + defer lib.deinit(); + var messages = try mtl.Pipeline.init(device, lib, plan.Kind.messages.symbol(), false); + errdefer messages.deinit(); + const gate_pipeline = try mtl.Pipeline.init(device, lib, plan.Kind.gates.symbol(), false); + return .{ .messages = messages, .gates = gate_pipeline }; + } + pub fn deinit(p: *Pipelines) void { + p.gates.deinit(); + p.messages.deinit(); + p.* = undefined; + } +}; + +fn bind(e: mtl.ComputeEncoder, refs: []const Ref) void { + for (refs, 0..) |r, slot| e.setBuffer(r.buf, r.off, slot); +} + +/// Output layout is [token][12 core layers][q,k,v,mlp][H], all binary32. +pub fn crossPassMessageAttention(p: *const Pipelines, e: mtl.ComputeEncoder, bank0: Ref, bank1: Ref, q_mlp: Ref, kv: Ref, out: Ref, rows: u32) void { + std.debug.assert(rows > 0 and rows <= 64); + e.setPipeline(p.messages); + bind(e, &.{ bank0, bank1, q_mlp, kv, out }); + e.setValue(RowsArgs{ .rows = rows }, 5); + e.dispatchGroups(mtl.Size.of(rows * message_entries, 1, 1), mtl.Size.of(256, 1, 1)); +} + +/// One controller tuple; h, m and output are [token][H] binary32 tensors. +pub fn gates(p: *const Pipelines, e: mtl.ComputeEncoder, h: Ref, m: Ref, down: Ref, forget: Ref, gain: Ref, out: Ref, rows: u32) void { + std.debug.assert(rows > 0 and rows <= 64); + e.setPipeline(p.gates); + bind(e, &.{ h, m, down, forget, gain, out }); + e.setValue(RowsArgs{ .rows = rows }, 6); + e.dispatchGroups(mtl.Size.of(rows, 1, 1), mtl.Size.of(256, 1, 1)); +} diff --git a/zig/src/families/inkling2/metal/loop_plan.zig b/zig/src/families/inkling2/metal/loop_plan.zig new file mode 100644 index 00000000000..86719e705b4 --- /dev/null +++ b/zig/src/families/inkling2/metal/loop_plan.zig @@ -0,0 +1,166 @@ +//! Pure Inkling 2 Mini loop launch geometry and independent FP64 arithmetic. +const std = @import("std"); + +pub const hidden = 2304; +pub const rank = 64; +pub const core_layers = 12; +pub const roles = 4; +pub const message_entries = core_layers * roles; +pub const eps = 1e-6; +pub const message_scale: f64 = @as(f32, @bitCast(@as(u32, 0x3caaaaab))); +pub const RowsArgs = extern struct { rows: u32 }; + +pub const Role = enum(u8) { q, k, v, mlp }; +pub const Kind = enum { + messages, + gates, + + pub fn symbol(k: Kind) []const u8 { + return switch (k) { + .messages => "tf_inkling2_loop_messages", + .gates => "tf_inkling2_loop_gates", + }; + } + pub fn label(k: Kind) []const u8 { + return switch (k) { + .messages => "metal inkling2 loop messages tf_inkling2_loop_messages", + .gates => "metal inkling2 loop gates tf_inkling2_loop_gates", + }; + } +}; + +pub const Call = struct { rows: usize, n: usize, k: usize }; +pub const Geometry = struct { groups: usize, threads: u32 = 256, tg_memory: u32 }; + +pub fn valid(kind: Kind, c: Call) bool { + if (c.rows == 0 or c.rows > 64) return false; + return switch (kind) { + .messages => c.n == message_entries * hidden and c.k == hidden, + .gates => c.n == hidden and c.k == rank, + }; +} +pub fn count(kind: Kind, c: Call) usize { + return switch (kind) { + .messages => c.rows * message_entries * hidden, + .gates => c.rows * hidden, + }; +} +pub fn geometry(kind: Kind, c: Call) Geometry { + return .{ + .groups = switch (kind) { + .messages => c.rows * message_entries, + .gates => c.rows, + }, + .tg_memory = switch (kind) { + .messages => 144, + .gates => 9552, + }, + }; +} + +/// q/mlp and k/v each occupy even/odd rows of their separate 24xH tensors. +pub fn queryRow(role: Role, layer: usize) usize { + std.debug.assert(layer < core_layers); + return 2 * layer + switch (role) { + .q, .k => @as(usize, 0), + .v, .mlp => 1, + }; +} +pub fn usesQueryMessageTensor(role: Role) bool { + return role == .q or role == .mlp; +} + +/// Round through FP32 and BF16 nearest-even, returning an exactly representable FP64 value. +pub fn roundBf16(v: anytype) f64 { + const x: f32 = @floatCast(v); + const bits: u32 = @bitCast(x); + const rounded: u16 = if (std.math.isNan(x)) + @truncate((bits >> 16) | 0x40) + else + @truncate((bits +% 0x7fff +% ((bits >> 16) & 1)) >> 16); + const value: f32 = @bitCast(@as(u32, rounded) << 16); + return value; +} + +pub fn rmsScale(x: []const f32) f64 { + std.debug.assert(x.len == hidden); + var ss: f64 = 0; + for (x) |v| ss += @as(f64, v) * v; + return 1 / @sqrt(ss / hidden + eps); +} + +/// One of the 48 messages. Banks contain their already-decoded BF16 values as f32. +pub fn message(bank0: []const f32, bank1: []const f32, q_mlp: []const f32, kv: []const f32, layer: usize, role: Role, out: []f64) void { + std.debug.assert(bank0.len == hidden and bank1.len == hidden and out.len == hidden); + std.debug.assert(q_mlp.len == 2 * core_layers * hidden and kv.len == q_mlp.len); + const queries = if (usesQueryMessageTensor(role)) q_mlp else kv; + const query = queries[queryRow(role, layer) * hidden ..][0..hidden]; + const inverse = [2]f64{ rmsScale(bank0), rmsScale(bank1) }; + var logits: [2]f64 = undefined; + var peak = -std.math.inf(f64); + inline for (0..2) |s| { + const bank = if (s == 0) bank0 else bank1; + var dot: f64 = 0; + for (0..hidden) |d| dot += @as(f64, query[d]) * (@as(f64, bank[d]) * inverse[s]); + logits[s] = dot * message_scale; + peak = @max(peak, logits[s]); + } + var weights: [2]f64 = undefined; + var den: f64 = 0; + for (0..2) |s| { + weights[s] = @exp(logits[s] - peak); + den += weights[s]; + } + for (0..hidden) |d| { + const beta0 = @as(f64, bank0[d]) * inverse[0]; + const beta1 = @as(f64, bank1[d]) * inverse[1]; + out[d] = weights[0] / den * beta0 + weights[1] / den * beta1; + } +} + +/// BF16(concat(rho(h), rho(m))) D projection and the BF16 zeta endpoint, with FP64 sums. +pub fn downProjection(h: []const f32, m: []const f32, down: []const f32, zeta: *[rank]f64) void { + std.debug.assert(h.len == hidden and m.len == hidden and down.len == rank * 2 * hidden); + const ih = rmsScale(h); + const im = rmsScale(m); + var normalized: [2 * hidden]f64 = undefined; + for (0..hidden) |d| { + normalized[d] = roundBf16(@as(f64, h[d]) * ih); + normalized[hidden + d] = roundBf16(@as(f64, m[d]) * im); + } + for (0..rank) |r| { + var dot: f64 = 0; + for (0..2 * hidden) |d| dot += @as(f64, down[r * 2 * hidden + d]) * normalized[d]; + zeta[r] = roundBf16(dot); + } +} + +/// The reference's four explicit binary32 blend nodes. FP64 carries values between nodes. +pub fn blend(forget_value: f64, gain_value: f64, h: f64, m: f64) f64 { + const f: f32 = @floatCast(forget_value); + const g: f32 = @floatCast(gain_value); + const state: f32 = @floatCast(h); + const message_value: f32 = @floatCast(m); + const keep: f32 = 1.0 - f; + const left: f32 = keep * state; + const right: f32 = g * message_value; + const sum: f32 = left + right; + return sum; +} + +/// Full rank-64 gate. Matrix slices contain their exact BF16 values widened to f32. +pub fn gate(h: []const f32, m: []const f32, down: []const f32, forget: []const f32, gain: []const f32, out: []f64) void { + std.debug.assert(h.len == hidden and m.len == hidden and out.len == hidden); + std.debug.assert(forget.len == hidden * rank and gain.len == forget.len); + var zeta: [rank]f64 = undefined; + downProjection(h, m, down, &zeta); + for (0..hidden) |d| { + var fdot: f64 = 0; + var gdot: f64 = 0; + for (0..rank) |r| { + fdot += @as(f64, forget[d * rank + r]) * zeta[r]; + gdot += @as(f64, gain[d * rank + r]) * zeta[r]; + } + out[d] = blend(std.math.tanh(fdot), std.math.tanh(gdot), h[d], m[d]); + } +} diff --git a/zig/src/families/inkling2/metal/loop_test.zig b/zig/src/families/inkling2/metal/loop_test.zig new file mode 100644 index 00000000000..9634fc44573 --- /dev/null +++ b/zig/src/families/inkling2/metal/loop_test.zig @@ -0,0 +1,208 @@ +//! Host-only proof of Mini's loop formulas, launch ABI, source inventory and rounding. +const std = @import("std"); +const p = @import("inkling2_loop_plan"); +const records = @import("core").contract.inkling2_loop_metal_records.records; +const shader = @import("inkling2_metal").loop; +const t = std.testing; + +fn near(want: f64, got: f64) !void { + try t.expectApproxEqAbs(want, got, 1e-10); +} + +test "loop entries have unique symbols, launch records and disabled FP contraction" { + for (std.enums.values(p.Kind), records) |kind, record| { + try t.expectEqualStrings(kind.label(), record.name); + try t.expectEqual(@as(usize, 1), std.mem.count(u8, shader, kind.symbol())); + try t.expectEqual(@as(u32, 256), record.threads); + try t.expectEqual(record.threads, record.reserved); + try t.expectEqual(p.geometry(kind, .{ .rows = 1, .n = 1, .k = 1 }).tg_memory, record.tg_memory); + } + try t.expect(std.mem.indexOf(u8, shader, "#pragma METAL fp contract(off)") != null); + try t.expect(std.mem.indexOf(u8, shader, "INKLING_LOOP_SCALE = 0x1.555556p-6f") != null); + try t.expect(std.mem.indexOf(u8, shader, "LoopMathSpecMissing") == null); +} + +test "shape admission and dispatch geometry fix H=2304, rank 64 and 48 messages" { + const mc = p.Call{ .rows = 7, .n = 48 * p.hidden, .k = p.hidden }; + const gc = p.Call{ .rows = 7, .n = p.hidden, .k = p.rank }; + try t.expect(p.valid(.messages, mc)); + try t.expect(p.valid(.gates, gc)); + try t.expectEqual(@as(usize, 7 * 48), p.geometry(.messages, mc).groups); + try t.expectEqual(@as(usize, 7), p.geometry(.gates, gc).groups); + try t.expectEqual(@as(usize, 7 * 48 * p.hidden), p.count(.messages, mc)); + try t.expectEqual(@as(usize, 7 * p.hidden), p.count(.gates, gc)); + try t.expect(!p.valid(.messages, .{ .rows = 1, .n = 47 * p.hidden, .k = p.hidden })); + try t.expect(!p.valid(.messages, .{ .rows = 1, .n = 48 * p.hidden, .k = 4608 })); + try t.expect(!p.valid(.gates, .{ .rows = 1, .n = p.hidden, .k = 32 })); + try t.expect(!p.valid(.gates, .{ .rows = 0, .n = p.hidden, .k = p.rank })); + try t.expectEqual(@as(usize, 4), @sizeOf(p.RowsArgs)); + try t.expectEqual(@as(usize, 0), @offsetOf(p.RowsArgs, "rows")); +} + +test "message with zero query is the exact mean of independently normalized banks" { + var bank0: [p.hidden]f32 = @splat(1); + var bank1: [p.hidden]f32 = @splat(2); + var q_mlp: [2 * p.core_layers * p.hidden]f32 = @splat(0); + var kv: [2 * p.core_layers * p.hidden]f32 = @splat(0); + var out: [p.hidden]f64 = undefined; + p.message(&bank0, &bank1, &q_mlp, &kv, 11, .v, &out); + const expected = (@as(f64, 1) / @sqrt(@as(f64, 1) + p.eps) + + @as(f64, 2) / @sqrt(@as(f64, 4) + p.eps)) / 2; + try near(expected, out[0]); + try near(expected, out[p.hidden - 1]); + try t.expectEqual(p.message_scale, @as(f64, @as(f32, @bitCast(@as(u32, 0x3caaaaab))))); +} + +test "q/mlp and k/v even-odd layouts select all four roles and scale after the dot" { + var bank0: [p.hidden]f32 = @splat(1); + var bank1: [p.hidden]f32 = @splat(2); + bank1[0] = 4; + var q_mlp: [2 * p.core_layers * p.hidden]f32 = @splat(0); + var kv: [2 * p.core_layers * p.hidden]f32 = @splat(0); + const layer = 5; + const all = [_]p.Role{ .q, .k, .v, .mlp }; + for (all) |role| { + const expected_row = @as(usize, 2 * layer) + @as(usize, @intFromBool(role == .v or role == .mlp)); + try t.expectEqual(expected_row, p.queryRow(role, layer)); + const matrix = if (p.usesQueryMessageTensor(role)) &q_mlp else &kv; + matrix[expected_row * p.hidden] = 48; + } + var first: [p.hidden]f64 = undefined; + p.message(&bank0, &bank1, &q_mlp, &kv, layer, all[0], &first); + const scale0 = p.rmsScale(&bank0); + const scale1 = p.rmsScale(&bank1); + const l0 = 48 * scale0 * p.message_scale; + const l1 = 48 * 4 * scale1 * p.message_scale; + const peak = @max(l0, l1); + const e0 = @exp(l0 - peak); + const e1 = @exp(l1 - peak); + const expected = e0 / (e0 + e1) * scale0 + e1 / (e0 + e1) * 4 * scale1; + try near(expected, first[0]); + try t.expect(first[0] != (scale0 + 4 * scale1) / 2); + var out: [p.hidden]f64 = undefined; + for (all[1..]) |role| { + p.message(&bank0, &bank1, &q_mlp, &kv, layer, role, &out); + for (first, out) |a, b| try near(a, b); + } +} + +test "message stress dots are exact in FP32 and discriminate BF16 accumulation" { + var bank0: [p.hidden]f32 = @splat(256); + var bank1: [p.hidden]f32 = @splat(-256); + var q_mlp: [2 * p.core_layers * p.hidden]f32 = @splat(0); + var kv: [2 * p.core_layers * p.hidden]f32 = @splat(0); + const query = q_mlp[0..p.hidden]; + for (0..p.hidden / 2) |d| { + const v: f32 = @floatFromInt(1 + d % 64); + const nudge: f32 = if (d < 8) 1 else 0; + query[d] = v; + query[p.hidden / 2 + d] = nudge - v; + } + var fp: f32 = 0; + var bf: f64 = 0; + for (query) |v| { + fp += v; + bf = p.roundBf16(bf + v); + } + try t.expectEqual(@as(f32, 8), fp); + try t.expect(bf != 8); + var out: [p.hidden]f64 = undefined; + p.message(&bank0, &bank1, &q_mlp, &kv, 0, .q, &out); + const expected = std.math.tanh(8 * p.message_scale); + try near(expected, out[0]); + try near(expected, out[p.hidden - 1]); +} + +test "rank gate hand witness shares one BF16 zeta and uses FP32 tanh projections" { + var h: [p.hidden]f32 = @splat(1); + var m: [p.hidden]f32 = @splat(2); + var down: [p.rank * 2 * p.hidden]f32 = @splat(0); + var forget: [p.hidden * p.rank]f32 = @splat(0); + var gain: [p.hidden * p.rank]f32 = @splat(0); + down[0] = 1; + for (0..p.hidden) |d| { + forget[d * p.rank] = 1; + gain[d * p.rank] = 1; + } + var zeta: [p.rank]f64 = undefined; + p.downProjection(&h, &m, &down, &zeta); + try near(1, zeta[0]); + for (zeta[1..]) |z| try near(0, z); + var out: [p.hidden]f64 = undefined; + p.gate(&h, &m, &down, &forget, &gain, &out); + const expected = p.blend(std.math.tanh(@as(f64, 1)), std.math.tanh(@as(f64, 1)), 1, 2); + try near(expected, out[0]); + try near(expected, out[p.hidden - 1]); + + // The message half starts at D column H; it is not interleaved with h. + @memset(&down, 0); + down[p.hidden] = 1; + p.downProjection(&h, &m, &down, &zeta); + try near(1, zeta[0]); + down[p.hidden] = 0; + down[0] = 1; + @memset(&m, 0); + p.downProjection(&h, &m, &down, &zeta); + try near(1, zeta[0]); +} + +test "concatenated normalized gate inputs round to BF16 before D accumulation" { + var h: [p.hidden]f32 = @splat(0); + var m: [p.hidden]f32 = @splat(0); + var down: [p.rank * 2 * p.hidden]f32 = @splat(0); + for (&h, 0..) |*v, d| v.* = @as(f32, @floatFromInt(d % 19 + 1)) / 32; + for (0..p.hidden) |d| down[d] = 1; + var zeta: [p.rank]f64 = undefined; + p.downProjection(&h, &m, &down, &zeta); + // Fixed witness rounds to 2024; accumulating unrounded normalized values would round to 2016. + try near(2024, zeta[0]); +} + +test "gate stress projections are exact in FP32 and expose BF16 sums" { + var h: [p.hidden]f32 = @splat(256); + var m: [p.hidden]f32 = @splat(-256); + var down: [p.rank * 2 * p.hidden]f32 = @splat(0); + var forget: [p.hidden * p.rank]f32 = @splat(0); + var gain: [p.hidden * p.rank]f32 = @splat(0); + for (0..p.rank) |r| for (0..p.hidden) |d| { + const w: f32 = @floatFromInt(1 + (r + d) % 64); + down[r * 2 * p.hidden + d] = w; + down[r * 2 * p.hidden + p.hidden + d] = if (d == 0) w - 1 else w; + }; + for ([_][]f32{ &forget, &gain }) |weights| for (0..p.hidden) |d| for (0..p.rank / 2) |r| { + const w: f32 = @floatFromInt(1 + (d + r) % 7); + weights[d * p.rank + r] = w; + weights[d * p.rank + r + p.rank / 2] = if (r == 0) 1 - w else -w; + }; + var fp: f32 = 0; + var bf: f64 = 0; + for (0..2 * p.hidden) |d| { + const term = @as(f64, down[d]) * (if (d < p.hidden) @as(f64, 1) else -1); + fp += @as(f32, @floatCast(term)); + bf = p.roundBf16(bf + term); + } + try t.expectEqual(@as(f32, 1), fp); + try t.expect(bf != 1); + var zeta: [p.rank]f64 = undefined; + p.downProjection(&h, &m, &down, &zeta); + for (zeta) |z| try near(1, z); + var out: [p.hidden]f64 = undefined; + p.gate(&h, &m, &down, &forget, &gain, &out); + const expected = p.blend(std.math.tanh(@as(f64, 1)), std.math.tanh(@as(f64, 1)), 256, -256); + for (out) |v| try near(expected, v); +} + +test "BF16 nearest-even and all four binary32 blend steps have exact witnesses" { + try near(1, p.roundBf16(1.00390625)); // midpoint: even mantissa is zero + try near(1.015625, p.roundBf16(1.01171875)); // midpoint: two is even + const f: f32 = 0.33333334; + const g: f32 = 0.14285715; + const h: f32 = 1.003; + const m: f32 = 1.007; + const keep: f32 = 1.0 - f; + const left: f32 = keep * h; + const right: f32 = g * m; + const rounded: f32 = left + right; + try t.expectEqual(@as(f64, rounded), p.blend(f, g, h, m)); + try t.expect(p.blend(f, g, h, m) != (1 - @as(f64, f)) * h + @as(f64, g) * m); +} diff --git a/zig/src/families/inkling2/metal/metal.zig b/zig/src/families/inkling2/metal/metal.zig new file mode 100644 index 00000000000..bef58022713 --- /dev/null +++ b/zig/src/families/inkling2/metal/metal.zig @@ -0,0 +1,7 @@ +//! Inkling 2 Mini's Metal launchers and their shader sources. + +pub const attention = @import("attention.zig"); +pub const glue = @import("glue.zig"); +pub const experts = @import("experts.zig"); +pub const experts_plan = @import("experts_plan.zig"); +pub const loop = @import("loop.zig"); diff --git a/zig/src/families/inkling2/metal/model.zig b/zig/src/families/inkling2/metal/model.zig new file mode 100644 index 00000000000..87c98f36fcf --- /dev/null +++ b/zig/src/families/inkling2/metal/model.zig @@ -0,0 +1,294 @@ +//! Inkling 2 Mini's resident text model: validated checkpoint weights and every Metal pipeline. +const std = @import("std"); +const mtl = @import("metal"); +const sources = @import("kernel_sources"); +const cfg = @import("../config.zig"); +const layer_plan = @import("../plan.zig"); +const ck = @import("../../../core/checkpoint_metal.zig"); +const shards = @import("core").checkpoint_host; +const attention = @import("attention.zig"); +const glue = @import("glue.zig"); +const experts = @import("experts.zig"); +const loop = @import("loop.zig"); + +pub const Tensor = ck.Tensor; +pub const DynamicConv = struct { static_w: Tensor, projection: Tensor }; +pub const Conv = union(enum) { static: Tensor, dynamic: DynamicConv }; +pub const Controller = struct { down: Tensor, forget: Tensor, gain: Tensor }; +pub const AttentionWeights = struct { + wq: Tensor, + wk: Tensor, + wv: Tensor, + wr: Tensor, + wo: Tensor, + gate: Tensor, + sink: Tensor, + q_scale: Tensor, + rel_scale: Tensor, + rel_projection: Tensor, + k_conv: Conv, + v_conv: Conv, + q_norm: Tensor, + k_norm: Tensor, + v_norm: Tensor, +}; +pub const ExpertMatrix = struct { + weight: Tensor, + scale: Tensor, + amax: ?Tensor = null, + denominator: ?Tensor = null, +}; +pub const LayerWeights = struct { + attn: AttentionWeights, + attn_conv: Tensor, + mlp_norm: Tensor, + mlp_conv: Tensor, + router_weight: Tensor, + router_bias: Tensor, + gu: ExpertMatrix, + down: ExpertMatrix, + controllers: ?[4]Controller, +}; +pub const Weights = struct { + embed: Tensor, + embed_norm: Tensor, + norm: Tensor, + unembed: Tensor, + output_query: Tensor, + cross_queries: Tensor, + cross_kv_queries: Tensor, + attn_queries: [23]Tensor, + mlp_queries: [24]Tensor, + layers: [24]LayerWeights, +}; + +/// Scalar copies and residuals around dispatch stay on Metal; forward never reads tensors back to the host. +pub const runtime_source = sources.inkling2_runtime; + +pub const RuntimeOp = enum { copy_bf16, copy_f32, widen, attention_partial, mlp_partial, capture_tap }; +pub const runtime_names = [_][:0]const u8{ + "tf_ink2_copy_bf16", + "tf_ink2_copy_f32", + "tf_ink2_widen", + "tf_ink2_attention_partial", + "tf_ink2_mlp_partial", + "tf_ink2_capture_tap", +}; + +pub fn admitConfig(c: *const cfg.Config) !void { + const t = c.text; + const l = t.loop orelse return error.Inkling2NotMini; + if (l.passes != 3 or l.core_start != 6 or l.core_end != 18 or l.gate_rank != 64) + return error.UnsupportedInkling2Loop; + if (t.hidden != 2304 or t.layers != 24 or t.vocab != 201024 or t.unpadded_vocab != 200058 or + t.window != 1024 or t.d_rel != 16 or t.rel_extent != 1024 or t.log_floor != 8192 or + t.block != 6 or t.experts != 128 or t.topk != 8 or t.expert_inter != 1152 or + t.max_context != 1048576) return error.UnsupportedInkling2Geometry; + for ([_]cfg.Heads{ t.local, t.global }) |h| if (h.q != 24 or h.kv != 8 or h.dim != 128) + return error.UnsupportedInkling2Geometry; + if (t.eps != 1e-6 or t.log_alpha != 0.1 or t.qk_clip != 22.627416997969522 or + t.rel_clip != 8 or t.route_scale != 8 or t.gate_cap != 4 or t.up_cap != 25 or + t.logit_cap != 30) return error.UnsupportedInkling2Constants; +} + +fn require(t: Tensor, dtype: ck.DType, dims: []const usize) !Tensor { + if (t.dtype != dtype or t.rank != dims.len) return error.UnexpectedInkling2Tensor; + for (dims, 0..) |d, i| if (t.shape[i] != d) return error.UnexpectedInkling2Tensor; + var count: usize = 1; + for (dims) |d| count = std.math.mul(usize, count, d) catch return error.UnexpectedInkling2Tensor; + if (t.bytes != count * dtype.size()) return error.UnexpectedInkling2Tensor; + return t; +} + +fn get(c: *const ck.Checkpoint, comptime fmt: []const u8, args: anytype, dtype: ck.DType, dims: []const usize) !Tensor { + var buf: [256]u8 = undefined; + const name = try std.fmt.bufPrint(&buf, fmt, args); + return require(try c.get(name), dtype, dims); +} + +fn matrix(c: *const ck.Checkpoint, layer: u32, comptime suffix: []const u8, precision: layer_plan.Precision, rows: usize, k: usize) !ExpertMatrix { + const base = "model.llm.layers.{d}.mlp.experts." ++ suffix; + const e = 128; + switch (precision) { + .nvfp4 => return .{ + .weight = try get(c, base ++ "_weight", .{layer}, .u8, &.{ e, rows, k / 2 }), + .scale = try get(c, base ++ "_weight_scale", .{layer}, .f8_e4m3, &.{ e, rows, k / 16 }), + .amax = try get(c, base ++ "_weight_amax", .{layer}, .f32, &.{e}), + .denominator = try get(c, base ++ "_weight_outer_scale_denominator", .{layer}, .f32, &.{1}), + }, + .mxfp8 => return .{ + .weight = try get(c, base ++ "_weight", .{layer}, .f8_e4m3, &.{ e, rows, k }), + .scale = try get(c, base ++ "_weight_scale", .{layer}, .u8, &.{ e, rows, k / 32 }), + }, + } +} + +fn loadConv(c: *const ck.Checkpoint, layer: u32, comptime role: []const u8, global: bool) !Conv { + if (!global) return .{ .static = try get(c, "model.llm.layers.{d}.attn." ++ role ++ "_sconv.weight", .{layer}, .bf16, &.{ 1024, 1, 4 }) }; + return .{ .dynamic = .{ + .static_w = try get(c, "model.llm.layers.{d}.attn." ++ role ++ "_sconv.static_w", .{layer}, .bf16, &.{ 4, 1024 }), + .projection = try get(c, "model.llm.layers.{d}.attn." ++ role ++ "_sconv.weight_proj", .{layer}, .bf16, &.{ 32, 2304 }), + } }; +} + +fn loadWeights(c: *const ck.Checkpoint, config: *const cfg.Config, wp: *const layer_plan.Plan) !Weights { + var w: Weights = undefined; + w.embed = try get(c, "model.llm.embed.weight", .{}, .bf16, &.{ 201024, 2304 }); + w.embed_norm = try get(c, "model.llm.embed_norm.weight", .{}, .bf16, &.{2304}); + w.norm = try get(c, "model.llm.norm.weight", .{}, .bf16, &.{2304}); + w.unembed = try get(c, "model.llm.unembed.weight", .{}, .bf16, &.{ 201024, 2304 }); + w.output_query = try get(c, "model.llm.attn_res.output_query", .{}, .f32, &.{2304}); + w.cross_queries = try get(c, "model.llm.middle_cycle_cross_pass_queries", .{}, .f32, &.{ 24, 2304 }); + w.cross_kv_queries = try get(c, "model.llm.middle_cycle_cross_pass_kv_queries", .{}, .f32, &.{ 24, 2304 }); + for (&w.attn_queries, 0..) |*q, i| { + const global = cfg.isGlobal(@intCast(i + 1)); + const dims: []const usize = if (global) &.{ 3, 2304 } else &.{2304}; + q.* = try get(c, "model.llm.attn_res.attn_queries.{d}", .{i}, .f32, dims); + } + for (&w.mlp_queries, 0..) |*q, i| q.* = try get(c, "model.llm.attn_res.mlp_queries.{d}", .{i}, .f32, &.{2304}); + for (&w.layers, 0..) |*l, i| { + const layer: u32 = @intCast(i); + const p = wp.at(layer); + const global = p.kind == .global; + const q_width: usize = @as(usize, p.heads.q) * p.heads.dim; + const local_norm = if (!global) try get(c, "model.llm.layers.{d}.attn_norm.weight", .{layer}, .bf16, &.{2304}) else undefined; + l.attn = .{ + .wq = try get(c, "model.llm.layers.{d}.attn.wq_du.weight", .{layer}, .bf16, &.{ q_width, 2304 }), + .wk = try get(c, "model.llm.layers.{d}.attn.wk_dv.weight", .{layer}, .bf16, &.{ 1024, 2304 }), + .wv = try get(c, "model.llm.layers.{d}.attn.wv_dv.weight", .{layer}, .bf16, &.{ 1024, 2304 }), + .wr = try get(c, "model.llm.layers.{d}.attn.wr_du.weight", .{layer}, .bf16, &.{ 384, 2304 }), + .wo = try get(c, "model.llm.layers.{d}.attn.wo_ud.weight", .{layer}, .bf16, &.{ 2304, q_width }), + .gate = try get(c, "model.llm.layers.{d}.attn.gate_attn.weight", .{layer}, .bf16, &.{ q_width, 2304 }), + .sink = try get(c, "model.llm.layers.{d}.attn.attn_sink_proj.weight", .{layer}, .bf16, &.{ 24, 2304 }), + .q_scale = try get(c, "model.llm.layers.{d}.attn.q_l2_clip.scale", .{layer}, .bf16, &.{ 24, 128 }), + .rel_scale = try get(c, "model.llm.layers.{d}.attn.rel_l2_clip.scale", .{layer}, .bf16, &.{ 24, 16 }), + .rel_projection = try get(c, "model.llm.layers.{d}.attn.rel_logits_proj.proj", .{layer}, .bf16, &.{ 16, p.extent }), + .k_conv = try loadConv(c, layer, "k", global), + .v_conv = try loadConv(c, layer, "v", global), + .q_norm = if (global) try get(c, "model.llm.layers.{d}.q_input_norm.weight", .{layer}, .bf16, &.{2304}) else local_norm, + .k_norm = if (global) try get(c, "model.llm.layers.{d}.k_input_norm.weight", .{layer}, .bf16, &.{2304}) else local_norm, + .v_norm = if (global) try get(c, "model.llm.layers.{d}.v_input_norm.weight", .{layer}, .bf16, &.{2304}) else local_norm, + }; + l.attn_conv = try get(c, "model.llm.layers.{d}.attn_sconv.weight", .{layer}, .bf16, &.{ 2304, 1, 4 }); + l.mlp_norm = try get(c, "model.llm.layers.{d}.mlp_norm.weight", .{layer}, .bf16, &.{2304}); + l.mlp_conv = try get(c, "model.llm.layers.{d}.mlp_sconv.weight", .{layer}, .bf16, &.{ 2304, 1, 4 }); + l.router_weight = try get(c, "model.llm.layers.{d}.mlp.gate.weight", .{layer}, .bf16, &.{ 128, 2304 }); + l.router_bias = try get(c, "model.llm.layers.{d}.mlp.gate.bias", .{layer}, .f32, &.{128}); + l.gu = try matrix(c, layer, "w13", p.precision, 2304, 2304); + l.down = try matrix(c, layer, "w2", p.precision, 2304, 1152); + l.controllers = null; + if (config.text.loop) |lp| if (layer >= lp.core_start and layer < lp.core_end) { + var controllers: [4]Controller = undefined; + inline for (.{ "attn", "k", "v", "mlp" }, 0..) |role, j| controllers[j] = .{ + .down = try get(c, "model.llm.layers.{d}.controllers." ++ role ++ ".down_weight", .{layer}, .bf16, &.{ 64, 4608 }), + .forget = try get(c, "model.llm.layers.{d}.controllers." ++ role ++ ".forget_weight", .{layer}, .bf16, &.{ 2304, 64 }), + .gain = try get(c, "model.llm.layers.{d}.controllers." ++ role ++ ".gain_weight", .{layer}, .bf16, &.{ 2304, 64 }), + }; + l.controllers = controllers; + }; + } + return w; +} + +pub const Model = struct { + gpa: std.mem.Allocator, + device: mtl.Device, + queue: mtl.Queue, + config: cfg.Config, + checkpoint: ck.Checkpoint, + weights: Weights, + weight_plan: layer_plan.Plan, + attention: attention.Kernels, + glue: glue.Pipelines, + experts: experts.Pipelines, + loop: loop.Pipelines, + dense: [6]mtl.Pipeline, + norm: mtl.Pipeline, + runtime: [runtime_names.len]mtl.Pipeline, + + 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; + const config_path = try std.fs.path.join(gpa, &.{ dir, "config.json" }); + defer gpa.free(config_path); + const text = try std.Io.Dir.cwd().readFileAlloc(io, config_path, gpa, .limited(1 << 24)); + defer gpa.free(text); + var why: cfg.Why = .{}; + m.config = cfg.parse(gpa, text, &why) catch |err| { + std.log.err("inkling2_loop: {s}", .{why.text()}); + return err; + }; + try admitConfig(&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); + + // Mini uses NVFP4 for layers 0-19 and MXFP8 for 20-23; matrix() rechecks all stored tensor metadata and bytes. + var precisions: [24]layer_plan.Precision = undefined; + for (&precisions, 0..) |*p, i| p.* = if (i < 20) .nvfp4 else .mxfp8; + m.weight_plan = try layer_plan.build(&m.config.text, &precisions); + if (m.weight_plan.n_visits != 48) return error.UnsupportedInkling2Loop; + for (files) |path| try m.checkpoint.addFileSelected(m.device, path, "", "model.llm."); + m.weights = try loadWeights(&m.checkpoint, &m.config, &m.weight_plan); + + m.attention = try attention.Kernels.init(gpa, m.device); + errdefer m.attention.deinit(); + m.glue = try glue.Pipelines.load(m.device); + errdefer m.glue.deinit(); + m.experts = try experts.Pipelines.load(m.device); + errdefer m.experts.deinit(); + m.loop = try loop.Pipelines.load(m.device); + errdefer m.loop.deinit(); + { + const lib = try mtl.Library.fromSource(m.device, sources.spark25_glue, .{ .language = mtl.CompileOptions.mlx().language, .math_functions = .precise }); + defer lib.deinit(); + var made: usize = 0; + errdefer for (m.dense[0..made]) |p| p.deinit(); + for ([_]u32{ 1, 2, 4, 8, 16, 32 }, 0..) |rows, i| { + var buf: [32]u8 = undefined; + const name = try std.fmt.bufPrintSentinel(&buf, "sp_matvec_{d}", .{rows}, 0); + m.dense[i] = try mtl.Pipeline.init(m.device, lib, name, false); + made += 1; + } + m.norm = try mtl.Pipeline.init(m.device, lib, "sp_norm", false); + } + errdefer { + m.norm.deinit(); + for (m.dense) |p| p.deinit(); + } + { + const lib = try mtl.Library.fromSource(m.device, runtime_source, mtl.CompileOptions.mlx()); + defer lib.deinit(); + var made: usize = 0; + errdefer for (m.runtime[0..made]) |p| p.deinit(); + for (runtime_names, 0..) |name, i| { + m.runtime[i] = try mtl.Pipeline.init(m.device, lib, name, false); + made += 1; + } + } + errdefer for (m.runtime) |p| p.deinit(); + return m; + } + + pub fn deinit(m: *Model) void { + for (m.runtime) |p| p.deinit(); + m.norm.deinit(); + for (m.dense) |p| p.deinit(); + m.loop.deinit(); + m.experts.deinit(); + m.glue.deinit(); + m.attention.deinit(); + m.checkpoint.deinit(); + m.queue.deinit(); + m.device.deinit(); + m.gpa.destroy(m); + } +}; diff --git a/zig/src/families/inkling2/metal/ref.zig b/zig/src/families/inkling2/metal/ref.zig new file mode 100644 index 00000000000..1e6f5a69622 --- /dev/null +++ b/zig/src/families/inkling2/metal/ref.zig @@ -0,0 +1,4 @@ +//! Shared Metal buffer reference for Inkling 2 launchers and their state buffers. +const mtl = @import("metal"); + +pub const Ref = struct { buf: mtl.Buffer, off: usize = 0 }; diff --git a/zig/src/families/inkling2/metal/runtime_kernels_test.zig b/zig/src/families/inkling2/metal/runtime_kernels_test.zig new file mode 100644 index 00000000000..ceb359181d8 --- /dev/null +++ b/zig/src/families/inkling2/metal/runtime_kernels_test.zig @@ -0,0 +1,116 @@ +//! Host-only proof of Mini's runtime source identity, launch ABI, block layout and rounding. +const std = @import("std"); +const p = @import("runtime_plan.zig"); +const model = @import("model.zig"); +const records = @import("core").contract.inkling2_runtime_metal_records.records; +const shader = @import("inkling2_metal").runtime; +const t = std.testing; + +fn near(want: f64, got: f64) !void { + try t.expectApproxEqAbs(want, got, 1e-12); +} + +test "runtime source is the one exported source and every helper has one launch record" { + try t.expectEqualStrings(shader, model.runtime_source); + try t.expectEqualStrings(shader, @import("kernel_sources").inkling2_runtime); + try t.expectEqual(std.enums.values(p.Kind).len, model.runtime_names.len); + try t.expectEqual(std.enums.values(p.Kind).len, records.len); + for (std.enums.values(p.Kind), records, model.runtime_names) |kind, record, runtime_name| { + try t.expectEqualStrings(kind.label(), record.name); + try t.expectEqualStrings(kind.symbol(), runtime_name); + try t.expectEqual(@as(usize, 1), std.mem.count(u8, shader, kind.symbol())); + try t.expectEqual(p.threads, record.threads); + try t.expectEqual(record.threads, record.reserved); + try t.expectEqual(@as(u32, 0), record.tg_memory); + } + try t.expectEqual(@as(usize, 1), std.mem.count(u8, shader, "#pragma METAL fp contract(off)")); + try t.expectEqual(@as(usize, 1), std.mem.count(u8, shader, "struct InkRuntimeArgs { uint count, boundary; };")); +} + +test "linear launches bind H=2304 rows and the exact eight-byte argument ABI" { + try t.expectEqual(@as(usize, 8), @sizeOf(p.RuntimeArgs)); + try t.expectEqual(@as(usize, 0), @offsetOf(p.RuntimeArgs, "count")); + try t.expectEqual(@as(usize, 4), @offsetOf(p.RuntimeArgs, "boundary")); + for (std.enums.values(p.Kind)) |kind| { + const call = p.Call{ .rows = 7, .n = p.hidden, .k = if (kind == .attention_partial) 4 else 1 }; + try t.expect(p.valid(kind, call)); + const a = p.args(kind, call); + try t.expectEqual(@as(u32, 7 * p.hidden), a.count); + try t.expectEqual(@as(u32, if (kind == .attention_partial) 4 else if (kind == .capture_tap) 1 else 0), a.boundary); + try t.expectEqual(@as(usize, 7 * p.hidden), p.geometry(call).count); + try t.expectEqual(p.threads, p.geometry(call).threads); + try t.expectEqual(@as(u32, 0), p.geometry(call).tg_memory); + const outputs: usize = 7 * p.hidden * (if (kind == .capture_tap) @as(usize, p.tap_channels) else 1); + try t.expectEqual(outputs, p.outputCount(kind, call)); + try t.expect(!p.valid(kind, .{ .rows = 0, .n = p.hidden, .k = call.k })); + if (kind == .copy_bf16 or kind == .copy_f32) { + try t.expect(p.valid(kind, .{ .rows = 5, .n = 1024, .k = 1 })); + } else { + try t.expect(!p.valid(kind, .{ .rows = 1, .n = p.hidden - 1, .k = call.k })); + } + } + try t.expect(!p.valid(.copy_bf16, .{ .rows = 1, .n = 0, .k = 1 })); + try t.expect(p.valid(.attention_partial, .{ .rows = 1, .n = p.hidden, .k = 0 })); + try t.expect(!p.valid(.attention_partial, .{ .rows = 1, .n = p.hidden, .k = 5 })); + try t.expect(!p.valid(.widen, .{ .rows = 1, .n = p.hidden, .k = 0 })); + try t.expect(p.valid(.capture_tap, .{ .rows = 1, .n = p.hidden, .k = 3 })); + try t.expect(!p.valid(.capture_tap, .{ .rows = 1, .n = p.hidden, .k = 4 })); +} + +test "DSpark capture channels are packed [row][tap][H] in visit order" { + try t.expectEqual(@as(usize, 4), p.tap_channels); + try t.expectEqual(@as(usize, 0), p.tapOffset(0, 0)); + try t.expectEqual(p.hidden, p.tapOffset(0, 1)); + try t.expectEqual(3 * p.hidden, p.tapOffset(0, 3)); + try t.expectEqual(4 * p.hidden, p.tapOffset(1, 0)); + try t.expectEqual(7 * p.hidden, p.tapOffset(1, 3)); + try t.expectEqual(2 * 4 * p.hidden, p.outputCount(.capture_tap, .{ .rows = 2, .n = p.hidden, .k = 0 })); + try t.expectEqual(2 * p.hidden, p.args(.capture_tap, .{ .rows = 2, .n = p.hidden, .k = 0 }).count); +} + +test "four completed BF16 blocks are row-major and disjoint from the partial source" { + try t.expectEqual(@as(usize, 0), p.blockOffset(0, 1)); + try t.expectEqual(3 * p.hidden, p.blockOffset(0, 4)); + try t.expectEqual(4 * p.hidden, p.blockOffset(1, 1)); + try t.expectEqual(15 * p.hidden, p.blockOffset(3, 4)); + var previous: usize = 0; + for (0..4) |row| for (1..5) |boundary| { + const at = p.blockOffset(row, boundary); + if (at != 0) try t.expectEqual(previous + p.hidden, at); + previous = at; + }; + try t.expectEqual(4 * 4 * p.hidden, previous + p.hidden); +} + +test "attention restart and addition references cover every valid boundary" { + const partial: f32 = 1.5; + const attention: f32 = -0.25; + try near(1.25, p.attentionPartial(partial, attention, 0)); + for (1..5) |boundary| try near(-0.25, p.attentionPartial(partial, attention, boundary)); + // One binary32 addition rounds this midpoint to one; unrounded FP64 addition would not. + const ulp: f32 = 0x1p-24; + try near(1, p.attentionPartial(1, ulp, 0)); + try t.expect(p.attentionPartial(1, ulp, 0) != 1 + @as(f64, ulp)); + for (1..5) |boundary| try near(@as(f64, ulp), p.attentionPartial(std.math.nan(f32), ulp, boundary)); +} + +test "MLP partial rounds its FP32 sum to nearest-even BF16" { + try near(1, p.roundBf16(@as(f32, 1.00390625))); + try near(1.015625, p.roundBf16(@as(f32, 1.01171875))); + try near(1, p.mlpPartial(1, 0.00390625)); + try near(1.015625, p.mlpPartial(1, 0.01171875)); + try t.expect(p.mlpPartial(1, 0.00390625) != 1.00390625); +} + +test "copy and widening witnesses preserve actual BF16 and FP32 values" { + const bf16 = @import("bf16_round"); + const bf_values = [_]f32{ -0.0, 1.0, -2.5, 0.0078125, std.math.inf(f32) }; + for (bf_values) |x| { + const bits = bf16.bits(x); + const stored: f32 = @bitCast(@as(u32, bits) << 16); + try t.expectEqual(@as(u32, @bitCast(x)), @as(u32, bits) << 16); + try near(x, stored); + } + const f32_values = [_]f32{ -0.0, 1.00000011920928955078125, -8192.25 }; + for (f32_values) |x| try t.expectEqual(@as(u32, @bitCast(x)), @as(u32, @bitCast(@as(f32, @floatCast(@as(f64, x)))))); +} diff --git a/zig/src/families/inkling2/metal/runtime_plan.zig b/zig/src/families/inkling2/metal/runtime_plan.zig new file mode 100644 index 00000000000..4edc008967d --- /dev/null +++ b/zig/src/families/inkling2/metal/runtime_plan.zig @@ -0,0 +1,105 @@ +//! Pure Inkling 2 Mini runtime launch geometry and independent FP64 references. +const std = @import("std"); + +pub const hidden = 2304; +pub const block_slots = 4; +pub const tap_channels = 4; +pub const max_rows = 64; +pub const threads: u32 = 256; +pub const RuntimeArgs = extern struct { count: u32, boundary: u32 }; + +pub const Kind = enum { + copy_bf16, + copy_f32, + widen, + attention_partial, + mlp_partial, + capture_tap, + + pub fn symbol(k: Kind) []const u8 { + return switch (k) { + .copy_bf16 => "tf_ink2_copy_bf16", + .copy_f32 => "tf_ink2_copy_f32", + .widen => "tf_ink2_widen", + .attention_partial => "tf_ink2_attention_partial", + .mlp_partial => "tf_ink2_mlp_partial", + .capture_tap => "tf_ink2_capture_tap", + }; + } + pub fn label(k: Kind) []const u8 { + return switch (k) { + .copy_bf16 => "metal inkling2 runtime copy_bf16 tf_ink2_copy_bf16", + .copy_f32 => "metal inkling2 runtime copy_f32 tf_ink2_copy_f32", + .widen => "metal inkling2 runtime widen tf_ink2_widen", + .attention_partial => "metal inkling2 runtime attention_partial tf_ink2_attention_partial", + .mlp_partial => "metal inkling2 runtime mlp_partial tf_ink2_mlp_partial", + .capture_tap => "metal inkling2 runtime capture_tap tf_ink2_capture_tap", + }; + } +}; + +/// `k` is one for pointwise helpers, a boundary for attention, or a DSpark tap channel. +pub const Call = struct { rows: usize, n: usize, k: usize }; +pub const Geometry = struct { count: usize, threads: u32 = threads, tg_memory: u32 = 0 }; + +pub fn valid(kind: Kind, c: Call) bool { + if (c.rows == 0 or c.rows > max_rows or c.n == 0 or c.rows > std.math.maxInt(u32) / c.n) return false; + return switch (kind) { + .copy_bf16, .copy_f32 => c.k == 1, + .capture_tap => c.n == hidden and c.k < tap_channels, + .widen, .attention_partial, .mlp_partial => c.n == hidden and switch (kind) { + .attention_partial => c.k <= block_slots, + else => c.k == 1, + }, + }; +} + +pub fn geometry(c: Call) Geometry { + return .{ .count = c.rows * c.n }; +} + +/// Values in the full destination for one capture launch; its dispatch still reads rows*n. +pub fn outputCount(kind: Kind, c: Call) usize { + const channels: usize = if (kind == .capture_tap) tap_channels else 1; + return c.rows * c.n * channels; +} + +pub fn args(kind: Kind, c: Call) RuntimeArgs { + std.debug.assert(valid(kind, c)); + return .{ .count = @intCast(c.rows * c.n), .boundary = if (kind == .attention_partial or kind == .capture_tap) @intCast(c.k) else 0 }; +} + +/// Completed blocks are [row][four BF16 blocks][H]; the separate partial is not stored here. +pub fn blockOffset(row: usize, boundary: usize) usize { + std.debug.assert(row < max_rows and boundary >= 1 and boundary <= block_slots); + return (row * block_slots + boundary - 1) * hidden; +} + +/// DSpark features are [row][four taps][H]; a capture launch writes one tap channel. +pub fn tapOffset(row: usize, channel: usize) usize { + std.debug.assert(row < max_rows and channel < tap_channels); + return (row * tap_channels + channel) * hidden; +} + +/// Round through binary32 and nearest-even BF16, returning an exactly representable FP64 value. +pub fn roundBf16(v: anytype) f64 { + const x: f32 = @floatCast(v); + const bits: u32 = @bitCast(x); + const rounded: u16 = if (std.math.isNan(x)) + @truncate((bits >> 16) | 0x40) + else + @truncate((bits +% 0x7fff +% ((bits >> 16) & 1)) >> 16); + const value: f32 = @bitCast(@as(u32, rounded) << 16); + return value; +} + +/// Boundary restarts the FP32 partial; otherwise the two exact BF16 inputs undergo one FP32 add. +pub fn attentionPartial(p: f32, x: f32, boundary: usize) f64 { + std.debug.assert(boundary <= block_slots); + return if (boundary != 0) x else @as(f32, p + x); +} + +/// FP32 residual addition followed by the required BF16 endpoint. +pub fn mlpPartial(t: f32, x: f32) f64 { + return roundBf16(@as(f32, t + x)); +} diff --git a/zig/src/families/inkling2/metal/runtime_test.zig b/zig/src/families/inkling2/metal/runtime_test.zig new file mode 100644 index 00000000000..f12f0fe2ad3 --- /dev/null +++ b/zig/src/families/inkling2/metal/runtime_test.zig @@ -0,0 +1,226 @@ +//! Host-only schedule, cache-layout, accepted-history and compact-snapshot checks. +const std = @import("std"); +const mtl = @import("metal"); +const ap = @import("attention_plan.zig"); +const cfg = @import("../config.zig"); +const layer_plan = @import("../plan.zig"); +const state = @import("state.zig"); +const snapshot = @import("snapshot.zig"); +const model = @import("model.zig"); +const fwd = @import("forward.zig"); +const backend = @import("backend.zig"); + +fn mini() cfg.Config { + return .{ + .text = .{ + .hidden = 2304, + .layers = 24, + .vocab = 201024, + .unpadded_vocab = 200058, + .local = .{ .q = 24, .kv = 8, .dim = 128 }, + .global = .{ .q = 24, .kv = 8, .dim = 128 }, + .window = 1024, + .d_rel = 16, + .rel_extent = 1024, + .log_floor = 8192, + .log_alpha = 0.1, + .eps = 1e-6, + .qk_clip = 22.627416997969522, + .rel_clip = 8, + .block = 6, + .experts = 128, + .topk = 8, + .expert_inter = 1152, + .route_scale = 8, + .gate_cap = 4, + .up_cap = 25, + .logit_cap = 30, + .max_context = 1048576, + .loop = .{ .core_start = 6, .core_end = 18, .passes = 3, .gate_rank = 64 }, + }, + .vision = undefined, + .mtp = null, + .eos = 200055, + .image_token = 200054, + }; +} + +fn schedule() layer_plan.Plan { + const c = mini(); + var precision: [24]layer_plan.Precision = @splat(.nvfp4); + for (precision[4..]) |*p| p.* = .mxfp8; + return layer_plan.build(&c.text, &precision) catch unreachable; +} + +test "Mini admits only its fixed geometry and expands 24 weights to 48 visits" { + const c = mini(); + try model.admitConfig(&c); + const p = schedule(); + try std.testing.expectEqual(@as(u32, 48), p.n_visits); + try std.testing.expectEqual(@as(u32, 8), p.visitCount(.global)); + try std.testing.expectEqual(@as(u32, 5), p.final_sources); + for (p.visits[0..p.n_visits], 0..) |v, i| { + try std.testing.expectEqual(@as(u32, @intCast(i)), v.cache_slot); + try std.testing.expect(v.layer < 24); + } + for ([_]usize{ 18, 30 }) |i| { + try std.testing.expect(p.visits[i].pass > 1); + try std.testing.expectEqual(@as(u32, 6), p.visits[i].layer); + try std.testing.expect(p.visits[i].hasMessages()); + } + try std.testing.expect(!p.visits[0].hasMessages()); + try std.testing.expect(!(p.visits[17].pass > 1 and p.visits[17].layer == 6)); +} + +test "Every visit and convolution role has disjoint persistent and staged bytes" { + var previous_persistent: usize = 0; + for (0..state.visit_slots) |slot| for (0..state.conv_states) |cs| { + const off = state.convByteOffset(slot, cs, 0, 3); + const len = 3 * state.convWidth(cs) * 2; + if (slot != 0 or cs != 0) try std.testing.expect(off >= previous_persistent); + previous_persistent = off + len; + for (0..4) |accepted| { + const source = state.convByteOffset(slot, cs, accepted, 3 + state.max_rows); + try std.testing.expect(source + len <= state.taps_bytes); + } + }; + try std.testing.expectEqual(state.conv_bytes, previous_persistent); + // Decode acceptance k preserves exactly old[k], old[k+1], old[k+2] through raw[k..k+3]. + for (0..state.window_rows + 1) |accepted| { + const old = state.convByteOffset(47, 3, 0, 3 + state.max_rows); + const selected = state.convByteOffset(47, 3, accepted, 3 + state.max_rows); + try std.testing.expectEqual(old + accepted * state.hidden * 2, selected); + } +} + +test "Compact snapshots charge global prefixes and sliding physical rings" { + const one_layer_pair: u64 = state.kv_width * 2 * 2; + for ([_]usize{ 0, 1, 1024, state.sliding_ring, state.sliding_ring + 1 }) |at| { + const n: u64 = @intCast(at); + const live = @as(u64, 8) * n + @as(u64, 40) * @as(u64, @intCast(@min(at, state.sliding_ring))); + const kv = live * one_layer_pair; + const expected = kv + state.conv_bytes; + try std.testing.expectEqual(expected, snapshot.bytes(at)); + } + try std.testing.expect(snapshot.bytes(4096) < snapshot.bytes(8192)); + try std.testing.expectEqual(state.conv_bytes, state.visit_slots * 3 * state.conv_row_values * 2); +} + +test "DSpark feature rows are 4x2304 BF16 and ranges expose only live accepted rows" { + try std.testing.expectEqual(@as(usize, 4 * 2304 * 2), state.feature_row_bytes); + try std.testing.expectEqual(@as(usize, 7 * 4 * 2304 * 2), state.captureBytes(7)); + const off = 3 * state.feature_row_bytes; + const tp = state.Tap{ .buf = null, .off = off, .start = 100, .rows = 4, .gen = 9 }; + try std.testing.expectEqual(off, try state.featureOffset(tp, 100, 4, 9)); + try std.testing.expectEqual(off + 2 * state.feature_row_bytes, try state.featureOffset(tp, 102, 2, 9)); + try std.testing.expectError(error.StaleInkling2Taps, state.featureOffset(tp, 100, 1, 10)); + try std.testing.expectError(error.Inkling2TapsNotHeld, state.featureOffset(tp, 99, 1, 9)); + try std.testing.expectError(error.Inkling2TapsNotHeld, state.featureOffset(tp, 102, 3, 9)); + try std.testing.expectError(error.Inkling2TapsNotHeld, state.featureOffset(tp, 104, 1, 9)); + try std.testing.expectError(error.Inkling2TapsNotHeld, state.featureOffset(tp, 100, 0, 9)); + var accepted = tp; + accepted.rows = 2; + try std.testing.expectEqual(off + state.feature_row_bytes, try state.featureOffset(accepted, 101, 1, 9)); + try std.testing.expectError(error.Inkling2TapsNotHeld, state.featureOffset(accepted, 102, 1, 9)); + accepted.gen = null; // the copied prompt-last row survives later scratch generations + try std.testing.expectEqual(off, try state.featureOffset(accepted, 100, 1, 1000)); +} + +test "tap48 captures every final-norm row but last-row-only logits keep their exact source" { + const captured = fwd.finalPlan(7, false, true); + try std.testing.expectEqual(@as(usize, 7), captured.work_rows); + try std.testing.expectEqual(@as(usize, 7), captured.capture_rows); + try std.testing.expectEqual(@as(usize, 1), captured.logits_rows); + try std.testing.expectEqual(@as(usize, 6), captured.logits_row); + try std.testing.expectEqual(@as(usize, 6 * state.hidden * 2), captured.logits_row * state.hidden * 2); + const all = fwd.finalPlan(7, true, true); + try std.testing.expectEqual(@as(usize, 7), all.logits_rows); + try std.testing.expectEqual(@as(usize, 0), all.logits_row); +} + +test "no-draft defaults retain KIM2's single last-row final norm and no capture" { + const options: fwd.Options = .{}; + try std.testing.expect(options.taps == null); + const plain = fwd.finalPlan(7, false, options.taps != null); + try std.testing.expectEqual(@as(usize, 1), plain.work_rows); + try std.testing.expectEqual(@as(usize, 0), plain.capture_rows); + try std.testing.expectEqual(@as(usize, 1), plain.logits_rows); + try std.testing.expectEqual(@as(usize, 0), plain.logits_row); + const all = fwd.finalPlan(7, true, false); + try std.testing.expectEqual(@as(usize, 7), all.work_rows); + try std.testing.expectEqual(@as(usize, 7), all.logits_rows); + try std.testing.expectEqual(@as(usize, 0), all.capture_rows); +} + +test "prepare_features requires exactly Mini's checkpoint tap list" { + var c = mini(); + c.mtp = .{ + .layers = 3, + .q_heads = 24, + .kv_heads = 8, + .head_dim = 128, + .inter = 9216, + .rope_theta = 1e6, + .window = 1024, + .local = .{ true, false, true, false, false, false, false, false }, + .block = 8, + .rank = 256, + .taps = .{ 5, 23, 41, 48, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, + .taps_n = 4, + }; + try backend.validateTaps(&c, &.{ 5, 23, 41, 48 }); + try std.testing.expectError(error.UnsupportedInkling2Taps, backend.validateTaps(&c, &.{ 5, 23, 41 })); + try std.testing.expectError(error.UnsupportedInkling2Taps, backend.validateTaps(&c, &.{ 5, 11, 41, 48 })); + c.mtp.?.taps[1] = 22; + try std.testing.expectError(error.UnsupportedInkling2Taps, backend.validateTaps(&c, &.{ 5, 23, 41, 48 })); + c.mtp = null; + try std.testing.expectError(error.UnsupportedInkling2Taps, backend.validateTaps(&c, &.{ 5, 23, 41, 48 })); +} + +/// Every head's first `rows` rows of every slot's keys and values, then the convolution states, to or from `flat`. +fn moveLive(queue: mtl.Queue, cache: *const state.Cache, flat: mtl.Buffer, rows: usize, into: bool) !void { + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const cb = queue.commandBuffer(); + const e = cb.blit(); + const n = rows * ap.head_dim * 2; + var at: usize = 0; + for (0..state.visit_slots) |slot| for ([_]usize{ cache.key_at[slot], cache.value_at[slot] }) |base| for (0..state.kv_width / ap.head_dim) |h| { + const off = base + h * cache.ring(slot) * ap.head_dim * 2; + if (into) e.copy(flat, at, cache.kv, off, n) else e.copy(cache.kv, off, flat, at, n); + at += n; + }; + if (into) e.copy(flat, at, cache.conv, 0, state.conv_bytes) else e.copy(cache.conv, 0, flat, at, state.conv_bytes); + e.end(); + cb.commit(); + cb.wait(); + if (cb.failure() != null) return error.GpuFailed; +} + +test "A snapshot restores each head's live rows into a cache of another capacity" { + const device = mtl.Device.init() catch return error.SkipZigTest; + const queue = try device.queue(); + defer queue.deinit(); + const p = schedule(); + const rows = 100; + var from = try state.Cache.init(device, 200, &p); + defer from.deinit(); + var to = try state.Cache.init(device, 500, &p); + defer to.deinit(); + try std.testing.expect(from.ring(5) != to.ring(5) and from.globals[5] and rows < from.ring(0)); + const size = state.visit_slots * 2 * state.kv_width * 2 * rows + state.conv_bytes; + const want = try device.buffer(size, mtl.ResourceOptions.shared); + defer want.deinit(); + const got = try device.buffer(size, mtl.ResourceOptions.shared); + defer got.deinit(); + var prng = std.Random.DefaultPrng.init(7); + prng.random().bytes(want.slice(u8, size)); + try moveLive(queue, &from, want, rows, true); + from.len = rows; + var snap = try snapshot.save(device, queue, &from); + defer snap.deinit(); + try snapshot.restore(&to, queue, &snap); + try std.testing.expectEqual(@as(usize, rows), to.len); + try moveLive(queue, &to, got, rows, false); + try std.testing.expect(std.mem.eql(u8, want.slice(u8, size), got.slice(u8, size))); +} diff --git a/zig/src/families/inkling2/metal/serving_test.zig b/zig/src/families/inkling2/metal/serving_test.zig new file mode 100644 index 00000000000..eb761e0fecd --- /dev/null +++ b/zig/src/families/inkling2/metal/serving_test.zig @@ -0,0 +1,307 @@ +//! Real-checkpoint Mini serving: serial target references, cache restore, DSpark and exact transactions. +const std = @import("std"); +const mtl = @import("metal"); +const lanes = @import("lanes"); +const api = @import("engine_api"); +const native = @import("../../../native/inkling2.zig"); +const Model = @import("model.zig").Model; +const backend = @import("backend.zig"); +const st = @import("state.zig"); +const dspark = @import("dspark.zig"); + +const gpa = std.testing.allocator; +const io = std.testing.io; +/// A history the prompt cache can end a state on: the family's chunk grid. +const history = st.prompt_rows; +const context = 4 * history; +const made = 24; +const taps = [_]u32{ 5, 23, 41, 48 }; + +fn checkpoint() ![]const u8 { + return @import("sys").getenv("TF_INKLING2_METAL_DIR") orelse error.SkipZigTest; +} + +fn prompt(comptime n: usize, salt: u32) [n]u32 { + var ids: [n]u32 = undefined; + for (&ids, 0..) |*id, i| id.* = @intCast(1000 + (i * 37 + @as(usize, salt) * 101) % 20000); + return ids; +} + +const TapSink = struct { + bytes: [st.feature_row_bytes]u8 = @splat(0), + seen: usize = 0, + + fn take(ptr: *anyopaque, s: *lanes.Stream, f: lanes.backend.Features, start: u64) !void { + const self: *TapSink = @ptrCast(@alignCast(ptr)); + try std.testing.expectEqual(lanes.backend.Features.Space.device, f.space); + try std.testing.expectEqual(lanes.backend.Features.Dtype.bf16, f.dtype); + try std.testing.expectEqual(@as(u32, st.feature_row_bytes), f.row_bytes); + try std.testing.expect(f.rows > 0); + if (start + f.rows != s.prompt_len) return; + const buf: mtl.Buffer = .{ .id = @ptrFromInt(f.buffer) }; + const bytes = buf.slice(u8, @intCast(f.offset + f.rows * f.row_bytes)); + const last = bytes[@intCast(f.offset + (f.rows - 1) * f.row_bytes)..][0..st.feature_row_bytes]; + @memcpy(&self.bytes, last); + self.seen += 1; + } +}; + +fn featureRow(b: lanes.backend.Backend, s: *lanes.Stream, start: u64) ![st.feature_row_bytes]u8 { + const f = try b.features(s, &taps, start, 1); + try std.testing.expectEqual(lanes.backend.Features.Space.device, f.space); + try std.testing.expectEqual(lanes.backend.Features.Dtype.bf16, f.dtype); + try std.testing.expectEqual(@as(u32, 1), f.rows); + try std.testing.expectEqual(@as(u32, st.feature_row_bytes), f.row_bytes); + const buf: mtl.Buffer = .{ .id = @ptrFromInt(f.buffer) }; + const bytes = buf.slice(u8, @intCast(f.offset + f.row_bytes)); + var row: [st.feature_row_bytes]u8 = undefined; + @memcpy(&row, bytes[@intCast(f.offset)..][0..st.feature_row_bytes]); + return row; +} + +const Reference = struct { + tokens: [made]u32, + first: lanes.LogprobRow, + tap: [st.feature_row_bytes]u8, + full_tap: [st.feature_row_bytes]u8 = undefined, + partial_tap: [st.feature_row_bytes]u8 = undefined, + continuation_tap: [st.feature_row_bytes]u8 = undefined, +}; + +fn serial(b: lanes.backend.Backend, ids: []const u32) !Reference { + var sink: TapSink = .{}; + var s = try lanes.Stream.init(gpa, .{ .id = "host-reference", .prompt = ids, .max_new = made, .drafts = false, .logprobs = 3 }); + defer s.deinit(gpa); + try b.vtable.prefill_features.?(b.ptr, &s, &taps, .{ .ptr = &sink, .take = TapSink.take }); + defer b.release(&s); + try std.testing.expectEqual(@as(usize, 1), sink.seen); + var next = try b.read(try b.first(&s, ids.len)); + const first = try b.firstRow(&s); + var out: Reference = .{ .tokens = undefined, .first = first, .tap = sink.bytes }; + out.tokens[0] = next; + try std.testing.expectEqual(next, first.token); + for (1..made) |i| { + next = try b.read(try b.queue(&s, .{ .value = next }, ids.len + i)); + out.tokens[i] = next; + switch (i) { + 8 => out.full_tap = try featureRow(b, &s, ids.len + 7), + 15 => out.partial_tap = try featureRow(b, &s, ids.len + 14), + 16 => out.continuation_tap = try featureRow(b, &s, ids.len + 15), + else => {}, + } + } + return out; +} + +fn withReference(dir: []const u8, ids: []const u32, extended: ?[]const u32) !struct { first: Reference, second: ?Reference } { + const model = try Model.load(gpa, io, dir); + defer model.deinit(); + const target = try backend.Metal.init(gpa, model, .{ .capacity = context, .streams = 1, .budget = 2 * st.cacheBytes(context) }); + defer target.deinit(); + try target.warm(); + const b = target.backend(); + try b.vtable.prepare_features.?(b.ptr, &taps); + const first = try serial(b, ids); + const repeated = try serial(b, ids); + try std.testing.expectEqualSlices(u8, &first.tap, &repeated.tap); + try std.testing.expectEqualSlices(u32, &first.tokens, &repeated.tokens); + try expectFirstRow(first.first, repeated.first); + const second = if (extended) |p| try serial(b, p) else null; + return .{ .first = first, .second = second }; +} + +fn expectFirstRow(want: lanes.LogprobRow, got: lanes.LogprobRow) !void { + try std.testing.expectEqual(want.token, got.token); + try std.testing.expectEqual(@as(u32, @bitCast(want.logprob)), @as(u32, @bitCast(got.logprob))); + try std.testing.expectEqual(want.count, got.count); + try std.testing.expectEqualSlices(u32, want.ids[0..want.count], got.ids[0..got.count]); + try std.testing.expectEqualSlices(f32, want.logprobs[0..want.count], got.logprobs[0..got.count]); +} + +const Reply = struct { + mutex: std.Io.Mutex = .init, + tokens: std.ArrayList(u32) = .empty, + rows: std.ArrayList(lanes.LogprobRow) = .empty, + cached: ?u32 = null, + drafted: u64 = 0, + accepted: u64 = 0, + done: ?api.Reason = null, + + fn event(ptr: *anyopaque, _: api.Id, item: *const api.Event) void { + const self: *Reply = @ptrCast(@alignCast(ptr)); + self.mutex.lockUncancelable(io); + defer self.mutex.unlock(io); + switch (item.*) { + .tokens => |ids| self.tokens.appendSlice(gpa, ids) catch {}, + .logprobs => |rows| self.rows.appendSlice(gpa, rows) catch {}, + .prefilled => |n| self.cached = n, + .finished => |f| { + self.done = f.reason; + self.drafted = f.stats.drafted; + self.accepted = f.stats.accepted; + }, + else => {}, + } + } + + fn wait(self: *Reply) !api.Reason { + for (0..600_000) |_| { + self.mutex.lockUncancelable(io); + const done = self.done; + self.mutex.unlock(io); + if (done) |reason| return reason; + std.Io.sleep(io, .fromMilliseconds(1), .awake) catch {}; + } + return error.Timeout; + } + + fn deinit(self: *Reply) void { + self.tokens.deinit(gpa); + self.rows.deinit(gpa); + } +}; + +fn serve(native_opened: api.Opened, id: api.Id, request: *const api.Request) !Reply { + var reply: Reply = .{}; + errdefer reply.deinit(); + try native_opened.engine.submit(id, request, .{ .ctx = &reply, .event = Reply.event }); + try std.testing.expectEqual(api.Reason.length, try reply.wait()); + try std.testing.expectEqual(@as(usize, made), reply.tokens.items.len); + return reply; +} + +fn opened(dir: []const u8, drafter: ?[]const u8, cache_gib: ?f64) !api.Opened { + var why: []const u8 = ""; + const result = try native.open(gpa, gpa, io, .{ + .dir = dir, + .model_type = "inkling2_loop", + .context = context, + .lanes = 1, + .drafts = drafter != null, + .drafter = drafter, + .prompt_cache_gib = cache_gib, + .decode_share = 0.5, + }, &why); + if (result == null) { + std.debug.print("Mini Metal open refused: {s}\n", .{why}); + return error.MiniMetalOpenRefused; + } + return result.?; +} + +fn expectTokens(want: *const Reference, got: *const Reply) !void { + try std.testing.expectEqualSlices(u32, &want.tokens, got.tokens.items); + try std.testing.expect(got.rows.items.len >= 1); + try expectFirstRow(want.first, got.rows.items[0]); +} + +fn transactions(dir: []const u8, drafter_dir: []const u8, ids: []const u32, want: *const Reference) !void { + const model = try Model.load(gpa, io, dir); + defer model.deinit(); + const target = try backend.Metal.init(gpa, model, .{ .capacity = context, .streams = 1, .budget = st.cacheBytes(context) }); + defer target.deinit(); + const draft_head = try dspark.Drafter.init(gpa, io, model.device, model, drafter_dir); + defer draft_head.deinit(); + try draft_head.setContext(context); + var wrapped = try lanes.drafted.Drafted.init(gpa, target.backend(), draft_head.drafter()); + defer wrapped.deinit(); + wrapped.first_rows = true; + const b = wrapped.backend(); + const target_b = target.backend(); + var s = try lanes.Stream.init(gpa, .{ .id = "transactions", .prompt = ids, .max_new = made, .drafts = true, .logprobs = 3 }); + defer s.deinit(gpa); + try b.prefill(&s); + defer b.release(&s); + try std.testing.expectEqual(want.tokens[0], try b.read(try b.first(&s, ids.len))); + try expectFirstRow(want.first, try b.firstRow(&s)); + try std.testing.expectEqualSlices(u8, &want.tap, &(try featureRow(target_b, &s, ids.len - 1))); + + const full_drafts = want.tokens[1..8]; + const full_positions = [_]u64{ ids.len + 1, ids.len + 2, ids.len + 3, ids.len + 4, ids.len + 5, ids.len + 6, ids.len + 7, ids.len + 8 }; + const full_path = [_]u32{ 0, 1, 2, 3, 4, 5, 6, 7 }; + const full = [_]lanes.backend.Window{.{ .stream = &s, .pending = want.tokens[0], .held = 0, .tokens = full_drafts, .parents = null, .positions = &full_positions }}; + var sampled: [8]u32 = undefined; + var echo: [7]u32 = undefined; + var full_out = [_]lanes.backend.Verified{.{ .sampled = &sampled, .drafts = &echo }}; + try b.verify(&full, &full_out); + try std.testing.expectEqualSlices(u32, want.tokens[1..9], &sampled); + try std.testing.expectEqualSlices(u32, full_drafts, &echo); + try b.keep(&full, &.{&full_path}); + try std.testing.expectEqualSlices(u8, &want.full_tap, &(try featureRow(target_b, &s, ids.len + 7))); + try b.draft(&.{.{ .stream = &s, .follow = want.tokens[1..9], .rows = &full_path, .start = ids.len, .position = ids.len + 9, .depth = 7 }}); + + var partial_drafts = want.tokens[9..16].*; + partial_drafts[6] = (want.tokens[15] + 1) % model.config.text.unpadded_vocab; + const partial_positions = [_]u64{ ids.len + 9, ids.len + 10, ids.len + 11, ids.len + 12, ids.len + 13, ids.len + 14, ids.len + 15, ids.len + 16 }; + const partial = [_]lanes.backend.Window{.{ .stream = &s, .pending = want.tokens[8], .held = 0, .tokens = &partial_drafts, .parents = null, .positions = &partial_positions }}; + const path = [_]u32{ 0, 1, 2, 3, 4, 5, 6 }; + var partial_out = [_]lanes.backend.Verified{.{ .sampled = &sampled, .drafts = &echo }}; + try b.verify(&partial, &partial_out); + try std.testing.expectEqualSlices(u32, want.tokens[9..16], sampled[0..7]); + try b.keep(&partial, &.{&path}); + try std.testing.expectEqualSlices(u8, &want.partial_tap, &(try featureRow(target_b, &s, ids.len + 14))); + try b.draft(&.{.{ .stream = &s, .follow = want.tokens[9..16], .rows = &path, .start = ids.len + 8, .position = ids.len + 16, .depth = 7 }}); + const next = try b.read(try b.queue(&s, .{ .value = want.tokens[15] }, ids.len + 16)); + try std.testing.expectEqual(want.tokens[16], next); + try std.testing.expectEqualSlices(u8, &want.continuation_tap, &(try featureRow(target_b, &s, ids.len + 15))); +} + +test "Mini Metal serving matches the host reference token for token" { + const dir = try checkpoint(); + const ids = prompt(history, 1); + var turn: [history + 16]u32 = undefined; + @memcpy(turn[0..history], &ids); + @memcpy(turn[history..], &prompt(16, 2)); + const refs = try withReference(dir, &ids, &turn); + var tap_nonzero = false; + for (refs.first.tap) |byte| tap_nonzero = tap_nonzero or byte != 0; + try std.testing.expect(tap_nonzero); + + const opened_once = try opened(dir, null, 1); + defer opened_once.close(opened_once.ctx); + try std.testing.expectEqual(@as(?f64, 0.5), opened_once.engine.info().decode_share); + const keepalive = opened_once.engine.keepaliveTarget() orelse return error.MissingMiniKeepalive; + keepalive.tick(keepalive.ctx); + var first = try serve(opened_once, 1, &.{ .prompt = &ids, .max_tokens = made, .drafts = false, .logprobs = 3, .history_len = ids.len }); + defer first.deinit(); + try expectTokens(&refs.first, &first); + var fresh = try serve(opened_once, 2, &.{ .prompt = &turn, .max_tokens = made, .drafts = false, .logprobs = 3, .history_len = ids.len }); + defer fresh.deinit(); + try std.testing.expectEqual(@as(?u32, 0), fresh.cached); + try expectTokens(&refs.second.?, &fresh); + var restored = try serve(opened_once, 3, &.{ .prompt = &turn, .max_tokens = made, .drafts = false, .logprobs = 3, .history_len = ids.len }); + defer restored.deinit(); + try std.testing.expectEqual(@as(?u32, ids.len), restored.cached); + try expectTokens(&refs.second.?, &restored); +} + +test "Mini Metal opt-in DSpark drafting preserves target tokens and rolls back exactly" { + const dir = try checkpoint(); + const drafter = @import("sys").getenv("TF_INKLING2_DSPARK_DIR") orelse return error.SkipZigTest; + const ids = prompt(history, 3); + var turn: [history + 16]u32 = undefined; + @memcpy(turn[0..history], &ids); + @memcpy(turn[history..], &prompt(16, 2)); + const refs = try withReference(dir, &ids, &turn); + try transactions(dir, drafter, &ids, &refs.first); + + const opened_once = try opened(dir, drafter, 1); + defer opened_once.close(opened_once.ctx); + var plain = try serve(opened_once, 10, &.{ .prompt = &ids, .max_tokens = made, .drafts = false, .logprobs = 3, .history_len = ids.len }); + defer plain.deinit(); + try expectTokens(&refs.first, &plain); + try std.testing.expectEqual(@as(u64, 0), plain.drafted); + var drafted = try serve(opened_once, 11, &.{ .prompt = &ids, .max_tokens = made, .drafts = true, .logprobs = 3, .history_len = ids.len }); + defer drafted.deinit(); + try expectTokens(&refs.first, &drafted); + try std.testing.expect(drafted.drafted > 0); + try std.testing.expect(drafted.accepted > 0); + var fresh = try serve(opened_once, 12, &.{ .prompt = &turn, .max_tokens = made, .drafts = true, .logprobs = 3, .history_len = ids.len }); + defer fresh.deinit(); + try std.testing.expectEqual(@as(?u32, 0), fresh.cached); + try expectTokens(&refs.second.?, &fresh); + var restored = try serve(opened_once, 13, &.{ .prompt = &turn, .max_tokens = made, .drafts = true, .logprobs = 3, .history_len = ids.len }); + defer restored.deinit(); + try std.testing.expectEqual(@as(?u32, ids.len), restored.cached); + try expectTokens(&refs.second.?, &restored); +} diff --git a/zig/src/families/inkling2/metal/snapshot.zig b/zig/src/families/inkling2/metal/snapshot.zig new file mode 100644 index 00000000000..14bbdf42977 --- /dev/null +++ b/zig/src/families/inkling2/metal/snapshot.zig @@ -0,0 +1,82 @@ +//! Compact retained snapshots of every live KV ring prefix and all convolution states. +const std = @import("std"); +const mtl = @import("metal"); +const state = @import("state.zig"); +const ap = @import("attention_plan.zig"); + +/// Eight global layers retain [0,at); forty sliding layers retain ring prefixes, with independent K/V pieces per visit. +pub fn bytes(at: usize) u64 { + const keys = @as(u64, 8) * @as(u64, @intCast(at)) + @as(u64, 40) * @as(u64, @intCast(@min(at, state.sliding_ring))); + return keys * @as(u64, state.kv_width) * 4 + state.conv_bytes; +} + +pub const Snap = struct { + buf: mtl.Buffer, + at: usize, + bytes: u64, + freed: bool = false, + follow: ?mtl.ResidencySet.Follow = null, + + pub fn free(s: *Snap) void { + if (!s.freed) { + s.setResident(null); + s.buf.deinit(); + s.freed = true; + } + } + + pub fn deinit(s: *Snap) void { + s.free(); + } + + pub fn setResident(s: *Snap, hook: ?mtl.ResidencySet.Follow) void { + if (s.freed) return; + if (s.follow) |f| f.leave(f.ctx, s.buf); + s.follow = hook; + if (hook) |f| f.join(f.ctx, s.buf); + } +}; + +fn encode(queue: mtl.Queue, cache: *const state.Cache, snap_buf: mtl.Buffer, snap: ?*const Snap, comptime what: []const u8) !void { + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const cb = queue.commandBuffer(); + const e = cb.blit(); + var at: usize = 0; + const len = if (snap) |image| image.at else cache.len; + for (0..state.visit_slots) |slot| { + const live = if (cache.globals[slot]) len else @min(len, cache.ring(slot)); + // A slot holds its heads one after another, each the ring's rows: a head's live rows are its first `live`. + const n = live * ap.head_dim * 2; + const head = cache.ring(slot) * ap.head_dim * 2; + if (n != 0) for ([_]usize{ cache.key_at[slot], cache.value_at[slot] }) |base| for (0..state.kv_width / ap.head_dim) |h| { + if (snap) |image| e.copy(image.buf, at, cache.kv, base + h * head, n) else e.copy(cache.kv, base + h * head, snap_buf, at, n); + at += n; + }; + } + if (snap) |image| e.copy(image.buf, at, cache.conv, 0, state.conv_bytes) else e.copy(cache.conv, 0, snap_buf, at, state.conv_bytes); + e.end(); + cb.commit(); + cb.wait(); + if (cb.failure()) |msg| { + std.log.err("inkling2_loop snapshot {s}: {s}", .{ what, msg }); + return error.GpuFailed; + } +} + +/// GPU-private snapshots retain only live global and sliding prefixes, never full-capacity allocations. +pub fn save(device: mtl.Device, queue: mtl.Queue, cache: *const state.Cache) !Snap { + if (cache.pending != null) return error.Inkling2CacheTransaction; + const size = bytes(cache.len); + const buf = try device.buffer(@intCast(size), mtl.ResourceOptions.private); + errdefer buf.deinit(); + try encode(queue, cache, buf, null, "save"); + return .{ .buf = buf, .at = cache.len, .bytes = size }; +} + +/// Restore into an empty, large-enough cache; global capacity may grow while sliding positions stay unchanged. +pub fn restore(cache: *state.Cache, queue: mtl.Queue, snap: *const Snap) !void { + if (snap.freed or cache.len != 0 or cache.pending != null or snap.at > cache.capacity or snap.bytes < bytes(snap.at)) return error.Inkling2SnapshotGeometry; + try encode(queue, cache, snap.buf, snap, "restore"); + cache.len = snap.at; +} diff --git a/zig/src/families/inkling2/metal/state.zig b/zig/src/families/inkling2/metal/state.zig new file mode 100644 index 00000000000..01c2085e4b7 --- /dev/null +++ b/zig/src/families/inkling2/metal/state.zig @@ -0,0 +1,369 @@ +//! Forty-eight independent visit caches and the GPU buffers used by one whole-loop forward. +const std = @import("std"); +const mtl = @import("metal"); +const plan = @import("../plan.zig"); +const ap = @import("attention_plan.zig"); + +pub const window_rows = 16; +pub const batch_rows = 32; +pub const prompt_rows = 64; +pub const max_rows = 64; +pub const max_segments = batch_rows; +pub const max_attention_stride = 64; +pub const hidden = 2304; +pub const feature_taps = 4; +pub const feature_row_bytes = feature_taps * hidden * 2; + +pub fn captureBytes(rows: usize) usize { + return rows * feature_row_bytes; +} +pub const query_width = 3072; +pub const kv_width = 1024; +pub const rel_width = 384; +pub const experts_per_token = 8; +pub const intermediate = 1152; +pub const vocabulary = 200058; +pub const message_entries = 48; +pub const block_slots = 4; +pub const conv_states = 4; +pub const visit_slots = 48; +pub const sliding_ring = ap.ringFor(1024, max_rows); +pub const conv_widths = [conv_states]usize{ 1024, 1024, 2304, 2304 }; +pub const conv_row_values = 1024 + 1024 + 2304 + 2304; +pub const conv_bytes = visit_slots * 3 * conv_row_values * 2; +pub const taps_bytes = visit_slots * (3 + max_rows) * conv_row_values * 2; + +pub fn globalSlots(capacity: usize) usize { + return std.mem.alignForward(usize, capacity, ap.tile_keys); +} + +pub fn globalStride(capacity: usize) usize { + return @max(@as(usize, ap.sliding_chunk / ap.tile_keys + 2), std.math.divCeil(usize, capacity, ap.global_chunk) catch unreachable); +} + +pub fn kvBytes(capacity: usize) usize { + const row_bytes = kv_width * 2; + return 40 * sliding_ring * 2 * row_bytes + 8 * globalSlots(capacity) * 2 * row_bytes; +} + +pub fn cacheBytes(capacity: usize) usize { + return kvBytes(capacity) + conv_bytes + taps_bytes + conv_bytes + vocabulary * 4; +} + +pub fn convWidth(state: usize) usize { + std.debug.assert(state < conv_states); + return conv_widths[state]; +} + +/// Values before a convolution state's rows in one slot's tightly sized layout. +pub fn convBase(state: usize, tap_rows: usize) usize { + var out: usize = 0; + for (0..state) |s| out += tap_rows * conv_widths[s]; + return out; +} + +pub fn convByteOffset(slot: usize, state: usize, rows_before: usize, tap_rows: usize) usize { + std.debug.assert(slot < visit_slots and rows_before <= tap_rows); + return (slot * tap_rows * conv_row_values + convBase(state, tap_rows) + rows_before * convWidth(state)) * 2; +} + +pub const Ref = @import("inkling2_metal_ref").Ref; + +/// Tap rows cover [start,start+rows); scratch rows carry a generation, unlike the prompt's stable last row. +pub const Tap = struct { buf: ?mtl.Buffer = null, off: usize = 0, start: u64 = 0, rows: usize = 0, gen: ?u64 = null }; + +/// Byte offset of a requested held feature range, rejecting stale and rejected rows. +pub fn featureOffset(t: Tap, start: u64, count: u32, generation: u64) !usize { + if (t.gen) |g| if (g != generation) return error.StaleInkling2Taps; + if (count == 0 or start < t.start) return error.Inkling2TapsNotHeld; + const delta = start - t.start; + const held: u64 = @intCast(t.rows); + if (delta >= held or count > held - delta) return error.Inkling2TapsNotHeld; + return t.off + @as(usize, @intCast(delta)) * feature_row_bytes; +} + +pub const Cache = struct { + kv: mtl.Buffer, + conv: mtl.Buffer, + taps: mtl.Buffer, + backup: mtl.Buffer, + logits: mtl.Buffer, + tap: Tap = .{}, + last_tap: ?mtl.Buffer = null, + key_at: [visit_slots]usize, + value_at: [visit_slots]usize, + rings: [visit_slots]u32, + globals: [visit_slots]bool, + capacity: usize, + len: usize = 0, + pending: ?usize = null, + follow: ?mtl.ResidencySet.Follow = null, + + pub fn init(device: mtl.Device, capacity: usize, schedule: *const plan.Plan) !Cache { + if (capacity == 0 or capacity > 1048576 or schedule.n_visits != visit_slots) return error.Inkling2CacheShape; + var out: Cache = .{ + .kv = undefined, + .conv = undefined, + .taps = undefined, + .backup = undefined, + .logits = undefined, + .key_at = undefined, + .value_at = undefined, + .rings = undefined, + .globals = undefined, + .capacity = capacity, + }; + var at: usize = 0; + for (0..visit_slots) |slot| { + const global = schedule.at(schedule.visit(@intCast(slot)).layer).kind == .global; + const ring_size = if (global) globalSlots(capacity) else sliding_ring; + out.globals[slot] = global; + out.rings[slot] = @intCast(ring_size); + out.key_at[slot] = at; + at += ring_size * kv_width * 2; + out.value_at[slot] = at; + at += ring_size * kv_width * 2; + } + std.debug.assert(at == kvBytes(capacity)); + out.kv = try device.buffer(@max(at, 16), mtl.ResourceOptions.private); + errdefer out.kv.deinit(); + out.conv = try device.buffer(conv_bytes, mtl.ResourceOptions.private); + errdefer out.conv.deinit(); + out.taps = try device.buffer(taps_bytes, mtl.ResourceOptions.private); + errdefer out.taps.deinit(); + out.backup = try device.buffer(conv_bytes, mtl.ResourceOptions.private); + errdefer out.backup.deinit(); + out.logits = try device.buffer(vocabulary * 4, mtl.ResourceOptions.shared); + errdefer out.logits.deinit(); + const queue = try device.queue(); + defer queue.deinit(); + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const cb = queue.commandBuffer(); + const e = cb.blit(); + e.fill(out.conv, 0, conv_bytes, 0); + e.end(); + cb.commit(); + cb.wait(); + if (cb.failure()) |msg| { + std.log.err("inkling2_loop cache clear: {s}", .{msg}); + return error.GpuFailed; + } + return out; + } + + pub fn setResident(c: *Cache, hook: ?mtl.ResidencySet.Follow) void { + const buffers = [_]mtl.Buffer{ c.kv, c.conv, c.taps, c.backup, c.logits }; + if (c.follow) |f| { + for (buffers) |b| f.leave(f.ctx, b); + if (c.last_tap) |b| f.leave(f.ctx, b); + } + c.follow = hook; + if (hook) |f| { + for (buffers) |b| f.join(f.ctx, b); + if (c.last_tap) |b| f.join(f.ctx, b); + } + } + + pub fn ring(c: *const Cache, slot: usize) usize { + return c.rings[slot]; + } + + pub fn keys(c: *const Cache, slot: usize) Ref { + return .{ .buf = c.kv, .off = c.key_at[slot] }; + } + + pub fn values(c: *const Cache, slot: usize) Ref { + return .{ .buf = c.kv, .off = c.value_at[slot] }; + } + + pub fn history(c: *const Cache, slot: usize, state: usize) Ref { + return .{ .buf = c.conv, .off = convByteOffset(slot, state, 0, 3) }; + } + + pub fn staged(c: *const Cache, slot: usize, state: usize, rows_before: usize) Ref { + return .{ .buf = c.taps, .off = convByteOffset(slot, state, rows_before, 3 + max_rows) }; + } + + pub fn attentionLayer(c: *const Cache, schedule: *const plan.Plan, slot: usize, rows: usize) ap.Layer { + std.debug.assert(rows <= max_rows); + var layer = if (schedule.at(schedule.visit(@intCast(slot)).layer).kind == .global) ap.Layer.global(@intCast(c.capacity)) else ap.Layer.sliding(1024, @intCast(rows)); + layer.ring = @intCast(c.ring(slot)); + return layer; + } + + /// Save all four pre-window three-tap histories before KV/conv speculation. + pub fn begin(c: *Cache, queue: mtl.Queue, rows: usize) !void { + if (c.pending != null or rows == 0 or rows > window_rows or c.len + rows > c.capacity) return error.Inkling2CacheTransaction; + try copyGpu(queue, c.conv, 0, c.backup, 0, conv_bytes, "begin"); + c.pending = rows; + } + + /// Commit accepted rows: staged taps select the new state; rejected KV positions are overwritten on replay. + pub fn commit(c: *Cache, queue: mtl.Queue, accepted: usize) !void { + const rows = c.pending orelse return error.Inkling2NoTransaction; + if (accepted > rows) return error.Inkling2CacheTransaction; + if (accepted < rows) { + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const cb = queue.commandBuffer(); + const e = cb.blit(); + e.copy(c.backup, 0, c.conv, 0, conv_bytes); + for (0..visit_slots) |slot| for (0..conv_states) |state| { + const bytes = 3 * convWidth(state) * 2; + e.copy(c.taps, convByteOffset(slot, state, accepted, 3 + max_rows), c.conv, convByteOffset(slot, state, 0, 3), bytes); + }; + e.end(); + cb.commit(); + cb.wait(); + if (cb.failure()) |msg| { + std.log.err("inkling2_loop cache commit: {s}", .{msg}); + return error.GpuFailed; + } + } + const start = c.len; + c.len += accepted; + if (c.tap.buf != null and c.tap.start == start) { + c.tap.rows = accepted; + } else c.tap = .{}; + c.pending = null; + } + + pub fn rollback(c: *Cache, queue: mtl.Queue) !void { + _ = c.pending orelse return error.Inkling2NoTransaction; + try copyGpu(queue, c.backup, 0, c.conv, 0, conv_bytes, "rollback"); + c.pending = null; + c.tap = .{}; + } + + pub fn deinit(c: *Cache) void { + c.setResident(null); + c.logits.deinit(); + if (c.last_tap) |b| b.deinit(); + c.backup.deinit(); + c.taps.deinit(); + c.conv.deinit(); + c.kv.deinit(); + c.* = undefined; + } +}; + +fn copyGpu(queue: mtl.Queue, from: mtl.Buffer, from_off: usize, to: mtl.Buffer, to_off: usize, bytes: usize, comptime what: []const u8) !void { + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const cb = queue.commandBuffer(); + const e = cb.blit(); + e.copy(from, from_off, to, to_off, bytes); + e.end(); + cb.commit(); + cb.wait(); + if (cb.failure()) |msg| { + std.log.err("inkling2_loop cache {s}: {s}", .{ what, msg }); + return error.GpuFailed; + } +} + +pub const fields = [_][]const u8{ + "ids", "pos", "seg_of", "segs", "p", "prelude", "blocks", "bank0", "bank1", "messages", + "partial", "ar", "gated", "mlp_ar", "mlp_gated", "q_norm", "k_norm", "v_norm", "q_raw", "k_raw", + "v_raw", "rel_raw", "sink", "gate", "k_conv", "v_conv", "q_prep", "rel_prep", "rel_tab", "part_o", + "part_ml", "att", "attn_dense", "attn_conv", "mlp_normed", "route_ids", "route_weights", "gu", "down", "mlp_out", + "mlp_conv", "logits_all", +}; + +fn sizes(rows: usize) [fields.len]usize { + const r = rows; + const h = hidden; + const q = query_width; + const kv = kv_width; + const bf = 2; + const fp = 4; + return .{ + r * 4, r * 4, r * 4, max_segments * @sizeOf(ap.Seg), r * h * bf, r * h * bf, r * block_slots * h * bf, + r * h * bf, r * h * bf, r * message_entries * h * fp, r * h * fp, 3 * r * h * fp, 3 * r * h * fp, r * h * fp, + r * h * fp, r * h * bf, r * h * bf, r * h * bf, r * q * bf, r * kv * bf, r * kv * bf, + r * rel_width * bf, r * 24 * bf, r * q * bf, r * kv * bf, r * kv * bf, r * q * bf, r * rel_width * bf, + r * 24 * ap.extent * bf, r * 24 * max_attention_stride * ap.head_dim * fp, r * 24 * max_attention_stride * 2 * fp, r * q * bf, r * h * bf, r * h * bf, r * h * bf, + r * experts_per_token * 4, r * experts_per_token * fp, r * experts_per_token * intermediate * bf, r * experts_per_token * h * bf, r * h * bf, r * h * bf, r * vocabulary * fp, + }; +} + +pub fn scratchBytes(rows: usize) usize { + var out: usize = 0; + for (sizes(rows)) |n| out += n; + return out; +} + +pub const Scratch = struct { + ids: mtl.Buffer, + pos: mtl.Buffer, + seg_of: mtl.Buffer, + segs: mtl.Buffer, + p: mtl.Buffer, + prelude: mtl.Buffer, + blocks: mtl.Buffer, + bank0: mtl.Buffer, + bank1: mtl.Buffer, + messages: mtl.Buffer, + partial: mtl.Buffer, + ar: mtl.Buffer, + gated: mtl.Buffer, + mlp_ar: mtl.Buffer, + mlp_gated: mtl.Buffer, + q_norm: mtl.Buffer, + k_norm: mtl.Buffer, + v_norm: mtl.Buffer, + q_raw: mtl.Buffer, + k_raw: mtl.Buffer, + v_raw: mtl.Buffer, + rel_raw: mtl.Buffer, + sink: mtl.Buffer, + gate: mtl.Buffer, + k_conv: mtl.Buffer, + v_conv: mtl.Buffer, + q_prep: mtl.Buffer, + rel_prep: mtl.Buffer, + rel_tab: mtl.Buffer, + part_o: mtl.Buffer, + part_ml: mtl.Buffer, + att: mtl.Buffer, + attn_dense: mtl.Buffer, + attn_conv: mtl.Buffer, + mlp_normed: mtl.Buffer, + route_ids: mtl.Buffer, + route_weights: mtl.Buffer, + gu: mtl.Buffer, + down: mtl.Buffer, + mlp_out: mtl.Buffer, + mlp_conv: mtl.Buffer, + logits_all: mtl.Buffer, + /// Opt-in DSpark features [row][tap][H], allocated by prepare_features. + taps: ?mtl.Buffer = null, + rows: usize, + + pub fn init(device: mtl.Device, rows: usize) !Scratch { + @setEvalBranchQuota(10_000); + if (rows == 0 or rows > max_rows) return error.Inkling2ScratchRows; + const ns = sizes(rows); + var s: Scratch = undefined; + var made: usize = 0; + errdefer inline for (fields, 0..) |f, i| if (i < made) @field(s, f).deinit(); + inline for (fields, 0..) |f, i| { + @field(s, f) = try device.buffer(@max(ns[i], 16), mtl.ResourceOptions.shared); + made += 1; + } + s.taps = null; + s.rows = rows; + return s; + } + + pub fn deinit(s: *Scratch) void { + inline for (fields) |f| @field(s, f).deinit(); + if (s.taps) |b| b.deinit(); + s.* = undefined; + } +}; + +comptime { + if (sliding_ring != 1088 or conv_bytes != 1916928) @compileError("Inkling cache geometry drift"); +} diff --git a/zig/src/families/inkling2/modelopt.zig b/zig/src/families/inkling2/modelopt.zig new file mode 100644 index 00000000000..7ef444cab24 --- /dev/null +++ b/zig/src/families/inkling2/modelopt.zig @@ -0,0 +1,454 @@ +//! Inkling 2 Mini's routed experts: stored NVFP4/MXFP8 codes, bf16 activations and fp32 routing. +const std = @import("std"); +const cuda = @import("cuda"); +const experts = @import("experts.zig"); +const core = @import("core"); + +pub const Format = enum(i32) { nvfp4 = 0, mxfp8 = 1 }; +pub const max_slots = 32; +const max_experts = 512; + +pub const Projection = struct { + codes: u64, + scales: u64, + amax: u64 = 0, + denominator: u64 = 0, + n: u32, + k: u32, +}; + +/// One physical layer. Loop visits share these device pointers. +pub const Layer = struct { + format: Format, + experts: u32, + w13: Projection, + w2: Projection, +}; + +pub const Weight = extern struct { + codes: u64, + scales: u64, + amax: u64, + denominator: u64, + experts: i64, + n: i64, + k: i64, + group: i32, + format: i32, + row0: i32, + row_step: i32, +}; + +pub const Kernels = struct { + mod: cuda.Module, + plan: cuda.Function, + decode: cuda.Function, + prompt: cuda.Function, + act: cuda.Function, + combine: cuda.Function, + resident: usize, + + pub fn load(d: *const cuda.Driver, sms: usize) !Kernels { + var mod = try cuda.Module.load(d, cuda.kernels.inkling2_modelopt); + errdefer mod.unload(); + const decode = try mod.function("tf_ink2moe_up"); + return .{ + .mod = mod, + .plan = try mod.function("tf_ink2moe_plan"), + .decode = decode, + .prompt = try mod.function("tf_ink2moe_prompt_up"), + .act = try mod.function("tf_ink2moe_act"), + .combine = try mod.function("tf_ink2moe_combine"), + .resident = @max(1, try decode.occupancy(128, 0)) * sms, + }; + } + + pub fn unload(k: *Kernels) void { + k.mod.unload(); + } +}; + +fn aligned(n: usize) usize { + return (n + 255) / 256 * 256; +} + +pub const Layout = struct { + gate: u64, + up: u64, + act: u64, + down: u64, + items: u64, + item_count: u64, + members: u64, + bytes: usize, +}; + +/// Reconstructs the stable intermediate addresses inside one scratch allocation. +pub fn layout(base: u64, rows: usize, slots: usize, hidden: usize, intermediate: usize) Layout { + const pairs = rows * slots; + const items_max = (pairs + 15) / 16 + @min(pairs, max_experts); + var at = base; + const take = struct { + fn f(p: *u64, bytes: usize) u64 { + const r = p.*; + p.* = r + aligned(bytes); + return r; + } + }.f; + const gate = take(&at, pairs * intermediate * 2); + const up = take(&at, pairs * intermediate * 2); + const act = take(&at, pairs * intermediate * 2); + const down = take(&at, pairs * hidden * 2); + const items = take(&at, items_max * 12); + const item_count = take(&at, 4); + const members = take(&at, pairs * 4); + return .{ .gate = gate, .up = up, .act = act, .down = down, .items = items, .item_count = item_count, .members = members, .bytes = at - base }; +} + +/// Gate, up, activation and per-expert outputs, plus the ascending-expert group plan. +pub fn scratchBytes(rows: usize, slots: usize, hidden: usize, intermediate: usize) !usize { + if (rows == 0 or rows > 2048 or slots == 0 or slots > max_slots) return error.BadExperts; + return layout(0, rows, slots, hidden, intermediate).bytes; +} + +fn i32d(v: usize) i32 { + return @intCast(v); +} + +pub fn weight(p: Projection, l: Layer, row0: i32, row_step: i32) Weight { + return .{ + .codes = p.codes, + .scales = p.scales, + .amax = p.amax, + .denominator = p.denominator, + .experts = l.experts, + .n = p.n, + .k = p.k, + .group = if (l.format == .nvfp4) 16 else 32, + .format = @backingInt(l.format), + .row0 = row0, + .row_step = row_step, + }; +} + +fn projection(s: cuda.Stream, fn_: cuda.Function, prompt: bool, resident: usize, x: u64, x_stride: usize, slots: usize, w: Weight, items: u64, item_count: u64, members: u64, out: u64, item_bound: usize) !void { + const kg: usize = @intCast(@divExact(w.k, 32)); + const outputs: usize = @intCast(if (w.row_step == 2) @divExact(w.n, 2) else w.n); + const nb = outputs / 32; + var a: cuda.Args = .{}; + a.add(x); + a.add(i32d(x_stride)); + a.add(i32d(slots)); + a.add(w); + a.add(i32d(kg)); + a.add(i32d(nb)); + for ([_]u64{ items, item_count, members, out }) |v| a.add(v); + a.add(i32d(outputs)); + a.add(@as(i32, -1)); + const bound = item_bound * nb; + const grid = if (prompt) (bound + 3) / 4 else @min((bound + 3) / 4, resident); + if (grid == 0) return; + try cuda.launch.launch(fn_, .{ .grid = .{ .x = @intCast(grid), .y = 1, .z = 1 }, .block = .{ .x = 128 } }, s, &a); +} + +/// Run one MoE layer. `pick` is row-major int32 expert IDs; routing `weights` are fp32. +pub fn run(k: *const Kernels, s: cuda.Stream, l: Layer, caps: experts.Caps, x: u64, x_stride: usize, pick: u64, weights: u64, rows: usize, slots: usize, out: u64, scratch: u64) !void { + if (rows == 0 or rows > 2048 or slots == 0 or slots > max_slots or l.experts == 0 or l.experts > max_experts) return error.BadExperts; + if (l.w13.n % 64 != 0 or l.w13.k % 32 != 0 or l.w2.n % 32 != 0 or l.w2.k % 32 != 0) return error.BadExperts; + if (l.w13.k != l.w2.n or l.w13.n / 2 != l.w2.k or x_stride < l.w13.k) return error.BadExperts; + const hidden: usize = l.w2.n; + const intermediate: usize = l.w2.k; + const pairs = rows * slots; + const b = layout(scratch, rows, slots, hidden, intermediate); + const listed = rows >= 32; + const tile: usize = if (listed) 64 else 16; + const item_bound = (pairs + tile - 1) / tile + @min(pairs, @as(usize, l.experts)); + + var g: cuda.Args = .{}; + for ([_]u64{ pick, b.items, b.members, b.item_count }) |v| g.add(v); + for ([_]usize{ rows, slots, l.experts, tile }) |v| g.add(i32d(v)); + try cuda.launch.launch(k.plan, .{ .grid = .{ .x = 1, .y = 1, .z = 1 }, .block = .{ .x = 32 } }, s, &g); + + const fn_ = if (listed) k.prompt else k.decode; + try projection(s, fn_, listed, k.resident, x, x_stride, slots, weight(l.w13, l, 0, 2), b.items, b.item_count, b.members, b.gate, item_bound); + try projection(s, fn_, listed, k.resident, x, x_stride, slots, weight(l.w13, l, 1, 2), b.items, b.item_count, b.members, b.up, item_bound); + + var aa: cuda.Args = .{}; + for ([_]u64{ b.gate, b.up, b.act }) |v| aa.add(v); + aa.add(i32d(pairs * intermediate)); + aa.add(caps.gate); + aa.add(caps.up); + try cuda.launch.launch(k.act, .{ .grid = .{ .x = @intCast((pairs * intermediate + 255) / 256), .y = 1, .z = 1 }, .block = .{ .x = 256 } }, s, &aa); + try projection(s, fn_, listed, k.resident, b.act, intermediate, 0, weight(l.w2, l, 0, 1), b.items, b.item_count, b.members, b.down, item_bound); + + var ca: cuda.Args = .{}; + for ([_]u64{ pick, weights, b.down, out }) |v| ca.add(v); + for ([_]i32{ i32d(rows), i32d(hidden), i32d(slots), i32d(l.experts) }) |v| ca.add(v); + const count = rows * hidden; + try cuda.launch.launch(k.combine, .{ .grid = .{ .x = @intCast((count + 255) / 256), .y = 1, .z = 1 }, .block = .{ .x = 256 } }, s, &ca); +} + +fn put(e: anytype, bytes: []const u8) !u64 { + const p = try e.alloc(bytes.len); + try e.arena.upload(p - e.arena.ptr, bytes); + return p; +} + +fn loadProjection(e: anytype, ck: *core.Checkpoint, prefix: []const u8, name: []const u8, format: Format, count: usize, n: usize, k: usize) !Projection { + var wb: [256]u8 = undefined; + var sb: [256]u8 = undefined; + const weight_name = try std.fmt.bufPrint(&wb, "{s}{s}_weight", .{ prefix, name }); + const scale_name = try std.fmt.bufPrint(&sb, "{s}{s}_weight_scale", .{ prefix, name }); + const w = switch (format) { + .nvfp4 => try ck.expect(weight_name, .u8, &.{ count, n, k / 2 }), + .mxfp8 => try ck.expect(weight_name, .f8_e4m3, &.{ count, n, k }), + }; + const scales = switch (format) { + .nvfp4 => try ck.expect(scale_name, .f8_e4m3, &.{ count, n, k / 16 }), + .mxfp8 => try ck.expect(scale_name, .u8, &.{ count, n, k / 32 }), + }; + var p: Projection = .{ .codes = try put(e, w.bytes), .scales = try put(e, scales.bytes), .n = @intCast(n), .k = @intCast(k) }; + if (format == .nvfp4) { + var ab: [256]u8 = undefined; + var db: [256]u8 = undefined; + const amax = try ck.expect(try std.fmt.bufPrint(&ab, "{s}{s}_weight_amax", .{ prefix, name }), .f32, &.{count}); + const denominator = try ck.expect(try std.fmt.bufPrint(&db, "{s}{s}_weight_outer_scale_denominator", .{ prefix, name }), .f32, &.{1}); + p.amax = try put(e, amax.bytes); + p.denominator = try put(e, denominator.bytes); + } + return p; +} + +/// Upload the checkpoint's two stored projections without a repack or an activation-quantization side input. +pub fn load(e: anytype, ck: *core.Checkpoint, prefix: []const u8, format: Format, count: usize, hidden: usize, intermediate: usize) !Layer { + if (count == 0 or count > max_experts or hidden % 32 != 0 or intermediate % 32 != 0) return error.BadExperts; + return .{ + .format = format, + .experts = @intCast(count), + .w13 = try loadProjection(e, ck, prefix, "w13", format, count, 2 * intermediate, hidden), + .w2 = try loadProjection(e, ck, prefix, "w2", format, count, hidden, intermediate), + }; +} + +test "Mini's expert scratch holds all tensor-core stages and the group plan" { + const bytes = try scratchBytes(2048, 8, 2304, 1152); + try std.testing.expectEqual(@as(usize, 72), @sizeOf(Weight)); + try std.testing.expect(bytes > 2048 * 8 * (3 * 1152 + 2304) * 2); + try std.testing.expectEqual(@as(i32, 0), @backingInt(Format.nvfp4)); + try std.testing.expectEqual(@as(i32, 1), @backingInt(Format.mxfp8)); + try std.testing.expectError(error.BadExperts, scratchBytes(0, 8, 2304, 1152)); +} + +/// One-member warp: A/B lanes explicit; exact rationals expose scalar/mma FP32 reduction diffs despite BF16 rounding. +const FragmentHostProbe = struct { + const expert_count = 2; + const hidden = 64; // two 32-column output blocks in the down projection + const intermediate = 64; // two gate/up blocks and two 32-input groups in down + const gate_cap = 4; + const up_cap = 25; + + const Matrix = struct { + codes: []const u8, + scales: []const u8, + n: usize, + k: usize, + + /// Checkpoint NVFP4 -> BF16, with outer scale one to isolate fragment addressing. + fn decoded(m: Matrix, e: usize, row: usize, col: usize) u16 { + const z = (e * m.n + row) * m.k + col; + const nib = (m.codes[z / 2] >> @as(u3, @intCast(4 * (col & 1)))) & 15; + const magnitude = ([8]f32{ 0, 0.5, 1, 1.5, 2, 3, 4, 6 })[nib & 7]; + const q = if ((nib & 8) != 0) -magnitude else magnitude; + const scale_code = m.scales[z / 16]; + const se = (scale_code >> 3) & 15; + const sm = scale_code & 7; + const sign: u32 = if ((scale_code & 128) != 0) 0x80000000 else 0; + const scale: f32 = if (se == 0) + @as(f32, @floatFromInt(sm)) * 0x1p-9 * (if (sign != 0) @as(f32, -1) else 1) + else + @bitCast(sign | ((@as(u32, se) + 120) << 23) | (@as(u32, sm) << 20)); + return core.bf16_round.bits(q * scale); + } + }; + + fn value(bits: u16) f32 { + return core.bf16_round.value(bits); + } + + fn fill(codes: []u8, scales: []u8, e: usize, n: usize, k: usize, one_per_row: bool) void { + const order = [16]u8{ 2, 10, 4, 13, 1, 7, 14, 0, 3, 9, 5, 12, 6, 15, 11, 8 }; + const scale_codes = [4]u8{ 0x28, 0x30, 0x2c, 0x34 }; // 1/4, 1/2, 3/8, 3/4 + for (0..n) |row| for (0..k) |col| { + const z = (e * n + row) * k + col; + const index = (7 * row + 11 * col + (row * col) % 13 + 3 * e) & 15; + var code = order[index]; + // Down's one nonzero rotates through all K positions over the two output tiles. + if (one_per_row and col != (19 * row + 7 * e) % k) code = 0; + if (one_per_row and col == (19 * row + 7 * e) % k and (code & 7) == 0) code = 2; + if ((col & 1) == 0) codes[z / 2] = code else codes[z / 2] |= code << 4; + if ((col & 15) == 0) scales[z / 16] = scale_codes[(3 * row + col / 16 + e) & 3]; + }; + } + + /// The arithmetic baseline: dequantize row-major weights and evaluate x @ W directly. + fn scalarProjection(m: Matrix, e: usize, row0: usize, row_step: usize, x: []const u16, out: []u16) void { + for (out, 0..) |*o, col| { + var sum: f32 = 0; + const row = row0 + row_step * col; + for (0..m.k) |k| sum += value(x[k]) * value(m.decoded(e, row, k)); + o.* = core.bf16_round.bits(sum); + } + } + + /// Served RT=1 (ten max): materialize uint2/uint4 A/B; m16n8k16 D gathers PTX lanes, B column 2*t+n, not lane gq. + fn fragmentProjection(m: Matrix, e: usize, row0: usize, row_step: usize, x: []const u16, out: []u16, members: usize) void { + const width = out.len / members; + for (0..width / 32) |cb| { + var acc: [32][4][4]f32 = std.mem.zeroes([32][4][4]f32); + for (0..m.k / 32) |g| { + // [lane][row half][q][uint2 member][BF16 in the member] + var a: [32][2][2][2][2]f32 = std.mem.zeroes([32][2][2][2][2]f32); + // Four ld_w uint4s: [n8 tile][lane][eight BF16 values in x,y,z,w]. + var b: [4][32][8]f32 = undefined; + for (0..32) |lane| { + const gq = lane >> 2; + const t = lane & 3; + for (0..2) |h| for (0..2) |q| for (0..2) |pair| for (0..2) |element| { + const i = gq + 8 * h; + // x = X + token*x_stride + 4*t; uint2 spans two adjacent pairs. + const col = 32 * g + 16 * q + 4 * t + 2 * pair + element; + a[lane][h][q][pair][element] = if (i < members) value(x[col]) else 0; + }; + for (0..4) |j| for (0..8) |i| { + const row = row0 + row_step * (cb * 32 + 8 * j + gq); + const col = g * 32 + 4 * t + (i & 3) + 16 * (i >> 2); + b[j][lane][i] = value(m.decoded(e, row, col)); + }; + } + for (0..2) |q| for (0..4) |j| for (0..32) |lane| { + const gq = lane >> 2; + const t = lane & 3; + for (0..2) |h| for (0..2) |n| { + const output_col = 2 * t + n; + var dot: f32 = 0; + for (0..16) |kk| { + // uint2 A/B permute mma K as 4*t+(0,1,2,3), valid only together; gather both source lanes. + const a_lane = 4 * gq + kk / 4; + const b_lane = 4 * output_col + kk / 4; + const av = a[a_lane][h][q][(kk & 3) / 2][kk & 1]; + const bv = b[j][b_lane][4 * q + (kk & 3)]; + dot += av * bv; + } + acc[lane][j][2 * h + n] += dot; + }; + }; + } + // Every valid member uses its own lane group's D row, including h=1,q=1. + for (0..32) |lane| for (0..2) |h| { + const member = (lane >> 2) + 8 * h; + if (member >= members) continue; + for (0..4) |j| for (0..2) |n| { + const col = cb * 32 + 8 * j + 2 * (lane & 3) + n; + out[member * width + col] = core.bf16_round.bits(acc[lane][j][2 * h + n]); + }; + }; + } + } + + fn reference(m13: Matrix, m2: Matrix, x: []const u16) [hidden]u16 { + var gate: [expert_count * intermediate]u16 = undefined; + var up: [expert_count * intermediate]u16 = undefined; + var act: [expert_count * intermediate]u16 = undefined; + var down: [expert_count * hidden]u16 = undefined; + var out: [hidden]u16 = undefined; + for (0..expert_count) |e| { + scalarProjection(m13, e, 0, 2, x, gate[e * intermediate ..][0..intermediate]); + scalarProjection(m13, e, 1, 2, x, up[e * intermediate ..][0..intermediate]); + for (0..intermediate) |j| { + const raw = value(gate[e * intermediate + j]); + const gc = gate_cap * @as(f32, @floatCast(std.math.tanh(raw / gate_cap))); + const uc = up_cap * @as(f32, @floatCast(std.math.tanh(value(up[e * intermediate + j]) / up_cap))); + const sigmoid: f32 = 1 / (1 + @exp(-raw)); + act[e * intermediate + j] = core.bf16_round.bits(gc * sigmoid * uc); + } + scalarProjection(m2, e, 0, 1, act[e * intermediate ..][0..intermediate], down[e * hidden ..][0..hidden]); + } + // Routing is slot 0 -> expert 1 (+3/4), slot 1 -> expert 0 (-3/8). + for (&out, 0..) |*o, col| { + var total: f32 = 0; + total += -0.375 * value(down[col]); + total += 0.75 * value(down[hidden + col]); + o.* = core.bf16_round.bits(total); + } + return out; + } + + fn model(m13: Matrix, m2: Matrix, x: []const u16) [hidden]u16 { + var gate: [expert_count * intermediate]u16 = undefined; + var up: [expert_count * intermediate]u16 = undefined; + var act: [expert_count * intermediate]u16 = undefined; + var down: [expert_count * hidden]u16 = undefined; + var out: [hidden]u16 = undefined; + for (0..expert_count) |e| { + fragmentProjection(m13, e, 0, 2, x, gate[e * intermediate ..][0..intermediate], 1); + fragmentProjection(m13, e, 1, 2, x, up[e * intermediate ..][0..intermediate], 1); + for (0..intermediate) |j| { + const raw = value(gate[e * intermediate + j]); + const gc = gate_cap * @as(f32, @floatCast(std.math.tanh(raw / gate_cap))); + const uc = up_cap * @as(f32, @floatCast(std.math.tanh(value(up[e * intermediate + j]) / up_cap))); + const sigmoid: f32 = 1 / (1 + @exp(-raw)); + act[e * intermediate + j] = core.bf16_round.bits(gc * sigmoid * uc); + } + fragmentProjection(m2, e, 0, 1, act[e * intermediate ..][0..intermediate], down[e * hidden ..][0..hidden], 1); + } + for (&out, 0..) |*o, col| { + var total: f32 = 0; + total += -0.375 * value(down[col]); + total += 0.75 * value(down[hidden + col]); + o.* = core.bf16_round.bits(total); + } + return out; + } + + fn checkMembers(m13: Matrix, x: []const u16) !void { + const members = 10; + var tensor: [members * intermediate]u16 = undefined; + var scalar: [intermediate]u16 = undefined; + scalarProjection(m13, 0, 0, 2, x, &scalar); + fragmentProjection(m13, 0, 0, 2, x, &tensor, members); + var first_difference: ?usize = null; + for (tensor, 0..) |got, i| if (got != scalar[i % intermediate]) { + first_difference = i; + break; + }; + try std.testing.expectEqual(@as(?usize, null), first_difference); + } + + fn check() !void { + var codes13: [expert_count * 2 * intermediate * hidden / 2]u8 = undefined; + var scales13: [expert_count * 2 * intermediate * hidden / 16]u8 = undefined; + var codes2: [expert_count * hidden * intermediate / 2]u8 = undefined; + var scales2: [expert_count * hidden * intermediate / 16]u8 = undefined; + for (0..expert_count) |e| { + fill(&codes13, &scales13, e, 2 * intermediate, hidden, false); + fill(&codes2, &scales2, e, hidden, intermediate, true); + } + const m13: Matrix = .{ .codes = &codes13, .scales = &scales13, .n = 2 * intermediate, .k = hidden }; + const m2: Matrix = .{ .codes = &codes2, .scales = &scales2, .n = hidden, .k = intermediate }; + var x: [hidden]u16 = undefined; + for (&x, 0..) |*v, i| v.* = core.bf16_round.bits(@as(f32, @floatFromInt(@as(i32, @intCast(i % 13)) - 6)) / 128); + const got = model(m13, m2, &x); + const want = reference(m13, m2, &x); + var first_difference: ?usize = null; + for (got, want, 0..) |g, w, i| if (g != w) { + first_difference = i; + break; + }; + try std.testing.expectEqual(@as(?usize, null), first_difference); + try checkMembers(m13, &x); + } +}; + +test "one token: m16n8k16 fragment pipeline matches independent BF16 dequantization" { + try FragmentHostProbe.check(); +} diff --git a/zig/src/families/inkling2/names.zig b/zig/src/families/inkling2/names.zig index 3c75db572bf..79890b60510 100644 --- a/zig/src/families/inkling2/names.zig +++ b/zig/src/families/inkling2/names.zig @@ -1,6 +1,6 @@ -//! Inkling 2 Small's weight map: each tensor the config implies, with dtype and shape, checked against headers. +//! Inkling 2 weight maps: each tensor the config implies, with dtype and shape, checked against headers. const std = @import("std"); -const st = @import("safetensors"); +const st = @import("core").safetensors; const config = @import("config.zig"); const plan = @import("plan.zig"); @@ -77,6 +77,19 @@ fn experts(c: *const Text, i: u32, prec: plan.Precision, sink: anytype) !void { } } +fn controllers(c: *const Text, i: u32, sink: anytype) !void { + const loop = c.loop orelse return; + if (i < loop.core_start or i >= loop.core_end) return; + const rank: u64 = loop.gate_rank; + const h: u64 = c.hidden; + const L = .{i}; + inline for (.{ "attn", "k", "mlp", "v" }) |kind| { + try put(sink, "model.llm.layers.{d}.controllers." ++ kind ++ ".down_weight", L, .bf16, &.{ rank, 2 * h }); + try put(sink, "model.llm.layers.{d}.controllers." ++ kind ++ ".forget_weight", L, .bf16, &.{ h, rank }); + try put(sink, "model.llm.layers.{d}.controllers." ++ kind ++ ".gain_weight", L, .bf16, &.{ h, rank }); + } +} + fn backbone(c: *const Text, prec: []const plan.Precision, sink: anytype) !void { const h: u64 = c.hidden; try put(sink, "model.llm.embed.weight", .{}, .bf16, &.{ c.vocab, h }); @@ -84,6 +97,11 @@ fn backbone(c: *const Text, prec: []const plan.Precision, sink: anytype) !void { try put(sink, "model.llm.norm.weight", .{}, .bf16, &.{h}); try put(sink, "model.llm.unembed.weight", .{}, .bf16, &.{ c.vocab, h }); try put(sink, "model.llm.attn_res.output_query", .{}, .f32, &.{h}); + if (c.loop) |loop| { + const rows = 2 * @as(u64, loop.core_end - loop.core_start); + try put(sink, "model.llm.middle_cycle_cross_pass_queries", .{}, .f32, &.{ rows, h }); + try put(sink, "model.llm.middle_cycle_cross_pass_kv_queries", .{}, .f32, &.{ rows, h }); + } for (0..c.layers) |k| { const i: u32 = @intCast(k); try put(sink, "model.llm.attn_res.mlp_queries.{d}", .{i}, .f32, &.{h}); @@ -93,6 +111,7 @@ fn backbone(c: *const Text, prec: []const plan.Precision, sink: anytype) !void { try put(sink, "model.llm.attn_res.attn_queries.{d}", .{i}, .f32, dims); } try attention(c, i, sink); + try controllers(c, i, sink); try put(sink, "model.llm.layers.{d}.attn_sconv.weight", .{i}, .bf16, &.{ h, 1, config.conv_taps }); try put(sink, "model.llm.layers.{d}.mlp_norm.weight", .{i}, .bf16, &.{h}); try put(sink, "model.llm.layers.{d}.mlp_sconv.weight", .{i}, .bf16, &.{ h, 1, config.conv_taps }); @@ -131,8 +150,8 @@ fn draft(m: config.Mtp, text: *const Text, sink: anytype) !void { const q: u64 = @as(u64, m.q_heads) * m.head_dim; const kv: u64 = @as(u64, m.kv_heads) * m.head_dim; const rank: u64 = m.rank; - // fuse_weight's six rows do not follow from the config, so any row count passes - try put(sink, "fuse_weight", .{}, .bf16, &.{ any, m.taps_n }); + // One fusion row per draft layer plus the Markov head, one column per target visit tap. + try put(sink, "fuse_weight", .{}, .bf16, &.{ m.layers + 1, m.taps_n }); try put(sink, "mask_embed", .{}, .bf16, &.{h}); try put(sink, "norm.weight", .{}, .bf16, &.{h}); try put(sink, "markov_head.dflare_norm.weight", .{}, .bf16, &.{h}); diff --git a/zig/src/families/inkling2/names_test.zig b/zig/src/families/inkling2/names_test.zig index c5eb215d86b..b194b435d28 100644 --- a/zig/src/families/inkling2/names_test.zig +++ b/zig/src/families/inkling2/names_test.zig @@ -1,14 +1,17 @@ -//! The weight map and layer plan against the tiny-random checkpoint's safetensors headers (fixtures fold them). +//! Weight maps and layer plans against safetensors headers (fixtures fold them). + const std = @import("std"); const config = @import("config.zig"); const config_test = @import("config_test.zig"); -const st = @import("safetensors"); +const st = @import("core").safetensors; const names = @import("names.zig"); const plan = @import("plan.zig"); const t = std.testing; const model_fixture = @embedFile("fixtures/tiny_model_header.txt"); const mtp_fixture = @embedFile("fixtures/tiny_mtp_header.txt"); +const mini_model_fixture = @embedFile("fixtures/mini_model_header.txt"); +const mini_mtp_fixture = @embedFile("fixtures/mini_mtp_header.txt"); fn byName(_: void, a: []const u8, b: []const u8) bool { return std.mem.lessThan(u8, a, b); @@ -78,6 +81,11 @@ fn load(a: std.mem.Allocator) !config.Config { return config.parse(a, config_test.tiny, &why); } +fn loadMini(a: std.mem.Allocator) !config.Config { + var why: config.Why = .{}; + return config.parse(a, config_test.mini, &why); +} + test "the folded fixtures unfold to the 404 and 84 tensors of tiny's two files, digests equal" { var arena = std.heap.ArenaAllocator.init(t.allocator); defer arena.deinit(); @@ -85,6 +93,13 @@ test "the folded fixtures unfold to the 404 and 84 tensors of tiny's two files, try t.expectEqual(@as(usize, 84), (try unfold(arena.allocator(), mtp_fixture, "inkling2-tiny-mtp")).count()); } +test "Mini's folded fixtures unfold to the 1244 and 54 tensors of its two files, digests equal" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + try t.expectEqual(@as(usize, 1244), (try unfold(arena.allocator(), mini_model_fixture, "inkling2-mini-model")).count()); + try t.expectEqual(@as(usize, 54), (try unfold(arena.allocator(), mini_mtp_fixture, "inkling2-mini-mtp")).count()); +} + test "the map names exactly tiny's backbone and vision tensors, with their dtypes and shapes" { var arena = std.heap.ArenaAllocator.init(t.allocator); defer arena.deinit(); @@ -108,6 +123,19 @@ test "the map names exactly tiny's draft head tensors" { try t.expect(r.clean()); } +test "Mini's config parses and the map names exactly its model and draft tensors" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const c = try loadMini(a); + const model = try names.check(a, &c, try unfold(a, mini_model_fixture, "inkling2-mini-model"), .model); + try t.expectEqual(@as(usize, 1244), model.expected); + try t.expect(model.clean()); + const mtp = try names.check(a, &c, try unfold(a, mini_mtp_fixture, "inkling2-mini-mtp"), .mtp); + try t.expectEqual(@as(usize, 54), mtp.expected); + try t.expect(mtp.clean()); +} + test "a missing tensor, a wrong shape, a wrong dtype and an unknown tensor are each reported by name" { var arena = std.heap.ArenaAllocator.init(t.allocator); defer arena.deinit(); @@ -177,6 +205,15 @@ test "expert precision follows each layer's tensors: NVFP4 on layers 0 to 5, MXF try t.expectError(error.ExpertFormat, names.precisions(bad, 12, &prec)); } +test "Mini's expert precision is NVFP4 on layers 0 to 19 and MXFP8 on 20 to 23" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const entries = try unfold(arena.allocator(), mini_model_fixture, "inkling2-mini-model"); + var prec: [24]plan.Precision = undefined; + try names.precisions(entries, 24, &prec); + for (prec, 0..) |p, i| try t.expectEqual(if (i < 20) plan.Precision.nvfp4 else plan.Precision.mxfp8, p); +} + test "the plan: global layers 5 and 11, blocks of six, three attention queries before each global layer" { var arena = std.heap.ArenaAllocator.init(t.allocator); defer arena.deinit(); @@ -199,6 +236,38 @@ test "the plan: global layers 5 and 11, blocks of six, three attention queries b try t.expectEqual(@as(u32, 3), p.at(11).attn_sources); try t.expectEqual(@as(u32, 3), p.final_sources); try t.expectError(error.PrecisionCount, plan.build(&c.text, prec[0..11])); + try t.expectEqual(@as(u32, 12), p.n_visits); + for (0..p.n_visits) |i| { + const v = p.visit(@intCast(i)); + try t.expectEqual(@as(u32, @intCast(i)), v.layer); + try t.expectEqual(@as(u32, @intCast(i)), v.cache_slot); + try t.expect(!v.hasMessages()); + } +} + +test "Mini's visit plan repeats only the core, gives all 48 visits private state and banks the previous pass" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const c = try loadMini(a); + var prec: [24]plan.Precision = undefined; + try names.precisions(try unfold(a, mini_model_fixture, "inkling2-mini-model"), 24, &prec); + const p = try plan.build(&c.text, &prec); + try t.expectEqual(@as(u32, 48), p.n_visits); + try t.expectEqual(@as(u32, 8), p.visitCount(.global)); + try t.expectEqual(@as(u32, 40), p.visitCount(.local)); + for (0..p.n_visits) |i| { + const v = p.visit(@intCast(i)); + const layer: u32 = if (i < 6) @intCast(i) else if (i < 42) 6 + @as(u32, @intCast((i - 6) % 12)) else @intCast(i - 24); + const pass: u32 = if (i >= 6 and i < 42) 1 + @as(u32, @intCast((i - 6) / 12)) else 0; + try t.expectEqual(layer, v.layer); + try t.expectEqual(pass, v.pass); + try t.expectEqual(@as(u32, @intCast(i)), v.cache_slot); + try t.expectEqual(pass >= 2, v.hasMessages()); + const previous: ?u32 = if (pass == 2) 6 else if (pass == 3) 18 else null; + try t.expectEqual(previous, v.previous_core_start); + } + try t.expectEqual(@as(u32, 5), p.final_sources); } /// A file's header through the core reader; the files may hold the header alone, so no data length is checked. diff --git a/zig/src/families/inkling2/plan.zig b/zig/src/families/inkling2/plan.zig index c2327d26bef..86effc0c4a3 100644 --- a/zig/src/families/inkling2/plan.zig +++ b/zig/src/families/inkling2/plan.zig @@ -19,27 +19,64 @@ pub const Layer = struct { precision: Precision, }; +pub const Visit = struct { + layer: u32, // physical weight layer; core layers repeat with the same weights + pass: u32, // zero outside the core, otherwise one-based loop pass + cache_slot: u32, // this visit's private KV and four short-convolution states + previous_core_start: ?u32, // previous pass's first visit; its two bank states feed this visit's messages + + pub fn hasMessages(v: Visit) bool { + return v.previous_core_start != null; + } +}; + pub const Plan = struct { layers: [config.max_layers]Layer, n: u32, + visits: [config.max_visits]Visit, + n_visits: u32, final_sources: u32, // the output query's states: every finished block and the last layer's output pub fn at(p: *const Plan, i: u32) *const Layer { return &p.layers[i]; } + pub fn visit(p: *const Plan, i: u32) *const Visit { + return &p.visits[i]; + } + pub fn count(p: *const Plan, kind: Kind) u32 { var k: u32 = 0; for (p.layers[0..p.n]) |l| k += @intFromBool(l.kind == kind); return k; } + + pub fn visitCount(p: *const Plan, kind: Kind) u32 { + var k: u32 = 0; + for (p.visits[0..p.n_visits]) |v| k += @intFromBool(p.layers[v.layer].kind == kind); + return k; + } }; /// The plan for a parsed config and each layer's expert precision (`prec` holds one entry per layer). +fn appendVisit(p: *Plan, c: *const config.Text, layer: u32, pass: u32) void { + const previous: ?u32 = if (c.loop) |core| + (if (pass >= 2) core.core_start + (pass - 2) * (core.core_end - core.core_start) else null) + else + null; + p.visits[p.n_visits] = .{ + .layer = layer, + .pass = pass, + .cache_slot = p.n_visits, + .previous_core_start = previous, + }; + p.n_visits += 1; +} pub fn build(c: *const config.Text, prec: []const Precision) error{PrecisionCount}!Plan { if (prec.len != c.layers) return error.PrecisionCount; var p: Plan = undefined; p.n = c.layers; + p.n_visits = 0; for (0..c.layers) |k| { const i: u32 = @intCast(k); const boundary = i % c.block == 0; @@ -58,5 +95,12 @@ pub fn build(c: *const config.Text, prec: []const Precision) error{PrecisionCoun }; } p.final_sources = (c.layers + c.block - 1) / c.block + 1; + if (c.loop) |loop| { + for (0..loop.core_start) |i| appendVisit(&p, c, @intCast(i), 0); + for (1..loop.passes + 1) |pass| for (loop.core_start..loop.core_end) |i| appendVisit(&p, c, @intCast(i), @intCast(pass)); + for (loop.core_end..c.layers) |i| appendVisit(&p, c, @intCast(i), 0); + } else { + for (0..c.layers) |i| appendVisit(&p, c, @intCast(i), 0); + } return p; } diff --git a/zig/src/families/inkling2/vision.zig b/zig/src/families/inkling2/vision.zig new file mode 100644 index 00000000000..eced25b1697 --- /dev/null +++ b/zig/src/families/inkling2/vision.zig @@ -0,0 +1,400 @@ +//! Inkling 2's vision tower on CUDA in bf16: patch embedding, 23 ViT layers with axial rotary, the 2 x 2 projector. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const image = @import("image.zig"); + +const vit = cuda.vit; + +pub const width = 1024; +pub const heads = 16; +pub const head_dim = 64; +pub const depth = 23; +pub const mlp_inter = 4096; +pub const proj_inter = 4096; +pub const hidden = 4608; // the decoder's width +const merged = image.merge * image.merge * width; // a token's four patch rows side by side +const eps: f32 = 1e-5; +const pre = "model.visual.backbone."; +/// The checkpoint names the tower reads (source shards and the pack's vision sidecar alike). +pub const prefixes = [_][]const u8{"model.visual."}; +/// Image tokens a tower's scratch covers when the caller names no limit: 1280 x 1280 pixels. +pub const default_tokens: u32 = 1024; +const attn_smem: u32 = 2 * 2 * 64 * (head_dim / 8 + 1) * 16; + +/// The family's tower kernels (inkling2/vision.cu). +pub const Kernels = struct { + mod: cuda.Module, + attention: cuda.Function, + embed: cuda.Function, + rope: cuda.Function, + scale_add: cuda.Function, + + pub fn load(d: *const cuda.Driver) !Kernels { + if (!cuda.kernels.available) return error.BuiltWithoutKernels; + var mod = try cuda.Module.load(d, cuda.kernels.inkling2_vision); + errdefer mod.unload(); + const k: Kernels = .{ + .mod = mod, + .attention = try mod.function("tf_ink2v_attention"), + .embed = try mod.function("tf_ink2v_embed"), + .rope = try mod.function("tf_ink2v_rope"), + .scale_add = try mod.function("tf_ink2v_scale_add"), + }; + try k.attention.allowDynamicShared(attn_smem); + return k; + } + + pub fn unload(k: *Kernels) void { + k.mod.unload(); + k.* = undefined; + } +}; + +/// The tower's tensors: a pack's vision.safetensors sidecar (as the release stores them), else the model's shards. +fn openTower(gpa: std.mem.Allocator, io: std.Io, dir: []const u8) !core.Checkpoint { + var buf: [std.fs.max_path_bytes]u8 = undefined; + const path = try std.fmt.bufPrint(&buf, "{s}/" ++ sidecar, .{dir}); + std.Io.Dir.cwd().access(io, path, .{}) catch return core.Checkpoint.openModelPrefixes(gpa, io, dir, &prefixes); + var ck: core.Checkpoint = .{ .gpa = gpa, .io = io }; + errdefer ck.close(); + try ck.add(dir, sidecar); + return ck; +} + +/// The file a pack carries the tower in, copied unchanged from the release's shards. +pub const sidecar = "vision.safetensors"; + +fn go(f: cuda.Function, s: cuda.Stream, grid: cuda.Dim3, threads: u32, shared: u32, a: *cuda.Args) !void { + try cuda.launch.launch(f, .{ .grid = grid, .block = .{ .x = threads }, .shared = shared }, s, a); +} + +const Layer = struct { ln1_w: u64, ln1_b: u64, qkv_w: u64, qkv_b: u64, out_w: u64, out_b: u64, ls1: u64, ln2_w: u64, ln2_b: u64, fc1_w: u64, fc1_b: u64, fc2_w: u64, fc2_b: u64, ls2: u64 }; + +/// What one image row of scratch costs: patch inputs, x/xn/att/y, qkv, mid, the f32 bias sums, tables. +const row_bytes: u64 = image.patch_width * 2 + 4 * width * 2 + 3 * width * 2 + mlp_inter * 2 + mlp_inter * 4 + 4 * 4 + 4 * 4 + 2 * image.pairs * 4; + +/// Scratch for pictures of up to `tokens` decoder tokens, plus cuBLASLt's workspace. +pub fn scratchBytes(tokens: u32) u64 { + const rows: u64 = @as(u64, tokens) * image.merge * image.merge + 1; + return rows * row_bytes + @as(u64, tokens) * proj_inter * 2 + (32 << 20); +} + +/// The tower's weights and scratch on one GPU. +pub const Tower = struct { + gpa: std.mem.Allocator, + d: *const cuda.Driver, + k: Kernels, + vk: vit.Kernels, + g: vit.Gemms, + bufs: std.ArrayList(cuda.DeviceBuffer) = .empty, + max_tokens: u32, + patch_w: u64 = 0, // [width][1200]: a native patch's row, column, channel + table: u64 = 0, // [32 * 32][width] position rows + cls: u64 = 0, + cls_pos: u64 = 0, + pre_w: u64 = 0, + pre_b: u64 = 0, + proj_in: u64 = 0, // [4096][4096], no bias + proj_out: u64 = 0, // [hidden][4096], no bias + layers: [depth]Layer = undefined, + px: u64 = 0, // bf16 [P][1200] + x: u64 = 0, // bf16 [R][width]: the residual stream (row 0 the class token) + xn: u64 = 0, + att: u64 = 0, + y: u64 = 0, + qkv: u64 = 0, // bf16 [R][3 width] + mid: u64 = 0, // bf16 [R][mlp_inter] + acc: u64 = 0, // f32 [R][mlp_inter]: a Linear's sums when cuBLASLt cannot fuse its bias + taps: u64 = 0, // u32 [P][4] + wts: u64 = 0, // f32 [P][4] + cs: u64 = 0, // f32 [R][32] + sn: u64 = 0, + p1: u64 = 0, // bf16 [T][proj_inter] + bytes: u64 = 0, + /// Layers encode runs (a parity tool stops early to read a layer's output at `x`). + layers_run: usize = depth, + + fn alloc(t: *Tower, n: usize) !u64 { + var b = try cuda.DeviceBuffer.alloc(t.d, @max(n, 256)); + errdefer b.free(); + try t.bufs.append(t.gpa, b); + t.bytes += n; + return b.ptr; + } + + fn up(t: *Tower, bytes: []const u8) !u64 { + const p = try t.alloc(bytes.len); + try t.d.check(t.d.api.cuMemcpyHtoD_v2(p, bytes.ptr, bytes.len), "cuMemcpyHtoD"); + return p; + } + + fn get(t: *Tower, ck: *core.Checkpoint, name: []const u8, dims: []const usize) !u64 { + return t.up((try ck.expect(name, .bf16, dims)).bytes); + } + + /// The tower from the checkpoint at `dir` (its model.visual.* tensors, bf16 as released), scratch for `max_tokens`. + pub fn load(gpa: std.mem.Allocator, io: std.Io, d: *const cuda.Driver, dir: []const u8, max_tokens: u32) !*Tower { + if (max_tokens == 0) return error.ImageTokens; + const t = try gpa.create(Tower); + errdefer gpa.destroy(t); + var k = try Kernels.load(d); + errdefer k.unload(); + var vk = try vit.Kernels.load(d); + errdefer vk.unload(); + t.* = .{ .gpa = gpa, .d = d, .k = k, .vk = vk, .g = try vit.Gemms.init(gpa, d), .max_tokens = max_tokens }; + errdefer { + for (t.bufs.items) |*b| b.free(); + t.bufs.deinit(gpa); + t.g.deinit(); + } + var ck = try openTower(gpa, io, dir); + defer core.checkpoint.cache.close(&ck); + t.patch_w = try t.get(&ck, pre ++ "embeddings.patch_embedding.weight", &.{ width, image.patch_width }); + t.table = try t.get(&ck, pre ++ "embeddings.position_embedding", &.{ image.grid * image.grid, width }); + t.cls = try t.get(&ck, pre ++ "embeddings.class_embedding", &.{width}); + t.cls_pos = try t.get(&ck, pre ++ "embeddings.cls_position_embedding", &.{width}); + t.pre_w = try t.get(&ck, pre ++ "ln_pre.weight", &.{width}); + t.pre_b = try t.get(&ck, pre ++ "ln_pre.bias", &.{width}); + t.proj_in = try t.get(&ck, "model.visual.proj_in.weight", &.{ proj_inter, merged }); + t.proj_out = try t.get(&ck, "model.visual.proj_out.weight", &.{ hidden, proj_inter }); + const w = try gpa.alloc(u8, 3 * width * width * 2); + defer gpa.free(w); + for (&t.layers, 0..) |*l, i| { + var nb: [128]u8 = undefined; + const at = struct { + fn f(buf: *[128]u8, li: usize, comptime rel: []const u8) ![]const u8 { + return std.fmt.bufPrint(buf, pre ++ "layers.{d}." ++ rel, .{li}); + } + }.f; + l.ln1_w = try t.get(&ck, try at(&nb, i, "ln_1.weight"), &.{width}); + l.ln1_b = try t.get(&ck, try at(&nb, i, "ln_1.bias"), &.{width}); + l.ln2_w = try t.get(&ck, try at(&nb, i, "ln_2.weight"), &.{width}); + l.ln2_b = try t.get(&ck, try at(&nb, i, "ln_2.bias"), &.{width}); + l.ls1 = try t.get(&ck, try at(&nb, i, "ls_1.gamma"), &.{width}); + l.ls2 = try t.get(&ck, try at(&nb, i, "ls_2.gamma"), &.{width}); + // q | k | v stacked by rows, their biases likewise: one Linear, heads as the attention reads them + var b: [3 * width * 2]u8 = undefined; + inline for (.{ "q", "k", "v" }, 0..) |which, j| { + const wt = try ck.expect(try at(&nb, i, "self_attn." ++ which ++ "_proj.weight"), .bf16, &.{ width, width }); + @memcpy(w[j * width * width * 2 ..][0 .. width * width * 2], wt.bytes); + const bt = try ck.expect(try at(&nb, i, "self_attn." ++ which ++ "_proj.bias"), .bf16, &.{width}); + @memcpy(b[j * width * 2 ..][0 .. width * 2], bt.bytes); + } + l.qkv_w = try t.up(w); + l.qkv_b = try t.up(&b); + l.out_w = try t.get(&ck, try at(&nb, i, "self_attn.out_proj.weight"), &.{ width, width }); + l.out_b = try t.get(&ck, try at(&nb, i, "self_attn.out_proj.bias"), &.{width}); + l.fc1_w = try t.get(&ck, try at(&nb, i, "mlp.c_fc.weight"), &.{ mlp_inter, width }); + l.fc1_b = try t.get(&ck, try at(&nb, i, "mlp.c_fc.bias"), &.{mlp_inter}); + l.fc2_w = try t.get(&ck, try at(&nb, i, "mlp.c_proj.weight"), &.{ width, mlp_inter }); + l.fc2_b = try t.get(&ck, try at(&nb, i, "mlp.c_proj.bias"), &.{width}); + } + const P: usize = @as(usize, max_tokens) * image.merge * image.merge; + const R = P + 1; + t.px = try t.alloc(P * image.patch_width * 2); + inline for (.{ "x", "xn", "att", "y" }) |f| @field(t, f) = try t.alloc(R * width * 2); + t.qkv = try t.alloc(R * 3 * width * 2); + t.mid = try t.alloc(R * mlp_inter * 2); + t.acc = try t.alloc(R * mlp_inter * 4); + t.taps = try t.alloc(P * 4 * 4); + t.wts = try t.alloc(P * 4 * 4); + t.cs = try t.alloc(R * image.pairs * 4); + t.sn = try t.alloc(R * image.pairs * 4); + t.p1 = try t.alloc(@as(usize, max_tokens) * proj_inter * 2); + return t; + } + + /// The device bytes load takes for `dir`: the tower's tensors as stored, scratch and workspace for `max_tokens`. + pub fn bytesFor(gpa: std.mem.Allocator, io: std.Io, dir: []const u8, max_tokens: u32) !u64 { + var ck = try openTower(gpa, io, dir); + defer core.checkpoint.cache.close(&ck); + var total: u64 = scratchBytes(max_tokens); + for (ck.files.items) |*f| for (f.names.keys()) |name| { + total += f.get(name).?.bytes.len; + }; + return total; + } + + pub fn deinit(t: *Tower) void { + for (t.bufs.items) |*b| b.free(); + t.bufs.deinit(t.gpa); + t.g.deinit(); + t.vk.unload(); + t.k.unload(); + t.gpa.destroy(t); + } + + fn upload(t: *Tower, dst: u64, bytes: []const u8) !void { + try t.d.check(t.d.api.cuMemcpyHtoD_v2(dst, bytes.ptr, bytes.len), "cuMemcpyHtoD"); + } + + /// The host tables of one picture (patch rows, position taps, rotary; rotary off only for a planted control). + fn stage(t: *Tower, s: cuda.Stream, p: image.Prepared, rope: bool) !void { + const P = image.patchCount(p); + const rows = try t.gpa.alloc(u16, P * image.patch_width); + defer t.gpa.free(rows); + const taps = try t.gpa.alloc(u32, P * 4); + defer t.gpa.free(taps); + const wts = try t.gpa.alloc(f32, P * 4); + defer t.gpa.free(wts); + const cs = try t.gpa.alloc(f32, (P + 1) * image.pairs); + defer t.gpa.free(cs); + const sn = try t.gpa.alloc(f32, (P + 1) * image.pairs); + defer t.gpa.free(sn); + image.patchRows(p, rows); + image.positionTaps(p, taps, wts); + image.rotary(p, cs, sn, rope); + try s.synchronize(); // the previous picture's kernels may still read the tables + try t.upload(t.px, std.mem.sliceAsBytes(rows)); + try t.upload(t.taps, std.mem.sliceAsBytes(taps)); + try t.upload(t.wts, std.mem.sliceAsBytes(wts)); + try t.upload(t.cs, std.mem.sliceAsBytes(cs)); + try t.upload(t.sn, std.mem.sliceAsBytes(sn)); + } + + /// One picture to its tokens' rows at `out` (bf16 [tokens][hidden]): what replaces its placeholders' embeddings. + pub fn encode(t: *Tower, s: cuda.Stream, p: image.Prepared, out: u64) !void { + return t.encodeWith(s, p, out, true); + } + + pub fn encodeWith(t: *Tower, s: cuda.Stream, p: image.Prepared, out: u64, rope: bool) !void { + const T: usize = p.tokens(); + if (T == 0 or p.pixels.len != T * image.side * image.side * 3) return error.ImageGrid; + if (T > t.max_tokens) return error.ImageTooLarge; + try t.stage(s, p, rope); + const P = image.patchCount(p); + const R = P + 1; + try t.g.run(s, t.px, t.patch_w, t.y, P, width, image.patch_width, .bf16); + var a: cuda.Args = .{}; + for ([_]u64{ t.y, t.table, t.taps, t.wts, t.cls, t.cls_pos, t.xn }) |v| a.add(v); + try go(t.k.embed, s, .{ .x = @intCast(R) }, 256, 0, &a); + try t.vk.layerNorm(s, t.xn, t.pre_w, t.pre_b, t.x, R, width, eps); + for (t.layers[0..@min(t.layers_run, depth)]) |l| try t.layer(s, l, R); + if (t.layers_run < depth) return; + // the projector: each token's four patch rows (merge order, after the class row) as one 4096-wide row + try t.g.run(s, t.x + width * 2, t.proj_in, t.p1, T, proj_inter, merged, .bf16); + try t.vk.pointwise(s, t.p1, null, t.p1, T * proj_inter, .gelu); + try t.g.run(s, t.p1, t.proj_out, out, T, hidden, proj_inter, .bf16); + } + + fn layer(t: *Tower, s: cuda.Stream, l: Layer, R: usize) !void { + try t.vk.layerNorm(s, t.x, l.ln1_w, l.ln1_b, t.xn, R, width, eps); + try vit.linear(&t.g, &t.vk, s, t.acc, t.xn, l.qkv_w, l.qkv_b, t.qkv, R, 3 * width, width); + var a: cuda.Args = .{}; + for ([_]u64{ t.qkv, t.cs, t.sn }) |v| a.add(v); + try go(t.k.rope, s, .{ .x = @intCast(R) }, 256, 0, &a); + var b: cuda.Args = .{}; + b.add(t.qkv); + b.add(t.att); + b.add(@as(c_int, @intCast(R))); + b.add(@as(c_int, heads)); + b.add(@as(f32, 1.0 / @sqrt(@as(f32, head_dim)))); + try go(t.k.attention, s, .{ .x = @intCast((R + 127) / 128), .y = heads }, 256, attn_smem, &b); + try vit.linear(&t.g, &t.vk, s, t.acc, t.att, l.out_w, l.out_b, t.y, R, width, width); + try t.scaleAdd(s, l.ls1, R); + try t.vk.layerNorm(s, t.x, l.ln2_w, l.ln2_b, t.xn, R, width, eps); + try vit.linearAct(&t.g, &t.vk, s, t.acc, t.xn, l.fc1_w, l.fc1_b, t.mid, R, mlp_inter, width, null, t.mid, .gelu); + try vit.linear(&t.g, &t.vk, s, t.acc, t.mid, l.fc2_w, l.fc2_b, t.y, R, width, mlp_inter); + try t.scaleAdd(s, l.ls2, R); + } + + /// x = bf16(x + bf16(gamma y)), the layer scale of torch's `residual + lambda * h`. + fn scaleAdd(t: *Tower, s: cuda.Stream, gamma: u64, R: usize) !void { + const n = R * width; + var a: cuda.Args = .{}; + for ([_]u64{ t.x, t.y, gamma }) |v| a.add(v); + a.add(@as(i64, @intCast(n))); + try go(t.k.scale_add, s, .{ .x = @intCast((n + 255) / 256) }, 256, 0, &a); + } +}; + +/// Prompt rows [at, at + n) take image rows [row, row + n) (rows of the encoded pictures, in prompt order). +pub const Span = struct { at: u32, n: u32, row: u32 }; + +/// The placeholder runs of a prompt's ids: each maximal run of image_token is one picture's rows, in order. +pub fn spans(a: std.mem.Allocator, ids: []const u32) ![]Span { + var out: std.ArrayList(Span) = .empty; + errdefer out.deinit(a); + var row: u32 = 0; + var i: usize = 0; + while (i < ids.len) : (i += 1) { + if (ids[i] != image.image_token) continue; + const at = i; + while (i < ids.len and ids[i] == image.image_token) i += 1; + try out.append(a, .{ .at = @intCast(at), .n = @intCast(i - at), .row = row }); + row += @intCast(i - at); + } + return out.toOwnedSlice(a); +} + +/// The prompt's placeholders must equal the encoded pictures' rows, as transformers' get_placeholder_mask requires. +pub fn check(list: []const Span, pictures: []const image.Prepared) !void { + var want: usize = 0; + for (pictures) |p| want += p.tokens(); + var have: usize = 0; + for (list) |sp| have += sp.n; + if (have != want) return error.ImagePlaceholders; +} + +/// One copy into a pass: pass row `dst` on takes image rows from `src`, `n` of them. +pub const Copy = struct { dst: u32, src: u32, n: u32 }; + +/// The part of a placeholder run inside a pass over prompt positions [lo, hi), if any. +pub fn cut(sp: Span, lo: usize, hi: usize) ?Copy { + const a = @max(lo, sp.at); + const b = @min(hi, sp.at + sp.n); + if (a >= b) return null; + return .{ .dst = @intCast(a - lo), .src = @intCast(sp.row + (a - sp.at)), .n = @intCast(b - a) }; +} + +/// After the normed embedding, a pass's rows at positions [lo, hi) (bf16 at `x`) take their image rows (at `rows`). +pub fn splice(d: *const cuda.Driver, s: cuda.Stream, rows: u64, list: []const Span, lo: usize, hi: usize, x: u64) !void { + for (list) |sp| { + const c = cut(sp, lo, hi) orelse continue; + const row: u64 = hidden * 2; + try d.check(d.api.cuMemcpyDtoDAsync_v2(x + c.dst * row, rows + c.src * row, c.n * row, s.handle), "cuMemcpyDtoDAsync"); + } +} + +test "placeholder runs map to picture rows in prompt order" { + const a = std.testing.allocator; + const t = image.image_token; + const got = try spans(a, &.{ 1, t, t, t, 2, 3, t, t, 4 }); + defer a.free(got); + try std.testing.expectEqual(@as(usize, 2), got.len); + try std.testing.expectEqual(Span{ .at = 1, .n = 3, .row = 0 }, got[0]); + try std.testing.expectEqual(Span{ .at = 6, .n = 2, .row = 3 }, got[1]); + var px: [2 * image.side * image.side * 3]f32 = undefined; + const two = [_]image.Prepared{ .{ .pixels = &px, .rows = 1, .cols = 3 }, .{ .pixels = &px, .rows = 1, .cols = 2 } }; + try check(got, &two); + try std.testing.expectError(error.ImagePlaceholders, check(got, two[0..1])); +} + +test "chunked passes give every placeholder the row masked_scatter gives it" { + const a = std.testing.allocator; + const t = image.image_token; + const ids = [_]u32{ 7, t, t, t, t, t, 9, 9, t, 4, t, t, t, t, t, t, t, 3, 2 }; + const list = try spans(a, &ids); + defer a.free(list); + for ([_]usize{ 1, 2, 3, 5, 8, ids.len }) |chunk| { + var got: [ids.len]i32 = @splat(-1); + var lo: usize = 0; + while (lo < ids.len) : (lo += chunk) { + const hi = @min(ids.len, lo + chunk); + for (list) |sp| if (cut(sp, lo, hi)) |c| for (0..c.n) |i| { + got[lo + c.dst + i] = @intCast(c.src + i); + }; + } + var next: i32 = 0; // masked_scatter: the k-th placeholder in the prompt takes feature row k + for (ids, got) |id, g| { + try std.testing.expectEqual(if (id == t) next else -1, g); + if (id == t) next += 1; + } + } +} + +test "scratch for the default limit stays under 256 MiB" { + try std.testing.expect(scratchBytes(default_tokens) < 256 << 20); + try std.testing.expectEqual(@as(u32, 36864), attn_smem); +} diff --git a/zig/src/families/lfm2/weights.zig b/zig/src/families/lfm2/weights.zig index 394b6ad2b61..9631d7e0a81 100644 --- a/zig/src/families/lfm2/weights.zig +++ b/zig/src/families/lfm2/weights.zig @@ -84,8 +84,8 @@ pub const Weights = struct { bytes: u64, memory: cuda.DeviceBuffer, - /// `dir`'s model.safetensors on the device as `plan` lays it out; a refusal is logged with its reason. - pub fn load(gpa: std.mem.Allocator, io: std.Io, d: *const cuda.Driver, dir: []const u8, cfg: *const Config) !Weights { + /// `dir`'s model.safetensors on the device as `plan` lays it out (the tower only with `tower`); refusals logged. + pub fn load(gpa: std.mem.Allocator, io: std.Io, d: *const cuda.Driver, dir: []const u8, cfg: *const Config, tower: bool) !Weights { const path = try std.fs.path.join(gpa, &.{ dir, "model.safetensors" }); defer gpa.free(path); var file = try core.safetensors.File.open(gpa, io, path); @@ -94,7 +94,7 @@ pub const Weights = struct { file.close(io); } var problem: []const u8 = ""; - var p = try plan(gpa, cfg, &file.names, &problem) orelse { + var p = try plan(gpa, cfg, &file.names, tower, &problem) orelse { defer gpa.free(problem); std.log.err("{s}", .{problem}); return error.UnreadableLfm2Checkpoint; @@ -158,9 +158,9 @@ fn shift(s: anytype, base: u64) void { const language = [_][]const u8{ "model.language_model.", "model.layers.", "model.embed" }; const projector = [_][]const u8{"model.multi_modal_projector."}; -/// Where every tensor `cfg` reads goes (host only), or null with `problem` (from `a`) saying why the header is refused. -pub fn plan(a: std.mem.Allocator, cfg: *const Config, header: *const Header, problem: *[]const u8) !?Plan { - var p: Planner = .{ .a = a, .header = header, .problem = problem }; +/// Where every tensor `cfg` reads goes (host only; its tower only with `tower`), or null with `problem` saying why not. +pub fn plan(a: std.mem.Allocator, cfg: *const Config, header: *const Header, tower: bool, problem: *[]const u8) !?Plan { + var p: Planner = .{ .a = a, .header = header, .problem = problem, .tower = tower }; p.build(cfg) catch |e| { p.out.deinit(a); return if (e == error.Refused) null else e; @@ -172,6 +172,7 @@ const Planner = struct { a: std.mem.Allocator, header: *const Header, problem: *[]const u8, + tower: bool, out: Plan = .{}, part: enum { language, vision } = .language, prefix_buf: [128]u8 = undefined, @@ -208,7 +209,9 @@ const Planner = struct { } } try p.unread(&language, p.out.pieces.items.len, "language tensor(s) the LFM2 kernels do not read"); - if (cfg.vision) |v| p.out.vision = try p.vision(cfg, v); + if (cfg.vision) |v| if (p.tower) { + p.out.vision = try p.vision(cfg, v); + }; } fn vision(p: *Planner, cfg: *const Config, v: config.Vision) !VisionWeights { @@ -413,7 +416,7 @@ test "plan stacks w1;w3 and q;k;v rows back to back on 256-byte boundaries, what const a = arena.allocator(); const header = try fakeHeader(a, &tiny_tensors, null); var problem: []const u8 = ""; - const p = (try plan(a, &tiny, &header, &problem)).?; + const p = (try plan(a, &tiny, &header, true, &problem)).?; try std.testing.expectEqual(tiny_tensors.len, p.pieces.items.len); try std.testing.expectEqualSlices(u64, &.{ 0, 256 }, &.{ p.embed, p.norm }); const conv, const attention = .{ p.layers[0], p.layers[1] }; @@ -456,18 +459,33 @@ test "a text-only checkpoint's model. names plan without a vision tower" { var cfg = tiny; cfg.vision = null; var problem: []const u8 = ""; - const p = (try plan(a, &cfg, &try fakeHeader(a, text.items, null), &problem)).?; + const p = (try plan(a, &cfg, &try fakeHeader(a, text.items, null), true, &problem)).?; try std.testing.expect(p.pieces.items.len == 21 and p.vision == null); try std.testing.expectEqualStrings("model.embed_tokens.weight", p.pieces.items[0].name); } +test "without --vision a VL checkpoint plans its language model alone: no tower byte is read or placed" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const header = try fakeHeader(a, &tiny_tensors, null); + var problem: []const u8 = ""; + const full = (try plan(a, &tiny, &header, true, &problem)).?; + const text = (try plan(a, &tiny, &header, false, &problem)).?; + try std.testing.expect(text.vision == null and text.pieces.items.len == 21); + for (text.pieces.items, full.pieces.items[0..21]) |t, f| try std.testing.expectEqualDeep(f, t); + try std.testing.expectEqual(full.pieces.items[20].dst + full.pieces.items[20].len, text.bytes); + // a tower the header lacks is no refusal without --vision: the planner never looks + try std.testing.expect(try plan(a, &tiny, &try fakeHeader(a, tiny_tensors[0..21], null), false, &problem) != null); +} + /// The refusal `plan` gives for the tiny tensors less `drop`, plus `add`, with `f32_name` stored as f32. fn refusal(a: std.mem.Allocator, drop: ?[]const u8, add: ?Fake, f32_name: ?[]const u8) ![]const u8 { var tensors: std.ArrayList(Fake) = .empty; for (tiny_tensors) |t| if (drop == null or !std.mem.eql(u8, t[0], drop.?)) try tensors.append(a, t); if (add) |t| try tensors.append(a, t); var problem: []const u8 = ""; - try std.testing.expect(try plan(a, &tiny, &try fakeHeader(a, tensors.items, f32_name), &problem) == null); + try std.testing.expect(try plan(a, &tiny, &try fakeHeader(a, tensors.items, f32_name), true, &problem) == null); return problem; } @@ -492,8 +510,8 @@ test "plan refuses a missing, mistyped, misshapen or unread tensor by name" { try std.testing.expectEqualStrings("1 projector tensor(s) the LFM2-VL tower does not read: " ++ projector_norm, try refusal(a, null, .{ projector_norm, &.{16} }, null)); try std.testing.expectEqualStrings("layer_norm.weight is stored as f32, and the LFM2-VL tower reads bf16 weights", try refusal(a, null, .{ projector_norm, &.{16} }, projector_norm)); var problem: []const u8 = ""; - try std.testing.expect(try plan(a, &tiny, &try fakeHeader(a, tiny_tensors[21..], null), &problem) == null); + try std.testing.expect(try plan(a, &tiny, &try fakeHeader(a, tiny_tensors[21..], null), true, &problem) == null); try std.testing.expectEqualStrings("no language-model tensors in this checkpoint (a complete d1 checkpoint is needed)", problem); - try std.testing.expect(try plan(a, &tiny, &try fakeHeader(a, tiny_tensors[0..21], null), &problem) == null); + try std.testing.expect(try plan(a, &tiny, &try fakeHeader(a, tiny_tensors[0..21], null), true, &problem) == null); try std.testing.expectEqualStrings("no vision tower tensors in this checkpoint, which its config's vision_config needs", problem); } diff --git a/zig/src/families/ling/cpu.zig b/zig/src/families/ling/cpu.zig new file mode 100644 index 00000000000..054b3d196ee --- /dev/null +++ b/zig/src/families/ling/cpu.zig @@ -0,0 +1,26 @@ +//! Ling CPU exports: the checked GGUF reader, its exact Q4_K, Q6_K and Q5_0 projections and the exact forward. +pub const rows = @import("cpu_rows.zig"); +pub const gguf = @import("cpu_gguf.zig"); +pub const gguf_rows = @import("cpu_gguf_rows.zig"); +pub const State = @import("cpu_state.zig").State; +pub const forward = @import("cpu_forward.zig"); +/// The exact forward over the published GGUF. +pub const Gguf = forward.Forward(gguf.File); +test { + _ = rows; + _ = State; + _ = @import("cpu_gguf.zig"); + _ = @import("cpu_gguf_refusal_test.zig"); + _ = @import("cpu_gguf_views.zig"); + _ = @import("cpu_gguf_values.zig"); + _ = @import("cpu_gguf_rows.zig"); + _ = @import("cpu_gguf_rows_test.zig"); + _ = @import("cpu_gguf_pool_test.zig"); + _ = @import("cpu_mla.zig"); + _ = @import("cpu_forward_test.zig"); + _ = @import("gguf_names.zig"); + @import("std").testing.refAllDecls(gguf.File); + @import("std").testing.refAllDecls(Gguf); + @import("std").testing.refAllDecls(Gguf.Session); + _ = &@import("cpu_gguf_config.zig").tiny; +} diff --git a/zig/src/families/ling/cpu_forward.zig b/zig/src/families/ling/cpu_forward.zig new file mode 100644 index 00000000000..fed7e19621c --- /dev/null +++ b/zig/src/families/ling/cpu_forward.zig @@ -0,0 +1,295 @@ +//! Exact CPU Ling forward over a weight source, with persistent KDA/MLA state and F32 arithmetic; no GPU. +const std = @import("std"); +const config = @import("config.zig"); +const op = @import("cpu_rows.zig"); +const kda = @import("kda.zig"); +const mla = @import("cpu_mla.zig"); +const route = @import("route.zig"); +const State = @import("cpu_state.zig").State; + +pub const Result = struct { + arena: std.heap.ArenaAllocator, + logits: []f32, + picks: []u32, + pub fn deinit(self: *Result) void { + self.arena.deinit(); + } +}; + +/// Borrowed output slices owned by a Session and valid until the next step, reset, or deinit. +pub const StepView = struct { + logits: []f32, + picks: []u32, +}; + +/// A source gives values, project, embed and optionally projectExperts; KDA rates are stored as exp(A_log). +pub fn Forward(comptime Source: type) type { + return struct { + const Run = struct { + a: std.mem.Allocator, + source: *Source, + c: *const config.Config, + threads: usize, + count: usize, + state: ?*State = null, + + fn name(self: Run, p: []const u8, n: []const u8) ![]const u8 { + return std.mem.concat(self.a, u8, &.{ p, n }); + } + + fn alloc(self: Run, width: usize) ![]f32 { + return self.a.alloc(f32, self.count * width); + } + + fn values(self: Run, p: []const u8, n: []const u8, shape: []const usize) ![]f32 { + return self.source.values(self.a, try self.name(p, n), shape); + } + + fn linearInto(self: Run, p: []const u8, n: []const u8, x: []const f32, y: []f32, width: usize, outputs: usize, rounded: bool) !void { + try self.source.project(try self.name(p, n), x, y, self.count, width, outputs, rounded, self.threads); + } + + fn linear(self: Run, p: []const u8, n: []const u8, x: []const f32, width: usize, outputs: usize, rounded: bool) ![]f32 { + const y = try self.alloc(outputs); + try self.linearInto(p, n, x, y, width, outputs, rounded); + return y; + } + + fn norm(self: Run, x: []const f32, p: []const u8, n: []const u8, width: usize) ![]f32 { + const w = try self.values(p, n, &.{width}); + const y = try self.alloc(width); + try op.norm(x, w, y, self.count, width, self.c.eps); + return y; + } + + fn mlp(self: Run, x: []const f32, p: []const u8, inter: usize, limit: f32) ![]f32 { + const hidden = self.c.hidden; + const g = try self.linear(p, "gate_proj.weight", x, hidden, inter, true); + const u = try self.linear(p, "up_proj.weight", x, hidden, inter, true); + for (g, u) |*v, *up| { + var silu = op.round(v.* * op.sigmoid(v.*)); + if (limit > 0) { + silu = @min(silu, limit); + up.* = std.math.clamp(up.*, -limit, limit); + } + v.* = op.round(silu * up.*); + } + return self.linear(p, "down_proj.weight", g, inter, hidden, true); + } + + fn kdaForward(self: Run, x: []const f32, p: []const u8, layer: usize) ![]f32 { + const c = self.c; + const W = c.kda_heads * 128; + const q = try self.linear(p, "q_proj.weight", x, c.hidden, W, true); + const k = try self.linear(p, "k_proj.weight", x, c.hidden, W, true); + const v = try self.linear(p, "v_proj.weight", x, c.hidden, W, true); + const proj = try self.alloc(3 * W); + for (0..self.count) |t| { + @memcpy(proj[t * 3 * W ..][0..W], q[t * W ..][0..W]); + @memcpy(proj[t * 3 * W + W ..][0..W], k[t * W ..][0..W]); + @memcpy(proj[t * 3 * W + 2 * W ..][0..W], v[t * W ..][0..W]); + } + const f = try self.linear(p, "f_proj.weight", x, c.hidden, W, true); + const b = try self.linear(p, "b_proj.weight", x, c.hidden, c.kda_heads, true); + const g = try self.linear(p, "g_proj.weight", x, c.hidden, W, true); + const cq = try self.values(p, "q_conv1d.weight", &.{ W, 1, 4 }); + const ck = try self.values(p, "k_conv1d.weight", &.{ W, 1, 4 }); + const cv = try self.values(p, "v_conv1d.weight", &.{ W, 1, 4 }); + const rate = try self.values(p, "A_log", &.{c.kda_heads}); + const dt = try self.values(p, "dt_bias", &.{W}); + const on = try self.values(p, "o_norm.weight", &.{128}); + const state = if (self.state) |s| s.layers[layer].kda.matrix else try self.a.alloc(f32, c.kda_heads * 128 * 128); + const history = if (self.state) |s| s.layers[layer].kda.history else try self.a.alloc([3]f32, 3 * W); + if (self.state == null) { + @memset(state, 0); + @memset(history, .{ 0, 0, 0 }); + } + const y = try self.alloc(W); + const shape = kda.Shape{ .heads = c.kda_heads, .lower_bound = c.lower_bound, .stored_rate = true, .eps = c.eps }; + try kda.mixState(y, state, proj, f, b, g, cq, ck, cv, rate, dt, on, shape, @intCast(self.count), history); + return self.linear(p, "o_proj.weight", y, W, c.hidden, true); + } + + fn mlaForward(self: Run, x: []const f32, p: []const u8, layer: usize) ![]f32 { + const c = self.c; + const qa = try self.linear(p, "q_a_proj.weight", x, c.hidden, c.q_lora, true); + const qn = try self.norm(qa, p, "q_a_layernorm.weight", c.q_lora); + const q = try self.linear(p, "q_b_proj.weight", qn, c.q_lora, c.mla_heads * 192, true); + const kv = try self.linear(p, "kv_a_proj_with_mqa.weight", x, c.hidden, 576, true); + const g = try self.linear(p, "g_proj.weight", x, c.hidden, c.mla_heads, true); + const w = try self.values(p, "kv_a_layernorm.weight", &.{512}); + const b = try self.values(p, "kv_b_proj.weight", &.{ c.mla_heads * 256, 512 }); + const y = try self.alloc(c.mla_heads * 128); + const shape = mla.Shape{ .heads = c.mla_heads, .eps = c.eps, .theta = c.rope_theta }; + if (self.state) |state| { + try mla.append(self.a, y, q, kv, w, b, g, shape, @intCast(self.count), &state.layers[layer].mla); + } else try mla.mix(self.a, y, q, kv, w, b, g, shape, @intCast(self.count), 0); + return self.linear(p, "dense.weight", y, c.mla_heads * 128, c.hidden, true); + } + + fn moe(self: Run, x: []const f32, p: []const u8, layer: usize, picks: []u32) ![]f32 { + const c = self.c; + const scores = try self.linear(p, "gate.weight", x, c.hidden, c.experts, false); + const bias = try self.values(p, "gate.expert_bias", &.{c.experts}); + const shape = route.Shape{ .experts = c.experts, .topk = c.topk, .n_group = c.n_group, .topk_group = c.topk_group, .scale = c.routed_scale }; + try route.checkBias(bias, shape); + const out = try self.alloc(c.hidden); + @memset(out, 0); + for (0..self.count) |t| { + var selected: [route.max_topk]route.Pick = undefined; + const n = route.selectF32(scores[t * c.experts ..][0..c.experts], bias, selected[0..c.topk], shape); + if (n != c.topk) return error.CpuRoute; + for (selected[0..n], 0..) |pick, j| picks[t * c.topk + j] = pick.id; + if (comptime @hasDecl(Source, "projectExperts")) if (self.threads > 1) { + var ids: [route.max_topk]u32 = undefined; + for (selected[0..n], 0..) |pick, j| ids[j] = pick.id; + const ys = try self.a.alloc(f32, n * c.hidden); + try self.source.projectExperts(p, ids[0..n], x[t * c.hidden ..][0..c.hidden], ys, c.hidden, c.moe_inter, c.expert_limit[layer], self.threads); + for (selected[0..n], 0..) |pick, j| { + for (out[t * c.hidden ..][0..c.hidden], ys[j * c.hidden ..][0..c.hidden]) |*o, v| o.* += v * pick.wt; + } + continue; + }; + const one = Run{ .a = self.a, .source = self.source, .c = c, .threads = self.threads, .count = 1 }; + for (selected[0..n]) |pick| { + const prefix = try std.fmt.allocPrint(self.a, "{s}experts.{d}.", .{ p, pick.id }); + const y = try one.mlp(x[t * c.hidden ..][0..c.hidden], prefix, c.moe_inter, c.expert_limit[layer]); + for (out[t * c.hidden ..][0..c.hidden], y) |*o, v| o.* += v * pick.wt; + } + } + const shared = try self.mlp(x, try self.name(p, "shared_experts."), c.shared_inter, c.shared_limit[layer]); + for (out, shared) |*o, v| o.* = op.round(op.round(o.*) + v); + return out; + } + }; + + const LogitsMode = enum { all, last, none }; + + fn runInto(work_a: std.mem.Allocator, source: *Source, c: *const config.Config, ids: []const u32, threads: usize, state: ?*State, logits_mode: LogitsMode, logits: []f32, picks: []u32) !void { + const r = Run{ .a = work_a, .source = source, .c = c, .threads = threads, .count = ids.len, .state = state }; + const x = try r.alloc(c.hidden); + try source.embed(ids, x); + for (0..c.layers) |i| { + const p = try std.fmt.allocPrint(r.a, "model.layers.{d}.", .{i}); + const h = try r.norm(x, p, "input_layernorm.weight", c.hidden); + const att = try r.name(p, "attention."); + const d = if (c.kind(@intCast(i)) == .kda) try r.kdaForward(h, att, i) else try r.mlaForward(h, att, i); + for (x, d) |*v, z| v.* = op.round(v.* + z); + const n = try r.norm(x, p, "post_attention_layernorm.weight", c.hidden); + const m = try r.name(p, "mlp."); + const y = if (i < c.dense_layers) try r.mlp(n, m, c.dense_inter, 0) else try r.moe(n, m, i, picks[(i - c.dense_layers) * ids.len * c.topk ..][0 .. ids.len * c.topk]); + for (x, y) |*v, z| v.* = op.round(v.* + z); + } + switch (logits_mode) { + .none => {}, + .all => { + const final = try r.norm(x, "model.", "norm.weight", c.hidden); + try r.linearInto("", "lm_head.weight", final, logits, c.hidden, c.vocab, false); + for (logits) |v| if (!std.math.isFinite(v)) return error.NonfiniteCpuLogits; + }, + .last => { + const last_x = x[(ids.len - 1) * c.hidden ..][0..c.hidden]; + const one = Run{ .a = r.a, .source = r.source, .c = r.c, .threads = r.threads, .count = 1, .state = r.state }; + const final = try one.norm(last_x, "model.", "norm.weight", c.hidden); + try one.linearInto("", "lm_head.weight", final, logits, c.hidden, c.vocab, false); + for (logits) |v| if (!std.math.isFinite(v)) return error.NonfiniteCpuLogits; + }, + } + } + + /// One to eight rows through every layer; without a state each call starts from position 0. + pub fn run(a: std.mem.Allocator, source: *Source, c: *const config.Config, ids: []const u32, threads: usize, state: ?*State, scratch: ?*std.heap.ArenaAllocator) !Result { + if (ids.len == 0 or ids.len > 8) return error.CpuRows; + if (threads == 0 or threads > 8) return error.CpuThreadCount; + var arena = std.heap.ArenaAllocator.init(a); + errdefer arena.deinit(); + const out_a = arena.allocator(); + const work_a = if (scratch) |s| s.allocator() else out_a; + const picks = try out_a.alloc(u32, (c.layers - c.dense_layers) * ids.len * c.topk); + const logits = try out_a.alloc(f32, ids.len * c.vocab); + try runInto(work_a, source, c, ids, threads, state, .all, logits, picks); + return .{ .arena = arena, .logits = logits, .picks = picks }; + } + + /// Serialized stream; a failed layer poisons its partial state until reset rather than reusing it silently. + pub const Session = struct { + a: std.mem.Allocator, + source: *Source, + config: config.Config, + state: State, + scratch: std.heap.ArenaAllocator, + logits_buf: []f32 = &.{}, + picks_buf: []u32 = &.{}, + threads: usize, + + pub fn init(a: std.mem.Allocator, source: *Source, c: config.Config, capacity: u32, threads: usize) !Session { + if (threads == 0 or threads > 8) return error.CpuThreadCount; + return .{ .a = a, .source = source, .config = c, .state = try State.init(a, c, capacity), .scratch = std.heap.ArenaAllocator.init(a), .threads = threads }; + } + + pub fn run(self: *Session, a: std.mem.Allocator, ids: []const u32) !Result { + if (self.state.poisoned) return error.CpuPoisonedState; + if (ids.len == 0 or ids.len > 8) return error.CpuRows; + if (ids.len > self.state.capacity - self.state.position) return error.CpuContextCapacity; + for (ids) |id| if (id >= self.config.vocab) return error.InvalidToken; + _ = self.scratch.reset(.retain_capacity); + errdefer self.state.poisoned = true; + const result = try Forward(Source).run(a, self.source, &self.config, ids, self.threads, &self.state, &self.scratch); + self.state.position += @intCast(ids.len); + return result; + } + + fn stepMode(self: *Session, ids: []const u32, mode: LogitsMode) !StepView { + if (self.state.poisoned) return error.CpuPoisonedState; + if (ids.len == 0 or ids.len > 8) return error.CpuRows; + if (ids.len > self.state.capacity - self.state.position) return error.CpuContextCapacity; + for (ids) |id| if (id >= self.config.vocab) return error.InvalidToken; + const need_logits: usize = switch (mode) { + .none => 0, + .last => self.config.vocab, + .all => ids.len * self.config.vocab, + }; + if (self.logits_buf.len < need_logits) { + const next_logits = try self.a.alloc(f32, need_logits); + if (self.logits_buf.len > 0) self.a.free(self.logits_buf); + self.logits_buf = next_logits; + } + const need_picks = (self.config.layers - self.config.dense_layers) * ids.len * self.config.topk; + if (self.picks_buf.len < need_picks) { + const next_picks = try self.a.alloc(u32, need_picks); + if (self.picks_buf.len > 0) self.a.free(self.picks_buf); + self.picks_buf = next_picks; + } + _ = self.scratch.reset(.retain_capacity); + errdefer self.state.poisoned = true; + const logits: []f32 = if (need_logits > 0) self.logits_buf[0..need_logits] else &.{}; + const picks = self.picks_buf[0..need_picks]; + try runInto(self.scratch.allocator(), self.source, &self.config, ids, self.threads, &self.state, mode, logits, picks); + self.state.position += @intCast(ids.len); + return .{ .logits = logits, .picks = picks }; + } + + /// Runs a step into session-owned output buffers reused across tokens without per-step allocation. + pub fn step(self: *Session, ids: []const u32) !StepView { + return self.stepMode(ids, .all); + } + + /// Advances state over a prompt chunk, skipping discarded lm_head projections on non-final prompt rows. + pub fn prefillChunk(self: *Session, ids: []const u32, want_last_logits: bool) !StepView { + return self.stepMode(ids, if (want_last_logits) .last else .none); + } + + pub fn reset(self: *Session) void { + self.state.reset(); + _ = self.scratch.reset(.retain_capacity); + } + + pub fn deinit(self: *Session) void { + if (self.logits_buf.len > 0) self.a.free(self.logits_buf); + if (self.picks_buf.len > 0) self.a.free(self.picks_buf); + self.scratch.deinit(); + self.state.deinit(); + } + }; + }; +} diff --git a/zig/src/families/ling/cpu_forward_test.zig b/zig/src/families/ling/cpu_forward_test.zig new file mode 100644 index 00000000000..46825ecf556 --- /dev/null +++ b/zig/src/families/ling/cpu_forward_test.zig @@ -0,0 +1,221 @@ +//! Exact CPU forward seams on a small synthetic F32 source: whole, chunked and one-row prompts, threads and reset. +const std = @import("std"); +const config = @import("config.zig"); +const op = @import("cpu_rows.zig"); +const g = @import("core").gguf; +const Pool = @import("cpu_gguf_pool.zig").Pool; +const Forward = @import("cpu_forward.zig").Forward(Synthetic); + +/// Deterministic F32 tensors keyed by name; KDA rates are positive, as the GGUF stores them. +const Synthetic = struct { + arena: std.heap.ArenaAllocator, + made: std.StringHashMapUnmanaged([]f32) = .empty, + hidden: usize, + pool: ?*Pool = null, + + fn deinit(s: *Synthetic) void { + if (s.pool) |p| p.destroy(); + s.arena.deinit(); + } + + /// Workers that dispatch even these small matrices, so every projection and expert row crosses threads. + fn workers(s: *Synthetic, threads: usize) !*Pool { + if (s.pool) |p| { + if (p.threads == threads) return p; + p.destroy(); + s.pool = null; + } + const p = try Pool.create(std.testing.allocator, std.testing.io, threads); + p.min_weights = 0; + s.pool = p; + return p; + } + + fn matrix(s: *Synthetic, name: []const u8, width: usize, n: usize) !g.Tensor { + const w = std.mem.sliceAsBytes(try s.tensor(name, n * width)); + return .{ .name = name, .kind = .f32, .rank = 2, .shape = .{ width, n, 1, 1 }, .offset = 0, .len = w.len, .bytes = w }; + } + + fn tensor(s: *Synthetic, name: []const u8, n: usize) ![]f32 { + if (s.made.get(name)) |v| { + if (v.len != n) return error.SyntheticShape; + return v; + } + const a = s.arena.allocator(); + const v = try a.alloc(f32, n); + var rng = std.Random.DefaultPrng.init(std.hash.Wyhash.hash(7, name)); + const r = rng.random(); + const norm = std.mem.endsWith(u8, name, "norm.weight"); + const rate = std.mem.endsWith(u8, name, "A_log"); + for (v) |*x| { + const u = r.float(f32) * 2 - 1; + x.* = if (norm) 1 + u / 8 else if (rate) 0.5 + (u + 1) / 2 else u / 8; + } + try s.made.put(a, try a.dupe(u8, name), v); + return v; + } + + pub fn values(s: *Synthetic, a: std.mem.Allocator, name: []const u8, shape: []const usize) ![]f32 { + var n: usize = 1; + for (shape) |d| n *= d; + return a.dupe(f32, try s.tensor(name, n)); + } + + pub fn project(s: *Synthetic, name: []const u8, x: []const f32, y: []f32, rows: usize, width: usize, outputs: usize, rounded: bool, threads: usize) !void { + const t = try s.matrix(name, width, outputs); + if (threads > 1) return (try s.workers(threads)).project(t, x, y, rows, rounded); + const w = try s.tensor(name, outputs * width); + const dense = op.Tensor{ .dtype = .f32, .rank = 2, .shape = .{ outputs, width, 1, 1, 1 }, .bytes = std.mem.sliceAsBytes(w) }; + try op.projectOn(dense, x, y, rows, width, outputs, rounded, 1); + } + + pub fn projectExperts(s: *Synthetic, prefix: []const u8, ids: []const u32, x: []const f32, out: []f32, hidden: usize, inter: usize, limit: f32, threads: usize) !void { + var list: [16]@import("cpu_gguf_pool.zig").Expert = undefined; + var buf: [128]u8 = undefined; + for (ids, 0..) |id, j| list[j] = .{ + .gate = try s.matrix(try s.arena.allocator().dupe(u8, try std.fmt.bufPrint(&buf, "{s}experts.{d}.gate_proj.weight", .{ prefix, id })), hidden, inter), + .up = try s.matrix(try s.arena.allocator().dupe(u8, try std.fmt.bufPrint(&buf, "{s}experts.{d}.up_proj.weight", .{ prefix, id })), hidden, inter), + .down = try s.matrix(try s.arena.allocator().dupe(u8, try std.fmt.bufPrint(&buf, "{s}experts.{d}.down_proj.weight", .{ prefix, id })), inter, hidden), + .out = out[j * hidden ..].ptr, + }; + try (try s.workers(threads)).experts(list[0..ids.len], x, hidden, inter, limit); + } + + pub fn embed(s: *Synthetic, ids: []const u32, out: []f32) !void { + const table = try s.tensor("model.word_embeddings.weight", tiny().vocab * s.hidden); + for (ids, 0..) |id, row| @memcpy(out[row * s.hidden ..][0..s.hidden], table[id * s.hidden ..][0..s.hidden]); + } +}; + +fn tiny() config.Config { + var c = std.mem.zeroes(config.Config); + c.hidden = 64; + c.layers = 4; + c.vocab = 48; + c.eps = 0.000001; + c.rope_theta = 6000000; + c.rope_dim = 64; + c.rope_style = .gptj; + c.group = 4; + c.dense_layers = 1; + c.dense_inter = 32; + c.kda_heads = 1; + c.kda_dim = 128; + c.conv = 4; + c.lower_bound = -5; + c.mla_heads = 2; + c.q_lora = 32; + c.kv_lora = 512; + c.nope = 128; + c.v_dim = 128; + c.head_gate = true; + c.experts = 8; + c.topk = 2; + c.n_group = 4; + c.topk_group = 2; + c.routed_scale = 2.5; + c.norm_topk = true; + c.expert_bias = true; + c.moe_inter = 16; + c.shared_inter = 16; + c.eos_n = 1; + return c; +} + +fn last(r: @import("cpu_forward.zig").Result, vocab: usize) []const u8 { + return std.mem.sliceAsBytes(r.logits[r.logits.len - vocab ..]); +} + +test "whole, chunked and one-row prompts give the same bytes at 1, 2, 3, 4 and 8 threads, and reset replays them" { + const a = std.testing.allocator; + var source = Synthetic{ .arena = std.heap.ArenaAllocator.init(a), .hidden = 64 }; + defer source.deinit(); + const c = tiny(); + const ids = [_]u32{ 3, 17, 5, 40, 9, 22 }; + var whole = try Forward.Session.init(a, &source, c, 16, 1); + defer whole.deinit(); + var want = try whole.run(a, &ids); + defer want.deinit(); + for (want.picks) |p| try std.testing.expect(p < c.experts); + var stateless = try Forward.run(a, &source, &c, &ids, 1, null, null); + defer stateless.deinit(); + try std.testing.expectEqualSlices(u8, std.mem.sliceAsBytes(want.logits), std.mem.sliceAsBytes(stateless.logits)); + for ([_]usize{ 1, 2, 3, 4, 8 }) |threads| for ([_]usize{ 1, 2, 4 }) |chunk| { + var s = try Forward.Session.init(a, &source, c, 16, threads); + defer s.deinit(); + for (0..2) |_| { + var at: usize = 0; + while (at < ids.len) { + const end = @min(ids.len, at + chunk); + var got = try s.run(a, ids[at..end]); + defer got.deinit(); + at = end; + if (at == ids.len) try std.testing.expectEqualSlices(u8, last(want, c.vocab), last(got, c.vocab)); + } + s.reset(); + } + }; +} + +test "a session refuses tokens past the vocabulary and past its capacity without advancing" { + const a = std.testing.allocator; + var source = Synthetic{ .arena = std.heap.ArenaAllocator.init(a), .hidden = 64 }; + defer source.deinit(); + var s = try Forward.Session.init(a, &source, tiny(), 2, 1); + defer s.deinit(); + try std.testing.expectError(error.InvalidToken, s.run(a, &.{48})); + try std.testing.expectError(error.CpuContextCapacity, s.run(a, &.{ 1, 2, 3 })); + try std.testing.expectEqual(@as(u32, 0), s.state.position); + var r = try s.run(a, &.{ 1, 2 }); + r.deinit(); + try std.testing.expectEqual(@as(u32, 2), s.state.position); +} + +test "session step reuses its output buffers and matches run byte for byte" { + const a = std.testing.allocator; + var source = Synthetic{ .arena = std.heap.ArenaAllocator.init(a), .hidden = 64 }; + defer source.deinit(); + const c = tiny(); + var ref = try Forward.Session.init(a, &source, c, 16, 1); + defer ref.deinit(); + var reuse = try Forward.Session.init(a, &source, c, 16, 1); + defer reuse.deinit(); + const chunks = [_][]const u32{ &.{ 3, 17, 5 }, &.{40}, &.{9}, &.{22} }; + var first_logits_ptr: ?[*]f32 = null; + var first_picks_ptr: ?[*]u32 = null; + for (chunks) |chunk| { + var want = try ref.run(a, chunk); + defer want.deinit(); + const got = try reuse.step(chunk); + try std.testing.expectEqualSlices(u8, std.mem.sliceAsBytes(want.logits), std.mem.sliceAsBytes(got.logits)); + try std.testing.expectEqualSlices(u32, want.picks, got.picks); + if (first_logits_ptr) |p| try std.testing.expectEqual(p, got.logits.ptr) else first_logits_ptr = got.logits.ptr; + if (first_picks_ptr) |p| try std.testing.expectEqual(p, got.picks.ptr) else first_picks_ptr = got.picks.ptr; + } +} + +test "session prefillChunk skips non-final logits while matching run state and final logits byte for byte" { + const a = std.testing.allocator; + var source = Synthetic{ .arena = std.heap.ArenaAllocator.init(a), .hidden = 64 }; + defer source.deinit(); + const c = tiny(); + var ref = try Forward.Session.init(a, &source, c, 16, 1); + defer ref.deinit(); + var fast = try Forward.Session.init(a, &source, c, 16, 1); + defer fast.deinit(); + + var r1 = try ref.run(a, &.{ 3, 17, 5 }); + defer r1.deinit(); + var r2 = try ref.run(a, &.{ 40, 9, 22 }); + defer r2.deinit(); + + const p1 = try fast.prefillChunk(&.{ 3, 17, 5 }, false); + try std.testing.expectEqual(@as(usize, 0), p1.logits.len); + const p2 = try fast.prefillChunk(&.{ 40, 9, 22 }, true); + try std.testing.expectEqualSlices(u8, last(r2, c.vocab), std.mem.sliceAsBytes(p2.logits)); + + var d_ref = try ref.run(a, &.{11}); + defer d_ref.deinit(); + const d_fast = try fast.step(&.{11}); + try std.testing.expectEqualSlices(u8, std.mem.sliceAsBytes(d_ref.logits), std.mem.sliceAsBytes(d_fast.logits)); +} diff --git a/zig/src/families/ling/cpu_gguf.zig b/zig/src/families/ling/cpu_gguf.zig new file mode 100644 index 00000000000..fdf4027c0ee --- /dev/null +++ b/zig/src/families/ling/cpu_gguf.zig @@ -0,0 +1,192 @@ +//! Checked borrowed GGUF source views for Ling-3.0-tiny on CPU; not a serving admission path. +const std = @import("std"); +const g = @import("core").gguf; +pub const reference = @import("core").gguf_source_reference; +pub const views = @import("cpu_gguf_views.zig"); +pub const names = @import("gguf_names.zig"); + +fn integer(d: *const g.Document, key: []const u8, expected: u64) !void { + const v = d.get(key) orelse return error.MissingLingGgufMetadata; + const n: u64 = switch (v) { + .uint32 => |x| x, + .uint64 => |x| x, + else => return error.BadLingGgufMetadata, + }; + if (n != expected) return error.UnsupportedLingGgufGeometry; +} +pub fn validateMetadata(d: *const g.Document) !void { + const arch = d.get("general.architecture") orelse return error.MissingLingGgufMetadata; + if (arch != .string or !std.mem.eql(u8, arch.string, "bailingmoe3")) return error.UnsupportedLingGgufArchitecture; + const checks = .{ .{ "block_count", 24 }, .{ "embedding_length", 1536 }, .{ "feed_forward_length", 4608 }, .{ "attention.head_count", 16 }, .{ "expert_count", 128 }, .{ "expert_used_count", 8 }, .{ "expert_group_count", 8 }, .{ "expert_group_used_count", 4 }, .{ "expert_gating_func", 2 }, .{ "vocab_size", 157184 }, .{ "ssm.conv_kernel", 4 }, .{ "kda.head_dim", 128 }, .{ "attention.q_lora_rank", 256 }, .{ "attention.kv_lora_rank", 512 }, .{ "rope.dimension_count", 64 }, .{ "expert_feed_forward_length", 512 }, .{ "expert_shared_feed_forward_length", 512 }, .{ "leading_dense_block_count", 1 } }; + inline for (checks) |check| try integer(d, "bailingmoe3." ++ check[0], check[1]); + try integer(d, "bailingmoe3.context_length", 131072); + try integer(d, "bailingmoe3.attention.key_length_mla", 192); + try integer(d, "bailingmoe3.attention.value_length_mla", 128); + try integer(d, "bailingmoe3.expert_shared_count", 1); + inline for (.{ .{ "rope.freq_base", 6000000.0 }, .{ "attention.layer_norm_rms_epsilon", 0.000001 }, .{ "kda.gate_lower_bound", -5.0 }, .{ "expert_weights_scale", 2.5 } }) |check| { + const value = d.get("bailingmoe3." ++ check[0]) orelse return error.MissingLingGgufMetadata; + const actual = try value.float(); + if (!std.math.isFinite(actual) or @as(f32, @floatCast(actual)) != @as(f32, check[1])) return error.UnsupportedLingGgufGeometry; + } + inline for (.{ "kda.safe_gate", "expert_weights_norm" }) |key| { + const value = d.get("bailingmoe3." ++ key) orelse return error.MissingLingGgufMetadata; + if (value != .boolean or !value.boolean) return error.UnsupportedLingGgufGeometry; + } + const kv = d.get("bailingmoe3.attention.head_count_kv") orelse return error.MissingLingGgufMetadata; + if (kv != .array or kv.array.len != 24) return error.UnsupportedLingGgufGeometry; + var it = kv.array.iterator(); + for (0..24) |layer| { + const value = (try it.next()) orelse return error.UnsupportedLingGgufGeometry; + if (try value.unsigned() != @as(u64, if (layer % 4 == 3) 1 else 0)) return error.UnsupportedLingGgufGeometry; + } + const tokens = d.get("tokenizer.ggml.tokens") orelse return error.MissingLingGgufMetadata; + if (tokens != .array or tokens.array.kind != .string or tokens.array.len != 157184) return error.UnsupportedLingGgufGeometry; + if (d.get("bailingmoe3.swiglu_clamp_exp") != null or d.get("bailingmoe3.swiglu_clamp_shexp") != null) return error.UnsupportedLingGgufClamp; +} +pub fn checkTensor(t: g.Tensor, n: names.Name) !void { + if (t.rank != n.rank or !std.mem.eql(u64, t.shape[0..t.rank], n.dims[0..n.rank])) return error.BadLingGgufTensorShape; + switch (n.role) { + .positive_exp_decay => { + if (t.kind != .f32 or t.bytes.len != 64) return error.UnsupportedLingGgufSmallType; + for (0..16) |i| { + const rate: f32 = @bitCast(std.mem.readInt(u32, t.bytes[i * 4 ..][0..4], .little)); + if (!std.math.isFinite(rate) or rate <= 0) return error.BadLingGgufDecay; + } + }, + .vector, .convolution => if (t.kind != .f32) return error.UnsupportedLingGgufSmallType, + else => switch (t.kind) { + .f32, .q4_k, .q6_k, .q5_0 => {}, + else => return error.UnsupportedLingGgufQuant, + }, + } +} +pub fn validateTensors(d: *const g.Document, plan: []const names.Name) !void { + for (plan) |name| try checkTensor(d.getTensor(name.source) orelse return error.MissingLingGgufTensor, name); + if (d.tensors.len != plan.len) return error.UnexpectedLingGgufTensor; +} +pub const File = struct { + const CachedValue = struct { data: []f32, rank: u8, shape: [4]usize }; + source: g.File, + arena: std.heap.ArenaAllocator, + plan: []names.Name, + joined_mla: [24]?[]f32 = @splat(null), + cached_values: std.StringHashMapUnmanaged(CachedValue) = .empty, + validated: std.StringHashMapUnmanaged(void) = .empty, + io: std.Io, + pool: ?*Pool = null, + pub const Pool = @import("cpu_gguf_pool.zig").Pool; + pub fn open(a: std.mem.Allocator, io: std.Io, path: []const u8) !File { + var source = try g.File.open(a, io, path, .{}); + errdefer source.close(io); + try validateMetadata(&source.document); + var arena = std.heap.ArenaAllocator.init(a); + errdefer arena.deinit(); + const plan = try names.tiny(arena.allocator()); + try validateTensors(&source.document, plan); + return .{ .source = source, .arena = arena, .plan = plan, .io = io }; + } + pub fn config(f: *const File) !@import("config.zig").Config { + return @import("cpu_gguf_config.zig").tiny(&f.source.document); + } + pub fn view(f: *const File, key: []const u8) !views.View { + return views.resolve(&f.source.document, f.plan, key); + } + pub fn values(f: *File, _: std.mem.Allocator, key: []const u8, shape: []const usize) ![]f32 { + if (f.cached_values.get(key)) |entry| { + if (shape.len != entry.rank or !std.mem.eql(usize, shape, entry.shape[0..entry.rank])) return error.BadLingGgufTensorShape; + return entry.data; + } + const v = try f.view(key); + const data: []f32 = if (v.name.role != .mla_key_transposed) + try @import("cpu_gguf_values.zig").small(f.arena.allocator(), v, shape) + else blk: { + if (!std.mem.eql(usize, shape, &.{ 4096, 512 })) return error.BadLingGgufTensorShape; + const prefix = "model.layers."; + if (!std.mem.startsWith(u8, key, prefix)) return error.MissingLingGgufTensor; + const tail = key[prefix.len..]; + const end = std.mem.indexOfScalar(u8, tail, '.') orelse return error.MissingLingGgufTensor; + const layer = try std.fmt.parseInt(usize, tail[0..end], 10); + if (layer >= 24 or layer % 4 != 3) return error.BadLingGgufTensorShape; + if (f.joined_mla[layer] == null) { + var buf: [64]u8 = undefined; + const name = try std.fmt.bufPrint(&buf, "blk.{d}.attn_v_b.weight", .{layer}); + const value = f.source.document.getTensor(name) orelse return error.MissingLingGgufTensor; + f.joined_mla[layer] = try @import("cpu_gguf_values.zig").joinMla(f.arena.child_allocator, v.tensor, value); + } + break :blk f.joined_mla[layer].?; + }; + if (shape.len <= 4) { + var stored_shape: [4]usize = @splat(0); + @memcpy(stored_shape[0..shape.len], shape); + const dup = try f.arena.allocator().dupe(u8, key); + try f.cached_values.put(f.arena.allocator(), dup, .{ + .data = data, + .rank = @intCast(shape.len), + .shape = stored_shape, + }); + } + return data; + } + /// A matrix view whose quantized scales have been validated once. + fn matrix(f: *File, key: []const u8, width: usize, n: usize) !g.Tensor { + const v = try f.view(key); + if (v.tensor.rank != 2 or v.tensor.shape[0] != width or v.tensor.shape[1] != n) return error.BadLingGgufMatrix; + if (v.tensor.kind != .f32 and !f.validated.contains(key)) { + try g.affine.validate(v.tensor.kind, v.tensor.bytes); + const dup = try f.arena.allocator().dupe(u8, key); + try f.validated.put(f.arena.allocator(), dup, {}); + } + return v.tensor; + } + /// The persistent workers for this thread count, made on first use and replaced when the count changes. + pub fn workers(f: *File, threads: usize) !*Pool { + if (f.pool) |p| { + if (p.threads == threads) return p; + p.destroy(); + f.pool = null; + } + f.pool = try Pool.create(f.arena.child_allocator, f.io, threads); + return f.pool.?; + } + pub fn project(f: *File, key: []const u8, input: []const f32, output: []f32, count: usize, width: usize, n: usize, rounded: bool, threads: usize) !void { + const t = try f.matrix(key, width, n); + if (threads > 1) return (try f.workers(threads)).project(t, input, output, count, rounded); + try @import("cpu_gguf_rows.zig").projectValidatedOn(t, input, output, count, rounded, 1); + } + /// One row's routed experts on the workers; `out` holds each result, `hidden` values apiece, in `ids` order. + pub fn projectExperts(f: *File, prefix: []const u8, ids: []const u32, x: []const f32, out: []f32, hidden: usize, inter: usize, limit: f32, threads: usize) !void { + var list: [16]@import("cpu_gguf_pool.zig").Expert = undefined; + if (ids.len > list.len or out.len != ids.len * hidden) return error.BadLingGgufMatrix; + var buf: [128]u8 = undefined; + for (ids, 0..) |id, j| list[j] = .{ + .gate = try f.matrix(try std.fmt.bufPrint(&buf, "{s}experts.{d}.gate_proj.weight", .{ prefix, id }), hidden, inter), + .up = try f.matrix(try std.fmt.bufPrint(&buf, "{s}experts.{d}.up_proj.weight", .{ prefix, id }), hidden, inter), + .down = try f.matrix(try std.fmt.bufPrint(&buf, "{s}experts.{d}.down_proj.weight", .{ prefix, id }), inter, hidden), + .out = out[j * hidden ..].ptr, + }; + try (try f.workers(threads)).experts(list[0..ids.len], x, hidden, inter, limit); + } + pub fn embed(f: *const File, ids: []const u32, output: []f32) !void { + try @import("cpu_gguf_values.zig").embedding(&f.source.document, ids, output); + } + pub fn close(f: *File, io: std.Io) void { + if (f.pool) |p| p.destroy(); + for (f.joined_mla) |entry| if (entry) |data| f.arena.child_allocator.free(data); + f.arena.deinit(); + f.source.close(io); + f.* = undefined; + } +}; + +test "Ling GGUF source views refuse wrong dimensions and quantized small tensors" { + const n = names.Name{ .source = "matrix", .native = "matrix", .role = .matrix, .rank = 2, .dims = .{ 1536, 512, 1 } }; + var t = g.Tensor{ .name = "matrix", .kind = .q4_k, .rank = 2, .shape = .{ 1536, 512, 1, 1 }, .offset = 0, .len = 0 }; + try checkTensor(t, n); + t.shape[1] = 511; + try std.testing.expectError(error.BadLingGgufTensorShape, checkTensor(t, n)); + const gain = names.Name{ .source = "gain", .native = "gain", .role = .vector, .rank = 1, .dims = .{ 1536, 1, 1 } }; + t = .{ .name = "gain", .kind = .q4_k, .rank = 1, .shape = .{ 1536, 1, 1, 1 }, .offset = 0, .len = 0 }; + try std.testing.expectError(error.UnsupportedLingGgufSmallType, checkTensor(t, gain)); + t.kind = .f32; + try checkTensor(t, gain); +} diff --git a/zig/src/families/ling/cpu_gguf_config.zig b/zig/src/families/ling/cpu_gguf_config.zig new file mode 100644 index 00000000000..20a4a641d56 --- /dev/null +++ b/zig/src/families/ling/cpu_gguf_config.zig @@ -0,0 +1,56 @@ +//! Fixed tiny geometry admitted by cpu_gguf; GGUF tensor kinds remain separate from safetensors dispatch. +const std = @import("std"); +const g = @import("core").gguf; +const cfg = @import("config.zig"); +pub fn tiny(d: *const g.Document) !cfg.Config { + var c = std.mem.zeroes(cfg.Config); + c.hidden = 1536; + c.layers = 24; + c.vocab = 157184; + c.eps = 0.000001; + c.rope_theta = 6000000; + c.rope_dim = 64; + c.rope_style = .gptj; + c.group = 4; + c.dense_layers = 1; + c.dense_inter = 4608; + c.kda_heads = 16; + c.kda_dim = 128; + c.conv = 4; + c.lower_bound = -5; + c.mla_heads = 16; + c.q_lora = 256; + c.kv_lora = 512; + c.nope = 128; + c.v_dim = 128; + c.head_gate = true; + c.experts = 128; + c.topk = 8; + c.n_group = 8; + c.topk_group = 4; + c.routed_scale = 2.5; + c.norm_topk = true; + c.expert_bias = true; + c.moe_inter = 512; + c.shared_inter = 512; + // GGUF bypasses safetensors quant dispatch; BF16-point activation nodes are unchanged. + c.quant = .bf16; + inline for (.{ "eos_token_id", "eot_token_id", "eom_token_id" }) |key| { + if (d.get("tokenizer.ggml." ++ key)) |v| { + const id = try v.unsigned(); + if (id >= c.vocab) return error.BadLingGgufToken; + const token: u32 = @intCast(id); + if (std.mem.indexOfScalar(u32, c.eos[0..c.eos_n], token) == null) { + c.eos[c.eos_n] = token; + c.eos_n += 1; + } + } + } + if (c.eos_n == 0) return error.MissingLingGgufEos; + if (d.get("tokenizer.ggml.bos_token_id")) |v| { + const id = try v.unsigned(); + if (id >= c.vocab) return error.BadLingGgufToken; + c.bos = @intCast(id); + } + return c; +} diff --git a/zig/src/families/ling/cpu_gguf_lanes.zig b/zig/src/families/ling/cpu_gguf_lanes.zig new file mode 100644 index 00000000000..0cf6fee62a5 --- /dev/null +++ b/zig/src/families/ling/cpu_gguf_lanes.zig @@ -0,0 +1,44 @@ +//! Lane helpers shared by the exact GGUF block kernels; each is a plain load, shuffle or widening with no rounding. +const std = @import("std"); + +pub inline fn readU16(p: [*]const u8) u16 { + return std.mem.readInt(u16, p[0..2], .little); +} + +pub inline fn readF16(p: [*]const u8) f32 { + return @floatCast(@as(f16, @bitCast(readU16(p)))); +} + +pub inline fn loadF32x8(p: [*]const f32) @Vector(8, f32) { + return @as(*align(1) const [8]f32, @ptrCast(p)).*; +} + +pub inline fn lowHalf(v: @Vector(16, u8)) @Vector(8, u8) { + return @shuffle(u8, v, undefined, [8]i32{ 0, 1, 2, 3, 4, 5, 6, 7 }); +} + +pub inline fn highHalf(v: @Vector(16, u8)) @Vector(8, u8) { + return @shuffle(u8, v, undefined, [8]i32{ 8, 9, 10, 11, 12, 13, 14, 15 }); +} + +pub inline fn u8x8ToF32x8(v: @Vector(8, u8)) @Vector(8, f32) { + return @floatFromInt(@as(@Vector(8, u32), v)); +} + +pub inline fn lowHalfI8(v: @Vector(16, i8)) @Vector(8, i8) { + return @shuffle(i8, v, undefined, [8]i32{ 0, 1, 2, 3, 4, 5, 6, 7 }); +} + +pub inline fn highHalfI8(v: @Vector(16, i8)) @Vector(8, i8) { + return @shuffle(i8, v, undefined, [8]i32{ 8, 9, 10, 11, 12, 13, 14, 15 }); +} + +pub inline fn i8x8ToF32x8(v: @Vector(8, i8)) @Vector(8, f32) { + return @floatFromInt(@as(@Vector(8, i32), v)); +} + +pub inline fn expandBits8(byte: u8) @Vector(8, u8) { + const bit_mask: @Vector(8, u8) = .{ 1, 2, 4, 8, 16, 32, 64, 128 }; + const bits = @as(@Vector(8, u8), @splat(byte)) & bit_mask; + return @select(u8, bits != @as(@Vector(8, u8), @splat(0)), @as(@Vector(8, u8), @splat(16)), @as(@Vector(8, u8), @splat(0))); +} diff --git a/zig/src/families/ling/cpu_gguf_pool.zig b/zig/src/families/ling/cpu_gguf_pool.zig new file mode 100644 index 00000000000..9a33e1dad9f --- /dev/null +++ b/zig/src/families/ling/cpu_gguf_pool.zig @@ -0,0 +1,242 @@ +//! Persistent exact workers: rows or whole experts are claimed in chunks, and each dot keeps its single-thread order. +const std = @import("std"); +const g = @import("core").gguf; +const rows = @import("cpu_rows.zig"); +const gguf_rows = @import("cpu_gguf_rows.zig"); + +/// One routed expert's gate, up and down matrices; its F32 result lands in `out`, one hidden row. +pub const Expert = struct { gate: g.Tensor, up: g.Tensor, down: g.Tensor, out: [*]f32 }; + +const Job = struct { + mode: enum { rows, experts }, + tensor: g.Tensor = undefined, + input: [*]const f32 = undefined, + output: [*]f32 = undefined, + count: usize = 1, + width: usize = 0, + inter: usize = 0, + n: usize = 0, + rounded: bool = true, + limit: f32 = 0, + experts: [*]const Expert = undefined, + units: usize = 0, + chunk: usize = 1, +}; + +fn range(t: g.Tensor, input: [*]const f32, output: [*]f32, count: usize, width: usize, n: usize, rounded: bool, lo: usize, hi: usize) void { + if (t.kind == .f32) { + const dense = rows.Tensor{ .dtype = .f32, .rank = 2, .shape = .{ n, width, 1, 1, 1 }, .bytes = t.bytes }; + return rows.projectRange(dense, input[0 .. count * width], output[0 .. count * n], count, width, n, rounded, lo, hi); + } + gguf_rows.dispatchRange(t.kind, t.bytes.ptr, input, output, count, width, n, rounded, lo, hi); +} + +/// The serial forward's SwiGLU expert for one row, with the same rounding and clamp at each step. +fn expert(j: *const Job, e: Expert) void { + var gate_buf: [1024]f32 = undefined; + var up_buf: [1024]f32 = undefined; + const gate = gate_buf[0..j.inter]; + const up = up_buf[0..j.inter]; + range(e.gate, j.input, gate.ptr, 1, j.width, j.inter, true, 0, j.inter); + range(e.up, j.input, up.ptr, 1, j.width, j.inter, true, 0, j.inter); + for (gate, up) |*v, *u| { + var silu = rows.round(v.* * rows.sigmoid(v.*)); + if (j.limit > 0) { + silu = @min(silu, j.limit); + u.* = std.math.clamp(u.*, -j.limit, j.limit); + } + v.* = rows.round(silu * u.*); + } + range(e.down, gate.ptr, e.out, 1, j.inter, j.width, true, 0, j.width); +} + +fn runJob(j: *const Job, lo: usize, hi: usize) void { + switch (j.mode) { + .rows => range(j.tensor, j.input, j.output, j.count, j.width, j.n, j.rounded, lo, hi), + .experts => for (lo..hi) |i| expert(j, j.experts[i]), + } +} + +fn chunkFor(units: usize, threads: usize) usize { + // About four claims a thread, 16 to 256 rows each, but never fewer than two chunks a thread. + const target = @max(@as(usize, 16), @min(@as(usize, 256), units / (threads * 4))); + var chunk = @min(target, @max(@as(usize, 1), units / (threads * 2))); + if (chunk > 1 and chunk % 2 != 0) chunk += 1; + return chunk; +} + +fn shape(t: g.Tensor) !struct { width: usize, n: usize } { + if (t.rank != 2) return error.BadLingGgufMatrix; + const width = std.math.cast(usize, t.shape[0]) orelse return error.BadLingGgufMatrix; + const n = std.math.cast(usize, t.shape[1]) orelse return error.BadLingGgufMatrix; + if (width == 0 or n == 0) return error.BadLingGgufMatrix; + const bytes = if (t.kind == .f32) try std.math.mul(usize, try std.math.mul(usize, n, width), 4) else blk: { + try gguf_rows.supported(t.kind); + const block = t.kind.block(); + if (width % block.values != 0) return error.BadLingGgufMatrix; + break :blk try std.math.mul(usize, n, try std.math.mul(usize, width / block.values, block.bytes)); + }; + if (t.bytes.len != bytes) return error.BadLingGgufMatrix; + return .{ .width = width, .n = n }; +} + +/// Extract up to `out.len` set CPU indices from a bitmask of `usize` words, in ascending order. +pub fn extractAllowedCpus(words: []const usize, out: []usize) usize { + const bits = @bitSizeOf(usize); + var count: usize = 0; + for (words, 0..) |word, wi| { + var w = word; + while (w != 0 and count < out.len) { + const bit = @ctz(w); + out[count] = wi * bits + bit; + count += 1; + w &= w - 1; + } + } + return count; +} + +fn pinSingleCpu(cpu: usize) void { + if (@import("builtin").os.tag != .linux) return; + const bits = @bitSizeOf(usize); + var set: std.os.linux.cpu_set_t = @splat(0); + if (cpu >= set.len * bits) return; + set[cpu / bits] = @as(usize, 1) << @intCast(cpu % bits); + std.os.linux.sched_setaffinity(0, &set) catch {}; +} + +/// Workers spin briefly between jobs, which come every few microseconds within a token, then park until woken. +pub const Pool = struct { + const spin_limit: usize = 500_000; + + allocator: std.mem.Allocator, + io: std.Io, + threads: usize, + /// Smaller matrices run on the calling thread; dispatch costs more than their work. + min_weights: usize = 256 * 256, + workers: [7]std.Thread = undefined, + made: usize = 0, + allowed_cpus: [8]usize = @splat(0), + pin_enabled: bool = false, + saved_mask: if (@import("builtin").os.tag == .linux) std.os.linux.cpu_set_t else void = + if (@import("builtin").os.tag == .linux) @splat(0) else {}, + mutex: std.Io.Mutex = .init, + ready: std.Io.Condition = .init, + generation: std.atomic.Value(usize) align(64) = .init(0), + remaining: std.atomic.Value(usize) align(64) = .init(0), + next: std.atomic.Value(usize) align(64) = .init(0), + stopping: std.atomic.Value(bool) align(64) = .init(false), + parked: std.atomic.Value(bool) align(64) = .init(false), + job: Job align(64) = undefined, + + pub fn create(a: std.mem.Allocator, io: std.Io, threads: usize) !*Pool { + if (threads == 0 or threads > 8) return error.CpuThreadCount; + const p = try a.create(Pool); + p.* = .{ .allocator = a, .io = io, .threads = threads }; + errdefer p.destroy(); + if (@import("builtin").os.tag == .linux and threads > 1) { + var mask: std.os.linux.cpu_set_t = @splat(0); + const rc = std.os.linux.sched_getaffinity(0, @sizeOf(std.os.linux.cpu_set_t), &mask); + if (std.os.linux.errno(rc) == .SUCCESS) { + if (extractAllowedCpus(&mask, p.allowed_cpus[0..threads]) >= threads) { + p.saved_mask = mask; + p.pin_enabled = true; + } + } + } + for (0..threads - 1) |id| { + p.workers[p.made] = try std.Thread.spawn(.{}, worker, .{ p, id }); + p.made += 1; + } + if (p.pin_enabled) pinSingleCpu(p.allowed_cpus[0]); + return p; + } + + pub fn destroy(p: *Pool) void { + p.stopping.store(true, .release); + p.mutex.lockUncancelable(p.io); + p.parked.store(false, .release); + p.ready.broadcast(p.io); + p.mutex.unlock(p.io); + for (p.workers[0..p.made]) |w| w.join(); + if (@import("builtin").os.tag == .linux and p.pin_enabled) { + std.os.linux.sched_setaffinity(0, &p.saved_mask) catch {}; + } + p.allocator.destroy(p); + } + + fn claim(p: *Pool) void { + const j = &p.job; + while (true) { + const lo = p.next.fetchAdd(j.chunk, .monotonic); + if (lo >= j.units) break; + runJob(j, lo, @min(j.units, lo + j.chunk)); + } + } + + fn worker(p: *Pool, id: usize) void { + if (p.pin_enabled) pinSingleCpu(p.allowed_cpus[id + 1]); + var seen: usize = 0; + while (true) { + var spins: usize = 0; + while (true) { + if (p.stopping.load(.acquire)) return; + const gen = p.generation.load(.acquire); + if (gen != seen) { + seen = gen; + break; + } + if (spins < spin_limit) { + spins += 1; + std.atomic.spinLoopHint(); + } else { + p.mutex.lockUncancelable(p.io); + p.parked.store(true, .release); + while (!p.stopping.load(.acquire) and p.generation.load(.acquire) == seen) p.ready.waitUncancelable(p.io, &p.mutex); + p.mutex.unlock(p.io); + spins = 0; + } + } + p.claim(); + _ = p.remaining.fetchSub(1, .acq_rel); + } + } + + /// Every worker takes part in every job, so the next job never starts while one still runs. + fn dispatch(p: *Pool, job: Job) void { + p.job = job; + p.next.store(0, .monotonic); + p.remaining.store(p.made, .release); + _ = p.generation.fetchAdd(1, .acq_rel); + if (p.parked.load(.acquire)) { + p.mutex.lockUncancelable(p.io); + p.parked.store(false, .release); + p.ready.broadcast(p.io); + p.mutex.unlock(p.io); + } + p.claim(); + while (p.remaining.load(.acquire) != 0) std.atomic.spinLoopHint(); + } + + /// The same bytes as gguf_rows.projectValidatedOn at one thread; quantized scales must already be validated. + pub fn project(p: *Pool, t: g.Tensor, input: []const f32, output: []f32, count: usize, rounded: bool) !void { + const s = try shape(t); + if (count == 0 or input.len != try std.math.mul(usize, count, s.width) or output.len != try std.math.mul(usize, count, s.n)) + return error.BadLingGgufMatrix; + const job = Job{ .mode = .rows, .tensor = t, .input = input.ptr, .output = output.ptr, .count = count, .width = s.width, .n = s.n, .rounded = rounded, .units = s.n, .chunk = chunkFor(s.n, p.threads) }; + if (p.made == 0 or s.width * s.n < p.min_weights) return runJob(&job, 0, s.n); + p.dispatch(job); + } + + /// One row's routed experts, one expert a claim; each writes only its own `out`. + pub fn experts(p: *Pool, list: []const Expert, input: []const f32, hidden: usize, inter: usize, limit: f32) !void { + if (inter == 0 or inter > 1024 or input.len != hidden) return error.BadLingGgufMatrix; + for (list) |e| for ([_]g.Tensor{ e.gate, e.up, e.down }, [_]usize{ hidden, hidden, inter }) |t, width| { + const s = try shape(t); + if (s.width != width or s.n != hidden + inter - width) return error.BadLingGgufMatrix; + }; + const job = Job{ .mode = .experts, .input = input.ptr, .width = hidden, .inter = inter, .limit = limit, .experts = list.ptr, .units = list.len, .chunk = 1 }; + if (p.made == 0) return runJob(&job, 0, list.len); + p.dispatch(job); + } +}; diff --git a/zig/src/families/ling/cpu_gguf_pool_test.zig b/zig/src/families/ling/cpu_gguf_pool_test.zig new file mode 100644 index 00000000000..6613d4b3828 --- /dev/null +++ b/zig/src/families/ling/cpu_gguf_pool_test.zig @@ -0,0 +1,108 @@ +//! Persistent workers against the one-thread exact projection, bit for bit, at 1, 2, 3, 4 and 8 threads. +const std = @import("std"); +const g = @import("core").gguf; +const rows = @import("cpu_rows.zig"); +const gguf_rows = @import("cpu_gguf_rows.zig"); +const pool_ = @import("cpu_gguf_pool.zig"); + +const thread_counts = [_]usize{ 1, 2, 3, 4, 8 }; + +fn quantized(a: std.mem.Allocator, kind: g.TensorKind, width: usize, n: usize, seed: usize) !g.Tensor { + const block = kind.block(); + const bytes = try a.alloc(u8, n * (width / block.values) * block.bytes); + for (bytes, 0..) |*v, i| v.* = @intCast((i * 31 + seed) % 256); + for (0..bytes.len / block.bytes) |b| { + const part = bytes[b * block.bytes ..][0..block.bytes]; + const at: usize = if (kind == .q6_k) 208 else 0; + std.mem.writeInt(u16, part[at..][0..2], if (b % 2 == 0) 0x2400 else 0xa400, .little); + if (kind == .q4_k) std.mem.writeInt(u16, part[2..4], 0x2000, .little); + } + try g.affine.validate(kind, bytes); + return .{ .name = "pool", .kind = kind, .rank = 2, .shape = .{ width, n, 1, 1 }, .offset = 0, .len = bytes.len, .bytes = bytes }; +} + +test "persistent workers project Q4_K, Q6_K, Q5_0 and F32 rows with the one-thread bytes" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const width: usize = 256; + const n: usize = 261; + var input: [8 * width]f32 = undefined; + for (&input, 0..) |*v, i| v.* = @as(f32, @floatFromInt(@as(i32, @intCast(i % 23)) - 11)) / 13; + const weights = try a.alloc(f32, n * width); + for (weights, 0..) |*w, i| w.* = @as(f32, @floatFromInt(@as(i32, @intCast(i % 29)) - 14)) / 17; + const f32_tensor = g.Tensor{ .name = "f32", .kind = .f32, .rank = 2, .shape = .{ width, n, 1, 1 }, .offset = 0, .len = n * width * 4, .bytes = std.mem.sliceAsBytes(weights) }; + const tensors = [_]g.Tensor{ try quantized(a, .q4_k, width, n, 7), try quantized(a, .q6_k, width, n, 11), try quantized(a, .q5_0, width, n, 13), f32_tensor }; + const want = try a.alloc(f32, 8 * n); + const got = try a.alloc(f32, 8 * n); + for (thread_counts) |threads| { + const pool = try pool_.Pool.create(std.testing.allocator, std.testing.io, threads); + defer pool.destroy(); + for ([_]usize{ 0, 256 * 256 }) |min_weights| { + pool.min_weights = min_weights; + for (tensors) |t| for ([_]usize{ 1, 2, 8 }) |count| for ([_]bool{ true, false }) |rounded| { + try gguf_rows.projectValidatedOn(t, input[0 .. count * width], want[0 .. count * n], count, rounded, 1); + @memset(got[0 .. count * n], std.math.nan(f32)); + try pool.project(t, input[0 .. count * width], got[0 .. count * n], count, rounded); + try std.testing.expectEqualSlices(u8, std.mem.sliceAsBytes(want[0 .. count * n]), std.mem.sliceAsBytes(got[0 .. count * n])); + }; + } + try std.testing.expectError(error.BadLingGgufMatrix, pool.project(tensors[0], input[0..width], got[0 .. n - 1], 1, true)); + } +} + +test "persistent workers run whole experts with the serial SwiGLU bytes" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const hidden: usize = 512; + const inter: usize = 256; + var x: [hidden]f32 = undefined; + for (&x, 0..) |*v, i| v.* = @as(f32, @floatFromInt(@as(i32, @intCast(i % 17)) - 8)) / 9; + var list: [8]pool_.Expert = undefined; + const got = try a.alloc(f32, list.len * hidden); + const want = try a.alloc(f32, list.len * hidden); + const kinds = [_]g.TensorKind{ .q4_k, .q6_k, .q5_0 }; + for (&list, 0..) |*e, j| e.* = .{ + .gate = try quantized(a, kinds[j % 3], hidden, inter, 3 * j + 1), + .up = try quantized(a, kinds[(j + 1) % 3], hidden, inter, 3 * j + 2), + .down = try quantized(a, kinds[(j + 2) % 3], inter, hidden, 3 * j + 3), + .out = got[j * hidden ..].ptr, + }; + for ([_]f32{ 0, 0.25 }) |limit| { + for (list, 0..) |e, j| { + var gate: [inter]f32 = undefined; + var up: [inter]f32 = undefined; + try gguf_rows.projectValidatedOn(e.gate, &x, &gate, 1, true, 1); + try gguf_rows.projectValidatedOn(e.up, &x, &up, 1, true, 1); + for (&gate, &up) |*v, *u| { + var silu = rows.round(v.* * rows.sigmoid(v.*)); + if (limit > 0) { + silu = @min(silu, limit); + u.* = std.math.clamp(u.*, -limit, limit); + } + v.* = rows.round(silu * u.*); + } + try gguf_rows.projectValidatedOn(e.down, &gate, want[j * hidden ..][0..hidden], 1, true, 1); + } + for (thread_counts) |threads| { + const pool = try pool_.Pool.create(std.testing.allocator, std.testing.io, threads); + defer pool.destroy(); + for (0..3) |_| { + @memset(got, std.math.nan(f32)); + try pool.experts(&list, &x, hidden, inter, limit); + try std.testing.expectEqualSlices(u8, std.mem.sliceAsBytes(want), std.mem.sliceAsBytes(got)); + } + } + } +} + +test "extractAllowedCpus reads sparse affinity masks in ascending order without hardcoded cores" { + const mask = [_]usize{ (@as(usize, 1) << 0) | (@as(usize, 1) << 3) | (@as(usize, 1) << 5) | (@as(usize, 1) << 7), (@as(usize, 1) << 2) }; + var out: [4]usize = undefined; + try std.testing.expectEqual(@as(usize, 4), pool_.extractAllowedCpus(&mask, &out)); + try std.testing.expectEqualSlices(usize, &.{ 0, 3, 5, 7 }, &out); + var all: [8]usize = undefined; + try std.testing.expectEqual(@as(usize, 5), pool_.extractAllowedCpus(&mask, &all)); + try std.testing.expectEqual(@as(usize, @bitSizeOf(usize) + 2), all[4]); +} diff --git a/zig/src/families/ling/cpu_gguf_q4k.zig b/zig/src/families/ling/cpu_gguf_q4k.zig new file mode 100644 index 00000000000..196eadd7ab3 --- /dev/null +++ b/zig/src/families/ling/cpu_gguf_q4k.zig @@ -0,0 +1,288 @@ +//! Exact Q4_K rows: each dot keeps the eight-lane FMA order of the scalar reference, so results match it bit for bit. +const rows = @import("cpu_rows.zig"); +const lanes = @import("cpu_gguf_lanes.zig"); +const readF16 = lanes.readF16; +const loadF32x8 = lanes.loadF32x8; +const lowHalf = lanes.lowHalf; +const highHalf = lanes.highHalf; +const u8x8ToF32x8 = lanes.u8x8ToF32x8; + +inline fn decodeQ4KScales(b: [*]const u8, scales: *[8]f32, biases: *[8]f32) void { + const d = readF16(b); + const m = readF16(b + 2); + const q = b + 4; + inline for (0..4) |grp| { + const s: u8 = q[grp] & 63; + const mn: u8 = q[grp + 4] & 63; + scales[grp] = d * @as(f32, @floatFromInt(s)); + biases[grp] = -m * @as(f32, @floatFromInt(mn)); + } + inline for (4..8) |grp| { + const s: u8 = (q[grp + 4] & 15) | ((q[grp - 4] >> 6) << 4); + const mn: u8 = (q[grp + 4] >> 4) | ((q[grp] >> 6) << 4); + scales[grp] = d * @as(f32, @floatFromInt(s)); + biases[grp] = -m * @as(f32, @floatFromInt(mn)); + } +} + +pub fn projectQ4KRange(bytes: [*]const u8, input: [*]const f32, output: [*]f32, count: usize, width: usize, n: usize, rounded: bool, lo: usize, hi: usize) void { + const blocks_per_row = width / 256; + const row_bytes = blocks_per_row * 144; + const mask4: @Vector(16, u8) = @splat(0x0F); + const shift4: @Vector(16, u8) = @splat(4); + + if (count == 1) { + var row = lo; + // Process 2 output rows in parallel to break FMA latency chains and reuse L1 input loads. + while (row + 1 < hi) : (row +%= 2) { + const r0_ptr = bytes + row * row_bytes; + const r1_ptr = r0_ptr + row_bytes; + var sum0: @Vector(8, f32) = @splat(0); + var sum1: @Vector(8, f32) = @splat(0); + var b: usize = 0; + while (b < blocks_per_row) : (b +%= 1) { + const b0 = r0_ptr + b * 144; + const b1 = r1_ptr + b * 144; + var scales0: [8]f32 = undefined; + var biases0: [8]f32 = undefined; + var scales1: [8]f32 = undefined; + var biases1: [8]f32 = undefined; + decodeQ4KScales(b0, &scales0, &biases0); + decodeQ4KScales(b1, &scales1, &biases1); + const x_blk = input + b * 256; + + inline for (0..4) |chunk| { + const qs0 = b0 + 16 + chunk * 32; + const qs1 = b1 + 16 + chunk * 32; + const raw0_a: @Vector(16, u8) = @as(*align(1) const [16]u8, @ptrCast(qs0)).*; + const raw0_b: @Vector(16, u8) = @as(*align(1) const [16]u8, @ptrCast(qs0 + 16)).*; + const raw1_a: @Vector(16, u8) = @as(*align(1) const [16]u8, @ptrCast(qs1)).*; + const raw1_b: @Vector(16, u8) = @as(*align(1) const [16]u8, @ptrCast(qs1 + 16)).*; + const xc = x_blk + chunk * 64; + + // Low nibbles (group 2 * chunk) + { + const lo0_a = raw0_a & mask4; + const lo0_b = raw0_b & mask4; + const lo1_a = raw1_a & mask4; + const lo1_b = raw1_b & mask4; + const s0: @Vector(8, f32) = @splat(scales0[2 * chunk]); + const k0: @Vector(8, f32) = @splat(biases0[2 * chunk]); + const s1: @Vector(8, f32) = @splat(scales1[2 * chunk]); + const k1: @Vector(8, f32) = @splat(biases1[2 * chunk]); + + const x0 = loadF32x8(xc); + sum0 = @mulAdd(@Vector(8, f32), x0, s0 * u8x8ToF32x8(lowHalf(lo0_a)) + k0, sum0); + sum1 = @mulAdd(@Vector(8, f32), x0, s1 * u8x8ToF32x8(lowHalf(lo1_a)) + k1, sum1); + + const x1 = loadF32x8(xc + 8); + sum0 = @mulAdd(@Vector(8, f32), x1, s0 * u8x8ToF32x8(highHalf(lo0_a)) + k0, sum0); + sum1 = @mulAdd(@Vector(8, f32), x1, s1 * u8x8ToF32x8(highHalf(lo1_a)) + k1, sum1); + + const x2 = loadF32x8(xc + 16); + sum0 = @mulAdd(@Vector(8, f32), x2, s0 * u8x8ToF32x8(lowHalf(lo0_b)) + k0, sum0); + sum1 = @mulAdd(@Vector(8, f32), x2, s1 * u8x8ToF32x8(lowHalf(lo1_b)) + k1, sum1); + + const x3 = loadF32x8(xc + 24); + sum0 = @mulAdd(@Vector(8, f32), x3, s0 * u8x8ToF32x8(highHalf(lo0_b)) + k0, sum0); + sum1 = @mulAdd(@Vector(8, f32), x3, s1 * u8x8ToF32x8(highHalf(lo1_b)) + k1, sum1); + } + // High nibbles (group 2 * chunk + 1) + { + const hi0_a = raw0_a >> shift4; + const hi0_b = raw0_b >> shift4; + const hi1_a = raw1_a >> shift4; + const hi1_b = raw1_b >> shift4; + const s0: @Vector(8, f32) = @splat(scales0[2 * chunk + 1]); + const k0: @Vector(8, f32) = @splat(biases0[2 * chunk + 1]); + const s1: @Vector(8, f32) = @splat(scales1[2 * chunk + 1]); + const k1: @Vector(8, f32) = @splat(biases1[2 * chunk + 1]); + + const x4 = loadF32x8(xc + 32); + sum0 = @mulAdd(@Vector(8, f32), x4, s0 * u8x8ToF32x8(lowHalf(hi0_a)) + k0, sum0); + sum1 = @mulAdd(@Vector(8, f32), x4, s1 * u8x8ToF32x8(lowHalf(hi1_a)) + k1, sum1); + + const x5 = loadF32x8(xc + 40); + sum0 = @mulAdd(@Vector(8, f32), x5, s0 * u8x8ToF32x8(highHalf(hi0_a)) + k0, sum0); + sum1 = @mulAdd(@Vector(8, f32), x5, s1 * u8x8ToF32x8(highHalf(hi1_a)) + k1, sum1); + + const x6 = loadF32x8(xc + 48); + sum0 = @mulAdd(@Vector(8, f32), x6, s0 * u8x8ToF32x8(lowHalf(hi0_b)) + k0, sum0); + sum1 = @mulAdd(@Vector(8, f32), x6, s1 * u8x8ToF32x8(lowHalf(hi1_b)) + k1, sum1); + + const x7 = loadF32x8(xc + 56); + sum0 = @mulAdd(@Vector(8, f32), x7, s0 * u8x8ToF32x8(highHalf(hi0_b)) + k0, sum0); + sum1 = @mulAdd(@Vector(8, f32), x7, s1 * u8x8ToF32x8(highHalf(hi1_b)) + k1, sum1); + } + } + } + const v0 = @reduce(.Add, sum0); + const v1 = @reduce(.Add, sum1); + output[row] = if (rounded) rows.round(v0) else v0; + output[row + 1] = if (rounded) rows.round(v1) else v1; + } + if (row < hi) { + const r0_ptr = bytes + row * row_bytes; + var sum0: @Vector(8, f32) = @splat(0); + var b: usize = 0; + while (b < blocks_per_row) : (b +%= 1) { + const b0 = r0_ptr + b * 144; + var scales0: [8]f32 = undefined; + var biases0: [8]f32 = undefined; + decodeQ4KScales(b0, &scales0, &biases0); + const x_blk = input + b * 256; + inline for (0..4) |chunk| { + const qs0 = b0 + 16 + chunk * 32; + const raw0_a: @Vector(16, u8) = @as(*align(1) const [16]u8, @ptrCast(qs0)).*; + const raw0_b: @Vector(16, u8) = @as(*align(1) const [16]u8, @ptrCast(qs0 + 16)).*; + const xc = x_blk + chunk * 64; + { + const lo0_a = raw0_a & mask4; + const lo0_b = raw0_b & mask4; + const s0: @Vector(8, f32) = @splat(scales0[2 * chunk]); + const k0: @Vector(8, f32) = @splat(biases0[2 * chunk]); + sum0 = @mulAdd(@Vector(8, f32), loadF32x8(xc), s0 * u8x8ToF32x8(lowHalf(lo0_a)) + k0, sum0); + sum0 = @mulAdd(@Vector(8, f32), loadF32x8(xc + 8), s0 * u8x8ToF32x8(highHalf(lo0_a)) + k0, sum0); + sum0 = @mulAdd(@Vector(8, f32), loadF32x8(xc + 16), s0 * u8x8ToF32x8(lowHalf(lo0_b)) + k0, sum0); + sum0 = @mulAdd(@Vector(8, f32), loadF32x8(xc + 24), s0 * u8x8ToF32x8(highHalf(lo0_b)) + k0, sum0); + } + { + const hi0_a = raw0_a >> shift4; + const hi0_b = raw0_b >> shift4; + const s0: @Vector(8, f32) = @splat(scales0[2 * chunk + 1]); + const k0: @Vector(8, f32) = @splat(biases0[2 * chunk + 1]); + sum0 = @mulAdd(@Vector(8, f32), loadF32x8(xc + 32), s0 * u8x8ToF32x8(lowHalf(hi0_a)) + k0, sum0); + sum0 = @mulAdd(@Vector(8, f32), loadF32x8(xc + 40), s0 * u8x8ToF32x8(highHalf(hi0_a)) + k0, sum0); + sum0 = @mulAdd(@Vector(8, f32), loadF32x8(xc + 48), s0 * u8x8ToF32x8(lowHalf(hi0_b)) + k0, sum0); + sum0 = @mulAdd(@Vector(8, f32), loadF32x8(xc + 56), s0 * u8x8ToF32x8(highHalf(hi0_b)) + k0, sum0); + } + } + } + const v0 = @reduce(.Add, sum0); + output[row] = if (rounded) rows.round(v0) else v0; + } + return; + } + + if (count == 2) { + const input1 = input + width; + for (lo..hi) |row| { + const r_ptr = bytes + row * row_bytes; + var sum0: @Vector(8, f32) = @splat(0); + var sum1: @Vector(8, f32) = @splat(0); + var b: usize = 0; + while (b < blocks_per_row) : (b +%= 1) { + const blk = r_ptr + b * 144; + var scales: [8]f32 = undefined; + var biases: [8]f32 = undefined; + decodeQ4KScales(blk, &scales, &biases); + const x0_blk = input + b * 256; + const x1_blk = input1 + b * 256; + inline for (0..4) |chunk| { + const qs = blk + 16 + chunk * 32; + const raw_a: @Vector(16, u8) = @as(*align(1) const [16]u8, @ptrCast(qs)).*; + const raw_b: @Vector(16, u8) = @as(*align(1) const [16]u8, @ptrCast(qs + 16)).*; + const x0c = x0_blk + chunk * 64; + const x1c = x1_blk + chunk * 64; + { + const lo_a = raw_a & mask4; + const lo_b = raw_b & mask4; + const s_lo: @Vector(8, f32) = @splat(scales[2 * chunk]); + const b_lo: @Vector(8, f32) = @splat(biases[2 * chunk]); + const w0 = s_lo * u8x8ToF32x8(lowHalf(lo_a)) + b_lo; + sum0 = @mulAdd(@Vector(8, f32), loadF32x8(x0c), w0, sum0); + sum1 = @mulAdd(@Vector(8, f32), loadF32x8(x1c), w0, sum1); + const w1 = s_lo * u8x8ToF32x8(highHalf(lo_a)) + b_lo; + sum0 = @mulAdd(@Vector(8, f32), loadF32x8(x0c + 8), w1, sum0); + sum1 = @mulAdd(@Vector(8, f32), loadF32x8(x1c + 8), w1, sum1); + const w2 = s_lo * u8x8ToF32x8(lowHalf(lo_b)) + b_lo; + sum0 = @mulAdd(@Vector(8, f32), loadF32x8(x0c + 16), w2, sum0); + sum1 = @mulAdd(@Vector(8, f32), loadF32x8(x1c + 16), w2, sum1); + const w3 = s_lo * u8x8ToF32x8(highHalf(lo_b)) + b_lo; + sum0 = @mulAdd(@Vector(8, f32), loadF32x8(x0c + 24), w3, sum0); + sum1 = @mulAdd(@Vector(8, f32), loadF32x8(x1c + 24), w3, sum1); + } + { + const hi_a = raw_a >> shift4; + const hi_b = raw_b >> shift4; + const s_hi: @Vector(8, f32) = @splat(scales[2 * chunk + 1]); + const b_hi: @Vector(8, f32) = @splat(biases[2 * chunk + 1]); + const w4 = s_hi * u8x8ToF32x8(lowHalf(hi_a)) + b_hi; + sum0 = @mulAdd(@Vector(8, f32), loadF32x8(x0c + 32), w4, sum0); + sum1 = @mulAdd(@Vector(8, f32), loadF32x8(x1c + 32), w4, sum1); + const w5 = s_hi * u8x8ToF32x8(highHalf(hi_a)) + b_hi; + sum0 = @mulAdd(@Vector(8, f32), loadF32x8(x0c + 40), w5, sum0); + sum1 = @mulAdd(@Vector(8, f32), loadF32x8(x1c + 40), w5, sum1); + const w6 = s_hi * u8x8ToF32x8(lowHalf(hi_b)) + b_hi; + sum0 = @mulAdd(@Vector(8, f32), loadF32x8(x0c + 48), w6, sum0); + sum1 = @mulAdd(@Vector(8, f32), loadF32x8(x1c + 48), w6, sum1); + const w7 = s_hi * u8x8ToF32x8(highHalf(hi_b)) + b_hi; + sum0 = @mulAdd(@Vector(8, f32), loadF32x8(x0c + 56), w7, sum0); + sum1 = @mulAdd(@Vector(8, f32), loadF32x8(x1c + 56), w7, sum1); + } + } + } + const v0 = @reduce(.Add, sum0); + const v1 = @reduce(.Add, sum1); + output[row] = if (rounded) rows.round(v0) else v0; + output[n + row] = if (rounded) rows.round(v1) else v1; + } + return; + } + + for (lo..hi) |row| { + const r_ptr = bytes + row * row_bytes; + var first: usize = 0; + while (first < count) : (first += 8) { + const batch = @min(8, count - first); + var sums: [8]@Vector(8, f32) = @splat(@splat(0)); + var b: usize = 0; + while (b < blocks_per_row) : (b +%= 1) { + const blk = r_ptr + b * 144; + var scales: [8]f32 = undefined; + var biases: [8]f32 = undefined; + decodeQ4KScales(blk, &scales, &biases); + inline for (0..4) |chunk| { + const qs = blk + 16 + chunk * 32; + const raw_a: @Vector(16, u8) = @as(*align(1) const [16]u8, @ptrCast(qs)).*; + const raw_b: @Vector(16, u8) = @as(*align(1) const [16]u8, @ptrCast(qs + 16)).*; + const lo_a = raw_a & mask4; + const lo_b = raw_b & mask4; + const s_lo: @Vector(8, f32) = @splat(scales[2 * chunk]); + const b_lo: @Vector(8, f32) = @splat(biases[2 * chunk]); + const w0 = s_lo * u8x8ToF32x8(lowHalf(lo_a)) + b_lo; + const w1 = s_lo * u8x8ToF32x8(highHalf(lo_a)) + b_lo; + const w2 = s_lo * u8x8ToF32x8(lowHalf(lo_b)) + b_lo; + const w3 = s_lo * u8x8ToF32x8(highHalf(lo_b)) + b_lo; + + const hi_a = raw_a >> shift4; + const hi_b = raw_b >> shift4; + const s_hi: @Vector(8, f32) = @splat(scales[2 * chunk + 1]); + const b_hi: @Vector(8, f32) = @splat(biases[2 * chunk + 1]); + const w4 = s_hi * u8x8ToF32x8(lowHalf(hi_a)) + b_hi; + const w5 = s_hi * u8x8ToF32x8(highHalf(hi_a)) + b_hi; + const w6 = s_hi * u8x8ToF32x8(lowHalf(hi_b)) + b_hi; + const w7 = s_hi * u8x8ToF32x8(highHalf(hi_b)) + b_hi; + + for (0..batch) |r| { + const xc = input + (first + r) * width + b * 256 + chunk * 64; + var acc = sums[r]; + acc = @mulAdd(@Vector(8, f32), loadF32x8(xc), w0, acc); + acc = @mulAdd(@Vector(8, f32), loadF32x8(xc + 8), w1, acc); + acc = @mulAdd(@Vector(8, f32), loadF32x8(xc + 16), w2, acc); + acc = @mulAdd(@Vector(8, f32), loadF32x8(xc + 24), w3, acc); + acc = @mulAdd(@Vector(8, f32), loadF32x8(xc + 32), w4, acc); + acc = @mulAdd(@Vector(8, f32), loadF32x8(xc + 40), w5, acc); + acc = @mulAdd(@Vector(8, f32), loadF32x8(xc + 48), w6, acc); + acc = @mulAdd(@Vector(8, f32), loadF32x8(xc + 56), w7, acc); + sums[r] = acc; + } + } + } + for (0..batch) |r| { + const value = @reduce(.Add, sums[r]); + output[(first + r) * n + row] = if (rounded) rows.round(value) else value; + } + } + } +} diff --git a/zig/src/families/ling/cpu_gguf_q6k_q50.zig b/zig/src/families/ling/cpu_gguf_q6k_q50.zig new file mode 100644 index 00000000000..527d7a5b3a8 --- /dev/null +++ b/zig/src/families/ling/cpu_gguf_q6k_q50.zig @@ -0,0 +1,363 @@ +//! Exact Q6_K and Q5_0 rows: each dot keeps the eight-lane FMA order of the scalar reference, bit for bit. +const rows = @import("cpu_rows.zig"); +const lanes = @import("cpu_gguf_lanes.zig"); +const readF16 = lanes.readF16; +const loadF32x8 = lanes.loadF32x8; +const lowHalf = lanes.lowHalf; +const highHalf = lanes.highHalf; +const lowHalfI8 = lanes.lowHalfI8; +const highHalfI8 = lanes.highHalfI8; +const i8x8ToF32x8 = lanes.i8x8ToF32x8; +const expandBits8 = lanes.expandBits8; + +inline fn q6kQuarter16(ql: @Vector(16, u8), qh: @Vector(16, u8), comptime quarter: usize) @Vector(16, i8) { + const mask4: @Vector(16, u8) = @splat(0x0F); + const lo = if (quarter < 2) (ql & mask4) else (ql >> @as(@Vector(16, u8), @splat(4))); + const hi = switch (quarter) { + 0 => (qh & @as(@Vector(16, u8), @splat(0x03))) << @as(@Vector(16, u8), @splat(4)), + 1 => (qh & @as(@Vector(16, u8), @splat(0x0C))) << @as(@Vector(16, u8), @splat(2)), + 2 => qh & @as(@Vector(16, u8), @splat(0x30)), + 3 => (qh & @as(@Vector(16, u8), @splat(0xC0))) >> @as(@Vector(16, u8), @splat(2)), + else => unreachable, + }; + return @as(@Vector(16, i8), @bitCast(lo | hi)) - @as(@Vector(16, i8), @splat(32)); +} + +pub fn projectQ6KRange(bytes: [*]const u8, input: [*]const f32, output: [*]f32, count: usize, width: usize, n: usize, rounded: bool, lo: usize, hi: usize) void { + const blocks_per_row = width / 256; + const row_bytes = blocks_per_row * 210; + + if (count == 1) { + var row = lo; + while (row + 1 < hi) : (row +%= 2) { + const r0_ptr = bytes + row * row_bytes; + const r1_ptr = r0_ptr + row_bytes; + var sum0: @Vector(8, f32) = @splat(0); + var sum1: @Vector(8, f32) = @splat(0); + var b: usize = 0; + while (b < blocks_per_row) : (b +%= 1) { + const b0 = r0_ptr + b * 210; + const b1 = r1_ptr + b * 210; + const d0 = readF16(b0 + 208); + const d1 = readF16(b1 + 208); + const x_blk = input + b * 256; + + inline for (0..2) |half| { + const ql0_ptr = b0 + half * 64; + const qh0_ptr = b0 + 128 + half * 32; + const sc0_ptr = b0 + 192 + half * 8; + const ql1_ptr = b1 + half * 64; + const qh1_ptr = b1 + 128 + half * 32; + const sc1_ptr = b1 + 192 + half * 8; + + const ql0_0: @Vector(16, u8) = @as(*align(1) const [16]u8, @ptrCast(ql0_ptr)).*; + const ql0_1: @Vector(16, u8) = @as(*align(1) const [16]u8, @ptrCast(ql0_ptr + 16)).*; + const ql0_2: @Vector(16, u8) = @as(*align(1) const [16]u8, @ptrCast(ql0_ptr + 32)).*; + const ql0_3: @Vector(16, u8) = @as(*align(1) const [16]u8, @ptrCast(ql0_ptr + 48)).*; + const qh0_0: @Vector(16, u8) = @as(*align(1) const [16]u8, @ptrCast(qh0_ptr)).*; + const qh0_1: @Vector(16, u8) = @as(*align(1) const [16]u8, @ptrCast(qh0_ptr + 16)).*; + + const ql1_0: @Vector(16, u8) = @as(*align(1) const [16]u8, @ptrCast(ql1_ptr)).*; + const ql1_1: @Vector(16, u8) = @as(*align(1) const [16]u8, @ptrCast(ql1_ptr + 16)).*; + const ql1_2: @Vector(16, u8) = @as(*align(1) const [16]u8, @ptrCast(ql1_ptr + 32)).*; + const ql1_3: @Vector(16, u8) = @as(*align(1) const [16]u8, @ptrCast(ql1_ptr + 48)).*; + const qh1_0: @Vector(16, u8) = @as(*align(1) const [16]u8, @ptrCast(qh1_ptr)).*; + const qh1_1: @Vector(16, u8) = @as(*align(1) const [16]u8, @ptrCast(qh1_ptr + 16)).*; + + inline for (0..4) |quarter| { + const ql0_a = if (quarter % 2 == 0) ql0_0 else ql0_2; + const ql0_b = if (quarter % 2 == 0) ql0_1 else ql0_3; + const ql1_a = if (quarter % 2 == 0) ql1_0 else ql1_2; + const ql1_b = if (quarter % 2 == 0) ql1_1 else ql1_3; + + const c0_a = q6kQuarter16(ql0_a, qh0_0, quarter); + const c0_b = q6kQuarter16(ql0_b, qh0_1, quarter); + const c1_a = q6kQuarter16(ql1_a, qh1_0, quarter); + const c1_b = q6kQuarter16(ql1_b, qh1_1, quarter); + + const s0_a: @Vector(8, f32) = @splat(d0 * @as(f32, @floatFromInt(@as(i8, @bitCast(sc0_ptr[quarter * 2]))))); + const s0_b: @Vector(8, f32) = @splat(d0 * @as(f32, @floatFromInt(@as(i8, @bitCast(sc0_ptr[quarter * 2 + 1]))))); + const s1_a: @Vector(8, f32) = @splat(d1 * @as(f32, @floatFromInt(@as(i8, @bitCast(sc1_ptr[quarter * 2]))))); + const s1_b: @Vector(8, f32) = @splat(d1 * @as(f32, @floatFromInt(@as(i8, @bitCast(sc1_ptr[quarter * 2 + 1]))))); + + const xq = x_blk + half * 128 + quarter * 32; + const x0 = loadF32x8(xq); + sum0 = @mulAdd(@Vector(8, f32), x0, s0_a * i8x8ToF32x8(lowHalfI8(c0_a)), sum0); + sum1 = @mulAdd(@Vector(8, f32), x0, s1_a * i8x8ToF32x8(lowHalfI8(c1_a)), sum1); + + const x1 = loadF32x8(xq + 8); + sum0 = @mulAdd(@Vector(8, f32), x1, s0_a * i8x8ToF32x8(highHalfI8(c0_a)), sum0); + sum1 = @mulAdd(@Vector(8, f32), x1, s1_a * i8x8ToF32x8(highHalfI8(c1_a)), sum1); + + const x2 = loadF32x8(xq + 16); + sum0 = @mulAdd(@Vector(8, f32), x2, s0_b * i8x8ToF32x8(lowHalfI8(c0_b)), sum0); + sum1 = @mulAdd(@Vector(8, f32), x2, s1_b * i8x8ToF32x8(lowHalfI8(c1_b)), sum1); + + const x3 = loadF32x8(xq + 24); + sum0 = @mulAdd(@Vector(8, f32), x3, s0_b * i8x8ToF32x8(highHalfI8(c0_b)), sum0); + sum1 = @mulAdd(@Vector(8, f32), x3, s1_b * i8x8ToF32x8(highHalfI8(c1_b)), sum1); + } + } + } + const v0 = @reduce(.Add, sum0); + const v1 = @reduce(.Add, sum1); + output[row] = if (rounded) rows.round(v0) else v0; + output[row + 1] = if (rounded) rows.round(v1) else v1; + } + if (row < hi) { + const r0_ptr = bytes + row * row_bytes; + var sum0: @Vector(8, f32) = @splat(0); + var b: usize = 0; + while (b < blocks_per_row) : (b +%= 1) { + const b0 = r0_ptr + b * 210; + const d0 = readF16(b0 + 208); + const x_blk = input + b * 256; + inline for (0..2) |half| { + const ql0_ptr = b0 + half * 64; + const qh0_ptr = b0 + 128 + half * 32; + const sc0_ptr = b0 + 192 + half * 8; + const ql0_0: @Vector(16, u8) = @as(*align(1) const [16]u8, @ptrCast(ql0_ptr)).*; + const ql0_1: @Vector(16, u8) = @as(*align(1) const [16]u8, @ptrCast(ql0_ptr + 16)).*; + const ql0_2: @Vector(16, u8) = @as(*align(1) const [16]u8, @ptrCast(ql0_ptr + 32)).*; + const ql0_3: @Vector(16, u8) = @as(*align(1) const [16]u8, @ptrCast(ql0_ptr + 48)).*; + const qh0_0: @Vector(16, u8) = @as(*align(1) const [16]u8, @ptrCast(qh0_ptr)).*; + const qh0_1: @Vector(16, u8) = @as(*align(1) const [16]u8, @ptrCast(qh0_ptr + 16)).*; + inline for (0..4) |quarter| { + const ql0_a = if (quarter % 2 == 0) ql0_0 else ql0_2; + const ql0_b = if (quarter % 2 == 0) ql0_1 else ql0_3; + const c0_a = q6kQuarter16(ql0_a, qh0_0, quarter); + const c0_b = q6kQuarter16(ql0_b, qh0_1, quarter); + const s0_a: @Vector(8, f32) = @splat(d0 * @as(f32, @floatFromInt(@as(i8, @bitCast(sc0_ptr[quarter * 2]))))); + const s0_b: @Vector(8, f32) = @splat(d0 * @as(f32, @floatFromInt(@as(i8, @bitCast(sc0_ptr[quarter * 2 + 1]))))); + const xq = x_blk + half * 128 + quarter * 32; + sum0 = @mulAdd(@Vector(8, f32), loadF32x8(xq), s0_a * i8x8ToF32x8(lowHalfI8(c0_a)), sum0); + sum0 = @mulAdd(@Vector(8, f32), loadF32x8(xq + 8), s0_a * i8x8ToF32x8(highHalfI8(c0_a)), sum0); + sum0 = @mulAdd(@Vector(8, f32), loadF32x8(xq + 16), s0_b * i8x8ToF32x8(lowHalfI8(c0_b)), sum0); + sum0 = @mulAdd(@Vector(8, f32), loadF32x8(xq + 24), s0_b * i8x8ToF32x8(highHalfI8(c0_b)), sum0); + } + } + } + const v0 = @reduce(.Add, sum0); + output[row] = if (rounded) rows.round(v0) else v0; + } + return; + } + + if (count == 2) { + const input1 = input + width; + for (lo..hi) |row| { + const r_ptr = bytes + row * row_bytes; + var sum0: @Vector(8, f32) = @splat(0); + var sum1: @Vector(8, f32) = @splat(0); + var b: usize = 0; + while (b < blocks_per_row) : (b +%= 1) { + const blk = r_ptr + b * 210; + const d = readF16(blk + 208); + const x0_blk = input + b * 256; + const x1_blk = input1 + b * 256; + inline for (0..2) |half| { + const ql_ptr = blk + half * 64; + const qh_ptr = blk + 128 + half * 32; + const sc_ptr = blk + 192 + half * 8; + const ql_0: @Vector(16, u8) = @as(*align(1) const [16]u8, @ptrCast(ql_ptr)).*; + const ql_1: @Vector(16, u8) = @as(*align(1) const [16]u8, @ptrCast(ql_ptr + 16)).*; + const ql_2: @Vector(16, u8) = @as(*align(1) const [16]u8, @ptrCast(ql_ptr + 32)).*; + const ql_3: @Vector(16, u8) = @as(*align(1) const [16]u8, @ptrCast(ql_ptr + 48)).*; + const qh_0: @Vector(16, u8) = @as(*align(1) const [16]u8, @ptrCast(qh_ptr)).*; + const qh_1: @Vector(16, u8) = @as(*align(1) const [16]u8, @ptrCast(qh_ptr + 16)).*; + inline for (0..4) |quarter| { + const ql_a = if (quarter % 2 == 0) ql_0 else ql_2; + const ql_b = if (quarter % 2 == 0) ql_1 else ql_3; + const c_a = q6kQuarter16(ql_a, qh_0, quarter); + const c_b = q6kQuarter16(ql_b, qh_1, quarter); + const s_a: @Vector(8, f32) = @splat(d * @as(f32, @floatFromInt(@as(i8, @bitCast(sc_ptr[quarter * 2]))))); + const s_b: @Vector(8, f32) = @splat(d * @as(f32, @floatFromInt(@as(i8, @bitCast(sc_ptr[quarter * 2 + 1]))))); + const x0q = x0_blk + half * 128 + quarter * 32; + const x1q = x1_blk + half * 128 + quarter * 32; + const w0 = s_a * i8x8ToF32x8(lowHalfI8(c_a)); + sum0 = @mulAdd(@Vector(8, f32), loadF32x8(x0q), w0, sum0); + sum1 = @mulAdd(@Vector(8, f32), loadF32x8(x1q), w0, sum1); + const w1 = s_a * i8x8ToF32x8(highHalfI8(c_a)); + sum0 = @mulAdd(@Vector(8, f32), loadF32x8(x0q + 8), w1, sum0); + sum1 = @mulAdd(@Vector(8, f32), loadF32x8(x1q + 8), w1, sum1); + const w2 = s_b * i8x8ToF32x8(lowHalfI8(c_b)); + sum0 = @mulAdd(@Vector(8, f32), loadF32x8(x0q + 16), w2, sum0); + sum1 = @mulAdd(@Vector(8, f32), loadF32x8(x1q + 16), w2, sum1); + const w3 = s_b * i8x8ToF32x8(highHalfI8(c_b)); + sum0 = @mulAdd(@Vector(8, f32), loadF32x8(x0q + 24), w3, sum0); + sum1 = @mulAdd(@Vector(8, f32), loadF32x8(x1q + 24), w3, sum1); + } + } + } + const v0 = @reduce(.Add, sum0); + const v1 = @reduce(.Add, sum1); + output[row] = if (rounded) rows.round(v0) else v0; + output[n + row] = if (rounded) rows.round(v1) else v1; + } + return; + } + + for (lo..hi) |row| { + const r_ptr = bytes + row * row_bytes; + var first: usize = 0; + while (first < count) : (first += 8) { + const batch = @min(8, count - first); + var sums: [8]@Vector(8, f32) = @splat(@splat(0)); + var b: usize = 0; + while (b < blocks_per_row) : (b +%= 1) { + const blk = r_ptr + b * 210; + const d = readF16(blk + 208); + inline for (0..2) |half| { + const ql_ptr = blk + half * 64; + const qh_ptr = blk + 128 + half * 32; + const sc_ptr = blk + 192 + half * 8; + const ql_0: @Vector(16, u8) = @as(*align(1) const [16]u8, @ptrCast(ql_ptr)).*; + const ql_1: @Vector(16, u8) = @as(*align(1) const [16]u8, @ptrCast(ql_ptr + 16)).*; + const ql_2: @Vector(16, u8) = @as(*align(1) const [16]u8, @ptrCast(ql_ptr + 32)).*; + const ql_3: @Vector(16, u8) = @as(*align(1) const [16]u8, @ptrCast(ql_ptr + 48)).*; + const qh_0: @Vector(16, u8) = @as(*align(1) const [16]u8, @ptrCast(qh_ptr)).*; + const qh_1: @Vector(16, u8) = @as(*align(1) const [16]u8, @ptrCast(qh_ptr + 16)).*; + inline for (0..4) |quarter| { + const ql_a = if (quarter % 2 == 0) ql_0 else ql_2; + const ql_b = if (quarter % 2 == 0) ql_1 else ql_3; + const c_a = q6kQuarter16(ql_a, qh_0, quarter); + const c_b = q6kQuarter16(ql_b, qh_1, quarter); + const s_a: @Vector(8, f32) = @splat(d * @as(f32, @floatFromInt(@as(i8, @bitCast(sc_ptr[quarter * 2]))))); + const s_b: @Vector(8, f32) = @splat(d * @as(f32, @floatFromInt(@as(i8, @bitCast(sc_ptr[quarter * 2 + 1]))))); + const w0 = s_a * i8x8ToF32x8(lowHalfI8(c_a)); + const w1 = s_a * i8x8ToF32x8(highHalfI8(c_a)); + const w2 = s_b * i8x8ToF32x8(lowHalfI8(c_b)); + const w3 = s_b * i8x8ToF32x8(highHalfI8(c_b)); + for (0..batch) |r| { + const xq = input + (first + r) * width + b * 256 + half * 128 + quarter * 32; + var acc = sums[r]; + acc = @mulAdd(@Vector(8, f32), loadF32x8(xq), w0, acc); + acc = @mulAdd(@Vector(8, f32), loadF32x8(xq + 8), w1, acc); + acc = @mulAdd(@Vector(8, f32), loadF32x8(xq + 16), w2, acc); + acc = @mulAdd(@Vector(8, f32), loadF32x8(xq + 24), w3, acc); + sums[r] = acc; + } + } + } + } + for (0..batch) |r| { + const value = @reduce(.Add, sums[r]); + output[(first + r) * n + row] = if (rounded) rows.round(value) else value; + } + } + } +} + +pub fn projectQ50Range(bytes: [*]const u8, input: [*]const f32, output: [*]f32, count: usize, width: usize, n: usize, rounded: bool, lo: usize, hi: usize) void { + const blocks_per_row = width / 32; + const row_bytes = blocks_per_row * 22; + const mask4: @Vector(16, u8) = @splat(0x0F); + const shift4: @Vector(16, u8) = @splat(4); + const bias16: @Vector(8, i8) = @splat(16); + + if (count == 1) { + var row = lo; + while (row + 1 < hi) : (row +%= 2) { + const r0_ptr = bytes + row * row_bytes; + const r1_ptr = r0_ptr + row_bytes; + var sum0: @Vector(8, f32) = @splat(0); + var sum1: @Vector(8, f32) = @splat(0); + var b: usize = 0; + while (b < blocks_per_row) : (b +%= 1) { + const b0 = r0_ptr + b * 22; + const b1 = r1_ptr + b * 22; + const s0: @Vector(8, f32) = @splat(readF16(b0)); + const s1: @Vector(8, f32) = @splat(readF16(b1)); + const qs0: @Vector(16, u8) = @as(*align(1) const [16]u8, @ptrCast(b0 + 6)).*; + const qs1: @Vector(16, u8) = @as(*align(1) const [16]u8, @ptrCast(b1 + 6)).*; + const lo0 = qs0 & mask4; + const hi0 = qs0 >> shift4; + const lo1 = qs1 & mask4; + const hi1 = qs1 >> shift4; + const xb = input + b * 32; + + const x0 = loadF32x8(xb); + const c0_0: @Vector(8, i8) = @as(@Vector(8, i8), @bitCast(lowHalf(lo0) | expandBits8(b0[2]))) - bias16; + const c1_0: @Vector(8, i8) = @as(@Vector(8, i8), @bitCast(lowHalf(lo1) | expandBits8(b1[2]))) - bias16; + sum0 = @mulAdd(@Vector(8, f32), x0, s0 * i8x8ToF32x8(c0_0), sum0); + sum1 = @mulAdd(@Vector(8, f32), x0, s1 * i8x8ToF32x8(c1_0), sum1); + + const x1 = loadF32x8(xb + 8); + const c0_1: @Vector(8, i8) = @as(@Vector(8, i8), @bitCast(highHalf(lo0) | expandBits8(b0[3]))) - bias16; + const c1_1: @Vector(8, i8) = @as(@Vector(8, i8), @bitCast(highHalf(lo1) | expandBits8(b1[3]))) - bias16; + sum0 = @mulAdd(@Vector(8, f32), x1, s0 * i8x8ToF32x8(c0_1), sum0); + sum1 = @mulAdd(@Vector(8, f32), x1, s1 * i8x8ToF32x8(c1_1), sum1); + + const x2 = loadF32x8(xb + 16); + const c0_2: @Vector(8, i8) = @as(@Vector(8, i8), @bitCast(lowHalf(hi0) | expandBits8(b0[4]))) - bias16; + const c1_2: @Vector(8, i8) = @as(@Vector(8, i8), @bitCast(lowHalf(hi1) | expandBits8(b1[4]))) - bias16; + sum0 = @mulAdd(@Vector(8, f32), x2, s0 * i8x8ToF32x8(c0_2), sum0); + sum1 = @mulAdd(@Vector(8, f32), x2, s1 * i8x8ToF32x8(c1_2), sum1); + + const x3 = loadF32x8(xb + 24); + const c0_3: @Vector(8, i8) = @as(@Vector(8, i8), @bitCast(highHalf(hi0) | expandBits8(b0[5]))) - bias16; + const c1_3: @Vector(8, i8) = @as(@Vector(8, i8), @bitCast(highHalf(hi1) | expandBits8(b1[5]))) - bias16; + sum0 = @mulAdd(@Vector(8, f32), x3, s0 * i8x8ToF32x8(c0_3), sum0); + sum1 = @mulAdd(@Vector(8, f32), x3, s1 * i8x8ToF32x8(c1_3), sum1); + } + const v0 = @reduce(.Add, sum0); + const v1 = @reduce(.Add, sum1); + output[row] = if (rounded) rows.round(v0) else v0; + output[row + 1] = if (rounded) rows.round(v1) else v1; + } + if (row < hi) { + const r0_ptr = bytes + row * row_bytes; + var sum0: @Vector(8, f32) = @splat(0); + var b: usize = 0; + while (b < blocks_per_row) : (b +%= 1) { + const b0 = r0_ptr + b * 22; + const s0: @Vector(8, f32) = @splat(readF16(b0)); + const qs0: @Vector(16, u8) = @as(*align(1) const [16]u8, @ptrCast(b0 + 6)).*; + const lo0 = qs0 & mask4; + const hi0 = qs0 >> shift4; + const xb = input + b * 32; + sum0 = @mulAdd(@Vector(8, f32), loadF32x8(xb), s0 * i8x8ToF32x8(@as(@Vector(8, i8), @bitCast(lowHalf(lo0) | expandBits8(b0[2]))) - bias16), sum0); + sum0 = @mulAdd(@Vector(8, f32), loadF32x8(xb + 8), s0 * i8x8ToF32x8(@as(@Vector(8, i8), @bitCast(highHalf(lo0) | expandBits8(b0[3]))) - bias16), sum0); + sum0 = @mulAdd(@Vector(8, f32), loadF32x8(xb + 16), s0 * i8x8ToF32x8(@as(@Vector(8, i8), @bitCast(lowHalf(hi0) | expandBits8(b0[4]))) - bias16), sum0); + sum0 = @mulAdd(@Vector(8, f32), loadF32x8(xb + 24), s0 * i8x8ToF32x8(@as(@Vector(8, i8), @bitCast(highHalf(hi0) | expandBits8(b0[5]))) - bias16), sum0); + } + const v0 = @reduce(.Add, sum0); + output[row] = if (rounded) rows.round(v0) else v0; + } + return; + } + + for (lo..hi) |row| { + const r_ptr = bytes + row * row_bytes; + var first: usize = 0; + while (first < count) : (first += 8) { + const batch = @min(8, count - first); + var sums: [8]@Vector(8, f32) = @splat(@splat(0)); + var b: usize = 0; + while (b < blocks_per_row) : (b +%= 1) { + const blk = r_ptr + b * 22; + const s: @Vector(8, f32) = @splat(readF16(blk)); + const qs: @Vector(16, u8) = @as(*align(1) const [16]u8, @ptrCast(blk + 6)).*; + const lo_n = qs & mask4; + const hi_n = qs >> shift4; + const w0 = s * i8x8ToF32x8(@as(@Vector(8, i8), @bitCast(lowHalf(lo_n) | expandBits8(blk[2]))) - bias16); + const w1 = s * i8x8ToF32x8(@as(@Vector(8, i8), @bitCast(highHalf(lo_n) | expandBits8(blk[3]))) - bias16); + const w2 = s * i8x8ToF32x8(@as(@Vector(8, i8), @bitCast(lowHalf(hi_n) | expandBits8(blk[4]))) - bias16); + const w3 = s * i8x8ToF32x8(@as(@Vector(8, i8), @bitCast(highHalf(hi_n) | expandBits8(blk[5]))) - bias16); + for (0..batch) |r| { + const xb = input + (first + r) * width + b * 32; + var acc = sums[r]; + acc = @mulAdd(@Vector(8, f32), loadF32x8(xb), w0, acc); + acc = @mulAdd(@Vector(8, f32), loadF32x8(xb + 8), w1, acc); + acc = @mulAdd(@Vector(8, f32), loadF32x8(xb + 16), w2, acc); + acc = @mulAdd(@Vector(8, f32), loadF32x8(xb + 24), w3, acc); + sums[r] = acc; + } + } + for (0..batch) |r| { + const value = @reduce(.Add, sums[r]); + output[(first + r) * n + row] = if (rounded) rows.round(value) else value; + } + } + } +} diff --git a/zig/src/families/ling/cpu_gguf_refusal_test.zig b/zig/src/families/ling/cpu_gguf_refusal_test.zig new file mode 100644 index 00000000000..6427458ea48 --- /dev/null +++ b/zig/src/families/ling/cpu_gguf_refusal_test.zig @@ -0,0 +1,305 @@ +//! Direct GGUF metadata, tensor-plan, clamp, KV-head, and EOS refusal tests for Ling-3.0-tiny CPU loading. +const std = @import("std"); +const g = @import("core").gguf; +const cpu_gguf = @import("cpu_gguf.zig"); +const cfg = @import("cpu_gguf_config.zig"); +const names = @import("gguf_names.zig"); + +const MetaOpts = struct { + arch: ?g.Value = .{ .string = "bailingmoe3" }, + block_count: g.Value = .{ .uint32 = 24 }, + rope_freq_base: g.Value = .{ .float32 = 6000000.0 }, + safe_gate: g.Value = .{ .boolean = true }, + tokens_len: u64 = 157184, + kv_mode: enum { valid, missing, scalar, short_len, bad_pattern, string_elems } = .valid, + clamp_exp: bool = false, + clamp_shexp: bool = false, + eos: ?g.Value = .{ .uint32 = 157152 }, + bos: ?g.Value = null, +}; + +fn appendInt(buf: *std.ArrayList(u8), a: std.mem.Allocator, comptime T: type, v: T) !void { + var raw: [@sizeOf(T)]u8 = undefined; + std.mem.writeInt(T, &raw, v, .little); + try buf.appendSlice(a, &raw); +} + +fn appendStr(buf: *std.ArrayList(u8), a: std.mem.Allocator, s: []const u8) !void { + try appendInt(buf, a, u64, s.len); + try buf.appendSlice(a, s); +} + +fn appendKv(buf: *std.ArrayList(u8), a: std.mem.Allocator, key: []const u8, v: g.Value) !void { + try appendStr(buf, a, key); + try appendInt(buf, a, u32, @backingInt(v)); + switch (v) { + .string => |s| try appendStr(buf, a, s), + .float32 => |x| try appendInt(buf, a, u32, @bitCast(x)), + .float64 => |x| try appendInt(buf, a, u64, @bitCast(x)), + .boolean => |b| try appendInt(buf, a, u8, @intFromBool(b)), + .array => unreachable, + inline else => |x| try appendInt(buf, a, @TypeOf(x), x), + } +} + +fn buildMetadataGguf(a: std.mem.Allocator, opts: MetaOpts) ![]u8 { + var kvs: std.ArrayList(u8) = .empty; + defer kvs.deinit(a); + var count: u64 = 0; + + if (opts.arch) |v| { + try appendKv(&kvs, a, "general.architecture", v); + count += 1; + } + try appendKv(&kvs, a, "bailingmoe3.block_count", opts.block_count); + count += 1; + + const ints = .{ + .{ "embedding_length", 1536 }, + .{ "feed_forward_length", 4608 }, + .{ "attention.head_count", 16 }, + .{ "expert_count", 128 }, + .{ "expert_used_count", 8 }, + .{ "expert_group_count", 8 }, + .{ "expert_group_used_count", 4 }, + .{ "expert_gating_func", 2 }, + .{ "vocab_size", 157184 }, + .{ "ssm.conv_kernel", 4 }, + .{ "kda.head_dim", 128 }, + .{ "attention.q_lora_rank", 256 }, + .{ "attention.kv_lora_rank", 512 }, + .{ "rope.dimension_count", 64 }, + .{ "expert_feed_forward_length", 512 }, + .{ "expert_shared_feed_forward_length", 512 }, + .{ "leading_dense_block_count", 1 }, + .{ "context_length", 131072 }, + .{ "attention.key_length_mla", 192 }, + .{ "attention.value_length_mla", 128 }, + .{ "expert_shared_count", 1 }, + }; + inline for (ints) |item| { + try appendKv(&kvs, a, "bailingmoe3." ++ item[0], .{ .uint32 = item[1] }); + count += 1; + } + + try appendKv(&kvs, a, "bailingmoe3.rope.freq_base", opts.rope_freq_base); + count += 1; + const floats = .{ + .{ "attention.layer_norm_rms_epsilon", @as(f32, 0.000001) }, + .{ "kda.gate_lower_bound", @as(f32, -5.0) }, + .{ "expert_weights_scale", @as(f32, 2.5) }, + }; + inline for (floats) |item| { + try appendKv(&kvs, a, "bailingmoe3." ++ item[0], .{ .float32 = item[1] }); + count += 1; + } + + try appendKv(&kvs, a, "bailingmoe3.kda.safe_gate", opts.safe_gate); + try appendKv(&kvs, a, "bailingmoe3.expert_weights_norm", .{ .boolean = true }); + count += 2; + + switch (opts.kv_mode) { + .missing => {}, + .scalar => { + try appendKv(&kvs, a, "bailingmoe3.attention.head_count_kv", .{ .uint32 = 16 }); + count += 1; + }, + .valid, .short_len, .bad_pattern => { + const len: u64 = if (opts.kv_mode == .short_len) 23 else 24; + try appendStr(&kvs, a, "bailingmoe3.attention.head_count_kv"); + try appendInt(&kvs, a, u32, @backingInt(g.MetadataKind.array)); + try appendInt(&kvs, a, u32, @backingInt(g.MetadataKind.uint32)); + try appendInt(&kvs, a, u64, len); + for (0..@intCast(len)) |layer| { + var val: u32 = if (layer % 4 == 3) 1 else 0; + if (opts.kv_mode == .bad_pattern and layer == 0) val = 1; + try appendInt(&kvs, a, u32, val); + } + count += 1; + }, + .string_elems => { + try appendStr(&kvs, a, "bailingmoe3.attention.head_count_kv"); + try appendInt(&kvs, a, u32, @backingInt(g.MetadataKind.array)); + try appendInt(&kvs, a, u32, @backingInt(g.MetadataKind.string)); + try appendInt(&kvs, a, u64, 24); + for (0..24) |_| try appendStr(&kvs, a, "0"); + count += 1; + }, + } + + try appendStr(&kvs, a, "tokenizer.ggml.tokens"); + try appendInt(&kvs, a, u32, @backingInt(g.MetadataKind.array)); + try appendInt(&kvs, a, u32, @backingInt(g.MetadataKind.string)); + try appendInt(&kvs, a, u64, opts.tokens_len); + // Empty strings are 8-byte zero lengths, keeping the 157184-token array at ~1.2 MiB in memory. + try kvs.appendNTimes(a, 0, @as(usize, @intCast(opts.tokens_len)) * 8); + count += 1; + + if (opts.clamp_exp) { + try appendKv(&kvs, a, "bailingmoe3.swiglu_clamp_exp", .{ .float32 = 7.0 }); + count += 1; + } + if (opts.clamp_shexp) { + try appendKv(&kvs, a, "bailingmoe3.swiglu_clamp_shexp", .{ .float32 = 7.0 }); + count += 1; + } + if (opts.eos) |v| { + try appendKv(&kvs, a, "tokenizer.ggml.eos_token_id", v); + count += 1; + } + if (opts.bos) |v| { + try appendKv(&kvs, a, "tokenizer.ggml.bos_token_id", v); + count += 1; + } + + var out: std.ArrayList(u8) = .empty; + errdefer out.deinit(a); + try out.appendSlice(a, "GGUF"); + try appendInt(&out, a, u32, 3); + try appendInt(&out, a, u64, 0); + try appendInt(&out, a, u64, count); + try out.appendSlice(a, kvs.items); + const aligned = std.mem.alignForward(usize, out.items.len, 32); + try out.appendNTimes(a, 0, aligned - out.items.len); + return out.toOwnedSlice(a); +} + +fn parseAndCheckMeta(a: std.mem.Allocator, opts: MetaOpts) !void { + const bytes = try buildMetadataGguf(a, opts); + defer a.free(bytes); + var doc = try g.Document.parse(a, bytes, .{}); + defer doc.deinit(); + try cpu_gguf.validateMetadata(&doc); +} + +fn parseAndCheckConfig(a: std.mem.Allocator, opts: MetaOpts) !void { + const bytes = try buildMetadataGguf(a, opts); + defer a.free(bytes); + var doc = try g.Document.parse(a, bytes, .{}); + defer doc.deinit(); + try cpu_gguf.validateMetadata(&doc); + _ = try cfg.tiny(&doc); +} + +test "Ling GGUF refuses wrong architecture and wrong geometry" { + const a = std.testing.allocator; + try parseAndCheckConfig(a, .{}); + + try std.testing.expectError(error.MissingLingGgufMetadata, parseAndCheckMeta(a, .{ .arch = null })); + try std.testing.expectError(error.UnsupportedLingGgufArchitecture, parseAndCheckMeta(a, .{ .arch = .{ .string = "llama" } })); + try std.testing.expectError(error.UnsupportedLingGgufArchitecture, parseAndCheckMeta(a, .{ .arch = .{ .uint32 = 1 } })); + + try std.testing.expectError(error.UnsupportedLingGgufGeometry, parseAndCheckMeta(a, .{ .block_count = .{ .uint32 = 23 } })); + try std.testing.expectError(error.BadLingGgufMetadata, parseAndCheckMeta(a, .{ .block_count = .{ .int32 = 24 } })); + try std.testing.expectError(error.UnsupportedLingGgufGeometry, parseAndCheckMeta(a, .{ .rope_freq_base = .{ .float32 = 10000.0 } })); + try std.testing.expectError(error.UnsupportedLingGgufGeometry, parseAndCheckMeta(a, .{ .rope_freq_base = .{ .float32 = std.math.nan(f32) } })); + try std.testing.expectError(error.UnsupportedLingGgufGeometry, parseAndCheckMeta(a, .{ .safe_gate = .{ .boolean = false } })); + try std.testing.expectError(error.UnsupportedLingGgufGeometry, parseAndCheckMeta(a, .{ .tokens_len = 157183 })); + + // Verify File.open itself refuses wrong architecture end-to-end on disk. + const io = std.testing.io; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const bad = try buildMetadataGguf(a, .{ .arch = .{ .string = "qwen2" } }); + defer a.free(bad); + try tmp.dir.writeFile(io, .{ .sub_path = "bad_arch.gguf", .data = bad }); + const path = try std.fmt.allocPrint(a, ".zig-cache/tmp/{s}/bad_arch.gguf", .{tmp.sub_path}); + defer a.free(path); + try std.testing.expectError(error.UnsupportedLingGgufArchitecture, cpu_gguf.File.open(a, io, path)); +} + +test "Ling GGUF refuses malformed KV-head metadata and forbidden clamps" { + const a = std.testing.allocator; + try std.testing.expectError(error.MissingLingGgufMetadata, parseAndCheckMeta(a, .{ .kv_mode = .missing })); + try std.testing.expectError(error.UnsupportedLingGgufGeometry, parseAndCheckMeta(a, .{ .kv_mode = .scalar })); + try std.testing.expectError(error.UnsupportedLingGgufGeometry, parseAndCheckMeta(a, .{ .kv_mode = .short_len })); + try std.testing.expectError(error.UnsupportedLingGgufGeometry, parseAndCheckMeta(a, .{ .kv_mode = .bad_pattern })); + try std.testing.expectError(error.MetadataTypeMismatch, parseAndCheckMeta(a, .{ .kv_mode = .string_elems })); + + try std.testing.expectError(error.UnsupportedLingGgufClamp, parseAndCheckMeta(a, .{ .clamp_exp = true })); + try std.testing.expectError(error.UnsupportedLingGgufClamp, parseAndCheckMeta(a, .{ .clamp_shexp = true })); +} + +test "Ling GGUF config refuses missing or invalid EOS and BOS tokens" { + const a = std.testing.allocator; + try std.testing.expectError(error.MissingLingGgufEos, parseAndCheckConfig(a, .{ .eos = null })); + try std.testing.expectError(error.BadLingGgufToken, parseAndCheckConfig(a, .{ .eos = .{ .uint32 = 157184 } })); + try std.testing.expectError(error.MetadataTypeMismatch, parseAndCheckConfig(a, .{ .eos = .{ .string = "eos" } })); + try std.testing.expectError(error.MetadataTypeMismatch, parseAndCheckConfig(a, .{ .eos = .{ .int32 = -1 } })); + try std.testing.expectError(error.BadLingGgufToken, parseAndCheckConfig(a, .{ .bos = .{ .uint32 = 157184 } })); +} + +fn makeValidTensor(n: names.Name, decay_bytes: []const u8) g.Tensor { + const kind: g.TensorKind = switch (n.role) { + .positive_exp_decay, .vector, .convolution => .f32, + else => .q4_k, + }; + return .{ + .name = n.source, + .kind = kind, + .rank = n.rank, + .shape = .{ n.dims[0], n.dims[1], n.dims[2], 1 }, + .offset = 0, + .len = if (n.role == .positive_exp_decay) decay_bytes.len else 0, + .bytes = if (n.role == .positive_exp_decay) decay_bytes else &.{}, + }; +} + +test "Ling GGUF refuses missing and extra tensors against the tiny tensor plan" { + const a = std.testing.allocator; + var arena = std.heap.ArenaAllocator.init(a); + defer arena.deinit(); + const plan = try names.tiny(arena.allocator()); + + var decay_raw: [64]u8 = undefined; + for (0..16) |i| std.mem.writeInt(u32, decay_raw[i * 4 ..][0..4], @bitCast(@as(f32, 0.5)), .little); + + // Baseline: exact plan passes. + var doc = g.Document{ + .gpa = a, + .bytes = &.{}, + .metadata = &.{}, + .tensors = try a.alloc(g.Tensor, plan.len), + .data_offset = 0, + .alignment = 32, + }; + defer { + doc.names.deinit(a); + a.free(doc.tensors); + } + for (plan, 0..) |n, i| { + doc.tensors[i] = makeValidTensor(n, &decay_raw); + try doc.names.put(a, n.source, i); + } + try cpu_gguf.validateTensors(&doc, plan); + + // Missing tensor: drop the last tensor from the document. + var missing = g.Document{ + .gpa = a, + .bytes = &.{}, + .metadata = &.{}, + .tensors = doc.tensors[0 .. plan.len - 1], + .data_offset = 0, + .alignment = 32, + }; + defer missing.names.deinit(a); + for (missing.tensors, 0..) |t, i| try missing.names.put(a, t.name, i); + try std.testing.expectError(error.MissingLingGgufTensor, cpu_gguf.validateTensors(&missing, plan)); + + // Extra tensor: all expected tensors plus one unexpected tensor. + const extra_tensors = try a.alloc(g.Tensor, plan.len + 1); + defer a.free(extra_tensors); + @memcpy(extra_tensors[0..plan.len], doc.tensors); + extra_tensors[plan.len] = .{ .name = "blk.0.extra.weight", .kind = .f32, .rank = 1, .shape = .{ 16, 1, 1, 1 }, .offset = 0, .len = 0 }; + var extra = g.Document{ + .gpa = a, + .bytes = &.{}, + .metadata = &.{}, + .tensors = extra_tensors, + .data_offset = 0, + .alignment = 32, + }; + defer extra.names.deinit(a); + for (extra.tensors, 0..) |t, i| try extra.names.put(a, t.name, i); + try std.testing.expectError(error.UnexpectedLingGgufTensor, cpu_gguf.validateTensors(&extra, plan)); +} diff --git a/zig/src/families/ling/cpu_gguf_rows.zig b/zig/src/families/ling/cpu_gguf_rows.zig new file mode 100644 index 00000000000..3dc5bf97afb --- /dev/null +++ b/zig/src/families/ling/cpu_gguf_rows.zig @@ -0,0 +1,147 @@ +//! GGUF CPU projection over the shared affine reader, with the existing eight-lane F32 sum order. +const std = @import("std"); +const core = @import("core"); +const g = core.gguf; +const rows = @import("cpu_rows.zig"); +const q4k = @import("cpu_gguf_q4k.zig"); +const q6k_q50 = @import("cpu_gguf_q6k_q50.zig"); + +pub fn supported(kind: g.TensorKind) !void { + switch (kind) { + .q4_k, .q6_k, .q5_0 => {}, + else => return error.UnsupportedLingGgufQuant, + } +} +pub fn decodeBlock(kind: g.TensorKind, src: []const u8, output: []f32) !void { + return switch (kind) { + .q4_k => decodeKnown(.q4_k, src, output), + .q6_k => decodeKnown(.q6_k, src, output), + .q5_0 => decodeKnown(.q5_0, src, output), + else => error.UnsupportedLingGgufQuant, + }; +} +fn decodeKnown(comptime kind: g.TensorKind, src: []const u8, output: []f32) !void { + const block = comptime kind.block(); + if (src.len != block.bytes or output.len != block.values) return error.BadLingGgufBlock; + const layout = comptime g.affine.layout(kind, kind.block().bytes) catch unreachable; + var words: [48]u32 = undefined; + var scales: [16]f32 = undefined; + var biases: [16]f32 = undefined; + try g.affine.into(kind, src, words[0..layout.words], scales[0..layout.groups], biases[0..layout.groups]); + const bits = layout.format.bits; + for (output, 0..) |*v, i| { + const at = i * bits; + const shift: u5 = @intCast(at % 32); + var code = words[at / 32] >> shift; + if (@as(usize, shift) + bits > 32) code |= words[at / 32 + 1] << @intCast(32 - @as(usize, shift)); + code &= (@as(u32, 1) << @intCast(bits)) - 1; + const group = i / layout.format.group; + const centered: i32 = @as(i32, @intCast(code)) - (if (kind == .q6_k) @as(i32, 32) else if (kind == .q5_0) @as(i32, 16) else 0); + // Centered multiplication retains negative zero from a negative source scale. + v.* = scales[group] * @as(f32, @floatFromInt(centered)); + if (kind == .q4_k) v.* += biases[group]; + } +} +pub fn decodeTensor(t: g.Tensor, output: []f32) !void { + var elements: usize = 1; + for (t.shape[0..t.rank]) |dim| elements = try std.math.mul(usize, elements, std.math.cast(usize, dim) orelse return error.BadLingGgufMatrix); + if (elements != output.len) return error.BadLingGgufMatrix; + if (t.kind == .f32) { + if (t.bytes.len != try std.math.mul(usize, elements, 4)) return error.BadLingGgufMatrix; + for (output, 0..) |*v, i| v.* = @bitCast(std.mem.readInt(u32, t.bytes[i * 4 ..][0..4], .little)); + return; + } + try supported(t.kind); + const b = t.kind.block(); + if (elements % b.values != 0 or t.bytes.len != try std.math.mul(usize, elements / b.values, b.bytes)) return error.BadLingGgufMatrix; + try g.affine.validate(t.kind, t.bytes); + for (0..elements / b.values) |i| try decodeBlock(t.kind, t.bytes[i * b.bytes ..][0..b.bytes], output[i * b.values ..][0..b.values]); +} + +pub fn projectReference(t: g.Tensor, input: []const f32, output: []f32, count: usize, rounded: bool) !void { + if (t.rank != 2 or count == 0) return error.BadLingGgufMatrix; + const width = std.math.cast(usize, t.shape[0]) orelse return error.BadLingGgufMatrix; + const n = std.math.cast(usize, t.shape[1]) orelse return error.BadLingGgufMatrix; + if (input.len != try std.math.mul(usize, count, width) or output.len != try std.math.mul(usize, count, n)) return error.BadLingGgufMatrix; + if (t.kind == .f32) return rows.project(.{ .dtype = .f32, .rank = 2, .shape = .{ n, width, 1, 1, 1 }, .bytes = t.bytes }, input, output, count, width, n, rounded); + try supported(t.kind); + const block = t.kind.block(); + if (width == 0 or n == 0 or width % block.values != 0 or t.bytes.len != try std.math.mul(usize, n, try std.math.mul(usize, width / block.values, block.bytes))) return error.BadLingGgufMatrix; + try g.affine.validate(t.kind, t.bytes); + for (0..n) |row| { + var first: usize = 0; + while (first < count) : (first += 8) { + const batch = @min(8, count - first); + var sums: [8]@Vector(8, f32) = @splat(@splat(0)); + for (0..width / block.values) |b| { + var values: [256]f32 = undefined; + const start = (row * (width / block.values) + b) * block.bytes; + try decodeBlock(t.kind, t.bytes[start..][0..block.bytes], values[0..block.values]); + for (0..batch) |r| { + var i: usize = 0; + while (i < block.values) : (i += 8) { + const x: @Vector(8, f32) = input[(first + r) * width + b * block.values + i ..][0..8].*; + const w: @Vector(8, f32) = values[i..][0..8].*; + sums[r] = @mulAdd(@Vector(8, f32), x, w, sums[r]); + } + } + } + for (0..batch) |r| { + const value = @reduce(.Add, sums[r]); + output[(first + r) * n + row] = if (rounded) rows.round(value) else value; + } + } + } +} + +pub fn dispatchRange(kind: g.TensorKind, bytes: [*]const u8, input: [*]const f32, output: [*]f32, count: usize, width: usize, n: usize, rounded: bool, lo: usize, hi: usize) void { + switch (kind) { + .q4_k => q4k.projectQ4KRange(bytes, input, output, count, width, n, rounded, lo, hi), + .q6_k => q6k_q50.projectQ6KRange(bytes, input, output, count, width, n, rounded, lo, hi), + .q5_0 => q6k_q50.projectQ50Range(bytes, input, output, count, width, n, rounded, lo, hi), + else => unreachable, + } +} + +/// Split output rows only: every row preserves the exact 8-lane FMA/reduction order at every thread count. +pub fn projectValidatedOn(t: g.Tensor, input: []const f32, output: []f32, count: usize, rounded: bool, threads: usize) !void { + if (threads == 0 or threads > 8) return error.CpuThreadCount; + if (t.rank != 2 or count == 0) return error.BadLingGgufMatrix; + const width = std.math.cast(usize, t.shape[0]) orelse return error.BadLingGgufMatrix; + const n = std.math.cast(usize, t.shape[1]) orelse return error.BadLingGgufMatrix; + if (input.len != try std.math.mul(usize, count, width) or output.len != try std.math.mul(usize, count, n)) return error.BadLingGgufMatrix; + if (t.kind == .f32) return rows.projectOn(.{ .dtype = .f32, .rank = 2, .shape = .{ n, width, 1, 1, 1 }, .bytes = t.bytes }, input, output, count, width, n, rounded, threads); + try supported(t.kind); + const block = t.kind.block(); + if (width == 0 or n == 0 or width % block.values != 0 or t.bytes.len != try std.math.mul(usize, n, try std.math.mul(usize, width / block.values, block.bytes))) return error.BadLingGgufMatrix; + const active = @min(threads, n); + if (active == 1) { + dispatchRange(t.kind, t.bytes.ptr, input.ptr, output.ptr, count, width, n, rounded, 0, n); + return; + } + var workers: [7]std.Thread = undefined; + var made: usize = 0; + defer for (workers[0..made]) |w| w.join(); + for (0..active - 1) |i| { + workers[made] = try std.Thread.spawn(.{}, dispatchRange, .{ t.kind, t.bytes.ptr, input.ptr, output.ptr, count, width, n, rounded, i * n / active, (i + 1) * n / active }); + made += 1; + } + dispatchRange(t.kind, t.bytes.ptr, input.ptr, output.ptr, count, width, n, rounded, (active - 1) * n / active, n); +} + +pub fn projectOn(t: g.Tensor, input: []const f32, output: []f32, count: usize, rounded: bool, threads: usize) !void { + if (t.kind != .f32) { + try supported(t.kind); + if (t.rank != 2 or count == 0) return error.BadLingGgufMatrix; + const width = std.math.cast(usize, t.shape[0]) orelse return error.BadLingGgufMatrix; + const n = std.math.cast(usize, t.shape[1]) orelse return error.BadLingGgufMatrix; + const block = t.kind.block(); + if (width == 0 or n == 0 or width % block.values != 0 or t.bytes.len != try std.math.mul(usize, n, try std.math.mul(usize, width / block.values, block.bytes))) return error.BadLingGgufMatrix; + try g.affine.validate(t.kind, t.bytes); + } + try projectValidatedOn(t, input, output, count, rounded, threads); +} + +pub fn project(t: g.Tensor, input: []const f32, output: []f32, count: usize, rounded: bool) !void { + return projectOn(t, input, output, count, rounded, 1); +} diff --git a/zig/src/families/ling/cpu_gguf_rows_test.zig b/zig/src/families/ling/cpu_gguf_rows_test.zig new file mode 100644 index 00000000000..350a312c905 --- /dev/null +++ b/zig/src/families/ling/cpu_gguf_rows_test.zig @@ -0,0 +1,116 @@ +//! Exact GGUF block decode and projection checks against the independent FP64 source definition. +const std = @import("std"); +const core = @import("core"); +const g = core.gguf; +const rows = @import("cpu_rows.zig"); +const gguf_rows = @import("cpu_gguf_rows.zig"); +const decodeBlock = gguf_rows.decodeBlock; +const decodeTensor = gguf_rows.decodeTensor; +const project = gguf_rows.project; +const projectOn = gguf_rows.projectOn; +const projectReference = gguf_rows.projectReference; + +test "GGUF block values match the independent FP64 source definition, including centered signed zeros" { + const ref = core.gguf_source_reference; + for ([_]g.TensorKind{ .q4_k, .q6_k, .q5_0 }) |kind| { + const block = kind.block(); + for ([_]u16{ 0, 0x8000, 0x3c00, 0xbc00, 0x0400, 0x7bff }) |scale| { + var bytes: [210]u8 = undefined; + for (&bytes, 0..) |*v, i| v.* = @intCast((i * 13 + 7) % 256); + const at: usize = if (kind == .q6_k) 208 else 0; + std.mem.writeInt(u16, bytes[at..][0..2], scale, .little); + if (kind == .q4_k) std.mem.writeInt(u16, bytes[2..4], 0x3400, .little); + var values: [256]f32 = undefined; + try decodeBlock(kind, bytes[0..block.bytes], values[0..block.values]); + for (values[0..block.values], 0..) |value, i| { + const expected: f32 = @floatCast(try ref.value(kind, bytes[0..block.bytes], i)); + try std.testing.expectEqual(@as(u32, @bitCast(expected)), @as(u32, @bitCast(value))); + } + } + } +} + +test "GGUF projections equal expanded source weights and reject bad scales before writing" { + const ref = core.gguf_source_reference; + for ([_]g.TensorKind{ .q4_k, .q6_k, .q5_0 }) |kind| { + const block = kind.block(); + var storage: [3 * 8 * 210]u8 = undefined; + const bytes = storage[0 .. 3 * (256 / block.values) * block.bytes]; + for (bytes, 0..) |*v, i| v.* = @intCast((i * 17 + 11) % 256); + var weights: [3 * 256]f32 = undefined; + for (0..bytes.len / block.bytes) |b| { + const part = bytes[b * block.bytes ..][0..block.bytes]; + const at: usize = if (kind == .q6_k) 208 else 0; + std.mem.writeInt(u16, part[at..][0..2], if (b % 2 == 0) 0x3c00 else 0xbc00, .little); + if (kind == .q4_k) std.mem.writeInt(u16, part[2..4], 0x3400, .little); + for (0..block.values) |i| weights[b * block.values + i] = @floatCast(try ref.value(kind, part, i)); + } + var input: [9 * 256]f32 = undefined; + for (&input, 0..) |*v, i| v.* = @as(f32, @floatFromInt(@as(i32, @intCast(i % 17)) - 8)) / 16; + input[0] = -0.0; + const t = g.Tensor{ .name = "matrix", .kind = kind, .rank = 2, .shape = .{ 256, 3, 1, 1 }, .offset = 0, .len = bytes.len, .bytes = bytes }; + for ([_]bool{ true, false }) |rounded| for ([_]usize{ 1, 2, 8, 9 }) |count| { + var expected: [27]f32 = undefined; + var actual: [27]f32 = undefined; + const x = input[0 .. count * 256]; + const want = expected[0 .. count * 3]; + const got = actual[0 .. count * 3]; + try rows.project(.{ .dtype = .f32, .rank = 2, .shape = .{ 3, 256, 1, 1, 1 }, .bytes = std.mem.sliceAsBytes(&weights) }, x, want, count, 256, 3, rounded); + try project(t, x, got, count, rounded); + try std.testing.expectEqualSlices(u8, std.mem.sliceAsBytes(want), std.mem.sliceAsBytes(got)); + }; + const scale_at = bytes.len - block.bytes + (if (kind == .q6_k) @as(usize, 208) else 0); + std.mem.writeInt(u16, bytes[scale_at..][0..2], 0x7c00, .little); + var unchanged: [6]f32 = @splat(1234); + try std.testing.expectError(error.NonFiniteQuantScale, project(t, input[0 .. 2 * 256], &unchanged, 2, true)); + for (unchanged) |v| try std.testing.expectEqual(@as(f32, 1234), v); + } +} + +test "selected GGUF embedding row decodes without using the adjacent row" { + const views = @import("cpu_gguf_views.zig"); + var bytes: [2 * 144]u8 = undefined; + for (&bytes, 0..) |*v, i| v.* = @truncate(i * 11 + 5); + for (0..2) |row| { + std.mem.writeInt(u16, bytes[row * 144 ..][0..2], if (row == 0) 0x3c00 else 0xbc00, .little); + std.mem.writeInt(u16, bytes[row * 144 + 2 ..][0..2], 0x3400, .little); + } + const t = g.Tensor{ .name = "embedding", .kind = .q4_k, .rank = 2, .shape = .{ 256, 2, 1, 1 }, .offset = 0, .len = bytes.len, .bytes = &bytes }; + const one = try views.row(t, 1); + var values: [256]f32 = undefined; + try decodeTensor(one, &values); + for (values, 0..) |v, i| { + const expected: f32 = @floatCast(try core.gguf_source_reference.value(.q4_k, bytes[144..], i)); + try std.testing.expectEqual(@as(u32, @bitCast(expected)), @as(u32, @bitCast(v))); + } + try std.testing.expectError(error.BadLingGgufRow, views.row(t, 2)); +} + +test "multi-threaded GGUF projections match scalar reference bit-for-bit across 1..8 threads" { + for ([_]g.TensorKind{ .q4_k, .q6_k, .q5_0 }) |kind| { + const block = kind.block(); + const width: usize = 256; + const n: usize = 13; + var storage: [13 * 8 * 210]u8 = undefined; + const bytes = storage[0 .. n * (width / block.values) * block.bytes]; + for (bytes, 0..) |*v, i| v.* = @intCast((i * 23 + 19) % 256); + for (0..bytes.len / block.bytes) |b| { + const part = bytes[b * block.bytes ..][0..block.bytes]; + const at: usize = if (kind == .q6_k) 208 else 0; + std.mem.writeInt(u16, part[at..][0..2], if (b % 3 == 0) 0x3c00 else if (b % 3 == 1) 0xbc00 else 0x8000, .little); + if (kind == .q4_k) std.mem.writeInt(u16, part[2..4], 0x3400, .little); + } + var input: [2 * width]f32 = undefined; + for (&input, 0..) |*v, i| v.* = @as(f32, @floatFromInt(@as(i32, @intCast(i % 19)) - 9)) / 11; + const t = g.Tensor{ .name = "mt", .kind = kind, .rank = 2, .shape = .{ width, n, 1, 1 }, .offset = 0, .len = bytes.len, .bytes = bytes }; + for ([_]usize{ 1, 2 }) |count| { + var expected: [2 * n]f32 = undefined; + var actual: [2 * n]f32 = undefined; + try projectReference(t, input[0 .. count * width], expected[0 .. count * n], count, true); + for ([_]usize{ 1, 2, 4, 8 }) |threads| { + try projectOn(t, input[0 .. count * width], actual[0 .. count * n], count, true, threads); + try std.testing.expectEqualSlices(u8, std.mem.sliceAsBytes(expected[0 .. count * n]), std.mem.sliceAsBytes(actual[0 .. count * n])); + } + } + } +} diff --git a/zig/src/families/ling/cpu_gguf_values.zig b/zig/src/families/ling/cpu_gguf_values.zig new file mode 100644 index 00000000000..25ae0101c32 --- /dev/null +++ b/zig/src/families/ling/cpu_gguf_values.zig @@ -0,0 +1,78 @@ +//! Small source views and MLA reconstruction; only the six split MLA tensors may become cached F32 matrices. +const std = @import("std"); +const g = @import("core").gguf; +const q = @import("cpu_gguf_rows.zig"); +const views = @import("cpu_gguf_views.zig"); + +pub fn small(a: std.mem.Allocator, v: views.View, shape: []const usize) ![]f32 { + if (v.tensor.kind != .f32) return error.UnsupportedLingGgufValueView; + var expected: [3]usize = @splat(1); + var rank: usize = v.name.rank; + switch (v.name.role) { + .vector => expected[0] = @intCast(v.name.dims[0]), + .positive_exp_decay => { + expected[0] = 16; + rank = 1; + }, + .convolution => for (0..3) |i| { + expected[i] = @intCast(v.name.dims[2 - i]); + }, + else => return error.UnsupportedLingGgufValueView, + } + if (shape.len != rank or !std.mem.eql(usize, shape, expected[0..rank])) return error.BadLingGgufTensorShape; + const count = v.tensor.bytes.len / 4; + const out = try a.alloc(f32, count); + errdefer a.free(out); + try q.decodeTensor(v.tensor, out); + return out; +} + +pub fn joinMla(a: std.mem.Allocator, key: g.Tensor, value: g.Tensor) ![]f32 { + if (key.rank != 3 or value.rank != 3 or !std.mem.eql(u64, key.shape[0..3], &.{ 128, 512, 16 }) or !std.mem.eql(u64, value.shape[0..3], &.{ 512, 128, 16 })) return error.BadLingGgufTensorShape; + var scratch = std.heap.ArenaAllocator.init(a); + defer scratch.deinit(); + const k = try scratch.allocator().alloc(f32, 16 * 512 * 128); + const v = try scratch.allocator().alloc(f32, k.len); + try q.decodeTensor(key, k); + try q.decodeTensor(value, v); + const result = try a.alloc(f32, 16 * 256 * 512); + for (0..16) |h| for (0..128) |n| for (0..512) |j| { + result[(h * 256 + n) * 512 + j] = k[(h * 512 + j) * 128 + n]; + result[(h * 256 + 128 + n) * 512 + j] = v[(h * 128 + n) * 512 + j]; + }; + return result; +} + +pub fn embedding(d: *const g.Document, ids: []const u32, output: []f32) !void { + const t = d.getTensor("token_embd.weight") orelse return error.MissingLingGgufTensor; + if (output.len != try std.math.mul(usize, ids.len, 1536)) return error.BadLingGgufTensorShape; + for (ids) |id| if (id >= 157184) return error.InvalidToken; + for (ids, 0..) |id, i| { + const one = try views.row(t, id); + try q.decodeTensor(one, output[i * 1536 ..][0..1536]); + } +} + +test "split MLA views reconstruct each head without mixing key and value coordinates" { + const a = std.testing.allocator; + const count = 16 * 512 * 128; + const k = try a.alloc(f32, count); + defer a.free(k); + const v = try a.alloc(f32, count); + defer a.free(v); + for (k, v, 0..) |*key, *value, i| { + key.* = @floatFromInt(i); + value.* = -@as(f32, @floatFromInt(i)); + } + const key = g.Tensor{ .name = "key", .kind = .f32, .rank = 3, .shape = .{ 128, 512, 16, 1 }, .offset = 0, .len = count * 4, .bytes = std.mem.sliceAsBytes(k) }; + const value = g.Tensor{ .name = "value", .kind = .f32, .rank = 3, .shape = .{ 512, 128, 16, 1 }, .offset = 0, .len = count * 4, .bytes = std.mem.sliceAsBytes(v) }; + const joined = try joinMla(a, key, value); + defer a.free(joined); + for (0..16) |h| for (0..128) |n| for (0..512) |j| { + try std.testing.expectEqual(k[(h * 512 + j) * 128 + n], joined[(h * 256 + n) * 512 + j]); + try std.testing.expectEqual(v[(h * 128 + n) * 512 + j], joined[(h * 256 + 128 + n) * 512 + j]); + }; + var bad = key; + bad.shape[0] = 127; + try std.testing.expectError(error.BadLingGgufTensorShape, joinMla(a, bad, value)); +} diff --git a/zig/src/families/ling/cpu_gguf_views.zig b/zig/src/families/ling/cpu_gguf_views.zig new file mode 100644 index 00000000000..51dae2b0dfe --- /dev/null +++ b/zig/src/families/ling/cpu_gguf_views.zig @@ -0,0 +1,79 @@ +//! Source view selection; expert stacks are sliced without copying quantized payloads. +const std = @import("std"); +const g = @import("core").gguf; +const names = @import("gguf_names.zig"); +pub const View = struct { tensor: g.Tensor, name: names.Name }; + +pub fn expert(t: g.Tensor, index: usize) !g.Tensor { + if (t.rank != 3 or t.shape[2] != 128 or index >= 128 or t.bytes.len != t.len or t.len % 128 != 0) return error.BadLingGgufExpert; + const bytes = t.len / 128; + var out = t; + out.rank = 2; + out.shape[2] = 1; + out.offset = std.math.add(usize, out.offset, index * bytes) catch return error.BadLingGgufExpert; + out.len = bytes; + out.bytes = t.bytes[index * bytes ..][0..bytes]; + return out; +} + +pub fn row(t: g.Tensor, index: usize) !g.Tensor { + if (t.rank != 2 or index >= t.shape[1] or t.shape[1] == 0 or t.bytes.len != t.len or t.len % t.shape[1] != 0) return error.BadLingGgufRow; + const bytes = t.len / @as(usize, @intCast(t.shape[1])); + var out = t; + out.shape[1] = 1; + out.offset = std.math.add(usize, out.offset, index * bytes) catch return error.BadLingGgufRow; + out.len = bytes; + out.bytes = t.bytes[index * bytes ..][0..bytes]; + return out; +} + +pub fn resolve(d: *const g.Document, plan: []const names.Name, key: []const u8) !View { + var buffer: [256]u8 = undefined; + var template = key; + var index: ?usize = null; + const marker = ".mlp.experts."; + if (std.mem.indexOf(u8, key, marker)) |at| { + const first = at + marker.len; + const end = first + (std.mem.indexOfScalar(u8, key[first..], '.') orelse return error.BadLingGgufExpert); + index = std.fmt.parseInt(usize, key[first..end], 10) catch return error.BadLingGgufExpert; + template = try std.fmt.bufPrint(&buffer, "{s}{{id}}{s}", .{ key[0..first], key[end..] }); + } + for (plan) |n| if (std.mem.eql(u8, n.native, template)) { + var t = d.getTensor(n.source) orelse return error.MissingLingGgufTensor; + if (index) |id| { + if (n.role != .experts) return error.BadLingGgufExpert; + t = try expert(t, id); + } else if (n.role == .experts) return error.BadLingGgufExpert; + return .{ .tensor = t, .name = n }; + }; + return error.MissingLingGgufTensor; +} + +test "expert slices preserve source rows and reject invalid stacks and indices" { + var bytes: [128 * 144]u8 = undefined; + for (&bytes, 0..) |*v, i| v.* = @truncate(i); + const t = g.Tensor{ .name = "stack", .kind = .q4_k, .rank = 3, .shape = .{ 256, 1, 128, 1 }, .offset = 32, .len = bytes.len, .bytes = &bytes }; + const one = try expert(t, 127); + try std.testing.expectEqual(@as(u8, 2), one.rank); + try std.testing.expectEqualSlices(u8, bytes[127 * 144 ..], one.bytes); + try std.testing.expectEqual(@as(usize, 32 + 127 * 144), one.offset); + try std.testing.expectError(error.BadLingGgufExpert, expert(t, 128)); + var malformed = t; + malformed.shape[2] = 127; + try std.testing.expectError(error.BadLingGgufExpert, expert(malformed, 0)); +} + +test "native expert lookup substitutes only a checked numeric expert index" { + const a = std.testing.allocator; + var bytes: [128 * 144]u8 = @splat(0); + var tensors = [_]g.Tensor{.{ .name = "blk.1.ffn_gate_exps.weight", .kind = .q4_k, .rank = 3, .shape = .{ 256, 1, 128, 1 }, .offset = 0, .len = bytes.len, .bytes = &bytes }}; + var doc = g.Document{ .gpa = a, .bytes = &bytes, .metadata = &.{}, .tensors = &tensors, .data_offset = 0, .alignment = 32 }; + defer doc.names.deinit(a); + try doc.names.put(a, tensors[0].name, 0); + const plan = [_]names.Name{.{ .source = tensors[0].name, .native = "model.layers.1.mlp.experts.{id}.gate_proj.weight", .role = .experts, .rank = 3, .dims = .{ 256, 1, 128 } }}; + const found = try resolve(&doc, &plan, "model.layers.1.mlp.experts.127.gate_proj.weight"); + try std.testing.expectEqual(@as(usize, 144), found.tensor.bytes.len); + try std.testing.expectEqual(@intFromPtr(&bytes) + 127 * 144, @intFromPtr(found.tensor.bytes.ptr)); + try std.testing.expectError(error.BadLingGgufExpert, resolve(&doc, &plan, "model.layers.1.mlp.experts.128.gate_proj.weight")); + try std.testing.expectError(error.BadLingGgufExpert, resolve(&doc, &plan, "model.layers.1.mlp.experts.-1.gate_proj.weight")); +} diff --git a/zig/src/families/ling/cpu_mla.zig b/zig/src/families/ling/cpu_mla.zig new file mode 100644 index 00000000000..b142f9e79ff --- /dev/null +++ b/zig/src/families/ling/cpu_mla.zig @@ -0,0 +1,172 @@ +//! Causal Ling MLA mixer with F32 accumulators and BF16 activation boundaries, without a graphics backend. +const std = @import("std"); +const rows_ = @import("cpu_rows.zig"); +const lat: u32 = 512; +const rope_dim: u32 = 64; +const nope: u32 = 128; +const vd: u32 = 128; +const key: u32 = lat + rope_dim; +const qd: u32 = nope + rope_dim; +const nfreq: u32 = rope_dim / 2; +const round32 = rows_.round; +const sig = rows_.sigmoid; +pub const Shape = struct { + heads: u32, + eps: f32, + theta: f64, + pub fn scale(_: Shape) f32 { + return 1 / @sqrt(@as(f32, qd)); + } +}; +fn rotate(out: []f32, z: []const f32, pos: u32, theta: f64) void { + for (0..nfreq) |i| { + const angle = @as(f64, @floatFromInt(pos)) / std.math.pow(f64, theta, @as(f64, @floatFromInt(2 * i)) / rope_dim); + const c: f32 = @floatCast(@cos(angle)); + const sn: f32 = @floatCast(@sin(angle)); + out[i] = z[2 * i] * c - z[2 * i + 1] * sn; + out[nfreq + i] = z[2 * i + 1] * c + z[2 * i] * sn; + } +} +pub const Cache = struct { + k_nope: []f32, + value: []f32, + rope: []f32, + capacity: u32, + position: u32 = 0, + + pub fn init(a: std.mem.Allocator, heads: u32, capacity: u32) !Cache { + return .{ .k_nope = try a.alloc(f32, @as(usize, capacity) * heads * nope), .value = try a.alloc(f32, @as(usize, capacity) * heads * vd), .rope = try a.alloc(f32, @as(usize, capacity) * rope_dim), .capacity = capacity }; + } +}; + +fn mixImpl( + alloc: std.mem.Allocator, + y: []f32, + q: []const f32, + kv: []const f32, + w_rms: []const f32, + kvb: []const f32, + g: []const f32, + s: Shape, + rows: u32, + pos0: u32, + cache: ?*Cache, +) !void { + const H = s.heads; + const T = rows; + const past = if (cache) |c| c.position else 0; + const total = past + T; + if (cache) |c| if (past > c.capacity or T > c.capacity - past) return error.CpuContextCapacity; + std.debug.assert(y.len == T * H * vd); + std.debug.assert(q.len == T * H * qd); + std.debug.assert(kv.len == T * key); + std.debug.assert(w_rms.len == lat); + std.debug.assert(kvb.len == H * (nope + vd) * lat); + std.debug.assert(g.len == T * H); + + const lat_t = try alloc.alloc(f32, T * lat); + defer alloc.free(lat_t); + const krope = if (cache) |c| c.rope[0 .. total * rope_dim] else try alloc.alloc(f32, T * rope_dim); + defer if (cache == null) alloc.free(krope); + const qrope = try alloc.alloc(f32, T * H * rope_dim); + defer alloc.free(qrope); + const k_nope = if (cache) |c| c.k_nope[0 .. total * H * nope] else try alloc.alloc(f32, T * H * nope); + defer if (cache == null) alloc.free(k_nope); + const v = if (cache) |c| c.value[0 .. total * H * vd] else try alloc.alloc(f32, T * H * vd); + defer if (cache == null) alloc.free(v); + + const eps: f32 = s.eps; + for (0..T) |t| { + var ss: f32 = 0; + for (0..lat) |i| { + const x: f32 = kv[t * key + i]; + ss += x * x; + } + const rstd = 1.0 / @sqrt(ss / @as(f32, lat) + eps); + for (0..lat) |i| { + const yn = @as(f32, kv[t * key + i]) * rstd; + lat_t[t * lat + i] = round32(round32(yn) * w_rms[i]); + } + var z: [rope_dim]f32 = undefined; + var out: [rope_dim]f32 = undefined; + for (0..rope_dim) |i| z[i] = kv[t * key + lat + i]; + rotate(&out, &z, pos0 + @as(u32, @intCast(t)), s.theta); + for (0..rope_dim) |i| krope[(past + t) * rope_dim + i] = round32(out[i]); + for (0..H) |h| { + for (0..rope_dim) |i| z[i] = q[(t * H + h) * qd + nope + i]; + rotate(&out, &z, pos0 + @as(u32, @intCast(t)), s.theta); + for (0..rope_dim) |i| qrope[(t * H + h) * rope_dim + i] = round32(out[i]); + } + } + + for (0..H) |h| { + for (0..T) |t| { + for (0..nope) |d| { + var acc: f32 = 0; + const w0 = ((h * (nope + vd) + d) * lat); + for (0..lat) |c| acc += lat_t[t * lat + c] * kvb[w0 + c]; + k_nope[((past + t) * H + h) * nope + d] = round32(acc); + } + for (0..vd) |d| { + var acc: f32 = 0; + const w0 = ((h * (nope + vd) + nope + d) * lat); + for (0..lat) |c| acc += lat_t[t * lat + c] * kvb[w0 + c]; + v[((past + t) * H + h) * vd + d] = round32(acc); + } + } + } + + const sc = s.scale(); + const scores = try alloc.alloc(f32, H * T * total); + defer alloc.free(scores); + for (0..H) |h| { + for (0..T) |t| { + for (0..total) |k| { + if (k > past + t) { + scores[(h * T + t) * total + k] = -std.math.inf(f32); + continue; + } + var p: f32 = 0; + const qb = (t * H + h) * qd; + const kb = (k * H + h) * nope; + for (0..nope) |d| p += @as(f32, q[qb + d]) * k_nope[kb + d]; + const qr = (t * H + h) * rope_dim; + for (0..rope_dim) |d| p += qrope[qr + d] * krope[k * rope_dim + d]; + scores[(h * T + t) * total + k] = p * sc; + } + } + } + + for (0..H) |h| { + for (0..T) |t| { + var m: f32 = -std.math.inf(f32); + const row = scores[(h * T + t) * total ..][0..total]; + for (0..past + t + 1) |k| m = @max(m, row[k]); + var den: f32 = 0; + for (0..past + t + 1) |k| { + row[k] = @exp(row[k] - m); + den += row[k]; + } + for (0..past + t + 1) |k| row[k] /= den; + var o: [vd]f32 = @splat(0); + for (0..past + t + 1) |k| { + const a = row[k]; + const vb = (k * H + h) * vd; + for (0..vd) |d| o[d] += a * v[vb + d]; + } + const gate = round32(sig(g[t * H + h])); + for (0..vd) |d| y[(t * H + h) * vd + d] = round32(round32(o[d]) * gate); + } + } + if (cache) |c| c.position = total; +} + +/// Initial-history reference path retained for direct comparison with persistent decode. +pub fn mix(a: std.mem.Allocator, y: []f32, q: []const f32, kv: []const f32, w: []const f32, b: []const f32, g: []const f32, shape: Shape, rows: u32, pos0: u32) !void { + return mixImpl(a, y, q, kv, w, b, g, shape, rows, pos0, null); +} + +/// Append only new K/V rows; old projections and attention state are never recomputed. +pub fn append(a: std.mem.Allocator, y: []f32, q: []const f32, kv: []const f32, w: []const f32, b: []const f32, g: []const f32, shape: Shape, rows: u32, cache: *Cache) !void { + return mixImpl(a, y, q, kv, w, b, g, shape, rows, cache.position, cache); +} diff --git a/zig/src/families/ling/cpu_rows.zig b/zig/src/families/ling/cpu_rows.zig new file mode 100644 index 00000000000..bc207466f9b --- /dev/null +++ b/zig/src/families/ling/cpu_rows.zig @@ -0,0 +1,141 @@ +//! Portable BF16/F32 dense rows and RMS normalization for the Ling CPU path. +const std = @import("std"); +const st = @import("core").safetensors; +const rounding = @import("bf16_round"); +pub const Tensor = st.Tensor; + +pub fn value(t: st.Tensor, i: usize) f32 { + return switch (t.dtype) { + .bf16 => rounding.value(std.mem.readInt(u16, t.bytes[i * 2 ..][0..2], .little)), + .f32 => @bitCast(std.mem.readInt(u32, t.bytes[i * 4 ..][0..4], .little)), + else => unreachable, + }; +} + +pub fn check(t: st.Tensor, shape: []const usize) !void { + if (t.dtype != .bf16 and t.dtype != .f32) return error.UnsupportedCpuDType; + if (t.rank != shape.len or !std.mem.eql(usize, t.shape[0..t.rank], shape)) return error.CpuTensorShape; + var n: usize = t.dtype.size(); + for (shape) |d| n = try std.math.mul(usize, n, d); + if (t.bytes.len != n) return error.CpuTensorShape; +} + +pub fn round(x: f32) f32 { + return rounding.round32(x); +} + +pub fn sigmoid(x: f32) f32 { + if (x >= 0) return 1 / (1 + @exp(-x)); + const e = @exp(x); + return e / (1 + e); +} + +pub fn project(t: st.Tensor, x: []const f32, y: []f32, rows: usize, width: usize, outputs: usize, rounded: bool) !void { + try check(t, &.{ outputs, width }); + if (rows == 0 or width == 0 or outputs == 0 or x.len != try std.math.mul(usize, rows, width) or + y.len != try std.math.mul(usize, rows, outputs)) return error.CpuRowShape; + projectRange(t, x, y, rows, width, outputs, rounded, 0, outputs); +} + +// Whole shapes and byte spans are checked by every caller before this dispatcher. +pub fn projectRange(t: st.Tensor, x: []const f32, y: []f32, rows: usize, width: usize, outputs: usize, rounded: bool, lo: usize, hi: usize) void { + switch (t.dtype) { + .bf16 => projectRangeTyped(u16, t.bytes.ptr, x, y, rows, width, outputs, rounded, lo, hi), + .f32 => projectRangeTyped(u32, t.bytes.ptr, x, y, rows, width, outputs, rounded, lo, hi), + else => unreachable, + } +} +fn nativeLittle(comptime T: type, v: T) T { + return if (@import("builtin").cpu.arch.endian() == .little) v else @byteSwap(v); +} +fn weights8(comptime W: type, p: [*]align(1) const W) @Vector(8, f32) { + const loaded: @Vector(8, W) = @as(*align(1) const [8]W, @ptrCast(p)).*; + const little = if (@import("builtin").cpu.arch.endian() == .little) loaded else @byteSwap(loaded); + if (W == u16) { + const widened: @Vector(8, u32) = @intCast(little); + return @bitCast(widened << @splat(16)); + } + return @bitCast(little); +} +fn projectRangeTyped(comptime W: type, bytes: [*]const u8, x: []const f32, y: []f32, rows: usize, width: usize, outputs: usize, rounded: bool, lo: usize, hi: usize) void { + const weights: [*]align(1) const W = @ptrCast(bytes); + const vector_end = width & ~@as(usize, 7); + for (0..rows) |r| { + const input = x.ptr + r * width; + const output = y.ptr + r * outputs; + for (lo..hi) |n| { + const row = weights + n * width; + var sum: @Vector(8, f32) = @splat(0); + var i: usize = 0; + // i cannot wrap: vector_end is within the validated row, rounded down to 8. + while (i < vector_end) : (i +%= 8) { + const w = weights8(W, row + i); + const a: @Vector(8, f32) = @as(*align(1) const [8]f32, @ptrCast(input + i)).*; + sum = @mulAdd(@Vector(8, f32), a, w, sum); + } + var acc: f32 = @reduce(.Add, sum); + while (i < width) : (i += 1) { + const bits = nativeLittle(W, row[i]); + const v: f32 = if (W == u16) rounding.value(bits) else @bitCast(bits); + acc = @mulAdd(f32, input[i], v, acc); + } + output[n] = if (rounded) round(acc) else acc; + } + } +} + +/// Split output columns only: each dot retains the same reduction order at every thread count. +pub fn projectOn(t: st.Tensor, x: []const f32, y: []f32, rows: usize, width: usize, outputs: usize, rounded: bool, threads: usize) !void { + if (threads == 0 or threads > 8) return error.CpuThreadCount; + try check(t, &.{ outputs, width }); + if (rows == 0 or width == 0 or outputs == 0 or x.len != try std.math.mul(usize, rows, width) or y.len != try std.math.mul(usize, rows, outputs)) return error.CpuRowShape; + const n = @min(threads, outputs); + var workers: [7]std.Thread = undefined; + var made: usize = 0; + defer for (workers[0..made]) |worker| worker.join(); + for (0..n - 1) |i| { + workers[made] = try std.Thread.spawn(.{}, projectRange, .{ t, x, y, rows, width, outputs, rounded, i * outputs / n, (i + 1) * outputs / n }); + made += 1; + } + projectRange(t, x, y, rows, width, outputs, rounded, (n - 1) * outputs / n, outputs); +} + +pub fn norm(x: []const f32, w: []const f32, y: []f32, rows: usize, width: usize, eps: f32) !void { + if (width == 0 or w.len != width or x.len != rows * width or y.len != x.len) return error.CpuRowShape; + for (0..rows) |r| { + const row = x[r * width ..][0..width]; + var ss: f32 = 0; + for (row) |v| ss += v * v; + const inv = 1 / @sqrt(ss / @as(f32, @floatFromInt(width)) + eps); + for (row, w, y[r * width ..][0..width]) |v, weight, *out| out.* = round(round(v * inv) * weight); + } +} + +test "dense rows reject malformed views and preserve nonfinite inputs" { + const bytes = [_]u8{ 0x80, 0x3f, 0x00, 0x40 }; + const w = st.Tensor{ .dtype = .bf16, .rank = 2, .shape = .{ 1, 2, 1, 1, 1 }, .bytes = &bytes }; + var out: [1]f32 = undefined; + try project(w, &.{ 3, 4 }, &out, 1, 2, 1, false); + try std.testing.expectEqual(@as(f32, 11), out[0]); + try std.testing.expectError(error.CpuTensorShape, project(w, &.{3}, &out, 1, 1, 1, false)); + try project(w, &.{ std.math.nan(f32), 4 }, &out, 1, 2, 1, false); + try std.testing.expect(std.math.isNan(out[0])); +} + +test "unaligned BF16 vector loads preserve all encodings including signed zero and NaN payloads" { + var bytes: [17]u8 = undefined; + const tensor = Tensor{ .dtype = .bf16, .rank = 2, .shape = .{ 1, 8, 1, 1, 1 }, .bytes = bytes[1..] }; + for (0..8192) |group| { + for (0..8) |lane| std.mem.writeInt(u16, bytes[1 + lane * 2 ..][0..2], @intCast(group * 8 + lane), .little); + const got: [8]f32 = weights8(u16, @ptrCast(bytes[1..].ptr)); + for (got, 0..) |v, lane| try std.testing.expectEqual(@as(u32, @bitCast(value(tensor, lane))), @as(u32, @bitCast(v))); + } +} + +test "unaligned F32 vector loads preserve exact payload bits" { + const bits = [_]u32{ 0, 0x80000000, 0x3f800000, 0xbf800000, 0x00000001, 0x7f800000, 0x7fc00123, 0x7f800001 }; + var bytes: [33]u8 = undefined; + for (bits, 0..) |v, i| std.mem.writeInt(u32, bytes[1 + i * 4 ..][0..4], v, .little); + const got: [8]f32 = weights8(u32, @ptrCast(bytes[1..].ptr)); + for (got, bits) |v, want| try std.testing.expectEqual(want, @as(u32, @bitCast(v))); +} diff --git a/zig/src/families/ling/cpu_state.zig b/zig/src/families/ling/cpu_state.zig new file mode 100644 index 00000000000..3dafabfd6ca --- /dev/null +++ b/zig/src/families/ling/cpu_state.zig @@ -0,0 +1,143 @@ +//! Per-stream CPU recurrent state and MLA cache; weights and temporary rows stay outside this arena. +const std = @import("std"); +const config = @import("config.zig"); +const mla = @import("cpu_mla.zig"); +pub const Kda = struct { matrix: []f32, history: [][3]f32 }; +pub const Layer = union(enum) { kda: Kda, mla: mla.Cache }; +pub const State = struct { + arena: std.heap.ArenaAllocator, + layers: []Layer, + capacity: u32, + position: u32 = 0, + poisoned: bool = false, + + pub fn init(a: std.mem.Allocator, c: config.Config, capacity: u32) !State { + if (capacity == 0 or capacity > 4096) return error.CpuContextCapacity; + var arena = std.heap.ArenaAllocator.init(a); + errdefer arena.deinit(); + const alloc = arena.allocator(); + const layers = try alloc.alloc(Layer, c.layers); + for (layers, 0..) |*layer, i| { + layer.* = if (c.kind(@intCast(i)) == .kda) .{ .kda = .{ + .matrix = try alloc.alloc(f32, c.kda_heads * 128 * 128), + .history = try alloc.alloc([3]f32, 3 * c.kda_heads * 128), + } } else .{ .mla = try mla.Cache.init(alloc, c.mla_heads, capacity) }; + } + var s = State{ .arena = arena, .layers = layers, .capacity = capacity }; + s.reset(); + return s; + } + + pub fn reset(self: *State) void { + for (self.layers) |*layer| switch (layer.*) { + .kda => |k| { + @memset(k.matrix, 0); + @memset(k.history, .{ 0, 0, 0 }); + }, + .mla => |*m| m.position = 0, + }; + self.position = 0; + self.poisoned = false; + } + + /// Copy only live cache rows; dead MLA storage is never read or published. + pub fn copyFrom(self: *State, source: *const State) !void { + if (source.position > self.capacity or source.position > source.capacity or self.layers.len != source.layers.len) + return error.CpuStateShape; + for (self.layers, source.layers) |*dst, src| { + if (std.meta.activeTag(dst.*) != std.meta.activeTag(src)) return error.CpuStateShape; + switch (src) { + .kda => |k| { + if (dst.kda.matrix.len != k.matrix.len or dst.kda.history.len != k.history.len) + return error.CpuStateShape; + }, + .mla => |m| { + if (m.capacity != source.capacity or dst.mla.capacity != self.capacity or + dst.mla.k_nope.len / dst.mla.capacity != m.k_nope.len / m.capacity or + dst.mla.value.len / dst.mla.capacity != m.value.len / m.capacity or + dst.mla.rope.len / dst.mla.capacity != m.rope.len / m.capacity or m.position > self.capacity) + return error.CpuStateShape; + }, + } + } + for (self.layers, source.layers) |*dst, src| switch (src) { + .kda => |k| { + @memcpy(dst.kda.matrix, k.matrix); + @memcpy(dst.kda.history, k.history); + }, + .mla => |m| { + const n = m.position; + const keys = m.k_nope.len / m.capacity * n; + const values = m.value.len / m.capacity * n; + const rope = m.rope.len / m.capacity * n; + @memcpy(dst.mla.k_nope[0..keys], m.k_nope[0..keys]); + @memcpy(dst.mla.value[0..values], m.value[0..values]); + @memcpy(dst.mla.rope[0..rope], m.rope[0..rope]); + dst.mla.position = n; + }, + }; + self.position = source.position; + self.poisoned = source.poisoned; + } + + pub fn deinit(self: *State) void { + self.arena.deinit(); + } +}; + +test "CPU committed state restores recurrent values and only live attention rows" { + const a = std.testing.allocator; + var arena = std.heap.ArenaAllocator.init(a); + defer arena.deinit(); + const alloc = arena.allocator(); + const source_layers = try alloc.alloc(Layer, 2); + const target_layers = try alloc.alloc(Layer, 2); + for ([_][]Layer{ source_layers, target_layers }) |layers| { + layers[0] = .{ .kda = .{ + .matrix = try alloc.alloc(f32, 4), + .history = try alloc.alloc([3]f32, 2), + } }; + layers[1] = .{ .mla = try mla.Cache.init(alloc, 1, 3) }; + } + var src = State{ .arena = undefined, .layers = source_layers, .capacity = 3, .position = 1 }; + var dst = State{ .arena = undefined, .layers = target_layers, .capacity = 3 }; + @memset(source_layers[0].kda.matrix, 7); + @memset(source_layers[0].kda.history, .{ 1, 2, 3 }); + @memset(source_layers[1].mla.k_nope, 11); + @memset(source_layers[1].mla.value, 12); + @memset(source_layers[1].mla.rope, 13); + source_layers[1].mla.position = 1; + @memset(target_layers[1].mla.k_nope, -1); + @memset(target_layers[1].mla.value, -1); + @memset(target_layers[1].mla.rope, -1); + try dst.copyFrom(&src); + try std.testing.expectEqual(@as(u32, 1), dst.position); + try std.testing.expectEqualSlices(f32, source_layers[0].kda.matrix, target_layers[0].kda.matrix); + try std.testing.expectEqualDeep(source_layers[0].kda.history, target_layers[0].kda.history); + try std.testing.expectEqualSlices(f32, source_layers[1].mla.k_nope[0..128], target_layers[1].mla.k_nope[0..128]); + try std.testing.expectEqual(@as(f32, -1), target_layers[1].mla.k_nope[128]); + try std.testing.expectEqual(@as(f32, 12), target_layers[1].mla.value[127]); + try std.testing.expectEqual(@as(f32, -1), target_layers[1].mla.value[128]); + try std.testing.expectEqual(@as(f32, 13), target_layers[1].mla.rope[63]); + try std.testing.expectEqual(@as(f32, -1), target_layers[1].mla.rope[64]); + dst.reset(); + try std.testing.expectEqual(@as(u32, 0), dst.position); + try std.testing.expectEqual(@as(f32, 0), target_layers[0].kda.matrix[0]); + const compact_layers = try alloc.alloc(Layer, 2); + compact_layers[0] = .{ .kda = .{ + .matrix = try alloc.alloc(f32, 4), + .history = try alloc.alloc([3]f32, 2), + } }; + compact_layers[1] = .{ .mla = try mla.Cache.init(alloc, 1, 1) }; + var compact = State{ .arena = undefined, .layers = compact_layers, .capacity = 1 }; + try compact.copyFrom(&src); + try dst.copyFrom(&compact); + try std.testing.expectEqual(@as(u32, 1), dst.position); + try std.testing.expectEqualSlices(f32, compact_layers[0].kda.matrix, target_layers[0].kda.matrix); + try std.testing.expectEqualSlices(f32, compact_layers[1].mla.k_nope, target_layers[1].mla.k_nope[0..128]); + src.poisoned = true; + try dst.copyFrom(&src); + try std.testing.expect(dst.poisoned); + dst.capacity = 2; + try std.testing.expectError(error.CpuStateShape, dst.copyFrom(&src)); +} diff --git a/zig/src/families/ling/gguf_names.zig b/zig/src/families/ling/gguf_names.zig new file mode 100644 index 00000000000..a55edb19fd2 --- /dev/null +++ b/zig/src/families/ling/gguf_names.zig @@ -0,0 +1,76 @@ +//! Source layouts for the tiny bailingmoe3 GGUF; transformed roles must not masquerade as native tensors. +const std = @import("std"); +pub const Role = enum { matrix, vector, convolution, positive_exp_decay, experts, mla_key_transposed, mla_value }; +pub const Name = struct { source: []const u8, native: []const u8, role: Role, rank: u8, dims: [3]u64 }; +const Builder = struct { + a: std.mem.Allocator, + entries: std.ArrayList(Name) = .empty, + fn add(b: *Builder, layer: ?usize, src: []const u8, dst: []const u8, dims: []const u64, role: Role) !void { + var shape: [3]u64 = @splat(1); + @memcpy(shape[0..dims.len], dims); + try b.entries.append(b.a, .{ .source = if (layer) |l| try std.fmt.allocPrint(b.a, "blk.{d}.{s}", .{ l, src }) else src, .native = if (layer) |l| try std.fmt.allocPrint(b.a, "model.layers.{d}.{s}", .{ l, dst }) else dst, .role = role, .rank = @intCast(dims.len), .dims = shape }); + } +}; +pub fn tiny(a: std.mem.Allocator) ![]Name { + var b = Builder{ .a = a }; + try b.add(null, "token_embd.weight", "model.word_embeddings.weight", &.{ 1536, 157184 }, .matrix); + try b.add(null, "output.weight", "lm_head.weight", &.{ 1536, 157184 }, .matrix); + try b.add(null, "output_norm.weight", "model.norm.weight", &.{1536}, .vector); + for (0..24) |l| { + try b.add(l, "attn_norm.weight", "input_layernorm.weight", &.{1536}, .vector); + try b.add(l, "ffn_norm.weight", "post_attention_layernorm.weight", &.{1536}, .vector); + if (l % 4 != 3) { + inline for (.{ "q", "k", "v" }) |part| { + try b.add(l, "attn_" ++ part ++ ".weight", "attention." ++ part ++ "_proj.weight", &.{ 1536, 2048 }, .matrix); + try b.add(l, "ssm_conv1d_" ++ part ++ ".weight", "attention." ++ part ++ "_conv1d.weight", &.{ 4, 1, 2048 }, .convolution); + } + try b.add(l, "attn_output.weight", "attention.o_proj.weight", &.{ 2048, 1536 }, .matrix); + try b.add(l, "ssm_f_a.weight", "attention.f_proj.weight", &.{ 1536, 2048 }, .matrix); + try b.add(l, "ssm_g_a.weight", "attention.g_proj.weight", &.{ 1536, 2048 }, .matrix); + try b.add(l, "ssm_beta.weight", "attention.b_proj.weight", &.{ 1536, 16 }, .matrix); + try b.add(l, "ssm_a", "attention.A_log", &.{ 1, 16 }, .positive_exp_decay); + try b.add(l, "ssm_dt.bias", "attention.dt_bias", &.{2048}, .vector); + try b.add(l, "ssm_norm.weight", "attention.o_norm.weight", &.{128}, .vector); + } else { + try b.add(l, "attn_q_a.weight", "attention.q_a_proj.weight", &.{ 1536, 256 }, .matrix); + try b.add(l, "attn_q_a_norm.weight", "attention.q_a_layernorm.weight", &.{256}, .vector); + try b.add(l, "attn_q_b.weight", "attention.q_b_proj.weight", &.{ 256, 3072 }, .matrix); + try b.add(l, "attn_kv_a_mqa.weight", "attention.kv_a_proj_with_mqa.weight", &.{ 1536, 576 }, .matrix); + try b.add(l, "attn_kv_a_norm.weight", "attention.kv_a_layernorm.weight", &.{512}, .vector); + try b.add(l, "attn_k_b.weight", "attention.kv_b_proj.weight", &.{ 128, 512, 16 }, .mla_key_transposed); + try b.add(l, "attn_v_b.weight", "attention.kv_b_proj.weight", &.{ 512, 128, 16 }, .mla_value); + try b.add(l, "attn_gate.weight", "attention.g_proj.weight", &.{ 1536, 16 }, .matrix); + try b.add(l, "attn_output.weight", "attention.dense.weight", &.{ 2048, 1536 }, .matrix); + } + if (l == 0) { + inline for (.{ "gate", "up" }) |part| try b.add(l, "ffn_" ++ part ++ ".weight", "mlp." ++ part ++ "_proj.weight", &.{ 1536, 4608 }, .matrix); + try b.add(l, "ffn_down.weight", "mlp.down_proj.weight", &.{ 4608, 1536 }, .matrix); + } else { + try b.add(l, "ffn_gate_inp.weight", "mlp.gate.weight", &.{ 1536, 128 }, .matrix); + try b.add(l, "exp_probs_b.bias", "mlp.gate.expert_bias", &.{128}, .vector); + inline for (.{ "gate", "up", "down" }) |part| { + const down = std.mem.eql(u8, part, "down"); + const k: u64 = if (down) 512 else 1536; + const n: u64 = if (down) 1536 else 512; + try b.add(l, "ffn_" ++ part ++ "_exps.weight", "mlp.experts.{id}." ++ part ++ "_proj.weight", &.{ k, n, 128 }, .experts); + try b.add(l, "ffn_" ++ part ++ "_shexp.weight", "mlp.shared_experts." ++ part ++ "_proj.weight", &.{ k, n }, .matrix); + } + } + } + return b.entries.toOwnedSlice(a); +} + +test "tiny GGUF plan covers 526 unique source identities and explicit transformed roles" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const entries = try tiny(arena.allocator()); + try std.testing.expectEqual(@as(usize, 526), entries.len); + var roles: [std.enums.values(Role).len]usize = @splat(0); + for (entries, 0..) |n, i| { + roles[@backingInt(n.role)] += 1; + for (entries[0..i]) |p| try std.testing.expect(!std.mem.eql(u8, p.source, n.source)); + } + try std.testing.expectEqual(@as(usize, 69), roles[@backingInt(Role.experts)]); + try std.testing.expectEqual(@as(usize, 18), roles[@backingInt(Role.positive_exp_decay)]); + try std.testing.expectEqual(@as(usize, 6), roles[@backingInt(Role.mla_key_transposed)]); +} diff --git a/zig/src/families/ling/kda.zig b/zig/src/families/ling/kda.zig index 20a9eab8387..53fd71fac6f 100644 --- a/zig/src/families/ling/kda.zig +++ b/zig/src/families/ling/kda.zig @@ -14,6 +14,7 @@ pub const Shape = struct { heads: u32, lower_bound: f32, eps: f32, + stored_rate: bool = false, pub fn of(c: *const config.Config) Shape { return .{ .heads = c.kda_heads, .lower_bound = c.lower_bound, .eps = c.eps }; @@ -57,11 +58,13 @@ fn mixAs( o_norm: []const f32, s: Shape, rows: u32, + history: ?[][3]T, ) void { const W = s.width(); const H = s.heads; const window_cap = 3 * max_width; - var windows: [window_cap][3]T = @splat(.{ 0, 0, 0 }); + var local: [window_cap][3]T = @splat(.{ 0, 0, 0 }); + const windows = history orelse local[0 .. 3 * W]; const scale: T = if (T == f32) q_scale else 1.0 / @sqrt(@as(T, @floatFromInt(dim))); const lower: T = @floatCast(s.lower_bound); const eps: T = @floatCast(s.eps); @@ -72,7 +75,7 @@ fn mixAs( var k: [dim]T = undefined; var v: [dim]T = undefined; var a: [dim]T = undefined; - const rate = @exp(@as(T, @floatCast(A_log[h]))); + const rate = if (s.stored_rate) @as(T, @floatCast(A_log[h])) else @exp(@as(T, @floatCast(A_log[h]))); for (0..dim) |d| { const ch_base = h * dim + d; inline for (.{ 0, 1, 2 }, .{ &q, &k, &v }, .{ conv_q, conv_k, conv_v }) |part, slot, cw| { @@ -142,7 +145,30 @@ pub fn mix( rows: u32, ) error{KdaWidthTooWide}!void { if (s.width() > max_width) return error.KdaWidthTooWide; - mixAs(f32, true, y, S, proj, fgate, braw, g2, conv_q, conv_k, conv_v, A_log, dt_bias, o_norm, s, rows); + mixAs(f32, true, y, S, proj, fgate, braw, g2, conv_q, conv_k, conv_v, A_log, dt_bias, o_norm, s, rows, null); +} + +/// Incremental KDA carries the exact three preceding projections beside its recurrent matrix. +pub fn mixState( + y: []f32, + S: []f32, + proj: []const f32, + fgate: []const f32, + braw: []const f32, + g2: []const f32, + conv_q: []const f32, + conv_k: []const f32, + conv_v: []const f32, + A_log: []const f32, + dt_bias: []const f32, + o_norm: []const f32, + s: Shape, + rows: u32, + history: [][3]f32, +) error{ KdaWidthTooWide, KdaHistoryShape }!void { + if (s.width() > max_width) return error.KdaWidthTooWide; + if (history.len != 3 * s.width()) return error.KdaHistoryShape; + mixAs(f32, true, y, S, proj, fgate, braw, g2, conv_q, conv_k, conv_v, A_log, dt_bias, o_norm, s, rows, history); } /// Same mixer in float64, no extra rounding: oracle/kda_inner.py (copy of Model.kda, r = identity). @@ -163,7 +189,7 @@ pub fn mixF64( rows: u32, ) error{KdaWidthTooWide}!void { if (s.width() > max_width) return error.KdaWidthTooWide; - mixAs(f64, false, y, S, proj, fgate, braw, g2, conv_q, conv_k, conv_v, A_log, dt_bias, o_norm, s, rows); + mixAs(f64, false, y, S, proj, fgate, braw, g2, conv_q, conv_k, conv_v, A_log, dt_bias, o_norm, s, rows, null); } test "tiny KDA geometry is the k3_kda kernel's: 16 heads, D=128, 4 taps, lower_bound -5" { @@ -276,7 +302,7 @@ fn checkOracle(bytes: []const u8) !void { const S_math = try a.alloc(f32, H * dim * dim); defer a.free(S_math); @memset(S_math, 0); - mixAs(f32, false, got_math, S_math, proj, fgate, braw, g2, conv_q, conv_k, conv_v, A_log, dt_bias, o_norm, s, rows); + mixAs(f32, false, got_math, S_math, proj, fgate, braw, g2, conv_q, conv_k, conv_v, A_log, dt_bias, o_norm, s, rows, null); try gateMixMath(want, got_math, W, rows, H); const got32 = try a.alloc(f32, want_n); @@ -285,6 +311,20 @@ fn checkOracle(bytes: []const u8) !void { defer a.free(S32); @memset(S32, 0); try mix(got32, S32, proj, fgate, braw, g2, conv_q, conv_k, conv_v, A_log, dt_bias, o_norm, s, rows); + const rates = try a.alloc(f32, H); + defer a.free(rates); + for (rates, A_log) |*v, log| v.* = @exp(log); + const stored_y = try a.alloc(f32, want_n); + defer a.free(stored_y); + const stored_s = try a.alloc(f32, H * dim * dim); + defer a.free(stored_s); + @memset(stored_s, 0); + var rate_shape = s; + rate_shape.stored_rate = true; + try mix(stored_y, stored_s, proj, fgate, braw, g2, conv_q, conv_k, conv_v, rates, dt_bias, o_norm, rate_shape, rows); + try std.testing.expectEqualSlices(u8, std.mem.sliceAsBytes(got32), std.mem.sliceAsBytes(stored_y)); + try std.testing.expectEqualSlices(u8, std.mem.sliceAsBytes(S32), std.mem.sliceAsBytes(stored_s)); + var row: u32 = 0; while (row < rows) : (row += 1) { var worst: f64 = 0; diff --git a/zig/src/families/minimax_m3/backend.zig b/zig/src/families/minimax_m3/backend.zig index 0c9dd88d78e..b9619291ac5 100644 --- a/zig/src/families/minimax_m3/backend.zig +++ b/zig/src/families/minimax_m3/backend.zig @@ -7,6 +7,7 @@ const fwd = @import("forward.zig"); const Model = @import("model.zig").Model; const snapshot = @import("snapshot.zig"); const pass = @import("prompt_pass.zig"); +const round_costs = @import("round_costs.zig"); const row = @import("../step5/backend.zig").row; const be = lanes.backend; @@ -42,6 +43,8 @@ pub const Metal = struct { 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, + shared: [round_costs.shared_widths.len]lanes.config.Cost = undefined, // shared rounds' ms by total rows, by measure() + shared_timed: usize = 0, values: []f32, // a logits row as f32, for the host twin of the GPU draw passes: std.AutoHashMapUnmanaged(*lanes.Stream, pass.Pass) = .empty, // prompt passes in progress (#3021) gen: u64 = 0, // forwards so far: a chunk's tapped rows in a scratch are current while their gen matches @@ -102,14 +105,16 @@ pub const Metal = struct { } 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] }; + return round_costs.facts(st.window_rows, st.batch_rows, self.options.streams, self.options.drafts, self.costs[0..self.timed], self.shared[0..self.shared_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); + // the scratch refuses caches past --context; one too short for a window leaves the rounds untimed + const capacity = @min(256, self.options.capacity); + if (capacity < max_window) return; + var cache = try st.Cache.init(self.model.device, c, capacity); defer cache.deinit(); var ids: [max_window]u32 = undefined; for (&ids, 0..) |*x, i| x.* = @intCast(1000 + i * 7919 % 50000); @@ -128,6 +133,36 @@ pub const Metal = struct { self.costs[rows - 1] = .{ .width = @intCast(rows), .ms = ms }; } self.timed = max_window; + try self.measureShared(capacity); + } + + /// Shared rounds of 12-32 rows, timed as real verify windows capped by the timing cache's context. + fn measureShared(self: *Metal, capacity: usize) !void { + const c = &self.model.config; + var caches: [st.batch_rows / max_window]st.Cache = undefined; + var made: usize = 0; + defer for (caches[0..made]) |*x| x.deinit(); + while (made < caches.len) : (made += 1) caches[made] = try st.Cache.init(self.model.device, c, capacity); + var ids: [st.batch_rows]u32 = undefined; + for (&ids, 0..) |*x, i| x.* = @intCast(1000 + i * 7919 % 50000); + for (round_costs.shared_widths, 0..) |total, j| { + var rows: [caches.len]usize = undefined; + const parts = round_costs.measurementWindows(total, st.window_rows, capacity, &rows); + var segments: [caches.len]fwd.Segment = undefined; + for (parts, 0..) |n, i| segments[i] = .{ .cache = &caches[i], .rows = n }; + var ms: f64 = 0; + for (0..2) |run| { + for (caches[0..parts.len]) |*x| x.len = 0; + var ts0: std.c.timespec = undefined; + _ = std.c.clock_gettime(.MONOTONIC, &ts0); + try fwd.runShared(self.model, &self.scratch, segments[0..parts.len], ids[0..total], .{ .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.shared[j] = .{ .width = total, .ms = ms }; + } + self.shared_timed = round_costs.shared_widths.len; } /// A tapped row's bytes: every tap's hidden row, bf16. diff --git a/zig/src/families/minimax_m3/cuda_dump_main.zig b/zig/src/families/minimax_m3/cuda_dump_main.zig index 92b4fbecf1f..0f09e35b2e3 100644 --- a/zig/src/families/minimax_m3/cuda_dump_main.zig +++ b/zig/src/families/minimax_m3/cuda_dump_main.zig @@ -114,7 +114,7 @@ pub fn main(init: std.process.Init) !u8 { /// Every row's logits of this rank's vocabulary share in verify windows: logits.r{rank}.bf16 and its .json. fn everyRow(gpa: std.mem.Allocator, io: std.Io, driver: *const cuda.Driver, stream: cuda.Stream, m: *const mm3.forward.Modules, dir: []const u8, ids: []const i32, out_dir: []const u8) !void { - const p = try mm3.native.place(); + const p = try mm3.native.toolPlace(); var lib: ?cuda.nccl.Library = null; var comm: cuda.nccl.Comm = null; if (p.world > 1) { diff --git a/zig/src/families/minimax_m3/cuda_native.zig b/zig/src/families/minimax_m3/cuda_native.zig index cc2fd4acc23..4c5a817789d 100644 --- a/zig/src/families/minimax_m3/cuda_native.zig +++ b/zig/src/families/minimax_m3/cuda_native.zig @@ -1,4 +1,4 @@ -//! MiniMax-M3.1-Flash native CUDA at TP (TF_MINIMAX_RANK, TF_MINIMAX_WORLD, NCCL_COMM_ID): rank 0 serves. +//! MiniMax-M3.1-Flash native CUDA at TP (--tp, --rank, NCCL's root): rank 0 serves. const std = @import("std"); const cuda = @import("cuda"); @@ -31,6 +31,11 @@ pub const Options = struct { slide: bool = false, room: ?Room = null, vision: ?vision_mod.Limits = null, // --vision: the last rank's tower, every rank's image rows + rank: u32 = 0, // the launch's, resolved from --tp/--rank and TF_MINIMAX_* (native/cuda_launch.zig) + tp: u32 = 1, + master: ?[]const u8 = null, + master_port: u16 = 29551, + launch_from: []const u8 = "", }; /// An image takes at most 576 tokens; a request's images 4096 in all unless --vision-image-tokens says otherwise. pub const default_image_tokens: u32 = 4096; @@ -52,15 +57,25 @@ pub const Loaded = struct { }; /// The tower's bytes on this rank: the last rank holds it, sized from its tensors (every rank's staging is small). -pub fn visionBytes(a: std.mem.Allocator, io: std.Io, dir: []const u8) !u64 { - const p = place() catch return 0; +pub fn visionBytes(a: std.mem.Allocator, io: std.Io, dir: []const u8, rank: u32, world: u32) !u64 { + const p = checked(.{ .rank = rank, .world = world }) catch return 0; return if (p.rank + 1 == p.world) vision_mod.Tower.bytesFor(a, io, dir) else 0; } -/// This rank's place: TF_MINIMAX_RANK of TF_MINIMAX_WORLD (both, or neither for one rank). pub const Place = struct { rank: usize, world: usize }; -pub fn place() !Place { +/// This rank's place as the launch resolved it (`o.rank` of `o.tp`). +pub fn place(o: anytype) !Place { + return checked(.{ .rank = o.rank, .world = o.tp }); +} + +fn checked(p: Place) !Place { + if (p.world < 1 or p.rank >= p.world) return error.NoRank; + return p; +} + +/// The dump tool's place: TF_MINIMAX_RANK of TF_MINIMAX_WORLD (both, or neither for one rank), its input as before. +pub fn toolPlace() !Place { const env = @import("sys").environment; const r = try env.read(?u64, "TF_MINIMAX_RANK", null); const w = try env.read(?u64, "TF_MINIMAX_WORLD", null); @@ -106,9 +121,9 @@ fn draftBytes(a: std.mem.Allocator, io: std.Io, dir: []const u8) !u64 { } /// Bytes this rank's weights take: its share of the split axes; the embeddings, the routers and dspark/ counted whole. -pub fn weightShare(a: std.mem.Allocator, io: std.Io, dir: []const u8, total: u64, drafts: bool) u64 { +pub fn weightShare(a: std.mem.Allocator, io: std.Io, dir: []const u8, total: u64, drafts: bool, rank: u32, world: u32) u64 { _ = drafts; // dspark/ is counted whole (drafts are on by default) - const p = place() catch return total; + const p = checked(.{ .rank = rank, .world = world }) catch return total; const c = cfg.Config.read(a, io, dir) catch return total; const f = (shard.Share.of(&c, p.rank, p.world) catch return total).part(&c); var moe: u64 = 0; @@ -140,10 +155,12 @@ const Owned = struct { pub fn open(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: []const u8, kernels: ?[]const u8, o: Options) !Loaded { _ = kernels; try @import("sys").environment.checkScope(.minimax_m3, @import("sys").environment.Process{}); - const p = try place(); + try cuda.rendezvous.fromMaster(o, cuda.rendezvous.Process{}, cuda.rendezvous.Process{}); // before the liveness line + const p = try place(o); try admit(@intCast(try ctx.attribute(.compute_capability_major) * 10 + try ctx.attribute(.compute_capability_minor)), p.world); if (p.world > 1 and std.c.getenv("NCCL_COMM_ID") == null) return error.NoCommId; if (p.world > 1) try cuda.tp_watch.start(io, p.rank, p.world); + if (p.world > 1) std.log.info("[tensorfold] minimax: rank {d} of {d} ({s})", .{ p.rank, p.world, o.launch_from }); return openRank(gpa, io, ctx, dir, o, p) catch |err| { cuda.tp_watch.fail(@errorName(err)); return err; @@ -309,10 +326,12 @@ fn release(own: *Owned) void { /// The server's words for this family's refusals. pub fn explain(_: ?*anyopaque, err: anyerror) ?[]const u8 { return switch (err) { - error.NoRank => "MiniMax-M3.1-Flash runs at TP over two hosts: set TF_MINIMAX_RANK (0 or 1) and TF_MINIMAX_WORLD=2 on both", - error.NoCommId => "MiniMax-M3.1-Flash's ranks meet over NCCL: set NCCL_COMM_ID to rank 0's address:port on both hosts", + error.NoRank => "MiniMax-M3.1-Flash runs at TP over two hosts: launch both with --tp 2 and --rank 0 or 1", + error.NoCommId => "MiniMax-M3.1-Flash's ranks meet over NCCL: give --master (rank 0's address) or set NCCL_COMM_ID to rank 0's address:port on both hosts", + error.RendezvousDisagree => "NCCL_COMM_ID differs from --master:--master-port: give one of them, or equal values", + error.MasterTooLong => "--master: too long for NCCL's root address (host:port in 320 bytes); give rank 0's address", error.MiniMaxM3RequiresSm121 => "MiniMax-M3.1-Flash on CUDA is served on GB10 (sm_121) only so far, and this GPU is another", - error.MiniMaxM3RequiresTwoRanks => "MiniMax-M3.1-Flash on CUDA is served at two TP ranks only so far: TF_MINIMAX_WORLD=2 on both hosts", + error.MiniMaxM3RequiresTwoRanks => "MiniMax-M3.1-Flash on CUDA is served at two TP ranks only so far: launch both hosts with --tp 2", error.NotExl3 => "MiniMax-M3.1-Flash on CUDA serves a published EXL3 pack (quantization_config quant_method \"exl3\"), e.g. Mia-AiLab/MiniMax-M3.1-Flash-EXL3-EAQ-v1-3.06-bpw", error.UnsupportedExl3 => "this EXL3 pack is not one the CUDA kernels read: exllamav3 1.x on the mul1 codebook, every projection at a width the dense kernels build", error.UnexpectedMiniMaxTensor => "a tensor is not stored as MiniMax-M3.1-Flash's EXL3 packs store it (the log names it)", @@ -340,3 +359,9 @@ test "the tower's scratch is load's buffers at the largest image" { // load's eleven scratch buffers at 2,304 patches (576 tokens, 2 x 2 patches each), summed by hand try std.testing.expectEqual(@as(u64, 183_785_472), vision_mod.Tower.scratch_bytes); } + +test "MiniMax's place is the launch's; the tower counts only on the last rank" { + try std.testing.expectEqual(Place{ .rank = 1, .world = 2 }, try place(.{ .rank = @as(u32, 1), .tp = @as(u32, 2) })); + try std.testing.expectError(error.NoRank, place(.{ .rank = @as(u32, 2), .tp = @as(u32, 2) })); + try std.testing.expectEqual(@as(u64, 0), try visionBytes(std.testing.allocator, std.testing.io, "missing", 0, 2)); +} diff --git a/zig/src/families/minimax_m3/round_costs.zig b/zig/src/families/minimax_m3/round_costs.zig new file mode 100644 index 00000000000..47e5f97d993 --- /dev/null +++ b/zig/src/families/minimax_m3/round_costs.zig @@ -0,0 +1,63 @@ +//! MiniMax-M3 Metal's timed rounds: a window of 1-8 rows, and shared rounds of 12-32 rows as several streams' windows. +const std = @import("std"); +const lanes = @import("lanes"); +const Cost = lanes.config.Cost; + +/// Shared rounds' total rows that measure() times beside the 1-8 row windows (32 is a round's most rows). +pub const shared_widths = [_]u32{ 12, 16, 24, 32 }; + +/// A shared round of `total` rows as streams' windows of `window` rows, the last the remainder; `out` holds them. +pub fn windows(total: usize, window: usize, out: []usize) []usize { + var n: usize = 0; + var left = total; + while (left > 0) : (n += 1) { + out[n] = @min(left, window); + left -= out[n]; + } + return out[0..n]; +} + +/// Timed shared segments use the real verification-window limit, capped by the throwaway cache's context. +pub fn measurementWindows(total: usize, window_rows: usize, capacity: usize, out: []usize) []usize { + return windows(total, @min(window_rows, capacity), out); +} + +/// The lane facts: `window` prices one stream's window by rows, `shared` a shared round by its total rows. +pub fn facts(window_rows: u32, batch_rows: u32, streams: u32, drafts: bool, window: []const Cost, shared: []const Cost) lanes.Model { + // rows are independent in every decode kernel, so any width, alone or beside other streams, gives one-row bits + return .{ .exact_width = window_rows, .gpu_tokens = !drafts, .hidden_rows = true, .batch_rows = batch_rows, .mtp = false, .speculate = false, .speculate_early = false, .drafts = 1, .max_streams = streams, .streams_exact = true, .window_costs = window, .shared_costs = shared }; +} + +test "MiniMax-M3 round costs: timed segments match real 16-row windows, capped by measurement capacity" { + var buf: [4]usize = undefined; + try std.testing.expectEqualSlices(usize, &.{12}, measurementWindows(12, 16, 256, &buf)); + try std.testing.expectEqualSlices(usize, &.{16}, measurementWindows(16, 16, 256, &buf)); + try std.testing.expectEqualSlices(usize, &.{ 16, 8 }, measurementWindows(24, 16, 256, &buf)); + try std.testing.expectEqualSlices(usize, &.{ 16, 16 }, measurementWindows(32, 16, 256, &buf)); + for (shared_widths) |w| try std.testing.expect(measurementWindows(w, 16, 256, &buf).len <= buf.len); + try std.testing.expectEqualSlices(usize, &.{ 8, 4 }, measurementWindows(12, 16, 8, &buf)); + try std.testing.expectEqualSlices(usize, &.{ 8, 8 }, measurementWindows(16, 16, 8, &buf)); + try std.testing.expectEqualSlices(usize, &.{ 8, 8, 8 }, measurementWindows(24, 16, 8, &buf)); + try std.testing.expectEqualSlices(usize, &.{ 8, 8, 8, 8 }, measurementWindows(32, 16, 8, &buf)); + for (shared_widths) |w| try std.testing.expect(measurementWindows(w, 16, 8, &buf).len <= buf.len); +} + +test "MiniMax-M3 round costs: 16 and 32 rows are priced from the timed rounds, not at 2x and 4x the 8-row window" { + const a = std.testing.allocator; + var window: [8]Cost = undefined; + for (&window, 1..) |*c, r| c.* = .{ .width = @intCast(r), .ms = 10.0 + 0.5 * @as(f64, @floatFromInt(r)) }; // 8 rows: 14 ms + // what wide rounds cost on the device, about 1.2-1.4x and 1.5-2x the 8-row window + const shared = [_]Cost{ .{ .width = 12, .ms = 15.5 }, .{ .width = 16, .ms = 17.5 }, .{ .width = 24, .ms = 21.0 }, .{ .width = 32, .ms = 24.5 } }; + var timed = try lanes.Config.init(a, facts(16, 32, 4, false, &window, &shared), 16, 15); + defer timed.deinit(a); + try std.testing.expectEqual(@as(?f64, 14.0), timed.shared_costs.get(8)); + try std.testing.expectEqual(@as(?f64, 17.5), timed.shared_costs.get(16)); + try std.testing.expectEqual(@as(?f64, 24.5), timed.shared_costs.get(32)); + try std.testing.expectEqual(@as(?f64, 19.25), timed.shared_costs.get(20)); // between 16 and 24 + try std.testing.expectEqual(@as(?f64, 14.75), timed.shared_costs.get(10)); // between 8 and 12 + // main's facts timed windows alone: past 8 rows, the 8-row window's ms a row, so 16 rows at 2x and 32 at 4x + var guessed = try lanes.Config.init(a, facts(16, 32, 4, false, &window, &.{}), 16, 15); + defer guessed.deinit(a); + try std.testing.expectEqual(@as(?f64, 28.0), guessed.shared_costs.get(16)); + try std.testing.expectEqual(@as(?f64, 56.0), guessed.shared_costs.get(32)); +} diff --git a/zig/src/families/muse_spark/native.zig b/zig/src/families/muse_spark/native.zig index 4be458df44a..95ced8cffc7 100644 --- a/zig/src/families/muse_spark/native.zig +++ b/zig/src/families/muse_spark/native.zig @@ -488,7 +488,7 @@ fn tpFrom(get: *const fn ([]const u8) ?[]const u8) tp.config.Error!?tp.Config { } /// Admission bytes of a rank: the checkpoint over the two TP ranks (the embedding stays in host memory). -pub fn weightShare(_: std.mem.Allocator, _: std.Io, _: []const u8, total: u64, _: bool) (tp.config.Error || error{MuseSparkRequiresTwoRanks})!u64 { +pub fn weightShare(_: std.mem.Allocator, _: std.Io, _: []const u8, total: u64, _: bool, _: u32, _: u32) (tp.config.Error || error{MuseSparkRequiresTwoRanks})!u64 { return share(total, tpRead()); } diff --git a/zig/src/families/nemotron/config.zig b/zig/src/families/nemotron/config.zig index 6b4328a983c..403938398cb 100644 --- a/zig/src/families/nemotron/config.zig +++ b/zig/src/families/nemotron/config.zig @@ -79,6 +79,7 @@ pub const Config = struct { rank: usize = 0, // this process's tensor-parallel rank of `world`: set at load, never by config.json world: usize = 1, ck: bool = false, // --precision checkpoint: e4m3 rows into the FP8 layers, NVFP4 rows into the experts + wide_rounds: bool = false, // TF_NEMOTRON_WIDE_ROUNDS where cuda_wide.allowed: shared rounds of 16 streams, 32 rows widths: [max_layers][4]Width = @splat(@splat(.{})), // each layer's matrices (members(kind) order) at their widths embed_width: Width = .{}, embed_bf16: bool = false, // the token table is stored bf16 (config.json's `false` for it), read by HIP only diff --git a/zig/src/families/nemotron/cuda.zig b/zig/src/families/nemotron/cuda.zig index 525ca818ae8..9af92970537 100644 --- a/zig/src/families/nemotron/cuda.zig +++ b/zig/src/families/nemotron/cuda.zig @@ -6,6 +6,7 @@ pub const Precision = @import("config.zig").Precision; pub const weights = @import("cuda_weights.zig"); pub const kernels = @import("cuda_kernels.zig"); pub const state = @import("cuda_state.zig"); +pub const wide = @import("cuda_wide.zig"); pub const Forward = @import("cuda_forward.zig").Forward; pub const Seg = @import("cuda_forward.zig").Seg; pub const Walk = @import("cuda_forward.zig").Walk; @@ -41,6 +42,9 @@ pub const identity = @import("core").checkpoint_identity; test { _ = omni; + _ = @import("cuda_wide.zig"); + _ = @import("cuda_wide_walk_test.zig"); + _ = @import("cuda_attn_segs_test.zig"); _ = @import("cuda_bolt_lanes_test.zig"); _ = @import("cuda_shared_draw.zig"); _ = @import("cuda_lanes.zig"); diff --git a/zig/src/families/nemotron/cuda_attn_segs_test.zig b/zig/src/families/nemotron/cuda_attn_segs_test.zig new file mode 100644 index 00000000000..b849d273cf9 --- /dev/null +++ b/zig/src/families/nemotron/cuda_attn_segs_test.zig @@ -0,0 +1,252 @@ +//! A shared round's attention past 8 streams: the real attentionSegs on a driver that runs the kernels' row mapping. +const std = @import("std"); +const cuda = @import("cuda"); +const glue = @import("cuda_glue.zig"); +const t = std.testing; + +/// nemotron_attention.cu's AttnSegs, as attentionSegs passes it by value. +const Segs = extern struct { kc: [glue.max_segs]u64, vc: [glue.max_segs]u64, meta: [glue.max_segs]u64, pt: [glue.max_segs]u64, ps: i64, row0: [glue.max_segs]c_int, n: c_int }; + +const base_shape: glue.Attn = .{ .nqkv = 6144, .heads = 32, .kv_heads = 2, .dim = 128, .nch = 2 }; +const qd: u64 = base_shape.heads * base_shape.dim; +const kvd: u64 = base_shape.kv_heads * base_shape.dim; +const page = 512; // paged_attn.cuh's PAGE + +/// Device memory by address (a value a row), each meta row's position and each page table's first page. +const Device = struct { + var mem: std.AutoHashMapUnmanaged(u64, u64) = .empty; + var pos: std.AutoHashMapUnmanaged(u64, i64) = .empty; + var pages: std.AutoHashMapUnmanaged(u64, u64) = .empty; + var fns: glue.Fns = undefined; + + fn get(at: u64) u64 { + return mem.get(at) orelse 0; + } + fn put(at: u64, v: u64) void { + mem.put(t.allocator, at, v) catch @panic("oom"); + } + fn arg(comptime T: type, args: [*]?*anyopaque, i: usize) T { + return @as(*align(1) const T, @ptrCast(args[i].?)).*; + } + /// key_at: contiguous rows, or the page the stream's table names at `ps` elements a page. + fn key(cache: u64, k: i64, pt: u64, ps: i64) u64 { + const kk: u64 = @bitCast(k); + if (pt == 0) return cache +% kk *% kvd *% 2; + const chunk = pages.get(pt).? *% @as(u64, @bitCast(ps)); + return cache +% (chunk +% (kk % page) *% kvd) *% 2; + } + + const Planes = struct { po: u64, pm: u64, pl: u64 }; + + fn kvRow(qkv: u64, row: u64, kc: u64, vc: u64, at: i64, pt: u64, ps: i64) void { + const v = get(qkv + row * base_shape.nqkv * 2); + put(key(kc, at, pt, ps), v); + put(key(vc, at, pt, ps), v +% 1); + } + /// A row's partial output, maxima and sums: its query against the stream's keys and values 0..at. + fn attnRow(qkv: u64, row: u64, kc: u64, vc: u64, at: i64, pt: u64, ps: i64, p: Planes) void { + var acc = get(qkv + row * base_shape.nqkv * 2) *% 31; + var k: i64 = 0; + while (k <= at) : (k += 1) acc = acc *% 1000003 +% get(key(kc, k, pt, ps)) *% 7 +% get(key(vc, k, pt, ps)); + put(p.po + row * base_shape.nch * qd * 4, acc); + put(p.pm + row * base_shape.nch * base_shape.heads * 4, acc ^ 0x55); + put(p.pl + row * base_shape.nch * base_shape.heads * 4, acc ^ 0xaa); + } + /// The merge: a row's output from its three planes, and the output's group sums. + fn mergeRow(p: Planes, row: u64, out: u64, xs: u64) void { + const o = get(p.po + row * base_shape.nch * qd * 4) *% 3 +% get(p.pm + row * base_shape.nch * base_shape.heads * 4) *% 5 +% get(p.pl + row * base_shape.nch * base_shape.heads * 4); + put(out + row * qd * 2, o); + put(xs + row * (qd / 64) * 4, o ^ 0x77); + } + + fn segOf(s: *const Segs, rq: c_int) usize { + var k: usize = 0; + while (k + 1 < s.n and s.row0[k + 1] <= rq) k += 1; + return k; + } + + fn launch(f: cuda.abi.Function, gx: c_uint, _: c_uint, _: c_uint, _: c_uint, _: c_uint, _: c_uint, _: c_uint, _: cuda.abi.Stream, raw: ?[*]?*anyopaque, _: ?[*]?*anyopaque) callconv(.c) c_int { + const a = raw.?; + const h = f; + for (0..gx) |rq| { + if (h == fns.kv_write.handle) { // qkv kc vc meta, 3 ints, pt ps + kvRow(arg(u64, a, 0), rq, arg(u64, a, 1), arg(u64, a, 2), pos.get(arg(u64, a, 3)).? + @as(i64, @intCast(rq)), arg(u64, a, 7), arg(i64, a, 8)); + } else if (h == fns.attn_chunk.handle or h == fns.attn_chunk_pf.handle) { // qkv kc vc meta po pm pl, 6 ints, scale, pt ps + attnRow(arg(u64, a, 0), rq, arg(u64, a, 1), arg(u64, a, 2), pos.get(arg(u64, a, 3)).? + @as(i64, @intCast(rq)), arg(u64, a, 14), arg(i64, a, 15), .{ .po = arg(u64, a, 4), .pm = arg(u64, a, 5), .pl = arg(u64, a, 6) }); + } else if (h == fns.attn_merge.handle) { // po pm pl meta out xs + mergeRow(.{ .po = arg(u64, a, 0), .pm = arg(u64, a, 1), .pl = arg(u64, a, 2) }, rq, arg(u64, a, 4), arg(u64, a, 5)); + } else { + const s = arg(Segs, a, 0); + const k = segOf(&s, @intCast(rq)); + const p = pos.get(s.meta[k]).? + @as(i64, @intCast(rq)) - s.row0[k]; + if (h == fns.kv_write_segs.handle) { // segs qkv + kvRow(arg(u64, a, 1), rq, s.kc[k], s.vc[k], p, s.pt[k], s.ps); + } else if (h == fns.attn_chunk_segs.handle) { // segs qkv po pm pl + attnRow(arg(u64, a, 1), rq, s.kc[k], s.vc[k], p, s.pt[k], s.ps, .{ .po = arg(u64, a, 2), .pm = arg(u64, a, 3), .pl = arg(u64, a, 4) }); + } else if (h == fns.attn_merge_segs.handle) { // segs po pm pl out xs + mergeRow(.{ .po = arg(u64, a, 1), .pm = arg(u64, a, 2), .pl = arg(u64, a, 3) }, rq, arg(u64, a, 4), arg(u64, a, 5)); + } else return 1; + } + } + return 0; + } +}; + +const Buffers = struct { qkv: u64, po: u64, pm: u64, pl: u64, out: u64, xs: u64 }; + +/// A round's layout: rows a stream (1-2, or 2 each), a gap between streams, paged or contiguous caches. +const Layout = struct { full: bool = false, gap: usize = 0, paged: bool = false }; + +fn rowsOf(l: Layout, i: usize) usize { + return if (l.full) 2 else 1 + i % 2; +} +fn cacheOf(i: usize) [4]u64 { + return .{ 0x1000_0000 + i * 0x10_0000, 0x2000_0000 + i * 0x10_0000, 0x3000_0000 + i * 0x100, 0x3800_0000 + i * 0x100 }; +} +fn posOf(i: usize) usize { + return 5 + 3 * i; +} +fn psOf(l: Layout) i64 { + return @intCast(shapeOf(l).ps); +} +fn shapeOf(l: Layout) glue.Attn { + var s = base_shape; + if (l.paged) s.ps = 1 << 20; + return s; +} + +/// A round of streams `first..first + n` from row 0 of `b`, `l`'s layout; `plant` moves one stream's first query. +fn round(g: glue.Glue, l: Layout, first: usize, n: usize, b: Buffers, parts: ?usize, plant: ?usize) !void { + var segs: [16]glue.AttnSeg = undefined; + var row: usize = 0; + for (segs[0..n], first..) |*s, i| { + const c = cacheOf(i); + s.* = .{ .kc = c[0], .vc = c[1], .meta = c[2], .row0 = row, .rows = rowsOf(l, i), .pt = if (l.paged) c[3] else 0 }; + for (0..rowsOf(l, i)) |r| Device.put(b.qkv + (row + r) * base_shape.nqkv * 2, 100_000 + i * 100 + r + @intFromBool(plant == i and r == 0)); + row += rowsOf(l, i) + l.gap; + } + // whole, as the forward and the MTP head call it; or in parts of `parts`, as they called it before REV60 1 + const step = parts orelse n; + var k0: usize = 0; + while (k0 < n) : (k0 += step) try g.attentionSegs(segs[k0..@min(n, k0 + step)], b.qkv, b.po, b.pm, b.pl, b.out, b.xs, shapeOf(l)); +} + +/// Every stream's output and group-sum rows, the keys and values it wrote, and earlier ones overwritten. +const Seen = struct { out: [16][2][2]u64 = @splat(@splat(@splat(0))), keys: [16][2][2]u64 = @splat(@splat(@splat(0))), corrupt: usize = 0 }; + +fn fresh(l: Layout, n: usize) !void { + Device.mem.clearRetainingCapacity(); + Device.pos.clearRetainingCapacity(); + Device.pages.clearRetainingCapacity(); + for (0..n) |i| { + const c = cacheOf(i); + try Device.pos.put(t.allocator, c[2], @intCast(posOf(i))); + try Device.pages.put(t.allocator, c[3], 3 + 2 * i); // each stream's first page somewhere of its own + for (0..posOf(i)) |k| { // the keys and values the stream already holds + Device.put(Device.key(c[0], @intCast(k), if (l.paged) c[3] else 0, psOf(l)), 1000 * i + k); + Device.put(Device.key(c[1], @intCast(k), if (l.paged) c[3] else 0, psOf(l)), 1000 * i + k + 7); + } + } +} + +/// Each stream's output and group-sum row addresses in a round of streams from `first` at `b`. +fn rowsAt(l: Layout, at: *[16][2][2]u64, first: usize, n: usize, b: Buffers, gap: usize) void { + var row: usize = 0; + for (first..first + n) |i| { + for (0..rowsOf(l, i)) |r| at[i][r] = .{ b.out + (row + r) * qd * 2, b.xs + (row + r) * (qd / 64) * 4 }; + row += rowsOf(l, i) + gap; + } +} + +fn seen(l: Layout, n: usize, at: *const [16][2][2]u64) Seen { + var s: Seen = .{}; + const ps = psOf(l); + for (0..n) |i| { + const c = cacheOf(i); + const pt = if (l.paged) c[3] else 0; + const p: i64 = @intCast(posOf(i)); + for (0..rowsOf(l, i)) |r| { + s.out[i][r] = .{ Device.get(at[i][r][0]), Device.get(at[i][r][1]) }; + s.keys[i][r] = .{ Device.get(Device.key(c[0], p + @as(i64, @intCast(r)), pt, ps)), Device.get(Device.key(c[1], p + @as(i64, @intCast(r)), pt, ps)) }; + } + for (0..posOf(i)) |k| { // the keys and values the stream held before the round + if (Device.get(Device.key(c[0], @intCast(k), pt, ps)) != 1000 * i + k) s.corrupt += 1; + if (Device.get(Device.key(c[1], @intCast(k), pt, ps)) != 1000 * i + k + 7) s.corrupt += 1; + } + } + return s; +} + +const wide: Buffers = .{ .qkv = 0x5000_0000, .po = 0x6000_0000, .pm = 0x6800_0000, .pl = 0x6900_0000, .out = 0x7000_0000, .xs = 0x7800_0000 }; +const narrow = [2]Buffers{ + .{ .qkv = 0x8000_0000, .po = 0x9000_0000, .pm = 0x9800_0000, .pl = 0x9900_0000, .out = 0xa000_0000, .xs = 0xa800_0000 }, + .{ .qkv = 0xb000_0000, .po = 0xc000_0000, .pm = 0xc800_0000, .pl = 0xc900_0000, .out = 0xd000_0000, .xs = 0xd800_0000 }, +}; + +/// The reference: streams 0..7 in one round, the rest in another, each from row 0 of its own buffers. +fn reference(g: glue.Glue, l: Layout, n: usize) !Seen { + try fresh(l, n); + try round(g, l, 0, 8, narrow[0], null, null); + try round(g, l, 8, n - 8, narrow[1], null, null); + var at: [16][2][2]u64 = undefined; + rowsAt(l, &at, 0, 8, narrow[0], l.gap); + rowsAt(l, &at, 8, n - 8, narrow[1], l.gap); + return seen(l, n, &at); +} + +fn wideRound(g: glue.Glue, l: Layout, n: usize, parts: ?usize, plant: ?usize) !Seen { + try fresh(l, n); + try round(g, l, 0, n, wide, parts, plant); + var at: [16][2][2]u64 = undefined; + rowsAt(l, &at, 0, n, wide, l.gap); + return seen(l, n, &at); +} + +fn expectSame(l: Layout, n: usize, want: Seen, got: Seen) !void { + try t.expectEqual(@as(usize, 0), got.corrupt); // no stream's earlier keys or values overwritten + for (0..n) |i| for (0..rowsOf(l, i)) |r| { + try t.expectEqual(want.out[i][r], got.out[i][r]); // output and its group sums + try t.expectEqual(want.keys[i][r], got.keys[i][r]); // the new key and value + }; +} + +fn rig(d: *cuda.Driver) glue.Glue { + d.api.cuLaunchKernel = Device.launch; + inline for (@typeInfo(glue.Fns).@"struct".field_names, 0..) |name, i| @field(Device.fns, name) = .{ .d = d, .handle = @ptrFromInt(0x100 + i) }; + return .{ .set = null, .f = &Device.fns, .s = .{ .d = d, .handle = null }, .emb = undefined, .norms = undefined, .moe = undefined }; +} + +fn deinit() void { + Device.mem.deinit(t.allocator); + Device.pos.deinit(t.allocator); + Device.pages.deinit(t.allocator); + Device.mem, Device.pos, Device.pages = .{ .empty, .empty, .empty }; // the next test starts afresh +} + +test "wide round walk: 9 to 16 streams' attention reads and writes each stream's own rows and cache, as 8-stream rounds do" { + defer deinit(); + var d: cuda.Driver = undefined; + const g = rig(&d); + // 1-2 rows a stream or 2 each (32 rows at 16 streams); contiguous caches or paged; streams' rows apart or not + const layouts = [_]Layout{ .{}, .{ .full = true }, .{ .paged = true }, .{ .full = true, .paged = true }, .{ .gap = 1 } }; + for (layouts) |l| for (9..17) |n| { + const want = try reference(g, l, n); + try t.expectEqual(@as(usize, 0), want.corrupt); + // whole, as the callers pass it now, and in the old callers' parts of 8 + for ([_]?usize{ null, glue.max_segs }) |parts| try expectSame(l, n, want, try wideRound(g, l, n, parts, null)); + }; +} + +test "wide round walk: the attention comparison catches one stream's moved query (a planted control)" { + defer deinit(); + var d: cuda.Driver = undefined; + const g = rig(&d); + const l: Layout = .{}; + const want = try reference(g, l, 12); + const got = try wideRound(g, l, 12, null, 10); + try t.expectEqual(@as(usize, 0), got.corrupt); + for (0..12) |i| { + const same = std.meta.eql(want.out[i], got.out[i]) and std.meta.eql(want.keys[i], got.keys[i]); + try t.expectEqual(i != 10, same); // stream 10 alone differs: its output, sums and new key and value + } +} diff --git a/zig/src/families/nemotron/cuda_costs.zig b/zig/src/families/nemotron/cuda_costs.zig index e89265dff3a..8aba3a8499e 100644 --- a/zig/src/families/nemotron/cuda_costs.zig +++ b/zig/src/families/nemotron/cuda_costs.zig @@ -200,7 +200,7 @@ fn timeAll(gpa: std.mem.Allocator, io: std.Io, e: *Engine, h: *Head, model_dir: var observer: Heads = .{ .chains = chains[0..heads.len] }; try rule.measureWidths(windows, &observer, raw.verify[1 .. rows + 1], again); if (!again) raw.verify[0] = 0; - try rule.smooth(windows, raw.verify[1 .. rows + 1]); + try rule.smoothSerial(windows, raw.verify[1 .. rows + 1]); for (heads, chains[0..heads.len]) |v, c| { const level = &raw.level[@backingInt(v)]; level.* = if (again) @min(level.*, c.level()) else c.level(); diff --git a/zig/src/families/nemotron/cuda_engine.zig b/zig/src/families/nemotron/cuda_engine.zig index 32f21bf2706..f0bf66986da 100644 --- a/zig/src/families/nemotron/cuda_engine.zig +++ b/zig/src/families/nemotron/cuda_engine.zig @@ -39,6 +39,7 @@ pub const Options = struct { slide: bool = false, // Sliding Weights asked for: refused for a checkpoint the learner cannot read vision: ?@import("cuda_vision.zig").Limits = null, // --vision: the checkpoint's image tower (an omni checkpoint's) precision: ?@import("config.zig").Precision = null, // --precision; null: the checkpoint's math where it is built + place: ?latent.At = null, // the server's resolved launch; null: the tools' TF_NEMOTRON_* (latent.place) }; const prompt_hooks = @import("cuda_prompt_hooks.zig"); @@ -49,8 +50,8 @@ pub const Taps = prompt_hooks.Taps; /// Serial rounds a host keeps queued ahead of the one it reads. pub const lookahead = 4; -/// Streams a shared window holds at most (their rows together at most state.windowRows). -pub const max_streams = 8; +/// Streams a shared window holds at most (their rows together at most state.sharedRows; 8 without the wide switch). +pub const max_streams = @import("cuda_wide.zig").wide_streams; // pinned words: the window's meta row, its ids, its sampled ids, a prompt chunk's ids, then a shared window's streams const pin_meta = 0; @@ -59,8 +60,10 @@ pub const pin_sampled = pin_ids + state.max_rows; const window_words = pin_sampled + state.max_rows; // a window's words, as a shared window's stream lays its own out pub const pin_prompt = window_words; const pin_shared = pin_prompt + @max(segs.MAX * state.prefill_rows, state.pass_rows); -// a shared window's batched draw: a Rule a row, a position a row, then its tokens -const pin_draw = pin_shared + max_streams * window_words; +/// Where a shared window's batched draw (a Rule a row, a position a row, its tokens) begins: past the switch's streams. +pub fn pinDraw(c: Config) usize { + return pin_shared + @import("cuda_wide.zig").streams(c) * window_words; +} const draw_rules_words = state.max_rows * 8; const draw_meta_words = state.max_rows; const draw_tokens_words = state.max_rows; @@ -138,7 +141,7 @@ pub const Engine = struct { e.* = .{ .gpa = gpa, .io = io, .ctx = ctx, .stream = undefined, .k = undefined, .w = undefined, .b = undefined, .c = undefined, .max_len = 0, .pinned = undefined, .history = undefined }; e.trace = (@import("sys").environment.Process{}).get("TF_SLIDE_TRACE") != null; e.c = try Config.read(gpa, io, model_dir); - try latent.place(&e.c); + if (opts.place) |at| try latent.placeAt(&e.c, at) else try latent.place(&e.c); var load_cache = @import("core").checkpoint.cache.Load.begin(io, e.c.world > 1); defer load_cache.deinit(); if (e.c.rank > 0) return error.RankServesExperts; // ranks past 0 run cuda_worker.serve, not an engine @@ -158,6 +161,10 @@ pub const Engine = struct { e.side.join.deinit(); }; e.k = try kern.Kernels.load(gpa, io, ctx, triton_dir); + const wide = @import("cuda_wide.zig"); + e.c.wide_rounds = wide.on() and wide.allowed(e.c, e.k.gb10, opts.slide); // before any buffer + e.k.wide = e.c.wide_rounds; + if (wide.on()) if (wide.refusal(e.c, e.k.gb10, opts.slide)) |why| std.log.warn("TF_NEMOTRON_WIDE_ROUNDS is set but rounds stay at 8 streams: {s}", .{why}); errdefer if (!keep_owner) e.k.deinit(); if (e.c.format == .modelopt) { if (opts.slide) return error.SlideNeedsMlx; // the learner reads MLX 4-bit projections @@ -218,7 +225,7 @@ pub const Engine = struct { errdefer if (!keep_owner) if (e.seg) |*s| s.deinit(); e.own = state.Seq.view(&e.b); e.bound = &e.own; - e.pinned = try cuda.HostBuffer.alloc(ctx.d, (pin_draw + draw_rules_words + draw_meta_words + draw_tokens_words) * 4); + e.pinned = try cuda.HostBuffer.alloc(ctx.d, (pinDraw(e.c) + draw_rules_words + draw_meta_words + draw_tokens_words) * 4); errdefer if (!keep_owner) e.pinned.free(); e.history = try cuda.HostBuffer.allocMapped(ctx.d, (@as(usize, e.max_len) + state.max_rows) * 4); errdefer if (!keep_owner) e.history.free(); @@ -464,15 +471,16 @@ pub const Engine = struct { /// Several streams' windows in one forward (eager): each stream's rows read its own caches, state and rule. pub fn verifyShared(e: *Engine, parts: []const Shared) !void { - if (parts.len < 1 or parts.len > max_streams) return error.BadWindow; + if (parts.len < 1 or parts.len > @import("cuda_wide.zig").streams(e.c)) return error.BadWindow; var total: usize = 0; for (parts) |p| { - if (p.rows < 1 or p.ids.len < 1 or p.ids.len > p.rows) return error.BadWindow; + // a stream's rows stride at windowRows in its own buffers (ids, hidden, Mamba rows), however wide the round + if (p.rows < 1 or p.rows > state.windowRows(e.c) or p.ids.len < 1 or p.ids.len > p.rows) return error.BadWindow; total += p.rows; } - if (total > state.windowRows(e.c)) return error.WindowTooWide; + if (total > state.sharedRows(e.c)) return error.WindowTooWide; try e.copied.synchronize(); - const host = e.pinned.slice(u32)[pin_shared..][0 .. max_streams * window_words]; + const host = e.pinned.slice(u32)[pin_shared..][0 .. parts.len * window_words]; var views: [max_streams]state.Buffers = undefined; var parts_f: [max_streams]Seg = undefined; var row0: usize = 0; @@ -495,13 +503,13 @@ pub const Engine = struct { e.draw_at[k] = @intCast(draw_row); draw_row += p.rows; } - var batch = if (parts.len > 1) @import("cuda_shared_draw.zig").batch(sd[0..parts.len], e.pinned, e.b.draw_rules, e.b.draw_meta, e.b.draw_tokens, pin_draw, pin_draw + draw_rules_words) else null; + var batch = if (parts.len > 1) @import("cuda_shared_draw.zig").batch(sd[0..parts.len], e.pinned, e.b.draw_rules, e.b.draw_meta, e.b.draw_tokens, pinDraw(e.c), pinDraw(e.c) + draw_rules_words) else null; if (batch) |b| try @import("cuda_shared_draw.zig").upload(b, e.ops()); try e.copied.record(e.stream); var f = e.forward(null); f.batch = if (batch) |*b| b else null; try f.windowSegs(parts_f[0..parts.len]); - const slab = e.pinned.slice(u32)[pin_draw + draw_rules_words + draw_meta_words ..][0..draw_row]; + const slab = e.pinned.slice(u32)[pinDraw(e.c) + draw_rules_words + draw_meta_words ..][0..draw_row]; if (batch != null) { try e.ops().download(std.mem.sliceAsBytes(slab), e.b.draw_tokens); } else for (parts, 0..) |p, k| { @@ -518,7 +526,7 @@ pub const Engine = struct { /// Part k's drawn ids from the last shared window (row r: the token at its position + r + 1). pub fn sharedTokens(e: *Engine, k: usize, rows: usize) ![]const u32 { try e.sampled_ready.synchronize(); - return e.pinned.slice(u32)[pin_draw + draw_rules_words + draw_meta_words + e.draw_at[k] ..][0..rows]; + return e.pinned.slice(u32)[pinDraw(e.c) + draw_rules_words + draw_meta_words + e.draw_at[k] ..][0..rows]; } /// The window's meta row as the kernels read it: position, buffer parity, previous keep, a spare word. diff --git a/zig/src/families/nemotron/cuda_forward.zig b/zig/src/families/nemotron/cuda_forward.zig index 926dfee8e7f..fd9833c229e 100644 --- a/zig/src/families/nemotron/cuda_forward.zig +++ b/zig/src/families/nemotron/cuda_forward.zig @@ -5,6 +5,7 @@ const cuda = @import("cuda"); const Config = @import("config.zig").Config; const kern = @import("cuda_kernels.zig"); const glue = @import("cuda_glue.zig"); +const max_streams = @import("cuda_engine.zig").max_streams; const weights = @import("cuda_weights.zig"); const state = @import("cuda_state.zig"); const Dump = @import("cuda_dump.zig").Dump; @@ -160,6 +161,8 @@ pub const Forward = struct { /// Streams share matmuls, norms and experts but keep their mixer state; each row's latch alone picks its lessons. pub fn windowSegs(f: *const Forward, segs: []const Seg) !void { + // the lesson route holds 8 streams (train.cu's too): lessons past it would be dropped, never silently + if (segs.len > lesson_route.max_segments and @import("cuda_lesson_trace.zig").adapterOf(f.w) != null) return error.LessonsPastRoute; var routed = f.routedWindow(segs); var flight: worker.Flight = .{ .jobs = if (routed.pass) |p| p.jobs else 0 }; routed.flight = &flight; @@ -194,7 +197,7 @@ pub const Forward = struct { const D: u64 = c.hidden; var rows: usize = 0; for (segs) |s| rows += s.rows; - if (rows > ms.rmax) return error.WindowTooWide; + if (!@import("cuda_wide.zig").windowFits(c, rows)) return error.WindowTooWide; // each stream keeps rmax rows for (segs) |s| try f.embed(s.b.ids, b.emb + s.row0 * D * 2, s.rows); try f.mark(.embed); var x = b.emb; @@ -244,13 +247,9 @@ pub const Forward = struct { const qd: u64 = c.heads * c.head_dim; try o.dense(b.y, b.xs, a.qkv, b.qkv, rows); try f.mark(.qkv); - var k0: usize = 0; - while (k0 < segs.len) : (k0 += glue.max_segs) { - const part = segs[k0..@min(segs.len, k0 + glue.max_segs)]; - var at_segs: [glue.max_segs]glue.AttnSeg = undefined; - for (part, at_segs[0..part.len]) |s, *out| out.* = .{ .kc = f.cache(s.b, s.b.k_cache, aj), .vc = f.cache(s.b, s.b.v_cache, aj), .meta = s.b.meta, .row0 = s.row0, .rows = s.rows, .pt = s.b.table }; - try t.attentionSegs(at_segs[0..part.len], b.qkv, b.po, b.pm, b.pl, b.att, b.axs, at); - } + var at_segs: [max_streams]glue.AttnSeg = undefined; // attentionSegs launches them in parts it rebases + for (segs, at_segs[0..segs.len]) |s, *out| out.* = .{ .kc = f.cache(s.b, s.b.k_cache, aj), .vc = f.cache(s.b, s.b.v_cache, aj), .meta = s.b.meta, .row0 = s.row0, .rows = s.rows, .pt = s.b.table }; + try t.attentionSegs(at_segs[0..segs.len], b.qkv, b.po, b.pm, b.pl, b.att, b.axs, at); try f.mark(.attention); try o.dense(b.att, b.axs, a.o, b.delta, rows); if (a.o_rest != 0) try o.restRows(b.att, qd, a.o_rest, b.delta, c.hidden, false, rows, 1, 0, c.hidden, qd); @@ -431,8 +430,8 @@ pub const Forward = struct { try sd.s.wait(sd.fork); const sp = b.sharedPlan(rows); const pairs = rows * c.slots(); - try g.decode(sd.s, .up, in[0], ex, sp, b.act, 2, pairs, 16, -1); - try g.decode(sd.s, .down_f32, in[1], ex, sp, b.ymoe, 2, pairs, 16, -1); + try g.decode(sd.s, .up, in[0], ex, sp, b.act, if (rows > 16) 4 else 2, pairs, 16, -1); + try g.decode(sd.s, .down_f32, in[1], ex, sp, b.ymoe, if (rows > 16) 4 else 2, pairs, 16, -1); try f.sharedRest(so, m, rows, true); try sd.join.record(sd.s); try f.glue.route(b.y, m.router, m.bias, b.part, b.pick, b.wts, rows, c.hidden, c.experts, c.top_k, c.slots(), c.routed_scaling, c.norm_topk); diff --git a/zig/src/families/nemotron/cuda_glue.zig b/zig/src/families/nemotron/cuda_glue.zig index 0de35e30956..f083d466e5d 100644 --- a/zig/src/families/nemotron/cuda_glue.zig +++ b/zig/src/families/nemotron/cuda_glue.zig @@ -78,6 +78,22 @@ const ScanSegs = extern struct { p: [max_segs]u64, xc: [max_segs]u64, dt: [max_s /// A stream's attention in a shared window, at one layer: its caches, meta row and first row of the shared rows. pub const AttnSeg = struct { kc: u64, vc: u64, meta: u64, row0: usize, rows: usize, pt: u64 = 0 }; +/// Whether the streams' rows follow each other from the first's: a launch's table maps its rows by their starts. +fn contiguous(segs: []const AttnSeg) bool { + var next = segs[0].row0; + for (segs) |s| { + if (s.row0 != next) return false; + next += s.rows; + } + return true; +} + +/// The attention buffers at row `r0`: qkv, partial outputs, maxima and sums, the output and its group sums. +fn rowsAt(r0: u64, at: Attn, b: [6]u64) [6]u64 { + const qd: u64 = at.heads * at.dim; + return .{ b[0] + r0 * at.nqkv * 2, b[1] + r0 * at.nch * qd * 4, b[2] + r0 * at.nch * at.heads * 4, b[3] + r0 * at.nch * at.heads * 4, b[4] + r0 * qd * 2, b[5] + r0 * (qd / 64) * 4 }; +} + const AttnSegs = extern struct { kc: [max_segs]u64, vc: [max_segs]u64, meta: [max_segs]u64, pt: [max_segs]u64, ps: i64, row0: [max_segs]c_int, n: c_int }; /// The router's K slices and the shared bytes its block stages: 16 rows and 16 experts of one slice, padded a word. @@ -184,6 +200,7 @@ pub const Glue = struct { /// The Mamba conv of a window: the last window's kept rows replay from RAW, then the window's rows. pub fn conv(g: Glue, proj: u64, base: u64, raw: u64, xc: u64, cw: u64, cb: u64, meta: u64, rows: usize, m: Shape) !void { + if (rows > m.rmax) return error.ScanShape; // a stream's rows stride at rmax, as the scan's if (g.tri()) |t| return t.conv(proj, base, raw, xc, cw, cb, meta, rows, m); var a: cuda.Args = .{}; ptrs(&a, &.{ proj, base, raw, xc, cw, cb, meta }); @@ -207,6 +224,7 @@ pub const Glue = struct { /// Every stream's conv, then every stream's scan, of a shared window: one launch each, or a stream at a time. pub fn mambaSegs(g: Glue, segs: []const MambaSeg, cw: u64, cb: u64, a_: u64, dsk: u64, dtb: u64, lo: f32, hi: f32, m: Shape) !void { + for (segs) |s| if (s.rows > m.rmax) return error.ScanShape; // each stream's conv and scan rows stride at rmax if (g.set != null or segs.len < 2 or segs.len > max_segs) { for (segs) |s| { try g.conv(s.proj, s.base, s.raw, s.xc, cw, cb, s.meta, s.rows, m); @@ -295,49 +313,56 @@ pub const Glue = struct { try g.go(g.f.attn_merge, .{ rows, at.kv_heads, 1 }, 256, 0, &b); } - /// Every stream's keys, values and attention over the shared rows: one launch each, or a stream at a time. + /// Every stream's keys, values and attention over the shared rows: launches of up to max_segs streams each. pub fn attentionSegs(g: Glue, segs: []const AttnSeg, qkv: u64, po: u64, pm: u64, pl: u64, out: u64, xs: u64, at: Attn) !void { - var rows: usize = 0; - for (segs) |s| rows += s.rows; - if (g.set != null or segs.len < 2 or segs.len > max_segs) { - const qd: u64 = at.heads * at.dim; + var k0: usize = 0; + while (k0 < segs.len) : (k0 += max_segs) try g.attentionPart(segs[k0..@min(segs.len, k0 + max_segs)], qkv, po, pm, pl, out, xs, at); + } + + /// Up to max_segs streams a launch, rows and table rebased to the part's first row; else one stream at a time. + fn attentionPart(g: Glue, segs: []const AttnSeg, qkv: u64, po: u64, pm: u64, pl: u64, out: u64, xs: u64, at: Attn) !void { + if (g.set != null or segs.len < 2 or segs.len > max_segs or !contiguous(segs)) { for (segs) |s| { - const r0: u64 = s.row0; - const q = qkv + r0 * at.nqkv * 2; + const r = rowsAt(s.row0, at, .{ qkv, po, pm, pl, out, xs }); var own = at; own.pt = s.pt; - try g.kvWrite(q, s.kc, s.vc, s.meta, s.rows, own); - try g.attention(q, s.kc, s.vc, s.meta, po + r0 * at.nch * qd * 4, pm + r0 * at.nch * at.heads * 4, pl + r0 * at.nch * at.heads * 4, out + r0 * qd * 2, xs + r0 * (qd / 64) * 4, s.rows, own); + try g.kvWrite(r[0], s.kc, s.vc, s.meta, s.rows, own); + try g.attention(r[0], s.kc, s.vc, s.meta, r[1], r[2], r[3], r[4], r[5], s.rows, own); } return; } const grp = at.heads / at.kv_heads; if (at.dim != 128 or grp > 16) return error.AttentionShape; + // the kernels index launch rows from 0 (seg_of): the part's rows start there, buffers moved to its first row + const base = segs[0].row0; + const r = rowsAt(base, at, .{ qkv, po, pm, pl, out, xs }); + var rows: usize = 0; var t = std.mem.zeroes(AttnSegs); for (segs, 0..) |s, k| { t.kc[k] = s.kc; t.vc[k] = s.vc; t.meta[k] = s.meta; t.pt[k] = s.pt; - t.row0[k] = int(s.row0); + t.row0[k] = int(s.row0 - base); + rows += s.rows; } t.ps = @intCast(at.ps); t.n = int(segs.len); var w: cuda.Args = .{}; w.add(t); - w.add(qkv); + w.add(r[0]); ints(&w, &.{ at.nqkv, at.heads * at.dim, at.kv_heads * at.dim }); try g.go(g.f.kv_write_segs, .{ rows, 1, 1 }, 256, 0, &w); const scale: f32 = @floatCast(std.math.pow(f64, @floatFromInt(at.dim), -0.5)); var a: cuda.Args = .{}; a.add(t); - ptrs(&a, &.{ qkv, po, pm, pl }); + ptrs(&a, &.{ r[0], r[1], r[2], r[3] }); ints(&a, &.{ at.nqkv, at.heads, at.kv_heads, grp, chunk_keys, at.nch }); a.add(scale); try g.go(g.f.attn_chunk_segs, .{ rows, at.kv_heads, @min(at.nch, chunk_blocks) }, 256, 0, &a); var b: cuda.Args = .{}; b.add(t); - ptrs(&b, &.{ po, pm, pl, out, xs }); + ptrs(&b, &.{ r[1], r[2], r[3], r[4], r[5] }); ints(&b, &.{ at.heads, at.kv_heads, grp, chunk_keys, at.nch }); try g.go(g.f.attn_merge_segs, .{ rows, at.kv_heads, 1 }, 256, 0, &b); } diff --git a/zig/src/families/nemotron/cuda_kernels.zig b/zig/src/families/nemotron/cuda_kernels.zig index d1be32fa78f..ee5ea671981 100644 --- a/zig/src/families/nemotron/cuda_kernels.zig +++ b/zig/src/families/nemotron/cuda_kernels.zig @@ -5,6 +5,9 @@ const cuda = @import("cuda"); const torch_ops = @import("cuda_torch_ops.zig"); const train_ops = @import("cuda_train_ops.zig"); const glue = @import("cuda_glue.zig"); +const parts = @import("cuda_wide.zig").wide_streams; +/// Rows tf_plan_routed stages at most (nemotron_ops.cu pk). +pub const plan_rows = 32; // a shared round's or batched draft's parts: nemotron_ops.cu PARTS /// Mangled names of the instantiations the copies in zig/kernels/cuda export (cuobjdump -symbols of each fatbin). const sym = struct { @@ -43,11 +46,11 @@ pub const Snaps = extern struct { }; /// A batched draft's rows: each part's `a` (wa bytes a row) and `b` (wb bytes a row), its start and row count. -pub const GatherRows = extern struct { a: [8]u64 = @splat(0), b: [8]u64 = @splat(0), rows: [8]c_int = @splat(0), row0: [8]c_int = @splat(0), wa: c_int = 0, wb: c_int = 0 }; +pub const GatherRows = extern struct { a: [parts]u64 = @splat(0), b: [parts]u64 = @splat(0), rows: [parts]c_int = @splat(0), row0: [parts]c_int = @splat(0), wa: c_int = 0, wb: c_int = 0 }; /// A span's last row: each part's source rows, moved to the destination rows in part order. -pub const LastRows = extern struct { a: [8]u64 = @splat(0), b: [8]u64 = @splat(0) }; +pub const LastRows = extern struct { a: [parts]u64 = @splat(0), b: [parts]u64 = @splat(0) }; /// A level's rows: each part's token and probability destinations, its start and row count, the level's words. -pub const ScatterRows = extern struct { tok: [8]u64 = @splat(0), prob: [8]u64 = @splat(0), rows: [8]c_int = @splat(0), row0: [8]c_int = @splat(0), tok_at: c_int = 0, prob_at: c_int = 0 }; +pub const ScatterRows = extern struct { tok: [parts]u64 = @splat(0), prob: [parts]u64 = @splat(0), rows: [parts]c_int = @splat(0), row0: [parts]c_int = @splat(0), tok_at: c_int = 0, prob_at: c_int = 0 }; pub const Kernels = struct { d: *const cuda.Driver, @@ -58,6 +61,7 @@ pub const Kernels = struct { norms: cuda.norms.Norms, moe: cuda.moe_glue.MoeGlue, // the shared top-k and combine affine: cuda.qlinear.Affine4Kernels, // the 4-bit projections: qmm_group, lane_gemv and qmm_prefill + wide: bool = false, // TF_NEMOTRON_WIDE_ROUNDS took at load: only then do 17-32 rows plan and project router: cuda.grouped.Router, experts: cuda.experts.Affine4Experts, // the 4-bit grouped experts: experts, experts_prefill and experts_pack pattn: cuda.Function, @@ -91,6 +95,7 @@ pub const Kernels = struct { const d = ctx.d; if (!cuda.kernels.available) return error.BuiltWithoutKernels; var k: Kernels = undefined; + k.wide = false; k.d = d; const kk = cuda.kernels; const images = [_][]const u8{ kk.qmm_group, kk.qmm_prefill, kk.experts, kk.experts_prefill, kk.experts_pack, kk.prefill_attention, kk.scan_rows, kk.nemotron_ops, kk.torch_argmax, kk.torch_topk, kk.torch_pointwise, kk.torch_indexing, kk.torch_movement, kk.torch_nemotron_constants, kk.sample, kk.lane_gemv, kk.nemotron_route, kk.nemotron_mamba, kk.nemotron_attention, kk.nemotron_keyed, kk.affine4_pack }; @@ -353,6 +358,8 @@ pub const Ops = struct { /// Decode rows of a projection on this stream (the affine-4 paths' bits unchanged); xs: x's 64-group sums. pub fn dense(o: Ops, x: u64, xs: u64, q: QLinear, out: u64, rows: usize) !void { + // a wide round's 17-32 affine-4 rows take verify's tiles (decode's chain a row); main's decode at 16 or fewer + if (o.k.wide and q == .affine4 and rows > cuda.qlinear.Affine4Kernels.max_rows) return o.k.affine.verify(o.s, x, xs, q.affine4, out, rows); return o.linear().decode(o.s, q, .{ .x = x, .sums = xs, .part = o.part }, out, rows); } @@ -449,7 +456,7 @@ pub const Ops = struct { /// experts.route's plan over the routed slots alone (rows <= 16, experts <= 128): the shared halves run apart. pub fn planRouted(o: Ops, picks: u64, rows: usize, slots: usize, routed: usize, count: usize, tile: usize, p: Plan) !void { - if (rows > 16 or slots > 8 or count > 128) return error.PlanTooWide; + if (rows > @as(usize, if (o.k.wide) plan_rows else 16) or slots > 8 or count > 128) return error.PlanTooWide; // pk: 32 rows on var a: cuda.Args = .{}; a.add(picks); for ([_]usize{ rows, slots, routed, count, tile }) |v| a.add(int(v)); diff --git a/zig/src/families/nemotron/cuda_lanes.zig b/zig/src/families/nemotron/cuda_lanes.zig index 8a31532c432..5fe0f28d00e 100644 --- a/zig/src/families/nemotron/cuda_lanes.zig +++ b/zig/src/families/nemotron/cuda_lanes.zig @@ -21,8 +21,10 @@ const fill = @import("cuda_lanes_fill.zig"); const be = lanes.backend; const LogRow = lanes.LogprobRow; const row_words = lanes.logprob.words; -/// Host-mapped words for every row a shared window holds, then the first token's row. -const row_slots = engine.max_streams * state.max_rows + 1; +/// Host-mapped words for every row a shared window holds (the switch's streams), then the first token's row. +pub fn rowSlots(c: config.Config) usize { + return @import("cuda_wide.zig").streams(c) * state.max_rows + 1; +} /// First tokens a handle names (the prompt's draw is on the host once prefill returns). const ring = 1024; /// A stream's sequence (`own`: the engine's, the graphs' buffers; `paged`: the pool's) and its first logprob row. @@ -45,7 +47,7 @@ pub const Cuda = struct { drawn: [ring]u32 = undefined, next: u64 = 0, pinned: cuda.HostBuffer, // each window's held drafts read back (state.max_rows words a stream) - rows_out: cuda.HostBuffer, // logprob rows the kernel writes straight to the host (row_slots of row_words) + rows_out: cuda.HostBuffer, // logprob rows the kernel writes straight to the host (rowSlots of row_words) rows_dev: u64, prompt_out: cuda.HostBuffer, // a prompt pass's rows (batch_rows of row_words), then its picks; apart from pending window rows prompt_dev: u64, @@ -56,14 +58,15 @@ pub const Cuda = struct { measured: ?costs.Measured = null, // a lone stream's depth rules price its rounds by these mtp_drafts: ?u32 = null, mtp_confidence: ?f64 = null, - bits: ?cuda.HostBuffer = null, // structured output's row bits, device-mapped (row_slots rows), made at first use + bits: ?cuda.HostBuffer = null, // structured output's row bits, device-mapped (rowSlots rows), made at first use bits_dev: u64 = 0, tapped: ?cuda.HostBuffer = null, // a recorder's rows on their way to the host (state.pass_rows of them) copy_drafts: bool = false, // the global draft switch also controls lane-core copy proposals pub fn init(gpa: std.mem.Allocator, e: *Engine, head: ?*Head) !Cuda { - var pinned = try cuda.HostBuffer.alloc(e.ctx.d, engine.max_streams * state.max_rows * 4); + const slots = rowSlots(e.c); + var pinned = try cuda.HostBuffer.alloc(e.ctx.d, @import("cuda_wide.zig").streams(e.c) * state.max_rows * 4); errdefer pinned.free(); - var rows_out = try cuda.HostBuffer.allocMapped(e.ctx.d, row_slots * row_words * 4); + var rows_out = try cuda.HostBuffer.allocMapped(e.ctx.d, slots * row_words * 4); errdefer rows_out.free(); var prompt_out = try cuda.HostBuffer.allocMapped(e.ctx.d, prompt_rows.batch_rows * (row_words + 1) * 4); errdefer prompt_out.free(); @@ -112,9 +115,9 @@ pub const Cuda = struct { pub fn putBits(self: *Cuda, slot: usize, masks: []const u32) !engine.Mask { const words = (self.e.c.vocab + 31) / 32; if (masks.len == 0) return .{}; - if (masks.len % words != 0 or slot * words + masks.len > row_slots * words) return error.InvalidGrammarMasks; + if (masks.len % words != 0 or slot * words + masks.len > rowSlots(self.e.c) * words) return error.InvalidGrammarMasks; if (self.bits == null) { - self.bits = try cuda.HostBuffer.allocMapped(self.e.ctx.d, row_slots * words * 4); + self.bits = try cuda.HostBuffer.allocMapped(self.e.ctx.d, rowSlots(self.e.c) * words * 4); self.bits_dev = try self.bits.?.device(); } @memcpy(self.bits.?.slice(u32)[slot * words ..][0..masks.len], masks); @@ -127,7 +130,7 @@ pub const Cuda = struct { if (position != s.prompt_len) return error.PositionMismatch; const l = self.lanes.getPtr(s) orelse return error.UnknownStream; self.e.bind(l.seq); - return self.take(try self.e.redrawFirst(position, try self.putBits(row_slots - 1, mask))); + return self.take(try self.e.redrawFirst(position, try self.putBits(rowSlots(self.e.c) - 1, mask))); } /// The head's drafts in the stream's window rows after the pending one, once they land (Backend.held). @@ -172,8 +175,9 @@ pub const Cuda = struct { .window_costs = self.costs[0..self.cost_count], .mtp_step_ms = self.mtp_ms, .hidden_rows = true, // copy-only models retain the landed shared target forward - .batch_rows = @intCast(width), - .max_streams = engine.max_streams, + .batch_rows = @intCast(state.sharedRows(self.e.c)), // 32 with TF_NEMOTRON_WIDE_ROUNDS; 17-32 priced linearly + .learn_row_costs = self.e.c.wide_rounds, // 17-32 rows are unmeasured: learn their cost, not a fixed overhead + .max_streams = @intCast(@import("cuda_wide.zig").streams(self.e.c)), }; } @@ -408,7 +412,7 @@ pub const Cuda = struct { /// Several windows in one forward (Engine.verifyShared), each stream's rows on its own sequence. fn verifyShared(self: *Cuda, windows: []const be.Window, out: []be.Verified) !void { const e = self.e; - if (windows.len > engine.max_streams) return error.WindowTooWide; + if (windows.len > @import("cuda_wide.zig").streams(self.e.c)) return error.WindowTooWide; // 8 with the switch off var parts: [engine.max_streams]engine.Shared = undefined; var ids: [engine.max_streams][state.max_rows]u32 = undefined; var bits_row: usize = 0; @@ -474,7 +478,7 @@ pub const Cuda = struct { break :blk first[0..]; }; const v = h.vocab(r.stream.context.items); - if (drafting < 2 or r.depth == 0 or batched == parts.len or rows + follow.len > state.windowRows(self.e.c)) { + if (drafting < 2 or r.depth == 0 or !@import("cuda_wide.zig").batches(self.e.c, batched, rows, follow.len)) { try h.chain(follow, r.depth, v); l.keep = h.keep; continue; diff --git a/zig/src/families/nemotron/cuda_lanes_fill.zig b/zig/src/families/nemotron/cuda_lanes_fill.zig index 1dab9362ed3..2ed73770243 100644 --- a/zig/src/families/nemotron/cuda_lanes_fill.zig +++ b/zig/src/families/nemotron/cuda_lanes_fill.zig @@ -11,8 +11,6 @@ const heat = @import("heat"); const Cuda = @import("cuda_lanes.zig").Cuda; const LogRow = lanes.LogprobRow; const row_words = lanes.logprob.words; -/// Host-mapped words for every row a shared window holds, then the first token's row (cuda_lanes.zig's row_slots). -const row_slots = engine.max_streams * state.max_rows + 1; /// Stepped passes between their chunks, by stream: each one's serial pass (cuda_prompt.zig's Pass). pub const Fills = std.AutoHashMapUnmanaged(*const lanes.Stream, pass.Pass); @@ -112,7 +110,7 @@ fn finish(self: *Cuda, s: *lanes.Stream, first: u32) !void { _ = self.take(first); s.fill_at.store(@intCast(ids.len), .monotonic); // the whole prompt, as a whole pass or a last chunk ends it if (s.logprobs) |k| { - const at = (row_slots - 1) * row_words; + const at = (@import("cuda_lanes.zig").rowSlots(self.e.c) - 1) * row_words; try e.ops().logprobRows(e.b.p_logits, e.c.vocab, e.b.p_sampled, k, false, self.rows_dev + at * 4, 1); try e.stream.synchronize(); self.lanes.getPtr(s).?.first = LogRow.fromWords(self.rows_out.slice(u32)[at..][0..row_words], first, k); diff --git a/zig/src/families/nemotron/cuda_latent.zig b/zig/src/families/nemotron/cuda_latent.zig index 5bfeef06e43..a98c8687498 100644 --- a/zig/src/families/nemotron/cuda_latent.zig +++ b/zig/src/families/nemotron/cuda_latent.zig @@ -85,15 +85,22 @@ pub fn partFloats(c: Config, rows: usize) usize { return rows * c.top_k * own * c.latent + rows * own * c.hidden; } -/// TF_NEMOTRON_RANK of TF_NEMOTRON_WORLD into `c`: both or neither; a world must hold whole shares. +/// The tools' place (cli, tf-cuda-test): TF_NEMOTRON_RANK of TF_NEMOTRON_WORLD, both or neither, their input as before. pub fn place(c: *Config) !void { const env = @import("sys").environment; const r = try env.read(?u64, "TF_NEMOTRON_RANK", null); const w = try env.read(?u64, "TF_NEMOTRON_WORLD", null); if (r == null and w == null) return; if (r == null or w == null) return error.NoRank; - c.rank = @intCast(r.?); - c.world = @intCast(w.?); + return placeAt(c, .{ .rank = @intCast(r.?), .world = @intCast(w.?) }); +} + +pub const At = struct { rank: usize, world: usize }; + +/// `at` into `c` (the server's resolved launch, or a tool's variables): a world must hold whole shares. +pub fn placeAt(c: *Config, at: At) !void { + c.rank = at.rank; + c.world = at.world; if (c.world < 1 or c.rank >= c.world) return error.NoRank; if (c.world == 1) return; if (c.latent == 0) { diff --git a/zig/src/families/nemotron/cuda_lesson_trace.zig b/zig/src/families/nemotron/cuda_lesson_trace.zig index cdd783eb4cf..c0e8c64fd99 100644 --- a/zig/src/families/nemotron/cuda_lesson_trace.zig +++ b/zig/src/families/nemotron/cuda_lesson_trace.zig @@ -8,7 +8,12 @@ const lesson_route = @import("living").lesson_route; /// Any block's change, for the buffers every block shares (null: no lesson is attached). pub fn lessons(e: *const Engine) ?weights.Adapter { - for (e.w.blocks) |blk| switch (blk.kind) { + return adapterOf(&e.w); +} + +/// The first block's change in `w` (null: no lesson is attached, by Sliding Weights or saved lessons). +pub fn adapterOf(w: *const weights.Weights) ?weights.Adapter { + for (w.blocks) |blk| switch (blk.kind) { .mamba => if (blk.mamba.adapter) |ad| return ad, .attention => if (blk.attn.adapter) |ad| return ad, .moe => if (blk.moe.adapter) |ad| return ad, diff --git a/zig/src/families/nemotron/cuda_mtp.zig b/zig/src/families/nemotron/cuda_mtp.zig index 5c44b3993cd..af6dd0d6a83 100644 --- a/zig/src/families/nemotron/cuda_mtp.zig +++ b/zig/src/families/nemotron/cuda_mtp.zig @@ -19,9 +19,16 @@ const host_drafts = meta_words; // pinned layout: meta, drafts, confidences, the const host_probs = host_drafts + max_chain; const host_tokens = host_probs + max_chain; const host_metas = host_tokens + state.pass_rows; // a meta row a stream for `chains` -const host_rules = host_metas + streams * meta_words; // a Rule a stream -const host_pos = host_rules + streams * 8; -const host_words = host_pos + streams; +/// The pinned layout past the metas, for `n` streams (the switch's: main's 8 off): a Rule a stream, then positions. +fn hostRules(n: usize) usize { + return host_metas + n * meta_words; +} +fn hostPos(n: usize) usize { + return hostRules(n) + n * 8; +} +pub fn hostWords(n: usize) usize { + return hostPos(n) + n; +} /// The output rows a draft level reads: the draft vocabulary's (the draft head), or the target's whole head. pub const Vocab = @import("cuda_mtp_projection.zig").Vocab; @@ -128,7 +135,7 @@ pub const Head = struct { const R: usize = state.pass_rows; const kv: usize = @as(usize, e.max_len) * c.kv_heads * c.head_dim * 2; const n = if (e.w.draft_coverage != null) c.vocab else e.w.draft_count; - const S: usize = streams; + const S: usize = @import("cuda_wide.zig").streams(c); // main's 8 with the switch off const sizes = [_]usize{ kv, kv, meta_words * 4, state.max_rows * D * 2, state.max_rows * 4, max_chain * 4, D * 2, R * D * 2, R * 2 * D * 2, R * 2 * D / 64 * 4, R * D * 2, S * D * 2, S * D * 2, S * D * 2, S * D / 64 * 4, S * n * 2, S * n * 4, S * sampler.max_candidates * 4, S * sampler.max_candidates * 8, S * sampler.max_candidates * 8, 32, S * D * 2, S * meta_words * 4, R * 4, torch_ops.topkScratchBytes(S, n), 4, S * 32, S * 4, S * 4, S * 4 }; var total: usize = 0; for (sizes) |s| total += std.mem.alignForward(usize, s, 256); @@ -145,7 +152,7 @@ pub const Head = struct { at += std.mem.alignForward(usize, s, 256); } try h.buf.fill8(0, e.stream.handle); // on the engine's stream: the legacy one would race its first uploads - h.pinned = try cuda.HostBuffer.alloc(e.ctx.d, host_words * 4); + h.pinned = try cuda.HostBuffer.alloc(e.ctx.d, hostWords(S) * 4); h.has_pinned = true; h.copied = try cuda.Event.init(e.ctx.d, false); h.has_copied = true; @@ -258,14 +265,9 @@ pub const Head = struct { try o.dense(h.cat, h.cxs, m.eh_proj, h.x, rows); try t.addRmsnorm(h.x, null, m.attn_norm, h.x, b.y, b.xs, rows, c.hidden, c.eps); try o.dense(b.y, b.xs, m.attn.qkv, b.qkv, rows); - var segs_buf: [glue.max_segs]glue.AttnSeg = undefined; - var at0: usize = 0; - while (at0 < spans.len) { - const take = @min(glue.max_segs, spans.len - at0); - for (spans[at0..][0..take], segs_buf[0..take]) |s, *sg| sg.* = .{ .kc = s.k_cache, .vc = s.v_cache, .meta = s.meta, .row0 = s.row0, .rows = s.rows, .pt = s.table }; - try t.attentionSegs(segs_buf[0..take], b.qkv, b.po, b.pm, b.pl, b.att, b.axs, f.ashape()); - at0 += take; - } + var segs_buf: [streams]glue.AttnSeg = undefined; // attentionSegs launches them in parts it rebases + for (spans, segs_buf[0..spans.len]) |s, *sg| sg.* = .{ .kc = s.k_cache, .vc = s.v_cache, .meta = s.meta, .row0 = s.row0, .rows = s.rows, .pt = s.table }; + try t.attentionSegs(segs_buf[0..spans.len], b.qkv, b.po, b.pm, b.pl, b.att, b.axs, f.ashape()); try o.dense(b.att, b.axs, m.attn.o, b.delta, rows); if (!tail) return; if (spans.len == 1) { @@ -422,13 +424,13 @@ pub const Head = struct { const e = h.e; const o = e.ops(); const D: u64 = e.c.hidden; - if (parts.len < 1 or parts.len > streams) return error.BadDraftRequest; + if (parts.len < 1 or parts.len > @import("cuda_wide.zig").streams(e.c)) return error.BadDraftRequest; // 8 off var total: usize = 0; for (parts) |p| { - if (p.keep < 1 or p.depth < 1 or p.depth >= state.windowRows(e.c)) return error.BadDraftRequest; + if (p.keep < 1 or p.keep > state.windowRows(e.c) or p.depth < 1 or p.depth >= state.windowRows(e.c)) return error.BadDraftRequest; total += p.keep; } - if (total > state.windowRows(e.c)) return error.BadDraftRequest; + if (total > state.sharedRows(e.c)) return error.BadDraftRequest; // the deepest first: the streams still drafting at a level are the leading rows of the last level's output std.mem.sort(Part, parts, {}, struct { fn deeper(_: void, x: Part, y: Part) bool { @@ -447,10 +449,10 @@ pub const Head = struct { var batched = e.k.triton == null and parts.len > 1; for (parts) |p| batched = batched and p.vocab == parts[0].vocab and (p.rule != null) == sampled and (!sampled or p.rule_host != null); if (batched and sampled) { - const rules = std.mem.sliceAsBytes(h.pinned.slice(u32)[host_rules..][0 .. parts.len * 8]); + const rules = std.mem.sliceAsBytes(h.pinned.slice(u32)[hostRules(@import("cuda_wide.zig").streams(e.c))..][0 .. parts.len * 8]); for (parts, 0..) |p, k| @memcpy(rules[k * 32 ..][0..32], std.mem.asBytes(&p.rule_host.?)); try o.upload(h.rules, rules); - const pos = h.pinned.slice(u32)[host_pos..][0..parts.len]; + const pos = h.pinned.slice(u32)[hostPos(@import("cuda_wide.zig").streams(e.c))..][0..parts.len]; for (parts, 0..) |p, k| pos[k] = @intCast(p.pos + p.keep); try o.upload(h.pos_slab, std.mem.sliceAsBytes(pos)); } diff --git a/zig/src/families/nemotron/cuda_native.zig b/zig/src/families/nemotron/cuda_native.zig index ea2ca3da1c8..55fc8fa7d7f 100644 --- a/zig/src/families/nemotron/cuda_native.zig +++ b/zig/src/families/nemotron/cuda_native.zig @@ -37,7 +37,21 @@ pub const prompt_rows: u32 = state.pass_rows; pub const window_rows: u32 = state.max_rows; // a request's last verify window: its pages hold that many rows past it pub const max_drafts: u32 = @import("cuda_mtp.zig").max_chain; // Super's; open refuses more than a checkpoint's window holds -pub const Options = struct { context: usize, drafts: bool, segments: usize = 1, slide: bool = false, vision: ?vision.Limits = null, precision: ?@import("config.zig").Precision = null, mtp_drafts: ?u32 = null, mtp_confidence: ?f64 = null }; +pub const Options = struct { + context: usize, + drafts: bool, + segments: usize = 1, + slide: bool = false, + vision: ?vision.Limits = null, + precision: ?@import("config.zig").Precision = null, + mtp_drafts: ?u32 = null, + mtp_confidence: ?f64 = null, + rank: u32 = 0, // the launch's, resolved from --tp/--rank and TF_NEMOTRON_* (native/cuda_launch.zig) + tp: u32 = 1, + master: ?[]const u8 = null, + master_port: u16 = 29551, + launch_from: []const u8 = "", +}; pub const vision = @import("cuda_vision.zig"); /// Thinking budgets the lone driver takes (cuda_lone.zig): above it, the stream goes to the lane core before its cut. @@ -113,9 +127,10 @@ const Owned = struct { gpa: std.mem.Allocator, e: *engine.Engine, head: ?*Head, /// Own-sequence graphs support both draw modes; drafting also captures the head. pub fn open(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: []const u8, kernels: ?[]const u8, o: Options) !Loaded { try @import("sys").environment.checkScope(.nemotron, @import("sys").environment.Process{}); - const rank = try @import("sys").environment.read(?u64, "TF_NEMOTRON_RANK", null); - if (rank != null and rank.? != 0) { - @import("cuda_worker.zig").serve(gpa, io, ctx, dir, o.precision) catch |err| { + try cuda.rendezvous.fromMaster(o, cuda.rendezvous.Process{}, cuda.rendezvous.Process{}); // before the liveness line + if (o.tp > 1) std.log.info("[tensorfold] nemotron: rank {d} of {d} ({s})", .{ o.rank, o.tp, o.launch_from }); + if (o.rank != 0) { // expert ranks never serve + @import("cuda_worker.zig").serve(gpa, io, ctx, dir, o.precision, .{ .rank = o.rank, .world = o.tp }) catch |err| { cuda.tp_watch.fail(@errorName(err)); // rank 0 stops with this rank's error std.log.err("expert rank stopped: {s}", .{@errorName(err)}); std.c._exit(1); // a stream may still wait on rank 0: a normal exit would join it @@ -124,7 +139,7 @@ pub fn open(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: [ } const carve = try openCarveout(gpa, ctx); errdefer if (carve) |c| closeCarveout(gpa, c); - const e = try engine.Engine.init(gpa, io, ctx, dir, kernels, .{ .context = o.context, .mtp = o.drafts, .graphs = true, .sampling = null, .segments = o.segments, .carveout = carve, .slide = o.slide, .vision = o.vision, .precision = o.precision }); + const e = try engine.Engine.init(gpa, io, ctx, dir, kernels, .{ .context = o.context, .mtp = o.drafts, .graphs = true, .sampling = null, .segments = o.segments, .carveout = carve, .slide = o.slide, .vision = o.vision, .precision = o.precision, .place = .{ .rank = o.rank, .world = o.tp } }); errdefer e.deinit(); if (o.mtp_drafts) |n| if (n >= state.windowRows(e.c)) return error.DraftsPastWindow; // Bolt has no MTP weights; copy drafts use the lane core and the target's ordinary verify windows. @@ -192,6 +207,8 @@ pub fn explain(_: ?*anyopaque, err: anyerror) ?[]const u8 { error.PrecisionNotBuilt => "--precision checkpoint: NVIDIA's FP4 and FP8 math is built for Nemotron 3.5 Super VL's NVFP4 checkpoint so far; serve this one with --precision full", error.DraftsPastWindow => std.fmt.comptimePrint("--mtp-drafts: this checkpoint verifies windows of {d} rows, so a round drafts {d} at most; serve it with --mtp-drafts {d} or fewer", .{ narrow, narrow - 1, narrow - 1 }), error.CheckpointMathNeedsBlackwell => "--precision checkpoint: NVIDIA's FP4 math runs on Blackwell (compute capability 12.x); serve with --precision full", + error.RendezvousDisagree => "NCCL_COMM_ID differs from --master:--master-port: give one of them, or equal values", + error.MasterTooLong => "--master: too long for NCCL's root address (host:port in 320 bytes); give rank 0's address", else => null, }; } diff --git a/zig/src/families/nemotron/cuda_native_omni.zig b/zig/src/families/nemotron/cuda_native_omni.zig index cad0e95585c..818f7a6485d 100644 --- a/zig/src/families/nemotron/cuda_native_omni.zig +++ b/zig/src/families/nemotron/cuda_native_omni.zig @@ -39,10 +39,10 @@ pub const slideRefusal = @import("cuda_omni_slide.zig").refusal; const nvfp4_bytes: f64 = 0.5625; /// Bytes this rank's weights take: rank 0 all but the other ranks' expert shares, rank r > 0 its expert shares alone. -pub fn weightShare(a: std.mem.Allocator, io: std.Io, dir: []const u8, total: u64, drafts: bool) u64 { +pub fn weightShare(a: std.mem.Allocator, io: std.Io, dir: []const u8, total: u64, drafts: bool, rank: u32, world: u32) u64 { _ = drafts; // the MTP head's experts are counted either way var c = Config.read(a, io, dir) catch return total; - latent.place(&c) catch return total; + latent.placeAt(&c, .{ .rank = rank, .world = world }) catch return total; if (c.world < 2 or c.latent == 0) return total; const moe: f64 = @floatFromInt(c.count(.moe) + 1); // the MTP head's MoE too const per: f64 = @floatFromInt(c.experts * 2 * c.expert_width * c.latent + 2 * c.shared_width * c.hidden); diff --git a/zig/src/families/nemotron/cuda_profile_window.zig b/zig/src/families/nemotron/cuda_profile_window.zig index 0e8f73e4d77..16b9260a73b 100644 --- a/zig/src/families/nemotron/cuda_profile_window.zig +++ b/zig/src/families/nemotron/cuda_profile_window.zig @@ -94,7 +94,7 @@ test "a prose round's seventh level is priced on decoding's windows, not on the var ms: [17]f64 = @splat(0); var levels: Levels = .{}; try rule.measureWidths(Gpu{}, &levels, ms[1..], false); - try rule.smooth(Gpu{}, ms[1..]); + try rule.smoothSerial(Gpu{}, ms[1..]); var r = @import("cuda_drafts.zig").depthRule(core.draft_depth.Costs.measured(&ms, 0.7108, 16)); for ([_][3]usize{ .{ 2, 3, 3 }, .{ 4, 11, 10 }, .{ 2, 2, 2 }, .{ 4, 4, 3 } }) |x| r.done(x[0], x[1], x[2]); // rounds 0-3 var run: f64 = 1.0; diff --git a/zig/src/families/nemotron/cuda_slide.zig b/zig/src/families/nemotron/cuda_slide.zig index a86275a7ad4..926dba093bc 100644 --- a/zig/src/families/nemotron/cuda_slide.zig +++ b/zig/src/families/nemotron/cuda_slide.zig @@ -143,6 +143,7 @@ pub fn loadLiving(gpa: std.mem.Allocator, io: std.Io, e: *engine.Engine, dir: [] var sites = try sites_mod.Sites.init(gpa, e.ctx.d, c, state.prefill_rows, saved.lessons.len); errdefer sites.deinit(); const blocks = try Living.fill(&saved, c, &sites); + if (@import("cuda_wide.zig").withLessons(&e.c)) |why| std.log.warn("TF_NEMOTRON_WIDE_ROUNDS is set but rounds stay at 8 streams: {s}", .{why}); sites.attach(&e.w, true); try recapture(e); std.log.info("slide: {d} saved lessons act on the replies their routers choose", .{blocks}); diff --git a/zig/src/families/nemotron/cuda_state.zig b/zig/src/families/nemotron/cuda_state.zig index 9dc9b127469..2dc5bb6b128 100644 --- a/zig/src/families/nemotron/cuda_state.zig +++ b/zig/src/families/nemotron/cuda_state.zig @@ -10,20 +10,35 @@ const sampler = @import("cuda_sampler.zig"); const seq_graphs = @import("cuda_seq_graphs.zig"); const latent = @import("cuda_latent.zig"); const worker = @import("cuda_worker.zig"); +const wide = @import("cuda_wide.zig"); pub const max_rows = 32; // a verify window's rows at most (the widest row tile of the row-parallel kernels) pub const prefill_rows = 2048; // rows of a staggered segment's chunk, and of a pass under dumps or lessons pub const pass_rows = 2 * prefill_rows; // rows a serial prompt pass runs at most (a row's bits are the same at any cut) pub const yield_rows = 256; // rows of a background pass's chunk: a request that arrives waits for one at most pub const chunk_keys = 512; // keys an attention chunk holds, at fixed absolute positions -const shared_rows = cuda.qlinear.Affine4Kernels.max_rows; // rows a shared plan covers (windowRows without a latent MoE) -const shared_words = 2 * shared_rows + 8 * shared_rows; // the shared expert's members, then (items, counts) a row count +/// The shared plans' layout, as at load: main's 16 rows of 8 words with the switch off, 32 rows of 14 with it. +const Plans = struct { rows: usize, per: usize, counts: usize }; +const narrow_plans: Plans = .{ .rows = cuda.qlinear.Affine4Kernels.max_rows, .per = 8, .counts = 6 }; +const wide_plans: Plans = .{ .rows = max_rows, .per = 14, .counts = 12 }; +fn plansOf(wide_rounds: bool) Plans { + return if (wide_rounds) wide_plans else narrow_plans; +} +/// Words the shared plans take: the shared expert's members, then (items, counts) a row count. +fn planWords(p: Plans) usize { + return 2 * p.rows + p.per * p.rows; +} /// Super verifies 32 rows; Bolt copies and non-latent affine models retain their qualified 16-row window. pub fn windowRows(c: Config) usize { return if (c.latent > 0 and !c.bolt) max_rows else cuda.qlinear.Affine4Kernels.max_rows; } +/// A shared round's rows at most: windowRows, or 32 with TF_NEMOTRON_WIDE_ROUNDS (a lone window stays windowRows). +pub fn sharedRows(c: Config) usize { + return if (c.wide_rounds) max_rows else windowRows(c); +} + /// Sub-allocations of one device allocation, 256-byte aligned like the driver's own. const Arena = struct { buf: cuda.DeviceBuffer, @@ -105,13 +120,13 @@ const scratch_count = 48; /// Bytes of the fixed shared plans: shared_words, or a latent MoE's (Bolt's too) plan for every row count. fn sharedBytes(c: Config) usize { - return (if (c.latent > 0) windowRows(c) * Buffers.latentPlanWords(c) else shared_words) * 4; + return (if (c.latent > 0) windowRows(c) * Buffers.latentPlanWords(c) else planWords(plansOf(c.wide_rounds))) * 4; } /// Scratch windows and chunks share on one stream: window logits, chunk io, activations, the expert plan. fn scratchSizes(c: Config, nch: usize) [scratch_count]usize { const R: usize = pass_rows; - const W: usize = windowRows(c); + const W: usize = sharedRows(c); const D: usize = c.hidden; const ns: usize = c.slots(); const qd: usize = c.heads * c.head_dim; @@ -292,6 +307,7 @@ pub const Buffers = struct { rule: u64, // the sequence's sampled rule, as sample.cu reads it table: u64, // the bound sequence's page table (0: contiguous KV planes) shared: u64, // the shared expert's fixed plans: one initialized plan per row count + wide_plans: bool = false, // their layout, the switch's at load (it can only turn off after, using fewer rows) pocket: u64, // the pocket's activations, fp32 [rows, pocket_width] lane_part: u64, // the lane matmul's fp32 slice partials on a card without clusters (rows short of fusing) lat: u64, // a latent MoE's rows in the latent width (bf16) @@ -317,6 +333,7 @@ pub const Buffers = struct { var a: Arena = .{ .buf = try cuda.DeviceBuffer.alloc(d, total) }; errdefer a.buf.free(); var b: Buffers = undefined; + b.wide_plans = c.wide_rounds; b.carved = carved; b.table = 0; b.state_bytes = own[0..7].*; @@ -361,8 +378,9 @@ pub const Buffers = struct { /// The shared expert's plan at `rows` rows: halves `experts` and `experts + 1` over slots top_k and top_k + 1. pub fn sharedPlan(b: *const Buffers, rows: usize) kern.Plan { - const items = b.shared + (2 * shared_rows + 8 * @as(u64, rows - 1)) * 4; - return .{ .members = b.shared, .items = items, .counts = items + 6 * 4, .rank = 0, .hist = 0 }; + const p = plansOf(b.wide_plans); + const items = b.shared + (2 * p.rows + p.per * @as(u64, rows - 1)) * 4; + return .{ .members = b.shared, .items = items, .counts = items + p.counts * 4, .rank = 0, .hist = 0 }; } /// Words one row count's latent shared plan takes: the pairs of a window's rows, then their items and counts. @@ -398,17 +416,20 @@ pub const Buffers = struct { for (1..windowRows(c) + 1) |rows| try ops.plan(b.sids, rows * sharedPairs(c), sharedPairs(c), 16, b.latentPlan(c, rows)); return ops.s.synchronize(); } - var w: [shared_words]u32 = undefined; - for (0..shared_rows) |r| { + const p = plansOf(b.wide_plans); + var buf: [planWords(wide_plans)]u32 = undefined; + const w = buf[0..planWords(p)]; + for (0..p.rows) |r| { w[r] = @intCast(r * c.slots() + c.top_k); - w[shared_rows + r] = @intCast(r * c.slots() + c.top_k + 1); + w[p.rows + r] = @intCast(r * c.slots() + c.top_k + 1); } - for (1..shared_rows + 1) |rows| { - const at = 2 * shared_rows + 8 * (rows - 1); + for (1..p.rows + 1) |rows| { + const at = 2 * p.rows + p.per * (rows - 1); const n: u32 = @intCast(rows); - w[at..][0..8].* = .{ @intCast(c.experts), 0, n, @intCast(c.experts + 1), shared_rows, n, 2, 2 }; + // off: main's own words; on: 16-row items past 16 rows (cuda_wide.sharedItems) + if (b.wide_plans) w[at..][0..14].* = wide.sharedItems(@intCast(c.experts), @intCast(p.rows), rows) else w[at..][0..8].* = .{ @intCast(c.experts), 0, n, @intCast(c.experts + 1), @intCast(p.rows), n, 2, 2 }; } - try ops.upload(b.shared, std.mem.sliceAsBytes(&w)); + try ops.upload(b.shared, std.mem.sliceAsBytes(w)); try ops.s.synchronize(); } @@ -503,3 +524,21 @@ test "Bolt's shared slot holds a plan for every window row count" { try std.testing.expect(if (rows < W) end <= b.latentPlan(c, rows + 1).members else end <= sharedBytes(c)); } } + +test "wide rounds: with the switch off the shared plans are main's, in bytes and in where each row count's plan sits (REV83 2)" { + var c: Config = .{ .hidden = 8, .vocab = 16, .layers = 2, .mamba_heads = 2, .mamba_head_dim = 4, .groups = 1, .state = 4, .conv_kernel = 4, .heads = 2, .kv_heads = 1, .head_dim = 4, .experts = 4, .top_k = 2, .expert_width = 4, .shared_width = 8, .routed_scaling = 1, .eps = 1e-5 }; + // main: 16 rows of members a half, then 8 words a row count (items at 0, counts at 6) + try std.testing.expectEqual(@as(usize, (2 * 16 + 8 * 16) * 4), sharedBytes(c)); + var b: Buffers = undefined; + b.shared = 0x1000; + b.wide_plans = false; + for (1..17) |rows| { + const p = b.sharedPlan(rows); + try std.testing.expectEqual(@as(u64, 0x1000 + (2 * 16 + 8 * (rows - 1)) * 4), p.items); + try std.testing.expectEqual(p.items + 6 * 4, p.counts); + } + c.wide_rounds = true; + try std.testing.expectEqual(@as(usize, (2 * 32 + 14 * 32) * 4), sharedBytes(c)); + b.wide_plans = true; + try std.testing.expectEqual(@as(u64, 0x1000 + (2 * 32 + 14 * 16) * 4), b.sharedPlan(17).items); +} diff --git a/zig/src/families/nemotron/cuda_wide.zig b/zig/src/families/nemotron/cuda_wide.zig new file mode 100644 index 00000000000..9e0e29e393a --- /dev/null +++ b/zig/src/families/nemotron/cuda_wide.zig @@ -0,0 +1,166 @@ +//! TF_NEMOTRON_WIDE_ROUNDS: shared rounds of up to 16 streams and 32 rows where each row keeps its 16-row bits. +const std = @import("std"); +const Config = @import("config.zig").Config; + +/// Streams a shared round holds: today's 8, or 16 with the switch. +pub const narrow_streams = 8; +pub const wide_streams = 16; + +/// The switch; default off. The startup check refused every malformed value already, so a plain default stands here. +pub fn on() bool { + return @import("sys").environment.read(bool, "TF_NEMOTRON_WIDE_ROUNDS", false) catch false; +} + +/// Where a 17-32-row round keeps each row's bits: GB10, one rank, non-latent, not Bolt, no e4m3/bf16 experts, no slide. +pub fn allowed(c: Config, gb10: bool, slide: bool) bool { + return refusal(c, gb10, slide) == null; +} + +/// Why the switch leaves rounds at 8 streams here (null: it applies), for the line the engine logs when it is set. +pub fn refusal(c: Config, gb10: bool, slide: bool) ?[]const u8 { + if (!gb10) return "only GB10's affine-4 has the 32-row verify"; + if (c.latent > 0) return "a latent checkpoint keeps its own 32-row window"; + if (c.bolt or c.ck or c.salm) return "Bolt, e4m3 checkpoint rows and bf16 experts are not proved at 17-32 rows"; + if (c.world != 1) return "it runs on one rank only"; + if (slide) return "Sliding Weights route lessons to 8 streams a pass"; + return null; +} + +/// Lessons attached after init (saved ones, which load without --slide): rounds back to 8 streams, and why; else null. +pub fn withLessons(c: *Config) ?[]const u8 { + if (!c.wide_rounds) return null; + c.wide_rounds = false; // every buffer was sized for 16 streams: 8 use less of each + return "saved lessons route to 8 streams a pass"; +} + +/// Whether a shared window of `rows` rows fits (its streams' Mamba rows stay at windowRows each, the scan's stride). +pub fn windowFits(c: Config, rows: usize) bool { + return rows <= @import("cuda_state.zig").sharedRows(c); +} + +/// The shared check's rows for stream `k`: uneven splits, within the round's room and the stream's own window. +pub fn checkRows(round: usize, k: usize, room: usize, waiting: usize, window: usize, left: usize) usize { + const cap = @min(room - waiting, window); + return @min(1 + (round * 7 + k * 5 + round / 3) % cap, left); +} + +/// Whether Head.chains batches one more stream of `more` rows: the switch's streams (main's 8 off) and shared rows. +pub fn batches(c: Config, batched: usize, rows: usize, more: usize) bool { + return batched < streams(c) and rows + more <= @import("cuda_state.zig").sharedRows(c); +} + +/// A shared round's streams at most. +pub fn streams(c: Config) usize { + return if (c.wide_rounds) wide_streams else narrow_streams; +} + +/// The shared expert's 16-row items at `rows` (1-32), halves at members 0 and `half`; then (items, experts). +pub fn sharedItems(experts: u32, half: u32, rows: usize) [14]u32 { + var w: [14]u32 = @splat(0); + const lo: u32 = @intCast(@min(rows, 16)); + const hi: u32 = @intCast(rows - lo); + if (hi == 0) { + w[0..6].* = .{ experts, 0, lo, experts + 1, half, lo }; + w[12..14].* = .{ 2, 2 }; + } else { + w[0..12].* = .{ experts, 0, 16, experts, 16, hi, experts + 1, half, 16, experts + 1, half + 16, hi }; + w[12..14].* = .{ 4, 2 }; + } + return w; +} + +test "wide rounds: shared plan items keep 16-row tiles, today's two items at 16 rows or fewer" { + for (1..17) |rows| { + const w = sharedItems(40, 32, rows); + const n: u32 = @intCast(rows); + try std.testing.expectEqualSlices(u32, &.{ 40, 0, n, 41, 32, n }, w[0..6]); + try std.testing.expectEqualSlices(u32, &.{ 2, 2 }, w[12..14]); + } + for (17..33) |rows| { + const w = sharedItems(40, 32, rows); + const hi: u32 = @intCast(rows - 16); + try std.testing.expectEqualSlices(u32, &.{ 40, 0, 16, 40, 16, hi, 41, 32, 16, 41, 48, hi, 4, 2 }, &w); + } +} + +const small: Config = .{ .hidden = 8, .vocab = 16, .layers = 2, .mamba_heads = 2, .mamba_head_dim = 4, .groups = 1, .state = 4, .conv_kernel = 4, .heads = 2, .kv_heads = 1, .head_dim = 4, .experts = 4, .top_k = 2, .expert_width = 4, .shared_width = 8, .routed_scaling = 1, .eps = 1e-5 }; + +test "wide rounds: 16 streams only with the switch, and only where each row's kernels are proved" { + var c: Config = small; + try std.testing.expectEqual(@as(usize, 8), streams(c)); + c.wide_rounds = true; + try std.testing.expectEqual(@as(usize, 16), streams(c)); + c = small; + try std.testing.expect(allowed(c, true, false)); + try std.testing.expect(!allowed(c, false, false)); // off GB10 affine-4 has no 32-row verify + inline for (.{ "bolt", "ck", "salm" }) |f| { + var x: Config = small; + @field(x, f) = true; + try std.testing.expect(!allowed(x, true, false)); + } + var lat: Config = small; + lat.latent = 1024; + try std.testing.expect(!allowed(lat, true, false)); // Super keeps its own 32-row window + var tp: Config = small; + tp.world = 2; + try std.testing.expect(!allowed(tp, true, false)); + try std.testing.expect(!allowed(small, true, true)); // lessons reach 8 streams' rows a pass (REV60 2) +} + +test "wide rounds: the shared-widths check's rounds reach 17 to 32 rows with the switch, a stream's within 16 (REV60 5)" { + for ([_]bool{ false, true }) |switched| { + var c: Config = small; + c.wide_rounds = switched; + const room = @import("cuda_state.zig").sharedRows(c); + const window = @import("cuda_state.zig").windowRows(c); + for (2..streams(c) + 1) |n| { + var widest: usize = 0; + for (0..64) |round| { + var left = room; + var total: usize = 0; + for (0..n) |k| { + const rows = checkRows(round, k, left, n - 1 - k, window, 1000); + try std.testing.expect(rows >= 1 and rows <= window); + if (!switched) try std.testing.expectEqual(1 + (round * 7 + k * 5 + round / 3) % (left - (n - 1 - k)), rows); // as before + left -= rows; + total += rows; + } + try std.testing.expect(total <= room); + widest = @max(widest, total); + } + if (switched) try std.testing.expect(widest > window); // the check now sends the rounds the switch allows + } + } +} + +test "wide rounds: the switch set where it cannot apply says why, so it is never silently ignored (REV60 7)" { + try std.testing.expect(refusal(small, true, false) == null); + try std.testing.expect(refusal(small, false, false) != null); + try std.testing.expect(refusal(small, true, true) != null); + inline for (.{ "bolt", "ck", "salm" }) |f| { + var x: Config = small; + @field(x, f) = true; + try std.testing.expect(refusal(x, true, false) != null); + } + try std.testing.expect(std.mem.indexOf(u8, @embedFile("cuda_engine.zig"), "if (wide.on()) if (wide.refusal(") != null); +} + +test "wide rounds: saved lessons loaded after init put rounds back at 8 streams and say why (REV74 1)" { + var c: Config = small; + try std.testing.expect(withLessons(&c) == null); // the switch off: nothing to undo + c.wide_rounds = true; + try std.testing.expect(withLessons(&c) != null); + try std.testing.expect(!c.wide_rounds); + try std.testing.expectEqual(@as(usize, 8), streams(c)); + try std.testing.expect(std.mem.indexOf(u8, @embedFile("cuda_slide.zig"), "if (@import(\"cuda_wide.zig\").withLessons(&e.c)) |why|") != null); +} + +test "wide rounds: a draft call batches the switch's streams, main's 8 with it off (REV83 1)" { + var c: Config = small; + try std.testing.expect(batches(c, 7, 0, 1)); + try std.testing.expect(!batches(c, 8, 0, 1)); // the ninth drafts alone, as on main + try std.testing.expect(!batches(c, 0, 16, 1)); // and past the shared rows + c.wide_rounds = true; + try std.testing.expect(batches(c, 15, 0, 1) and !batches(c, 16, 0, 1)); + try std.testing.expect(std.mem.indexOf(u8, @embedFile("cuda_lanes.zig"), "!@import(\"cuda_wide.zig\").batches(self.e.c, batched, rows, follow.len)") != null); +} diff --git a/zig/src/families/nemotron/cuda_wide_walk_test.zig b/zig/src/families/nemotron/cuda_wide_walk_test.zig new file mode 100644 index 00000000000..c8b6365a7f1 --- /dev/null +++ b/zig/src/families/nemotron/cuda_wide_walk_test.zig @@ -0,0 +1,155 @@ +//! A 32-row Lightning shared round walked through every call's row limit: none refuses it (no WindowTooWide). +const std = @import("std"); +const cuda = @import("cuda"); +const config = @import("config.zig"); +const state = @import("cuda_state.zig"); +const wide = @import("cuda_wide.zig"); +const kern = @import("cuda_kernels.zig"); + +/// Lightning's config as the loader parses it (its quantization block, 4-bit in groups of 64), the switch on or off. +fn lightning(on: bool) !config.Config { + var why: config.Why = .{}; + var c = try config.parse(std.testing.allocator, config.lightning, &why); + try std.testing.expect(wide.allowed(c, true, false)); // GB10, one rank, non-latent, not Bolt: the switch applies + c.wide_rounds = on; + return c; +} + +test "wide round walk: Lightning's matrices are affine-4 64-groups, so every dense call takes the affine-4 path" { + const c = try lightning(true); + var buf: [96]u8 = undefined; + try std.testing.expect(c.other(&buf) == null); // no matrix at another width or group (fourOnly passes on CUDA) + try std.testing.expectEqual(@as(usize, 4), c.bits); + try std.testing.expectEqual(@as(usize, 64), c.group_size); + try std.testing.expectEqual(config.Format.mlx, c.format); +} + +test "wide round walk: a 32-row shared round passes every row limit on the way, 16 rows a stream" { + const c = try lightning(true); + const rows = state.sharedRows(c); + try std.testing.expectEqual(@as(usize, 32), rows); + // the forward's window (cuda_forward.zig windowRows): the round's rows; D1050 served RED here + try std.testing.expect(wide.windowFits(c, rows)); + try std.testing.expect(!wide.windowFits(c, rows + 1)); + // each stream's Mamba conv and scan rows (glue's rmax, the per-sequence stride): its own window, 16 rows + try std.testing.expectEqual(@as(usize, 16), state.windowRows(c)); + // the dense calls (in_proj, out_proj, qkv, o, the head): affine-4 rows past 16 take verify (verifyRows, PDL) + var a4: cuda.qlinear.Affine4Kernels = undefined; + a4.pdl = true; + a4.wide_verify = false; + try std.testing.expect(rows <= a4.verifyRows()); + try std.testing.expect(rows > cuda.qlinear.Affine4Kernels.max_rows); // and the swap is what those rows take + // the routed plan stages the round's rows, the shared expert's plan holds them in 16-row items + try std.testing.expect(rows <= kern.plan_rows); + for (1..rows + 1) |r| { + const w = wide.sharedItems(@intCast(c.experts), 32, r); + var held: usize = 0; + for (0..w[12]) |i| held += w[3 * i + 2]; + try std.testing.expectEqual(2 * r, held); // both halves' rows, every one in an item + for (0..w[12]) |i| try std.testing.expect(w[3 * i + 2] <= 16); + } + // the copies of a batched draft or shared draw: a part a stream + try std.testing.expect(wide.streams(c) <= wide.wide_streams); +} + +test "wide round walk: with the switch off every limit stays at today's 16 rows and 8 streams" { + const c = try lightning(false); + try std.testing.expectEqual(@as(usize, 16), state.sharedRows(c)); + try std.testing.expect(wide.windowFits(c, 16)); + try std.testing.expect(!wide.windowFits(c, 17)); // as the forward refused before + try std.testing.expectEqual(@as(usize, 8), wide.streams(c)); +} + +test "wide round walk: a stream past its own window's rows is refused, however wide the round (REV60 3)" { + const c = try lightning(true); + const rows = state.windowRows(c); + var e: @import("cuda_engine.zig").Engine = undefined; + e.c = c; + var seq: state.Seq = undefined; + const ids = [_]u32{1}; + try std.testing.expectError(error.BadWindow, e.verifyShared(&.{.{ .seq = &seq, .ids = &ids, .rows = rows + 1 }})); + var h: @import("cuda_mtp.zig").Head = undefined; + h.e = &e; + var parts = [_]@import("cuda_mtp.zig").Part{.{ .k_cache = 0, .v_cache = 0, .probs = 0, .ids = 0, .hidden = 0, .sampled = 0, .rule = null, .pos = 0, .keep = rows + 1, .depth = 1 }}; + try std.testing.expectError(error.BadDraftRequest, h.chains(&parts)); + const glue = @import("cuda_glue.zig"); + const g: glue.Glue = .{ .set = null, .f = undefined, .s = undefined, .emb = undefined, .norms = undefined, .moe = undefined }; + const shape: glue.Shape = .{ .proj = 1, .xd = 1, .cd = 1, .heads = 1, .dh = 32, .groups = 1, .state = 128, .rmax = rows }; + const seg: glue.MambaSeg = .{ .proj = 0, .base = 0, .raw = 0, .xc = 0, .dt = 0, .state = 0, .meta = 0, .y = 0, .rows = 1 }; + var past = seg; + past.rows = rows + 1; + try std.testing.expectError(error.ScanShape, g.mambaSegs(&.{ seg, past }, 0, 0, 0, 0, 0, 0, 0, shape)); // the batched conv + try std.testing.expectError(error.ScanShape, g.mambaSegs(&.{past}, 0, 0, 0, 0, 0, 0, 0, shape)); // a stream alone +} + +test "wide round walk: with the switch the lanes learn what a row past 16 costs, not a wider fixed overhead (REV60 4)" { + for ([_]bool{ false, true }) |on| { + var e: @import("cuda_engine.zig").Engine = undefined; + e.c = try lightning(on); + var b: @import("cuda_lanes.zig").Cuda = undefined; + b.e = &e; + b.head = null; + b.copy_drafts = false; + b.cost_count = 0; + b.mtp_ms = 0; + b.mtp_drafts = null; + b.mtp_confidence = null; + const f = b.facts(); + // 17-32 rows are priced from the measured 16 linearly: depth.zig's row cost learns what they take here + try std.testing.expectEqual(on, f.learn_row_costs); + try std.testing.expectEqual(@as(u32, if (on) 32 else 16), f.batch_rows); + } +} + +test "wide round walk: a round past 8 streams with lessons attached is refused, not served without them (REV74 1)" { + const weights = @import("cuda_weights.zig"); + const fwd = @import("cuda_forward.zig"); + var blk: weights.Block = .{ .kind = .attention, .norm = 0 }; + blk.attn.adapter = @as(weights.Adapter, undefined); + var w: weights.Weights = undefined; + w.blocks = (&blk)[0..1]; + var f: fwd.Forward = undefined; + f.w = &w; + var segs: [9]fwd.Seg = undefined; + try std.testing.expectError(error.LessonsPastRoute, f.windowSegs(&segs)); +} + +test "wide round walk: with the switch off a direct draft call past 8 streams is refused, and conv checks its rows (REV74 4)" { + const c = try lightning(false); + var e: @import("cuda_engine.zig").Engine = undefined; + e.c = c; + var h: @import("cuda_mtp.zig").Head = undefined; + h.e = &e; + const part: @import("cuda_mtp.zig").Part = .{ .k_cache = 0, .v_cache = 0, .probs = 0, .ids = 0, .hidden = 0, .sampled = 0, .rule = null, .pos = 0, .keep = 1, .depth = 1 }; + var parts: [9]@import("cuda_mtp.zig").Part = @splat(part); + try std.testing.expectError(error.BadDraftRequest, h.chains(&parts)); + const glue = @import("cuda_glue.zig"); + const g: glue.Glue = .{ .set = null, .f = undefined, .s = undefined, .emb = undefined, .norms = undefined, .moe = undefined }; + const shape: glue.Shape = .{ .proj = 1, .xd = 1, .cd = 1, .heads = 1, .dh = 32, .groups = 1, .state = 128, .rmax = 16 }; + try std.testing.expectError(error.ScanShape, g.conv(0, 0, 0, 0, 0, 0, 0, 17, shape)); +} + +test "wide round walk: with the switch off every host buffer is sized for main's 8 streams (REV83 2)" { + const off = try lightning(false); + const on = try lightning(true); + const engine = @import("cuda_engine.zig"); + // the engine's pinned words: a shared window's streams before the draw, main's 8 off + try std.testing.expectEqual(engine.pinDraw(on) - 8 * engine.pin_prompt, engine.pinDraw(off)); + // the lanes' mapped logprob rows: main's 8 streams of 32 rows, then the first token's + try std.testing.expectEqual(@as(usize, 8 * state.max_rows + 1), @import("cuda_lanes.zig").rowSlots(off)); + // the head's pinned words and device buffers: sized by the switch's streams + const mtp = @import("cuda_mtp.zig"); + try std.testing.expectEqual(mtp.hostWords(16) - 8 * (1 + state.max_rows + 8 + 1), mtp.hostWords(wide.streams(off))); + try std.testing.expect(std.mem.indexOf(u8, @embedFile("cuda_mtp.zig"), "const S: usize = @import(\"cuda_wide.zig\").streams(c);") != null); +} + +test "wide round walk: with the switch off the 17-32-row kernel paths refuse as main did (REV83 2)" { + const src = @embedFile("cuda_kernels.zig"); + // the dense call routes past 16 rows only with the switch (shared qlinear.decode is main's) + try std.testing.expect(std.mem.indexOf(u8, src, "if (o.k.wide and q == .affine4 and rows > cuda.qlinear.Affine4Kernels.max_rows) return o.k.affine.verify(") != null); + // the routed plan admits 32 rows only with it, main's 16 without + try std.testing.expect(std.mem.indexOf(u8, src, "if (rows > @as(usize, if (o.k.wide) plan_rows else 16) or slots > 8 or count > 128) return error.PlanTooWide;") != null); + // the kernels' flag is the switch's, set before any buffer, and false until then + try std.testing.expect(std.mem.indexOf(u8, src, "var k: Kernels = undefined;\n k.wide = false;") != null); + try std.testing.expect(std.mem.indexOf(u8, @embedFile("cuda_engine.zig"), "e.k.wide = e.c.wide_rounds;") != null); +} diff --git a/zig/src/families/nemotron/cuda_worker.zig b/zig/src/families/nemotron/cuda_worker.zig index 20d590a9617..c6407956d4c 100644 --- a/zig/src/families/nemotron/cuda_worker.zig +++ b/zig/src/families/nemotron/cuda_worker.zig @@ -339,10 +339,10 @@ fn loadLayers(gpa: std.mem.Allocator, io: std.Io, ops: kern.Ops, dir: []const u8 } /// Rank r > 0: its expert shares of every MoE layer, computed for rank 0's jobs until rank 0 ends. -pub fn serve(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: []const u8, precision: ?@import("config.zig").Precision) !void { +pub fn serve(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: []const u8, precision: ?@import("config.zig").Precision, placed: ?latent.At) !void { const t0 = std.Io.Clock.awake.now(io); var c = try Config.read(gpa, io, dir); - try latent.place(&c); + if (placed) |x| try latent.placeAt(&c, x) else try latent.place(&c); // the server's launch, or a tool's variables var load_cache = core.checkpoint.cache.Load.begin(io, c.world > 1); defer load_cache.deinit(); if (c.rank == 0 or c.latent == 0) return error.NotAnExpertRank; diff --git a/zig/src/families/nemotron/timing.zig b/zig/src/families/nemotron/timing.zig index 9d42fa44ed0..7d6885a57e7 100644 --- a/zig/src/families/nemotron/timing.zig +++ b/zig/src/families/nemotron/timing.zig @@ -5,6 +5,7 @@ const lanes = @import("lanes"); const fwd = @import("forward.zig"); const st = @import("state.zig"); const backend = @import("backend.zig"); +const warm = lanes.cost_rule.warm_prices; pub const Kind = enum(u2) { prefill, step, verify, draft }; @@ -69,6 +70,28 @@ fn median(v: []f64) f64 { return if (v.len % 2 == 1) v[v.len / 2] else (v[v.len / 2 - 1] + v[v.len / 2]) / 2; } +const WarmCandidate = struct { + shared: bool, + count: usize, + values: [32]f64 = undefined, + widths: [32]u32 = undefined, +}; + +fn selectWarm(costs: *const Costs, cursor: *[3]u64) ?WarmCandidate { + const turn: warm.Turn = .{ .value = cursor[2] }; + cursor[2] = turn.next(); + for (turn.order()) |shared| { + const entries = if (shared) costs.shared[0..costs.shareds] else costs.window[0..costs.windows]; + var candidate: WarmCandidate = .{ .shared = shared, .count = entries.len }; + for (entries, 0..) |entry, i| { + candidate.values[i] = entry.ms; + candidate.widths[i] = entry.width; + } + if (warm.admit(candidate.values[0..entries.len], candidate.widths[0..entries.len], &cursor[@intFromBool(shared)])) return candidate; + } + return null; +} + /// GPU-timed fastest runs after a warm-up: windows of 1-33 rows, shared 2-row rounds, a head step; kept per build. pub fn measure(b: *backend.Metal, io: std.Io) !void { const c = b.m.config; @@ -79,13 +102,57 @@ pub fn measure(b: *backend.Metal, io: std.Io) !void { const keyed = if (tag == 0) base else shape[0 .. base.len + (try std.fmt.bufPrint(shape[base.len..], "/w{x:0>16}", .{tag})).len]; const parts = [_][]const u8{ "nemotron-metal", std.mem.span(b.m.device.name()), keyed }; const k = lanes.cost_cache.key(b.gpa, io, &parts) catch null; - if (k) |key| if (lanes.cost_cache.load(Costs, b.gpa, io, key)) |kept| { - b.costs = kept; - b.timing = .{}; + const most = @min(b.o.batch_rows / 2, 64); + var kept = if (k) |key| lanes.cost_cache.load(Costs, b.gpa, io, key) else null; + if (kept) |table| { + if (table.windows != wide.len + backend.max_window or table.shareds != sharedCount(most)) kept = null else { + for (table.window[0..table.windows], 0..) |c2, i| { + if (c2.width != widthOf(i) or !(c2.ms > 0) or !std.math.isFinite(c2.ms)) { + kept = null; + break; + } + } + for (table.shared[0..table.shareds], 0..) |c2, i| { + if (c2.width != 2 * streamsOf(i) or !(c2.ms > 0) or !std.math.isFinite(c2.ms)) { + kept = null; + break; + } + } + } + } + const last = lanes.cost_cache.referenceKey(&(parts ++ [_][]const u8{"costs"})); + if (kept) |table| { + var costs = table; + if (most == 0) { + b.costs = costs; + b.timing = .{}; + return; + } + const cursor_key = lanes.cost_cache.buildKey(&(k orelse unreachable), &.{"metal-heal-v2"}); + var cursor = lanes.cost_cache.load([3]u64, b.gpa, io, cursor_key) orelse [3]u64{ 0, 0, 0 }; + defer lanes.cost_cache.save([3]u64, b.gpa, io, cursor_key, cursor); + defer b.timing = .{}; + b.costs = table; + var candidate = selectWarm(&costs, &cursor) orelse return; + const values = candidate.values[0..candidate.count]; + const widths = candidate.widths[0..candidate.count]; + var caches: [64]st.Cache = undefined; + var n: usize = 0; + defer for (caches[0..n]) |*x| x.deinit(&b.pool); + var timer: WarmTimer = .{ .b = b, .caches = &caches, .n = &n, .shared = candidate.shared }; + const stats = warm.prepared(&timer, values, widths, &cursor[@intFromBool(candidate.shared)], 0, warm.Local{}, true) catch return; + if (stats.lowered > 0) { + const entries = if (candidate.shared) costs.shared[0..candidate.count] else costs.window[0..candidate.count]; + for (entries, values) |*entry, value| entry.ms = value; + b.costs = costs; + lanes.cost_cache.save(Costs, b.gpa, io, k.?, costs); + lanes.cost_cache.save(Costs, b.gpa, io, last, costs); + } return; - }; + } + if (most == 0) return error.NoTimingStreams; var caches: [64]st.Cache = undefined; - const n = @min(b.o.batch_rows / 2, caches.len); + const n = most; try makeEach(st.Cache, caches[0..n], CacheMaker{ .b = b }); defer for (caches[0..n]) |*x| x.deinit(&b.pool); // the GPU's clocks ramp up under load: time nothing until it has run for a while @@ -97,16 +164,17 @@ pub fn measure(b: *backend.Metal, io: std.Io) !void { var head = [1]f64{0}; const head_ms: ?*f64 = if (b.head != null) &head[0] else null; const ref = lanes.cost_cache.referenceKey(&parts); - const last = lanes.cost_cache.referenceKey(&(parts ++ [_][]const u8{"costs"})); // the last build's table for this chip and shape stands while a probe of each kernel path stays within drift - if (lanes.cost_cache.load(Costs, b.gpa, io, last)) |kept| if (try holds(windows, heads, shared, kept, b.head != null, sharedCount(n))) { - b.costs = kept; + if (lanes.cost_cache.load(Costs, b.gpa, io, last)) |last_costs| if (try holds(windows, heads, shared, last_costs, b.head != null, sharedCount(n))) { + b.costs = last_costs; b.timing = .{}; - if (k) |key| lanes.cost_cache.save(Costs, b.gpa, io, key, kept); + if (k) |key| lanes.cost_cache.save(Costs, b.gpa, io, key, last_costs); return; }; try lanes.cost_rule.measure(windows, heads, &ms, head_ms, false); - try lanes.cost_rule.smooth(windows, &ms); + var window_widths: [wide.len + backend.max_window]u32 = undefined; + for (&window_widths, 0..) |*w, i| w.* = @intCast(widthOf(i)); + try lanes.cost_rule.smoothWidths(windows, &ms, &window_widths); if (lanes.cost_cache.load(Reference, b.gpa, io, ref)) |r| { if (lanes.cost_rule.drifted(&ms, &r.window) or (b.head != null and lanes.cost_rule.drifted(&head, &r.head))) { try lanes.cost_rule.measure(windows, heads, &ms, head_ms, true); @@ -115,7 +183,12 @@ pub fn measure(b: *backend.Metal, io: std.Io) !void { var costs = Costs{ .windows = ms.len, .head_ms = head[0] }; for (ms, 0..) |m, i| costs.window[i] = .{ .width = @intCast(widthOf(i)), .ms = m }; costs.shareds = sharedCount(n); - for (costs.shared[0..costs.shareds], 0..) |*s, i| s.* = .{ .width = @intCast(2 * streamsOf(i)), .ms = try lanes.cost_rule.fastest(shared, i) }; + var shared_ms: [8]f64 = undefined; + try lanes.cost_rule.measureWindows(shared, shared_ms[0..costs.shareds], false); + var shared_widths: [8]u32 = undefined; + for (shared_widths[0..costs.shareds], 0..) |*w, i| w.* = @intCast(2 * streamsOf(i)); + try lanes.cost_rule.smoothWidths(shared, shared_ms[0..costs.shareds], shared_widths[0..costs.shareds]); + for (costs.shared[0..costs.shareds], shared_ms[0..costs.shareds], 0..) |*s2, m, i| s2.* = .{ .width = @intCast(2 * streamsOf(i)), .ms = m }; b.costs = costs; b.timing = .{}; if (k) |key| lanes.cost_cache.save(Costs, b.gpa, io, key, costs); @@ -258,6 +331,29 @@ const WindowTimer = struct { } }; +const WarmTimer = struct { + b: *backend.Metal, + caches: *[64]st.Cache, + n: *usize, + shared: bool, + began: f64 = 0, + pub fn start(t: *WarmTimer) void { + t.began = mtl.clock.seconds(); + } + pub fn elapsedMs(t: *WarmTimer) f64 { + return (mtl.clock.seconds() - t.began) * 1e3; + } + pub fn prepare(t: *WarmTimer, plan: lanes.cost_rule.warm_prices.Plan, widths: []const u32) !void { + const needed = if (t.shared) plan.widest(widths) / 2 else 1; + try makeEach(st.Cache, t.caches[0..needed], CacheMaker{ .b = t.b }); + t.n.* = needed; + } + pub fn time(t: *WarmTimer, i: usize) !f64 { + if (t.shared) return (SharedTimer{ .b = t.b, .caches = t.caches[0..t.n.*] }).time(i); + return (WindowTimer{ .b = t.b, .caches = t.caches[0..t.n.*] }).time(i); + } +}; + /// Shared entry `i`: one round of `streamsOf(i)` streams, a 2-row window each. const SharedTimer = struct { b: *backend.Metal, @@ -370,3 +466,26 @@ pub fn profile(b: *backend.Metal, cache: *st.Cache, steps: usize) !void { std.debug.print("the head's one-row step:\n", .{}); hp.report(steps); } + +test "nemotron timing: a shared table at the budget never blocks the lone table" { + const Fake = struct { + pub fn time(_: @This(), _: usize) !f64 { + return 50; + } + }; + var costs: Costs = .{ .windows = 2, .shareds = 2 }; + costs.window[0..2].* = .{ .{ .width = 1, .ms = 50 }, .{ .width = 33, .ms = 60 } }; + costs.shared[0..2].* = .{ .{ .width = 4, .ms = 50 }, .{ .width = 128, .ms = 200 } }; + var cursor: [3]u64 = @splat(0); + for (1..7) |load| { + const selected = selectWarm(&costs, &cursor); + try std.testing.expect(selected != null); + var candidate = selected.?; + try std.testing.expect(!candidate.shared); + const stats = try warm.local(Fake{}, candidate.values[0..2], candidate.widths[0..2], &cursor[0]); + try std.testing.expect(stats.reads > 0); + try std.testing.expectEqual(@as(u64, load), cursor[0]); + try std.testing.expectEqual(@as(u64, load), cursor[2]); + } + try std.testing.expectEqual(@as(u64, 0), cursor[1]); +} diff --git a/zig/src/families/qwen27/attention_plan.zig b/zig/src/families/qwen27/attention_plan.zig index 870c888d159..a7f1b39451e 100644 --- a/zig/src/families/qwen27/attention_plan.zig +++ b/zig/src/families/qwen27/attention_plan.zig @@ -48,9 +48,9 @@ pub const Geometry = struct { } pub fn check(g: Geometry) !void { - // The GQA group is a shader constant: 6 (24/4, 12/2 on a rank), or on one Mac 16 (32/2) or the 9B's 4 (16/4). + // The GQA group is a shader constant: 6 (24/4, 12/2 on a rank), or on one Mac 16 (32/2), 4 (16/4) or 8 (16/2). if (g.dim != 256 or g.rotary != 64 or g.heads == 0 or g.kv_heads == 0 or g.heads % g.kv_heads != 0) return error.TargetAttentionShape; - const one_mac = (g.heads == 32 and g.kv_heads == 2) or (g.heads == 16 and g.kv_heads == 4); + const one_mac = (g.heads == 32 and g.kv_heads == 2) or (g.heads == 16 and g.kv_heads == 4) or (g.heads == 16 and g.kv_heads == 2); if (g.heads / g.kv_heads != 6 and !one_mac) return error.TargetAttentionShape; } pub fn promptRows(g: Geometry, requested: u32) u32 { @@ -553,6 +553,11 @@ test "target attention reads every config dimension without widening kernel qual c.heads = 16; // its rank of a two-way split is not qualified c.kv_heads = 1; try std.testing.expectError(error.TargetAttentionShape, Geometry.fromConfig(c, true)); + c.kv_heads = 2; // Qwen3.6-35B-A3B: GQA8, one Mac only + try std.testing.expectEqual(@as(u32, 8), (try Geometry.fromConfig(c, true)).group()); + c.heads = 8; // its rank of a two-way split is not qualified + c.kv_heads = 1; + try std.testing.expectError(error.TargetAttentionShape, Geometry.fromConfig(c, true)); c.heads = 24; c.kv_heads = 2; try std.testing.expectError(error.TargetAttentionShape, Geometry.fromConfig(c, true)); diff --git a/zig/src/families/qwen27/config.zig b/zig/src/families/qwen27/config.zig index 4c7dc1a9f6c..1e0812d0d59 100644 --- a/zig/src/families/qwen27/config.zig +++ b/zig/src/families/qwen27/config.zig @@ -11,7 +11,7 @@ pub const max_layers = 128; pub const max_eos = 8; pub const Problem = fields.Problem; comptime { - std.debug.assert(eos_ids.qwen27_metal.max.? == max_eos); + std.debug.assert(eos_ids.qwen35.max.? == max_eos); } pub const Config = struct { @@ -46,6 +46,8 @@ pub const Config = struct { moe_intermediate: usize = 0, /// Whether a row's top-k softmax weights are renormalized to sum to one (`norm_topk_prob`). renorm: bool = false, + /// The head is the embedding (`tie_word_embeddings`), admitted only by `parseTied` with its switch on. + tied_head: bool = false, pub fn moe(c: Config) bool { return c.experts != 0; @@ -261,6 +263,11 @@ pub fn parse(gpa: std.mem.Allocator, json: []const u8, generation: ?[]const u8) /// `parse`, with `p` naming the field behind a BadConfig the field layer refused. pub fn parseWhy(gpa: std.mem.Allocator, json: []const u8, generation: ?[]const u8, p: *Problem) !Config { + return parseTied(gpa, json, generation, p, false); +} + +/// `parseWhy`, admitting a dense tied head when `allow_tied`; a routed tied head stays refused. +pub fn parseTied(gpa: std.mem.Allocator, json: []const u8, generation: ?[]const u8, p: *Problem, allow_tied: bool) !Config { const parsed = try std.json.parseFromSlice(std.json.Value, gpa, json, .{}); defer parsed.deinit(); const root = try object(parsed.value); @@ -274,7 +281,8 @@ pub fn parseWhy(gpa: std.mem.Allocator, json: []const u8, generation: ?[]const u } else return error.NotQwenDense; const experts = if (t.get("num_experts")) |v| try integer(v, true, tower.at("num_experts"), p) else 0; if (routed != (experts != 0)) return error.NotQwenDense; - if (try rules.tied(root, t, .metal27)) return error.TiedEmbeddingHead; + const tied_head = try rules.tied(root, t, .metal27); + if (tied_head and (!allow_tied or routed)) return error.TiedEmbeddingHead; try rules.check(t, .metal27); const heads = try required(tower, "num_attention_heads"); const hidden = try required(tower, "hidden_size"); @@ -301,6 +309,7 @@ pub fn parseWhy(gpa: std.mem.Allocator, json: []const u8, generation: ?[]const u .dk = try required(tower, "linear_key_head_dim"), .dv = try required(tower, "linear_value_head_dim"), .conv_kernel = try required(tower, "linear_conv_kernel_dim"), + .tied_head = tied_head, .eps = @floatCast(try optional(tower, "rms_norm_eps", 1e-6)), .rope_dims = @intFromFloat(@as(f64, @floatFromInt(head_dim)) * factor), .rope_theta = if (rp) |r| try optional(r, "rope_theta", try optional(tower, "rope_theta", 10000000)) else try optional(tower, "rope_theta", 10000000), @@ -331,7 +340,7 @@ pub fn parseWhy(gpa: std.mem.Allocator, json: []const u8, generation: ?[]const u const gen = if (generation) |text| try std.json.parseFromSlice(std.json.Value, gpa, text, .{}) else null; defer if (gen) |g| g.deinit(); const gen_doc: std.json.Value = if (gen) |g| .{ .object = try object(g.value) } else .null; - const ids = eos_ids.collect(&c.eos, eos_ids.qwen27_metal, parsed.value, .{ .object = t }, gen_doc, c.vocab) catch |e| return switch (e) { + const ids = eos_ids.collect(&c.eos, eos_ids.qwen35, parsed.value, .{ .object = t }, gen_doc, c.vocab) catch |e| return switch (e) { error.BadEosValue => error.BadConfig, else => e, }; diff --git a/zig/src/families/qwen27/config_test.zig b/zig/src/families/qwen27/config_test.zig index 665cf026275..f8560d7e1bb 100644 --- a/zig/src/families/qwen27/config_test.zig +++ b/zig/src/families/qwen27/config_test.zig @@ -7,6 +7,7 @@ const Span = cfg.Span; const Mode = cfg.Mode; const split = cfg.split; const object = cfg.object; +const eos_ids = @import("checkpoint_eos"); const fixture = \\{"model_type":"qwen3_5","hidden_size":64,"intermediate_size":128,"num_hidden_layers":4, @@ -101,13 +102,7 @@ test "a scaled rope (rope_type or type yarn, a rope_scaling block) is refused; a test "a routed config reads its experts, the shared expert's width as the layer's and the routing flag" { const a = std.testing.allocator; - const json = - \\{"model_type":"qwen3_5_moe","text_config":{"model_type":"qwen3_5_moe_text","hidden_size":3072,"intermediate_size":1024, - \\"moe_intermediate_size":1024,"shared_expert_intermediate_size":1024,"num_experts":256,"num_experts_per_tok":8, - \\"num_hidden_layers":48,"num_attention_heads":32,"num_key_value_heads":2,"head_dim":256,"vocab_size":248320, - \\"linear_num_key_heads":16,"linear_num_value_heads":64,"linear_key_head_dim":128,"linear_value_head_dim":128, - \\"linear_conv_kernel_dim":4,"partial_rotary_factor":0.25,"eos_token_id":248044}} - ; + const json = hf_fixture; const c = try parse(a, json, null); try std.testing.expect(c.moe()); try std.testing.expectEqual(@as(usize, 256), c.experts); @@ -123,6 +118,56 @@ test "a routed config reads its experts, the shared expert's width as the layer' try std.testing.expectError(error.NotQwenDense, parse(a, dense_typed, null)); } +/// An HF-layout checkpoint: its ids sit in text_config and its vocabulary is the real 27B's. +const hf_fixture = + \\{"model_type":"qwen3_5_moe","text_config":{"model_type":"qwen3_5_moe_text","hidden_size":3072,"intermediate_size":1024, + \\"moe_intermediate_size":1024,"shared_expert_intermediate_size":1024,"num_experts":256,"num_experts_per_tok":8, + \\"num_hidden_layers":48,"num_attention_heads":32,"num_key_value_heads":2,"head_dim":256,"vocab_size":248320, + \\"linear_num_key_heads":16,"linear_num_value_heads":64,"linear_key_head_dim":128,"linear_value_head_dim":128, + \\"linear_conv_kernel_dim":4,"partial_rotary_factor":0.25,"eos_token_id":248044}} +; + +test "qwen27: generation_config.json adds <|im_end|> to an HF-layout config's end ids" { + const a = std.testing.allocator; + const generation = "{\"eos_token_id\":[248046,248044]}"; + const merged = try parse(a, hf_fixture, generation); + // the tower's own id first, then generation_config.json's new one, each kept once + try std.testing.expectEqualSlices(u32, &.{ 248044, 248046 }, merged.eos[0..merged.eos_count]); + // main's behaviour: without the file text_config's id stands alone, which is why the loader passes it + const alone = try parse(a, hf_fixture, null); + try std.testing.expectEqualSlices(u32, &.{248044}, alone.eos[0..alone.eos_count]); + // core's shared reader gives the same ids for the same two documents + const model = try std.json.parseFromSlice(std.json.Value, a, hf_fixture, .{}); + defer model.deinit(); + const gen = try std.json.parseFromSlice(std.json.Value, a, generation, .{}); + defer gen.deinit(); + const shared = try eos_ids.resolve(a, model.value, gen.value, 248320); + defer a.free(shared); + try std.testing.expectEqualSlices(u32, &.{ 248044, 248046 }, shared); +} + +/// mlx-community/Qwen3.6-35B-A3B-4bit's text_config (its MTP and vision fields left out): no intermediate_size. +pub const a3b_json = + \\{"model_type":"qwen3_5_moe","text_config":{"model_type":"qwen3_5_moe_text","hidden_size":2048, + \\"moe_intermediate_size":512,"shared_expert_intermediate_size":512,"num_experts":256,"num_experts_per_tok":8, + \\"num_hidden_layers":40,"num_attention_heads":16,"num_key_value_heads":2,"head_dim":256,"vocab_size":248320, + \\"linear_num_key_heads":16,"linear_num_value_heads":32,"linear_key_head_dim":128,"linear_value_head_dim":128, + \\"linear_conv_kernel_dim":4,"partial_rotary_factor":0.25,"attn_output_gate":true,"eos_token_id":248044}} +; + +test "Qwen3.6-35B-A3B's config reads as routed experts of 512 over 2,048, the shared expert's width as the layer's" { + const c = try parse(std.testing.allocator, a3b_json, null); + try std.testing.expect(c.moe()); + try std.testing.expectEqual(@as(usize, 2048), c.hidden); + try std.testing.expectEqual(@as(usize, 512), c.intermediate); + try std.testing.expectEqual(@as(usize, 512), c.moe_intermediate); + try std.testing.expectEqual(@as(usize, 8), c.top_k); + try std.testing.expectEqual(@as(usize, 32), c.v_heads); + try std.testing.expect(c.renorm); // absent: renormalized + try std.testing.expectEqual(Kind.attention, c.kind(39)); + try std.testing.expectEqual(Kind.linear, c.kind(38)); +} + test "a routed config refuses a rank split" { var c = model27(); c.experts = 256; @@ -142,6 +187,18 @@ test "dense config refuses MoE and tied embedding heads" { try std.testing.expectError(error.TiedEmbeddingHead, parse(a, tied, null)); } +test "a tied head parses only with its switch, dense, and marks the config" { + const a = std.testing.allocator; + const tied = try edit(a, "tie_word_embeddings", .{ .bool = true }); + defer a.free(tied); + var p: cfg.Problem = .{}; + try std.testing.expectError(error.TiedEmbeddingHead, cfg.parseTied(a, tied, null, &p, false)); + try std.testing.expect((try cfg.parseTied(a, tied, null, &p, true)).tied_head); + const untied = try edit(a, "tie_word_embeddings", .{ .bool = false }); + defer a.free(untied); + try std.testing.expect(!(try cfg.parseTied(a, untied, null, &p, true)).tied_head); +} + test "invalid scalar shapes and types fail without a cast trap" { const a = std.testing.allocator; for ([_]std.json.Value{ .{ .integer = -1 }, .{ .integer = 0 }, .{ .bool = true }, .{ .integer = 4294967296 } }) |v| { diff --git a/zig/src/families/qwen27/decode_round.zig b/zig/src/families/qwen27/decode_round.zig index 482f985d076..741bd733429 100644 --- a/zig/src/families/qwen27/decode_round.zig +++ b/zig/src/families/qwen27/decode_round.zig @@ -24,6 +24,13 @@ pub const pagesOn = kv_pages.on; pub const KvPages = kv_pages.KvPages; pub const KvSpan = kv_pages.KvSpan; const kvp = kv_pages.kvp; +const kv_grow = @import("kv_grow.zig"); +const kv_slots = @import("kv_slots.zig"); + +/// The host's hook for buffers a slot's K/V growth made. +pub const Grown = struct { ctx: *anyopaque, added: *const fn (ctx: *anyopaque, buffers: []const mtl.Buffer) void }; + +const stage_planes = @import("stage_planes.zig"); /// Whether `cb` failed on the GPU; its Metal error (out of memory, a timeout) is logged with `what` it ran. pub fn gpuFailed(cb: mtl.CommandBuffer, what: []const u8) bool { const msg = cb.failure() orelse return false; @@ -51,6 +58,10 @@ pub const Runner = struct { ready: u32, // slots [0, ready) have their K/V rows; a later slot takes its own when first used (ensure) capacity: u32, kv: ?KvPages = null, + /// TF_Q27_KV_GROW: slots hold the rows their streams reached, grown by this step; null: the whole context. + kv_step: ?u32 = null, + /// A grown slot's new buffers, for the host's residency set (committed now, as a new slot's are). + grown: ?Grown = null, active: ?[32]u8 = null, failed: bool = false, capture_taps: bool = false, @@ -84,15 +95,19 @@ pub const Runner = struct { /// A runner of `slots` whose first `ready` take their K/V rows now, the rest when first used (ensure). pub fn initReady(a: std.mem.Allocator, m: *Model, slots: u32, capacity: u32, ready: u32) !Runner { - return build(a, m, slots, capacity, ready, false); + return build(a, m, slots, capacity, ready, false, null); } /// A runner whose slots all take their K/V rows from one arena of core-pool pages, each promised `capacity` rows. pub fn initPaged(a: std.mem.Allocator, m: *Model, slots: u32, capacity: u32) !Runner { - return build(a, m, slots, capacity, slots, true); + return build(a, m, slots, capacity, slots, true, null); + } + + pub fn initGrow(a: std.mem.Allocator, m: *Model, slots: u32, capacity: u32, ready: u32, kv_step: ?u32) !Runner { + return build(a, m, slots, capacity, ready, false, kv_step); } - fn build(a: std.mem.Allocator, m: *Model, slots: u32, capacity: u32, ready: u32, paged: bool) !Runner { + fn build(a: std.mem.Allocator, m: *Model, slots: u32, capacity: u32, ready: u32, paged: bool, kv_step: ?u32) !Runner { if (slots == 0 or slots > attn.planning.max_streams or capacity == 0 or m.frame.capacity % 16 != 0 or ready == 0 or ready > slots) return error.BadRoundCapacity; const geometry = try attn.planning.Geometry.fromConfig(m.config, try @import("simd_attention.zig").sharedPrefix(m.device.tensorUnits())); const linear_index = try a.alloc(u32, m.config.layers); @@ -163,14 +178,15 @@ pub const Runner = struct { } const kv: ?KvPages = if (paged) try kv_pages.caches(a, m, na, slots, capacity, caches) else null; errdefer if (kv) |k| kv_pages.free(k); + const first = if (kv_step) |s| kv_grow.first(s, capacity) else capacity; if (!paged) for (0..na) |layer| for (0..ready) |slot| { - caches[layer * slots + slot] = try slotCache(a, m, &owned, capacity); + caches[layer * slots + slot] = try kv_slots.slotCache(a, m, &owned, first); }; const offsets = try a.alloc(u32, slots); errdefer a.free(offsets); @memset(offsets, 0); const taps = try Taps.init(m.device, m.frame.capacity, @intCast(m.config.hidden)); - return .{ .allocator = a, .model = m, .geometry = geometry, .gdn = pool, .attention = attention, .scratch = scratch, .bindings = bindings, .caches = caches, .linear_index = linear_index, .attention_index = attention_index, .offsets = offsets, .owned = owned, .taps = taps, .slots = slots, .ready = ready, .capacity = capacity, .kv = kv }; + return .{ .allocator = a, .model = m, .geometry = geometry, .gdn = pool, .attention = attention, .scratch = scratch, .bindings = bindings, .caches = caches, .linear_index = linear_index, .attention_index = attention_index, .offsets = offsets, .owned = owned, .taps = taps, .slots = slots, .ready = ready, .capacity = capacity, .kv = kv, .kv_step = kv_step }; } pub const cover = slot_pages.cover; @@ -189,36 +205,29 @@ pub const Runner = struct { return kv_pages.spans(r, a, slot, at, list); } - /// One slot's K/V rows across the attention layers. - pub fn slotBytes(r: *const Runner) usize { - return r.caches.len / r.slots * 2 * @as(usize, r.capacity) * r.model.config.kvDim() * 2; + pub const slotBytes = kv_slots.slotBytes; + pub const ensure = kv_slots.ensure; + pub const heldRows = kv_slots.heldRows; + /// Slot `slot` holds `need` K/V rows, grown layer by layer (kv_slots.zig). + pub fn reserve(r: *Runner, slot: u32, need: u32) !void { + return kv_slots.reserve(r, slot, need); } - /// Slot `slot`'s K/V rows (the next unready slot, as free slots are taken lowest first); its new buffers. - pub fn ensure(r: *Runner, slot: u32) ![]const mtl.Buffer { - if (slot < r.ready) return &.{}; - if (slot != r.ready) return error.SlotOutOfOrder; - const first = r.owned.items.len; - errdefer { - for (r.owned.items[first..]) |b| b.deinit(); - r.owned.shrinkRetainingCapacity(first); - } - const layers = r.caches.len / r.slots; - for (0..layers) |layer| r.caches[layer * r.slots + slot] = try slotCache(r.allocator, r.model, &r.owned, r.capacity); - r.ready += 1; - if (r.residency) |f| for (r.owned.items[first..]) |b| f.join(f.ctx, b); - return r.owned.items[first..]; - } - - /// The K/V buffers of the ready slots (for a residency set). - pub fn readyBuffers(r: *const Runner, a: std.mem.Allocator, out: *std.ArrayList(mtl.Buffer)) !void { - if (r.kv) |k| return out.appendSlice(a, &.{ k.arena, k.tables }); - for (0..r.caches.len / r.slots) |layer| for (0..r.ready) |slot| { - const c = r.caches[layer * r.slots + slot]; - try out.appendSlice(a, &.{ c.keys.buffer, c.values.buffer }); - }; + pub const releaseGrown = kv_slots.release; + + /// Emptied slot `slot` holds the rows a prompt of `need` tokens fills, without a copy (kv_slots.zig). + pub fn admit(r: *Runner, slot: u32, need: u32) !void { + return kv_slots.admit(r, slot, need); } + pub const busy = kv_slots.busy; + /// settleSlot for a hook that holds the runner as an opaque pointer (a drafter context's ring). + pub fn settleOpaque(ctx: *anyopaque, slot: u32) void { + const r: *Runner = @ptrCast(@alignCast(ctx)); + r.settleSlot(slot); + } + + pub const readyBuffers = kv_slots.readyBuffers; pub fn setResident(r: *Runner, hook: ?mtl.ResidencySet.Follow) void { @import("residency.zig").setRunner(r, hook); } @@ -273,7 +282,9 @@ pub const Runner = struct { // A rank's head writes only this rank's vocabulary columns; the tail's matcher reads the whole vocabulary. if (r.tail != null and r.reduce != null) return error.TailOnRank; for (round.slots, round.windows) |slot, window| if (slot >= r.ready or r.offsets[slot] != window.start) return error.CachePositionDiffers; + if (stage_planes.on) if (stage_planes.active != null) try stage_planes.admit(round.windows); // refused before the round touches any state for (round.slots, round.windows) |slot, window| try r.cover(slot, window.start + @as(u32, @intCast(window.parents.len))); + for (round.slots, round.windows) |slot, window| try r.reserve(slot, window.start + @as(u32, @intCast(window.parents.len))); const paths = try r.allocator.alloc([]const u32, round.windows.len); defer r.allocator.free(paths); @memset(paths, &.{}); @@ -317,7 +328,7 @@ pub const Runner = struct { defer pool.pop(); const spanned = if (r.trace) |t| t.spanned else 0; // a profiled pass's spans commit buffers of their own const handed = if (r.model.ane) |share| share.gpu_seconds else 0; - const tail_facts = @import("prompt_tail.zig").facts(r, head, accepted, placed.images != null or r.images != null); + const tail_facts = stage_planes.begin(@import("prompt_tail.zig").facts(r, head, accepted, placed.images != null or r.images != null)); r.tail_from = @import("prompt_tail.zig").first(tail_facts, round.ids.len, round.windows.len); defer r.tail_from = null; if (r.tail_from) |t0| r.model.frame.setTail(t0, @intCast(round.ids.len)); @@ -347,6 +358,7 @@ pub const Runner = struct { if (accepted) { for (round.slots, round.windows) |slot, window| r.offsets[slot] = window.start + @as(u32, @intCast(window.parents.len)); } else r.active = fingerprint(round); + if (stage_planes.on) if (stage_planes.active) |planes| try planes.end(round.windows[0].start); // after the round is committed, so a refusal leaves it whole } /// One MTP head pass (mtp.zig `pass`); a round left to keep reads nothing it writes. @@ -518,7 +530,7 @@ pub const Runner = struct { pub fn attentionPlan(r: *Runner, round: *const Round) !attn.Plan { var windows: [attn.planning.max_streams]attn.planning.Window = undefined; if (round.windows.len > windows.len) return error.AttentionStreams; - for (round.windows, 0..) |window, i| windows[i] = .{ .parents = window.parents, .start = window.start, .capacity = r.capacity }; + for (round.windows, round.slots, 0..) |window, slot, i| windows[i] = .{ .parents = window.parents, .start = window.start, .capacity = if (r.kv_step != null) r.heldRows(slot) else r.capacity }; var plan = try attn.Plan.init(r.allocator, windows[0..round.windows.len], r.geometry); if (r.attention.join != null) plan.pair(&.{}); // a stream's rows in pairs over the keys below its window return plan; @@ -565,22 +577,6 @@ pub const Runner = struct { } }; -fn slotCache(a: std.mem.Allocator, m: *Model, owned: *std.ArrayList(mtl.Buffer), capacity: u32) !attn.Cache { - const bytes = @as(usize, capacity) * m.config.kvDim() * 2; - const key = try allocation(a, m.device, owned, bytes); - const value = try allocation(a, m.device, owned, bytes); - return .{ .keys = .{ .buffer = key }, .values = .{ .buffer = value }, .capacity = capacity }; -} - -fn allocation(a: std.mem.Allocator, device: mtl.Device, owned: *std.ArrayList(mtl.Buffer), bytes: usize) !mtl.Buffer { - const b = try device.buffer(bytes, mtl.ResourceOptions.shared | mtl.ResourceOptions.untracked); - owned.append(a, b) catch |err| { - b.deinit(); - return err; - }; - return b; -} - fn fingerprint(round: *const Round) [32]u8 { var hash = std.crypto.hash.sha2.Sha256.init(.{}); hash.update(std.mem.sliceAsBytes(round.ids)); diff --git a/zig/src/families/qwen27/dflash/caches.zig b/zig/src/families/qwen27/dflash/caches.zig index f6fefc31fc6..450ce655942 100644 --- a/zig/src/families/qwen27/dflash/caches.zig +++ b/zig/src/families/qwen27/dflash/caches.zig @@ -4,7 +4,7 @@ const cfg = @import("config.zig"); pub fn Pair(comptime Buffer: type) type { return struct { keys: Buffer, values: Buffer }; } -/// `layers` rolling K/V caches of the window plus one block, as a stream's drafter context holds them. +/// `layers` rolling K/V caches of each layer's window plus one block, as a stream's drafter context holds them. pub fn newCaches(comptime Buffer: type, a: std.mem.Allocator, device: anytype, c: cfg.Config, layers: usize) ![]Pair(Buffer) { const Cache = Pair(Buffer); const caches = try a.alloc(Cache, layers); @@ -14,8 +14,8 @@ pub fn newCaches(comptime Buffer: type, a: std.mem.Allocator, device: anytype, c cache.keys.deinit(); cache.values.deinit(); }; - for (caches) |*cache| { - const bytes = @as(usize, c.window + 16) * c.kvWidth() * 2; + for (caches, 0..) |*cache, i| { + const bytes = @as(usize, c.layerWindow(i) + 16) * c.kvWidth() * 2; const keys = try device.buffer(bytes, @import("metal").ResourceOptions.shared | @import("metal").ResourceOptions.untracked); const values = device.buffer(bytes, @import("metal").ResourceOptions.shared | @import("metal").ResourceOptions.untracked) catch |err| { keys.deinit(); diff --git a/zig/src/families/qwen27/dflash/config.zig b/zig/src/families/qwen27/dflash/config.zig index fa290e327bc..58446bf8676 100644 --- a/zig/src/families/qwen27/dflash/config.zig +++ b/zig/src/families/qwen27/dflash/config.zig @@ -8,7 +8,10 @@ pub const tap_ids = [max_taps]u32{ 5, 19, 33, 47, 61, 0, 0, 0 }; /// incoai/Ornith-1.5-122B-DFlash2: six layers over Ornith-1.5-122B's 48, a block of 16. pub const flint_tap_ids = [max_taps]u32{ 5, 15, 26, 36, 46, 0, 0, 0 }; pub const ornith_tap_ids = [max_taps]u32{ 1, 7, 14, 20, 26, 32, 39, 45 }; +/// DFlash2 (conv kernels and a candidate selector) or z-lab's DFlash v1 (a plain qwen3 body, taps fused by fc). +pub const Variant = enum { dflash2, v1 }; pub const Config = struct { + variant: Variant = .dflash2, hidden: u32 = 5120, intermediate: u32 = 17408, layers: u32 = 5, @@ -28,6 +31,22 @@ pub const Config = struct { theta: f64 = 10000000, taps: [max_taps]u32 = tap_ids, tap_count: u32 = 5, + /// v1: the layers whose layer_types entry is full_attention (DFlash2 layers are all sliding). + full: [8]bool = @splat(false), + /// v1: the positions a stream's drafter context keeps (its full layers see all of them; 0: the window). + history: u32 = 0, + /// Positions kept: the ring's rows and the full layers' context; sliding layers see the last `window` - 1. + pub fn span(c: Config) u32 { + return if (c.variant == .v1 and c.history > c.window) c.history else c.window; + } + /// Rows layer `i` attends behind its block: its own window, or the whole span for a full layer. + pub fn layerWindow(c: Config, i: usize) u32 { + return if (c.full[i]) c.span() else c.window; + } + /// A ring row: v1 keeps fused, normed taps (fc and hidden_norm ran in the taps pass); DFlash2 keeps raw taps. + pub fn ringWidth(c: Config) u32 { + return if (c.variant == .v1) c.hidden else c.tapWidth(); + } pub fn qWidth(c: Config) u32 { return c.heads * c.head_dim; } @@ -46,13 +65,16 @@ pub const Config = struct { pub fn depth(c: Config) u32 { return c.block - 1; } + /// DFlash2: 15 a layer and six globals; v1: 11 a layer beside fc, hidden_norm and norm. pub fn tensorCount(c: Config) usize { - return 15 * @as(usize, c.layers) + 6; + return if (c.variant == .v1) 11 * @as(usize, c.layers) + 3 else 15 * @as(usize, c.layers) + 6; } + /// DFlash2: seven linears and two conv projections a layer, fc and the selector's projection; v1: seven and fc. pub fn linearCount(c: Config) usize { - return 9 * @as(usize, c.layers) + 2; + return if (c.variant == .v1) 7 * @as(usize, c.layers) + 1 else 9 * @as(usize, c.layers) + 2; } pub fn check(c: Config) !void { + if (c.variant == .v1) return c.checkV1(); const dimensions = [_]u32{ c.hidden, c.intermediate, c.layers, c.vocab, c.heads, c.kv_heads, c.head_dim, c.target_layers, c.group, c.rank, c.topk }; for (dimensions) |n| if (n == 0) return error.BadDraftConfig; if (c.hidden % 64 != 0 or c.intermediate % 64 != 0 or c.hidden % c.group != 0 or c.heads % c.kv_heads != 0 or c.head_dim % 2 != 0 or (c.block != 8 and c.block != 16) or c.conv != 2 or c.layers > 8 or c.mask >= c.vocab or c.topk > c.vocab or c.window < c.block) return error.BadDraftConfig; @@ -67,10 +89,30 @@ pub const Config = struct { _ = try std.math.mul(u32, c.hidden / c.group, 4); if (q % 64 != 0) return error.BadDraftConfig; } + /// The drafters name in the serving and startup lines: DFlash for z-labs v1 layout, DFlash2 for its successor. + pub fn kind(c: Config) []const u8 { + return if (c.variant == .v1) "DFlash" else "DFlash2"; + } /// A draft reads one target's taps and vocabulary: its width, vocabulary and tapped depth. pub fn bind(c: Config, hidden: usize, vocab: usize, layers: usize) !void { if (hidden != c.hidden or vocab != c.vocab or layers != c.target_layers) return error.DraftForAnotherTarget; } + /// v1 has no conv kernels and no selector (group, conv and rank zero); its lattice keeps the head's top-k. + fn checkV1(c: Config) !void { + const dimensions = [_]u32{ c.hidden, c.intermediate, c.layers, c.vocab, c.heads, c.kv_heads, c.head_dim, c.target_layers, c.topk, c.tap_count }; + for (dimensions) |n| if (n == 0) return error.BadDraftConfig; + if (c.group != 0 or c.conv != 0 or c.rank != 0) return error.BadDraftConfig; + if (c.hidden % 64 != 0 or c.intermediate % 64 != 0 or c.heads % c.kv_heads != 0 or c.head_dim % 2 != 0 or c.block < 2 or c.block > 16 or c.layers > 8 or c.tap_count > max_taps or c.mask >= c.vocab or c.topk > 16 or c.topk > c.vocab or c.window < c.block) return error.BadDraftConfig; + if (!std.math.isFinite(c.eps) or c.eps <= 0 or !std.math.isFinite(c.theta) or c.theta <= 0) return error.BadDraftConfig; + for (c.taps[0..c.tap_count]) |i| if (i >= c.target_layers) return error.BadDraftConfig; + for (c.taps[0..c.tap_count], 0..) |tap, i| for (c.taps[0..i]) |previous| if (tap == previous) return error.UnsupportedDraftTaps; + for (c.taps[c.tap_count..]) |unused| if (unused != 0) return error.BadDraftConfig; + for (c.full[c.layers..]) |unused| if (unused) return error.BadDraftConfig; + const q = try std.math.mul(u32, c.heads, c.head_dim); + _ = try std.math.mul(u32, c.kv_heads, c.head_dim); + _ = try std.math.mul(u32, c.hidden, c.tap_count); + if (q % 64 != 0) return error.BadDraftConfig; + } /// Published Qwen, Ornith and Flint shapes admitted by the shared Metal draft runtime. pub fn requireStock(c: Config) !void { try c.check(); @@ -108,6 +150,7 @@ pub fn parse(gpa: std.mem.Allocator, raw: []const u8) !Config { const o = try object(p.value); const d = try object(o.get("dflash_config") orelse return error.BadDraftConfig); const architectures = o.get("architectures") orelse return error.BadDraftConfig; + if (architectures == .array and architectures.array.items.len == 1 and architectures.array.items[0] == .string and std.mem.eql(u8, architectures.array.items[0].string, "DFlashDraftModel")) return parseV1(o, d); if (architectures != .array or architectures.array.items.len != 1 or architectures.array.items[0] != .string or !std.mem.eql(u8, architectures.array.items[0].string, "DFlash2DraftModel")) return error.BadDraftConfig; try text(o, "model_type", "qwen3"); try text(o, "dtype", "bfloat16"); @@ -136,6 +179,41 @@ pub fn parse(gpa: std.mem.Allocator, raw: []const u8) !Config { try c.requireStock(); return c; } +/// z-lab's DFlash v1 layout (DFlashDraftModel): its taps, block, mask and layer kinds from the config. +fn parseV1(o: std.json.ObjectMap, d: std.json.ObjectMap) !Config { + try text(o, "model_type", "qwen3"); + try text(o, "dtype", "bfloat16"); + try text(o, "hidden_act", "silu"); + for ([_][]const u8{ "attention_bias", "tie_word_embeddings" }) |key| { + const v = o.get(key) orelse return error.BadDraftConfig; + if (v != .bool or v.bool) return error.BadDraftConfig; + } + // the draft attends to its whole block both ways; a config that says otherwise is not this reading + if (o.get("is_causal")) |v| if (v != .bool or v.bool) return error.BadDraftConfig; + for ([_][]const u8{ "conv_group_size", "conv_kernel_size", "selector_rank", "selector_top_k" }) |key| if (d.get(key) != null) return error.BadDraftConfig; + const sliding = o.get("use_sliding_window") orelse return error.BadDraftConfig; + if (sliding != .bool or !sliding.bool or try number(o, "attention_dropout") != 0) return error.BadDraftConfig; + const rope = try object(o.get("rope_parameters") orelse return error.BadDraftConfig); + try text(rope, "rope_type", "default"); + if (o.get("rope_scaling")) |v| if (v != .null) return error.BadDraftConfig; + var c = Config{ .variant = .v1, .hidden = try integer(o, "hidden_size"), .intermediate = try integer(o, "intermediate_size"), .layers = try integer(o, "num_hidden_layers"), .vocab = try integer(o, "vocab_size"), .heads = try integer(o, "num_attention_heads"), .kv_heads = try integer(o, "num_key_value_heads"), .head_dim = try integer(o, "head_dim"), .target_layers = try integer(o, "num_target_layers"), .block = try integer(d, "block_size"), .mask = try integer(d, "mask_token_id"), .window = try integer(o, "sliding_window"), .group = 0, .conv = 0, .rank = 0, .topk = 16, .eps = @floatCast(try number(o, "rms_norm_eps")), .theta = try number(rope, "rope_theta"), .taps = @splat(0), .tap_count = 0 }; + const taps = d.get("target_layer_ids") orelse return error.BadDraftConfig; + if (taps != .array or taps.array.items.len == 0 or taps.array.items.len > max_taps) return error.BadDraftConfig; + for (taps.array.items, 0..) |v, i| { + if (v != .integer or v.integer < 0 or v.integer > std.math.maxInt(u32)) return error.BadDraftConfig; + c.taps[i] = @intCast(v.integer); + } + c.tap_count = @intCast(taps.array.items.len); + if (c.layers == 0 or c.layers > 8) return error.BadDraftConfig; + const types = o.get("layer_types") orelse return error.BadDraftConfig; + if (types != .array or types.array.items.len != c.layers) return error.BadDraftConfig; + for (types.array.items, 0..) |v, i| { + if (v != .string) return error.BadDraftConfig; + if (std.mem.eql(u8, v.string, "full_attention")) c.full[i] = true else if (!std.mem.eql(u8, v.string, "sliding_attention")) return error.BadDraftConfig; + } + try c.check(); + return c; +} /// --drafter's config against the target's, from the two folders' config.json: a refusal comes before either loads. pub fn admit(gpa: std.mem.Allocator, io: std.Io, target_dir: []const u8, draft_dir: []const u8) !Config { @@ -280,3 +358,89 @@ test "Flint DFlash2 binds only its published target shape and post-block taps" { bad.theta = 10000000; try std.testing.expectError(error.NotStockDFlash2, bad.requireStock()); } +// z-lab/Qwen3.5-9B-DFlash's config.json, as published (Ornith-1.5-9B-DFlash publishes the same file). +const v1_fixture = + \\{"architectures":["DFlashDraftModel"],"attention_bias":false,"attention_dropout":0.0, + \\"auto_map":{"AutoModel":"dflash.DFlashDraftModel"},"bos_token_id":null, + \\"dflash_config":{"block_size":16,"mask_token_id":248077,"target_layer_ids":[1,5,9,13,17,21,25,29]}, + \\"dtype":"bfloat16","eos_token_id":248044,"head_dim":128,"hidden_act":"silu","hidden_size":4096, + \\"initializer_range":0.02,"intermediate_size":12288, + \\"layer_types":["sliding_attention","sliding_attention","sliding_attention","sliding_attention","sliding_attention","full_attention"], + \\"max_position_embeddings":262144,"max_window_layers":6,"model_type":"qwen3","num_attention_heads":32, + \\"num_hidden_layers":6,"num_key_value_heads":8,"num_target_layers":32,"pad_token_id":null,"rms_norm_eps":1e-06, + \\"rope_parameters":{"rope_theta":10000000,"rope_type":"default"},"sliding_window":4096,"tie_word_embeddings":false, + \\"transformers_version":"5.7.0","use_cache":true,"use_sliding_window":true,"vocab_size":248320} +; +test "the 9B target takes its own DFlash v1 drafter, and the 27B target refuses it by name" { + const a = std.testing.allocator; + const nine = try targetJson(a, 4096, 12288, 32, 16, 32); + defer a.free(nine); + const big = try targetJson(a, 5120, 17408, 64, 24, 48); + defer a.free(big); + try std.testing.expectEqual(Variant.v1, (try admitFolders(nine, v1_fixture)).variant); + try std.testing.expectError(error.DraftForAnotherTarget, admitFolders(big, v1_fixture)); +} +test "a DFlash v1 config reads its own taps, layer kinds, block and window" { + const c = try parse(std.testing.allocator, v1_fixture); + try std.testing.expectEqual(Variant.v1, c.variant); + try std.testing.expectEqual(@as(u32, 8), c.tap_count); + try std.testing.expectEqualSlices(u32, &.{ 1, 5, 9, 13, 17, 21, 25, 29 }, c.taps[0..8]); + try std.testing.expectEqual(@as(u32, 16), c.block); + try std.testing.expectEqual(@as(u32, 15), c.depth()); + try std.testing.expectEqual(@as(u32, 248077), c.mask); + try std.testing.expectEqual(@as(u32, 4096), c.window); + try std.testing.expectEqual(@as(u32, 4096), c.hidden); + try std.testing.expectEqual(@as(u32, 12288), c.intermediate); + try std.testing.expectEqual(@as(u32, 6), c.layers); + try std.testing.expectEqual(@as(u32, 32), c.target_layers); + try std.testing.expectEqualSlices(bool, &.{ false, false, false, false, false, true }, c.full[0..6]); + try std.testing.expectEqual(@as(u32, 32768), c.tapWidth()); + try std.testing.expectEqual(@as(u32, 0), c.rank); + try std.testing.expectEqual(@as(u32, 16), c.topk); +} +test "a DFlash v1 draft counts eleven tensors a layer and seven linears a layer beside fc" { + const c = try parse(std.testing.allocator, v1_fixture); + try std.testing.expectEqual(@as(usize, 69), c.tensorCount()); + try std.testing.expectEqual(@as(usize, 43), c.linearCount()); +} +test "a DFlash v1 config whose taps fall past the target or repeat is refused" { + const a = std.testing.allocator; + const past = try std.mem.replaceOwned(u8, a, v1_fixture, "25,29]", "25,32]"); + defer a.free(past); + try std.testing.expectError(error.BadDraftConfig, parse(a, past)); + const repeated = try std.mem.replaceOwned(u8, a, v1_fixture, "25,29]", "25,25]"); + defer a.free(repeated); + try std.testing.expectError(error.UnsupportedDraftTaps, parse(a, repeated)); +} +test "a DFlash v1 config that asks for a causal draft is refused" { + const a = std.testing.allocator; + const causal = try std.mem.replaceOwned(u8, a, v1_fixture, "\"attention_bias\":false", "\"attention_bias\":false,\"is_causal\":true"); + defer a.free(causal); + try std.testing.expectError(error.BadDraftConfig, parse(a, causal)); +} +test "a v1 draft keeps fused ring rows and gives its full layer the whole span" { + var c = try parse(std.testing.allocator, v1_fixture); + try std.testing.expectEqual(@as(u32, 4096), c.ringWidth()); + try std.testing.expectEqual(@as(u32, 4096), c.span()); + c.history = 32768; + try std.testing.expectEqual(@as(u32, 32768), c.span()); + try std.testing.expectEqual(@as(u32, 4096), c.layerWindow(0)); + try std.testing.expectEqual(@as(u32, 32768), c.layerWindow(5)); +} +test "DFlash2 keeps raw tap rows and its window everywhere" { + var c = Config{}; + c.history = 32768; + try std.testing.expectEqual(@as(u32, 25600), c.ringWidth()); + try std.testing.expectEqual(@as(u32, 2048), c.layerWindow(0)); + try std.testing.expectEqual(@as(u32, 2048), c.span()); +} +test "the stock DFlash2 config keeps its five taps and twenty-five-thousand-wide rows" { + const c = try parse(std.testing.allocator, fixture); + try std.testing.expectEqual(Variant.dflash2, c.variant); + try std.testing.expectEqual(@as(u32, 5), c.tap_count); + try std.testing.expectEqual(@as(u32, 25600), c.tapWidth()); +} +test "a v1 config names its drafter DFlash, and DFlash2 stays DFlash2" { + try std.testing.expectEqualStrings("DFlash", (try parse(std.testing.allocator, v1_fixture)).kind()); + try std.testing.expectEqualStrings("DFlash2", (try parse(std.testing.allocator, fixture)).kind()); +} diff --git a/zig/src/families/qwen27/dflash/execution.zig b/zig/src/families/qwen27/dflash/execution.zig index f9544da5a22..f30683f2b7b 100644 --- a/zig/src/families/qwen27/dflash/execution.zig +++ b/zig/src/families/qwen27/dflash/execution.zig @@ -22,6 +22,13 @@ fn rotate(ops: op.Ops, frame: u64, x: op.View, positions: []const u64, heads: u3 try y.check(x.rows, x.width, .bf16); return y; } +fn add(ops: op.Ops, frame: u64, x: op.View, y: op.View) !op.View { + const sum = ops.vtable.add orelse return error.DraftOperatorShape; + try y.check(x.rows, x.width, .bf16); + const z = try sum(ops.ptr, frame, x, y); + try z.check(x.rows, x.width, .bf16); + return z; +} /// `block`: rows a conv window spans; a batched pass stacks several streams' blocks. fn convolve(ops: op.Ops, frame: u64, x: op.View, dynamic: op.View, weights: w.Conv, branch: u32, residual: ?op.View, c: Config, block: u32) !op.View { try dynamic.check(x.rows, c.dynamicWidth(), .bf16); @@ -35,9 +42,9 @@ pub fn append(ops: op.Ops, g: *const w.Graph, preparation: op.Preparation, conte try preparation.check(); const c = g.config; try c.check(); - if (context.cache == 0 or context.begin > context.end or next.cache != context.cache or positions.len == 0 or next.end != try std.math.add(u64, context.end, positions.len) or next.begin != @max(context.begin, next.end -| (@as(u64, c.window) - 1))) return error.BadDraftContext; + if (context.cache == 0 or context.begin > context.end or next.cache != context.cache or positions.len == 0 or next.end != try std.math.add(u64, context.end, positions.len) or next.begin != @max(context.begin, next.end -| (@as(u64, c.span()) - 1))) return error.BadDraftContext; for (positions, 0..) |p, i| if (p != context.end + i or p >= next.end) return error.BadCommittedTaps; - try taps.check(@intCast(positions.len), c.tapWidth(), .bf16); + try taps.check(@intCast(positions.len), c.ringWidth(), .bf16); const frame = try ops.vtable.begin(ops.ptr); defer ops.vtable.release(ops.ptr, frame); const transaction = try ops.vtable.context_begin(ops.ptr, context); @@ -50,9 +57,9 @@ fn checkAppend(g: *const w.Graph, preparation: op.Preparation, context: op.Conte try preparation.check(); const c = g.config; try c.check(); - if (context.cache == 0 or context.begin > context.end or next.cache != context.cache or positions.len == 0 or next.end != try std.math.add(u64, context.end, positions.len) or next.begin != @max(context.begin, next.end -| (@as(u64, c.window) - 1))) return error.BadDraftContext; + if (context.cache == 0 or context.begin > context.end or next.cache != context.cache or positions.len == 0 or next.end != try std.math.add(u64, context.end, positions.len) or next.begin != @max(context.begin, next.end -| (@as(u64, c.span()) - 1))) return error.BadDraftContext; for (positions, 0..) |p, i| if (p != context.end + i or p >= next.end) return error.BadCommittedTaps; - try taps.check(@intCast(positions.len), c.tapWidth(), .bf16); + try taps.check(@intCast(positions.len), c.ringWidth(), .bf16); } /// Where appended keys and values go: a transaction's context, or a batched pass's stream. @@ -62,8 +69,8 @@ fn encodeAppend(ops: op.Ops, g: *const w.Graph, preparation: op.Preparation, tap } fn encodeAppendTo(ops: op.Ops, g: *const w.Graph, preparation: op.Preparation, taps: op.View, positions: []const u64, frame: u64, sink: Sink) !void { const c = g.config; - const fusion = try project(ops, frame, taps, g.fusion, preparation.mode); - const hidden = try norm(ops, frame, fusion, g.hidden_norm, c.eps, 1, c.hidden); + // a v1 ring holds rows already fused and normed (the target's taps pass ran fc and hidden_norm) + const hidden = if (c.variant == .v1) taps else try norm(ops, frame, try project(ops, frame, taps, g.fusion, preparation.mode), g.hidden_norm, c.eps, 1, c.hidden); for (g.layers, 0..) |layer, i| { const raw_keys = try project(ops, frame, hidden, layer.attention.k, preparation.mode); const keys = try rotate(ops, frame, try norm(ops, frame, raw_keys, layer.attention.k_norm, c.eps, c.kv_heads, c.head_dim), positions, c.kv_heads, c); @@ -79,7 +86,7 @@ fn encodeAppendTo(ops: op.Ops, g: *const w.Graph, preparation: op.Preparation, t pub fn appendBlock(ops: op.Ops, g: *const w.Graph, preparation: op.Preparation, context: op.Context, taps: op.View, positions: []const u64, next: op.Context, anchor: u32, block: u32) !op.Lattice { if (block < 2 or block > 16) return error.BadRuntimeBlock; try checkAppend(g, preparation, context, taps, positions, next); - if (anchor >= g.config.vocab or next.end - next.begin > g.config.window - 1) return error.BadDraftContext; + if (anchor >= g.config.vocab or next.end - next.begin > g.config.span() - 1) return error.BadDraftContext; const frame = try ops.vtable.begin(ops.ptr); defer ops.vtable.release(ops.ptr, frame); const transaction = try ops.vtable.context_begin(ops.ptr, context); @@ -99,7 +106,7 @@ pub const Consumer = struct { ptr: *anyopaque, call: *const fn (*anyopaque, u64, fn start(ops: op.Ops, g: *const w.Graph, preparation: op.Preparation, context: op.Context, anchor: u32) !u64 { try preparation.check(); try g.config.check(); - if (anchor >= g.config.vocab or context.cache == 0 or context.begin > context.end or context.end - context.begin > g.config.window - 1) return error.BadDraftContext; + if (anchor >= g.config.vocab or context.cache == 0 or context.begin > context.end or context.end - context.begin > g.config.span() - 1) return error.BadDraftContext; return ops.vtable.begin(ops.ptr); } fn encode(ops: op.Ops, g: *const w.Graph, preparation: op.Preparation, context: op.Context, anchor: u32, frame: u64, block: u32, given: []const u32) !Output { @@ -127,7 +134,9 @@ pub fn encodeStreams(ops: op.Ops, g: *const w.Graph, preparation: op.Preparation for (given, 1..) |t, i| ids[i] = t; var hidden = try ops.vtable.embed(ops.ptr, frame, g.embed, ids[0..rows]); try hidden.check(rows, c.hidden, .bf16); - for (g.layers, 0..) |layer, i| { + if (c.variant == .v1) { + hidden = try layersV1(ops, g, preparation, frame, hidden, positions[0..rows], streams[0].context, if (n > 1) contexts[0..n] else &.{}, block); + } else for (g.layers, 0..) |layer, i| { var residual = hidden; const xn = try norm(ops, frame, hidden, layer.input_norm, c.eps, 1, c.hidden); const dynamic = try project(ops, frame, xn, layer.attention_conv.projection, preparation.mode); @@ -156,9 +165,32 @@ pub fn encodeStreams(ops: op.Ops, g: *const w.Graph, preparation: op.Preparation const head = try ops.vtable.head(ops.ptr, frame, final); if (head.logits.handle == 0 or head.logits.rows != headed or head.logits.dtype != .bf16 or head.logits.width == 0 or head.logits.width > c.vocab or head.logits.stride < head.logits.width) return error.DraftOperatorShape; if (head.token_ids) |mapping| try mapping.check(1, head.logits.width, .u32) else if (head.logits.width != c.vocab) return error.DraftCandidateId; - const projected = try project(ops, frame, final, g.hidden_projection, preparation.mode); + // a v1 draft has no selector projection: its lattice reads none (rank 0), so the final rows stand in + const projected = if (c.variant == .v1) final else try project(ops, frame, final, g.hidden_projection, preparation.mode); return .{ .head = head, .projected = projected }; } +/// A DFlash v1 body: attention and a SwiGLU MLP a layer, each added to its residual (no conv kernels). +fn layersV1(ops: op.Ops, g: *const w.Graph, preparation: op.Preparation, frame: u64, embedded: op.View, positions: []const u64, context: op.Context, contexts: []const op.Context, block: u32) !op.View { + const c = g.config; + const rows = embedded.rows; + var hidden = embedded; + for (g.layers, 0..) |layer, i| { + const xn = try norm(ops, frame, hidden, layer.input_norm, c.eps, 1, c.hidden); + const query = try rotate(ops, frame, try norm(ops, frame, try project(ops, frame, xn, layer.attention.q, preparation.mode), layer.attention.q_norm, c.eps, c.heads, c.head_dim), positions, c.heads, c); + const keys = try rotate(ops, frame, try norm(ops, frame, try project(ops, frame, xn, layer.attention.k, preparation.mode), layer.attention.k_norm, c.eps, c.kv_heads, c.head_dim), positions, c.kv_heads, c); + const values = try project(ops, frame, xn, layer.attention.v, preparation.mode); + const attended = try ops.vtable.attention(ops.ptr, frame, .{ .context = context, .config = c, .layer = @intCast(i), .query = query, .keys = keys, .values = values, .positions = positions, .streams = contexts, .block = block }); + try attended.check(rows, c.qWidth(), .bf16); + hidden = try add(ops, frame, hidden, try project(ops, frame, attended, layer.attention.o, preparation.mode)); + const post = try norm(ops, frame, hidden, layer.post_norm, c.eps, 1, c.hidden); + const gate = try project(ops, frame, post, layer.mlp.gate, preparation.mode); + const up = try project(ops, frame, post, layer.mlp.up, preparation.mode); + const activated = try ops.vtable.swiglu(ops.ptr, frame, gate, up); + try activated.check(rows, c.intermediate, .bf16); + hidden = try add(ops, frame, hidden, try project(ops, frame, activated, layer.mlp.down, preparation.mode)); + } + return hidden; +} /// A stream's new taps for a batched pass: absorbed into its caches before its block reads them. pub const Absorb = struct { taps: op.View, positions: []const u64 }; @@ -168,15 +200,14 @@ pub const Stacked = struct { taps: op.View, positions: []const u64, spans: []con /// One read of each absorb weight for every stacked row, each row's position its own stream's. pub fn encodeStacked(ops: op.Ops, g: *const w.Graph, preparation: op.Preparation, frame: u64, s: Stacked) !void { const c = g.config; - try s.taps.check(@intCast(s.positions.len), c.tapWidth(), .bf16); + try s.taps.check(@intCast(s.positions.len), c.ringWidth(), .bf16); var next: u32 = 0; for (s.spans) |span| { if (span.rows == 0 or span.first != next) return error.BadCommittedTaps; next += span.rows; } if (next != s.positions.len) return error.BadCommittedTaps; - const fusion = try project(ops, frame, s.taps, g.fusion, preparation.mode); - const hidden = try norm(ops, frame, fusion, g.hidden_norm, c.eps, 1, c.hidden); + const hidden = if (c.variant == .v1) s.taps else try norm(ops, frame, try project(ops, frame, s.taps, g.fusion, preparation.mode), g.hidden_norm, c.eps, 1, c.hidden); for (g.layers, 0..) |layer, i| { const raw_keys = try project(ops, frame, hidden, layer.attention.k, preparation.mode); const keys = try rotate(ops, frame, try norm(ops, frame, raw_keys, layer.attention.k_norm, c.eps, c.kv_heads, c.head_dim), s.positions, c.kv_heads, c); @@ -192,7 +223,7 @@ pub fn encodeStacked(ops: op.Ops, g: *const w.Graph, preparation: op.Preparation /// Each stream's new taps through its own absorb pass, in stream order. pub fn encodeAbsorbs(ops: op.Ops, g: *const w.Graph, preparation: op.Preparation, frame: u64, absorbs: []const ?Absorb) !void { for (absorbs, 0..) |a, k| if (a) |x| { - try x.taps.check(@intCast(x.positions.len), g.config.tapWidth(), .bf16); + try x.taps.check(@intCast(x.positions.len), g.config.ringWidth(), .bf16); try encodeAppendTo(ops, g, preparation, x.taps, x.positions, frame, .{ .stream = @intCast(k) }); }; } @@ -202,7 +233,7 @@ pub fn absorbBlocks(ops: op.Ops, g: *const w.Graph, preparation: op.Preparation, try preparation.check(); try g.config.check(); if (block < 2 or block > 16 or streams.len < 2 or streams.len * block > 128 or out.len != streams.len or absorbs.len != streams.len) return error.BadRuntimeBlock; - for (streams) |s| if (s.anchor >= g.config.vocab or s.context.cache == 0 or s.context.begin > s.context.end or s.context.end - s.context.begin > g.config.window - 1) return error.BadDraftContext; + for (streams) |s| if (s.anchor >= g.config.vocab or s.context.cache == 0 or s.context.begin > s.context.end or s.context.end - s.context.begin > g.config.span() - 1) return error.BadDraftContext; if (stacked) |s| try encodeStacked(ops, g, preparation, frame, s) else try encodeAbsorbs(ops, g, preparation, frame, absorbs); const output = try encodeStreams(ops, g, preparation, streams, frame, block, &.{}); try ops.vtable.lattices(ops.ptr, frame, output.head, output.projected, g.config, block, out); diff --git a/zig/src/families/qwen27/dflash/execution_v1_test.zig b/zig/src/families/qwen27/dflash/execution_v1_test.zig new file mode 100644 index 00000000000..5619426f7cd --- /dev/null +++ b/zig/src/families/qwen27/dflash/execution_v1_test.zig @@ -0,0 +1,183 @@ +//! Fake operators prove the DFlash v1 schedule: a plain qwen3 body, two residual adds a layer, no conv, no selector. +const std = @import("std"); +const ck = @import("../checkpoint.zig"); +const cfg = @import("config.zig"); +const op = @import("operators.zig"); +const execution = @import("execution.zig"); +const fixtures = @import("fixtures.zig"); +const session = @import("session.zig"); +const selector = @import("selector.zig"); +const toy = fixtures.toy_v1; +const Fake = struct { + handle: u64 = 1, + projects: u32 = 0, + adds: u32 = 0, + attends: u32 = 0, + appends: u32 = 0, + commits: u32 = 0, + ids: [16]u32 = undefined, + positions: [16]u64 = undefined, + headed: u32 = 0, + fn self(ptr: *anyopaque) *Fake { + return @ptrCast(@alignCast(ptr)); + } + fn view(f: *Fake, rows: u32, width: u32) op.View { + f.handle += 1; + return .{ .handle = f.handle, .rows = rows, .width = width, .stride = width, .dtype = .bf16 }; + } + fn begin(ptr: *anyopaque) !u64 { + self(ptr).handle += 1; + return self(ptr).handle; + } + fn release(_: *anyopaque, _: u64) void {} + fn project(ptr: *anyopaque, _: u64, x: op.View, t: ck.Tensor, _: op.Mode) !op.View { + if (t.bytes.len == 0) return error.FakeAbsentWeight; + self(ptr).projects += 1; + return self(ptr).view(x.rows, @intCast(t.shape[0])); + } + fn norm(ptr: *anyopaque, _: u64, x: op.View, n: op.Norm) !op.View { + if (x.width != n.heads * n.head_dim) return error.FakeNormShape; + return self(ptr).view(x.rows, x.width); + } + fn embed(ptr: *anyopaque, _: u64, _: ck.Linear, ids: []const u32) !op.View { + @memcpy(self(ptr).ids[0..ids.len], ids); + return self(ptr).view(@intCast(ids.len), toy.hidden); + } + fn conv(_: *anyopaque, _: u64, _: op.View, _: op.Conv) !op.View { + return error.FakeV1HasNoConv; + } + fn rope(ptr: *anyopaque, _: u64, x: op.View, a: op.Rotary) !op.View { + if (a.positions.len <= 16) @memcpy(self(ptr).positions[0..a.positions.len], a.positions); + return self(ptr).view(x.rows, x.width); + } + fn attention(ptr: *anyopaque, _: u64, a: op.Attention) !op.View { + if (a.mask != .all_slots or a.layer != self(ptr).attends or a.query.rows != a.positions.len or a.positions[0] != a.context.end) return error.FakeAttentionOrder; + self(ptr).attends += 1; + return self(ptr).view(a.query.rows, a.config.qWidth()); + } + fn swiglu(ptr: *anyopaque, _: u64, a: op.View, b: op.View) !op.View { + if (a.width != b.width or a.rows != b.rows) return error.FakeMlpShape; + return self(ptr).view(a.rows, a.width); + } + fn add(ptr: *anyopaque, _: u64, x: op.View, y: op.View) !op.View { + if (x.rows != y.rows or x.width != y.width or x.width != toy.hidden) return error.FakeAddShape; + self(ptr).adds += 1; + return self(ptr).view(x.rows, x.width); + } + fn mask(ptr: *anyopaque, _: u64, x: op.View, first: u32, count: u32) !op.View { + if (first != 1 or count != x.rows - 1) return error.FakeAnchorShift; + return self(ptr).view(count, x.width); + } + fn head(ptr: *anyopaque, _: u64, x: op.View) !op.Head { + self(ptr).headed = x.rows; + return .{ .logits = self(ptr).view(x.rows, toy.vocab) }; + } + fn lattices(_: *anyopaque, _: u64, _: op.Head, _: op.View, _: cfg.Config, _: u32, _: []op.Lattice) !void { + return error.FakeBatchedHead; + } + fn streamAppend(_: *anyopaque, _: u64, _: u32, _: u32, _: op.View, _: op.View, _: []const u64) !void { + return error.FakeBatchedHead; + } + /// A chain: depth d's best candidate is token 10 + d, its runner-up far behind. + fn lattice(_: *anyopaque, _: u64, h: op.Head, _: op.View, c: cfg.Config) !op.Lattice { + const a = std.testing.allocator; + const ids = try a.alloc(u32, h.logits.rows * c.topk); + errdefer a.free(ids); + const unary = try a.alloc(f32, ids.len); + errdefer a.free(unary); + for (0..h.logits.rows) |d| { + ids[d * c.topk] = @intCast(10 + d); + unary[d * c.topk] = 0; + ids[d * c.topk + 1] = @intCast(40 + d); + unary[d * c.topk + 1] = -20; + } + return .{ .gpa = a, .depth = h.logits.rows, .topk = c.topk, .rank = c.rank, .candidates = ids, .unary = unary, .projected = try a.alloc(f32, 0) }; + } + fn contextBegin(_: *anyopaque, _: op.Context) !u64 { + return 1; + } + fn append(ptr: *anyopaque, _: u64, _: u64, layer: u32, k: op.View, v: op.View, positions: []const u64) !void { + const f = self(ptr); + if (layer != f.appends or k.rows != positions.len or v.rows != k.rows) return error.FakeAppendOrder; + f.appends += 1; + } + fn commit(ptr: *anyopaque, _: u64, _: u64, _: op.Context) !void { + self(ptr).commits += 1; + } + fn stage(_: *anyopaque, _: u64, _: u64, _: op.Context) !void {} + fn abort(_: *anyopaque, _: u64) void {} + fn ops(f: *Fake) op.Ops { + return .{ .ptr = f, .vtable = &.{ .begin = begin, .release = release, .project = project, .norm = norm, .embed = embed, .conv = conv, .rope = rope, .attention = attention, .swiglu = swiglu, .mask_rows = mask, .head = head, .lattice = lattice, .lattices = lattices, .context_begin = contextBegin, .context_append = append, .context_commit = commit, .context_stage = stage, .context_abort = abort, .stream_append = streamAppend, .add = add } }; + } +}; +fn taps() session.Batch { + return .{ .values = .{ .handle = 99, .rows = 2, .width = toy.ringWidth(), .stride = toy.ringWidth(), .dtype = .bf16 }, .positions = &.{ 0, 1 }, .layers = toy.taps, .target_end = 2 }; +} + +test "a v1 block runs attention and an MLP a layer, two residual adds each, and heads its fifteen mask rows" { + const a = std.testing.allocator; + var store = try fixtures.Store.initConfig(a, toy); + defer store.deinit(); + var g = try store.graph(a); + defer g.deinit(); + var fake = Fake{}; + var state = try session.Session.init(toy, 1, 0); + const p = op.Preparation{ .mode = .bf16_reference }; + try state.absorb(fake.ops(), &g, p, taps()); + try std.testing.expectEqual(@as(u32, 3), fake.appends); + // the context append from fused ring rows: k and v a layer, no fc (the target's taps pass ran it) + try std.testing.expectEqual(@as(u32, 2 * 3), fake.projects); + fake.projects = 0; + var tree = try state.treeBlock(a, fake.ops(), &g, p, 5, try state.firstDraw(), 16, .{ .nodes = 15 }); + defer tree.deinit(); + try std.testing.expectEqualSlices(u32, &.{ 5, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62 }, &fake.ids); + try std.testing.expectEqualSlices(u64, &.{ 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17 }, &fake.positions); + try std.testing.expectEqual(@as(u32, 3), fake.attends); + try std.testing.expectEqual(@as(u32, 6), fake.adds); + // q, k, v, o, gate, up and down a layer, and no selector projection + try std.testing.expectEqual(@as(u32, 7 * 3), fake.projects); + try std.testing.expectEqual(@as(u32, 15), fake.headed); + // with no selector, a confident lattice is a chain of each depth's best + try std.testing.expectEqual(@as(usize, 15), tree.tokens.len); + for (tree.tokens, tree.parents, 0..) |token, parent, d| { + try std.testing.expectEqual(@as(u32, @intCast(10 + d)), token); + try std.testing.expectEqual(@as(i32, @intCast(d)) - 1, parent); + } +} +test "a v1 graph holds no conv or selector tensor" { + const a = std.testing.allocator; + var store = try fixtures.Store.initConfig(a, toy); + defer store.deinit(); + var g = try store.graph(a); + defer g.deinit(); + try std.testing.expectEqual(@as(usize, 11 * 3 + 3), store.keys.len); + try std.testing.expectEqual(@as(usize, 0), g.hidden_projection.bytes.len); + try std.testing.expectEqual(@as(usize, 0), g.predecessor.bytes.len); + for (g.layers) |l| try std.testing.expectEqual(@as(usize, 0), l.attention_conv.projection.bytes.len + l.mlp_conv.base.bytes.len); + try std.testing.expect(try g.nativeBytes() > 0); +} +test "a v1 block without an add operator is refused, not run without its residuals" { + const a = std.testing.allocator; + var store = try fixtures.Store.initConfig(a, toy); + defer store.deinit(); + var g = try store.graph(a); + defer g.deinit(); + var fake = Fake{}; + var vtable = fake.ops().vtable.*; + vtable.add = null; + const ops = op.Ops{ .ptr = &fake, .vtable = &vtable }; + try std.testing.expectError(error.DraftOperatorShape, execution.forwardBlock(ops, &g, .{ .mode = .bf16_reference }, .{ .cache = 1, .begin = 0, .end = 2 }, 5, 16)); +} + +test "a v1 drafter's context keeps its whole span, not just the sliding window" { + var c = toy; + c.history = 64; + const s = try session.Session.init(c, 1, 0); + var positions: [40]u64 = undefined; + for (&positions, 0..) |*p, i| p.* = i; + const next = try s.admit(.{ .values = .{ .handle = 2, .rows = 40, .width = c.ringWidth(), .stride = c.ringWidth(), .dtype = .bf16 }, .positions = &positions, .layers = c.taps, .target_end = 40 }); + try std.testing.expectEqual(@as(u64, 0), next.begin); + const windowed = try session.Session.init(toy, 1, 0); + const cropped = try windowed.admit(.{ .values = .{ .handle = 2, .rows = 40, .width = toy.ringWidth(), .stride = toy.ringWidth(), .dtype = .bf16 }, .positions = &positions, .layers = toy.taps, .target_end = 40 }); + try std.testing.expectEqual(@as(u64, 40 - 31), cropped.begin); +} diff --git a/zig/src/families/qwen27/dflash/fixtures.zig b/zig/src/families/qwen27/dflash/fixtures.zig index 4eb14e967f4..85b187f358a 100644 --- a/zig/src/families/qwen27/dflash/fixtures.zig +++ b/zig/src/families/qwen27/dflash/fixtures.zig @@ -4,56 +4,64 @@ const ck = @import("../checkpoint.zig"); const Config = @import("config.zig").Config; const weights = @import("weights.zig"); pub const toy = Config{ .hidden = 64, .intermediate = 128, .vocab = 64, .heads = 8, .kv_heads = 4, .head_dim = 8, .mask = 63, .window = 16, .rank = 16, .topk = 2 }; +/// A tiny DFlash v1 draft: three taps of an eight-layer target, a sixteen-row block, its last layer full. +pub const toy_v1 = Config{ .variant = .v1, .hidden = 64, .intermediate = 128, .layers = 3, .vocab = 64, .heads = 8, .kv_heads = 4, .head_dim = 8, .target_layers = 8, .block = 16, .mask = 62, .window = 32, .group = 0, .conv = 0, .rank = 0, .topk = 2, .taps = .{ 1, 3, 5, 0, 0, 0, 0, 0 }, .tap_count = 3, .full = .{ false, false, true, false, false, false, false, false } }; const Dimensions = struct { values: @FieldType(ck.Tensor, "shape"), rank: usize }; pub const Store = struct { arena: std.heap.ArenaAllocator, + config: Config = toy, keys: [][]const u8 = undefined, tensors: []ck.Tensor = undefined, embed: ck.Tensor = undefined, pub fn init(gpa: std.mem.Allocator) !Store { - var s = Store{ .arena = std.heap.ArenaAllocator.init(gpa) }; + return initConfig(gpa, toy); + } + /// Zeroed tensors for every name the draft of config `c` reads. + pub fn initConfig(gpa: std.mem.Allocator, c: Config) !Store { + var s = Store{ .arena = std.heap.ArenaAllocator.init(gpa), .config = c }; errdefer s.deinit(); const a = s.arena.allocator(); - s.keys = try weights.names(a, toy); + s.keys = try weights.names(a, c); s.tensors = try a.alloc(ck.Tensor, s.keys.len); for (s.keys, s.tensors) |name, *t| { - const shape = dims(name); + const shape = dims(c, name); var count: usize = 2; for (shape.values[0..shape.rank]) |n| count = try std.math.mul(usize, count, n); const data = try a.alloc(u8, count); @memset(data, 0); t.* = .{ .dtype = .bf16, .rank = @intCast(shape.rank), .shape = shape.values, .bytes = data }; } - const data = try a.alloc(u8, toy.vocab * toy.hidden * 2); + const data = try a.alloc(u8, c.vocab * c.hidden * 2); @memset(data, 0); - s.embed = .{ .dtype = .bf16, .rank = 2, .shape = .{ toy.vocab, toy.hidden, 1, 1, 1 }, .bytes = data }; + s.embed = .{ .dtype = .bf16, .rank = 2, .shape = .{ c.vocab, c.hidden, 1, 1, 1 }, .bytes = data }; return s; } pub fn deinit(s: *Store) void { s.arena.deinit(); } pub fn graph(s: *Store, gpa: std.mem.Allocator) !weights.Graph { - return weights.load(gpa, .{ .source = .{ .ptr = s, .getFn = get }, .names = s.keys }, toy, .{ .dense = s.embed }); + return weights.load(gpa, .{ .source = .{ .ptr = s, .getFn = get }, .names = s.keys }, s.config, .{ .dense = s.embed }); } fn get(ptr: *anyopaque, name: []const u8) !ck.Tensor { const s: *Store = @ptrCast(@alignCast(ptr)); for (s.keys, s.tensors) |key, t| if (std.mem.eql(u8, key, name)) return t; return error.MissingTensor; } - fn dims(name: []const u8) Dimensions { - if (std.mem.eql(u8, name, "fc.weight")) return .{ .values = .{ toy.hidden, toy.tapWidth(), 1, 1, 1 }, .rank = 2 }; - if (std.mem.eql(u8, name, "candidate_selector.hidden_projection.weight")) return .{ .values = .{ toy.rank, toy.hidden, 1, 1, 1 }, .rank = 2 }; - if (std.mem.startsWith(u8, name, "candidate_selector.")) return .{ .values = .{ toy.vocab, toy.rank, 1, 1, 1 }, .rank = 2 }; - if (std.mem.endsWith(u8, name, "base_kernel")) return .{ .values = .{ 2, 2, toy.hidden, 1, 1 }, .rank = 3 }; - if (std.mem.endsWith(u8, name, "kernel_projection.weight")) return .{ .values = .{ toy.dynamicWidth(), toy.hidden, 1, 1, 1 }, .rank = 2 }; - if (std.mem.endsWith(u8, name, "q_proj.weight")) return .{ .values = .{ toy.qWidth(), toy.hidden, 1, 1, 1 }, .rank = 2 }; - if (std.mem.endsWith(u8, name, "k_proj.weight") or std.mem.endsWith(u8, name, "v_proj.weight")) return .{ .values = .{ toy.kvWidth(), toy.hidden, 1, 1, 1 }, .rank = 2 }; - if (std.mem.endsWith(u8, name, "o_proj.weight")) return .{ .values = .{ toy.hidden, toy.qWidth(), 1, 1, 1 }, .rank = 2 }; - if (std.mem.endsWith(u8, name, "gate_proj.weight") or std.mem.endsWith(u8, name, "up_proj.weight")) return .{ .values = .{ toy.intermediate, toy.hidden, 1, 1, 1 }, .rank = 2 }; - if (std.mem.endsWith(u8, name, "down_proj.weight")) return .{ .values = .{ toy.hidden, toy.intermediate, 1, 1, 1 }, .rank = 2 }; - if (std.mem.endsWith(u8, name, "q_norm.weight") or std.mem.endsWith(u8, name, "k_norm.weight")) return .{ .values = .{ toy.head_dim, 1, 1, 1, 1 }, .rank = 1 }; - return .{ .values = .{ toy.hidden, 1, 1, 1, 1 }, .rank = 1 }; + fn dims(toy_config: Config, name: []const u8) Dimensions { + const t = toy_config; + if (std.mem.eql(u8, name, "fc.weight")) return .{ .values = .{ t.hidden, t.tapWidth(), 1, 1, 1 }, .rank = 2 }; + if (std.mem.eql(u8, name, "candidate_selector.hidden_projection.weight")) return .{ .values = .{ t.rank, t.hidden, 1, 1, 1 }, .rank = 2 }; + if (std.mem.startsWith(u8, name, "candidate_selector.")) return .{ .values = .{ t.vocab, t.rank, 1, 1, 1 }, .rank = 2 }; + if (std.mem.endsWith(u8, name, "base_kernel")) return .{ .values = .{ 2, 2, t.hidden, 1, 1 }, .rank = 3 }; + if (std.mem.endsWith(u8, name, "kernel_projection.weight")) return .{ .values = .{ t.dynamicWidth(), t.hidden, 1, 1, 1 }, .rank = 2 }; + if (std.mem.endsWith(u8, name, "q_proj.weight")) return .{ .values = .{ t.qWidth(), t.hidden, 1, 1, 1 }, .rank = 2 }; + if (std.mem.endsWith(u8, name, "k_proj.weight") or std.mem.endsWith(u8, name, "v_proj.weight")) return .{ .values = .{ t.kvWidth(), t.hidden, 1, 1, 1 }, .rank = 2 }; + if (std.mem.endsWith(u8, name, "o_proj.weight")) return .{ .values = .{ t.hidden, t.qWidth(), 1, 1, 1 }, .rank = 2 }; + if (std.mem.endsWith(u8, name, "gate_proj.weight") or std.mem.endsWith(u8, name, "up_proj.weight")) return .{ .values = .{ t.intermediate, t.hidden, 1, 1, 1 }, .rank = 2 }; + if (std.mem.endsWith(u8, name, "down_proj.weight")) return .{ .values = .{ t.hidden, t.intermediate, 1, 1, 1 }, .rank = 2 }; + if (std.mem.endsWith(u8, name, "q_norm.weight") or std.mem.endsWith(u8, name, "k_norm.weight")) return .{ .values = .{ t.head_dim, 1, 1, 1, 1 }, .rank = 1 }; + return .{ .values = .{ t.hidden, 1, 1, 1, 1 }, .rank = 1 }; } }; diff --git a/zig/src/families/qwen27/dflash/generation.zig b/zig/src/families/qwen27/dflash/generation.zig index ddc0596d550..fac34853731 100644 --- a/zig/src/families/qwen27/dflash/generation.zig +++ b/zig/src/families/qwen27/dflash/generation.zig @@ -23,6 +23,7 @@ pub const Generation = struct { pending: ?u32 = null, // runRound's next token as the last accept picked it; anything else that moves the target clears it pub fn init(a: std.mem.Allocator, runner: *Runner, draft: *Draft) !Generation { if (&runner.model.checkpoint != draft.backend.target.checkpoint or runner.model.config.hidden != draft.graph.config.hidden or runner.model.config.layers != draft.graph.config.target_layers) return error.TargetBinding; + try runner.taps.setFuser(runner.model.device, null); // a fused ring keeps its count: no drafter's fuser before use runner.capture_taps = true; try runner.taps.use(runner.model.device, draft.graph.config.tapIds()); const options = mtl.ResourceOptions.shared | mtl.ResourceOptions.untracked; @@ -33,6 +34,9 @@ pub const Generation = struct { const matcher = try @import("round_gpu.zig").Matcher.init(runner.model.device); errdefer matcher.deinit(); const commit = try @import("core").tree_commit_gpu.Ops.init(runner.model.device); + errdefer commit.deinit(); + // a v1 ring keeps fused rows: the target's taps pass runs the drafter's fc and hidden_norm as they complete + if (draft.graph.config.variant == .v1) try runner.taps.setFuser(runner.model.device, try draft.fuser(runner.taps.capacity)); return .{ .allocator = a, .runner = runner, .draft = draft, .kept = kept, .taps = taps, .matcher = matcher, .commit = commit }; } pub fn deinit(g: Generation) void { @@ -163,7 +167,8 @@ pub const Generation = struct { const width: u32 = @intCast(g.runner.model.config.vocab); const shape = try g.matcher.encode(e, .{ .buf = logits.buffer, .off = logits.offset }, ids, parents, width, budget, eos); const result = @import("core").tree_commit_gpu.Ref{ .buf = g.matcher.buffers[4] }; - try g.commit.taps(e, result, .{ .buf = g.runner.taps.buffer }, .{ .buf = g.taps }, .{ .rows = shape.rows, .width = g.runner.taps.width, .capacity = g.runner.taps.capacity, .planes = @intCast(g.runner.taps.count) }); + const src = g.runner.taps.source(); + try g.commit.taps(e, result, .{ .buf = src.buffer }, .{ .buf = g.taps }, .{ .rows = shape.rows, .width = src.width, .capacity = g.runner.taps.capacity, .planes = src.planes }); try g.commit.head(e, result, .{ .buf = logits.buffer, .off = logits.offset }, .{ .rows = shape.rows, .width = width, .stride = width }); return shape; } diff --git a/zig/src/families/qwen27/dflash/operators.zig b/zig/src/families/qwen27/dflash/operators.zig index 45ad1df88a0..de90332fddb 100644 --- a/zig/src/families/qwen27/dflash/operators.zig +++ b/zig/src/families/qwen27/dflash/operators.zig @@ -81,6 +81,8 @@ pub const Ops = struct { context_abort: *const fn (*anyopaque, u64) void, // a batched pass's stream k. stream_append: *const fn (*anyopaque, u64, u32, u32, View, View, []const u64) anyerror!void, + // x + y, row for row: a DFlash v1 layer's residuals (DFlash2 adds them inside its conv). + add: ?*const fn (*anyopaque, u64, View, View) anyerror!View = null, }; }; diff --git a/zig/src/families/qwen27/dflash/root.zig b/zig/src/families/qwen27/dflash/root.zig index 916cb4ccf51..777f7d66711 100644 --- a/zig/src/families/qwen27/dflash/root.zig +++ b/zig/src/families/qwen27/dflash/root.zig @@ -22,4 +22,5 @@ test { _ = @import("execution_test.zig"); _ = @import("absorb_batch.zig"); _ = @import("absorb_batch_test.zig"); + _ = @import("execution_v1_test.zig"); } diff --git a/zig/src/families/qwen27/dflash/runtime_backend.zig b/zig/src/families/qwen27/dflash/runtime_backend.zig index 8fe8da8697e..889e5288096 100644 --- a/zig/src/families/qwen27/dflash/runtime_backend.zig +++ b/zig/src/families/qwen27/dflash/runtime_backend.zig @@ -59,6 +59,7 @@ pub const Backend = struct { config: cfg.Config, primitives: core.draft_ops.Ops, attention: core.shared_attention.Attention, + attention_full: ?core.shared_attention.Attention = null, // a v1 full layer's, over the whole span topk: core.bf16_topk_gpu.Ops, head: @import("runtime_head.zig").Head, frame: Frame, @@ -82,6 +83,8 @@ pub const Backend = struct { errdefer primitives.deinit(); const attention = try core.shared_attention.Attention.init(a, target.device, .{ .query_heads = c.heads, .kv_heads = c.kv_heads, .head_dim = c.head_dim, .capacity = c.window + 16, .output = .bf16 }); errdefer attention.deinit(); + const attention_full: ?core.shared_attention.Attention = if (c.span() > c.window) try core.shared_attention.Attention.init(a, target.device, .{ .query_heads = c.heads, .kv_heads = c.kv_heads, .head_dim = c.head_dim, .capacity = c.span() + 16, .output = .bf16 }) else null; + errdefer if (attention_full) |x| x.deinit(); const topk = try core.bf16_topk_gpu.Ops.init(target.device); errdefer topk.deinit(); var head = try @import("runtime_head.zig").Head.init(a, target.device, target.weights.head); @@ -89,7 +92,7 @@ pub const Backend = struct { // the trimmed head's shape is the drafter's own: compile its pipeline here, not in the first draft round try target.kernels.prepareDecode(head.linear); const caches = try newCaches(a, target.device, c, c.layers); - return .{ .allocator = a, .target = target, .checkpoint = checkpoint, .config = c, .primitives = primitives, .attention = attention, .topk = topk, .head = head, .frame = .{ .allocator = a, .device = target.device, .queue = target.queue }, .caches = caches }; + return .{ .allocator = a, .target = target, .checkpoint = checkpoint, .config = c, .primitives = primitives, .attention = attention, .attention_full = attention_full, .topk = topk, .head = head, .frame = .{ .allocator = a, .device = target.device, .queue = target.queue }, .caches = caches }; } pub fn setResident(b: *Backend, hook: ?mtl.ResidencySet.Follow) void { @import("../residency.zig").setDraft(b, hook); @@ -108,6 +111,7 @@ pub const Backend = struct { freeCaches(b.allocator, b.caches); b.head.deinit(); b.topk.deinit(); + if (b.attention_full) |x| x.deinit(); b.attention.deinit(); b.primitives.deinit(); } @@ -150,6 +154,26 @@ pub const Backend = struct { pub fn linear(name: []const u8, rank: usize) bool { return rank == 2 and std.mem.endsWith(u8, name, ".weight"); } + /// `rows` rows of x (contiguous, `w`'s width) through linear `w` into y, outside any drafter frame. + pub fn encodeLinear(b: *Backend, e: mtl.ComputeEncoder, w: ck.Tensor, mode: op.Mode, x: Ref, y: Ref, rows: u32) !void { + const n: u32 = @intCast(w.shape[0]); + const k: u32 = @intCast(w.shape[1]); + if (mode == .bf16_reference) { + try b.primitives.linear(e, x, try b.weight(w), y, .{ .rows = rows, .n = n, .k = k, .x_stride = k, .w_stride = k, .y_stride = n }); + } else if (b.tiled.get(@intFromPtr(w.bytes.ptr))) |t| { + simd.encode(e, try simd.call(&b.simd.?, t.n, t.k, rows, false, false, 0), t.matrix(), x.buf, x.off, y.buf, y.off); + } else { + const adapter = b.prepared.get(@intFromPtr(w.bytes.ptr)) orelse return error.DraftPreparationUnqualified; + var first: u32 = 0; + while (first < rows) : (first += 16) { + try adapter.encode(e, .{ .buf = x.buf, .off = x.off + @as(usize, first) * k * 2 }, .{ .buf = y.buf, .off = y.off + @as(usize, first) * n * 2 }, @min(rows - first, 16)); + } + } + } + /// The attention whose capacity is layer `layer`'s window. + pub fn attentionFor(b: *const Backend, layer: u32) *const core.shared_attention.Attention { + return if (b.config.layerWindow(layer) > b.config.window) &b.attention_full.? else &b.attention; + } pub fn ops(b: *Backend) op.Ops { return .{ .ptr = b, .vtable = &callbacks.vtable }; } diff --git a/zig/src/families/qwen27/dflash/runtime_callbacks.zig b/zig/src/families/qwen27/dflash/runtime_callbacks.zig index ccf6de7fda8..00d6938484b 100644 --- a/zig/src/families/qwen27/dflash/runtime_callbacks.zig +++ b/zig/src/families/qwen27/dflash/runtime_callbacks.zig @@ -89,6 +89,18 @@ fn swiglu(ptr: *anyopaque, epoch: u64, g: op.View, u: op.View) !op.View { e.barrier(); return y; } +fn add(ptr: *anyopaque, epoch: u64, x: op.View, y: op.View) !op.View { + const b = backend(ptr); + const e = try b.encoder(epoch); + if (x.rows != y.rows or x.width != y.width or x.dtype != .bf16 or y.dtype != .bf16 or x.stride != x.width or y.stride != y.width) return error.DraftOperatorShape; + const z = try b.frame.alloc(x.rows, x.width, .bf16); + const xr = try b.frame.ref(x); + const yr = try b.frame.ref(y); + const zr = try b.frame.ref(z); + b.target.glue.residual(e, .{ .buffer = xr.buf, .offset = xr.off }, .{ .buffer = yr.buf, .offset = yr.off }, .{ .buffer = zr.buf, .offset = zr.off }, x.width, x.rows); + e.barrier(); + return z; +} fn maskRows(ptr: *anyopaque, epoch: u64, x: op.View, first: u32, rows: u32) !op.View { const b = backend(ptr); _ = try b.encoder(epoch); @@ -153,4 +165,4 @@ fn lattices(ptr: *anyopaque, epoch: u64, h: op.Head, projected: op.View, c: Conf made += 1; } } -pub const vtable = op.Ops.VTable{ .begin = begin, .release = release, .project = project, .norm = norm, .embed = embed, .conv = conv, .rope = rope, .attention = context.attention, .swiglu = swiglu, .mask_rows = maskRows, .head = head, .lattice = lattice, .lattices = lattices, .context_begin = context.begin, .context_append = context.append, .context_commit = context.commit, .context_stage = context.stage, .context_abort = context.abort, .stream_append = context.streamAppend }; +pub const vtable = op.Ops.VTable{ .begin = begin, .release = release, .project = project, .norm = norm, .embed = embed, .conv = conv, .rope = rope, .attention = context.attention, .swiglu = swiglu, .mask_rows = maskRows, .head = head, .lattice = lattice, .lattices = lattices, .context_begin = context.begin, .context_append = context.append, .context_commit = context.commit, .context_stage = context.stage, .context_abort = context.abort, .stream_append = context.streamAppend, .add = add }; diff --git a/zig/src/families/qwen27/dflash/runtime_context.zig b/zig/src/families/qwen27/dflash/runtime_context.zig index c76c34028c1..f50cd9f4537 100644 --- a/zig/src/families/qwen27/dflash/runtime_context.zig +++ b/zig/src/families/qwen27/dflash/runtime_context.zig @@ -23,7 +23,7 @@ pub fn append(ptr: *anyopaque, transaction: u64, epoch: u64, layer: u32, keys: o try values.check(keys.rows, keys.width, .bf16); if (b.appended != 0 and b.appended_rows != positions.len) return error.BadCommittedTaps; for (positions, 0..) |position, i| if (position != b.context.end + i) return error.BadCommittedTaps; - try appendRows(b, e, b.caches[layer], keys, values, positions); + try appendRows(b, e, b.caches[layer], layer, keys, values, positions); b.appended |= @as(u32, 1) << @intCast(layer); b.appended_rows = @intCast(positions.len); } @@ -33,24 +33,25 @@ pub fn streamAppend(ptr: *anyopaque, epoch: u64, stream: u32, layer: u32, keys: if (b.transaction != null or stream >= b.batch.len or layer >= b.config.layers or positions.len == 0) return error.BadDraftContext; try keys.check(@intCast(positions.len), b.config.kvWidth(), .bf16); try values.check(keys.rows, keys.width, .bf16); - try appendRows(b, e, b.batch[stream][layer], keys, values, positions); + try appendRows(b, e, b.batch[stream][layer], layer, keys, values, positions); } /// Rows' keys and values into `cache` at their positions' ring slots, 16 a dispatch. -fn appendRows(b: *Backend, e: @import("metal").ComputeEncoder, cache: @import("runtime_backend.zig").Cache, keys: op.View, values: op.View, positions: []const u64) !void { +fn appendRows(b: *Backend, e: @import("metal").ComputeEncoder, cache: @import("runtime_backend.zig").Cache, layer: u32, keys: op.View, values: op.View, positions: []const u64) !void { + const window = b.config.layerWindow(layer); const k = try b.frame.ref(keys); const v = try b.frame.ref(values); var first: usize = 0; while (first < positions.len) : (first += 16) { const count = @min(positions.len - first, 16); var slots: [16]u32 = undefined; - for (slots[0..count], 0..) |*slot, i| slot.* = @intCast(positions[first + i] % b.config.window); + for (slots[0..count], 0..) |*slot, i| slot.* = @intCast(positions[first + i] % window); const off = first * b.config.kvWidth() * 2; - try b.attention.appendKv(e, slots[0..count], .{ .buf = k.buf, .off = k.off + off }, .{ .buf = v.buf, .off = v.off + off }, .{ .buf = cache.keys }, .{ .buf = cache.values }); + try b.attentionFor(layer).appendKv(e, slots[0..count], .{ .buf = k.buf, .off = k.off + off }, .{ .buf = v.buf, .off = v.off + off }, .{ .buf = cache.keys }, .{ .buf = cache.values }); e.barrier(); } } fn ready(b: *Backend, transaction: u64, epoch: u64, next: op.Context) !void { - if (b.transaction != transaction or transaction != epoch or b.appended != (@as(u32, 1) << @intCast(b.config.layers)) - 1 or next.cache != b.context.cache or next.end != b.context.end + b.appended_rows or next.begin != @max(b.context.begin, next.end -| (@as(u64, b.config.window) - 1))) return error.BadDraftContext; + if (b.transaction != transaction or transaction != epoch or b.appended != (@as(u32, 1) << @intCast(b.config.layers)) - 1 or next.cache != b.context.cache or next.end != b.context.end + b.appended_rows or next.begin != @max(b.context.begin, next.end -| (@as(u64, b.config.span()) - 1))) return error.BadDraftContext; } pub fn commit(ptr: *anyopaque, transaction: u64, epoch: u64, next: op.Context) !void { const b = cast(ptr); @@ -81,11 +82,11 @@ pub fn abort(ptr: *anyopaque, transaction: u64) void { b.staged = null; } } -fn gather(b: *Backend, e: @import("metal").ComputeEncoder, context: op.Context, cache: @import("metal").Buffer, out: Ref) !void { +fn gather(b: *Backend, e: @import("metal").ComputeEncoder, context: op.Context, cache: @import("metal").Buffer, window: u32, out: Ref) !void { const rows: u32 = @intCast(context.end - context.begin); if (rows == 0) return; - const at: u32 = @intCast(context.begin % b.config.window); - const first = @min(rows, b.config.window - at); + const at: u32 = @intCast(context.begin % window); + const first = @min(rows, window - at); const width = b.config.kvWidth(); try b.copy(e, .{ .buf = cache, .off = @as(usize, at) * width * 2 }, out, first, width); if (first < rows) try b.copy(e, .{ .buf = cache }, .{ .buf = out.buf, .off = out.off + @as(usize, first) * width * 2 }, rows - first, width); @@ -107,12 +108,14 @@ pub fn attention(ptr: *anyopaque, epoch: u64, p: op.Attention) !op.View { } /// Query rows [first, first + rows) against `context`'s cached keys and their own, into the same rows of `result`. -fn attendRows(b: *Backend, e: @import("metal").ComputeEncoder, p: op.Attention, context: op.Context, caches: []const @import("runtime_backend.zig").Cache, first: u32, rows: u32, result: op.View) !void { +fn attendRows(b: *Backend, e: @import("metal").ComputeEncoder, p: op.Attention, kept: op.Context, caches: []const @import("runtime_backend.zig").Cache, first: u32, rows: u32, result: op.View) !void { + const window = b.config.layerWindow(p.layer); + const context = layerContext(kept, window); const context_rows: u32 = @intCast(context.end - context.begin); const keys = context_rows + rows; // An unwrapped context is contiguous in the cache: the query rows go behind it and attention reads in place. - const at: u32 = @intCast(context.begin % b.config.window); - const in_place = at + context_rows <= b.config.window and at + keys <= b.config.window + 16; + const at: u32 = @intCast(context.begin % window); + const in_place = at + context_rows <= window and at + keys <= window + 16; var k: Ref = undefined; var v: Ref = undefined; if (in_place) { @@ -123,8 +126,8 @@ fn attendRows(b: *Backend, e: @import("metal").ComputeEncoder, p: op.Attention, const merged_v = try b.frame.alloc(keys, b.config.kvWidth(), .bf16); k = try b.frame.ref(merged_k); v = try b.frame.ref(merged_v); - try gather(b, e, context, caches[p.layer].keys, k); - try gather(b, e, context, caches[p.layer].values, v); + try gather(b, e, context, caches[p.layer].keys, window, k); + try gather(b, e, context, caches[p.layer].values, window, v); } const off = @as(usize, context_rows) * b.config.kvWidth() * 2; const own_k = try b.frame.ref(p.keys); @@ -133,16 +136,27 @@ fn attendRows(b: *Backend, e: @import("metal").ComputeEncoder, p: op.Attention, try b.copy(e, .{ .buf = own_v.buf, .off = own_v.off + @as(usize, first) * p.values.stride * 2 }, .{ .buf = v.buf, .off = v.off + off }, rows, p.values.width); const mask = try b.frame.alloc(rows, keys, .u8); const mask_ref = try b.frame.ref(mask); - try fillMask(mask_ref.buf.contents()[mask_ref.off..][0 .. @as(usize, rows) * keys], context_rows, rows, b.config.window, b.config.block); + try fillMask(mask_ref.buf.contents()[mask_ref.off..][0 .. @as(usize, rows) * keys], context_rows, rows, window, b.config.block); const q = try b.frame.ref(p.query); const y = try b.frame.ref(result); const scale = 1.0 / @sqrt(@as(f32, @floatFromInt(b.config.head_dim))); const R = @import("core").shared_attention.Ref; const views = [_]R{ .{ .buf = q.buf, .off = q.off + @as(usize, first) * p.query.stride * 2 }, .{ .buf = k.buf, .off = k.off }, .{ .buf = v.buf, .off = v.off }, .{ .buf = mask_ref.buf, .off = mask_ref.off }, .{ .buf = y.buf, .off = y.off + @as(usize, first) * result.stride * 2 } }; // Long contexts share each 256-key chunk across the query heads of one KV head. - if (keys > 1024) try b.attention.encodeSplit(e, rows, keys, keys, scale, views[0], views[1], views[2], views[3], views[4]) else try b.attention.encode(e, rows, keys, keys, scale, views[0], views[1], views[2], views[3], views[4]); + const attend = b.attentionFor(p.layer); + if (keys > 1024) try attend.encodeSplit(e, rows, keys, keys, scale, views[0], views[1], views[2], views[3], views[4]) else try attend.encode(e, rows, keys, keys, scale, views[0], views[1], views[2], views[3], views[4]); } +/// The rows a layer of window `window` attends: the kept context's last `window` - 1 (all of it for a full layer). +pub fn layerContext(kept: op.Context, window: u32) op.Context { + return .{ .cache = kept.cache, .begin = @max(kept.begin, kept.end -| (@as(u64, window) - 1)), .end = kept.end }; +} +test "a sliding layer attends its own window of a longer kept context, a full layer all of it" { + const kept = op.Context{ .cache = 1, .begin = 0, .end = 10000 }; + try std.testing.expectEqual(@as(u64, 10000 - 4095), layerContext(kept, 4096).begin); + try std.testing.expectEqual(@as(u64, 0), layerContext(kept, 32768).begin); + try std.testing.expectEqual(@as(u64, 7), layerContext(.{ .cache = 1, .begin = 7, .end = 100 }, 4096).begin); +} /// Slots before `trained` cannot see later slots, retaining their trained-block mask. pub fn fillMask(out: []u8, context_rows: u32, queries: u32, window: u32, trained: u32) !void { if (queries == 0 or window == 0 or context_rows >= window or trained == 0) return error.BadDraftContext; diff --git a/zig/src/families/qwen27/dflash/runtime_lattice.zig b/zig/src/families/qwen27/dflash/runtime_lattice.zig index e55d6f82092..46e8143743b 100644 --- a/zig/src/families/qwen27/dflash/runtime_lattice.zig +++ b/zig/src/families/qwen27/dflash/runtime_lattice.zig @@ -10,9 +10,10 @@ fn value(r: @import("runtime_frame.zig").Ref, at: usize) f32 { pub fn read(a: std.mem.Allocator, frame: *const Frame, topk: op.View, hidden: op.View, c: Config, head: op.Head) !op.Lattice { if (!frame.completed) return error.DraftLatticeShape; try topk.check(head.logits.rows, @sizeOf(@import("core").bf16_topk.Row), .u8); - try hidden.check(head.logits.rows, c.rank, .bf16); + // rank 0 (a v1 draft): no selector projection to read, whatever `hidden` holds + if (c.rank > 0) try hidden.check(head.logits.rows, c.rank, .bf16); const picked = try frame.ref(topk); - const projected = try frame.ref(hidden); + const projected = if (c.rank > 0) try frame.ref(hidden) else picked; const mapping = if (head.token_ids) |ids| try frame.ref(ids) else null; const count = @as(usize, head.logits.rows) * c.topk; var out = op.Lattice{ .gpa = a, .depth = head.logits.rows, .topk = c.topk, .rank = c.rank, .candidates = try a.alloc(u32, count), .unary = undefined, .projected = undefined }; diff --git a/zig/src/families/qwen27/dflash/runtime_model.zig b/zig/src/families/qwen27/dflash/runtime_model.zig index 7e17c52792a..85719aa673a 100644 --- a/zig/src/families/qwen27/dflash/runtime_model.zig +++ b/zig/src/families/qwen27/dflash/runtime_model.zig @@ -9,6 +9,8 @@ const Backend = @import("runtime_backend.zig").Backend; const Target = @import("../model.zig").Model; const Session = @import("session.zig").Session; const op = @import("operators.zig"); +const tap_ring = @import("../tap_ring.zig"); +const kv_grow = @import("../kv_grow.zig"); const execution = @import("execution.zig"); const absorb_batch = @import("absorb_batch.zig"); const selector = @import("selector.zig"); @@ -26,12 +28,18 @@ pub const Model = struct { tree_block: u32 = 16, pending: mtl.Buffer, committed_end: u64 = 0, + fuse_out: ?mtl.Buffer = null, // fc's rows before hidden_norm, for the target's taps pass + fuse_rows: u32 = 0, absorb_batch: bool = false, // TF_Q27_DFLASH_ABSORB_BATCH: a shared round's streams absorb in one pass absorb_batches: u64 = 0, // stacked absorb passes absorb_batch_rows: u64 = 0, // rows those passes took absorb_passes_saved: u64 = 0, // per-stream weight passes they replaced pub fn load(a: std.mem.Allocator, io: std.Io, target: *Target, dir: []const u8, mode: op.Mode) !*Model { - return optIn(try loadBound(a, io, backend_mod.Target.qwen(target), dir, mode)); + return loadSpan(a, io, target, dir, mode, 0); + } + /// `history`: positions a v1 drafter keeps for its full layers (the served span); 0 keeps the window. + pub fn loadSpan(a: std.mem.Allocator, io: std.Io, target: *Target, dir: []const u8, mode: op.Mode, history: u32) !*Model { + return optIn(try loadBoundSpan(a, io, backend_mod.Target.qwen(target), dir, mode, history)); } /// The 27B's own switch: a family that shares this drafter through a bound target keeps the per-stream absorb. fn optIn(m: *Model) !*Model { @@ -40,12 +48,16 @@ pub const Model = struct { return m; } pub fn loadBound(a: std.mem.Allocator, io: std.Io, target: backend_mod.Target, dir: []const u8, mode: op.Mode) !*Model { + return loadBoundSpan(a, io, target, dir, mode, 0); + } + fn loadBoundSpan(a: std.mem.Allocator, io: std.Io, target: backend_mod.Target, dir: []const u8, mode: op.Mode, history: u32) !*Model { if (mode == .python_q4g64) return error.DraftPreparationUnqualified; const path = try std.fs.path.join(a, &.{ dir, "config.json" }); defer a.free(path); const text = try std.Io.Dir.cwd().readFileAlloc(io, path, a, .limited(1 << 20)); defer a.free(text); - const c = try cfg.parse(a, text); + var c = try cfg.parse(a, text); + if (c.variant == .v1) c.history = history; try c.bind(target.config.hidden, target.config.vocab, target.config.layers); const shards = try core.checkpoint_host.shardFiles(a, io, dir); defer core.checkpoint_host.freeShardFiles(a, shards); @@ -63,6 +75,8 @@ pub const Model = struct { model.allocator = a; model.tree_block = 16; model.committed_end = 0; + model.fuse_out = null; + model.fuse_rows = 0; model.absorb_batch = false; model.absorb_batches = 0; model.absorb_batch_rows = 0; @@ -78,7 +92,7 @@ pub const Model = struct { errdefer model.graph.deinit(); if (mode == .prepared_q4_reference) try model.backend.prepare(); model.checkpoint.closeFiles(); - model.pending = try target.device.buffer(@as(usize, c.window) * c.tapWidth() * 2, mtl.ResourceOptions.shared | mtl.ResourceOptions.untracked); + model.pending = try target.device.buffer(@as(usize, c.span()) * c.ringWidth() * 2, mtl.ResourceOptions.shared | mtl.ResourceOptions.untracked); errdefer model.pending.deinit(); model.session = try Session.init(c, 1, 0); model.preparation = .{ .mode = mode, .quantization_verified = mode == .prepared_q4_reference, .source_sha256 = if (mode == .prepared_q4_reference) core.affine4.signature() else @splat(0) }; @@ -86,6 +100,7 @@ pub const Model = struct { } pub fn deinit(m: *Model) void { if (m.absorb_batches > 0) std.log.info("qwen27: DFlash2 absorb batches {d}, rows {d}, weight passes saved {d}", .{ m.absorb_batches, m.absorb_batch_rows, m.absorb_passes_saved }); + if (m.fuse_out) |b| b.deinit(); m.graph.deinit(); m.backend.deinit(); m.pending.deinit(); @@ -107,30 +122,49 @@ pub const Model = struct { m.session = try Session.init(m.graph.config, 1, 0); m.committed_end = 0; } + /// The target's taps pass fuses rows for this v1 drafter: fc then hidden_norm on up to `rows` rows a pass. + pub fn fuser(m: *Model, rows: u32) !@import("../taps.zig").Fuser { + if (m.graph.config.variant != .v1 or rows == 0) return error.BadDraftOptions; + if (m.fuse_out) |b| b.deinit(); + m.fuse_out = null; + m.fuse_out = try m.backend.target.device.buffer(@as(usize, rows) * m.graph.config.hidden * 2, opts); + m.fuse_rows = rows; + return .{ .ptr = m, .width = m.graph.config.hidden, .encode = fuseEncode }; + } + fn fuseEncode(ptr: *anyopaque, e: mtl.ComputeEncoder, x: @import("../projection.zig").Ref, y: @import("../projection.zig").Ref, rows: u32) !void { + const m: *Model = @ptrCast(@alignCast(ptr)); + if (rows == 0 or rows > m.fuse_rows or m.backend.failed) return error.BadCommittedTaps; + const c = m.graph.config; + const out = m.fuse_out.?; + try m.backend.encodeLinear(e, m.graph.fusion, m.preparation.mode, .{ .buf = x.buffer, .off = x.offset }, .{ .buf = out }, rows); + e.barrier(); + try m.backend.primitives.norm(e, .{ .buf = out }, try m.backend.weight(m.graph.hidden_norm), .{ .buf = y.buffer, .off = y.offset }, .{ .rows = rows, .heads = 1, .dim = c.hidden, .x_stride = c.hidden, .y_stride = c.hidden, .eps = c.eps }); + e.barrier(); + } pub fn absorb(m: *Model, taps: @import("runtime_backend.zig").Ref, rows: u32) !void { if (m.backend.failed or m.backend.frame.active or m.backend.transaction != null or rows == 0 or rows > 128) return error.BadCommittedTaps; try m.ring().absorb(taps.buf, taps.off, rows); } /// The committed taps the drafter reads, as a ring a lane's state copies. pub fn ring(m: *Model) @import("../tap_ring.zig").Ring { - return .{ .buf = m.pending, .end = &m.committed_end, .window = m.graph.config.window, .stride = @as(usize, m.graph.config.tapWidth()) * 2 }; + return .{ .buf = m.pending, .end = &m.committed_end, .window = m.graph.config.span(), .stride = @as(usize, m.graph.config.ringWidth()) * 2 }; } pub fn flush(m: *Model) !void { if (m.backend.failed or m.backend.frame.active or m.backend.transaction != null or m.committed_end == 0 or m.session.context.end > m.committed_end) return error.BadDraftContext; - const begin = m.committed_end -| (@as(u64, m.graph.config.window) - 1); + const begin = m.committed_end -| (@as(u64, m.graph.config.span()) - 1); if (m.session.context.end < begin) { m.session.context = .{ .cache = 1, .begin = begin, .end = begin }; m.session.ready = false; m.backend.context = m.session.context; } - const stride = @as(usize, m.graph.config.tapWidth()) * 2; + const stride = @as(usize, m.graph.config.ringWidth()) * 2; while (m.session.context.end < m.committed_end) { const first = m.session.context.end; - const slot: u32 = @intCast(first % m.graph.config.window); - const rows: u32 = @intCast(@min(@min(m.committed_end - first, 128), m.graph.config.window - slot)); + const slot: u32 = @intCast(first % m.graph.config.span()); + const rows: u32 = @intCast(@min(@min(m.committed_end - first, 128), m.graph.config.span() - slot)); var positions: [128]u64 = undefined; for (positions[0..rows], 0..) |*position, i| position.* = first + i; - const view = try m.backend.frame.borrow(.{ .buf = m.pending, .off = @as(usize, slot) * stride }, rows, m.graph.config.tapWidth()); + const view = try m.backend.frame.borrow(.{ .buf = m.pending, .off = @as(usize, slot) * stride }, rows, m.graph.config.ringWidth()); try m.session.absorb(m.backend.ops(), &m.graph, m.preparation, .{ .values = view, .positions = positions[0..rows], .layers = m.graph.config.taps, .target_end = first + rows }); } } @@ -206,10 +240,10 @@ pub const Model = struct { defer ops.vtable.release(ops.ptr, frame); var absorbs: [8]?execution.Absorb = @splat(null); var positions: [8][128]u64 = undefined; - const stride = @as(usize, c.tapWidth()) * 2; + const stride = @as(usize, c.ringWidth()) * 2; for (news[0..n], absorbs[0..n], 0..) |f, *a, k| if (f) |x| { for (positions[k][0..x.rows], 0..) |*p, i| p.* = x.first + i; - a.* = .{ .taps = try m.backend.frame.add(.{ .buf = x.ring, .off = @as(usize, x.slot) * stride }, x.rows, c.tapWidth(), c.tapWidth(), .bf16), .positions = positions[k][0..x.rows] }; + a.* = .{ .taps = try m.backend.frame.add(.{ .buf = x.ring, .off = @as(usize, x.slot) * stride }, x.rows, c.ringWidth(), c.ringWidth(), .bf16), .positions = positions[k][0..x.rows] }; }; var spans: [8]absorb_batch.Span = undefined; var stacked_positions: [absorb_batch.max_rows]u64 = undefined; @@ -250,7 +284,7 @@ pub const Model = struct { const plan = absorb_batch.plan(counts[0..news.len], spans) orelse return null; const last = plan[plan.len - 1]; const rows = last.first + last.rows; - const width = m.graph.config.tapWidth(); + const width = m.graph.config.ringWidth(); const stride = @as(usize, width) * 2; const taps = try m.backend.frame.alloc(rows, width, .bf16); const out = try m.backend.frame.ref(taps); @@ -265,7 +299,7 @@ pub const Model = struct { /// A short run of committed taps the session lacks, for a batched frame to absorb (null: none, or flush first). const Fresh = struct { ring: mtl.Buffer, slot: u32, rows: u32, first: u64, next: op.Context }; fn fresh(m: *const Model) ?Fresh { - const window = m.graph.config.window; + const window = m.graph.config.span(); const span = @import("catchup.zig").fresh(m.session.ready, m.session.context.begin, m.session.context.end, m.committed_end, window) orelse return null; return .{ .ring = m.pending, .slot = span.slot, .rows = span.rows, .first = span.first, .next = .{ .cache = m.session.context.cache, .begin = span.begin, .end = m.committed_end } }; } @@ -281,14 +315,14 @@ pub const Model = struct { if (m.committed_end == 0) return error.DraftContextNotReady; const block = @min(m.tree_block, nodes + 1); if (block < 2) return .{ .gpa = m.allocator, .tokens = &.{}, .parents = &.{}, .scores = &.{} }; - const window = m.graph.config.window; + const window = m.graph.config.span(); if (@import("catchup.zig").fresh(m.session.ready, m.session.context.begin, m.session.context.end, m.committed_end, window)) |span| { const rows = span.rows; const slot = span.slot; var positions: [128]u64 = undefined; for (positions[0..rows], 0..) |*position, i| position.* = m.session.context.end + i; - const stride = @as(usize, m.graph.config.tapWidth()) * 2; - const view = try m.backend.frame.borrow(.{ .buf = m.pending, .off = @as(usize, slot) * stride }, rows, m.graph.config.tapWidth()); + const stride = @as(usize, m.graph.config.ringWidth()) * 2; + const view = try m.backend.frame.borrow(.{ .buf = m.pending, .off = @as(usize, slot) * stride }, rows, m.graph.config.ringWidth()); return m.session.absorbTreeBlock(m.allocator, m.backend.ops(), &m.graph, m.preparation, .{ .values = view, .positions = positions[0..rows], .layers = m.graph.config.taps, .target_end = m.session.context.end + rows }, pending, block, options); } try m.flush(); @@ -304,21 +338,69 @@ pub const Context = struct { caches: []Cache, session: Session, context: op.Context = .{ .cache = 1, .begin = 0, .end = 0 }, + device: mtl.Device, + span: u32, // the ring's window + stride: usize, // a ring row's bytes + held: u32, // the ring's rows: the span unless it grows as used + step: ?u32 = null, // a ring that grows as used (TF_Q27_KV_GROW): its first rows and step + settle: ?Settle = null, // the slot's pending reads land before its ring's buffer changes + + /// The runner's wait for a blit still reading the slot (Runner.settleSlot). + pub const Settle = struct { ctx: *anyopaque, slot: u32, run: *const fn (ctx: *anyopaque, slot: u32) void }; - /// `drafting`: the stream drafts its own trees, so it gets K/V caches; else only its ring. + /// `drafting`: the stream drafts its own trees, so it gets K/V caches; its ring grows by `step` (null: the span). pub fn init(a: std.mem.Allocator, m: *const Model, drafting: bool) !*Context { + return initGrow(a, m, drafting, null); + } + + pub fn initGrow(a: std.mem.Allocator, m: *const Model, drafting: bool, step: ?u32) !*Context { const c = m.graph.config; const device = m.backend.target.device; const x = try a.create(Context); errdefer a.destroy(x); - const pending = try device.buffer(@as(usize, c.window) * c.tapWidth() * 2, opts); + const grows = step; // drafter frames wait for their ring reads before closing: a ring grows between them + const held = if (grows) |s| kv_grow.first(s, c.span()) else c.span(); + const pending = try device.buffer(@as(usize, held) * c.ringWidth() * 2, opts); errdefer pending.deinit(); const caches = try backend_mod.newCaches(a, device, c, if (drafting) c.layers else 0); errdefer backend_mod.freeCaches(a, caches); - x.* = .{ .pending = pending, .caches = caches, .session = try Session.init(c, 1, 0) }; + x.* = .{ .pending = pending, .caches = caches, .session = try Session.init(c, 1, 0), .device = device, .span = c.span(), .stride = @as(usize, c.ringWidth()) * 2, .held = held, .step = grows }; x.setResident(m.backend.residency); return x; } + /// The ring's buffer holding `rows` (Ring.Grow): a wider one takes every held row at its place. + fn growRing(ctx: *anyopaque, rows: u32) anyerror!mtl.Buffer { + const x: *Context = @ptrCast(@alignCast(ctx)); + if (rows <= x.held) return x.pending; + const stride = x.stride; + const next = tap_ring.grownRows(x.held, rows, x.step.?, x.span); + const fresh = try x.device.buffer(@as(usize, next) * stride, opts); + if (x.settle) |s| s.run(s.ctx, s.slot); + tap_ring.carry(x.pending, fresh, x.held, stride); + std.log.info("qwen27: slot {d} taps ring grew from {d} to {d} rows", .{ if (x.settle) |h| h.slot else 0, x.held, next }); + x.swapRing(fresh, next); + return fresh; + } + /// The ring back to its first rows once its stream left; nothing reads the old rows once `settle` returns. + fn shrinkRing(x: *Context) !void { + const s = x.step orelse return; + const first = kv_grow.first(s, x.span); + if (x.held <= first) return; + const stride = x.stride; + const fresh = try x.device.buffer(@as(usize, first) * stride, opts); + if (x.settle) |h| h.run(h.ctx, h.slot); + std.log.info("qwen27: slot {d} taps ring gave back {d} to {d} rows", .{ if (x.settle) |h| h.slot else 0, x.held, first }); + x.swapRing(fresh, first); + } + fn swapRing(x: *Context, fresh: mtl.Buffer, rows: u32) void { + if (x.residency) |f| { + f.leave(f.ctx, x.pending); + f.join(f.ctx, fresh); + } + x.pending.deinit(); + x.pending = fresh; + x.held = rows; + } pub fn setResident(x: *Context, hook: ?mtl.ResidencySet.Follow) void { if (x.residency) |f| x.apply(f, false); x.residency = hook; @@ -336,13 +418,14 @@ pub const Context = struct { } /// Empty, as Model.reset leaves the model's own. pub fn reset(x: *Context, c: cfg.Config) !void { + try x.shrinkRing(); x.committed_end = 0; x.session = try Session.init(c, 1, 0); x.context = .{ .cache = 1, .begin = 0, .end = 0 }; } /// Its taps ring, where the lane backend absorbs the stream's kept rows while it is parked. pub fn ring(x: *Context, c: cfg.Config) @import("../tap_ring.zig").Ring { - return .{ .buf = x.pending, .end = &x.committed_end, .window = c.window, .stride = @as(usize, c.tapWidth()) * 2 }; + return .{ .buf = x.pending, .end = &x.committed_end, .window = c.span(), .stride = @as(usize, c.ringWidth()) * 2, .grow = if (x.step != null) .{ .ctx = x, .run = growRing } else null }; } /// Its buffers, for a residency set. pub fn buffers(x: *const Context, list: *std.ArrayList(mtl.Buffer), a: std.mem.Allocator) !void { diff --git a/zig/src/families/qwen27/dflash/selector.zig b/zig/src/families/qwen27/dflash/selector.zig index c15dfb19ab3..f6e0e9aaf1b 100644 --- a/zig/src/families/qwen27/dflash/selector.zig +++ b/zig/src/families/qwen27/dflash/selector.zig @@ -84,7 +84,8 @@ fn expand(g: *const weights.Graph, lattice: op.Lattice, options: Options, first: } pub fn propose(gpa: std.mem.Allocator, g: *const weights.Graph, lattice: op.Lattice, anchor: u32, first_position: u64, options: Options) !Tree { try g.config.check(); - for ([_]weights.Tensor{ g.predecessor, g.successor }) |t| if (t.dtype != .bf16 or t.rank != 2 or t.shape[0] != g.config.vocab or t.shape[1] != g.config.rank) return error.DraftCodebookShape; + // a v1 draft has no codebooks (rank 0): its edges score nothing and its tree follows each depth's marginals + if (g.config.rank > 0) for ([_]weights.Tensor{ g.predecessor, g.successor }) |t| if (t.dtype != .bf16 or t.rank != 2 or t.shape[0] != g.config.vocab or t.shape[1] != g.config.rank) return error.DraftCodebookShape; try lattice.check(g.config); if (anchor >= g.config.vocab or options.nodes > 63 or options.children == 0 or options.children > 16 or lattice.topk > 16 or !std.math.isFinite(options.tau) or options.tau <= 0 or !std.math.isFinite(options.edge) or !std.math.isFinite(options.noise_weight) or !std.math.isFinite(options.temperature) or options.temperature <= 0) return error.BadDraftSelector; if (!std.math.isFinite(options.overhead_ms) or options.overhead_ms < 0) return error.BadDraftCosts; diff --git a/zig/src/families/qwen27/dflash/session.zig b/zig/src/families/qwen27/dflash/session.zig index 28199fa7c0d..8c35fb4f46f 100644 --- a/zig/src/families/qwen27/dflash/session.zig +++ b/zig/src/families/qwen27/dflash/session.zig @@ -17,11 +17,11 @@ pub const Session = struct { } pub fn admit(s: Session, batch: Batch) !op.Context { if (!std.mem.eql(u32, batch.layers[0..s.config.tap_count], s.config.tapIds()) or batch.positions.len == 0) return error.BadCommittedTaps; - try batch.values.check(@intCast(batch.positions.len), s.config.tapWidth(), .bf16); + try batch.values.check(@intCast(batch.positions.len), s.config.ringWidth(), .bf16); const end = try std.math.add(u64, s.context.end, batch.positions.len); if (end != batch.target_end) return error.BadCommittedTaps; for (batch.positions, 0..) |position, i| if (position != s.context.end + i or position >= batch.target_end) return error.BadCommittedTaps; - const begin = @max(s.context.begin, end -| (@as(u64, s.config.window) - 1)); + const begin = @max(s.context.begin, end -| (@as(u64, s.config.span()) - 1)); return .{ .cache = s.context.cache, .begin = begin, .end = end }; } pub fn absorb(s: *Session, ops: op.Ops, graph: *const weights.Graph, preparation: op.Preparation, batch: Batch) !void { diff --git a/zig/src/families/qwen27/dflash/weights.zig b/zig/src/families/qwen27/dflash/weights.zig index 570230cce5d..de2931eee68 100644 --- a/zig/src/families/qwen27/dflash/weights.zig +++ b/zig/src/families/qwen27/dflash/weights.zig @@ -34,6 +34,11 @@ pub const Graph = struct { }; const suffixes = [_][]const u8{ "input_layernorm.weight", "post_attention_layernorm.weight", "self_attn.q_proj.weight", "self_attn.k_proj.weight", "self_attn.v_proj.weight", "self_attn.o_proj.weight", "self_attn.q_norm.weight", "self_attn.k_norm.weight", "mlp.gate_proj.weight", "mlp.up_proj.weight", "mlp.down_proj.weight", "attention_conv.kernel_projection.weight", "attention_conv.base_kernel", "mlp_conv.kernel_projection.weight", "mlp_conv.base_kernel" }; const globals = [_][]const u8{ "fc.weight", "hidden_norm.weight", "norm.weight", "candidate_selector.hidden_projection.weight", "candidate_selector.predecessor_codebook", "candidate_selector.successor_codebook" }; +/// A DFlash v1 draft's own tensors: the first eleven suffixes a layer, and fc, hidden_norm and norm. +const v1_suffixes = suffixes[0..11]; +const v1_globals = globals[0..3]; +/// A tensor a v1 draft does not have (its conv and selector slots): no bytes, never bound to a kernel. +pub const absent = Tensor{ .dtype = .bf16, .rank = 0, .shape = @splat(1), .bytes = &.{} }; pub fn names(gpa: std.mem.Allocator, c: Config) ![][]const u8 { const result = try gpa.alloc([]const u8, c.tensorCount()); var made: usize = 0; @@ -41,11 +46,12 @@ pub fn names(gpa: std.mem.Allocator, c: Config) ![][]const u8 { for (result[0..made]) |name| gpa.free(name); gpa.free(result); } - for (globals) |name| { + const v1 = c.variant == .v1; + for (if (v1) v1_globals else &globals) |name| { result[made] = try gpa.dupe(u8, name); made += 1; } - for (0..c.layers) |i| for (suffixes) |suffix| { + for (0..c.layers) |i| for (if (v1) v1_suffixes else &suffixes) |suffix| { result[made] = try std.fmt.allocPrint(gpa, "layers.{d}.{s}", .{ i, suffix }); made += 1; }; @@ -99,6 +105,7 @@ pub fn load(gpa: std.mem.Allocator, source: Inventory, c: Config, embed: ck.Line const src = source.source; const layers = try gpa.alloc(Layer, c.layers); errdefer gpa.free(layers); + if (c.variant == .v1) return loadV1(gpa, src, c, layers, embed); for (layers, 0..) |*l, i| l.* = .{ .input_norm = try layerTensor(src, i, "input_layernorm.weight", &.{c.hidden}), .post_norm = try layerTensor(src, i, "post_attention_layernorm.weight", &.{c.hidden}), @@ -110,6 +117,37 @@ pub fn load(gpa: std.mem.Allocator, source: Inventory, c: Config, embed: ck.Line return .{ .gpa = gpa, .config = c, .layers = layers, .fusion = try get(src, "fc.weight", &.{ c.hidden, c.tapWidth() }), .hidden_norm = try get(src, "hidden_norm.weight", &.{c.hidden}), .norm = try get(src, "norm.weight", &.{c.hidden}), .hidden_projection = try get(src, "candidate_selector.hidden_projection.weight", &.{ c.rank, c.hidden }), .predecessor = try get(src, "candidate_selector.predecessor_codebook", &.{ c.vocab, c.rank }), .successor = try get(src, "candidate_selector.successor_codebook", &.{ c.vocab, c.rank }), .embed = embed }; } +/// v1 layers: the qwen3 body alone; the conv and selector slots stay `absent`. +fn loadV1(gpa: std.mem.Allocator, src: ck.Source, c: Config, layers: []Layer, embed: ck.Linear) !Graph { + const none = Conv{ .projection = absent, .base = absent }; + for (layers, 0..) |*l, i| l.* = .{ + .input_norm = try layerTensor(src, i, "input_layernorm.weight", &.{c.hidden}), + .post_norm = try layerTensor(src, i, "post_attention_layernorm.weight", &.{c.hidden}), + .attention = .{ .q = try layerTensor(src, i, "self_attn.q_proj.weight", &.{ c.qWidth(), c.hidden }), .k = try layerTensor(src, i, "self_attn.k_proj.weight", &.{ c.kvWidth(), c.hidden }), .v = try layerTensor(src, i, "self_attn.v_proj.weight", &.{ c.kvWidth(), c.hidden }), .o = try layerTensor(src, i, "self_attn.o_proj.weight", &.{ c.hidden, c.qWidth() }), .q_norm = try layerTensor(src, i, "self_attn.q_norm.weight", &.{c.head_dim}), .k_norm = try layerTensor(src, i, "self_attn.k_norm.weight", &.{c.head_dim}) }, + .mlp = .{ .gate = try layerTensor(src, i, "mlp.gate_proj.weight", &.{ c.intermediate, c.hidden }), .up = try layerTensor(src, i, "mlp.up_proj.weight", &.{ c.intermediate, c.hidden }), .down = try layerTensor(src, i, "mlp.down_proj.weight", &.{ c.hidden, c.intermediate }) }, + .attention_conv = none, + .mlp_conv = none, + }; + return .{ .gpa = gpa, .config = c, .layers = layers, .fusion = try get(src, "fc.weight", &.{ c.hidden, c.tapWidth() }), .hidden_norm = try get(src, "hidden_norm.weight", &.{c.hidden}), .norm = try get(src, "norm.weight", &.{c.hidden}), .hidden_projection = absent, .predecessor = absent, .successor = absent, .embed = embed }; +} + +test "a DFlash v1 inventory is its sixty-nine qwen3 names, no conv or selector" { + const a = std.testing.allocator; + var c = Config{ .variant = .v1, .hidden = 4096, .intermediate = 12288, .layers = 6, .target_layers = 32, .block = 16, .mask = 248077, .window = 4096, .group = 0, .conv = 0, .rank = 0, .topk = 16, .taps = .{ 1, 5, 9, 13, 17, 21, 25, 29 }, .tap_count = 8 }; + c.full[5] = true; + try c.check(); + const list = try names(a, c); + defer freeNames(a, list); + try inventory(a, list, c); + try std.testing.expectEqual(@as(usize, 69), list.len); + for (list) |name| { + try std.testing.expect(std.mem.indexOf(u8, name, "conv") == null); + try std.testing.expect(std.mem.indexOf(u8, name, "selector") == null); + } + try std.testing.expectEqualStrings("fc.weight", list[0]); + try std.testing.expectEqualStrings("layers.5.mlp.down_proj.weight", list[list.len - 1]); +} + test "inventory is81exact names including unsuffixed BF16codebooks" { const a = std.testing.allocator; const list = try names(a, .{}); diff --git a/zig/src/families/qwen27/forward.zig b/zig/src/families/qwen27/forward.zig index 2b56a60697d..896ca2456e8 100644 --- a/zig/src/families/qwen27/forward.zig +++ b/zig/src/families/qwen27/forward.zig @@ -17,6 +17,8 @@ pub const Mixer = struct { /// A pass that keeps no row and has no other reader of the last layer: that layer writes keys and values only. keys: ?*const fn (*anyopaque, mtl.ComputeEncoder, usize, wts.Attention, *Frame, u32) anyerror!void = null, }; +/// Staged references (tf-qwen27-run only): the stream after each stage, the final norm and the head's rows. +const stage_planes = @import("stage_planes.zig"); /// One exchange: `x` its index, `ref` this rank's `width` columns of the seam in the window's slot for x. pub const Seam = struct { x: u32, ref: Ref }; @@ -101,6 +103,7 @@ pub const Stages = struct { m.glue.imageRows(lane.enc, s.hidden, rows, m.frame.get(.takes), @intCast(m.config.hidden), s.rows); lane.enc.barrier(); } + if (stage_planes.on) try stage_planes.record(s.model.glue, lane.enc, .embed, s.hidden, s.rows); } pub fn wait(_: *Stages, _: usize) @import("core").segments.Wait { return .mixer; @@ -117,6 +120,7 @@ pub const Stages = struct { if (s.pending != null) { std.mem.swap(Ref, &s.hidden, &s.residual); if (s.hooks.tap) |tap| try tap(s.hooks.ptr, e, index - 1, s.hidden, s.rows); + if (stage_planes.on) try stage_planes.record(s.model.glue, e, .{ .block = index - 1 }, s.hidden, s.rows); } } /// The last layer of a pass whose other rows nothing reads: q, attention, o and the MLP have no reader. @@ -173,6 +177,7 @@ pub const Stages = struct { try m.kernels.norm(e, t.at(s.hidden, h), t.at(f.get(.output), h), wts.ref(layer.post_norm), f.get(.eps), t.dims, t.at(s.residual, h), t.at(f.get(.input), h), t.sums(f.get(.sums)), h, t.n); e.barrier(); std.mem.swap(Ref, &s.hidden, &s.residual); + if (stage_planes.on) try stage_planes.record(s.model.glue, e, .{ .mixer = index }, s.hidden, s.rows); if (layer.moe) |*mo| if (!m.moe.?.sorted(mo, m.kernels.prompt)) { // decode rows: the routed block runs the shared expert as one more slot of the experts' kernel try m.moe.?.block(lane.enc, m.config, mo, f, s.rows, m.kernels.prompt); @@ -264,6 +269,11 @@ pub const Stages = struct { e.barrier(); std.mem.swap(Ref, &s.hidden, &s.residual); if (s.hooks.tap) |tap| try tap(s.hooks.ptr, e, m.config.layers - 1, s.hidden, s.rows); + if (stage_planes.on) { + // the last block is the residual stream; final is the normed rows the head reads (f.input) + try stage_planes.record(m.glue, e, .{ .block = m.config.layers - 1 }, s.hidden, s.rows); + try stage_planes.record(m.glue, e, .final, f.get(.input), s.rows); + } if (s.head == .all and s.rows > @import("gpu_frame.zig").logit_rows) return error.BadFrameRows; if (s.head != .none) { var input = f.get(.input); @@ -273,6 +283,10 @@ pub const Stages = struct { head_sums.ref.offset += @as(usize, s.rows - 1) * 4; } try m.kernels.quant(e, m.weights.head, input, head_sums, f.get(.dims), s.logits orelse f.get(.logits), if (s.head == .last) 1 else s.rows); + if (stage_planes.on) if (stage_planes.active != null) { + e.barrier(); + try stage_planes.record(m.glue, e, .logits, f.get(.logits), if (s.head == .last) 1 else s.rows); + }; } e.barrier(); if (s.reduce) |r| { diff --git a/zig/src/families/qwen27/gpu_weights.zig b/zig/src/families/qwen27/gpu_weights.zig index 045ab6b0312..80b4ce19709 100644 --- a/zig/src/families/qwen27/gpu_weights.zig +++ b/zig/src/families/qwen27/gpu_weights.zig @@ -396,7 +396,11 @@ pub fn load(allocator: std.mem.Allocator, device: mtl.Device, checkpoint: *const for (layers, 0..) |*l, i| l.* = try b.layer(s, i); const embed = try b.quant("model.embed_tokens", g.vocab, g.hidden, ws.embed); const norm = try b.tensor("model.norm.weight", .bf16, &.{c.hidden}); - const head = try b.linear(&.{.{ .module = "lm_head", .n = g.vocab, .w = ws.head, .span = s.vocabRows() }}, g.hidden); + const stored_head = try std.mem.concat(allocator, u8, &.{ prefix, "lm_head.weight" }); + defer allocator.free(stored_head); + // a tied head repacks the embedding's bytes into its own lane buffers; the embedding keeps its file layout + const head_module = try @import("tied_head.zig").module(g.tied_head, checkpoint.has(stored_head)); + const head = try b.linear(&.{.{ .module = head_module, .n = g.vocab, .w = ws.head, .span = s.vocabRows() }}, g.hidden); if (device.tensorUnits()) try laneOrder(allocator, device, layers, head); return .{ .allocator = allocator, .layers = layers, .embed = embed, .norm = norm, .head = head, .owned = owned, .runs = runs }; } @@ -405,6 +409,7 @@ pub fn load(allocator: std.mem.Allocator, device: mtl.Device, checkpoint: *const /// one rank, 4-bit g64. pub fn loadMtp(w: *Weights, device: mtl.Device, checkpoint: *const cp.Checkpoint, s: *const cfg.Shard) !void { if (s.ranks != 1) return error.MtpNeedsOneRank; + if (s.global.tied_head) return error.MtpNeedsUntiedHead; const c = s.local; const prefix: []const u8 = if (checkpoint.has("language_model.mtp.norm.weight")) "language_model." else if (checkpoint.has("mtp.norm.weight")) "" else return error.MissingMtpHead; var stage = cp.Stage{ .device = device }; @@ -448,10 +453,11 @@ fn layerJobs(a: std.mem.Allocator, jobs: *std.ArrayList(lane.Order), l: Layer) ! for (list) |p| try regJobs(a, jobs, p); } -/// Only 4-bit g64 matrices take the reg kernel; other widths keep lane_projection.weight_layout. +/// 4-, 5-, and 6-bit g64 matrices take the reg kernel; other widths keep lane_projection.weight_layout. fn regJobs(a: std.mem.Allocator, jobs: *std.ArrayList(lane.Order), p: Linear) std.mem.Allocator.Error!void { for (p.runs) |r| try regJobs(a, jobs, r.linear); - if (p.runs.len == 0 and p.bits == 4 and p.group == 64 and p.n % 32 == 0) try jobs.append(a, .{ .w = .{ .buf = p.words.buffer, .off = p.words.offset }, .n = p.n, .k = p.k }); + const reg_bits = p.bits == 4 or p.bits == 5 or p.bits == 6; + if (p.runs.len == 0 and reg_bits and p.group == 64 and p.n % 32 == 0) try jobs.append(a, .{ .w = .{ .buf = p.words.buffer, .off = p.words.offset }, .n = p.n, .k = p.k, .bits = p.bits }); } /// A borrowed quantized tensor as the row kernels' matrix. diff --git a/zig/src/families/qwen27/kv_grow.zig b/zig/src/families/qwen27/kv_grow.zig new file mode 100644 index 00000000000..dd69edc4178 --- /dev/null +++ b/zig/src/families/qwen27/kv_grow.zig @@ -0,0 +1,46 @@ +//! Grow-as-used K/V (opt-in): a slot holds the rows its stream reached, not the whole context. +const std = @import("std"); + +/// One blit of a K/V buffer's head into a wider buffer, in bytes. +pub const Move = struct { from: usize, to: usize, len: usize }; + +/// TF_Q27_KV_GROW: the rows a slot starts with and grows by (a multiple of 16); unset or 0 keeps every slot full. +pub fn step(text: ?[]const u8) !?u32 { + const value = text orelse return null; + const n = std.fmt.parseInt(u32, value, 10) catch return error.BadKvGrowStep; + if (n == 0) return null; + if (n % 16 != 0) return error.BadKvGrowStep; + return n; +} + +/// A slot's first rows: one step, at most the context. +pub fn first(s: u32, context: u32) u32 { + return @min(s, context); +} + +/// Rows for `need`: the need rounded up to the step, or a quarter more than `held`, at most the context. +pub fn rows(held: u32, need: u32, s: u32, context: u32) u32 { + if (need <= held) return held; + const rounded = (@as(u64, need) + s - 1) / s * s; + const quarter = @as(u64, held) + held / 4; + return @intCast(@min(@max(rounded, quarter), context)); +} + +/// An empty slot's rows for a prompt of `need`: rounded up to the step, at least one step, at most the context. +pub fn admitted(need: u32, s: u32, context: u32) u32 { + const rounded = (@as(u64, need) + s - 1) / s * s; + return @intCast(@min(@max(rounded, s), context)); +} + +/// Head h of a [heads][old][dim] bf16 buffer to its place in a [heads][new][dim] one. +pub fn moves(out: []Move, heads: usize, dim: usize, old: u32, new: u32) []Move { + std.debug.assert(out.len >= heads and new >= old); + const row = dim * @sizeOf(u16); + for (out[0..heads], 0..) |*m, h| m.* = .{ .from = h * old * row, .to = h * new * row, .len = @as(usize, old) * row }; + return out[0..heads]; +} + +/// A slot's K and V bytes across `layers` attention layers at `r` rows of `kv` bf16 values. +pub fn slotBytes(layers: usize, kv: usize, r: u32) usize { + return layers * 2 * @as(usize, r) * kv * @sizeOf(u16); +} diff --git a/zig/src/families/qwen27/kv_slots.zig b/zig/src/families/qwen27/kv_slots.zig new file mode 100644 index 00000000000..7ab70ddc1b2 --- /dev/null +++ b/zig/src/families/qwen27/kv_slots.zig @@ -0,0 +1,167 @@ +//! Grow-as-used K/V for a runner's slots (TF_Q27_KV_GROW): grow before rows are written, give back once a slot is free. +const std = @import("std"); +const mtl = @import("metal"); +const Model = @import("model.zig").Model; +const Runner = @import("decode_round.zig").Runner; +const gpuFailed = @import("decode_round.zig").gpuFailed; +const attn = @import("attention.zig"); +const kv_grow = @import("kv_grow.zig"); + +/// Slot `slot` holds `need` K/V rows: layer by layer, a wider pair takes every old byte at its place (waited blit). +pub fn reserve(r: *Runner, slot: u32, need: u32) !void { + const s = r.kv_step orelse return; + if (slot >= r.ready) return error.SlotNotReady; + const held = r.heldRows(slot); + if (need <= held) return; + if (need > r.capacity) return error.AttentionCapacity; + r.settleSlot(slot); + if (r.failed or r.active != null) return error.RoundNotReady; + const rows = kv_grow.rows(held, need, s, r.capacity); + const layers = r.caches.len / r.slots; + const bytes = @as(usize, rows) * r.model.config.kvDim() * 2; + // one layer at a time, so growth holds at most one layer's old pair beside the new rows + for (0..layers) |layer| { + const at = layer * r.slots + slot; + const c = r.caches[at]; + if (c.capacity >= rows) continue; // grown before an earlier failure + if (c.keys.offset != 0 or c.values.offset != 0 or c.key_stride != 0 or c.value_stride != 0) return error.KvGrowLayout; + var fresh: [2]mtl.Buffer = undefined; + fresh[0] = try r.model.device.buffer(bytes, mtl.ResourceOptions.shared | mtl.ResourceOptions.untracked); + errdefer fresh[0].deinit(); + fresh[1] = try r.model.device.buffer(bytes, mtl.ResourceOptions.shared | mtl.ResourceOptions.untracked); + errdefer fresh[1].deinit(); + const old = [2]mtl.Buffer{ c.keys.buffer, c.values.buffer }; + { + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const cb = r.model.queue.commandBuffer(); + const e = cb.blit(); + var moves: [attn.planning.max_streams]kv_grow.Move = undefined; + for (old, fresh) |from, to| { + for (kv_grow.moves(&moves, r.model.config.kv_heads, r.model.config.head_dim, c.capacity, rows)) |mv| e.copy(from, mv.from, to, mv.to, mv.len); + } + e.end(); + cb.commit(); + cb.wait(); + if (gpuFailed(cb, "a slot's K/V growth")) return error.RoundGpuFailure; + } + swapPair(r, at, fresh, rows); + } + std.log.info("qwen27: slot {d} K/V grew from {d} to {d} rows ({d} of {d} MiB held)", .{ slot, held, rows, kv_grow.slotBytes(layers, r.model.config.kvDim(), rows) >> 20, r.slotBytes() >> 20 }); +} + +/// Slot `slot` back to its first rows once no stream holds it and no blit reads it: its rows are gone (offset 0). +pub fn release(r: *Runner, slot: u32) !void { + const s = r.kv_step orelse return; + return refit(r, slot, kv_grow.first(s, r.capacity)); +} + +/// An emptied slot takes the rows a prompt of `need` tokens fills, at once and without a copy (a fresh pass). +pub fn admit(r: *Runner, slot: u32, need: u32) !void { + const s = r.kv_step orelse return; + if (need > r.capacity) return error.AttentionCapacity; + return refit(r, slot, kv_grow.admitted(need, s, r.capacity)); +} + +/// Every layer of empty slot `slot` holds exactly `first` rows: new buffers where it holds any other count. +fn refit(r: *Runner, slot: u32, first: u32) !void { + if (slot >= r.ready) return; + var held: u32 = 0; + for (0..r.caches.len / r.slots) |layer| held = @max(held, r.caches[layer * r.slots + slot].capacity); + if (held == first and r.heldRows(slot) == first) return; + r.settleSlot(slot); + if (r.failed) return error.RoundNotReady; + const bytes = @as(usize, first) * r.model.config.kvDim() * 2; + for (0..r.caches.len / r.slots) |layer| { + const at = layer * r.slots + slot; + const c = r.caches[at]; + if (c.capacity == first) continue; + var fresh: [2]mtl.Buffer = undefined; + fresh[0] = try r.model.device.buffer(bytes, mtl.ResourceOptions.shared | mtl.ResourceOptions.untracked); + errdefer fresh[0].deinit(); + fresh[1] = try r.model.device.buffer(bytes, mtl.ResourceOptions.shared | mtl.ResourceOptions.untracked); + swapPair(r, at, fresh, first); + } + r.offsets[slot] = 0; + std.log.info("qwen27: slot {d} K/V refit from {d} to {d} rows", .{ slot, held, first }); +} + +/// Cache `at` takes `fresh` (`rows` each); its old pair leaves the residency set and is freed. +fn swapPair(r: *Runner, at: usize, fresh: [2]mtl.Buffer, rows: u32) void { + const c = r.caches[at]; + for ([_]mtl.Buffer{ c.keys.buffer, c.values.buffer }, fresh) |from, to| { + for (r.owned.items) |*b| if (b.id == from.id) { + b.* = to; + }; + if (r.residency) |f| { + f.leave(f.ctx, from); + f.join(f.ctx, to); + } + from.deinit(); + } + r.caches[at] = .{ .keys = .{ .buffer = fresh[0] }, .values = .{ .buffer = fresh[1] }, .capacity = rows }; + if (r.grown) |g| g.added(g.ctx, &fresh); +} + +/// One slot's K/V rows across the attention layers. +pub fn slotBytes(r: *const Runner) usize { + return r.caches.len / r.slots * 2 * @as(usize, r.capacity) * r.model.config.kvDim() * 2; +} + +/// Slot `slot`'s K/V rows (the next unready slot, as free slots are taken lowest first); its new buffers. +pub fn ensure(r: *Runner, slot: u32) ![]const mtl.Buffer { + if (slot < r.ready) return &.{}; + if (slot != r.ready) return error.SlotOutOfOrder; + const first = r.owned.items.len; + errdefer { + for (r.owned.items[first..]) |b| b.deinit(); + r.owned.shrinkRetainingCapacity(first); + } + const layers = r.caches.len / r.slots; + const rows = if (r.kv_step) |s| kv_grow.first(s, r.capacity) else r.capacity; + for (0..layers) |layer| r.caches[layer * r.slots + slot] = try slotCache(r.allocator, r.model, &r.owned, rows); + r.ready += 1; + if (r.residency) |f| for (r.owned.items[first..]) |b| f.join(f.ctx, b); + return r.owned.items[first..]; +} + +/// The K/V rows slot `slot` holds now: the fewest any attention layer holds. +pub fn heldRows(r: *const Runner, slot: u32) u32 { + var rows: u32 = std.math.maxInt(u32); + for (0..r.caches.len / r.slots) |layer| rows = @min(rows, r.caches[layer * r.slots + slot].capacity); + return rows; +} + +/// Whether a blit still reads slot `slot` (without waiting for it). +pub fn busy(r: *const Runner, slot: u32) bool { + const cb = r.reading[slot] orelse return false; + return switch (cb.status()) { + .completed, .@"error" => false, + else => true, + }; +} + +/// The K/V buffers of the ready slots (for a residency set). +pub fn readyBuffers(r: *const Runner, a: std.mem.Allocator, out: *std.ArrayList(mtl.Buffer)) !void { + if (r.kv) |k| return out.appendSlice(a, &.{ k.arena, k.tables }); + for (0..r.caches.len / r.slots) |layer| for (0..r.ready) |slot| { + const c = r.caches[layer * r.slots + slot]; + try out.appendSlice(a, &.{ c.keys.buffer, c.values.buffer }); + }; +} + +pub fn slotCache(a: std.mem.Allocator, m: *Model, owned: *std.ArrayList(mtl.Buffer), capacity: u32) !attn.Cache { + const bytes = @as(usize, capacity) * m.config.kvDim() * 2; + const key = try allocation(a, m.device, owned, bytes); + const value = try allocation(a, m.device, owned, bytes); + return .{ .keys = .{ .buffer = key }, .values = .{ .buffer = value }, .capacity = capacity }; +} + +fn allocation(a: std.mem.Allocator, device: mtl.Device, owned: *std.ArrayList(mtl.Buffer), bytes: usize) !mtl.Buffer { + const b = try device.buffer(bytes, mtl.ResourceOptions.shared | mtl.ResourceOptions.untracked); + owned.append(a, b) catch |err| { + b.deinit(); + return err; + }; + return b; +} diff --git a/zig/src/families/qwen27/model.zig b/zig/src/families/qwen27/model.zig index 8fc0bfbc810..d1d2142b88c 100644 --- a/zig/src/families/qwen27/model.zig +++ b/zig/src/families/qwen27/model.zig @@ -93,11 +93,20 @@ pub const Model = struct { defer a.free(path); const text = try std.Io.Dir.cwd().readFileAlloc(io, path, a, .limited(16 << 20)); defer a.free(text); + const gen_path = try std.fs.path.join(a, &.{ dir, "generation_config.json" }); + defer a.free(gen_path); + // generation_config.json beside config.json: a missing file is none, any other read failure is the loader's + const generation = std.Io.Dir.cwd().readFileAlloc(io, gen_path, a, .limited(1 << 20)) catch |e| switch (e) { + error.FileNotFound => null, + else => return e, + }; + defer if (generation) |g| a.free(g); var problem: cfg.Problem = .{}; - const c = cfg.parseWhy(a, text, null, &problem) catch |e| { + const c = parseServed(a, text, generation, &problem) catch |e| { if (problem.len != 0) std.log.err("{s}: {s}", .{ path, problem.text() }); return e; }; + if (c.tied_head and ranks != 1) return error.TiedHeadNeedsOneRank; var local = c; const shard = if (ranks == 1) cfg.Shard{ .rank = 0, .ranks = 1, .global = c, .local = local } else try cfg.split(&local, rank, ranks, mode); try supported(shard.global); @@ -253,6 +262,11 @@ const sizes = [_]Size{ .{ .hidden = 4096, .intermediate = 12288, .layers = 32, .heads = 16, .v_heads = 32 }, }; +/// The served config: a dense tied head is admitted only under TF_QWEN27_TIED_HEAD=1. +pub fn parseServed(a: std.mem.Allocator, text: []const u8, generation: ?[]const u8, problem: *cfg.Problem) !cfg.Config { + return cfg.parseTied(a, text, generation, problem, try platform.environment.read(bool, @import("tied_head.zig").flag, false)); +} + fn qualifiedSize(c: cfg.Config) bool { for (sizes) |z| if (c.hidden == z.hidden and c.intermediate == z.intermediate and c.layers == z.layers and c.heads == z.heads and c.v_heads == z.v_heads) return true; return false; @@ -263,14 +277,31 @@ pub fn supported(c: cfg.Config) !void { const dense = qualifiedSize(c) and c.kv_heads == 4 and c.k_heads == 16 and !c.moe(); // Ornith-1.5-122B: 256 experts of 1,024 and a shared expert of 1,024 over 3,072, 32 heads over 2 of 256 const routed = c.hidden == 3072 and c.intermediate == 1024 and c.layers == 48 and c.heads == 32 and c.kv_heads == 2 and c.k_heads == 16 and c.v_heads == 64 and c.experts == 256 and c.top_k == 8 and c.moe_intermediate == 1024; - if (!(dense or routed) or c.vocab != 248320) return error.UnqualifiedQwenShape; + if (!(dense or routed or a3b(c)) or c.vocab != 248320) return error.UnqualifiedQwenShape; try @import("geometry.zig").supported(c); } +/// Qwen3.6-35B-A3B: 256 experts of 512 and a shared expert of 512 over 2,048, 16 heads over 2 of 256 (text only). +pub fn a3b(c: cfg.Config) bool { + return c.hidden == 2048 and c.intermediate == 512 and c.layers == 40 and c.heads == 16 and c.kv_heads == 2 and c.k_heads == 16 and c.v_heads == 32 and c.experts == 256 and c.top_k == 8 and c.moe_intermediate == 512; +} + fn qualifiedGeneration(generation: u32) bool { return generation >= 13 and generation <= 18; } +test "the qualified shapes: the dense 27B, Ornith-1.5-122B and Qwen3.6-35B-A3B; a 35B of other widths is refused" { + var c = try cfg.parse(std.testing.allocator, @import("config_test.zig").a3b_json, null); + try supported(c); + try std.testing.expect(a3b(c)); // --vision refuses it by this + c.moe_intermediate = 1024; + try std.testing.expect(!a3b(c)); + try std.testing.expectError(error.UnqualifiedQwenShape, supported(c)); + c.moe_intermediate = 512; + c.top_k = 10; + try std.testing.expectError(error.UnqualifiedQwenShape, supported(c)); +} + test "unknown and older GPU generations refuse before any weight load" { try std.testing.expect(qualifiedGeneration(13)); try std.testing.expect(qualifiedGeneration(15)); diff --git a/zig/src/families/qwen27/mtp.zig b/zig/src/families/qwen27/mtp.zig index 093b82eb455..1f3e48defe2 100644 --- a/zig/src/families/qwen27/mtp.zig +++ b/zig/src/families/qwen27/mtp.zig @@ -37,7 +37,7 @@ pub const Scratch = struct { }; /// A logits row's pick and its probability under the head's softmax. -pub const Pick = struct { token: u32, chance: f32 }; +pub const Pick = @import("mtp_pick.zig").Pick; pub fn pick(values: []const u16) !Pick { const token = try @import("session.zig").argmax(values); const top: f32 = @bitCast(@as(u32, values[token]) << 16); @@ -75,6 +75,42 @@ pub fn encode(m: *Model, sc: *const Scratch, e: *mtl.ComputeEncoder, hooks: forw /// One MTP head pass on `r` (`round`: its cache rows and positions); a round left to keep reads nothing it writes. pub fn pass(r: *Runner, round: *const Round, sc: *const Scratch, hidden: Ref, head: forward.Head) !Ref { + return passAround(r, round, sc, hidden, head, Plain{}); +} + +const Plain = struct { + pub fn before(_: Plain, _: mtl.ComputeEncoder) !void {} + pub fn after(_: Plain, _: mtl.ComputeEncoder, _: Ref) !void {} +}; + +fn Steps(Around: type) type { + return struct { + r: *Runner, + sc: *const Scratch, + e: *mtl.ComputeEncoder, + cb: mtl.CommandBuffer, + hidden: Ref, + rows: u32, + mode: forward.Head, + around: Around, + pub fn before(s: *@This()) !void { + try s.around.before(s.e.*); + } + pub fn head(s: *@This()) !Ref { + return encode(s.r.model, s.sc, s.e, .{ .ptr = s.r, .gdn = Runner.gdnForward, .attention = Runner.attentionForward }, s.hidden, s.rows, s.mode); + } + pub fn after(s: *@This(), out: Ref) !void { + try s.around.after(s.e.*, out); + } + pub fn commit(s: *@This()) !void { + s.e.end(); + s.cb.commit(); + } + }; +} + +/// `pass` with `around.before` and `around.after` encoded on its one command buffer, before and after the head. +pub fn passAround(r: *Runner, round: *const Round, sc: *const Scratch, hidden: Ref, head: forward.Head, around: anytype) !Ref { if (r.failed or r.model.weights.mtp == null or round.ids.len > r.model.frame.capacity) return error.RoundNotReady; var attention_plan = try r.attentionPlan(round); defer attention_plan.deinit(); @@ -91,9 +127,8 @@ pub fn pass(r: *Runner, round: *const Round, sc: *const Scratch, hidden: Ref, he const cb = r.model.queue.commandBuffer(); var e = cb.compute(.serial); errdefer e.end(); // an encoder left open aborts the process when it is released - const out = try encode(r.model, sc, &e, .{ .ptr = r, .gdn = Runner.gdnForward, .attention = Runner.attentionForward }, hidden, @intCast(round.ids.len), head); - e.end(); - cb.commit(); + var steps = Steps(@TypeOf(around)){ .r = r, .sc = sc, .e = &e, .cb = cb, .hidden = hidden, .rows = @intCast(round.ids.len), .mode = head, .around = around }; + const out = try @import("mtp_pick.zig").fused(&steps, Ref); cb.wait(); if (rounds.gpuFailed(cb, "the MTP head")) { r.failed = true; diff --git a/zig/src/families/qwen27/mtp_pick.zig b/zig/src/families/qwen27/mtp_pick.zig new file mode 100644 index 00000000000..32997996ad3 --- /dev/null +++ b/zig/src/families/qwen27/mtp_pick.zig @@ -0,0 +1,176 @@ +//! TF_Q27_MTP_GPU_PICK: the MTP head's draft pick from a GPU top-1 row, and its chance bit-equal to the CPU pick's. +const std = @import("std"); +const topk = @import("bf16_topk"); + +/// A logits row's pick and its probability under the head's softmax. +pub const Pick = struct { token: u32, chance: f32 }; + +/// Rows one top-k dispatch takes: a wider pass keeps the CPU pick. +pub const max_rows = topk.max_rows; + +/// The top-1 launch for `rows` logits rows of `vocab` values each. +pub fn params(rows: u32, vocab: u32) topk.Params { + return .{ .rows = rows, .vocab = vocab, .k = 1, .stride = vocab }; +} + +/// Each BF16 value's softmax term against one top value, computed once: the sum's terms and order stay the CPU pick's. +pub const Memo = struct { + terms: []f64, + marks: []u32, + stamp: u32 = 0, + top: ?u16 = null, + + pub fn init(gpa: std.mem.Allocator) !Memo { + const terms = try gpa.alloc(f64, 1 << 16); + errdefer gpa.free(terms); + const marks = try gpa.alloc(u32, 1 << 16); + @memset(marks, 0); + return .{ .terms = terms, .marks = marks }; + } + + pub fn deinit(m: *Memo, gpa: std.mem.Allocator) void { + gpa.free(m.terms); + gpa.free(m.marks); + } + + fn aim(m: *Memo, top: u16) void { + if (m.top == top) return; + m.top = top; + if (m.stamp == std.math.maxInt(u32)) { + @memset(m.marks, 0); + m.stamp = 0; + } + m.stamp += 1; + } + + /// One over the sum of exp(v - top), every value in row order, as the CPU pick adds them. + pub fn chance(m: *Memo, values: []const u16, top: u16) f32 { + m.aim(top); + const high: f32 = @bitCast(@as(u32, top) << 16); + var sum: f64 = 0; + for (values) |v| { + if (m.marks[v] != m.stamp) { + m.marks[v] = m.stamp; + m.terms[v] = @exp(@as(f64, @as(f32, @bitCast(@as(u32, v) << 16)) - high)); + } + sum += m.terms[v]; + } + return @floatCast(1 / sum); + } +}; + +/// The pick from a logits row's top-1 result; a nonfinite row fails as the CPU pick does. +pub fn fromRow(row: *const topk.Row, values: []const u16, memo: *Memo) !Pick { + const p = params(1, std.math.cast(u32, values.len) orelse return error.BadLogits); + const entries = topk.decode(row, p) catch |err| return if (err == error.NonfiniteTopK) error.NonfiniteLogits else err; + const top: u16 = @intCast(@as(u32, @bitCast(entries[0].score)) >> 16); + if (values[entries[0].token] != top) return error.BadTopKResult; + return .{ .token = entries[0].token, .chance = memo.chance(values, top) }; +} + +/// One fused pass's order: rows in, the head, picks and saves, then a single commit. +pub fn fused(ctx: anytype, Out: type) !Out { + try ctx.before(); + const out = try ctx.head(); + try ctx.after(out); + try ctx.commit(); + return out; +} + +const Recorder = struct { + log: [8]u8 = undefined, + n: usize = 0, + fail: u8 = 0, + + fn note(r: *Recorder, c: u8) !void { + if (r.fail == c) return error.Injected; + r.log[r.n] = c; + r.n += 1; + } + fn before(r: *Recorder) !void { + try r.note('g'); + } + fn head(r: *Recorder) !u32 { + try r.note('h'); + return 7; + } + fn after(r: *Recorder, out: u32) !void { + try std.testing.expectEqual(@as(u32, 7), out); + try r.note('p'); + } + fn commit(r: *Recorder) !void { + try r.note('c'); + } +}; + +test "qwen27 MTP pick: a fused absorb gathers, runs the head, picks and saves, then commits once" { + var r = Recorder{}; + try std.testing.expectEqual(@as(u32, 7), try fused(&r, u32)); + try std.testing.expectEqualStrings("ghpc", r.log[0..r.n]); + for ("ghp") |at| { + var bad = Recorder{ .fail = at }; + try std.testing.expectError(error.Injected, fused(&bad, u32)); + try std.testing.expect(std.mem.indexOfScalar(u8, bad.log[0..bad.n], 'c') == null); + } +} + +fn expectSame(values: []const u16, memo: *Memo) !void { + const cpu = try @import("mtp.zig").pick(values); + const row = try topk.oracle(values, 1); + const gpu = try fromRow(&row, values, memo); + try std.testing.expectEqual(cpu.token, gpu.token); + try std.testing.expectEqual(@as(u32, @bitCast(cpu.chance)), @as(u32, @bitCast(gpu.chance))); +} + +test "qwen27 MTP pick: the top-1 contract picks the CPU's token and chance, ties and signed zeros included" { + const a = std.testing.allocator; + var memo = try Memo.init(a); + defer memo.deinit(a); + const cases = [_][]const u16{ + &.{ 0xc000, 0x3f80, 0x3f80, 0xbf80 }, // the first of a tie + &.{ 0x8000, 0x0000, 0x8000 }, // -0 and +0 tie, so the first wins + &.{ 0x0000, 0x8000 }, + &.{ 0x0001, 0x0002, 0x0002 }, // subnormal values order by value + &.{ 0x8002, 0x8001, 0x8001 }, + &.{0xbf80}, + }; + for (cases) |c| try expectSame(c, &memo); + var random = std.Random.DefaultPrng.init(0x2716); + const rng = random.random(); + var values: [4096]u16 = undefined; + for (0..64) |round| { + for (&values) |*v| { + // few distinct values in the odd rounds, so ties at the top are common + const raw = if (round % 2 == 1) rng.intRangeAtMost(u16, 0x3f80, 0x3f84) else rng.int(u16); + v.* = if (raw & 0x7f80 == 0x7f80) raw & 0xbfff else raw; + } + try expectSame(&values, &memo); + } +} + +test "qwen27 MTP pick: a nonfinite row fails as the CPU pick does, and a result that misreads its row is refused" { + const a = std.testing.allocator; + var memo = try Memo.init(a); + defer memo.deinit(a); + for ([_][]const u16{ &.{ 0x3f80, 0x7fc1 }, &.{ 0x7f80, 0x3f80 }, &.{ 0xff80, 0x3f80 } }) |values| { + try std.testing.expectError(error.NonfiniteLogits, @import("mtp.zig").pick(values)); + const row = try topk.oracle(values, 1); + try std.testing.expectError(error.NonfiniteLogits, fromRow(&row, values, &memo)); + } + const values = [_]u16{ 0x3f80, 0x4000 }; + var row = try topk.oracle(&values, 1); + row.entries[0].token = 0; + try std.testing.expectError(error.BadTopKResult, fromRow(&row, &values, &memo)); +} + +test "qwen27 MTP pick: a memo reused across tops never keeps a term from the last top" { + const a = std.testing.allocator; + var memo = try Memo.init(a); + defer memo.deinit(a); + try expectSame(&.{ 0x3f80, 0x4000 }, &memo); + try expectSame(&.{ 0x3f80, 0x4040 }, &memo); + try expectSame(&.{ 0x3f80, 0x4000 }, &memo); + memo.stamp = std.math.maxInt(u32); + try expectSame(&.{ 0x3f80, 0x4080 }, &memo); + try std.testing.expectEqual(@as(u32, 1), memo.stamp); +} diff --git a/zig/src/families/qwen27/projection.zig b/zig/src/families/qwen27/projection.zig index 7d32bb6798d..2603403df60 100644 --- a/zig/src/families/qwen27/projection.zig +++ b/zig/src/families/qwen27/projection.zig @@ -79,8 +79,8 @@ pub fn prepare(device: mtl.Device, allocator: std.mem.Allocator, owned: *std.Arr n = try std.math.add(usize, n, rows); } if (!device.tensorUnits() or n % tile != 0) return prepareRows(device, allocator, owned, parts, n, k, tile, slices, gn); + if (group == 64 and (bits == 4 or bits == 5 or bits == 6)) slices = key.m5 orelse slices; if (bits != 4 or group != 64) return prepareLanes(device, allocator, owned, parts, n, k, tile, slices, gn); - slices = key.m5 orelse slices; const w = try device.buffer(n * k / 2, mtl.ResourceOptions.shared | mtl.ResourceOptions.untracked); owned.append(allocator, w) catch |err| { w.deinit(); diff --git a/zig/src/families/qwen27/prompt_memory.zig b/zig/src/families/qwen27/prompt_memory.zig index 9d224f9710e..1b5b59d1b57 100644 --- a/zig/src/families/qwen27/prompt_memory.zig +++ b/zig/src/families/qwen27/prompt_memory.zig @@ -19,8 +19,21 @@ pub fn frameBytes(c: Config, rows: u32) usize { return buffers(frame.allocationSizes(c, rows)) + (if (rows > frame.small_rows) buffers(frame.decodeSizes(c, rows)) else 0); } +/// A prompt row's tap bytes: `planes` raw planes, plus a fusing drafter's row-major copy, fc rows and fused row. +pub fn tapRowBytes(hidden: usize, planes: usize, fused: bool) usize { + return (planes + if (fused) planes + 2 else 0) * hidden * 2; +} +test "qwen27 memory: an eight-tap fusing drafter's prompt taps cost what its planes and fusion buffers hold" { + try std.testing.expectEqual(@as(usize, 5 * 5120 * 2), tapRowBytes(5120, 5, false)); + try std.testing.expectEqual(@as(usize, 18 * 4096 * 2), tapRowBytes(4096, 8, true)); +} + /// Frame bytes already belong to the model; these are the runner's future bytes at its peak (`planes`: its tap planes). pub fn runnerBytes(c: Config, context: u32, slots: u32, rows: u32, shared: bool, ring: usize, planes: usize) !usize { + return runnerBytesTaps(c, context, slots, rows, shared, ring, tapRowBytes(c.hidden, planes, false)); +} +/// runnerBytes with the drafter's own tap row bytes (tapRowBytes). +pub fn runnerBytesTaps(c: Config, context: u32, slots: u32, rows: u32, shared: bool, ring: usize, tap_row: usize) !usize { var attention: usize = 0; for (0..c.layers) |i| attention += @intFromBool(c.kind(i) == .attention); const linear = c.layers - attention; @@ -31,7 +44,7 @@ pub fn runnerBytes(c: Config, context: u32, slots: u32, rows: u32, shared: bool, const kv = attention * @as(usize, slots) * buffers([_]usize{ @as(usize, context) * c.kvDim() * 2, @as(usize, context) * c.kvDim() * 2 }); const bindings = attention * buffers([_]usize{ (planning.global_words + planning.max_streams * planning.stream_words) * 4, planning.max_streams * 16, rows * 16 }); const before = if (slots > 1) buffers([_]usize{budget.state}) else 0; - const taps = buffers([_]usize{@as(usize, rows) * planes * c.hidden * 2}); + const taps = buffers([_]usize{@as(usize, rows) * tap_row}); return kv + bindings + before + taps + buffers(scratch.sizes) + buffers(budget.allocationSizes()) + slots * (ring + (256 << 20)); } @@ -43,11 +56,12 @@ pub const Fit = struct { ring: usize = 0, /// The runner's tap planes: the 27B's five, or the drafter's own count. planes: usize = 5, + tap_row: usize = 0, // tapRowBytes for the drafter's taps; 0: five raw planes current_rows: u32, left: usize, pub fn cost(f: Fit, rows: u32, slots: u32) !usize { - return (try runnerBytes(f.config, f.context, slots, rows, f.shared, f.ring, f.planes)) + (frameBytes(f.config, rows) -| frameBytes(f.config, f.current_rows)); + return (try runnerBytesTaps(f.config, f.context, slots, rows, f.shared, f.ring, if (f.tap_row > 0) f.tap_row else tapRowBytes(f.config.hidden, f.planes, false))) + (frameBytes(f.config, rows) -| frameBytes(f.config, f.current_rows)); } pub fn choose(f: Fit, requested: u32, explicit: bool) !u32 { diff --git a/zig/src/families/qwen27/quant_gpu.zig b/zig/src/families/qwen27/quant_gpu.zig index 93aba64e74b..ed16663ae37 100644 --- a/zig/src/families/qwen27/quant_gpu.zig +++ b/zig/src/families/qwen27/quant_gpu.zig @@ -156,7 +156,7 @@ pub const Kernels = struct { cut: [2]u32, long: bool, ) !std.AutoHashMapUnmanaged(Key, lane.Projection).GetOrPutResult { - const reg = p.bits == 4 and p.group == 64; + const reg = (p.bits == 4 or p.bits == 5 or p.bits == 6) and p.group == 64; const key = Key{ .kind = .projection, .n = p.n, @@ -269,9 +269,10 @@ pub const Kernels = struct { try span.end(); return; } - const reg = p.bits == 4 and p.group == 64; + const reg = (p.bits == 4 or p.bits == 5 or p.bits == 6) and p.group == 64; if (!reg and (skip > 0 or cut[1] > 0)) return error.BadCoreProjectionRows; - const long = if (reg) longKey(k.long_prompt, k.prompt, rows) else k.long_prompt and k.prompt and rows > 16; + // Row-block prompt passes at every non-reg width on every tensor-unit chip; Ultras keep their long keys. + const long = if (reg) longKey(k.long_prompt, k.prompt, rows) else k.prompt and rows > 16 and (k.long_prompt or k.device.tensorUnits()); const sums: ?Sums = if (reg or (p.bits == 8 and p.group == 64)) xs else null; const entry = try k.laneEntry(p, sk, skip, cut, long); const step = entry.value_ptr.max_rows; diff --git a/zig/src/families/qwen27/qwen27.zig b/zig/src/families/qwen27/qwen27.zig index 79fd1125b04..f2c991813e3 100644 --- a/zig/src/families/qwen27/qwen27.zig +++ b/zig/src/families/qwen27/qwen27.zig @@ -2,6 +2,7 @@ pub const dflash = @import("dflash/root.zig"); pub const gguf = @import("gguf.zig"); pub const config = @import("config.zig"); +pub const tied_head = @import("tied_head.zig"); pub const affine = @import("affine.zig"); pub const widths = @import("widths.zig"); pub const checkpoint = @import("checkpoint.zig"); @@ -15,6 +16,8 @@ pub const decode_round = @import("decode_round.zig"); pub const forward = @import("forward.zig"); /// The MTP draft head's forward (the 27B's mtp-4bit.safetensors, or Ornith's bf16 `mtp.*` release). pub const mtp = @import("mtp.zig"); +/// TF_Q27_MTP_GPU_PICK: the draft pick from a GPU top-1 row. +pub const mtp_pick = @import("mtp_pick.zig"); pub const gdn = @import("gdn.zig"); pub const gdn_contract = @import("gdn_contract.zig"); pub const gdn_hook = @import("gdn_hook.zig"); @@ -32,6 +35,7 @@ pub const model = @import("model.zig"); pub const moe_gpu = @import("moe_gpu.zig"); pub const projection = @import("projection.zig"); pub const prompt_memory = @import("prompt_memory.zig"); +pub const kv_grow = @import("kv_grow.zig"); pub const prompt_rows = @import("prompt_rows.zig"); pub const prompt_marks = @import("prompt_marks.zig"); pub const prompt_tail = @import("prompt_tail.zig"); @@ -45,12 +49,16 @@ pub const disk = @import("disk.zig"); pub const taps = @import("taps.zig"); pub const tap_gather = @import("tap_gather.zig"); pub const tap_ring = @import("tap_ring.zig"); +/// Staged references: a round's stage rows copied to their planes (tf-qwen27-run --stages). +pub const stage_planes = @import("stage_planes.zig"); /// The 27B's Metal sources by name (the kernel contract compiles them as the engine does). pub const runtime_sources = @import("qwen_runtime_sources"); test { _ = dflash; _ = disk; _ = @import("core").gpu_profile; + _ = @import("core").qwen35_stages; + _ = stage_planes; _ = session; _ = @import("gdn_test.zig"); _ = @import("simd_attention.zig"); diff --git a/zig/src/families/qwen27/residency.zig b/zig/src/families/qwen27/residency.zig index bb14753233e..32daac24729 100644 --- a/zig/src/families/qwen27/residency.zig +++ b/zig/src/families/qwen27/residency.zig @@ -27,6 +27,7 @@ pub fn setRunner(r: anytype, hook: ?mtl.ResidencySet.Follow) void { pub fn appendDraft(b: anytype, a: std.mem.Allocator, list: *std.ArrayList(mtl.Buffer)) !void { try fields.append(a, list, &b.attention); + if (b.attention_full) |*x| try fields.append(a, list, x); try fields.append(a, list, &b.topk); try list.appendSlice(a, b.head.owned.items); try list.appendSlice(a, b.frame.pool.items); @@ -42,6 +43,7 @@ pub fn appendDraft(b: anytype, a: std.mem.Allocator, list: *std.ArrayList(mtl.Bu fn draftBuffers(b: anytype, hook: mtl.ResidencySet.Follow, joining: bool) void { fields.apply(&b.attention, hook, joining); + if (b.attention_full) |*x| fields.apply(x, hook, joining); fields.apply(&b.topk, hook, joining); for (b.head.owned.items) |buffer| fields.one(buffer, hook, joining); for (b.caches) |*c| fields.apply(c, hook, joining); diff --git a/zig/src/families/qwen27/snapshot.zig b/zig/src/families/qwen27/snapshot.zig index 695e712bc08..84491d33bf5 100644 --- a/zig/src/families/qwen27/snapshot.zig +++ b/zig/src/families/qwen27/snapshot.zig @@ -240,7 +240,10 @@ pub fn restoreSlot(a: std.mem.Allocator, r: *Runner, slot: u32, ring: ?Ring, st: try st.landed(); try r.reset(slot); try r.cover(slot, st.at); // a paged slot's pages for the state's rows before the copy writes them - try copy(a, r, slot, ring, st, false); + try r.reserve(slot, st.at); // a slot whose K/V and ring grow as used holds the state's rows first + var held = ring; + if (held) |*g| try g.hold(st.at); + try copy(a, r, slot, held, st, false); r.offsets[slot] = st.at; if (ring) |g| g.end.* = st.draft_end; } @@ -253,12 +256,15 @@ pub fn moveSlot(a: std.mem.Allocator, r: *Runner, from: u32, from_ring: ?Ring, t if (from_ring) |g| if (g.end.* != at) return error.NotAtMark; try r.reset(to); try r.cover(to, at); + try r.reserve(to, at); + var to_held = to_ring; + if (to_held) |*g| try g.hold(at); var src: std.ArrayList(Part) = .empty; defer src.deinit(a); var dst: std.ArrayList(Part) = .empty; defer dst.deinit(a); try parts(r, from, from_ring, at, &src, a, false); - try parts(r, to, to_ring, at, &dst, a, false); + try parts(r, to, to_held, at, &dst, a, false); if (src.items.len != dst.items.len) return error.SnapshotLayout; const pool = mtl.objc.Pool.push(); defer pool.pop(); diff --git a/zig/src/families/qwen27/stage_planes.zig b/zig/src/families/qwen27/stage_planes.zig new file mode 100644 index 00000000000..fbbc7ed9d12 --- /dev/null +++ b/zig/src/families/qwen27/stage_planes.zig @@ -0,0 +1,62 @@ +//! Staged references on Metal: a round copies each stage's rows into its own plane, read once the round has run. +const std = @import("std"); +const mtl = @import("metal"); +const Ref = @import("projection.zig").Ref; +const Glue = @import("glue_gpu.zig").Kernels; +const stages = @import("core").qwen35_stages; +const root = @import("root"); + +/// Built in only when the program's root says `pub const qwen27_stages = true` (tf-qwen27-run): served code has none. +pub const on = @hasDecl(root, "qwen27_stages") and root.qwen27_stages; +/// The planes a tool's one runner records into (null: none); void unless built in, so no served type changes. +pub var active: if (on) ?*Planes else void = if (on) null else {}; + +pub const Planes = struct { + buffer: mtl.Buffer, + round: stages.Round, + + pub fn init(device: mtl.Device, recorder: *stages.Recorder, capacity: u32, logit_capacity: u32) !Planes { + const round = try stages.Round.init(recorder, capacity, logit_capacity); + return .{ .buffer = try device.buffer(round.bytes(), mtl.ResourceOptions.shared | mtl.ResourceOptions.untracked), .round = round }; + } + + pub fn deinit(p: Planes) void { + p.buffer.deinit(); + } + + pub fn begin(p: *Planes) void { + p.round.begin(); + } + + pub fn record(p: *Planes, glue: Glue, e: mtl.ComputeEncoder, at: stages.Point, x: Ref, rows: u32) !void { + try p.round.mark(at, rows); + const width: u32 = @intCast(p.round.recorder.width(at)); + try glue.unstack(e, x, .{ .buffer = p.buffer, .offset = p.round.offset(at) }, .{ .rows = rows, .width = width, .stride = width, .offset = 0 }); + e.barrier(); + } + + /// Hands a finished round, whose rows start at cache position `first`, to the recorder. + pub fn end(p: *Planes, first: u32) !void { + try p.round.end(p.buffer.slice(u8, p.buffer.length()), first); + } +}; + +/// Staged references record one stream's chain (a headless prompt chunk records 0 logit rows); others are refused. +pub fn admit(windows: anytype) !void { + try stages.admit(windows.len, windows.len == 1 and stages.isChain(windows[0].parents), true); +} + +/// A round's prompt tail facts with its planes begun: recording reads the last layer's stream and final norm. +pub inline fn begin(facts: anytype) @TypeOf(facts) { + var out = facts; + if (on) if (active) |p| { + p.begin(); + out.last_tapped = true; + }; + return out; +} + +/// A pass's stage rows into the active planes, when stages are built in and asked for. +pub inline fn record(glue: Glue, e: mtl.ComputeEncoder, at: stages.Point, x: Ref, rows: u32) !void { + if (on) if (active) |p| try p.record(glue, e, at, x, rows); +} diff --git a/zig/src/families/qwen27/tap_ring.zig b/zig/src/families/qwen27/tap_ring.zig index 3360a3d954e..27fb1d378f9 100644 --- a/zig/src/families/qwen27/tap_ring.zig +++ b/zig/src/families/qwen27/tap_ring.zig @@ -1,12 +1,17 @@ //! A stream's committed target taps over the drafter's window, by position modulo the window. const std = @import("std"); const mtl = @import("metal"); +const kv_grow = @import("kv_grow.zig"); pub const Ring = struct { buf: mtl.Buffer, end: *u64, // taps committed so far (the stream's fed tokens) window: u32, stride: usize, // one row's bytes + grow: ?Grow = null, // a ring that holds the rows its stream reached: the buffer holding `rows`; null: the window + + /// The buffer holding at least `rows` rows (it may be a new one; the old rows stay at their places). + pub const Grow = struct { ctx: *anyopaque, run: *const fn (ctx: *anyopaque, rows: u32) anyerror!mtl.Buffer }; /// Rows [off, off + rows) of `taps` follow the committed ones. pub fn absorb(r: Ring, taps: mtl.Buffer, off: usize, rows: u32) !void { @@ -18,18 +23,35 @@ pub const Ring = struct { pub fn absorbBytes(r: Ring, data: []const u8, rows: u32) !void { if (rows == 0 or data.len != @as(usize, rows) * r.stride) return error.BadCommittedTaps; const end = try std.math.add(u64, r.end.*, rows); + const buf = if (r.grow) |g| try g.run(g.ctx, @intCast(@min(end, r.window))) else r.buf; var first: usize = 0; while (first < rows) { const slot: usize = @intCast((r.end.* + first) % r.window); const count = @min(rows - first, r.window - slot); - @memcpy(r.buf.contents()[slot * r.stride ..][0 .. count * r.stride], data[first * r.stride ..][0 .. count * r.stride]); + @memcpy(buf.contents()[slot * r.stride ..][0 .. count * r.stride], data[first * r.stride ..][0 .. count * r.stride]); first += count; } r.end.* = end; } + /// The ring holds a state of `rows` tokens before a blit writes it (a restore); its buffer may change. + pub fn hold(r: *Ring, rows: u64) !void { + if (r.grow) |g| r.buf = try g.run(g.ctx, @intCast(@min(rows, r.window))); + } + /// Ring bytes a state after `at` tokens needs: slots [0, at) until the ring wraps, then all of it. pub fn bytes(r: Ring, at: u64) usize { return @as(usize, @intCast(@min(at, r.window))) * r.stride; } }; + +/// Rows a growing ring takes for `need`: the K/V growth rule, at most the window. +pub fn grownRows(held: u32, need: u32, step: u32, window: u32) u32 { + return kv_grow.rows(held, need, step, window); +} + +/// A grown ring's first `held` rows into its new buffer, at the same places (the CPU writes rings). +pub fn carry(old: mtl.Buffer, new: mtl.Buffer, held: u32, stride: usize) void { + const n = @as(usize, held) * stride; + @memcpy(new.contents()[0..n], old.contents()[0..n]); +} diff --git a/zig/src/families/qwen27/taps.zig b/zig/src/families/qwen27/taps.zig index 418871042e5..a879f377d67 100644 --- a/zig/src/families/qwen27/taps.zig +++ b/zig/src/families/qwen27/taps.zig @@ -6,10 +6,20 @@ const Glue = @import("glue_gpu.zig").Kernels; /// The 27B drafter's tap layers, the default before a drafter sets its own. pub const layers = [_]usize{ 5, 19, 33, 47, 61 }; +/// The most tap planes a drafter may name (a DFlash v1 draft names up to eight). pub const max_planes = 8; +/// A drafter's fusion of a row's taps (fc then hidden_norm), encoded where the taps complete. +pub const Fuser = struct { ptr: *anyopaque, width: u32, encode: *const fn (*anyopaque, mtl.ComputeEncoder, Ref, Ref, u32) anyerror!void }; +/// Where accepted rows gather from: the raw planes, or one plane of fused rows. +pub const Source = struct { buffer: mtl.Buffer, width: u32, planes: u32 }; + pub const Taps = struct { buffer: mtl.Buffer, + fuser: ?Fuser = null, + fused: ?mtl.Buffer = null, // [capacity][fuser width] + rowmajor: ?mtl.Buffer = null, // [capacity][count * width]: a row's planes side by side, fc's input + identity: ?mtl.Buffer = null, // 0, 1, ... capacity - 1: every row, for the row-major gather capacity: u32, width: u32, seen: u16 = 0, @@ -27,6 +37,7 @@ pub const Taps = struct { /// A drafter's tap layers; the buffer grows to their count when it holds fewer planes, never shrinks. pub fn use(t: *Taps, device: mtl.Device, ids: []const u32) !void { if (ids.len == 0 or ids.len > max_planes) return error.BadTapIndex; + if (t.fuser != null and ids.len != t.count) return error.BadTapShape; // a fused ring keeps its tap count if (ids.len > t.planes) { const grown = try planesBuffer(device, t.capacity, t.width, ids.len); t.buffer.deinit(); @@ -43,9 +54,44 @@ pub const Taps = struct { } pub fn deinit(t: Taps) void { + t.dropFused(); t.buffer.deinit(); } + fn dropFused(t: Taps) void { + if (t.fused) |b| b.deinit(); + if (t.rowmajor) |b| b.deinit(); + if (t.identity) |b| b.deinit(); + } + + /// Completed taps fused for a drafter whose ring keeps fused rows; null: planes stay raw. + pub fn setFuser(t: *Taps, device: mtl.Device, f: ?Fuser) !void { + t.dropFused(); + t.fuser = null; + t.fused = null; + t.rowmajor = null; + t.identity = null; + const fuser = f orelse return; + if (fuser.width == 0) return error.BadTapShape; + const options = mtl.ResourceOptions.shared | mtl.ResourceOptions.untracked; + const fused = try device.buffer(@as(usize, t.capacity) * fuser.width * 2, options); + errdefer fused.deinit(); + const rowmajor = try device.buffer(@as(usize, t.capacity) * t.count * t.width * 2, options); + errdefer rowmajor.deinit(); + const identity = try device.buffer(@as(usize, t.capacity) * 4, options); + for (identity.slice(u32, t.capacity), 0..) |*x, i| x.* = @intCast(i); + t.fuser = fuser; + t.fused = fused; + t.rowmajor = rowmajor; + t.identity = identity; + } + + /// The rows accepted taps gather from. + pub fn source(t: Taps) Source { + if (t.fused) |f| return .{ .buffer = f, .width = t.fuser.?.width, .planes = 1 }; + return .{ .buffer = t.buffer, .width = t.width, .planes = @intCast(t.count) }; + } + pub fn begin(t: *Taps) void { t.seen = 0; t.rows = 0; @@ -61,6 +107,13 @@ pub const Taps = struct { e.barrier(); t.seen |= bit; t.rows = rows; + if (t.fuser) |f| if (t.seen == (@as(u16, 1) << @intCast(t.count)) - 1) { + const kept = Ref{ .buffer = t.identity.? }; + try glue.tapRows(e, .{ .buffer = t.buffer }, kept, .{ .buffer = t.rowmajor.? }, .{ .rows = rows, .width = t.width, .capacity = t.capacity, .planes = @intCast(t.count) }); + e.barrier(); + try f.encode(f.ptr, e, .{ .buffer = t.rowmajor.? }, .{ .buffer = t.fused.? }, rows); + e.barrier(); + }; } pub fn plane(t: Taps, index: usize) !Ref { @@ -69,7 +122,7 @@ pub const Taps = struct { } pub fn complete(t: Taps) !void { - if (t.count == 0 or t.count > t.planes or t.seen != (@as(u16, 1) << @intCast(t.count)) - 1) return error.IncompleteTaps; + if (t.count == 0 or t.count > t.planes or t.seen != fullMask(t.count)) return error.IncompleteTaps; } pub fn accepted(t: Taps, glue: Glue, e: mtl.ComputeEncoder, path: []const u32, kept: Ref, out: Ref) !void { @@ -77,11 +130,21 @@ pub const Taps = struct { if (path.len == 0) return; if (path.len > t.rows) return error.BadTapGather; for (path) |row| if (row >= t.rows) return error.BadTapGather; - try glue.tapRows(e, .{ .buffer = t.buffer }, kept, out, .{ .rows = @intCast(path.len), .width = t.width, .capacity = t.capacity, .planes = @intCast(t.count) }); + const s = t.source(); + try glue.tapRows(e, .{ .buffer = s.buffer }, kept, out, .{ .rows = @intCast(path.len), .width = s.width, .capacity = t.capacity, .planes = s.planes }); e.barrier(); } }; +fn fullMask(count: usize) u16 { + return @intCast((@as(u16, 1) << @intCast(count)) - 1); +} + +test "eight tap planes complete when all eight are seen" { + try std.testing.expectEqual(@as(u16, 0xff), fullMask(8)); + try std.testing.expectEqual(@as(u16, 0x1f), fullMask(5)); +} + test "DFlash tap ids name completed target blocks" { try std.testing.expectEqualSlices(usize, &.{ 5, 19, 33, 47, 61 }, &layers); } diff --git a/zig/src/families/qwen27/tied_head.zig b/zig/src/families/qwen27/tied_head.zig new file mode 100644 index 00000000000..ac80de41a3d --- /dev/null +++ b/zig/src/families/qwen27/tied_head.zig @@ -0,0 +1,18 @@ +//! A tied head: the output projection reads the embedding's tensors and format, never a stored `lm_head`. +const std = @import("std"); + +pub const flag = "TF_QWEN27_TIED_HEAD"; +pub const embedding = "model.embed_tokens"; +pub const stored_head = "lm_head"; + +/// The module the head loads from; a tied config with its own `lm_head` is ambiguous and refused. +pub fn module(tied: bool, stored: bool) error{TiedHeadInCheckpoint}![]const u8 { + if (!tied) return stored_head; + if (stored) return error.TiedHeadInCheckpoint; + return embedding; +} + +/// Bytes of the head's load-time repack, which a tied checkpoint's files do not count. +pub fn bytes(vocab: usize, hidden: usize, bits: usize, group: usize) usize { + return vocab * (hidden * bits / 8 + hidden / group * 4); +} diff --git a/zig/src/families/qwen27/weights.zig b/zig/src/families/qwen27/weights.zig index c5c8acce02f..2d81ea00377 100644 --- a/zig/src/families/qwen27/weights.zig +++ b/zig/src/families/qwen27/weights.zig @@ -4,6 +4,7 @@ const Config = @import("config.zig").Config; const Kind = @import("config.zig").Kind; const ck = @import("checkpoint.zig"); const Formats = @import("affine.zig").Formats; +const tied_head = @import("tied_head.zig"); pub const Tensor = ck.Tensor; pub const Linear = ck.Linear; pub const Mlp = struct { gate: Linear, up: Linear, down: Linear }; @@ -18,6 +19,8 @@ pub const Weights = struct { norm: Tensor, head: Linear, layers: []Layer, + /// `head` borrows the embedding's tensors, so their bytes count once. + tied: bool = false, pub fn deinit(w: *Weights) void { w.gpa.free(w.layers); @@ -25,7 +28,7 @@ pub const Weights = struct { } pub fn tensorBytes(w: Weights) !usize { - var total = try std.math.add(usize, linearBytes(w.embed), linearBytes(w.head)); + var total = try std.math.add(usize, linearBytes(w.embed), if (w.tied) 0 else linearBytes(w.head)); total = try std.math.add(usize, total, w.norm.bytes.len); for (w.layers) |l| { total = try std.math.add(usize, total, l.input_norm.bytes.len + l.post_norm.bytes.len); @@ -159,5 +162,7 @@ pub fn load(gpa: std.mem.Allocator, src: ck.Source, formats: *const Formats, c: const layers = try gpa.alloc(Layer, c.layers); errdefer gpa.free(layers); for (layers, 0..) |*l, i| l.* = try b.layer(c, i); - return .{ .gpa = gpa, .prefix = b.prefix, .layers = layers, .embed = try b.linear("model.embed_tokens", c.vocab, c.hidden), .norm = try b.tensor("model.norm.weight", &.{c.hidden}), .head = try b.linear("lm_head", c.vocab, c.hidden) }; + var stored: [96]u8 = undefined; + const head = try tied_head.module(c.tied_head, try present(src, try std.fmt.bufPrint(&stored, "{s}lm_head.weight", .{b.prefix}))); + return .{ .gpa = gpa, .prefix = b.prefix, .layers = layers, .embed = try b.linear("model.embed_tokens", c.vocab, c.hidden), .norm = try b.tensor("model.norm.weight", &.{c.hidden}), .head = try b.linear(head, c.vocab, c.hidden), .tied = c.tied_head }; } diff --git a/zig/src/families/qwen27/weights_test.zig b/zig/src/families/qwen27/weights_test.zig index 0a554bb6793..f565657b691 100644 --- a/zig/src/families/qwen27/weights_test.zig +++ b/zig/src/families/qwen27/weights_test.zig @@ -4,6 +4,7 @@ const Config = @import("config.zig"); const ck = @import("checkpoint.zig"); const Formats = @import("affine.zig").Formats; const weights = @import("weights.zig"); +const widths = @import("widths.zig"); const gpa = std.testing.allocator; const json = "{\"model_type\":\"qwen3_5\",\"hidden_size\":64,\"intermediate_size\":128,\"num_hidden_layers\":4,\"num_attention_heads\":4,\"num_key_value_heads\":2,\"head_dim\":16,\"vocab_size\":96,\"linear_num_key_heads\":2,\"linear_num_value_heads\":4,\"linear_key_head_dim\":16,\"linear_value_head_dim\":16,\"linear_conv_kernel_dim\":4,\"eos_token_id\":[2,11],\"quantization\":{\"bits\":4,\"group_size\":32,\"layers.0.linear_attn.in_proj_a\":false}}"; const Fake = struct { @@ -169,3 +170,47 @@ test "wrong layer schedule cannot reuse an attention matrix as recurrent weights c.kinds[3] = .linear; try std.testing.expectError(error.MissingTensor, weights.load(gpa, src.source(), &fmt, c)); } + +test "a tied head binds the embedding's own bytes, counts them once and refuses a stored head" { + var src = try Fake.init(""); + defer src.deinit(); + var fmt = try Formats.init(gpa, json); + defer fmt.deinit(); + var c = try Config.parse(gpa, json, null); + var untied = try weights.load(gpa, src.source(), &fmt, c); + defer untied.deinit(); + const untied_bytes = try untied.tensorBytes(); + c.tied_head = true; + try std.testing.expectError(error.TiedHeadInCheckpoint, weights.load(gpa, src.source(), &fmt, c)); + for ([_][]const u8{ "weight", "scales", "biases" }) |leaf| { + var name: [32]u8 = undefined; + const removed = src.tensors.fetchRemove(try std.fmt.bufPrint(&name, "lm_head.{s}", .{leaf})).?; + gpa.free(removed.key); + gpa.free(removed.value.bytes); + } + var w = try weights.load(gpa, src.source(), &fmt, c); + defer w.deinit(); + const e = w.embed.quantized; + const h = w.head.quantized; + try std.testing.expectEqual(e.weight.bytes.ptr, h.weight.bytes.ptr); + try std.testing.expectEqual(e.scales.bytes.ptr, h.scales.bytes.ptr); + try std.testing.expectEqual(e.biases.bytes.ptr, h.biases.bytes.ptr); + try std.testing.expectEqualSlices(u8, e.weight.bytes, h.weight.bytes); + const head_bytes = e.weight.bytes.len + e.scales.bytes.len + e.biases.bytes.len; + try std.testing.expectEqual(untied_bytes - head_bytes, try w.tensorBytes()); +} + +test "a tied head takes the embedding's width, not the format an lm_head key would name" { + const text = "{\"quantization\":{\"group_size\":32,\"bits\":4,\"model.embed_tokens\":{\"group_size\":32,\"bits\":8},\"lm_head\":{\"group_size\":32,\"bits\":4}}}"; + var fmt = try Formats.init(gpa, text); + defer fmt.deinit(); + var c = try Config.parse(gpa, json, null); + var untied = try widths.Widths.resolve(gpa, &fmt, c); + defer untied.deinit(); + try std.testing.expectEqual(@as(u8, 4), untied.head.bits); + c.tied_head = true; + var tied = try widths.Widths.resolve(gpa, &fmt, c); + defer tied.deinit(); + try std.testing.expectEqual(tied.embed, tied.head); + try std.testing.expectEqual(@as(u8, 8), tied.head.bits); +} diff --git a/zig/src/families/qwen27/widths.zig b/zig/src/families/qwen27/widths.zig index 751b0cb62c8..1bba272009e 100644 --- a/zig/src/families/qwen27/widths.zig +++ b/zig/src/families/qwen27/widths.zig @@ -106,7 +106,8 @@ pub const Widths = struct { l[@backingInt(m)] = try one(f, try std.fmt.bufPrint(&name, "model.layers.{d}.{s}", .{ i, leaf(c, m) })); }; } - return .{ .allocator = a, .layers = layers, .embed = try one(f, "model.embed_tokens"), .head = try one(f, "lm_head") }; + const embed = try one(f, "model.embed_tokens"); + return .{ .allocator = a, .layers = layers, .embed = embed, .head = if (c.tied_head) embed else try one(f, "lm_head") }; } /// Every module 4-bit g64, for synthetic graphs. @@ -209,12 +210,13 @@ pub fn admit(w: *const Widths, c: cfg.Config, chip: Chip, why: *Why) !void { }; } -/// One run's kernel: 4/64 keeps today's choice; other widths take the non-reg lane kernel or the row kernel. +/// One run's kernel: 4-, 5-, and 6-bit g64 take reg lanes; other widths take non-reg lanes or row kernels. fn check(chip: Chip, n: usize, k: usize, w: Width) !void { _ = try @import("projection.zig").split(n, k); // The lane sums and odd word counts assume group 64 off the 4-bit kernel. if (chip.tensor_units and w.bits != 4 and w.group != 64) return error.UnsupportedLaneGroup; - if (chip.tensor_units and n % 32 == 0) return (lane.Layout{ .n = n, .k = k, .format = .{ .bits = w.bits, .group = w.group }, .precompute_sums = isUniform(w), .reg = isUniform(w) }).validate(); + const reg = (w.bits == 4 or w.bits == 5 or w.bits == 6) and w.group == 64; + if (chip.tensor_units and n % 32 == 0) return (lane.Layout{ .n = n, .k = k, .format = .{ .bits = w.bits, .group = w.group }, .precompute_sums = reg or (w.bits == 8 and w.group == 64), .reg = reg }).validate(); if (isUniform(w) and n % 8 == 0) return; if (std.mem.indexOfScalar(u8, chip.row_bits, w.bits) == null) return error.UnsupportedRowBits; return (row.Weights{ .w = undefined, .scales = undefined, .biases = undefined, .n = n, .k = k, .group = w.group }).validate(); @@ -278,6 +280,25 @@ fn testAdmitRouted(quantization: []const u8, why: *Why) !void { return admit(&w, c, .{ .tensor_units = true, .row_bits = &all_rows }, why); } +/// Qwen3.6-35B-A3B's shapes (no intermediate_size) at `quantization`, on a chip with or without tensor units. +fn testAdmitA3b(quantization: []const u8, units: bool, why: *Why) !void { + const a = std.testing.allocator; + const text = try std.fmt.allocPrint(a, + \\{{"model_type":"qwen3_5_moe","text_config":{{"model_type":"qwen3_5_moe_text","hidden_size":2048, + \\"moe_intermediate_size":512,"shared_expert_intermediate_size":512,"num_experts":256,"num_experts_per_tok":8, + \\"num_hidden_layers":40,"num_attention_heads":16,"num_key_value_heads":2,"head_dim":256,"vocab_size":248320, + \\"linear_num_key_heads":16,"linear_num_value_heads":32,"linear_key_head_dim":128,"linear_value_head_dim":128, + \\"linear_conv_kernel_dim":4,"partial_rotary_factor":0.25,"eos_token_id":248044}},"quantization":{s}}} + , .{quantization}); + defer a.free(text); + const c = try cfg.parse(a, text, null); + var f = try affine.Formats.init(a, text); + defer f.deinit(); + var w = try Widths.resolve(a, &f, c); + defer w.deinit(); + return admit(&w, c, .{ .tensor_units = units, .row_bits = &all_rows }, why); +} + /// TensorFold/Qwen3.8-27B-oQ4 override shapes: 4-bit g64, 5-bit GDN, MLP and attention members, one 6-bit v. const oq4 = \\{"group_size":64,"bits":4,"mode":"affine", @@ -418,3 +439,23 @@ test "a shared expert whose width differs from the experts' is refused at admiss try std.testing.expectEqual(error.SharedExpertWidth, why.reason); try std.testing.expectEqualStrings("mlp.shared_expert.down_proj", why.module); } + +test "Qwen3.6-35B-A3B's published widths are admitted with and without tensor units" { + var why: Why = .{}; + // mlx-community/Qwen3.6-35B-A3B-4bit: 4-bit g64, every layer's router and shared gate at 8 bits + const published = + \\{"group_size":64,"bits":4,"mode":"affine", + \\"language_model.model.layers.0.mlp.gate":{"group_size":64,"bits":8}, + \\"language_model.model.layers.0.mlp.shared_expert_gate":{"group_size":64,"bits":8}, + \\"language_model.model.layers.39.mlp.gate":{"group_size":64,"bits":8}, + \\"language_model.model.layers.39.mlp.shared_expert_gate":{"group_size":64,"bits":8}} + ; + for ([_]bool{ true, false }) |units| try testAdmitA3b(published, units, &why); + // a router at 8 bits with its shared gate left at 4 cannot share one matrix + const split_gate = + \\{"group_size":64,"bits":4,"mode":"affine", + \\"language_model.model.layers.0.mlp.gate":{"group_size":64,"bits":8}} + ; + try std.testing.expectError(error.UnqualifiedQwenFormat, testAdmitA3b(split_gate, false, &why)); + try std.testing.expectEqual(error.SharedGateWidth, why.reason); +} diff --git a/zig/src/families/qwen3_5/backend/hip/engine/engine.zig b/zig/src/families/qwen3_5/backend/hip/engine/engine.zig index 1bb0fcd2268..5e48045f30e 100644 --- a/zig/src/families/qwen3_5/backend/hip/engine/engine.zig +++ b/zig/src/families/qwen3_5/backend/hip/engine/engine.zig @@ -156,11 +156,12 @@ pub const Engine = struct { const e = try gpa.create(Engine); errdefer gpa.destroy(e); e.gpa = gpa; - // --vision on a checkpoint without a tower serves text, as before; an unreadable tower still refuses at open - const seen: @FieldType(Options, "vision") = if (o.vision == null) null else if (vision.Vision.config(gpa, io, dir)) |_| o.vision else |err| switch (err) { - error.NoQwenVision => null, + // --vision on a checkpoint without a tower refuses by name (core's gate); an unreadable tower refuses too + const tower = if (o.vision == null) false else if (vision.Vision.config(gpa, io, dir)) |_| true else |err| switch (err) { + error.NoQwenVision => false, else => return err, }; + const seen: @FieldType(Options, "vision") = if (try @import("engine_api").visionGate(o.vision != null, tower)) o.vision else null; e.o = o; e.o.prompt_rows = @max(o.prompt_rows, o.cut_rows); // a test's cut is one piece: the prompts arena holds it e.o.vision = seen; @@ -305,6 +306,17 @@ pub const Engine = struct { e.blas = null; } + /// Rows a prompt pass takes through a layer at once (every rank the same: `prompt_rows.step`). + pub fn stepRows(e: *const Engine) usize { + return @import("prompt_rows.zig").step(e.o.prompt_rows, e.o.policy); + } + + /// The share of `sizeBytes` that grows with the prompt rows: the prompts arena and the ids a pass uploads. + pub fn promptBytes(e: *Engine, capacity: usize) !usize { + const prompt_rows = @min(e.o.prompt_rows, capacity); + return try scratch.prompts(e, prompt_rows, capacity) + prompt_rows * 4; + } + /// Device bytes `size(capacity, pool_pages)` would allocate with `rows` rows a forward: what admission weighs. pub fn sizeBytes(e: *Engine, rows: usize, capacity: usize, pool_pages: usize) !usize { const prompt_rows = @min(e.o.prompt_rows, capacity); @@ -517,7 +529,7 @@ pub const Engine = struct { for (ids) |t| if (t >= e.model().spec.vocab) return error.InvalidQwenToken; // no kernel bounds an id try e.ids_dev.uploadAsync(0, e.ids.view(0, 4 * ids.len), e.stream); var p: Poll = undefined; - const rows = try fwd.spanFor(e.ops(&e.prompts), e.model(), caches, e.ids_dev.base(), end - pos0, pos0, e.poll(cancel, end - pos0, &p), reads); + const rows = try fwd.spanFor(e.ops(&e.prompts), e.model(), caches, e.ids_dev.base(), end - pos0, pos0, e.stepRows(), e.poll(cancel, end - pos0, &p), reads); try e.stream.synchronize(); return rows; } @@ -536,7 +548,7 @@ pub const Engine = struct { const o = e.ops(&e.prompts); var p: Poll = undefined; // the last row's logits and MTP's input are read: past its keys, the last layer runs that row's tile - const kept = try fwd.spanFor(o, m, caches, e.ids_dev.base(), len, pos0, e.poll(cancel, len, &p), passes.prefill); + const kept = try fwd.spanFor(o, m, caches, e.ids_dev.base(), len, pos0, e.stepRows(), e.poll(cancel, len, &p), passes.prefill); const row = kept.row(len - 1, m.spec.hidden); if (last) |b| try hip.raw.copy(b, 0, row.ptr, m.spec.hidden * m.act.size(), e.stream.handle); var token: [1]u32 = undefined; diff --git a/zig/src/families/qwen3_5/backend/hip/engine/hip_lanes.zig b/zig/src/families/qwen3_5/backend/hip/engine/hip_lanes.zig index 603ccf55818..e9193c7c8dc 100644 --- a/zig/src/families/qwen3_5/backend/hip/engine/hip_lanes.zig +++ b/zig/src/families/qwen3_5/backend/hip/engine/hip_lanes.zig @@ -10,6 +10,7 @@ const state = @import("../forward/state.zig"); const mtp = @import("mtp.zig"); const costs = @import("hip_costs.zig"); const prefix = @import("prefix.zig"); +const prompt_rows = @import("prompt_rows.zig"); const hip_prefix = @import("hip_prefix.zig"); const memory = @import("memory.zig"); const pages = @import("../forward/pages.zig"); @@ -340,9 +341,19 @@ pub const Hip = struct { return lane; } - /// Where the chunk from `at` ends: decoding streams wait less; a readout keeps the chunk (rocBLAS bits by rows). + /// Where the chunk from `at` ends: the prompt rows alone, fewer beside decoders; rocBLAS bits keep the chunk. pub fn reach(h: *Hip, lane: *Lane, at: usize, limit: usize) !usize { - const rows = if (h.e.o.cut_rows > 0) h.e.o.cut_rows else if (lane.readout == null and h.decoding()) h.e.o.policy.fill_rows else prefix.chunk; + const o = &h.e.o; + const rows = if (o.cut_rows > 0) + o.cut_rows + else if (lane.readout != null) + prefix.chunk + else if (h.decoding()) + o.policy.fill_rows + else if (h.e.plain()) + prefix.chunk + else + prompt_rows.idle(o.prompt_rows, o.policy); const end = prefix.chunkEnd(at, limit, rows); if (h.cuts) |c| try c.append(h.gpa, @intCast(end)); return end; diff --git a/zig/src/families/qwen3_5/backend/hip/engine/hip_prompt_test.zig b/zig/src/families/qwen3_5/backend/hip/engine/hip_prompt_test.zig index 8637e8609ea..e5d7a0942c9 100644 --- a/zig/src/families/qwen3_5/backend/hip/engine/hip_prompt_test.zig +++ b/zig/src/families/qwen3_5/backend/hip/engine/hip_prompt_test.zig @@ -300,6 +300,7 @@ test "a readout begins at row 0 with no cuts while the tree would resume a plain test "a test's cut rows fix every piece end, which the recorder lists" { var e: @import("engine.zig").Engine = undefined; e.o = .{ .cut_rows = 300 }; + e.weights.embed = .{ .mlx = undefined }; // a quantized checkpoint: the chunk rule reads only the format var h: source.Hip = undefined; h.gpa = T.allocator; h.e = &e; @@ -344,6 +345,50 @@ test "a readout's piece stays the chunk while another lane decodes; a plain prom try T.expectEqual(2 * prefix.chunk, try h.reach(&reader, prefix.chunk, 5000)); } +test "alone a plain prompt takes the engine's prompt rows; a readout keeps the chunk, a decoder's neighbour the fill rows" { + var e: @import("engine.zig").Engine = undefined; + e.o = .{ .prompt_rows = 4096, .policy = .{ .prefill_step = 4096 } }; // as a lone gfx1151 opens + e.weights.embed = .{ .mlx = undefined }; + var h: source.Hip = undefined; + h.gpa = T.allocator; + h.e = &e; + h.cuts = null; + h.streams = .init(T.allocator); + defer h.streams.deinit(); + var plain: source.Lane = undefined; // reach reads a lane's readout only + plain.readout = null; + var reader: source.Lane = undefined; + var state: u8 = 0; + reader.readout = @ptrCast(&state); + try T.expectEqual(@as(usize, 4096), try h.reach(&plain, 0, 9000)); + try T.expectEqual(@as(usize, 8192), try h.reach(&plain, 4096, 9000)); + try T.expectEqual(prefix.chunk, try h.reach(&reader, 0, 9000)); + var talking: source.Lane = undefined; + talking.fill = null; // past its prompt: it decodes + var key: lanes.Stream = undefined; + try h.streams.map.put(T.allocator, &key, &talking); + try T.expectEqual(@as(usize, e.o.policy.fill_rows), try h.reach(&plain, 0, 9000)); + try T.expectEqual(prefix.chunk, try h.reach(&reader, 0, 9000)); +} + +test "a bf16 checkpoint, and an engine opened for longer passes than its policy's rows, keep the chunk" { + var e: @import("engine.zig").Engine = undefined; + e.o = .{ .prompt_rows = 4096, .policy = .{ .prefill_step = 4096 } }; + e.weights.embed = .{ .bf16 = undefined }; // rocBLAS products: their bits follow the rows of a piece + var h: source.Hip = undefined; + h.gpa = T.allocator; + h.e = &e; + h.cuts = null; + h.streams = .init(T.allocator); + defer h.streams.deinit(); + var plain: source.Lane = undefined; + plain.readout = null; + try T.expectEqual(prefix.chunk, try h.reach(&plain, 0, 9000)); + e.o = .{ .prompt_rows = 9000 }; // a check's longest prompt under the plain policy + e.weights.embed = .{ .mlx = undefined }; + try T.expectEqual(prefix.chunk, try h.reach(&plain, 0, 9000)); +} + test "every piece of a readout, the last too, goes to its readout with no projection, draw or kept cut" { var tokens: [1300]u32 = @splat(1); var logits: [1]u16 = undefined; diff --git a/zig/src/families/qwen3_5/backend/hip/engine/native.zig b/zig/src/families/qwen3_5/backend/hip/engine/native.zig index 8be82f337a2..66c30716938 100644 --- a/zig/src/families/qwen3_5/backend/hip/engine/native.zig +++ b/zig/src/families/qwen3_5/backend/hip/engine/native.zig @@ -1,5 +1,4 @@ //! Qwen3.5 / Qwen3.6 for the native server on HIP: the engine sized to GPU memory and the lane backend over it. - const std = @import("std"); const hip = @import("hip"); const lanes = @import("lanes"); @@ -7,7 +6,7 @@ const engine = @import("engine.zig"); const Engine = engine.Engine; const memory = @import("memory.zig"); const mtp = @import("mtp.zig"); -const prefix = @import("prefix.zig"); +const prompt_rows = @import("prompt_rows.zig"); const pages = @import("../forward/pages.zig"); const state = @import("../forward/state.zig"); const worker = @import("worker.zig"); @@ -160,6 +159,20 @@ fn openDraft(gpa: std.mem.Allocator, io: std.Io, e: *Engine, dir: []const u8, st const Readouts = struct { cfg: @import("core").joint_schema.Config, bounds: hip.joint_schema.plan.Bounds }; +/// The admitted streams' plan at some prompt rows, by `served`: the drafter's contexts and tap rings count in it. +const Plans = struct { + e: *Engine, + d: ?*Draft, + streams: usize, + capacity: usize, + readouts: ?Readouts, + + pub fn at(p: Plans, rows: usize) !prompt_rows.Plan { + p.e.o.prompt_rows = rows; + return .{ .whole = try served(p.e, p.d, p.streams, p.capacity, p.readouts), .prompt = try p.e.promptBytes(p.capacity) }; + } +}; + /// Loads this rank's share of the model, admits the streams its memory holds (with the other ranks) and sizes them. fn prepare( a: std.mem.Allocator, @@ -212,6 +225,7 @@ fn prepare( "cannot read or parse /proc/meminfo's MemTotal and MemAvailable; refusing HIP unified-memory admission", .{}, ), + error.VisionWithoutTower => steps.refuseAll(a, problem, "{s}", .{@import("engine_api").visionWords("this Qwen3.5 checkpoint", err).?}), // the CUDA engine refuses these alike: --vision asks for images, so a tower it cannot read stops the start error.UnsupportedQwenVision => steps.refuseAll( a, @@ -231,6 +245,10 @@ fn prepare( else => steps.refuseAll(a, problem, "the native HIP engine cannot load {s} ({s})", .{ dir, @errorName(err) }), }; errdefer e.deinit(); + // admission starts from the fallback's rows where a lone rank has them: the policy's must not cost a stream + const want = prompt_rows.opening(dev.policy, e.plain()); + const small = prompt_rows.fallback(dev.policy, dev.fallback_step, want); + e.o.prompt_rows = small orelse want; // a Clef head's weights go up beside the model's and count with them var head = try loadJoint(a, gpa, io, e, dir, problem); errdefer if (head) |*h| h.deinit(); @@ -281,6 +299,19 @@ fn prepare( .{ o.streams, gibs(asked), window, gibs(room), streams }, ); } + // a prompt cache a flag asked for claims its bytes beside the streams, unless it may pass the cap + const flag: ?usize = if (o.cache_gib) |g| @intFromFloat(g * (1 << 30)) else null; + const claim = prompt_rows.claim(flag, o.cache_over_cap); + // the policy's rows come back when their larger plan holds that claim and the streams the fallback admitted + var opened: prompt_rows.Opened = .{ .rows = want }; + const plans: Plans = .{ .e = e, .d = d, .streams = streams, .capacity = capacity, .readouts = readouts }; + if (small) |s| opened = prompt_rows.settled(plans, want, s, room, claim) catch |err| return steps.refuseAll( + a, + problem, + "the native HIP engine cannot count its scratch ({s})", + .{@errorName(err)}, + ); + e.o.prompt_rows = opened.rows; const need = served(e, d, streams, capacity, readouts) catch |err| return steps.refuseAll( a, problem, @@ -291,7 +322,7 @@ fn prepare( const left = room - need; const policy = dev.policy; const keep: usize = policy.slots; - var budget: usize = if (o.cache_gib) |g| @intFromFloat(g * (1 << 30)) else left; + var budget: usize = flag orelse left; if (budget > left and !o.cache_over_cap) { return steps.refuseAll( a, @@ -322,8 +353,9 @@ fn prepare( ); const own_bytes = if (d) |x| x.streamBytes() else 0; const lane = gibs(state.Caches.deviceBytes(e.model(), capacity) + e.model().taps.ringBytes(e.model().spec.hidden) + pages.pagesFor(capacity) * memory.pageBytes(e.weights.spec, e.act.size()) + own_bytes); - const startup = try std.fmt.allocPrint(gpa, "HIP {s} device {d}, rank {d} of {d}: model {d:.2} GiB{s}; {d} stream{s} at once, {d:.2} GiB each at a {d}-token window, of {d:.1} GiB left after a {d:.1} GiB reserve; prompt cache {d:.2} GiB ({d} pages, {d} snapshots); prompts in {d}-row chunks", .{ - hip.kernels.arch, dev.index, o.rank, o.world, gibs(model), if (d != null) " with its DFlash2 drafter" else "", streams, if (streams == 1) "" else "s", lane, window, gibs(room), gibs(reserve), gibs(budget), cache.pages, cache.snaps, prefix.chunk, + var why: [96]u8 = undefined; + const startup = try std.fmt.allocPrint(gpa, "HIP {s} device {d}, rank {d} of {d}: model {d:.2} GiB{s}; {d} stream{s} at once, {d:.2} GiB each at a {d}-token window, of {d:.1} GiB left after a {d:.1} GiB reserve; prompt cache {d:.2} GiB ({d} pages, {d} snapshots); prompts in {d}-row chunks{s}", .{ + hip.kernels.arch, dev.index, o.rank, o.world, gibs(model), if (d != null) " with its DFlash2 drafter" else "", streams, if (streams == 1) "" else "s", lane, window, gibs(room), gibs(reserve), gibs(budget), cache.pages, cache.snaps, opened.rows, opened.note(&why), }); return .{ .e = e, .streams = streams, .cache = cache, .startup = startup, .joint = head, .bounds = if (readouts) |r| r.bounds else undefined, .draft = d }; } diff --git a/zig/src/families/qwen3_5/backend/hip/engine/prompt_rows.zig b/zig/src/families/qwen3_5/backend/hip/engine/prompt_rows.zig new file mode 100644 index 00000000000..55846f8531a --- /dev/null +++ b/zig/src/families/qwen3_5/backend/hip/engine/prompt_rows.zig @@ -0,0 +1,167 @@ +//! The rows a prompt pass takes: what the policy asks, the fallback that keeps a stream or a cache, a piece, a step. + +const std = @import("std"); +const hip = @import("hip"); +const prefix = @import("prefix.zig"); +const fwd = @import("../forward/forward.zig"); + +/// The rows a policy asks of a prompt pass: its step, no less than the rows a chunk takes while other streams decode. +pub fn asked(policy: hip.Policy) usize { + return @max(policy.prefill_step, policy.fill_rows); +} + +/// The rows an engine opens with: the policy's, or the chunk for a bf16 checkpoint (rocBLAS bits follow the rows). +pub fn opening(policy: hip.Policy, plain: bool) usize { + return if (plain) prefix.chunk else asked(policy); +} + +/// The smaller rows admission starts from: the plain step behind a GPU's larger default, if below `want` (null: none). +pub fn fallback(policy: hip.Policy, plain_step: ?u32, want: usize) ?usize { + const rows: usize = @max(plain_step orelse return null, policy.fill_rows); + return if (rows < want) rows else null; +} + +/// The rows a server took; the rows its policy asked where the fallback's replaced them, and whether for the cache. +pub const Opened = struct { + rows: usize, + narrowed: ?usize = null, + cache: bool = false, + + /// What the startup line says after the rows taken: the rows asked for and what they would cost, if they gave way. + pub fn note(o: Opened, buf: []u8) []const u8 { + const n = o.narrowed orelse return ""; + const cost = if (o.cache) "leave less than the prompt cache" else "admit fewer of the streams"; + return std.fmt.bufPrint(buf, " ({d}-row chunks would {s} asked for)", .{ n, cost }) catch ""; + } +}; + +/// Bytes a prompt cache claims beside the streams: what `--prompt-cache-gib` gave, or 0 when it may pass the cap. +pub fn claim(flag: ?u64, over_cap: bool) u64 { + return if (over_cap) 0 else flag orelse 0; +} + +/// `want` rows, or `small` when the larger scratch costs a stream `small`'s admits (`beside` bytes) or the `cache`. +pub fn settle(want: usize, small: usize, room: u64, cache: u64, larger: u64, smaller: u64, beside: u64) Opened { + // the admitted streams count as one: the larger scratch holds them all, or costs one the server asked for + if (hip.policy.narrows(room, 0, larger, smaller, beside, 1)) return .{ .rows = small, .narrowed = want }; + // a cache a flag asked for is sized after the rows from what they leave: it rides as `narrows`'s slots + const lost = hip.policy.narrows(room, cache, larger, smaller, beside, 1); + return if (lost) .{ .rows = small, .narrowed = want, .cache = true } else .{ .rows = want }; +} + +/// The admitted streams' device bytes at some prompt rows: the whole plan, and the share the prompt scratch takes. +pub const Plan = struct { whole: u64, prompt: u64 }; + +/// `settle` over the streams' plans at `small` and `want` rows (`plans.at(rows)`), with all that grows with the rows. +pub fn settled(plans: anytype, want: usize, small: usize, room: u64, cache: u64) !Opened { + const at_small: Plan = try plans.at(small); + const beside = at_small.whole - at_small.prompt; + // what grows with the rows beside the prompt scratch (a drafter's tap rings) rides with the larger scratch + const larger = (try plans.at(want)).whole - beside; + return settle(want, small, room, cache, larger, at_small.prompt, beside); +} + +/// Rows a plain prompt's piece takes when nothing decodes: the policy's, at most the `held` rows a pass takes. +pub fn idle(held: usize, policy: hip.Policy) usize { + return @min(held, asked(policy)); +} + +/// Rows a pass takes through a layer at once: the policy's once they pass SPAN, at most the `held` rows of a pass. +pub fn step(held: usize, policy: hip.Policy) usize { + return @min(held, @max(fwd.SPAN, asked(policy))); +} + +const T = std.testing; + +fn igpu() hip.Policy { + return hip.Policy.forCaps(hip.Caps.of("gfx1151").?, 1); +} + +test "a lone gfx1151 opens with its policy's 4,096 rows; gfx1100, a group and prefill_step=1024 keep 1,024" { + try T.expectEqual(@as(usize, 4096), opening(igpu(), false)); + try T.expectEqual(@as(usize, 1024), opening(hip.Policy.forCaps(hip.Caps.of("gfx1100").?, 1), false)); + try T.expectEqual(@as(usize, 1024), opening(hip.Policy.forCaps(hip.Caps.of("gfx1151").?, 2), false)); + var notes: hip.Policy.Notes = .{}; + const flagged = try hip.Policy.resolveFrom(igpu(), "prefill_step=1024", .none, ¬es); + try T.expectEqual(@as(usize, 1024), opening(flagged, false)); + try T.expectEqual(@as(usize, prefix.chunk), opening(igpu(), true)); // a bf16 checkpoint keeps the chunk +} + +test "admission has smaller rows to start from only behind a GPU's larger default step" { + try T.expectEqual(@as(?usize, 1024), fallback(igpu(), 1024, 4096)); + try T.expectEqual(@as(?usize, null), fallback(igpu(), null, 4096)); // a group, or a step a flag asked for + try T.expectEqual(@as(?usize, null), fallback(igpu(), 1024, prefix.chunk)); // a bf16 checkpoint's chunk +} + +test "the policy's rows give way only when their scratch costs a stream the server asked for" { + const gib: u64 = 1 << 30; + // the streams fit beside either scratch, the second time to the byte: the policy's rows stay + try T.expectEqual(Opened{ .rows = 4096 }, settle(4096, 1024, 40 * gib, 0, 5 * gib, 1 * gib, 20 * gib)); + try T.expectEqual(Opened{ .rows = 4096 }, settle(4096, 1024, 25 * gib, 0, 5 * gib, 1 * gib, 20 * gib)); + // they fit only beside the smaller scratch: the fallback's rows, and the rows they replaced for the startup line + try T.expectEqual(Opened{ .rows = 1024, .narrowed = 4096 }, settle(4096, 1024, 25 * gib - 1, 0, 5 * gib, 1 * gib, 20 * gib)); + try T.expectEqual(Opened{ .rows = 1024, .narrowed = 4096 }, settle(4096, 1024, 21 * gib, 0, 30 * gib, 1 * gib, 20 * gib)); + // a cache that fits beside neither scratch changes none of it: the plan it is refused from must fit the room + try T.expectEqual(Opened{ .rows = 1024, .narrowed = 4096 }, settle(4096, 1024, 21 * gib, 9 * gib, 30 * gib, 1 * gib, 20 * gib)); +} + +test "a prompt cache a flag asked for that fits beside the fallback's scratch alone takes the fallback's rows" { + const gib: u64 = 1 << 30; + const for_cache: Opened = .{ .rows = 1024, .narrowed = 4096, .cache = true }; + // 40 GiB of room and 20 of streams: the policy's scratch leaves 15 GiB, the fallback's 19; both ends of the band + try T.expectEqual(for_cache, settle(4096, 1024, 40 * gib, claim(15 * gib + 1, false), 5 * gib, 1 * gib, 20 * gib)); + try T.expectEqual(for_cache, settle(4096, 1024, 40 * gib, claim(19 * gib, false), 5 * gib, 1 * gib, 20 * gib)); +} + +test "with no prompt cache asked for, the policy's rows stay wherever their scratch holds the streams" { + const gib: u64 = 1 << 30; + try T.expectEqual(Opened{ .rows = 4096 }, settle(4096, 1024, 40 * gib, claim(null, false), 5 * gib, 1 * gib, 20 * gib)); +} + +test "a prompt cache that fits beside the policy's scratch keeps the policy's rows" { + const gib: u64 = 1 << 30; + try T.expectEqual(Opened{ .rows = 4096 }, settle(4096, 1024, 40 * gib, claim(15 * gib, false), 5 * gib, 1 * gib, 20 * gib)); +} + +test "a prompt cache that may pass the cap weighs nothing: the policy's rows stay" { + const gib: u64 = 1 << 30; + try T.expectEqual(Opened{ .rows = 4096 }, settle(4096, 1024, 40 * gib, claim(16 * gib, true), 5 * gib, 1 * gib, 20 * gib)); +} + +/// The engine's plan for four streams in small: a MiB a prompt row, 4 GiB a stream, and a drafter's bytes beside each. +const Drafted = struct { + drafter: bool, + + pub fn at(p: Drafted, rows: usize) !Plan { + const mib: u64 = 1 << 20; + const r: u64 = rows; + // a 256 MiB context, and a tap ring of 64 KiB a row: the drafter's 2,048-row window past the rows a pass writes + const drafts: u64 = if (p.drafter) 256 * mib + (2048 + r) * 64 * 1024 else 0; + return .{ .whole = r * mib + 4 * (4096 * mib + drafts), .prompt = r * mib }; + } +}; + +test "a drafter's contexts and tap rings count with a prompt cache's claim, the larger rows' longer rings too" { + const gib: u64 = 1 << 30; + const drafted: Drafted = .{ .drafter = true }; + const alone: Drafted = .{ .drafter = false }; + // 30 GiB and an 8 GiB cache: the drafter's 2.5 GiB at 4,096 rows leave too little for it, its 1.75 at 1,024 do not + const for_cache: Opened = .{ .rows = 1024, .narrowed = 4096, .cache = true }; + try T.expectEqual(for_cache, try settled(drafted, 4096, 1024, 30 * gib, claim(8 * gib, false))); + try T.expectEqual(Opened{ .rows = 4096 }, try settled(alone, 4096, 1024, 30 * gib, claim(8 * gib, false))); + // 22 GiB and no cache: the 22.5 GiB plan at 4,096 rows costs a stream, the 18.75 GiB at 1,024 holds all four + const for_streams: Opened = .{ .rows = 1024, .narrowed = 4096 }; + try T.expectEqual(for_streams, try settled(drafted, 4096, 1024, 22 * gib, claim(null, false))); + try T.expectEqual(Opened{ .rows = 4096 }, try settled(alone, 4096, 1024, 22 * gib, claim(null, false))); + // the startup line names the rows that gave way and why + var why: [96]u8 = undefined; + try T.expectEqualStrings(" (4096-row chunks would leave less than the prompt cache asked for)", for_cache.note(&why)); + try T.expectEqualStrings(" (4096-row chunks would admit fewer of the streams asked for)", for_streams.note(&why)); +} + +test "a pass crosses a layer in the policy's rows once they pass the span, never in more rows than it holds" { + try T.expectEqual(@as(usize, 4096), step(4096, igpu())); // a lone gfx1151's chunk is one step a layer + try T.expectEqual(@as(usize, 1024), step(1024, igpu())); // narrowed to the fallback's rows + try T.expectEqual(@as(usize, 1024), step(1024, .{})); + try T.expectEqual(@as(usize, fwd.SPAN), step(9000, .{})); // a check's longest prompt keeps the span +} diff --git a/zig/src/families/qwen3_5/backend/hip/engine/scratch.zig b/zig/src/families/qwen3_5/backend/hip/engine/scratch.zig index 83117340c65..e3402dbd5e3 100644 --- a/zig/src/families/qwen3_5/backend/hip/engine/scratch.zig +++ b/zig/src/families/qwen3_5/backend/hip/engine/scratch.zig @@ -20,7 +20,7 @@ pub fn prompts(e: *Engine, rows: usize, capacity: usize) !usize { var arena = hip.Arena.counting(); const o = counting(e, &arena); // every take grows with the rows and the keys walked, so the last chunk of a full window is the largest - const hidden = try fwd.span(o, m, &caches, 0, rows, capacity - rows, null); + const hidden = (try fwd.spanFor(o, m, &caches, 0, rows, capacity - rows, e.stepRows(), null, .{ .logits = true, .readers = true })).rows; const y = try o.project(fwd.at(hidden, (rows - 1) * m.spec.hidden), m.head, 1, false); _ = try e.wholeRows(o, y, 1); return arena.peak; diff --git a/zig/src/families/qwen3_5/backend/hip/engine/vision.zig b/zig/src/families/qwen3_5/backend/hip/engine/vision.zig index 3d30de8e402..ca64492d89c 100644 --- a/zig/src/families/qwen3_5/backend/hip/engine/vision.zig +++ b/zig/src/families/qwen3_5/backend/hip/engine/vision.zig @@ -24,19 +24,11 @@ pub const Vision = struct { defer arena.deinit(); const aa = arena.allocator(); const cfg = try read(aa, io, dir, "config.json") orelse return error.NoQwenVision; - if (!declared(aa, cfg)) return error.NoQwenVision; + if (!api.visionDeclared(aa, cfg)) return error.NoQwenVision; // a declared vision_config the parser cannot read is a broken tower, not a text checkpoint return try vl.Config.parse(aa, cfg, try read(aa, io, dir, "preprocessor_config.json"), try read(aa, io, dir, "processor_config.json")) orelse error.UnsupportedQwenVision; } - /// Whether config.json names a vision_config other than null: absent or null is a text-only checkpoint. - fn declared(a: std.mem.Allocator, cfg: []const u8) bool { - const doc = std.json.parseFromSliceLeaky(std.json.Value, a, cfg, .{}) catch return true; - if (doc != .object) return true; - const vc = doc.object.get("vision_config") orelse return false; - return vc != .null; - } - /// Aggregate image tokens also bound each independently encoded image; scratch is fixed at open. pub fn patchCapacity(limits: api.VisionOpen) !usize { if (limits.image_tokens == 0 or limits.image_tokens > shared.max_patches / 4 or limits.max_images == 0 or limits.max_images > 64) return error.BadImageLimits; @@ -262,14 +254,13 @@ test "Qwen HIP vision memory matches fixed weights and receipt/default scratch e } } -test "only an absent or null vision_config is a text-only checkpoint; another value is a broken tower" { - var arena = std.heap.ArenaAllocator.init(std.testing.allocator); - defer arena.deinit(); - const a = arena.allocator(); - try std.testing.expect(!Vision.declared(a, "{\"model_type\":\"qwen3_5\"}")); - try std.testing.expect(!Vision.declared(a, "{\"vision_config\":null}")); - try std.testing.expect(Vision.declared(a, "{\"vision_config\":[]}")); - try std.testing.expect(Vision.declared(a, "{\"vision_config\":\"x\"}")); - try std.testing.expect(Vision.declared(a, "{\"vision_config\":{}}")); - try std.testing.expect(Vision.declared(a, "not json")); +test "--vision on a checkpoint without a vision_config is refused by name before the HIP runtime opens" { + const a = std.testing.allocator; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "config.json", .data = "{\"model_type\":\"qwen3_5\"}" }); + const dir = try tmp.dir.realPathFileAlloc(std.testing.io, ".", a); + defer a.free(dir); + // the runtime, the context and the weights open after the gate: a refusal here held none of them + try std.testing.expectError(error.VisionWithoutTower, @import("engine.zig").Engine.load(a, std.testing.io, dir, .{ .vision = .{} })); } diff --git a/zig/src/families/qwen3_5/backend/hip/forward/forward.zig b/zig/src/families/qwen3_5/backend/hip/forward/forward.zig index bb1ab0a6ff1..de827bba30b 100644 --- a/zig/src/families/qwen3_5/backend/hip/forward/forward.zig +++ b/zig/src/families/qwen3_5/backend/hip/forward/forward.zig @@ -1,4 +1,4 @@ -//! A prompt span through every layer in steps of SPAN rows, on the prefill formulas. +//! A prompt span through every layer in steps of SPAN rows or the rows a caller names, on the prefill formulas. const std = @import("std"); const hip = @import("hip"); @@ -56,11 +56,11 @@ pub const Final = struct { /// The span's final-normed rows (len, hidden) in the activation dtype; `ids` are int32 token ids on the device. pub fn span(ops: Ops, m: *const view.Model, caches: *state.Caches, ids: u64, len: usize, pos0: usize, trace: ?Trace) Error!Tensor { - return (try spanFor(ops, m, caches, ids, len, pos0, trace, .{ .logits = true, .readers = true })).rows; + return (try spanFor(ops, m, caches, ids, len, pos0, SPAN, trace, .{ .logits = true, .readers = true })).rows; } -/// `span` for a caller reading `reads`: past its keys and values, the last layer runs only rows a reader reaches. -pub fn spanFor(ops: Ops, m: *const view.Model, caches: *state.Caches, ids: u64, len: usize, pos0: usize, trace: ?Trace, reads: Reads) Error!Final { +/// `span` in steps of `step` rows read as `reads`: past its keys and values, the last layer runs only the rows read. +pub fn spanFor(ops: Ops, m: *const view.Model, caches: *state.Caches, ids: u64, len: usize, pos0: usize, step: usize, trace: ?Trace, reads: Reads) Error!Final { // prefill's kernels at any row count: a prompt's rows have the same bits fresh, resumed or in steps var o = ops; o.prefill = true; @@ -69,8 +69,8 @@ pub fn spanFor(ops: Ops, m: *const view.Model, caches: *state.Caches, ids: u64, const from = prompt_tail.of(m, o, traced).first(reads, len); const x = try take(o, m.act, len * s.hidden); var start: usize = 0; - while (start < len) : (start += SPAN) { - const rows = @min(SPAN, len - start); + while (start < len) : (start += step) { + const rows = @min(step, len - start); try o.embedRows(m.embed, ids + start * 4, rows, at(x, start * s.hidden)); } if (m.frame) |frame| { @@ -82,8 +82,8 @@ pub fn spanFor(ops: Ops, m: *const view.Model, caches: *state.Caches, ids: u64, // rows before `kept` reach no reader past the last layer's keys and values const kept = if (index + 1 == m.layers.len) from else 0; start = 0; - while (start < len) : (start += SPAN) { - const rows = @min(SPAN, len - start); + while (start < len) : (start += step) { + const rows = @min(step, len - start); const mark = o.arena.mark(); defer o.arena.release(mark); const xs = at(x, start * s.hidden); diff --git a/zig/src/families/qwen3_5/backend/hip/forward/prompt_tail_test.zig b/zig/src/families/qwen3_5/backend/hip/forward/prompt_tail_test.zig index b599ec80158..870e8ccc16d 100644 --- a/zig/src/families/qwen3_5/backend/hip/forward/prompt_tail_test.zig +++ b/zig/src/families/qwen3_5/backend/hip/forward/prompt_tail_test.zig @@ -142,6 +142,11 @@ fn full(i: usize, format: Format) view.Full { /// The launches of one span of `len` rows from `pos0` over two full layers, read as `reads`; the last's in `last`. fn record(len: usize, pos0: usize, reads: fwd.Reads, last: Format) !fwd.Final { + return recordIn(len, pos0, fwd.SPAN, reads, last); +} + +/// `record` in steps of `step` rows a layer, as an engine opened with that many prompt rows runs a chunk. +fn recordIn(len: usize, pos0: usize, step: usize, reads: fwd.Reads, last: Format) !fwd.Final { Mock.rt.api.hipModuleLaunchKernel = Mock.launch; Mock.rt.api.hipModuleGetFunction = Mock.function; Mock.count = 0; @@ -180,7 +185,7 @@ fn record(len: usize, pos0: usize, reads: fwd.Reads, last: Format) !fwd.Final { var caches: state.Caches = .{ .layers = &cache_layers, .total = 4096, .desc = .{ .r = &Mock.rt, .ptr = @ptrFromInt(0x6_0000_0000), .len = 1 }, .pool = &pool }; var arena = hip.Arena.counting(); const o: hip.ops.Ops = .{ .l = &l, .bf16 = true, .stream = @ptrFromInt(0x10), .arena = &arena }; - return fwd.spanFor(o, &m, &caches, 0x7_0000_0000, len, pos0, null, reads); + return fwd.spanFor(o, &m, &caches, 0x7_0000_0000, len, pos0, step, null, reads); } /// The recorded launches of kernel `kernel` ("product": any product's) and weight `weight` where nonzero, in order. @@ -321,3 +326,27 @@ test "qwen3_5 hip prompt tail: across a step edge, the read row's step runs main try T.expect(!std.mem.eql(u8, w[0].name, got[0].name)); } } + +test "qwen3_5 hip prompt tail: a 4,096-row chunk at the 4,096-row step is one step a layer, its tail the last tile" { + var buf: [16]Launch = undefined; + const kept = try recordIn(4096, 0, 4096, .{ .logits = true, .readers = false }, .mlx); + try T.expectEqual(@as(usize, 4096 - 128), kept.from); + // one launch a product over the whole chunk, where SPAN would cut it in two + try productRows(0, &all_slots, 4096); + try productRows(1, &.{ slot.k, slot.v }, 4096); + try productRows(1, &query_slots, 128); + const att = launches(&buf, "fa_paged", 0); + try T.expectEqual(@as(usize, 2), att.len); + try expectAttention(4096, 0, 4096, att[0]); + try expectAttention(128, 3968, 4096, att[1]); + try T.expectEqual(@as(i64, 128), launches(&buf, "rms_rows", final_norm)[0].rows); + // 4,200 rows: the tail from 4,072 is the first step's last 24 rows and all 104 of the second + _ = try recordIn(4200, 0, 4096, .{ .logits = true, .readers = false }, .mlx); + const two = launches(&buf, "fa_paged", 0); + try T.expectEqual(@as(usize, 4), two.len); + try expectAttention(24, 4072, 4096, two[2]); + try expectAttention(104, 4096, 4200, two[3]); + // the same chunk through `record` (SPAN) is two steps a layer: the step is the caller's + _ = try record(4096, 0, .{ .logits = true, .readers = false }, .mlx); + try T.expectEqual(@as(usize, 2), launches(&buf, "page_write", 0x4_1000_0000).len); +} diff --git a/zig/src/families/qwen3_5/config_checks.zig b/zig/src/families/qwen3_5/config_checks.zig index cdb193515af..d9135ae07f2 100644 --- a/zig/src/families/qwen3_5/config_checks.zig +++ b/zig/src/families/qwen3_5/config_checks.zig @@ -11,7 +11,7 @@ pub const Error = error{ BadEos, TooManyEos, MissingEos, InvalidConfig, InvalidR /// The most end ids a checkpoint may declare across config.json and generation_config.json. pub const max_eos = 8; comptime { - std.debug.assert(eos_ids.qwen35_hip.max.? == max_eos); + std.debug.assert(eos_ids.qwen35.max.? == max_eos); } /// The most decoder layers a config may declare. @@ -98,10 +98,10 @@ pub fn products(s: Sizes) Error!void { for (widths) |w| if (w > limit) return error.InvalidConfig; } -/// The HIP loader's end ids by core's qwen35_hip policy: root, text tower and generation_config.json, below `vocab`. +/// The HIP loader's end ids by core's qwen35 policy: the root's, the tower's only when it gave none, then generation's. pub fn eos(out: *[max_eos]u32, root: std.json.ObjectMap, tower: std.json.ObjectMap, generation: ?std.json.ObjectMap, vocab: usize) Error![]const u32 { const gen: std.json.Value = if (generation) |g| .{ .object = g } else .null; - return eos_ids.collect(out, eos_ids.qwen35_hip, .{ .object = root }, .{ .object = tower }, gen, vocab) catch |e| return switch (e) { + return eos_ids.collect(out, eos_ids.qwen35, .{ .object = root }, .{ .object = tower }, gen, vocab) catch |e| return switch (e) { error.BadEosValue => error.BadEos, else => |x| x, }; diff --git a/zig/src/families/qwen3_5/cuda_attention.zig b/zig/src/families/qwen3_5/cuda_attention.zig index eee13a817f1..27dc699b906 100644 --- a/zig/src/families/qwen3_5/cuda_attention.zig +++ b/zig/src/families/qwen3_5/cuda_attention.zig @@ -1,5 +1,21 @@ //! A batch with a paged stream keys its captured graph apart; the kernels read each stream through its own layout. const std = @import("std"); +const environment = @import("sys").environment; + +const all_rows_name = "TF_QWEN35_ATTN_ALL_ROWS"; + +pub fn parseAllRows(raw: ?[]const u8) !bool { + return environment.value(bool, all_rows_name, raw, false); +} + +pub fn allRows() !bool { + return environment.read(bool, all_rows_name, false); +} + +/// Only a BF16 decode window wider than one row takes the single all-length rows launch. +pub fn rowsOnly(enabled: bool, prompt: bool, total: usize) bool { + return enabled and !prompt and total > 1; +} pub fn hasPages(segs: anytype) bool { for (segs) |sg| if (sg.pt != 0) return true; @@ -14,6 +30,20 @@ test "Qwen attention path: unpaged, paged and mixed segment tables" { try std.testing.expect(hasPages(@as([]const Seg, &.{ .{ .pt = 0 }, .{ .pt = 0x4000 } }))); } +test "Qwen attention path: all-rows flag is strict and defaults off" { + for ([_]?[]const u8{ null, "", " ", "\t", " \t\r\n" }) |raw| try std.testing.expect(!try parseAllRows(raw)); + try std.testing.expect(!try parseAllRows("0")); + try std.testing.expect(try parseAllRows("1")); + for ([_][]const u8{ "2", "yes", "on", "true", "00", "1 " }) |raw| try std.testing.expectError(error.InvalidEnvironment, parseAllRows(raw)); +} + +test "Qwen attention path: all-rows opt-in is limited to multi-row decode windows" { + for ([_]bool{ false, true }) |prompt| for ([_]usize{ 1, 4, 8, 16 }) |total| { + try std.testing.expect(!rowsOnly(false, prompt, total)); + try std.testing.expectEqual(!prompt and total > 1, rowsOnly(true, prompt, total)); + }; +} + test "Qwen attention path: layout is part of every captured shape key" { const Shape = @import("cuda_shapes.zig").Shape; for (1..129) |rows| for (1..rows + 1) |segments| for ([_]u8{ 1, 2, 4, 8, 16 }) |slots| { diff --git a/zig/src/families/qwen3_5/cuda_bf16_bytes.zig b/zig/src/families/qwen3_5/cuda_bf16_bytes.zig index f6700928b4e..8287f77f027 100644 --- a/zig/src/families/qwen3_5/cuda_bf16_bytes.zig +++ b/zig/src/families/qwen3_5/cuda_bf16_bytes.zig @@ -21,8 +21,9 @@ pub fn textWeightBytes(a: std.mem.Allocator, io: std.Io, dir: []const u8) !?u64 return total; } -/// A BF16 chat tower's weights and one call's scratch; 0 for other formats (files count it) and for Clef. -pub fn visionBytes(a: std.mem.Allocator, io: std.Io, dir: []const u8) !u64 { +/// A BF16 chat tower's weights and one call's scratch on rank 0, which holds it; 0 for other formats and for Clef. +pub fn visionBytes(a: std.mem.Allocator, io: std.Io, dir: []const u8, rank: u32, _: u32) !u64 { + if (rank != 0) return 0; const g = geometry.Geometry.read(a, io, dir) catch return 0; if (!g.bf16 or @import("cuda_decide.zig").present(a, io, dir)) return 0; const v = @import("qwen_vision"); @@ -114,19 +115,19 @@ test "BF16 chat preflight: the tower's weights and scratch, none for a decision defer a.free(dir); const v = @import("qwen_vision"); const c = (try v.Settings.read(a, io, dir)).?.tower; - try std.testing.expectEqual(@as(u64, v.Tower.weightBytes(c) + v.Tower.scratchBytes(c, v.max_patches)), try visionBytes(a, io, dir)); + try std.testing.expectEqual(@as(u64, v.Tower.weightBytes(c) + v.Tower.scratchBytes(c, v.max_patches)), try visionBytes(a, io, dir, 0, 1)); // with a joint head beside it, --vision is the decision backbone's refusal (cuda_decide), not a tower budget try tmp.dir.writeFile(io, .{ .sub_path = @import("cuda_decide.zig").head_file, .data = "{}" }); - try std.testing.expectEqual(@as(u64, 0), try visionBytes(a, io, dir)); + try std.testing.expectEqual(@as(u64, 0), try visionBytes(a, io, dir, 0, 1)); try tmp.dir.deleteFile(io, @import("cuda_decide.zig").head_file); // an unreadable tower (14-pixel patches) counts nothing, so preflight leaves its refusal to the family's open const patch14 = try std.mem.replaceOwned(u8, a, lighton, "\"patch_size\": 16", "\"patch_size\": 14"); defer a.free(patch14); try tmp.dir.writeFile(io, .{ .sub_path = "config.json", .data = patch14 }); - try std.testing.expectEqual(@as(u64, 0), try visionBytes(a, io, dir)); + try std.testing.expectEqual(@as(u64, 0), try visionBytes(a, io, dir, 0, 1)); // an MLX checkpoint's files count its tower already const mlx = try std.mem.replaceOwned(u8, a, config_text, "\"tie_word_embeddings\":false,", "\"tie_word_embeddings\":false,\"quantization\":{\"group_size\":64,\"bits\":4},"); defer a.free(mlx); try tmp.dir.writeFile(io, .{ .sub_path = "config.json", .data = mlx }); - try std.testing.expectEqual(@as(u64, 0), try visionBytes(a, io, dir)); + try std.testing.expectEqual(@as(u64, 0), try visionBytes(a, io, dir, 0, 1)); } diff --git a/zig/src/families/qwen3_5/cuda_draft.zig b/zig/src/families/qwen3_5/cuda_draft.zig index 63a2fa64adf..bb3f5c3e238 100644 --- a/zig/src/families/qwen3_5/cuda_draft.zig +++ b/zig/src/families/qwen3_5/cuda_draft.zig @@ -27,6 +27,7 @@ pub const Config = @import("cuda_draft_config.zig").Config; pub const frame = @import("cuda_draft_frame.zig"); pub const memory = @import("cuda_draft_memory.zig"); pub const spine = @import("cuda_dspine_frame.zig"); +pub const graphs = @import("cuda_draft_graphs.zig"); const Fns = struct { gather_taps: cuda.Function, gather_rows: cuda.Function, dyn_conv: cuda.Function, norm_rope: cuda.Function, ring_put: cuda.Function, attn: cuda.Function, dyn_conv_batch: cuda.Function, norm_rope_batch: cuda.Function, mask_rows: cuda.Function, attn_partial: cuda.Function, attn_merge: cuda.Function }; /// qwen35_draft.cu's TapRows. @@ -115,6 +116,8 @@ pub const Draft = struct { target_taps: usize = 0, /// TF_QWEN_KV_PAGES: a stream's ring is a view of its target lane's run (null: the contexts own theirs). ring_of: ?RingOf = null, + graphs: graphs.Graphs = .{}, + pub const TapRows = @import("cuda_draft.zig").TapRows; /// all: every stream is a pool lane (TF_QWEN_KV_PAGES_ALL), so the drafter keeps no ring of its own. pub const RingOf = struct { ctx: *anyopaque, ring: *const fn (*anyopaque, *Stream) ?u64, all: bool = false }; @@ -164,6 +167,7 @@ pub const Draft = struct { try d.pool.append(gpa, ctx); d.startup.warmups += profile.elapsed(io, warm_start); d.startup.load = profile.elapsed(io, started) - d.startup.reserve - d.startup.warmups; + d.graphs.on = c.kind == .dflash2 and graphs.enabled(); return d; } @@ -182,6 +186,7 @@ pub const Draft = struct { } pub fn deinit(d: *Draft) void { + if (graphs.enabled()) d.graphs.deinit(d.gpa); var it = d.streams.valueIterator(); while (it.next()) |ctx| d.drop(ctx.*); d.streams.deinit(d.gpa); @@ -266,6 +271,7 @@ pub const Draft = struct { const started = profile.now(d.io); const previous_times = d.startup; try memory.resize(d, n); + if (graphs.enabled()) d.graphs.clear(d.gpa); // with a pool the other streams' rings are lane runs (all: every stream's) const own = if (d.ring_of) |r| (if (r.all) 0 else @min(n, 1)) else n; try d.pool.ensureTotalCapacity(d.gpa, own); @@ -337,32 +343,13 @@ pub const Draft = struct { const previous = d.projection_role; defer d.projection_role = previous; d.projection_role = if (prompt) .prompt else .live; - const c = d.c; if (rows_) |rs| if (rs.len != n_ or n_ > engine.most_window) return error.BadDraftRows; const span = absorbs.open(d, ctx, start_, n_); // the context's window opened for the rows var start = span.start; var n = span.n; - const e = d.e; while (n > 0) { const rows = @min(n, max_rows); - if (rows_) |rs| { - var tr: TapRows = .{ .n = @intCast(rows), .rows = @splat(0) }; - for (rs, 0..) |r, i| tr.rows[i] = @intCast(r); - try e.run(d.fns.gather_rows, .{ rows, 1, 1 }, .{ 256, 1, 1 }, .{ tap_ring, @as(c_int, @intCast(e.tapRows())), @as(c_longlong, @intCast(start)), tr, @as(c_int, @intCast(c.n_taps * c.hidden)), d.taps_in }); - } else try e.run(d.fns.gather_taps, .{ rows, 1, 1 }, .{ 256, 1, 1 }, .{ tap_ring, @as(c_int, @intCast(e.tapRows())), @as(c_longlong, @intCast(start)), @as(c_int, @intCast(c.n_taps * c.hidden)), d.taps_in }); - try d.proj(d.w.fc, d.taps_in, d.th, rows); - try d.norm(d.th, d.w.hidden_norm, d.thn, rows); - for (d.w.layers, 0..) |l, i| { - if (e.affine.pdl) { - try d.projManySums(&.{ l.k, l.v }, d.thn, &.{ d.kabs, d.vabs }, rows, false); - try d.normRope(d.kabs, l.k_norm, d.kn, rows, c.kv_heads, start); - } else { - try d.projAgain(l.k, d.thn, d.kabs, rows); - try d.normRope(d.kabs, l.k_norm, d.kn, rows, c.kv_heads, start); - try d.projAgain(l.v, d.thn, d.vabs, rows); - } - try e.run(d.fns.ring_put, .{ rows, 1, 1 }, .{ 256, 1, 1 }, .{ d.kn, d.vabs, d.ringK(ctx, i), d.ringV(ctx, i), @as(c_int, @intCast(c.kvWidth())), @as(c_longlong, @intCast(start)), @as(c_int, @intCast(c.ringRows())) }); - } + if (!try graphs.absorb(d, ctx, tap_ring, start, rows, rows_, prompt)) try graphs.absorbRows(d, ctx, tap_ring, start, rows, rows_); start += rows; n -= rows; ctx.end = start; diff --git a/zig/src/families/qwen3_5/cuda_draft_frame.zig b/zig/src/families/qwen3_5/cuda_draft_frame.zig index 396d8ae8b12..efd48d89744 100644 --- a/zig/src/families/qwen3_5/cuda_draft_frame.zig +++ b/zig/src/families/qwen3_5/cuda_draft_frame.zig @@ -6,6 +6,7 @@ const draft = @import("cuda_draft.zig"); const tree = @import("cuda_draft_tree.zig"); const layers = @import("cuda_layers.zig"); const sig = @import("cuda_signatures.zig"); +pub const ql_span = @import("cuda_draft_ql_span.zig"); pub const max_streams = @import("cuda_engine.zig").max_segs; pub const max_rows = max_streams * 16; const lp_words = 43; @@ -89,6 +90,23 @@ pub fn forward(d: anytype, items: []const dr.Hold, contexts: []const *draft.Ctx) errdefer cuda.completion.drain(e.d, e.stream, "a failed DFlash frame did not drain before its pinned staging was reused"); try e.d.check(e.d.api.cuMemcpyHtoDAsync_v2(d.ids, st.ptr, B * 4, e.stream.handle), "cuMemcpyHtoDAsync"); try e.d.check(e.d.api.cuMemcpyHtoDAsync_v2(d.segments, st.ptr + segments_at, items.len * @sizeOf(Segment), e.stream.handle), "cuMemcpyHtoDAsync"); + const rows = items.len * (c.block - 1); + const spanned = try draft.graphs.hold(d, items.len, contexts, narrow(contexts), kernels); + try e.d.check(e.d.api.cuMemcpyDtoHAsync_v2(st.ptr + words_at, d.words, rows * lp_words * 4, e.stream.handle), "cuMemcpyDtoHAsync"); + try e.d.check(e.d.api.cuMemcpyDtoHAsync_v2(st.ptr + hp_at, d.hp, rows * c.rank * 2, e.stream.handle), "cuMemcpyDtoHAsync"); + try e.stream.synchronize(); + if (spanned != null) for (0..rows) |r| { + const w = std.mem.bytesAsSlice(u32, st[words_at + r * lp_words * 4 ..][0 .. lp_words * 4]); + for (w[2..][0..c.topk]) |*id| id.* = columnId(id.*); + }; + try publish(d, items, contexts); +} + +/// A hold frame's kernels, from the embedding to the selector rows; the packed logits when spanned. +fn kernels(d: anytype, streams: usize, contexts: []const *draft.Ctx) !?u64 { + const c = d.c; + const e = d.e; + const B = streams * c.block; try e.embed(d.ids, d.h, B, 0); for (d.w.layers, 0..) |l, i| { try d.norm(d.h, l.input_norm, d.x, B); @@ -108,9 +126,9 @@ pub fn forward(d: anytype, items: []const dr.Hold, contexts: []const *draft.Ctx) try d.projAgain(l.down, d.act, d.o, B); try conv(d, d.o, l.mlp_base, d.h2, d.h, B, 1); } - const rows = items.len * (c.block - 1); + const rows = streams * (c.block - 1); var masked = d.h + c.hidden * 2; - if (items.len > 1) { + if (streams > 1) { try e.run(d.fns.mask_rows, .{ rows, 1, 1 }, .{ 256, 1, 1 }, .{ d.h, d.h2, @as(c_int, @intCast(c.hidden)), @as(c_int, @intCast(c.block)) }); masked = d.h2; } @@ -118,14 +136,7 @@ pub fn forward(d: anytype, items: []const dr.Hold, contexts: []const *draft.Ctx) const spanned = try logitsOf(d, contexts, d.x, d.logits, rows); try e.draws.topkRows(e.stream, spanned orelse d.logits, if (spanned != null) span_width else c.vocab, @intCast(c.topk), d.parts, d.words, rows); try d.proj(d.w.selector, d.x, d.hp, rows); - try e.d.check(e.d.api.cuMemcpyDtoHAsync_v2(st.ptr + words_at, d.words, rows * lp_words * 4, e.stream.handle), "cuMemcpyDtoHAsync"); - try e.d.check(e.d.api.cuMemcpyDtoHAsync_v2(st.ptr + hp_at, d.hp, rows * c.rank * 2, e.stream.handle), "cuMemcpyDtoHAsync"); - try e.stream.synchronize(); - if (spanned != null) for (0..rows) |r| { - const w = std.mem.bytesAsSlice(u32, st[words_at + r * lp_words * 4 ..][0 .. lp_words * 4]); - for (w[2..][0..c.topk]) |*id| id.* = columnId(id.*); - }; - try publish(d, items, contexts); + return spanned; } /// A lane stream's prompt and reply tokens since the last scan: one outside the spans marks the stream wide. @@ -189,7 +200,12 @@ fn head(d: anytype, x: u64, logits: u64, rows: usize) !?u64 { const v = try x3Views(q); break :blk .{ .{ .x3 = v.first }, .{ .x3 = v.tail }, x3_tail_at }; }, - .an, .ql, .bf => return full(d, x, logits, rows), + .ql => |w| blk: { + if (!ql_span.enabled()) return full(d, x, logits, rows); + const v = ql_span.views(w, spans[0][1], tail_tile, spans[1][1]) orelse return full(d, x, logits, rows); + break :blk .{ .{ .ql = v.first }, .{ .ql = v.tail }, tail_tile }; + }, + .an, .bf => return full(d, x, logits, rows), }; const tail_n = spans[1][1] - tail_at; const a = logits; // rows x 98,304, then rows x the tail's columns, then the packed rows x 98,592 diff --git a/zig/src/families/qwen3_5/cuda_draft_graphs.zig b/zig/src/families/qwen3_5/cuda_draft_graphs.zig new file mode 100644 index 00000000000..f16b33182db --- /dev/null +++ b/zig/src/families/qwen3_5/cuda_draft_graphs.zig @@ -0,0 +1,203 @@ +//! Opt-in CUDA graphs of a DFlash2 hold and live absorb: the eager launches, captured, live arguments set each round. +const std = @import("std"); +const cuda = @import("cuda"); +const platform = @import("sys"); +const trace = @import("cuda_launch_trace.zig"); +const graph = cuda.graph; + +/// TF_DFLASH_GRAPH=1 replays a DFlash2 hold and live absorb from CUDA graphs; off by default. +pub fn enabled() bool { + return platform.environment.read(bool, "TF_DFLASH_GRAPH", false) catch false; +} + +const Hold = struct { exec: graph.Exec, spanned: ?u64 }; +const Absorb = struct { source: graph.Graph, exec: graph.Exec, gather: graph.Node, ropes: []graph.Node, rings: []graph.Node }; + +pub const Graphs = struct { + on: bool = false, + holds: std.AutoHashMapUnmanaged(u32, Hold) = .empty, + absorbs: std.AutoHashMapUnmanaged(u32, Absorb) = .empty, + + /// Drops every graph: their captured addresses die with the scratch they name. + pub fn clear(g: *Graphs, gpa: std.mem.Allocator) void { + var holds = g.holds.valueIterator(); + while (holds.next()) |h| h.exec.deinit(); + g.holds.clearRetainingCapacity(); + var absorbs = g.absorbs.valueIterator(); + while (absorbs.next()) |a| dropAbsorb(gpa, a); + g.absorbs.clearRetainingCapacity(); + } + + pub fn deinit(g: *Graphs, gpa: std.mem.Allocator) void { + g.clear(gpa); + g.holds.deinit(gpa); + g.absorbs.deinit(gpa); + } +}; + +fn dropAbsorb(gpa: std.mem.Allocator, a: *Absorb) void { + a.exec.deinit(); + a.source.deinit(); + gpa.free(a.ropes); + gpa.free(a.rings); +} + +fn live(d: anytype) bool { + return enabled() and d.graphs.on and trace.active == null and d.e.learning == null and !d.e.pockets.any(); +} + +fn tapsArgs(d: anytype, ring: u64, start: u64) struct { u64, c_int, c_longlong, c_int, u64 } { + return .{ ring, @as(c_int, @intCast(d.e.tapRows())), @as(c_longlong, @intCast(start)), @as(c_int, @intCast(d.c.n_taps * d.c.hidden)), d.taps_in }; +} + +fn tapRows(d: anytype, rows: usize, rs: []const u32) @TypeOf(d.*).TapRows { + var tr: @TypeOf(d.*).TapRows = .{ .n = @intCast(rows), .rows = @splat(0) }; + for (rs, 0..) |r, i| tr.rows[i] = @intCast(r); + return tr; +} + +fn rowsArgs(d: anytype, ring: u64, start: u64, rows: usize, rs: []const u32) struct { u64, c_int, c_longlong, @TypeOf(d.*).TapRows, c_int, u64 } { + return .{ ring, @as(c_int, @intCast(d.e.tapRows())), @as(c_longlong, @intCast(start)), tapRows(d, rows, rs), @as(c_int, @intCast(d.c.n_taps * d.c.hidden)), d.taps_in }; +} + +fn ropeArgs(d: anytype, w: u64, start: u64) struct { u64, u64, u64, c_int, c_int, c_longlong, @TypeOf(d.c.eps), @TypeOf(d.c.theta) } { + const heads = d.c.kv_heads; + return .{ d.kabs, w, d.kn, @as(c_int, @intCast(heads)), @as(c_int, @intCast(heads * d.c.head_dim)), @as(c_longlong, @intCast(start)), d.c.eps, d.c.theta }; +} + +fn ringArgs(d: anytype, ctx: anytype, layer: usize, start: u64) struct { u64, u64, u64, u64, c_int, c_longlong, c_int } { + return .{ d.kn, d.vabs, d.ringK(ctx, layer), d.ringV(ctx, layer), @as(c_int, @intCast(d.c.kvWidth())), @as(c_longlong, @intCast(start)), @as(c_int, @intCast(d.c.ringRows())) }; +} + +/// One chunk of an absorb: the launches in their eager order. +pub fn absorbRows(d: anytype, ctx: anytype, ring: u64, start: u64, rows: usize, rs: ?[]const u32) !void { + const e = d.e; + const c = d.c; + if (rs) |list| { + try e.run(d.fns.gather_rows, .{ rows, 1, 1 }, .{ 256, 1, 1 }, rowsArgs(d, ring, start, rows, list)); + } else try e.run(d.fns.gather_taps, .{ rows, 1, 1 }, .{ 256, 1, 1 }, tapsArgs(d, ring, start)); + try d.proj(d.w.fc, d.taps_in, d.th, rows); + try d.norm(d.th, d.w.hidden_norm, d.thn, rows); + for (d.w.layers, 0..) |l, i| { + if (e.affine.pdl) { + try d.projManySums(&.{ l.k, l.v }, d.thn, &.{ d.kabs, d.vabs }, rows, false); + try e.run(d.fns.norm_rope, .{ rows * c.kv_heads, 1, 1 }, .{ 32, 1, 1 }, ropeArgs(d, l.k_norm, start)); + } else { + try d.projAgain(l.k, d.thn, d.kabs, rows); + try e.run(d.fns.norm_rope, .{ rows * c.kv_heads, 1, 1 }, .{ 32, 1, 1 }, ropeArgs(d, l.k_norm, start)); + try d.projAgain(l.v, d.thn, d.vabs, rows); + } + try e.run(d.fns.ring_put, .{ rows, 1, 1 }, .{ 256, 1, 1 }, ringArgs(d, ctx, i, start)); + } +} + +fn set(exec: graph.Exec, node: graph.Node, f: cuda.Function, grid: [3]u32, block: u32, args: anytype) !void { + var a: cuda.Args = .{}; + inline for (args) |v| a.add(v); + const cfg: cuda.Config = .{ .grid = .{ .x = grid[0], .y = grid[1], .z = grid[2] }, .block = .{ .x = block, .y = 1, .z = 1 } }; + try exec.setKernel(node, f, cfg, &a); +} + +fn capture(d: anytype, ctx: anytype, ring: u64, start: u64, rows: usize, rs: ?[]const u32) !?Absorb { + const stream = d.e.stream; + try graph.beginCapture(stream, .thread_local); + absorbRows(d, ctx, ring, start, rows, rs) catch |err| { + var broken = graph.endCapture(stream) catch return err; + broken.deinit(); + return err; + }; + var source = try graph.endCapture(stream); + errdefer source.deinit(); + const layers = d.w.layers.len; + const all = try d.gpa.alloc(graph.Node, try source.nodeCount()); + defer d.gpa.free(all); + const ropes = try d.gpa.alloc(graph.Node, layers); + errdefer d.gpa.free(ropes); + const rings = try d.gpa.alloc(graph.Node, layers); + errdefer d.gpa.free(rings); + const want = if (rs != null) d.fns.gather_rows.handle else d.fns.gather_taps.handle; + var gather: ?graph.Node = null; + var nr: usize = 0; + var np: usize = 0; + for (try source.nodes(all)) |node| { + var p: cuda.abi.KernelNodeParams = undefined; + try d.e.d.check(d.e.d.api.cuGraphKernelNodeGetParams_v2(node, &p), "cuGraphKernelNodeGetParams"); + if (p.func == want) { + if (gather != null) return error.BadDraftGraph; + gather = node; + } else if (p.func == d.fns.norm_rope.handle) { + if (nr == layers) return error.BadDraftGraph; + ropes[nr] = node; + nr += 1; + } else if (p.func == d.fns.ring_put.handle) { + if (np == layers) return error.BadDraftGraph; + rings[np] = node; + np += 1; + } + } + if (gather == null or nr != layers or np != layers) return error.BadDraftGraph; + const exec = source.instantiate() catch |err| { + if (err != error.GraphNotPermitted) return err; + source.deinit(); + d.gpa.free(ropes); + d.gpa.free(rings); + return null; + }; + return .{ .source = source, .exec = exec, .gather = gather.?, .ropes = ropes, .rings = rings }; +} + +/// Runs one live chunk from its graph; false: run it eagerly (off, a prompt chunk, or a graph the driver refused). +pub fn absorb(d: anytype, ctx: anytype, ring: u64, start: u64, rows: usize, rs: ?[]const u32, prompt: bool) !bool { + if (prompt or rows > 16 or !live(d)) return false; + const key: u32 = @intCast(rows | @as(usize, @intFromBool(rs != null)) << 8); + const gop = try d.graphs.absorbs.getOrPut(d.gpa, key); + if (!gop.found_existing) { + errdefer _ = d.graphs.absorbs.remove(key); + gop.value_ptr.* = (try capture(d, ctx, ring, start, rows, rs)) orelse { + _ = d.graphs.absorbs.remove(key); + d.graphs.on = false; + return false; + }; + } + const a = gop.value_ptr; + const r: u32 = @intCast(rows); + if (rs) |list| { + try set(a.exec, a.gather, d.fns.gather_rows, .{ r, 1, 1 }, 256, rowsArgs(d, ring, start, rows, list)); + } else try set(a.exec, a.gather, d.fns.gather_taps, .{ r, 1, 1 }, 256, tapsArgs(d, ring, start)); + for (d.w.layers, a.ropes, a.rings, 0..) |l, rope, put, i| { + try set(a.exec, rope, d.fns.norm_rope, .{ r * @as(u32, @intCast(d.c.kv_heads)), 1, 1 }, 32, ropeArgs(d, l.k_norm, start)); + try set(a.exec, put, d.fns.ring_put, .{ r, 1, 1 }, 256, ringArgs(d, ctx, i, start)); + } + try a.exec.launchOn(d.e.stream); + return true; +} + +/// A hold frame's kernels from their graph, keyed by what changes them; returns the packed logits when spanned. +pub fn hold(d: anytype, streams: usize, contexts: anytype, narrow: bool, comptime body: anytype) !?u64 { + if (!live(d)) return body(d, streams, contexts); + const key: u32 = @intCast(streams | @as(usize, @intFromBool(narrow)) << 16 | @as(usize, @backingInt(d.projection_role)) << 17); + if (d.graphs.holds.get(key)) |h| { + try h.exec.launchOn(d.e.stream); + return h.spanned; + } + const stream = d.e.stream; + try graph.beginCapture(stream, .thread_local); + const spanned = body(d, streams, contexts) catch |err| { + var broken = graph.endCapture(stream) catch return err; + broken.deinit(); + return err; + }; + var source = try graph.endCapture(stream); + defer source.deinit(); + var exec = source.instantiate() catch |err| { + if (err != error.GraphNotPermitted) return err; + d.graphs.on = false; + return body(d, streams, contexts); + }; + d.graphs.holds.put(d.gpa, key, .{ .exec = exec, .spanned = spanned }) catch |err| { + exec.deinit(); + return err; + }; + try exec.launchOn(stream); // on failure the cache still owns the graph + return spanned; +} diff --git a/zig/src/families/qwen3_5/cuda_draft_ql_span.zig b/zig/src/families/qwen3_5/cuda_draft_ql_span.zig new file mode 100644 index 00000000000..3917f4fd550 --- /dev/null +++ b/zig/src/families/qwen3_5/cuda_draft_ql_span.zig @@ -0,0 +1,48 @@ +//! Span views of a ModelOpt draft head: the stored tiles, on the whole head's K slices, for NVFP4 and plain FP8. +const cuda = @import("cuda"); +const platform = @import("sys"); +const qmmf = cuda.qmmf; +const Weight = cuda.qlinear.Weight; + +/// TF_DFLASH_QL_SPAN=1 drafts a ModelOpt head over the spans; off by default. +pub fn enabled() bool { + return platform.environment.read(bool, "TF_DFLASH_QL_SPAN", false) catch false; +} + +/// Rows [from, from + n) of a packed FP4 or FP8 weight, `from` on a 64-row tile, summing in the whole weight's slices. +pub fn view(q: qmmf.Weight, from: usize, n: usize) ?qmmf.Weight { + if (from % qmmf.group != 0 or n == 0 or from + n > q.n or q.k % qmmf.group != 0) return null; + var out = q; + switch (q.mode) { + .fp4 => { + out.codes = q.codes + from * q.k / 2; + out.scales = q.scales + from * q.k / 16; + }, + .fp8 => out.codes = q.codes + from * q.k, + .mxfp8, .fp8g, .bf16 => return null, // a short view of these can select another tile kernel + } + out.n = @intCast(n); + out.npad = @intCast((n + 127) / 128 * 128); + return qmmf.pinned(out, qmmf.slices(q)) catch null; +} + +pub const Views = struct { first: Weight, tail: Weight }; + +/// The first span and the tiles holding the tail span, or null when this head must stay whole. +pub fn views(w: Weight, first_n: usize, tail_at: usize, vocab: usize) ?Views { + switch (w) { + .nvfp4 => |q| { + if (q.n != vocab) return null; + const first = view(q, 0, first_n) orelse return null; + const tail = view(q, tail_at, q.n - tail_at) orelse return null; + return .{ .first = .{ .nvfp4 = first }, .tail = .{ .nvfp4 = tail } }; + }, + .fp8 => |q| { + if (q.n != vocab or q.act != 0) return null; + const first = view(q, 0, first_n) orelse return null; + const tail = view(q, tail_at, q.n - tail_at) orelse return null; + return .{ .first = .{ .fp8 = first }, .tail = .{ .fp8 = tail } }; + }, + else => return null, + } +} diff --git a/zig/src/families/qwen3_5/cuda_engine.zig b/zig/src/families/qwen3_5/cuda_engine.zig index 7ff380f43b6..30dbe7b7619 100644 --- a/zig/src/families/qwen3_5/cuda_engine.zig +++ b/zig/src/families/qwen3_5/cuda_engine.zig @@ -79,6 +79,7 @@ pub const Engine = struct { stream: cuda.Stream, mods: [19]cuda.Module, kv8: bool, // attention caches as e4m3 rows with a scale each + attention_all_rows: bool = false, // exact opt-in all-length BF16 rows for multi-row decode windows rope_table: u64 = 0, // YaRN's attention factor and 32 frequencies on the device (cuda_rope.zig); 0: plain rope rope_buf: ?cuda.DeviceBuffer = null, // the table's buffer (cuda_rope_table.zig) fp8: Kv8, @@ -205,6 +206,7 @@ pub const Engine = struct { e.geo = .{ .hid = @intCast(g.hidden), .nk = @intCast(g.k_heads), .nv = @intCast(g.v_heads), .qh = @intCast(g.q_heads), .kvh = @intCast(g.kv_heads), .nl = @intCast(g.deltas()) }; e.verify_rows = most_verify; e.kv8 = kv8; + e.attention_all_rows = try @import("cuda_attention.zig").allRows(); e.rope_table = 0; // plain rope until cuda_rope.zig uploads a YaRN table (the engine starts undefined) e.rope_buf = null; e.window_rows = most_window; @@ -292,12 +294,10 @@ pub const Engine = struct { errdefer recurrent.shutdown(e); e.startup.add(try profile.withCache(e.gpa, io, e, Cache)); } - /// Reserve prompt INT8 workspace before serving; prompt forwards are not graph-captured. pub fn warmPromptInt8(e: *Engine) !void { try e.int8.ensureRows(e, e.scratch_rows); } - /// Every path a request takes, run once now: WDDM stalls a process's first forwards for seconds (a 20 s launch). pub fn warmCache(e: *Engine, warm_cache: *Cache) !void { // Commit the configured prompt and verify ceiling before admission; warmup then reuses it. diff --git a/zig/src/families/qwen3_5/cuda_forward.zig b/zig/src/families/qwen3_5/cuda_forward.zig index 56ab6e16352..16c01482778 100644 --- a/zig/src/families/qwen3_5/cuda_forward.zig +++ b/zig/src/families/qwen3_5/cuda_forward.zig @@ -4,6 +4,7 @@ const E = @import("cuda_engine.zig"); const tap_window = @import("cuda_cache.zig").tap_window; const cuda = @import("cuda"); const sig = @import("cuda_signatures.zig"); +const attention = @import("cuda_attention.zig"); const hooks = @import("cuda_learn_hooks.zig"); const geometry = @import("cuda_geometry.zig"); const modelopt = @import("cuda_modelopt.zig"); @@ -129,8 +130,10 @@ pub fn body(e: *E.Engine, shape: anytype) !void { const rows_fn = if (shape.mt2) (if (shape.paged) e.mt2.paged else e.mt2.whole) else (if (shape.join) e.fp8.attn_rows_join else if (shape.paged) e.fp8.attn_rows else e.fp8.attn_rows8_whole); try launch(e, rows_fn, sig.attn_rows8, .{ groups, max_chunks, g.kv_heads }, .{ if (shape.mt2) @as(usize, 128) else 256, 1, 1 }, rows_args); } else { - try shared(e, if (shape.paged) e.fns.attn_partial else e.fns.attn_partial_whole, sig.attn_partial, .{ total, max_chunks, g.kv_heads }, 128, args); - try shared(e, if (shape.join) e.fns.attn_rows_join else if (shape.paged) e.fns.attn_rows else e.fns.attn_rows_whole, sig.attn_rows, .{ groups, max_chunks, g.kv_heads }, 256, rows_args); + const rows_only = attention.rowsOnly(e.attention_all_rows, prompt, total); + const bf16_rows_args = .{ geo, e.qn, t_segs, t_rows, t_anc, @as(c_int, ai), t_params, @as(f32, 1.0 / 16.0), @as(c_int, @intCast(total)), e.pm, e.pl, e.po, rows_only }; + if (!rows_only) try shared(e, if (shape.paged) e.fns.attn_partial else e.fns.attn_partial_whole, sig.attn_partial, .{ total, max_chunks, g.kv_heads }, 128, args); + try shared(e, if (shape.join) e.fns.attn_rows_join else if (shape.paged) e.fns.attn_rows else e.fns.attn_rows_whole, sig.attn_rows, .{ groups, max_chunks, g.kv_heads }, 256, bf16_rows_args); } try launch(e, e.fns.attn_merge, sig.attn_merge, .{ g.q_heads, total, 1 }, .{ 32, 1, 1 }, .{ geo, e.pm, e.pl, e.po, t_segs, t_rows, t_anc, t_params, e.y }); } @@ -160,7 +163,7 @@ pub fn body(e: *E.Engine, shape: anytype) !void { try e.projMany(&.{ m.gate, m.up }, x0, &.{ e.gate, e.up }, rows, prompt); // one EXL3 group launch } else if (e.affine.pdl and !prompt and e.learning == null and m.gate == .a4 and m.up == .a4) { try e.projMany(&.{ m.gate, m.up }, e.x, &.{ e.gate, e.up }, total, false); - } else { + } else if (try @import("cuda_group_proj.zig").run(e, &.{ m.gate, m.up }, x0, &.{ e.gate, e.up }, rows, prompt)) {} else { try e.projAgain(m.gate, x0, e.gate, rows, prompt); try e.projAgain(m.up, x0, e.up, rows, prompt); } diff --git a/zig/src/families/qwen3_5/cuda_group_proj.zig b/zig/src/families/qwen3_5/cuda_group_proj.zig new file mode 100644 index 00000000000..c504c27dc7c --- /dev/null +++ b/zig/src/families/qwen3_5/cuda_group_proj.zig @@ -0,0 +1,53 @@ +//! TF_Q35_GROUP_PROJ=1: same-input ModelOpt projections in one lane launch, each with its own launch's bits (opt-in). +const cuda = @import("cuda"); +const platform = @import("sys"); +const engine = @import("cuda_engine.zig"); + +const Engine = engine.Engine; +const Proj = engine.Proj; +const group = cuda.qmmf_group; + +/// The switch, read once when the ModelOpt kernels load; default off. +pub fn on() !bool { + return platform.environment.read(bool, "TF_Q35_GROUP_PROJ", false); +} + +/// The grouped kernels when the switch is on and slices meet in clusters (sm_90 on), else null. +pub fn load(lane: *const cuda.qmmf.Lane) !?group.Group { + if (!lane.clusters or !try on()) return null; + return try group.Group.load(lane); +} + +/// The lane weight a ModelOpt projection decodes through (NVFP4, FP8, BF16), else null. +fn laneWeight(p: Proj) ?cuda.qmmf.Weight { + if (p != .ql) return null; + return switch (p.ql) { + .nvfp4, .fp8, .bf16 => |q| q, + else => null, + }; +} + +/// `ls` over x into `outs` as compatible grouped launches, or false: the caller runs separate launches. +pub fn run(e: *Engine, ls: []const Proj, x: u64, outs: []const u64, rows: usize, prompt: bool) !bool { + if (@import("cuda_launch_trace.zig").active != null) return false; // the trace keeps counting separate launches + const k = if (e.mo) |*m| m else return false; + const g = k.group orelse return false; + if (prompt and rows > 16) return false; // modelopt.project's prompt GEMM + if (ls.len > group.most) return false; + var ws: [group.most]cuda.qmmf.Weight = undefined; + for (ls, ws[0..ls.len]) |l, *w| w.* = laneWeight(l) orelse return false; + for (ws[0..ls.len]) |w| if (w.k != ws[0].k) return false; + for (outs, 0..) |out, i| for (outs[i + 1 ..]) |other| if (out == other) return false; + var shapes: [2]group.Shape = undefined; + var count: usize = 0; + var at: usize = 0; + while (at < ls.len) { + var end = at + 1; + while (end < ls.len and ws[end].mode == ws[at].mode) : (end += 1) {} + shapes[count] = group.plan(k.lane, ws[at..end], outs[at..end], rows) orelse return false; + count += 1; + at = end; + } + for (shapes[0..count]) |sh| try g.launch(e.stream, x, rows, ws[0].k, sh, k.lane.pdl); + return true; +} diff --git a/zig/src/families/qwen3_5/cuda_modelopt.zig b/zig/src/families/qwen3_5/cuda_modelopt.zig index da853b39ed4..1e5733f4e28 100644 --- a/zig/src/families/qwen3_5/cuda_modelopt.zig +++ b/zig/src/families/qwen3_5/cuda_modelopt.zig @@ -245,6 +245,7 @@ pub const Kernels = struct { /// Slice partials where no cluster meets them (before sm_90): the most any projection takes below fused_rows. part: ?DeviceBuffer = null, experts: ?cuda.experts.Nvfp4Experts = null, // a MoE's routed experts (cuda_modelopt_experts.zig) + group: ?cuda.qmmf_group.Group = null, // TF_Q35_GROUP_PROJ: grouped same-input projections pub fn load(d: *const cuda.Driver, capability: u32, sms: usize, moe: bool) !Kernels { if (modeloptRefusal(capability) != null) return error.ModeloptNeedsSm80; @@ -257,7 +258,8 @@ pub const Kernels = struct { errdefer pack.unload(); var experts: ?cuda.experts.Nvfp4Experts = if (moe) try cuda.experts.Nvfp4Experts.load(d, sms) else null; errdefer if (experts) |*x| x.unload(); - return .{ .lane = lane, .prompt = prompt, .pack = pack, .embed = try cuda.embed_rows.EmbedRows.load(d), .experts = experts }; + const group = try @import("cuda_group_proj.zig").load(&lane); + return .{ .lane = lane, .prompt = prompt, .pack = pack, .embed = try cuda.embed_rows.EmbedRows.load(d), .experts = experts, .group = group }; } pub fn unload(k: *Kernels) void { diff --git a/zig/src/families/qwen3_5/cuda_projection_many.zig b/zig/src/families/qwen3_5/cuda_projection_many.zig index b9c2142c9f8..97972a5fc39 100644 --- a/zig/src/families/qwen3_5/cuda_projection_many.zig +++ b/zig/src/families/qwen3_5/cuda_projection_many.zig @@ -33,6 +33,7 @@ pub fn projectMany(e: *Engine, ls: []const Proj, x: u64, xs: u64, outs: []const if (l != .a4 or l.inputs() != ls[0].inputs()) break false; } else true; if (!segmented) { + if (try @import("cuda_group_proj.zig").run(e, ls, x, outs, rows, prompt)) return; for (ls, outs, 0..) |l, out, i| try e.project(l, x, xs, out, rows, prompt, params, sums and i == 0); return; } diff --git a/zig/src/families/qwen3_5/cuda_signatures.zig b/zig/src/families/qwen3_5/cuda_signatures.zig index 66087358d20..1631cceffe3 100644 --- a/zig/src/families/qwen3_5/cuda_signatures.zig +++ b/zig/src/families/qwen3_5/cuda_signatures.zig @@ -1,8 +1,8 @@ //! The q35 attention kernels' parameter lists, as their .cu sources declare them. const std = @import("std"); -/// A parameter's kind: the geometry struct, a device pointer, a 32-bit count or a float scale. -pub const Kind = enum { geo, ptr, i32, f32 }; +/// A parameter's kind: geometry struct, device pointer, 32-bit count, float scale or Boolean mode. +pub const Kind = enum { geo, ptr, i32, f32, boolean }; /// One kernel's parameter list, in the .cu source's order. pub const Sig = struct { @@ -23,7 +23,7 @@ pub const attn_partial = Sig{ .name = "attn_partial", .handle = "e.fns.attn_part pub const attn_partial8 = Sig{ .name = "attn_partial8", .handle = "e.fp8.attn_partial", .symbol = "tf_q35_attn_partial8", .params = &.{ .geo, .ptr, .ptr, .ptr, .ptr, .i32, .ptr, .f32, .ptr, .ptr, .ptr } }; /// The bf16 decode attention over a long stream's rows: a block a group of rows. -pub const attn_rows = Sig{ .name = "attn_rows", .handle = "e.fns.attn_rows", .symbol = "tf_q35_attn_rows", .params = &.{ .geo, .ptr, .ptr, .ptr, .ptr, .i32, .ptr, .f32, .i32, .ptr, .ptr, .ptr } }; +pub const attn_rows = Sig{ .name = "attn_rows", .handle = "e.fns.attn_rows", .symbol = "tf_q35_attn_rows", .params = &.{ .geo, .ptr, .ptr, .ptr, .ptr, .i32, .ptr, .f32, .i32, .ptr, .ptr, .ptr, .boolean } }; /// The e4m3 decode attention over a long stream's rows. pub const attn_rows8 = Sig{ .name = "attn_rows8", .handle = "e.fp8.attn_rows", .symbol = "tf_q35_attn_rows8", .params = &.{ .geo, .ptr, .ptr, .ptr, .ptr, .i32, .ptr, .f32, .i32, .ptr, .ptr, .ptr } }; @@ -35,7 +35,7 @@ pub const attn_rows8_join = Sig{ .name = "attn_rows8_join", .handle = "e.fp8.att /// Whole-window instances use the same ABI without consulting Seg.pt. pub const attn_partial_whole = Sig{ .name = "attn_partial_whole", .handle = "e.fns.attn_partial_whole", .symbol = "tf_q35_attn_partial_whole", .params = &.{ .geo, .ptr, .ptr, .ptr, .ptr, .i32, .ptr, .f32, .ptr, .ptr, .ptr } }; pub const attn_partial8_whole = Sig{ .name = "attn_partial8_whole", .handle = "e.fp8.attn_partial8_whole", .symbol = "tf_q35_attn_partial8_whole", .params = &.{ .geo, .ptr, .ptr, .ptr, .ptr, .i32, .ptr, .f32, .ptr, .ptr, .ptr } }; -pub const attn_rows_whole = Sig{ .name = "attn_rows_whole", .handle = "e.fns.attn_rows_whole", .symbol = "tf_q35_attn_rows_whole", .params = &.{ .geo, .ptr, .ptr, .ptr, .ptr, .i32, .ptr, .f32, .i32, .ptr, .ptr, .ptr } }; +pub const attn_rows_whole = Sig{ .name = "attn_rows_whole", .handle = "e.fns.attn_rows_whole", .symbol = "tf_q35_attn_rows_whole", .params = &.{ .geo, .ptr, .ptr, .ptr, .ptr, .i32, .ptr, .f32, .i32, .ptr, .ptr, .ptr, .boolean } }; pub const attn_rows8_whole = Sig{ .name = "attn_rows8_whole", .handle = "e.fp8.attn_rows8_whole", .symbol = "tf_q35_attn_rows8_whole", .params = &.{ .geo, .ptr, .ptr, .ptr, .ptr, .i32, .ptr, .f32, .i32, .ptr, .ptr, .ptr } }; /// The merge: a row's chunks' partials into each (row, query head)'s output. @@ -79,6 +79,7 @@ pub fn kindOf(comptime T: type) ?Kind { if (T == u64) return .ptr; if (T == c_int) return .i32; if (T == f32) return .f32; + if (T == bool) return .boolean; const info = @typeInfo(T); if (info == .@"struct" and info.@"struct".layout == .@"extern") return .geo; return null; diff --git a/zig/src/families/qwen3_5/hip.zig b/zig/src/families/qwen3_5/hip.zig index b0352fcd3b6..ec61e5f7b1d 100644 --- a/zig/src/families/qwen3_5/hip.zig +++ b/zig/src/families/qwen3_5/hip.zig @@ -52,6 +52,7 @@ test { _ = moe; _ = sample; _ = prefix; + _ = @import("backend/hip/engine/prompt_rows.zig"); _ = hip_lanes; _ = radix; _ = native_engine; diff --git a/zig/src/families/qwen3_5/stages.zig b/zig/src/families/qwen3_5/stages.zig new file mode 100644 index 00000000000..86bd3233b80 --- /dev/null +++ b/zig/src/families/qwen3_5/stages.zig @@ -0,0 +1,346 @@ +//! Staged references (off unless asked for): a qwen3_5 forward's stages in one bf16 layout, for qwen36_stage_ref.py. +const std = @import("std"); + +/// The residual stream after the embedding, after each layer's mixer and its MLP, then the final norm and the head. +pub const Point = union(enum) { + embed, + mixer: usize, + block: usize, + final, + logits, + + /// The point's plane among `count(layers)`; a layer past the model's is refused. + pub fn index(p: Point, layers: usize) !usize { + return switch (p) { + .embed => 0, + .mixer => |l| if (l < layers) 1 + 2 * l else error.BadStageLayer, + .block => |l| if (l < layers) 2 + 2 * l else error.BadStageLayer, + .final => 1 + 2 * layers, + .logits => 2 + 2 * layers, + }; + } + + /// The file stem: embed, l07.mixer, l07.block, final, logits. + pub fn name(p: Point, buf: []u8) ![]const u8 { + return switch (p) { + .embed => "embed", + .mixer => |l| std.fmt.bufPrint(buf, "l{d:0>2}.mixer", .{l}), + .block => |l| std.fmt.bufPrint(buf, "l{d:0>2}.block", .{l}), + .final => "final", + .logits => "logits", + }; + } +}; + +pub fn count(layers: usize) usize { + return 3 + 2 * layers; +} + +/// The point at plane `i`, the inverse of `Point.index`. +pub fn point(i: usize, layers: usize) !Point { + if (i >= count(layers)) return error.BadStageLayer; + if (i == 0) return .embed; + if (i == 1 + 2 * layers) return .final; + if (i == 2 + 2 * layers) return .logits; + return if (i % 2 == 1) .{ .mixer = (i - 1) / 2 } else .{ .block = (i - 2) / 2 }; +} + +/// What an engine may record, asked before the round runs: one stream's chain of rows, its final norm and head. +pub fn admit(streams: usize, chain: bool, head: bool) !void { + if (streams != 1) return error.StagesNeedOneStream; + if (!chain) return error.StagesNeedChain; + if (!head) return error.StagesNeedHead; +} + +/// A window whose every row's parent is the row before it (the first's is -1): one linear sequence, no branches. +pub fn isChain(parents: []const i32) bool { + for (parents, 0..) |parent, row| if (parent != @as(i32, @intCast(row)) - 1) return false; + return true; +} + +/// A device engine's stage hook: `rows` rows of the point's width at device address `ptr`, valid once drained. +pub const DeviceHook = struct { + ctx: *anyopaque, + f: *const fn (ctx: *anyopaque, at: Point, ptr: u64, rows: usize) anyerror!void, +}; + +/// One round's planes in an engine's buffer: every stream point `capacity` rows wide, then the logits plane. +pub const Round = struct { + recorder: *Recorder, + capacity: u32, + logit_capacity: u32, + /// Each plane's rows this round: a stream plane left at 0 when the round ends was never recorded. + rows: [max_planes]u32 = @splat(0), + + pub const max_planes = 256; + + pub fn init(recorder: *Recorder, capacity: u32, logit_capacity: u32) !Round { + if (capacity == 0 or logit_capacity == 0 or count(recorder.layers) > max_planes) return error.BadStageShape; + return .{ .recorder = recorder, .capacity = capacity, .logit_capacity = logit_capacity }; + } + + /// The buffer's bytes: every plane at its capacity. + pub fn bytes(r: Round) usize { + return r.offset(.logits) + @as(usize, r.logit_capacity) * r.recorder.vocab * 2; + } + + pub fn offset(r: Round, at: Point) usize { + const i = at.index(r.recorder.layers) catch unreachable; + return i * @as(usize, r.capacity) * r.recorder.hidden * 2; + } + + pub fn begin(r: *Round) void { + r.rows = @splat(0); + } + + /// Claims `at`'s plane for `rows` rows; the engine then copies them to `offset(at)`. + pub fn mark(r: *Round, at: Point, rows: usize) !void { + const i = try at.index(r.recorder.layers); + if (rows == 0 or rows > (if (at == .logits) r.logit_capacity else r.capacity)) return error.BadStageShape; + if (r.rows[i] != 0) return error.DuplicateStage; + r.rows[i] = @intCast(rows); + } + + /// Hands the round in `base` to the recorder (every stream point holds its rows); its marks are spent either way. + pub fn end(r: *Round, base: []const u8, first: u32) !void { + defer r.rows = @splat(0); + const n = count(r.recorder.layers); + if (base.len < r.bytes()) return error.BadStageShape; + const rows = r.rows[0]; + for (r.rows[0..n], 0..) |got, i| if ((try point(i, r.recorder.layers)) != .logits and got != rows) return error.IncompleteStages; + var views: [max_planes][]const u8 = undefined; + for (views[0..n], 0..) |*view, i| { + const at = try point(i, r.recorder.layers); + view.* = base[r.offset(at)..][0 .. @as(usize, r.rows[i]) * r.recorder.width(at) * 2]; + } + try r.recorder.round(first, rows, r.rows[n - 1], views[0..n]); + } +}; + +/// A run's stages on the host: bf16 rows per point and the cache position of every row, in the order rounds ran. +pub const Recorder = struct { + allocator: std.mem.Allocator, + layers: usize, + hidden: usize, + vocab: usize, + planes: []std.ArrayList(u8), + positions: std.ArrayList(u32) = .empty, + logit_positions: std.ArrayList(u32) = .empty, + + pub fn init(a: std.mem.Allocator, layers: usize, hidden: usize, vocab: usize) !Recorder { + if (layers == 0 or hidden == 0 or vocab == 0) return error.BadStageShape; + const planes = try a.alloc(std.ArrayList(u8), count(layers)); + @memset(planes, .empty); + return .{ .allocator = a, .layers = layers, .hidden = hidden, .vocab = vocab, .planes = planes }; + } + + pub fn deinit(r: *Recorder) void { + for (r.planes) |*p| p.deinit(r.allocator); + r.allocator.free(r.planes); + r.positions.deinit(r.allocator); + r.logit_positions.deinit(r.allocator); + } + + pub fn width(r: Recorder, p: Point) usize { + return if (p == .logits) r.vocab else r.hidden; + } + + /// One round from cache position `first`, all or nothing; `logits` rows end at its last (0, 1 or `rows`). + pub fn round(r: *Recorder, first: u32, rows: u32, logits: u32, planes: []const []const u8) !void { + if (rows == 0 or (logits != 0 and logits != 1 and logits != rows) or planes.len != count(r.layers)) return error.BadStageShape; + for (planes, 0..) |bytes, i| { + const p = try point(i, r.layers); + const n: usize = if (p == .logits) logits else rows; + if (bytes.len != n * r.width(p) * 2) return error.BadStageShape; + } + for (planes, r.planes) |bytes, *plane| try plane.ensureUnusedCapacity(r.allocator, bytes.len); + try r.positions.ensureUnusedCapacity(r.allocator, rows); + try r.logit_positions.ensureUnusedCapacity(r.allocator, logits); + for (planes, r.planes) |bytes, *plane| plane.appendSliceAssumeCapacity(bytes); + for (0..rows) |row| r.positions.appendAssumeCapacity(first + @as(u32, @intCast(row))); + for (rows - logits..rows) |row| r.logit_positions.appendAssumeCapacity(first + @as(u32, @intCast(row))); + } + + /// `dir`/.bf16 per point, row-major, and index.json with the shapes and every row's cache position. + pub fn write(r: Recorder, io: std.Io, dir: []const u8) !void { + const cwd = std.Io.Dir.cwd(); + try cwd.createDirPath(io, dir); + var path_buf: [std.fs.max_path_bytes]u8 = undefined; + var name_buf: [32]u8 = undefined; + const Entry = struct { name: []const u8, width: usize, rows: usize }; + const entries = try r.allocator.alloc(Entry, r.planes.len); + defer r.allocator.free(entries); + for (r.planes, entries, 0..) |plane, *entry, i| { + const p = try point(i, r.layers); + const stem = try p.name(&name_buf); + const path = try std.fmt.bufPrint(&path_buf, "{s}/{s}.bf16", .{ dir, stem }); + try cwd.writeFile(io, .{ .sub_path = path, .data = plane.items }); + entry.* = .{ .name = try r.allocator.dupe(u8, stem), .width = r.width(p), .rows = plane.items.len / (r.width(p) * 2) }; + } + defer for (entries) |e| r.allocator.free(e.name); + const index = try std.json.Stringify.valueAlloc(r.allocator, .{ + .version = 1, + .dtype = "bf16", + .layers = r.layers, + .hidden = r.hidden, + .vocab = r.vocab, + .stages = entries, + .positions = r.positions.items, + .logit_positions = r.logit_positions.items, + }, .{}); + defer r.allocator.free(index); + try cwd.writeFile(io, .{ .sub_path = try std.fmt.bufPrint(&path_buf, "{s}/index.json", .{dir}), .data = index }); + } +}; + +test "stage planes and names cover every point once, in forward order" { + var buf: [32]u8 = undefined; + for ([_]usize{ 1, 2, 40 }) |layers| { + for (0..count(layers)) |i| try std.testing.expectEqual(i, try (try point(i, layers)).index(layers)); + } + try std.testing.expectEqualStrings("l07.mixer", try (Point{ .mixer = 7 }).name(&buf)); + try std.testing.expectEqualStrings("l39.block", try (Point{ .block = 39 }).name(&buf)); + try std.testing.expectError(error.BadStageLayer, (Point{ .block = 2 }).index(2)); + try std.testing.expectError(error.BadStageLayer, point(count(2), 2)); +} + +test "isChain and admit: every parent list of up to three rows, stream count and head" { + const choices = [_]i32{ -2, -1, 0, 1, 2 }; + var parents: [3]i32 = undefined; + for (0..4) |len| for (0..std.math.pow(usize, choices.len, len)) |code| { + var c = code; + for (parents[0..len]) |*p| { + p.* = choices[c % choices.len]; + c /= choices.len; + } + const chain = [_]i32{ -1, 0, 1 }; + try std.testing.expectEqual(std.mem.eql(i32, chain[0..len], parents[0..len]), isChain(parents[0..len])); + }; + for (0..3) |streams| for ([_]bool{ false, true }) |chain| for ([_]bool{ false, true }) |head| { + const want: ?anyerror = if (streams != 1) error.StagesNeedOneStream else if (!chain) error.StagesNeedChain else if (!head) error.StagesNeedHead else null; + if (want) |err| try std.testing.expectError(err, admit(streams, chain, head)) else try admit(streams, chain, head); + }; +} + +test "Round: every sequence of four round events lands exactly the rounds a model of the engine's caller lands" { + // One layer, one value wide, 2 rows of capacity; fill tags every point's rows, partial only the embedding's. + const Fill = struct { rows: u32, head: u32 }; + const Event = union(enum) { begin, fill: Fill, partial, end, fail: usize }; + const events = [_]Event{ + .begin, .partial, .end, + .{ .fill = .{ .rows = 1, .head = 0 } }, .{ .fill = .{ .rows = 1, .head = 1 } }, .{ .fill = .{ .rows = 1, .head = 2 } }, + .{ .fill = .{ .rows = 2, .head = 0 } }, .{ .fill = .{ .rows = 2, .head = 1 } }, .{ .fill = .{ .rows = 2, .head = 2 } }, + .{ .fail = 0 }, .{ .fail = 3 }, .{ .fail = 6 }, + }; + const a = std.testing.allocator; + const n = events.len + 1; + var seq: [4]usize = undefined; + var landed_rounds: usize = 0; + var refused_by_oom: usize = 0; + for (0..std.math.pow(usize, n, seq.len)) |code| { + var c = code; + var len: usize = 0; + while (len < seq.len and c % n != events.len) : (len += 1) { + seq[len] = c % n; + c /= n; + } + if (len < seq.len and c / n != 0) continue; // events after the end marker would repeat a shorter sequence + var failing = std.testing.FailingAllocator.init(a, .{}); + var rec = try Recorder.init(failing.allocator(), 1, 1, 1); + defer rec.deinit(); + var round_ = try Round.init(&rec, 2, 2); + var base: [64]u8 = @splat(0); + // The model: what is marked, every plane's bytes and the positions that should have landed. + var marked: enum { none, partial, fill } = .none; + var fill: Fill = undefined; + var tag: u8 = 0; + var next: u32 = 9; + var want: [5]std.ArrayList(u8) = @splat(.empty); + defer for (&want) |*w| w.deinit(a); + var want_positions: std.ArrayList(u32) = .empty; + defer want_positions.deinit(a); + var want_logits: std.ArrayList(u32) = .empty; + defer want_logits.deinit(a); + for (seq[0..len]) |e| switch (events[e]) { + .begin => { + round_.begin(); + marked = .none; + }, + .partial => { + const got = round_.mark(.embed, 1); + if (marked == .none) { + try got; + marked = .partial; + } else try std.testing.expectError(error.DuplicateStage, got); + }, + .fill => |f| { + // The engine's order: a refused mark stops the forward, so a fill lands whole or not at all. + if (marked != .none) { + try std.testing.expectError(error.DuplicateStage, round_.mark(.embed, f.rows)); + continue; + } + tag += 1; + for (0..5) |i| { + const at = try point(i, 1); + const rows = if (at == .logits) f.head else f.rows; + if (rows == 0) continue; + try round_.mark(at, rows); + @memset(base[round_.offset(at)..][0 .. rows * 2], tag); + } + marked = .fill; + fill = f; + }, + .end, .fail => { + const k: ?usize = if (events[e] == .fail) events[e].fail else null; + if (k) |after| { + failing.fail_index = failing.alloc_index + after; + failing.resize_fail_index = failing.resize_index + after; + } + const got = round_.end(&base, next); + failing.fail_index = std.math.maxInt(usize); + failing.resize_fail_index = std.math.maxInt(usize); + const was = marked; + marked = .none; + switch (was) { + .none => try std.testing.expectError(error.BadStageShape, got), + .partial => try std.testing.expectError(error.IncompleteStages, got), + .fill => if (fill.head == 2 and fill.rows == 1) try std.testing.expectError(error.BadStageShape, got) else { + got catch |err| { + try std.testing.expect(k != null and err == error.OutOfMemory); + refused_by_oom += 1; + continue; + }; + landed_rounds += 1; + for (&want, 0..) |*w, i| try w.appendNTimes(a, tag, 2 * if (i == 4) fill.head else fill.rows); + for (0..fill.rows) |row| try want_positions.append(a, next + @as(u32, @intCast(row))); + for (fill.rows - fill.head..fill.rows) |row| try want_logits.append(a, next + @as(u32, @intCast(row))); + next += fill.rows; + }, + } + }, + }; + for (want, rec.planes) |w, got| try std.testing.expectEqualSlices(u8, w.items, got.items); + try std.testing.expectEqualSlices(u32, want_positions.items, rec.positions.items); + try std.testing.expectEqualSlices(u32, want_logits.items, rec.logit_positions.items); + } + // The enumeration reaches both a landed round and an allocation failure that leaves the recorder unchanged. + try std.testing.expect(landed_rounds > 0 and refused_by_oom > 0); +} + +test "a round's rows land on their positions; a short plane or odd head count is refused" { + const a = std.testing.allocator; + var r = try Recorder.init(a, 1, 2, 3); + defer r.deinit(); + const row: [4]u8 = @splat(0); + const two: [8]u8 = @splat(0); + const logit: [6]u8 = @splat(0); + // A two-row prompt round with its last row's logits, then a one-row step. + try r.round(5, 2, 1, &.{ &two, &two, &two, &two, &logit }); + try r.round(7, 1, 1, &.{ &row, &row, &row, &row, &logit }); + try std.testing.expectEqualSlices(u32, &.{ 5, 6, 7 }, r.positions.items); + try std.testing.expectEqualSlices(u32, &.{ 6, 7 }, r.logit_positions.items); + try std.testing.expectEqual(@as(usize, 12), r.planes[0].items.len); + try std.testing.expectError(error.BadStageShape, r.round(8, 1, 1, &.{ &row, &row, &row, row[0..2], &logit })); + try std.testing.expectError(error.BadStageShape, r.round(8, 3, 2, &.{ &row, &row, &row, &row, &logit })); + try std.testing.expectEqual(@as(usize, 3), r.positions.items.len); +} diff --git a/zig/src/families/ricursive/cuda.zig b/zig/src/families/ricursive/cuda.zig new file mode 100644 index 00000000000..98b3e097147 --- /dev/null +++ b/zig/src/families/ricursive/cuda.zig @@ -0,0 +1,19 @@ +//! Ripple on CUDA: the family's kernels (glue, attention prep, attention), weights and forward, beside Metal's. + +pub const kernels = @import("cuda_kernels.zig"); +pub const prep = @import("cuda_prep.zig"); +pub const attn = @import("cuda_attn.zig"); +pub const weights = @import("cuda_weights.zig"); +pub const model = @import("cuda_model.zig"); +pub const backend = @import("cuda_backend.zig"); +pub const native = @import("cuda_native.zig"); + +test { + _ = kernels; + _ = prep; + _ = attn; + _ = weights; + _ = model; + _ = backend; + _ = native; +} diff --git a/zig/src/families/ricursive/cuda_attn.zig b/zig/src/families/ricursive/cuda_attn.zig new file mode 100644 index 00000000000..1916f9b7d5c --- /dev/null +++ b/zig/src/families/ricursive/cuda_attn.zig @@ -0,0 +1,397 @@ +//! Ripple's attention on CUDA (group 10, dim 128): window_attention's prompt and decode, tree_attention's global. +const std = @import("std"); +const cuda = @import("cuda"); + +const wa = cuda.window_attention; +const ta = cuda.tree_attention; +const Stream = cuda.Stream; +const Function = cuda.Function; + +pub const head_dim = 128; +/// Query heads a block: Ripple's group 10 is no multiple of the shared prompt's 4 (WindowAttention.prompt refuses it). +pub const heads_a_block = 2; +/// Eight warps, each 16 rows of one head: 64 rows a block. +pub const rows_a_block = 16 * (8 / heads_a_block); + +/// wattn_kernel<128, 8, 2, 8>: keys in a ring (sliding layers) or linear (global layers). +pub const prompt_symbol = "_ZN16tf_window_prompt12wattn_kernelILi128ELi8ELi2ELi8EEEvPK13__nv_bfloat16S3_S3_PS1_iiiiifii"; +/// The same over a stream's pages (global layers only: no window). +pub const prompt_pg_symbol = "tf_window_prompt_h2_pg"; +/// window_attention.zig's prompt_smem: eight staging slots of 32 keys at head dim 128. +const prompt_smem: u32 = 8 * 32 * 16 * 16; + +pub const Kernels = struct { + prompt: Function, + prompt_pg: Function, + + /// The two instances from the window_attention image WindowAttention.load loaded (it owns the module). + pub fn init(w: *const wa.WindowAttention) !Kernels { + const p = try w.mod.function(prompt_symbol); + try p.allowDynamicShared(prompt_smem); + const pg = try w.mod.function(prompt_pg_symbol); + try pg.allowDynamicShared(prompt_smem); + return .{ .prompt = p, .prompt_pg = pg }; + } +}; + +/// A sliding layer: keys (pos - window, pos] of a ring holding key p at row p % ring (prompt and decode). +pub fn sliding(h: usize, hk: usize, window: usize, ring: usize, scale: f32) wa.Window { + return .{ .h = h, .hk = hk, .d = head_dim, .win = window, .ring = ring, .scale = scale }; +} + +/// A global layer's prompt rows: every key up to the row's own, linear (key p at row p) or in pages. +pub fn global(h: usize, hk: usize, scale: f32, pg: ?wa.Pages) wa.Window { + return .{ .h = h, .hk = hk, .d = head_dim, .win = 0, .ring = 0, .scale = scale, .pg = pg }; +} + +/// A ring holds every key a call's rows see: it never wraps in the call, or it takes the window and the rows. +fn ringHolds(w: wa.Window, p0: usize, n: usize) bool { + if (w.ring == 0 or p0 + n <= w.ring) return true; + return w.win > 0 and w.win - 1 + n <= w.ring; +} + +/// The shapes the two-heads-a-block kernels take; the shared prompt's checks plus the ring's. +pub fn check(w: wa.Window, p0: usize, n: usize) error{WindowShape}!void { + if (w.d != head_dim or w.hk == 0 or w.h % w.hk != 0 or (w.h / w.hk) % heads_a_block != 0) return error.WindowShape; + if (p0 + n > std.math.maxInt(i32) or w.win > std.math.maxInt(i32) or w.ring > std.math.maxInt(i32)) return error.WindowShape; + if (w.pg) |pg| if (w.win != 0 or w.ring != 0 or pg.tokens == 0 or pg.page_elems > std.math.maxInt(i63)) return error.WindowShape; + if (!ringHolds(w, p0, n)) return error.WindowShape; +} + +/// The launch: (rows / 64) x (key heads x head pairs) blocks of 256 threads, 64 KiB of staged keys. +pub fn config(w: wa.Window, n: usize) cuda.Config { + const pairs = w.h / w.hk / heads_a_block; + return .{ .grid = .{ .x = @intCast((n + rows_a_block - 1) / rows_a_block), .y = @intCast(w.hk * pairs), .z = 1 }, .block = .{ .x = 256 }, .shared = prompt_smem }; +} + +/// n prompt rows of one stream at p0, p0 + 1, ...: q [n, h, 128] -> out [n, h, 128]; kc/vc as WindowAttention.prompt. +pub fn prompt(k: *const Kernels, s: Stream, q: u64, kc: u64, vc: u64, out: u64, p0: usize, n: usize, w: wa.Window) !void { + try check(w, p0, n); + if (n == 0) return; + var a: cuda.Args = .{}; + for ([_]u64{ q, kc, vc, out }) |v| a.add(v); + for ([_]usize{ p0, n, w.h, w.hk, w.h / w.hk }) |v| a.add(@as(i32, @intCast(v))); + a.add(w.scale); + a.add(@as(i32, @intCast(w.win))); + a.add(@as(i32, @intCast(w.ring))); + if (w.pg) |pg| { + a.add(pg.table); + a.add(@as(i64, @intCast(pg.page_elems))); + a.add(@as(i32, @intCast(pg.tokens))); + } + try cuda.launch.launch(if (w.pg != null) k.prompt_pg else k.prompt, config(w, n), s, &a); +} + +/// Global layers' heads: 80 query heads over 8 key heads (group 10). +pub const global_heads = 80; +pub const global_kv_heads = 8; + +/// A call's plan for tree_attention, int32 row_stream [m], streams [m, 4], depths [m], then int64 offs [m, 2]. +fn planBytes(max_rows: usize) usize { + return max_rows * (6 * 4 + 2 * 8); +} + +/// Row r its own stream: committed keys 0..pos + r from the pages, depth 0 (no path keys); K, V from `origin`. +fn plan(buf: []u8, max_rows: usize, pos: usize, rows: usize, k_off: i64, v_off: i64) void { + for (0..rows) |r| planRow(buf, max_rows, r, pos + r + 1, k_off, v_off); +} + +/// Row r its own stream (and its call table row), `committed` keys from the pages, depth 0; K, V from `origin`. +fn planRow(buf: []u8, max_rows: usize, r: usize, committed: usize, k_off: i64, v_off: i64) void { + const ints = std.mem.bytesAsSlice(i32, buf[0 .. 24 * max_rows]); + const offs = std.mem.bytesAsSlice(i64, buf[24 * max_rows ..][0 .. 16 * max_rows]); + ints[r] = @intCast(r); + ints[max_rows + 4 * r ..][0..4].* = .{ @intCast(r), 1, @intCast(committed), 0 }; + ints[5 * max_rows + r] = 0; + offs[2 * r] = k_off; + offs[2 * r + 1] = v_off; +} + +/// Every row's fixed fields, staged once: its own stream and table row, K at the pool, V `v_off` past it, committed 0. +fn stagePlan(buf: []u8, max_rows: usize, v_off: i64) void { + for (0..max_rows) |r| planRow(buf, max_rows, r, 0, 0, v_off); +} + +/// Row r's committed keys (pos[r] + 1) into the staged plan; returns the streams' bytes to upload, 16 a row. +fn commitRows(buf: []u8, max_rows: usize, pos: []const usize) []const u8 { + const streams = std.mem.bytesAsSlice(i32, buf[4 * max_rows .. 20 * max_rows]); + for (pos, 0..) |p, r| streams[4 * r + 2] = @intCast(p + 1); + return buf[4 * max_rows ..][0 .. 16 * pos.len]; +} + +/// tree_attention's fp32 partials for `max_rows` rows over keys to `context`: o, max, sum by group, then slices. +pub fn scratchBytes(max_rows: usize, context: usize) usize { + return ta.TreeAttention.scratchBytes(max_rows, global_heads, global_kv_heads, ta.TreeAttention.groups(context), head_dim); +} + +/// The device's SMs: tree_attention takes one-warp blocks for small grids (the same bits as four-warp blocks). +fn smCount(d: *const cuda.Driver) !usize { + var dev: cuda.abi.Device = 0; + try d.check(d.api.cuCtxGetDevice(&dev), "cuCtxGetDevice"); + var sms: c_int = 0; + try d.check(d.api.cuDeviceGetAttribute(&sms, .multiprocessor_count, dev), "cuDeviceGetAttribute"); + return @intCast(@max(sms, 1)); +} + +/// Global decode: tree_attention's paged kernels and merge, each row a stream of its own over the layer's pages. +pub const GlobalDecode = struct { + tree: ta.TreeAttention, + plan: cuda.DeviceBuffer, + scratch: cuda.DeviceBuffer, + host: []u8, + gpa: std.mem.Allocator, + max_rows: usize, + /// The most keys a row sees (pos + rows): the partials are strided by its groups. + context: usize, + /// V's offset from K that `stage` uploaded (null: not staged); decodeGlobal's plan overwrites the staged fields. + v_off: ?usize = null, + + /// The device bytes init allocates: the partials and the plan. + pub fn bytes(max_rows: usize, context: usize) usize { + return scratchBytes(max_rows, context) + std.mem.alignForward(usize, planBytes(max_rows), 256); + } + + pub fn init(d: *const cuda.Driver, gpa: std.mem.Allocator, max_rows: usize, context: usize) !GlobalDecode { + if (max_rows == 0 or context < max_rows or context > std.math.maxInt(i32)) return error.GlobalShape; + var tree = try ta.TreeAttention.load(d); + errdefer tree.unload(); + tree.sms = try smCount(d); + const host = try gpa.alloc(u8, planBytes(max_rows)); + errdefer gpa.free(host); + @memset(host, 0); + var p = try cuda.DeviceBuffer.alloc(d, host.len); + errdefer p.free(); + const sc = try cuda.DeviceBuffer.alloc(d, scratchBytes(max_rows, context)); + return .{ .tree = tree, .plan = p, .scratch = sc, .host = host, .gpa = gpa, .max_rows = max_rows, .context = context }; + } + + pub fn deinit(g: *GlobalDecode) void { + g.scratch.free(); + g.plan.free(); + g.gpa.free(g.host); + g.tree.unload(); + } + + /// The plan's fixed fields for every row, uploaded once (stagePlan): a round then uploads only its committed keys. + pub fn stage(g: *GlobalDecode, s: Stream, v_off: usize) !void { + if (v_off > std.math.maxInt(i63)) return error.GlobalShape; + stagePlan(g.host, g.max_rows, @intCast(v_off)); + try g.plan.uploadAsync(0, g.host, s.handle); + g.v_off = v_off; + } + + /// The key groups a graph's rounds take: those of the context, so its grid and partials' strides serve every round. + pub fn groups(g: *const GlobalDecode) usize { + return ta.TreeAttention.groups(g.context); + } +}; + +/// q [rows, 80, 128], row r at pos + r over keys 0..pos + r of `pages` (kc, vc: tf_rc_prep's pools) -> out. +pub const DecodeArgs = struct { q: u64, kc: u64, vc: u64, out: u64, pos: usize, rows: usize, pages: wa.Pages, scale: f32 }; + +/// The calls the plan takes: at most init's rows, keys to its context, pages of whole int32 positions. +pub fn admit(max_rows: usize, context: usize, a: DecodeArgs) error{GlobalShape}!void { + if (a.rows > max_rows or a.pos > context or a.rows > context - a.pos) return error.GlobalShape; + const pg = a.pages; + if (pg.tokens == 0 or pg.tokens > std.math.maxInt(i32) or pg.page_elems == 0 or pg.page_elems > std.math.maxInt(i63)) return error.GlobalShape; +} + +/// One global layer's decode rows. The plan is uploaded each call (not inside a CUDA graph capture). +pub fn decodeGlobal(g: *const GlobalDecode, s: Stream, a: DecodeArgs) !void { + return decodeHeads(g, s, a, global_heads); +} + +/// decodeGlobal with `h` query heads over the 8 key heads: Ripple's 80, or a control's other group. +pub fn decodeHeads(g: *const GlobalDecode, s: Stream, a: DecodeArgs, h: usize) !void { + try admit(g.max_rows, g.context, a); + if (h == 0 or h > global_heads or h % global_kv_heads != 0) return error.GlobalShape; + if (a.rows == 0) return; + const origin = @min(a.kc, a.vc); + plan(g.host, g.max_rows, a.pos, a.rows, @intCast((a.kc - origin) / 2), @intCast((a.vc - origin) / 2)); + try g.plan.uploadAsync(0, g.host, s.handle); + const pg: ta.Pages = .{ .table = a.pages.table, .page = a.pages.page_elems, .tok = a.pages.tokens, .stride = 0 }; + try run(g, s, a.q, a.kc, a.vc, a.out, a.rows, h, pg, ta.TreeAttention.groups(a.pos + a.rows), a.scale); +} + +/// A round's global-layer plan: row r its own tree stream at pos[r], K at `kc`, V `v_off` past it, `ng` key groups. +pub const Planned = struct { rows: usize, ng: usize, v_off: usize }; + +/// The rounds the plan takes: 1 to init's rows, each position within its context, V offsets of int64 elements. +pub fn admitRows(max_rows: usize, context: usize, pos: []const usize, v_off: usize) error{GlobalShape}!void { + if (pos.len == 0 or pos.len > max_rows or v_off > std.math.maxInt(i63)) return error.GlobalShape; + for (pos) |p| if (p >= context) return error.GlobalShape; +} + +/// The groups a call's partials are strided by: those of its row with the most keys. +pub fn groupsOf(pos: []const usize) usize { + var most: usize = 0; + for (pos) |p| most = @max(most, p + 1); + return ta.TreeAttention.groups(most); +} + +/// tree_attention.zig's choice for a call: one-warp blocks (true) or four-warp blocks, by rows, groups and key heads. +pub fn oneWarp(g: *const GlobalDecode, rows: usize, ng: usize) bool { + return g.tree.sms > 0 and rows * ng * global_kv_heads <= ta.slice_items; +} + +/// A round's rows into the staged plan, each a one-row call's stream; `fixed`: the context's key groups, same bits. +pub fn planRows(g: *const GlobalDecode, s: Stream, pos: []const usize, fixed: bool) !Planned { + const v_off = g.v_off orelse return error.PlanNotStaged; + try admitRows(g.max_rows, g.context, pos, v_off); + try g.plan.uploadAsync(4 * g.max_rows, commitRows(g.host, g.max_rows, pos), s.handle); + return .{ .rows = pos.len, .ng = if (fixed) g.groups() else groupsOf(pos), .v_off = v_off }; +} + +/// One global layer's planned rows, `h` query heads over the 8 key heads: q [rows, h, 128] -> out [rows, h, 128]. +pub fn runRows(g: *const GlobalDecode, s: Stream, p: Planned, q: u64, kc: u64, out: u64, h: usize, pages: wa.Pages, scale: f32) !void { + if (h == 0 or h > global_heads or h % global_kv_heads != 0) return error.GlobalShape; + if (pages.tokens == 0 or pages.tokens > std.math.maxInt(i32) or pages.page_elems == 0 or pages.page_elems > std.math.maxInt(i63) or pages.stride > std.math.maxInt(i32)) return error.GlobalShape; + const pg: ta.Pages = .{ .table = pages.table, .page = pages.page_elems, .tok = pages.tokens, .stride = pages.stride }; + try run(g, s, q, kc, kc + 2 * p.v_off, out, p.rows, h, pg, p.ng, scale); +} + +/// tree_attention over the uploaded plan: `n` rows, `ng` groups of partials, the pages `pg`. +fn run(g: *const GlobalDecode, s: Stream, q: u64, kc: u64, vc: u64, out: u64, n: usize, h: usize, pg: ta.Pages, ng: usize, scale: f32) !void { + const m = g.max_rows; + const base = g.plan.ptr; + const depths = base + 20 * m; // also `paths`: depth 0 reads none + const rows: ta.Rows = .{ .row_stream = base, .streams = base + 4 * m, .offs = base + 24 * m, .origin = @min(kc, vc), .paths = depths, .depths = depths, .pages = pg }; + const sc = ta.TreeAttention.scratch(g.scratch.ptr, n, h, global_kv_heads, ng, head_dim); + // kn, vn: path keys, of which there are none (each row's own key is committed in the pages) + try g.tree.run(s, q, kc, vc, rows, sc, out, n, h, global_kv_heads, head_dim, ng, scale); +} + +test "Ripple's prompt grid: 64 rows a block, five head pairs of each of 8 key heads" { + const t = std.testing; + const w = sliding(80, 8, 1024, 3072, 0.08838835); + for ([_][2]u32{ .{ 2048, 32 }, .{ 1000, 16 }, .{ 333, 6 }, .{ 1, 1 } }) |c| { + const cfg = config(w, c[0]); + try t.expectEqual(c[1], @as(u32, cfg.grid.x)); + try t.expectEqual(@as(u32, 40), @as(u32, cfg.grid.y)); + try t.expectEqual(@as(u32, 256), @as(u32, cfg.block.x)); + try t.expectEqual(@as(u32, 65536), cfg.shared); + } +} + +test "the ring takes the window and a 2,048-row chunk past its wrap; a longer chunk or a short ring is refused" { + const t = std.testing; + const w = sliding(80, 8, 1024, 3072, 0.08838835); + try check(w, 8216, 2048); + try check(w, 0, 3072); // no wrap in the call + try t.expectError(error.WindowShape, check(w, 8216, 2050)); + try t.expectError(error.WindowShape, check(sliding(80, 8, 1024, 3000, 0.08838835), 8216, 2048)); + try check(global(80, 8, 0.08838835, null), 6000, 2048); // linear keys: no ring + var every = global(80, 8, 0.08838835, null); + every.ring = 4096; + try t.expectError(error.WindowShape, check(every, 4000, 200)); // every key, from a ring that wraps +} + +test "shapes the kernel does not take are refused" { + const t = std.testing; + try t.expectError(error.WindowShape, check(sliding(72, 8, 1024, 3072, 1), 0, 16)); // group 9 + var wide = sliding(80, 8, 1024, 3072, 1); + wide.d = 256; + try t.expectError(error.WindowShape, check(wide, 0, 16)); + var pg = sliding(80, 8, 1024, 3072, 1); + pg.pg = .{ .table = 0, .page_elems = 2 * 512 * 8 * 128, .tokens = 512 }; + try t.expectError(error.WindowShape, check(pg, 0, 16)); // pages hold global layers' keys only + try check(global(80, 8, 1, .{ .table = 0, .page_elems = 2 * 512 * 8 * 128, .tokens = 512 }), 6000, 2048); +} + +test "global decode plan: each row its own stream, committed to its own key, no path keys" { + const t = std.testing; + var buf: [planBytes(4)]u8 = @splat(0xee); + plan(&buf, 4, 510, 3, 0, 2048); + const ints = std.mem.bytesAsSlice(i32, buf[0..96]); + const offs = std.mem.bytesAsSlice(i64, buf[96..]); + for (0..3) |r| { + const ri: i32 = @intCast(r); + try t.expectEqual(ri, ints[r]); + try t.expectEqualSlices(i32, &.{ ri, 1, 511 + ri, 0 }, &[4]i32{ ints[4 + 4 * r], ints[5 + 4 * r], ints[6 + 4 * r], ints[7 + 4 * r] }); + try t.expectEqual(@as(i32, 0), ints[20 + r]); + try t.expectEqual(@as(i64, 0), offs[2 * r]); + try t.expectEqual(@as(i64, 2048), offs[2 * r + 1]); + } + try t.expectEqual(@as(i32, @bitCast(@as(u32, 0xeeeeeeee))), ints[3]); // row 3: past the call's rows, untouched +} + +test "global decode takes 1 to 16 rows to the context, and pages of whole positions" { + const t = std.testing; + const pg: wa.Pages = .{ .table = 0, .page_elems = 2 * 512 * 8 * 128, .tokens = 512 }; + const at = struct { + fn f(pos: usize, rows: usize, p: wa.Pages) DecodeArgs { + return .{ .q = 0, .kc = 0, .vc = 0, .out = 0, .pos = pos, .rows = rows, .pages = p, .scale = 0.08838835 }; + } + }.f; + try admit(16, 131072, at(131056, 16, pg)); + try admit(16, 131072, at(0, 1, pg)); + try t.expectError(error.GlobalShape, admit(16, 131072, at(131057, 16, pg))); // past the context + try t.expectError(error.GlobalShape, admit(16, 131072, at(200000, 1, pg))); + try t.expectError(error.GlobalShape, admit(16, 131072, at(0, 17, pg))); + var none = pg; + none.tokens = 0; + try t.expectError(error.GlobalShape, admit(16, 131072, at(0, 1, none))); +} + +test "global decode rows: each row its own stream and call table row, committed to its own position" { + const t = std.testing; + var buf: [planBytes(4)]u8 = @splat(0xee); + const pos = [_]usize{ 4095, 511, 3071 }; + for (pos, 0..) |p, r| planRow(&buf, 4, r, p + 1, 0, 4608); + const ints = std.mem.bytesAsSlice(i32, buf[0..96]); + const offs = std.mem.bytesAsSlice(i64, buf[96..]); + for (pos, 0..) |p, r| { + const ri: i32 = @intCast(r); + try t.expectEqual(ri, ints[r]); + try t.expectEqualSlices(i32, &.{ ri, 1, @as(i32, @intCast(p + 1)), 0 }, &[4]i32{ ints[4 + 4 * r], ints[5 + 4 * r], ints[6 + 4 * r], ints[7 + 4 * r] }); + try t.expectEqual(@as(i64, 4608), offs[2 * r + 1]); + } + var one: [planBytes(4)]u8 = @splat(0xee); + plan(&one, 4, 510, 3, 0, 4608); + var rows: [planBytes(4)]u8 = @splat(0xee); + for (0..3) |r| planRow(&rows, 4, r, 510 + r + 1, 0, 4608); + try t.expectEqualSlices(u8, &one, &rows); // a stream's consecutive rows, planned one by one + try t.expectEqual(@as(usize, 8), groupsOf(&pos)); // 4,096 keys: 8 groups of 512 + try t.expectEqual(@as(usize, 9), groupsOf(&.{4096})); +} + +test "staged plan: fixed fields once, a round's committed keys its only upload, B1's per-row plan for its rows" { + const t = std.testing; + var staged: [planBytes(4)]u8 = @splat(0xee); + stagePlan(&staged, 4, 4608); + const first = [_]usize{ 4095, 511, 3071 }; + _ = commitRows(&staged, 4, &first); + const pos = [_]usize{ 7, 3072 }; // a later round of fewer rows: rows past it keep the last round's keys + const up = commitRows(&staged, 4, &pos); + try t.expectEqual(@as(usize, 2 * 16), up.len); + try t.expectEqual(@intFromPtr(&staged) + 16, @intFromPtr(up.ptr)); // streams' rows, after row_stream [4] + var b1: [planBytes(4)]u8 = @splat(0xee); + for (0..4) |r| planRow(&b1, 4, r, 0, 0, 4608); + for (pos, 0..) |p, r| planRow(&b1, 4, r, p + 1, 0, 4608); + planRow(&b1, 4, 2, 3072, 0, 4608); + try t.expectEqualSlices(u8, &b1, &staged); + const ints = std.mem.bytesAsSlice(i32, staged[0..96]); + try t.expectEqualSlices(i32, &.{ 1, 1, 3073, 0 }, &[4]i32{ ints[8], ints[9], ints[10], ints[11] }); +} + +test "a graph's key groups: the context's, at least any round's; their partials fit init's scratch" { + const t = std.testing; + try t.expectEqual(@as(usize, 16), ta.TreeAttention.groups(8192)); // the forward test's context + try t.expectEqual(@as(usize, 64), ta.TreeAttention.groups(32768)); // the default context + try t.expect(groupsOf(&.{ 8191, 0 }) <= ta.TreeAttention.groups(8192)); + const w = ta.TreeAttention.scratch(0, 48, global_heads, global_kv_heads, ta.TreeAttention.groups(8192), head_dim); + try t.expectEqual(@as(u64, scratchBytes(48, 8192)), w.sl + ta.slice_items * 4 * 10 * 4); // the last slice sum's end +} + +test "global decode rows: 1 to init's rows, each position within the context" { + const t = std.testing; + try admitRows(16, 131072, &.{ 131071, 0, 70000 }, 512 * 1024 * 256); + try t.expectError(error.GlobalShape, admitRows(16, 131072, &.{131072}, 0)); + try t.expectError(error.GlobalShape, admitRows(2, 131072, &.{ 1, 2, 3 }, 0)); + try t.expectError(error.GlobalShape, admitRows(2, 131072, &.{}, 0)); +} + +test "global decode scratch: 16 rows' partials over 131,072 keys (256 groups), then the slices" { + try std.testing.expectEqual(@as(usize, (16 * 80 * 256 + 1024 * 4 * 10) * 130 * 4), scratchBytes(16, 131072)); + try std.testing.expectEqual(@as(usize, 191_692_800), scratchBytes(16, 131072)); +} diff --git a/zig/src/families/ricursive/cuda_backend.zig b/zig/src/families/ricursive/cuda_backend.zig new file mode 100644 index 00000000000..ae628c57194 --- /dev/null +++ b/zig/src/families/ricursive/cuda_backend.zig @@ -0,0 +1,466 @@ +//! Ripple behind lanes.Backend on CUDA: a slot a stream, a chunk a step, a round all windows; cuda.sample draws. +const std = @import("std"); +const cuda = @import("cuda"); +const lanes = @import("lanes"); +const cfg = @import("config.zig"); +const fwd = @import("cuda_model.zig"); +/// The prompt cache's states (cuda_snap.zig), reached through the backend. +pub const snap = @import("cuda_snap.zig"); + +const be = lanes.backend; +const Stream = lanes.Stream; +const LogRow = lanes.LogprobRow; +const row_words: usize = lanes.logprob.words; + +pub const prompt_rows: u32 = fwd.prompt_rows; +/// Rows a round takes over every stream: the model's scratch for rounds is opened at this many. +pub const round_rows: u32 = 128; +/// The widest window a stream verifies (B1: a window's rows are the one-row steps' rows). +pub const max_window: u32 = 16; +/// Positions a slot keeps past a reply for a verify window's rows. +pub const reserve: usize = max_window; +/// Drawn tokens a handle names (a ring; read before the round loop could wrap it). +const ring = 1024; +/// Rows of logprob words at once: a round's, or a prompt pass's head rows. +const word_rows = @max(round_rows, fwd.head_rows); + +/// The positions opened for an asked context: it and the verify reserve, within the maximum, at least a round's rows. +pub fn physical(context: usize) usize { + return std.math.clamp(context +| reserve, @as(usize, round_rows), cfg.max_context); +} + +/// A prompt and its reply fit `positions` with the verify reserve left over. +pub fn fits(positions: usize, prompt: usize, reply: usize) bool { + return prompt <= positions and reply <= positions - prompt and reserve <= positions - prompt - reply; +} + +const Lane = struct { + slot: usize, + len: u64 = 0, // the cache length: positions [0, len) hold this stream's keys + base: u64 = 0, // the cache length the last verify started from + hi: usize = 0, // positions written (rejected rows too): release zeroes [0, hi) + rows: std.ArrayList(u32) = .empty, // the last verify's row tokens + last: u64, // the prompt's last row's bf16 logits [V] (the first draw reads them) + rule: u64, // sample.cu's Rule, when the stream samples + sampled: bool = false, + fill: ?usize = null, // a prompt pass going a chunk at a time: where its next chunk starts + first: ?LogRow = null, // the first token's logprob row, with `logprobs` +}; + +pub const Ripple = struct { + gpa: std.mem.Allocator, + d: *const cuda.Driver, + m: *const fwd.Model, + st: fwd.Seq = .{}, // slot 0's positions when the CLI drives the forward itself (cli/cuda_ricursive.zig) + tok: cuda.DeviceBuffer, // int32 drawn tokens: the handle ring, then a round's rows + meta: cuda.DeviceBuffer, // a draw's first position minus one, a window each + words: cuda.DeviceBuffer, // logprob words, word_rows rows of row_words + picks: cuda.DeviceBuffer, // a prompt pass's next tokens (head_rows) + slot_bufs: cuda.DeviceBuffer, // a slot's last-row logits, then its rule, a slot each + sample: cuda.Module, + draws: cuda.sample.Draws, + lanes: std.AutoHashMapUnmanaged(*const Stream, Lane) = .empty, + free: []bool, // slot i is free + next: u64 = 0, + + /// A slot's share of slot_bufs: its last row's logits, then its rule. + fn slotStride(vocab: usize) usize { + return std.mem.alignForward(usize, vocab * 2, 256) + 256; + } + + /// The device bytes `init` allocates for `slots` slots (the caches are the model's, fwd.Model.openBytes). + pub fn openBytes(vocab: usize, slots: usize) usize { + return (ring + round_rows) * 4 + round_rows * 16 + word_rows * row_words * 4 + fwd.head_rows * 4 + slots * slotStride(vocab); + } + + pub fn init(gpa: std.mem.Allocator, d: *const cuda.Driver, m: *const fwd.Model) !Ripple { + const slots = m.arena.slots; + const free = try gpa.alloc(bool, slots); + errdefer gpa.free(free); + @memset(free, true); + var tok = try cuda.DeviceBuffer.alloc(d, (ring + round_rows) * 4); + errdefer tok.free(); + var meta = try cuda.DeviceBuffer.alloc(d, round_rows * 16); + errdefer meta.free(); + var words = try cuda.DeviceBuffer.alloc(d, word_rows * row_words * 4); + errdefer words.free(); + var picks = try cuda.DeviceBuffer.alloc(d, fwd.head_rows * 4); + errdefer picks.free(); + var slot_bufs = try cuda.DeviceBuffer.alloc(d, slots * slotStride(m.c.vocab)); + errdefer slot_bufs.free(); + var sample = try cuda.Module.load(d, cuda.kernels.sample); + errdefer sample.unload(); + const draws = try cuda.sample.Draws.resolve(sample); + return .{ .gpa = gpa, .d = d, .m = m, .tok = tok, .meta = meta, .words = words, .picks = picks, .slot_bufs = slot_bufs, .sample = sample, .draws = draws, .free = free }; + } + + pub fn deinit(x: *Ripple) void { + var it = x.lanes.valueIterator(); + while (it.next()) |l| l.rows.deinit(x.gpa); + x.lanes.deinit(x.gpa); + x.gpa.free(x.free); + x.sample.unload(); + x.slot_bufs.free(); + x.picks.free(); + x.words.free(); + x.meta.free(); + x.tok.free(); + x.* = undefined; + } + + pub fn backend(x: *Ripple) be.Backend { + return .{ .ptr = x, .vtable = &vtable, .chunk_invariant = true }; // chunk cuts give the same bits + } + + const vtable: be.Backend.VTable = .{ .prefill = prefill, .prefill_step = prefillStep, .cancel_prefill = cancelPrefill, .first = first, .queue = queue, .read = read, .verify = verify, .keep = keep, .draft = draft, .release = release, .first_row = firstRow, .prompt_rows = true, .reports_fill = true }; + + /// The round loop's facts: no draft head; host copies verified in windows up to 16 rows, streams sharing a round. + pub fn facts(x: *const Ripple) lanes.Model { + const rows: u32 = @intCast(x.m.round_rows); + return .{ .copy_match = 8, .exact_width = @min(max_window, rows), .gpu_tokens = false, .mtp = false, .speculate = false, .hidden_rows = true, .batch_rows = rows, .max_streams = @intCast(@min(x.m.arena.slots, rows)) }; + } + + fn self(ptr: *anyopaque) *Ripple { + return @ptrCast(@alignCast(ptr)); + } + + fn upload(x: *Ripple, dst: u64, bytes: []const u8) !void { + try cuda.copy_source.enqueue(x.d, dst, bytes, x.m.s); + } + + fn tokAt(x: *const Ripple, i: usize) u64 { + return x.tok.ptr + i * 4; + } + + /// `rows` bf16 logits rows drawn into `out`, row r at `position0 + r` (argmax when greedy). + fn drawRows(x: *Ripple, l: *const Lane, logits: u64, rows: usize, position0: u64, out: u64, meta_at: usize) !void { + const v = x.m.c.vocab; + if (!l.sampled) return x.m.k.argmaxRows(x.m.s, logits, rows, v, v, out); + const meta = [4]i32{ @intCast(position0 - 1), 0, 0, 0 }; + const mp = x.meta.ptr + meta_at * 16; + try x.upload(mp, std.mem.asBytes(&meta)); + try x.draws.draw(x.m.s, logits, v, l.rule, mp, 0, out, rows, null, null); + } + + /// The stream's caches at `at` for the prompt cache, copied behind the chunk that ends there. + pub fn saveState(x: *Ripple, owner: ?*anyopaque, at: u32) !*snap.Saved { + const s: *const Stream = @ptrCast(@alignCast(owner orelse return error.NoOwner)); + const l = x.lanes.getPtr(s) orelse return error.UnknownStream; + if ((l.fill orelse l.len) != at) return error.NotAtMark; // a state is copied only where the pass stands + return snap.save(x.gpa, x.m, l.slot, at); + } + + /// The stream's slot made to hold `k`'s state (a restore outside its prompt pass). + pub fn restoreState(x: *Ripple, owner: ?*anyopaque, k: *const snap.Saved) !void { + const s: *const Stream = @ptrCast(@alignCast(owner orelse return error.NoOwner)); + const l = x.lanes.getPtr(s) orelse return error.UnknownStream; + try snap.restore(x.m, l.slot, k); + l.len = k.at; + l.hi = @max(l.hi, k.at); + } + + pub fn dropState(x: *Ripple, k: *snap.Saved) void { + snap.drop(x.gpa, x.m.s, k); + } + + fn freeSlot(x: *const Ripple) ?usize { + return std.mem.indexOfScalar(bool, x.free, true); + } + + /// Whether a request could start now: a free slot; one that never fits passes (its prefill refuses it by name). + pub fn admits(x: *const Ripple, prompt: usize, max_new: usize) bool { + if (!fits(x.m.context, prompt, max_new)) return true; + return x.freeSlot() != null; + } + + /// A prompt pass begins: a slot, the stream's rule, a kept state restored; where its first chunk starts. + fn opening(x: *Ripple, s: *Stream) !*Lane { + const p = s.prompt(); + if (p.len == 0) return error.EmptyPrompt; + if (!fits(x.m.context, p.len, @as(usize, s.max_new))) return error.PastContext; + if (s.grammar != null) return error.StructuresUnsupported; + const got = try x.lanes.getOrPut(x.gpa, s); + if (!got.found_existing) { + const slot = x.freeSlot() orelse { + x.lanes.removeByPtr(got.key_ptr); + return error.NoFreeSlot; + }; + x.free[slot] = false; + const at = x.slot_bufs.ptr + slot * slotStride(x.m.c.vocab); + got.value_ptr.* = .{ .slot = slot, .last = at, .rule = at + slotStride(x.m.c.vocab) - 256 }; + } + const l = got.value_ptr; + l.sampled = false; + l.first = null; + if (s.sampling) |sp| if (sp.temperature > 0) { + const r = cuda.sample.Rule.from(lanes.gpu_rule.rule(sp)); + try x.upload(l.rule, std.mem.asBytes(&r)); + l.sampled = true; + }; + s.cached = 0; + s.prompt_rows.clearRetainingCapacity(); + // a pass with prompt logprobs starts at 0: every prompt row is scored + l.fill = if (s.prompt_logprobs != null) 0 else x.resumeAt(s, l, p.len); + s.fill_at.store(@intCast(l.fill.?), .monotonic); + return l; + } + + /// The kept state's position, restored into the slot (0: none, not this prompt's, or another shape's). + fn resumeAt(x: *Ripple, s: *Stream, l: *Lane, len: usize) usize { + const saved = s.reuse.saved orelse return 0; + const k: *const snap.Saved = @ptrCast(@alignCast(saved)); + if (k.at != s.reuse.at or k.at == 0 or k.at >= len or !snap.sameKey(k.key, snap.keyOf(x.m.c))) { + s.reuse_failed = true; + return 0; + } + snap.restore(x.m, l.slot, k) catch { + s.reuse_failed = true; + return 0; + }; + l.hi = @max(l.hi, k.at); + s.cached = k.at; + return k.at; + } + + /// The chunk's rows [at, end) that predict a prompt token, `head_rows` at a time: words and rank to prompt rows. + fn promptRows(x: *Ripple, s: *Stream, at: usize, end: usize, k: u8) !void { + const p = s.prompt(); + const v = x.m.c.vocab; + const scored = @min(end, p.len - 1) -| at; + var r0: usize = 0; + while (r0 < scored) : (r0 += fwd.head_rows) { + const n = @min(fwd.head_rows, scored - r0); + const next = p[at + r0 + 1 ..][0..n]; + try x.m.headRows(r0, n); + try x.upload(x.picks.ptr, std.mem.sliceAsBytes(next)); + try x.draws.logprobRows(x.m.s, x.m.b.rows, v, x.picks.ptr, k, true, x.words.ptr, n); + var words: [fwd.head_rows * row_words]u32 = undefined; + try x.m.download(x.words.ptr, std.mem.sliceAsBytes(words[0 .. n * row_words])); + for (next, 0..) |t, i| try s.prompt_rows.append(x.gpa, LogRow.fromWords(words[i * row_words ..][0..row_words], t, k)); + } + } + + /// One chunk of `l.fill`, at most `max_rows` (0: full), cut at the next mark; true once the last prompt row is in. + fn chunk(x: *Ripple, s: *Stream, l: *Lane, max_rows: u32) !bool { + const p = s.prompt(); + const at = l.fill orelse return true; + if (s.isCancelled()) { + s.keepInterruptedPrefill(@intCast(at)); + return error.Cancelled; + } + const rows: usize = if (max_rows == 0) prompt_rows else @min(max_rows, prompt_rows); + var end = @min(p.len, at + rows); + for (s.reuse.marks) |mk| if (mk > at and mk < end) { + end = mk; + }; + const done = end == p.len; + try x.m.prompt(l.slot, at, p[at..end]); + if (s.prompt_logprobs) |k| try x.promptRows(s, at, end, k); + if (done) { + try x.m.head(end - at - 1); + try x.d.check(x.d.api.cuMemcpyDtoDAsync_v2(l.last, x.m.b.logits, x.m.c.vocab * 2, x.m.s.handle), "cuMemcpyDtoDAsync"); + } + s.fill_at.store(@intCast(end), .monotonic); + l.hi = @max(l.hi, end); + l.fill = if (done) null else end; + if (done) l.len = p.len; + if (s.reuse.hook) |hk| if (std.mem.indexOfScalar(u32, s.reuse.marks, @intCast(end)) != null) hk.at(hk.ptr, s, @intCast(end)); + return done; + } + + fn prefill(ptr: *anyopaque, s: *Stream) anyerror!void { + const x = self(ptr); + const l = try x.opening(s); + errdefer x.dropLane(s); + while (!try x.chunk(s, l, 0)) {} + } + + fn prefillStep(ptr: *anyopaque, s: *Stream, max_rows: u32) anyerror!bool { + const x = self(ptr); + const going = if (x.lanes.getPtr(s)) |l| l.fill != null else false; + const l = if (going) x.lanes.getPtr(s).? else try x.opening(s); + errdefer x.dropLane(s); + return x.chunk(s, l, max_rows); + } + + fn cancelPrefill(ptr: *anyopaque, s: *Stream) !void { + const l = self(ptr).lanes.getPtr(s) orelse return; + if (l.fill) |at| s.keepInterruptedPrefill(@intCast(at)); + } + + fn laneOf(x: *Ripple, s: *const Stream) !*Lane { + return x.lanes.getPtr(s) orelse error.UnknownStream; + } + + fn handle(x: *Ripple) u64 { + const h = x.next; + x.next += 1; + return h; + } + + /// The prompt's last row drawn at `position`; with logprobs, its row kept for first_row. + fn first(ptr: *anyopaque, s: *Stream, position: u64) anyerror!u64 { + const x = self(ptr); + const l = try x.laneOf(s); + if (position != l.len or l.fill != null) return error.PositionMismatch; + const h = x.handle(); + try x.drawRows(l, l.last, 1, position, x.tokAt(h % ring), 0); + if (s.logprobs) |k| { + try x.draws.logprobRows(x.m.s, l.last, x.m.c.vocab, x.tokAt(h % ring), k, false, x.words.ptr, 1); + var w: [row_words]u32 = undefined; + try x.m.download(x.words.ptr, std.mem.sliceAsBytes(&w)); + l.first = LogRow.fromWords(&w, try read(x, h), k); + } + return h; + } + + fn firstRow(ptr: *anyopaque, s: *Stream) anyerror!LogRow { + const l = try self(ptr).laneOf(s); + return l.first orelse error.NoFirstRow; + } + + fn value(x: *Ripple, feed: be.Feed) !u32 { + return switch (feed) { + .value => |v| v, + .handle => |h| read(x, h), + }; + } + + /// One token at the cache's end: a round of one row, its row through the head, drawn at `position`. + fn queue(ptr: *anyopaque, s: *Stream, feed: be.Feed, position: u64) anyerror!u64 { + const x = self(ptr); + const l = try x.laneOf(s); + const t = try x.value(feed); + if (l.fill != null or position != l.len + 1) return error.PositionMismatch; + try x.m.round(&.{.{ .slot = l.slot, .p0 = l.len, .tokens = 1 }}, &.{t}); + try x.m.rowLogits(1); + l.len += 1; + l.hi = @max(l.hi, l.len); + const h = x.handle(); + try x.drawRows(l, x.m.b.rows, 1, position, x.tokAt(h % ring), 0); + return h; + } + + fn read(ptr: *anyopaque, h: u64) anyerror!u32 { + const x = self(ptr); + if (h >= x.next or x.next - h > ring) return error.NoSuchToken; + var out: [1]u32 = undefined; + try x.m.download(x.tokAt(h % ring), std.mem.sliceAsBytes(&out)); + return out[0]; + } + + /// Every window's rows in one round (a chain a stream, from its cache length), each window drawn at its positions. + fn verify(ptr: *anyopaque, windows: []const be.Window, out: []be.Verified) anyerror!void { + const x = self(ptr); + const v = x.m.c.vocab; + const chains = try x.gpa.alloc(fwd.Chain, windows.len); + defer x.gpa.free(chains); + var ids: [round_rows]u32 = undefined; + var total: usize = 0; + for (windows, chains) |w, *c| { + if (w.held != 0) return error.NoHeldDrafts; // no draft head: every draft comes from the host + if (w.parents != null) return error.ChainsOnly; + if (w.masks.len != 0) return error.StructuresUnsupported; + const l = try x.laneOf(w.stream); + if (w.rows() > max_window) return error.WindowTooWide; + if (total + w.rows() > @min(round_rows, x.m.round_rows)) return error.RoundTooWide; + if (l.fill != null) return error.PositionMismatch; + l.base = l.len; + l.rows.clearRetainingCapacity(); + try l.rows.append(x.gpa, w.pending); + try l.rows.appendSlice(x.gpa, w.tokens); + for (w.positions, 0..) |pos, r| if (pos != l.base + r + 1) return error.PositionMismatch; + c.* = .{ .slot = l.slot, .p0 = l.base, .tokens = l.rows.items.len }; + @memcpy(ids[total..][0..l.rows.items.len], l.rows.items); + total += l.rows.items.len; + } + try x.m.round(chains, ids[0..total]); + try x.m.rowLogits(total); + var at: usize = 0; + var scored = false; + for (windows, out, 0..) |w, o, i| { + const l = x.lanes.getPtr(w.stream).?; + const n = l.rows.items.len; + const logits = x.m.b.rows + at * v * 2; + try x.drawRows(l, logits, n, w.positions[0], x.tokAt(ring + at), i); + if (o.rows.len > 0) { + try x.draws.logprobRows(x.m.s, logits, v, x.tokAt(ring + at), w.stream.logprobs.?, false, x.words.ptr + at * row_words * 4, n); + scored = true; + } + at += n; + } + var got: [round_rows]u32 = undefined; + try x.m.download(x.tokAt(ring), std.mem.sliceAsBytes(got[0..total])); + var words: [round_rows * row_words]u32 = undefined; + if (scored) try x.m.download(x.words.ptr, std.mem.sliceAsBytes(words[0 .. total * row_words])); + at = 0; + for (windows, out) |w, o| { + const l = x.lanes.getPtr(w.stream).?; + const n = l.rows.items.len; + @memcpy(o.sampled[0..n], got[at..][0..n]); + @memcpy(o.drafts[0 .. n - 1], l.rows.items[1..]); + for (o.rows, o.sampled[0..o.rows.len], at..) |*r, pick, row| r.* = LogRow.fromWords(words[row * row_words ..][0..row_words], pick, w.stream.logprobs.?); + l.len = l.base + n; // a chain keeps every row unless rolled back + l.hi = @max(l.hi, l.len); + at += n; + } + } + + fn keep(ptr: *anyopaque, windows: []const be.Window, paths: []const []const u32) anyerror!void { + const x = self(ptr); + for (windows, paths) |w, path| { + const l = try x.laneOf(w.stream); + if (path.len == 0 or path.len > l.rows.items.len) return error.EmptyPath; + for (path, 0..) |r, i| if (r != i) return error.ChainsOnly; // a chain keeps a prefix of its rows + l.len = l.base + path.len; // caches are positional: the next round overwrites what the rejected rows wrote + } + } + + /// No draft head: absorbing is a no-op, and a request for drafts is refused by name. + fn draft(_: *anyopaque, requests: []const be.DraftRequest) anyerror!void { + for (requests) |r| if (r.depth != 0 or r.lanes != null) return error.NoDraftHead; + } + + /// The stream's slot zeroed where it wrote (a fresh arena's bytes for the next stream) and freed. + fn dropLane(x: *Ripple, s: *const Stream) void { + if (x.lanes.fetchRemove(s)) |entry| { + var l = entry.value; + x.m.reset(l.slot, l.hi) catch |e| std.log.warn("ripple: slot {d} not zeroed on release ({s})", .{ l.slot, @errorName(e) }); + x.free[l.slot] = true; + l.rows.deinit(x.gpa); + } + } + + fn release(ptr: *anyopaque, s: *Stream) void { + self(ptr).dropLane(s); + } +}; + +test "ricursive cuda backend: the verify reserve past a reply; positions opened for a context" { + try std.testing.expect(fits(32784, 30000, 2768)); + try std.testing.expect(fits(32784, 32784 - reserve - 1, 1)); + try std.testing.expect(!fits(32784, 32784 - reserve, 1)); + try std.testing.expect(!fits(32784, 32785, 0)); + try std.testing.expectEqual(@as(usize, 32768 + reserve), physical(32768)); + try std.testing.expect(fits(physical(32768), 32000, 768)); // the asked context holds a prompt and its reply + try std.testing.expectEqual(@as(usize, 262144), physical(262144)); // the model's maximum caps it + try std.testing.expectEqual(@as(usize, round_rows), physical(1)); +} + +test "ricursive cuda backend: windows of 16 rows, a stream a slot, rows a round" { + var m: fwd.Model = undefined; + m.round_rows = round_rows; + m.arena.slots = 6; + const x: Ripple = .{ .gpa = std.testing.allocator, .d = undefined, .m = &m, .tok = undefined, .meta = undefined, .words = undefined, .picks = undefined, .slot_bufs = undefined, .sample = undefined, .draws = undefined, .free = &.{} }; + const f = x.facts(); + try std.testing.expectEqual(@as(u32, 16), f.exact_width); + try std.testing.expectEqual(@as(u32, 6), f.max_streams); + try std.testing.expectEqual(@as(u32, 128), f.batch_rows); + try std.testing.expect(f.hidden_rows and f.copy_drafts and !f.mtp and !f.gpu_tokens); + try std.testing.expect(Ripple.slotStride(100352) >= 100352 * 2 + @sizeOf(cuda.sample.Rule)); + std.testing.refAllDecls(Ripple); +} + +test { + _ = snap; +} diff --git a/zig/src/families/ricursive/cuda_kernels.zig b/zig/src/families/ricursive/cuda_kernels.zig new file mode 100644 index 00000000000..7f2bb50f27b --- /dev/null +++ b/zig/src/families/ricursive/cuda_kernels.zig @@ -0,0 +1,171 @@ +//! Ripple's glue kernels on CUDA (ricursive.cu): the Metal family's glue.metal launches, one by one. + +const std = @import("std"); +const cuda = @import("cuda"); + +const Stream = cuda.Stream; +const Function = cuda.Function; + +fn int(x: usize) c_int { + return @intCast(x); +} + +fn ceil(n: usize, d: usize) u32 { + return @intCast((n + d - 1) / d); +} + +/// Threads a block in every glue launch (ricursive.cuh's NT). +pub const threads = 256; +/// The widest row tf_rc_add_norm holds: each thread four 8-value chunks (MOST). +pub const most_width = 8 * threads * 4; + +pub const Kernels = struct { + mod: cuda.Module, + embed: Function, + add_norm: Function, + gate: Function, + silu_clamp: Function, + // plug-in point: the prep and attention launches, a Function each, tf_rc_ in ricursive.cu + + pub fn load(d: *const cuda.Driver) !Kernels { + if (!cuda.kernels.available) return error.BuiltWithoutKernels; + var mod = try cuda.Module.load(d, cuda.kernels.ricursive); + errdefer mod.unload(); + var k: Kernels = undefined; + k.mod = mod; + inline for (@typeInfo(Kernels).@"struct".field_names, @typeInfo(Kernels).@"struct".field_types) |name, T| if (T == Function) { + const sym = "tf_rc_" ++ name; + @field(k, name) = try mod.function(sym); + }; + return k; + } + + pub fn unload(k: *Kernels) void { + k.mod.unload(); + k.* = undefined; + } +}; + +fn go(f: Function, s: Stream, grid: cuda.Dim3, a: *cuda.Args) !void { + try cuda.launch.launch(f, .{ .grid = grid, .block = .{ .x = threads }, .shared = 0 }, s, a); +} + +/// An elementwise launch's grid: 256 of a row's values a block, a grid row a row (at most 65,535). +fn plane(rows: usize, width: usize) !cuda.Dim3 { + if (rows == 0 or rows > 65535 or width == 0) return error.UnsupportedShape; + return .{ .x = ceil(width, threads), .y = @intCast(rows) }; +} + +/// R and V0 = bf16(E[ids] * scale), the fp32 scale: the residual's rows and the value residual's source (u32 ids). +pub fn embed(k: *const Kernels, s: Stream, ids: u64, table: u64, resid: u64, v0: u64, rows: usize, width: usize, scale: f32) !void { + return embedBy(k.embed, s, ids, table, resid, v0, rows, width, scale); +} + +/// `embed` through `f`: the served kernel or a control of it. +pub fn embedBy(f: Function, s: Stream, ids: u64, table: u64, resid: u64, v0: u64, rows: usize, width: usize, scale: f32) !void { + const grid = try plane(rows, width); + var a: cuda.Args = .{}; + for ([_]u64{ ids, table, resid, v0 }) |v| a.add(v); + a.add(int(rows)); + a.add(int(width)); + a.add(scale); + try go(f, s, grid, &a); +} + +/// One tf_rc_add_norm launch: `branch` 0 skips the add (and `post`), `v0` 0 skips the lerp (and `vx`). +pub const NormRows = struct { + resid: u64, // R, read and written in place + branch: u64 = 0, // Y: the attention's or the FFN's output rows + post: u64 = 0, // w_post, Y's norm weight + next: u64, // w_next, the next norm's weight + v0: u64 = 0, // the value residual's source rows + x: u64, // X: the next norm's rows + vx: u64 = 0, // lerp(V0, X, blend): v's input + rows: usize, + width: usize, + eps: f32, + blend: f32 = 0, +}; + +/// tf_rc_add_norm's layout: 8-value chunks, at most most_width a row, every pointer 16-byte aligned. +pub fn normLayout(p: NormRows) !void { + if (p.width == 0 or p.width % 8 != 0 or p.width > most_width) return error.UnsupportedWidth; + if (p.rows == 0 or p.rows > std.math.maxInt(i32)) return error.UnsupportedShape; + if ((p.branch == 0) != (p.post == 0) or (p.v0 == 0) != (p.vx == 0)) return error.MissingOperand; + for ([_]u64{ p.resid, p.branch, p.post, p.next, p.v0, p.x, p.vx }) |v| if (v % 16 != 0) return error.Misaligned; +} + +/// R = bf16(R + norm(Y, w_post)) with Y, then X = norm(R, w_next), and VX = lerp(V0, X, blend) with V0: a row a block. +pub fn addNorm(k: *const Kernels, s: Stream, p: NormRows) !void { + return addNormBy(k.add_norm, s, p); +} + +/// `addNorm` through `f`: the served kernel or a control of it. +pub fn addNormBy(f: Function, s: Stream, p: NormRows) !void { + try normLayout(p); + var a: cuda.Args = .{}; + for ([_]u64{ p.resid, p.branch, p.post, p.next, p.v0, p.x, p.vx }) |v| a.add(v); + a.add(int(p.rows)); + a.add(int(p.width)); + a.add(p.eps); + a.add(p.blend); + try go(f, s, .{ .x = @intCast(p.rows) }, &a); +} + +/// The attention's output gate in place: A = bf16(A * bf16(sigmoid(G))) over rows of `width` (query heads x 128). +pub fn gate(k: *const Kernels, s: Stream, act: u64, g: u64, rows: usize, width: usize) !void { + return gateBy(k.gate, s, act, g, rows, width); +} + +/// `gate` through `f`: the served kernel or a control of it. +pub fn gateBy(f: Function, s: Stream, act: u64, g: u64, rows: usize, width: usize) !void { + const grid = try plane(rows, width); + var a: cuda.Args = .{}; + a.add(act); + a.add(g); + a.add(int(rows)); + a.add(int(width)); + try go(f, s, grid, &a); +} + +/// A = bf16(bf16(silu(min(g, limit))) * clamp(u, -limit, limit)) from stacked gate | up rows, 2 x `width` each. +pub fn siluClamp(k: *const Kernels, s: Stream, gu: u64, act: u64, rows: usize, width: usize, limit: f32) !void { + return siluClampBy(k.silu_clamp, s, gu, act, rows, width, limit); +} + +/// `siluClamp` through `f`: the served kernel or a control of it. +pub fn siluClampBy(f: Function, s: Stream, gu: u64, act: u64, rows: usize, width: usize, limit: f32) !void { + const grid = try plane(rows, width); + var a: cuda.Args = .{}; + a.add(gu); + a.add(act); + a.add(int(rows)); + a.add(int(width)); + a.add(limit); + try go(f, s, grid, &a); +} + +test "launch geometry: ceilings and the add-norm's layout" { + try std.testing.expectEqual(@as(u32, 20), ceil(5120, threads)); + try std.testing.expectEqual(@as(u32, 40), ceil(10240, threads)); + try std.testing.expectEqual(@as(u32, 160), ceil(40960, threads)); + try std.testing.expectEqual(@as(usize, 8192), most_width); + try std.testing.expectError(error.UnsupportedShape, plane(65536, 5120)); + try std.testing.expectError(error.UnsupportedShape, plane(1, 0)); + const p: NormRows = .{ .resid = 256, .next = 512, .x = 768, .rows = 2048, .width = 5120, .eps = 1e-6 }; + try normLayout(p); + for ([_]usize{ 5124, 8200, 0 }) |w| { + var bad = p; + bad.width = w; + try std.testing.expectError(error.UnsupportedWidth, normLayout(bad)); + } + var bad = p; + bad.branch = 1024; + try std.testing.expectError(error.MissingOperand, normLayout(bad)); + bad = p; + bad.v0 = 1024; + try std.testing.expectError(error.MissingOperand, normLayout(bad)); + bad = p; + bad.x = 776; + try std.testing.expectError(error.Misaligned, normLayout(bad)); +} diff --git a/zig/src/families/ricursive/cuda_model.zig b/zig/src/families/ricursive/cuda_model.zig new file mode 100644 index 00000000000..09af6dbd9d8 --- /dev/null +++ b/zig/src/families/ricursive/cuda_model.zig @@ -0,0 +1,589 @@ +//! Ripple's forward on CUDA: Metal forward.zig's layer order; prompt chunks of one slot, and rounds of rows over slots. +const std = @import("std"); +const cuda = @import("cuda"); +const cfg = @import("config.zig"); +const glue = @import("cuda_kernels.zig"); +const rp = @import("cuda_prep.zig"); +const attn = @import("cuda_attn.zig"); +const wts = @import("cuda_weights.zig"); + +const wa = cuda.window_attention; +const Stream = cuda.Stream; +const DeviceBuffer = cuda.DeviceBuffer; +const Config = cfg.Config; +const Weight = cuda.qmmf.Weight; + +/// A prompt forward's rows at most (a chunk). +pub const prompt_rows = 2048; +/// A sliding layer's ring: the window's keys before a chunk and the chunk's own (window - 1 + 2,048, to 128s). +pub const ring_rows = 3072; +/// Positions a global layer's page holds. +pub const page_tokens = 512; +/// Rows the head writes at once for a chunk's every-row logits. +pub const head_rows = 128; +/// A one-row round's rows: the round maximum of the CLI and the one-stream backend (one-row chain decode). +pub const decode_rows = 1; +/// Device offsets start on 256 bytes (the row kernels read 16-byte chunks). +const buffer_align = 256; + +/// prompt: a chunk by the prompt kernels; decode: a round of one chain by the lane matmul and the decode attention. +pub const Mode = enum { prompt, decode }; + +/// One stream's rows in a round: `tokens` consecutive positions from p0 in its slot. +pub const Chain = struct { slot: usize, p0: usize, tokens: usize }; + +pub const Kernels = @import("cuda_model_kernels.zig").Kernels; + +/// The forward's scratch for `prompt_rows` rows (a round's at most), each at its own 256-byte boundary. +const Bufs = struct { + resid: u64 = 0, // bf16 [R, H]: the residual + v0: u64 = 0, // bf16 [R, H]: the value residual's source (the scaled embedding) + x: u64 = 0, // bf16 [R, H]: the next norm's rows + vx: u64 = 0, // bf16 [R, H]: lerp(v0, x, blend), v's input + y: u64 = 0, // bf16 [R, H]: o's and down's output + qkg: u64 = 0, // bf16 [R, q + kv + q]: the fused projection + v: u64 = 0, // bf16 [R, kv] + q: u64 = 0, // bf16 [R, heads, 128]: prep's normed, rotated queries + att: u64 = 0, // bf16 [R, q]: the attention, then gated in place + g: u64 = 0, // bf16 [R, q]: the gate's rows contiguous (several rows) + gu: u64 = 0, // bf16 [R, 2I]: gate then up a row, as tf_rc_silu_clamp reads them + act: u64 = 0, // bf16 [R, I]: the planar gate, then silu_clamp's output + up: u64 = 0, // bf16 [R, I]: the planar up + ids: u64 = 0, // u32 [R] + pos: u64 = 0, // int32 [round]: a round's rows' positions + slot: u64 = 0, // int32 [round]: a round's rows' slots + inv: u64 = 0, // f32 [64]: RoPE's inverse frequencies + wscr: u64 = 0, // the sliding decode's partials (16 bytes at head dim 128) + part: u64 = 0, // the lane matmul's slice partials at a round's rows + logits: u64 = 0, // bf16 [V]: the last row's + rows: u64 = 0, // bf16 [max(head_rows, round), V]: a chunk's or a round's rows + ctab: u64 = 0, // int32 [round, pages a slot]: a round's call table, row r row r's slot's page ids +}; + +/// The scratch for rounds of at most `round` rows over slots of `per_slot` pages. +fn bufSizes(c: Config, part: usize, round: usize, per_slot: usize) Bufs { + const r = prompt_rows; + const h = c.hidden; + const q = c.queryWidth(); + const f = c.intermediate; + return .{ + .resid = r * h * 2, + .v0 = r * h * 2, + .x = r * h * 2, + .vx = r * h * 2, + .y = r * h * 2, + .qkg = r * wts.qkgWidth(c) * 2, + .v = r * c.kvWidth() * 2, + .q = r * q * 2, + .att = r * q * 2, + .g = r * q * 2, + .gu = r * 2 * f * 2, + .act = r * f * 2, + .up = r * f * 2, + .ids = r * 4, + .pos = round * 4, + .slot = round * 4, + .inv = cfg.head_dim / 2 * 4, + .wscr = wa.WindowAttention.scratchBytes(slidingWindow(c), round), + .part = part, + .logits = c.vocab * 2, + .rows = @max(head_rows, round) * c.vocab * 2, + .ctab = round * per_slot * 4, + }; +} + +/// Each buffer's offset from `base` in field order; the bytes they span. +fn place(sizes: Bufs, base: u64, out: *Bufs) usize { + var at: usize = 0; + inline for (@typeInfo(Bufs).@"struct".field_names) |name| { + @field(out, name) = base + at; + at = std.mem.alignForward(usize, at + @field(sizes, name), buffer_align); + } + return at; +} + +fn slidingWindow(c: Config) wa.Window { + return attn.sliding(c.heads, c.kv_heads, c.window, ring_rows, c.scale()); +} + +/// The pages a slot's global layer holds: the context in whole pages. +pub fn pagesOf(context: usize) usize { + return (context + page_tokens - 1) / page_tokens; +} + +/// A layer's caches from slot 0: a sliding layer's rings [slots][ring][kv_heads][128], or (`pg`) a global's pages. +pub const Cache = struct { kc: u64, vc: u64, pg: ?wa.Pages = null }; + +/// One slot's rows of a layer as a snapshot copies them: position p at ring row p % ring_rows, or global row p. +pub const Span = struct { k: u64, v: u64, rows: usize, row_bytes: usize, ring: bool }; + +/// One slot's caches: a sliding layer's K and V rings, a global layer's K and V pages for `context`. +pub fn slotBytes(c: Config, context: usize) usize { + const kvw = c.kvWidth(); + const g = c.globals(); + return (c.layers - g) * 2 * ring_rows * kvw * 2 + g * 2 * pagesOf(context) * page_tokens * kvw * 2; +} + +/// Every slot's caches in one buffer, a layer at a time (each slot's rows, K then V), then the page table. +pub const Arena = struct { + gpa: std.mem.Allocator, + kv: DeviceBuffer, + caches: []Cache, // a layer each, at slot 0 + ids: []i32, // the page table's host copy [slots][per_slot]: the call tables gather its rows + slots: usize, + per_slot: usize, // pages a slot's global layer holds + kvw: usize, + + /// `slots` slots' caches for `context` positions and the int32 table. + pub fn bytes(c: Config, context: usize, slots: usize) usize { + return slots * slotBytes(c, context) + std.mem.alignForward(usize, slots * pagesOf(context) * 4, buffer_align); + } + + /// Zeroed caches (no stale bits under a masked key), the identity table: slot s's page j is page s * per_slot + j. + pub fn init(gpa: std.mem.Allocator, d: *const cuda.Driver, s: Stream, c: Config, context: usize, slots: usize) !Arena { + const kvw = c.kvWidth(); + const per = pagesOf(context); + var kv = try DeviceBuffer.alloc(d, bytes(c, context, slots)); + errdefer kv.free(); + try d.check(d.api.cuMemsetD8Async(kv.ptr, 0, kv.len, s.handle), "cuMemsetD8Async"); + const caches = try gpa.alloc(Cache, c.layers); + errdefer gpa.free(caches); + const ids = try gpa.alloc(i32, slots * per); + errdefer gpa.free(ids); + for (ids, 0..) |*x, i| x.* = @intCast(i); + const table_at = kv.len - std.mem.alignForward(usize, ids.len * 4, buffer_align); + try cuda.copy_source.enqueue(d, kv.ptr + table_at, std.mem.sliceAsBytes(ids), s); + var at: u64 = kv.ptr; + for (caches, 0..) |*cache, i| { + const half: usize = slots * if (c.global[i]) per * page_tokens * kvw * 2 else ring_rows * kvw * 2; + cache.* = .{ .kc = at, .vc = at + half }; + if (c.global[i]) cache.pg = .{ .table = kv.ptr + table_at, .page_elems = page_tokens * kvw, .tokens = page_tokens, .stride = per }; + at += 2 * half; + } + return .{ .gpa = gpa, .kv = kv, .caches = caches, .ids = ids, .slots = slots, .per_slot = per, .kvw = kvw }; + } + + pub fn deinit(a: *Arena) void { + a.gpa.free(a.ids); + a.gpa.free(a.caches); + a.kv.free(); + a.* = undefined; + } + + /// Layer i's caches of one slot as a prompt chunk reads them: its rings, or the pools and its table row (stride 0). + pub fn slotCache(a: *const Arena, i: usize, slot: usize) Cache { + const c = a.caches[i]; + if (c.pg) |pg| { + var row = pg; + row.table += slot * a.per_slot * 4; + row.stride = 0; + return .{ .kc = c.kc, .vc = c.vc, .pg = row }; + } + const ring = ring_rows * a.kvw * 2; + return .{ .kc = c.kc + slot * ring, .vc = c.vc + slot * ring }; + } + + /// Layer i's rows of one slot. + pub fn span(a: *const Arena, i: usize, slot: usize) Span { + const c = a.caches[i]; + const row = a.kvw * 2; + const rows: usize = if (c.pg != null) a.per_slot * page_tokens else ring_rows; + return .{ .k = c.kc + slot * rows * row, .v = c.vc + slot * rows * row, .rows = rows, .row_bytes = row, .ring = c.pg == null }; + } + + /// The V pools' offset from the K pools in bf16 elements: the same in every global layer. + fn vOff(a: *const Arena) usize { + for (a.caches) |c| if (c.pg != null) return (c.vc - c.kc) / 2; + return 0; + } +}; + +/// A round's rows on the host: positions and slots (int32 for the kernels, usize for the plan), the call table. +const Host = struct { pos: []i32, slot: []i32, at: []usize, ctab: []i32 }; + +/// Checks a round's chains against `ids` and fills the host rows: chain j's rows in order, each slot at most once. +fn fill(h: Host, table: []const i32, per_slot: usize, slots: usize, context: usize, chains: []const Chain, n: usize) !void { + if (n == 0 or n > h.pos.len) return error.ForwardRows; + var r: usize = 0; + for (chains, 0..) |ch, j| { + if (ch.slot >= slots) return error.NoSuchSlot; + if (ch.tokens == 0 or ch.tokens > n - r) return error.ForwardRows; + if (ch.p0 > context or ch.tokens > context - ch.p0) return error.PastContext; + for (chains[0..j]) |o| if (o.slot == ch.slot) return error.SlotTwice; // its rows would race in the caches + for (r..r + ch.tokens, ch.p0..) |row, p| { + h.pos[row] = @intCast(p); + h.slot[row] = @intCast(ch.slot); + h.at[row] = p; + @memcpy(h.ctab[row * per_slot ..][0..per_slot], table[ch.slot * per_slot ..][0..per_slot]); + } + r += ch.tokens; + } + if (r != n) return error.ForwardRows; +} + +/// One slot's stream as the CLI and the one-stream backend drive it: its slot and the positions its caches hold. +pub const Seq = struct { slot: usize = 0, len: usize = 0 }; + +/// A forward's rows: a prompt chunk of one chain, or a round (its global layers' plan, null without global layers). +const Pass = union(enum) { chunk: Chain, round: ?attn.Planned }; + +pub const Model = struct { + gpa: std.mem.Allocator, + d: *const cuda.Driver, + s: Stream, + w: *const wts.Weights, + k: *const Kernels, + c: Config, + context: usize, + /// A round's rows at most (a caller's choice, for example 16 rows for each of its streams; at most prompt_rows). + round_rows: usize, + scratch: DeviceBuffer, + b: Bufs = .{}, + gd: attn.GlobalDecode, + arena: Arena, + host: Host, + /// Rounds replay CUDA graphs (round's `.graph`); false: eager launches with the round's own key groups (B1's). + graphs: bool = true, + /// Captured rounds by row count ([n], n to round_rows), each the layers' launches over the staged rows. + execs: []?cuda.graph.Exec, + + /// The lane's slice partials of every projection and the head at up to `rows` rows (they reduce below fused_rows). + fn partBytes(w: *const wts.Weights, k: *const Kernels, rows: usize) usize { + var most: usize = 0; + for ([_]usize{ rows, @min(rows, cuda.qmmf.fused_rows - 1) }) |m| { + most = @max(most, k.lane.partBytes(m, w.head)); + for (w.layers) |l| for ([_]Weight{ l.qkg, l.v, l.o, l.gate, l.up, l.down }) |x| { + most = @max(most, k.lane.partBytes(m, x)); + }; + } + return most; + } + + /// The device bytes init allocates beside the weights: scratch, `slots` slots' caches, global decode for `round`. + pub fn openBytes(w: *const wts.Weights, k: *const Kernels, context: usize, slots: usize, round_rows: usize) usize { + const c = w.config; + var b: Bufs = .{}; + const scratch = place(bufSizes(c, partBytes(w, k, round_rows), round_rows, pagesOf(context)), 0, &b); + return scratch + Arena.bytes(c, context, slots) + attn.GlobalDecode.bytes(round_rows, context); + } + + /// Scratch for `round_rows`-row rounds and `slots` slots of `context` positions; refuses a shape no ring holds. + pub fn init(gpa: std.mem.Allocator, d: *const cuda.Driver, s: Stream, w: *const wts.Weights, k: *const Kernels, context: usize, slots: usize, round_rows: usize) !Model { + const c = w.config; + if (c.window == 0 or c.window - 1 + prompt_rows > ring_rows) return error.UnsupportedRicursiveCudaShape; + if (context == 0 or context > cfg.max_context) return error.PastContext; + // a round's rows fit the chunk's scratch (and a chain's rows never lap the ring); page ids are int32 + if (round_rows == 0 or round_rows > prompt_rows or round_rows > context or slots == 0 or slots * pagesOf(context) > std.math.maxInt(i32)) return error.ForwardRows; + const sizes = bufSizes(c, partBytes(w, k, round_rows), round_rows, pagesOf(context)); + var b: Bufs = .{}; + var scratch = try DeviceBuffer.alloc(d, place(sizes, 0, &b)); + errdefer scratch.free(); + _ = place(sizes, scratch.ptr, &b); + var inv: [cfg.head_dim / 2]f32 = undefined; + c.inverseFrequencies(&inv); + try cuda.copy_source.enqueue(d, b.inv, std.mem.sliceAsBytes(&inv), s); + var gd = try attn.GlobalDecode.init(d, gpa, round_rows, context); + errdefer gd.deinit(); + var arena = try Arena.init(gpa, d, s, c, context, slots); + errdefer arena.deinit(); + try gd.stage(s, arena.vOff()); + const execs = try gpa.alloc(?cuda.graph.Exec, round_rows + 1); + errdefer gpa.free(execs); + @memset(execs, null); + const h: Host = .{ + .pos = try gpa.alloc(i32, round_rows), + .slot = try gpa.alloc(i32, round_rows), + .at = try gpa.alloc(usize, round_rows), + .ctab = try gpa.alloc(i32, round_rows * arena.per_slot), + }; + return .{ .gpa = gpa, .d = d, .s = s, .w = w, .k = k, .c = c, .context = context, .round_rows = round_rows, .scratch = scratch, .b = b, .gd = gd, .arena = arena, .host = h, .execs = execs }; + } + + pub fn deinit(m: *Model) void { + m.dropGraphs(); + m.gpa.free(m.execs); + m.gpa.free(m.host.ctab); + m.gpa.free(m.host.at); + m.gpa.free(m.host.slot); + m.gpa.free(m.host.pos); + m.arena.deinit(); + m.gd.deinit(); + m.scratch.free(); + m.* = undefined; + } + + /// Zeroes a slot's positions [0, written) (a ring past its rows whole): a fresh arena's bytes, for another stream. + pub fn reset(m: *const Model, slot: usize, written: usize) !void { + if (slot >= m.arena.slots) return error.NoSuchSlot; + for (0..m.c.layers) |i| { + const sp = m.arena.span(i, slot); + const n = @min(written, sp.rows) * sp.row_bytes; + for ([_]u64{ sp.k, sp.v }) |x| try m.d.check(m.d.api.cuMemsetD8Async(x, 0, n, m.s.handle), "cuMemsetD8Async"); + } + } + + fn linear(m: *const Model, x: u64, ldx: usize, n: usize, w: Weight, y: u64, mode: Mode) !void { + if (mode == .decode) return m.k.lane.matmulOut(m.s, x, ldx, n, w, y, .bf16, m.b.part); + return m.k.prompt.matmulOut(m.s, x, ldx, n, w, y, .bf16); + } + + fn copy2D(m: *const Model, src: u64, src_pitch: usize, dst: u64, dst_pitch: usize, width: usize, height: usize) !void { + const p: cuda.abi.Memcpy2D = .{ .src = src, .src_pitch = src_pitch, .dst = dst, .dst_pitch = dst_pitch, .width = width, .height = height }; + try m.d.check(m.d.api.cuMemcpy2DAsync_v2(&p, m.s.handle), "cuMemcpy2DAsync"); + } + + /// Gate and up into gu's rows (gate at column 0, up at column I): one row straight in, else planar then copied. + fn mlpIn(m: *const Model, l: *const wts.Layer, n: usize, mode: Mode) !void { + const h = m.c.hidden; + const f2 = m.c.intermediate * 2; + const b = m.b; + if (n == 1) { + try m.linear(b.x, h, 1, l.gate, b.gu, mode); + return m.linear(b.x, h, 1, l.up, b.gu + f2, mode); + } + try m.linear(b.x, h, n, l.gate, b.act, mode); + try m.linear(b.x, h, n, l.up, b.up, mode); + try m.copy2D(b.act, f2, b.gu, 2 * f2, f2, n); + try m.copy2D(b.up, f2, b.gu + f2, 2 * f2, f2, n); + } + + /// Layer i's q, k, v prep and attention: a chunk's prep and prompt kernels, or a round's prep_rows and decode. + fn attention(m: *const Model, l: *const wts.Layer, i: usize, n: usize, pass: Pass) !void { + const c = m.c; + const b = m.b; + const k = m.k; + const qw = c.queryWidth(); + const kvw = c.kvWidth(); + const wq = wts.qkgWidth(c); + const scale = c.scale(); + const xq = rp.Rows.of(b.qkg, wq); + const xk = rp.Rows.of(b.qkg + qw * 2, wq); + const xv = rp.Rows.of(b.v, kvw); + switch (pass) { + .chunk => |ch| { + const cache = m.arena.slotCache(i, ch.slot); + try rp.prep(&k.prep, m.s, .{ .xq = xq, .xk = xk, .xv = xv, .inv = b.inv, .qw = l.q_norm, .kw = l.k_norm, .q = b.q, .kc = cache.kc, .vc = cache.vc, .rows = n, .heads = c.heads, .kv_heads = c.kv_heads, .pos = ch.p0, .ring = if (cache.pg == null) ring_rows else 0, .rope = !c.global[i], .eps = c.eps, .pg = cache.pg }); + const w = if (cache.pg) |pg| attn.global(c.heads, c.kv_heads, scale, pg) else slidingWindow(c); + return attn.prompt(&k.attn, m.s, b.q, cache.kc, cache.vc, b.att, ch.p0, n, w); + }, + .round => |planned| { + const cache = m.arena.caches[i]; + try rp.prepRows(&k.prep, m.s, .{ .xq = xq, .xk = xk, .xv = xv, .inv = b.inv, .qw = l.q_norm, .kw = l.k_norm, .q = b.q, .kc = cache.kc, .vc = cache.vc, .rows = n, .heads = c.heads, .kv_heads = c.kv_heads, .pos = b.pos, .slot = b.slot, .ring = if (cache.pg == null) ring_rows else 0, .rope = !c.global[i], .eps = c.eps, .pg = cache.pg }); + if (cache.pg) |pg| { + var call = pg; // tree_attention reads its streams' rows: the round's gathered table + call.table = b.ctab; + return attn.runRows(&m.gd, m.s, planned.?, b.q, cache.kc, b.att, c.heads, call, scale); + } + return k.win.decode(m.s, b.q, cache.kc, cache.vc, b.att, b.pos, b.slot, slidingWindow(c), b.wscr, n); + }, + } + } + + /// The forward's n rows (ids uploaded): every layer, then the final norm into x (the heads read it). + fn layers(m: *const Model, n: usize, pass: Pass) !void { + const c = m.c; + const s = m.s; + const b = m.b; + const k = m.k; + const h = c.hidden; + const qw = c.queryWidth(); + const kvw = c.kvWidth(); + const wq = wts.qkgWidth(c); + const mode: Mode = if (pass == .chunk) .prompt else .decode; + const ls = m.w.layers; + try glue.embed(&k.glue, s, b.ids, m.w.embed, b.resid, b.v0, n, h, c.embed_scale); + try glue.addNorm(&k.glue, s, .{ .resid = b.resid, .next = ls[0].input_norm, .v0 = b.v0, .x = b.x, .vx = b.vx, .rows = n, .width = h, .eps = c.eps, .blend = ls[0].blend }); + for (ls, 0..) |*l, i| { + try m.linear(b.x, h, n, l.qkg, b.qkg, mode); + try m.linear(b.vx, h, n, l.v, b.v, mode); + try m.attention(l, i, n, pass); + const g_at = b.qkg + (qw + kvw) * 2; + const g = if (n == 1) g_at else blk: { // tf_rc_gate reads G rows contiguous + try m.copy2D(g_at, wq * 2, b.g, qw * 2, qw * 2, n); + break :blk b.g; + }; + try glue.gate(&k.glue, s, b.att, g, n, qw); + try m.linear(b.att, qw, n, l.o, b.y, mode); + try glue.addNorm(&k.glue, s, .{ .resid = b.resid, .branch = b.y, .post = l.post_attn, .next = l.pre_ffn, .x = b.x, .rows = n, .width = h, .eps = c.eps }); + try m.mlpIn(l, n, mode); + try glue.siluClamp(&k.glue, s, b.gu, b.act, n, c.intermediate, c.clamp); + try m.linear(b.act, c.intermediate, n, l.down, b.y, mode); + if (i + 1 < ls.len) { + const next = &ls[i + 1]; + try glue.addNorm(&k.glue, s, .{ .resid = b.resid, .branch = b.y, .post = l.post_ffn, .next = next.input_norm, .v0 = b.v0, .x = b.x, .vx = b.vx, .rows = n, .width = h, .eps = c.eps, .blend = next.blend }); + } else try glue.addNorm(&k.glue, s, .{ .resid = b.resid, .branch = b.y, .post = l.post_ffn, .next = m.w.norm, .x = b.x, .rows = n, .width = h, .eps = c.eps }); + } + } + + /// A prompt chunk of one slot: `ids` at p0, p0 + 1, ... (at most prompt_rows). + pub fn prompt(m: *const Model, slot: usize, p0: usize, ids: []const u32) !void { + const n = ids.len; + if (n == 0 or n > prompt_rows) return error.ForwardRows; + if (slot >= m.arena.slots) return error.NoSuchSlot; + if (p0 > m.context or n > m.context - p0) return error.PastContext; + try cuda.copy_source.enqueue(m.d, m.b.ids, std.mem.sliceAsBytes(ids), m.s); + try m.layers(n, .{ .chunk = .{ .slot = slot, .p0 = p0, .tokens = n } }); + } + + /// One round: chain j's `tokens` rows at p0, p0 + 1, ... of its slot, each seeing its slot's keys to its position. + pub fn round(m: *const Model, chains: []const Chain, ids: []const u32) !void { + return m.roundAs(chains, ids, if (m.graphs) .graph else .exact); + } + + /// Launches: graph (captured, the context's key groups), exact (eager, own key groups), fixed (eager, graph's). + pub const Run = enum { graph, exact, fixed }; + + /// A round's rows launched as `run` says; ids, positions, slots, table rows and committed keys upload first. + pub fn roundAs(m: *const Model, chains: []const Chain, ids: []const u32, run: Run) !void { + const n = ids.len; + const h = m.host; + try fill(h, m.arena.ids, m.arena.per_slot, m.arena.slots, m.context, chains, n); + const b = m.b; + try cuda.copy_source.enqueue(m.d, b.ids, std.mem.sliceAsBytes(ids), m.s); + try cuda.copy_source.enqueue(m.d, b.pos, std.mem.sliceAsBytes(h.pos[0..n]), m.s); + try cuda.copy_source.enqueue(m.d, b.slot, std.mem.sliceAsBytes(h.slot[0..n]), m.s); + const planned: ?attn.Planned = if (m.c.globals() == 0) null else blk: { + try cuda.copy_source.enqueue(m.d, b.ctab, std.mem.sliceAsBytes(h.ctab[0 .. n * m.arena.per_slot]), m.s); + break :blk try attn.planRows(&m.gd, m.s, h.at[0..n], run != .exact); + }; + if (run != .graph) return m.layers(n, .{ .round = planned }); + const g = &m.execs[n]; + if (g.* == null) g.* = try m.capture(n, planned); + try g.*.?.launchOn(m.s); + } + + /// The layers' launches for a round of n rows as a graph: they read every per-round value from the staged buffers. + fn capture(m: *const Model, n: usize, planned: ?attn.Planned) !cuda.graph.Exec { + try m.s.synchronize(); + try cuda.graph.beginCapture(m.s, .thread_local); + m.layers(n, .{ .round = planned }) catch |e| { + if (cuda.graph.endCapture(m.s)) |g| { + var gg = g; + gg.deinit(); + } else |_| {} + return e; + }; + var g = try cuda.graph.endCapture(m.s); + defer g.deinit(); + return g.instantiate(); + } + + /// Every captured graph dropped (the next round of each row count captures again). + pub fn dropGraphs(m: *const Model) void { + for (m.execs) |*g| if (g.*) |*e| { + e.deinit(); + g.* = null; + }; + } + + /// The row counts whose rounds have a graph. + pub fn captured(m: *const Model) usize { + var n: usize = 0; + for (m.execs) |g| n += @intFromBool(g != null); + return n; + } + + /// `ids` at seq.len, seq.len + 1, ...: a prompt chunk, or (decode) a round of one chain; seq.len moves past them. + pub fn forward(m: *const Model, seq: *Seq, ids: []const u32, mode: Mode) !void { + switch (mode) { + .prompt => try m.prompt(seq.slot, seq.len, ids), + .decode => try m.round(&.{.{ .slot = seq.slot, .p0 = seq.len, .tokens = ids.len }}, ids), + } + seq.len += ids.len; + } + + /// The last forward's row `row` through the bf16 head (the lane matmul) into `logits` [V]. + pub fn head(m: *const Model, row: usize) !void { + const h = m.c.hidden; + try m.k.lane.matmulOut(m.s, m.b.x + row * h * 2, h, 1, m.w.head, m.b.logits, .bf16, m.b.part); + } + + /// The last forward's rows [r0, r0 + rows) (at most head_rows) through the head (the prompt matmul) into `rows`. + pub fn headRows(m: *const Model, r0: usize, rows: usize) !void { + if (rows == 0 or rows > head_rows) return error.ForwardRows; + const h = m.c.hidden; + try m.k.prompt.matmulOut(m.s, m.b.x + r0 * h * 2, h, rows, m.w.head, m.b.rows, .bf16); + } + + /// The last round's rows [0, rows) through the head (the lane matmul, as head's) into `rows` [rows, V]. + pub fn rowLogits(m: *const Model, rows: usize) !void { + if (rows == 0 or rows > m.round_rows) return error.ForwardRows; + try m.k.lane.matmulOut(m.s, m.b.x, m.c.hidden, rows, m.w.head, m.b.rows, .bf16, m.b.part); + } + + /// The greedy draw of `logits` into `out` (int32). + pub fn draw(m: *const Model, out: u64) !void { + try m.k.argmaxRows(m.s, m.b.logits, 1, m.c.vocab, m.c.vocab, out); + } + + /// The greedy draws of rowLogits' rows into `out` (int32 [rows]). + pub fn drawRows(m: *const Model, rows: usize, out: u64) !void { + try m.k.argmaxRows(m.s, m.b.rows, rows, m.c.vocab, m.c.vocab, out); + } + + /// Device bytes at `ptr` into `out`, after the stream's work. + pub fn download(m: *const Model, ptr: u64, out: []u8) !void { + try m.s.synchronize(); + try m.d.check(m.d.api.cuMemcpyDtoH_v2(out.ptr, ptr, out.len), "cuMemcpyDtoH"); + } +}; + +const testing = std.testing; + +fn release() !Config { + var c = try cfg.parse(testing.allocator, @embedFile("fixtures/config.json")); + c.fp4_mlp = true; + return c; +} + +test "ricursive cuda caches: 64 rings of 3,072 rows, 16 layers' pages for the context; slots side by side" { + const c = try release(); + try testing.expectEqual(@as(usize, 16), c.globals()); + const ring = 64 * 2 * 3072 * 1024 * 2; + try testing.expectEqual(ring + 16 * 2 * 64 * 512 * 1024 * 2 + 256, Arena.bytes(c, 32768, 1)); // one slot at the default context + try testing.expectEqual(ring + 16 * 2 * 9 * 512 * 1024 * 2 + 256, Arena.bytes(c, 4096 + 1, 1)); // a part page is a page + try testing.expectEqual(4 * slotBytes(c, 32768) + 4 * 64 * 4, Arena.bytes(c, 32768, 4)); // the table: 4 rows of 64 ids + try testing.expect(c.window - 1 + prompt_rows <= ring_rows); +} + +test "ricursive cuda scratch: every buffer on 256 bytes, about 1 GiB for 2,048 rows" { + const c = try release(); + var b: Bufs = .{}; + const total = place(bufSizes(c, 1 << 20, 1, 64), 4096, &b); + inline for (@typeInfo(Bufs).@"struct".field_names) |name| try testing.expect(@field(b, name) % buffer_align == 0); + try testing.expectEqual(@as(u64, 4096), b.resid); + try testing.expect(b.rows > b.logits and b.logits > b.part); + try testing.expect(total > 1_000_000_000 and total < 1_200_000_000); + var wide: Bufs = .{}; + const sizes = bufSizes(c, 0, 256, 64); + try testing.expectEqual(@as(usize, 256 * c.vocab * 2), sizes.rows); // a round past head_rows: its rows' logits + try testing.expectEqual(@as(usize, 256 * 64 * 4), sizes.ctab); + _ = place(sizes, 0, &wide); +} + +test "ricursive cuda round rows: chains in order, each row its slot's table row; a slot twice or a short round refused" { + const per = 3; + var table: [4 * per]i32 = undefined; + for (&table, 0..) |*x, i| x.* = @intCast(i); + var pos: [8]i32 = undefined; + var slot: [8]i32 = undefined; + var at: [8]usize = undefined; + var ctab: [8 * per]i32 = undefined; + const h: Host = .{ .pos = &pos, .slot = &slot, .at = &at, .ctab = &ctab }; + try fill(h, &table, per, 4, 1536, &.{ .{ .slot = 2, .p0 = 510, .tokens = 3 }, .{ .slot = 0, .p0 = 7, .tokens = 1 } }, 4); + try testing.expectEqualSlices(i32, &.{ 510, 511, 512, 7 }, pos[0..4]); + try testing.expectEqualSlices(i32, &.{ 2, 2, 2, 0 }, slot[0..4]); + try testing.expectEqualSlices(usize, &.{ 510, 511, 512, 7 }, at[0..4]); + try testing.expectEqualSlices(i32, &.{ 6, 7, 8, 6, 7, 8, 6, 7, 8, 0, 1, 2 }, ctab[0 .. 4 * per]); + try testing.expectError(error.SlotTwice, fill(h, &table, per, 4, 1536, &.{ .{ .slot = 1, .p0 = 0, .tokens = 1 }, .{ .slot = 1, .p0 = 1, .tokens = 1 } }, 2)); + try testing.expectError(error.ForwardRows, fill(h, &table, per, 4, 1536, &.{.{ .slot = 1, .p0 = 0, .tokens = 2 }}, 3)); + try testing.expectError(error.ForwardRows, fill(h, &table, per, 4, 1536, &.{.{ .slot = 1, .p0 = 0, .tokens = 9 }}, 9)); + try testing.expectError(error.NoSuchSlot, fill(h, &table, per, 4, 1536, &.{.{ .slot = 4, .p0 = 0, .tokens = 1 }}, 1)); + try testing.expectError(error.PastContext, fill(h, &table, per, 4, 1536, &.{.{ .slot = 3, .p0 = 1535, .tokens = 2 }}, 2)); +} + +test "ricursive cuda forward type-checks against the kernels' wrappers" { + testing.refAllDecls(Model); + testing.refAllDecls(Kernels); + testing.refAllDecls(Arena); +} diff --git a/zig/src/families/ricursive/cuda_model_kernels.zig b/zig/src/families/ricursive/cuda_model_kernels.zig new file mode 100644 index 00000000000..e91e22cec6c --- /dev/null +++ b/zig/src/families/ricursive/cuda_model_kernels.zig @@ -0,0 +1,60 @@ +//! The kernels Ripple's CUDA forward loads together: glue, prep, attention, the lane and prompt matmuls, argmax. +const cuda = @import("cuda"); +const glue = @import("cuda_kernels.zig"); +const rp = @import("cuda_prep.zig"); +const attn = @import("cuda_attn.zig"); + +const wa = cuda.window_attention; +const Stream = cuda.Stream; + +pub const Kernels = struct { + glue: glue.Kernels, + prep: rp.Kernels, + win: wa.WindowAttention, // sliding decode (tf_window_decode_tc); owns the prompt attention's module + attn: attn.Kernels, + lane: cuda.qmmf.Lane, + prompt: cuda.nvfp4.Prompt, + argmax_mod: cuda.Module, + argmax: cuda.Function, // torch.argmax's first maximum, int32 a row + + pub fn load(ctx: *const cuda.Context) !Kernels { + if (!cuda.kernels.available) return error.BuiltWithoutKernels; + const d = ctx.d; + var k: Kernels = undefined; + k.glue = try glue.Kernels.load(d); + errdefer k.glue.unload(); + k.prep = try rp.Kernels.load(d); + errdefer k.prep.unload(); + k.win = try wa.WindowAttention.load(d); + errdefer k.win.unload(); + k.attn = try attn.Kernels.init(&k.win); + k.lane = try cuda.qmmf.Lane.load(d, (try ctx.capability()) / 10); + errdefer k.lane.unload(); + k.prompt = try cuda.nvfp4.Prompt.load(d); + errdefer k.prompt.unload(); + k.argmax_mod = try cuda.Module.load(d, cuda.kernels.torch_argmax); + errdefer k.argmax_mod.unload(); + k.argmax = try k.argmax_mod.function("tf_argmax_rows_i32_kernel"); + return k; + } + + pub fn deinit(k: *Kernels) void { + k.argmax_mod.unload(); + k.prompt.unload(); + k.lane.unload(); + k.win.unload(); + k.prep.unload(); + k.glue.unload(); + k.* = undefined; + } + + /// int32 argmax of `rows` bf16 rows of `vocab` logits (`stride` apart) into `out`. + pub fn argmaxRows(k: *const Kernels, s: Stream, logits: u64, rows: usize, vocab: usize, stride: usize, out: u64) !void { + var a: cuda.Args = .{}; + a.add(logits); + a.add(out); + for ([_]usize{ rows, vocab, stride }) |x| a.add(@as(i64, @intCast(x))); + a.add(@as(i32, 0)); // dtype 0: bf16 + try cuda.launch.launch(k.argmax, .{ .grid = .{ .x = @intCast(rows), .y = 1, .z = 1 }, .block = .{ .x = 1024 }, .shared = 0 }, s, &a); + } +}; diff --git a/zig/src/families/ricursive/cuda_native.zig b/zig/src/families/ricursive/cuda_native.zig new file mode 100644 index 00000000000..2b17bd165e9 --- /dev/null +++ b/zig/src/families/ricursive/cuda_native.zig @@ -0,0 +1,302 @@ +//! Ripple behind the native CUDA registry: several streams, an arena slot each; the prompt cache's states; refusals. +const std = @import("std"); +const cuda = @import("cuda"); +const lanes = @import("lanes"); +const wts = @import("cuda_weights.zig"); +const fwd = @import("cuda_model.zig"); +const be = @import("cuda_backend.zig"); +const cfg = @import("config.zig"); + +const snap = be.snap; + +pub const model_type = "ricursive"; +pub const formats: []const []const u8 = &.{"modelopt-nvfp4"}; +pub const default_context: i64 = 32768; +pub const max_segments: u32 = 1; +pub const prompt_rows: u32 = be.prompt_rows; +/// A kept state is the caches through its position and nothing past it (no draft head reads a token on). +pub const snap_lookahead: u32 = 0; +pub const takes_drafter = false; +pub const drafter_refusal = "--drafter: Ripple on CUDA loads no drafter yet; serve it without --drafter"; +/// `explain` words this family's open refusals too. +pub const explains_open = true; +/// The server's think block rules: Ripple opens `` itself or answers bare, and its markers take no budget. +pub fn thinking(info: anytype) void { + info.reasoning_optional = true; + info.thinking_budget = false; +} + +/// GB10's memory (121.7 GiB), the budget when the server gives no reading of its room. +pub const gb10_bytes: u64 = @intFromFloat(121.7 * (1 << 30)); + +/// The server's reading of the room left after the weights; null if unreadable. +pub const Room = struct { ctx: *anyopaque, read: *const fn (*anyopaque) ?u64 }; +/// --parallel: the streams made at open (auto: the most that fit, at most a round's rows over 16-row windows). +pub const Options = struct { context: usize, drafts: bool, segments: usize = 1, slide: bool = false, lanes: u32 = 8, lanes_fixed: bool = false, room: ?Room = null }; + +/// What the native server drives: every stream's caches, allocated at open. +pub const Loaded = struct { + backend: lanes.backend.Backend, + facts: lanes.Model, + rows: u32, + stream_bytes: usize, + free_streams: u32, + ctx: *anyopaque, + deinit: *const fn (*anyopaque) void, + target: *be.Ripple, // the prompt cache keeps this backend's states (snap_*) +}; + +/// The weights, kernels, stream, forward and backend one open owns. +pub const Owned = struct { gpa: std.mem.Allocator, w: wts.Weights, k: fwd.Kernels, s: cuda.Stream, m: fwd.Model, rb: be.Ripple }; + +/// Device bytes past the weights for the CLI's one stream at `context` positions: scratch, caches, the backend's. +pub fn openBytes(w: *const wts.Weights, k: *const fwd.Kernels, context: usize) u64 { + return fwd.Model.openBytes(w, k, context, 1, fwd.decode_rows) + be.Ripple.openBytes(w.config.vocab, 1); +} + +/// `need` bytes in `room`, or the refusal: the caches of the asked context do not fit. +fn admit(need: u64, room: u64, context: usize) !void { + if (need <= room) return; + std.log.err("ripple: a {d}-token context needs {d:.2} GiB of caches and scratch past the weights; the CUDA memory budget leaves {d:.2} GiB", .{ context, gib(need), gib(room) }); + return error.NoStreamFits; +} + +fn gib(b: u64) f64 { + return @as(f64, @floatFromInt(b)) / (1 << 30); +} + +/// The request's context option, refused past the model's or empty. +fn contextOf(context: usize) !usize { + if (context == 0 or context > cfg.max_context) return error.PastContext; + return context; +} + +/// Streams to allocate in `room`: as asked, else (auto) the most that fit; a fixed count past them or a round refuses. +fn fit(room: u64, asked: u32, fixed: bool, plan: anytype) !usize { + const most = be.round_rows / be.max_window; + if (fixed and asked > most) return error.ParallelPastRound; + var n = std.math.clamp(@as(usize, asked), 1, most); + while (try plan.bytes(n) > room) : (n -= 1) { + if (fixed) return error.ParallelPastMemory; + if (n == 1) return error.NoStreamFits; + } + return n; +} + +/// The device bytes `n` streams take at `positions`: the forward's scratch for a round, their slots, the backend's. +const Plan = struct { + w: *const wts.Weights, + k: *const fwd.Kernels, + positions: usize, + + fn bytes(p: Plan, n: usize) !u64 { + return fwd.Model.openBytes(p.w, p.k, p.positions, n, be.round_rows) + be.Ripple.openBytes(p.w.config.vocab, n); + } +}; + +/// The checkpoint through the CUDA gate, the kernels and a stream; the forward is made by the caller. +fn begin(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: []const u8) !*Owned { + const own = try gpa.create(Owned); + errdefer gpa.destroy(own); + own.gpa = gpa; + own.w = try wts.load(gpa, io, ctx.d, dir); + errdefer own.w.deinit(); + own.k = try fwd.Kernels.load(ctx); + errdefer own.k.deinit(); + own.s = try cuda.Stream.init(ctx.d, false); + return own; +} + +/// begin's parts, freed when an open stops before its forward is made. +fn abandon(own: *Owned) void { + own.s.deinit(); + own.k.deinit(); + own.w.deinit(); + own.gpa.destroy(own); +} + +fn roomOf(room_reading: ?Room) u64 { + // the server's budget; a CLI run has none and lets the allocation refuse, as Dory's does + return if (room_reading) |r| r.read(r.ctx) orelse 0 else std.math.maxInt(u64); +} + +/// The CLI's open: one slot of `context` positions and one-row rounds, if they fit the room (null: unchecked). +pub fn openOwned(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: []const u8, context_asked: usize, room_reading: ?Room) !*Owned { + const context = try contextOf(context_asked); + const own = try begin(gpa, io, ctx, dir); + errdefer abandon(own); + try admit(openBytes(&own.w, &own.k, context), roomOf(room_reading), context); + own.m = try fwd.Model.init(gpa, ctx.d, own.s, &own.w, &own.k, context, 1, fwd.decode_rows); + errdefer own.m.deinit(); + own.rb = try be.Ripple.init(gpa, ctx.d, &own.m); + return own; +} + +pub fn closeOwned(own: *Owned) void { + own.rb.deinit(); + own.m.deinit(); + abandon(own); +} + +/// The server's open: as many streams as asked and fit (auto: the most), each a slot of context and verify reserve. +pub fn open(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: []const u8, kernels: ?[]const u8, o: Options) !Loaded { + if (kernels != null) return error.CapturedKernels; + if (o.lanes_fixed and o.lanes > be.round_rows / be.max_window) return error.ParallelPastRound; // before the weights load + if (o.segments > 1) return error.SegmentsUnsupported; + const positions = be.physical(try contextOf(o.context)); + const own = try begin(gpa, io, ctx, dir); + errdefer abandon(own); + const plan: Plan = .{ .w = &own.w, .k = &own.k, .positions = positions }; + const room = roomOf(o.room); + const n = fit(room, o.lanes, o.lanes_fixed, plan) catch |e| { + if (e == error.ParallelPastMemory) { + const most = fit(room, o.lanes, false, plan) catch 0; + std.log.err("--parallel {d} needs {d:.2} GiB at a {d}-token context, and the CUDA memory budget leaves {d:.2} GiB after the weights: {d} stream{s} fit", .{ o.lanes, gib(try plan.bytes(o.lanes)), o.context, gib(room), most, if (most == 1) "" else "s" }); + } + if (e == error.NoStreamFits) std.log.err("ripple: one stream at a {d}-token context needs {d:.2} GiB of caches and scratch past the weights; the CUDA memory budget leaves {d:.2} GiB", .{ o.context, gib(try plan.bytes(1)), gib(room) }); + return e; + }; + own.m = try fwd.Model.init(gpa, ctx.d, own.s, &own.w, &own.k, positions, n, be.round_rows); + errdefer own.m.deinit(); + own.rb = try be.Ripple.init(gpa, ctx.d, &own.m); + std.log.info("Ripple on CUDA: {d} stream{s} of {d} positions (a {d}-token context and a {d}-row verify reserve), rounds of {d} rows, prompt chunks of {d}", .{ n, if (n == 1) "" else "s", positions, o.context, be.reserve, be.round_rows, fwd.prompt_rows }); + return .{ + .backend = own.rb.backend(), + .facts = own.rb.facts(), + .rows = be.max_window, + .stream_bytes = fwd.Arena.bytes(own.w.config, positions, 1), + .free_streams = @intCast(n), + .ctx = own, + .deinit = release, + .target = &own.rb, + }; +} + +fn release(p: *anyopaque) void { + closeOwned(@ptrCast(@alignCast(p))); +} + +/// Whether a request's caches could start now (the lane host's admission, on its engine thread). +pub fn fits(p: *anyopaque, prompt: u32, max_tokens: u32) bool { + const own: *const Owned = @ptrCast(@alignCast(p)); + return own.rb.admits(prompt, max_tokens); +} + +fn ripple(ptr: *anyopaque) *be.Ripple { + return @ptrCast(@alignCast(ptr)); +} + +/// Bytes a state at `at` prompt tokens takes. +pub fn snap_bytes(ptr: *anyopaque, at: u32) u64 { + return snap.bytes(ripple(ptr).m.c, at); +} + +/// The prompt pass stands at `at` (a chunk start or a mark): copy the stream's caches there. +pub fn snap_save(ptr: *anyopaque, owner: ?*anyopaque, at: u32) anyerror!*anyopaque { + return @ptrCast(try ripple(ptr).saveState(owner, at)); +} + +pub fn snap_restore(ptr: *anyopaque, owner: ?*anyopaque, saved: *anyopaque) anyerror!void { + return ripple(ptr).restoreState(owner, @ptrCast(@alignCast(saved))); +} + +pub fn snap_drop(ptr: *anyopaque, saved: *anyopaque) void { + ripple(ptr).dropState(@ptrCast(@alignCast(saved))); +} + +/// A request or load this engine refuses, in words; null: none of its own. +pub fn explain(_: ?*anyopaque, err: anyerror) ?[]const u8 { + return switch (err) { + error.PastContext => "the prompt and its reply exceed this server's context window: shorten it, lower max_tokens or raise --context (at most 262,144)", + error.NoFreeSlot => "every stream's caches are in use: retry once another request ends", + error.NoStreamFits => "the CUDA memory budget fits no Ripple stream at this context after the weights: lower --context, free device memory, or adjust TENSORFOLD_MEMORY_RESERVE_GIB / TENSORFOLD_CUDA_MEMORY_LIMIT_GB", + error.ParallelPastRound => std.fmt.comptimePrint("--parallel: Ripple on CUDA holds at most {d} streams (a round's rows over 16-row windows): serve --parallel {d} or fewer, or auto", .{ be.round_rows / be.max_window, be.round_rows / be.max_window }), + error.ParallelPastMemory => "--parallel: the CUDA memory budget fits fewer Ripple streams than asked (each stream's caches are allocated at load): lower --parallel or --context, serve --parallel auto, or adjust TENSORFOLD_MEMORY_RESERVE_GIB / TENSORFOLD_CUDA_MEMORY_LIMIT_GB", + error.SegmentsUnsupported => "--segments: Ripple on CUDA runs its prompt chunks one after another: serve without --segments", + error.NoDraftHead => "Ripple on CUDA has no draft head: drafts come from the prompt's own text only", + error.StructuresUnsupported => "structured output is not built for Ripple on CUDA yet", + error.CapturedKernels => "Ripple runs on the engine's own kernels: unset TENSORFOLD_CUDA_KERNELS", + error.BuiltWithoutKernels => "this build carries no CUDA kernel images: build with -Dnvcc", + error.RicursiveCudaNeedsNvfp4 => "Ripple on CUDA serves the NVFP4 release (ModelOpt W4A16 MLPs, bf16 attention): the BF16 checkpoint's 130 GB do not fit GB10", + error.UnsupportedRicursiveCudaShape => "this Ripple checkpoint's shape is not one the CUDA kernels take (group of 2 to 16 query heads in pairs, hidden size at most 8,192, widths in whole 128s)", + error.Unimplemented => "Ripple's CUDA global-layer decode is not in this build yet", + else => null, + }; +} + +test "ricursive cuda native: a reply thinks or answers bare, with no thinking budget, as on Metal" { + var info: struct { reasoning_optional: bool = false, thinking_budget: bool = true } = .{}; + thinking(&info); + try std.testing.expect(info.reasoning_optional and !info.thinking_budget); +} + +test "ricursive cuda native: every refusal of its own is worded, the rest left to the server" { + for ([_]anyerror{ error.PastContext, error.NoFreeSlot, error.NoStreamFits, error.ParallelPastRound, error.ParallelPastMemory, error.SegmentsUnsupported, error.NoDraftHead, error.StructuresUnsupported, error.CapturedKernels, error.BuiltWithoutKernels, error.RicursiveCudaNeedsNvfp4, error.UnsupportedRicursiveCudaShape, error.Unimplemented }) |e| { + try std.testing.expect(explain(null, e) != null); + } + for ([_]anyerror{ error.OutOfMemory, error.SamplingUnsupported, error.LogprobsUnsupported, error.WindowTooWide }) |e| { + try std.testing.expect(explain(null, e) == null); + } +} + +test "ricursive cuda native: the release at 32,768 and 262,144 positions on GB10; a context past the room refused" { + var c = try cfg.parse(std.testing.allocator, @embedFile("fixtures/config.json")); + c.fp4_mlp = true; + const weights: u64 = wts.deviceBytes(c); + const scratch: u64 = 1_200_000_000; // the forward's 2,048 rows (cuda_model's test bounds it) + for ([_]usize{ 32768, 262144 }) |context| { + const need = fwd.Arena.bytes(c, be.physical(context), 1) + scratch; + try admit(need, gb10_bytes - weights, context); + } + try std.testing.expectEqual(@as(usize, 32768), try contextOf(32768)); + try std.testing.expectError(error.PastContext, contextOf(cfg.max_context + 1)); + try std.testing.expectError(error.PastContext, contextOf(0)); +} + +/// A synthetic plan: `stream` bytes a stream plus `fixed` bytes of scratch. +const Fake = struct { + stream: u64, + fixed: u64, + fn bytes(f: Fake, n: usize) !u64 { + return f.fixed + n * f.stream; + } +}; + +test "ricursive cuda native: the streams made at open fit the room; auto takes what fits, a fixed count refuses" { + const g: u64 = 1 << 30; + const one: Fake = .{ .stream = g, .fixed = 0 }; + try std.testing.expectEqual(@as(usize, 2), try fit(2 * g, 8, false, one)); + try std.testing.expectError(error.ParallelPastMemory, fit(2 * g, 8, true, one)); + try std.testing.expectEqual(@as(usize, 1), try fit(5 * g / 2, 8, false, Fake{ .stream = g, .fixed = g })); + try std.testing.expectError(error.NoStreamFits, fit(g - 1, 8, false, one)); + try std.testing.expectEqual(@as(usize, 8), try fit(std.math.maxInt(u64), 8, false, one)); + try std.testing.expectEqual(@as(usize, 8), try fit(std.math.maxInt(u64), 64, false, one)); + try std.testing.expectError(error.ParallelPastRound, fit(1024 * g, 9, true, one)); +} + +test "ricursive cuda native: streams at a context on GB10 by the release's slot bytes" { + var c = try cfg.parse(std.testing.allocator, @embedFile("fixtures/config.json")); + c.fp4_mlp = true; + const room = gb10_bytes - wts.deviceBytes(c); + const scratch: u64 = 1_400_000_000; // a round's and a chunk's scratch, about (cuda_model's test bounds the chunk's) + // a slot: 64 rings of 3,072 rows (805 MB) and 16 global layers' pages for the positions + const Slots = struct { + c: cfg.Config, + positions: usize, + fixed: u64, + fn bytes(p: @This(), n: usize) !u64 { + return p.fixed + fwd.Arena.bytes(p.c, p.positions, n); + } + }; + try std.testing.expectEqual(@as(usize, 8), try fit(room, 8, false, Slots{ .c = c, .positions = be.physical(32768), .fixed = scratch })); + try std.testing.expect(try fit(room, 8, false, Slots{ .c = c, .positions = be.physical(262144), .fixed = scratch }) < 8); +} + +test "the prompt cache's hooks compile against the store's vtable" { + const pc: struct { bytes: *const fn (*anyopaque, u32) u64, save: *const fn (*anyopaque, ?*anyopaque, u32) anyerror!*anyopaque, restore: *const fn (*anyopaque, ?*anyopaque, *anyopaque) anyerror!void, drop: *const fn (*anyopaque, *anyopaque) void } = .{ .bytes = snap_bytes, .save = snap_save, .restore = snap_restore, .drop = snap_drop }; + try std.testing.expect(@intFromPtr(pc.save) != 0); +} + +test "ricursive cuda native: the open path type-checks against the registry's shape" { + std.testing.refAllDecls(@This()); +} diff --git a/zig/src/families/ricursive/cuda_prep.zig b/zig/src/families/ricursive/cuda_prep.zig new file mode 100644 index 00000000000..9c78409c31d --- /dev/null +++ b/zig/src/families/ricursive/cuda_prep.zig @@ -0,0 +1,170 @@ +//! Ripple's attention prep on CUDA (ricursive_prep.cu): glue.metal's rc_prep, q dense and k, v into a ring or pages. + +const std = @import("std"); +const cuda = @import("cuda"); + +const Stream = cuda.Stream; +const Function = cuda.Function; +/// A stream's pages as window_attention's paged prompt reads them; `stride` (a slot's table entries) is prep_rows'. +pub const Pages = cuda.window_attention.Pages; + +const head_dim = 128; + +/// A warp a (head, row), 8 warps a block: tf_rc_prep's and tf_rc_prep_rows' __launch_bounds__. +const warps = 8; +const threads = 32 * warps; + +fn int(x: usize) c_int { + return @intCast(x); +} + +fn ceil(n: usize, d: usize) u32 { + return @intCast((n + d - 1) / d); +} + +pub const Kernels = struct { + mod: cuda.Module, + prep: Function, + prep_rows: Function, + + pub fn load(d: *const cuda.Driver) !Kernels { + if (!cuda.kernels.available) return error.BuiltWithoutKernels; + var mod = try cuda.Module.load(d, cuda.kernels.ricursive_prep); + errdefer mod.unload(); + return .{ .mod = mod, .prep = try mod.function("tf_rc_prep"), .prep_rows = try mod.function("tf_rc_prep_rows") }; + } + + pub fn unload(k: *Kernels) void { + k.mod.unload(); + k.* = undefined; + } +}; + +/// One projection's bf16 output rows (ricursive_prep.cuh Rows): the first row and the elements between rows. +pub const Rows = extern struct { + x: u64, + stride: i32, + pad: i32 = 0, + + pub fn of(x: u64, stride: usize) Rows { + return .{ .x = x, .stride = int(stride) }; + } +}; + +/// `rows` rows at pos + row: q, and k and v at ring slot (pos + row) % ring or in pages; `rope` false: NoPE, normed. +pub const Prep = struct { xq: Rows, xk: Rows, xv: Rows, inv: u64, qw: u64, kw: u64, q: u64, kc: u64, vc: u64, rows: usize, heads: usize, kv_heads: usize, pos: usize, ring: usize, rope: bool, eps: f32, pg: ?Pages = null }; + +/// The writes the kernel takes: a ring at least the call's rows, or pages each holding `tokens` whole rows. +pub fn admit(p: Prep) !void { + if (p.pos + p.rows > std.math.maxInt(i32)) return error.PrepShape; + if (p.pg) |pg| { + if (pg.tokens == 0 or pg.tokens > std.math.maxInt(i32) or pg.page_elems < pg.tokens * p.kv_heads * head_dim or pg.page_elems > std.math.maxInt(i63)) return error.PageShape; + } else if (p.rows > p.ring) return error.RingTooSmall; // a call's rows would overwrite their own slots +} + +/// A block of 8 heads across, a row down. +pub fn grid(p: Prep) cuda.Dim3 { + return .{ .x = ceil(p.heads + p.kv_heads, warps), .y = @intCast(p.rows), .z = 1 }; +} + +pub fn prep(k: *const Kernels, s: Stream, p: Prep) !void { + return prepVia(k.prep, null, s, p); +} + +/// The launch on `f`: the served tf_rc_prep, or (keep not null) contract_controls' tf_ctl_rc_prep keeping those points. +pub fn prepVia(f: Function, keep: ?i32, s: Stream, p: Prep) !void { + if (p.rows == 0) return; + try admit(p); + var a: cuda.Args = .{}; + for ([_]Rows{ p.xq, p.xk, p.xv }) |r| a.add(r); + for ([_]u64{ p.inv, p.qw, p.kw, p.q, p.kc, p.vc }) |v| a.add(v); + for ([_]usize{ p.rows, p.heads, p.kv_heads, p.pos, p.ring }) |v| a.add(int(v)); + a.add(@as(c_int, @intFromBool(p.rope))); + a.add(p.eps); + a.add(if (p.pg) |pg| pg.table else @as(u64, 0)); // null: the ring + a.add(@as(i64, if (p.pg) |pg| @intCast(pg.page_elems) else 0)); + a.add(@as(c_int, if (p.pg) |pg| @intCast(pg.tokens) else 0)); + if (keep) |v| a.add(@as(c_int, v)); + try cuda.launch.launch(f, .{ .grid = grid(p), .block = .{ .x = threads }, .shared = 0 }, s, &a); +} + +/// tf_rc_prep_rows: row r at pos[r] of stream slot[r] (device int32, replayable); rows a ring apart must not share. +pub const PrepRows = struct { xq: Rows, xk: Rows, xv: Rows, inv: u64, qw: u64, kw: u64, q: u64, kc: u64, vc: u64, rows: usize, heads: usize, kv_heads: usize, pos: u64, slot: ?u64 = null, ring: usize, rope: bool, eps: f32, pg: ?Pages = null }; + +/// The writes tf_rc_prep_rows takes: a ring (positions on the device, unchecked), or pages of `tokens` whole rows. +pub fn admitRows(p: PrepRows) !void { + if (p.pg) |pg| { + if (pg.tokens == 0 or pg.tokens > std.math.maxInt(i32) or pg.page_elems < pg.tokens * p.kv_heads * head_dim or pg.page_elems > std.math.maxInt(i63) or pg.stride > std.math.maxInt(i32)) return error.PageShape; + } else if (p.ring == 0 or p.ring > std.math.maxInt(i32)) return error.RingTooSmall; +} + +/// tf_rc_prep's grid: a block of 8 heads across, a row down. +pub fn gridRows(p: PrepRows) cuda.Dim3 { + return .{ .x = ceil(p.heads + p.kv_heads, warps), .y = @intCast(p.rows), .z = 1 }; +} + +pub fn prepRows(k: *const Kernels, s: Stream, p: PrepRows) !void { + return prepRowsVia(k.prep_rows, null, s, p); +} + +/// The launch on `f`: the served tf_rc_prep_rows, or (keep not null) contract_controls' tf_ctl_rc_prep_rows. +pub fn prepRowsVia(f: Function, keep: ?i32, s: Stream, p: PrepRows) !void { + if (p.rows == 0) return; + try admitRows(p); + var a: cuda.Args = .{}; + for ([_]Rows{ p.xq, p.xk, p.xv }) |r| a.add(r); + for ([_]u64{ p.inv, p.qw, p.kw, p.q, p.kc, p.vc }) |v| a.add(v); + for ([_]usize{ p.rows, p.heads, p.kv_heads }) |v| a.add(int(v)); + a.add(p.pos); + a.add(p.slot orelse @as(u64, 0)); // null: stream 0 + a.add(int(p.ring)); + a.add(@as(c_int, @intFromBool(p.rope))); + a.add(p.eps); + a.add(if (p.pg) |pg| pg.table else @as(u64, 0)); // null: the rings + a.add(@as(i64, if (p.pg) |pg| @intCast(pg.page_elems) else 0)); + a.add(@as(c_int, if (p.pg) |pg| @intCast(pg.tokens) else 0)); + a.add(@as(c_int, if (p.pg) |pg| @intCast(pg.stride) else 0)); + if (keep) |v| a.add(@as(c_int, v)); + try cuda.launch.launch(f, .{ .grid = gridRows(p), .block = .{ .x = threads }, .shared = 0 }, s, &a); +} + +test "launch geometry: 88 heads in 11 blocks a row, Rows as the kernel's struct" { + const p: Prep = .{ .xq = Rows.of(0, 0), .xk = Rows.of(0, 0), .xv = Rows.of(0, 0), .inv = 0, .qw = 0, .kw = 0, .q = 0, .kc = 0, .vc = 0, .rows = 2048, .heads = 80, .kv_heads = 8, .pos = 0, .ring = 3072, .rope = true, .eps = 1e-6 }; + const g = grid(p); + try std.testing.expectEqual(@as(c_uint, 11), g.x); + try std.testing.expectEqual(@as(c_uint, 2048), g.y); + try std.testing.expectEqual(@as(usize, 16), @sizeOf(Rows)); +} + +test "admit: a ring holds the call's rows; pages hold 512 whole rows of 8 heads" { + const t = std.testing; + var p: Prep = .{ .xq = Rows.of(0, 0), .xk = Rows.of(0, 0), .xv = Rows.of(0, 0), .inv = 0, .qw = 0, .kw = 0, .q = 0, .kc = 0, .vc = 0, .rows = 2048, .heads = 80, .kv_heads = 8, .pos = 6000, .ring = 3072, .rope = true, .eps = 1e-6 }; + try admit(p); + p.ring = 2047; + try t.expectError(error.RingTooSmall, admit(p)); + p.pg = .{ .table = 0, .page_elems = 512 * 8 * 128, .tokens = 512 }; + try admit(p); // pages: no ring + p.pg.?.page_elems -= 1; + try t.expectError(error.PageShape, admit(p)); + p.pg = .{ .table = 0, .page_elems = 0, .tokens = 0 }; + try t.expectError(error.PageShape, admit(p)); +} + +test "rows: tf_rc_prep's grid; a ring of some rows, or pages of whole rows and an int32 table stride" { + const t = std.testing; + var p: PrepRows = .{ .xq = Rows.of(0, 0), .xk = Rows.of(0, 0), .xv = Rows.of(0, 0), .inv = 0, .qw = 0, .kw = 0, .q = 0, .kc = 0, .vc = 0, .rows = 64, .heads = 80, .kv_heads = 8, .pos = 0, .ring = 3072, .rope = true, .eps = 1e-6 }; + const g = gridRows(p); + try t.expectEqual(@as(c_uint, 11), g.x); + try t.expectEqual(@as(c_uint, 64), g.y); + try admitRows(p); + p.rows = 4096; // several streams' rows: more than one ring holds, each in its own + try admitRows(p); + p.ring = 0; + try t.expectError(error.RingTooSmall, admitRows(p)); + p.pg = .{ .table = 0, .page_elems = 512 * 8 * 128, .tokens = 512, .stride = 256 }; + try admitRows(p); // pages: no ring + p.pg.?.stride = 1 << 31; + try t.expectError(error.PageShape, admitRows(p)); + p.pg = .{ .table = 0, .page_elems = 512 * 8 * 128 - 1, .tokens = 512, .stride = 256 }; + try t.expectError(error.PageShape, admitRows(p)); +} diff --git a/zig/src/families/ricursive/cuda_snap.zig b/zig/src/families/ricursive/cuda_snap.zig new file mode 100644 index 00000000000..9a8c6fc1805 --- /dev/null +++ b/zig/src/families/ricursive/cuda_snap.zig @@ -0,0 +1,169 @@ +//! A stream's caches for the prompt cache: each sliding layer's last window - 1 ring rows, each global's first `at`. +const std = @import("std"); +const cuda = @import("cuda"); +const cfg = @import("config.zig"); +const fwd = @import("cuda_model.zig"); + +/// What a state was made under: its layers, which of them are global, the window and the KV width. +pub const Key = struct { layers: u32, global: [cfg.max_layers]bool, window: u32, kv_width: u32 }; + +/// The key every state of a model at `c` carries. +pub fn keyOf(c: cfg.Config) Key { + return .{ .layers = @intCast(c.layers), .global = c.global, .window = @intCast(c.window), .kv_width = @intCast(c.kvWidth()) }; +} + +pub fn sameKey(a: Key, b: Key) bool { + return std.meta.eql(a, b); +} + +/// A kept state: a layer at a time, K then V, global layers' positions [0, at), sliding rings' last positions in order. +pub const Saved = struct { at: u32, key: Key, buf: cuda.DeviceBuffer }; + +/// Positions a sliding ring keeps at `at`: a later row at `at` or past reads keys from at - window + 1 on. +fn tail(window: usize, at: usize) usize { + return @min(at, window - 1); +} + +/// Bytes a state at `at` takes. +pub fn bytes(c: cfg.Config, at: usize) u64 { + const row = c.kvWidth() * 2; + var n: usize = 0; + for (0..c.layers) |i| n += 2 * (if (c.global[i]) at else tail(c.window, at)) * row; + return n; +} + +/// Each layer's K then V rows of `slot` for positions [first, at): one call a run of consecutive rows, in order. +fn each(a: *const fwd.Arena, window: usize, slot: usize, at: usize, ctx: anytype, comptime f: fn (@TypeOf(ctx), dev: u64, off: usize, len: usize) anyerror!void) !void { + var off: usize = 0; + for (0..a.caches.len) |i| { + const sp = a.span(i, slot); + for ([_]u64{ sp.k, sp.v }) |base| { + var p = if (sp.ring) at - tail(window, at) else 0; + while (p < at) { + const row = if (sp.ring) p % sp.rows else p; // a global layer's table is the identity + const run = @min(at - p, sp.rows - row); + try f(ctx, base + row * sp.row_bytes, off, run * sp.row_bytes); + off += run * sp.row_bytes; + p += run; + } + } + } +} + +const Copy = struct { d: *const cuda.Driver, s: cuda.Stream, buf: u64, out: bool }; + +fn copy(c: Copy, dev: u64, off: usize, len: usize) anyerror!void { + const src = if (c.out) dev else c.buf + off; + const dst = if (c.out) c.buf + off else dev; + try c.d.check(c.d.api.cuMemcpyDtoDAsync_v2(dst, src, len, c.s.handle), "cuMemcpyDtoDAsync"); +} + +/// Copy `slot`'s state at `at` into new storage, queued on the model's stream behind the chunk that ends there. +pub fn save(gpa: std.mem.Allocator, m: *const fwd.Model, slot: usize, at: u32) !*Saved { + if (at == 0 or at > m.context) return error.NotAtMark; + const k = try gpa.create(Saved); + errdefer gpa.destroy(k); + k.* = .{ .at = at, .key = keyOf(m.c), .buf = try cuda.DeviceBuffer.alloc(m.d, @max(bytes(m.c, at), 256)) }; + errdefer k.buf.free(); + try each(&m.arena, m.c.window, slot, at, Copy{ .d = m.d, .s = m.s, .buf = k.buf.ptr, .out = true }, copy); + return k; +} + +/// Make `slot`'s caches hold `k`'s state, queued before its next chunk; another shape's state is refused. +pub fn restore(m: *const fwd.Model, slot: usize, k: *const Saved) !void { + if (!sameKey(k.key, keyOf(m.c))) return error.StateOfAnotherShape; + if (k.at == 0 or k.at > m.context) return error.PastContext; + try each(&m.arena, m.c.window, slot, k.at, Copy{ .d = m.d, .s = m.s, .buf = k.buf.ptr, .out = false }, copy); +} + +/// Free a state once the queued copies of it are done. +pub fn drop(gpa: std.mem.Allocator, s: cuda.Stream, k: *Saved) void { + s.synchronize() catch {}; + k.buf.free(); + gpa.destroy(k); +} + +const testing = std.testing; + +const Count = struct { + runs: *std.ArrayList([3]usize), + fn add(c: Count, dev: u64, off: usize, len: usize) anyerror!void { + try c.runs.append(testing.allocator, .{ dev, off, len }); + } +}; + +fn release() !cfg.Config { + var c = try cfg.parse(testing.allocator, @embedFile("fixtures/config.json")); + c.fp4_mlp = true; + return c; +} + +/// An arena of `slots` slots at `context` positions with fake device addresses (no device memory): layer i at i << 40. +fn fakeArena(c: cfg.Config, caches: []fwd.Cache, slots: usize, context: usize) fwd.Arena { + const per = fwd.pagesOf(context); + const kvw = c.kvWidth(); + for (caches, 0..) |*x, i| { + const half: usize = slots * if (c.global[i]) per * fwd.page_tokens * kvw * 2 else fwd.ring_rows * kvw * 2; + x.* = .{ .kc = @as(u64, i + 1) << 40, .vc = (@as(u64, i + 1) << 40) + half }; + if (c.global[i]) x.pg = .{ .table = 0, .page_elems = fwd.page_tokens * kvw, .tokens = fwd.page_tokens, .stride = per }; + } + return .{ .gpa = testing.allocator, .kv = undefined, .caches = caches, .ids = &.{}, .slots = slots, .per_slot = per, .kvw = kvw }; +} + +test "ricursive cuda state: each ring's last 1,023 rows at their ring rows, wrapped in two runs; globals' first at rows" { + const c = try release(); + var caches: [cfg.max_layers]fwd.Cache = undefined; + const a = fakeArena(c, caches[0..c.layers], 3, 8192); + const rb = c.kvWidth() * 2; + const at = 3500; // a ring of 3,072: positions 2,477 to 3,071 then 3,072 to 3,499 at ring rows 0 to 427 + try testing.expectEqual(@as(usize, 2048), rb); + try testing.expectEqual(@as(u64, 2 * (16 * at + 64 * 1023) * rb), bytes(c, at)); + var runs: std.ArrayList([3]usize) = .empty; + defer runs.deinit(testing.allocator); + try each(&a, c.window, 2, at, Count{ .runs = &runs }, Count.add); + try testing.expectEqual(@as(usize, 2 * (16 + 64 * 2)), runs.items.len); + // layer 0 is sliding: slot 2's ring starts 2 * 3,072 rows in; its K rows 2,477.. then 0.. + const k0 = caches[0].kc + 2 * fwd.ring_rows * rb; + try testing.expectEqual([3]usize{ k0 + (at - 1023) * rb, 0, (fwd.ring_rows - (at - 1023)) * rb }, runs.items[0]); + try testing.expectEqual([3]usize{ k0, runs.items[0][2], (at % fwd.ring_rows) * rb }, runs.items[1]); + try testing.expectEqual(caches[0].vc + 2 * fwd.ring_rows * rb + (at - 1023) * rb, runs.items[2][0]); + // layer 4 is global: one run of K and one of V from the slot's first page (the identity table) + try testing.expect(c.global[4]); + const g = runs.items[4 * 4 ..][0..2]; + try testing.expectEqual([3]usize{ caches[4].kc + 2 * fwd.pagesOf(8192) * fwd.page_tokens * rb, g[0][1], at * rb }, g[0]); + try testing.expectEqual(caches[4].vc + 2 * fwd.pagesOf(8192) * fwd.page_tokens * rb, g[1][0]); + var total: usize = 0; + for (runs.items, 0..) |r, i| { + if (i > 0) try testing.expectEqual(runs.items[i - 1][1] + runs.items[i - 1][2], r[1]); // packed in order + total += r[2]; + } + try testing.expectEqual(bytes(c, at), total); +} + +test "ricursive cuda state: before the window fills, a ring keeps every position from 0 in one run" { + const c = try release(); + var caches: [cfg.max_layers]fwd.Cache = undefined; + const a = fakeArena(c, caches[0..c.layers], 1, 4096); + const at = 510; // a page edge two rows on + var runs: std.ArrayList([3]usize) = .empty; + defer runs.deinit(testing.allocator); + try each(&a, c.window, 0, at, Count{ .runs = &runs }, Count.add); + try testing.expectEqual(@as(usize, 2 * c.layers), runs.items.len); + for (runs.items) |r| try testing.expectEqual(@as(usize, at * 2048), r[2]); + try testing.expectEqual(@as(u64, 2 * c.layers * at * 2048), bytes(c, at)); +} + +test "ricursive cuda state: the key names the shape; another shape's state is refused" { + const c = try release(); + var other = c; + other.global[0] = true; + try testing.expect(sameKey(keyOf(c), keyOf(c))); + try testing.expect(!sameKey(keyOf(c), keyOf(other))); + var m: fwd.Model = undefined; + m.c = c; + m.context = 8192; + var buf: cuda.DeviceBuffer = undefined; + buf.ptr = 0; + const k: Saved = .{ .at = 10, .key = keyOf(other), .buf = buf }; + try testing.expectError(error.StateOfAnotherShape, restore(&m, 0, &k)); +} diff --git a/zig/src/families/ricursive/cuda_weights.zig b/zig/src/families/ricursive/cuda_weights.zig new file mode 100644 index 00000000000..1b755ddec52 --- /dev/null +++ b/zig/src/families/ricursive/cuda_weights.zig @@ -0,0 +1,431 @@ +//! Ripple's weights on CUDA: NVFP4 MLPs for the lane matmul, bf16 attention (q, k, g as one) and head; gate refusals. +const std = @import("std"); +const core = @import("core"); +const cuda = @import("cuda"); +const cfg = @import("config.zig"); +const glue = @import("cuda_kernels.zig"); +const attn = @import("cuda_attn.zig"); + +const Config = cfg.Config; +const Checkpoint = core.checkpoint.Checkpoint; +const Tensor = core.checkpoint.Tensor; +const Weight = cuda.qmmf.Weight; +const DeviceBuffer = cuda.DeviceBuffer; + +/// Bytes a small tensor's device copy starts on: tf_rc_add_norm reads 16-byte chunks. +const small_align = 256; + +/// What CUDA serves: the NVFP4 release's MLPs, and shapes the kernels and packers take. +pub fn gate(c: *const Config) !void { + if (!c.fp4_mlp) return error.RicursiveCudaNeedsNvfp4; + const g = c.group(); + // tf_window_decode_tc holds a key head's queries in one tile (at most 16); the prompt kernel pairs them + if (g % attn.heads_a_block != 0 or g > 16) return error.UnsupportedRicursiveCudaShape; + if (c.hidden % 8 != 0 or c.hidden > glue.most_width) return error.UnsupportedRicursiveCudaShape; + // packBf16 and packWords take k in whole 64s; every output a whole number of 128-row blocks (no padding) + for ([_]usize{ c.hidden, c.queryWidth(), c.intermediate }) |k| if (k % cuda.qmmf.group != 0) return error.UnsupportedRicursiveCudaShape; + for ([_]usize{ c.queryWidth(), c.kvWidth(), c.hidden, c.intermediate, c.vocab }) |n| if (n % 128 != 0) return error.UnsupportedRicursiveCudaShape; +} + +/// The fused projection's rows: q, then k, then g; v stays apart (its input is the value-residual blend). +pub fn qkgWidth(c: Config) usize { + return 2 * c.queryWidth() + c.kvWidth(); +} + +/// An NVFP4 projection as ModelOpt stores it: nibbles [n, k / 2], E4M3 scales [n, k / 16], the fp32 global. +pub const Fp4 = struct { w: Tensor, scales: Tensor, global: f32, n: usize, k: usize }; + +pub const LayerMap = struct { + q: Tensor, + k: Tensor, + v: Tensor, + g: Tensor, + o: Tensor, + q_norm: Tensor, + k_norm: Tensor, + lambda: u16, // value_res_lambda's bf16 bits + input_norm: Tensor, + post_attn: Tensor, + pre_ffn: Tensor, + post_ffn: Tensor, + gate: Fp4, + up: Fp4, + down: Fp4, +}; + +/// Every tensor the CUDA engine reads, checked by dtype and shape; input_scale is taken and unread, as on Metal. +pub const Map = struct { + gpa: std.mem.Allocator, + embed: Tensor, + head: Tensor, + norm: Tensor, + layers: []LayerMap, + + pub fn deinit(m: *Map) void { + m.gpa.free(m.layers); + m.* = undefined; + } +}; + +const Names = struct { + ck: *Checkpoint, + buf: [160]u8 = undefined, + + fn bf16(n: *Names, shape: []const usize, comptime fmt: []const u8, args: anytype) !Tensor { + return n.ck.expect(try std.fmt.bufPrint(&n.buf, fmt, args), .bf16, shape); + } + + fn fp4(n: *Names, rows: usize, k: usize, comptime fmt: []const u8, args: anytype) !Fp4 { + const w = try n.ck.expect(try std.fmt.bufPrint(&n.buf, fmt ++ ".weight", args), .u8, &.{ rows, k / 2 }); + const s = try n.ck.expect(try std.fmt.bufPrint(&n.buf, fmt ++ ".weight_scale", args), .f8_e4m3, &.{ rows, k / 16 }); + const t = try n.ck.expect(try std.fmt.bufPrint(&n.buf, fmt ++ ".weight_scale_2", args), .f32, &.{}); + const v: f32 = @bitCast(std.mem.readInt(u32, t.bytes[0..4], .little)); + if (!(v > 0) or !std.math.isFinite(v)) { + std.log.err("ricursive: " ++ fmt ++ ".weight_scale_2 {e} is not a positive finite scale", args ++ .{v}); + return error.UnexpectedTensor; + } + const input = try std.fmt.bufPrint(&n.buf, fmt ++ ".input_scale", args); + if (n.ck.has(input)) _ = try n.ck.get(input); // the activations stay bf16 (W4A16): taken, never read + return .{ .w = w, .scales = s, .global = v, .n = rows, .k = k }; + } +}; + +/// The release's names (PR 2231's weights.zig); a missing, mistyped or leftover tensor refuses the checkpoint. +pub fn map(gpa: std.mem.Allocator, ck: *Checkpoint, c: Config) !Map { + var nm: Names = .{ .ck = ck }; + const h = c.hidden; + const q = c.queryWidth(); + const kv = c.kvWidth(); + const f = c.intermediate; + var m: Map = .{ .gpa = gpa, .embed = undefined, .head = undefined, .norm = undefined, .layers = try gpa.alloc(LayerMap, c.layers) }; + errdefer gpa.free(m.layers); + m.embed = try nm.bf16(&.{ c.vocab, h }, "model.embed_tokens.weight", .{}); + m.head = try nm.bf16(&.{ c.vocab, h }, "lm_head.weight", .{}); + m.norm = try nm.bf16(&.{h}, "model.norm.weight", .{}); + for (m.layers, 0..) |*l, i| { + const p = "model.layers.{d}."; + const a = p ++ "self_attn."; + const lambda = try nm.bf16(&.{1}, a ++ "value_res_lambda", .{i}); + l.* = .{ + .q = try nm.bf16(&.{ q, h }, a ++ "q_proj.weight", .{i}), + .k = try nm.bf16(&.{ kv, h }, a ++ "k_proj.weight", .{i}), + .v = try nm.bf16(&.{ kv, h }, a ++ "v_proj.weight", .{i}), + .g = try nm.bf16(&.{ q, h }, a ++ "g_proj.weight", .{i}), + .o = try nm.bf16(&.{ h, q }, a ++ "o_proj.weight", .{i}), + .q_norm = try nm.bf16(&.{cfg.head_dim}, a ++ "q_norm.weight", .{i}), + .k_norm = try nm.bf16(&.{cfg.head_dim}, a ++ "k_norm.weight", .{i}), + .lambda = std.mem.readInt(u16, lambda.bytes[0..2], .little), + .input_norm = try nm.bf16(&.{h}, p ++ "input_layernorm.weight", .{i}), + .post_attn = try nm.bf16(&.{h}, p ++ "post_attention_layernorm.weight", .{i}), + .pre_ffn = try nm.bf16(&.{h}, p ++ "pre_feedforward_layernorm.weight", .{i}), + .post_ffn = try nm.bf16(&.{h}, p ++ "post_feedforward_layernorm.weight", .{i}), + .gate = try nm.fp4(f, h, p ++ "mlp.gate_proj", .{i}), + .up = try nm.fp4(f, h, p ++ "mlp.up_proj", .{i}), + .down = try nm.fp4(h, f, p ++ "mlp.down_proj", .{i}), + }; + } + if (ck.unused() != 0) return error.UnusedTensors; + return m; +} + +/// torch's bf16 sigmoid of a bf16 scalar: fp32 1 / (1 + exp(-x)) to bf16, nearest even (Metal's weights.zig's copy). +pub fn blendOf(lambda: u16) f32 { + const x: f32 = @bitCast(@as(u32, lambda) << 16); + const s: f32 = 1.0 / (1.0 + @exp(-x)); + const bits: u32 = @bitCast(s); + const rounded = (bits + 0x7fff + ((bits >> 16) & 1)) & 0xffff0000; + return @bitCast(rounded); +} + +pub const Layer = struct { + qkg: Weight, // bf16 [q + kv + q, H]: q rows, k rows, g rows + v: Weight, // bf16 [kv, H] + o: Weight, // bf16 [H, q] + gate: Weight, // NVFP4 [I, H] + up: Weight, + down: Weight, // NVFP4 [H, I] + input_norm: u64, // bf16 [H] + post_attn: u64, + pre_ffn: u64, + post_ffn: u64, + q_norm: u64, // bf16 [128] + k_norm: u64, + blend: f32, // bf16(sigmoid(value_res_lambda)) +}; + +/// Device bytes `deviceBytes` counts beside the small tensors: every projection, the table and the head. +pub fn deviceBytes(c: Config) usize { + const h = c.hidden; + const fp4 = c.intermediate * h / 2 + c.intermediate * h / 16; // words and scale tiles (no padding: gate) + const per_layer = (qkgWidth(c) + c.kvWidth()) * h * 2 + h * c.queryWidth() * 2 + 3 * fp4 + smallLayerBytes(c); + return 2 * c.vocab * h * 2 + c.layers * per_layer + std.mem.alignForward(usize, h * 2, small_align); +} + +/// A layer's norm weights, each at its own 256-byte boundary. +fn smallLayerBytes(c: Config) usize { + return 4 * std.mem.alignForward(usize, c.hidden * 2, small_align) + 2 * std.mem.alignForward(usize, cfg.head_dim * 2, small_align); +} + +pub const Weights = struct { + gpa: std.mem.Allocator, + config: Config, + embed: u64 = 0, // bf16 [V, H] as stored (tf_rc_embed gathers rows) + head: Weight = undefined, // bf16 [V, H] packed + norm: u64 = 0, // bf16 [H] + layers: []Layer = &.{}, + buffers: std.ArrayList(DeviceBuffer) = .empty, + bytes: usize = 0, + + pub fn deinit(w: *Weights) void { + for (w.buffers.items) |*b| b.free(); + w.buffers.deinit(w.gpa); + w.gpa.free(w.layers); + w.* = undefined; + } + + fn upload(w: *Weights, d: *const cuda.Driver, bytes: []const u8) !u64 { + var b = try DeviceBuffer.fromHost(d, bytes); + errdefer b.free(); + try w.buffers.append(w.gpa, b); + w.bytes += bytes.len; + return b.ptr; + } + + /// bf16 matrices one under another ([sum n, k]), packed as one projection for the lane and prompt matmuls. + fn dense(w: *Weights, d: *const cuda.Driver, parts: []const Tensor, k: usize) !Weight { + var n: usize = 0; + for (parts) |p| n += p.bytes.len / 2 / k; + const src = try w.gpa.alloc(u16, n * k); + defer w.gpa.free(src); + var at: usize = 0; + for (parts) |p| { + @memcpy(std.mem.sliceAsBytes(src)[at..][0..p.bytes.len], p.bytes); + at += p.bytes.len; + } + const out = try w.gpa.alloc(u16, cuda.modelopt.padded(n) * k); + defer w.gpa.free(out); + cuda.qmmf.packBf16(out, src, n, k); + return cuda.modelopt.bf16Weight(try w.upload(d, std.mem.sliceAsBytes(out)), n, k); + } + + fn fp4(w: *Weights, d: *const cuda.Driver, p: Fp4) !Weight { + const words = try w.gpa.alloc(u32, cuda.nvfp4.padded(p.n) / 64 * (p.k / 64) * 512); + defer w.gpa.free(words); + const tiles = try w.gpa.alloc(u8, cuda.nvfp4.padded(p.n) * (p.k / 16)); + defer w.gpa.free(tiles); + cuda.nvfp4.packWords(words, p.w.bytes, p.n, p.k); + cuda.nvfp4.packScales(tiles, p.scales.bytes, p.n, p.k); + const wp = try w.upload(d, std.mem.sliceAsBytes(words)); + const tp = try w.upload(d, tiles); + return cuda.nvfp4.weight(wp, tp, p.global, p.n, p.k); + } +}; + +/// The small tensors in one host image, each at a 256-byte boundary; their offsets into it. +const Small = struct { + bytes: std.ArrayList(u8) = .empty, + + fn put(s: *Small, gpa: std.mem.Allocator, t: Tensor) !usize { + const at = std.mem.alignForward(usize, s.bytes.items.len, small_align); + try s.bytes.appendNTimes(gpa, 0, at - s.bytes.items.len); + try s.bytes.appendSlice(gpa, t.bytes); + return at; + } +}; + +/// config.json through the CUDA gate, every tensor mapped and checked, then layer by layer onto the GPU. +pub fn load(gpa: std.mem.Allocator, io: std.Io, d: *const cuda.Driver, dir: []const u8) !Weights { + const c = try Config.read(gpa, io, dir); + try gate(&c); + var ck = try Checkpoint.openModel(gpa, io, dir); + defer core.checkpoint.cache.close(&ck); + var m = try map(gpa, &ck, c); + defer m.deinit(); + var w: Weights = .{ .gpa = gpa, .config = c }; + errdefer w.deinit(); + const h = c.hidden; + w.layers = try gpa.alloc(Layer, c.layers); + w.embed = try w.upload(d, m.embed.bytes); + w.head = try w.dense(d, &.{m.head}, h); + var small: Small = .{}; + defer small.bytes.deinit(gpa); + const at_norm = try small.put(gpa, m.norm); + const offsets = try gpa.alloc([6]usize, c.layers); + defer gpa.free(offsets); + for (w.layers, m.layers, offsets) |*l, t, *o| { + l.* = .{ + .qkg = try w.dense(d, &.{ t.q, t.k, t.g }, h), + .v = try w.dense(d, &.{t.v}, h), + .o = try w.dense(d, &.{t.o}, c.queryWidth()), + .gate = try w.fp4(d, t.gate), + .up = try w.fp4(d, t.up), + .down = try w.fp4(d, t.down), + .input_norm = 0, + .post_attn = 0, + .pre_ffn = 0, + .post_ffn = 0, + .q_norm = 0, + .k_norm = 0, + .blend = blendOf(t.lambda), + }; + for ([_]Tensor{ t.input_norm, t.post_attn, t.pre_ffn, t.post_ffn, t.q_norm, t.k_norm }, o) |x, *at| at.* = try small.put(gpa, x); + } + const base = try w.upload(d, small.bytes.items); + w.norm = base + at_norm; + for (w.layers, offsets) |*l, o| { + l.input_norm = base + o[0]; + l.post_attn = base + o[1]; + l.pre_ffn = base + o[2]; + l.post_ffn = base + o[3]; + l.q_norm = base + o[4]; + l.k_norm = base + o[5]; + } + return w; +} + +const testing = std.testing; +const tio = testing.io; + +/// The release's config (the fixture), as its NVFP4 quantization_config sets it. +fn release() !Config { + var c = try cfg.parse(testing.allocator, @embedFile("fixtures/config.json")); + c.fp4_mlp = true; + return c; +} + +test "ricursive cuda gate: the NVFP4 release passes, the BF16 checkpoint and unbuilt shapes are refused" { + var c = try release(); + try gate(&c); + try testing.expectEqual(@as(usize, 21504), qkgWidth(c)); + c.fp4_mlp = false; + try testing.expectError(error.RicursiveCudaNeedsNvfp4, gate(&c)); + c = try release(); + c.kv_heads = 16; // group 5: the prompt kernel pairs query heads + try testing.expectError(error.UnsupportedRicursiveCudaShape, gate(&c)); + c = try release(); + c.hidden = 10240; // past tf_rc_add_norm's 8,192 + try testing.expectError(error.UnsupportedRicursiveCudaShape, gate(&c)); +} + +test "ricursive cuda weights: the release's device bytes, about 57 GB, the planned 53.3 GiB" { + const c = try release(); + const b = deviceBytes(c); + try testing.expect(b > 57_000_000_000 and b < 57_400_000_000); +} + +test "ricursive cuda blendOf: torch's bf16 sigmoid" { + try testing.expectEqual(@as(f32, 0.5), blendOf(0x0000)); + try testing.expectEqual(@as(f32, 0.73046875), blendOf(0x3f80)); + try testing.expectEqual(@as(f32, 0.26953125), blendOf(0xbf80)); +} + +test "ricursive cuda fused q, k and g: one packing of the rows equals each part packed in its place" { + const gpa = testing.allocator; + const k = 128; + const ns = [_]usize{ 256, 128, 256 }; + var total: usize = 0; + for (ns) |n| total += n; + const src = try gpa.alloc(u16, total * k); + defer gpa.free(src); + for (src, 0..) |*v, i| v.* = @truncate(i *% 2654435761); + const whole = try gpa.alloc(u16, total * k); + defer gpa.free(whole); + cuda.qmmf.packBf16(whole, src, total, k); + var at: usize = 0; + const part = try gpa.alloc(u16, 256 * k); + defer gpa.free(part); + for (ns) |n| { + cuda.qmmf.packBf16(part[0 .. n * k], src[at..][0 .. n * k], n, k); + try testing.expectEqualSlices(u16, whole[at..][0 .. n * k], part[0 .. n * k]); + at += n * k; + } +} + +/// A tiny Ripple: 5 layers (the fifth global), 4 query heads over 2 key heads. +fn tiny() Config { + var c: Config = .{ .hidden = 128, .intermediate = 256, .layers = 5, .heads = 4, .kv_heads = 2, .vocab = 128, .eps = 1e-6, .theta = 10000, .window = 16, .embed_scale = 1, .clamp = 20, .context = 64, .fp4_mlp = true }; + c.global[4] = true; + return c; +} + +/// A safetensors file of every tensor `c` names (zeros, each global scale 1). +fn writeFixture(a: std.mem.Allocator, dir: std.Io.Dir, c: Config, input_scales: bool) !void { + const E = struct { name: []const u8, dtype: []const u8, shape: []const usize }; + var list: std.ArrayList(E) = .empty; + const h = c.hidden; + const Add = struct { + fn bf(l: *std.ArrayList(E), al: std.mem.Allocator, name: []const u8, shape: []const usize) !void { + try l.append(al, .{ .name = name, .dtype = "BF16", .shape = try al.dupe(usize, shape) }); + } + fn fp4(l: *std.ArrayList(E), al: std.mem.Allocator, pre: []const u8, n: usize, k: usize, input: bool) !void { + try l.append(al, .{ .name = try std.fmt.allocPrint(al, "{s}.weight", .{pre}), .dtype = "U8", .shape = try al.dupe(usize, &.{ n, k / 2 }) }); + try l.append(al, .{ .name = try std.fmt.allocPrint(al, "{s}.weight_scale", .{pre}), .dtype = "F8_E4M3", .shape = try al.dupe(usize, &.{ n, k / 16 }) }); + try l.append(al, .{ .name = try std.fmt.allocPrint(al, "{s}.weight_scale_2", .{pre}), .dtype = "F32", .shape = &.{} }); + if (input) try l.append(al, .{ .name = try std.fmt.allocPrint(al, "{s}.input_scale", .{pre}), .dtype = "F32", .shape = &.{} }); + } + }; + try Add.bf(&list, a, "model.embed_tokens.weight", &.{ c.vocab, h }); + try Add.bf(&list, a, "lm_head.weight", &.{ c.vocab, h }); + try Add.bf(&list, a, "model.norm.weight", &.{h}); + for (0..c.layers) |i| { + const p = try std.fmt.allocPrint(a, "model.layers.{d}.", .{i}); + for ([_][]const u8{ "input_layernorm", "post_attention_layernorm", "pre_feedforward_layernorm", "post_feedforward_layernorm" }) |n| try Add.bf(&list, a, try std.fmt.allocPrint(a, "{s}{s}.weight", .{ p, n }), &.{h}); + for ([_][]const u8{ "q_proj", "g_proj" }) |n| try Add.bf(&list, a, try std.fmt.allocPrint(a, "{s}self_attn.{s}.weight", .{ p, n }), &.{ c.queryWidth(), h }); + for ([_][]const u8{ "k_proj", "v_proj" }) |n| try Add.bf(&list, a, try std.fmt.allocPrint(a, "{s}self_attn.{s}.weight", .{ p, n }), &.{ c.kvWidth(), h }); + try Add.bf(&list, a, try std.fmt.allocPrint(a, "{s}self_attn.o_proj.weight", .{p}), &.{ h, c.queryWidth() }); + for ([_][]const u8{ "q_norm", "k_norm" }) |n| try Add.bf(&list, a, try std.fmt.allocPrint(a, "{s}self_attn.{s}.weight", .{ p, n }), &.{cfg.head_dim}); + try Add.bf(&list, a, try std.fmt.allocPrint(a, "{s}self_attn.value_res_lambda", .{p}), &.{1}); + for ([_][]const u8{ "gate_proj", "up_proj" }) |n| try Add.fp4(&list, a, try std.fmt.allocPrint(a, "{s}mlp.{s}", .{ p, n }), c.intermediate, h, input_scales); + try Add.fp4(&list, a, try std.fmt.allocPrint(a, "{s}mlp.down_proj", .{p}), h, c.intermediate, input_scales); + } + var header: std.Io.Writer.Allocating = .init(a); + try header.writer.writeAll("{"); + var at: usize = 0; + const sizes = try a.alloc(usize, list.items.len); + for (list.items, sizes, 0..) |e, *size, j| { + var n: usize = if (e.dtype[0] == 'B') 2 else if (e.dtype[0] == 'F' and e.dtype[1] == '3') 4 else 1; + for (e.shape) |x| n *= x; + size.* = n; + try header.writer.print("{s}\"{s}\":{{\"dtype\":\"{s}\",\"shape\":[", .{ if (j == 0) "" else ",", e.name, e.dtype }); + for (e.shape, 0..) |x, i| try header.writer.print("{s}{d}", .{ if (i == 0) "" else ",", x }); + try header.writer.print("],\"data_offsets\":[{d},{d}]}}", .{ at, at + n }); + at += n; + } + try header.writer.writeAll("}"); + const hd = header.written(); + const file = try a.alloc(u8, 8 + hd.len + at); + @memset(file, 0); + std.mem.writeInt(u64, file[0..8], hd.len, .little); + @memcpy(file[8..][0..hd.len], hd); + var off: usize = 0; + for (list.items, sizes) |e, n| { + if (std.mem.endsWith(u8, e.name, "weight_scale_2")) std.mem.writeInt(u32, file[8 + hd.len + off ..][0..4], @bitCast(@as(f32, 1)), .little); + off += n; + } + try dir.writeFile(tio, .{ .sub_path = "model.safetensors", .data = file }); +} + +fn tmpPath(a: std.mem.Allocator, tmp: testing.TmpDir) ![]u8 { + const cwd = try std.process.currentPathAlloc(tio, a); + return std.fmt.allocPrint(a, "{s}/.zig-cache/tmp/{s}", .{ cwd, tmp.sub_path }); +} + +test "ricursive cuda names: every tensor of a tiny NVFP4 release maps, input_scale taken and unread" { + var arena: std.heap.ArenaAllocator = .init(testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const c = tiny(); + for ([_]bool{ true, false }) |input| { + var tmp = testing.tmpDir(.{}); + defer tmp.cleanup(); + try writeFixture(a, tmp.dir, c, input); + var ck = try Checkpoint.openModel(testing.allocator, tio, try tmpPath(a, tmp)); + defer ck.close(); + var m = try map(testing.allocator, &ck, c); + defer m.deinit(); + try testing.expectEqual(@as(usize, 5), m.layers.len); + try testing.expectEqual(@as(f32, 1), m.layers[3].down.global); + try testing.expectEqual(@as(usize, 128), m.layers[0].gate.k); + try testing.expectEqual(@as(f32, 0.5), blendOf(m.layers[4].lambda)); + } +} diff --git a/zig/src/families/uocr/decoder.zig b/zig/src/families/uocr/decoder.zig index cdd222c3cb6..6902ec24eff 100644 --- a/zig/src/families/uocr/decoder.zig +++ b/zig/src/families/uocr/decoder.zig @@ -1,6 +1,7 @@ //! Unlimited-OCR-2's decoder on Metal: the prompt in chunks of rows, then a token a step, over exact bf16 caches. const std = @import("std"); const mtl = @import("metal"); +const lanes = @import("lanes"); const cfg = @import("config.zig"); const ks = @import("kernels.zig"); const wts = @import("weights.zig"); @@ -158,12 +159,13 @@ pub const Decoder = struct { } /// Prefill a prompt: `image_rows` (bf16 [image tokens, 1280]) at its image tokens, the token embeddings elsewhere. - pub fn prefill(d: *Decoder, p: prompt_mod.Prompt, image_rows: []const u16) !void { + pub fn prefill(d: *Decoder, p: prompt_mod.Prompt, image_rows: []const u16, stream: ?*const lanes.Stream) !void { const n = p.len(); if (n == 0 or n > d.cap) return error.UocrPromptTooLong; var images: usize = 0; for (p.ids) |id| images += @intFromBool(id == cfg.image_token); if (image_rows.len != images * H) return error.UocrImageRows; + if (stream) |st| if (st.isCancelled()) return error.Cancelled; try d.upload(p); var tr: ?pass_mod.Trace = null; if (d.trace != null or d.trace_parts != null) tr = try pass_mod.Trace.init(d.device, n); @@ -173,6 +175,7 @@ pub const Decoder = struct { var s0: usize = 0; const embed: [*]const u16 = @ptrCast(@alignCast(d.w.embed.addr())); while (s0 < n) { + if (stream) |st| if (st.isCancelled()) return error.Cancelled; const r = @min(d.rows, n - s0); const x = d.scratch.host(u16, .x, r * H); for (0..r) |i| { diff --git a/zig/src/families/uocr/serve.zig b/zig/src/families/uocr/serve.zig index a8e25ca1674..c50dbaeb515 100644 --- a/zig/src/families/uocr/serve.zig +++ b/zig/src/families/uocr/serve.zig @@ -101,7 +101,7 @@ pub const Model = struct { pub const Prepared = struct { pixels: []f32, gh: u32, gw: u32, tokens: u32, hash: u64 }; /// Every image of the stream through the tower, laid out as its image tokens in prompt order. - fn encodeImages(m: *Model, a: std.mem.Allocator, images: []const lanes.stream.Image) ![]u16 { + fn encodeImages(m: *Model, a: std.mem.Allocator, images: []const lanes.stream.Image, stream: ?*const lanes.Stream) ![]u16 { var total: usize = 0; for (images) |img| total += img.tokens; const rows = try a.alloc(u16, total * H); @@ -111,6 +111,7 @@ pub const Model = struct { const tile_px = 3 * cfg.tile_size * cfg.tile_size; var at: usize = 0; for (images) |img| { + if (stream) |st| if (st.isCancelled()) return error.Cancelled; const across: usize = img.gw; const down: usize = img.gh; const tiles: usize = if (across * down > 1) across * down else 0; @@ -152,10 +153,12 @@ pub const Model = struct { if (ids.len == 0 or ids.len + @max(stream.max_new, 1) - 1 > m.decoder.cap) return error.UocrPromptTooLong; var arena: std.heap.ArenaAllocator = .init(m.gpa); defer arena.deinit(); - const rows = try m.encodeImages(arena.allocator(), stream.images); + if (stream.isCancelled()) return error.Cancelled; + const rows = try m.encodeImages(arena.allocator(), stream.images, stream); + if (stream.isCancelled()) return error.Cancelled; var p = try prompt_mod.positions(m.gpa, try m.gpa.dupe(u32, ids)); errdefer p.deinit(m.gpa); - try m.decoder.prefill(p, rows); + try m.decoder.prefill(p, rows, stream); m.guard = generate.Guard.init(p); m.step = prompt_mod.Step.init(p); m.prompt = p; @@ -223,3 +226,78 @@ test "uocr: a page's token bounds" { try std.testing.expectEqual(@as(u32, 273), basePageTokens()); try std.testing.expect(maxPageTokens() > basePageTokens()); } + +/// Whether a stream's request is cancelled; the tests count the checks a pass makes. +const Probe = struct { + at: usize = 0, + cancel_after: usize = 0, + fn cancelled(ptr: *anyopaque) bool { + const p: *Probe = @ptrCast(@alignCast(ptr)); + p.at += 1; + return p.at > p.cancel_after; + } +}; + +fn fakeStream(a: std.mem.Allocator, probe: *Probe, ids: []const u32) !lanes.Stream { + return lanes.Stream.init(a, .{ .id = "cancel-test", .prompt = ids, .max_new = 4, .cancel_check = .{ .ptr = probe, .check = Probe.cancelled } }); +} + +fn fakeDecoder(a: std.mem.Allocator, cap: usize, rows: usize) decoder_mod.Decoder { + return .{ .gpa = a, .device = undefined, .queue = undefined, .k = undefined, .w = undefined, .cap = cap, .rows = rows }; +} + +fn fakeModel(a: std.mem.Allocator) Model { + return .{ .gpa = a, .io = undefined, .device = undefined, .queue = undefined, .weights = undefined, .kernels = undefined, .encoder = undefined, .decoder = fakeDecoder(a, cfg.max_context, 0) }; +} + +test "uocr: a request cancelled before image encoding stops before the tower" { + const a = std.testing.allocator; + var probe: Probe = .{ .cancel_after = 0 }; + var ids = [_]u32{ cfg.image_token, 10, 11 }; + var s = try fakeStream(a, &probe, &ids); + defer s.deinit(a); + var m = fakeModel(a); + var pixels: [4]f32 = .{ 0, 0, 0, 0 }; + const img: lanes.stream.Image = .{ .pixels = &pixels, .gh = 1, .gw = 1, .at = 0, .tokens = 2 }; + s.images = &.{img}; + try std.testing.expectError(error.Cancelled, Model.prefillFn(&m, &s)); + try std.testing.expectEqual(@as(usize, 1), probe.at); // the first check alone: no encode ran + try std.testing.expect(m.stream == null and m.prompt == null); +} + +test "uocr: a request cancelled between encoding and the prefill keeps the model unclaimed" { + const a = std.testing.allocator; + var probe: Probe = .{ .cancel_after = 1 }; + var ids = [_]u32{ cfg.image_token, 10, 11 }; + var s = try fakeStream(a, &probe, &ids); + defer s.deinit(a); + var m = fakeModel(a); + try std.testing.expectError(error.Cancelled, Model.prefillFn(&m, &s)); + try std.testing.expectEqual(@as(usize, 2), probe.at); // checks before and after the (empty) encode + try std.testing.expect(m.stream == null and m.prompt == null); +} + +test "uocr: a request cancelled before the first prefill chunk writes no cache" { + const a = std.testing.allocator; + var probe: Probe = .{ .cancel_after = 0 }; + var ids = [_]u32{ cfg.image_token, 10, 11 }; + var s = try fakeStream(a, &probe, &ids); + defer s.deinit(a); + var p = try prompt_mod.positions(a, try a.dupe(u32, &ids)); + defer p.deinit(a); + var rows: [H]u16 = undefined; + var d = fakeDecoder(a, 8, 2); + try std.testing.expectError(error.Cancelled, d.prefill(p, &rows, &s)); + try std.testing.expectEqual(@as(usize, 0), d.len); // nothing committed +} + +test "uocr: a request that is never cancelled reaches the decoder's shape gate" { + const a = std.testing.allocator; + var probe: Probe = .{ .cancel_after = 100 }; + var ids = [_]u32{ cfg.image_token, 10, 11 }; + var s = try fakeStream(a, &probe, &ids); + defer s.deinit(a); + var m = fakeModel(a); + try std.testing.expectError(error.UocrImageRows, Model.prefillFn(&m, &s)); // past both checks, into prefill unchanged + try std.testing.expect(m.stream == null and m.prompt == null); +} diff --git a/zig/src/hip/kernel_tests/attention.zig b/zig/src/hip/kernel_tests/attention.zig index f767f03e300..393673b5192 100644 --- a/zig/src/hip/kernel_tests/attention.zig +++ b/zig/src/hip/kernel_tests/attention.zig @@ -226,6 +226,114 @@ test "the planned decode walk over pages writes the flat walk's bits for grouped try decode(t, &rng, 16, 4, 128, 16384, &.{16381}); } +/// A round's slots in one planned walk against each row walked alone: the scores' and rows' bits, on poisoned caches. +fn slots(t: *Rig, rng: *rig.Rng, heads: usize, kv_heads: usize, span: usize, counts: []const usize, ends: []const usize) !void { + const d = 256; + const scale: f32 = 1 / @sqrt(@as(f32, d)); + var rows: usize = 0; + for (counts) |n| rows += n; + const pos = try gpa.alloc(i32, rows); + defer gpa.free(pos); + const slot = try gpa.alloc(i32, rows); + defer gpa.free(slot); + const first = try gpa.alloc(i32, counts.len); + defer gpa.free(first); + const count = try gpa.alloc(i32, counts.len); + defer gpa.free(count); + const descs = try gpa.alloc(u64, counts.len); + defer gpa.free(descs); + var bufs: std.ArrayList(DeviceBuffer) = .empty; + defer { + for (bufs.items) |*b| b.free(); + bufs.deinit(gpa); + } + const words = 4; + const nan: u16 = if (t.bf16) 0x7fc5 else 0x7e05; + const inf: u16 = if (t.bf16) 0x7f80 else 0x7c00; + var row: usize = 0; + for (counts, ends, 0..) |n, end, s| { + first[s] = @intCast(row); + count[s] = @intCast(n); + for (0..n) |i| { + pos[row + i] = @intCast(end - n + i); + slot[row + i] = @intCast(s); + } + row += n; + // its own cache: a NaN key and value only its last row sees, infinite ones past its rows, an infinite value + const c = try Cache.make(t, rng, kv_heads, span, d); + defer c.free(); + for (0..kv_heads) |h| { + c.k[(h * span + end - 1) * d + 3 + h] = nan; + if (end < span) c.k[(h * span + end) * d + 7] = inf; + c.v[(h * span + end - n) * d + 11] = inf; + c.v[(h * span + end - 1) * d + 13 + h] = nan; + if (end < span) c.v[(h * span + end) * d + 17] = inf; + } + for ([_][]const u16{ c.k, c.v }) |src| { + const pooled = try c.pool(src, kv_heads, span, d); + defer gpa.free(pooled); + try bufs.append(gpa, try t.upload(pooled)); + } + const desc = try gpa.alloc(u64, words + (c.table.len + 1) / 2); + defer gpa.free(desc); + @memset(desc, 0); + desc[2] = at(bufs.items[bufs.items.len - 2]); + desc[3] = at(bufs.items[bufs.items.len - 1]); + @memcpy(std.mem.sliceAsBytes(desc[words..])[0 .. c.table.len * 4], std.mem.sliceAsBytes(c.table)); + try bufs.append(gpa, try t.upload(desc)); + descs[s] = at(bufs.items[bufs.items.len - 1]); + } + const hq = try gpa.alloc(f32, rows * heads * d); + defer gpa.free(hq); + for (hq) |*x| x.* = rng.unit(); + const zero = [_]i32{0}; + const lone = [_]i32{1}; + var ins: [8]DeviceBuffer = undefined; // q, the plan's pos, slot, first, count and descriptors, a one-row plan's + for (&ins, [_][]const u8{ std.mem.sliceAsBytes(hq), std.mem.sliceAsBytes(pos), std.mem.sliceAsBytes(slot), std.mem.sliceAsBytes(first), std.mem.sliceAsBytes(count), std.mem.sliceAsBytes(descs), std.mem.asBytes(&zero), std.mem.asBytes(&lone) }) |*b, host| { + b.* = try t.upload(host); + try bufs.append(gpa, b.*); + } + const tiles = span / 128; + const scratch = [_]usize{ rows * heads * span * 4, rows * heads * d * 4, rows * heads * 2 * 4, rows * heads * tiles * d * 4 }; + var outs: [2][4]DeviceBuffer = undefined; // the shared walk's scores and rows, then each row's alone; stats, partials + for (&outs) |*o| for (o, scratch) |*b, len| { + b.* = try t.alloc(len); + try bufs.append(gpa, b.*); + try b.fill8(0xff); + }; + const p: plan.PlanRef = .{ .rows = rows, .slots = counts.len, .args = .{ .pos = at(ins[1]), .slot = at(ins[2]), .first = at(ins[3]), .count = at(ins[4]), .desc = at(ins[5]), .pages = words, .pool = @intCast(span / page) } }; + const s = t.stream.handle; + try t.on.planCausal(at(ins[0]), at(outs[0][1]), at(outs[0][0]), at(outs[0][2]), at(outs[0][3]), p, 0, heads, kv_heads, d, span, scale, t.kind(), s); + // row r alone: a one-row plan over its slot, its q, scores and output at row r's place + for (0..rows) |r| { + const desc = at(ins[5]) + 8 * @as(usize, @intCast(slot[r])); + const one: plan.PlanRef = .{ .rows = 1, .slots = 1, .args = .{ .pos = at(ins[1]) + 4 * r, .slot = at(ins[6]), .first = at(ins[6]), .count = at(ins[7]), .desc = desc, .pages = words, .pool = @intCast(span / page) } }; + try t.on.planCausal(at(ins[0]) + r * heads * d * 4, at(outs[1][1]) + r * heads * d * 4, at(outs[1][0]) + r * heads * span * 4, at(outs[1][2]), at(outs[1][3]), one, 0, heads, kv_heads, d, span, scale, t.kind(), s); + } + try t.stream.synchronize(); + for (0..2) |i| { + const shared = try rig.download(u32, outs[0][i]); + defer gpa.free(shared); + const alone = try rig.download(u32, outs[1][i]); + defer gpa.free(alone); + try std.testing.expectEqualSlices(u32, alone, shared); + } +} + +test "a round's slots in one planned walk write each row's bits walked alone, a slot's rows sharing its key and value reads" { + const t = try Rig.open(1 << 20); + defer t.close(); + var rng: rig.Rng = .{ .state = 0x5107 }; + // slots of 3, 1, 2 and 4 rows: at the span's end, mid-span, across a block's edge, at the span's start + try slots(t, &rng, 16, 2, 32768, &.{ 3, 1, 2, 4 }, &.{ 32768, 9001, 16385, 4 }); + try slots(t, &rng, 24, 4, 16384, &.{ 1, 4, 3 }, &.{ 16384, 130, 8195 }); + // every slot one row (streams with no drafts), and slots of 1, 2, 3 and 4 rows together + try slots(t, &rng, 16, 2, 32768, &.{ 1, 1, 1, 1 }, &.{ 32768, 9001, 16385, 1 }); + try slots(t, &rng, 24, 4, 32768, &.{ 2, 1, 1, 3, 1, 4 }, &.{ 32768, 20000, 16385, 9001, 128, 4 }); + // slots of more than four rows: the values' chunks of four, then the rest of the slot + try slots(t, &rng, 16, 2, 32768, &.{ 6, 1, 5 }, &.{ 32768, 9001, 16385 }); +} + /// A prompt of `qlen` queries from `q_pos0` over `span` positions: the paged 64-row tile writes the flat tile's bits. fn prompt(t: *Rig, rng: *rig.Rng, heads: usize, kv_heads: usize, d: usize, qlen: usize, q_pos0: usize) !void { const span = q_pos0 + qlen; diff --git a/zig/src/hip/kernels.zig b/zig/src/hip/kernels.zig index 69ce080ebb0..64f13ec1993 100644 --- a/zig/src/hip/kernels.zig +++ b/zig/src/hip/kernels.zig @@ -20,6 +20,8 @@ pub const Group = enum { qwen_vision, draft, exl3, + plan_rows, + inkling2, }; pub const group_count = @typeInfo(Group).@"enum".field_names.len; diff --git a/zig/src/hip/launches.zig b/zig/src/hip/launches.zig index 2bdad452847..09b355f6b8f 100644 --- a/zig/src/hip/launches.zig +++ b/zig/src/hip/launches.zig @@ -52,6 +52,10 @@ pub const exl3 = @import("launches/exl3.zig"); pub const ConvArgs = conv.ConvArgs; pub const PlanArgs = plan.PlanArgs; pub const PlanRef = plan.PlanRef; +/// Rows of one slot a block of the shared-row score kernels takes. +pub const score_rows = plan.score_rows; +/// Rows of one slot a block of the shared-row values kernels takes. +pub const apply_rows = plan.apply_rows; pub const PlanKeep = plan.Keep; /// The stream tile's columns a lane, for launches that copy its geometry. pub const stream_pick = @import("launches/stream_pick.zig"); @@ -126,9 +130,15 @@ pub const Launcher = struct { score2_act: [2]Function, score256: [2]Function, // d 256 on long spans, kScoreSteps steps a block score256_act: [2]Function, + /// score256, q fp32, in a multi-row launch (plan_rows.hip): one-row slots' rows, then the others' chunks + score256_lone: [2]Function, + score256_rows: [2]Function, sum_act: Function, attend: [2]Function, apply: [2]Function, + /// apply at d 256 on long spans, q fp32, in a multi-row launch (plan_rows.hip): as score256_lone and _rows + apply_lone: [2]Function, + apply_rows: [2]Function, keep: Function, gather: Function, gdn: [2]Function, // dk 128, 16 @@ -205,6 +215,7 @@ pub const Launcher = struct { const pre = l.mods[@backingInt(kernels.Group.prefill)]; const dec = l.mods[@backingInt(kernels.Group.decode)]; const pl = l.mods[@backingInt(kernels.Group.plan)]; + const plr = l.mods[@backingInt(kernels.Group.plan_rows)]; l.fuse = choices.fuse; l.wide = choices.wide; l.edge = edge_pass; @@ -220,9 +231,13 @@ pub const Launcher = struct { .score2_act = .{ try pl.function("tf_plan_score2_act_f16"), try pl.function("tf_plan_score2_act_bf16") }, .score256 = .{ try pl.function("tf_plan_score256_f16"), try pl.function("tf_plan_score256_bf16") }, .score256_act = .{ try pl.function("tf_plan_score256_act_f16"), try pl.function("tf_plan_score256_act_bf16") }, + .score256_lone = .{ try plr.function("tf_plan_lone_score256_f16"), try plr.function("tf_plan_lone_score256_bf16") }, + .score256_rows = .{ try plr.function("tf_plan_rows_score256_f16"), try plr.function("tf_plan_rows_score256_bf16") }, .sum_act = try pl.function("tf_sum_partials_act"), .attend = .{ try pl.function("tf_plan_attend_f16"), try pl.function("tf_plan_attend_bf16") }, .apply = .{ try pl.function("tf_plan_apply_f16"), try pl.function("tf_plan_apply_bf16") }, + .apply_lone = .{ try plr.function("tf_plan_lone_apply_f16"), try plr.function("tf_plan_lone_apply_bf16") }, + .apply_rows = .{ try plr.function("tf_plan_rows_apply_f16"), try plr.function("tf_plan_rows_apply_bf16") }, .keep = try pl.function("tf_plan_keep"), .gather = try pl.function("tf_plan_gather"), .gdn = .{ try gd.function("tf_gdn_plan_128"), try gd.function("tf_gdn_plan_16") }, @@ -391,6 +406,8 @@ pub const Launcher = struct { pub const planKvWrite = plan.planKvWrite; pub const planCausal = plan.planCausal; pub const planCausalAs = plan.planCausalAs; + pub const planScore = plan.planScore; + pub const planApply = plan.planApply; pub const planKvWriteAct = plan.planKvWriteAct; pub const planTap = plan.planTap; pub const tapRows = plan.tapRows; diff --git a/zig/src/hip/launches/plan.zig b/zig/src/hip/launches/plan.zig index f9f86d428b6..f13d72dd334 100644 --- a/zig/src/hip/launches/plan.zig +++ b/zig/src/hip/launches/plan.zig @@ -98,6 +98,11 @@ const score_keys_short = 2; const score_span = 16384; /// Steps of its warps' keys a tf_plan_score256_* block walks (plan.hip's kScoreSteps). const score_steps = 8; +/// Rows of one slot a tf_plan_rows_score256_* block scores from one read of their keys (plan_rows.hip's kRows). +pub const score_rows = 2; + +/// Which blocks score a walk's rows: a block a row, or a slot's rows in chunks of `score_rows` a block. +pub const Rows = enum { one, shared }; /// One query a row (rows, heads, d) fp32 over its slot's caches up to its position; the walk covers `span` keys. pub fn planCausal(l: *const Launcher, q: u64, out: u64, scores: u64, stats: u64, partials: u64, p: PlanRef, layer: usize, heads: usize, kv_heads: usize, d: usize, span: usize, scale: f32, kind: c_int, s: S) Error!void { @@ -123,63 +128,90 @@ pub fn planCausalAs( act: bool, s: S, ) Error!void { - if (d > 256 or heads < 1 or kv_heads < 1 or @rem(heads, kv_heads) != 0 or kind < 1 or kind > 2) return invalid("planned attention"); - const which: usize = @intCast(kind - 1); + const shared = roundRows(p.rows); + try planScore(l, q, scores, p, layer, heads, kv_heads, d, span, scale, kind, act, shared, s); const rows = p.rows; const tiles: c_int = @intCast(cdiv(span, 128)); - const span_c: c_int = @intCast(span); - const heads_c: c_int = @intCast(heads); - const kv_c: c_int = @intCast(kv_heads); - const d_c: c_int = @intCast(d); - const layer_c: c_int = @intCast(layer); - // a block takes `group` query heads of one KV head (at most plan.hip's kMaxGroup): the cache is read once for them + var b: Args = .{}; + try b.add(scores); + try b.add(stats); + try b.add(@as(c_int, @intCast(span))); + try b.add(@as(c_int, 0)); + try b.add(p.args.pos); + try l.go(l.softmax_stats, dim(heads, rows, 1), dim(256, 1, 1), 0, s, &b); + try planApply(l, scores, stats, partials, p, layer, heads, kv_heads, d, span, kind, act, shared, s); + var e: Args = .{}; + try e.add(partials); + try e.add(out); + try e.add(tiles); + try e.add(@as(c_int, @intCast(d))); + if (act) try e.add(kind); + try l.go(if (act) l.plan.sum_act else l.sum_partials, dim(heads, rows, 1), dim(256, 1, 1), 0, s, &e); +} + +/// The score and values blocks of a walk's launch: one-row launches keep a block a row, wider ones share loads. +fn roundRows(rows: usize) Rows { + return if (rows > 1) .shared else .one; +} + +/// Query heads a score block takes, of one KV head (at most plan.hip's kMaxGroup): the cache is read once for them. +fn scoreGroup(heads: usize, kv_heads: usize) usize { var group = @divExact(heads, kv_heads); while (group > 16) group = @divExact(group, smallestFactor(group)); - const blocks = @divExact(heads, group); + return group; +} + +/// Rows a score block works: a chunk of its slot's when `rows` shares them at d = 256 on long spans with q fp32. +fn blockRows(rows: Rows, d: usize, span: usize, act: bool) usize { + return if (rows == .shared and d == 256 and span >= score_span and !act) score_rows else 1; +} + +/// planCausalAs's score step: each row's scores (rows, heads, span) fp32 against its slot's keys, -inf past its own. +pub fn planScore( + l: *const Launcher, + q: u64, + scores: u64, + p: PlanRef, + layer: usize, + heads: usize, + kv_heads: usize, + d: usize, + span: usize, + scale: f32, + kind: c_int, + act: bool, + rows: Rows, + s: S, +) Error!void { + if (d > 256 or heads < 1 or kv_heads < 1 or @rem(heads, kv_heads) != 0 or kind < 1 or kind > 2) return invalid("planned attention"); + const which: usize = @intCast(kind - 1); + const group = scoreGroup(heads, kv_heads); var a: Args = .{}; try a.add(q); try a.add(scores); - try a.add(span_c); - try a.add(heads_c); - try a.add(kv_c); - try a.add(d_c); + try a.add(@as(c_int, @intCast(span))); + try a.add(@as(c_int, @intCast(heads))); + try a.add(@as(c_int, @intCast(kv_heads))); + try a.add(@as(c_int, @intCast(d))); try a.add(scale); try a.add(p.args); - try a.add(layer_c); + try a.add(@as(c_int, @intCast(layer))); // four warps a block score their keys for the block's heads; short spans take fewer keys a warp to fill the card const long = span >= score_span; const keys: usize = if (long) score_keys else score_keys_short; // d = 256 (the Qwen checkpoints) on long spans takes its own kernels, a block walking score_steps steps const wide = long and d == 256; - const fns = if (wide) (if (act) l.plan.score256_act else l.plan.score256) else if (act) (if (long) l.plan.score_act else l.plan.score2_act) else if (long) l.plan.score else l.plan.score2; const steps: usize = if (wide) score_steps else 1; - try l.go(fns[which], dim(cdiv(span, 4 * keys * steps), blocks, rows), dim(128, 1, 1), @intCast(group * d * 4), s, &a); - var b: Args = .{}; - try b.add(scores); - try b.add(stats); - try b.add(span_c); - try b.add(@as(c_int, 0)); - try b.add(p.args.pos); - try l.go(l.softmax_stats, dim(heads, rows, 1), dim(256, 1, 1), 0, s, &b); - var c: Args = .{}; - try c.add(scores); - try c.add(stats); - try c.add(partials); - try c.add(span_c); - try c.add(heads_c); - try c.add(kv_c); - try c.add(d_c); - try c.add(p.args); - try c.add(layer_c); - const apply = @divExact(heads, applyGroup(group, @intCast(tiles), heads, rows)); - try l.go(l.plan.apply[which], dim(tiles, apply, rows), dim(256, 1, 1), 0, s, &c); - var e: Args = .{}; - try e.add(partials); - try e.add(out); - try e.add(tiles); - try e.add(d_c); - if (act) try e.add(kind); - try l.go(if (act) l.plan.sum_act else l.sum_partials, dim(heads, rows, 1), dim(256, 1, 1), 0, s, &e); + const grid = dim(cdiv(span, 4 * keys * steps), @divExact(heads, group), p.rows); + const lds: u32 = @intCast(group * d * 4); + const chunk = blockRows(rows, d, span, act); + if (chunk > 1) { + // the rows of one-row slots at the one-row kernel's occupancy, then the chunks of the others, both on this grid + try l.go(l.plan.score256_lone[which], grid, dim(128, 1, 1), lds, s, &a); + return l.go(l.plan.score256_rows[which], grid, dim(128, 1, 1), @intCast(chunk * lds), s, &a); + } + const fns = if (wide) (if (act) l.plan.score256_act else l.plan.score256) else if (act) (if (long) l.plan.score_act else l.plan.score2_act) else if (long) l.plan.score else l.plan.score2; + try l.go(fns[which], grid, dim(128, 1, 1), lds, s, &a); } /// Keys the one-block walk (`planAttend`) takes at most. @@ -222,6 +254,55 @@ pub fn planAttend( /// Blocks under which the values' walk splits a KV head's query heads over more blocks. const apply_blocks = 128; +/// Rows of one slot a tf_plan_rows_apply_* block weighs from one read of their values (plan_rows.hip's kApplyRows). +pub const apply_rows = 4; +/// Query heads a tf_plan_rows_apply_* block takes at most (plan_rows.hip's kApplyHeads): the weights its LDS holds. +const apply_heads = 8; + +/// planCausalAs's values step: each row's 128-key tiles of its weighted values, (rows, heads, tiles, d) fp32 partials. +pub fn planApply( + l: *const Launcher, + scores: u64, + stats: u64, + partials: u64, + p: PlanRef, + layer: usize, + heads: usize, + kv_heads: usize, + d: usize, + span: usize, + kind: c_int, + act: bool, + rows: Rows, + s: S, +) Error!void { + if (d > 256 or heads < 1 or kv_heads < 1 or @rem(heads, kv_heads) != 0 or kind < 1 or kind > 2) return invalid("planned attention"); + const which: usize = @intCast(kind - 1); + const tiles = cdiv(span, 128); + var a: Args = .{}; + try a.add(scores); + try a.add(stats); + try a.add(partials); + try a.add(@as(c_int, @intCast(span))); + try a.add(@as(c_int, @intCast(heads))); + try a.add(@as(c_int, @intCast(kv_heads))); + try a.add(@as(c_int, @intCast(d))); + try a.add(p.args); + try a.add(@as(c_int, @intCast(layer))); + const group = applyGroup(scoreGroup(heads, kv_heads), tiles, heads, p.rows); + const grid = dim(tiles, @divExact(heads, group), p.rows); + if (applyRows(rows, d, span, act, group) > 1) { + // the rows of one-row slots at the one-row kernel's occupancy, then the chunks of the others, both on this grid + try l.go(l.plan.apply_lone[which], grid, dim(256, 1, 1), 0, s, &a); + return l.go(l.plan.apply_rows[which], grid, dim(256, 1, 1), 0, s, &a); + } + try l.go(l.plan.apply[which], grid, dim(256, 1, 1), 0, s, &a); +} + +/// Rows an apply block weighs: a chunk of its slot's where the score's blocks share theirs and its heads fit the LDS. +fn applyRows(rows: Rows, d: usize, span: usize, act: bool, group: usize) usize { + return if (blockRows(rows, d, span, act) > 1 and group <= apply_heads) apply_rows else 1; +} /// Query heads an apply block takes: fewer while the grid is small (a head's sums do not depend on its block). fn applyGroup(group: usize, tiles: usize, heads: usize, rows: usize) usize { @@ -326,6 +407,32 @@ pub fn planGdnReplay(l: *const Launcher, keep: u64, p: PlanRef, key_heads: usize try l.go(l.plan.gdn_replay[wide], dim(@divExact(dv, 8), value_heads, p.slots * layers), dim(32, 8, 1), 0, s, &a); } +test "a slot's rows share the score's key loads only past one row, at d 256 on long spans with q fp32" { + const std = @import("std"); + try std.testing.expectEqual(Rows.one, roundRows(1)); + try std.testing.expectEqual(Rows.shared, roundRows(2)); + try std.testing.expectEqual(@as(usize, score_rows), blockRows(roundRows(4), 256, score_span, false)); + try std.testing.expectEqual(@as(usize, 1), blockRows(roundRows(1), 256, 1 << 18, false)); + try std.testing.expectEqual(@as(usize, 1), blockRows(.shared, 256, score_span - 1, false)); + try std.testing.expectEqual(@as(usize, 1), blockRows(.shared, 128, 1 << 18, false)); + try std.testing.expectEqual(@as(usize, 1), blockRows(.shared, 256, 1 << 18, true)); + try std.testing.expectEqual(@as(usize, 8), scoreGroup(16, 2)); + try std.testing.expectEqual(@as(usize, 16), scoreGroup(64, 2)); +} + +test "a slot's rows share the values' loads in chunks of four where the score's do, with at most 8 heads a block" { + const std = @import("std"); + try std.testing.expectEqual(@as(usize, apply_rows), applyRows(roundRows(4), 256, score_span, false, apply_heads)); + try std.testing.expectEqual(@as(usize, 1), applyRows(roundRows(1), 256, 1 << 18, false, 8)); + try std.testing.expectEqual(@as(usize, 1), applyRows(.shared, 256, score_span - 1, false, 8)); + try std.testing.expectEqual(@as(usize, 1), applyRows(.shared, 128, 1 << 18, false, 8)); + try std.testing.expectEqual(@as(usize, 1), applyRows(.shared, 256, 1 << 18, true, 8)); + try std.testing.expectEqual(@as(usize, 1), applyRows(.shared, 256, 1 << 18, false, 16)); + // the served groups: Qwen3.6-35B-A3B's 16 heads over 2 KV heads, Qwen3.8-27B's 24 over 4 + try std.testing.expectEqual(@as(usize, 8), applyGroup(scoreGroup(16, 2), cdiv(score_span, 128), 16, 2)); + try std.testing.expectEqual(@as(usize, 6), applyGroup(scoreGroup(24, 4), cdiv(score_span, 128), 24, 2)); +} + test "a small walk splits the heads of a KV head, a wide one keeps them together" { const std = @import("std"); try std.testing.expectEqual(@as(usize, 1), applyGroup(16, 1, 32, 1)); diff --git a/zig/src/hip/policy.zig b/zig/src/hip/policy.zig index 56b4e2ba00e..80e21e8b04a 100644 --- a/zig/src/hip/policy.zig +++ b/zig/src/hip/policy.zig @@ -218,6 +218,11 @@ pub const Policy = struct { } }; +/// Whether the smaller chunk admits more of `want` streams than the larger's in `room`, after the `slots` bytes. +pub fn narrows(room: u64, slots: u64, larger: u64, smaller: u64, per: u64, want: u64) bool { + return @min(want, (room -| slots -| smaller) / per) > @min(want, (room -| slots -| larger) / per); +} + test "apply sets fields and refuses what it does not know" { var p: Policy = .{}; try p.apply("matrix=off, kernels=reference,prefill_step=2048"); diff --git a/zig/src/inkling2_metal_host_test.zig b/zig/src/inkling2_metal_host_test.zig new file mode 100644 index 00000000000..eb76bab6406 --- /dev/null +++ b/zig/src/inkling2_metal_host_test.zig @@ -0,0 +1,6 @@ +//! Inkling 2 Mini Metal host tests rooted with the production engine sources. + +test { + _ = @import("families/inkling2/metal/host_test.zig"); + _ = @import("inkling2_native.zig"); +} diff --git a/zig/src/inkling2_native.zig b/zig/src/inkling2_native.zig new file mode 100644 index 00000000000..9101c4a644f --- /dev/null +++ b/zig/src/inkling2_native.zig @@ -0,0 +1,3 @@ +//! Module root for the Inkling 2 Mini native backend and its zig/src family dependencies. +pub const open = @import("native/inkling2.zig").open; +pub const refusal = @import("native/inkling2.zig").refusal; diff --git a/zig/src/native/cache_fit.zig b/zig/src/native/cache_fit.zig index f4facf4a4e9..7c1094db2a3 100644 --- a/zig/src/native/cache_fit.zig +++ b/zig/src/native/cache_fit.zig @@ -95,6 +95,11 @@ pub fn budgetUnder(limit: ?u64, gib: ?f64, over: bool, spare: u64, a: std.mem.Al return budgetUnderBeside(limit, gib, over, spare, 0, a, why, rank, null); } +/// A family's allocated buffers can further bound the automatic grant before its receipt is printed. +pub fn budgetUnderMaximum(limit: ?u64, gib: ?f64, over: bool, spare: u64, maximum: u64, a: std.mem.Allocator, why: *[]const u8, rank: []const u8) !api.PromptCachePlan { + return budgetUnderBeside(limit, gib, over, spare, 0, a, why, rank, maximum); +} + /// A host that sizes sessions after the cache retains its fixed automatic ceiling. pub fn budgetUnderFixed(limit: ?u64, gib: ?f64, over: bool, spare: u64, a: std.mem.Allocator, why: *[]const u8, rank: []const u8) !api.PromptCachePlan { return budgetUnderBeside(limit, gib, over, spare, 0, a, why, rank, DEFAULT_MINIMUM); @@ -110,7 +115,8 @@ fn budgetUnderBeside(limit: ?u64, gib: ?f64, over: bool, spare: u64, later: u64, const total = ram() orelse 0; const loaded = footprint() orelse 0; if (total == 0 or loaded == 0) { - const b = if (gib) |g| (if (g > 0) std.math.lossyCast(u64, g * GiB) else 0) else @min(spare, DEFAULT_MINIMUM); + const proposed = if (gib) |g| (if (g > 0) std.math.lossyCast(u64, g * GiB) else 0) else @min(spare, DEFAULT_MINIMUM); + const b = if (gib == null and fixed != null) @min(proposed, fixed.?) else proposed; std.log.info("prompt cache: {d:.1} GiB for kept prompt states{s} (no memory reading)", .{ gibs(b), rank }); return .{ .source = if (gib != null) .explicit else .metal_working_set, .budget_bytes = b, .explicit_budget = gib != null }; } @@ -124,7 +130,7 @@ fn budgetUnderBeside(limit: ?u64, gib: ?f64, over: bool, spare: u64, later: u64, } else why.* = try std.fmt.allocPrint(a, "--prompt-cache-gib {d} would take this server past 70% of this Mac's memory: it holds {d:.1} GiB once loaded{s}, 70% of {d:.0} GiB is {d:.1} GiB, and {d} GiB stays free for prompt buffers, so {d:.1} GiB is left for kept prompt states. Pass a smaller one{s}, leave --prompt-cache-gib out for the default {d:.1} GiB, or add --prompt-cache-over-cap to keep {d} GiB anyway.", .{ gib.?, gibs(loaded), streams, gibs(total), gibs(total / 100 * SHARE_PERCENT), MARGIN >> 30, gibs(left), if (later > 0) ", serve a smaller --parallel" else "", gibs(@min(left, fixed orelse defaultBudget(left))), gib.? }); return e; }; - const default_note = if (gib != null) "" else if (fixed != null) "; default: at most 16 GiB before session sizing; --prompt-cache-gib overrides it" else "; default: half the room, at least 16 GiB when available; --prompt-cache-gib overrides it"; + const default_note = if (gib != null) "" else if (fixed != null) (if (fixed.? == DEFAULT_MINIMUM) "; default: at most 16 GiB before session sizing; --prompt-cache-gib overrides it" else "; default: bounded by the remaining allowance; --prompt-cache-gib overrides it") else "; default: half the room, at least 16 GiB when available; --prompt-cache-gib overrides it"; std.log.info("prompt cache: {d:.1} GiB from {d:.1} GiB free under the {s} ({d:.1} GiB in use once loaded{s}, {d:.0} GiB of RAM, {d} GiB kept for prompt buffers){s}{s}{s}", .{ gibs(f.budget), gibs(f.room), if (limit != null) "load limit" else "70% cap", gibs(loaded), streams, gibs(total), MARGIN >> 30, if (f.budget > f.room) ", past the cap by --prompt-cache-over-cap" else "", rank, default_note }); return .{ .source = .physical_footprint, @@ -302,3 +308,13 @@ test "Flash Next batch retains main's session count at 128 GiB and a 30 GiB foot try std.testing.expectEqual(1 + old_room / each, 1 + plan.sessions / each); try std.testing.expectEqual(@as(u64, 0), (try fitUnderDefault(cap, 30 * GiB, 0, false, DEFAULT_MINIMUM)).budget); } + +test "cache maximum: missing footprint readings retain the automatic allowance" { + var why: []const u8 = ""; + const automatic = try budgetUnderMaximum(24 * GiB, null, false, 20 * GiB, 2 * GiB, std.testing.allocator, &why, ""); + try std.testing.expectEqual(@as(u64, 2 * GiB), automatic.budget_bytes); + const explicit = try budgetUnderMaximum(24 * GiB, 8, true, 20 * GiB, 2 * GiB, std.testing.allocator, &why, ""); + try std.testing.expectEqual(@as(u64, 8 * GiB), explicit.budget_bytes); + const off = try budgetUnderMaximum(24 * GiB, 0, false, 20 * GiB, 0, std.testing.allocator, &why, ""); + try std.testing.expectEqual(@as(u64, 0), off.budget_bytes); +} diff --git a/zig/src/native/cuda.zig b/zig/src/native/cuda.zig index 449016e155c..a116b5ba740 100644 --- a/zig/src/native/cuda.zig +++ b/zig/src/native/cuda.zig @@ -178,11 +178,8 @@ pub fn open(a: Allocator, gpa: Allocator, io: std.Io, o: api.Open, problem: *[]c return null; } fn openWith(comptime F: type, a: Allocator, gpa: Allocator, io: std.Io, asked: api.Open, problem: *[]const u8) !?api.Opened { - const o = family_memory.familyOpen(F, asked); - if (try refusals.place(F, a, o)) |why| { // a rank inside its world, a world the family serves: before admission - problem.* = why; - return null; - } + const resolved = (try @import("cuda_launch.zig").resolve(F, a, asked, problem)) orelse return null; // resolved and placed, before admission + const o = family_memory.familyOpen(F, resolved); if (refusals.family(F, o)) |why| { problem.* = why; return null; @@ -402,7 +399,7 @@ fn openWith(comptime F: type, a: Allocator, gpa: Allocator, io: std.Io, asked: a const store = try gpa.create(pc.Store); errdefer gpa.destroy(store); // rules and budget from the family's snap_* declarations (cuda_snaps.zig) - const image: ?*const pc.rows.Image = if (F == nemotron.native) &cuda_disk.image else if (comptime cuda_disk.keptDisk(F)) |K| &K.image else null; + const image: ?*const pc.rows.Image = if (F == nemotron.native) &cuda_disk.image else if (F == @import("glm_cuda").native) &@import("cuda_glm_disk.zig").image else if (comptime cuda_disk.keptDisk(F)) |K| &K.image else null; const copies: pc.Snapshots = .{ .ptr = loaded.target, .vtable = &snaps.Snaps(F, image).vtable }; var rules = snaps.passRules(F, @import("cuda_startup.zig").rows(F, loaded)); if (o.tp != 1) rules.warm = .off; // no warm passes across ranks: the cache keeps as without warm turns @@ -416,7 +413,7 @@ fn openWith(comptime F: type, a: Allocator, gpa: Allocator, io: std.Io, asked: a try kv_pages.store(F, store, loaded, kept); // its snapshot slots, before a disk probe takes one h.store = store; if (o.learn_conversations) if (o.learn) |root| { - if (F == nemotron.native) try cuda_disk.attach(a, io, &g.ctx, o, root, kernels, loaded, store); + if (F == nemotron.native) try cuda_disk.attach(a, io, &g.ctx, o, root, kernels, loaded, store) else if (F == @import("glm_cuda").native) try @import("cuda_glm_disk.zig").attach(a, io, &g.ctx, o, root, kernels, loaded, store); if (comptime cuda_disk.keptDisk(F)) |K| try cuda_disk.attachKept(K, F.model_type, a, io, &g.ctx, o, root, kernels, loaded, store); }; } @@ -559,6 +556,7 @@ test { _ = kv_pages; _ = drafted; _ = cuda_disk; // its tests run under test-cuda-disk-open-host's filter + _ = @import("cuda_glm_disk.zig"); _ = @import("cuda_disk_identity_test.zig"); _ = cuda_witness; _ = @import("cuda_pool_after_warmup.zig"); diff --git a/zig/src/native/cuda_disk_policy_test.zig b/zig/src/native/cuda_disk_policy_test.zig index 543c3d26674..d490a1a676a 100644 --- a/zig/src/native/cuda_disk_policy_test.zig +++ b/zig/src/native/cuda_disk_policy_test.zig @@ -171,6 +171,9 @@ test "disk identity: Flash Next CUDA resolved prompt rows, kernel forms and expe try changed.append(t.allocator, try flashKey(&x, &c)); @field(k.forms, field) = true; } + k.forms.gdn_chain_tpr = true; + try changed.append(t.allocator, try flashKey(&x, &c)); + k.forms.gdn_chain_tpr = false; inline for (.{ "readout_rows", "fact_rows" }) |field| { @field(k.forms, field) = std.math.maxInt(usize); // 0 set: never the tiles try changed.append(t.allocator, try flashKey(&x, &c)); @@ -219,7 +222,7 @@ test "disk identity: Flash Next CUDA prompt forms take each setting's value at l const env = @import("sys").env; const Engine = @typeInfo(@FieldType(flash.Cuda, "engine")).pointer.child; const Forms = @FieldType(@FieldType(Engine, "batch_k"), "forms"); - const names = [_][:0]const u8{ "TF_FLASHNEXT_GDN_FUSED", "TF_FLASHNEXT_HC_FUSE", "TF_FLASHNEXT_KEEP_INPASS", "TF_FLASHNEXT_READOUT_ROWS", "TF_FLASHNEXT_FACT_ROWS", "TF_FLASHNEXT_READOUT_FUSED" }; + const names = [_][:0]const u8{ "TF_FLASHNEXT_GDN_FUSED", "TF_FLASHNEXT_GDN_CHAIN_TPR", "TF_FLASHNEXT_HC_FUSE", "TF_FLASHNEXT_KEEP_INPASS", "TF_FLASHNEXT_READOUT_ROWS", "TF_FLASHNEXT_FACT_ROWS", "TF_FLASHNEXT_READOUT_FUSED" }; for (names) |n| _ = env.unsetenv(n); defer for (names) |n| { _ = env.unsetenv(n); @@ -234,6 +237,8 @@ test "disk identity: Flash Next CUDA prompt forms take each setting's value at l try t.expectEqual(@as(usize, 32), Forms.resolve().fact_rows); _ = env.setenv("TF_FLASHNEXT_READOUT_FUSED", "1", 1); try t.expect(Forms.resolve().readout_fused); + _ = env.setenv("TF_FLASHNEXT_GDN_CHAIN_TPR", "1", 1); + try t.expect(Forms.resolve().gdn_chain_tpr); } const nemotron = @import("nemotron"); diff --git a/zig/src/native/cuda_families.zig b/zig/src/native/cuda_families.zig index 6741ad5526a..330152792e4 100644 --- a/zig/src/native/cuda_families.zig +++ b/zig/src/native/cuda_families.zig @@ -12,9 +12,10 @@ const gemma4 = @import("gemma4_cuda"); const spark25 = @import("spark25"); const dory = @import("dory"); const qwen3 = @import("qwen3_cuda"); +const inkling2 = @import("inkling2"); /// CUDA families provide metadata, open their lane backend and explain their refusals. -pub const registry = .{ nemotron.native, nemotron.omni, glm.native, minimax.native, qwen35.native, qwen35.native_moe, flashnext.native, kolibri1.native, gemma4.native, gemma4.native31, spark25.native, dory.native, @import("dots_mocr_cuda").native, @import("muse_spark").native, @import("lfm2_moe_cuda").native }; +pub const registry = .{ nemotron.native, nemotron.omni, glm.native, minimax.native, qwen35.native, qwen35.native_moe, flashnext.native, kolibri1.native, gemma4.native, gemma4.native31, spark25.native, dory.native, @import("dots_mocr_cuda").native, @import("muse_spark").native, @import("ricursive_cuda").native, @import("lfm2_moe_cuda").native, inkling2.native }; pub const families: []const api.Family = blk: { var out: [registry.len + 6]api.Family = undefined; for (registry, 0..) |F, i| out[i] = .{ .model_type = F.model_type, .formats = F.formats, .decision_formats = if (@hasDecl(F, "decision_formats")) F.decision_formats else &.{} }; @@ -31,8 +32,8 @@ pub const families: []const api.Family = blk: { test "every registered family and d1's decision engine are listed for capabilities" { try std.testing.expectEqual(@as(usize, registry.len + 6), families.len); try std.testing.expectEqualStrings("nemotron_h", families[0].model_type); - try std.testing.expectEqualStrings("lfm2_moe", families[registry.len - 1].model_type); - try std.testing.expectEqualStrings("lfm2_vl", families[registry.len].model_type); + try std.testing.expectEqualStrings("lfm2_moe", families[registry.len - 2].model_type); + try std.testing.expectEqualStrings("inkling2_loop", families[registry.len - 1].model_type); try std.testing.expectEqualStrings("qwen4", families[registry.len + 2].model_type); try std.testing.expectEqualStrings("qwen4_text", families[registry.len + 3].model_type); try std.testing.expectEqualStrings("qwen3", families[registry.len + 4].model_type); diff --git a/zig/src/native/cuda_family_info.zig b/zig/src/native/cuda_family_info.zig index c5f4796fb99..a4eedc7a6f3 100644 --- a/zig/src/native/cuda_family_info.zig +++ b/zig/src/native/cuda_family_info.zig @@ -3,10 +3,11 @@ const std = @import("std"); const api = @import("engine_api"); const registry = @import("cuda_families.zig").registry; -/// The Info `openWith` serves: the host's fields, then what the family declares (its reasoning block). +/// The Info `openWith` serves: the host's fields, then what the family declares (its reasoning block, its think rules). pub fn familyInfo(comptime F: type, host: api.Info) api.Info { var info = host; info.reasoning = reasoning(F); + if (@hasDecl(F, "thinking")) F.thinking(&info); // a family's own think block rules return info; } @@ -32,4 +33,6 @@ test "the Info openWith serves carries each family's reasoning declaration over const kept = familyInfo(Plain, .{ .lanes = 6, .context_window = 8192, .startup = "plan" }); try std.testing.expect(kept.lanes == 6 and kept.context_window == 8192 and std.mem.eql(u8, kept.startup, "plan")); inline for (registry) |F| try std.testing.expectEqual(reasoning(F), familyInfo(F, .{ .reasoning = !reasoning(F) }).reasoning); + const bare = familyInfo(@import("ricursive_cuda").native, .{}); // Ripple's think rules: optional, no budget + try std.testing.expect(bare.reasoning_optional and !bare.thinking_budget); } diff --git a/zig/src/native/cuda_family_memory.zig b/zig/src/native/cuda_family_memory.zig index 05dc477aafc..d6e0ecf1a92 100644 --- a/zig/src/native/cuda_family_memory.zig +++ b/zig/src/native/cuda_family_memory.zig @@ -68,7 +68,7 @@ pub fn weights(comptime F: type, a: Allocator, io: std.Io, o: api.Open, problem: problem.* = try std.fmt.allocPrint(a, "cannot estimate checkpoint weight files ({s}); refusing CUDA admission", .{@errorName(err)}); return null; }; - const text = if (@hasDecl(F, "placementWeightBytes")) try F.placementWeightBytes(a, io, o.dir, o.tp, o.rank, o.drafts) else if (@hasDecl(F, "weightShare")) share(F, a, io, o.dir, whole, o.drafts) catch |err| { + const text = if (@hasDecl(F, "placementWeightBytes")) try F.placementWeightBytes(a, io, o.dir, o.tp, o.rank, o.drafts) else if (@hasDecl(F, "weightShare")) share(F, a, io, o.dir, whole, o.drafts, o.rank, o.tp) catch |err| { problem.* = (if (@hasDecl(F, "explains_open")) F.explain(null, err) else null) orelse try std.fmt.allocPrint(a, "cannot size this rank's weights ({s})", .{@errorName(err)}); return null; } else whole; @@ -76,8 +76,8 @@ pub fn weights(comptime F: type, a: Allocator, io: std.Io, o: api.Open, problem: } /// `F.weightShare`, plain bytes or an error union (a family whose split settings can be refused). -fn share(comptime F: type, a: Allocator, io: std.Io, dir: []const u8, whole: u64, drafts: bool) anyerror!u64 { - return F.weightShare(a, io, dir, whole, drafts); +fn share(comptime F: type, a: Allocator, io: std.Io, dir: []const u8, whole: u64, drafts: bool, rank: u32, tp: u32) anyerror!u64 { + return F.weightShare(a, io, dir, whole, drafts, rank, tp); } /// Logs, from 0.25 GiB, the free pages on the per-CPU lists that a pool's reading counted. diff --git a/zig/src/native/cuda_glm_disk.zig b/zig/src/native/cuda_glm_disk.zig new file mode 100644 index 00000000000..bb9674fa4bd --- /dev/null +++ b/zig/src/native/cuda_glm_disk.zig @@ -0,0 +1,266 @@ +//! GLM-5.3-Flash's CUDA kept states on disk (--learn-conversations): every rank's part in rank 0's files. +const std = @import("std"); +const cuda = @import("cuda"); +const api = @import("engine_api"); +const lanes = @import("lanes"); +const glm = @import("glm_cuda"); +const cuda_disk = @import("cuda_disk.zig"); +const img = glm.disk_image; +const ranks = glm.disk_ranks; +const rows = api.prompt_cache.rows; +const Engine = glm.engine.Engine; +const Kept = glm.engine.Kept; +const Allocator = std.mem.Allocator; + +pub const image: rows.Image = .{ .parts = parts, .gather = gather, .blank = blank, .scatter = scatter, .whole = whole }; + +/// Every rank's prefix bytes, read at attach (the process serves one model; rank 0 alone serves). +var prefix_buf: [8]u64 = undefined; +var prefixes: []const u64 = &.{}; +/// Where each rank's verify window rows begin in its prefix (the probe's hash leaves them out). +var window_buf: [prefix_buf.len]u64 = undefined; + +fn engineOf(ptr: *anyopaque) *Engine { + return @ptrCast(@alignCast(ptr)); +} + +fn parts(ptr: *anyopaque, at: u32, out: *std.ArrayList(rows.image.Part), a: Allocator) anyerror!void { + var list: std.ArrayList(img.Part) = .empty; + defer list.deinit(a); + try img.storeParts(try ranks.shape(engineOf(ptr)), prefixes, at, &list, a); + for (list.items) |p| try out.append(a, .{ .bytes = p.bytes, .row = p.row, .per = p.per }); +} + +/// The other ranks asleep before a disk call go back to sleep after it (their lines, not NCCL, wait meanwhile). +const Rest = struct { + e: *Engine, + asleep: bool, + + fn of(e: *Engine) Rest { + return .{ .e = e, .asleep = ranks.asleep(e) }; + } + + fn done(r: Rest) void { + if (r.asleep) ranks.rest(r.e) catch |err| std.log.warn("glm: the ranks did not sleep after a disk step ({s})", .{@errorName(err)}); + } +}; + +fn gather(ptr: *anyopaque, saved: api.prompt_cache.Saved, ranges: []const rows.image.Range, out: []u8) anyerror!void { + const e = engineOf(ptr); + const k: *Kept = @ptrCast(@alignCast(saved)); + const rest = Rest.of(e); + defer rest.done(); + var pieces: std.ArrayList(img.Piece) = .empty; + defer pieces.deinit(e.gpa); + const sh = try ranks.shape(e); + var o: usize = 0; + for (ranges) |g| { + pieces.clearRetainingCapacity(); + try img.route(sh, prefixes, k.at, g.off, g.len, &pieces, e.gpa); + for (pieces.items) |p| { + const n: usize = @intCast(p.len); + try ranks.take(e, p.rank, k.id, p.off, out[o..][0..n]); + o += n; + } + } +} + +/// A new id leased at `at` on every rank, filled by `scatter` and sealed by the words in its last one. +fn blank(ptr: *anyopaque, at: u32) anyerror!api.prompt_cache.Saved { + const e = engineOf(ptr); + const rest = Rest.of(e); + defer rest.done(); + const k = try e.gpa.create(Kept); + errdefer e.gpa.destroy(k); + k.* = .{ .id = try ranks.blank(e, at), .at = at }; + return @ptrCast(k); +} + +/// The last scatter brings the state's own file, words first: every rank seals it then (the words place the head). +fn scatter(ptr: *anyopaque, saved: api.prompt_cache.Saved, ranges: []const rows.image.Range, in: []const u8) anyerror!void { + const e = engineOf(ptr); + const k: *Kept = @ptrCast(@alignCast(saved)); + const rest = Rest.of(e); + defer rest.done(); + if (ranges.len > 0 and ranges[0].off == 0) { + if (ranges[0].len < img.Words.bytes) return error.DiskWords; + var x: [img.Words.count]u64 = undefined; + @memcpy(std.mem.sliceAsBytes(&x), in[0..img.Words.bytes]); + try ranks.seal(e, k.id, try ranks.decode(e, x, k.at)); + } + var pieces: std.ArrayList(img.Piece) = .empty; + defer pieces.deinit(e.gpa); + var out: std.ArrayList(ranks.Piece) = .empty; // at TP: the other ranks' bytes and the shared ones, in few steps + defer out.deinit(e.gpa); + const sh = try ranks.shape(e); + var o: usize = 0; + for (ranges) |g| { + pieces.clearRetainingCapacity(); + try img.route(sh, prefixes, k.at, g.off, g.len, &pieces, e.gpa); + for (pieces.items) |p| { + const n: usize = @intCast(p.len); + const bytes = in[o..][0..n]; + o += n; + if (p.rank == 0 and p.off < img.Words.bytes) continue; // the words went with the seal + if (prefixes.len == 1 or (p.rank == 0 and !p.shared)) { + try ranks.copy(e, k.id, p.off, @constCast(bytes), false); + } else try out.append(e.gpa, .{ .to = if (p.shared) ranks.every else p.rank, .off = if (p.shared) p.off - prefixes[0] else p.off, .bytes = bytes }); + } + } + if (out.items.len > 0) try ranks.rows(e, k.id, out.items); +} + +fn whole(ptr: *anyopaque, saved: api.prompt_cache.Saved) bool { + const k: *Kept = @ptrCast(@alignCast(saved)); + const s = engineOf(ptr).snaps.get(k.id) orelse return false; + return s.len != 0; +} + +/// A fixed prompt's store image hashed, other ranks' shared bytes checked equal: both but the bytes it never writes. +fn probe(a: Allocator, io: std.Io, backend: lanes.backend.Backend, e: *Engine) !struct { hash: u64, rate: f64 } { + const mark: u32 = glm.native.prompt_rows; + var toks: [glm.native.prompt_rows + 40]u32 = undefined; + for (&toks, 0..) |*x, i| x.* = @intCast(1000 + i * 7919 % 50000); + const Hook = struct { + e: *Engine, + saved: ?*anyopaque = null, + failed: ?anyerror = null, + fn at(p: *anyopaque, _: *lanes.Stream, m: u32) void { + const h: *@This() = @ptrCast(@alignCast(p)); + h.saved = glm.native.snap_save(h.e, null, m) catch |err| { + h.failed = err; + return; + }; + } + }; + var hook: Hook = .{ .e = e }; + const marks = [_]u32{mark}; + var s = try lanes.Stream.init(a, .{ .id = "probe", .prompt = &toks, .max_new = 1, .drafts = e.mtp, .reuse = .{ .marks = &marks, .hook = .{ .ptr = &hook, .at = Hook.at } } }); + defer s.deinit(a); + const t0 = std.Io.Clock.awake.now(io).toNanoseconds(); + backend.vtable.prefill(backend.ptr, &s) catch |err| { + backend.vtable.release(backend.ptr, &s); + return err; + }; + const ns = std.Io.Clock.awake.now(io).toNanoseconds() - t0; + backend.vtable.release(backend.ptr, &s); + const saved = hook.saved orelse return hook.failed orelse error.ProbeUnmarked; + defer glm.native.snap_drop(e, saved); + const k: *Kept = @ptrCast(@alignCast(saved)); + const sh = try ranks.shape(e); + const own = img.imageBytes(sh, mark); + var total = own; + for (prefixes[1..]) |p| total += p; + const bytes = try a.alloc(u8, @intCast(total)); + try gather(e, saved, &.{.{ .off = 0, .len = total }}, bytes); + var loose: std.ArrayList(img.Span) = .empty; + try img.unwritten(sh, prefixes, window_buf[0..prefixes.len], mark, (try ranks.wordsOf(e, k.id)).mtp_len, &loose, a); + img.clear(loose.items, 0, bytes); + const from = img.Words.bytes + sh.prefix; + const shared = bytes[@intCast(from)..@intCast(own)]; + var past: std.ArrayList(img.Span) = .empty; // the spans past rank 0's prefix, as spans of `shared` + for (loose.items) |x| if (x.off >= from) try past.append(a, .{ .off = x.off - from, .len = x.len }); + try ranks.same(e, k.id, prefixes, shared, past.items, try a.alloc(u8, shared.len)); + try ranks.rest(e); + return .{ .hash = std.hash.Wyhash.hash(0x676c6d, bytes), .rate = @as(f64, @floatFromInt(toks.len)) / (@as(f64, @floatFromInt(@max(ns, 1))) / 1e9) }; +} + +/// What --learn-conversations refuses before it reads a rank: TF_KV_SHARE, and more ranks than `prefix_buf` holds. +fn refusal(e: *const Engine) !void { + // TF_KV_SHARE leaves a kept state's prefix pages in the pool's prompt cache, outside the lease the image reads + if (e.share_pages) return error.KvShareWithLearnConversations; + if (e.share.world > prefix_buf.len) return error.TooManyRanks; +} + +/// --learn-conversations: every rank's prefix read, the identity probed on this thread, the store attached. +pub fn attach(a: Allocator, io: std.Io, ctx: *const cuda.Context, o: api.Open, root: []const u8, kernels: ?[]const u8, loaded: anytype, store: *api.prompt_cache.Store) !void { + const e: *Engine = loaded.target; + refusal(e) catch |err| { + if (err == error.KvShareWithLearnConversations) std.log.err("--learn-conversations: GLM-5.3-Flash's disk images read a kept state's whole lease, and TF_KV_SHARE leaves its prefix pages out of it; serve without one of them", .{}); + return err; + }; + try ranks.prefixes(e, prefix_buf[0..e.share.world], window_buf[0..e.share.world]); + prefixes = prefix_buf[0..e.share.world]; + const sh = try ranks.shape(e); + var facts: std.ArrayList(u64) = .empty; + try facts.appendSlice(a, &.{ e.share.world, sh.capacity, sh.ring_rows, sh.tail, @intFromBool(sh.head), @intFromBool(sh.scales), @intFromBool(e.drafter != null) }); + try facts.appendSlice(a, prefixes); + const p = try probe(a, io, loaded.backend, e); + const id = try cuda_disk.identityOf(a, io, ctx, o.dir, kernels, facts.items, p.hash, .{ .family = o.model_type, .backend = "cuda" }); + const r = try open(store, o, root, id, img.longest(sh)); + r.prefill_rate = p.rate; + std.log.info("glm: conversation states on disk in {s} ({d} states, {d} MiB of {d} MiB; {d} ranks' parts; a save stages up to {d} MiB)", .{ r.dir, r.states.items.len, r.held() >> 20, r.cap >> 20, prefixes.len, r.staging_bytes >> 20 }); +} + +/// The store for `id` through the shared attach, whose staging floor takes a `longest`-token state whole (rows.attach). +fn open(store: *api.prompt_cache.Store, o: api.Open, root: []const u8, id: u64, longest: u32) !*rows.Rows { + const gibs = struct { + fn bytes(g: f64) u64 { + return @intFromFloat(g * (1 << 30)); + } + }.bytes; + // spill stays off: an eviction would gather on rank 0 mid-pass while the other ranks wait in the gate's all-reduce + return rows.attach(store.gpa, store, .{ .root = root, .identity = id, .cap = gibs(o.learn_gib), .floor = gibs(o.learn_min_free_gib), .daily = gibs(o.learn_daily_gib), .lookahead = store.rules.lookahead, .planned = store.rules.planned, .grid = store.rules.grid, .longest = longest }); +} + +test "GLM disk attach: TF_KV_SHARE and more ranks than the prefixes hold are refused by name" { + const e = try std.testing.allocator.create(Engine); + defer std.testing.allocator.destroy(e); + e.share_pages = false; + e.share.world = prefix_buf.len; + try refusal(e); + e.share.world = prefix_buf.len + 1; + try std.testing.expectError(error.TooManyRanks, refusal(e)); + e.share.world = 2; + e.share_pages = true; + try std.testing.expectError(error.KvShareWithLearnConversations, refusal(e)); +} + +test "CUDA disk open: GLM's store takes the shared attach's staging floor, so a 125K-token state is staged, not StagingFull" { + const gpa = std.testing.allocator; + const T = struct { + const token = 18_944; // about 18.5 KiB a token, as a served state's files measure (683 MiB at 36,864 tokens) + fn parts(_: *anyopaque, at: u32, out: *std.ArrayList(rows.image.Part), a: Allocator) anyerror!void { + try out.append(a, .{ .bytes = @as(u64, at) * token, .row = token }); + } + fn bytes(_: *anyopaque, _: u32) u64 { + return 0; + } + fn save(_: *anyopaque, _: ?*anyopaque, _: u32) anyerror!api.prompt_cache.Saved { + return error.Unused; + } + fn restore(_: *anyopaque, _: ?*anyopaque, _: api.prompt_cache.Saved) anyerror!void {} + fn drop(_: *anyopaque, _: api.prompt_cache.Saved) void {} + }; + const sized: rows.Image = .{ .parts = T.parts, .gather = gather, .blank = blank, .scatter = scatter, .whole = whole }; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const root = try tmp.dir.realPathFileAlloc(std.testing.io, ".", gpa); + defer gpa.free(root); + var family: u8 = 0; + const vt: api.prompt_cache.Snapshots.VTable = .{ .bytes = T.bytes, .save = T.save, .restore = T.restore, .drop = T.drop, .rows = &sized }; + const default = (rows.Options{ .root = "", .identity = 0, .cap = 0, .floor = 0, .daily = 0 }).staging_bytes; + const window = 131_072; + // a RAM store that keeps the state, and one too small for it: the floor is the state's charge within that budget + for ([_]u64{ 8 << 30, 1 << 29 }) |budget| { + var store = api.prompt_cache.Store.init(gpa, .{ .ptr = &family, .vtable = &vt }, .{ .lookahead = 1 }, budget); + const r = open(&store, .{ .dir = "d", .model_type = "glm", .learn = root, .learn_conversations = true }, root, 7, window) catch |e| { + store.deinit(); + return e; + }; + defer r.deinit(); + defer store.deinit(); // the store before its disk, as the rows fixtures close them + try std.testing.expectEqual(r, store.disk.?); + try std.testing.expectEqual(rows.Spill.off, r.spill); + const long = try rows.write.coldCharge(r, 124_928); // the conversation the default skipped (StagingFull) + try std.testing.expect(long > default); + if (budget > long) { + try std.testing.expect(r.staging_bytes >= long); // the permit a save's stage step asks `fits` of + try std.testing.expectEqual(try rows.write.coldCharge(r, window), r.staging_bytes); // the longest, whole + } else try std.testing.expectEqual(default, r.staging_bytes); + } +} + +test { + std.testing.refAllDecls(@This()); +} diff --git a/zig/src/native/cuda_launch.zig b/zig/src/native/cuda_launch.zig new file mode 100644 index 00000000000..f315550b133 --- /dev/null +++ b/zig/src/native/cuda_launch.zig @@ -0,0 +1,168 @@ +//! A CUDA family's place from the launch flags and its legacy rank variables (fabric/mesh/launch.zig), resolved once. +const std = @import("std"); +const api = @import("engine_api"); +const mesh = @import("mesh"); +const settings = @import("sys").environment; +const glm = @import("glm_cuda").native; +const minimax = @import("minimax_m3_cuda").native; +const nemotron = @import("nemotron"); + +const Allocator = std.mem.Allocator; +const Family = mesh.launch.Family; + +/// Which rank aliases `F` reads: only the CUDA families that had their own rank variables. +pub fn family(comptime F: type) Family { + if (F == glm) return .glm; + if (F == minimax) return .minimax; + if (F == nemotron.native or F == nemotron.omni) return .nemotron; + return .other; +} + +/// `o` resolved (`tp`, `rank`, `launch_from`) in a world `F` serves, or null with `problem` set; before admission. +pub fn resolve(comptime F: type, a: Allocator, o: api.Open, problem: *[]const u8) !?api.Open { + const out = (try resolveWith(a, o, family(F), settings.Process{}, problem)) orelse return null; + if (try @import("cuda_refusal.zig").place(F, a, out)) |why| { // a rank inside its world, a world the family serves + problem.* = why; + return null; + } + return out; +} + +pub fn resolveWith(a: Allocator, o: api.Open, fam: Family, lookup: anytype, problem: *[]const u8) !?api.Open { + if (fam == .other) return o; // no aliases: the request's own tp and rank stand, checked by the family + const flags: mesh.launch.Flags = .{ + .tp = if (o.given.tp) o.tp else null, + .rank = if (o.given.rank) o.rank else null, + .master = if (o.master.len > 0) o.master else null, + .port = o.master_port, + }; + const l = mesh.launch.resolve(flags, lookup, fam) catch |e| { + // no world at all: GLM's own open refuses it (NoRank) where it always has, after the device and admission + if (e == error.NoPlace) return unplaced(o); + problem.* = try refusal(a, e, fam, o, lookup); + return null; + }; + for ([_]?[:0]const u8{ l.world_name, l.rank_name }) |name| if (name) |n| if (settings.retired(n, o.release)) |r| { + problem.* = try std.fmt.allocPrint(a, "{s} was replaced by {s} in {s}; launch with {s}", .{ n, r.flag.?, r.retire.?, r.flag.? }); + return null; + }; + var out = o; + out.tp = l.tensor; + out.rank = l.rank; + out.launch_from = switch (l.from) { + .flags => "--tp", + .alias => try std.fmt.allocPrint(a, "{s}, an alias of --tp", .{l.world_name.?}), + .mixed => try std.fmt.allocPrint(a, "--tp and {s}", .{l.world_name.?}), + .default => "one rank", + }; + if (l.world_name) |n| if (settings.rule(n).retire) |r| + std.log.warn("{s} and {s} are aliases of --tp and --rank until {s}; launch with --tp {d} --rank {d}", .{ n, l.rank_name.?, r, l.tensor, l.rank }); + return out; +} + +/// `o` as the flags left it, with no source: a family that needs a place refuses it in its own `open`. +fn unplaced(o: api.Open) api.Open { + var out = o; + out.launch_from = ""; + return out; +} + +/// Each refusal names only the flags given and the alias values read, never a default the user did not give. +fn refusal(a: Allocator, e: mesh.launch.Error, fam: Family, o: api.Open, lookup: anytype) ![]const u8 { + const n = mesh.launch.names(fam).?; + const world = lookup.get(n.world) orelse ""; + const rank = lookup.get(n.rank) orelse ""; + return switch (e) { + error.PartialAlias => std.fmt.allocPrint(a, "{s} and {s} go together: launch with --tp and --rank", .{ n.world, n.rank }), + error.BadAlias => std.fmt.allocPrint(a, "{s}={s} and {s}={s}: whole numbers; launch with --tp and --rank", .{ n.world, world, n.rank, rank }), + error.Disagree => if (o.given.tp and (std.fmt.parseInt(u32, world, 10) catch o.tp) != o.tp) + std.fmt.allocPrint(a, "--tp {d} differs from {s}={s}: give one of them, or equal values", .{ o.tp, n.world, world }) + else + std.fmt.allocPrint(a, "--rank {d} differs from {s}={s}: give one of them, or equal values", .{ o.rank, n.rank, rank }), + error.BadFlag => badFlag(a, o, n, world, rank), + error.NoPlace => unreachable, // resolveWith passes it on (unplaced) + error.PipelineNotServed => "argument --pp: pipeline stages are not served yet (#2005); serve with --pp 1", + }; +} + +/// The merged rank against the world's real source: --tp, the world alias, or --tp's default of 1. +fn badFlag(a: Allocator, o: api.Open, n: mesh.launch.Names, world: []const u8, rank: []const u8) ![]const u8 { + const r = if (o.given.rank) o.rank else std.fmt.parseInt(u32, rank, 10) catch 0; + if (o.given.tp) return std.fmt.allocPrint(a, "argument --rank: {d} is not below --tp {d}", .{ r, o.tp }); + if (world.len > 0) return std.fmt.allocPrint(a, "argument --rank: {d} is not below {s}={s}", .{ r, n.world, world }); + return std.fmt.allocPrint(a, "argument --rank: {d} is not below --tp 1 (its default; no --tp was given)", .{r}); +} + +const testing = std.testing; + +const Map = struct { + pairs: []const [2][]const u8, + pub fn get(m: Map, name: []const u8) ?[]const u8 { + for (m.pairs) |p| if (std.mem.eql(u8, p[0], name)) return p[1]; + return null; + } +}; + +test "GLM by its aliases, by flags or by both resolves alike; other families read no aliases" { + var arena: std.heap.ArenaAllocator = .init(testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var problem: []const u8 = ""; + const pair: Map = .{ .pairs = &.{ .{ "TF_GLM_WORLD", "2" }, .{ "TF_GLM_RANK", "1" } } }; + const none: Map = .{ .pairs = &.{} }; + const by_alias = (try resolveWith(a, .{ .dir = "d", .model_type = "glm5_next" }, .glm, pair, &problem)).?; + const by_flags = (try resolveWith(a, .{ .dir = "d", .model_type = "glm5_next", .tp = 2, .rank = 1, .given = .{ .tp = true, .rank = true } }, .glm, none, &problem)).?; + const by_both = (try resolveWith(a, .{ .dir = "d", .model_type = "glm5_next", .tp = 2, .given = .{ .tp = true } }, .glm, pair, &problem)).?; + for ([_]api.Open{ by_alias, by_flags, by_both }) |o| { + try testing.expectEqual(@as(u32, 2), o.tp); + try testing.expectEqual(@as(u32, 1), o.rank); + } + try testing.expectEqualStrings("TF_GLM_WORLD, an alias of --tp", by_alias.launch_from); + try testing.expectEqualStrings("--tp", by_flags.launch_from); + try testing.expectEqualStrings("--tp and TF_GLM_WORLD", by_both.launch_from); + const mm: Map = .{ .pairs = &.{ .{ "TF_MINIMAX_WORLD", "2" }, .{ "TF_MINIMAX_RANK", "1" } } }; + const minimax_alias = (try resolveWith(a, .{ .dir = "d", .model_type = "minimax_m3_vl" }, .minimax, mm, &problem)).?; + try testing.expectEqual(@as(u32, 1), minimax_alias.rank); + try testing.expectEqualStrings("TF_MINIMAX_WORLD, an alias of --tp", minimax_alias.launch_from); + try testing.expectEqual(Family.minimax, family(minimax)); + try testing.expectEqual(Family.glm, family(glm)); + try testing.expectEqual(Family.nemotron, family(nemotron.native)); + try testing.expectEqual(Family.nemotron, family(nemotron.omni)); + const other = (try resolveWith(a, .{ .dir = "d", .model_type = "m" }, .other, pair, &problem)).?; + try testing.expectEqual(@as(u32, 1), other.tp); + // a request built in code keeps its placement: no flag bits, no aliases, nothing to resolve + const coded = (try resolveWith(a, .{ .dir = "d", .model_type = "m", .tp = 2, .rank = 1 }, .other, pair, &problem)).?; + try testing.expectEqual(@as(u32, 2), coded.tp); + try testing.expectEqual(@as(u32, 1), coded.rank); +} + +test "refusals name the flags and the aliases; a retired alias names its flag" { + var arena: std.heap.ArenaAllocator = .init(testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var problem: []const u8 = ""; + const none: Map = .{ .pairs = &.{} }; + const unset = (try resolveWith(a, .{ .dir = "d", .model_type = "glm5_next" }, .glm, none, &problem)).?; + try testing.expectEqualStrings("", unset.launch_from); // GLM's open refuses it (NoRank), as it always has + const pair: Map = .{ .pairs = &.{ .{ "TF_GLM_WORLD", "3" }, .{ "TF_GLM_RANK", "1" } } }; + try testing.expect(try resolveWith(a, .{ .dir = "d", .model_type = "glm5_next", .tp = 2, .given = .{ .tp = true } }, .glm, pair, &problem) == null); + try testing.expectEqualStrings("--tp 2 differs from TF_GLM_WORLD=3: give one of them, or equal values", problem); + try testing.expect(try resolveWith(a, .{ .dir = "d", .model_type = "glm5_next", .rank = 2, .given = .{ .rank = true } }, .glm, pair, &problem) == null); + try testing.expectEqualStrings("--rank 2 differs from TF_GLM_RANK=1: give one of them, or equal values", problem); + const two: Map = .{ .pairs = &.{ .{ "TF_GLM_WORLD", "2" }, .{ "TF_GLM_RANK", "2" } } }; + try testing.expect(try resolveWith(a, .{ .dir = "d", .model_type = "glm5_next", .rank = 2, .given = .{ .rank = true } }, .glm, two, &problem) == null); + try testing.expectEqualStrings("argument --rank: 2 is not below TF_GLM_WORLD=2", problem); + const partial: Map = .{ .pairs = &.{.{ "TF_GLM_WORLD", "3" }} }; + try testing.expect(try resolveWith(a, .{ .dir = "d", .model_type = "glm5_next" }, .glm, partial, &problem) == null); + try testing.expectStringStartsWith(problem, "TF_GLM_WORLD and TF_GLM_RANK go together"); + // the retirement release is settings.alias_retire, set at landing; an earlier release still reads the alias + try testing.expect(try resolveWith(a, .{ .dir = "d", .model_type = "glm5_next", .release = settings.alias_retire }, .glm, pair, &problem) == null); + try testing.expectEqualStrings(try std.fmt.allocPrint(a, "TF_GLM_WORLD was replaced by --tp in {s}; launch with --tp", .{settings.alias_retire}), problem); + try testing.expect(try resolveWith(a, .{ .dir = "d", .model_type = "glm5_next", .release = "0.0.1" }, .glm, pair, &problem) != null); + // the values a launch gave, not defaults: a parsed world equal to --tp leaves the rank as the conflict + const plus: Map = .{ .pairs = &.{ .{ "TF_GLM_WORLD", "+2" }, .{ "TF_GLM_RANK", "1" } } }; + try testing.expect(try resolveWith(a, .{ .dir = "d", .model_type = "glm5_next", .tp = 2, .rank = 0, .given = .{ .tp = true, .rank = true } }, .glm, plus, &problem) == null); + try testing.expectEqualStrings("--rank 0 differs from TF_GLM_RANK=1: give one of them, or equal values", problem); + try testing.expect(try resolveWith(a, .{ .dir = "d", .model_type = "glm5_next", .tp = 2, .given = .{ .tp = true } }, .glm, two, &problem) == null); + try testing.expectEqualStrings("argument --rank: 2 is not below --tp 2", problem); +} diff --git a/zig/src/native/cuda_options.zig b/zig/src/native/cuda_options.zig index 98cb42bec4f..ef19c8f98e5 100644 --- a/zig/src/native/cuda_options.zig +++ b/zig/src/native/cuda_options.zig @@ -16,6 +16,7 @@ pub fn set(comptime F: type, o: api.Open, opts: *F.Options, problem: *[]const u8 opts.master = if (o.master.len > 0) o.master else null; opts.master_port = o.master_port; } + if (@hasField(F.Options, "launch_from")) opts.launch_from = o.launch_from; if (comptime @hasField(F.Options, "vision")) { if (o.vision) |vo| { const own: ?u32 = comptime if (@hasDecl(F, "default_image_tokens")) F.default_image_tokens else null; diff --git a/zig/src/native/cuda_refusal.zig b/zig/src/native/cuda_refusal.zig index 7c4b71ddbd3..af2bd320fc7 100644 --- a/zig/src/native/cuda_refusal.zig +++ b/zig/src/native/cuda_refusal.zig @@ -42,9 +42,9 @@ pub fn backend(o: api.Open) ?[]const u8 { return null; } -/// LFM2 reads a checkpoint's pictures through its own tower without --vision: the flag is refused, not ignored. +/// LFM2 opens outside `family()`: its ranks are refused here, and --vision goes on to core's gate in its open. pub fn lfm2(o: api.Open) ?[]const u8 { - return if (o.vision != null) lfm2_vision else unranked(o); + return unranked(o); } pub const no_ranks = "this CUDA family has no tensor-parallel ranks: serve without --tp and --rank"; @@ -54,9 +54,6 @@ pub fn unranked(o: api.Open) ?[]const u8 { return if (o.tp != 1 or (o.given.rank and o.rank != 0)) no_ranks else null; } -const lfm2_vision = "--vision: LFM2 reads the checkpoint's images through its own tower without the flag; " ++ - "serve it without --vision"; - /// A given --rank below the world, as main's CLI refused it, and a world in the family's `worlds` when it lists them. pub fn place(comptime F: type, a: std.mem.Allocator, o: api.Open) !?[]const u8 { if (o.given.rank and o.rank >= o.tp) return try std.fmt.allocPrint(a, "argument --rank: {d} is not below --tp {d}", .{ o.rank, o.tp }); @@ -64,7 +61,7 @@ pub fn place(comptime F: type, a: std.mem.Allocator, o: api.Open) !?[]const u8 { return null; } -/// A family takes --drafter only if it says so, and --learn-conversations only as Nemotron; null: `o` may open `F`. +/// A family takes --drafter only if it says so, and --learn-conversations only as Nemotron, GLM or a kept_disk family. pub fn family(comptime F: type, o: api.Open) ?[]const u8 { if (comptime @hasDecl(F, "kvHostRefusal")) if (F.kvHostRefusal(o)) |why| return why; if (qwen35Tp(F, o)) |why| return why; // ahead of every flag's own refusal: no rank of this family serves yet @@ -74,11 +71,16 @@ pub fn family(comptime F: type, o: api.Open) ?[]const u8 { if ((o.tp != 1 or (o.given.rank and o.rank != 0)) and !ranked) return no_ranks; // ahead of the drafter's and --learn-conversations' refusals (--spill-gib sets that flag), on a line of its own if (o.spill == .evicted and F != nemotron.native and @import("cuda_disk.zig").keptDisk(F) == null) return "--spill-gib keeps evicted states on disk for Nemotron, the Qwen hybrids, Flash Next, Gemma 4, Dory and Spark2.5 only on CUDA: serve this model without it"; + // GLM's disk store writes every rank's part between passes and stages nothing at eviction (cuda_glm_disk.attach) + if (F == @import("glm_cuda").native and (o.spill != .off or o.keep != null)) return "--spill-gib and --checkpoint-slots: GLM-5.3-Flash on CUDA keeps states on disk with --learn-conversations alone; serve it without them"; + // a live-half keep holds one KDA half, and GLM's disk image holds both (cuda_disk_image.zig) + if (F == @import("glm_cuda").native and o.learn_conversations and @import("glm_cuda").snapshots.layout.liveHalfEnabled()) + return "--learn-conversations and TF_GLM_KV_LIVE_HALF=1: GLM-5.3-Flash's disk image holds both KDA halves and a live-half keep one; serve without one of them"; if (o.drafter != null and !(@hasDecl(F, "takes_drafter") and F.takes_drafter)) { if (@hasDecl(F, "drafter_refusal")) return F.drafter_refusal; // a family without an MTP head says so itself return "--drafter loads a separate drafter, and this CUDA family drafts with its own MTP head: serve without --drafter"; } - if (o.learn_conversations and F != nemotron.native and @import("cuda_disk.zig").keptDisk(F) == null) return "--learn-conversations keeps conversation states on disk for Nemotron, the Qwen hybrids, Flash Next, Gemma 4, Dory and Spark2.5 only on CUDA: serve this model without it"; + if (o.learn_conversations and F != nemotron.native and F != @import("glm_cuda").native and @import("cuda_disk.zig").keptDisk(F) == null) return "--learn-conversations keeps conversation states on disk for Nemotron, GLM-5.3-Flash, the Qwen hybrids, Flash Next, Gemma 4, Dory and Spark2.5 only on CUDA: serve this model without it"; if (o.learn_conversations and o.tp > 1) if (@import("cuda_disk.zig").keptDisk(F)) |K| if (@hasDecl(K, "one_rank") and K.one_rank) return "--learn-conversations keeps one rank's states on disk for this CUDA family: serve without --tp or without --learn-conversations"; if (o.kv8 and !(@hasDecl(F, "Options") and @hasField(F.Options, "kv8"))) return "--kv-cache fp8: this CUDA family keeps bf16 caches; serve without it"; if (o.prompt_int8 and !(@hasDecl(F, "Options") and @hasField(F.Options, "prompt_int8"))) return "--prompt-precision int8: this CUDA family's prompt matmuls take bf16 inputs; serve without it"; @@ -220,12 +222,15 @@ test "flags with nothing to do on CUDA are refused, not ignored" { try std.testing.expect(backend(.{ .dir = "d", .model_type = "nemotron_h", .prompt_cache_gib = 4 }) == null); } -test "--vision is each family's to take: Super VL reads images, LFM2 refuses the flag, the rest refuse at their open" { +test "--vision is each family's to take: LFM2 passes it on to core's gate at its open, its ranks are still refused" { for ([_][]const u8{ "nemotron_h", "nemotron_h_omni", "glm5_next", "lfm2_vl" }) |t| { try std.testing.expect(backend(.{ .dir = "d", .model_type = t, .vision = .{} }) == null); } - try std.testing.expectEqualStrings(lfm2_vision, lfm2(.{ .dir = "d", .model_type = "lfm2_vl", .vision = .{} }) orelse ""); + try std.testing.expect(lfm2(.{ .dir = "d", .model_type = "lfm2_vl", .vision = .{} }) == null); try std.testing.expect(lfm2(.{ .dir = "d", .model_type = "lfm2_vl" }) == null); + try std.testing.expectEqualStrings(no_ranks, lfm2(.{ .dir = "d", .model_type = "lfm2_vl", .vision = .{}, .tp = 2 }).?); + const one: api.Open = .{ .dir = "d", .model_type = "lfm2_vl", .vision = .{}, .rank = 1, .given = .{ .rank = true } }; + try std.testing.expectEqualStrings(no_ranks, lfm2(one).?); } test "--drafter opens only a family that takes one" { @@ -277,7 +282,7 @@ test "a family with no head of its own words its --drafter refusal" { try std.testing.expectEqualStrings("--drafter: none yet", family(Headless, .{ .dir = "d", .model_type = "m", .drafter = "x" }) orelse ""); } -test "--learn-conversations opens Nemotron and a family whose states declare a disk image, no other" { +test "--learn-conversations opens Nemotron, GLM-5.3-Flash and a family whose states declare a disk image, no other" { const Other = struct {}; const Imaged = struct { pub const kept_disk = struct {}; @@ -302,6 +307,7 @@ test "--learn-conversations opens Nemotron and a family whose states declare a d try std.testing.expect(family(AllRanks, .{ .dir = "d", .model_type = "m", .tp = 2, .learn_conversations = true }) == null); try std.testing.expectStringStartsWith(family(Other, .{ .dir = "d", .model_type = "m", .learn_conversations = true }) orelse "", "--learn-conversations keeps"); try std.testing.expect(family(nemotron.native, .{ .dir = "d", .model_type = "nemotron_h", .learn_conversations = true }) == null); + try std.testing.expect(family(@import("glm_cuda").native, .{ .dir = "d", .model_type = "glm5_next", .learn_conversations = true }) == null); } test "CUDA MTP controls respect window and probability bounds" { @@ -357,27 +363,38 @@ test "--prompt-cache-gib is refused by name for a family that keeps no prompts, try std.testing.expect(family(@import("lfm2_moe_cuda").native, .{ .dir = "d", .model_type = "lfm2_moe", .prompt_cache_gib = 4 }) == null); } -test "--spill-gib and --checkpoint-slots open the families with a disk image; the rest refuse them by name" { +test "--spill-gib and --checkpoint-slots open the families with a disk image; GLM and the rest refuse them by name" { const spilled: api.Open = .{ .dir = "d", .model_type = "m", .learn = "/s", .learn_conversations = true, .spill = .evicted, .keep = 2 }; try std.testing.expect(backend(spilled) == null); try std.testing.expect(family(nemotron.native, spilled) == null); try std.testing.expect(family(@import("qwen35").native, spilled) == null); try std.testing.expect(family(@import("qwen35").native_moe, spilled) == null); try std.testing.expect(family(@import("flashnext").native, spilled) == null); + const glm = @import("glm_cuda").native; // its states go to disk with --learn-conversations alone + try std.testing.expectStringStartsWith(family(glm, spilled) orelse "", "--spill-gib keeps evicted states"); + const finish: api.Open = .{ .dir = "d", .model_type = "glm5_next", .learn = "/s", .learn_conversations = true, .spill = .finish }; + try std.testing.expectStringStartsWith(family(glm, finish) orelse "", "--spill-gib and --checkpoint-slots: GLM"); + const slots: api.Open = .{ .dir = "d", .model_type = "glm5_next", .learn = "/s", .learn_conversations = true, .keep = 2 }; + try std.testing.expectStringStartsWith(family(glm, slots) orelse "", "--spill-gib and --checkpoint-slots: GLM"); + try std.testing.expect(family(glm, .{ .dir = "d", .model_type = "glm5_next", .learn = "/s", .learn_conversations = true }) == null); const Other = struct {}; try std.testing.expectStringStartsWith(family(Other, spilled) orelse "", "--spill-gib keeps evicted states"); try std.testing.expectStringStartsWith(backend(.{ .dir = "d", .model_type = "m", .keep = 2 }) orelse "", "--checkpoint-slots sets how many"); try std.testing.expect(backend(.{ .dir = "d", .model_type = "m" }) == null); } -test "GLM keeps its prompt states in the process: no disk image, so --spill-gib and --learn-conversations refuse" { +test "GLM keeps its prompt states on disk with --learn-conversations alone, and refuses it with TF_GLM_KV_LIVE_HALF=1" { // TF_GLM_KV_LIVE_HALF's keeps omit the dead KDA half; they must never reach a store a server without the flag reads const glm = @import("glm_cuda").native; try std.testing.expect(@import("cuda_disk.zig").keptDisk(glm) == null); const spill: api.Open = .{ .dir = "d", .model_type = "glm5_next", .learn = "/s", .learn_conversations = true, .spill = .evicted }; try std.testing.expectStringStartsWith(family(glm, spill) orelse "", "--spill-gib keeps evicted states"); const learn: api.Open = .{ .dir = "d", .model_type = "glm5_next", .learn = "/s", .learn_conversations = true }; - try std.testing.expectStringStartsWith(family(glm, learn) orelse "", "--learn-conversations keeps"); + try std.testing.expect(family(glm, learn) == null); + const env = @import("sys").env; + try std.testing.expectEqual(@as(c_int, 0), env.setenv("TF_GLM_KV_LIVE_HALF", "1", 1)); + defer _ = env.unsetenv("TF_GLM_KV_LIVE_HALF"); + try std.testing.expectStringStartsWith(family(glm, learn) orelse "", "--learn-conversations and TF_GLM_KV_LIVE_HALF=1"); } /// The scopes this open's startup check covers, from its flags and model type. diff --git a/zig/src/native/cuda_vision_offer.zig b/zig/src/native/cuda_vision_offer.zig index f0a0b398e62..f5261563c47 100644 --- a/zig/src/native/cuda_vision_offer.zig +++ b/zig/src/native/cuda_vision_offer.zig @@ -115,7 +115,7 @@ fn omniVideo(ctx: *anyopaque, a: Allocator, src: api.VideoSource, max_tokens: u3 /// The device bytes a family's tower takes beside its text weights on this rank, 0 without --vision. pub fn weightBytes(comptime F: type, a: Allocator, io: std.Io, o: api.Open) !u64 { - if (comptime @hasDecl(F, "visionBytes")) if (o.vision != null and o.rank == 0) return F.visionBytes(a, io, o.dir); + if (comptime @hasDecl(F, "visionBytes")) if (o.vision != null) return F.visionBytes(a, io, o.dir, o.rank, o.tp); // its holder's rank return 0; } diff --git a/zig/src/native/flashnext_cache_budget.zig b/zig/src/native/flashnext_cache_budget.zig new file mode 100644 index 00000000000..ffc1d6d1868 --- /dev/null +++ b/zig/src/native/flashnext_cache_budget.zig @@ -0,0 +1,8 @@ +//! Automatic cache room must respect both the footprint and allocated pool buffers. +const math = @import("cache_budget.zig"); +const margin = @import("sys").memory_policy.margin; +pub fn automatic(cap: u64, ready: u64, allocated: u64) !u64 { + const room = cap -| ready -| margin; + const physical = (try math.fitUnder(cap, ready, null, false, .{ .margin = margin, .ceiling = @min(room, @max(16 * math.GiB, room / 2)) })).budget; + return @min(physical, cap -| allocated -| margin); +} diff --git a/zig/src/native/flashnext_cache_setup.zig b/zig/src/native/flashnext_cache_setup.zig index 14236f1a8a8..a9bb07088aa 100644 --- a/zig/src/native/flashnext_cache_setup.zig +++ b/zig/src/native/flashnext_cache_setup.zig @@ -13,6 +13,11 @@ pub fn cacheBudget(eng: *fx.Engine, gib: ?f64, over: bool, limit: ?u64, a: Alloc if (limit) |cap| { const ready = cache_fit.footprint() orelse return error.NoMemoryReading; if (ready +| cache_fit.MARGIN > cap) return error.OverMemoryLimit; + if (gib == null) if (eng.r.fsr) |fsr| if (fsr.pool != null) { + const maximum = try @import("flashnext_cache_budget.zig").automatic(cap, ready, dev.allocated()); + if (maximum < cache_fit.defaultBudget(cap -| ready -| cache_fit.MARGIN)) + return cache_fit.budgetUnderMaximum(cap, gib, over, dev.maxWorkingSet() -| dev.allocated(), maximum, a, why, rank); + }; return cache_fit.budgetUnder(cap, gib, over, dev.maxWorkingSet() -| dev.allocated(), a, why, rank); } return cache_fit.budget(gib, over, dev.maxWorkingSet() -| dev.allocated() -| (8 << 30), a, why, rank); diff --git a/zig/src/native/glm_host.zig b/zig/src/native/glm_host.zig index b7070ff5a90..ddee2bb22e6 100644 --- a/zig/src/native/glm_host.zig +++ b/zig/src/native/glm_host.zig @@ -157,7 +157,7 @@ pub fn open(gpa: Allocator, io: std.Io, dir: []const u8, window: u32, speed_up: if (eng.ep != null) return error.LearnConversationsOnPair; if (h.cache) |*store| { const id = try glm_disk.identity(gpa, io, dir, eng, &h.slots); - const r = try api.prompt_cache.rows.attach(gpa, store, .{ .root = l.root, .identity = id.id, .cap = l.cap, .floor = l.floor, .daily = l.daily, .lookahead = cache_rules.lookahead, .planned = cache_rules.planned, .spill = l.spill, .slots = l.slots }); + const r = try api.prompt_cache.rows.attach(gpa, store, .{ .root = l.root, .identity = id.id, .cap = l.cap, .floor = l.floor, .daily = l.daily, .lookahead = cache_rules.lookahead, .planned = cache_rules.planned, .spill = l.spill, .slots = l.slots, .longest = serves }); r.prefill_rate = id.rate; } } else { diff --git a/zig/src/native/inkling2.zig b/zig/src/native/inkling2.zig new file mode 100644 index 00000000000..dd0105c93ea --- /dev/null +++ b/zig/src/native/inkling2.zig @@ -0,0 +1,287 @@ +//! Text-only Inkling 2 Mini on Metal, with exact prompt reuse and budgeted stream state. +const std = @import("std"); +const mtl = @import("metal"); +const api = @import("engine_api"); +const lanes = @import("lanes"); +const Model = @import("../families/inkling2/metal/model.zig").Model; +const st = @import("../families/inkling2/metal/state.zig"); +const backend = @import("../families/inkling2/metal/backend.zig"); +const dspark = @import("../families/inkling2/metal/dspark.zig"); + +const Host = struct { + gpa: std.mem.Allocator, + io: std.Io, + model: *Model, + metal: *backend.Metal, + drafter: ?*dspark.Drafter = null, + drafted: ?lanes.drafted.Drafted = null, + warm: mtl.keepalive.Target, + clock: lanes.backend.WallClock, + config: lanes.Config = undefined, + core: lanes.Engine, + host: api.LaneHost, + cache: ?api.prompt_cache.Store = null, + cache_cap: u64 = 0, + + fn close(ctx: *anyopaque) void { + const h: *Host = @ptrCast(@alignCast(ctx)); + h.host.stop(); + if (h.cache) |*store| store.deinit(); + h.core.deinit(); + h.config.deinit(h.gpa); + if (h.drafted) |*d| d.deinit(); + if (h.drafter) |d| d.deinit(); + h.metal.deinit(); + h.model.deinit(); + h.gpa.destroy(h); + } +}; + +pub fn refusal(o: api.Open) ?[]const u8 { + if (o.vision != null or o.cfg_enabled or o.cfg_batched) return "inkling2_loop: this Metal engine serves text only; images and audio are unsupported"; + if (o.loops != null) return "inkling2_loop: the model has exactly three core passes; --loops cannot override them"; + if (o.mtp_drafts != null or o.mtp_confidence != null) return "inkling2_loop: use --drafter for the checkpoint's DSpark head; external draft controls remain unsupported"; + if (o.precision != null) return "inkling2_loop: the checkpoint's NVFP4, MXFP8 and BF16 arithmetic is fixed; serve without --precision"; + if (o.speed_up != null) return "inkling2_loop: this Metal engine serves one Mac; --speed-up is unsupported"; + if (o.learn != null or o.learn_conversations) return "inkling2_loop: learned disk states are not implemented; serve without --learn and --learn-conversations"; + if (o.prompt_cache_gib) |g| if (!std.math.isFinite(g) or g < 0 or g > 1024 * 1024) return "inkling2_loop: --prompt-cache-gib must be a finite, nonnegative budget"; + return null; +} + +fn drafterDirectory(o: api.Open) ?[]const u8 { + return if (o.drafts) o.drafter else null; +} + +fn contextProblem(window: i64, fits: usize) ?[]const u8 { + if (window < 1) return "inkling2_loop: --context must be at least one token, and the selected context must fit the Metal state budget"; + if (window > fits) return "inkling2_loop: --context exceeds the largest window this Mac can afford beside the checkpoint and DSpark state"; + return null; +} + +pub fn open(a: std.mem.Allocator, gpa: std.mem.Allocator, io: std.Io, o: api.Open, problem: *[]const u8) !?api.Opened { + if (refusal(o)) |why| { + problem.* = why; + return null; + } + if (try o.slideRefusal(a, "Macs")) |why| { + problem.* = why; + return null; + } + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const model = Model.load(gpa, io, o.dir) catch |err| { + problem.* = try std.fmt.allocPrint(a, "the native Inkling 2 Mini engine cannot load this checkpoint ({s})", .{@errorName(err)}); + return null; + }; + const drafter_dir = drafterDirectory(o); + errdefer model.deinit(); + const drafter = if (drafter_dir) |dir| dspark.Drafter.init(gpa, io, model.device, model, dir) catch |err| { + problem.* = try std.fmt.allocPrint(a, "--drafter: Inkling 2 Mini DSpark cannot load {s} ({s})", .{ dir, @errorName(err) }); + model.deinit(); + return null; + } else null; + errdefer if (drafter) |d| d.deinit(); + var ram: u64 = 0; + if (@import("builtin").os.tag.isDarwin()) { + var len: usize = @sizeOf(u64); + if (std.c.sysctlbyname("hw.memsize", &ram, &len, null, 0) != 0) ram = 0; + } + const scratch: u64 = st.scratchBytes(st.batch_rows) + st.scratchBytes(st.prompt_rows); + const resident = model.checkpoint.residentBytes() + scratch + if (drafter) |d| d.fixedBytes() + dspark.Drafter.scoreBytes(0) else 0; + const budget = cacheBudget(ram, model.device.maxWorkingSet(), @import("sys").getenv("INKLING2_LOAD_LIMIT_GB"), resident) catch { + if (drafter) |d| d.deinit(); + model.deinit(); + problem.* = "INKLING2_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 streams: u64 = @max(o.lanes, 1); + const draft_fixed = if (drafter != null) dspark.Drafter.streamBytes(0) + 127 * (dspark.Drafter.streamBytes(1) - dspark.Drafter.streamBytes(0)) else 0; + const draft_token = if (drafter) |_| dspark.Drafter.streamBytes(1) - dspark.Drafter.streamBytes(0) else 0; + const draft_shared_token = if (drafter) |_| dspark.Drafter.scoreBytes(1) - dspark.Drafter.scoreBytes(0) else 0; + const fits = longest(budget, model.config.text.max_context, streams, draft_fixed, draft_token, draft_shared_token); + const window: i64 = o.context orelse @intCast(fits); + if (contextProblem(window, fits)) |why| { + if (drafter) |d| d.deinit(); + model.deinit(); + problem.* = why; + return null; + } + std.log.info("inkling2_loop: {d:.1} GiB for stream and prompt state, 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.drafter = drafter; + const reserved = if (drafter != null) streams * dspark.Drafter.streamBytes(@intCast(window)) + dspark.Drafter.scoreBytes(@intCast(window)) - dspark.Drafter.scoreBytes(0) else 0; + if (reserved > budget) return error.DSparkReservationExceeded; + h.metal = try backend.Metal.init(gpa, model, .{ .capacity = @intCast(window), .streams = @max(o.lanes, 1), .budget = budget - reserved }); + errdefer h.metal.deinit(); + try h.metal.warm(); + h.drafted = null; + h.warm = .{ .queue = model.queue }; + if (drafter) |d| { + try d.setContext(@intCast(window)); + h.drafted = try lanes.drafted.Drafted.init(gpa, h.metal.backend(), d.drafter()); + h.drafted.?.first_rows = true; + } + errdefer if (h.drafted) |*d| d.deinit(); + const facts = if (h.drafted) |*d| d.facts(h.metal.facts()) else h.metal.facts(); + h.config = try lanes.Config.init(gpa, facts, st.window_rows, st.window_rows - 1); + errdefer h.config.deinit(gpa); + h.clock = .{ .io = io }; + h.core = lanes.Engine.init(gpa, &h.config, if (h.drafted) |*d| d.backend() else h.metal.backend(), h.clock.clock()); + errdefer h.core.deinit(); + h.host = api.LaneHost.init(gpa, io, &h.core, .{ .lanes = o.lanes, .context_window = @intCast(window), .prefill_step = st.prompt_rows, .decode_share = o.decode_share, .structures = true, .logprobs = true, .draft_sources = .{ .drafter = if (drafter_dir) |dir| .{ .kind = "DSpark", .name = o.drafter_name orelse dir } else null } }); + 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 = backend.Metal; + const rules: api.prompt_cache.Rules = .{ .lookahead = 0, .planned = true, .grid = st.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(); + 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 }; +} + +fn cacheBudget(ram: u64, working_set: u64, text: ?[]const u8, resident: u64) error{BadLoadLimit}!u64 { + var limit: u64 = @intFromFloat(@as(f64, @floatFromInt(ram)) * 0.75); + const value = std.mem.trim(u8, text orelse "", " \t"); + if (value.len > 0) { + const gb = std.fmt.parseFloat(f64, value) catch return error.BadLoadLimit; + if (!std.math.isFinite(gb) or gb <= 0) return error.BadLoadLimit; + const cap = @min(ram, working_set); + const bytes = gb * 1e9; + limit = if (bytes >= @as(f64, @floatFromInt(cap))) cap else @intFromFloat(bytes); + } + const margin: u64 = 2 << 30; + return if (limit > resident + margin) limit - resident - margin else 0; +} + +fn longest(bytes: u64, most: u32, streams: u64, draft_fixed: u64, draft_token: u64, draft_shared_token: u64) usize { + const one: u64 = st.cacheBytes(1) + streams * (draft_fixed + draft_token) + draft_shared_token; + if (one > bytes) return 0; + var lo: usize = 1; + var hi: usize = most; + while (lo < hi) { + const mid = lo + (hi - lo + 1) / 2; + const need = st.cacheBytes(mid) + streams * (draft_fixed + draft_token * @as(u64, @intCast(mid))) + draft_shared_token * @as(u64, @intCast(mid)); + if (need <= bytes) lo = mid else hi = mid - 1; + } + return lo; +} + +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 }); +} + +test "Inkling native admission keeps DSpark opt-in and refuses learned modes" { + var o: api.Open = .{ .dir = "checkpoint", .model_type = "inkling2_loop" }; + try std.testing.expect(refusal(o) == null); + try std.testing.expect(drafterDirectory(o) == null); + o.drafter = "checkpoint"; + try std.testing.expectEqualStrings("checkpoint", drafterDirectory(o).?); + o.drafts = false; + try std.testing.expect(drafterDirectory(o) == null); + o.speed_up = "distributed"; + try std.testing.expect(refusal(o) != null); + o.speed_up = null; + o.learn = "learned"; + try std.testing.expect(refusal(o) != null); + try std.testing.expect(contextProblem(0, 10) != null); + try std.testing.expect(contextProblem(-1, 10) != null); + try std.testing.expect(contextProblem(11, 10) != null); + try std.testing.expect(contextProblem(10, 10) == null); +} + +test "Inkling native open publishes the exact admission refusal" { + var problem: []const u8 = "not published"; + const o: api.Open = .{ .dir = "unused", .model_type = "inkling2_loop", .learn_conversations = true }; + try std.testing.expect((try open(std.testing.allocator, std.testing.allocator, std.testing.io, o, &problem)) == null); + try std.testing.expectEqualStrings("inkling2_loop: learned disk states are not implemented; serve without --learn and --learn-conversations", problem); +} + +test "Inkling native open releases DSpark when the later context admission refuses (TF_INKLING2_METAL_DIR, TF_INKLING2_DSPARK_DIR)" { + const dir = @import("sys").getenv("TF_INKLING2_METAL_DIR") orelse return error.SkipZigTest; + const drafter_dir = @import("sys").getenv("TF_INKLING2_DSPARK_DIR") orelse return error.SkipZigTest; + var problem: []const u8 = "not published"; + var o: api.Open = .{ .dir = dir, .model_type = "inkling2_loop", .context = 0, .drafter = drafter_dir }; + try std.testing.expect((try open(std.testing.allocator, std.testing.allocator, std.testing.io, o, &problem)) == null); + try std.testing.expectEqualStrings("inkling2_loop: --context must be at least one token, and the selected context must fit the Metal state budget", problem); + o.context = std.math.maxInt(i64); + problem = "not published"; + try std.testing.expect((try open(std.testing.allocator, std.testing.allocator, std.testing.io, o, &problem)) == null); + try std.testing.expectEqualStrings("inkling2_loop: --context exceeds the largest window this Mac can afford beside the checkpoint and DSpark state", problem); + // Null skips errdefer; omitting explicit deinit leaks allocations caught by std.testing.allocator. +} + +test "Inkling native open unwinds DSpark when the later Host allocation fails (TF_INKLING2_METAL_DIR, TF_INKLING2_DSPARK_DIR)" { + const Fault = struct { + drafter_allocated: bool = false, + host_failed: bool = false, + + fn allocator(f: *@This()) std.mem.Allocator { + return .{ .ptr = f, .vtable = &.{ .alloc = alloc, .resize = resize, .remap = remap, .free = free } }; + } + fn alloc(ctx: *anyopaque, len: usize, alignment: std.mem.Alignment, ra: usize) ?[*]u8 { + const f: *@This() = @ptrCast(@alignCast(ctx)); + if (f.drafter_allocated and len == @sizeOf(Host)) { + f.host_failed = true; + return null; + } + const memory = std.testing.allocator.rawAlloc(len, alignment, ra) orelse return null; + if (len == @sizeOf(dspark.Drafter)) f.drafter_allocated = true; + return memory; + } + fn resize(_: *anyopaque, memory: []u8, alignment: std.mem.Alignment, len: usize, ra: usize) bool { + return std.testing.allocator.rawResize(memory, alignment, len, ra); + } + fn remap(_: *anyopaque, memory: []u8, alignment: std.mem.Alignment, len: usize, ra: usize) ?[*]u8 { + return std.testing.allocator.rawRemap(memory, alignment, len, ra); + } + fn free(_: *anyopaque, memory: []u8, alignment: std.mem.Alignment, ra: usize) void { + std.testing.allocator.rawFree(memory, alignment, ra); + } + }; + const dir = @import("sys").getenv("TF_INKLING2_METAL_DIR") orelse return error.SkipZigTest; + const drafter_dir = @import("sys").getenv("TF_INKLING2_DSPARK_DIR") orelse return error.SkipZigTest; + var fault: Fault = .{}; + var problem: []const u8 = ""; + const o: api.Open = .{ .dir = dir, .model_type = "inkling2_loop", .context = 1, .lanes = 1, .drafter = drafter_dir }; + try std.testing.expectError(error.OutOfMemory, open(std.testing.allocator, fault.allocator(), std.testing.io, o, &problem)); + try std.testing.expect(fault.drafter_allocated and fault.host_failed); + // Removing errdefer leaks DSpark and its weights in std.testing.allocator. +} + +test "Inkling native load limit clamps before integer conversion" { + const gib: u64 = 1 << 30; + try std.testing.expectEqual(8_000_000_000 - 5 * gib, try cacheBudget(16 * gib, 14 * gib, "8", 3 * gib)); + try std.testing.expectEqual(9 * gib, try cacheBudget(16 * gib, 14 * gib, "1e30", 3 * gib)); + try std.testing.expectEqual(0, try cacheBudget(4 * gib, 4 * gib, null, 3 * gib)); + for ([_][]const u8{ "0", "-1", "nan", "inf", "bad" }) |text| { + try std.testing.expectError(error.BadLoadLimit, cacheBudget(16 * gib, 14 * gib, text, 3 * gib)); + } +} + +test "Inkling native longest context accounts target, streams and shared draft scores" { + const budget = st.cacheBytes(7) + 2 * (11 + 7 * 13) + 7 * 17; + try std.testing.expectEqual(@as(usize, 7), longest(budget, 8, 2, 11, 13, 17)); + try std.testing.expectEqual(@as(usize, 0), longest(st.cacheBytes(1) - 1, 8, 1, 0, 0, 0)); + const per_token = dspark.Drafter.streamBytes(1) - dspark.Drafter.streamBytes(0); + const conservative = dspark.Drafter.streamBytes(0) + 127 * per_token + 129 * per_token; + try std.testing.expect(conservative >= dspark.Drafter.streamBytes(129)); +} diff --git a/zig/src/native/inkling2_capabilities_test.zig b/zig/src/native/inkling2_capabilities_test.zig new file mode 100644 index 00000000000..5dd1c0c1403 --- /dev/null +++ b/zig/src/native/inkling2_capabilities_test.zig @@ -0,0 +1,13 @@ +//! Inkling's checkpoint-format offer in the production native Metal registry. +const std = @import("std"); +const native_metal = @import("native_metal"); + +test "Metal capabilities: inkling2_loop serves the checkpoint's ModelOpt NVFP4 weights" { + var found = false; + for (native_metal.families) |family| if (std.mem.eql(u8, family.model_type, "inkling2_loop")) { + found = true; + try std.testing.expectEqual(@as(usize, 1), family.formats.len); + try std.testing.expectEqualStrings("modelopt-nvfp4", family.formats[0]); + }; + try std.testing.expect(found); +} diff --git a/zig/src/native/lfm2.zig b/zig/src/native/lfm2.zig index f4e4d4b41fb..052b9b91063 100644 --- a/zig/src/native/lfm2.zig +++ b/zig/src/native/lfm2.zig @@ -162,6 +162,13 @@ pub fn open(a: Allocator, gpa: Allocator, io: std.Io, o: api.Open, problem: *[]c e.* = .{ .gpa = gpa, .io = io, .window = window, .driver = undefined, .ctx = undefined, .cfg = undefined, .weights = undefined, .model = undefined }; e.cfg = try lfm2.config.Config.load(gpa, io, o.dir, problem) orelse return null; errdefer e.cfg.deinit(gpa); + // --vision against the config's vision_config (core's gate): without it the tower stays on disk + const tower = api.visionGate(o.vision != null, e.cfg.vision != null) catch |err| { + problem.* = api.visionWords("this LFM2 checkpoint", err).?; + e.cfg.deinit(gpa); + gpa.destroy(e); + return null; + }; e.driver = cuda.Driver.open() catch |err| { problem.* = try std.fmt.allocPrint(a, "no CUDA driver ({s})", .{@errorName(err)}); return null; @@ -170,7 +177,7 @@ pub fn open(a: Allocator, gpa: Allocator, io: std.Io, o: api.Open, problem: *[]c e.ctx = try cuda.Context.init(&e.driver, 0); errdefer e.ctx.deinit(); try e.ctx.makeCurrent(); - e.weights = try lfm2.weights.Weights.load(gpa, io, &e.driver, o.dir, &e.cfg); + e.weights = try lfm2.weights.Weights.load(gpa, io, &e.driver, o.dir, &e.cfg, tower); errdefer e.weights.deinit(gpa); e.model = try lfm2.model.Model.init(gpa, &e.driver, &e.cfg, &e.weights, window); errdefer e.model.deinit(); diff --git a/zig/src/native/lfm3.zig b/zig/src/native/lfm3.zig index 9c13198c767..9255b131ed7 100644 --- a/zig/src/native/lfm3.zig +++ b/zig/src/native/lfm3.zig @@ -41,6 +41,7 @@ fn cacheRules() api.prompt_cache.Rules { } pub fn open(a: std.mem.Allocator, gpa: std.mem.Allocator, io: std.Io, o: api.Open, problem: *[]const u8) !?api.Opened { + const warm_turns = try @import("sys").environment.read(bool, "TF_LFM3_METAL_WARM_TURNS", false); const pool = mtl.objc.Pool.push(); defer pool.pop(); var config = q.config.Config.read(gpa, io, o.dir) catch |err| { @@ -76,7 +77,8 @@ pub fn open(a: std.mem.Allocator, gpa: std.mem.Allocator, io: std.Io, o: api.Ope h.gpa = gpa; h.model = model; h.resident = null; - const chunk = prompt_chunk; + // Every prompt row, including decoded history, uses the one-row forward in warm mode. + const chunk: u32 = if (warm_turns) 1 else prompt_chunk; h.metal = try q.backend.Metal.init(gpa, model, .{ .capacity = window, .chunk = chunk, .streams = @max(o.lanes, 2) }); errdefer h.metal.deinit(); const per_stream = q.state.cacheBytes(&model.config.layer_types, window); @@ -92,7 +94,9 @@ pub fn open(a: std.mem.Allocator, gpa: std.mem.Allocator, io: std.Io, o: api.Ope h.clock = .{ .io = io }; h.core = lanes.Engine.init(gpa, &h.config, h.metal.backend(), h.clock.clock()); errdefer h.core.deinit(); - h.host = api.LaneHost.init(gpa, io, &h.core, .{ .name = "lfm3", .lanes = served, .context_window = @intCast(window), .prefill_step = chunk, .structures = true, .vision = null }); + h.host = api.LaneHost.init(gpa, io, &h.core, .{ .name = "lfm3", .lanes = served, .context_window = @intCast(window), .prefill_step = prompt_chunk, .structures = true, .vision = null }); + h.host.decoded_rows = warm_turns; + if (warm_turns) h.host.info_.prefill_min_chunk = 1; h.cache = null; var why: []const u8 = ""; const dev = model.device; @@ -110,12 +114,18 @@ pub fn open(a: std.mem.Allocator, gpa: std.mem.Allocator, io: std.Io, o: api.Ope h.host.info_.prompt_cache_plan = plan; if (plan.budget_bytes > 0) { const S = q.backend.Snaps; + const rules: api.prompt_cache.Rules = if (warm_turns) + .{ .chunk = 1, .min_prompt = 0, .warm = .waits } + else + cacheRules(); h.cache = api.prompt_cache.Store.init(gpa, .{ .ptr = h.metal, .vtable = &.{ .bytes = S.bytes, .save = S.save, .restore = S.restore, .drop = S.drop }, - }, cacheRules(), plan.budget_bytes); + }, rules, plan.budget_bytes); h.host.cache = &h.cache.?; h.host.info_.prompt_cache = true; + h.host.info_.warm_turns = warm_turns; + if (warm_turns) h.host.warm_quiet = 150 * std.time.ns_per_ms; } errdefer if (h.cache) |*store| store.deinit(); try mtl.resident.streams.hold(h, io, "lfm3"); diff --git a/zig/src/native/metal.zig b/zig/src/native/metal.zig index e63feaaddb9..73376a93bc5 100644 --- a/zig/src/native/metal.zig +++ b/zig/src/native/metal.zig @@ -62,6 +62,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 = "inkling2_loop", .formats = &.{"modelopt-nvfp4"} }, .{ .model_type = "minimax_m3_vl", .formats = &.{ "mlx-q3g64", "mlx-q8g64" } }, .{ .model_type = "hy_v4_flash", .formats = &.{ "mlx-q4g64", "mlx-q8g64" } }, .{ .model_type = "qwen3", .formats = &.{"bf16"} }, @@ -78,7 +79,6 @@ fn isGemma4(model_type: []const u8) bool { fn readMemory(_: ?*anyopaque, reset_peak: bool) ?api.Memory { return cache_fit.hostMemory(0, reset_peak); } - /// One loaded model behind the lane host: everything the engine thread reads lives here. const Host = struct { gpa: Allocator, @@ -125,7 +125,6 @@ const Host = struct { h.gpa.destroy(h); } }; - /// The engine for `o.dir`, or null with `problem` set when no Metal engine reads the checkpoint. pub fn open(a: Allocator, gpa: Allocator, io: std.Io, o: api.Open, problem: *[]const u8) !?api.Opened { const report = @import("sys").optional_libraries.atBoundary(); @@ -170,6 +169,7 @@ pub fn open(a: Allocator, gpa: Allocator, io: std.Io, o: api.Open, problem: *[]c 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, "inkling2_loop")) return @import("tensorfold").inkling2_native.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, "llama")) return @import("llama.zig").open(a, gpa, io, o, problem); if (std.mem.eql(u8, o.model_type, "flint")) return @import("flint.zig").open(a, gpa, io, o, problem); @@ -305,7 +305,7 @@ fn refusal(a: Allocator, o: api.Open, dense: bool) !?[]const u8 { if (o.prompt_int8) return prompt_int8_refusal; if (!learners.supports(t)) if (try o.slideRefusal(a, "Macs")) |why| return why; if (!std.mem.eql(u8, t, "qwen3_5_moe")) if (@import("qwen27_mtp.zig").refusal(o.mtp_drafts, o.mtp_confidence, o.drafter != null, std.mem.eql(u8, t, "qwen3_5") and dense)) |why| return why; - if (o.drafter != null and !dense and !isGemma4(t) and !std.mem.eql(u8, t, "llama") and !std.mem.eql(u8, t, "qwen3_5_moe") and !std.mem.eql(u8, t, "flint") and !std.mem.eql(u8, t, "glm5_next")) return "--drafter is supported for Qwen3.8-27B-class checkpoints (qwen3_5 with its own output head), Qwen3.5-MoE (qwen3_5_moe), GLM-5.3-Flash (glm5_next), Gemma 4 dense, Flint (DFlash2 on M5) and Llama (a smaller Llama on the same tokenizer)"; + if (o.drafter != null and !dense and !isGemma4(t) and !std.mem.eql(u8, t, "llama") and !std.mem.eql(u8, t, "qwen3_5_moe") and !std.mem.eql(u8, t, "flint") and !std.mem.eql(u8, t, "glm5_next") and !std.mem.eql(u8, t, "inkling2_loop")) return "--drafter is supported for Qwen3.8-27B-class checkpoints (qwen3_5 with its own output head), Qwen3.5-MoE (qwen3_5_moe), GLM-5.3-Flash (glm5_next), Gemma 4 dense, Flint (DFlash2 on M5), Inkling 2 Mini (DSpark) and Llama (a smaller Llama on the same tokenizer)"; const one_mac: ?[]const u8 = if (std.mem.eql(u8, t, "nemotron_h")) "Nemotron" else if (std.mem.eql(u8, t, "nemotron_h_puzzle")) "Nemotron 3.5 Bolt" else if (std.mem.eql(u8, t, "lfm2_moe")) "LFM2.5-24B-A2B" else if (isGemma4(t)) "Gemma 4" else if (std.mem.eql(u8, t, "step5_vl")) "Step-5" else if (std.mem.eql(u8, t, "spark2_5")) "Spark-X2.6" else if (std.mem.eql(u8, t, "minimax_m3_vl")) "MiniMax-M3.1-Flash" else if (std.mem.eql(u8, t, "qwen3_5_moe")) "Qwen3.5-MoE" else if (std.mem.eql(u8, t, "llama")) "Llama" else if (std.mem.eql(u8, t, "flint")) "Flint" else if (std.mem.eql(u8, t, "unlimited-ocr")) "Unlimited-OCR-2" else if (std.mem.eql(u8, t, "ricursive")) "Ripple" else if (!std.mem.eql(u8, t, "qwen3_5")) null else if (dense) "Qwen3.8-27B" else "Qwen3.5-2B"; if (o.speed_up != null) if (one_mac) |name| return try std.fmt.allocPrint(a, "--speed-up joins two Macs for Flash Next, GLM-5.3-Flash and GLM-5.3 only: serve {s} without it", .{name}); if (o.recall and std.mem.eql(u8, t, "qwen4_exp")) return recall_refusal; @@ -321,7 +321,7 @@ fn refusal(a: Allocator, o: api.Open, dense: bool) !?[]const u8 { /// Whether `dir` opens on the Qwen3.8-27B-class engine: the 27B-class qwen3_5 checkpoints, and Qwen3.5-MoE. fn ownsQwen27(a: Allocator, io: std.Io, t: []const u8, dir: []const u8) bool { - return (std.mem.eql(u8, t, "qwen3_5") and @import("qwen27_engine.zig").owns(a, io, dir)) or std.mem.eql(u8, t, "qwen3_5_moe"); + return (std.mem.eql(u8, t, "qwen3_5") and @import("qwen27_engine.zig").owns(a, io, dir, @import("sys").environment.read(bool, "TF_QWEN27_TIED_HEAD", false) catch false)) or std.mem.eql(u8, t, "qwen3_5_moe"); } /// The context a Qwen3.8-27B-class start serves (--context, else 32,768); null with `problem` set past 1 to 262,144. diff --git a/zig/src/native/minimax_m3.zig b/zig/src/native/minimax_m3.zig index ce2e2f535fa..edd3c0ce31a 100644 --- a/zig/src/native/minimax_m3.zig +++ b/zig/src/native/minimax_m3.zig @@ -113,6 +113,8 @@ pub fn open(a: std.mem.Allocator, gpa: std.mem.Allocator, io: std.Io, o: api.Ope 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()); + } else if (h.metal.facts().copy_drafts) { + try h.metal.measure(); // the lanes' own copy drafts are priced against the same rounds, with no drafter too } errdefer if (h.wrap) |*w| w.deinit(); errdefer if (h.draft) |d| d.deinit(); diff --git a/zig/src/native/qwen27_costs.zig b/zig/src/native/qwen27_costs.zig index 2be76738187..0ac1794d9a7 100644 --- a/zig/src/native/qwen27_costs.zig +++ b/zig/src/native/qwen27_costs.zig @@ -4,26 +4,56 @@ const mtl = @import("metal"); const q = @import("tensorfold").qwen27; const lanes = @import("tensorfold").lanes; const be = lanes.backend; +const warm = lanes.cost_rule.warm_prices; +const Phase = struct { + key: ?[32]u8 = null, + turn: warm.Turn = .{}, + + fn retryNarrow(phase: Phase) bool { + return phase.turn.preferredShared() and !phase.turn.attempted; + } +}; +const Probe = struct { + start_turn: bool = false, + from: usize = 0, + floor: f64 = 0, + seed: ?lanes.cost_cache.KeySeed = null, + phase: ?*Phase = null, +}; + pub fn measure(b: anytype, io: std.Io) !void { + const has_shared = b.tensor_units and b.runner.slots > 1 and + ((b.window < 64 and b.runner.capacity > 64) or (b.window < 32 and b.runner.capacity > 32)); + var phase: Phase = .{}; + const seed = lanes.cost_cache.keySeed(b.gpa, io, false) catch null; + const probe: Probe = .{ .start_turn = has_shared, .seed = seed, .phase = &phase }; + defer if (phase.key) |key| lanes.cost_cache.save(u64, b.gpa, io, key, phase.turn.next()); + try narrow(b, io, probe); + if (!has_shared) return; + if (b.window < 64 and b.runner.capacity > 64) try shared(b, io, 64, seed, &phase) else try shared(b, io, 32, seed, &phase); + if (phase.retryNarrow()) { + const timed = b.timed; + defer b.timed = timed; + try narrow(b, io, .{ .seed = seed, .phase = &phase }); + } +} + +fn narrow(b: anytype, io: std.Io, probe: Probe) !void { switch (b.window) { - 16 => try sized(b, io, 16, "qwen27-lanes"), - 32 => try sized(b, io, 32, "qwen27-lanes"), - 64 => try sized(b, io, 64, "qwen27-lanes"), + 16 => try sized(b, io, 16, "qwen27-lanes", probe), + 32 => try sized(b, io, 32, "qwen27-lanes", probe), + 64 => try sized(b, io, 64, "qwen27-lanes", probe), else => return error.WindowTooWide, } - if (!b.tensor_units or b.runner.slots == 1) return; - if (b.window < 64 and b.runner.capacity > 64) return shared(b, io, 64); - if (b.window < 32 and b.runner.capacity > 32) return shared(b, io, 32); } /// Price wider unfused forwards without taking another stream's caches or changing the lone window's prices. -fn shared(b: anytype, io: std.Io, comptime width: usize) !void { +fn shared(b: anytype, io: std.Io, comptime width: usize, seed: ?lanes.cost_cache.KeySeed, phase: *Phase) !void { const window = b.window; const draft = b.draft; const profile = b.pass_profile; const costs = b.costs; const timed = b.timed; - if (draft) |d| try d.generation.settle(); b.window = width; b.draft = null; b.pass_profile = false; @@ -32,43 +62,86 @@ fn shared(b: anytype, io: std.Io, comptime width: usize) !void { b.draft = draft; b.pass_profile = profile; @memcpy(b.costs[0..window], costs[0..window]); - if (draft) |d| d.reset() catch {}; } errdefer { b.costs = costs; b.timed = timed; } - try sized(b, io, width, "qwen27-shared-rows"); + try sized(b, io, width, "qwen27-shared-rows", .{ .from = window, .floor = sharedFloor(costs[0..window]), .seed = seed, .phase = phase }); +} + +fn sharedFloor(costs: []const lanes.config.Cost) f64 { + var floor: f64 = 0; + for (costs) |cost| floor = @max(floor, cost.ms); + return floor; } -fn sized(b: anytype, io: std.Io, comptime width: usize, kind: []const u8) !void { +fn sized(b: anytype, io: std.Io, comptime width: usize, kind: []const u8, probe: Probe) !void { const r = b.runner; if (b.owners[0] != null or r.active != null) return error.StreamBusy; var shape: [128]u8 = undefined; const parts = [_][]const u8{ kind, std.mem.span(r.model.device.name()), try q.widths.costShape(r.model.config, r.model.widths_tag, &shape, width, r.capture_taps) }; - const k = lanes.cost_cache.key(b.gpa, io, &parts) catch null; - if (k) |key| if (lanes.cost_cache.load([width]lanes.config.Cost, b.gpa, io, key)) |kept| { - @memcpy(b.costs[0..width], &kept); - b.timed = width; - return; + const k = if (probe.seed) |seed| seed.key(&parts) else null; + var kept = if (k) |key| lanes.cost_cache.load([width]lanes.config.Cost, b.gpa, io, key) else null; + if (kept) |table| for (table, 0..) |c, i| { + if (c.width != i + 1 or !(c.ms > 0) or !std.math.isFinite(c.ms)) { + kept = null; + break; + } }; - if (r.capacity <= width) return error.ContextFull; - defer { - if (b.draft) |d| d.reset() catch {} else r.reset(0) catch {}; + var probe_now = if (probe.phase) |phase| !phase.turn.attempted else true; + if (kept != null and probe.start_turn) { + const current = k orelse unreachable; + const phase_key = lanes.cost_cache.buildKey(¤t, &.{"metal-family-phase-v1"}); + const turn: warm.Turn = .{ .value = lanes.cost_cache.load(u64, b.gpa, io, phase_key) orelse 0 }; + probe_now = !turn.preferredShared(); + if (probe.phase) |p| { + p.key = phase_key; + p.turn = turn; + } + } + if (kept) |table| { + @memcpy(b.costs[0..width], &table); + b.timed = width; + if (!probe_now or r.capacity <= width) return; } + if (r.capacity <= width) return error.ContextFull; + var ms: [width]f64 = undefined; + var widths: [width]u32 = undefined; + if (kept) |table| for (table, &ms, &widths) |c, *m, *w| { + m.* = c.ms; + w.* = c.width; + }; + const cursor_key = if (k) |key| lanes.cost_cache.buildKey(&key, &.{"metal-heal-v2"}) else null; + var cursor = if (cursor_key) |key| lanes.cost_cache.load(u64, b.gpa, io, key) orelse 0 else 0; + const before = cursor; + defer if (cursor != before) if (cursor_key) |key| lanes.cost_cache.save(u64, b.gpa, io, key, cursor); + if (kept != null and !warm.admit(ms[probe.from..], widths[probe.from..], &cursor)) return; + if (probe.phase) |phase| phase.turn.attempted = true; var ids: [192]u32 = undefined; for (&ids, 0..) |*t, i| t.* = @intCast((i * 7919 + 13) % r.model.config.vocab); - const prompt = ids[0..@min(ids.len, r.capacity - width)]; // a small --context still holds a window past it - try b.refill(prompt); - var s = try lanes.Stream.init(b.gpa, .{ .id = "timing", .prompt = prompt, .max_new = 1 }); + const prompt = ids[0..lanes.cost_rule.context.promptRows(r.capacity, width, width + 5)]; + var s = lanes.Stream.init(b.gpa, .{ .id = "timing", .prompt = prompt, .max_new = 1 }) catch |err| { + if (kept != null) return; + return err; + }; defer s.deinit(b.gpa); const timer: Timer(@TypeOf(b)) = .{ .b = b, .s = &s, .prompt = prompt }; + if (kept != null) { + var warm_timer: WarmTimer(@TypeOf(b)) = .{ .timer = timer }; + warm_timer.timer.from = probe.from; + const stats = (try warmProbe(b, &warm_timer, ms[probe.from..], widths[probe.from..], &cursor, probe.floor)) orelse return; + for (b.costs[0..width], ms, 0..) |*c, m, i| c.* = .{ .width = @intCast(i + 1), .ms = m }; + b.timed = width; + if (stats.lowered > 0) if (k) |key| lanes.cost_cache.save([width]lanes.config.Cost, b.gpa, io, key, b.costs[0..width].*); + return; + } + try b.refill(prompt); for (0..5) |_| _ = try timer.time(width - 1); // the widest window first, while the GPU's clocks ramp up - var ms: [width]f64 = undefined; - for (&ms, 0..) |*m, i| m.* = try lanes.cost_rule.fastest(timer, i); - try lanes.cost_rule.smooth(timer, &ms); + try lanes.cost_rule.serialWindows(timer, &ms); const ref = lanes.cost_cache.referenceKey(&parts); if (lanes.cost_cache.load([width]f64, b.gpa, io, ref)) |reference| if (lanes.cost_rule.drifted(&ms, &reference)) try lanes.cost_rule.again(timer, &ms); + try resetProbe(b); for (b.costs[0..width], ms, 0..) |*cost, m, i| cost.* = .{ .width = @intCast(i + 1), .ms = m }; b.timed = width; if (k) |key| lanes.cost_cache.save([width]lanes.config.Cost, b.gpa, io, key, b.costs[0..width].*); @@ -81,9 +154,11 @@ fn Timer(comptime B: type) type { b: B, s: *lanes.Stream, prompt: []const u32, + from: usize = 0, pub fn time(t: @This(), i: usize) !f64 { - if (t.b.runner.offsets[0] + i + 1 > t.b.runner.capacity) try t.b.refill(t.prompt); - return timeWindow(t.b, t.s, i + 1); + const rows = t.from + i + 1; + if (t.b.runner.offsets[0] + rows > t.b.runner.capacity) try t.b.refill(t.prompt); + return timeWindow(t.b, t.s, rows); } }; } @@ -101,5 +176,162 @@ fn timeWindow(b: anytype, s: *lanes.Stream, rows: usize) !f64 { try b.backend().verify(&.{w}, &out); var path = [_]u32{0}; try b.backend().keep(&.{w}, &.{&path}); + try b.settle(); return (mtl.clock.seconds() - t0) * 1e3; } + +fn WarmTimer(comptime B: type) type { + return struct { + timer: Timer(B), + began: f64 = 0, + pub fn start(t: *@This()) void { + t.began = mtl.clock.seconds(); + } + pub fn elapsedMs(t: *@This()) f64 { + return (mtl.clock.seconds() - t.began) * 1e3; + } + pub fn prepare(t: *@This(), _: anytype, _: []const u32) !void { + try t.timer.b.refill(t.timer.prompt); + } + pub fn time(t: *@This(), i: usize) !f64 { + return t.timer.time(i); + } + }; +} + +fn resetProbe(b: anytype) !void { + if (b.draft) |d| try d.reset() else try b.runner.reset(0); +} + +fn warmProbe(b: anytype, timer: anytype, ms: []f64, widths: []const u32, cursor: *u64, floor: f64) !?warm.Stats { + const stats: ?warm.Stats = warm.prepared(timer, ms, widths, cursor, floor, warm.Local{}, true) catch blk: { + b.dropRound(); + b.runner.recover(); + if (b.draft) |d| try d.model.recover(); + break :blk null; + }; + try resetProbe(b); + return stats; +} + +const ProbeRunner = struct { + active: ?usize = null, + failed: bool = false, + resets: usize = 0, + + pub fn recover(r: *@This()) void { + r.active = null; + r.failed = false; + } + + pub fn reset(r: *@This(), slot: usize) !void { + try std.testing.expectEqual(@as(usize, 0), slot); + if (r.active != null or r.failed) return error.RoundNotReady; + r.resets += 1; + } +}; + +const ProbeBackend = struct { + const Model = struct { + failed: bool = false, + recover_error: bool = false, + + pub fn recover(m: *@This()) !void { + if (m.recover_error) return error.DraftRecoveryFailed; + m.failed = false; + } + }; + const Draft = struct { + runner: *ProbeRunner, + model: Model = .{}, + reset_error: bool = false, + + pub fn reset(d: *@This()) !void { + if (d.reset_error or d.model.failed) return error.DraftResetFailed; + try d.runner.reset(0); + } + }; + runner: *ProbeRunner, + draft: ?*Draft = null, + round: bool = false, + + pub fn dropRound(b: *@This()) void { + b.round = false; + } +}; + +test "qwen27 startup: shared probe uses the maximum live narrow cost" { + const Fake = struct { + pub fn time(_: @This(), _: usize) !f64 { + return 19.9; + } + }; + const costs = [_]lanes.config.Cost{ .{ .width = 1, .ms = 20 }, .{ .width = 2, .ms = 19.8 } }; + var ms = [_]f64{21}; + var cursor: u64 = 0; + var runner: ProbeRunner = .{}; + var b: ProbeBackend = .{ .runner = &runner }; + _ = (try warmProbe(&b, Fake{}, &ms, &.{3}, &cursor, sharedFloor(&costs))).?; + try std.testing.expectEqual(@as(f64, 21), ms[0]); +} + +test "qwen27 startup: recover a failed verify or keep before retaining cached prices" { + const Fault = struct { + b: *ProbeBackend, + keep: bool, + + pub fn time(f: @This(), _: usize) !f64 { + f.b.runner.active = 0; + f.b.runner.failed = f.keep; + if (f.keep) { + f.b.round = true; + f.b.draft.?.model.failed = true; + return error.KeepGpuFailure; + } + return error.DrawGpuFailure; + } + }; + var runner: ProbeRunner = .{}; + var draft: ProbeBackend.Draft = .{ .runner = &runner }; + var b: ProbeBackend = .{ .runner = &runner }; + var ms = [_]f64{21}; + var cursor: u64 = 0; + try std.testing.expect((try warmProbe(&b, Fault{ .b = &b, .keep = false }, &ms, &.{1}, &cursor, 0)) == null); + b.draft = &draft; + const keep: Fault = .{ .b = &b, .keep = true }; + try std.testing.expect((try warmProbe(&b, keep, &ms, &.{1}, &cursor, 0)) == null); + try std.testing.expect(runner.active == null and !runner.failed and !b.round and !draft.model.failed); + try std.testing.expectEqual(@as(usize, 2), runner.resets); + try std.testing.expectEqual(@as(f64, 21), ms[0]); + draft.model.recover_error = true; + try std.testing.expectError(error.DraftRecoveryFailed, warmProbe(&b, keep, &ms, &.{1}, &cursor, 0)); + draft.model.recover_error = false; + draft.reset_error = true; + try std.testing.expectError(error.DraftResetFailed, warmProbe(&b, keep, &ms, &.{1}, &cursor, 0)); + try std.testing.expectEqual(@as(usize, 2), runner.resets); +} + +test "qwen27 startup: no-fit shared turns still probe narrow on the same load" { + const Fake = struct { + pub fn time(_: @This(), _: usize) !f64 { + return 80; + } + }; + var narrow_ms = [_]f64{80}; + var shared_cursor: u64 = 0; + var narrow_cursor: u64 = 0; + var saved: u64 = 0; + var runner: ProbeRunner = .{}; + var b: ProbeBackend = .{ .runner = &runner }; + for (1..7) |load| { + var phase: Phase = .{ .turn = .{ .value = saved } }; + if (phase.turn.preferredShared()) phase.turn.attempted = warm.admit(&.{200}, &.{64}, &shared_cursor); + if (!phase.turn.preferredShared() or phase.retryNarrow()) { + const stats = (try warmProbe(&b, Fake{}, &narrow_ms, &.{16}, &narrow_cursor, 0)).?; + try std.testing.expectEqual(@as(u32, 1), stats.reads); + } + saved = phase.turn.next(); + try std.testing.expectEqual(@as(u64, load), narrow_cursor); + } + try std.testing.expectEqual(@as(u64, 0), shared_cursor); +} diff --git a/zig/src/native/qwen27_draft.zig b/zig/src/native/qwen27_draft.zig index a030c8995bd..a92f7ef3f1b 100644 --- a/zig/src/native/qwen27_draft.zig +++ b/zig/src/native/qwen27_draft.zig @@ -70,6 +70,7 @@ pub const Draft = struct { defer pool.pop(); d.generation.deinit(); d.runner.capture_taps = d.previous_capture; + d.runner.taps.setFuser(d.runner.model.device, null) catch unreachable; // dropping a fuser allocates nothing d.runner.taps.ids = d.previous_taps; d.runner.taps.count = d.previous_count; d.model.backend.profile(null); // a borrowed drafter outlives the host and its trace diff --git a/zig/src/native/qwen27_engine.zig b/zig/src/native/qwen27_engine.zig index fa36da1c76a..74f4e09f519 100644 --- a/zig/src/native/qwen27_engine.zig +++ b/zig/src/native/qwen27_engine.zig @@ -3,18 +3,19 @@ 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 { +/// The 27B engine, unless the checkpoint has the pinned 2B's hidden size, or a tied head with `tied_on` false. +pub fn owns(a: Allocator, io: std.Io, dir: []const u8, tied_on: bool) 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; + var tied = false; 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("tie_word_embeddings")) |v| tied = tied or (v == .bool and v.bool); if (o.object.get("hidden_size")) |v| if (v == .integer and v.integer == tf.qwen35.config.hidden) return false; } - return true; + return !tied or tied_on; } test "a qwen3_5 checkpoint opens the 27B engine unless it has the 2B's geometry or a tied head" { @@ -25,7 +26,7 @@ test "a qwen3_5 checkpoint opens the 27B engine unless it has the 2B's geometry 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 + try std.testing.expect(owns(a, io, dir, false)); // 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 }, @@ -36,6 +37,11 @@ test "a qwen3_5 checkpoint opens the 27B engine unless it has the 2B's geometry }; 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)); + try std.testing.expectEqual(c.big, owns(a, io, dir, false)); } + // the switch moves a tied head of another size to the 27B engine; the 2B's hidden size stays with the 2B + try tmp.dir.writeFile(io, .{ .sub_path = "config.json", .data = "{\"model_type\":\"qwen3_5\",\"text_config\":{\"tie_word_embeddings\":true,\"hidden_size\":4096}}" }); + try std.testing.expect(owns(a, io, dir, true)); + try tmp.dir.writeFile(io, .{ .sub_path = "config.json", .data = "{\"model_type\":\"qwen3_5\",\"text_config\":{\"tie_word_embeddings\":true,\"hidden_size\":2048}}" }); + try std.testing.expect(!owns(a, io, dir, true)); } diff --git a/zig/src/native/qwen27_images.zig b/zig/src/native/qwen27_images.zig index 443c0f46e0c..c42c04b20de 100644 --- a/zig/src/native/qwen27_images.zig +++ b/zig/src/native/qwen27_images.zig @@ -44,6 +44,10 @@ pub const Vision = struct { /// The checkpoint's tower for `model`'s width under its rope, for `o.image_tokens` image tokens a request. pub fn open(gpa: Allocator, io: std.Io, model: *const q.model.Model, dir: []const u8, o: api.VisionOpen, a: Allocator, why: *[]const u8) !*Vision { + if (q.model.a3b(model.config)) { + why.* = "--vision: Qwen3.6-35B-A3B is served as text only; its image path is not qualified"; + return error.VisionUnqualified; + } const read = struct { fn f(al: Allocator, i: std.Io, d: []const u8, name: []const u8) ?[]const u8 { const path = std.fs.path.join(al, &.{ d, name }) catch return null; diff --git a/zig/src/native/qwen27_keep.zig b/zig/src/native/qwen27_keep.zig index 75adc3ddb8a..005f6c1a647 100644 --- a/zig/src/native/qwen27_keep.zig +++ b/zig/src/native/qwen27_keep.zig @@ -42,7 +42,8 @@ const Commit = struct { const e = cb.compute(.concurrent); var ended = false; errdefer if (!ended) e.end(); - try g.commit.taps(e, ref, .{ .buf = r.taps.buffer }, .{ .buf = g.taps }, .{ .rows = rows, .width = r.taps.width, .capacity = r.taps.capacity, .planes = @intCast(r.taps.count) }); + const src = r.taps.source(); + try g.commit.taps(e, ref, .{ .buf = src.buffer }, .{ .buf = g.taps }, .{ .rows = rows, .width = src.width, .capacity = r.taps.capacity, .planes = src.planes }); try g.commit.head(e, ref, .{ .buf = logits.buffer, .off = logits.offset }, .{ .rows = rows, .width = vocab, .stride = vocab }); e.end(); ended = true; @@ -97,7 +98,8 @@ pub fn encodeTail(ptr: *anyopaque, e: mtl.ComputeEncoder) !void { const shape = try g.matcher.encode(e, .{ .buf = logits.buffer, .off = logits.offset }, b.round.?.ids, b.round.?.windows[0].parents, vocab, contract.max_rows, &.{}); const ref = tf.tree_commit_gpu.Ref{ .buf = g.matcher.buffers[4] }; try r.taps.complete(); - try g.commit.taps(e, ref, .{ .buf = r.taps.buffer }, .{ .buf = g.taps }, .{ .rows = shape.rows, .width = r.taps.width, .capacity = r.taps.capacity, .planes = @intCast(r.taps.count) }); + const src = r.taps.source(); + try g.commit.taps(e, ref, .{ .buf = src.buffer }, .{ .buf = g.taps }, .{ .rows = shape.rows, .width = src.width, .capacity = r.taps.capacity, .planes = src.planes }); const metric = mtl.pass_metrics.phase(.keep); defer metric.end(); std.debug.assert(b.prepared_keep == null); diff --git a/zig/src/native/qwen27_lanes.zig b/zig/src/native/qwen27_lanes.zig index 20456418f79..6582104310a 100644 --- a/zig/src/native/qwen27_lanes.zig +++ b/zig/src/native/qwen27_lanes.zig @@ -99,6 +99,7 @@ pub const Metal = struct { standing: @import("qwen27_resume.zig").Standing = .{}, // what slot 0 stands at once its stream left (#1197) rewind: ?mtl.Buffer = null, // slot 0's DeltaNet states and taps at its last pass's history end slot_resume: bool = true, // TF_QWEN27_SLOT_RESUME: a later prompt resumes where slot 0 stands (0: off) + give_back: [max_streams]bool = @splat(false), // a free slot's grown K/V and ring wait to go back (slots.giveBack) draft_block: @import("qwen27_draft_block.zig").Lone = .{}, // TF_Q27_DFLASH_ADAPTIVE_BLOCK: a lone stream's block rows pub fn init(gpa: std.mem.Allocator, runner: *q.decode_round.Runner, draft: ?*Draft) !*Metal { @@ -127,7 +128,10 @@ pub const Metal = struct { if (draft) |d| { const g = d.model.ring(); b.gathered_taps = try device.buffer(batch_rows * g.stride, opts); - for (b.contexts[1..runner.ready], 1..) |*x, slot| x.* = try Context.init(gpa, d.model, slot < b.draft_slots); + for (b.contexts[1..runner.ready], 1..) |*x, slot| { + x.* = try Context.initGrow(gpa, d.model, slot < b.draft_slots, runner.kv_step); + x.*.?.settle = .{ .ctx = runner, .slot = @intCast(slot), .run = q.decode_round.Runner.settleOpaque }; + } } return b; } @@ -359,11 +363,12 @@ pub const Metal = struct { std.debug.assert(r.active == null); if (r.active != null) return error.RoundNotReady; try r.taps.complete(); - try q.tap_gather.gather(r.taps.buffer.contents()[0..r.taps.buffer.length()], r.taps.capacity, r.taps.rows, r.taps.width, r.taps.count, rows[0..n], out.contents()[0..out.length()]); + const src = r.taps.source(); + try q.tap_gather.gather(src.buffer.contents()[0..src.buffer.length()], r.taps.capacity, r.taps.rows, src.width, src.planes, rows[0..n], out.contents()[0..out.length()]); var at: usize = 0; for (paths, b.windows[0..b.count]) |path, slot| { const g = b.ringOf(slot).?; - if (g.stride != r.taps.width * r.taps.count * 2) return error.BadTapGather; + if (g.stride != @as(usize, src.width) * src.planes * 2) return error.BadTapGather; // a v1 ring: one fused plane if (b.early[slot] == 0) { try g.absorb(out, at * g.stride, @intCast(path.len)); at += path.len; diff --git a/zig/src/native/qwen27_mtp.zig b/zig/src/native/qwen27_mtp.zig index cf07e599a21..1426def0000 100644 --- a/zig/src/native/qwen27_mtp.zig +++ b/zig/src/native/qwen27_mtp.zig @@ -17,6 +17,77 @@ pub const refusal = flags.refusal; const logit_rows = 32; /// Hazard-tracked: a pass's staged rows and each stream's saved row move between blits and kernels. const opts = mtl.ResourceOptions.shared; +const topk = tf.bf16_topk_gpu; + +/// TF_Q27_MTP_GPU_PICK: the pick's kernel, its rows, the rows a fused save reads, and the chance's terms. +const Fast = struct { + ops: topk.Ops, + rows: mtl.Buffer, + saved: mtl.Buffer, + memo: q.mtp_pick.Memo, + held: u32 = 0, // logits rows of the last pass with a GPU pick (0: the CPU picks) + + fn init(gpa: std.mem.Allocator, device: mtl.Device) !Fast { + const ops = try topk.Ops.init(device); + errdefer ops.deinit(); + const rows = try device.buffer(q.mtp_pick.max_rows * @sizeOf(topk.contract.Row), opts); + errdefer rows.deinit(); + const saved = try device.buffer(lb.max_streams * 4, opts); + errdefer saved.deinit(); + return .{ .ops = ops, .rows = rows, .saved = saved, .memo = try q.mtp_pick.Memo.init(gpa) }; + } + + fn deinit(f: *Fast, gpa: std.mem.Allocator) void { + f.ops.deinit(); + f.rows.deinit(); + f.saved.deinit(); + f.memo.deinit(gpa); + } + + /// The top-1 of each logits row when one launch holds them; a wider pass keeps the CPU pick. + fn encode(f: *Fast, e: mtl.ComputeEncoder, logits: mtl.Buffer, rows: u32, vocab: u32) !void { + f.held = 0; + if (rows == 0 or rows > q.mtp_pick.max_rows) return; + try f.ops.encode(e, .{ .buf = logits }, .{ .buf = f.rows }, q.mtp_pick.params(rows, vocab)); + f.held = rows; + } +}; + +/// Picks on the head's command buffer, for a chained step. +const PickOnly = struct { + x: *Mtp, + rows: u32, + pub fn before(_: PickOnly, _: mtl.ComputeEncoder) !void {} + pub fn after(p: PickOnly, e: mtl.ComputeEncoder, _: Ref) !void { + try p.x.fast.?.encode(e, p.x.scratch.logits, p.rows, @intCast(p.x.back.runner.model.config.vocab)); + } +}; + +/// One absorb on one command buffer: the kept rows, the head, its picks, each stream's newest row. +const Fused = struct { + x: *Mtp, + items: []const dr.Absorb, + firsts: []const u32, + lasts: []const usize, + ctxs: []const *Ctx, + total: usize, + picks: u32, + pub fn before(a: Fused, e: mtl.ComputeEncoder) !void { + try a.x.gatherRows(e, a.items, a.firsts, a.total); + e.barrier(); + } + pub fn after(a: Fused, e: mtl.ComputeEncoder, out: Ref) !void { + const x = a.x; + const m = x.back.runner.model; + const f = &x.fast.?; + try f.encode(e, x.scratch.logits, a.picks, @intCast(m.config.vocab)); + const at = f.saved.slice(u32, a.lasts.len); + for (a.lasts, at, a.ctxs, 0..) |last, *v, c, i| { + v.* = @intCast(last); + try m.glue.tapRows(e, out, .{ .buffer = f.saved, .offset = i * 4 }, .{ .buffer = c.out }, .{ .rows = 1, .width = @intCast(m.config.hidden), .capacity = @intCast(a.total), .planes = 1 }); + } + } +}; /// A stream's head: its rows, its newest row's normed output, and the chain it holds. const Ctx = struct { @@ -37,6 +108,7 @@ pub const Mtp = struct { controls: lanes.mtp_policy.Controls, tap: [1]u32, step_ms: f64 = 0, // one chained step, timed at load + fast: ?Fast = null, // TF_Q27_MTP_GPU_PICK=1 streams: std.AutoHashMapUnmanaged(*Stream, *Ctx) = .empty, /// The head of the target's model, its taps the last layer's rows (the residual the final norm reads). @@ -52,6 +124,9 @@ pub const Mtp = struct { errdefer index.deinit(); const x = try gpa.create(Mtp); x.* = .{ .gpa = gpa, .back = back, .scratch = scratch, .stage = stage, .index = index, .controls = controls, .tap = .{@intCast(m.config.layers - 1)} }; + errdefer gpa.destroy(x); + if (try @import("sys").environment.read(bool, "TF_Q27_MTP_GPU_PICK", false)) x.fast = try Fast.init(gpa, m.device); + errdefer if (x.fast) |*f| f.deinit(gpa); x.step_ms = try x.time(); return x; } @@ -63,6 +138,7 @@ pub const Mtp = struct { x.scratch.deinit(); x.stage.deinit(); x.index.deinit(); + if (x.fast) |*f| f.deinit(x.gpa); x.gpa.destroy(x); } @@ -84,7 +160,7 @@ pub const Mtp = struct { var round = try x.plan(&.{.{ .slot = 0, .start = 0, .capacity = r.capacity, .ids = &.{0} }}); defer round.deinit(); const t0 = mtl.clock.seconds(); - _ = try r.headPass(&round, &x.scratch, .{ .buffer = x.stage }, .last); + _ = try x.chainPass(&round, .{ .buffer = x.stage }, .last, 1); _ = try x.pickRow(0); best = @min(best, (mtl.clock.seconds() - t0) * 1000); } @@ -98,7 +174,30 @@ pub const Mtp = struct { fn pickRow(x: *Mtp, row: usize) !q.mtp.Pick { const vocab = x.back.runner.model.config.vocab; - return q.mtp.pick(x.scratch.logits.slice(u16, row * vocab + vocab)[row * vocab ..]); + const values = x.scratch.logits.slice(u16, row * vocab + vocab)[row * vocab ..]; + if (x.fast) |*f| if (row < f.held) return q.mtp_pick.fromRow(&f.rows.slice(topk.contract.Row, f.held)[row], values, &f.memo); + return q.mtp.pick(values); + } + + /// A chained head pass, its picks on the same command buffer when the GPU pick is on. + fn chainPass(x: *Mtp, round: *const Round, hidden: Ref, head: q.forward.Head, rows: u32) !Ref { + const r = x.back.runner; + if (x.fast == null) return r.headPass(round, &x.scratch, hidden, head); + return q.mtp.passAround(r, round, &x.scratch, hidden, head, PickOnly{ .x = x, .rows = rows }); + } + + /// Encodes each item's kept rows into the stage, at its first row in the pass. + fn gatherRows(x: *Mtp, e: mtl.ComputeEncoder, items: []const dr.Absorb, firsts: []const u32, total: usize) !void { + const m = x.back.runner.model; + const row = m.config.hidden * 2; + const index = x.index.slice(u32, total); + for (items, firsts) |it, first| { + const n = count(it); + for (index[first..][0..n], 0..) |*v, j| v.* = if (it.rows) |rs| rs[j] else @intCast(j); + const f = it.features; + const src = Ref{ .buffer = .{ .id = @ptrFromInt(f.buffer) }, .offset = f.offset }; + try m.glue.tapRows(e, src, .{ .buffer = x.index, .offset = first * 4 }, .{ .buffer = x.stage, .offset = first * row }, .{ .rows = @intCast(n), .width = @intCast(m.config.hidden), .capacity = f.rows, .planes = 1 }); + } } fn ctxOf(x: *Mtp, s: *Stream) !*Ctx { @@ -198,29 +297,31 @@ pub const Mtp = struct { const lone_last = picks == 1 and wants[items.len - 1] and rd.firsts[items.len - 1] + count(items[items.len - 1]) == total; const head: q.forward.Head = if (picks == 0) .none else if (lone_last) .last else .all; if (head == .all and total > logit_rows) return error.BadMtpRows; - { - const pool = mtl.objc.Pool.push(); - defer pool.pop(); - const cb = m.queue.commandBuffer(); - const e = cb.compute(.serial); - errdefer e.end(); // an encoder left open aborts the process when it is released - const index = x.index.slice(u32, total); - for (items, rd.firsts) |it, first| { - const n = count(it); - for (index[first..][0..n], 0..) |*v, j| v.* = if (it.rows) |rs| rs[j] else @intCast(j); - const f = it.features; - const src = Ref{ .buffer = .{ .id = @ptrFromInt(f.buffer) }, .offset = f.offset }; - try m.glue.tapRows(e, src, .{ .buffer = x.index, .offset = first * 4 }, .{ .buffer = x.stage, .offset = first * row }, .{ .rows = @intCast(n), .width = @intCast(m.config.hidden), .capacity = f.rows, .planes = 1 }); - } - e.end(); - cb.commit(); - cb.wait(); - if (q.decode_round.gpuFailed(cb, "the MTP head's rows")) return error.RoundGpuFailure; - } - const out = try r.headPass(&rd, &x.scratch, .{ .buffer = x.stage }, head); var lasts: [lb.max_streams]usize = undefined; for (items, rd.firsts, lasts[0..items.len]) |it, first, *last| last.* = first + count(it) - 1; - try x.save(out, lasts[0..items.len], ctxs[0..items.len]); + if (x.fast != null) { + const logits: u32 = switch (head) { + .none => 0, + .last => 1, + .all => @intCast(total), + }; + _ = try q.mtp.passAround(r, &rd, &x.scratch, .{ .buffer = x.stage }, head, Fused{ .x = x, .items = items, .firsts = rd.firsts, .lasts = lasts[0..items.len], .ctxs = ctxs[0..items.len], .total = total, .picks = logits }); + } else { + { + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const cb = m.queue.commandBuffer(); + const e = cb.compute(.serial); + errdefer e.end(); // an encoder left open aborts the process when it is released + try x.gatherRows(e, items, rd.firsts, total); + e.end(); + cb.commit(); + cb.wait(); + if (q.decode_round.gpuFailed(cb, "the MTP head's rows")) return error.RoundGpuFailure; + } + const out = try r.headPass(&rd, &x.scratch, .{ .buffer = x.stage }, head); + try x.save(out, lasts[0..items.len], ctxs[0..items.len]); + } for (items, ctxs[0..items.len], wants[0..items.len], lasts[0..items.len]) |it, c, want, last| { // from the target's start: a state the head did not follow (a resumed prompt) has the target's rows below c.len = it.start + count(it); @@ -283,7 +384,7 @@ pub const Mtp = struct { var rd = try x.plan(inputs[0..n]); defer rd.deinit(); const hidden = if (n == 1) src[who[0]] else try x.stageRows(src[0..items.len], who[0..n], rd.firsts); - const out = try r.headPass(&rd, &x.scratch, hidden, if (n == 1) .last else .all); + const out = try x.chainPass(&rd, hidden, if (n == 1) .last else .all, @intCast(if (n == 1) 1 else rd.ids.len)); for (who[0..n], rd.firsts) |i, first| { const c = ctxs[i]; const pick = try x.pickRow(if (n == 1) 0 else first); diff --git a/zig/src/native/qwen27_reserve.zig b/zig/src/native/qwen27_reserve.zig index e241beeaf9e..dfc16c21c15 100644 --- a/zig/src/native/qwen27_reserve.zig +++ b/zig/src/native/qwen27_reserve.zig @@ -48,11 +48,21 @@ pub const Budget = struct { working_set: usize, }; +/// A tied head's repack, which the checkpoint's file bytes do not include. +fn tiedHeadBytes(a: std.mem.Allocator, text: []const u8, c: Config) !usize { + if (!c.tied_head) return 0; + var formats = try q.affine.Formats.init(a, text); + defer formats.deinit(); + const s = (try formats.resolve("model.embed_tokens")) orelse return error.MissingAffineFormat; + return q.tied_head.bytes(c.vocab, c.hidden, s.bits, s.group_size); +} + /// Startup's charge for `dir` on this Mac, no drafter or images; `weights` bytes stand in for the loaded model. pub fn budget(a: std.mem.Allocator, io: std.Io, dir: []const u8, weights: u64, context: u32, streams: u32, fixed: bool) !Budget { const path = try std.fs.path.join(a, &.{ dir, "config.json" }); const text = try std.Io.Dir.cwd().readFileAlloc(io, path, a, .limited(16 << 20)); - const c = try q.config.parse(a, text, null); + var problem: q.config.Problem = .{}; + const c = try q.model.parseServed(a, text, null, &problem); if (context == 0 or context > c.max_position) return error.ContextFull; const dev = try mtl.Device.init(); defer dev.deinit(); @@ -61,7 +71,7 @@ pub fn budget(a: std.mem.Allocator, io: std.Io, dir: []const u8, weights: u64, c const shared = try q.simd_attention.sharedPrefix(units); const geometry = try q.attention_plan.Geometry.fromConfig(c, shared); const current = @max(loaded_rows, q.model.promptRows(c, 0, geometry)); - const held = @as(usize, @intCast(weights)) + memory.frameBytes(c, current); + const held = @as(usize, @intCast(weights)) + try tiedHeadBytes(a, text, c) + memory.frameBytes(c, current); const f = fit(c, context, window, streams, shared, 0, q.taps.layers.len, current, try memory.room(dev.maxWorkingSet(), held, cap())); const r = try rows(f, dev.generation(), window); const slots = f.streams(r, fixed) catch |err| if (err == error.TooManyStreams) 0 else return err; diff --git a/zig/src/native/qwen27_served.zig b/zig/src/native/qwen27_served.zig index 34a08d09d1a..e41950175af 100644 --- a/zig/src/native/qwen27_served.zig +++ b/zig/src/native/qwen27_served.zig @@ -21,6 +21,10 @@ const disk = @import("qwen27_disk.zig"); const images = @import("qwen27_images.zig"); const Mtp = @import("qwen27_mtp.zig").Mtp; const Allocator = std.mem.Allocator; +const helpers = @import("qwen27_served_helpers.zig"); +const room = helpers.room; +const drafterRefusal = helpers.drafterRefusal; +const gibBytes = helpers.gibBytes; pub const Options = struct { context: u32, @@ -201,12 +205,6 @@ fn shareRoom(h: *const Host, why: *[]const u8) !u64 { return share_fit.room(cache_fit.ram(), cache_fit.footprint(), try laterFootprint(h), guards); } -/// Room left beside the weights and an 8 GiB margin. -fn room(model: *const q.model.Model) usize { - const dev = model.device; - return q.prompt_memory.room(dev.maxWorkingSet(), dev.allocated(), cap()) catch 0; -} - /// TF_QWEN27_WORKING_SET_BYTES: a development cap on the device's reported working set. const cap = reserve.cap; @@ -313,12 +311,6 @@ pub fn open(gpa: Allocator, io: std.Io, dir: []const u8, o: Options, a: Allocato return h; } -/// Why --drafter is refused before the target or the drafter loads. -fn drafterRefusal(a: Allocator, dir: []const u8, drafter: []const u8, err: anyerror) ![]const u8 { - if (err == error.DraftForAnotherTarget) return std.fmt.allocPrint(a, "--drafter {s} drafts for another target: its width, vocabulary or tapped layers do not fit {s} (DraftForAnotherTarget)", .{ drafter, dir }); - return std.fmt.allocPrint(a, "--drafter {s} is not a drafter the native Qwen engine serves for {s} ({s}): it takes z-lab/Qwen3.8-27B-DFlash2 as released, for Qwen3.8-27B", .{ drafter, dir, @errorName(err) }); -} - /// A loaded model served as `open` serves one, `drafter` bound in place of `o.drafter`; both stay the caller's. pub fn attach(parent: Allocator, io: std.Io, model: *q.model.Model, drafter: ?*q.dflash.runtime_model.Model, o: Options, a: Allocator, why: *[]const u8) !*Host { const setup = tf.startup_receipt.span(.runtime_setup); @@ -350,7 +342,7 @@ pub fn attach(parent: Allocator, io: std.Io, model: *q.model.Model, drafter: ?*q const gpa = if (profiling) h.counted.allocator() else parent; var draft_model = drafter; const owns_draft = drafter == null and o.drafter != null; - if (owns_draft) draft_model = q.dflash.runtime_model.Model.load(gpa, io, model, o.drafter.?, if (o.drafter_bits == 4) .prepared_q4_reference else .bf16_reference) catch |err| { + if (owns_draft) draft_model = q.dflash.runtime_model.Model.loadSpan(gpa, io, model, o.drafter.?, if (o.drafter_bits == 4) .prepared_q4_reference else .bf16_reference, capacity + window) catch |err| { why.* = try std.fmt.allocPrint(a, "the native Qwen3.8-27B drafter cannot load {s} ({s})", .{ o.drafter.?, @errorName(err) }); return error.DrafterLoad; }; @@ -361,7 +353,8 @@ pub fn attach(parent: Allocator, io: std.Io, model: *q.model.Model, drafter: ?*q const shared = try q.simd_attention.sharedPrefix(model.device.tensorUnits()); // the MTP head's keys and values: one more attention layer a slot, beside the drafter's ring when there is one const head_kv: usize = if (mtp_on) @as(usize, capacity + window) * model.config.kvDim() * 2 * 2 else 0; - const fit_prompt = reserve.fit(model.config, capacity, window, o.streams, shared, head_kv + if (draft_model) |d| @as(usize, d.ring().window) * d.ring().stride else 0, if (draft_model) |d| d.graph.config.tap_count else q.taps.layers.len, model.frame.capacity, room(model)); + var fit_prompt = reserve.fit(model.config, capacity, window, o.streams, shared, head_kv + if (draft_model) |d| @as(usize, d.ring().window) * d.ring().stride else 0, if (draft_model) |d| d.graph.config.tap_count else q.taps.layers.len, model.frame.capacity, room(model)); + if (draft_model) |d| fit_prompt.tap_row = memory.tapRowBytes(model.config.hidden, d.graph.config.tap_count, d.graph.config.variant == .v1); const rows = try reserve.rows(fit_prompt, model.device.generation(), window); const slots = fit_prompt.streams(rows, o.streams_fixed) catch |err| { const dev = model.device; @@ -375,7 +368,7 @@ pub fn attach(parent: Allocator, io: std.Io, model: *q.model.Model, drafter: ?*q model.frame.deinit(); model.frame = next; } - std.log.info("qwen27: prompt capacity={d} rows, startup stream and scratch reserve={d} bytes", .{ rows, try memory.runnerBytes(model.config, capacity + window, slots, rows, shared, fit_prompt.ring, fit_prompt.planes) }); + std.log.info("qwen27: prompt capacity={d} rows, startup stream and scratch reserve={d} bytes", .{ rows, try memory.runnerBytesTaps(model.config, capacity + window, slots, rows, shared, fit_prompt.ring, if (fit_prompt.tap_row > 0) fit_prompt.tap_row else memory.tapRowBytes(model.config.hidden, fit_prompt.planes, false)) }); h.gpa = gpa; h.model = model; h.owns_model = false; @@ -385,8 +378,14 @@ pub fn attach(parent: Allocator, io: std.Io, model: *q.model.Model, drafter: ?*q h.resident = null; h.disk_stage = null; h.vision = o.images; // closed with the host; a failed attach leaves it to the caller - h.trace = null; // TF_QWEN27_METAL_KV_PAGES=1: every slot's rows in pages; Fit charged each its window - h.runner = try if (try q.decode_round.pagesOn()) q.decode_round.Runner.initPaged(gpa, model, slots, capacity + window) else q.decode_round.Runner.initReady(gpa, model, slots, capacity + window, 1); + h.trace = null; + const paged = try q.decode_round.pagesOn(); + const kv_step = if (paged) null else q.kv_grow.step(@import("sys").environment.rawText("TF_Q27_KV_GROW")) catch |err| { + why.* = "TF_Q27_KV_GROW must be 0 (off) or a row count that is a multiple of 16"; + return err; + }; + h.runner = try if (paged) q.decode_round.Runner.initPaged(gpa, model, slots, capacity + window) else q.decode_round.Runner.initGrow(gpa, model, slots, capacity + window, 1, kv_step); + if (kv_step) |s| std.log.info("qwen27: K/V grows as used: a slot starts at {d} rows and grows by {d} or a quarter, up to {d}", .{ q.kv_grow.first(s, capacity + window), s, capacity + window }); errdefer h.runner.deinit(); if (profileEvery()) |every| { h.trace = .{ .queue = model.queue, .report_every = every }; // enabled once measure() has priced the windows @@ -403,7 +402,13 @@ pub fn attach(parent: Allocator, io: std.Io, model: *q.model.Model, drafter: ?*q h.back.serial_copy_match = policy.serialCopyMatch(units, window, lanes_value); h.back.chunk = h.runner.promptRows(@min(rows, reserve.requested(model.device.generation(), model.config.moe()))); h.back.grow = .{ .ctx = h, .room = Host.roomFor, .added = Host.added }; + h.runner.grown = .{ .ctx = h, .added = Host.added }; h.back.vision = o.images; + h.warm = .{ .queue = model.queue }; // ready slots wired before the cache budget reads the footprint + const residency = tf.startup_receipt.span(.residency); + holdResident(h, io) catch |err| std.log.warn("qwen27: no residency set ({s}); the first request after an idle second re-wires the weights", .{@errorName(err)}); + residency.end(); + errdefer q.residency.drop(h); // decided before cache sizing and the worker starts if (h.draft != null or h.mtp_layer != null or mtp_on) try h.back.measure(io); h.mtp = null; h.wrap = null; @@ -421,7 +426,7 @@ pub fn attach(parent: Allocator, io: std.Io, model: *q.model.Model, drafter: ?*q h.core = lanes.Engine.init(gpa, &h.cfg, if (h.wrap) |*w| w.backend() else h.back.backend(), h.clock.clock()); errdefer h.core.deinit(); const offer: ?api.Vision = if (o.images) |v| .{ .ctx = h, .prepare = Host.prepareImage, .image_token = v.c.image_token, .markers = &v.markers, .image_tokens = v.capacity, .max_images = v.max_images, .image_share = if (o.vision) |x| x.image_share else .request, .explain = tf.qwen_vl.geometry.problem } else null; - h.host = api.LaneHost.init(gpa, io, &h.core, .{ .name = "qwen27", .draft_sources = .{ .mtp = h.mtp_layer != null, .drafter = if (h.draft != null) .{ .kind = "DFlash2", .name = o.drafter_name orelse o.drafter orelse "" } else if (mtp_on) .{ .kind = "MTP", .name = q.gpu_weights.mtp_file } else null }, .structures = @import("qwen27_masks.zig").supported, .penalties = true, .lanes = slots, .context_window = capacity, .prefill_step = @intCast(h.back.chunk), .decode_share = o.decode_share, .vision = offer }); + h.host = api.LaneHost.init(gpa, io, &h.core, .{ .name = "qwen27", .draft_sources = .{ .mtp = h.mtp_layer != null, .drafter = if (h.draft) |d| .{ .kind = d.model.graph.config.kind(), .name = o.drafter_name orelse o.drafter orelse "" } else if (mtp_on) .{ .kind = "MTP", .name = q.gpu_weights.mtp_file } else null }, .structures = @import("qwen27_masks.zig").supported, .penalties = true, .lanes = slots, .context_window = capacity, .prefill_step = @intCast(h.back.chunk), .decode_share = o.decode_share, .vision = offer }); h.host.memory = .{ .ctx = h, .read = readMemory }; h.host.explain = .{ .text = words }; h.host.decoded_rows = true; // a reply's rows prefill with the bits decoding gave them, with the cache on or off @@ -431,11 +436,6 @@ pub fn attach(parent: Allocator, io: std.Io, model: *q.model.Model, drafter: ?*q if (o.decode_share == null and std.c.getenv("TENSORFOLD_PREFILL_SHARE") == null) h.host.srpt = .withDefault(true); var loop_text: [160]u8 = undefined; std.log.info("qwen27: {s}", .{try policy.describe(&loop_text, serial, window, h.draft != null, h.back.copies)}); - h.warm = .{ .queue = model.queue }; // ready slots wired before the cache budget reads the footprint - const residency = tf.startup_receipt.span(.residency); - holdResident(h, io) catch |err| std.log.warn("qwen27: no residency set ({s}); the first request after an idle second re-wires the weights", .{@errorName(err)}); - residency.end(); - errdefer q.residency.drop(h); // decided before cache sizing and the worker starts const ane = tf.startup_receipt.span(.optional_ane); if (model.share_pending) { const before = cache_fit.footprint(); @@ -457,10 +457,9 @@ pub fn attach(parent: Allocator, io: std.Io, model: *q.model.Model, drafter: ?*q if (h.trace) |*t| t.enabled = true; // serving rounds count from here: measure() timed whole, unsplit buffers try h.host.start(); tf.startup_receipt.span(.model_ready).end(); - std.log.info("{f}", .{StartupLine{ .streams = slots, .context = capacity, .draft_slots = if (h.draft != null) h.back.draft_slots else 0, .mtp = h.mtp_layer != null or mtp_on, .images = o.images != null }}); + std.log.info("{f}", .{StartupLine{ .streams = slots, .context = capacity, .draft_slots = if (h.draft != null) h.back.draft_slots else 0, .mtp = h.mtp_layer != null or mtp_on, .drafter = if (h.draft) |d| d.model.graph.config.kind() else "DFlash2", .images = o.images != null }}); return h; } - test "qwen27 startup: draft stream count, singular text and optional suffixes" { const limit = try lb.draftSlots(); const limited = platform.c.getenv("TF_Q27_DRAFT_SLOTS") != null; @@ -514,11 +513,6 @@ fn laterRoom(h: *const Host) u64 { return share_fit.room(cache_fit.ram(), cache_fit.footprint(), laterFootprint(h) catch return 0, guards); } -/// --prompt-cache-gib's bytes (0 or less: none). -fn gibBytes(gib: f64) u64 { - return if (gib > 0) std.math.lossyCast(u64, gib * cache_fit.GiB) else 0; -} - /// Reserve later buffers and the loaded share's priced bytes that its construction left outside the footprint. fn laterFootprint(h: *const Host) !u64 { const tower: u64 = if (h.back.vision) |v| v.firstUse() else 0; diff --git a/zig/src/native/qwen27_served_helpers.zig b/zig/src/native/qwen27_served_helpers.zig new file mode 100644 index 00000000000..8d530d2b820 --- /dev/null +++ b/zig/src/native/qwen27_served_helpers.zig @@ -0,0 +1,22 @@ +const std = @import("std"); +const tf = @import("tensorfold"); +const q = tf.qwen27; +const cache_fit = @import("cache_fit.zig"); +const reserve = @import("qwen27_reserve.zig"); + +/// Room left beside the weights and an 8 GiB margin. +pub fn room(model: *const q.model.Model) usize { + const dev = model.device; + return q.prompt_memory.room(dev.maxWorkingSet(), dev.allocated(), reserve.cap()) catch 0; +} + +/// Why --drafter is refused before the target or the drafter loads. +pub fn drafterRefusal(a: std.mem.Allocator, dir: []const u8, drafter: []const u8, err: anyerror) ![]const u8 { + if (err == error.DraftForAnotherTarget) return std.fmt.allocPrint(a, "--drafter {s} drafts for another target: its width, vocabulary or tapped layers do not fit {s} (DraftForAnotherTarget)", .{ drafter, dir }); + return std.fmt.allocPrint(a, "--drafter {s} is not a drafter the native Qwen engine serves for {s} ({s}): it takes z-lab/Qwen3.8-27B-DFlash2 as released for Qwen3.8-27B, or a DFlash drafter (DFlashDraftModel) made for this target", .{ drafter, dir, @errorName(err) }); +} + +/// --prompt-cache-gib's bytes (0 or less: none). +pub fn gibBytes(gib: f64) u64 { + return if (gib > 0) std.math.lossyCast(u64, gib * cache_fit.GiB) else 0; +} diff --git a/zig/src/native/qwen27_slots.zig b/zig/src/native/qwen27_slots.zig index 388d411337f..ff6608998e2 100644 --- a/zig/src/native/qwen27_slots.zig +++ b/zig/src/native/qwen27_slots.zig @@ -44,6 +44,7 @@ pub fn opening(b: *Metal, s: *lanes.Stream, slot: u32) !Fill { if (resumed == 0) { if (d) |x| try x.reset() else try b.runner.reset(slot); try clearContext(b, slot); + try b.runner.admit(slot, @intCast(ids.len)); // a fresh pass: the slot takes its prompt's rows at once } s.cached = resumed; draft_fns.mtpOpen(b, slot); @@ -217,6 +218,7 @@ pub fn cancelPrefill(ptr: *anyopaque, s: *lanes.Stream) anyerror!void { /// A pass that failed or went back to the queue frees its slot, pages and promise (a standing slot 0's rows stay). fn drop(b: *Metal, slot: u32) void { + b.give_back[slot] = b.runner.kv_step != null; b.runner.release(slot, slot == 0 and b.standing.tokens.len > 0); b.owners[slot] = null; } @@ -413,7 +415,8 @@ pub fn ready(b: *Metal, slot: u32, s: *const lanes.Stream) !void { defer added.deinit(b.gpa); try added.appendSlice(b.gpa, try b.runner.ensure(slot)); if (context_missing) { - const x = try Context.init(b.gpa, b.draft.?.model, drafting); + const x = try Context.initGrow(b.gpa, b.draft.?.model, drafting, b.runner.kv_step); + x.settle = .{ .ctx = b.runner, .slot = slot, .run = q.decode_round.Runner.settleOpaque }; b.contexts[slot] = x; try x.buffers(&added, b.gpa); } @@ -422,8 +425,12 @@ pub fn ready(b: *Metal, slot: u32, s: *const lanes.Stream) !void { /// A drafter context's bytes: the taps ring, and K/V caches when the slot drafts. fn contextBytes(c: q.dflash.config.Config, drafting: bool) usize { - const ring = @as(usize, c.window) * c.tapWidth() * 2; - return ring + if (drafting) @as(usize, c.layers) * 2 * (@as(usize, c.window) + 16) * c.kvWidth() * 2 else 0; + const ring = @as(usize, c.span()) * c.ringWidth() * 2; + var caches: usize = 0; + if (drafting) for (0..c.layers) |i| { + caches += 2 * (@as(usize, c.layerWindow(i)) + 16) * c.kvWidth() * 2; + }; + return ring + caches; } /// A free slot for a new stream, slot 0 (the drafter's) first. @@ -453,10 +460,29 @@ pub fn unbind(b: *Metal, s: *lanes.Stream) void { var live: usize = 0; for (b.owners[0..b.runner.slots]) |owner| live += @intFromBool(owner != null); if (live <= 1) b.runner.trimBefore(); + b.give_back[slot] = b.runner.kv_step != null; + giveBack(b); +} + +/// Free, unread slots give back grown K/V and rings without waiting; slot 0 keeps what a next turn resumes from. +pub fn giveBack(b: *Metal) void { + for (0..b.runner.slots) |k| { + if (!b.give_back[k]) continue; + const slot: u32 = @intCast(k); + if (b.owners[k] != null) { + b.give_back[k] = false; + continue; + } + if ((slot == 0 and b.standing.tokens.len > 0) or b.runner.busy(slot)) continue; + b.give_back[k] = false; + b.runner.releaseGrown(slot) catch |err| std.log.warn("qwen27: slot {d} keeps its K/V ({s})", .{ slot, @errorName(err) }); + clearContext(b, slot) catch {}; + } } /// A promote unbind left for later, once no round is pending: a stream still in slot 0 or none to move ends it. pub fn promoteDue(b: *Metal) void { + giveBack(b); if (!b.promote_due or b.round != null) return; b.promote_due = false; promote(b); diff --git a/zig/src/native/qwen27_startup.zig b/zig/src/native/qwen27_startup.zig index 1f896061102..c4f28ec9594 100644 --- a/zig/src/native/qwen27_startup.zig +++ b/zig/src/native/qwen27_startup.zig @@ -3,28 +3,43 @@ const std = @import("std"); /// The startup line's drafting clause: the smaller of `streams` and `draft_slots`, or "" when none draft. pub fn draftWording(buf: []u8, streams: u32, draft_slots: u32) ![]const u8 { + return draftWordingKind(buf, "DFlash2", streams, draft_slots); +} + +/// draftWording for a drafter named `kind` (config.kind(): DFlash for z-lab's v1 layout, DFlash2 for its successor). +pub fn draftWordingKind(buf: []u8, kind: []const u8, streams: u32, draft_slots: u32) ![]const u8 { const drafts = @min(streams, draft_slots); if (drafts == 0) return ""; if (drafts == streams) { - if (streams == 1) return "DFlash2 drafts for the only stream"; - if (streams == 2) return "DFlash2 drafts for both streams"; - return std.fmt.bufPrint(buf, "DFlash2 drafts for all {d} streams", .{streams}); + if (streams == 1) return std.fmt.bufPrint(buf, "{s} drafts for the only stream", .{kind}); + if (streams == 2) return std.fmt.bufPrint(buf, "{s} drafts for both streams", .{kind}); + return std.fmt.bufPrint(buf, "{s} drafts for all {d} streams", .{ kind, streams }); } - return std.fmt.bufPrint(buf, "DFlash2 drafts for {d} of {d} streams", .{ drafts, streams }); + return std.fmt.bufPrint(buf, "{s} drafts for {d} of {d} streams", .{ kind, drafts, streams }); } pub const StartupLine = struct { streams: u32, context: u32, draft_slots: u32, - mtp: bool, // --mtp-drafts: the checkpoint's MTP layer drafts for every stream + mtp: bool = false, // --mtp-drafts: the checkpoint's MTP layer drafts for every stream images: bool, + drafter: []const u8 = "DFlash2", // the drafter's name in the line (config.kind()) pub fn format(line: StartupLine, w: *std.Io.Writer) std.Io.Writer.Error!void { try w.print("Qwen3.8-27B: {d} stream{s} of {d} tokens", .{ line.streams, if (line.streams == 1) "" else "s", line.context }); var wording: [64]u8 = undefined; - const drafting = draftWording(&wording, line.streams, line.draft_slots) catch return error.WriteFailed; + const drafting = draftWordingKind(&wording, line.drafter, line.streams, line.draft_slots) catch return error.WriteFailed; if (drafting.len > 0) try w.print(", {s}", .{drafting}) else if (line.mtp) try w.writeAll(", MTP drafts for each stream"); if (line.images) try w.writeAll(", images read"); } }; + +test "qwen27 startup: a v1 drafter's line names DFlash, a DFlash2 drafter's stays DFlash2" { + var buf: [96]u8 = undefined; + const v1 = try std.fmt.bufPrint(&buf, "{f}", .{StartupLine{ .streams = 2, .context = 4096, .draft_slots = 8, .images = false, .drafter = "DFlash" }}); + try std.testing.expectEqualStrings("Qwen3.8-27B: 2 streams of 4096 tokens, DFlash drafts for both streams", v1); + var two: [96]u8 = undefined; + const stock = try std.fmt.bufPrint(&two, "{f}", .{StartupLine{ .streams = 1, .context = 4096, .draft_slots = 8, .images = false }}); + try std.testing.expectEqualStrings("Qwen3.8-27B: 1 stream of 4096 tokens, DFlash2 drafts for the only stream", stock); +} diff --git a/zig/src/native/qwen35.zig b/zig/src/native/qwen35.zig index f2aaa8f1044..4136624f316 100644 --- a/zig/src/native/qwen35.zig +++ b/zig/src/native/qwen35.zig @@ -47,6 +47,48 @@ fn pagesOn() !bool { return @import("sys").environment.read(bool, "TF_QWEN35_METAL_KV_PAGES", false); } +fn chunkRows(_: std.mem.Allocator, window: usize, problem: *[]const u8) !usize { + const settings = @import("sys").environment; + comptime settings.registered("TF_QWEN35_CHUNK"); + const chunk = settings.read(usize, "TF_QWEN35_CHUNK", 128) catch |err| { + if (err == error.InvalidEnvironment) { + problem.* = "TF_QWEN35_CHUNK: a whole number 1 to the model's context window; unset for the shipped 128"; + return error.InvalidChunk; + } + return err; + }; + if (chunk == 0 or chunk > window) { + problem.* = "TF_QWEN35_CHUNK: a whole number 1 to the model's context window; unset for the shipped 128"; + return error.InvalidChunk; + } + return chunk; +} + +test "TF_QWEN35_CHUNK is parsed through platform/environment.zig" { + const settings = @import("sys").environment; + try std.testing.expectEqual(@as(?u64, null), try settings.parse("TF_QWEN35_CHUNK", null)); + try std.testing.expectEqual(@as(?u64, 512), try settings.parse("TF_QWEN35_CHUNK", "512")); + try std.testing.expectError(error.InvalidEnvironment, settings.parse("TF_QWEN35_CHUNK", "0")); + try std.testing.expectError(error.InvalidEnvironment, settings.parse("TF_QWEN35_CHUNK", "4k")); +} + +test "qwen35 startup: TF_QWEN35_CHUNK refuses before the checkpoint loader runs" { + const env = @import("sys").env; + const saved = std.c.getenv("TF_QWEN35_CHUNK"); + defer if (saved) |v| { + _ = env.setenv("TF_QWEN35_CHUNK", std.mem.span(v), 1); + } else { + _ = env.unsetenv("TF_QWEN35_CHUNK"); + }; + try std.testing.expectEqual(@as(c_int, 0), env.setenv("TF_QWEN35_CHUNK", "4k", 1)); + var problem: []const u8 = ""; + try std.testing.expectError(error.InvalidChunk, chunkRows(std.testing.allocator, 8192, &problem)); + try std.testing.expectEqualStrings( + "TF_QWEN35_CHUNK: a whole number 1 to the model's context window; unset for the shipped 128", + problem, + ); +} + /// The pool beside the model under the load limit: kv_pool's plan of the streams and pages, made now; why not, or null. fn planPages(a: std.mem.Allocator, metal: *q.backend.Metal, device: mtl.Device, o: api.Open, window: u64) !?[]const u8 { const kv = q.state.kv; @@ -69,10 +111,26 @@ fn gib(bytes: u64) f64 { } pub fn open(a: std.mem.Allocator, gpa: std.mem.Allocator, io: std.Io, o: api.Open, problem: *[]const u8) !?api.Opened { + const settings = @import("sys").environment; + if (try settings.refusal(a, settings.Process{}, .{ .metal = true })) |why| { + problem.* = why; + return null; + } if (try o.slideRefusal(a, "Macs")) |why| { problem.* = why; return null; } + const cfg = q.config.Config.read(a, io, o.dir) catch |err| { + problem.* = try std.fmt.allocPrint(a, "the native Qwen engine cannot read this checkpoint ({s})", .{@errorName(err)}); + return null; + }; + const window: i64 = o.context orelse @intCast(cfg.context); + if (window < 1 or window > cfg.context) { + problem.* = "--context must fit the Qwen checkpoint's positive context window"; + return null; + } + const chunk = chunkRows(a, @intCast(@max(window, 1)), problem) catch return null; + const chunk_u32: u32 = @intCast(chunk); const pool = mtl.objc.Pool.push(); defer pool.pop(); const model = q.Model.load(gpa, io, o.dir) catch |err| { @@ -80,19 +138,12 @@ pub fn open(a: std.mem.Allocator, gpa: std.mem.Allocator, io: std.Io, o: api.Ope return null; }; errdefer model.deinit(); - const window: i64 = o.context orelse @intCast(model.config.context); - if (window < 1 or window > model.config.context) { - model.deinit(); - problem.* = "--context must fit the Qwen checkpoint's positive context window"; - return null; - } const h = try gpa.create(Host); errdefer gpa.destroy(h); h.gpa = gpa; h.model = model; h.resident = null; - const chunk = 128; - h.metal = try q.backend.Metal.init(gpa, model, .{ .capacity = @intCast(window), .chunk = chunk, .streams = @max(o.lanes, 2) }); + h.metal = try q.backend.Metal.init(gpa, model, .{ .capacity = @intCast(window), .chunk = chunk_u32, .streams = @max(o.lanes, 2) }); errdefer h.metal.deinit(); // TF_QWEN35_METAL_KV_PAGES: the page plan sets the streams; otherwise each stream's whole cache is admitted at load const paged = try pagesOn(); @@ -115,7 +166,7 @@ pub fn open(a: std.mem.Allocator, gpa: std.mem.Allocator, io: std.Io, o: api.Ope h.clock = .{ .io = io }; h.core = lanes.Engine.init(gpa, &h.config, h.metal.backend(), h.clock.clock()); errdefer h.core.deinit(); - h.host = api.LaneHost.init(gpa, io, &h.core, .{ .lanes = served, .context_window = @intCast(window), .prefill_step = chunk, .decode_share = o.decode_share, .structures = true }); + h.host = api.LaneHost.init(gpa, io, &h.core, .{ .lanes = served, .context_window = @intCast(window), .prefill_step = chunk_u32, .decode_share = o.decode_share, .structures = true }); h.host.memory = .{ .ctx = h, .read = readMemory }; h.cache = null; if (o.prompt_cache_gib) |budget_gib| { @@ -134,7 +185,7 @@ pub fn open(a: std.mem.Allocator, gpa: std.mem.Allocator, io: std.Io, o: api.Ope h.cache = api.prompt_cache.Store.init(gpa, .{ .ptr = h.metal, .vtable = &.{ .bytes = S.bytes, .save = S.save, .restore = S.restore, .drop = S.drop }, - }, .{ .planned = true, .grid = chunk, .chunk = chunk, .warm_usable = true }, plan.budget_bytes); + }, .{ .planned = true, .grid = chunk_u32, .chunk = chunk_u32, .warm_usable = true }, plan.budget_bytes); h.host.cache = &h.cache.?; } } diff --git a/zig/src/platform/environment.zig b/zig/src/platform/environment.zig index a10319debdf..92d4bfd7687 100644 --- a/zig/src/platform/environment.zig +++ b/zig/src/platform/environment.zig @@ -44,6 +44,7 @@ pub const rules = [_]Rule{ .{ .name = "TF_QWEN_KV_HOST_GIB", .scope = .cuda, .kind = .u64, .min = 1, .max = std.math.maxInt(u64) >> 30, .forms = "positive whole GiB fitting an unsigned 64-bit byte count; blank or unset: one full KV window" }, .{ .name = "TF_CACHE_EVICT", .scope = .common, .kind = .word, .words = &.{ "main", "decayed_resume" }, .forms = "main or decayed_resume (default main)" }, .{ .name = "TF_FLASHNEXT_BATCH_DRAWS", .scope = .cuda, .kind = .flag, .blank_default = false, .forms = "0 or 1 (0 restores per-stream Flash Next row draws; default 1)" }, + .{ .name = "TF_QWEN35_ATTN_ALL_ROWS", .scope = .cuda, .kind = .flag, .forms = "0 or 1 (default 0; 1 runs exact all-length BF16 rows for multi-row Qwen decode windows)" }, .{ .name = "TF_STARTUP_RECEIPT", .scope = .common, .kind = .flag, .forms = "0 or 1 (opt-in startup and first completion receipts)" }, .{ .name = "TF_SHARED_PRICE_LOG", .scope = .common, .kind = .flag, .forms = "0 or 1 (1 logs the shared plain price, a line a round)" }, .{ .name = "TENSORFOLD_DEVICE_CHECK", .scope = .common, .kind = .flag, .forms = "0 or 1 (0 skips serve's device-profile check; default 1)" }, @@ -52,6 +53,7 @@ pub const rules = [_]Rule{ .{ .name = "TENSORFOLD_PARALLEL", .scope = .common, .kind = .parallel, .trim = " \t", .min = 1, .max = 4096, .forms = "a whole number from 1 to 4096, or auto (up to 8 lanes; the --parallel flag wins when present)" }, .{ .name = "TENSORFOLD_PRESSURE_CACHE_PERCENT", .scope = .common, .kind = .percent, .trim = " \t", .forms = "a whole percentage from 0 to 100" }, .{ .name = "TENSORFOLD_PREFIX_WAIT_MS", .scope = .common, .kind = .u32, .trim = " \t", .first_digit = true, .forms = "whole milliseconds from 0 to 4294967295 (0 disables waiting)" }, + .{ .name = "TENSORFOLD_PRIORITY_AGE_MS", .scope = .common, .kind = .u32, .trim = " \t", .first_digit = true, .forms = "whole milliseconds from 0 to 4294967295 (0 keeps foreground-first FIFO)" }, .{ .name = "TENSORFOLD_RESTORE_PREFETCH", .scope = .common, .kind = .u64, .trim = " \t", .first_digit = true, .forms = "a whole unsigned 64-bit read count (0 disables reading ahead; capped at 65536)" }, .{ .name = "TENSORFOLD_RESTORE_PREFETCH_GIB", .scope = .common, .kind = .u64, .trim = " \t", .first_digit = true, .forms = "a whole unsigned 64-bit GiB count (capped at 16777216)" }, .{ .name = "TENSORFOLD_RESTORE_PREFETCH_MS", .scope = .common, .kind = .u64, .trim = " \t", .first_digit = true, .forms = "whole unsigned 64-bit milliseconds (capped at 1099511627776)" }, @@ -68,15 +70,19 @@ pub const rules = [_]Rule{ .{ .name = "TF_DSPINE_WINDOW", .scope = .cuda, .kind = .size, .min = 16, .max = 8192, .forms = "a whole row count from 16 to 8192, at most the DSpine drafter's own sliding_window" }, .{ .name = "TF_DRAFT_NODES", .scope = .cuda, .kind = .size, .forms = "a whole nonnegative native-size node count (capped by the drafter's window)" }, .{ .name = "TF_QMMF_HALF_BELOW", .scope = .cuda, .kind = .size, .forms = "a whole nonnegative native-size block count (0 disables half tiles)" }, + .{ .name = "TF_QMMF_HALF_BN", .scope = .cuda, .kind = .flag, .forms = "0 or 1 (1 adds FP4, FP8 and FP8G half tiles below two blocks an SM; default 0)" }, .{ .name = "TF_HY4_MEM_FLOOR_GIB", .scope = .cuda, .kind = .size, .forms = "whole GiB of MemAvailable below which the Hy4-flash CUDA loader stops (default 10)" }, // Qwen 3.5 CUDA and HIP settings, read through this table: .{ .name = "TENSORFOLD_MEMORY_RESERVE_GIB", .scope = .cuda, .kind = .real, .forms = "a finite GiB amount (the HIP admission's floor and the memory's size still bound it)" }, .{ .name = "TENSORFOLD_HIP_MEMORY_LIMIT_GB", .scope = .cuda, .kind = .real, .forms = "a finite GiB amount (the HIP admission still fits its byte count in a 64-bit size)" }, .{ .name = "TF_QWEN_KEEP_LATE", .scope = .cuda, .kind = .flag, .forms = "0 or 1 (default 0)" }, + .{ .name = "TF_Q35_GROUP_PROJ", .scope = .cuda, .kind = .flag, .forms = "0 or 1 (1 groups same-input ModelOpt decode projections in one launch; default 0)" }, .{ .name = "TF_QWEN_KV_PAGE_TEST", .scope = .cuda, .kind = .size, .min = 1, .max = 2147483647, .forms = "a whole page size from 1 to 2147483647 (unset: off)" }, .{ .name = "TF_COST_KEY_TRACE", .scope = .cuda, .kind = .flag, .forms = "0 or 1 (default 0)" }, .{ .name = "TF_TIMING", .scope = .cuda, .kind = .flag, .forms = "0 or 1 (default 0)" }, .{ .name = "TF_NO_TREES", .scope = .cuda, .kind = .flag, .forms = "0 or 1 (default 0; 1 keeps the CUDA drafter's chains only)" }, + .{ .name = "TF_DFLASH_QL_SPAN", .scope = .cuda, .kind = .flag, .forms = "0 or 1 (default 0; 1 drafts a ModelOpt NVFP4 or FP8 head over the DFlash2 spans)" }, + .{ .name = "TF_DFLASH_GRAPH", .scope = .cuda, .kind = .flag, .forms = "0 or 1 (default 0; 1 replays DFlash2 holds and live absorbs from CUDA graphs)" }, .{ .name = "TF_MTP_TREES", .scope = .cuda, .kind = .flag, .forms = "0 or 1 (default 0; opt in to sampled MTP tree drafting)" }, .{ .name = "TF_MTP_BATCH", .scope = .cuda, .kind = .flag, .forms = "0 or 1 (default 1; 0 keeps one stream at a time)" }, .{ .name = "TF_QWEN_POOL_LOG", .scope = .cuda, .kind = .flag, .forms = "0 or 1 (default 0)" }, @@ -102,6 +108,7 @@ pub const rules = [_]Rule{ .{ .name = "TF_HEAD_GEOMETRY", .scope = .metal, .kind = .size, .forms = "a whole nonnegative native-size geometry count" }, .{ .name = "TF_PROMPT_ROWS", .scope = .metal, .kind = .prompt, .forms = "a multiple of 16 from 128 to 2048 for native serving" }, .{ .name = "TF_ANE_COLUMNS", .scope = .metal, .kind = .u32, .forms = "a whole column count from 0 to 4294967295 (0 disables the share)" }, + .{ .name = "TF_LFM3_METAL_WARM_TURNS", .scope = .metal, .kind = .flag, .forms = "0 or 1 (default 0)" }, .{ .name = "TF_METAL4", .scope = .metal, .kind = .flag, .forms = "0 or 1 (0 keeps Metal 3; 1 sends the work of a family that supports it through Metal 4 on macOS 26 and later, the default for DeepSeek-V4.1 there)" }, .{ .name = "TF_METAL4_TIMELINE", .scope = .metal, .kind = .u32, .forms = "a whole round count from 0 to 4294967295 (0, the default, stamps nothing; n stamps every stage of n rounds of each kind on a Metal 4 queue and logs them)" }, .{ .name = "TF_DSV41_ROUND_PROF", .scope = .metal, .kind = .flag, .forms = "0 or 1 (1 logs DeepSeek-V4.1 Metal decode rounds' host and GPU milliseconds by rows)" }, @@ -109,11 +116,15 @@ pub const rules = [_]Rule{ .{ .name = "GLM_EHPROJ_NAX", .scope = .metal, .kind = .flag, .forms = "0 or 1 (0 serves GLM's MTP eh_proj on the scalar kernel)" }, .{ .name = "TF_FLASHNEXT_GROUPED_ROWS", .scope = .metal, .kind = .size, .forms = "0 (never) or the rows, 1 to 32, from which a window's experts run grouped", .max = 32 }, .{ .name = "TF_FN_GX_GATEUP_MB2", .scope = .metal, .kind = .flag, .forms = "0 or 1 (1: Flash Next's grouped gate/up decodes an expert's weights once for two rows; same output bits)" }, + .{ .name = "TF_FN_GX_SHARED", .scope = .metal, .kind = .flag, .forms = "0 or 1 (1: Flash Next shared rounds use eligible grouped experts with the per-row kernels' bits)" }, .{ .name = "TF_QWEN27_SLOT_RESUME", .scope = .metal, .kind = .flag, .forms = "0 or 1 (0 stops slot 0 resuming a later prompt; unset or blank keeps it on)" }, .{ .name = "TF_QWEN27_SHARED_PREFIX", .scope = .metal, .kind = .flag, .forms = "0 or 1 (0 keeps the 27B's cached keys on the tail kernel before M5; unset or blank is 1)" }, .{ .name = "TF_QWEN27_METAL_KV_PAGES", .scope = .metal, .kind = .flag, .forms = "0 or 1 (1 puts the 27B's keys and values in core-pool pages; unset or blank is 0)" }, + .{ .name = "TF_Q27_MTP_GPU_PICK", .scope = .metal, .kind = .flag, .forms = "0 or 1 (1 fuses the 27B MTP absorb and picks drafts on the GPU; unset or blank is 0)" }, .{ .name = "TF_QWEN27_JOIN", .scope = .metal, .kind = .flag, .forms = "0 or 1 (1 runs a window's rows in pairs in the 27B's decode tail before M5; unset or blank is 1)" }, + .{ .name = "TF_QWEN27_TIED_HEAD", .scope = .metal, .kind = .flag, .forms = "0 or 1 (1 lets a dense Qwen with a tied head load, its head read from the embedding; unset or blank is 0)" }, .{ .name = "TF_QWEN35_METAL_KV_PAGES", .scope = .metal, .kind = .flag, .forms = "0 or 1 (1 puts the streams' keys and values in core-pool pages; unset or blank is 0)" }, + .{ .name = "TF_QWEN35_CHUNK", .scope = .metal, .kind = .size, .min = 1, .forms = "whole prompt rows a prefill pass, 1 to the served context window (default 128)" }, .{ .name = "TF_DSV41_SMALL", .scope = .metal, .kind = .flag, .forms = "0 or 1 (1 reads a DeepSeek-V4.1 Metal checkpoint's config at its own small shapes)" }, .{ .name = "TF_DSV41_ASSETS", .scope = .metal, .kind = .path, .forms = "a directory path without control characters holding DeepSeek-V4.1's Engram token map" }, .{ .name = "TF_DSV41_ENGRAM_DIR", .scope = .metal, .kind = .path, .forms = "a directory path without control characters holding DeepSeek-V4.1's packed Engram tables" }, @@ -157,6 +168,7 @@ pub const rules = [_]Rule{ .{ .name = "TF_MINIMAX_WORLD", .scope = .minimax_m3, .kind = .u32, .forms = "a whole world size from 1", .flag = "--tp", .retire = alias_retire }, .{ .name = "TF_NEMOTRON_RANK", .scope = .nemotron, .kind = .u32, .forms = "a whole rank from 0", .flag = "--rank", .retire = alias_retire }, .{ .name = "TF_NEMOTRON_WORLD", .scope = .nemotron, .kind = .u32, .forms = "a whole world size from 1", .flag = "--tp", .retire = alias_retire }, + .{ .name = "TF_NEMOTRON_WIDE_ROUNDS", .scope = .nemotron, .kind = .flag, .forms = "0 or 1 (default 0)" }, .{ .name = "TF_GLM_HOST_CACHE", .scope = .glm, .kind = .flag, .forms = "0 or 1" }, .{ .name = "TF_GLM_VISION_HOST", .scope = .glm, .kind = .flag, .forms = "0 or 1" }, .{ .name = "TF_GLM_PROF", .scope = .glm, .kind = .flag, .forms = "0 or 1" }, @@ -165,6 +177,7 @@ pub const rules = [_]Rule{ .{ .name = "TF_QWEN_PDL", .scope = .common, .kind = .flag, .forms = "0 or 1" }, .{ .name = "TF_GLM_PROMPT_STEPS", .scope = .glm, .kind = .flag, .forms = "0 or 1" }, .{ .name = "TF_GLM_SHARED", .scope = .glm, .kind = .flag, .forms = "0 or 1" }, + .{ .name = "TF_GLM_WIDE_EXPERT_TILE", .scope = .glm, .kind = .flag, .forms = "0 or 1 (default 0)" }, .{ .name = "TF_GLM_DSEL", .scope = .glm, .kind = .flag, .forms = "0 or 1" }, .{ .name = "TF_GLM_DSCORES", .scope = .glm, .kind = .flag, .forms = "0 or 1" }, .{ .name = "TF_GLM_MOE_DIRECT", .scope = .glm, .kind = .flag, .forms = "0 or 1" }, @@ -264,7 +277,9 @@ pub const rules = [_]Rule{ .{ .name = "TF_FLASHNEXT_KEEP_INPASS", .scope = .flashnext, .kind = .flag, .forms = "0 or 1 (default 1)" }, .{ .name = "TF_FLASHNEXT_FIRST_EARLY", .scope = .flashnext, .kind = .flag, .forms = "0 or 1 (default 1)" }, .{ .name = "TF_FLASHNEXT_GPU_TOPK", .scope = .flashnext, .kind = .flag, .forms = "0 or 1 (default 1)" }, + .{ .name = "TF_FLASHNEXT_BATCH_GDN_WIDE", .scope = .flashnext, .kind = .flag, .forms = "0 or 1 (default 0)" }, .{ .name = "TF_FLASHNEXT_GDN_FUSED", .scope = .flashnext, .kind = .flag, .forms = "0 or 1 (default 1)" }, + .{ .name = "TF_FLASHNEXT_GDN_CHAIN_TPR", .scope = .flashnext, .kind = .flag, .forms = "0 or 1 (default 0)" }, .{ .name = "TF_FLASHNEXT_GDN_LANES", .scope = .flashnext, .kind = .flag, .forms = "0 or 1 (default 1)" }, .{ .name = "TF_FLASHNEXT_BATCH_HEADS", .scope = .flashnext, .kind = .flag, .forms = "0 or 1 (default 1)" }, .{ .name = "TF_FLASHNEXT_SAMPLED_HEADS", .scope = .flashnext, .kind = .flag, .forms = "0 or 1 (default 1)" }, diff --git a/zig/src/platform/environment_flashnext_test.zig b/zig/src/platform/environment_flashnext_test.zig index cbf82150955..82ef4864a33 100644 --- a/zig/src/platform/environment_flashnext_test.zig +++ b/zig/src/platform/environment_flashnext_test.zig @@ -33,13 +33,13 @@ fn check(name: []const u8, raw: []const u8, valid: bool) !void { try t.expect(std.mem.endsWith(u8, why.?, e.rule(name).forms)); } -test "Flash Next strict env: the table holds all 37 settings: 25 switches, 9 integers, 1 real, 2 structured" { +test "Flash Next strict env: the table holds all 39 settings: 27 switches, 9 integers, 1 real, 2 structured" { var counts: [4]usize = @splat(0); for (e.rules) |r| if (r.scope == .flashnext) { try t.expect(std.mem.startsWith(u8, r.name, "TF_FLASHNEXT_")); counts[@backingInt(group(r))] += 1; }; - try t.expectEqual([4]usize{ 25, 9, 1, 2 }, counts); + try t.expectEqual([4]usize{ 27, 9, 1, 2 }, counts); } test "Flash Next strict env: unset and blank settings both read as the caller's default" { diff --git a/zig/src/platform/environment_test.zig b/zig/src/platform/environment_test.zig index 5a182df0c21..9f4ac21c05c 100644 --- a/zig/src/platform/environment_test.zig +++ b/zig/src/platform/environment_test.zig @@ -43,14 +43,19 @@ const valid = [_]Case{ .{ .name = "TF_FLASHNEXT_BATCH_DRAWS", .raw = "1", .n = 1 }, .{ .name = "TF_CUDA_POOL_AFTER_WARMUP", .raw = "0", .n = 0 }, .{ .name = "TF_CUDA_POOL_AFTER_WARMUP", .raw = "1", .n = 1 }, + .{ .name = "TF_LFM3_METAL_WARM_TURNS", .raw = "0", .n = 0 }, + .{ .name = "TF_LFM3_METAL_WARM_TURNS", .raw = "1", .n = 1 }, .{ .name = "TF_FLASHNEXT_READOUT_FUSED", .raw = "0", .n = 0 }, .{ .name = "TF_FLASHNEXT_READOUT_FUSED", .raw = "1", .n = 1 }, + .{ .name = "TF_QWEN35_ATTN_ALL_ROWS", .raw = "0", .n = 0 }, + .{ .name = "TF_QWEN35_ATTN_ALL_ROWS", .raw = "1", .n = 1 }, .{ .name = "TENSORFOLD_VIDEO_TOKENS", .raw = "0", .n = 0 }, .{ .name = "TENSORFOLD_VIDEO_TOKENS", .raw = "18446744073709551615", .n = std.math.maxInt(u64) }, .{ .name = "TENSORFOLD_MAX_PDF_PAGES", .raw = "4294967295", .n = std.math.maxInt(u32) }, .{ .name = "TENSORFOLD_PRESSURE_CACHE_PERCENT", .raw = "\t100 ", .n = 100 }, .{ .name = "TENSORFOLD_PRESSURE_CACHE_PERCENT", .raw = "0", .n = 0 }, .{ .name = "TENSORFOLD_PREFIX_WAIT_MS", .raw = "\t4294967295 ", .n = std.math.maxInt(u32) }, + .{ .name = "TENSORFOLD_PRIORITY_AGE_MS", .raw = " 30000\t", .n = 30000 }, .{ .name = "TENSORFOLD_PULL_CONNECT_SECONDS", .raw = " 30\t", .n = 30 }, .{ .name = "TENSORFOLD_PULL_STALL_SECONDS", .raw = "4294967295", .n = std.math.maxInt(u32) }, .{ .name = "TENSORFOLD_RESTORE_PREFETCH", .raw = " 0\t", .n = 0 }, @@ -78,6 +83,8 @@ const valid = [_]Case{ .{ .name = "TF_QWEN_KEEP_LATE", .raw = "1", .n = 1 }, .{ .name = "TF_QWEN_PDL", .raw = "0", .n = 0 }, .{ .name = "TF_QWEN_PDL", .raw = "1", .n = 1 }, + .{ .name = "TF_Q35_GROUP_PROJ", .raw = "0", .n = 0 }, + .{ .name = "TF_Q35_GROUP_PROJ", .raw = "1", .n = 1 }, .{ .name = "TF_QWEN_KV_PAGE_TEST", .raw = "1", .n = 1 }, .{ .name = "TF_QWEN_KV_PAGE_TEST", .raw = "2147483647", .n = 2147483647 }, .{ .name = "TF_COST_KEY_TRACE", .raw = "0", .n = 0 }, @@ -86,6 +93,10 @@ const valid = [_]Case{ .{ .name = "TF_TIMING", .raw = "1", .n = 1 }, .{ .name = "TF_NO_TREES", .raw = "0", .n = 0 }, .{ .name = "TF_NO_TREES", .raw = "1", .n = 1 }, + .{ .name = "TF_DFLASH_QL_SPAN", .raw = "0", .n = 0 }, + .{ .name = "TF_DFLASH_QL_SPAN", .raw = "1", .n = 1 }, + .{ .name = "TF_DFLASH_GRAPH", .raw = "0", .n = 0 }, + .{ .name = "TF_DFLASH_GRAPH", .raw = "1", .n = 1 }, .{ .name = "TF_MTP_TREES", .raw = "0", .n = 0 }, .{ .name = "TF_MTP_TREES", .raw = "1", .n = 1 }, .{ .name = "TF_MTP_BATCH", .raw = "0", .n = 0 }, @@ -104,6 +115,8 @@ const valid = [_]Case{ .{ .name = "TF_DRAFT_NODES", .raw = "0", .n = 0 }, .{ .name = "TF_DRAFT_NODES", .raw = "64", .n = 64 }, .{ .name = "TF_QMMF_HALF_BELOW", .raw = "0", .n = 0 }, + .{ .name = "TF_QMMF_HALF_BN", .raw = "0", .n = 0 }, + .{ .name = "TF_QMMF_HALF_BN", .raw = "1", .n = 1 }, .{ .name = "TF_HY4_MEM_FLOOR_GIB", .raw = "10", .n = 10 }, .{ .name = "TENSORFOLD_PROMPT_CACHE_KEEP_OTHERS", .raw = "0", .n = 0 }, .{ .name = "TENSORFOLD_PROMPT_CACHE_KEEP_OTHERS", .raw = "1", .n = 1 }, @@ -118,6 +131,8 @@ const valid = [_]Case{ .{ .name = "TF_MINIMAX_WORLD", .raw = "2", .n = 2 }, .{ .name = "TF_NEMOTRON_RANK", .raw = "0", .n = 0 }, .{ .name = "TF_NEMOTRON_WORLD", .raw = "4294967295", .n = 4294967295 }, + .{ .name = "TF_NEMOTRON_WIDE_ROUNDS", .raw = "0", .n = 0 }, + .{ .name = "TF_NEMOTRON_WIDE_ROUNDS", .raw = "1", .n = 1 }, .{ .name = "TF_ROCE_HCA", .raw = "rocep1s0f0,rocep1s0f1", .n = 2 }, .{ .name = "TF_ROCE_HCA", .raw = "=mlx5_0:1", .n = 1 }, .{ .name = "TF_DRAMA_PREFILL_ROWS", .raw = " 128 ", .n = 128 }, @@ -126,6 +141,8 @@ const valid = [_]Case{ .{ .name = "TF_FLASHNEXT_GROUPED_ROWS", .raw = "32", .n = 32 }, .{ .name = "TF_FN_GX_GATEUP_MB2", .raw = "0", .n = 0 }, .{ .name = "TF_FN_GX_GATEUP_MB2", .raw = "1", .n = 1 }, + .{ .name = "TF_FN_GX_SHARED", .raw = "0", .n = 0 }, + .{ .name = "TF_FN_GX_SHARED", .raw = "1", .n = 1 }, .{ .name = "TF_QWEN35_CHUNK_SOLO", .raw = "8192", .n = 8192 }, .{ .name = "TF_QWEN35_CHUNK_SOLO", .raw = "6144", .n = 6144 }, .{ .name = "TF_GEMMA4_CHUNK_SOLO", .raw = "2048", .n = 2048 }, @@ -144,6 +161,8 @@ const valid = [_]Case{ .{ .name = "TF_Q27_DRAFT_SLOTS", .raw = "4294967295", .n = std.math.maxInt(u32) }, .{ .name = "TF_Q27_DFLASH_ABSORB_BATCH", .raw = "0", .n = 0 }, .{ .name = "TF_Q27_DFLASH_ABSORB_BATCH", .raw = "1", .n = 1 }, + .{ .name = "TF_Q27_MTP_GPU_PICK", .raw = "0", .n = 0 }, + .{ .name = "TF_Q27_MTP_GPU_PICK", .raw = "1", .n = 1 }, .{ .name = "TF_HEAD_GEOMETRY", .raw = "0", .n = 0 }, .{ .name = "TF_PROMPT_ROWS", .raw = "128", .n = 128 }, .{ .name = "TF_PROMPT_ROWS", .raw = "2048", .n = 2048 }, @@ -161,8 +180,12 @@ const valid = [_]Case{ .{ .name = "TF_QWEN27_METAL_KV_PAGES", .raw = "1", .n = 1 }, .{ .name = "TF_QWEN27_JOIN", .raw = "0", .n = 0 }, .{ .name = "TF_QWEN27_JOIN", .raw = "1", .n = 1 }, + .{ .name = "TF_QWEN27_TIED_HEAD", .raw = "0", .n = 0 }, + .{ .name = "TF_QWEN27_TIED_HEAD", .raw = "1", .n = 1 }, .{ .name = "TF_QWEN35_METAL_KV_PAGES", .raw = "0", .n = 0 }, .{ .name = "TF_QWEN35_METAL_KV_PAGES", .raw = "1", .n = 1 }, + .{ .name = "TF_QWEN35_CHUNK", .raw = "128", .n = 128 }, + .{ .name = "TF_QWEN35_CHUNK", .raw = "512", .n = 512 }, .{ .name = "XPU_A8_BITS", .raw = "4", .n = 4 }, .{ .name = "XPU_A8_BITS", .raw = "8", .n = 8 }, .{ .name = "XPU_TP", .raw = "1", .n = 1 }, @@ -285,6 +308,8 @@ test "environment: range, enum, whitespace and native prompt geometry refusals a .{ "TF_Q27_POCKET_OFF", "no\ncontrol" }, .{ "TF_QWEN_KEEP_LATE", "2" }, .{ "TF_TIMING", "2" }, .{ "TF_NO_TREES", "true" }, .{ "TF_GEMMA4_ARGMAX_GRAPH", "2" }, .{ "TF_GEMMA4_ARGMAX_GRAPH", "on" }, + .{ "TF_Q35_GROUP_PROJ", "2" }, .{ "TF_Q35_GROUP_PROJ", "on" }, + .{ "TF_QMMF_HALF_BN", "2" }, .{ "TF_QMMF_HALF_BN", "on" }, .{ "TF_MTP_TREES", "yes" }, .{ "TF_MTP_BATCH", "off" }, .{ "TF_QWEN_POOL_LOG", "true" }, .{ "TF_COST_KEY_TRACE", "on" }, .{ "TF_COST_KEY_TRACE", "on" }, .{ "TF_ROCE_HCA", "rocep1s0f0,roceP2p1s0f0,rocep1s0f1" }, @@ -450,7 +475,7 @@ test "environment: a legacy alias is checked only while its canonical name is un } test "environment: the Metal Qwen and slide-learning switches take their forms, read blank as unset and name a refusal" { - const flags = [_][:0]const u8{ "TF_QWEN27_SLOT_RESUME", "TF_QWEN27_SHARED_PREFIX", "TF_QWEN27_METAL_KV_PAGES", "TF_QWEN27_JOIN", "TF_QWEN35_METAL_KV_PAGES", "TF_SLIDE_TAKE_OUT_CHECK", "TF_SLIDE_TAP_CHECK" }; + const flags = [_][:0]const u8{ "TF_Q27_MTP_GPU_PICK", "TF_QWEN27_SLOT_RESUME", "TF_QWEN27_SHARED_PREFIX", "TF_QWEN27_METAL_KV_PAGES", "TF_QWEN27_JOIN", "TF_QWEN27_TIED_HEAD", "TF_QWEN35_METAL_KV_PAGES", "TF_SLIDE_TAKE_OUT_CHECK", "TF_SLIDE_TAP_CHECK" }; for (flags) |name| { try t.expectEqual(@as(?u64, 0), try e.parse(name, "0")); try t.expectEqual(@as(?u64, 1), try e.parse(name, "1")); @@ -468,7 +493,9 @@ test "environment: the Metal Qwen and slide-learning switches take their forms, try t.expect(!(try e.value(bool, "TF_QWEN27_SLOT_RESUME", "0", true))); try t.expect(!(try e.value(bool, "TF_QWEN27_METAL_KV_PAGES", null, false))); try t.expect(try e.value(bool, "TF_QWEN27_JOIN", null, true) and !(try e.value(bool, "TF_QWEN27_JOIN", "0", true))); + try t.expect(!(try e.value(bool, "TF_QWEN27_TIED_HEAD", null, false)) and try e.value(bool, "TF_QWEN27_TIED_HEAD", "1", false)); try t.expect(try e.value(bool, "TF_QWEN35_METAL_KV_PAGES", "1", false)); + try t.expect(!(try e.value(bool, "TF_Q27_MTP_GPU_PICK", null, false)) and try e.value(bool, "TF_Q27_MTP_GPU_PICK", "1", false)); } test "rank aliases name their flag and refuse from their retirement release" { diff --git a/zig/src/qwen27_memory_test.zig b/zig/src/qwen27_memory_test.zig index 5fbd5181755..799e765d8bd 100644 --- a/zig/src/qwen27_memory_test.zig +++ b/zig/src/qwen27_memory_test.zig @@ -144,3 +144,127 @@ test "qwen27 memory: a refusal advises lowering parallel, the raise, or lowering try std.testing.expectEqualStrings(c.text, try std.fmt.bufPrint(&buf, "{f}", .{c.advice})); } } + +const kv_grow = @import("families/qwen27/kv_grow.zig"); + +test "qwen27 memory: grow-as-used K/V is off unless TF_Q27_KV_GROW names a 16-row step" { + try std.testing.expectEqual(@as(?u32, null), try kv_grow.step(null)); + try std.testing.expectEqual(@as(?u32, null), try kv_grow.step("0")); + try std.testing.expectEqual(@as(?u32, 4096), try kv_grow.step("4096")); + try std.testing.expectEqual(@as(?u32, 16), try kv_grow.step("16")); + for ([_][]const u8{ "", "-1", "15", "4097", "x", "99999999999" }) |text| try std.testing.expectError(error.BadKvGrowStep, kv_grow.step(text)); +} + +test "qwen27 memory: a slot starts at one step and grows to the need, a quarter more, or the context" { + // first rows: one step, never past the context + try std.testing.expectEqual(@as(u32, 4096), kv_grow.first(4096, 32784)); + try std.testing.expectEqual(@as(u32, 2000), kv_grow.first(4096, 2000)); + // enough already: unchanged + try std.testing.expectEqual(@as(u32, 4096), kv_grow.rows(4096, 4096, 4096, 32784)); + try std.testing.expectEqual(@as(u32, 4096), kv_grow.rows(4096, 10, 4096, 32784)); + // the need rounded up to the step + try std.testing.expectEqual(@as(u32, 8192), kv_grow.rows(4096, 4097, 4096, 32784)); + try std.testing.expectEqual(@as(u32, 32768), kv_grow.rows(4096, 30001, 4096, 32784)); + // a quarter more than held when that is past the rounded need + try std.testing.expectEqual(@as(u32, 20480), kv_grow.rows(16384, 16385, 4096, 32784)); + try std.testing.expectEqual(@as(u32, 20480), kv_grow.rows(16384, 16385, 16, 32784)); + // never past the context + try std.testing.expectEqual(@as(u32, 32784), kv_grow.rows(32768, 32780, 4096, 32784)); + try std.testing.expectEqual(@as(u32, 32784), kv_grow.rows(28672, 28673, 4096, 32784)); +} + +test "qwen27 memory: an emptied slot takes its prompt's rows at once, at least one step, at most the context" { + try std.testing.expectEqual(@as(u32, 4096), kv_grow.admitted(1, 4096, 131088)); + try std.testing.expectEqual(@as(u32, 4096), kv_grow.admitted(4096, 4096, 131088)); + try std.testing.expectEqual(@as(u32, 8192), kv_grow.admitted(4097, 4096, 131088)); + // one growth for a 65,536-token prompt, where growing from the first rows takes ten + try std.testing.expectEqual(@as(u32, 65536), kv_grow.admitted(65536, 4096, 131088)); + try std.testing.expectEqual(@as(u32, 131088), kv_grow.admitted(131080, 4096, 131088)); + try std.testing.expectEqual(@as(u32, 2000), kv_grow.admitted(64, 4096, 2000)); +} + +test "qwen27 memory: growing moves every K/V head to its place in the wider buffer" { + // 4 heads of dim 256 in bf16: head h starts at h * rows * 256 * 2 bytes + var moves: [4]kv_grow.Move = undefined; + const got = kv_grow.moves(&moves, 4, 256, 4096, 8192); + try std.testing.expectEqual(@as(usize, 4), got.len); + for (got, 0..) |m, h| { + try std.testing.expectEqual(h * 4096 * 256 * 2, m.from); + try std.testing.expectEqual(h * 8192 * 256 * 2, m.to); + try std.testing.expectEqual(@as(usize, 4096 * 256 * 2), m.len); + } + // the old buffer's bytes are exactly covered, the new head regions never overlap + try std.testing.expectEqual(@as(usize, 4 * 4096 * 256 * 2), got[3].from + got[3].len); + try std.testing.expect(got[2].to + got[2].len <= got[3].to); + // a slot's bytes at a row count, for the residency set and the memory receipts + try std.testing.expectEqual(@as(usize, 8 * 2 * 4096 * 1024 * 2), kv_grow.slotBytes(8, 1024, 4096)); +} + +const tap_ring = @import("families/qwen27/tap_ring.zig"); +const Ring = tap_ring.Ring; +const mtl_fake = @import("metal"); + +/// A ring that starts at `held` rows and grows by tap_ring.grow, as a parked slot's ring does. +const Growing = struct { + buf: mtl_fake.Buffer, + held: u32, + window: u32, + stride: usize, + asks: u32 = 0, + fn make(n: u32, stride: usize) !mtl_fake.Buffer { + const data = try std.testing.allocator.alignedAlloc(u8, .@"16", n * stride); + @memset(data, 0); + return .{ .id = n, .data = data }; + } + fn free(b: mtl_fake.Buffer) void { + std.testing.allocator.free(b.data); + } + fn run(ctx: *anyopaque, want: u32) anyerror!mtl_fake.Buffer { + const g: *Growing = @ptrCast(@alignCast(ctx)); + g.asks += 1; + if (want <= g.held) return g.buf; + const next = tap_ring.grownRows(g.held, want, 16, g.window); + const fresh = try make(next, g.stride); + tap_ring.carry(g.buf, fresh, g.held, g.stride); + free(g.buf); + g.buf = fresh; + g.held = next; + return fresh; + } +}; + +test "qwen27 memory: a growing taps ring holds the same rows at the same places as a whole-window ring" { + const window: u32 = 64; + const stride: usize = 4; + var whole_end: u64 = 0; + var grow_end: u64 = 0; + const whole_buf = try Growing.make(window, stride); + defer Growing.free(whole_buf); + var g = Growing{ .buf = try Growing.make(16, stride), .held = 16, .window = window, .stride = stride }; + defer Growing.free(g.buf); + const whole = Ring{ .buf = whole_buf, .end = &whole_end, .window = window, .stride = stride }; + var growing = Ring{ .buf = g.buf, .end = &grow_end, .window = window, .stride = stride, .grow = .{ .ctx = &g, .run = Growing.run } }; + const src = try Growing.make(128, stride); + defer Growing.free(src); + var next: u32 = 1; + for ([_]u32{ 5, 11, 1, 20, 30, 40 }) |n| { // past 16, 32 and the 64-row window: grows, then wraps + for (0..n) |i| std.mem.writeInt(u32, src.contents()[i * stride ..][0..4], next + @as(u32, @intCast(i)), .little); + next += n; + try whole.absorb(src, 0, n); + try growing.absorb(src, 0, n); + try std.testing.expectEqual(whole_end, grow_end); + const first = whole_end -| window; + for (first..whole_end) |pos| { + const at = (pos % window) * stride; + try std.testing.expectEqualSlices(u8, whole_buf.contents()[at..][0..stride], g.buf.contents()[at..][0..stride]); + } + } + try std.testing.expectEqual(window, g.held); // a wrapped ring holds the whole window + // a restore into the ring asks for its rows first; a held ring is not asked to grow + var restored = Ring{ .buf = g.buf, .end = &grow_end, .window = window, .stride = stride, .grow = .{ .ctx = &g, .run = Growing.run } }; + try restored.hold(200); + try std.testing.expectEqual(window, g.held); + try std.testing.expectEqual(@as(u32, 16), tap_ring.grownRows(16, 3, 16, 64)); + try std.testing.expectEqual(@as(u32, 48), tap_ring.grownRows(16, 33, 16, 64)); + try std.testing.expectEqual(@as(u32, 64), tap_ring.grownRows(48, 49, 16, 64)); +} diff --git a/zig/src/server/chat.zig b/zig/src/server/chat.zig index 9a0782625fd..2bea070c6e3 100644 --- a/zig/src/server/chat.zig +++ b/zig/src/server/chat.zig @@ -78,6 +78,7 @@ pub const Reply = struct { tool_calls_streamed: bool, native_tool_format: bool = false, native_calls: ?[]Value = null, + native_cut_calls: bool = false, // a native parser's calls were cut by the token cap: finish_reason stays length finish_reason: []const u8, prompt_tokens: usize, cached_tokens: usize, @@ -297,12 +298,13 @@ pub fn generate(srv: *Server, cx: *Cx, prepared: Prepared, sink: ?Sink, gone: an srv.release(preparing, null); // a background request waits only while a foreground one prepares preparing = false; var gen: Generation = .{ .srv = srv, .a = a, .box = &box, .id = id, .asked = input.cancel, .reply_id = input.id, .seed = if (request.sampling) |v| v.seed else null, .report_seed = input.choices > 1, .sink = sink, .thinking = prepared.reasoning or (srv.text.vtable.format != .kimi and srv.info.capability(.reasoning) and reply_text.isChannel(srv.markers)), .chat = input.prompt == null, .stops = .{ .strings = stops_opt.strings }, .ignore_eos = stops_opt.ignore_eos, .grammar = if (request.structure) |st| (if (st.after) |t| .{ .after = t } else .on) else .none, .max_tokens = request.max_tokens, .tools = input.tools, .token_ids = prepared.token_ids, .lp = if (request.logprobs != null) .{ .positions = if (sink) |s| s.tokens != null else false } else null, .loop_stop = request.loop_stop, .single = fields_mod.flag(input.fields, "tool_call_single") orelse false, .required = fields_mod.flag(input.fields, "tool_call_required") orelse false, .recover = input.prompt == null and request.structure == null, .deadline_ns = prepared.deadline_ns }; + gen.call_end = @import("chat_inkling2.zig").callEnd(srv, gen.required, request.structure); defer srv.noteRequest(prepared.prompt_len, cached_tokens.within(box.cached, prepared.prompt_len), gen.collected.items.len, box.stats.drafted, box.stats.accepted, box.stats.rounds, received, gen.first_ns, gen.last_ns, box.stats.prefill_seconds, if (box.stats.prefill_seconds != null) box.stats.queued_seconds else null); errdefer if (!gen.engine_done) gen.cancel(); // the engine writes to the mailbox until it says finished if (srv.recipients and input.prompt == null) gen.recipient = try recipient_reply.Reading.of(a, srv.text, request.prompt, input.tools, prepared.reasoning); const result: Failure!Reply = blk: { if (sink) |s| if (s.begin) |begin| begin(s.ctx, prepared.prompt_len) catch break :blk error.Cancelled; - if (sink != null and input.tools.len > 0 and srv.text.vtable.format != .kimi) gen.calls = tool_stream.Streamer.init(a, input.tools) catch |e| break :blk e; + if (sink != null and input.tools.len > 0 and srv.text.vtable.format != .kimi and !@import("chat_inkling2.zig").enabled(srv)) gen.calls = tool_stream.Streamer.init(a, input.tools) catch |e| break :blk e; gen.loop(gone) catch |e| break :blk e; break :blk gen.finish(cx, prepared.prompt_len, received, prepared.thinking, prepared.reasoning, effort, prepared.sampled, prepared.drafts); }; diff --git a/zig/src/server/chat_generation.zig b/zig/src/server/chat_generation.zig index 463888eb672..8d4256fa786 100644 --- a/zig/src/server/chat_generation.zig +++ b/zig/src/server/chat_generation.zig @@ -56,6 +56,7 @@ pub const Generation = struct { max_tokens: u32, single: bool, // parallel_tool_calls: false: a cut call is no call, so its prose ends as the whole reply's does required: bool = false, // tool_choice "required" or a named function: the reply must call a tool + call_end: bool = false, // Inkling 2's required call grammar: its end of message after a complete call ends the turn token_ids: bool, // "return_token_ids": the response's tensorfold block carries the reply's token ids tools: []const Value, calls: ?tool_stream.Streamer = null, @@ -63,6 +64,7 @@ pub const Generation = struct { collected: std.ArrayList(u32) = .empty, visible: reply_text.Incremental = .{}, kimi: ?@import("kimi_reply.zig").Stream = null, + inkling2: ?@import("inkling2_reply.zig").Stream = null, hidden: std.ArrayList(u8) = .empty, // reused for the answer without its call blocks streamed: reply_text.Shown = .{}, // what content streamed, kept apart from the decode buffer that grows under slices streamed_reasoning: reply_text.Shown = .{}, @@ -108,7 +110,11 @@ pub const Generation = struct { fn stopHit(g: *Generation) Allocator.Error!bool { if (g.stops.strings.len == 0) return false; const t = g.collected.items; - const tail = t[t.len -| g.stops.tail()..]; + // Inkling 2's byte tokens can spell one character in several: its window counts the stop's bytes + const inkling = @import("chat_inkling2.zig"); + const window = if (inkling.enabled(g.srv)) inkling.stopWindow(g.stops.strings) else g.stops.tail(); + const tail = t[t.len -| window..]; + if (inkling.enabled(g.srv)) return inkling.stopIn(g.a, g.srv.text, t, window, g.stops.strings); const text = try g.srv.text.decode(g.a, tail); for (g.stops.strings) |s| if (std.mem.indexOf(u8, text, s) != null) return true; return false; @@ -124,6 +130,9 @@ pub const Generation = struct { landed += 1; if (g.eos(t)) { g.reason = "stop"; + } else if (try @import("chat_inkling2.zig").endsBare(g, t)) { + g.reason = "stop"; + g.srv.engine.cancel(g.id); // an Inkling 2 grammar's call or text message ended: the turn ends there } else if (try g.stopHit()) { g.reason = "stop"; g.srv.engine.cancel(g.id); // the engine ends EOS and length itself; a stop string is the server's @@ -150,6 +159,7 @@ pub const Generation = struct { const all = try g.visible.extend(g.a, g.srv.text, reply_text.decodeText, fresh.tokens); if (g.visible.pending()) return; // a character still split across tokens if (g.srv.text.vtable.format == .kimi) return @import("chat_kimi.zig").stream(g, sink); + if (@import("chat_inkling2.zig").enabled(g.srv)) return @import("chat_inkling2.zig").stream(g, sink); const raw_visible = g.stops.visible(all, true); const text = try @import("tool_minimax.zig").dsml(g.a, raw_visible, g.tools); // MiniMax-M3's calls as DSML var answer = text; @@ -308,7 +318,8 @@ pub const Generation = struct { const finished_ns = nowNs(g.srv.io); const content_tokens = if (g.grammar.keepsTrailing(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 native = if (g.srv.text.vtable.format == .kimi) try @import("chat_kimi.zig").read(g, content_tokens, true) else null; + const inkling = @import("chat_inkling2.zig").enabled(g.srv); + const native: ?@import("native_reply.zig").Result = if (g.srv.text.vtable.format == .kimi) try @import("chat_kimi.zig").read(g, content_tokens, true) else if (inkling) try @import("chat_inkling2.zig").read(g, content_tokens, true) else null; const raw_visible = g.stops.visible(raw, false); const visible = if (native) |n| n.content else try @import("tool_minimax.zig").dsml(a, raw_visible, g.tools); const close_at: ?reply_text.Close = if (native == null and g.thinking) @@ -323,7 +334,7 @@ pub const Generation = struct { var reasoning: ?[]const u8 = null; const read = g.thinking or g.recipient != null; // the reply's split text is its content if (native) |n| { - const r = reply_text.pyStrip(n.reasoning); + const r = if (inkling) n.reasoning else reply_text.pyStrip(n.reasoning); reasoning = if (r.len > 0) r else null; } else if (read) { const split = if (g.recipient) |*r| try r.split(a, text, if (std.mem.eql(u8, reason, "length")) .cut else if (g.stops.matched(raw) != null) .stopped else .ended) else try reply_text.splitThinkingAt(a, text, true, g.srv.markers, close_at.?); @@ -380,6 +391,17 @@ pub const Generation = struct { try runtime.put(a, "seconds", .{ .float = @max(0, decode_s) }); // the reply's decode seconds, as tokens_per_second divides them try @import("grammar_metrics.zig").put(a, runtime, m.stats.grammar); if (m.stats.gpu_seconds) |gpu| try runtime.put(a, "gpu_seconds", .{ .float = gpu }); // TF_Q27_PROFILE only + // Inkling 2's refused calls are dropped, never shown: say how many, as kept calls are counted + if (inkling) if (native) |n| if (n.rejected_calls > 0) { + log.line("warning: dropped {d} malformed, unoffered or unfinished Inkling 2 tool calls", .{n.rejected_calls}); + try runtime.put(a, "rejected_tool_calls", try json.intValue(a, n.rejected_calls)); + }; + // a bare Inkling 2 reply's envelopes kept as content, reported and counted as the shared route reports them + if (inkling) if (native) |n| if (n.kept) |kept| { + log.line("warning: kept {d} malformed or unoffered tool envelopes as content", .{kept.rejected_envelopes}); + g.srv.metrics.keptToolCalls(g.srv.io, kept.kept_unoffered, kept.kept_malformed); + try runtime.put(a, "kept_tool_calls", try @import("openai_calls.zig").keptBlock(a, kept)); + }; try runtime.put(a, "prefill_seconds", if (m.stats.prefill_seconds) |p| .{ .float = p } else .null); const widths = try a.alloc(Value, m.widths.len); for (m.widths, widths) |w, *slot| slot.* = try json.intValue(a, w); @@ -429,6 +451,7 @@ pub const Generation = struct { .tool_calls_streamed = g.calls != null and g.calls.?.streamed, .native_tool_format = native != null, .native_calls = if (native) |n| n.calls else null, + .native_cut_calls = if (native) |n| n.cut_calls else false, .finish_reason = reason, .prompt_tokens = prompt_len, .cached_tokens = cached_tokens.within(m.cached, prompt_len), diff --git a/zig/src/server/chat_inkling2.zig b/zig/src/server/chat_inkling2.zig new file mode 100644 index 00000000000..92b93b18e28 --- /dev/null +++ b/zig/src/server/chat_inkling2.zig @@ -0,0 +1,233 @@ +//! Inkling 2's release block grammar on chat replies; raw completions remain literal. +const std = @import("std"); +const reply_text = @import("reply_text.zig"); +const native_reply = @import("native_reply.zig"); +const parser = @import("inkling2_reply.zig"); +const chat = @import("chat.zig"); +const api = @import("engine_api"); +const Allocator = std.mem.Allocator; + +/// Only HfText's config.json model_type sets this, from the family's two: Small's and Mini's; aliases do not. +pub fn enabled(srv: anytype) bool { + return srv.text.native_inkling2; +} + +/// A required call grammar's ends: the eos ids, and on Inkling 2 the end of the call's message. +pub fn grammarEnds(srv: anytype, a: Allocator, eos: []const u32) Allocator.Error![]const u32 { + if (!enabled(srv) or eos.len == 0) return eos; + const end = srv.text.tokenId("<|end_message|>") orelse return eos; + if (std.mem.indexOfScalar(u32, eos, end) != null) return eos; + return std.mem.concat(a, u32, &.{ eos, &.{end} }); +} + +/// A surviving required-tool grammar enables the complete-call stop, independently of the engine's EOS list. +pub fn callEnd(srv: anytype, required: bool, structure: ?api.Structure) bool { + if (!enabled(srv) or !required) return false; + const st = structure orelse return false; + return st.kind == .structural_tag and std.mem.eql(u8, st.field, "tool_choice"); +} + +/// Whether `t` ends a required call's bare reply: only after complete calls, with nothing open or refused after them. +pub fn endsBare(g: anytype, t: u32) Allocator.Error!bool { + if (!g.call_end or !g.chat or g.ignore_eos) return false; + if (g.srv.text.tokenId("<|end_message|>") != t) return false; + const before = g.collected.items[0 .. g.collected.items.len - 1]; + if (before.len == 0 or g.srv.text.tokenId("<|message_model|>") == before[0]) return false; + // an earlier bare end of message closes nothing and carries no text: only the other ids are the reply's + var kept: std.ArrayList(u32) = .empty; + for (before) |id| if (id != t) try kept.append(g.a, id); + const text = try g.srv.text.decode(g.a, kept.items); + const parsed = try @import("tool_parse.zig").parse(g.a, text, g.tools, null); + // an unclosed or malformed call, or any text, left beside the calls means the reply is not yet only calls + const rest = std.mem.trim(u8, parsed.content, " \t\r\n"); + return parsed.calls != null and parsed.rejected_envelopes == 0 and rest.len == 0; +} + +/// Tokens a stop check decodes: the longest stop's bytes plus 8, as a byte token can carry one byte of a character. +pub fn stopWindow(strings: []const []const u8) usize { + var longest: usize = 0; + for (strings) |stop| longest = @max(longest, stop.len); + return longest + 8; +} + +/// Whether the reply's newest `window` tokens hold a stop in its lossy decode, as the whole reply's decode reads them. +pub fn stopIn(a: Allocator, text: anytype, ids: []const u32, window: usize, strings: []const []const u8) Allocator.Error!bool { + const tail = ids[ids.len -| window..]; + var bytes: std.ArrayList(u8) = .empty; + for (tail) |id| { + const b = (try text.tokenBytes(a, id)) orelse return generic(a, text, tail, strings); + try bytes.appendSlice(a, b); + } + // the up to three bytes before the window, where a character owning its first bytes would begin + var before: std.ArrayList(u8) = .empty; + var k = ids.len - tail.len; + while (k > 0 and before.items.len < 3) { + k -= 1; + const b = (try text.tokenBytes(a, ids[k])) orelse return generic(a, text, tail, strings); + try before.insertSlice(a, 0, b); + } + const pre = before.items[before.items.len -| 3..]; + const skip = try owned(a, pre, bytes.items); + const empty: parser.RawText = .{}; + const view = try empty.view(a, bytes.items[skip..], true); + return firstStop(strings, view.text.items) != null; +} + +/// How many of `window`'s first bytes a character begun in `pre` owns: the last lead there, as `unicode.scan` reads it. +fn owned(a: Allocator, pre: []const u8, window: []const u8) Allocator.Error!usize { + var lead = pre.len; + while (lead > 0) { + lead -= 1; + if (pre[lead] & 0xC0 != 0x80) break; + } else return 0; + if (pre[lead] < 0x80) return 0; + const joined = try std.mem.concat(a, u8, &.{ pre[lead..], window[0..@min(3, window.len)] }); + const covered = @import("tokenizer").unicode.scan(joined, 0).len; + const inside = pre.len - lead; + return if (covered > inside) covered - inside else 0; +} + +fn generic(a: Allocator, text: anytype, tail: []const u32, strings: []const []const u8) Allocator.Error!bool { + const decoded = try text.decode(a, tail); + return firstStop(strings, decoded) != null; +} + +/// Where the first stop string starts in the raw text: the generation stops there and reports it. +fn firstStop(strings: []const []const u8, raw: []const u8) ?usize { + var first: ?usize = null; + for (strings) |stop| if (std.mem.indexOf(u8, raw, stop)) |at| { + if (first == null or at < first.?) first = at; + }; + return first; +} + +/// Where a tail of `raw` that could begin a stop string starts, held while the reply grows; null: none could. +fn held(strings: []const []const u8, raw: []const u8) ?usize { + var start: ?usize = null; + for (strings) |stop| { + var size = @min(stop.len -| 1, raw.len); + while (size > 0) : (size -= 1) if (std.mem.endsWith(u8, raw, stop[0..size])) { + if (start == null or raw.len - size < start.?) start = raw.len - size; + break; + }; + } + return start; +} + +/// The reply as its raw text shows it before byte `at`, where a stop starts: whole tokens, then part of one. +fn cut(g: anytype, ids: []const u32, at: usize) Allocator.Error!?parser.Stream { + var s = try parser.Stream.init(g.a, g.srv.text); + var offset: usize = 0; + for (ids, 0..) |id, k| { + const bytes = (try g.srv.text.tokenBytes(g.a, id)) orelse return null; + if (offset + bytes.len > at) { + _ = try s.extend(ids[0..k], g.tools); + try s.partial(id, bytes[0 .. at - offset]); + return s; + } + offset += bytes.len; + } + _ = try s.extend(ids, g.tools); + return s; +} + +/// The reply ended on its token cap: a call it was writing is returned cut, as the shared route returns one. +fn atLength(g: anytype) bool { + if (comptime !@hasField(@TypeOf(g.*), "box")) { + return false; // a test's stand-in generation has no engine box + } else { + if (g.deadline_hit) return false; + if (g.reason) |r| return std.mem.eql(u8, r, "length"); + return g.box.reason == .length; + } +} + +/// The request's parallel_tool_calls: false; a test's stand-in generation has none. +fn single(g: anytype) bool { + return if (comptime @hasField(@TypeOf(g.*), "single")) g.single else false; +} + +/// A bare reply's calls in the shared route's order: parsed calls, cut recovery at the cap, then the one-call filter. +fn bareCalls(g: anytype, result: *native_reply.Result) Allocator.Error!void { + const policy: @import("tool_policy.zig").Policy = .{ .single = single(g) }; + const parsed = try @import("tool_parse.zig").parse(g.a, result.content, g.tools, policy.maxCalls()); + if (parsed.rejected_envelopes > 0) result.kept = parsed; + const cut_calls = if (!policy.single and atLength(g)) try @import("tool_stream.zig").cutCalls(g.a, result.content, g.tools) else null; + if (cut_calls != null) { + result.content = try reply_text.cutProse(g.a, result.content); + result.cut_calls = true; + } + const found = cut_calls orelse parsed.calls orelse { + if (policy.single or parsed.calls != null) result.content = try policy.parsedContent(g.a, parsed.content); + return; + }; + if (cut_calls == null) result.content = try policy.parsedContent(g.a, parsed.content); + // numbered as the native calls are, so the whole reply and its stream give the same ids + for (found, 0..) |call, i| if (call == .object) try call.object.put(g.a, "id", .{ .string = try std.fmt.allocPrint(g.a, "call_{d}", .{i}) }); + result.calls = found; +} + +pub fn read(g: anytype, ids: []const u32, finished: bool) Allocator.Error!native_reply.Result { + const stopping = g.stops.strings.len > 0; + if (!g.chat) { + // the raw text: the generation's own incremental decode while it streams, decoded once when it is done + const raw = if (finished) try g.srv.text.decode(g.a, ids) else g.visible.text.items; + return .{ .content = g.stops.visible(raw, !finished), .reasoning = "", .calls = null, .reasoning_tokens = 0 }; + } + var whole: parser.Stream = undefined; + const s: *parser.Stream = if (g.inkling2) |*p| p else blk: { + whole = try parser.Stream.init(g.a, g.srv.text); + break :blk &whole; + }; + if (stopping and s.next == 0) s.track_raw = true; + var result = try s.extend(ids, g.tools); + if (finished) result = try s.done(); + if (stopping and s.raw_ok) { + // one coordinate: a stop is found in the lossy decode the generation checks, then placed in the exact bytes + const raw = s.raw.items; + const decoded = try s.decoded.view(g.a, raw, finished); + const text = decoded.text.items; + const stop = firstStop(g.stops.strings, text); + if (stop orelse (if (finished) null else held(g.stops.strings, text))) |found| if (found < text.len) { + var part = (try cut(g, ids, decoded.exact(raw.len, found))).?; + // usage counts every generated id: a stop cuts what is shown, never what was made + const tokens = result.reasoning_tokens; + result = try part.result(finished); + result.reasoning_tokens = tokens; + }; + } else if (stopping) { + // no token-local bytes: the raw decode places the stop, and the parsed channels are cut by it + const raw = if (finished) try g.srv.text.decode(g.a, ids) else g.visible.text.items; + if (firstStop(g.stops.strings, raw) != null) { + result.content = g.stops.visible(result.content, false); + result.reasoning = g.stops.visible(result.reasoning, false); + } else if (!finished) { + result.content = g.stops.visible(result.content, true); + result.reasoning = g.stops.visible(result.reasoning, true); + } + } + // a bare reply's calls are the shared parser's; bare as the shown parse reads it, past a stop the cut's + if (finished and result.bare and g.tools.len > 0) try bareCalls(g, &result); + // calls in a reply the token cap ended keep finish_reason length: the reply may have gone on + if (finished and result.calls != null and atLength(g)) result.cut_calls = true; + return result; +} + +pub fn stream(g: anytype, sink: chat.Sink) chat.Failure!void { + const ids = reply_text.stripTrailing(g.collected.items, g.srv.eos); + if (g.chat and g.inkling2 == null) g.inkling2 = try parser.Stream.init(g.a, g.srv.text); + const result = try read(g, ids, false); + // The persistent token cursor grows monotonically; calls wait for its final close. + const reason = g.streamed_reasoning.after(result.reasoning, true); + if (reason.len > 0) { + try g.streamed_reasoning.set(g.a, result.reasoning, reason); + try g.emit(sink, try reply_text.deltaOf(g.a, "reasoning_content", reason)); + } + // a bare reply offering tools may be a grammar's call envelope: its text waits for the finished reply + if (g.chat and g.tools.len > 0 and result.bare) return; + const delta = g.streamed.after(result.content, true); + if (delta.len > 0) { + try g.streamed.set(g.a, result.content, delta); + try g.emit(sink, .{ .string = delta }); + } +} diff --git a/zig/src/server/cli.zig b/zig/src/server/cli.zig index d56fe37acb8..16e7dcaded3 100644 --- a/zig/src/server/cli.zig +++ b/zig/src/server/cli.zig @@ -167,7 +167,7 @@ pub const flags = [_]Flag{ }; /// The variables this binary honours as the Python engine does, then the CUDA build's or the Metal build's. -pub const env = [_][]const u8{ "TENSORFOLD_API_KEY", "TENSORFOLD_NO_LIVE", "TENSORFOLD_SEED_SALT", "TENSORFOLD_REQUEST_LOG", "TENSORFOLD_REQUEST_JOURNAL", "TENSORFOLD_TOOL_ID_KEY_FILE", "TENSORFOLD_PHASE_METRICS", "TENSORFOLD_LIBPDFIUM", "TENSORFOLD_MAX_PDF_PAGES", "TENSORFOLD_DEVICE_CHECK", "HF_HOME", "HF_HUB_CACHE", "BRAVE_SEARCH_API_KEY" } ++ +pub const env = [_][]const u8{ "TENSORFOLD_API_KEY", "TENSORFOLD_NO_LIVE", "TENSORFOLD_SEED_SALT", "TENSORFOLD_REQUEST_LOG", "TENSORFOLD_REQUEST_JOURNAL", "TENSORFOLD_TOOL_ID_KEY_FILE", "TENSORFOLD_PHASE_METRICS", "TENSORFOLD_LIBPDFIUM", "TENSORFOLD_MAX_PDF_PAGES", "TENSORFOLD_DEVICE_CHECK", "HF_HOME", "HF_HUB_CACHE", "BRAVE_SEARCH_API_KEY", "TENSORFOLD_PARALLEL", "TENSORFOLD_VIDEO_TOKENS", "TENSORFOLD_PREFIX_WAIT_MS", "TENSORFOLD_PRIORITY_AGE_MS", "TENSORFOLD_PRESSURE_CACHE_PERCENT", "TENSORFOLD_RESTORE_PREFETCH", "TENSORFOLD_RESTORE_PREFETCH_GIB", "TENSORFOLD_RESTORE_PREFETCH_MS", "TENSORFOLD_PULL_CONNECT_SECONDS", "TENSORFOLD_PULL_STALL_SECONDS", "TF_CACHE_EVICT", "TF_SHARED_PRICE_LOG", "TF_STARTUP_RECEIPT", "TF_QWEN_PDL", "TENSORFOLD_LOG_TIME", "TENSORFOLD_TOOL_GRAMMAR", "TF_DSV41_TOOL_GRAMMAR", "TF_GLM_WORLD", "TF_GLM_CLEAR_THINKING", "TF_DSV41_SCHEMA_PROMPT", "TF_SLIDE_TAKE_OUT_CHECK" } ++ (if (cuda_build) [_][]const u8{ "TF_CUDA_DEVICE", "TF_CUDA_SEGMENTS", "TENSORFOLD_CUDA_KERNELS", "TENSORFOLD_MEMORY_RESERVE_GIB", "TENSORFOLD_CUDA_MEMORY_LIMIT_GB", "TENSORFOLD_P2P_DIAGNOSTICS", "TENSORFOLD_P2P_PROBE" } else [_][]const u8{}) ++ (if (builtin.os.tag == .macos) [_][]const u8{"TF_Q27_PROFILE"} else [_][]const u8{}); pub const Args = @import("cli_args.zig").Args; diff --git a/zig/src/server/cli_capabilities.zig b/zig/src/server/cli_capabilities.zig index 25cdb05edfc..83c1c3bd870 100644 --- a/zig/src/server/cli_capabilities.zig +++ b/zig/src/server/cli_capabilities.zig @@ -94,6 +94,22 @@ test "capability audit: environment list is a subset beside the complete profile try std.testing.expect(additional > 0); } +fn declaredEnv(name: []const u8) bool { + for (cli.env) |listed| if (std.mem.eql(u8, listed, name)) return true; + return false; +} + +test "capability audit: environment declares every variable serve reads" { + // The app's variables page accepts only this list (#3684): common rules plus serve's direct reads. + const e = @import("sys").environment; + for (e.rules) |r| { + if (r.scope != .common) continue; + try std.testing.expect(declaredEnv(r.name)); + } + const direct = [_][]const u8{ "TENSORFOLD_LOG_TIME", "TENSORFOLD_TOOL_GRAMMAR", "TF_DSV41_TOOL_GRAMMAR", "TF_GLM_WORLD", "TF_GLM_CLEAR_THINKING", "TF_DSV41_SCHEMA_PROMPT", "TF_SLIDE_TAKE_OUT_CHECK" }; + for (direct) |name| try std.testing.expect(declaredEnv(name)); +} + test "capability audit: decision-only formats are listed apart from the formats a family chats in" { var out: std.Io.Writer.Allocating = .init(std.testing.allocator); defer out.deinit(); diff --git a/zig/src/server/cortheon/web.zig b/zig/src/server/cortheon/web.zig index 3cdebe7314b..b83e621bbf4 100644 --- a/zig/src/server/cortheon/web.zig +++ b/zig/src/server/cortheon/web.zig @@ -125,7 +125,8 @@ pub const Client = struct { const host = std.mem.trim(u8, raw_host, "[]"); if (host.len == 0) return error.BadUrl; const port: u16 = uri.port orelse if (tls) 443 else 80; - const pin = try c.resolve(a, host, port); + const deadline = Io.Clock.awake.now(c.http.io).addDuration(.fromMilliseconds(limits.timeout_ms)); + const pin = try c.resolve(a, host, port, deadline); if (tls) try c.trust(); const name = HostName.init(host) catch null; const conn = c.http.connectTcpOptions(.{ @@ -169,36 +170,33 @@ pub const Client = struct { } /// The IPv4 address to connect to: an IP literal itself, else the first public IPv4; every address must be public. - fn resolve(c: *Client, a: Allocator, host: []const u8, port: u16) Error![]const u8 { + fn resolve(c: *Client, a: Allocator, host: []const u8, port: u16, deadline: Io.Timestamp) Error![]const u8 { if (!address_policy.publicHost(host)) return error.NotPublic; if (Io.net.IpAddress.parse(host, port)) |ip| { if (!publicAddress(ip)) return error.NotPublic; return if (ip == .ip4) host else error.Ipv6Only; // only an IPv4 address can be pinned under a TLS name } else |_| {} - const io = c.http.io; - const name = HostName.init(host) catch return error.BadUrl; - var results: [32]HostName.LookupResult = undefined; - var queue: Io.Queue(HostName.LookupResult) = .init(&results); - var canonical: [HostName.max_len]u8 = undefined; - name.lookup(io, &queue, .{ .port = port, .canonical_name_buffer = &canonical }) catch return error.Network; - var pin: ?[]const u8 = null; - var any = false; - while (queue.getOne(io)) |r| switch (r) { - .address => |addr| { - if (!publicAddress(addr)) return error.NotPublic; - any = true; - if (pin == null and addr == .ip4) { - const b = addr.ip4.bytes; - pin = try std.fmt.allocPrint(a, "{d}.{d}.{d}.{d}", .{ b[0], b[1], b[2], b[3] }); - } + _ = HostName.init(host) catch return error.BadUrl; + // A libc lookup may ignore cancellation; the shared resolver waits to its deadline and caps live workers. + const media = @import("../media_fetch.zig"); + const resolver = @import("../media_fetch_net.zig"); + var failure: media.Failure = .{}; + const addresses = resolver.resolve(a, c.http.io, host, deadline, &failure) catch |err| switch (err) { + error.OutOfMemory => return error.OutOfMemory, + error.Media => { + if (std.mem.eql(u8, failure.text, "image URLs must resolve only to public internet addresses")) return error.NotPublic; + if (std.mem.endsWith(u8, failure.text, "timed out")) return error.Timeout; + return error.Network; }, - .canonical_name => {}, - } else |e| switch (e) { - error.Closed => {}, - error.Canceled => return error.Network, - } - if (!any) return error.Network; - return pin orelse error.Ipv6Only; // connecting by name would let a rebinding name swap in a private address + }; + defer a.free(addresses); + // Resolution uses a service port only to obtain addresses; the caller connects to its original URL port. + for (addresses) |addr| if (addr == .ip4) { + const bytes = addr.ip4.bytes; + return std.fmt.allocPrint(a, "{d}.{d}.{d}.{d}", .{ bytes[0], bytes[1], bytes[2], bytes[3] }); + }; + return error.Ipv6Only; // connecting by name would let a rebinding name swap in a private address + } }; diff --git a/zig/src/server/cortheon/web_deadline_test.zig b/zig/src/server/cortheon/web_deadline_test.zig new file mode 100644 index 00000000000..aff8e048d59 --- /dev/null +++ b/zig/src/server/cortheon/web_deadline_test.zig @@ -0,0 +1,77 @@ +//! Real web Client.get with a fake DNS backend; neither test can reach a socket or an external resolver. +const std = @import("std"); +const Io = std.Io; +const net = Io.net; +const web = @import("web.zig"); +const transport = @import("../media_fetch_net.zig"); +const t = std.testing; +const Fake = struct { + var table: Io.VTable = undefined; + var addresses: []const net.IpAddress = &.{}; + var delay_ms: i64 = 0; + var abandon: std.atomic.Value(bool) = .init(false); + var active: std.atomic.Value(bool) = .init(false); + var calls: std.atomic.Value(u32) = .init(0); + fn lookup(_: ?*anyopaque, _: net.HostName, q: *Io.Queue(net.HostName.LookupResult), _: net.HostName.LookupOptions) net.HostName.LookupError!void { + const io = t.io; + active.store(true, .release); + defer active.store(false, .release); + defer q.close(io); + _ = calls.fetchAdd(1, .monotonic); + if (delay_ms > 0) { + const end = Io.Clock.awake.now(io).addDuration(.fromMilliseconds(delay_ms)); + while (Io.Clock.awake.now(io).nanoseconds < end.nanoseconds) io.sleep(.fromMilliseconds(5), .awake) catch {}; + return error.NameServerFailure; + } + for (addresses) |addr| while ((q.put(io, &.{.{ .address = addr }}, 0) catch return error.NameServerFailure) == 0) { + if (abandon.load(.acquire)) return error.NameServerFailure; + io.sleep(.fromMilliseconds(1), .awake) catch {}; + }; + } + fn system() Io { + table = t.io.vtable.*; + table.netLookup = lookup; + table.async = Io.noAsync; + abandon.store(false, .release); + calls.store(0, .monotonic); + return .{ .userdata = t.io.userdata, .vtable = &table }; + } + fn drain() void { + while (active.load(.acquire) or transport.lookups.load(.acquire) != 0) t.io.sleep(.fromMilliseconds(5), .awake) catch {}; + } + fn stop() void { + t.io.sleep(.fromMilliseconds(250), .awake) catch {}; + abandon.store(true, .release); + } +}; +test "request access audit: web deadline returns before a DNS backend that ignores cancellation" { + Fake.addresses = &.{}; + Fake.delay_ms = 1000; + defer { + Fake.drain(); + Fake.delay_ms = 0; + } + const io = Fake.system(); + var client: web.Client = .init(t.allocator, io, "fixture"); + defer client.deinit(); + const start = Io.Clock.awake.now(io); + try t.expectError(error.Timeout, client.get(t.allocator, "http://slow.audit.invalid/", &.{}, .{ .timeout_ms = 100 })); + const elapsed_ms = start.durationTo(Io.Clock.awake.now(io)).toMilliseconds(); + try t.expectEqual(@as(u32, 1), Fake.calls.load(.monotonic)); + try t.expect(elapsed_ms < 750); +} +test "request access audit: all DNS answers including a private address past the queue are checked" { + var addresses: [40]net.IpAddress = undefined; + for (&addresses, 0..) |*addr, i| addr.* = .{ .ip4 = .{ .bytes = .{ 8, 8, 4, @intCast(i + 1) }, .port = 80 } }; + addresses[39] = .{ .ip4 = .{ .bytes = .{ 127, 0, 0, 1 }, .port = 80 } }; + Fake.addresses = &addresses; + Fake.delay_ms = 0; + defer Fake.drain(); + const io = Fake.system(); + const stopper = try std.Thread.spawn(.{}, Fake.stop, .{}); + defer stopper.join(); + var client: web.Client = .init(t.allocator, io, "fixture"); + defer client.deinit(); + try t.expectError(error.NotPublic, client.get(t.allocator, "http://many.audit.invalid/", &.{}, .{ .timeout_ms = 5000 })); + try t.expectEqual(@as(u32, 1), Fake.calls.load(.monotonic)); +} diff --git a/zig/src/server/engines.zig b/zig/src/server/engines.zig index e7e199d6cd5..722d281cffd 100644 --- a/zig/src/server/engines.zig +++ b/zig/src/server/engines.zig @@ -69,7 +69,7 @@ pub fn open(a: Allocator, gpa: Allocator, io: std.Io, dir: []const u8, model_typ problem.* = "--record writes rows from the CUDA engine only so far: serve without --record"; return null; } - return native.open(a, gpa, io, try cli.request(a, dir, model_type, args), problem); + return native.open(a, gpa, io, try released(a, dir, model_type, args), problem); } /// A tensor-parallel rank above 0 runs rank 0's steps until it stops; false with ``problem`` set when it cannot. @@ -82,7 +82,14 @@ pub fn follow(a: Allocator, gpa: Allocator, io: std.Io, dir: []const u8, model_t problem.* = "this build has no tensor-parallel ranks"; return false; } - return native.follow(a, gpa, io, try cli.request(a, dir, model_type, args), problem); + return native.follow(a, gpa, io, try released(a, dir, model_type, args), problem); +} + +/// The engine's request with this build's release, by which a CUDA family's rank aliases retire. +fn released(a: Allocator, dir: []const u8, model_type: []const u8, args: cli.Args) !api.Open { + var o = try cli.request(a, dir, model_type, args); + o.release = @import("build_options").version; + return o; } /// `tensorfold device`'s side of the join: what `capabilities --json` lists, without its chip probe or a driver. diff --git a/zig/src/server/gpu_turn.zig b/zig/src/server/gpu_turn.zig index f16b328c398..873a519d2ba 100644 --- a/zig/src/server/gpu_turn.zig +++ b/zig/src/server/gpu_turn.zig @@ -6,19 +6,27 @@ pub const path = "/tmp/tensorfold-speech.lock"; /// Where batch work gives way: the speech lock (tests point `at` at their own). pub const Turn = struct { io: std.Io, at: []const u8 = path }; -/// How often waiting batch work looks again; one poll is the most speech's end can be missed by. +/// How often waiting work looks again; one poll is the most speech's end can be missed by. const poll: std.Io.Duration = .fromMilliseconds(20); -/// Shared hold; best effort only when the lock file cannot be opened. It blocks only behind batch work's exclusive -/// probes, which `free` and `mark` take with tryLock and release at once, never across GPU work. +/// Longest speech waits behind an exclusive hold: batch probes take microseconds, so a longer one is not a probe. +const patience: std.Io.Duration = .fromSeconds(1); + +/// Windows files have no mode bits, so only POSIX widens or checks them. +const modes = @hasDecl(std.Io.File.Permissions, "fromMode"); + +/// Shared hold; best effort, so speech goes on without one when the lock cannot be opened or stays held. pub fn speak(io: std.Io, at: []const u8) ?std.Io.File { defer stamp(io, at); const file = open(io, at) catch return null; - file.lock(io, .shared) catch { - file.close(io); - return null; - }; - return file; + const until = std.Io.Clock.awake.now(io).addDuration(patience); + while (true) { + if (file.tryLock(io, .shared) catch break) return file; + if (std.Io.Clock.awake.now(io).compare(.gte, until)) break; + io.sleep(poll, .awake) catch break; + } + file.close(io); + return null; } pub fn done(io: std.Io, held: ?std.Io.File) void { @@ -35,20 +43,28 @@ pub fn yield(io: std.Io, at: []const u8) f64 { return @as(f64, @floatFromInt(started.durationTo(std.Io.Clock.awake.now(io)).toNanoseconds())) / 1e9; } -/// Whether no speech holds the turn; an error counts as free, as speech never depends on batch work seeing it. +/// Whether no voice holds the turn: a hold refusing even a shared probe is no voice, and an error counts as free. fn free(io: std.Io, file: std.Io.File) bool { - const got = file.tryLock(io, .exclusive) catch return true; - if (got) file.unlock(io); - return got; + if (file.tryLock(io, .exclusive) catch return true) { + file.unlock(io); + return true; + } + if (!(file.tryLock(io, .shared) catch return true)) return true; + file.unlock(io); + return false; } -/// Read-only so the speech server's and a render's users can share one file; flock needs no write access. +/// Read-only, so speech and a render share one file; made only when absent, else `existing` keeps a planted name inert. fn open(io: std.Io, at: []const u8) !std.Io.File { const dir = std.Io.Dir.cwd(); - return dir.openFile(io, at, .{}) catch |e| switch (e) { + return existing(io, at, .read_only) catch |e| switch (e) { error.FileNotFound => { - const file = try dir.createFile(io, at, .{ .read = true, .truncate = false }); - file.setPermissions(io, .fromMode(0o644)) catch {}; // past the creator's umask, so the other user opens it + const file = dir.createFile(io, at, .{ .read = true, .exclusive = true }) catch |create_err| { + if (create_err == error.PathAlreadyExists) return existing(io, at, .read_only); + return create_err; + }; + errdefer file.close(io); + if (modes) try file.setPermissions(io, .fromMode(0o644)); // past the creator's umask, so the other user opens it return file; }, else => e, @@ -59,16 +75,16 @@ pub const Mark = struct { inode: std.Io.File.INode, bytes: [16]u8 }; /// Snapshot before a timed region; missing instrumentation or active speech cannot certify a clean sample. pub fn mark(io: std.Io, at: []const u8) ?Mark { + const lock = open(io, at) catch return null; + defer lock.close(io); + if (!(lock.tryLock(io, .exclusive) catch return null)) return null; + defer lock.unlock(io); // held through the read, so no speech can stamp behind it const file = marker(io, at) catch return null; defer file.close(io); const stat = file.stat(io) catch return null; - if (stat.kind != .file or stat.permissions.toMode() & 0o666 != 0o666) return null; + if (modes and stat.permissions.toMode() & 0o666 != 0o666) return null; var result: Mark = .{ .inode = stat.inode, .bytes = undefined }; if ((file.readPositionalAll(io, &result.bytes, 0) catch return null) != result.bytes.len) return null; - const lock = open(io, at) catch return null; - defer lock.close(io); - if (!(lock.tryLock(io, .exclusive) catch return null)) return null; - lock.unlock(io); return result; } @@ -94,14 +110,14 @@ fn marker(io: std.Io, at: []const u8) !std.Io.File { var buf: [std.fs.max_path_bytes]u8 = undefined; const name = try std.fmt.bufPrint(&buf, "{s}.stamp", .{at}); const dir = std.Io.Dir.cwd(); - return dir.openFile(io, name, .{ .mode = .read_write, .follow_symlinks = false }) catch |e| switch (e) { + return existing(io, name, .read_write) catch |e| switch (e) { error.FileNotFound => { const file = dir.createFile(io, name, .{ .read = true, .exclusive = true }) catch |create_err| { - if (create_err == error.PathAlreadyExists) return dir.openFile(io, name, .{ .mode = .read_write, .follow_symlinks = false }); + if (create_err == error.PathAlreadyExists) return existing(io, name, .read_write); return create_err; }; errdefer file.close(io); - try file.setPermissions(io, .fromMode(0o666)); + if (modes) try file.setPermissions(io, .fromMode(0o666)); var bytes: [16]u8 = undefined; io.random(&bytes); try file.writePositionalAll(io, &bytes, 0); @@ -111,6 +127,63 @@ fn marker(io: std.Io, at: []const u8) !std.Io.File { }; } +/// The one regular file with no other name at `name`: no symlink, and nonblocking so a planted FIFO cannot stall. +fn existing(io: std.Io, name: []const u8, mode: std.Io.Dir.OpenFileOptions.Mode) !std.Io.File { + const file: std.Io.File = if (@import("builtin").os.tag == .windows) + try std.Io.Dir.cwd().openFile(io, name, .{ .mode = mode, .follow_symlinks = false }) + else + .{ .handle = try std.posix.openat(std.posix.AT.FDCWD, name, .{ + .ACCMODE = if (mode == .read_write) .RDWR else .RDONLY, + .NOFOLLOW = true, + .NONBLOCK = true, + .CLOEXEC = true, + }, 0), .flags = .{ .nonblocking = false } }; + errdefer file.close(io); + const stat = try file.stat(io); + if (stat.kind != .file or stat.nlink != 1) return error.NotRegularFile; + return file; +} + +/// Committed command buffers waited in order; errors wait for every one, so the GPU never reads a freed buffer. +pub fn Queue(comptime C: type, comptime capacity: usize) type { + return struct { + ring: [capacity]C = undefined, + first: usize = 0, + n: usize = 0, + /// GPU seconds of the buffers waited so far. + gpu: f64 = 0, + failed: bool = false, + + const Self = @This(); + + /// Keeps `cb`, then waits the oldest until at most `ahead` remain unwaited. + pub fn add(q: *Self, cb: C, ahead: usize) !void { + if (q.n == capacity) q.waitOldest(); + q.ring[(q.first + q.n) % capacity] = cb; + q.n += 1; + while (q.n > ahead) q.waitOldest(); + if (q.failed) return q.drain(); + } + + /// Waits every buffer still kept; GpuFailed if any of them, or any waited earlier, failed. + pub fn drain(q: *Self) !void { + while (q.n > 0) q.waitOldest(); + if (q.failed) return error.GpuFailed; + } + + fn waitOldest(q: *Self) void { + const cb = q.ring[q.first]; + q.first = (q.first + 1) % capacity; + q.n -= 1; + cb.wait(); + if (cb.failure()) |text| { + std.debug.print("command buffer failed: {s}\n", .{text}); + q.failed = true; + } else q.gpu += cb.gpuSeconds(); + } + }; +} + test "batch work waits for every speech hold to end, and not at all without one" { const io = std.testing.io; var tmp = std.testing.tmpDir(.{}); @@ -138,7 +211,7 @@ test "batch work waits for every speech hold to end, and not at all without one" try std.testing.expectEqual(@as(f64, 0), yield(io, lock)); } -test "speech waits out a batch probe however long it is held, and the file it makes is open to every user" { +test "speech waits out a batch probe, and the file it makes is open to every user" { const io = std.testing.io; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); @@ -168,6 +241,54 @@ test "speech waits out a batch probe however long it is held, and the file it ma try std.testing.expect(!clean(io, lock, before)); } +test "a planted lock path neither redirects the files speech makes nor holds speech up for long" { + if (@import("builtin").os.tag == .windows) return error.SkipZigTest; + const io = std.testing.io; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const at = try tmp.dir.realPathFileAlloc(io, ".", std.testing.allocator); + defer std.testing.allocator.free(at); + const lock = try std.fs.path.join(std.testing.allocator, &.{ at, "speech.lock" }); + defer std.testing.allocator.free(lock); + + // dangling symlinks where the lock and its stamp go: nothing is created or chmodded at their targets + try tmp.dir.symLink(io, "victim", "speech.lock", .{}); + try tmp.dir.symLink(io, "victim.stamp", "speech.lock.stamp", .{}); + try std.testing.expect(speak(io, lock) == null); + try std.testing.expectEqual(@as(f64, 0), yield(io, lock)); + try std.testing.expect(mark(io, lock) == null); + try std.testing.expectError(error.FileNotFound, tmp.dir.access(io, "victim", .{})); + try std.testing.expectError(error.FileNotFound, tmp.dir.access(io, "victim.stamp", .{})); + + // a FIFO for the lock and a hard link for the stamp: neither stalls speech, and the link's target keeps its bytes + try tmp.dir.deleteFile(io, "speech.lock"); + try tmp.dir.deleteFile(io, "speech.lock.stamp"); + var fifo_buf: [std.fs.max_path_bytes:0]u8 = undefined; + try std.testing.expectEqual(@as(c_int, 0), mkfifo(try std.fmt.bufPrintSentinel(&fifo_buf, "{s}", .{lock}, 0), 0o666)); + try tmp.dir.writeFile(io, .{ .sub_path = "victim", .data = "kept" }); + try tmp.dir.hardLink("victim", tmp.dir, "speech.lock.stamp", io, .{}); + const planted = std.Io.Clock.awake.now(io); + try std.testing.expect(speak(io, lock) == null); + try std.testing.expectEqual(@as(f64, 0), yield(io, lock)); + try std.testing.expect(mark(io, lock) == null); + try std.testing.expect(planted.durationTo(std.Io.Clock.awake.now(io)).toNanoseconds() < std.time.ns_per_s); + var kept: [8]u8 = undefined; + try std.testing.expectEqualStrings("kept", try tmp.dir.readFile(io, "victim", &kept)); + + // an exclusive hold that never lets go: speech starts without the turn, and batch work does not wait on it + try tmp.dir.deleteFile(io, "speech.lock"); + try tmp.dir.deleteFile(io, "speech.lock.stamp"); + const squatter = try open(io, lock); + defer squatter.close(io); + try squatter.lock(io, .exclusive); + const started = std.Io.Clock.awake.now(io); + try std.testing.expect(speak(io, lock) == null); + try std.testing.expect(started.durationTo(std.Io.Clock.awake.now(io)).toNanoseconds() < 3 * std.time.ns_per_s); + try std.testing.expectEqual(@as(f64, 0), yield(io, lock)); +} + +extern "c" fn mkfifo(path: [*:0]const u8, mode: std.c.mode_t) c_int; + test "timed work excludes speech completed entirely between polls and preexisting speech" { const io = std.testing.io; var tmp = std.testing.tmpDir(.{}); @@ -214,3 +335,72 @@ test "timed work excludes speech completed entirely between polls and preexistin try std.testing.expect(!clean(io, lock, mark(io, lock))); } } + +test "speech that stamps and ends while the stamp is read cannot certify a timed step" { + const io = std.testing.io; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const at = try tmp.dir.realPathFileAlloc(io, ".", std.testing.allocator); + defer std.testing.allocator.free(at); + const lock = try std.fs.path.join(std.testing.allocator, &.{ at, "speech.lock" }); + defer std.testing.allocator.free(lock); + + const before = mark(io, lock); + // speech took its hold mid-step but has not stamped; it stamps and lets go during the next stamp read + const Late = struct { + var voice: ?std.Io.File = null; + var name: []const u8 = ""; + fn read(userdata: ?*anyopaque, file: std.Io.File, data: []const []u8, offset: u64) std.Io.File.ReadPositionalError!usize { + const n = try std.testing.io.vtable.fileReadPositional(userdata, file, data, offset); + if (voice) |held| { + voice = null; + stamp(std.testing.io, name); + done(std.testing.io, held); + } + return n; + } + }; + const held = try open(io, lock); + try held.lock(io, .shared); + Late.voice = held; + Late.name = lock; + defer if (Late.voice) |still| done(io, still); + var vtable = io.vtable.*; + vtable.fileReadPositional = Late.read; + try std.testing.expect(!clean(.{ .userdata = io.userdata, .vtable = &vtable }, lock, before)); +} + +test "a failed command buffer is reported only after every buffer committed with it has completed" { + const Fake = struct { + bad: bool = false, + waited: *usize, + fn wait(c: @This()) void { + c.waited.* += 1; + } + fn failure(c: @This()) ?[*:0]const u8 { + return if (c.bad) "fault" else null; + } + fn gpuSeconds(_: @This()) f64 { + return 1; + } + }; + var waited: usize = 0; + var q: Queue(Fake, 4) = .{}; + for (0..5) |_| try q.add(.{ .waited = &waited }, 3); // at most three left unwaited + try std.testing.expectEqual(@as(usize, 2), waited); + try std.testing.expectEqual(@as(f64, 2), q.gpu); + // the oldest fails while three committed after it still run: the error waits for all of them + try q.drain(); + try q.add(.{ .waited = &waited, .bad = true }, 3); + for (0..2) |_| try q.add(.{ .waited = &waited }, 3); + try std.testing.expectEqual(@as(usize, 5), waited); + try std.testing.expectError(error.GpuFailed, q.add(.{ .waited = &waited }, 3)); + try std.testing.expectEqual(@as(usize, 9), waited); + try std.testing.expectEqual(@as(usize, 0), q.n); + + var late: Queue(Fake, 4) = .{}; + try late.add(.{ .waited = &waited, .bad = true }, 3); + try late.add(.{ .waited = &waited }, 3); + try std.testing.expectError(error.GpuFailed, late.drain()); + try std.testing.expectEqual(@as(usize, 11), waited); +} diff --git a/zig/src/server/hf_text.zig b/zig/src/server/hf_text.zig index fa0422a8cae..3baa7bb2aeb 100644 --- a/zig/src/server/hf_text.zig +++ b/zig/src/server/hf_text.zig @@ -36,6 +36,7 @@ pub const HfText = struct { native_kimi: ?*KimiText = null, source: []const u8 = "", native_deepseek: bool = false, + native_inkling2: bool = false, schema_prompt: bool = true, // TF_DSV41_SCHEMA_PROMPT: response_format's schema as the encoder's ``## Response Format`` overridden: bool = false, // the chat template is --chat-template's file unread_template: bool = false, // a native DeepSeek checkpoint's own Jinja, which its encoder replaces @@ -100,6 +101,9 @@ pub const HfText = struct { return error.Load; }; if (model_config == .object) if (model_config.object.get("model_type")) |kind| { + // the Inkling 2 family's two model types (families/inkling2/config.zig): Small's and Mini's looped one + t.native_inkling2 = template_override == null and kind == .string and + (std.mem.eql(u8, kind.string, "inkling2") or std.mem.eql(u8, kind.string, "inkling2_loop")); t.native_deepseek = template_override == null and kind == .string and (std.mem.eql(u8, kind.string, "deepseek_v4") or std.mem.eql(u8, kind.string, "deepseek_v41")); if (kind == .string and std.mem.eql(u8, kind.string, "glm5_next")) { @@ -258,7 +262,7 @@ pub const HfText = struct { pub fn text(t: *HfText) model_text.Text { if (t.native_kimi) |kimi| return kimi.text(); - return .{ .native_deepseek = t.native_deepseek and t.compiled == null, .deferred_native = @import("deferred_tools.zig").native(if (t.tool_source.len > 0) t.tool_source else t.source), .ctx = t, .vtable = &.{ + return .{ .native_deepseek = t.native_deepseek and t.compiled == null, .native_inkling2 = t.native_inkling2, .deferred_native = @import("deferred_tools.zig").native(if (t.tool_source.len > 0) t.tool_source else t.source), .ctx = t, .vtable = &.{ .encode = encodeFn, .decode = decodeFn, .token_id = tokenIdFn, diff --git a/zig/src/server/inkling2_boundary_test.zig b/zig/src/server/inkling2_boundary_test.zig new file mode 100644 index 00000000000..9c59d5d40be --- /dev/null +++ b/zig/src/server/inkling2_boundary_test.zig @@ -0,0 +1,112 @@ +//! Inkling 2 reply parsing at turn boundaries: role headers, thinking token counts, bare replies, raw decode cost. +const std = @import("std"); +const json = @import("json"); +const model_text = @import("model_text.zig"); +const reply = @import("inkling2_reply.zig"); +const fx = @import("inkling2_fake.zig"); +const Piece = fx.Piece; +const plain = fx.plain; +const t = std.testing; + +const mm = fx.message_model; +const text = fx.content_text; +const think = fx.content_thinking; +const close = fx.end_message; +const tool_json = fx.content_tool_json; + +/// Whole and every growing prefix through one cursor agree; the whole reply is returned. +fn both(a: std.mem.Allocator, pieces: []const Piece, tools: []const json.Value) !reply.Result { + const whole = try fx.parse(a, pieces, tools); + var fake: fx.Fake = .{ .pieces = pieces }; + var stream = try reply.Stream.init(a, fake.text()); + const ids = try a.alloc(u32, pieces.len); + for (pieces, ids) |piece, *id| id.* = piece.id; + for (1..ids.len + 1) |n| _ = try stream.extend(ids[0..n], tools); + const done = try stream.done(); + try t.expectEqualStrings(whole.content, done.content); + try t.expectEqualStrings(whole.reasoning, done.reasoning); + try t.expectEqual(whole.rejected_calls, done.rejected_calls); + return whole; +} + +test "Inkling 2 parse: a user, system or tool header ends the model's turn in every channel" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + for ([_]Piece{ fx.message_user, fx.message_system, fx.message_tool }) |role| { + // with ignore_eos the reply goes on past its end into another role's turn: none of it is the model's + const after = [_]Piece{ mm, text, plain(70, "A"), close, fx.end_sampling, role, text, plain(71, "USER"), close }; + try t.expectEqualStrings("A", (try both(a, &after, &.{})).content); + const open_think = [_]Piece{ mm, think, plain(72, "x"), role, text, plain(73, "USER") }; + const got = try both(a, &open_think, &.{}); + try t.expectEqualStrings("x", got.reasoning); + try t.expectEqualStrings("", got.content); + try t.expect(!got.open_think); + } +} + +test "Inkling 2 parse: a role header inside a JSON call refuses it instead of stitching the next turn's text in" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const tools = try fx.offeredTools(a, &.{"lookup"}); + const pieces = [_]Piece{ mm, plain(74, "lookup"), tool_json, plain(75, "{\"name\":\"lookup\",\"args\":{\"x\":"), fx.message_user, text, plain(76, "1}}"), close }; + const got = try both(a, &pieces, tools); + try t.expect(got.calls == null); + try t.expectEqual(@as(usize, 1), got.rejected_calls); + try t.expectEqualStrings("", got.content); +} + +test "Inkling 2 parse: reasoning tokens count a thinking block from its header through its close" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const Case = struct { pieces: []const Piece, tokens: usize }; + const cases = [_]Case{ + .{ .pieces = &.{ mm, think, plain(80, "x"), close }, .tokens = 4 }, + .{ .pieces = &.{ mm, plain(81, "name"), think, plain(82, "x"), plain(83, "y"), close }, .tokens = 6 }, + .{ .pieces = &.{ mm, think, plain(84, "x"), fx.unused, plain(85, "y"), close }, .tokens = 6 }, + .{ .pieces = &.{ mm, think, plain(86, "open") }, .tokens = 3 }, + // the answer's block is not thinking + .{ .pieces = &.{ mm, think, plain(87, "x"), close, mm, text, plain(88, "answer"), close }, .tokens = 4 }, + }; + for (cases) |case| try t.expectEqual(case.tokens, (try both(a, case.pieces, &.{})).reasoning_tokens); +} + +test "Inkling 2 parse: text before any message header is a bare reply's content, as a grammar writes one" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const bare = [_]Piece{ plain(90, "{\"ok\""), plain(91, ":true}") }; + try t.expectEqualStrings("{\"ok\":true}", (try both(a, &bare, &.{})).content); + // once a header has arrived, text between blocks is a header's name, never content + const shaped = [_]Piece{ mm, plain(92, "name"), text, plain(93, "B"), close, plain(94, "stray") }; + try t.expectEqualStrings("B", (try both(a, &shaped, &.{})).content); +} + +test "Inkling 2 parse: a streamed raw completion decodes no prefix: the generation's own decode serves it" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var pieces: [64]Piece = undefined; + for (&pieces, 0..) |*piece, i| piece.* = plain(@intCast(100 + i), "x"); + var fake: fx.Fake = .{ .pieces = &pieces }; + const Srv = struct { text: model_text.Text }; + const srv: Srv = .{ .text = fake.text() }; + var g: struct { + a: std.mem.Allocator, + chat: bool = false, + inkling2: ?reply.Stream = null, + tools: []const json.Value = &.{}, + srv: *const Srv, + stops: @import("reply_text.zig").Stops = .{ .strings = &.{} }, + visible: @import("reply_text.zig").Incremental = .{}, + } = .{ .a = a, .srv = &srv }; + var ids: [pieces.len]u32 = undefined; + for (&pieces, &ids) |piece, *id| id.* = piece.id; + fx.decoded_ids = 0; + for (1..ids.len + 1) |n| _ = try @import("chat_inkling2.zig").read(&g, ids[0..n], false); + const done = try @import("chat_inkling2.zig").read(&g, &ids, true); + try t.expectEqual(@as(usize, 64), done.content.len); + try t.expectEqual(ids.len, fx.decoded_ids); // one decode, of the finished reply +} diff --git a/zig/src/server/inkling2_chat_test.zig b/zig/src/server/inkling2_chat_test.zig new file mode 100644 index 00000000000..8f1998eaf8c --- /dev/null +++ b/zig/src/server/inkling2_chat_test.zig @@ -0,0 +1,551 @@ +//! Inkling 2's release reply grammar through HfText and the actual OpenAI route. +const std = @import("std"); +const json = @import("json"); +const api = @import("engine_api"); +const HfText = @import("hf_text.zig").HfText; +const Server = @import("server.zig").Server; +const openai = @import("openai.zig"); +const t = std.testing; + +const sample = "<|message_model|><|content_thinking|>The user asks: ... 340 + 51 = 391. ... <|end_message|><|message_model|><|content_text|>391<|end_message|>"; +const thought = "The user asks: ... 340 + 51 = 391. ... "; + +/// The committed release tokenizer and template, with only the served model type changed by a case. +const Fixture = struct { + tmp: std.testing.TmpDir, + path: [:0]u8, + + /// `kind` "release": the Mini checkpoint's own config.json, tokenizer_config.json and chat template. + fn init(a: std.mem.Allocator, kind: []const u8) !Fixture { + var tmp = std.testing.tmpDir(.{}); + errdefer tmp.cleanup(); + const release = std.mem.eql(u8, kind, "release"); + const at = "zig/src/families/inkling2/fixtures/"; + const files = [_][2][]const u8{ + .{ at ++ "mini_tokenizer.json", "tokenizer.json" }, + .{ if (release) at ++ "release_chat_template.jinja" else at ++ "chat_template.jinja", "chat_template.jinja" }, + .{ at ++ "release_tokenizer_config.json", "tokenizer_config.json" }, + .{ at ++ "mini_config.json", "config.json" }, + }; + for (files[0..if (release) 3 else 2]) |file| { + const bytes = try std.Io.Dir.cwd().readFileAlloc(t.io, file[0], a, .limited(1 << 20)); + try tmp.dir.writeFile(t.io, .{ .sub_path = file[1], .data = bytes }); + } + // the release config's model_type and architectures; its EOS 200006 is past the cut tokenizer's base vocabulary + const config = if (release) blk: { + const v = (try json.parseText(a, try std.Io.Dir.cwd().readFileAlloc(t.io, files[3][0], a, .limited(1 << 20)))).ok; + const arch = try json.stringify(a, v.get("architectures").?, .{ .ascii = false }); + break :blk try std.fmt.allocPrint(a, "{{\"model_type\":\"{s}\",\"architectures\":{s}}}", .{ v.get("model_type").?.string, arch }); + } else try std.fmt.allocPrint(a, "{{\"model_type\":\"{s}\"}}", .{kind}); + try tmp.dir.writeFile(t.io, .{ .sub_path = "config.json", .data = config }); + // The cut tokenizer's base vocabulary ends below the release EOS id; id 2 only drives the fake engine's finish. + try tmp.dir.writeFile(t.io, .{ .sub_path = "generation_config.json", .data = "{\"eos_token_id\":2}" }); + return .{ .tmp = tmp, .path = try tmp.dir.realPathFileAlloc(t.io, ".", a) }; + } + + fn deinit(f: *Fixture) void { + f.tmp.cleanup(); + } +}; + +/// Answers `reply` in chunks of `stride` tokens. +const Script = struct { + a: std.mem.Allocator, + reply: []const u32, + stride: usize, + lane: bool = false, + eos_len: usize = 0, // the request's end ids, as the engine got them + + fn engine(s: *@This()) api.Engine { + return .{ .ctx = s, .vtable = &.{ .info = info, .submit = submit, .cancel = cancel, .status = status, .memory = memory } }; + } + fn info(_: *anyopaque) api.Info { + return .{ .context_window = 4096 }; + } + fn submit(ctx: *anyopaque, id: api.Id, request: *const api.Request, sink: api.Sink) api.SubmitError!void { + const s: *@This() = @ptrCast(@alignCast(ctx)); + s.eos_len = request.eos.len; + sink.event(sink.ctx, id, &.{ .prefilled = 0 }); + if (s.lane) return @import("inkling2_lane_script.zig").submit(s.a, id, request, sink, s.reply, s.stride) catch return error.InvalidRequest; + var limit = s.reply.len; + for (s.reply, 0..) |token, i| if (std.mem.indexOfScalar(u32, request.eos, token) != null) { + limit = i + 1; + break; + }; + var start: usize = 0; + while (start < limit) { + const end = @min(start + s.stride, limit); + sink.event(sink.ctx, id, &.{ .tokens = s.reply[start..end] }); + start = end; + } + const ended = limit > 0 and std.mem.indexOfScalar(u32, request.eos, s.reply[limit - 1]) != null; + sink.event(sink.ctx, id, &.{ .finished = .{ .reason = if (ended) .stop else .length } }); + } + fn cancel(_: *anyopaque, _: api.Id) void {} + fn status(_: *anyopaque, out: *api.Status, _: []u32) void { + out.* = .{}; + } + fn memory(_: *anyopaque, _: bool) ?api.Memory { + return null; + } +}; + +/// The route's whole reply or its stream's events, as JSON text. +const Got = struct { + a: std.mem.Allocator, + status: u16 = 0, + body: []const u8 = "", + events: std.ArrayList([]const u8) = .empty, + + fn out(g: *Got) openai.Out { + return .{ .ctx = g, .vt = &.{ .open = open, .event = event, .reply = reply } }; + } + fn open(_: *anyopaque, _: usize) error{Closed}!void {} + fn event(ctx: *anyopaque, payload: ?json.Value) error{Closed}!void { + const g: *Got = @ptrCast(@alignCast(ctx)); + const text = json.stringify(g.a, payload orelse return, .{ .ascii = false }) catch return error.Closed; + g.events.append(g.a, text) catch return error.Closed; + } + fn reply(ctx: *anyopaque, status_code: u16, payload: json.Value) void { + const g: *Got = @ptrCast(@alignCast(ctx)); + g.status = status_code; + g.body = json.stringify(g.a, payload, .{ .ascii = false }) catch ""; + } +}; + +/// What a client receives, joined across whole replies or stream deltas. +pub const Seen = struct { + reasoning: []const u8, + content: []const u8, + ids: []const u8, + names: []const u8, + arguments: []const u8, + rejected: i64 = 0, // the tensorfold block's rejected_tool_calls + usage: Usage = .{}, + kept: []const u8 = "", // the tensorfold block's kept_tool_calls, as JSON + finish: []const u8 = "", + eos_len: usize = 0, // the engine's request's end ids + grammars: usize = 0, // grammars the shared compiler compiled (ends: the eos ids) + tool_grammars: usize = 0, // grammars the required-call compiler compiled (ends: eos and the end of message) + token_ids: []const u8 = "", // the tensorfold block's token_ids, as JSON, when the request asked for them +}; + +/// Grammars accepted as compiled, with no grammar library: the route attaches them, the script ignores them. +const Grammars = struct { + compiled: usize = 0, + fn compiler(g: *Grammars) api.grammar.Compiler { + var out: api.grammar.Compiler = undefined; + out.h = g; + out.words = 4; + out.f.compile = compile; + out.f.free = free; + out.f.close = free; + return out; + } + fn compile(ptr: *anyopaque, _: c_int, _: [*]const u8, _: usize, _: [*]u8, _: usize) callconv(.c) ?*anyopaque { + const g: *Grammars = @ptrCast(@alignCast(ptr)); + g.compiled += 1; + return ptr; + } + fn free(_: *anyopaque) callconv(.c) void {} +}; + +const Usage = struct { completion: i64 = -1, reasoning: i64 = -1 }; + +fn intOf(v: ?json.Value) i64 { + const n = v orelse return -1; + return if (n == .int) std.fmt.parseInt(i64, n.int, 10) catch -1 else -1; +} + +/// The reply's usage, when this body or event carries it. +fn usageOf(v: json.Value, into: *Usage) void { + const u = v.get("usage") orelse return; + if (u != .object) return; + into.completion = intOf(u.get("completion_tokens")); + if (u.get("completion_tokens_details")) |d| if (d == .object) { + into.reasoning = intOf(d.get("reasoning_tokens")); + }; +} + +fn idsOf(a: std.mem.Allocator, v: json.Value, into: *[]const u8) !void { + const tf = v.get("tensorfold") orelse return; + const ids = tf.get("token_ids") orelse return; + into.* = try json.stringify(a, ids, .{ .ascii = false, .compact = true }); +} + +fn keptOf(a: std.mem.Allocator, v: json.Value, into: *[]const u8) !void { + const tf = v.get("tensorfold") orelse return; + const kept = tf.get("kept_tool_calls") orelse return; + into.* = try json.stringify(a, kept, .{ .ascii = false, .compact = true }); +} + +fn rejectedOf(v: json.Value) i64 { + const tf = v.get("tensorfold") orelse return 0; + const n = tf.get("rejected_tool_calls") orelse return 0; + return if (n == .int) std.fmt.parseInt(i64, n.int, 10) catch 0 else 0; +} + +fn appendCall(a: std.mem.Allocator, call: json.Value, ids: *std.ArrayList(u8), names: *std.ArrayList(u8), arguments: *std.ArrayList(u8)) !void { + if (call.get("id")) |v| if (v == .string) try ids.appendSlice(a, v.string); + const f = call.get("function") orelse return; + if (f.get("name")) |v| if (v == .string) try names.appendSlice(a, v.string); + if (f.get("arguments")) |v| if (v == .string) try arguments.appendSlice(a, v.string); +} + +pub fn run(a: std.mem.Allocator, kind: []const u8, reply: []const u32, extra: []const u8, stream: bool, stride: usize, request: []const u8, chat_route: bool) !Seen { + return runMode(a, kind, reply, extra, stream, stride, request, chat_route, false); +} + +fn runMode(a: std.mem.Allocator, kind: []const u8, reply: []const u32, extra: []const u8, stream: bool, stride: usize, request: []const u8, chat_route: bool, lane: bool) !Seen { + var fx = try Fixture.init(a, kind); + defer fx.deinit(); + var problem: []const u8 = ""; + const hf = try HfText.load(a, t.io, fx.path, null, a, &problem); + defer hf.deinit(); + var script: Script = .{ .a = a, .reply = reply, .stride = stride, .lane = lane }; + const srv = try Server.init(a, t.io, script.engine(), hf.text(), .{ .served_name = "m", .model_ids = &.{"m"}, .enable_thinking = false, .use_drafts = false }, null); + defer srv.deinit(); + var grammars: Grammars = .{}; + var tool_grammars: Grammars = .{}; + var compiler = grammars.compiler(); + var tool_compiler = tool_grammars.compiler(); + srv.info.structures = true; + srv.grammars = &compiler; + if (comptime @hasField(Server, "tool_grammars")) srv.tool_grammars = &tool_compiler; + defer srv.grammars = null; + defer if (comptime @hasField(Server, "tool_grammars")) { + srv.tool_grammars = null; + }; + const body = try std.fmt.allocPrint(a, "{{\"model\":\"m\",\"max_tokens\":256,{s},\"stream\":{s}{s}}}", .{ request, if (stream) "true" else "false", extra }); + var got: Got = .{ .a = a }; + var conn = try @import("http_conn.zig").Conn.init(a, -1, "fixture"); + defer conn.deinit(); + openai.run(srv, a, got.out(), .{ .conn = &conn }, chat_route, (try json.parseText(a, body)).ok); + var reasoning: std.ArrayList(u8) = .empty; + var content: std.ArrayList(u8) = .empty; + var ids: std.ArrayList(u8) = .empty; + var names: std.ArrayList(u8) = .empty; + var arguments: std.ArrayList(u8) = .empty; + var rejected: i64 = 0; + var usage: Usage = .{}; + var kept: []const u8 = ""; + var token_ids: []const u8 = ""; + var finish: []const u8 = ""; + if (!stream) { + try t.expectEqual(@as(u16, 200), got.status); + const v = (try json.parseText(a, got.body)).ok; + rejected = rejectedOf(v); + usageOf(v, &usage); + try keptOf(a, v, &kept); + try idsOf(a, v, &token_ids); + const first = v.get("choices").?.array[0]; + if (first.get("finish_reason")) |f| if (f == .string) { + finish = f.string; + }; + const m = if (first.get("message")) |message| message else first; + if (m.get("reasoning_content")) |r| if (r == .string) try reasoning.appendSlice(a, r.string); + if (m.get("content")) |c| if (c == .string) try content.appendSlice(a, c.string); + if (m.get("text")) |c| if (c == .string) try content.appendSlice(a, c.string); + if (m.get("tool_calls")) |calls| if (calls == .array) for (calls.array) |call| try appendCall(a, call, &ids, &names, &arguments); + } else for (got.events.items) |e| { + const v = (try json.parseText(a, e)).ok; + rejected += rejectedOf(v); + usageOf(v, &usage); + try keptOf(a, v, &kept); + try idsOf(a, v, &token_ids); + const choices = v.get("choices") orelse continue; + if (choices != .array or choices.array.len == 0) continue; + const first = choices.array[0]; + const d = if (first.get("delta")) |delta| delta else first; + if (first.get("finish_reason")) |f| if (f == .string) { + finish = f.string; + }; + if (d.get("reasoning_content")) |r| if (r == .string) try reasoning.appendSlice(a, r.string); + if (d.get("content")) |c| if (c == .string) try content.appendSlice(a, c.string); + if (d.get("text")) |c| if (c == .string) try content.appendSlice(a, c.string); + if (d.get("tool_calls")) |calls| if (calls == .array) for (calls.array) |call| try appendCall(a, call, &ids, &names, &arguments); + } + return .{ .reasoning = reasoning.items, .content = content.items, .ids = ids.items, .names = names.items, .arguments = arguments.items, .rejected = rejected, .finish = finish, .usage = usage, .kept = kept, .eos_len = script.eos_len, .grammars = grammars.compiled, .tool_grammars = tool_grammars.compiled, .token_ids = token_ids }; +} + +pub fn ask(a: std.mem.Allocator, kind: []const u8, reply: []const u32, extra: []const u8, stream: bool, stride: usize) !Seen { + return run(a, kind, reply, extra, stream, stride, "\"messages\":[{\"role\":\"user\",\"content\":\"Hi\"}]", true); +} + +/// The same route, whose scripted backend commits through the production lane Stream. +pub fn askLane(a: std.mem.Allocator, kind: []const u8, reply: []const u32, extra: []const u8, stream: bool, stride: usize) !Seen { + return runMode(a, kind, reply, extra, stream, stride, "\"messages\":[{\"role\":\"user\",\"content\":\"Hi\"}]", true, true); +} + +fn askRaw(a: std.mem.Allocator, reply: []const u32, stream: bool, stride: usize) !Seen { + return run(a, "inkling2", reply, "", stream, stride, "\"prompt\":\"Hi\"", false); +} + +pub fn encodeReply(a: std.mem.Allocator, raw: []const u8) ![]const u32 { + var fx = try Fixture.init(a, "inkling2"); + defer fx.deinit(); + var problem: []const u8 = ""; + const hf = try HfText.load(a, t.io, fx.path, null, a, &problem); + defer hf.deinit(); + return hf.text().encode(a, raw, false); +} + +/// Compare the whole body with streams at several engine chunk widths. +fn probe(a: std.mem.Allocator, raw: []const u8, extra: []const u8) !Seen { + return probeIds(a, "inkling2", try encodeReply(a, raw), extra); +} + +pub fn probeIds(a: std.mem.Allocator, kind: []const u8, reply: []const u32, extra: []const u8) !Seen { + const whole = try ask(a, kind, reply, extra, false, 1); + for ([_]usize{ 1, 2, 3, 256 }) |stride| { + const s = try ask(a, kind, reply, extra, true, stride); + try t.expectEqualStrings(whole.content, s.content); + try t.expectEqualStrings(whole.reasoning, s.reasoning); + try t.expectEqualStrings(whole.ids, s.ids); + try t.expectEqualStrings(whole.names, s.names); + try t.expectEqualStrings(whole.arguments, s.arguments); + try t.expectEqualStrings(whole.finish, s.finish); + } + return whole; +} + +test "Inkling 2 reply: the supplied raw reply splits without exposing controls or requiring EOS" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const got = try probe(arena.allocator(), sample, ""); + try t.expectEqualStrings(thought, got.reasoning); + try t.expectEqualStrings("391", got.content); + try t.expectEqualStrings("", got.ids); + try t.expectEqualStrings("", got.names); + try t.expectEqualStrings("", got.arguments); +} + +test "Inkling 2 reply: repeated blocks and a native JSON tool call agree whole and streamed" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const raw = "<|message_model|><|content_thinking|>Check <|end_message|>" ++ + "<|message_model|><|content_text|>Before<|end_message|>" ++ + "<|message_model|>lookup<|content_invoke_tool_json|>{\"name\":\"lookup\",\"args\":{\"q\":\"x\",\"nested\":{\"ok\":true}}}<|end_message|>" ++ + "<|content_text|> After<|end_message|><|content_model_end_sampling|>"; + const tools = ",\"tools\":[{\"type\":\"function\",\"function\":{\"name\":\"lookup\",\"parameters\":{\"type\":\"object\"}}}]"; + const got = try probe(arena.allocator(), raw, tools); + try t.expectEqualStrings("Check ", got.reasoning); + try t.expectEqualStrings("Before After", got.content); + try t.expectEqualStrings("call_0", got.ids); + try t.expectEqualStrings("lookup", got.names); + try t.expectEqualStrings("{\"q\":\"x\",\"nested\":{\"ok\":true}}", got.arguments); +} + +test "Inkling 2 reply: another model keeps the same token bytes on the previous generic path" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const reply = try encodeReply(a, sample); + const whole = try ask(a, "not_inkling2", reply, "", false, 1); + try t.expectEqualStrings(sample, whole.content); + try t.expectEqualStrings("", whole.reasoning); + for ([_]usize{ 1, 2, 256 }) |stride| { + const streamed = try ask(a, "not_inkling2", reply, "", true, stride); + try t.expectEqualStrings(sample, streamed.content); + try t.expectEqualStrings("", streamed.reasoning); + } +} + +test "Inkling 2 reply: raw completions keep control spellings literal whole and streamed" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const reply = try encodeReply(a, sample); + const whole = try askRaw(a, reply, false, 1); + try t.expectEqualStrings(sample, whole.content); + try t.expectEqualStrings("", whole.reasoning); + for ([_]usize{ 1, 2, 256 }) |stride| { + const streamed = try askRaw(a, reply, true, stride); + try t.expectEqualStrings(sample, streamed.content); + try t.expectEqualStrings("", streamed.reasoning); + } +} + +test "Inkling 2 reply: the tokenizer's other special tokens inside blocks never reach the client" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const raw = "<|message_model|><|content_thinking|>a<|endoftext|>b<|end_message|>" ++ + "<|message_model|><|content_text|>A<|begin_of_text|>B<|endoftext|>C<|content_xml|>D<|end_message|>"; + const got = try probe(arena.allocator(), raw, ""); + try t.expectEqualStrings("ab", got.reasoning); + try t.expectEqualStrings("ABCD", got.content); +} + +test "Inkling 2 reply: a refused call is counted for the client, whole and streamed" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const raw = "<|message_model|>other<|content_invoke_tool_json|>{\"name\":\"other\",\"args\":{}}<|end_message|>"; + const tools = ",\"tools\":[{\"type\":\"function\",\"function\":{\"name\":\"lookup\",\"parameters\":{\"type\":\"object\"}}}]"; + const reply = try encodeReply(a, raw); + const whole = try ask(a, "inkling2", reply, tools, false, 1); + try t.expectEqual(@as(i64, 1), whole.rejected); + try t.expectEqualStrings("", whole.content); + const streamed = try ask(a, "inkling2", reply, tools, true, 2); + try t.expectEqual(@as(i64, 1), streamed.rejected); +} + +pub const lookup = ",\"tools\":[{\"type\":\"function\",\"function\":{\"name\":\"lookup\",\"parameters\":{\"type\":\"object\"}}}]"; + +test "Inkling 2 reply: the Mini checkpoint's own files (model_type inkling2_loop) route chat through the split" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const got = try probeIds(a, "release", try encodeReply(a, sample), ""); + try t.expectEqualStrings(thought, got.reasoning); + try t.expectEqualStrings("391", got.content); + // cut inside thinking, and cut on the next header: the parts shown, never a marker + const cut = try probeIds(a, "release", try encodeReply(a, "<|message_model|><|content_thinking|>The user asks"), ""); + try t.expectEqualStrings("The user asks", cut.reasoning); + try t.expectEqualStrings("", cut.content); + try t.expectEqualStrings("length", cut.finish); + const header = try probeIds(a, "release", try encodeReply(a, "<|message_model|><|content_thinking|>Ensure.<|end_message|><|message_model|>"), ""); + try t.expectEqualStrings("Ensure.", header.reasoning); + try t.expectEqualStrings("", header.content); +} + +test "Inkling 2 reply: a grammar's bare JSON is the content, and its bare call envelope a call" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const json_reply = try probeIds(a, "release", try encodeReply(a, "{\"city\":\"Paris\"}"), ""); + try t.expectEqualStrings("{\"city\":\"Paris\"}", json_reply.content); + try t.expectEqualStrings("", json_reply.reasoning); + const raw = "{\"name\":\"lookup\",\"arguments\":{\"q\":\"x\"}}"; + // ended on the fixture's EOS (2), as a grammar's reply ends: a script that runs out reports the token cap + const call = try probeIds(a, "release", try std.mem.concat(a, u32, &.{ try encodeReply(a, raw), &.{2} }), lookup); + try t.expectEqualStrings("lookup", call.names); + try t.expectEqualStrings("{\"q\":\"x\"}", call.arguments); + try t.expectEqualStrings("", call.content); + try t.expectEqualStrings("tool_calls", call.finish); +} + +test "Inkling 2 reply: a stop string matches the raw reply, not text joined across removed controls" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const raw = "<|message_model|><|content_text|>left<|end_message|><|message_model|><|content_text|>RIGHT<|end_message|>"; + const got = try probe(arena.allocator(), raw, ",\"stop\":\"tR\""); + try t.expectEqualStrings("leftRIGHT", got.content); +} + +test "Inkling 2 reply: a raw stop after a finished call keeps the call and cuts only what follows" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const raw = "<|message_model|>lookup<|content_invoke_tool_json|>{\"name\":\"lookup\",\"args\":{\"q\":1}}<|end_message|>" ++ + "<|message_model|><|content_text|>done STOP more<|end_message|>"; + const got = try probe(arena.allocator(), raw, lookup ++ ",\"stop\":\"STOP\""); + try t.expectEqualStrings("lookup", got.names); + try t.expectEqualStrings("{\"q\":1}", got.arguments); + try t.expectEqualStrings("done ", got.content); + try t.expectEqualStrings("tool_calls", got.finish); +} + +test "Inkling 2 reply: a special token between a character's byte tokens leaves the character whole" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + // 138 and 110 are the byte tokens of CE B2, beta; the fixture's own ids for the controls and a special between them + const special = try encodeReply(a, "<|endoftext|>"); + try t.expectEqual(@as(usize, 1), special.len); + for ([_][]const u8{ "<|content_text|>", "<|content_thinking|>" }, 0..) |opener, i| { + const head = try encodeReply(a, try std.mem.concat(a, u8, &.{ "<|message_model|>", opener })); + const reply = try std.mem.concat(a, u32, &.{ head, &.{138}, special, &.{110}, try encodeReply(a, "<|end_message|>") }); + const got = try probeIds(a, "release", reply, ""); + try t.expectEqualStrings("\u{3b2}", if (i == 0) got.content else got.reasoning); + } +} + +/// The release fixture tokenizer's id for a control spelling: KS50's fixtures name the full tokenizer's 2000xx ids. +pub fn control(a: std.mem.Allocator, spelling: []const u8) !u32 { + const ids = try encodeReply(a, spelling); + try t.expectEqual(@as(usize, 1), ids.len); + return ids[0]; +} + +/// A KS50 fixture: its control spellings as the fixture tokenizer's ids, its byte and word ids exactly. +pub fn fixture(a: std.mem.Allocator, opener: []const u8, ids: []const u32) ![]const u32 { + return std.mem.concat(a, u32, &.{ &.{ try control(a, "<|message_model|>"), try control(a, opener) }, ids }); +} + +test "Inkling 2 reply: KS50 1, a bare grammar reply cut by the token cap returns its call cut, no markup" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const got = try probeIds(a, "release", try encodeReply(a, "{\"name\":\"lookup\",\"arguments\":{\"q\":\"x"), lookup); + try t.expectEqualStrings("lookup", got.names); + try t.expectEqualStrings("{\"q\":\"x", got.arguments); + try t.expectEqualStrings("", got.content); + try t.expectEqualStrings("length", got.finish); +} + +test "Inkling 2 reply: KS50 2, a stop spelled across a removed special shows nothing of it, streamed one token a time" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const reply = try fixture(a, "<|content_text|>", &.{ 64, try control(a, "<|unused_200030|>"), 65, 66 }); + const got = try probeIds(a, "release", reply, ",\"stop\":\"a<|unused_200030|>bc\""); + try t.expectEqualStrings("", got.content); + try t.expectEqualStrings("stop", got.finish); +} + +test "Inkling 2 reply: KS50 3, a stop after an invalid byte is placed in the exact bytes, not the lossy text" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const got = try probeIds(a, "release", try fixture(a, "<|content_text|>", &.{ 138, 50, 51, 46, 47 }), ",\"stop\":\"STOP\""); + try t.expectEqualStrings("\u{fffd}", got.content); +} + +test "Inkling 2 reply: KS50 4, an unfinished character at the cap reads as one replacement" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const got = try probeIds(a, "release", try fixture(a, "<|content_text|>", &.{ 156, 254 }), ""); + try t.expectEqualStrings("\u{fffd}", got.content); + try t.expectEqualStrings("length", got.finish); +} + +test "Inkling 2 reply: KS50 5, a stop inside thinking cuts what is shown, never the usage" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const got = try probeIds(a, "release", try fixture(a, "<|content_thinking|>", &.{268}), ",\"stop\":\"he\""); + try t.expectEqualStrings("t", got.reasoning); + try t.expectEqual(@as(i64, 3), got.usage.completion); + try t.expectEqual(@as(i64, 3), got.usage.reasoning); +} + +test "Inkling 2 reply: KS50 6, a bare reply's unoffered envelope is reported as the shared route reports it" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const envelope = "{\"name\":\"other\",\"arguments\":{}}"; + const reply = try encodeReply(a, envelope ++ "<|content_model_end_sampling|>"); + for ([_]bool{ false, true }) |stream| { + const got = try ask(a, "release", reply, lookup, stream, 1); + try t.expectEqualStrings(envelope, got.content); + try t.expectEqualStrings("{\"unoffered\":1,\"malformed\":0,\"unoffered_names\":[\"other\"]}", got.kept); + } +} + +test "Inkling 2 reply: KS50 7, a stop of ten two-byte characters ends the reply at its last byte token" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var body: [21]u32 = undefined; + body[0] = 32; + for (0..10) |i| { + body[1 + 2 * i] = 127; + body[2 + 2 * i] = 102; + } + const reply = try std.mem.concat(a, u32, &.{ try fixture(a, "<|content_text|>", &body), &.{89} }); + const got = try probeIds(a, "release", reply, ",\"stop\":\"\u{e9}\u{e9}\u{e9}\u{e9}\u{e9}\u{e9}\u{e9}\u{e9}\u{e9}\u{e9}\",\"ignore_eos\":true"); + try t.expectEqualStrings("A", got.content); + try t.expectEqualStrings("stop", got.finish); + try t.expectEqual(@as(i64, 23), got.usage.completion); +} diff --git a/zig/src/server/inkling2_fake.zig b/zig/src/server/inkling2_fake.zig new file mode 100644 index 00000000000..50fc29a658a --- /dev/null +++ b/zig/src/server/inkling2_fake.zig @@ -0,0 +1,153 @@ +//! A fake Inkling 2 tokenizer for the reply parser's host tests: listed pieces, their ids and added flags. +const std = @import("std"); +const json = @import("json"); +const model_text = @import("model_text.zig"); +const reply = @import("inkling2_reply.zig"); +const Allocator = std.mem.Allocator; +const Value = json.Value; + +pub const Piece = struct { + id: u32, + text: []const u8, + added: bool = false, +}; + +pub fn plain(id: u32, text: []const u8) Piece { + return .{ .id = id, .text = text }; +} + +pub const message_model = Piece{ .id = 200001, .text = "<|message_model|>", .added = true }; +pub const content_text = Piece{ .id = 200004, .text = "<|content_text|>", .added = true }; +pub const end_sampling = Piece{ .id = 200006, .text = "<|content_model_end_sampling|>", .added = true }; +pub const content_thinking = Piece{ .id = 200008, .text = "<|content_thinking|>", .added = true }; +pub const end_message = Piece{ .id = 200010, .text = "<|end_message|>", .added = true }; +pub const content_tool_error = Piece{ .id = 200022, .text = "<|content_tool_error|>", .added = true }; +pub const content_tool_json = Piece{ .id = 200049, .text = "<|content_invoke_tool_json|>", .added = true }; +pub const content_tool_text = Piece{ .id = 200057, .text = "<|content_invoke_tool_text|>", .added = true }; +// The tokenizer's other special tokens, none of them a reply control. +pub const message_user = Piece{ .id = 200000, .text = "<|message_user|>", .added = true }; +pub const message_tool = Piece{ .id = 200003, .text = "<|message_tool|>", .added = true }; +pub const message_system = Piece{ .id = 200002, .text = "<|message_system|>", .added = true }; +pub const end_of_text = Piece{ .id = 199999, .text = "<|endoftext|>", .added = true }; +pub const content_xml = Piece{ .id = 200024, .text = "<|content_xml|>", .added = true }; +pub const unused = Piece{ .id = 200030, .text = "<|unused_200030|>", .added = true }; + +/// Token ids the fake has decoded, summed over every call. +pub var decoded_ids: usize = 0; + +pub const Fake = struct { + pieces: []const Piece, + + pub fn text(f: *Fake) model_text.Text { + return .{ + .ctx = f, + .vtable = &.{ + .encode = encode, + .decode = decode, + .token_id = tokenId, + .token_string = tokenString, + .vocab_size = vocabSize, + .eos_ids = eosIds, + .render = render, + .template_source = templateSource, + .added = added, + .special = added, // every added Inkling 2 token is special in its tokenizer config + }, + }; + } + + fn find(f: *const Fake, id: u32) ?Piece { + for (f.pieces) |piece| if (piece.id == id) return piece; + return null; + } + + fn encode(ctx: *anyopaque, a: Allocator, input: []const u8, _: bool) model_text.Error![]u32 { + const f: *Fake = @ptrCast(@alignCast(ctx)); + for (f.pieces) |piece| if (std.mem.eql(u8, input, piece.text)) { + const ids = try a.alloc(u32, 1); + ids[0] = piece.id; + return ids; + }; + return error.Template; + } + + fn decode(ctx: *anyopaque, a: Allocator, ids: []const u32) Allocator.Error![]u8 { + const f: *Fake = @ptrCast(@alignCast(ctx)); + decoded_ids += ids.len; + var out: std.ArrayList(u8) = .empty; + errdefer out.deinit(a); + for (ids) |id| { + const piece = f.find(id) orelse std.debug.panic("unknown fake token {d}", .{id}); + try out.appendSlice(a, piece.text); + } + return out.toOwnedSlice(a); + } + + fn tokenId(ctx: *anyopaque, spelling: []const u8) ?u32 { + const f: *Fake = @ptrCast(@alignCast(ctx)); + for (f.pieces) |piece| if (piece.added and std.mem.eql(u8, spelling, piece.text)) return piece.id; + return null; + } + + fn tokenString(ctx: *anyopaque, a: Allocator, id: u32) Allocator.Error![]u8 { + const f: *Fake = @ptrCast(@alignCast(ctx)); + const piece = f.find(id) orelse return a.dupe(u8, ""); + return a.dupe(u8, piece.text); + } + + fn vocabSize(_: *anyopaque) u32 { + return 200058; + } + + fn eosIds(_: *anyopaque) []const u32 { + return &.{200006}; + } + + fn added(ctx: *anyopaque, id: u32) bool { + const f: *Fake = @ptrCast(@alignCast(ctx)); + const piece = f.find(id) orelse return false; + return piece.added; + } + + fn render(_: *anyopaque, _: Allocator, _: Value, _: model_text.RenderOptions, _: *[]const u8) model_text.Error!model_text.Rendered { + return error.Template; + } + + fn templateSource(_: *anyopaque) []const u8 { + return ""; + } +}; + +pub fn parse(a: Allocator, pieces: []const Piece, tools: []const Value) !reply.Result { + var fake: Fake = .{ .pieces = pieces }; + const ids = try a.alloc(u32, pieces.len); + for (pieces, ids) |piece, *id| id.* = piece.id; + return reply.parse(a, fake.text(), ids, tools); +} + +pub fn offeredTools(a: Allocator, names: []const []const u8) ![]Value { + const tools = try a.alloc(Value, names.len); + for (names, tools) |name, *tool| { + const function = try json.newObject(a); + try function.put(a, "name", .{ .string = name }); + const object = try json.newObject(a); + try object.put(a, "type", .{ .string = "function" }); + try object.put(a, "function", .{ .object = function }); + tool.* = .{ .object = object }; + } + return tools; +} + +pub fn expectCall(calls: ?[]Value, index: usize, name: []const u8, arguments: []const u8) !void { + try std.testing.expect(calls != null); + const all = calls.?; + try std.testing.expect(all.len > index); + const call = all[index]; + var id_buffer: [32]u8 = undefined; + const id = try std.fmt.bufPrint(&id_buffer, "call_{d}", .{index}); + try std.testing.expectEqualStrings(id, call.get("id").?.string); + try std.testing.expectEqualStrings("function", call.get("type").?.string); + const function = call.get("function").?; + try std.testing.expectEqualStrings(name, function.get("name").?.string); + try std.testing.expectEqualStrings(arguments, function.get("arguments").?.string); +} diff --git a/zig/src/server/inkling2_ks51_test.zig b/zig/src/server/inkling2_ks51_test.zig new file mode 100644 index 00000000000..cb472bf5969 --- /dev/null +++ b/zig/src/server/inkling2_ks51_test.zig @@ -0,0 +1,106 @@ +//! KS51's four Inkling 2 release-path findings through the route, whole and streamed at strides 1, 2, 3 and 256. +const std = @import("std"); +const h = @import("inkling2_chat_test.zig"); +const t = std.testing; + +/// Byte tokens of the release fixture's ByteLevel alphabet, by the byte each carries. +fn byte(b: u8) u32 { + return switch (b) { + 0x80 => 222, + 0x8F => 237, + 0x90 => 238, + 0x9F => 253, + 0xA0 => 254, + 0xBF => 123, + 0xC0 => 124, + 0xC1 => 125, + 0xC2 => 126, + 0xCE => 138, + 0xE0 => 156, + 0xED => 169, + 0xEE => 170, + 0xF0 => 172, + 0xF4 => 176, + 0xF5 => 177, + else => unreachable, + }; +} + +fn text(a: std.mem.Allocator, bytes: []const u8) ![]const u32 { + const ids = try a.alloc(u32, bytes.len); + for (bytes, ids) |b, *id| id.* = byte(b); + return h.fixture(a, "<|content_text|>", ids); +} + +test "Inkling 2 reply: KS51 1, a replacement-character stop cuts where the generation found it" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + // CE alone decodes as U+FFFD: the generation's stop, and the cut's + const alone = try h.probeIds(a, "release", try text(a, &.{0xCE}), ",\"stop\":\"\u{fffd}\""); + try t.expectEqualStrings("", alone.content); + try t.expectEqualStrings("stop", alone.finish); + // U+FFFD before ASCII stop text, and the ASCII stop beside it + const with_stop = try h.fixture(a, "<|content_text|>", &.{ 138, 50, 51, 46, 47 }); + const before = try h.probeIds(a, "release", with_stop, ",\"stop\":\"\u{fffd}STOP\""); + try t.expectEqualStrings("", before.content); + try t.expectEqualStrings("stop", before.finish); + const beside = try h.probeIds(a, "release", with_stop, ",\"stop\":\"STOP\""); + try t.expectEqualStrings("\u{fffd}", beside.content); +} + +test "Inkling 2 reply: KS51 2, every invalid UTF-8 form reads as the tokenizer's replacements, valid boundaries as text" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const r = "\u{fffd}"; + const Case = struct { bytes: []const u8, want: []const u8 }; + const cases = [_]Case{ + .{ .bytes = &.{ 0xC0, 0x80 }, .want = r ++ r }, // overlong two-byte lead + .{ .bytes = &.{ 0xC1, 0xBF }, .want = r ++ r }, + .{ .bytes = &.{ 0xE0, 0x80, 0x80 }, .want = r ++ r ++ r }, // overlong three-byte form + .{ .bytes = &.{ 0xF0, 0x80, 0x80, 0x80 }, .want = r ++ r ++ r ++ r }, // overlong four-byte form + .{ .bytes = &.{ 0xED, 0xA0, 0x80 }, .want = r ++ r ++ r }, // a surrogate + .{ .bytes = &.{ 0xF4, 0x90, 0x80, 0x80 }, .want = r ++ r ++ r ++ r }, // past U+10FFFF + .{ .bytes = &.{ 0xF5, 0x80, 0x80, 0x80 }, .want = r ++ r ++ r ++ r }, // a lead past F4 + .{ .bytes = &.{ 0xF5, 0x80 }, .want = r ++ r }, // the same, cut by the cap + .{ .bytes = &.{ 0xC2, 0x80 }, .want = "\u{80}" }, // the valid boundaries + .{ .bytes = &.{ 0xED, 0x9F, 0xBF }, .want = "\u{d7ff}" }, + .{ .bytes = &.{ 0xEE, 0x80, 0x80 }, .want = "\u{e000}" }, + .{ .bytes = &.{ 0xF0, 0x90, 0x80, 0x80 }, .want = "\u{10000}" }, + .{ .bytes = &.{ 0xF4, 0x8F, 0xBF, 0xBF }, .want = "\u{10ffff}" }, + }; + for (cases) |case| try t.expectEqualStrings(case.want, (try h.probeIds(a, "release", try text(a, case.bytes), "")).content); +} + +test "Inkling 2 reply: KS51 3, finished bare calls before a cut one all return, and the reply keeps length" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const one = "{\"name\":\"lookup\",\"arguments\":{\"q\":\"one\"}}"; + const two = try h.probeIds(a, "release", try h.encodeReply(a, one ++ "{\"name\":\"lookup\",\"arguments\":{\"q\":\"tw"), h.lookup); + try t.expectEqualStrings("lookuplookup", two.names); + try t.expectEqualStrings("{\"q\":\"one\"}{\"q\":\"tw", two.arguments); + try t.expectEqualStrings("", two.content); + try t.expectEqualStrings("length", two.finish); + const many = try h.probeIds(a, "release", try h.encodeReply(a, one ++ one ++ "{\"name\":\"lookup\",\"arguments\":{\"q\":\"x"), h.lookup); + try t.expectEqualStrings("lookuplookuplookup", many.names); + try t.expectEqualStrings("length", many.finish); + const prose = try h.probeIds(a, "release", try h.encodeReply(a, "Sure.{\"name\":\"lookup\",\"arguments\":{\"q\":\"x"), h.lookup); + try t.expectEqualStrings("lookup", prose.names); + try t.expectEqualStrings("{\"q\":\"x", prose.arguments); + try t.expectEqualStrings("Sure.", prose.content); + try t.expectEqualStrings("length", prose.finish); +} + +test "Inkling 2 reply: KS51 4, under one call a bare call cut by the cap is no call and no text" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const cut = try h.encodeReply(a, "{\"name\":\"lookup\",\"arguments\":{\"q\":\"x"); + const got = try h.probeIds(a, "release", cut, h.lookup ++ ",\"parallel_tool_calls\":false"); + try t.expectEqualStrings("", got.names); + try t.expectEqualStrings("", got.arguments); + try t.expectEqualStrings("", got.content); + try t.expectEqualStrings("length", got.finish); +} diff --git a/zig/src/server/inkling2_ks53_test.zig b/zig/src/server/inkling2_ks53_test.zig new file mode 100644 index 00000000000..38e62fe5e74 --- /dev/null +++ b/zig/src/server/inkling2_ks53_test.zig @@ -0,0 +1,91 @@ +//! KS53's two Inkling 2 findings and the stop boundaries around them, whole and streamed at strides 1, 2, 3 and 256. +const std = @import("std"); +const h = @import("inkling2_chat_test.zig"); +const t = std.testing; + +const strides = [_]usize{ 1, 2, 3, 256 }; + +/// A raw completion's reply, whole and at every stride: the same content, finish and completion tokens. +fn raw(a: std.mem.Allocator, reply: []const u32, extra: []const u8) !h.Seen { + const whole = try h.run(a, "release", reply, extra, false, 1, "\"prompt\":\"Hi\"", false); + for (strides) |stride| { + const s = try h.run(a, "release", reply, extra, true, stride, "\"prompt\":\"Hi\"", false); + try t.expectEqualStrings(whole.content, s.content); + try t.expectEqualStrings(whole.finish, s.finish); + try t.expectEqual(whole.usage.completion, s.usage.completion); + } + return whole; +} + +test "Inkling 2 reply: KS53 1, a raw reply opening on an invalid byte meets a replacement stop at offset zero" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + // 222 is byte 80 and 32 is A: no character before the reply owns 80, so it reads as U+FFFD and stops there + const first = try raw(a, &.{ 222, 32 }, ",\"stop\":\"\u{fffd}\""); + try t.expectEqualStrings("", first.content); + try t.expectEqualStrings("stop", first.finish); + try t.expectEqual(@as(i64, 1), first.usage.completion); + const spelled = try raw(a, &.{ 222, 50, 51, 46, 47 }, ",\"stop\":\"\u{fffd}STOP\""); + try t.expectEqualStrings("", spelled.content); + try t.expectEqualStrings("stop", spelled.finish); + try t.expectEqual(@as(i64, 5), spelled.usage.completion); +} + +test "Inkling 2 reply: KS53 2, a stop right after a bare envelope keeps its call, as the cut reply reads it" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const envelope = "{\"name\":\"lookup\",\"arguments\":{\"q\":\"x\"}}"; + const got = try h.probeIds(a, "release", try h.encodeReply(a, envelope ++ "<|message_model|>"), h.lookup ++ ",\"stop\":\"<|message_model|>\""); + try t.expectEqualStrings("lookup", got.names); + try t.expectEqualStrings("{\"q\":\"x\"}", got.arguments); + try t.expectEqualStrings("", got.content); + try t.expectEqualStrings("tool_calls", got.finish); +} + +test "Inkling 2 reply: stops at offset zero, at and inside controls, and at envelope edges, whole and streamed" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const envelope = "{\"name\":\"lookup\",\"arguments\":{\"q\":\"x\"}}"; + const Case = struct { reply: []const u8, stop: []const u8, tools: bool = false, content: []const u8 = "", reasoning: []const u8 = "", names: []const u8 = "", finish: []const u8 = "stop" }; + const cases = [_]Case{ + // offset zero of a block's text, and the reply's first control itself + .{ .reply = "<|message_model|><|content_text|>STOP more<|end_message|>", .stop = "STOP" }, + .{ .reply = "<|message_model|><|content_text|>hi<|end_message|>", .stop = "<|message_model|>" }, + // inside a control's spelling, a control with the text after it, and a thinking block's opener + .{ .reply = "<|message_model|><|content_text|>hi<|end_message|>", .stop = "content_text" }, + .{ .reply = "<|message_model|><|content_text|>hi<|end_message|>", .stop = "<|content_text|>hi" }, + .{ .reply = "<|message_model|><|content_thinking|>abc<|end_message|>", .stop = "<|content_thinking|>" }, + // right after a block's close + .{ .reply = "<|message_model|><|content_text|>hi<|end_message|><|message_model|>", .stop = "<|end_message|>", .content = "hi" }, + // a bare envelope's opening edge, and text right after its closing edge + .{ .reply = envelope, .stop = "", .tools = true }, + .{ .reply = envelope ++ "done", .stop = "done", .tools = true, .names = "lookup", .finish = "tool_calls" }, + }; + for (cases) |case| { + const extra = try std.fmt.allocPrint(a, "{s},\"stop\":{f}", .{ if (case.tools) h.lookup else "", std.json.fmt(case.stop, .{}) }); + const got = try h.probeIds(a, "release", try h.encodeReply(a, case.reply), extra); + try t.expectEqualStrings(case.content, got.content); + try t.expectEqualStrings(case.reasoning, got.reasoning); + try t.expectEqualStrings(case.names, got.names); + try t.expectEqualStrings(case.finish, got.finish); + } + // raw completions: an ASCII stop at offset zero, and windows opening on owned and unowned continuation bytes + const at_zero = try raw(a, &.{ 50, 51, 46, 47 }, ",\"stop\":\"STOP\""); + try t.expectEqualStrings("", at_zero.content); + try t.expectEqual(@as(i64, 4), at_zero.usage.completion); + // 13 tokens against a 12-token window: the last check's window opens on A9, which C3 before it owns + var owned: [13]u32 = @splat(32); + owned[0] = 127; + owned[1] = 102; + const whole_char = try raw(a, &owned, ",\"stop\":\"\u{fffd}A\""); + try t.expectEqualStrings("\u{e9}AAAAAAAAAAA", whole_char.content); + try t.expectEqualStrings("length", whole_char.finish); + try t.expectEqual(@as(i64, 13), whole_char.usage.completion); + const unowned = try raw(a, &.{ 32, 222, 32 }, ",\"stop\":\"\u{fffd}\""); + try t.expectEqualStrings("A", unowned.content); + try t.expectEqualStrings("stop", unowned.finish); + try t.expectEqual(@as(i64, 2), unowned.usage.completion); +} diff --git a/zig/src/server/inkling2_lane_script.zig b/zig/src/server/inkling2_lane_script.zig new file mode 100644 index 00000000000..be9e963a556 --- /dev/null +++ b/zig/src/server/inkling2_lane_script.zig @@ -0,0 +1,24 @@ +//! Scripted tokens through the actual lane commit/EOS logic, with the route's actual request ends. +const std = @import("std"); +const api = @import("engine_api"); +const lanes = @import("lanes"); + +pub fn submit(a: std.mem.Allocator, id: api.Id, request: *const api.Request, sink: api.Sink, reply: []const u32, stride: usize) !void { + var stream = try lanes.Stream.init(a, .{ + .id = "inkling-required-stop", + .prompt = request.prompt, + .max_new = request.max_tokens, + .eos = request.eos, + .drafts = false, + }); + defer stream.deinit(a); + var start: usize = 0; + while (start < reply.len and !stream.finished) { + const end = @min(start + stride, reply.len); + const before = stream.emitted().len; + const landed = try stream.commit(a, reply[start..end], &.{}); + if (landed > 0) sink.event(sink.ctx, id, &.{ .tokens = stream.emitted()[before..] }); + start += landed; + } + sink.event(sink.ctx, id, &.{ .finished = .{ .reason = if (stream.reason == .stop) .stop else .length } }); +} diff --git a/zig/src/server/inkling2_reply.zig b/zig/src/server/inkling2_reply.zig new file mode 100644 index 00000000000..a7960fa0e71 --- /dev/null +++ b/zig/src/server/inkling2_reply.zig @@ -0,0 +1,370 @@ +//! Inkling 2's full native reply, split by control-token identity rather than text. +const std = @import("std"); +const json = @import("json"); +const model_text = @import("model_text.zig"); +const native_reply = @import("native_reply.zig"); +const tool_specs = @import("tool_specs.zig"); +const Allocator = std.mem.Allocator; +const Value = json.Value; +pub const Result = native_reply.Result; + +const Kind = enum { + message_model, + message_other, // a user, system or tool header: never the model's turn + thinking, + content_text, + invoke_tool_text, + tool_error, + invoke_tool_json, + end_message, + end_sampling, +}; + +const Control = struct { kind: Kind, spelling: []const u8 }; +const controls = [_]Control{ + .{ .kind = .message_model, .spelling = "<|message_model|>" }, + .{ .kind = .message_other, .spelling = "<|message_user|>" }, + .{ .kind = .message_other, .spelling = "<|message_system|>" }, + .{ .kind = .message_other, .spelling = "<|message_tool|>" }, + .{ .kind = .thinking, .spelling = "<|content_thinking|>" }, + .{ .kind = .content_text, .spelling = "<|content_text|>" }, + .{ .kind = .invoke_tool_text, .spelling = "<|content_invoke_tool_text|>" }, + .{ .kind = .tool_error, .spelling = "<|content_tool_error|>" }, + .{ .kind = .invoke_tool_json, .spelling = "<|content_invoke_tool_json|>" }, + .{ .kind = .end_message, .spelling = "<|end_message|>" }, + .{ .kind = .end_sampling, .spelling = "<|content_model_end_sampling|>" }, +}; +const Resolved = [controls.len]?u32; +const State = enum { none, thinking, content, tool_json, foreign }; + +fn resolve(a: Allocator, text: model_text.Text) Allocator.Error!Resolved { + var out: Resolved = undefined; + for (&out) |*entry| entry.* = null; + for (controls, 0..) |control, i| { + const id = text.tokenId(control.spelling) orelse continue; + if (!text.isAdded(id)) continue; + const vocabulary_spelling = try text.tokenString(a, id); + defer a.free(vocabulary_spelling); + if (std.mem.eql(u8, vocabulary_spelling, control.spelling)) out[i] = id; + } + return out; +} + +fn controlKind(text: model_text.Text, ids: Resolved, id: u32) ?Kind { + if (!text.isAdded(id)) return null; + for (ids, controls) |control_id, control| if (control_id == id) return control.kind; + return null; +} + +const replacement = "\u{fffd}"; +const unicode = @import("tokenizer").unicode; + +/// `b` as the tokenizer's lossy decode reads it (`unicode.scan`), each piece and its offset into `sink`; returns used. +fn lossy(b: []const u8, done: bool, sink: anytype) Allocator.Error!usize { + var i: usize = 0; + while (i < b.len) { + const step = unicode.scan(b, i); + if (step.cp != null) { + try sink.emit(i, b[i..][0..step.len]); + } else if (!done and i + step.len == b.len and b[i] >= 0xC2 and b[i] <= 0xF4) { + break; // a character still arriving + } else try sink.emit(i, replacement); + i += step.len; + } + return i; +} + +/// A channel's whole UTF-8 characters, a tail waiting past dropped tokens; one U+FFFD per maximal invalid subpart. +const Channel = struct { + text: std.ArrayList(u8) = .empty, + tail: std.ArrayList(u8) = .empty, + + const Sink = struct { + a: Allocator, + out: *std.ArrayList(u8), + fn emit(k: @This(), _: usize, piece: []const u8) Allocator.Error!void { + try k.out.appendSlice(k.a, piece); + } + }; + + fn settle(c: *Channel, a: Allocator, b: []const u8, done: bool) Allocator.Error!usize { + return lossy(b, done, Sink{ .a = a, .out = &c.text }); + } + + fn add(c: *Channel, a: Allocator, bytes: []const u8) Allocator.Error!void { + try c.tail.appendSlice(a, bytes); + const b = c.tail.items; + const i = try c.settle(a, b, false); + std.mem.copyForwards(u8, b[0 .. b.len - i], b[i..]); + c.tail.shrinkRetainingCapacity(b.len - i); + } + + /// Whole characters while the reply grows; once it is done, an unfinished character reads as one replacement. + fn view(c: *const Channel, a: Allocator, done: bool) Allocator.Error![]const u8 { + if (!done or c.tail.items.len == 0) return c.text.items; + var out: Channel = .{}; + try out.text.appendSlice(a, c.text.items); + _ = try out.settle(a, c.tail.items, true); + return out.text.items; + } + + fn clear(c: *Channel) void { + c.text.clearRetainingCapacity(); + c.tail.clearRetainingCapacity(); + } +}; + +fn finishTool(a: Allocator, payload: []const u8, tools: []const Value, calls: *std.ArrayList(Value), rejected: *usize) Allocator.Error!void { + const document = switch (try json.parse(a, payload)) { + .ok => |value| value, + .err => { + rejected.* += 1; + return; + }, + }; + if (document != .object) { + rejected.* += 1; + return; + } + const name_value = document.get("name") orelse { + rejected.* += 1; + return; + }; + const arguments = document.get("args") orelse { + rejected.* += 1; + return; + }; + if (name_value != .string or arguments != .object) { + rejected.* += 1; + return; + } + const name = try a.dupe(u8, name_value.string); // Calls outlive the reusable payload. + var offered = false; + for (tools) |tool| { + if (std.mem.eql(u8, name, try tool_specs.toolName(a, tool))) { + offered = true; + break; + } + } + if (!offered) { + rejected.* += 1; + return; + } + + const function = try json.newObject(a); + try function.put(a, "name", .{ .string = name }); + try function.put(a, "arguments", .{ .string = try json.stringify(a, arguments, .{ .ascii = false, .compact = true }) }); + const call = try json.newObject(a); + try call.put(a, "id", .{ .string = try std.fmt.allocPrint(a, "call_{d}", .{calls.items.len}) }); + try call.put(a, "type", .{ .string = "function" }); + try call.put(a, "function", .{ .object = function }); + try calls.append(a, .{ .object = call }); +} + +/// The reply's raw text as its lossy decode reads it, controls spelled, and where each piece's exact bytes begin. +pub const RawText = struct { + text: std.ArrayList(u8) = .empty, + dec: std.ArrayList(usize) = .empty, // each piece's offset in `text` + src: std.ArrayList(usize) = .empty, // and its exact bytes' offset in the raw bytes + settled: usize = 0, + + const Sink = struct { + a: Allocator, + r: *RawText, + base: usize, + fn emit(k: @This(), at: usize, piece: []const u8) Allocator.Error!void { + try k.r.dec.append(k.a, k.r.text.items.len); + try k.r.src.append(k.a, k.base + at); + try k.r.text.appendSlice(k.a, piece); + } + }; + + fn add(r: *RawText, a: Allocator, raw: []const u8) Allocator.Error!void { + r.settled += try lossy(raw[r.settled..], false, Sink{ .a = a, .r = r, .base = r.settled }); + } + + /// The decoded text; once the reply is done, an unfinished character at its end reads as replacements. + pub fn view(r: *const RawText, a: Allocator, raw: []const u8, done: bool) Allocator.Error!RawText { + if (!done or r.settled == raw.len) return r.*; + var out: RawText = .{ .settled = r.settled }; + try out.text.appendSlice(a, r.text.items); + try out.dec.appendSlice(a, r.dec.items); + try out.src.appendSlice(a, r.src.items); + _ = try lossy(raw[r.settled..], true, Sink{ .a = a, .r = &out, .base = r.settled }); + return out; + } + + /// The exact-byte offset of decoded offset `at`, which starts a piece: a stop and its prefixes start on one. + pub fn exact(r: *const RawText, raw_len: usize, at: usize) usize { + if (at >= r.text.items.len) return raw_len; + var lo: usize = 0; + var hi: usize = r.dec.items.len; + while (hi - lo > 1) { + const mid = (lo + hi) / 2; + if (r.dec.items[mid] <= at) lo = mid else hi = mid; + } + return r.src.items[lo]; + } +}; + +/// Owns the reply parser between growing token prefixes; results borrow its arena-backed lists. +pub const Stream = struct { + a: Allocator, + text: model_text.Text, + resolved: Resolved, + content: Channel = .{}, + reasoning: Channel = .{}, + tool_payload: Channel = .{}, + calls: std.ArrayList(Value) = .empty, + state: State = .none, + reasoning_tokens: usize = 0, // every id from a thinking block's header through its close + header: usize = 0, // ids of the current message header so far, which a thinking block counts as its own + messages: usize = 0, // message headers seen; text before the first is a bare reply, as a grammar holds one + foreign: bool = false, // the newest header is a user, system or tool turn + rejected: usize = 0, // tool calls refused: malformed, unoffered, or left open by a new header + next: usize = 0, + raw: std.ArrayList(u8) = .empty, // the reply's exact token bytes, controls spelled, kept for stop strings + track_raw: bool = false, + raw_ok: bool = true, // every token has token-local bytes; false: the raw text cannot place a stop + decoded: RawText = .{}, // `raw` as the lossy decode reads it: stops are found there, then placed in `raw` + + pub fn init(a: Allocator, text: model_text.Text) Allocator.Error!Stream { + return .{ .a = a, .text = text, .resolved = try resolve(a, text) }; + } + + pub fn result(s: *const Stream, finished: bool) Allocator.Error!Result { + return .{ + .content = try s.content.view(s.a, finished), + .reasoning = try s.reasoning.view(s.a, finished), + .calls = if (s.calls.items.len == 0) null else s.calls.items, + .reasoning_tokens = s.reasoning_tokens, + .rejected = s.rejected > 0 or s.state == .tool_json, + .rejected_calls = s.rejected + @intFromBool(s.state == .tool_json), + .open_think = s.state == .thinking, + .bare = s.bare(), + }; + } + + /// The finished reply: an unfinished character at a channel's end reads as replacements. + pub fn done(s: *const Stream) Allocator.Error!Result { + return s.result(true); + } + + /// No message header has arrived: the reply is bare text, as a grammar from its first token writes. + pub fn bare(s: *const Stream) bool { + return s.messages == 0; + } + + /// Neither a listed control nor any other special token of the tokenizer: text a block holds. + pub fn payload(s: *const Stream, id: u32) bool { + return controlKind(s.text, s.resolved, id) == null and !s.text.isSpecial(id); + } + + fn channel(s: *Stream) ?*Channel { + return switch (s.state) { + .thinking => &s.reasoning, + .content => &s.content, + .tool_json => &s.tool_payload, + .none => if (s.bare()) &s.content else null, + .foreign => null, + }; + } + + /// Payload ids' bytes, token by token, so a character split around a dropped token stays whole. + fn add(s: *Stream, ch: *Channel, run: []const u32) Allocator.Error!void { + for (run, 0..) |id, i| { + const bytes = (try s.text.tokenBytes(s.a, id)) orelse { + // a decoder whose tokens' bytes depend on their neighbours: the rest of the run decodes as one + const decoded = try s.text.decode(s.a, run[i..]); + return ch.add(s.a, decoded); + }; + try ch.add(s.a, bytes); + } + } + + /// The first `len` bytes of payload token `id`, where a stop string cuts the reply inside it. + pub fn partial(s: *Stream, id: u32, bytes: []const u8) Allocator.Error!void { + if (!s.payload(id)) return; + if (s.channel()) |ch| try ch.add(s.a, bytes); + } + + /// Append `ids`' exact bytes to the raw text; a token without token-local bytes ends it. + fn keepRaw(s: *Stream, ids: []const u32) Allocator.Error!void { + for (ids) |id| { + if (!s.raw_ok) return; + if (try s.text.tokenBytes(s.a, id)) |bytes| try s.raw.appendSlice(s.a, bytes) else s.raw_ok = false; + } + if (s.raw_ok) try s.decoded.add(s.a, s.raw.items); + } + + /// Consume only the new suffix; ids is a monotonically growing full prefix, and EOS stripping must never shrink it. + pub fn extend(s: *Stream, ids: []const u32, tools: []const Value) Allocator.Error!Result { + std.debug.assert(ids.len >= s.next); + const from = s.next; + while (s.next < ids.len) { + const id = ids[s.next]; + const kind = controlKind(s.text, s.resolved, id); + if (kind == .message_model or kind == .message_other) { + // every role header is a hard boundary: it closes an open block, and a call in it never finished + if (s.state == .tool_json) s.rejected += 1; + s.state = .none; + s.messages += 1; + s.header = 1; + s.foreign = kind == .message_other; + s.next += 1; + continue; + } + if (s.state == .thinking) s.reasoning_tokens += 1; + if (kind == .end_sampling) { + // closes nothing: an open channel stays reported, and with ignore_eos the reply goes on + s.next += 1; + continue; + } + if (kind == .end_message) { + if (s.state == .tool_json) try finishTool(s.a, try s.tool_payload.view(s.a, true), tools, &s.calls, &s.rejected); + s.state = .none; + s.header = 0; + s.next += 1; + continue; + } + if (s.state == .none) if (kind) |found| { + s.state = if (s.foreign) .foreign else switch (found) { + .thinking => .thinking, + .content_text, .invoke_tool_text, .tool_error => .content, + .invoke_tool_json => .tool_json, + else => .none, + }; + if (s.state == .thinking) s.reasoning_tokens += s.header + 1; + if (s.state == .tool_json) s.tool_payload.clear(); + s.header = 0; + s.next += 1; + continue; + }; + const ch = s.channel() orelse { + // a header's name, a foreign turn's text, or text between blocks: never the reply's + if (s.state == .none and s.header > 0) s.header += 1; + s.next += 1; + continue; + }; + if (!s.payload(id)) { + // a control or any other special token inside a block is never payload + s.next += 1; + continue; + } + const start = s.next; + s.next += 1; + while (s.next < ids.len and s.payload(ids[s.next])) s.next += 1; + if (s.state == .thinking) s.reasoning_tokens += s.next - start - 1; + try s.add(ch, ids[start..s.next]); + } + if (s.track_raw) try s.keepRaw(ids[from..s.next]); + return s.result(false); + } +}; + +/// Parse a whole reply through the same cursor used by streamed replies. +pub fn parse(a: Allocator, text: model_text.Text, ids: []const u32, tools: []const Value) Allocator.Error!Result { + var stream = try Stream.init(a, text); + _ = try stream.extend(ids, tools); + return stream.done(); +} diff --git a/zig/src/server/inkling2_reply_test.zig b/zig/src/server/inkling2_reply_test.zig new file mode 100644 index 00000000000..4673d595724 --- /dev/null +++ b/zig/src/server/inkling2_reply_test.zig @@ -0,0 +1,461 @@ +//! Pure host coverage for Inkling 2 native reply splitting. +const std = @import("std"); +const json = @import("json"); +const model_text = @import("model_text.zig"); +const reply = @import("inkling2_reply.zig"); +const Allocator = std.mem.Allocator; +const Value = json.Value; + +const fx = @import("inkling2_fake.zig"); +const Piece = fx.Piece; +const plain = fx.plain; +const message_model = fx.message_model; +const content_text = fx.content_text; +const end_sampling = fx.end_sampling; +const content_thinking = fx.content_thinking; +const end_message = fx.end_message; +const content_tool_error = fx.content_tool_error; +const content_tool_json = fx.content_tool_json; +const content_tool_text = fx.content_tool_text; +const message_user = fx.message_user; +const message_system = fx.message_system; +const end_of_text = fx.end_of_text; +const content_xml = fx.content_xml; +const unused = fx.unused; +const Fake = fx.Fake; +const parse = fx.parse; +const offeredTools = fx.offeredTools; +const expectCall = fx.expectCall; + +test "Inkling 2 parse: raw checkpoint sample line two splits thinking and answer without sampling EOS" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const pieces = [_]Piece{ + message_model, + content_thinking, + plain(1, "The user asks: ... 340 + 51 = 391. ... "), + end_message, + message_model, + content_text, + plain(2, "391"), + end_message, + }; + const got = try parse(a, &pieces, &.{}); + try std.testing.expectEqualStrings("391", got.content); + try std.testing.expectEqualStrings("The user asks: ... 340 + 51 = 391. ... ", got.reasoning); + try std.testing.expectEqual(@as(usize, 4), got.reasoning_tokens); + try std.testing.expect(got.calls == null); + try std.testing.expect(!got.rejected); + try std.testing.expect(!got.open_think); +} + +test "Inkling 2 parse: named and unnamed repeated blocks join exactly without separators or stripping" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const pieces = [_]Piece{ + message_model, + plain(10, "first-name"), + content_thinking, + plain(11, " first\n"), + end_message, + content_text, + plain(12, "\nalpha"), + end_message, + message_model, + plain(13, "second-name"), + content_tool_text, + plain(14, " ฮฒ "), + end_message, + content_tool_error, + plain(15, "gamma\n"), + end_message, + message_model, + plain(16, "third-name"), + content_thinking, + plain(17, "second "), + }; + const got = try parse(a, &pieces, &.{}); + try std.testing.expectEqualStrings("\nalpha ฮฒ gamma\n", got.content); + try std.testing.expectEqualStrings(" first\nsecond ", got.reasoning); + try std.testing.expectEqual(@as(usize, 9), got.reasoning_tokens); + try std.testing.expect(got.calls == null); + try std.testing.expect(!got.rejected); + try std.testing.expect(got.open_think); +} + +test "Inkling 2 parse: nested scalar and escaped JSON and empty arguments become completed calls once" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const payload = + \\{"name":"lookup","args":{"nested":{"array":[1,true,null,"x"]},"scalar":-2.5,"escaped":"quote: \" slash: \\ line:\n snowman:โ˜ƒ"}} + ; + const pieces = [_]Piece{ + message_model, + plain(20, "a-header-name-that-is-not-the-function"), + content_tool_json, + plain(21, payload), + end_message, + content_tool_json, + plain(22, "{\"name\":\"empty\",\"args\":{}}"), + end_message, + }; + const tools = try offeredTools(a, &.{ "lookup", "empty" }); + const got = try parse(a, &pieces, tools); + try std.testing.expectEqualStrings("", got.content); + try std.testing.expectEqualStrings("", got.reasoning); + try std.testing.expectEqual(@as(usize, 0), got.reasoning_tokens); + try std.testing.expect(!got.rejected); + try std.testing.expect(!got.open_think); + try std.testing.expectEqual(@as(usize, 2), got.calls.?.len); + const arguments = + \\{"nested":{"array":[1,true,null,"x"]},"scalar":-2.5,"escaped":"quote: \" slash: \\ line:\n snowman:โ˜ƒ"} + ; + try expectCall(got.calls, 0, "lookup", arguments); + try expectCall(got.calls, 1, "empty", "{}"); +} + +test "Inkling 2 parse: malformed JSON envelopes are rejected without leaking their payloads" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const bad_payloads = [_][]const u8{ + "", + "{", + "[]", + "{}", + "{\"name\":1,\"args\":{}}", + "{\"name\":\"lookup\"}", + "{\"name\":\"lookup\",\"args\":[]}", + "{\"name\":\"lookup\",\"args\":null}", + "{\"name\":\"lookup\",\"args\":{},}", + "{\"name\":\"lookup\",\"args\":{}} trailing", + }; + const tools = try offeredTools(a, &.{"lookup"}); + for (bad_payloads, 0..) |payload, n| { + const pieces = [_]Piece{ content_tool_json, plain(@intCast(1000 + n), payload), end_message }; + const got = try parse(a, &pieces, tools); + try std.testing.expect(got.rejected); + try std.testing.expect(got.calls == null); + try std.testing.expectEqualStrings("", got.content); + try std.testing.expectEqualStrings("", got.reasoning); + try std.testing.expect(!got.open_think); + } +} + +test "Inkling 2 parse: an unoffered name is rejected and earlier completed output survives a later bad call" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const tools = try offeredTools(a, &.{"lookup"}); + const unoffered = [_]Piece{ + content_tool_json, + plain(30, "{\"name\":\"not-offered\",\"args\":{}}"), + end_message, + }; + const rejected = try parse(a, &unoffered, tools); + try std.testing.expect(rejected.rejected); + try std.testing.expect(rejected.calls == null); + try std.testing.expectEqualStrings("", rejected.content); + + const pieces = [_]Piece{ + content_thinking, + plain(31, "kept reasoning"), + end_message, + content_text, + plain(32, "kept content"), + end_message, + content_tool_json, + plain(33, "{\"name\":\"lookup\",\"args\":{\"x\":1}}"), + end_message, + content_tool_json, + plain(34, "{\"name\":\"not-offered\",\"args\":{}}"), + end_message, + }; + const got = try parse(a, &pieces, tools); + try std.testing.expect(got.rejected); + try std.testing.expectEqualStrings("kept content", got.content); + try std.testing.expectEqualStrings("kept reasoning", got.reasoning); + try std.testing.expectEqual(@as(usize, 3), got.reasoning_tokens); + try std.testing.expectEqual(@as(usize, 1), got.calls.?.len); + try expectCall(got.calls, 0, "lookup", "{\"x\":1}"); + try std.testing.expect(!got.open_think); +} + +test "Inkling 2 parse: every truncation class retains only its complete blocks and partial text channels" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const Case = struct { + pieces: []const Piece, + content: []const u8 = "", + reasoning: []const u8 = "", + reasoning_tokens: usize = 0, + rejected: bool = false, + open_think: bool = false, + }; + const empty = [_]Piece{}; + const header = [_]Piece{message_model}; + const named_header = [_]Piece{ message_model, plain(40, "unfinished-name") }; + const stray_text = [_]Piece{plain(41, "not-in-a-block")}; + const stray_close = [_]Piece{end_message}; + const empty_think = [_]Piece{content_thinking}; + const partial_think = [_]Piece{ message_model, content_thinking, plain(42, "partial thought") }; + const empty_text = [_]Piece{content_text}; + const partial_text = [_]Piece{ message_model, content_text, plain(43, "partial answer") }; + const partial_tool_text = [_]Piece{ content_tool_text, plain(44, "partial tool text") }; + const empty_json = [_]Piece{content_tool_json}; + const partial_json = [_]Piece{ content_tool_json, plain(45, "{\"name\":\"lookup\",\"args\":{") }; + const valid_unclosed_json = [_]Piece{ content_tool_json, plain(46, "{\"name\":\"lookup\",\"args\":{}}") }; + const completed_then_header = [_]Piece{ + content_thinking, + plain(47, "done"), + end_message, + content_text, + plain(48, "answer"), + end_message, + message_model, + plain(49, "unfinished-next-header"), + }; + const cases = [_]Case{ + .{ .pieces = &empty }, + .{ .pieces = &header }, + .{ .pieces = &named_header }, + .{ .pieces = &stray_text, .content = "not-in-a-block" }, // no header at all: a bare reply, as a grammar writes + .{ .pieces = &stray_close }, + .{ .pieces = &empty_think, .reasoning_tokens = 1, .open_think = true }, + .{ .pieces = &partial_think, .reasoning = "partial thought", .reasoning_tokens = 3, .open_think = true }, + .{ .pieces = &empty_text }, + .{ .pieces = &partial_text, .content = "partial answer" }, + .{ .pieces = &partial_tool_text, .content = "partial tool text" }, + .{ .pieces = &empty_json, .rejected = true }, + .{ .pieces = &partial_json, .rejected = true }, + .{ .pieces = &valid_unclosed_json, .rejected = true }, + .{ .pieces = &completed_then_header, .content = "answer", .reasoning = "done", .reasoning_tokens = 3 }, + }; + const tools = try offeredTools(a, &.{"lookup"}); + for (cases) |case| { + const got = try parse(a, case.pieces, tools); + try std.testing.expectEqualStrings(case.content, got.content); + try std.testing.expectEqualStrings(case.reasoning, got.reasoning); + try std.testing.expectEqual(case.reasoning_tokens, got.reasoning_tokens); + try std.testing.expectEqual(case.rejected, got.rejected); + try std.testing.expectEqual(case.open_think, got.open_think); + try std.testing.expect(got.calls == null); + } +} + +test "Inkling 2 parse: a sampling end closes nothing, so ignore_eos text goes on and open channels stay reported" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + // ignore_eos keeps decoding past the sampling end: the next message is the reply's too + const closed = [_]Piece{ + message_model, content_text, plain(50, "shown"), end_message, end_sampling, + message_model, content_text, plain(51, " next"), end_message, + }; + const done = try parse(a, &closed, &.{}); + try std.testing.expectEqualStrings("shown next", done.content); + try std.testing.expect(!done.rejected); + try std.testing.expect(!done.open_think); + + const thinking = [_]Piece{ content_thinking, plain(52, "open thought"), end_sampling }; + const open = try parse(a, &thinking, &.{}); + try std.testing.expectEqualStrings("open thought", open.reasoning); + try std.testing.expectEqualStrings("", open.content); + try std.testing.expect(open.open_think); + try std.testing.expect(!open.rejected); + + const tools = try offeredTools(a, &.{"lookup"}); + const tool = [_]Piece{ content_tool_json, plain(54, "{\"name\":\"lookup\",\"args\":{}}"), end_sampling }; + const incomplete = try parse(a, &tool, tools); + try std.testing.expect(incomplete.rejected); + try std.testing.expectEqual(@as(usize, 1), incomplete.rejected_calls); + try std.testing.expect(incomplete.calls == null); + try std.testing.expectEqualStrings("", incomplete.content); + try std.testing.expect(!incomplete.open_think); +} + +test "Inkling 2 parse: literal control spellings on ordinary token ids remain payload" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const pieces = [_]Piece{ + content_text, + plain(60, "<|content_thinking|>"), + plain(61, " and "), + plain(62, "<|end_message|>"), + plain(63, "<|content_model_end_sampling|>"), + end_message, + content_thinking, + plain(64, "<|content_text|>"), + end_message, + content_text, + plain(65, "tail"), + end_message, + }; + const got = try parse(a, &pieces, &.{}); + try std.testing.expectEqualStrings("<|content_thinking|> and <|end_message|><|content_model_end_sampling|>tail", got.content); + try std.testing.expectEqualStrings("<|content_text|>", got.reasoning); + try std.testing.expectEqual(@as(usize, 3), got.reasoning_tokens); + try std.testing.expect(!got.rejected); + try std.testing.expect(!got.open_think); +} + +test "Inkling 2 parse: reparsing every token prefix is monotonic and never exposes incomplete JSON" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const pieces = [_]Piece{ + message_model, // 0 + plain(70, "reasoner"), // 1 + content_thinking, // 2 + plain(71, "why"), // 3 + end_message, // 4 + message_model, // 5 + plain(72, "speaker"), // 6 + content_text, // 7 + plain(73, "before"), // 8 + end_message, // 9 + message_model, // 10 + plain(74, "lookup"), // 11 + content_tool_json, // 12 + plain(75, "{\"name\":\"lookup\",\"args\":{\"x\":1}}"), // 13 + end_message, // 14 + content_tool_error, // 15 + plain(76, "after"), // 16 + end_message, // 17 + end_sampling, // 18 + content_text, // 19 + plain(77, "next"), // 20: past the sampling end, as ignore_eos decodes it + end_message, // 21 + }; + const tools = try offeredTools(a, &.{"lookup"}); + var previous_content: []const u8 = ""; + var previous_reasoning: []const u8 = ""; + var previous_reasoning_tokens: usize = 0; + var previous_calls: usize = 0; + for (0..pieces.len + 1) |n| { + const got = try parse(a, pieces[0..n], tools); + try std.testing.expect(std.mem.startsWith(u8, got.content, previous_content)); + try std.testing.expect(std.mem.startsWith(u8, got.reasoning, previous_reasoning)); + try std.testing.expect(got.reasoning_tokens >= previous_reasoning_tokens); + const call_count = if (got.calls) |calls| calls.len else 0; + try std.testing.expect(call_count >= previous_calls); + try std.testing.expectEqual(@as(usize, if (n >= 15) 1 else 0), call_count); + try std.testing.expectEqual(@as(usize, if (n < 3) 0 else @min(n, 5)), got.reasoning_tokens); + try std.testing.expectEqual(n == 3 or n == 4, got.open_think); + try std.testing.expectEqual(n == 13 or n == 14, got.rejected); + if (call_count > 0) try expectCall(got.calls, 0, "lookup", "{\"x\":1}"); + try std.testing.expect(std.mem.indexOf(u8, got.content, "{\"name\"") == null); + previous_content = got.content; + previous_reasoning = got.reasoning; + previous_reasoning_tokens = got.reasoning_tokens; + previous_calls = call_count; + } + const final = try parse(a, &pieces, tools); + try std.testing.expectEqualStrings("beforeafternext", final.content); + try std.testing.expectEqualStrings("why", final.reasoning); + try std.testing.expectEqual(@as(usize, 5), final.reasoning_tokens); + try std.testing.expectEqual(@as(usize, 1), final.calls.?.len); + try std.testing.expect(!final.rejected); + try std.testing.expect(!final.open_think); +} + +test "Inkling 2 parse: the tokenizer's other special tokens inside a block are never payload, whole or streamed" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const pieces = [_]Piece{ + message_model, content_thinking, plain(70, "think"), end_of_text, plain(71, "ing"), end_message, + message_model, content_text, plain(72, "A"), unused, plain(73, "B"), end_of_text, + plain(74, "C"), content_xml, plain(75, "D"), unused, end_message, + }; + const whole = try parse(a, &pieces, &.{}); + try std.testing.expectEqualStrings("thinking", whole.reasoning); + try std.testing.expectEqualStrings("ABCD", whole.content); + var fake: Fake = .{ .pieces = &pieces }; + var stream = try reply.Stream.init(a, fake.text()); + var ids: [pieces.len]u32 = undefined; + for (&pieces, &ids) |piece, *id| id.* = piece.id; + var last: reply.Result = undefined; + for (1..ids.len + 1) |n| last = try stream.extend(ids[0..n], &.{}); + try std.testing.expectEqualStrings("thinking", last.reasoning); + try std.testing.expectEqualStrings("ABCD", last.content); +} + +test "Inkling 2 parse: a new message inside an unclosed block closes it, so its tool call parses" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const tools = try offeredTools(a, &.{"lookup"}); + const pieces = [_]Piece{ + message_model, content_text, plain(80, "Hi"), + message_model, plain(81, "lookup"), content_tool_json, + plain(82, "{\"name\":\"lookup\",\"args\":{\"q\":1}}"), end_message, + }; + const got = try parse(a, &pieces, tools); + try std.testing.expectEqualStrings("Hi", got.content); + try expectCall(got.calls, 0, "lookup", "{\"q\":1}"); + try std.testing.expect(!got.rejected); + // a call left open by the next message never finished: refused and counted, its payload never shown + const open_call = [_]Piece{ + message_model, content_tool_json, plain(83, "{\"name\":\"lookup\",\"args\":{}}"), + message_model, content_text, plain(84, "after"), + end_message, + }; + const cut = try parse(a, &open_call, tools); + try std.testing.expectEqualStrings("after", cut.content); + try std.testing.expect(cut.calls == null); + try std.testing.expectEqual(@as(usize, 1), cut.rejected_calls); +} + +test "Inkling 2 parse: every refused call is counted: unoffered, malformed and unfinished" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const tools = try offeredTools(a, &.{"lookup"}); + const pieces = [_]Piece{ + message_model, content_tool_json, plain(90, "{\"name\":\"other\",\"args\":{}}"), end_message, + message_model, content_tool_json, plain(91, "{\"name\":"), end_message, + message_model, content_tool_json, plain(92, "{\"name\":\"lookup\",\"args\":{}}"), end_message, + message_model, content_tool_json, plain(93, "{\"name\":\"lookup\""), + }; + const got = try parse(a, &pieces, tools); + try std.testing.expectEqual(@as(usize, 3), got.rejected_calls); + try expectCall(got.calls, 0, "lookup", "{}"); +} + +test "Inkling 2 parse: a stop string costs streamed frames no whole-reply decode" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var pieces: [3 + 64]Piece = undefined; + pieces[0] = message_model; + pieces[1] = content_text; + for (pieces[2 .. pieces.len - 1], 0..) |*piece, i| piece.* = plain(@intCast(100 + i), "x"); + pieces[pieces.len - 1] = end_message; + var fake: Fake = .{ .pieces = &pieces }; + const Srv = struct { text: model_text.Text }; + const srv: Srv = .{ .text = fake.text() }; + var g: struct { + a: Allocator, + chat: bool = true, + inkling2: ?reply.Stream = null, + tools: []const Value = &.{}, + srv: *const Srv, + stops: @import("reply_text.zig").Stops, + visible: @import("reply_text.zig").Incremental = .{}, + } = .{ .a = a, .srv = &srv, .stops = .{ .strings = &.{"STOP"} } }; + g.inkling2 = try reply.Stream.init(a, srv.text); + var ids: [pieces.len]u32 = undefined; + for (&pieces, &ids) |piece, *id| id.* = piece.id; + fx.decoded_ids = 0; + for (1..ids.len + 1) |n| _ = try @import("chat_inkling2.zig").read(&g, ids[0..n], false); + const done = try @import("chat_inkling2.zig").read(&g, &ids, true); + try std.testing.expectEqual(@as(usize, 64), done.content.len); + // each token decoded once by the parser and once for the finished reply's stop check: linear, not quadratic + try std.testing.expect(fx.decoded_ids <= 2 * ids.len); +} diff --git a/zig/src/server/inkling2_required_test.zig b/zig/src/server/inkling2_required_test.zig new file mode 100644 index 00000000000..b8ff1efe5b8 --- /dev/null +++ b/zig/src/server/inkling2_required_test.zig @@ -0,0 +1,180 @@ +//! Inkling 2 grammar replies: an end of message after a bare call ends the turn; finish_reason keeps the cap. +const std = @import("std"); +const h = @import("inkling2_chat_test.zig"); +const t = std.testing; + +const call_x = "{\"name\":\"lookup\",\"arguments\":{\"q\":\"x\"}}"; +const call_y = "{\"name\":\"lookup\",\"arguments\":{\"q\":\"y\"}}"; +/// The tools with tool_choice "required": the call grammar whose end of message may end the turn. +const required = h.lookup ++ ",\"tool_choice\":\"required\""; + +test "Inkling 2 reply: a bare call then its end of message ends the turn, not three repeats to the cap" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + // the served failure's shape: the call, the model's own end of the call's message, then what it wrote past it + const reply = try h.encodeReply(a, call_x ++ "<|end_message|>" ++ call_x ++ call_x); + const head = (try h.encodeReply(a, call_x ++ "<|end_message|>")).len; + const got = try h.probeIds(a, "release", reply, required); + try t.expectEqualStrings("lookup", got.names); + try t.expectEqualStrings("{\"q\":\"x\"}", got.arguments); + try t.expectEqualStrings("", got.content); + try t.expectEqualStrings("tool_calls", got.finish); + try t.expectEqual(@as(i64, @intCast(head)), got.usage.completion); +} + +test "Inkling 2 reply: a different second call still returns with parallel calls; parallel_tool_calls false keeps one" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const reply = try h.encodeReply(a, call_x ++ "\n" ++ call_y ++ "<|end_message|>" ++ call_x); + const two = try h.probeIds(a, "release", reply, required); + try t.expectEqualStrings("lookuplookup", two.names); + try t.expectEqualStrings("{\"q\":\"x\"}{\"q\":\"y\"}", two.arguments); + try t.expectEqualStrings("tool_calls", two.finish); + const one = try h.probeIds(a, "release", reply, required ++ ",\"parallel_tool_calls\":false"); + try t.expectEqualStrings("lookup", one.names); + try t.expectEqualStrings("{\"q\":\"x\"}", one.arguments); + try t.expectEqualStrings("", one.content); + try t.expectEqualStrings("tool_calls", one.finish); +} + +test "Inkling 2 reply: finished calls in a reply the token cap ended keep finish_reason length, bare or native" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const bare = try h.encodeReply(a, call_x ++ call_x); + const capped = try h.probeIds(a, "release", bare, try std.fmt.allocPrint(a, "{s},\"max_tokens\":{d}", .{ required, bare.len })); + try t.expectEqualStrings("lookuplookup", capped.names); + try t.expectEqualStrings("length", capped.finish); + const native = try h.encodeReply(a, "<|message_model|>lookup<|content_invoke_tool_json|>{\"name\":\"lookup\",\"args\":{\"q\":1}}<|end_message|>"); + const cut = try h.probeIds(a, "release", native, try std.fmt.allocPrint(a, "{s},\"max_tokens\":{d}", .{ required, native.len })); + try t.expectEqualStrings("lookup", cut.names); + try t.expectEqualStrings("length", cut.finish); + // the same calls ending before the cap, on the end of sampling, still report tool_calls + const ended = try h.probeIds(a, "release", try h.encodeReply(a, call_x ++ "<|end_message|>"), try std.fmt.allocPrint(a, "{s},\"max_tokens\":{d}", .{ required, bare.len + 8 })); + try t.expectEqualStrings("tool_calls", ended.finish); +} + +test "Inkling 2 reply: an end of message inside a native reply does not end the turn" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const text = try h.encodeReply(a, "<|message_model|><|content_thinking|>Plan.<|end_message|><|message_model|><|content_text|>391<|end_message|>"); + const reply = try std.mem.concat(a, u32, &.{ text, &.{2} }); // the fixture's EOS + const got = try h.probeIds(a, "release", reply, h.lookup); + try t.expectEqualStrings("Plan.", got.reasoning); + try t.expectEqualStrings("391", got.content); + try t.expectEqualStrings("stop", got.finish); +} + +/// The end ids a plain reply's request carries (the release fixture's eos ids). +fn plainEnds(a: std.mem.Allocator) !usize { + return (try h.probeIds(a, "release", try endsOwn(a, "x"), "")).eos_len; +} + +/// `text` then the release fixture's EOS (2), as a reply that ends on its own. +fn endsOwn(a: std.mem.Allocator, text: []const u8) ![]const u32 { + return std.mem.concat(a, u32, &.{ try h.encodeReply(a, text), &.{2} }); +} + +test "Inkling 2 reply: KS62 1, a bare end of message in a reply with no tools or auto tools does not end it" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const reply = try endsOwn(a, "left<|end_message|>right"); + for ([_][]const u8{ "", h.lookup }) |extra| { + const got = try h.probeIds(a, "release", reply, extra); + try t.expectEqualStrings("leftright", got.content); + try t.expectEqualStrings("stop", got.finish); + try t.expectEqual(try plainEnds(a), got.eos_len); + } +} + +test "Inkling 2 reply: KS62 2, a JSON grammar keeps its own ends and is not cut at an end of message" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const reply = try endsOwn(a, "{\"a\":1}<|end_message|>x"); + // the request boundary refuses a format beside a required call (grammar.refusal), so a format here stands alone + for ([_][]const u8{ "", h.lookup }) |tools| { + const extra = try std.mem.concat(a, u8, &.{ tools, ",\"response_format\":{\"type\":\"json_object\"}" }); + const got = try h.probeIds(a, "release", reply, extra); + try t.expectEqualStrings("{\"a\":1}x", got.content); + try t.expectEqual(try plainEnds(a), got.eos_len); + } +} + +test "Inkling 2 reply: a required call grammar takes the end of message, and only after a complete call" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const reply = try h.encodeReply(a, "<|end_message|>" ++ call_x ++ "<|end_message|>" ++ call_x); + const got = try h.probeIds(a, "release", reply, required); + try t.expectEqual(try plainEnds(a), got.eos_len); + try t.expectEqualStrings("lookup", got.names); + try t.expectEqualStrings("{\"q\":\"x\"}", got.arguments); + try t.expectEqualStrings("tool_calls", got.finish); +} + +test "Inkling 2 reply: KS64, a complete call then an open one: the end of message inside it does not end the turn" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const open_y = "{\"name\":\"lookup\",\"arguments\":{\"q\":\"y\"}}"; + const reply = try endsOwn(a, call_x ++ open_y ++ "<|end_message|>"); + const got = try h.probeIds(a, "release", reply, required); + try t.expectEqualStrings("lookuplookup", got.names); + try t.expectEqualStrings("{\"q\":\"x\"}{\"q\":\"y\"}", got.arguments); + try t.expectEqualStrings("tool_calls", got.finish); +} + +test "Inkling 2 reply: a required reply ends at an end of message only when it is complete calls and nothing else" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const Case = struct { reply: []const u8, names: []const u8, arguments: []const u8 }; + const cases = [_]Case{ + // a closed but malformed envelope after the call: refused, so the end inside the reply is not its end + .{ .reply = call_x ++ "{not json}<|end_message|>" ++ call_y, .names = "lookuplookup", .arguments = "{\"q\":\"x\"}{\"q\":\"y\"}" }, + // a complete call naming a tool not offered: refused the same way + .{ .reply = "{\"name\":\"other\",\"arguments\":{}}<|end_message|>" ++ call_x, .names = "lookup", .arguments = "{\"q\":\"x\"}" }, + // text beside the call + .{ .reply = call_x ++ "note<|end_message|>" ++ call_y, .names = "lookuplookup", .arguments = "{\"q\":\"x\"}{\"q\":\"y\"}" }, + // only blanks after the call: the reply is the call, so the end of message ends it + .{ .reply = call_x ++ "\n <|end_message|>" ++ call_y, .names = "lookup", .arguments = "{\"q\":\"x\"}" }, + // two complete calls: both, then the end + .{ .reply = call_x ++ call_y ++ "<|end_message|>" ++ call_x, .names = "lookuplookup", .arguments = "{\"q\":\"x\"}{\"q\":\"y\"}" }, + }; + for (cases) |case| { + const got = try h.probeIds(a, "release", try endsOwn(a, case.reply), required); + try t.expectEqualStrings(case.names, got.names); + try t.expectEqualStrings(case.arguments, got.arguments); + try t.expectEqualStrings("tool_calls", got.finish); + } +} + +test "Inkling 2 reply: a json_schema reply ends on the same token ids as before the call stop, whole and streamed" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + // the model's own end of message after the JSON, then the end of sampling (the fixture's EOS, 2) + const reply = try endsOwn(a, "{\"a\":1}<|end_message|>"); + const want = try std.json.Stringify.valueAlloc(a, reply, .{}); + const extra = ",\"return_token_ids\":true,\"response_format\":{\"type\":\"json_schema\",\"json_schema\":{\"name\":\"r\",\"schema\":{\"type\":\"object\"}}}"; + for ([_]usize{ 0, 1, 2, 3, 256 }) |stride| { + const got = try h.ask(a, "release", reply, extra, stride > 0, @max(stride, 1)); + // every generated id, the end of message and the end of sampling last, as 267544184f returns them + try t.expectEqualStrings(want, got.token_ids); + try t.expectEqualStrings("{\"a\":1}", got.content); + try t.expectEqualStrings("stop", got.finish); + // compiled by the shared compiler, whose ends are the eos ids alone, and sent with the plain ends + try t.expectEqual(@as(usize, 1), got.grammars); + try t.expectEqual(@as(usize, 0), got.tool_grammars); + try t.expectEqual(try plainEnds(a), got.eos_len); + } +} + +test { + _ = @import("inkling2_stop_test.zig"); +} diff --git a/zig/src/server/inkling2_stop_test.zig b/zig/src/server/inkling2_stop_test.zig new file mode 100644 index 00000000000..e3f0ebdb9d0 --- /dev/null +++ b/zig/src/server/inkling2_stop_test.zig @@ -0,0 +1,92 @@ +//! The partial second-call trigger at the route and production lane stop boundary, with token-id controls. +const std = @import("std"); +const h = @import("inkling2_chat_test.zig"); +const t = std.testing; +const call_x = "{\"name\":\"lookup\",\"arguments\":{\"q\":\"x\"}}"; +const open_y = "{\"name\":\"lookup\",\"arguments\":{\"q\":\"y\"}}"; +const required = h.lookup ++ ",\"tool_choice\":\"required\",\"return_token_ids\":true"; + +fn partialSecond(lane: bool) !void { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const reply = try std.mem.concat(a, u32, &.{ try h.encodeReply(a, call_x ++ open_y ++ "<|end_message|>"), &.{2} }); + const want = try std.json.Stringify.valueAlloc(a, reply, .{}); + const plain = try h.ask(a, "release", &.{2}, "", false, 1); + var failures: usize = 0; + for ([_]usize{ 0, 1, 2, 3, 256 }) |stride| { + const got = if (lane) try h.askLane(a, "release", reply, required, stride > 0, @max(stride, 1)) else try h.ask(a, "release", reply, required, stride > 0, @max(stride, 1)); + const exact = std.mem.eql(u8, "lookuplookup", got.names) and + std.mem.eql(u8, "{\"q\":\"x\"}{\"q\":\"y\"}", got.arguments) and + std.mem.eql(u8, "tool_calls", got.finish) and std.mem.eql(u8, want, got.token_ids) and + got.eos_len == plain.eos_len and got.grammars == 0 and got.tool_grammars == 1; + std.debug.print("INKLING_STOP_CELL lane={any} stride={d} exact={any} calls={s} eos={d}/{d}\n", .{ lane, stride, exact, got.names, got.eos_len, plain.eos_len }); + if (!exact) failures += 1; + } + try t.expectEqual(@as(usize, 0), failures); +} + +test "Inkling 2 reply: KS65 request EOS cannot cut an open second call at the route harness" { + try partialSecond(false); +} + +test "Inkling 2 reply: KS65 request EOS cannot cut an open second call at the production lane commit" { + try partialSecond(true); +} + +test "Inkling 2 reply: plain auto and JSON-schema token ids stay exact through both stop boundaries" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const plain = try h.ask(a, "release", &.{2}, "", false, 1); + const Case = struct { text: []const u8, extra: []const u8, grammars: usize = 0 }; + const cases = [_]Case{ + .{ .text = "left<|end_message|>right", .extra = "" }, + .{ .text = "left<|end_message|>right", .extra = h.lookup }, + .{ .text = "{\"a\":1}<|end_message|>", .extra = ",\"response_format\":{\"type\":\"json_schema\",\"json_schema\":{\"name\":\"r\",\"schema\":{\"type\":\"object\"}}}", .grammars = 1 }, + }; + for (cases) |case| { + const reply = try std.mem.concat(a, u32, &.{ try h.encodeReply(a, case.text), &.{2} }); + const want = try std.json.Stringify.valueAlloc(a, reply, .{}); + const extra = try std.mem.concat(a, u8, &.{ case.extra, ",\"return_token_ids\":true" }); + for ([_]bool{ false, true }) |lane| for ([_]usize{ 0, 1, 2, 3, 256 }) |stride| { + const got = if (lane) try h.askLane(a, "release", reply, extra, stride > 0, @max(stride, 1)) else try h.ask(a, "release", reply, extra, stride > 0, @max(stride, 1)); + try t.expectEqualStrings(want, got.token_ids); + try t.expectEqualStrings("stop", got.finish); + try t.expectEqual(plain.eos_len, got.eos_len); + try t.expectEqual(case.grammars, got.grammars); + try t.expectEqual(@as(usize, 0), got.tool_grammars); + }; + } +} + +test "Inkling 2 reply: non-Inkling required tools keep all token ids and the shared compiler" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const reply = try std.mem.concat(a, u32, &.{ try h.encodeReply(a, call_x ++ "<|end_message|>" ++ call_x), &.{2} }); + const want = try std.json.Stringify.valueAlloc(a, reply, .{}); + const plain = try h.ask(a, "not_inkling2", &.{2}, "", false, 1); + for ([_]bool{ false, true }) |lane| for ([_]usize{ 0, 1, 2, 3, 256 }) |stride| { + const got = if (lane) try h.askLane(a, "not_inkling2", reply, required, stride > 0, @max(stride, 1)) else try h.ask(a, "not_inkling2", reply, required, stride > 0, @max(stride, 1)); + try t.expectEqualStrings(want, got.token_ids); + try t.expectEqualStrings("lookuplookup", got.names); + try t.expectEqual(plain.eos_len, got.eos_len); + try t.expectEqual(@as(usize, 1), got.grammars); + try t.expectEqual(@as(usize, 0), got.tool_grammars); + }; +} + +test "Inkling 2 reply: complete-call stop requires a surviving required-tool grammar" { + const callEnd = @import("chat_inkling2.zig").callEnd; + const api = @import("engine_api"); + var srv: struct { text: struct { native_inkling2: bool } } = .{ .text = .{ .native_inkling2 = true } }; + const tool: api.Structure = .{ .kind = .structural_tag, .field = "tool_choice" }; + try t.expect(callEnd(&srv, true, tool)); + try t.expect(!callEnd(&srv, false, tool)); + try t.expect(!callEnd(&srv, true, null)); + try t.expect(!callEnd(&srv, true, .{ .kind = .json_schema, .field = "response_format" })); + try t.expect(!callEnd(&srv, true, .{ .kind = .structural_tag, .field = "guided_structural_tag" })); + srv.text.native_inkling2 = false; + try t.expect(!callEnd(&srv, true, tool)); +} diff --git a/zig/src/server/kimi_reply.zig b/zig/src/server/kimi_reply.zig index 71a0161ca0c..44e09893bce 100644 --- a/zig/src/server/kimi_reply.zig +++ b/zig/src/server/kimi_reply.zig @@ -7,14 +7,7 @@ const values = @import("kimi_values.zig"); const V = json.Value; const A = std.mem.Allocator; -pub const Result = struct { - content: []const u8, - reasoning: []const u8, - calls: ?[]V, - reasoning_tokens: usize, - rejected: bool = false, - open_think: bool = false, // the think channel was still open where the tokens end -}; +pub const Result = @import("native_reply.zig").Result; const Tag = enum { message, think, response, tools, call, argument, json }; const Header = struct { tag: Tag, attrs: *json.Object }; diff --git a/zig/src/server/model_text.zig b/zig/src/server/model_text.zig index cc5a61552b7..4218f900fd7 100644 --- a/zig/src/server/model_text.zig +++ b/zig/src/server/model_text.zig @@ -144,6 +144,8 @@ pub const Rendered = struct { }; pub const Text = struct { + /// The release Inkling 2 reply controls; set only from config.json's model_type. + native_inkling2: bool = false, native_deepseek: bool = false, /// The chat template renders ``defer_loading`` and ``tool_reference`` itself (deferred_tools.zig). deferred_native: bool = false, diff --git a/zig/src/server/native_reply.zig b/zig/src/server/native_reply.zig new file mode 100644 index 00000000000..ebd436251b1 --- /dev/null +++ b/zig/src/server/native_reply.zig @@ -0,0 +1,15 @@ +//! The common result of a model family's token-aware full-reply parser. +const json = @import("json"); + +pub const Result = struct { + content: []const u8, + reasoning: []const u8, + calls: ?[]json.Value, + reasoning_tokens: usize, + rejected: bool = false, + rejected_calls: usize = 0, // calls a parser refused and dropped; only Inkling 2 reports them + kept: ?@import("tool_parse.zig").Parsed = null, // a bare Inkling 2 reply's envelopes kept as content + bare: bool = false, // Inkling 2: no message header before the reply's end or its stop, as a grammar writes + cut_calls: bool = false, // the calls were cut by the token cap: the reply keeps finish_reason length + open_think: bool = false, +}; diff --git a/zig/src/server/openai_calls.zig b/zig/src/server/openai_calls.zig index 33774ac4d69..4588f269fd9 100644 --- a/zig/src/server/openai_calls.zig +++ b/zig/src/server/openai_calls.zig @@ -16,7 +16,7 @@ pub fn attach(r: anytype, reply: *chat.Reply) Allocator.Error!?[]Value { const found = reply.native_calls; const calls = (if (r.turn != null) cortheon.clientCalls(found) else found) orelse return null; reply.content = try r.plan.policy.parsedContent(r.a, reply.content); - reply.finish_reason = "tool_calls"; + if (!reply.native_cut_calls) reply.finish_reason = "tool_calls"; reply.tool_calls_streamed = false; return if (r.plan.policy.single and calls.len > 1) calls[0..1] else calls; } @@ -59,7 +59,7 @@ pub fn streamed(r: anytype, delta: Value) Allocator.Error!void { } /// The reply's `tensorfold.kept_tool_calls`: both counts, and the unoffered names the model wrote. -fn keptBlock(a: Allocator, parsed: tool_parse.Parsed) Allocator.Error!Value { +pub fn keptBlock(a: Allocator, parsed: tool_parse.Parsed) Allocator.Error!Value { const o = try json.newObject(a); try o.put(a, "unoffered", try json.intValue(a, parsed.kept_unoffered)); try o.put(a, "malformed", try json.intValue(a, parsed.kept_malformed)); diff --git a/zig/src/server/profile_line.zig b/zig/src/server/profile_line.zig index 917293dfd27..0681242bf45 100644 --- a/zig/src/server/profile_line.zig +++ b/zig/src/server/profile_line.zig @@ -168,6 +168,7 @@ test "profile line: new rows and every grouped member report real names and scop .{ .name = "TF_SLIDE_ROUTED", .raw = "1", .family = "nemotron_h", .backend = "cuda", .class = "experimental" }, .{ .name = "TF_QWEN27_METAL_KV_PAGES", .raw = "1", .family = "qwen3_5", .backend = "metal", .class = "arithmetic" }, .{ .name = "TF_QWEN35_METAL_KV_PAGES", .raw = "1", .family = "qwen3_5", .backend = "metal", .class = "arithmetic" }, + .{ .name = "TF_Q27_MTP_GPU_PICK", .raw = "1", .family = "qwen3_5", .backend = "metal", .class = "arithmetic" }, }) |c| { const env: ExtraEnv = .{ .name = c.name, .value = c.raw }; const line = try format(a, .stable, c.family, c.backend, env); diff --git a/zig/src/server/root.zig b/zig/src/server/root.zig index 6f3d82ded98..af5d27b505a 100644 --- a/zig/src/server/root.zig +++ b/zig/src/server/root.zig @@ -25,6 +25,12 @@ test { _ = @import("kimi_reply_test.zig"); _ = @import("kimi_stream_test.zig"); _ = @import("kimi_http_test.zig"); + _ = @import("inkling2_chat_test.zig"); + _ = @import("inkling2_reply_test.zig"); + _ = @import("inkling2_boundary_test.zig"); + _ = @import("inkling2_ks51_test.zig"); + _ = @import("inkling2_required_test.zig"); + _ = @import("inkling2_ks53_test.zig"); _ = @import("profile_line.zig"); _ = @import("auth_scope_test.zig"); _ = @import("family_sampling.zig"); @@ -46,6 +52,7 @@ test { _ = @import("gpu_turn.zig"); _ = @import("request_deadline_test.zig"); _ = @import("request_deadline_http_test.zig"); + _ = @import("gpu_turn.zig"); _ = @import("idle_unload.zig"); _ = @import("idle_unload_test.zig"); _ = @import("wait_reason_test.zig"); @@ -114,6 +121,7 @@ test { if (comptime @import("builtin").os.tag != .windows) _ = @import("speech_stream_test.zig"); // over a Unix socket pair if (comptime @import("builtin").os.tag != .windows) _ = @import("images_generations_test.zig"); // over a Unix socket pair if (comptime @import("builtin").os.tag != .windows) _ = @import("speech_lane_release_test.zig"); + if (comptime @import("builtin").os.tag != .windows) _ = @import("speech_voices_test.zig"); if (comptime @import("builtin").os.tag != .windows) _ = @import("speech_speakers_test.zig"); if (comptime @import("builtin").os.tag != .windows) _ = @import("speech_sampling_test.zig"); if (comptime @import("builtin").os.tag != .windows) _ = @import("speech_voices_test.zig"); @@ -342,6 +350,7 @@ test { _ = @import("quoted_markers_test.zig"); _ = @import("request_cost_test.zig"); _ = @import("prompt_tool_turn_test.zig"); + _ = @import("tool_conformance_test.zig"); } test { diff --git a/zig/src/server/routes.zig b/zig/src/server/routes.zig index 948d1e0a3d7..0d677a46b54 100644 --- a/zig/src/server/routes.zig +++ b/zig/src/server/routes.zig @@ -94,7 +94,7 @@ fn get(srv: *Server, conn: *Conn, a: Allocator) void { const route = auth.routePath(conn.path); if (std.mem.eql(u8, route, "/v1/voices")) { if (srv.info.speech == null) return unknown(conn, a); - const value = srv.voices.listing(a) catch return; + const value = @import("speech_voices.zig").listing(srv, a) catch return; return sendValue(conn, a, 200, value); } if (std.mem.eql(u8, route, "/memory") or std.mem.eql(u8, route, "/v1/memory")) diff --git a/zig/src/server/server.zig b/zig/src/server/server.zig index 43e83c3c9f9..3400373bc13 100644 --- a/zig/src/server/server.zig +++ b/zig/src/server/server.zig @@ -105,6 +105,8 @@ pub const Server = struct { /// Structured output's compiler, opened by the first structured request (Python's grammar.compiler). grammars: ?*api.grammar.Compiler = null, grammar_problem: ?[]const u8 = null, + tool_grammars: ?*api.grammar.Compiler = null, // Inkling 2's required calls: the eos ids and its end of message + tool_grammar_problem: ?[]const u8 = null, grammar_mutex: std.Io.Mutex = .init, /// The facts the learner was taught and whether the weights recall them. slide: slide_graph.Graph, @@ -136,19 +138,7 @@ pub const Server = struct { return error.InvalidVisionMarkers; }; srv.video_decoder = @import("input_types.zig").decodes(srv.info.vision); // no decoder: video parts are a 400, never a 500 - srv.voices = .{ .gpa = gpa, .io = io, .dir = config.voice.dir }; - if (srv.info.speech == null and (config.voice.dir != null or config.voice.inline_voices or config.voice.manage)) return error.VoicesRequireSpeech; - const engine_voices = if (srv.info.speech) |sp| sp.voices else &.{}; - if (engine_voices.len > 0) { - // the engine's own catalog answers by index: inline objects and admin edits the store never reaches it - if (config.voice.inline_voices or config.voice.manage) return error.EngineOwnedVoices; - // the server's own copy: an idle unload frees the engine's names while /v1/voices still lists them - const voices = try srv.arena.allocator().alloc(@import("drama_voice.zig").Voice, engine_voices.len); - for (engine_voices, voices) |name, *voice| voice.* = .{ .name = try srv.arena.allocator().dupe(u8, name), .references = &.{} }; - srv.engine_voices = voices; - try srv.voices.swap(voices); - } else if (config.voice.dir) |dir| try srv.voices.load(dir); - _ = try srv.voices.select(srv.arena.allocator(), config.voice.default, "default"); + try @import("speech_voices.zig").start(srv, gpa, io, config); if (!srv.info.capability(.text_generation)) { if (config.cortheon) return error.CortheonRequiresTextGeneration; return srv; @@ -206,6 +196,7 @@ pub const Server = struct { srv.load.detach(false); // an engine still attached is still open: it stops writing before anything here frees srv.stopKeepalive(); if (srv.grammars) |g| g.close(); + if (srv.tool_grammars) |g| if (g != srv.grammars) g.close(); srv.metrics.deinit(); srv.voices.deinit(); srv.arena.deinit(); @@ -313,8 +304,19 @@ pub const Server = struct { /// A request's grammar, compiled once here and handed to the engine (a 400 with xgrammar's reason if it cannot be). pub fn compiledStructure(srv: *Server, cx: *Cx, kind: grammar.Kind, text: []const u8, field: []const u8, thinking: bool) errors.Refused!api.Structure { + return srv.compiledWith(cx, srv.grammarCompiler(), srv.grammar_problem, kind, text, field, thinking); + } + + /// A required tool call's grammar: on Inkling 2 its own compiler, which may also end at a call's end of message. + pub fn compiledToolStructure(srv: *Server, cx: *Cx, text: []const u8, field: []const u8, thinking: bool) errors.Refused!api.Structure { + if (!@import("chat_inkling2.zig").enabled(srv)) return srv.compiledStructure(cx, .structural_tag, text, field, thinking); + const c = srv.compilerFor(&srv.tool_grammars, &srv.tool_grammar_problem, true); + return srv.compiledWith(cx, c, srv.tool_grammar_problem, .structural_tag, text, field, thinking); + } + + fn compiledWith(srv: *Server, cx: *Cx, compiler: ?*api.grammar.Compiler, problem: ?[]const u8, kind: grammar.Kind, text: []const u8, field: []const u8, thinking: bool) errors.Refused!api.Structure { try grammar.checkNesting(cx, kind, text, field); - const c = srv.grammarCompiler() orelse return cx.fail(.request, "{s}: {s}", .{ if (kind == .structural_tag) field else "structured output", srv.grammar_problem.? }); + const c = compiler orelse return cx.fail(.request, "{s}: {s}", .{ if (kind == .structural_tag) field else "structured output", problem.? }); var err: [512]u8 = undefined; const compiled = c.compile(srv.io, @fromBackingInt(@intCast(@backingInt(kind))), text, &err) catch return cx.fail(.request, "{s}: the grammar cannot be enforced: {s}", .{ field, std.mem.sliceTo(&err, 0) }); @@ -334,12 +336,17 @@ pub const Server = struct { /// The model's grammar compiler: tokenizer.json, the text model's vocab_size, the eos ids. fn grammarCompiler(srv: *Server) ?*api.grammar.Compiler { + return srv.compilerFor(&srv.grammars, &srv.grammar_problem, false); + } + + /// A compiler opened once into `slot`; `calls`: its ends also take Inkling 2's end of message (chat_inkling2). + fn compilerFor(srv: *Server, slot: *?*api.grammar.Compiler, problem: *?[]const u8, calls: bool) ?*api.grammar.Compiler { srv.grammar_mutex.lockUncancelable(srv.io); defer srv.grammar_mutex.unlock(srv.io); - if (srv.grammars) |g| return g; - if (srv.grammar_problem != null) return null; + if (slot.*) |g| return g; + if (problem.* != null) return null; const a = srv.arena.allocator(); - srv.grammar_problem = blk: { + problem.* = blk: { const dir = std.Io.Dir.cwd(); const tok = dir.readFileAlloc(srv.io, std.fs.path.join(a, &.{ srv.config.model_dir, "tokenizer.json" }) catch break :blk "out of memory", a, .limited(256 << 20)) catch break :blk "the checkpoint has no tokenizer.json"; const cfg_text = dir.readFileAlloc(srv.io, std.fs.path.join(a, &.{ srv.config.model_dir, "config.json" }) catch break :blk "out of memory", a, .limited(16 << 20)) catch break :blk "the checkpoint has no config.json"; @@ -350,15 +357,16 @@ pub const Server = struct { const vocab = grammar.vocabSize(cfg) orelse break :blk "structured output needs the checkpoint's config.json vocab_size"; var err: [512]u8 = undefined; const c = a.create(api.grammar.Compiler) catch break :blk "out of memory"; - c.* = api.grammar.Compiler.open(srv.io, a, tok, vocab, srv.eos, &err) catch |e| break :blk switch (e) { + const ends = if (calls) @import("chat_inkling2.zig").grammarEnds(srv, a, srv.eos) catch break :blk "out of memory" else srv.eos; + c.* = api.grammar.Compiler.open(srv.io, a, tok, vocab, ends, &err) catch |e| break :blk switch (e) { error.NoGrammarLibrary => @import("sys").optional_libraries.spec(.grammar).message, else => a.dupe(u8, std.mem.sliceTo(&err, 0)) catch "out of memory", }; - srv.grammars = c; + slot.* = c; log.line("structured output: xgrammar over {d} tokens", .{vocab}); break :blk null; }; - return srv.grammars; + return slot.*; } /// Counts one finished request for /metrics. diff --git a/zig/src/server/server_config.zig b/zig/src/server/server_config.zig index 851b2e926ce..baf61d2d538 100644 --- a/zig/src/server/server_config.zig +++ b/zig/src/server/server_config.zig @@ -48,6 +48,8 @@ pub const Config = struct { silence_mid: bool = false, silence_guard: bool = false, cfg: ?@import("drama_cfg.zig").Options = null, + /// The flock a voice holds while it synthesizes, so batch work on this GPU gives way (gpu_turn.zig). + speech_lock: []const u8 = @import("gpu_turn.zig").path, prompt_seed: bool = false, // --prompt-seed: historical prompt-keyed sampling when a request omits its seed cache_salt_per_key: bool = false, // --cache-salt-per-key: the matched API key salts each request's prompt cache /// TENSORFOLD_REQUEST_LOG: where chat and completion bodies are appended; null: nowhere. diff --git a/zig/src/server/speech.zig b/zig/src/server/speech.zig index 030f54c82e8..6062b9cd678 100644 --- a/zig/src/server/speech.zig +++ b/zig/src/server/speech.zig @@ -215,10 +215,14 @@ fn promptOf(srv: *Server, cx: *Cx, sp: api.SpeechInfo, input: []const u8) errors return counted.ids; } -/// Acquired errors, final replies and completed stream observations release the lane before client writes. -pub fn releaseLane(srv: *Server, released: *bool) void { - if (released.*) return; - released.* = true; +/// A synthesis' output lane and its GPU turn (renders on this GPU pause while it is held). +pub const Lane = struct { released: bool = false, turn: ?std.Io.File = null }; + +/// Errors, final replies and completed streams release the lane before client writes: a slow client blocks no one. +pub fn releaseLane(srv: *Server, lane: *Lane) void { + if (lane.released) return; + lane.released = true; + gpu_turn.done(srv.io, lane.turn); _ = srv.speech_inflight.fetchSub(1, .acq_rel); } @@ -233,31 +237,29 @@ fn synthesize(srv: *Server, c: *Conn, cx: *Cx, id: []const u8, sp: api.SpeechInf } if (srv.speech_inflight.cmpxchgWeak(held, held + 1, .acq_rel, .acquire)) |now| held = now else break; } - // a render or benchmark on this GPU pauses at its next short command buffer until this voice has finished - const turn = gpu_turn.speak(srv.io, gpu_turn.path); - defer gpu_turn.done(srv.io, turn); - var lane_released = false; - defer releaseLane(srv, &lane_released); + // a render or benchmark on this GPU pauses at its next short command buffer until this voice's engine work ends + var lane: Lane = .{ .turn = gpu_turn.speak(srv.io, srv.config.speech_lock) }; + defer releaseLane(srv, &lane); const pcm_len = std.math.mul(usize, sp.max_frames, sp.frame_length) catch 0; if (pcm_len == 0 or sp.sample_rate == 0 or sp.sample_rate > std.math.maxInt(u32) / 2) { - releaseLane(srv, &lane_released); + releaseLane(srv, &lane); return fail(c, cx, id, metadata.*, .server, "the engine advertises no usable speech output"); } const pcm = srv.gpa.alloc(f32, pcm_len) catch { - releaseLane(srv, &lane_released); + releaseLane(srv, &lane); return fail(c, cx, id, metadata.*, .server, "out of memory"); }; defer srv.gpa.free(pcm); var result: api.SpeechResult = .{}; const frames: []const [11]i32 = if (sp.voices.len > 0) &.{} else plan.frames orelse drama_prompt.rows(cx.a, plan.prompt) catch |e| { - releaseLane(srv, &lane_released); + releaseLane(srv, &lane); return switch (e) { error.OutOfMemory => fail(c, cx, id, metadata.*, .server, "out of memory"), error.InvalidToken => fail(c, cx, id, metadata.*, .request, "invalid speech token"), }; }; const guided = drama_cfg.guide(cx.a, srv.text, srv.config.cfg, metadata.cfg_gamma orelse 1, plan.input, plan.refs.len > 0) catch { - releaseLane(srv, &lane_released); + releaseLane(srv, &lane); return fail(c, cx, id, metadata.*, .server, "the tokenizer cannot encode the unconditional prompt"); }; const request: api.SpeechRequest = .{ @@ -283,7 +285,7 @@ fn synthesize(srv: *Server, c: *Conn, cx: *Cx, id: []const u8, sp: api.SpeechInf defer if (srv.keepalive) |k| k.end(); const started = clock.nowNs(srv.io); srv.engine.submitSpeech(engine_id, &request, .{ .ctx = &box, .event = Mailbox.onEvent }) catch |e| { - releaseLane(srv, &lane_released); + releaseLane(srv, &lane); return switch (e) { error.Busy => blk: { srv.load.refused(.engine_busy); @@ -299,17 +301,17 @@ fn synthesize(srv: *Server, c: *Conn, cx: *Cx, id: []const u8, sp: api.SpeechInf }; }; // The engine holds request, prompt, pcm and result until finished; no path below returns before that. - if (plan.stream) return streaming.streamReply(srv, c, cx, id, sp, plan, received, &box, engine_id, pcm, &result, metadata.*, &lane_released); + if (plan.stream) return streaming.streamReply(srv, c, cx, id, sp, plan, received, &box, engine_id, pcm, &result, metadata.*, &lane); if (streaming.settle(srv, c, &box, engine_id, null) == null) return streaming.left(srv, c, id, plan.prompt.len, received); if (streaming.why(&box, result.samples, pcm.len)) |message| { - releaseLane(srv, &lane_released); + releaseLane(srv, &lane); return fail(c, cx, id, metadata.*, .server, message); } const take: Take = .{ .pcm = pcm[0..result.samples], .reason = box.reason, .silence_mid = result.silence_mid }; var spare: []f32 = &.{}; defer srv.gpa.free(spare); const sent = redraw(srv, c, cx, id, sp, plan, received, request, started, take, &spare, metadata) orelse return; - releaseLane(srv, &lane_released); + releaseLane(srv, &lane); reply(srv, c, cx, id, sp, plan, received, sent, metadata.*); } diff --git a/zig/src/server/speech_lane_release_test.zig b/zig/src/server/speech_lane_release_test.zig index b0a0e8a7085..0eb14e086b4 100644 --- a/zig/src/server/speech_lane_release_test.zig +++ b/zig/src/server/speech_lane_release_test.zig @@ -51,7 +51,7 @@ test "speech submit errors release the lane before the first write" { try std.testing.expect(!failed); } -test "the speech lane is free while the reply body is still being written" { +test "the speech lane and GPU turn are free while the reply body is still being written" { var script: Script = .{ .steps = &.{3072 * frame}, .max_frames = 3072 }; var s: Served = undefined; try s.start(&script, "HTTP/1.1", whole_body, 30000); @@ -70,6 +70,7 @@ test "the speech lane is free while the reply body is still being written" { } // At least 11 MB remains unwritten, so the route's deferred release cannot have run. try std.testing.expectEqual(@as(u32, 0), s.srv.speech_inflight.load(.acquire)); + try std.testing.expect(try s.turnFree()); const rest = try s.readRest(); s.join(&script); joined = true; @@ -123,7 +124,7 @@ test "a completed non-empty stream releases the lane before its first write" { try std.testing.expectEqual(@as(u32, 0), probe.first_inflight); } -test "the speech lane is free while a completed stream's body is still being written" { +test "the speech lane and GPU turn are free while a completed stream's body is still being written" { var script: Script = .{ .steps = &.{3072 * frame}, .max_frames = 3072, .inline_ = true }; var s: Served = undefined; try s.start(&script, "HTTP/1.1", harness.stream_body, 30000); @@ -142,6 +143,7 @@ test "the speech lane is free while a completed stream's body is still being wri } // At least 11 MB remains unwritten, so the route's deferred release cannot have run. try std.testing.expectEqual(@as(u32, 0), s.srv.speech_inflight.load(.acquire)); + try std.testing.expect(try s.turnFree()); const rest = try s.readRest(); s.join(&script); joined = true; @@ -155,7 +157,7 @@ test "the speech lane is free while a completed stream's body is still being wri try std.testing.expectEqual(@as(u32, 0), s.srv.speech_inflight.load(.acquire)); } -test "a stream the engine is still writing holds its lane at its first audio write" { +test "a stream the engine is still writing holds its lane and GPU turn at its first audio write" { var script: Script = .{ .steps = &.{ frame, 3 * frame }, .hold = 1 }; var s: Served = undefined; try s.start(&script, "HTTP/1.1", harness.stream_body, 2000); @@ -172,6 +174,7 @@ test "a stream the engine is still writing holds its lane at its first audio wri try std.testing.expect(try s.more(2000)); } try std.testing.expectEqual(@as(u32, 1), s.srv.speech_inflight.load(.acquire)); + try std.testing.expect(!try s.turnFree()); script.release.store(true, .release); const rest = try s.readRest(); s.join(&script); diff --git a/zig/src/server/speech_sampling.zig b/zig/src/server/speech_sampling.zig index 8e3a4dc80fa..1977f348161 100644 --- a/zig/src/server/speech_sampling.zig +++ b/zig/src/server/speech_sampling.zig @@ -23,8 +23,14 @@ pub fn isField(key: []const u8) bool { return false; } +/// Drama 3's defaults and top-k ceiling. pub fn parse(cx: *errors.Cx, body: Value) errors.Refused!Options { - var out: Options = .{}; + return parseFrom(cx, body, .{}, 64); +} + +/// The request's sampling fields over `base`, with top_k from 1 through `max_top_k`. +pub fn parseFrom(cx: *errors.Cx, body: Value, base: Options, comptime max_top_k: u32) errors.Refused!Options { + var out = base; if (body.field("temperature")) |value| out.temperature = try number(cx, value, std.math.floatMax(f32), "temperature must be a finite nonnegative f32 number"); if (body.field("top_p")) |value| { @@ -32,10 +38,10 @@ pub fn parse(cx: *errors.Cx, body: Value) errors.Refused!Options { if (out.top_p == 0) return cx.refuse("top_p must be greater than 0"); } if (body.field("top_k")) |value| { - const message = "top_k must be an integer from 1 through 64"; + const message = std.fmt.comptimePrint("top_k must be an integer from 1 through {d}", .{max_top_k}); if (value != .int) return cx.refuse(message); const n = std.fmt.parseInt(u32, value.int, 10) catch return cx.refuse(message); - if (n == 0 or n > 64) return cx.refuse(message); + if (n == 0 or n > max_top_k) return cx.refuse(message); out.top_k = n; } if (body.field("seed")) |value| { diff --git a/zig/src/server/speech_sampling_test.zig b/zig/src/server/speech_sampling_test.zig index 1af8b63d0b0..f97cf2b49aa 100644 --- a/zig/src/server/speech_sampling_test.zig +++ b/zig/src/server/speech_sampling_test.zig @@ -151,3 +151,21 @@ test "speech sampling: a silenced stream retains controls and does not redraw" { try std.testing.expectEqual(@as(usize, 1), script.takes); try expectDraw(&script, 0, .{ .temperature = 0.5, .top_p = 0.9, .top_k = 30 }, 2); } + +test "speech sampling: parseFrom keeps a caller's defaults and refuses top_k past its ceiling" { + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + const a = arena.allocator(); + const sampling = @import("speech_sampling.zig"); + const base: sampling.Options = .{ .temperature = 0.5, .top_p = 0.7, .top_k = 200 }; + var cx: @import("errors.zig").Cx = .{ .a = a }; + const omitted = (try @import("json").parse(a, "{\"top_p\":0.25}")).ok; + try std.testing.expectEqualDeep(sampling.Options{ .temperature = 0.5, .top_p = 0.25, .top_k = 200 }, try sampling.parseFrom(&cx, omitted, base, 4096)); + const wide = (try @import("json").parse(a, "{\"top_k\":4096}")).ok; + try std.testing.expectEqual(@as(u32, 4096), (try sampling.parseFrom(&cx, wide, base, 4096)).top_k); + const past = (try @import("json").parse(a, "{\"top_k\":4097}")).ok; + try std.testing.expectError(error.Refused, sampling.parseFrom(&cx, past, base, 4096)); + try std.testing.expectEqualStrings("top_k must be an integer from 1 through 4096", cx.message); + try std.testing.expectError(error.Refused, sampling.parse(&cx, (try @import("json").parse(a, "{\"top_k\":65}")).ok)); + try std.testing.expectEqualStrings("top_k must be an integer from 1 through 64", cx.message); +} diff --git a/zig/src/server/speech_stream.zig b/zig/src/server/speech_stream.zig index 3d13dcbed20..6aa81ae7c46 100644 --- a/zig/src/server/speech_stream.zig +++ b/zig/src/server/speech_stream.zig @@ -32,10 +32,10 @@ pub fn why(box: *const Mailbox, samples: usize, capacity: usize) ?[]const u8 { } /// An error reply when synthesis ends before any audio; else the chunks, and the terminator only after a complete one. -pub fn streamReply(srv: *Server, c: *Conn, cx: *Cx, id: []const u8, sp: api.SpeechInfo, plan: Plan, received: i96, box: *Mailbox, engine_id: api.Id, pcm: []f32, result: *const api.SpeechResult, metadata: Metadata, lane_released: *bool) void { - const sent = streamAudio(srv, c, sp, box, engine_id, pcm, metadata, lane_released) orelse return left(srv, c, id, plan.prompt.len, received); +pub fn streamReply(srv: *Server, c: *Conn, cx: *Cx, id: []const u8, sp: api.SpeechInfo, plan: Plan, received: i96, box: *Mailbox, engine_id: api.Id, pcm: []f32, result: *const api.SpeechResult, metadata: Metadata, lane: *speech.Lane) void { + const sent = streamAudio(srv, c, sp, box, engine_id, pcm, metadata, lane) orelse return left(srv, c, id, plan.prompt.len, received); // streamAudio releases on observed completion before further head/audio writes; keep this exactly-once safety net. - speech.releaseLane(srv, lane_released); + speech.releaseLane(srv, lane); const mismatch: ?[]const u8 = if (result.samples != sent.samples) "the finished synthesis does not match the audio it published" else null; const problem = why(box, result.samples, pcm.len) orelse mismatch; if (sent.samples == 0) { @@ -72,12 +72,12 @@ pub fn streamReply(srv: *Server, c: *Conn, cx: *Cx, id: []const u8, sp: api.Spee const Sent = struct { samples: usize = 0, first_ready: i96 = 0, first_written: i96 = 0 }; /// Sends everything published since the last send as one chunk, converted in place; null: the client left. -fn streamAudio(srv: *Server, c: *Conn, sp: api.SpeechInfo, box: *Mailbox, engine_id: api.Id, pcm: []f32, metadata: Metadata, lane_released: *bool) ?Sent { +fn streamAudio(srv: *Server, c: *Conn, sp: api.SpeechInfo, box: *Mailbox, engine_id: api.Id, pcm: []f32, metadata: Metadata, lane: *speech.Lane) ?Sent { var sent: Sent = .{}; var size: [20]u8 = undefined; while (true) { const seen = settle(srv, c, box, engine_id, sent.samples) orelse return null; - if (seen.finished) speech.releaseLane(srv, lane_released); + if (seen.finished) speech.releaseLane(srv, lane); const now = seen.published; if (now == sent.samples) return sent; // finished, and everything published is sent const first = sent.samples == 0; diff --git a/zig/src/server/speech_stream_test.zig b/zig/src/server/speech_stream_test.zig index fd3cf7579e7..94b7b561114 100644 --- a/zig/src/server/speech_stream_test.zig +++ b/zig/src/server/speech_stream_test.zig @@ -176,6 +176,9 @@ pub const Served = struct { eof: bool = false, client_open: bool = true, probe: ?*LaneProbe = null, + /// Each request's own speech lock, so live speech on this machine never meets the test's. + tmp: std.testing.TmpDir, + lock: []u8, pub fn start(s: *Served, script: *Script, version: []const u8, body: []const u8, write_ms: i32) !void { return s.open(script, .{ .served_name = "m", .model_ids = &.{"m"}, .silence_mid = script.mid_enabled }, "", version, body, write_ms); @@ -189,8 +192,13 @@ pub const Served = struct { pub fn openProbed(s: *Served, script: *Script, config: server.Config, headers: []const u8, version: []const u8, body: []const u8, write_ms: i32, probe: ?*LaneProbe) !void { var pair: [2]std.c.fd_t = undefined; if (std.c.socketpair(std.posix.AF.UNIX, std.posix.SOCK.STREAM, 0, &pair) != 0) return error.SocketPair; - s.* = .{ .srv = undefined, .client = pair[0], .route_fd = pair[1], .route = undefined, .write_ms = write_ms, .probe = probe }; - s.srv = try server.Server.init(gpa, std.testing.io, script.engine(), s.text.text(), config, null); + s.* = .{ .srv = undefined, .client = pair[0], .route_fd = pair[1], .route = undefined, .write_ms = write_ms, .probe = probe, .tmp = std.testing.tmpDir(.{}), .lock = undefined }; + const dir = try s.tmp.dir.realPathFileAlloc(std.testing.io, ".", gpa); + defer gpa.free(dir); + s.lock = try std.fs.path.join(gpa, &.{ dir, "speech.lock" }); + var isolated = config; + isolated.speech_lock = s.lock; + s.srv = try server.Server.init(gpa, std.testing.io, script.engine(), s.text.text(), isolated, null); if (probe) |p| p.srv = s.srv; if (script.voices.len > 0) try s.srv.voices.swap(script.voices); if (script.output_full) s.srv.speech_inflight.store(s.srv.info.lanes, .release); @@ -225,6 +233,17 @@ pub const Served = struct { _ = std.c.close(s.route_fd); s.got.deinit(gpa); s.srv.deinit(); + gpa.free(s.lock); + s.tmp.cleanup(); + } + + /// Whether no voice holds the GPU turn now; never waits. + pub fn turnFree(s: *Served) !bool { + const file = try std.Io.Dir.cwd().openFile(std.testing.io, s.lock, .{}); + defer file.close(std.testing.io); + const got = try file.tryLock(std.testing.io, .exclusive); + if (got) file.unlock(std.testing.io); + return got; } /// Reads more of the reply; false at EOF or after `wait_ms` of silence. diff --git a/zig/src/server/speech_voices.zig b/zig/src/server/speech_voices.zig new file mode 100644 index 00000000000..eb7dc1ffdc3 --- /dev/null +++ b/zig/src/server/speech_voices.zig @@ -0,0 +1,27 @@ +//! A speech server's voices: Drama 3's catalog store, loaded at startup and listed on `/v1/voices`. +const std = @import("std"); +const server = @import("server.zig"); + +/// Fills `srv.voices` from the engine's own catalog or `--voices` and selects the default voice; voice flags without a +/// speech model are refused, and so are inline and managed voices on an engine-owned catalog. +pub fn start(srv: *server.Server, gpa: std.mem.Allocator, io: std.Io, config: server.Config) !void { + const voice = config.voice; + srv.voices = .{ .gpa = gpa, .io = io, .dir = voice.dir }; + if (srv.info.speech == null and (voice.dir != null or voice.inline_voices or voice.manage)) return error.VoicesRequireSpeech; + const engine_voices = if (srv.info.speech) |sp| sp.voices else &.{}; + if (engine_voices.len > 0) { + // the engine's own catalog answers by index: inline objects and admin edits the store never reaches it + if (voice.inline_voices or voice.manage) return error.EngineOwnedVoices; + // the server's own copy: an idle unload frees the engine's names while /v1/voices still lists them + const voices = try srv.arena.allocator().alloc(@import("drama_voice.zig").Voice, engine_voices.len); + for (engine_voices, voices) |name, *v| v.* = .{ .name = try srv.arena.allocator().dupe(u8, name), .references = &.{} }; + srv.engine_voices = voices; + try srv.voices.swap(voices); + } else if (voice.dir) |dir| try srv.voices.load(dir); + _ = try srv.voices.select(srv.arena.allocator(), voice.default, "default"); +} + +/// The `/v1/voices` reply. +pub fn listing(srv: *server.Server, a: std.mem.Allocator) !@import("json").Value { + return srv.voices.listing(a); +} diff --git a/zig/src/server/speech_voices_test.zig b/zig/src/server/speech_voices_test.zig index f2aaead5e4c..84e384b16ed 100644 --- a/zig/src/server/speech_voices_test.zig +++ b/zig/src/server/speech_voices_test.zig @@ -2,13 +2,13 @@ const std = @import("std"); const server = @import("root.zig"); const harness = @import("speech_stream_test.zig"); -const gpa = std.testing.allocator; +const Script = harness.Script; +const Served = harness.Served; +const Bytes = harness.Bytes; const frame = harness.frame; const pcm = harness.pcm; const expectHeader = harness.expectHeader; -const Bytes = harness.Bytes; -const Script = harness.Script; -const Served = harness.Served; +const gpa = std.testing.allocator; test "voices: HTTP listing and reference rows use the family CLI builder" { var arena = std.heap.ArenaAllocator.init(gpa); diff --git a/zig/src/server/stop_hook.zig b/zig/src/server/stop_hook.zig index e1548029e45..31aa66870ee 100644 --- a/zig/src/server/stop_hook.zig +++ b/zig/src/server/stop_hook.zig @@ -11,7 +11,11 @@ pub const StopHook = struct { const h: *StopHook = @ptrCast(@alignCast(ctx)); var arena: std.heap.ArenaAllocator = .init(h.srv.gpa); defer arena.deinit(); - const tail = emitted[emitted.len -| h.stops.tail()..]; + // Inkling 2's byte tokens can spell one character in several: its window counts the stop's bytes + const inkling = @import("chat_inkling2.zig"); + const window = if (inkling.enabled(h.srv)) inkling.stopWindow(h.stops.strings) else h.stops.tail(); + const tail = emitted[emitted.len -| window..]; + if (inkling.enabled(h.srv)) return inkling.stopIn(arena.allocator(), h.srv.text, emitted, window, h.stops.strings) catch false; const text = h.srv.text.decode(arena.allocator(), tail) catch return false; for (h.stops.strings) |stop| if (std.mem.indexOf(u8, text, stop) != null) return true; return false; diff --git a/zig/src/server/systemone.zig b/zig/src/server/systemone.zig index d2355a15d3c..b6a47cebf0f 100644 --- a/zig/src/server/systemone.zig +++ b/zig/src/server/systemone.zig @@ -62,6 +62,9 @@ pub fn post(srv: *Server, conn: *Conn, a: Allocator) void { routes.sendValue(conn, a, cx.status(), openai.wrapError(a, err) catch return); } +/// A server without pictures: its checkpoint has no tower, or it started without --vision (core's gate). +pub const no_pictures = "this server reads no pictures: start it with --vision on a checkpoint with a vision tower"; + /// The answers to a System One body, or its refusal. pub fn reply(srv: *Server, cx: *Cx, body: Value) errors.Refused!Value { const state = body.get("state") orelse return cx.refuse("a request needs a state (null when the question is the whole state)"); @@ -70,7 +73,7 @@ pub fn reply(srv: *Server, cx: *Cx, body: Value) errors.Refused!Value { if (raw_questions != .object or raw_questions.object.count() == 0) return cx.refuse("questions is a non-empty object of id: question"); const questions = try cx.a.alloc(Question, raw_questions.object.count()); for (raw_questions.object.keys(), raw_questions.object.values(), questions) |id, raw, *q| q.* = try parse(cx, id, raw); - if (seen.urls.len > 0 and !srv.engine.info().pictures) return cx.refuse("this checkpoint has no vision tower"); + if (seen.urls.len > 0 and !srv.engine.info().pictures) return cx.refuse(no_pictures); var f: Format = .{ .srv = srv, .cx = cx, .one = .init(cx.a) }; // with pictures the head and the state are encoded apart, the pictures' tokens between them (the processor's ids) diff --git a/zig/src/server/systemone_test.zig b/zig/src/server/systemone_test.zig index 47e3aabfeb8..80db61b202c 100644 --- a/zig/src/server/systemone_test.zig +++ b/zig/src/server/systemone_test.zig @@ -204,7 +204,7 @@ test "System One refuses in the goldens' words, before any scoring" { const pictured = "{\"state\": \"x\", \"images\": [\"data:image/png;base64,AA\"], \"questions\": {\"q\": {\"type\": \"noul\", \"instructions\": \"i\"}}}"; var cx: errors.Cx = .{ .a = a }; try std.testing.expectError(error.Refused, systemone.reply(srv, &cx, (try json.parse(a, pictured)).ok)); - try std.testing.expectEqualStrings("this checkpoint has no vision tower", cx.message); + try std.testing.expectEqualStrings(systemone.no_pictures, cx.message); head.window = 8; try std.testing.expectError(error.Refused, systemone.reply(srv, &cx, (try json.parse(a, answered[0].body)).ok)); try std.testing.expectEqualStrings("a decision sequence exceeds the 8-token context", cx.message); diff --git a/zig/src/server/tool_conformance_test.zig b/zig/src/server/tool_conformance_test.zig new file mode 100644 index 00000000000..314c92bd959 --- /dev/null +++ b/zig/src/server/tool_conformance_test.zig @@ -0,0 +1,227 @@ +//! Chat template families: each renders its tools section, a call it writes parses back, a bad one stays text. +const std = @import("std"); +const api = @import("engine_api"); +const json = @import("json"); +const f = @import("control_tokens_fixture.zig"); +const errors = @import("errors.zig"); +const HfText = @import("hf_text.zig").HfText; +const messages_mod = @import("messages.zig"); +const Server = @import("server.zig").Server; +const tool_lfm2 = @import("tool_lfm2.zig"); +const tool_minimax = @import("tool_minimax.zig"); +const tool_parse = @import("tool_parse.zig"); + +const testing = std.testing; +const Allocator = std.mem.Allocator; +const Value = json.Value; + +const Script = struct { + fn engine(s: *@This()) api.Engine { + return .{ .ctx = s, .vtable = &.{ .info = info, .submit = submit, .cancel = cancel, .status = status, .memory = memory } }; + } + fn info(_: *anyopaque) api.Info { + return .{ .context_window = 32768 }; + } + fn submit(_: *anyopaque, _: api.Id, _: *const api.Request, _: api.Sink) api.SubmitError!void {} + fn cancel(_: *anyopaque, _: api.Id) void {} + fn status(_: *anyopaque, out: *api.Status, _: []u32) void { + out.* = .{}; + } + fn memory(_: *anyopaque, _: bool) ?api.Memory { + return null; + } +}; + +const tools_json = + \\[{"type":"function","function":{"name":"read_file","description":"Read a file","parameters":{"type":"object","properties":{"path":{"type":"string"},"content":{"type":"string"}},"required":["path"]}}}] +; + +/// `body` parsed as the request's messages, rendered through the family's template, tools offered. +fn render(a: Allocator, template_src: []const u8, body: []const u8, tools: Value) ![]const u8 { + var fixture = try f.Fixture.init(a, 0); + defer fixture.deinit(); + try fixture.tmp.dir.writeFile(std.testing.io, .{ .sub_path = "chat_template.jinja", .data = template_src }); + var problem: []const u8 = ""; + const hf = try HfText.load(a, std.testing.io, fixture.path, null, a, &problem); + defer hf.deinit(); + var script: Script = .{}; + const srv = try Server.init(a, std.testing.io, script.engine(), hf.text(), .{ .served_name = "m", .model_ids = &.{"m"}, .enable_thinking = false, .use_drafts = false }, null); + defer srv.deinit(); + var cx: errors.Cx = .{ .a = a }; + const raw = (try json.parseText(a, body)).ok; + const normalized = try messages_mod.normalizeWith(&cx, raw, srv.late_system, srv.needs_user_after_tool, srv.media()); + const with_args = try messages_mod.toolArguments(&cx, normalized); + const r = try srv.text.render(a, with_args, .{ .tools = tools, .add_generation_prompt = true }, &problem); + return r.text; +} + +const Rewrite = enum { none, lfm2, minimax }; + +/// `output` as the model wrote it: any family rewrite, then the finished-reply parser. +fn callsOf(a: Allocator, output: []const u8, tools: []const Value, rewrite: Rewrite) !tool_parse.Parsed { + const text = switch (rewrite) { + .none => output, + .lfm2 => try tool_lfm2.dsml(a, output, tools, true), + .minimax => try tool_minimax.dsml(a, output, tools), + }; + return tool_parse.parse(a, text, tools, null); +} + +/// `v`'s function object, or null. +fn fnOf(v: Value) ?*const json.Object { + const o = if (v == .object) v.object else return null; + const fn_v = o.get("function") orelse return null; + return if (fn_v == .object) fn_v.object else null; +} + +/// The parsed calls' names and arguments in order, as a canonical line each: `name=JSON`. +fn digest(a: Allocator, parsed: tool_parse.Parsed) ![]const u8 { + var out: std.ArrayList(u8) = .empty; + const calls = parsed.calls orelse return out.items; + for (calls) |call| { + const fobj = fnOf(call) orelse continue; + try out.appendSlice(a, fobj.get("name").?.string); + try out.append(a, '='); + if (fobj.get("arguments")) |args| { + const s = if (args == .string) args.string else try json.stringify(a, args, .{ .ascii = false }); + try out.appendSlice(a, s); + } + try out.append(a, '\n'); + } + return out.items; +} + +const args_esc = "{\"path\":\"notes.txt\",\"content\":\"l\\u00edne\\n\\u65e5\\u672c\\u8a9e \\\"q\\\" {\\\"a\\\":1}\"}"; + +/// One family: its template, the pieces its tools section and its rendered call must carry, its model-output samples. +const Family = struct { + name: []const u8, + template: ?[]const u8 = null, + tools_parts: []const []const u8 = &.{}, + call_part: ?[]const u8 = null, + result_part: ?[]const u8 = null, + output: []const u8 = "", + rewrite: Rewrite = .none, + two: []const u8 = "", + malformed: []const u8 = "", +}; + +const families = [_]Family{ + .{ // GLM-5.3: name.... + .name = "glm", + .template = @embedFile("fixtures/thinking/glm53.jinja"), + .tools_parts = &.{ "# Tools", "", "read_file", "path" }, + .call_part = "read_filepath", + .result_part = "file body", + .output = "Checking.\nread_filepathnotes.txt", + .two = "read_filepatharead_filepathb", + .malformed = "read_filepathnotes.txt", + }, + .{ // Qwen3.8: v + .name = "qwen", + .template = @embedFile("fixtures/thinking/qwen38.jinja"), + .tools_parts = &.{ "read_file", "path" }, + .call_part = "\n", + .result_part = "file body", + .output = "\n\n\nnotes.txt\n\n\n", + .two = "\n\n\na\n\n\n\n\n\n\nb\n\n\n", + .malformed = "\n\n\nnotes.txt", + }, + .{ // Dory shares the Qwen3-Coder XML call form. + .name = "dory", + .template = @embedFile("fixtures/dory/chat_template.jinja"), + .tools_parts = &.{ "read_file", "path" }, + .call_part = "\n", + .result_part = "file body", + .output = "\n\n\nnotes.txt\n\n\n", + .two = "\n\n\na\n\n\n\n\n\n\nb\n\n\n", + .malformed = "\n\n\nnotes.txt", + }, + .{ // LFM2: <|tool_call_start|>[name(k=v)]<|tool_call_end|>, rewritten as DSML before parsing. + .name = "lfm2", + .template = @embedFile("fixtures/thinking/lfm2.jinja"), + .tools_parts = &.{ "List of tools: [", "read_file" }, + .call_part = "<|tool_call_start|>[read_file(", + .result_part = "file body", + .output = "<|tool_call_start|>[read_file(path=\"notes.txt\")]<|tool_call_end|>", + .rewrite = .lfm2, + .two = "<|tool_call_start|>[read_file(path=\"a\"), read_file(path=\"b\")]<|tool_call_end|>", + .malformed = "<|tool_call_start|>[read_file(path=", + }, + .{ // ChatML's control tokens: tools and calls as JSON in the template; models answer {json}. + .name = "chatml", + .template = @embedFile("fixtures/control_tokens/chatml.jinja"), + .tools_parts = &.{"read_file"}, + .call_part = "call_1", + .result_part = "file body", + .output = "\n{\"name\": \"read_file\", \"arguments\": {\"path\": \"notes.txt\"}}\n", + .two = "\n{\"name\": \"read_file\", \"arguments\": {\"path\": \"a\"}}\n\n\n{\"name\": \"read_file\", \"arguments\": {\"path\": \"b\"}}\n", + .malformed = "\n{\"name\": \"read_file\", \"arguments\": {", + }, + .{ // DeepSeek's control tokens; its models answer in DSML. + .name = "deepseek", + .template = @embedFile("fixtures/control_tokens/deepseek.jinja"), + .tools_parts = &.{"read_file"}, + .call_part = "call_1", + .result_part = "file body", + .output = "<๏ฝœDSML๏ฝœtool_calls><๏ฝœDSML๏ฝœinvoke name=\"read_file\"><๏ฝœDSML๏ฝœparameter name=\"path\" string=\"true\">notes.txt", + .two = "<๏ฝœDSML๏ฝœtool_calls><๏ฝœDSML๏ฝœinvoke name=\"read_file\"><๏ฝœDSML๏ฝœparameter name=\"path\" string=\"true\">a<๏ฝœDSML๏ฝœinvoke name=\"read_file\"><๏ฝœDSML๏ฝœparameter name=\"path\" string=\"true\">b", + .malformed = "<๏ฝœDSML๏ฝœtool_calls><๏ฝœDSML๏ฝœinvoke name=\"read_file\"><๏ฝœDSML๏ฝœparameter name=\"path\" string=\"true\">notes.txt", + }, + .{ // GLM's control tokens; same tag calls as the thinking template. + .name = "glm-control", + .template = @embedFile("fixtures/control_tokens/glm.jinja"), + .tools_parts = &.{"read_file"}, + .call_part = "call_1", + .result_part = "file body", + .output = "read_filepathnotes.txt", + .two = "read_filepatharead_filepathb", + .malformed = "read_filepathnotes.txt", + }, + .{ // MiniMax-M3's prefixed XML, rewritten as DSML before parsing; its template ships with the model. + .name = "minimax", + .rewrite = .minimax, + .output = "]<]minimax[>[]<]minimax[>[]<]minimax[>[notes.txt]<]minimax[>[]<]minimax[>[]<]minimax[>[", + .two = "]<]minimax[>[]<]minimax[>[]<]minimax[>[a]<]minimax[>[]<]minimax[>[]<]minimax[>[]<]minimax[>[b]<]minimax[>[]<]minimax[>[]<]minimax[>[", + .malformed = "]<]minimax[>[]<]minimax[>[]<]minimax[>[notes.txt", + }, + .{ // Gemma's Pythonic calls inside a tool_call envelope; the template ships with the model. + .name = "gemma", + .output = "call:read_file{path:\"notes.txt\"}", + .two = "call:read_file{path:\"a\"}call:read_file{path:\"b\"}", + .malformed = "call:read_file{path:", + }, +}; + +test "tool conformance: every chat template family renders tools, round-trips calls and never invents one" { + var arena = std.heap.ArenaAllocator.init(testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const tools = (try json.parseText(a, tools_json)).ok.array; + const arg_line = "read_file={\"path\":\"notes.txt\"}\n"; + for (families) |fam| { + if (fam.template) |src| { + // (a) one tool definition plus a user turn renders the tools section as the template defines it + const defs = try render(a, src, "[{\"role\":\"user\",\"content\":\"Read notes.\"}]", .{ .array = tools }); + for (fam.tools_parts) |part| { + if (std.mem.indexOf(u8, defs, part) == null) std.debug.print("{s} tools section missing {s}\n", .{ fam.name, part }); + try testing.expect(std.mem.indexOf(u8, defs, part) != null); + } + // (b) an assistant tool call plus its tool result renders the family's markup + const hist = "[{\"role\":\"user\",\"content\":\"Read notes.\"},{\"role\":\"assistant\",\"tool_calls\":[{\"id\":\"call_1\",\"type\":\"function\",\"function\":{\"name\":\"read_file\",\"arguments\":" ++ args_esc ++ "}}]},{\"role\":\"tool\",\"tool_call_id\":\"call_1\",\"content\":\"file body\"}]"; + const past = try render(a, src, hist, .{ .array = tools }); + try testing.expect(std.mem.indexOf(u8, past, fam.call_part.?) != null); + try testing.expect(std.mem.indexOf(u8, past, fam.result_part.?) != null); + } + // (b) the family's call markup parses back with the same name and arguments + const one = try callsOf(a, fam.output, tools, fam.rewrite); + try testing.expectEqualStrings(arg_line, try digest(a, one)); + // (c) two calls in one turn keep their order + const pair = try callsOf(a, fam.two, tools, fam.rewrite); + try testing.expectEqualStrings("read_file={\"path\":\"a\"}\nread_file={\"path\":\"b\"}\n", try digest(a, pair)); + // (d) a malformed or truncated call is error or plain text, never a different call + const bad = try callsOf(a, fam.malformed, tools, fam.rewrite); + try testing.expectEqualStrings("", try digest(a, bad)); + try testing.expect(std.mem.indexOf(u8, try digest(a, bad), "read_file") == null); + } +} diff --git a/zig/src/server/tool_grammar.zig b/zig/src/server/tool_grammar.zig index 7234df27795..767cd3e872f 100644 --- a/zig/src/server/tool_grammar.zig +++ b/zig/src/server/tool_grammar.zig @@ -51,7 +51,7 @@ pub fn structure(srv: *Server, cx: *Cx, tools: []const Value, parallel: bool, th try fits(cx, once); const text = if (!parallel) once else if (markup) try lfmBuild(cx, tools, true) else try build(cx.a, s, tools, true); const reason = try std.fmt.allocPrint(cx.a, "tool_choice \"required\" or a named function on backend '{s}'", .{srv.backendName()}); - var st = try srv.compiledStructure(cx, .structural_tag, text, reason, thinking); + var st = try srv.compiledToolStructure(cx, text, reason, thinking); // The structure names the request's field; the sentence above words the 400. st.field = "tool_choice"; return st; diff --git a/zig/src/tensorfold.zig b/zig/src/tensorfold.zig index 10eb161e6a1..df7b77ae8a2 100644 --- a/zig/src/tensorfold.zig +++ b/zig/src/tensorfold.zig @@ -3,6 +3,7 @@ const std = @import("std"); pub const startup_receipt = @import("profile").startup_receipt; pub const benchmark_group = @import("core/benchmark_group.zig"); +pub const chunked_write = @import("core/chunked_write.zig"); pub const safetensors = @import("core/safetensors.zig"); /// torch.save archives and WAV files: Drama 3's codec and clips, through its `core` shim. pub const torch_pth = @import("core/torch_pth.zig"); @@ -10,6 +11,7 @@ pub const wav = @import("core/wav.zig"); pub const gguf = @import("core/gguf.zig"); pub const Checkpoint = checkpoint_host.Checkpoint; pub const checkpoint_host = @import("core/checkpoint.zig"); +pub const checkpoint_file_cache = @import("core/checkpoint_file_cache.zig"); pub const digest_cache = @import("core/digest_cache.zig"); pub const checkpoint_metal = checkpoint; pub const qwen27 = @import("families/qwen27/qwen27.zig"); @@ -32,6 +34,9 @@ pub const picture = @import("core/picture/picture.zig"); pub const audio = @import("core/audio.zig"); pub const ids_json = @import("core/ids_json.zig"); pub const lanes = @import("lanes"); +pub const inkling2_native = @import("inkling2_native.zig"); +pub const inkling2_metal_host = @import("families/inkling2/metal/metal.zig"); +pub const inkling2_dspark_host = @import("families/inkling2/metal/dspark_kernels.zig"); pub const segments = @import("core/segments.zig"); pub const prompt_tail = @import("core/prompt_tail.zig"); pub const row_projection = @import("core/row_projection.zig"); @@ -74,6 +79,7 @@ pub const flashnext_learned = @import("families/flashnext/learned.zig"); pub const flashnext_think_check = @import("families/flashnext/think_check.zig"); pub const glm = @import("families/glm/glm.zig"); pub const qwen35 = @import("families/qwen3_5/qwen3_5.zig"); +pub const qwen35_stages = @import("families/qwen3_5/stages.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"); diff --git a/zig/tests/contract/metal_affine.zig b/zig/tests/contract/metal_affine.zig index 7449c48708c..0ee5ffd9f44 100644 --- a/zig/tests/contract/metal_affine.zig +++ b/zig/tests/contract/metal_affine.zig @@ -79,7 +79,7 @@ const router_rows = [_]c.Shape{ .{ .rows = 1024, .n = 320, .k = 3072 }, .{ .rows fn laneBase(v: Variant) ?[]const u8 { if (v.kind != .lane_reg) return null; if (v.inline_sums) return "the reg kernel with its sums pass"; - return if (v.bits == 4) "the cooperative lane kernel" else null; + return if (v.bits == 4) "the cooperative lane kernel" else if (v.bits == 5 or v.bits == 6) "the lane kernel" else null; } pub fn spec(v: Variant, name: []const u8) c.Spec { @@ -151,7 +151,7 @@ pub const Proj = struct { } }, .lane => {}, - .lane_reg => if (v.bits == 4) { + .lane_reg => if (v.bits == 4 or v.bits == 5 or v.bits == 6) { p.order = try lane.RegOrder.init(device); }, } @@ -188,7 +188,7 @@ pub const Proj = struct { /// The kernel's layout, or with `base` the layout of the kernel it replaces. fn layout(p: *const Proj, shape: c.Shape, base: bool) lane.Layout { const reg = p.v.kind == .lane_reg and (!base or p.v.inline_sums); - const coop = base and !reg; + const coop = base and !reg and p.v.bits == 4; return .{ .n = shape.n, .k = shape.k, .format = .{ .bits = p.v.bits, .group = p.v.group }, .sk = p.v.sk, .output = if (p.v.f32_out) .f32 else .bf16, .precompute_sums = p.v.kind == .lane_reg or p.v.coop, .cooperative = coop or (p.v.coop and !reg), .reg = reg, .inline_sums = reg and p.v.inline_sums and !base }; } @@ -249,7 +249,9 @@ pub const Proj = struct { p.s = try p.rig.input(std.mem.sliceAsBytes(psb)); if (p.v.kind == .lane_reg) { p.tiled = try p.rig.input(std.mem.sliceAsBytes(pw)); - if (p.order) |o| try o.run(&.{.{ .w = .{ .buf = p.w.buf, .off = p.w.off }, .n = shape.n, .k = shape.k }}) else { + if (p.order) |o| { + if (!p.v.control) try o.run(&.{.{ .w = .{ .buf = p.w.buf, .off = p.w.off }, .n = shape.n, .k = shape.k, .bits = p.v.bits }}); + } else { const reg_words = p.rig.bytes(p.w, pw.len * 4); try lane.regOrder8(@alignCast(std.mem.bytesAsSlice(u32, reg_words)), shape.n, shape.k); } diff --git a/zig/tests/contract/metal_affine_gather.zig b/zig/tests/contract/metal_affine_gather.zig index 91273746ce8..c8588f53f5a 100644 --- a/zig/tests/contract/metal_affine_gather.zig +++ b/zig/tests/contract/metal_affine_gather.zig @@ -76,8 +76,8 @@ const offset_inf = c.Known{ .gate = .nonfinite, .finding = "an infinite input gi pub fn spec(v: Variant) c.Spec { const known = if (v.bits == 4 and v.mutation == .none and !v.glm_m3_fast) offset_inf else null; - // Ornith-1.5-122B: gate and up 1024 x 3072, down 3072 x 1024; 32 rows an expert (32-row tiles), past 64 (64-row) - const served = &[_]c.Shape{ .{ .rows = 256, .n = 1024, .k = 3072 }, .{ .rows = 520, .n = 3072, .k = 1024 } }; + // Ornith-1.5-122B's experts (1024 x 3072, 3072 x 1024), then Qwen3.6-35B-A3B's (512 x 2048, 2048 x 512) + const served = &[_]c.Shape{ .{ .rows = 256, .n = 1024, .k = 3072 }, .{ .rows = 520, .n = 3072, .k = 1024 }, .{ .rows = 256, .n = 512, .k = 2048 }, .{ .rows = 520, .n = 2048, .k = 512 } }; return .{ .name = name(v), .accum = .f32, .depth = groupDepth64, .out = .bf16, .known = known, .replaces = if (v.identity) "the frozen affine_mm before exact-nonfinite groups" else null, .tiles = .{ .{ .size = 32 }, .{ .size = 64, .step = 64, .min = 64 }, .{ .size = 128, .step = 64, .min = 64 } }, .served = served }; } diff --git a/zig/tests/contract/metal_flashnext_grouped.zig b/zig/tests/contract/metal_flashnext_grouped.zig index 91144bbf2f9..b7a979964d6 100644 --- a/zig/tests/contract/metal_flashnext_grouped.zig +++ b/zig/tests/contract/metal_flashnext_grouped.zig @@ -8,7 +8,7 @@ const g = contract.gates; const Fixture = tf.flashnext_grouped_fixture.Fixture; const fx = tf.flashnext_grouped_fixture; -/// MB=2's served widths: every row count from 5 to 16, odd and even. +/// Grouped shared and MB=2 widths: every row count from 5 to 16, odd and even. const widths = blk: { var out: [12]c.Shape = undefined; for (&out, 5..) |*s, rows| s.* = .{ .rows = rows, .n = fx.inner, .k = fx.d }; @@ -50,7 +50,7 @@ pub const Probe = struct { .out = .raw, .replaces = if (p.mb2) "the grouped gate/up decoding an expert's weights once a pair (MB=1), on the same weights, logits and rows" else "the recorded 4/32 expert gate/up and down kernels a row at a time, on the same weights, logits and rows", .nan = .{ .stated = "every output bit of the recorded kernels, non-finite scales included, is retained" }, - .served = if (p.mb2) &widths else &.{ .{ .rows = 5, .n = fx.inner, .k = fx.d }, .{ .rows = 8, .n = fx.inner, .k = fx.d }, .{ .rows = 13, .n = fx.inner, .k = fx.d }, .{ .rows = 16, .n = fx.inner, .k = fx.d } }, + .served = &widths, .sums = .{ .why = "grouping changes which threadgroup runs a (row, expert) pair, not a sum; the recorded kernels' sums are not requalified here" }, }, .vt = &vt }; } diff --git a/zig/tests/contract/metal_gemma4_mixed.zig b/zig/tests/contract/metal_gemma4_mixed.zig index 1e5f2f75509..aaf4537c668 100644 --- a/zig/tests/contract/metal_gemma4_mixed.zig +++ b/zig/tests/contract/metal_gemma4_mixed.zig @@ -92,6 +92,7 @@ pub const Probe = struct { defer p.a.free(sb); try lane.pack(l, words, f.scales, f.biases, pw, sb); const w = try p.rig.input(std.mem.sliceAsBytes(pw)); + if (l.reg) try lane.regOrder(p.rig.device, &.{.{ .w = ref(w), .n = 32, .k = 256, .bits = width }}); const meta = try p.rig.input(std.mem.sliceAsBytes(sb)); p.runs[j] = x; p.storage[j] = .{ w, meta }; @@ -140,7 +141,7 @@ pub fn limits(a: std.mem.Allocator, device: mtl.Device, only: ?[]const u8) !usiz defer a.free(source); const label = try std.fmt.allocPrint(a, "{s} q{d}", .{ name, width }); defer a.free(label); - problems += try @import("metal_limits.zig").onThisGpu(a, device, .{ .decl = .{ .name = label, .threads = @intCast(32 * l.sk), .tg_memory = @intCast(l.threadgroupBytes()), .offline = false }, .function = "tf_lane", .here = source, .pre_m5 = "" }, false); + problems += try @import("metal_limits.zig").onThisGpu(a, device, .{ .decl = .{ .name = label, .threads = @intCast(32 * l.sk), .tg_memory = @intCast(l.threadgroupBytes()), .offline = false }, .function = if (l.reg) "tf_lane_reg" else "tf_lane", .here = source, .pre_m5 = "" }, false); } return problems; } diff --git a/zig/tests/contract/metal_inkling2_attention.zig b/zig/tests/contract/metal_inkling2_attention.zig new file mode 100644 index 00000000000..9b359464c85 --- /dev/null +++ b/zig/tests/contract/metal_inkling2_attention.zig @@ -0,0 +1,565 @@ +//! Inkling 2 Mini Metal attention gates 1-4 with an independent float64 formula and both prompt layouts. +const std = @import("std"); +const mtl = @import("metal"); +const contract = @import("contract"); +const rig_ = @import("rig.zig"); +const controls = @import("metal_inkling2_attention_controls.zig"); +const sources = @import("inkling2_metal"); +const plan = @import("tensorfold").inkling2_metal_host.attention.planning; +const c = contract.spec; +const g = contract.gates; +const Which = controls.Which; +const Mutation = controls.Mutation; +const D = 128; +const H = 24; +const KV = 8; +const R = 16; +const EXTENT = 1024; +const scale = 0.08838834764831845; + +const prep_shapes = [_]c.Shape{ .{ .rows = 7, .n = H * D, .k = 1030 }, .{ .rows = 3, .n = H * D, .k = 9000 } }; +const prep_global_shapes = [_]c.Shape{ prep_shapes[0], prep_shapes[1], .{ .rows = 4, .n = H * D, .k = 1048576 } }; +const rel_shapes = [_]c.Shape{ .{ .rows = 4, .n = H * EXTENT, .k = R }, .{ .rows = 1, .n = H * EXTENT, .k = R } }; +const sliding_shapes = [_]c.Shape{ .{ .rows = 7, .n = H * D, .k = 1030 }, .{ .rows = 3, .n = H * D, .k = 2049 } }; +const global_shapes = [_]c.Shape{ .{ .rows = 4, .n = H * D, .k = 1100 }, .{ .rows = 2, .n = H * D, .k = 1030 } }; +const prompt_shapes = [_]c.Shape{ .{ .rows = 8, .n = H * D, .k = 1100 }, .{ .rows = 64, .n = H * D, .k = 80 } }; +fn depth(s: c.Shape) usize { + return D + 4 * s.k + 64; +} +fn flat(_: c.Shape) usize { + return R; +} +fn spec(w: Which) c.Spec { + const x: c.Spec = .{ .name = "", .accum = .f32, .depth = depth, .ops = 64, .mids = 8, .out = .bf16, .served = &global_shapes, .sums = .{ .f16 = 0, .bf16 = 0, .exact = true, .why = "P and outputs have required bf16 roundings" } }; + var s = x; + switch (w) { + .prep_sliding, .prep_global => { + s.name = if (w == .prep_global) "metal inkling2 attention prep global tf_ink2_prep" else "metal inkling2 attention prep sliding tf_ink2_prep"; + s.served = if (w == .prep_global) &prep_global_shapes else &prep_shapes; + s.ops = 32; + s.mids = 2; + }, + .rel_table => { + s.name = "metal inkling2 attention relative table tf_ink2_rel_table"; + s.served = &rel_shapes; + s.depth = flat; + s.ops = 4; + s.mids = 0; + }, + .decode_sliding => { + s.name = "metal inkling2 attention scalar sliding tf_ink2_attn_scalar"; + s.served = &sliding_shapes; + }, + .decode_global => { + s.name = "metal inkling2 attention scalar global tf_ink2_attn_scalar"; + s.served = &global_shapes; + }, + .prompt_m5 => { + s.name = "metal inkling2 prompt m5 tf_ink2_attn_prompt"; + s.served = &prompt_shapes; + }, + .prompt_pre_m5 => { + s.name = "metal inkling2 prompt pre-m5 tf_ink2_attn_prompt"; + s.served = &prompt_shapes; + }, + } + return s; +} +fn bf(x: u16) f64 { + return c.fromBf16(x); +} +fn rn(x: f64) f64 { + return c.fromBf16(c.toBf16(@floatCast(x))); +} +fn bits(x: f64) u16 { + return c.toBf16(@floatCast(x)); +} +fn minNum(x: f64, y: f64) f64 { + return if (std.math.isNan(x)) y else if (std.math.isNan(y)) x else @min(x, y); +} +fn maxNan(x: f64, y: f64) f64 { + return if (std.math.isNan(x) or std.math.isNan(y)) std.math.nan(f64) else @max(x, y); +} +fn sigmoid(x: f64) f64 { + return 1 / (1 + @exp(-x)); +} +/// Prompt P rounds to BF16 at each tile maximum; later rescaling does not round twice. The result anchors weights. +fn promptWeights(score: []const f64, weights: []f64) f64 { + const tile_keys = 64; + const sub_keys = 1024; + var top = -std.math.inf(f64); + var upper = -std.math.inf(f64); + var first: usize = 0; + while (first < score.len) { + const end = @min(first + tile_keys, score.len); + const sub_first = first - first % sub_keys; + var tile_peak = top; + for (score[first..end]) |sc| tile_peak = maxNan(tile_peak, sc); + const mu = if (tile_peak == -std.math.inf(f64)) 0 else tile_peak; + const keep = @exp(top - mu); + for (weights[sub_first..first]) |*w| w.* *= keep; + for (weights[first..end], score[first..end]) |*w, sc| w.* = rn(@exp(sc - mu)); + top = tile_peak; + if (first % sub_keys == sub_keys - tile_keys or end == score.len) { + if (top != -std.math.inf(f64)) { + const merged = maxNan(upper, top); + const old_scale = @exp(upper - merged); + const new_scale = @exp(top - merged); + for (weights[0..sub_first]) |*w| w.* *= old_scale; + for (weights[sub_first..end]) |*w| w.* *= new_scale; + upper = merged; + } + top = -std.math.inf(f64); + } + first = end; + } + return upper; +} +fn tau(pos: usize) f64 { + return 1 + 0.1 * @log(@max(@as(f64, @floatFromInt(pos + 1)) / 8192, 1)); +} +fn periodic(p: usize, col: usize) f64 { + const i = p % 1024; + if (i < 512) return @floatFromInt(129 + (i * 73 + col * 31) % 127); + const j = i - 512; + return -@as(f64, @floatFromInt(129 + ((j + 1) * 73 + col * 31) % 127)) + @as(f64, if (j < 8) 1 else 0); +} +const Sim = struct { acc: c.Accum, order: g.Order }; +fn sum(v: []const f64, sim: ?Sim) f64 { + if (sim) |s| return contract.rows.sumIn(s.acc, s.order, v); + var total: f64 = 0; + for (v) |x| total += x; + return total; +} + +pub const Probe = struct { + a: std.mem.Allocator, + rig: rig_.Rig, + which: Which, + mutation: Mutation, + lib: mtl.Library, + main: mtl.Pipeline, + merge_lib: ?mtl.Library = null, + merge: mtl.Pipeline = undefined, + fused: bool = false, + shape: c.Shape = .{ .rows = 0, .n = 0, .k = 0 }, + fill: g.Fill = .random, + layer: plan.Layer = undefined, + q: []u16 = &.{}, + kc: []u16 = &.{}, + vc: []u16 = &.{}, + tab: []u16 = &.{}, + sink: []u16 = &.{}, + gate: []u16 = &.{}, + rel: []u16 = &.{}, + proj: []u16 = &.{}, + qs: []u16 = &.{}, + rs: []u16 = &.{}, + pos: []usize = &.{}, + refs: [10]rig_.Ref = undefined, + out: [4]rig_.Ref = undefined, + meta: [3]rig_.Ref = undefined, + po: rig_.Ref = undefined, + pml: rig_.Ref = undefined, + + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, w: Which, m: Mutation) !Probe { + const plain = if (controls.isPrompt(w)) (if (w == .prompt_pre_m5) sources.prompt_attention_pre_m5 else sources.prompt_attention) else sources.attention; + const text = try controls.apply(a, plain, m); + defer a.free(text); + var lib = try mtl.Library.fromSource(device, text, mtl.CompileOptions.mlx()); + errdefer lib.deinit(); + var main = try mtl.Pipeline.init(device, lib, controls.function(w), false); + errdefer main.deinit(); + var merge_lib: ?mtl.Library = null; + errdefer if (merge_lib) |loaded| loaded.deinit(); + var merge: mtl.Pipeline = undefined; + const fused = controls.isAttention(w); + if (fused) { + if (controls.isPrompt(w)) merge_lib = try mtl.Library.fromSource(device, sources.attention, mtl.CompileOptions.mlx()); + const merge_library = if (merge_lib) |loaded| loaded else lib; + merge = try mtl.Pipeline.init(device, merge_library, "tf_ink2_merge", false); + } + return .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .which = w, .mutation = m, .lib = lib, .main = main, .merge_lib = merge_lib, .merge = merge, .fused = fused }; + } + fn hostFree(p: *Probe) void { + inline for (.{ "q", "kc", "vc", "tab", "sink", "gate", "rel", "proj", "qs", "rs", "pos" }) |f| { + p.a.free(@field(p, f)); + @field(p, f) = &.{}; + } + } + pub fn deinit(p: *Probe) void { + p.hostFree(); + p.rig.deinit(); + if (p.fused) p.merge.deinit(); + if (p.merge_lib) |loaded| loaded.deinit(); + p.main.deinit(); + p.lib.deinit(); + } + const vt = g.hooks(Probe); + pub fn kernel(p: *Probe) g.Kernel { + var k: g.Kernel = .{ .spec = spec(p.which), .ctx = p, .vt = &vt }; + if (p.mutation != .none) { + k.spec.name = p.mutation.name(); + k.control = p.mutation.gate(); + } + return k; + } + fn sizes(p: *const Probe) [4]usize { + const n = p.rigCache(); + return .{ p.shape.rows * H * D, p.shape.rows * H * R, n, n }; + } + fn rigCache(p: *const Probe) usize { + return KV * p.layer.ring * D; + } + pub fn count(p: *const Probe) usize { + if (p.which == .rel_table) return p.shape.rows * H * EXTENT; + if (controls.isAttention(p.which)) return p.shape.rows * H * D; + const z = p.sizes(); + return z[0] + z[1] + z[2] + z[3]; + } + pub fn prepare(p: *Probe, s: c.Shape, fill: g.Fill, seed: u64) !bool { + if (s.rows == 0 or s.k < s.rows) return false; + if (p.which == .rel_table) { + if (s.n != H * EXTENT or s.k != R) return false; + } else if (s.n != H * D) return false; + p.hostFree(); + p.rig.reset(); + p.shape = s; + p.fill = fill; + const global = p.which == .prep_global or p.which == .decode_global or controls.isPrompt(p.which); + const sliding = p.which == .prep_sliding or p.which == .decode_sliding; + p.layer = .{ .window = if (sliding) 1024 else 0, .ring = 2048, .chunk = if (sliding) 256 else plan.global_chunk, .tau = global }; + const rows = s.rows; + const rh = rows * H; + const cache = KV * p.layer.ring * D; + p.pos = try p.a.alloc(usize, rows); + for (p.pos, 0..) |*v, r| v.* = s.k - rows + r; + if (p.which != .rel_table) { + p.q = try p.a.alloc(u16, rh * D); + p.tab = try p.a.alloc(u16, rh * EXTENT); + @memset(p.q, 0); + @memset(p.tab, 0); + } else { + p.rel = try p.a.alloc(u16, rh * R); + p.proj = try p.a.alloc(u16, R * EXTENT); + @memset(p.rel, 0); + @memset(p.proj, 0); + } + if (!controls.isAttention(p.which) and p.which != .rel_table) p.rel = try p.a.alloc(u16, rh * R); + if (p.which != .rel_table) { + p.kc = try p.a.alloc(u16, if (controls.isAttention(p.which)) cache else rows * KV * D); + p.vc = try p.a.alloc(u16, p.kc.len); + @memset(p.kc, 0); + @memset(p.vc, 0); + } + if (controls.isAttention(p.which)) { + p.sink = try p.a.alloc(u16, rh); + p.gate = try p.a.alloc(u16, rh * D); + @memset(p.sink, 0); + @memset(p.gate, 0); + } + if (p.which == .prep_sliding or p.which == .prep_global) { + p.qs = try p.a.alloc(u16, H * D); + p.rs = try p.a.alloc(u16, H * R); + @memset(p.qs, 0); + @memset(p.rs, 0); + } + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + p.fillValues(rng, global); + if (fill == .nonfinite) p.plant(); + try p.bind(); + return true; + } + fn fillValues(p: *Probe, rng: std.Random, global: bool) void { + const stress = p.fill == .stress; + for (p.q) |*v| v.* = bits(if (stress and controls.isAttention(p.which)) 0 else if (stress) @floatFromInt(@as(i32, @intCast(rng.uintLessThan(u32, 511))) - 255) else rng.floatNorm(f64) * 0.3); + for (p.kc) |*v| v.* = bits(if (stress and controls.isAttention(p.which)) 0 else if (stress) @floatFromInt(@as(i32, @intCast(rng.uintLessThan(u32, 255))) - 127) else rng.floatNorm(f64) * 0.3); + for (p.vc, 0..) |*v, i| v.* = if (stress and controls.isAttention(p.which)) bits(periodic(i / D % p.layer.ring, i % D)) else bits(if (stress) @floatFromInt(@as(i32, @intCast(rng.uintLessThan(u32, 255))) - 127) else rng.floatNorm(f64)); + for (p.tab) |*v| v.* = bits(if (stress) 0 else rng.floatNorm(f64) * 0.25); + for (p.sink) |*v| v.* = bits(if (stress) -std.math.inf(f64) else 2 + 4 * rng.float(f64)); + for (p.gate) |*v| v.* = bits(if (stress) 32 else rng.floatNorm(f64)); + for (p.rel, 0..) |*v, i| v.* = bits(if (stress) @floatFromInt(2 * (i % 31) + 1) else rng.floatNorm(f64)); + for (p.proj, 0..) |*v, i| v.* = bits(if (stress) @floatFromInt(1 + i % 2) else rng.floatNorm(f64) * 0.5); + for (p.qs) |*v| v.* = bits(if (stress) 1 else 0.5 + 2 * rng.float(f64)); + for (p.rs) |*v| v.* = bits(if (stress) 1 else 0.5 + 2 * rng.float(f64)); + if (global and !controls.isAttention(p.which)) { + _ = tau(p.pos[0]); + } + } + fn plant(p: *Probe) void { + const nan = bits(std.math.nan(f64)); + const inf = bits(std.math.inf(f64)); + if (p.which == .rel_table) { + p.rel[3] = nan; + if (p.rel.len > R + 5) p.rel[R + 5] = inf; + if (p.rel.len > 2 * R + 1) { + p.rel[2 * R] = inf; + p.rel[2 * R + 1] = inf | 0x8000; + } + } else if (controls.isAttention(p.which)) { + p.q[D + 5] = nan; + p.sink[2] = inf; + p.gate[3 * D] = inf; + p.gate[3 * D + 1] = inf | 0x8000; + } else { + p.q[D + 3] = nan; + p.kc[5] = inf; + p.vc[D] = inf | 0x8000; + p.rel[2] = nan; + } + } + fn bind(p: *Probe) !void { + const rows = p.shape.rows; + if (p.which == .rel_table) { + p.refs[0] = try p.rig.input(std.mem.sliceAsBytes(p.rel)); + p.refs[1] = try p.rig.input(std.mem.sliceAsBytes(p.proj)); + p.out[0] = try p.rig.output(p.count() * 2); + return; + } + if (controls.isAttention(p.which)) { + const arrays = [_][]u16{ p.q, p.kc, p.vc, p.tab, p.sink, p.gate }; + for (arrays, 0..) |x, i| p.refs[i] = try p.rig.input(std.mem.sliceAsBytes(x)); + } else { + const arrays = [_][]u16{ p.q, p.kc, p.vc, p.rel, p.qs, p.rs }; + for (arrays, 0..) |x, i| p.refs[i] = try p.rig.input(std.mem.sliceAsBytes(x)); + } + const pos32 = try p.a.alloc(i32, rows); + defer p.a.free(pos32); + const seg32 = try p.a.alloc(i32, rows); + defer p.a.free(seg32); + @memset(seg32, 0); + for (pos32, p.pos) |*v, x| v.* = @intCast(x); + const seg = [1]plan.Seg{.{ .row0 = 0, .n = @intCast(rows), .p0 = @intCast(p.shape.k - rows), .off = 0 }}; + p.meta[0] = try p.rig.input(std.mem.sliceAsBytes(pos32)); + p.meta[1] = try p.rig.input(std.mem.sliceAsBytes(seg32)); + p.meta[2] = try p.rig.input(std.mem.sliceAsBytes(&seg)); + if (controls.isAttention(p.which)) { + const stride = plan.slotsFor(p.layer, p.shape.k); + const parts = rows * H * stride; + p.po = try p.rig.scratch(parts * D * 4); + p.pml = try p.rig.scratch(parts * 8); + p.out[0] = try p.rig.output(p.count() * 2); + } else for (p.sizes(), 0..) |n, i| p.out[i] = try p.rig.output(n * 2); + } + pub fn run(p: *Probe) !void { + const pass = p.rig.begin(); + const e = pass.e; + e.setPipeline(p.main); + const rows: u32 = @intCast(p.shape.rows); + const ring = p.layer.ring; + if (p.which == .rel_table) { + e.setBuffer(p.refs[0].buf, p.refs[0].off, 0); + e.setBuffer(p.refs[1].buf, p.refs[1].off, 1); + e.setBuffer(p.out[0].buf, p.out[0].off, 2); + e.dispatchGroups(mtl.Size.of(rows * H, 1, 1), mtl.Size.of(256, 1, 1)); + } else if (!controls.isAttention(p.which)) { + @memset(p.rig.bytes(p.out[2], p.sizes()[2] * 2), 0); + @memset(p.rig.bytes(p.out[3], p.sizes()[3] * 2), 0); + for (p.refs[0..6], 0..) |r, i| e.setBuffer(r.buf, r.off, i); + for (p.meta, 6..) |r, i| e.setBuffer(r.buf, r.off, i); + for (p.out, 9..) |r, i| e.setBuffer(r.buf, r.off, i); + e.setValue(plan.PrepArgs{ .heads = H, .kv_heads = KV, .ring = ring, .global = @intFromBool(p.layer.tau), .qk_clip = 22.627416997969522, .rel_clip = 8, .floor_pos = 8192, .alpha = 0.1, .eps = 1e-6 }, 13); + e.dispatchGroups(mtl.Size.of(rows, H + 2 * KV, 1), mtl.Size.of(32, 1, 1)); + } else { + const stride = plan.slotsFor(p.layer, p.shape.k); + for (p.refs[0..4], 0..) |r, i| e.setBuffer(r.buf, r.off, i); + e.setBuffer(p.meta[2].buf, p.meta[2].off, 4); + e.setBuffer(p.po.buf, p.po.off, 5); + e.setBuffer(p.pml.buf, p.pml.off, 6); + const sc: f32 = 1.0 / @sqrt(@as(f32, D)); + if (controls.isPrompt(p.which)) { + e.setValue(plan.PromptArgs{ .heads = H, .kv_heads = KV, .ring = ring, .chunk = p.layer.chunk, .c0 = 0, .chunks = stride, .scale = sc }, 7); + const blocks = (rows * (H / KV) + plan.prompt_pairs - 1) / plan.prompt_pairs; + e.dispatchGroups(mtl.Size.of(blocks, KV, stride), mtl.Size.of(256, 1, 1)); + } else { + e.setBuffer(p.meta[0].buf, p.meta[0].off, 7); + e.setBuffer(p.meta[1].buf, p.meta[1].off, 8); + e.setValue(plan.AttnArgs{ .heads = H, .kv_heads = KV, .ring = ring, .window = p.layer.window, .chunk = p.layer.chunk, .c0 = 0, .chunks = stride, .scale = sc }, 9); + e.dispatchGroups(mtl.Size.of(rows * H, stride, 1), mtl.Size.of(32, 1, 1)); + } + e.barrier(); + e.setPipeline(p.merge); + e.setBuffer(p.po.buf, p.po.off, 0); + e.setBuffer(p.pml.buf, p.pml.off, 1); + e.setBuffer(p.refs[4].buf, p.refs[4].off, 2); + e.setBuffer(p.refs[5].buf, p.refs[5].off, 3); + e.setBuffer(p.meta[0].buf, p.meta[0].off, 4); + e.setBuffer(p.out[0].buf, p.out[0].off, 5); + e.setValue(plan.MergeArgs{ .heads = H, .window = p.layer.window, .chunk = p.layer.chunk, .c0 = 0, .chunks = stride }, 6); + e.dispatchGroups(mtl.Size.of(rows * H, 1, 1), mtl.Size.of(D, 1, 1)); + } + try p.rig.finish(pass); + } + pub fn reference(p: *Probe, want: []f64, mag: []f64) !void { + if (p.which == .rel_table) return p.tableRef(null, want, mag); + if (controls.isAttention(p.which)) return p.attentionRef(null, want, mag); + return p.prepRef(null, want, mag); + } + pub fn simulate(p: *Probe, acc: c.Accum, order: g.Order, out: []f64) !void { + const mag = try p.a.alloc(f64, out.len); + defer p.a.free(mag); + const sim: Sim = .{ .acc = acc, .order = order }; + if (p.which == .rel_table) return p.tableRef(sim, out, mag); + if (controls.isAttention(p.which)) return p.attentionRef(sim, out, mag); + return p.prepRef(sim, out, mag); + } + fn tableRef(p: *Probe, sim: ?Sim, want: []f64, mag: []f64) !void { + var terms: [R]f64 = undefined; + for (want, mag, 0..) |*w, *m, o| { + const rh = o / EXTENT; + const d = o % EXTENT; + for (&terms, 0..) |*v, j| v.* = bf(p.rel[rh * R + j]) * bf(p.proj[j * EXTENT + d]); + m.* = 0; + for (terms) |x| m.* += @abs(x); + const x = sum(&terms, sim); + w.* = if (sim != null) rn(x) else x; + } + } + fn headClip(x: []const f64, threshold: f64, sim: ?Sim, t: ?f64, want: []f64, mag: []f64) void { + var sq: [D]f64 = undefined; + mZero(mag); + for (sq[0..x.len], x, 0..) |*v, y, i| { + v.* = y * y; + mag[i] = @abs(y); + } + const f = minNum(threshold / (@sqrt(sum(sq[0..x.len], sim)) + 1e-6), 1); + for (want, x, mag) |*w, v, *m| { + w.* = rn(v * f); + if (t) |tv| w.* = rn(w.* * tv); + m.* = @abs(v) + v * v; + } + } + /// prep uses independent K/V and attention uses populated ring caches; q and rel never alias either one. + fn prepRef(p: *Probe, sim: ?Sim, want: []f64, mag: []f64) !void { + @memset(want, 0); + @memset(mag, 0); + const z = p.sizes(); + var x: [D]f64 = undefined; + for (0..p.shape.rows) |r| { + const tv: ?f64 = if (p.layer.tau) tau(p.pos[r]) else null; + for (0..H) |h| { + for (&x, 0..) |*v, d| v.* = bf(p.q[(r * H + h) * D + d]) * bf(p.qs[h * D + d]); + headClip(&x, 22.627416997969522, sim, tv, want[(r * H + h) * D ..][0..D], mag[(r * H + h) * D ..][0..D]); + for (x[0..R], 0..) |*v, d| v.* = bf(p.rel[(r * H + h) * R + d]) * bf(p.rs[h * R + d]); + const at = z[0] + (r * H + h) * R; + headClip(x[0..R], 8, sim, tv, want[at..][0..R], mag[at..][0..R]); + } + for (0..KV) |h| { + const slot = (h * p.layer.ring + p.pos[r] % p.layer.ring) * D; + for (&x, 0..) |*v, d| v.* = bf(p.kc[(r * KV + h) * D + d]); + headClip(&x, 22.627416997969522, sim, null, want[z[0] + z[1] + slot ..][0..D], mag[z[0] + z[1] + slot ..][0..D]); + var sq: [D]f64 = undefined; + for (&x, &sq, 0..) |*v, *ss, d| { + v.* = bf(p.vc[(r * KV + h) * D + d]); + ss.* = v.* * v.*; + } + const inv = 1 / @sqrt(sum(&sq, sim) / D + 1e-6); + for (0..D) |d| { + const at = z[0] + z[1] + z[2] + slot + d; + want[at] = rn(x[d] * inv); + mag[at] = sq[d] + @abs(x[d]); + } + } + } + } + fn mZero(mag: []f64) void { + @memset(mag, 0); + } + fn attentionRef(p: *Probe, sim: ?Sim, want: []f64, mag: []f64) !void { + const most = p.shape.k; + const score = try p.a.alloc(f64, most); + defer p.a.free(score); + const weights = try p.a.alloc(f64, most); + defer p.a.free(weights); + const terms = try p.a.alloc(f64, @max(most, D)); + defer p.a.free(terms); + for (0..p.shape.rows) |r| { + for (0..H) |h| { + const rh = r * H + h; + const pos = p.pos[r]; + const lo = if (p.layer.window > 0) (pos + 1) -| p.layer.window else 0; + const n = pos + 1 - lo; + const kvh = h / (H / KV); + const z = bf(p.sink[rh]); + // Prompt P is BF16 at the keys' maximum; the sink joins in the final merge using the shared maximum. + const prompt = sim == null and controls.isPrompt(p.which); + var peak = if (prompt) -std.math.inf(f64) else z; + for (lo..pos + 1) |kp| { + const j = kp - lo; + const at = (kvh * p.layer.ring + kp % p.layer.ring) * D; + for (0..D) |d| terms[d] = bf(p.q[rh * D + d]) * bf(p.kc[at + d]); + const distance = pos - kp; + const bias = if (distance < EXTENT) bf(p.tab[rh * EXTENT + distance]) else 0; + score[j] = sum(terms[0..D], sim) * scale + bias; + peak = maxNan(peak, score[j]); + } + if (prompt) { + peak = promptWeights(score[0..n], weights[0..n]); + } else for (weights[0..n], score[0..n]) |*w, sc| w.* = @exp(sc - peak); + const merged_peak = if (prompt) maxNan(peak, z) else peak; + const rescale = if (prompt) @exp(peak - merged_peak) else 1; + const den = sum(weights[0..n], sim) * rescale + @exp(z - merged_peak); + for (0..D) |d| { + for (lo..pos + 1) |kp| { + const j = kp - lo; + const at = (kvh * p.layer.ring + kp % p.layer.ring) * D; + terms[j] = weights[j] * bf(p.vc[at + d]); + } + const num = sum(terms[0..n], sim) * rescale; + const y = num / den * sigmoid(bf(p.gate[rh * D + d])); + want[rh * D + d] = if (sim != null) rn(y) else y; + mag[rh * D + d] = (@abs(num) + den + 1) * (1 + @abs(y)); + for (terms[0..n]) |v| mag[rh * D + d] += @abs(v * rescale); + } + } + } + } +}; + +fn supported(device: mtl.Device, w: Which) bool { + return switch (w) { + .prompt_m5 => device.tensorUnits(), + .prompt_pre_m5 => !device.tensorUnits(), + else => true, + }; +} +pub const Suite = struct { + a: std.mem.Allocator, + device: mtl.Device, + queue: mtl.Queue, + kernels: *std.ArrayList(g.Kernel), + probes: std.ArrayList(*Probe) = .empty, + pub fn collect(s: *Suite, only: ?[]const u8) !void { + for (std.enums.values(Which)) |w| { + if (!supported(s.device, w) or (only != null and std.mem.indexOf(u8, spec(w).name, only.?) == null)) continue; + try s.add(w, .none); + } + for (std.enums.values(Mutation)) |m| { + if (m == .none) continue; + const w = m.which(); + if (!supported(s.device, w) or (only != null and std.mem.indexOf(u8, m.name(), only.?) == null)) continue; + try s.add(w, m); + } + } + fn add(s: *Suite, w: Which, m: Mutation) !void { + const p = try s.a.create(Probe); + errdefer s.a.destroy(p); + p.* = Probe.init(s.a, s.device, s.queue, w, m) catch |err| { + var k: g.Kernel = .{ .spec = spec(w), .ctx = undefined, .vt = undefined, .control = m.gate(), .init_error = err }; + if (m != .none) k.spec.name = m.name(); + try s.kernels.append(s.a, k); + s.a.destroy(p); + return; + }; + try s.probes.append(s.a, p); + try s.kernels.append(s.a, p.kernel()); + } + pub fn deinit(s: *Suite) void { + for (s.probes.items) |p| { + p.deinit(); + s.a.destroy(p); + } + s.probes.deinit(s.a); + } +}; diff --git a/zig/tests/contract/metal_inkling2_attention_controls.zig b/zig/tests/contract/metal_inkling2_attention_controls.zig new file mode 100644 index 00000000000..f4b9cc69cb9 --- /dev/null +++ b/zig/tests/contract/metal_inkling2_attention_controls.zig @@ -0,0 +1,157 @@ +//! Count-checked, discriminating source edits for every Inkling 2 attention shader entry point. +const std = @import("std"); +const contract = @import("contract"); + +pub const Which = enum { prep_sliding, prep_global, rel_table, decode_sliding, decode_global, prompt_m5, prompt_pre_m5 }; +pub fn function(w: Which) []const u8 { + return switch (w) { + .prep_sliding, .prep_global => "tf_ink2_prep", + .rel_table => "tf_ink2_rel_table", + .decode_sliding, .decode_global => "tf_ink2_attn_scalar", + .prompt_m5, .prompt_pre_m5 => "tf_ink2_attn_prompt", + }; +} +pub fn isPrompt(w: Which) bool { + return w == .prompt_m5 or w == .prompt_pre_m5; +} +pub fn isAttention(w: Which) bool { + return w == .decode_sliding or w == .decode_global or isPrompt(w); +} + +pub const Mutation = enum { + none, + prep_swap_kv, + prep_tau_off, + rel_late, + decode_late_bias, + merge_no_sink, + prompt_late_bias, + prompt_pre_late_bias, + pub fn name(m: Mutation) []const u8 { + return switch (m) { + .none => "", + .prep_swap_kv => "control: metal inkling2 attention prep sliding with gated K/V inputs exchanged tf_ink2_prep", + .prep_tau_off => "control: metal inkling2 attention global prep without tau tf_ink2_prep", + .rel_late => "control: metal inkling2 attention relative projection one column late tf_ink2_rel_table", + .decode_late_bias => "control: metal inkling2 attention sliding first key score boosted tf_ink2_attn_scalar", + .merge_no_sink => "control: metal inkling2 attention global merge without sink tf_ink2_merge", + .prompt_late_bias => "control: metal inkling2 prompt m5 first key bias boosted tf_ink2_attn_prompt", + .prompt_pre_late_bias => "control: metal inkling2 prompt pre-m5 first key bias boosted tf_ink2_attn_prompt", + }; + } + pub fn gate(m: Mutation) ?contract.gates.Gate { + return if (m == .none) null else .shapes; + } + pub fn which(m: Mutation) Which { + return switch (m) { + .none => unreachable, + .prep_swap_kv => .prep_sliding, + .prep_tau_off => .prep_global, + .rel_late => .rel_table, + .decode_late_bias => .decode_sliding, + .merge_no_sink => .decode_global, + .prompt_late_bias => .prompt_m5, + .prompt_pre_late_bias => .prompt_pre_m5, + }; + } + const Edit = struct { from: []const u8, to: []const u8 }; + fn edit(m: Mutation) Edit { + return switch (m) { + .none => unreachable, + .prep_swap_kv => .{ + .from = "const device bfloat* src = (key ? k_raw : v_raw) + (size_t(row) * a.kv_heads + h) * D;", + .to = "const device bfloat* src = (key ? v_raw : k_raw) + (size_t(row) * a.kv_heads + h) * D;", + }, + .prep_tau_off => .{ + .from = "const float tau = a.global ? 1.0f + a.alpha * precise::log(max(float(pos + 1) / a.floor_pos, 1.0f)) : 1.0f;", + .to = "const float tau = 1.0f;", + }, + .rel_late => .{ + .from = "acc += r[j] * float(proj[j * EXTENT + d]);", + .to = "acc += r[j] * float(proj[j * EXTENT + (d + 1) % EXTENT]);", + }, + .decode_late_bias => .{ + .from = "const float score = (dot_score * a.scale + bias) * LOG2E;", + .to = "const float score = (dot_score * a.scale + bias + (kp == from ? 128.0f : 0.0f)) * LOG2E;", + }, + .merge_no_sink => .{ + .from = "const float sk = float(sink[rh]) * LOG2E, mf = max(mm, sk), a0 = precise::exp2(mm - mf);", + .to = "const float sk = -INFINITY, mf = max(mm, sk), a0 = precise::exp2(mm - mf);", + }, + .prompt_late_bias, .prompt_pre_late_bias => .{ + .from = "const float bias = live && distance < EXTENT ? float(tab[prow * EXTENT + distance]) : 0.0f;", + .to = "const float bias = (live && distance < EXTENT ? float(tab[prow * EXTENT + distance]) : 0.0f) + (live && kp == b_lo ? 128.0f : 0.0f);", + }, + }; + } +}; + +pub fn apply(a: std.mem.Allocator, text: []const u8, m: Mutation) ![]u8 { + if (m == .none) return a.dupe(u8, text); + const e = m.edit(); + if (std.mem.count(u8, text, e.from) != 1) return error.ControlEditMissing; + return std.mem.replaceOwned(u8, a, text, e.from, e.to); +} + +test "Inkling 2 attention controls each hit one live statement and cannot apply twice" { + const a = std.testing.allocator; + const sources = @import("inkling2_metal"); + for (std.enums.values(Mutation)) |m| { + if (m == .none) continue; + const w = m.which(); + const plain = if (isPrompt(w)) (if (w == .prompt_pre_m5) sources.prompt_attention_pre_m5 else sources.prompt_attention) else sources.attention; + const edited = try apply(a, plain, m); + defer a.free(edited); + try std.testing.expect(std.mem.indexOf(u8, edited, m.edit().to) != null); + try std.testing.expectError(error.ControlEditMissing, apply(a, edited, m)); + try std.testing.expectEqual(contract.gates.Gate.shapes, m.gate().?); + } + const unchanged = try apply(a, sources.attention, .none); + defer a.free(unchanged); + try std.testing.expectEqualStrings(sources.attention, unchanged); +} + +fn fp64Clip(src: []const f64, dst: []f64, threshold: f64) void { + var ss: f64 = 0; + for (src) |x| ss += x * x; + const f = @min(threshold / (@sqrt(ss) + 1e-6), 1); + for (dst, src) |*y, x| y.* = x * f; +} + +fn fp64Rms(src: []const f64, dst: []f64) void { + var ss: f64 = 0; + for (src) |x| ss += x * x; + const inv = 1 / @sqrt(ss / @as(f64, @floatFromInt(src.len)) + 1e-6); + for (dst, src) |*y, x| y.* = x * inv; +} + +test "Inkling 2 gated FP64 prep exchanges only K/V" { + const q = [4]f64{ 4, 0, 0, 0 }; + const rel = [4]f64{ 4, 0, 0, 0 }; + const k = [4]f64{ 4, 0, 0, 0 }; + const v = [4]f64{ 0, 3, 0, 0 }; + var q_base: [4]f64 = undefined; + var q_swap: [4]f64 = undefined; + var rel_base: [4]f64 = undefined; + var rel_swap: [4]f64 = undefined; + var k_base: [4]f64 = undefined; + var k_swap: [4]f64 = undefined; + var v_base: [4]f64 = undefined; + var v_swap: [4]f64 = undefined; + fp64Clip(&q, &q_base, 5); + fp64Clip(&q, &q_swap, 5); + fp64Clip(&rel, &rel_base, 5); + fp64Clip(&rel, &rel_swap, 5); + fp64Clip(&k, &k_base, 5); + fp64Clip(&v, &k_swap, 5); + fp64Rms(&v, &v_base); + fp64Rms(&k, &v_swap); + try std.testing.expectEqualSlices(f64, &q_base, &q_swap); + try std.testing.expectEqualSlices(f64, &rel_base, &rel_swap); + try std.testing.expectEqualSlices(f64, &.{ 4, 0, 0, 0 }, &k_base); + try std.testing.expectEqualSlices(f64, &.{ 0, 3, 0, 0 }, &k_swap); + const v_from_v = 3 * (1 / @sqrt(@as(f64, 9) / 4 + 1e-6)); + const v_from_k = 4 * (1 / @sqrt(@as(f64, 16) / 4 + 1e-6)); + try std.testing.expectEqualSlices(f64, &.{ 0, v_from_v, 0, 0 }, &v_base); + try std.testing.expectEqualSlices(f64, &.{ v_from_k, 0, 0, 0 }, &v_swap); +} diff --git a/zig/tests/contract/metal_inkling2_controls_host.zig b/zig/tests/contract/metal_inkling2_controls_host.zig new file mode 100644 index 00000000000..f60081c09ce --- /dev/null +++ b/zig/tests/contract/metal_inkling2_controls_host.zig @@ -0,0 +1,10 @@ +//! Every Inkling 2 Mini source control must apply once without a Metal compiler. + +test { + _ = @import("metal_inkling2_attention_controls.zig"); + _ = @import("metal_inkling2_glue_controls.zig"); + _ = @import("metal_inkling2_experts_controls.zig"); + _ = @import("metal_inkling2_loop_controls.zig"); + _ = @import("metal_inkling2_runtime_controls.zig"); + _ = @import("metal_inkling2_dspark_controls.zig"); +} diff --git a/zig/tests/contract/metal_inkling2_dspark.zig b/zig/tests/contract/metal_inkling2_dspark.zig new file mode 100644 index 00000000000..6274197e9d0 --- /dev/null +++ b/zig/tests/contract/metal_inkling2_dspark.zig @@ -0,0 +1,590 @@ +//! Mini DSpark's ten real Metal launches with guarded buffers, FP64 references and red controls. +const std = @import("std"); +const mtl = @import("metal"); +const controls = @import("metal_inkling2_dspark_controls.zig"); +const contract = @import("contract"); +const c = contract.spec; +const g = contract.gates; +const rig_ = @import("rig.zig"); +const host = @import("tensorfold").inkling2_dspark_host; +const sources = @import("inkling2_metal"); + +const H = host.hidden; +const Q = host.query_width; +const KV = host.kv_width; +const RANK = host.rank; +const RNN = host.rnn_width; +const INTER = host.intermediate; + +fn depth(s: c.Shape) usize { + return s.k + 16; +} +fn bf(v: anytype) f64 { + return host.roundBf16(v); +} +fn rounded(values: []f32) void { + for (values) |*v| v.* = c.fromBf16(c.toBf16(v.*)); +} +fn rms(values: []const f32, start: usize, width: usize) f32 { + var sum: f32 = 0; + for (0..width) |d| { + const x = values[start + d]; + sum += x * x; + } + return 1.0 / @sqrt(sum / @as(f32, @floatFromInt(width)) + 1e-6); +} +fn rope(d: usize, position: usize, x: f32, other: f32) f64 { + const frequency = std.math.pow(f32, 1e6, -@as(f32, @floatFromInt(d % 64)) / 64.0); + const angle = @as(f32, @floatFromInt(position)) * frequency; + const rotated: f32 = if (d < 64) x * @cos(angle) - other * @sin(angle) else other * @sin(angle) + x * @cos(angle); + return bf(rotated); +} + +pub const Probe = struct { + a: std.mem.Allocator, + arena: std.heap.ArenaAllocator, + rig: rig_.Rig, + kind: host.Kind, + pipes: host.Pipelines, + shape: c.Shape = undefined, + served: [6]c.Shape = undefined, + served_len: usize = 0, + f: [8][]f32 = @splat(&.{}), + phi: []u16 = &.{}, + refs: [8]rig_.Ref = undefined, + outs: [3]rig_.Ref = undefined, + score_scratch: rig_.Ref = undefined, + + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, kind: host.Kind) !Probe { + return initSource(a, device, queue, kind, sources.inkling2_dspark); + } + pub fn initSource(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, kind: host.Kind, text: []const u8) !Probe { + var self: Probe = .{ .a = a, .arena = .init(a), .rig = .{ .a = a, .device = device, .queue = queue }, .kind = kind, .pipes = try host.Pipelines.loadSource(device, text) }; + switch (kind) { + .init_rows => self.setServed(&.{.{ .rows = 8, .n = H, .k = 0 }}), + .fuse_taps => self.setServed(&.{ .{ .rows = 5, .n = H, .k = 0 }, .{ .rows = 1, .n = H, .k = 0 }, .{ .rows = 3, .n = H, .k = 0 }, .{ .rows = 7, .n = H, .k = 0 } }), + .block_qkv => self.setServed(&.{ .{ .rows = 8, .n = Q, .k = 17 }, .{ .rows = 8, .n = Q, .k = 67 } }), + .context_kv => self.setServed(&.{ .{ .rows = 5, .n = KV, .k = 17 }, .{ .rows = 1, .n = KV, .k = 31 }, .{ .rows = 3, .n = KV, .k = 47 }, .{ .rows = 8, .n = KV, .k = 67 } }), + .attention => self.setServed(&.{ + .{ .rows = 8, .n = 0, .k = 0 }, + .{ .rows = 8, .n = 1, .k = 0 }, + .{ .rows = 8, .n = 3, .k = 0 }, + .{ .rows = 8, .n = 3, .k = 5 }, + .{ .rows = 8, .n = 1025, .k = 1 }, + .{ .rows = 8, .n = 1025, .k = 7 }, + }), + .residual_norm => self.setServed(&.{ .{ .rows = 8, .n = H, .k = 1 }, .{ .rows = 8, .n = H, .k = 0 } }), + .swiglu => self.setServed(&.{.{ .rows = 8, .n = INTER, .k = 0 }}), + .kappa => self.setServed(&.{ .{ .rows = 5, .n = RNN, .k = 0 }, .{ .rows = 1, .n = RNN, .k = 0 }, .{ .rows = 3, .n = RNN, .k = 0 }, .{ .rows = 7, .n = RNN, .k = 0 } }), + .recurrent => self.setServed(&.{.{ .rows = 8, .n = RNN, .k = 0 }}), + .base => self.setServed(&.{ .{ .rows = 5, .n = 5, .k = 0 }, .{ .rows = 1, .n = 1, .k = 0 }, .{ .rows = 3, .n = 17, .k = 0 }, .{ .rows = 7, .n = 129, .k = 0 } }), + .logits => self.setServed(&.{.{ .rows = 8, .n = host.vocab, .k = 0 }}), + } + return self; + } + fn setServed(self: *Probe, shapes: []const c.Shape) void { + @memcpy(self.served[0..shapes.len], shapes); + self.served_len = shapes.len; + } + pub fn deinit(self: *Probe) void { + self.rig.deinit(); + self.arena.deinit(); + self.pipes.deinit(); + } + + const vt = g.hooks(Probe); + pub fn kernel(self: *Probe) g.Kernel { + return .{ .ctx = self, .vt = &vt, .spec = .{ + .name = self.kind.label(), + .accum = .none, + .depth = depth, + .ops = 0, + .mids = 0, + .out = if (self.kind == .kappa) .f32 else .bf16, + .served = self.served[0..self.served_len], + .sums = .{ .f16 = 0, .bf16 = 0, .why = "explicit serial FP32 reference and required BF16 nodes are checked directly" }, + } }; + } + pub fn count(self: *Probe) usize { + return switch (self.kind) { + .init_rows => 8 * H, + .fuse_taps => (4 * self.shape.rows + 1) * H, + .block_qkv => 8 * (Q + 2 * KV), + .context_kv => 2 * self.shape.rows * KV, + .attention => 8 * Q, + .residual_norm => 2 * 8 * H, + .swiglu => 8 * INTER, + .kappa => self.shape.rows * RNN, + .recurrent => RNN + 2 * RANK, + .base => self.shape.rows * self.shape.n, + .logits => host.vocab, + }; + } + + fn floats(self: *Probe, n: usize, rng: std.Random) ![]f32 { + const values = try self.arena.allocator().alloc(f32, n); + for (values) |*v| v.* = rng.float(f32) * 0.5 - 0.25; + return values; + } + fn input(self: *Probe, values: []const f32, is_bf: bool) !rig_.Ref { + if (!is_bf) return self.rig.input(std.mem.sliceAsBytes(values)); + const bits = try self.arena.allocator().alloc(u16, values.len); + for (bits, values) |*b, v| b.* = c.toBf16(v); + return self.rig.input(std.mem.sliceAsBytes(bits)); + } + fn output(self: *Probe, slot: usize, elements: usize, elem: c.Elem) !void { + self.outs[slot] = try self.rig.output(elements * c.size(elem)); + } + fn first(self: *const Probe) usize { + const from = self.shape.k / 2; + const local = self.shape.k % 2 != 0; + return @max(from, if (local and self.shape.n > 1024) self.shape.n - 1024 else 0); + } + + pub fn prepare(self: *Probe, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + var admitted = false; + for (self.served[0..self.served_len]) |served| if (std.meta.eql(shape, served)) { + admitted = true; + break; + }; + if (!admitted) return false; + self.rig.reset(); + _ = self.arena.reset(.retain_capacity); + self.shape = shape; + self.f = @splat(&.{}); + self.phi = &.{}; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + const nf = fill == .nonfinite; + const rows = shape.rows; + switch (self.kind) { + .init_rows => { + self.f[0] = try self.floats(H, rng); + self.f[1] = try self.floats(H, rng); + if (nf) self.f[0][0] = std.math.nan(f32); + rounded(self.f[0]); + rounded(self.f[1]); + self.refs[0] = try self.input(self.f[0], true); + self.refs[1] = try self.input(self.f[1], true); + try self.output(0, 8 * H, .bf16); + }, + .fuse_taps => { + self.f[0] = try self.floats(rows * 4 * H, rng); + self.f[1] = try self.floats(16, rng); + self.f[2] = try self.floats(4 * H, rng); + if (nf) self.f[0][0] = std.math.nan(f32); + for (self.f[0..3]) |values| rounded(values); + @memcpy(self.f[1][0..4], &[_]f32{ 0, 0.5, -0.25, 2 }); + for (self.f[0][0 .. 4 * H]) |*v| v.* *= 400; + rounded(self.f[0]); + for (0..3) |j| self.refs[j] = try self.input(self.f[j], true); + try self.output(0, 4 * rows * H, .bf16); + try self.output(1, H, .bf16); + }, + .block_qkv => { + const sizes = [_]usize{ 8 * Q, 8 * KV, 8 * KV, 128, 128 }; + for (sizes, 0..) |n, j| { + self.f[j] = try self.floats(n, rng); + rounded(self.f[j]); + self.refs[j] = try self.input(self.f[j], true); + } + if (nf) { + self.f[0][0] = std.math.nan(f32); + self.refs[0] = try self.input(self.f[0], true); + } + try self.output(0, 8 * Q, .bf16); + try self.output(1, 8 * KV, .bf16); + try self.output(2, 8 * KV, .bf16); + }, + .context_kv => { + self.f[0] = try self.floats(rows * KV, rng); + self.f[1] = try self.floats(rows * KV, rng); + self.f[2] = try self.floats(128, rng); + if (nf) self.f[0][0] = std.math.nan(f32); + for (self.f[0..3]) |values| rounded(values); + for (0..3) |j| self.refs[j] = try self.input(self.f[j], true); + try self.output(0, rows * KV, .bf16); + try self.output(1, rows * KV, .bf16); + }, + .attention => { + const ring = @max(shape.n, 1); + const sizes = [_]usize{ 8 * Q, 8 * KV, 8 * KV, ring * KV, ring * KV }; + for (sizes, 0..) |n, j| { + self.f[j] = try self.floats(n, rng); + rounded(self.f[j]); + self.refs[j] = try self.input(self.f[j], true); + } + if (nf) { + self.f[0][0] = std.math.nan(f32); + self.refs[0] = try self.input(self.f[0], true); + } + self.score_scratch = try self.rig.scratch(8 * 24 * (shape.n - self.first() + 8) * 4); + self.refs[5] = self.score_scratch; + try self.output(0, 8 * Q, .bf16); + }, + .residual_norm => { + self.f[0] = try self.floats(8 * H, rng); + self.f[1] = try self.floats(8 * H, rng); + self.f[2] = try self.floats(H, rng); + if (nf) self.f[0][0] = std.math.nan(f32); + for (self.f[0..3]) |values| rounded(values); + for (0..3) |j| self.refs[j] = try self.input(self.f[j], true); + try self.output(0, 8 * H, .bf16); + try self.output(1, 8 * H, .bf16); + }, + .swiglu => { + self.f[0] = try self.floats(8 * INTER, rng); + self.f[1] = try self.floats(8 * INTER, rng); + if (nf) self.f[0][0] = std.math.nan(f32); + for (self.f[0..2]) |values| rounded(values); + for (0..2) |j| self.refs[j] = try self.input(self.f[j], true); + try self.output(0, 8 * INTER, .bf16); + }, + .kappa => { + self.f[0] = try self.floats(rows * H, rng); + self.f[1] = try self.floats(H, rng); + self.f[2] = try self.floats(RNN * 5120, rng); + self.f[3] = try self.floats(RNN, rng); + if (nf) self.f[0][0] = std.math.nan(f32); + for (self.f[0..4]) |values| rounded(values); + for (0..4) |j| self.refs[j] = try self.input(self.f[j], true); + try self.output(0, rows * RNN, .f32); + }, + .recurrent => { + self.f[0] = try self.floats(RANK, rng); + self.f[1] = try self.floats(RNN, rng); + self.f[2] = try self.floats(RNN * 5120, rng); + self.f[3] = try self.floats(2 * RANK, rng); + if (nf) self.f[0][0] = std.math.nan(f32); + for (self.f[0..4]) |values| rounded(values); + @memset(self.f[0], 99.5); + self.f[1][0] = c.fromBf16(c.toBf16(0.6)); + self.f[1][RANK] = c.fromBf16(c.toBf16(0.8)); + self.f[1][2 * RANK] = c.fromBf16(c.toBf16(0.3)); + for ([_]usize{ 0, RANK, 2 * RANK }) |channel| @memset(self.f[2][channel * 5120 ..][0..512], 0); + if (nf) self.f[0][0] = std.math.nan(f32); + for (0..4) |j| self.refs[j] = try self.input(self.f[j], true); + try self.output(0, RNN, .bf16); + try self.output(1, RANK, .bf16); + try self.output(2, RANK, .bf16); + }, + .logits => { + self.f[0] = try self.floats(host.vocab, rng); + self.f[1] = try self.floats(host.vocab, rng); + self.f[2] = try self.floats(RANK, rng); + for (self.f[0]) |*v| v.* = rng.float(f32) * 120 - 60; + if (nf) self.f[0][0] = std.math.nan(f32); + for (self.f[0..3]) |values| rounded(values); + self.f[0][0] = 40; + self.f[0][1] = 1000; + self.f[1][0] = 0.125; + if (nf) self.f[0][0] = std.math.nan(f32); + self.f[2][0] = c.fromBf16(c.toBf16(0.0001)); + self.phi = try self.arena.allocator().alloc(u16, host.vocab * RANK); + for (self.phi) |*v| v.* = c.toBf16(rng.float(f32) * 0.5 - 0.25); + @memset(self.phi[0..RANK], 0); + self.phi[0] = c.toBf16(1); + self.refs[0] = try self.input(self.f[0], true); + self.refs[1] = try self.rig.input(std.mem.sliceAsBytes(self.phi)); + self.refs[2] = try self.input(self.f[1], true); + self.refs[3] = try self.input(self.f[2], true); + try self.output(0, host.vocab, .bf16); + }, + .base => { + self.f[0] = try self.floats(shape.n * H, rng); + self.f[1] = try self.floats(rows * H, rng); + if (nf) self.f[0][0] = std.math.nan(f32); + rounded(self.f[0]); + rounded(self.f[1]); + if (!nf) { + @memset(self.f[0][0..H], 1); + @memset(self.f[1][0..H], 1); + } + self.refs[0] = try self.input(self.f[0], true); + self.refs[1] = try self.input(self.f[1], true); + try self.output(0, rows * shape.n, .bf16); + }, + } + return true; + } + + fn hostRef(ref: rig_.Ref) host.Ref { + return .{ .buf = ref.buf, .off = ref.off }; + } + pub fn run(self: *Probe) !void { + const pass = self.rig.begin(); + const e = pass.e; + const R = self.refs; + const O = self.outs; + const p = &self.pipes; + switch (self.kind) { + .init_rows => host.initializeRows(p, e, hostRef(R[0]), hostRef(R[1]), hostRef(O[0])), + .fuse_taps => host.fuseTaps(p, e, hostRef(R[0]), hostRef(R[1]), hostRef(R[2]), hostRef(O[0]), hostRef(O[1]), @intCast(self.shape.rows)), + .block_qkv => host.blockQkv(p, e, hostRef(R[0]), hostRef(R[1]), hostRef(R[2]), hostRef(R[3]), hostRef(R[4]), hostRef(O[0]), hostRef(O[1]), hostRef(O[2]), @intCast(self.shape.k)), + .context_kv => host.commitContext(p, e, hostRef(R[0]), hostRef(R[1]), hostRef(R[2]), hostRef(O[0]), hostRef(O[1]), @intCast(self.shape.k), @intCast(self.shape.rows), @intCast(self.shape.rows)), + .attention => host.attend(p, e, hostRef(R[0]), hostRef(R[1]), hostRef(R[2]), hostRef(R[3]), hostRef(R[4]), hostRef(self.score_scratch), hostRef(O[0]), @intCast(self.shape.n), @intCast(@max(self.shape.n, 1)), self.shape.k % 2 != 0, @intCast(self.shape.k / 2)), + .residual_norm => host.residualNorm(p, e, hostRef(R[0]), hostRef(R[1]), hostRef(R[2]), hostRef(O[0]), hostRef(O[1]), 8, self.shape.k != 0), + .swiglu => host.swiglu(p, e, hostRef(R[0]), hostRef(R[1]), hostRef(O[0]), 8 * INTER), + .kappa => host.kappa(p, e, hostRef(R[0]), hostRef(R[1]), hostRef(R[2]), hostRef(R[3]), hostRef(O[0]), @intCast(self.shape.rows)), + .recurrent => host.recurrentStep(p, e, hostRef(R[0]), hostRef(R[1]), hostRef(R[2]), hostRef(R[3]), hostRef(O[0]), hostRef(O[1]), hostRef(O[2]), 1), + .base => host.base(p, e, hostRef(R[0]), hostRef(R[1]), hostRef(O[0]), @intCast(self.shape.rows), @intCast(self.shape.n)), + .logits => host.finalLogits(p, e, hostRef(R[0]), hostRef(R[1]), hostRef(R[2]), hostRef(R[3]), hostRef(O[0])), + } + try self.rig.finish(pass); + } + + fn fusionReference(self: *Probe, want: []f64) void { + const rows = self.shape.rows; + for (0..4) |fusion| { + var scores: [4]f32 = undefined; + var peak: f32 = -std.math.inf(f32); + for (0..4) |j| { + scores[j] = self.f[1][fusion * 4 + j]; + peak = @max(peak, scores[j]); + } + var den: f32 = 0; + for (0..4) |j| { + scores[j] = @exp(scores[j] - peak); + den += scores[j]; + } + var alpha: [4]f32 = undefined; + for (0..4) |j| alpha[j] = @floatCast(bf(scores[j] / den)); + for (0..rows) |row| { + var square: f32 = 0; + for (0..H) |d| { + var mixed: f32 = 0; + for (0..4) |j| mixed += alpha[j] * self.f[0][(row * 4 + j) * H + d]; + square += mixed * mixed; + } + const scale: f32 = 1.0 / @sqrt(square / H + 1e-6); + for (0..H) |d| { + var mixed: f32 = 0; + for (0..4) |j| mixed += alpha[j] * self.f[0][(row * 4 + j) * H + d]; + const out = bf(mixed * scale * self.f[2][fusion * H + d]); + want[(fusion * rows + row) * H + d] = out; + if (fusion == 3 and row + 1 == rows) want[4 * rows * H + d] = out; + } + } + } + } + fn qkvReference(self: *Probe, want: []f64) void { + for (0..8) |row| for (0..24) |h| for (0..128) |d| { + const at = row * Q + h * 128 + d; + const other_at = row * Q + h * 128 + (if (d < 64) d + 64 else d - 64); + const scale = rms(self.f[0], row * Q + h * 128, 128); + const x: f32 = @floatCast(bf(self.f[0][at] * scale * self.f[3][d])); + const other: f32 = @floatCast(bf(self.f[0][other_at] * scale * self.f[3][if (d < 64) d + 64 else d - 64])); + want[at] = rope(d, self.shape.k + row, x, other); + }; + const offset = 8 * Q; + for (0..8) |row| for (0..8) |h| for (0..128) |d| { + const at = row * KV + h * 128 + d; + const other_at = row * KV + h * 128 + (if (d < 64) d + 64 else d - 64); + const scale = rms(self.f[1], row * KV + h * 128, 128); + const x: f32 = @floatCast(bf(self.f[1][at] * scale * self.f[4][d])); + const other: f32 = @floatCast(bf(self.f[1][other_at] * scale * self.f[4][if (d < 64) d + 64 else d - 64])); + want[offset + at] = rope(d, self.shape.k + row, x, other); + want[offset + 8 * KV + at] = self.f[2][at]; + }; + } + fn contextReference(self: *Probe, want: []f64) void { + const rows = self.shape.rows; + for (0..rows) |row| for (0..8) |h| for (0..128) |d| { + const src = row * KV + h * 128 + d; + const dst = ((self.shape.k + row) % rows) * KV + h * 128 + d; + const partner = if (d < 64) d + 64 else d - 64; + const other_src = row * KV + h * 128 + partner; + const scale = rms(self.f[0], row * KV + h * 128, 128); + const x: f32 = @floatCast(bf(self.f[0][src] * scale * self.f[2][d])); + const other: f32 = @floatCast(bf(self.f[0][other_src] * scale * self.f[2][partner])); + want[dst] = rope(d, self.shape.k + row, x, other); + want[rows * KV + dst] = self.f[1][src]; + }; + } + fn attentionReference(self: *Probe, want: []f64) !void { + const committed = self.shape.n; + const first_kept = self.first(); + const retained = committed - first_kept; + const score_count = retained + 8; + const ring = @max(committed, 1); + const scores = try self.a.alloc(f32, score_count); + defer self.a.free(scores); + for (0..8) |row| for (0..24) |h| { + const kv = h / 3; + const q_at = row * Q + h * 128; + var peak: f32 = -std.math.inf(f32); + for (0..score_count) |j| { + var dot: f32 = 0; + const k_at = if (j < retained) ((first_kept + j) % ring) * KV + kv * 128 else (j - retained) * KV + kv * 128; + const keys = if (j < retained) self.f[3] else self.f[1]; + for (0..128) |d| dot += self.f[0][q_at + d] * keys[k_at + d]; + scores[j] = dot * @as(f32, 0x1.6a09e6p-7); + peak = @max(peak, scores[j]); + } + var den: f32 = 0; + for (scores) |s| den += @exp(s - peak); + for (0..128) |d| { + var sum: f32 = 0; + for (0..score_count) |j| { + const v_at = if (j < retained) ((first_kept + j) % ring) * KV + kv * 128 + d else (j - retained) * KV + kv * 128 + d; + const values = if (j < retained) self.f[4] else self.f[2]; + sum += (@exp(scores[j] - peak) / den) * values[v_at]; + } + want[q_at + d] = bf(sum); + } + }; + } + fn recurrentReference(self: *Probe, want: []f64) void { + for (0..RANK) |i| { + var z: [3]f32 = undefined; + for (0..3) |part| { + const channel = part * RANK + i; + var sum: f32 = 0; + for (0..RANK) |d| sum += self.f[0][d] * self.f[2][channel * 5120 + d]; + for (0..RANK) |d| sum += self.f[3][RANK + d] * self.f[2][channel * 5120 + 256 + d]; + sum += self.f[1][channel]; + z[part] = @floatCast(bf(sum)); + want[channel] = z[part]; + } + const gamma: f32 = @floatCast(bf(1.0 / (1.0 + @exp(-z[0])))); + const candidate: f32 = @floatCast(bf(std.math.tanh(z[1]))); + const keep: f32 = @floatCast(bf(1.0 - gamma)); + const left: f32 = @floatCast(bf(gamma * self.f[0][i])); + const right: f32 = @floatCast(bf(keep * candidate)); + want[RNN + i] = bf(left + right); + want[RNN + RANK + i] = bf(std.math.tanh(z[2])); + } + } + + pub fn reference(self: *Probe, want: []f64, mag: []f64) !void { + switch (self.kind) { + .init_rows => for (0..8) |row| { + for (0..H) |d| want[row * H + d] = self.f[if (row == 0) 0 else 1][d]; + }, + .fuse_taps => self.fusionReference(want), + .block_qkv => self.qkvReference(want), + .context_kv => self.contextReference(want), + .attention => try self.attentionReference(want), + .residual_norm => for (0..8) |row| { + var square: f32 = 0; + for (0..H) |d| { + const at = row * H + d; + const sigma: f32 = if (self.shape.k != 0) self.f[0][at] else self.f[0][at] + self.f[1][at]; + square += sigma * sigma; + } + const scale: f32 = 1.0 / @sqrt(square / H + 1e-6); + for (0..H) |d| { + const at = row * H + d; + const sigma: f32 = if (self.shape.k != 0) self.f[0][at] else self.f[0][at] + self.f[1][at]; + want[at] = bf(sigma); + want[8 * H + at] = bf(sigma * scale * self.f[2][d]); + } + }, + .swiglu => for (want, 0..) |*w, i| { + const gate = self.f[0][i]; + w.* = bf((gate / (1.0 + @exp(-gate))) * self.f[1][i]); + }, + .kappa => for (0..self.shape.rows) |row| for (0..RNN) |channel| { + var sum: f32 = 0; + for (0..H) |d| sum += self.f[0][row * H + d] * self.f[2][channel * 5120 + 512 + d]; + for (0..H) |d| sum += self.f[1][d] * self.f[2][channel * 5120 + 2816 + d]; + sum += self.f[3][channel]; + want[row * RNN + channel] = sum; + }, + .recurrent => self.recurrentReference(want), + .base => for (0..self.shape.rows) |row| for (0..self.shape.n) |id| { + var dot: f32 = 0; + for (0..H) |d| dot += self.f[0][id * H + d] * self.f[1][row * H + d]; + want[row * self.shape.n + id] = bf(dot); + }, + .logits => for (0..host.vocab) |i| { + var dot: f32 = 0; + for (0..RANK) |d| dot += c.fromBf16(self.phi[i * RANK + d]) * self.f[2][d]; + const bias: f32 = @floatCast(bf(self.f[1][i] + dot)); + const logit: f32 = @floatCast(bf(self.f[0][i] + bias)); + want[i] = bf(30.0 * std.math.tanh(logit / 30.0)); + }, + } + for (mag, want) |*m, w| m.* = 1 + @abs(w); + } + + pub fn check(self: *Probe, gate: g.Gate) !?[]const u8 { + if (gate != .shapes and gate != .nonfinite) return "numeric hooks must be used"; + const want = try self.a.alloc(f64, self.count()); + defer self.a.free(want); + const mag = try self.a.alloc(f64, self.count()); + defer self.a.free(mag); + try self.reference(want, mag); + const bytes = try self.rig.outputBytes(); + for (want, 0..) |w, i| { + if (self.kind == .kappa) { + const got = c.read(.f32, bytes, i); + if (gate == .nonfinite and c.classOf(got) != c.classOf(w)) return "kappa floating-point class differs"; + if (gate == .shapes and std.math.isFinite(w) and @abs(got - w) > 2e-5 * @max(1, @abs(w))) return "FP32 kappa dot or column split differs"; + } else { + const bits = std.mem.readInt(u16, bytes[2 * i ..][0..2], .little); + const expected = c.toBf16(@floatCast(w)); + if (std.math.isNan(w)) { + if (!std.math.isNan(c.fromBf16(bits))) return "BF16 NaN was not propagated"; + } else if (bits != expected) { + const relative: f64 = switch (self.kind) { + .fuse_taps, .block_qkv, .context_kv, .swiglu, .logits => 0.02, + .attention => 0.03, + .base => 0, + else => 0, + }; + const got = c.fromBf16(bits); + if (@abs(@as(f64, got) - w) > @max(1e-5, relative * @abs(w))) return "BF16 endpoint differs from the explicit FP32/FP64 reference"; + } + } + } + if (self.kind == .logits and gate == .shapes) { + if (!(want[1] <= 30 and want[1] > 29.9)) return "the planted large logit does not prove softcap saturation"; + } + if (self.kind == .base and gate == .shapes and self.f[0][0] == 1) { + if (want[0] != 2304) return "raw base projection was softened instead of rounded once"; + } + return null; + } +}; + +pub const Suite = struct { + a: std.mem.Allocator, + device: mtl.Device, + queue: mtl.Queue, + kernels: *std.ArrayList(g.Kernel), + probes: std.ArrayList(*Probe) = .empty, + + fn add(s: *Suite, kind: host.Kind, control: bool, only: ?[]const u8) !void { + const name = if (control) controls.name(@fromBackingInt(@intCast(@backingInt(kind)))) else kind.label(); + if (only) |text| if (std.mem.indexOf(u8, name, text) == null) return; + const probe = try s.a.create(Probe); + errdefer s.a.destroy(probe); + if (control) { + const text = try controls.source(s.a, sources.inkling2_dspark, @fromBackingInt(@intCast(@backingInt(kind)))); + defer s.a.free(text); + probe.* = try Probe.initSource(s.a, s.device, s.queue, kind, text); + } else probe.* = try Probe.init(s.a, s.device, s.queue, kind); + errdefer probe.deinit(); + try s.probes.append(s.a, probe); + var k = probe.kernel(); + if (control) { + k.spec.name = name; + k.control = .shapes; + } + try s.kernels.append(s.a, k); + } + pub fn collect(s: *Suite, only: ?[]const u8) !void { + for (std.enums.values(host.Kind)) |kind| { + try s.add(kind, false, only); + try s.add(kind, true, only); + } + } + pub fn deinit(s: *Suite) void { + for (s.probes.items) |probe| { + probe.deinit(); + s.a.destroy(probe); + } + s.probes.deinit(s.a); + } +}; diff --git a/zig/tests/contract/metal_inkling2_dspark_controls.zig b/zig/tests/contract/metal_inkling2_dspark_controls.zig new file mode 100644 index 00000000000..638e1535fdf --- /dev/null +++ b/zig/tests/contract/metal_inkling2_dspark_controls.zig @@ -0,0 +1,56 @@ +//! One host-checkable arithmetic mutation for every Mini DSpark Metal kernel. +const std = @import("std"); + +pub const Kind = enum { init_rows, fuse_taps, block_qkv, context_kv, attention, residual_norm, swiglu, kappa, recurrent, base, logits }; +const Edit = struct { from: []const u8, to: []const u8 }; +fn edit(kind: Kind) Edit { + return switch (kind) { + .init_rows => .{ .from = "rows[row * DSP_H + d] = src[d];", .to = "rows[row * DSP_H + d] = mask[d];" }, + .fuse_taps => .{ .from = "alpha[j] = float(bfloat(scores[j] / sum));", .to = "alpha[j] = scores[j] / sum;" }, + .block_qkv => .{ .from = "const float rotated = d < 64 ? x * cs - other * sn : other * sn + x * cs;", .to = "const float rotated = d < 64 ? x * cs - other * sn : x * sn + other * cs;" }, + .context_kv => .{ .from = "keys[at] = bfloat(d < 64 ? x * cs - other * sn : other * sn + x * cs);", .to = "keys[at] = bfloat(d < 64 ? x * cs - other * sn : x * sn + other * cs);" }, + .attention => .{ .from = "const uint first = max(a.from, a.local && a.committed > 1024 ? a.committed - 1024 : 0);", .to = "const uint first = a.from;" }, + .residual_norm => .{ .from = "normalized[at] = bfloat(sigma * scale * float(weight[d]));", .to = "normalized[at] = bfloat(float(new_residual[at]) * scale * float(weight[d]));" }, + .swiglu => .{ .from = "out[i] = bfloat((gate / (1.0f + exp(-gate))) * float(u[i]));", .to = "out[i] = bfloat(gate * float(u[i]));" }, + .kappa => .{ .from = "sum += float(y[row * DSP_H + d]) * float(weight[channel * 5120 + 512 + d]);", .to = "sum += float(y[row * DSP_H + d]) * float(weight[channel * 5120 + d]);" }, + .recurrent => .{ .from = "const bfloat left = bfloat(float(gamma) * float(state[i]));", .to = "const float left = float(gamma) * float(state[i]);" }, + .base => .{ .from = "out[i] = bfloat(dot);", .to = "out[i] = bfloat(30.0f * tanh(dot / 30.0f));" }, + .logits => .{ .from = "const bfloat bias = bfloat(float(beta[i]) + dot);", .to = "const float bias = float(beta[i]) + dot;" }, + }; +} + +pub fn name(kind: Kind) []const u8 { + return switch (kind) { + inline else => |k| "control: metal inkling2 dspark " ++ @tagName(k), + }; +} +pub fn source(a: std.mem.Allocator, production: []const u8, kind: Kind) ![]u8 { + const e = edit(kind); + if (std.mem.count(u8, production, e.from) != 1) return error.ControlEditMissing; + return std.mem.replaceOwned(u8, a, production, e.from, e.to); +} + +test "every DSpark control applies once and only mutates its arithmetic anchor" { + const production = @import("inkling2_metal").inkling2_dspark; + const a = std.testing.allocator; + for (std.enums.values(Kind)) |kind| { + const e = edit(kind); + try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, production, e.from)); + const changed = try source(a, production, kind); + defer a.free(changed); + const at = std.mem.indexOf(u8, production, e.from).?; + try std.testing.expectEqualStrings(production[0..at], changed[0..at]); + try std.testing.expectEqualStrings(e.to, changed[at..][0..e.to.len]); + try std.testing.expectEqualStrings(production[at + e.from.len ..], changed[at + e.to.len ..]); + try std.testing.expectError(error.ControlEditMissing, source(a, changed, kind)); + try std.testing.expectError(error.ControlEditMissing, source(a, "", kind)); + } +} + +test "repeated DSpark control anchors are refused" { + const production = @import("inkling2_metal").inkling2_dspark; + const a = std.testing.allocator; + const twice = try std.mem.concat(a, u8, &.{ production, production }); + defer a.free(twice); + for (std.enums.values(Kind)) |kind| try std.testing.expectError(error.ControlEditMissing, source(a, twice, kind)); +} diff --git a/zig/tests/contract/metal_inkling2_experts.zig b/zig/tests/contract/metal_inkling2_experts.zig new file mode 100644 index 00000000000..55c9a3d1c66 --- /dev/null +++ b/zig/tests/contract/metal_inkling2_experts.zig @@ -0,0 +1,409 @@ +//! Inkling 2 Mini M3 contracts: independent FP64 decode/dot/activation and ascending-expert combine. +const std = @import("std"); +const mtl = @import("metal"); +const contract = @import("contract"); +const c = contract.spec; +const g = contract.gates; +const rows = contract.rows; +const bf = contract.bf16_round.bf16; +const rig_ = @import("rig.zig"); +const host = @import("tensorfold").inkling2_metal_host.experts; +const controls = @import("metal_inkling2_experts_controls.zig"); +const src = @import("inkling2_metal"); + +pub const Kind = enum { nv_gu, nv_down, mx_gu, mx_down, nv_decode, mx_decode, combine }; + +fn symbol(k: Kind) []const u8 { + return switch (k) { + .nv_gu => "tf_ink2_nvfp4_gu", + .nv_down => "tf_ink2_nvfp4_down", + .mx_gu => "tf_ink2_mxfp8_gu", + .mx_down => "tf_ink2_mxfp8_down", + .nv_decode => "tf_ink2_nvfp4_quantize", + .mx_decode => "tf_ink2_mxfp8_quantize", + .combine => "tf_ink2_combine", + }; +} + +fn mutation(k: Kind) controls.Mutation { + return switch (k) { + .nv_gu => .nv_gu_up, + .nv_down => .nv_down_phi, + .mx_gu => .mx_gu_up, + .mx_down => .mx_down_scale, + .nv_decode => .nv_decode_nibble, + .mx_decode => .mx_decode_scale, + .combine => .combine_slot_order, + }; +} + +fn isNv(k: Kind) bool { + return k == .nv_gu or k == .nv_down or k == .nv_decode; +} +fn isGu(k: Kind) bool { + return k == .nv_gu or k == .mx_gu; +} +fn isDown(k: Kind) bool { + return k == .nv_down or k == .mx_down; +} +fn isDecode(k: Kind) bool { + return k == .nv_decode or k == .mx_decode; +} +fn depth(s: c.Shape) usize { + return s.k + 3; +} + +pub fn spec(k: Kind, control: bool) c.Spec { + const base = if (control) mutation(k).name() else switch (k) { + .nv_gu => "metal inkling2 experts tf_ink2_nvfp4_gu", + .nv_down => "metal inkling2 experts tf_ink2_nvfp4_down", + .mx_gu => "metal inkling2 experts tf_ink2_mxfp8_gu", + .mx_down => "metal inkling2 experts tf_ink2_mxfp8_down", + .nv_decode => "metal inkling2 experts tf_ink2_nvfp4_quantize", + .mx_decode => "metal inkling2 experts tf_ink2_mxfp8_quantize", + .combine => "metal inkling2 experts tf_ink2_combine", + }; + return .{ + .name = base, + .accum = if (isDecode(k)) .none else .f32, + .depth = depth, + .ops = if (isGu(k)) 12 else if (isDecode(k)) 1 else 3, + .mids = if (isGu(k)) 3 else 0, + .out = .bf16, + .served = switch (k) { + .nv_gu, .mx_gu => &.{ .{ .rows = 2, .n = 4, .k = 32 }, .{ .rows = 4, .n = 8, .k = 64 } }, + .nv_down, .mx_down => &.{ .{ .rows = 2, .n = 8, .k = 32 }, .{ .rows = 4, .n = 12, .k = 64 } }, + .nv_decode, .mx_decode => &.{ .{ .rows = 2, .n = 32, .k = 32 }, .{ .rows = 3, .n = 64, .k = 64 } }, + .combine => &.{ .{ .rows = 2, .n = 8, .k = 8 }, .{ .rows = 4, .n = 12, .k = 8 } }, + }, + .sums = if (k == .combine) .{ .f16 = 0, .bf16 = 100, .why = "bounded cancellation is exact in fp32 but loses its residual in bf16" } else .{ .f16 = 0, .bf16 = 0, .why = "independent FP64 terms and explicit BF16 nodes" }, + }; +} + +const Sim = struct { acc: c.Accum, order: g.Order }; +const Sample = struct { value: f64, magnitude: f64 }; +const Dot = struct { value: f64, magnitude: f64 }; + +pub const Probe = struct { + a: std.mem.Allocator, + rig: rig_.Rig, + pipes: host.Pipelines, + kind: Kind, + ctl: controls.Mutation, + shape: c.Shape = undefined, + x: []u16 = &.{}, + w: []u8 = &.{}, + scales: []u8 = &.{}, + amax: []f32 = &.{}, + denominator: []f32 = &.{}, + ids: []i32 = &.{}, + weights: []f32 = &.{}, + refs: [7]rig_.Ref = undefined, + + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, kind: Kind, control: bool) !Probe { + const text = try controls.apply(a, if (control) mutation(kind) else .none); + defer a.free(text); + return .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .pipes = try host.Pipelines.loadSource(device, text), .kind = kind, .ctl = if (control) mutation(kind) else .none }; + } + + fn clear(p: *Probe) void { + p.a.free(p.x); + p.a.free(p.w); + p.a.free(p.scales); + p.a.free(p.amax); + p.a.free(p.denominator); + p.a.free(p.ids); + p.a.free(p.weights); + p.x = &.{}; + p.w = &.{}; + p.scales = &.{}; + p.amax = &.{}; + p.denominator = &.{}; + p.ids = &.{}; + p.weights = &.{}; + p.rig.reset(); + } + + pub fn deinit(p: *Probe) void { + p.clear(); + p.pipes.deinit(); + p.rig.deinit(); + } + + pub fn kernel(p: *Probe) g.Kernel { + return .{ .spec = spec(p.kind, p.ctl != .none), .ctx = p, .vt = if (p.kind == .combine and p.ctl == .combine_slot_order) &vt_exact else &vt, .control = p.ctl.gate() }; + } + const vt = blk: { + var table = g.hooks(Probe); + table.check = null; + break :blk table; + }; + const vt_exact = g.hooks(Probe); + + fn call(p: *const Probe) host.Call { + return .{ .rows = @intCast(p.shape.rows), .k = @intCast(if (p.kind == .combine) 32 else p.shape.k), .n = @intCast(p.shape.n), .experts = if (p.kind == .combine) 8 else 4, .topk = if (p.kind == .combine) 8 else 2, .format = if (isNv(p.kind)) .nvfp4 else .mxfp8 }; + } + + pub fn prepare(p: *Probe, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + const k = p.kind; + if (shape.rows == 0 or shape.rows > 8) return false; + if (isGu(k) and (shape.n > 8 or shape.k > 64 or shape.k % 32 != 0)) return false; + if (isDown(k) and (shape.n > 12 or shape.k > 64 or shape.k % 32 != 0)) return false; + if (isDecode(k) and (shape.n != shape.k or shape.k > 64 or shape.k % 32 != 0)) return false; + if (k == .combine and (shape.n > 12 or shape.k != 8)) return false; + p.clear(); + p.shape = shape; + const nv = isNv(k); + const topk: usize = if (k == .combine) 8 else 2; + const routes = shape.rows * topk; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + if (!isDecode(k)) { + const nx = if (isGu(k)) shape.rows * shape.k else if (isDown(k)) routes * shape.k else routes * shape.n; + p.x = try p.a.alloc(u16, nx); + for (p.x, 0..) |*v, i| v.* = c.toBf16((rng.float(f32) * 2 - 1) * (if (i % 7 == 0) @as(f32, 3) else 1)); + } + p.ids = try p.a.alloc(i32, routes); + const combine_ids = [_]i32{ 2, 0, 1, 7, 3, 6, 4, 5 }; + // Eight distinct, unsorted routes exercise ascending-expert accumulation. + for (p.ids, 0..) |*id, i| id.* = if (k == .combine) combine_ids[i % 8] else @intCast(if (i % 2 == 0) 2 else (i / 2) % 2); + const matrices: usize = if (isGu(k)) 8 * shape.n else if (isDown(k)) 4 * shape.n else shape.rows; + if (k != .combine) { + p.w = try p.a.alloc(u8, matrices * (if (nv) shape.k / 2 else shape.k)); + p.scales = try p.a.alloc(u8, matrices * (shape.k / @as(usize, if (nv) 16 else 32))); + for (p.w) |*v| v.* = rng.int(u8); + for (p.scales, 0..) |*v, i| v.* = if (nv) @intCast(0x30 + (i % 17)) else @intCast(125 + (i % 5)); + if (!nv) for (p.w) |*v| if (v.* & 0x7f == 0x7f) { + v.* = (v.* & 0x80) | 0x7e; + }; + if (k == .mx_decode) { + p.w[0] = 0x30; + p.scales[0] = 255; // Decodes to 2^127 without first forming an overflowing 2^128. + } + } + if (nv) { + p.amax = try p.a.alloc(f32, if (isDecode(k)) 1 else 4); + for (p.amax, 0..) |*v, i| v.* = 2688.125 + @as(f32, @floatFromInt(i)) * 0.375; + p.denominator = try p.a.alloc(f32, 1); + p.denominator[0] = 2695.75; + } + if (k == .combine) p.weights = try p.a.alloc(f32, routes); + if (fill == .stress and !isDecode(k)) { + for (p.x, 0..) |*v, i| v.* = c.toBf16(@as(f32, @floatFromInt(128 * (1 + i % 13))) * (if (i >= p.x.len / 2) @as(f32, -1) else 1)); + if (k != .combine) @memset(p.scales, if (nv) 0x38 else 127); + } + if (k == .combine) { + const values = [_]f32{ 1, 2, 3, 4, 5, 6, 7, 8 }; + for (p.x, 0..) |*v, i| v.* = c.toBf16(if (fill == .stress) 1 else values[i % 8]); + if (fill == .stress) { + const terms = [_]f32{ 1024, 1, 1, 1, 1, 1, 1, -1029 }; + // Map expert indices back to route slots; the ascending sum is 1024 + six 1s - 1029. + for (0..p.shape.rows) |token| for (0..8) |expert| for (0..8) |slot| if (p.ids[token * 8 + slot] == expert) { + p.weights[token * 8 + slot] = terms[expert]; + }; + } else if (p.ctl == .combine_slot_order) { + const control_weights = [_]f32{ 0x1p127, 0x1p126, -0x1p127 / 3.0, 0.25, -0.2, 1.0 / 3.0, -2.0 / 7.0, 0.375 }; + for (p.weights, 0..) |*v, i| v.* = control_weights[i % 8]; + // Only this planted control overflows route order; ascending experts remain finite. + } else { + const ordinary_weights = [_]f32{ 0.125, -0.25, 0.375, -0.5, 0.625, -0.75, 0.875, -1 }; + for (p.weights, 0..) |*v, i| v.* = ordinary_weights[i % 8]; + } + } + if (fill == .nonfinite) { + if (!isDecode(k) and p.x.len >= 3) { + p.x[0] = c.toBf16(std.math.nan(f32)); + p.x[p.x.len / 2] = c.toBf16(std.math.inf(f32)); + p.x[p.x.len - 1] = c.toBf16(-std.math.inf(f32)); + } else if (isDecode(k) and p.scales.len > 1) { + if (nv) p.scales[0] = 0x7f else p.w[0] = 0x7f; + } + } + const out = try p.rig.output(p.count() * 2); + if (k == .combine) { + p.refs[0] = try p.rig.input(std.mem.sliceAsBytes(p.x)); + p.refs[1] = try p.rig.input(std.mem.sliceAsBytes(p.ids)); + p.refs[2] = try p.rig.input(std.mem.sliceAsBytes(p.weights)); + p.refs[3] = out; + } else if (isDecode(k)) { + p.refs[0] = try p.rig.input(p.w); + p.refs[1] = try p.rig.input(p.scales); + if (nv) { + p.refs[2] = try p.rig.input(std.mem.sliceAsBytes(p.amax)); + p.refs[3] = try p.rig.input(std.mem.sliceAsBytes(p.denominator)); + p.refs[4] = out; + } else p.refs[2] = out; + } else { + p.refs[0] = try p.rig.input(std.mem.sliceAsBytes(p.x)); + p.refs[1] = try p.rig.input(p.w); + p.refs[2] = try p.rig.input(p.scales); + if (nv) { + p.refs[3] = try p.rig.input(std.mem.sliceAsBytes(p.amax)); + p.refs[4] = try p.rig.input(std.mem.sliceAsBytes(p.denominator)); + p.refs[5] = try p.rig.input(std.mem.sliceAsBytes(p.ids)); + p.refs[6] = out; + } else { + p.refs[3] = try p.rig.input(std.mem.sliceAsBytes(p.ids)); + p.refs[4] = out; + } + } + return true; + } + + fn hr(b: rig_.Ref) host.Ref { + return .{ .buf = b.buf, .off = b.off }; + } + + pub fn run(p: *Probe) !void { + const pass = p.rig.begin(); + const e = pass.e; + const nv = isNv(p.kind); + if (isDecode(p.kind)) { + if (nv) try host.nvfp4Quantize(&p.pipes, e, hr(p.refs[0]), hr(p.refs[1]), hr(p.refs[2]), hr(p.refs[3]), hr(p.refs[4]), @intCast(p.shape.rows), @intCast(p.shape.k)) else try host.mxfp8Quantize(&p.pipes, e, hr(p.refs[0]), hr(p.refs[1]), hr(p.refs[2]), @intCast(p.shape.rows), @intCast(p.shape.k)); + } else if (isGu(p.kind)) { + if (nv) try host.nvfp4Gu(&p.pipes, e, hr(p.refs[0]), hr(p.refs[1]), hr(p.refs[2]), hr(p.refs[3]), hr(p.refs[4]), hr(p.refs[5]), hr(p.refs[6]), p.call()) else try host.mxfp8Gu(&p.pipes, e, hr(p.refs[0]), hr(p.refs[1]), hr(p.refs[2]), hr(p.refs[3]), hr(p.refs[4]), p.call()); + } else if (isDown(p.kind)) { + if (nv) try host.nvfp4Down(&p.pipes, e, hr(p.refs[0]), hr(p.refs[1]), hr(p.refs[2]), hr(p.refs[3]), hr(p.refs[4]), hr(p.refs[5]), hr(p.refs[6]), p.call()) else try host.mxfp8Down(&p.pipes, e, hr(p.refs[0]), hr(p.refs[1]), hr(p.refs[2]), hr(p.refs[3]), hr(p.refs[4]), p.call()); + } else try host.combine(&p.pipes, e, hr(p.refs[0]), hr(p.refs[1]), hr(p.refs[2]), hr(p.refs[3]), p.call()); + try p.rig.finish(pass); + } + + pub fn count(p: *const Probe) usize { + return if (isGu(p.kind) or isDown(p.kind)) p.shape.rows * 2 * p.shape.n else p.shape.rows * p.shape.n; + } + + fn e2(code: u8) f64 { + const v = ([_]f64{ 0, 0.5, 1, 1.5, 2, 3, 4, 6 })[code & 7]; + return if (code & 8 != 0) -v else v; + } + fn e4(code: u8) f64 { + const exponent = (code >> 3) & 15; + const mantissa = code & 7; + if (exponent == 15 and mantissa == 7) return std.math.nan(f64); + const v = if (exponent == 0) @as(f64, @floatFromInt(mantissa)) / 512 else std.math.ldexp(@as(f64, 8 + @as(u16, mantissa)), @as(i32, exponent) - 10); + return if (code & 0x80 != 0) -v else v; + } + fn weight(p: *const Probe, expert: usize, row: usize, col: usize) f64 { + const nv = isNv(p.kind); + const k = p.shape.k; + const rows_per_expert: usize = if (isGu(p.kind)) 2 * p.shape.n else p.shape.n; + const matrix_row = if (isDecode(p.kind)) row else expert * rows_per_expert + row; + if (!nv) { + const value = p.w[matrix_row * k + col]; + const scale = p.scales[matrix_row * (k / 32) + col / 32]; + return bf(std.math.ldexp(e4(value), @as(i32, scale) - 127)); + } + const codes = p.w[matrix_row * (k / 2) + col / 2]; + const code = if (col % 2 == 0) codes & 15 else codes >> 4; + const scale = p.scales[matrix_row * (k / 16) + col / 16]; + const factor = bf(p.amax[if (isDecode(p.kind)) 0 else expert]) / bf(p.denominator[0]); + return bf(@as(f32, @floatCast(e2(code) * e4(scale) * factor))); + } + + fn dot(p: *const Probe, expert: usize, row: usize, x: []const u16, sim: ?Sim) Dot { + var terms: [64]f64 = undefined; + var magnitude: f64 = 0; + for (0..p.shape.k) |col| { + const term = p.weight(expert, row, col) * @as(f64, c.fromBf16(x[col])); + terms[col] = term; + magnitude += @abs(term); + } + return .{ .value = if (sim) |s| rows.sumIn(s.acc, s.order, terms[0..p.shape.k]) else blk: { + var sum: f64 = 0; + for (terms[0..p.shape.k]) |term| sum += term; + break :blk sum; + }, .magnitude = magnitude }; + } + + fn evaluate(p: *const Probe, at: usize, sim: ?Sim) Sample { + if (isDecode(p.kind)) return .{ .value = p.weight(0, at / p.shape.k, at % p.shape.k), .magnitude = 0 }; + if (p.kind == .combine) { + const token = at / p.shape.n; + const col = at % p.shape.n; + var terms: [8]f64 = undefined; + var magnitude: f64 = 0; + var made: usize = 0; + for (0..8) |expert| for (0..8) |slot| if (p.ids[token * 8 + slot] == @as(i32, @intCast(expert))) { + const value = p.weights[token * 8 + slot] * @as(f64, c.fromBf16(p.x[(token * 8 + slot) * p.shape.n + col])); + terms[made] = value; + made += 1; + magnitude += @abs(value); + }; + const sum = if (sim) |s| rows.sumIn(s.acc, s.order, terms[0..made]) else blk: { + var total: f64 = 0; + for (terms[0..made]) |term| total += term; + break :blk total; + }; + return .{ .value = bf(sum), .magnitude = magnitude }; + } + const pair = at / p.shape.n; + const n = at % p.shape.n; + const token = pair / 2; + const expert: usize = @intCast(p.ids[pair]); + const x = if (isGu(p.kind)) p.x[token * p.shape.k ..][0..p.shape.k] else p.x[pair * p.shape.k ..][0..p.shape.k]; + if (isDown(p.kind)) { + const d = p.dot(expert, n, x, sim); + return .{ .value = bf(d.value), .magnitude = d.magnitude }; + } + const gd = p.dot(expert, 2 * n, x, sim); + const ud = p.dot(expert, 2 * n + 1, x, sim); + const gate = bf(gd.value); + const up = bf(ud.value); + const left = 4 * std.math.tanh(gate / 4) * (1 / (1 + @exp(-gate))); + return .{ .value = bf(left * (25 * std.math.tanh(up / 25))), .magnitude = gd.magnitude + ud.magnitude }; + } + + pub fn reference(p: *Probe, want: []f64, mag: []f64) !void { + for (want, mag, 0..) |*v, *m, i| { + const sample = p.evaluate(i, null); + v.* = sample.value; + m.* = sample.magnitude; + } + } + + pub fn simulate(p: *Probe, acc: c.Accum, order: g.Order, out: []f64) !void { + for (out, 0..) |*v, i| v.* = p.evaluate(i, .{ .acc = acc, .order = order }).value; + } + pub fn check(p: *Probe, gate: g.Gate) !?[]const u8 { + if (gate != .shapes) return null; + const bytes = try p.rig.outputBytes(); + const want = try p.a.alloc(f64, p.count()); + defer p.a.free(want); + const mag = try p.a.alloc(f64, p.count()); + defer p.a.free(mag); + try p.reference(want, mag); + for (want, 0..) |w, i| if (c.read(.bf16, bytes, i) != w) return "route-slot output differs from the ascending-expert reference"; + return null; + } +}; + +pub const Suite = struct { + a: std.mem.Allocator, + device: mtl.Device, + queue: mtl.Queue, + kernels: *std.ArrayList(g.Kernel), + probes: [14]Probe = undefined, + made: usize = 0, + + pub fn deinit(s: *Suite) void { + for (s.probes[0..s.made]) |*probe| probe.deinit(); + } + + pub fn collect(s: *Suite, only: ?[]const u8) !void { + for (std.enums.values(Kind)) |kind| for ([_]bool{ false, true }) |control| { + const label = if (control) mutation(kind).name() else spec(kind, false).name; + if (only) |needle| if (std.mem.indexOf(u8, label, needle) == null) continue; + s.probes[s.made] = try Probe.init(s.a, s.device, s.queue, kind, control); + s.made += 1; + try s.kernels.append(s.a, s.probes[s.made - 1].kernel()); + }; + } +}; + +test "contract labels resolve to the seven shipped entries" { + for (std.enums.values(Kind)) |kind| { + const name = spec(kind, false).name; + try std.testing.expect(std.mem.startsWith(u8, name, "metal inkling2 experts ")); + try std.testing.expect(std.mem.indexOf(u8, src.experts, symbol(kind)) != null); + } +} diff --git a/zig/tests/contract/metal_inkling2_experts_controls.zig b/zig/tests/contract/metal_inkling2_experts_controls.zig new file mode 100644 index 00000000000..e28ae1f9cd3 --- /dev/null +++ b/zig/tests/contract/metal_inkling2_experts_controls.zig @@ -0,0 +1,83 @@ +//! Count-checked M3 source mutations: every shader entry has a genuine arithmetic control. +const std = @import("std"); +const src = @import("inkling2_metal"); +const g = @import("contract").gates; + +pub const Mutation = enum { + none, + nv_gu_up, + nv_down_phi, + mx_gu_up, + mx_down_scale, + nv_decode_nibble, + mx_decode_scale, + combine_slot_order, + + pub fn name(m: Mutation) []const u8 { + return switch (m) { + .none => "", + .nv_gu_up => "control: metal inkling2 experts tf_ink2_nvfp4_gu up row", + .nv_down_phi => "control: metal inkling2 experts tf_ink2_nvfp4_down phi", + .mx_gu_up => "control: metal inkling2 experts tf_ink2_mxfp8_gu up row", + .mx_down_scale => "control: metal inkling2 experts tf_ink2_mxfp8_down scale", + .nv_decode_nibble => "control: metal inkling2 experts tf_ink2_nvfp4_quantize nibble", + .mx_decode_scale => "control: metal inkling2 experts tf_ink2_mxfp8_quantize scale", + .combine_slot_order => "control: metal inkling2 experts tf_ink2_combine route-slot order", + }; + } + + pub fn gate(m: Mutation) ?g.Gate { + return if (m == .none) null else .shapes; + } + + const Edit = struct { from: []const u8, to: []const u8 }; + fn edit(m: Mutation) Edit { + return switch (m) { + .none => unreachable, + .nv_gu_up => .{ .from = "const uint gr = 2u * n, ur = gr + 1u;", .to = "const uint gr = 2u * n, ur = gr;" }, + .mx_gu_up => .{ .from = "const uint gr = 2u * n, ur = gr + 1u;", .to = "const uint gr = 2u * n, ur = gr;" }, + .nv_down_phi => .{ .from = "const float phi = ink2_phi(amax, denominator, expert);", .to = "const float phi = precise::divide(2.0f * amax[expert], denominator[0]);" }, + .nv_decode_nibble => .{ .from = "W[row * (a.k / 2u) + col / 2u], col,", .to = "W[row * (a.k / 2u) + col / 2u], col + 1u," }, + .mx_down_scale => .{ .from = "S + expert_s + ulong(n) * (a.k / 32u), X + ulong(group) * a.k, a.k));", .to = "S + expert_s + ulong(n) * (a.k / 16u), X + ulong(group) * a.k, a.k));" }, + .mx_decode_scale => .{ .from = "S[row * (a.k / 32u) + col / 32u]", .to = "S[row * (a.k / 32u) + col / 16u]" }, + .combine_slot_order => .{ + .from = "for (uint expert = 0; expert < a.experts; ++expert)\n for (uint slot = 0; slot < a.topk; ++slot)\n if (uint(ids[group * a.topk + slot]) == expert)\n sum += weights[group * a.topk + slot] * float(down[(group * a.topk + slot) * a.n + n]);", + .to = "for (uint slot = 0; slot < a.topk; ++slot)\n sum += weights[group * a.topk + slot] * float(down[(group * a.topk + slot) * a.n + n]);", + }, + }; + } +}; + +pub fn apply(a: std.mem.Allocator, m: Mutation) ![]u8 { + if (m == .none) return a.dupe(u8, src.experts); + const change = m.edit(); + const expected: usize = switch (m) { + .nv_gu_up, .mx_gu_up, .nv_down_phi => 2, + else => 1, + }; + if (std.mem.count(u8, src.experts, change.from) != expected) return error.ControlEditCount; + // The same textual mutation serves both formats; a control compiles only its selected entry. + return std.mem.replaceOwned(u8, a, src.experts, change.from, change.to); +} + +test "every expert control edits exactly its planted arithmetic" { + const a = std.testing.allocator; + for (std.enums.values(Mutation)) |m| { + if (m == .none) continue; + const edited = try apply(a, m); + defer a.free(edited); + try std.testing.expect(std.mem.indexOf(u8, edited, m.edit().to) != null); + try std.testing.expectEqual(g.Gate.shapes, m.gate().?); + try std.testing.expect(std.mem.startsWith(u8, m.name(), "control: metal inkling2 experts ")); + } + const plain = try apply(a, .none); + defer a.free(plain); + try std.testing.expectEqualStrings(src.experts, plain); +} + +test "expert source exports all seven entries and has no activation quantizer" { + for ([_][]const u8{ "tf_ink2_nvfp4_gu", "tf_ink2_nvfp4_down", "tf_ink2_mxfp8_gu", "tf_ink2_mxfp8_down", "tf_ink2_nvfp4_quantize", "tf_ink2_mxfp8_quantize", "tf_ink2_combine" }) |name| + try std.testing.expect(std.mem.indexOf(u8, src.experts, name) != null); + try std.testing.expect(std.mem.indexOf(u8, src.experts, "never quantize an activation") != null); + try std.testing.expect(std.mem.indexOf(u8, src.experts, "e2m1(float") == null); +} diff --git a/zig/tests/contract/metal_inkling2_glue.zig b/zig/tests/contract/metal_inkling2_glue.zig new file mode 100644 index 00000000000..496f4c69f98 --- /dev/null +++ b/zig/tests/contract/metal_inkling2_glue.zig @@ -0,0 +1,376 @@ +//! Inkling 2 Mini glue under FP64 references, guarded buffers and real Metal dispatch. +const std = @import("std"); +const mtl = @import("metal"); +const controls = @import("metal_inkling2_glue_controls.zig"); +const contract = @import("contract"); +const c = contract.spec; +const g = contract.gates; +const rig_ = @import("rig.zig"); +const host = @import("tensorfold").inkling2_metal_host.glue; +const p = host.plan; +const sources = @import("inkling2_metal"); + +fn depth(s: c.Shape) usize { + return s.k + 40; +} +fn value(rng: std.Random) f32 { + return rng.float(f32) * 0.5 - 0.25; +} +fn fromBf(v: u16) f32 { + return c.fromBf16(v); +} + +fn round(values: []f32) void { + for (values) |*v| v.* = c.fromBf16(c.toBf16(v.*)); +} + +pub const Probe = struct { + a: std.mem.Allocator, + arena: std.heap.ArenaAllocator, + rig: rig_.Rig, + kind: p.Kind, + pipes: host.Pipelines, + shape: c.Shape = undefined, + served: [3]c.Shape = undefined, + f: [4][]f32 = @splat(&.{}), + ids: []u32 = &.{}, + route_ids: rig_.Ref = undefined, + refs: [5]rig_.Ref = undefined, + out: rig_.Ref = undefined, + nonfinite: bool = false, + + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, kind: p.Kind) !Probe { + return initSource(a, device, queue, kind, sources.glue); + } + pub fn initSource(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, kind: p.Kind, text: []const u8) !Probe { + var self: Probe = .{ .a = a, .arena = .init(a), .rig = .{ .a = a, .device = device, .queue = queue }, .kind = kind, .pipes = try host.Pipelines.loadSource(device, text) }; + self.served = switch (kind) { + .embed_norm => .{ .{ .rows = 1, .n = p.hidden, .k = p.hidden }, .{ .rows = 5, .n = p.hidden, .k = p.hidden }, .{ .rows = 7, .n = p.hidden, .k = p.hidden } }, + .ar => .{ .{ .rows = 2, .n = p.hidden, .k = p.hidden }, .{ .rows = 4, .n = p.hidden, .k = p.hidden }, .{ .rows = 5, .n = p.hidden, .k = p.hidden } }, + .conv_static => .{ .{ .rows = 1, .n = 128, .k = 4 }, .{ .rows = 5, .n = 1024, .k = 4 }, .{ .rows = 7, .n = p.hidden, .k = 4 } }, + .conv_dynamic => .{ .{ .rows = 1, .n = 128, .k = 4 }, .{ .rows = 5, .n = 512, .k = 4 }, .{ .rows = 7, .n = 1024, .k = 4 } }, + .router => .{ .{ .rows = 1, .n = 8, .k = p.hidden }, .{ .rows = 5, .n = 8, .k = p.hidden }, .{ .rows = 7, .n = 8, .k = p.hidden } }, + .swiglu => .{ .{ .rows = 1, .n = p.intermediate, .k = 2 }, .{ .rows = 5, .n = p.intermediate, .k = 2 }, .{ .rows = 7, .n = p.intermediate, .k = 2 } }, + .logits => .{ .{ .rows = 1, .n = 128, .k = p.hidden }, .{ .rows = 5, .n = 256, .k = p.hidden }, .{ .rows = 7, .n = 128, .k = p.hidden } }, + .expert_pick => .{ .{ .rows = 1, .n = p.intermediate, .k = 8 }, .{ .rows = 5, .n = p.intermediate, .k = 8 }, .{ .rows = 7, .n = p.intermediate, .k = 8 } }, + .expert_combine => .{ .{ .rows = 1, .n = p.hidden, .k = 8 }, .{ .rows = 5, .n = p.hidden, .k = 8 }, .{ .rows = 7, .n = p.hidden, .k = 8 } }, + }; + return self; + } + pub fn deinit(self: *Probe) void { + self.rig.deinit(); + self.arena.deinit(); + self.pipes.deinit(); + } + const vt_checked = g.hooks(Probe); + const vt_plain = blk: { + var vt = g.hooks(Probe); + vt.check = null; + break :blk vt; + }; + pub fn kernel(self: *Probe) g.Kernel { + const out: c.Elem = switch (self.kind) { + .ar, .router, .logits => .f32, + else => .bf16, + }; + return .{ + .ctx = self, + .vt = if (self.kind == .router) &vt_checked else &vt_plain, + .spec = .{ + .name = self.kind.label(), + .accum = .f32, + .depth = depth, + .ops = 96, + .mids = if (self.kind == .logits) 1 else 0, + .out = out, + .served = &self.served, + .nan = if (self.kind == .router) .{ .stated = "a NaN selected score makes the shared normalization and every selected weight NaN" } else .propagate, + // AR's integer stress terms are exact in FP32 and must discriminate FP16/BF16 by 100x. + .sums = if (self.kind == .ar) .{} else .{ .f16 = 0, .bf16 = 0, .why = "nonlinear norms, exponentials and BF16 endpoints have no uniform lower-precision separability factor" }, + }, + }; + } + pub fn count(self: *Probe) usize { + return if (self.kind == .ar) 2 * p.hidden else p.count(self.kind, .{ .rows = self.shape.rows, .n = self.shape.n, .k = self.shape.k }); + } + fn floats(self: *Probe, n: usize, rng: std.Random) ![]f32 { + const out = try self.arena.allocator().alloc(f32, n); + for (out) |*x| x.* = value(rng); + return out; + } + fn input(self: *Probe, values: []const f32, bf: bool) !rig_.Ref { + if (!bf) return self.rig.input(std.mem.sliceAsBytes(values)); + const bits = try self.arena.allocator().alloc(u16, values.len); + for (bits, values) |*b, x| b.* = c.toBf16(x); + return self.rig.input(std.mem.sliceAsBytes(bits)); + } + pub fn prepare(self: *Probe, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (!p.valid(self.kind, .{ .rows = shape.rows, .n = shape.n, .k = shape.k })) return false; + if (self.kind == .embed_norm and shape.n != p.hidden) return false; + self.rig.reset(); + _ = self.arena.reset(.retain_capacity); + self.shape = shape; + self.nonfinite = fill == .nonfinite; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + const r = shape.rows; + const n = shape.n; + const nf = fill == .nonfinite; + self.f = @splat(&.{}); + switch (self.kind) { + .embed_norm => { + self.f[0] = try self.floats(64 * p.hidden, rng); + self.f[1] = try self.floats(p.hidden, rng); + self.ids = try self.arena.allocator().alloc(u32, r); + for (self.ids, 0..) |*id, i| id.* = @intCast(i % 64); + if (nf) self.f[0][0] = std.math.nan(f32); + self.refs[0] = try self.rig.input(std.mem.sliceAsBytes(self.ids)); + self.refs[1] = try self.input(self.f[0], true); + self.refs[2] = try self.input(self.f[1], true); + }, + .ar => { + self.f[0] = try self.floats((r - 1) * p.hidden, rng); + self.f[1] = try self.floats(p.hidden, rng); + self.f[2] = try self.floats(2 * p.hidden, rng); + if (fill == .stress) { + // Each 2304-term square sum is exactly 9 * 2^24 in FP32 under every order. + for (0..r) |s| { + const values = if (s + 1 == r) self.f[1] else self.f[0][s * p.hidden ..][0..p.hidden]; + @memset(values, if (s % 2 == 0) 256 else -256); + } + // Normalized mirrored queries leave +/-8; partial sums stay exact integers in FP32. + for (0..2) |query_row| { + const row = self.f[2][query_row * p.hidden ..][0..p.hidden]; + for (0..p.hidden / 2) |d| { + const v: f32 = @floatFromInt(1 + rng.uintLessThan(u32, 64)); + const nudge: f32 = if (d < 8) 1 else 0; + row[d] = v; + row[p.hidden / 2 + d] = nudge - v; + } + } + } + if (nf) self.f[2][0] = std.math.inf(f32); + self.refs[0] = try self.input(self.f[0], true); + self.refs[1] = try self.input(self.f[1], false); + self.refs[2] = try self.input(self.f[2], false); + }, + .conv_static => { + self.f[0] = try self.floats((r + 3) * n, rng); + self.f[1] = try self.floats(4 * n, rng); + if (nf) self.f[0][0] = std.math.nan(f32); + self.refs[0] = try self.input(self.f[0], true); + self.refs[1] = try self.input(self.f[1], true); + }, + .conv_dynamic => { + self.f[0] = try self.floats((r + 3) * n, rng); + self.f[1] = try self.floats(r * p.hidden, rng); + self.f[2] = try self.floats(4 * n, rng); + self.f[3] = try self.floats(32 * p.hidden, rng); + if (nf) self.f[1][0] = std.math.nan(f32); + for (0..4) |j| self.refs[j] = try self.input(self.f[j], true); + }, + .router => { + self.f[0] = try self.floats(r * p.hidden, rng); + self.f[1] = try self.floats(p.expert_count * p.hidden, rng); + self.f[2] = try self.floats(p.expert_count, rng); + if (nf) self.f[0][0] = std.math.nan(f32); + self.refs[0] = try self.input(self.f[0], true); + self.refs[1] = try self.input(self.f[1], true); + self.refs[2] = try self.input(self.f[2], false); + self.route_ids = try self.rig.scratch(r * 8 * 4); + }, + .swiglu => { + self.f[0] = try self.floats(r * n * 2, rng); + if (nf) self.f[0][0] = std.math.nan(f32); + self.refs[0] = try self.input(self.f[0], true); + }, + .logits => { + self.f[0] = try self.floats(r * p.hidden, rng); + self.f[1] = try self.floats(n * p.hidden, rng); + if (nf) self.f[0][0] = std.math.nan(f32); + self.refs[0] = try self.input(self.f[0], true); + self.refs[1] = try self.input(self.f[1], true); + }, + .expert_pick => { + self.f[0] = try self.floats(r * p.expert_count * n, rng); + if (nf) self.f[0][0] = std.math.nan(f32); + self.ids = try self.arena.allocator().alloc(u32, r * 8); + for (self.ids, 0..) |*id, j| id.* = @intCast(j % 8 * 13 + j / 8); + self.refs[0] = try self.input(self.f[0], true); + self.refs[1] = try self.rig.input(std.mem.sliceAsBytes(self.ids)); + }, + .expert_combine => { + self.f[0] = try self.floats(r * 8 * n, rng); + self.f[1] = try self.floats(r * 8, rng); + if (nf) self.f[0][0] = std.math.nan(f32); + self.refs[0] = try self.input(self.f[0], true); + self.refs[1] = try self.input(self.f[1], false); + }, + } + // Every BF16 input and the FP64 oracle see exactly the same stored values. + for (self.f, 0..) |values, j| if (values.len > 0 and switch (self.kind) { + .ar => j == 0, + .router => j < 2, + .expert_combine => j == 0, + else => true, + }) round(values); + const bytes = self.count() * @as(usize, if (self.kind == .ar or self.kind == .router or self.kind == .logits) 4 else 2); + self.out = try self.rig.output(bytes); + return true; + } + fn at(ref: rig_.Ref) host.Ref { + return .{ .buf = ref.buf, .off = ref.off }; + } + pub fn run(self: *Probe) !void { + const pass = self.rig.begin(); + const e = pass.e; + const pl = &self.pipes; + const R = self.refs; + const y = at(self.out); + const r: u32 = @intCast(self.shape.rows); + const n: u32 = @intCast(self.shape.n); + switch (self.kind) { + .embed_norm => host.embedNorm(pl, e, at(R[0]), at(R[1]), at(R[2]), y, r), + .ar => host.ar(pl, e, at(R[0]), at(R[1]), at(R[2]), y, r, 2), + .conv_static => host.convStatic(pl, e, at(R[0]), at(R[1]), y, r, n), + .conv_dynamic => host.convDynamic(pl, e, at(R[0]), at(R[1]), at(R[2]), at(R[3]), y, r, n), + .router => host.router(pl, e, at(R[0]), at(R[1]), at(R[2]), at(self.route_ids), y, r), + .swiglu => host.swiglu(pl, e, at(R[0]), y, r, n), + .logits => host.logits(pl, e, at(R[0]), at(R[1]), y, r, n), + .expert_pick => host.expertPick(pl, e, at(R[0]), at(R[1]), y, r, n), + .expert_combine => host.expertCombine(pl, e, at(R[0]), at(R[1]), y, r, n), + } + try self.rig.finish(pass); + } + pub fn reference(self: *Probe, want: []f64, mag: []f64) !void { + const r = self.shape.rows; + const n = self.shape.n; + for (0..r) |row| switch (self.kind) { + .embed_norm => { + const x = self.f[0][self.ids[row] * p.hidden ..][0..p.hidden]; + for (0..p.hidden) |d| want[row * p.hidden + d] = p.embedValue(x, self.f[1], d); + }, + .ar => { + var qout: [2 * p.hidden]f64 = undefined; + for (0..2) |q| p.blockResidual(self.f[0], self.f[1], self.f[2], r, q, qout[q * p.hidden ..][0..p.hidden]); + @memcpy(want, &qout); + break; + }, + .conv_static => { + for (0..n) |d| want[row * n + d] = p.staticConv(self.f[0], self.f[1], n, row, d); + }, + .conv_dynamic => { + for (0..n) |d| want[row * n + d] = p.dynamicConv(self.f[0], self.f[1], self.f[2], self.f[3], n, row, d); + }, + .router => { + const route = p.route(self.f[0][row * p.hidden ..][0..p.hidden], self.f[1], self.f[2]); + @memcpy(want[row * 8 ..][0..8], &route.weights); + }, + .swiglu => { + for (0..n) |d| want[row * n + d] = p.swiglu(self.f[0][(row * n + d) * 2], self.f[0][(row * n + d) * 2 + 1]); + }, + .logits => { + for (0..n) |v| want[row * n + v] = p.logit(self.f[0][row * p.hidden ..][0..p.hidden], self.f[1], v); + }, + .expert_pick => { + for (0..8) |j| { + for (0..n) |d| want[(row * 8 + j) * n + d] = p.pick(self.f[0], self.ids, n, row, j, d); + } + }, + .expert_combine => { + for (0..n) |d| want[row * n + d] = p.combine(self.f[0][row * 8 * n ..], self.f[1][row * 8 ..][0..8], n, d); + }, + }; + for (mag, want) |*m, w| m.* = 10 * @abs(w) + 1e-5; + } + pub fn simulate(self: *Probe, acc: c.Accum, order: g.Order, out: []f64) !void { + if (self.kind == .ar) { + const sim: p.ArSum = .{ + .accum = switch (acc) { + .none => .none, + .f32 => .f32, + .f16 => .f16, + .bf16 => .bf16, + }, + .order = switch (order) { + .sequential => .sequential, + .pairwise => .pairwise, + .strided => .strided, + }, + }; + for (0..2) |q| p.blockResidualIn(self.f[0], self.f[1], self.f[2], self.shape.rows, q, sim, out[q * p.hidden ..][0..p.hidden]); + return; + } + const mag = try self.a.alloc(f64, out.len); + defer self.a.free(mag); + return self.reference(out, mag); + } + pub fn check(self: *Probe, gate: g.Gate) !?[]const u8 { + if (self.kind != .router) return "numeric hooks must be used"; + const bytes = try self.rig.outputBytes(); + const want = try self.a.alloc(f64, self.count()); + defer self.a.free(want); + const mag = try self.a.alloc(f64, self.count()); + defer self.a.free(mag); + try self.reference(want, mag); + if (gate == .nonfinite) { + for (want, 0..) |w, i| if (std.math.isNan(c.read(.f32, bytes, i)) != std.math.isNan(w)) return "NaN normalization rule differs"; + return null; + } + const got_ids = std.mem.bytesAsSlice(u32, self.rig.bytes(self.route_ids, self.shape.rows * 8 * 4)); + for (0..self.shape.rows) |row| { + const route = p.route(self.f[0][row * p.hidden ..][0..p.hidden], self.f[1], self.f[2]); + for (0..8) |j| { + if (got_ids[row * 8 + j] != route.ids[j]) return "selected IDs differ"; + const got = c.read(.f32, bytes, row * 8 + j); + if (@abs(got - want[row * 8 + j]) > 1e-5 * @max(1, @abs(want[row * 8 + j]))) return "router weight differs"; + } + } + return null; + } +}; + +pub const Suite = struct { + a: std.mem.Allocator, + device: mtl.Device, + queue: mtl.Queue, + kernels: *std.ArrayList(g.Kernel), + probes: std.ArrayList(*Probe) = .empty, + + fn add(s: *Suite, kind: p.Kind, control: bool, only: ?[]const u8) !void { + const name = if (control) controls.name(kind) else kind.label(); + if (only) |text| if (std.mem.indexOf(u8, name, text) == null) return; + const probe = try s.a.create(Probe); + errdefer s.a.destroy(probe); + if (control) { + const text = try controls.source(s.a, sources.glue, kind); + defer s.a.free(text); + probe.* = try Probe.initSource(s.a, s.device, s.queue, kind, text); + } else { + probe.* = try Probe.init(s.a, s.device, s.queue, kind); + } + errdefer probe.deinit(); + try s.probes.append(s.a, probe); + var k = probe.kernel(); + if (control) { + k.spec.name = name; + k.control = .shapes; + } + try s.kernels.append(s.a, k); + } + + pub fn collect(s: *Suite, only: ?[]const u8) !void { + for (std.enums.values(p.Kind)) |kind| { + try s.add(kind, false, only); + try s.add(kind, true, only); + } + } + + pub fn deinit(s: *Suite) void { + for (s.probes.items) |probe| { + probe.deinit(); + s.a.destroy(probe); + } + s.probes.deinit(s.a); + } +}; diff --git a/zig/tests/contract/metal_inkling2_glue_controls.zig b/zig/tests/contract/metal_inkling2_glue_controls.zig new file mode 100644 index 00000000000..aba23199f09 --- /dev/null +++ b/zig/tests/contract/metal_inkling2_glue_controls.zig @@ -0,0 +1,65 @@ +//! One host-checkable source-planted arithmetic fault for every Inkling 2 Mini glue kernel. +const std = @import("std"); +const p = @import("inkling2_glue_plan"); + +const Edit = struct { from: []const u8, to: []const u8 }; +fn edit(kind: p.Kind) Edit { + return switch (kind) { + .embed_norm => .{ .from = "float(weight[d]) * (float(x[d]) * inverse)", .to = "float(weight[0]) * (float(x[d]) * inverse)" }, + .ar => .{ .from = "weights[s] = dot * INKLING_AR_SCALE;", .to = "weights[s] = dot;" }, + .conv_static => .{ .from = "weight[c * 4 + tap]", .to = "weight[c * 4 + 3 - tap]" }, + .conv_dynamic => .{ .from = "static_w[lag * a.channels + c]", .to = "static_w[(3 - lag) * a.channels + c]" }, + .router => .{ .from = "scores[e] + bias[e] > scores[best] + bias[best]", .to = "scores[e] > scores[best]" }, + .swiglu => .{ .from = "ink_cap(u, 25.0f)", .to = "ink_cap(g, 25.0f)" }, + .logits => .{ .from = "ink_cap(float(bfloat(dot)), 30.0f)", .to = "ink_cap(dot, 30.0f)" }, + .expert_pick => .{ .from = "ids[r * 8 + j]", .to = "ids[r * 8 + 7 - j]" }, + .expert_combine => .{ .from = "acc += weights[r * 8 + j] * float(picked[(size_t(r) * 8 + j) * a.channels + d]);", .to = "acc -= weights[r * 8 + j] * float(picked[(size_t(r) * 8 + j) * a.channels + d]);" }, + }; +} + +pub fn source(a: std.mem.Allocator, production: []const u8, kind: p.Kind) ![]u8 { + const e = edit(kind); + if (std.mem.count(u8, production, e.from) != 1) return error.ControlEditMissing; + return std.mem.replaceOwned(u8, a, production, e.from, e.to); +} + +pub fn name(kind: p.Kind) []const u8 { + return switch (kind) { + .embed_norm => "control: metal inkling2 glue embed_norm tf_inkling2_embed_norm", + .ar => "control: metal inkling2 glue ar tf_inkling2_ar", + .conv_static => "control: metal inkling2 glue conv_static tf_inkling2_conv_static", + .conv_dynamic => "control: metal inkling2 glue conv_dynamic tf_inkling2_conv_dynamic", + .router => "control: metal inkling2 glue router tf_inkling2_router", + .swiglu => "control: metal inkling2 glue swiglu tf_inkling2_swiglu", + .logits => "control: metal inkling2 glue logits tf_inkling2_logits", + .expert_pick => "control: metal inkling2 glue expert_pick tf_inkling2_expert_pick", + .expert_combine => "control: metal inkling2 glue expert_combine tf_inkling2_expert_combine", + }; +} + +test "every glue control applies once and changes only its arithmetic anchor" { + const production = @import("inkling2_metal").glue; + const a = std.testing.allocator; + for (std.enums.values(p.Kind)) |kind| { + const e = edit(kind); + try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, production, e.from)); + const changed = try source(a, production, kind); + defer a.free(changed); + const at = std.mem.indexOf(u8, production, e.from).?; + try std.testing.expectEqualStrings(production[0..at], changed[0..at]); + try std.testing.expectEqualStrings(e.to, changed[at..][0..e.to.len]); + try std.testing.expectEqualStrings(production[at + e.from.len ..], changed[at + e.to.len ..]); + try std.testing.expectError(error.ControlEditMissing, source(a, changed, kind)); + try std.testing.expectError(error.ControlEditMissing, source(a, "", kind)); + } +} + +test "a repeated glue control anchor is ambiguous and refuses to prove a fault" { + const a = std.testing.allocator; + const production = @import("inkling2_metal").glue; + for (std.enums.values(p.Kind)) |kind| { + const twice = try std.mem.concat(a, u8, &.{ production, production }); + defer a.free(twice); + try std.testing.expectError(error.ControlEditMissing, source(a, twice, kind)); + } +} diff --git a/zig/tests/contract/metal_inkling2_loop.zig b/zig/tests/contract/metal_inkling2_loop.zig new file mode 100644 index 00000000000..f597983003e --- /dev/null +++ b/zig/tests/contract/metal_inkling2_loop.zig @@ -0,0 +1,327 @@ +//! Mini cross-pass messages and rank-64 gates under FP64 oracles and mutation controls. +const std = @import("std"); +const mtl = @import("metal"); +const controls = @import("metal_inkling2_loop_controls.zig"); +const contract = @import("contract"); +const c = contract.spec; +const g = contract.gates; +const rig_ = @import("rig.zig"); +const host = @import("tensorfold").inkling2_metal_host.loop; +const p = host.plan; +const sources = @import("inkling2_metal"); + +fn depth(s: c.Shape) usize { + return if (s.n == p.message_entries * p.hidden) 2 * s.k + 16 else 2 * p.hidden + s.k + 16; +} +fn value(rng: std.Random) f32 { + return rng.float(f32) * 0.5 - 0.25; +} +fn round(values: []f32) void { + for (values) |*v| v.* = c.fromBf16(c.toBf16(v.*)); +} + +pub const Probe = struct { + a: std.mem.Allocator, + arena: std.heap.ArenaAllocator, + rig: rig_.Rig, + kind: p.Kind, + pipes: host.Pipelines, + shape: c.Shape = undefined, + served: [3]c.Shape = undefined, + f: [6][]f32 = @splat(&.{}), + refs: [6]rig_.Ref = undefined, + out: rig_.Ref = undefined, + + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, kind: p.Kind) !Probe { + return initSource(a, device, queue, kind, sources.loop); + } + pub fn initSource(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, kind: p.Kind, text: []const u8) !Probe { + var self: Probe = .{ + .a = a, + .arena = .init(a), + .rig = .{ .a = a, .device = device, .queue = queue }, + .kind = kind, + .pipes = try host.Pipelines.loadSource(device, text), + }; + self.served = switch (kind) { + .messages => .{ + .{ .rows = 1, .n = p.message_entries * p.hidden, .k = p.hidden }, + .{ .rows = 5, .n = p.message_entries * p.hidden, .k = p.hidden }, + .{ .rows = 7, .n = p.message_entries * p.hidden, .k = p.hidden }, + }, + .gates => .{ + .{ .rows = 1, .n = p.hidden, .k = p.rank }, + .{ .rows = 5, .n = p.hidden, .k = p.rank }, + .{ .rows = 7, .n = p.hidden, .k = p.rank }, + }, + }; + return self; + } + pub fn deinit(self: *Probe) void { + self.rig.deinit(); + self.arena.deinit(); + self.pipes.deinit(); + } + + const vt = g.hooks(Probe); + pub fn kernel(self: *Probe) g.Kernel { + return .{ .ctx = self, .vt = &vt, .spec = .{ + .name = self.kind.label(), + .accum = .f32, + .depth = depth, + .ops = if (self.kind == .messages) 32 else 64, + .mids = if (self.kind == .gates) 2 else 0, + .out = .f32, + .served = &self.served, + .sums = .{}, + } }; + } + pub fn count(self: *Probe) usize { + return p.count(self.kind, .{ .rows = self.shape.rows, .n = self.shape.n, .k = self.shape.k }); + } + + fn floats(self: *Probe, n: usize, rng: std.Random) ![]f32 { + const values = try self.arena.allocator().alloc(f32, n); + for (values) |*v| v.* = value(rng); + return values; + } + fn input(self: *Probe, values: []const f32, bf: bool) !rig_.Ref { + if (!bf) return self.rig.input(std.mem.sliceAsBytes(values)); + const bits = try self.arena.allocator().alloc(u16, values.len); + for (bits, values) |*b, v| b.* = c.toBf16(v); + return self.rig.input(std.mem.sliceAsBytes(bits)); + } + + pub fn prepare(self: *Probe, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + const call = p.Call{ .rows = shape.rows, .n = shape.n, .k = shape.k }; + if (!p.valid(self.kind, call)) return false; + self.rig.reset(); + _ = self.arena.reset(.retain_capacity); + self.shape = shape; + self.f = @splat(&.{}); + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + const r = shape.rows; + switch (self.kind) { + .messages => { + self.f[0] = try self.floats(r * p.hidden, rng); + self.f[1] = try self.floats(r * p.hidden, rng); + self.f[2] = try self.floats(2 * p.core_layers * p.hidden, rng); + self.f[3] = try self.floats(2 * p.core_layers * p.hidden, rng); + if (fill == .stress) { + // rho(+256) = +1 and rho(-256) = -1 in FP32: their square sum is 9 * 2^24. + @memset(self.f[0], 256); + @memset(self.f[1], -256); + // Mirrored integer queries leave 8, while every partial sum stays below 2^24. + for ([_][]f32{ self.f[2], self.f[3] }) |queries| for (0..2 * p.core_layers) |query_row| { + const row = queries[query_row * p.hidden ..][0..p.hidden]; + for (0..p.hidden / 2) |d| { + const v: f32 = @floatFromInt(1 + rng.uintLessThan(u32, 64)); + const nudge: f32 = if (d < 8) 1 else 0; + row[d] = v; + row[p.hidden / 2 + d] = nudge - v; + } + }; + } + if (fill == .nonfinite) self.f[0][0] = std.math.nan(f32); + round(self.f[0]); + round(self.f[1]); + self.refs[0] = try self.input(self.f[0], true); + self.refs[1] = try self.input(self.f[1], true); + self.refs[2] = try self.input(self.f[2], false); + self.refs[3] = try self.input(self.f[3], false); + }, + .gates => { + self.f[0] = try self.floats(r * p.hidden, rng); + self.f[1] = try self.floats(r * p.hidden, rng); + self.f[2] = try self.floats(p.rank * 2 * p.hidden, rng); + self.f[3] = try self.floats(p.hidden * p.rank, rng); + self.f[4] = try self.floats(p.hidden * p.rank, rng); + if (fill == .stress) { + @memset(self.f[0], 256); + @memset(self.f[1], -256); + // D sees [+1; -1]: mirrored integer rows leave zeta = 1, with exact FP32 partials. + for (0..p.rank) |rank| for (0..p.hidden) |d| { + const w: f32 = @floatFromInt(1 + rng.uintLessThan(u32, 64)); + self.f[2][rank * 2 * p.hidden + d] = w; + self.f[2][rank * 2 * p.hidden + p.hidden + d] = if (d == 0) w - 1 else w; + }; + // With zeta = 1, mirrored F/Gamma rows leave one, also exactly in every FP32 order. + for ([_][]f32{ self.f[3], self.f[4] }) |weights| for (0..p.hidden) |d| for (0..p.rank / 2) |rank| { + const w: f32 = @floatFromInt(1 + rng.uintLessThan(u32, 7)); + weights[d * p.rank + rank] = w; + weights[d * p.rank + rank + p.rank / 2] = if (rank == 0) 1 - w else -w; + }; + } + if (fill == .nonfinite) self.f[0][0] = std.math.nan(f32); + round(self.f[2]); + round(self.f[3]); + round(self.f[4]); + self.refs[0] = try self.input(self.f[0], false); + self.refs[1] = try self.input(self.f[1], false); + self.refs[2] = try self.input(self.f[2], true); + self.refs[3] = try self.input(self.f[3], true); + self.refs[4] = try self.input(self.f[4], true); + }, + } + self.out = try self.rig.output(self.count() * @sizeOf(f32)); + return true; + } + + fn at(ref: rig_.Ref) host.Ref { + return .{ .buf = ref.buf, .off = ref.off }; + } + pub fn run(self: *Probe) !void { + const pass = self.rig.begin(); + const e = pass.e; + const rows: u32 = @intCast(self.shape.rows); + switch (self.kind) { + .messages => host.crossPassMessageAttention(&self.pipes, e, at(self.refs[0]), at(self.refs[1]), at(self.refs[2]), at(self.refs[3]), at(self.out), rows), + .gates => host.gates(&self.pipes, e, at(self.refs[0]), at(self.refs[1]), at(self.refs[2]), at(self.refs[3]), at(self.refs[4]), at(self.out), rows), + } + try self.rig.finish(pass); + } + + pub fn reference(self: *Probe, want: []f64, mag: []f64) !void { + switch (self.kind) { + .messages => for (0..self.shape.rows) |row| { + const b0 = self.f[0][row * p.hidden ..][0..p.hidden]; + const b1 = self.f[1][row * p.hidden ..][0..p.hidden]; + for (0..p.message_entries) |entry| { + const role: p.Role = @fromBackingInt(@intCast(entry % p.roles)); + const dst = want[(row * p.message_entries + entry) * p.hidden ..][0..p.hidden]; + p.message(b0, b1, self.f[2], self.f[3], entry / p.roles, role, dst); + } + }, + .gates => for (0..self.shape.rows) |row| { + const h = self.f[0][row * p.hidden ..][0..p.hidden]; + const m = self.f[1][row * p.hidden ..][0..p.hidden]; + p.gate(h, m, self.f[2], self.f[3], self.f[4], want[row * p.hidden ..][0..p.hidden]); + }, + } + for (mag, want) |*m, w| m.* = if (self.kind == .messages) + 10 * @abs(w) + 1e-3 + else + 32 * @abs(w) + 8; + } + fn simRms(x: []const f32, acc: c.Accum, order: g.Order, terms: []f64) f64 { + for (x, 0..) |v, d| terms[d] = @as(f64, v) * v; + const ss = contract.rows.sumIn(acc, order, terms[0..p.hidden]); + return 1 / @sqrt(ss / @as(f64, @floatFromInt(p.hidden)) + p.eps); + } + + fn simMessage(bank0: []const f32, bank1: []const f32, q_mlp: []const f32, kv: []const f32, layer: usize, role: p.Role, inverse: [2]f64, acc: c.Accum, order: g.Order, terms: []f64, out: []f64) void { + const queries = if (p.usesQueryMessageTensor(role)) q_mlp else kv; + const query = queries[p.queryRow(role, layer) * p.hidden ..][0..p.hidden]; + var logits: [2]f64 = undefined; + var peak = -std.math.inf(f64); + inline for (0..2) |s| { + const bank = if (s == 0) bank0 else bank1; + for (0..p.hidden) |d| terms[d] = @as(f64, query[d]) * (@as(f64, bank[d]) * inverse[s]); + logits[s] = contract.rows.sumIn(acc, order, terms[0..p.hidden]) * p.message_scale; + peak = @max(peak, logits[s]); + } + var weights: [2]f64 = undefined; + var den: f64 = 0; + for (0..2) |s| { + weights[s] = @exp(logits[s] - peak); + den += weights[s]; + } + for (0..p.hidden) |d| out[d] = weights[0] / den * (@as(f64, bank0[d]) * inverse[0]) + weights[1] / den * (@as(f64, bank1[d]) * inverse[1]); + } + + fn simGate(h: []const f32, m: []const f32, down: []const f32, forget: []const f32, gain: []const f32, inverse: [2]f64, acc: c.Accum, order: g.Order, terms: []f64, normalized: *[2 * p.hidden]f64, zeta: *[p.rank]f64, out: []f64) void { + for (0..p.hidden) |d| { + normalized[d] = p.roundBf16(@as(f64, h[d]) * inverse[0]); + normalized[p.hidden + d] = p.roundBf16(@as(f64, m[d]) * inverse[1]); + } + for (0..p.rank) |r| { + for (0..2 * p.hidden) |d| terms[d] = @as(f64, down[r * 2 * p.hidden + d]) * normalized[d]; + zeta[r] = p.roundBf16(contract.rows.sumIn(acc, order, terms)); + } + for (0..p.hidden) |d| { + for (0..p.rank) |r| terms[r] = @as(f64, forget[d * p.rank + r]) * zeta[r]; + const fdot = contract.rows.sumIn(acc, order, terms[0..p.rank]); + for (0..p.rank) |r| terms[r] = @as(f64, gain[d * p.rank + r]) * zeta[r]; + const gdot = contract.rows.sumIn(acc, order, terms[0..p.rank]); + out[d] = p.blend(std.math.tanh(fdot), std.math.tanh(gdot), h[d], m[d]); + } + } + + pub fn simulate(self: *Probe, acc: c.Accum, order: g.Order, out: []f64) !void { + const terms = try self.a.alloc(f64, 2 * p.hidden); + defer self.a.free(terms); + switch (self.kind) { + .messages => for (0..self.shape.rows) |row| { + const banks = [2][]const f32{ + self.f[0][row * p.hidden ..][0..p.hidden], + self.f[1][row * p.hidden ..][0..p.hidden], + }; + var inverse: [2]f64 = undefined; + inline for (0..2) |s| inverse[s] = simRms(banks[s], acc, order, terms); + for (0..p.message_entries) |entry| { + const role: p.Role = @fromBackingInt(@intCast(entry % p.roles)); + const dst = out[(row * p.message_entries + entry) * p.hidden ..][0..p.hidden]; + simMessage(banks[0], banks[1], self.f[2], self.f[3], entry / p.roles, role, inverse, acc, order, terms, dst); + } + }, + .gates => { + var normalized: [2 * p.hidden]f64 = undefined; + var zeta: [p.rank]f64 = undefined; + for (0..self.shape.rows) |row| { + const h = self.f[0][row * p.hidden ..][0..p.hidden]; + const m = self.f[1][row * p.hidden ..][0..p.hidden]; + var inverse: [2]f64 = undefined; + inverse[0] = simRms(h, acc, order, terms); + inverse[1] = simRms(m, acc, order, terms); + simGate(h, m, self.f[2], self.f[3], self.f[4], inverse, acc, order, terms, &normalized, &zeta, out[row * p.hidden ..][0..p.hidden]); + } + }, + } + } +}; + +pub const Suite = struct { + a: std.mem.Allocator, + device: mtl.Device, + queue: mtl.Queue, + kernels: *std.ArrayList(g.Kernel), + probes: std.ArrayList(*Probe) = .empty, + + fn add(s: *Suite, kind: p.Kind, control: bool, only: ?[]const u8) !void { + const name = if (control) controls.name(kind) else kind.label(); + if (only) |text| if (std.mem.indexOf(u8, name, text) == null) return; + const probe = try s.a.create(Probe); + errdefer s.a.destroy(probe); + if (control) { + const text = try controls.source(s.a, sources.loop, kind); + defer s.a.free(text); + probe.* = try Probe.initSource(s.a, s.device, s.queue, kind, text); + } else { + probe.* = try Probe.init(s.a, s.device, s.queue, kind); + } + errdefer probe.deinit(); + try s.probes.append(s.a, probe); + var k = probe.kernel(); + if (control) { + k.spec.name = name; + k.control = .shapes; + } + try s.kernels.append(s.a, k); + } + + pub fn collect(s: *Suite, only: ?[]const u8) !void { + for (std.enums.values(p.Kind)) |kind| { + try s.add(kind, false, only); + try s.add(kind, true, only); + } + } + + pub fn deinit(s: *Suite) void { + for (s.probes.items) |probe| { + probe.deinit(); + s.a.destroy(probe); + } + s.probes.deinit(s.a); + } +}; diff --git a/zig/tests/contract/metal_inkling2_loop_controls.zig b/zig/tests/contract/metal_inkling2_loop_controls.zig new file mode 100644 index 00000000000..5464bf58e5d --- /dev/null +++ b/zig/tests/contract/metal_inkling2_loop_controls.zig @@ -0,0 +1,53 @@ +//! One host-checkable arithmetic mutation for each Inkling 2 Mini loop kernel. +const std = @import("std"); +const p = @import("inkling2_loop_plan"); + +const Edit = struct { from: []const u8, to: []const u8 }; +fn edit(kind: p.Kind) Edit { + return switch (kind) { + // Drops the required post-dot binary32(1/48) scale. + .messages => .{ .from = "weights[s] = dot * INKLING_LOOP_SCALE;", .to = "weights[s] = dot;" }, + // Drops the model-dtype rounding between D accumulation and F/Gamma. + .gates => .{ .from = "zeta[t] = float(bfloat(dot));", .to = "zeta[t] = dot;" }, + }; +} + +pub fn source(a: std.mem.Allocator, production: []const u8, kind: p.Kind) ![]u8 { + const e = edit(kind); + if (std.mem.count(u8, production, e.from) != 1) return error.ControlEditMissing; + return std.mem.replaceOwned(u8, a, production, e.from, e.to); +} + +pub fn name(kind: p.Kind) []const u8 { + return switch (kind) { + .messages => "control: metal inkling2 loop messages tf_inkling2_loop_messages", + .gates => "control: metal inkling2 loop gates tf_inkling2_loop_gates", + }; +} + +test "every loop control applies once and changes only its arithmetic anchor" { + const production = @import("inkling2_metal").loop; + const a = std.testing.allocator; + for (std.enums.values(p.Kind)) |kind| { + const e = edit(kind); + try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, production, e.from)); + const changed = try source(a, production, kind); + defer a.free(changed); + const at = std.mem.indexOf(u8, production, e.from).?; + try std.testing.expectEqualStrings(production[0..at], changed[0..at]); + try std.testing.expectEqualStrings(e.to, changed[at..][0..e.to.len]); + try std.testing.expectEqualStrings(production[at + e.from.len ..], changed[at + e.to.len ..]); + try std.testing.expectError(error.ControlEditMissing, source(a, changed, kind)); + try std.testing.expectError(error.ControlEditMissing, source(a, "", kind)); + } +} + +test "a repeated loop control anchor is ambiguous and refuses to prove a fault" { + const a = std.testing.allocator; + const production = @import("inkling2_metal").loop; + for (std.enums.values(p.Kind)) |kind| { + const twice = try std.mem.concat(a, u8, &.{ production, production }); + defer a.free(twice); + try std.testing.expectError(error.ControlEditMissing, source(a, twice, kind)); + } +} diff --git a/zig/tests/contract/metal_inkling2_main.zig b/zig/tests/contract/metal_inkling2_main.zig new file mode 100644 index 00000000000..57f7558ce6d --- /dev/null +++ b/zig/tests/contract/metal_inkling2_main.zig @@ -0,0 +1,41 @@ +//! Inkling 2 Mini Metal suites and the lifetimes of their contract probes. +const std = @import("std"); +const mtl = @import("metal"); +const g = @import("contract").gates; + +pub const Suites = struct { + attention: @import("metal_inkling2_attention.zig").Suite, + glue: @import("metal_inkling2_glue.zig").Suite, + experts: @import("metal_inkling2_experts.zig").Suite, + loop: @import("metal_inkling2_loop.zig").Suite, + runtime: @import("metal_inkling2_runtime.zig").Suite, + dspark: @import("metal_inkling2_dspark.zig").Suite, + + pub fn create(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, kernels: *std.ArrayList(g.Kernel), only: ?[]const u8) !Suites { + var s = Suites{ + .attention = .{ .a = a, .device = device, .queue = queue, .kernels = kernels }, + .glue = .{ .a = a, .device = device, .queue = queue, .kernels = kernels }, + .experts = .{ .a = a, .device = device, .queue = queue, .kernels = kernels }, + .loop = .{ .a = a, .device = device, .queue = queue, .kernels = kernels }, + .runtime = .{ .a = a, .device = device, .queue = queue, .kernels = kernels }, + .dspark = .{ .a = a, .device = device, .queue = queue, .kernels = kernels }, + }; + errdefer s.deinit(); + try s.attention.collect(only); + try s.glue.collect(only); + try s.experts.collect(only); + try s.loop.collect(only); + try s.runtime.collect(only); + try s.dspark.collect(only); + return s; + } + + pub fn deinit(s: *Suites) void { + s.attention.deinit(); + s.glue.deinit(); + s.experts.deinit(); + s.loop.deinit(); + s.runtime.deinit(); + s.dspark.deinit(); + } +}; diff --git a/zig/tests/contract/metal_inkling2_runtime.zig b/zig/tests/contract/metal_inkling2_runtime.zig new file mode 100644 index 00000000000..5f0fc8ddefd --- /dev/null +++ b/zig/tests/contract/metal_inkling2_runtime.zig @@ -0,0 +1,290 @@ +//! Inkling 2 Mini runtime helpers under FP64 references, guarded buffers and exact ABI launches. +const std = @import("std"); +const mtl = @import("metal"); +const controls = @import("metal_inkling2_runtime_controls.zig"); +const contract = @import("contract"); +const c = contract.spec; +const g = contract.gates; +const rig_ = @import("rig.zig"); +const p = @import("inkling2_runtime_plan"); +const sources = @import("inkling2_metal"); + +fn depth(_: c.Shape) usize { + return 1; +} +fn value(rng: std.Random) f32 { + return rng.float(f32) * 0.5 - 0.25; +} +fn round(values: []f32) void { + for (values) |*v| v.* = c.fromBf16(c.toBf16(v.*)); +} + +pub const Probe = struct { + a: std.mem.Allocator, + arena: std.heap.ArenaAllocator, + rig: rig_.Rig, + kind: p.Kind, + pipe: mtl.Pipeline, + shape: c.Shape = undefined, + served: [5]c.Shape = undefined, + f: [2][]f32 = @splat(&.{}), + refs: [2]rig_.Ref = undefined, + blocks: rig_.Ref = undefined, + blocks_before: []u16 = &.{}, + out: rig_.Ref = undefined, + + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, kind: p.Kind) !Probe { + return initSource(a, device, queue, kind, sources.runtime); + } + pub fn initSource(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, kind: p.Kind, text: []const u8) !Probe { + var self: Probe = .{ + .a = a, + .arena = .init(a), + .rig = .{ .a = a, .device = device, .queue = queue }, + .kind = kind, + .pipe = undefined, + }; + errdefer self.arena.deinit(); + self.pipe = try rig_.pipeline(device, text, kind.symbol()); + self.served = switch (kind) { + .attention_partial => .{ + .{ .rows = 1, .n = p.hidden, .k = 0 }, + .{ .rows = 5, .n = p.hidden, .k = 1 }, + .{ .rows = 3, .n = p.hidden, .k = 2 }, + .{ .rows = 2, .n = p.hidden, .k = 3 }, + .{ .rows = 7, .n = p.hidden, .k = 4 }, + }, + .copy_bf16, .copy_f32 => .{ + .{ .rows = 1, .n = p.hidden, .k = 1 }, + .{ .rows = 5, .n = 1024, .k = 1 }, + .{ .rows = 7, .n = p.hidden, .k = 1 }, + .{ .rows = 16, .n = 1024, .k = 1 }, + .{ .rows = 32, .n = p.hidden, .k = 1 }, + }, + .capture_tap => .{ + .{ .rows = 1, .n = p.hidden, .k = 0 }, + .{ .rows = 5, .n = p.hidden, .k = 1 }, + .{ .rows = 7, .n = p.hidden, .k = 2 }, + .{ .rows = 16, .n = p.hidden, .k = 3 }, + .{ .rows = 32, .n = p.hidden, .k = 3 }, + }, + else => .{ + .{ .rows = 1, .n = p.hidden, .k = 1 }, + .{ .rows = 5, .n = p.hidden, .k = 1 }, + .{ .rows = 7, .n = p.hidden, .k = 1 }, + .{ .rows = 16, .n = p.hidden, .k = 1 }, + .{ .rows = 32, .n = p.hidden, .k = 1 }, + }, + }; + return self; + } + pub fn deinit(self: *Probe) void { + self.pipe.deinit(); + self.rig.deinit(); + self.arena.deinit(); + } + + const vt_plain = blk: { + var vt = g.hooks(Probe); + vt.check = null; + break :blk vt; + }; + const vt_checked = g.hooks(Probe); + pub fn kernel(self: *Probe) g.Kernel { + return .{ .ctx = self, .vt = if (self.kind == .attention_partial) &vt_checked else &vt_plain, .spec = .{ + .name = self.kind.label(), + .accum = .none, + .depth = depth, + .ops = if (self.kind == .attention_partial or self.kind == .mlp_partial) 1 else 0, + .out = switch (self.kind) { + .copy_bf16, .mlp_partial, .capture_tap => .bf16, + .copy_f32, .widen, .attention_partial => .f32, + }, + .served = &self.served, + .sums = .{ .f16 = 0, .bf16 = 0, .why = "pointwise moves and single additions have no reduction accumulator to discriminate" }, + } }; + } + pub fn count(self: *Probe) usize { + return p.outputCount(self.kind, .{ .rows = self.shape.rows, .n = self.shape.n, .k = self.shape.k }); + } + + fn floats(self: *Probe, n: usize, rng: std.Random) ![]f32 { + const values = try self.arena.allocator().alloc(f32, n); + for (values) |*v| v.* = value(rng); + return values; + } + fn input(self: *Probe, values: []const f32, bf: bool) !rig_.Ref { + if (!bf) return self.rig.input(std.mem.sliceAsBytes(values)); + const bits = try self.arena.allocator().alloc(u16, values.len); + for (bits, values) |*b, v| b.* = c.toBf16(v); + return self.rig.input(std.mem.sliceAsBytes(bits)); + } + pub fn prepare(self: *Probe, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + const call = p.Call{ .rows = shape.rows, .n = shape.n, .k = shape.k }; + if (!p.valid(self.kind, call)) return false; + self.rig.reset(); + _ = self.arena.reset(.retain_capacity); + self.shape = shape; + self.f = @splat(&.{}); + self.blocks_before = &.{}; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + const n = shape.rows * shape.n; + self.f[0] = try self.floats(n, rng); + switch (self.kind) { + .copy_bf16, .widen, .capture_tap => round(self.f[0]), + .attention_partial => { + self.f[1] = try self.floats(n, rng); + round(self.f[0]); + round(self.f[1]); + const blocks = try self.arena.allocator().alloc(u16, shape.rows * p.block_slots * p.hidden); + for (blocks) |*b| b.* = c.toBf16(value(rng)); + self.blocks_before = blocks; + self.blocks = try self.rig.scratch(std.mem.sliceAsBytes(blocks).len); + @memcpy(self.rig.bytes(self.blocks, std.mem.sliceAsBytes(blocks).len), std.mem.sliceAsBytes(blocks)); + self.refs[1] = try self.input(self.f[1], true); + }, + .mlp_partial => { + self.f[1] = try self.floats(n, rng); + round(self.f[1]); + self.refs[1] = try self.input(self.f[1], true); + }, + .copy_f32 => {}, + } + if (fill == .nonfinite) self.f[0][0] = std.math.nan(f32); + self.refs[0] = try self.input(self.f[0], self.kind == .copy_bf16 or self.kind == .widen or self.kind == .attention_partial or self.kind == .capture_tap); + const elem: c.Elem = switch (self.kind) { + .copy_bf16, .mlp_partial, .capture_tap => .bf16, + .copy_f32, .widen, .attention_partial => .f32, + }; + self.out = try self.rig.output(self.count() * c.size(elem)); + if (self.kind == .capture_tap) { + const untouched = std.mem.bytesAsSlice(u16, self.rig.bytes(self.out, self.count() * 2)); + @memset(untouched, c.toBf16(1)); + } + return true; + } + + pub fn run(self: *Probe) !void { + const pass = self.rig.begin(); + const e = pass.e; + e.setPipeline(self.pipe); + e.setBuffer(self.refs[0].buf, self.refs[0].off, 0); + switch (self.kind) { + .copy_bf16, .copy_f32, .widen, .capture_tap => { + e.setBuffer(self.out.buf, self.out.off, 1); + e.setValue(p.args(self.kind, .{ .rows = self.shape.rows, .n = self.shape.n, .k = self.shape.k }), 2); + }, + .attention_partial => { + e.setBuffer(self.refs[1].buf, self.refs[1].off, 1); + e.setBuffer(self.blocks.buf, self.blocks.off, 2); + e.setBuffer(self.out.buf, self.out.off, 3); + e.setValue(p.args(self.kind, .{ .rows = self.shape.rows, .n = self.shape.n, .k = self.shape.k }), 4); + }, + .mlp_partial => { + e.setBuffer(self.refs[1].buf, self.refs[1].off, 1); + e.setBuffer(self.out.buf, self.out.off, 2); + e.setValue(p.args(self.kind, .{ .rows = self.shape.rows, .n = self.shape.n, .k = self.shape.k }), 3); + }, + } + e.dispatchThreads(mtl.Size.of(p.geometry(.{ .rows = self.shape.rows, .n = self.shape.n, .k = self.shape.k }).count, 1, 1), mtl.Size.of(p.threads, 1, 1)); + try self.rig.finish(pass); + } + + pub fn reference(self: *Probe, want: []f64, mag: []f64) !void { + if (self.kind == .capture_tap) { + for (want, mag, 0..) |*w, *m, i| { + const row = i / (p.tap_channels * p.hidden); + const channel = (i / p.hidden) % p.tap_channels; + const x = self.f[0][row * p.hidden + i % p.hidden]; + w.* = if (channel == self.shape.k) x else 1; + m.* = @abs(@as(f64, x)); + } + return; + } + for (want, mag, 0..) |*w, *m, i| { + const x = self.f[0][i]; + const y = if (self.f[1].len == 0) 0 else self.f[1][i]; + w.* = switch (self.kind) { + .copy_bf16, .copy_f32, .widen, .capture_tap => x, + .attention_partial => p.attentionPartial(x, y, self.shape.k), + .mlp_partial => p.mlpPartial(x, y), + }; + m.* = @abs(@as(f64, x)) + @abs(@as(f64, y)); + } + } + + pub fn check(self: *Probe, gate: g.Gate) !?[]const u8 { + if (self.kind != .attention_partial or (gate != .shapes and gate != .nonfinite)) return "numeric hooks must be used"; + const want = try self.a.alloc(f64, self.count()); + defer self.a.free(want); + const mag = try self.a.alloc(f64, self.count()); + defer self.a.free(mag); + try self.reference(want, mag); + const bytes = try self.rig.outputBytes(); + var planted: usize = 0; + for (want, 0..) |w, i| { + const got = c.read(.f32, bytes, i); + if (c.classOf(got) != c.classOf(w)) return "partial's floating-point class differs"; + if (c.classOf(w) != .finite) planted += 1; + if (gate == .shapes and std.math.isFinite(w) and got != w) return "FP32 partial differs from the FP64 reference's explicit rounding"; + } + if (gate == .nonfinite and (planted == 0 or planted == want.len)) return "the planted NaN does not discriminate finite and non-finite partials"; + const block_bytes = self.rig.bytes(self.blocks, std.mem.sliceAsBytes(self.blocks_before).len); + const got_blocks = std.mem.bytesAsSlice(u16, block_bytes); + for (0..self.shape.rows) |row| for (0..p.block_slots) |slot| for (0..p.hidden) |d| { + const at = (row * p.block_slots + slot) * p.hidden + d; + const expected = if (self.shape.k != 0 and slot == self.shape.k - 1) + c.toBf16(self.f[0][row * p.hidden + d]) + else + self.blocks_before[at]; + if (got_blocks[at] != expected) return "completed-block row/slot layout differs"; + }; + return null; + } +}; + +pub const Suite = struct { + a: std.mem.Allocator, + device: mtl.Device, + queue: mtl.Queue, + kernels: *std.ArrayList(g.Kernel), + probes: std.ArrayList(*Probe) = .empty, + + fn add(s: *Suite, kind: p.Kind, control: bool, only: ?[]const u8) !void { + const name = if (control) controls.name(kind) else kind.label(); + if (only) |text| if (std.mem.indexOf(u8, name, text) == null) return; + const probe = try s.a.create(Probe); + errdefer s.a.destroy(probe); + if (control) { + const text = try controls.source(s.a, sources.runtime, kind); + defer s.a.free(text); + probe.* = try Probe.initSource(s.a, s.device, s.queue, kind, text); + } else { + probe.* = try Probe.init(s.a, s.device, s.queue, kind); + } + errdefer probe.deinit(); + try s.probes.append(s.a, probe); + var k = probe.kernel(); + if (control) { + k.spec.name = name; + k.control = .shapes; + } + try s.kernels.append(s.a, k); + } + + pub fn collect(s: *Suite, only: ?[]const u8) !void { + for (std.enums.values(p.Kind)) |kind| { + try s.add(kind, false, only); + try s.add(kind, true, only); + } + } + + pub fn deinit(s: *Suite) void { + for (s.probes.items) |probe| { + probe.deinit(); + s.a.destroy(probe); + } + s.probes.deinit(s.a); + } +}; diff --git a/zig/tests/contract/metal_inkling2_runtime_controls.zig b/zig/tests/contract/metal_inkling2_runtime_controls.zig new file mode 100644 index 00000000000..09c1b4526a9 --- /dev/null +++ b/zig/tests/contract/metal_inkling2_runtime_controls.zig @@ -0,0 +1,65 @@ +//! One host-checkable arithmetic or layout mutation for each Inkling 2 Mini runtime helper. +const std = @import("std"); +const p = @import("inkling2_runtime_plan"); + +const Edit = struct { from: []const u8, to: []const u8 }; +fn edit(kind: p.Kind) Edit { + return switch (kind) { + .copy_bf16 => .{ + .from = "kernel void tf_ink2_copy_bf16(const device bfloat* x [[buffer(0)]], device bfloat* y [[buffer(1)]], constant InkRuntimeArgs& a [[buffer(2)]], uint i [[thread_position_in_grid]]) {\n if (i < a.count) y[i] = x[i];", + .to = "kernel void tf_ink2_copy_bf16(const device bfloat* x [[buffer(0)]], device bfloat* y [[buffer(1)]], constant InkRuntimeArgs& a [[buffer(2)]], uint i [[thread_position_in_grid]]) {\n if (i < a.count) y[i] = bfloat(0);", + }, + .copy_f32 => .{ + .from = "kernel void tf_ink2_copy_f32(const device float* x [[buffer(0)]], device float* y [[buffer(1)]], constant InkRuntimeArgs& a [[buffer(2)]], uint i [[thread_position_in_grid]]) {\n if (i < a.count) y[i] = x[i];", + .to = "kernel void tf_ink2_copy_f32(const device float* x [[buffer(0)]], device float* y [[buffer(1)]], constant InkRuntimeArgs& a [[buffer(2)]], uint i [[thread_position_in_grid]]) {\n if (i < a.count) y[i] = 0.0f;", + }, + .widen => .{ .from = "if (i < a.count) y[i] = float(x[i]);", .to = "if (i < a.count) y[i] = 2.0f * float(x[i]);" }, + .attention_partial => .{ .from = "blocks[row * 4 * 2304 + (a.boundary - 1) * 2304 + d] = p[i];", .to = "blocks[row * 2304 + (a.boundary - 1) * 2304 + d] = p[i];" }, + .mlp_partial => .{ .from = "p[i] = bfloat(t[i] + float(x[i]));", .to = "p[i] = bfloat(t[i] - float(x[i]));" }, + .capture_tap => .{ .from = "y[row * 4 * 2304 + a.boundary * 2304 + d] = x[i];", .to = "y[row * 4 * 2304 + ((a.boundary + 1) % 4) * 2304 + d] = x[i];" }, + }; +} + +pub fn source(a: std.mem.Allocator, production: []const u8, kind: p.Kind) ![]u8 { + const e = edit(kind); + if (std.mem.count(u8, production, e.from) != 1) return error.ControlEditMissing; + return std.mem.replaceOwned(u8, a, production, e.from, e.to); +} + +pub fn name(kind: p.Kind) []const u8 { + return switch (kind) { + .copy_bf16 => "control: metal inkling2 runtime copy_bf16 tf_ink2_copy_bf16", + .copy_f32 => "control: metal inkling2 runtime copy_f32 tf_ink2_copy_f32", + .widen => "control: metal inkling2 runtime widen tf_ink2_widen", + .attention_partial => "control: metal inkling2 runtime attention_partial tf_ink2_attention_partial", + .mlp_partial => "control: metal inkling2 runtime mlp_partial tf_ink2_mlp_partial", + .capture_tap => "control: metal inkling2 runtime capture_tap tf_ink2_capture_tap", + }; +} + +test "every runtime control applies once and changes only its discriminating anchor" { + const production = @import("inkling2_metal").runtime; + const a = std.testing.allocator; + for (std.enums.values(p.Kind)) |kind| { + const e = edit(kind); + try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, production, e.from)); + const changed = try source(a, production, kind); + defer a.free(changed); + const at = std.mem.indexOf(u8, production, e.from).?; + try std.testing.expectEqualStrings(production[0..at], changed[0..at]); + try std.testing.expectEqualStrings(e.to, changed[at..][0..e.to.len]); + try std.testing.expectEqualStrings(production[at + e.from.len ..], changed[at + e.to.len ..]); + try std.testing.expectError(error.ControlEditMissing, source(a, changed, kind)); + try std.testing.expectError(error.ControlEditMissing, source(a, "", kind)); + } +} + +test "a repeated runtime control anchor is ambiguous and refuses to prove a fault" { + const production = @import("inkling2_metal").runtime; + const a = std.testing.allocator; + for (std.enums.values(p.Kind)) |kind| { + const twice = try std.mem.concat(a, u8, &.{ production, production }); + defer a.free(twice); + try std.testing.expectError(error.ControlEditMissing, source(a, twice, kind)); + } +} diff --git a/zig/tests/contract/metal_lane_variants.zig b/zig/tests/contract/metal_lane_variants.zig index ec77c168e59..5cffbb937e3 100644 --- a/zig/tests/contract/metal_lane_variants.zig +++ b/zig/tests/contract/metal_lane_variants.zig @@ -7,6 +7,10 @@ pub const m5 = [_]Reg{ .{ .v = .{ .kind = .lane, .bits = 4, .group = 64, .sk = 2 }, .name = "metal lane projection q4 g64 sk2" }, .{ .v = .{ .kind = .lane, .bits = 4, .group = 64, .coop = true }, .name = "metal lane projection q4 g64 cooperative" }, .{ .v = .{ .kind = .lane_reg, .bits = 4, .group = 64 }, .name = "metal lane projection q4 g64 reg" }, + .{ .v = .{ .kind = .lane_reg, .bits = 5, .group = 64 }, .name = "metal lane projection q5 g64 reg" }, + .{ .v = .{ .kind = .lane_reg, .bits = 5, .group = 64, .control = true }, .name = "control: metal lane projection q5 g64 reg, unreordered tiles" }, + .{ .v = .{ .kind = .lane_reg, .bits = 6, .group = 64 }, .name = "metal lane projection q6 g64 reg" }, + .{ .v = .{ .kind = .lane_reg, .bits = 6, .group = 64, .control = true }, .name = "control: metal lane projection q6 g64 reg, unreordered tiles" }, .{ .v = .{ .kind = .lane, .bits = 8, .group = 128, .sk = 4 }, .name = "metal lane projection q8 g128 sk4" }, } ++ q8 ++ hy4; diff --git a/zig/tests/contract/metal_limits.zig b/zig/tests/contract/metal_limits.zig index 109e6cde919..8b4fbe697b8 100644 --- a/zig/tests/contract/metal_limits.zig +++ b/zig/tests/contract/metal_limits.zig @@ -34,7 +34,7 @@ fn boltSource(name: []const u8) ![]const u8 { } /// Each registration's function is its label's last word; the label's words say which source it compiles. -fn launchOf(a: std.mem.Allocator, device: mtl.Device, d: limits.MetalLaunch) !Launch { +pub fn launchOf(a: std.mem.Allocator, device: mtl.Device, d: limits.MetalLaunch) !Launch { return resolve(a, device, d, true); } @@ -52,6 +52,8 @@ pub fn supported(device: mtl.Device, d: limits.MetalLaunch) bool { return @import("metal_support.zig").tensor(device.tensorUnits(), d.name); if (@import("metal_dsv41_limits.zig").tensorOnly(d.name)) return @import("metal_support.zig").tensor(device.tensorUnits(), d.name); + if (std.mem.startsWith(u8, d.name, "lane projection ") and std.mem.indexOf(u8, d.name, " reg ") != null) + return @import("metal_support.zig").tensor(device.tensorUnits(), d.name); return !std.mem.startsWith(u8, d.name, "qwen27 q8 ") or @import("metal_support.zig").tensor(device.tensorUnits(), d.name); } @@ -212,6 +214,25 @@ fn resolve(a: std.mem.Allocator, device: mtl.Device, d: limits.MetalLaunch, comp const t = try @import("metal_flint.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, "metal inkling2 ")) { + if (!assemble) return undefined; + const body = if (std.mem.startsWith(u8, d.name, "metal inkling2 dspark ")) + @import("inkling2_metal").inkling2_dspark + else if (std.mem.startsWith(u8, d.name, "metal inkling2 runtime ")) + @import("inkling2_metal").runtime + else if (std.mem.startsWith(u8, d.name, "metal inkling2 loop ")) + @import("inkling2_metal").loop + else if (std.mem.startsWith(u8, d.name, "metal inkling2 experts ")) + @import("inkling2_metal").experts + else if (std.mem.startsWith(u8, d.name, "metal inkling2 glue ")) + @import("inkling2_metal").glue + else if (std.mem.startsWith(u8, d.name, "metal inkling2 prompt ")) + @import("inkling2_metal").prompt_attention + else + @import("inkling2_metal").attention; + const pre_m5 = if (std.mem.startsWith(u8, d.name, "metal inkling2 prompt ")) @import("inkling2_metal").prompt_attention_pre_m5 else body; + return .{ .decl = d, .function = fun, .here = body, .pre_m5 = pre_m5 }; + } if (std.mem.startsWith(u8, d.name, "lfm2 masked prompt ")) { if (!assemble) return undefined; const body = try tf.lfm2_moe.source.prompt(device, a, true); @@ -414,10 +435,16 @@ fn resolve(a: std.mem.Allocator, device: mtl.Device, d: limits.MetalLaunch, comp break :blk try std.mem.concat(a, u8, &.{ full_head, body }); } else pre; return .{ .decl = d, .function = fun, .here = here, .pre_m5 = pre }; + } else if (std.mem.startsWith(u8, d.name, "lane order ")) { + if (!assemble) return undefined; + return .{ .decl = d, .function = fun, .here = sources.core_lane_order, .pre_m5 = sources.core_lane_order }; } else if (has(d.name, "lane projection")) { if (!assemble) return undefined; - const sk: usize = if (has(d.name, "sk4")) 4 else 1; - const full = try tf.lane_projection.source(a, .{ .n = 2048, .k = 2048, .format = .{ .bits = 6, .group = 32 }, .sk = sk }); + const reg = has(d.name, " reg "); + const bits: u8 = if (has(d.name, "q5")) 5 else 6; + const group: usize = if (reg) 64 else 32; + const sk: usize = if (has(d.name, "sk8")) 8 else if (has(d.name, "sk4")) 4 else 1; + const full = try tf.lane_projection.source(a, .{ .n = 2048, .k = 2048, .format = .{ .bits = bits, .group = group }, .sk = sk, .precompute_sums = reg, .reg = reg }); head = full[0..std.mem.indexOf(u8, full, sources.core_lane_projection[0..64]).?]; text = sources.core_lane_projection; frags = true; diff --git a/zig/tests/contract/metal_main.zig b/zig/tests/contract/metal_main.zig index afdbea351fe..2e38359f288 100644 --- a/zig/tests/contract/metal_main.zig +++ b/zig/tests/contract/metal_main.zig @@ -356,6 +356,8 @@ pub fn main(init: std.process.Init) !u8 { var ling_mla_set = ling_mla.Suite{ .a = a, .device = device, .queue = queue }; defer ling_mla_set.deinit(); try ling_mla_set.collect(&kernels, o.only); + var inkling2_suites = try @import("metal_inkling2_main.zig").Suites.create(a, device, queue, &kernels, o.only); + defer inkling2_suites.deinit(); for ([_][]const Reg{ &common, if (tensor) &m5_only else &.{} }) |list| for (list) |v| { if (!wanted(o, v.name)) continue; const p = try a.create(affine_k.Proj); diff --git a/zig/tests/contract/metal_mapping_test.zig b/zig/tests/contract/metal_mapping_test.zig index aedf4e04e08..7ef293a5dcf 100644 --- a/zig/tests/contract/metal_mapping_test.zig +++ b/zig/tests/contract/metal_mapping_test.zig @@ -15,6 +15,16 @@ test "Metal launch map: every registered launch and control has a resolver branc try std.testing.expectEqual(@as(usize, 0), missing); } +test "Metal launch map: every DSpark limit pipeline has a resolver branch" { + var count: usize = 0; + for (registry.all_metal) |d| { + if (!std.mem.startsWith(u8, d.name, "metal inkling2 dspark ")) continue; + try launches.requireMapped(d); + count += 1; + } + try std.testing.expectEqual(@as(usize, 11), count); +} + test "Metal launch map: unknown registrations stay errors on every chip" { try std.testing.expectError(error.UnknownLaunch, launches.requireMapped(.{ .name = "unregistered family missing_kernel", .threads = 32, .tg_memory = 0 })); } diff --git a/zig/tests/contract/metal_q27_attn.zig b/zig/tests/contract/metal_q27_attn.zig index f5649ac014a..7b27a72cff2 100644 --- a/zig/tests/contract/metal_q27_attn.zig +++ b/zig/tests/contract/metal_q27_attn.zig @@ -12,8 +12,8 @@ const planning = q.attention_plan; const D = 256; -/// Geometry.check's shapes: the 27B (24 over 4), its two-Mac rank (12 over 2), GQA16 (32 over 2), the 9B (16 over 4). -pub const Heads = enum { q27b, rank, gqa16, q9b }; +/// Geometry.check's shapes: the 27B (24/4), its two-Mac rank (12/2), GQA16 (32/2), the 9B (16/4), the 35B-A3B (16/2). +pub const Heads = enum { q27b, rank, gqa16, q9b, q35b }; pub fn geometry(h: Heads, shared: bool) planning.Geometry { return switch (h) { @@ -21,6 +21,7 @@ pub fn geometry(h: Heads, shared: bool) planning.Geometry { .rank => .{ .heads = 12, .kv_heads = 2, .shared_prefix = shared }, .gqa16 => .{ .heads = 32, .kv_heads = 2, .shared_prefix = shared }, .q9b => .{ .heads = 16, .kv_heads = 4, .shared_prefix = shared }, + .q35b => .{ .heads = 16, .kv_heads = 2, .shared_prefix = shared }, }; } @@ -30,6 +31,7 @@ pub fn label(h: Heads) []const u8 { .rank => "27B rank", .gqa16 => "GQA16", .q9b => "9B", + .q35b => "35B-A3B", }; } diff --git a/zig/tests/contract/metal_q27_attn_rows.zig b/zig/tests/contract/metal_q27_attn_rows.zig index 613f4470db1..5ba3f49c74e 100644 --- a/zig/tests/contract/metal_q27_attn_rows.zig +++ b/zig/tests/contract/metal_q27_attn_rows.zig @@ -19,7 +19,7 @@ const u = 0x1p-24; const scale = 0.0625; /// One Mac's head counts (a rank's 12 over 2 merges as a pair, so its rows are not one call's). -pub const heads = [_]at_.Heads{ .q27b, .gqa16, .q9b }; +pub const heads = [_]at_.Heads{ .q27b, .gqa16, .q9b, .q35b }; /// decode: a round's trees and chains as decode_round.zig plans them; prompt: one chain through the prompt kernel. pub const Which = enum { decode, prompt }; diff --git a/zig/tests/contract/metal_qwen27_moe.zig b/zig/tests/contract/metal_qwen27_moe.zig index 895c7dba3b4..c3b5d54b597 100644 --- a/zig/tests/contract/metal_qwen27_moe.zig +++ b/zig/tests/contract/metal_qwen27_moe.zig @@ -78,8 +78,8 @@ pub const Extra = struct { .depth = rowDepth, .out = .bf16, .tiles = .{ .{ .size = 2 }, .{ .size = 8, .step = 8, .min = 8 }, .{ .size = 512, .step = 64, .min = 64 } }, - // Ornith's decode windows: gate and up (1,024 over 3,072), down (3,072 over 1,024) - .served = &.{ .{ .rows = 16, .n = 1024, .k = 3072 }, .{ .rows = 1, .n = 3072, .k = 1024 } }, + // decode windows: Ornith's gate and up (1,024 over 3,072) and down, then the 35B-A3B's (512 over 2,048) + .served = &.{ .{ .rows = 16, .n = 1024, .k = 3072 }, .{ .rows = 1, .n = 3072, .k = 1024 }, .{ .rows = 16, .n = 512, .k = 2048 }, .{ .rows = 1, .n = 2048, .k = 512 } }, }; } diff --git a/zig/tests/contract/metal_qwen27_moe_rows.zig b/zig/tests/contract/metal_qwen27_moe_rows.zig index ab460e0f0ae..c2487e5e572 100644 --- a/zig/tests/contract/metal_qwen27_moe_rows.zig +++ b/zig/tests/contract/metal_qwen27_moe_rows.zig @@ -174,7 +174,8 @@ pub const Gather = struct { .out = .raw, .nan = .{ .stated = "each sorted slot's row is its token's input row, bit for bit" }, .tiles = .{ .{ .size = 8, .step = 8, .min = 8 }, .{ .size = 256, .step = 64, .min = 64 }, .{} }, - .served = &.{ .{ .rows = 8192, .n = 3072, .k = 1 }, .{ .rows = 128, .n = 3072, .k = 1 }, .{ .rows = 8, .n = 3072, .k = 1 } }, + // Ornith's hidden width, then the 35B-A3B's + .served = &.{ .{ .rows = 8192, .n = 3072, .k = 1 }, .{ .rows = 128, .n = 3072, .k = 1 }, .{ .rows = 8, .n = 3072, .k = 1 }, .{ .rows = 8192, .n = 2048, .k = 1 }, .{ .rows = 8, .n = 2048, .k = 1 } }, }; } @@ -266,7 +267,8 @@ pub const Glu = struct { .ops = 12, .out = .bf16, .tiles = .{ .{ .size = 1 }, .{ .size = 256, .step = 1, .min = 1 }, .{} }, - .served = &.{ .{ .rows = 9216, .n = 1024, .k = 1 }, .{ .rows = 144, .n = 1024, .k = 1 }, .{ .rows = 9, .n = 1024, .k = 1 } }, + // Ornith's experts' width, then the 35B-A3B's + .served = &.{ .{ .rows = 9216, .n = 1024, .k = 1 }, .{ .rows = 144, .n = 1024, .k = 1 }, .{ .rows = 9, .n = 1024, .k = 1 }, .{ .rows = 9216, .n = 512, .k = 1 }, .{ .rows = 9, .n = 512, .k = 1 } }, }; } @@ -364,7 +366,8 @@ pub const Combine = struct { .out = .bf16, .in_place = in_out, .tiles = .{ .{ .size = 1 }, .{ .size = 256, .step = 1, .min = 1 }, .{} }, - .served = &.{ .{ .rows = 16, .n = 3072, .k = route_topk }, .{ .rows = 1, .n = 3072, .k = route_topk }, .{ .rows = 1024, .n = 3072, .k = route_topk } }, + // Ornith's hidden width, then the 35B-A3B's + .served = &.{ .{ .rows = 16, .n = 3072, .k = route_topk }, .{ .rows = 1, .n = 3072, .k = route_topk }, .{ .rows = 1024, .n = 3072, .k = route_topk }, .{ .rows = 16, .n = 2048, .k = route_topk }, .{ .rows = 1024, .n = 2048, .k = route_topk } }, }; } diff --git a/zig/tests/cuda/contract_drama3.zig b/zig/tests/cuda/contract_drama3.zig index f1ab6e3eb27..f70f03512a7 100644 --- a/zig/tests/cuda/contract_drama3.zig +++ b/zig/tests/cuda/contract_drama3.zig @@ -1,4 +1,4 @@ -//! Drama 3's kernels under the CUDA contract: RMS norm rows (d3_rmsnorm), the compact router and the CFG mix. +//! Drama 3 under the CUDA contract: RMS norm rows (plain gamma and gated form), compact router and CFG mix. const std = @import("std"); const cuda = @import("cuda"); const core = @import("core"); @@ -99,17 +99,18 @@ pub fn mixSpec() c.Spec { return .{ .name = "cuda drama3 d3_cfg_mix (semantic CFG, gamma 2.5)", .accum = .none, .depth = noSums, .out = .f32, .tiles = .{ .{}, .{ .size = 256 }, .{} }, .served = &.{.{ .rows = 1, .n = 4097, .k = 1 }} }; } -/// d3_cfg_mix updates the conditional logits in place: each run starts from a fresh copy of them. +/// d3_cfg_mix mixes in place from a fresh copy each run; the control passes gamma - 1 (cond + gamma * (cond - uncond)). pub const Mix = struct { rig: rig_.Rig, f: cuda.Function, + control: bool = false, cond: []f32 = &.{}, uncond: []f32 = &.{}, u: u64 = 0, out: u64 = 0, - pub fn init(gpu: check.Gpu, s: cuda.Stream, mod: cuda.Module) !Mix { - return .{ .rig = .{ .gpu = gpu, .s = s }, .f = try mod.function("d3_cfg_mix") }; + pub fn init(gpu: check.Gpu, s: cuda.Stream, mod: cuda.Module, control: bool) !Mix { + return .{ .rig = .{ .gpu = gpu, .s = s }, .f = try mod.function("d3_cfg_mix"), .control = control }; } pub fn deinit(self: *Mix) void { @@ -125,13 +126,14 @@ pub const Mix = struct { } pub fn kernel(self: *Mix) g.Kernel { - return .{ .spec = mixSpec(), .ctx = self, .vt = &mix_vt }; + var k: g.Kernel = .{ .spec = mixSpec(), .ctx = self, .vt = &mix_vt, .control = if (self.control) .shapes else null }; + if (self.control) k.spec.name = "cuda drama3 d3_cfg_mix control: launched with gamma - 1"; + return k; } const mix_vt = g.hooks(Mix); pub fn prepare(self: *Mix, shape: c.Shape, fill: g.Fill, seed: u64) !bool { - if (shape.rows != 1) return false; self.free(); self.rig.reset(); const a = self.rig.gpu.gpa; @@ -164,7 +166,7 @@ pub const Mix = struct { a.add(self.out); a.add(self.u); a.add(@as(c_int, @intCast(n))); - a.add(mix_gamma); + a.add(if (self.control) mix_gamma - 1 else mix_gamma); try cuda.launch.launch(self.f, .{ .grid = .{ .x = @intCast((n + 255) / 256), .y = 1, .z = 1 }, .block = .{ .x = 256 } }, self.rig.s, &a); try self.rig.s.synchronize(); } @@ -187,13 +189,13 @@ pub const Mix = struct { } }; -/// The drama3 image, its norm, its compact router with the unmasked control and its CFG mix, appended to `kernels`. +/// The drama3 image's registrations onto `kernels`: norm rows, then compact router and CFG mix each with its control. pub const Group = struct { a: std.mem.Allocator, mod: cuda.Module, norm: Norm, routers: [2]router_k.Router, - mix: Mix, + mixes: [2]Mix, pub fn create(a: std.mem.Allocator, gpu: check.Gpu, s: cuda.Stream, kernels: *std.ArrayList(g.Kernel)) !*Group { const self = try a.create(Group); @@ -202,18 +204,18 @@ pub const Group = struct { self.mod = try cuda.Module.load(gpu.d, cuda.kernels.drama3); errdefer self.mod.unload(); self.norm = try Norm.init(gpu, s, self.mod); + self.mixes = .{ try .init(gpu, s, self.mod, false), try .init(gpu, s, self.mod, true) }; self.routers = .{ try .init(gpu, s, self.mod, false), try .init(gpu, s, self.mod, true) }; - self.mix = try Mix.init(gpu, s, self.mod); try kernels.append(a, self.norm.kernel()); for (&self.routers) |*r| try kernels.append(a, r.kernel()); - try kernels.append(a, self.mix.kernel()); + for (&self.mixes) |*m| try kernels.append(a, m.kernel()); return self; } pub fn destroy(self: *Group) void { self.norm.deinit(); for (&self.routers) |*r| r.deinit(); - self.mix.deinit(); + for (&self.mixes) |*m| m.deinit(); self.mod.unload(); self.a.destroy(self); } diff --git a/zig/tests/cuda/contract_flashnext_glue.zig b/zig/tests/cuda/contract_flashnext_glue.zig index 39943562a30..8210331f3a9 100644 --- a/zig/tests/cuda/contract_flashnext_glue.zig +++ b/zig/tests/cuda/contract_flashnext_glue.zig @@ -45,10 +45,19 @@ const prompt_served = [_]c.Shape{ .{ .rows = parts.max_chunk, .n = nv * dv, .k = dk }, }; +/// The existing dispatch seams and chunk limits stay first; KR15's ordinary short-row cells follow. +const chain_served = prompt_served ++ [_]c.Shape{ + .{ .rows = 1, .n = nv * dv, .k = dk }, + .{ .rows = 4, .n = nv * dv, .k = dk }, + .{ .rows = 8, .n = nv * dv, .k = dk }, + .{ .rows = 16, .n = nv * dv, .k = dk }, + .{ .rows = 32, .n = nv * dv, .k = dk }, +}; + /// rows = token rows; n = outputs a row (value heads x width, pooled blocks, or the read-out's mixed dims). pub fn spec(kind: Kind) c.Spec { return switch (kind) { - .chain => .{ .name = "cuda flashnext DeltaNet prompt chain fn_gdn_chain_tpr", .accum = .none, .depth = noSums, .out = .raw, .nan = .{ .stated = "ys and the state bit-equal to fn_gdn_rows_to's, non-finite inputs included" }, .replaces = "fn_gdn_rows_to", .tiles = .{ .{ .size = 16 }, .{}, .{} }, .served = &prompt_served }, + .chain => .{ .name = "cuda flashnext DeltaNet prompt chain fn_gdn_chain_tpr", .accum = .none, .depth = noSums, .out = .raw, .nan = .{ .stated = "ys and the state bit-equal to fn_gdn_rows_to's, non-finite inputs included" }, .replaces = "fn_gdn_rows_to", .tiles = .{ .{ .size = 16 }, .{}, .{} }, .served = &chain_served }, .scores => .{ .name = "cuda flashnext indexer scores qsa_tile::scores<8, 4>", .accum = .none, .depth = noSums, .out = .raw, .nan = .{ .stated = "every score byte equal to fn_qsa_scores', non-finite inputs included" }, .replaces = "fn_qsa_scores", .tiles = .{ .{ .size = 8 }, .{ .size = 256, .step = 1, .min = 1 }, .{} }, .served = &.{ .{ .rows = 64, .n = 600, .k = di }, .{ .rows = 300, .n = 2100, .k = di } } }, .fused => .{ .name = "cuda flashnext DeltaNet prompt block fn_gdn_fused (front, chain, gated norm)", .accum = .none, .depth = noSums, .out = .raw, .nan = .{ .stated = "gated-norm rows, xs, the state, the readouts and on even row counts two cache marks' kept states bit-equal to fn_gdn_front -> fn_gdn_rows_to -> fn_gdn_norm (rows_to over each mark's rows), non-finite inputs included" }, .replaces = "fn_gdn_front, fn_gdn_chain_tpr and fn_gdn_norm", .tiles = .{ .{ .size = 16 }, .{}, .{} }, .in_place = true, .served = &prompt_served }, .readout => .{ .name = "cuda flashnext hyper-connection read-out on prompt tiles (hcf down, reduce, hcf up, rinv, mix_h)", .accum = .none, .depth = noSums, .out = .raw, .nan = .{ .stated = "act, xs, inj, mixed and xsm bit-equal to #952's chain, non-finite inputs included" }, .replaces = "fn_hc_down, fn_hc_reduce_act and fn_hc_upmix", .tiles = .{ .{ .size = 64 }, .{}, .{} }, .served = &.{ .{ .rows = 64, .n = dims, .k = wide }, .{ .rows = 130, .n = dims, .k = wide } } }, diff --git a/zig/tests/cuda/contract_flashnext_glue_test.zig b/zig/tests/cuda/contract_flashnext_glue_test.zig index f3bd7cea5e8..7ac2f3e5dd4 100644 --- a/zig/tests/cuda/contract_flashnext_glue_test.zig +++ b/zig/tests/cuda/contract_flashnext_glue_test.zig @@ -26,6 +26,35 @@ test "the flashnext prompt specs serve the admitted row range with the dispatch } } +test "KR15 TPR contracts serve every short row on full heads and both TP=2 ranks" { + for ([_]usize{ 1, 4, 8, 16, 32 }) |rows| { + var full = false; + for (glue.spec(.chain).served) |x| if (x.rows == rows and x.n == lay.Heads.full.valueDim()) { + full = true; + }; + try std.testing.expect(full); + for (0..2) |rank| { + var half = false; + for (heads.spec(.tpr, rank).served) |x| if (x.rows == rows and x.n == lay.Heads.half.valueDim()) { + half = true; + }; + try std.testing.expect(half); + } + } +} + +test "ordinary GDN dispatch opts into TPR only below 64 rows and keeps rollback selection" { + for ([_]usize{ 1, 4, 8, 16, 32, 63 }) |rows| { + try std.testing.expectEqual(flash.gdn.ChainForm.chain, flash.gdn.chainForm(rows, 0, false)); + try std.testing.expectEqual(flash.gdn.ChainForm.chain_to, flash.gdn.chainForm(rows, 1, false)); + try std.testing.expectEqual(flash.gdn.ChainForm.chain_tpr, flash.gdn.chainForm(rows, 0, true)); + try std.testing.expectEqual(flash.gdn.ChainForm.chain_tpr, flash.gdn.chainForm(rows, 1, true)); + } + for ([_]usize{ 64, 65, 1536 }) |rows| for ([_]u64{ 0, 1 }) |state_out| for ([_]bool{ false, true }) |enabled| { + try std.testing.expectEqual(flash.gdn.ChainForm.chain_tpr, flash.gdn.chainForm(rows, state_out, enabled)); + }; +} + test "the fused block declares the state alias and binds one buffer for it" { try std.testing.expect(glue.spec(.fused).in_place); try std.testing.expect(!glue.spec(.chain).in_place); // the chain's kernel marks its state input __restrict__ diff --git a/zig/tests/cuda/contract_flashnext_heads.zig b/zig/tests/cuda/contract_flashnext_heads.zig index b4dcd0a889f..c276327f62c 100644 --- a/zig/tests/cuda/contract_flashnext_heads.zig +++ b/zig/tests/cuda/contract_flashnext_heads.zig @@ -26,6 +26,15 @@ const half_served = [_]c.Shape{ .{ .rows = parts.max_chunk, .n = Heads.half.nv * dv, .k = dk }, }; +/// KR15's rank-local TPR cells mirror every full-head short-row shape at TP=2. +const tpr_served = half_served ++ [_]c.Shape{ + .{ .rows = 1, .n = Heads.half.nv * dv, .k = dk }, + .{ .rows = 4, .n = Heads.half.nv * dv, .k = dk }, + .{ .rows = 8, .n = Heads.half.nv * dv, .k = dk }, + .{ .rows = 16, .n = Heads.half.nv * dv, .k = dk }, + .{ .rows = 32, .n = Heads.half.nv * dv, .k = dk }, +}; + const ranks = 2; const names = blk: { @@ -44,7 +53,7 @@ const originals = blk: { /// rows = token rows; n = the candidate's value heads x dv; k = dk. pub fn spec(kind: Kind, rank: usize) c.Spec { - return .{ .name = names[@backingInt(kind)][rank], .accum = .none, .depth = noSums, .out = .raw, .nan = .{ .stated = "every output byte, the state's included, equal to the full kernel's on these heads, non-finite inputs included" }, .replaces = originals[@backingInt(kind)], .tiles = .{ .{ .size = 16 }, .{}, .{} }, .in_place = kind == .rows or kind == .fused, .served = &half_served }; + return .{ .name = names[@backingInt(kind)][rank], .accum = .none, .depth = noSums, .out = .raw, .nan = .{ .stated = "every output byte, the state's included, equal to the full kernel's on these heads, non-finite inputs included" }, .replaces = originals[@backingInt(kind)], .tiles = .{ .{ .size = 16 }, .{}, .{} }, .in_place = kind == .rows or kind == .fused, .served = if (kind == .tpr) &tpr_served else &half_served }; } /// A buffer the kernel reads: what its rows hold (null: not cut, the norm weight), its element bytes and its values. diff --git a/zig/tests/cuda/contract_glm_wide_expert.zig b/zig/tests/cuda/contract_glm_wide_expert.zig new file mode 100644 index 00000000000..d7e07463577 --- /dev/null +++ b/zig/tests/cuda/contract_glm_wide_expert.zig @@ -0,0 +1,133 @@ +//! Actual GLM down dispatch: a hot expert with a 64-pair plan, compared to its unchanged waves path. +const std = @import("std"); +const cuda = @import("cuda"); +const glm = @import("glm_cuda"); +const core = @import("core"); +const rig_ = @import("contract_rig.zig"); +const c = core.contract.spec; +const g = core.contract.gates; +fn depth(shape: c.Shape) usize { + return shape.k; +} +pub fn spec() c.Spec { + const served = comptime blk: { + var out: [8]c.Shape = undefined; + var at: usize = 0; + for (.{ 512, 1024 }) |k| for (.{ 16, 17, 24, 32 }) |rows| { + out[at] = .{ .rows = rows, .n = 4096, .k = k }; + at += 1; + }; + break :blk out; + }; + return .{ .name = "cuda GLM wide expert fact down", .accum = .f32, .depth = depth, .out = .raw, .replaces = "GLM factored down waves", .nan = .{ .stated = "Exact original GLM down bytes including NaN/Inf payloads and untouched skipped slots" }, .served = &served, .sums = .{ .why = "Same per-group MMA from zero, scale FMA and global scale; replacement byte equality" } }; +} +pub const Partial = struct { + rig: rig_.Rig, + ks: *glm.experts.Kernels, + shape: c.Shape = undefined, + plan: glm.experts.Plan = undefined, + layer: cuda.experts.Layer = undefined, + x: u64 = 0, + out: u64 = 0, + base: u64 = 0, + nonfinite: bool = false, + corrupt: bool = false, + pub fn kernel(self: *Partial) g.Kernel { + var s = spec(); + if (self.nonfinite) s.name = "cuda GLM wide expert fact down nonfinite"; + if (self.corrupt) s.name = "control: GLM wide expert output byte changed"; + return .{ .spec = s, .ctx = self, .vt = &vt, .control = if (self.corrupt) .shapes else null }; + } + const vt = g.hooks(Partial); + pub fn deinit(self: *Partial) void { + self.rig.deinit(); + } + pub fn count(self: *Partial) usize { + return self.shape.rows * 2 * self.shape.n * 4; + } + pub fn prepare(self: *Partial, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.rows < 1 or shape.rows > 64 or shape.n != 4096 or (shape.k != 512 and shape.k != 1024)) return false; + self.rig.reset(); + self.shape = shape; + const a = self.rig.gpu.gpa; + const x = try a.alloc(u16, shape.rows * 2 * shape.k); + defer a.free(x); + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + for (x) |*v| v.* = c.toBf16(rng.float(f32) * 2 - 1); + if (self.nonfinite or fill == .nonfinite) for (0..shape.rows) |row| for ([_]u16{ 0x7fc1, 0xffc2, 0x7f80, 0xff80 }, 0..) |h, i| { + x[row * 2 * shape.k + 31 + i * 32] = h; + }; + const weights = try a.alloc(u8, (shape.n / 32) * (shape.k / 32) * 576); + defer a.free(weights); + var off: usize = 0; + while (off < weights.len) : (off += 576) { + rng.bytes(weights[off..][0..512]); + @memset(weights[off + 512 ..][0..64], 0x20); + } + const global: f32 = 0.125; + self.x = try self.rig.input(std.mem.sliceAsBytes(x)); + self.layer = .{ .format = .nvfp4, .up = 0, .down = try self.rig.input(weights), .down_scale = try self.rig.input(std.mem.asBytes(&global)), .dims = shape.n, .width = shape.k, .experts = 1 }; + const items = [_]i32{ 0, 0, @intCast(shape.rows) }; + const counts = [_]i32{1}; + const members = try a.alloc(i32, shape.rows); + defer a.free(members); + for (members, 0..) |*v, i| v.* = @intCast(i * 2); + self.plan = .{ .route = .{ .items = try self.rig.input(std.mem.asBytes(&items)), .counts = try self.rig.input(std.mem.asBytes(&counts)), .members = try self.rig.input(std.mem.sliceAsBytes(members)), .rank = 0, .hist = 0 }, .slots = 2, .experts = 2, .prompt = false, .fact = true }; + self.out = try self.rig.output(self.count()); + self.base = try self.rig.scratch(self.count()); + const b: cuda.DeviceBuffer = .{ .d = self.rig.gpu.d, .ptr = self.base, .len = self.count() }; + try b.fill8(0xff, self.rig.s.handle); + return true; + } + fn launch(self: *Partial, wide: bool) !void { + var ks = self.ks.*; + ks.wide_tile = wide; + try glm.experts.run(&ks, self.rig.s, .down_f32, self.layer, self.plan, self.x, self.shape.k, self.shape.rows, if (wide) self.out else self.base, 1); + try self.rig.s.synchronize(); + } + pub fn run(self: *Partial) !void { + try self.launch(true); + if (self.corrupt) { + const bytes = try self.rig.outputBytes(); + var byte = [_]u8{bytes[0] ^ 1}; + const b: cuda.DeviceBuffer = .{ .d = self.rig.gpu.d, .ptr = self.out, .len = self.count() }; + try b.upload(0, &byte); + } + } + pub fn replaced(self: *Partial) ![]const u8 { + try self.launch(false); + return self.rig.bytes(self.base, self.count()); + } + pub fn reference(_: *Partial, want: []f64, mag: []f64) !void { + @memset(want, 0); + @memset(mag, 0); + } + pub fn check(self: *Partial, _: g.Gate) !?[]const u8 { + const got = try self.rig.gpu.gpa.dupe(u8, try self.rig.outputBytes()); + defer self.rig.gpu.gpa.free(got); + return if (std.mem.eql(u8, got, try self.replaced())) null else "GLM wide expert output differs from original waves"; + } +}; +pub const Suite = struct { + ks: glm.experts.Kernels, + cells: [3]Partial, + pub fn create(gpu: @import("check.zig").Gpu, s: cuda.Stream, kernels: *std.ArrayList(g.Kernel)) !*Suite { + const a = gpu.gpa; + const self = try a.create(Suite); + errdefer a.destroy(self); + self.ks = .{ .nvfp4 = try cuda.experts.Nvfp4Experts.load(gpu.d, @intCast(try gpu.ctx.attribute(.multiprocessor_count))), .b32 = null, .router = undefined }; + errdefer self.ks.nvfp4.unload(); + for (&self.cells, 0..) |*p, i| { + p.* = .{ .rig = .{ .gpu = gpu, .s = s }, .ks = &self.ks, .nonfinite = i == 1, .corrupt = i == 2 }; + try kernels.append(a, p.kernel()); + } + return self; + } + pub fn destroy(self: *Suite) void { + const a = self.cells[0].rig.gpu.gpa; + for (&self.cells) |*p| p.deinit(); + self.ks.nvfp4.unload(); + a.destroy(self); + } +}; diff --git a/zig/tests/cuda/contract_idol_attn.zig b/zig/tests/cuda/contract_idol_attn.zig index 534d7fb35e3..bc59d7603c1 100644 --- a/zig/tests/cuda/contract_idol_attn.zig +++ b/zig/tests/cuda/contract_idol_attn.zig @@ -43,6 +43,8 @@ pub const Attn = struct { qkv: std.ArrayList(u16) = .empty, /// The key head whose K and V rows the reference holds now. held: ?usize = null, + /// Gate 4's inputs: every key alike, so every token's outputs are token 0's. + alike: bool = false, dev: u64 = 0, out: u64 = 0, @@ -75,6 +77,7 @@ pub const Attn = struct { t.heads = shape.rows; t.tokens = shape.n; t.held = null; + t.alike = fill == .stress; try t.qkv.resize(a, t.tokens * t.stride()); var prng = std.Random.DefaultPrng.init(seed); const rng = prng.random(); @@ -150,11 +153,27 @@ pub const Attn = struct { } pub fn reference(t: *Attn, want: []f64, mag: []f64) !void { - return t.ref.?.reference(t, t.outputs(), 1.0 / 8.0, want, mag); + try t.ref.?.reference(t, t.computed(), 1.0 / 8.0, want, mag); + t.repeat(want); + t.repeat(mag); } pub fn simulate(t: *Attn, acc: c.Accum, order: g.Order, out: []f64) !void { - return t.ref.?.simulate(t, t.outputs(), 1.0 / 8.0, acc, order, out); + try t.ref.?.simulate(t, t.computed(), 1.0 / 8.0, acc, order, out); + t.repeat(out); + } + + /// The output heads float64 computes: token 0's alone when the keys are alike (gate 4 at 8,192 tokens). + fn computed(t: *Attn) usize { + return if (t.alike) t.heads else t.outputs(); + } + + /// Token 0's outputs copied to every token when the keys are alike. + fn repeat(t: *const Attn, out: []f64) void { + if (!t.alike) return; + const w = t.heads * r.D; + var i = w; + while (i < out.len) : (i += w) @memcpy(out[i..][0..w], out[0..w]); } }; @@ -187,3 +206,20 @@ test "gate 4's attention inputs at the joint rows: fp32 sums exact in every orde } try std.testing.expect(margin[0] >= 100 and margin[1] >= 100); } + +test "gate 4's alike keys: token 0's outputs copied to every token match float64 over every token" { + const a = std.testing.allocator; + var t: Attn = .{ .rig = undefined, .k = undefined, .name = "host" }; + defer if (t.ref) |*x| x.deinit(); + defer t.qkv.deinit(a); + try t.inputs(a, .{ .rows = 3, .n = 37, .k = 37 }, .stress, 0x1d02); + const n = t.count(); + const buf = try a.alloc(f64, 4 * n); + defer a.free(buf); + try t.reference(buf[0..n], buf[n .. 2 * n]); + try t.ref.?.reference(&t, t.outputs(), 1.0 / 8.0, buf[2 * n .. 3 * n], buf[3 * n ..]); + try std.testing.expectEqualSlices(f64, buf[2 * n ..], buf[0 .. 2 * n]); + try t.simulate(.f16, .strided, buf[0..n]); + try t.ref.?.simulate(&t, t.outputs(), 1.0 / 8.0, .f16, .strided, buf[n .. 2 * n]); + try std.testing.expectEqualSlices(f64, buf[n .. 2 * n], buf[0..n]); +} diff --git a/zig/tests/cuda/contract_idol_dec_attn.zig b/zig/tests/cuda/contract_idol_dec_attn.zig index 679c8ab1b99..ea6e8878f11 100644 --- a/zig/tests/cuda/contract_idol_dec_attn.zig +++ b/zig/tests/cuda/contract_idol_dec_attn.zig @@ -59,6 +59,62 @@ fn ulp16(x: f64) f64 { return std.math.pow(f64, 2, @floor(std.math.log2(a)) - 10); } +/// A query's float64 sum P V, allowance terms and l; P fp32 (tile 0) or fp16 at each `tile` keys' running max. +fn weigh(s: []const f64, ds: []const f64, v: []const f16, stride: usize, tile: usize, sums: f64, out: []f64, tol: []f64, flip: []f64) f64 { + var m: f64 = -std.math.inf(f64); + var top: usize = 0; + var nan = false; + for (s, 0..) |x, j| { + nan = nan or std.math.isNan(x); + if (x > m) { + m = x; + top = j; + } + } + if (nan) m = std.math.nan(f64); + @memset(out, 0); + @memset(tol, 0); + @memset(flip, 0); + var l: f64 = 0; + var mt: f64 = -std.math.inf(f64); + var at: usize = 0; + const step = if (tile == 0) s.len else tile; + var lo: usize = 0; + while (lo < s.len) : (lo += step) { + const hi = @min(lo + step, s.len); + for (s[lo..hi], lo..) |x, j| if (x > mt) { + mt = x; + at = j; + }; + if (nan) mt = m; + // the tile's fp32 rescales to the final max (exact here: their rounding is in `sums`) + const a = @exp(mt - m); + for (s[lo..hi], ds[lo..hi], lo..) |sj, dj, j| { + const pj = @exp(sj - m); + l += pj; + // P's relative error: its score's and the top score's sums, exp2's approximation + const rel = dj + ds[top] + 0x1p-21; + var used = pj; + var turn: f64 = 0; + if (tile != 0) { + const pt = if (sj == -std.math.inf(f64)) 0 else @exp(sj - mt); + used = @as(f64, half(pt)) * a; + const u = ulp16(pt); + const mid = (@floor(pt / u) + 0.5) * u; + // where P rounds hangs on its score's and the running max's sums + if (@abs(pt - mid) <= pt * (dj + ds[at] + 0x1p-21) + 0x1p-60) turn = u * a; + } + for (out, tol, flip, 0..) |*o, *tl, *fl, e| { + const vv: f64 = v[j * stride + e]; + o.* += used * vv; + tl.* += pj * @abs(vv) * (rel + sums); + fl.* += turn * @abs(vv); + } + } + } + return l; +} + pub const Attention = struct { rig: rig_.Rig, k: *const dk.Kernels, @@ -184,7 +240,7 @@ pub const Attention = struct { return t.lq * H; } - /// Float64 O at the kernel's P; `mag` the allowance: fp32 steps, P's rounding near a midpoint, O's own rounding. + /// Float64 O at the kernel's P (see `weigh`); `mag` the allowance: fp32 steps, P near a midpoint, O's own rounding. pub fn reference(t: *Attention, want: []f64, mag: []f64) !void { const a = t.rig.gpu.gpa; const L = t.lk; @@ -195,6 +251,7 @@ pub const Attention = struct { const kf = try a.alloc(f64, L * D); defer a.free(kf); const sums = c.gamma(@floatFromInt(depths[t.which](.{ .rows = heads, .n = t.lq, .k = L })), c.unit(.f32)); + const tile: usize = if (t.rounded()) forms[t.which].tiles[2].size else 0; var qf: [D]f64 = undefined; var out: [D]f64 = undefined; var tol: [D]f64 = undefined; @@ -206,9 +263,6 @@ pub const Attention = struct { }; for (0..p) |i| { for (&qf, t.qAt(i, hd)) |*x, b| x.* = b; - var m: f64 = -std.math.inf(f64); - var top: usize = 0; - var nan = false; for (s, ds, 0..) |*sj, *dj, j| { const Vec = @Vector(8, f64); var acc: Vec = @splat(0); @@ -221,37 +275,8 @@ pub const Attention = struct { } sj.* = @reduce(.Add, acc) * scale; dj.* = c.gamma(D, c.unit(.f32)) * @reduce(.Add, mag_acc) * scale; - nan = nan or std.math.isNan(sj.*); - if (sj.* > m) { - m = sj.*; - top = j; - } - } - if (nan) m = std.math.nan(f64); - var l: f64 = 0; - @memset(&out, 0); - @memset(&tol, 0); - @memset(&flip, 0); - for (s, ds, 0..) |sj, dj, j| { - const pj = @exp(sj - m); - l += pj; - // P's relative error: its score's and the top score's sums, exp2's approximation - const rel = dj + ds[top] + 0x1p-21; - var used = pj; - var turn: f64 = 0; - if (t.rounded()) { - used = half(pj); - const u = ulp16(pj); - const mid = (@floor(pj / u) + 0.5) * u; - if (@abs(pj - mid) <= pj * rel + 0x1p-60) turn = u; - } - for (&out, &tol, &flip, t.vAt(j, hd)) |*o, *tl, *fl, vh| { - const vv: f64 = vh; - o.* += used * vv; - tl.* += pj * @abs(vv) * (rel + sums); - fl.* += turn * @abs(vv); - } } + const l = weigh(s, ds, t.kv.items[H + hd * D ..], 2 * H, tile, sums, &out, &tol, &flip); var row = i; while (row < t.lq) : (row += p) { const at = row * H + hd * D; @@ -309,3 +334,52 @@ test "an exact head's fp32 remainder lies past the short form's allowance, and i const u = ulp16(p); try std.testing.expect(@abs(p - (@floor(p / u) + 0.5) * u) > p * 2 * rel); } + +/// The kernel's online softmax in fp32 over one value column: P to fp16 at the running max, o and l rescaled. +fn online(s: []const f64, v: []const f16, tile: usize) f64 { + var m: f32 = -std.math.inf(f32); + var l: f32 = 0; + var o: f32 = 0; + var lo: usize = 0; + while (lo < s.len) : (lo += tile) { + const keys = s[lo..@min(lo + tile, s.len)]; + var n = m; + for (keys) |x| n = @max(n, @as(f32, @floatCast(x))); + const a: f32 = if (m == -std.math.inf(f32)) 0 else @exp(m - n); + l *= a; + o *= a; + for (keys, v[lo..][0..keys.len]) |x, vh| { + const p = @exp(@as(f32, @floatCast(x)) - n); + l += p; + o += @as(f32, @as(f16, @floatCast(p))) * @as(f32, vh); + } + m = n; + } + return o / l; +} + +test "a later tile's larger score moves where P rounds: the reference follows the tile maxima, not the final max" { + // tile 0's P V cancels at its own max (3 x 1 vs 4 x 0.75), not at tile 2's 0.2 higher; tile 1 far below + var s: [129]f64 = undefined; + var v: [129]f16 = undefined; + for (&s, &v, 0..) |*x, *y, j| { + x.* = if (j < 32) 0 else if (j < 64) @log(0.75) else if (j < 128) -30 else 0.2; + y.* = if (j < 32) 3 else if (j < 64) -4 else 0; + } + const ds: [129]f64 = @splat(c.gamma(D, c.unit(.f32)) * 4 * scale); + const sums = c.gamma(@floatFromInt(depthTiled(.{ .rows = heads, .n = 1, .k = s.len })), c.unit(.f32)); + var o: [2][1]f64 = undefined; + var tol: [2][1]f64 = undefined; + var flip: [2][1]f64 = undefined; + var want: [2]f64 = undefined; + var mag: [2]f64 = undefined; + // 0: the kernel's 64-key tiles; 1: one tile over every key, P rounded at the final max + for ([_]usize{ 64, s.len }, 0..) |tile, i| { + const l = weigh(&s, &ds, &v, 1, tile, sums, &o[i], &tol[i], &flip[i]); + want[i] = o[i][0] / l; + mag[i] = (tol[i][0] + flip[i][0]) / l + @abs(want[i]) * 0x1p-10 + 0x1p-24; + } + const got = online(&s, &v, 64); + try std.testing.expect(@abs(got - want[0]) <= mag[0]); + try std.testing.expect(@abs(got - want[1]) > 4 * mag[1]); +} diff --git a/zig/tests/cuda/contract_inkling2.zig b/zig/tests/cuda/contract_inkling2.zig index fccf522af06..1ab486edf31 100644 --- a/zig/tests/cuda/contract_inkling2.zig +++ b/zig/tests/cuda/contract_inkling2.zig @@ -1,4 +1,4 @@ -//! Inkling 2's CUDA kernels under the contract: attention, glue, drafter, experts and tower, each with controls. +//! Inkling 2's CUDA kernels under the contract: attention, glue, experts and tower, each with controls. const std = @import("std"); const cuda = @import("cuda"); const check = @import("check.zig"); @@ -9,6 +9,8 @@ pub const Set = struct { gpa: std.mem.Allocator, attn: @import("contract_inkling2_attn.zig").Set = .{}, ops: @import("contract_inkling2_ops.zig").Set = .{}, + experts: @import("contract_inkling2_experts.zig").Set = .{}, + loop_math: @import("contract_inkling2_loop_math_extra.zig").Set = .{}, /// The set, its kernels appended to `list`. pub fn init(gpu: check.Gpu, s: cuda.Stream, a: std.mem.Allocator, list: *std.ArrayList(g.Kernel)) !*Set { @@ -18,10 +20,16 @@ pub const Set = struct { try set.attn.init(gpu, s, a, list); errdefer set.attn.deinit(); try set.ops.init(gpu, s, a, list); + errdefer set.ops.deinit(); + try set.experts.init(gpu, s, a, list); + errdefer set.experts.deinit(); + try set.loop_math.init(gpu, s, a, list); return set; } pub fn deinit(set: *Set) void { + set.loop_math.deinit(); + set.experts.deinit(); set.ops.deinit(); set.attn.deinit(); set.gpa.destroy(set); diff --git a/zig/tests/cuda/contract_inkling2_attn_prep.zig b/zig/tests/cuda/contract_inkling2_attn_prep.zig index 35cea83270a..456e98b43d1 100644 --- a/zig/tests/cuda/contract_inkling2_attn_prep.zig +++ b/zig/tests/cuda/contract_inkling2_attn_prep.zig @@ -4,7 +4,7 @@ const cuda = @import("cuda"); const core = @import("core"); const ink = @import("inkling2"); const rig_ = @import("contract_rig.zig"); -const ref = @import("contract_inkling2_attn_ref.zig"); +const ref = core.contract.inkling2_attn_ref; const contract = core.contract; const c = contract.spec; diff --git a/zig/tests/cuda/contract_inkling2_attn_rows.zig b/zig/tests/cuda/contract_inkling2_attn_rows.zig index 71aaac07794..ad95cb5de5a 100644 --- a/zig/tests/cuda/contract_inkling2_attn_rows.zig +++ b/zig/tests/cuda/contract_inkling2_attn_rows.zig @@ -4,7 +4,7 @@ const cuda = @import("cuda"); const core = @import("core"); const ink = @import("inkling2"); const rig_ = @import("contract_rig.zig"); -const ref = @import("contract_inkling2_attn_ref.zig"); +const ref = core.contract.inkling2_attn_ref; const contract = core.contract; const c = contract.spec; diff --git a/zig/tests/cuda/contract_inkling2_experts.zig b/zig/tests/cuda/contract_inkling2_experts.zig new file mode 100644 index 00000000000..73f89cff366 --- /dev/null +++ b/zig/tests/cuda/contract_inkling2_experts.zig @@ -0,0 +1,88 @@ +//! Inkling 2's grouped experts and vision tower (inkling2/experts.cu, vision.cu) under the contract, with controls. +const std = @import("std"); +const cuda = @import("cuda"); +const ink = @import("inkling2"); +const check = @import("check.zig"); +const g = @import("core").contract.gates; +const rig_ = @import("contract_rig.zig"); +const ref = @import("contract_minimax_glue_ref.zig"); +const grouped = @import("contract_inkling2_experts_grouped.zig"); +const vision = @import("contract_inkling2_experts_vision.zig"); +const modelopt = @import("contract_inkling2_modelopt.zig"); +const Attention = @import("contract_inkling2_experts_attn.zig").Attention; + +/// Every registration, each control after the kernel it breaks; the gates point at these fields. +pub const Set = struct { + live: bool = false, + ek: ink.experts.Kernels = undefined, + vk: ink.vision.Kernels = undefined, + mk: ink.modelopt.Kernels = undefined, + groups: [2]grouped.Group = undefined, + projections: [4]grouped.Grouped = undefined, + moe: [11]modelopt.ModelOpt = undefined, + embeds: [2]ref.Gated(vision.Embed) = undefined, + ropes: [2]ref.Gated(vision.Rope) = undefined, + adds: [2]ref.Gated(vision.ScaleAdd) = undefined, + attns: [2]Attention = undefined, + + pub fn init(set: *Set, gpu: check.Gpu, s: cuda.Stream, a: std.mem.Allocator, list: *std.ArrayList(g.Kernel)) !void { + set.ek = try ink.experts.Kernels.load(gpu.d); + errdefer set.ek.unload(); + set.vk = try ink.vision.Kernels.load(gpu.d); + errdefer set.vk.unload(); + const sms: usize = @intCast(try gpu.ctx.attribute(.multiprocessor_count)); + set.mk = try ink.modelopt.Kernels.load(gpu.d, sms); + errdefer set.mk.unload(); + const rig: rig_.Rig = .{ .gpu = gpu, .s = s }; + for (&set.groups, 0..) |*x, i| x.* = .{ .rig = rig, .k = &set.ek, .wrong_run = i == 1 }; + const forms = [4]@import("contract_inkling2_experts_ref.zig").Form{ .rows, .rows, .wide, .wide }; + for (&set.projections, forms, 0..) |*x, f, i| x.* = .{ .rig = rig, .k = &set.ek, .form = f, .fault = if (i == 1) .short else if (i == 3) .swapped else .none }; + const prompt = [11]bool{ false, true, false, true, false, true, false, false, false, true, false }; + for (&set.moe, 0..) |*x, i| x.* = .{ + .rig = rig, + .k = &set.mk, + .format = if (i < 4) .nvfp4 else .mxfp8, + .phase = if (prompt[i]) .prompt else .decode, + .fault = switch (i) { + 0, 1, 4, 5 => .none, + 2, 6 => .wrong_combine, + 3, 9 => .wrong_prompt_up, + 7 => .wrong_plan, + 8 => .wrong_up, + 10 => .wrong_act, + else => unreachable, + }, + }; + for (&set.embeds, 0..) |*x, i| x.* = .{ .rig = rig, .k = .{ .kern = &set.vk, .late = i == 1 } }; + for (&set.ropes, 0..) |*x, i| x.* = .{ .rig = rig, .k = .{ .kern = &set.vk, .swapped = i == 1 } }; + for (&set.adds, 0..) |*x, i| x.* = .{ .rig = rig, .k = .{ .kern = &set.vk, .late = i == 1 } }; + for (&set.attns, 0..) |*x, i| x.* = .{ .rig = rig, .k = &set.vk, .wide = i == 1 }; + set.live = true; + for (&set.groups) |*x| try list.append(a, x.kernel()); + for (&set.projections) |*x| try list.append(a, x.kernel()); + for (&set.moe) |*x| try list.append(a, x.kernel()); + for (&set.embeds) |*x| try list.append(a, x.kernel()); + for (&set.ropes) |*x| try list.append(a, x.kernel()); + for (&set.adds) |*x| try list.append(a, x.kernel()); + for (&set.attns) |*x| try list.append(a, x.kernel()); + } + + pub fn deinit(set: *Set) void { + if (!set.live) return; + for (&set.attns) |*x| x.deinit(); + for (&set.adds) |*x| x.deinit(); + for (&set.ropes) |*x| x.deinit(); + for (&set.embeds) |*x| x.deinit(); + for (&set.moe) |*x| x.deinit(); + for (&set.projections) |*x| x.deinit(); + for (&set.groups) |*x| x.deinit(); + set.mk.unload(); + set.vk.unload(); + set.ek.unload(); + set.live = false; + } +}; + +test { + _ = @import("contract_inkling2_experts_ref.zig"); +} diff --git a/zig/tests/cuda/contract_inkling2_experts_attn.zig b/zig/tests/cuda/contract_inkling2_experts_attn.zig new file mode 100644 index 00000000000..e914309ae75 --- /dev/null +++ b/zig/tests/cuda/contract_inkling2_experts_attn.zig @@ -0,0 +1,282 @@ +//! tf_ink2v_attention under the contract: the tower's full attention over one picture's rows, head dim 64. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const ink = @import("inkling2"); +const rig_ = @import("contract_rig.zig"); +const attn = @import("contract_attn.zig"); + +const c = core.contract.spec; +const g = core.contract.gates; +const aref = core.attention_ref; +const threads = core.contract.reference_threads; + +const D = ink.vision.head_dim; +const smem: u32 = 2 * 2 * 64 * (D / 8 + 1) * 16; // vision.zig's attn_smem + +/// The P x V chain of a row: every key, a 64-key tile at a time. +fn keyChain(s: c.Shape) usize { + return s.k + 64; +} + +fn scale(wide: bool) f32 { + return 1.0 / @sqrt(@as(f32, if (wide) 128 else D)); +} + +/// Shape: heads (rows), head dim (n), sequence rows W (k): 16 heads at 1, 4 and 32 tokens, two at 256 to 4,096. +fn spec(wide: bool) c.Spec { + const served = &[_]c.Shape{ .{ .rows = 2, .n = D, .k = 1025 }, .{ .rows = 16, .n = D, .k = 5 }, .{ .rows = 16, .n = D, .k = 17 }, .{ .rows = 16, .n = D, .k = 129 }, .{ .rows = 2, .n = D, .k = 4097 }, .{ .rows = 2, .n = D, .k = 16385 } }; + const name = if (wide) "inkling2 experts control: tf_ink2v_attention scaled for head dim 128" else "inkling2 experts vision tf_ink2v_attention (full attention, head dim 64)"; + return .{ .name = name, .accum = .f32, .depth = keyChain, .ops = 1, .out = .bf16, .tiles = .{ .{}, .{}, .{ .size = 128 } }, .served = served, .sums = .{ .why = attn.why } }; +} + +/// Gate 4's values: odd integers, every other one times 4, the second half cancelling the first (fp32 exact at 16K). +fn mirrored(rng: std.Random, out: []f32) void { + const h = out.len / 2; + for (0..h) |i| { + const v: f32 = @floatFromInt((1 + 2 * rng.uintLessThan(u32, 128)) * @as(u32, if (i % 2 == 1) 4 else 1)); + out[i] = v; + out[h + i] = (if (i < 8) @as(f32, 1) else 0) - v; + } + if (out.len % 2 == 1) out[out.len - 1] = 0; +} + +pub const Attention = struct { + rig: rig_.Rig, + k: *const ink.vision.Kernels, + wide: bool = false, // control: the score scale of head dim 128 + shape: c.Shape = undefined, + qkv: []u16 = &.{}, // [W][3 heads 64]: q heads, then k, then v + f: []f64 = &.{}, // [3][heads][W][64]: the same in float64 + keys: []usize = &.{}, + stressed: bool = false, + dev: u64 = 0, + out: u64 = 0, + msg: [240]u8 = undefined, + + pub fn deinit(self: *Attention) void { + self.free(); + self.rig.deinit(); + } + + fn free(self: *Attention) void { + const a = self.rig.gpu.gpa; + a.free(self.qkv); + a.free(self.f); + a.free(self.keys); + self.qkv = &.{}; + self.f = &.{}; + self.keys = &.{}; + } + + pub fn kernel(self: *Attention) g.Kernel { + return .{ .spec = spec(self.wide), .ctx = self, .vt = &vt, .control = if (self.wide) .shapes else null }; + } + + const vt = g.hooks(Attention); + + fn heads(self: *const Attention) usize { + return self.shape.rows; + } + + fn at(self: *const Attention, row: usize, which: usize, head: usize) []u16 { + return self.qkv[row * 3 * self.heads() * D + (which * self.heads() + head) * D ..][0..D]; + } + + /// Float64 rows of q, k or v for one head: [W][64]. + fn rows(self: *const Attention, which: usize, head: usize) []const f64 { + const w = self.shape.k; + return self.f[(which * self.heads() + head) * w * D ..][0 .. w * D]; + } + + pub fn prepare(self: *Attention, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + self.rig.reset(); + if (shape.n != D or shape.rows == 0 or shape.k == 0) return false; + const a = self.rig.gpu.gpa; + self.free(); + self.shape = shape; + self.stressed = fill == .stress; + const W = shape.k; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + self.qkv = try a.alloc(u16, W * 3 * shape.rows * D); + for (self.qkv) |*e| e.* = attn.normal(rng); + switch (fill) { + .random => {}, + .nonfinite => self.plant(), + .stress => try self.stress(rng), + } + self.f = try a.alloc(f64, self.qkv.len); + for (0..W) |j| for (0..3) |which| for (0..shape.rows) |h| { + for (self.f[((which * shape.rows + h) * W + j) * D ..][0..D], self.at(j, which, h)) |*y, x| y.* = c.fromBf16(x); + }; + self.keys = try a.alloc(usize, W); + for (self.keys, 0..) |*k, i| k.* = i; + self.dev = try self.rig.input(std.mem.sliceAsBytes(self.qkv)); + self.out = try self.rig.output(W * shape.rows * D * 2); + return true; + } + + /// Head 0: NaN in row 0's query, +inf and -inf in values, both in one column; head 1: NaN in one key. + fn plant(self: *Attention) void { + const L = self.shape.k; + self.at(0, 0, 0)[3] = c.toBf16(std.math.nan(f32)); + self.at(L - 1, 2, 0)[7] = c.toBf16(std.math.inf(f32)); + self.at(L / 2, 2, 0)[9] = c.toBf16(-std.math.inf(f32)); + if (L >= 3) { + self.at(1, 2, 0)[11] = c.toBf16(std.math.inf(f32)); + self.at(2, 2, 0)[11] = c.toBf16(-std.math.inf(f32)); + } + if (self.heads() > 1) self.at(L / 3, 1, 1)[5] = c.toBf16(std.math.nan(f32)); + } + + /// Gate 4: every key one vector (each p is 1); each value column mirrored over the keys. + fn stress(self: *Attention, rng: std.Random) !void { + const a = self.rig.gpu.gpa; + const L = self.shape.k; + var key: [D]u16 = undefined; + for (&key) |*e| e.* = attn.normal(rng); + const col = try a.alloc(f32, L); + defer a.free(col); + for (0..self.heads()) |h| { + for (0..L) |j| @memcpy(self.at(j, 1, h), &key); + for (0..D) |e| { + mirrored(rng, col); + for (col, 0..) |y, j| self.at(j, 2, h)[e] = c.toBf16(y); + } + } + } + + pub fn run(self: *Attention) !void { + var a: cuda.Args = .{}; + a.add(self.dev); + a.add(self.out); + a.add(@as(c_int, @intCast(self.shape.k))); + a.add(@as(c_int, @intCast(self.heads()))); + a.add(scale(self.wide)); + try cuda.launch.launch(self.k.attention, .{ .grid = .{ .x = @intCast((self.shape.k + 127) / 128), .y = @intCast(self.heads()) }, .block = .{ .x = 256 }, .shared = smem }, self.rig.s, &a); + try self.rig.s.synchronize(); + } + + pub fn count(self: *Attention) usize { + return self.shape.k * self.heads() * D; + } + + /// Output rows [lo, hi) (row-major over sequence row and head) checked against attention_ref on one thread. + const Job = struct { + t: *const Attention, + out: []const u8, + lo: usize, + hi: usize, + gate: g.Gate, + planted: usize = 0, + bad: ?usize = null, // first failing output + ratio: f64 = 0, + + pub fn run(j: *Job) void { + var want: [D]f64 = undefined; + var tol: [D]f64 = undefined; + const t = j.t; + const s: f64 = scale(false); + for (j.lo..j.hi) |i| { + const row = i / t.heads(); + const head = i % t.heads(); + aref.head(t.rows(0, head)[row * D ..][0..D], t.rows(1, head), t.rows(2, head), t.keys, D, s, &want, &tol); + for (want, tol, 0..) |w, tl, e| { + const got = c.read(.bf16, j.out, i * D + e); + if (c.classOf(w) != .finite) j.planted += 1; + const off = c.classOf(got) != c.classOf(w) or (j.gate != .nonfinite and std.math.isFinite(w) and !(@abs(got - w) <= tl)); + if (off and j.bad == null) { + j.bad = i * D + e; + j.ratio = @abs(got - w) / tl; + } + } + if (j.bad != null) return; + } + } + }; + + /// Gates 1 and 3: every output's class equals float64's, and a finite one is within attention_ref's bound. + pub fn check(self: *Attention, gate: g.Gate) !?[]const u8 { + const out = try self.rig.outputBytes(); + const n = self.shape.k * self.heads(); + var jobs: [threads.maximum]Job = undefined; + const parts = threads.count(threads.maximum, n); + for (jobs[0..parts], 0..) |*j, p| j.* = .{ .t = self, .out = out, .lo = n * p / parts, .hi = n * (p + 1) / parts, .gate = gate }; + threads.run(Job, jobs[0..parts], .normal); + var planted: usize = 0; + for (jobs[0..parts]) |j| { + planted += j.planted; + if (j.bad) |b| { + const got = c.read(.bf16, out, b); + return try std.fmt.bufPrint(&self.msg, "output {d} (row {d}, head {d}, dim {d}) is {e:.6}: {t}, {d:.2} of attention_ref's bound", .{ b, b / D / self.heads(), b / D % self.heads(), b % D, got, c.classOf(got), j.ratio }); + } + } + if (gate == .nonfinite and (planted == 0 or planted == n * D)) return try std.fmt.bufPrint(&self.msg, "the planted values make {d} of {d} reference outputs non-finite: no proof", .{ planted, n * D }); + return null; + } + + /// Float64 softmax(s q.k) v of one output row, and its terms' magnitude sum p |v| / sum p. + fn one(self: *const Attention, i: usize, p: []f64, want: []f64, mag: []f64) void { + const row = i / self.heads(); + const head = i % self.heads(); + const q = self.rows(0, head)[row * D ..][0..D]; + const k = self.rows(1, head); + const v = self.rows(2, head); + var m: f64 = -std.math.inf(f64); + for (p, 0..) |*x, j| { + var s: f64 = 0; + for (0..D) |e| s += q[e] * k[j * D + e]; + x.* = s * scale(false); + m = @max(m, x.*); + } + var l: f64 = 0; + for (p) |*x| { + x.* = @exp(x.* - m); + l += x.*; + } + for (0..D) |e| { + var s: f64 = 0; + var abs: f64 = 0; + for (p, 0..) |x, j| { + s += x * v[j * D + e]; + abs += x * @abs(v[j * D + e]); + } + want[i * D + e] = s / l; + mag[i * D + e] = abs / l; + } + } + + /// Gate 4 reads these; under its stress every key scores alike, so a head's rows share one output row. + pub fn reference(self: *Attention, want: []f64, mag: []f64) !void { + const a = self.rig.gpu.gpa; + const p = try a.alloc(f64, self.shape.k); + defer a.free(p); + const n = self.shape.k * self.heads(); + for (0..n) |i| { + if (self.stressed and i >= self.heads()) { + @memcpy(want[i * D ..][0..D], want[(i % self.heads()) * D ..][0..D]); + @memcpy(mag[i * D ..][0..D], mag[(i % self.heads()) * D ..][0..D]); + } else self.one(i, p, want, mag); + } + } + + /// Gate 4's sums in an accumulator: its keys score alike, so every p is 1 and the sums are V's terms and l's ones. + pub fn simulate(self: *Attention, acc: c.Accum, order: g.Order, out: []f64) !void { + if (!self.stressed) return error.SumsNeedStress; + const a = self.rig.gpu.gpa; + const L = self.shape.k; + const terms = try a.alloc(f64, L); + defer a.free(terms); + const ones = try a.alloc(f64, L); + defer a.free(ones); + @memset(ones, 1); + const l = core.contract.rows.sumIn(acc, order, ones); + for (0..self.heads()) |h| for (0..D) |e| { + const v = self.rows(2, h); + for (terms, 0..) |*x, j| x.* = v[j * D + e]; + out[h * D + e] = core.contract.rows.sumIn(acc, order, terms) / l; + }; + for (self.heads()..L * self.heads()) |i| @memcpy(out[i * D ..][0..D], out[(i % self.heads()) * D ..][0..D]); + } +}; diff --git a/zig/tests/cuda/contract_inkling2_experts_grouped.zig b/zig/tests/cuda/contract_inkling2_experts_grouped.zig new file mode 100644 index 00000000000..1d82f7c6a2f --- /dev/null +++ b/zig/tests/cuda/contract_inkling2_experts_grouped.zig @@ -0,0 +1,296 @@ +//! tf_ink2x_rows, tf_ink2x_wide and tf_ink2x_group under the contract: each bit-equal to the main kernel it replaces. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const ink = @import("inkling2"); +const rig_ = @import("contract_rig.zig"); +const ref = @import("contract_inkling2_experts_ref.zig"); + +const c = core.contract.spec; +const g = core.contract.gates; + +fn i32s(v: usize) i32 { + return @intCast(v); +} + +/// One projection as experts.run launches it, on the lists tf_exl3_group writes; the baseline runs tf_exl3_grouped_2. +pub const Grouped = struct { + rig: rig_.Rig, + k: *const ink.experts.Kernels, + form: ref.Form, + fault: ref.Fault = .none, + fix: ?ref.Fixture = null, + tp: [2]u64 = .{ 0, 0 }, + k2: [2]u64 = .{ 0, 0 }, + x: [2]u64 = .{ 0, 0 }, + uids: u64 = 0, + ucount: u64 = 0, + members: u64 = 0, + items: u64 = 0, + nitems: u64 = 0, + out: u64 = 0, + base: u64 = 0, + msg: [160]u8 = undefined, + + pub fn deinit(self: *Grouped) void { + self.drop(); + self.rig.deinit(); + } + + fn drop(self: *Grouped) void { + if (self.fix) |*f| f.deinit(); + self.fix = null; + self.rig.reset(); + } + + pub fn kernel(self: *Grouped) g.Kernel { + return .{ .spec = ref.spec(self.form, self.fault), .ctx = self, .vt = &vt, .control = if (self.fault == .none) null else .shapes }; + } + + const vt = g.hooks(Grouped); + + fn put(self: *Grouped, x: anytype) !u64 { + return self.rig.input(std.mem.sliceAsBytes(x)); + } + + pub fn prepare(self: *Grouped, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (!ref.Fixture.valid(shape)) return false; + self.drop(); + const a = self.rig.gpu.gpa; + self.fix = try ref.Fixture.init(a, shape, fill, seed); + const f = &self.fix.?; + var pool: [f.trellis.len]u64 = undefined; + for (&pool, f.trellis) |*p, t| p.* = try self.put(t); + const m = ref.mats(shape); + for (0..2) |mat| { + var tp: [ref.experts]u64 = undefined; + var k2: [ref.experts]i32 = undefined; + for (&tp, &k2, 0..) |*t, *h, e| { + const i = ref.Fixture.entry(e, @min(mat, m - 1)); + t.* = pool[i]; + h.* = ref.halves(i); + } + self.tp[mat] = try self.put(&tp); + self.k2[mat] = try self.put(&k2); + } + const p = f.pairs(); + const xs = p * shape.k; + self.x[0] = try self.put(f.x[0..xs]); + self.x[1] = if (m == 2) try self.put(f.x[xs..]) else self.x[0]; + var l = try ref.Lists.init(a, f.pick, shape.rows); + defer l.deinit(a); + self.uids = try self.put(l.uids); + self.ucount = try self.put(&[1]i32{l.count}); + self.members = try self.put(l.members); + const items = try a.alloc(i32, 3 * ref.maxItems(p)); + defer a.free(items); + const n = l.items(shape.rows, ref.per(self.form), items); + self.items = try self.put(items); + const listed = ref.listed(self.form, shape.rows); + const short: i32 = @intFromBool(self.fault == .short); + self.nitems = try self.put(&[1]i32{(if (listed) n else l.count) - short}); + self.out = try self.rig.output(f.outputs() * 4); + self.base = try self.rig.scratch(f.outputs() * 4); + return true; + } + + /// experts.zig's launch: WideArgs in its add order, items and their count (rows kernel below 17 rows: the groups). + fn launch(self: *Grouped) !void { + const sh = self.fix.?.shape; + const p = self.fix.?.pairs(); + const sk = self.fix.?.sk; + const listed = ref.listed(self.form, sh.rows); + const per = ref.per(self.form); + const x0 = if (self.fault == .swapped) self.x[1] else self.x[0]; + var a: cuda.Args = .{}; + for ([_]u64{ x0, self.x[1], self.tp[0], self.tp[1], self.k2[0], self.k2[1], self.uids, if (listed) self.items else 0, self.nitems, self.members, self.out }) |v| a.add(v); + for ([_]usize{ sh.k, sh.n, p, sk, sh.rows, ref.slots }) |v| a.add(i32s(v)); + const maxu = @min(p, ref.experts); + const gy = if (listed) (p + per - 1) / per + maxu else maxu; + const cols: usize = if (self.form == .wide) 64 else 128; + const f = if (self.form == .wide) self.k.wide else self.k.rows; + try cuda.launch.launch(f, .{ .grid = .{ .x = @intCast(sh.n / cols), .y = @intCast(gy), .z = @intCast(ref.mats(sh) * sk) }, .block = .{ .x = 128 } }, self.rig.s, &a); + } + + pub fn run(self: *Grouped) !void { + try self.launch(); + try self.rig.s.synchronize(); + } + + /// exl3_experts.Experts.run's grouped launch on the same lists: GroupedArgs, one member tile a grid z step. + pub fn replaced(self: *Grouped) ![]const u8 { + const sh = self.fix.?.shape; + const p = self.fix.?.pairs(); + const sk = self.fix.?.sk; + const maxu = @min(p, ref.experts); + const m = ref.mats(sh); + var a: cuda.Args = .{}; + for ([_]u64{ self.x[0], self.x[1], self.tp[0], self.tp[1], self.k2[0], self.k2[1], self.uids, self.ucount, self.members, self.base }) |v| a.add(v); + for ([_]usize{ sh.k, sh.n, p, sk, sh.rows, ref.slots, maxu, m, 0, 0 }) |v| a.add(i32s(v)); + a.add(@as(i32, -1)); + const mt = (sh.rows + 15) / 16; + try cuda.launch.launch(self.k.main.grouped[2], .{ .grid = .{ .x = @intCast(maxu), .y = @intCast(sh.n / 128), .z = @intCast(m * sk * mt) }, .block = .{ .x = 128 } }, self.rig.s, &a); + return self.rig.bytes(self.base, self.outputs() * 4); + } + + /// Gate 1: tf_exl3_grouped_2's bytes, and some output non-finite: the planted values. + pub fn check(self: *Grouped, _: g.Gate) !?[]const u8 { + const a = self.rig.gpu.gpa; + const got = try a.dupe(u8, try self.rig.outputBytes()); + defer a.free(got); + const want = try self.replaced(); + if (std.mem.indexOfDiff(u8, got, want)) |at| return try std.fmt.bufPrint(&self.msg, "byte {d} of {d} differs from tf_exl3_grouped_2's", .{ at, got.len }); + for (0..got.len / 4) |i| if (c.classOf(c.read(.f32, got, i)) != .finite) return null; + return try std.fmt.bufPrint(&self.msg, "no output is non-finite: the planted values prove nothing", .{}); + } + + fn outputs(self: *Grouped) usize { + return self.fix.?.outputs(); + } + + pub fn count(self: *Grouped) usize { + return self.outputs(); + } + + pub fn reference(self: *Grouped, want: []f64, mag: []f64) !void { + return self.fix.?.reference(want, mag); + } + + pub fn simulate(self: *Grouped, acc: c.Accum, order: g.Order, out: []f64) !void { + return self.fix.?.simulate(acc, order, out); + } +}; + +/// Shape: token rows x slots (8) x experts (384); short calls pad members with -1, longer ones list item runs. +fn groupSpec(control: bool) c.Spec { + const served = &[_]c.Shape{ .{ .rows = 8, .n = ref.slots, .k = ref.experts }, .{ .rows = 1, .n = ref.slots, .k = ref.experts }, .{ .rows = 15, .n = ref.slots, .k = ref.experts }, .{ .rows = 16, .n = ref.slots, .k = ref.experts }, .{ .rows = 17, .n = ref.slots, .k = ref.experts }, .{ .rows = 128, .n = ref.slots, .k = ref.experts }, .{ .rows = 511, .n = ref.slots, .k = ref.experts }, .{ .rows = 512, .n = ref.slots, .k = ref.experts }, .{ .rows = 2048, .n = ref.slots, .k = ref.experts } }; + const name = if (control) "inkling2 experts control: tf_ink2x_group listing 16-member runs for the prompt kernel" else "inkling2 experts tf_ink2x_group (tf_exl3_group's lists, then item runs)"; + return .{ .name = name, .accum = .none, .depth = noSums, .out = .raw, .replaces = "tf_exl3_group (main's grouping), the runs its counts give", .nan = .{ .stated = "picks outside [0, experts) are left out, as tf_exl3_group leaves them" }, .tiles = .{ .{ .size = 16 }, .{}, .{} }, .served = served }; +} + +fn noSums(_: c.Shape) usize { + return 0; +} + +/// tf_ink2x_group as experts.run launches it; the baseline runs tf_exl3_group and adds the runs on the host. +pub const Group = struct { + rig: rig_.Rig, + k: *const ink.experts.Kernels, + wrong_run: bool = false, + shape: c.Shape = undefined, + pick: []i32 = &.{}, + dev: u64 = 0, + outs: [5]u64 = @splat(0), // uids, count, members, items, item count + base: [3]u64 = @splat(0), + want: std.ArrayList(u8) = .empty, + msg: [160]u8 = undefined, + + pub fn deinit(self: *Group) void { + const a = self.rig.gpu.gpa; + a.free(self.pick); + self.want.deinit(a); + self.rig.deinit(); + } + + pub fn kernel(self: *Group) g.Kernel { + return .{ .spec = groupSpec(self.wrong_run), .ctx = self, .vt = &vt, .control = if (self.wrong_run) .shapes else null }; + } + + const vt = g.hooks(Group); + + fn maxu(self: *const Group) usize { + return @min(self.shape.rows * ref.slots, ref.experts); + } + + fn sizes(self: *const Group) [5]usize { + const p = self.shape.rows * ref.slots; + return .{ self.maxu() * 4, 4, self.maxu() * self.shape.rows * 4, 3 * ref.maxItems(p) * 4, 4 }; + } + + pub fn prepare(self: *Group, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.rows == 0 or shape.n != ref.slots or shape.k != ref.experts or shape.rows * shape.n * 4 > 64 * 1024) return false; + self.rig.reset(); + const a = self.rig.gpu.gpa; + self.shape = shape; + a.free(self.pick); + self.pick = &.{}; + self.pick = try a.alloc(i32, shape.rows * ref.slots); + var prng = std.Random.DefaultPrng.init(seed); + ref.picks(prng.random(), self.pick); + if (fill == .nonfinite) { + const put = [_]i32{ -1, ref.experts, 1 << 20 }; + for (put, 0..) |v, i| self.pick[(i * 5 + 1) % self.pick.len] = v; + } + self.dev = try self.rig.input(std.mem.sliceAsBytes(self.pick)); + for (&self.outs, self.sizes()) |*o, n| o.* = try self.rig.output(n); + for (&self.base, self.sizes()[0..3]) |*o, n| o.* = try self.rig.scratch(n); + return true; + } + + pub fn run(self: *Group) !void { + const rows = self.shape.rows; + const listed = rows >= ink.experts.listed_from; + const run_: usize = if (rows >= ink.experts.wide_from and !self.wrong_run) 32 else 16; + var b: cuda.Args = .{}; + for ([_]u64{ self.dev, self.outs[0], self.outs[1], self.outs[2], self.outs[3], self.outs[4] }) |v| b.add(v); + for ([_]usize{ rows, ref.slots, ref.experts, rows, if (listed) run_ else 0, @intFromBool(!listed) }) |v| b.add(i32s(v)); + const shared: u32 = @intCast(ref.experts * (32 * 2 + 2 * 4)); + try cuda.launch.launch(self.k.group, .{ .grid = .{ .x = 1 }, .block = .{ .x = 1024 }, .shared = shared }, self.rig.s, &b); + try self.rig.s.synchronize(); + } + + /// tf_exl3_group's lists as written, words no launch writes as the rig poisons them, and the runs from its counts. + pub fn replaced(self: *Group) ![]const u8 { + const a = self.rig.gpu.gpa; + const rows = self.shape.rows; + var m: cuda.Args = .{}; + for ([_]u64{ self.dev, self.base[0], self.base[1], self.base[2] }) |v| m.add(v); + for ([_]usize{ rows, ref.slots, ref.experts, rows }) |v| m.add(i32s(v)); + try cuda.launch.launch(self.k.main.group, .{ .grid = .{ .x = 1 }, .block = .{ .x = 1024 }, .shared = @intCast(rows * ref.slots * 4) }, self.rig.s, &m); + const sz = self.sizes(); + self.want.clearRetainingCapacity(); + try self.want.appendNTimes(a, 0xff, sz[0] + sz[1] + sz[2] + sz[3] + sz[4]); + const w = self.want.items; + const cnt = std.mem.readInt(i32, (try self.rig.bytes(self.base[1], 4))[0..4], .little); + if (cnt < 0 or @as(usize, @intCast(cnt)) > self.maxu()) return error.BadBaselineCount; + const used: usize = @intCast(cnt); + @memcpy(w[0 .. used * 4], (try self.rig.bytes(self.base[0], sz[0]))[0 .. used * 4]); + std.mem.writeInt(i32, w[sz[0]..][0..4], cnt, .little); + const mem = w[sz[0] + 4 ..][0..sz[2]]; + @memcpy(mem[0 .. used * rows * 4], (try self.rig.bytes(self.base[2], sz[2]))[0 .. used * rows * 4]); + if (rows >= ink.experts.listed_from) { + const members = try a.alloc(i32, sz[2] / 4); + defer a.free(members); + @memcpy(std.mem.sliceAsBytes(members), mem); + const l: ref.Lists = .{ .uids = &.{}, .count = cnt, .members = members }; + const items = try a.alloc(i32, sz[3] / 4); + defer a.free(items); + const n = l.items(rows, if (rows >= ink.experts.wide_from) 32 else 16, items); + const start = sz[0] + 4 + sz[2]; + for (items, 0..) |v, i| if (v >= 0) std.mem.writeInt(i32, w[start + 4 * i ..][0..4], v, .little); + std.mem.writeInt(i32, w[start + sz[3] ..][0..4], n, .little); + } + return w; + } + + /// Gate 1: the baseline's bytes with picks outside the experts planted. + pub fn check(self: *Group, _: g.Gate) !?[]const u8 { + const a = self.rig.gpu.gpa; + const got = try a.dupe(u8, try self.rig.outputBytes()); + defer a.free(got); + const want = try self.replaced(); + if (std.mem.indexOfDiff(u8, got, want)) |at| return try std.fmt.bufPrint(&self.msg, "byte {d} of {d} differs from tf_exl3_group's lists and their runs", .{ at, got.len }); + return null; + } + + pub fn count(self: *Group) usize { + var n: usize = 0; + for (self.sizes()) |s| n += s; + return n; + } + + pub fn reference(_: *Group, want: []f64, mag: []f64) !void { + @memset(want, 0); + @memset(mag, 0); + } +}; diff --git a/zig/tests/cuda/contract_inkling2_experts_ref.zig b/zig/tests/cuda/contract_inkling2_experts_ref.zig new file mode 100644 index 00000000000..9549c2b112e --- /dev/null +++ b/zig/tests/cuda/contract_inkling2_experts_ref.zig @@ -0,0 +1,293 @@ +//! Inkling 2's grouped experts on the host: specs, Inkling's routing and trellises, float64 sums, replays. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const ink = @import("inkling2"); + +const fmt = core.exl3_format; +const c = core.contract.spec; +const rows_ = core.contract.rows; + +pub const experts = 384; +pub const slots = 8; // top 8 +pub const hidden = 4608; +pub const width = 1152; // a rank's intermediate at TP=2: 2304 cut in 128-column blocks +const pool = 16; // distinct trellises a shape: expert e's gate takes pool[e % 16], its up pool[(7e + 3) % 16] +const warps = 4; // wide_body's W +const step: f32 = 256; // gate 4's x: multiples of 256 to 8,192, so fp16 sums of the products overflow + +/// The served kernels: decode rows and short windows (128 columns, 16 members), prompt chunks (64 columns, 32). +pub const Form = enum { rows, wide }; +/// Gate 3's planted faults, both launch arguments: the call's last item dropped, the up rows read as gate rows. +pub const Fault = enum { none, short, swapped }; + +/// Half-bits a value of pool entry i: the release's 2- and 3-bit trellises in turn. +pub fn halves(i: usize) u16 { + return if (i % 2 == 0) 4 else 6; +} + +/// exl3_experts.plan's K splits as experts.run takes them: gate and up where K > N, down otherwise. +pub fn split(s: c.Shape) usize { + return cuda.exl3_experts.plan(s.k, s.n, s.k > s.n) catch 1; +} + +/// Gate and up (two matrices, K > N), or down (one). +pub fn mats(s: c.Shape) usize { + return if (s.k > s.n) 2 else 1; +} + +/// Whether a call takes an item list: the prompt kernel always, the rows kernel from experts.listed_from rows. +pub fn listed(form: Form, rows: usize) bool { + return form == .wide or rows >= ink.experts.listed_from; +} + +/// Members a run: the prompt kernel's 32, the rows kernel's 16. +pub fn per(form: Form) usize { + return if (form == .wide) 32 else 16; +} + +/// Items experts.zig makes room for: runs of 16 members, plus one partial run a distinct expert. +pub fn maxItems(p: usize) usize { + return (p + 15) / 16 + @min(p, experts); +} + +/// A split's 16-input mma steps, the 16 products inside one, then the 4 warps' partials added in warp order. +fn depth(s: c.Shape) usize { + return s.k / split(s) / 16 + 16 + warps; +} + +fn served(rows: []const usize, comptime n: usize) [2 * n]c.Shape { + var out: [2 * n]c.Shape = undefined; + for (rows[0..n], 0..) |r, i| { + out[2 * i] = .{ .rows = r, .n = width, .k = hidden }; + out[2 * i + 1] = .{ .rows = r, .n = hidden, .k = width }; + } + return out; +} + +const rows_served = served(&.{ 8, 1, 15, 16, 17, 128, 511 }, 7); +const wide_served = served(&.{ 512, 513, 2048 }, 3); +const rule = "as tf_exl3_grouped_2 gives them: NaN and infinite inputs"; + +pub fn spec(form: Form, fault: Fault) c.Spec { + const name = switch (fault) { + .none => if (form == .rows) "inkling2 experts tf_ink2x_rows (decode rows to 511, 128 columns by 16 members)" else "inkling2 experts tf_ink2x_wide (prompt chunks from 512, 64 columns by 32 members)", + .short => "inkling2 experts control: tf_ink2x_rows launched one item short", + .swapped => "inkling2 experts control: tf_ink2x_wide reading the up rows as gate rows", + }; + const edge: c.Tile = if (form == .rows) .{ .size = 16 } else .{ .size = ink.experts.wide_from, .min = ink.experts.wide_from }; + const tiles = [3]c.Tile{ edge, .{ .size = 128, .step = 128, .min = 128 }, .{ .size = 256, .step = 64, .min = 64 } }; + const list: []const c.Shape = if (form == .rows) &rows_served else &wide_served; + return .{ .name = name, .accum = .f32, .depth = depth, .out = .f32, .replaces = "tf_exl3_grouped_2 (main's grouped experts, mul1)", .nan = .{ .stated = rule }, .tiles = tiles, .served = list, .sums = .{ .exact = false } }; +} + +/// Each row's 8 distinct experts: expert 0 in every row (long runs and a partial one), the rest at random. +pub fn picks(rng: std.Random, out: []i32) void { + for (0..out.len / slots) |r| { + const row = out[r * slots ..][0..slots]; + row[0] = 0; + var i: usize = 1; + while (i < slots) { + const e: i32 = @intCast(rng.uintLessThan(u32, experts)); + if (std.mem.indexOfScalar(i32, row[0..i], e) != null) continue; + row[i] = e; + i += 1; + } + } +} + +/// One projection's host side: the pool's trellises, the pairs' fp16 rows per matrix, each pair's expert. +pub const Fixture = struct { + a: std.mem.Allocator, + shape: c.Shape, + sk: usize, + trellis: [pool][]i16, + x: []u16, // fp16 bits [mats][pairs][k], the rotated rows + pick: []i32, // [pairs]: pair p = row * slots + slot + w: [pool][]f16 = @splat(@as([]f16, &.{})), // each entry's W_q [k][n], decoded on first use + + /// false: a shape the kernels are not built for (plan() finds no split, N not a whole number of 128s). + pub fn valid(s: c.Shape) bool { + if (s.rows == 0 or s.n == 0 or s.k == 0 or s.n % 128 != 0) return false; + _ = cuda.exl3_experts.plan(s.k, s.n, s.k > s.n) catch return false; + return true; + } + + pub fn init(a: std.mem.Allocator, s: c.Shape, fill: rows_.Fill, seed: u64) !Fixture { + var f: Fixture = .{ .a = a, .shape = s, .sk = split(s), .trellis = @splat(@as([]i16, &.{})), .x = &.{}, .pick = &.{} }; + errdefer f.deinit(); + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + for (&f.trellis, 0..) |*t, i| { + t.* = try a.alloc(i16, s.k / 16 * (s.n / 16) * @as(usize, halves(i)) * 8); + for (t.*) |*v| v.* = rng.int(i16); + } + const p = f.pairs(); + f.pick = try a.alloc(i32, p); + picks(rng, f.pick); + f.x = try a.alloc(u16, mats(s) * p * s.k); + for (f.x) |*v| v.* = bits(rng.float(f32) * 4 - 2); + switch (fill) { + .random => {}, + .nonfinite => { + const k = s.k; + const at = [_][2]usize{ .{ 0, k / 3 }, .{ 1, k / 2 }, .{ 2, k - 1 }, .{ 3, 0 }, .{ 3, k - 1 } }; + const put = [_]f32{ std.math.nan(f32), std.math.inf(f32), -std.math.inf(f32), std.math.inf(f32), -std.math.inf(f32) }; + for (at, put) |q, v| if (q[0] < p) { + f.x[q[0] * k + q[1]] = bits(v); + }; + }, + .stress => for (f.x) |*v| { + v.* = bits(step * @as(f32, @floatFromInt(1 + rng.uintLessThan(u32, 32)))); + }, + } + return f; + } + + pub fn deinit(f: *Fixture) void { + for (f.trellis) |t| f.a.free(t); + for (f.w) |w| f.a.free(w); + f.a.free(f.x); + f.a.free(f.pick); + f.* = undefined; + } + + pub fn pairs(f: *const Fixture) usize { + return f.shape.rows * slots; + } + + pub fn outputs(f: *const Fixture) usize { + return mats(f.shape) * f.sk * f.pairs() * f.shape.n; + } + + /// The pool entry matrix `mat` of expert e reads. + pub fn entry(e: usize, mat: usize) usize { + return if (mat == 0) e % pool else (7 * e + 3) % pool; + } + + fn weights(f: *Fixture, i: usize) ![]const f16 { + if (f.w[i].len > 0) return f.w[i]; + const s = f.shape; + f.w[i] = try f.a.alloc(f16, s.k * s.n); + fmt.unpack(.{ .halves = halves(i) }, .mul1, f.trellis[i], s.k / 16, s.n / 16, f.w[i]); + return f.w[i]; + } + + /// The terms output (mat, split, pair, column) sums: x times W_q over the split's K range, in K order. + fn terms(f: *Fixture, mat: usize, sp: usize, p: usize, j: usize, t: []f64) !void { + const s = f.shape; + const e: usize = @intCast(f.pick[p]); + const w = try f.weights(entry(e, mat)); + const per_split = s.k / f.sk; + const x = f.x[(mat * f.pairs() + p) * s.k ..]; + for (t, sp * per_split..) |*o, i| o.* = value(x[i]) * @as(f64, w[i * s.n + j]); + } + + fn each(f: *Fixture, ctx: anytype, comptime body: fn (@TypeOf(ctx), usize, []const f64) void) !void { + const t = try f.a.alloc(f64, f.shape.k / f.sk); + defer f.a.free(t); + for (0..mats(f.shape)) |mat| for (0..f.sk) |sp| for (0..f.pairs()) |p| for (0..f.shape.n) |j| { + try f.terms(mat, sp, p, j, t); + body(ctx, (((mat * f.sk) + sp) * f.pairs() + p) * f.shape.n + j, t); + }; + } + + pub fn reference(f: *Fixture, want: []f64, mag: []f64) !void { + const Ctx = struct { want: []f64, mag: []f64 }; + try f.each(Ctx{ .want = want, .mag = mag }, struct { + fn body(x: Ctx, o: usize, t: []const f64) void { + var sum: f64 = 0; + var abs: f64 = 0; + for (t) |v| { + sum += v; + abs += @abs(v); + } + x.want[o] = sum; + x.mag[o] = abs; + } + }.body); + } + + pub fn simulate(f: *Fixture, acc: c.Accum, order: rows_.Order, out: []f64) !void { + const Ctx = struct { acc: c.Accum, order: rows_.Order, out: []f64 }; + try f.each(Ctx{ .acc = acc, .order = order, .out = out }, struct { + fn body(x: Ctx, o: usize, t: []const f64) void { + x.out[o] = rows_.sumIn(x.acc, x.order, t); + } + }.body); + } +}; + +/// The lists tf_exl3_group writes for `pick`: distinct experts in id order, members row * 32 + slot, -1 after them. +pub const Lists = struct { + uids: []i32, + count: i32, + members: []i32, // [min(pairs, experts)][rows] + + pub fn init(a: std.mem.Allocator, pick: []const i32, rows: usize) !Lists { + const maxu = @min(pick.len, experts); + const uids = try a.alloc(i32, maxu); + errdefer a.free(uids); + const members = try a.alloc(i32, maxu * rows); + @memset(members, -1); + var used: usize = 0; + for (0..experts) |e| { + var m: usize = 0; + for (pick, 0..) |pe, p| if (pe == e) { + members[used * rows + m] = @intCast(p / slots * 32 + p % slots); + m += 1; + }; + if (m == 0) continue; + uids[used] = @intCast(e); + used += 1; + } + return .{ .uids = uids, .count = @intCast(used), .members = members }; + } + + pub fn deinit(l: *Lists, a: std.mem.Allocator) void { + a.free(l.uids); + a.free(l.members); + } + + /// tf_ink2x_group's items for runs of `run` members: (u, first, count) in expert order, -1 words after them. + pub fn items(l: Lists, rows: usize, run: usize, out: []i32) i32 { + @memset(out, -1); + var n: usize = 0; + for (0..@intCast(l.count)) |u| { + const m = l.members[u * rows ..][0..rows]; + const cnt = std.mem.indexOfScalar(i32, m, -1) orelse rows; + var first: usize = 0; + while (first < cnt) : (first += run) { + out[3 * n ..][0..3].* = .{ @intCast(u), @intCast(first), @intCast(@min(run, cnt - first)) }; + n += 1; + } + } + return @intCast(n); + } +}; + +fn bits(v: f32) u16 { + return @bitCast(@as(f16, @floatCast(v))); +} + +fn value(h: u16) f64 { + return @as(f16, @bitCast(h)); +} + +test "inkling2 experts contract: every served shape has a split, items fit experts.zig's room" { + for (rows_served ++ wide_served) |s| { + try std.testing.expect(Fixture.valid(s)); + try std.testing.expectEqual(@as(usize, 0), s.k % (split(s) * 16 * warps)); + } + try std.testing.expectEqual(@as(usize, 4), split(rows_served[0])); + var prng = std.Random.DefaultPrng.init(1); + const pick = try std.testing.allocator.alloc(i32, 2048 * slots); + defer std.testing.allocator.free(pick); + picks(prng.random(), pick); + var l = try Lists.init(std.testing.allocator, pick, 2048); + defer l.deinit(std.testing.allocator); + const out = try std.testing.allocator.alloc(i32, 3 * maxItems(pick.len)); + defer std.testing.allocator.free(out); + try std.testing.expect(l.items(2048, 16, out) <= maxItems(pick.len)); + try std.testing.expectEqual(@as(i32, 0), l.uids[0]); +} diff --git a/zig/tests/cuda/contract_inkling2_experts_vision.zig b/zig/tests/cuda/contract_inkling2_experts_vision.zig new file mode 100644 index 00000000000..976a8ce7448 --- /dev/null +++ b/zig/tests/cuda/contract_inkling2_experts_vision.zig @@ -0,0 +1,275 @@ +//! Inkling 2's tower glue (vision.cu) under the contract: patch rows to the sequence, axial rotary, layer-scaled adds. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const ink = @import("inkling2"); +const rig_ = @import("contract_rig.zig"); +const ref = @import("contract_minimax_glue_ref.zig"); + +const c = core.contract.spec; +const g = core.contract.gates; +const Iv = ref.Iv; +const Sums = ref.Sums; +const Kernels = ink.vision.Kernels; + +const width = ink.vision.width; +const qkv_width = 3 * width; +const pairs = ink.vision.head_dim / 2; +const grid = 1024; // the position table's rows (32 x 32) + +/// Sequence rows R = 4 T + 1 (the class row, then four patches a token): 1, 4, 256, 1,024 and 4,096 tokens. +fn tower(comptime n: usize, comptime k: usize) [5]c.Shape { + var out: [5]c.Shape = undefined; + for (&out, [_]usize{ 17, 5, 1025, 4097, 16385 }) |*s, r| s.* = .{ .rows = r, .n = n, .k = k }; + return out; +} + +const embed_served = tower(width, 4); +const rope_served = tower(qkv_width, 1); +const add_served = tower(width, 1); + +fn four(_: c.Shape) usize { + return 4; +} + +fn launch(f: cuda.Function, s: cuda.Stream, blocks: usize, args: []const u64, tail: ?i64) !void { + var a: cuda.Args = .{}; + for (args) |v| a.add(v); + if (tail) |t| a.add(t); + try cuda.launch.launch(f, .{ .grid = .{ .x = @intCast(blocks) }, .block = .{ .x = 256 } }, s, &a); +} + +/// Row 0 bf16(cls + cls_pos); row r bf16(pe + bf16(sum of four table rows times their bilinear weights, in fp32)). +pub const Embed = struct { + kern: *const Kernels, + late: bool = false, // control: each weight read one tap late + shape: c.Shape = undefined, + pe: []u16 = &.{}, + table: []u16 = &.{}, + taps: []u32 = &.{}, + wts: []f32 = &.{}, + cls: []u16 = &.{}, + pos: []u16 = &.{}, + dev: [6]u64 = @splat(0), + out: u64 = 0, + + pub const sums = {}; + + pub fn spec(self: *const Embed) c.Spec { + const name = if (self.late) "inkling2 experts control: tf_ink2v_embed reading each weight one tap late" else "inkling2 experts vision tf_ink2v_embed (class row, patches plus resampled positions)"; + return .{ .name = name, .accum = .f32, .depth = four, .out = .bf16, .served = &embed_served, .sums = .{ .f16 = 0, .bf16 = 0, .why = "four taps a value, rounded to bf16: no sum long enough to tell fp32 from half" } }; + } + + pub fn control(self: *const Embed) ?g.Gate { + return if (self.late) .shapes else null; + } + + pub fn free(self: *Embed, a: std.mem.Allocator) void { + inline for (.{ "pe", "table", "taps", "wts", "cls", "pos" }) |f| { + a.free(@field(self, f)); + @field(self, f) = &.{}; + } + } + + pub fn prepare(self: *Embed, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { + if (shape.rows < 2 or shape.n != width or shape.k != 4) return false; + self.free(a); + self.shape = shape; + const p = shape.rows - 1; + const stress = fill == .stress; + self.pe = try ref.bfs(a, rng, p * width, -2, 2); + self.table = try ref.bfs(a, rng, grid * width, -1, 1); + self.cls = try ref.bfs(a, rng, width, -1, 1); + self.pos = try ref.bfs(a, rng, width, -1, 1); + self.taps = try a.alloc(u32, p * 4); + self.wts = try a.alloc(f32, p * 4); + for (0..p) |i| { + const x = rng.float(f32); + const y = rng.float(f32); + self.wts[4 * i ..][0..4].* = if (stress) .{ ref.int(rng, 0, 3), ref.int(rng, 0, 3), ref.int(rng, 0, 3), ref.int(rng, 0, 3) } else .{ (1 - x) * (1 - y), x * (1 - y), (1 - x) * y, x * y }; + for (self.taps[4 * i ..][0..4]) |*t| t.* = rng.uintLessThan(u32, grid); + } + if (stress) for ([_][]u16{ self.pe, self.table, self.cls, self.pos }) |v| { + for (v) |*e| e.* = c.toBf16(ref.int(rng, -8, 8)); + }; + if (fill == .nonfinite) { + self.pe[3] = c.toBf16(ref.nan); // patch 0 + self.table[self.taps[4] * width + 5] = c.toBf16(ref.inf); // every patch that taps patch 1's first row + self.cls[7] = c.toBf16(-ref.inf); + if (p > 2) self.pe[2 * width + 9] = c.toBf16(-ref.inf); + } + self.dev = .{ try ref.input(rig, self.pe), try ref.input(rig, self.table), try ref.input(rig, self.taps), try ref.input(rig, self.wts), try ref.input(rig, self.cls), try ref.input(rig, self.pos) }; + self.out = try rig.output(shape.rows * width * 2); + return true; + } + + pub fn run(self: *Embed, rig: *rig_.Rig) !void { + const d = self.dev; + try launch(self.kern.embed, rig.s, self.shape.rows, &.{ d[0], d[1], d[2], d[3] + @as(u64, if (self.late) 4 else 0), d[4], d[5], self.out }, null); + } + + pub fn count(self: *const Embed) usize { + return self.shape.rows * width; + } + + pub fn solve(self: *const Embed, _: std.mem.Allocator, s: Sums, out: []Iv) !void { + var terms: [4]Iv = undefined; + var scratch: [4]f64 = undefined; + for (0..width) |e| out[e] = Iv.of(ref.bf(self.cls[e])).add(Iv.of(ref.bf(self.pos[e]))).bf(); + for (1..self.shape.rows) |r| for (0..width) |e| { + const p = r - 1; + for (&terms, 0..) |*t, i| t.* = Iv.of(ref.bf(self.table[self.taps[4 * p + i] * width + e])).mul(Iv.of(self.wts[4 * p + i])); + const pos = s.sum(&terms, 4, &scratch).bf(); + out[r * width + e] = Iv.of(ref.bf(self.pe[p * width + e])).add(pos).bf(); + }; + } +}; + +/// q and k heads of qkv [R, 3 x 1024] turned in place, pair (2j, 2j + 1) of each head by fp32 cos and sin of row r. +pub const Rope = struct { + kern: *const Kernels, + swapped: bool = false, // control: cos and sin swapped + shape: c.Shape = undefined, + qkv: []u16 = &.{}, + cs: []f32 = &.{}, + sn: []f32 = &.{}, + dev: [2]u64 = @splat(0), + out: u64 = 0, + + pub fn spec(self: *const Rope) c.Spec { + const name = if (self.swapped) "inkling2 experts control: tf_ink2v_rope with cos and sin swapped" else "inkling2 experts vision tf_ink2v_rope (2D rotary of q and k, in place)"; + return .{ .name = name, .accum = .none, .depth = ref.noSums, .out = .bf16, .in_place = true, .served = &rope_served }; + } + + pub fn control(self: *const Rope) ?g.Gate { + return if (self.swapped) .shapes else null; + } + + pub fn free(self: *Rope, a: std.mem.Allocator) void { + a.free(self.qkv); + a.free(self.cs); + a.free(self.sn); + self.qkv = &.{}; + self.cs = &.{}; + self.sn = &.{}; + } + + pub fn prepare(self: *Rope, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { + if (shape.rows == 0 or shape.n != qkv_width) return false; + self.free(a); + self.shape = shape; + const r = shape.rows; + self.qkv = try ref.bfs(a, rng, r * qkv_width, -3, 3); + self.cs = try a.alloc(f32, r * pairs); + self.sn = try a.alloc(f32, r * pairs); + for (self.cs, self.sn) |*x, *y| { + const angle = rng.float(f32) * 64; + x.* = @cos(angle); + y.* = @sin(angle); + } + if (fill == .nonfinite) { + self.qkv[3] = c.toBf16(ref.nan); // row 0, q head 0, pair 1's second value + self.qkv[qkv_width + width + 64 + 10] = c.toBf16(ref.inf); // row 1, k head 1 + self.qkv[2 * qkv_width + 2 * width + 5] = c.toBf16(-ref.inf); // row 2, v: as it is + if (r > 3) self.qkv[3 * qkv_width + 63] = c.toBf16(-ref.inf); + } + self.dev = .{ try ref.input(rig, self.cs), try ref.input(rig, self.sn) }; + self.out = try rig.output(self.qkv.len * 2); + return true; + } + + pub fn run(self: *Rope, rig: *rig_.Rig) !void { + try ref.restore(rig, self.out, std.mem.sliceAsBytes(self.qkv)); // in place: every run from the same rows + const cs = if (self.swapped) self.dev[1] else self.dev[0]; + const sn = if (self.swapped) self.dev[0] else self.dev[1]; + try launch(self.kern.rope, rig.s, self.shape.rows, &.{ self.out, cs, sn }, null); + } + + pub fn count(self: *const Rope) usize { + return self.qkv.len; + } + + pub fn solve(self: *const Rope, _: std.mem.Allocator, _: Sums, out: []Iv) !void { + for (out, self.qkv, 0..) |*o, x, at| { + const col = at % qkv_width; + if (col >= 2 * width) { + o.* = Iv.of(ref.bf(x)); + continue; + } + const d = col % 64; + const first = at - d % 2; + const r = at / qkv_width; + const cv = Iv.of(self.cs[r * pairs + d / 2]); + const sv = Iv.of(self.sn[r * pairs + d / 2]); + const av = Iv.of(ref.bf(self.qkv[first])); + const bv = Iv.of(ref.bf(self.qkv[first + 1])); + o.* = (if (d % 2 == 0) av.mul(cv).add(bv.neg().mul(sv)) else bv.mul(cv).add(av.mul(sv))).bf(); + } + } +}; + +/// x = bf16(x + bf16(gamma[i % 1024] y)) over [R, 1024] in place: torch's `residual + lambda * h` in bf16. +pub const ScaleAdd = struct { + kern: *const Kernels, + late: bool = false, // control: gamma read one column late + shape: c.Shape = undefined, + x: []u16 = &.{}, + y: []u16 = &.{}, + gamma: []u16 = &.{}, + dev: [2]u64 = @splat(0), + out: u64 = 0, + + pub fn spec(self: *const ScaleAdd) c.Spec { + const name = if (self.late) "inkling2 experts control: tf_ink2v_scale_add reading gamma one column late" else "inkling2 experts vision tf_ink2v_scale_add (layer-scaled residual add, in place)"; + return .{ .name = name, .accum = .none, .depth = ref.noSums, .out = .bf16, .in_place = true, .served = &add_served }; + } + + pub fn control(self: *const ScaleAdd) ?g.Gate { + return if (self.late) .shapes else null; + } + + pub fn free(self: *ScaleAdd, a: std.mem.Allocator) void { + a.free(self.x); + a.free(self.y); + a.free(self.gamma); + self.x = &.{}; + self.y = &.{}; + self.gamma = &.{}; + } + + pub fn prepare(self: *ScaleAdd, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { + if (shape.rows == 0 or shape.n != width) return false; + self.free(a); + self.shape = shape; + const n = shape.rows * width; + self.x = try ref.bfs(a, rng, n, -4, 4); + self.y = try ref.bfs(a, rng, n, -4, 4); + self.gamma = try ref.bfs(a, rng, width, -0.5, 0.5); + if (fill == .nonfinite) { + self.x[0] = c.toBf16(ref.nan); + self.y[1] = c.toBf16(ref.inf); + self.gamma[2] = c.toBf16(-ref.inf); // column 2 of every row + self.x[width + 3] = c.toBf16(ref.inf); + } + self.dev = .{ try ref.input(rig, self.y), try ref.input(rig, self.gamma) }; + self.out = try rig.output(n * 2); + return true; + } + + pub fn run(self: *ScaleAdd, rig: *rig_.Rig) !void { + try ref.restore(rig, self.out, std.mem.sliceAsBytes(self.x)); + const n = self.count(); + try launch(self.kern.scale_add, rig.s, (n + 255) / 256, &.{ self.out, self.dev[0], self.dev[1] + @as(u64, if (self.late) 2 else 0) }, @intCast(n)); + } + + pub fn count(self: *const ScaleAdd) usize { + return self.shape.rows * width; + } + + pub fn solve(self: *const ScaleAdd, _: std.mem.Allocator, _: Sums, out: []Iv) !void { + for (out, self.x, self.y, 0..) |*o, x, y, i| { + const scaled = Iv.of(ref.bf(self.gamma[i % width])).mul(Iv.of(ref.bf(y))).bf(); + o.* = Iv.of(ref.bf(x)).add(scaled).bf(); + } + } +}; diff --git a/zig/tests/cuda/contract_inkling2_loop_math.zig b/zig/tests/cuda/contract_inkling2_loop_math.zig new file mode 100644 index 00000000000..bef2f7d69ef --- /dev/null +++ b/zig/tests/cuda/contract_inkling2_loop_math.zig @@ -0,0 +1,479 @@ +//! Mini loop math under the contract, with independent host arithmetic and planted single-fault controls. +const std = @import("std"); +const core = @import("core"); +const ink = @import("inkling2"); +const rig_ = @import("contract_rig.zig"); +const ref = @import("contract_inkling2_ops_ref.zig"); + +const c = core.contract.spec; +const g = core.contract.gates; +const lm = ink.loop_math_cuda; +pub const eps = ref.eps; +pub const mini_h = 2304; + +/// Exact raw-output checks, with interval references and accumulator simulations for gate 4. +pub fn Checked(comptime T: type) type { + return struct { + const Self = @This(); + inner: ref.Gated(T), + rig: *rig_.Rig = undefined, + msg: [200]u8 = undefined, + + pub fn deinit(self: *Self) void { + self.inner.deinit(); + } + + pub fn kernel(self: *Self) g.Kernel { + self.rig = &self.inner.rig; + return .{ .spec = self.inner.k.spec(), .ctx = self, .vt = &vt, .control = self.inner.k.control() }; + } + + const vt = g.hooks(Self); + + pub fn prepare(self: *Self, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + return self.inner.prepare(shape, fill, seed); + } + + pub fn run(self: *Self) !void { + try self.inner.run(); + } + + pub fn count(self: *Self) usize { + return self.inner.count(); + } + + pub fn reference(self: *Self, want: []f64, mag: []f64) !void { + try self.inner.reference(want, mag); + } + + pub fn bounds(self: *Self, want: []const f64, mag: []const f64, allow: []f64) !void { + try self.inner.bounds(want, mag, allow); + } + + pub fn simulate(self: *Self, acc: c.Accum, order: g.Order, out: []f64) !void { + try self.inner.simulate(acc, order, out); + } + + pub fn check(self: *Self, _: g.Gate) !?[]const u8 { + const a = self.rig.gpu.gpa; + const got = try a.dupe(u8, try self.rig.outputBytes()); + defer a.free(got); + return self.inner.k.check(a, got, &self.msg); + } + }; +} + +pub fn queryScale(cols: usize) ref.Iv { + return if (cols == mini_h) ref.Iv.of(scale(cols)) else ref.Iv.of(@floatFromInt(cols)).rsqrt(); +} + +pub fn softmax(logits: []ref.Iv) void { + var m = logits[0]; + for (logits[1..]) |v| m = .{ .m = @max(m.m, v.m), .lo = @max(m.lo, v.lo), .hi = @max(m.hi, v.hi) }; + var den = ref.Iv.of(0); + for (logits) |*v| { + v.* = v.sub(m).exp(); + den = den.add(v.*); + } + for (logits) |*v| v.* = v.div(den); +} + +/// Irregular integer squares stay exact in FP32 for gate 4, but overflow FP16 and round in every BF16 order. +fn stressBank(i: usize) f32 { + return if ((i * 37 + i / 7) % 5 == 0) 384 else 256; +} + +/// Messages nearly cancel two normalized banks; the unmatched first tap keeps FP16 normalization overflow visible. +fn messageStressBank(bank: usize, col: usize, cols: usize) f32 { + if (bank == 0) return stressBank(col); + if (col == 0) return 0; + return -stressBank((col + 1) % cols); +} + +/// AR cyclically assigns [x, -x, 0] over its sources so zero-query outputs expose RMS-sum differences. +pub fn arStressSource(source: usize, col: usize) f32 { + if (source == 0 and col == 0) return 0; + const value = stressBank(col - col % 3); + return switch ((col + 2 * source) % 3) { + 0 => value, + 1 => -value, + 2 => 0, + else => unreachable, + }; +} + +pub fn close(got: f32, want: f32) bool { + if (std.math.isNan(want)) return std.math.isNan(got); + if (!std.math.isFinite(want)) return got == want; + if (!std.math.isFinite(got)) return false; + const tolerance = 1e-4 * (1.0 + @abs(want)); + return @abs(got - want) <= tolerance; +} + +pub fn bf(x: u16) f32 { + return @floatCast(ref.bf(x)); +} + +pub fn bfRound(x: f32) f32 { + return bf(c.toBf16(x)); +} +pub fn cudaMax(a: f32, b: f32) f32 { + if (std.math.isNan(a)) return b; + if (std.math.isNan(b)) return a; + return @max(a, b); +} + +pub fn sameBf(got: u16, want: u16) bool { + if ((want & 0x7fff) > 0x7f80) return (got & 0x7fff) > 0x7f80; // NaN payload is not part of the math rule + return got == want; +} + +pub fn scale(cols: usize) f32 { + return if (cols == mini_h) 1.0 / 48.0 else 1.0 / @sqrt(@as(f32, @floatFromInt(cols))); +} + +fn warp(v: *[32]f32) f32 { + var offset: usize = 16; + while (offset != 0) : (offset >>= 1) { + const old = v.*; + for (0..32) |lane| v.*[lane] = old[lane] + old[lane ^ offset]; + } + return v.*[0]; +} + +/// The exact lane chains and butterfly tree of loop_math.cu. Terms are fused into each lane's accumulator. +pub fn reduce(a: []const f32, b: []const f32, threads: usize) f32 { + var partial: [32]f32 = @splat(0); + for (0..threads / 32) |w| { + var lanes: [32]f32 = undefined; + for (0..32) |lane| { + const tid = w * 32 + lane; + var sum: f32 = 0; + var i = tid; + while (i < a.len) : (i += threads) sum = @mulAdd(f32, a[i], b[i], sum); + lanes[lane] = sum; + } + partial[w] = warp(&lanes); + } + return warp(&partial); +} + +pub fn fail(msg: []u8, comptime fmt: []const u8, args: anytype) !?[]const u8 { + return try std.fmt.bufPrint(msg, fmt, args); +} + +const message_shapes = [_]c.Shape{ + .{ .rows = 1, .n = 4 * 12 * mini_h, .k = mini_h }, + .{ .rows = 16, .n = 4 * 128, .k = 128 }, + .{ .rows = 2048, .n = 4 * 128, .k = 128 }, +}; + +/// Two normalized banks and the checkpoint's even/odd q,mlp and k,v queries, compared element by element. +pub const Messages = struct { + kern: *const lm.Kernels, + aliased: bool = false, + shape: c.Shape = undefined, + banks: [2][]u16 = .{ &.{}, &.{} }, + queries: [2][]f32 = .{ &.{}, &.{} }, + dev: [5]u64 = @splat(0), + out: u64 = 0, + + pub fn spec(self: *const Messages) c.Spec { + return .{ .name = if (self.aliased) "control: inkling2 loop messages with both previous-pass inputs wired to bank zero" else "inkling2 loop tf_ink2_loop_messages (two normalized banks, post-dot 1/48, four roles)", .accum = .f32, .depth = depth, .out = .f32, .served = if (self.aliased) message_shapes[0..2] else &message_shapes }; + } + + fn depth(s: c.Shape) usize { + return 2 * ((s.k + 255) / 256 + 10); + } + + pub fn control(self: *const Messages) ?g.Gate { + return if (self.aliased) .shapes else null; + } + + pub fn free(self: *Messages, a: std.mem.Allocator) void { + for (&self.banks) |*x| a.free(x.*); + for (&self.queries) |*x| a.free(x.*); + self.banks = .{ &.{}, &.{} }; + self.queries = .{ &.{}, &.{} }; + } + + pub fn prepare(self: *Messages, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { + if (shape.rows == 0 or shape.k == 0 or shape.n % (4 * shape.k) != 0) return false; + self.free(a); + self.shape = shape; + const cols = shape.k; + const layers = shape.n / (4 * cols); + for (&self.banks, 0..) |*x, bank| { + x.* = try a.alloc(u16, shape.rows * cols); + if (fill == .stress) { + for (x.*, 0..) |*v, i| v.* = c.toBf16(messageStressBank(bank, i % cols, cols)); + } else for (x.*) |*v| v.* = c.toBf16(rng.float(f32) * 2 - 1); + } + for (&self.queries) |*x| { + x.* = try ref.f32s(a, rng, 2 * layers * cols, -0.25, 0.25); + if (fill == .stress) @memset(x.*, 0); + } + if (fill == .nonfinite) { + ref.plant(u16, self.banks[0], shape.rows, cols, ref.asBf); + ref.plant(u16, self.banks[1], shape.rows, cols, ref.asBf); + } + for (self.banks, 0..) |x, i| self.dev[i] = try ref.input(rig, x); + for (self.queries, 0..) |x, i| self.dev[2 + i] = try ref.input(rig, x); + self.out = try rig.output(shape.rows * shape.n * 4); + return true; + } + + pub fn run(self: *Messages, rig: *rig_.Rig) !void { + const b1 = if (self.aliased) self.dev[0] else self.dev[1]; + const layers = self.shape.n / (4 * self.shape.k); + try lm.messages(self.kern, rig.s, self.dev[0], b1, self.dev[2], self.dev[3], self.out, self.shape.rows, layers, self.shape.k, eps); + } + + pub fn count(self: *const Messages) usize { + return self.shape.rows * self.shape.n; + } + + pub fn solve(self: *const Messages, a: std.mem.Allocator, s: ref.Sums, out: []ref.Iv) !void { + const cols = self.shape.k; + const layers = self.shape.n / (4 * cols); + const terms = try a.alloc(ref.Iv, cols); + defer a.free(terms); + const scratch = try a.alloc(f64, cols); + defer a.free(scratch); + const later = ref.later(s); + for (0..self.shape.rows) |row| { + var inv: [2]ref.Iv = undefined; + for (0..2) |b| { + for (terms, self.banks[b][row * cols ..][0..cols]) |*t, v| { + const x = ref.Iv.of(ref.bf(v)); + t.* = x.mul(x); + } + inv[b] = ref.rms(s.sum(terms, depth(self.shape), scratch), cols, eps); + } + for (0..layers) |j| for (0..4) |role| { + const query = self.queries[if (role == 0 or role == 3) 0 else 1][(2 * j + @intFromBool(role >= 2)) * cols ..][0..cols]; + var logits: [2]ref.Iv = undefined; + for (0..2) |b| { + for (terms, query, self.banks[b][row * cols ..][0..cols]) |*t, q, v| t.* = ref.Iv.of(q).mul(ref.Iv.of(ref.bf(v)).mul(inv[b])); + logits[b] = later.sum(terms, depth(self.shape), scratch).mul(queryScale(cols)); + } + softmax(&logits); + for (0..cols) |i| { + var value = ref.Iv.of(0); + for (0..2) |b| { + const beta = ref.Iv.of(ref.bf(self.banks[b][row * cols + i])).mul(inv[b]); + value = value.add(logits[b].mul(beta)); + } + const at = ((j * 4 + role) * self.shape.rows + row) * cols + i; + out[at] = value; + } + }; + } + } + + pub fn check(self: *const Messages, a: std.mem.Allocator, got: []const u8, msg: []u8) !?[]const u8 { + const cols = self.shape.k; + const layers = self.shape.n / (4 * cols); + const raw0 = try a.alloc(f32, cols); + defer a.free(raw0); + const raw1 = try a.alloc(f32, cols); + defer a.free(raw1); + const beta0 = try a.alloc(f32, cols); + defer a.free(beta0); + const beta1 = try a.alloc(f32, cols); + defer a.free(beta1); + for (0..self.shape.rows) |row| { + for (raw0, self.banks[0][row * cols ..][0..cols]) |*x, v| x.* = bf(v); + for (raw1, self.banks[1][row * cols ..][0..cols]) |*x, v| x.* = bf(v); + const inv0 = 1.0 / @sqrt(reduce(raw0, raw0, 256) / @as(f32, @floatFromInt(cols)) + eps); + const inv1 = 1.0 / @sqrt(reduce(raw1, raw1, 256) / @as(f32, @floatFromInt(cols)) + eps); + for (beta0, raw0) |*x, v| x.* = v * inv0; + for (beta1, raw1) |*x, v| x.* = v * inv1; + for (0..layers) |j| for (0..4) |role| { + const query = self.queries[if (role == 0 or role == 3) 0 else 1][(2 * j + @intFromBool(role >= 2)) * cols ..][0..cols]; + const l0 = reduce(query, beta0, 256) * scale(cols); + const l1 = reduce(query, beta1, 256) * scale(cols); + const m = cudaMax(l0, l1); + const e0 = @exp(l0 - m); + const e1 = @exp(l1 - m); + const den = e0 + e1; + const w0 = e0 / den; + const w1 = e1 / den; + for (0..cols) |i| { + const want = w0 * beta0[i] + w1 * beta1[i]; + const at = ((j * 4 + role) * self.shape.rows + row) * cols + i; + const value = ref.readF32(got, at); + if (!close(value, want)) return fail(msg, "row {d} core {d} role {d} col {d}: {e} where {e} is due", .{ row, j, role, i, value, want }); + } + }; + } + return null; + } +}; + +const gate_shapes = [_]c.Shape{ + .{ .rows = 1, .n = mini_h, .k = 2 * mini_h }, + .{ .rows = 16, .n = mini_h, .k = 2 * mini_h }, + .{ .rows = 2048, .n = 128, .k = 256 }, +}; + +/// Host reference preserves BF16 n/zeta and all four FP32 output steps; control substitutes F for Gain. +pub const Gate = struct { + kern: *const lm.Kernels, + wrong_gain: bool = false, + shape: c.Shape = undefined, + h: []f32 = &.{}, + m: []f32 = &.{}, + d: []u16 = &.{}, + f: []u16 = &.{}, + gain: []u16 = &.{}, + dev: [5]u64 = @splat(0), + out: u64 = 0, + + pub fn spec(self: *const Gate) c.Spec { + return .{ .name = if (self.wrong_gain) "control: inkling2 loop rank-64 gate with forget weights again instead of gain" else "inkling2 loop tf_ink2_loop_gate (BF16 down input/result, FP32 F/G tanh and four output steps)", .accum = .f32, .depth = depth, .out = .f32, .served = if (self.wrong_gain) gate_shapes[0..2] else &gate_shapes }; + } + + fn depth(s: c.Shape) usize { + return (s.k + 255) / 256 + 10 + lm.rank; + } + + pub fn control(self: *const Gate) ?g.Gate { + return if (self.wrong_gain) .shapes else null; + } + + pub fn free(self: *Gate, a: std.mem.Allocator) void { + a.free(self.h); + a.free(self.m); + a.free(self.d); + a.free(self.f); + a.free(self.gain); + self.h = &.{}; + self.m = &.{}; + self.d = &.{}; + self.f = &.{}; + self.gain = &.{}; + } + + pub fn prepare(self: *Gate, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { + if (shape.rows == 0 or shape.n == 0 or shape.k != 2 * shape.n) return false; + self.free(a); + self.shape = shape; + const cols = shape.n; + self.h = try ref.f32s(a, rng, shape.rows * cols, -1, 1); + self.m = try ref.f32s(a, rng, shape.rows * cols, -1, 1); + self.d = try ref.bfs(a, rng, lm.rank * 2 * cols, -0.1, 0.1); + self.f = try ref.bfs(a, rng, cols * lm.rank, -0.2, 0.2); + self.gain = try ref.bfs(a, rng, cols * lm.rank, -0.2, 0.2); + if (fill == .stress) { + for (self.h, 0..) |*v, i| v.* = stressBank(i % cols); + for (self.m, 0..) |*v, i| v.* = stressBank(i % cols); + for (self.d) |*v| v.* = c.toBf16(ref.int(rng, -8, 8)); + for (self.f) |*v| v.* = c.toBf16(ref.int(rng, -8, 8)); + for (self.gain) |*v| v.* = c.toBf16(ref.int(rng, -8, 8)); + } + if (fill == .nonfinite) { + ref.plant(f32, self.h, shape.rows, cols, ref.asF32); + ref.plant(f32, self.m, shape.rows, cols, ref.asF32); + } + self.dev = .{ try ref.input(rig, self.h), try ref.input(rig, self.m), try ref.input(rig, self.d), try ref.input(rig, self.f), try ref.input(rig, self.gain) }; + self.out = try rig.output(shape.rows * cols * 4); + return true; + } + + pub fn run(self: *Gate, rig: *rig_.Rig) !void { + try lm.gate(self.kern, rig.s, self.dev[0], self.dev[1], self.dev[2], self.dev[3], if (self.wrong_gain) self.dev[3] else self.dev[4], self.out, self.shape.rows, self.shape.n, eps); + } + + pub fn count(self: *const Gate) usize { + return self.shape.rows * self.shape.n; + } + + pub fn solve(self: *const Gate, a: std.mem.Allocator, s: ref.Sums, out: []ref.Iv) !void { + const cols = self.shape.n; + const n = try a.alloc(ref.Iv, 2 * cols); + defer a.free(n); + const terms = try a.alloc(ref.Iv, 2 * cols); + defer a.free(terms); + const scratch = try a.alloc(f64, 2 * cols); + defer a.free(scratch); + const zeta = try a.alloc(ref.Iv, lm.rank); + defer a.free(zeta); + const later = ref.later(s); + const zeta_depth = (2 * cols + 31) / 32 + 5; + for (0..self.shape.rows) |row| { + const h = self.h[row * cols ..][0..cols]; + const m = self.m[row * cols ..][0..cols]; + var inv: [2]ref.Iv = undefined; + for (0..2) |b| { + const x = if (b == 0) h else m; + for (terms[0..cols], x) |*t, v| { + const e = ref.Iv.of(v); + t.* = e.mul(e); + } + inv[b] = ref.rms(s.sum(terms[0..cols], depth(self.shape), scratch), cols, eps); + } + for (n[0..cols], h) |*v, x| v.* = ref.Iv.of(x).mul(inv[0]).bf(); + for (n[cols..], m) |*v, x| v.* = ref.Iv.of(x).mul(inv[1]).bf(); + for (0..lm.rank) |r| { + for (terms, n, self.d[r * 2 * cols ..][0 .. 2 * cols]) |*t, x, w| t.* = ref.Iv.of(ref.bf(w)).mul(x); + zeta[r] = later.sum(terms, zeta_depth, scratch).bf(); + } + for (0..cols) |i| { + for (terms[0..lm.rank], zeta, self.f[i * lm.rank ..][0..lm.rank]) |*t, z, w| t.* = ref.Iv.of(ref.bf(w)).mul(z); + const forget = ref.tanh(later.sum(terms[0..lm.rank], lm.rank, scratch)); + for (terms[0..lm.rank], zeta, self.gain[i * lm.rank ..][0..lm.rank]) |*t, z, w| t.* = ref.Iv.of(ref.bf(w)).mul(z); + const gain = ref.tanh(later.sum(terms[0..lm.rank], lm.rank, scratch)); + const keep = ref.Iv.of(1).sub(forget); + const old = keep.mul(ref.Iv.of(h[i])); + const added = gain.mul(ref.Iv.of(m[i])); + out[row * cols + i] = old.add(added); + } + } + } + + pub fn check(self: *const Gate, a: std.mem.Allocator, got: []const u8, msg: []u8) !?[]const u8 { + const cols = self.shape.n; + const n = try a.alloc(f32, 2 * cols); + defer a.free(n); + const weights = try a.alloc(f32, 2 * cols); + defer a.free(weights); + const zeta = try a.alloc(f32, lm.rank); + defer a.free(zeta); + const zf = try a.alloc(f32, lm.rank); + defer a.free(zf); + const zg = try a.alloc(f32, lm.rank); + defer a.free(zg); + for (0..self.shape.rows) |row| { + const h = self.h[row * cols ..][0..cols]; + const m = self.m[row * cols ..][0..cols]; + const ih = 1.0 / @sqrt(reduce(h, h, 256) / @as(f32, @floatFromInt(cols)) + eps); + const im = 1.0 / @sqrt(reduce(m, m, 256) / @as(f32, @floatFromInt(cols)) + eps); + for (n[0..cols], h) |*v, x| v.* = bfRound(x * ih); + for (n[cols..], m) |*v, x| v.* = bfRound(x * im); + for (0..lm.rank) |r| { + for (weights, self.d[r * 2 * cols ..][0 .. 2 * cols]) |*v, w| v.* = bf(w); + zeta[r] = bfRound(reduce(weights, n, 256)); + } + for (0..cols) |i| { + for (zf, self.f[i * lm.rank ..][0..lm.rank]) |*v, w| v.* = bf(w); + for (zg, self.gain[i * lm.rank ..][0..lm.rank]) |*v, w| v.* = bf(w); + var sf: f32 = 0; + var sg: f32 = 0; + for (0..lm.rank) |r| { + sf = @mulAdd(f32, zf[r], zeta[r], sf); + sg = @mulAdd(f32, zg[r], zeta[r], sg); + } + const forget = std.math.tanh(sf); + const gain = std.math.tanh(sg); + const keep: f32 = 1.0 - forget; + const old: f32 = keep * h[i]; + const added: f32 = gain * m[i]; + const want: f32 = old + added; + const value = ref.readF32(got, row * cols + i); + if (!close(value, want)) return fail(msg, "row {d} col {d}: {e} where {e} is due", .{ row, i, value, want }); + } + } + return null; + } +}; diff --git a/zig/tests/cuda/contract_inkling2_loop_math_extra.zig b/zig/tests/cuda/contract_inkling2_loop_math_extra.zig new file mode 100644 index 00000000000..49bd3ae650e --- /dev/null +++ b/zig/tests/cuda/contract_inkling2_loop_math_extra.zig @@ -0,0 +1,426 @@ +//! Mini QKV projection, raw AR and BF16 tap rounding, with the loop suites' shared registration. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const check = @import("check.zig"); +const ink = @import("inkling2"); +const rig_ = @import("contract_rig.zig"); +const ref = @import("contract_inkling2_ops_ref.zig"); +const base = @import("contract_inkling2_loop_math.zig"); + +const c = core.contract.spec; +const g = core.contract.gates; +const lm = ink.loop_math_cuda; +const K = base.Checked; +const eps = base.eps; +const mini_h = base.mini_h; +const queryScale = base.queryScale; +const softmax = base.softmax; +const arStressSource = base.arStressSource; +const close = base.close; +const bf = base.bf; +const bfRound = base.bfRound; +const cudaMax = base.cudaMax; +const sameBf = base.sameBf; +const scale = base.scale; +const reduce = base.reduce; +const fail = base.fail; +const Messages = base.Messages; +const Gate = base.Gate; +const qkv_shapes = [_]c.Shape{ + .{ .rows = 1, .n = 3072, .k = mini_h }, + .{ .rows = 16, .n = 384, .k = 128 }, + .{ .rows = 2048, .n = 384, .k = 128 }, +}; + +/// Distinct q/k/v rows, with the Small single-input aliasing bug planted as the control. +pub const ProjectQkv = struct { + kern: *const lm.Kernels, + shared_input: bool = false, + shape: c.Shape = undefined, + u: [3][]u16 = .{ &.{}, &.{}, &.{} }, + w: [3][]u16 = .{ &.{}, &.{}, &.{} }, + dev: [6]u64 = @splat(0), + out: [3]u64 = @splat(0), + + pub fn spec(self: *const ProjectQkv) c.Spec { + return .{ .name = if (self.shared_input) "control: Mini split QKV projection using Small's one normalized input for all roles" else "inkling2 loop tf_ink2_loop_project_qkv (distinct normalized q/k/v inputs, unchanged raw layouts)", .accum = .f32, .depth = depth, .out = .bf16, .served = if (self.shared_input) qkv_shapes[0..2] else &qkv_shapes }; + } + + fn depth(s: c.Shape) usize { + return s.k; + } + + pub fn control(self: *const ProjectQkv) ?g.Gate { + return if (self.shared_input) .shapes else null; + } + + pub fn free(self: *ProjectQkv, a: std.mem.Allocator) void { + for (&self.u) |*x| a.free(x.*); + for (&self.w) |*x| a.free(x.*); + self.u = .{ &.{}, &.{}, &.{} }; + self.w = .{ &.{}, &.{}, &.{} }; + } + + pub fn prepare(self: *ProjectQkv, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { + if (shape.rows == 0 or shape.n == 0 or shape.n % 3 != 0 or shape.k == 0) return false; + self.free(a); + self.shape = shape; + for (&self.u) |*x| x.* = try ref.bfs(a, rng, shape.rows * shape.k, -1, 1); + for (&self.w, 0..) |*x, role| x.* = try ref.bfs(a, rng, (if (role == 0) shape.n else shape.n / 3) * shape.k, -0.1, 0.1); + if (fill == .stress) { + // Mirrored products cancel to eight small FP32 terms; lower precisions lose their large partials. + const half = shape.k / 2; + for (self.u) |bank| for (0..shape.rows) |row| { + const values = bank[row * shape.k ..][0..shape.k]; + for (0..half) |i| { + values[i] = c.toBf16(ref.int(rng, 8, 16)); + values[half + i] = values[i]; + } + if (shape.k % 2 != 0) values[shape.k - 1] = 0; + }; + for (self.w) |bank| for (0..bank.len / shape.k) |row| { + const values = bank[row * shape.k ..][0..shape.k]; + for (0..half) |i| { + const v = ref.int(rng, 8, 16); + values[i] = c.toBf16(v); + values[half + i] = c.toBf16(-v); + } + for (0..@min(8, half)) |i| values[half + i] = c.toBf16(1 - bf(values[i])); + if (shape.k % 2 != 0) values[shape.k - 1] = 0; + }; + } + if (fill == .nonfinite) for (&self.u) |*x| ref.plant(u16, x.*, shape.rows, shape.k, ref.asBf); + for (self.u, 0..) |x, i| self.dev[i] = try ref.input(rig, x); + for (self.w, 0..) |x, i| self.dev[3 + i] = try ref.input(rig, x); + for (0..3) |role| self.out[role] = try rig.output(shape.rows * (if (role == 0) shape.n else shape.n / 3) * 2); + return true; + } + + pub fn run(self: *ProjectQkv, rig: *rig_.Rig) !void { + const k = if (self.shared_input) self.dev[0] else self.dev[1]; + const v = if (self.shared_input) self.dev[0] else self.dev[2]; + try lm.projectQkv(self.kern, rig.s, self.dev[0], k, v, self.dev[3], self.dev[4], self.dev[5], self.out[0], self.out[1], self.out[2], self.shape.rows, self.shape.k, self.shape.n, self.shape.n / 3); + } + + pub fn count(self: *const ProjectQkv) usize { + return self.shape.rows * self.shape.n * 5 / 3; + } + + pub fn solve(self: *const ProjectQkv, a: std.mem.Allocator, s: ref.Sums, out: []ref.Iv) !void { + const cols = self.shape.k; + const terms = try a.alloc(ref.Iv, cols); + defer a.free(terms); + const scratch = try a.alloc(f64, cols); + defer a.free(scratch); + var offset: usize = 0; + for (0..3) |role| { + const width = if (role == 0) self.shape.n else self.shape.n / 3; + for (0..self.shape.rows) |row| for (0..width) |j| { + for (terms, self.u[role][row * cols ..][0..cols], self.w[role][j * cols ..][0..cols]) |*t, x, w| t.* = ref.Iv.of(ref.bf(x) * ref.bf(w)); + out[offset + row * width + j] = s.sum(terms, depth(self.shape), scratch).bf(); + }; + offset += self.shape.rows * width; + } + } + + pub fn check(self: *const ProjectQkv, a: std.mem.Allocator, got: []const u8, msg: []u8) !?[]const u8 { + const cols = self.shape.k; + const x = try a.alloc(f32, cols); + defer a.free(x); + const w = try a.alloc(f32, cols); + defer a.free(w); + var byte_at: usize = 0; + for (0..3) |role| { + const width = if (role == 0) self.shape.n else self.shape.n / 3; + for (0..self.shape.rows) |row| for (0..width) |j| { + for (x, self.u[role][row * cols ..][0..cols]) |*v, u| v.* = bf(u); + for (w, self.w[role][j * cols ..][0..cols]) |*v, u| v.* = bf(u); + var sum: f32 = 0; + for (0..cols) |i| sum = @mulAdd(f32, x[i], w[i], sum); + const want = c.toBf16(sum); + const at = byte_at + (row * width + j) * 2; + const value = std.mem.readInt(u16, got[at..][0..2], .little); + if (!sameBf(value, want)) return fail(msg, "role {d} row {d} output {d}: {x} where {x} is due", .{ role, row, j, value, want }); + }; + byte_at += self.shape.rows * width * 2; + } + return null; + } +}; + +const ar_shapes = [_]c.Shape{ + .{ .rows = 1, .n = mini_h, .k = 1 }, + .{ .rows = 16, .n = 128, .k = 3 }, + .{ .rows = 2048, .n = 128, .k = 3 }, +}; + +/// Raw AR before controllers. Two completed blocks plus a partial; control omits the second completed block. +pub const Ar = struct { + kern: *const lm.Kernels, + partial_bf16: bool, + short: bool = false, + shape: c.Shape = undefined, + blocks: [2][]u16 = .{ &.{}, &.{} }, + partial32: []f32 = &.{}, + partial16: []u16 = &.{}, + query: []f32 = &.{}, + dev: [4]u64 = @splat(0), // two blocks, partial, query + out: u64 = 0, + + pub fn spec(self: *const Ar) c.Spec { + return .{ .name = if (self.short) "control: inkling2 loop raw AR omitting its second completed block" else if (self.partial_bf16) "inkling2 loop tf_ink2_loop_ar (BF16 partial, FP32 unnormalized output)" else "inkling2 loop tf_ink2_loop_ar (FP32 partial, FP32 unnormalized output)", .accum = .f32, .depth = depth, .out = .f32, .served = if (self.short) ar_shapes[1..2] else &ar_shapes }; + } + + fn depth(s: c.Shape) usize { + return (s.n + 511) / 512 + 10 + 3; + } + + pub fn control(self: *const Ar) ?g.Gate { + return if (self.short) .shapes else null; + } + + pub fn free(self: *Ar, a: std.mem.Allocator) void { + for (&self.blocks) |*x| a.free(x.*); + a.free(self.partial32); + a.free(self.partial16); + a.free(self.query); + self.blocks = .{ &.{}, &.{} }; + self.partial32 = &.{}; + self.partial16 = &.{}; + self.query = &.{}; + } + + pub fn prepare(self: *Ar, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { + if (shape.rows == 0 or shape.n == 0 or shape.k == 0 or shape.k > lm.max_queries) return false; + self.free(a); + self.shape = shape; + for (&self.blocks, 0..) |*x, source| { + x.* = try ref.bfs(a, rng, shape.rows * shape.n, -1, 1); + if (fill == .stress) { + for (x.*, 0..) |*v, i| v.* = c.toBf16(arStressSource(source, i % shape.n)); + } + } + if (self.partial_bf16) { + self.partial16 = try ref.bfs(a, rng, shape.rows * shape.n, -1, 1); + if (fill == .stress) { + for (self.partial16, 0..) |*v, i| v.* = c.toBf16(arStressSource(2, i % shape.n)); + } + self.dev[2] = try ref.input(rig, self.partial16); + } else { + self.partial32 = try ref.f32s(a, rng, shape.rows * shape.n, -1, 1); + if (fill == .stress) { + for (self.partial32, 0..) |*v, i| v.* = arStressSource(2, i % shape.n); + } + self.dev[2] = try ref.input(rig, self.partial32); + } + self.query = try ref.f32s(a, rng, shape.k * shape.n, -0.25, 0.25); + if (fill == .stress) @memset(self.query, 0); + if (fill == .nonfinite) for (&self.blocks) |*x| ref.plant(u16, x.*, shape.rows, shape.n, ref.asBf); + for (self.blocks, 0..) |x, i| self.dev[i] = try ref.input(rig, x); + self.dev[3] = try ref.input(rig, self.query); + self.out = try rig.output(shape.rows * shape.n * shape.k * 4); + return true; + } + + pub fn run(self: *Ar, rig: *rig_.Rig) !void { + var args: lm.ArArgs = .{ .partial = self.dev[2], .query = self.dev[3], .out = self.out, .n_blocks = if (self.short) 1 else 2, .partial_bf16 = @intFromBool(self.partial_bf16), .nq = @intCast(self.shape.k), .rows = @intCast(self.shape.rows), .c = @intCast(self.shape.n), .eps = eps }; + args.blocks[0] = self.dev[0]; + args.blocks[1] = self.dev[1]; + try lm.ar(self.kern, rig.s, args); + } + + pub fn count(self: *const Ar) usize { + return self.shape.rows * self.shape.n * self.shape.k; + } + + fn entry(self: *const Ar, source: usize, row: usize, col: usize) f32 { + const at = row * self.shape.n + col; + return if (source < 2) bf(self.blocks[source][at]) else if (self.partial_bf16) bf(self.partial16[at]) else self.partial32[at]; + } + + pub fn solve(self: *const Ar, a: std.mem.Allocator, s: ref.Sums, out: []ref.Iv) !void { + const cols = self.shape.n; + const terms = try a.alloc(ref.Iv, cols); + defer a.free(terms); + const scratch = try a.alloc(f64, cols); + defer a.free(scratch); + for (0..self.shape.rows) |row| { + var inv: [3]ref.Iv = undefined; + for (0..3) |j| { + for (terms, 0..) |*t, i| { + const x = ref.Iv.of(self.entry(j, row, i)); + t.* = x.mul(x); + } + inv[j] = ref.rms(s.sum(terms, depth(self.shape), scratch), cols, eps); + } + for (0..self.shape.k) |q| { + var logits: [3]ref.Iv = undefined; + for (0..3) |j| { + for (terms, 0..) |*t, i| t.* = ref.Iv.of(self.entry(j, row, i)).mul(inv[j]).mul(ref.Iv.of(self.query[q * cols + i])); + logits[j] = s.sum(terms, depth(self.shape), scratch).mul(queryScale(cols)); + } + softmax(&logits); + for (0..cols) |i| { + var value = ref.Iv.of(0); + for (0..3) |j| { + const beta = ref.Iv.of(self.entry(j, row, i)).mul(inv[j]); + value = value.add(logits[j].mul(beta)); + } + out[(q * self.shape.rows + row) * cols + i] = value; + } + } + } + } + + pub fn check(self: *const Ar, a: std.mem.Allocator, got: []const u8, msg: []u8) !?[]const u8 { + const cols = self.shape.n; + const sources = 3; + const raw = try a.alloc(f32, cols); + defer a.free(raw); + const beta = try a.alloc(f32, sources * cols); + defer a.free(beta); + const weights = try a.alloc(f32, sources); + defer a.free(weights); + for (0..self.shape.rows) |row| { + var invs: [3]f32 = undefined; + for (0..sources) |j| { + for (raw, 0..) |*v, i| v.* = self.entry(j, row, i); + invs[j] = 1.0 / @sqrt(reduce(raw, raw, 512) / @as(f32, @floatFromInt(cols)) + eps); + for (beta[j * cols ..][0..cols], raw) |*v, x| v.* = x * invs[j]; + } + for (0..self.shape.k) |q| { + var logits: [3]f32 = undefined; + var m = -std.math.inf(f32); + for (0..sources) |j| { + const query = self.query[q * cols ..][0..cols]; + logits[j] = reduce(query, beta[j * cols ..][0..cols], 512) * scale(cols); + m = cudaMax(m, logits[j]); + } + var den: f32 = 0; + for (0..sources) |j| { + weights[j] = @exp(logits[j] - m); + den += weights[j]; + } + for (0..sources) |j| weights[j] /= den; + for (0..cols) |i| { + var want: f32 = 0; + for (0..sources) |j| want = @mulAdd(f32, weights[j], beta[j * cols + i], want); + const at = (q * self.shape.rows + row) * cols + i; + const value = ref.readF32(got, at); + if (!close(value, want)) return fail(msg, "query {d} row {d} col {d}: {e} where {e} is due", .{ q, row, i, value, want }); + } + } + } + return null; + } +}; + +test "AR normalizes each FP32 query term before reduction and scales after its dot" { + const source = [_]f32{ + @bitCast(@as(u32, 0x3f800008)), @bitCast(@as(u32, 0x3f800001)), + @bitCast(@as(u32, 0x40400001)), 0, + }; + const query = [_]f32{ + @bitCast(@as(u32, 0x3f800010)), @bitCast(@as(u32, 0x3fffffff)), + @bitCast(@as(u32, 0xc0000001)), 0, + }; + const inv: f32 = @bitCast(@as(u32, 0x3f800001)); + var normalized: [4]f32 = undefined; + for (&normalized, source) |*v, x| v.* = x * inv; + const dot = reduce(&query, &normalized, 512); + const old = reduce(&query, &source, 512) * inv * scale(source.len); + const scaled = dot * scale(source.len); + try std.testing.expectEqual(@as(u32, 0xbfbffffb), @as(u32, @bitCast(scaled))); + try std.testing.expectEqual(@as(u32, 0xbfbffffa), @as(u32, @bitCast(old))); +} + +const round_shapes = [_]c.Shape{ + .{ .rows = 1, .n = mini_h, .k = 1 }, + .{ .rows = 2048, .n = 32, .k = 1 }, +}; + +/// Dynamic taps' required BF16 storage rounding, followed by exact widening for the FP32 convolution. +pub const RoundBf16 = struct { + kern: *const lm.Kernels, + short: bool = false, + shape: c.Shape = undefined, + x: []f32 = &.{}, + dev: u64 = 0, + out: u64 = 0, + + pub fn spec(self: *const RoundBf16) c.Spec { + return .{ .name = if (self.short) "control: inkling2 loop dynamic taps leave the final value unrounded" else "inkling2 loop tf_ink2_loop_round_bf16 (global dynamic taps, BF16 then FP32)", .accum = .none, .depth = ref.noSums, .out = .f32, .served = if (self.short) round_shapes[0..1] else &round_shapes }; + } + + pub fn control(self: *const RoundBf16) ?g.Gate { + return if (self.short) .shapes else null; + } + + pub fn free(self: *RoundBf16, a: std.mem.Allocator) void { + a.free(self.x); + self.x = &.{}; + } + + pub fn prepare(self: *RoundBf16, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { + if (shape.rows == 0 or shape.n == 0) return false; + self.free(a); + self.shape = shape; + self.x = try ref.f32s(a, rng, shape.rows * shape.n, -32, 32); + if (fill == .nonfinite) ref.plant(f32, self.x, shape.rows, shape.n, ref.asF32); + self.dev = try ref.input(rig, self.x); + self.out = try rig.output(self.x.len * 4); + return true; + } + + pub fn run(self: *RoundBf16, rig: *rig_.Rig) !void { + try lm.roundBf16(self.kern, rig.s, self.dev, self.out, self.x.len - @intFromBool(self.short)); + } + + pub fn count(self: *const RoundBf16) usize { + return self.x.len; + } + + pub fn solve(self: *const RoundBf16, _: std.mem.Allocator, _: ref.Sums, out: []ref.Iv) !void { + for (out, self.x) |*o, x| o.* = ref.Iv.of(x).bf(); + } + + pub fn check(self: *const RoundBf16, _: std.mem.Allocator, got: []const u8, msg: []u8) !?[]const u8 { + for (self.x, 0..) |x, i| { + const want = bfRound(x); + const value = ref.readF32(got, i); + if (!ref.sameF32(value, want)) return fail(msg, "tap {d}: {e} where {e} is due", .{ i, value, want }); + } + return null; + } +}; + +pub const Set = struct { + k: lm.Kernels = undefined, + loaded: bool = false, + messages: [2]K(Messages) = undefined, + gates: [2]K(Gate) = undefined, + qkvs: [2]K(ProjectQkv) = undefined, + ars: [3]K(Ar) = undefined, + rounds: [2]K(RoundBf16) = undefined, + + pub fn init(set: *Set, gpu: check.Gpu, s: cuda.Stream, a: std.mem.Allocator, list: *std.ArrayList(g.Kernel)) !void { + set.k = try lm.Kernels.load(gpu.d); + set.loaded = true; + const k = &set.k; + const rig: rig_.Rig = .{ .gpu = gpu, .s = s }; + for (&set.messages, 0..) |*x, i| x.* = .{ .inner = .{ .rig = rig, .k = .{ .kern = k, .aliased = i == 1 } } }; + for (&set.gates, 0..) |*x, i| x.* = .{ .inner = .{ .rig = rig, .k = .{ .kern = k, .wrong_gain = i == 1 } } }; + for (&set.qkvs, 0..) |*x, i| x.* = .{ .inner = .{ .rig = rig, .k = .{ .kern = k, .shared_input = i == 1 } } }; + for (&set.ars, 0..) |*x, i| x.* = .{ .inner = .{ .rig = rig, .k = .{ .kern = k, .partial_bf16 = i == 1, .short = i == 2 } } }; + for (&set.rounds, 0..) |*x, i| x.* = .{ .inner = .{ .rig = rig, .k = .{ .kern = k, .short = i == 1 } } }; + inline for (.{ "messages", "gates", "qkvs", "ars", "rounds" }) |f| for (&@field(set, f)) |*x| try list.append(a, x.kernel()); + } + + pub fn deinit(set: *Set) void { + if (!set.loaded) return; + inline for (.{ "messages", "gates", "qkvs", "ars", "rounds" }) |f| for (&@field(set, f)) |*x| x.deinit(); + set.k.unload(); + set.loaded = false; + } +}; diff --git a/zig/tests/cuda/contract_inkling2_modelopt.zig b/zig/tests/cuda/contract_inkling2_modelopt.zig new file mode 100644 index 00000000000..5052173fd2a --- /dev/null +++ b/zig/tests/cuda/contract_inkling2_modelopt.zig @@ -0,0 +1,590 @@ +//! Mini's packed NVFP4/MXFP8 expert pipeline on BF16 activations, with bit-exact and float64 references. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const ink = @import("inkling2"); +const rig_ = @import("contract_rig.zig"); + +const c = core.contract.spec; +const g = core.contract.gates; +const mo = ink.modelopt; +const experts = 8; +const slots = 8; + +const CombineArgs = extern struct { + experts: u64, + pick: u64, + weights: u64, + out: u64, + rows: i32, + h: i32, + slots: i32, +}; + +const TensorActArgs = extern struct { + gateup: u64, + out: u64, + n: i32, +}; + +const Baseline = struct { + mod: cuda.Module, + tensor_mod: cuda.Module, + pack: cuda.Function, + project: cuda.Function, + act: cuda.Function, + combine: cuda.Function, +}; + +fn bf(x: f32) f32 { + return c.fromBf16(c.toBf16(x)); +} + +fn e2m1(n: u8) f32 { + const table = [8]f32{ 0, 0.5, 1, 1.5, 2, 3, 4, 6 }; + const v = table[n & 7]; + return if ((n & 8) != 0) -v else v; +} + +fn e4m3(n: u8) f32 { + const e = (n >> 3) & 15; + const m: f32 = @floatFromInt(n & 7); + var v: f32 = undefined; + if (e == 0) { + v = m * 0x1p-9; + } else if (e == 15 and n & 7 == 7) { + v = std.math.nan(f32); + } else { + v = std.math.pow(f32, 2, @as(f32, @floatFromInt(e)) - 7) * (1 + m / 8); + } + return if ((n & 128) != 0) -v else v; +} + +fn route(slot: usize) u32 { + const ids = [8]u32{ 7, 7, 2, 5, 0, 6, 3, 4 }; + return ids[slot]; +} + +fn routeWeight(token: usize, slot: usize) f32 { + _ = token; + // Route order loses the unit between opposite large terms; expert order keeps it. + return switch (slot) { + 0 => 0x1p24, + 1 => 1, + 2 => -0x1p24, + else => 0, + }; +} + +const test_amax: f32 = 1.0039; // bf16: 1 +const test_den: f32 = 2696.001; // bf16: 2704 + +fn nvfp4Weight(code: u8, scale: u8) u16 { + const factor = bf(test_amax) / bf(test_den); + return c.toBf16(e2m1(code) * e4m3(scale) * factor); +} + +fn ue8m0(n: u8) f32 { + return std.math.pow(f32, 2, @as(f32, @floatFromInt(@as(i32, n) - 127))); +} + +fn mxfp8Weight(code: u8, scale: u8) u16 { + return c.toBf16(e4m3(code) * ue8m0(scale)); +} + +const Phase = enum { decode, prompt }; +const Fault = enum { none, wrong_combine, wrong_plan, wrong_up, wrong_prompt_up, wrong_act }; +fn rawSpec(format: mo.Format, phase: Phase, fault: Fault) c.Spec { + const served = &[_]c.Shape{ + .{ .rows = 1, .n = 2304, .k = 1152 }, + .{ .rows = 16, .n = 2304, .k = 1152 }, + .{ .rows = 31, .n = 2304, .k = 1152 }, + .{ .rows = 32, .n = 2304, .k = 1152 }, + .{ .rows = 2048, .n = 2304, .k = 1152 }, + }; + const name = switch (fault) { + .none => if (format == .nvfp4) + (if (phase == .decode) "inkling2 Mini NVFP4 decode w13/w2 tensor-core experts" else "inkling2 Mini NVFP4 prompt w13/w2 tensor-core experts") + else + (if (phase == .decode) "inkling2 Mini MXFP8 decode w13/w2 tensor-core experts" else "inkling2 Mini MXFP8 prompt w13/w2 tensor-core experts"), + .wrong_combine => if (format == .nvfp4) "control: inkling2 Mini NVFP4 int32 route IDs reinterpreted as FP32 weights" else "control: inkling2 Mini MXFP8 int32 route IDs reinterpreted as FP32 weights", + .wrong_plan => "control: inkling2 Mini MXFP8 plan routes to the next expert IDs", + .wrong_up => "control: inkling2 Mini MXFP8 decode up projection clears the planted up-row code", + .wrong_prompt_up => if (format == .nvfp4) "control: inkling2 Mini NVFP4 prompt up projection clears the planted up-row code" else "control: inkling2 Mini MXFP8 prompt up projection clears the planted up-row code", + .wrong_act => "control: inkling2 Mini MXFP8 activation uses gate cap eight", + }; + const shapes = if (fault == .wrong_prompt_up or (fault == .none and phase == .prompt)) + served[3..] + else if (fault == .none) + served[0..3] + else + served[0..2]; + return .{ + .name = name, + .accum = .f32, + .depth = depth, + .ops = 8, + .mids = 4, + .out = .bf16, + .replaces = "host-dequantized BF16 tensor projections, softcapped SwiGLU, ascending FP32 routing", + .nan = .{ .stated = "a non-finite BF16 input row propagates through its selected experts" }, + .tiles = .{ .{ .size = 16 }, .{ .size = 32 }, .{ .size = 32 } }, + .served = shapes, + .sums = .{ .f16 = 30, .bf16 = 30 }, + }; +} +fn depth(s: c.Shape) usize { + return s.n + s.k + 2 * core.attention_range.mma_step + slots; +} +pub const ModelOpt = struct { + rig: rig_.Rig, + k: *const mo.Kernels, + format: mo.Format, + phase: Phase, + shape: c.Shape = undefined, + fault: Fault = .none, + arena: ?std.heap.ArenaAllocator = null, + x: []const u16 = &.{}, + w13: []const u16 = &.{}, + w2: []const u16 = &.{}, + l: mo.Layer = undefined, + dev_x: u64 = 0, + pick: u64 = 0, + weights: u64 = 0, + out: u64 = 0, + stress: bool = false, + scratch: u64 = 0, + base_pick: u64 = 0, + base_w13: u64 = 0, + base_w2: u64 = 0, + base_pack13: u64 = 0, + base_pack2: u64 = 0, + base_gateup: u64 = 0, + base_act: u64 = 0, + base_down: u64 = 0, + base_out: u64 = 0, + baseline: ?Baseline = null, + + pub fn kernel(self: *ModelOpt) g.Kernel { + return .{ .spec = rawSpec(self.format, self.phase, self.fault), .ctx = self, .vt = &vt, .control = if (self.fault == .none) null else .shapes }; + } + + const vt = g.hooks(ModelOpt); + + pub fn deinit(self: *ModelOpt) void { + self.drop(); + if (self.baseline) |*b| { + b.tensor_mod.unload(); + b.mod.unload(); + } + self.baseline = null; + self.rig.deinit(); + } + + fn drop(self: *ModelOpt) void { + if (self.arena) |*a| a.deinit(); + self.arena = null; + self.rig.reset(); + } + + fn projectionRef(a: std.mem.Allocator, format: mo.Format, nexperts: usize, n: usize, k: usize, gate_up: bool, fill: g.Fill) !struct { codes: []u8, scales: []u8, amax: []f32, den: [1]f32, ref: []u16 } { + const values = nexperts * n * k; + const raw = try a.alloc(u8, if (format == .nvfp4) values / 2 else values); + const ref = try a.alloc(u16, values); + const group: usize = if (format == .nvfp4) 16 else 32; + const scales = try a.alloc(u8, values / group); + const amax = try a.alloc(f32, if (format == .nvfp4) nexperts else 0); + if (format == .nvfp4) @memset(amax, if (fill == .stress) bf(test_den) else test_amax); + const codes = [16]u8{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }; + const fp8 = [16]u8{ 0x00, 0x08, 0x10, 0x18, 0x20, 0x28, 0x30, 0x38, 0x80, 0x88, 0x90, 0x98, 0xa0, 0xa8, 0xb0, 0xb8 }; + const nv_scales = [4]u8{ 0x38, 0x30, 0x40, 0x34 }; + // General controls stay finite; the dedicated scale-255 test covers +inf without masking faults as shared NaNs. + const mx_scales = [4]u8{ 127, 128, 126, 129 }; + if (fill == .stress) { + for (0..nexperts) |e| for (0..n) |row| { + const base = (e * n + row) * k; + const scale_base = (e * n + row) * (k / group); + @memset(scales[scale_base..][0 .. k / group], if (format == .nvfp4) 0x38 else 127); + for (0..k) |col| { + // Mirrored +/-1 terms cancel to small integers; eight up rows retain a down-projection nudge. + const zero = gate_up and (row & 1) == 1 and row / 2 < 8 and col == k / 2 + 8; + const code: u8 = if (zero) 0 else if (format == .nvfp4) (if (col < k / 2) 2 else 10) else (if (col < k / 2) 0x38 else 0xb8); + if (format == .nvfp4) { + if ((col & 1) == 0) raw[base / 2 + col / 2] = code else raw[base / 2 + col / 2] |= code << 4; + } else raw[base + col] = code; + ref[base + col] = c.toBf16(if (zero) 0 else if (col < k / 2) 1 else -1); + } + }; + return .{ .codes = raw, .scales = scales, .amax = amax, .den = .{test_den}, .ref = ref }; + } + for (0..nexperts) |e| for (0..n) |row| { + const base = (e * n + row) * k; + const scale_base = (e * n + row) * (k / group); + if (format == .nvfp4) { + for (0..k / 2) |cb| { + var n0 = codes[(2 * (base / 2 + cb) * 5 + 3) & 15]; + const n1 = if (cb == 0) 0 else codes[(2 * (base / 2 + cb) * 5 + 7) & 15]; + if (cb == 0) n0 = if (!gate_up or row < 2) (if (gate_up) 2 else 7) else 0; + raw[base / 2 + cb] = n0 | (n1 << 4); + const gi = cb / 8; + scales[scale_base + gi] = if (gi == 0) 0x38 else nv_scales[(scale_base + gi) & 3]; + const scale = scales[scale_base + gi]; + ref[base + 2 * cb] = nvfp4Weight(n0, scale); + ref[base + 2 * cb + 1] = nvfp4Weight(n1, scale); + } + } else { + for (0..k) |col| { + var code = fp8[((base + col) * 5 + 3) & 15]; + // Gate six makes caps four and eight differ deterministically on the one-token control. + if (col == 0) code = if (!gate_up) 0x40 else if (row == 0) 0x4c else if (row == 1) 0x38 else 0; + raw[base + col] = code; + const gi = col / 32; + scales[scale_base + gi] = if (gi == 0) 127 else mx_scales[(scale_base + gi) % mx_scales.len]; + ref[base + col] = mxfp8Weight(code, scales[scale_base + gi]); + } + } + }; + return .{ .codes = raw, .scales = scales, .amax = amax, .den = .{test_den}, .ref = ref }; + } + + pub fn prepare(self: *ModelOpt, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + _ = seed; + if (self.phase == .prompt and shape.rows < 32 and fill != .stress and fill != .nonfinite) return false; + if (shape.n != 2304 or shape.k != 1152 or shape.rows == 0 or shape.rows > 2048) return false; + self.drop(); + self.shape = shape; + self.stress = fill == .stress; + self.arena = std.heap.ArenaAllocator.init(self.rig.gpu.gpa); + const a = self.arena.?.allocator(); + const h = shape.n; + const m = shape.k; + const pairs = shape.rows * slots; + const x = try a.alloc(u16, shape.rows * h); + for (x, 0..) |*v, i| { + const q: f32 = @as(f32, @floatFromInt(@as(i32, @intCast(i % 17)) - 8)) / 64; + v.* = c.toBf16(q); + } + @memset(x[0..h], 0); + x[0] = c.toBf16(1); // One gate/up activation and one down product make token zero a decode probe. + if (fill == .nonfinite) x[0] = 0x7fc0; + if (fill == .stress) for (0..shape.rows) |row| for (0..h) |col| { + const v: f32 = 4 * @as(f32, @floatFromInt(1 + col % 64)); + x[row * h + col] = c.toBf16(v + @as(f32, if (col >= h / 2 and col < h / 2 + 8) 4 else 0)); + }; + self.x = x; + const p13 = try projectionRef(a, self.format, experts, 2 * m, h, true, fill); + const p2 = try projectionRef(a, self.format, experts, h, m, false, fill); + self.w13 = p13.ref; + self.w2 = p2.ref; + self.dev_x = try self.rig.input(std.mem.sliceAsBytes(x)); + const dev13 = if (self.fault == .wrong_up or self.fault == .wrong_prompt_up) blk: { + const wrong = try a.dupe(u8, p13.codes); + for (0..experts) |e| { + const code_stride: usize = if (self.format == .nvfp4) 2 else 1; + const z = (e * 2 * m + 1) * h / code_stride; + if (self.format == .nvfp4) wrong[z] &= 0xf0 else wrong[z] = 0; + } + break :blk try self.rig.input(wrong); + } else try self.rig.input(p13.codes); + const dev13s = try self.rig.input(p13.scales); + const dev2 = try self.rig.input(p2.codes); + const dev2s = try self.rig.input(p2.scales); + var amax13: u64 = 0; + var amax2: u64 = 0; + var den13: u64 = 0; + var den2: u64 = 0; + if (self.format == .nvfp4) { + amax13 = try self.rig.input(std.mem.sliceAsBytes(p13.amax)); + amax2 = try self.rig.input(std.mem.sliceAsBytes(p2.amax)); + den13 = try self.rig.input(std.mem.asBytes(&p13.den)); + den2 = try self.rig.input(std.mem.asBytes(&p2.den)); + } + self.l = .{ + .format = self.format, + .experts = experts, + .w13 = .{ .codes = dev13, .scales = dev13s, .amax = amax13, .denominator = den13, .n = @intCast(2 * m), .k = @intCast(h) }, + .w2 = .{ .codes = dev2, .scales = dev2s, .amax = amax2, .denominator = den2, .n = @intCast(h), .k = @intCast(m) }, + }; + const picks = try a.alloc(i32, pairs); + const weights = try a.alloc(f32, pairs); + for (picks, weights, 0..) |*p, *w, i| { + const slot = i % slots; + const id = if (self.fault == .wrong_plan) (route(slot) + 1) % experts else route(slot); + p.* = @intCast(id); + w.* = routeWeight(i / slots, slot); + } + const base_picks = try a.alloc(i32, pairs); + for (base_picks, 0..) |*p, i| p.* = @intCast(route(i % slots)); + self.pick = try self.rig.input(std.mem.sliceAsBytes(picks)); + self.weights = try self.rig.input(std.mem.sliceAsBytes(weights)); + self.out = try self.rig.output(shape.rows * h * 2); + self.scratch = try self.rig.scratch(try mo.scratchBytes(shape.rows, slots, h, m)); + self.base_pick = try self.rig.input(std.mem.sliceAsBytes(base_picks)); + self.base_w13 = try self.rig.input(std.mem.sliceAsBytes(p13.ref)); + self.base_w2 = try self.rig.input(std.mem.sliceAsBytes(p2.ref)); + self.base_pack13 = try self.rig.scratch(experts * 2 * m * h * 2); + self.base_pack2 = try self.rig.scratch(experts * h * m * 2); + self.base_gateup = try self.rig.scratch(pairs * 2 * m * 2); + self.base_act = try self.rig.scratch(pairs * m * 2); + self.base_down = try self.rig.scratch(pairs * h * 2); + self.base_out = try self.rig.scratch(shape.rows * h * 2); + return true; + } + + pub fn run(self: *ModelOpt) !void { + const route_weights = if (self.fault == .wrong_combine) self.pick else self.weights; + const caps = if (self.fault == .wrong_act) ink.experts.Caps{ .gate = 8, .up = 25 } else ink.experts.Caps{ .gate = 4, .up = 25 }; + if (self.phase == .prompt and self.shape.rows < 32) return self.runPrompt(caps); + try mo.run(self.k, self.rig.s, self.l, caps, self.dev_x, self.shape.n, self.pick, route_weights, self.shape.rows, slots, self.out, self.scratch); + } + + fn pack(self: *ModelOpt, b: *const Baseline, src: u64, n: usize, k: usize, dst: u64) !void { + var a: cuda.Args = .{}; + a.add(src); + a.add(@as(i64, @intCast(n * k))); + a.add(@as(i32, @intCast(k))); + for ([_]i32{ 0, 0, 0 }) |v| a.add(v); + a.add(@as(i32, @intCast(n))); + a.add(@as(i32, @intCast(k))); + a.add(dst); + const q = (n / 32) * (k / 32) * 128; + try cuda.launch.launch(b.pack, .{ .grid = .{ .x = @intCast((q + 255) / 256), .y = experts, .z = 1 }, .block = .{ .x = 256 } }, self.rig.s, &a); + } + + fn tensorProjection(self: *ModelOpt, b: *const Baseline, x: u64, x_stride: usize, slot_count: usize, w: u64, n: usize, k: usize, plan: mo.Layout, out: u64, item_bound: usize) !void { + var a: cuda.Args = .{}; + a.add(x); + a.add(@as(i32, @intCast(x_stride))); + a.add(@as(i32, @intCast(slot_count))); + a.add(w); + a.add(@as(i32, @intCast(k / 32))); + a.add(@as(i32, @intCast(n / 32))); + for ([_]u64{ plan.items, plan.item_count, plan.members, out }) |v| a.add(v); + a.add(@as(i32, @intCast(n))); + a.add(@as(i32, -1)); + const nb = n / 32; + const grid = (item_bound * nb + 3) / 4; + try cuda.launch.launch(b.project, .{ .grid = .{ .x = @intCast(grid), .y = 1, .z = 1 }, .block = .{ .x = 128 } }, self.rig.s, &a); + } + + /// Tensor projections over host-dequantized weights, the baseline epilogue and the original ascending combine. + pub fn replaced(self: *ModelOpt) ![]const u8 { + if (self.baseline == null) { + var mod = try cuda.Module.load(self.rig.gpu.d, cuda.kernels.inkling2_experts); + errdefer mod.unload(); + var tensor_mod = try cuda.Module.load(self.rig.gpu.d, cuda.kernels.experts_bf16); + errdefer tensor_mod.unload(); + self.baseline = .{ + .mod = mod, + .tensor_mod = tensor_mod, + .pack = try tensor_mod.function("tf_bf16_experts_pack"), + .project = try tensor_mod.function("tf_bf16_experts_down_bf16"), + .act = try mod.function("tf_ink2moe_tensor_act"), + .combine = try mod.function("tf_ink2moe_combine"), + }; + } + const b = &self.baseline.?; + const pairs = self.shape.rows * slots; + const h = self.shape.n; + const m = self.shape.k; + const plan = mo.layout(self.scratch, self.shape.rows, slots, h, m); + const tile: usize = if (self.shape.rows < 32) 16 else 64; + const item_bound = (pairs + tile - 1) / tile + @min(pairs, experts); + var pa: cuda.Args = .{}; + for ([_]u64{ self.base_pick, plan.items, plan.members, plan.item_count }) |v| pa.add(v); + for ([_]i32{ @intCast(self.shape.rows), slots, experts, @intCast(tile) }) |v| pa.add(v); + try cuda.launch.launch(self.k.plan, .{ .grid = .{ .x = 1, .y = 1, .z = 1 }, .block = .{ .x = 32 } }, self.rig.s, &pa); + try self.pack(b, self.base_w13, 2 * m, h, self.base_pack13); + try self.pack(b, self.base_w2, h, m, self.base_pack2); + try self.tensorProjection(b, self.dev_x, h, slots, self.base_pack13, 2 * m, h, plan, self.base_gateup, item_bound); + var aa: cuda.Args = .{}; + aa.add(TensorActArgs{ .gateup = self.base_gateup, .out = self.base_act, .n = @intCast(pairs * m) }); + try cuda.launch.launch(b.act, .{ .grid = .{ .x = @intCast((pairs * m + 255) / 256), .y = 1, .z = 1 }, .block = .{ .x = 256 } }, self.rig.s, &aa); + try self.tensorProjection(b, self.base_act, m, 0, self.base_pack2, h, m, plan, self.base_down, item_bound); + var ca: cuda.Args = .{}; + ca.add(CombineArgs{ .experts = self.base_down, .pick = self.base_pick, .weights = self.weights, .out = self.base_out, .rows = @intCast(self.shape.rows), .h = @intCast(h), .slots = slots }); + const outputs = self.shape.rows * h; + try cuda.launch.launch(b.combine, .{ .grid = .{ .x = @intCast((outputs + 255) / 256), .y = 1, .z = 1 }, .block = .{ .x = 256 } }, self.rig.s, &ca); + return self.rig.bytes(self.base_out, 2 * self.count()); + } + + fn promptProjection(self: *ModelOpt, x: u64, stride: usize, pair_slots: usize, p: mo.Projection, row0: i32, step: i32, plan: mo.Layout, out: u64, bound: usize) !void { + const outputs: usize = @intCast(if (step == 2) p.n / 2 else p.n); + var a: cuda.Args = .{}; + a.add(x); + a.add(@as(i32, @intCast(stride))); + a.add(@as(i32, @intCast(pair_slots))); + a.add(mo.weight(p, self.l, row0, step)); + a.add(@as(i32, @intCast(p.k / 32))); + a.add(@as(i32, @intCast(outputs / 32))); + for ([_]u64{ plan.items, plan.item_count, plan.members, out }) |v| a.add(v); + a.add(@as(i32, @intCast(outputs))); + a.add(@as(i32, -1)); + const grid = (bound * outputs / 32 + 3) / 4; + try cuda.launch.launch(self.k.prompt, .{ .grid = .{ .x = @intCast(grid), .y = 1, .z = 1 }, .block = .{ .x = 128 } }, self.rig.s, &a); + } + + fn runPrompt(self: *ModelOpt, caps: ink.experts.Caps) !void { + const pairs = self.shape.rows * slots; + const b = mo.layout(self.scratch, self.shape.rows, slots, self.shape.n, self.shape.k); + const bound = (pairs + 63) / 64 + @min(pairs, experts); + var plan_args: cuda.Args = .{}; + for ([_]u64{ self.pick, b.items, b.members, b.item_count }) |v| plan_args.add(v); + for ([_]i32{ @intCast(self.shape.rows), slots, experts, 64 }) |v| plan_args.add(v); + try cuda.launch.launch(self.k.plan, .{ .grid = .{ .x = 1, .y = 1, .z = 1 }, .block = .{ .x = 32 } }, self.rig.s, &plan_args); + try self.promptProjection(self.dev_x, self.shape.n, slots, self.l.w13, 0, 2, b, b.gate, bound); + try self.promptProjection(self.dev_x, self.shape.n, slots, self.l.w13, 1, 2, b, b.up, bound); + var aa: cuda.Args = .{}; + for ([_]u64{ b.gate, b.up, b.act }) |v| aa.add(v); + aa.add(@as(i32, @intCast(pairs * self.shape.k))); + aa.add(caps.gate); + aa.add(caps.up); + try cuda.launch.launch(self.k.act, .{ .grid = .{ .x = @intCast((pairs * self.shape.k + 255) / 256), .y = 1, .z = 1 }, .block = .{ .x = 256 } }, self.rig.s, &aa); + try self.promptProjection(b.act, self.shape.k, 0, self.l.w2, 0, 1, b, b.down, bound); + var ca: cuda.Args = .{}; + for ([_]u64{ self.pick, self.weights, b.down, self.out }) |v| ca.add(v); + for ([_]i32{ @intCast(self.shape.rows), @intCast(self.shape.n), slots, experts }) |v| ca.add(v); + const output_count = self.shape.rows * self.shape.n; + try cuda.launch.launch(self.k.combine, .{ .grid = .{ .x = @intCast((output_count + 255) / 256), .y = 1, .z = 1 }, .block = .{ .x = 256 } }, self.rig.s, &ca); + } + + pub fn count(self: *const ModelOpt) usize { + return self.shape.rows * self.shape.n; + } + + fn roundTo(acc: c.Accum, v: f64) f64 { + return switch (acc) { + .f32 => @as(f32, @floatCast(v)), + .f16 => @as(f16, @floatCast(v)), + .bf16 => c.fromBf16(c.toBf16(@floatCast(v))), + .none => v, + }; + } + fn rounded(v: f64) f64 { + return c.fromBf16(c.toBf16(@floatCast(v))); + } + fn activate(gate: f64, up: f64) f64 { + const gate_f32: f32 = @floatCast(gate); + const up_f32: f32 = @floatCast(up); + const gc = 4 * @as(f32, @floatCast(std.math.tanh(gate_f32 / 4))); + const uc = 25 * @as(f32, @floatCast(std.math.tanh(up_f32 / 25))); + const sigmoid: f32 = 1 / (1 + @exp(-gate_f32)); + return rounded(gc * sigmoid * uc); + } + + fn evaluate(self: *const ModelOpt, acc: c.Accum, order: g.Order, out: []f64, mag: ?[]f64) !void { + const a = self.rig.gpu.gpa; + const pairs = self.shape.rows * slots; + const h = self.shape.n; + const m = self.shape.k; + const t = try a.alloc(f64, h); + defer a.free(t); + const act = try a.alloc(f64, pairs * m); + defer a.free(act); + const upstream = try a.alloc(f64, pairs * m); + defer a.free(upstream); + const down = try a.alloc(f64, pairs * h); + defer a.free(down); + const down_mag = try a.alloc(f64, pairs * h); + defer a.free(down_mag); + for (0..if (self.stress) 1 else pairs) |p| { + const token = p / slots; + const e = route(p % slots); + const x = self.x[token * h ..][0..h]; + const w = self.w13[e * 2 * m * h ..]; + for (0..m) |j| { + var gabs: f64 = 0; + var uabs: f64 = 0; + for (0..h) |i| { + const xv = c.fromBf16(x[i]); + t[i] = xv * c.fromBf16(w[(2 * j) * h + i]); + gabs += @abs(t[i]); + } + const gate = rounded(core.contract.rows.sumIn(acc, order, t)); + for (0..h) |i| { + t[i] = c.fromBf16(x[i]) * c.fromBf16(w[(2 * j + 1) * h + i]); + uabs += @abs(t[i]); + } + const up = rounded(core.contract.rows.sumIn(acc, order, t)); + act[p * m + j] = activate(gate, up); + upstream[p * m + j] = 32 * gabs + 8 * uabs; + } + } + if (self.stress) for (1..pairs) |p| { + @memcpy(act[p * m ..][0..m], act[0..m]); + @memcpy(upstream[p * m ..][0..m], upstream[0..m]); + }; + for (0..if (self.stress) 1 else pairs) |p| for (0..if (self.stress) 1 else h) |col| { + const w = self.w2[route(p % slots) * h * m + col * m ..][0..m]; + var abs: f64 = 0; + for (0..m) |j| { + t[j] = act[p * m + j] * c.fromBf16(w[j]); + abs += @abs(t[j]) + @abs(c.fromBf16(w[j])) * upstream[p * m + j]; + } + down[p * h + col] = rounded(core.contract.rows.sumIn(acc, order, t[0..m])); + down_mag[p * h + col] = abs; + }; + if (self.stress) { + @memset(down, down[0]); + @memset(down_mag, down_mag[0]); + } + for (0..self.shape.rows) |token| for (0..h) |col| { + var total: f64 = 0; + var abs: f64 = 0; + for (0..experts) |e| for (0..slots) |slot| { + if (route(slot) != e) continue; + const p = token * slots + slot; + const weight = routeWeight(token, slot); + total = roundTo(acc, total + roundTo(acc, weight * down[p * h + col])); + abs += @abs(weight) * down_mag[p * h + col]; + }; + out[token * h + col] = rounded(total); + if (mag) |v| v[token * h + col] = abs; + }; + } + + pub fn reference(self: *ModelOpt, want: []f64, mag: []f64) !void { + if (self.x[0] == 0x7fc0) { + @memset(want, 0); + @memset(mag, 0); + @memset(want[0..self.shape.n], std.math.nan(f64)); + return; + } + return self.evaluate(.none, .sequential, want, mag); + } + + pub fn simulate(self: *ModelOpt, acc: c.Accum, order: g.Order, out: []f64) !void { + return self.evaluate(acc, order, out, null); + } +}; + +test "A2: amax and denominator are BF16 before the FP32 quotient" { + // code=6, scale=1: rounded sources give 0x3b11; f32 sources give 0x3b12. + try std.testing.expectEqual(@as(u16, 0x3b11), nvfp4Weight(7, 0x38)); + const factor = bf(test_amax) / bf(test_den); + try std.testing.expectEqual(@as(f32, 1) / 2704, factor); + const unrounded = c.toBf16(e2m1(7) * e4m3(0x38) * (test_amax / test_den)); + try std.testing.expectEqual(@as(u16, 0x3b12), unrounded); +} + +test "MXFP8 UE8M0 scale 255 decodes to positive infinity" { + try std.testing.expectEqual(std.math.inf(f32), ue8m0(255)); + try std.testing.expectEqual(@as(u16, 0x7f80), mxfp8Weight(0x38, 255)); +} + +test "A12: ascending experts retain the unit cancelled in route order" { + var route_sum: f32 = 0; + for (0..slots) |slot| route_sum += routeWeight(0, slot); + try std.testing.expectEqual(@as(f32, 0), route_sum); + var expert_sum: f32 = 0; + for (0..experts) |e| for (0..slots) |slot| { + if (route(slot) == e) expert_sum += routeWeight(0, slot); + }; + try std.testing.expectEqual(@as(f32, 1), expert_sum); +} + +test "the independent baseline's CUDA structs match experts.cu" { + try std.testing.expectEqual(@as(usize, 48), @sizeOf(CombineArgs)); + try std.testing.expectEqual(@as(usize, 24), @sizeOf(TensorActArgs)); + try std.testing.expectEqual(@as(usize, 16), @offsetOf(TensorActArgs, "n")); +} diff --git a/zig/tests/cuda/contract_inkling2_ops_mix.zig b/zig/tests/cuda/contract_inkling2_ops_mix.zig index 22fc073bf40..b837c657b8b 100644 --- a/zig/tests/cuda/contract_inkling2_ops_mix.zig +++ b/zig/tests/cuda/contract_inkling2_ops_mix.zig @@ -10,7 +10,8 @@ const g = core.contract.gates; const Iv = ref.Iv; const Sums = ref.Sums; const ops = ref.ops; -const C = ref.hidden; +const small_hidden = ref.hidden; +const mini_hidden = 2304; /// forward.zig's mixes: attention's (q, k and v queries, bf16 stream), the MLP's (fp32 residual), layer 0's (no query). pub const Form = enum { attn, mlp, first }; @@ -23,16 +24,16 @@ fn nq(f: Form) usize { } /// A thread's columns 512 apart, then the block's two shuffle stages. -fn depth(_: c.Shape) usize { - return ref.blockDepth(C, 512); +fn depth(s: c.Shape) usize { + return ref.blockDepth(s.n, 512); } /// Rows x hidden x blocks (completed blocks + the partial): mix_rows takes calls of more than 16 rows, mix the rest. pub fn mixSpec(f: Form, narrow: bool, fault: Fault) c.Spec { - const wide = &[_]c.Shape{ .{ .rows = 17, .n = C, .k = 9 }, .{ .rows = 64, .n = C, .k = 5 }, .{ .rows = 2048, .n = C, .k = 9 }, .{ .rows = 128, .n = C, .k = 1 }, .{ .rows = 32, .n = C, .k = 2 } }; - const decode = &[_]c.Shape{ .{ .rows = 1, .n = C, .k = 9 }, .{ .rows = 16, .n = C, .k = 9 }, .{ .rows = 8, .n = C, .k = 5 }, .{ .rows = 2, .n = C, .k = 1 }, .{ .rows = 4, .n = C, .k = 2 } }; - const one = &[_]c.Shape{ .{ .rows = 17, .n = C, .k = 1 }, .{ .rows = 2048, .n = C, .k = 1 }, .{ .rows = 64, .n = C, .k = 1 } }; - const one_decode = &[_]c.Shape{ .{ .rows = 1, .n = C, .k = 1 }, .{ .rows = 16, .n = C, .k = 1 }, .{ .rows = 5, .n = C, .k = 1 } }; + const wide = &[_]c.Shape{ .{ .rows = 17, .n = small_hidden, .k = 9 }, .{ .rows = 64, .n = small_hidden, .k = 5 }, .{ .rows = 2048, .n = small_hidden, .k = 9 }, .{ .rows = 128, .n = small_hidden, .k = 1 }, .{ .rows = 32, .n = small_hidden, .k = 2 }, .{ .rows = 17, .n = mini_hidden, .k = 5 }, .{ .rows = 64, .n = mini_hidden, .k = 3 }, .{ .rows = 2048, .n = mini_hidden, .k = 5 }, .{ .rows = 128, .n = mini_hidden, .k = 1 }, .{ .rows = 32, .n = mini_hidden, .k = 2 } }; + const decode = &[_]c.Shape{ .{ .rows = 1, .n = small_hidden, .k = 9 }, .{ .rows = 16, .n = small_hidden, .k = 9 }, .{ .rows = 8, .n = small_hidden, .k = 5 }, .{ .rows = 2, .n = small_hidden, .k = 1 }, .{ .rows = 4, .n = small_hidden, .k = 2 }, .{ .rows = 1, .n = mini_hidden, .k = 5 }, .{ .rows = 16, .n = mini_hidden, .k = 5 }, .{ .rows = 8, .n = mini_hidden, .k = 3 }, .{ .rows = 2, .n = mini_hidden, .k = 1 }, .{ .rows = 4, .n = mini_hidden, .k = 2 } }; + const one = &[_]c.Shape{ .{ .rows = 17, .n = small_hidden, .k = 1 }, .{ .rows = 2048, .n = small_hidden, .k = 1 }, .{ .rows = 64, .n = small_hidden, .k = 1 }, .{ .rows = 17, .n = mini_hidden, .k = 1 }, .{ .rows = 2048, .n = mini_hidden, .k = 1 }, .{ .rows = 64, .n = mini_hidden, .k = 1 } }; + const one_decode = &[_]c.Shape{ .{ .rows = 1, .n = small_hidden, .k = 1 }, .{ .rows = 16, .n = small_hidden, .k = 1 }, .{ .rows = 5, .n = small_hidden, .k = 1 }, .{ .rows = 1, .n = mini_hidden, .k = 1 }, .{ .rows = 16, .n = mini_hidden, .k = 1 }, .{ .rows = 5, .n = mini_hidden, .k = 1 } }; const names = [2][3][]const u8{ .{ "inkling2 ops tf_ink2_mix_rows attention (3 queries, bf16 stream)", "inkling2 ops tf_ink2_mix_rows MLP (1 query, fp32 residual)", "inkling2 ops tf_ink2_mix_rows layer 0 (no query)" }, .{ "inkling2 ops tf_ink2_mix attention (3 queries, bf16 stream)", "inkling2 ops tf_ink2_mix MLP (1 query, fp32 residual)", "inkling2 ops tf_ink2_mix layer 0 (no query)" }, @@ -93,10 +94,11 @@ pub const Mix = struct { /// Values in [-2, 2) with one in 61 eight times larger, queries in [-1, 1); stress: integers in [-16, 16]. pub fn prepare(self: *Mix, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { - if (shape.rows == 0 or shape.n != C or shape.k < 1 or shape.k > ops.max_blocks + 1) return false; + if (shape.rows == 0 or (shape.n != small_hidden and shape.n != mini_hidden) or shape.k < 1 or shape.k > ops.max_blocks + 1) return false; self.free(a); self.shape = shape; - const rows = shape.rows; + const C = self.shape.n; + const rows = self.shape.rows; const nb = shape.k - 1; const q = nq(self.form); const stress = fill == .stress; @@ -116,7 +118,7 @@ pub const Mix = struct { if (nb == 0) ref.plant(f32, self.part, 1, C, ref.asF32); if (rows > 1) ref.plant(f32, self.part[C..], @min(rows - 1, 3), C, ref.asF32); } - var m: ops.MixArgs = .{ .partial = 0, .query = 0, .out = 0, .n_blocks = @intCast(nb), .partial_bf16 = @intFromBool(self.bf16Part()), .nq = @intCast(q), .rows = @intCast(rows), .c = C, .eps = ref.eps }; + var m: ops.MixArgs = .{ .partial = 0, .query = 0, .out = 0, .n_blocks = @intCast(nb), .partial_bf16 = @intFromBool(self.bf16Part()), .nq = @intCast(q), .rows = @intCast(rows), .c = @intCast(C), .eps = ref.eps }; for (0..nb) |j| m.blocks[j] = try ref.input(rig, self.blocks[j * rows * C ..][0 .. rows * C]); if (self.bf16Part()) { const h = try a.alloc(u16, rows * C); @@ -153,16 +155,19 @@ pub const Mix = struct { } pub fn count(self: *const Mix) usize { + const C = self.shape.n; return nq(self.form) * self.shape.rows * C; } fn at(self: *const Mix, j: usize, r: usize, col: usize) f64 { + const C = self.shape.n; const nb = self.shape.k - 1; return if (j < nb) ref.bf(self.blocks[(j * self.shape.rows + r) * C + col]) else self.part[r * C + col]; } /// Each row as the kernels compute it: every block's RMS and query dots, a softmax a query, the mix, its norm. pub fn solve(self: *const Mix, a: std.mem.Allocator, s: Sums, out: []Iv) !void { + const C = self.shape.n; const rows = self.shape.rows; const n = self.shape.k; const q = nq(self.form); @@ -173,7 +178,7 @@ pub const Mix = struct { const h = try a.alloc(Iv, q * C); defer a.free(h); const d = depth(self.shape); - const root = Iv.of(C).rsqrt(); + const root = Iv.of(@as(f64, @floatFromInt(C))).rsqrt(); for (0..rows) |r| { var rr: [ops.max_blocks + 1]Iv = undefined; var w: [ops.max_queries][ops.max_blocks + 1]Iv = undefined; @@ -182,8 +187,8 @@ pub const Mix = struct { for (terms, 0..) |*t, col| t.* = Iv.of(self.at(j, r, col)).mul(Iv.of(self.at(j, r, col))); rr[j] = ref.rms(s.sum(terms, d, scratch), C, 1e-6); for (0..q) |qi| { - for (terms, 0..) |*t, col| t.* = Iv.of(self.at(j, r, col)).mul(Iv.of(self.query[qi * C + col])); - w[qi][j] = s.sum(terms, d, scratch).mul(rr[j]).mul(root); + for (terms, 0..) |*t, col| t.* = Iv.of(self.at(j, r, col)).mul(rr[j]).mul(Iv.of(self.query[qi * C + col])); + w[qi][j] = s.sum(terms, d, scratch).mul(root); } } for (0..q) |qi| softmax(w[qi][0..n]); @@ -220,3 +225,26 @@ fn softmax(l: []Iv) void { } for (l, 0..) |*v, j| v.* = e[j].div(t); } + +test "mix normalizes each FP32 query term before reduction and scales after its dot" { + const source = [_]f32{ + @bitCast(@as(u32, 0x3f800008)), @bitCast(@as(u32, 0x3f800001)), + @bitCast(@as(u32, 0x40400001)), 0, + }; + const query = [_]f32{ + @bitCast(@as(u32, 0x3f800010)), @bitCast(@as(u32, 0x3fffffff)), + @bitCast(@as(u32, 0xc0000001)), 0, + }; + const inv: f32 = @bitCast(@as(u32, 0x3f800001)); + var dot: f32 = 0; + var raw_dot: f32 = 0; + for (source, query) |x, q| { + dot = @mulAdd(f32, q, x * inv, dot); + raw_dot = @mulAdd(f32, q, x, raw_dot); + } + const inverse_root_h: f32 = 0.5; + const scaled = dot * inverse_root_h; + const old = raw_dot * inv * inverse_root_h; + try std.testing.expectEqual(@as(u32, 0xbfbffffb), @as(u32, @bitCast(scaled))); + try std.testing.expectEqual(@as(u32, 0xbfbffffa), @as(u32, @bitCast(old))); +} diff --git a/zig/tests/cuda/contract_inkling2_ops_route.zig b/zig/tests/cuda/contract_inkling2_ops_route.zig index c17be9c5860..8e04891dab9 100644 --- a/zig/tests/cuda/contract_inkling2_ops_route.zig +++ b/zig/tests/cuda/contract_inkling2_ops_route.zig @@ -21,7 +21,7 @@ const topk_rule = "the 8 largest score + bias, the lower id on ties, a NaN never /// Rows x experts x picks: every row of a call, a block each. pub fn topkSpec(unbiased: bool) c.Spec { - const served = &[_]c.Shape{ .{ .rows = 16, .n = experts, .k = top }, .{ .rows = 1, .n = experts, .k = top }, .{ .rows = 128, .n = experts, .k = top }, .{ .rows = 2048, .n = experts, .k = top } }; + const served = &[_]c.Shape{ .{ .rows = 16, .n = experts, .k = top }, .{ .rows = 1, .n = experts, .k = top }, .{ .rows = 128, .n = experts, .k = top }, .{ .rows = 2048, .n = experts, .k = top }, .{ .rows = 16, .n = 128, .k = top }, .{ .rows = 1, .n = 128, .k = top }, .{ .rows = 128, .n = 128, .k = top }, .{ .rows = 2048, .n = 128, .k = top } }; const name = if (unbiased) "control: inkling2 ops tf_ink2_topk without the selection bias" else "inkling2 ops tf_ink2_topk (sigmoid scores, bias, route scale 8)"; return .{ .name = name, .accum = .none, .depth = ref.noSums, .out = .raw, .nan = .{ .stated = topk_rule }, .served = if (unbiased) served[0..2] else served }; } @@ -122,7 +122,7 @@ pub const Topk = struct { const had: f64 = @as(f32, 0.08838834764831845); // exl3_decode.cuh's HAD_SCALE, as fp32 holds it const gate_cap: f32 = 4; const up_cap: f32 = 25; -const width = 1152; // a rank's 2,304-wide expert intermediate at TP=2 +const width = 1152; // Small's width at TP=2; Mini runs one rank with the same full width. const fixture_experts = 8; /// fwht128 and tf_exl3_fwht alike: butterflies (lo + hi, lo - hi) at strides 1, 2, ..., 64 of the 128 values. @@ -142,7 +142,7 @@ fn gateDepth(s: c.Shape) usize { /// (row, slot) pairs x a rank's width x the gate/up's K splits: 1 row, 16, a 128-row window, a 2,048-row window. pub fn gateupSpec(swapped: bool) c.Spec { - const served = &[_]c.Shape{ .{ .rows = 8, .n = width, .k = 4 }, .{ .rows = 128, .n = width, .k = 4 }, .{ .rows = 1024, .n = width, .k = 4 }, .{ .rows = 16384, .n = width, .k = 4 } }; + const served = &[_]c.Shape{ .{ .rows = 8, .n = width, .k = 4 }, .{ .rows = 128, .n = width, .k = 4 }, .{ .rows = 1024, .n = width, .k = 4 }, .{ .rows = 16384, .n = width, .k = 4 }, .{ .rows = 8, .n = width, .k = 2 }, .{ .rows = 128, .n = width, .k = 2 }, .{ .rows = 1024, .n = width, .k = 2 }, .{ .rows = 16384, .n = width, .k = 2 } }; const name = if (swapped) "control: inkling2 ops tf_ink2_gateup with the caps swapped" else "inkling2 ops tf_ink2_gateup (softcapped SwiGLU, gate cap 4, up cap 25)"; return .{ .name = name, .accum = .f32, .depth = gateDepth, .out = .f16, .tiles = .{ .{}, .{ .size = 128, .step = 128, .min = 128 }, .{} }, .served = if (swapped) served[0..2] else served }; } diff --git a/zig/tests/cuda/contract_inkling2_ops_rows.zig b/zig/tests/cuda/contract_inkling2_ops_rows.zig index cb17ac6cbe0..953f54fb68a 100644 --- a/zig/tests/cuda/contract_inkling2_ops_rows.zig +++ b/zig/tests/cuda/contract_inkling2_ops_rows.zig @@ -21,7 +21,7 @@ fn embedDepth(s: c.Shape) usize { /// Rows x hidden x hidden: a prompt chunk, a verify window, one decode row (the drafter's anchor embeds one too). pub fn embedSpec(shifted: bool) c.Spec { - const served = &[_]c.Shape{ .{ .rows = 16, .n = C, .k = C }, .{ .rows = 1, .n = C, .k = C }, .{ .rows = 128, .n = C, .k = C }, .{ .rows = 2048, .n = C, .k = C } }; + const served = &[_]c.Shape{ .{ .rows = 16, .n = C, .k = C }, .{ .rows = 1, .n = C, .k = C }, .{ .rows = 128, .n = C, .k = C }, .{ .rows = 2048, .n = C, .k = C }, .{ .rows = 16, .n = 2304, .k = 2304 }, .{ .rows = 1, .n = 2304, .k = 2304 }, .{ .rows = 128, .n = 2304, .k = 2304 }, .{ .rows = 2048, .n = 2304, .k = 2304 } }; if (shifted) return .{ .name = "control: inkling2 ops tf_ink2_embed gathering the next row", .accum = .f32, .depth = embedDepth, .out = .bf16, .served = served[0..2] }; return .{ .name = "inkling2 ops tf_ink2_embed (embed_norm, rounded once)", .accum = .f32, .depth = embedDepth, .out = .bf16, .served = served }; } @@ -114,14 +114,14 @@ fn dotDepth(s: c.Shape) usize { /// Rows x outputs x hidden; tiles: calls of 32 rows or more with fp32 out (router, taps), bit-equal to tf_ink2_rowdot. pub fn dotSpec(d: Dot, tiles: bool, short: bool) c.Spec { const plain: []const c.Shape = switch (d) { // comptime arrays: a spec outlives this call - .router => &.{ .{ .rows = 16, .n = 384, .k = C }, .{ .rows = 1, .n = 384, .k = C }, .{ .rows = 31, .n = 384, .k = C }, .{ .rows = 7, .n = 384, .k = C } }, - .sink => &.{ .{ .rows = 16, .n = 24, .k = C }, .{ .rows = 1, .n = 24, .k = C }, .{ .rows = 128, .n = 24, .k = C }, .{ .rows = 2048, .n = 24, .k = C } }, - .taps => &.{ .{ .rows = 16, .n = 16, .k = C }, .{ .rows = 1, .n = 16, .k = C }, .{ .rows = 31, .n = 16, .k = C } }, + .router => &.{ .{ .rows = 16, .n = 384, .k = C }, .{ .rows = 1, .n = 384, .k = C }, .{ .rows = 31, .n = 384, .k = C }, .{ .rows = 7, .n = 384, .k = C }, .{ .rows = 16, .n = 128, .k = 2304 }, .{ .rows = 1, .n = 128, .k = 2304 }, .{ .rows = 31, .n = 128, .k = 2304 }, .{ .rows = 7, .n = 128, .k = 2304 } }, + .sink => &.{ .{ .rows = 16, .n = 24, .k = C }, .{ .rows = 1, .n = 24, .k = C }, .{ .rows = 128, .n = 24, .k = C }, .{ .rows = 2048, .n = 24, .k = C }, .{ .rows = 16, .n = 24, .k = 2304 }, .{ .rows = 1, .n = 24, .k = 2304 }, .{ .rows = 128, .n = 24, .k = 2304 }, .{ .rows = 2048, .n = 24, .k = 2304 } }, + .taps => &.{ .{ .rows = 16, .n = 16, .k = C }, .{ .rows = 1, .n = 16, .k = C }, .{ .rows = 31, .n = 16, .k = C }, .{ .rows = 16, .n = 16, .k = 2304 }, .{ .rows = 1, .n = 16, .k = 2304 }, .{ .rows = 31, .n = 16, .k = 2304 } }, }; const wide: []const c.Shape = if (d == .router) - &.{ .{ .rows = 64, .n = 384, .k = C }, .{ .rows = 32, .n = 384, .k = C }, .{ .rows = 100, .n = 384, .k = C }, .{ .rows = 2048, .n = 384, .k = C } } + &.{ .{ .rows = 64, .n = 384, .k = C }, .{ .rows = 32, .n = 384, .k = C }, .{ .rows = 100, .n = 384, .k = C }, .{ .rows = 2048, .n = 384, .k = C }, .{ .rows = 64, .n = 128, .k = 2304 }, .{ .rows = 32, .n = 128, .k = 2304 }, .{ .rows = 100, .n = 128, .k = 2304 }, .{ .rows = 2048, .n = 128, .k = 2304 } } else - &.{ .{ .rows = 64, .n = 16, .k = C }, .{ .rows = 32, .n = 16, .k = C }, .{ .rows = 100, .n = 16, .k = C }, .{ .rows = 2048, .n = 16, .k = C } }; + &.{ .{ .rows = 64, .n = 16, .k = C }, .{ .rows = 32, .n = 16, .k = C }, .{ .rows = 100, .n = 16, .k = C }, .{ .rows = 2048, .n = 16, .k = C }, .{ .rows = 64, .n = 16, .k = 2304 }, .{ .rows = 32, .n = 16, .k = 2304 }, .{ .rows = 100, .n = 16, .k = 2304 }, .{ .rows = 2048, .n = 16, .k = 2304 } }; const names = [3][2][]const u8{ .{ "inkling2 ops tf_ink2_rowdot router (fp32 sigmoid scores)", "inkling2 ops tf_ink2_rowdot_tiles router (fp32 sigmoid scores)" }, .{ "inkling2 ops tf_ink2_rowdot attention sinks (bf16 sigmoid)", "" }, diff --git a/zig/tests/cuda/contract_limits.zig b/zig/tests/cuda/contract_limits.zig index aa8b0751e50..747fcba1edb 100644 --- a/zig/tests/cuda/contract_limits.zig +++ b/zig/tests/cuda/contract_limits.zig @@ -48,8 +48,8 @@ pub fn image(name: []const u8) error{UnknownContractImage}![]const u8 { if (std.mem.eql(u8, name, "flashnext_hcn")) return kk.flashnext_hcn; inline for (.{ "qwen4_projection", "qwen4_hc", "qwen4_gdn", "qwen4_ple", "gemma4_ple" }) |n| if (std.mem.eql(u8, name, n)) return @field(kk, n); - inline for (.{ "tree_round", "act_rows", "gdn_prep", "qk_rows", "norms", "moe", "experts", "qwen36_mtp", "nemotron_attention", "nemotron_route", "nemotron_latent", "qmm_group", "qmm_prefill", "lane_gemv", "prompt16", "qmmf", "ck_experts", "nvfp4_experts", "nvfp4_experts_tile", "nvfp4_experts32", "rank_sum", "prefill_attention", "vit", "embed_rows", "route_rows", "flashnext_gdn", "flashnext_batch", "flashnext_hc", "flashnext_attn", "flashnext_mtp", "qwen_vision", "exl3_linear", "exl3_experts", "exl3_candidate", "experts3", "experts3_prefill", "drama3", "drama3_fp8", "drama3_codec", "glm_mm", "glm_dflash", "glm_glue", "glm_ops", "glm_index", "nemotron_mamba", "sample", "qwen35", "qwen35_bf16_rows", "qwen35_keep", "qwen35_kv8", "w4a8_prefill", "qwen35_draft", "ck_lane", "gdn_train", "train_q4", "train_attn", "flashnext_train", "train", "attn_train", "qwen27_train", "tree_attention", "block_attention", "window_attention", "window_pages", "moe_glue", "dense_rows", "qmm", "flashnext_fact", "flashnext_hcf", "flashnext_fexp", "experts_rows", "nemotron_ops", "minimax_m3", "minimax_m3_attn", "experts_bf16", "nemo_audio", "moss_image", "idol", "idol_decoder", "lfm2_moe", "lfm2", "dots_mocr", "muse_glue", "muse_attention", "muse_linear", "muse_experts2", "muse_dflash", "muse_dflash2" }) |n| if (std.mem.eql(u8, name, n)) return @field(kk, n); - inline for (.{ "inkling2_attn", "inkling2_pattn", "inkling2_ops", "inkling2_rows" }) |n| if (std.mem.eql(u8, name, n)) return @field(kk, n); + inline for (.{ "tree_round", "act_rows", "gdn_prep", "qk_rows", "norms", "moe", "experts", "qwen36_mtp", "nemotron_attention", "nemotron_route", "nemotron_latent", "qmm_group", "qmm_prefill", "lane_gemv", "prompt16", "qmmf", "ck_experts", "nvfp4_experts", "nvfp4_experts_tile", "nvfp4_experts32", "rank_sum", "prefill_attention", "vit", "embed_rows", "route_rows", "flashnext_gdn", "flashnext_batch", "flashnext_hc", "flashnext_attn", "flashnext_mtp", "qwen_vision", "exl3_linear", "exl3_experts", "exl3_candidate", "experts3", "experts3_prefill", "drama3", "drama3_fp8", "drama3_codec", "glm_mm", "glm_dflash", "glm_glue", "glm_ops", "glm_index", "nemotron_mamba", "sample", "qwen35", "qwen35_bf16_rows", "qwen35_keep", "qwen35_kv8", "w4a8_prefill", "qwen35_draft", "ck_lane", "gdn_train", "train_q4", "train_attn", "flashnext_train", "train", "attn_train", "qwen27_train", "tree_attention", "block_attention", "window_attention", "window_pages", "moe_glue", "dense_rows", "qmm", "flashnext_fact", "flashnext_hcf", "flashnext_fexp", "experts_rows", "nemotron_ops", "minimax_m3", "minimax_m3_attn", "experts_bf16", "nemo_audio", "moss_image", "idol", "idol_decoder", "lfm2_moe", "lfm2", "dots_mocr", "muse_glue", "muse_attention", "muse_linear", "muse_experts2", "muse_dflash", "muse_dflash2", "ricursive", "ricursive_prep" }) |n| if (std.mem.eql(u8, name, n)) return @field(kk, n); + inline for (.{ "inkling2_attn", "inkling2_pattn", "inkling2_ops", "inkling2_rows", "inkling2_experts", "inkling2_modelopt", "inkling2_loop_math", "inkling2_vision" }) |n| if (std.mem.eql(u8, name, n)) return @field(kk, n); inline for (.{ "moss_image_decoder", "moss_image_encoder" }) |n| if (std.mem.eql(u8, name, n)) return @field(kk, n); if (std.mem.eql(u8, name, "contract_controls")) return if (options.controls) &controls.bytes else &.{}; return error.UnknownContractImage; diff --git a/zig/tests/cuda/contract_moss_image_ref.zig b/zig/tests/cuda/contract_moss_image_ref.zig index da19db27114..5f16bc4e82d 100644 --- a/zig/tests/cuda/contract_moss_image_ref.zig +++ b/zig/tests/cuda/contract_moss_image_ref.zig @@ -73,7 +73,9 @@ pub fn exp(x: f64) f64 { /// z / (1 + exp(-z)) in float64: it falls to `knee + 1` at `knee`, then rises to 0 and above. pub fn silu(z: f64) f64 { - return z / (1 + @exp(-z)); + const e = @exp(-z); + // expf overflows to inf past fp32's largest value (z below -88.72), so the kernel's silu is -0 there + return z / (1 + if (e > std.math.floatMax(f32)) std.math.inf(f64) else e); } /// silu's turning point, where its derivative's 1 + z (1 - sigmoid z) is zero: e^z = -z - 1. @@ -162,3 +164,10 @@ pub fn invNorm(ss: f64, r: Range, n: f64) struct { inv: f64, r: Range } { pub fn input(rig: *rig_.Rig, x: anytype) !u64 { return rig.input(std.mem.sliceAsBytes(x)); } + +test "silu: fp32 expf overflow at bf16 -89 gives -0, as the kernel stores (#4791)" { + const r = siluRange(Range.of(-89)).fp32(exp_ulps + 0.5 + div_ulps).bf16(); + try std.testing.expect(silu(-89) == 0 and r.lo <= 0 and 0 <= r.hi); + // the largest bf16 below the overflow keeps its finite exp, and nonfinite inputs keep their NaN + try std.testing.expect(silu(-88.5) < 0 and std.math.isNan(silu(-std.math.inf(f64)))); +} diff --git a/zig/tests/cuda/contract_q35_attn.zig b/zig/tests/cuda/contract_q35_attn.zig index 9ede8ed9f86..bf423e80642 100644 --- a/zig/tests/cuda/contract_q35_attn.zig +++ b/zig/tests/cuda/contract_q35_attn.zig @@ -29,9 +29,9 @@ const Ancestor = extern struct { bits: u64, depth: u32, chain: u32 }; pub const Cache = enum { bf16, fp8 }; -/// A registered form: its cache, and for the control a launch that drops each row's last chunk. -pub const Form = struct { cache: Cache, control: bool = false, mt2: bool = false, whole: bool = false }; -pub const forms = [_]Form{ .{ .cache = .bf16 }, .{ .cache = .fp8 }, .{ .cache = .bf16, .control = true }, .{ .cache = .fp8, .mt2 = true }, .{ .cache = .fp8, .mt2 = true, .whole = true } }; +/// A registered form: cache/layout controls, optional wrong-output control, and the exact all-length BF16 opt-in. +pub const Form = struct { cache: Cache, control: bool = false, mt2: bool = false, whole: bool = false, all_rows: bool = false }; +pub const forms = [_]Form{ .{ .cache = .bf16 }, .{ .cache = .fp8 }, .{ .cache = .bf16, .control = true }, .{ .cache = .fp8, .mt2 = true }, .{ .cache = .fp8, .mt2 = true, .whole = true }, .{ .cache = .bf16, .all_rows = true } }; /// A row's merged output sums every key it sees, then the chunks' partials (at most 64). fn keyChain(s: c.Shape) usize { @@ -45,12 +45,17 @@ const stress_keys = 2048; const nan_key = "a NaN key in one of a row's several chunks leaves the row finite: tf_q35_attn_merge skips that chunk"; pub fn spec(f: Form) c.Spec { - const name = if (f.mt2) (if (f.whole) "cuda qwen35 MT2 fp8 whole attention" else "cuda qwen35 MT2 fp8 paged attention") else switch (f.cache) { + const name = if (f.all_rows) "cuda qwen35 opt-in all-length BF16 rows attention" else if (f.mt2) (if (f.whole) "cuda qwen35 MT2 fp8 whole attention" else "cuda qwen35 MT2 fp8 paged attention") else switch (f.cache) { .bf16 => if (f.control) "control qwen35 attention dropping each row's last chunk" else "cuda qwen35 decode attention, bf16 cache (tf_q35_attn_partial, tf_q35_attn_merge)", .fp8 => "cuda qwen35 decode attention, fp8 cache (tf_q35_attn_partial8, tf_q35_attn_merge)", }; - // a DFlash2 window past 2,048 keys, four streams' windows, a 128-row prompt chunk, 256-key chunks past 8,192 - const served: []const c.Shape = if (f.mt2) &.{ .{ .rows = 1, .n = qh, .k = 512 }, .{ .rows = 1, .n = qh, .k = 8191 }, .{ .rows = 1, .n = qh, .k = 8192 }, .{ .rows = 3, .n = qh, .k = 32768 }, .{ .rows = 5, .n = qh, .k = 9000 }, .{ .rows = 6, .n = qh, .k = 9000 }, .{ .rows = 16, .n = qh, .k = 65535 }, .{ .rows = 1, .n = qh, .k = 122779 } } else &.{ .{ .rows = 16, .n = qh, .k = 2100 }, .{ .rows = 64, .n = qh, .k = 700 }, .{ .rows = 128, .n = qh, .k = 300 }, .{ .rows = 16, .n = qh, .k = 9000 }, .{ .rows = 64, .n = qh, .k = 9000 } }; + // Required opt-in cells plus the established short/long, multi-window, prompt-chain and MT2 coverage. + const served: []const c.Shape = if (f.all_rows) &.{ + .{ .rows = 1, .n = qh, .k = 512 }, .{ .rows = 4, .n = qh, .k = 512 }, .{ .rows = 8, .n = qh, .k = 512 }, .{ .rows = 16, .n = qh, .k = 512 }, + .{ .rows = 1, .n = qh, .k = 2048 }, .{ .rows = 4, .n = qh, .k = 2048 }, .{ .rows = 8, .n = qh, .k = 2048 }, .{ .rows = 16, .n = qh, .k = 2048 }, + .{ .rows = 1, .n = qh, .k = 7168 }, .{ .rows = 4, .n = qh, .k = 7168 }, .{ .rows = 8, .n = qh, .k = 7168 }, .{ .rows = 16, .n = qh, .k = 7168 }, + .{ .rows = 1, .n = qh, .k = 16384 }, .{ .rows = 4, .n = qh, .k = 16384 }, .{ .rows = 8, .n = qh, .k = 16384 }, .{ .rows = 16, .n = qh, .k = 16384 }, + } else if (f.mt2) &.{ .{ .rows = 1, .n = qh, .k = 512 }, .{ .rows = 1, .n = qh, .k = 8191 }, .{ .rows = 1, .n = qh, .k = 8192 }, .{ .rows = 3, .n = qh, .k = 32768 }, .{ .rows = 5, .n = qh, .k = 9000 }, .{ .rows = 6, .n = qh, .k = 9000 }, .{ .rows = 16, .n = qh, .k = 65535 }, .{ .rows = 1, .n = qh, .k = 122779 } } else &.{ .{ .rows = 16, .n = qh, .k = 2100 }, .{ .rows = 64, .n = qh, .k = 700 }, .{ .rows = 128, .n = qh, .k = 300 }, .{ .rows = 16, .n = qh, .k = 9000 }, .{ .rows = 64, .n = qh, .k = 9000 } }; return .{ .name = name, .accum = .f32, .depth = keyChain, .ops = 3, .out = .bf16, .replaces = if (f.mt2) "the four-MMA FP8 row tile" else "the chunk-major grid (each row alone)", .tiles = .{ .{ .size = if (f.mt2) 32 / group else width }, .{}, .{ .size = 128 } }, .served = served, .sums = .{ .why = attn.why }, .known = .{ .gate = .nonfinite, .finding = nan_key } }; } @@ -316,7 +321,9 @@ pub const Q35 = struct { rows_args.add(ptr); } const shared: u32 = if (self.form.cache == .bf16) attn_tiles else 0; - try cuda.launch.launch(self.partial, .{ .grid = .{ .x = @intCast(n), .y = @intCast(z), .z = kvh }, .block = .{ .x = 128 }, .shared = shared }, self.rig.s, &args); + const rows_only = self.form.all_rows and n > 1; + if (self.form.cache == .bf16) rows_args.add(rows_only); + if (!rows_only) try cuda.launch.launch(self.partial, .{ .grid = .{ .x = @intCast(n), .y = @intCast(z), .z = kvh }, .block = .{ .x = 128 }, .shared = shared }, self.rig.s, &args); const tile: usize = if (self.form.mt2) 32 / group else 64 / group; const groups = (n + tile - 1) / tile; try cuda.launch.launch(self.long_rows, .{ .grid = .{ .x = @intCast(groups), .y = @intCast(z), .z = kvh }, .block = .{ .x = if (self.form.mt2) @as(u32, 128) else 256 }, .shared = shared }, self.rig.s, &rows_args); diff --git a/zig/tests/cuda/contract_q35_attn_host.zig b/zig/tests/cuda/contract_q35_attn_host.zig index 75286faf321..a107b4a07dd 100644 --- a/zig/tests/cuda/contract_q35_attn_host.zig +++ b/zig/tests/cuda/contract_q35_attn_host.zig @@ -10,7 +10,7 @@ const Call = struct { block: [3]u32, shared: u32, geo: Geo, - args: [12]u64 = @splat(0), + args: [13]u64 = @splat(0), }; const Trace = struct { var calls: std.ArrayList(Call) = .empty; @@ -60,6 +60,7 @@ const Trace = struct { call.args[7] = @as(u32, @bitCast(read(f32, a, 7))); if (long) call.args[8] = @intCast(read(c_int, a, 8)); for (8 + @as(usize, @intFromBool(long))..11 + @as(usize, @intFromBool(long))) |i| call.args[i] = read(u64, a, i); + if (id == 2) call.args[12] = @intFromBool(read(bool, a, 12)); } calls.append(T.allocator, call) catch return 2; return 0; @@ -113,6 +114,7 @@ fn partial(call: Call, form: adapter.Form, long: bool, rows: usize, first: usize if (long) try T.expectEqual(rows, call.args[8]); const at: usize = if (long) 9 else 8; try T.expectEqualSlices(u64, &.{ p[0] + first * 24 * 64 * 4, p[1] + first * 24 * 64 * 4, p[2] + first * 24 * 64 * 256 * 4 }, call.args[at..][0..3]); + if (form.cache == .bf16) try T.expectEqual(form.all_rows and rows > 1, call.args[12] != 0); } fn merge(call: Call, rows: usize, p: [3]u64, out: u64) !void { try T.expectEqual(@as(usize, 3), call.id); @@ -125,18 +127,18 @@ fn merge(call: Call, rows: usize, p: [3]u64, out: u64) !void { test "q35 contract host: actual adapter launches short and long TC paths then merge for both caches" { defer Trace.deinit(); var d = driver(); - for (adapter.forms) |form| for ([_]usize{ 1, 9, 10, 11, 16, 64, 128 }) |rows| { - // Both entries are needed even for mixed streams: length-based selection happens on the device. + for (adapter.forms) |form| for ([_]usize{ 1, 4, 8, 9, 10, 11, 16, 17, 64, 128 }) |rows| { for ([_]usize{ 700, 8191, 8192, 9000 }) |keys| { Trace.reset(); var q = try make(&d, form, rows, keys); defer q.deinit(); try q.run(); - try T.expectEqual(@as(usize, 3), Trace.calls.items.len); + const rows_only = form.all_rows and rows > 1; + try T.expectEqual(@as(usize, if (rows_only) 2 else 3), Trace.calls.items.len); const z: u32 = if (form.control) 9 else 64; - try partial(Trace.calls.items[0], form, false, rows, 0, z, q.part); - try partial(Trace.calls.items[1], form, true, rows, 0, z, q.part); - try merge(Trace.calls.items[2], rows, q.part, q.out); + if (!rows_only) try partial(Trace.calls.items[0], form, false, rows, 0, z, q.part); + try partial(Trace.calls.items[@intFromBool(!rows_only)], form, true, rows, 0, z, q.part); + try merge(Trace.calls.items[if (rows_only) 1 else 2], rows, q.part, q.out); try T.expect(!Trace.bad_attribute); try T.expectEqualSlices(usize, if (form.cache == .bf16) &.{ 1, 2 } else &.{}, Trace.attrs.items); } diff --git a/zig/tests/cuda/contract_q35_launch_args_host.zig b/zig/tests/cuda/contract_q35_launch_args_host.zig index 7976cb3af94..0c4219cc73b 100644 --- a/zig/tests/cuda/contract_q35_launch_args_host.zig +++ b/zig/tests/cuda/contract_q35_launch_args_host.zig @@ -25,7 +25,7 @@ fn word(text: []const u8, at: usize) []const u8 { return text[at..]; } -/// A parameter's kind: the geometry struct, a pointer, a count or a scale. +/// A parameter's kind: geometry struct, pointer, count, scale or Boolean mode. fn classify(param: []const u8) ?sig.Kind { const text = std.mem.trim(u8, param, " \t\r\n"); if (text.len == 0) return null; @@ -35,6 +35,7 @@ fn classify(param: []const u8) ?sig.Kind { if (std.mem.indexOfScalar(u8, text, '*') != null) return .ptr; if (std.mem.eql(u8, first, "int")) return .i32; if (std.mem.eql(u8, first, "float")) return .f32; + if (std.mem.eql(u8, first, "bool")) return .boolean; return null; } @@ -127,11 +128,12 @@ fn tupleElements(a: std.mem.Allocator, tokens: []const Tok, text: []const u8, op return out.items; } -/// The kind a launch site's argument carries: the geometry struct, a pointer, a count or a scale. +/// The kind a launch site's argument carries: geometry struct, pointer, count, scale or Boolean mode. fn argKind(text: []const u8) sig.Kind { if (std.mem.startsWith(u8, text, "@as(f32")) return .f32; if (std.mem.startsWith(u8, text, "@as(c_int")) return .i32; if (std.mem.eql(u8, text, "geo")) return .geo; + if (std.mem.eql(u8, text, "rows_only")) return .boolean; return .ptr; } diff --git a/zig/tests/cuda/contract_qwen_pages.zig b/zig/tests/cuda/contract_qwen_pages.zig index ce296ef5aad..44839b638e6 100644 --- a/zig/tests/cuda/contract_qwen_pages.zig +++ b/zig/tests/cuda/contract_qwen_pages.zig @@ -259,6 +259,7 @@ fn launch(gpu: check.Gpu, s: cuda.Stream, fns: Fns, f: Fixture, tables: ?[2][]co try cuda.launch.launch(t.partial, .{ .grid = .{ .x = @intCast(m), .y = max_chunks, .z = kv_heads }, .block = .{ .x = 128 }, .shared = t.shared }, s, &args); var rows_args: cuda.Args = .{}; inline for (.{ geo, qn, segs_d, rowseg_d, rowanc_d, layer, none, @as(f32, 1.0 / 16.0), @as(c_int, @intCast(m)), pm, pl, po }) |x| rows_args.add(x); + if (f.format == .bf16) rows_args.add(false); const groups = (m + 64 / group - 1) / (64 / group); try cuda.launch.launch(t.rows, .{ .grid = .{ .x = @intCast(groups), .y = max_chunks, .z = kv_heads }, .block = .{ .x = 256 }, .shared = t.shared }, s, &rows_args); } else try cuda.launch.launch(fns.partial, .{ .grid = .{ .x = max_chunks, .y = kv_heads, .z = @intCast(m) }, .block = .{ .x = 32 * group } }, s, &args); diff --git a/zig/tests/cuda/contract_qwen_shared_prefix.zig b/zig/tests/cuda/contract_qwen_shared_prefix.zig index de52f91cf00..e9af24c2eaf 100644 --- a/zig/tests/cuda/contract_qwen_shared_prefix.zig +++ b/zig/tests/cuda/contract_qwen_shared_prefix.zig @@ -169,6 +169,7 @@ fn rows(k: Kernel, f: cuda.Function, s: cuda.Stream, x: Staged) !void { const none: u64 = 0; var args: cuda.Args = .{}; inline for (.{ geo, x.q, x.segs, x.rowseg, x.rowanc, layer, none, scale, @as(c_int, @intCast(x.m)), x.pm, x.pl, x.po }) |v| args.add(v); + if (k.format == .bf16) args.add(false); const groups = (x.m + k.tile_rows - 1) / k.tile_rows; try cuda.launch.launch(f, .{ .grid = .{ .x = @intCast(groups), .y = max_chunks, .z = kv_heads }, .block = .{ .x = k.threads }, .shared = k.shared }, s, &args); } diff --git a/zig/tests/cuda/contract_ricursive.zig b/zig/tests/cuda/contract_ricursive.zig new file mode 100644 index 00000000000..4888f49060c --- /dev/null +++ b/zig/tests/cuda/contract_ricursive.zig @@ -0,0 +1,57 @@ +//! Ripple's CUDA kernels under the contract, with controls (ricursive-contract): glue, attention prep, attention. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const rc = @import("ricursive_cuda"); +const check = @import("check.zig"); +const glue = @import("contract_ricursive_glue.zig"); +const prep = @import("contract_ricursive_prep.zig"); +const attn = @import("contract_ricursive_attn.zig"); + +const g = core.contract.gates; + +/// Every registration, on the heap: the gates hold pointers to them. +pub const Set = struct { + gpa: std.mem.Allocator, + k: rc.kernels.Kernels, + glue: glue.Set = .{}, + prep: *prep.Set = undefined, // its own image, and contract_controls' tf_ctl_rc_prep + attn: *attn.Set = undefined, // window_attention's image (WindowAttention owns it), tree_attention's (GlobalDecode) + + /// The set, its kernels appended to `list`. + pub fn init(gpu: check.Gpu, s: cuda.Stream, a: std.mem.Allocator, list: *std.ArrayList(g.Kernel)) !*Set { + const set = try gpu.gpa.create(Set); + errdefer gpu.gpa.destroy(set); + set.* = .{ .gpa = gpu.gpa, .k = try rc.kernels.Kernels.load(gpu.d) }; + errdefer set.k.unload(); + try set.glue.init(gpu, s, &set.k, a, list); + errdefer set.glue.deinit(); + set.prep = try prep.Set.init(gpu, s, a, list); + errdefer set.prep.deinit(); + set.attn = try attn.Set.init(gpu, s, a, list); + return set; + } + + pub fn deinit(set: *Set) void { + set.attn.deinit(); + set.prep.deinit(); + set.glue.deinit(); + set.k.unload(); + set.gpa.destroy(set); + } +}; + +/// Ripple's kernels' gates 1-4 and their controls alone. +pub fn run(gpu: check.Gpu) !void { + const a = gpu.gpa; + var s = try cuda.Stream.init(gpu.d, false); + defer s.deinit(); + var list: std.ArrayList(g.Kernel) = .empty; + defer list.deinit(a); + const set = try Set.init(gpu, s, a, &list); + defer set.deinit(); + var t: g.Tally = .{}; + try g.runAll(a, list.items, 0x726970, &t); + std.debug.print("SUMMARY ricursive: {d} kernels, {d} pass gates 1-4, {d} fail; {d} controls: {d} red as planted, {d} missed\n", .{ t.kernels, t.passed, t.failed, t.controls, t.caught, t.missed }); + try check.expect(t.problems() == 0, "ricursive-contract: {d} gate failures, {d} controls missed", .{ t.failed, t.missed }); +} diff --git a/zig/tests/cuda/contract_ricursive_attn.zig b/zig/tests/cuda/contract_ricursive_attn.zig new file mode 100644 index 00000000000..cfb1f4d925c --- /dev/null +++ b/zig/tests/cuda/contract_ricursive_attn.zig @@ -0,0 +1,304 @@ +//! Ripple's attention under the contract on CUDA (80/8 heads): prompt rows, sliding decode, global decode over pages. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const rc = @import("ricursive_cuda").attn; +const check = @import("check.zig"); +const rig_ = @import("contract_rig.zig"); +const attn = @import("contract_attn.zig"); +const wk = @import("contract_window.zig"); + +const c = core.contract.spec; +const g = core.contract.gates; +const wa = cuda.window_attention; + +/// Ripple-65B's attention: 80 query heads over 8 key heads, head dim 128, a 1,024-key window in a ring of 3,072. +const h = 80; +const hk = 8; +const window = 1024; +const ring = 3072; +/// Global layers' pages: tree_attention's span, as its decode reads them. +const page = 512; + +/// Sliding chunks: before the window fills, across its edge, and past the ring's wrap (key 9,216 at slot 0). +const sliding_served = [_]c.Shape{ .{ .rows = 333, .n = h, .k = 0 }, .{ .rows = 1000, .n = h, .k = 700 }, .{ .rows = 2048, .n = h, .k = 8216 } }; +/// Global chunks (every key): from the start, past 1,500 keys, and a whole 2,048-row pass. +const global_served = [_]c.Shape{ .{ .rows = 333, .n = h, .k = 0 }, .{ .rows = 1000, .n = h, .k = 1500 }, .{ .rows = 2048, .n = h, .k = 0 } }; +/// A control's one shape: past the window and the ring's wrap, where each fault binds. +const control_served = [_]c.Shape{.{ .rows = 333, .n = h, .k = 8216 }}; +/// The chunk control's: chunks of 333 after the first. +const chunk_served = [_]c.Shape{.{ .rows = 1000, .n = h, .k = 700 }}; + +/// A control's fault: score scale doubled, window doubled, ring one slot short, or later chunks' scale one ulp up. +pub const Fault = enum { none, scale, window, ring, late_scale }; + +/// A prompt registration: the window test's call, cut into `chunk` rows a launch (0: one launch), and its fault. +pub const Cfg = struct { base: wk.Cfg, chunk: usize = 0, fault: Fault = .none }; + +fn slidingCfg(name: []const u8, served: []const c.Shape) wk.Cfg { + return .{ .name = name, .h = h, .hk = hk, .d = 128, .win = window, .ring = ring, .prompt = true, .served = served }; +} + +fn globalCfg(name: []const u8, pages: usize, served: []const c.Shape) wk.Cfg { + return .{ .name = name, .h = h, .hk = hk, .d = 128, .win = 0, .ring = 0, .prompt = true, .pages = pages, .served = served }; +} + +pub const prompts = [_]Cfg{ + .{ .base = slidingCfg("cuda ricursive prompt wattn_kernel<128, 8, 2, 8>, 80/8 heads, window 1024, ring 3072", &sliding_served) }, + .{ .base = globalCfg("cuda ricursive prompt wattn_kernel<128, 8, 2, 8>, 80/8 heads, every key (global layers)", 0, &global_served) }, + .{ .base = globalCfg("cuda ricursive prompt tf_window_prompt_h2_pg, 80/8 heads, every key, pages of 512", page, &global_served) }, + // a row's bits do not depend on its chunk: cuts of the same rows bit-equal to one call + .{ .base = slidingCfg("cuda ricursive prompt in chunks of 1,000, window 1024: one call's bits", &sliding_served), .chunk = 1000 }, + .{ .base = slidingCfg("cuda ricursive prompt in chunks of 333, window 1024: one call's bits", &sliding_served), .chunk = 333 }, + .{ .base = globalCfg("cuda ricursive prompt in chunks of 333, every key: one call's bits", 0, &global_served), .chunk = 333 }, + .{ .base = slidingCfg("control: Ripple's prompt rows with the score scaled twice", &control_served), .fault = .scale }, + .{ .base = slidingCfg("control: Ripple's prompt rows with a window of 2,048 keys", &control_served), .fault = .window }, + .{ .base = slidingCfg("control: Ripple's prompt rows with a ring one slot short (3,071)", &control_served), .fault = .ring }, + .{ .base = .{ .name = "control: Ripple's paged prompt rows whose first page id is a spare page's (all NaN)", .h = h, .hk = hk, .d = 128, .win = 0, .ring = 0, .prompt = true, .pages = page, .stale = true, .served = &control_served } }, + .{ .base = slidingCfg("control: Ripple's prompt in chunks of 333, the later chunks' scale one ulp up", &chunk_served), .chunk = 333, .fault = .late_scale }, +}; + +/// Sliding decode through tf_window_decode_tc as it is: one-row steps past the ring's wrap, and 16-row windows. +pub const decodes = [_]wk.Cfg{ + .{ .name = "cuda ricursive decode tf_window_decode_tc, 80/8 heads, window 1024, ring 3072", .h = h, .hk = hk, .d = 128, .win = window, .ring = ring, .streams = 2, .served = &.{ .{ .rows = 1, .n = h, .k = 9500 }, .{ .rows = 16, .n = h, .k = 3000 } } }, +}; + +/// The P x V chain of a sliding prompt's last row: at most its window's keys, a tile at a time, then the fold. +fn slidingChain(s: c.Shape) usize { + return @min(s.k + s.rows, window) + 64 + 64; +} + +/// A global prompt's last row: every key to its own. +fn globalChain(s: c.Shape) usize { + return s.k + s.rows + 64 + 64; +} + +/// Global decode: two pages' rows across a page's edge, rows 1 and 16 from the first key, a page's first key, deep. +const gdec_served = [_]c.Shape{ .{ .rows = 16, .n = h, .k = 505 }, .{ .rows = 1, .n = h, .k = 0 }, .{ .rows = 16, .n = h, .k = 0 }, .{ .rows = 1, .n = h, .k = 512 }, .{ .rows = 1, .n = h, .k = 30000 }, .{ .rows = 16, .n = h, .k = 30000 } }; +/// A control's shape: 16 rows across a page's edge. +const gdec_control = [_]c.Shape{.{ .rows = 16, .n = h, .k = 505 }}; +/// The short control's: rows over their first keys, where one key is much of a row's weight. +const gdec_short = [_]c.Shape{.{ .rows = 16, .n = h, .k = 1 }}; +/// GlobalDecode's rows and keys in the contract: the served shapes' most. +const global_rows = 16; +const global_context = 30000 + 16; + +/// Gate 4 at 30,000 keys: past about 8,000 keys the stress values' sums leave fp32's 24 bits, so no order is exact. +const deep_sums: c.Sums = .{ .bf16 = 0, .exact = false, .why = "past 8,000 keys the stress values' sums leave fp32's 24 bits: gate 4 holds the float64 bound, which fp16 sums overflow" }; + +/// A global decode control's fault: score scale doubled, each row one key short, or 64 query heads (group 8). +pub const GlobalFault = enum { none, scale, short, heads }; + +/// A global decode registration: the window test's paged prompt rows (row r at k + r over keys 0..k + r). +pub const GlobalCfg = struct { base: wk.Cfg, fault: GlobalFault = .none }; + +fn pagedCfg(name: []const u8, served: []const c.Shape, stale: bool) wk.Cfg { + return .{ .name = name, .h = h, .hk = hk, .d = 128, .win = 0, .ring = 0, .prompt = true, .pages = page, .stale = stale, .served = served }; +} + +pub const globals = [_]GlobalCfg{ + .{ .base = pagedCfg("cuda ricursive global decode tf_tree_*_pg + tf_tree_merge, 80/8 heads, every key, pages of 512", &gdec_served, false) }, + .{ .base = pagedCfg("control: Ripple's global decode with the score scaled twice", &gdec_control, false), .fault = .scale }, + .{ .base = pagedCfg("control: Ripple's global decode whose first page id is a spare page's (all NaN)", &gdec_control, true) }, + .{ .base = pagedCfg("control: Ripple's global decode with each row one key short", &gdec_short, false), .fault = .short }, + .{ .base = pagedCfg("control: Ripple's global decode with 64 query heads over the 8 key heads (group 8)", &gdec_control, false), .fault = .heads }, +}; + +/// Decode rows: rows, query heads and the first row's position; tree_attention's 16-pair tiles and 512-key groups. +pub fn globalSpec(f: GlobalCfg) c.Spec { + const b = f.base; + return .{ .name = b.name, .accum = .f32, .depth = &globalChain, .ops = 1, .out = .bf16, .tiles = .{ .{ .size = 16 }, .{}, .{ .size = page, .min = 0 } }, .served = b.served, .sums = deep_sums }; +} + +/// Prompt rows: chunk rows, query heads and the chunk's start; 64-row blocks, 64-key tiles. +pub fn spec(f: Cfg) c.Spec { + const b = f.base; + return .{ .name = b.name, .accum = .f32, .depth = if (b.win > 0) &slidingChain else &globalChain, .ops = 1, .out = .bf16, .replaces = if (f.chunk > 0) "wattn_kernel<128, 8, 2, 8> in one call" else null, .tiles = .{ .{ .size = rc.rows_a_block }, .{}, .{ .size = 64, .min = 0 } }, .served = b.served, .sums = .{ .why = attn.why } }; +} + +pub const Prompt = struct { + rig: *rig_.Rig, // the window test's own + w: wk.Window, + k: *const rc.Kernels, + f: Cfg, + base: u64 = 0, // chunked: the one call's output (scratch) + + pub fn deinit(self: *Prompt) void { + self.w.deinit(); + } + + pub fn kernel(self: *Prompt) g.Kernel { + const control = self.f.fault != .none or self.f.base.stale; + return .{ .spec = spec(self.f), .ctx = self, .vt = &vt, .control = if (control) .shapes else null }; + } + + const vt = g.hooks(Prompt); + + pub fn prepare(self: *Prompt, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (!try self.w.prepare(shape, fill, seed)) return false; + if (self.f.chunk > 0) self.base = try self.rig.scratch(self.w.count() * 2); + return true; + } + + /// The launch's window: the registration's, with its control's fault (`later`: a chunk after the first). + fn window(self: *const Prompt, later: bool) wa.Window { + const f = self.f.base; + const scale: f32 = @floatCast(1 / @sqrt(@as(f64, @floatFromInt(f.d)))); // the window test's, so its reference's + const pg: ?wa.Pages = if (f.pages > 0) .{ .table = self.w.table, .page_elems = 2 * f.pages * f.hk * f.d, .tokens = f.pages } else null; + var w = if (f.win > 0) rc.sliding(f.h, f.hk, f.win, f.ring, scale) else rc.global(f.h, f.hk, scale, pg); + switch (self.f.fault) { + .none => {}, + .scale => w.scale *= 2, + .window => w.win *= 2, + .ring => w.ring -= 1, + .late_scale => if (later) { + w.scale = std.math.nextAfter(f32, w.scale, 1); + }, + } + return w; + } + + /// Rows [r, r + m) of the prepared call into `out`, at positions k + r, ... + fn launch(self: *Prompt, r: usize, m: usize, out: u64) !void { + const at = r * self.f.base.h * self.f.base.d * 2; // a row's heads, bf16, in q and out + const w = &self.w; + try rc.prompt(self.k, self.rig.s, w.dev[0] + at, w.dev[1], w.dev[2], out + at, w.shape.k + r, m, self.window(r > 0)); + } + + pub fn run(self: *Prompt) !void { + const n = self.w.shape.rows; + const step = if (self.f.chunk > 0) self.f.chunk else n; + var r: usize = 0; + while (r < n) : (r += step) try self.launch(r, @min(step, n - r), self.w.out); + try self.rig.s.synchronize(); + } + + /// The chunks' baseline: the prepared rows in one call. + pub fn replaced(self: *Prompt) ![]const u8 { + const n = self.w.shape.rows; + try rc.prompt(self.k, self.rig.s, self.w.dev[0], self.w.dev[1], self.w.dev[2], self.base, self.w.shape.k, n, self.window(false)); + return try self.rig.bytes(self.base, self.w.count() * 2); + } + + pub fn count(self: *Prompt) usize { + return self.w.count(); + } + + pub fn check(self: *Prompt, gate: g.Gate) !?[]const u8 { + return self.w.check(gate); + } + + pub fn reference(self: *Prompt, want: []f64, mag: []f64) !void { + return self.w.reference(want, mag); + } + + pub fn simulate(self: *Prompt, acc: c.Accum, order: g.Order, out: []f64) !void { + return self.w.simulate(acc, order, out); + } +}; + +/// Global decode through rc.decodeGlobal, over the window test's paged prompt inputs and its float64 reference. +pub const Global = struct { + rig: *rig_.Rig, // the window test's own + w: wk.Window, + gd: *const rc.GlobalDecode, + f: GlobalCfg, + + pub fn deinit(self: *Global) void { + self.w.deinit(); + } + + pub fn kernel(self: *Global) g.Kernel { + const control = self.f.fault != .none or self.f.base.stale; + return .{ .spec = globalSpec(self.f), .ctx = self, .vt = &vt, .control = if (control) .shapes else null }; + } + + const vt = g.hooks(Global); + + pub fn prepare(self: *Global, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.rows > self.gd.max_rows or shape.k + shape.rows > self.gd.context) return false; + return self.w.prepare(shape, fill, seed); + } + + pub fn run(self: *Global) !void { + const f = self.f.base; + const w = &self.w; + var a: rc.DecodeArgs = .{ + .q = w.dev[0], + .kc = w.dev[1], + .vc = w.dev[2], + .out = w.out, + .pos = w.shape.k, + .rows = w.shape.rows, + .pages = .{ .table = w.table, .page_elems = 2 * f.pages * f.hk * f.d, .tokens = f.pages }, + .scale = @floatCast(1 / @sqrt(@as(f64, @floatFromInt(f.d)))), // the window test's, so its reference's + }; + switch (self.f.fault) { + .none, .heads => {}, + .scale => a.scale *= 2, + .short => a.pos -|= 1, + } + if (self.f.fault == .heads) try rc.decodeHeads(self.gd, w.rig.s, a, 64) else try rc.decodeGlobal(self.gd, w.rig.s, a); + try w.rig.s.synchronize(); + } + + pub fn count(self: *Global) usize { + return self.w.count(); + } + + pub fn check(self: *Global, gate: g.Gate) !?[]const u8 { + return self.w.check(gate); + } + + pub fn reference(self: *Global, want: []f64, mag: []f64) !void { + return self.w.reference(want, mag); + } + + pub fn simulate(self: *Global, acc: c.Accum, order: g.Order, out: []f64) !void { + return self.w.simulate(acc, order, out); + } +}; + +/// Every registration, on the heap: the gates hold pointers to them, and each prompt's rig pointer into itself. +pub const Set = struct { + gpa: std.mem.Allocator, + win: wa.WindowAttention, + k: rc.Kernels = undefined, + gd: rc.GlobalDecode = undefined, + prompts: [prompts.len]Prompt = undefined, + decodes: [decodes.len]wk.Window = undefined, + globals: [globals.len]Global = undefined, + + /// The set, its kernels appended to `list`. + pub fn init(gpu: check.Gpu, s: cuda.Stream, a: std.mem.Allocator, list: *std.ArrayList(g.Kernel)) !*Set { + const set = try gpu.gpa.create(Set); + errdefer gpu.gpa.destroy(set); + set.* = .{ .gpa = gpu.gpa, .win = try wa.WindowAttention.load(gpu.d) }; + errdefer set.win.unload(); + set.k = try rc.Kernels.init(&set.win); + set.gd = try rc.GlobalDecode.init(gpu.d, gpu.gpa, global_rows, global_context); + errdefer set.gd.deinit(); + for (&set.prompts, prompts) |*x, f| { + x.* = .{ .rig = undefined, .w = .{ .rig = .{ .gpu = gpu, .s = s }, .f = f.base, .g = &set.win }, .k = &set.k, .f = f }; + x.rig = &x.w.rig; + } + for (&set.decodes, decodes) |*x, f| x.* = .{ .rig = .{ .gpu = gpu, .s = s }, .f = f, .g = &set.win }; + for (&set.globals, globals) |*x, f| { + x.* = .{ .rig = undefined, .w = .{ .rig = .{ .gpu = gpu, .s = s }, .f = f.base, .g = &set.win }, .gd = &set.gd, .f = f }; + x.rig = &x.w.rig; + } + for (&set.prompts) |*x| try list.append(a, x.kernel()); + for (&set.decodes) |*x| try list.append(a, x.kernel()); + for (&set.globals) |*x| try list.append(a, x.kernel()); + return set; + } + + pub fn deinit(set: *Set) void { + for (&set.prompts) |*x| x.deinit(); + for (&set.decodes) |*x| x.deinit(); + for (&set.globals) |*x| x.deinit(); + set.gd.deinit(); + set.win.unload(); + set.gpa.destroy(set); + } +}; diff --git a/zig/tests/cuda/contract_ricursive_glue.zig b/zig/tests/cuda/contract_ricursive_glue.zig new file mode 100644 index 00000000000..e51c8fd8838 --- /dev/null +++ b/zig/tests/cuda/contract_ricursive_glue.zig @@ -0,0 +1,492 @@ +//! Ripple's CUDA glue under the contract: tf_rc_embed, tf_rc_add_norm (four forms), tf_rc_gate, tf_rc_silu_clamp. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const rc = @import("ricursive_cuda"); +const check = @import("check.zig"); +const rig_ = @import("contract_rig.zig"); +const ref = @import("contract_minimax_glue_ref.zig"); // the family-neutral Gated wrapper and fills + +const c = core.contract.spec; +const g = core.contract.gates; +const kern = rc.kernels; +const Iv = ref.Iv; +const Sums = ref.Sums; +const Kernels = kern.Kernels; +const Function = cuda.Function; + +const hidden = 5120; +const query = 80 * 128; // the output gate's rows: query heads x head dim +const intermediate = 40960; +const vocab = 100352; +const eps: f32 = 1e-6; +const embed_scale: f32 = 71.55417527999327; +const limit: f32 = 20; // the FFN's clamp + +/// The forward's row counts at width n: decode 1 to 16, odd tails and prompt chunks up to 2,048. +fn rowsAt(n: usize, k: usize) [7]c.Shape { + var out: [7]c.Shape = undefined; + for ([_]usize{ 16, 1, 3, 7, 333, 1000, 2048 }, &out) |r, *s| s.* = .{ .rows = r, .n = n, .k = k }; + return out; +} + +const embed_rows = rowsAt(hidden, 1); +const norm_rows = rowsAt(hidden, hidden); +const gate_rows = rowsAt(query, 1); +const silu_rows = rowsAt(intermediate, 2 * intermediate); +const elementwise: c.Tile = .{ .size = 256, .step = 1, .min = 1 }; + +pub fn embedSpec(control: bool) c.Spec { + const name = if (control) "control: cuda ricursive tf_rc_embed, the scale rounded to bf16 (71.5)" else "cuda ricursive tf_rc_embed (fp32 scale, rounded once; R and V0)"; + return .{ .name = name, .accum = .none, .depth = ref.noSums, .out = .bf16, .tiles = .{ .{}, elementwise, .{} }, .served = &embed_rows }; +} + +/// R and V0 = bf16(E[ids] * scale) over the whole vocabulary's table: row 0 reads its last row. +pub const Embed = struct { + kern: *const Kernels, + f: Function, + /// control: the scale rounded to bf16 before the product + ctl: bool = false, + shape: c.Shape = undefined, + table: []u16 = &.{}, + ids: []u32 = &.{}, + dev: [2]u64 = @splat(0), // the table, the ids + out: [2]u64 = @splat(0), // R, V0 + + pub fn spec(self: *const Embed) c.Spec { + return embedSpec(self.ctl); + } + + pub fn control(self: *const Embed) ?g.Gate { + return if (self.ctl) .shapes else null; + } + + pub fn free(self: *Embed, a: std.mem.Allocator) void { + a.free(self.table); + a.free(self.ids); + self.table = &.{}; + self.ids = &.{}; + } + + /// The rows the ids read in [-1, 1), the rest zero (never read); non-finite: NaN, +Inf, -Inf in the first rows. + pub fn prepare(self: *Embed, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { + if (shape.rows == 0 or shape.n == 0) return false; + self.free(a); + self.shape = shape; + const n = shape.n; + self.ids = try a.alloc(u32, shape.rows); + for (self.ids, 0..) |*id, r| id.* = if (r == 0) vocab - 1 else rng.uintLessThan(u32, vocab); + self.table = try a.alloc(u16, vocab * n); + @memset(self.table, 0); + for (self.ids) |id| for (self.table[@as(usize, id) * n ..][0..n]) |*v| { + v.* = c.toBf16(rng.float(f32) * 2 - 1); + }; + if (fill == .nonfinite) for ([_]f32{ ref.nan, ref.inf, -ref.inf }, 0..) |x, r| if (r < shape.rows) { + self.table[@as(usize, self.ids[r]) * n + (7 * r + 1) % n] = c.toBf16(x); + }; + self.dev = .{ try ref.input(rig, self.table), try ref.input(rig, self.ids) }; + self.out = .{ try rig.output(shape.rows * n * 2), try rig.output(shape.rows * n * 2) }; + return true; + } + + pub fn run(self: *Embed, rig: *rig_.Rig) !void { + try kern.embedBy(self.f, rig.s, self.dev[1], self.dev[0], self.out[0], self.out[1], self.shape.rows, self.shape.n, embed_scale); + } + + pub fn count(self: *const Embed) usize { + return 2 * self.shape.rows * self.shape.n; + } + + pub fn solve(self: *const Embed, _: std.mem.Allocator, _: Sums, out: []Iv) !void { + const n = self.shape.n; + const half = self.shape.rows * n; + for (0..self.shape.rows) |r| for (0..n) |i| { + const v = Iv.of(ref.bf(self.table[@as(usize, self.ids[r]) * n + i])).mul(Iv.of(embed_scale)).bf(); + out[r * n + i] = v; + out[half + r * n + i] = v; + }; + } +}; + +/// tf_rc_add_norm's forms in the forward: a first norm (plain or with v's lerp), an add, an add into the next lerp. +pub const Form = enum { plain, lerp, add, add_lerp }; + +/// A control's dropped rounding point (ricursive.cuh's add_norm bits). +pub const Point = enum { y_row, y_out, resid, x_row, x_lerp }; + +fn adds(f: Form) bool { + return f == .add or f == .add_lerp; +} + +fn lerps(f: Form) bool { + return f == .lerp or f == .add_lerp; +} + +/// The blend each lerp form runs at: below one half and above it, torch.lerp's two branches. +fn blendOf(f: Form) f32 { + return if (f == .add_lerp) 0.69921875 else 0.30078125; +} + +/// A thread's fma chain (8 values a chunk, a chunk per 2,048 of the row), the warp's 5 shuffles and the block's 5. +fn normDepth(s: c.Shape) usize { + return 8 * ((s.n + 2047) / 2048) + 10; +} + +pub fn normSpec(f: Form, drop: ?Point) c.Spec { + const name = if (drop) |p| switch (p) { + .y_row => "control: cuda ricursive tf_rc_add_norm without bf16(y / rms)", + .y_out => "control: cuda ricursive tf_rc_add_norm without bf16(w_post y / rms)", + .resid => "control: cuda ricursive tf_rc_add_norm, the next norm reads the residual before its bf16", + .x_row => "control: cuda ricursive tf_rc_add_norm without bf16(r / rms)", + .x_lerp => "control: cuda ricursive tf_rc_add_norm, the lerp reads X before its bf16", + } else switch (f) { + .plain => "cuda ricursive tf_rc_add_norm (X = norm(R))", + .lerp => "cuda ricursive tf_rc_add_norm lerp (X and lerp(V0, X), blend below one half)", + .add => "cuda ricursive tf_rc_add_norm add (R += norm(Y), in place, then X)", + .add_lerp => "cuda ricursive tf_rc_add_norm add lerp (R += norm(Y), X, lerp(V0, X) above one half)", + }; + const chunks: c.Tile = .{ .size = 2048, .step = 8, .min = 8 }; // a thread's chunk per 2,048 of the row + return .{ .name = name, .accum = .f32, .depth = normDepth, .out = .bf16, .in_place = adds(f), .tiles = .{ .{}, chunks, .{} }, .served = &norm_rows, .sums = .{} }; +} + +/// Residual rows as bf16: [-1, 1), one in 64 twenty times larger; stress: integers in [-32, 32]. +fn residual(a: std.mem.Allocator, rng: std.Random, n: usize, fill: g.Fill) ![]u16 { + const x = try a.alloc(u16, n); + for (x, 0..) |*v, i| v.* = c.toBf16(if (fill == .stress) ref.int(rng, -32, 32) else (rng.float(f32) * 2 - 1) * (if (i % 64 == 7) @as(f32, 20) else 1)); + return x; +} + +/// NaN, +Inf and -Inf at known places: a row each, row 3 holding both infinities. +fn plant(x: []u16, rows: usize, n: usize) void { + const at = [_][2]usize{ .{ 0, n / 3 }, .{ 1, n / 2 }, .{ 2, n - 1 }, .{ 3, 0 }, .{ 3, n - 1 } }; + const put = [_]f32{ ref.nan, ref.inf, -ref.inf, ref.inf, -ref.inf }; + for (at, put) |p, v| if (p[0] < rows) { + x[p[0] * n + p[1]] = c.toBf16(v); + }; +} + +/// 1 / rms of a row's values (ranges): an fp32 sum of squares over `depth` roundings, then 1 / sqrt(mean + eps). +fn invRms(s: Sums, x: []const Iv, depth: usize, scratch: []f64, sq: []Iv) Iv { + for (sq, x) |*q, v| { + const lo = @min(@abs(v.lo), @abs(v.hi)); + const hi = @max(@abs(v.lo), @abs(v.hi)); + q.* = .{ .m = v.m * v.m, .lo = if (v.lo <= 0 and v.hi >= 0) 0 else lo * lo, .hi = hi * hi }; + } + const total = s.sum(sq, depth, scratch); + return total.div(Iv.of(@floatFromInt(x.len))).add(Iv.of(eps)).rsqrt(); +} + +/// torch.lerp as the kernel's fma: w (e - s) + s below one half, (w - 1)(e - s) + e above it; rounded to bf16 once. +fn lerp(s: Iv, e: Iv, w: f32) Iv { + const d = e.sub(s); + return (if (@abs(w) < 0.5) Iv.of(w).mul(d).add(s) else Iv.of(w - 1).mul(d).add(e)).bf(); +} + +/// tf_rc_add_norm on hidden-wide rows: R, w_next; Y and w_post with the add; V0 and the blend with the lerp. +pub const AddNorm = struct { + kern: *const Kernels, + f: Function, + form: Form, + drop: ?Point = null, + shape: c.Shape = undefined, + r: []u16 = &.{}, // R before the launch + y: []u16 = &.{}, + post: []u16 = &.{}, + next: []u16 = &.{}, + v0: []u16 = &.{}, + p: kern.NormRows = undefined, + + pub const sums = {}; + + pub fn spec(self: *const AddNorm) c.Spec { + return normSpec(self.form, self.drop); + } + + pub fn control(self: *const AddNorm) ?g.Gate { + return if (self.drop != null) .shapes else null; + } + + pub fn free(self: *AddNorm, a: std.mem.Allocator) void { + for ([_]*[]u16{ &self.r, &self.y, &self.post, &self.next, &self.v0 }) |s| { + a.free(s.*); + s.* = &.{}; + } + } + + /// Y in [-0.5, 0.5), weights [0.5, 1.5), V0 [-2, 2); stress: Y zero; non-finite: in Y (add) or R, V0 rows 4-6. + pub fn prepare(self: *AddNorm, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { + if (shape.rows == 0 or shape.n == 0 or shape.n % 8 != 0 or shape.n > kern.most_width) return false; + self.free(a); + self.shape = shape; + const rows = shape.rows; + const n = shape.n; + const add = adds(self.form); + const mix = lerps(self.form); + self.r = try residual(a, rng, rows * n, fill); + self.y = try ref.bfs(a, rng, if (add) rows * n else 0, -0.5, 0.5); + if (fill == .stress) @memset(self.y, 0); + self.post = try ref.bfs(a, rng, if (add) n else 0, 0.5, 1.5); + self.next = try ref.bfs(a, rng, n, 0.5, 1.5); + self.v0 = try ref.bfs(a, rng, if (mix) rows * n else 0, -2, 2); + if (fill == .nonfinite) { + plant(if (add) self.y else self.r, rows, n); + if (mix) for ([_]f32{ ref.nan, ref.inf, -ref.inf }, 4..) |x, row| if (row < rows) { + self.v0[row * n + n / 4] = c.toBf16(x); + }; + } + const bytes = rows * n * 2; + self.p = .{ .resid = 0, .next = try ref.input(rig, self.next), .x = 0, .rows = rows, .width = n, .eps = eps, .blend = if (mix) blendOf(self.form) else 0 }; + if (add) { + self.p.branch = try ref.input(rig, self.y); + self.p.post = try ref.input(rig, self.post); + self.p.resid = try rig.output(bytes); // in place: restored before each launch + } else self.p.resid = try ref.input(rig, self.r); + if (mix) self.p.v0 = try ref.input(rig, self.v0); + self.p.x = try rig.output(bytes); + if (mix) self.p.vx = try rig.output(bytes); + return true; + } + + pub fn run(self: *AddNorm, rig: *rig_.Rig) !void { + if (adds(self.form)) try ref.restore(rig, self.p.resid, std.mem.sliceAsBytes(self.r)); // read and written in place: every run the same pass + try kern.addNormBy(self.f, rig.s, self.p); + } + + pub fn count(self: *const AddNorm) usize { + const outs = 1 + @as(usize, @intFromBool(adds(self.form))) + @intFromBool(lerps(self.form)); + return outs * self.shape.rows * self.shape.n; + } + + /// The outputs in the order prepare allocates them: R (with the add), X, VX (with the lerp). + pub fn solve(self: *const AddNorm, a: std.mem.Allocator, s: Sums, out: []Iv) !void { + const n = self.shape.n; + const total = self.shape.rows * n; + const buf = try a.alloc(Iv, 3 * n); + defer a.free(buf); + const scratch = try a.alloc(f64, n); + defer a.free(scratch); + const depth = normDepth(self.shape); + const r = buf[0..n]; + const y = buf[n .. 2 * n]; + const sq = buf[2 * n ..]; + const lead: usize = if (adds(self.form)) total else 0; + const out_r = out[0..lead]; + const out_x = out[lead..][0..total]; + const out_vx = out[lead + total ..]; + for (0..self.shape.rows) |row| { + const o = row * n; + for (r, self.r[o..][0..n]) |*v, h| v.* = Iv.of(ref.bf(h)); + if (adds(self.form)) { + for (y, self.y[o..][0..n]) |*v, h| v.* = Iv.of(ref.bf(h)); + const inv_y = invRms(s, y, depth, scratch, sq); + for (r, y, self.post) |*v, yv, w| v.* = v.add(Iv.of(ref.bf(w)).mul(yv.mul(inv_y).bf()).bf()).bf(); + @memcpy(out_r[o..][0..n], r); + } + const inv = invRms(s, r, depth, scratch, sq); + for (out_x[o..][0..n], r, self.next) |*x, v, w| x.* = Iv.of(ref.bf(w)).mul(v.mul(inv).bf()).bf(); + if (lerps(self.form)) for (out_vx[o..][0..n], out_x[o..][0..n], self.v0[o..][0..n]) |*vx, x, h| { + vx.* = lerp(Iv.of(ref.bf(h)), x, blendOf(self.form)); + }; + } + } +}; + +/// The control kernel without point `p` (ricursive.cu's tf_rc_ctl_add_norm_*). +fn dropped(k: *const Kernels, p: Point) !Function { + return switch (p) { + .y_row => k.mod.function("tf_rc_ctl_add_norm_y_row"), + .y_out => k.mod.function("tf_rc_ctl_add_norm_y_out"), + .resid => k.mod.function("tf_rc_ctl_add_norm_resid"), + .x_row => k.mod.function("tf_rc_ctl_add_norm_x_row"), + .x_lerp => k.mod.function("tf_rc_ctl_add_norm_x_lerp"), + }; +} + +pub fn gateSpec(control: bool) c.Spec { + const name = if (control) "control: cuda ricursive tf_rc_gate without bf16(sigmoid(g))" else "cuda ricursive tf_rc_gate (fp32 sigmoid then bf16, in place)"; + return .{ .name = name, .accum = .none, .depth = ref.noSums, .out = .bf16, .in_place = true, .tiles = .{ .{}, elementwise, .{} }, .served = &gate_rows }; +} + +/// A = bf16(A * bf16(sigmoid(G))) in place: A in [-4, 4), G in [-12, 12); non-finite: G's NaN and infinities, then A's. +pub const Gate = struct { + kern: *const Kernels, + f: Function, + /// control: the sigmoid left in fp32 + ctl: bool = false, + shape: c.Shape = undefined, + act: []u16 = &.{}, + gv: []u16 = &.{}, + dev_a: u64 = 0, + dev_g: u64 = 0, + + pub fn spec(self: *const Gate) c.Spec { + return gateSpec(self.ctl); + } + + pub fn control(self: *const Gate) ?g.Gate { + return if (self.ctl) .shapes else null; + } + + pub fn free(self: *Gate, a: std.mem.Allocator) void { + a.free(self.act); + a.free(self.gv); + self.act = &.{}; + self.gv = &.{}; + } + + pub fn prepare(self: *Gate, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { + if (shape.rows == 0 or shape.n == 0) return false; + self.free(a); + self.shape = shape; + const n = shape.n; + self.act = try ref.bfs(a, rng, shape.rows * n, -4, 4); + self.gv = try ref.bfs(a, rng, shape.rows * n, -12, 12); + if (fill == .nonfinite) { + const put = [_]struct { usize, bool, f32 }{ .{ 0, true, ref.nan }, .{ 1, true, ref.inf }, .{ 2, true, -ref.inf }, .{ 3, false, ref.nan }, .{ 4, false, ref.inf }, .{ 5, false, -ref.inf } }; + for (put) |p| if (p[0] < shape.rows) { + (if (p[1]) self.gv else self.act)[p[0] * n + p[0] + 1] = c.toBf16(p[2]); + }; + } + self.dev_g = try ref.input(rig, self.gv); + self.dev_a = try rig.output(shape.rows * n * 2); // in place: restored before each launch + return true; + } + + pub fn run(self: *Gate, rig: *rig_.Rig) !void { + try ref.restore(rig, self.dev_a, std.mem.sliceAsBytes(self.act)); + try kern.gateBy(self.f, rig.s, self.dev_a, self.dev_g, self.shape.rows, self.shape.n); + } + + pub fn count(self: *const Gate) usize { + return self.shape.rows * self.shape.n; + } + + pub fn solve(self: *const Gate, _: std.mem.Allocator, _: Sums, out: []Iv) !void { + for (out, self.act, self.gv) |*o, x, gh| o.* = Iv.of(ref.bf(x)).mul(Iv.of(ref.bf(gh)).sigmoid().bf()).bf(); + } +}; + +/// A SiLU-clamp control: the silu left in fp32, or up clamped above only. +pub const SiluDrop = enum { round, lower }; + +const silu_nan = "torch.clamp's bounds: a NaN gate or up gives NaN, +Inf reads as the limit, a -Inf up as -limit; a -Inf gate gives NaN (-Inf / Inf)"; + +pub fn siluSpec(drop: ?SiluDrop) c.Spec { + const name = if (drop) |d| switch (d) { + .round => "control: cuda ricursive tf_rc_silu_clamp without bf16(silu(g))", + .lower => "control: cuda ricursive tf_rc_silu_clamp, up clamped above only", + } else "cuda ricursive tf_rc_silu_clamp (stacked gate | up, clamp 20)"; + return .{ .name = name, .accum = .none, .depth = ref.noSums, .out = .bf16, .nan = .{ .stated = silu_nan }, .tiles = .{ .{}, elementwise, .{} }, .served = &silu_rows }; +} + +/// bf16(bf16(silu(min(g, 20))) * clamp(u, -20, 20)) from stacked gate | up rows, as the up-gate projection writes them. +pub const SiluClamp = struct { + kern: *const Kernels, + f: Function, + drop: ?SiluDrop = null, + shape: c.Shape = undefined, + gate: []u16 = &.{}, + up: []u16 = &.{}, + dev: u64 = 0, + out: u64 = 0, + + pub fn spec(self: *const SiluClamp) c.Spec { + return siluSpec(self.drop); + } + + pub fn control(self: *const SiluClamp) ?g.Gate { + return if (self.drop != null) .shapes else null; + } + + pub fn free(self: *SiluClamp, a: std.mem.Allocator) void { + a.free(self.gate); + a.free(self.up); + self.gate = &.{}; + self.up = &.{}; + } + + /// Gate and up in [-30, 30) (past the clamp both ways); non-finite: NaN, +Inf and -Inf in each of gate and up. + pub fn prepare(self: *SiluClamp, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { + if (shape.rows == 0 or shape.n == 0) return false; + self.free(a); + self.shape = shape; + const rows = shape.rows; + const n = shape.n; + self.gate = try ref.bfs(a, rng, rows * n, -30, 30); + self.up = try ref.bfs(a, rng, rows * n, -30, 30); + if (fill == .nonfinite) { + const put = [_]struct { usize, bool, f32 }{ .{ 0, true, ref.nan }, .{ 1, true, ref.inf }, .{ 2, true, -ref.inf }, .{ 3, false, ref.nan }, .{ 4, false, ref.inf }, .{ 5, false, -ref.inf } }; + for (put) |p| if (p[0] < rows) { + (if (p[1]) self.gate else self.up)[p[0] * n + p[0] + 1] = c.toBf16(p[2]); + }; + } + const both = try a.alloc(u16, 2 * rows * n); + defer a.free(both); + for (0..rows) |r| { + @memcpy(both[2 * r * n ..][0..n], self.gate[r * n ..][0..n]); + @memcpy(both[(2 * r + 1) * n ..][0..n], self.up[r * n ..][0..n]); + } + self.dev = try ref.input(rig, both); + self.out = try rig.output(rows * n * 2); + return true; + } + + pub fn run(self: *SiluClamp, rig: *rig_.Rig) !void { + try kern.siluClampBy(self.f, rig.s, self.dev, self.out, self.shape.rows, self.shape.n, limit); + } + + pub fn count(self: *const SiluClamp) usize { + return self.shape.rows * self.shape.n; + } + + pub fn solve(self: *const SiluClamp, _: std.mem.Allocator, _: Sums, out: []Iv) !void { + for (out, self.gate, self.up) |*o, gh, uh| { + const gv = Iv.of(ref.bf(gh)).atMost(limit); + const u = Iv.of(ref.bf(uh)).atMost(limit).atLeast(-limit); + const silu = gv.div(Iv.of(1).add(gv.neg().exp())).bf(); + o.* = silu.mul(u).bf(); + } + } +}; + +/// The glue's registrations, held where the gates point at them (the caller's heap set). +pub const Set = struct { + embeds: [2]ref.Gated(Embed) = undefined, + norms: [4]ref.Gated(AddNorm) = undefined, + norm_ctls: [5]ref.Gated(AddNorm) = undefined, + gates: [2]ref.Gated(Gate) = undefined, + silus: [3]ref.Gated(SiluClamp) = undefined, + + /// Every registration over `k`, appended to `list` (each control after the kernel it breaks). + pub fn init(set: *Set, gpu: check.Gpu, s: cuda.Stream, k: *const Kernels, a: std.mem.Allocator, list: *std.ArrayList(g.Kernel)) !void { + const rig: rig_.Rig = .{ .gpu = gpu, .s = s }; + set.embeds = .{ + .{ .rig = rig, .k = .{ .kern = k, .f = k.embed } }, + .{ .rig = rig, .k = .{ .kern = k, .f = try k.mod.function("tf_rc_ctl_embed_bf16_scale"), .ctl = true } }, + }; + for (&set.norms, std.enums.values(Form)) |*x, f| x.* = .{ .rig = rig, .k = .{ .kern = k, .f = k.add_norm, .form = f } }; + for (&set.norm_ctls, std.enums.values(Point)) |*x, p| x.* = .{ .rig = rig, .k = .{ .kern = k, .f = try dropped(k, p), .form = .add_lerp, .drop = p } }; + set.gates = .{ + .{ .rig = rig, .k = .{ .kern = k, .f = k.gate } }, + .{ .rig = rig, .k = .{ .kern = k, .f = try k.mod.function("tf_rc_ctl_gate_sigmoid"), .ctl = true } }, + }; + set.silus = .{ + .{ .rig = rig, .k = .{ .kern = k, .f = k.silu_clamp } }, + .{ .rig = rig, .k = .{ .kern = k, .f = try k.mod.function("tf_rc_ctl_silu_round"), .drop = .round } }, + .{ .rig = rig, .k = .{ .kern = k, .f = try k.mod.function("tf_rc_ctl_silu_no_lower"), .drop = .lower } }, + }; + for (&set.embeds) |*x| try list.append(a, x.kernel()); + for (&set.norms) |*x| try list.append(a, x.kernel()); + for (&set.norm_ctls) |*x| try list.append(a, x.kernel()); + for (&set.gates) |*x| try list.append(a, x.kernel()); + for (&set.silus) |*x| try list.append(a, x.kernel()); + } + + pub fn deinit(set: *Set) void { + for (&set.embeds) |*x| x.deinit(); + for (&set.norms) |*x| x.deinit(); + for (&set.norm_ctls) |*x| x.deinit(); + for (&set.gates) |*x| x.deinit(); + for (&set.silus) |*x| x.deinit(); + } +}; diff --git a/zig/tests/cuda/contract_ricursive_prep.zig b/zig/tests/cuda/contract_ricursive_prep.zig new file mode 100644 index 00000000000..34e68d2c7d6 --- /dev/null +++ b/zig/tests/cuda/contract_ricursive_prep.zig @@ -0,0 +1,560 @@ +//! Ripple's CUDA attention prep under the contract: tf_rc_prep with its controls, tf_rc_prep_rows bit-equal to it. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const rp = @import("ricursive_cuda").prep; +const check = @import("check.zig"); +const rig_ = @import("contract_rig.zig"); +const ref = @import("contract_minimax_glue_ref.zig"); + +const c = core.contract.spec; +const g = core.contract.gates; +const Iv = ref.Iv; +const Sums = ref.Sums; + +const controls = struct { + pub const bytes align(16) = @embedFile("fatbin_contract_controls").*; +}; + +const D = 128; +const heads = 80; +const kv_heads = 8; +const kvw = kv_heads * D; +const qk_stride = (heads + kv_heads) * D; // a fused q | k projection's row; v is its own projection +const width = (heads + 2 * kv_heads) * D; // a row's outputs: its q, k and v heads +const eps: f32 = 1e-6; +const theta: f64 = 10000; +const sliding_ring = 3072; // state.zig: the window less 1 plus a 2,048-row chunk, to 128s +const page = 512; // positions a global layer's page holds: tree_attention's span, as Kolibri-1's pages + +/// ricursive_prep.cuh's rounding points. +const norm_row: i32 = 1; +const norm_out: i32 = 2; +const cos_pt: i32 = 4; +const sin_pt: i32 = 8; +const out_pt: i32 = 16; +const all: i32 = 31; + +/// Layer kinds: sliding (RoPE, the 3,072-slot ring), global (NoPE, a ring that never wraps), global in 512-row pages. +pub const Form = enum { sliding, global, paged }; + +/// A registration: the served kernel (keep null), or a control keeping every rounding point but one. +pub const Entry = struct { name: []const u8, form: Form, keep: ?i32 = null }; + +/// NoPE stores the normed value as it is, so the norm's last rounding and the output's show only on sliding layers. +pub const entries = [_]Entry{ + .{ .name = "cuda ricursive tf_rc_prep sliding (RoPE, the 3,072-slot ring)", .form = .sliding }, + .{ .name = "cuda ricursive tf_rc_prep global (NoPE, a slot a position)", .form = .global }, + .{ .name = "cuda ricursive tf_rc_prep global over pages of 512 (NoPE, a shuffled page table)", .form = .paged }, + .{ .name = "control: ricursive tf_rc_prep drops bf16(x r)", .form = .sliding, .keep = all & ~norm_row }, + .{ .name = "control: ricursive tf_rc_prep drops bf16(w bf16(x r))", .form = .sliding, .keep = all & ~norm_out }, + .{ .name = "control: ricursive tf_rc_prep drops bf16(cos)", .form = .sliding, .keep = all & ~cos_pt }, + .{ .name = "control: ricursive tf_rc_prep drops bf16(sin)", .form = .sliding, .keep = all & ~sin_pt }, + .{ .name = "control: ricursive tf_rc_prep truncates its output, not rounding it", .form = .sliding, .keep = all & ~out_pt }, +}; + +/// Rows x a row's outputs x the call's end position (pos + rows): windows across the wrap, deep and last; chunks. +const sliding_served = [_]c.Shape{ + .{ .rows = 16, .n = width, .k = 3 * sliding_ring + 9 }, // a decode window across the ring's wrap + .{ .rows = 1, .n = width, .k = sliding_ring }, // the ring's last slot + .{ .rows = 1, .n = width, .k = sliding_ring + 1 }, // slot 0 again + .{ .rows = 7, .n = width, .k = 100_007 }, + .{ .rows = 16, .n = width, .k = 262_144 }, // the longest context checked + .{ .rows = 2048, .n = width, .k = 2048 }, // the first prompt chunk + .{ .rows = 2048, .n = width, .k = 4096 }, // the second, across the wrap + .{ .rows = 1000, .n = width, .k = 2 * sliding_ring + 500 }, // half before the wrap, half after + .{ .rows = 333, .n = width, .k = 333 }, + .{ .rows = 333, .n = width, .k = sliding_ring + 100 }, +}; + +/// The ring is slots(capacity) for a capacity of the end position: k a multiple of 64 ends on its last slot. +const global_served = [_]c.Shape{ + .{ .rows = 16, .n = width, .k = 100_016 }, + .{ .rows = 1, .n = width, .k = 262_144 }, // the last position of the longest context + .{ .rows = 5, .n = width, .k = 704 }, + .{ .rows = 2048, .n = width, .k = 2048 }, + .{ .rows = 1000, .n = width, .k = 3048 }, + .{ .rows = 333, .n = width, .k = 65_869 }, +}; + +/// The global shapes over pages, and a decode window across a page's edge (positions 1,016 to 1,031). +const paged_served = global_served ++ [_]c.Shape{.{ .rows = 16, .n = width, .k = 1032 }}; + +/// A lane's 4 fma steps, the warp's 5 shuffles. +fn depth(_: c.Shape) usize { + return 4 + 5; +} + +pub fn prepSpec(e: Entry) c.Spec { + const served: []const c.Shape = switch (e.form) { + .sliding => &sliding_served, + .global => &global_served, + .paged => &paged_served, + }; + return .{ .name = e.name, .accum = .f32, .depth = depth, .out = .bf16, .served = served, .sums = .{} }; +} + +/// q [rows][80][128], then the k and v rings' held slots, or (paged) every row of the call's pages and two spares. +pub const Prep = struct { + kern: *const rp.Kernels, + entry: Entry, + ctl: ?cuda.Function = null, + shape: c.Shape = undefined, + pos: usize = 0, + ring: usize = 0, + first: usize = 0, // the lowest slot the outputs hold + held: usize = 0, // the slots they hold + qk: []u16 = &.{}, + v: []u16 = &.{}, + qw: []u16 = &.{}, + kw: []u16 = &.{}, + inv: []f32 = &.{}, + table: []i32 = &.{}, // paged: the stream's page ids by position / 512 + dev: [6]u64 = @splat(0), // qk, v, inv, qw, kw, table + outs: [3]u64 = @splat(0), // q, and the k and v rings' bases (slot 0) + + pub const sums = {}; + + pub fn spec(self: *const Prep) c.Spec { + return prepSpec(self.entry); + } + + pub fn control(self: *const Prep) ?g.Gate { + return if (self.entry.keep != null) .shapes else null; + } + + pub fn free(self: *Prep, a: std.mem.Allocator) void { + for ([_]*[]u16{ &self.qk, &self.v, &self.qw, &self.kw }) |x| { + a.free(x.*); + x.* = &.{}; + } + a.free(self.inv); + self.inv = &.{}; + a.free(self.table); + self.table = &.{}; + } + + /// The call at `shape`: its position, ring or pages, inputs and outputs. + pub fn prepare(self: *Prep, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { + if (shape.n != width or shape.rows == 0 or shape.k < shape.rows) return false; + self.free(a); + self.shape = shape; + const rows = shape.rows; + self.pos = shape.k - rows; + const sliding = self.entry.form == .sliding; + const paged = self.entry.form == .paged; + self.ring = if (sliding) sliding_ring else if (paged) 0 else std.mem.alignForward(usize, shape.k, 64); + if (!paged and rows > self.ring) return false; + self.first = if (sliding or paged) 0 else self.pos; + self.held = if (sliding) self.ring else rows; + if (paged) { + // the call's pages drawn from a pool two larger, in shuffled order; pages below them are never read (-1) + const lo = self.pos / page; + const hi = (shape.k - 1) / page; + const pool = hi - lo + 1 + 2; + const ids = try a.alloc(i32, pool); + defer a.free(ids); + for (ids, 0..) |*x, i| x.* = @intCast(i); + rng.shuffle(i32, ids); + self.table = try a.alloc(i32, hi + 1); + @memset(self.table, -1); + @memcpy(self.table[lo..], ids[0 .. hi - lo + 1]); + self.held = pool * page; + } + try self.inputs(a, rig, rows, fill, rng); + const off = self.first * kvw * 2; // the rings' base, so slot `first` lands on the buffer's first row + self.outs[0] = try rig.output(rows * heads * D * 2); // allocated in the order the outputs gather: q, k, v + self.outs[1] = try rig.output(self.held * kvw * 2) - off; + self.outs[2] = try rig.output(self.held * kvw * 2) - off; + return true; + } + + /// Heads in [-3, 3) (one in 9 a tenth the size), weights in [0.5, 1.5); stress: integers in [-64, 64]; uploaded. + fn inputs(self: *Prep, a: std.mem.Allocator, rig: *rig_.Rig, rows: usize, fill: g.Fill, rng: std.Random) !void { + self.qk = try a.alloc(u16, rows * qk_stride); + self.v = try a.alloc(u16, rows * kvw); + for ([_][]u16{ self.qk, self.v }, [_]usize{ qk_stride, kvw }) |x, stride| for (x, 0..) |*e, i| { + e.* = c.toBf16(if (fill == .stress) ref.int(rng, -64, 64) else (rng.float(f32) * 6 - 3) * (if (i % stride / D % 9 == 4) @as(f32, 0.1) else 1)); + }; + if (fill == .nonfinite and rows >= 4) { + self.qk[3] = c.toBf16(ref.nan); // row 0's first q head: its every output NaN + self.qk[qk_stride + D + 9] = c.toBf16(ref.inf); // row 1's second q head: r = 0, so dim 9 (and 73 rotated) NaN + self.qk[2 * qk_stride + heads * D + 70] = c.toBf16(-ref.inf); // row 2's first k head, in the second half + self.v[3 * kvw + 2 * D + 5] = c.toBf16(ref.inf); // row 3's third v head: copied as it is + } + self.qw = try ref.bfs(a, rng, D, 0.5, 1.5); + self.kw = try ref.bfs(a, rng, D, 0.5, 1.5); + self.inv = try a.alloc(f32, D / 2); + for (self.inv, 0..) |*f, i| f.* = 1.0 / @as(f32, @floatCast(std.math.pow(f64, theta, @as(f64, @floatFromInt(2 * i)) / D))); // config.zig's inverseFrequencies + self.dev = .{ try ref.input(rig, self.qk), try ref.input(rig, self.v), try ref.input(rig, self.inv), try ref.input(rig, self.qw), try ref.input(rig, self.kw), if (self.table.len > 0) try ref.input(rig, self.table) else 0 }; + } + + pub fn run(self: *Prep, rig: *rig_.Rig) !void { + const off = self.first * kvw * 2; + if (self.held > self.shape.rows) for (self.outs[1..]) |o| try rig.zero(o + off, self.held * kvw * 2); // slots no row reaches: zero, as in the reference + const d = self.dev; + const p: rp.Prep = .{ .xq = rp.Rows.of(d[0], qk_stride), .xk = rp.Rows.of(d[0] + heads * D * 2, qk_stride), .xv = rp.Rows.of(d[1], kvw), .inv = d[2], .qw = d[3], .kw = d[4], .q = self.outs[0], .kc = self.outs[1], .vc = self.outs[2], .rows = self.shape.rows, .heads = heads, .kv_heads = kv_heads, .pos = self.pos, .ring = self.ring, .rope = self.entry.form == .sliding, .eps = eps, .pg = if (self.entry.form == .paged) .{ .table = d[5], .page_elems = page * kvw, .tokens = page } else null }; + if (self.ctl) |f| try rp.prepVia(f, self.entry.keep.?, rig.s, p) else try rp.prep(self.kern, rig.s, p); + } + + pub fn count(self: *const Prep) usize { + return self.shape.rows * heads * D + 2 * self.held * kvw; + } + + /// One head's 128 outputs: bf16(w bf16(x r)), then on sliding layers bf16(x c + other s), c, s the bf16 cos, sin. + fn head(self: *const Prep, s: Sums, x: []const u16, w: []const u16, cs: []const Iv, sn: []const Iv, out: []Iv, scratch: []f64) void { + var sq: [D]Iv = undefined; + var n: [D]Iv = undefined; + for (&sq, x) |*q, v| q.* = Iv.of(ref.bf(v) * ref.bf(v)); + const r = s.sum(&sq, depth(self.shape), scratch).div(Iv.of(D)).add(Iv.of(eps)).rsqrt(); + for (&n, x, w) |*o, v, wv| o.* = Iv.of(ref.bf(wv)).mul(Iv.of(ref.bf(v)).mul(r).bf()).bf(); + for (out, 0..) |*o, d| { + if (self.entry.form != .sliding) { + o.* = n[d]; + continue; + } + const other = if (d < D / 2) n[d + D / 2].neg() else n[d - D / 2]; + o.* = n[d].mul(cs[d % (D / 2)]).add(other.mul(sn[d % (D / 2)])).bf(); + } + } + + /// Position p's row in the outputs' k and v: its ring slot, or its page's row in the pool. + fn slot(self: *const Prep, p: usize) usize { + if (self.entry.form == .paged) return @as(usize, @intCast(self.table[p / page])) * page + p % page; + return p % self.ring - self.first; + } + + /// Row r's position and its row in the outputs' k and v: the call's pos + r. + fn rowPos(self: *const Prep, r: usize) usize { + return self.pos + r; + } + + fn rowSlot(self: *const Prep, r: usize) usize { + return self.slot(self.pos + r); + } + + /// Every rounding point kept, whatever the entry: a control's kernel drops one and must leave these ranges. + pub fn solve(self: *const Prep, _: std.mem.Allocator, s: Sums, out: []Iv) !void { + self.solveAt(s, out, self); + } + + /// The outputs with row r at by.rowPos(r), its k and v at row by.rowSlot(r) of the held ones (the rest zero). + fn solveAt(self: *const Prep, s: Sums, out: []Iv, by: anytype) void { + const rows = self.shape.rows; + const qn = rows * heads * D; + const ks = out[qn..][0 .. self.held * kvw]; + const vs = out[qn + self.held * kvw ..]; + @memset(ks, Iv.of(0)); + @memset(vs, Iv.of(0)); + var scratch: [D]f64 = undefined; + var cs: [D / 2]Iv = undefined; + var sn: [D / 2]Iv = undefined; + for (0..rows) |r| { + const position: f32 = @floatFromInt(by.rowPos(r)); + for (&cs, &sn, self.inv) |*co, *si, f| { + const angle = Iv.of(position * f); // the kernel's fp32 angle, exactly + co.* = angle.trig(false).bf(); + si.* = angle.trig(true).bf(); + } + const t = by.rowSlot(r); // the row's slot, as the outputs hold it + const xr = self.qk[r * qk_stride ..][0..qk_stride]; + for (0..heads) |h| self.head(s, xr[h * D ..][0..D], self.qw, &cs, &sn, out[(r * heads + h) * D ..][0..D], &scratch); + for (0..kv_heads) |h| self.head(s, xr[(heads + h) * D ..][0..D], self.kw, &cs, &sn, ks[t * kvw + h * D ..][0..D], &scratch); + for (vs[t * kvw ..][0..kvw], self.v[r * kvw ..][0..kvw]) |*o, x| o.* = Iv.of(ref.bf(x)); + } + } +}; + +/// tf_rc_prep_rows' calls: 4 streams' rows round-robin in 5 shuffled slots (one unused), last rows 3,073 apart. +const streams = 4; +const slots = streams + 1; +const apart = sliding_ring + 1; + +/// A registration of tf_rc_prep_rows (form sliding or paged): the served kernel, or the control naming no row's stream. +pub const RowsEntry = struct { name: []const u8, form: Form, keep: ?i32 = null }; + +pub const rows_entries = [_]RowsEntry{ + .{ .name = "cuda ricursive tf_rc_prep_rows sliding (4 streams' rows in their 3,072-slot rings)", .form = .sliding }, + .{ .name = "cuda ricursive tf_rc_prep_rows global over pages of 512 (4 streams, each its row of the page table)", .form = .paged }, + .{ .name = "control: ricursive tf_rc_prep_rows drops the slot (every row into slot 0's ring)", .form = .sliding, .keep = all }, +}; + +/// Rows x a row's outputs x the first stream's last position + 1 (the others end 3,073, 6,146 and 9,219 below it). +const rows_served = [_]c.Shape{ + .{ .rows = 16, .n = width, .k = 4 * sliding_ring + 2 }, // verify windows of 4 ending at ring slots 1, 0, 3,071, 3,070 + .{ .rows = 4, .n = width, .k = 4 * sliding_ring + 2 }, // a decode round: a row a stream, at those slots + .{ .rows = 7, .n = width, .k = 3 * apart + 3 }, // windows of 2, 2, 2 and 1, the last stream's row at position 2 + .{ .rows = 64, .n = width, .k = 100_007 }, + .{ .rows = 16, .n = width, .k = 262_144 }, // the longest context checked +}; + +/// Gate 3 holds tf_rc_prep_rows to tf_rc_prep's bits; gates 1 and 4 to the float64 reference, as tf_rc_prep. +pub fn rowsSpec(e: RowsEntry) c.Spec { + return .{ .name = e.name, .accum = .f32, .depth = depth, .out = .bf16, .replaces = "tf_rc_prep (a launch a row, at its position on its stream's cache)", .served = &rows_served, .sums = .{} }; +} + +/// Rows stream i holds in a call of `rows`: rows i, i + 4, ... +fn streamRows(rows: usize, i: usize) usize { + return (rows + streams - 1 - i) / streams; +} + +/// Stream i's last position. +fn lastPos(shape: c.Shape, i: usize) usize { + return shape.k - 1 - i * apart; +} + +/// Stream i's pages: its first and one past its last (none without rows). +fn pageSpan(shape: c.Shape, i: usize) [2]usize { + const n = streamRows(shape.rows, i); + if (n == 0) return .{ 0, 0 }; + return .{ (lastPos(shape, i) + 1 - n) / page, lastPos(shape, i) / page + 1 }; +} + +/// tf_rc_prep_rows on Prep's inputs, against tf_rc_prep a launch a row into scratch alike (every slot's ring or pages). +pub const PrepRows = struct { + kern: *const rp.Kernels, + entry: RowsEntry, + ctl: ?cuda.Function = null, + p: Prep, // inputs, outputs and arithmetic: the form's one-stream registration's + at: []i32 = &.{}, // row r's position + of: []i32 = &.{}, // row r's slot + stride: usize = 0, // paged: a slot's entries in the table + dev: [2]u64 = @splat(0), // at, of + base: [3]u64 = @splat(0), // tf_rc_prep's q and k and v caches + host: std.ArrayList(u8) = .empty, // their bytes, in the outputs' order + + pub const sums = {}; + + pub fn spec(self: *const PrepRows) c.Spec { + return rowsSpec(self.entry); + } + + pub fn control(self: *const PrepRows) ?g.Gate { + return if (self.entry.keep != null) .shapes else null; + } + + pub fn free(self: *PrepRows, a: std.mem.Allocator) void { + self.p.free(a); + a.free(self.at); + self.at = &.{}; + a.free(self.of); + self.of = &.{}; + self.host.deinit(a); + self.host = .empty; + } + + pub fn prepare(self: *PrepRows, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { + const rows = shape.rows; + const most = streamRows(rows, 0); + if (shape.n != width or rows == 0 or most > sliding_ring or shape.k < (streams - 1) * apart + most) return false; + self.free(a); + const p = &self.p; + p.shape = shape; + const paged = self.entry.form == .paged; + var ids: [slots]i32 = undefined; + for (&ids, 0..) |*x, i| x.* = @intCast(i); + rng.shuffle(i32, &ids); // stream i in slot ids[i] + self.at = try a.alloc(i32, rows); + self.of = try a.alloc(i32, rows); + for (self.at, self.of, 0..) |*x, *t, r| { + const i = r % streams; + x.* = @intCast(lastPos(shape, i) + 1 - streamRows(rows, i) + r / streams); + t.* = ids[i]; + } + p.ring = if (paged) 0 else sliding_ring; + p.first = 0; + p.held = slots * sliding_ring; + if (paged) { + // each stream's pages from a pool two larger, in shuffled order; a slot's other entries are never read (-1) + self.stride = (shape.k - 1) / page + 1; + var need: usize = 0; + for (0..streams) |i| need += pageSpan(shape, i)[1] - pageSpan(shape, i)[0]; + const pool = try a.alloc(i32, need + 2); + defer a.free(pool); + for (pool, 0..) |*x, i| x.* = @intCast(i); + rng.shuffle(i32, pool); + p.table = try a.alloc(i32, slots * self.stride); + @memset(p.table, -1); + var next: usize = 0; + for (0..streams) |i| { + const span = pageSpan(shape, i); + const row = p.table[@as(usize, @intCast(ids[i])) * self.stride ..]; + for (span[0]..span[1]) |pg| { + row[pg] = pool[next]; + next += 1; + } + } + p.held = pool.len * page; + } + try p.inputs(a, rig, rows, fill, rng); + self.dev = .{ try ref.input(rig, self.at), try ref.input(rig, self.of) }; + const qb = rows * heads * D * 2; + const kb = p.held * kvw * 2; + p.outs = .{ try rig.output(qb), try rig.output(kb), try rig.output(kb) }; // gathered in this order: q, k, v + self.base = .{ try rig.scratch(qb), try rig.scratch(kb), try rig.scratch(kb) }; + return true; + } + + fn call(self: *const PrepRows) rp.PrepRows { + const p = &self.p; + const d = p.dev; + return .{ .xq = rp.Rows.of(d[0], qk_stride), .xk = rp.Rows.of(d[0] + heads * D * 2, qk_stride), .xv = rp.Rows.of(d[1], kvw), .inv = d[2], .qw = d[3], .kw = d[4], .q = p.outs[0], .kc = p.outs[1], .vc = p.outs[2], .rows = p.shape.rows, .heads = heads, .kv_heads = kv_heads, .pos = self.dev[0], .slot = self.dev[1], .ring = p.ring, .rope = self.entry.form == .sliding, .eps = eps, .pg = if (self.entry.form == .paged) .{ .table = d[5], .page_elems = page * kvw, .tokens = page, .stride = self.stride } else null }; + } + + pub fn run(self: *PrepRows, rig: *rig_.Rig) !void { + for (self.p.outs[1..]) |o| try rig.zero(o, self.p.held * kvw * 2); // slots no row reaches: zero, as in the reference + if (self.ctl) |f| try rp.prepRowsVia(f, self.entry.keep.?, rig.s, self.call()) else try rp.prepRows(self.kern, rig.s, self.call()); + } + + /// Gate 3's baseline: tf_rc_prep, a launch a row at the row's position, on its slot's ring or its slot's table row. + pub fn baseline(self: *PrepRows, rig: *rig_.Rig) ![]const u8 { + const p = &self.p; + const d = p.dev; + const b = self.base; + const kb = p.held * kvw * 2; + for (b[1..]) |o| try rig.zero(o, kb); + const paged = self.entry.form == .paged; + for (self.at, self.of, 0..) |x, t, r| { + const ts: usize = @intCast(t); + const ring_at = ts * p.ring * kvw * 2; // the slot's ring (pages: ring 0, the pools themselves) + try rp.prep(self.kern, rig.s, .{ + .xq = rp.Rows.of(d[0] + r * qk_stride * 2, qk_stride), + .xk = rp.Rows.of(d[0] + (r * qk_stride + heads * D) * 2, qk_stride), + .xv = rp.Rows.of(d[1] + r * kvw * 2, kvw), + .inv = d[2], + .qw = d[3], + .kw = d[4], + .q = b[0] + r * heads * D * 2, + .kc = b[1] + ring_at, + .vc = b[2] + ring_at, + .rows = 1, + .heads = heads, + .kv_heads = kv_heads, + .pos = @intCast(x), + .ring = p.ring, + .rope = !paged, + .eps = eps, + .pg = if (paged) .{ .table = d[5] + ts * self.stride * 4, .page_elems = page * kvw, .tokens = page } else null, + }); + } + const a = rig.gpu.gpa; + self.host.clearRetainingCapacity(); + for (b, [_]usize{ p.shape.rows * heads * D * 2, kb, kb }) |o, n| try self.host.appendSlice(a, try rig.bytes(o, n)); + return self.host.items; + } + + pub fn count(self: *const PrepRows) usize { + return self.p.count(); + } + + /// Row r's position, and its row in the outputs' k and v: its slot's ring slot, or its page's row in the pool. + fn rowPos(self: *const PrepRows, r: usize) usize { + return @intCast(self.at[r]); + } + + fn rowSlot(self: *const PrepRows, r: usize) usize { + const x: usize = @intCast(self.at[r]); + const t: usize = @intCast(self.of[r]); + if (self.entry.form == .paged) return @as(usize, @intCast(self.p.table[t * self.stride + x / page])) * page + x % page; + return t * sliding_ring + x % sliding_ring; + } + + /// Every rounding point kept: Prep's reference at each row's own position and slot. + pub fn solve(self: *const PrepRows, _: std.mem.Allocator, s: Sums, out: []Iv) !void { + self.p.solveAt(s, out, self); + } +}; + +/// ref.Gated(PrepRows) and the spec's baseline: tf_rc_prep's bytes on the same inputs (ref.Gated has no `replaced`). +pub const RowsGated = struct { + in: ref.Gated(PrepRows), + rig: *rig_.Rig, // in.rig: the hooks read the outputs there + + const vt = g.hooks(RowsGated); + + pub fn kernel(self: *RowsGated) g.Kernel { + return .{ .spec = self.in.k.spec(), .ctx = self, .vt = &vt, .control = self.in.k.control() }; + } + + pub fn prepare(self: *RowsGated, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + return self.in.prepare(shape, fill, seed); + } + + pub fn run(self: *RowsGated) !void { + return self.in.run(); + } + + pub fn count(self: *RowsGated) usize { + return self.in.count(); + } + + pub fn reference(self: *RowsGated, want: []f64, mag: []f64) !void { + return self.in.reference(want, mag); + } + + pub fn bounds(self: *RowsGated, want: []const f64, mag: []const f64, allow: []f64) !void { + return self.in.bounds(want, mag, allow); + } + + pub fn intervals(self: *RowsGated, low: []f64, high: []f64) !void { + return self.in.intervals(low, high); + } + + pub fn simulate(self: *RowsGated, acc: c.Accum, order: g.Order, out: []f64) !void { + return self.in.simulate(acc, order, out); + } + + pub fn replaced(self: *RowsGated) ![]const u8 { + return self.in.k.baseline(self.rig); + } +}; + +/// The registrations, on the heap: the gates hold pointers to them. +pub const Set = struct { + gpa: std.mem.Allocator, + k: rp.Kernels, + ctl: cuda.Module, + preps: [entries.len]ref.Gated(Prep) = undefined, + rows: [rows_entries.len]RowsGated = undefined, + + /// The set, its kernels appended to `list` (the controls after the kernel they break). + pub fn init(gpu: check.Gpu, s: cuda.Stream, a: std.mem.Allocator, list: *std.ArrayList(g.Kernel)) !*Set { + const set = try gpu.gpa.create(Set); + errdefer gpu.gpa.destroy(set); + var k = try rp.Kernels.load(gpu.d); + errdefer k.unload(); + var ctl = try cuda.Module.load(gpu.d, &controls.bytes); + errdefer ctl.unload(); + const f = try ctl.function("tf_ctl_rc_prep"); + const fr = try ctl.function("tf_ctl_rc_prep_rows"); + set.* = .{ .gpa = gpu.gpa, .k = k, .ctl = ctl }; + for (&set.preps, entries) |*x, e| x.* = .{ .rig = .{ .gpu = gpu, .s = s }, .k = .{ .kern = &set.k, .entry = e, .ctl = if (e.keep != null) f else null } }; + for (&set.rows, rows_entries) |*x, e| { + x.* = .{ .in = .{ .rig = .{ .gpu = gpu, .s = s }, .k = .{ .kern = &set.k, .entry = e, .ctl = if (e.keep != null) fr else null, .p = .{ .kern = &set.k, .entry = .{ .name = e.name, .form = e.form } } } }, .rig = undefined }; + x.rig = &x.in.rig; + } + for (&set.preps) |*x| try list.append(a, x.kernel()); + for (&set.rows) |*x| try list.append(a, x.kernel()); + return set; + } + + pub fn deinit(set: *Set) void { + for (&set.rows) |*x| x.in.deinit(); + for (&set.preps) |*x| x.deinit(); + set.ctl.unload(); + set.k.unload(); + set.gpa.destroy(set); + } +}; + +test "each control keeps all of tf_rc_prep's rounding points but one, and each point has its control" { + var dropped: i32 = 0; + for (entries) |e| if (e.keep) |k| { + const gone = all & ~k; + try std.testing.expectEqual(@as(u32, 1), @popCount(gone)); + try std.testing.expect((dropped & gone) == 0); + try std.testing.expect(e.form == .sliding); + dropped |= gone; + }; + try std.testing.expectEqual(all, dropped); +} diff --git a/zig/tests/cuda/contract_row_best.zig b/zig/tests/cuda/contract_row_best.zig index e63acda2852..3fef88ea228 100644 --- a/zig/tests/cuda/contract_row_best.zig +++ b/zig/tests/cuda/contract_row_best.zig @@ -7,14 +7,29 @@ pub const ref = @import("contract_row_best_ref.zig"); const c = core.contract.spec; const g = core.contract.gates; +/// fn_row_best; its split over 32 blocks a row (fn_row_best_max, fn_row_best_sum); a control: the split over V - 1. +pub const Kind = enum { whole, split, control }; + +fn spec(kind: Kind) c.Spec { + var s = ref.spec; + if (kind == .whole) return s; + s.name = if (kind == .split) "cuda Flash Next fn_row_best_max + fn_row_best_sum (replaces fn_row_best)" else "control: the split row best over V - 1 values posing as fn_row_best"; + s.replaces = "fn_row_best"; + return s; +} + pub const Best = struct { rig: rig_.Rig, f: cuda.Function, + kind: Kind = .whole, + split: ?[2]cuda.Function = null, shape: c.Shape = undefined, bits: []u16 = &.{}, input: u64 = 0, output: u64 = 0, probe: u64 = 0, + scratch: u64 = 0, + base: u64 = 0, pub fn deinit(self: *Best) void { self.rig.gpu.gpa.free(self.bits); @@ -24,7 +39,7 @@ pub const Best = struct { const vt = g.hooks(Best); pub fn kernel(self: *Best) g.Kernel { - return .{ .spec = ref.spec, .ctx = self, .vt = &vt }; + return .{ .spec = spec(self.kind), .ctx = self, .vt = &vt, .control = if (self.kind == .control) .shapes else null }; } pub fn prepare(self: *Best, shape: c.Shape, fill: g.Fill, seed: u64) !bool { @@ -39,6 +54,10 @@ pub const Best = struct { self.input = try self.rig.input(std.mem.sliceAsBytes(self.bits)); self.output = try self.rig.output(self.count() * 4); self.probe = try self.rig.scratch(16); + if (self.kind != .whole) { + self.scratch = try self.rig.scratch(shape.rows * (32 * 12 + 4)); + self.base = try self.rig.scratch(self.count() * 4); + } return true; } @@ -52,8 +71,40 @@ pub const Best = struct { try self.rig.s.synchronize(); } + fn launchSplit(self: *Best, v: usize) !void { + const fns = self.split.?; + const rows = self.shape.rows; + const sums = self.scratch + rows * 32 * 8; + const cfg: cuda.launch.Config = .{ .grid = .{ .x = @intCast(rows), .y = 32 }, .block = .{ .x = 32 } }; + var first: cuda.Args = .{}; + first.add(self.input); + first.add(@as(c_int, @intCast(v))); + first.add(@as(c_longlong, @intCast(self.shape.k + 17))); + first.add(self.scratch); + try cuda.launch.launch(fns[0], cfg, self.rig.s, &first); + var second: cuda.Args = .{}; + second.add(self.input); + second.add(@as(c_int, @intCast(v))); + second.add(@as(c_longlong, @intCast(self.shape.k + 17))); + second.add(self.scratch); + second.add(sums); + second.add(sums + rows * 32 * 4); + second.add(self.output); + try cuda.launch.launch(fns[1], cfg, self.rig.s, &second); + try self.rig.s.synchronize(); + } + pub fn run(self: *Best) !void { - try self.launch(self.input, self.output, self.shape.rows); + switch (self.kind) { + .whole => try self.launch(self.input, self.output, self.shape.rows), + .split => try self.launchSplit(self.shape.k), + .control => try self.launchSplit(@max(self.shape.k, 2) - 1), + } + } + + pub fn replaced(self: *Best) ![]const u8 { + try self.launch(self.input, self.base, self.shape.rows); + return self.rig.bytes(self.base, self.count() * 4); } pub fn count(self: *Best) usize { @@ -73,7 +124,7 @@ pub const Best = struct { const actual = try a.dupe(u8, try self.rig.outputBytes()); defer a.free(actual); if (ref.check(self.bits, self.shape, actual)) |why| return why; - if (gate == .shapes) for (0..self.shape.rows) |row| { + if (gate == .shapes and self.kind == .whole) for (0..self.shape.rows) |row| { try self.launch(self.input + row * (self.shape.k + 17) * 2, self.probe, 1); if (!std.mem.eql(u8, actual[row * 16 ..][0..16], try self.rig.bytes(self.probe, 16))) return "a batched reduction row differs from the same input reduced alone"; diff --git a/zig/tests/cuda/contract_tests.zig b/zig/tests/cuda/contract_tests.zig index 60a71223219..63a90590344 100644 --- a/zig/tests/cuda/contract_tests.zig +++ b/zig/tests/cuda/contract_tests.zig @@ -301,9 +301,11 @@ fn registered(gpu: check.Gpu, only: []const []const u8, t0: *i96) !g.Tally { for (&shifts) |*shift| try kernels.append(a, shift.kernel()); var mtp = try cuda.Module.load(gpu.d, kk.flashnext_mtp); defer mtp.unload(); - var best = best_k.Best{ .rig = .{ .gpu = gpu, .s = s }, .f = try mtp.function("fn_row_best") }; - defer best.deinit(); - try kernels.append(a, best.kernel()); + const best_split = [2]cuda.Function{ try mtp.function("fn_row_best_max"), try mtp.function("fn_row_best_sum") }; + var bests: [3]best_k.Best = undefined; + for (std.enums.values(best_k.Kind), &bests) |kind, *b| b.* = .{ .rig = .{ .gpu = gpu, .s = s }, .f = try mtp.function("fn_row_best"), .kind = kind, .split = best_split }; + defer for (&bests) |*b| b.deinit(); + for (&bests) |*b| try kernels.append(a, b.kernel()); var selections: [2]qsa_k.Select = undefined; for ([_]bool{ false, true }, &selections) |padded, *selection| selection.* = .{ .rig = .{ .gpu = gpu, .s = s }, .f = try batch.function("fn_qsa_select"), .padded = padded }; @@ -590,6 +592,8 @@ fn registered(gpu: check.Gpu, only: []const []const u8, t0: *i96) !g.Tally { defer f32w_control.deinit(); try kernels.append(a, f32w_control.kernel()); const glm_fns = try glm.glue.Kernels.load(glm_glue); + const glm_wide = try @import("contract_glm_wide_expert.zig").Suite.create(gpu, s, &kernels); + defer glm_wide.destroy(); var glm_lat = glm_pages_k.LatWrite{ .rig = .{ .gpu = gpu, .s = s }, .f = glm_fns.lat_write }; defer glm_lat.deinit(); try kernels.append(a, glm_lat.kernel()); diff --git a/zig/tests/cuda/flashnext_gdn_heads_tests.zig b/zig/tests/cuda/flashnext_gdn_heads_tests.zig index d84d4c53ad4..8f4466c251b 100644 --- a/zig/tests/cuda/flashnext_gdn_heads_tests.zig +++ b/zig/tests/cuda/flashnext_gdn_heads_tests.zig @@ -9,8 +9,8 @@ const Rig = rig_.Rig; const Heads = lay.Heads; const Part = lay.Part; -/// Token rows: one, a few, a stage of 16, the TPR seam's either side, and the default chunk. -const counts = [_]usize{ 1, 4, 16, 63, 64, 1536 }; +/// Token rows: every KR15 short-row cell, the TPR seam's either side, and the default chunk. +const counts = [_]usize{ 1, 4, 8, 16, 32, 63, 64, 1536 }; /// A pass's inputs, host bytes in one layout: projection rows, conv window and taps, gates, norm weight, state. const In = struct { p: []const u8, cs: []const u8, cw: []const u8, a_log: []const u8, dt: []const u8, nw: []const u8, st: []const u8 }; diff --git a/zig/tests/cuda/glm_lanes_tests.zig b/zig/tests/cuda/glm_lanes_tests.zig index d2e5f44f8db..031e325a138 100644 --- a/zig/tests/cuda/glm_lanes_tests.zig +++ b/zig/tests/cuda/glm_lanes_tests.zig @@ -38,10 +38,11 @@ pub fn coverCheck(gpu: Gpu, checkpoint: []const u8, dc_path: []const u8, rank: c const comm = try openComm(gpu, &lib, rank, world, id_path); defer _ = lib.api.ncclCommDestroy(comm); var problem: []const u8 = ""; - const set = glm.ranks.Settings.read(&glm.ranks.environment, &problem) catch |err| { + var set = glm.ranks.Settings.read(&glm.ranks.environment, &problem) catch |err| { std.debug.print("REFUSE {s}\n", .{problem}); return err; }; + glm.ranks.toolPieces(&set, &glm.ranks.environment); // TF_GLM_WORLD's rule, as before const e = try glm.engine.Engine.init(gpu.gpa, gpu.io, gpu.d, gpu.ctx, checkpoint, &lib, comm, @intCast(rank), @intCast(world), .{ .capacity = dc.capacity, .mtp = true, .settings = set }); defer e.deinit(); try e.prepareSnapshots(2 * e.stateBytes(4096)); @@ -147,10 +148,11 @@ pub fn concurrentCheck(gpu: Gpu, checkpoint: []const u8, dc_path: []const u8, ra const comm = try openComm(gpu, &lib, rank, world, id_path); defer _ = lib.api.ncclCommDestroy(comm); var problem: []const u8 = ""; - const set = glm.ranks.Settings.read(&glm.ranks.environment, &problem) catch |err| { + var set = glm.ranks.Settings.read(&glm.ranks.environment, &problem) catch |err| { std.debug.print("REFUSE {s}\n", .{problem}); return err; }; + glm.ranks.toolPieces(&set, &glm.ranks.environment); // TF_GLM_WORLD's rule, as before const e = try glm.engine.Engine.init(gpu.gpa, gpu.io, gpu.d, gpu.ctx, checkpoint, &lib, comm, @intCast(rank), @intCast(world), .{ .capacity = dc.capacity, .mtp = true, .settings = set }); defer e.deinit(); var link = try glm.follow.Link.init(gpu.gpa, gpu.d, &lib, comm, e.stream, dc.capacity); @@ -226,10 +228,11 @@ pub fn sharedCheck(gpu: Gpu, checkpoint: []const u8, dc_path: []const u8, rank: const comm = try openComm(gpu, &lib, rank, world, id_path); defer _ = lib.api.ncclCommDestroy(comm); var problem: []const u8 = ""; - const set = glm.ranks.Settings.read(&glm.ranks.environment, &problem) catch |err| { + var set = glm.ranks.Settings.read(&glm.ranks.environment, &problem) catch |err| { std.debug.print("REFUSE {s}\n", .{problem}); return err; }; + glm.ranks.toolPieces(&set, &glm.ranks.environment); // TF_GLM_WORLD's rule, as before const e = try glm.engine.Engine.init(gpu.gpa, gpu.io, gpu.d, gpu.ctx, checkpoint, &lib, comm, @intCast(rank), @intCast(world), .{ .capacity = dc.capacity, .mtp = true, .settings = set }); defer e.deinit(); var link = try glm.follow.Link.init(gpu.gpa, gpu.d, &lib, comm, e.stream, dc.capacity); diff --git a/zig/tests/cuda/glm_paged_tests.zig b/zig/tests/cuda/glm_paged_tests.zig index 34d82c37174..83d152f6189 100644 --- a/zig/tests/cuda/glm_paged_tests.zig +++ b/zig/tests/cuda/glm_paged_tests.zig @@ -28,6 +28,7 @@ pub fn pagedCheck(gpu: Gpu, checkpoint: []const u8, rank: c_int, world: c_int, i std.debug.print("REFUSE {s}\n", .{problem}); return err; }; + glm.ranks.toolPieces(&set, &glm.ranks.environment); // TF_GLM_WORLD's rule, as before set.pages = true; // every rank's engine makes its own sequence on pages, as TF_KV_PAGES does const e = try glm.engine.Engine.init(gpu.gpa, gpu.io, gpu.d, gpu.ctx, checkpoint, &lib, comm, @intCast(rank), @intCast(world), .{ .capacity = capacity, .mtp = true, .settings = set }); defer e.deinit(); diff --git a/zig/tests/cuda/glm_pair_tests.zig b/zig/tests/cuda/glm_pair_tests.zig index 633e1d9c6a4..97e5be2004c 100644 --- a/zig/tests/cuda/glm_pair_tests.zig +++ b/zig/tests/cuda/glm_pair_tests.zig @@ -17,10 +17,11 @@ pub fn pairCheck(gpu: Gpu, checkpoint: []const u8, dc_path: []const u8, rank: c_ const comm = try @import("glm_lanes_tests.zig").openComm(gpu, &lib, rank, world, id_path); defer _ = lib.api.ncclCommDestroy(comm); var problem: []const u8 = ""; - const set = glm.ranks.Settings.read(&glm.ranks.environment, &problem) catch |err| { + var set = glm.ranks.Settings.read(&glm.ranks.environment, &problem) catch |err| { std.debug.print("REFUSE {s}\n", .{problem}); return err; }; + glm.ranks.toolPieces(&set, &glm.ranks.environment); // TF_GLM_WORLD's rule, as before try check.expect(set.pair, "glm-pair-check needs TF_GLM_PROMPT_PAIR on (unset or 1)", .{}); try check.expect(world > 1, "glm-pair-check needs other ranks: at TP=1 an engine makes no twin", .{}); const C = glm.engine.prompt_rows; diff --git a/zig/tests/cuda/glm_solo_tests.zig b/zig/tests/cuda/glm_solo_tests.zig index 300cd96b9ae..39cd7f1798a 100644 --- a/zig/tests/cuda/glm_solo_tests.zig +++ b/zig/tests/cuda/glm_solo_tests.zig @@ -27,10 +27,11 @@ pub fn soloCheck(gpu: Gpu, checkpoint: []const u8, dc_path: []const u8, rank: c_ const comm = try @import("glm_lanes_tests.zig").openComm(gpu, &lib, rank, world, id_path); defer _ = lib.api.ncclCommDestroy(comm); var problem: []const u8 = ""; - const set = glm.ranks.Settings.read(&glm.ranks.environment, &problem) catch |err| { + var set = glm.ranks.Settings.read(&glm.ranks.environment, &problem) catch |err| { std.debug.print("REFUSE {s}\n", .{problem}); return err; }; + glm.ranks.toolPieces(&set, &glm.ranks.environment); // TF_GLM_WORLD's rule, as before try check.expect(set.solo, "glm-solo-check needs TF_GLM_CHUNK_SOLO=4096", .{}); const C = glm.engine.prompt_rows; const capacity = @max(dc.capacity, 6 * C); diff --git a/zig/tests/cuda/glm_split_tests.zig b/zig/tests/cuda/glm_split_tests.zig index a2dcf5bf734..f53c1fadfb1 100644 --- a/zig/tests/cuda/glm_split_tests.zig +++ b/zig/tests/cuda/glm_split_tests.zig @@ -18,10 +18,11 @@ pub fn splitCheck(gpu: Gpu, checkpoint: []const u8, dc_path: []const u8, rank: c const comm = try @import("glm_lanes_tests.zig").openComm(gpu, &lib, rank, world, id_path); defer _ = lib.api.ncclCommDestroy(comm); var problem: []const u8 = ""; - const set = glm.ranks.Settings.read(&glm.ranks.environment, &problem) catch |err| { + var set = glm.ranks.Settings.read(&glm.ranks.environment, &problem) catch |err| { std.debug.print("REFUSE {s}\n", .{problem}); return err; }; + glm.ranks.toolPieces(&set, &glm.ranks.environment); // TF_GLM_WORLD's rule, as before const C = glm.engine.prompt_rows; const capacity = @max(dc.capacity, 4 * C); const e = try glm.engine.Engine.init(gpu.gpa, gpu.io, gpu.d, gpu.ctx, checkpoint, &lib, comm, @intCast(rank), @intCast(world), .{ .capacity = capacity, .mtp = true, .settings = set }); diff --git a/zig/tests/cuda/glm_tap_tests.zig b/zig/tests/cuda/glm_tap_tests.zig index 2dee558c71b..17445004790 100644 --- a/zig/tests/cuda/glm_tap_tests.zig +++ b/zig/tests/cuda/glm_tap_tests.zig @@ -25,10 +25,11 @@ pub fn tapSplitCheck(gpu: Gpu, checkpoint: []const u8, drafter: []const u8, rank const comm = try @import("glm_lanes_tests.zig").openComm(gpu, &lib, rank, world, id_path); defer _ = lib.api.ncclCommDestroy(comm); var problem: []const u8 = ""; - const set = glm.ranks.Settings.read(&glm.ranks.environment, &problem) catch |err| { + var set = glm.ranks.Settings.read(&glm.ranks.environment, &problem) catch |err| { std.debug.print("REFUSE {s}\n", .{problem}); return err; }; + glm.ranks.toolPieces(&set, &glm.ranks.environment); // TF_GLM_WORLD's rule, as before const WIN: usize = @intCast(glm.dflash.WIN); const C = glm.engine.prompt_rows; const lens = [_]usize{ WIN - 1, WIN, WIN + 1, 8000 }; // 2,047 / 2,048 / 2,049, then about 8k in several chunks diff --git a/zig/tests/cuda/group_proj_tests.zig b/zig/tests/cuda/group_proj_tests.zig new file mode 100644 index 00000000000..8f0e2e6efba --- /dev/null +++ b/zig/tests/cuda/group_proj_tests.zig @@ -0,0 +1,142 @@ +//! TF_Q35_GROUP_PROJ's grouped lane launch: each projection's bytes against its own launch, rows 1-16, then times. +const std = @import("std"); +const cuda = @import("cuda"); +const check = @import("check.zig"); +const rig = @import("flashnext_rig.zig"); + +const Mode = cuda.qmmf.Mode; +const group = cuda.qmmf_group; + +const Set = struct { name: []const u8, mode: Mode, k: usize, ns: []const usize }; + +/// The served Qwen3.8-27B ModelOpt groups (NVFP4 MLP, FP8 mixers, BF16 a/b heads), then padding, edges and four. +const sets = [_]Set{ + .{ .name = "MLP gate+up", .mode = .fp4, .k = 5120, .ns = &.{ 17408, 17408 } }, + .{ .name = "GDN qkv+z", .mode = .fp8, .k = 5120, .ns = &.{ 10240, 6144 } }, + .{ .name = "GDN a+b", .mode = .bf16, .k = 5120, .ns = &.{ 48, 48 } }, + .{ .name = "attention q+k+v", .mode = .fp8, .k = 5120, .ns = &.{ 12288, 1024, 1024 } }, + .{ .name = "fp4 one slice padded to the cluster", .mode = .fp4, .k = 4096, .ns = &.{ 12352, 200, 72 } }, + .{ .name = "bf16 64-column tiles", .mode = .bf16, .k = 1024, .ns = &.{ 12288, 6400 } }, + .{ .name = "fp8 four, an odd width", .mode = .fp8, .k = 2048, .ns = &.{ 64, 2048, 131, 4096 } }, +}; + +/// Tensor scales: one, small, subnormal and infinite. +const scales = [_]f32{ 1.0, 0x1p-12, 1e-40, std.math.inf(f32) }; + +/// bf16 specials an adversarial row mixes in: zeros, subnormals, the largest finite and infinities. +const specials = [_]u16{ 0x0000, 0x8000, 0x0001, 0x8001, 0x7F7F, 0xFF7F, 0x7F80, 0xFF80 }; + +/// One projection packed for the lane: random bytes, or bounded values without NaN codes. +fn build(r: *rig.Rig, a: std.mem.Allocator, rng: std.Random, mode: Mode, n: usize, k: usize, adversarial: bool) !cuda.qmmf.Weight { + const np = cuda.modelopt.padded(n); + switch (mode) { + .fp4 => { + const codes = try a.alloc(u8, n * k / 2); + rng.bytes(codes); + const blocks = try a.alloc(u8, n * k / 16); + for (blocks) |*s| s.* = if (adversarial) rng.int(u8) else 0x30 + rng.uintLessThan(u8, 16); + const words = try a.alloc(u32, np / 64 * (k / 64) * 512); + cuda.nvfp4.packWords(words, codes, n, k); + const tiles = try a.alloc(u8, np * (k / 16)); + cuda.nvfp4.packScales(tiles, blocks, n, k); + return cuda.nvfp4.weight(try r.dev(std.mem.sliceAsBytes(words)), try r.dev(tiles), 1.0, n, k); + }, + .fp8 => { + const codes = try a.alloc(u8, n * k); + for (codes) |*c| c.* = if (adversarial) rng.int(u8) else rng.int(u8) & 0xF7; // no e4m3 NaN + const tiled = try a.alloc(u8, np * k); + cuda.fp8.packCodes(tiled, codes, n, k); + return cuda.modelopt.fp8Weight(try r.dev(tiled), 1.0, n, k); + }, + .bf16 => { + const w: []const u16 = if (adversarial) std.mem.bytesAsSlice(u16, std.mem.sliceAsBytes(r.words(n * k / 2))) else r.bfs(n * k, 0.05); + const tiled = try a.alloc(u16, np * k); + cuda.qmmf.packBf16(tiled, w, n, k); + return cuda.modelopt.bf16Weight(try r.dev(std.mem.sliceAsBytes(tiled)), n, k); + }, + else => unreachable, + } +} + +fn refill(r: *rig.Rig, ptr: u64, bytes: usize) !void { + const b: cuda.DeviceBuffer = .{ .d = r.gpu.d, .ptr = ptr, .len = bytes }; + try b.fill8(0xff, r.s.handle); +} + +pub fn run(gpu: check.Gpu) !void { + var arena = std.heap.ArenaAllocator.init(gpu.gpa); + defer arena.deinit(); + const a = arena.allocator(); + var prng = std.Random.DefaultPrng.init(0x6a1d); + const rng = prng.random(); + var r = try rig.Rig.init(gpu, a, rng); + defer r.deinit(); + var lane = try cuda.qmmf.Lane.load(gpu.d, @intCast(try gpu.ctx.capability() / 10)); + defer lane.unload(); + if (!lane.clusters) { + std.debug.print("SKIP group-proj: no clusters before sm_90, where the engine never groups\n", .{}); + return; + } + const g = try group.Group.load(&lane); + var cells: usize = 0; + for (sets) |set| for ([_]bool{ false, true }) |adversarial| { + var ws: [group.most]cuda.qmmf.Weight = undefined; + var sep: [group.most]u64 = undefined; + var grp: [group.most]u64 = undefined; + var bytes: [group.most]usize = undefined; + var part_bytes: usize = 16; + const count = set.ns.len; + for (set.ns, 0..) |n, i| { + ws[i] = try build(&r, a, rng, set.mode, n, set.k, adversarial); + bytes[i] = (group.max_rows + 1) * n * 2; // the 16 rows and a guard row nothing may write + sep[i] = try r.out(bytes[i]); + grp[i] = try r.out(bytes[i]); + part_bytes = @max(part_bytes, lane.partBytes(group.max_rows, ws[i])); + } + const part = try r.out(part_bytes); + const xs = if (adversarial) r.bfs(group.max_rows * set.k, 4.0) else r.bfs(group.max_rows * set.k, 1.0); + if (adversarial) for (xs) |*v| { + if (rng.uintLessThan(u8, 8) == 0) v.* = specials[rng.uintLessThan(usize, specials.len)]; + }; + const x = try r.dev(std.mem.sliceAsBytes(xs)); + const tensor_scales: []const f32 = if (set.mode == .bf16) scales[0..1] else &scales; + for (tensor_scales) |scale| for (1..group.max_rows + 1) |m| { + for (ws[0..count]) |*w| w.scale = scale; + for (0..count) |i| { + try refill(&r, sep[i], bytes[i]); + try refill(&r, grp[i], bytes[i]); + } + const sh = group.plan(lane, ws[0..count], grp[0..count], m) orelse + return check.expect(false, "group-proj {s}: rows {d} not planned", .{ set.name, m }); + for (ws[0..count], sep[0..count]) |w, y| try lane.matmul(r.s, x, set.k, m, w, y, part); + try g.launch(r.s, x, m, set.k, sh, false); + try r.s.synchronize(); + for (0..count) |i| { + const want = try r.back(u8, sep[i], bytes[i]); + const got = try r.back(u8, grp[i], bytes[i]); + try check.sameBytes(set.name, got, want); + cells += 1; + } + }; + if (!adversarial) try time(&r, gpu, lane, g, set, ws[0..count], grp[0..count], x, part); + }; + check.pass("group-proj: {d} projections at rows 1-16, tensor scales and adversarial values: bytes equal", .{cells}); +} + +/// The grouped launch against the separate ones, warm, at 1 and 16 rows (this engine's lanes only). +fn time(r: *rig.Rig, gpu: check.Gpu, lane: cuda.qmmf.Lane, g: group.Group, set: Set, ws: []const cuda.qmmf.Weight, outs: []const u64, x: u64, part: u64) !void { + for ([_]usize{ 1, 16 }) |m| { + const sh = group.plan(lane, ws, outs, m).?; + var us: [2]f64 = undefined; + const reps = 200; + for (0..2) |grouped| { + const t0 = check.now(gpu.io); + for (0..reps) |_| { + if (grouped == 1) try g.launch(r.s, x, m, set.k, sh, false) else for (ws, outs) |w, y| try lane.matmul(r.s, x, set.k, m, w, y, part); + } + try r.s.synchronize(); + us[grouped] = @as(f64, @floatFromInt(check.now(gpu.io) - t0)) / 1e3 / reps; + } + std.debug.print("group-proj {s} rows {d}: separate {d:.1} us, grouped {d:.1} us ({d} blocks, cluster {d})\n", .{ set.name, m, us[0], us[1], sh.blocks, sh.cluster }); + } +} diff --git a/zig/tests/cuda/inkling2_serving_tests.zig b/zig/tests/cuda/inkling2_serving_tests.zig new file mode 100644 index 00000000000..b663effeefe --- /dev/null +++ b/zig/tests/cuda/inkling2_serving_tests.zig @@ -0,0 +1,397 @@ +//! Real Inkling 2 Mini CUDA serving: device draws against host selection, snapshots, admission and copied drafts. +const std = @import("std"); +const lanes = @import("lanes"); +const mini = @import("inkling2"); +const cuda = @import("cuda"); +const check = @import("check.zig"); + +const native = mini.native; +const Backend = @TypeOf(@as(native.Owned, undefined).backend); +const Gpu = check.Gpu; +const sampled: lanes.Sampling = .{ .seed = 37, .temperature = 0.8, .top_k = 64, .top_p = 0.95 }; + +const Trace = struct { + ids: []u32, + logits: []f32, + cached: u32, + failed: bool, + + fn deinit(t: *Trace, gpa: std.mem.Allocator) void { + gpa.free(t.ids); + gpa.free(t.logits); + } +}; + +fn target(loaded: *native.Loaded) *Backend { + return &loaded.target.backend; +} + +fn download(b: *Backend, src: u64, out: []f32) !void { + try b.s.synchronize(); + try cuda.memory.download(b.d, src, std.mem.sliceAsBytes(out)); +} + +/// A real target pass with either CUDA's draws or host selection over its downloaded fp32 logits. +fn trace(gpu: Gpu, loaded: *native.Loaded, prompt: []const u32, sampling: ?lanes.Sampling, n: usize, host: bool, reuse: lanes.stream.Reuse) !Trace { + const t = target(loaded); + const v = t.m.w.c.text.unpadded_vocab; + var s = try lanes.Stream.init(gpu.gpa, .{ .id = "mini-trace", .prompt = prompt, .max_new = @intCast(n), .sampling = sampling, .reuse = reuse }); + defer s.deinit(gpu.gpa); + const b = loaded.backend; + defer b.release(&s); + const ids = try gpu.gpa.alloc(u32, n); + errdefer gpu.gpa.free(ids); + const logits = try gpu.gpa.alloc(f32, n * v); + errdefer gpu.gpa.free(logits); + try b.prefill(&s); + try download(t, try t.lastOf(&s), logits[0..v]); + var handle: ?u64 = try b.first(&s, prompt.len); + for (0..n) |i| { + ids[i] = if (host) try lanes.gpu_full.draw(gpu.gpa, logits[i * v ..][0..v], sampling, @intCast(prompt.len + i), null) else try b.read(handle.?); + if (i + 1 < n) { + handle = try b.queue(&s, .{ .value = ids[i] }, prompt.len + i + 1); + try download(t, t.m.s.logits, logits[(i + 1) * v ..][0..v]); + } + } + return .{ .ids = ids, .logits = logits, .cached = s.cached, .failed = s.reuse_failed }; +} + +fn sameTrace(a: *const Trace, b: *const Trace) !void { + if (!std.mem.eql(u32, a.ids, b.ids)) return error.MiniServingTokenMismatch; + if (!std.mem.eql(u8, std.mem.sliceAsBytes(a.logits), std.mem.sliceAsBytes(b.logits))) return error.MiniServingLogitMismatch; +} + +fn hostReference(gpu: Gpu, loaded: *native.Loaded, prompt: []const u32) !void { + for ([_]?lanes.Sampling{ null, sampled }, 0..) |sampling, case| { + var device = try trace(gpu, loaded, prompt, sampling, 12, false, .{}); + defer device.deinit(gpu.gpa); + var host = try trace(gpu, loaded, prompt, sampling, 12, true, .{}); + defer host.deinit(gpu.gpa); + sameTrace(&device, &host) catch |err| { + std.debug.print("RESULT mini-serving host-reference case={d} mismatch={s}\n", .{ case, @errorName(err) }); + return err; + }; + } +} + +/// Save one complete state at `cut`, restore it through the genuine prompt-reuse hook and rerun the suffix. +fn resumedAt(gpu: Gpu, loaded: *native.Loaded, prompt: []const u32, cut: u32, sampling: ?lanes.Sampling, fresh: *const Trace) !void { + const Saved = @TypeOf(loaded.target.model).Saved; + const Keeper = struct { + b: *Backend, + saved: ?*Saved = null, + fn at(ptr: *anyopaque, s: *lanes.Stream, mark: u32) void { + const k: *@This() = @ptrCast(@alignCast(ptr)); + k.saved = k.b.saveState(s, mark) catch null; + } + }; + const t = target(loaded); + const saved = snapshot: { + var s = try lanes.Stream.init(gpu.gpa, .{ .id = "mini-snapshot", .prompt = prompt, .max_new = 1, .reuse = .{ .marks = &.{cut} } }); + defer s.deinit(gpu.gpa); + const b = loaded.backend; + defer b.release(&s); + var keeper: Keeper = .{ .b = t }; + s.reuse.hook = .{ .ptr = &keeper, .at = Keeper.at }; + try b.prefill(&s); + break :snapshot keeper.saved orelse return error.MiniSnapshotNotSaved; + }; + defer t.dropState(saved); + var resumed = try trace(gpu, loaded, prompt, sampling, fresh.ids.len, false, .{ .saved = saved, .at = cut }); + defer resumed.deinit(gpu.gpa); + if (resumed.cached != cut or resumed.failed) return error.MiniSnapshotNotRestored; + try sameTrace(fresh, &resumed); +} + +/// A keeps states at 14 and 39; B resumes A's 14, keeps its 39 and decodes; A resumed at 39 must equal fresh A. +fn crossPrompt(gpu: Gpu, loaded: *native.Loaded, ids: []const u32) !void { + const Saved = @TypeOf(loaded.target.model).Saved; + const Keeper = struct { + b: *Backend, + saved: [2]?*Saved = .{ null, null }, + fn at(ptr: *anyopaque, s: *lanes.Stream, mark: u32) void { + const k: *@This() = @ptrCast(@alignCast(ptr)); + k.saved[@intFromBool(mark != 14)] = k.b.saveState(s, mark) catch null; + } + }; + const t = target(loaded); + const b = loaded.backend; + const a = ids[0..40]; + var other: [40]u32 = undefined; + @memcpy(other[0..14], ids[0..14]); + @memcpy(other[14..], ids[500..526]); + var fresh = try trace(gpu, loaded, a, null, 8, false, .{}); + defer fresh.deinit(gpu.gpa); + var ka: Keeper = .{ .b = t }; + defer for (ka.saved) |x| if (x) |y| t.dropState(y); + { + var s = try lanes.Stream.init(gpu.gpa, .{ .id = "mini-a", .prompt = a, .max_new = 1, .reuse = .{ .marks = &.{ 14, 39 } } }); + defer s.deinit(gpu.gpa); + defer b.release(&s); + s.reuse.hook = .{ .ptr = &ka, .at = Keeper.at }; + try b.prefill(&s); + } + var kb: Keeper = .{ .b = t }; + defer for (kb.saved) |x| if (x) |y| t.dropState(y); + { + var s = try lanes.Stream.init(gpu.gpa, .{ .id = "mini-b", .prompt = &other, .max_new = 8, .reuse = .{ .saved = ka.saved[0] orelse return error.MiniSnapshotNotSaved, .at = 14, .marks = &.{39} } }); + defer s.deinit(gpu.gpa); + defer b.release(&s); + s.reuse.hook = .{ .ptr = &kb, .at = Keeper.at }; + try b.prefill(&s); + if (s.cached != 14 or kb.saved[1] == null) return error.MiniSnapshotNotRestored; + var h = try b.first(&s, other.len); + for (0..6) |i| h = try b.queue(&s, .{ .handle = h }, other.len + i + 1); + } + var resumed = try trace(gpu, loaded, a, null, 8, false, .{ .saved = ka.saved[1] orelse return error.MiniSnapshotNotSaved, .at = 39 }); + defer resumed.deinit(gpu.gpa); + if (resumed.cached != 39 or resumed.failed) return error.MiniSnapshotNotRestored; + sameTrace(&fresh, &resumed) catch |err| { + std.debug.print("RESULT mini-serving cross-prompt resume mismatch={s} fresh={any} resumed={any}\n", .{ @errorName(err), fresh.ids, resumed.ids }); + return err; + }; +} + +fn freshAndResumed(gpu: Gpu, loaded: *native.Loaded, prompt: []const u32) !void { + for ([_]?lanes.Sampling{ null, sampled }, 0..) |sampling, case| { + var fresh = try trace(gpu, loaded, prompt, sampling, 8, false, .{}); + defer fresh.deinit(gpu.gpa); + const cuts: []const u32 = if (case == 0) &.{ 17, 2048 } else &.{ 2049, @intCast(prompt.len - 1) }; + for (cuts) |cut| try resumedAt(gpu, loaded, prompt, cut, sampling, &fresh); + } +} + +fn serve(gpu: Gpu, loaded: *native.Loaded, s: *lanes.Stream, proposer: ?lanes.proposer.Proposer) !void { + var cfg = try lanes.Config.init(gpu.gpa, loaded.facts, native.prompt_rows, native.window_rows); + defer cfg.deinit(gpu.gpa); + cfg.timed = false; + var clock: lanes.fake.FixedClock = .{}; + var e = lanes.Engine.init(gpu.gpa, &cfg, loaded.backend, clock.clock()); + defer e.deinit(); + if (proposer) |p| s.proposer = p; + try e.addStream(s); + while (!s.finished) try e.step(); + if (s.reason != .length) return error.MiniServingDidNotFinish; +} + +fn admission(gpu: Gpu, loaded: *native.Loaded, a: []const u32, b: []const u32) !void { + var plain_a = try trace(gpu, loaded, a, null, 10, false, .{}); + defer plain_a.deinit(gpu.gpa); + var plain_b = try trace(gpu, loaded, b, sampled, 10, false, .{}); + defer plain_b.deinit(gpu.gpa); + var first = try lanes.Stream.init(gpu.gpa, .{ .id = "mini-first", .prompt = a, .max_new = 10 }); + defer first.deinit(gpu.gpa); + var second = try lanes.Stream.init(gpu.gpa, .{ .id = "mini-second", .prompt = b, .max_new = 10, .sampling = sampled }); + defer second.deinit(gpu.gpa); + var cfg = try lanes.Config.init(gpu.gpa, loaded.facts, native.prompt_rows, native.window_rows); + defer cfg.deinit(gpu.gpa); + cfg.timed = false; + var clock: lanes.fake.FixedClock = .{}; + var e = lanes.Engine.init(gpu.gpa, &cfg, loaded.backend, clock.clock()); + defer e.deinit(); + if (!native.fits(loaded.ctx, @intCast(a.len), first.max_new)) return error.MiniUnexpectedFreeSlot; + try e.addStream(&first); + if (native.fits(loaded.ctx, @intCast(b.len), second.max_new)) return error.MiniBusyAdmissionRefused; + try std.testing.expectError(error.NoFreeSlot, loaded.backend.prefill(&second)); + while (!first.finished) try e.step(); + try std.testing.expectEqual(lanes.stream.Reason.length, first.reason); + if (!std.mem.eql(u32, first.emitted(), plain_a.ids)) return error.MiniAdmissionChangedFirst; + if (!native.fits(loaded.ctx, @intCast(b.len), second.max_new)) return error.MiniSlotNotReleased; + try e.addStream(&second); + while (!second.finished) try e.step(); + try std.testing.expectEqual(lanes.stream.Reason.length, second.reason); + if (!std.mem.eql(u32, second.emitted(), plain_b.ids)) return error.MiniAdmissionChangedSecond; +} + +/// Four slots: interleaved greedy and seeded streams equal solo; a fifth is refused before anything is queued. +fn concurrent(gpu: Gpu, loaded: *native.Loaded, ids: []const u32) !void { + const n = 4; + const cuts = [n][2]usize{ .{ 0, 257 }, .{ 17, 1042 }, .{ 300, 2400 }, .{ 5, 70 } }; + var solo: [n]Trace = undefined; + var done: usize = 0; + defer for (solo[0..done]) |*x| x.deinit(gpu.gpa); + for (cuts, 0..) |c, i| { + solo[i] = try trace(gpu, loaded, ids[c[0]..c[1]], if (i % 2 == 0) null else sampled, 10, false, .{}); + done += 1; + } + try loaded.reserve(loaded.ctx, n); + { + var busy: [n]lanes.Stream = undefined; + var opened: usize = 0; + defer for (busy[0..opened]) |*x| { + loaded.backend.release(x); + x.deinit(gpu.gpa); + }; + for (&busy, 0..) |*x, i| { + x.* = try lanes.Stream.init(gpu.gpa, .{ .id = "mini-busy", .prompt = ids[i .. i + 8], .max_new = 1 }); + opened += 1; + if (!native.fits(loaded.ctx, 8, 1)) return error.MiniSlotMissing; + try loaded.backend.prefill(x); + } + if (native.fits(loaded.ctx, 8, 1)) return error.MiniFifthAdmitted; + var fifth = try lanes.Stream.init(gpu.gpa, .{ .id = "mini-fifth", .prompt = ids[0..8], .max_new = 1 }); + defer fifth.deinit(gpu.gpa); + try std.testing.expectError(error.NoFreeSlot, loaded.backend.prefill(&fifth)); + if (fifth.fill_at.load(.monotonic) != 0) return error.MiniFifthQueued; + } + var streams: [n]lanes.Stream = undefined; + var made: usize = 0; + defer for (streams[0..made]) |*x| x.deinit(gpu.gpa); + for (cuts, 0..) |c, i| { + streams[i] = try lanes.Stream.init(gpu.gpa, .{ .id = "mini-concurrent", .prompt = ids[c[0]..c[1]], .max_new = 10, .sampling = if (i % 2 == 0) null else sampled }); + made += 1; + } + var cfg = try lanes.Config.init(gpu.gpa, loaded.facts, native.prompt_rows, native.window_rows); + defer cfg.deinit(gpu.gpa); + cfg.timed = false; + var clock: lanes.fake.FixedClock = .{}; + var e = lanes.Engine.init(gpu.gpa, &cfg, loaded.backend, clock.clock()); + defer e.deinit(); + for (&streams) |*x| try e.addStream(x); + var live = true; + while (live) { + try e.step(); + live = false; + for (&streams) |*x| live = live or !x.finished; + } + for (&streams, solo) |*x, want| { + if (x.reason != .length) return error.MiniServingDidNotFinish; + if (!std.mem.eql(u32, x.emitted(), want.ids)) return error.MiniConcurrentChangedTokens; + } +} + +/// Priced copies deliberately alternate whole matches, first-row rejection and a prefix match. +const Copier = struct { + prompt_len: usize, + plain: []const u32, + out: [4]u32 = undefined, + calls: usize = 0, + rejected: bool = false, + partial: bool = false, + continued: bool = false, + full: bool = false, + was_rejected: bool = false, + + fn propose(ptr: *anyopaque, context: []const u32, most: i64) anyerror![]const u32 { + const c: *@This() = @ptrCast(@alignCast(ptr)); + const n = context.len - c.prompt_len; + if (n >= c.plain.len or most < 2) return &.{}; + if (c.was_rejected) c.continued = true; + const count = @min(c.out.len, @min(c.plain.len - n, @as(usize, @intCast(most)))); + for (c.out[0..count], 0..) |*token, i| token.* = c.plain[n + i]; + const mode = c.calls % 3; + c.was_rejected = false; + if (mode == 0 and count >= 2) { + c.full = true; + } else if (mode == 1 and count >= 2) { + c.out[0] = if (c.out[0] == 0) 1 else 0; + c.rejected = true; + c.was_rejected = true; + } else if (count >= 2) { + c.out[1] = if (c.out[1] == 0) 1 else 0; + c.partial = true; + } + c.calls += 1; + return c.out[0..count]; + } + + fn proposer(c: *Copier) lanes.proposer.Proposer { + return .{ .ptr = c, .vtable = &.{ + .propose = propose, + .last_match = struct { + fn f(_: *anyopaque) i64 { + return 1; + } + }.f, + .priced = true, + } }; + } +}; + +/// Rewind a rejected, partially accepted or fully accepted window, then compare continuation bits with serial decode. +fn rollback(gpu: Gpu, loaded: *native.Loaded, prompt: []const u32, sampling: ?lanes.Sampling, plain: []const u32, accepted: usize) !void { + const t = target(loaded); + const v = t.m.w.c.text.unpadded_vocab; + const next = accepted + 1; + const ref = try gpu.gpa.alloc(f32, v); + defer gpu.gpa.free(ref); + var serial = try lanes.Stream.init(gpu.gpa, .{ .id = "mini-serial", .prompt = prompt, .max_new = 12, .sampling = sampling }); + defer serial.deinit(gpu.gpa); + const b = loaded.backend; + try b.prefill(&serial); + for (plain[0 .. next + 1], 0..) |token, i| _ = try b.queue(&serial, .{ .value = token }, prompt.len + i + 1); + try download(t, t.m.s.logits, ref); + b.release(&serial); + + var drafted = try lanes.Stream.init(gpu.gpa, .{ .id = "mini-drafted", .prompt = prompt, .max_new = 12, .sampling = sampling, .drafts = true }); + defer drafted.deinit(gpu.gpa); + defer b.release(&drafted); + try b.prefill(&drafted); + const pending = plain[0]; + var tokens: [4]u32 = undefined; + for (&tokens, 0..) |*token, i| token.* = plain[i + 1]; + if (accepted < tokens.len) tokens[accepted] = if (tokens[accepted] == 0) 1 else 0; + var positions: [5]u64 = undefined; + for (&positions, 0..) |*p, i| p.* = prompt.len + i + 1; + const window: lanes.backend.Window = .{ .stream = &drafted, .tokens = &tokens, .parents = null, .positions = &positions, .pending = pending, .held = 0 }; + var picks: [5]u32 = undefined; + var drafts: [4]u32 = undefined; + var out = [1]lanes.backend.Verified{.{ .sampled = &picks, .drafts = &drafts }}; + try b.verify(&.{window}, &out); + if (picks[accepted] != plain[next]) return error.MiniWrongCorrection; + var path: [5]u32 = undefined; + for (path[0..next], 0..) |*p, i| p.* = @intCast(i); + try b.keep(&.{window}, &.{path[0..next]}); + const handle = try b.queue(&drafted, .{ .value = plain[next] }, prompt.len + next + 1); + const after = try gpu.gpa.alloc(f32, v); + defer gpu.gpa.free(after); + try download(t, t.m.s.logits, after); + if (!std.mem.eql(u8, std.mem.sliceAsBytes(ref), std.mem.sliceAsBytes(after))) return error.MiniRollbackChangedLogits; + if (try b.read(handle) != plain[next + 1]) return error.MiniPostRejectionTokenChanged; +} + +fn copiedDrafts(gpu: Gpu, loaded: *native.Loaded, prompt: []const u32) !void { + for ([_]?lanes.Sampling{ null, sampled }) |sampling| { + var plain = try trace(gpu, loaded, prompt, sampling, 12, false, .{}); + defer plain.deinit(gpu.gpa); + var copier: Copier = .{ .prompt_len = prompt.len, .plain = plain.ids }; + var s = try lanes.Stream.init(gpu.gpa, .{ .id = "mini-copied", .prompt = prompt, .max_new = 12, .sampling = sampling, .drafts = true }); + defer s.deinit(gpu.gpa); + try serve(gpu, loaded, &s, copier.proposer()); + if (!std.mem.eql(u32, s.emitted(), plain.ids)) return error.MiniCopiesChangedTarget; + if (s.drafted == 0 or s.accepted == 0 or s.accepted == s.drafted) return error.MiniCopyCoverageMissing; + if (!(copier.full and copier.rejected and copier.partial and copier.continued)) return error.MiniCopyCaseMissing; + for ([_]usize{ 0, 1, 4 }) |accepted| try rollback(gpu, loaded, prompt, sampling, plain.ids, accepted); + } +} + +fn readIds(gpu: Gpu, path: []const u8) ![]u32 { + const text = try std.Io.Dir.cwd().readFileAlloc(gpu.io, path, gpu.gpa, .limited(1 << 26)); + defer gpu.gpa.free(text); + var out: std.ArrayList(u32) = .empty; + errdefer out.deinit(gpu.gpa); + var it = std.mem.tokenizeAny(u8, text, ", \n\r\t[]"); + while (it.next()) |t| try out.append(gpu.gpa, try std.fmt.parseInt(u32, t, 10)); + return out.toOwnedSlice(gpu.gpa); +} + +pub fn run(gpu: Gpu, model: []const u8, ids_path: []const u8) !void { + const ids = try readIds(gpu, ids_path); + defer gpu.gpa.free(ids); + if (ids.len < 4096) return error.MiniServingPromptTooShort; + const context = ids.len + 64; + var loaded = try native.open(gpu.gpa, gpu.io, gpu.ctx, model, null, .{ .context = context, .drafts = true }); + defer loaded.deinit(loaded.ctx); + try hostReference(gpu, &loaded, ids[0..4096]); + check.pass("Mini CUDA serving matches the host reference token for token", .{}); + try freshAndResumed(gpu, &loaded, ids[0..2309]); + check.pass("Mini CUDA fresh and resumed prompts produce identical logits and tokens", .{}); + try crossPrompt(gpu, &loaded, ids); + check.pass("Mini CUDA a state resumed after another prompt resumed its prefix equals the fresh prompt", .{}); + try admission(gpu, &loaded, ids[0..257], ids[17..1042]); + check.pass("Mini CUDA one-slot admission serializes concurrent requests without changing tokens", .{}); + try concurrent(gpu, &loaded, ids); + check.pass("Mini CUDA four slots: concurrent greedy and seeded replies equal solo, a fifth is refused", .{}); + try copiedDrafts(gpu, &loaded, ids[0..64]); + check.pass("Mini CUDA opt-in copy drafting preserves target tokens and rolls back exactly", .{}); +} diff --git a/zig/tests/cuda/lane_half_n_tests.zig b/zig/tests/cuda/lane_half_n_tests.zig new file mode 100644 index 00000000000..ced8477ec9c --- /dev/null +++ b/zig/tests/cuda/lane_half_n_tests.zig @@ -0,0 +1,121 @@ +//! TF_QMMF_HALF_BN's FP4, FP8 and FP8G half tiles against the 64-column tile: bytes at rows 1-16, then times. +const std = @import("std"); +const cuda = @import("cuda"); +const check = @import("check.zig"); +const rig = @import("flashnext_rig.zig"); + +const Mode = cuda.qmmf.Mode; +const half_n = cuda.qmmf_half; + +const Shape = struct { n: usize, k: usize }; + +/// Qwen3.8-27B's decode projections (MLP, GDN, attention, outputs), then column edges and the a/b heads' width. +const shapes = [_]Shape{ + .{ .n = 17408, .k = 5120 }, .{ .n = 5120, .k = 17408 }, .{ .n = 10240, .k = 5120 }, .{ .n = 6144, .k = 5120 }, + .{ .n = 12288, .k = 5120 }, .{ .n = 1024, .k = 5120 }, .{ .n = 5120, .k = 6144 }, .{ .n = 48, .k = 5120 }, + .{ .n = 72, .k = 1024 }, .{ .n = 131, .k = 2048 }, +}; + +/// Tensor scales: one, small, subnormal and infinite. +const scales = [_]f32{ 1.0, 0x1p-12, 1e-40, std.math.inf(f32) }; + +/// bf16 specials an adversarial row mixes in: zeros, subnormals, the largest finite and infinities. +const specials = [_]u16{ 0x0000, 0x8000, 0x0001, 0x8001, 0x7F7F, 0xFF7F, 0x7F80, 0xFF80 }; + +/// A random weight in `mode`, packed for the lane: raw bytes and scale bits when adversarial, else bounded values. +fn build(r: *rig.Rig, a: std.mem.Allocator, rng: std.Random, mode: Mode, sh: Shape, adversarial: bool) !cuda.qmmf.Weight { + const n = sh.n; + const k = sh.k; + const np = cuda.modelopt.padded(n); + switch (mode) { + .fp4 => { + const codes = try a.alloc(u8, n * k / 2); + rng.bytes(codes); + const blocks = try a.alloc(u8, n * k / 16); + for (blocks) |*s| s.* = if (adversarial) rng.int(u8) else 0x30 + rng.uintLessThan(u8, 16); + const words = try a.alloc(u32, np / 64 * (k / 64) * 512); + cuda.nvfp4.packWords(words, codes, n, k); + const tiles = try a.alloc(u8, np * (k / 16)); + cuda.nvfp4.packScales(tiles, blocks, n, k); + return cuda.nvfp4.weight(try r.dev(std.mem.sliceAsBytes(words)), try r.dev(tiles), 1.0, n, k); + }, + .fp8, .fp8g => { + const codes = try a.alloc(u8, n * k); + for (codes) |*c| c.* = if (adversarial) rng.int(u8) else rng.int(u8) & 0xF7; // no e4m3 NaN + const tiled = try a.alloc(u8, cuda.fp8.padded(n) * k); + cuda.fp8.packCodes(tiled, codes, n, k); + const codes_dev = try r.dev(tiled); + if (mode == .fp8) return cuda.modelopt.fp8Weight(codes_dev, 1.0, n, k); + // kernel tiles [npad/64][k/64][64] of fp32: any bits when adversarial + const tiles = try a.alloc(f32, cuda.fp8.padded(n) * (k / 64)); + for (tiles) |*s| s.* = if (adversarial) @bitCast(rng.int(u32)) else 0x1p-8 * (1 + rng.float(f32)); + return cuda.fp8.weight(codes_dev, try r.dev(std.mem.sliceAsBytes(tiles)), n, k); + }, + else => unreachable, + } +} + +fn refill(r: *rig.Rig, ptr: u64, bytes: usize) !void { + const b: cuda.DeviceBuffer = .{ .d = r.gpu.d, .ptr = ptr, .len = bytes }; + try b.fill8(0xff, r.s.handle); +} + +pub fn run(gpu: check.Gpu) !void { + var arena = std.heap.ArenaAllocator.init(gpu.gpa); + defer arena.deinit(); + const a = arena.allocator(); + var prng = std.Random.DefaultPrng.init(0x5b32); + const rng = prng.random(); + var r = try rig.Rig.init(gpu, a, rng); + defer r.deinit(); + var lane = try cuda.qmmf.Lane.load(gpu.d, @intCast(try gpu.ctx.capability() / 10)); + defer lane.unload(); + const set = try half_n.load(&lane); + var cells: usize = 0; + for (half_n.modes) |mode| for (shapes) |sh| for ([_]bool{ false, true }) |adversarial| { + const w0 = try build(&r, a, rng, mode, sh, adversarial); + const xs = r.bfs(16 * sh.k, if (adversarial) 4.0 else 1.0); + if (adversarial) for (xs) |*v| { + if (rng.uintLessThan(u8, 8) == 0) v.* = specials[rng.uintLessThan(usize, specials.len)]; + }; + const x = try r.dev(std.mem.sliceAsBytes(xs)); + const part = try r.out(@max(16, lane.partBytes(16, w0))); + const bytes = 17 * sh.n * 4; // 16 rows of fp32 and a guard row nothing may write + const ys = [2]u64{ try r.out(bytes), try r.out(bytes) }; + const tensor_scales: []const f32 = if (adversarial) &scales else scales[0..1]; + for (tensor_scales) |scale| for (1..17) |m| inline for (.{ cuda.qmmf.Out.bf16, cuda.qmmf.Out.f32 }) |out| { + var w = w0; + w.scale = scale; + for (ys, 0..) |y, on| { + try refill(&r, y, bytes); + lane.half_n = if (on == 1) set else null; + lane.half_below = if (on == 1) std.math.maxInt(usize) else 0; + try lane.matmulOut(r.s, x, sh.k, m, w, y, out, part); + } + try r.s.synchronize(); + try check.sameBytes("half tiles (FP4, FP8, FP8G) equal the 64-column tile", try r.back(u8, ys[1], bytes), try r.back(u8, ys[0], bytes)); + cells += 1; + }; + if (!adversarial) try time(&r, gpu, &lane, set, mode, sh, w0, x, ys[0], part); + }; + lane.half_n = null; + check.pass("lane-half-n: {d} FP4, FP8 and FP8G calls at rows 1-16, both outputs, adversarial values: bytes equal", .{cells}); +} + +/// The 64-column tile against the half tile, warm, at 1 and 16 rows (this engine's lanes only). +fn time(r: *rig.Rig, gpu: check.Gpu, lane: *cuda.qmmf.Lane, set: half_n.Set, mode: Mode, sh: Shape, w: cuda.qmmf.Weight, x: u64, y: u64, part: u64) !void { + for ([_]usize{ 1, 16 }) |m| { + var us: [2]f64 = undefined; + const reps = 200; + for (0..2) |on| { + lane.half_n = if (on == 1) set else null; + lane.half_below = if (on == 1) std.math.maxInt(usize) else 0; + const t0 = check.now(gpu.io); + for (0..reps) |_| try lane.matmul(r.s, x, sh.k, m, w, y, part); + try r.s.synchronize(); + us[on] = @as(f64, @floatFromInt(check.now(gpu.io) - t0)) / 1e3 / reps; + } + const p = cuda.qmmf.planFor(m, w, lane.clusters); + std.debug.print("lane-half-n {t} rows {d} n={d} k={d} (sk {d}): 64-col {d:.1} us, half {d:.1} us\n", .{ mode, m, sh.n, sh.k, p.sk, us[0], us[1] }); + } +} diff --git a/zig/tests/cuda/lfm2_vision_tests.zig b/zig/tests/cuda/lfm2_vision_tests.zig index c32fb828514..0b8b0becd28 100644 --- a/zig/tests/cuda/lfm2_vision_tests.zig +++ b/zig/tests/cuda/lfm2_vision_tests.zig @@ -343,7 +343,7 @@ fn features(r: *Rig, model: []const u8) !void { return error.TestFailed; }; defer cfg.deinit(gpa); - var w = try lfm2.weights.Weights.load(gpa, io, r.gpu.d, model, &cfg); + var w = try lfm2.weights.Weights.load(gpa, io, r.gpu.d, model, &cfg, true); defer w.deinit(gpa); var v = try vision.Vision.init(gpa, r.gpu.d, &cfg, &(w.vision orelse return error.NoVisionTower)); defer v.deinit(); diff --git a/zig/tests/cuda/main.zig b/zig/tests/cuda/main.zig index 06ebaadbf9c..2ae14911b1d 100644 --- a/zig/tests/cuda/main.zig +++ b/zig/tests/cuda/main.zig @@ -28,6 +28,7 @@ const affine8_tests = @import("affine8_tests.zig"); const native_fp_tests = @import("native_fp_tests.zig"); const affine4_decode_tests = @import("affine4_decode_tests.zig"); const absorb_batch_tests = @import("absorb_batch_tests.zig"); +const wide_rounds_tests = @import("wide_rounds_tests.zig"); const w4a8_tests = @import("w4a8_tests.zig"); const glm_exl3_tests = @import("glm_exl3_tests.zig"); const glm_kda_pad_check = @import("glm_kda_pad_check.zig"); @@ -109,6 +110,7 @@ const dory_tests = @import("dory_tests.zig"); const kolibri_layer_tests = @import("kolibri_layer_tests.zig"); const aot_fallback_tests = @import("aot_fallback_tests.zig"); const qwen_draft_frames = @import("qwen_draft_frames.zig"); +const ripple = @import("ripple_commands.zig"); const usage = @import("main_usage.zig").usage; @@ -146,6 +148,33 @@ fn arg(rest: []const [:0]const u8, i: usize) ![]const u8 { return rest[i]; } +fn compileInkling2Contracts() !void { + const shape: @import("core").contract.spec.Shape = .{ .rows = 1, .n = 2304, .k = 2 }; + const a: std.mem.Allocator = undefined; + const gpu: check.Gpu = undefined; + const stream: cuda.Stream = undefined; + var list: std.ArrayList(@import("core").contract.gates.Kernel) = .empty; + const set = try @import("contract_inkling2.zig").Set.init(gpu, stream, a, &list); + set.deinit(); + var rig: @import("contract_rig.zig").Rig = undefined; + const rng: std.Random = undefined; + var mix: @import("contract_inkling2_ops_mix.zig").Mix = undefined; + _ = try mix.prepare(a, &rig, shape, .random, rng); + try mix.run(&rig); + _ = try mix.replaced(&rig); + const sums: @import("contract_inkling2_ops_ref.zig").Sums = undefined; + const solved: []@import("contract_inkling2_ops_ref.zig").Iv = undefined; + try mix.solve(a, sums, solved); + var modelopt: @import("contract_inkling2_modelopt.zig").ModelOpt = undefined; + _ = try modelopt.prepare(shape, .random, 0); + try modelopt.run(); + _ = modelopt.kernel(); + _ = modelopt.count(); + const want: []f64 = undefined; + const mag: []f64 = undefined; + try modelopt.reference(want, mag); +} + fn compileContractGlue() !void { // the contract glue's device path, built with the runner: prepare through the vtable const cores = std.Thread.getCpuCount() catch 1; if (cores != 0) return; @@ -153,6 +182,7 @@ fn compileContractGlue() !void { // the contract glue's device path, built with g.kind = .chain; const kernels = [_]@import("core").contract.gates.Kernel{g.kernel()}; for (kernels) |k| _ = try k.vt.prepare(k.ctx, .{ .rows = 0, .n = 0, .k = 0 }, .random, 0); + try compileInkling2Contracts(); } fn run(gpu: check.Gpu, cmd: []const u8, rest: []const [:0]const u8) !void { @@ -191,6 +221,8 @@ fn run(gpu: check.Gpu, cmd: []const u8, rest: []const [:0]const u8) !void { if (std.mem.eql(u8, cmd, "qmmf-prompt-repro")) return @import("qmmf_prompt_tests.zig").repro(gpu); if (std.mem.eql(u8, cmd, "qmmf-prompt-bench")) return @import("qmmf_prompt_tests.zig").bench(gpu); if (std.mem.eql(u8, cmd, "lane-half")) return lane_half_tests.run(gpu); + if (std.mem.eql(u8, cmd, "group-proj")) return @import("group_proj_tests.zig").run(gpu); + if (std.mem.eql(u8, cmd, "lane-half-n")) return @import("lane_half_n_tests.zig").run(gpu); if (std.mem.eql(u8, cmd, "flashnext-dense-hc")) return flashnext_dense_hc_tests.run(gpu); if (std.mem.eql(u8, cmd, "flashnext-hc")) return flashnext_hc_tests.run(gpu); if (std.mem.eql(u8, cmd, "flashnext-attn")) return flashnext_attn_tests.run(gpu); @@ -241,6 +273,7 @@ fn run(gpu: check.Gpu, cmd: []const u8, rest: []const [:0]const u8) !void { if (std.mem.eql(u8, cmd, "native-fp")) return native_fp_tests.run(gpu); if (std.mem.eql(u8, cmd, "affine4-decode")) return affine4_decode_tests.run(gpu); if (std.mem.eql(u8, cmd, "absorb-batch")) return absorb_batch_tests.run(gpu); + if (std.mem.eql(u8, cmd, "wide-rounds")) return wide_rounds_tests.run(gpu); if (std.mem.eql(u8, cmd, "w4a8")) return w4a8_tests.run(gpu); if (std.mem.eql(u8, cmd, "glm-exl3") or std.mem.eql(u8, cmd, "glm-exl3-items")) return glm_exl3_tests.runCmd(gpu, cmd); if (std.mem.eql(u8, cmd, "glm-kda-pad-split")) return glm_kda_pad_check.run(gpu); @@ -336,11 +369,13 @@ fn run(gpu: check.Gpu, cmd: []const u8, rest: []const [:0]const u8) !void { if (std.mem.eql(u8, cmd, "qwen-pages")) return @import("contract_qwen_pages.zig").run(gpu); if (std.mem.eql(u8, cmd, "qwen-shared-prefix")) return @import("contract_qwen_shared_prefix.zig").run(gpu, rest); if (std.mem.eql(u8, cmd, "qwen-norm-shift")) return @import("qwen_norm_shift_tests.zig").run(gpu); + if (std.mem.eql(u8, cmd, "qwen-prefill-cap")) return @import("qwen_prefill_cap_tests.zig").run(gpu, try arg(rest, 0), try arg(rest, 1)); if (std.mem.eql(u8, cmd, "clef")) return @import("clef_tests.zig").run(gpu, rest); if (std.mem.startsWith(u8, cmd, "dots-")) return @import("dots_tests.zig").run(gpu, cmd, rest); if (std.mem.eql(u8, cmd, "qwen-pending")) return @import("contract_qwen_pending.zig").run(gpu); if (std.mem.eql(u8, cmd, "dspine-table")) return @import("dspine_table_tests.zig").runAll(gpu); if (std.mem.eql(u8, cmd, "minimax-contract")) return @import("contract_minimax.zig").run(gpu); + if (try ripple.run(gpu, cmd)) return; if (std.mem.eql(u8, cmd, "rope-yarn")) return @import("contract_qwen_rope_yarn.zig").run(gpu); if (std.mem.eql(u8, cmd, "pocket-contract")) return @import("contract_pocket.zig").run(gpu); if (std.mem.eql(u8, cmd, "flashnext-modelopt-contract")) return @import("contract_flashnext_modelopt.zig").run(gpu); @@ -379,6 +414,7 @@ fn run(gpu: check.Gpu, cmd: []const u8, rest: []const [:0]const u8) !void { if (std.mem.eql(u8, cmd, "kolibri-reference")) return kolibri_layer_tests.reference(gpu, try arg(rest, 0), try arg(rest, 1)); if (std.mem.eql(u8, cmd, "kolibri-layers")) return kolibri_layer_tests.layers(gpu, try arg(rest, 0), try arg(rest, 1)); if (std.mem.eql(u8, cmd, "kolibri-full")) return kolibri_tests.full(gpu, try arg(rest, 0), try arg(rest, 1), try arg(rest, 2)); + if (std.mem.eql(u8, cmd, "inkling2-serving")) return @import("inkling2_serving_tests.zig").run(gpu, try arg(rest, 0), try arg(rest, 1)); if (std.mem.eql(u8, cmd, "kolibri-pages")) return @import("kolibri_pages_tests.zig").pages(gpu, rest); if (std.mem.eql(u8, cmd, "kolibri-greedy")) return kolibri_tests.greedy(gpu, try arg(rest, 0), try arg(rest, 1), try arg(rest, 2), try arg(rest, 3)); if (std.mem.eql(u8, cmd, "kolibri-logits")) return kolibri_tests.logits(gpu, try arg(rest, 0), try arg(rest, 1), try arg(rest, 2), if (rest.len > 3) rest[3] else null); diff --git a/zig/tests/cuda/main_usage.zig b/zig/tests/cuda/main_usage.zig index 5ea8569a84c..3cc35e2b77d 100644 --- a/zig/tests/cuda/main_usage.zig +++ b/zig/tests/cuda/main_usage.zig @@ -3,6 +3,7 @@ pub const usage = \\usage: tf-cuda-test \\ qwen4 synthetic native Qwen4: binary64 logits/tokens, state seams, lanes and copied drafts + \\ inkling2-serving MODEL IDS_FILE Mini CUDA host-reference, resume, admission and copy-rollback serving equivalence \\ qwen-draft-frames MODEL DRAFTER IDS OUT native 27B DFlash frames: raw bytes equal across partitions, controls red \\ experts-rows experts_rows.cu's windows and chunks against the decode kernel's one-row launches \\ route-rows route_rows.cu's router logits and softmax top-k against float64 (synthetic rows) @@ -25,6 +26,8 @@ pub const usage = \\ nvfp4-b32 block 32 experts with csf0 scales: block 16's bytes on equal scales, each form and width \\ nvfp4-nz5 NVFP4_NZ5's block 32 experts: E2M1's bytes with each +5 a 4 under a scale 1.25x as large \\ lane-half lane half tiles (MXFP8, BF16): bytes equal to the 64-column tile, FP64, cold-weight time + \\ group-proj grouped same-input lane projections: each one's bytes equal its own launch, rows 1-16 + \\ lane-half-n TF_QMMF_HALF_BN half tiles (FP4, FP8, FP8G): bytes equal to the 64-column tile, rows 1-16 \\ flashnext-dense-hc dense connection weights and FP32 normalization against FP64 \\ flashnext-hc Flash Next's own hyper-connection and n-gram glue against float64 (synthetic rows) \\ flashnext-attn Flash Next's own attention glue, pooling and block scores against float64 (synthetic) @@ -86,6 +89,7 @@ pub const usage = \\ marks MODEL IDS_FILE N PATTERNS states kept inside chunks against chunks cut at the same rows, byte for byte \\ prompt-cuts MODEL IDS_FILE a prompt keeping states inside chunks and at their ends (background passes too), and resumed from each, equals one uncut pass \\ prompt-segments MODEL IDS_FILE a prompt run as 2 to 4 staggered segments a call equals one uncut pass, byte for byte + \\ qwen-prefill-cap MODEL IDS_FILE a 12,000-row Qwen prompt cut at 512 rows beside a live stream equals its uncut pass: logits and 64 greedy tokens, byte for byte \\ cached-plans-tp2 MODEL IDS_FILE rank-zero cached plans and prompt resumes with the existing expert rank \\ shared-fork MODEL the latent MoE's shared expert on the side stream (held back), lone and in shared windows of 2/4/8 streams, against one stream, byte for byte \\ recapture MODEL graphs captured again while another sequence is bound: both keep their sampling rules @@ -102,6 +106,7 @@ pub const usage = \\ native-fp -Dnative-fp-decode: hardware e2m1/e4m3 pair decode equals software on every finite input \\ affine4-decode affine-4 decode at the Qwen3.5 shapes: row counts and segmented launches byte for byte \\ absorb-batch DFlash2 absorb projections over 1/4/8/16 streams' rows in one pass vs each alone, byte for byte + \\ wide-rounds Nemotron Lightning dense calls at 17-32 rows vs 16-row calls (affine-4, NVFP4), byte for byte \\ w4a8 int8-activation prompt matmuls on affine-4 tiles: float64 of their formula, rows (synthetic) \\ carveout [MiB] [card] GB10 display memory: round trips and bandwidth (SKIP without the card) \\ nvfp4 NVFP4 projections against recorded lane-matmul and prompt-GEMM fixture bytes @@ -157,6 +162,9 @@ pub const usage = \\ pocket-contract Nemotron's pocket kernels (learned neurons) through gates 1-4, controls red \\ flashnext-modelopt-contract Flash Next NVFP4's BF16 dense and FP8 MTP-expert downs through gates 1-4 \\ minimax-contract MiniMax-M3.1-Flash's indexer and block-sparse attention through gates 1-4, controls red + \\ ricursive-contract Ripple's glue, attention prep and attention (group 10) through gates 1-4, controls red + \\ ripple-forward Ripple's forward rounds (streams, verify windows, mixes) == one-row steps, bit for bit (synthetic) + \\ ripple-serve Ripple's lane backend: shared rounds, copied drafts, kept states, logprob rows (synthetic) \\ moss-contract [ONLY..] MOSS-Image's own kernels, its decoder's unpack and its encoder's mixer, gates 1-4, controls red \\ idol-decoder-contract Idol's decoders' stem, to_kv, head norms and attention through gates 1-4, controls red \\ idol-contract Idol's denoiser glue and head-64 attention through gates 1-4, controls red diff --git a/zig/tests/cuda/qwen_prefill_cap_tests.zig b/zig/tests/cuda/qwen_prefill_cap_tests.zig new file mode 100644 index 00000000000..885555ea32c --- /dev/null +++ b/zig/tests/cuda/qwen_prefill_cap_tests.zig @@ -0,0 +1,193 @@ +//! tf-cuda-test qwen-prefill-cap MODEL IDS_FILE: a 12,000-row Qwen prompt capped at 512 rows, against its uncut pass. +const std = @import("std"); +const lanes = @import("lanes"); +const q = @import("qwen35"); +const check = @import("check.zig"); +const request_starts = @import("request_start_checks.zig"); + +const prompt_rows = 12000; +const cap: u32 = 512; +const draws = 64; // greedy tokens compared after the prompt: the first from its last row, then 63 decode rows +const key_chunk = 256; // window_attention.chunk_keys: full attention reads its keys in chunks of this many rows +const peer_from = 5000; // the live stream's prompt: 300 rows of the file, sharing no prefix with the long prompt +const peer_rows = 300; +const peer_draws = 192; // above any case's steps plus `draws`: the peer decodes after each step and target token +const context = prompt_rows + peer_draws + 96; + +/// A cut layout: the request's chunk starts, the last capped piece's rows, and whether cuts fall inside key chunks. +const Case = struct { name: []const u8, starts: []const u32, tail: u32, inside_keys: bool }; + +const cases = [_]Case{ + .{ .name = "grid chunks", .starts = &.{}, .tail = 224, .inside_keys = false }, + .{ .name = "600-row chunk (512 + 88)", .starts = &.{ 4096, 4696 }, .tail = 136, .inside_keys = true }, + .{ .name = "off-grid start", .starts = &.{4133}, .tail = 187, .inside_keys = true }, + // cold chunks of 512 plus 1, 63, 64, 65, 127, 128, 129, 255, 256 and 257 rows: second pieces cross each tile + .{ .name = "tile edges", .starts = &.{ 513, 1088, 1664, 2241, 2880, 3520, 4161, 4928, 5696, 6465 }, .tail = 415, .inside_keys = true }, +}; + +const Ctx = struct { gpu: check.Gpu, l: *q.native.Lanes, b: lanes.backend.Backend, vocab: usize }; + +/// What a pass leaves: its cut ends, the prompt's last logits and each decode row's, and the greedy tokens. +const Pass = struct { + cuts: std.ArrayList(u32) = .empty, + logits: []u16, + tokens: [draws]u32 = undefined, + + fn deinit(p: *Pass, gpa: std.mem.Allocator) void { + p.cuts.deinit(gpa); + gpa.free(p.logits); + } +}; + +/// The newest forward's one kept row, read from the device. +fn deviceRow(c: *const Ctx, out: []u16) !void { + const e = c.l.e; + try e.d.check(e.d.api.cuMemcpyDtoH_v2(out.ptr, e.logits, out.len * 2), "cuMemcpyDtoH"); +} + +/// The second stream: decoding one greedy token a round on the same engine, each row's logits hashed. +const Peer = struct { + c: *const Ctx, + s: lanes.Stream, + tokens: [peer_draws]u32 = undefined, + rows: [peer_draws][32]u8 = undefined, + n: usize = 0, + + fn init(c: *const Ctx, ids: []const u32) !Peer { + return .{ .c = c, .s = try lanes.Stream.init(c.gpu.gpa, .{ .id = "peer", .prompt = ids, .max_new = peer_draws, .drafts = false }) }; + } + + fn deinit(p: *Peer) void { + p.c.b.vtable.release(p.c.b.ptr, &p.s); + p.s.deinit(p.c.gpu.gpa); + } + + fn start(p: *Peer) !void { + const b = p.c.b; + while (!try b.vtable.prefill_step.?(b.ptr, &p.s, 0)) {} + const cache = try p.c.l.cacheOf(&p.s); + std.crypto.hash.sha2.Sha256.hash(std.mem.sliceAsBytes(cache.logits), &p.rows[0], .{}); + p.tokens[0] = try b.vtable.read(b.ptr, try b.vtable.first(b.ptr, &p.s, peer_rows)); + p.n = 1; + } + + fn round(p: *Peer) !void { + try check.expect(p.n < peer_draws, "qwen-prefill-cap: the live stream ran out of its {d} tokens", .{peer_draws}); + const b = p.c.b; + const handle = try b.vtable.queue(b.ptr, &p.s, .{ .value = p.tokens[p.n - 1] }, peer_rows + p.n); + const row = try p.c.gpu.gpa.alloc(u16, p.c.vocab); + defer p.c.gpu.gpa.free(row); + try deviceRow(p.c, row); + std.crypto.hash.sha2.Sha256.hash(std.mem.sliceAsBytes(row), &p.rows[p.n], .{}); + p.tokens[p.n] = try b.vtable.read(b.ptr, handle); + p.n += 1; + } + + /// Every token and row so far equals the same stream's run alone. + fn same(p: *const Peer, alone: *const Peer, what: []const u8) !void { + try check.sameBytes(what, std.mem.sliceAsBytes(p.tokens[0..p.n]), std.mem.sliceAsBytes(alone.tokens[0..p.n])); + for (p.rows[0..p.n], alone.rows[0..p.n], 0..) |got, want, i| + try check.expect(std.mem.eql(u8, &got, &want), "{s}: logits of its token {d} differ", .{ what, i }); + } +}; + +/// One prompt pass under `max_rows` (0: cold cuts), then its greedy tokens; `peer` decodes after each step and token. +fn pass(c: *const Ctx, ids: []const u32, starts: []const u32, max_rows: u32, peer: ?*Peer) !Pass { + const gpa = c.gpu.gpa; + const b = c.b; + var out: Pass = .{ .logits = try gpa.alloc(u16, draws * c.vocab) }; + errdefer out.deinit(gpa); + var s = try lanes.Stream.init(gpa, .{ .id = "long", .prompt = ids, .max_new = draws, .drafts = false, .chunks = starts }); + defer s.deinit(gpa); + defer b.vtable.release(b.ptr, &s); + while (true) { + const done = try b.vtable.prefill_step.?(b.ptr, &s, max_rows); + try out.cuts.append(gpa, s.fill_at.load(.monotonic)); + if (done) break; + if (peer) |p| try p.round(); + } + const cache = try c.l.cacheOf(&s); + @memcpy(out.logits[0..c.vocab], cache.logits); + out.tokens[0] = try b.vtable.read(b.ptr, try b.vtable.first(b.ptr, &s, ids.len)); + for (1..draws) |i| { + if (peer) |p| try p.round(); + const handle = try b.vtable.queue(b.ptr, &s, .{ .value = out.tokens[i - 1] }, ids.len + i); + try deviceRow(c, out.logits[i * c.vocab ..][0..c.vocab]); + out.tokens[i] = try b.vtable.read(b.ptr, handle); + } + return out; +} + +/// The capped cuts: at most `cap` rows each, every cold cut kept, the expected last piece, cuts inside key chunks. +fn cutsHold(case: Case, cold: []const u32, got: []const u32) !void { + try check.expect(got.len > cold.len, "{s}: {d} capped steps for {d} cold ones: the cap did not reach the pass", .{ case.name, got.len, cold.len }); + try check.expect(got[got.len - 1] == prompt_rows, "{s}: the pass ended at row {d}", .{ case.name, got[got.len - 1] }); + var from: u32 = 0; + var inside = false; + for (got) |end| { + try check.expect(end > from and end - from <= cap, "{s}: a step of {d} rows ending at {d}", .{ case.name, end - from, end }); + inside = inside or (end != prompt_rows and end % key_chunk != 0); // the prompt's end is not a cut + from = end; + } + for (cold) |end| try check.expect(std.mem.indexOfScalar(u32, got, end) != null, "{s}: cold cut {d} did not land", .{ case.name, end }); + const last = got[got.len - 1] - got[got.len - 2]; + try check.expect(last == case.tail, "{s}: the last piece has {d} rows, expected {d}", .{ case.name, last, case.tail }); + try check.expect(inside == case.inside_keys, "{s}: cuts inside a {d}-row key chunk: {any}, expected {any}", .{ case.name, key_chunk, inside, case.inside_keys }); +} + +fn equal(what: []const u8, got: *const Pass, want: *const Pass) !void { + try check.sameBytes(what, std.mem.sliceAsBytes(got.logits), std.mem.sliceAsBytes(want.logits)); + try check.sameBytes(what, std.mem.sliceAsBytes(&got.tokens), std.mem.sliceAsBytes(&want.tokens)); +} + +/// One layout: uncut, capped alone (a difference here is the cut's), then capped beside the live stream. +fn runCase(c: *const Ctx, ids: []const u32, peer_ids: []const u32, alone: *const Peer, case: Case) !void { + const gpa = c.gpu.gpa; + var whole = try pass(c, ids, case.starts, 0, null); + defer whole.deinit(gpa); + var solo = try pass(c, ids, case.starts, cap, null); + defer solo.deinit(gpa); + try cutsHold(case, whole.cuts.items, solo.cuts.items); + var buf: [120]u8 = undefined; + try equal(try std.fmt.bufPrint(&buf, "{s}: capped alone", .{case.name}), &solo, &whole); + var peer = try Peer.init(c, peer_ids); + defer peer.deinit(); + try peer.start(); + var live = try pass(c, ids, case.starts, cap, &peer); + defer live.deinit(gpa); + try check.expect(std.mem.eql(u32, live.cuts.items, solo.cuts.items), "{s}: the cuts moved beside a live stream", .{case.name}); + try equal(try std.fmt.bufPrint(&buf, "{s}: capped beside a live stream", .{case.name}), &live, &whole); + try peer.same(alone, try std.fmt.bufPrint(&buf, "{s}: the live stream", .{case.name})); + var digest: [32]u8 = undefined; + std.crypto.hash.sha2.Sha256.hash(std.mem.sliceAsBytes(whole.logits), &digest, .{}); + check.pass("qwen-prefill-cap {s}: {d} cold steps, {d} capped, last piece {d} rows, {d} logit rows and {d} tokens equal, live stream's {d} tokens equal (logits sha256 {x})", .{ case.name, whole.cuts.items.len, live.cuts.items.len, case.tail, draws, draws, peer.n, digest }); +} + +/// MODEL's text path over the first 12,000 ids of IDS_FILE, every layout, and a control that a changed prompt shows. +pub fn run(gpu: check.Gpu, model: []const u8, ids_path: []const u8) !void { + const gpa = gpu.gpa; + const ids = try request_starts.readIds(gpu, ids_path, std.fmt.comptimePrint("{d}", .{prompt_rows})); + defer gpa.free(ids); + const loaded = try q.native.openLanes(gpa, gpu.io, gpu.ctx, model, null, .{ .context = context, .drafts = false }); + defer loaded.deinit(loaded.ctx); + const l: *q.native.Lanes = @ptrCast(@alignCast(loaded.ctx)); + try check.expect(l.e.scratch_rows == q.engine.grid_rows, "qwen-prefill-cap: unset TF_QWEN35_CHUNK_SOLO: the uncut pass must take {d}-row steps, not {d}", .{ q.engine.grid_rows, l.e.scratch_rows }); + try request_starts.validateIds(ids, l.e.g.vocab); + const c: Ctx = .{ .gpu = gpu, .l = l, .b = loaded.backend, .vocab = l.e.g.vocab }; + const peer_ids = ids[peer_from..][0..peer_rows]; + var alone = try Peer.init(&c, peer_ids); + defer alone.deinit(); + try alone.start(); + while (alone.n < peer_draws) try alone.round(); + for (cases) |case| try runCase(&c, ids, peer_ids, &alone, case); + // the control: one changed prompt token must change the bytes this cell compares + const changed = try gpa.dupe(u32, ids); + defer gpa.free(changed); + changed[prompt_rows - 2] = if (changed[prompt_rows - 2] + 1 == c.vocab) 0 else changed[prompt_rows - 2] + 1; + var base = try pass(&c, ids, &.{}, 0, null); + defer base.deinit(gpa); + var other = try pass(&c, changed, &.{}, 0, null); + defer other.deinit(gpa); + try check.expect(!std.mem.eql(u16, base.logits, other.logits), "qwen-prefill-cap: a changed prompt token left the compared logits equal", .{}); + check.pass("qwen-prefill-cap: {d} layouts equal their uncut pass; a changed prompt token changes the compared logits", .{cases.len}); +} diff --git a/zig/tests/cuda/ripple_commands.zig b/zig/tests/cuda/ripple_commands.zig new file mode 100644 index 00000000000..cc60d2ead9f --- /dev/null +++ b/zig/tests/cuda/ripple_commands.zig @@ -0,0 +1,15 @@ +//! Ripple's tf-cuda-test commands, which main.zig reaches through one entry. +const std = @import("std"); +const check = @import("check.zig"); + +/// Runs `cmd` when it is one of Ripple's commands; false for any other. +pub fn run(gpu: check.Gpu, cmd: []const u8) !bool { + if (std.mem.eql(u8, cmd, "ricursive-contract")) { + try @import("contract_ricursive.zig").run(gpu); + } else if (std.mem.eql(u8, cmd, "ripple-forward")) { + try @import("ripple_forward_tests.zig").run(gpu); + } else if (std.mem.eql(u8, cmd, "ripple-serve")) { + try @import("ripple_serve_tests.zig").run(gpu); + } else return false; + return true; +} diff --git a/zig/tests/cuda/ripple_forward_tests.zig b/zig/tests/cuda/ripple_forward_tests.zig new file mode 100644 index 00000000000..4b5851ab592 --- /dev/null +++ b/zig/tests/cuda/ripple_forward_tests.zig @@ -0,0 +1,489 @@ +//! Ripple's forward rounds == one-row steps, bit for bit (ripple-forward): streams, verify windows, graphs, reuse. +const std = @import("std"); +const cuda = @import("cuda"); +const rc = @import("ricursive_cuda"); +const check = @import("check.zig"); + +const fwd = rc.model; +const wts = rc.weights; +const Config = @FieldType(wts.Weights, "config"); +const Weight = cuda.qmmf.Weight; + +/// The release's attention and widths, so every lane matmul takes the release's plan (tile, K slices, cluster). +pub fn config() Config { + var c: Config = .{ .hidden = 5120, .intermediate = 12288, .layers = 10, .heads = 80, .kv_heads = 8, .vocab = 16384, .eps = 1e-6, .theta = 10000, .window = 1024, .embed_scale = 71.55417527999327, .clamp = 20, .context = 8192, .fp4_mlp = true }; + for (0..c.layers) |i| c.global[i] = i % 5 == 4; + return c; +} + +/// bf16 bits of x, rounded to nearest even. +fn bf16(x: f32) u16 { + const b: u32 = @bitCast(x); + return @intCast((b + 0x7fff + ((b >> 16) & 1)) >> 16); +} + +const Build = struct { + w: *wts.Weights, + d: *const cuda.Driver, + r: std.Random, + + fn put(b: Build, bytes: []const u8) !u64 { + var buf = try cuda.DeviceBuffer.fromHost(b.d, bytes); + errdefer buf.free(); + try b.w.buffers.append(b.w.gpa, buf); + b.w.bytes += bytes.len; + return buf.ptr; + } + + /// `n` bf16 values of magnitude in [2^e, 2^(e+1)), random signs and mantissas (fast: the release's sizes). + fn values(b: Build, n: usize, e: i32) ![]u16 { + const v = try b.w.gpa.alloc(u16, n); + const exp: u16 = @intCast((e + 127) << 7); + var bits: u64 = 0; + for (v, 0..) |*x, i| { + if (i % 4 == 0) bits = b.r.int(u64); + x.* = exp | @as(u16, @truncate(bits & 0x807f)); + bits >>= 16; + } + return v; + } + + /// A norm's or the embedding's bf16 values, normal with deviation `sd` around `mean`. + fn small(b: Build, n: usize, mean: f32, sd: f32) !u64 { + const v = try b.w.gpa.alloc(u16, n); + defer b.w.gpa.free(v); + for (v) |*x| x.* = bf16(mean + sd * b.r.floatNorm(f32)); + return b.put(std.mem.sliceAsBytes(v)); + } + + /// A bf16 [n, k] projection packed for the lane and prompt matmuls, its values about 1 / sqrt(k). + fn dense(b: Build, n: usize, k: usize) !Weight { + const src = try b.values(n * k, -@as(i32, std.math.log2_int(usize, k) / 2) - 1); + defer b.w.gpa.free(src); + const out = try b.w.gpa.alloc(u16, cuda.modelopt.padded(n) * k); + defer b.w.gpa.free(out); + cuda.qmmf.packBf16(out, src, n, k); + return cuda.modelopt.bf16Weight(try b.put(std.mem.sliceAsBytes(out)), n, k); + } + + /// An NVFP4 [n, k] projection: random nibbles, E4M3 scales of 1 to 3, a global of 1/1024 (about 1 / sqrt(k)). + fn fp4(b: Build, n: usize, k: usize) !Weight { + const gpa = b.w.gpa; + const codes = try gpa.alloc(u8, n * k / 2); + defer gpa.free(codes); + b.r.bytes(codes); + const scales = try gpa.alloc(u8, n * k / 16); + defer gpa.free(scales); + const e4m3 = [_]u8{ 0x38, 0x3c, 0x40, 0x44 }; + b.r.bytes(scales); + for (scales) |*x| x.* = e4m3[x.* & 3]; + const words = try gpa.alloc(u32, cuda.nvfp4.padded(n) / 64 * (k / 64) * 512); + defer gpa.free(words); + const tiles = try gpa.alloc(u8, cuda.nvfp4.padded(n) * (k / 16)); + defer gpa.free(tiles); + cuda.nvfp4.packWords(words, codes, n, k); + cuda.nvfp4.packScales(tiles, scales, n, k); + return cuda.nvfp4.weight(try b.put(std.mem.sliceAsBytes(words)), try b.put(tiles), 1.0 / 1024.0, n, k); + } +}; + +/// Random weights in the loader's layout (cuda_weights.load): q, k and g one projection, NVFP4 MLPs. +pub fn build(gpu: check.Gpu, c: Config, seed: u64) !wts.Weights { + var w: wts.Weights = .{ .gpa = gpu.gpa, .config = c }; + errdefer w.deinit(); + var prng = std.Random.DefaultPrng.init(seed); + const b: Build = .{ .w = &w, .d = gpu.d, .r = prng.random() }; + const h = c.hidden; + const q = c.queryWidth(); + const kv = c.kvWidth(); + w.embed = try b.small(c.vocab * h, 0, 0.02); + w.head = try b.dense(c.vocab, h); + w.norm = try b.small(h, 1, 0.1); + w.layers = try gpu.gpa.alloc(wts.Layer, c.layers); + for (w.layers) |*l| l.* = .{ + .qkg = try b.dense(2 * q + kv, h), + .v = try b.dense(kv, h), + .o = try b.dense(h, q), + .gate = try b.fp4(c.intermediate, h), + .up = try b.fp4(c.intermediate, h), + .down = try b.fp4(h, c.intermediate), + .input_norm = try b.small(h, 1, 0.1), + .post_attn = try b.small(h, 1, 0.1), + .pre_ffn = try b.small(h, 1, 0.1), + .post_ffn = try b.small(h, 1, 0.1), + .q_norm = try b.small(128, 1, 0.1), + .k_norm = try b.small(128, 1, 0.1), + .blend = wts.blendOf(bf16(b.r.float(f32) * 2 - 1)), + }; + return w; +} + +/// A stream: its prompt's length and decode tokens (teacher-forced, so every run feeds the same rows). +const Spec = struct { name: []const u8, prompt: usize }; + +const specs = [_]Spec{ + .{ .name = "A", .prompt = 507 }, // rows across the 512-row page edge + .{ .name = "B", .prompt = 3066 }, // across the 3,072-row ring's wrap + .{ .name = "C", .prompt = 1019 }, // across 1,024: a page edge and the window's + .{ .name = "D", .prompt = 37 }, + .{ .name = "E", .prompt = 4093 }, // a wrapped ring, rows across 4,096 keys (8 to 9 key groups) +}; + +/// Rounds of (stream, rows): several streams a row each, a verify window, mixes of 20 and 48 rows, one and k rows. +const rounds = [_][]const [2]usize{ + &.{ .{ 0, 1 }, .{ 1, 1 }, .{ 2, 1 }, .{ 3, 1 }, .{ 4, 1 } }, + &.{.{ 1, 8 }}, + &.{ .{ 0, 5 }, .{ 2, 5 }, .{ 3, 5 }, .{ 4, 5 } }, + &.{ .{ 0, 10 }, .{ 1, 10 }, .{ 2, 10 }, .{ 3, 10 }, .{ 4, 8 } }, + &.{ .{ 3, 1 }, .{ 1, 3 } }, +}; +const round_rows = 48; + +fn decodeTokens(j: usize) usize { + var n: usize = 0; + for (rounds) |r| for (r) |x| if (x[0] == j) { + n += x[1]; + }; + return n; +} + +const Streams = struct { + gpa: std.mem.Allocator, + ids: [specs.len][]u32 = undefined, // the prompt, then the decode tokens + want: [specs.len][][]u8 = undefined, // one-row steps' logits a decode token + prompt: [specs.len][]u8 = undefined, // the prompt's last row's logits + + fn init(gpa: std.mem.Allocator, vocab: usize, seed: u64) !Streams { + var x: Streams = .{ .gpa = gpa }; + var prng = std.Random.DefaultPrng.init(seed); + for (specs, 0..) |sp, j| { + x.ids[j] = try gpa.alloc(u32, sp.prompt + decodeTokens(j)); + for (x.ids[j]) |*t| t.* = prng.random().uintLessThan(u32, @intCast(vocab)); + x.want[j] = try gpa.alloc([]u8, decodeTokens(j)); + for (x.want[j]) |*l| l.* = try gpa.alloc(u8, vocab * 2); + x.prompt[j] = try gpa.alloc(u8, vocab * 2); + } + return x; + } + + fn deinit(x: *Streams) void { + for (0..specs.len) |j| { + for (x.want[j]) |l| x.gpa.free(l); + x.gpa.free(x.want[j]); + x.gpa.free(x.ids[j]); + x.gpa.free(x.prompt[j]); + } + } +}; + +/// Equal logits rows, or the first differing logit and how many differ. +fn same(comptime what: []const u8, args: anytype, got: []const u8, want: []const u8) bool { + if (std.mem.eql(u8, got, want)) return true; + const g = std.mem.bytesAsSlice(u16, got); + const w = std.mem.bytesAsSlice(u16, want); + var diff: usize = 0; + var first: usize = g.len; + for (g, w, 0..) |a, b, i| if (a != b) { + diff += 1; + first = @min(first, i); + }; + std.debug.print(" DIFF ", .{}); + std.debug.print(what, args); + std.debug.print(": {d} of {d} logits differ, first {d}: {x:0>4} for {x:0>4}\n", .{ diff, g.len, first, g[first], w[first] }); + return false; +} + +/// A prompt into `slot` from 0 in chunks of up to 2,048 rows, its last row through the head. +fn prefill(m: *const fwd.Model, slot: usize, ids: []const u32) !fwd.Seq { + var seq: fwd.Seq = .{ .slot = slot }; + while (seq.len < ids.len) { + const end = @min(ids.len, seq.len + fwd.prompt_rows); + const at = seq.len; + try m.forward(&seq, ids[at..end], .prompt); + if (end == ids.len) try m.head(end - at - 1); + } + return seq; +} + +/// One-row steps of stream j in its reference slot j: the logits each round must give. +fn reference(m: *fwd.Model, x: *Streams, j: usize, logits: []u8) !usize { + const ids = x.ids[j]; + const n = specs[j].prompt; + var seq = try prefill(m, j, ids[0..n]); + try m.download(m.b.logits, x.prompt[j]); + var fails: usize = 0; + for (x.want[j], n..) |want, p| { + try m.forward(&seq, ids[p..][0..1], .decode); + try m.head(0); + try m.download(m.b.logits, want); + if (p != n and p != n + 5) continue; + // the same row again on four-warp tree blocks (sms 0): its keys are rewritten with the same bits + const sms = m.gd.tree.sms; + m.gd.tree.sms = 0; + seq.len -= 1; + try m.forward(&seq, ids[p..][0..1], .decode); + try m.head(0); + try m.download(m.b.logits, logits); + m.gd.tree.sms = sms; + if (same("tree one-warp vs four-warp, stream {s} at {d}", .{ specs[j].name, p }, logits, want)) { + check.pass("ripple-forward tree one-warp == four-warp blocks: stream {s} at {d} ({d} key groups)", .{ specs[j].name, p, rc.attn.groupsOf(&.{p}) }); + } else { + std.debug.print("FAIL ripple-forward tree one-warp != four-warp blocks: stream {s} at {d}\n", .{ specs[j].name, p }); + fails += 1; + } + } + return fails; +} + +/// The driver's free device bytes (GB10: of its unified memory) after the stream's work. +fn freeBytes(m: *const fwd.Model) !usize { + try m.s.synchronize(); + var free: usize = 0; + var total: usize = 0; + try m.d.check(m.d.api.cuMemGetInfo_v2(&free, &total), "cuMemGetInfo"); + return free; +} + +/// The last round's rows' logits by rowLogits into `out`. +fn roundRows(m: *const fwd.Model, n: usize, out: []u8) !void { + try m.rowLogits(n); + try m.download(m.b.rows, out[0 .. n * m.c.vocab * 2]); +} + +/// Each of n rows of `got` the same as `want`'s. +fn sameRows(what: []const u8, n: usize, v: usize, got: []const u8, want: []const u8) bool { + var ok = true; + for (0..n) |r| ok = same("{s} row {d}", .{ what, r }, got[r * v ..][0..v], want[r * v ..][0..v]) and ok; + return ok; +} + +/// A round from its graph into `got`, then eager over the same caches into `want`; true when every row's logits match. +fn graphVsEager(m: *const fwd.Model, what: []const u8, chains: []const fwd.Chain, ids: []const u32, got: []u8, want: []u8) !bool { + try m.roundAs(chains, ids, .graph); + try roundRows(m, ids.len, got); + try m.roundAs(chains, ids, .exact); + try roundRows(m, ids.len, want); + return sameRows(what, ids.len, m.c.vocab * 2, got, want); +} + +/// Rounds over the test slots against the references, by rowLogits and by head: a graph, fixed eager, then B1's eager. +fn runRounds(m: *const fwd.Model, x: *Streams, base: usize, done: *[specs.len]usize, logits: []u8, rows: []u8, by_graph: []u8, by_fixed: []u8) !usize { + const v = m.c.vocab; + var fails: usize = 0; + var chains: [specs.len]fwd.Chain = undefined; + var ids: [round_rows]u32 = undefined; + var who: [round_rows][2]usize = undefined; // (stream, decode token) a row + var pos: [round_rows]usize = undefined; + for (rounds, 0..) |rd, ri| { + var n: usize = 0; + for (rd, 0..) |c, ci| { + const j = c[0]; + const p0 = specs[j].prompt + done[j]; + chains[ci] = .{ .slot = base + j, .p0 = p0, .tokens = c[1] }; + for (0..c[1]) |i| { + ids[n] = x.ids[j][p0 + i]; + who[n] = .{ j, done[j] + i }; + pos[n] = p0 + i; + n += 1; + } + done[j] += c[1]; + } + const ch = chains[0..rd.len]; + const free0 = try freeBytes(m); + try m.roundAs(ch, ids[0..n], .graph); + try roundRows(m, n, by_graph); + const graph_mib = (@as(f64, @floatFromInt(free0)) - @as(f64, @floatFromInt(try freeBytes(m)))) / (1 << 20); + std.debug.print("INFO ripple-forward graph of {d} rows: {d:.1} MiB of device memory (the driver's free bytes before and after its capture), {d} graphs\n", .{ n, graph_mib, m.captured() }); + try m.roundAs(ch, ids[0..n], .fixed); + try roundRows(m, n, by_fixed); + try m.roundAs(ch, ids[0..n], .exact); + try roundRows(m, n, rows); + var bad: usize = 0; + for (0..n) |r| { + const want = x.want[who[r][0]][who[r][1]]; + const name = specs[who[r][0]].name; + if (!same("round {d} row {d} (stream {s} at {d}) by rowLogits", .{ ri, r, name, pos[r] }, rows[r * v * 2 ..][0 .. v * 2], want)) bad += 1; + try m.head(r); + try m.download(m.b.logits, logits); + if (!same("round {d} row {d} (stream {s} at {d}) by head", .{ ri, r, name, pos[r] }, logits, want)) bad += 1; + } + const ng = rc.attn.groupsOf(pos[0..n]); + const path = if (rc.attn.oneWarp(&m.gd, n, ng)) "one-warp" else "four-warp"; + if (bad == 0) { + check.pass("ripple-forward round {d}: {d} chains, {d} rows ({s} tree blocks, {d} key groups) == one-row steps", .{ ri, rd.len, n, path, ng }); + } else { + std.debug.print("FAIL ripple-forward round {d}: {d} chains, {d} rows ({s} tree blocks, {d} key groups): {d} row comparisons differ\n", .{ ri, rd.len, n, path, ng, bad }); + fails += 1; + } + const fixed = m.gd.groups(); + const fixed_path = if (rc.attn.oneWarp(&m.gd, n, fixed)) "one-warp" else "four-warp"; + if (sameRows("fixed key groups", n, v * 2, by_fixed, rows)) { + check.pass("ripple-forward fixed key groups, round {d}: {d} groups ({s}) == the round's own {d} ({s}), eager", .{ ri, fixed, fixed_path, ng, path }); + } else { + std.debug.print("FAIL ripple-forward fixed key groups, round {d}: {d} groups ({s}) != the round's own {d} ({s})\n", .{ ri, fixed, fixed_path, ng, path }); + fails += 1; + } + if (sameRows("graph", n, v * 2, by_graph, rows)) { + check.pass("ripple-forward graph, round {d}: {d} rows replayed from a graph == the eager round", .{ ri, n }); + } else { + std.debug.print("FAIL ripple-forward graph, round {d}: {d} rows from a graph != the eager round\n", .{ ri, n }); + fails += 1; + } + } + return fails; +} + +/// A replayed round: (slot, p0, rows) a chain. +const Replay = struct { what: []const u8, chains: []const [3]usize }; + +/// Graphs captured by the rounds above, replayed at other positions and slots (each against eager). +const elsewhere = [_]Replay{ + .{ .what = "the 5-row graph (five one-row chains) as one window in slot 1 at 3,070 (the ring's wrap, a page edge)", .chains = &.{.{ 1, 3070, 5 }} }, + .{ .what = "the 8-row graph (one window) as four 2-row chains: page edges at 512 and 1,024, 4,096 keys, the reused slot", .chains = &.{ .{ 0, 511, 2 }, .{ 2, 1023, 2 }, .{ 4, 4095, 2 }, .{ 6, 52, 2 } } }, + .{ .what = "the one-row graph in slot 8 at 54", .chains = &.{.{ 8, 54, 1 }} }, + .{ .what = "the 4-row graph (two chains) as one window over 4,096 keys of a wrapped ring", .chains = &.{.{ 9, 4094, 4 }} }, + .{ .what = "the 20-row graph (four chains) as one window in slot 4 at 3,060 (the ring's wrap, a page edge)", .chains = &.{.{ 4, 3060, 20 }} }, +}; + +/// Graphs of several row counts replayed in another order than their captures (5, 8, 20, 48, 4, 17, 1). +const any_order = [_]Replay{ + .{ .what = "48 rows", .chains = &.{ .{ 5, 3040, 24 }, .{ 7, 1000, 24 } } }, + .{ .what = "1 row", .chains = &.{.{ 3, 53, 1 }} }, + .{ .what = "17 rows", .chains = &.{.{ 9, 4080, 17 }} }, + .{ .what = "4 rows", .chains = &.{ .{ 0, 500, 1 }, .{ 1, 3080, 3 } } }, + .{ .what = "1 row again", .chains = &.{.{ 2, 1030, 1 }} }, + .{ .what = "8 rows", .chains = &.{.{ 8, 40, 8 }} }, +}; + +/// A replay's chains and `toks`' first rows as its ids; true when the graph's rows equal eager's. +fn replay(m: *const fwd.Model, r: Replay, toks: []const u32, got: []u8, want: []u8) !bool { + var chains: [specs.len]fwd.Chain = undefined; + var n: usize = 0; + for (r.chains, 0..) |c, i| { + chains[i] = .{ .slot = c[0], .p0 = c[1], .tokens = c[2] }; + n += c[2]; + } + return graphVsEager(m, r.what, chains[0..r.chains.len], toks[0..n], got, want); +} + +pub fn run(gpu: check.Gpu) !void { + const a = gpu.gpa; + const c = config(); + try wts.gate(&c); + var s = try cuda.Stream.init(gpu.d, false); + defer s.deinit(); + var w = try build(gpu, c, 0x7269_7070); + defer w.deinit(); + var k = try fwd.Kernels.load(gpu.ctx); + defer k.deinit(); + // slots 0-4 the references', 5-9 the rounds' + var m = try fwd.Model.init(a, gpu.d, s, &w, &k, c.context, 2 * specs.len, round_rows); + defer m.deinit(); + var x = try Streams.init(a, c.vocab, 0x6677); + defer x.deinit(); + const logits = try a.alloc(u8, c.vocab * 2); + defer a.free(logits); + const rows = try a.alloc(u8, round_rows * c.vocab * 2); + defer a.free(rows); + const by_graph = try a.alloc(u8, round_rows * c.vocab * 2); + defer a.free(by_graph); + const by_fixed = try a.alloc(u8, round_rows * c.vocab * 2); + defer a.free(by_fixed); + var fails: usize = 0; + + // the references and B1's checks: eager one-row steps and rounds (graphs only where a check names them) + m.graphs = false; + for (0..specs.len) |j| fails += try reference(&m, &x, j, logits); + + // 1. a prompt chunk in another slot: the same bits + const base = specs.len; + var prompts: usize = 0; + for (specs, 0..) |sp, j| { + _ = try prefill(&m, base + j, x.ids[j][0..sp.prompt]); + try m.download(m.b.logits, logits); + if (!same("prompt of stream {s} in slot {d}", .{ sp.name, base + j }, logits, x.prompt[j])) { + std.debug.print("FAIL ripple-forward prompt of stream {s}: slot {d} != slot {d}\n", .{ sp.name, base + j, j }); + prompts += 1; + } + } + if (prompts == 0) check.pass("ripple-forward prompts: {d} streams' last rows the same in their test slots", .{specs.len}); + fails += prompts; + + // 2. rounds of several streams, verify windows and mixes + var done: [specs.len]usize = @splat(0); + fails += try runRounds(&m, &x, base, &done, logits, rows, by_graph, by_fixed); + + // 3. a slot reused after reset: B's (a wrapped ring, 7 pages) takes D, all its decode rows one verify window + const slot = base + 1; + try m.reset(slot, specs[1].prompt + decodeTokens(1)); + const d = 3; + const n = specs[d].prompt; + const t = decodeTokens(d); + _ = try prefill(&m, slot, x.ids[d][0..n]); + try m.download(m.b.logits, logits); + var bad: usize = @intFromBool(!same("reused slot's prompt", .{}, logits, x.prompt[d])); + // the window from a graph first, then B1's eager window into `rows` + const window_by_graph = try graphVsEager(&m, "reused slot window", &.{.{ .slot = slot, .p0 = n, .tokens = t }}, x.ids[d][n..][0..t], by_graph, rows); + for (0..t) |r| { + if (!same("reused slot row {d}", .{r}, rows[r * c.vocab * 2 ..][0 .. c.vocab * 2], x.want[d][r])) bad += 1; + } + if (bad == 0) { + check.pass("ripple-forward reused slot: stream D after B's reset, prompt and a {d}-row window == one-row steps", .{t}); + } else { + std.debug.print("FAIL ripple-forward reused slot: {d} rows differ\n", .{bad}); + fails += 1; + } + if (window_by_graph) { + check.pass("ripple-forward graph, reused slot: a {d}-row window replayed from a graph == the eager window", .{t}); + } else { + std.debug.print("FAIL ripple-forward graph, reused slot: a {d}-row window from a graph != the eager window\n", .{t}); + fails += 1; + } + + // 4. the one-row graph (the CLI's decode) by `forward`: captured once, replayed across the wrap and a page edge + const reused = base; + try m.reset(reused, specs[0].prompt + decodeTokens(0)); + var seq = try prefill(&m, reused, x.ids[1][0..specs[1].prompt]); + try m.download(m.b.logits, logits); + var steps: usize = @intFromBool(!same("B's prompt in slot {d}", .{reused}, logits, x.prompt[1])); + m.graphs = true; + const first = seq.len; + for (x.want[1], first..) |want, p| { + try m.forward(&seq, x.ids[1][p..][0..1], .decode); + try m.head(0); + try m.download(m.b.logits, logits); + if (!same("one-row graph step at {d}", .{p}, logits, want)) steps += 1; + } + m.graphs = false; + if (steps == 0) { + check.pass("ripple-forward one-row graph: captured in slot {d} at {d}, replayed to {d} (the ring's wrap, a page edge) == one-row eager steps", .{ reused, first, seq.len - 1 }); + } else { + std.debug.print("FAIL ripple-forward one-row graph: {d} of {d} steps differ from one-row eager steps\n", .{ steps, x.want[1].len }); + fails += 1; + } + + // 5. graphs captured above, replayed at other positions and slots + var toks: [round_rows]u32 = undefined; + var prng = std.Random.DefaultPrng.init(0x6772_6170); + for (&toks) |*tk| tk.* = prng.random().uintLessThan(u32, @intCast(c.vocab)); + for (elsewhere) |r| { + if (try replay(&m, r, &toks, by_graph, rows)) { + check.pass("ripple-forward graph elsewhere: {s} == eager", .{r.what}); + } else { + std.debug.print("FAIL ripple-forward graph elsewhere: {s} != eager\n", .{r.what}); + fails += 1; + } + } + + // 6. graphs of several row counts coexist: replayed in another order, none captured again + const graphs = m.captured(); + var order: usize = 0; + for (any_order) |r| order += @intFromBool(!try replay(&m, r, &toks, by_graph, rows)); + if (order == 0 and m.captured() == graphs) { + check.pass("ripple-forward graphs coexist: {d} row counts' graphs, replayed as 48, 1, 17, 4, 1 and 8 rows == eager, none captured again", .{graphs}); + } else { + std.debug.print("FAIL ripple-forward graphs coexist: {d} of {d} replays differ, {d} graphs before and {d} after\n", .{ order, any_order.len, graphs, m.captured() }); + fails += 1; + } + try check.expect(fails == 0, "ripple-forward: {d} checks differ", .{fails}); +} diff --git a/zig/tests/cuda/ripple_serve_tests.zig b/zig/tests/cuda/ripple_serve_tests.zig new file mode 100644 index 00000000000..55014f9f94b --- /dev/null +++ b/zig/tests/cuda/ripple_serve_tests.zig @@ -0,0 +1,484 @@ +//! Ripple served through its lane backend, bit for bit (ripple-serve): shared rounds, drafts, kept states, logprobs. +const std = @import("std"); +const cuda = @import("cuda"); +const lanes = @import("lanes"); +const rc = @import("ricursive_cuda"); +const check = @import("check.zig"); + +const fwd = rc.model; +const wts = rc.weights; +const be = rc.backend; +const snap = be.snap; +const Stream = lanes.Stream; +const Backend = lanes.backend.Backend; +const Window = lanes.backend.Window; +const Verified = lanes.backend.Verified; +const LogRow = lanes.LogprobRow; + +const fixture = @import("ripple_forward_tests.zig"); // the release-width weights on 10 layers + +const Spec = struct { name: []const u8, prompt: usize }; + +const specs = [_]Spec{ + .{ .name = "D", .prompt = 37 }, + .{ .name = "A", .prompt = 507 }, // decode rows across the 512-row page edge + .{ .name = "E", .prompt = 4093 }, // a wrapped ring; decode rows across 4,096 keys + .{ .name = "C", .prompt = 1019 }, // kept states at 510 and 514, about the first page edge +}; +const D = 0; +const A = 1; +const E = 2; +const C = 3; +/// The three streams decoding together (checks 1 and 2). +const shared = [_]usize{ D, A, E }; + +/// Draws a stream makes: the first (the prompt's last row), then one a round. +const steps = 8; +const max_new = 64; +const slots = 4; + +/// Each draw of a stream (the token at prompt length + i) and the bf16 logits it was drawn from. +const Trace = struct { + tokens: [steps]u32 = undefined, + logits: [steps][]u8 = undefined, + + fn init(gpa: std.mem.Allocator, vocab: usize) !Trace { + var t: Trace = .{}; + var made: usize = 0; + errdefer for (t.logits[0..made]) |l| gpa.free(l); + for (&t.logits) |*l| { + l.* = try gpa.alloc(u8, vocab * 2); + made += 1; + } + return t; + } + + fn deinit(t: *Trace, gpa: std.mem.Allocator) void { + for (t.logits) |l| gpa.free(l); + } +}; + +/// Draws and logits equal from step `from` on, or the first difference printed. +fn sameTrace(comptime what: []const u8, args: anytype, got: *const Trace, want: *const Trace, from: usize) bool { + for (from..steps) |i| { + if (got.tokens[i] == want.tokens[i] and std.mem.eql(u8, got.logits[i], want.logits[i])) continue; + const g = std.mem.bytesAsSlice(u16, got.logits[i]); + const w = std.mem.bytesAsSlice(u16, want.logits[i]); + var diff: usize = 0; + for (g, w) |a, b| diff += @intFromBool(a != b); + std.debug.print(" DIFF ", .{}); + std.debug.print(what, args); + std.debug.print(": step {d}: token {d} for {d}, {d} of {d} logits differ\n", .{ i, got.tokens[i], want.tokens[i], diff, g.len }); + return false; + } + return true; +} + +const Rig = struct { + gpa: std.mem.Allocator, + m: *fwd.Model, + x: *be.Ripple, + b: Backend, + + fn stream(r: Rig, id: []const u8, p: []const u32, sampling: ?lanes.Sampling) !Stream { + return Stream.init(r.gpa, .{ .id = id, .prompt = p, .max_new = max_new, .sampling = sampling, .drafts = false }); + } + + /// The prompt pass; the slot the stream took. + fn open(r: Rig, s: *Stream) !usize { + try r.b.prefill(s); + return r.x.lanes.getPtr(s).?.slot; + } + + /// The first draw and its logits (the prompt's last row, kept in the stream's slot). + fn first(r: Rig, s: *Stream, t: *Trace) !u32 { + const tok = try r.b.read(try r.b.first(s, s.prompt().len)); + t.tokens[0] = tok; + try r.m.download(r.x.lanes.getPtr(s).?.last, t.logits[0]); + return tok; + } + + /// One-row rounds by queue from step `from` (fed `tok`, the draw before it), each draw and its logits into `t`. + fn decode(r: Rig, s: *Stream, t: *Trace, from: usize, tok0: u32) !void { + var tok = tok0; + for (from..steps) |i| { + tok = try r.b.read(try r.b.queue(s, .{ .value = tok }, s.prompt().len + i)); + t.tokens[i] = tok; + try r.m.download(r.m.b.rows, t.logits[i]); + } + } + + /// Stream `s` alone from its prompt (or its kept state); the slot it took. + fn alone(r: Rig, s: *Stream, t: *Trace) !usize { + const slot = try r.open(s); + defer r.b.release(s); + try r.decode(s, t, 1, try r.first(s, t)); + return slot; + } + + /// Streams `ss` together: their prompt passes, first draws, then one-row windows by verify and keep (no drafts). + fn together(r: Rig, ss: []const *Stream, ts: []Trace) !void { + const v2 = r.m.c.vocab * 2; + var opened: usize = 0; + defer for (ss[0..opened]) |s| r.b.release(s); + for (ss) |s| { + _ = try r.open(s); + opened += 1; + } + var pending: [shared.len]u32 = undefined; + for (ss, ts, 0..) |s, *t, j| pending[j] = try r.first(s, t); + var windows: [shared.len]Window = undefined; + var out: [shared.len]Verified = undefined; + var pos: [shared.len][1]u64 = undefined; + var sampled: [shared.len][1]u32 = undefined; + var drafts: [shared.len][1]u32 = undefined; + const row0 = [_]u32{0}; + const paths: [shared.len][]const u32 = @splat(&row0); + const n = ss.len; + for (1..steps) |i| { + for (ss, 0..) |s, j| { + pos[j] = .{s.prompt().len + i}; + windows[j] = .{ .stream = s, .pending = pending[j], .held = 0, .tokens = &.{}, .parents = null, .positions = &pos[j] }; + out[j] = .{ .sampled = &sampled[j], .drafts = drafts[j][0..0] }; + } + try r.b.verify(windows[0..n], out[0..n]); + for (ts[0..n], 0..) |*t, j| { + try r.m.download(r.m.b.rows + j * v2, t.logits[i]); + t.tokens[i] = sampled[j][0]; + pending[j] = sampled[j][0]; + } + try r.b.keep(windows[0..n], paths[0..n]); + } + } +}; + +/// Check 1 and 2: three streams together == each alone (`sp` null: greedy), their slots 0 to 2 against slot 0 alone. +fn sharedRounds(r: Rig, prompts: []const []u32, alone: []const Trace, sp: ?lanes.Sampling, label: []const u8) !usize { + var ss: [shared.len]Stream = undefined; + var made: usize = 0; + defer for (ss[0..made]) |*s| s.deinit(r.gpa); + var ptrs: [shared.len]*Stream = undefined; + for (shared, &ss, &ptrs) |j, *s, *p| { + var each = sp; + if (each) |*q| q.seed +%= j; + s.* = try r.stream(specs[j].name, prompts[j], each); + made += 1; + p.* = s; + } + var ts: [shared.len]Trace = undefined; + var traced: usize = 0; + defer for (ts[0..traced]) |*t| t.deinit(r.gpa); + for (&ts) |*t| { + t.* = try Trace.init(r.gpa, r.m.c.vocab); + traced += 1; + } + try r.together(&ptrs, &ts); + var bad: usize = 0; + for (shared, &ts) |j, *t| { + if (!sameTrace("{s} stream {s} together vs alone", .{ label, specs[j].name }, t, &alone[j], 0)) bad += 1; + } + if (bad == 0) { + check.pass("ripple-serve {s} shared rounds: streams D, A, E ({d}, {d}, {d} prompt tokens) together == each alone, {d} draws and their logits each", .{ label, specs[D].prompt, specs[A].prompt, specs[E].prompt, steps }); + return 0; + } + std.debug.print("FAIL ripple-serve {s} shared rounds: {d} of {d} streams differ from alone\n", .{ label, bad, shared.len }); + return 1; +} + +/// Check 3: a 7-row window of copied drafts with a wrong fourth keeps 4 rows; draws then == plain decode. +fn copiedDrafts(r: Rig, p: []const u32, plain: *const Trace) !usize { + const v = r.m.c.vocab; + var s = try r.stream("copied", p, null); + defer s.deinit(r.gpa); + var t = try Trace.init(r.gpa, v); + defer t.deinit(r.gpa); + _ = try r.open(&s); + defer r.b.release(&s); + const n = p.len; + const t0 = try r.first(&s, &t); + const wrong = 4; // the draft for prompt length + 4 + var drafts: [6]u32 = undefined; + for (&drafts, 1..) |*d, i| d.* = plain.tokens[i]; + drafts[wrong - 1] = @intCast((plain.tokens[wrong] + 1) % v); + var pos: [7]u64 = undefined; + for (&pos, 1..) |*q, i| q.* = n + i; + var sampled: [7]u32 = undefined; + var dr: [6]u32 = undefined; + const w: Window = .{ .stream = &s, .pending = t0, .held = 0, .tokens = &drafts, .parents = null, .positions = &pos }; + var out = [_]Verified{.{ .sampled = &sampled, .drafts = &dr }}; + try r.b.verify(&.{w}, &out); + // rows 0 to 3 read plain tokens: their draws are plain steps 1 to 4; row 3's is the bonus past the wrong draft + for (0..wrong) |row| { + t.tokens[row + 1] = sampled[row]; + try r.m.download(r.m.b.rows + row * v * 2, t.logits[row + 1]); + } + const kept = [_]u32{ 0, 1, 2, 3 }; + try r.b.keep(&.{w}, &.{&kept}); + try r.decode(&s, &t, wrong + 1, sampled[wrong - 1]); + const ok = std.mem.eql(u32, &dr, &drafts) and sameTrace("copied drafts", .{}, &t, plain, 0); + if (ok) { + check.pass("ripple-serve copied drafts: stream A, a 7-row window (positions {d} to {d}) with a wrong 4th draft keeps 4 rows; draws and logits == plain decode, and the next 3 steps too", .{ n + 1, n + 7 }); + return 0; + } + std.debug.print("FAIL ripple-serve copied drafts: stream A's window or the steps after it differ from plain decode\n", .{}); + return 1; +} + +/// The prompt cache's hook: a state at each mark the pass stands at. +const Keep = struct { + x: *be.Ripple, + saved: [2]?*snap.Saved = .{ null, null }, + n: usize = 0, + + fn hook(ptr: *anyopaque, s: *Stream, at: u32) void { + const k: *Keep = @ptrCast(@alignCast(ptr)); + if (k.n == k.saved.len) return; + k.saved[k.n] = k.x.saveState(s, at) catch |e| blk: { + std.debug.print(" saveState at {d}: {s}\n", .{ at, @errorName(e) }); + break :blk null; + }; + k.n += 1; + } +}; + +/// Check 4: states kept at `ats`, each restored into another slot and continued == the uninterrupted `plain`. +fn keptStates(r: Rig, name: []const u8, p: []const u32, ats: []const u32, notes: []const []const u8, plain: *const Trace) !usize { + var keep: Keep = .{ .x = r.x }; + var saver = try Stream.init(r.gpa, .{ .id = "saver", .prompt = p, .max_new = max_new, .drafts = false, .reuse = .{ .marks = ats, .hook = .{ .ptr = &keep, .at = Keep.hook } } }); + defer saver.deinit(r.gpa); + const from = try r.open(&saver); + defer r.b.release(&saver); // held while the restores run, so each lands in another slot + defer for (keep.saved[0..keep.n]) |k| if (k) |saved| r.x.dropState(saved); + var bad: usize = 0; + for (ats, notes, 0..) |at, note, i| { + const saved = (if (i < keep.n) keep.saved[i] else null) orelse { + std.debug.print("FAIL ripple-serve kept state at {d} of stream {s}: none kept\n", .{ at, name }); + bad += 1; + continue; + }; + var s = try Stream.init(r.gpa, .{ .id = "restored", .prompt = p, .max_new = max_new, .drafts = false, .reuse = .{ .saved = saved, .at = at } }); + defer s.deinit(r.gpa); + var t = try Trace.init(r.gpa, r.m.c.vocab); + defer t.deinit(r.gpa); + const into = try r.alone(&s, &t); + const ok = !s.reuse_failed and s.cached == at and into != from and sameTrace("state at {d}", .{at}, &t, plain, 0); + if (ok) { + check.pass("ripple-serve kept state at {d} of stream {s} ({s}, {d:.1} MiB): saved from slot {d}, restored into slot {d}, {d} more prompt rows and {d} draws == uninterrupted", .{ at, name, note, @as(f64, @floatFromInt(snap.bytes(r.m.c, at))) / (1 << 20), from, into, p.len - at, steps }); + } else { + std.debug.print("FAIL ripple-serve kept state at {d} of stream {s}: reuse_failed {s}, cached {d}, slots {d} -> {d}, or draws differ\n", .{ at, name, if (s.reuse_failed) "yes" else "no", s.cached, from, into }); + bad += 1; + } + } + return bad; +} + +/// The Nemotron CUDA logprobs' bound against a float64 log-softmax of the same logits (CHANGELOG, #572). +const tol: f64 = 2e-6; + +/// A float64 log-softmax of one bf16 logits row. +const Host = struct { + vals: []align(1) const u16, + lse: f64, + + fn init(row: []const u8) Host { + var h: Host = .{ .vals = std.mem.bytesAsSlice(u16, row), .lse = 0 }; + var most = -std.math.inf(f64); + for (0..h.vals.len) |i| most = @max(most, h.at(i)); + var sum: f64 = 0; + for (0..h.vals.len) |i| sum += @exp(h.at(i) - most); + h.lse = most + @log(sum); + return h; + } + + fn at(h: Host, i: usize) f64 { + const f: f32 = @bitCast(@as(u32, h.vals[i]) << 16); + return f; + } + + fn lp(h: Host, i: usize) f64 { + return h.at(i) - h.lse; + } + + /// The best ids, logit descending, ties by the lower id. + fn best(h: Host, out: []u32) void { + var n: usize = 0; + for (0..h.vals.len) |i| { + const v = h.at(i); + var j = n; + while (j > 0 and h.at(out[j - 1]) < v) j -= 1; + if (j == out.len) continue; + var q = @min(n, out.len - 1); + while (q > j) : (q -= 1) out[q] = out[q - 1]; + out[j] = @intCast(i); + n = @min(n + 1, out.len); + } + } + + /// vLLM's rank: the ids whose logit is at or above the pick's, itself included. + fn rank(h: Host, pick: u32) u32 { + var n: u32 = 0; + for (0..h.vals.len) |i| n += @intFromBool(h.at(i) >= h.at(pick)); + return n; + } +}; + +/// A backend row against the host's: the pick, its best ids exactly, their log probabilities within `tol`. +fn rowMatches(h: Host, row: LogRow, pick: u32, k: u8, ranked: bool, worst: *f64) bool { + var ok = row.token == pick and row.count == k; + const e0 = @abs(@as(f64, row.logprob) - h.lp(pick)); + worst.* = @max(worst.*, e0); + ok = ok and e0 <= tol; + var ids: [lanes.logprob.max_top]u32 = undefined; + h.best(ids[0..k]); + for (0..k) |i| { + const e = @abs(@as(f64, row.logprobs[i]) - h.lp(ids[i])); + worst.* = @max(worst.*, e); + ok = ok and row.ids[i] == ids[i] and e <= tol; + } + if (ranked) ok = ok and row.rank == h.rank(pick); + return ok; +} + +fn verdict(ok: bool, comptime what: []const u8, args: anytype, worst: f64) usize { + std.debug.print("{s} ripple-serve logprob rows: ", .{if (ok) "PASS" else "FAIL"}); + std.debug.print(what, args); + if (ok) { + std.debug.print(" == a float64 log-softmax (ids exact, worst {e:.2} <= {e:.0})\n", .{ worst, tol }); + return 0; + } + std.debug.print(" differ from a float64 log-softmax (worst {e:.2}, bound {e:.0})\n", .{ worst, tol }); + return 1; +} + +/// Check 5: the first draw's row and a verify window's rows (20 best), and prompt rows with ranks (5 best). +fn logprobRows(r: Rig, pa: []const u32, plain: *const Trace, pe: []const u32) !usize { + const v = r.m.c.vocab; + const row_bytes = v * 2; + const k: u8 = lanes.logprob.max_top; + var bad: usize = 0; + const buf = try r.gpa.alloc(u8, fwd.head_rows * row_bytes); + defer r.gpa.free(buf); + { + var s = try Stream.init(r.gpa, .{ .id = "logprobs", .prompt = pa, .max_new = max_new, .drafts = false, .logprobs = k }); + defer s.deinit(r.gpa); + var t = try Trace.init(r.gpa, v); + defer t.deinit(r.gpa); + _ = try r.open(&s); + defer r.b.release(&s); + const t0 = try r.first(&s, &t); + var worst: f64 = 0; + const row = try r.b.firstRow(&s); + bad += verdict(rowMatches(Host.init(t.logits[0]), row, t0, k, false, &worst), "the first draw's row (stream A, {d} best)", .{k}, worst); + + // a 4-row window of plain drafts, every row scored + const n = pa.len; + const drafts = plain.tokens[1..4]; + var pos: [4]u64 = undefined; + for (&pos, 1..) |*q, i| q.* = n + i; + var sampled: [4]u32 = undefined; + var dr: [3]u32 = undefined; + var rows: [4]LogRow = undefined; + const w: Window = .{ .stream = &s, .pending = t0, .held = 0, .tokens = drafts, .parents = null, .positions = &pos }; + var out = [_]Verified{.{ .sampled = &sampled, .drafts = &dr, .rows = &rows }}; + try r.b.verify(&.{w}, &out); + try r.m.download(r.m.b.rows, buf[0 .. 4 * row_bytes]); + worst = 0; + var ok = true; + for (rows, sampled, 0..) |lr, pick, i| ok = rowMatches(Host.init(buf[i * row_bytes ..][0..row_bytes]), lr, pick, k, false, &worst) and ok; + bad += verdict(ok, "a 4-row verify window's rows (stream A at {d} to {d}, {d} best)", .{ n + 1, n + 4, k }, worst); + } + { + // prompt rows: the reference logits from the same prompt in a slot no stream holds, head_rows at a time + const kp: u8 = 5; + const slot = slots - 1; + const scored = pe.len - 1; + const want = try r.gpa.alloc(u8, scored * row_bytes); + defer r.gpa.free(want); + try r.m.prompt(slot, 0, pe); + var r0: usize = 0; + while (r0 < scored) : (r0 += fwd.head_rows) { + const rows = @min(fwd.head_rows, scored - r0); + try r.m.headRows(r0, rows); + try r.m.download(r.m.b.rows, want[r0 * row_bytes ..][0 .. rows * row_bytes]); + } + try r.m.reset(slot, pe.len); + var s = try Stream.init(r.gpa, .{ .id = "prompt-logprobs", .prompt = pe, .max_new = max_new, .drafts = false, .prompt_logprobs = kp }); + defer s.deinit(r.gpa); + try r.b.prefill(&s); + r.b.release(&s); + var worst: f64 = 0; + var ok = s.prompt_rows.items.len == scored; + if (ok) { + for (s.prompt_rows.items, 0..) |lr, i| ok = rowMatches(Host.init(want[i * row_bytes ..][0..row_bytes]), lr, pe[i + 1], kp, true, &worst) and ok; + } + bad += verdict(ok, "{d} prompt rows with ranks ({d} best, {d}-row head batches)", .{ scored, kp, fwd.head_rows }, worst); + } + return bad; +} + +pub fn run(gpu: check.Gpu) !void { + const a = gpu.gpa; + const c = fixture.config(); + try wts.gate(&c); + var s = try cuda.Stream.init(gpu.d, false); + defer s.deinit(); + const t0 = check.now(gpu.io); + var w = try fixture.build(gpu, c, 0x7269_7070); + defer w.deinit(); + std.debug.print("ripple-serve: weights built in {d:.1} s\n", .{@as(f64, @floatFromInt(check.now(gpu.io) - t0)) / 1e9}); + var k = try fwd.Kernels.load(gpu.ctx); + defer k.deinit(); + var m = try fwd.Model.init(a, gpu.d, s, &w, &k, c.context, slots, be.round_rows); + defer m.deinit(); + var x = try be.Ripple.init(a, gpu.d, &m); + defer x.deinit(); + const r: Rig = .{ .gpa = a, .m = &m, .x = &x, .b = x.backend() }; + + var prompts: [specs.len][]u32 = undefined; + var made: usize = 0; + defer for (prompts[0..made]) |p| a.free(p); + var prng = std.Random.DefaultPrng.init(0x7365_7276); + for (specs, &prompts) |sp, *p| { + p.* = try a.alloc(u32, sp.prompt); + made += 1; + for (p.*) |*t| t.* = prng.random().uintLessThan(u32, @intCast(c.vocab)); + } + const sampling: lanes.Sampling = .{ .seed = 0x5eed, .temperature = 1.0, .top_p = 0.95, .top_k = 20 }; + + // each stream alone in a fresh slot, greedy (all four) and sampled (the shared three, a seed each) + var greedy: [specs.len]Trace = undefined; + var sampled: [specs.len]Trace = undefined; + var traced: usize = 0; + defer for (greedy[0..traced], sampled[0..traced]) |*g, *q| { + g.deinit(a); + q.deinit(a); + }; + for (&greedy, &sampled) |*g, *q| { + g.* = try Trace.init(a, c.vocab); + q.* = Trace.init(a, c.vocab) catch |e| { + g.deinit(a); + return e; + }; + traced += 1; + } + for (specs, prompts, &greedy, 0..) |sp, p, *g, j| { + var st = try r.stream(sp.name, p, null); + defer st.deinit(a); + _ = try r.alone(&st, g); + if (std.mem.indexOfScalar(usize, &shared, j) == null) continue; + var each = sampling; + each.seed +%= j; + var sq = try r.stream(sp.name, p, each); + defer sq.deinit(a); + _ = try r.alone(&sq, &sampled[j]); + } + + var fails: usize = 0; + fails += try sharedRounds(r, &prompts, &greedy, null, "greedy"); + fails += try sharedRounds(r, &prompts, &sampled, sampling, "sampled (temperature 1, top-p 0.95, top-k 20)"); + fails += try copiedDrafts(r, prompts[A], &greedy[A]); + fails += try keptStates(r, "E", prompts[E], &.{3500}, &.{"past the 3,072-row ring's wrap"}, &greedy[E]); + fails += try keptStates(r, "C", prompts[C], &.{ 510, 514 }, &.{ "two rows before a 512-row page edge", "two rows across a 512-row page edge" }, &greedy[C]); + fails += try logprobRows(r, prompts[A], &greedy[A], prompts[E][0..300]); + try check.expect(fails == 0, "ripple-serve: {d} checks differ", .{fails}); +} diff --git a/zig/tests/cuda/shared_plans.zig b/zig/tests/cuda/shared_plans.zig index 2ead168b7d8..d5e2a7aabba 100644 --- a/zig/tests/cuda/shared_plans.zig +++ b/zig/tests/cuda/shared_plans.zig @@ -40,6 +40,6 @@ pub fn tp2(gpu: check.Gpu, model: []const u8, ids: []const u8) !void { var c = try nemotron.Config.read(gpu.gpa, gpu.io, model); try nemotron.latent.place(&c); if (c.world != 2 or c.latent == 0 or c.bolt) return error.ExpectedLatentTwoRanks; - if (c.rank > 0) return nemotron.worker.serve(gpu.gpa, gpu.io, gpu.ctx, model, null); + if (c.rank > 0) return nemotron.worker.serve(gpu.gpa, gpu.io, gpu.ctx, model, null, null); // its TF_NEMOTRON_* place, read above try @import("prompt_cuts.zig").run(gpu, model, ids); } diff --git a/zig/tests/cuda/wide_rounds_tests.zig b/zig/tests/cuda/wide_rounds_tests.zig new file mode 100644 index 00000000000..09eeb525593 --- /dev/null +++ b/zig/tests/cuda/wide_rounds_tests.zig @@ -0,0 +1,163 @@ +//! TF_NEMOTRON_WIDE_ROUNDS: Lightning's dense calls at 17-32 rows give each row its bytes from 16-row calls. +const std = @import("std"); +const cuda = @import("cuda"); +const check = @import("check.zig"); +const quant_ref = @import("quant_ref_tests.zig"); +const Gpu = check.Gpu; + +const qlinear = cuda.qlinear; +const Rig = quant_ref.RigT; + +/// Lightning's dense projections (n, k): in_proj, out_proj (and o), qkv, MTP eh_proj, draft head, lm_head. +const shapes = [_][2]usize{ .{ 10304, 2688 }, .{ 2688, 4096 }, .{ 4608, 2688 }, .{ 2688, 5376 }, .{ 49152, 2688 }, .{ 131072, 2688 } }; +/// A wide round's rows: the narrow rounds it replaces are 16 rows, then the rest. +const row_counts = [_]usize{ 17, 25, 32 }; + +fn sums(r: *Rig, x: []const u16, rows: usize, k: usize) ![]f32 { + const out = try r.a.alloc(f32, rows * k / 64); + for (0..rows) |row| for (0..k / 64) |g| { + var s: f32 = 0; + for (0..64) |j| s += @floatCast(quant_ref.helpers.bfOf(x[row * k + g * 64 + j])); + out[row * (k / 64) + g] = s; + }; + return out; +} + +/// A weight in each format a wide round takes: MLX affine-4 (packed as served), NVFP4, and ModelOpt's FP8 and bf16. +const W = union(enum) { affine4: qlinear.Affine4, nvfp4: cuda.qmmf.Weight, fp8: cuda.qmmf.Weight, bf16: cuda.qmmf.Weight }; + +fn affine(r: *Rig, a4: *const qlinear.Affine4Kernels, n: usize, k: usize) !W { + const words = try r.a.alloc(u32, n * k / 8); + for (words) |*w| w.* = r.rng.int(u32); + const scales = try r.a.alloc(u16, n * k / 64); + const biases = try r.a.alloc(u16, n * k / 64); + for (scales, biases) |*sv, *bv| { + sv.* = quant_ref.helpers.bf16Of((r.rng.float(f32) * 0.9 + 0.1) * 0.0025); + bv.* = quant_ref.helpers.bf16Of(-(r.rng.float(f32) * 0.4 + 0.8) * 0.02); + } + const lay = qlinear.Affine4.layout(n, k); + const q: qlinear.Affine4 = .{ .w = try r.zeros(lay.words), .s = try r.zeros(lay.scales), .b = try r.zeros(lay.scales), .n = n, .k = k, .npad = lay.npad }; + try a4.pack(r.s, try r.dev(std.mem.sliceAsBytes(words)), try r.dev(std.mem.sliceAsBytes(scales)), try r.dev(std.mem.sliceAsBytes(biases)), q); + return .{ .affine4 = q }; +} + +fn fp4(r: *Rig, n: usize, k: usize) !W { + const npad = (n + 127) / 128 * 128; + const codes = try r.a.alloc(u8, npad * k / 2); + r.rng.bytes(codes); + const scales = try r.a.alloc(u8, npad * k / 16); + for (scales) |*v| v.* = 0x30 + r.rng.uintLessThan(u8, 16); + return .{ .nvfp4 = .{ .mode = .fp4, .codes = try r.dev(codes), .scales = try r.dev(scales), .scale = 1, .n = @intCast(n), .k = @intCast(k), .npad = @intCast(npad) } }; +} + +/// ModelOpt FP8: finite e4m3 codes on the lane's padded rows, one scale. +fn fp8(r: *Rig, n: usize, k: usize) !W { + const codes = try r.a.alloc(u8, cuda.modelopt.padded(n) * k); + for (codes) |*c| c.* = r.rng.uintLessThan(u8, 0x70) | (r.rng.int(u8) & 0x80); + return .{ .fp8 = cuda.modelopt.fp8Weight(try r.dev(codes), 0.75, n, k) }; +} + +/// ModelOpt bf16: small finite values on the lane's padded rows. +fn bf16(r: *Rig, n: usize, k: usize) !W { + const vals = try r.a.alloc(u16, cuda.modelopt.padded(n) * k); + for (vals) |*v| v.* = quant_ref.helpers.bf16Of((r.rng.float(f32) - 0.5) * 0.05); + return .{ .bf16 = cuda.modelopt.bf16Weight(try r.dev(std.mem.sliceAsBytes(vals)), n, k) }; +} + +/// One call of `rows` rows from row `at`, as the engine's dense projection makes it. +fn call(l: qlinear.Linear, r: *Rig, w: W, x: u64, xs: u64, part: u64, out: u64, at: usize, rows: usize) !void { + const k: usize = switch (w) { + inline else => |q| q.k, + }; + const n: usize = switch (w) { + inline else => |q| q.n, + }; + const weight: qlinear.Weight = switch (w) { + .affine4 => |q| .{ .affine4 = q }, + .nvfp4 => |q| .{ .nvfp4 = q }, + .fp8 => |q| .{ .fp8 = q }, + .bf16 => |q| .{ .bf16 = q }, + }; + const ax = x + at * k * 2; + const axs = xs + at * (k / 64) * 4; + // nemotron Ops.dense with the switch on: affine-4 rows past 16 take verify's tiles + if (weight == .affine4 and rows > qlinear.Affine4Kernels.max_rows) return l.affine4.?.verify(r.s, ax, axs, weight.affine4, out + at * n * 2, rows); + try l.decode(r.s, weight, .{ .x = ax, .sums = axs, .part = part }, out + at * n * 2, rows); +} + +pub fn run(gpu: Gpu) !void { + if ((try gpu.ctx.capability()) != 121) { + check.pass("wide-rounds: N/A off GB10 (the switch stays off there: affine-4 has no 32-row verify)", .{}); + return; + } + var arena: std.heap.ArenaAllocator = .init(gpu.gpa); + defer arena.deinit(); + var s = try cuda.Stream.init(gpu.d, false); + defer s.deinit(); + var prng = std.Random.DefaultPrng.init(1050); + var r: Rig = .{ .gpu = gpu, .a = arena.allocator(), .s = s, .rng = prng.random() }; + defer { + for (r.bufs.items) |*b| b.free(); + r.bufs.deinit(gpu.gpa); + } + const kk = cuda.kernels; + const images = [_][]const u8{ kk.qmm_group, kk.qmm_prefill, kk.lane_gemv, kk.affine4_pack }; + var mods: [images.len]cuda.Module = undefined; + var loaded: usize = 0; + defer for (mods[0..loaded]) |*md| md.unload(); + for (images, &mods) |img, *md| { + md.* = try cuda.Module.load(gpu.d, img); + loaded += 1; + } + const sms: usize = @intCast(try gpu.ctx.attribute(.multiprocessor_count)); + var a4 = try qlinear.Affine4Kernels.resolve(gpu.d, mods[0], mods[1], mods[2], mods[3], sms, true); + defer a4.deinit(); + var lane = try cuda.qmmf.Lane.load(gpu.d, 12); + defer lane.unload(); + const l: qlinear.Linear = .{ .affine4 = &a4, .lane = &lane }; + const part = try r.zeros(64 << 20); // slice partials where the lane reduces them + var cells: usize = 0; + for (shapes) |sh| for ([_]std.meta.Tag(W){ .affine4, .nvfp4, .fp8, .bf16 }) |format| { + const mark = r.bufs.items.len; + defer { + for (r.bufs.items[mark..]) |*b| b.free(); + r.bufs.shrinkRetainingCapacity(mark); + } + const n = sh[0]; + const k = sh[1]; + const w = switch (format) { + .affine4 => try affine(&r, &a4, n, k), + .nvfp4 => try fp4(&r, n, k), + .fp8 => try fp8(&r, n, k), + .bf16 => try bf16(&r, n, k), + }; + const x = try r.bfs(32 * k, 1.0); + for ([_]u16{ 0x7FC0, 0x7F80, 0xFF80 }, [_]usize{ 2, 19, 30 }) |special, row| x[row * k + 5] = special; // NaN, +-Inf + const dx = try r.dev(std.mem.sliceAsBytes(x)); + const dxs = try r.dev(std.mem.sliceAsBytes(try sums(&r, x, 32, k))); + for (row_counts) |rows| { + const wide = try r.zeros(rows * n * 2); + const narrow = try r.zeros(rows * n * 2); + try call(l, &r, w, dx, dxs, part, wide, 0, rows); + try call(l, &r, w, dx, dxs, part, narrow, 0, 16); + try call(l, &r, w, dx, dxs, part, narrow, 16, rows - 16); + try check.sameBytes("wide rounds: each format's rows equal their 16-row calls", try r.back(wide, rows * n * 2), try r.back(narrow, rows * n * 2)); + cells += 1; + } + // planted control: row 20's input moved changes row 20 of the wide call and no other row + const before = try r.zeros(32 * n * 2); + try call(l, &r, w, dx, dxs, part, before, 0, 32); + x[20 * k] ^= 0x0040; + const cx = try r.dev(std.mem.sliceAsBytes(x)); + const cxs = try r.dev(std.mem.sliceAsBytes(try sums(&r, x, 32, k))); + const after = try r.zeros(32 * n * 2); + try call(l, &r, w, cx, cxs, part, after, 0, 32); + const b = try r.back(before, 32 * n * 2); + const a = try r.back(after, 32 * n * 2); + try check.expect(!std.mem.eql(u8, b[20 * n * 2 ..][0 .. n * 2], a[20 * n * 2 ..][0 .. n * 2]), "wide rounds: the planted row moves ([{d}, {d}])", .{ n, k }); + try check.sameBytes("wide rounds: rows beside the planted one stay", a[0 .. 20 * n * 2], b[0 .. 20 * n * 2]); + try check.sameBytes("wide rounds: rows after the planted one stay", a[21 * n * 2 ..], b[21 * n * 2 ..]); + x[20 * k] ^= 0x0040; + }; + check.pass("wide-rounds: {d} cells, Lightning's dense shapes in affine-4, NVFP4, FP8 and bf16 at 17/25/32 rows byte-equal to 16 + the rest, NaN/Inf planted, control caught", .{cells}); +} diff --git a/zig/tests/fixtures/gradient-serving.tsv b/zig/tests/fixtures/gradient-serving.tsv index bb44d50c79e..94054526225 100644 --- a/zig/tests/fixtures/gradient-serving.tsv +++ b/zig/tests/fixtures/gradient-serving.tsv @@ -14,7 +14,7 @@ zig/kernels/cuda/flashnext_attn.cu 9731e39b67a8adb4a0a42222e9f888877932f2aa7108b zig/kernels/cuda/flashnext_batch.cu 95260b964fb633d23df28970672d87688f21cdd9073e44f92a1523b54b4ecd99 raw zig/kernels/cuda/flashnext_gdn.cu c7b9712626778d452e18234e2dfc3b26f8112618cdc492957c4b5f5454d64126 raw zig/kernels/cuda/flashnext_hc.cu 54fa2cfa22e483341835f6349cf0a8f508459ed1b65804728cb1358ac82b24f1 raw main 5c7cf5c117, d88c1ed57d (sum_rn and rms_scale shared; same SASS) -zig/kernels/cuda/flashnext_mtp.cu 5d213b1b4a1d0588eea3acb4633a0c8bc4d9bdf6f27485604452a3b603677a09 raw #2927 +zig/kernels/cuda/flashnext_mtp.cu a9c21f52cd00d9aa05e9cf1dae5b0168e5e48f87cb3a4a226221b89037acd6d9 raw #2927, the MTP rows' row best split over 32 blocks a row (fn_row_best_max, fn_row_best_sum), fn_row_best's bits zig/kernels/cuda/fp8_experts.cu 156aa7337b41c67d200d8b58a24422cc96cfa032c9fd0711080f09ddc733baee raw zig/kernels/cuda/gdn.cu e5ef9dcce75c478e59e476d2fa8747baee2317bd283b0756f125ea050dad9228 raw zig/kernels/cuda/glm_glue.cu 74e69a7c20827d498c190334fffaa896f2a4f05e107fdf9d2d34b09b55a1c75c raw #2722 (one added line, the include of glm_index_decode.cuh: the decode select's scan and merge) @@ -41,7 +41,7 @@ zig/kernels/cuda/nemotron_attention.cu a8a6bc39c2620176aff6c5d436b4a93edf5c86c8d zig/kernels/cuda/nemotron_keyed.cu ed8bdd7012970d9896ec703bd7c3d5ec83e02f41dba4ce1f896fc39c1ee349c9 raw zig/kernels/cuda/nemotron_latent.cu 04fba97043d0948f82a3b9477f448dd76b21f6d11d1a445e020bd41cacb85c2b raw commits e40bd6eae, 8a8ff3d64; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate zig/kernels/cuda/nemotron_mamba.cu dcaba12253d3931ae48c7ebd4e13dfb956f540ae19f4ab83130c3f21745be5ec raw commits fa2af585f, f0ef17e69; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate -zig/kernels/cuda/nemotron_ops.cu 2ef87c655b49d33214f8856d2ad775aacf6198ab2ca343f87fde588639ecccd1 raw #3124 +zig/kernels/cuda/nemotron_ops.cu c95b1df56910c879538e471c8b7e53355923802f53ab8e9e7daf99f3502ceec6 raw #3124; TF_NEMOTRON_WIDE_ROUNDS (tf_plan_routed stages 32 rows; gather, last-row and scatter copies take 16 parts; 16 rows or 8 parts unchanged) zig/kernels/cuda/nemotron_route.cu 65da41432442f9fd99f73abefe87f34cf3c46b4971afe3c3557a48bca96f6511 raw commits 739c924de, 8cfdaa739, b77a33b08, 7f6f940eb, 05d0617af, bc76d90d6; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate zig/kernels/cuda/norms.cu 89d3c6cea39fe3e1bf8d5a2fe60465f7ae272548f14711abb59ddac709d2d1db raw main d4541b00e0 (rms_scale shared; same SASS) zig/kernels/cuda/nvfp4_experts.cu dc78d37c1eb1d9a9fff6c1ba9c5f0a9b0eb485a47a56e7b0b2fdbb8bbf1b223b raw #2266 (decode cp.async rings, GB10 SASS unchanged); #4493 (opt-in paired prompt experts, 128-row items) @@ -56,7 +56,7 @@ zig/kernels/cuda/common/router_tiles.cuh aab559bf104e3f47344deaa9ae10622b6962b8a zig/kernels/cuda/common/router_mma.cuh 3aca244a38f2e4b4f28bf74f333f384b1060b764c25b004cef4e6c636e7cc1dd raw zig/kernels/cuda/qmm_group.cu 8780fd710be3ce2f04e53fa1e69eb062809d3bec6391d9bd49983d0588e374d0 raw zig/kernels/cuda/qmm_prefill.cu e3724114b87cae6f6f761b2f86357f05b1693d84a0233e4d58ce46349fa853f6 raw #2825 hoists copy addresses before the K loop; copy order and math match prefill_kernel -zig/kernels/cuda/qmmf.cu ab4cd147437f27fa945193f5213623b76d17424b8b941bf8c314ce7e8fa314eb raw main ec76abd45 (128-row BF16 prompt tile, bytes unchanged), c3acc3466 (K32 staging, bytes unchanged), e32de56c6 (#2721: tf_qmmf_native_fp4_check and the e2m1 pair decode behind -Dnative-fp-decode; default builds byte-identical); dependent decode launches: weights load before griddepcontrol.wait (TF_QMMF_WFIRST), Lane.pdl; TF_FLASHNEXT_FUSED_SPLIT (fused instances at row tiles 16 and 32; off keeps main's kernels) +zig/kernels/cuda/qmmf.cu 94daadde680ffdf24b76c14e5f084ec52566fda71c9da8f529d1514f829b670f raw main ec76abd45 (128-row BF16 prompt tile, bytes unchanged), c3acc3466 (K32 staging, bytes unchanged), e32de56c6 (#2721: tf_qmmf_native_fp4_check and the e2m1 pair decode behind -Dnative-fp-decode; default builds byte-identical); dependent decode launches: weights load before griddepcontrol.wait (TF_QMMF_WFIRST), Lane.pdl; TF_FLASHNEXT_FUSED_SPLIT (fused instances at row tiles 16 and 32; off keeps main's kernels); #4515 (opt-in grouped same-input projections preserving each split-K and K-slice order; device gate unchecked); #4533 TF_QMMF_HALF_BN adds FP4/FP8/FP8G 32-column instances, default off zig/kernels/cuda/qwen_vision.cu eeab10300aae424fd957856e4ddba77a3543e9a86bc61701dd09687d7e3b5ea5 raw zig/kernels/cuda/rank_sum.cu 3781c3a4441cfef903c1d0712240ad4d7ab4aaf2d3fb18b323597bcec3587909 raw zig/kernels/cuda/route_rows.cu a2bf267f360cb57257aaef9765d4dca93f68523338b0881d710bbfcb01917dad raw @@ -93,7 +93,7 @@ zig/src/cuda/experts.zig 0ada89c63783a53d138cdf33b3f3e2f961535e91448c82eeb5ca99a zig/src/cuda/fp8.zig a9caf312cb451dc95572b493e69ae211dd1e8b5be5b2c48cae3febd5d9327143 raw series patches 65-pr-1024.patch; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate zig/src/cuda/graph.zig 17639aaef0298c934b3f5ad3511925169c096ae57ede8ebee655faa838844f7b raw zig/src/cuda/grouped.zig 5fa1f39394b701eab59383bc7ed214ea3e17652a1229236df49f5281e6e764b5 raw commits e1be0806d; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate -zig/src/cuda/kernels.zig d348915a2365645f8a0aa1106e73a34572ad13cc52e2d8c042d5de32fdde8d49 raw main 42735f94f0 (#2335: the mla image registered), f35900e60c (#2709: the dots_mocr image registered), #1630 (the experts_bf16 image registered), #2914 (covers: the release SM check), #1631 (the nemo_audio image registered), #1767 (the idol image registered), (Hy4-flash images registered); #1295: the six Muse Spark images registered; #3413 (the flashnext_hcn image registered); #4125: the inkling2_attn and inkling2_pattn images registered; the hy4_engram image registered (#4004); #4126: the inkling2_ops and inkling2_rows images registered; #1858: the idol_decoder image registered +zig/src/cuda/kernels.zig 43a403bbac618bafc5417a38f35712d14cc9de7bf7a4d45fd1a2d24d0b8eb801 raw main 42735f94f0 (#2335: the mla image registered), f35900e60c (#2709: the dots_mocr image registered), #1630 (the experts_bf16 image registered), #2914 (covers: the release SM check), #1631 (the nemo_audio image registered), #1767 (the idol image registered), (Hy4-flash images registered); #1295: the six Muse Spark images registered; #3413 (the flashnext_hcn image registered); #4125: the inkling2_attn and inkling2_pattn images registered; the hy4_engram image registered (#4004); #4126: the inkling2_ops and inkling2_rows images registered; #4127: the inkling2_experts and inkling2_vision images registered; Mini ModelOpt and loop-math images registered; #1858: the idol_decoder image registered; #2302: the ricursive and ricursive_prep images registered zig/src/cuda/launch.zig 9ec64848834d82ddcea85a6123e975c95a5ae2bf85c2a71772244794b0bcd705 raw series patches 14-runtime-foundation.patch; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate zig/src/cuda/memory.zig c140f1700e0f257a3ac09b1bfaa4a0d704d1922ccbffc3d453d75be0fef4b617 raw commits 5dcf77d7c, f630f1a90, e9bf05ffd, 881cccaa4, a34cb6ded; series patches 14-runtime-foundation.patch; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate, this change (DeviceBuffer.allocVia allocates through a given hook; alloc is allocVia with the installed one, unchanged) zig/src/cuda/modelopt.zig 648c9ba58197af0ce905f8792383502fc44a52c45d1413fe9e21d28d04c22253 raw @@ -103,9 +103,9 @@ zig/src/cuda/nccl.zig 005a4dd9ed6929b6022c4daff8d8d82c0ee43ea3e468221fd4a8de9ae6 zig/src/cuda/norms.zig c6ac613ff91b31257b5bce55311d8cf38a785862bfad9eb0c7bf0b2ba7b0df95 raw zig/src/cuda/nvfp4.zig 0556e93c12e4eb21db45d0d9d9ee7d4c1c4ab6a32a359b67edfc0b4b7fb90928 raw #3252: launcher for the lean SwiGLU pair zig/src/cuda/qlinear.zig 680c653d110b53e52918bb13f7c54c12ffac4097959319281dc7509c085c062f raw commits da01294e0, 7f6f940eb, 4cec0eba1, c360607f0, ba1a9a2bb, b631fe069, 0a2a1c681, aca5a88e2, c12503be2, 7b17d0eb7, d7e44b555, 59be20e24, d40bc9e8b, f1f7f9abd, 3915bceaf, e8eabc82c; series patches 14-runtime-foundation.patch, 25-mimo-02.patch; MiMo-only aliases omitted from this candidate; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate -zig/src/cuda/qmmf.zig d95cbbce9598ee49b4677468f6672773470d9c52db5cb79ee20531963b2409fb raw main ec76abd45, c3acc3466, fbf8d960d (BF16 prompt tile, Flash Next only), 6a1feb26e (TF_QMMF_HALF_BELOW refused by name); dependent decode launches: weights load before griddepcontrol.wait (TF_QMMF_WFIRST), Lane.pdl; TF_FLASHNEXT_FUSED_SPLIT (fuse_split_n, default 0: main's kernels); threshold owned by Flash Next's lane, other families keep 0 +zig/src/cuda/qmmf.zig 08acd959abfd7336cded19c67d044590c3497066e6f36381d03ea31b9a733f1a raw main ec76abd45, c3acc3466, fbf8d960d (BF16 prompt tile, Flash Next only), 6a1feb26e (TF_QMMF_HALF_BELOW refused by name); dependent decode launches: weights load before griddepcontrol.wait (TF_QMMF_WFIRST), Lane.pdl; TF_FLASHNEXT_FUSED_SPLIT (fuse_split_n, default 0: main's kernels); threshold owned by Flash Next's lane, other families keep 0; #4533 optional FP4/FP8/FP8G half tiles, default off zig/src/cuda/rank_scatter.zig 303fd707713af732dd1d31c6a940dd4eeed44e9b26fe202919da5925654fc212 raw -zig/src/cuda/root.zig acf7f9d879a577622b705bfde274264ebb8ff8f4d6a4fb34b8828fff1642bcd5 raw main 42735f94f0 (#2335: cuda.mla exported), (cuda.affine_experts exported for Hy4-flash); main 42735f94f0 (#2335: cuda.mla exported); #3518 (exports roce_pair_rule; the test block imports roce_layout, roce_pairs and roce_pair_rule); #4493 (opt-in paired prompt experts, 128-row items) +zig/src/cuda/root.zig d4f3c80440208cae60fb2336ac2b2e4837dc7035e34eb3ca6d189765c5422e62 raw main 42735f94f0 (#2335: cuda.mla exported), (cuda.affine_experts exported for Hy4-flash); main 42735f94f0 (#2335: cuda.mla exported); #3518 (exports roce_pair_rule; the test block imports roce_layout, roce_pairs and roce_pair_rule); #4493 (opt-in paired prompt experts, 128-row items); #4533 exports qmmf_half zig/src/cuda/route_rows.zig e23257dea1f244ebba4399d7bc0730953f75eebbd7789819d5785e88a8907206 raw zig/src/cuda/sample.zig 9e3a31bd0480284ff069148b2d3c92f1e2ba24f16c18362dae9de48ec7fc65fe raw series patches 02-cuda-rounds.patch; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate; main 37b0776ce (#2680: adds ruleFor and rule, which reach the same core rule, byte-equal over a 25,480-setting grid; existing code unchanged), #3124 zig/src/cuda/segments.zig 8d029a27a7b2a77916c91c9e650cee07c25aec317efacfdb3f8f8967744899a9 raw @@ -115,7 +115,7 @@ zig/src/cuda/tp_watch.zig 19ed1d12bc56f804b5d207d04226e9f6131a517aaf7aec4c4b2d0b zig/src/cuda/triton.zig 256323865c6a4676b8b75aae9e32d2d9732cf2623efedb9462cf6f95302c3e83 raw zig/src/cuda/vit.zig 0a9200b161e331cf3f5937ff5dcc5c65bcb15e3de8127c277f6a31595d2e5296 raw #2239 (convCols, convFlatten and the head-64 full attention for Qwen3-ASR's audio tower; existing paths unchanged) zig/src/families/flashnext/cuda_attn.zig 99dfe79f919a8599490f1cdba0bec20d6e73ccbeafe26d5848419a465fdfa0d0 raw -zig/src/families/flashnext/cuda_batch.zig f1c5ab1478497ab2c0abdf77776dfed36fa9092579d4306e4320a32cfadf6910 raw main 42ff6c510f (disk states keyed by the resolved prompt passes; serving unchanged); #XXXX: the scratch test's ceiling restated at the 3,072-row default, #3413 (TF_FLASHNEXT_READOUT_FUSED's prompt read-out; unchanged when unset) +zig/src/families/flashnext/cuda_batch.zig b368dc5784c9d7e82d9e29ce26f37b3471d31a21e12a144127d365bdcc4ead96 raw main 42ff6c510f (disk states keyed by the resolved prompt passes; serving unchanged); #XXXX: the scratch test's ceiling restated at the 3,072-row default, #3413 (TF_FLASHNEXT_READOUT_FUSED's prompt read-out; unchanged when unset); TF_FLASHNEXT_GDN_CHAIN_TPR's opt-in row dispatch; unset leaves the key unchanged zig/src/families/flashnext/cuda_batch_state.zig 493ee0dc5bc832b9344d16de92ab33f5de15574b4d9a81f283558c4d729c6db6 raw y and moe_f32 take one spare row for a --tp 2 prompt pass's padded rank block; replies unchanged; #XXXX: the default prompt chunk is 3,072 rows; the shared pass takes the pooled n-gram gather first (TF_FLASHNEXT_GATHER_EARLY); replies unchanged zig/src/families/flashnext/cuda_collective.zig bf475ffb46b3440fcad280f46e34de25cd22b79ed96a0b587d0869e7451d3519 raw adds sumBlock, the in-place FP32 reduce-scatter with sum's peer check, deadline and abort; no served change on its own zig/src/families/flashnext/cuda_compare_main.zig ade014dfec88f0b386076cdc093ea20710d7bf36c33ff566ca2caf472064695b raw main dfd9ac5ef4 (#2585: the TF_FLASHNEXT_* startup check), c274b45cc1 (the check through the flashnext module) @@ -123,15 +123,15 @@ zig/src/families/flashnext/cuda_config.zig 19366ee591270c719fa6f710af0efd4d5a55c zig/src/families/flashnext/cuda_draft_affine.zig 2ec22bec1a38a6d2cc7e16a65d41deeb452d1a679661351a473652b5f39f2da8 raw zig/src/families/flashnext/cuda_embed.zig f52cee06a9bf820554b5443e9278be7bedf3381ff6d2529902b40c6699de4518 raw zig/src/families/flashnext/cuda_embed_main.zig 2b596788cccd420368fe803676e8ad45a4f0bf7a115a6cd8cbde9151cbf1e597 raw -zig/src/families/flashnext/cuda_gdn.zig bc952357f4d6c076542b419b0ee71bbdce89715f0223ab31b4abf821fc2bee62 raw +zig/src/families/flashnext/cuda_gdn.zig 017bf5d52085a7a2cfcb899fc26d08fe92ed21ba1673f9e1a1476a1e2e2dc45a raw zig/src/families/flashnext/cuda_glue.zig 0bd837ea17d1bd0a7a0820dc0ee99c4da90113c15d62b3fac31bd7af47a0ecb1 raw zig/src/families/flashnext/cuda_hc.zig 01f897ac65d6edd2cd6ac76d97cb4d96619c25ffa85bd619d6d76f4f465cda9a raw zig/src/families/flashnext/cuda_head.zig 734cc1ccea8e99ce9a061273a2dd3042f32e4848b622b5de616aa4b6f546bdd4 raw #3749: TF_FLASHNEXT_SHARD_HEAD read through platform/environment.zig, blank as unset -zig/src/families/flashnext/cuda_images.zig ef78a0eb8403a73da2d19bd7ed2aa4b2349a191f408060da79bee3963cd56ff2 raw #3164 (a resumed prompt sends only the images past its kept state) +zig/src/families/flashnext/cuda_images.zig 4696ef29dc81f30882f964d69a71c5378b247bfb772b51b354569639bf5a8812 raw #3164 (a resumed prompt sends only the images past its kept state); #3164 (a resumed prompt sends only the images past its kept state); #3456: a checkpoint's vision tower loads only with --vision, images without it are refused by the shared gate; text replies are unchanged zig/src/families/flashnext/cuda_images_test.zig 4278e5241f6c7e0e710e9a8ddf0482855db158eeee2463200a2c2de32c9dadd7 raw #3164 (resumed image rows tested) -zig/src/families/flashnext/cuda_lanes.zig 9c7e764298beab6c239064d0b151729763a374d19e20edb2a94025eda9053ea2 raw main 4f6017ced (marks inside the pass), fbca90714 (shared solo-chunk rule, #2391), 80e0fd72c (#2753: non-finite draft rows refused by name; finite rows unchanged), dfd9ac5ef4 (#2585: TF_FLASHNEXT_* read through platform/environment.zig, malformed text refused at startup; valid values keep their meaning), #1953: the ladder's values through snap_intermediate, #3308 (loader host test updates the named startup-refusal expectations; no runtime edit to this pinned file); #3135 (kept_disk renamed kept_view for the shared kept image; no served change), this change (the page pool opens with the load's device and io, for its arena mapped as pages are used; a new paged stream's first prompt step waits while the arena's thread maps its pieces; paging off: unchanged), #2917: one launch description and rank flags change this source; #3164 (resumed image rows passed to the tower), #3219 +zig/src/families/flashnext/cuda_lanes.zig 0aa9e028693cff3c88253952ff82526da59879b9018a01951ad6c5cf3dacae5e raw main 4f6017ced (marks inside the pass), fbca90714 (shared solo-chunk rule, #2391), 80e0fd72c (#2753: non-finite draft rows refused by name; finite rows unchanged), dfd9ac5ef4 (#2585: TF_FLASHNEXT_* read through platform/environment.zig, malformed text refused at startup; valid values keep their meaning), #1953: the ladder's values through snap_intermediate, #3308 (loader host test updates the named startup-refusal expectations; no runtime edit to this pinned file); #3135 (kept_disk renamed kept_view for the shared kept image; no served change), this change (the page pool opens with the load's device and io, for its arena mapped as pages are used; a new paged stream's first prompt step waits while the arena's thread maps its pieces; paging off: unchanged), #2917: one launch description and rank flags change this source; #3164 (resumed image rows passed to the tower), #3219, #2919 (the resolved rank and world reach visionBytes) zig/src/families/flashnext/cuda_lanes_admission_test.zig a87b5320d8cda1f95d254c2148c849005c2158b70afb73da3e32b627e6d2f13d raw -zig/src/families/flashnext/cuda_lanes_load.zig 3911082a7e95c1ffdcf8f6662d2b7b8127112c66794065f2df00bf95fc638fcf raw main dfd9ac5ef4 (#2585: TF_FLASHNEXT_* read through platform/environment.zig, malformed text refused at startup; valid values keep their meaning), #3467: after load a shard drops its page cache except the n-gram ranges, and the sweep reaches nested shards; tensors and replies are unchanged, this change (the load's device and io handed to the page pool's arena; paging off: unchanged) +zig/src/families/flashnext/cuda_lanes_load.zig 872cf185ad0e928b565b7ba9222563b8519167e66c9db91033eeac078c492be2 raw main dfd9ac5ef4 (#2585: TF_FLASHNEXT_* read through platform/environment.zig, malformed text refused at startup; valid values keep their meaning), #3467: after load a shard drops its page cache except the n-gram ranges, and the sweep reaches nested shards; tensors and replies are unchanged, this change (the load's device and io handed to the page pool's arena; paging off: unchanged); main dfd9ac5ef4 (#2585: TF_FLASHNEXT_* read through platform/environment.zig, malformed text refused at startup; valid values keep their meaning), #3467: after load a shard drops its page cache except the n-gram ranges, and the sweep reaches nested shards; tensors and replies are unchanged, this change (the load's device and io handed to the page pool's arena; paging off: unchanged); #3456: a checkpoint's vision tower loads only with --vision, images without it are refused by the shared gate; text replies are unchanged zig/src/families/flashnext/cuda_lanes_restore_test.zig f9947521a6d9c7d7380ca1b784a93a43b364c6fa5861cad15efd3538d2b8ceff raw zig/src/families/flashnext/cuda_launch.zig f056079d88e9295455bf44bed7ed4053e55fdb8579cfdb392c31a4c3af18e73c raw exports cuda_moe_exchange.zig for its device test; no served change; #2837 (Flash Next TP=2 graph replay); #3413 exports cuda_tiles.zig and readout_fused.zig for their tests zig/src/families/flashnext/cuda_media.zig 394601e8a807f5516f501efcaefa6fb3308f392ee322db7296b11c90814f8eea raw @@ -141,7 +141,7 @@ zig/src/families/flashnext/cuda_mixed_experts.zig d0362f591e98c2d13581ae48fb75fb zig/src/families/flashnext/cuda_mlp.zig 8224a28003487487e69eb669be11eaafafdb1ce0bc4c5e57024cef0a6a29e66f raw zig/src/families/flashnext/cuda_modelopt_experts.zig de779975629770b33ad5c0ebf9aa6e334f7a98f173a452d2b7c33b50a08d968e raw zig/src/families/flashnext/cuda_moe.zig 87ba75343c1d228800ed9fcc6d933f1175df172c008e14a8c7a64ff7011bed44 raw -zig/src/families/flashnext/cuda_mtp.zig 63235190fa55742d8819a1b612e998e2c64560b733d05aa5d7b1bd7bfc67f4fa raw main 80e0fd72c (#2753: non-finite draft rows refused by name; finite rows unchanged), dfd9ac5ef4 (#2585: TF_FLASHNEXT_* read through platform/environment.zig, malformed text refused at startup; valid values keep their meaning), #2927, main 3a56d4eb92 (one added line, the test import of cuda_mtp_load.zig so its loader tests run) +zig/src/families/flashnext/cuda_mtp.zig 25bd4a7ce6b740d2e4c1eec012bfdfb4a10a97a24cd3150b1335b89862dd970e raw main 80e0fd72c (#2753: non-finite draft rows refused by name; finite rows unchanged), dfd9ac5ef4 (#2585: TF_FLASHNEXT_* read through platform/environment.zig, malformed text refused at startup; valid values keep their meaning), #2927, main 3a56d4eb92 (one added line, the test import of cuda_mtp_load.zig so its loader tests run), the MTP rows' row best split over 32 blocks a row (fn_row_best_max, fn_row_best_sum), fn_row_best's bits, headBytes counts the split's scratch (split_bytes) zig/src/families/flashnext/cuda_mtp_check.zig 35d9d0ad51171ca2d70a0458f90fe6a04dd5f759fd9f005593c9d1189fb7846d raw main dfd9ac5ef4 (#2585: TF_FLASHNEXT_* read through platform/environment.zig, malformed text refused at startup; valid values keep their meaning) zig/src/families/flashnext/cuda_mtp_draft.zig 41628480a1071c4a58a229f5e8b42e26fcd030a046ca6796d2dcb2fedb8daf28 raw main 80e0fd72c (#2753: non-finite draft rows refused by name; finite rows unchanged), dfd9ac5ef4 (#2585: TF_FLASHNEXT_* read through platform/environment.zig, malformed text refused at startup; valid values keep their meaning), 52479d3036 (#2585: a test of the blank TF_FLASHNEXT_KEEP_LATE reader) zig/src/families/flashnext/cuda_mtp_load.zig d205877fe6d9d6b7b24a0ae061e8fc59a947fdcb1911d38e9f788af2468816c2 raw main 3a56d4eb92 (the draft head's mode read through platform/environment.zig: unset or blank keeps affine4, bf16 keeps the stored rows; kernels and launch counts unchanged) diff --git a/zig/tests/h3_image_server.zig b/zig/tests/h3_image_server.zig index af96607ba2b..a3d870c0b36 100644 --- a/zig/tests/h3_image_server.zig +++ b/zig/tests/h3_image_server.zig @@ -28,7 +28,7 @@ const usage = ; /// The transformer bound to one picture layout, its host copies in its own arena. -const Binding = struct { +pub const Binding = struct { arena: *std.heap.ArenaAllocator, model: *h3.Model, canvas: h3.picture.Size, @@ -37,7 +37,7 @@ const Binding = struct { tags: []const i32, weights: ?mtl.ResidencySet, - fn init(gpa: std.mem.Allocator, folder: *const image_tool.Folder, case: *const image_tool.Case, tags: []const i32, weights: ?mtl.ResidencySet, sched: ?h3.picture.Pdd) !Binding { + pub fn init(gpa: std.mem.Allocator, folder: *const image_tool.Folder, case: *const image_tool.Case, tags: []const i32, weights: ?mtl.ResidencySet, sched: ?h3.picture.Pdd) !Binding { const arena = try gpa.create(std.heap.ArenaAllocator); errdefer gpa.destroy(arena); arena.* = .init(gpa); @@ -60,7 +60,7 @@ const Binding = struct { return std.meta.eql(b.canvas, case.canvas) and b.rows == case.rows and b.references == case.layout.references.len and std.mem.eql(i32, b.tags, tags); } - fn release(b: *Binding) void { + pub fn release(b: *Binding) void { if (b.weights) |set| { set.remove(b.model.wq); set.remove(b.model.ws); @@ -275,6 +275,10 @@ const testing = std.testing; const fixture = @import("checkpoint_fixture"); const files = @import("h3_image_files.zig"); +test { + _ = @import("h3_image_server_speech.zig"); +} + /// A tiny synthetic MiniMax-H3-Image transformer: one block, hidden 256, inner 256, mlp 256, six steps. const synthetic = struct { const hidden = 256; @@ -412,7 +416,7 @@ fn expectSameLatent(want: []const f32, got: []const f32) !void { } /// The folder and the four cases the resident tests share; the caller frees the checkpoint's shards. -fn residentFixture(init: std.process.Init, a: std.mem.Allocator, dir: std.Io.Dir, dir_path: []const u8, device: mtl.Device) !struct { folder: image_tool.Folder, cases: [4]Built } { +pub fn residentFixture(init: std.process.Init, a: std.mem.Allocator, dir: std.Io.Dir, dir_path: []const u8, device: mtl.Device) !struct { folder: image_tool.Folder, cases: [4]Built } { try syntheticFolder(a, init.io, dir); var folder = try image_tool.Folder.open(init, a, dir_path); errdefer { @@ -667,147 +671,6 @@ test "a failed bind releases every Metal object it made" { try testing.expect(device.allocated() <= ceiling); } -/// An io whose `nth` exclusive tryLock (a stage's speech probe) first takes speech for `ms` on the real io: speech -/// arrives mid-stage, after the passes probed before it were submitted. One at a time; `join` after the stage. -const Arrival = struct { - var base: std.Io = undefined; - var vtable: std.Io.VTable = undefined; - var lock: []const u8 = undefined; - var nth: usize = 0; - var hold_ms: i64 = 0; - var speech: ?std.Thread = null; - - fn at(io: std.Io, path: []const u8, probe: usize, ms: i64) h3.gpu_turn.Turn { - base = io; - vtable = io.vtable.*; - vtable.fileTryLock = tryLock; - lock = path; - nth = probe; - hold_ms = ms; - speech = null; - return .{ .io = .{ .userdata = io.userdata, .vtable = &vtable }, .at = path }; - } - - fn tryLock(userdata: ?*anyopaque, file: std.Io.File, kind: std.Io.File.Lock) std.Io.File.LockError!bool { - if (kind == .exclusive and nth > 0) { - nth -= 1; - if (nth == 0) speech = speakFor(base, lock, hold_ms) catch null; - } - return base.vtable.fileTryLock(userdata, file, kind); - } - - fn join() !void { - (speech orelse return error.NoSpeechArrived).join(); - } -}; - -/// Speech holding `lock` for `ms` from now, released from its own thread. -fn speakFor(io: std.Io, lock: []const u8, ms: i64) !std.Thread { - const held = h3.gpu_turn.speak(io, lock) orelse return error.NoSpeechHold; - return std.Thread.spawn(.{}, struct { - fn release(i: std.Io, file: std.Io.File, wait: i64) void { - i.sleep(.fromMilliseconds(wait), .awake) catch {}; - h3.gpu_turn.done(i, file); - } - }.release, .{ io, held, ms }); -} - -test "speech arriving during the prompt encoder, denoising or the decoder holds its next pass, output unchanged" { - const io = testing.io; - const device = try mtl.Device.init(); - var arena = std.heap.ArenaAllocator.init(testing.allocator); - defer arena.deinit(); - const a = arena.allocator(); - var tmp = std.testing.tmpDir(.{}); - defer tmp.cleanup(); - const dir_path = try std.fmt.allocPrint(a, ".zig-cache/tmp/{s}", .{tmp.sub_path}); - const lock = try std.fs.path.join(a, &.{ dir_path, "speech.lock" }); - const hold_ms = 500; - const least = 0.25; // seconds the next pass must wait: the hold less any delay before its probe, with room to spare - - // the prompt encoder and the token refiner, on the prompt selftest's tiny checkpoint - var prng = std.Random.DefaultPrng.init(0x5133); - const tiny = try prompt_tool.Tiny.write(io, a, prng.random(), dir_path); - const g = prompt_tool.tiny_text; - var runner = try h3.Runner.init(device); - defer runner.deinit(); - var text_w = try h3.weights.loadText(testing.allocator, io, device, tiny.text_dir, g); - defer text_w.deinit(testing.allocator); - var front_w = try h3.weights.loadRefiner(testing.allocator, io, device, tiny.front_dir, prompt_tool.tiny_front); - defer front_w.deinit(testing.allocator); - const T = 70; - const ids = try a.alloc(u32, T); - for (ids, 0..) |*id, i| id.* = @intCast(i % g.vocab); - const pos = try a.alloc([3]i32, T); - for (pos, 0..) |*p, i| p.* = @splat(@intCast(i)); - const rows = try a.alloc(u16, T * g.hidden); - const text = try a.alloc(u16, T * prompt_tool.tiny_front.hidden); - try runner.encode(&text_w, ids, pos, null, rows); - try runner.refine(&front_w, rows, text); - const held_rows = try a.alloc(u16, rows.len); - const held_text = try a.alloc(u16, text.len); - // the second probe: speech arrives once the first of the two layers (or of the refiner's three passes) is submitted - runner.give_way = Arrival.at(io, lock, 2, hold_ms); - try runner.encode(&text_w, ids, pos, null, held_rows); - try Arrival.join(); - try testing.expect(runner.paused >= least); - runner.give_way = Arrival.at(io, lock, 2, hold_ms); - try runner.refine(&front_w, held_rows, held_text); - try Arrival.join(); - try testing.expect(runner.paused >= least); - try testing.expectEqualSlices(u16, rows, held_rows); - try testing.expectEqualSlices(u16, text, held_text); - - // the decoder: 2 x 2 tiles of a 20 x 28 cell latent, one pass each - const d = try h3.Decoder.init(testing.allocator, device, 2, 100); - defer d.deinit(); - try d.synthetic(0x5eed); - const config: h3.vae.Config = .{ .mean = @splat(0), .std = @splat(1), .tile = 256, .overlap = 64, .rope_theta = 100 }; - const latent = try a.alloc(f32, try h3.host.latentLength(20, 28)); - for (latent, 0..) |*v, i| v.* = @as(f32, @floatFromInt(i % 17)) / 8 - 1; - const pixels = try a.alloc(f32, 3 * 20 * 28 * h3.vae.cell_pixels * h3.vae.cell_pixels); - _ = try d.decode(a, &config, latent, 20, 28, 2, 1, pixels, null); - const held_pixels = try a.alloc(f32, pixels.len); - d.give_way = Arrival.at(io, lock, 2, hold_ms); // after the first of four tiles - const took = try d.decode(a, &config, latent, 20, 28, 2, 1, held_pixels, null); - try Arrival.join(); - try testing.expect(took.paused >= least); - try testing.expectEqualSlices(f32, pixels, held_pixels); - - // denoising: one step of the resident transformer - if (!device.tensorUnits()) return; - var environ_map: std.process.Environ.Map = .init(testing.allocator); - defer environ_map.deinit(); - const init = std.process.Init{ - .minimal = .{ .environ = .empty, .args = .{ .vector = &.{} } }, - .arena = &arena, - .gpa = testing.allocator, - .io = io, - .environ_map = &environ_map, - .preopens = .empty, - }; - var f = try residentFixture(init, a, tmp.dir, dir_path, device); - defer { - for (&f.cases) |*c| c.case.file.deinit(); - f.folder.heads.deinit(); - for (f.folder.ck.shards) |*shard| shard.deinit(); - testing.allocator.free(f.folder.ck.shards); - } - f.folder.turn = .{ .io = io, .at = lock }; - const case = &f.cases[0].case; - var b = try Binding.init(testing.allocator, &f.folder, case, f.cases[0].tags, null, null); - defer b.release(); - const velocity = try a.alloc(f32, case.noise.len); - _ = try b.model.forward(case.noise, &.{}, 0, null, velocity, &.{}); - const held_velocity = try a.alloc(f32, velocity.len); - // the third probe, after `mark` and the forward's first yield: speech arrives once the first block is submitted - b.model.give_way = Arrival.at(io, lock, 3, hold_ms); - const step = try b.model.forward(case.noise, &.{}, 0, null, held_velocity, &.{}); - try Arrival.join(); - try testing.expect(step.paused >= least and !step.timing_valid); - try testing.expectEqualSlices(f32, velocity, held_velocity); -} - test "an over-long request line is drained and the next one read" { var input: [5031]u8 = undefined; @memset(input[0..5000], 'x'); diff --git a/zig/tests/h3_image_server_speech.zig b/zig/tests/h3_image_server_speech.zig new file mode 100644 index 00000000000..1680368add6 --- /dev/null +++ b/zig/tests/h3_image_server_speech.zig @@ -0,0 +1,166 @@ +//! Speech arriving mid-stage in tf-h3-image-server: each stage gives way and its output is unchanged. +const std = @import("std"); +const mtl = @import("metal"); +const h3 = @import("h3"); +const prompt_tool = @import("h3_image_prompt.zig"); +const server = @import("h3_image_server.zig"); +const testing = std.testing; + +/// An io whose `nth` exclusive tryLock (a stage's probe) first takes speech for `ms`; `join` after the stage. +const Arrival = struct { + var base: std.Io = undefined; + var vtable: std.Io.VTable = undefined; + var lock: []const u8 = undefined; + var nth: usize = 0; + var hold_ms: i64 = 0; + var speech: ?std.Thread = null; + var watched: []const f32 = &.{}; + var untouched = false; + + fn at(io: std.Io, path: []const u8, probe: usize, ms: i64) h3.gpu_turn.Turn { + base = io; + vtable = io.vtable.*; + vtable.fileTryLock = tryLock; + lock = path; + nth = probe; + hold_ms = ms; + speech = null; + watched = &.{}; + return .{ .io = .{ .userdata = io.userdata, .vtable = &vtable }, .at = path }; + } + + fn tryLock(userdata: ?*anyopaque, file: std.Io.File, kind: std.Io.File.Lock) std.Io.File.LockError!bool { + if (kind == .exclusive and nth > 0) { + nth -= 1; + if (nth == 0) speech = speak() catch null; + } + return base.vtable.fileTryLock(userdata, file, kind); + } + + /// Speech holding `lock` for `hold_ms` from now, released from its own thread. + fn speak() !std.Thread { + const held = h3.gpu_turn.speak(base, lock) orelse return error.NoSpeechHold; + return std.Thread.spawn(.{}, release, .{held}); + } + + fn release(held: std.Io.File) void { + base.sleep(.fromMilliseconds(hold_ms), .awake) catch {}; + untouched = std.mem.allEqual(f32, watched, 0); + h3.gpu_turn.done(base, held); + } + + fn join() !void { + (speech orelse return error.NoSpeechArrived).join(); + } +}; + +test "speech arriving during the prompt encoder, denoising or the decoder holds its next pass, output unchanged" { + const io = testing.io; + const device = try mtl.Device.init(); + var arena = std.heap.ArenaAllocator.init(testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const dir_path = try std.fmt.allocPrint(a, ".zig-cache/tmp/{s}", .{tmp.sub_path}); + const lock = try std.fs.path.join(a, &.{ dir_path, "speech.lock" }); + const hold_ms = 500; + const least = 0.25; // seconds the next pass must wait: the hold less any delay before its probe, with room to spare + + // the prompt encoder and the token refiner, on the prompt selftest's tiny checkpoint + var prng = std.Random.DefaultPrng.init(0x5133); + const tiny = try prompt_tool.Tiny.write(io, a, prng.random(), dir_path); + const g = prompt_tool.tiny_text; + var runner = try h3.Runner.init(device); + defer runner.deinit(); + var text_w = try h3.weights.loadText(testing.allocator, io, device, tiny.text_dir, g); + defer text_w.deinit(testing.allocator); + var front_w = try h3.weights.loadRefiner(testing.allocator, io, device, tiny.front_dir, prompt_tool.tiny_front); + defer front_w.deinit(testing.allocator); + const T = 70; + const ids = try a.alloc(u32, T); + for (ids, 0..) |*id, i| id.* = @intCast(i % g.vocab); + const pos = try a.alloc([3]i32, T); + for (pos, 0..) |*p, i| p.* = @splat(@intCast(i)); + const rows = try a.alloc(u16, T * g.hidden); + const text = try a.alloc(u16, T * prompt_tool.tiny_front.hidden); + try runner.encode(&text_w, ids, pos, null, rows); + try runner.refine(&front_w, rows, text); + const held_rows = try a.alloc(u16, rows.len); + const held_text = try a.alloc(u16, text.len); + // the second probe: speech arrives once the first of the two layers (or of the refiner's three passes) is submitted + runner.give_way = Arrival.at(io, lock, 2, hold_ms); + try runner.encode(&text_w, ids, pos, null, held_rows); + try Arrival.join(); + try testing.expect(runner.paused >= least); + runner.give_way = Arrival.at(io, lock, 2, hold_ms); + try runner.refine(&front_w, held_rows, held_text); + try Arrival.join(); + try testing.expect(runner.paused >= least); + try testing.expectEqualSlices(u16, rows, held_rows); + try testing.expectEqualSlices(u16, text, held_text); + + // the decoder: 2 x 2 tiles of a 20 x 28 cell latent, one pass each + const d = try h3.Decoder.init(testing.allocator, device, 2, 100); + defer d.deinit(); + try d.synthetic(0x5eed); + const config: h3.vae.Config = .{ .mean = @splat(0), .std = @splat(1), .tile = 256, .overlap = 64, .rope_theta = 100 }; + const latent = try a.alloc(f32, try h3.host.latentLength(20, 28)); + for (latent, 0..) |*v, i| v.* = @as(f32, @floatFromInt(i % 17)) / 8 - 1; + const pixels = try a.alloc(f32, 3 * 20 * 28 * h3.vae.cell_pixels * h3.vae.cell_pixels); + _ = try d.decode(a, &config, latent, 20, 28, 2, 1, pixels, null); + const held_pixels = try a.alloc(f32, pixels.len); + d.give_way = Arrival.at(io, lock, 2, hold_ms); // after the first of four tiles + const took = try d.decode(a, &config, latent, 20, 28, 2, 1, held_pixels, null); + try Arrival.join(); + try testing.expect(took.paused >= least); + try testing.expectEqualSlices(f32, pixels, held_pixels); + + // denoising: one step of the resident transformer + if (!device.tensorUnits()) return; + var environ_map: std.process.Environ.Map = .init(testing.allocator); + defer environ_map.deinit(); + const init = std.process.Init{ + .minimal = .{ .environ = .empty, .args = .{ .vector = &.{} } }, + .arena = &arena, + .gpa = testing.allocator, + .io = io, + .environ_map = &environ_map, + .preopens = .empty, + }; + var f = try server.residentFixture(init, a, tmp.dir, dir_path, device); + defer { + for (&f.cases) |*c| c.case.file.deinit(); + f.folder.heads.deinit(); + for (f.folder.ck.shards) |*shard| shard.deinit(); + testing.allocator.free(f.folder.ck.shards); + } + f.folder.turn = .{ .io = io, .at = lock }; + const case = &f.cases[0].case; + var b = try server.Binding.init(testing.allocator, &f.folder, case, f.cases[0].tags, null, null); + defer b.release(); + const velocity = try a.alloc(f32, case.noise.len); + _ = try b.model.forward(case.noise, &.{}, 0, null, velocity, &.{}); + const held_velocity = try a.alloc(f32, velocity.len); + // the third probe, after `mark` and the forward's first yield: speech arrives once the first block is submitted + b.model.give_way = Arrival.at(io, lock, 3, hold_ms); + const step = try b.model.forward(case.noise, &.{}, 0, null, held_velocity, &.{}); + try Arrival.join(); + try testing.expect(step.paused >= least and !step.timing_valid); + try testing.expectEqualSlices(f32, velocity, held_velocity); + // the probe after the last block's: speech arriving as the last blocks drain holds the output heads + const out = b.model.video_velocity.slice(f32, b.model.video * b.model.video_in); + @memset(out, 0); + b.model.give_way = Arrival.at(io, lock, 3 + b.model.blocks.len, hold_ms); + Arrival.watched = out; + const last = try b.model.forward(case.noise, &.{}, 0, null, held_velocity, &.{}); + try Arrival.join(); + try testing.expect(Arrival.untouched and last.paused >= least and !last.timing_valid); + try testing.expectEqualSlices(f32, velocity, held_velocity); + // the probe after the final command buffer is waited: speech arriving then does not hold a finished step + b.model.give_way = Arrival.at(io, lock, 4 + b.model.blocks.len, hold_ms); + const done = try b.model.forward(case.noise, &.{}, 0, null, held_velocity, &.{}); + try Arrival.join(); + try testing.expect(done.paused == 0 and !done.timing_valid); + try testing.expectEqualSlices(f32, velocity, held_velocity); +} diff --git a/zig/tests/hip/contract_apply_rows.zig b/zig/tests/hip/contract_apply_rows.zig new file mode 100644 index 00000000000..d084fa1ead2 --- /dev/null +++ b/zig/tests/hip/contract_apply_rows.zig @@ -0,0 +1,451 @@ +//! plan_rows.hip's two-launch values step under the contract: slots, poisoned values, tf_plan_apply_*'s bits. +const std = @import("std"); +const hip = @import("hip"); +const core = @import("core"); +const rig_ = @import("contract_rig.zig"); +const kit = @import("contract_kit.zig"); +const walk_rows = @import("contract_walk_rows.zig"); + +const contract = core.contract; +const c = contract.spec; +const g = contract.gates; +const sums = contract.rows; + +const page = 64; +const d = 256; +/// Keys a values tile sums (plan_apply_body's). +const tile = 128; +/// Spans the shared-row values kernels take from (launches/plan.zig's score_span). +const long_span = 16384; + +/// Query heads over KV heads: Qwen3.6-35B-A3B's 16 over 2 and Qwen3.8-27B's 24 over 4, the score's cases. +pub const cases = walk_rows.cases; + +/// served[0] takes gates 1-2 (slots of 3, 1 and 4 rows, a span with a part tile), gate 4 the 262,144-key span. +const served = blk: { + var t: [cases.len][7]c.Shape = undefined; + for (cases, 0..) |x, i| t[i] = .{ + .{ .rows = 8, .n = x.heads, .k = 16387 }, + .{ .rows = 16, .n = x.heads, .k = 65536 }, + .{ .rows = 4, .n = x.heads, .k = 131072 }, + .{ .rows = 2, .n = x.heads, .k = 262144 }, + .{ .rows = 64, .n = x.heads, .k = 16384 }, + .{ .rows = 5, .n = x.heads, .k = 65536 }, + .{ .rows = 7, .n = x.heads, .k = 131072 }, + }; + break :blk t; +}; + +/// The real launches, or a control's: chunks led across slots (first 0, count every row), or the chunks' launch alone. +pub const Fault = enum { none, crossing, alone }; + +/// The registrations: each case in fp16 and bf16 caches, then each control in each. +pub const count_all = 2 * cases.len + 4; + +const kernel_names = [2][]const u8{ "tf_plan_rows_apply_f16", "tf_plan_rows_apply_bf16" }; +const lone_names = [2][]const u8{ "tf_plan_lone_apply_f16", "tf_plan_lone_apply_bf16" }; +const replaced_names = [2][]const u8{ "tf_plan_apply_f16", "tf_plan_apply_bf16" }; + +/// Each case's names [case][bf16], and the controls' [bf16]. +const names = blk: { + var t: [cases.len][2][]const u8 = undefined; + for (cases, 0..) |x, i| for (0..2) |bf| { + const what = "hip {s} then {s}, {d} heads over {d}: one-row slots alone, the others' rows on one read of their values"; + t[i][bf] = std.fmt.comptimePrint(what, .{ lone_names[bf], kernel_names[bf], x.heads, x.kv }); + }; + break :blk t; +}; +const control_names = blk: { + var t: [2][2][]const u8 = undefined; + for (0..2) |bf| { + t[0][bf] = "control: hip " ++ kernel_names[bf] ++ ", chunks led across slots (first 0, count every row)"; + t[1][bf] = "control: hip " ++ kernel_names[bf] ++ " alone, the one-row slots' launch left out"; + } + break :blk t; +}; + +/// Case `i`'s spec in kind `k`: the bits of the one-row kernel it replaces, edges at a chunk's rows and a tile's keys. +pub fn spec(i: usize, k: kit.Kind, fault: Fault) c.Spec { + const bf = @intFromBool(k == .bf16); + return .{ + .name = if (fault == .none) names[i][bf] else control_names[@intFromBool(fault == .alone)][bf], + .accum = .f32, + .depth = depth, + .out = .f32, + .replaces = replaced_names[bf], + .tiles = .{ .{ .size = hip.launches.apply_rows }, .{}, .{ .size = long_span + tile, .min = long_span } }, + .served = &served[i], + }; +} + +/// A tile's adds, after each term's subtract, exp (two roundings), divide and product. +fn depth(_: c.Shape) usize { + return tile + 5; +} + +/// Rows a slot holds: one each for an odd count from 5 (streams with no drafts), else cycling 3, 1, 4, 2 and 6. +fn counts(a: std.mem.Allocator, rows: usize) ![]usize { + var out: std.ArrayList(usize) = .empty; + const cycle: []const usize = if (rows % 2 == 1 and rows >= 5) &.{1} else &.{ 3, 1, 4, 2, 6 }; + var left = rows; + while (left > 0) : (left -= out.items[out.items.len - 1]) try out.append(a, @min(left, cycle[out.items.len % cycle.len])); + return out.toOwnedSlice(a); +} + +/// Slot s's last row's visible keys: the span's end, mid-span, one past a tile's first key, or the span's start. +fn lastVisible(s: usize, rows: usize, k: usize) usize { + const v = switch (s % 4) { + 0 => k - s / 4 * 7, + 1 => k / 2 + 5 + s / 4 * 64, + 2 => k / 4 / tile * tile + 1 + s / 4, + else => rows + s / 4, + }; + return std.math.clamp(v, rows, k); +} + +fn mix(x: u32) u32 { + var h = x; + h ^= h >> 16; + h *%= 0x7feb352d; + h ^= h >> 15; + h *%= 0x846ca68b; + h ^= h >> 16; + return h; +} + +/// A finite value of the kind, any sign and mantissa, magnitude in [2^-4, 2^2), as its 16 bits. +fn finite(k: kit.Kind, h: u32) u16 { + const sign: u16 = @intCast(h >> 31); + return if (k == .bf16) + sign << 15 | @as(u16, @intCast(123 + (h >> 8) % 6)) << 7 | @as(u16, @intCast(h & 0x7f)) + else + sign << 15 | @as(u16, @intCast(11 + (h >> 10) % 6)) << 10 | @as(u16, @intCast(h & 0x3ff)); +} + +/// A NaN of payload h (quiet or signaling) or an infinity of either sign, as the kind's 16 bits. +fn nonFinite(k: kit.Kind, h: u32) u16 { + const top: u16 = if (k == .bf16) 0x7f80 else 0x7c00; + const mant: u32 = if (k == .bf16) 0x7f else 0x3ff; + return switch (h % 3) { + 0 => @as(u16, @intCast((h >> 31) << 15)) | top | @as(u16, @intCast(1 + (h >> 8) % mant)), + 1 => top, + else => 0x8000 | top, + }; +} + +/// Gate 4's value: an integer in [1, 255] of either sign, times 16 for half of them, the same in every tile. +fn stressValue(k: kit.Kind, h: usize, key: usize, j: usize) u16 { + const r = mix(@intCast((h * tile + key % tile) * d + j)); + const v: f64 = @floatFromInt((1 + r % 255) * @as(u32, if (r >> 9 & 1 == 1) 16 else 1)); + var b: [2]u8 = undefined; + kit.put(k, &b, 0, if (r >> 31 == 1) -v else v); // eight significant bits: exact in both kinds + return std.mem.readInt(u16, &b, .little); +} + +/// shape.rows rows over slots of `counts` rows, each slot's own pages in one pool; every row's partials of every tile. +pub const RowsApply = struct { + rig: rig_.Rig, + l: *const hip.Launcher, + k: kit.Kind, + case: usize, + fault: Fault = .none, + arena: std.heap.ArenaAllocator, + shape: c.Shape = undefined, + stress: bool = false, + scores: []f32 = &.{}, // [rows][heads][span], NaN past a row's keys + stats: []f32 = &.{}, // [rows][heads][2]: the max and the sum the weights divide by + pool: []u16 = &.{}, // the values in the kind, [kv][pages][page][d] + pages: usize = 0, + /// Each slot's page table, and each row's slot and visible keys. + tables: [][]u32 = &.{}, + slot: []usize = &.{}, + vis: []usize = &.{}, + plan: hip.launches.PlanRef = undefined, + /// The control's plan: every slot's first 0 and its count every row. + crossing: hip.launches.PlanRef = undefined, + sc32: u64 = 0, + st32: u64 = 0, + out: u64 = 0, + tree: u64 = 0, // the replaced kernel's partials + + /// Registration i of `count_all`: each case in fp16 then bf16 caches, then each control likewise. + pub fn init(a: std.mem.Allocator, rt: *const hip.Runtime, s: hip.Stream, l: *const hip.Launcher, i: usize) RowsApply { + const control = i >= 2 * cases.len; + return .{ + .rig = .{ .a = a, .r = rt, .s = s }, + .l = l, + .k = if (i % 2 == 1) .bf16 else .f16, + .case = if (control) 0 else i / 2, + .fault = if (!control) .none else if (i < 2 * cases.len + 2) .crossing else .alone, + .arena = .init(a), + }; + } + + pub fn deinit(self: *RowsApply) void { + self.arena.deinit(); + self.rig.deinit(); + } + + /// A control keeps its case's spec under its own name and must go red at gate 3. + pub fn kernel(self: *RowsApply) g.Kernel { + return .{ .spec = spec(self.case, self.k, self.fault), .ctx = self, .vt = &vt, .control = if (self.fault != .none) .shapes else null }; + } + + const vt = g.hooks(RowsApply); + + /// Element 0 of position `pos` of KV head `h` in slot `s`'s pages. + fn at(self: *const RowsApply, s: usize, h: usize, pos: usize) usize { + return ((h * self.pages + self.tables[s][pos / page]) * page + pos % page) * d; + } + + fn tiles(self: *const RowsApply) usize { + return (self.shape.k + tile - 1) / tile; + } + + pub fn prepare(self: *RowsApply, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + const kv = cases[self.case].kv; + if (shape.rows == 0 or shape.k < long_span or shape.n % kv != 0) return false; + self.rig.reset(); + _ = self.arena.reset(.free_all); + self.shape = shape; + self.stress = fill == .stress; + const a = self.arena.allocator(); + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + const keys = shape.k; + const per = try counts(a, shape.rows); + const slots = per.len; + // each slot's rows at consecutive positions up to its last row's, and its pages, permuted over one pool + self.slot = try a.alloc(usize, shape.rows); + self.vis = try a.alloc(usize, shape.rows); + const first = try a.alloc(i32, slots); + const many = try a.alloc(i32, slots); + const need = try a.alloc(usize, slots); + var row: usize = 0; + self.pages = 0; + for (per, 0..) |n, s| { + const last = lastVisible(s, n, keys); + first[s] = @intCast(row); + many[s] = @intCast(n); + for (0..n) |i| { + self.slot[row + i] = s; + self.vis[row + i] = last - (n - 1) + i; + } + row += n; + need[s] = (last + page - 1) / page; + self.pages += need[s]; + } + self.tables = try a.alloc([]u32, slots); + var next: usize = 0; + for (self.tables, need) |*t, n| { + t.* = try a.alloc(u32, n); + for (t.*, next..) |*p, i| p.* = @intCast(if (self.pages % 5 == 0) self.pages - 1 - i else (i * 5 + 3) % self.pages); + next += n; + } + self.pool = try a.alloc(u16, kv * self.pages * page * d); + const salt: u32 = @truncate(seed); + for (self.tables, 0..) |t, s| for (0..kv) |h| for (0..t.len * page) |pos| { + const row_at = self.at(s, h, pos); + const hk = mix(@as(u32, @truncate((s * kv + h) * keys + pos)) *% 0x27d4eb2f +% salt); + for (self.pool[row_at..][0..d], 0..) |*x, j| { + x.* = if (self.stress) stressValue(self.k, h, pos, j) else finite(self.k, mix(hk ^ @as(u32, @intCast(j)) *% 0x9e3779b1)); + } + // one key in 41 holds a NaN or an infinity at one element, seen by some rows and past others + if (!self.stress and hk % 41 == 0) self.pool[row_at + hk / 41 % d] = nonFinite(self.k, mix(hk)); + }; + if (!self.stress) for (per, need, 0..) |n, pages, s| { + const last = lastVisible(s, n, keys); + // the value only a slot's last row weighs, and the one past all its rows, both non-finite + for ([_]usize{ last - 1, last }) |pos| if (pos < pages * page) for (0..kv) |h| { + self.pool[self.at(s, h, pos) + (pos + h) % d] = nonFinite(self.k, mix(@intCast(pos + h))); + }; + }; + try self.weights(rng, fill); + self.sc32 = try self.rig.input(std.mem.sliceAsBytes(self.scores)); + self.st32 = try self.rig.input(std.mem.sliceAsBytes(self.stats)); + const pool = try self.rig.input(std.mem.sliceAsBytes(self.pool)); + // each slot's descriptor [cached, kept, k pool, v pool], then its page table + const words = 4; + const descs = try a.alloc(u64, slots); + for (self.tables, descs) |t, *dev| { + const desc = try a.alloc(u64, words + (t.len + 1) / 2); + @memset(desc, 0); + desc[3] = pool; + @memcpy(std.mem.sliceAsBytes(desc[words..])[0 .. t.len * 4], std.mem.sliceAsBytes(t)); + dev.* = try self.rig.input(std.mem.sliceAsBytes(desc)); + } + const pos = try a.alloc(i32, shape.rows); + const slot = try a.alloc(i32, shape.rows); + for (pos, slot, self.vis, self.slot) |*p, *s, v, x| { + p.* = @intCast(v - 1); + s.* = @intCast(x); + } + const args: hip.launches.PlanArgs = .{ + .pos = try self.rig.input(std.mem.sliceAsBytes(pos)), + .slot = try self.rig.input(std.mem.sliceAsBytes(slot)), + .first = try self.rig.input(std.mem.sliceAsBytes(first)), + .count = try self.rig.input(std.mem.sliceAsBytes(many)), + .desc = try self.rig.input(std.mem.sliceAsBytes(descs)), + .pages = words, + .pool = @intCast(self.pages), + }; + self.plan = .{ .rows = shape.rows, .slots = slots, .args = args }; + self.crossing = self.plan; + if (self.fault == .crossing) { + const zero = try a.alloc(i32, slots); + @memset(zero, 0); + const all = try a.alloc(i32, slots); + @memset(all, @intCast(shape.rows)); + self.crossing.args.first = try self.rig.input(std.mem.sliceAsBytes(zero)); + self.crossing.args.count = try self.rig.input(std.mem.sliceAsBytes(all)); + } + self.out = try self.rig.output(self.count() * 4); + self.tree = try self.rig.scratch(self.count() * 4); + return true; + } + + /// The fp32 scores and stats: weights in (e^-4 / 64, 1], gate 4's 1, 1/2 or 1/4, gate 1's NaN and infinities. + fn weights(self: *RowsApply, rng: std.Random, fill: g.Fill) !void { + const s = self.shape; + const a = self.arena.allocator(); + self.scores = try a.alloc(f32, s.rows * s.n * s.k); + self.stats = try a.alloc(f32, s.rows * s.n * 2); + for (0..s.rows) |r| for (0..s.n) |h| { + const i = r * s.n + h; + const top: f32 = if (self.stress) 0.5 else @floatCast(rng.float(f64) * 4 - 2); + self.stats[2 * i] = top; + self.stats[2 * i + 1] = if (self.stress) @floatFromInt(@as(u32, 1) << @intCast(h % 3)) else @floatCast(1 + rng.float(f64) * 63); + for (self.scores[i * s.k ..][0..s.k], 0..) |*x, key| { + x.* = if (key >= self.vis[r]) std.math.nan(f32) else if (self.stress) top else @floatCast(@as(f64, top) - rng.float(f64) * 4); + } + }; + if (self.stress) return; + // a NaN, an infinite and a negatively infinite score at keys some rows of a chunk weigh, and a NaN max + for ([_][3]usize{ .{ 0, 0, 5 }, .{ 1, 1, 200 }, .{ 2, 2, 300 } }, [_]f32{ std.math.nan(f32), std.math.inf(f32), -std.math.inf(f32) }) |x, v| { + if (x[0] < s.rows and x[2] < self.vis[x[0]]) self.scores[(x[0] * s.n + x[1]) * s.k + x[2]] = v; + } + if (fill == .nonfinite and s.rows > 3) self.stats[2 * (3 * s.n + 3)] = std.math.nan(f32); + } + + pub fn run(self: *RowsApply) !void { + const s = self.shape; + if (self.fault == .alone) return self.chunksAlone(); + const p = if (self.fault == .crossing) self.crossing else self.plan; + try self.l.planApply(self.sc32, self.st32, self.out, p, 0, s.n, cases[self.case].kv, d, s.k, @backingInt(self.k), false, .shared, self.rig.s.handle); + try self.rig.s.synchronize(); + } + + /// The control's launch: planApply's tf_plan_rows_apply_* on its grid, without tf_plan_lone_apply_*. + fn chunksAlone(self: *RowsApply) !void { + const s = self.shape; + const kv = cases[self.case].kv; + var a: hip.launch.Args = .{}; + try a.add(self.sc32); + try a.add(self.st32); + try a.add(self.out); + for ([_]usize{ s.k, s.n, kv, d }) |x| try a.add(@as(c_int, @intCast(x))); + try a.add(self.plan.args); + try a.add(@as(c_int, 0)); + const grid: hip.launch.Dim3 = .{ .x = @intCast(self.tiles()), .y = @intCast(kv), .z = @intCast(s.rows) }; + const f = self.l.plan.apply_rows[@intCast(@backingInt(self.k) - 1)]; + try hip.launch.launch(f, .{ .grid = grid, .block = .{ .x = 256 } }, self.rig.s, &a); + try self.rig.s.synchronize(); + } + + /// tf_plan_apply_*'s bytes on the same plan: a block a row. + pub fn replaced(self: *RowsApply) ![]const u8 { + const s = self.shape; + try self.l.planApply(self.sc32, self.st32, self.tree, self.plan, 0, s.n, cases[self.case].kv, d, s.k, @backingInt(self.k), false, .one, self.rig.s.handle); + return self.rig.bytes(self.tree, self.count() * 4); + } + + pub fn count(self: *RowsApply) usize { + return self.shape.rows * self.shape.n * self.tiles() * d; + } + + /// Each tile's sum of exp(score - max) / sum times the values over the keys a row sees, 0 past them, in float64. + pub fn reference(self: *RowsApply, want: []f64, mag: []f64) !void { + try self.work(want, mag, null); + } + + /// Gate 4's partials with each tile's products summed in the accumulator and order. + pub fn simulate(self: *RowsApply, acc: c.Accum, order: g.Order, out: []f64) !void { + try self.work(out, null, .{ acc, order }); + } + + /// Element j of key `pos` of KV head `h` in slot `s`'s pages, as float64. + fn value(self: *const RowsApply, s: usize, h: usize, pos: usize, j: usize) f64 { + const bits = self.pool[self.at(s, h, pos) + j]; + return if (self.k == .bf16) @as(f64, c.fromBf16(bits)) else @as(f64, @as(f16, @bitCast(bits))); + } + + /// Every row's partials, in float64 or (`sim`) as an accumulator sums a tile; gate 4's whole tiles are worked once. + fn work(self: *RowsApply, out: []f64, mag: ?[]f64, sim: ?struct { c.Accum, g.Order }) !void { + const s = self.shape; + const a = self.rig.a; + const kv = cases[self.case].kv; + const group = s.n / kv; + const n = self.tiles(); + @memset(out, 0); + if (mag) |m| @memset(m, 0); + const vals = try a.alloc(f64, tile * d); // a tile's values, [key][j] + defer a.free(vals); + const w = try a.alloc(f64, tile); + defer a.free(w); + const terms = try a.alloc(f64, tile); + defer a.free(terms); + var r0: usize = 0; + while (r0 < s.rows) { + var r1 = r0 + 1; + while (r1 < s.rows and self.slot[r1] == self.slot[r0]) r1 += 1; + var most: usize = 0; + for (self.vis[r0..r1]) |v| most = @max(most, v); + const sl = self.slot[r0]; + for (0..kv) |hk| { + // gate 4: the first whole tile's partials of each row and head, copied to its other whole tiles + var whole: ?usize = null; + for (0..n) |t| { + const key0 = t * tile; + if (key0 >= most) break; + const top = @min(key0 + tile, most); + if (!self.stress or t == 0 or top - key0 < tile or whole == null) { + for (key0..top) |pos| for (0..d) |j| { + vals[(pos - key0) * d + j] = self.value(sl, hk, if (self.stress) pos % tile else pos, j); + }; + } + for (r0..r1) |r| for (hk * group..(hk + 1) * group) |h| { + const stop = @min(key0 + tile, self.vis[r]); + if (stop <= key0) continue; + const base = ((r * s.n + h) * n + t) * d; + if (self.stress and stop - key0 == tile) { + if (whole) |from| { + const src = ((r * s.n + h) * n + from) * d; + @memcpy(out[base..][0..d], out[src..][0..d]); + if (mag) |m| @memcpy(m[base..][0..d], m[src..][0..d]); + continue; + } + } + const i = r * s.n + h; + const top_s: f64 = self.stats[2 * i]; + const sum: f64 = self.stats[2 * i + 1]; + for (w[0 .. stop - key0], key0..) |*x, pos| x.* = @exp(@as(f64, self.scores[i * s.k + pos]) - top_s) / sum; + for (0..d) |j| { + var acc: f64 = 0; + var abs: f64 = 0; + for (terms[0 .. stop - key0], w[0 .. stop - key0], 0..) |*x, wk, e| { + x.* = wk * vals[e * d + j]; + acc += x.*; + abs += @abs(x.*); + } + if (sim) |how| acc = sums.sumIn(how[0], how[1], terms[0 .. stop - key0]); + out[base + j] = acc; + if (mag) |m| m[base + j] = abs; + } + }; + if (self.stress and top - key0 == tile and whole == null) whole = t; + } + } + r0 = r1; + } + } +}; diff --git a/zig/tests/hip/contract_families.zig b/zig/tests/hip/contract_families.zig index be88c7abb9c..bf5132d338c 100644 --- a/zig/tests/hip/contract_families.zig +++ b/zig/tests/hip/contract_families.zig @@ -4,6 +4,7 @@ pub const Entry = @import("contract_entry.zig").Entry; pub const entries = [_]Entry{ .{ .group = .glm_ocr, .run = @import("contract_glm_ocr.zig").run }, + .{ .group = .inkling2, .run = @import("contract_inkling2.zig").run }, .{ .group = .joint_schema, .run = @import("contract_joint_schema.zig").run }, .{ .group = .lighton_ocr, .run = @import("contract_lighton.zig").run }, .{ .group = .qwen_vision, .run = @import("contract_qwen_vision.zig").run }, diff --git a/zig/tests/hip/contract_inkling2.zig b/zig/tests/hip/contract_inkling2.zig new file mode 100644 index 00000000000..e8e4b57dce4 --- /dev/null +++ b/zig/tests/hip/contract_inkling2.zig @@ -0,0 +1,76 @@ +//! Inkling 2's HIP attention (zig/kernels/hip/inkling2) under the contract at Mini's shapes, with planted controls. +const std = @import("std"); +const hip = @import("hip"); +const core = @import("core"); +const K = @import("inkling2_hip"); +const Profile = @import("contract_entry.zig").Profile; +const rows = @import("contract_inkling2_rows.zig"); +const prep = @import("contract_inkling2_prep.zig"); + +const g = core.contract.gates; + +/// The `inkling2` contract entry (contract_families.zig): prep, the table, each attention path, then the controls. +pub fn run(a: std.mem.Allocator, _: std.Io, profile: Profile) anyerror!g.Tally { + var r = try hip.Runtime.open(); + defer r.close(); + var ctx = try hip.Context.init(&r, 0); + defer ctx.deinit(); + var s = try hip.Stream.init(&r); + defer s.deinit(); + var k = try K.Kernels.load(&r, hip.kernels.images[@backingInt(hip.kernels.Group.inkling2)]); + defer k.unload(); + var list: std.ArrayList(g.Kernel) = .empty; + defer list.deinit(a); + var set: Set = .{}; + try set.init(a, &r, s, &k, profile, &list); + defer set.deinit(); + var t: g.Tally = .{}; + try g.runAll(a, list.items, 0x6b63, &t); + return t; +} + +/// The launches as the forward makes them: prep, the bias table, then the chunks and their merge. +pub const Set = struct { + attns: [12]rows.Attn = undefined, + exacts: [2]rows.Attn = undefined, + preps: [5]prep.Prep = undefined, + tables: [2]prep.Table = undefined, + made: bool = false, + + const forms = [_]struct { rows.Path, bool, rows.Plant }{ + .{ .sliding, false, .none }, .{ .fold, false, .none }, .{ .split, false, .none }, + .{ .prompt, false, .none }, .{ .sliding, true, .none }, .{ .fold, true, .none }, + .{ .split, true, .none }, .{ .sliding, false, .late_bias }, .{ .fold, false, .no_sink }, + .{ .prompt, false, .q_ulp }, .{ .sliding, false, .window_one }, .{ .sliding, false, .pre_sigmoid }, + }; + const prep_forms = [_]struct { bool, bool, prep.Fault }{ .{ false, false, .none }, .{ true, false, .none }, .{ true, true, .none }, .{ true, false, .tau_off }, .{ true, false, .cross_write } }; + + /// Every registration, its kernels first and its controls after, each with its own buffers. + pub fn init(set: *Set, a: std.mem.Allocator, r: *const hip.Runtime, s: hip.Stream, k: *const K.Kernels, profile: Profile, list: *std.ArrayList(g.Kernel)) !void { + for (&set.attns, forms) |*x, f| x.* = .{ .rig = .{ .a = a, .r = r, .s = s }, .k = k, .path = f[0], .apart = f[1], .plant = f[2], .profile = profile }; + for (&set.preps, prep_forms) |*x, f| x.* = .{ .rig = .{ .a = a, .r = r, .s = s }, .k = k, .global = f[0], .apart = f[1], .fault = f[2] }; + for (&set.tables, 0..) |*x, i| x.* = .{ .rig = .{ .a = a, .r = r, .s = s }, .k = k, .late = i == 1 }; + for (&set.exacts, [_]rows.Path{ .sliding, .fold }) |*x, p| x.* = .{ .rig = .{ .a = a, .r = r, .s = s }, .k = k, .path = p, .exact_p = true, .profile = profile }; + set.made = true; + for (set.preps[0..3]) |*x| try list.append(a, x.kernel()); + try list.append(a, set.tables[0].kernel()); + for (set.attns[0..7]) |*x| try list.append(a, x.kernel()); + for (&set.exacts) |*x| try list.append(a, x.kernel()); + for (set.preps[3..]) |*x| try list.append(a, x.kernel()); + try list.append(a, set.tables[1].kernel()); + for (set.attns[7..]) |*x| try list.append(a, x.kernel()); + } + + pub fn deinit(set: *Set) void { + if (!set.made) return; + for (&set.attns) |*x| x.deinit(); + for (&set.exacts) |*x| x.deinit(); + for (&set.preps) |*x| x.deinit(); + for (&set.tables) |*x| x.deinit(); + set.made = false; + } +}; + +test { + _ = @import("contract_inkling2_fill.zig"); +} diff --git a/zig/tests/hip/contract_inkling2_fill.zig b/zig/tests/hip/contract_inkling2_fill.zig new file mode 100644 index 00000000000..fcb14e3470b --- /dev/null +++ b/zig/tests/hip/contract_inkling2_fill.zig @@ -0,0 +1,305 @@ +//! Inkling 2's HIP attention inputs: Mini's shapes, the rows' streams, the fills of each gate and the FP64 pool. +const std = @import("std"); +const core = @import("core"); +const K = @import("inkling2_hip"); + +const contract = core.contract; +const ref = contract.inkling2_attn_ref; +const c = contract.spec; +const g = contract.gates; +const D = ref.D; + +/// Mini's attention: 24 query heads over 8 key heads (GQA 3:1), n_floor 8,192 (config.json). +pub const heads = 24; +pub const kv = 8; +pub const group = heads / kv; +pub const floor_pos: f64 = 8192; +/// Global keys to 1M wrap a 4,096-slot ring (key p in slot p % ring): no 2 GiB cache needed. +pub const global_ring = 4096; + +/// A call's streams: rows of stream i sit at its own positions and its caches `segs[i].off` elements in. +pub const Layout = struct { + layer: K.Layer, + rows: usize, + streams: usize, + segs: [3]K.Seg, + + /// Stream 0's rows end at the context (k - 1), stream 1's near k / 2, stream 2's near k / 3: far from its end. + pub fn of(layer: K.Layer, rows: usize, k: usize, streams: usize) Layout { + var x: Layout = .{ .layer = layer, .rows = rows, .streams = streams, .segs = undefined }; + const cache: i64 = @intCast(@as(usize, layer.ring) * kv * D); + var row0: usize = 0; + for (0..3) |i| { + const n = if (i >= streams) 0 else if (i > 0) rows / streams else rows - (streams - 1) * (rows / streams); + const last = if (i == 0) k else @max(n, k / (i + 1)); + x.segs[i] = .{ .row0 = @intCast(row0), .n = @intCast(n), .p0 = @intCast(last - n), .off = cache * @as(i64, @intCast(i)) }; + row0 += n; + } + return x; + } + + pub fn streamOf(x: *const Layout, row: usize) usize { + var st: usize = 0; + while (st + 1 < x.streams and row >= @as(usize, @intCast(x.segs[st + 1].row0))) st += 1; + return st; + } + + pub fn posOf(x: *const Layout, row: usize) usize { + const s = x.segs[x.streamOf(row)]; + return @as(usize, @intCast(s.p0)) + row - @as(usize, @intCast(s.row0)); + } +}; + +/// Gate 4's value at key p of column col: period 1,024, its second half the first's negation a key along, + 1 on 8. +fn periodic(p: usize, col: usize) f64 { + const i = p % 1024; + if (i < 512) return @floatFromInt(129 + (i * 73 + col * 31) % 127); + const j = i - 512; + return -@as(f64, @floatFromInt(129 + ((j + 1) % 512 * 73 + col * 31) % 127)) + @as(f64, if (j < 8) 1 else 0); +} + +/// One call's host inputs, as prep leaves them for the attention launches. +pub const Data = struct { + q: []u16 = &.{}, + kc: []u16 = &.{}, + vc: []u16 = &.{}, + tab: []u16 = &.{}, + sink: []u16 = &.{}, + gate: []u16 = &.{}, + pos: []usize = &.{}, + stream: []usize = &.{}, + + pub const makeExactP = fillExactP; + + pub fn free(d: *Data, a: std.mem.Allocator) void { + inline for (.{ "q", "kc", "vc", "tab", "sink", "gate", "pos", "stream" }) |f| a.free(@field(d, f)); + d.* = .{}; + } + + /// q, k clipped as prep leaves them, v rms-normed, the table rel . proj rounded once; stress: gate 4's rows. + pub fn make(d: *Data, a: std.mem.Allocator, lay: Layout, fill: g.Fill, seed: u64) !void { + const rows = lay.rows; + const ring: usize = lay.layer.ring; + d.pos = try a.alloc(usize, rows); + d.stream = try a.alloc(usize, rows); + for (0..rows) |r| { + d.stream[r] = lay.streamOf(r); + d.pos[r] = lay.posOf(r); + } + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + const stress = fill == .stress; + d.q = try a.alloc(u16, rows * heads * D); + d.kc = try a.alloc(u16, lay.streams * kv * ring * D); + d.vc = try a.alloc(u16, d.kc.len); + d.tab = try a.alloc(u16, rows * heads * ref.extent); + d.sink = try a.alloc(u16, rows * heads); + d.gate = try a.alloc(u16, rows * heads * D); + const amp: f64 = if (fill == .nonfinite) 0.3 else 3; // non-finite rows: no p underflows, so 0 x inf never meets + var x: [D]f64 = undefined; + for (0..rows * heads) |rh| { + for (&x) |*v| v.* = if (stress) 0 else rng.floatNorm(f64) * amp; + const f = ref.clipFactor(&x, ref.qk_clip); + for (d.q[rh * D ..][0..D], x) |*o, v| o.* = ref.bits(v * f); // q/k L2 clip, then one bf16 rounding + } + for (0..lay.streams * kv * ring) |slot| { + for (&x) |*v| v.* = rng.floatNorm(f64) * 2.5; + const f = ref.clipFactor(&x, ref.qk_clip); + for (d.kc[slot * D ..][0..D], x) |*o, v| o.* = ref.bits(v * f); + var ss: f64 = 0; + for (&x) |*v| { + v.* = rng.floatNorm(f64); + ss += v.* * v.*; + } + const inv = 1 / @sqrt(ss / D + ref.eps); + const col0 = (slot / ring % kv) * D; + for (d.vc[slot * D ..][0..D], x, 0..) |*o, v, dd| o.* = ref.bits(if (stress) periodic(slot % ring, col0 + dd) else v * inv); + } + var proj: [ref.d_rel * ref.extent]f64 = undefined; + for (&proj) |*p| p.* = ref.rn(rng.floatNorm(f64) * 0.5); + var rel: [ref.d_rel]f64 = undefined; + for (0..rows * heads) |rh| { + for (&rel) |*v| v.* = rng.floatNorm(f64); + const f = ref.clipFactor(&rel, ref.rel_clip); + for (&rel) |*v| v.* = ref.rn(v.* * f); + for (d.tab[rh * ref.extent ..][0..ref.extent], 0..) |*o, dd| { + var acc: f64 = 0; + for (rel, 0..) |rv, j| acc += rv * proj[j * ref.extent + dd]; + o.* = if (stress) 0 else ref.bits(acc); // the bf16 table: rel . proj rounded once (transformers' bf16 matmul) + } + d.sink[rh] = if (stress) 0xff80 else ref.bits(8 + 16 * rng.float(f64)); // a raw logit + for (d.gate[rh * D ..][0..D]) |*o| o.* = ref.bits(if (stress) 32 else rng.floatNorm(f64) * 2); // raw, pre-sigmoid + } + if (fill == .nonfinite) d.plantNonfinite(ring); + } + + /// NaN q, a +inf sink, both gate infinities, +inf in a key and +inf, -inf in values every row of stream 0 sees. + fn plantNonfinite(d: *Data, ring: usize) void { + const nan = c.toBf16(std.math.nan(f32)); + if (d.pos.len > 3) { + d.sink[3 * heads + 4] = nan; + d.gate[(3 * heads + 5) * D + 7] = nan; + } + const inf = c.toBf16(std.math.inf(f32)); + const rows = d.pos.len; + const p0 = d.pos[0]; + const at = struct { + fn f(kvh: usize, slot: usize, dd: usize, r: usize) usize { + return (kvh * r + slot) * D + dd; + } + }.f; + d.q[(0 * heads + 1) * D + 5] = nan; + if (rows > 1) d.sink[1 * heads + 2] = inf; + if (rows > 2) { + d.gate[(2 * heads + 3) * D + 0] = inf; + d.gate[(2 * heads + 3) * D + 1] = inf | 0x8000; + } + d.kc[at(2, p0 % ring, 7, ring)] = inf; + d.vc[at(1, p0 % ring, 9, ring)] = inf; + d.vc[at(1, p0 % ring, 10, ring)] = inf; + if (p0 > 0) d.vc[at(1, (p0 - 1) % ring, 10, ring)] = inf | 0x8000; + } +}; + +/// The device's score of a bias with q = 0: (0 scale + bias) log2e, rounded once in fp32 (tile.hpp's score). +fn score(b: u16) f32 { + const log2e: f32 = 1.4426950408889634; + return @as(f32, @floatCast(ref.bf(b))) * log2e; +} + +/// bf16(exp2f(d)) when certain: the exact power sits over 2^-21 (4 fp32 ulp, past exp2f's error) from a tie. +fn roundedP(d: f32) ?f64 { + const e = std.math.exp2(@as(f64, d)); + const lo = ref.rn(e * (1 - 0x1p-21)); + return if (lo == ref.rn(e * (1 + 0x1p-21))) lo else null; +} + +/// Exact-P rows (one 64-key tile, pos < 64): bias 2 at distance 0 (the max), the rest drawn where bf16 P is certain. +fn fillExactP(d: *Data, a: std.mem.Allocator, lay: Layout, seed: u64) !void { + try d.make(a, lay, .random, seed); + var prng = std.Random.DefaultPrng.init(seed ^ 0x9e3779b97f4a7c15); + const rng = prng.random(); + @memset(d.q, 0); // every score is its bias: q.k = 0 + @memset(d.sink, 0xff80); // no sink, so the merge's rescale is exp2(0) = 1 + @memset(d.gate, ref.bits(32)); // sigmoid(32) is 1 in fp32 + for (d.vc) |*o| o.* = ref.bits(@floatFromInt(rng.intRangeAtMost(i32, -16, 16))); + const top = ref.bits(2); + for (0..d.sink.len) |rh| { + const t = d.tab[rh * ref.extent ..][0..ref.extent]; + t[0] = top; + for (t[1..]) |*o| { // biases in [-1, 1.75]: every P in [2^-5, 1), its bf16 lsb at least 2^-12 + o.* = ref.bits(-1 + 2.75 * rng.float(f64)); + while (roundedP(score(o.*) - score(top)) == null) o.* = ref.bits(-1 + 2.75 * rng.float(f64)); + } + } +} + +/// An exact-P row's outputs: sum bf16(P) v and sum bf16(P) are exact in fp32 (23 bits), so out = bf16(fp32(o / l)). +pub fn exactP(call: *const ref.Call, r: usize, h: usize, out: []f64) void { + const pos = call.pos[r]; + const lo = if (call.window > 0) (pos + 1) -| call.window else 0; + const t = call.tab[(r * heads + h) * ref.extent ..][0..ref.extent]; + const base = (call.stream[r] * kv + h / group) * call.ring; + var o: [D]f64 = @splat(0); + var l: f64 = 0; + for (lo..pos + 1) |p| { + const w = roundedP(score(t[pos - p]) - score(t[0])).?; + l += w; + for (&o, call.v[(base + p % call.ring) * D ..][0..D]) |*x, v| x.* += w * ref.bf(v); + } + for (out, o) |*y, x| y.* = c.fromBf16(c.toBf16(@as(f32, @floatCast(x)) / @as(f32, @floatCast(l)))); +} + +/// The reference's (row, head) pairs (gate 4: (row, key head) pairs) over up to six threads, each its own buffers. +pub const Pool = struct { + call: *const ref.Call, + want: []f64, + tol: []f64, + sim: ?struct { acc: c.Accum, order: g.Order } = null, + + const Job = struct { + pool: *const Pool, + first: usize, + step: usize, + items: usize, + ks: *ref.Keys, + p: []f64, + col: []f64, + + pub fn run(j: *Job) void { + const pool = j.pool; + var i = j.first; + while (i < j.items) : (i += j.step) { + if (pool.sim) |s| { + const r = i / kv; + const h0 = (i % kv) * group; + const o = pool.want[(r * heads + h0) * D ..][0..D]; + ref.simulate(pool.call, r, h0, s.acc, s.order, j.p, j.col, o); + for (1..group) |e| @memcpy(pool.want[(r * heads + h0 + e) * D ..][0..D], o); + } else { + const at = i * D; + ref.row(pool.call, i / heads, i % heads, j.ks, pool.want[at..][0..D], pool.tol[at..][0..D]); + } + } + } + }; + + pub fn run(a: std.mem.Allocator, pool: Pool, items: usize) !void { + const n = contract.reference_threads.count(6, items); + var jobs: [contract.reference_threads.maximum]Job = undefined; + var keys: usize = 0; + for (pool.call.pos) |p| keys = @max(keys, p + 1); + var made: usize = 0; + defer for (jobs[0..made]) |j| { + a.destroy(j.ks); + a.free(j.p); + a.free(j.col); + }; + for (jobs[0..n], 0..) |*j, w| { + const big = if (pool.sim != null) keys else 0; + j.* = .{ .pool = &pool, .first = w, .step = n, .items = items, .ks = try a.create(ref.Keys), .p = try a.alloc(f64, big), .col = try a.alloc(f64, big) }; + made += 1; + } + contract.reference_threads.run(Job, jobs[0..n], .normal); + } +}; + +test "HIP inkling2 layout: three streams' rows, positions and cache offsets" { + const l = Layout.of(K.Layer.sliding(1024, 2048), 10, 20000, 3); + try std.testing.expectEqual([3]i32{ 0, 4, 7 }, [3]i32{ l.segs[0].row0, l.segs[1].row0, l.segs[2].row0 }); + try std.testing.expectEqual(@as(usize, 19999), l.posOf(3)); + try std.testing.expectEqual(@as(usize, 9997), l.posOf(4)); + try std.testing.expectEqual(@as(usize, 2), l.streamOf(9)); + try std.testing.expectEqual(@as(i64, 2 * 3072 * 8 * 128), l.segs[2].off); + const one = Layout.of(K.Layer.sliding(1024, 2048), 5, 300, 1); + try std.testing.expectEqual(@as(i32, 5), one.segs[0].n); + try std.testing.expectEqual(@as(usize, 0), one.streamOf(4)); +} + +test "HIP inkling2 exact P: the outputs follow bf16 P's bits, and an unrounded P moves over a quarter of them" { + const a = std.testing.allocator; + const lay = Layout.of(K.Layer.sliding(1024, 2048), 16, 64, 2); + var d: Data = .{}; + defer d.free(a); + try d.makeExactP(a, lay, 7); + const call: ref.Call = .{ .q = d.q, .k = d.kc, .v = d.vc, .tab = d.tab, .sink = d.sink, .gate = d.gate, .pos = d.pos, .stream = d.stream, .ring = lay.layer.ring, .window = lay.layer.window, .heads = heads, .kv = kv, .chain = .hip }; + var want: [D]f64 = undefined; + var moved: usize = 0; + for (0..16 * heads) |rh| { + const r = rh / heads; + const h = rh % heads; + exactP(&call, r, h, &want); + const pos = d.pos[r]; + const t = d.tab[rh * ref.extent ..][0..ref.extent]; + const base = (d.stream[r] * kv + h / group) * lay.layer.ring; + var o: [D]f64 = @splat(0); + var l: f64 = 0; + for (0..pos + 1) |p| { // the same rows with P left unrounded + const w = std.math.exp2(@as(f64, score(t[pos - p]) - score(t[0]))); + l += w; + for (&o, d.vc[(base + p % lay.layer.ring) * D ..][0..D]) |*x, v| x.* += w * ref.bf(v); + } + for (want, o) |x, y| moved += @intFromBool(x != c.fromBf16(c.toBf16(@floatCast(y / l)))); + } + try std.testing.expect(moved * 4 > 16 * heads * D); // 19,232 of 49,152 at this seed +} diff --git a/zig/tests/hip/contract_inkling2_prep.zig b/zig/tests/hip/contract_inkling2_prep.zig new file mode 100644 index 00000000000..5f8196d667c --- /dev/null +++ b/zig/tests/hip/contract_inkling2_prep.zig @@ -0,0 +1,432 @@ +//! Inkling 2's HIP attention inputs under the contract: tf_ink2_prep (q, rel, k, v rows) and tf_ink2_rel_table. +const std = @import("std"); +const core = @import("core"); +const K = @import("inkling2_hip"); +const Rig = @import("contract_rig.zig").Rig; +const fill_ = @import("contract_inkling2_fill.zig"); + +const contract = core.contract; +const ref = contract.inkling2_attn_ref; +const c = contract.spec; +const g = contract.gates; +const D = ref.D; +const heads = fill_.heads; +const kv = fill_.kv; +const R = ref.d_rel; +const u: f64 = 0x1p-24; + +fn sh(rows: usize, k: usize) c.Shape { + return .{ .rows = rows, .n = heads * D, .k = k }; +} + +const prep_shapes = [_]c.Shape{ sh(16, 300000), sh(2048, 2048), sh(1, 1048576), sh(128, 1048576), sh(2048, 1048576), sh(7, 8192), sh(4, 8193), sh(2, 8194) }; +const apart_shapes = [_]c.Shape{ sh(16, 300000), sh(128, 1048576), sh(9, 20000) }; +const nan_rule = "a NaN in a q, k or rel head stays NaN and leaves the head's other values unclipped (fminf drops the NaN " ++ + "norm, where transformers' clamp gives NaN); an infinity makes its head 0 and itself NaN; v rows propagate"; + +fn depthPrep(_: c.Shape) usize { + return 4 + 5; // a lane's four squares, then the wave's five butterfly adds +} + +/// rows x 24 heads x 128 (q); k: the first stream's context, so global rows meet tau (floor 8,192) at 1M positions. +pub fn prepSpec(global: bool, apart: bool) c.Spec { + const name = if (apart) "inkling2 hip attn tf_ink2_prep global: three streams' rows and caches in one launch" else if (global) "inkling2 hip attn tf_ink2_prep global (q, rel scaled by tau; k, v into a 4,096-slot ring)" else "inkling2 hip attn tf_ink2_prep sliding (q, rel, k, v rows into the 3,072-slot ring)"; + const why = "a head's sum of squares only scales it: a bf16 sum's error stays under the bf16 output's rounding"; + var s: c.Spec = .{ .name = name, .accum = .f32, .depth = depthPrep, .ops = 16, .out = .bf16, .served = &prep_shapes, .nan = .{ .stated = nan_rule }, .sums = .{ .f16 = 100, .bf16 = 0, .why = why } }; + if (apart) { + s.served = &apart_shapes; + s.replaces = "tf_ink2_prep one stream at a time, at each stream's row and cache offsets"; + } + return s; +} + +/// A prep control's fault: alpha 0 on the device, or stream 1's rows written at stream 0's cache offset. +pub const Fault = enum { none, tau_off, cross_write }; + +/// tf_ink2_prep as the forward calls it: raw projections in, prepared q and rel out, k and v into the rows' slots. +pub const Prep = struct { + rig: Rig, + k: *const K.Kernels, + global: bool, + apart: bool = false, + fault: Fault = .none, + shape: c.Shape = undefined, + fill: g.Fill = .random, + lay: fill_.Layout = undefined, + raw: [4][]u16 = .{ &.{}, &.{}, &.{}, &.{} }, // q [rows][24][128], k, v [rows][8][128], rel [rows][24][16] + scales: [2][]u16 = .{ &.{}, &.{} }, // q_scale [24][128], rel_scale [24][16] + pos: []usize = &.{}, + stream: []usize = &.{}, + want: []f64 = &.{}, + lo: []f64 = &.{}, + hi: []f64 = &.{}, + zeros: []u8 = &.{}, + dev: [5]u64 = @splat(0), // pos, seg_of, segs (the device's: a control's faulted copy), zeros' seg_of, the base + alone: [3]u64 = @splat(0), // each stream's segment from row 0 + in: [6]u64 = @splat(0), + out: [4]u64 = @splat(0), // q, rel, kc, vc + msg: [160]u8 = undefined, + + pub fn deinit(self: *Prep) void { + self.free(); + self.rig.deinit(); + } + + fn free(self: *Prep) void { + const a = self.rig.a; + for (&self.raw) |*x| a.free(x.*); + for (&self.scales) |*x| a.free(x.*); + self.raw = .{ &.{}, &.{}, &.{}, &.{} }; + self.scales = .{ &.{}, &.{} }; + inline for (.{ "pos", "stream", "want", "lo", "hi", "zeros" }) |f| { + a.free(@field(self, f)); + @field(self, f) = &.{}; + } + } + + pub fn kernel(self: *Prep) g.Kernel { + var s = prepSpec(self.global, self.apart); + switch (self.fault) { + .none => {}, + .tau_off => s.name = "control: inkling2 hip attn tf_ink2_prep global rows without tau", + .cross_write => s.name = "control: inkling2 hip attn tf_ink2_prep writing stream 1's k, v into stream 0's slots", + } + return .{ .spec = s, .ctx = self, .vt = &vt, .control = if (self.fault == .none) null else .shapes }; + } + + const vt = g.hooks(Prep); + + fn sizes(self: *const Prep) [4]usize { + const rows = self.shape.rows; + const cache = self.lay.streams * kv * @as(usize, self.lay.layer.ring) * D; + return .{ rows * heads * D, rows * heads * R, cache, cache }; + } + + pub fn count(self: *const Prep) usize { + const s = self.sizes(); + return s[0] + s[1] + s[2] + s[3]; + } + + /// Projections as N(0, 3) (most heads clip), scales in [0.5, 3); stress: integers to 256, every partial sum exact. + pub fn prepare(self: *Prep, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.n != heads * D or shape.rows == 0 or shape.k < shape.rows) return false; + if (self.apart and shape.rows < 3) return false; + self.free(); + self.rig.reset(); + self.shape = shape; + self.fill = fill; + const a = self.rig.a; + const rows = shape.rows; + const layer: K.Layer = if (self.global) .{ .window = 0, .ring = fill_.global_ring, .chunk = 0, .tau = true } else .{ .window = 1024, .ring = K.Layer.sliding(1024, 2048).ring, .chunk = 0, .tau = false }; + const streams: usize = if (self.apart) 3 else if (rows >= 2 and rows <= 128) 2 else 1; + self.lay = fill_.Layout.of(layer, rows, shape.k, streams); + self.pos = try a.alloc(usize, rows); + self.stream = try a.alloc(usize, rows); + const pos32 = try a.alloc(i32, 2 * rows); + defer a.free(pos32); + for (0..rows) |r| { + self.stream[r] = self.lay.streamOf(r); + self.pos[r] = self.lay.posOf(r); + pos32[r] = @intCast(self.pos[r]); + pos32[rows + r] = @intCast(self.stream[r]); + } + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + const lens = [4]usize{ rows * heads * D, rows * kv * D, rows * kv * D, rows * heads * R }; + for (&self.raw, lens, 0..) |*x, n, w| { + x.* = try a.alloc(u16, n); + for (x.*, 0..) |*v, i| v.* = ref.bits(switch (fill) { + .stress => @floatFromInt(if (i % 64 == w) @as(i32, 256) else @as(i32, @intCast(rng.uintLessThan(u32, 511))) - 255), + else => rng.floatNorm(f64) * 3, + }); + } + for (&self.scales, [2]usize{ heads * D, heads * R }) |*x, n| { + x.* = try a.alloc(u16, n); + for (x.*) |*v| v.* = ref.bits(if (fill == .stress) 1 else 0.5 + 2.5 * rng.float(f64)); + } + if (fill == .nonfinite) { + const nan = c.toBf16(std.math.nan(f32)); + const inf = c.toBf16(std.math.inf(f32)); + self.raw[0][(0 * heads + 1) * D + 3] = nan; + if (rows > 1) self.raw[1][(1 * kv + 0) * D + 5] = inf; + if (rows > 2) self.raw[2][(2 * kv + 1) * D + 0] = inf | 0x8000; + if (rows > 2) self.raw[2][(2 * kv + 1) * D + 1] = inf; + if (rows > 3) self.raw[3][(3 * heads + 0) * R + 2] = nan; + } + var segs = self.lay.segs; + if (self.fault == .cross_write) segs[1].off = segs[0].off; + self.dev[0] = try self.rig.input(std.mem.sliceAsBytes(pos32[0..rows])); + self.dev[1] = try self.rig.input(std.mem.sliceAsBytes(pos32[rows..])); + self.dev[2] = try self.rig.input(std.mem.sliceAsBytes(segs[0..streams])); + for (self.raw, 0..) |x, i| self.in[i] = try self.rig.input(std.mem.sliceAsBytes(x)); + for (self.scales, 0..) |x, i| self.in[4 + i] = try self.rig.input(std.mem.sliceAsBytes(x)); + const sz = self.sizes(); + for (&self.out, sz) |*o, n| o.* = try self.rig.output(n * 2); + self.zeros = try a.alloc(u8, sz[2] * 2); + @memset(self.zeros, 0); + if (self.apart) { + @memset(pos32[rows..], 0); + self.dev[3] = try self.rig.input(std.mem.sliceAsBytes(pos32[rows..])); + self.dev[4] = try self.rig.scratch(self.count() * 2); + for (self.lay.segs, &self.alone) |s, *x| { + var one = s; + one.row0 = 0; + x.* = try self.rig.input(std.mem.asBytes(&one)); + } + } + return true; + } + + fn config(self: *const Prep) K.Prep { + const alpha: f32 = if (self.fault == .tau_off) 0 else @floatCast(ref.alpha); + return .{ .qk_clip = @floatCast(ref.qk_clip), .rel_clip = @floatCast(ref.rel_clip), .floor = @floatCast(fill_.floor_pos), .alpha = alpha, .eps = @floatCast(ref.eps) }; + } + + pub fn run(self: *Prep) !void { + try self.rig.put(self.out[2], self.zeros); // slots no row writes stay 0, so a stray write shows + try self.rig.put(self.out[3], self.zeros); + const r: K.Rows = .{ .rows = @intCast(self.shape.rows), .heads = heads, .kv_heads = kv, .pos = self.dev[0], .seg_of = self.dev[1], .segs = self.dev[2], .tiles = 0, .n_tiles = 0, .last_pos = @intCast(self.shape.k - 1), .streams = @intCast(self.lay.streams) }; + try K.prep(self.k, self.rig.s, r, self.lay.layer, self.config(), self.in[0..4].*, self.in[4..6].*, self.out[0], self.out[1], .{ .k = self.out[2], .v = self.out[3] }); + try self.rig.s.synchronize(); + } + + /// Each stream's rows alone, at its row offsets into the inputs and outputs and its segment's cache offset. + pub fn replaced(self: *Prep) ![]const u8 { + const sz = self.sizes(); + const base = self.dev[4]; + const at = [4]u64{ base, base + sz[0] * 2, base + (sz[0] + sz[1]) * 2, base + (sz[0] + sz[1] + sz[2]) * 2 }; + try self.rig.put(at[2], self.zeros); + try self.rig.put(at[3], self.zeros); + for (self.lay.segs, self.alone) |s, one| { + const r0: u64 = @intCast(s.row0); + const r: K.Rows = .{ .rows = @intCast(s.n), .heads = heads, .kv_heads = kv, .pos = self.dev[0] + r0 * 4, .seg_of = self.dev[3], .segs = one, .tiles = 0, .n_tiles = 0, .last_pos = @intCast(s.p0 + s.n - 1), .streams = 1 }; + const raw = [4]u64{ self.in[0] + r0 * heads * D * 2, self.in[1] + r0 * kv * D * 2, self.in[2] + r0 * kv * D * 2, self.in[3] + r0 * heads * R * 2 }; + try K.prep(self.k, self.rig.s, r, self.lay.layer, self.config(), raw, self.in[4..6].*, at[0] + r0 * heads * D * 2, at[1] + r0 * heads * R * 2, .{ .k = at[2], .v = at[3] }); + } + return self.rig.bytes(base, self.count() * 2); + } + + /// One head's outputs: x (bf16 products, exact in fp32) times its clip factor, rounded; tau after a first rounding. + fn head(self: *Prep, x: []f64, thr: f64, t: ?f64, at: usize, acc: ?c.Accum, order: g.Order) void { + var sq: [D]f64 = undefined; + for (sq[0..x.len], x) |*s, v| s.* = v * v; + const ss = if (acc) |k| contract.rows.sumIn(k, order, sq[0..x.len]) else contract.rows.sumIn(.none, .sequential, sq[0..x.len]); + const f = ref.minNum(thr / (@sqrt(ss) + 1e-6), 1); // the L2 clip's factor: fp32 sums, sqrt, add, divide, fminf + for (x, 0..) |v, i| self.put(at + i, v * f, t, 12 * u); + } + + /// Output i from its fp32 value v (relative error eps before rounding): rn(v), or rn(rn(v) tau) on global rows. + fn put(self: *Prep, i: usize, v: f64, t: ?f64, eps: f64) void { + const one = [2]f64{ ref.rn(v - @abs(v) * eps), ref.rn(v + @abs(v) * eps) }; // bf16 of each end: rounding is monotone + if (t) |tv| { + self.want[i] = ref.rn(ref.rn(v) * tv); + const ends = [2]f64{ one[0] * tv, one[1] * tv }; // tau in fp32 (logf, divide, fmaxf, product, add): 8u wider + self.lo[i] = ref.rn(ends[0] - @abs(ends[0]) * 8 * u); + self.hi[i] = ref.rn(ends[1] + @abs(ends[1]) * 8 * u); + } else { + self.want[i] = ref.rn(v); + self.lo[i] = one[0]; + self.hi[i] = one[1]; + } + } + + /// float64 prep at the device's rounding points (want), and the range its fp32 steps allow (lo, hi). + fn compute(self: *Prep, acc: ?c.Accum, order: g.Order) !void { + const a = self.rig.a; + const n = self.count(); + inline for (.{ "want", "lo", "hi" }) |f| { + a.free(@field(self, f)); + @field(self, f) = try a.alloc(f64, n); + @memset(@field(self, f), 0); + } + const sz = self.sizes(); + const ring: usize = self.lay.layer.ring; + var x: [D]f64 = undefined; + for (0..self.shape.rows) |r| { + const t: ?f64 = if (self.global) ref.tauAt(self.pos[r], fill_.floor_pos) else null; + for (0..heads) |h| { + for (x[0..D], 0..) |*v, i| v.* = ref.bf(self.raw[0][(r * heads + h) * D + i]) * ref.bf(self.scales[0][h * D + i]); + self.head(x[0..D], ref.qk_clip, t, (r * heads + h) * D, acc, order); + for (x[0..R], 0..) |*v, i| v.* = ref.bf(self.raw[3][(r * heads + h) * R + i]) * ref.bf(self.scales[1][h * R + i]); + self.head(x[0..R], ref.rel_clip, t, sz[0] + (r * heads + h) * R, acc, order); + } + for (0..kv) |h| { + const slot = ((self.stream[r] * kv + h) * ring + self.pos[r] % ring) * D; + for (x[0..D], 0..) |*v, i| v.* = ref.bf(self.raw[1][(r * kv + h) * D + i]); + self.head(x[0..D], ref.qk_clip, null, sz[0] + sz[1] + slot, acc, order); // k: the clip alone + var sq: [D]f64 = undefined; + for (&sq, x[0..D], 0..) |*s, *v, i| { + v.* = ref.bf(self.raw[2][(r * kv + h) * D + i]); + s.* = v.* * v.*; + } + const ss = if (acc) |k| contract.rows.sumIn(k, order, &sq) else contract.rows.sumIn(.none, .sequential, &sq); + const inv = 1 / @sqrt(ss / D + ref.eps); // v's RMS norm: fp32 sums, then rsqrtf within 2 ulp + for (x[0..D], 0..) |v, i| self.put(sz[0] + sz[1] + sz[2] + slot + i, v * inv, null, 16 * u); + } + } + } + + pub fn reference(self: *Prep, want: []f64, mag: []f64) !void { + try self.compute(null, .sequential); + @memcpy(want, self.want); + for (mag, want) |*m, w| m.* = @abs(w); + } + + pub fn bounds(self: *Prep, want: []const f64, _: []const f64, allow: []f64) !void { + for (allow, want, self.lo, self.hi) |*l, w, lo, hi| l.* = if (std.math.isFinite(w)) @max(@abs(lo - w), @abs(hi - w)) + 0x1p-140 else std.math.floatMax(f64); + } + + pub fn intervals(self: *Prep, low: []f64, high: []f64) !void { + for (low, high, self.lo, self.hi) |*l, *h, lo, hi| { + l.* = @min(lo, hi); + h.* = @max(lo, hi); + } + } + + pub fn simulate(self: *Prep, acc: c.Accum, order: g.Order, out: []f64) !void { + try self.compute(acc, order); + @memcpy(out, self.want); + try self.compute(null, .sequential); // the kernel's run is then checked against float64's ranges, not the replay's + } + + /// The stated rule: classes as float64 prep with fminf's NaN rule; at shapes, each output inside its range. + pub fn check(self: *Prep, at: g.Gate) !?[]const u8 { + try self.compute(null, .sequential); + const out = try self.rig.outputBytes(); + var planted: usize = 0; + for (self.want, self.lo, self.hi, 0..) |w, lo, hi, i| { + const got = c.read(.bf16, out, i); + if (c.classOf(w) != .finite) planted += 1; + if (c.classOf(got) != c.classOf(w)) return std.fmt.bufPrint(&self.msg, "output {d} is {e} where the rule gives {e}", .{ i, got, w }) catch "a class differs"; + if (at == .shapes and std.math.isFinite(w) and !(got >= @min(lo, hi) and got <= @max(lo, hi))) + return std.fmt.bufPrint(&self.msg, "output {d} is {e}, outside [{e}, {e}] (float64 {e})", .{ i, got, @min(lo, hi), @max(lo, hi), w }) catch "an output leaves its range"; + } + if (at == .nonfinite and planted == 0) return "the planted values give no non-finite output: no proof"; + return null; + } +}; + +const table_shapes = [_]c.Shape{ .{ .rows = 16, .n = heads * ref.extent, .k = R }, .{ .rows = 2048, .n = heads * ref.extent, .k = R }, .{ .rows = 1, .n = heads * ref.extent, .k = R }, .{ .rows = 128, .n = heads * ref.extent, .k = R } }; + +fn depthTable(_: c.Shape) usize { + return R; // a product and an add a rel value, in tap order +} + +pub fn tableSpec() c.Spec { + return .{ .name = "inkling2 hip attn tf_ink2_rel_table (bf16 bias of each (row, head) at distances 0..1023)", .accum = .f32, .depth = depthTable, .out = .bf16, .served = &table_shapes }; +} + +/// tf_ink2_rel_table: tab[rh][d] = bf16(sum_j rel[rh][j] proj[j][d]), proj the layer's rel_logits_proj [16][1024]. +pub const Table = struct { + rig: Rig, + k: *const K.Kernels, + late: bool = false, // control: the device reads proj one column late + shape: c.Shape = undefined, + rel: []u16 = &.{}, + proj: []u16 = &.{}, + in: [3]u64 = @splat(0), // rel, proj, the device's proj + out: u64 = 0, + + pub fn deinit(self: *Table) void { + const a = self.rig.a; + a.free(self.rel); + a.free(self.proj); + self.rig.deinit(); + } + + pub fn kernel(self: *Table) g.Kernel { + var s = tableSpec(); + if (self.late) s.name = "control: inkling2 hip attn tf_ink2_rel_table reading rel_logits_proj one column late"; + return .{ .spec = s, .ctx = self, .vt = &vt, .control = if (self.late) .shapes else null }; + } + + const vt = g.hooks(Table); + + pub fn count(self: *const Table) usize { + return self.shape.rows * heads * ref.extent; + } + + /// rel as prep leaves it (clipped to 8), proj N(0, 0.5); stress: 512 x odd mirrored a step along, proj 1 or 2. + pub fn prepare(self: *Table, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.n != heads * ref.extent or shape.k != R or shape.rows == 0) return false; + const a = self.rig.a; + a.free(self.rel); + a.free(self.proj); + self.rel = &.{}; + self.proj = &.{}; + self.rig.reset(); + self.shape = shape; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + const n = shape.rows * heads; + self.rel = try a.alloc(u16, n * R); + self.proj = try a.alloc(u16, R * ref.extent); + for (self.proj, 0..) |*p, i| p.* = ref.bits(if (fill == .stress) projStress(i / ref.extent, i % ref.extent) else rng.floatNorm(f64) * 0.5); + var x: [R]f64 = undefined; + for (0..n) |rh| { + for (&x, 0..) |*v, j| v.* = if (fill == .stress) relStress(rh, j) else rng.floatNorm(f64); + const f = if (fill == .stress) 1 else ref.clipFactor(&x, ref.rel_clip); + for (self.rel[rh * R ..][0..R], x) |*o, v| o.* = ref.bits(v * f); + } + if (fill == .nonfinite) { + self.rel[0 * R + 3] = c.toBf16(std.math.nan(f32)); + self.rel[1 * R + 5] = c.toBf16(std.math.inf(f32)); + self.rel[2 * R + 0] = c.toBf16(std.math.inf(f32)); + self.rel[2 * R + 1] = c.toBf16(-std.math.inf(f32)); + } + self.in[0] = try self.rig.input(std.mem.sliceAsBytes(self.rel)); + self.in[1] = try self.rig.input(std.mem.sliceAsBytes(self.proj)); + self.in[2] = self.in[1]; + if (self.late) { + const t = try a.alloc(u16, self.proj.len); + defer a.free(t); + for (t, 0..) |*v, i| v.* = if (i % ref.extent + 1 < ref.extent) self.proj[i + 1] else 0; + self.in[2] = try self.rig.input(std.mem.sliceAsBytes(t)); + } + self.out = try self.rig.output(self.count() * 2); + return true; + } + + fn projStress(j: usize, d: usize) f64 { + const jj = if (j >= 8) (j - 8 + 1) % 8 else j; + return @floatFromInt(1 + (jj * 7 + d) % 2); + } + + fn relStress(rh: usize, j: usize) f64 { + if (j < 8) return 512 * @as(f64, @floatFromInt(2 * ((rh * 5 + j * 3) % 64) + 1)); + return -relStress(rh, (j - 8 + 1) % 8) + @as(f64, if (j == 8) 512 else 0); + } + + pub fn run(self: *Table) !void { + const r: K.Rows = .{ .rows = @intCast(self.shape.rows), .heads = heads, .kv_heads = kv, .pos = 0, .seg_of = 0, .segs = 0, .tiles = 0, .n_tiles = 0, .last_pos = 0, .streams = 1 }; + try K.relTable(self.k, self.rig.s, r, self.in[0], self.in[2], self.out); + try self.rig.s.synchronize(); + } + + fn terms(self: *const Table, o: usize, t: *[R]f64) void { + const rh = o / ref.extent; + const d = o % ref.extent; + for (t, 0..) |*v, j| v.* = ref.bf(self.rel[rh * R + j]) * ref.bf(self.proj[j * ref.extent + d]); // exact in fp32 + } + + pub fn reference(self: *Table, want: []f64, mag: []f64) !void { + var t: [R]f64 = undefined; + for (want, mag, 0..) |*w, *m, o| { + self.terms(o, &t); + w.* = 0; + m.* = 0; + for (t) |v| { + w.* += v; + m.* += @abs(v); + } + } + } + + pub fn simulate(self: *Table, acc: c.Accum, order: g.Order, out: []f64) !void { + var t: [R]f64 = undefined; + for (out, 0..) |*v, o| { + self.terms(o, &t); + v.* = contract.rows.sumIn(acc, order, &t); + } + } +}; diff --git a/zig/tests/hip/contract_inkling2_rows.zig b/zig/tests/hip/contract_inkling2_rows.zig new file mode 100644 index 00000000000..c0c86eefa05 --- /dev/null +++ b/zig/tests/hip/contract_inkling2_rows.zig @@ -0,0 +1,330 @@ +//! Inkling 2's HIP attention launches under the contract at Mini's 24/8 heads: sliding, fold, split, prompt, the merge. +const std = @import("std"); +const core = @import("core"); +const K = @import("inkling2_hip"); +const Rig = @import("contract_rig.zig").Rig; +const Profile = @import("contract_entry.zig").Profile; +const fill_ = @import("contract_inkling2_fill.zig"); + +const contract = core.contract; +const ref = contract.inkling2_attn_ref; +const c = contract.spec; +const g = contract.gates; +const D = ref.D; +const heads = fill_.heads; +const kv = fill_.kv; +const n_out = heads * D; + +/// The launch kernels.attend picks: sliding chunks, a block a global chunk, a block a sub-chunk, one stream's prompt. +pub const Path = enum { sliding, fold, split, prompt }; + +/// A control's planted fault, through the device's inputs or launch only: the served kernels run as they are. +pub const Plant = enum { none, late_bias, no_sink, q_ulp, window_one, pre_sigmoid }; + +pub const fold_name = "inkling2 hip attn tf_ink2_attn_fold + tf_ink2_merge (global layers, 16,384-key chunks)"; + +/// Unused beside `bounds`: the reference derives each output's allowance from the device's own steps. +fn depth(_: c.Shape) usize { + return 16 * 65 + 2 * (16 + 64) + 8; +} + +fn sh(rows: usize, k: usize) c.Shape { + return .{ .rows = rows, .n = n_out, .k = k }; +} + +// served shapes: decode windows, long global spans to 1M keys on a 4,096-slot ring that wraps, and prompt chunks +const sliding_full = [_]c.Shape{ sh(16, 4096), sh(1, 1048576), sh(2048, 2048), sh(2048, 1048576), sh(128, 300000), sh(7, 1030), sh(1, 1), sh(3, 3) }; +const fold_full = [_]c.Shape{ sh(16, 20000), sh(1, 1048576), sh(128, 300000), sh(70, 16390), sh(2, 1048576), sh(16, 16), sh(5, 1024), sh(5, 1025), sh(3, 3) }; +const split_full = [_]c.Shape{ sh(16, 20000), sh(1, 1048576), sh(8, 1048576), sh(64, 70000), sh(33, 1030) }; +const prompt_full = [_]c.Shape{ sh(130, 20000), sh(1, 1048576), sh(2048, 2048), sh(2048, 18432), sh(256, 1048576) }; +const sliding_smoke = [_]c.Shape{ sh(16, 4096), sh(7, 1030), sh(2048, 2048) }; +// smoke keeps one 1M-key row: gate 4 sums over the longest served span, where bf16 sums miss by over 100x +const fold_smoke = [_]c.Shape{ sh(16, 20000), sh(70, 16390), sh(1, 1048576) }; +const split_smoke = [_]c.Shape{ sh(16, 20000), sh(33, 1030), sh(1, 1048576) }; +const prompt_smoke = [_]c.Shape{ sh(130, 20000), sh(2048, 2048), sh(1, 1048576) }; +// three streams in one launch: at least a row each +const apart_full = [_]c.Shape{ sh(16, 20000), sh(3, 1048576), sh(64, 70000), sh(9, 1030) }; +const apart_smoke = [_]c.Shape{ sh(16, 20000), sh(9, 1030), sh(3, 1048576) }; + +fn served(path: Path, apart: bool, profile: Profile) []const c.Shape { + const full = profile == .full; + if (apart) return if (full) &apart_full else &apart_smoke; + return switch (path) { + .sliding => if (full) &sliding_full else &sliding_smoke, + .fold => if (full) &fold_full else &fold_smoke, + .split => if (full) &split_full else &split_smoke, + .prompt => if (full) &prompt_full else &prompt_smoke, + }; +} + +// exact P: rows below position 64, one tile each; the outputs equal float64 bit for bit +const exact_shapes = [_]c.Shape{ sh(16, 64), sh(1, 64), sh(64, 64), sh(3, 40) }; + +/// The exact-P registrations: bf16 P's own bits decide every output, so an unrounded P goes red at shapes. +fn exactSpec(path: Path) c.Spec { + const why = "64 keys of gate 4's values: neither fp16 nor bf16 provably misses here; the 1M-key registrations prove fp32"; + var x: c.Spec = .{ .name = "", .accum = .f32, .depth = depth, .ops = 12, .out = .bf16, .served = &exact_shapes, .sums = .{ .f16 = 0, .bf16 = 0, .why = why } }; + x.tiles = .{ .{ .size = 4 }, .{}, .{} }; + x.name = if (path == .sliding) "inkling2 hip attn sliding rows at bf16 P's own bits (q 0, no sink, gate 1, integer v)" else "inkling2 hip attn global fold rows at bf16 P's own bits (q 0, no sink, gate 1, integer v)"; + return x; +} + +/// rows x 24 heads x 128 outputs; k: the first stream's context (its last row's position + 1). +pub fn spec(path: Path, apart: bool, profile: Profile) c.Spec { + const no: c.Tile = .{}; + const rows4: c.Tile = if (apart) .{ .size = 4, .min = 3 } else .{ .size = 4 }; // 12 pairs: three 4-pair tiles + var x: c.Spec = .{ .name = "", .accum = .f32, .depth = depth, .ops = 12, .out = .bf16, .served = served(path, apart, profile) }; + switch (path) { + .sliding => { + x.name = "inkling2 hip attn tf_ink2_attn + tf_ink2_merge (sliding layers: window 1,024, 256-key chunks)"; + x.tiles = .{ rows4, no, .{ .size = 1024 } }; + }, + .fold => { + x.name = fold_name; + x.tiles = .{ rows4, no, .{ .size = 16384 } }; + }, + .split => { + x.name = "inkling2 hip attn tf_ink2_attn split + tf_ink2_merge (global layers, a block a 1,024-key sub-chunk)"; + x.tiles = .{ rows4, no, .{ .size = 1024 } }; + x.replaces = fold_name; + }, + .prompt => { + x.name = "inkling2 hip attn tf_ink2_attn_prompt + tf_ink2_merge (one stream's prompt rows, 8 pairs a block)"; + x.tiles = .{ .{ .size = 8 }, no, .{ .size = 16384 } }; + x.replaces = fold_name; + }, + } + if (apart) { + x.name = switch (path) { + .sliding => "inkling2 hip attn sliding: three streams' rows and caches in one launch", + .fold => "inkling2 hip attn global fold: three streams' rows and caches in one launch", + .split => "inkling2 hip attn global split: three streams' rows and caches in one launch", + .prompt => unreachable, + }; + x.replaces = "the same launches one stream at a time, at each stream's row and cache offsets"; + } + return x; +} + +pub const Attn = struct { + rig: Rig, + k: *const K.Kernels, + path: Path, + plant: Plant = .none, + apart: bool = false, + exact_p: bool = false, // q 0, no sink, gate 1, integer v: each output bf16(fp32(sum bf16(P) v / sum bf16(P))) + profile: Profile = .full, + shape: c.Shape = undefined, + fill: g.Fill = .random, + lay: fill_.Layout = undefined, + data: fill_.Data = .{}, + tol: []f64 = &.{}, + dev: Dev = .{}, + alone: [3]Alone = undefined, + + const Dev = struct { q: u64 = 0, q_run: u64 = 0, kc: u64 = 0, vc: u64 = 0, tab: u64 = 0, tab_run: u64 = 0, sink: u64 = 0, sink_run: u64 = 0, gate: u64 = 0, gate_run: u64 = 0, pos: u64 = 0, seg_of: u64 = 0, segs: u64 = 0, tiles: u64 = 0, n_tiles: u32 = 0, po: u64 = 0, pml: u64 = 0, out: u64 = 0, base: u64 = 0 }; + /// One stream's own launch: its segment from row 0, and its tiles. + const Alone = struct { segs: u64, tiles: u64, n_tiles: u32 }; + + pub fn deinit(self: *Attn) void { + self.free(); + self.rig.deinit(); + } + + fn free(self: *Attn) void { + self.data.free(self.rig.a); + self.rig.a.free(self.tol); + self.tol = &.{}; + } + + pub fn kernel(self: *Attn) g.Kernel { + var s = if (self.exact_p) exactSpec(self.path) else spec(self.path, self.apart, self.profile); + s.name = switch (self.plant) { + .none => s.name, + .late_bias => "control: inkling2 hip attn sliding rows read each distance's bias one distance late", + .no_sink => "control: inkling2 hip attn global fold rows merged without their sink", + .q_ulp => "control: inkling2 hip attn prompt rows with one q value a bf16 step up (bit equality must see it)", + .window_one => "control: inkling2 hip attn sliding rows with a window one key long", + .pre_sigmoid => "control: inkling2 hip attn sliding rows given sigmoid(sink) and sigmoid(gate), as #4387's glue did", + }; + return .{ .spec = s, .ctx = self, .vt = &vt, .control = if (self.plant == .none) null else .shapes }; + } + + const vt = g.hooks(Attn); + + pub fn count(self: *const Attn) usize { + return self.shape.rows * n_out; + } + + fn call(self: *const Attn) ref.Call { + const d = &self.data; + return .{ .q = d.q, .k = d.kc, .v = d.vc, .tab = d.tab, .sink = d.sink, .gate = d.gate, .pos = d.pos, .stream = d.stream, .ring = self.lay.layer.ring, .window = self.lay.layer.window, .exact = self.fill == .stress, .heads = heads, .kv = kv, .chain = .hip }; + } + + /// The rows' streams (fill_.Layout), their inputs, and the device's buffers; false for a shape the path refuses. + pub fn prepare(self: *Attn, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.n != n_out or shape.rows == 0 or shape.k < shape.rows) return false; + if (self.path == .split and shape.rows > K.split_rows) return false; + if (self.apart and shape.rows < 3) return false; + self.free(); + self.rig.reset(); + self.shape = shape; + self.fill = fill; + const a = self.rig.a; + const rows = shape.rows; + const layer: K.Layer = if (self.path == .sliding) K.Layer.sliding(1024, 2048) else .{ .window = 0, .ring = fill_.global_ring, .chunk = K.global_chunk, .tau = true }; + const streams: usize = if (self.apart) 3 else if (self.path != .prompt and rows >= 2 and rows <= 128) 2 else 1; + self.lay = fill_.Layout.of(layer, rows, shape.k, streams); + if (self.exact_p and fill == .random) try self.data.makeExactP(a, self.lay, seed) else try self.data.make(a, self.lay, fill, seed); + const d = &self.dev; + const td = &self.data; + d.q = try self.rig.input(std.mem.sliceAsBytes(td.q)); + d.kc = try self.rig.input(std.mem.sliceAsBytes(td.kc)); + d.vc = try self.rig.input(std.mem.sliceAsBytes(td.vc)); + d.tab = try self.rig.input(std.mem.sliceAsBytes(td.tab)); + d.sink = try self.rig.input(std.mem.sliceAsBytes(td.sink)); + d.gate = try self.rig.input(std.mem.sliceAsBytes(td.gate)); + const pos32 = try a.alloc(i32, rows); + defer a.free(pos32); + for (pos32, td.pos) |*p, v| p.* = @intCast(v); + d.pos = try self.rig.input(std.mem.sliceAsBytes(pos32)); + const segs = self.lay.segs[0..streams]; + d.segs = try self.rig.input(std.mem.sliceAsBytes(segs)); + const tiles = try a.alloc(K.Tile, K.tileCount(rows, fill_.group) + streams); + defer a.free(tiles); + d.n_tiles = @intCast(try K.tiles(segs, fill_.group, tiles)); + d.tiles = try self.rig.input(std.mem.sliceAsBytes(tiles[0..d.n_tiles])); + if (self.apart) for (segs, &self.alone) |s, *x| { + var one = s; + one.row0 = 0; + x.segs = try self.rig.input(std.mem.asBytes(&one)); + x.n_tiles = @intCast(try K.tiles(&.{one}, fill_.group, tiles)); + x.tiles = try self.rig.input(std.mem.sliceAsBytes(tiles[0..x.n_tiles])); + }; + try self.planted(); + const per: usize = if (self.path == .split) K.subs else 1; + const parts = rows * heads * K.slotsFor(layer, shape.k) * per; + d.po = try self.rig.scratch(parts * D * 4); + d.pml = try self.rig.scratch(parts * 8); + d.out = try self.rig.output(rows * n_out * 2); + if (self.apart or self.path == .split or self.path == .prompt) d.base = try self.rig.scratch(rows * n_out * 2); + return true; + } + + /// The device's own inputs: a control's faulted copy, else the true ones. + fn planted(self: *Attn) !void { + const a = self.rig.a; + const d = &self.dev; + const td = &self.data; + d.q_run = d.q; + d.tab_run = d.tab; + d.sink_run = d.sink; + d.gate_run = d.gate; + switch (self.plant) { + .none, .window_one => {}, + .late_bias => { + const t = try a.dupe(u16, td.tab); + defer a.free(t); + for (0..t.len / ref.extent) |rh| for (0..ref.extent) |dd| { + t[rh * ref.extent + dd] = if (dd + 1 < ref.extent) td.tab[rh * ref.extent + dd + 1] else 0; + }; + d.tab_run = try self.rig.input(std.mem.sliceAsBytes(t)); + }, + .no_sink => { + const t = try a.alloc(u16, td.sink.len); + defer a.free(t); + @memset(t, 0xff80); + d.sink_run = try self.rig.input(std.mem.sliceAsBytes(t)); + }, + .q_ulp => { + const t = try a.dupe(u16, td.q); + defer a.free(t); + t[0] +%= 1; + d.q_run = try self.rig.input(std.mem.sliceAsBytes(t)); + }, + .pre_sigmoid => { + const s = try a.alloc(u16, td.sink.len); + defer a.free(s); + for (s, td.sink) |*o, v| o.* = ref.bits(sigmoid(ref.bf(v))); + d.sink_run = try self.rig.input(std.mem.sliceAsBytes(s)); + const t = try a.alloc(u16, td.gate.len); + defer a.free(t); + for (t, td.gate) |*o, v| o.* = ref.bits(sigmoid(ref.bf(v))); + d.gate_run = try self.rig.input(std.mem.sliceAsBytes(t)); + }, + } + } + + fn sigmoid(x: f64) f64 { + return 1 / (1 + @exp(-x)); + } + + /// One launch's inputs: rows from `row0` (a stream alone) or all of them. + const Call = struct { r: K.Rows, row0: usize = 0, q: u64, tab: u64, sink: u64, gate: u64, out: u64 }; + + /// kernels.attend as the forward calls it; `path` picks its branch through `streams` and the partial room. + fn launch(self: *Attn, path: Path, x: Call) !void { + const d = self.dev; + var r = x.r; + var layer = self.lay.layer; + if (self.plant == .window_one) layer.window = 1; + const stride = K.slotsFor(self.lay.layer, self.shape.k); + var slots: usize = @as(usize, r.rows) * heads * stride; // a partial a chunk: no room to split + switch (path) { + .sliding, .prompt => {}, + .fold => r.streams = @max(r.streams, 2), // the dispatcher's multi-stream branch + .split => slots *= K.subs, + } + const b = x.row0 * heads; + try K.attend(self.k, self.rig.s, r, layer, stride, slots, x.q + b * D * 2, .{ .k = d.kc, .v = d.vc }, x.tab + b * ref.extent * 2, d.po, d.pml, x.sink + b * 2, x.gate + b * D * 2, x.out + b * D * 2); + } + + fn rowsAll(self: *const Attn) K.Rows { + const d = self.dev; + return .{ .rows = @intCast(self.shape.rows), .heads = heads, .kv_heads = kv, .pos = d.pos, .seg_of = 0, .segs = d.segs, .tiles = d.tiles, .n_tiles = d.n_tiles, .last_pos = @intCast(self.shape.k - 1), .streams = @intCast(self.lay.streams) }; + } + + pub fn run(self: *Attn) !void { + const d = self.dev; + try self.launch(self.path, .{ .r = self.rowsAll(), .q = d.q_run, .tab = d.tab_run, .sink = d.sink_run, .gate = d.gate_run, .out = d.out }); + try self.rig.s.synchronize(); + } + + /// The baseline on the true inputs: each stream alone (apart), else the fold the split and prompt must equal. + pub fn replaced(self: *Attn) ![]const u8 { + const d = self.dev; + if (!self.apart) { + try self.launch(.fold, .{ .r = self.rowsAll(), .q = d.q, .tab = d.tab, .sink = d.sink, .gate = d.gate, .out = d.base }); + return self.rig.bytes(d.base, self.count() * 2); + } + for (self.lay.segs[0..3], self.alone) |s, x| { + const row0: usize = @intCast(s.row0); + const r: K.Rows = .{ .rows = @intCast(s.n), .heads = heads, .kv_heads = kv, .pos = d.pos + row0 * 4, .seg_of = 0, .segs = x.segs, .tiles = x.tiles, .n_tiles = x.n_tiles, .last_pos = @intCast(s.p0 + s.n - 1), .streams = 1 }; + try self.launch(self.path, .{ .r = r, .row0 = row0, .q = d.q, .tab = d.tab, .sink = d.sink, .gate = d.gate, .out = d.base }); + } + return self.rig.bytes(d.base, self.count() * 2); + } + + pub fn reference(self: *Attn, want: []f64, mag: []f64) !void { + const a = self.rig.a; + a.free(self.tol); + self.tol = try a.alloc(f64, want.len); + const cl = self.call(); + if (self.exact_p and self.fill == .random) { + for (0..self.shape.rows * heads) |rh| fill_.exactP(&cl, rh / heads, rh % heads, want[rh * D ..][0..D]); + @memset(self.tol, 0); // bit for bit + } else try fill_.Pool.run(a, .{ .call = &cl, .want = want, .tol = self.tol }, self.shape.rows * heads); + for (mag, want) |*m, w| m.* = @abs(w); + } + + pub fn bounds(self: *Attn, _: []const f64, _: []const f64, allow: []f64) !void { + for (allow, self.tol) |*l, t| l.* = if (std.math.isFinite(t)) t else std.math.floatMax(f64); + } + + /// Gate 4 (stress rows only): q = 0 gives every head of a key head the same row, so one replay serves its group. + pub fn simulate(self: *Attn, acc: c.Accum, order: g.Order, out: []f64) !void { + std.debug.assert(self.fill == .stress); + const cl = self.call(); + try fill_.Pool.run(self.rig.a, .{ .call = &cl, .want = out, .tol = &.{}, .sim = .{ .acc = acc, .order = order } }, self.shape.rows * kv); + } +}; diff --git a/zig/tests/hip/contract_main.zig b/zig/tests/hip/contract_main.zig index 34a466f3f2d..4e863eee527 100644 --- a/zig/tests/hip/contract_main.zig +++ b/zig/tests/hip/contract_main.zig @@ -13,6 +13,8 @@ const mamba_k = @import("contract_mamba.zig"); const scan_k = @import("contract_scan.zig"); const moe_k = @import("contract_nemo_moe.zig"); const walk_k = @import("contract_walk.zig"); +const walk_rows_k = @import("contract_walk_rows.zig"); +const apply_rows_k = @import("contract_apply_rows.zig"); const prefill_k = @import("contract_prefill.zig"); const add_rms_k = @import("contract_add_rms.zig"); const tail_k = @import("contract_tail.zig"); @@ -200,6 +202,16 @@ fn run(a: std.mem.Allocator, io: std.Io) !usize { for (&qwen_walks, 0..) |*w, i| w.* = .qwenAt(a, &r, s, &l, i); defer for (&qwen_walks) |*w| w.deinit(); for (&qwen_walks) |*w| try kernels.append(a, w.kernel()); + // d = 256's score of a launch's slots, a slot's rows on one read of its keys: each head group, both kinds; controls + var row_walks: [walk_rows_k.count_all]walk_rows_k.RowsScore = undefined; + for (&row_walks, 0..) |*w, i| w.* = .init(a, &r, s, &l, i); + defer for (&row_walks) |*w| w.deinit(); + for (&row_walks) |*w| try kernels.append(a, w.kernel()); + // d = 256's values of a launch's slots, a slot's rows on one read of them: each head group, both kinds; controls + var row_applies: [apply_rows_k.count_all]apply_rows_k.RowsApply = undefined; + for (&row_applies, 0..) |*w, i| w.* = .init(a, &r, s, &l, i); + defer for (&row_applies) |*w| w.deinit(); + for (&row_applies) |*w| try kernels.append(a, w.kernel()); var prefills: [2]prefill_k.Prefill = undefined; for (&prefills, [_]bool{ true, false }) |*p, paged| p.* = .init(a, &r, s, &l, paged); defer for (&prefills) |*p| p.deinit(); diff --git a/zig/tests/hip/contract_walk_rows.zig b/zig/tests/hip/contract_walk_rows.zig new file mode 100644 index 00000000000..fb15839473a --- /dev/null +++ b/zig/tests/hip/contract_walk_rows.zig @@ -0,0 +1,418 @@ +//! plan_rows.hip's two-launch score step under the contract: slots, poisoned caches, tf_plan_score256_*'s bits. +const std = @import("std"); +const hip = @import("hip"); +const core = @import("core"); +const rig_ = @import("contract_rig.zig"); +const kit = @import("contract_kit.zig"); + +const contract = core.contract; +const c = contract.spec; +const g = contract.gates; +const sums = contract.rows; + +const page = 64; +const d = 256; +/// Spans the d = 256 score kernels take from (launches/plan.zig's score_span). +const long_span = 16384; +/// Gate 4's keys repeat every `period` positions, so its float64 sums are worked once a period. +const period = 61; + +/// Query heads over KV heads: Qwen3.6-35B-A3B's 16 over 2 and Qwen3.8-27B's 24 over 4. +pub const Case = struct { heads: usize, kv: usize }; +pub const cases = [_]Case{ .{ .heads = 16, .kv = 2 }, .{ .heads = 24, .kv = 4 } }; + +/// served[0] takes gates 1-2 (slots of 3, 1 and 4 rows, a span with a scalar tail), gate 4 the 262,144-key span. +const served = blk: { + var t: [cases.len][7]c.Shape = undefined; + for (cases, 0..) |x, i| t[i] = .{ + .{ .rows = 8, .n = x.heads, .k = 16387 }, + .{ .rows = 16, .n = x.heads, .k = 65536 }, + .{ .rows = 4, .n = x.heads, .k = 131072 }, + .{ .rows = 2, .n = x.heads, .k = 262144 }, + .{ .rows = 64, .n = x.heads, .k = 16384 }, + .{ .rows = 5, .n = x.heads, .k = 65536 }, + .{ .rows = 7, .n = x.heads, .k = 131072 }, + }; + break :blk t; +}; + +/// The real launches, or a control's: chunks led across slots (first 0, count every row), or the chunks' launch alone. +pub const Fault = enum { none, crossing, alone }; + +/// The registrations: each case in fp16 and bf16 caches, then each control in each. +pub const count_all = 2 * cases.len + 4; + +const kernel_names = [2][]const u8{ "tf_plan_rows_score256_f16", "tf_plan_rows_score256_bf16" }; +const lone_names = [2][]const u8{ "tf_plan_lone_score256_f16", "tf_plan_lone_score256_bf16" }; +const replaced_names = [2][]const u8{ "tf_plan_score256_f16", "tf_plan_score256_bf16" }; + +/// Each case's names [case][bf16], and the controls' [bf16]. +const names = blk: { + var t: [cases.len][2][]const u8 = undefined; + for (cases, 0..) |x, i| for (0..2) |bf| { + const what = "hip {s} then {s}, {d} heads over {d}: one-row slots alone, the others' rows on one read of their keys"; + t[i][bf] = std.fmt.comptimePrint(what, .{ lone_names[bf], kernel_names[bf], x.heads, x.kv }); + }; + break :blk t; +}; +const control_names = blk: { + var t: [2][2][]const u8 = undefined; + for (0..2) |bf| { + t[0][bf] = "control: hip " ++ kernel_names[bf] ++ ", chunks led across slots (first 0, count every row)"; + t[1][bf] = "control: hip " ++ kernel_names[bf] ++ " alone, the one-row slots' launch left out"; + } + break :blk t; +}; + +/// Case `i`'s spec in kind `k`: the bits of the one-row kernel it replaces, edges at a chunk's rows and a block's keys. +pub fn spec(i: usize, k: kit.Kind, fault: Fault) c.Spec { + const bf = @intFromBool(k == .bf16); + return .{ + .name = if (fault == .none) names[i][bf] else control_names[@intFromBool(fault == .alone)][bf], + .accum = .f32, + .depth = depth, + .ops = 1, // the scale + .out = .f32, + .replaces = replaced_names[bf], + .tiles = .{ .{ .size = hip.launches.score_rows }, .{}, .{ .size = long_span + 128, .min = long_span } }, + .served = &served[i], + }; +} + +/// A lane's eight products and sums, the five folds of the wave. +fn depth(_: c.Shape) usize { + return 2 * 8 + 5; +} + +/// Rows a slot holds: one each for an odd count from 5 (streams with no drafts), else cycling 3, 1, 4, 2. +fn counts(a: std.mem.Allocator, rows: usize) ![]usize { + var out: std.ArrayList(usize) = .empty; + const cycle: []const usize = if (rows % 2 == 1 and rows >= 5) &.{1} else &.{ 3, 1, 4, 2 }; + var left = rows; + while (left > 0) : (left -= out.items[out.items.len - 1]) try out.append(a, @min(left, cycle[out.items.len % cycle.len])); + return out.toOwnedSlice(a); +} + +/// Slot s's last row's visible keys: the span's end, mid-span, one past a block's first key, or the span's start. +fn lastVisible(s: usize, rows: usize, k: usize) usize { + const v = switch (s % 4) { + 0 => k - s / 4 * 7, + 1 => k / 2 + 5 + s / 4 * 64, + 2 => k / 4 / 128 * 128 + 1 + s / 4, + else => rows + s / 4, + }; + return std.math.clamp(v, rows, k); +} + +fn mix(x: u32) u32 { + var h = x; + h ^= h >> 16; + h *%= 0x7feb352d; + h ^= h >> 15; + h *%= 0x846ca68b; + h ^= h >> 16; + return h; +} + +/// A finite value of the kind, any sign and mantissa, magnitude in [2^-4, 2^2), as its 16 bits. +fn finite(k: kit.Kind, h: u32) u16 { + const sign: u16 = @intCast(h >> 31); + return if (k == .bf16) + sign << 15 | @as(u16, @intCast(123 + (h >> 8) % 6)) << 7 | @as(u16, @intCast(h & 0x7f)) + else + sign << 15 | @as(u16, @intCast(11 + (h >> 10) % 6)) << 10 | @as(u16, @intCast(h & 0x3ff)); +} + +/// A NaN of payload h (quiet or signaling) or an infinity of either sign, as the kind's 16 bits. +fn nonFinite(k: kit.Kind, h: u32) u16 { + const top: u16 = if (k == .bf16) 0x7f80 else 0x7c00; + const mant: u32 = if (k == .bf16) 0x7f else 0x3ff; + return switch (h % 3) { + 0 => @as(u16, @intCast((h >> 31) << 15)) | top | @as(u16, @intCast(1 + (h >> 8) % mant)), + 1 => top, + else => 0x8000 | top, + }; +} + +/// Gate 4's key element: integers in [1, 255] of either sign, the second half negated but for one, repeating. +fn stressKey(k: kit.Kind, h: usize, pos: usize, j: usize) u16 { + const r = mix(@intCast((h * period + pos % period) * 128 + j % 128)); + const v: f64 = @floatFromInt(1 + r % 255); + const x = if (r >> 31 == 1) -v else v; + var b: [2]u8 = undefined; + kit.put(k, &b, 0, if (j < 128) x else if (j == 128) 1 - x else -x); // integers of 256 or less are exact in both + return std.mem.readInt(u16, &b, .little); +} + +/// Gate 4's query element: integers in [1, 63], the second half equal to the first, so a dot is its first query. +fn stressQuery(i: usize) f64 { + return @floatFromInt(1 + mix(@intCast(i / d * 128 + i % d % 128)) % 63); +} + +fn scale() f32 { + return 1 / @sqrt(@as(f32, d)); +} + +/// shape.rows rows over slots of `counts` rows, each slot's own pages in one pool; the scores of every row and head. +pub const RowsScore = struct { + rig: rig_.Rig, + l: *const hip.Launcher, + k: kit.Kind, + case: usize, + fault: Fault = .none, + arena: std.heap.ArenaAllocator, + shape: c.Shape = undefined, + stress: bool = false, + q: []f64 = &.{}, // [rows][heads][d] + pool: []u16 = &.{}, // the keys in the kind, [kv][pages][page][d] + pages: usize = 0, + /// Each slot's page table, and each row's slot and visible keys. + tables: [][]u32 = &.{}, + slot: []usize = &.{}, + vis: []usize = &.{}, + plan: hip.launches.PlanRef = undefined, + /// The control's plan: every slot's first 0 and its count every row. + crossing: hip.launches.PlanRef = undefined, + q32: u64 = 0, + out: u64 = 0, + tree: u64 = 0, // the replaced kernel's scores + + /// Registration i of `count_all`: each case in fp16 then bf16 caches, then each control likewise. + pub fn init(a: std.mem.Allocator, rt: *const hip.Runtime, s: hip.Stream, l: *const hip.Launcher, i: usize) RowsScore { + const control = i >= 2 * cases.len; + return .{ + .rig = .{ .a = a, .r = rt, .s = s }, + .l = l, + .k = if (i % 2 == 1) .bf16 else .f16, + .case = if (control) 0 else i / 2, + .fault = if (!control) .none else if (i < 2 * cases.len + 2) .crossing else .alone, + .arena = .init(a), + }; + } + + pub fn deinit(self: *RowsScore) void { + self.arena.deinit(); + self.rig.deinit(); + } + + /// A control keeps its case's spec under its own name and must go red at gate 3. + pub fn kernel(self: *RowsScore) g.Kernel { + return .{ .spec = spec(self.case, self.k, self.fault), .ctx = self, .vt = &vt, .control = if (self.fault != .none) .shapes else null }; + } + + const vt = g.hooks(RowsScore); + + /// Element 0 of position `pos` of KV head `h` in slot `s`'s pages. + fn at(self: *const RowsScore, s: usize, h: usize, pos: usize) usize { + return ((h * self.pages + self.tables[s][pos / page]) * page + pos % page) * d; + } + + pub fn prepare(self: *RowsScore, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + const kv = cases[self.case].kv; + if (shape.rows == 0 or shape.k < long_span or shape.n % kv != 0) return false; + self.rig.reset(); + _ = self.arena.reset(.free_all); + self.shape = shape; + self.stress = fill == .stress; + const a = self.arena.allocator(); + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + const keys = shape.k; + const per = try counts(a, shape.rows); + const slots = per.len; + // each slot's rows at consecutive positions up to its last row's, and its pages, permuted over one pool + self.slot = try a.alloc(usize, shape.rows); + self.vis = try a.alloc(usize, shape.rows); + const first = try a.alloc(i32, slots); + const many = try a.alloc(i32, slots); + const need = try a.alloc(usize, slots); + var row: usize = 0; + self.pages = 0; + for (per, 0..) |n, s| { + const last = lastVisible(s, n, keys); + first[s] = @intCast(row); + many[s] = @intCast(n); + for (0..n) |i| { + self.slot[row + i] = s; + self.vis[row + i] = last - (n - 1) + i; + } + row += n; + need[s] = (last + page - 1) / page; + self.pages += need[s]; + } + self.tables = try a.alloc([]u32, slots); + var next: usize = 0; + for (self.tables, need) |*t, n| { + t.* = try a.alloc(u32, n); + for (t.*, next..) |*p, i| p.* = @intCast(if (self.pages % 5 == 0) self.pages - 1 - i else (i * 5 + 3) % self.pages); + next += n; + } + self.pool = try a.alloc(u16, kv * self.pages * page * d); + const salt: u32 = @truncate(seed); + for (self.tables, 0..) |t, s| for (0..kv) |h| for (0..t.len * page) |pos| { + const row_at = self.at(s, h, pos); + const hk = mix(@as(u32, @truncate((s * kv + h) * keys + pos)) *% 0x27d4eb2f +% salt); + for (self.pool[row_at..][0..d], 0..) |*x, j| { + x.* = if (self.stress) stressKey(self.k, h, pos, j) else finite(self.k, mix(hk ^ @as(u32, @intCast(j)) *% 0x9e3779b1)); + } + // one key in 41 holds a NaN or an infinity at one element, seen by some rows and past others + if (!self.stress and hk % 41 == 0) self.pool[row_at + hk / 41 % d] = nonFinite(self.k, mix(hk)); + }; + if (!self.stress) for (per, need, 0..) |n, pages, s| { + const last = lastVisible(s, n, keys); + // the key only a slot's last row sees, and the one past all its rows, both non-finite + for ([_]usize{ last - 1, last }) |pos| if (pos < pages * page) for (0..kv) |h| { + self.pool[self.at(s, h, pos) + (pos + h) % d] = nonFinite(self.k, mix(@intCast(pos + h))); + }; + }; + // queries: fp32 values in [-1, 1) away from zero, gate 4's integers, or one NaN at gate 1 + self.q = try a.alloc(f64, shape.rows * shape.n * d); + for (self.q, 0..) |*v, i| { + const x = rng.float(f64) * 2 - 1; + v.* = if (self.stress) stressQuery(i) else @as(f32, @floatCast(if (@abs(x) < 0x1p-8) 0.5 else x)); + } + if (fill == .nonfinite) self.q[0] = std.math.nan(f64); // row 0, head 0 + const qb = try kit.f32Bytes(a, self.q); + // quiet NaNs of distinct payloads in row 1's head 1 + if (!self.stress and shape.rows > 1) for (0..4) |e| { + const i = (shape.n + 1) * d + e * 37; + std.mem.writeInt(u32, qb[4 * i ..][0..4], 0x7fc00000 | @as(u32, @intCast(e * 0x1235 + 1)), .little); + self.q[i] = std.math.nan(f64); + }; + self.q32 = try self.rig.input(qb); + const pool = try self.rig.input(std.mem.sliceAsBytes(self.pool)); + // each slot's descriptor [cached, kept, k pool, v pool], then its page table + const words = 4; + const descs = try a.alloc(u64, slots); + for (self.tables, descs) |t, *dev| { + const desc = try a.alloc(u64, words + (t.len + 1) / 2); + @memset(desc, 0); + desc[2] = pool; + @memcpy(std.mem.sliceAsBytes(desc[words..])[0 .. t.len * 4], std.mem.sliceAsBytes(t)); + dev.* = try self.rig.input(std.mem.sliceAsBytes(desc)); + } + const pos = try a.alloc(i32, shape.rows); + const slot = try a.alloc(i32, shape.rows); + for (pos, slot, self.vis, self.slot) |*p, *s, v, x| { + p.* = @intCast(v - 1); + s.* = @intCast(x); + } + const args: hip.launches.PlanArgs = .{ + .pos = try self.rig.input(std.mem.sliceAsBytes(pos)), + .slot = try self.rig.input(std.mem.sliceAsBytes(slot)), + .first = try self.rig.input(std.mem.sliceAsBytes(first)), + .count = try self.rig.input(std.mem.sliceAsBytes(many)), + .desc = try self.rig.input(std.mem.sliceAsBytes(descs)), + .pages = words, + .pool = @intCast(self.pages), + }; + self.plan = .{ .rows = shape.rows, .slots = slots, .args = args }; + self.crossing = self.plan; + if (self.fault == .crossing) { + const zero = try a.alloc(i32, slots); + @memset(zero, 0); + const all = try a.alloc(i32, slots); + @memset(all, @intCast(shape.rows)); + self.crossing.args.first = try self.rig.input(std.mem.sliceAsBytes(zero)); + self.crossing.args.count = try self.rig.input(std.mem.sliceAsBytes(all)); + } + self.out = try self.rig.output(self.count() * 4); + self.tree = try self.rig.scratch(self.count() * 4); + return true; + } + + pub fn run(self: *RowsScore) !void { + const s = self.shape; + if (self.fault == .alone) return self.chunksAlone(); + const p = if (self.fault == .crossing) self.crossing else self.plan; + try self.l.planScore(self.q32, self.out, p, 0, s.n, cases[self.case].kv, d, s.k, scale(), @backingInt(self.k), false, .shared, self.rig.s.handle); + try self.rig.s.synchronize(); + } + + /// The control's launch: planScore's tf_plan_rows_score256_* on its grid and LDS, without tf_plan_lone_score256_*. + fn chunksAlone(self: *RowsScore) !void { + const s = self.shape; + const kv = cases[self.case].kv; + var a: hip.launch.Args = .{}; + try a.add(self.q32); + try a.add(self.out); + for ([_]usize{ s.k, s.n, kv, d }) |x| try a.add(@as(c_int, @intCast(x))); + try a.add(scale()); + try a.add(self.plan.args); + try a.add(@as(c_int, 0)); + const grid: hip.launch.Dim3 = .{ .x = @intCast((s.k + 127) / 128), .y = @intCast(kv), .z = @intCast(s.rows) }; + const lds: u32 = @intCast(hip.launches.score_rows * s.n / kv * d * 4); + const f = self.l.plan.score256_rows[@intCast(@backingInt(self.k) - 1)]; + try hip.launch.launch(f, .{ .grid = grid, .block = .{ .x = 128 }, .shared = lds }, self.rig.s, &a); + try self.rig.s.synchronize(); + } + + /// tf_plan_score256_*'s bytes on the same plan: a block a row. + pub fn replaced(self: *RowsScore) ![]const u8 { + const s = self.shape; + try self.l.planScore(self.q32, self.tree, self.plan, 0, s.n, cases[self.case].kv, d, s.k, scale(), @backingInt(self.k), false, .one, self.rig.s.handle); + return self.rig.bytes(self.tree, self.count() * 4); + } + + pub fn count(self: *RowsScore) usize { + return self.shape.rows * self.shape.n * self.shape.k; + } + + /// q k * scale in float64 for the keys a row sees, -inf past them; each score's magnitude is its terms' sum. + pub fn reference(self: *RowsScore, want: []f64, mag: []f64) !void { + try self.work(want, mag, null); + } + + /// Gate 4's scores with each dot's products summed in the accumulator and order, then scaled. + pub fn simulate(self: *RowsScore, acc: c.Accum, order: g.Order, out: []f64) !void { + try self.work(out, null, .{ acc, order }); + } + + /// Every row's scores, each dot in float64 or (`sim`) as an accumulator sums it; gate 4's once a period. + fn work(self: *RowsScore, out: []f64, mag: ?[]f64, sim: ?struct { c.Accum, g.Order }) !void { + const s = self.shape; + const sc: f64 = scale(); + const kv = cases[self.case].kv; + const heads = s.n / kv; + for (0..s.rows) |r| for (0..s.n) |h| { + const base = (r * s.n + h) * s.k; + @memset(out[base + self.vis[r] .. base + s.k], -std.math.inf(f64)); + if (mag) |m| @memset(m[base..][0..s.k], 0); + }; + var krow: [d]f64 = undefined; + var terms: [d]f64 = undefined; + var r0: usize = 0; + while (r0 < s.rows) { + var r1 = r0 + 1; + while (r1 < s.rows and self.slot[r1] == self.slot[r0]) r1 += 1; + var most: usize = 0; + for (self.vis[r0..r1]) |v| most = @max(most, v); + const reach = if (self.stress) @min(most, period) else most; + for (0..kv) |hk| for (0..reach) |pos| { + const row_at = self.at(self.slot[r0], hk, pos); + for (&krow, self.pool[row_at..][0..d]) |*x, bits| x.* = kit.get(self.k, std.mem.asBytes(&bits), 0); + for (r0..r1) |r| if (pos < self.vis[r]) for (hk * heads..(hk + 1) * heads) |h| { + var dot: f64 = 0; + var abs: f64 = 0; + for (self.q[(r * s.n + h) * d ..][0..d], krow, &terms) |x, y, *t| { + t.* = x * y; + dot += t.*; + abs += @abs(t.*); + } + if (sim) |how| dot = sums.sumIn(how[0], how[1], &terms); + const i = (r * s.n + h) * s.k + pos; + out[i] = dot * sc; + if (mag) |m| m[i] = abs * sc; + }; + }; + if (self.stress) for (r0..r1) |r| for (0..s.n) |h| { + const base = (r * s.n + h) * s.k; + for (@min(period, self.vis[r])..self.vis[r]) |pos| { + out[base + pos] = out[base + pos - period]; + if (mag) |m| m[base + pos] = m[base + pos - period]; + } + }; + r0 = r1; + } + } +}; diff --git a/zig/tests/idol_generate.zig b/zig/tests/idol_generate.zig new file mode 100644 index 00000000000..d8528c2a43b --- /dev/null +++ b/zig/tests/idol_generate.zig @@ -0,0 +1,293 @@ +//! tf-idol-generate: Idol end to end on Metal, one picture to a 3DGS PLY: both encoders, the denoiser, the decoders. +const std = @import("std"); +const mtl = @import("metal"); +const tf = @import("tensorfold"); +const id = tf.idol; +const cfg = id.config; +const vae = id.vae; +const dn = id.dino; +const dc = id.decoder_config; +const gs = id.gaussian; + +const usage = + \\tf-idol-generate SNAPSHOT_DIR VAE_DIR DINO_DIR PICTURE OUT_DIR [--seed N] [--steps N] [--cfg X] [--gaussians N] + \\ [--noise FILE] [--features FILE]... + \\SNAPSHOT_DIR is a speridlabs/idol snapshot, VAE_DIR FLUX.2-klein-4B's vae/ folder, DINO_DIR + \\timm/vit_huge_plus_patch16_dinov3.lvd1689m. PICTURE is a safetensors file holding the 1,024 x 1,024 picture + \\IdolPipeline.preprocess returns, in [0, 1]: `image` [1024, 1024, 3] (idol_case.py vae) or `pixels` [3, 1024, 1024] + \\(idol_case.py dino). Defaults: seed 42, 50 steps, guidance 3, 262,144 Gaussians, as IdolPipeline's. + \\The denoiser starts from torch.Generator("cpu").manual_seed(seed)'s randn [8192, 16] then [5], as idol_case.py + \\case draws it (the SDK draws on its device's generator). The VAE posterior's noise and the octree's draws come from + \\native seeded generators. --noise FILE gives the posterior's noise instead (`noise` [128, 128, 32], as idol_case.py + \\vae records the SDK's) and, if it holds them, the starting `latent` [8192, 16] and `camera` [5]. --features FILE + \\(once or twice) gives feature1 [1, 4101, 1280] and feature2 [1, 4101, 128] and skips both encoders (PICTURE: -). + \\Writes OUT_DIR/generate.ply, camera.json, start.f32 (the starting latent and camera), sample.f32 and + \\tf-idol-generate.json (each stage's seconds). Each model is freed once its stage is done. +; + +const N = cfg.latent_rows * cfg.latent_channels; +const cam_n = cfg.camera_channels; +const f1_n = cfg.cond_rows * cfg.cond_channels; +const f2_n = cfg.cond_rows * cfg.cond2_channels; +const noise_n = vae.latent * vae.latent * id.vae_weights.latent_channels; +comptime { + std.debug.assert(id.picture.side == vae.size); // the picture the encoders read is the one the VAE encodes +} +const rescale: f64 = 3.0; + +const TorchCpu = id.torch_rng.TorchCpu; + +const Options = struct { + seed: u64 = 42, + steps: usize = 50, + guidance: f32 = 3.0, + gaussians: usize = 262144, + noise: ?[]const u8 = null, + features: [2]?[]const u8 = .{ null, null }, +}; + +fn parse(args: []const [:0]const u8) !Options { + var o: Options = .{}; + var i: usize = 6; + while (i < args.len) : (i += 2) { + if (i + 1 >= args.len) return error.Usage; + const k = args[i]; + const v = args[i + 1]; + if (std.mem.eql(u8, k, "--seed")) { + o.seed = try std.fmt.parseInt(u64, v, 10); + } else if (std.mem.eql(u8, k, "--steps")) { + o.steps = try std.fmt.parseInt(usize, v, 10); + } else if (std.mem.eql(u8, k, "--cfg")) { + o.guidance = try std.fmt.parseFloat(f32, v); + } else if (std.mem.eql(u8, k, "--gaussians")) { + o.gaussians = try std.fmt.parseInt(usize, v, 10); + } else if (std.mem.eql(u8, k, "--noise")) { + o.noise = v; + } else if (std.mem.eql(u8, k, "--features")) { + if (o.features[0] == null) o.features[0] = v else if (o.features[1] == null) o.features[1] = v else return error.Usage; + } else return error.Usage; + } + if (o.steps == 0) return error.Usage; + return o; +} + +/// Tensor `name` of `f`, float32 with `n` values, or null when absent. +fn maybe(a: std.mem.Allocator, f: *const tf.safetensors.File, name: []const u8, n: usize) !?[]f32 { + const t = f.get(name) orelse return null; + if (t.dtype != .f32 or t.numel() != n) { + std.debug.print("{s} is not {d} float32 values\n", .{ name, n }); + return error.BadTensor; + } + const out = try a.alloc(f32, n); + @memcpy(std.mem.sliceAsBytes(out), t.bytes); + return out; +} + +/// The picture as [3, 1024, 1024] (DINOv3's input) and [1024, 1024, 3] (the VAE's), each name in its own layout only. +fn picture(a: std.mem.Allocator, io: std.Io, path: []const u8) ![2][]f32 { + var f = try tf.safetensors.File.open(a, io, path); + defer f.close(io); + return tf.idol.picture.layouts(a, f.get("pixels"), f.get("image")) catch |e| { + std.debug.print("{s}: {s}\n", .{ path, tf.idol.picture.explain(e) }); + return e; + }; +} + +fn print(list: *std.ArrayList(u8), a: std.mem.Allocator, comptime fmt: []const u8, args: anytype) !void { + try list.appendSlice(a, try std.fmt.allocPrint(a, fmt, args)); +} + +fn gb(bytes: u64) f64 { + return @as(f64, @floatFromInt(bytes)) / 1e9; +} + +/// Seconds per stage, as printed and written. +const Times = struct { + load_dino: f64 = 0, + dino: f64 = 0, + load_vae: f64 = 0, + vae: f64 = 0, + load_denoiser: f64 = 0, + condition: f64 = 0, + denoise: f64 = 0, + load_decoders: f64 = 0, + octree: f64 = 0, + gaussian_decoder: f64 = 0, + activation: f64 = 0, + ply: f64 = 0, + total: f64 = 0, +}; + +/// feature1 and feature2 from the encoders, or from --features files. +fn encode(a: std.mem.Allocator, io: std.Io, device: mtl.Device, args: []const [:0]const u8, o: Options, t: *Times, metal_peak: *u64) ![2][]f32 { + if (o.features[0]) |first| { + var f1: ?[]f32 = null; + var f2: ?[]f32 = null; + for ([_]?[]const u8{ first, o.features[1] }) |maybe_path| if (maybe_path) |path| { + var f = try tf.safetensors.File.open(a, io, path); + defer f.close(io); + if (try maybe(a, &f, "feature1", f1_n)) |v| f1 = v; + if (try maybe(a, &f, "feature2", f2_n)) |v| f2 = v; + }; + if (f1 == null or f2 == null) { + std.debug.print("--features needs feature1 [1, 4101, 1280] and feature2 [1, 4101, 128]\n", .{}); + return error.MissingTensor; + } + std.debug.print("features: given, both encoders skipped\n", .{}); + return .{ f1.?, f2.? }; + } + const pics = try picture(a, io, args[4]); + const f1 = try a.alloc(f32, f1_n); + const f2 = try a.alloc(f32, f2_n); + { + var started = mtl.clock.seconds(); + const enc = try dn.Encoder.load(std.heap.page_allocator, io, device, args[3]); + defer enc.deinit(); + t.load_dino = mtl.clock.seconds() - started; + started = mtl.clock.seconds(); + const tm = try enc.encode(pics[0], f1); + t.dino = mtl.clock.seconds() - started; + metal_peak.* = @max(metal_peak.*, device.allocated()); + std.debug.print("DINOv3: loaded in {d:.2} s; feature1 in {d:.3} s ({d:.3} s on the GPU)\n", .{ t.load_dino, t.dino, tm.gpu }); + } + const noise = try a.alloc(f32, noise_n); + var given = false; + if (o.noise) |path| { + var f = try tf.safetensors.File.open(a, io, path); + defer f.close(io); + if (try maybe(a, &f, "noise", noise_n)) |v| { + @memcpy(noise, v); + given = true; + } + } + if (!given) { + var rng = std.Random.DefaultPrng.init(o.seed +% 0x9e3779b97f4a7c15); + for (noise) |*v| v.* = rng.random().floatNorm(f32); + } + { + var started = mtl.clock.seconds(); + const enc = try vae.Encoder.load(std.heap.page_allocator, io, device, args[2]); + defer enc.deinit(); + t.load_vae = mtl.clock.seconds() - started; + started = mtl.clock.seconds(); + const tm = try enc.encode(pics[1], noise, f2, .{}); + t.vae = mtl.clock.seconds() - started; + metal_peak.* = @max(metal_peak.*, device.allocated()); + std.debug.print("VAE: loaded in {d:.2} s; feature2 in {d:.3} s ({d:.3} s on the GPU), posterior noise {s}\n", .{ t.load_vae, t.vae, tm.gpu, if (given) "given" else "native" }); + } + return .{ f1, f2 }; +} + +/// The guided schedule from the starting noise `x` (latent then camera), in place. +fn denoise(a: std.mem.Allocator, io: std.Io, device: mtl.Device, dir: []const u8, f: [2][]f32, x: []f32, o: Options, t: *Times, metal_peak: *u64) !void { + var started = mtl.clock.seconds(); + const model = try id.Model.load(std.heap.page_allocator, io, device, dir); + defer model.deinit(); + t.load_denoiser = mtl.clock.seconds() - started; + started = mtl.clock.seconds(); + var conds: [2]id.Condition = undefined; + conds[0] = try model.condition(f[0], f[1]); + defer conds[0].deinit(); + @memset(f[0], 0); + @memset(f[1], 0); + conds[1] = try model.condition(f[0], f[1]); + defer conds[1].deinit(); + t.condition = mtl.clock.seconds() - started; + const ts = try a.alloc(f64, o.steps + 1); + id.host.schedule(ts, rescale); + const vc = try a.alloc(f32, N); + const vu = try a.alloc(f32, N); + var cc: [cam_n]f32 = undefined; + var cu: [cam_n]f32 = undefined; + var gpu: f64 = 0; + const w = o.guidance; + started = mtl.clock.seconds(); + for (0..o.steps) |s| { + const time: f32 = @floatCast(1000 * ts[s]); + const cam: *const [cam_n]f32 = x[N..][0..cam_n]; + const p = try model.forward(&conds[0], x[0..N], cam, time, vc, &cc); + const q = try model.forward(&conds[1], x[0..N], cam, time, vu, &cu); + const by: f32 = @floatCast(ts[s] - ts[s + 1]); + for (x[0..N], vc, vu) |*v, pc, pu| v.* -= ((1 + w) * pc - w * pu) * by; + for (x[N..], cc, cu) |*v, pc, pu| v.* -= ((1 + w) * pc - w * pu) * by; + gpu += p.gpu + q.gpu; + } + t.denoise = mtl.clock.seconds() - started; + metal_peak.* = @max(metal_peak.*, device.allocated()); + std.debug.print("denoiser: loaded in {d:.2} s; condition {d:.3} s; {d} steps in {d:.2} s ({d:.2} s on the GPU)\n", .{ t.load_denoiser, t.condition, o.steps, t.denoise, gpu }); +} + +pub fn main(init: std.process.Init) !u8 { + const a = init.arena.allocator(); + const io = init.io; + const args = try init.minimal.args.toSlice(a); + const o = (if (args.len >= 6) parse(args) else error.Usage) catch { + std.debug.print("{s}\n", .{usage}); + return 2; + }; + const out_dir = args[5]; + try std.Io.Dir.cwd().createDirPath(io, out_dir); + const begun = mtl.clock.seconds(); + var t: Times = .{}; + var metal_peak: u64 = 0; + + // the starting noise first: it does not depend on the picture + const x = try a.alloc(f32, N + cam_n); + var gen = TorchCpu.init(o.seed); + gen.randn(x[0..N]); + gen.randn(x[N..]); + var start_given = false; + if (o.noise) |path| { + var f = try tf.safetensors.File.open(a, io, path); + defer f.close(io); + const lat = try maybe(a, &f, "latent", N); + const cam = try maybe(a, &f, "camera", cam_n); + if (lat != null and cam != null) { + @memcpy(x[0..N], lat.?); + @memcpy(x[N..], cam.?); + start_given = true; + } + } + try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = try std.fmt.allocPrint(a, "{s}/start.f32", .{out_dir}), .data = std.mem.sliceAsBytes(x) }); + + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const device = try mtl.Device.init(); + std.debug.print("{s}: seed {d}, {d} steps, guidance {d}, {d} Gaussians; starting noise {s}\n", .{ device.name(), o.seed, o.steps, o.guidance, o.gaussians, if (start_given) "given" else "torch CPU-seeded" }); + const features = try encode(a, io, device, args, o, &t, &metal_peak); + try denoise(a, io, device, args[1], features, x, o, &t, &metal_peak); + try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = try std.fmt.allocPrint(a, "{s}/sample.f32", .{out_dir}), .data = std.mem.sliceAsBytes(x) }); + + var started = mtl.clock.seconds(); + const d = try id.Decoder.load(std.heap.page_allocator, io, device, args[1], try dc.anchors(o.gaussians)); + t.load_decoders = mtl.clock.seconds() - started; + var draws: id.octree.Draws = .{ .native = std.Random.DefaultPrng.init(o.seed) }; + var r = try id.decode.decode(std.heap.page_allocator, d, x[0..N], o.gaussians, &draws, null); + defer r.deinit(std.heap.page_allocator); + metal_peak = @max(metal_peak, device.allocated()); + d.deinit(); + t.octree = r.time.octree; + t.gaussian_decoder = r.time.gaussian; + t.activation = r.time.activation; + std.debug.print("decoders: loaded in {d:.2} s; octree {d:.3} s, Gaussian decoder {d:.3} s, activation {d:.3} s\n", .{ t.load_decoders, t.octree, t.gaussian_decoder, t.activation }); + + started = mtl.clock.seconds(); + const bytes = try gs.ply(a, r.gaussians); + try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = try std.fmt.allocPrint(a, "{s}/generate.ply", .{out_dir}), .data = bytes }); + const c = gs.camera(x[N..][0..cam_n].*); + const cam_json = try std.fmt.allocPrint(a, "{{\"yaw\": {d}, \"pitch\": {d}, \"radius\": {d}, \"fov\": {d}}}\n", .{ c.yaw, c.pitch, c.radius, c.fov }); + try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = try std.fmt.allocPrint(a, "{s}/camera.json", .{out_dir}), .data = cam_json }); + t.ply = mtl.clock.seconds() - started; + t.total = mtl.clock.seconds() - begun; + + const load = t.load_dino + t.load_vae + t.load_denoiser + t.load_decoders; + std.debug.print("PLY: {d} Gaussians, {d} bytes in {d:.3} s; camera {s}", .{ r.gaussians.count(), bytes.len, t.ply, cam_json }); + std.debug.print("total {d:.2} s: load {d:.2}, dino {d:.3}, vae {d:.3}, condition {d:.3}, denoise {d:.2}, octree {d:.3}, Gaussian decoder {d:.3} (+ activation {d:.3}), PLY {d:.3}; Metal peak {d:.2} GB\n", .{ t.total, load, t.dino, t.vae, t.condition, t.denoise, t.octree, t.gaussian_decoder, t.activation, t.ply, gb(metal_peak) }); + var out: std.ArrayList(u8) = .empty; + try print(&out, a, "{{\"device\": \"{s}\", \"seed\": {d}, \"steps\": {d}, \"cfg\": {d}, \"gaussians\": {d}, \"start_noise\": \"{s}\", \"vae_noise\": \"{s}\", \"features_given\": {}", .{ device.name(), o.seed, o.steps, o.guidance, r.gaussians.count(), if (start_given) "given" else "torch_cpu", if (o.features[0] != null) "unused" else if (o.noise != null) "given" else "native", o.features[0] != null }); + try print(&out, a, ", \"load_s\": {d:.4}", .{load}); + inline for (@typeInfo(Times).@"struct".field_names) |name| try print(&out, a, ", \"{s}_s\": {d:.4}", .{ name, @field(t, name) }); + try print(&out, a, ", \"metal_peak_allocated_gb\": {d:.3}, \"camera\": {s}}}\n", .{ gb(metal_peak), std.mem.trimEnd(u8, cam_json, "\n") }); + try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = try std.fmt.allocPrint(a, "{s}/tf-idol-generate.json", .{out_dir}), .data = out.items }); + return 0; +} diff --git a/zig/tests/ling_cpu_decode.zig b/zig/tests/ling_cpu_decode.zig new file mode 100644 index 00000000000..7b2c6b5370e --- /dev/null +++ b/zig/tests/ling_cpu_decode.zig @@ -0,0 +1,79 @@ +//! Greedy Ling-3.0-tiny CPU decode from a GGUF and prompt token IDs; prints the IDs and tokens a second. +const std = @import("std"); +const cpu = @import("ling_cpu"); + +const usage = "usage: ling-cpu-decode MODEL.gguf ID,ID,... COUNT [THREADS]\n"; + +fn top(values: []const f32) u32 { + var best: usize = 0; + for (values, 0..) |v, i| if (v > values[best]) { + best = i; + }; + return @intCast(best); +} + +fn rate(tokens: usize, ns: i96) f64 { + return @as(f64, @floatFromInt(tokens)) * 1e9 / @as(f64, @floatFromInt(@max(ns, 1))); +} + +pub fn main(init: std.process.Init) !void { + const a = init.arena.allocator(); + const args = try init.minimal.args.toSlice(a); + var buf: [4096]u8 = undefined; + var out = std.Io.File.stdout().writerStreaming(init.io, &buf); + const w = &out.interface; + if (args.len != 4 and args.len != 5) { + try w.writeAll(usage); + try w.flush(); + return error.Usage; + } + var prompt: std.ArrayList(u32) = .empty; + var it = std.mem.tokenizeScalar(u8, args[2], ','); + while (it.next()) |id| try prompt.append(a, try std.fmt.parseInt(u32, id, 10)); + const count = try std.fmt.parseInt(u32, args[3], 10); + const threads = if (args.len == 5) try std.fmt.parseInt(usize, args[4], 10) else 1; + if (prompt.items.len == 0 or count == 0 or prompt.items.len + count > 4096) return error.PromptCapacity; + + const opening = std.Io.Clock.awake.now(init.io); + var file = try cpu.gguf.File.open(init.gpa, init.io, args[1]); + defer file.close(init.io); + const c = try file.config(); + var session = try cpu.Gguf.Session.init(init.gpa, &file, c, @intCast(prompt.items.len + count), threads); + defer session.deinit(); + const opened = std.Io.Clock.awake.now(init.io); + try w.print("model opened in {d:.2} s, {d} threads, exact\n", .{ @as(f64, @floatFromInt(opening.durationTo(opened).toNanoseconds())) / 1e9, threads }); + try w.flush(); + + var next: u32 = undefined; + var at: usize = 0; + while (at < prompt.items.len) { + const end = @min(prompt.items.len, at + 8); + const is_last = end == prompt.items.len; + const step = try session.prefillChunk(prompt.items[at..end], is_last); + if (is_last) next = top(step.logits); + at = end; + } + const prefilled = std.Io.Clock.awake.now(init.io); + const prefill_ns = opened.durationTo(prefilled).toNanoseconds(); + try w.print("prefill {d} tokens in {d:.2} s ({d:.2} tokens/s)\n", .{ prompt.items.len, @as(f64, @floatFromInt(prefill_ns)) / 1e9, rate(prompt.items.len, prefill_ns) }); + try w.writeAll("generated:"); + try w.flush(); + + var made: usize = 0; + var stopped = false; + while (made < count) { + try w.print(" {d}", .{next}); + try w.flush(); + made += 1; + const step = try session.step(&.{next}); + if (std.mem.indexOfScalar(u32, c.eos[0..c.eos_n], next) != null) { + stopped = true; + break; + } + next = top(step.logits); + } + const done = std.Io.Clock.awake.now(init.io); + const decode_ns = prefilled.durationTo(done).toNanoseconds(); + try w.print("\ndecode {d} tokens in {d:.2} s ({d:.2} tokens/s), finish {s}\n", .{ made, @as(f64, @floatFromInt(decode_ns)) / 1e9, rate(made, decode_ns), if (stopped) "stop" else "length" }); + try w.flush(); +} diff --git a/zig/tests/qwen27/run.zig b/zig/tests/qwen27/run.zig index 46420bb9e1b..a1be85fe5b6 100644 --- a/zig/tests/qwen27/run.zig +++ b/zig/tests/qwen27/run.zig @@ -1,16 +1,20 @@ //! The real-weight gate. Help returns before any device or checkpoint access. const std = @import("std"); +/// --stages: the qwen27 stage recorder is built into this tool only (stage_planes.on). +pub const qwen27_stages = true; const q = @import("qwen27"); const mtl = @import("metal"); const sources = @import("qwen_runtime_sources"); const gdn_source = @import("qwen_gdn_source"); -const profile = @import("core").gpu_profile; +const core = @import("core"); +const profile = core.gpu_profile; const core_lane = @import("core_lane"); const help = \\tf-qwen27-run --run --model DIR --tokens IDS.json [--max-tokens 256] \\ [--chunk 128] [--compare-chunk 16] [--reference GENERATED.json] [--force-length] \\ [--no-warmup] [--profile-steps N] [--profile-prompt] [--teacher] [--seams N] [--resume-reply] + \\ [--stages DIR] \\IDs and reference files are JSON arrays of unsigned token IDs, already chat-rendered. \\Greedy only, drafts off; JSON receipt on stdout, errors on stderr. \\--teacher feeds every reference token and records native top2 at all positions; margin timing is diagnostic. @@ -19,6 +23,7 @@ const help = \\--seams N (with --compare-chunk): state/KV/logits bytes every N prompt rows under both chunks and after decode. \\--resume-reply: the reply fed again in one pass that keeps no row, then a turn's tail, against decoding it. \\--profile-prompt: GPU seconds by class over the timed prompt (split command buffers, so slower than unprofiled). + \\--stages DIR writes the measured prompt's and decode's staged references (stream per stage, final norm, logits). \\CPU only: --help or --emit-sources EXISTING_DIR, no Metal device or model load. ; @@ -110,6 +115,7 @@ pub fn main(init: std.process.Init) !void { var chunk: usize = 128; var compare: usize = 0; var seam_every: usize = 0; + var stages_dir: ?[]const u8 = null; var run = false; var force = false; var warmup = true; @@ -146,7 +152,7 @@ pub fn main(init: std.process.Init) !void { if (i + 1 >= args.len) return error.MissingValue; i += 1; const value = args[i]; - if (std.mem.eql(u8, arg, "--model")) model = value else if (std.mem.eql(u8, arg, "--tokens")) file = value else if (std.mem.eql(u8, arg, "--reference")) reference = value else if (std.mem.eql(u8, arg, "--max-tokens")) count = try std.fmt.parseInt(usize, value, 10) else if (std.mem.eql(u8, arg, "--chunk")) chunk = try std.fmt.parseInt(usize, value, 10) else if (std.mem.eql(u8, arg, "--profile-steps")) profile_steps = try std.fmt.parseInt(usize, value, 10) else if (std.mem.eql(u8, arg, "--compare-chunk")) compare = try std.fmt.parseInt(usize, value, 10) else if (std.mem.eql(u8, arg, "--seams")) seam_every = try std.fmt.parseInt(usize, value, 10) else return error.UnknownOption; + if (std.mem.eql(u8, arg, "--model")) model = value else if (std.mem.eql(u8, arg, "--tokens")) file = value else if (std.mem.eql(u8, arg, "--reference")) reference = value else if (std.mem.eql(u8, arg, "--max-tokens")) count = try std.fmt.parseInt(usize, value, 10) else if (std.mem.eql(u8, arg, "--chunk")) chunk = try std.fmt.parseInt(usize, value, 10) else if (std.mem.eql(u8, arg, "--profile-steps")) profile_steps = try std.fmt.parseInt(usize, value, 10) else if (std.mem.eql(u8, arg, "--compare-chunk")) compare = try std.fmt.parseInt(usize, value, 10) else if (std.mem.eql(u8, arg, "--seams")) seam_every = try std.fmt.parseInt(usize, value, 10) else if (std.mem.eql(u8, arg, "--stages")) stages_dir = value else return error.UnknownOption; } if (!run or model == null or file == null or chunk == 0 or chunk > 2048 or compare > 2048 or count > 65536 or (seam_every > 0 and compare == 0)) return error.BadOptions; const ids = try tokens(a, io, file.?); @@ -174,6 +180,15 @@ pub fn main(init: std.process.Init) !void { var trace = profile.Trace{ .queue = m.queue }; if (profile_steps > 0 or profile_prompt) runner.profile(&trace); trace.enabled = profile_prompt; + var recorder: ?core.qwen35_stages.Recorder = null; + defer if (recorder) |*r| r.deinit(); + var planes: ?q.stage_planes.Planes = null; + defer if (planes) |p| p.deinit(); + if (stages_dir != null) { + recorder = try core.qwen35_stages.Recorder.init(init.gpa, m.config.layers, m.config.hidden, m.config.vocab); + planes = try q.stage_planes.Planes.init(m.device, &recorder.?, m.frame.capacity, @min(m.frame.capacity, q.gpu_frame.logit_rows)); + q.stage_planes.active = &planes.?; + } const start = std.Io.Clock.awake.now(io); try s.prefill(ids, chunk); const prompt_ns = start.durationTo(std.Io.Clock.awake.now(io)).toNanoseconds(); @@ -183,6 +198,8 @@ pub fn main(init: std.process.Init) !void { const generation = try generated(a, s, count, force, expected, if (profile_steps > 0) &trace else null, profile_steps, teacher); const out = generation.tokens; const decode_ns = decode_start.durationTo(std.Io.Clock.awake.now(io)).toNanoseconds(); + q.stage_planes.active = null; + if (stages_dir) |dir| try recorder.?.write(io, dir); const decoded = if (compare > 0) try s.fingerprint() else digest; const reference_equal = if (expected) |wanted| std.mem.eql(u32, out, wanted) else false; if (compare > 0) { diff --git a/zig/tests/qwen35/hidden_run.zig b/zig/tests/qwen35/hidden_run.zig index 7a6ca788b48..9ad43cb5b4c 100644 --- a/zig/tests/qwen35/hidden_run.zig +++ b/zig/tests/qwen35/hidden_run.zig @@ -2,6 +2,7 @@ const std = @import("std"); const hip = @import("hip"); +const core = @import("core"); const qwen35 = @import("qwen3_5"); const ids_file = @import("ids_file.zig"); @@ -72,7 +73,10 @@ pub fn run(gpa: std.mem.Allocator, io: std.Io, args: []const [:0]const u8) !void defer gpa.free(ids); if (ids.len == 0) return error.MissingArgument; const piece = if (cut == 0) ids.len else @min(cut, ids.len); - const e = try Engine.open(gpa, io, args[0], .{ .capacity = ids.len + 64, .prompt_rows = piece, .streams = 1, .batch_rows = 32, .policy = (try @import("group.zig").resolve("", 0)).policy }); + var policy = (try @import("group.zig").resolve("", 0)).policy; + // a cut stands for a server's prompt step: each piece crosses a layer whole, as that server's chunks do + policy.prefill_step = @intCast(@max(policy.prefill_step, cut)); + const e = try Engine.open(gpa, io, args[0], .{ .capacity = ids.len + 64, .prompt_rows = piece, .streams = 1, .batch_rows = 32, .policy = policy }); defer e.deinit(); const m = e.model(); // numpy has no bf16: its bits as uint16, which the oracle widens @@ -93,7 +97,7 @@ pub fn run(gpa: std.mem.Allocator, io: std.Io, args: []const [:0]const u8) !void @memset(out[10 + dict.len ..][0..pad], ' '); out[head - 1] = '\n'; if (layers) try residuals(e, ids, out[head..]) else try rows(e, ids, cut, out[head..]); - try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = args[2], .data = out }); + try core.chunked_write.writeFileChunked(io, std.Io.Dir.cwd(), args[2], out); const what = if (layers) "layers' residual rows" else "final-norm rows"; std.debug.print("wrote {d} {s} x {d} ({s}, pieces of {d}) to {s}\n", .{ ids.len, what, m.spec.hidden, descr, piece, args[2] }); } diff --git a/zig/tests/qwen35/logits_run.zig b/zig/tests/qwen35/logits_run.zig index 61ac1c10870..12f210a2452 100644 --- a/zig/tests/qwen35/logits_run.zig +++ b/zig/tests/qwen35/logits_run.zig @@ -2,6 +2,7 @@ const std = @import("std"); const hip = @import("hip"); +const core = @import("core"); const qwen35 = @import("qwen3_5"); const ids_file = @import("ids_file.zig"); const Kind = @import("logit_kind.zig").Kind; @@ -115,6 +116,6 @@ pub fn run(gpa: std.mem.Allocator, io: std.Io, args: []const [:0]const u8) !void out[head - 1] = '\n'; var file: File = .{ .body = out[head..], .width = width }; try stream(gpa, e, ids, mode, .{ .ctx = &file, .put = File.put }); - try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = args[2], .data = out }); + try core.chunked_write.writeFileChunked(io, std.Io.Dir.cwd(), args[2], out); std.debug.print("wrote {d}{s} rows x {d} logits to {s}\n", .{ ids.len, if (mode.decode) " decoded" else "", vocab(e), args[2] }); } diff --git a/zig/tests/qwen35/tail_run.zig b/zig/tests/qwen35/tail_run.zig index 1decdc60549..5665a024132 100644 --- a/zig/tests/qwen35/tail_run.zig +++ b/zig/tests/qwen35/tail_run.zig @@ -46,7 +46,7 @@ fn run(gpa: std.mem.Allocator, e: *Engine, ids: hip.DeviceBuffer, len: usize, re } e.prompts.reset(); const o = e.ops(&e.prompts); - const kept = try fwd.spanFor(o, m, &caches, ids.base(), len, 0, null, reads); + const kept = try fwd.spanFor(o, m, &caches, ids.base(), len, 0, e.stepRows(), null, reads); if (kept.from < len) { const row = kept.row(len - 1, m.spec.hidden); const logits = try o.project(row, m.head, 1, false); diff --git a/zig/tests/qwen35_cuda_main.zig b/zig/tests/qwen35_cuda_main.zig index b76da69e0b4..7356485459a 100644 --- a/zig/tests/qwen35_cuda_main.zig +++ b/zig/tests/qwen35_cuda_main.zig @@ -255,7 +255,7 @@ pub fn main(init: std.process.Init) !u8 { try out.appendSlice(a, copy.host.bytes[0..@intCast(copy.len)]); } else try out.appendSlice(a, std.mem.sliceAsBytes(cache.logits)); } - try std.Io.Dir.cwd().writeFile(init.io, .{ .sub_path = args[4], .data = out.items }); + try core.chunked_write.writeFileChunked(init.io, std.Io.Dir.cwd(), args[4], out.items); return 0; } diff --git a/zig/tests/qwen35_forward.zig b/zig/tests/qwen35_forward.zig index 1092dfedb0f..13fa3d8fa6c 100644 --- a/zig/tests/qwen35_forward.zig +++ b/zig/tests/qwen35_forward.zig @@ -31,6 +31,6 @@ pub fn main(init: std.process.Init) !void { @memcpy(out[at * q.config.vocab * 2 ..][0 .. n * q.config.vocab * 2], scratch.logits.contents()[0 .. n * q.config.vocab * 2]); at += n; } - try std.Io.Dir.cwd().writeFile(init.io, .{ .sub_path = args[3], .data = out }); + try tf.chunked_write.writeFileChunked(init.io, std.Io.Dir.cwd(), args[3], out); std.debug.print("native Qwen forward: {d} rows, bf16 logits, fp32 recurrent state\n", .{ids.len}); } diff --git a/zig/tests/qwen35_pipe.zig b/zig/tests/qwen35_pipe.zig index 3cf77043dd9..f257319e303 100644 --- a/zig/tests/qwen35_pipe.zig +++ b/zig/tests/qwen35_pipe.zig @@ -1,6 +1,7 @@ //! `tf-qwen35-cuda pipe [fp8]`: greedy streams decoded in `k` groups, one engine or a stage ring. const std = @import("std"); const cuda = @import("cuda"); +const core = @import("core"); const stage = @import("stage"); const q = @import("qwen35"); const E = q.engine; @@ -123,7 +124,7 @@ fn finish(init: std.process.Init, a: std.mem.Allocator, e: *E.Engine, lead: *S.L try lead.step(closes[0..set.streams], &.{}, .window); var out: std.ArrayList(u8) = .empty; for (streams) |x| try out.appendSlice(a, std.mem.sliceAsBytes(x.hist.items[set.prompt..][0..set.tokens])); - try std.Io.Dir.cwd().writeFile(init.io, .{ .sub_path = out_path, .data = out.items }); + try core.chunked_write.writeFileChunked(init.io, std.Io.Dir.cwd(), out_path, out.items); const ms = @as(f64, @floatFromInt(t2 - t1)) / 1e6; const made = @as(f64, @floatFromInt(set.streams * set.tokens)); std.debug.print("pipe {s}: {{\"streams\":{d},\"k\":{d},\"draft\":{d},\"prompt\":{d},\"tokens\":{d},\"prompt_ms\":{d:.1},\"decode_ms\":{d:.1},\"tok_s\":{d:.2},\"rounds\":{d},\"drafted\":{d},\"kept_drafts\":{d}}}\n", .{ role, set.streams, set.k, set.draft, set.prompt, set.tokens, @as(f64, @floatFromInt(t1 - t0)) / 1e6, ms, made * 1e3 / ms, rounds, drafted, taken }); diff --git a/zig/tests/qwen35_stage.zig b/zig/tests/qwen35_stage.zig index db64bff16c9..b0d7d2cb761 100644 --- a/zig/tests/qwen35_stage.zig +++ b/zig/tests/qwen35_stage.zig @@ -1,6 +1,7 @@ //! `tf-qwen35-cuda stage [fp8]`: one scenario's logits from one engine, or rank 0 of a stage ring. const std = @import("std"); const cuda = @import("cuda"); +const core = @import("core"); const stage = @import("stage"); const q = @import("qwen35"); const E = q.engine; @@ -79,7 +80,7 @@ fn finish(init: std.process.Init, a: std.mem.Allocator, e: *E.Engine, lead: *S.L for (toks) |t| std.debug.print(" {d}", .{t}); std.debug.print("\n", .{}); report(0, role); - try std.Io.Dir.cwd().writeFile(init.io, .{ .sub_path = out_path, .data = out.items }); + try core.chunked_write.writeFileChunked(init.io, std.Io.Dir.cwd(), out_path, out.items); return 0; } diff --git a/zig/tests/uocr/decode.zig b/zig/tests/uocr/decode.zig index cba0d5e947f..f9258f1a60a 100644 --- a/zig/tests/uocr/decode.zig +++ b/zig/tests/uocr/decode.zig @@ -206,7 +206,7 @@ pub fn main(init: std.process.Init) !u8 { } const t1 = mtl.clock.seconds(); - try dec.prefill(p, rows); + try dec.prefill(p, rows, null); const t_pre = mtl.clock.seconds() - t1; dec.trace = null; dec.trace_parts = null; @@ -257,7 +257,7 @@ pub fn main(init: std.process.Init) !u8 { { var fed = try uo.decoder.Decoder.init(gpa, device, queue, &k, &w, n + max_new + 1, n); defer fed.deinit(); - try fed.prefill(p, rows); + try fed.prefill(p, rows, null); var guard = uo.generate.Guard.init(p); var st = uo.prompt.Step.init(p); var flips: usize = 0; @@ -285,7 +285,7 @@ pub fn main(init: std.process.Init) !u8 { dec.deinit(); dec = try uo.decoder.Decoder.init(gpa, device, queue, &k, &w, n + max_new + 1, @min(c, n)); const t3 = mtl.clock.seconds(); - try dec.prefill(p, rows); + try dec.prefill(p, rows, null); const lg = try dec.logits(); const t_chunked = mtl.clock.seconds() - t3; const same_logits = std.mem.eql(u16, lg, first_logits);