diff --git a/.github/workflows/no-gpu.yml b/.github/workflows/no-gpu.yml index 5b149fba4b8..62c68e0b6ef 100644 --- a/.github/workflows/no-gpu.yml +++ b/.github/workflows/no-gpu.yml @@ -25,6 +25,17 @@ concurrency: # tip, and the hosted queue (58 runs behind ~13 jobs) held main's and contributors' checks for hours. A train # whose local run is red starts this workflow on its branch by hand (workflow_dispatch) for GitHub's verdict. jobs: + comfyui-moss-installer: + runs-on: ubuntu-latest + timeout-minutes: 5 + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + with: + persist-credentials: false + - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0 + with: + python-version: "3.12" + - run: python -m unittest discover -s tools/comfyui_runtime/tests -v benchmark-clients: if: ${{ !startsWith(github.head_ref, 'lead/train-') }} # a landing train's tip: see the note above jobs strategy: diff --git a/.github/workflows/web.yml b/.github/workflows/web.yml index ca41261eddd..5fd247a2832 100644 --- a/.github/workflows/web.yml +++ b/.github/workflows/web.yml @@ -7,6 +7,11 @@ on: pull_request: paths: ["web/**", ".github/workflows/web.yml", "build.zig.zon"] +concurrency: + # a pull request push cancels that PR's older run (18 Nov: 28 superseded runs sat queued); main pushes all run + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + permissions: contents: read diff --git a/.github/workflows/zig-fmt.yml b/.github/workflows/zig-fmt.yml index 258b4f9ea25..74871d1d529 100644 --- a/.github/workflows/zig-fmt.yml +++ b/.github/workflows/zig-fmt.yml @@ -7,13 +7,13 @@ on: types: [opened, synchronize, reopened] workflow_dispatch: -permissions: - contents: read - -# A newer push to main or to a pull request cancels the older format run, as No GPU does. concurrency: + # a pull request push cancels that PR's older run (18 Nov: 28 superseded runs sat queued); main pushes all run group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} - cancel-in-progress: true + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +permissions: + contents: read # 19 Nov: a landing train's PR (lead/train-*) skips these jobs. Our local CI runs the same checks on the train's # tip, and the hosted queue (58 runs behind ~13 jobs) held main's and contributors' checks for hours. A train diff --git a/CHANGELOG.md b/CHANGELOG.md index 69a2befb2e6..fcf63c7f60d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,9 +1,141 @@ # What's new in TensorFold -Each release's page on GitHub has its notes and measurements. See [the 1.0.0 release notes](docs/release-notes-1.0.0.md) for the native binary's supported models and migration details. +Each release's page on GitHub has its notes and measurements. See [the 1.0.0 release notes](docs/release-notes-1.0.0.md) for the native binary's supported models and migration details. For Desktop installers and changes awaiting a Desktop build, see the [Desktop changelog](app/CHANGELOG.md). ## Unreleased +- Kernel contract: the GLM record for `df_sumn` under nvcc 13.3 (40 registers) is the one checked; a stale generic 33-register entry no longer overrides it (#4291). Thanks to @Bizuayeu. + +- Docs: Desktop's packaged release notes move to `app/CHANGELOG.md`, apart from the engine's, with a link each way (#4284). Thanks to @garvrao80. + + + + + +- Qwen dense and MoE hybrids on CUDA: opt-in `TF_QWEN_KV_HOST=1` keeps the KV pages in mapped pinned host memory, with the state and verify runs on the device, so a long window can fit on a card with little room left beside the weights; it needs `TF_QWEN_KV_PAGES`, `TF_QWEN_KV_PAGES_ALL=1`, `--parallel 1` and a discrete GPU, takes an optional `TF_QWEN_KV_HOST_GIB` cap, refuses spill, disk snapshots and `TF_QWEN_KV_SHARE` by name, and trades speed for room, since attention reads the pages over the device interconnect; unset, the plan and every path stay as they were (#2637). Thanks to @MaverickKB. + +- GLM-5.3-Flash on CUDA: EXL3 `mcg` routed experts load at any whole-bit width from 1 to 8, mixed by projection within a layer, where only 4-bit was admitted, and the prompt expert kernels gain a 3-bit form; the 4-bit path is unchanged (#2094, refs #2093). Thanks to @MiaAI-Lab. + + + +- Qwen3.8-27B on Metal: a lone sampled stream's DFlash2 draft tree ranks its candidates with the stream's own keyed draw, so the drafts follow what the target samples; the target still decides every token, and greedy and multi-stream rounds are unchanged (#3978). Thanks to @hobbesd. + +- Lane host: concurrent identical prompts join a leader that is filling a prompt state it will keep, so they reuse its whole fill and return the same tokens they would alone; a prompt whose state would not be kept, a zero budget, the leader's cancellation or a timeout still runs on its own (#3693, refs #3397, #3487). Thanks to @bikepresentbal. + +- Load prefetch: DeepSeek's checkpoint reader makes the same number of allocations on every run, so the allocation-failure host test passes on macOS (#4344). + +- Flash Next on HIP: on one GPU, a prompt's first token goes out before its last chunk's kept prompt states are saved, and they are saved before any later step writes the stream's caches; kept-state copies pass through one pinned 32 MiB buffer, and on Linux each kept state sits on small pages of its own (#3647). + +- Server: with `--execution-witness`, `"execution_witness": true` on a chat completion or completion adds an `execution_witness` object to the reply (on a stream, its finish chunk): the witness read when the engine takes the request and again at the end, the SHA-256 of the prompt ids, the resolved request and the reply tokens, the finish reason and a `binding` over them, or `unknown` with a reason (#2958, refs #2741). Thanks to @kotevcode. + +- Idol's octree and Gaussian decoders on CUDA, beside the Metal decoders and driven by the same `tf-idol-decode` case driver and gates. The stem, `to_kv` and the head norms run in fp32 and `input_layer` and the head in true fp32 (no TF32), the blocks through the denoiser's CUDA linears and norms. Attention keeps fp32 scores and sums and rounds P to nearest fp16 as torch's CUDA kernels do, fp32 throughout at 8 query rows or fewer as the cases' SDK runs them. The six kernels and 13 controls are registered with the kernel contract (`tf-cuda-test idol-decoder-contract`). It admits sm_121 (GB10) and sm_120 and refuses other GPUs. It compiles for both and its host tests pass; it has not yet run on a GPU (#1858, after #1773 and #1767, for #1757). Thanks to @jayleaton. + +- TensorFold Web: the packaged stand-in reports 1.3.2, matching the engine version, so the Web checks pass on main again (#4346). + +- Flash Next on XPU: prompt and decode passes run on Xe2 DPAS tile kernels with prompt chunks sized to the solo stream and MTP chains that stop when draft confidence falls, keeping replies bit-exact across chunk sizes (#3603, refs #3583). Thanks to @supernovae. + +- CUDA: at `--tp 2` a Flash Next rank now waits for its peer to finish loading before the first collective, up to 10 minutes instead of failing at the collective's 30 s bound; a peer that fails or closes its link ends the wait with `RankDisconnected` (#2972, fixes #2970). Thanks to @swbiggart. + +- CUDA: at `--tp 2` a Flash Next rank's control-link wait polls with a 50 µs timeout for its first 50 ms and then blocks as before, so drafted rounds pick up the next header sooner; replies are unchanged (#2971). Thanks to @swbiggart. + +- CUDA: `capabilities --json` now advertises `modelopt-mixed` and `modelopt-nvfp4` for the dense Qwen3.5 family, matching the ModelOpt exports its loader serves (#4192). Thanks to @javierbits. +- CUDA capabilities: the dense Qwen3.8-27B row now advertises the ModelOpt exports its loader reads, `modelopt-mixed` (`nvidia/Qwen3.8-27B-NVFP4`) and `modelopt-nvfp4`, beside `mlx-q4g64` and `exl3`; a client that filters on `capabilities --json` no longer hides a checkpoint the engine serves (#4150). Thanks to @Flyinpiz-dev. +- HIP: the gfx12 WMMA step pieces move from `tiles/wmma12_gemm.hpp` into a shared header, `tiles/wmma12_step.hpp`, for the coming gfx12 affine tile; it is only a move, so the kernels' bytes do not change (#3862, refs #2401). Thanks to @millaguie. + +- CI: the Zig format workflow runs again on pushes and pull requests; two concurrency settings had left its file with a duplicate key, which GitHub refused (#4339). + +- Server: `POST /v1/prompt_cache/flush` drops the prompt states the server keeps for resuming conversations, in RAM and on disk when it keeps them there (`--prompt-cache-disk`, `--learn-conversations` or `--spill-gib`), once no request is running, so replies in flight are unchanged; it needs a full or `[admin]` key when API keys are on (a loopback caller without keys), answers 503 if requests have not ended within 10 minutes and 501 on an engine without the prompt cache, and leaves `--learn`'s shared-prefix states on disk (#3210, fixes #3183). + +- DeepSeek V4.1 on Metal keeps sampling scratch between picks and scans greedy logits in vectors with the same chosen IDs (#3288). + +- Flash Next on CUDA: a bf16 language head's draft rows load as 4-bit affine groups of 32 by default, and `TF_FLASHNEXT_DRAFT_HEAD=bf16` keeps them as stored; a malformed value stops the start by name, and replies are unchanged because drafts are verified (#3477, refs #1870). Thanks to @BadAd84. + +- Idol's FLUX.2 VAE image encoder runs natively on Metal in fp32: one 1,024 x 1,024 picture to the denoiser's 4,101 condition rows, with the posterior's noise as an input. It is 0.185 s an encode on an M5 Ultra against 0.095 s for the SDK's bf16 encoder on torch MPS, and lies far closer to a float64 run: worst row 5.1e-5 against the SDK's 2.7e-2. `tf-idol-vae` gates it from a case `tools/zig/idol_case.py vae` records, with the ungated FLUX.2-klein-4B weights (#1774, after #1766, for #1757). Thanks to @jayleaton. + +- Nemotron on HIP: at `--tp 1`, `--mtp-drafts` takes up to 15, widening a lone stream's verify window up to 16 rows; unset or at 3 or fewer the window stays at four rows, rounds shared by several streams chain at most three drafts a stream, and above `--tp 1` more than three is refused by name (#3613, refs #3394). Thanks to @gilby. + +- Server: opt-in --tool-think-close bounds thinking for required or named tool calls so the call has room in max_tokens; the flag defaults off and keeps smaller thinking budgets (#4157). Thanks to @jayleaton. + +- CUDA: Drama 3 loads compact NVFP4 checkpoints as stored, stages held experts in slot order, and masks routing to their original ids (#4144). Thanks to @plotarmordev. + +- CUDA: opt-in TF_DSV41_FLOAT_LINEAR runs DeepSeek-V4.1 backbone projections kept as float matrices on the plain path; with it unset, such a pack is still refused (#4076). Thanks to @BadAd84. + +- Docs: the README's build section says that a Linux `zig build native` compiles for the build machine's CPU, and that `-Dcpu=baseline` or `-Dcpu=x86_64_v3` builds a binary for another machine, with thanks to @Nipale-ai (#3179; #3301). + +- Spark 2.5 on CUDA: gate and up load as one stacked weight and decode in one launch on every CUDA chip instead of two launches, with the bits unchanged; only 4-bit checkpoints take this path (#3130). + +- LFM2-MoE and LFM3 on Metal: a keep that drops no rows skips the conv-state and logits copy in `Cache.keep`, since `commit` and `run` already wrote those bytes; a partial keep still restores through a new `take()` (#3078). + +- LFM2-MoE on Metal: prefill runs one chunk a call with decode rounds between chunks, so a new prompt no longer stalls other streams' replies; the backend declares `prefill_step` and `cancel_prefill` beside `reports_fill` (#3058). + +- Tools: `tools/comfyui_runtime` installs the offline ComfyUI MOSS sampler on a GB10: it checks the release CLI and the pinned native source, builds only `moss-image-cuda`, and switches to a new runtime only after integrity and run checks, keeping the active one when setup fails; a separate offline tool writes fused BF16 checkpoint metadata without changing tensor payloads (#2737). + +- CI: the Zig format and TensorFold Web workflows cancel a pull request's older run when it gets a newer push, so superseded runs no longer queue; main pushes all run (#3850). + +- Server: chat and legacy completions requests take `deadline_s` (seconds, more than 0 and at most 1,000,000; any other value is refused before the engine): at that time the server cancels the engine itself and the reply ends with `finish_reason: "deadline"`, keeping every token the engine gave and its usage; a reply the engine ended first, or a cancel that came first, keeps its own ending, and without the field nothing changes (#3438). Thanks to @jayleaton. + +- Tests: the CUDA kernel contract's NVFP4_NZ5 stress fill holds +5s among its 4s and 6s, its float64 reference reads code 0b1000 as 5, and a second planted control goes red at the sums gate, so that gate covers the +5 code; no kernel changes (#3543, refs #2894). Thanks to @Bizuayeu. + +- CUDA on unified-memory Linux (GB10): the start-up memory budget is at most the free memory CUDA reports, less the same reserve, instead of `/proc/meminfo` alone, and the server first drops the checkpoint's own shards from the page cache, so a checkpoint that was just read is not refused for its own cached pages; discrete cards, Windows, Metal and HIP are unchanged (#3192, part of #1857). + +- Qwen 3.5/3.6/3.8 on CUDA: a prompt chunk before the last that nothing reads (no last-layer tap, learning, MLP or pocket reader, prompt int8 path or image) stops its last layer after its keys, values and RoPE, skipping that layer's query projection, attention, output projection, MLP and head, with the same reply tokens; the final chunk is unchanged (#3060, fixes #2941). Thanks to @javierbits. + +- Qwen3.5 on CUDA: EXL3 checkpoints with the mcg codebook marker are admitted alongside mul1 ones, and unknown markers are still refused as an unsupported quantization (#3412). Thanks to @Ch0mpaa. + +- LFM3 on Metal: a new prompt is filled a chunk at a time between other streams' decode rounds instead of stalling them for its whole prefill, and a pass can be cancelled keeping the state at the last chunk's end; chunks are cut exactly as before, so replies are unchanged (#3088, part of #3021). + +- LFM3 on Metal: in a shared round, every stream's qk now runs in one dispatch instead of once per stream per attention layer, with the same arithmetic per row, so replies are unchanged (#3079). + +- Prompt cache: save states displaced by backend expiry to the eviction-only disk tier, avoiding stale resumptions (fixes #2669). + +- Qwen3.8-27B on Metal: lease the GDN rollback bank from the shared recurrent workspace (#4178). Thanks to @jschmied. + +- Cluster: bring-up reports the leader, epoch and view it agreed on and counts only acknowledgments for that view, so a rank that finishes after a peer says goodbye no longer reports a smaller view on slow runners (#4135, fixes #4123). Thanks to @AIFlowML. + +- GLM-5.3-Flash on CUDA: drafted decode after a 1,040,384-token prompt takes its DSA index scores from `tf_glm_index_scores`, 13.8% faster at TP=4 (172.39 against 151.51 tok/s median) with byte-identical scores and the same tokens; shorter windows keep `tf_glm_scores` (#3689). Thanks to @Bizuayeu. +- Flash Next on HIP: on one GPU with the prompt cache on, a prompt chunk runs on through the prompt-cache marks its side buffers can hold, writing each marked row's state aside, instead of ending at the first mark (#3646). + +- GLM-5.3-Flash on CUDA: `TF_GLM_DRAFT_SPLIT=1` splits the DFlash2 drafter's MLP across three ranks or more where each share is 256-aligned, without `TF_ROCE=1`; the ranks must set it alike, two ranks split as before, and unset changes nothing. On three GB10s whose gathers stay on NCCL, decode with `--drafter` is about 5% faster at one stream (four streams within their start-to-start spread), with the same replies and the same tokens a round on the measured prompts. As with `TF_ROCE=1`, the split drafter adds its down projection's rank shares in another order, so its proposals can differ at near-ties (#3616, for #3581). + +- Flash Next on HIP: on an integrated GPU that shares the host's pages (no firmware carve-out), the default kept-prompt cache takes no more than the memory the streams leave, at most 16 GiB and none when nothing is left; an explicit `--prompt-cache-gib` still sets it (#3645). + +- Tests: the Web loopback startup test sets its fixture ready before probing, so its health, model-list and relay checks no longer depend on warm-up timing (#3753, fixes #3752). Thanks to @AIFlowML. +- Ling-3.0-tiny on Metal: a bf16 forward diagnostic runs all 24 layers of the published checkpoint on kernels that already exist, with no new GPU kernel source; `zig build test-ling-forward`, given `TF_LING_CHECKPOINT` and a Python with torch and safetensors (`TF_LING_PYTHON`), checks whole, chunked and resumed runs byte for byte and reports the distance from float64. Nothing is served yet (#3919, part of #1247). Thanks to @ThinkOffApp. + +- Server: `TENSORFOLD_PARALLEL` sets the default lanes when `serve` has no `--parallel`: a whole number 1 to 4096 or `auto`; the flag wins when both are given, a blank value keeps the default, and any other value is refused by name at startup (#3685, for #3684). Thanks to @bikepresentball. + +- Lane host: a streamed reply whose client falls 1,024 tokens behind sits out rounds until the reader is within 512 again, and one whose client reads nothing for 60 seconds is cancelled like a disconnect, so a stalled reader stops holding its lane; the text a reader receives is unchanged (#3234). + +- Web: Qwen3.6-35B-A3B is listed for CUDA only, and starting it on a machine without CUDA is refused before anything launches, so a Mac is no longer pointed at the Python engine for it (#3738, refs #3710). Thanks to @AIFlowML. + +- Flash Next on HIP: the first stream's caches are made at load, so the first prompt no longer waits on allocating them; each layer's weights are read past the page cache by threads, the next layer's read under way, and the n-gram gather spreads over all of the pool's parts instead of at most 32 (#3644). + +- App on Linux: with `TENSORFOLD_LINUX_SANDBOX=1` and bubblewrap installed, agent commands run in a bubblewrap sandbox that keeps every repository's `config`, `config.worktree`, `hooks` and `info` read-only, nested repositories included, and freezes worktree `.git` pointers; a workspace with no repository, a worktree whose gitdir or shared directory lies outside the workspace, a path the sandbox cannot inspect, or a walk past 32 levels or 50,000 directories is refused with code 126 before anything runs. Without the setting, Linux commands stay refused as before (#3364, fixes #1693). Thanks to @eXsoR65. + +- Gemma 4 on Metal: each linear's bytes are held once instead of three times (the shard, the lane or row pack and a prompt-chunk copy): the linears are staged from their files during load and the files close after it, with the same bytes and the default prompt-cache budget unchanged (#3350). Thanks to @jschmied. + +- Server: `/v1/messages` and its `count_tokens` accept Anthropic's deferred tools: a tool with `defer_loading: true` stays out of the prompt until a `tool_reference` block in a `tool_result` loads it, rendered by a template that reads both fields (GLM-5.3's) or else as the tool's name, description and parameters in text; a reference to a tool the request does not offer, a non-boolean `defer_loading` or all tools deferred is refused, and requests without these fields are unchanged (#3212, fixes #3115). + +- MiniMax-M3 on Metal: the DFlash2 and DSpark drafters hold up to eight streams' blocks in one pass and one wait instead of a pass per stream, and absorb no longer waits for the GPU; drafted replies are unchanged (#3121). + +- MiniMax-M3 on Metal: a new prompt is filled a chunk at a time between other streams' decode rounds instead of stalling them for its whole prefill, and a stepping drafter absorbs each chunk before the next; a pass can be cancelled keeping the state at the last chunk's end, and chunks are cut exactly as before, so replies are unchanged (#3089, part of #3021). + +- Server: `response_format: {"type": "structural_tag", ...}` on the native server keeps the reply free text while each structure's `begin` opens a region that must be JSON matching its `schema` and close with its `end`, with optional `triggers`; past 64 structures or triggers, 256-byte tags or the 512 KiB grammar limit the request is refused with HTTP 400 before any stream starts (#3208). + +- Qwen3.8 Flash Next on Metal: a request cancelled while its prompt is still filling keeps the prompt state it had already landed at a resumable cut, so a follow-up with the same prefix resumes from there instead of starting over (#3657, refs #3618). + +- GLM-5.3-Flash on Metal can draft with a published DFlash2 checkpoint behind `--drafter DIR` (and `--drafter-bits`); drafted replies equal plain ones, and the default stays MTP (#3920). Thanks to @gilby. + +- Qwen3.5-2B on Metal: a new stream's prompt runs one chunk a call at the same cuts as before, so other streams' decode rounds run between its chunks instead of waiting for the whole prompt; a cancel between chunks keeps the state at the last chunk's end (#3090, refs #3021). + +- Tools: add tf-h3-image to compare MiniMax-H3-Image Metal transformer steps with exported picture cases (#2766). + +- Qwen3.8-27B on Metal with `TF_QWEN27_METAL_KV_PAGES=1`: a stream that opens a slot is promised the KV pages of its prompt and one widest pass instead of every slot being promised its whole window at load; a pass past that promises the rest before it takes a page and fails with `LaneMemory` before any page is taken when the pool cannot meet it, and a stream that leaves, a failed or requeued prompt pass, a reset and a move to slot 0 give back the slot's pages and promise. Without the flag nothing changes (#3377, refs #1293). Thanks to @CodingEmil. +- Qwen3.8-27B on Metal with `TF_QWEN27_METAL_KV_PAGES=1`: Macs with tensor units (M5) take the flag instead of refusing it, and a paged prompt pass finds each 512-key chunk's two pages once instead of reading the page table at every 32-key step, with every token and cache row unchanged (#3180, part of #1293). Thanks to @CodingEmil. +- Nemotron 3.5 Lightning on HIP: the MTP head file is read at the width its own metadata states, so it drafts beside an oQ checkpoint of any width, and a head at a width the launches do not read is refused by name (#3251, part of #3061). Thanks to @gilby. + +- Tests: the served-evidence concurrency test pairs its two generated streams in the fake server, so a busy runner can no longer decode them one after the other and turn it red; other conformance fixtures keep their pacing. + - GLM-5.3-Flash on CUDA at tensor-parallel widths where a rank's fused KDA input is not a multiple of eight columns (TP=3, 5, 6 or 7): the stack is padded at load to its own width rounded up to eight columns and stays row-major bf16, so prompt windows take the staged B16 tiles with every byte as before; `TF_GLM_KDA_PAD=1` still tiles the stack for glm_mm (#3697, for #3516). Thanks to @ultradaoto. - Windows: the native CUDA product compiles again: Muse Spark, which needs two TP ranks over the POSIX-only TP fabric, is refused by name on Windows (TP across ranks runs on Linux only) instead of breaking the build, and CI now type-checks the Windows CUDA product (`zig build compile-native-cuda-windows`, #4171, fixes #4105). diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 9c9f5c0ac6d..9da3dcbcf7f 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -67,6 +67,10 @@ Without Xcode's Metal compiler it warns `skipping offline Metal shader checks` a tests that need Linux, CUDA or a Metal device skip themselves. `native` writes `zig-out/native/bin/tensorfold-native`, the server. +On Linux, `zig build native` compiles for the build machine's CPU, so the binary can stop with `Illegal instruction` on a +machine without the same features (AVX-512, for example). To build for another machine, name its CPU: `-Dcpu=baseline` +runs on any x86_64, as the release archives do, and `-Dcpu=x86_64_v3` on an x86-64-v3-capable machine (AVX2 class). + Structured output and required tool calls need the release archive's `lib/` or `zig build grammar -Dxgrammar=DIR`; prepare DIR with `git clone --branch v0.2.8 --recurse-submodules https://github.com/mlc-ai/xgrammar` (use the native build's same `--prefix` for grammar). To build one stripped server for one GPU (`zig build -Dgpu=spark -Dnvcc=...`, about 69% smaller than the four-target server), see [Build a server for one GPU](RUNBOOK.md#build-a-server-for-one-gpu). The `apple_m1` CPU target keeps the macOS binary compatible with M1 through M5. diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index 430e65e7a5c..175ea1db71b 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -575,3 +575,12 @@ model and states no licence; no weights are included. `tools/zig/inkling2_fixtur from `Inkling2L2Clip` and `Inkling2ScaledL2Clip`, the relative-position logits from `Inkling2RelativeLogits`, and the sinks and sigmoid output gate from `Inkling2SlidingAttention` and `Inkling2FullAttention`. The kernels, their chunked layout and their rounding points are TensorFold's own. + +## Inkling 2 glue kernels + +`zig/kernels/cuda/inkling2/ops.cu`, `zig/kernels/cuda/inkling2/rows.cu` and `zig/src/families/inkling2/ops.zig` compute +these layers of Hugging Face transformers' `src/transformers/models/inkling2/modeling_inkling2.py` at commit +`109a7d19bf66` ([huggingface/transformers](https://github.com/huggingface/transformers), Apache-2.0): +`Inkling2NormedEmbedding`, `Inkling2BlockAttentionResidual`, `Inkling2ShortConvolution`, +`Inkling2DynamicShortConvolution`, `Inkling2TopKRouter`, `Inkling2SoftcappedSwiGLU` and `Inkling2Softcap`. The kernels +are TensorFold's own. diff --git a/app/CHANGELOG.md b/app/CHANGELOG.md new file mode 100644 index 00000000000..d96ef06a356 --- /dev/null +++ b/app/CHANGELOG.md @@ -0,0 +1,36 @@ +# TensorFold Desktop changelog + +Desktop installers ship under `app-v*` tags. Engine updates follow a separate release schedule. +See the [engine changelog](../CHANGELOG.md) for engine releases. + +## Unreleased + +These are highlights from changes merged after Desktop 1.0.0. They are available in builds from +current source and are awaiting a packaged Desktop release. + +- Search in **Current conversation** ignores the project filter from **All saved conversations**. + Switching back restores the selected project. [#3900](https://github.com/ashhart/TensorFold/pull/3900) +- **Planning only** opens the model picker on **Local**. The regular model button opens **All**. + [#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) +- **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 + before enabling copy or save. [#3834](https://github.com/ashhart/TensorFold/pull/3834) +- Model downloads honor proxy settings and offer a retry when a download stalls or fails. + [#4141](https://github.com/ashhart/TensorFold/pull/4141) +- Benchmarks accept community-v2 results and preserve optional Mac product-family labels in + saved history and exports. [#4031](https://github.com/ashhart/TensorFold/pull/4031) · [#2693](https://github.com/ashhart/TensorFold/pull/2693) + +## 1.0.0 · 2026-11-02 + +[TensorFold for Mac 1.0.0 release notes and installer](https://github.com/ashhart/TensorFold/releases/tag/app-v1.0.0) + +- First stable Desktop release for Apple silicon Macs running macOS 13.3 or later. +- Ask TensorFold adds a compact input bar with window selection and capture preview. The main + window can close into the background and reopen from the menu bar. +- Connection health and the unified inbox show account status and provider errors. The interface + includes Portuguese. +- The installer bundles engine 1.2.0. The app can download and activate engine 1.2.1 separately + from **Models → Details → Engine updates**. diff --git a/app/README.md b/app/README.md index 2228ee9dd39..165bbcf7bd4 100644 --- a/app/README.md +++ b/app/README.md @@ -4,8 +4,9 @@ An agentic AI coding app for the Mac, with the TensorFold engine built in. It al any OpenAI‑compatible LLM endpoint, local or cloud. The look comes from the TensorFold brand: graphite and navy surfaces, an electric-blue primary and the fold gradient. -The current desktop release is [beta 9](https://github.com/ashhart/TensorFold/releases/tag/v1.0.0-beta.9). -It launches the bundled native Zig engine directly. +Download [TensorFold for Mac 1.0.0](https://github.com/ashhart/TensorFold/releases/tag/app-v1.0.0), +the current Desktop release. It launches the bundled native Zig engine directly. +See the [Desktop changelog](CHANGELOG.md) for shipped and unreleased app changes. It reads, edits, and runs your code through a tool‑use loop, with streaming responses, live diffs, and per‑action approval. diff --git a/app/docs/linux-port/SANDBOX-REVIEW.md b/app/docs/linux-port/SANDBOX-REVIEW.md index b78c990d3ad..ab7bfeb7667 100644 --- a/app/docs/linux-port/SANDBOX-REVIEW.md +++ b/app/docs/linux-port/SANDBOX-REVIEW.md @@ -2,20 +2,23 @@ ## Status -The bubblewrap backend is **not part of this change**: it was written, reviewed below, and then scoped out -until the gaps in items 1 and 2 close (git metadata for absent, nested and worktree repositories; minimal -runtime roots). This review and the plan that carried the backend are the record; the branch keeps Linux -commands on the existing fail-closed behaviour. No product default was weakened. +The bubblewrap backend is **implemented on this branch** and stays opt-in +(`TENSORFOLD_LINUX_SANDBOX=1`). This review is the record of what blocked it; the blockers below are +now either closed or stated as limits in [STATUS.md](STATUS.md). No product default was weakened: +without the opt-in, Linux `run_command` keeps the existing fail-closed behaviour. -This read-only subagent review identified issues missed during initial implementation. Prior claims that the failing probe proved a nested-container limitation were not established: its namespace lacks the ELF dynamic loader path. Merely passing argument-construction tests does not prove confinement. +The read-only subagent review identified issues missed during initial implementation. Prior claims +that the failing probe proved a nested-container limitation were not established: its namespace +lacked the ELF dynamic loader path. Passing argument-construction tests alone does not prove +confinement either; the conformance test exercises a real namespace. ## Release blockers -1. **Mount ordering:** all read-only mounts precede all writable mounts. A writable TMPDIR parent hides a read-only workspace mount below it. Build one ordered mount plan with explicit permissions, or private scratch mounts; test effective writes, not argument presence. -2. **Git-control protection:** existing top-level entries alone are insufficient. Missing controls, fresh/nested repositories, submodule metadata, and worktree pointers/common directories are not safely covered. A writable `.git` pointer can be retargeted in place. Enumeration cannot prevent future Git metadata creation in arbitrary writable directories. Choose an enforceable confinement design or reject unsupported writable execution; do not advertise SBPL parity. -3. **Capability probe:** the `/usr`-only probe omits `/lib64` (and `/lib` on some systems), causing ENOENT for dynamically linked executables. Derive probes from the production mount plan, use matching namespace flags, and preserve diagnostic reasons. Do not retry sandbox-denied tool operations through another route. -4. **Runtime visibility:** user-managed Node/Python/Rust/Nix installations remain in PATH but outside mounted roots. Add minimal explicit trusted runtime roots rather than mounting HOME wholesale. -5. **Validation:** live tests currently skip when the bad probe fails. Add a required Linux CI lane with known-working bubblewrap. Use owned outside-workspace files for denial tests, local listener positive/negative network controls, and actual Git repositories. Cover temp overlap, metadata creation/retargeting, worktrees, nested repositories, shell cancellation, usrmerge and runtime paths. +1. **Mount ordering (closed):** all read-only mounts precede all writable mounts. A writable TMPDIR parent hides a read-only workspace mount below it. Build one ordered mount plan with explicit permissions, or private scratch mounts; test effective writes, not argument presence. +2. **Git-control protection (closed, with stated limits):** existing top-level entries alone are insufficient. Missing controls, fresh/nested repositories, submodule metadata, and worktree pointers/common directories are not safely covered. A writable `.git` pointer can be retargeted in place. Enumeration cannot prevent future Git metadata creation in arbitrary writable directories. Choose an enforceable confinement design or reject unsupported writable execution; do not advertise SBPL parity. +3. **Capability probe (closed):** the `/usr`-only probe omitted `/lib64` (and `/lib` on some systems), causing ENOENT for dynamically linked executables. Derive probes from the production mount plan, use matching namespace flags, and preserve diagnostic reasons. Do not retry sandbox-denied tool operations through another route. +4. **Runtime visibility (open):** user-managed Node/Python/Rust/Nix installations remain in PATH but outside mounted roots. Add minimal explicit trusted runtime roots rather than mounting HOME wholesale. +5. **Validation (partly closed):** live tests skip when the probe fails; a Linux CI lane exists but does not install bubblewrap, so device-level conformance must run on a host that has it. Add a required Linux CI lane with known-working bubblewrap. Use owned outside-workspace files for denial tests, local listener positive/negative network controls, and actual Git repositories. Cover temp overlap, metadata creation/retargeting, worktrees, nested repositories, shell cancellation, usrmerge and runtime paths. ## Other corrections diff --git a/app/docs/linux-port/STATUS.md b/app/docs/linux-port/STATUS.md index 40a1feceae5..50bf63975b8 100644 --- a/app/docs/linux-port/STATUS.md +++ b/app/docs/linux-port/STATUS.md @@ -55,22 +55,29 @@ clean-machine install. read the workspace on any platform. Attachments are the supported way to give a bot file content; workspace work belongs to a task or project chat. -## Linux command sandbox — separate work, not in this change - -Per the maintainer's review, the bubblewrap backend is not part of this client portability change: -commands stay refused on Linux until the git and worktree gaps are closed. The implementation and its -conformance test are preserved on the `sandbox-followup` branch for a separate PR. It remains -**opt-in** (`TENSORFOLD_LINUX_SANDBOX=1`) because three deviations from the macOS sandbox profile -remain: - -1. Creating a brand-new `.git` where none exists cannot be denied; existing repositories pin `.git` - against rename and pin `config`, `config.worktree`, `hooks` and `info` read-only. -2. Nested repositories and submodule gitdirs below the workspace root are not pinned. -3. A worktree `.git` pointer file is mounted writable, so its external gitdir is not protected. - -On this branch the Linux backend is absent entirely, so `run_command` keeps the existing fail-closed -behavior; the development-only `VONTRA_ALLOW_UNSANDBOXED_COMMANDS=1` escape hatch is unchanged. Details and review -history: [SANDBOX-REVIEW.md](SANDBOX-REVIEW.md). +## Linux command sandbox — follow-up branch + +The bubblewrap backend is implemented on this branch and stays **opt-in** +(`TENSORFOLD_LINUX_SANDBOX=1`) until a maintainer decides otherwise. It pins every repository it +finds under the workspace — including repositories inside dependency folders and nested worktrees — +and refuses instead of protecting only some. + +Limits, stated rather than hidden: + +1. A workspace with no repository is refused: bwrap mounts paths and cannot deny creating `.git` by + name, so the sandbox requires metadata it can pin. +2. The walk refuses at 32 directory levels or 50,000 directories rather than silently pinning a + subset, and it refuses when it cannot inspect a path (permission denied, I/O error) instead of + skipping a directory that could hold a repository. A workspace that trips any of these keeps + commands refused. +3. Control entries a repository does not have yet (`config.worktree`, `hooks`, `info`) are mounted + read-only from empty placeholders, which bwrap creates as empty files or directories inside + `.git` on first use. A writable run therefore cannot add or edit them. +4. A worktree's `.git` pointer file is mounted read-only and its gitdir and shared directory must + stay inside the workspace; anything else is refused before a command runs. + +The development-only `VONTRA_ALLOW_UNSANDBOXED_COMMANDS=1` escape hatch is unchanged. Details and +review history: [SANDBOX-REVIEW.md](SANDBOX-REVIEW.md). ## Connecting to a Mac engine diff --git a/app/electron/agent/engine/hub.test.ts b/app/electron/agent/engine/hub.test.ts index 020934590d4..3c8fd890bc7 100644 --- a/app/electron/agent/engine/hub.test.ts +++ b/app/electron/agent/engine/hub.test.ts @@ -126,9 +126,13 @@ async function main() { assert.ok(blocked.calls.filter((url) => url.endsWith('/config.json')).length <= 6, 'same-origin redirect loops are bounded') } - // Installed already. + // Installed already, with or without an app-managed selection. const installed = await preflightRepo('mlx-community/Qwen3.5-2B-MLX-4bit', null, context(ok.fetchImpl, { installed: new Set(['mlx-community/Qwen3.5-2B-MLX-4bit']) })) assert.equal(installed.verdict, 'installed') + const selected = await preflightRepo('mlx-community/Qwen3.5-2B-MLX-4bit', null, context(ok.fetchImpl, { installed: new Set(['mlx-community/Qwen3.5-2B-MLX-4bit']), installedRevision: async () => SHA })) + assert.equal(selected.verdict, 'installed') + const external = await preflightRepo('mlx-community/Qwen3.5-2B-MLX-4bit', null, context(ok.fetchImpl, { installed: new Set(['mlx-community/Qwen3.5-2B-MLX-4bit']), installedRevision: async () => null })) + assert.equal(external.verdict, 'installed') // Unsupported family, and a drafter on its own. const gemma = mockHub(repoRoutes('google/gemma-9', { modelType: 'gemma4' })) diff --git a/app/electron/agent/engine/hub.ts b/app/electron/agent/engine/hub.ts index 9fe020a31ce..a588b0f5707 100644 --- a/app/electron/agent/engine/hub.ts +++ b/app/electron/agent/engine/hub.ts @@ -173,9 +173,9 @@ export interface PreflightContext extends HubDeps { // App admission policy per checkpoint family: a user load-limit override applies to its own family only. memoryLimitFor?: (modelType: string | null) => { bytes: number; basis: string } installed: Set + installedRevision?: (repo: string) => Promise drafterFor: (repo: string) => string | null cachedBytes: (repo: string) => Promise - freeDiskBytes: () => Promise now?: () => number } @@ -218,7 +218,8 @@ export async function preflightRepo(repo: string, revision: string | null, ctx: const neededDiskBytes = Math.max(0, totalBytes - cachedBytes) const freeDiskBytes = await ctx.freeDiskBytes() const fitsDisk = freeDiskBytes == null ? null : freeDiskBytes >= neededDiskBytes + DISK_HEADROOM_BYTES - const installed = ctx.installed.has(repo) + const selectedRevision = ctx.installedRevision ? await ctx.installedRevision(repo) : null + const installed = ctx.installed.has(repo) && (selectedRevision == null || selectedRevision === sha) const reasons: string[] = [] if (!modelType) reasons.push('Its config.json names no model_type, so no engine family can be matched.') diff --git a/app/electron/agent/engine/model-hub.ts b/app/electron/agent/engine/model-hub.ts index ef103c6ffdf..7d0baa52b95 100644 --- a/app/electron/agent/engine/model-hub.ts +++ b/app/electron/agent/engine/model-hub.ts @@ -15,8 +15,8 @@ interface ModelHubOptions { totalMemoryBytes: number capabilities: () => Promise 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 @@ -54,7 +54,7 @@ export class ModelHub { const result = await preflightRepo(repo, revision, { ...this.deps(), families: caps.families, familyTitles: FAMILY_TITLES, totalMemoryBytes: this.options.totalMemoryBytes, memoryLimitBytes: memory.limit, memoryBudgetBytes: memory.budget, memoryLimitFor: memory.limitFor, - installed: new Set(installed.map((m) => m.repo)), drafterFor, + installed: new Set(installed.map((m) => m.repo)), installedRevision: this.options.installedRevision, drafterFor, cachedBytes: (r) => repoCachedBytes(this.options.cacheDir(), r), freeDiskBytes: () => freeDiskBytes(this.options.cacheDir()), }) diff --git a/app/electron/agent/engine/model-revisions.test.ts b/app/electron/agent/engine/model-revisions.test.ts index d9f363938c5..fb799609eb6 100644 --- a/app/electron/agent/engine/model-revisions.test.ts +++ b/app/electron/agent/engine/model-revisions.test.ts @@ -7,6 +7,7 @@ import { makeHarness, seedModel, waitFor } from './test-fixtures/harness' const SHA = 'd'.repeat(40) const OTHER = 'e'.repeat(40) +const NEWER = 'b'.repeat(40) const REPO = 'Org/Reviewed' const PRIMARY = 'TensorFold/Qwen3.8-27B-MLX-4bit' const DRAFTER = 'z-lab/Qwen3.8-27B-DFlash2' @@ -25,9 +26,10 @@ function reviewedFetch(options: { invalidSha?: boolean; missingDrafter?: boolean if (route === `/${ownerRepo}/resolve/${sha}/config.json`) body = { model_type: 'qwen3_5', quantization: { bits: 4, group_size: 64 } } if (ownerRepo === DRAFTER && options.missingDrafter) body = undefined } + if (route === `/api/models/${REPO}/revision/newer`) body = { sha: NEWER } if (route === `/api/models/${REPO}/revision/unsupported`) body = { sha: OTHER } - if ([`/api/models/${REPO}/tree/${SHA}`, `/api/models/${REPO}/tree/${OTHER}`].includes(route)) body = [{ type: 'file', path: 'model.safetensors', size: 8192 }] - if (route === `/${REPO}/resolve/${SHA}/config.json`) body = { model_type: 'qwen3_5', quantization: { bits: 4, group_size: 64 } } + if ([`/api/models/${REPO}/tree/${SHA}`, `/api/models/${REPO}/tree/${OTHER}`, `/api/models/${REPO}/tree/${NEWER}`].includes(route)) body = [{ type: 'file', path: 'model.safetensors', size: 8192 }] + if ([`/${REPO}/resolve/${SHA}/config.json`, `/${REPO}/resolve/${NEWER}/config.json`].includes(route)) body = { model_type: 'qwen3_5', quantization: { bits: 4, group_size: 64 } } if (route === `/${REPO}/resolve/${OTHER}/config.json`) body = { model_type: 'gemma4' } return body ? new Response(JSON.stringify(body), { headers: { 'content-type': 'application/json' } }) : new Response('missing', { status: 404 }) }) as typeof fetch @@ -44,7 +46,11 @@ async function main() { await waitFor(() => service.pullList().find((p) => p.repo === REPO && p.state === 'done')) const pull = (await h.records()).find((r) => r.kind === 'pull') assert.equal(pull.revision, SHA, 'the actual child must pull the immutable checkpoint whose format and memory were reviewed') - await service.preflight(REPO) // Re-populate the main-review cache after the completed pull invalidates it. + const sameRevision = await service.preflight(REPO) + assert.equal(sameRevision.verdict, 'installed', 'the selected immutable revision stays installed') + const newerRevision = await service.preflight(REPO, 'newer') + assert.equal(newerRevision.resolvedRevision, NEWER) + assert.equal(newerRevision.verdict, 'ok', 'a different immutable revision remains available for download') await assert.rejects(() => service.pull(REPO, 'unsupported'), /serves no gemma4/, 'a cached main preflight cannot authorize another revision') const registry = path.join(h.root, 'engine', 'model-revisions.json') diff --git a/app/electron/agent/engine/service.ts b/app/electron/agent/engine/service.ts index 8672bafec11..4c1d0673b46 100644 --- a/app/electron/agent/engine/service.ts +++ b/app/electron/agent/engine/service.ts @@ -111,7 +111,7 @@ export class EngineService { this.envOverridesApplied = this.preferences.get().envOverrides this.models = new ModelHub({ endpoint: this.launch.endpoint, fetch: options.fetch, env: () => this.env, totalMemoryBytes: this.totalMemoryBytes, - capabilities: () => this.capabilitiesDoc(), installed: () => this.installed(), cacheDir: () => this.hub, + capabilities: () => this.capabilitiesDoc(), installed: () => this.installed(), installedRevision: (repo) => this.revisions.selected(repo), cacheDir: () => this.hub, memory: () => ({ limit: this.supervisor.memoryLimitBytes, budget: this.supervisor.memoryBudgetBytes, limitFor: (modelType) => this.supervisor.memoryPolicyFor(modelType) }), }) this.revisions = new ModelRevisions(options.appHome, () => this.hub) diff --git a/app/electron/agent/linux-sandbox.conformance.test.ts b/app/electron/agent/linux-sandbox.conformance.test.ts new file mode 100644 index 00000000000..91f0f88ec48 --- /dev/null +++ b/app/electron/agent/linux-sandbox.conformance.test.ts @@ -0,0 +1,137 @@ +// A restricted namespace must report a skip rather than claim confinement. +import assert from 'node:assert/strict' +import { createServer } from 'node:net' +import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs' +import { homedir, tmpdir } from 'node:os' +import path from 'node:path' +import { runSandboxedCommand } from './sandbox' + +process.env.TENSORFOLD_LINUX_SANDBOX = '1' +const { canUseLinuxSandbox, probeLinuxSandbox } = await import('./linux-sandbox') + +if (process.platform !== 'linux') { + console.log('CONFORMANCE: skipped (not Linux)') +} else if (!probeLinuxSandbox(process.cwd())) { + console.log('CONFORMANCE: skipped (bubblewrap cannot create a namespace on this host)') +} else { + assert.equal(canUseLinuxSandbox(), true, 'the opt-in enables the backend once the probe passes') + const root = realpathSync(mkdtempSync(path.join(realpathSync(tmpdir()), 'tf-bwrap-conformance-'))) + const cwd = path.join(root, 'ws') + mkdirSync(path.join(cwd, '.git', 'hooks'), { recursive: true }) + writeFileSync(path.join(cwd, '.git', 'config'), '[core]\n') + + const server = createServer((socket) => socket.end('ok')) + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)) + const port = (server.address() as { port: number }).port + + try { + const hello = await runSandboxedCommand('printf confined', { cwd }) + assert.equal(hello.stdout, 'confined') + assert.equal(hello.implementation, 'linux-bwrap', 'the Linux backend reported the run') + + const inside = await runSandboxedCommand('printf data > inside.txt', { cwd, profile: 'build-test' }) + assert.equal(inside.code, 0, inside.stderr) + assert.equal(readFileSync(path.join(cwd, 'inside.txt'), 'utf8'), 'data') + + const outsideTarget = path.join(realpathSync(homedir()), 'tf-bwrap-escape.txt') + const outside = await runSandboxedCommand(`printf escape > ${JSON.stringify(outsideTarget)}`, { cwd, profile: 'build-test' }) + assert.notEqual(outside.code, 0, 'writes outside the mounted roots fail') + assert.equal(existsSync(outsideTarget), false, 'nothing appeared outside the workspace') + + const readOnly = await runSandboxedCommand('printf blocked > ro.txt', { cwd, profile: 'read-only' }) + assert.notEqual(readOnly.code, 0, 'read-only profiles cannot write the workspace') + assert.equal(existsSync(path.join(cwd, 'ro.txt')), false) + + const gitTamper = await runSandboxedCommand('printf pwned > .git/hooks/evil', { cwd, profile: 'build-test' }) + assert.notEqual(gitTamper.code, 0, 'git hooks stay read-only under a writable profile') + assert.equal(existsSync(path.join(cwd, '.git', 'hooks', 'evil')), false) + + const gitConfig = await runSandboxedCommand('printf pwned >> .git/config', { cwd, profile: 'build-test' }) + assert.notEqual(gitConfig.code, 0, 'git config stays read-only under a writable profile') + assert.equal(readFileSync(path.join(cwd, '.git', 'config'), 'utf8'), '[core]\n') + + const nested = path.join(cwd, 'vendor', 'sub') + mkdirSync(path.join(nested, '.git', 'hooks'), { recursive: true }) + writeFileSync(path.join(nested, '.git', 'config'), '[core]\n') + const nestedHook = await runSandboxedCommand('printf pwned > vendor/sub/.git/hooks/evil', { cwd, profile: 'build-test' }) + assert.notEqual(nestedHook.code, 0, 'a nested repository\'s hooks stay read-only') + assert.equal(existsSync(path.join(nested, '.git', 'hooks', 'evil')), false) + const nestedConfig = await runSandboxedCommand('printf pwned >> vendor/sub/.git/config', { cwd, profile: 'build-test' }) + assert.notEqual(nestedConfig.code, 0, 'a nested repository\'s config stays read-only') + assert.equal(readFileSync(path.join(nested, '.git', 'config'), 'utf8'), '[core]\n') + + const newConfig = await runSandboxedCommand('printf pwned > .git/config.worktree', { cwd, profile: 'build-test' }) + assert.notEqual(newConfig.code, 0, 'a missing control file cannot be created') + assert.equal(existsSync(path.join(cwd, '.git', 'config.worktree')), true, 'the placeholder exists but stayed read-only') + assert.equal(readFileSync(path.join(cwd, '.git', 'config.worktree'), 'utf8'), '', 'the placeholder was not written') + + const inModules = path.join(cwd, 'node_modules', 'dep') + mkdirSync(path.join(inModules, '.git', 'hooks'), { recursive: true }) + writeFileSync(path.join(inModules, '.git', 'config'), '[core]\n') + const moduleHook = await runSandboxedCommand('printf pwned > node_modules/dep/.git/hooks/evil', { cwd, profile: 'build-test' }) + assert.notEqual(moduleHook.code, 0, 'a repository inside node_modules stays pinned') + + const innerWorktree = path.join(cwd, 'inner-worktree') + const innerGitdir = path.join(cwd, '.git', 'worktrees', 'inner') + mkdirSync(innerGitdir, { recursive: true }) + mkdirSync(innerWorktree, { recursive: true }) + writeFileSync(path.join(innerWorktree, '.git'), 'gitdir: ../.git/worktrees/inner\n') + const repoint = await runSandboxedCommand('printf "gitdir: /tmp/planted\n" > inner-worktree/.git', { cwd, profile: 'build-test' }) + assert.notEqual(repoint.code, 0, 'the worktree pointer stays read-only') + assert.match(readFileSync(path.join(innerWorktree, '.git'), 'utf8'), /^gitdir: \.\.\/\.git\/worktrees\/inner/, 'the pointer was not rewritten') + + const unreadable = path.join(cwd, 'unreadable-dir') + mkdirSync(unreadable) + chmodSync(unreadable, 0o000) + try { + const refusedWalk = await runSandboxedCommand('printf should-not-run', { cwd, profile: 'build-test' }) + assert.equal(refusedWalk.code, 126, 'an uninspectable directory refuses the command') + assert.match(refusedWalk.stderr, /cannot inspect .*unreadable-dir/) + } finally { + chmodSync(unreadable, 0o700) + rmSync(unreadable, { recursive: true, force: true }) + } + + const sharedWorktree = path.join(cwd, 'shared-worktree') + const sharedGitdir = path.join(cwd, '.git', 'worktrees', 'shared') + const outsideShared = path.join(root, 'elsewhere-shared', '.git') + mkdirSync(path.join(outsideShared, 'hooks'), { recursive: true }) + mkdirSync(sharedGitdir, { recursive: true }) + mkdirSync(sharedWorktree, { recursive: true }) + writeFileSync(path.join(sharedWorktree, '.git'), 'gitdir: ../.git/worktrees/shared\n') + writeFileSync(path.join(sharedGitdir, 'commondir'), `${path.relative(sharedGitdir, outsideShared)}\n`) + const refusedShared = await runSandboxedCommand('printf should-not-run', { cwd, profile: 'build-test' }) + assert.equal(refusedShared.code, 126, 'a worktree with an outside shared directory is refused') + assert.match(refusedShared.stderr, /shared git directory is outside the workspace/) + rmSync(sharedWorktree, { recursive: true, force: true }) + rmSync(path.join(cwd, '.git', 'worktrees', 'shared'), { recursive: true, force: true }) + rmSync(path.join(root, 'elsewhere-shared'), { recursive: true, force: true }) + + const outsideWorktree = path.join(root, 'outside-worktree') + mkdirSync(path.join(root, 'elsewhere', '.git', 'worktrees', 'outside'), { recursive: true }) + mkdirSync(outsideWorktree) + writeFileSync(path.join(outsideWorktree, '.git'), 'gitdir: ../elsewhere/.git/worktrees/outside\n') + const refusedWorktree = await runSandboxedCommand('printf should-not-run', { cwd: outsideWorktree, profile: 'build-test' }) + assert.equal(refusedWorktree.code, 126, 'a worktree outside the workspace is refused') + assert.equal(refusedWorktree.sandboxed, false) + assert.match(refusedWorktree.stderr, /outside the workspace/) + + const denied = await runSandboxedCommand(`timeout 3 bash -c 'exec 3<>/dev/tcp/127.0.0.1/${port}'`, { cwd, profile: 'build-test' }) + assert.notEqual(denied.code, 0, 'build-test cannot reach a loopback listener') + const allowed = await runSandboxedCommand(`timeout 3 bash -c 'exec 3<>/dev/tcp/127.0.0.1/${port}'`, { cwd, profile: 'network-fetch' }) + assert.equal(allowed.code, 0, `network-fetch reaches the same listener: ${allowed.stderr}`) + + const controller = new AbortController() + const started = Date.now() + const pending = runSandboxedCommand('sleep 30', { cwd, profile: 'build-test', signal: controller.signal }) + setTimeout(() => controller.abort(), 300) + const cancelled = await pending + assert.notEqual(cancelled.code, 0, 'cancelled command did not report success') + assert.ok(Date.now() - started < 10_000, 'cancellation stops the sandboxed command promptly') + + console.log('CONFORMANCE: passed (filesystem, git controls, placeholders, nested repositories, worktree pinning and refusal, shared-directory refusal, uninspectable-path refusal, network and cancellation enforced)') + } finally { + server.close() + rmSync(root, { recursive: true, force: true }) + } +} diff --git a/app/electron/agent/linux-sandbox.test.ts b/app/electron/agent/linux-sandbox.test.ts new file mode 100644 index 00000000000..75ffebbaf35 --- /dev/null +++ b/app/electron/agent/linux-sandbox.test.ts @@ -0,0 +1,168 @@ +import assert from 'node:assert/strict' +import { chmodSync, mkdtempSync, mkdirSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import path from 'node:path' +import { canUseLinuxSandbox, linuxSandboxArgv, linuxSandboxBinary, planLinuxMounts } from './linux-sandbox' +import { runSandboxedCommand } from './sandbox' + +let passed = 0 +const ok = (name: string) => { passed++; console.log(` ✓ ${name}`) } + +const root = mkdtempSync(path.join(realpathSync(tmpdir()), 'vontra-linux-sandbox-')) +try { + const cwd = path.join(root, 'ws') + mkdirSync(path.join(cwd, '.git', 'hooks'), { recursive: true }) + mkdirSync(path.join(cwd, '.git', 'info'), { recursive: true }) + writeFileSync(path.join(cwd, '.git', 'config'), '[core]\n') + + const buildTest = linuxSandboxArgv(cwd, { allowCwdWrite: true, allowNetwork: false }) + assert.ok(buildTest.includes('--unshare-all'), 'namespaces unshared') + assert.ok(!buildTest.includes('--share-net'), 'network stays unshared') + assert.ok(buildTest.includes('--die-with-parent')) + const bind = (argv: string[], flag: string, target: string) => + argv.some((arg, i) => arg === flag && argv[i + 2] === target) + assert.ok(bind(buildTest, '--bind', cwd), 'cwd bound writable') + assert.ok(bind(buildTest, '--ro-bind', path.join(cwd, '.git', 'config')), 'git config pinned read-only') + assert.ok(bind(buildTest, '--ro-bind', path.join(cwd, '.git', 'hooks')), 'git hooks pinned read-only') + assert.ok(bind(buildTest, '--bind', path.join(cwd, '.git')), 'git dir pinned against rename') + assert.equal(buildTest.at(-1), '--', 'argv ends before the command') + + const nested = path.join(cwd, 'vendor', 'sub') + mkdirSync(path.join(nested, '.git', 'hooks'), { recursive: true }) + writeFileSync(path.join(nested, '.git', 'config'), '[core]\n') + const nestedArgv = linuxSandboxArgv(cwd, { allowCwdWrite: true, allowNetwork: false }) + assert.ok(bind(nestedArgv, '--bind', path.join(nested, '.git')), 'nested .git pinned against rename') + assert.ok(bind(nestedArgv, '--ro-bind', path.join(nested, '.git', 'config')), 'nested git config read-only') + assert.ok(bind(nestedArgv, '--ro-bind', path.join(nested, '.git', 'hooks')), 'nested git hooks read-only') + ok('nested repositories are pinned like the workspace root') + + process.env.TENSORFOLD_LINUX_SANDBOX = '1' + + const inModules = path.join(cwd, 'node_modules', 'dep') + mkdirSync(path.join(inModules, '.git', 'hooks'), { recursive: true }) + writeFileSync(path.join(inModules, '.git', 'config'), '[core]\n') + const deep = path.join(cwd, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'deep-repo') + mkdirSync(path.join(deep, '.git', 'hooks'), { recursive: true }) + writeFileSync(path.join(deep, '.git', 'config'), '[core]\n') + const walked = linuxSandboxArgv(cwd, { allowCwdWrite: true, allowNetwork: false }) + assert.ok(bind(walked, '--bind', path.join(inModules, '.git')), 'a repository inside node_modules is pinned') + assert.ok(bind(walked, '--bind', path.join(deep, '.git')), 'a deeply nested repository is pinned') + ok('dependency folders and deep repositories are pinned, not skipped') + + let chain = path.join(cwd, 'too-deep') + for (let i = 0; i < 34; i++) chain = path.join(chain, `level-${i}`) + mkdirSync(chain, { recursive: true }) + assert.throws(() => linuxSandboxArgv(cwd, { allowCwdWrite: true, allowNetwork: false }), /will not walk below 32 directory levels/) + rmSync(path.join(cwd, 'too-deep'), { recursive: true, force: true }) + ok('a workspace deeper than the walk bound is refused') + + const innerWorktree = path.join(cwd, 'inner-worktree') + const innerGitdir = path.join(cwd, '.git', 'worktrees', 'inner') + mkdirSync(innerGitdir, { recursive: true }) + mkdirSync(innerWorktree, { recursive: true }) + writeFileSync(path.join(innerWorktree, '.git'), 'gitdir: ../.git/worktrees/inner\n') + const worktreeArgv = linuxSandboxArgv(cwd, { allowCwdWrite: true, allowNetwork: false }) + assert.ok(bind(worktreeArgv, '--ro-bind', path.join(innerWorktree, '.git')), 'the worktree pointer is read-only') + assert.ok(bind(worktreeArgv, '--bind', innerGitdir), 'the worktree gitdir stays writable for refs and objects') + ok('a nested worktree is pinned through its gitdir and its pointer is frozen') + + const unreadable = path.join(cwd, 'unreadable-dir') + mkdirSync(unreadable) + chmodSync(unreadable, 0o000) + assert.throws(() => linuxSandboxArgv(cwd, { allowCwdWrite: true, allowNetwork: false }), /cannot inspect .*unreadable-dir/) + chmodSync(unreadable, 0o700) + rmSync(unreadable, { recursive: true, force: true }) + ok('a directory the walk cannot inspect is refused') + + const sharedWorktree = path.join(cwd, 'shared-worktree') + const sharedGitdir = path.join(cwd, '.git', 'worktrees', 'shared') + const outsideShared = path.join(root, 'elsewhere-shared', '.git') + mkdirSync(path.join(outsideShared, 'hooks'), { recursive: true }) + mkdirSync(sharedGitdir, { recursive: true }) + mkdirSync(sharedWorktree, { recursive: true }) + writeFileSync(path.join(sharedWorktree, '.git'), 'gitdir: ../.git/worktrees/shared\n') + writeFileSync(path.join(sharedGitdir, 'commondir'), `${path.relative(sharedGitdir, outsideShared)}\n`) + assert.throws(() => linuxSandboxArgv(cwd, { allowCwdWrite: true, allowNetwork: false }), /shared git directory is outside the workspace/) + rmSync(path.join(root, 'elsewhere-shared'), { recursive: true, force: true }) + rmSync(sharedWorktree, { recursive: true, force: true }) + rmSync(path.join(cwd, '.git', 'worktrees', 'shared'), { recursive: true, force: true }) + ok('a worktree whose shared directory resolves outside the workspace is refused') + + const outsideWorktree = path.join(root, 'outside-worktree') + mkdirSync(path.join(root, 'elsewhere', '.git', 'worktrees', 'outside'), { recursive: true }) + mkdirSync(outsideWorktree) + writeFileSync(path.join(outsideWorktree, '.git'), 'gitdir: ../elsewhere/.git/worktrees/outside\n') + assert.throws(() => linuxSandboxArgv(outsideWorktree, { allowCwdWrite: true, allowNetwork: false }), /outside the workspace/) + if (canUseLinuxSandbox()) { + const refused = await runSandboxedCommand('printf should-not-run', { cwd: outsideWorktree }) + assert.equal(refused.code, 126) + assert.equal(refused.sandboxed, false) + assert.match(refused.stderr, /outside the workspace/) + ok('a worktree pointing outside the workspace is refused before the command runs') + } else { + console.log(' (worktree refusal runtime check skipped: bubblewrap unavailable)') + } + + const plain = path.join(root, 'plain-workspace') + mkdirSync(plain) + assert.throws(() => linuxSandboxArgv(plain, { allowCwdWrite: true, allowNetwork: false }), /needs a git workspace/) + if (canUseLinuxSandbox()) { + const plainRun = await runSandboxedCommand('printf should-not-run', { cwd: plain }) + assert.equal(plainRun.code, 126) + assert.match(plainRun.stderr, /needs a git workspace/) + ok('a workspace without a repository keeps commands refused') + } else { + console.log(' (non-repository refusal runtime check skipped: bubblewrap unavailable)') + } + + const readOnly = linuxSandboxArgv(cwd, { allowCwdWrite: false, allowNetwork: false }) + assert.ok(bind(readOnly, '--ro-bind', cwd), 'cwd bound read-only') + assert.ok(!bind(readOnly, '--bind', cwd), 'cwd not writable') + assert.ok(!readOnly.some((arg, i) => arg === '--ro-bind' && readOnly[i + 2] === path.join(cwd, '.git')), 'no git pinning without cwd writes') + const network = linuxSandboxArgv(cwd, { allowCwdWrite: false, allowNetwork: true }) + assert.ok(network.includes('--share-net'), 'network-fetch shares the network namespace') + ok('draft profile contains requested mount and network arguments (not confinement proof)') + + const tmpCwd = path.join(realpathSync(tmpdir()), 'vontra-tmp-workspace') + mkdirSync(tmpCwd, { recursive: true }) + const tmpMounts = planLinuxMounts(tmpCwd, { allowCwdWrite: false, allowNetwork: false }) + assert.deepEqual(tmpMounts.filter((mount) => mount.path === tmpCwd).map((mount) => mount.mode), ['ro'], 'read-only workspace stays read-only') + const tmpIndex = tmpMounts.findIndex((mount) => mount.path === realpathSync(tmpdir())) + const cwdIndex = tmpMounts.findIndex((mount) => mount.path === tmpCwd) + assert.ok(tmpIndex >= 0 && cwdIndex > tmpIndex, 'the read-only workspace mount follows its writable temporary parent') + assert.equal(tmpMounts[cwdIndex].mode, 'ro') + const writeMounts = planLinuxMounts(tmpCwd, { allowCwdWrite: true, allowNetwork: false }) + assert.equal(writeMounts.find((mount) => mount.path === tmpCwd)?.mode, 'rw') + const ordered = planLinuxMounts(cwd, { allowCwdWrite: true, allowNetwork: false }) + for (let i = 1; i < ordered.length; i++) assert.ok(ordered[i - 1].path.length <= ordered[i].path.length, 'mounts are parent-first') + ok('mount plan keeps a read-only workspace decisive under a writable temporary parent') + + const real = path.join(root, 'real-usr-bin') + const link = path.join(root, 'bin') + mkdirSync(real) + symlinkSync(real, link) + const withLink = linuxSandboxArgv(cwd, { allowCwdWrite: false, allowNetwork: false, extraReadRoots: [link] }) + assert.ok(withLink.some((arg, i) => arg === '--symlink' && withLink[i + 1] === real && withLink[i + 2] === link), 'symlinked root gets a compat symlink') + assert.ok(bind(withLink, '--ro-bind', real), 'the resolved root is bound') + ok('symlinked read roots resolve and keep their original path visible') + + if (canUseLinuxSandbox()) { + const hello = await runSandboxedCommand('printf hello', { cwd }) + assert.equal(hello.stdout, 'hello') + assert.equal(hello.implementation, 'linux-bwrap') + const escape = await runSandboxedCommand('touch /usr/bin/vontra-escape-attempt', { cwd, profile: 'read-only' }) + assert.notEqual(escape.code, 0, 'writes outside the profile fail') + assert.equal(escape.sandboxed, true) + const planted = await runSandboxedCommand('printf pwned > .git/hooks/evil', { cwd, profile: 'build-test' }) + assert.notEqual(planted.code, 0, 'git hooks stay read-only under build-test') + const net = await runSandboxedCommand('curl -sI --max-time 3 https://example.com', { cwd, profile: 'build-test' }) + assert.notEqual(net.code, 0, 'build-test has no network') + ok('bwrap confinement: fs, git-control and network rules enforced') + } else { + console.log(' (draft Linux backend disabled pending qualification; confinement NOT verified)') + } +} finally { + rmSync(root, { recursive: true, force: true }) +} + +console.log(`\n${passed} passed`) diff --git a/app/electron/agent/linux-sandbox.ts b/app/electron/agent/linux-sandbox.ts new file mode 100644 index 00000000000..55d435b504b --- /dev/null +++ b/app/electron/agent/linux-sandbox.ts @@ -0,0 +1,288 @@ +import { spawnSync } from 'node:child_process' +import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, statSync, writeFileSync } from 'node:fs' +import type { Dirent } from 'node:fs' +import os from 'node:os' +import path from 'node:path' +import { commandShell } from './cli-path' + +// Linux command sandbox on bubblewrap: macOS sandbox-exec profiles, mirrored as bwrap argv only. + +export const LINUX_SANDBOX_IMPLEMENTATION = 'linux-bwrap' + +export function linuxSandboxBinary(): string | null { + for (const candidate of ['/usr/bin/bwrap', '/bin/bwrap']) if (existsSync(candidate)) return candidate + return null +} + +let linuxSandboxAvailable: boolean | undefined + +/** Probe the real production argv with a read-only fixture, so loader and mount rules are exercised. */ +export function probeLinuxSandbox(cwd: string, run = spawnSync): boolean { + const binary = linuxSandboxBinary() + if (!binary) return false + const probe = run(binary, [...linuxSandboxArgv(cwd, { allowCwdWrite: false, allowNetwork: false, production: false }), commandShell(), '-c', 'exit 0'], { + stdio: 'ignore', + timeout: 4_000, + }) + return probe.status === 0 +} + +export function canUseLinuxSandbox(): boolean { + // Opt-in only until conformance is qualified; never enabled by default on an unverified host. + const qualified = process.env.TENSORFOLD_LINUX_SANDBOX === '1' + if (!qualified || process.platform !== 'linux') return false + const binary = linuxSandboxBinary() + if (!binary) return false + if (linuxSandboxAvailable !== undefined) return linuxSandboxAvailable + linuxSandboxAvailable = probeLinuxSandbox(process.cwd()) + return linuxSandboxAvailable +} + +interface ResolvedRoot { + requested: string + resolved: string +} + +/** Existing roots, realpath'd (usrmerge collapses /bin into /usr/bin), parents before children. */ +function resolveRoots(requested: Array): ResolvedRoot[] { + const seen = new Set() + const out: ResolvedRoot[] = [] + for (const item of requested) { + if (!item) continue + let resolved: string + try { + resolved = realpathSync(path.resolve(item)) + } catch { continue } + if (seen.has(resolved)) continue + seen.add(resolved) + out.push({ requested: path.resolve(item), resolved }) + } + return out.sort((a, b) => a.resolved.length - b.resolved.length || a.resolved.localeCompare(b.resolved)) +} + +/** usrmerge compatibility links: /bin -> usr/bin etc. so absolute interpreter paths still resolve. */ +function compatSymlinks(roots: ResolvedRoot[]): string[] { + const args: string[] = [] + for (const root of roots) { + if (root.requested === root.resolved) continue + try { + if (!lstatSync(root.requested).isSymbolicLink()) continue + } catch { continue } + args.push('--symlink', root.resolved, root.requested) + } + return args +} + +/** A workspace the sandbox cannot protect: git metadata the profile would not mount. */ +export class LinuxSandboxError extends Error {} + +// Git control files stay read-only under a writable workspace; refs and objects stay writable. +const GIT_CONTROL_FILES = ['config', 'config.worktree'] +const GIT_CONTROL_DIRS = ['hooks', 'info'] +const NESTED_DEPTH_LIMIT = 32 +const NESTED_DIRECTORY_LIMIT = 50_000 + +const insideWorkspace = (cwd: string, target: string) => target === cwd || target.startsWith(`${cwd}${path.sep}`) + +/** Missing is safe to skip; any other inspection failure refuses, because it could hide a repository. */ +const isMissing = (error: unknown) => { + const code = (error as NodeJS.ErrnoException)?.code + return code === 'ENOENT' || code === 'ENOTDIR' +} + +function refuseInspection(target: string, error: unknown): never { + throw new LinuxSandboxError(`The sandbox cannot inspect ${target}: ${(error as Error)?.message ?? String(error)}`) +} + +function workspacePath(cwd: string, target: string): string | null { + let resolved: string + try { resolved = realpathSync(target) } catch (error) { if (isMissing(error)) return null; refuseInspection(target, error) } + if (!insideWorkspace(cwd, resolved)) throw new LinuxSandboxError(`The sandbox will not mount git metadata outside the workspace: ${target}`) + return resolved +} + +// Read-only placeholders prevent writable runs from creating absent Git control entries. +let fixtures: { file: string; dir: string } | null = null +function placeholderSources(cwd: string): { file: string; dir: string } { + if (fixtures) return fixtures + const root = path.join(os.homedir(), '.cache', 'tensorfold-linux-sandbox') + if (insideWorkspace(cwd, root)) throw new LinuxSandboxError(`The sandbox cannot keep placeholders outside a workspace rooted at ${cwd}.`) + mkdirSync(root, { recursive: true, mode: 0o700 }) + mkdirSync(path.join(root, 'empty-dir'), { recursive: true, mode: 0o700 }) + const emptyFile = path.join(root, 'empty-file') + if (!existsSync(emptyFile)) writeFileSync(emptyFile, '', { mode: 0o600 }) + fixtures = { file: emptyFile, dir: path.join(root, 'empty-dir') } + return fixtures +} + +function gitdirPointer(pointer: string): string | null { + try { + const match = /^gitdir:[ \t]*(.+)$/m.exec(readFileSync(pointer, 'utf8')) + return match ? match[1].trim() : null + } catch { return null } +} + +function pinControlEntries(cwd: string, gitDir: string, args: string[]): void { + const sources = placeholderSources(cwd) + for (const [entry, isDir] of [...GIT_CONTROL_FILES.map((name) => [name, false] as const), ...GIT_CONTROL_DIRS.map((name) => [name, true] as const)]) { + const target = path.join(gitDir, entry) + const resolved = workspacePath(cwd, target) + args.push('--ro-bind', resolved ?? (isDir ? sources.dir : sources.file), target) + } +} + +function pinGitDirectory(cwd: string, gitDir: string, args: string[]): void { + const resolved = workspacePath(cwd, gitDir) + if (!resolved) throw new LinuxSandboxError(`The sandbox cannot resolve the git directory ${gitDir}.`) + args.push('--bind', resolved, gitDir) + pinControlEntries(cwd, gitDir, args) +} + +function pinWorktree(cwd: string, pointer: string, args: string[]): void { + const pointerPath = workspacePath(cwd, pointer) + if (!pointerPath) throw new LinuxSandboxError(`The sandbox cannot resolve the worktree pointer at ${pointer}.`) + const target = gitdirPointer(pointer) + if (!target) throw new LinuxSandboxError(`The sandbox cannot read the worktree pointer at ${pointer}.`) + let gitdir: string + try { gitdir = realpathSync(path.resolve(path.dirname(pointer), target)) } catch { throw new LinuxSandboxError(`The sandbox cannot resolve the worktree gitdir in ${pointer}.`) } + if (!insideWorkspace(cwd, gitdir)) throw new LinuxSandboxError(`The sandbox refuses a worktree whose gitdir is outside the workspace: ${gitdir}`) + pinGitDirectory(cwd, gitdir, args) + // Freezing the pointer stops a run from repointing the workspace at metadata it built itself. + args.push('--ro-bind', pointerPath, pointer) + const common = workspacePath(cwd, path.join(gitdir, 'commondir')) + if (!common) return + let commonDir: string + try { commonDir = realpathSync(path.resolve(path.dirname(common), readFileSync(common, 'utf8').trim())) } catch { throw new LinuxSandboxError(`The sandbox cannot resolve the shared git directory in ${common}.`) } + if (!insideWorkspace(cwd, commonDir)) throw new LinuxSandboxError(`The sandbox refuses a worktree whose shared git directory is outside the workspace: ${commonDir}`) + pinControlEntries(cwd, commonDir, args) +} + +/** Every .git under the workspace. Bounds refuse: silently pinning a subset would be a false promise. */ +function nestedGitPaths(cwd: string): string[] { + const found: string[] = [] + const seen = new Set([realpathSync(cwd)]) + let directories = 0 + const walk = (dir: string, depth: number): void => { + if (depth > NESTED_DEPTH_LIMIT) throw new LinuxSandboxError(`The sandbox will not walk below ${NESTED_DEPTH_LIMIT} directory levels to find nested repositories.`) + let entries: Dirent[] + try { entries = readdirSync(dir, { withFileTypes: true }) } catch (error) { + if (isMissing(error)) return + refuseInspection(dir, error) + } + for (const entry of entries) { + if (entry.name === '.git') continue + const candidate = path.join(dir, entry.name) + let child: string | null = null + if (entry.isDirectory()) child = candidate + else if (entry.isSymbolicLink()) { + let resolved: string + let kind: 'file' | 'dir' + try { + resolved = realpathSync(candidate) + kind = statSync(resolved).isDirectory() ? 'dir' : 'file' + } catch (error) { + if (isMissing(error)) continue + refuseInspection(candidate, error) + } + if (kind === 'dir' && insideWorkspace(cwd, resolved)) child = resolved + } + if (!child) continue + if (++directories > NESTED_DIRECTORY_LIMIT) throw new LinuxSandboxError(`The sandbox will not walk more than ${NESTED_DIRECTORY_LIMIT} workspace directories to find nested repositories.`) + const real = realpathSync(child) + if (seen.has(real)) continue + seen.add(real) + const nested = path.join(real, '.git') + try { lstatSync(nested); found.push(nested) } catch (error) { if (!isMissing(error)) refuseInspection(nested, error) } + walk(real, depth + 1) + } + } + walk(cwd, 0) + return found +} + +export function gitMetadataArgs(cwd: string): string[] { + const args: string[] = [] + const rootGit = path.join(cwd, '.git') + let rootKind: 'dir' | 'file' | null = null + try { rootKind = lstatSync(rootGit).isDirectory() ? 'dir' : 'file' } catch (error) { + if (!isMissing(error)) refuseInspection(rootGit, error) + rootKind = null + } + // A workspace without a repository keeps commands refused: bwrap cannot deny creating .git by name. + if (!rootKind) throw new LinuxSandboxError('The sandbox needs a git workspace; commands stay refused here.') + if (rootKind === 'file') pinWorktree(cwd, rootGit, args) + else pinGitDirectory(cwd, rootGit, args) + for (const nested of nestedGitPaths(cwd)) { + let kind: 'dir' | 'file' + try { kind = lstatSync(nested).isDirectory() ? 'dir' : 'file' } catch (error) { + if (isMissing(error)) continue + refuseInspection(nested, error) + } + if (kind === 'file') pinWorktree(cwd, nested, args) + else pinGitDirectory(cwd, nested, args) + } + return args +} + +export interface LinuxSandboxProfileOptions { + allowCwdWrite: boolean + allowNetwork: boolean + extraReadRoots?: Array + /** False for the capability probe, which must not inspect or depend on the caller's workspace. */ + production?: boolean +} + +/** Every requested read root, kept with its unresolved name so usrmerge links stay visible. */ +export function linuxReadRoots(cwd: string, options: LinuxSandboxProfileOptions): ResolvedRoot[] { + return resolveRoots([ + cwd, + '/bin', + '/sbin', + '/lib', + '/lib64', + '/usr/bin', + '/usr/sbin', + '/usr/lib', + '/usr/libexec', + '/usr/share', + '/usr/local', + '/etc', + '/opt', + os.tmpdir(), + process.env.TMPDIR, + ...(options.extraReadRoots ?? []), + ]) +} + +/** One final decision per resolved path; later mounts win, so children must follow their parents. */ +export function planLinuxMounts(cwd: string, options: LinuxSandboxProfileOptions): Array<{ mode: 'ro' | 'rw'; path: string }> { + const readRoots = linuxReadRoots(cwd, options) + const writeRoots = resolveRoots([ + ...(options.allowCwdWrite ? [cwd] : []), + os.tmpdir(), + process.env.TMPDIR, + ]) + const writable = new Set(writeRoots.map((root) => root.resolved)) + const byPath = new Map() + for (const root of readRoots) byPath.set(root.resolved, writable.has(root.resolved) ? 'rw' : 'ro') + for (const root of writeRoots) byPath.set(root.resolved, 'rw') + // A read-only workspace always wins, even when it sits inside a writable temporary parent. + const canonicalCwd = (() => { try { return realpathSync(cwd) } catch { return path.resolve(cwd) } })() + if (!options.allowCwdWrite) byPath.set(canonicalCwd, 'ro') + return [...byPath.entries()] + .map(([mountPath, mode]) => ({ mode, path: mountPath })) + .sort((a, b) => a.path.length - b.path.length || a.path.localeCompare(b.path)) +} + +/** bwrap argv (without the binary) implementing the same contract as macSandboxProfile. */ +export function linuxSandboxArgv(cwd: string, options: LinuxSandboxProfileOptions): string[] { + const mounts = planLinuxMounts(cwd, options) + const args: string[] = ['--unshare-all', '--die-with-parent'] + if (options.allowNetwork) args.push('--share-net') + args.push('--proc', '/proc', '--dev', '/dev') + for (const mount of mounts) args.push(mount.mode === 'rw' ? '--bind' : '--ro-bind', mount.path, mount.path) + if (options.allowCwdWrite) args.push(...gitMetadataArgs(realpathSync(cwd))) + args.push(...compatSymlinks(linuxReadRoots(cwd, options))) + args.push('--chdir', cwd, '--') + return args +} diff --git a/app/electron/agent/sandbox-workspace.ts b/app/electron/agent/sandbox-workspace.ts new file mode 100644 index 00000000000..a66ab77f3e2 --- /dev/null +++ b/app/electron/agent/sandbox-workspace.ts @@ -0,0 +1,74 @@ +import { spawnSync } from 'node:child_process' +import { createHash } from 'node:crypto' +import { lstatSync, readlinkSync, readFileSync, realpathSync } from 'node:fs' +import path from 'node:path' +import { hostGitEnv } from './host-git-env' + +export interface SandboxWorkspaceSnapshot { + root: string + files: Array<{ path: string; fingerprint: string }> +} + +export const MAX_HASH_BYTES = 10 * 1024 * 1024 + +function gitOutput(args: string[], cwd: string): Buffer | null { + const result = spawnSync('git', args, { + cwd, + encoding: 'buffer', + maxBuffer: 32 * 1024 * 1024, + timeout: 20_000, + env: hostGitEnv({ ...process.env, GIT_OPTIONAL_LOCKS: '0' }), + }) + return result.status === 0 && Buffer.isBuffer(result.stdout) ? result.stdout : null +} + +export function captureWorkspaceSnapshot(cwd: string): SandboxWorkspaceSnapshot | null { + const rootRaw = gitOutput(['rev-parse', '--show-toplevel'], cwd) + if (!rootRaw) return null + const rootText = rootRaw.toString('utf8').trim() + if (!rootText) return null + let root: string + try { root = realpathSync(rootText) } catch { return null } + const listed = gitOutput(['ls-files', '-c', '-o', '--exclude-standard', '-z'], root) + if (!listed) return null + const files: Array<{ path: string; fingerprint: string }> = [] + for (const rel of listed.toString('utf8').split('\0').filter(Boolean)) { + if (rel.startsWith('/') || rel.split('/').includes('..')) continue + const full = path.join(root, ...rel.split('/')) + let stat + try { stat = lstatSync(full) } catch { continue } + let fingerprint: string + if (stat.isSymbolicLink()) { + try { fingerprint = `link:${workspaceContentFingerprint(readlinkSync(full))}` } catch { continue } + } else if (stat.isFile()) { + try { + fingerprint = stat.size <= MAX_HASH_BYTES + ? `file:${workspaceContentFingerprint(readFileSync(full))}` + : `large:${stat.size}:${stat.mtimeMs}:${stat.ctimeMs}` + } catch { continue } + } else { + continue + } + files.push({ path: rel.replace(/\\/g, '/'), fingerprint }) + } + return { root, files: files.sort((a, b) => a.path.localeCompare(b.path)) } +} + +function workspaceContentFingerprint(content: string | Buffer): string { + return createHash('sha256').update(content).digest('hex') +} + +export function changedWorkspacePaths(cwd: string, before: SandboxWorkspaceSnapshot | undefined): string[] { + if (!before) return [] + const after = captureWorkspaceSnapshot(before.root) + if (!after || after.root !== before.root) return [] + const previous = new Map(before.files.map((file) => [file.path, file.fingerprint])) + const current = new Map(after.files.map((file) => [file.path, file.fingerprint])) + const changed = new Set() + for (const [file, fingerprint] of current) if (previous.get(file) !== fingerprint) changed.add(file) + for (const file of previous.keys()) if (!current.has(file)) changed.add(file) + return [...changed].sort().map((repoPath) => { + const relative = path.relative(cwd, path.join(before.root, ...repoPath.split('/'))) + return relative.split(path.sep).join('/') || '.' + }) +} diff --git a/app/electron/agent/sandbox.ts b/app/electron/agent/sandbox.ts index 12a5d366f0a..e5e37aa379b 100644 --- a/app/electron/agent/sandbox.ts +++ b/app/electron/agent/sandbox.ts @@ -1,13 +1,16 @@ import { spawn, spawnSync } from 'node:child_process' import { createHash } from 'node:crypto' -import { copyFileSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readlinkSync, readdirSync, readFileSync, realpathSync, rmSync, statSync } from 'node:fs' +import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, rmSync, statSync } from 'node:fs' import os from 'node:os' import path from 'node:path' import { StringDecoder } from 'node:string_decoder' import { approvalPolicyScope, isReadOnlyShellCommand } from './approval-policy' import { commandShell, commandShellArgs } from './cli-path' +import { LinuxSandboxError, canUseLinuxSandbox, linuxSandboxArgv, linuxSandboxBinary } from './linux-sandbox' import { commandApprovalReason } from './command-policy' -import { hostGitEnv } from './host-git-env' +import { MAX_HASH_BYTES, captureWorkspaceSnapshot, changedWorkspacePaths } from './sandbox-workspace' +import type { SandboxWorkspaceSnapshot } from './sandbox-workspace' +export type { SandboxWorkspaceSnapshot } from './sandbox-workspace' import { redactCommandStreams } from './command-output-redaction' import { SECRET_MASK } from './security' import { redactSecretValues } from './secret-detection' @@ -48,18 +51,13 @@ export interface SandboxArtifactBaseline { workspaceSnapshot?: SandboxWorkspaceSnapshot } -export interface SandboxWorkspaceSnapshot { - root: string - files: Array<{ path: string; fingerprint: string }> -} - export interface SandboxArtifactBundle { schema: typeof SANDBOX_ARTIFACT_SCHEMA id: string command: string cwd: string profile: SandboxProfileId | 'unsandboxed' - implementation: 'macos-sandbox-exec' | 'unsandboxed' + implementation: 'macos-sandbox-exec' | 'linux-bwrap' | 'unsandboxed' inputSnapshot: SandboxFileArtifact[] outputFiles: SandboxFileArtifact[] screenshots: SandboxFileArtifact[] @@ -75,7 +73,7 @@ export interface SandboxedCommandResult { stderr: string sandboxed: boolean profile: SandboxProfileId | 'unsandboxed' - implementation: 'macos-sandbox-exec' | 'unsandboxed' + implementation: 'macos-sandbox-exec' | 'linux-bwrap' | 'unsandboxed' /** Number of value-level secrets removed from stdout/stderr before this result left the sandbox. */ redactionCount?: number artifacts?: SandboxArtifactBundle @@ -129,7 +127,6 @@ const PACKAGE_INSTALL_INPUT_PATHS = [ ] const ARTIFACT_SKIP_DIRS = new Set(['.git', 'node_modules']) const MAX_ARTIFACT_FILES = 120 -const MAX_HASH_BYTES = 10 * 1024 * 1024 const SCREENSHOT_RE = /\.(?:png|jpe?g|webp|gif)$/i export function commandNeedsNetwork(command: string): boolean { @@ -221,9 +218,7 @@ export async function runSandboxedCommand(command: string, options: SandboxedCom const profile = options.profile ?? sandboxProfileForCommand(command) const allowNetwork = sandboxProfileAllowsNetwork(profile, options.allowNetwork) const cwd = prepareSandboxExecutionCwd(hostCwd, profile) - // package-install runs in a throwaway temp dir; remove it once artifacts are captured so we - // don't orphan a (potentially node_modules-sized) directory per install. The host cwd is never - // deleted — only a sandbox-owned scratch dir that differs from it. + // Only sandbox-owned package-install scratch is removed after artifact capture. const ephemeralCwd = cwd === hostCwd ? null : cwd try { const baseline = captureSandboxArtifactBaseline(cwd, Date.now(), SANDBOX_PROFILES[profile].allowCwdWrite) @@ -239,6 +234,34 @@ export async function runSandboxedCommand(command: string, options: SandboxedCom }) return attachSandboxArtifacts(command, cwd, result, baseline) } + if (canUseLinuxSandbox()) { + const definition = SANDBOX_PROFILES[profile] + let bwrapArgv: string[] + try { + bwrapArgv = linuxSandboxArgv(cwd, { allowCwdWrite: definition.allowCwdWrite, allowNetwork }) + } catch (error) { + // A workspace whose git metadata the profile cannot protect keeps commands refused. + if (!(error instanceof LinuxSandboxError)) throw error + return attachSandboxArtifacts(command, cwd, { + code: 126, + stdout: '', + stderr: `${error.message}\n`, + sandboxed: false, + profile, + implementation: 'unsandboxed', + }, baseline) + } + const result = await runShell([linuxSandboxBinary()!, ...bwrapArgv, commandShell(), ...commandShellArgs(), command], { + cwd, + timeoutMs: options.timeoutMs, + maxBuffer: options.maxBuffer, + sandboxed: true, + profile, + implementation: 'linux-bwrap', + signal: options.signal, + }) + return attachSandboxArtifacts(command, cwd, result, baseline) + } if (!allowUnsandboxedCommands()) { return attachSandboxArtifacts(command, cwd, { code: 126, @@ -330,8 +353,7 @@ function runShell(argv: string[], opts: { cwd: string; timeoutMs?: number; maxBu } opts.signal?.addEventListener('abort', onAbort, { once: true }) if (opts.signal?.aborted) onAbort() - // Per-stream decoders buffer partial multi-byte sequences across chunk boundaries, so emoji/CJK - // split across two 'data' events don't decode to U+FFFD replacement chars. + // Streaming decoders preserve UTF-8 characters split across data events. const outDecoder = new StringDecoder('utf8') const errDecoder = new StringDecoder('utf8') const append = (kind: 'stdout' | 'stderr', chunk: Buffer) => { @@ -340,12 +362,7 @@ function runShell(argv: string[], opts: { cwd: string; timeoutMs?: number; maxBu else stderr = (stderr + text).slice(0, maxBuffer) if (stdout.length + stderr.length >= maxBuffer && !overflowed) { overflowed = true - // Cancel the unrelated timeout timer so it doesn't double-fire later, then run the same - // SIGTERM-now/SIGKILL-after-grace-period escalation the timeout path uses, so a child that - // traps/ignores SIGTERM doesn't linger until the original (possibly much longer) timeout. - // Note: `child.killed` reflects whether a signal was *sent*, not whether the process has - // actually exited yet — checking `exitCode`/`signalCode` (only set once 'exit' fires) is - // what correctly detects a child that is still alive after ignoring SIGTERM. + // A sent signal is not an exit; escalate after the grace period while the child is alive. clearTimeout(timer) terminate() } @@ -387,68 +404,6 @@ function attachSandboxArtifacts(command: string, cwd: string, result: SandboxedC } } -function gitOutput(args: string[], cwd: string): Buffer | null { - const result = spawnSync('git', args, { - cwd, - encoding: 'buffer', - maxBuffer: 32 * 1024 * 1024, - timeout: 20_000, - env: hostGitEnv({ ...process.env, GIT_OPTIONAL_LOCKS: '0' }), - }) - return result.status === 0 && Buffer.isBuffer(result.stdout) ? result.stdout : null -} - -function captureWorkspaceSnapshot(cwd: string): SandboxWorkspaceSnapshot | null { - const rootRaw = gitOutput(['rev-parse', '--show-toplevel'], cwd) - if (!rootRaw) return null - const rootText = rootRaw.toString('utf8').trim() - if (!rootText) return null - let root: string - try { root = realpathSync(rootText) } catch { return null } - const listed = gitOutput(['ls-files', '-c', '-o', '--exclude-standard', '-z'], root) - if (!listed) return null - const files: Array<{ path: string; fingerprint: string }> = [] - for (const rel of listed.toString('utf8').split('\0').filter(Boolean)) { - if (rel.startsWith('/') || rel.split('/').includes('..')) continue - const full = path.join(root, ...rel.split('/')) - let stat - try { stat = lstatSync(full) } catch { continue } - let fingerprint: string - if (stat.isSymbolicLink()) { - try { fingerprint = `link:${workspaceContentFingerprint(readlinkSync(full))}` } catch { continue } - } else if (stat.isFile()) { - try { - fingerprint = stat.size <= MAX_HASH_BYTES - ? `file:${workspaceContentFingerprint(readFileSync(full))}` - : `large:${stat.size}:${stat.mtimeMs}:${stat.ctimeMs}` - } catch { continue } - } else { - continue - } - files.push({ path: rel.replace(/\\/g, '/'), fingerprint }) - } - return { root, files: files.sort((a, b) => a.path.localeCompare(b.path)) } -} - -function workspaceContentFingerprint(content: string | Buffer): string { - return createHash('sha256').update(content).digest('hex') -} - -function changedWorkspacePaths(cwd: string, before: SandboxWorkspaceSnapshot | undefined): string[] { - if (!before) return [] - const after = captureWorkspaceSnapshot(before.root) - if (!after || after.root !== before.root) return [] - const previous = new Map(before.files.map((file) => [file.path, file.fingerprint])) - const current = new Map(after.files.map((file) => [file.path, file.fingerprint])) - const changed = new Set() - for (const [file, fingerprint] of current) if (previous.get(file) !== fingerprint) changed.add(file) - for (const file of previous.keys()) if (!current.has(file)) changed.add(file) - return [...changed].sort().map((repoPath) => { - const relative = path.relative(cwd, path.join(before.root, ...repoPath.split('/'))) - return relative.split(path.sep).join('/') || '.' - }) -} - function collectArtifactFiles(cwd: string, roots: string[]): SandboxFileArtifact[] { const out: SandboxFileArtifact[] = [] for (const root of roots) { diff --git a/app/electron/main/host/security-controls.ts b/app/electron/main/host/security-controls.ts index 005686055aa..1aceb8ee566 100644 --- a/app/electron/main/host/security-controls.ts +++ b/app/electron/main/host/security-controls.ts @@ -1,3 +1,4 @@ +import { canUseLinuxSandbox } from '../../agent/linux-sandbox' import { canUseMacSandbox } from '../../agent/sandbox' import type { SecurityControlSnapshot } from '../../agent/types' import { store } from '../state' @@ -33,7 +34,7 @@ export function securityControlSnapshot(): SecurityControlSnapshot { return { actor: auditActor(), role: currentSecurityRole(), - commandSandboxAvailable: canUseMacSandbox(), + commandSandboxAvailable: canUseMacSandbox() || canUseLinuxSandbox(), mcpSandboxAvailable: canUseMacSandbox(), signedUpdatesRequired: signedUpdatesRequired(), updatePublicKeyConfigured: !!updateSignaturePublicKey(), @@ -48,8 +49,7 @@ export function securityControlSnapshot(): SecurityControlSnapshot { quarantinedProtectedFiles: localSecrets.quarantinedProtectedFiles, quarantinedProtectedPaths: localSecrets.quarantinedProtectedPaths, quarantineBackupPaths: localSecrets.quarantineBackupPaths, - // There is no plaintext-store bypass. Keep the compatibility field honest - // even if a stale deployment still exports the former unused variable. + // Legacy environment values must not advertise a plaintext-store bypass. unencryptedLocalStoreAllowed: false, strictAuditEnabled: envEnabled('VONTRA_STRICT_AUDIT'), auditHealthy: !getLastAuditError(), diff --git a/build.zig b/build.zig index 60ec0cf950f..4872d3f1a1c 100644 --- a/build.zig +++ b/build.zig @@ -293,8 +293,8 @@ pub fn build(b: *std.Build) void { @import("zig/build/test_allocator.zig").wire(b); } -/// The native Metal server build is owned by the shared Metal target module. -const nativeServer = metal_build.nativeServer; +/// The native Metal server build is owned by its own module, like cuda.zig's. +const nativeServer = @import("zig/build/metal_server.zig").nativeServer; /// macOS: the metallib, the Metal runtime's test programs and the engine over Metal. const metalTargets = metal_build.metalTargets; diff --git a/docs/api.md b/docs/api.md index f4d489be330..308e95118c3 100644 --- a/docs/api.md +++ b/docs/api.md @@ -46,11 +46,11 @@ different scopes, or scopes a key the flags or environment already give, is refu | Scope | Routes | | --- | --- | | `inference` | POST `/v1/chat/completions`, `/v1/completions`, `/v1/responses`, `/v1/messages`, `/v1/messages/count_tokens`, `/v1/tokenize`, `/v1/detokenize`, `/v1/apply-template`, `/v1/audio/speech`, `/v1/images/generations`, `/v1/embeddings`, `/v1/decisions`, `/v1/systemone`, `/score`, `/v1/score`, `/v2/rerank`, `/v1/rerank` (also by PUT), `/v1/ocr`, and the same paths without `/v1` where the server has them; GET `/v1/models`, `/models`, `/v1/models/{id}`, `/models/{id}`, `/v1/voices`; a WebSocket upgrade on GET `/v1/responses` or `/responses` | -| `read` | GET `/metrics`, `/v1/metrics`, `/v1/load`, `/memory`, `/v1/memory`, `/stats`, `/dashboard`, `/v1/benchmark/manifest`, `/v1/models`, `/models`, `/v1/models/{id}`, `/models/{id}`, `/v1/voices` | +| `read` | GET `/metrics`, `/v1/metrics`, `/v1/load`, `/memory`, `/v1/memory`, `/stats`, `/dashboard`, `/v1/benchmark/manifest`, `/v1/execution/witness`, `/v1/models`, `/models`, `/v1/models/{id}`, `/models/{id}`, `/v1/voices` | A scoped key reaches nothing else: not the stored Responses (GET or DELETE `/v1/responses/ID`), Recall, Sliding Weights, -`/v1/imprint`, adding or deleting voices (`--manage-voices`), another method, or a suffix alias such as `/alt/completions` -that the server answers for a full key. The route +`/v1/imprint`, adding or deleting voices (`--manage-voices`), `/v1/prompt_cache/flush`, another method, or a suffix +alias such as `/alt/completions` that the server answers for a full key. The route is matched exactly after the query and trailing slashes are cut. A refused route answers 403 with the code `insufficient_scope` (Messages routes: an Anthropic `permission_error`) and closes the connection before the body is read or a parked model reloads. The public routes stay public. @@ -61,6 +61,9 @@ a Responses socket, a `previous_response_id` that the socket's own cache holds i it was accepted with if the file changes while it runs. Scopes are authorization only: every key shares one model, its prompt cache and the metrics. +A reply's binding carries the read-scoped execution witness, so `"execution_witness": true` needs `read` beside +`inference`; a key without `read` answers 403 `insufficient_scope` naming the field before the request is planned. + ## Browser request headers @@ -460,14 +463,16 @@ delete runs gets 503, an id that is not a number 400, and an id the graph does n | `chat_template_kwargs.enable_thinking` | Template thinking toggle; explicit off returns HTTP 400 when a thinking tokenizer has neither a template switch nor a closable generation prefix; omitted switches keep working. `chat_template_kwargs.thinking` (`true`/`false` or `{"type": "enabled"}`/`{"type": "disabled"}`, as DeepSeek-V4 clients send it) is read the same way when `enable_thinking` is absent; other values are ignored | Both | | `thinking` | Top-level toggle, the same forms as `chat_template_kwargs.thinking`; read only when the kwargs set neither toggle, so the kwargs win. Enabling it clears a `reasoning_effort` of `none`, so the template's default effort applies | Both | | `draft` | False selects the serial reference; CUDA rejects it if the engine has no serial switch | Both | -| `response_format`, `guided_json`, `guided_regex`, `guided_choice`, `guided_grammar`, `structured_outputs` | A JSON schema, any JSON object, a regex, a choice or an EBNF grammar the reply must match | Both | +| `response_format`, `guided_json`, `guided_regex`, `guided_choice`, `guided_grammar`, `structured_outputs` | A JSON schema, any JSON object, a regex, a choice or an EBNF grammar the reply must match; on the native server also `structural_tag`, JSON regions inside free text | Both | | `grammar_budget` | Boolean, default false. Under a grammar (the fields above, or a required tool call), never draw a token after which the reply could no longer complete within `max_tokens`; see [Structured output](#structured-output) | Native | | `ignore_eos` | Disable model end-of-sequence stopping; the reply limit still applies | Both | | `stop` | Stop at a string or any string in a list; omit the matched text from the response | Both | | `reasoning_effort` | `none`, `minimal`, `low`, `medium`, `high`, `xhigh` or `max` | Both | | `thinking_budget` | Token-count limit inside reasoning | Both | | `priority` | `background` yields to foreground requests | Both | +| `deadline_s` | Seconds, more than 0 and at most 1,000,000, on chat and legacy completions: at that time the server cancels the engine itself and the reply ends with `finish_reason: "deadline"`, keeping every token the engine gave, usage and token ids. A reply that ends first, or a [cancel](#cancel-a-request) that came first, keeps its own ending; without the field nothing changes | Native | | `return_token_ids` | The reply's token ids in the response's `tensorfold.token_ids`, the tokens its `token_sha256` hashes | Native | +| `execution_witness` | Boolean, default false. True binds the reply to the execution witness; see [Reply binding](#reply-binding). A server without `--execution-witness` answers 400, a key with `inference` but not `read` 403 | Both | `n` must be 1; multiple choices receive HTTP 400. @@ -669,6 +674,14 @@ asks for it and sends no `priority` of its own is treated as `priority: "backgro field always wins over the default. This lets one server answer to several ids at their usual priority while a background-only client (a batch extractor, say) gets one id that always yields, without sending the field itself. +A streamed reply whose client stops reading does not keep its lane decoding. On an engine on the shared lane host, once +1,024 of a stream's tokens are waiting in the server for its client, the stream sits out rounds; it runs again once the +client has taken all but 512 of them. Other streams keep their pace, and the text the client receives is the same, +byte for byte, as a fast client's. A stream that sits out 60 seconds while its client reads nothing is cancelled as a +disconnect is: the reply ends with `finish_reason: "cancelled"` and its lane goes to the next request. A client that +reads as the reply arrives never pauses, and whole (non-streamed) replies are not affected. Engines served outside the +shared lane host, such as Flash Next's one-reply-at-a-time host, do not pause. + The native CUDA build serves Nemotron, and its concurrent requests share each round. The rest of this paragraph describes the Python 0.6.6 engine's CUDA families. On CUDA, `--parallel auto` serves one request at a time. An explicit `--parallel N` above one shares rounds @@ -769,6 +782,23 @@ back to the host before each verify, the grammar cuts the ones it rejects and dr closing markup), and each row's logits are masked before its draw, so drafted, `"draft": false` and concurrent replies are the same. +The native server also takes `response_format: {"type": "structural_tag", "structures": [...], "triggers": [...]}` on +`/v1/chat/completions` and `/v1/completions`. The reply is free text, and each structure's `begin` string opens a region +that must be JSON matching its `schema` and close with its `end` string. Each structure is +`{"begin": "", "schema": {...}, "end": ""}`: `begin` and `end` are non-empty strings of at most 256 +bytes, and `schema` is a JSON schema object (or its JSON text, or `true`). `triggers` are the strings that open a +region: each must start at least one structure's `begin`, and every `begin` must start with exactly one of them. +Without `triggers`, each distinct `begin` that no shorter `begin` starts is a trigger. A trigger can't appear in the +free text except as the start of a region, so with `"triggers": ["<"]` every `<` opens a structure. Outside regions the +text is unconstrained; inside one, its JSON allows at most 32 blank characters between two tokens, as `json_schema` +does. A reply may hold any number of regions, including none, and can't end inside one. A request takes up to 64 +structures and 64 triggers, compiling to at most 512 KiB of grammar; a malformed list returns HTTP 400 before any stream +starts, naming the structure and field. xgrammar's own `{"type": "structural_tag", "format": {...}}` form is refused. +The server compiles the request onto the same grammar engine as the other formats (xgrammar's `triggered_tags`), so +the backends, drafting and thinking work as described above, and `grammar_budget` as described below. As with the +other formats, it takes the place of the strict-tool grammar under `tool_choice: "auto"` and is refused beside +`tool_choice: "required"` or a named function. Requests without it are unchanged. + On the native server, `/v1/chat/completions` and `/v1/responses` enforce `tool_choice: "required"` and a named function with the engine's token grammar. Chat uses `{"type":"function","function":{"name":"lookup"}}`; Responses uses `{"type":"function","name":"lookup"}`. Only offered tools are allowed; an unknown name or a required @@ -781,6 +811,10 @@ Qwen XML and JSON call templates keep their envelopes. Gemma 4 uses uses the canonical `{"name":"NAME","arguments":{...}}` form. The native grammar limits whitespace between calls; `parallel_tool_calls: false` allows exactly one. With thinking enabled, the constraint starts after the think-end token. A reply cut short by `max_tokens` can remain incomplete and ends as `length`. +With `--tool-think-close` (off by default), a required or named call on an engine that takes `thinking_budget` gets a +think budget of `max_tokens - max(256, max_tokens / 4)`, or the request's own `thinking_budget` when that is smaller, +so the think block closes with room left for the call instead of ending as `length`. It changes the reply of any such +call whose thinking would have run past that point. `"auto"`, `"none"` and requests without tools are unchanged. Drafting stays enabled and uses the same grammar masks as plain decoding. This requires the loaded backend's structured-output capability and `libtfgrammar`. Nemotron, Qwen3.5-2B, @@ -1001,11 +1035,12 @@ A startup capacity estimate is not a measured release capacity. On a unified-memory GPU (the DGX Spark's GB10), the CUDA server's allocations come out of the host's RAM but are not charged to a container's memory limit (`docker run --memory`, cgroup `memory.max`): the limit neither caps the model's weights and cache nor keeps them from crowding other work on the machine. The startup budget is the host's -`MemAvailable` less a reserve (a tenth of RAM, at least 4 GiB). On native CUDA a stream's window is `--context`, the -model's own window at `--context 0`, or, when it is unset, the family's default capped at the model's own window; on -the paged families the streams and pages then fill the budget up to the streams' windows plus the cache's pages, so -once those exceed it, the free memory after load is the reserve. To leave room for other containers, start the server -with a smaller `--context` or `--parallel`. +`MemAvailable`, at most the free memory CUDA reports, less a reserve (a tenth of RAM, at least 4 GiB). CUDA does not +count the page cache as free, so before loading, the server drops the checkpoint's own shards from it. On native CUDA +a stream's window is `--context`, the model's own window at `--context 0`, or, when it is unset, the family's default +capped at the model's own window; on the paged families the streams and pages then fill the budget up to the streams' +windows plus the cache's pages, so once those exceed it, the free memory after load is the reserve. To leave room for +other containers, start the server with a smaller `--context` or `--parallel`. `TENSORFOLD_MEMORY_RESERVE_GIB` replaces that reserve (at least 2 GiB) when you know the machine's headroom: a larger one leaves more for other work, a smaller one more for KV caches. The reserve also carries CUDA context, NCCL and workspace memory the estimate does not count, and exhausting a unified GPU's memory can freeze the host, so lower it @@ -1446,7 +1481,8 @@ an engine that keeps no prompt states answers 501. - `DELETE /v1/imprint` forgets every conversation state this server's model and build keep on disk: it deletes the store's state and row files and answers `freed_bytes`. What stays holds no conversation data: the store's folder with its `used` stamp, and the `written` and `clock` files at the top of the `--learn-dir` folder (the bytes written today, - and the order the stores were last opened in). States in RAM stay until they are evicted. + and the order the stores were last opened in). States in RAM stay until they are evicted, or until a + [flush](#flush-the-prompt-cache). What stays on disk: under the `--learn-dir` folder (`~/.cache/tensorfold/learned` by default), directories readable by their owner only (0700) hold files readable by their owner only (0600). They contain token ids and the model's own @@ -1497,6 +1533,72 @@ server sends the counters described under [Responses](#responses). For memory fi [`/memory`](memory-diagnostics.md) (it needs a key when keys are configured) or `/metrics`' `tensorfold:process_footprint_bytes`. +## Execution witness + +`serve --execution-witness` (off by default) adds `GET /v1/execution/witness`, a read-scoped snapshot of what serves +replies. Without the flag the route answers 404, nothing is hashed and replies are unchanged. The flag needs an API key +(`--api-key`, `--api-key-file` or `TENSORFOLD_API_KEY`) or `--unix-socket`, whose owner-only socket stands for one; +without either the server refuses to start. Hashing starts after the server is ready, on a thread of its own, and a read +never hashes: it copies the latest snapshot. A stop ends a hash in progress at its next block. + +A known snapshot is `{"schema": 1, "state": "known", "witness", "content", "instance", "epoch", "path", "components"}`: + +| Field | Meaning | +| --- | --- | +| `content` | SHA-256 over `path` and every component; the same files, build and settings give the same value after a restart | +| `witness` | SHA-256 over `content`, `instance` and `epoch`: a restart or an engine reload always gives a new one | +| `instance` | 128 random bits drawn when this process started | +| `epoch` | The engine's generation: 1 at startup, one more each time `--idle-unload` reloads it | +| `path` | The engine's label for the supported path it attests | +| `components.engine` | The engine's own digest of what it binds for that path | +| `components.binary` | The running executable's SHA-256, read from the file the server opened before loading the model (`/proc/self/exe` on Linux, the executable's path elsewhere) | +| `components.text` | The checkpoint's tokenizer, template, special-token and EOS files (or their absence) and `--chat-template`'s file, whose stamps the server took before loading them | +| `components.preparation` | The serve defaults a request starts from: sampling, `--instruct-sampling`, max tokens, thinking, loop guard, seed salt, drafts, and the loaded template and EOS ids | +| `components.environment` | Every `TF_*` and `TENSORFOLD_*` variable the process started with, except names ending in `_API_KEY`, `_SECRET`, `_PASSWORD`, `_TOKEN`, `_SIGNING_KEY`, `_SECRET_FILE` or `_KEY_FILE` (such as `TENSORFOLD_API_KEY`, `TENSORFOLD_TOOL_ID_KEY_FILE`, `TF_RUNTIME_SIGNING_KEY` and `TF_STAGE_SECRET_FILE`); other names, such as `TF_SLIDE_POCKET_KEY`, are hashed | + +Otherwise the body is `{"schema": 1, "state": "unknown", "reason", "instance", "epoch"}`, and inference is unaffected. +`reason` is `pending` (still hashing), `unsupported_path` (the engine attests no supported path; every engine so far), +`feature_excluded` (with `feature` naming the flag: `--slide`, `--learn`, `--learn-conversations`, `--spill-gib`, +`--compact-at`, `--compact-memory`, `--cortheon`, `--recall`, `--drafter`, `--mtp-drafts`, `--record`, `--vision`, +`--tp` above 1 or `--speed-up`), `parked` or `reloading` (an idle-unloaded engine), `files_changed` (a text file or +the executable changed after the server opened or stamped it) or `hash_failed` (a file could not be read; when the +binary cannot be opened or the text files cannot be stamped at startup, a startup line says why). The engine's facts +and the epoch are read under the lock every reload takes, so one snapshot never mixes two engines. The snapshot alone +does not qualify a response cache. + +### Reply binding + +A chat completion or completion with `"execution_witness": true` carries a top-level `execution_witness` object on the +whole reply, or on a stream's finish chunk (not on the separate usage chunk). It is read just before the engine takes +the request and again once the reply ends; the request keeps the engine from parking in between. The witness is +read-scoped, so a scoped key needs `read` beside `inference` to ask (else 403 `insufficient_scope`); a full or `[admin]` +key may always ask. Only these two routes carry the binding: `/v1/responses`, `/v1/messages` (and its `count_tokens`), +`/api/chat` and `/api/generate` rebuild the request and answer a true `execution_witness` with HTTP 400. + +| Field | Meaning | +| --- | --- | +| `state` | `known` when the witness was known at both reads, with the same `epoch` and `witness`; else `unknown` | +| `binding` | Known only: SHA-256 over `witness`, `prompt_sha256`, `request_sha256`, `token_sha256` and `finish_reason` | +| `witness`, `path` | Known only: the snapshot's, as `GET /v1/execution/witness` gives them | +| `instance`, `epoch` | The process and the engine generation at the end | +| `reason`, `feature`, `admitted_epoch` | Unknown only: the snapshot's reason, or `epoch_changed`, `witness_changed` or `unbound` (below); the epoch at admission | +| `prompt_sha256` | The prompt's token ids after the template, hashed as `tensorfold.token_sha256` hashes the reply's | +| `token_sha256` | The reply's token ids, equal to `tensorfold.token_sha256` | +| `finish_reason` | The reply's | +| `request` | The resolved request the engine read: `max_tokens` after the window's clamp; `sampling` (null when greedy, else the `seed` actually used, `temperature`, `top_k`, `top_p` and `min_p`); `presence_penalty`, `frequency_penalty`; `eos` and `stop`; `drafts`; `think_budget`, `think_close`, `think_end`, `answer_max`; `loop_guard`, `loop_stop`; `call` (a required tool call's gate); `structure` (the grammar's `kind`, `text_sha256`, `after`, `budget`); `logprobs`, `prompt_logprobs`, `decide` and `untaught` | +| `request_sha256` | SHA-256 over `request`, walked in order as below | + +Every field is length-prefixed: its byte length as a little-endian u64, then its bytes. `request_sha256` hashes the field +`tensorfold resolved request v1`, then the value: `n` for null; `b` then `1` or `0`; `i` then the integer's decimal +text; `f` then the float's IEEE-754 bits as a little-endian u64 (every float in the reply round-trips); `s` then the +string; `a` then the count as a little-endian u64, then each item; `o` then the count, then each key as a field and its +value. `binding` hashes the field `tensorfold execution binding v1`, then `witness`, `prompt_sha256`, `request_sha256`, +`token_sha256` and `finish_reason`, each as its text in the reply. A reply that took a path that binds nothing (with +`--compact-at` or `--cortheon`, which the witness already excludes) carries only `schema`, `state: "unknown"`, `reason` +(and `feature`), `instance` and `epoch`, with the snapshot's reason. `reason` is `unbound` if that snapshot reads known; +no route does that today, since each path that binds nothing runs only under a flag the witness excludes, so `unbound` +would mean a reply path that skipped the binding by mistake. No response cache reads the binding yet. + ## Cancel a request `POST /v1/requests/{id}/cancel` (or `/requests/{id}/cancel`) cancels a running or queued request by the id its @@ -1517,6 +1619,31 @@ also refuses a request that carries `Forwarded`, `X-Forwarded-For`, `X-Forwarded `CF-Connecting-IP` or `True-Client-IP`. A proxy that adds none of them cannot be told apart from a local caller: give a proxied server keys. +## Flush the prompt cache + +`POST /v1/prompt_cache/flush` drops every prompt state the server keeps for resuming conversations: those in RAM, and +those on disk when it keeps them there (`--prompt-cache-disk DIR`, `--learn-conversations` or `--spill-gib`). It waits +for the requests already running to end, so their replies are unchanged, and requests that arrive meanwhile wait in the +queue and start after it. Then it answers 200 with `{"object": "prompt_cache.flush", "states": ..., "ram_bytes": ..., +"disk_bytes": ..., "disk": ..., "waited_seconds": ...}`: the states dropped from RAM and the bytes they held in the +cache's budget, the bytes deleted from the server's own state folder, whether this server keeps states on disk, and how +long the flush waited. The next turn of any conversation prefills its whole prompt and gives the tokens it would have +given resumed. Two flushes asked together run one after the other, and the second finds nothing left. States `--learn` +keeps for shared prompt prefixes stay on disk, as they do after `DELETE /v1/imprint`, so with `--learn` a later prompt +may still resume from one. The body, if any, is ignored. + +An engine without the shared prompt cache (its cache turned off, or a backend that keeps its states its own way) +answers 501 `not_supported` at once and holds nothing back. If the running requests have not ended within 10 minutes, +the flush is withdrawn: nothing is dropped, new requests start again, and the answer is 503 `timeout`. While a flush +waits, `--idle-unload` does not unload the model; a model it has already unloaded is not loaded for a flush, which +answers 503 `model_unloaded` (no state is in RAM then, and the states it saved to disk stay until a flush after the next +request loads it). + +Who may flush is decided as for [cancelling a request](#cancel-a-request). With API keys it is an admin route: a full +or `[admin]` key may flush from any address, a scoped key gets 403 `insufficient_scope` and a missing key 401. Without +keys only a caller whose socket is on the loopback address (127.0.0.0/8 or ::1) may flush, and only when the request +carries none of the proxy headers listed there; anyone else gets 403 `loopback_only`. + ## The Responses API `POST /v1/responses` takes OpenAI's Responses request and runs it as the equivalent chat completion, through the @@ -1563,7 +1690,7 @@ prompt cache resumes the shared prefix as it does for chat. `store: false` keeps response. HTTP 400 refuses what this server does not run: built-in tools (web search, file search, computer use and the -others), `conversation`, `prompt` templates, `context_management`, `truncation: "auto"`, file IDs and +others), `conversation`, `prompt` templates, `context_management`, `truncation: "auto"`, `execution_witness`, file IDs and remote file URLs (`input_file` parts with inline `file_data` run on a model started with `--vision --vision-pdf`), `item_reference` items, encrypted reasoning items, and a `previous_response_id` that is not stored. `include` takes a list of OpenAI's names. `message.output_text.logprobs` asks for logprobs where the engine has them @@ -1668,7 +1795,8 @@ is an explicit off, which returns HTTP 400 when the template cannot honor it (se `/v1/messages` submits. Thinking round-trips as plaintext with an empty signature; `display` does not suppress it. Claude Code's `context_management` keep-all thinking directive is accepted. Mid-conversation system text stays in place with its system role; the model's chat template must support later system messages. Turn-scoped -system messages, per-message output configuration and inline tool changes are unsupported. +system messages, per-message output configuration and inline tool changes are unsupported, and a true +`execution_witness` answers HTTP 400 (see [Reply binding](#reply-binding)). JSON schema output, including Claude Code title requests, requires `pip install 'tensorfold[grammar]'`. That install is the Python 0.6.6 engine's; the native server uses `libtfgrammar` from the release archive instead ([structured output](#structured-output)). diff --git a/docs/environment.md b/docs/environment.md index 0f302bb129b..fbf0aa9aead 100644 --- a/docs/environment.md +++ b/docs/environment.md @@ -10,6 +10,7 @@ Diagnostics quote and escape the supplied text so it cannot create another termi | `TF_CACHE_EVICT` | `main` (default) or `decayed_resume`. The opt-in gives recently resumed RAM snapshots bounded recency credit, within the same cache budget. It changes victim choice, not stored state or token arithmetic. Paged stores keep their own policy. Blank keeps `main`; other values are refused at server startup. | | `TENSORFOLD_VIDEO_TOKENS` | Nonnegative whole video-token budget; default 16384; stored as an unsigned 64-bit count | | `TENSORFOLD_MAX_PDF_PAGES` | Whole count 1 through 4294967295, capped by `--vision-max-images`; default min(16, image limit) | +| `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_RESTORE_PREFETCH` | Whole unsigned 64-bit count, capped at 65536; zero disables reading ahead; default 2 | @@ -43,6 +44,7 @@ Diagnostics quote and escape the supplied text so it cannot create another termi | `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_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 | | `TENSORFOLD_LFM2_KV_PAGES` | Exactly `0` or `1`, checked when the CUDA backend starts; unset leases pool pages ([profiles](profiles.md)) | @@ -61,8 +63,9 @@ Diagnostics quote and escape the supplied text so it cannot create another termi | `TF_GLM_PROMPT_STEPS` | Exactly `0` or `1`; default on (GLM prompt passes in chunks); read on rank 0 | | `TF_GLM_SHARED` | Exactly `0` or `1`; default on (GLM windows share a forward); read on rank 0 | | `TF_GLM_DSEL` | Exactly `0` or `1`; default on (a GLM decode window's DSA select runs on many CTAs; 0 keeps one CTA a row) | +| `TF_GLM_DSCORES` | Exactly `0` or `1`; default on (a GLM decode window's DSA index scores run on glm_index_scores; 0 keeps tf_glm_scores) | | `TF_GLM_DFLASH2_LOG` | Whole unsigned 64-bit count of DFlash2 rounds whose drafts are logged; default 0 | -| `TF_GLM_DRAFT_CONFIDENCE` | Finite number 0 through 1 where a DFlash2 chain's chance product stops it; default 0.7 | +| `TF_GLM_DRAFT_CONFIDENCE` | Finite number 0 through 1 where a DFlash2 chain's chance product stops it; default 0.7 on CUDA, 0.5 on Metal | | `TF_GLM_CONTEXT_CEILING` | GLM-5.3-Flash on CUDA: whole token count 1 through 2147483616, the window `--context` may ask for and `--context 0` serves, in place of config.json's 1048576; read at GLM's open. Past that length the model's quality is the operator's to check. Unset keeps config.json's window | | `TF_GLM_EXPERT_FORM` | `classic` or `factored`: the expert form GLM's CUDA decode windows use at every width (the same bits either way), also at a load that times nothing; unset or blank races the two at each timed width when a build first loads with drafts and scratch context and keeps each width's winner, else classic; read on rank 0, which chooses every rank's forms | | `TF_GLM_INDEX_CUDA` | GLM on CUDA: exactly `1` (both DSA indexer kernels), `0` (neither) or `scores` (scores only); unset or blank is `both` | @@ -121,13 +124,13 @@ An explicit `--device` or `--segments` wins over its environment value, even if The carveout size is checked only when the carveout is enabled, and still rounds to framebuffer rows. `TF_NO_TREES` retains precedence over `TF_DRAFT_NODES`. Backend-specific settings are checked when that backend starts; slide settings require learning to be enabled. -The `TF_GLM_*` rows are checked when GLM's CUDA family opens, on every rank, so they never stop another family. +The `TF_GLM_*` rows are checked when GLM's CUDA family opens, on every rank, so they never stop another family; on Metal `TF_GLM_DRAFT_CONFIDENCE` is read and validated when GLM loads `--drafter`. Common server settings are checked before checkpoint resolution, including when no request would use them yet. Direct family readers also refuse malformed values when called without the server. ## Flash Next -Flash Next checks these 34 settings when its engine loads, before any device or checkpoint work: a malformed value +Flash Next checks these 35 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 | @@ -166,6 +169,7 @@ stops the start with the variable, the supplied text and the accepted forms. | `TF_FLASHNEXT_KV_PAGE_TEST` | Whole page size the kernels take: whole blocks of the indexer's ratio up to the window; unset or blank leaves the plain caches | | `TF_FLASHNEXT_CONFIDENCE` | Finite number, negative values included; default -0.4, the chain's own stop | | `TF_FLASHNEXT_PROMPT` | Exactly `rows` for the rows path; unset or blank keeps the plain path | +| `TF_FLASHNEXT_DRAFT_HEAD` | Exactly `bf16` or `affine4`; unset or blank is `affine4`, a bf16 language head's draft rows held as 4-bit affine groups of 32. `bf16` keeps the rows as stored. Drafts only, so replies are unchanged | An on-by-default switch keeps the same kernels and bits as off; only the launch count changes. The two row counts and the two draft counts keep their existing clamps after parsing. @@ -197,3 +201,19 @@ The profile registry reports selected arithmetic/experimental overrides; it does See [profiles](profiles.md) for classes, scopes and grouped slide-learning names. `capabilities --json` no longer advertises `TENSORFOLD_NO_UPDATE_CHECK` or `HF_HUB_OFFLINE`: the native binary reads neither. The command-line `--no-update-check` remains an accepted no-op. + + +### Qwen mapped-host KV capacity mode + +`TF_QWEN_KV_HOST=1` opts the dense and MoE CUDA hybrids into mapped pinned-host KV pages (#2637). +It requires `TF_QWEN_KV_PAGES` and `TF_QWEN_KV_PAGES_ALL=1`, `--parallel 1`, and a discrete GPU. +State and verify runs remain on the device. Spill, disk snapshots and `TF_QWEN_KV_SHARE` are refused by name. +The default path, with the switch unset, retains its existing plan, allocations and execution. + +| Setting | Accepted value | Default | Effect | +|---|---|---|---| +| `TF_QWEN_KV_HOST_GIB` | Positive whole GiB, at most 17179869183 | Unset or blank | Optional upper limit; below a whole KV window including lookahead is refused. Runs are not charged to this cap. | + +This is a capacity tradeoff, not a speed claim: attention reads mapped host KV over the device interconnect. +Set `--prompt-cache-gib` explicitly to bound the separate host prompt cache. +Host-on inference equality and performance on a discrete GPU remain device checks, not host-test results. diff --git a/docs/kernel-contract.md b/docs/kernel-contract.md index ef102b60ccf..e01ce669687 100644 --- a/docs/kernel-contract.md +++ b/docs/kernel-contract.md @@ -384,6 +384,8 @@ Its decoders' own kernels (`metal_idol_decoder*.zig`) are checked too: the point `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). 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. @@ -426,8 +428,9 @@ CUDA also checks GLM-5.3-Flash's KV page kernels on a page table out of order: t (`tf_glm_lat_write`, `tf_glm_pool_keys`), the index scores and the selected tokens' rows (`tf_glm_scores`, `tf_glm_dsa_tokens`), and the MLA chunks through their merge (`tf_glm_chunks_16` and `tf_glm_chunks_32`, dense and sparse). Its prompt indexer (`tf_glm_index_scores`, `tf_glm_index_pools`) is bit-equal to `tf_glm_scores` and -`tf_glm_select_rows`, and its decode select at a 1,024-thread block a row (`tf_glm_select_rows_wide`) and in spans -over many blocks (`tf_glm_dsel_scan`, then `tf_glm_dsel_merge` a block a row) to `tf_glm_select_rows`; both stated +`tf_glm_select_rows`, its decode windows' scores (`tf_glm_index_scores` at the decode tiling) to `tf_glm_scores`, +and its decode select at a 1,024-thread block a row (`tf_glm_select_rows_wide`) and in spans over many blocks +(`tf_glm_dsel_scan`, then `tf_glm_dsel_merge` a block a row) to `tf_glm_select_rows`; both stated rules rank any NaN above +inf, as the GPU's `s + 0` makes every NaN one positive NaN. CUDA also checks `TF_GLM_KV_HOST`'s gather (`tf_glm_kvh_*` in `glm_ops.cu`, launched by `cuda_kv_host.zig`): the marks (a slot for each distinct pick; past its slots, the call flagged and no row left marked), the picked rows into @@ -473,6 +476,7 @@ both gather heights, with a partial last column group in the dense entry. Gate 1 requires the predecessor's bytes, NaN payloads included; these entries compare and keep sums rather than requalify them, so gate 4 does not apply. Each has a control, a planted source fault red at `shapes`, and its launches are in `glm_launch_records.zig`. +GLM's Metal DFlash2 drafter also registers its ring-buffer block attention (`glm_draft_attend`, `glm_draft_attend_merge`), top-k selector (`glm_draft_topk`), candidate-subset gather head (`glm dflash2 head`, q4/q8 affine gather and row paths), same-buffer GPU accept (`glm_draft_accept`) and GPU follow (`glm_draft_follow`), with planted controls for ring overrun, masked-key leakage, stream-0 ring aliasing, candidate-score tie/drop faults, wrong accepted token, and oversized sliding window. CUDA also checks LFM2.5-24B-A2B's kernels: the router's fp32 logits (`tf_lfm2m_route`) and its top-4 rule, Liquid's 3-tap short conv with its per-row state snapshots and the state commit (`liquid_conv.cuh`), each against the host's replay of its fp32 and bf16 steps (three controls: ties to the higher expert, bx unrounded, every stream committing into @@ -490,7 +494,9 @@ the fp32 down launched one 32-input group short, and a down summing in bf16). nv decode forms on sm_120 and sm_121 take other registers than 13.0's and have their own records. CUDA also checks GLM's NVFP4_NZ5 block 32 experts (`tf_nvfp4_nz5_*`), each bit-equal to the block 16 instance it replaces on the same values: a planted +5 is a 4 there under its scale two e4m3 steps up (x1.25), and the E2M1 -entry reading NVFP4_NZ5's codes, each +5 as -0, is the planted control. +entry reading NVFP4_NZ5's codes, each +5 as -0, is the planted control. Gate 4's stress fill holds +5s among its 4s +and 6s, two on equal inputs mirrored by a -4 and a -6 (NVFP4_NZ5 has no -5), with the float64 reference reading +0b1000 as 5; the same E2M1 entry on that fill is a second control, red at gate 4. CUDA also checks Nemotron's pocket (`nemotron_ops.cu`, the learned neurons the living-weights learner adds beside the shared expert): relu^2 up into act rows and down added into the shared expert's slot, a block row a row and tiled, the down to fp32 and bf16, against float64, the neurons past the count NaN so a read of one shows (two controls: the up's diff --git a/docs/optimization-ledger.md b/docs/optimization-ledger.md index 66709817759..8909cb53019 100644 --- a/docs/optimization-ledger.md +++ b/docs/optimization-ledger.md @@ -64,7 +64,7 @@ last two hold the families with only a Metal, HIP or scoring backend. | 13. MoE grouped | done [#605] | done [#1351], open M[#2784] | done [#864] | no (dense) | done [#558] | | 14. CUDA graphs | done¹ | done [#1786] | open [#2279] | done [#1174] | done [#615] | | 15. MTP | done [#1562] | done [#1925] | done [#1585]; wide C open [#2257] | done [#1385] | done [#997] | -| 16. DFlash(2) | done [#1465] | yes | done [#979] | done C¹ M[#879] | yes | +| 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] | @@ -299,8 +299,8 @@ below; these are estimates for planning a port, not results. | Family | Last layer, layers | Main blocker | Gain | Effort | | --- | --- | --- | --- | --- | - | qwen3_5 (27B) | full attention, 64 | MTP taps the last layer | −1.2..−1.6 % TTFT | done [#2229] | - | qwen3_5 (35B-A3B) | full attention, 40 | MTP taps the last layer | −1.3..−2.9 % TTFT (no drafter) | done [#2229] | + | qwen3_5 (27B) | full attention, 64 | MTP taps the last layer when drafting | −1.2..−1.6 % TTFT; unread chunks [#2941] | done [#2229] | + | qwen3_5 (35B-A3B) | full attention, 40 | MTP taps the last layer when drafting | −1.3..−2.9 % TTFT (no drafter); unread chunks −0.5..−0.6 % (−28..−35 ms) cold 32K, −3 ms 8K [#2941] | done [#2229] | | gemma4 | global attention, 42–60 | drafter taps copy every row | ~1.5 % | easy | | dory | an MLP sublayer, 72 sublayers | none | ~1.3 % | easy | | spark25 | full attention, 36 | fused QKVG GEMM | ~2 % | medium | @@ -312,7 +312,7 @@ below; these are estimates for planning a port, not results. | glm | KDA linear layer, 45 | must write the recurrent state for every row | small | hard | | qwen4, lfm2 | | | n/a | | - The qwen3_5 numbers are measured. The others are estimates (`~`): about 1/layers, minus the k/v share. + The qwen3_5 numbers are measured. The 35B-A3B unread-chunk path is a quiet-GB10 A/B: 32K −28.4 ms median per-round and −34.5 ms median adjacent (-0.5..-0.6 %), 8K −3..−4 ms, 2K level, tokens equal ([#2941], @jschmied). The others are estimates (`~`): about 1/layers, minus the k/v share. 2. **KV pages from the core pool.** Streams lease KV pages from one `kv_pool` as their rows grow, instead of each reserving a whole `--context` window, so more streams fit and a short request holds little ([#1156], [#781]'s @@ -489,6 +489,7 @@ below; these are estimates for planning a port, not results. | Family | Gain (measured) | Where | | --- | --- | --- | | flashnext (C), TP=2 | prompt passes reduce-scatter the experts' slots by rows: rank 0 sends 5.81 → 3.43 MiB a prompt token, cold prefill +26.5..+26.8 % on two GB10s, +30.9..+33.9 % on two RTX PRO 6000s, same replies | [#2977] | + | flashnext (C), TP=2 | control-link waits poll 50 µs for 50 ms before they block: drafted decode +1.4..+1.5 % at one stream, +3.7..+4.7 % at four on two GB10s, same replies | [#2971] | 26. **Pipeline stages.** Layer ranges on different nodes, one hidden row a token over Ethernet, so a GB10 and a Mac can serve one model ([#2005]). The stage link and its protocol are [#2012] and [#2060]; the 27B as a stage is @@ -707,3 +708,5 @@ below; these are estimates for planning a port, not results. [#2977]: https://github.com/ashhart/TensorFold/pull/2977 [#2805]: https://github.com/ashhart/TensorFold/pull/2805 [#3305]: https://github.com/ashhart/TensorFold/issues/3305 +[#2941]: https://github.com/ashhart/TensorFold/issues/2941 +[#2971]: https://github.com/ashhart/TensorFold/pull/2971 diff --git a/docs/profiles.md b/docs/profiles.md index 242b10a18b8..ac755f11a4b 100644 --- a/docs/profiles.md +++ b/docs/profiles.md @@ -180,8 +180,10 @@ The other pool classes conservatively retain the audit's `arithmetic` classifica Images and vision bias also have independent rows. `ENGRAM_DIR` is reported as ``; its path is never printed by the registry line. The legacy `TF_DSV41_TOOL_GRAMMAR` alias has a server-wide reader, although this row covers DeepSeek CUDA. A present `TENSORFOLD_TOOL_GRAMMAR` takes precedence and suppresses the masked legacy row. +`FLOAT_LINEAR` is off by default and is not one of this table's rows: with it unset a projection a pack keeps as a +float matrix alone is refused, as before. -All 81 `TF_DSV41_*` settings that DeepSeek validates are rows of the shared startup table in +All 82 `TF_DSV41_*` settings that DeepSeek validates are rows of the shared startup table in `zig/src/platform/environment.zig` (see [environment settings](environment.md)). Their readers read through that table; the served-knob readers of `PREFILL_ROWS` and `INDEX_BUDGET_MIB` keep their own stricter refusals after it. `Model.open` and the AOT planner check those rows before any allocation, device or checkpoint work, and a later @@ -271,3 +273,13 @@ On a verified four-rank verbs relay with no opposite-rank link, `tf-tp-test suit exchange references, including that exchange in graph replays. NCCL selects those receive ports by channel on this topology. The suite prints the reason, the two reference types and the number of comparisons left out; all sums, gathers, remaining graph nodes and timing sweeps still run. Other topologies keep the complete suite. + + +### Qwen host KV placement + +`TF_QWEN_KV_HOST=1` is an opt-in identical-output placement switch for the dense and MoE CUDA Qwen hybrids (#2637). +It places only KV pages in mapped pinned-host memory; state and verify runs stay on the device. +It requires a discrete GPU, `TF_QWEN_KV_PAGES`, `TF_QWEN_KV_PAGES_ALL=1` and `--parallel 1`. +Integrated GPUs, spill, disk snapshots and `TF_QWEN_KV_SHARE` are refused. The GiB cap is documented in [environment.md](environment.md). +Unset keeps the existing plan and device-page behavior. Host tests prove planning and allocation ownership only; +model token equality, MTP and resumed-prompt equality still require the same-checkpoint device receipt. diff --git a/docs/receipts/flashnext-draft-head/README.md b/docs/receipts/flashnext-draft-head/README.md new file mode 100644 index 00000000000..8b446c150fe --- /dev/null +++ b/docs/receipts/flashnext-draft-head/README.md @@ -0,0 +1,113 @@ +# Flash Next draft head: main against the branch + +`TF_FLASHNEXT_DRAFT_HEAD=bf16|affine4` says how the MTP head holds a bf16 language head's rows for the draft vocabulary +(79,591 rows of 2,560). On main, unset is `bf16`, and a blank value stops the start (`BadDraftHead`). On the branch, +unset or blank is `affine4`: 4-bit codes with a bf16 scale and bias for each group of 32, fitted at load from the +group's minimum and maximum, as `TF_FLASHNEXT_DRAFT_HEAD=affine4` already does on main. `bf16` keeps main's rows. + +Two windows, each with both arms built from the same upstream main: + +- 1, 2 and 4 streams at a 131,072-token context: main `d6c4cce602eef4aff235625a5325bb617a9674ff` against the branch on + it (`cells.csv`, `rule5.md`, `exactness.md`). +- 1, 4 and 8 streams at a 65,536-token context: main `41a72fd2578dfbdd73b25663da78d5fc0047bd95` against the branch on it + (`cells-8.csv`, `rule5-8.md`). `--parallel 8` does not start at 131,072 tokens here; the engine stops with + `--parallel 8 needs 32.86 GiB for its streams at a 131072-token window, and the CUDA memory budget leaves 27.99 GiB`. + +## Source and environment + +- One NVIDIA GB10 (sm_121), Zig 0.17.0, CUDA 13.3, Linux. +- Checkpoint `nvidia/Qwen3.8-Flash-Next-FP4-Local`, revision `b9ce18a6887e18c089fdea8509a33e63429a3300`, every arm. Its + language head is bf16, the case the setting applies to. +- bf16 KV, prompt cache on, a fresh server per arm. Server flags `--kv-cache bf16 --max-tokens 32768 --temperature 1.0 + --top-p 0.95 --top-k 20`; the tools set each request's temperature. +- The serve recipe sets the same environment for every arm. Of the settings main reads: `TF_FLASHNEXT_KEEP_LATE=1` and + `TF_FLASHNEXT_WARM_AHEAD=1` (main's defaults are unset and 0), `TENSORFOLD_MEMORY_RESERVE_GIB=9`, and + `TF_FLASHNEXT_CONFIDENCE`, `TF_FLASHNEXT_DRAFTS`, `TF_FLASHNEXT_GDN_LANES`, `TF_FLASHNEXT_SAMPLED_HEADS` and + `TF_FLASHNEXT_SHARED_SIDE` at main's defaults. The twelve other `TF_FLASHNEXT_*` names it sets have no reader on main. +- Arms, in order: M1 (main), U1 (branch, unset), X1 (branch, `bf16`), M2, X2, U2 (branch, set blank). No cell was + slower in either window, so the noise rule's rerun did not run. +- Main's tools. First window: `tools/bench_openai.py` (one stream; greedy, 3 reps; temperature 1.0, 9 reps with seeds + 1234 to 1242; its median decode rate) and `tools/bench_concurrent.py --alone --serial` (1, 2 and 4 streams, 256 + tokens, 3 reps; greedy, and temperature 1.0 with `--seed` 1234, 2234 and 3234; aggregate tok/s). Second window: + `tools/bench_concurrent.py --alone --serial` at 1, 4 and 8 streams, greedy and temperature 1.0 with `--seed` 1234. + +## Decode speed and tokens a round + +The CSV files have every cell of every arm. `tokens_per_round` is the tools' tokens a streamed chunk (a round sends its +accepted drafts and one verified token), `accepted_per_round` is that less one, and `server_acceptance` is the +server's `mtp_accepted_total` over `mtp_drafted_total` across the invocation. The `rule5` files have every cell's runs +and verdicts; there U is the branch unset or blank (`affine4`) and X is the branch with `bf16`. Below, the branch unset +is the mean of its two runs against the mean of main's two. + +First window, main `d6c4cce602`, 131,072 tokens: + +| cells | unset (`affine4`) against main | tokens a round, main to unset | +|---|---|---| +| greedy, code, 1/2/4 streams | +15.9%, +10.5%, +9.3% | 5.22 to 5.45, 4.83 to 4.83, 4.83 to 4.83 | +| greedy, chat, 1/2/4 streams | +9.5%, +8.8%, +8.0% | 2.81 to 2.84, 2.51 to 2.54, 2.51 to 2.54 | +| greedy, one stream (`bench_openai`), code and chat | +16.5%, +9.6% | 5.22 to 5.45, 2.81 to 2.84 | +| temperature 1.0, 9 seeds, one stream (`bench_openai`), code and chat | +12.5%, +7.0% | 4.06 to 4.13, 2.56 to 2.48 | +| temperature 1.0, seeds 1234, 2234 and 3234, code, 1/2/4 streams | +5.9% to +12.2% (9 cells) | -0.14 to +0.10 | +| temperature 1.0, seeds 1234, 2234 and 3234, chat, 1/2/4 streams | +3.7% to +8.2% (9 cells) | -0.11 to +0.01 | + +Second window, main `41a72fd257`, 65,536 tokens, `--parallel 8`: + +| cells | unset (`affine4`) against main | tokens a round, main to unset | +|---|---|---| +| greedy, code, 1/4/8 streams | +16.4%, +9.0%, +8.4% | 5.22 to 5.45, 4.83 to 4.83, 4.49 to 4.49 | +| greedy, chat, 1/4/8 streams | +9.0%, +8.1%, +6.9% | 2.81 to 2.84, 2.51 to 2.54, 2.51 to 2.54 | +| temperature 1.0, seed 1234, code, 1/4/8 streams | +9.0%, +5.9%, +5.5% | 4.57 to 4.57, 3.83 to 3.81, 3.72 to 3.74 | +| temperature 1.0, seed 1234, chat, 1/4/8 streams | +6.2%, +5.6%, +4.4% | 2.39 to 2.35, 2.46 to 2.44, 2.43 to 2.41 | + +With `bf16` the branch is level with main in every cell of both windows (-0.5% to +1.8%), with main's tokens a round in +every cell and main's server acceptance in every invocation. + +Server acceptance, main to unset. First window: greedy 0.624 to 0.629 (`bench_openai`) and 0.679 to 0.697 +(`bench_concurrent`); temperature 1.0, 0.691 to 0.685 (`bench_openai`, 9 seeds), 0.722 to 0.715 (seed 1234), 0.700 to +0.678 (seed 2234) and 0.688 to 0.696 (seed 3234). Second window: greedy 0.686 to 0.713, seed 1234 0.714 to 0.712. The +greedy code cells at 4 and 8 streams keep main's tokens a round and still run faster, so that gain is the cheaper draft +pass, not acceptance. + +## The noise rule + +A cell is slower when both branch runs are under both main runs and the mean gap is over 1%; it gets one rerun, and a +repeat is a loss. + +- Unset and blank against main: 0 of 28 cells slower in the first window and 0 of 12 in the second. In all 40 both + branch runs are above both main runs, by 3.7% to 16.5% on the mean. +- `bf16` against main: 0 of 40 cells slower; all 40 level. + +## Memory + +The server process's device memory (`nvidia-smi --query-compute-apps`), after load and after the benches. First window: +main 75,305 and 76,578 MiB (76,582 for M2), `bf16` the same, unset and blank 75,038 and 76,311 to 76,313 MiB. Second +window: main 75,289 and 76,536 to 76,548 MiB, `bf16` 75,289 and 76,546 to 76,558 MiB, unset and blank 75,022 and +76,271 to 76,281 MiB. The 267 MiB is the draft rows: 79,591 x 2,560 weights at 0.625 bytes each against 2. + +## Cold prompts + +First window: a cold 8k and a cold 32k prompt (new text each rep, 2 cached tokens), three reps an arm, thinking off: +medians 4.01 to 4.06 s at 8k and 16.07 to 16.19 s at 32k across the six arms. The draft head is not in prompt +processing. + +## Off, on and malformed values + +- U1 (unset) and U2 (the container's environment holds `TF_FLASHNEXT_DRAFT_HEAD=` empty) take the same rounds: their + server acceptance is the same in every invocation. +- `TF_FLASHNEXT_DRAFT_HEAD=BF16` stops the branch's start before any load: `TF_FLASHNEXT_DRAFT_HEAD="BF16": expected + bf16 or affine4 (unset or blank keeps affine4, a bf16 language head's draft rows as 4-bit groups of 32; bf16 keeps + the rows as stored)`. +- On main, `TF_FLASHNEXT_DRAFT_HEAD=` (blank) stops the start when the head loads, with `BadDraftHead`. + +## Exactness + +`exactness.md` (first window): drafted against `"draft": false`, resumed against fresh and concurrent against solo, on +main, the branch unset and the branch with `bf16`, each with the prompt cache on and off. Every equality holds in every +arm, and the branch's replies equal main's. Second window: `bench_concurrent.py`'s own comparison of each concurrent +reply with the same request alone finds 0 unequal across every request of every arm, at 1, 4 and 8 streams. + +## Not established + +GB10 only. Eight streams ran at 65,536 tokens, the largest of 131,072 and 65,536 that starts with the recipe's 9 GiB +reserve. A checkpoint whose language head is affine keeps its stored rows and was not run. Metal and HIP do not read +this setting. diff --git a/docs/receipts/flashnext-draft-head/cells-8.csv b/docs/receipts/flashnext-draft-head/cells-8.csv new file mode 100644 index 00000000000..9322348e682 --- /dev/null +++ b/docs/receipts/flashnext-draft-head/cells-8.csv @@ -0,0 +1,73 @@ +arm,invocation,prompt,temperature,seed,streams,aggregate_tps,per_stream_tps,tokens_per_round,accepted_per_round,server_accepted,server_drafted,server_acceptance,failed,unmeasured +M1,conc_t0,code,0.0,,1,73.4,73.4,5.224,4.224,14264,20808,0.6855,0,0 +M1,conc_t0,code,0.0,,4,245.9,63.2,4.83,3.83,14264,20808,0.6855,0,0 +M1,conc_t0,code,0.0,,8,375.9,49.4,4.491,3.491,14264,20808,0.6855,0,0 +M1,conc_t0,chat,0.0,,1,47.1,47.1,2.813,1.813,14264,20808,0.6855,0,0 +M1,conc_t0,chat,0.0,,4,157.4,39.9,2.51,1.51,14264,20808,0.6855,0,0 +M1,conc_t0,chat,0.0,,8,259.5,33.4,2.51,1.51,14264,20808,0.6855,0,0 +M1,conc_t1_s1234,code,1.0,1234,1,70.5,70.5,4.571,3.571,16053,22476,0.7142,0,0 +M1,conc_t1_s1234,code,1.0,1234,4,129.9,37.7,3.835,2.835,16053,22476,0.7142,0,0 +M1,conc_t1_s1234,code,1.0,1234,8,186.2,26.6,3.724,2.724,16053,22476,0.7142,0,0 +M1,conc_t1_s1234,chat,1.0,1234,1,44.8,44.8,2.393,1.393,16053,22476,0.7142,0,0 +M1,conc_t1_s1234,chat,1.0,1234,4,105.2,27.5,2.456,1.456,16053,22476,0.7142,0,0 +M1,conc_t1_s1234,chat,1.0,1234,8,149.2,19.6,2.427,1.427,16053,22476,0.7142,0,0 +U1,conc_t0,code,0.0,,1,84.7,84.7,5.447,4.447,14313,20064,0.7134,0,0 +U1,conc_t0,code,0.0,,4,265.4,68.6,4.83,3.83,14313,20064,0.7134,0,0 +U1,conc_t0,code,0.0,,8,404.5,53.4,4.491,3.491,14313,20064,0.7134,0,0 +U1,conc_t0,chat,0.0,,1,51.2,51.2,2.844,1.844,14313,20064,0.7134,0,0 +U1,conc_t0,chat,0.0,,4,169.7,43.0,2.535,1.535,14313,20064,0.7134,0,0 +U1,conc_t0,chat,0.0,,8,275.3,35.5,2.535,1.535,14313,20064,0.7134,0,0 +U1,conc_t1_s1234,code,1.0,1234,1,76.9,76.9,4.571,3.571,16023,22497,0.7122,0,0 +U1,conc_t1_s1234,code,1.0,1234,4,137.0,39.6,3.807,2.807,16023,22497,0.7122,0,0 +U1,conc_t1_s1234,code,1.0,1234,8,195.9,28.4,3.737,2.737,16023,22497,0.7122,0,0 +U1,conc_t1_s1234,chat,1.0,1234,1,47.4,47.4,2.349,1.349,16023,22497,0.7122,0,0 +U1,conc_t1_s1234,chat,1.0,1234,4,110.8,28.9,2.444,1.444,16023,22497,0.7122,0,0 +U1,conc_t1_s1234,chat,1.0,1234,8,155.5,20.5,2.412,1.412,16023,22497,0.7122,0,0 +X1,conc_t0,code,0.0,,1,72.7,72.7,5.224,4.224,14264,20808,0.6855,0,0 +X1,conc_t0,code,0.0,,4,242.3,62.2,4.83,3.83,14264,20808,0.6855,0,0 +X1,conc_t0,code,0.0,,8,371.0,48.7,4.491,3.491,14264,20808,0.6855,0,0 +X1,conc_t0,chat,0.0,,1,46.5,46.5,2.813,1.813,14264,20808,0.6855,0,0 +X1,conc_t0,chat,0.0,,4,156.1,39.6,2.51,1.51,14264,20808,0.6855,0,0 +X1,conc_t0,chat,0.0,,8,257.3,33.2,2.51,1.51,14264,20808,0.6855,0,0 +X1,conc_t1_s1234,code,1.0,1234,1,70.3,70.3,4.571,3.571,16053,22476,0.7142,0,0 +X1,conc_t1_s1234,code,1.0,1234,4,129.1,37.5,3.835,2.835,16053,22476,0.7142,0,0 +X1,conc_t1_s1234,code,1.0,1234,8,185.3,27.3,3.724,2.724,16053,22476,0.7142,0,0 +X1,conc_t1_s1234,chat,1.0,1234,1,44.6,44.6,2.393,1.393,16053,22476,0.7142,0,0 +X1,conc_t1_s1234,chat,1.0,1234,4,104.7,27.4,2.456,1.456,16053,22476,0.7142,0,0 +X1,conc_t1_s1234,chat,1.0,1234,8,148.4,19.4,2.427,1.427,16053,22476,0.7142,0,0 +M2,conc_t0,code,0.0,,1,72.4,72.4,5.224,4.224,14264,20808,0.6855,0,0 +M2,conc_t0,code,0.0,,4,241.9,62.2,4.83,3.83,14264,20808,0.6855,0,0 +M2,conc_t0,code,0.0,,8,371.7,48.9,4.491,3.491,14264,20808,0.6855,0,0 +M2,conc_t0,chat,0.0,,1,46.6,46.6,2.813,1.813,14264,20808,0.6855,0,0 +M2,conc_t0,chat,0.0,,4,155.8,39.5,2.51,1.51,14264,20808,0.6855,0,0 +M2,conc_t0,chat,0.0,,8,256.6,33.0,2.51,1.51,14264,20808,0.6855,0,0 +M2,conc_t1_s1234,code,1.0,1234,1,70.2,70.2,4.571,3.571,16053,22476,0.7142,0,0 +M2,conc_t1_s1234,code,1.0,1234,4,129.2,37.6,3.835,2.835,16053,22476,0.7142,0,0 +M2,conc_t1_s1234,code,1.0,1234,8,184.9,26.8,3.724,2.724,16053,22476,0.7142,0,0 +M2,conc_t1_s1234,chat,1.0,1234,1,44.5,44.5,2.393,1.393,16053,22476,0.7142,0,0 +M2,conc_t1_s1234,chat,1.0,1234,4,104.7,27.4,2.456,1.456,16053,22476,0.7142,0,0 +M2,conc_t1_s1234,chat,1.0,1234,8,148.6,19.4,2.427,1.427,16053,22476,0.7142,0,0 +X2,conc_t0,code,0.0,,1,72.7,72.7,5.224,4.224,14264,20808,0.6855,0,0 +X2,conc_t0,code,0.0,,4,244.6,62.6,4.83,3.83,14264,20808,0.6855,0,0 +X2,conc_t0,code,0.0,,8,374.1,49.2,4.491,3.491,14264,20808,0.6855,0,0 +X2,conc_t0,chat,0.0,,1,46.7,46.7,2.813,1.813,14264,20808,0.6855,0,0 +X2,conc_t0,chat,0.0,,4,156.6,39.7,2.51,1.51,14264,20808,0.6855,0,0 +X2,conc_t0,chat,0.0,,8,257.7,33.2,2.51,1.51,14264,20808,0.6855,0,0 +X2,conc_t1_s1234,code,1.0,1234,1,70.6,70.6,4.571,3.571,16053,22476,0.7142,0,0 +X2,conc_t1_s1234,code,1.0,1234,4,129.7,37.8,3.835,2.835,16053,22476,0.7142,0,0 +X2,conc_t1_s1234,code,1.0,1234,8,185.6,26.6,3.724,2.724,16053,22476,0.7142,0,0 +X2,conc_t1_s1234,chat,1.0,1234,1,44.7,44.7,2.393,1.393,16053,22476,0.7142,0,0 +X2,conc_t1_s1234,chat,1.0,1234,4,104.9,27.4,2.456,1.456,16053,22476,0.7142,0,0 +X2,conc_t1_s1234,chat,1.0,1234,8,148.9,19.4,2.427,1.427,16053,22476,0.7142,0,0 +U2,conc_t0,code,0.0,,1,85.0,85.0,5.447,4.447,14313,20064,0.7134,0,0 +U2,conc_t0,code,0.0,,4,266.3,68.4,4.83,3.83,14313,20064,0.7134,0,0 +U2,conc_t0,code,0.0,,8,406.1,53.5,4.491,3.491,14313,20064,0.7134,0,0 +U2,conc_t0,chat,0.0,,1,50.9,50.9,2.844,1.844,14313,20064,0.7134,0,0 +U2,conc_t0,chat,0.0,,4,169.0,42.9,2.535,1.535,14313,20064,0.7134,0,0 +U2,conc_t0,chat,0.0,,8,276.5,35.6,2.535,1.535,14313,20064,0.7134,0,0 +U2,conc_t1_s1234,code,1.0,1234,1,76.4,76.4,4.571,3.571,16023,22497,0.7122,0,0 +U2,conc_t1_s1234,code,1.0,1234,4,137.3,40.1,3.807,2.807,16023,22497,0.7122,0,0 +U2,conc_t1_s1234,code,1.0,1234,8,195.6,28.6,3.737,2.737,16023,22497,0.7122,0,0 +U2,conc_t1_s1234,chat,1.0,1234,1,47.4,47.4,2.349,1.349,16023,22497,0.7122,0,0 +U2,conc_t1_s1234,chat,1.0,1234,4,110.9,28.9,2.444,1.444,16023,22497,0.7122,0,0 +U2,conc_t1_s1234,chat,1.0,1234,8,155.3,20.5,2.412,1.412,16023,22497,0.7122,0,0 diff --git a/docs/receipts/flashnext-draft-head/cells.csv b/docs/receipts/flashnext-draft-head/cells.csv new file mode 100644 index 00000000000..5f8559ba0ba --- /dev/null +++ b/docs/receipts/flashnext-draft-head/cells.csv @@ -0,0 +1,169 @@ +arm,invocation,prompt,temperature,seed,streams,aggregate_tps,per_stream_tps,tokens_per_round,accepted_per_round,server_accepted,server_drafted,server_acceptance,failed,unmeasured +M1,openai_t0,fibonacci-raw,0.0,,1,72.36,72.36,5.224,4.224,1488,2384,0.6242,0,0 +M1,openai_t0,gpu-chat-no-think,0.0,,1,46.46,46.46,2.813,1.813,1488,2384,0.6242,0,0 +M1,openai_t1,fibonacci-raw,1.0,1234+rep,1,61.47,61.47,4.063,3.063,3468,5019,0.691,0,0 +M1,openai_t1,gpu-chat-no-think,1.0,1234+rep,1,44.14,44.14,2.56,1.56,3468,5019,0.691,0,0 +M1,conc_t0,code,0.0,,1,72.2,72.2,5.224,4.224,7934,11682,0.6792,0,0 +M1,conc_t0,code,0.0,,2,137.4,69.5,4.83,3.83,7934,11682,0.6792,0,0 +M1,conc_t0,code,0.0,,4,241.5,62.2,4.83,3.83,7934,11682,0.6792,0,0 +M1,conc_t0,chat,0.0,,1,46.3,46.3,2.813,1.813,7934,11682,0.6792,0,0 +M1,conc_t0,chat,0.0,,2,86.3,43.4,2.51,1.51,7934,11682,0.6792,0,0 +M1,conc_t0,chat,0.0,,4,155.7,39.5,2.51,1.51,7934,11682,0.6792,0,0 +M1,conc_t1_s1234,code,1.0,1234,1,69.7,69.7,4.571,3.571,8607,11917,0.7222,0,0 +M1,conc_t1_s1234,code,1.0,1234,2,88.1,51.0,3.765,2.765,8607,11917,0.7222,0,0 +M1,conc_t1_s1234,code,1.0,1234,4,128.5,37.1,3.835,2.835,8607,11917,0.7222,0,0 +M1,conc_t1_s1234,chat,1.0,1234,1,44.3,44.3,2.393,1.393,8607,11917,0.7222,0,0 +M1,conc_t1_s1234,chat,1.0,1234,2,69.5,36.2,2.45,1.45,8607,11917,0.7222,0,0 +M1,conc_t1_s1234,chat,1.0,1234,4,104.0,27.1,2.456,1.456,8607,11917,0.7222,0,0 +M1,conc_t1_s2234,code,1.0,2234,1,66.2,66.2,4.197,3.197,8689,12418,0.6997,0,0 +M1,conc_t1_s2234,code,1.0,2234,2,90.5,45.8,3.58,2.58,8689,12418,0.6997,0,0 +M1,conc_t1_s2234,code,1.0,2234,4,134.2,35.8,3.835,2.835,8689,12418,0.6997,0,0 +M1,conc_t1_s2234,chat,1.0,2234,1,44.8,44.8,2.586,1.586,8689,12418,0.6997,0,0 +M1,conc_t1_s2234,chat,1.0,2234,2,72.2,36.5,2.56,1.56,8689,12418,0.6997,0,0 +M1,conc_t1_s2234,chat,1.0,2234,4,106.6,27.3,2.547,1.547,8689,12418,0.6997,0,0 +M1,conc_t1_s3234,code,1.0,3234,1,60.1,60.1,3.606,2.606,8509,12375,0.6876,0,0 +M1,conc_t1_s3234,code,1.0,3234,2,89.6,45.9,3.631,2.631,8509,12375,0.6876,0,0 +M1,conc_t1_s3234,code,1.0,3234,4,123.1,33.5,3.751,2.751,8509,12375,0.6876,0,0 +M1,conc_t1_s3234,chat,1.0,3234,1,43.8,43.8,2.415,1.415,8509,12375,0.6876,0,0 +M1,conc_t1_s3234,chat,1.0,3234,2,68.2,34.9,2.415,1.415,8509,12375,0.6876,0,0 +M1,conc_t1_s3234,chat,1.0,3234,4,103.4,27.1,2.444,1.444,8509,12375,0.6876,0,0 +U1,openai_t0,fibonacci-raw,0.0,,1,84.11,84.11,5.447,4.447,1500,2384,0.6292,0,0 +U1,openai_t0,gpu-chat-no-think,0.0,,1,51.02,51.02,2.844,1.844,1500,2384,0.6292,0,0 +U1,openai_t1,fibonacci-raw,1.0,1234+rep,1,70.75,70.75,4.129,3.129,3461,5056,0.6845,0,0 +U1,openai_t1,gpu-chat-no-think,1.0,1234+rep,1,48.15,48.15,2.485,1.485,3461,5056,0.6845,0,0 +U1,conc_t0,code,0.0,,1,84.0,84.0,5.447,4.447,7965,11430,0.6969,0,0 +U1,conc_t0,code,0.0,,2,152.1,76.9,4.83,3.83,7965,11430,0.6969,0,0 +U1,conc_t0,code,0.0,,4,264.2,68.0,4.83,3.83,7965,11430,0.6969,0,0 +U1,conc_t0,chat,0.0,,1,50.8,50.8,2.844,1.844,7965,11430,0.6969,0,0 +U1,conc_t0,chat,0.0,,2,94.2,47.2,2.535,1.535,7965,11430,0.6969,0,0 +U1,conc_t0,chat,0.0,,4,168.3,42.8,2.535,1.535,7965,11430,0.6969,0,0 +U1,conc_t1_s1234,code,1.0,1234,1,76.3,76.3,4.571,3.571,8573,11992,0.7149,0,0 +U1,conc_t1_s1234,code,1.0,1234,2,93.9,54.0,3.71,2.71,8573,11992,0.7149,0,0 +U1,conc_t1_s1234,code,1.0,1234,4,136.4,39.8,3.807,2.807,8573,11992,0.7149,0,0 +U1,conc_t1_s1234,chat,1.0,1234,1,46.9,46.9,2.349,1.349,8573,11992,0.7149,0,0 +U1,conc_t1_s1234,chat,1.0,1234,2,74.6,39.0,2.438,1.438,8573,11992,0.7149,0,0 +U1,conc_t1_s1234,chat,1.0,1234,4,110.1,28.9,2.444,1.444,8573,11992,0.7149,0,0 +U1,conc_t1_s2234,code,1.0,2234,1,71.0,71.0,4.063,3.063,8585,12660,0.6781,0,0 +U1,conc_t1_s2234,code,1.0,2234,2,97.3,49.2,3.58,2.58,8585,12660,0.6781,0,0 +U1,conc_t1_s2234,code,1.0,2234,4,143.9,38.6,3.821,2.821,8585,12660,0.6781,0,0 +U1,conc_t1_s2234,chat,1.0,2234,1,46.9,46.9,2.485,1.485,8585,12660,0.6781,0,0 +U1,conc_t1_s2234,chat,1.0,2234,2,75.1,37.8,2.45,1.45,8585,12660,0.6781,0,0 +U1,conc_t1_s2234,chat,1.0,2234,4,111.2,28.2,2.473,1.473,8585,12660,0.6781,0,0 +U1,conc_t1_s3234,code,1.0,3234,1,67.7,67.7,3.71,2.71,8515,12231,0.6962,0,0 +U1,conc_t1_s3234,code,1.0,3234,2,98.1,49.6,3.606,2.606,8515,12231,0.6962,0,0 +U1,conc_t1_s3234,code,1.0,3234,4,132.9,35.9,3.724,2.724,8515,12231,0.6962,0,0 +U1,conc_t1_s3234,chat,1.0,3234,1,47.4,47.4,2.415,1.415,8515,12231,0.6962,0,0 +U1,conc_t1_s3234,chat,1.0,3234,2,73.9,38.0,2.427,1.427,8515,12231,0.6962,0,0 +U1,conc_t1_s3234,chat,1.0,3234,4,110.3,28.7,2.444,1.444,8515,12231,0.6962,0,0 +X1,openai_t0,fibonacci-raw,0.0,,1,72.44,72.44,5.224,4.224,1488,2384,0.6242,0,0 +X1,openai_t0,gpu-chat-no-think,0.0,,1,46.37,46.37,2.813,1.813,1488,2384,0.6242,0,0 +X1,openai_t1,fibonacci-raw,1.0,1234+rep,1,64.39,64.39,4.063,3.063,3468,5019,0.691,0,0 +X1,openai_t1,gpu-chat-no-think,1.0,1234+rep,1,45.82,45.82,2.56,1.56,3468,5019,0.691,0,0 +X1,conc_t0,code,0.0,,1,72.3,72.3,5.224,4.224,7934,11682,0.6792,0,0 +X1,conc_t0,code,0.0,,2,137.7,69.7,4.83,3.83,7934,11682,0.6792,0,0 +X1,conc_t0,code,0.0,,4,242.3,62.3,4.83,3.83,7934,11682,0.6792,0,0 +X1,conc_t0,chat,0.0,,1,46.5,46.5,2.813,1.813,7934,11682,0.6792,0,0 +X1,conc_t0,chat,0.0,,2,86.3,43.5,2.51,1.51,7934,11682,0.6792,0,0 +X1,conc_t0,chat,0.0,,4,155.2,39.5,2.51,1.51,7934,11682,0.6792,0,0 +X1,conc_t1_s1234,code,1.0,1234,1,70.1,70.1,4.571,3.571,8607,11917,0.7222,0,0 +X1,conc_t1_s1234,code,1.0,1234,2,88.4,51.1,3.765,2.765,8607,11917,0.7222,0,0 +X1,conc_t1_s1234,code,1.0,1234,4,128.9,37.2,3.835,2.835,8607,11917,0.7222,0,0 +X1,conc_t1_s1234,chat,1.0,1234,1,44.4,44.4,2.393,1.393,8607,11917,0.7222,0,0 +X1,conc_t1_s1234,chat,1.0,1234,2,69.7,36.4,2.45,1.45,8607,11917,0.7222,0,0 +X1,conc_t1_s1234,chat,1.0,1234,4,104.4,27.1,2.456,1.456,8607,11917,0.7222,0,0 +X1,conc_t1_s2234,code,1.0,2234,1,66.2,66.2,4.197,3.197,8689,12418,0.6997,0,0 +X1,conc_t1_s2234,code,1.0,2234,2,91.0,46.0,3.58,2.58,8689,12418,0.6997,0,0 +X1,conc_t1_s2234,code,1.0,2234,4,134.6,36.0,3.835,2.835,8689,12418,0.6997,0,0 +X1,conc_t1_s2234,chat,1.0,2234,1,44.8,44.8,2.586,1.586,8689,12418,0.6997,0,0 +X1,conc_t1_s2234,chat,1.0,2234,2,72.5,36.7,2.56,1.56,8689,12418,0.6997,0,0 +X1,conc_t1_s2234,chat,1.0,2234,4,107.2,27.4,2.547,1.547,8689,12418,0.6997,0,0 +X1,conc_t1_s3234,code,1.0,3234,1,60.3,60.3,3.606,2.606,8509,12375,0.6876,0,0 +X1,conc_t1_s3234,code,1.0,3234,2,89.9,46.0,3.631,2.631,8509,12375,0.6876,0,0 +X1,conc_t1_s3234,code,1.0,3234,4,123.6,34.0,3.751,2.751,8509,12375,0.6876,0,0 +X1,conc_t1_s3234,chat,1.0,3234,1,44.1,44.1,2.415,1.415,8509,12375,0.6876,0,0 +X1,conc_t1_s3234,chat,1.0,3234,2,68.5,35.1,2.415,1.415,8509,12375,0.6876,0,0 +X1,conc_t1_s3234,chat,1.0,3234,4,103.8,27.1,2.444,1.444,8509,12375,0.6876,0,0 +M2,openai_t0,fibonacci-raw,0.0,,1,72.55,72.55,5.224,4.224,1488,2384,0.6242,0,0 +M2,openai_t0,gpu-chat-no-think,0.0,,1,46.66,46.66,2.813,1.813,1488,2384,0.6242,0,0 +M2,openai_t1,fibonacci-raw,1.0,1234+rep,1,64.7,64.7,4.063,3.063,3468,5019,0.691,0,0 +M2,openai_t1,gpu-chat-no-think,1.0,1234+rep,1,46.08,46.08,2.56,1.56,3468,5019,0.691,0,0 +M2,conc_t0,code,0.0,,1,72.7,72.7,5.224,4.224,7934,11682,0.6792,0,0 +M2,conc_t0,code,0.0,,2,137.8,69.6,4.83,3.83,7934,11682,0.6792,0,0 +M2,conc_t0,code,0.0,,4,241.6,62.1,4.83,3.83,7934,11682,0.6792,0,0 +M2,conc_t0,chat,0.0,,1,46.7,46.7,2.813,1.813,7934,11682,0.6792,0,0 +M2,conc_t0,chat,0.0,,2,86.8,43.6,2.51,1.51,7934,11682,0.6792,0,0 +M2,conc_t0,chat,0.0,,4,156.3,39.6,2.51,1.51,7934,11682,0.6792,0,0 +M2,conc_t1_s1234,code,1.0,1234,1,70.3,70.3,4.571,3.571,8607,11917,0.7222,0,0 +M2,conc_t1_s1234,code,1.0,1234,2,88.6,51.0,3.765,2.765,8607,11917,0.7222,0,0 +M2,conc_t1_s1234,code,1.0,1234,4,129.0,37.2,3.835,2.835,8607,11917,0.7222,0,0 +M2,conc_t1_s1234,chat,1.0,1234,1,44.7,44.7,2.393,1.393,8607,11917,0.7222,0,0 +M2,conc_t1_s1234,chat,1.0,1234,2,69.8,36.4,2.45,1.45,8607,11917,0.7222,0,0 +M2,conc_t1_s1234,chat,1.0,1234,4,104.4,27.2,2.456,1.456,8607,11917,0.7222,0,0 +M2,conc_t1_s2234,code,1.0,2234,1,66.5,66.5,4.197,3.197,8689,12418,0.6997,0,0 +M2,conc_t1_s2234,code,1.0,2234,2,91.2,46.0,3.58,2.58,8689,12418,0.6997,0,0 +M2,conc_t1_s2234,code,1.0,2234,4,134.8,36.0,3.835,2.835,8689,12418,0.6997,0,0 +M2,conc_t1_s2234,chat,1.0,2234,1,45.1,45.1,2.586,1.586,8689,12418,0.6997,0,0 +M2,conc_t1_s2234,chat,1.0,2234,2,72.6,36.8,2.56,1.56,8689,12418,0.6997,0,0 +M2,conc_t1_s2234,chat,1.0,2234,4,107.3,27.4,2.547,1.547,8689,12418,0.6997,0,0 +M2,conc_t1_s3234,code,1.0,3234,1,60.5,60.5,3.606,2.606,8509,12375,0.6876,0,0 +M2,conc_t1_s3234,code,1.0,3234,2,90.0,46.1,3.631,2.631,8509,12375,0.6876,0,0 +M2,conc_t1_s3234,code,1.0,3234,4,123.7,34.0,3.751,2.751,8509,12375,0.6876,0,0 +M2,conc_t1_s3234,chat,1.0,3234,1,44.2,44.2,2.415,1.415,8509,12375,0.6876,0,0 +M2,conc_t1_s3234,chat,1.0,3234,2,68.8,35.3,2.415,1.415,8509,12375,0.6876,0,0 +M2,conc_t1_s3234,chat,1.0,3234,4,104.0,27.1,2.444,1.444,8509,12375,0.6876,0,0 +X2,openai_t0,fibonacci-raw,0.0,,1,72.25,72.25,5.224,4.224,1488,2384,0.6242,0,0 +X2,openai_t0,gpu-chat-no-think,0.0,,1,46.3,46.3,2.813,1.813,1488,2384,0.6242,0,0 +X2,openai_t1,fibonacci-raw,1.0,1234+rep,1,64.04,64.04,4.063,3.063,3468,5019,0.691,0,0 +X2,openai_t1,gpu-chat-no-think,1.0,1234+rep,1,45.82,45.82,2.56,1.56,3468,5019,0.691,0,0 +X2,conc_t0,code,0.0,,1,72.3,72.3,5.224,4.224,7934,11682,0.6792,0,0 +X2,conc_t0,code,0.0,,2,137.6,69.4,4.83,3.83,7934,11682,0.6792,0,0 +X2,conc_t0,code,0.0,,4,242.2,62.1,4.83,3.83,7934,11682,0.6792,0,0 +X2,conc_t0,chat,0.0,,1,46.5,46.5,2.813,1.813,7934,11682,0.6792,0,0 +X2,conc_t0,chat,0.0,,2,86.4,43.4,2.51,1.51,7934,11682,0.6792,0,0 +X2,conc_t0,chat,0.0,,4,155.7,39.5,2.51,1.51,7934,11682,0.6792,0,0 +X2,conc_t1_s1234,code,1.0,1234,1,69.8,69.8,4.571,3.571,8607,11917,0.7222,0,0 +X2,conc_t1_s1234,code,1.0,1234,2,88.2,50.9,3.765,2.765,8607,11917,0.7222,0,0 +X2,conc_t1_s1234,code,1.0,1234,4,128.7,37.4,3.835,2.835,8607,11917,0.7222,0,0 +X2,conc_t1_s1234,chat,1.0,1234,1,44.5,44.5,2.393,1.393,8607,11917,0.7222,0,0 +X2,conc_t1_s1234,chat,1.0,1234,2,69.8,36.4,2.45,1.45,8607,11917,0.7222,0,0 +X2,conc_t1_s1234,chat,1.0,1234,4,104.1,27.1,2.456,1.456,8607,11917,0.7222,0,0 +X2,conc_t1_s2234,code,1.0,2234,1,66.2,66.2,4.197,3.197,8689,12418,0.6997,0,0 +X2,conc_t1_s2234,code,1.0,2234,2,90.7,45.8,3.58,2.58,8689,12418,0.6997,0,0 +X2,conc_t1_s2234,code,1.0,2234,4,134.5,36.0,3.835,2.835,8689,12418,0.6997,0,0 +X2,conc_t1_s2234,chat,1.0,2234,1,44.7,44.7,2.586,1.586,8689,12418,0.6997,0,0 +X2,conc_t1_s2234,chat,1.0,2234,2,72.4,36.6,2.56,1.56,8689,12418,0.6997,0,0 +X2,conc_t1_s2234,chat,1.0,2234,4,107.1,27.4,2.547,1.547,8689,12418,0.6997,0,0 +X2,conc_t1_s3234,code,1.0,3234,1,60.2,60.2,3.606,2.606,8509,12375,0.6876,0,0 +X2,conc_t1_s3234,code,1.0,3234,2,89.8,45.9,3.631,2.631,8509,12375,0.6876,0,0 +X2,conc_t1_s3234,code,1.0,3234,4,123.4,33.7,3.751,2.751,8509,12375,0.6876,0,0 +X2,conc_t1_s3234,chat,1.0,3234,1,44.0,44.0,2.415,1.415,8509,12375,0.6876,0,0 +X2,conc_t1_s3234,chat,1.0,3234,2,68.5,35.0,2.415,1.415,8509,12375,0.6876,0,0 +X2,conc_t1_s3234,chat,1.0,3234,4,103.8,27.0,2.444,1.444,8509,12375,0.6876,0,0 +U2,openai_t0,fibonacci-raw,0.0,,1,84.63,84.63,5.447,4.447,1500,2384,0.6292,0,0 +U2,openai_t0,gpu-chat-no-think,0.0,,1,51.01,51.01,2.844,1.844,1500,2384,0.6292,0,0 +U2,openai_t1,fibonacci-raw,1.0,1234+rep,1,71.2,71.2,4.129,3.129,3461,5056,0.6845,0,0 +U2,openai_t1,gpu-chat-no-think,1.0,1234+rep,1,48.35,48.35,2.485,1.485,3461,5056,0.6845,0,0 +U2,conc_t0,code,0.0,,1,84.0,84.0,5.447,4.447,7965,11430,0.6969,0,0 +U2,conc_t0,code,0.0,,2,152.0,77.0,4.83,3.83,7965,11430,0.6969,0,0 +U2,conc_t0,code,0.0,,4,263.9,68.0,4.83,3.83,7965,11430,0.6969,0,0 +U2,conc_t0,chat,0.0,,1,51.0,51.0,2.844,1.844,7965,11430,0.6969,0,0 +U2,conc_t0,chat,0.0,,2,94.2,47.4,2.535,1.535,7965,11430,0.6969,0,0 +U2,conc_t0,chat,0.0,,4,168.7,42.8,2.535,1.535,7965,11430,0.6969,0,0 +U2,conc_t1_s1234,code,1.0,1234,1,76.2,76.2,4.571,3.571,8573,11992,0.7149,0,0 +U2,conc_t1_s1234,code,1.0,1234,2,94.2,54.0,3.71,2.71,8573,11992,0.7149,0,0 +U2,conc_t1_s1234,code,1.0,1234,4,136.4,39.6,3.807,2.807,8573,11992,0.7149,0,0 +U2,conc_t1_s1234,chat,1.0,1234,1,47.2,47.2,2.349,1.349,8573,11992,0.7149,0,0 +U2,conc_t1_s1234,chat,1.0,1234,2,74.8,39.1,2.438,1.438,8573,11992,0.7149,0,0 +U2,conc_t1_s1234,chat,1.0,1234,4,110.4,28.9,2.444,1.444,8573,11992,0.7149,0,0 +U2,conc_t1_s2234,code,1.0,2234,1,71.0,71.0,4.063,3.063,8585,12660,0.6781,0,0 +U2,conc_t1_s2234,code,1.0,2234,2,97.3,49.8,3.58,2.58,8585,12660,0.6781,0,0 +U2,conc_t1_s2234,code,1.0,2234,4,143.9,38.7,3.821,2.821,8585,12660,0.6781,0,0 +U2,conc_t1_s2234,chat,1.0,2234,1,47.1,47.1,2.485,1.485,8585,12660,0.6781,0,0 +U2,conc_t1_s2234,chat,1.0,2234,2,75.0,37.8,2.45,1.45,8585,12660,0.6781,0,0 +U2,conc_t1_s2234,chat,1.0,2234,4,111.4,28.2,2.473,1.473,8585,12660,0.6781,0,0 +U2,conc_t1_s3234,code,1.0,3234,1,67.6,67.6,3.71,2.71,8515,12231,0.6962,0,0 +U2,conc_t1_s3234,code,1.0,3234,2,98.0,49.9,3.606,2.606,8515,12231,0.6962,0,0 +U2,conc_t1_s3234,code,1.0,3234,4,133.1,35.9,3.724,2.724,8515,12231,0.6962,0,0 +U2,conc_t1_s3234,chat,1.0,3234,1,47.6,47.6,2.415,1.415,8515,12231,0.6962,0,0 +U2,conc_t1_s3234,chat,1.0,3234,2,74.3,38.1,2.427,1.427,8515,12231,0.6962,0,0 +U2,conc_t1_s3234,chat,1.0,3234,4,110.4,28.8,2.444,1.444,8515,12231,0.6962,0,0 diff --git a/docs/receipts/flashnext-draft-head/exactness.md b/docs/receipts/flashnext-draft-head/exactness.md new file mode 100644 index 00000000000..0f1af412649 --- /dev/null +++ b/docs/receipts/flashnext-draft-head/exactness.md @@ -0,0 +1,29 @@ +| check | measure | main | PR, unset | PR, bf16 | +|---|---|---|---|---| +| 1 | bench_concurrent --serial, code+chat, greedy | 2/2 equal (token_sha256, [256] tok) | 2/2 equal (token_sha256, [256] tok) | 2/2 equal (token_sha256, [256] tok) | +| 1 | bench_concurrent --serial, code+chat, temperature 1.0 | 8/8 equal (token_sha256, [256] tok) | 8/8 equal (token_sha256, [256] tok) | 8/8 equal (token_sha256, [256] tok) | +| 1 | bench_concurrent --serial, six golden, greedy | 6/6 equal (token_sha256, [256] tok) | 6/6 equal (token_sha256, [256] tok) | 6/6 equal (token_sha256, [256] tok) | +| 1 | served_exactness drafts, 8 prompts, cache on | 8/8 equal (token_ids, [256] tok); accepted 13-237 a reply, plain drafted ['0'] | 8/8 equal (token_ids, [256] tok); accepted 12-237 a reply, plain drafted ['0'] | 8/8 equal (token_ids, [256] tok); accepted 13-237 a reply, plain drafted ['0'] | +| 1 | served_exactness drafts, 8 prompts, cache off | 8/8 equal (token_ids, [256] tok); accepted 13-237 a reply, plain drafted ['0'] | 8/8 equal (token_ids, [256] tok); accepted 12-237 a reply, plain drafted ['0'] | 8/8 equal (token_ids, [256] tok); accepted 13-237 a reply, plain drafted ['0'] | +| 1 | serve_check drafted == serial (greedy, t0.8), cache off | 2/2 ok | 2/2 ok | 2/2 ok | +| 2 | served_exactness turns (on) against fresh (off), 5 chats | 7/7 equal (token_ids, [14, 43, 25, 70, 256, 120, 12] tok); resumed from [13, 16, 16, 13, 24, 18, 3406] of [112, 84, 99, 208, 306, 25, 3459] prompt tokens; fresh cached [0] | 7/7 equal (token_ids, [14, 43, 25, 70, 256, 120, 12] tok); resumed from [13, 16, 16, 13, 24, 18, 3406] of [112, 84, 99, 208, 306, 25, 3459] prompt tokens; fresh cached [0] | 7/7 equal (token_ids, [14, 43, 25, 70, 256, 120, 12] tok); resumed from [13, 16, 16, 13, 24, 18, 3406] of [112, 84, 99, 208, 306, 25, 3459] prompt tokens; fresh cached [0] | +| 2 | bench_cache repeated/concurrent == first, cache on | 4 equal, 0 unequal, 0 unverified; states {'cold': 1, 'reused': 3}; cached [0, 2570, 2570, 2570]; {'qualified': True} | 4 equal, 0 unequal, 0 unverified; states {'cold': 1, 'reused': 3}; cached [0, 2570, 2570, 2570]; {'qualified': True} | 4 equal, 0 unequal, 0 unverified; states {'cold': 1, 'reused': 3}; cached [0, 2570, 2570, 2570]; {'qualified': True} | +| 3 | bench_concurrent --alone, identical code+chat, 1/2/4, greedy | 42/42 equal, 0 failed requests | 42/42 equal, 0 failed requests | 42/42 equal, 0 failed requests | +| 3 | bench_concurrent --alone, code+chat, 1/2/4, temperature 1.0 | 42/42 equal, 0 failed requests | 42/42 equal, 0 failed requests | 42/42 equal, 0 failed requests | +| 3 | bench_concurrent --alone, six golden distinct, 1/2/4/6, greedy | 13/13 equal, 0 failed requests | 13/13 equal, 0 failed requests | 13/13 equal, 0 failed requests | +| 3 | serve_check together/among-decoders/twice, cache off | 12/12 ok | 12/12 ok | 12/12 ok | + +| check | main | PR, unset | PR, bf16 | +|---|---|---|---| +| drafted == draft:false | PASS | PASS | PASS | +| resumed == fresh | PASS | PASS | PASS | +| concurrent == solo | PASS | PASS | PASS | + +Replies against main's (same request, same boot kind): +- pr-default: conc alone+serial hashes 16/16; gold alone+serial hashes 6/6; d_on plain token ids 8/8; d_off plain token ids 8/8; turn first token ids 7/7; turn resumed token ids 7/7 +- pr-bf16: conc alone+serial hashes 16/16; gold alone+serial hashes 6/6; d_on plain token ids 8/8; d_off plain token ids 8/8; turn first token ids 7/7; turn resumed token ids 7/7 + +serve_check lines (cache off; its resumed == fresh line compares two cold requests on that server): +- main: 15 ok, 0 FAIL [] +- pr-default: 15 ok, 0 FAIL [] +- pr-bf16: 15 ok, 0 FAIL [] diff --git a/docs/receipts/flashnext-draft-head/rule5-8.md b/docs/receipts/flashnext-draft-head/rule5-8.md new file mode 100644 index 00000000000..34547a9a6ed --- /dev/null +++ b/docs/receipts/flashnext-draft-head/rule5-8.md @@ -0,0 +1,14 @@ +| invocation | prompt | temp | seed | streams | M1 | M2 | U1 | U2 | X1 | X2 | U vs main | X vs main | tokens a round M / U / X | +|---|---|---|---|---|---|---|---|---|---|---|---|---|---| +| conc_t0 | chat | 0.0 | | 1 | 47.1 | 46.6 | 51.2 | 50.9 | 46.5 | 46.7 | +9.0% faster | -0.5% level | 2.81 / 2.84 / 2.81 | +| conc_t0 | chat | 0.0 | | 4 | 157.4 | 155.8 | 169.7 | 169.0 | 156.1 | 156.6 | +8.1% faster | -0.2% level | 2.51 / 2.54 / 2.51 | +| conc_t0 | chat | 0.0 | | 8 | 259.5 | 256.6 | 275.3 | 276.5 | 257.3 | 257.7 | +6.9% faster | -0.2% level | 2.51 / 2.54 / 2.51 | +| conc_t0 | code | 0.0 | | 1 | 73.4 | 72.4 | 84.7 | 85.0 | 72.7 | 72.7 | +16.4% faster | -0.3% level | 5.22 / 5.45 / 5.22 | +| conc_t0 | code | 0.0 | | 4 | 245.9 | 241.9 | 265.4 | 266.3 | 242.3 | 244.6 | +9.0% faster | -0.2% level | 4.83 / 4.83 / 4.83 | +| conc_t0 | code | 0.0 | | 8 | 375.9 | 371.7 | 404.5 | 406.1 | 371.0 | 374.1 | +8.4% faster | -0.3% level | 4.49 / 4.49 / 4.49 | +| conc_t1_s1234 | chat | 1.0 | 1234 | 1 | 44.8 | 44.5 | 47.4 | 47.4 | 44.6 | 44.7 | +6.2% faster | +0.0% level | 2.39 / 2.35 / 2.39 | +| conc_t1_s1234 | chat | 1.0 | 1234 | 4 | 105.2 | 104.7 | 110.8 | 110.9 | 104.7 | 104.9 | +5.6% faster | -0.1% level | 2.46 / 2.44 / 2.46 | +| conc_t1_s1234 | chat | 1.0 | 1234 | 8 | 149.2 | 148.6 | 155.5 | 155.3 | 148.4 | 148.9 | +4.4% faster | -0.2% level | 2.43 / 2.41 / 2.43 | +| conc_t1_s1234 | code | 1.0 | 1234 | 1 | 70.5 | 70.2 | 76.9 | 76.4 | 70.3 | 70.6 | +9.0% faster | +0.1% level | 4.57 / 4.57 / 4.57 | +| conc_t1_s1234 | code | 1.0 | 1234 | 4 | 129.9 | 129.2 | 137.0 | 137.3 | 129.1 | 129.7 | +5.9% faster | -0.1% level | 3.83 / 3.81 / 3.83 | +| conc_t1_s1234 | code | 1.0 | 1234 | 8 | 186.2 | 184.9 | 195.9 | 195.6 | 185.3 | 185.6 | +5.5% faster | -0.1% level | 3.72 / 3.74 / 3.72 | diff --git a/docs/receipts/flashnext-draft-head/rule5.md b/docs/receipts/flashnext-draft-head/rule5.md new file mode 100644 index 00000000000..b3f401a5245 --- /dev/null +++ b/docs/receipts/flashnext-draft-head/rule5.md @@ -0,0 +1,30 @@ +| invocation | prompt | temp | seed | streams | M1 | M2 | U1 | U2 | X1 | X2 | U vs main | X vs main | tokens a round M / U / X | +|---|---|---|---|---|---|---|---|---|---|---|---|---|---| +| openai_t0 | fibonacci-raw | 0.0 | | 1 | 72.4 | 72.5 | 84.1 | 84.6 | 72.4 | 72.3 | +16.5% faster | -0.1% level | 5.22 / 5.45 / 5.22 | +| openai_t0 | gpu-chat-no-think | 0.0 | | 1 | 46.5 | 46.7 | 51.0 | 51.0 | 46.4 | 46.3 | +9.6% faster | -0.5% level | 2.81 / 2.84 / 2.81 | +| openai_t1 | fibonacci-raw | 1.0 | 1234+rep | 1 | 61.5 | 64.7 | 70.7 | 71.2 | 64.4 | 64.0 | +12.5% faster | +1.8% level | 4.06 / 4.13 / 4.06 | +| openai_t1 | gpu-chat-no-think | 1.0 | 1234+rep | 1 | 44.1 | 46.1 | 48.2 | 48.3 | 45.8 | 45.8 | +7.0% faster | +1.6% level | 2.56 / 2.48 / 2.56 | +| conc_t0 | chat | 0.0 | | 1 | 46.3 | 46.7 | 50.8 | 51.0 | 46.5 | 46.5 | +9.5% faster | +0.0% level | 2.81 / 2.84 / 2.81 | +| conc_t0 | chat | 0.0 | | 2 | 86.3 | 86.8 | 94.2 | 94.2 | 86.3 | 86.4 | +8.8% faster | -0.2% level | 2.51 / 2.54 / 2.51 | +| conc_t0 | chat | 0.0 | | 4 | 155.7 | 156.3 | 168.3 | 168.7 | 155.2 | 155.7 | +8.0% faster | -0.4% level | 2.51 / 2.54 / 2.51 | +| conc_t0 | code | 0.0 | | 1 | 72.2 | 72.7 | 84.0 | 84.0 | 72.3 | 72.3 | +15.9% faster | -0.2% level | 5.22 / 5.45 / 5.22 | +| conc_t0 | code | 0.0 | | 2 | 137.4 | 137.8 | 152.1 | 152.0 | 137.7 | 137.6 | +10.5% faster | +0.0% level | 4.83 / 4.83 / 4.83 | +| conc_t0 | code | 0.0 | | 4 | 241.5 | 241.6 | 264.2 | 263.9 | 242.3 | 242.2 | +9.3% faster | +0.3% level | 4.83 / 4.83 / 4.83 | +| conc_t1_s1234 | chat | 1.0 | 1234 | 1 | 44.3 | 44.7 | 46.9 | 47.2 | 44.4 | 44.5 | +5.7% faster | -0.1% level | 2.39 / 2.35 / 2.39 | +| conc_t1_s1234 | chat | 1.0 | 1234 | 2 | 69.5 | 69.8 | 74.6 | 74.8 | 69.7 | 69.8 | +7.3% faster | +0.1% level | 2.45 / 2.44 / 2.45 | +| conc_t1_s1234 | chat | 1.0 | 1234 | 4 | 104.0 | 104.4 | 110.1 | 110.4 | 104.4 | 104.1 | +5.8% faster | +0.0% level | 2.46 / 2.44 / 2.46 | +| conc_t1_s1234 | code | 1.0 | 1234 | 1 | 69.7 | 70.3 | 76.3 | 76.2 | 70.1 | 69.8 | +8.9% faster | -0.1% level | 4.57 / 4.57 / 4.57 | +| conc_t1_s1234 | code | 1.0 | 1234 | 2 | 88.1 | 88.6 | 93.9 | 94.2 | 88.4 | 88.2 | +6.5% faster | -0.1% level | 3.77 / 3.71 / 3.77 | +| conc_t1_s1234 | code | 1.0 | 1234 | 4 | 128.5 | 129.0 | 136.4 | 136.4 | 128.9 | 128.7 | +5.9% faster | +0.0% level | 3.83 / 3.81 / 3.83 | +| conc_t1_s2234 | chat | 1.0 | 2234 | 1 | 44.8 | 45.1 | 46.9 | 47.1 | 44.8 | 44.7 | +4.6% faster | -0.4% level | 2.59 / 2.48 / 2.59 | +| conc_t1_s2234 | chat | 1.0 | 2234 | 2 | 72.2 | 72.6 | 75.1 | 75.0 | 72.5 | 72.4 | +3.7% faster | +0.1% level | 2.56 / 2.45 / 2.56 | +| conc_t1_s2234 | chat | 1.0 | 2234 | 4 | 106.6 | 107.3 | 111.2 | 111.4 | 107.2 | 107.1 | +4.1% faster | +0.2% level | 2.55 / 2.47 / 2.55 | +| conc_t1_s2234 | code | 1.0 | 2234 | 1 | 66.2 | 66.5 | 71.0 | 71.0 | 66.2 | 66.2 | +7.0% faster | -0.2% level | 4.20 / 4.06 / 4.20 | +| conc_t1_s2234 | code | 1.0 | 2234 | 2 | 90.5 | 91.2 | 97.3 | 97.3 | 91.0 | 90.7 | +7.1% faster | +0.0% level | 3.58 / 3.58 / 3.58 | +| conc_t1_s2234 | code | 1.0 | 2234 | 4 | 134.2 | 134.8 | 143.9 | 143.9 | 134.6 | 134.5 | +7.0% faster | +0.0% level | 3.83 / 3.82 / 3.83 | +| conc_t1_s3234 | chat | 1.0 | 3234 | 1 | 43.8 | 44.2 | 47.4 | 47.6 | 44.1 | 44.0 | +8.0% faster | +0.1% level | 2.42 / 2.42 / 2.42 | +| conc_t1_s3234 | chat | 1.0 | 3234 | 2 | 68.2 | 68.8 | 73.9 | 74.3 | 68.5 | 68.5 | +8.2% faster | +0.0% level | 2.42 / 2.43 / 2.42 | +| conc_t1_s3234 | chat | 1.0 | 3234 | 4 | 103.4 | 104.0 | 110.3 | 110.4 | 103.8 | 103.8 | +6.4% faster | +0.1% level | 2.44 / 2.44 / 2.44 | +| conc_t1_s3234 | code | 1.0 | 3234 | 1 | 60.1 | 60.5 | 67.7 | 67.6 | 60.3 | 60.2 | +12.2% faster | -0.1% level | 3.61 / 3.71 / 3.61 | +| conc_t1_s3234 | code | 1.0 | 3234 | 2 | 89.6 | 90.0 | 98.1 | 98.0 | 89.9 | 89.8 | +9.2% faster | +0.1% level | 3.63 / 3.61 / 3.63 | +| conc_t1_s3234 | code | 1.0 | 3234 | 4 | 123.1 | 123.7 | 132.9 | 133.1 | 123.6 | 123.4 | +7.8% faster | +0.1% level | 3.75 / 3.72 / 3.75 | diff --git a/docs/receipts/qwen-unread-chunks-2941/README.md b/docs/receipts/qwen-unread-chunks-2941/README.md new file mode 100644 index 00000000000..904dd28e29b --- /dev/null +++ b/docs/receipts/qwen-unread-chunks-2941/README.md @@ -0,0 +1,120 @@ +# Qwen CUDA unread prompt chunks (#2941) + +A non-final prompt chunk whose rows nothing reads stops its last layer at its keys, values and their rotary rows. +This receipt covers the branch's exactness, sampled and drafted replies, the 8K and 16K prompt-cache marks and +cold prefill on one GB10. + +## Source and environment + +- Device binaries: base `0591c4e85dca440749063d171d4305d65a6edb50` and head `4a7a7f127`, one `zig build native + -Dsm=121 -Dnvcc=/usr/local/cuda/bin/nvcc` build an arm. Binary md5: base `6720d18b2b1d8875477d5520b95dc26c`, + head `fe92ed6a93d7ede5c7a6bb6fa42a3cff`. The prompt-cache state rows below were measured after the rebase, on + current main `f794b26a8` against the review head `5d1f494cfe`. +- One NVIDIA GB10 (sm_121), CUDA 13.0 (V13.0.88), Zig 0.17.0, Linux 7.0. +- Checkpoint `nvidia/Qwen3.6-35B-A3B-NVFP4`, revision `491c2f1ea524c639598bf8fa787a93fed5a6fbce`. +- Serve flags: `--parallel 1 --context 40960 --no-update-check --prompt-cache-gib 0` for cold, sampled and drafted + rows; `--prompt-cache-gib 4` for the resumed turns, and `--prompt-cache-disk` for the kept-state rows. The GB10 also + served an unrelated 86 GiB model, so cold TTFT is reported but is not a clean performance gate; exactness is the + gate. + +## Cold replies + +One request each at 2,048, 8,192 and 32,768 tokens, 16 greedy reply tokens, fresh server an arm. Base and head +`token_sha256`/`output_sha256` are equal at every length. The base arm was re-run with no build on the machine so +its TTFT is comparable to the head arm: + +| Prompt tokens | Base `token_sha256` / `output_sha256` | Head `token_sha256` / `output_sha256` | Base TTFT | Head TTFT | +| ---: | --- | --- | ---: | ---: | +| 2,048 | `0551b205…` / `4dfc61c7…` | `0551b205…` / `4dfc61c7…` | 0.344 s | 0.337 s | +| 8,192 | `eabb9ee4…` / `bfda9f68…` | `eabb9ee4…` / `bfda9f68…` | 1.282 s | 1.270 s | +| 32,768 | `bfdffc1b…` / `3e1bd53e…` | `bfdffc1b…` / `3e1bd53e…` | 6.006 s | 5.962 s | + +The full hashes are in `runs/base-cold.json` and `runs/head-cold.json`. The 32,768-token prompt cuts eight +4,096-row chunks; the seven non-final ones reported `unread=true` in the server log, with no tap, learning, MLP, +pocket, int8 or image reader. That log line came from a temporary `std.log.info` in `cuda_prefill.chunk` for the +run; the diff adds no log line. + +The prompts are the server tokenizer's output for Python 3.12.3's standard-library source; the raw arrays were +tokenized once per server start, so a different Python version changes the text but not the equality check. + +## Quiet-GB10 A/B (reported by @jschmied) + +A separate quiet-GB10 run, base `a3aecd8d0` against head `e7c385e96` (the same `zig/` diff as this head, apart from +hunk offsets), one fresh server an arm in base-head-head-base order, 3 rounds, SM clock capped at 2300 MHz, page +cache dropped before every server, 16 greedy tokens. Binary md5: base `1375faa01aeefc2f9ac40c907d6dab81`, head +`a479e68ff08992d57ff66f15faf52e3f`. Every `token_sha256`/`output_sha256` equals this receipt's: + +| Prompt | Base TTFT median [min-max] | Head TTFT median [min-max] | Paired head - base, per round | Adjacent pairs slower | +| ---: | ---: | ---: | --- | ---: | +| 2,048 | 0.3275 s [0.3238-0.3291] | 0.3259 s [0.3224-0.3272] | +1.8 / -4.5 / -2.7 ms | 3 of 6 | +| 8,192 | 1.2360 s [1.2353-1.2437] | 1.2328 s [1.2273-1.2356] | -3.1 / -9.9 / -1.5 ms | 0 of 6 | +| 32,768 | 5.8006 s [5.7908-5.8210] | 5.7695 s [5.7437-5.7825] | -28.4 / -61.8 / -23.0 ms | 0 of 6 | + +At 32K the median per-round delta is -28.4 ms and the median of the six adjacent pairs is -34.5 ms (-0.5 to +-0.6 %); 8K gains about 3-4 ms and 2K is level. The raw per-arm rows, gate output and server logs are with +@jschmied. + +## Sampled and drafted replies + +The same 8,192 and 32,768 token prompts at temperature 1.0 with seed 1234, then the same prompts with the server's +default draft mode; every base and head row has the same `token_sha256` and `output_sha256`: + +| Mode | 8,192 base / head | 32,768 base / head | +| --- | --- | --- | +| Sampled, T 1.0, seed 1234 | equal (`eabb9ee4…`) | equal (`bfdffc1b…`) | +| Drafted, default | equal (`eabb9ee4…`) | equal (`bfdffc1b…`) | + +Raw rows are in `runs/{base,head}-sampled.json` and `runs/{base,head}-drafted.json`. With the default drafter the +MTP tap on the last layer makes `unread` false, so these rows exercise the unchanged full path. + +## Prompt-cache marks + +A chat prompt is sent, then the same conversation with a question appended, on base and head with a 4 GiB prompt +cache. The 8K run resumes 8,192 tokens and the 16K run 16,384; every resumed reply is +`token_sha256 e1de42ac…` / `output_sha256 19079cfe…` on both arms. A cache-off run of the appended prompt has the +same reply, so the resumed path equals a fresh one. + +| First prompt | Resumed at | Base reply | Head reply | +| ---: | ---: | --- | --- | +| 9,352 tokens | 8,192 | `e1de42ac…` / `19079cfe…` | `e1de42ac…` / `19079cfe…` | +| 17,972 tokens | 16,384 | `e1de42ac…` / `19079cfe…` | `e1de42ac…` / `19079cfe…` | + +The runs are `runs/{base,head}-chat8k.json`, `runs/{base,head}-chat16k.json` and `runs/head-chat-fresh.json`. + +The kept states at those two marks were then compared on base `f794b26a8` (current main, binary md5 +`4f84a3a4c4fc72d7904cc5aa62b533f1`) against head `5d1f494cfe` (binary md5 +`b52e931eaa1e922f239d33f67564a877`), a fresh server an arm with `--prompt-cache-gib 4 --prompt-cache-disk`, and the +same commands. `states.py` reads the disk tier's `.st` file and every `.blk` file it names, and hashes payloads only: +the files' trailers carry the build's own block names. The recurrence and convolution state is the state file's +payload past its 16-byte position, shift and format words; the K/V digest covers each named block's payload. Both +arms are byte-equal: + +| Resumed at | Field | Base | Head | Files | +| ---: | --- | --- | --- | ---: | +| 8,192 | Recurrence + conv state | `4c17690b79f771208134c6065f760cfca7ba8ed63f983e510d89f64b74e962f9` | `4c17690b79f771208134c6065f760cfca7ba8ed63f983e510d89f64b74e962f9` | 1 state | +| 8,192 | K/V blocks | `c0d8a3685f8c0c142260be48766c2e56adeaf08fd43f3ef5899c006dee297d5f` | `c0d8a3685f8c0c142260be48766c2e56adeaf08fd43f3ef5899c006dee297d5f` | 32 blocks | +| 16,384 | Recurrence + conv state | `a849f8970ab05562bab42fb78ff4ee57ef08ec70dfbf13f084ca3cdb5bd642a2` | `a849f8970ab05562bab42fb78ff4ee57ef08ec70dfbf13f084ca3cdb5bd642a2` | 1 state | +| 16,384 | K/V blocks | `8909fc17c889bebe82313ae0ee39900acc2ed9ba386f2156aa5e958b873fecb4` | `8909fc17c889bebe82313ae0ee39900acc2ed9ba386f2156aa5e958b873fecb4` | 64 blocks | + +The same run reproduced the reply `token_sha256`/`output_sha256` rows above. The digests are in +`runs/{base,head}-marks.json`. + +## Commands + +```sh +BIN=zig-out/native/bin/tensorfold-native +G=docs/receipts/qwen-unread-chunks-2941 +$BIN serve nvidia/Qwen3.6-35B-A3B-NVFP4 --name gate --port 8081 --context 40960 --parallel 1 \ + --no-update-check --prompt-cache-gib 0 +python3 $G/gate.py cold http://127.0.0.1:8081 gate $G/runs/head-cold.json +python3 $G/gate.py sampled http://127.0.0.1:8081 gate $G/runs/head-sampled.json +python3 $G/gate.py drafted http://127.0.0.1:8081 gate $G/runs/head-drafted.json +# restart with --prompt-cache-gib 4 --prompt-cache-disk /tmp/states-head +python3 $G/gate.py chat8k http://127.0.0.1:8081 gate $G/runs/head-chat8k.json +python3 $G/gate.py chat16k http://127.0.0.1:8081 gate $G/runs/head-chat16k.json +python3 $G/states.py /tmp/states-head 8192 16384 > $G/runs/head-marks.json +``` + +`gate.py` sends the checkpoint's own tokenizer output through `tools/bench_concurrent.stream`, so each row is +the server's own `ttft_s`, cached-token count and token hashes. `states.py` reads the disk tier's kept states at a +mark and hashes the recurrence, convolution and K/V payloads. diff --git a/docs/receipts/qwen-unread-chunks-2941/gate.py b/docs/receipts/qwen-unread-chunks-2941/gate.py new file mode 100644 index 00000000000..2936c438bae --- /dev/null +++ b/docs/receipts/qwen-unread-chunks-2941/gate.py @@ -0,0 +1,75 @@ +"""Cold and resumed Qwen CUDA replies as token hashes, for an unread-prefill-chunk A/B.""" +import json +import os +import sys +import urllib.request +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[3] / "tools")) +import bench_concurrent as bench + +LENGTHS = (2048, 8192, 32768) + + +def tokenize(base, model): + text = "".join(open(os.path.join(os.path.dirname(os.__file__), n), encoding="utf-8", errors="replace").read() + for n in sorted(os.listdir(os.path.dirname(os.__file__))) if n.endswith(".py")) + body = json.dumps({"model": model, "prompt": text}).encode() + req = urllib.request.Request(base + "/v1/tokenize", data=body, headers={"Content-Type": "application/json"}) + with urllib.request.urlopen(req, timeout=300) as resp: + return json.loads(resp.read())["tokens"] + + +def request(base, model, name, prompt, tokens=16, temperature=0, seed=None, draft=False): + item = {"name": name, "kind": "completion", "prompt": prompt} + r = bench.stream(base, model, item, tokens, temperature, seed, draft=draft) + return {k: r.get(k) for k in ("prompt_tokens", "cached_tokens", "token_sha256", "output_sha256", "ttft_s", "error")} + + +def chat(base, model, name, prompt, tokens=16): + item = {"name": name, "kind": "chat", "prompt": prompt} + r = bench.stream(base, model, item, tokens, 0, None, draft=False) + return {k: r.get(k) for k in ("prompt_tokens", "cached_tokens", "token_sha256", "output_sha256", "ttft_s", "error")} + + +def main(): + mode, base, model, out = sys.argv[1:5] + ids = tokenize(base, model) + if mode == "cold": + rows = [] + for n in LENGTHS: + row = request(base, model, f"cold-{n}", ids[:n]) + row["length"] = n + rows.append(row) + print(json.dumps(row), flush=True) + json.dump(rows, open(out, "w"), indent=2) + elif mode == "sampled": + rows = [] + for n in (8192, 32768): + row = request(base, model, f"sampled-{n}", ids[:n], 16, 1.0, 1234) + row["length"] = n + rows.append(row) + print(json.dumps(row), flush=True) + json.dump(rows, open(out, "w"), indent=2) + elif mode == "drafted": + rows = [] + for n in (8192, 32768): + row = request(base, model, f"drafted-{n}", ids[:n], 16, draft=True) + row["length"] = n + rows.append(row) + print(json.dumps(row), flush=True) + json.dump(rows, open(out, "w"), indent=2) + elif mode in ("chat", "chat8k", "chat16k"): + chars = {"chat": 30000, "chat8k": 36000, "chat16k": 70000}[mode] + text = "".join(open(os.path.join(os.path.dirname(os.__file__), n), encoding="utf-8", errors="replace").read() + for n in sorted(os.listdir(os.path.dirname(os.__file__))) if n.endswith(".py"))[:chars] + first = chat(base, model, "prefix", "Explain this Python code in one sentence.\n\n" + text, 2) + second = chat(base, model, "resumed", "Explain this Python code in one sentence.\n\n" + text + "\n\nAnswer in one word.", 16) + print(json.dumps({"prefix": first, "resumed": second}), flush=True) + json.dump({"prefix": first, "resumed": second}, open(out, "w"), indent=2) + else: + raise SystemExit(f"mode must be cold, sampled, drafted, chat, chat8k or chat16k, not {mode}") + + +if __name__ == "__main__": + main() diff --git a/docs/receipts/qwen-unread-chunks-2941/runs/base-chat16k.json b/docs/receipts/qwen-unread-chunks-2941/runs/base-chat16k.json new file mode 100644 index 00000000000..62069c8ede2 --- /dev/null +++ b/docs/receipts/qwen-unread-chunks-2941/runs/base-chat16k.json @@ -0,0 +1,18 @@ +{ + "prefix": { + "prompt_tokens": 17972, + "cached_tokens": 8192, + "token_sha256": "45ea8c4a80ae3aef55655bed61df036b7563a343ba2ba4798a7b562c7f59ad28", + "output_sha256": "a88150b951e889af79158b6f953f746424f4c048f749ee71c948c32b0661af68", + "ttft_s": 1.821077258005971, + "error": null + }, + "resumed": { + "prompt_tokens": 17978, + "cached_tokens": 16384, + "token_sha256": "e1de42acf830e5ec3a2f43890ebe33a29f9a186ddc0ac95ae0ac34595641af76", + "output_sha256": "19079cfe1bf997fb44a8a928a10f2574b80865b1a20faa560d12369d98497ef7", + "ttft_s": 0.35697189799975604, + "error": null + } +} \ No newline at end of file diff --git a/docs/receipts/qwen-unread-chunks-2941/runs/base-chat8k.json b/docs/receipts/qwen-unread-chunks-2941/runs/base-chat8k.json new file mode 100644 index 00000000000..eb494c32942 --- /dev/null +++ b/docs/receipts/qwen-unread-chunks-2941/runs/base-chat8k.json @@ -0,0 +1,18 @@ +{ + "prefix": { + "prompt_tokens": 9352, + "cached_tokens": 0, + "token_sha256": "45ea8c4a80ae3aef55655bed61df036b7563a343ba2ba4798a7b562c7f59ad28", + "output_sha256": "a88150b951e889af79158b6f953f746424f4c048f749ee71c948c32b0661af68", + "ttft_s": 1.5748464240168687, + "error": null + }, + "resumed": { + "prompt_tokens": 9358, + "cached_tokens": 8192, + "token_sha256": "e1de42acf830e5ec3a2f43890ebe33a29f9a186ddc0ac95ae0ac34595641af76", + "output_sha256": "19079cfe1bf997fb44a8a928a10f2574b80865b1a20faa560d12369d98497ef7", + "ttft_s": 0.2634730660065543, + "error": null + } +} \ No newline at end of file diff --git a/docs/receipts/qwen-unread-chunks-2941/runs/base-cold.json b/docs/receipts/qwen-unread-chunks-2941/runs/base-cold.json new file mode 100644 index 00000000000..a976cb8acea --- /dev/null +++ b/docs/receipts/qwen-unread-chunks-2941/runs/base-cold.json @@ -0,0 +1,29 @@ +[ + { + "prompt_tokens": 2048, + "cached_tokens": 0, + "token_sha256": "0551b205acb27d6e538b91b0cf5664c7de0ebe74f51ffcf323a1b598a8612d6b", + "output_sha256": "4dfc61c7c56afa657e8d6f0ec17dcee7cbd5d10120d5842982bc80ab9b1c5a6a", + "ttft_s": 0.34365210399846546, + "error": null, + "length": 2048 + }, + { + "prompt_tokens": 8192, + "cached_tokens": 0, + "token_sha256": "eabb9ee47126ea56d086699c051f993c9578286e7c7f5fcf62c8782225706828", + "output_sha256": "bfda9f689c88a5004b7d32e325e391984d27b4528088f66a62348dbb4b9f63f1", + "ttft_s": 1.2816720829869155, + "error": null, + "length": 8192 + }, + { + "prompt_tokens": 32768, + "cached_tokens": 0, + "token_sha256": "bfdffc1b07cf64389fcfbbf4787d66ae1129eab9b716182e6d9b27aa0b80ff84", + "output_sha256": "3e1bd53ec06abd9b91c90f32f037c0ff187ee2eefeba47425ff757c9c74424b5", + "ttft_s": 6.006065038003726, + "error": null, + "length": 32768 + } +] \ No newline at end of file diff --git a/docs/receipts/qwen-unread-chunks-2941/runs/base-drafted.json b/docs/receipts/qwen-unread-chunks-2941/runs/base-drafted.json new file mode 100644 index 00000000000..931df1b8388 --- /dev/null +++ b/docs/receipts/qwen-unread-chunks-2941/runs/base-drafted.json @@ -0,0 +1,20 @@ +[ + { + "prompt_tokens": 8192, + "cached_tokens": 0, + "token_sha256": "eabb9ee47126ea56d086699c051f993c9578286e7c7f5fcf62c8782225706828", + "output_sha256": "bfda9f689c88a5004b7d32e325e391984d27b4528088f66a62348dbb4b9f63f1", + "ttft_s": 1.2752266759925988, + "error": null, + "length": 8192 + }, + { + "prompt_tokens": 32768, + "cached_tokens": 0, + "token_sha256": "bfdffc1b07cf64389fcfbbf4787d66ae1129eab9b716182e6d9b27aa0b80ff84", + "output_sha256": "3e1bd53ec06abd9b91c90f32f037c0ff187ee2eefeba47425ff757c9c74424b5", + "ttft_s": 5.998814410995692, + "error": null, + "length": 32768 + } +] \ No newline at end of file diff --git a/docs/receipts/qwen-unread-chunks-2941/runs/base-marks.json b/docs/receipts/qwen-unread-chunks-2941/runs/base-marks.json new file mode 100644 index 00000000000..375626bd8ba --- /dev/null +++ b/docs/receipts/qwen-unread-chunks-2941/runs/base-marks.json @@ -0,0 +1,18 @@ +{ + "8192": [ + { + "state": "1d57033358c022a06118be4c0d4c0399", + "blocks": 32, + "state_sha256": "4c17690b79f771208134c6065f760cfca7ba8ed63f983e510d89f64b74e962f9", + "kv_sha256": "c0d8a3685f8c0c142260be48766c2e56adeaf08fd43f3ef5899c006dee297d5f" + } + ], + "16384": [ + { + "state": "913fd95a4c9bec5d1e8f60218217a118", + "blocks": 64, + "state_sha256": "a849f8970ab05562bab42fb78ff4ee57ef08ec70dfbf13f084ca3cdb5bd642a2", + "kv_sha256": "8909fc17c889bebe82313ae0ee39900acc2ed9ba386f2156aa5e958b873fecb4" + } + ] +} diff --git a/docs/receipts/qwen-unread-chunks-2941/runs/base-sampled.json b/docs/receipts/qwen-unread-chunks-2941/runs/base-sampled.json new file mode 100644 index 00000000000..9fdf100aa42 --- /dev/null +++ b/docs/receipts/qwen-unread-chunks-2941/runs/base-sampled.json @@ -0,0 +1,20 @@ +[ + { + "prompt_tokens": 8192, + "cached_tokens": 0, + "token_sha256": "eabb9ee47126ea56d086699c051f993c9578286e7c7f5fcf62c8782225706828", + "output_sha256": "bfda9f689c88a5004b7d32e325e391984d27b4528088f66a62348dbb4b9f63f1", + "ttft_s": 1.289427698997315, + "error": null, + "length": 8192 + }, + { + "prompt_tokens": 32768, + "cached_tokens": 0, + "token_sha256": "bfdffc1b07cf64389fcfbbf4787d66ae1129eab9b716182e6d9b27aa0b80ff84", + "output_sha256": "3e1bd53ec06abd9b91c90f32f037c0ff187ee2eefeba47425ff757c9c74424b5", + "ttft_s": 6.005827143002534, + "error": null, + "length": 32768 + } +] \ No newline at end of file diff --git a/docs/receipts/qwen-unread-chunks-2941/runs/head-chat-fresh.json b/docs/receipts/qwen-unread-chunks-2941/runs/head-chat-fresh.json new file mode 100644 index 00000000000..374926b65e7 --- /dev/null +++ b/docs/receipts/qwen-unread-chunks-2941/runs/head-chat-fresh.json @@ -0,0 +1,18 @@ +{ + "prefix": { + "prompt_tokens": 7857, + "cached_tokens": 0, + "token_sha256": "2d92f715116a7e96bd52e51c3b111d84b9223c834c670fe24b9167e530468977", + "output_sha256": "7517f965a8a56f040faeb8d4cce68a39b20584a6ed0828d18d3c4948de25e0cb", + "ttft_s": 1.2289988420088775, + "error": null + }, + "resumed": { + "prompt_tokens": 7863, + "cached_tokens": 0, + "token_sha256": "e1de42acf830e5ec3a2f43890ebe33a29f9a186ddc0ac95ae0ac34595641af76", + "output_sha256": "19079cfe1bf997fb44a8a928a10f2574b80865b1a20faa560d12369d98497ef7", + "ttft_s": 1.2395485939923674, + "error": null + } +} \ No newline at end of file diff --git a/docs/receipts/qwen-unread-chunks-2941/runs/head-chat16k.json b/docs/receipts/qwen-unread-chunks-2941/runs/head-chat16k.json new file mode 100644 index 00000000000..5aaea37a66e --- /dev/null +++ b/docs/receipts/qwen-unread-chunks-2941/runs/head-chat16k.json @@ -0,0 +1,18 @@ +{ + "prefix": { + "prompt_tokens": 17972, + "cached_tokens": 8192, + "token_sha256": "45ea8c4a80ae3aef55655bed61df036b7563a343ba2ba4798a7b562c7f59ad28", + "output_sha256": "a88150b951e889af79158b6f953f746424f4c048f749ee71c948c32b0661af68", + "ttft_s": 1.7911394390102942, + "error": null + }, + "resumed": { + "prompt_tokens": 17978, + "cached_tokens": 16384, + "token_sha256": "e1de42acf830e5ec3a2f43890ebe33a29f9a186ddc0ac95ae0ac34595641af76", + "output_sha256": "19079cfe1bf997fb44a8a928a10f2574b80865b1a20faa560d12369d98497ef7", + "ttft_s": 0.3614026880240999, + "error": null + } +} \ No newline at end of file diff --git a/docs/receipts/qwen-unread-chunks-2941/runs/head-chat8k.json b/docs/receipts/qwen-unread-chunks-2941/runs/head-chat8k.json new file mode 100644 index 00000000000..38ea6d6e408 --- /dev/null +++ b/docs/receipts/qwen-unread-chunks-2941/runs/head-chat8k.json @@ -0,0 +1,18 @@ +{ + "prefix": { + "prompt_tokens": 9352, + "cached_tokens": 0, + "token_sha256": "45ea8c4a80ae3aef55655bed61df036b7563a343ba2ba4798a7b562c7f59ad28", + "output_sha256": "a88150b951e889af79158b6f953f746424f4c048f749ee71c948c32b0661af68", + "ttft_s": 1.5258941400097683, + "error": null + }, + "resumed": { + "prompt_tokens": 9358, + "cached_tokens": 8192, + "token_sha256": "e1de42acf830e5ec3a2f43890ebe33a29f9a186ddc0ac95ae0ac34595641af76", + "output_sha256": "19079cfe1bf997fb44a8a928a10f2574b80865b1a20faa560d12369d98497ef7", + "ttft_s": 0.26243771199369803, + "error": null + } +} \ No newline at end of file diff --git a/docs/receipts/qwen-unread-chunks-2941/runs/head-cold.json b/docs/receipts/qwen-unread-chunks-2941/runs/head-cold.json new file mode 100644 index 00000000000..d1816eb21bb --- /dev/null +++ b/docs/receipts/qwen-unread-chunks-2941/runs/head-cold.json @@ -0,0 +1,29 @@ +[ + { + "prompt_tokens": 2048, + "cached_tokens": 0, + "token_sha256": "0551b205acb27d6e538b91b0cf5664c7de0ebe74f51ffcf323a1b598a8612d6b", + "output_sha256": "4dfc61c7c56afa657e8d6f0ec17dcee7cbd5d10120d5842982bc80ab9b1c5a6a", + "ttft_s": 0.3367427690245677, + "error": null, + "length": 2048 + }, + { + "prompt_tokens": 8192, + "cached_tokens": 0, + "token_sha256": "eabb9ee47126ea56d086699c051f993c9578286e7c7f5fcf62c8782225706828", + "output_sha256": "bfda9f689c88a5004b7d32e325e391984d27b4528088f66a62348dbb4b9f63f1", + "ttft_s": 1.2697269890049938, + "error": null, + "length": 8192 + }, + { + "prompt_tokens": 32768, + "cached_tokens": 0, + "token_sha256": "bfdffc1b07cf64389fcfbbf4787d66ae1129eab9b716182e6d9b27aa0b80ff84", + "output_sha256": "3e1bd53ec06abd9b91c90f32f037c0ff187ee2eefeba47425ff757c9c74424b5", + "ttft_s": 5.962409850995755, + "error": null, + "length": 32768 + } +] \ No newline at end of file diff --git a/docs/receipts/qwen-unread-chunks-2941/runs/head-drafted.json b/docs/receipts/qwen-unread-chunks-2941/runs/head-drafted.json new file mode 100644 index 00000000000..2d298c24007 --- /dev/null +++ b/docs/receipts/qwen-unread-chunks-2941/runs/head-drafted.json @@ -0,0 +1,20 @@ +[ + { + "prompt_tokens": 8192, + "cached_tokens": 0, + "token_sha256": "eabb9ee47126ea56d086699c051f993c9578286e7c7f5fcf62c8782225706828", + "output_sha256": "bfda9f689c88a5004b7d32e325e391984d27b4528088f66a62348dbb4b9f63f1", + "ttft_s": 1.2700206250010524, + "error": null, + "length": 8192 + }, + { + "prompt_tokens": 32768, + "cached_tokens": 0, + "token_sha256": "bfdffc1b07cf64389fcfbbf4787d66ae1129eab9b716182e6d9b27aa0b80ff84", + "output_sha256": "3e1bd53ec06abd9b91c90f32f037c0ff187ee2eefeba47425ff757c9c74424b5", + "ttft_s": 5.960642635007389, + "error": null, + "length": 32768 + } +] \ No newline at end of file diff --git a/docs/receipts/qwen-unread-chunks-2941/runs/head-marks.json b/docs/receipts/qwen-unread-chunks-2941/runs/head-marks.json new file mode 100644 index 00000000000..2e275d9a9ba --- /dev/null +++ b/docs/receipts/qwen-unread-chunks-2941/runs/head-marks.json @@ -0,0 +1,18 @@ +{ + "8192": [ + { + "state": "a5100d6d33cef4e8279c6aedf1066dcf", + "blocks": 32, + "state_sha256": "4c17690b79f771208134c6065f760cfca7ba8ed63f983e510d89f64b74e962f9", + "kv_sha256": "c0d8a3685f8c0c142260be48766c2e56adeaf08fd43f3ef5899c006dee297d5f" + } + ], + "16384": [ + { + "state": "4eeea0362f5b1dbceefdbcfaf4a46610", + "blocks": 64, + "state_sha256": "a849f8970ab05562bab42fb78ff4ee57ef08ec70dfbf13f084ca3cdb5bd642a2", + "kv_sha256": "8909fc17c889bebe82313ae0ee39900acc2ed9ba386f2156aa5e958b873fecb4" + } + ] +} diff --git a/docs/receipts/qwen-unread-chunks-2941/runs/head-sampled.json b/docs/receipts/qwen-unread-chunks-2941/runs/head-sampled.json new file mode 100644 index 00000000000..157a32f4800 --- /dev/null +++ b/docs/receipts/qwen-unread-chunks-2941/runs/head-sampled.json @@ -0,0 +1,20 @@ +[ + { + "prompt_tokens": 8192, + "cached_tokens": 0, + "token_sha256": "eabb9ee47126ea56d086699c051f993c9578286e7c7f5fcf62c8782225706828", + "output_sha256": "bfda9f689c88a5004b7d32e325e391984d27b4528088f66a62348dbb4b9f63f1", + "ttft_s": 1.2701901760010514, + "error": null, + "length": 8192 + }, + { + "prompt_tokens": 32768, + "cached_tokens": 0, + "token_sha256": "bfdffc1b07cf64389fcfbbf4787d66ae1129eab9b716182e6d9b27aa0b80ff84", + "output_sha256": "3e1bd53ec06abd9b91c90f32f037c0ff187ee2eefeba47425ff757c9c74424b5", + "ttft_s": 5.967192418000195, + "error": null, + "length": 32768 + } +] \ No newline at end of file diff --git a/docs/receipts/qwen-unread-chunks-2941/states.py b/docs/receipts/qwen-unread-chunks-2941/states.py new file mode 100644 index 00000000000..3b976d6e687 --- /dev/null +++ b/docs/receipts/qwen-unread-chunks-2941/states.py @@ -0,0 +1,98 @@ +"""Kept-state and K/V digests at a prompt-cache mark, from the disk tier's own files.""" +import hashlib +import json +import struct +import sys +from pathlib import Path + +MAGIC = 0x42524654 +BLOCK_TOKENS = 256 +WORDS = 16 +TRAILER = struct.Struct(" lo] + digest.update(words(len(inside))) + for span in inside: + digest.update(words(max(span[0], lo), min(span[1], hi))) + inside = [start for start in starts if lo <= start < hi] + digest.update(words(len(inside))) + for start in inside: + digest.update(words(start)) + + +def next_start(starts, at, end): + return min([start for start in starts if at <= start < end] or [end]) + + +def block_names(identity, tokens, spans, starts, at): + seeded = hashlib.sha256() + seeded.update(b"tensorfold rows 1") + seeded.update(words(identity & 0xFFFFFFFF, identity >> 32, BLOCK_TOKENS, 0, 1)) + chain = seeded.digest() + names = [] + for lo in range(0, at, BLOCK_TOKENS): + hi = lo + BLOCK_TOKENS + digest = hashlib.sha256() + digest.update(chain) + digest.update(struct.pack(f"<{BLOCK_TOKENS}I", *tokens[lo:hi])) + edges(digest, spans, starts, lo, hi) + chain = digest.digest() + named = hashlib.sha256() + named.update(chain) + named.update(words(0, 0)) # window, lookahead + named.update(words(next_start(starts, hi, at))) + names.append(named.digest()) + return names + + +def parse(path): + data = path.read_bytes() + magic, version, kind, flags, payload, payload_hash, meta_bytes, meta_hash, name, at, block, reserved = TRAILER.unpack(data[-TRAILER.size:]) + if magic != MAGIC or version != 1 or kind != 2 or block != BLOCK_TOKENS or payload + meta_bytes + TRAILER.size != len(data): + return None + counts = struct.unpack_from(" bool:\n \"\"\"Whether ``text`` holds a character of any of the given code point ranges.\"\"\"\n\n if not text:\n return False\n if \"CJK\" in unicodedata.name(text[0], \"\") and any(a <= 0x4E00 <= b for a, b in ranges):\n return True\n for char in text:\n point = ord(char)\n if any(a <= point <= b for a, b in ranges):\n return True\n return False\n\n\ndef main() -> None:\n p = argparse.ArgumentParser()\n p.add_argument(\"tokenizer\", help=\"the checkpoint's tokenizer.json\")\n p.add_argument(\"base\", help=\"an existing draft vocabulary to extend (tools/draft_vocab.py writes one)\")\n p.add_argument(\"out\")\n p.add_argument(\"--script\", action=\"append\", required=True, choices=sorted(SCRIPTS),\n help=\"a script whose ids to add; repeat for more\")\n args = p.parse_args()\n\n tok = Tokenizer.from_file(args.tokenizer)\n vocab = tok.get_vocab_size(with_added_tokens=False)\n with open(args.base, encoding=\"utf-8\") as handle:\n base = {int(line) for line in handle if line.strip()}\n ranges = tuple(r for name in args.script for r in SCRIPTS[name])\n\n added: set[int] = set()\n for index in range(vocab):\n # byte-level BPE: a token is a byte blob, so a character test only works after decoding\n if in_scripts(tok.decode([index], skip_special_tokens=False), ranges):\n added.add(index)\n ids = sorted(base | added)\n with open(args.out, \"w\", encoding=\"utf-8\") as handle:\n handle.write(\"\".join(f\"{i}\\n\" for i in ids))\n print(f\"{args.base}: {len(base)} ids + {len(added - base)} {'/'.join(args.script)} ids \"\n f\"= {len(ids)} of {vocab} ({len(ids) / vocab:.1%}) -> {args.out}\")\n\n\nif __name__ == \"__main__\":\n main()\n```\n\nThe same file with every double-quoted string changed to single quotes, in full:\n```python\n" + }, + { + "name": "edit-zig_gate", + "kind": "completion", + "prompt": "Original file `zig_gate.py`:\n```python\n\"\"\"Release gate step for the native engine: passed cells as manifest entries, zig/gate.json from them, and a check.\"\"\"\n\nfrom __future__ import annotations\n\nimport argparse\nimport json\nfrom pathlib import Path\nimport sys\n\nfrom tensorfold import families, native\nfrom tensorfold.native import contract, switch\n\n\ndef _installed() -> tuple[Path, dict]:\n binary = native.binary()\n if binary is None:\n raise SystemExit(f\"no native engine in this install ({native.ROOT / native.BINARY})\")\n return binary, contract.capabilities(binary)\n\n\ndef cell(run: str, model: Path, backend: str = \"auto\") -> dict:\n \"\"\"The manifest entry for ``model`` on this machine with this install's bundle, checked against the schema.\"\"\"\n\n _, found = _installed()\n if found[\"chip\"] is None:\n raise SystemExit(\"the native engine reports no usable GPU here\")\n entry = {\"family\": families.model_type(model), \"format\": contract.weight_format(families.read_config(model)),\n \"backend\": switch.backend(backend), \"chip\": found[\"chip\"], \"run\": run, \"bundle\": native.bundle_digest()}\n contract.check(entry, contract.schema(\"gate\")[\"properties\"][\"entries\"][\"items\"])\n return entry\n\n\ndef write(out: Path, cells: list[Path], bundles: list[str] = ()) -> dict:\n \"\"\"zig/gate.json from cell files (an entry or a whole manifest each), sorted, deduplicated, checked.\"\"\"\n\n entries = []\n for path in cells:\n document = json.loads(path.read_text())\n entries += document[\"entries\"] if \"entries\" in document else [document]\n keep = sorted({json.dumps(entry, sort_keys=True) for entry in entries if not bundles or entry[\"bundle\"] in bundles})\n manifest = {\"schema\": 1, \"entries\": [json.loads(entry) for entry in keep]}\n contract.check(manifest, contract.schema(\"gate\"))\n out.write_text(json.dumps(manifest, indent=2) + \"\\n\")\n return manifest\n\n\ndef verify() -> int:\n \"\"\"Print this install's native engine, chip, bundle and the gate entries that name its bundle.\"\"\"\n\n _, found = _installed()\n digest = native.bundle_digest()\n entries = contract.manifest()[\"entries\"]\n mine = [entry for entry in entries if entry[\"bundle\"] == digest]\n print(json.dumps({\"version\": found[\"version\"], \"chip\": found[\"chip\"], \"bundle\": digest,\n \"entries\": len(entries), \"this_bundle\": mine}, indent=1))\n return 0 if mine else 1\n\n\ndef main(argv: list[str] | None = None) -> int:\n parser = argparse.ArgumentParser(description=__doc__)\n commands = parser.add_subparsers(dest=\"command\", required=True)\n one = commands.add_parser(\"cell\", help=\"print the entry for a cell whose native arm passed, run in that install\")\n one.add_argument(\"--run\", required=True, help=\"the release gate label, e.g. rel066a (public: no machine names)\")\n one.add_argument(\"--model\", required=True, type=Path, help=\"the checkpoint directory the arm served\")\n one.add_argument(\"--backend\", choices=(\"auto\", \"mlx\", \"cuda\"), default=\"auto\")\n out = commands.add_parser(\"write\", help=\"write zig/gate.json from cell files or manifests\")\n out.add_argument(\"--out\", required=True, type=Path)\n out.add_argument(\"--bundle\", action=\"append\", default=[], help=\"keep only entries for this bundle sha256\")\n out.add_argument(\"cells\", nargs=\"*\", type=Path)\n commands.add_parser(\"verify\", help=\"exit 0 only when this install's bundle has gate entries\")\n args = parser.parse_args(argv)\n if args.command == \"cell\":\n print(json.dumps(cell(args.run, args.model, args.backend), indent=1))\n return 0\n if args.command == \"write\":\n manifest = write(args.out, args.cells, args.bundle)\n print(f\"{args.out}: {len(manifest['entries'])} entries\", file=sys.stderr)\n return 0\n return verify()\n\n\nif __name__ == \"__main__\":\n raise SystemExit(main())\n```\n\nThe same file with the module docstring removed and nothing else changed, in full:\n```python\n" + }, + { + "name": "edit-clef_tokens", + "kind": "completion", + "prompt": "Original file `clef_tokens.py`:\n```python\n\"\"\"Record Clef's encode_record ids and spans for the server's clef_tokens.json fixture (CPU, checkpoint tokenizer).\"\"\"\n# usage: python3 -I tools/clef_tokens.py CLEF_DIR OUT_JSON (CLEF_DIR: Cloudflare/clef-flash at REVISION)\nimport importlib.util\nimport json\nimport os\nimport sys\n\nSOURCES = {\"repo\": \"Cloudflare/clef-flash\", \"revision\": \"fb4417d31c1d\", \"transformers\": \"5.22.1\", \"torch\": \"2.15\"}\nREVISION = \"fb4417d31c1d0f9e7e77f1141b40aaede7491e00\"\n\n\ndef records():\n \"\"\"The pinned records: every question type, the fallbacks, Unicode and combining marks, specials, truncation.\"\"\"\n out = [\n {\"state\": \"The door is open.\", \"questions\": {\"open\": {\"type\": \"noul\", \"instructions\": \"Is the door open?\"}}},\n {\"state\": {\"items\": [\"a\", \"b\"], \"n\": 3}, \"questions\": {\"pick\": {\"type\": \"choice\", \"instructions\": \"Pick one.\",\n \"criteria\": {\"zeta\": \"Last\", \"Alpha\": \"First\", \"\u00e9t\u00e9\": \"Summer\", \"beta\": None, \"10\": \"Ten\", \"9\": \"Nine\"}}}},\n {\"state\": \"Rate the reply.\", \"questions\": {\"q\": {\"type\": \"score\", \"instructions\": {\"rubric\": \"1-5\", \"strict\": True},\n \"criteria\": [\"awful\", \"poor\", \"fine\", \"good\", None]}}},\n {\"state\": \"x\", \"questions\": {\n \"missing\": {\"type\": \"noul\"}, \"none\": {\"type\": \"noul\", \"instructions\": None},\n \"empty\": {\"type\": \"noul\", \"instructions\": \"\"}, \"false\": {\"type\": \"noul\", \"instructions\": False},\n \"zero\": {\"type\": \"noul\", \"instructions\": 0}, \"list\": {\"type\": \"noul\", \"instructions\": []},\n \"dict\": {\"type\": \"noul\", \"instructions\": {}}}},\n {\"state\": \"\u6771\u4eac\u306e\u5929\u6c17\u306f\u6674\u308c\u3002 \ud83d\ude00 \u041f\u0440\u0438\u0432\u0435\u0442 \u043c\u0438\u0440! \u0645\u0631\u062d\u0628\u0627 \u0628\u0627\u0644\u0639\u0627\u0644\u0645\", \"questions\": {\"lang\": {\"type\": \"choice\",\n \"criteria\": {\"ja\": \"Japanese\", \"ru\": \"Russian\", \"ar\": \"Arabic\"}}}},\n {\"state\": \"\u0915\u094d\u0937\u0924\u094d\u0930\u093f\u092f \u0939\u093f\u0928\u094d\u0926\u0940 \u2014 cafe\u0301 vs caf\u00e9 \u2014 \u0e20\u0e32\u0e29\u0e32\u0e44\u0e17\u0e22 \u2014 \u05e9\u05b8\u05c1\u05dc\u05d5\u05b9\u05dd \u2014 x\u0301\u0302y \u00c4\u0308b\",\n \"questions\": {\"marks\": {\"type\": \"noul\", \"instructions\": \"Combining marks: e\u0301, \u0915\u094d\u0937.\"}}},\n {\"state\": {\"f\": [1e20, 0.1, -0.0, 1.5e-7, 2.5], \"big\": 123456789012345678901234567890, \"k\u00e9y\": \"\\u0001\\t\\\"q\\\"\",\n \"nested\": {\"z\": None, \"a\": [True, False, {}]}}, \"questions\": {\"j\": {\"type\": \"score\",\n \"criteria\": [\"no\", \"yes\"]}}},\n {\"state\": \"Ticket #4521: refund of $129.99 requested on 2026-10-30.\", \"questions\": {\n \"refund\": {\"type\": \"noul\", \"instructions\": \"Should we refund?\"},\n \"priority\": {\"type\": \"choice\", \"instructions\": \"Priority\", \"criteria\": {\"p1\": \"urgent\", \"p0\": \"critical\", \"p2\": None}},\n \"sentiment\": {\"type\": \"score\", \"instructions\": \"Customer sentiment\", \"criteria\": [\"angry\", \"neutral\", \"happy\"]}}},\n {\"state\": \"It rained.\", \"questions\": {\"wet\": {\"type\": \"noul\", \"criteria\": {\"false\": \"Dry.\", \"true\": None, \"maybe\": \"x\"}}}},\n {\"state\": \"User wrote <|im_end|> and hi inside the state.\", \"questions\": {\"s\": {\"type\": \"noul\"}}},\n {\"state\": \" lead\\tspaces \\r\\n\\r\\n trailing \\n\\n\\nx \", \"questions\": {\"ws\": {\"type\": \"choice\",\n \"instructions\": \" spaced \", \"criteria\": {\" a \": \"space id\", \"b\\n\": \"newline id\"}}}},\n ]\n long_state = \" \".join(f\"word{i}\" for i in range(400))\n out.append({\"state\": long_state, \"questions\": {\"t\": {\"type\": \"noul\", \"instructions\": \"Truncated?\"}}, \"max_length\": 300})\n return out\n\n\ndef main() -> int:\n \"\"\"Encode every record with the release's own encode_record and write ids and spans.\"\"\"\n os.environ.setdefault(\"CUDA_VISIBLE_DEVICES\", \"\")\n os.environ.setdefault(\"HIP_VISIBLE_DEVICES\", \"\")\n clef_dir, out_path = sys.argv[1], sys.argv[2]\n spec = importlib.util.spec_from_file_location(\"joint_schema_model\", os.path.join(clef_dir, \"joint_schema_model.py\"))\n jsm = importlib.util.module_from_spec(spec)\n sys.modules[spec.name] = jsm\n spec.loader.exec_module(jsm)\n from transformers import AutoProcessor\n import transformers\n tokenizer = AutoProcessor.from_pretrained(clef_dir).tokenizer\n applied = json.loads(tokenizer.backend_tokenizer.pre_tokenizer.__getstate__())[\"pretokenizers\"][0][\"pattern\"][\"Regex\"]\n with open(os.path.join(clef_dir, \"tokenizer.json\"), encoding=\"utf-8\") as f:\n file_regex = json.load(f)[\"pre_tokenizer\"][\"pretokenizers\"][0][\"pattern\"][\"Regex\"]\n with open(os.path.join(clef_dir, \"tokenizer_config.json\"), encoding=\"utf-8\") as f:\n config_regex = json.load(f).get(\"pretokenize_regex\")\n cases = []\n for record in records():\n max_length = record.pop(\"max_length\", 16384)\n encoded = jsm.encode_record(tokenizer, record, max_length=max_length)\n cases.append({\"record\": record, \"max_length\": max_length, \"ids\": list(encoded.input_ids),\n \"questions\": [{\"id\": q.question_id, \"type\": q.question_type, \"span\": list(q.question_span),\n \"options\": [list(s) for s in q.option_spans], \"option_ids\": list(q.option_ids)}\n for q in encoded.questions]})\n regex = \"tokenizer_config.json pretokenize_regex\" if applied == config_regex else \"tokenizer.json\"\n if applied not in (config_regex, file_regex):\n regex = \"neither file's\"\n out = {\"sources\": dict(SOURCES, revision_full=REVISION, transformers_seen=transformers.__version__,\n tokenizer_class=type(tokenizer).__name__, pretokenize=regex), \"cases\": cases}\n with open(out_path, \"w\", encoding=\"utf-8\") as f:\n json.dump(out, f, ensure_ascii=False, separators=(\",\", \":\"))\n f.write(\"\\n\")\n print(f\"wrote {out_path}: {len(cases)} records, pre-tokenizer from {regex}\")\n return 0\n\n\nif __name__ == \"__main__\":\n sys.exit(main())\n```\n\nThe same file with `import sys` added at the top and nothing else changed, in full:\n```python\n" + }, + { + "name": "edit-bench_thinking", + "kind": "completion", + "prompt": "Original file `bench_thinking.py`:\n```python\n\"\"\"Discover explicit thinking-off support once and label the requested benchmark mode.\"\"\"\nimport json\nimport urllib.request\n\nfrom bench_auth import authorize\n\n\ndef discover(base: str, model: str, api_key: str | None = None) -> dict:\n \"\"\"Only consistent booleans for this model are trusted; older servers remain unknown.\"\"\"\n out = {\"thinking_switch\": None, \"thinking_applicable\": None}\n try:\n request = urllib.request.Request(base.rstrip(\"/\") + \"/v1/models\", headers={\"Accept\": \"application/json\"})\n authorize(request, api_key)\n with urllib.request.urlopen(request, timeout=30) as response:\n raw = response.read(1_048_577)\n if len(raw) > 1_048_576:\n return out\n document = json.loads(raw)\n if not isinstance(document, dict) or not isinstance(document.get(\"data\"), list):\n return out\n entries = [entry.get(\"capabilities\", {}) for entry in document[\"data\"]\n if isinstance(entry, dict) and entry.get(\"id\") == model]\n for field in out:\n bits = [entry.get(field) if isinstance(entry, dict) else None for entry in entries]\n if bits and all(type(bit) is bool and bit is bits[0] for bit in bits):\n out[field] = bits[0]\n except (OSError, ValueError, TypeError):\n pass\n return out\n\n\ndef configure(items: list[dict], capabilities: dict | bool | None) -> list[dict]:\n \"\"\"Keep shared prompt definitions unchanged and retain unknown applicability for older servers.\"\"\"\n values = capabilities if isinstance(capabilities, dict) else {\"thinking_switch\": capabilities}\n return [{**item, **values} for item in items]\n\n\ndef mode(item: dict) -> str:\n \"\"\"Distinguish a verified off request, an unverified off request and a known unsupported switch.\"\"\"\n if item[\"kind\"] != \"chat\" or item.get(\"thinking_applicable\") is False:\n return \"not applicable\"\n switch = item.get(\"thinking_switch\")\n if switch is True:\n return \"off\"\n return \"default (thinking off unsupported)\" if switch is False else \"off requested (unverified)\"\n\n\ndef request_off(item: dict) -> bool:\n return item[\"kind\"] == \"chat\" and item.get(\"thinking_applicable\") is not False and item.get(\"thinking_switch\") is not False\n\n\ndef receipt(item: dict) -> dict:\n return {\"thinking\": mode(item), \"thinking_off_requested\": request_off(item),\n \"thinking_switch\": item.get(\"thinking_switch\"), \"thinking_applicable\": item.get(\"thinking_applicable\")}\n\n\ndef load_comparison(path: str | None) -> list[dict]:\n if path is None:\n return []\n with open(path, encoding=\"utf-8\") as source:\n value = json.load(source)\n rows = value.get(\"cells\") if isinstance(value, dict) else value\n if not isinstance(rows, list) or not all(isinstance(row, dict) for row in rows):\n raise ValueError(\"comparison receipt must hold a row list or cells list\")\n return rows\n\n\ndef comparison(row: dict, previous: list[dict]) -> dict:\n def key(value):\n prompt = value.get(\"prompt\")\n if prompt == \"gpu-chat\":\n prompt = \"gpu-chat-no-think\"\n return prompt, value.get(\"temperature\"), value.get(\"streams\")\n def label(value):\n modes = value.get(\"thinking_modes\")\n return \", \".join(modes) if isinstance(modes, list) else value.get(\"thinking\", \"unknown\")\n matches = [old for old in previous if key(old) == key(row)]\n if not matches:\n return row\n same = all(label(old) == label(row) for old in matches)\n out = {**row, \"thinking_comparable\": same}\n if not same:\n out[\"comparison_warning\"] = \"Thinking labels differ; do not compare these rates\"\n out[\"comparison_thinking\"] = sorted({label(old) for old in matches})\n return out\n```\n\nThe same file with each function's first line followed by a `# TODO: review` comment, in full:\n```python\n" + }, + { + "name": "edit-draft_vocab", + "kind": "completion", + "prompt": "Original file `draft_vocab.py`:\n```python\n\"\"\"A draft vocabulary for a draft head: the most frequent token ids over some text, plus the lowest ids.\n\nDrafts never need to be exact (the target verifies every one), so a head can score a subset of the vocabulary and\nread proportionally fewer weights. A token outside the list can never be drafted, which costs speed, never\ncorrectness. Build it from public text only: the list ships with the package.\n\n python tools/draft_vocab.py TOKENIZER_JSON OUT.txt --size 32768 --min-count 10 'corpus/**/*.py' 'docs/**/*.md'\n\"\"\"\n\nfrom __future__ import annotations\n\nimport argparse\nimport collections\nimport glob\nimport json\n\nimport sys\n\n\ndef text_main() -> None:\n from tokenizers import Tokenizer\n\n p = argparse.ArgumentParser()\n p.add_argument(\"tokenizer\")\n p.add_argument(\"out\")\n p.add_argument(\"patterns\", nargs=\"+\")\n p.add_argument(\"--size\", type=int, default=32768)\n p.add_argument(\"--keep-below\", type=int, default=1024, help=\"always keep ids below this (special tokens)\")\n p.add_argument(\"--max-bytes\", type=int, default=2_000_000, help=\"skip files larger than this\")\n p.add_argument(\"--min-count\", type=int, default=10,\n help=\"leave out ids seen fewer times (rare names and one-off words); the id prefix fills the rest\")\n p.add_argument(\"--added-tokens\", action=\"store_true\", help=\"always keep the tokenizer's added (special) tokens\")\n p.add_argument(\"--base\", help=\"an existing list kept whole (the new ids extend it)\")\n p.add_argument(\"--exclude\", help=\"ids never kept (tokens the privacy gate flags)\")\n args = p.parse_args()\n tok = Tokenizer.from_file(args.tokenizer)\n counts: collections.Counter = collections.Counter()\n files = sorted({f for pat in args.patterns for f in glob.glob(pat, recursive=True)})\n total = used = 0\n for path in files:\n try:\n with open(path, encoding=\"utf-8\") as handle:\n text = handle.read(args.max_bytes + 1)\n except (UnicodeDecodeError, OSError, IsADirectoryError):\n continue\n if not text or len(text) > args.max_bytes:\n continue\n ids = tok.encode(text).ids\n counts.update(ids)\n total += len(ids)\n used += 1\n keep = set(range(args.keep_below))\n if args.added_tokens:\n keep |= {t[\"id\"] for t in json.loads(open(args.tokenizer).read())[\"added_tokens\"]}\n if args.base:\n keep |= {int(t) for t in open(args.base).read().split()}\n drop = {int(t) for t in open(args.exclude).read().split()} if args.exclude else set()\n keep -= drop\n for tid, count in counts.most_common():\n if len(keep) >= args.size or count < args.min_count:\n break\n if tid not in drop:\n keep.add(tid)\n fill = iter(range(args.keep_below, tok.get_vocab_size()))\n while len(keep) < args.size: # the id prefix fills a short list\n t = next(fill)\n if t not in drop:\n keep.add(t)\n ids = sorted(keep)\n covered = sum(c for t, c in counts.items() if t in keep)\n with open(args.out, \"w\") as handle:\n handle.write(\"\\n\".join(str(i) for i in ids) + \"\\n\")\n print(json.dumps({\"files\": used, \"tokens\": total, \"size\": len(ids), \"coverage\": round(covered / max(1, total), 4),\n \"from_counts\": sum(1 for t, c in counts.items() if c >= args.min_count and t in keep)}))\n\n\ndef main() -> None:\n if len(sys.argv) > 1 and sys.argv[1] == \"responses\":\n from draft_vocab_responses import main as response_main\n response_main(sys.argv[2:])\n else:\n text_main()\n\n\nif __name__ == \"__main__\":\n main()\n```\n\nThe same file with the variable `args` renamed to `opts` everywhere, in full:\n```python\n" + }, + { + "name": "edit-bench_metrics", + "kind": "completion", + "prompt": "Original file `bench_metrics.py`:\n```python\n\"\"\"Prompt/TTFT rate, ITL, TPOT and round gaps from streamed chunk arrivals; docs/cache-benchmarks.md defines each.\"\"\"\nimport math\nimport statistics\n\nfrom bench_evidence import count\n\n# Old receipt keys still written beside their replacements, so readers of older receipts keep working.\nDEPRECATED = {\"prefill_tps\": \"prompt_ttft_tps\", \"aggregate_prefill_tps\": \"aggregate_prompt_ttft_tps\"}\nNOTE = {old: f\"deprecated: same value as {new}; prompt tokens over client TTFT, not the engine's prefill time\"\n for old, new in DEPRECATED.items()}\n\n\ndef rank(sorted_values: list[float], q: float) -> float | None:\n \"\"\"Nearest-rank percentile of an ascending list (None for an empty one).\"\"\"\n if not sorted_values:\n return None\n return sorted_values[max(0, math.ceil(len(sorted_values) * q) - 1)]\n\n\ndef arrivals(run: dict) -> list[float] | None:\n \"\"\"A reply's output chunk arrivals (every output kind); older run dicts without them give their text pieces.\"\"\"\n if \"output_times\" in run:\n return run[\"output_times\"]\n return [p[0] for p in run.get(\"pieces\") or []]\n\n\ndef samples(run: dict) -> tuple[list[float], bool] | None:\n \"\"\"A reply's chunk gaps in ms and whether each chunk is known to hold one token; None when unmatched.\"\"\"\n times, n = arrivals(run), count(run.get(\"tokens\"))\n if not run.get(\"complete\") or times is None or n is None or n < 2 or len(times) < 2 or len(times) > n:\n return None\n if any(b < a for a, b in zip(times, times[1:])):\n return None\n return [(b - a) * 1000 for a, b in zip(times, times[1:])], len(times) == n\n\n\ndef summary(itl: list[float], gaps: list[float], tokens: int, chunks: int, spans: int) -> dict:\n \"\"\"Token ITL/TPOT (ms; known only where every chunk held one token), chunk-level round gaps and estimates.\"\"\"\n itl, gaps = sorted(itl), sorted(gaps)\n return {\"itl_mean_ms\": statistics.fmean(itl) if itl else None, \"itl_p50_ms\": rank(itl, 0.5),\n \"itl_p95_ms\": rank(itl, 0.95), \"tpot_ms\": statistics.fmean(itl) if itl else None,\n \"chunk_tpot_estimate_ms\": sum(gaps) / spans if gaps and spans else None,\n \"round_gap_p50_ms\": rank(gaps, 0.5), \"round_gap_p95_ms\": rank(gaps, 0.95),\n \"round_gap_mean_ms\": statistics.fmean(gaps) if gaps else None,\n \"tokens_per_chunk\": tokens / chunks if chunks else None}\n\n\ndef prompt_ttft_tps(run: dict) -> float | None:\n \"\"\"prompt_tokens / client TTFT of a cold request (not engine prefill time); None for a reused or unverified one.\"\"\"\n prompt, ttft = count(run.get(\"prompt_tokens\")), run.get(\"ttft_s\")\n if run.get(\"cache_state\") != \"cold\" or not prompt or type(ttft) not in (int, float) or ttft <= 0:\n return None\n return prompt / ttft\n\n\ndef request(run: dict) -> dict:\n \"\"\"One request's figures (None where its stream does not support them).\"\"\"\n rate = prompt_ttft_tps(run)\n out = {\"prompt_ttft_tps\": rate, \"prefill_tps\": rate, \"token_timing\": None, **summary([], [], 0, 0, 0)}\n got = samples(run)\n if got is not None:\n gaps, per_token = got\n out.update(token_timing=\"token\" if per_token else \"chunk\",\n **summary(gaps if per_token else [], gaps, run[\"tokens\"], len(gaps) + 1, run[\"tokens\"] - 1))\n return out\n\n\ndef pooled(runs: list[dict]) -> dict:\n \"\"\"Every measurable stream's samples together (token ITL from one-token-a-chunk streams), and the aggregate rate.\"\"\"\n itl, gaps, tokens, chunks, spans, timed, token_timed = [], [], 0, 0, 0, 0, 0\n for r in runs:\n got = samples(r)\n if got is None:\n continue\n itl += got[0] if got[1] else []\n gaps += got[0]\n tokens += r[\"tokens\"]\n chunks += len(got[0]) + 1\n spans += r[\"tokens\"] - 1\n timed += 1\n token_timed += got[1]\n out = {\"streams_timed\": timed, \"streams_token_timed\": token_timed, **summary(itl, gaps, tokens, chunks, spans),\n \"aggregate_prompt_ttft_tps\": None}\n cold = [r for r in runs if prompt_ttft_tps(r) is not None and type(r.get(\"first\")) in (int, float)\n and type(r.get(\"sent\")) in (int, float)]\n if cold and len(cold) == len(runs):\n span = max(r[\"first\"] for r in cold) - min(r[\"sent\"] for r in cold)\n out[\"aggregate_prompt_ttft_tps\"] = sum(r[\"prompt_tokens\"] for r in cold) / span if span > 0 else None\n out[\"aggregate_prefill_tps\"] = out[\"aggregate_prompt_ttft_tps\"]\n return out\n```\n\nThe same file with all blank lines inside functions removed, in full:\n```python\n" + }, + { + "name": "edit-bench_evidence", + "kind": "completion", + "prompt": "Original file `bench_evidence.py`:\n```python\n\"\"\"Validated usage and output fingerprints shared by the HTTP benchmark clients.\"\"\"\nimport hashlib\nimport json\nimport re\n\n\ndef count(value):\n \"\"\"A server-reported nonnegative integer; missing, boolean and coerced numbers stay unknown.\"\"\"\n return value if type(value) is int and value >= 0 else None\n\n\ndef tool_pieces(delta):\n \"\"\"A delta's tool-call fragments as (index, type, name, arguments); a missing index is the fragment's position.\"\"\"\n calls = delta.get(\"tool_calls\") or []\n if not isinstance(calls, list):\n raise ValueError(\"invalid_tool_chunk\")\n out = []\n for position, call in enumerate(calls):\n function = (call.get(\"function\") or {}) if isinstance(call, dict) else None\n index = call.get(\"index\", position) if isinstance(call, dict) else None\n if not isinstance(function, dict) or type(index) is not int or index < 0:\n raise ValueError(\"invalid_tool_chunk\")\n parts = (call.get(\"type\") or \"\", function.get(\"name\") or \"\", function.get(\"arguments\") or \"\")\n if not all(isinstance(part, str) for part in parts):\n raise ValueError(\"invalid_tool_chunk\")\n out.append((index, *parts))\n return out\n\n\nclass Evidence:\n \"\"\"Hash each choice's content, reasoning and tool calls apart so network chunk boundaries cannot alter them.\"\"\"\n\n def __init__(self):\n self.choices = {}\n self.tools = {}\n self.observed_output = False\n\n def add(self, choice):\n \"\"\"Take one choice delta; returns the output kinds it carried (\"content\", \"reasoning\", \"tool\").\"\"\"\n delta = choice.get(\"delta\") or {}\n index = choice.get(\"index\", 0)\n content = choice.get(\"text\") or delta.get(\"content\") or \"\"\n reasoning = delta.get(\"reasoning_content\") or \"\"\n if not isinstance(content, str) or not isinstance(reasoning, str) or type(index) is not int or index < 0:\n raise ValueError(\"invalid_text_chunk\")\n calls = tool_pieces(delta)\n self.observed_output |= bool(content or reasoning)\n text, thought = self.choices.setdefault(index, (hashlib.sha256(), hashlib.sha256()))\n text.update(content.encode(\"utf-8\"))\n thought.update(reasoning.encode(\"utf-8\"))\n for at, kind, name, arguments in calls:\n parts = self.tools.setdefault((index, at), [\"\", [], []])\n parts[0] = parts[0] or kind\n parts[1].append(name)\n parts[2].append(arguments)\n tool = any(name or arguments for _, _, name, arguments in calls)\n return {kind for kind, seen in ((\"content\", content), (\"reasoning\", reasoning), (\"tool\", tool)) if seen}\n\n def digest(self):\n \"\"\"One choice: SHA-256 of its content and reasoning digests; several: of each choice's, in index order.\"\"\"\n empty = (hashlib.sha256(), hashlib.sha256())\n parts = [self.choices[i] for i in sorted(self.choices)] or [empty]\n each = [hashlib.sha256(text.digest() + thought.digest()) for text, thought in parts]\n return each[0].hexdigest() if len(each) == 1 else hashlib.sha256(b\"\".join(d.digest() for d in each)).hexdigest()\n\n def tool_digest(self):\n \"\"\"SHA-256 of the assembled calls (choice, index, type, name, arguments); server call ids are left out.\"\"\"\n calls = [[*key, kind, \"\".join(name), \"\".join(arguments)] for key in sorted(self.tools)\n for kind, name, arguments in [self.tools[key]]]\n return hashlib.sha256(json.dumps(calls, separators=(\",\", \":\")).encode(\"utf-8\")).hexdigest() if calls else None\n\n def finish(self, usage, runtime, complete):\n usage = usage if isinstance(usage, dict) else {}\n runtime = runtime if isinstance(runtime, dict) else {}\n details = usage.get(\"prompt_tokens_details\")\n details = details if isinstance(details, dict) else {}\n prompt = count(usage.get(\"prompt_tokens\"))\n cached = count(details.get(\"cached_tokens\"))\n tokens = count(usage.get(\"completion_tokens\"))\n valid = prompt is not None and cached is not None and cached <= prompt\n state = \"cold\" if valid and cached == 0 else \"reused\" if valid else \"unverified\"\n if not complete:\n state = \"unverified\"\n token_sha = runtime.get(\"token_sha\")\n if not isinstance(token_sha, str) or not re.fullmatch(r\"(?:[0-9a-f]{12}|[0-9a-f]{64})\", token_sha):\n token_sha = None\n token_sha256 = runtime.get(\"token_sha256\")\n if not isinstance(token_sha256, str) or not re.fullmatch(r\"[0-9a-f]{64}\", token_sha256):\n token_sha256 = None\n if token_sha and token_sha256 and not token_sha256.startswith(token_sha[:12]):\n token_sha256 = None\n verified_output = complete and self.observed_output\n return {\"prompt_tokens\": prompt, \"cached_tokens\": cached, \"tokens\": tokens, \"cache_state\": state,\n \"complete\": complete, \"token_sha\": token_sha if verified_output else None,\n \"token_sha256\": token_sha256 if verified_output else None,\n \"output_sha256\": self.digest() if verified_output else None,\n \"tool_calls\": len(self.tools), \"tool_sha256\": self.tool_digest() if complete else None}\n\n\ndef token_equal(left, right):\n \"\"\"Missing token hashes or failed/incomplete streams are unverified, never an equality pass.\"\"\"\n if left.get(\"error\") or right.get(\"error\") or not left.get(\"complete\") or not right.get(\"complete\"):\n return None\n a, b = left.get(\"token_sha256\"), right.get(\"token_sha256\")\n if not all(isinstance(v, str) and re.fullmatch(r\"[0-9a-f]{64}\", v) for v in (a, b)):\n return None\n return a == b\n```\n\nThe same file with `token_equal` renamed to `same_tokens`, in full:\n```python\n" + }, + { + "name": "edit-bench_fill", + "kind": "completion", + "prompt": "Original file `bench_fill.py`:\n```python\n\"\"\"A long prompt filling beside a running reply: what each side waits, every reply checked against its run alone.\"\"\"\nimport argparse\nimport json\nimport math\nimport sys\nimport threading\nimport time\nimport urllib.request\n\nfrom bench_auth import authorize, read_api_key\nfrom bench_evidence import token_equal\nimport bench_openai as bench\n\nif sys.version_info < (3, 11):\n sys.exit(f\"Python 3.11+ is required (this is {sys.version.split()[0]}); \"\n \"TensorFold's tools use PEP 604 unions. Try: python3.12 tools/bench_fill.py ...\")\n\nREPLY = \"Explain how a hash map handles collisions, with a small worked example in Python, then compare the approaches.\"\nREPLY_LEAD_S = 0.5 # a reply is decoding this long after it is sent\n\n\ndef largest_gaps(pieces: list) -> tuple[float | None, float | None]:\n \"\"\"The 95th percentile and the largest ms between a reply's text pieces.\"\"\"\n gaps = sorted((b[0] - a[0]) * 1000 for a, b in zip(pieces, pieces[1:]))\n if not gaps:\n return None, None\n return round(gaps[max(0, math.ceil(len(gaps) * 0.95) - 1)], 1), round(gaps[-1], 1)\n\n\ndef row(reply: dict, long_: dict) -> dict:\n \"\"\"One order's waits; both_done_s counts from whichever request went first.\"\"\"\n p95, largest = largest_gaps(reply[\"pieces\"])\n done = max(reply[\"pieces\"][-1][0], long_[\"pieces\"][-1][0])\n return {\"reply_s\": round(reply[\"pieces\"][-1][0] - reply[\"sent\"], 2), \"long_ttft_s\": round(long_[\"ttft_s\"], 2),\n \"both_done_s\": round(done - min(reply[\"sent\"], long_[\"sent\"]), 2),\n \"reply_gap_p95_ms\": p95, \"reply_gap_max_ms\": largest}\n\n\ndef summary(alone: dict, reply_first: dict, long_first: dict) -> dict:\n \"\"\"Each order beside the two runs alone; a reply is exact only when its hash is known and equals its run alone.\"\"\"\n return {\"alone\": {\"reply_s\": round(alone[\"reply\"][\"pieces\"][-1][0] - alone[\"reply\"][\"sent\"], 2),\n \"long_ttft_s\": round(alone[\"long\"][\"ttft_s\"], 2)},\n \"reply_first\": row(reply_first[\"reply\"], reply_first[\"long\"]),\n \"long_first\": row(long_first[\"reply\"], long_first[\"long\"]),\n \"exact\": all(token_equal(alone[side], order[side]) is True\n for order in (reply_first, long_first) for side in (\"reply\", \"long\")),\n \"cold\": all(r[\"long\"][\"cached_tokens\"] == 0 for r in (alone, reply_first, long_first))}\n\n\ndef request(args, key, item, tokens) -> dict:\n \"\"\"One greedy streamed request, stamped with when it was sent.\"\"\"\n sent = time.perf_counter()\n return {**bench.stream(args.base, args.model, item, tokens, 0, 1234, api_key=key), \"sent\": sent}\n\n\ndef together(args, key, first: tuple, second: tuple, lead_s: float) -> tuple[dict, dict]:\n \"\"\"`first` under way for `lead_s`, then `second` beside it; the two receipts in that order.\"\"\"\n results = [None, None]\n\n def run(at, spec):\n results[at] = request(args, key, *spec)\n\n threads = [threading.Thread(target=run, args=(at, spec)) for at, spec in enumerate((first, second))]\n threads[0].start()\n time.sleep(lead_s)\n threads[1].start()\n for t in threads:\n t.join()\n return results[0], results[1]\n\n\ndef main() -> None:\n p = argparse.ArgumentParser(description=__doc__)\n p.add_argument(\"base\")\n p.add_argument(\"model\")\n p.add_argument(\"--corpus\", required=True, help=\"a text file of at least --long tokens\")\n p.add_argument(\"--long\", type=int, default=65536, help=\"the long prompt's tokens\")\n p.add_argument(\"--reply\", type=int, default=1024, help=\"the running reply's tokens\")\n p.add_argument(\"--lead\", type=float, default=5.0, help=\"seconds the long prompt fills before the reply is sent\")\n p.add_argument(\"--output\")\n p.add_argument(\"--api-key-env\", metavar=\"NAME\", help=\"read the bearer API key from this environment variable\")\n args = p.parse_args()\n key = read_api_key(p, args.api_key_env)\n with open(args.corpus, encoding=\"utf-8\", errors=\"replace\") as f:\n body = json.dumps({\"prompt\": f.read(), \"add_special_tokens\": False}).encode()\n req = urllib.request.Request(args.base + \"/tokenize\", body, {\"Content-Type\": \"application/json\"})\n authorize(req, key)\n with urllib.request.urlopen(req, timeout=600) as r:\n ids = json.load(r)[\"tokens\"]\n if len(ids) < args.long:\n p.exit(1, f\"the corpus has {len(ids)} tokens; --long needs {args.long}\\n\")\n long_ask = ({\"name\": \"long\", \"kind\": \"completion\", \"prompt\": ids[:args.long]}, 64)\n reply_ask = ({\"name\": \"reply\", \"kind\": \"chat\", \"prompt\": REPLY}, args.reply)\n request(args, key, reply_ask[0], 16) # a warm start, so no order pays for a cold one\n alone = {\"long\": request(args, key, *long_ask), \"reply\": request(args, key, *reply_ask)}\n reply, long_ = together(args, key, reply_ask, long_ask, REPLY_LEAD_S)\n long2, reply2 = together(args, key, long_ask, reply_ask, args.lead)\n report = summary(alone, {\"reply\": reply, \"long\": long_}, {\"reply\": reply2, \"long\": long2})\n print(json.dumps(report), flush=True)\n if args.output:\n with open(args.output, \"w\") as f:\n json.dump(report, f, indent=1)\n if not report[\"cold\"]:\n p.exit(1, \"the long prompt reused cached tokens: serve with --prompt-cache-gib 0\\n\")\n if not report[\"exact\"]:\n p.exit(1, \"a reply's tokens differ beside the other request\\n\")\n\n\nif __name__ == \"__main__\":\n main()\n```\n\nThe same file with the `main` function renamed to `run` and its call updated, in full:\n```python\n" + } +] diff --git a/tools/comfyui_runtime/README.md b/tools/comfyui_runtime/README.md new file mode 100644 index 00000000000..3f1ffd270cb --- /dev/null +++ b/tools/comfyui_runtime/README.md @@ -0,0 +1,79 @@ +# TensorFold runtime installer for ComfyUI + +This standalone Python CLI installs the latest stable TensorFold native CLI and builds the MOSS worker required by this integration. It uses only Python's standard library. ComfyUI nodes read the installed manifest and never check for updates or download code. + +## Install + +The first MOSS-only PR is scoped to experimental BF16 generation on Linux aarch64 with NVIDIA GB10, SM121. Use Python 3.10 or later, Git, Zig **0.17.0**, and a complete CUDA 13 toolchain with matching `nvcc`, NVVM, CRT and CCCL headers. + +SM120 is refused by name. `install` and `update` read every GPU's compute capability with `nvidia-smi --query-gpu=compute_cap --format=csv,noheader` before any download or build, and `run` reads it again before the worker starts. Any GPU other than 12.1 stops them with `MOSS ComfyUI generation is qualified on GB10 (sm_121) only; this GPU is sm_120` (naming the capability found). A capability that cannot be read, because `nvidia-smi` is missing, the driver lacks the field, it lists no GPU or it times out, is refused rather than assumed. The worker is compiled for sm_121 alone, with no sm_120 image or PTX, so its kernels cannot load on an SM120 GPU even when it is started directly. No SM120 workflow, numerical comparison or live kernel-contract check has run. Before this check, Linux x86_64 passed software tests and an actual native build on a CPU-only host; a host without an sm_121 GPU is now refused at install. Windows and macOS media installation fail before network access or builds. + +Generation also requires the NVIDIA driver and CUDA 13 cuBLASLt runtime libraries. The dynamic loader must find `libcuda.so.1` and `libcublasLt.so.13` (or `libcublasLt.so`) on its search path. An nvcc-only installation does not provide these generation prerequisites. + +```sh +python tools/comfyui_runtime/tensorfold_runtime.py install \ + --comfy-root /path/to/ComfyUI \ + --backend cuda \ + --zig /path/to/zig \ + --nvcc /usr/local/cuda/bin/nvcc +``` + +The command obtains the latest stable release from `ashhart/TensorFold`, matches the exact Linux archive and companion checksum, verifies the archive and every internally listed file, and builds the reviewed media revision below. Use ComfyUI's default `models` directory with this installer. It installs only under `ComfyUI/models/tensorfold`; no global packages, shell startup files or services are changed. Builds use two concurrent jobs and allow up to two hours for each native build command. The patched `moss-image-cuda` target builds only the three denoiser kernel images. This setup does not build unrelated model families. + +The standalone CLI version and media source are independent. The latest CLI archive does not contain the MOSS backend. Updating the CLI never silently changes the media source revision. + +## Compatibility pins + +| Component | Pin | +|---|---| +| TensorFold media source | `1ddac962008367ec2c50e10202c910ecf430b5eb` | +| Official source URL | `https://codeload.github.com/ashhart/TensorFold/tar.gz/1ddac962008367ec2c50e10202c910ecf430b5eb` | +| Source archive SHA-256 | `013d687c5b72718220ac8e137252492d72be85d27ff9cec37525d714c52dc2ba` | +| ComfyUI compatibility patch SHA-256 | `e6156ed11263a2d32586245b1702a6bc47ac0049e65bf1724afad69242eb617f` | +| Zig | `0.17.0`, checked against the source `.zig-version` | +| Compiled CUDA targets | `121` only (`-Dsm=121`); live generation validated on GB10 SM121 only | + +The bundled `tf_installer/moss-comfy.patch` is verified before application. It changes numerical materialization, reduction and cuBLASLt planning to match ComfyUI, adds a MOSS-only attention entrypoint, and adds the narrow build target. It is applied to the extracted build copy, including when that copy is nested inside a ComfyUI Git repository. The supplied checkout is never edited. `runtime.json` records both the source revision and patch digest. + +The source archive pin was taken from the exact official URL above. An optional `--source-archive /path/to/source.tar.gz` uses the same checksum verification. An optional `--source-checkout /path/to/TensorFold` requires the exact commit and a clean Git working tree, then builds an archive of tracked Git objects in a separate directory. Existing source checkouts are never built in place. + +## Run + +```sh +python tools/comfyui_runtime/tensorfold_runtime.py run --comfy-root /path/to/ComfyUI -- TRANSFORMER_DIR CASE OUT_DIR +``` + +`run` refuses any GPU but GB10 (sm_121), verifies the active manifest and the worker's SHA-256, then replaces itself with the installed `tf-moss-image`, passing the arguments after `--` unchanged. The worker never starts, and so never loads weights, on a refused GPU. + +## Updates and status + +```sh +python tools/comfyui_runtime/tensorfold_runtime.py update --comfy-root /path/to/ComfyUI --nvcc /usr/local/cuda/bin/nvcc +python tools/comfyui_runtime/tensorfold_runtime.py status --comfy-root /path/to/ComfyUI +``` + +`update` resolves the latest stable standalone engine automatically. If the installed engine, media revision and compatibility patch are current, it keeps the existing installation. An old manifest without the compatibility digest rebuilds MOSS before activation, including when the CLI version is unchanged. When only the standalone engine changes, it reuses the verified MOSS worker without requiring Zig or nvcc and without rebuilding them. Downgrades are refused. A changed media revision requires an explicitly updated integration release and its compatibility pin. If an existing installation fails integrity checks, `update` stops; `install` builds a verified replacement while preserving the old manifest until activation. + +`status` is offline: it checks the manifest, artifact SHA-256 values and required executable permissions without executing the engine, loading the library, querying a GPU or making network requests. If executable permissions are missing, `update` stops and `install` builds a replacement, including when the latest engine version is already installed. + +Each successful install occupies a new directory under `models/tensorfold/installs`. The installer checks the native CLI version and MOSS invocation contract before atomically replacing `runtime.json`. A failed download, hash verification, build or pre-activation probe leaves the previously active manifest intact. Failed-run logs remain under `models/tensorfold/logs/failed-*`, and the CLI prints their location. At most 16 logs of up to 1 MiB each are retained per failed run; larger logs keep their beginning and end. Existing install directories remain available while running ComfyUI processes finish using them. Stop and restart ComfyUI after an update to load the new worker. No automatic cleanup deletes older runtimes. + +The checksum files for the latest CLI are fetched from the same official release over HTTPS; they provide integrity and release consistency, not an independent publisher signature. Media source additionally has the fixed checksum above. Archive traversal, links, special files, duplicate members, extra unhashed files and excessive sizes are refused. + +## Verification + +```sh +python -m unittest discover -s tools/comfyui_runtime/tests -v +``` + +These tests exercise archive attacks, release metadata, exact source/toolchain pins, GPU admission at install and run, subprocess failures, deadlines and descendant cleanup, offline status, tampering and failed-build/activation preservation. They do not establish image correctness, GPU compatibility or performance. The installer makes no claim that its probes qualify real generation. + +## Prepare the official MOSS checkpoint + +The pinned native loader expects separate Q/K/V weights. ComfyUI's published BF16 MOSS checkpoint combines them. Convert that file once before selecting it in TensorFold MOSS Image: + +```sh +python tools/comfyui_runtime/prepare_moss.py moss_image_base_bf16.safetensors moss_image_base_tensorfold_bf16.safetensors +``` + +This offline command writes a new safetensors header and copies the original tensor payload unchanged. It uses bounded memory, needs about 10 GB of extra disk space, and refuses to overwrite an existing file. Keep the original checkpoint for standard ComfyUI comparisons. Existing unfused BF16 checkpoints need no conversion; INT8, FP8 and other quantized files are unsupported. diff --git a/tools/comfyui_runtime/prepare_moss.py b/tools/comfyui_runtime/prepare_moss.py new file mode 100644 index 00000000000..203a6cb19d8 --- /dev/null +++ b/tools/comfyui_runtime/prepare_moss.py @@ -0,0 +1,105 @@ +import argparse +import json +import math +import os +from pathlib import Path +import re +import shutil +import stat +import struct + + +QKV = re.compile(r"layers\.[0-9]+\.proj\.qkv\.weight") + + +def unique_object(pairs): + result = {} + for key, value in pairs: + if key in result: + raise ValueError(f"Duplicate checkpoint field: {key}") + result[key] = value + return result + + +def split_header(header, payload_size): + result, spans, count = {}, [], 0 + if not isinstance(header, dict): + raise ValueError("The safetensors header must be an object") + for name, tensor in header.items(): + if name == "__metadata__": + if not isinstance(tensor, dict) or any(not isinstance(value, str) for value in tensor.values()): + raise ValueError("Invalid checkpoint metadata") + result[name] = tensor + continue + if not isinstance(tensor, dict) or tensor.get("dtype") not in ("BF16", "F32"): + raise ValueError("MOSS preparation requires BF16 weights and F32 RoPE data") + shape, span = tensor.get("shape"), tensor.get("data_offsets") + if not isinstance(shape, list) or not shape or any(type(n) is not int or n <= 0 for n in shape): + raise ValueError(f"Invalid tensor shape: {name}") + size = math.prod(shape) * (2 if tensor["dtype"] == "BF16" else 4) + if not isinstance(span, list) or len(span) != 2 or any(type(n) is not int for n in span) or span[0] < 0 or span[1] - span[0] != size: + raise ValueError(f"Invalid tensor extent: {name}") + spans.append(span) + if QKV.fullmatch(name): + if tensor["dtype"] != "BF16" or len(shape) != 2 or shape[0] != 3 * shape[1]: + raise ValueError(f"Invalid fused QKV tensor: {name}") + width = size // 3 + for index, part in enumerate(("q", "k", "v")): + key = name.replace(".qkv.", f".{part}.") + if key in header: + raise ValueError("Checkpoint mixes fused and separate QKV tensors") + start = span[0] + index * width + result[key] = {"dtype": "BF16", "shape": [shape[1], shape[1]], "data_offsets": [start, start + width]} + count += 1 + else: + result[name] = tensor + end = 0 + for start, stop in sorted(spans): + if start != end: + raise ValueError("Tensor storage overlaps or contains a gap") + end = stop + if end != payload_size or not count: + raise ValueError("Checkpoint is truncated, has trailing data, or has no fused MOSS QKV weights") + return result + + +def prepare(source, output): + source, output = Path(source).resolve(strict=True), Path(output) + with source.open("rb") as incoming: + before = os.fstat(incoming.fileno()) + if not stat.S_ISREG(before.st_mode): + raise ValueError("The source must be a regular safetensors file") + length = incoming.read(8) + if len(length) != 8: + raise ValueError("Truncated safetensors header") + size = struct.unpack(" 1024 * 1024 or total > 16 * 1024 * 1024 or depth > 32: + raise InstallError("Archive metadata exceeds its size or nesting limit.") + archive._metadata_bytes = total + archive._metadata_depth = depth + try: + return reader(archive) + finally: + archive._metadata_depth -= 1 + + def _proc_pax(self, archive): + return self._metadata(archive, super()._proc_pax) + + def _proc_gnulong(self, archive): + return self._metadata(archive, super()._proc_gnulong) + + def _proc_sparse(self, archive): + raise InstallError("Sparse archive files are refused.") + + +def file_hash(path): + digest = hashlib.sha256() + with Path(path).open("rb") as source: + for block in iter(lambda: source.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def verify_hash(path, expected): + if not re.fullmatch(r"[a-f0-9]{64}", expected): + raise InstallError("Expected SHA-256 is malformed.") + actual = file_hash(path) + if actual != expected: + raise InstallError(f"SHA-256 mismatch for {Path(path).name}: {actual} != {expected}") + + +def relative_name(name): + if not isinstance(name, str) or not name or "\\" in name or "\0" in name or ":" in name: + raise InstallError("Unsafe archive path.") + parts = name.split("/") + if any(part in ("", ".", "..") for part in parts): + raise InstallError(f"Unsafe archive path: {name!r}") + return parts + + +def parse_sums(text): + sums = {} + for line in text.splitlines(): + if not line.strip(): + continue + match = re.fullmatch(r"([a-fA-F0-9]{64}) [ *](.+)", line) + if not match: + raise InstallError("Malformed SHA-256 checksum line.") + name = match[2] + if name.startswith("./"): + name = name[2:] + relative_name(name) + if name in sums: + raise InstallError(f"Duplicate checksum entry: {name}") + sums[name] = match[1].lower() + if not sums: + raise InstallError("Empty checksum manifest.") + return sums + + +def extract_archive(archive, destination, root_name, max_bytes=MAX_EXTRACTED_BYTES): + relative_name(root_name) + if "/" in root_name: + raise InstallError("Expected archive root must be one directory.") + destination = Path(destination) + destination.mkdir(mode=0o700) + seen = set() + files = set() + total = 0 + try: + with tarfile.open(archive, "r:*", tarinfo=BoundedTarInfo) as tar: + for member in tar: + name = member.name.rstrip("/") if member.isdir() else member.name + parts = relative_name(name) + if parts[0] != root_name: + raise InstallError("Archive member is outside its expected root.") + if name in seen: + raise InstallError(f"Duplicate archive member: {name}") + seen.add(name) + if len(seen) > 100000: + raise InstallError("Archive has too many members.") + if member.type not in (tarfile.REGTYPE, tarfile.AREGTYPE, tarfile.DIRTYPE) or member.sparse is not None: + raise InstallError("Archive links, sparse files and special files are refused.") + if member.size < 0 or (member.isdir() and member.size): + raise InstallError("Archive member has an invalid size.") + total += member.size + if member.size > 1024 * 1024 * 1024 or total > max_bytes: + raise InstallError("Archive exceeds its unpacked size limit.") + if len(parts) == 1 and not member.isdir(): + raise InstallError("Archive root is not a directory.") + target = destination.joinpath(*parts) + if member.isdir(): + target.mkdir(mode=0o755, parents=True, exist_ok=True) + continue + target.parent.mkdir(mode=0o755, parents=True, exist_ok=True) + with tar.extractfile(member) as source, target.open("xb") as output: + remaining = member.size + while remaining: + block = source.read(min(1024 * 1024, remaining)) + if not block: + raise InstallError("Archive member is truncated.") + output.write(block) + remaining -= len(block) + target.chmod(0o755 if member.mode & 0o111 else 0o644) + files.add("/".join(parts[1:])) + except (tarfile.TarError, EOFError, OSError) as error: + raise InstallError(f"Could not safely extract archive: {error}") from error + root = destination / root_name + if not files or not root.is_dir(): + raise InstallError("Archive is empty.") + return root, files + + +def verify_engine(root, files, version): + if "HOST-ONLY" in files: + raise InstallError("A host-only verification archive cannot run CUDA inference.") + required = {"bin/tensorfold-native", "SHA256SUMS", "VERSION", "LICENSE", "NOTICE", "THIRD_PARTY_NOTICES.md", "RUNTIME.md"} + if not required.issubset(files): + raise InstallError(f"Engine archive is missing required files: {sorted(required - files)}") + sums_file = root / "SHA256SUMS" + if sums_file.stat().st_size > 4 * 1024 * 1024: + raise InstallError("Engine checksum manifest is too large.") + sums = parse_sums(sums_file.read_text(encoding="utf-8")) + if set(sums) != files - {"SHA256SUMS"}: + raise InstallError("Engine archive and internal checksums name different files.") + for name, digest in sums.items(): + verify_hash(root / name, digest) + if (root / "VERSION").read_text(encoding="ascii").strip() != version: + raise InstallError("Engine archive VERSION differs from its release.") + executable = root / "bin/tensorfold-native" + if not executable.stat().st_mode & stat.S_IXUSR: + raise InstallError("Engine binary is not executable.") diff --git a/tools/comfyui_runtime/tf_installer/build.py b/tools/comfyui_runtime/tf_installer/build.py new file mode 100644 index 00000000000..a101ba96380 --- /dev/null +++ b/tools/comfyui_runtime/tf_installer/build.py @@ -0,0 +1,135 @@ +import os +import platform +import shutil +import signal +import subprocess +import sys +import time +from pathlib import Path + +from .archive import extract_archive, verify_hash +from .network import download +from .pins import InstallError, MAX_SOURCE_BYTES, MAX_SOURCE_EXTRACTED_BYTES, SOURCE_REVISION, SOURCE_PATCH_SHA256, SOURCE_ROOT, SOURCE_SHA256, SOURCE_URL, ZIG_VERSION + + +def host_platform(backend): + architecture = platform.machine().lower() + aliases = {"x86_64": "x86_64", "amd64": "x86_64", "aarch64": "aarch64", "arm64": "aarch64"} + if platform.system() != "Linux" or architecture not in aliases or backend != "cuda": + raise InstallError("Media companions currently support Linux x86_64/aarch64 with CUDA only. No files were downloaded or built.") + return "linux-" + aliases[architecture] + + +def executable(value, name): + selected = value or shutil.which(name) + if not selected: + raise InstallError(f"{name} was not found; supply its executable path.") + path = Path(selected).expanduser().resolve(strict=True) + if not path.is_file() or not os.access(path, os.X_OK): + raise InstallError(f"{name} is not an executable file.") + return str(path) + + +def stop_process_group(process): + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + try: + process.wait(timeout=5) + except subprocess.TimeoutExpired as error: + raise InstallError("Could not stop the installation subprocess group after SIGKILL.") from error + + +def run_command(arguments, cwd, log, timeout=3600, expected=0, environment=None): + log = Path(log) + environment = None if environment is None else {**os.environ, **environment} + with log.open("wb") as output: + process = subprocess.Popen(arguments, cwd=cwd, env=environment, stdin=subprocess.DEVNULL, stdout=output, stderr=subprocess.STDOUT, start_new_session=True) + deadline = time.monotonic() + timeout + failed = False + try: + while process.poll() is None: + if time.monotonic() >= deadline or log.stat().st_size > 64 * 1024 * 1024: + raise InstallError(f"{Path(arguments[0]).name} exceeded its time or log-size limit.") + time.sleep(0.1) + if process.returncode != expected: + with log.open("rb") as source: + source.seek(max(0, log.stat().st_size - 8192)) + detail = source.read().decode("utf-8", "replace") + raise InstallError(f"{Path(arguments[0]).name} exited {process.returncode}:\n{detail}") + except BaseException: + failed = True + raise + finally: + try: + stop_process_group(process) + except (OSError, InstallError) as error: + if not failed: + raise + print(f"TensorFold subprocess cleanup failed: {error}", file=sys.stderr) + with log.open("rb") as source: + text = source.read(65536).decode("utf-8", "replace").strip() + return text + ("\n[output truncated]" if log.stat().st_size > 65536 else "") + + +def check_toolchain(zig, nvcc, work, run=run_command): + zig = executable(zig, "zig") + nvcc = executable(nvcc, "nvcc") + actual = run([zig, "version"], work, work / "zig-version.log", timeout=15) + if actual != ZIG_VERSION: + raise InstallError(f"Pinned media source requires Zig {ZIG_VERSION}, found {actual!r}.") + run([nvcc, "--version"], work, work / "nvcc-version.log", timeout=15) + return zig, nvcc + + +def prepare_source(work, checkout=None, archive=None, fetch=download, run=run_command): + if checkout and archive: + raise InstallError("Select only one of --source-checkout and --source-archive.") + if checkout: + path = Path(checkout).expanduser().resolve(strict=True) + git = executable(None, "git") + prefix = [git, "--no-replace-objects", "-c", "core.fsmonitor=false", "-C", str(path)] + revision = run(prefix + ["rev-parse", "HEAD"], work, work / "source-head.log", timeout=15) + dirty = run(prefix + ["status", "--porcelain=v1", "--untracked-files=all"], work, work / "source-status.log", timeout=30) + if revision != SOURCE_REVISION or dirty: + raise InstallError(f"Source checkout must be clean and exactly {SOURCE_REVISION}.") + source_archive = work / "source.tar" + run(prefix + ["archive", "--format=tar", f"--prefix={SOURCE_ROOT}/", f"--output={source_archive}", SOURCE_REVISION], work, work / "source-archive.log", timeout=120) + else: + source_archive = Path(archive).expanduser().resolve(strict=True) if archive else fetch(SOURCE_URL, work / "source.tar.gz", MAX_SOURCE_BYTES) + if not source_archive.is_file() or source_archive.stat().st_size > MAX_SOURCE_BYTES: + raise InstallError("Pinned source archive is missing or too large.") + verify_hash(source_archive, SOURCE_SHA256) + source, _ = extract_archive(source_archive, work / "source-unpacked", SOURCE_ROOT, MAX_SOURCE_EXTRACTED_BYTES) + if (source / ".zig-version").read_text(encoding="ascii").strip() != ZIG_VERSION: + raise InstallError("Source .zig-version differs from the reviewed toolchain pin.") + return source + + +def apply_media_patch(source, work, run=run_command): + source_patch = Path(__file__).with_name("moss-comfy.patch").resolve(strict=True) + verify_hash(source_patch, SOURCE_PATCH_SHA256) + git = executable(None, "git") + environment = {"GIT_CEILING_DIRECTORIES": str(source.parent.resolve())} + run([git, "apply", "--check", str(source_patch)], source, work / "media-patch-check.log", timeout=30, environment=environment) + run([git, "apply", str(source_patch)], source, work / "media-patch.log", timeout=30, environment=environment) + + +def build_media(source, work, candidate, zig, nvcc, run=run_command): + apply_media_patch(source, work, run) + prefix = work / "built" + options = ["-j2", f"-Dnvcc={nvcc}", "-Dsm=121", "--prefix", str(prefix), "--cache-dir", str(work / "zig-cache")] + environment = {"ZIG_GLOBAL_CACHE_DIR": str(work / "zig-global-cache")} + run([zig, "build", "moss-image-cuda", *options], source, work / "moss-build.log", timeout=7200, environment=environment) + origin = prefix / "bin/tf-moss-image" + target = candidate / "media/bin/tf-moss-image" + if origin.is_symlink() or not origin.is_file() or origin.stat().st_size == 0: + raise InstallError("Build did not produce a regular MOSS companion.") + target.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(origin, target) + target.chmod(0o755) + usage = run([str(target)], work, work / "moss-probe.log", timeout=20, expected=2) + if "tf-moss-image TRANSFORMER_DIR CASE OUT_DIR" not in usage: + raise InstallError("MOSS companion does not expose the reviewed invocation contract.") + return {"moss": target} diff --git a/tools/comfyui_runtime/tf_installer/device.py b/tools/comfyui_runtime/tf_installer/device.py new file mode 100644 index 00000000000..527a7dde467 --- /dev/null +++ b/tools/comfyui_runtime/tf_installer/device.py @@ -0,0 +1,42 @@ +import re +import shutil +import subprocess + +from .pins import InstallError + +QUALIFIED_SM = 121 +QUALIFIED = "MOSS ComfyUI generation is qualified on GB10 (sm_121) only" + + +def nvidia_smi(timeout=15): + """Every GPU's compute capability as the NVIDIA driver reports it, one line a GPU.""" + tool = shutil.which("nvidia-smi") + if tool is None: + raise InstallError("nvidia-smi was not found") + try: + result = subprocess.run([tool, "--query-gpu=compute_cap", "--format=csv,noheader"], stdin=subprocess.DEVNULL, capture_output=True, timeout=timeout, check=False) + except subprocess.TimeoutExpired as error: + raise InstallError(f"nvidia-smi did not answer within {timeout} s") from error + if result.returncode != 0: + detail = result.stderr.decode("utf-8", "replace").strip() or result.stdout.decode("utf-8", "replace").strip() + raise InstallError(f"nvidia-smi exited {result.returncode}: {detail[:200]}") + return result.stdout.decode("utf-8", "replace") + + +def require_gb10(query=nvidia_smi): + """Refuse every GPU but sm_121 by name; a capability that cannot be read is refused, never assumed.""" + try: + lines = [line.strip() for line in query().splitlines() if line.strip()] + except (InstallError, OSError, UnicodeError) as error: + raise InstallError(f"{QUALIFIED}; this GPU's compute capability could not be read ({error}).") from error + if not lines: + raise InstallError(f"{QUALIFIED}; this GPU's compute capability could not be read (nvidia-smi listed no GPU).") + for index, line in enumerate(lines): + match = re.fullmatch(r"([0-9]{1,2})\.([0-9])", line) + if match is None: + raise InstallError(f"{QUALIFIED}; this GPU's compute capability could not be read ({line[:40]!r}).") + sm = int(match[1]) * 10 + int(match[2]) + if sm != QUALIFIED_SM: + which = "this GPU" if len(lines) == 1 else f"GPU {index} of {len(lines)}" + raise InstallError(f"{QUALIFIED}; {which} is sm_{sm}.") + return f"sm_{QUALIFIED_SM}" diff --git a/tools/comfyui_runtime/tf_installer/install.py b/tools/comfyui_runtime/tf_installer/install.py new file mode 100644 index 00000000000..a518cc397c4 --- /dev/null +++ b/tools/comfyui_runtime/tf_installer/install.py @@ -0,0 +1,197 @@ +import json +import os +import shutil +import stat +import uuid +from contextlib import contextmanager +from pathlib import Path + +try: + import fcntl +except ImportError: + fcntl = None + +from .archive import extract_archive, file_hash, relative_name, verify_engine, verify_hash +from .build import build_media, check_toolchain, host_platform, prepare_source, run_command +from .device import nvidia_smi, require_gb10 +from .logs import build_workspace +from .network import download, fetch_release, get_release, version_tuple +from .pins import InstallError, SOURCE_REVISION, SOURCE_PATCH_SHA256 + + +def runtime_root(comfy_root): + comfy = Path(comfy_root).expanduser().resolve(strict=True) + if not (comfy / "main.py").is_file() or not (comfy / "folder_paths.py").is_file(): + raise InstallError("--comfy-root must name a ComfyUI checkout containing main.py and folder_paths.py.") + root = comfy / "models/tensorfold" + if root.is_symlink(): + raise InstallError("TensorFold's managed runtime directory must not be a symlink.") + return root + + +def manifest_file(root, value, executable=False): + parts = relative_name(value) + path = root + for part in parts: + path = path / part + if path.is_symlink(): + raise InstallError("Runtime artifact paths must not contain symlinks.") + if not path.is_file() or executable and not path.stat().st_mode & stat.S_IXUSR: + raise InstallError(f"Runtime artifact is missing or not executable: {value}") + return path + + +def read_status(root): + path = root / "runtime.json" + if path.is_symlink() or not path.is_file() or path.stat().st_size > 65536: + raise InstallError("No valid runtime.json is installed.") + try: + data = json.loads(path.read_text(encoding="utf-8")) + if type(data["schema"]) is not int or data["schema"] != 1 or data["backend"] != "cuda" or data["source_revision"] != SOURCE_REVISION or data["platform"] not in ("linux-x86_64", "linux-aarch64"): + raise InstallError("Runtime manifest does not match this integration's compatibility contract.") + version_tuple(data["engine"]["version"]) + for item in (data["engine"], data["artifacts"]["moss"]): + verify_hash(manifest_file(root, item["path"], executable=True), item["sha256"]) + media = manifest_file(root, data["artifacts"]["moss"]["path"]).parent.parent + license_files(media / "licenses") + except (KeyError, TypeError, ValueError, UnicodeError) as error: + raise InstallError("Malformed runtime manifest.") from error + return data + + +@contextmanager +def install_lock(root): + if fcntl is None: + raise InstallError("Linux file locking is required for installation.") + fd = os.open(root / ".install.lock", os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW, 0o600) + try: + if not stat.S_ISREG(os.fstat(fd).st_mode): + raise InstallError("Unsafe installation lock.") + try: + fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) + except BlockingIOError as error: + raise InstallError("Another TensorFold installation is active.") from error + yield + finally: + os.close(fd) + + +def activate(root, candidate, manifest, replace=os.replace): + installs = root / "installs" + if installs.is_symlink(): + raise InstallError("Managed installs directory must not be a symlink.") + installs.mkdir(exist_ok=True) + name = f"{manifest['engine']['version']}-{SOURCE_REVISION[:12]}-{uuid.uuid4().hex}" + destination = installs / name + for item in (manifest["engine"], manifest["artifacts"]["moss"]): + item["path"] = f"installs/{name}/{item['path']}" + pending = root / f".runtime-{uuid.uuid4().hex}.json" + moved = False + try: + os.rename(candidate, destination) + moved = True + with pending.open("x", encoding="utf-8") as output: + json.dump(manifest, output, indent=2, sort_keys=True) + output.write("\n") + output.flush() + os.fsync(output.fileno()) + replace(pending, root / "runtime.json") + except BaseException: + pending.unlink(missing_ok=True) + if moved: + shutil.rmtree(destination) + raise + directory = os.open(root, os.O_RDONLY | os.O_DIRECTORY) + try: + os.fsync(directory) + finally: + os.close(directory) + return manifest + + +def license_files(source): + if source.is_symlink() or not source.is_dir(): + raise InstallError("Media licenses directory is missing or unsafe; use install to rebuild the pinned media.") + for name in ("LICENSE", "NOTICE", "THIRD_PARTY_NOTICES.md"): + origin = source / name + if origin.is_symlink() or not origin.is_file(): + raise InstallError("Media license files are missing or unsafe; use install to rebuild the pinned media.") + license_tree = source / "LICENSES" + if license_tree.is_symlink() or not license_tree.is_dir() or any(path.is_symlink() for path in license_tree.rglob("*")): + raise InstallError("Media license tree is missing or unsafe; use install to rebuild the pinned media.") + + +def copy_media_licenses(source, candidate): + license_files(source) + target = candidate / "media/licenses" + target.mkdir(parents=True) + for name in ("LICENSE", "NOTICE", "THIRD_PARTY_NOTICES.md"): + shutil.copyfile(source / name, target / name) + shutil.copytree(source / "LICENSES", target / "LICENSES") + + +def reuse_media(root, previous, candidate): + entry = previous["artifacts"]["moss"] + origin = manifest_file(root, entry["path"], executable=True) + target = candidate / "media/bin/tf-moss-image" + target.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(origin, target) + verify_hash(target, entry["sha256"]) + target.chmod(0o755) + copy_media_licenses(origin.parent.parent / "licenses", candidate) + return {"moss": target} + + +def install(comfy_root, backend="cuda", zig=None, nvcc=None, source_checkout=None, source_archive=None, action="install", fetch=download, run=run_command, builder=build_media, log=print, gpu=nvidia_smi): + platform = host_platform(backend) + try: + require_gb10(gpu) + except InstallError as error: + raise InstallError(f"{error} No files were downloaded or built.") from error + root = runtime_root(comfy_root) + root.mkdir(mode=0o700, parents=True, exist_ok=True) + with install_lock(root), build_workspace(root, log) as work: + old = None + if (root / "runtime.json").exists() or (root / "runtime.json").is_symlink(): + try: + old = read_status(root) + except (InstallError, OSError): + if action == "update": + raise InstallError("Installed runtime failed integrity checks; use install to build a verified replacement.") + log("Existing runtime failed verification; preparing a replacement before changing its manifest.") + if action == "update" and old is None: + raise InstallError("No runtime is installed; use install first.") + release = get_release(work, platform, fetch) + if old and version_tuple(release["version"]) < version_tuple(old["engine"]["version"]): + raise InstallError("Refusing to downgrade the active standalone engine.") + media_current = old and old.get("source_patch_sha256") == SOURCE_PATCH_SHA256 + if media_current and old["engine"]["version"] == release["version"] and old["platform"] == platform: + log(f"Already current: standalone engine {release['version']}; media source {SOURCE_REVISION}.") + return old + log(f"Installing standalone engine {release['version']}; media companions stay pinned to {SOURCE_REVISION}.") + version, archive, digest = fetch_release(work, release, fetch) + verify_hash(archive, digest) + engine, files = extract_archive(archive, work / "engine-unpacked", f"tensorfold-{version}-{platform}") + verify_engine(engine, files, version) + actual = run([str(engine / "bin/tensorfold-native"), "--version"], work, work / "engine-version.log", timeout=20) + if actual != f"tensorfold-native {version}": + raise InstallError("Downloaded native engine reports the wrong version.") + candidate = work / "candidate" + candidate.mkdir() + shutil.move(str(engine), candidate / "engine") + if media_current and old["platform"] == platform: + log("Reusing verified media companions from the unchanged source revision; no compiler is needed.") + artifacts = reuse_media(root, old, candidate) + else: + zig, nvcc = check_toolchain(zig, nvcc, work, run) + source = prepare_source(work, source_checkout, source_archive, fetch, run) + log("Building the pinned MOSS CUDA companion; the current runtime remains active until all probes pass.") + artifacts = builder(source, work, candidate, zig, nvcc, run) + copy_media_licenses(source, candidate) + native = candidate / "engine/bin/tensorfold-native" + manifest = {"schema": 1, "source_revision": SOURCE_REVISION, "source_patch_sha256": SOURCE_PATCH_SHA256, "platform": platform, "backend": backend, + "engine": {"version": version, "path": "engine/bin/tensorfold-native", "sha256": file_hash(native)}, + "artifacts": {name: {"path": str(path.relative_to(candidate)), "sha256": file_hash(path)} for name, path in artifacts.items()}} + result = activate(root, candidate, manifest) + log("Runtime activated. GPU generation and performance have not been verified by installation.") + return result diff --git a/tools/comfyui_runtime/tf_installer/logs.py b/tools/comfyui_runtime/tf_installer/logs.py new file mode 100644 index 00000000000..0d3ada14187 --- /dev/null +++ b/tools/comfyui_runtime/tf_installer/logs.py @@ -0,0 +1,46 @@ +from contextlib import contextmanager +from pathlib import Path +import tempfile + +from .pins import InstallError + + +MAX_LOG_BYTES = 1024 * 1024 +MAX_LOG_FILES = 16 + + +def preserve_logs(root, work): + files = [path for path in sorted(work.glob("*.log")) if not path.is_symlink() and path.is_file()][:MAX_LOG_FILES] + if not files: + return None + logs = root / "logs" + if logs.is_symlink(): + raise InstallError("The managed logs directory must not be a symlink.") + logs.mkdir(mode=0o700, exist_ok=True) + destination = Path(tempfile.mkdtemp(prefix="failed-", dir=logs)) + marker = b"\n[log truncated; first and last portions retained]\n" + for path in files: + with path.open("rb") as source: + data = source.read(MAX_LOG_BYTES + 1) + if len(data) > MAX_LOG_BYTES: + half = (MAX_LOG_BYTES - len(marker)) // 2 + source.seek(-half, 2) + data = data[:half] + marker + source.read(half) + (destination / path.name).write_bytes(data) + return destination + + +@contextmanager +def build_workspace(root, log): + with tempfile.TemporaryDirectory(prefix=".install-", dir=root) as directory: + work = Path(directory) + try: + yield work + except BaseException: + try: + saved = preserve_logs(root, work) + if saved is not None: + log(f"Installation logs saved to {saved}.") + except (OSError, InstallError) as error: + log(f"Could not preserve installation logs: {error}") + raise diff --git a/tools/comfyui_runtime/tf_installer/moss-comfy.patch b/tools/comfyui_runtime/tf_installer/moss-comfy.patch new file mode 100644 index 00000000000..58c61303c5e --- /dev/null +++ b/tools/comfyui_runtime/tf_installer/moss-comfy.patch @@ -0,0 +1,1874 @@ +diff --git a/LICENSES/FlashAttention-BSD-3.txt b/LICENSES/FlashAttention-BSD-3.txt +new file mode 100644 +index 0000000000000000000000000000000000000000..5860e4b33f3d9d85fc636137c559331d51783a5b +--- /dev/null ++++ b/LICENSES/FlashAttention-BSD-3.txt +@@ -0,0 +1,29 @@ ++BSD 3-Clause License ++ ++Copyright (c) 2022, the respective contributors, as shown by the AUTHORS file. ++All rights reserved. ++ ++Redistribution and use in source and binary forms, with or without ++modification, are permitted provided that the following conditions are met: ++ ++* Redistributions of source code must retain the above copyright notice, this ++ list of conditions and the following disclaimer. ++ ++* Redistributions in binary form must reproduce the above copyright notice, ++ this list of conditions and the following disclaimer in the documentation ++ and/or other materials provided with the distribution. ++ ++* Neither the name of the copyright holder nor the names of its ++ contributors may be used to endorse or promote products derived from ++ this software without specific prior written permission. ++ ++THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" ++AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ++IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ++DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE ++FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ++DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ++SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ++CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ++OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ++OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md +index 0cc42a93ea9ec5392740317512297da64304c657..cb01cff854ef47a6ce62a57a306b7eae7245950c 100644 +--- a/THIRD_PARTY_NOTICES.md ++++ b/THIRD_PARTY_NOTICES.md +@@ -382,3 +382,17 @@ seeded CPU generator, so that it makes the same latents bit for bit: + - `log256_ps` and `sincos256_ps` from `avx_mathfun.h`, which PyTorch includes (zlib license, Copyright (C) 2012 Giovanni + Garberoglio, based on Julien Pommier's `sse_mathfun.h`, Copyright (C) 2007; the license is in + `LICENSES/avx_mathfun-zlib.txt`). ++ ++ ++## MOSS ComfyUI numerical compatibility ++ ++The CUDA compatibility path follows the numerical conventions of PyTorch 2.14.1, ++Comfy Kitchen 0.2.41 and FlashAttention 2. PyTorch is Copyright (c) 2016- Facebook, ++Inc. and its affiliates, under BSD-3-Clause. Comfy Kitchen normalization and rotary ++kernels are Copyright (c) 2025 Comfy Org and NVIDIA CORPORATION & AFFILIATES, ++under Apache-2.0. FlashAttention is Copyright (c) 2023-2024 Tri Dao, under BSD-3-Clause. ++The existing BSD and Apache license texts are in LICENSES/. ++ ++References: https://github.com/pytorch/pytorch/tree/v2.14.1, ++https://github.com/Comfy-Org/comfy-kitchen/tree/v0.2.41, ++https://github.com/Dao-AILab/flash-attention. +diff --git a/zig/build/cuda.zig b/zig/build/cuda.zig +index cfb83c933bde66db56d34194530389ac201ba055..bdf07cdaf89e5d93de97920c81de1488c4c1aa4f 100644 +--- a/zig/build/cuda.zig ++++ b/zig/build/cuda.zig +@@ -138,9 +138,21 @@ pub fn targets(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.bu + b.getInstallStep().dependOn(&q35_install.step); + b.step("qwen35-cuda", "Build the Qwen CUDA forward and raw state receipt tool").dependOn(&q35_install.step); + // tf-moss-image: MOSS-Image's transformer on a reference case (tools/zig/moss_image_case.py), compared and timed +- const moss = b.createModule(.{ .root_source_file = b.path("zig/src/families/moss_image/cuda.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{ .{ .name = "cuda", .module = cuda }, .{ .name = "core", .module = mods.core } } }); +- const moss_tool = b.createModule(.{ .root_source_file = b.path("zig/tests/moss_image_cuda.zig"), .target = target, .optimize = optimize, .link_libc = true, .strip = strip, .imports = &.{ .{ .name = "cuda", .module = cuda }, .{ .name = "core", .module = mods.core }, .{ .name = "moss_image", .module = moss } } }); +- b.installArtifact(b.addExecutable(.{ .name = "tf-moss-image", .root_module = moss_tool })); ++ var moss_images = images; ++ for (kernels, &moss_images) |kernel, *image| { ++ if (!std.mem.eql(u8, kernel.name, "moss_image") and !std.mem.eql(u8, kernel.name, "vit") and !std.mem.eql(u8, kernel.name, "prefill_attention")) image.* = null; ++ } ++ const moss_cuda = runtime(b, target, optimize, if (nvcc != null or prebuilt != null) &moss_images else &.{}); ++ const moss = b.createModule(.{ .root_source_file = b.path("zig/src/families/moss_image/cuda.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{ .{ .name = "cuda", .module = moss_cuda }, .{ .name = "core", .module = mods.core } } }); ++ const moss_tool = b.createModule(.{ .root_source_file = b.path("zig/tests/moss_image_cuda.zig"), .target = target, .optimize = optimize, .link_libc = true, .strip = strip, .imports = &.{ .{ .name = "cuda", .module = moss_cuda }, .{ .name = "core", .module = mods.core }, .{ .name = "moss_image", .module = moss } } }); ++ const moss_install = b.addInstallArtifact(b.addExecutable(.{ .name = "tf-moss-image", .root_module = moss_tool }), .{}); ++ b.getInstallStep().dependOn(&moss_install.step); ++ b.step("moss-image-cuda", "Build the MOSS-Image CUDA denoiser").dependOn(&moss_install.step); ++ const moss_contract = b.createModule(.{ .root_source_file = b.path("zig/tests/cuda/moss_contract_main.zig"), .target = target, .optimize = optimize, .link_libc = true, .strip = strip, .imports = &.{ .{ .name = "cuda", .module = moss_cuda }, .{ .name = "core", .module = mods.core }, .{ .name = "moss_image_cuda", .module = b.createModule(.{ .root_source_file = b.path("zig/src/families/moss_image/cuda_kernels.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{.{ .name = "cuda", .module = moss_cuda }} }) } } }); ++ moss_contract.addAnonymousImport("fatbin_contract_controls", .{ .root_source_file = controls orelse b.addWriteFiles().add("moss_no_controls.fatbin", "") }); ++ const moss_contract_install = b.addInstallArtifact(b.addExecutable(.{ .name = "tf-moss-contract", .root_module = moss_contract }), .{}); ++ b.step("moss-image-contract", "Build the complete MOSS CUDA kernel-contract runner").dependOn(&moss_contract_install.step); ++ + const d3_tool = b.createModule(.{ .root_source_file = b.path("zig/src/families/drama3/generate.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{ .{ .name = "core", .module = mods.core }, .{ .name = "drama3", .module = @import("drama3_host.zig").module(b, target, optimize, cuda, mods.core) } } }); + const d3_exe = b.addExecutable(.{ .name = "drama3-generate", .root_module = d3_tool }); + b.step("drama3-generate", "Drama generation and replay controls on CUDA").dependOn(&b.addInstallArtifact(d3_exe, .{}).step); +diff --git a/zig/build/cuda_runtime.zig b/zig/build/cuda_runtime.zig +index daa3ea94cce0f79ff993ada166cc5a9e9385118c..ce38f4dda566a95483dba9d4c354693a6271b6a0 100644 +--- a/zig/build/cuda_runtime.zig ++++ b/zig/build/cuda_runtime.zig +@@ -5,16 +5,18 @@ pub fn stagger(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.bu + return b.createModule(.{ .root_source_file = b.path("zig/src/core/stagger.zig"), .target = target, .optimize = optimize }); + } + +-/// The runtime module for `target`; `with_kernels` false builds it host-only (empty images). ++/// The runtime module for `target`; selected images are lazy imports, and no images builds it host-only. + pub fn runtime(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, images: []const ?std.Build.LazyPath) *std.Build.Module { + const options = b.addOptions(); +- var with = images.len > 0; +- for (images) |i| with = with and i != null; ++ var with = false; ++ for (images) |i| with = with or i != null; + options.addOption(bool, "with_kernels", with); + const cuda = b.createModule(.{ .root_source_file = b.path("zig/src/cuda/root.zig"), .target = target, .optimize = optimize, .link_libc = true }); + cuda.addImport("gpu_memory", @import("gpu_memory.zig").module(b, target)); + cuda.addOptions("kernel_options", options); + cuda.addImport("stagger", stagger(b, target, optimize)); +- if (with) for (@import("cuda_kernels.zig").kernels, images) |k, image| cuda.addAnonymousImport(b.fmt("fatbin_{s}", .{k.name}), .{ .root_source_file = image.? }); ++ if (with) for (@import("cuda_kernels.zig").kernels, images) |k, image| { ++ if (image) |file| cuda.addAnonymousImport(b.fmt("fatbin_{s}", .{k.name}), .{ .root_source_file = file }); ++ }; + return cuda; + } +diff --git a/zig/kernels/cuda/contract_controls.cu b/zig/kernels/cuda/contract_controls.cu +index 63ff744b4754364d20627c38dc91279901d5eb42..383ac033f5a13a231c7421df079d50216d81d6b2 100644 +--- a/zig/kernels/cuda/contract_controls.cu ++++ b/zig/kernels/cuda/contract_controls.cu +@@ -365,7 +365,7 @@ extern "C" __global__ void __launch_bounds__(128) tf_ctl_pocket_in_fmax(const __ + act[static_cast(r) * 64 + j] = z * z; + } + } +-// Gate 3: moss_image.cu's steps, each with one of the publisher's bf16 points dropped; their range checks must go red. ++// MOSS arithmetic controls change one required materialization or scalar. + namespace tf_ctl_moss { + typedef __nv_bfloat16 bf16; + __device__ __forceinline__ float bf(float x) { return __bfloat162float(__float2bfloat16_rn(x)); } +@@ -374,25 +374,53 @@ __device__ __forceinline__ float warp_sum(float v) { + for (int o = 16; o > 0; o >>= 1) v += __shfl_xor_sync(0xffffffffu, v, o); + return v; + } +-// tf_moss_norm; DROP 0: bf16(x inv), 1: bf16(y s). ++// Norm faults: add normalized BF16, or omit folded-scale BF16. + template + __device__ void norm(const bf16* X, const bf16* W, const bf16* S, const bf16* B, bf16* Y, int width, float eps, + int modulated) { + __shared__ float part[8]; + const bf16* x = X + (size_t)blockIdx.x * width; + bf16* y = Y + (size_t)blockIdx.x * width; ++ // Match the reference's row reduction and rsqrt, including its small-row path. ++ const bool warp_row = modulated && gridDim.x <= 1024; ++ const int threads = warp_row ? 32 : (modulated ? 256 : 128); ++ if (threadIdx.x >= threads) return; + float a = 0.0f; +- for (int i = threadIdx.x; i < width; i += 256) a += ld(x + i) * ld(x + i); +- a = warp_sum(a); +- if ((threadIdx.x & 31) == 0) part[threadIdx.x >> 5] = a; +- __syncthreads(); +- float total = 0.0f; +- for (int w = 0; w < 8; ++w) total += part[w]; +- const float inv = 1.0f / sqrtf(total / (float)width + eps); +- for (int i = threadIdx.x; i < width; i += 256) { +- const float xn = ld(x + i) * inv; +- float v = bf((DROP == 0 ? xn : bf(xn)) * ld(W + i)); +- if (modulated) v = (DROP == 1 ? v * ld(S + i) : bf(v * ld(S + i))) + ld(B + i); ++ if (warp_row) { ++ for (int i = threadIdx.x; i < width; i += 32) a = fmaf(ld(x + i), ld(x + i), a); ++ } else { ++ const int vector = modulated ? 8 : 4; ++ for (int base = threadIdx.x * vector; base < width; base += threads * vector) ++ for (int j = 0; j < vector && base + j < width; ++j) { ++ const float value = ld(x + base + j); ++ a = fmaf(value, value, a); ++ } ++ } ++ for (int offset = 16; offset; offset >>= 1) a += __shfl_down_sync(0xffffffffu, a, offset); ++ float total; ++ if (warp_row) { ++ total = __shfl_sync(0xffffffffu, a, 0); ++ } else { ++ if ((threadIdx.x & 31) == 0) part[threadIdx.x >> 5] = a; ++ __syncthreads(); ++ total = 0.0f; ++ if (modulated) { ++ for (int w = 0; w < 8; ++w) total += part[w]; ++ } else { ++ // PyTorch's vectorized RMSNorm merges four warps as a tree. ++ for (int step = 2; step; step >>= 1) { ++ if (threadIdx.x < step) part[threadIdx.x] += part[threadIdx.x + step]; ++ __syncthreads(); ++ } ++ total = part[0]; ++ } ++ } ++ const float inv = rsqrtf(modulated ? fmaf(total, 1.0f / width, eps) : total / width + eps); ++ for (int i = threadIdx.x; i < width; i += threads) { ++ const float raw = ld(x + i) * inv; ++ const float normalized = DROP == 0 ? bf(raw) : raw; ++ const float folded = modulated ? (DROP == 1 ? bf(ld(W + i) * ld(S + i)) - 1.0f : bf(bf(ld(W + i) * ld(S + i)) - 1.0f)) : 0.0f; ++ const float v = modulated ? fmaf(normalized, 1.0f + folded, ld(B + i)) : normalized * ld(W + i); + y[i] = __float2bfloat16_rn(v); + } + } +@@ -412,8 +440,8 @@ extern "C" __global__ void __launch_bounds__(256) tf_ctl_moss_norm_scale(const _ + tf_ctl_moss::norm<1>(X, W, S, B, Y, width, eps, modulated); + } + +-// tf_moss_qk without bf16(q cos). +-extern "C" __global__ void __launch_bounds__(256) tf_ctl_moss_qk_cos(const __nv_bfloat16* QR, const __nv_bfloat16* KR, ++// An extra normalized-query BF16 point before the learned weight is the fault. ++extern "C" __global__ void __launch_bounds__(256) tf_ctl_moss_qk_normalized(const __nv_bfloat16* QR, const __nv_bfloat16* KR, + const __nv_bfloat16* VR, const __nv_bfloat16* NQ, + const __nv_bfloat16* NK, const float* CS, + const float* SN, __nv_bfloat16* QKV, int rows, +@@ -421,32 +449,36 @@ extern "C" __global__ void __launch_bounds__(256) tf_ctl_moss_qk_cos(const __nv_ + using namespace tf_ctl_moss; + const int r = blockIdx.x, h = blockIdx.y * 8 + (threadIdx.x >> 5), lane = threadIdx.x & 31; + if (h >= heads || r >= rows) return; +- const size_t from = (size_t)r * stride + h * 128 + lane * 4; ++ const size_t from = (size_t)r * stride + h * 128 + lane; + float q[4], k[4], qq = 0.0f, kk = 0.0f; ++#pragma unroll + for (int i = 0; i < 4; ++i) { +- q[i] = ld(QR + from + i); +- k[i] = ld(KR + from + i); +- qq += q[i] * q[i]; +- kk += k[i] * k[i]; ++ q[i] = ld(QR + from + i * 32); ++ k[i] = ld(KR + from + i * 32); ++ qq = fmaf(q[i], q[i], qq); ++ kk = fmaf(k[i], k[i], kk); + } +- const float qn = 1.0f / sqrtf(warp_sum(qq) / 128.0f + eps); +- const float kn = 1.0f / sqrtf(warp_sum(kk) / 128.0f + eps); ++#pragma unroll ++ for (int offset = 16; offset; offset >>= 1) { ++ qq += __shfl_down_sync(0xffffffffu, qq, offset); ++ kk += __shfl_down_sync(0xffffffffu, kk, offset); ++ } ++ const float qn = rsqrtf(fmaf(__shfl_sync(0xffffffffu, qq, 0), 1.0f / 128.0f, eps)); ++ const float kn = rsqrtf(fmaf(__shfl_sync(0xffffffffu, kk, 0), 1.0f / 128.0f, eps)); ++#pragma unroll + for (int i = 0; i < 4; ++i) { +- q[i] = bf(bf(q[i] * qn) * ld(NQ + lane * 4 + i)); +- k[i] = bf(bf(k[i] * kn) * ld(NK + lane * 4 + i)); ++ q[i] = bf(bf(q[i] * qn) * ld(NQ + lane + i * 32)); ++ k[i] = bf((k[i] * kn) * ld(NK + lane + i * 32)); + } +- const float sign = lane < 16 ? -1.0f : 1.0f; +- bf16* qo = QKV + (size_t)r * 3 * heads * 128 + h * 128 + lane * 4; +- bf16* ko = qo + heads * 128; +- bf16* vo = ko + heads * 128; ++ const size_t row = (size_t)r * 3 * heads * 128 + h * 128 + lane; ++#pragma unroll + for (int i = 0; i < 4; ++i) { +- const float qp = sign * __shfl_xor_sync(0xffffffffu, q[i], 16); +- const float kp = sign * __shfl_xor_sync(0xffffffffu, k[i], 16); +- const int j = (lane & 15) * 4 + i; +- const float c = CS[(size_t)r * 64 + j], s = SN[(size_t)r * 64 + j]; +- qo[i] = __float2bfloat16_rn(q[i] * c + bf(qp * s)); +- ko[i] = __float2bfloat16_rn(bf(k[i] * c) + bf(kp * s)); +- vo[i] = VR[from + i]; ++ const float sign = i < 2 ? -1.0f : 1.0f; ++ const int pair = lane + (i & 1) * 32; ++ const float c = CS[(size_t)r * 64 + pair], s = SN[(size_t)r * 64 + pair]; ++ QKV[row + i * 32] = __float2bfloat16_rn((i < 2 ? fmaf(q[i], c, (sign * q[i ^ 2]) * s) : fmaf(sign * q[i ^ 2], s, q[i] * c))); ++ QKV[row + heads * 128 + i * 32] = __float2bfloat16_rn((i < 2 ? fmaf(k[i], c, (sign * k[i ^ 2]) * s) : fmaf(sign * k[i ^ 2], s, k[i] * c))); ++ QKV[row + 2 * heads * 128 + i * 32] = VR[from + i * 32]; + } + } + +@@ -465,7 +497,7 @@ extern "C" __global__ void __launch_bounds__(256) tf_ctl_moss_situ_sigmoid(const + O[(size_t)r * width + c] = __float2bfloat16_rn(left * right); + } + +-// tf_moss_gate_add without bf16(g y). ++// An extra BF16 product breaks the fused residual. + extern "C" __global__ void __launch_bounds__(256) tf_ctl_moss_gate_add_product(__nv_bfloat16* X, const __nv_bfloat16* Y, + const __nv_bfloat16* G, int width, + int rows) { +@@ -473,7 +505,7 @@ extern "C" __global__ void __launch_bounds__(256) tf_ctl_moss_gate_add_product(_ + const int c = blockIdx.y * 256 + threadIdx.x, r = blockIdx.x; + if (c >= width || r >= rows) return; + const size_t i = (size_t)r * width + c; +- X[i] = __float2bfloat16_rn(ld(X + i) + ld(G + c) * ld(Y + i)); ++ X[i] = __float2bfloat16_rn(bf(ld(G + c) * ld(Y + i)) + ld(X + i)); + } + // Gate 3: main's tf_exl3_plan_finish (PlanStage without alpha), the baseline, and two SwiGLU-OAI faults that go red. + #include "exl3_plan.cuh" +@@ -538,3 +570,26 @@ TF_CTL_EXL3_GROUPED(tf_ctl_exl3_grouped_old_2, 2, tf_exl3::PLAIN) + TF_CTL_EXL3_GROUPED(tf_ctl_exl3_grouped_skip, 2, tf_exl3::SKIP) + TF_CTL_EXL3_GROUPED(tf_ctl_exl3_grouped_stale, 2, tf_exl3::STALE) + #undef TF_CTL_EXL3_GROUPED ++ ++// MOSS elementwise controls deliberately change one output formula. ++extern "C" __global__ void __launch_bounds__(256) tf_ctl_moss_bias_tail(__nv_bfloat16* x, const __nv_bfloat16* b, int width, int rows) { ++ const int c = blockIdx.y * 256 + threadIdx.x, r = blockIdx.x; ++ if (c + 1 < width && r < rows) { const size_t i = (size_t)r * width + c; x[i] = __float2bfloat16_rn(__bfloat162float(x[i]) + __bfloat162float(b[c])); } ++} ++extern "C" __global__ void tf_ctl_moss_silu_identity(__nv_bfloat16* x, int width) { ++ const int i = blockIdx.x * blockDim.x + threadIdx.x; ++ if (i < width) x[i] = __float2bfloat16_rn(__bfloat162float(x[i])); ++} ++extern "C" __global__ void tf_ctl_moss_modulation_scale(const __nv_bfloat16* shared, __nv_bfloat16* out, int width) { ++ const int i = blockIdx.x * blockDim.x + threadIdx.x; ++ if (i >= width) return; ++ const int from[8] = {1, 0, 2, 4, 3, 5, 7, 6}; ++ for (int v = 0; v < 8; ++v) out[v * width + i] = shared[from[v] * width + i]; ++ out[8 * width + i] = __float2bfloat16_rn(1.0f); ++} ++extern "C" __global__ void tf_ctl_moss_time_phase(__nv_bfloat16* out, float timestep) { ++ const int i = threadIdx.x; ++ const float phase = 0.5f * timestep * expf((-9.210340371976184f * i) / 128.0f); ++ out[i] = __float2bfloat16_rn(cosf(phase)); ++ out[128 + i] = __float2bfloat16_rn(sinf(phase)); ++} +diff --git a/zig/kernels/cuda/moss_image.cu b/zig/kernels/cuda/moss_image.cu +index 402af740c989fec7960784b5d951f603d332b290..008468e5a85539bc873d994331f7d17f84d5b72d 100644 +--- a/zig/kernels/cuda/moss_image.cu ++++ b/zig/kernels/cuda/moss_image.cu +@@ -1,4 +1,4 @@ +-// MOSS-Image's glue on CUDA: moss_image.metal's kernels op for op, rounded where the publisher's torch code rounds. ++// MOSS-Image's ComfyUI CUDA arithmetic, with explicit BF16 materialization and FMA boundaries. + #include + #include + +@@ -19,7 +19,7 @@ __device__ __forceinline__ float warp_sum(float v) { + + using namespace tf_moss; + +-// y = bf16(bf16(x * rsqrt(mean(x^2) + eps)) * w), then if modulated bf16(bf16(y * s) + b); a block of 256 a row. ++// Match Torch RMSNorm or Comfy Kitchen RMS-AdaLN, including their distinct reduction orders. + extern "C" __global__ void __launch_bounds__(256) tf_moss_norm(const bf16* __restrict__ X, const bf16* __restrict__ W, + const bf16* __restrict__ S, const bf16* __restrict__ B, + bf16* __restrict__ Y, int width, float eps, +@@ -27,18 +27,45 @@ extern "C" __global__ void __launch_bounds__(256) tf_moss_norm(const bf16* __res + __shared__ float part[8]; + const bf16* x = X + (size_t)blockIdx.x * width; + bf16* y = Y + (size_t)blockIdx.x * width; ++ // Match the reference's row reduction and rsqrt, including its small-row path. ++ const bool warp_row = modulated && gridDim.x <= 1024; ++ const int threads = warp_row ? 32 : (modulated ? 256 : 128); ++ if (threadIdx.x >= threads) return; + float a = 0.0f; +- for (int i = threadIdx.x; i < width; i += 256) a += ld(x + i) * ld(x + i); +- a = warp_sum(a); +- if ((threadIdx.x & 31) == 0) part[threadIdx.x >> 5] = a; +- __syncthreads(); +- float total = 0.0f; +-#pragma unroll +- for (int w = 0; w < 8; ++w) total += part[w]; +- const float inv = 1.0f / sqrtf(total / (float)width + eps); +- for (int i = threadIdx.x; i < width; i += 256) { +- float v = bf(bf(ld(x + i) * inv) * ld(W + i)); +- if (modulated) v = bf(v * ld(S + i)) + ld(B + i); ++ if (warp_row) { ++ for (int i = threadIdx.x; i < width; i += 32) a = fmaf(ld(x + i), ld(x + i), a); ++ } else { ++ const int vector = modulated ? 8 : 4; ++ for (int base = threadIdx.x * vector; base < width; base += threads * vector) ++ for (int j = 0; j < vector && base + j < width; ++j) { ++ const float value = ld(x + base + j); ++ a = fmaf(value, value, a); ++ } ++ } ++ for (int offset = 16; offset; offset >>= 1) a += __shfl_down_sync(0xffffffffu, a, offset); ++ float total; ++ if (warp_row) { ++ total = __shfl_sync(0xffffffffu, a, 0); ++ } else { ++ if ((threadIdx.x & 31) == 0) part[threadIdx.x >> 5] = a; ++ __syncthreads(); ++ total = 0.0f; ++ if (modulated) { ++ for (int w = 0; w < 8; ++w) total += part[w]; ++ } else { ++ // PyTorch's vectorized RMSNorm merges four warps as a tree. ++ for (int step = 2; step; step >>= 1) { ++ if (threadIdx.x < step) part[threadIdx.x] += part[threadIdx.x + step]; ++ __syncthreads(); ++ } ++ total = part[0]; ++ } ++ } ++ const float inv = rsqrtf(modulated ? fmaf(total, 1.0f / width, eps) : total / width + eps); ++ for (int i = threadIdx.x; i < width; i += threads) { ++ const float normalized = ld(x + i) * inv; ++ const float folded = modulated ? bf(bf(ld(W + i) * ld(S + i)) - 1.0f) : 0.0f; ++ const float v = modulated ? fmaf(normalized, 1.0f + folded, ld(B + i)) : normalized * ld(W + i); + y[i] = __float2bfloat16_rn(v); + } + } +@@ -51,37 +78,36 @@ extern "C" __global__ void __launch_bounds__(256) tf_moss_qk(const bf16* __restr + int rows, int heads, int stride, float eps) { + const int r = blockIdx.x, h = blockIdx.y * 8 + (threadIdx.x >> 5), lane = threadIdx.x & 31; + if (h >= heads || r >= rows) return; +- const size_t from = (size_t)r * stride + h * 128 + lane * 4; ++ const size_t from = (size_t)r * stride + h * 128 + lane; + float q[4], k[4], qq = 0.0f, kk = 0.0f; + #pragma unroll + for (int i = 0; i < 4; ++i) { +- q[i] = ld(QR + from + i); +- k[i] = ld(KR + from + i); +- qq += q[i] * q[i]; +- kk += k[i] * k[i]; ++ q[i] = ld(QR + from + i * 32); ++ k[i] = ld(KR + from + i * 32); ++ qq = fmaf(q[i], q[i], qq); ++ kk = fmaf(k[i], k[i], kk); ++ } ++#pragma unroll ++ for (int offset = 16; offset; offset >>= 1) { ++ qq += __shfl_down_sync(0xffffffffu, qq, offset); ++ kk += __shfl_down_sync(0xffffffffu, kk, offset); + } +- const float qn = 1.0f / sqrtf(warp_sum(qq) / 128.0f + eps); +- const float kn = 1.0f / sqrtf(warp_sum(kk) / 128.0f + eps); ++ const float qn = rsqrtf(fmaf(__shfl_sync(0xffffffffu, qq, 0), 1.0f / 128.0f, eps)); ++ const float kn = rsqrtf(fmaf(__shfl_sync(0xffffffffu, kk, 0), 1.0f / 128.0f, eps)); + #pragma unroll + for (int i = 0; i < 4; ++i) { +- q[i] = bf(bf(q[i] * qn) * ld(NQ + lane * 4 + i)); +- k[i] = bf(bf(k[i] * kn) * ld(NK + lane * 4 + i)); ++ q[i] = bf((q[i] * qn) * ld(NQ + lane + i * 32)); ++ k[i] = bf((k[i] * kn) * ld(NK + lane + i * 32)); + } +- // lane l holds channels 4l..4l+3; its partner half sits 16 lanes away. The first half turns by -partner. +- const float sign = lane < 16 ? -1.0f : 1.0f; +- const size_t row = (size_t)r * 3 * heads * 128; +- bf16* qo = QKV + row + h * 128 + lane * 4; +- bf16* ko = qo + heads * 128; +- bf16* vo = ko + heads * 128; ++ const size_t row = (size_t)r * 3 * heads * 128 + h * 128 + lane; + #pragma unroll + for (int i = 0; i < 4; ++i) { +- const float qp = sign * __shfl_xor_sync(0xffffffffu, q[i], 16); +- const float kp = sign * __shfl_xor_sync(0xffffffffu, k[i], 16); +- const int j = (lane & 15) * 4 + i; +- const float c = CS[(size_t)r * 64 + j], s = SN[(size_t)r * 64 + j]; +- qo[i] = __float2bfloat16_rn(bf(q[i] * c) + bf(qp * s)); +- ko[i] = __float2bfloat16_rn(bf(k[i] * c) + bf(kp * s)); +- vo[i] = VR[from + i]; ++ const float sign = i < 2 ? -1.0f : 1.0f; ++ const int pair = lane + (i & 1) * 32; ++ const float c = CS[(size_t)r * 64 + pair], s = SN[(size_t)r * 64 + pair]; ++ QKV[row + i * 32] = __float2bfloat16_rn((i < 2 ? fmaf(q[i], c, (sign * q[i ^ 2]) * s) : fmaf(sign * q[i ^ 2], s, q[i] * c))); ++ QKV[row + heads * 128 + i * 32] = __float2bfloat16_rn((i < 2 ? fmaf(k[i], c, (sign * k[i ^ 2]) * s) : fmaf(sign * k[i ^ 2], s, k[i] * c))); ++ QKV[row + 2 * heads * 128 + i * 32] = VR[from + i * 32]; + } + } + +@@ -105,5 +131,39 @@ extern "C" __global__ void __launch_bounds__(256) tf_moss_gate_add(bf16* __restr + const int c = blockIdx.y * 256 + threadIdx.x, r = blockIdx.x; + if (c >= width || r >= rows) return; + const size_t i = (size_t)r * width + c; +- X[i] = __float2bfloat16_rn(ld(X + i) + bf(ld(G + c) * ld(Y + i))); ++ X[i] = __float2bfloat16_rn(fmaf(ld(G + c), ld(Y + i), ld(X + i))); ++} ++ ++extern "C" __global__ void __launch_bounds__(256) tf_moss_bias_add(bf16* __restrict__ X, const bf16* __restrict__ B, ++ int width, int rows) { ++ const int c = blockIdx.y * 256 + threadIdx.x, r = blockIdx.x; ++ if (c >= width || r >= rows) return; ++ const size_t i = (size_t)r * width + c; ++ X[i] = __float2bfloat16_rn(ld(X + i) + ld(B + c)); ++} ++ ++// Match ComfyUI's float32 sinusoid, then materialize BF16 before the time MLP. ++extern "C" __global__ void tf_moss_time(bf16* out, float timestep) { ++ const int i = threadIdx.x; ++ const float frequency = expf((-9.210340371976184f * i) / 128.0f); ++ const float phase = timestep * frequency; ++ out[i] = __float2bfloat16_rn(cosf(phase)); ++ out[128 + i] = __float2bfloat16_rn(sinf(phase)); ++} ++ ++extern "C" __global__ void tf_moss_silu(bf16* x, int width) { ++ const int i = blockIdx.x * blockDim.x + threadIdx.x; ++ if (i < width) { const float v = ld(x + i); x[i] = __float2bfloat16_rn(v / (1.0f + expf(-v))); } ++} ++ ++// shared is shift, scale, gate for attention and MLP, followed by head shift, scale. ++extern "C" __global__ void tf_moss_modulation(const bf16* shared, bf16* out, int width) { ++ const int i = blockIdx.x * blockDim.x + threadIdx.x; ++ if (i >= width) return; ++ const int from[8] = {1, 0, 2, 4, 3, 5, 7, 6}; ++ for (int v = 0; v < 8; ++v) { ++ const float value = ld(shared + from[v] * width + i); ++ out[v * width + i] = __float2bfloat16_rn(value + ((v == 0 || v == 3 || v == 6) ? 1.0f : 0.0f)); ++ } ++ out[8 * width + i] = __float2bfloat16_rn(1.0f); + } +diff --git a/zig/kernels/cuda/prefill_attention.cu b/zig/kernels/cuda/prefill_attention.cu +index 2719004affabad632c1dc2c19b3add8a5929804f..da6bc4c11292a4cb5808319bbad8ac09cfc82d8d 100644 +--- a/zig/kernels/cuda/prefill_attention.cu ++++ b/zig/kernels/cuda/prefill_attention.cu +@@ -187,9 +187,8 @@ hpattn8_kernel(const __nv_bfloat16* __restrict__ q, const uint8_t* __restrict__ + } + + // full_kernel's row arithmetic, one barrier a 64-key tile: two buffers of odd-padded rows, the next tile loading. +-template +-__global__ void __launch_bounds__(32 * WARPS) +-vision_kernel(const __nv_bfloat16* __restrict__ qkv, __nv_bfloat16* __restrict__ out, int W, int HO, float scale) { ++template ++__device__ __forceinline__ void image_kernel_body(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[]; +@@ -225,11 +224,14 @@ vision_kernel(const __nv_bfloat16* __restrict__ qkv, __nv_bfloat16* __restrict__ + #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) { ++ // MOSS follows FlashAttention's reverse key-tile traversal. ++ constexpr bool reverse = COMFY; ++ stage(reverse ? tiles - 1 : 0); ++ for (int tile = 0; tile < tiles; ++tile) { ++ const int t = reverse ? tiles - 1 - tile : tile; + cp_wait<0>(); + __syncthreads(); // tile t landed, and every warp is done with tile t - 1 +- if (t + 1 < tiles) stage(t + 1); ++ if (tile + 1 < tiles) stage(reverse ? t - 1 : t + 1); + const uint4* ks = smem + (t & 1) * 2 * BN * RS; + const uint4* vs = ks + BN * RS; + float sc[NT][4]; +@@ -253,10 +255,10 @@ vision_kernel(const __nv_bfloat16* __restrict__ qkv, __nv_bfloat16* __restrict__ + #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; ++ sc[n][0] = c <= last ? (reverse ? sc[n][0] : __fmul_rn(sc[n][0], scale)) : -INFINITY; ++ sc[n][1] = c + 1 <= last ? (reverse ? sc[n][1] : __fmul_rn(sc[n][1], scale)) : -INFINITY; ++ sc[n][2] = c <= last ? (reverse ? sc[n][2] : __fmul_rn(sc[n][2], scale)) : -INFINITY; ++ sc[n][3] = c + 1 <= last ? (reverse ? sc[n][3] : __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])); + } +@@ -266,21 +268,33 @@ vision_kernel(const __nv_bfloat16* __restrict__ qkv, __nv_bfloat16* __restrict__ + } + 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; ++ const float a0 = act0 ? (m0 == -INFINITY ? 0.0f : (reverse ? exp2f(__fmul_rn(__fsub_rn(m0, n0), __fmul_rn(scale, LOG2E))) : texp(__fsub_rn(m0, n0)))) : 1.0f; ++ const float a1 = act1 ? (m1 == -INFINITY ? 0.0f : (reverse ? exp2f(__fmul_rn(__fsub_rn(m1, n1), __fmul_rn(scale, LOG2E))) : 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; ++ sc[n][0] = act0 && c <= last ? (reverse ? exp2f(__fsub_rn(__fmul_rn(sc[n][0], __fmul_rn(scale, LOG2E)), __fmul_rn(n0, __fmul_rn(scale, LOG2E)))) : texp(__fsub_rn(sc[n][0], n0))) : 0.0f; ++ sc[n][1] = act0 && c + 1 <= last ? (reverse ? exp2f(__fsub_rn(__fmul_rn(sc[n][1], __fmul_rn(scale, LOG2E)), __fmul_rn(n0, __fmul_rn(scale, LOG2E)))) : texp(__fsub_rn(sc[n][1], n0))) : 0.0f; ++ sc[n][2] = act1 && c <= last ? (reverse ? exp2f(__fsub_rn(__fmul_rn(sc[n][2], __fmul_rn(scale, LOG2E)), __fmul_rn(n1, __fmul_rn(scale, LOG2E)))) : texp(__fsub_rn(sc[n][2], n1))) : 0.0f; ++ sc[n][3] = act1 && c + 1 <= last ? (reverse ? exp2f(__fsub_rn(__fmul_rn(sc[n][3], __fmul_rn(scale, LOG2E)), __fmul_rn(n1, __fmul_rn(scale, LOG2E)))) : 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)); ++ if constexpr (reverse) { ++ l0 = __fmaf_rn(l0, a0, sc[0][0]); ++ l1 = __fmaf_rn(l1, a1, sc[0][2]); ++ l0 = __fadd_rn(l0, sc[0][1]); ++ l1 = __fadd_rn(l1, sc[0][3]); ++#pragma unroll ++ for (int n = 1; n < NT; ++n) { ++ l0 = __fadd_rn(__fadd_rn(l0, sc[n][0]), sc[n][1]); ++ l1 = __fadd_rn(__fadd_rn(l1, sc[n][2]), sc[n][3]); ++ } ++ } else { ++ l0 = __fmaf_rn(l0, a0, rowsum(c0)); ++ l1 = __fmaf_rn(l1, a1, rowsum(c1)); ++ } + m0 = n0; + m1 = n1; + #pragma unroll +@@ -303,18 +317,38 @@ vision_kernel(const __nv_bfloat16* __restrict__ qkv, __nv_bfloat16* __restrict__ + } + } + } ++ if constexpr (reverse) { ++ l0 = __fadd_rn(l0, __shfl_xor_sync(0xffffffffu, l0, 2)); ++ l1 = __fadd_rn(l1, __shfl_xor_sync(0xffffffffu, l1, 2)); ++ l0 = __fadd_rn(l0, __shfl_xor_sync(0xffffffffu, l0, 1)); ++ l1 = __fadd_rn(l1, __shfl_xor_sync(0xffffffffu, l1, 1)); ++ } + #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)); ++ pack((reverse ? __fmul_rn(o[i][0], 1.0f / l0) : tdiv(o[i][0], l0)), (reverse ? __fmul_rn(o[i][1], 1.0f / 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)); ++ pack((reverse ? __fmul_rn(o[i][2], 1.0f / l1) : tdiv(o[i][2], l1)), (reverse ? __fmul_rn(o[i][3], 1.0f / l1) : tdiv(o[i][3], l1))); + } + } + ++ ++// The canonical vision path keeps its traversal and rounding. MOSS uses ComfyUI's FlashAttention order. ++template ++__global__ void __launch_bounds__(32 * WARPS) ++vision_kernel(const __nv_bfloat16* qkv, __nv_bfloat16* out, int rows, int heads, float scale) { ++ image_kernel_body(qkv, out, rows, heads, scale); ++} ++ ++template ++__global__ void __launch_bounds__(32 * WARPS) ++moss_kernel(const __nv_bfloat16* qkv, __nv_bfloat16* out, int rows, int heads, float scale) { ++ image_kernel_body(qkv, out, rows, heads, scale); ++} ++ + } // namespace tf_prefill_attention + + // Head dim 128, eight warps, eight query heads a block, eight staging slots (Nemotron's 16 heads a KV head). +@@ -348,3 +382,5 @@ template __global__ void tf_prefill_attention::hpattn_whole_kernel<256, 8, 2, 2> + template __global__ void tf_prefill_attention::hpattn8_whole_kernel<256, 8, 2, 2>(const __nv_bfloat16* __restrict__, + const uint8_t* __restrict__, const uint8_t* __restrict__, const float* __restrict__, const float* __restrict__, + __nv_bfloat16* __restrict__, int, int, int, int, int, float, int); ++ ++template __global__ void tf_prefill_attention::moss_kernel<128, 8>(const __nv_bfloat16*, __nv_bfloat16*, int, int, float); +diff --git a/zig/src/core/contract/gates.zig b/zig/src/core/contract/gates.zig +index e00e23f6b25a957fb53316b327519d49a1221259..a815417a16b1cdd66056a5fff1180fa278023ced 100644 +--- a/zig/src/core/contract/gates.zig ++++ b/zig/src/core/contract/gates.zig +@@ -49,10 +49,16 @@ pub const VTable = struct { + check: ?*const fn (*anyopaque, Gate) anyerror!?[]const u8 = null, + /// A replacement's baseline: the replaced kernel's bytes on the prepared inputs. + replaced: ?*const fn (*anyopaque) anyerror![]const u8 = null, ++ /// Frees the device buffers and host copies the last `prepare` left; called once a kernel's gates are done. ++ release: ?*const fn (*anyopaque) void = null, + }; + + /// The VTable of a test type T: its prepare, run, count and reference, its `rig`'s bytes, and the optional hooks. + pub fn hooks(comptime T: type) VTable { ++ const Rig = switch (@typeInfo(@FieldType(T, "rig"))) { ++ .pointer => |p| p.child, ++ else => @FieldType(T, "rig"), ++ }; + const H = struct { + fn of(ctx: *anyopaque) *T { + return @ptrCast(@alignCast(ctx)); +@@ -96,6 +102,9 @@ pub fn hooks(comptime T: type) VTable { + fn replaced(ctx: *anyopaque) anyerror![]const u8 { + return of(ctx).replaced(); + } ++ fn release(ctx: *anyopaque) void { ++ if (@hasDecl(Rig, "finishGates")) of(ctx).rig.finishGates() else of(ctx).rig.reset(); ++ } + }; + return .{ + .prepare = H.prepare, +@@ -111,6 +120,7 @@ pub fn hooks(comptime T: type) VTable { + .simulate = if (@hasDecl(T, "simulate")) H.simulate else null, + .check = if (@hasDecl(T, "check")) H.check else null, + .replaced = if (@hasDecl(T, "replaced")) H.replaced else null, ++ .release = if (@hasDecl(Rig, "reset")) H.release else null, + }; + } + +@@ -310,7 +320,7 @@ pub fn sums(a: std.mem.Allocator, k: Kernel, seed: u64) !Verdict { + const q = misses(got, want, allow); + if (!(q <= 1)) return say(.fail, .sums, s.name, "{d:.1}x over its exact-sum bound at k {d}: not fp32 sums (fp16 would miss {d:.0}x, bf16 {d:.0}x)", .{ q, shape.k, margin[0], margin[1] }); + if (need[1] == 0 or need[0] == 0) return say(.pass, .sums, s.name, "within its bound at k {d}; fp16 sums would miss {d:.0}x, bf16 {d:.1}x ({s})", .{ shape.k, margin[0], margin[1], s.sums.why }); +- return say(.pass, .sums, s.name, "exact sums at k {d}, where fp16 sums would miss by {d:.0}x and bf16 by {d:.0}x", .{ shape.k, margin[0], margin[1] }); ++ return say(.pass, .sums, s.name, "{s} at k {d}, where fp16 sums would miss by {d:.0}x and bf16 by {d:.0}x", .{ if (s.sums.exact) "exact sums" else "FP32 sums within their derived bound", shape.k, margin[0], margin[1] }); + } + + /// A kernel's or control's gates 1-4; a control must fail its own gate and passes when it does. +@@ -341,6 +351,7 @@ 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| { ++ defer if (k.vt.release) |free| free(k.ctx); + const s = std.hash.Wyhash.hash(seed, k.spec.name); + if (k.control) |g| { + t.controls += 1; +diff --git a/zig/src/core/contract/moss_image_cuda_records.zig b/zig/src/core/contract/moss_image_cuda_records.zig +index d810c8dd5d5c8230294b12e78e68d0fbdcbb4888..855c9ad7f96926cc37373d2956b3214730003eb2 100644 +--- a/zig/src/core/contract/moss_image_cuda_records.zig ++++ b/zig/src/core/contract/moss_image_cuda_records.zig +@@ -1,13 +1,18 @@ + //! MOSS-Image's CUDA launches: its own steps (moss_image.cu) and full attention at head dim 128. + const registry = @import("registry.zig"); + +-/// nvcc 13.0's usage, the compiler of the release fatbins; nvcc 13.2 compiles each the same. ++/// nvcc 13.0 compile records for the MOSS compatibility build. + pub const cuda = [_]registry.CudaRecord{ +- .{ .launch = .{ .name = "moss_image tf_moss_norm", .symbol = "tf_moss_norm", .image = "moss_image", .threads = 256 }, .usage = .{ .{ .regs = 32, .static = 32, .bound = 256 }, .{ .regs = 34, .static = 32, .bound = 256 }, .{ .regs = 34, .static = 32, .bound = 256 }, .{ .regs = 33, .static = 32, .bound = 256 }, .{ .regs = 33, .static = 32, .bound = 256 } } }, +- .{ .launch = .{ .name = "moss_image tf_moss_qk", .symbol = "tf_moss_qk", .image = "moss_image", .threads = 256 }, .usage = .{ .{ .regs = 32, .static = 0, .bound = 256 }, .{ .regs = 40, .static = 0, .bound = 256 }, .{ .regs = 40, .static = 0, .bound = 256 }, .{ .regs = 40, .static = 0, .bound = 256 }, .{ .regs = 40, .static = 0, .bound = 256 } } }, +- .{ .launch = .{ .name = "moss_image tf_moss_situ", .symbol = "tf_moss_situ", .image = "moss_image", .threads = 256 }, .usage = .{ .{ .regs = 18, .static = 0, .bound = 256 }, .{ .regs = 18, .static = 0, .bound = 256 }, .{ .regs = 18, .static = 0, .bound = 256 }, .{ .regs = 17, .static = 0, .bound = 256 }, .{ .regs = 17, .static = 0, .bound = 256 } } }, +- .{ .launch = .{ .name = "moss_image tf_moss_gate_add", .symbol = "tf_moss_gate_add", .image = "moss_image", .threads = 256 }, .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 } } }, +- .{ .launch = .{ .name = "vit vision_kernel<128, 8> (MOSS-Image)", .symbol = "_ZN20tf_prefill_attention13vision_kernelILi128ELi8EEEvPK13__nv_bfloat16PS1_iif", .image = "prefill_attention", .threads = 256, .dynamic = 69632, .opt_in = true }, .usage = .{ .{ .regs = 178, .static = 0, .bound = 256 }, .{ .regs = 178, .static = 0, .bound = 256 }, .{ .regs = 178, .static = 0, .bound = 256 }, .{ .regs = 170, .static = 0, .bound = 256 }, .{ .regs = 170, .static = 0, .bound = 256 } } }, ++ .{ .launch = .{ .name = "moss_image tf_moss_norm", .symbol = "tf_moss_norm", .image = "moss_image", .threads = 256 }, .usage = .{ .{ .regs = 30, .static = 32, .bound = 256, .local = 0 }, .{ .regs = 37, .static = 32, .bound = 256, .local = 0 }, .{ .regs = 37, .static = 32, .bound = 256, .local = 0 }, .{ .regs = 40, .static = 32, .bound = 256, .local = 0 }, .{ .regs = 40, .static = 32, .bound = 256, .local = 0 } } }, ++ .{ .launch = .{ .name = "moss_image tf_moss_qk", .symbol = "tf_moss_qk", .image = "moss_image", .threads = 256 }, .usage = .{ .{ .regs = 32, .static = 0, .bound = 256, .local = 0 }, .{ .regs = 40, .static = 0, .bound = 256, .local = 0 }, .{ .regs = 40, .static = 0, .bound = 256, .local = 0 }, .{ .regs = 40, .static = 0, .bound = 256, .local = 0 }, .{ .regs = 40, .static = 0, .bound = 256, .local = 0 } } }, ++ .{ .launch = .{ .name = "moss_image tf_moss_situ", .symbol = "tf_moss_situ", .image = "moss_image", .threads = 256 }, .usage = .{ .{ .regs = 18, .static = 0, .bound = 256, .local = 0 }, .{ .regs = 18, .static = 0, .bound = 256, .local = 0 }, .{ .regs = 18, .static = 0, .bound = 256, .local = 0 }, .{ .regs = 17, .static = 0, .bound = 256, .local = 0 }, .{ .regs = 17, .static = 0, .bound = 256, .local = 0 } } }, ++ .{ .launch = .{ .name = "moss_image tf_moss_gate_add", .symbol = "tf_moss_gate_add", .image = "moss_image", .threads = 256 }, .usage = .{ .{ .regs = 10, .static = 0, .bound = 256, .local = 0 }, .{ .regs = 10, .static = 0, .bound = 256, .local = 0 }, .{ .regs = 10, .static = 0, .bound = 256, .local = 0 }, .{ .regs = 14, .static = 0, .bound = 256, .local = 0 }, .{ .regs = 14, .static = 0, .bound = 256, .local = 0 } } }, ++ .{ .launch = .{ .name = "vit vision_kernel<128, 8> (MOSS-Image)", .symbol = "_ZN20tf_prefill_attention13vision_kernelILi128ELi8EEEvPK13__nv_bfloat16PS1_iif", .image = "prefill_attention", .threads = 256, .dynamic = 69632, .opt_in = true }, .usage = .{ .{ .regs = 178, .static = 0, .bound = 256, .local = 0 }, .{ .regs = 178, .static = 0, .bound = 256, .local = 0 }, .{ .regs = 178, .static = 0, .bound = 256, .local = 0 }, .{ .regs = 170, .static = 0, .bound = 256, .local = 0 }, .{ .regs = 170, .static = 0, .bound = 256, .local = 0 } } }, ++ .{ .launch = .{ .name = "moss_image tf_moss_bias_add", .symbol = "tf_moss_bias_add", .image = "moss_image", .threads = 256 }, .usage = .{ .{ .regs = 10, .static = 0, .bound = 256, .local = 0 }, .{ .regs = 10, .static = 0, .bound = 256, .local = 0 }, .{ .regs = 10, .static = 0, .bound = 256, .local = 0 }, .{ .regs = 12, .static = 0, .bound = 256, .local = 0 }, .{ .regs = 12, .static = 0, .bound = 256, .local = 0 } } }, ++ .{ .launch = .{ .name = "moss_image tf_moss_time", .symbol = "tf_moss_time", .image = "moss_image", .threads = 128 }, .usage = .{ .{ .regs = 19, .static = 0, .bound = 0, .local = 0 }, .{ .regs = 19, .static = 0, .bound = 0, .local = 0 }, .{ .regs = 19, .static = 0, .bound = 0, .local = 0 }, .{ .regs = 23, .static = 0, .bound = 0, .local = 0 }, .{ .regs = 23, .static = 0, .bound = 0, .local = 0 } } }, ++ .{ .launch = .{ .name = "moss_image tf_moss_silu", .symbol = "tf_moss_silu", .image = "moss_image", .threads = 256 }, .usage = .{ .{ .regs = 16, .static = 0, .bound = 0, .local = 0 }, .{ .regs = 16, .static = 0, .bound = 0, .local = 0 }, .{ .regs = 16, .static = 0, .bound = 0, .local = 0 }, .{ .regs = 16, .static = 0, .bound = 0, .local = 0 }, .{ .regs = 16, .static = 0, .bound = 0, .local = 0 } } }, ++ .{ .launch = .{ .name = "moss_image tf_moss_modulation", .symbol = "tf_moss_modulation", .image = "moss_image", .threads = 256 }, .usage = .{ .{ .regs = 19, .static = 0, .bound = 0, .local = 0 }, .{ .regs = 19, .static = 0, .bound = 0, .local = 0 }, .{ .regs = 19, .static = 0, .bound = 0, .local = 0 }, .{ .regs = 20, .static = 0, .bound = 0, .local = 0 }, .{ .regs = 20, .static = 0, .bound = 0, .local = 0 } } }, ++ .{ .launch = .{ .name = "moss_image moss_kernel<128, 8>", .symbol = "_ZN20tf_prefill_attention11moss_kernelILi128ELi8EEEvPK13__nv_bfloat16PS1_iif", .image = "prefill_attention", .threads = 256, .dynamic = 69632, .opt_in = true }, .usage = .{ .{ .regs = 194, .static = 0, .bound = 256, .local = 0 }, .{ .regs = 194, .static = 0, .bound = 256, .local = 0 }, .{ .regs = 194, .static = 0, .bound = 256, .local = 0 }, .{ .regs = 174, .static = 0, .bound = 256, .local = 0 }, .{ .regs = 174, .static = 0, .bound = 256, .local = 0 } } }, + }; + + test "MOSS-Image CUDA: every launch is in the live registry and fits every SM" { +diff --git a/zig/src/core/contract/registry.zig b/zig/src/core/contract/registry.zig +index 8e8e10c965ac5afd9f9bd67b503983e8c13e5e3b..c7bb536ebe68458a513679f0f62564c1b5156d2f 100644 +--- a/zig/src/core/contract/registry.zig ++++ b/zig/src/core/contract/registry.zig +@@ -13,6 +13,7 @@ pub const CudaRecord = struct { + /// Keep the independent later compiler selection when adding a late 13.0 receipt. + later_pending: bool = false, + }; ++pub const moss_cuda = @import("moss_image_cuda_records.zig").cuda; + const target = @import("registry_target.zig"); + pub const TargetDecision = target.TargetDecision; + pub const targetDecision = target.targetDecision; +diff --git a/zig/src/core/contract/seed_test.zig b/zig/src/core/contract/seed_test.zig +index 7b613b6326705ac5e5de20a166390fdb0ab72f06..9136d3ab2b0a611eddf6889d9a3671a1c4f537c1 100644 +--- a/zig/src/core/contract/seed_test.zig ++++ b/zig/src/core/contract/seed_test.zig +@@ -4,8 +4,17 @@ const g = @import("gates.zig"); + const c = @import("contract.zig"); + const Probe = struct { + seed: u64 = 0, ++ buffer: ?[]u8 = null, ++ previous: ?*Probe = null, ++ fn release(p: *anyopaque) void { ++ const self: *Probe = @ptrCast(@alignCast(p)); ++ if (self.buffer) |buffer| std.testing.allocator.free(buffer); ++ self.buffer = null; ++ } + fn prepare(p: *anyopaque, _: c.Shape, _: g.Fill, s: u64) anyerror!bool { + const self: *Probe = @ptrCast(@alignCast(p)); ++ if (self.previous) |previous| std.debug.assert(previous.buffer == null); ++ if (self.buffer == null) self.buffer = try std.testing.allocator.alloc(u8, 64); + self.seed = s; + return false; + } +@@ -31,7 +40,7 @@ const Probe = struct { + return 0; + } + fn kernel(p: *Probe, name: []const u8) g.Kernel { +- return .{ .spec = .{ .name = name, .accum = .none, .out = .raw, .depth = depth, .served = &.{.{ .rows = 1, .n = 1, .k = 1 }}, .tiles = .{ .{}, .{}, .{} } }, .ctx = p, .vt = &.{ .prepare = prepare, .run = run, .output = bytes, .inputs = bytes, .intact = intact, .overlap = overlap, .count = count, .reference = reference } }; ++ return .{ .spec = .{ .name = name, .accum = .none, .out = .raw, .depth = depth, .served = &.{.{ .rows = 1, .n = 1, .k = 1 }}, .tiles = .{ .{}, .{}, .{} } }, .ctx = p, .vt = &.{ .prepare = prepare, .run = run, .output = bytes, .inputs = bytes, .intact = intact, .overlap = overlap, .count = count, .reference = reference, .release = release } }; + } + }; + test "contract seed: an inserted kernel cannot change another named fixture's seed" { +@@ -47,3 +56,15 @@ test "contract seed: an inserted kernel cannot change another named fixture's se + try std.testing.expectEqual(before, target.seed); + try std.testing.expect(inserted.seed != target.seed); + } ++ ++test "contract release: prior kernel buffers are freed before the next prepares" { ++ const was = g.quiet; ++ g.quiet = true; ++ defer g.quiet = was; ++ var a: Probe = .{}; ++ var b: Probe = .{ .previous = &a }; ++ var tally: g.Tally = .{}; ++ try g.runAll(std.testing.allocator, &.{ a.kernel("first"), b.kernel("second") }, 0x6b63, &tally); ++ try std.testing.expect(a.buffer == null); ++ try std.testing.expect(b.buffer == null); ++} +diff --git a/zig/src/cuda/cublaslt.zig b/zig/src/cuda/cublaslt.zig +index c620786cb54bd54cbaa9c997b1489d0d908010ce..5fdaa686b42f62003c3b751b9c3ffef33e472f74 100644 +--- a/zig/src/cuda/cublaslt.zig ++++ b/zig/src/cuda/cublaslt.zig +@@ -151,14 +151,24 @@ pub const Linear = struct { + errdefer _ = lt.api.cublasLtMatmulPreferenceDestroy(self.pref); + const limit: u64 = workspace_limit; + try lt.check(lt.api.cublasLtMatmulPreferenceSetAttribute(self.pref, pref_max_workspace_bytes, &limit, @sizeOf(u64)), "set workspace"); ++ self.epilogue = epilogue; ++ if (epilogue != .none) { ++ const e: u32 = @backingInt(epilogue); ++ try lt.check(lt.api.cublasLtMatmulDescSetAttribute(self.desc, desc_epilogue, &e, @sizeOf(u32)), "set epilogue"); ++ } + var found: [1]Heuristic = undefined; + var count: c_int = 0; + try lt.check(lt.api.cublasLtMatmulAlgoGetHeuristic(self.handle, self.desc, self.a, self.b, self.c, self.c, self.pref, 1, &found, &count), "cublasLtMatmulAlgoGetHeuristic"); ++ if ((count < 1 or found[0].state != 0) and epilogue != .none) { ++ const none: u32 = @backingInt(Epilogue.none); ++ try lt.check(lt.api.cublasLtMatmulDescSetAttribute(self.desc, desc_epilogue, &none, @sizeOf(u32)), "unset epilogue"); ++ self.epilogue = .none; ++ try lt.check(lt.api.cublasLtMatmulAlgoGetHeuristic(self.handle, self.desc, self.a, self.b, self.c, self.c, self.pref, 1, &found, &count), "cublasLtMatmulAlgoGetHeuristic"); ++ } + if (count < 1 or found[0].state != 0) return error.NoAlgorithm; + self.algo = found[0].algo; + self.workspace_need = found[0].workspace_size; +- self.epilogue = .none; +- if (epilogue != .none) try self.fuse(epilogue, workspace_limit); ++ if (epilogue != .none and self.epilogue == .none) try self.fuse(epilogue, workspace_limit); + return self; + } + +diff --git a/zig/src/cuda/vit.zig b/zig/src/cuda/vit.zig +index f7acecdc15357c54762847fcaa44baf9d748eb45..89115a94b387b9d9e64754af379f663a176c932d 100644 +--- a/zig/src/cuda/vit.zig ++++ b/zig/src/cuda/vit.zig +@@ -193,12 +193,19 @@ pub const Gemms = struct { + gpa: Allocator, + lt: cublaslt.Library, + workspace: memory.DeviceBuffer, ++ bias_workspace_bytes: usize, + plans: std.AutoHashMapUnmanaged([3]u64, Linear) = .empty, + + pub fn init(gpa: Allocator, d: *const Driver) !Gemms { ++ return initWithBiasWorkspace(gpa, d, workspace_bytes); ++ } ++ ++ /// A separate bias workspace reproduces the reference's cuBLASLt addmm policy. ++ pub fn initWithBiasWorkspace(gpa: Allocator, d: *const Driver, bias_workspace_bytes: usize) !Gemms { ++ if (bias_workspace_bytes == 0 or bias_workspace_bytes > workspace_bytes) return error.BadWorkspaceSize; + var lt = try cublaslt.Library.open(); + errdefer lt.close(); +- return .{ .gpa = gpa, .lt = lt, .workspace = try memory.DeviceBuffer.alloc(d, workspace_bytes) }; ++ return .{ .gpa = gpa, .lt = lt, .workspace = try memory.DeviceBuffer.alloc(d, workspace_bytes), .bias_workspace_bytes = bias_workspace_bytes }; + } + + pub fn deinit(g: *Gemms) void { +@@ -211,7 +218,7 @@ pub const Gemms = struct { + + /// y [rows, n] = x [rows, k] . w [n, k]^T, f32 accumulation, `out` rows. + pub fn run(g: *Gemms, s: Stream, x: u64, w: u64, y: u64, rows: usize, n: usize, k: usize, out: cublaslt.DataType) !void { +- try (try g.plan(rows, n, k, out, .none)).run(x, w, y, g.workspace.ptr, workspace_bytes, s.handle); ++ try (try g.plan(rows, n, k, out, .none)).run(x, w, y, g.workspace.ptr, g.workspace.len, s.handle); + } + + /// Whether the shape's own algorithm carries the bias in cuBLASLt's epilogue; else `linear` sums through f32. +@@ -222,7 +229,7 @@ pub const Gemms = struct { + fn plan(g: *Gemms, rows: usize, n: usize, k: usize, out: cublaslt.DataType, epilogue: cublaslt.Epilogue) !*const Linear { + const key = [3]u64{ rows, n, k | @as(u64, @intCast(@backingInt(out))) << 40 | @as(u64, @backingInt(epilogue)) << 48 }; + const got = try g.plans.getOrPut(g.gpa, key); +- if (!got.found_existing) got.value_ptr.* = Linear.initEpilogue(&g.lt, rows, n, k, out, workspace_bytes, epilogue) catch |e| { ++ if (!got.found_existing) got.value_ptr.* = Linear.initEpilogue(&g.lt, rows, n, k, out, if (epilogue == .none) g.workspace.len else g.bias_workspace_bytes, epilogue) catch |e| { + g.plans.removeByPtr(got.key_ptr); + return e; + }; +@@ -233,7 +240,7 @@ pub const Gemms = struct { + /// y [rows, n] = bf16(x . w^T + b), the bias in cuBLASLt's epilogue, or else through f32 `acc` and tf_vit_bias. + pub fn linear(g: *Gemms, k: *const Kernels, s: Stream, acc: u64, x: u64, w: u64, b: u64, y: u64, rows: usize, n: usize, kk: usize) !void { + const p = try g.plan(rows, n, kk, .bf16, .bias); +- if (p.epilogue == .bias) return p.runBias(x, w, b, y, g.workspace.ptr, workspace_bytes, s.handle); ++ if (p.epilogue == .bias) return p.runBias(x, w, b, y, g.workspace.ptr, g.bias_workspace_bytes, s.handle); + try g.run(s, x, w, acc, rows, n, kk, .f32); + try k.bias(s, acc, b, y, rows, n); + } +@@ -242,7 +249,7 @@ pub fn linear(g: *Gemms, k: *const Kernels, s: Stream, acc: u64, x: u64, w: u64, + pub fn linearAct(g: *Gemms, k: *const Kernels, s: Stream, acc: u64, x: u64, w: u64, b: u64, y: u64, rows: usize, n: usize, kk: usize, r: ?u64, out: u64, act: Act) !void { + const p = try g.plan(rows, n, kk, .bf16, .bias); + if (p.epilogue == .bias) { +- try p.runBias(x, w, b, y, g.workspace.ptr, workspace_bytes, s.handle); ++ try p.runBias(x, w, b, y, g.workspace.ptr, g.bias_workspace_bytes, s.handle); + return k.pointwise(s, y, r, out, rows * n, act); + } + try g.run(s, x, w, acc, rows, n, kk, .f32); +@@ -254,11 +261,15 @@ const Full = struct { + dim: usize, + warps: u32, + slots: u32 = 0, ++ moss: bool = false, + + fn sym(comptime f: Full) [:0]const u8 { + const p = "_ZN20tf_prefill_attention"; + const t = "EEEvPK13__nv_bfloat16PS1_iif"; +- if (f.slots == 0) return std.fmt.comptimePrint(p ++ "13vision_kernelILi{d}ELi{d}" ++ t, .{ f.dim, f.warps }); ++ if (f.slots == 0) { ++ const name = if (f.moss) "11moss_kernel" else "13vision_kernel"; ++ return std.fmt.comptimePrint(p ++ name ++ "ILi{d}ELi{d}" ++ t, .{ f.dim, f.warps }); ++ } + return std.fmt.comptimePrint(p ++ "11full_kernelILi{d}ELi{d}ELi{d}" ++ t, .{ f.dim, f.warps, f.slots }); + } + +@@ -296,6 +307,19 @@ pub const Attention = struct { + return a; + } + ++ pub fn loadMoss(d: *const Driver) !Attention { ++ var a = try load(d); ++ errdefer a.unload(); ++ inline for (fulls, 0..) |shape, i| { ++ if (shape.dim == 128) { ++ const f = Full{ .dim = 128, .warps = shape.warps, .moss = true }; ++ a.fns[i] = try a.mod.function(comptime f.sym()); ++ try a.fns[i].allowDynamicShared(f.smem()); ++ } ++ } ++ return a; ++ } ++ + pub fn unload(a: *Attention) void { + a.mod.unload(); + } +diff --git a/zig/src/families/moss_image/cuda_kernels.zig b/zig/src/families/moss_image/cuda_kernels.zig +index 1e89e0107135a772064aabc695e4e61e48fda55a..6f2213598ea08113f6a89b91b12004d2449bf9db 100644 +--- a/zig/src/families/moss_image/cuda_kernels.zig ++++ b/zig/src/families/moss_image/cuda_kernels.zig +@@ -16,12 +16,16 @@ pub const Kernels = struct { + qk: cuda.Function, + situ: cuda.Function, + gate_add: cuda.Function, ++ bias_add: cuda.Function, ++ time: cuda.Function, ++ silu: cuda.Function, ++ modulation: 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.moss_image); + errdefer mod.unload(); +- return .{ .mod = mod, .norm = try mod.function("tf_moss_norm"), .qk = try mod.function("tf_moss_qk"), .situ = try mod.function("tf_moss_situ"), .gate_add = try mod.function("tf_moss_gate_add") }; ++ return .{ .mod = mod, .norm = try mod.function("tf_moss_norm"), .qk = try mod.function("tf_moss_qk"), .situ = try mod.function("tf_moss_situ"), .gate_add = try mod.function("tf_moss_gate_add"), .bias_add = try mod.function("tf_moss_bias_add"), .time = try mod.function("tf_moss_time"), .silu = try mod.function("tf_moss_silu"), .modulation = try mod.function("tf_moss_modulation") }; + } + + pub fn unload(k: *Kernels) void { +@@ -33,14 +37,14 @@ fn go(f: cuda.Function, s: cuda.Stream, grid: cuda.launch.Dim3, threads: u32, a: + try cuda.launch.launch(f, .{ .grid = grid, .block = .{ .x = threads } }, s, a); + } + +-/// y = the RMSNorm of `rows` rows of x with weight w, then bf16(bf16(y s) + b) when `modulated`. ++/// Torch RMSNorm, or Comfy Kitchen RMS-AdaLN with the norm weight folded into the BF16 scale. + pub fn norm(k: *const Kernels, s: cuda.Stream, x: u64, w: u64, scale: u64, shift: u64, y: u64, rows: usize, width: usize, eps: f32, modulated: bool) !void { + var a: cuda.Args = .{}; + for ([_]u64{ x, w, scale, shift, y }) |v| a.add(v); + a.add(int(width)); + a.add(eps); + a.add(@as(c_int, @intFromBool(modulated))); +- try go(k.norm, s, .{ .x = @intCast(rows) }, 256, &a); ++ try go(k.norm, s, .{ .x = @intCast(rows) }, if (!modulated) 128 else if (rows <= 1024) 32 else 256, &a); + } + + /// q, k heads normed and rotated, v copied: rows `stride` apart into packed q | k | v rows of 3 heads 128. +@@ -68,7 +72,38 @@ pub fn gateAdd(k: *const Kernels, s: cuda.Stream, x: u64, y: u64, g: u64, rows: + try go(k.gate_add, s, .{ .x = @intCast(rows), .y = ceil(width, 256) }, 256, &a); + } + ++pub fn biasAdd(k: *const Kernels, s: cuda.Stream, x: u64, b: u64, rows: usize, width: usize) !void { ++ var a: cuda.Args = .{}; ++ a.add(x); ++ a.add(b); ++ a.add(int(width)); ++ a.add(int(rows)); ++ try go(k.bias_add, s, .{ .x = @intCast(rows), .y = ceil(width, 256) }, 256, &a); ++} ++ + test "launch geometry: rows on grid x (past y's 65,535), 256-column strips on y" { + try std.testing.expectEqual(@as(u32, 12), ceil(3072, 256)); + try std.testing.expectEqual(@as(u32, 3), ceil(24, 8)); + } ++ ++pub fn time(k: *const Kernels, s: cuda.Stream, out: u64, timestep: f32) !void { ++ var a: cuda.Args = .{}; ++ a.add(out); ++ a.add(timestep); ++ try go(k.time, s, .{ .x = 1 }, 128, &a); ++} ++ ++pub fn silu(k: *const Kernels, s: cuda.Stream, x: u64, width: usize) !void { ++ var a: cuda.Args = .{}; ++ a.add(x); ++ a.add(int(width)); ++ try go(k.silu, s, .{ .x = ceil(width, 256) }, 256, &a); ++} ++ ++pub fn modulation(k: *const Kernels, s: cuda.Stream, shared: u64, out: u64, width: usize) !void { ++ var a: cuda.Args = .{}; ++ a.add(shared); ++ a.add(out); ++ a.add(int(width)); ++ try go(k.modulation, s, .{ .x = ceil(width, 256) }, 256, &a); ++} +diff --git a/zig/src/families/moss_image/cuda_model.zig b/zig/src/families/moss_image/cuda_model.zig +index 46476082b97f927188b87fb9c36c9dc257fd4c9a..929616679198ee8bd1ee4e3783fd5f408f6f448a 100644 +--- a/zig/src/families/moss_image/cuda_model.zig ++++ b/zig/src/families/moss_image/cuda_model.zig +@@ -31,7 +31,7 @@ pub const Scratch = struct { + // the kernels' row counts and offsets are c_int + if (rows > std.math.maxInt(c_int) / (2 * F)) return error.ImageTooLarge; + const wide = try mul(rows, H * 2); +- const sums = try mul(@max(try mul(image, H), try mul(text, 3 * H)), 4); ++ const sums = try mul(@max(6 * H, @max(try mul(image, H), try mul(text, 3 * H))), 4); + const lat = try mul(image, cfg.channels * 2); + return .{ .parts = .{ + wide, wide, wide, wide, wide, try mul(wide, 3), wide, wide, try mul(rows, 2 * F * 2), +@@ -59,7 +59,7 @@ pub fn seconds() f64 { + pub const Prompt = struct { + rows: usize, + text: cuda.DeviceBuffer, +- /// cos then sin, each (image rows + rows, 64) fp32 holding bf16 values. ++ /// cos then sin, each (image rows + rows, 64) fp32. + rope: cuda.DeviceBuffer, + + pub fn deinit(p: *Prompt) void { +@@ -134,9 +134,9 @@ pub const Model = struct { + errdefer t.k.unload(); + t.vk = try cuda.vit.Kernels.load(d); + errdefer t.vk.unload(); +- t.gemms = try cuda.vit.Gemms.init(gpa, d); ++ t.gemms = try cuda.vit.Gemms.initWithBiasWorkspace(gpa, d, 1 << 20); + errdefer t.gemms.deinit(); +- t.att = try cuda.vit.Attention.load(d); ++ t.att = try cuda.vit.Attention.loadMoss(d); + errdefer t.att.unload(); + t.w = try wts.load(gpa, io, d, dir); + errdefer { +@@ -199,7 +199,7 @@ pub const Model = struct { + const table = (t.image + T) * half; + const tables = try t.gpa.alloc(f32, 2 * table); + defer t.gpa.free(tables); +- host.rotary(tables[0..table], tables[table..], &t.w.bands, T, t.rows, t.columns); ++ host.rotaryComfy(tables[0..table], tables[table..], T, t.rows, t.columns); + p.rope = try cuda.DeviceBuffer.fromHost(t.d, std.mem.sliceAsBytes(tables)); + errdefer p.rope.free(); + try t.upload(t.ctx, std.mem.sliceAsBytes(embeds)); +@@ -221,22 +221,28 @@ pub const Model = struct { + if (skip) |s| if (s >= cfg.layers) return error.BadSkipLayer; + const started = seconds(); + var spent: f64 = 0; +- if (t.timestep != timestep) { +- var vectors: [host.vectors][H]u16 = undefined; +- t.timestep = null; +- try host.modulation(&vectors, t.gpa, t.w.modulation, timestep); +- try t.upload(t.mods, std.mem.sliceAsBytes(&vectors)); +- t.timestep = timestep; +- spent = seconds() - started; +- } + const halves = try t.gpa.alloc(u16, latents.len); + defer t.gpa.free(halves); + for (halves, latents) |*o, v| o.* = host.bf16(v); + try t.upload(t.lat, std.mem.sliceAsBytes(halves)); + const N = R + p.rows; + try t.marks[0].record(t.stream); ++ if (t.timestep != timestep) { ++ t.timestep = null; ++ const w = t.w.modulation; ++ try ks.time(&t.k, t.stream, t.ug, timestep); ++ try t.linearBias(t.ug, w.time_1, w.time_1_b, t.xn, 1, H, cfg.time_dim); ++ try ks.silu(&t.k, t.stream, t.xn, H); ++ try t.linearBias(t.xn, w.time_2, w.time_2_b, t.y, 1, H, H); ++ try t.linearBias(t.y, w.blocks, w.blocks_b, t.ug, 1, 6 * H, H); ++ try t.linearBias(t.y, w.head, w.head_b, t.ug + 6 * H * 2, 1, 2 * H, H); ++ try ks.modulation(&t.k, t.stream, t.ug, t.mods, H); ++ t.timestep = timestep; ++ spent = seconds() - started; ++ } + try t.d.check(t.d.api.cuMemcpyDtoDAsync_v2(t.x + R * H * 2, p.text.ptr, p.rows * H * 2, t.stream.handle), "cuMemcpyDtoDAsync"); +- try t.linearBias(t.lat, t.w.video_in, t.w.video_in_b, t.x, R, H, cfg.channels); ++ try t.linear(t.lat, t.w.video_in, t.x, R, H, cfg.channels); ++ try ks.biasAdd(&t.k, t.stream, t.x, t.w.video_in_b, R, H); + for (t.w.blocks, 0..) |b, i| if (skip != i) try t.block(b, N, p.cos(), p.sin(R)); + try t.norm(R, t.w.final_norm, .{ .scale = .scale_out, .shift = .shift_out }); + try t.linear(t.xn, t.w.final_out, t.vel, R, cfg.channels, H); +diff --git a/zig/src/families/moss_image/cuda_weights.zig b/zig/src/families/moss_image/cuda_weights.zig +index 9343ef9995f1e9b3f1f847ad3e1b1e6f1c2fc69c..b8e207910c5c32c09a1f27c706449ea333d022bb 100644 +--- a/zig/src/families/moss_image/cuda_weights.zig ++++ b/zig/src/families/moss_image/cuda_weights.zig +@@ -26,7 +26,7 @@ pub const Weights = struct { + /// The rotary's frequencies as the checkpoint stores them (fp32). + bands: [cfg.bands]f32 = undefined, + /// The modulation's projections, read on the host from the mapped checkpoint (host.modulation). +- modulation: host.Weights = undefined, ++ modulation: struct { time_1: u64, time_1_b: u64, time_2: u64, time_2_b: u64, blocks: u64, blocks_b: u64, head: u64, head_b: u64 } = undefined, + bytes: u64 = 0, + + pub fn deinit(w: *Weights) void { +@@ -118,14 +118,14 @@ pub fn load(gpa: std.mem.Allocator, io: std.Io, d: *const cuda.Driver, dir: []co + const bands = try w.typed("rope.bands", .f32, &.{cfg.bands}); + @memcpy(std.mem.asBytes(&w.bands), bands.bytes); + w.modulation = .{ +- .time_1 = try w.values("time_embedding.0.weight", &.{ h, cfg.time_dim }), +- .time_1_b = try w.values("time_embedding.0.bias", &.{h}), +- .time_2 = try w.values("time_embedding.2.weight", &.{ h, h }), +- .time_2_b = try w.values("time_embedding.2.bias", &.{h}), +- .blocks = try w.values("shared_block_modulation.weight", &.{ 6 * h, h }), +- .blocks_b = try w.values("shared_block_modulation.bias", &.{6 * h}), +- .head = try w.values("video_head_modulation.weight", &.{ 2 * h, h }), +- .head_b = try w.values("video_head_modulation.bias", &.{2 * h}), ++ .time_1 = try w.take(d, "time_embedding.0.weight", &.{ h, cfg.time_dim }), ++ .time_1_b = try w.take(d, "time_embedding.0.bias", &.{h}), ++ .time_2 = try w.take(d, "time_embedding.2.weight", &.{ h, h }), ++ .time_2_b = try w.take(d, "time_embedding.2.bias", &.{h}), ++ .blocks = try w.take(d, "shared_block_modulation.weight", &.{ 6 * h, h }), ++ .blocks_b = try w.take(d, "shared_block_modulation.bias", &.{6 * h}), ++ .head = try w.take(d, "video_head_modulation.weight", &.{ 2 * h, h }), ++ .head_b = try w.take(d, "video_head_modulation.bias", &.{2 * h}), + }; + if (w.ck.unused() != 0) { + std.log.err("moss image: the checkpoint has {d} transformer tensors this family does not read", .{w.ck.unused()}); +diff --git a/zig/src/families/moss_image/host.zig b/zig/src/families/moss_image/host.zig +index b442df775940fe5e643e7b852313c9c4bfb285e1..60d00e75d4e1c36c954eb12266525e0659724677 100644 +--- a/zig/src/families/moss_image/host.zig ++++ b/zig/src/families/moss_image/host.zig +@@ -160,3 +160,51 @@ test "project sums in fp32 and adds the bias before its one rounding" { + project(&one, &eighth, &[_]f32{45.6}, &z); + try std.testing.expectEqual(@as(f32, 45.75), z[0]); + } ++ ++/// ComfyUI keeps double-precision coordinates and float32 rotary tables. ++pub fn rotaryComfy(cos: []f32, sin: []f32, text: usize, rows: usize, columns: usize) void { ++ const half = cfg.head_dim / 2; ++ const image = rows * columns; ++ std.debug.assert(cos.len == (image + text) * half and sin.len == cos.len); ++ var frequencies: [cfg.bands]f64 = undefined; ++ for (&frequencies, 0..) |*frequency, i| frequency.* = 1.0 / std.math.pow(f64, 10000, @as(f64, @floatFromInt(i)) / cfg.bands); ++ const top = @as(f64, @floatFromInt(rows - 1)) / 2; ++ const left = @as(f64, @floatFromInt(columns - 1)) / 2; ++ for (0..image + text) |r| { ++ const at: [4]f64 = if (r < image) ++ .{ 0, @floatFromInt(text), @as(f64, @floatFromInt(r / columns)) - top, @as(f64, @floatFromInt(r % columns)) - left } ++ else ++ .{ 0, @floatFromInt(r - image), 0, 0 }; ++ for (0..half) |j| { ++ const angle = at[j / cfg.bands] * frequencies[j % cfg.bands]; ++ cos[r * half + j] = @floatCast(@cos(angle)); ++ sin[r * half + j] = @floatCast(@sin(angle)); ++ } ++ } ++} ++ ++test "Comfy rotary keeps float32 tables" { ++ var cos: [(16 * 14 + 33) * 64]f32 = undefined; ++ var sin: [cos.len]f32 = undefined; ++ rotaryComfy(&cos, &sin, 33, 16, 14); ++ try std.testing.expectEqual(@as(u32, 0xbc5986b7), @as(u32, @bitCast(cos[13 * 64 + 16]))); ++ try std.testing.expectEqual(@as(u32, 0x3f7ffa39), @as(u32, @bitCast(sin[13 * 64 + 16]))); ++ try std.testing.expectEqual(@as(u32, 0x3f75245a), @as(u32, @bitCast(cos[13 * 64 + 17]))); ++ try std.testing.expectEqual(@as(u32, 0xbe938821), @as(u32, @bitCast(sin[13 * 64 + 17]))); ++ try std.testing.expectEqual(@as(u32, 0xbe8feb12), @as(u32, @bitCast(cos[13 * 64 + 21]))); ++ try std.testing.expectEqual(@as(u32, 0x3f75adad), @as(u32, @bitCast(sin[13 * 64 + 21]))); ++ try std.testing.expectEqual(@as(u32, 0x3f7ffedf), @as(u32, @bitCast(cos[13 * 64 + 31]))); ++ try std.testing.expectEqual(@as(u32, 0x3bc04ac5), @as(u32, @bitCast(sin[13 * 64 + 31]))); ++ try std.testing.expectEqual(@as(u32, 0x3eb17a2f), @as(u32, @bitCast(cos[13 * 64 + 32]))); ++ try std.testing.expectEqual(@as(u32, 0xbf7020c4), @as(u32, @bitCast(sin[13 * 64 + 32]))); ++ try std.testing.expectEqual(@as(u32, 0xbef323a1), @as(u32, @bitCast(cos[13 * 64 + 33]))); ++ try std.testing.expectEqual(@as(u32, 0x3f614af3), @as(u32, @bitCast(sin[13 * 64 + 33]))); ++ try std.testing.expectEqual(@as(u32, 0x3f7ffff1), @as(u32, @bitCast(cos[13 * 64 + 47]))); ++ try std.testing.expectEqual(@as(u32, 0xbaaecfda), @as(u32, @bitCast(sin[13 * 64 + 47]))); ++ try std.testing.expectEqual(@as(u32, 0x3f7a01a6), @as(u32, @bitCast(cos[13 * 64 + 48]))); ++ try std.testing.expectEqual(@as(u32, 0x3e5c486a), @as(u32, @bitCast(sin[13 * 64 + 48]))); ++ try std.testing.expectEqual(@as(u32, 0xbf5ef7cd), @as(u32, @bitCast(cos[13 * 64 + 49]))); ++ try std.testing.expectEqual(@as(u32, 0xbefb90bb), @as(u32, @bitCast(sin[13 * 64 + 49]))); ++ try std.testing.expectEqual(@as(u32, 0x3f7ffff5), @as(u32, @bitCast(cos[13 * 64 + 63]))); ++ try std.testing.expectEqual(@as(u32, 0x3a9780f1), @as(u32, @bitCast(sin[13 * 64 + 63]))); ++} +diff --git a/zig/tests/cuda/contract_moss_image.zig b/zig/tests/cuda/contract_moss_image.zig +index 4dbf0634b6d91caf8e562b773229a651a5721c4a..33936262580b264528fc5e52cba3db6071f2d0a7 100644 +--- a/zig/tests/cuda/contract_moss_image.zig ++++ b/zig/tests/cuda/contract_moss_image.zig +@@ -8,8 +8,11 @@ const rig_ = @import("contract_rig.zig"); + const norms = @import("contract_moss_image_norms.zig"); + const steps = @import("contract_moss_image_steps.zig"); + const full = @import("contract_moss_image_attn.zig"); ++const elementwise = @import("contract_moss_image_elementwise.zig"); ++const time = @import("contract_moss_image_time.zig"); + + const g = core.contract.gates; ++const rows = @import("contract_rows.zig"); + + const controls = struct { + pub const bytes align(16) = @embedFile("fatbin_contract_controls").*; +@@ -21,11 +24,18 @@ pub const Set = struct { + k: moss.Kernels, + ctl: cuda.Module, + att: cuda.vit.Attention, ++ legacy_att: cuda.vit.Attention, + norms: [4]norms.Norm = undefined, + qks: [3]norms.Qk = undefined, + situs: [3]steps.Situ = undefined, + adds: [2]steps.GateAdd = undefined, + full: full.Full = undefined, ++ legacy: full.Full = undefined, ++ attention_control: full.Full = undefined, ++ elementwise: [6]elementwise.Elementwise = undefined, ++ times: [2]time.Time = undefined, ++ unused_norms: cuda.norms.Norms = undefined, ++ harness_controls: [5]rows.Row = undefined, + + /// The set, its kernels appended to `list` (each control after the kernel it breaks). + pub fn init(gpu: check.Gpu, s: cuda.Stream, a: std.mem.Allocator, list: *std.ArrayList(g.Kernel)) !*Set { +@@ -35,20 +45,24 @@ pub const Set = struct { + errdefer k.unload(); + var ctl = try cuda.Module.load(gpu.d, &controls.bytes); + errdefer ctl.unload(); +- set.* = .{ .gpa = gpu.gpa, .k = k, .ctl = ctl, .att = try cuda.vit.Attention.load(gpu.d) }; ++ var attention = try cuda.vit.Attention.loadMoss(gpu.d); ++ errdefer attention.unload(); ++ var legacy = try cuda.vit.Attention.load(gpu.d); ++ errdefer legacy.unload(); ++ set.* = .{ .gpa = gpu.gpa, .k = k, .ctl = ctl, .att = attention, .legacy_att = legacy }; + const rig: rig_.Rig = .{ .gpu = gpu, .s = s }; + const ends: @import("contract_moss_image_ref.zig").Ends = .{ .a = gpu.gpa }; + var with = k; + with.norm = try ctl.function("tf_ctl_moss_norm_inv"); + set.norms[0] = .{ .rig = rig, .k = k, .modulated = false, .name = "cuda moss image tf_moss_norm", .ends = ends }; +- set.norms[1] = .{ .rig = rig, .k = with, .modulated = false, .name = "control: moss image tf_moss_norm drops bf16(x inv)", .control = .shapes, .ends = ends }; ++ set.norms[1] = .{ .rig = rig, .k = with, .modulated = false, .name = "control: moss image tf_moss_norm adds bf16(x inv)", .control = .shapes, .ends = ends }; + with.norm = try ctl.function("tf_ctl_moss_norm_scale"); + set.norms[2] = .{ .rig = rig, .k = k, .modulated = true, .name = "cuda moss image tf_moss_norm modulated", .ends = ends }; +- set.norms[3] = .{ .rig = rig, .k = with, .modulated = true, .name = "control: moss image tf_moss_norm modulated drops bf16(y s)", .control = .shapes, .ends = ends }; ++ set.norms[3] = .{ .rig = rig, .k = with, .modulated = true, .name = "control: moss image tf_moss_norm modulated drops folded-scale bf16", .control = .shapes, .ends = ends }; + with = k; +- with.qk = try ctl.function("tf_ctl_moss_qk_cos"); ++ with.qk = try ctl.function("tf_ctl_moss_qk_normalized"); + set.qks[0] = .{ .rig = rig, .k = k, .packed_rows = false, .name = "cuda moss image tf_moss_qk q k v rows", .ends = ends }; +- set.qks[1] = .{ .rig = rig, .k = with, .packed_rows = false, .name = "control: moss image tf_moss_qk drops bf16(q cos)", .control = .shapes, .ends = ends }; ++ set.qks[1] = .{ .rig = rig, .k = with, .packed_rows = false, .name = "control: moss image tf_moss_qk adds bf16(q inv)", .control = .shapes, .ends = ends }; + set.qks[2] = .{ .rig = rig, .k = k, .packed_rows = true, .name = "cuda moss image tf_moss_qk packed qkv rows", .ends = ends }; + with = k; + with.situ = try ctl.function("tf_ctl_moss_situ_sigmoid"); +@@ -58,13 +72,40 @@ pub const Set = struct { + with = k; + with.gate_add = try ctl.function("tf_ctl_moss_gate_add_product"); + set.adds[0] = .{ .rig = rig, .k = k, .name = "cuda moss image tf_moss_gate_add", .ends = ends }; +- set.adds[1] = .{ .rig = rig, .k = with, .name = "control: moss image tf_moss_gate_add drops bf16(g y)", .control = .shapes, .ends = ends }; ++ set.adds[1] = .{ .rig = rig, .k = with, .name = "control: moss image tf_moss_gate_add adds bf16(g y)", .control = .shapes, .ends = ends }; + set.full = .{ .rig = rig, .att = &set.att }; ++ set.legacy = .{ .rig = rig, .att = &set.legacy_att, .name = "cuda moss image legacy vision_kernel<128, 8>" }; ++ set.attention_control = .{ .rig = rig, .att = &set.att, .name = "control: moss attention wrong scale", .control = .shapes, .bad_scale = true }; ++ for ([_]elementwise.Kind{ .bias, .silu, .modulation }, 0..) |kind, i| { ++ with = k; ++ const names = [_][]const u8{ "cuda moss image tf_moss_bias_add", "cuda moss image tf_moss_silu", "cuda moss image tf_moss_modulation" }; ++ const bad = [_][]const u8{ "control: moss bias drops tail", "control: moss silu is identity", "control: moss modulation omits one" }; ++ switch (kind) { ++ .bias => with.bias_add = try ctl.function("tf_ctl_moss_bias_tail"), ++ .silu => with.silu = try ctl.function("tf_ctl_moss_silu_identity"), ++ .modulation => with.modulation = try ctl.function("tf_ctl_moss_modulation_scale"), ++ } ++ set.elementwise[2 * i] = .{ .rig = rig, .k = k, .kind = kind, .name = names[i], .ends = ends }; ++ set.elementwise[2 * i + 1] = .{ .rig = rig, .k = with, .kind = kind, .name = bad[i], .control = .shapes, .ends = ends }; ++ } ++ set.times[0] = .{ .rig = rig, .k = k, .name = "cuda moss image tf_moss_time integer and adapter grids", .ends = ends }; ++ with = k; ++ with.time = try ctl.function("tf_ctl_moss_time_phase"); ++ set.times[1] = .{ .rig = rig, .k = with, .name = "control: moss time halves phase", .control = .shapes, .ends = ends }; ++ + for (&set.norms) |*x| try list.append(a, x.kernel()); + for (&set.qks) |*x| try list.append(a, x.kernel()); + for (&set.situs) |*x| try list.append(a, x.kernel()); + for (&set.adds) |*x| try list.append(a, x.kernel()); + try list.append(a, set.full.kernel()); ++ try list.append(a, set.legacy.kernel()); ++ try list.append(a, set.attention_control.kernel()); ++ for (&set.elementwise) |*x| try list.append(a, x.kernel()); ++ for (&set.times) |*x| try list.append(a, x.kernel()); ++ for ([_]rows.Which{ .fmax_max, .atomic_sum, .scribble_sum, .tail_sum, .half_dot }, &set.harness_controls) |which, *item| { ++ item.* = try rows.Row.init(gpu, s, &set.unused_norms, ctl, which); ++ try list.append(a, item.kernel()); ++ } + return set; + } + +@@ -74,6 +115,12 @@ pub const Set = struct { + for (&set.situs) |*x| x.deinit(); + for (&set.adds) |*x| x.deinit(); + set.full.deinit(); ++ set.legacy.deinit(); ++ set.attention_control.deinit(); ++ for (&set.elementwise) |*x| x.deinit(); ++ for (&set.times) |*x| x.deinit(); ++ for (&set.harness_controls) |*x| x.deinit(); ++ set.legacy_att.unload(); + set.att.unload(); + set.ctl.unload(); + set.k.unload(); +diff --git a/zig/tests/cuda/contract_moss_image_attn.zig b/zig/tests/cuda/contract_moss_image_attn.zig +index 176c9cf4e029783aa776411a7f7705223b06f9df..26ca6a01156bc0fde89ef468763754bb1c429969 100644 +--- a/zig/tests/cuda/contract_moss_image_attn.zig ++++ b/zig/tests/cuda/contract_moss_image_attn.zig +@@ -20,9 +20,9 @@ fn scale() f32 { + } + + /// Shape: heads (rows), head width (n), rows L (k); 24 heads at prompt lengths, two stand for them at joint ones. +-pub fn spec() c.Spec { ++pub fn spec(name: []const u8) c.Spec { + return .{ +- .name = "cuda moss image vit vision_kernel<128, 8> (full attention)", ++ .name = name, + .accum = .f32, + .depth = keyChain, + .ops = 1, +@@ -35,6 +35,9 @@ pub fn spec() c.Spec { + + pub const Full = struct { + rig: rig_.Rig, ++ name: []const u8 = "cuda moss image moss_kernel<128, 8>", ++ control: ?g.Gate = null, ++ bad_scale: bool = false, + att: *const cuda.vit.Attention, + r: ?attn.Ref = null, + shape: c.Shape = undefined, +@@ -50,7 +53,7 @@ pub const Full = struct { + } + + pub fn kernel(self: *Full) g.Kernel { +- return .{ .spec = spec(), .ctx = self, .vt = &vt }; ++ return .{ .spec = spec(self.name), .ctx = self, .vt = &vt, .control = self.control }; + } + + const vt = g.hooks(Full); +@@ -123,7 +126,7 @@ pub const Full = struct { + } + + pub fn run(self: *Full) !void { +- try self.att.full(self.rig.s, self.dev, self.out, self.shape.k, self.shape.rows, D, scale()); ++ try self.att.full(self.rig.s, self.dev, self.out, self.shape.k, self.shape.rows, D, scale() * @as(f32, if (self.bad_scale) 2 else 1)); + try self.rig.s.synchronize(); + } + +diff --git a/zig/tests/cuda/contract_moss_image_elementwise.zig b/zig/tests/cuda/contract_moss_image_elementwise.zig +new file mode 100644 +index 0000000000000000000000000000000000000000..ecaf68471a62e2d219c7010b9e87c933c4702145 +--- /dev/null ++++ b/zig/tests/cuda/contract_moss_image_elementwise.zig +@@ -0,0 +1,144 @@ ++//! MOSS bias, SiLU and modulation through independent FP64 formulas and guarded CUDA buffers. ++const std = @import("std"); ++const cuda = @import("cuda"); ++const moss = @import("moss_image_cuda"); ++const rig_ = @import("contract_rig.zig"); ++const mi = @import("contract_moss_image_ref.zig"); ++const c = mi.c; ++const g = mi.g; ++const Range = mi.Range; ++ ++pub const Kind = enum { bias, silu, modulation }; ++ ++pub const Elementwise = struct { ++ rig: rig_.Rig, ++ k: moss.Kernels, ++ kind: Kind, ++ name: []const u8, ++ control: ?g.Gate = null, ++ shape: c.Shape = undefined, ++ x: []u16 = &.{}, ++ b: []u16 = &.{}, ++ ins: [2]u64 = @splat(0), ++ out: u64 = 0, ++ ends: mi.Ends, ++ ++ pub fn spec(t: *const Elementwise) c.Spec { ++ return .{ ++ .name = t.name, ++ .accum = .none, ++ .depth = mi.noSums, ++ .ops = if (t.kind == .silu) 2 * (mi.exp_ulps + mi.div_ulps) + 1 else 1, ++ .out = .bf16, ++ .in_place = t.kind != .modulation, ++ .tiles = .{ .{}, .{ .size = 256 }, .{} }, ++ .served = if (t.kind == .bias) ++ &.{ .{ .rows = 65536, .n = mi.hidden, .k = 1 }, .{ .rows = 4096, .n = mi.hidden, .k = 1 }, .{ .rows = 1, .n = mi.hidden, .k = 1 } } ++ else ++ &.{.{ .rows = 1, .n = mi.hidden, .k = 1 }}, ++ }; ++ } ++ ++ fn free(t: *Elementwise) void { ++ t.rig.gpu.gpa.free(t.x); ++ t.rig.gpu.gpa.free(t.b); ++ t.x = &.{}; ++ t.b = &.{}; ++ } ++ ++ pub fn deinit(t: *Elementwise) void { ++ t.free(); ++ t.ends.deinit(); ++ t.rig.deinit(); ++ } ++ ++ pub fn kernel(t: *Elementwise) g.Kernel { ++ return .{ .spec = t.spec(), .ctx = t, .vt = &vt, .control = t.control }; ++ } ++ const vt = g.hooks(Elementwise); ++ ++ pub fn prepare(t: *Elementwise, shape: c.Shape, fill: g.Fill, seed: u64) !bool { ++ if (shape.rows == 0 or shape.n == 0) return false; ++ t.rig.reset(); ++ t.free(); ++ t.shape = shape; ++ const a = t.rig.gpu.gpa; ++ const n = shape.rows * shape.n * @as(usize, if (t.kind == .modulation) 8 else 1); ++ t.x = try a.alloc(u16, n); ++ t.b = try a.alloc(u16, if (t.kind == .bias) shape.n else 0); ++ var random = std.Random.DefaultPrng.init(seed); ++ mi.randomBf16(random.random(), t.x, -16, 16); ++ mi.randomBf16(random.random(), t.b, -4, 4); ++ if (fill == .nonfinite) { ++ for ([_]u16{ mi.nan16, mi.inf16, mi.ninf16 }, 0..) |v, i| t.x[i % n] = v; ++ if (t.kind == .bias) for ([_]u16{ mi.nan16, mi.inf16, mi.ninf16 }, 0..) |v, i| { ++ t.b[(i + 3) % t.b.len] = v; ++ }; ++ } ++ t.ins[0] = try mi.input(&t.rig, t.x); ++ if (t.kind == .bias) t.ins[1] = try mi.input(&t.rig, t.b); ++ t.out = try t.rig.output(t.count() * 2); ++ return true; ++ } ++ ++ pub fn count(t: *Elementwise) usize { ++ return t.shape.rows * t.shape.n * @as(usize, if (t.kind == .modulation) 9 else 1); ++ } ++ ++ pub fn run(t: *Elementwise) !void { ++ if (t.kind != .modulation) { ++ const bytes = t.x.len * 2; ++ try (cuda.DeviceBuffer{ .d = t.rig.gpu.d, .ptr = t.out, .len = bytes }).copyFrom(0, t.ins[0], bytes, t.rig.s.handle); ++ } ++ switch (t.kind) { ++ .bias => try moss.biasAdd(&t.k, t.rig.s, t.out, t.ins[1], t.shape.rows, t.shape.n), ++ .silu => try moss.silu(&t.k, t.rig.s, t.out, t.count()), ++ .modulation => for (0..t.shape.rows) |row| { ++ const input = t.ins[0] + row * 8 * t.shape.n * 2; ++ const output = t.out + row * 9 * t.shape.n * 2; ++ try moss.modulation(&t.k, t.rig.s, input, output, t.shape.n); ++ }, ++ } ++ try t.rig.s.synchronize(); ++ } ++ ++ pub fn reference(t: *Elementwise, want: []f64, mag: []f64) !void { ++ try t.ends.size(t.count()); ++ const from = [_]usize{ 1, 0, 2, 4, 3, 5, 7, 6 }; ++ for (0..t.count()) |i| { ++ const n = t.shape.n; ++ var value: f64 = undefined; ++ var range: Range = undefined; ++ switch (t.kind) { ++ .bias => { ++ value = c.fromBf16(t.x[i]) + c.fromBf16(t.b[i % n]); ++ range = Range.of(value).fp32(0.5).bf16(); ++ }, ++ .silu => { ++ const x: f64 = c.fromBf16(t.x[i]); ++ value = x / (1 + @exp(-x)); ++ range = Range.of(@exp(-x)).fp32(2.5).add(Range.of(1)).fp32(0.5).recip().mul(Range.of(x)).fp32(mi.div_ulps).bf16(); ++ }, ++ .modulation => { ++ const sample = i / (9 * n); ++ const row = (i / n) % 9; ++ if (row == 8) { ++ value = 1; ++ } else { ++ const x = c.fromBf16(t.x[sample * 8 * n + from[row] * n + i % n]); ++ value = x + @as(f64, if (row == 0 or row == 3 or row == 6) 1 else 0); ++ } ++ range = Range.of(value).fp32(0.5).bf16(); ++ }, ++ } ++ t.ends.put(want, mag, i, mi.bf(value), range); ++ } ++ } ++ ++ pub fn bounds(t: *Elementwise, want: []const f64, _: []const f64, allow: []f64) !void { ++ t.ends.bounds(want, allow); ++ } ++ pub fn intervals(t: *Elementwise, low: []f64, high: []f64) !void { ++ t.ends.intervals(low, high); ++ } ++}; +diff --git a/zig/tests/cuda/contract_moss_image_limits.zig b/zig/tests/cuda/contract_moss_image_limits.zig +new file mode 100644 +index 0000000000000000000000000000000000000000..4cd834cc71436443577d1006008c1184d1819361 +--- /dev/null ++++ b/zig/tests/cuda/contract_moss_image_limits.zig +@@ -0,0 +1,89 @@ ++//! Compile records on every release SM and the companion's actual launches on this device. ++const std = @import("std"); ++const cuda = @import("cuda"); ++const core = @import("core"); ++const check = @import("check.zig"); ++const limits = core.contract.limits; ++const registry = core.contract.registry; ++const cubin = core.contract.cubin; ++const records = struct { ++ pub const cuda = core.contract.registry.moss_cuda; ++}; ++const controls = struct { ++ pub const bytes align(16) = @embedFile("fatbin_contract_controls").*; ++}; ++ ++fn image(name: []const u8) ![]const u8 { ++ if (std.mem.eql(u8, name, "moss_image")) return cuda.kernels.moss_image; ++ if (std.mem.eql(u8, name, "prefill_attention")) return cuda.kernels.prefill_attention; ++ if (std.mem.eql(u8, name, "vit")) return cuda.kernels.vit; ++ if (std.mem.eql(u8, name, "contract_controls")) return &controls.bytes; ++ return error.UnknownImage; ++} ++ ++pub fn audit(gpu: check.Gpu, record_only: bool) !usize { ++ const a = gpu.gpa; ++ var problems: usize = 0; ++ var caught: usize = 0; ++ for (records.cuda ++ registry.cuda_controls) |record| { ++ const control = std.mem.startsWith(u8, record.launch.name, "control:"); ++ const bytes = try image(record.launch.image); ++ const images = try cubin.images(a, bytes); ++ defer cubin.freeImages(a, images); ++ var measured: [limits.sms.len]limits.Usage = undefined; ++ for (limits.sms, 0..) |sm, i| { ++ const im = for (images) |candidate| { ++ if (candidate.sm == sm.sm) break candidate; ++ } else return error.MissingArchitecture; ++ const kernels = try cubin.kernels(a, im.elf, sm.sm); ++ defer a.free(kernels); ++ const kernel = for (kernels) |candidate| { ++ if (std.mem.eql(u8, candidate.name, record.launch.symbol)) break candidate; ++ } else return error.MissingKernel; ++ measured[i] = kernel.usage; ++ if (record_only) continue; ++ var details: std.ArrayList(u8) = .empty; ++ defer details.deinit(a); ++ const failures = try limits.cuda(record.launch, kernel.usage, sm, &details, a); ++ if (control) { ++ if (failures > 0) caught += 1 else problems += 1; ++ std.debug.print("{s} limits sm_{d} {s}\n", .{ if (failures > 0) "RED" else "MISSED", sm.sm, record.launch.name }); ++ } else { ++ const current = std.meta.eql(kernel.usage, record.usage[i]); ++ if (!current or failures > 0) problems += 1; ++ std.debug.print("{s} limits sm_{d} {s}: regs={d} shared={d} bound={d} local={d}\n", .{ if (current and failures == 0) "PASS" else "FAIL", sm.sm, record.launch.name, kernel.usage.regs, kernel.usage.static, kernel.usage.bound, kernel.usage.local }); ++ } ++ } ++ if (record_only and !control) { ++ std.debug.print("RECORDJSON {s} [", .{record.launch.symbol}); ++ for (measured, 0..) |u, i| std.debug.print("{s}{{\"regs\":{d},\"static\":{d},\"bound\":{d},\"local\":{d}}}", .{ if (i == 0) "" else ",", u.regs, u.static, u.bound, u.local }); ++ std.debug.print("]\n", .{}); ++ } ++ } ++ if (record_only) return 0; ++ const capability: u32 = @intCast(try gpu.ctx.capability()); ++ const shared: u32 = @intCast(try gpu.ctx.attribute(.max_shared_memory_per_block_optin)); ++ for (records.cuda ++ registry.cuda_controls) |record| { ++ const control = std.mem.startsWith(u8, record.launch.name, "control:"); ++ var module = try cuda.Module.load(gpu.d, try image(record.launch.image)); ++ defer module.unload(); ++ const name = try a.dupeSentinel(u8, record.launch.symbol, 0); ++ defer a.free(name); ++ const function = try module.function(name); ++ const max_threads: u32 = @intCast(try function.attribute(.max_threads_per_block)); ++ const static: u32 = @intCast(try function.attribute(.shared_size_bytes)); ++ const regs: u32 = @intCast(try function.attribute(.num_regs)); ++ const at = for (limits.sms, 0..) |sm, i| { ++ if (sm.sm == capability) break i; ++ } else return error.UnregisteredDevice; ++ const fits = record.launch.threads <= max_threads and static + record.launch.dynamic <= shared; ++ const current = static == record.usage[at].static and regs == record.usage[at].regs; ++ if (control) { ++ if (!fits) caught += 1 else problems += 1; ++ } else if (!fits or !current) problems += 1; ++ const passed = if (control) !fits else fits and current; ++ std.debug.print("{s} live sm_{d} {s}: regs={d} shared={d} threads={d}/{d}\n", .{ if (passed) (if (control) "RED" else "PASS") else "FAIL", capability, record.launch.name, regs, static, record.launch.threads, max_threads }); ++ } ++ std.debug.print("SUMMARY moss limits: {d} launches, {d} compile/live controls red, {d} problems\n", .{ records.cuda.len, caught, problems }); ++ return problems; ++} +diff --git a/zig/tests/cuda/contract_moss_image_norms.zig b/zig/tests/cuda/contract_moss_image_norms.zig +index 721bec1b158b7ed34fe290c1dc5ca0c9d7e080da..d6a87577abb0b672cfb4afd72e88168b88a3811d 100644 +--- a/zig/tests/cuda/contract_moss_image_norms.zig ++++ b/zig/tests/cuda/contract_moss_image_norms.zig +@@ -13,11 +13,15 @@ const bf = mi.bf; + + const norm_why = "a bf16 output follows the sum of squares as ss^-1/2: a bf16 sum's error is a few output ulps"; + +-// --- tf_moss_norm: bf16(bf16(x inv) w), then bf16(bf16(y s) + b) when modulated ---------------------------------- ++// Unrounded normalized rows, with Comfy Kitchen scale folding when modulated. + + /// A thread's share of the row in turn, the warp's 5 shuffles, then the 8 warps' partials in order. +-fn normDepth(s: c.Shape) usize { +- return (s.k + 255) / 256 + 5 + 8; ++fn plainDepth(s: c.Shape) usize { ++ return (s.k + 127) / 128 + 5 + 2; ++} ++ ++fn modDepth(s: c.Shape) usize { ++ return if (s.rows <= 1024) (s.k + 31) / 32 + 5 else (s.k + 255) / 256 + 5 + 8; + } + + fn normServed(comptime list: []const usize) [list.len]c.Shape { +@@ -49,9 +53,9 @@ pub const Norm = struct { + return .{ + .name = name, + .accum = .f32, +- .depth = normDepth, +- .ops = 2 * (mi.div_ulps + mi.sqrt_ulps) + 1, +- .mids = if (modulated) 3 else 1, ++ .depth = if (modulated) modDepth else plainDepth, ++ .ops = 2 * mi.rsqrt_ulps + (if (modulated) @as(f64, 7) else 4), ++ .mids = if (modulated) 2 else 0, + .out = .bf16, + .tiles = .{ .{}, .{}, .{ .size = 256 } }, + .served = if (modulated) &modulated_rows else &plain_rows, +@@ -121,17 +125,20 @@ pub const Norm = struct { + + fn row(t: *Norm, ends: *Ends, r: usize, ss: f64, ssr: Range, want: []f64, mag: []f64) void { + const k = t.shape.k; +- const n = mi.invNorm(ss, ssr, @floatFromInt(k)); ++ const n = mi.invNorm(ss, ssr, @floatFromInt(k), t.modulated); + for (0..k) |j| { + const x: f64 = c.fromBf16(t.x[r * k + j]); + const w: f64 = c.fromBf16(t.v[j]); +- var y = bf(bf(x * n.inv) * w); +- var yr = Range.of(x).mul(n.r).fp32(0.5).bf16().mul(Range.of(w)).fp32(0.5).bf16(); ++ var y = bf((x * n.inv) * w); ++ const normalized = Range.of(x).mul(n.r).fp32(0.5); ++ var yr = normalized.mul(Range.of(w)).fp32(0.5).bf16(); + if (t.modulated) { + const s: f64 = c.fromBf16(t.v[k + j]); + const b: f64 = c.fromBf16(t.v[2 * k + j]); +- y = bf(bf(y * s) + b); +- yr = yr.mul(Range.of(s)).fp32(0.5).bf16().add(Range.of(b)).fp32(0.5).bf16(); ++ const folded = bf(bf(w * s) - 1); ++ y = bf((x * n.inv) * (1 + folded) + b); ++ const factor = Range.of(w * s).fp32(0.5).bf16().add(Range.of(-1)).fp32(0.5).bf16().add(Range.of(1)).fp32(0.5); ++ yr = normalized.mul(factor).add(Range.of(b)).fp32(0.5).bf16(); + } + ends.put(want, mag, r * k + j, y, yr); + } +@@ -141,7 +148,7 @@ pub const Norm = struct { + try t.ends.size(t.count()); + const k = t.shape.k; + for (0..t.shape.rows) |r| { +- const s = mi.squares(t.x[r * k ..][0..k], normDepth(t.shape), t.fill == .stress); ++ const s = mi.squares(t.x[r * k ..][0..k], (if (t.modulated) modDepth(t.shape) else plainDepth(t.shape)), t.fill == .stress); + t.row(&t.ends, r, s.ss, s.r, want, mag); + } + } +@@ -214,8 +221,8 @@ pub const Qk = struct { + .name = name, + .accum = .f32, + .depth = qkDepth, +- .ops = 2 * (mi.div_ulps + mi.sqrt_ulps) + 1, +- .mids = 3, ++ .ops = 2 * mi.rsqrt_ulps + 6, ++ .mids = 1, + .out = .bf16, + .tiles = .{ .{}, .{ .size = 8 }, .{} }, + .served = if (packed_rows) &qk_prompt else &qk_joint, +@@ -307,14 +314,14 @@ pub const Qk = struct { + fn head(t: *Qk, ends: *Ends, which: usize, r: usize, h: usize, ss: f64, ssr: Range, want: []f64, mag: []f64) void { + const x = t.qkv[which][r * t.width() + h * D ..][0..D]; + const w = t.nw[which * D ..][0..D]; +- const n = mi.invNorm(ss, ssr, D); ++ const n = mi.invNorm(ss, ssr, D, true); + var normed: [D]f64 = undefined; + var nr: [D]Range = undefined; + for (x, w, &normed, &nr) |xv, wv, *o, *orr| { + const f: f64 = c.fromBf16(xv); + const wf: f64 = c.fromBf16(wv); +- o.* = bf(bf(f * n.inv) * wf); +- orr.* = Range.of(f).mul(n.r).fp32(0.5).bf16().mul(Range.of(wf)).fp32(0.5).bf16(); ++ o.* = bf((f * n.inv) * wf); ++ orr.* = Range.of(f).mul(n.r).fp32(0.5).mul(Range.of(wf)).fp32(0.5).bf16(); + } + const half = t.shape.rows * D / 2; + const base = (r * 3 + which) * t.width() + h * D; +@@ -324,8 +331,10 @@ pub const Qk = struct { + const sign: f64 = if (ch < D / 2) -1 else 1; + const cs: f64 = t.rot[r * D / 2 + j]; + const sn: f64 = t.rot[half + r * D / 2 + j]; +- const v = bf(bf(normed[ch] * cs) + bf(sign * normed[partner] * sn)); +- const vr = nr[ch].mul(Range.of(cs)).fp32(0.5).bf16().add(nr[partner].mul(Range.of(sign * sn)).fp32(0.5).bf16()).fp32(0.5).bf16(); ++ const v = bf(normed[ch] * cs + sign * normed[partner] * sn); ++ const left = nr[ch].mul(Range.of(cs)); ++ const right = nr[partner].mul(Range.of(sign * sn)); ++ const vr = (if (ch < D / 2) left.add(right.fp32(0.5)) else right.add(left.fp32(0.5))).fp32(0.5).bf16(); + ends.put(want, mag, base + ch, v, vr); + } + } +diff --git a/zig/tests/cuda/contract_moss_image_ref.zig b/zig/tests/cuda/contract_moss_image_ref.zig +index daf1f4ff2ad7eaac48b1f12ec37c6595e81ad852..781b853690a357f8192cd09bfcce8a860b7ab338 100644 +--- a/zig/tests/cuda/contract_moss_image_ref.zig ++++ b/zig/tests/cuda/contract_moss_image_ref.zig +@@ -13,7 +13,7 @@ pub const heads = 24; + pub const ffn = 8192; + + /// MOSS-Image's row counts: image and prompt rows (1200x880 and 1024x1024 with 63, 34 or 10), and prompt rows alone. +-pub const joint = [_]usize{ 4188, 4135, 4130, 4106 }; ++pub const joint = [_]usize{ 4188, 4135, 4130, 4106, 1025, 1024, 296, 2 }; + pub const prompt = [_]usize{ 63, 34, 10 }; + + // nvcc's error bounds under the glue flags (--prec-div, --prec-sqrt: IEEE division and sqrtf; expf, tanhf 2 ulps). +@@ -132,10 +132,16 @@ pub fn squares(x: []const u16, depth: usize, exact: bool) struct { ss: f64, r: R + return .{ .ss = ss, .r = .{ .lo = ss - e, .hi = ss + e } }; + } + +-/// 1 / sqrtf(ss / n + eps) in float64 and its range through the kernel's division, add, sqrtf and reciprocal. +-pub fn invNorm(ss: f64, r: Range, n: f64) struct { inv: f64, r: Range } { +- const mean = (Range{ .lo = r.lo / n, .hi = r.hi / n }).fp32(div_ulps); +- return .{ .inv = 1 / @sqrt(ss / n + eps), .r = mean.add(Range.of(eps)).fp32(0.5).up(sqrt).fp32(sqrt_ulps).recip().fp32(div_ulps) }; ++// CUDA's rsqrtf accuracy is 2 ULP from the rounded result; FP64 comparisons include its half-ULP rounding. ++pub const rsqrt_ulps = 2.5; ++ ++/// FP64 inverse RMS and the range through the actual division or reciprocal-FMA mean and rsqrtf. ++pub fn invNorm(ss: f64, r: Range, n: f64, fused_mean: bool) struct { inv: f64, r: Range } { ++ const mean = if (fused_mean) ++ r.mul(Range.of(1 / n).fp32(0.5)).add(Range.of(eps)).fp32(0.5) ++ else ++ (Range{ .lo = r.lo / n, .hi = r.hi / n }).fp32(div_ulps).add(Range.of(eps)).fp32(0.5); ++ return .{ .inv = 1 / @sqrt(ss / n + eps), .r = (Range{ .lo = 1 / @sqrt(mean.hi), .hi = 1 / @sqrt(mean.lo) }).fp32(rsqrt_ulps) }; + } + + pub fn input(rig: *rig_.Rig, x: anytype) !u64 { +diff --git a/zig/tests/cuda/contract_moss_image_steps.zig b/zig/tests/cuda/contract_moss_image_steps.zig +index f8d12bb6261a303902783a7a958ec74999a94b24..376c9512e0d89525eeda5d0e73cdaafa452fea01 100644 +--- a/zig/tests/cuda/contract_moss_image_steps.zig ++++ b/zig/tests/cuda/contract_moss_image_steps.zig +@@ -131,7 +131,7 @@ pub const Situ = struct { + } + }; + +-// --- tf_moss_gate_add: x = bf16(x + bf16(g y)), in place --------------------------------------------------------- ++// tf_moss_gate_add materializes one fused residual result in place. + + pub const GateAdd = struct { + rig: rig_.Rig, +@@ -153,7 +153,7 @@ pub const GateAdd = struct { + .accum = .none, + .depth = mi.noSums, + .ops = 1, +- .mids = 1, ++ .mids = 0, + .out = .bf16, + .in_place = true, + .tiles = .{ .{}, .{ .size = 256 }, .{} }, +@@ -227,8 +227,8 @@ pub const GateAdd = struct { + const x: f64 = c.fromBf16(xb); + const y: f64 = c.fromBf16(yb); + const gv: f64 = c.fromBf16(t.gv[i % t.shape.n]); +- const r = Range.of(gv * y).fp32(0.5).bf16().add(Range.of(x)).fp32(0.5).bf16(); +- t.ends.put(want, mag, i, bf(x + bf(gv * y)), r); ++ const r = Range.of(gv * y + x).fp32(0.5).bf16(); ++ t.ends.put(want, mag, i, bf(x + gv * y), r); + } + } + pub fn bounds(t: *GateAdd, want: []const f64, _: []const f64, allow: []f64) !void { +diff --git a/zig/tests/cuda/contract_moss_image_time.zig b/zig/tests/cuda/contract_moss_image_time.zig +new file mode 100644 +index 0000000000000000000000000000000000000000..86e61c097365adba9cd34748d7a122738f9a6a6c +--- /dev/null ++++ b/zig/tests/cuda/contract_moss_image_time.zig +@@ -0,0 +1,101 @@ ++//! Integer and actual adapter timestep grids, with FP64 sinusoids and derived FP32 transcendental ranges. ++const std = @import("std"); ++const moss = @import("moss_image_cuda"); ++const rig_ = @import("contract_rig.zig"); ++const mi = @import("contract_moss_image_ref.zig"); ++const c = mi.c; ++const g = mi.g; ++const Range = mi.Range; ++ ++pub const Time = struct { ++ rig: rig_.Rig, ++ k: moss.Kernels, ++ name: []const u8, ++ control: ?g.Gate = null, ++ shape: c.Shape = undefined, ++ fill: g.Fill = .random, ++ out: u64 = 0, ++ ends: mi.Ends, ++ ++ pub fn kernel(t: *Time) g.Kernel { ++ return .{ .spec = .{ .name = t.name, .accum = .none, .depth = mi.noSums, .ops = 12, .out = .bf16, .served = &.{.{ .rows = 2001, .n = 256, .k = 1 }} }, .ctx = t, .vt = &vt, .control = t.control }; ++ } ++ const vt = g.hooks(Time); ++ ++ pub fn deinit(t: *Time) void { ++ t.ends.deinit(); ++ t.rig.deinit(); ++ } ++ pub fn count(t: *Time) usize { ++ return t.shape.rows * 256; ++ } ++ ++ pub fn prepare(t: *Time, shape: c.Shape, fill: g.Fill, _: u64) !bool { ++ if (shape.n != 256 or shape.rows == 0) return false; ++ var inputs: [2001 * 4]u8 = undefined; ++ for (0..2001) |row| std.mem.writeInt(u32, inputs[row * 4 ..][0..4], @bitCast(gridTime(row)), .little); ++ var digest: [32]u8 = undefined; ++ std.crypto.hash.sha2.Sha256.hash(&inputs, &digest, .{}); ++ const hex = std.fmt.bytesToHex(digest, .lower); ++ if (!std.mem.eql(u8, &hex, "c60288519f0d6cb98ab71900de27efbf5b84d75e127b4b84f5b9d479e5fe7333")) return error.AdapterTimeGridChanged; ++ t.rig.reset(); ++ t.shape = shape; ++ t.fill = fill; ++ t.out = try t.rig.output(t.count() * 2); ++ return true; ++ } ++ ++ fn gridTime(row: usize) f32 { ++ @setFloatMode(.strict); ++ if (row <= 1000) return @floatFromInt(row); ++ const index = row - 1001; ++ const end: f32 = 1.0 / 1000.0; ++ const step: f32 = (end - 1.0) / 999.0; ++ const position: f32 = @floatFromInt(if (index < 500) index else 999 - index); ++ const product: f32 = step * position; ++ const sigma: f32 = if (index < 500) 1.0 + product else end - product; ++ return sigma * 1000.0; ++ } ++ ++ fn timestep(t: *const Time, row: usize) f32 { ++ if (t.fill == .nonfinite) return switch (row % 4) { ++ 0 => std.math.nan(f32), ++ 1 => std.math.inf(f32), ++ 2 => -std.math.inf(f32), ++ else => gridTime(row), ++ }; ++ return gridTime(row); ++ } ++ ++ pub fn run(t: *Time) !void { ++ for (0..t.shape.rows) |row| try moss.time(&t.k, t.rig.s, t.out + row * 256 * 2, t.timestep(row)); ++ try t.rig.s.synchronize(); ++ } ++ ++ pub fn reference(t: *Time, want: []f64, mag: []f64) !void { ++ try t.ends.size(t.count()); ++ const base: f64 = @as(f32, -9.210340371976184); ++ for (0..t.shape.rows) |row| for (0..128) |column| { ++ const i: f64 = @floatFromInt(column); ++ const step: f64 = t.timestep(row); ++ const phase = step * @exp(base * i / 128); ++ const exponent = Range.of(base * i).fp32(0.5).mul(Range.of(1.0 / 128.0)).fp32(0.5); ++ const frequency = Range.of(@exp(exponent.lo)); ++ const fr = Range{ .lo = frequency.lo, .hi = @exp(exponent.hi) }; ++ const pr = fr.fp32(2.5).mul(Range.of(step)).fp32(0.5); ++ const radius = @max(@abs(pr.lo - phase), @abs(pr.hi - phase)); ++ for (0..2) |part| { ++ const v = if (part == 0) @cos(phase) else @sin(phase); ++ const span = Range{ .lo = @max(-1, v - radius), .hi = @min(1, v + radius) }; ++ t.ends.put(want, mag, row * 256 + part * 128 + column, mi.bf(v), span.fp32(2.5).bf16()); ++ } ++ }; ++ } ++ ++ pub fn bounds(t: *Time, want: []const f64, _: []const f64, allow: []f64) !void { ++ t.ends.bounds(want, allow); ++ } ++ pub fn intervals(t: *Time, low: []f64, high: []f64) !void { ++ t.ends.intervals(low, high); ++ } ++}; +diff --git a/zig/tests/cuda/moss_contract_main.zig b/zig/tests/cuda/moss_contract_main.zig +new file mode 100644 +index 0000000000000000000000000000000000000000..b9c4ef7d4c74c32bc04ba29ff935ea97f5611381 +--- /dev/null ++++ b/zig/tests/cuda/moss_contract_main.zig +@@ -0,0 +1,16 @@ ++//! The MOSS companion's CUDA contract runner. ++const std = @import("std"); ++const cuda = @import("cuda"); ++ ++pub fn main(init: std.process.Init) !void { ++ var driver = try cuda.Driver.open(); ++ defer driver.close(); ++ var context = try cuda.Context.init(&driver, 0); ++ defer context.deinit(); ++ const gpu: @import("check.zig").Gpu = .{ .d = &driver, .ctx = &context, .gpa = init.gpa, .io = init.io }; ++ const args = try init.minimal.args.toSlice(init.arena.allocator()); ++ const record_only = args.len == 2 and std.mem.eql(u8, args[1], "--record"); ++ if (!record_only) try @import("contract_moss_image.zig").run(gpu); ++ const failures = try @import("contract_moss_image_limits.zig").audit(gpu, record_only); ++ if (failures != 0) return error.KernelLimitsFailed; ++} +diff --git a/zig/tests/moss_image_run.zig b/zig/tests/moss_image_run.zig +index da0e873f7df497ad8c2466a65932f5c6f5a65faf..83953338fe0ca3e8059dc1b2fbfd8d1b8d84792c 100644 +--- a/zig/tests/moss_image_run.zig ++++ b/zig/tests/moss_image_run.zig +@@ -201,7 +201,7 @@ pub fn run(comptime B: type, init: std.process.Init) !u8 { + for (x, cond, uncond) |*o, pc, pu| o.* += (pu + guidance * (pc - pu)) * by; + const wall = c.wall + u.wall; + total += wall; +- std.debug.print("step {d}/{d}: {d:.3} s ({d:.3} s on the GPU, {d:.3} s modulation on the host)\n", .{ s + 1, steps, wall, c.gpu + u.gpu, c.host + u.host }); ++ std.debug.print("step {d}/{d}: {d:.3} s ({d:.3} s on the GPU, {d:.3} s modulation setup)\n", .{ s + 1, steps, wall, c.gpu + u.gpu, c.host + u.host }); + try print(&out, a, "{s}{{\"wall_s\": {d:.4}, \"gpu_s\": {d:.4}, \"host_s\": {d:.4}}}", .{ if (s == 0) "" else ", ", wall, c.gpu + u.gpu, c.host + u.host }); + } + try print(&out, a, "], \"denoise_s\": {d:.3}", .{total}); diff --git a/tools/comfyui_runtime/tf_installer/network.py b/tools/comfyui_runtime/tf_installer/network.py new file mode 100644 index 00000000000..f39746b82a1 --- /dev/null +++ b/tools/comfyui_runtime/tf_installer/network.py @@ -0,0 +1,126 @@ +import json +import re +import time +import urllib.error +import urllib.parse +import urllib.request +from pathlib import Path + +from .archive import parse_sums +from .pins import InstallError, MAX_ARCHIVE_BYTES, RELEASE_API, RELEASE_BASE + + +ALLOWED_HOSTS = frozenset({"api.github.com", "github.com", "codeload.github.com", "release-assets.githubusercontent.com", "objects.githubusercontent.com"}) +VERSION = re.compile(r"(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)") + + +def checked_url(url): + try: + parts = urllib.parse.urlsplit(url) + if parts.scheme != "https" or parts.hostname not in ALLOWED_HOSTS or parts.username or parts.password or parts.port not in (None, 443) or parts.fragment: + raise InstallError("Download URL is outside the official HTTPS hosts.") + except ValueError as error: + raise InstallError("Malformed download URL.") from error + return url + + +class OfficialRedirects(urllib.request.HTTPRedirectHandler): + max_redirections = 5 + + def redirect_request(self, req, fp, code, msg, headers, newurl): + checked_url(newurl) + return super().redirect_request(req, fp, code, msg, headers, newurl) + + +def download(url, path, limit, timeout=300, opener=None): + checked_url(url) + media_type = "application/vnd.github+json" if urllib.parse.urlsplit(url).hostname == "api.github.com" else "application/octet-stream" + request = urllib.request.Request(url, headers={"User-Agent": "TensorFold-ComfyUI-installer/1", "Accept": media_type}) + opener = opener or urllib.request.build_opener(OfficialRedirects()) + deadline = time.monotonic() + timeout + path = Path(path) + try: + with opener.open(request, timeout=min(30, timeout)) as response, path.open("xb") as output: + checked_url(response.geturl()) + if response.status != 200: + raise InstallError(f"Download returned HTTP {response.status}.") + raw_length = response.headers.get("Content-Length") + if raw_length is not None and (not raw_length.isdigit() or int(raw_length) > limit): + raise InstallError("Download Content-Length exceeds its limit or is malformed.") + size = 0 + while True: + if time.monotonic() > deadline: + raise InstallError("Download exceeded its time budget.") + block = response.read1(min(1024 * 1024, limit - size + 1)) + if not block: + break + size += len(block) + if size > limit: + raise InstallError("Download exceeds its size limit.") + output.write(block) + if raw_length is not None and size != int(raw_length): + raise InstallError("Download ended before its declared Content-Length.") + except (OSError, urllib.error.URLError, ValueError) as error: + raise InstallError(f"Download failed: {error}") from error + return path + + +def version_tuple(value): + if not isinstance(value, str) or not VERSION.fullmatch(value): + raise InstallError("Release version is not stable MAJOR.MINOR.PATCH.") + return tuple(int(part) for part in value.split(".")) + + +def select_release(metadata, platform): + if not isinstance(metadata, dict) or metadata.get("draft") is not False or metadata.get("prerelease") is not False: + raise InstallError("GitHub did not return a stable published release.") + tag = metadata.get("tag_name", "") + if not isinstance(tag, str) or not tag.startswith("v"): + raise InstallError("Release tag has no v prefix.") + version = tag[1:] + version_tuple(version) + filename = f"tensorfold-{version}-{platform}.tar.gz" + assets = metadata.get("assets") + if not isinstance(assets, list): + raise InstallError("Release assets are missing.") + selected = {} + for name in (filename, filename + ".sha256"): + matches = [asset for asset in assets if isinstance(asset, dict) and asset.get("name") == name] + if len(matches) != 1: + raise InstallError(f"Release needs exactly one {name} asset.") + asset = matches[0] + expected = f"{RELEASE_BASE}/{tag}/{name}" + if asset.get("browser_download_url") != expected: + raise InstallError("Release asset URL does not match its official name and tag.") + size = asset.get("size") + limit = MAX_ARCHIVE_BYTES if name == filename else 65536 + if type(size) is not int or not 0 < size <= limit: + raise InstallError("Release asset size is invalid.") + selected[name] = asset + return {"version": version, "filename": filename, "assets": selected} + + +def get_release(work, platform, fetch=download): + metadata_path = fetch(RELEASE_API, work / "release.json", 2 * 1024 * 1024) + try: + return select_release(json.loads(metadata_path.read_text(encoding="utf-8")), platform) + except (UnicodeError, json.JSONDecodeError) as error: + raise InstallError("Release metadata is not valid JSON.") from error + + +def fetch_release(work, release, fetch=download): + filename = release["filename"] + archive_asset = release["assets"][filename] + checksum_asset = release["assets"][filename + ".sha256"] + checksum_path = fetch(checksum_asset["browser_download_url"], work / "release.sha256", 65536) + sums = parse_sums(checksum_path.read_text(encoding="ascii")) + if set(sums) != {filename}: + raise InstallError("Companion checksum must name exactly this archive.") + digest = sums[filename] + published = archive_asset.get("digest") + if published is not None and published != f"sha256:{digest}": + raise InstallError("GitHub's asset digest and companion checksum disagree.") + archive = fetch(archive_asset["browser_download_url"], work / filename, MAX_ARCHIVE_BYTES) + if archive.stat().st_size != archive_asset["size"]: + raise InstallError("Downloaded archive size differs from release metadata.") + return release["version"], archive, digest diff --git a/tools/comfyui_runtime/tf_installer/pins.py b/tools/comfyui_runtime/tf_installer/pins.py new file mode 100644 index 00000000000..845c959dc5e --- /dev/null +++ b/tools/comfyui_runtime/tf_installer/pins.py @@ -0,0 +1,16 @@ +SOURCE_REVISION = "1ddac962008367ec2c50e10202c910ecf430b5eb" +SOURCE_PATCH_SHA256 = "e6156ed11263a2d32586245b1702a6bc47ac0049e65bf1724afad69242eb617f" +SOURCE_SHA256 = "013d687c5b72718220ac8e137252492d72be85d27ff9cec37525d714c52dc2ba" +SOURCE_URL = f"https://codeload.github.com/ashhart/TensorFold/tar.gz/{SOURCE_REVISION}" +SOURCE_ROOT = f"TensorFold-{SOURCE_REVISION}" +ZIG_VERSION = "0.17.0" +RELEASE_API = "https://api.github.com/repos/ashhart/TensorFold/releases/latest" +RELEASE_BASE = "https://github.com/ashhart/TensorFold/releases/download" +MAX_ARCHIVE_BYTES = 1024 * 1024 * 1024 +MAX_EXTRACTED_BYTES = 3 * 1024 * 1024 * 1024 +MAX_SOURCE_BYTES = 256 * 1024 * 1024 +MAX_SOURCE_EXTRACTED_BYTES = 1024 * 1024 * 1024 + + +class InstallError(Exception): + pass diff --git a/tools/comfyui_runtime/tf_installer/worker.py b/tools/comfyui_runtime/tf_installer/worker.py new file mode 100644 index 00000000000..00be7900038 --- /dev/null +++ b/tools/comfyui_runtime/tf_installer/worker.py @@ -0,0 +1,13 @@ +import os + +from .device import nvidia_smi, require_gb10 +from .install import manifest_file, read_status, runtime_root + + +def start_worker(comfy_root, arguments, gpu=nvidia_smi, execute=None): + """Replace this process with the installed MOSS worker; any GPU but GB10's sm_121 is refused before it starts.""" + require_gb10(gpu) + root = runtime_root(comfy_root) + manifest = read_status(root) + worker = manifest_file(root, manifest["artifacts"]["moss"]["path"], executable=True) + (execute or os.execv)(str(worker), [str(worker), *arguments]) diff --git a/tools/tests/fake_served_api.py b/tools/tests/fake_served_api.py index b7ed32cae48..23c00871b55 100644 --- a/tools/tests/fake_served_api.py +++ b/tools/tests/fake_served_api.py @@ -60,6 +60,8 @@ import threading import time +from fake_stream_pair import StreamPairs + FAULTS = ("drafted", "repeat", "concurrent", "resumed", "refusals", "cancel_lane", "cancel_free", "cancel_reply", "cancel_health", "evict", "undrafted", "plain_drafts", "sampled_drafts", "unsampled", "serial", "empty") BATCH_WINDOW = 0.15 # seconds a lone request waits for a partner under the concurrent fault @@ -207,11 +209,14 @@ def do_POST(self): key = json.dumps({k: v for k, v in body.items() if k not in ("stream", "stream_options")}, sort_keys=True) if server.prefill and not body.get("stream") and self.left(server.prefill): return - with server.one if server.fault == "serial" else contextlib.nullcontext(): + pair = server.stream_pairs if body.get("stream") and server.fault != "serial" else None + with server.one if server.fault == "serial" else contextlib.nullcontext(), \ + (pair.claim() if pair else contextlib.nullcontext()) as slot: payload = self.answer(body, key) # Out of flight before the reply is written: the client's next request must not find this one counted. if body.get("stream"): - self.play(streamed(payload, body.get("max_tokens", 16), TOKEN_GAP), key) + steps = streamed(payload, body.get("max_tokens", 16), TOKEN_GAP) + self.play(pair.steps(steps, slot) if pair else steps, key) else: self.reply(200, payload) with server.lock: @@ -363,12 +368,13 @@ def play(self, steps, key=None): @contextlib.contextmanager -def running(cache=False, fault=None, linger=0.0, steps=None, warm=0.0, lanes_free=True, prefill=0.0): +def running(cache=False, fault=None, linger=0.0, steps=None, warm=0.0, lanes_free=True, prefill=0.0, *, pair_streams=False): """One fake on 127.0.0.1 port 0, yielding its base URL; stopped on exit.""" server = FixtureHTTPServer(("127.0.0.1", 0), FakeEngine) server.cache, server.fault, server.seen, server.inflight, server.linger = cache, fault, {}, 0, linger server.steps, server.kept, server.evicted, server.cut = steps, collections.OrderedDict(), set(), set() server.streams = server.leaked = server.lost = server.disconnects = server.overlaps = 0 + server.stream_pairs = StreamPairs(COUNTED) if pair_streams else None server.warm, server.warm_until, server.lanes_free, server.prefill = warm, 0.0, lanes_free, prefill server.census_at, server.census_gap = -1e9, 1e9 # no census read yet server.lock, server.one = threading.Lock(), threading.Lock() @@ -389,7 +395,7 @@ def fake(cache, fault=None, linger=0.0, **shape): # linger: seconds each handler stays alive after its reply, widening any window between reply and exit. if fault not in (None, *FAULTS): raise ValueError(f"unknown fault {fault}") - # shape: warm, lanes_free and prefill, see ``running``. + # shape: warm, lanes_free, prefill; pair_streams opts the served-evidence fixture into visible-text rendezvous. with running(cache, fault, linger, **shape) as url: yield url diff --git a/tools/tests/fake_stream_pair.py b/tools/tests/fake_stream_pair.py new file mode 100644 index 00000000000..c21938b7315 --- /dev/null +++ b/tools/tests/fake_stream_pair.py @@ -0,0 +1,73 @@ +"""Optional rendezvous for the served-evidence fixture; ordinary conformance streams keep their original pacing.""" +import contextlib +import json +import threading +import time + + +def content(step): + """Whether this SSE event contains visible text.""" + return isinstance(step, bytes) and step.startswith(b"data: {") and any( + c.get("delta", {}).get("content") for c in json.loads(step[6:]).get("choices", [])) + + +class StreamPairs: + """Pair active generated replies; a lone reply never waits for admission.""" + + def __init__(self, timeout): + self.timeout = timeout + self.lock = threading.Lock() + self.pending = None + + @contextlib.contextmanager + def claim(self): + with self.lock: + slot = self.pending + if slot is None: + slot = [None, None] + self.pending = slot + else: + slot[0] = threading.Barrier(2) + self.pending = None + try: + yield slot + finally: + with self.lock: + barrier = slot[0] + if self.pending is slot: + self.pending = None + if barrier is not None: + barrier.abort() + + def meet(self, slot): + with self.lock: + barrier = slot[0] + if barrier is not None and slot[1] is None: + slot[1] = time.monotonic() + self.timeout + if barrier is not None: + try: + barrier.wait(timeout=max(0.0, slot[1] - time.monotonic())) + except threading.BrokenBarrierError: + pass + + def steps(self, steps, slot): + """Keep every byte and pause; spread visible text across the existing generated-stream pause budget.""" + events = [s for s in steps if isinstance(s, bytes)] + pauses = [s for s in steps if not isinstance(s, bytes)] + visible = sum(bool(content(s)) for s in events) + if pauses and visible > 2: + paced, slept = [], 0 + for index, step in enumerate(events): + due = min(index, visible - 2) * (len(pauses) - 1) // (visible - 2) + due += index >= visible - 1 + paced.extend(pauses[slept:due]) + paced.append(step) + slept = due + steps = paced + for step in steps: + visible = content(step) + if visible: + self.meet(slot) + yield step + if visible: + self.meet(slot) diff --git a/tools/tests/test_bench_fake_stream_pair.py b/tools/tests/test_bench_fake_stream_pair.py new file mode 100644 index 00000000000..afd3113a5e8 --- /dev/null +++ b/tools/tests/test_bench_fake_stream_pair.py @@ -0,0 +1,76 @@ +"""Pairing is a served-evidence fixture option; conformance, scripts and serial faults keep their step order.""" +import io +import json +from pathlib import Path +import sys +import threading +from types import SimpleNamespace +import unittest +from unittest import mock + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import fake_served_api as fake + + +class PairingScopeTests(unittest.TestCase): + def post(self, body, *, fault=None, pairs=None, script=None): + server = SimpleNamespace(steps=script, fault=fault, prefill=0.0, stream_pairs=pairs, + one=threading.Lock(), lock=threading.Lock(), warm=0.0, linger=0.0) + handler = object.__new__(fake.FakeEngine) + raw = json.dumps(body).encode() + handler.server, handler.rfile = server, io.BytesIO(raw) + handler.headers = {"Content-Length": str(len(raw))} + handler.answer = lambda *_: fake.doc(text="abcdefg") + played, replied = [], [] + handler.play = lambda steps, key=None: played.append(list(steps)) + handler.reply = lambda status, payload: replied.append((status, payload)) + handler.do_POST() + return played, replied + + def test_conformance_streams_keep_the_original_pacing(self): + expected = fake.streamed(fake.doc(text="abcdefg"), 64, fake.TOKEN_GAP) + faults = (None, "concurrent", "unsampled", "cancel_lane", "cancel_free", "cancel_reply", "cancel_health") + for fault in faults: + with self.subTest(fault=fault): + played, replied = self.post({"stream": True, "max_tokens": 64}, fault=fault) + self.assertEqual(played, [expected]) + self.assertEqual(replied, []) + + def test_serial_json_script_and_refusal_never_join(self): + pairs = mock.Mock() + pairs.claim.side_effect = AssertionError("unrelated path joined the served-evidence rendezvous") + played, _ = self.post({"stream": True, "max_tokens": 4}, fault="serial", pairs=pairs) + self.assertEqual(played, [fake.streamed(fake.doc(text="abcdefg"), 4, fake.TOKEN_GAP)]) + _, replied = self.post({"max_tokens": 4}, pairs=pairs) + self.assertEqual(replied, [(200, fake.doc(text="abcdefg"))]) + script = [b"data: [DONE]\n\n"] + played, _ = self.post({"stream": True}, pairs=pairs, script=lambda _: script) + self.assertEqual(played, [script]) + _, replied = self.post({"stream": True, "n": 2}, pairs=pairs) + self.assertEqual(replied[0][0], 400) + pairs.claim.assert_not_called() + + def test_running_requires_explicit_pairing(self): + for shape, enabled in (({}, False), ({"pair_streams": True}, True)): + with self.subTest(enabled=enabled), mock.patch.object(fake, "FixtureHTTPServer") as factory: + server = factory.return_value + server.server_address = ("127.0.0.1", 1) + with fake.running(**shape): + self.assertEqual(isinstance(server.stream_pairs, fake.StreamPairs), enabled) + if not enabled: + self.assertIsNone(server.stream_pairs) + + def test_opted_in_stream_uses_pairing_and_keeps_every_byte_and_pause(self): + pairs = fake.StreamPairs(fake.COUNTED) + played, replied = self.post({"stream": True, "max_tokens": 512}, pairs=pairs) + original = fake.streamed(fake.doc(text="abcdefg"), 512, fake.TOKEN_GAP) + for kind in (bytes, float): + self.assertEqual([s for s in played[0] if isinstance(s, kind)], + [s for s in original if isinstance(s, kind)]) + self.assertNotEqual(played[0], original) + self.assertEqual(replied, []) + self.assertIsNone(pairs.pending) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_bench_served_evidence.py b/tools/tests/test_bench_served_evidence.py index 3955638b3be..bce1ff19b26 100644 --- a/tools/tests/test_bench_served_evidence.py +++ b/tools/tests/test_bench_served_evidence.py @@ -23,7 +23,7 @@ def concurrent(fault=None): 512 tokens keep each stream ~0.1 s long at the fake's token gap, so the two streams overlap on a slow runner too (20 Nov: at 64 tokens a hosted Windows runner decoded them one after the other and main went red).""" - with tempfile.TemporaryDirectory() as folder, fake(False, fault) as url: + with tempfile.TemporaryDirectory() as folder, fake(False, fault, pair_streams=True) as url: out = Path(folder) / "out.json" subprocess.run([sys.executable, str(TOOLS / "bench_concurrent.py"), url, "fake", "--levels", "2", "--reps", "1", "--temperatures", "0", "--tokens", "512", "--alone", "--serial", "--output", str(out)], diff --git a/tools/zig/drama3_compact_gb10.sh b/tools/zig/drama3_compact_gb10.sh index a0990d7c359..2f63e445e01 100755 --- a/tools/zig/drama3_compact_gb10.sh +++ b/tools/zig/drama3_compact_gb10.sh @@ -26,8 +26,8 @@ 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 -# a pruned checkpoint: an unpruned NVFP4 one keeps the original router in every layer and stops here -grep -q 'routed experts NVFP4 in 40 of 40 layers; compact routers in 40 of 40 layers' "$out/compact.log" +# 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" # 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 diff --git a/tools/zig/drama3_limits_gate.sh b/tools/zig/drama3_limits_gate.sh index 4fb9cf684c3..744879ec16c 100755 --- a/tools/zig/drama3_limits_gate.sh +++ b/tools/zig/drama3_limits_gate.sh @@ -1,6 +1,5 @@ #!/bin/sh -# drama3_limits_gate.sh STATUS LOG: every launch and control is within limits and d3_router_compact was audited on all -# five SMs. Stale records fail no launch: d3_router_compact's is pending, others belong to their own launches' receipts. +# drama3_limits_gate.sh STATUS LOG: fails unless d3_router_compact was audited on all five SMs; stale records pass. status=$1 log=$2 grep -Eq '^(FAIL|MISSED) limits' "$log" && exit 1 [ "$(grep -c '^PASS limits sm_[0-9]* drama3 d3_router_compact: ' "$log")" -eq 5 ] || exit 1 diff --git a/tools/zig/drama3_limits_gate_test.py b/tools/zig/drama3_limits_gate_test.py index 335012781f7..6e85e9bc948 100644 --- a/tools/zig/drama3_limits_gate_test.py +++ b/tools/zig/drama3_limits_gate_test.py @@ -1,4 +1,4 @@ -"""drama3_limits_gate.sh: stale records pass, a failed launch, missing image, missed control or unaudited router fails.""" +"""drama3_limits_gate.sh: stale records pass; a failed launch, missing image or unaudited router fails.""" import re import subprocess import tempfile diff --git a/tools/zig/idol_case.py b/tools/zig/idol_case.py index bb5b662c452..51c5cf3dc10 100644 --- a/tools/zig/idol_case.py +++ b/tools/zig/idol_case.py @@ -20,8 +20,11 @@ the SDK's decode of CASE's final sample: each octree level's parents, probabilities, draws and counts, the anchors, the Gaussian decoder's raw rows, the activated Gaussians, the PLY and the camera (OUT/decode.*) + vae VAE SDK IMAGE OUT [--stages] the FLUX.2 VAE rows of a preprocessed image: the SDK's, then float64's WEIGHTS is a speridlabs/idol snapshot; SDK an idol-sdk checkout at the pinned commit. F holds feature1 (DINOv3 rows [1, 4101, 1280]) and feature2 (FLUX.2 VAE rows [1, 4101, 128]), in one file or two, as the SDK's ImageEncoder returns. +VAE is the vae/ folder of black-forest-labs/FLUX.2-klein-4B at the pinned revision (FLUX.2-dev's gives the same bf16 +weights); IMAGE the 1024 x 1024 RGB picture IdolPipeline.preprocess returns. """ SDK_COMMIT = "4702a7f00850e34b6e83a2170cc123c3e9570744" @@ -495,7 +498,7 @@ def recorded_like(*a, **k): "ruler_device": args.ruler_device if args.ruler else None} (out / "decode.json").write_text(json.dumps(meta, indent=1) + "\n") print(json.dumps(meta)) - return 0 + def main(argv: list[str]) -> int: @@ -510,6 +513,13 @@ def main(argv: list[str]) -> int: d.add_argument("--ruler", action="store_true", help="both decoders again in float32 on the SDK's own inputs") d.add_argument("--ruler-device", default="cpu", choices=("mps", "cpu", "cuda")) d.add_argument("--time-only", action="store_true", help="the timed decode alone, nothing recorded") + p = sub.add_parser("vae") + for name in ("vae", "sdk", "image", "out_dir"): + p.add_argument(name) + p.add_argument("--device", default="mps", choices=("mps", "cpu", "cuda")) + p.add_argument("--seed", type=int, default=42) + p.add_argument("--repeats", type=int, default=5, help="timed encodes after the first") + p.add_argument("--stages", action="store_true", help="float64's down blocks, mid block and moments too") for name in ("case", "blocks", "exact"): p = sub.add_parser(name) p.add_argument("weights") @@ -530,6 +540,10 @@ def main(argv: list[str]) -> int: else: p.add_argument("--steps", type=int, default=50) args = ap.parse_args(argv) + if args.cmd == "vae": + sys.path.insert(0, str(Path(__file__).resolve().parent)) + from idol_vae_case import vae_case + return vae_case(args) return {"case": case, "blocks": blocks, "exact": exact, "decode": decode}[args.cmd](args) diff --git a/tools/zig/idol_vae_case.py b/tools/zig/idol_vae_case.py new file mode 100644 index 00000000000..5cfa4ef1bde --- /dev/null +++ b/tools/zig/idol_vae_case.py @@ -0,0 +1,148 @@ +"""idol_case.py vae: the SDK's FLUX.2 VAE rows for a preprocessed picture, its posterior noise and a float64 ruler.""" + +from __future__ import annotations + +import hashlib +import json +import sys +import time +from pathlib import Path + +from idol_case import SDK_COMMIT, flush + +CONDITIONING_SHA256 = "8c9cc50d327df3a5269cda392ef46cf4ed9c1e603f42f46050beda83f355f5ab" +DIFFUSERS_VERSION = "0.42.1" +DIFFUSERS_SHA256 = { + "models/autoencoders/autoencoder_kl_flux2.py": "1afe08d76a93e994a453bd9036b57d173516211c2e6b9794ea64f485bea57f57", + "models/autoencoders/vae.py": "59b51fdf2d951da45d697569271e0c99adf4a959ec0f91885f3d9314e925a12c", + "models/unets/unet_2d_blocks.py": "545d158c9d98fb8971c501303117fd3e32d27ae28506b89005c65548404f7437", + "models/resnet.py": "77ad799719fa51bf0fc703f0486915b791c9b69673983abeb3e32c6edcc76650", + "models/downsampling.py": "bce174aa8007b2c40787331e7f46b31eef1eab7785f16b4e54733553b3d14724", + "models/attention_processor.py": "59871fd4e66fc14a26f0e0464706ab24680e13dcd93161c55123678a5e671772", + "utils/torch_utils.py": "bce0a1a4488557e8f80dc02de5782c2b510e91ba2e07f7ae8d26168cee9afc2a", +} +# FLUX.2-klein-4B's vae/ (Apache 2.0, ungated) at its pinned revision, and FLUX.2-dev's: the same weights once in bf16 +VAE_REVISION = "e7b7dc27f91deacad38e78976d1f2b499d76a294" +VAE_SHA256 = {"ca70d2202afe6415bdbcb8793ba8cd99fd159cfe6192381504d6c4d3036e0f04": "FLUX.2-klein-4B", + "d64f3a68e1cc4f9f4e29b6e0da38a0204fe9a49f2d4053f0ec1fa1ca02f9c4b5": "FLUX.2-dev"} + + +def flux2_vae(vae_dir: str, sdk_dir: str): + """The SDK's ImageEncoder and diffusers' FLUX.2 VAE (bf16, as the SDK loads it), each file used checked first.""" + import diffusers + import torch + + def pinned(path: Path, want: str, what: str) -> None: + digest = hashlib.sha256(path.read_bytes()).hexdigest() + if digest != want: + sys.exit(f"{path} has sha256 {digest}; this tool runs only {what}'s ({want})") + + pinned(Path(sdk_dir) / "idol/conditioning.py", CONDITIONING_SHA256, f"idol-sdk {SDK_COMMIT[:12]}") + if diffusers.__version__ != DIFFUSERS_VERSION: + sys.exit(f"diffusers is {diffusers.__version__}; this tool runs only {DIFFUSERS_VERSION}") + root = Path(diffusers.__file__).parent + for name, want in DIFFUSERS_SHA256.items(): + pinned(root / name, want, f"diffusers {DIFFUSERS_VERSION}") + weights = Path(vae_dir) / "diffusion_pytorch_model.safetensors" + digest = hashlib.sha256(weights.read_bytes()).hexdigest() + if digest not in VAE_SHA256: + sys.exit(f"{weights} is neither FLUX.2-klein-4B {VAE_REVISION[:12]}'s vae/ nor FLUX.2-dev's") + sys.path.insert(0, str(Path(sdk_dir))) + from diffusers.models import AutoencoderKLFlux2 + from idol.conditioning import ImageEncoder + + vae = AutoencoderKLFlux2.from_pretrained(vae_dir, torch_dtype=torch.bfloat16) + return ImageEncoder, vae.eval().requires_grad_(False), VAE_SHA256[digest] + + +def tokens64(vae, pixels, noise): + """ImageEncoder._flux2_tokens's steps in float64 with the SDK's noise: the ruler, and each stage when asked.""" + import torch + + latents = vae.encode(pixels * 2 - 1).latent_dist + latents = latents.mean + latents.std * noise + batch, channels, height, width = latents.shape + latents = latents.view(batch, channels, height // 2, 2, width // 2, 2).permute(0, 1, 3, 5, 2, 4) + latents = latents.reshape(batch, channels * 4, height // 2, width // 2) + mean = vae.bn.running_mean.view(1, -1, 1, 1) + std = torch.sqrt(vae.bn.running_var.view(1, -1, 1, 1) + vae.config.batch_norm_eps) + rows = ((latents - mean) / std).flatten(2).transpose(1, 2) + return torch.cat([torch.zeros(batch, 5, rows.shape[2], dtype=rows.dtype), rows], dim=1) + + +def distance(ours, ruler) -> dict: + """1 - cosine and the worst row's relative L2 error against the ruler, the rows of 128 as tf-idol-vae reads them.""" + a, b = ours.double().reshape(-1, 128), ruler.double().reshape(-1, 128) + cos = float((a * b).sum() / (a.norm() * b.norm())) + rows = ((a - b).norm(dim=1) / b.norm(dim=1).clamp_min(1e-30)).max() + return {"one_minus_cos": 1 - cos, "worst_row": float(rows), "max_abs": float((a - b).abs().max())} + + +def vae_case(args) -> int: + """The SDK's feature2 for one image on MPS (seeded as IdolPipeline seeds it), its noise, and the float64 ruler.""" + import types + + import diffusers.models.autoencoders.vae as vae_module + import numpy as np + import torch + from PIL import Image + from safetensors.torch import save_file + + out = Path(args.out_dir) + out.mkdir(parents=True, exist_ok=True) + image_encoder, vae, source = flux2_vae(args.vae, args.sdk) + picture = Image.open(args.image).convert("RGB") + if picture.size != (1024, 1024): + sys.exit(f"{args.image} is {picture.size}; the encoders see the 1024 x 1024 picture preprocess returns") + pixels = torch.from_numpy(np.array(picture)).permute(2, 0, 1).float().div(255.0)[None] + encoder = types.SimpleNamespace(flux2_vae=vae.to(args.device)) + drawn = [] + randn = vae_module.randn_tensor + + def recorded(*a, **k): + drawn.append(randn(*a, **k)) + return drawn[-1] + + vae_module.randn_tensor = recorded + times = [] + with torch.no_grad(): + for i in range(args.repeats + 1): + torch.manual_seed(args.seed) + mark = time.perf_counter() + rows = image_encoder._flux2_tokens(encoder, pixels.to(args.device)) + flush(args.device) + times.append(time.perf_counter() - mark) + if i == 0: + sdk_rows, noise = rows[0].cpu(), drawn[0].float().cpu() + vae_module.randn_tensor = randn + if any(not torch.equal(d.float().cpu(), noise) for d in drawn): + sys.exit("the seeded noise differs between encodes") + stages = {} + hooks = [] + if args.stages: + named = [(f"down.{i}", b) for i, b in enumerate(vae.encoder.down_blocks)] + [("mid", vae.encoder.mid_block)] + named.append(("moments", vae.quant_conv)) + for name, module in named: + def keep(_m, _i, output, name=name): + stages[name] = output[0].permute(1, 2, 0).float().contiguous() + hooks.append(module.register_forward_hook(keep)) + vae64 = vae.to("cpu").double() + with torch.no_grad(): + mark = time.perf_counter() + ruler = tokens64(vae64, pixels.double(), noise.double())[0] + ruler_s = time.perf_counter() - mark + for h in hooks: + h.remove() + tensors = {"image": pixels[0].permute(1, 2, 0).contiguous(), "noise": noise[0].permute(1, 2, 0).contiguous(), + "sdk": sdk_rows.float().contiguous(), "ruler": ruler.float().contiguous()} + save_file(tensors, str(out / "vae.safetensors")) + if stages: + save_file(stages, str(out / "vae_stages.safetensors")) + sdk = distance(sdk_rows, ruler) + meta = {"seed": args.seed, "device": args.device, "torch": torch.__version__, "sdk": SDK_COMMIT, + "diffusers": DIFFUSERS_VERSION, "vae": source, "vae_revision": VAE_REVISION, + "sdk_vs_float64": sdk, "float64_s": round(ruler_s, 2), "encode_s": [round(t, 4) for t in times]} + (out / "vae.json").write_text(json.dumps(meta, indent=1) + "\n") + warm = sorted(times[1:]) or times + print(json.dumps(meta | {"median_encode_s": warm[len(warm) // 2]})) + return 0 diff --git a/tools/zig/ling_forward_check.py b/tools/zig/ling_forward_check.py new file mode 100644 index 00000000000..cc5b7c9f65c --- /dev/null +++ b/tools/zig/ling_forward_check.py @@ -0,0 +1,93 @@ +"""Run native Ling whole/chunk/resume checks beside the one FP64 oracle on identical routed picks.""" +import argparse +import array +import json +import math +import os +from pathlib import Path +import shutil +import struct +import sys +import subprocess +import tempfile + +ROOT = Path(__file__).resolve().parents[2] + + +def compare(native, reference): + data = reference.read_bytes() + if data[:8] != b"TFLINGF2": + raise ValueError("unexpected oracle format") + tokens, vocab, layers, topk = struct.unpack_from("<4I", data, 8) + at = 36 + tokens * 4 + exact = array.array("d", data[at:at + tokens * vocab * 8]) + rounded = array.array("d", data[at + tokens * vocab * 8:at + tokens * vocab * 16]) + metal = array.array("f", native.read_bytes()) + if len(metal) != tokens * vocab: + raise ValueError("native logits shape mismatch") + rows = [] + for row in range(tokens): + lo, hi = row * vocab, (row + 1) * vocab + a, b, g = exact[lo:hi], rounded[lo:hi], metal[lo:hi] + if not all(math.isfinite(v) for v in g): + raise ValueError("non-finite native logits") + pair = {} + for name, values in (("metal", g), ("bf16", b)): + errors = [x - y for x, y in zip(values, a)] + pair[name] = {"rms": math.sqrt(math.fsum(x*x for x in errors) / vocab), + "max": max(map(abs, errors)), "top": max(range(vocab), key=values.__getitem__)} + pair["top64"] = max(range(vocab), key=a.__getitem__) + rows.append(pair) + result = {"tokens": tokens, "moe_layers": layers, "top_k": topk, "rows": rows, + "forced_gap": struct.unpack_from(" r["bf16"]["rms"] for r in rows) + result["top_tokens_equal"] = all(r["metal"]["top"] == r["bf16"]["top"] == r["top64"] for r in rows) + result["accuracy_acceptance"] = "unresolved; distances reported without relaxing the reference bound" + return result + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--binary", type=Path, required=True) + parser.add_argument("--counts", type=int, nargs="+", default=[2, 8, 32]) + parser.add_argument("--out", type=Path) + args = parser.parse_args() + checkpoint = os.environ.get("TF_LING_CHECKPOINT") + if not checkpoint or not (Path(checkpoint) / "model.safetensors.index.json").is_file(): + print("SKIP Ling full forward: set TF_LING_CHECKPOINT to the bf16 Ling-3.0-tiny checkpoint") + return + python = os.environ.get("TF_LING_PYTHON") or shutil.which("python3") + if not python: + print("SKIP Ling oracle: set TF_LING_PYTHON or install python3 on PATH") + return + probe = subprocess.run([python, "-c", "import torch, safetensors"], capture_output=True) + if probe.returncode: + print("SKIP Ling oracle: selected Python needs torch and safetensors") + return + with tempfile.TemporaryDirectory(prefix="ling-forward-") as temp: + out = args.out or Path(temp) + out.mkdir(parents=True, exist_ok=True) + for count in args.counts: + native, reference = out / f"native-{count}.f32", out / f"reference-{count}.bin" + if sys.platform == "darwin": + pressure = subprocess.check_output(["memory_pressure"], text=True) + free = int(pressure.split("System-wide memory free percentage:")[-1].strip().rstrip("%")) + if free <= 40: + raise RuntimeError("memory free is at or below 40%; refusing the Ling GPU run") + subprocess.run([str(args.binary.resolve()), checkpoint, str(native), str(count)], check=True) + oracle = ROOT / "zig/src/families/ling/oracle/ling_forward.py" + subprocess.run([python, str(oracle), checkpoint, str(reference), "--tokens", str(count), + "--picks", str(native) + ".picks"], check=True) + result = compare(native, reference) + (out / f"summary-{count}.json").write_text(json.dumps(result, indent=2) + "\n") + print(json.dumps(result), flush=True) + if not result["top_tokens_equal"]: + raise RuntimeError("top-token mismatch; inspect the numerical receipt") + print("Ling exactness checks completed; numerical acceptance remains a separate review decision") + + +if __name__ == "__main__": + main() diff --git a/web/tensorfold_web/data/catalog.json b/web/tensorfold_web/data/catalog.json index 725dae10034..fabcd40a3fa 100644 --- a/web/tensorfold_web/data/catalog.json +++ b/web/tensorfold_web/data/catalog.json @@ -127,7 +127,6 @@ "fast" ], "backends": [ - "mlx", "cuda" ], "drafter": null, diff --git a/web/tensorfold_web/data/native-version.json b/web/tensorfold_web/data/native-version.json index fa178c09a5e..6d39c461d5b 100644 --- a/web/tensorfold_web/data/native-version.json +++ b/web/tensorfold_web/data/native-version.json @@ -1 +1 @@ -{"version":"1.3.0"} +{"version":"1.3.2"} diff --git a/web/tensorfold_web/server_engine_control.py b/web/tensorfold_web/server_engine_control.py index 639f34d27bc..68374f62f4e 100644 --- a/web/tensorfold_web/server_engine_control.py +++ b/web/tensorfold_web/server_engine_control.py @@ -10,6 +10,7 @@ from . import ( living, + machine, ) from . import settings as settings_mod from .gate import Busy @@ -55,6 +56,8 @@ def launch(model: str, entry: Any) -> dict: if why: eng.note(f"{copy} serves without learning: {why}") return result + if entry and entry.backends == ["cuda"] and machine.detect().backend != "cuda": + raise RuntimeError(f"{entry.name} is available on CUDA only") here = bool(entry and cat.native_here(entry)) result = eng.start(model, native_model=here, drafter=entry.drafter if here and entry else None) if not here: diff --git a/web/tests/test_network_startup.py b/web/tests/test_network_startup.py index 779ed1e7156..e1f68741972 100644 --- a/web/tests/test_network_startup.py +++ b/web/tests/test_network_startup.py @@ -8,7 +8,7 @@ from tensorfold_web import catalog, mock_engine, native from tensorfold_web import settings as settings_mod from tensorfold_web.engine import Engine -from tensorfold_web.mock_engine import serve +from tensorfold_web.mock_engine import State, serve from tensorfold_web.server import create_app @@ -41,6 +41,7 @@ def log_message(self, *args): pass proxy = ThreadingHTTPServer(("127.0.0.1", 0), Proxy) threading.Thread(target=proxy.serve_forever, daemon=True).start() + monkeypatch.setattr(State, "started", 0.0) # Exercise a ready stand-in regardless of test order. local = serve(port=0) # past the stand-in's three-second warm-up, whatever the suite's timing monkeypatch.setattr(mock_engine.State, "started", time.time() - 4) diff --git a/web/tests/test_qwen35b_catalog.py b/web/tests/test_qwen35b_catalog.py new file mode 100644 index 00000000000..fe5c2c0dd1a --- /dev/null +++ b/web/tests/test_qwen35b_catalog.py @@ -0,0 +1,65 @@ +import pytest +from fastapi.testclient import TestClient + +from tensorfold_web import catalog, native, server_system, settings +from tensorfold_web.engine import Engine +from tensorfold_web.engines import PythonLauncher, choose +from tensorfold_web.machine import GIB, Gpu, Machine +from tensorfold_web.server import create_app + +MODEL = "TensorFold/Qwen3.6-35B-A3B-MLX-4bit-MTP" +DENSE = "TensorFold/Qwen3.8-27B-MLX-4bit" + + +@pytest.mark.parametrize(("backend", "has_python"), [ + ("mlx", True), + ("mlx", False), + ("cuda", False), +]) +def test_qwen35b_is_cuda_only_in_the_catalog_and_start_route(tmp_path, monkeypatch, backend, has_python): + machine = Machine("macOS" if backend == "mlx" else "Linux", "test", "arm64", "test", + 128 * GIB, 120 * GIB, True, gpus=[Gpu("test", 128 * GIB)], backend=backend) + monkeypatch.setattr(settings, "config_dir", lambda: tmp_path) + monkeypatch.setattr(server_system, "detect", lambda: machine) + monkeypatch.setattr("tensorfold_web.machine.detect", lambda: machine) + monkeypatch.setattr(catalog, "installed", lambda *_: False) + monkeypatch.setattr(native, "find_binary", lambda: "/x/tensorfold") + monkeypatch.setattr(native, "refused", lambda *_: None) + monkeypatch.setattr(native, "capabilities", lambda _: { + "backends": ["metal" if backend == "mlx" else "cuda"], + "families": {"qwen3_5": ["mlx-q4g64"], "qwen3_5_moe": ["mlx-q4g64"]}, + }) + monkeypatch.setattr(PythonLauncher, "available", lambda _: has_python) + cat = catalog.Catalog() + cat.refresh_sizes_async = lambda: None + monkeypatch.setattr(cat, "size_of", lambda repo: 20 * GIB if repo == MODEL else None) + s = settings.Settings(engine_url="http://127.0.0.1:9", remote=False) + engine = Engine(s) + starts = [] + + def start(model, *, native_model, drafter): + starts.append((model, native_model, drafter)) + choose(native_model) # check the same launcher availability as Engine.start + if native_model: + engine.exit_code = 0 # end the launch observation without a child process + return {"status": "starting"} + + monkeypatch.setattr(engine, "start", start) + monkeypatch.setattr(engine, "info", dict) + client = TestClient(create_app(settings=s, engine=engine, catalog=cat)) + rows = {row["id"]: row for row in client.get("/api/catalog").json()["models"]} + response = client.post("/api/engine/start", json={"model": MODEL}) + row = rows[MODEL] + assert row["backends"] == ["cuda"] + assert row["runs_here"] is (backend == "cuda") + assert rows[DENSE]["native"] is True # another Qwen checkpoint still uses the native engine + if backend == "mlx": + assert not row.get("recommended") + assert "CUDA" in row["runs_note"] and "0.6.6" not in row["runs_note"] + assert response.status_code == 409 + assert "CUDA" in response.json()["detail"] + assert starts == [] + else: + assert row["native"] is True + assert response.status_code == 200 + assert starts == [(MODEL, True, None)] diff --git a/zig/build/cache_replay.zig b/zig/build/cache_replay.zig index 4b06f718380..17ef5fd1631 100644 --- a/zig/build/cache_replay.zig +++ b/zig/build/cache_replay.zig @@ -15,6 +15,8 @@ pub fn steps(b: *std.Build) void { b.step("test-cache-replay-host", "Replay equivalence, ownership, accounting and selector witnesses without devices").dependOn(&b.addRunArtifact(tests).step); const existing = b.addTest(.{ .root_module = cache }); b.step("test-prompt-cache-host", "The snapshot store's existing host suite without a device backend").dependOn(&b.addRunArtifact(existing).step); + const miss_tests = b.addTest(.{ .root_module = cache, .filters = &.{"miss reasons:"} }); + b.step("test-prompt-cache-miss-host", "Prompt-cache miss attribution without a device backend").dependOn(&b.addRunArtifact(miss_tests).step); const store_tests = b.addTest(.{ .root_module = cache, .filters = &.{ "prompt_cache", "prompt_radix" } }); b.step("test-cache-store-host", "Snapshot store lookup, lifetime, reservation and eviction tests without devices").dependOn(&b.addRunArtifact(store_tests).step); const agent = b.addExecutable(.{ .name = "tf-cache-agent-replay", .root_module = b.createModule(.{ .root_source_file = b.path("zig/cache_agent_replay.zig"), .target = target, .optimize = .ReleaseSafe, .link_libc = true, .imports = imports }) }); diff --git a/zig/build/cuda.zig b/zig/build/cuda.zig index a03bb3e2f1d..61d5769a106 100644 --- a/zig/build/cuda.zig +++ b/zig/build/cuda.zig @@ -127,7 +127,8 @@ pub fn targets(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.bu runner.addImport("glm_cuda", glmCuda(b, target, optimize, cuda, mods.core, mods.lanes, mods.heat, mods.api)); @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); - 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) }, .{ "idol_cuda", @import("idol_cuda.zig").targets(b, target, optimize, strip, cuda, mods.core) } }) |m| runner.addImport(m[0], m[1]); + @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]); 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 @@ -155,6 +156,7 @@ pub fn targets(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.bu contract_images.dependOn(fatbin_step); @import("cuda_contract_deepseek.zig").images(b, runner_exe, contract_images, kernels, &images, prebuilt, nvcc, version, sms, opts.cuobjdump); @import("dsv41_serve.zig").install(b, target, optimize, cuda, nvcc != null or prebuilt != null); + @import("hy4_cuda.zig").install(b, target, optimize, cuda, mods.core); const server_exe = nativeServer(b, target, optimize, cuda, mods.core, mods.lanes, mods.nemotron, mods.heat, mods.qwen35, mods.qwen_vision, mods.tokenizer, mods.living, build_options, true, strip); b.step("compile-config-server", "Compile the actual CUDA server config entry point without installing or running").dependOn(&server_exe.step); // tf-qwen35-cuda: the Qwen CUDA forward's rows for a reference to compare, and its tower on picture files @@ -340,7 +342,7 @@ pub fn hostTests(b: *std.Build, draft_ids: *std.Build.Module, build_options: *st @import("drama3_host.zig").plan(b, drama3, mods.core, native_modules.api, cuda); @import("drama3_host.zig").metal(b, mods.core, native_modules.api); const safety = b.step("test-kv-safety-host", "Actual native KV startup budget and paged constructors under allocation/completion faults"); - for ([_]*std.Build.Module{ native, mods.nemotron }) |m| safety.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = m, .filters = &.{"kv safety:"} })).step); + for ([_]*std.Build.Module{ native, mods.nemotron, mods.qwen35 }) |m| safety.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = m, .filters = &.{"kv safety:"} })).step); b.step("test-cache-capacity-host", "Startup cache capacity facts and warnings without a GPU").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = native, .filters = &.{"cache capacity:"} })).step); b.step("test-snap-fork-host", "CUDA prompt-cache rules: no fork marks unless a family sets snap_fork, its marks when it does").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = native, .filters = &.{"snap fork:"} })).step); b.step("test-snap-hooks-host", "CUDA prompt-cache hooks: a family's spare, trim and reuses reach the store").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = native, .filters = &.{"snap hooks:"} })).step); diff --git a/zig/build/cuda_kernels.zig b/zig/build/cuda_kernels.zig index baea6c92681..4ddb07b7e23 100644 --- a/zig/build/cuda_kernels.zig +++ b/zig/build/cuda_kernels.zig @@ -149,6 +149,7 @@ pub const kernels = [_]Kernel{ .{ .name = "glm_ops", .flags = &.{"-O3"} }, // ours: GLM's integer work the Python family did in torch (the DSA token lists) .{ .name = "glm_index", .flags = &.{"-O3"} }, // a prompt chunk's DSA scores and top-512 pools .{ .name = "hy4_indexpool", .src = "hy4_flash/indexpool", .flags = &.{ "-O3", "--fmad=false" } }, + .{ .name = "hy4_engram", .src = "hy4_flash/engram", .flags = &.{ "-O3", "--fmad=false" } }, .{ .name = "affine_experts", .flags = &.{ "-O3", "--fmad=false" } }, .{ .name = "hy4_index_recall", .src = "hy4_flash/index_recall", .flags = &.{ "-O3", "--fmad=false" } }, .{ .name = "hy4_attention_sink", .src = "hy4_flash/attention_sink", .flags = &.{ "-O3", "--fmad=false" } }, @@ -158,8 +159,11 @@ pub const kernels = [_]Kernel{ .{ .name = "minimax_m3", .flags = glue }, // ours: MiniMax-M3.1-Flash's glue (norms, RoPE prep, routing, DSpark, tower RoPE) .{ .name = "minimax_m3_attn", .flags = glue }, // ours: MiniMax-M3.1-Flash's indexer and block-sparse attention .{ .name = "idol", .flags = glue }, // ours: Idol's denoiser glue and its fp16 head-64 attention + .{ .name = "idol_decoder", .flags = glue }, // ours: Idol's decoders' stem, to_kv, head norms and attention .{ .name = "inkling2_attn", .src = "inkling2/attention", .flags = &.{"-O3"} }, // ours: Inkling 2's relative-bias attention .{ .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 = "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/cuda_server_host.zig b/zig/build/cuda_server_host.zig index 04848283ae5..1c977de2eb2 100644 --- a/zig/build/cuda_server_host.zig +++ b/zig/build/cuda_server_host.zig @@ -27,6 +27,9 @@ pub fn steps(b: *std.Build, host: std.Build.ResolvedTarget, cuda: *std.Build.Mod b.step("test-wait-reasons-server-host", "The ledger's wait, refusal and failure labels in /metrics and /v1/load").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = server_tests, .filters = &.{"wait reason ledger:"} })).step); // the open-connection limit, one address's share under pressure and its flags (#3048), on Linux hosts too b.step("test-connection-admission-host", "Connection limit, per-address share, trusted proxies and idle shedding").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = server_tests, .filters = &.{ "security: ", "connection CLI:" } })).step); + const flush = b.step("test-prompt-cache-flush-host", "The prompt cache flush: its hold, a cold next turn, withdrawal and who may call it"); + flush.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = native_modules.api, .filters = &.{"prompt cache flush:"} })).step); + flush.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = server_tests, .filters = &.{"prompt cache flush"} })).step); b.step("test-drama-cfg-host", "Drama CFG CLI, HTTP and voice transitions without GPU execution").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = server_tests, .filters = &.{"CFG"} })).step); b.step("test-speech-redraw-deadline-host", "Busy speech redraw expiry without counting an unsubmitted take").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = server_tests, .filters = &.{"a busy redraw stops at its latest start"} })).step); b.step("test-server-keepalive-host", "Silent engine keepalives and cancellation through the threaded server").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = server_tests, .filters = &.{"a silent engine's stream gets keepalives before its first token"} })).step); @@ -36,6 +39,7 @@ pub fn steps(b: *std.Build, host: std.Build.ResolvedTarget, cuda: *std.Build.Mod eos_policy.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = mods.tokenizer, .filters = &.{"EOS policy:"} })).step); eos_policy.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = kolibri1Module(b, host, .debug, cuda, mods.core, mods.lanes), .filters = &.{"EOS policy:"} })).step); b.step("test-serve-flags-host", "Serve flag parsing, the flat TOML reader and --config expansion, without a GPU").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = server_tests, .filters = &.{ "--compact-at:", "flat TOML:", "serve --config:" } })).step); + b.step("test-request-deadline-host", "deadline_s: the server ends a reply at its deadline with usage and ids").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = server_tests, .filters = &.{"request deadline:"} })).step); b.step("test-dory-cli-host", "Dory CUDA loop option forwarding and invalid-value refusals").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = server_tests, .filters = &.{"--device and --segments:"} })).step); b.step("test-dory-chat-host", "Dory chat template, EOS, reasoning split and qwen3_coder call on the CPU").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = server_tests, .filters = &.{"Dory chat:"} })).step); b.step("test-embeddings-protocol-host", "Embedding request and response contracts without an admitted model or GPU").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = server_tests, .filters = &.{"embeddings protocol:"} })).step); diff --git a/zig/build/drama3_metal.zig b/zig/build/drama3_metal.zig index 54d1e8d4398..9f7885f3e13 100644 --- a/zig/build/drama3_metal.zig +++ b/zig/build/drama3_metal.zig @@ -70,7 +70,9 @@ pub fn targets(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.bu .imports = &.{ .{ .name = "drama3", .module = family }, .{ .name = "drama3_metallib", .module = bytes } }, }), }); - b.step("drama3-metal-quant-check", "Build the NVFP4 Metal operator checker; does not execute GPU work").dependOn(&b.addInstallArtifact(quant_check, .{}).step); + const quant = b.step("drama3-metal-quant-check", "Build the NVFP4 Metal operator checker; does not execute GPU work"); + quant.dependOn(&b.addInstallArtifact(quant_check, .{}).step); + if (no_compiler) |fail| quant.dependOn(fail); const tool = b.createModule(.{ .root_source_file = b.path("zig/src/families/drama3/generate.zig"), .target = target, diff --git a/zig/build/flashnext_batch_host.zig b/zig/build/flashnext_batch_host.zig index 3b170855367..cbfa0bc4ce6 100644 --- a/zig/build/flashnext_batch_host.zig +++ b/zig/build/flashnext_batch_host.zig @@ -21,6 +21,11 @@ pub fn tests(b: *std.Build, all: *std.Build.Step) void { 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", .{}); + const cancel_tf = b.createModule(.{ .root_source_file = b.addWriteFiles().add("flashnext-cancel-tf.zig", "pub const lanes = @import(\"lanes\");\n"), .target = b.graph.host, .imports = &.{.{ .name = "lanes", .module = lanes }} }); + const cancelled = b.createModule(.{ .root_source_file = b.path("zig/src/native/flashnext_cancel.zig"), .target = b.graph.host, .link_libc = true, .imports = &.{.{ .name = "tensorfold", .module = cancel_tf }} }); + const cancel_run = b.addRunArtifact(b.addTest(.{ .root_module = cancelled })); + b.step("test-flashnext-cancel-host", "Single-reply cancellation retains only an actual landed prompt state").dependOn(&cancel_run.step); + all.dependOn(&cancel_run.step); const schedule_run = b.addRunArtifact(b.addTest(.{ .root_module = schedule, .filters = &.{ "flashnext prefill:", "fill aging:" } })); b.step("test-flashnext-prefill-pairs-host", "Prompt head lookahead and segment coverage without a device").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = schedule, .filters = &.{"flashnext prefill: prompt head pairs"} })).step); const schedule_step = b.step("test-flashnext-scheduling-host", "Actual Flash Next prompt steps and shared-host fairness without devices"); diff --git a/zig/build/glm_checks.zig b/zig/build/glm_checks.zig index e18cf76b9a3..5245fc68717 100644 --- a/zig/build/glm_checks.zig +++ b/zig/build/glm_checks.zig @@ -3,7 +3,7 @@ const std = @import("std"); /// tf-glm-rows-check: the products at every MLX width against float64, every row's bits in every window and launch. -pub fn targets(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, metal: *std.Build.Module, engine: *std.Build.Module, sources: *std.Build.Module) void { +pub fn targets(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, metal: *std.Build.Module, engine: *std.Build.Module, sources: *std.Build.Module, test_step: *std.Build.Step) void { const exe = b.addExecutable(.{ .name = "tf-glm-rows-check", .root_module = b.createModule(.{ .root_source_file = b.path("zig/tests/glm_rows_check.zig"), .target = target, @@ -117,6 +117,40 @@ pub fn targets(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.bu .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "tensorfold", .module = engine } }, }) }); b.step("tf-glm-mm-groups", "GLM-5.3-Flash's prompt experts and dense products in column groups against core/affine_mm.zig's, bit for bit, GPU time").dependOn(&b.addInstallArtifact(mgroups, .{}).step); + drafter(b, target, optimize, metal, engine, test_step); +} + +/// The GLM DFlash2 drafter's host test (no GPU) and its synthetic device check, each under its own step. +fn drafter(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, metal: *std.Build.Module, engine: *std.Build.Module, test_step: *std.Build.Step) void { + const imports: []const std.Build.Module.Import = &.{ .{ .name = "metal", .module = metal }, .{ .name = "tensorfold", .module = engine } }; + const host = b.addTest(.{ .root_module = b.createModule(.{ + .root_source_file = b.path("zig/tests/glm_metal_dflash_host.zig"), + .target = target, + .optimize = optimize, + .link_libc = true, + .imports = imports, + }) }); + const host_run = b.addRunArtifact(host); + b.step("test-glm-metal-dflash-host", "GLM DFlash2 drafter on Metal: config, schedule, taps and facts on the CPU").dependOn(&host_run.step); + test_step.dependOn(&host_run.step); + const synthetic = b.addExecutable(.{ .name = "tf-glm-metal-dflash-synthetic", .root_module = b.createModule(.{ + .root_source_file = b.path("zig/tests/glm_metal_dflash_synthetic.zig"), + .target = target, + .optimize = optimize, + .link_libc = true, + .imports = imports, + }) }); + b.step("tf-glm-metal-dflash-synthetic", "Build the GLM DFlash2 synthetic device check").dependOn(&b.addInstallArtifact(synthetic, .{}).step); + b.step("test-glm-metal-dflash-synthetic", "GLM DFlash2 drafter on the GPU over synthetic weights: taps, frames, drafts").dependOn(&b.addRunArtifact(synthetic).step); + const speed = b.addExecutable(.{ .name = "tf-glm-dflash-speed", .root_module = b.createModule(.{ + .root_source_file = b.path("zig/tests/glm_metal_dflash_speed.zig"), + .target = target, + .optimize = optimize, + .link_libc = true, + .imports = imports, + }) }); + const about = "GLM DFlash2 drafter passes at incoai's shapes on synthetic weights: ms a pass and a stage, bf16 and 4-bit"; + b.step("tf-glm-dflash-speed", about).dependOn(&b.addInstallArtifact(speed, .{}).step); } /// tf-glm-sample-check and test-glm-sampling: the real GLM sampler against its host reference, no checkpoint. diff --git a/zig/build/glm_expiry.zig b/zig/build/glm_expiry.zig index 622dd0f2bd3..25e71ec4643 100644 --- a/zig/build/glm_expiry.zig +++ b/zig/build/glm_expiry.zig @@ -45,27 +45,44 @@ pub fn steps(b: *std.Build, test_step: *std.Build.Step, lanes: *std.Build.Module .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "kernel_sources", .module = sources }, .{ .name = "tensorfold", .module = api } }, }) }); b.step("check-glm-gather-gpu-host", "Compile the GPU gather equality gate without compiling or running shaders").dependOn(&gpu_check.step); - const schedule = b.addTest(.{ .filters = &.{ "glm prefill:", "fill aging:" }, .root_module = b.createModule(.{ - .root_source_file = b.path("zig/src/glm_schedule_tests.zig"), - .target = b.graph.host, - .optimize = .debug, - .link_libc = true, - .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "lanes", .module = lanes }, .{ .name = "fabric", .module = fabric }, .{ .name = "kernel_sources", .module = sources } }, - }) }); + const core = sharedHostCore(b, metal); + const sched_mod = hostMod(b, "zig/src/glm_schedule_tests.zig", metal, lanes, fabric, sources, core); + const schedule = b.addTest(.{ .filters = &.{ "glm prefill:", "fill aging:" }, .root_module = sched_mod }); if (b.graph.host.result.os.tag == .macos) schedule.root_module.linkSystemLibrary("objc", .{}); const schedule_run = b.addRunArtifact(schedule); b.step("test-glm-scheduling-host", "Actual GLM prefill chunks and lane-host decode fairness using a fake engine").dependOn(&schedule_run.step); b.step("test-glm-prefill-widths-host", "Actual GLM pass widths, restore cuts and shared lane stats without devices").dependOn(&schedule_run.step); if (b.graph.host.result.os.tag == .macos) { - const compile = b.addObject(.{ .name = "glm-restore-host", .root_module = b.createModule(.{ - .root_source_file = b.path("zig/src/glm_restore_compile.zig"), - .target = b.graph.host, - .optimize = .debug, - .link_libc = true, - .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "lanes", .module = lanes }, .{ .name = "fabric", .module = fabric } }, - }) }); + const comp_mod = hostMod(b, "zig/src/glm_restore_compile.zig", metal, lanes, fabric, sources, core); + const compile = b.addObject(.{ .name = "glm-restore-host", .root_module = comp_mod }); b.step("check-glm-restore-host", "Compile the real GLM Metal prefill and restore bodies without shaders or execution").dependOn(&compile.step); } test_step.dependOn(&run.step); b.step("test-glm-expiry", "CPU GLM expiry, borrowed snapshots and peer command ordering").dependOn(&run.step); } + +const HostCore = struct { bf16_topk: *std.Build.Module, bf16_topk_gpu: *std.Build.Module, draft_ops: *std.Build.Module }; + +fn sharedHostCore(b: *std.Build, metal: *std.Build.Module) HostCore { + const host = b.graph.host; + const topk_src = b.createModule(.{ .root_source_file = b.path("zig/bf16_topk_sources.zig") }); + const draft_src = b.createModule(.{ .root_source_file = b.path("zig/draft_ops_sources.zig") }); + const bf16_topk = b.createModule(.{ .root_source_file = b.path("zig/src/core/bf16_topk.zig"), .target = host, .optimize = .debug }); + return .{ + .bf16_topk = bf16_topk, + .bf16_topk_gpu = b.createModule(.{ .root_source_file = b.path("zig/src/core/bf16_topk_gpu.zig"), .target = host, .optimize = .debug, .link_libc = true, .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "bf16_topk", .module = bf16_topk }, .{ .name = "bf16_topk_sources", .module = topk_src } } }), + .draft_ops = b.createModule(.{ .root_source_file = b.path("zig/src/core/draft_ops.zig"), .target = host, .optimize = .debug, .link_libc = true, .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "draft_ops_sources", .module = draft_src } } }), + }; +} + +fn hostMod(b: *std.Build, path: []const u8, metal: *std.Build.Module, lanes: *std.Build.Module, fabric: *std.Build.Module, sources: *std.Build.Module, core: HostCore) *std.Build.Module { + const mod = b.createModule(.{ + .root_source_file = b.path(path), + .target = b.graph.host, + .optimize = .debug, + .link_libc = true, + .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "lanes", .module = lanes }, .{ .name = "fabric", .module = fabric }, .{ .name = "kernel_sources", .module = sources }, .{ .name = "bf16_topk", .module = core.bf16_topk }, .{ .name = "bf16_topk_gpu", .module = core.bf16_topk_gpu }, .{ .name = "draft_ops", .module = core.draft_ops } }, + }); + mod.addImport("core", mod); + return mod; +} diff --git a/zig/build/glm_family_host.zig b/zig/build/glm_family_host.zig index e20d136ad4b..747675eb46b 100644 --- a/zig/build/glm_family_host.zig +++ b/zig/build/glm_family_host.zig @@ -39,6 +39,7 @@ pub fn steps(b: *std.Build, cuda: *std.Build.Module, glm: *std.Build.Module, mod b.step("test-glm-thin-weights-host", "TF_GLM_LAYERS's admission bytes by tensor from synthetic shard headers").dependOn(&thin_run.step); step.dependOn(&thin_run.step); b.step("test-glm-tp3-host", "Uneven KDA head shares through actual projection and load planning, without devices").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = glm, .filters = &.{"GLM TP3:"} })).step); + b.step("test-glm-exl3-host", "GLM EXL3 admission, mixed-width expert loading and scratch sizing, without devices").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = glm, .filters = &.{"GLM EXL3:"} })).step); // TF_GLM_INDEX_CUDA: the launch rules, and (its own slower step) glm_index_*.cuh as host C++ against plain models const index_run = b.addRunArtifact(b.addTest(.{ .root_module = glm, .filters = &.{"GLM index:"} })); b.step("test-glm-index-host", "GLM's prompt indexer launch rules without devices").dependOn(&index_run.step); diff --git a/zig/build/hip.zig b/zig/build/hip.zig index fe6e8172a29..3629da26fc3 100644 --- a/zig/build/hip.zig +++ b/zig/build/hip.zig @@ -502,15 +502,14 @@ const groups = [_]Source{ }; /// What the group sources include, so an edit to one rebuilds them. const headers = [_][]const u8{ - "attention/attention_fa.hip", "attention/prefill.hpp", "decode/pages.hpp", "decode/plan.hpp", "ops/attention.hpp", - "ops/common.hpp", "ops/draw.hpp", "ops/tp.hpp", "ops/elementwise.hpp", "ops/linear.hpp", - "ops/moe.hpp", "ops/norms.hpp", "ops/rope.hpp", "common/arch.hpp", "common/dot2.hpp", - "common/vec.hpp", "common/wmma.hpp", "quant/act.hpp", "quant/mlx.hpp", "quant/mlx_decoder.hpp", - "quant/mlx_pieces.hpp", "quant/mlx_tiles.hpp", "tiles/dot2.hpp", "tiles/epilogue.hpp", "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", + "attention/attention_fa.hip", "attention/prefill.hpp", "decode/pages.hpp", "decode/plan.hpp", "ops/attention.hpp", "ops/common.hpp", + "ops/draw.hpp", "ops/tp.hpp", "ops/elementwise.hpp", "ops/linear.hpp", "ops/moe.hpp", "ops/norms.hpp", + "ops/rope.hpp", "common/arch.hpp", "common/dot2.hpp", "common/vec.hpp", "common/wmma.hpp", "quant/act.hpp", + "quant/mlx.hpp", "quant/mlx_decoder.hpp", "quant/mlx_pieces.hpp", "quant/mlx_tiles.hpp", "tiles/dot2.hpp", "tiles/epilogue.hpp", + "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", }; /// 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/host_ci.zig b/zig/build/host_ci.zig index 059bbf7eb0e..8d4f042af96 100644 --- a/zig/build/host_ci.zig +++ b/zig/build/host_ci.zig @@ -165,6 +165,7 @@ const linux_host = [_][]const u8{ "test-flashnext-nonfinite-host", "test-flashnext-precise-host", "test-flashnext-prefill-pairs-host", + "test-flashnext-cancel-host", "test-flashnext-proposal-host", "test-flashnext-proposal-pack-host", "test-flashnext-rotary-bound-host", @@ -285,13 +286,17 @@ const macos_adapters = [_][]const u8{ "test-gguf-linux-compile", "test-h3-modulation-bf16", "test-h3-read-ahead", + "test-lfm3-metal-steps-host", + "test-lfm2-moe-metal-steps-host", "test-masked-values-host", "test-metal-counters-host", "test-minimax-info-host", + "test-minimax-m3-metal-steps-host", "test-qwen-dense-geometry-host", "test-qwen-dense-route-host", "test-qwen27-draft-tree-host", "test-qwen27-facts-host", + "test-qwen35-metal-steps-host", "test-recurrent-forks", "test-shared-head-cost-metal-host", "test-slide-metal-host", diff --git a/zig/build/hy4_cuda.zig b/zig/build/hy4_cuda.zig new file mode 100644 index 00000000000..0587c98277e --- /dev/null +++ b/zig/build/hy4_cuda.zig @@ -0,0 +1,19 @@ +//! Hy4-flash CUDA tools: the greedy text generator for EXL3 routed-expert checkpoints. +const std = @import("std"); + +pub fn install(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, cuda: *std.Build.Module, core: *std.Build.Module) void { + const root = b.createModule(.{ + .root_source_file = b.path("zig/src/families/hy4_flash/cuda_generate.zig"), + .target = target, + .optimize = optimize, + .link_libc = true, + .imports = &.{ .{ .name = "cuda", .module = cuda }, .{ .name = "core", .module = core } }, + }); + root.addImport("engram_hash_core", b.createModule(.{ + .root_source_file = b.path("zig/src/families/deepseek_v41/engram_hash.zig"), + .target = target, + .optimize = optimize, + })); + const exe = b.addExecutable(.{ .name = "tf-hy4-cuda-generate", .root_module = root }); + b.step("hy4-cuda-generate", "Build the Hy4-flash CUDA greedy generator for EXL3 checkpoints").dependOn(&b.addInstallArtifact(exe, .{}).step); +} diff --git a/zig/build/idol_cuda.zig b/zig/build/idol_cuda.zig index 5457afc86b6..a0f541b8eea 100644 --- a/zig/build/idol_cuda.zig +++ b/zig/build/idol_cuda.zig @@ -1,4 +1,4 @@ -//! Idol's CUDA denoiser in the build: its kernels for tf-cuda-test's contract, tf-idol on CUDA, its host tests. +//! Idol on CUDA in the build: its kernels for tf-cuda-test's contract, tf-idol and tf-idol-decode, its host tests. const std = @import("std"); /// The family's module over the runtime and the core. @@ -6,27 +6,44 @@ pub fn module(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.bui return b.createModule(.{ .root_source_file = b.path("zig/src/families/idol/cuda.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{ .{ .name = "cuda", .module = cuda }, .{ .name = "core", .module = core } } }); } -/// The launchers alone (idol.cu's kernels), as tf-cuda-test's contract imports them. +/// The launchers alone (idol.cu's kernels, or with `file` idol_decoder.cu's), as tf-cuda-test's contract imports them. fn launchers(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, cuda: *std.Build.Module) *std.Build.Module { - return b.createModule(.{ .root_source_file = b.path("zig/src/families/idol/cuda_kernels.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{.{ .name = "cuda", .module = cuda }} }); + return launchersOf(b, target, optimize, cuda, "cuda_kernels.zig"); } -/// tf-idol, the case driver on the first GPU; returns the launchers for tf-cuda-test's `runner` (idol-contract). -pub fn targets(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, strip: ?bool, cuda: *std.Build.Module, core: *std.Build.Module) *std.Build.Module { - const tool = b.createModule(.{ .root_source_file = b.path("zig/tests/idol_cuda.zig"), .target = target, .optimize = optimize, .link_libc = true, .strip = strip, .imports = &.{ .{ .name = "cuda", .module = cuda }, .{ .name = "core", .module = core }, .{ .name = "idol", .module = module(b, target, optimize, cuda, core) } } }); - const exe = b.addExecutable(.{ .name = "tf-idol", .root_module = tool }); - b.installArtifact(exe); - b.step("idol-cuda", "Build tf-idol: Idol's denoiser on a reference case on CUDA").dependOn(&b.addInstallArtifact(exe, .{}).step); - return launchers(b, target, optimize, cuda); +fn launchersOf(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, cuda: *std.Build.Module, file: []const u8) *std.Build.Module { + return b.createModule(.{ .root_source_file = b.path(b.fmt("zig/src/families/idol/{s}", .{file})), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{.{ .name = "cuda", .module = cuda }} }); +} + +/// The launchers in tf-cuda-test's `runner` (idol-contract, idol-decoder-contract), and tf-idol and tf-idol-decode. +pub fn targets(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, strip: ?bool, cuda: *std.Build.Module, core: *std.Build.Module, runner: *std.Build.Module) void { + runner.addImport("idol_cuda", launchers(b, target, optimize, cuda)); + runner.addImport("idol_decoder_cuda", launchersOf(b, target, optimize, cuda, "cuda_decoder_kernels.zig")); + const family = module(b, target, optimize, cuda, core); + const tools = [_]struct { []const u8, []const u8, []const u8, []const u8 }{ + .{ "tf-idol", "zig/tests/idol_cuda.zig", "idol-cuda", "Build tf-idol: Idol's denoiser on a reference case on CUDA" }, + .{ "tf-idol-decode", "zig/tests/idol_decode_cuda.zig", "idol-decode-cuda", "Build tf-idol-decode: Idol's decoders on a reference case on CUDA" }, + }; + for (tools) |t| { + const tool = b.createModule(.{ .root_source_file = b.path(t[1]), .target = target, .optimize = optimize, .link_libc = true, .strip = strip, .imports = &.{ .{ .name = "cuda", .module = cuda }, .{ .name = "core", .module = core }, .{ .name = "idol", .module = family } } }); + const exe = b.addExecutable(.{ .name = t[0], .root_module = tool }); + b.installArtifact(exe); + b.step(t[2], t[3]).dependOn(&b.addInstallArtifact(exe, .{}).step); + } } /// The family's host tests (config, schedule, scratch, admission, launch geometry, contract ranges) in `all`. pub fn hostTests(b: *std.Build, cuda: *std.Build.Module, core: *std.Build.Module, all: *std.Build.Step) void { const host = b.graph.host; const run = b.addRunArtifact(b.addTest(.{ .root_module = module(b, host, .debug, cuda, core) })); - const refs = b.createModule(.{ .root_source_file = b.path("zig/tests/cuda/contract_idol_host.zig"), .target = host, .optimize = .debug, .link_libc = true, .imports = &.{ .{ .name = "cuda", .module = cuda }, .{ .name = "core", .module = core }, .{ .name = "idol_cuda", .module = launchers(b, host, .debug, cuda) } } }); + const refs = b.createModule(.{ .root_source_file = b.path("zig/tests/cuda/contract_idol_host.zig"), .target = host, .optimize = .debug, .link_libc = true, .imports = &.{ + .{ .name = "cuda", .module = cuda }, + .{ .name = "core", .module = core }, + .{ .name = "idol_cuda", .module = launchers(b, host, .debug, cuda) }, + .{ .name = "idol_decoder_cuda", .module = launchersOf(b, host, .debug, cuda, "cuda_decoder_kernels.zig") }, + } }); const ref_run = b.addRunArtifact(b.addTest(.{ .root_module = refs })); - const step = b.step("test-idol-cuda-host", "Idol's CUDA denoiser host tests and contract references (no GPU work)"); + const step = b.step("test-idol-cuda-host", "Idol's CUDA denoiser and decoders' host tests and contract references (no GPU work)"); for ([_]*std.Build.Step{ &run.step, &ref_run.step }) |s| { step.dependOn(s); all.dependOn(s); diff --git a/zig/build/kernel_contract.zig b/zig/build/kernel_contract.zig index 44f766986d4..24a89514712 100644 --- a/zig/build/kernel_contract.zig +++ b/zig/build/kernel_contract.zig @@ -131,6 +131,7 @@ pub fn hostTests(b: *std.Build, family: *std.Build.Step) void { pub fn metal(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, metal_mod: *std.Build.Module, engine: *std.Build.Module, sources: *std.Build.Module, kimi_metallib: *std.Build.Module) void { @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 exe = b.addExecutable(.{ .name = "tf-kernel-contract", .root_module = b.createModule(.{ .root_source_file = b.path("zig/tests/contract/metal_main.zig"), .target = target, diff --git a/zig/build/ling_forward.zig b/zig/build/ling_forward.zig new file mode 100644 index 00000000000..4851d0804c4 --- /dev/null +++ b/zig/build/ling_forward.zig @@ -0,0 +1,79 @@ +//! Local bf16 Ling forward diagnostics over existing registered Metal kernels. +const std = @import("std"); +pub fn steps(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, metal_mod: *std.Build.Module, sources: *std.Build.Module, kimi_metallib: *std.Build.Module) void { + const ling_ck = b.createModule(.{ + .root_source_file = b.path("zig/src/families/ling/checkpoint.zig"), + .target = target, + .imports = &.{ + .{ .name = "metal", .module = metal_mod }, + .{ .name = "safetensors", .module = b.createModule(.{ .root_source_file = b.path("zig/src/core/safetensors.zig"), .target = target }) }, + }, + }); + const ling_kernels = b.createModule(.{ .root_source_file = b.path("zig/src/families/kimi_k3/kernels.zig"), .target = target, .imports = &.{.{ .name = "metal", .module = metal_mod }} }); + const ling_rows = b.createModule(.{ .root_source_file = b.path("zig/src/families/ling/metal_rows.zig"), .target = target, .imports = &.{ + .{ .name = "metal", .module = metal_mod }, + .{ .name = "kernel_sources", .module = sources }, + .{ .name = "ling_checkpoint", .module = ling_ck }, + .{ .name = "kimi_kernels", .module = ling_kernels }, + .{ .name = "kimi_metallib", .module = kimi_metallib }, + } }); + const ling_kda = b.createModule(.{ .root_source_file = b.path("zig/src/families/ling/metal_kda.zig"), .target = target, .imports = &.{ + .{ .name = "metal", .module = metal_mod }, + .{ .name = "ling_checkpoint", .module = ling_ck }, + .{ .name = "kimi_kernels", .module = ling_kernels }, + .{ .name = "ling_rows", .module = ling_rows }, + } }); + const ling_sources = b.createModule(.{ .root_source_file = b.path("zig/kernels/metal/ling/sources.zig") }); + const ling_mla = b.createModule(.{ .root_source_file = b.path("zig/src/families/ling/metal_mla.zig"), .target = target, .imports = &.{ + .{ .name = "metal", .module = metal_mod }, .{ .name = "ling_checkpoint", .module = ling_ck }, + .{ .name = "kimi_kernels", .module = ling_kernels }, .{ .name = "ling_rows", .module = ling_rows }, + .{ .name = "ling_sources", .module = ling_sources }, + } }); + const ling_moe = b.createModule(.{ .root_source_file = b.path("zig/src/families/ling/metal_moe.zig"), .target = target, .imports = &.{ + .{ .name = "metal", .module = metal_mod }, .{ .name = "ling_checkpoint", .module = ling_ck }, + .{ .name = "kimi_kernels", .module = ling_kernels }, .{ .name = "ling_rows", .module = ling_rows }, + .{ .name = "ling_sources", .module = ling_sources }, + } }); + const ling_forward = b.createModule(.{ .root_source_file = b.path("zig/src/families/ling/metal_forward.zig"), .target = target, .imports = &.{ + .{ .name = "metal", .module = metal_mod }, .{ .name = "ling_checkpoint", .module = ling_ck }, + .{ .name = "ling_rows", .module = ling_rows }, .{ .name = "ling_kda", .module = ling_kda }, + .{ .name = "ling_mla", .module = ling_mla }, .{ .name = "ling_moe", .module = ling_moe }, + } }); + const ling_forward_tool = b.addExecutable(.{ .name = "ling-forward", .root_module = b.createModule(.{ + .root_source_file = b.path("zig/tests/ling_forward.zig"), + .target = target, + .optimize = optimize, + .link_libc = true, + .imports = &.{ .{ .name = "metal", .module = metal_mod }, .{ .name = "ling_checkpoint", .module = ling_ck }, .{ .name = "ling_rows", .module = ling_rows }, .{ .name = "ling_forward", .module = ling_forward }, .{ .name = "ling_mla", .module = ling_mla } }, + }) }); + b.step("tf-ling-forward", "Build the native Ling bf16 full-forward diagnostic").dependOn(&b.addInstallArtifact(ling_forward_tool, .{}).step); + const python = b.graph.environ_map.get("TF_LING_PYTHON") orelse "python3"; + const full_check = b.addSystemCommand(&.{ python, "tools/zig/ling_forward_check.py", "--binary" }); + full_check.addArtifactArg(ling_forward_tool); + b.step("test-ling-forward", "Optional real-checkpoint Ling exactness and FP64 comparison receipts").dependOn(&full_check.step); + const ling_projection = b.addExecutable(.{ .name = "ling-projection", .root_module = b.createModule(.{ + .root_source_file = b.path("zig/tests/ling_projection.zig"), + .target = target, + .optimize = optimize, + .link_libc = true, + .imports = &.{ + .{ .name = "metal", .module = metal_mod }, + .{ .name = "ling_checkpoint", .module = ling_ck }, + .{ .name = "kimi_metallib", .module = kimi_metallib }, + .{ .name = "kimi_kernels", .module = ling_kernels }, + .{ .name = "ling_rows", .module = ling_rows }, + .{ .name = "ling_kda", .module = ling_kda }, + .{ .name = "ling_mla", .module = ling_mla }, + .{ .name = "ling_moe", .module = ling_moe }, + }, + }) }); + b.step("tf-ling-projection", "Build Ling's real bf16 projection diagnostic").dependOn(&b.addInstallArtifact(ling_projection, .{}).step); + const ling_checkpoint = b.addExecutable(.{ .name = "ling-checkpoint", .root_module = b.createModule(.{ + .root_source_file = b.path("zig/tests/ling_checkpoint.zig"), + .target = target, + .optimize = optimize, + .link_libc = true, + .imports = &.{ .{ .name = "metal", .module = metal_mod }, .{ .name = "ling_checkpoint", .module = ling_ck } }, + }) }); + b.step("tf-ling-checkpoint", "Build the native bf16 Ling checkpoint validator").dependOn(&b.addInstallArtifact(ling_checkpoint, .{}).step); +} diff --git a/zig/build/metal_image_programs.zig b/zig/build/metal_image_programs.zig index f03f6c9364f..3377fd4ea71 100644 --- a/zig/build/metal_image_programs.zig +++ b/zig/build/metal_image_programs.zig @@ -16,4 +16,5 @@ pub const rows = [_]Program{ .{ .name = "tf-uocr-vision", .path = "zig/tests/uocr/vision.zig", .about = "Unlimited-OCR-2's image encoder on a reference dump's pixels: SAM gated against float32, CLIP and the projector reported" }, .{ .name = "tf-uocr-blocks", .path = "zig/tests/uocr/blocks.zig", .about = "Unlimited-OCR-2's image encoder step by step: each SAM block, the neck, CLIP's front, each CLIP layer and the projector alone against float32" }, .{ .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" }, }; diff --git a/zig/build/metal_server.zig b/zig/build/metal_server.zig new file mode 100644 index 00000000000..a7ecdee845e --- /dev/null +++ b/zig/build/metal_server.zig @@ -0,0 +1,122 @@ +//! tensorfold-native over the Metal engines: the server executable, its step and its host tests. +const std = @import("std"); +const server_build = @import("server.zig"); +const exlr8_build = @import("exlr8.zig"); +const golden_build = @import("golden.zig"); +const mlxMetalStd = @import("metal_targets.zig").mlxMetalStd; + +pub fn nativeServer(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, metal: *std.Build.Module, engine: *std.Build.Module, living: *std.Build.Module, api: *std.Build.Module, engines: *std.Build.Module, build_options: *std.Build.Step.Options, test_step: ?*std.Build.Step, no_compiler: ?*std.Build.Step) *std.Build.Step.Compile { + // the HTTP side keeps its safety checks; the engine below it runs at `optimize` + const tokenizer = engines.import_table.get("tokenizer") orelse b.createModule(.{ .root_source_file = b.path("zig/src/core/tokenizer/tokenizer.zig"), .target = target, .optimize = .ReleaseSafe, .link_libc = true }); + const template = b.createModule(.{ .root_source_file = b.path("zig/src/core/template/template.zig"), .target = target, .optimize = .ReleaseSafe, .link_libc = true }); + const exe = b.addExecutable(.{ .name = "tensorfold-native", .root_module = b.createModule(.{ + .root_source_file = b.path("zig/src/server/main.zig"), + .target = target, + .optimize = .ReleaseSafe, + .link_libc = true, + .imports = &.{ .{ .name = "core", .module = engine }, .{ .name = "engine_api", .module = api }, .{ .name = "tokenizer", .module = tokenizer }, .{ .name = "template", .module = template }, .{ .name = "native_engines", .module = engines }, .{ .name = "living", .module = living }, .{ .name = "checkpoint_cli", .module = b.createModule(.{ .root_source_file = b.path("zig/src/cli/cli.zig"), .target = target, .optimize = .ReleaseSafe, .link_libc = true, .imports = &.{ .{ .name = "native_engines", .module = engines }, exlr8_build.cliImport(b, target, .ReleaseSafe, engine), .{ .name = "core", .module = engine } } }) } }, + }) }); + exe.root_module.addOptions("build_options", build_options); + _ = server_build.addTo(b, exe.root_module, target, .ReleaseSafe); + if (test_step == null) { + exe.root_module.strip = true; + return exe; + } + const install = b.addInstallArtifact(exe, .{ .dest_dir = .{ .override = .{ .custom = "native/bin" } } }); + const native = b.step("native", "tensorfold-native with the Metal engines into zig-out/native/bin (bundles: -Dcpu=apple_m1)"); + native.dependOn(&install.step); + if (no_compiler) |fail| native.dependOn(fail); + // Link libSystem's memcpy to avoid compiler-rt's weak replacement. + const libc_mem = b.addSystemCommand(&.{ "sh", "-c", "nm -m \"$0\" | grep -q 'external _memcpy (from libSystem)' || { echo 'tensorfold-native links its own memcpy: find the typed std.json int parse or 128-bit float conversion that pulled in compiler-rt'; exit 1; }" }); + libc_mem.addArtifactArg(exe); + test_step.?.dependOn(&libc_mem.step); + // core/root.zig, as cuda.zig gives the server tests: the engine's tensorfold.zig shares files with qwen_draw + const core = b.createModule(.{ .root_source_file = b.path("zig/src/core/root.zig"), .target = target, .optimize = .Debug, .link_libc = true, .imports = &.{.{ .name = "tokenizer", .module = tokenizer }} }); + const server_tests = b.createModule(.{ + .root_source_file = b.path("zig/src/server/root.zig"), + .target = target, + .optimize = .Debug, // the server's unit tests run with safety checks, as zig_test.sh builds them + .link_libc = true, + .imports = &.{ .{ .name = "engine_api", .module = api }, .{ .name = "tokenizer", .module = tokenizer }, .{ .name = "template", .module = template }, .{ .name = "living", .module = living }, .{ .name = "core", .module = core } }, + }); + // the required-tools tests' 27B mask policy and lane fake, on the engine API's own lanes module + if (api.import_table.get("lanes")) |lanes_mod| { + const q27 = @import("qwen27_required.zig").modules(b, lanes_mod); + server_tests.addImport("qwen27_mask_fake", q27.fake); + server_tests.addImport("qwen27_masks", q27.masks); + } + const server_json = server_build.addTo(b, server_tests, target, .Debug); + server_build.testImports(b, server_tests, target, .Debug); + test_step.?.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = server_tests })).step); + // the PDF render worker as tensorfold-native spawns it; POSIX only, as Windows renders in process + if (target.result.os.tag != .windows) { + const worker_exe = b.addOptions(); + worker_exe.addOptionPath("path", exe.getEmittedBin()); + const pdf_worker = b.createModule(.{ .root_source_file = b.path("zig/src/server/pdf_worker_test.zig"), .target = target, .optimize = .Debug, .link_libc = true }); + for (server_tests.import_table.keys(), server_tests.import_table.values()) |name, module| pdf_worker.addImport(name, module); + pdf_worker.addOptions("pdf_worker_exe", worker_exe); + const pdf_worker_run = b.addRunArtifact(b.addTest(.{ .root_module = pdf_worker, .filters = &.{"tensorfold-native PDF render worker:"} })); + test_step.?.dependOn(&pdf_worker_run.step); + b.step("test-pdf-worker", "The PDF render worker spawned from tensorfold-native, rendering where libpdfium is found").dependOn(&pdf_worker_run.step); + } + const kimi_text = b.addExecutable(.{ .name = "tf-k3-text-golden", .root_module = b.createModule(.{ + .root_source_file = b.path("zig/src/server/kimi_golden_main.zig"), + .target = target, + .optimize = .ReleaseSafe, + .link_libc = true, + .imports = &.{ .{ .name = "json", .module = server_json }, .{ .name = "tokenizer", .module = tokenizer } }, + }) }); + b.step("tf-k3-text-golden", "Kimi release prompt token ids against an explicitly supplied local tokenizer").dependOn(&b.addInstallArtifact(kimi_text, .{}).step); + const kimi_host = b.step("test-kimi-serving-host", "Kimi native text, HTTP and resident budget refusals on the host"); + for ([_]*std.Build.Module{ server_tests, engines }) |module| + kimi_host.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = module, .filters = &.{"Kimi"} })).step); + + test_step.?.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = server_json })).step); + @import("cortheon_fuzz.zig").add(b, target, api, tokenizer, template, core); + @import("stream_scan_bench.zig").add(b, target, api, tokenizer, template, core); + // the parse half's tests, as their own test binary (zig/src/server/tool_parse_test.zig) + const tool_parse_tests = b.addTest(.{ .root_module = b.createModule(.{ .root_source_file = b.path("zig/src/server/tool_parse_test.zig"), .target = target, .optimize = .Debug, .link_libc = true, .imports = &.{ .{ .name = "engine_api", .module = api }, .{ .name = "tokenizer", .module = tokenizer }, .{ .name = "template", .module = template } } }) }); + _ = server_build.addTo(b, tool_parse_tests.root_module, target, .Debug); + server_build.testImports(b, tool_parse_tests.root_module, target, .Debug); + test_step.?.dependOn(&b.addRunArtifact(tool_parse_tests).step); + // the chat-template engine's tests (zig/src/core/template/tests.zig), which no other test binary reaches + test_step.?.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = b.createModule(.{ .root_source_file = b.path("zig/src/core/template/tests.zig"), .target = target, .optimize = .Debug, .link_libc = true }) })).step); + // the engine seam's own tests (lane_host.zig), as zig/tests/server/zig_test.sh runs them + test_step.?.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = api })).step); + // the frozen server parity goldens, checked by Zig driving fake_serve + 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-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-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" }); + embed_air.addFileArg(b.path("zig/kernels/metal/qwen3/heads.metal")); + embed_air.addArg("-o"); + _ = embed_air.addOutputFileArg("qwen3-heads.air"); + embed_host.dependOn(&embed_air.step); + embed_host.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = engine, .filters = &.{"embedding"} })).step); + embed_host.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = engines, .filters = &.{"Qwen3 Metal"} })).step); + 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 reuse = b.addExecutable(.{ .name = "tf-flashnext-reuse", .root_module = b.createModule(.{ + .root_source_file = b.path("zig/tests/flashnext_reuse.zig"), + .target = target, + .optimize = optimize, + .link_libc = true, + .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "tensorfold", .module = engine }, .{ .name = "engine_api", .module = api } }, + }) }); + b.installArtifact(reuse); + b.step("tf-flashnext-reuse", "Flash Next prompt reuse against fresh prompt passes: replies at every depth and kept states' bytes").dependOn(&b.addInstallArtifact(reuse, .{}).step); + const batch = b.addExecutable(.{ .name = "tf-flashnext-batch", .root_module = b.createModule(.{ + .root_source_file = b.path("zig/tests/flashnext_batch.zig"), + .target = target, + .optimize = optimize, + .link_libc = true, + .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "tensorfold", .module = engine }, .{ .name = "kernel_sources", .module = engine.import_table.get("kernel_sources").? } }, + }) }); + b.step("tf-flashnext-batch", "Flash Next shared rounds against fresh legacy replies with prompt admission and cancellation").dependOn(&b.addInstallArtifact(batch, .{}).step); + return exe; +} diff --git a/zig/build/metal_targets.zig b/zig/build/metal_targets.zig index 2172e8a2d92..3a567d6022b 100644 --- a/zig/build/metal_targets.zig +++ b/zig/build/metal_targets.zig @@ -9,8 +9,7 @@ const flashnext_checks = @import("flashnext_checks.zig"); const counters_build = @import("metal_counters.zig"); const exl3_build = @import("exl3.zig"); const exlr8_build = @import("exlr8.zig"); -const server_build = @import("server.zig"); -const golden_build = @import("golden.zig"); +const metal_server = @import("metal_server.zig"); const contract_build = @import("kernel_contract.zig"); const image_programs = @import("metal_image_programs.zig"); const metal_lists = @import("metal_source_lists.zig"); @@ -74,122 +73,6 @@ pub fn embedded(b: *std.Build, lib: std.Build.LazyPath, file: []const u8) *std.B return b.createModule(.{ .root_source_file = src }); } -pub fn nativeServer(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, metal: *std.Build.Module, engine: *std.Build.Module, living: *std.Build.Module, api: *std.Build.Module, engines: *std.Build.Module, build_options: *std.Build.Step.Options, test_step: ?*std.Build.Step, no_compiler: ?*std.Build.Step) *std.Build.Step.Compile { - // the HTTP side keeps its safety checks; the engine below it runs at `optimize` - const tokenizer = engines.import_table.get("tokenizer") orelse b.createModule(.{ .root_source_file = b.path("zig/src/core/tokenizer/tokenizer.zig"), .target = target, .optimize = .ReleaseSafe, .link_libc = true }); - const template = b.createModule(.{ .root_source_file = b.path("zig/src/core/template/template.zig"), .target = target, .optimize = .ReleaseSafe, .link_libc = true }); - const exe = b.addExecutable(.{ .name = "tensorfold-native", .root_module = b.createModule(.{ - .root_source_file = b.path("zig/src/server/main.zig"), - .target = target, - .optimize = .ReleaseSafe, - .link_libc = true, - .imports = &.{ .{ .name = "core", .module = engine }, .{ .name = "engine_api", .module = api }, .{ .name = "tokenizer", .module = tokenizer }, .{ .name = "template", .module = template }, .{ .name = "native_engines", .module = engines }, .{ .name = "living", .module = living }, .{ .name = "checkpoint_cli", .module = b.createModule(.{ .root_source_file = b.path("zig/src/cli/cli.zig"), .target = target, .optimize = .ReleaseSafe, .link_libc = true, .imports = &.{ .{ .name = "native_engines", .module = engines }, exlr8_build.cliImport(b, target, .ReleaseSafe, engine), .{ .name = "core", .module = engine } } }) } }, - }) }); - exe.root_module.addOptions("build_options", build_options); - _ = server_build.addTo(b, exe.root_module, target, .ReleaseSafe); - if (test_step == null) { - exe.root_module.strip = true; - return exe; - } - const install = b.addInstallArtifact(exe, .{ .dest_dir = .{ .override = .{ .custom = "native/bin" } } }); - const native = b.step("native", "tensorfold-native with the Metal engines into zig-out/native/bin (bundles: -Dcpu=apple_m1)"); - native.dependOn(&install.step); - if (no_compiler) |fail| native.dependOn(fail); - // Link libSystem's memcpy to avoid compiler-rt's weak replacement. - const libc_mem = b.addSystemCommand(&.{ "sh", "-c", "nm -m \"$0\" | grep -q 'external _memcpy (from libSystem)' || { echo 'tensorfold-native links its own memcpy: find the typed std.json int parse or 128-bit float conversion that pulled in compiler-rt'; exit 1; }" }); - libc_mem.addArtifactArg(exe); - test_step.?.dependOn(&libc_mem.step); - // core/root.zig, as cuda.zig gives the server tests: the engine's tensorfold.zig shares files with qwen_draw - const core = b.createModule(.{ .root_source_file = b.path("zig/src/core/root.zig"), .target = target, .optimize = .Debug, .link_libc = true, .imports = &.{.{ .name = "tokenizer", .module = tokenizer }} }); - const server_tests = b.createModule(.{ - .root_source_file = b.path("zig/src/server/root.zig"), - .target = target, - .optimize = .Debug, // the server's unit tests run with safety checks, as zig_test.sh builds them - .link_libc = true, - .imports = &.{ .{ .name = "engine_api", .module = api }, .{ .name = "tokenizer", .module = tokenizer }, .{ .name = "template", .module = template }, .{ .name = "living", .module = living }, .{ .name = "core", .module = core } }, - }); - // the required-tools tests' 27B mask policy and lane fake, on the engine API's own lanes module - if (api.import_table.get("lanes")) |lanes_mod| { - const q27 = @import("qwen27_required.zig").modules(b, lanes_mod); - server_tests.addImport("qwen27_mask_fake", q27.fake); - server_tests.addImport("qwen27_masks", q27.masks); - } - const server_json = server_build.addTo(b, server_tests, target, .Debug); - server_build.testImports(b, server_tests, target, .Debug); - test_step.?.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = server_tests })).step); - // the PDF render worker as tensorfold-native spawns it; POSIX only, as Windows renders in process - if (target.result.os.tag != .windows) { - const worker_exe = b.addOptions(); - worker_exe.addOptionPath("path", exe.getEmittedBin()); - const pdf_worker = b.createModule(.{ .root_source_file = b.path("zig/src/server/pdf_worker_test.zig"), .target = target, .optimize = .Debug, .link_libc = true }); - for (server_tests.import_table.keys(), server_tests.import_table.values()) |name, module| pdf_worker.addImport(name, module); - pdf_worker.addOptions("pdf_worker_exe", worker_exe); - const pdf_worker_run = b.addRunArtifact(b.addTest(.{ .root_module = pdf_worker, .filters = &.{"tensorfold-native PDF render worker:"} })); - test_step.?.dependOn(&pdf_worker_run.step); - b.step("test-pdf-worker", "The PDF render worker spawned from tensorfold-native, rendering where libpdfium is found").dependOn(&pdf_worker_run.step); - } - const kimi_text = b.addExecutable(.{ .name = "tf-k3-text-golden", .root_module = b.createModule(.{ - .root_source_file = b.path("zig/src/server/kimi_golden_main.zig"), - .target = target, - .optimize = .ReleaseSafe, - .link_libc = true, - .imports = &.{ .{ .name = "json", .module = server_json }, .{ .name = "tokenizer", .module = tokenizer } }, - }) }); - b.step("tf-k3-text-golden", "Kimi release prompt token ids against an explicitly supplied local tokenizer").dependOn(&b.addInstallArtifact(kimi_text, .{}).step); - const kimi_host = b.step("test-kimi-serving-host", "Kimi native text, HTTP and resident budget refusals on the host"); - for ([_]*std.Build.Module{ server_tests, engines }) |module| - kimi_host.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = module, .filters = &.{"Kimi"} })).step); - - test_step.?.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = server_json })).step); - @import("cortheon_fuzz.zig").add(b, target, api, tokenizer, template, core); - @import("stream_scan_bench.zig").add(b, target, api, tokenizer, template, core); - // the parse half's tests, as their own test binary (zig/src/server/tool_parse_test.zig) - const tool_parse_tests = b.addTest(.{ .root_module = b.createModule(.{ .root_source_file = b.path("zig/src/server/tool_parse_test.zig"), .target = target, .optimize = .Debug, .link_libc = true, .imports = &.{ .{ .name = "engine_api", .module = api }, .{ .name = "tokenizer", .module = tokenizer }, .{ .name = "template", .module = template } } }) }); - _ = server_build.addTo(b, tool_parse_tests.root_module, target, .Debug); - server_build.testImports(b, tool_parse_tests.root_module, target, .Debug); - test_step.?.dependOn(&b.addRunArtifact(tool_parse_tests).step); - // the chat-template engine's tests (zig/src/core/template/tests.zig), which no other test binary reaches - test_step.?.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = b.createModule(.{ .root_source_file = b.path("zig/src/core/template/tests.zig"), .target = target, .optimize = .Debug, .link_libc = true }) })).step); - // the engine seam's own tests (lane_host.zig), as zig/tests/server/zig_test.sh runs them - test_step.?.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = api })).step); - // the frozen server parity goldens, checked by Zig driving fake_serve - 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-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-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" }); - embed_air.addFileArg(b.path("zig/kernels/metal/qwen3/heads.metal")); - embed_air.addArg("-o"); - _ = embed_air.addOutputFileArg("qwen3-heads.air"); - embed_host.dependOn(&embed_air.step); - embed_host.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = engine, .filters = &.{"embedding"} })).step); - embed_host.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = engines, .filters = &.{"Qwen3 Metal"} })).step); - 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 reuse = b.addExecutable(.{ .name = "tf-flashnext-reuse", .root_module = b.createModule(.{ - .root_source_file = b.path("zig/tests/flashnext_reuse.zig"), - .target = target, - .optimize = optimize, - .link_libc = true, - .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "tensorfold", .module = engine }, .{ .name = "engine_api", .module = api } }, - }) }); - b.installArtifact(reuse); - b.step("tf-flashnext-reuse", "Flash Next prompt reuse against fresh prompt passes: replies at every depth and kept states' bytes").dependOn(&b.addInstallArtifact(reuse, .{}).step); - const batch = b.addExecutable(.{ .name = "tf-flashnext-batch", .root_module = b.createModule(.{ - .root_source_file = b.path("zig/tests/flashnext_batch.zig"), - .target = target, - .optimize = optimize, - .link_libc = true, - .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "tensorfold", .module = engine }, .{ .name = "kernel_sources", .module = engine.import_table.get("kernel_sources").? } }, - }) }); - b.step("tf-flashnext-batch", "Flash Next shared rounds against fresh legacy replies with prompt admission and cancellation").dependOn(&b.addInstallArtifact(batch, .{}).step); - return exe; -} - pub fn metalTargets(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, draft_ids: *std.Build.Module, build_options: *std.Build.Step.Options, test_step: *std.Build.Step) void { const metal_std = b.option([]const u8, "metal-std", "Metal language version (default: MLX's for this macOS)") orelse mlxMetalStd(b); // Without the offline compiler the tests embed empty metallibs; the programs that load them stop instead. @@ -480,10 +363,10 @@ pub fn metalTargets(b: *std.Build, target: std.Build.ResolvedTarget, optimize: s qwen27_build.targets(b, target, optimize, metal, sources, engine, lanes, mods.qwen27, test_step); core_checks.targets(b, target, optimize, metal, engine); contract_build.metal(b, target, optimize, metal, engine, sources, kimi_bytes); - glm_checks.targets(b, target, optimize, metal, engine, sources); + glm_checks.targets(b, target, optimize, metal, engine, sources, test_step); flashnext_checks.targets(b, target, optimize, metal, engine); - _ = nativeServer(b, target, optimize, metal, engine, mods.living, api, engines, build_options, test_step, no_compiler); + _ = metal_server.nativeServer(b, target, optimize, metal, engine, mods.living, api, engines, build_options, test_step, no_compiler); const cluster_metal = b.createModule(.{ .root_source_file = b.path("zig/src/cluster/metal_sink.zig"), @@ -519,7 +402,9 @@ pub fn metalTargets(b: *std.Build, target: std.Build.ResolvedTarget, optimize: s .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "kimi_k3", .module = kimi }, .{ .name = "kimi_metallib", .module = kimi_bytes }, .{ .name = "cluster", .module = cluster } }, }) }); b.installArtifact(k3_cluster); - b.step("tf-k3-cluster", "Kimi K3 tensor- and expert-parallel ranks against one node, through the cluster's canon").dependOn(&b.addInstallArtifact(k3_cluster, .{}).step); + const k3_cluster_step = b.step("tf-k3-cluster", "Kimi K3 tensor- and expert-parallel ranks against one node, through the cluster's canon"); + k3_cluster_step.dependOn(&b.addInstallArtifact(k3_cluster, .{}).step); + if (no_compiler) |fail| k3_cluster_step.dependOn(fail); const tp2 = b.addExecutable(.{ .name = "tf-tp2-bench", .root_module = b.createModule(.{ .root_source_file = b.path("zig/tests/tp2_bench.zig"), .target = target, @@ -611,7 +496,7 @@ pub fn distMetalServer(b: *std.Build, target: std.Build.ResolvedTarget, draft_id 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")); @import("woof.zig").addNative(b, target, .fast, engines, @import("woof.zig").core(b, target, .fast, m.engine)); - return nativeServer(b, target, .fast, m.metal, m.engine, m.living, api, engines, build_options, null, null); + return metal_server.nativeServer(b, target, .fast, m.metal, m.engine, m.living, api, engines, build_options, null, null); } pub fn kimiModule(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, metal: *std.Build.Module, engine: *std.Build.Module, lanes: *std.Build.Module) *std.Build.Module { diff --git a/zig/build/minimax_cuda.zig b/zig/build/minimax_cuda.zig index ba640bc8be3..8c597ab0a34 100644 --- a/zig/build/minimax_cuda.zig +++ b/zig/build/minimax_cuda.zig @@ -30,4 +30,8 @@ pub fn hostTests(b: *std.Build, host: std.Build.ResolvedTarget, cuda: *std.Build const mesh = @import("mesh.zig").module(b, host, .debug, @import("cuda_engines.zig").canonModule(b, host, .debug)); const decl = b.addRunArtifact(b.addTest(.{ .root_module = b.createModule(.{ .root_source_file = b.path("zig/src/families/minimax_m3/cuda_shard_decl_test.zig"), .target = host, .optimize = .debug, .imports = &.{.{ .name = "mesh", .module = mesh }} }) })); run.step.dependOn(&decl.step); + // the Metal drafters' stacked hold: each stream's block at its rows, its sequence apart, eight streams a pass + 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); } diff --git a/zig/build/prefill_widths_metal.zig b/zig/build/prefill_widths_metal.zig index d577611bfb3..69ca742fac0 100644 --- a/zig/build/prefill_widths_metal.zig +++ b/zig/build/prefill_widths_metal.zig @@ -30,6 +30,21 @@ pub fn rest(b: *std.Build, engine: *std.Build.Module, lanes: *std.Build.Module) _ = object.getEmittedBin(); const check = b.step("check-metal-prefill-rest-host", "Actual remaining Metal prompt callback bodies without shaders or execution"); check.dependOn(&object.step); + // MiniMax-M3's prompt pass a chunk a call (#3021): its cuts, a decode between chunks, the drafter's rows, a cancel + const mm_root = b.createModule(.{ .root_source_file = b.path("zig/src/families/minimax_m3/prefill_steps_test.zig"), .target = b.graph.host, .optimize = .debug, .link_libc = true, .imports = &.{.{ .name = "lanes", .module = lanes }} }); + const mm_run = b.addRunArtifact(b.addTest(.{ .root_module = mm_root, .filters = &.{"MiniMax-M3 Metal steps:"} })); + mm_run.has_side_effects = true; + b.step("test-minimax-m3-metal-steps-host", "MiniMax-M3 Metal's stepped prompt pass on recording fakes, no GPU").dependOn(&mm_run.step); + // LFM3's prompt pass a chunk a call (#3021): its cuts, a decode between chunks, a cancel, the whole pass's yield + const lfm3_root = b.createModule(.{ .root_source_file = b.path("zig/src/families/lfm3/prefill_steps_test.zig"), .target = b.graph.host, .optimize = .debug, .link_libc = true, .imports = &.{.{ .name = "lanes", .module = lanes }} }); + const lfm3_run = b.addRunArtifact(b.addTest(.{ .root_module = lfm3_root, .filters = &.{"LFM3 Metal steps:"} })); + lfm3_run.has_side_effects = true; + b.step("test-lfm3-metal-steps-host", "LFM3 Metal's stepped prompt pass on recording fakes, no GPU").dependOn(&lfm3_run.step); + // LFM2-MoE's prompt pass a chunk a call (#3021): its cuts, a decode between chunks, the drafter's rows, a cancel + const lfm_root = b.createModule(.{ .root_source_file = b.path("zig/src/families/lfm2_moe/prefill_steps.zig"), .target = b.graph.host, .optimize = .debug, .link_libc = true, .imports = &.{.{ .name = "lanes", .module = lanes }} }); + const lfm_run = b.addRunArtifact(b.addTest(.{ .root_module = lfm_root, .filters = &.{"LFM2-MoE Metal steps:"} })); + lfm_run.has_side_effects = true; + b.step("test-lfm2-moe-metal-steps-host", "LFM2-MoE Metal's stepped prompt pass on recording fakes, no GPU").dependOn(&lfm_run.step); 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 host = b.createModule(.{ .root_source_file = b.path("zig/src/native/qwen4_metal.zig"), .target = b.graph.host, .link_libc = true, .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "tensorfold", .module = engine }, .{ .name = "engine_api", .module = api }, .{ .name = "contract", .module = @import("kernel_contract.zig").module(b, b.graph.host, .debug) } } }); @import("qwen4.zig").metalNative(b, b.graph.host, host); diff --git a/zig/build/qwen35_cache_host.zig b/zig/build/qwen35_cache_host.zig index 90c88440446..25c33d3a839 100644 --- a/zig/build/qwen35_cache_host.zig +++ b/zig/build/qwen35_cache_host.zig @@ -15,6 +15,15 @@ pub fn tests(b: *std.Build) void { .imports = &.{ .{ .name = "metal", .module = fake }, .{ .name = "lanes", .module = lanes }, .{ .name = "kernel_sources", .module = sources } }, }); b.step("test-qwen35-cache-host", "Qwen2B retained bytes, paged images and resumed host-reference tokens").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = root, .filters = &.{"Qwen retained:"} })).step); + // Qwen2B's prompt pass a chunk a call (#3021): its cuts, its state, a resume, a cancel, decodes between chunks + const steps = b.createModule(.{ + .root_source_file = b.path("zig/src/qwen35_prefill_steps_test.zig"), + .target = b.graph.host, + .optimize = .debug, + .link_libc = true, + .imports = &.{ .{ .name = "metal", .module = fake }, .{ .name = "lanes", .module = lanes }, .{ .name = "kernel_sources", .module = sources } }, + }); + b.step("test-qwen35-metal-steps-host", "Qwen2B Metal's stepped prompt pass on host-backed caches, no GPU").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = steps, .filters = &.{"Qwen2B Metal steps:"} })).step); const pure = &.{ "admit the affine 2B", "admit untied heads", "text_config parses", "a top-level config", "the geometry refuses", "the Python loader's refusals", "candidate selection preserves", "a masked draw", "a stream's cache bytes" }; b.step("test-qwen35-metal-host", "Qwen2B geometry, keyed draws and state sizing on the CPU").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = root, .filters = pure })).step); const topk = b.createModule(.{ .root_source_file = b.path("zig/src/core/lanes/sampling_row_topk.zig"), .target = b.graph.host, .optimize = .debug, .link_libc = true }); diff --git a/zig/build/residency_host.zig b/zig/build/residency_host.zig index 1bf0fcc1a59..ce870335006 100644 --- a/zig/build/residency_host.zig +++ b/zig/build/residency_host.zig @@ -6,6 +6,9 @@ pub fn steps(b: *std.Build) void { if (b.graph.host.result.os.tag == .macos) metal.linkSystemLibrary("objc", .{}); const run = b.addRunArtifact(b.addTest(.{ .root_module = metal, .filters = &.{ "residency", "a set is built", "buffers made later", "a join whose", "an operator load ceiling" } })); b.step("test-metal-residency-host", "Unique residency allocations, limits, flags and lifetimes without devices").dependOn(&run.step); + const timeline_module = b.createModule(.{ .root_source_file = b.path("zig/src/metal/metal4_timeline.zig"), .target = b.graph.host, .link_libc = true }); + const timeline = b.addRunArtifact(b.addTest(.{ .root_module = timeline_module, .filters = &.{ "timeline stage records:", "timeline rounds:", "timeline init:", "timeline kernels:", "timeline labels:" } })); + b.step("test-metal-timeline-host", "Metal 4 timeline allocation failure boundaries without a device").dependOn(&timeline.step); const recording = b.createModule(.{ .root_source_file = b.path("zig/residency_recording_metal.zig"), .target = b.graph.host }); const lanes = b.createModule(.{ .root_source_file = b.path("zig/src/core/lanes/lanes.zig"), .target = b.graph.host, .link_libc = true }); // the prompt cache's budget over the same residency limits, so its no-footprint branch runs off macOS too diff --git a/zig/build/server.zig b/zig/build/server.zig index a157e0143b7..af6108ab8a6 100644 --- a/zig/build/server.zig +++ b/zig/build/server.zig @@ -135,6 +135,9 @@ pub fn toolHostTests(b: *std.Build, parser: *std.Build.Module, server: *std.Buil const scopes = b.addRunArtifact(b.addTest(.{ .root_module = server, .filters = &.{"auth scopes"} })); scopes.has_side_effects = true; b.step("test-key-scopes-host", "Key-file scopes: exact route grants, stateless Responses and refusals over sockets").dependOn(&scopes.step); + const witnessed = b.addRunArtifact(b.addTest(.{ .root_module = server, .filters = &.{"execution witness"} })); + witnessed.has_side_effects = true; + b.step("test-execution-witness-host", "The opt-in execution witness: parts, scopes, reload epochs and refusals over sockets").dependOn(&witnessed.step); const profile_line = b.addRunArtifact(b.addTest(.{ .root_module = server, .filters = &.{"profile line:"} })); profile_line.has_side_effects = true; b.step("test-profile-line-host", "Profile start-up line scoping against the tree's real backend names").dependOn(&profile_line.step); diff --git a/zig/build/xpu.zig b/zig/build/xpu.zig index c734e802350..3745687719f 100644 --- a/zig/build/xpu.zig +++ b/zig/build/xpu.zig @@ -41,7 +41,7 @@ pub fn steps(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.buil c.addArgs(&.{ "-device", device, "-options", b.fmt("{s}{s} -I zig/kernels/xpu/qwen27", .{ if (std.mem.startsWith(u8, k[0], "rows_") or std.mem.eql(u8, k[0], "flashnext")) opts_rows else opts, k[2] }), "-output_no_suffix", "-output", k[0], "-out_dir" }); c.setCwd(b.path(".")); c.addFileInput(b.path("zig/kernels/xpu/gemma4/attn_rows_g4.cl")); - for ([_][]const u8{ "flashnext.cl", "fn_mixers.cl", "fn_moe_head.cl" }) |part| c.addFileInput(b.path(b.fmt("zig/kernels/xpu/flashnext/{s}", .{part}))); + for ([_][]const u8{ "flashnext.cl", "fn_dpas.cl", "fn_mixers.cl", "fn_moe_head.cl" }) |part| c.addFileInput(b.path(b.fmt("zig/kernels/xpu/flashnext/{s}", .{part}))); for ([_][]const u8{ "glue.cl", "glue_attn.cl", "glue_quant.cl", "shape.h" }) |part| c.addFileInput(b.path(b.fmt("zig/kernels/xpu/qwen27/{s}", .{part}))); const dir = c.addOutputDirectoryArg(b.fmt("ocloc-{s}", .{k[0]})); _ = files.addCopyFile(dir.path(b, b.fmt("{s}.bin", .{k[0]})), b.fmt("{s}.bin", .{k[0]})); diff --git a/zig/cuda_family_groups_host.zig b/zig/cuda_family_groups_host.zig index 60e830bba4b..15b2f76cd08 100644 --- a/zig/cuda_family_groups_host.zig +++ b/zig/cuda_family_groups_host.zig @@ -15,6 +15,7 @@ fn reset() void { Trace.count = 0; Trace.prompts = 0; Trace.grouped = 0; + Trace.segmented = 0; } fn check(rows: usize, parts: usize, tile: usize, grouped: bool, prompt: bool) !void { const per = (rows + tile - 1) / tile; @@ -113,3 +114,36 @@ test "GB10 family grouping: Spark MLP preserves prompts and other GPUs" { try t.expectEqual(@as(usize, if (gb10) 9 else 16), Trace.count); } } + +test "GB10 family grouping: Spark stacked gate-up views use one segmented launch off GB10" { + var d: cuda.Driver = undefined; + const e = fixture.engine(&d, false); + var k: spark.kernels.Kernels = undefined; + k.affine = e.affine; + k.affine.seg_fn = .{ .d = &d, .handle = @ptrFromInt(8) }; + k.affine.split_fn = .{ .d = &d, .handle = @ptrFromInt(2) }; // recorded as one member's GemvPart, as gemv_fn's + k.affine.split = .{ + .work = .{ .d = &d, .ptr = 0x4000000, .len = 8 << 20, .borrowed = true }, + .tickets = .{ .d = &d, .ptr = 0x5000000, .len = 4096, .borrowed = true }, + }; + const geo = spark.config.spark4b; + const stack: cuda.qlinear.Affine4 = .{ .w = 0x100000, .s = 0x2000000, .b = 0x3000000, .n = 2 * geo.intermediate, .k = geo.hidden, .npad = 2 * geo.intermediate }; + const views = try spark.weights.gateUpViews(stack, geo.intermediate); + const ps = [_]spark.weights.Proj{ .{ .a4 = views[0] }, .{ .a4 = views[1] } }; + const m: spark.forward.Model = undefined; + for ([_]usize{ 1, 2, 8, 16, 17, 32, 64, 128 }) |rows| { + reset(); + try m.projectMany(&k, e.stream, &ps, x, xs, &.{ out, out + 0x1000000 }, rows, false); + const chunks = (rows + 15) / 16; + try t.expectEqual(chunks, Trace.segmented); + try t.expectEqual(2 * chunks, Trace.count); + for (Trace.calls[0..Trace.count], 0..) |call, i| { + const start = i / 2 * 16; + try t.expectEqual(@as(usize, 8), call.id); + try t.expectEqual(@as(c_int, 2), call.sk); + try t.expectEqual(x + start * geo.hidden * 2, call.x); + try t.expectEqual(xs + start * (geo.hidden / 64) * 4, call.xs); + try t.expectEqual(out + (i % 2) * 0x1000000 + start * geo.intermediate * 2, call.out); + } + } +} diff --git a/zig/exl3_prompt_host.zig b/zig/exl3_prompt_host.zig index 655ac1983cb..3cd2e5fbe39 100644 --- a/zig/exl3_prompt_host.zig +++ b/zig/exl3_prompt_host.zig @@ -17,8 +17,8 @@ const Capture = struct { 3 => &.{ 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4 }, 5 => &.{ 8, 8, 8, 8, 8, 8, 4, 4, 4, 4, 4 }, 11 => &.{ 8, 4, 8, 8, 4 }, - 12 => &.{ 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 4, 4, 4, 4, 4, 4 }, - 13 => &.{ 8, 8, 8, 8, 8, 8, 8, 4, 4, 4 }, + 12, 14 => &.{ 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 4, 4, 4, 4, 4, 4 }, + 13, 15 => &.{ 8, 8, 8, 8, 8, 8, 8, 4, 4, 4 }, else => &.{}, }; for (sizes, 0..) |size, j| { @@ -57,7 +57,7 @@ fn run(rows: usize, prompt: bool, shared: bool) !void { d.api.cuMemcpy2DAsync_v2 = Capture.copy; const s: cuda.Stream = .{ .d = &d, .handle = null }; var k: ex.Experts = .{ .mod = undefined, .group = function(&d, 1), .rot_in = function(&d, 2), .grouped = @splat(function(&d, 3)), .gateup = function(&d, 4), .down_combine = function(&d, 5) }; - if (comptime @hasField(ex.Experts, "prompt")) k.prompt = .{ .rotate = function(&d, 11), .gateup = function(&d, 12), .down = function(&d, 13) }; + if (comptime @hasField(ex.Experts, "prompt")) k.prompt = .{ .rotate = function(&d, 11), .gateup = function(&d, 12), .down = function(&d, 13), .gateup_k6 = function(&d, 14), .down_k6 = function(&d, 15) }; const ek: glm.experts.Kernels = .{ .nvfp4 = undefined, .b32 = null, .router = .{ .plan_small = function(&d, 20), .plan_rank = function(&d, 21), .plan_offsets = function(&d, 22), .plan_scatter = function(&d, 23), .plan_rows = function(&d, 24), .plan_rank_rows = function(&d, 25), .plan_scatter_rows = function(&d, 26) } }; const w: glm.exl3.Experts = .{ .gt = 100, .ut = 200, .dt = 300, .k2 = 400, .suh_g = 500, .suh_u = 600, .svh_g = 700, .svh_u = 800, .suh_d = 900, .svh_d = 1000, .shx = shared }; const sc: glm.exl3.Scratch = .{ .picks = 0x100000000, .xg = 0, .xu = 0, .z = 0 }; @@ -167,14 +167,26 @@ test "exl3 prompt: decode uses item plans and keeps slot and input offsets acros } } -test "exl3 prompt: the common dispatch requires verified mcg4 geometry and keeps every fallback" { +test "exl3 prompt: the common dispatch requires verified mcg3 or mcg4 geometry and keeps every fallback" { const P = ex.prompt; var l: ex.Layer = .{ .gate = 0, .up = 0, .down = 0, .gate_k2 = 0, .up_k2 = 0, .down_k2 = 0, .suh_g = 0, .suh_u = 0, .svh_g = 0, .svh_u = 0, .suh_d = 0, .svh_d = 0, .dims = 512, .width = 256, .experts = 9, .codebook = .mcg, .uniform_k2 = 8 }; try std.testing.expect(P.eligible(l)); l.uniform_k2 = 0; try std.testing.expect(!P.eligible(l)); l.uniform_k2 = 6; - try std.testing.expect(!P.eligible(l)); + try std.testing.expect(P.eligible(l)); + for ([_]u32{ 4, 5, 7, 10 }) |k2| { + l.uniform_k2 = k2; + try std.testing.expect(!P.eligible(l)); + } + l.uniform_k2 = 0; + for ([_][2]u32{ .{ 6, 0 }, .{ 0, 8 }, .{ 4, 8 }, .{ 6, 10 } }) |w| { + l.uniform_k2_gu = w[0]; + l.uniform_k2_d = w[1]; + try std.testing.expect(!P.eligible(l)); + } + l.uniform_k2_gu = 0; + l.uniform_k2_d = 0; l.uniform_k2 = 8; for ([_]ex.Codebook{ .inst3, .mul1 }) |cb| { l.codebook = cb; @@ -250,3 +262,41 @@ test "exl3 prompt: GLM admission facts through shared lanes keep drafted plain a for ([_]bool{ false, true }) |drafts| for ([_]usize{ 0, 1, 3, 7 }) |others| try std.testing.expectEqual(plain, try reply(drafts, others, seed)); } } + +test "exl3 prompt: each projection group launches the kernel of its own verified width, with the same arguments" { + var d: cuda.Driver = undefined; + d.api.cuLaunchKernel = Capture.launch; + const s: cuda.Stream = .{ .d = &d, .handle = null }; + var k: ex.Experts = .{ .mod = undefined, .group = function(&d, 1), .rot_in = function(&d, 2), .grouped = @splat(function(&d, 3)), .gateup = function(&d, 4), .down_combine = function(&d, 5) }; + k.prompt = .{ .rotate = function(&d, 11), .gateup = function(&d, 12), .down = function(&d, 13), .gateup_k6 = function(&d, 14), .down_k6 = function(&d, 15) }; + const router: cuda.grouped.Router = .{ .plan_small = function(&d, 20), .plan_rank = function(&d, 21), .plan_offsets = function(&d, 22), .plan_scatter = function(&d, 23), .plan_rows = function(&d, 24), .plan_rank_rows = function(&d, 25), .plan_scatter_rows = function(&d, 26) }; + const plan: cuda.grouped.Plan = .{ .items = 10000, .members = 20000, .counts = 30000, .rank = 40000, .hist = 50000 }; + var l: ex.Layer = .{ .gate = 100, .up = 200, .down = 300, .gate_k2 = 400, .up_k2 = 400, .down_k2 = 400, .suh_g = 500, .suh_u = 600, .svh_g = 700, .svh_u = 800, .suh_d = 900, .svh_d = 1000, .dims = 512, .width = 256, .experts = 9, .codebook = .mcg, .limit = 10, .shared_input = true }; + var want: [2]Capture.Call = undefined; // the 4-bit gate/up and down launches + for ([_][3]u32{ .{ 8, 0, 0 }, .{ 0, 6, 8 }, .{ 0, 6, 6 }, .{ 0, 8, 6 }, .{ 6, 0, 0 }, .{ 8, 8, 8 }, .{ 6, 6, 0 } }) |w| { + l.uniform_k2 = w[0]; + l.uniform_k2_gu = w[1]; + l.uniform_k2_d = w[2]; + const sc = try ex.prompt.scratch(0x1000, l, 40, 8); + Capture.reset(); + try k.prompt.run(&k, router, s, l, 0x200000000, 520, 0x300000000, 40, sc, plan, 0x400000000, 9); + const gu: usize = if ((if (w[1] != 0) w[1] else w[0]) == 6) 14 else 12; + const dn: usize = if ((if (w[2] != 0) w[2] else w[0]) == 6) 15 else 13; + try std.testing.expectEqual(@as(usize, 1), Capture.by(gu).len); + try std.testing.expectEqual(@as(usize, 1), Capture.by(dn).len); + try std.testing.expectEqual(@as(usize, 1), Capture.by(11).len); + for ([_]usize{ 12, 13, 14, 15 }) |id| if (id != gu and id != dn) try std.testing.expectEqual(@as(usize, 0), Capture.by(id).len); + const got = [2]Capture.Call{ Capture.by(gu)[0], Capture.by(dn)[0] }; + if (w[0] == 8 and w[1] == 0) want = got; + for (got, want) |g, x| { + try std.testing.expectEqual(x.grid, g.grid); + try std.testing.expectEqual(x.block, g.block); + try std.testing.expectEqual(x.args, g.args); + } + } + l.uniform_k2 = 8; + l.uniform_k2_gu = 6; // disagrees with every projection's 8: not verified, so no prompt launch + l.uniform_k2_d = 0; + try std.testing.expect(!ex.prompt.eligible(l)); + try std.testing.expectError(error.Exl3Shape, ex.prompt.scratch(0x1000, l, 40, 8)); +} diff --git a/zig/glm_exl3_prompt_host.zig b/zig/glm_exl3_prompt_host.zig index f0d067fab49..1308d03e361 100644 --- a/zig/glm_exl3_prompt_host.zig +++ b/zig/glm_exl3_prompt_host.zig @@ -81,7 +81,7 @@ fn run(rows: usize, prompt: bool, shared: bool, count: usize) !void { var k: glm.exl3.Kernels = undefined; inline for (.{ "group", "rot_in", "gateup", "down_combine" }, .{ 9, 5, 13, 14 }) |field, id| @field(k, field) = Record.function(&d, id); k.grouped = .{ Record.function(&d, 10), Record.function(&d, 11), Record.function(&d, 12) }; - k.prompt = .{ .rotate = Record.function(&d, 6), .gateup = Record.function(&d, 7), .down = Record.function(&d, 8) }; + k.prompt = .{ .rotate = Record.function(&d, 6), .gateup = Record.function(&d, 7), .down = Record.function(&d, 8), .gateup_k6 = Record.function(&d, 21), .down_k6 = Record.function(&d, 22) }; var ek: glm.experts.Kernels = undefined; inline for (.{ "plan_small", "plan_rows", "plan_rank", "plan_offsets", "plan_scatter", "plan_rank_rows", "plan_scatter_rows" }, .{ 1, 18, 2, 3, 4, 19, 20 }) |field, id| @field(ek.router, field) = Record.function(&d, id); const w = glm.exl3.Experts{ .gt = 101, .ut = 102, .dt = 103, .k2 = 104, .suh_g = 105, .suh_u = 106, .svh_g = 107, .svh_u = 108, .suh_d = 109, .svh_d = 110, .shx = shared }; @@ -169,12 +169,23 @@ fn guarded(text: []const u8, name: []const u8, payload: []const u8) bool { return guard < @min(load, member); } +/// Whether kernel `name`'s whole body is the call `call` (the guarded template at one width). +fn forwards(text: []const u8, name: []const u8, call: []const u8) bool { + const at = std.mem.indexOf(u8, text, name) orelse return false; + const tail = text[at..]; + const open = std.mem.indexOf(u8, tail, "{\n") orelse return false; + const end = std.mem.indexOf(u8, tail, "\n}") orelse return false; + return open < end and std.mem.startsWith(u8, std.mem.trim(u8, tail[open + 2 .. end], " "), call) and std.mem.count(u8, tail[open + 2 .. end], ";") == 1; +} + test "GLM EXL3 prompt: shared-id guards precede payload loads and late-guard controls are caught" { - try t.expect(guarded(source, "tf_exl3_prompt_gu(", "tgateup<")); - try t.expect(guarded(source, "tf_exl3_prompt_down(", "members[first")); + try t.expect(guarded(source, "void prompt_gu(", "tgateup<")); + try t.expect(guarded(source, "void prompt_down(", "members[first")); + for ([_][2][]const u8{ .{ "tf_exl3_prompt_gu(", "prompt_gu<8>(" }, .{ "tf_exl3_prompt_gu_k6(", "prompt_gu<6>(" }, .{ "tf_exl3_prompt_down(", "prompt_down<8>(" }, .{ "tf_exl3_prompt_down_k6(", "prompt_down<6>(" } }) |k| try t.expect(forwards(source, k[0], k[1])); + try t.expect(!forwards(source, "tf_exl3_prompt_gu(", "prompt_gu<6>(")); const bad = try std.mem.replaceOwned(u8, t.allocator, source, "if (e == skip) return;", "const volatile int control_member = members[items[3 * item + 1]];\n if (e == skip) return;"); defer t.allocator.free(bad); try t.expectEqual(@as(usize, 2), std.mem.count(u8, bad, "if (e == skip) return;")); - try t.expect(!guarded(bad, "tf_exl3_prompt_gu(", "tgateup<")); - try t.expect(!guarded(bad, "tf_exl3_prompt_down(", "members[first")); + try t.expect(!guarded(bad, "void prompt_gu(", "tgateup<")); + try t.expect(!guarded(bad, "void prompt_down(", "members[first")); } diff --git a/zig/kernels/cuda/contract_controls_idol_decoder.cuh b/zig/kernels/cuda/contract_controls_idol_decoder.cuh new file mode 100644 index 00000000000..7dff0031dda --- /dev/null +++ b/zig/kernels/cuda/contract_controls_idol_decoder.cuh @@ -0,0 +1,53 @@ +// Idol's decoders' controls: idol_decoder.cu's templates at BREAK 1 to 3, each breaking a rounding point, sum or rule. +#pragma once + +#include "idol_decoder.cuh" +#include "idol_decoder_attention.cuh" + +#define TF_CTL_IDOL_DEC_EMBED(NAME, BREAK) \ + extern "C" __global__ void __launch_bounds__(256) \ + NAME(const float* P, const float* W, const float* B, const float* F, float* Hs, int rows) { \ + tf_idol_dec::embed(P, W, B, F, Hs, rows); \ + } +TF_CTL_IDOL_DEC_EMBED(tf_ctl_idol_dec_embed_pe16, 1) +TF_CTL_IDOL_DEC_EMBED(tf_ctl_idol_dec_embed_sum16, 2) +#undef TF_CTL_IDOL_DEC_EMBED + +#define TF_CTL_IDOL_DEC_HALF(NAME, BREAK) \ + extern "C" __global__ void __launch_bounds__(256) \ + NAME(const float* Y, const float* B, __half* O, int width, int rows) { \ + tf_idol_dec::to_half(Y, B, O, width, rows); \ + } +TF_CTL_IDOL_DEC_HALF(tf_ctl_idol_dec_half_early, 1) +TF_CTL_IDOL_DEC_HALF(tf_ctl_idol_dec_half_writes, 2) +#undef TF_CTL_IDOL_DEC_HALF + +#define TF_CTL_IDOL_DEC_KV(NAME, BREAK) \ + extern "C" __global__ void __launch_bounds__(256) \ + NAME(const __half* X, const __half* W, const __half* B, __half* KV, int rows) { \ + tf_idol_dec::kv(X, W, B, KV, rows); \ + } +TF_CTL_IDOL_DEC_KV(tf_ctl_idol_dec_kv_early, 1) +TF_CTL_IDOL_DEC_KV(tf_ctl_idol_dec_kv_sum16, 2) +#undef TF_CTL_IDOL_DEC_KV + +#define TF_CTL_IDOL_DEC_HEADS(NAME, BREAK) \ + extern "C" __global__ void __launch_bounds__(256) \ + NAME(const __half* X, const float* G, __half* Y, int stride, int offset, int rows) { \ + tf_idol_dec::heads(X, G, Y, stride, offset, rows); \ + } +TF_CTL_IDOL_DEC_HEADS(tf_ctl_idol_dec_heads_fmax, 1) +TF_CTL_IDOL_DEC_HEADS(tf_ctl_idol_dec_heads_div16, 2) +TF_CTL_IDOL_DEC_HEADS(tf_ctl_idol_dec_heads_sq16, 3) +#undef TF_CTL_IDOL_DEC_HEADS + +#define TF_CTL_IDOL_DEC_ATTENTION(NAME, BODY) \ + extern "C" __global__ void __launch_bounds__(256) NAME(const __half* Q, int qs, const __half* KV, int ks, \ + __half* O, int lq, int lk, int heads, float scale) { \ + BODY(Q, qs, KV, ks, O, lq, lk, heads, scale); \ + } +TF_CTL_IDOL_DEC_ATTENTION(tf_ctl_idol_dec_attention_unmasked, (tf_idol_dec::rows<64, 8, 1>)) +TF_CTL_IDOL_DEC_ATTENTION(tf_ctl_idol_dec_attention_pv16, (tf_idol_dec::rows<64, 8, 2>)) +TF_CTL_IDOL_DEC_ATTENTION(tf_ctl_idol_dec_few_p16, tf_idol_dec::few<1>) +TF_CTL_IDOL_DEC_ATTENTION(tf_ctl_idol_dec_few_pv16, tf_idol_dec::few<2>) +#undef TF_CTL_IDOL_DEC_ATTENTION diff --git a/zig/kernels/cuda/contract_controls_set.cu b/zig/kernels/cuda/contract_controls_set.cu index 7b5e05d389b..df0f2139831 100644 --- a/zig/kernels/cuda/contract_controls_set.cu +++ b/zig/kernels/cuda/contract_controls_set.cu @@ -8,3 +8,5 @@ #include "contract_idol_controls.cuh" #include "contract_embed_controls.cuh" #include "contract_hcn_controls.cuh" +// Idol decoders: controls for rounding, sums and exceptional values. +#include "contract_controls_idol_decoder.cuh" diff --git a/zig/kernels/cuda/exl3_experts.cu b/zig/kernels/cuda/exl3_experts.cu index 52ddf77dbf9..77ea3a7b6ff 100644 --- a/zig/kernels/cuda/exl3_experts.cu +++ b/zig/kernels/cuda/exl3_experts.cu @@ -282,7 +282,9 @@ extern "C" __global__ void tf_exl3_prompt_rotate(const __nv_bfloat16* __restrict for (int j = 0; j < 4; ++j) o[j] = __float2half_rn(v[j] * HAD_SCALE); } -extern "C" __global__ void __launch_bounds__(256, 2) tf_exl3_prompt_gu(const half* __restrict__ Xg, const half* __restrict__ Xu, +// Gate and up of one width K2 (8: 4 bits, 6: 3 bits), the shared expert skipped before any payload read. +template +__device__ __forceinline__ void prompt_gu(const half* __restrict__ Xg, const half* __restrict__ Xu, const uint64_t* __restrict__ Tg, const uint64_t* __restrict__ Tu, const int* __restrict__ items, const int* __restrict__ counts, const int* __restrict__ members, const half* __restrict__ svh_g, const half* __restrict__ svh_u, const half* __restrict__ suh_d, half* __restrict__ xd, int K, int N, int xdiv, float limit, int act_mode, int skip) { @@ -292,18 +294,34 @@ extern "C" __global__ void __launch_bounds__(256, 2) tf_exl3_prompt_gu(const hal const int e = items[3 * item]; if (e == skip) return; - __shared__ __align__(16) unsigned char smem_raw[tsmem_bytes()]; // one buffer for either instantiation + __shared__ __align__(16) unsigned char smem_raw[tsmem_bytes()]; // one buffer for either instantiation __shared__ int rows_sh[TPM]; - if (xdiv > 1) tgateup(Xg, Xu, Tg, Tu, items, counts, members, svh_g, svh_u, suh_d, xd, K, N, xdiv, limit, act_mode, smem_raw, rows_sh); - else tgateup<2 * TPM>(Xg, Xu, Tg, Tu, items, counts, members, svh_g, svh_u, suh_d, xd, K, N, 1, limit, act_mode, smem_raw, rows_sh); + if (xdiv > 1) tgateup(Xg, Xu, Tg, Tu, items, counts, members, svh_g, svh_u, suh_d, xd, K, N, xdiv, limit, act_mode, smem_raw, rows_sh); + else tgateup<2 * TPM, K2>(Xg, Xu, Tg, Tu, items, counts, members, svh_g, svh_u, suh_d, xd, K, N, 1, limit, act_mode, smem_raw, rows_sh); +} + +extern "C" __global__ void __launch_bounds__(256, 2) tf_exl3_prompt_gu(const half* __restrict__ Xg, const half* __restrict__ Xu, + const uint64_t* __restrict__ Tg, const uint64_t* __restrict__ Tu, const int* __restrict__ items, const int* __restrict__ counts, + const int* __restrict__ members, const half* __restrict__ svh_g, const half* __restrict__ svh_u, const half* __restrict__ suh_d, + half* __restrict__ xd, int K, int N, int xdiv, float limit, int act_mode, int skip) { + prompt_gu<8>(Xg, Xu, Tg, Tu, items, counts, members, svh_g, svh_u, suh_d, xd, K, N, xdiv, limit, act_mode, skip); +} + +// The same at 3 bits: gate and up both 3-bit mcg (tile_words<6>: 96-byte tiles), the arguments tf_exl3_prompt_gu's. +extern "C" __global__ void __launch_bounds__(256, 2) tf_exl3_prompt_gu_k6(const half* __restrict__ Xg, const half* __restrict__ Xu, + const uint64_t* __restrict__ Tg, const uint64_t* __restrict__ Tu, const int* __restrict__ items, const int* __restrict__ counts, + const int* __restrict__ members, const half* __restrict__ svh_g, const half* __restrict__ svh_u, const half* __restrict__ suh_d, + half* __restrict__ xd, int K, int N, int xdiv, float limit, int act_mode, int skip) { + prompt_gu<6>(Xg, Xu, Tg, Tu, items, counts, members, svh_g, svh_u, suh_d, xd, K, N, xdiv, limit, act_mode, skip); } // Block (256 model-width columns, item): y[row][slot][:] = the down epilogue of the item's pairs (this rank's share). -extern "C" __global__ void __launch_bounds__(256, 2) tf_exl3_prompt_down(const half* __restrict__ Xd, const uint64_t* __restrict__ Td, +template +__device__ __forceinline__ void prompt_down(const half* __restrict__ Xd, const uint64_t* __restrict__ Td, const int* __restrict__ items, const int* __restrict__ counts, const int* __restrict__ members, const half* __restrict__ svh_d, float* __restrict__ y, int K, int D, int skip) { - __shared__ __align__(16) unsigned char smem_raw[tsmem_bytes()]; + __shared__ __align__(16) unsigned char smem_raw[tsmem_bytes()]; __shared__ int rows_sh[TPM]; const int cb = blockIdx.x, item = blockIdx.y; if (item >= counts[0]) return; @@ -314,7 +332,7 @@ extern "C" __global__ void __launch_bounds__(256, 2) tf_exl3_prompt_down(const h __syncthreads(); const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31; float acc[TMT][TNB][4]; - tmain<1, TPM>(Xd, Xd, Td, Td, rows_sh, cnt, e, K, D >> 4, cb, 1, reinterpret_cast(smem_raw), acc); + tmain<1, TPM, K2>(Xd, Xd, Td, Td, rows_sh, cnt, e, K, D >> 4, cb, 1, reinterpret_cast(smem_raw), acc); float* Ed = reinterpret_cast(smem_raw); for (int hf = 0; hf < 2 && hf * TPH < cnt; ++hf) { if (hf) __syncthreads(); @@ -336,3 +354,16 @@ extern "C" __global__ void __launch_bounds__(256, 2) tf_exl3_prompt_down(const h } } } + +extern "C" __global__ void __launch_bounds__(256, 2) tf_exl3_prompt_down(const half* __restrict__ Xd, const uint64_t* __restrict__ Td, + const int* __restrict__ items, const int* __restrict__ counts, const int* __restrict__ members, const half* __restrict__ svh_d, + float* __restrict__ y, int K, int D, int skip) { + prompt_down<8>(Xd, Td, items, counts, members, svh_d, y, K, D, skip); +} + +// The same at 3 bits (3-bit mcg down), the arguments tf_exl3_prompt_down's. +extern "C" __global__ void __launch_bounds__(256, 2) tf_exl3_prompt_down_k6(const half* __restrict__ Xd, const uint64_t* __restrict__ Td, + const int* __restrict__ items, const int* __restrict__ counts, const int* __restrict__ members, const half* __restrict__ svh_d, + float* __restrict__ y, int K, int D, int skip) { + prompt_down<6>(Xd, Td, items, counts, members, svh_d, y, K, D, skip); +} diff --git a/zig/kernels/cuda/exl3_prompt.cuh b/zig/kernels/cuda/exl3_prompt.cuh index 9f93e276650..cbbf60d12ce 100644 --- a/zig/kernels/cuda/exl3_prompt.cuh +++ b/zig/kernels/cuda/exl3_prompt.cuh @@ -4,12 +4,14 @@ #include "common/qmm_frag.cuh" namespace tf_exl3_prompt { using namespace tf_exl3; +// One mcg tile of K2 half-bits a value (8: 4 bits, 6: 3 bits) from shared memory into this lane's B fragments. +template __device__ __forceinline__ void decode_tile_p(const uint32_t* tile, int lane, uint32_t (&b0)[2], uint32_t (&b1)[2]) { - uint32_t w[lane_words<8>()]; + uint32_t w[lane_words()]; int word, offset; - lane_start<8>(lane, word, offset); - for (int i = 0; i < lane_words<8>(); ++i) w[i] = tile[(word + i) % tile_words<8>()]; - decode_lane<8, CB_MCG>(w, lane, b0, b1); + lane_start(lane, word, offset); + for (int i = 0; i < lane_words(); ++i) w[i] = tile[(word + i) % tile_words()]; + decode_lane(w, lane, b0, b1); } __device__ __forceinline__ void cp_async16(void* dst, const void* src, bool valid) { tf_common::cp16z(dst, src, valid); @@ -22,12 +24,14 @@ namespace tf_exl3_prompt { constexpr int TPM = 64, TNW = 8, TMT = 16 / TNW, TNB = TPM / 8, TT = TNW * 32, TPH = TPM / 2; constexpr int TBK = 32, TKT = TBK / 16, TSTAGES = 3, TXS = TBK + 8; -constexpr int TWORDS = 16 * TKT * 32; +template +constexpr int twords() { return 16 * TKT * tile_words(); } // a stage's weight words: 16 tiles by TKT constexpr int GU_ES = 128 + 4, DN_ES = 256 + 4; // the epilogue sums' row strides (floats) -template -constexpr int tstage_halves() { return XR * TXS + 2 * TWORDS; } +template +constexpr int tstage_halves() { return XR * TXS + 2 * twords(); } +template constexpr int tsmem_bytes() { - const int gu = TSTAGES * tstage_halves<2 * TPM>() * 2; // gate and up rows apart (no shared rotation) + const int gu = TSTAGES * tstage_halves<2 * TPM, K2>() * 2; // gate and up rows apart (no shared rotation) const int ep = 2 * TPH * GU_ES * 4, dn = TPH * DN_ES * 4; return gu > ep ? (gu > dn ? gu : dn) : (ep > dn ? ep : dn); } @@ -40,11 +44,12 @@ __device__ __forceinline__ void ttile(int q, int cb, int& mat, int& nt) { } // Main loop: acc[i][nb] = warp tile i x members nb * 8 .. + 7 over K; XR rows a stage (TPM if X0 == X1, else 2 TPM). -template +template __device__ __forceinline__ void tmain(const half* __restrict__ X0, const half* __restrict__ X1, const uint64_t* __restrict__ tp0, const uint64_t* __restrict__ tp1, const int* rows_sh, int cnt, int e, int K, int NTILES, int cb, int xdiv, half* stage, float (&acc)[TMT][TNB][4]) { - constexpr int SH = tstage_halves(); + constexpr int SH = tstage_halves(); + constexpr int TW = tile_words(), PIECES = TW / 4; // a tile's 32-bit words and 16-byte pieces const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31; int mat, nt_unused; ttile(warp * TMT, cb, mat, nt_unused); @@ -69,12 +74,12 @@ __device__ __forceinline__ void tmain(const half* __restrict__ X0, const half* _ cp_async16(dst + ((size_t)m * TPM + i) * TXS + j * 8, src, r >= 0); } uint32_t* wdst = reinterpret_cast(dst + (size_t)XR * TXS); - for (int idx = threadIdx.x; idx < 16 * TKT * 8; idx += TT) { // 16-byte pieces of the 128-byte tile words - const int q = idx / (TKT * 8), kk = (idx / 8) % TKT, part = idx % 8; + for (int idx = threadIdx.x; idx < 16 * TKT * PIECES; idx += TT) { // 16-byte pieces of the tiles' words + const int q = idx / (TKT * PIECES), kk = (idx / PIECES) % TKT, part = idx % PIECES; int wm, nt; ttile(q, cb, wm, nt); - const uint32_t* src = (wm ? T1 : T0) + (((size_t)chunk * TKT + kk) * NTILES + nt) * 32 + part * 4; - cp_async16(wdst + ((size_t)q * TKT + kk) * 32 + part * 4, src, true); + const uint32_t* src = (wm ? T1 : T0) + (((size_t)chunk * TKT + kk) * NTILES + nt) * TW + part * 4; + cp_async16(wdst + ((size_t)q * TKT + kk) * TW + part * 4, src, true); } }; #pragma unroll @@ -96,7 +101,7 @@ __device__ __forceinline__ void tmain(const half* __restrict__ X0, const half* _ #pragma unroll for (int i = 0; i < TMT; ++i) { uint32_t b0[2], b1[2]; - decode_tile_p(ws + ((size_t)(warp * TMT + i) * TKT + kk) * 32, lane, b0, b1); + decode_tile_p(ws + ((size_t)(warp * TMT + i) * TKT + kk) * TW, lane, b0, b1); a[i][0] = b0[0]; a[i][1] = b1[0]; a[i][2] = b0[1]; a[i][3] = b1[1]; } #pragma unroll @@ -135,7 +140,7 @@ __device__ __forceinline__ void tspill(float* E, int ES, int col0, const float ( } } -template +template __device__ __forceinline__ void tgateup(const half* __restrict__ Xg, const half* __restrict__ Xu, const uint64_t* __restrict__ Tg, const uint64_t* __restrict__ Tu, const int* __restrict__ items, const int* __restrict__ counts, const int* __restrict__ members, const half* __restrict__ svh_g, const half* __restrict__ svh_u, const half* __restrict__ suh_d, half* __restrict__ xd, @@ -147,7 +152,7 @@ __device__ __forceinline__ void tgateup(const half* __restrict__ Xg, const half* __syncthreads(); const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31; float acc[TMT][TNB][4]; - tmain<2, XR>(Xg, Xu, Tg, Tu, rows_sh, cnt, e, K, N >> 4, cb, xdiv, reinterpret_cast(smem_raw), acc); + tmain<2, XR, K2>(Xg, Xu, Tg, Tu, rows_sh, cnt, e, K, N >> 4, cb, xdiv, reinterpret_cast(smem_raw), acc); float* Eg = reinterpret_cast(smem_raw); int mat, nt; ttile<2>(warp * TMT, cb, mat, nt); diff --git a/zig/kernels/cuda/hy4_flash/engram.cu b/zig/kernels/cuda/hy4_flash/engram.cu new file mode 100644 index 00000000000..1b0f10d43bf --- /dev/null +++ b/zig/kernels/cuda/hy4_flash/engram.cu @@ -0,0 +1,110 @@ +// Hy4-flash's Engram branch, rounded as engram.metal does; only the stock profile simulates the FP8 round trip. +#include +#include +#include +#include +#include "../common/reduce.cuh" + +namespace { +constexpr uint32_t heads = 16, head_width = 96, streams = 4, threads = 128; +// `nn.RMSNorm(eps=None)` on BF16 input uses its FP32 opmath epsilon. +constexpr float rms_epsilon = 1.1920928955078125e-07f; + +__device__ __forceinline__ float bf(float x) { return __bfloat162float(__float2bfloat16_rn(x)); } + +// E4M3FN, ties to even, subnormals, saturating at 448 (inputs are clamped first, as in the reference). +__device__ __forceinline__ float e4m3(float x) { + const __nv_fp8_storage_t code = __nv_cvt_float_to_fp8(x, __NV_SATFINITE, __NV_E4M3); + return __half2float(__half(__nv_cvt_fp8_to_halfraw(code, __NV_E4M3))); +} +} // namespace + +// One warp per (head, row): optional FP8 round trip of the gathered row, then the head's RMSNorm. +extern "C" __global__ void __launch_bounds__(32) tf_hy4_engram_lookup( + const __nv_bfloat16 *raw, const __nv_bfloat16 *gamma, __nv_bfloat16 *out, uint32_t fp8) { + const uint32_t head = blockIdx.x, lane = threadIdx.x; + const uint64_t start = (uint64_t(blockIdx.y) * heads + head) * head_width; + float x[3], maximum = 0.0f; + for (uint32_t i = 0; i < 3; ++i) { + x[i] = __bfloat162float(raw[start + lane + i * 32]); + maximum = fmaxf(maximum, fabsf(x[i])); + } + if (fp8 != 0) { + const float scale = bf(fmaxf(tf_common::warp_max(maximum), bf(1e-12f)) / 448.0f); + for (uint32_t i = 0; i < 3; ++i) { + const float code = e4m3(fminf(fmaxf(bf(x[i] / scale), -448.0f), 448.0f)); + const float quantized = bf(code * scale); + x[i] = bf(x[i] + bf(quantized - x[i])); + } + } + const float sum = tf_common::warp_sum(x[0] * x[0] + x[1] * x[1] + x[2] * x[2]); + const float inv = 1.0f / sqrtf(sum / float(head_width) + rms_epsilon); + for (uint32_t i = 0; i < 3; ++i) { + const uint32_t col = lane + 32 * i; + out[start + col] = __float2bfloat16_rn((x[i] * inv) * __bfloat162float(gamma[head * head_width + col])); + } +} + +__device__ __forceinline__ float four_warps(float v, float *parts) { + const uint32_t lane = threadIdx.x % 32, warp = threadIdx.x / 32; + v = tf_common::warp_sum(v); + if (lane == 0) parts[warp] = v; + __syncthreads(); + const float sum = (parts[0] + parts[2]) + (parts[1] + parts[3]); + __syncthreads(); + return sum; +} + +// One block per (stream, row): normed key and query, signed-sqrt gate, then state + gate*signal + scale*signal. +extern "C" __global__ void __launch_bounds__(128) tf_hy4_engram_apply( + const __nv_bfloat16 *state, const __nv_bfloat16 *keys, const __nv_bfloat16 *key_bias, + const __nv_bfloat16 *key_gain, const __nv_bfloat16 *query_gain, const __nv_bfloat16 *delta_gain, + const __nv_bfloat16 *value, const __nv_bfloat16 *value_bias, const __nv_bfloat16 *value_gain, + const uint32_t *media_mask, __nv_bfloat16 *out, uint32_t rows, uint32_t h) { + __shared__ float parts[4]; + __shared__ float gate; + const uint32_t stream = blockIdx.x, row = blockIdx.y, t = threadIdx.x; + const uint64_t base = (uint64_t(row) * streams + stream) * h; + if (media_mask[row] != 0) { + for (uint32_t j = t; j < h; j += threads) out[base + j] = state[base + j]; + return; + } + const uint64_t kbase = (uint64_t(stream) * rows + row) * h, vbase = uint64_t(row) * h; + const uint32_t gain = stream * h; + float sq_key = 0.0f, sq_query = 0.0f, sq_value = 0.0f; + for (uint32_t j = t; j < h; j += threads) { + const float k = bf(__bfloat162float(keys[kbase + j]) + __bfloat162float(key_bias[gain + j])); + const float q = __bfloat162float(state[base + j]); + const float v = bf(__bfloat162float(value[vbase + j]) + __bfloat162float(value_bias[j])); + sq_key = __fmaf_rn(k, k, sq_key); + sq_query = __fmaf_rn(q, q, sq_query); + sq_value = __fmaf_rn(v, v, sq_value); + } + const float key_sum = four_warps(sq_key, parts); + const float query_sum = four_warps(sq_query, parts); + const float value_sum = four_warps(sq_value, parts); + const float norm_key = 1.0f / sqrtf(key_sum / float(h) + rms_epsilon); + const float norm_query = 1.0f / sqrtf(query_sum / float(h) + rms_epsilon); + const float norm_value = 1.0f / sqrtf(value_sum / float(h) + rms_epsilon); + float dot = 0.0f; + for (uint32_t j = t; j < h; j += threads) { + const float k = bf(__bfloat162float(keys[kbase + j]) + __bfloat162float(key_bias[gain + j])); + const float q = __bfloat162float(state[base + j]); + const float key = bf((k * norm_key) * __bfloat162float(key_gain[gain + j])); + const float query = bf((q * norm_query) * __bfloat162float(query_gain[gain + j])); + dot += bf(key * query); + } + const float sum = four_warps(dot, parts); + if (t == 0) { + const float scaled = bf(bf(sum) * (1.0f / sqrtf(float(h)))); + const float x = scaled == 0.0f ? 0.0f : copysignf(bf(sqrtf(fmaxf(fabsf(scaled), bf(1e-6f)))), scaled); + gate = bf(1.0f / (1.0f + expf(-x))); + } + __syncthreads(); + for (uint32_t j = t; j < h; j += threads) { + const float v = bf(__bfloat162float(value[vbase + j]) + __bfloat162float(value_bias[j])); + const float signal = bf(bf(v * norm_value) * __bfloat162float(value_gain[j])); + const float delta = bf(bf(gate * signal) + bf(__bfloat162float(delta_gain[gain + j]) * signal)); + out[base + j] = __float2bfloat16_rn(__bfloat162float(state[base + j]) + delta); + } +} diff --git a/zig/kernels/cuda/hy4_flash/indexpool.cu b/zig/kernels/cuda/hy4_flash/indexpool.cu index 0e90a872779..b809408a9e1 100644 --- a/zig/kernels/cuda/hy4_flash/indexpool.cu +++ b/zig/kernels/cuda/hy4_flash/indexpool.cu @@ -30,3 +30,47 @@ extern "C" __global__ void tf_hy4_pool_groups( output[static_cast(group) * width + column] = ((projected[0] + projected[1]) + projected[2]) + projected[3]; } + +#include +#include "../common/reduce.cuh" + +// One block per closed group: FP32 value/gate projections of its 4 token keys, pooling with ape, FP32 key_norm. +extern "C" __global__ void __launch_bounds__(128) tf_hy4_index_groups( + const __nv_bfloat16 *token_keys, + const float *value_weights, + const float *gate_weights, + const float *position_bias, + const float *norm, + __nv_bfloat16 *output, + unsigned int first_group, + float epsilon) { + __shared__ float keys[4][128]; + __shared__ float scratch[32]; + const unsigned int group = first_group + blockIdx.x, column = threadIdx.x; + const unsigned long long base = static_cast(group) * 4 * 128; + #pragma unroll + for (unsigned int slot = 0; slot < 4; ++slot) keys[slot][column] = __bfloat162float(token_keys[base + slot * 128 + column]); + __syncthreads(); + float logits[4], projected[4]; + #pragma unroll + for (unsigned int slot = 0; slot < 4; ++slot) { + float value = 0.0f, gate = 0.0f; + for (unsigned int k = 0; k < 128; ++k) { + value = __fmaf_rn(keys[slot][k], value_weights[column * 128 + k], value); + gate = __fmaf_rn(keys[slot][k], gate_weights[column * 128 + k], gate); + } + projected[slot] = value; + logits[slot] = gate + position_bias[slot * 128 + column]; + } + const float maximum = fmaxf(fmaxf(logits[0], logits[1]), fmaxf(logits[2], logits[3])); + float weights[4]; + #pragma unroll + for (unsigned int slot = 0; slot < 4; ++slot) weights[slot] = expf(logits[slot] - maximum); + const float normalizer = ((weights[0] + weights[1]) + weights[2]) + weights[3]; + float pooled = 0.0f; + #pragma unroll + for (unsigned int slot = 0; slot < 4; ++slot) pooled += projected[slot] * (weights[slot] / normalizer); + const float squares = tf_common::block_sum_tree(pooled * pooled, scratch, 4); + const float inverse = rsqrtf(squares / 128.0f + epsilon); + output[static_cast(group) * 128 + column] = __float2bfloat16_rn(norm[column] * (pooled * inverse)); +} diff --git a/zig/kernels/cuda/idol_decoder.cu b/zig/kernels/cuda/idol_decoder.cu new file mode 100644 index 00000000000..c6e25a4bb4c --- /dev/null +++ b/zig/kernels/cuda/idol_decoder.cu @@ -0,0 +1,45 @@ +// Idol's decoders' own CUDA steps beside idol.cu's: each its template's BREAK 0 (the controls are the other values). +#include "idol_decoder.cuh" +#include "idol_decoder_attention.cuh" + +using tf_idol_dec::f16; + +// h [rows, 1024] fp32 = in_proj(p) + pe(p) for points p [rows, 3] fp32. +extern "C" __global__ void __launch_bounds__(256) tf_idol_dec_embed(const float* __restrict__ P, const float* __restrict__ W, + const float* __restrict__ B, const float* __restrict__ F, + float* __restrict__ Hs, int rows) { + tf_idol_dec::embed<0>(P, W, B, F, Hs, rows); +} + +// o [rows, width] fp16 = y + b by column. +extern "C" __global__ void __launch_bounds__(256) tf_idol_dec_half(const float* Y, const float* __restrict__ B, + f16* __restrict__ O, int width, int rows) { + tf_idol_dec::to_half<0>(Y, B, O, width, rows); +} + +// kv [rows, 2048] fp16 = to_kv of the fp16 latent rows [rows, 16]. +extern "C" __global__ void __launch_bounds__(256) tf_idol_dec_kv(const f16* __restrict__ X, const f16* __restrict__ W, + const f16* __restrict__ B, f16* __restrict__ KV, int rows) { + tf_idol_dec::kv<0>(X, W, B, KV, rows); +} + +// 16 heads of 64 at column `offset` of rows `stride` apart RMS-normed by gamma, in place when Y is X. +extern "C" __global__ void __launch_bounds__(256) tf_idol_dec_heads(const f16* X, const float* __restrict__ G, f16* Y, + int stride, int offset, int rows) { + tf_idol_dec::heads<0>(X, G, Y, stride, offset, rows); +} + +// o [lq, heads 64] = softmax(q k^T scale) v from query rows to key rows, P rounded to fp16 for P x V. +extern "C" __global__ void __launch_bounds__(256) tf_idol_dec_attention(const f16* __restrict__ Q, int qs, + const f16* __restrict__ KV, int ks, + f16* __restrict__ O, int lq, int lk, int heads, + float scale) { + tf_idol_dec::rows<64, 8, 0>(Q, qs, KV, ks, O, lq, lk, heads, scale); +} + +// The same for lq <= 8 query rows and lk <= 8192 keys, fp32 throughout. +extern "C" __global__ void __launch_bounds__(256) tf_idol_dec_few(const f16* __restrict__ Q, int qs, + const f16* __restrict__ KV, int ks, f16* __restrict__ O, + int lq, int lk, int heads, float scale) { + tf_idol_dec::few<0>(Q, qs, KV, ks, O, lq, lk, heads, scale); +} diff --git a/zig/kernels/cuda/idol_decoder.cuh b/zig/kernels/cuda/idol_decoder.cuh new file mode 100644 index 00000000000..85258e0618e --- /dev/null +++ b/zig/kernels/cuda/idol_decoder.cuh @@ -0,0 +1,187 @@ +// Idol's decoders' steps (idol_decoder.metal's op for op) as templates: BREAK 0 ships, `if constexpr` drops the rest. +#pragma once + +#include +#include +#include + +#include "idol_attention.cuh" + +namespace tf_idol_dec { + +typedef __half f16; + +__device__ __forceinline__ float h(float x) { return __half2float(__float2half_rn(x)); } +__device__ __forceinline__ float ld(const f16* p) { return __half2float(*p); } + +// F.normalize's clamp_min(1e-12): a NaN norm stays NaN (fmaxf would drop it). +__device__ __forceinline__ float clamp_min(float n) { return n < 1e-12f ? 1e-12f : n; } + +// h = in_proj(p) + pe(p) fp32: sin then cos of fp32(fp32(x f) pi) a axis, 4 zeros. BREAK 1: fp16 pe; 2: fp16 sums. +template +__device__ __forceinline__ void embed(const float* __restrict__ P, const float* __restrict__ W, + const float* __restrict__ B, const float* __restrict__ F, float* __restrict__ Hs, + int rows) { + const int c = blockIdx.y * 256 + threadIdx.x, r = blockIdx.x; + if (c >= 1024 || r >= rows) return; + const float x0 = P[r * 3], x1 = P[r * 3 + 1], x2 = P[r * 3 + 2]; + float s; + if constexpr (BREAK == 2) { + s = h(__fmaf_rn(h(x2), h(W[c * 3 + 2]), h(__fmaf_rn(h(x1), h(W[c * 3 + 1]), h(__fmul_rn(h(x0), h(W[c * 3]))))))); + } else { + s = __fmaf_rn(x2, W[c * 3 + 2], __fmaf_rn(x1, W[c * 3 + 1], __fmul_rn(x0, W[c * 3]))); + } + s = __fadd_rn(s, B[c]); + float pe = 0.0f; + if (c < 1020) { + const int a = c / 340, j = c % 340; + const float x = a == 0 ? x0 : (a == 1 ? x1 : x2); + const float ang = __fmul_rn(__fmul_rn(x, F[j % 170]), 3.14159265358979323846f); + pe = j < 170 ? sinf(ang) : cosf(ang); + if constexpr (BREAK == 1) pe = h(pe); + } + Hs[(size_t)r * 1024 + c] = __fadd_rn(s, pe); +} + +// o = fp16(y + b) by column, an fp32 Linear's bias then the blocks' cast. BREAK 1: fp16 y first; 2: writes its input. +template +__device__ __forceinline__ void to_half(const float* Y, const float* __restrict__ B, f16* __restrict__ O, int width, + int rows) { + const int c = blockIdx.y * 256 + threadIdx.x, r = blockIdx.x; + if (c >= width || r >= rows) return; + const size_t i = (size_t)r * width + c; + const float y = BREAK == 1 ? h(Y[i]) : Y[i]; + O[i] = __float2half_rn(__fadd_rn(y, B[c])); + if constexpr (BREAK == 2) const_cast(Y)[i] = 0.0f; +} + +// kv [rows, 2048] = fp16(ctx w^T + b), fp32 FMA sums of the fp16 latent. BREAK 1: fp16 ctx w first; 2: fp16 sums. +template +__device__ __forceinline__ void kv(const f16* __restrict__ X, const f16* __restrict__ W, const f16* __restrict__ B, + f16* __restrict__ KV, int rows) { + const int c = blockIdx.y * 256 + threadIdx.x, r = blockIdx.x; + if (c >= 2048 || r >= rows) return; + float s = 0.0f; +#pragma unroll + for (int k = 0; k < 16; ++k) { + s = __fmaf_rn(ld(X + r * 16 + k), ld(W + c * 16 + k), s); + if constexpr (BREAK == 2) s = h(s); + } + if constexpr (BREAK == 1) s = h(s); + KV[(size_t)r * 2048 + c] = __float2half_rn(__fadd_rn(s, ld(B + c))); +} + +// MultiHeadRMSNorm in fp32 of 16 heads at `offset`, a warp a head, Y may be X. BREAK 1: fmaxf; 2: fp16 x / n; 3: sums. +template +__device__ __forceinline__ void heads(const f16* X, const float* __restrict__ G, f16* Y, int stride, int offset, + int rows) { + const int r = blockIdx.x, hd = blockIdx.y * 8 + (threadIdx.x >> 5), lane = threadIdx.x & 31; + if (hd >= 16 || r >= rows) return; + const size_t at = (size_t)r * stride + offset + hd * 64 + lane * 2; + const float a0 = ld(X + at), a1 = ld(X + at + 1); + float sq = __fadd_rn(__fmul_rn(a0, a0), __fmul_rn(a1, a1)); + if constexpr (BREAK == 3) sq = h(sq); +#pragma unroll + for (int o = 16; o > 0; o >>= 1) { + sq = __fadd_rn(sq, __shfl_xor_sync(0xffffffffu, sq, o)); + if constexpr (BREAK == 3) sq = h(sq); + } + const float len = __fsqrt_rn(sq); + const float n = BREAK == 1 ? fmaxf(len, 1e-12f) : clamp_min(len); + float q0 = __fdiv_rn(a0, n), q1 = __fdiv_rn(a1, n); + if constexpr (BREAK == 2) { + q0 = h(q0); + q1 = h(q1); + } + const int g = hd * 64 + lane * 2; + Y[at] = __float2half_rn(__fmul_rn(__fmul_rn(q0, G[g]), 8.0f)); + Y[at + 1] = __float2half_rn(__fmul_rn(__fmul_rn(q1, G[g + 1]), 8.0f)); +} + +// lq <= 8 queries, lk <= 8192 keys in fp32 as the cases' MPS kernel; a block a row and head. BREAK 1: fp16 P; 2: sums. +template +__device__ __forceinline__ void few(const f16* __restrict__ Q, int qs, const f16* __restrict__ KV, int ks, + f16* __restrict__ O, int lq, int lk, int heads, float scale) { + __shared__ float q[64]; + __shared__ float part[8][64]; + __shared__ float red[9]; + const int r = blockIdx.x, hd = blockIdx.y, t = threadIdx.x, lane = t & 31, w = t >> 5; + if (r >= lq) return; + if (t < 64) q[t] = __fmul_rn(ld(Q + (size_t)r * qs + hd * 64 + t), scale); + __syncthreads(); + const f16* kh = KV + hd * 64; + const f16* vh = KV + (heads + hd) * 64; + float s[32]; + float top = -INFINITY; +#pragma unroll + for (int i = 0; i < 32; ++i) { + const int j = t + i * 256; + s[i] = -INFINITY; + if (j >= lk) continue; + const __half2* kr = reinterpret_cast(kh + (size_t)j * ks); + float d = 0.0f; +#pragma unroll + for (int c = 0; c < 32; ++c) { + const float2 kv2 = __half22float2(kr[c]); + d = __fmaf_rn(q[2 * c], kv2.x, __fmaf_rn(q[2 * c + 1], kv2.y, d)); + } + s[i] = d; + top = fmaxf(top, d); + } +#pragma unroll + for (int o = 16; o > 0; o >>= 1) top = fmaxf(top, __shfl_xor_sync(0xffffffffu, top, o)); + if (lane == 0) red[w] = top; + __syncthreads(); + if (t == 0) { + float m = red[0]; + for (int i = 1; i < 8; ++i) m = fmaxf(m, red[i]); + red[8] = m; + } + __syncthreads(); + top = red[8]; + float o[64]; +#pragma unroll + for (int c = 0; c < 64; ++c) o[c] = 0.0f; + float sum = 0.0f; +#pragma unroll + for (int i = 0; i < 32; ++i) { + const int j = t + i * 256; + if (j >= lk) continue; + float e = expf(__fsub_rn(s[i], top)); + if constexpr (BREAK == 1) e = h(e); + sum = __fadd_rn(sum, e); + const __half2* vr = reinterpret_cast(vh + (size_t)j * ks); +#pragma unroll + for (int c = 0; c < 32; ++c) { + const float2 v2 = __half22float2(vr[c]); + o[2 * c] = __fmaf_rn(e, v2.x, o[2 * c]); + o[2 * c + 1] = __fmaf_rn(e, v2.y, o[2 * c + 1]); + if constexpr (BREAK == 2) { + o[2 * c] = h(o[2 * c]); + o[2 * c + 1] = h(o[2 * c + 1]); + } + } + } + __syncthreads(); +#pragma unroll + for (int x = 16; x > 0; x >>= 1) sum = __fadd_rn(sum, __shfl_xor_sync(0xffffffffu, sum, x)); + if (lane == 0) red[w] = sum; +#pragma unroll + for (int c = 0; c < 64; ++c) { + float v = o[c]; +#pragma unroll + for (int x = 16; x > 0; x >>= 1) v = __fadd_rn(v, __shfl_xor_sync(0xffffffffu, v, x)); + if (lane == 0) part[w][c] = v; + } + __syncthreads(); + if (t < 64) { + float total = 0.0f, acc = 0.0f; + for (int i = 0; i < 8; ++i) { + total = __fadd_rn(total, red[i]); + acc = __fadd_rn(acc, part[i][t]); + } + O[(size_t)r * heads * 64 + hd * 64 + t] = __float2half_rn(__fdiv_rn(acc, total)); + } +} + +} // namespace tf_idol_dec diff --git a/zig/kernels/cuda/idol_decoder_attention.cuh b/zig/kernels/cuda/idol_decoder_attention.cuh new file mode 100644 index 00000000000..68ddf8de2da --- /dev/null +++ b/zig/kernels/cuda/idol_decoder_attention.cuh @@ -0,0 +1,151 @@ +// The decoders' tiled attention: full's row arithmetic (P to nearest fp16 for P V), queries to other keys. +#pragma once + +#include "idol_attention.cuh" +#include "idol_decoder.cuh" + +namespace tf_idol_dec { + +using tf_idol_attn::BN; +using tf_idol_attn::mma; +using tf_idol_attn::mma0; +using tf_idol_attn::pack; +using tf_idol_attn::rowsum; +using tf_idol_attn::tdiv; +using tf_idol_attn::texp; + +// o [LQ, HO D] = softmax(q k^T scale) v, v at column (HO + h) D of k's rows. BREAK 1: keys past LK kept; 2: fp16 P V. +template +__device__ __forceinline__ void rows(const __half* __restrict__ qp, int qs, const __half* __restrict__ kvp, int ks, + __half* __restrict__ out, int LQ, int LK, 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 = LK - 1, tiles = (LK + BN - 1) / BN; + const __half* __restrict__ q = qp + head * D; + const __half* __restrict__ kc = kvp + head * D; + const __half* __restrict__ vc = kvp + (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 < LK; + qmm_frag::cp16z(dst + (kv * BN + r) * RS + c, (kv ? vc : kc) + (int64_t)(in ? key : 0) * ks + c * 8, in); + } + qmm_frag::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, LQ - 1) * qs); + const uint32_t* q1 = reinterpret_cast(q + (int64_t)min(r1, LQ - 1) * qs); +#pragma unroll + for (int k = 0; k < K16; ++k) { + qa[k][0] = r0 < LQ ? q0[8 * k + qd] : 0u; + qa[k][1] = r1 < LQ ? q1[8 * k + qd] : 0u; + qa[k][2] = r0 < LQ ? q0[8 * k + qd + 4] : 0u; + qa[k][3] = r1 < LQ ? 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) { + qmm_frag::wait<0>(); + __syncthreads(); // tile t landed, and every warp is done with tile t - 1 + if (t + 1 < tiles) stage(t + 1); + const uint4* kt = smem + (t & 1) * 2 * BN * RS; + const uint4* vt = kt + 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]; + qmm_frag::ldmatrix4(b, kt + (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]); + } + } + } + // keys past LK: their K rows read as zeros, so unmasked (BREAK 1) they score 0 and join the softmax + const int kb = t * BN + 2 * qd, end = BREAK == 1 ? tiles * BN - 1 : last; + float tm0 = -INFINITY, tm1 = -INFINITY; +#pragma unroll + for (int n = 0; n < NT; ++n) { + const int c = kb + 8 * n; + sc[n][0] = c <= end ? __fmul_rn(sc[n][0], scale) : -INFINITY; + sc[n][1] = c + 1 <= end ? __fmul_rn(sc[n][1], scale) : -INFINITY; + sc[n][2] = c <= end ? __fmul_rn(sc[n][2], scale) : -INFINITY; + sc[n][3] = c + 1 <= end ? __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 <= end ? texp(__fsub_rn(sc[n][0], n0)) : 0.0f; + sc[n][1] = act0 && c + 1 <= end ? texp(__fsub_rn(sc[n][1], n0)) : 0.0f; + sc[n][2] = act1 && c <= end ? texp(__fsub_rn(sc[n][2], n1)) : 0.0f; + sc[n][3] = act1 && c + 1 <= end ? 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]; + qmm_frag::ldmatrix4t(b, vt + (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]); + if constexpr (BREAK == 2) { +#pragma unroll + for (int e = 0; e < 4; ++e) { + o[i][e] = h(o[i][e]); + o[i + 1][e] = h(o[i + 1][e]); + } + } + } + } + } +#pragma unroll + for (int i = 0; i < C; ++i) { + const int d = 8 * i + 2 * qd; + if (r0 < LQ) + *reinterpret_cast(out + ((int64_t)r0 * HO + head) * D + d) = pack(tdiv(o[i][0], l0), tdiv(o[i][1], l0)); + if (r1 < LQ) + *reinterpret_cast(out + ((int64_t)r1 * HO + head) * D + d) = pack(tdiv(o[i][2], l1), tdiv(o[i][3], l1)); + } +} + +} // namespace tf_idol_dec diff --git a/zig/kernels/cuda/inkling2/ops.cu b/zig/kernels/cuda/inkling2/ops.cu new file mode 100644 index 00000000000..2e26fc6892c --- /dev/null +++ b/zig/kernels/cuda/inkling2/ops.cu @@ -0,0 +1,598 @@ +// Inkling 2 glue: embedding, block attention-residual mix, row dots, router top-k, softcapped SwiGLU, short convs. +#include +#include +#include +#include + +#include "exl3_decode.cuh" + +namespace ink2o { + +constexpr int kMaxBlocks = 8; +constexpr int kMaxQueries = 3; +constexpr int kConvTaps = 4; +constexpr int kMixCache = 10; // tf_ink2_mix holds a row of up to kMixCache x blockDim columns in registers + +__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; +} + +// Sums of N values over the block in a fixed order: warp shuffles, then warp 0 over the warps' 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) { + float t = lane < nw ? sh[i * 32 + lane] : 0.0f; + v[i] = __shfl_sync(0xffffffffu, warpSum(t), 0); + } +} + +} // namespace ink2o + +using namespace ink2o; + +// Per row: the embedding row times rsqrt(mean square + eps) times the norm weight, one bf16 round (embed_norm). +extern "C" __global__ void __launch_bounds__(256) tf_ink2_embed(const int* __restrict__ ids, const uint16_t* __restrict__ table, + const uint16_t* __restrict__ w, uint16_t* __restrict__ out, + int C, float eps) { + __shared__ float sh[32]; + const size_t row = blockIdx.x; + const uint16_t* e = table + static_cast(ids[row]) * C; + float s[1] = {0.0f}; + for (int c = threadIdx.x; c < C; c += blockDim.x) s[0] += bf(e[c]) * bf(e[c]); + blockSums<1>(s, sh); + const float r = rsqrtf(s[0] / C + eps); + for (int c = threadIdx.x; c < C; c += blockDim.x) out[row * C + c] = tobf(bf(w[c]) * (bf(e[c]) * r)); +} + +// The block attention-residual mix (Inkling2BlockAttentionResidual) and the norm after it, per row and query. +struct MixArgs { + const uint16_t* blocks[kMaxBlocks]; // bf16 [rows, C] each: the completed blocks' inputs + const void* partial; // [rows, C]: bf16 when partial_bf16, else fp32 + const float* query; // fp32 [nq, C]; null: no mix, the partial alone (layer 0's attention) + const uint16_t* norm[kMaxQueries]; // bf16 [C] per query: the RMSNorm after the mix + uint16_t* out; // bf16 [nq, rows, C] + int n_blocks, partial_bf16, nq, rows, C; + float eps; +}; + +constexpr int kMixStage = 4, kMixCols = kMixStage * 512; // tf_ink2_mix: slices of 512 columns staged at a time + +__device__ __forceinline__ void mixStage(const MixArgs& a, size_t row, int c0, uint16_t (*sb)[kMixCols], unsigned char* sp) { + const int cols = min(kMixCols, a.C - c0); // a multiple of 8: C % 128 == 0 (ops.zig) + const int chunks = cols / 8; // 16 bytes of bf16 a chunk + for (int j = 0; j < a.n_blocks; ++j) + for (int i = threadIdx.x; i < chunks; i += blockDim.x) + __pipeline_memcpy_async(&sb[j][i * 8], a.blocks[j] + row * a.C + c0 + i * 8, 16); + const int pe = a.partial_bf16 ? 2 : 4; + const unsigned char* p = static_cast(a.partial) + (row * a.C + c0) * pe; + for (int i = threadIdx.x; i < cols * pe / 16; i += blockDim.x) __pipeline_memcpy_async(sp + i * 16, p + i * 16, 16); + __pipeline_commit(); // one memory round trip a slice instead of one a block + __pipeline_wait_prior(0); + __syncthreads(); +} + +// Narrow calls (decode rows): staged slices; the same sums in the same order as tf_ink2_mix_rows. +extern "C" __global__ void __launch_bounds__(512) tf_ink2_mix(const MixArgs a) { + constexpr int kV = (kMaxBlocks + 1) * (1 + kMaxQueries); + __shared__ float sh[32 * kV]; + __shared__ float wts[kMaxQueries][kMaxBlocks + 1]; + __shared__ float rr[kMaxBlocks + 1]; + __shared__ __align__(16) uint16_t sb[kMaxBlocks][kMixCols]; + __shared__ __align__(16) unsigned char sp[kMixCols * 4]; + const size_t row = blockIdx.x; + const int C = a.C, n = a.n_blocks + 1; + // block j's column c, staged: thread t reads only the columns t + 512 k it adds, in the order the sums always took + auto entry = [&](int j, int i) -> float { + if (j < a.n_blocks) return bf(sb[j][i]); + 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]; +#pragma unroll + for (int i = 0; i < kV; ++i) v[i] = 0.0f; + 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) { + const int c = c0 + i; + float qc[kMaxQueries]; +#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; +#pragma unroll + for (int q = 0; q < kMaxQueries; ++q) + if (q < a.nq) v[j * (1 + kMaxQueries) + 1 + q] += x * qc[q]; + } + } + } + __syncthreads(); // the next slice overwrites the staged one + } + 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)); + } + __syncthreads(); + if (threadIdx.x < a.nq) { + float* l = wts[threadIdx.x]; + float m = -INFINITY, t = 0.0f; + for (int j = 0; j < n; ++j) m = fmaxf(m, l[j]); + for (int j = 0; j < n; ++j) t += expf(l[j] - m); + for (int j = 0; j < n; ++j) l[j] = expf(l[j] - m) / t; + } + __syncthreads(); + } + // every query's mixed row kept in registers (C <= kMixCache x blockDim, ops.zig): read once, normed, written + float s[kMaxQueries] = {0.0f, 0.0f, 0.0f}; + float hc[kMaxQueries][kMixCache]; +#pragma unroll + for (int k = 0; k < kMixCache; ++k) { + const int c = threadIdx.x + k * 512; + if (k % kMixStage == 0) { + if (k > 0) __syncthreads(); + if (k * 512 < C) mixStage(a, row, k * 512, sb, sp); + } + const int i = threadIdx.x + (k % kMixStage) * 512; + float h[kMaxQueries] = {0.0f, 0.0f, 0.0f}; + if (c < C) { + if (a.query) { +#pragma unroll + for (int j = 0; j < kMaxBlocks + 1; ++j) + if (j < n) { + const float x = entry(j, i); +#pragma unroll + for (int q = 0; q < kMaxQueries; ++q) + if (q < a.nq) h[q] += wts[q][j] * (x * rr[j]); + } + } else { + h[0] = entry(a.n_blocks, i); + } + } +#pragma unroll + for (int q = 0; q < kMaxQueries; ++q) { + s[q] += h[q] * h[q]; // rows past C add 0.0f * 0.0f: the sums keep their bits + hc[q][k] = h[q]; + } + } + blockSums(s, sh); +#pragma unroll + for (int q = 0; q < kMaxQueries; ++q) { + if (q >= a.nq) break; + const float r = rsqrtf(s[q] / C + a.eps); + uint16_t* o = a.out + (static_cast(q) * a.rows + row) * C; +#pragma unroll + for (int k = 0; k < kMixCache; ++k) { + const int c = threadIdx.x + k * 512; + if (c < C) o[c] = tobf(bf(a.norm[q][c]) * (hc[q][k] * r)); + } + } +} + +// Wide calls (prompt chunks, wide verifies): the block-by-block mix, which hides its loads behind other rows. +extern "C" __global__ void __launch_bounds__(512) tf_ink2_mix_rows(const MixArgs 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 C = a.C, n = a.n_blocks + 1; + auto entry = [&](int j, int c) -> float { + if (j < a.n_blocks) return bf(a.blocks[j][row * C + c]); + return a.partial_bf16 ? bf(static_cast(a.partial)[row * C + c]) + : static_cast(a.partial)[row * C + c]; + }; + if (a.query) { + for (int j = 0; j < n; ++j) { + float v[1 + kMaxQueries] = {0.0f, 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)); + } + } + __syncthreads(); + if (threadIdx.x < a.nq) { + float* l = wts[threadIdx.x]; + float m = -INFINITY, t = 0.0f; + for (int j = 0; j < n; ++j) m = fmaxf(m, l[j]); + for (int j = 0; j < n; ++j) t += expf(l[j] - m); + for (int j = 0; j < n; ++j) l[j] = expf(l[j] - m) / t; + } + __syncthreads(); + } + for (int q = 0; q < a.nq; ++q) { + float s[1] = {0.0f}; + for (int c = threadIdx.x; c < C; c += blockDim.x) { + float h = 0.0f; + if (a.query) + for (int j = 0; j < n; ++j) h += wts[q][j] * (entry(j, c) * rr[j]); + else + h = entry(a.n_blocks, c); + s[0] += h * h; + } + blockSums<1>(s, sh); + const float r = rsqrtf(s[0] / C + a.eps); + uint16_t* o = a.out + (static_cast(q) * a.rows + row) * C; + for (int c = threadIdx.x; c < C; c += blockDim.x) { + float h = 0.0f; + if (a.query) + for (int j = 0; j < n; ++j) h += wts[q][j] * (entry(j, c) * rr[j]); + else + h = entry(a.n_blocks, c); + o[c] = tobf(bf(a.norm[q][c]) * (h * r)); + } + } +} + +// out[row, j] = x[row, :] . W[j, :] in fp32 (bf16 inputs), a warp an output; act 1 takes the sigmoid; bf16 or fp32 out. +extern "C" __global__ void __launch_bounds__(256) tf_ink2_rowdot(const uint16_t* __restrict__ x, const uint16_t* __restrict__ W, + void* __restrict__ out, int J, int C, int out_bf16, int act) { + const int lane = threadIdx.x & 31, j = blockIdx.y * 8 + (threadIdx.x >> 5); + if (j >= J) return; + const size_t row = blockIdx.x; + const uint16_t* xr = x + row * C; + const uint16_t* wr = W + static_cast(j) * C; + float s = 0.0f; + for (int c = lane; c < C; c += 32) s += bf(xr[c]) * bf(wr[c]); + s = warpSum(s); + if (lane != 0) return; + if (act == 1) s = 1.0f / (1.0f + expf(-s)); + if (out_bf16) + static_cast(out)[row * J + j] = tobf(s); + else + static_cast(out)[row * J + j] = s; +} + +// Router picks per row: top-K of score + bias (ties to the lower id), weights score / sum(scores) * scale (fp32). +extern "C" __global__ void __launch_bounds__(512) tf_ink2_topk(const float* __restrict__ scores, const float* __restrict__ bias, + int* __restrict__ pick, float* __restrict__ wts, int E, int K, + float scale) { + __shared__ float bv[16]; + __shared__ int bi[16]; + __shared__ float chosen[32]; + __shared__ int chosen_id[32]; + const size_t row = blockIdx.x; + const int lane = threadIdx.x & 31, w = threadIdx.x >> 5, nw = blockDim.x >> 5; + float sel[8]; + const int per = (E + blockDim.x - 1) / blockDim.x; + for (int i = 0; i < per && i < 8; ++i) { + const int e = threadIdx.x + i * blockDim.x; + sel[i] = e < E ? scores[row * E + e] + bias[e] : -INFINITY; + } + for (int k = 0; k < K; ++k) { + float v = -INFINITY; + int id = 0x7fffffff; + for (int i = 0; i < per && i < 8; ++i) { + const int e = threadIdx.x + i * blockDim.x; + if (e < E && (sel[i] > v || (sel[i] == v && e < id))) { v = sel[i]; id = e; } + } + for (int o = 16; o > 0; o >>= 1) { + const float ov = __shfl_xor_sync(0xffffffffu, v, o); + const int oi = __shfl_xor_sync(0xffffffffu, id, o); + if (ov > v || (ov == v && oi < id)) { v = ov; id = oi; } + } + if (lane == 0) { bv[w] = v; bi[w] = id; } + __syncthreads(); + if (threadIdx.x == 0) { + float m = bv[0]; + int mi = bi[0]; + for (int i = 1; i < nw; ++i) + if (bv[i] > m || (bv[i] == m && bi[i] < mi)) { m = bv[i]; mi = bi[i]; } + chosen_id[k] = mi; + chosen[k] = scores[row * E + mi]; + } + __syncthreads(); + const int got = chosen_id[k]; + if (got % blockDim.x == static_cast(threadIdx.x)) sel[got / blockDim.x] = -INFINITY; + __syncthreads(); + } + if (threadIdx.x == 0) { + float t = 0.0f; + for (int k = 0; k < K; ++k) t += chosen[k]; + for (int k = 0; k < K; ++k) { + pick[row * K + k] = chosen_id[k]; + wts[row * K + k] = chosen[k] / (t + 1e-20f) * scale; + } + } +} + +// The shared gate/up epilogue with Inkling's softcapped SwiGLU: gcap tanh(g/gcap) sigmoid(g) ucap tanh(u/ucap). +struct GateUpArgs { + const float* z; // [(mat * sk + split) * P + p] * N + col + const int* pick; // int32 [P] + const half* svh_g; // fp16 [E, N] + const half* svh_u; // fp16 [E, N] + const half* suh_d; // fp16 [E, N] + half* xd; // fp16 [P, N] + int p, n, sk, experts; + float gate_cap, up_cap; +}; + +extern "C" __global__ void tf_ink2_gateup(const GateUpArgs a) { + using namespace tf_exl3; + const int p = blockIdx.x, blk = blockIdx.y; + const int e = a.pick[p]; + if (e < 0 || e >= a.experts) return; + const int lane = threadIdx.x; + const int n = blk * 128 + 4 * lane; + float gv[4], uv[4]; +#pragma unroll + for (int j = 0; j < 4; ++j) { + float sg = 0.f, su = 0.f; + for (int s = 0; s < a.sk; ++s) { + sg += a.z[((size_t)(0 * a.sk + s) * a.p + p) * a.n + n + j]; + su += a.z[((size_t)(1 * a.sk + s) * a.p + p) * a.n + n + j]; + } + gv[j] = sg; + uv[j] = su; + } + fwht128(gv, lane); + fwht128(uv, lane); + float v[4]; +#pragma unroll + for (int j = 0; j < 4; ++j) { + const float g = gv[j] * HAD_SCALE * __half2float(a.svh_g[(size_t)e * a.n + n + j]); + const float u = uv[j] * HAD_SCALE * __half2float(a.svh_u[(size_t)e * a.n + n + j]); + const float act = a.gate_cap * tanhf(g / a.gate_cap) * (1.f / (1.f + expf(-g))) * a.up_cap * tanhf(u / a.up_cap); + v[j] = act * __half2float(a.suh_d[(size_t)e * a.n + n + j]); + } + fwht128(v, lane); + half* o = a.xd + (size_t)p * a.n + n; +#pragma unroll + for (int j = 0; j < 4; ++j) o[j] = __float2half_rn(v[j] * HAD_SCALE); +} + +// Short causal conv over a stream's rows (4 taps, last 3 inputs in `state`): static [C][4] or dynamic [4][C] + dyn. +struct ConvArgs { + const void* x; // [rows, C]: fp32 (`parts` rank partials, part_stride apart, added in rank order) or bf16 + float* state; // fp32 [3, C], oldest first + const uint16_t* w; // bf16 taps + const float* dyn; // fp32 [rows, heads * 4] or null + const uint16_t* base; // bf16 [rows, C] (mode 1, null: zero) + float* resid; // fp32 [rows, C] (modes 1 and 2) + uint16_t* out; // bf16 [rows, C] (modes 0 and 2) + const int4* segs; // per stream (blockIdx.y): row0, rows, state slot; null: one stream, all rows + float* hist; // fp32 [rows, C]: each row's input as the state keeps it (null: none) + long long part_stride; + long long state_stride; // elements between the streams' states + int parts, x_bf16, round_in, heads, C, rows, mode; // mode 0: out = y; 1: resid = base + bf16(y); 2: resid + bf16(y) +}; + +// Rows in blocks of 32 (z), each from its three prior inputs recomputed (same bits); block 0 owns the state. +extern "C" __global__ void __launch_bounds__(128) tf_ink2_conv(const ConvArgs a) { + const int c = blockIdx.x * blockDim.x + threadIdx.x; + const int C = a.C, r0 = blockIdx.z * 32, hd = a.dyn ? c / (C / a.heads) : 0; + const int4 sg = a.segs ? a.segs[blockIdx.y] : make_int4(0, a.rows, 0, 0); + if (c >= C || r0 >= sg.y) return; + float* state = a.state + sg.z * a.state_stride; + const auto input = [&](int t) { + const size_t at = static_cast(t) * C + c; + float x = a.x_bf16 ? bf(static_cast(a.x)[at]) : static_cast(a.x)[at]; + for (int r = 1; r < a.parts; ++r) x += static_cast(a.x)[at + r * a.part_stride]; + return a.round_in ? bfr(x) : x; + }; + const int t0 = sg.x + r0, t1 = sg.x + min(sg.y, r0 + 32), end = sg.x + sg.y; + float h0 = r0 == 0 ? state[c] : input(t0 - 3), h1 = r0 == 0 ? state[C + c] : input(t0 - 2); + float h2 = r0 == 0 ? state[2 * C + c] : input(t0 - 1); + for (int t = t0; t < t1; ++t) { + const size_t at = static_cast(t) * C + c; + const float x = input(t); + float y; + if (a.hist) a.hist[at] = x; + if (a.dyn) { + const float* d = a.dyn + (static_cast(t) * a.heads + hd) * kConvTaps; + y = (bf(a.w[c]) + d[0]) * x + (bf(a.w[C + c]) + d[1]) * h2; + y += (bf(a.w[2 * C + c]) + d[2]) * h1; + y += (bf(a.w[3 * C + c]) + d[3]) * h0; + y = (y + x) / 3.0f; + } else { + const uint16_t* w = a.w + static_cast(c) * kConvTaps; + y = bf(w[0]) * h0 + bf(w[1]) * h1; + y += bf(w[2]) * h2; + y += bf(w[3]) * x; + y = (y + x) / 2.2360679774997896f; + } + if (a.mode == 0) a.out[at] = tobf(y); + else if (a.mode == 1) a.resid[at] = (a.base ? bf(a.base[at]) : 0.0f) + bfr(y); + else a.out[at] = tobf(a.resid[at] + bfr(y)); + h0 = h1, h1 = h2, h2 = x; + } + if (r0 != 0) return; + const bool last = t1 == end; // else the stream's last three inputs, recomputed + state[c] = last ? h0 : input(end - 3); + state[C + c] = last ? h1 : input(end - 2); + state[2 * C + c] = last ? h2 : input(end - 1); +} + +// A conv site of every slot: slot 0's state, its C, and byte offsets of its rows in a hist and in a slot's backup. +struct RewindSite { + float* state; + long long hist, backup; + int C, pad; +}; + +// A window keeps its first n rows: each site's state becomes the last 3 of (backup's 3 inputs, rows' inputs from hist). +extern "C" __global__ void __launch_bounds__(128) tf_ink2_conv_rewind(const RewindSite* __restrict__ sites, const char* backup, + const char* hist, int slot, int row0, int n) { + const RewindSite s = sites[blockIdx.y]; + const int c = blockIdx.x * blockDim.x + threadIdx.x; + if (c >= s.C) return; + const int C = s.C; + const float* b = reinterpret_cast(backup + s.backup); + const float* x = reinterpret_cast(hist + s.hist) + static_cast(row0) * C; + float* st = s.state + static_cast(slot) * 3 * C; +#pragma unroll + for (int k = 0; k < 3; ++k) { + const int i = n - 3 + k; + st[k * C + c] = i < 0 ? b[(3 + i) * C + c] : x[static_cast(i) * C + c]; + } +} + +// The final logit softcap in place: x = tanh(x / cap) * cap. +extern "C" __global__ void tf_ink2_softcap(float* __restrict__ x, long long n, float cap) { + const long long i = static_cast(blockIdx.x) * blockDim.x + threadIdx.x; + if (i < n) x[i] = tanhf(x[i] / cap) * cap; +} + +namespace ink2o { + +__device__ __forceinline__ bool better(float v, int i, float bv, int bi) { return v > bv || (v == bv && i < bi); } + +} // namespace ink2o + +// Each row's greedy pick over its first n fp32 columns: the largest value, the lowest id among equals, plus base. +extern "C" __global__ void __launch_bounds__(1024) tf_ink2_top1(const float* __restrict__ x, long long stride, int n, + int base, float* __restrict__ val, int* __restrict__ id) { + using namespace ink2o; + __shared__ float sv[32]; + __shared__ int si[32]; + const float* r = x + static_cast(blockIdx.x) * stride; + float bv = -INFINITY; + int bi = 0x7fffffff; + for (int i = threadIdx.x; i < n; i += blockDim.x) { + if (better(r[i], i, bv, bi)) { + bv = r[i]; + bi = i; + } + } + for (int o = 16; o > 0; o >>= 1) { + const float ov = __shfl_xor_sync(0xffffffffu, bv, o); + const int oi = __shfl_xor_sync(0xffffffffu, bi, o); + if (better(ov, oi, bv, bi)) { + bv = ov; + bi = oi; + } + } + const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31; + if (lane == 0) { + sv[warp] = bv; + si[warp] = bi; + } + __syncthreads(); + if (warp != 0) return; + const int nw = blockDim.x >> 5; + bv = lane < nw ? sv[lane] : -INFINITY; + bi = lane < nw ? si[lane] : 0x7fffffff; + for (int o = 16; o > 0; o >>= 1) { + const float ov = __shfl_xor_sync(0xffffffffu, bv, o); + const int oi = __shfl_xor_sync(0xffffffffu, bi, o); + if (better(ov, oi, bv, bi)) { + bv = ov; + bi = oi; + } + } + if (lane == 0) { + val[blockIdx.x] = bv; + id[blockIdx.x] = (bi == 0x7fffffff ? 0 : bi) + base; + } +} + +namespace ink2r { + +// sample.cu's keys, unchanged: a draft raced with them lands on the token a keyed draw at that position would take +__device__ __forceinline__ unsigned long long mix(unsigned long long x) { + x ^= x >> 30; + x *= 0xBF58476D1CE4E5B9ull; + x ^= x >> 27; + x *= 0x94D049BB133111EBull; + return x ^ (x >> 31); +} + +__device__ __forceinline__ float race_uniform(unsigned long long seed, unsigned pos, unsigned id) { + unsigned long long x = mix(seed + 0x9E3779B97F4A7C15ull); + x = mix(x ^ (static_cast(pos) * 0xD1B54A32D192ED03ull)); + x = mix(x ^ static_cast(id)); + const float u = (static_cast(static_cast(x >> 40)) + 0.5f) * (1.0f / 16777216.0f); + return fminf(u, __uint_as_float(0x3F7FFFFFu)); +} + +} // namespace ink2r + +// One fp32 row's Gumbel race at `pos` under sample.cu's keys (ids base + i): the best score and its id. +extern "C" __global__ void __launch_bounds__(1024) tf_ink2_race1(const float* __restrict__ x, int n, int base, + unsigned long long seed, float inv_t, unsigned pos, + float* __restrict__ val, int* __restrict__ id) { + using namespace ink2o; + __shared__ float sv[32]; + __shared__ int si[32]; + float bv = -INFINITY; + int bi = 0x7fffffff; + for (int i = threadIdx.x; i < n; i += blockDim.x) { + const float v = bfr(x[i]) * inv_t - logf(-logf(ink2r::race_uniform(seed, pos, static_cast(base + i)))); + if (better(v, i, bv, bi)) { + bv = v; + bi = i; + } + } + for (int o = 16; o > 0; o >>= 1) { + const float ov = __shfl_xor_sync(0xffffffffu, bv, o); + const int oi = __shfl_xor_sync(0xffffffffu, bi, o); + if (better(ov, oi, bv, bi)) { + bv = ov; + bi = oi; + } + } + const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31; + if (lane == 0) { + sv[warp] = bv; + si[warp] = bi; + } + __syncthreads(); + if (warp != 0) return; + bv = lane < static_cast(blockDim.x >> 5) ? sv[lane] : -INFINITY; + bi = lane < static_cast(blockDim.x >> 5) ? si[lane] : 0x7fffffff; + for (int o = 16; o > 0; o >>= 1) { + const float ov = __shfl_xor_sync(0xffffffffu, bv, o); + const int oi = __shfl_xor_sync(0xffffffffu, bi, o); + if (better(ov, oi, bv, bi)) { + bv = ov; + bi = oi; + } + } + if (lane == 0) { + val[0] = bv; + id[0] = (bi == 0x7fffffff ? 0 : bi) + base; + } +} + +// fp32 logits rows into bf16 whole rows at column col0: the first n columns rounded, the rest of `width` -inf. +extern "C" __global__ void tf_ink2_tobf(const float* __restrict__ x, long long stride, int n, uint16_t* __restrict__ out, + long long out_stride, long long col0, int width) { + using namespace ink2o; + const int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i >= width) return; + const size_t row = blockIdx.y; + out[row * out_stride + col0 + i] = i < n ? tobf(x[row * stride + i]) : static_cast(0xff80u); +} + +// A link step's words (header and ids) written to the device buffer every rank broadcasts from. +struct Ink2Words { + unsigned w[96]; +}; + +extern "C" __global__ void tf_ink2_put_words(unsigned* __restrict__ dst, int n, const Ink2Words words) { + const int i = threadIdx.x; + if (i < n) dst[i] = words.w[i]; +} diff --git a/zig/kernels/cuda/inkling2/rows.cu b/zig/kernels/cuda/inkling2/rows.cu new file mode 100644 index 00000000000..cb29302c006 --- /dev/null +++ b/zig/kernels/cuda/inkling2/rows.cu @@ -0,0 +1,83 @@ +// Inkling 2's prompt-row kernels: the router's row dots in tiles (tf_ink2_rowdot's bits), the dense GEMM's epilogue. +#include + +#include "exl3_candidate.cuh" + +namespace ink2r { + +constexpr int kRows = 32, kOuts = 16, kCols = 128; + +__device__ __forceinline__ float bf(uint16_t u) { return __uint_as_float(static_cast(u) << 16); } + +} // namespace ink2r + +// fp32 sigmoid?(x[row] . W[j]): lane l sums columns l, l + 32, ... then the xor tree, as tf_ink2_rowdot; C % 128 == 0. +extern "C" __global__ void __launch_bounds__(256) tf_ink2_rowdot_tiles(const uint16_t* __restrict__ x, + const uint16_t* __restrict__ W, + float* __restrict__ out, int rows, int J, + int C, int act) { + using namespace ink2r; + __shared__ float xs[kRows][kCols]; + __shared__ float ws[kOuts][kCols]; + const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5; + const int r0 = blockIdx.x * kRows, j0 = blockIdx.y * kOuts; + float acc[4][kOuts]; +#pragma unroll + for (int i = 0; i < 4; ++i) +#pragma unroll + for (int j = 0; j < kOuts; ++j) acc[i][j] = 0.0f; + for (int c0 = 0; c0 < C; c0 += kCols) { + __syncthreads(); + for (int e = threadIdx.x; e < (kRows + kOuts) * kCols / 8; e += 256) { + const int r = e / (kCols / 8), c = (e % (kCols / 8)) * 8; + const bool wrow = r >= kRows; + const int src = wrow ? j0 + r - kRows : r0 + r; + uint4 v = make_uint4(0, 0, 0, 0); + if (src < (wrow ? J : rows)) + v = *reinterpret_cast((wrow ? W : x) + static_cast(src) * C + c0 + c); + float* d = wrow ? &ws[r - kRows][c] : &xs[r][c]; + const uint32_t u[4] = {v.x, v.y, v.z, v.w}; + for (int k = 0; k < 4; ++k) { + d[2 * k] = ink2r::bf(static_cast(u[k] & 0xffffu)); + d[2 * k + 1] = ink2r::bf(static_cast(u[k] >> 16)); + } + } + __syncthreads(); + for (int m = 0; m < kCols / 32; ++m) { + const int c = m * 32 + lane; + float xv[4], wv[kOuts]; +#pragma unroll + for (int i = 0; i < 4; ++i) xv[i] = xs[warp * 4 + i][c]; +#pragma unroll + for (int j = 0; j < kOuts; ++j) wv[j] = ws[j][c]; +#pragma unroll + for (int i = 0; i < 4; ++i) +#pragma unroll + for (int j = 0; j < kOuts; ++j) acc[i][j] += xv[i] * wv[j]; + } + } +#pragma unroll + for (int i = 0; i < 4; ++i) { + const int row = r0 + warp * 4 + i; +#pragma unroll + for (int j = 0; j < kOuts; ++j) { + float s = acc[i][j]; + for (int o = 16; o > 0; o >>= 1) s += __shfl_xor_sync(0xffffffffu, s, o); + if (lane != 0 || row >= rows || j0 + j >= J) continue; + out[static_cast(row) * J + j0 + j] = act == 1 ? 1.0f / (1.0f + expf(-s)) : s; + } + } +} + +// A warp a (row, 128-column block) of a prompt GEMM's fp32 sums: transform, svh, 2^-3 (tf_exl3_prompt_job's tail). +extern "C" __global__ void __launch_bounds__(32) tf_ink2_prompt_tail(const float* __restrict__ z, const __half* svh, + unsigned n, uint8_t* y, unsigned y_f32) { + const unsigned lane = threadIdx.x, row = blockIdx.y, ob = blockIdx.x; + float v[4]; + for (int q = 0; q < 4; ++q) v[q] = z[static_cast(row) * n + ob * 128 + lane + 32 * q]; + tf_exl3_fwht(v, lane); + for (int q = 0; q < 4; ++q) { + const unsigned c = ob * 128 + lane + 32 * q; + tf_exl3_store(y, static_cast(row) * n + c, __fmul_rn(v[q], __fmul_rn(__half2float(svh[c]), 0.125f)), y_f32); + } +} diff --git a/zig/kernels/hip/tiles/wmma12_gemm.hpp b/zig/kernels/hip/tiles/wmma12_gemm.hpp index 22279860782..0a9bc6de912 100644 --- a/zig/kernels/hip/tiles/wmma12_gemm.hpp +++ b/zig/kernels/hip/tiles/wmma12_gemm.hpp @@ -1,31 +1,18 @@ #pragma once // gfx12 WMMA BF16 GEMM tile: y = x . W^T for BF16 x (m x k) and BF16 W (n x k, as stored), fp32 sums. -// Two block geometries (W12Geo), picked by the product's size; whatever the block, each output adds its k products in k -// order, 16 a WMMA step into one fp32 accumulator, so a row's bytes depend on neither m nor the geometry. +// Two block geometries (W12Geo, in tiles/wmma12_step.hpp), picked by the product's size; whatever the block, each +// output adds its k products in k order, 16 a WMMA step into one fp32 accumulator, so a row's bytes depend on neither m +// nor the geometry. // The K loop's barrier orders LDS only (no global data moves between waves), so it keeps the L0 cache. #include "common/vec.hpp" #include "common/wmma.hpp" +#include "tiles/wmma12_step.hpp" namespace tf { namespace rocm { -// A block of BM x BN outputs, WM x WN waves of (BM / WM) x (BN / WN), K steps of BK through double-buffered LDS. -// Staged rows are padded by 8 halves when that fits 64 KiB; past it they are unpadded with their 16-byte chunks -// XOR-swizzled by row (w12_at), which spreads the readers' banks without the pad. -template -struct W12Geo { - static constexpr int BM = BM_, BN = BN_, BK = BK_, WM = WM_, WN = WN_; - static constexpr bool Padded = 2 * (BM + BN) * (BK + 8) * 2 <= 64 * 1024; - static constexpr int Ld = Padded ? BK + 8 : BK; // halves a staged row, 16-byte aligned - static constexpr int Threads = 32 * WM * WN; - static_assert(BM % (16 * WM) == 0 && BN % (16 * WN) == 0, "a wave's sub-tile is whole 16 x 16 products"); - static_assert(BK % 16 == 0, "a K step is whole 16-deep products"); - static_assert(Padded || BK % 64 == 0, "an unpadded row holds whole groups of 8 chunks to swizzle"); - static_assert(2 * (BM + BN) * Ld * 2 <= 64 * 1024, "double-buffered x and W rows fit 64 KiB of LDS"); -}; - // Few rows or narrow outputs take the small block so the grid fills the GPU; launches/dense.zig mirrors both shapes. // The big block's 64-deep steps take 64 KiB unpadded (swizzled): half the barriers of 32-deep steps. using W12Small = W12Geo<16, 64, 64, 1, 4>; @@ -34,37 +21,6 @@ using W12Big = W12Geo<128, 128, 64, 2, 4>; using W12Pair = W12Geo<16, 64, 64, 1, 2>; constexpr int kW12Band = 4; // row blocks a band of the launch order walks the column blocks with -typedef __bf16 bf16x8 __attribute__((ext_vector_type(8))); - -// The half offset of 16-byte chunk c of staged row r: in place when padded, else at c ^ (r % 8). -template -__device__ __forceinline__ int w12_at(int r, int c) { - if constexpr (G::Padded) return r * G::Ld + 8 * c; - else return r * G::Ld + 8 * (c ^ (r % 8)); -} - -// The K loop's barrier: LDS stores before it are seen by LDS loads after it; global memory is not ordered (none moves). -__device__ __forceinline__ void w12_sync() { - __builtin_amdgcn_fence(__ATOMIC_RELEASE, "workgroup", "local"); - __builtin_amdgcn_s_barrier(); - __builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "workgroup", "local"); -} - -// The served step, a 16-deep BF16 product into fp32 sums; the contract's control swaps in a less exact one. -struct W12Step { -#if TF_DEVICE_WMMA_GFX12 - __device__ static f32x8 mma(bf16x8 a, bf16x8 b, f32x8 c) { - return __builtin_amdgcn_wmma_f32_16x16x16_bf16_w32_gfx12(a, b, c); - } -#endif -}; - -// The served tile's staging: operand loads undo the stores' swizzle, and the K loop's barriers order LDS. The contract's -// controls each break one (a swizzle the loads ignore, a K loop without its barriers) and must go red. -struct W12Exact { - static constexpr bool swizzled_loads = true, ordered = true; -}; - // Block (x, y) in launch order takes tile (bx, by): bands of kW12Band row blocks share each column block's weights. __device__ __forceinline__ void w12_band(int& bx, int& by) { const int cols = gridDim.x, rows = gridDim.y; @@ -125,17 +81,15 @@ __device__ __forceinline__ void wmma12_gemm_tile(const Args& a) { #pragma unroll for (int q = 0; q < XPT; ++q) { const int p = tid + q * kW12Threads; - if (XP % kW12Threads == 0 || p < XP) *reinterpret_cast(&xs[buf][w12_at(p / PR, p % PR)]) = rx[q]; + if (XP % kW12Threads == 0 || p < XP) w12_store(xs[buf], p / PR, p % PR, rx[q]); } #pragma unroll for (int q = 0; q < WPT; ++q) { const int p = tid + q * kW12Threads; - if (WP % kW12Threads == 0 || p < WP) *reinterpret_cast(&ws[buf][w12_at(p / PR, p % PR)]) = rw[q]; + if (WP % kW12Threads == 0 || p < WP) w12_store(ws[buf], p / PR, p % PR, rw[q]); } }; - // an operand's chunk as the stores laid it out (a control's loads may ignore the swizzle) - const auto load_at = [](int r, int c) { return Fault::swizzled_loads ? w12_at(r, c) : r * G::Ld + 8 * c; }; f32x8 acc[TM][TN]; #pragma unroll for (int i = 0; i < TM; ++i) @@ -146,7 +100,7 @@ __device__ __forceinline__ void wmma12_gemm_tile(const Args& a) { const int koff = 8 * (lane >> 4); fetch(0); stash(0); - if constexpr (Fault::ordered) w12_sync(); + w12_sync(); for (int s = 0; s < steps; ++s) { const int buf = s & 1; if (s + 1 < steps) fetch(s + 1); @@ -154,16 +108,16 @@ __device__ __forceinline__ void wmma12_gemm_tile(const Args& a) { for (int kk = 0; kk < kW12K; kk += 16) { bf16x8 av[TM], bv[TN]; #pragma unroll - for (int i = 0; i < TM; ++i) av[i] = *reinterpret_cast(&xs[buf][load_at(arow + 16 * i, (kk + koff) / 8)]); + for (int i = 0; i < TM; ++i) av[i] = w12_load(xs[buf], arow + 16 * i, (kk + koff) / 8); #pragma unroll - for (int j = 0; j < TN; ++j) bv[j] = *reinterpret_cast(&ws[buf][load_at(bcol + 16 * j, (kk + koff) / 8)]); + for (int j = 0; j < TN; ++j) bv[j] = w12_load(ws[buf], bcol + 16 * j, (kk + koff) / 8); #pragma unroll for (int i = 0; i < TM; ++i) #pragma unroll for (int j = 0; j < TN; ++j) acc[i][j] = Step::mma(av[i], bv[j], acc[i][j]); } if (s + 1 < steps) stash(buf ^ 1); - if constexpr (Fault::ordered) w12_sync(); + w12_sync(); } if constexpr (requires { Epi::pairs; }) { // weights packed in 16-row groups (gate f..f+15, then up f..f+15) and a wave's columns whole 32-column groups: diff --git a/zig/kernels/hip/tiles/wmma12_step.hpp b/zig/kernels/hip/tiles/wmma12_step.hpp new file mode 100644 index 00000000000..19b4937817c --- /dev/null +++ b/zig/kernels/hip/tiles/wmma12_step.hpp @@ -0,0 +1,79 @@ +#pragma once + +// The gfx12 WMMA pieces below a tile's K loop, shared by the tiles that stage BF16 operands in LDS: the block +// geometry and its staging layout, the LDS-only barrier, the 16-deep BF16 step, the operand loads, and the staging +// the contract's controls break. A tile keeps its own K loop and epilogue (tiles/wmma12_gemm.hpp). +// tiles/wmma12_gemm_k32_ref.hpp does not include this header: it is a frozen copy that the served block must equal. + +#include "common/arch.hpp" +#include "common/vec.hpp" +#include "common/wmma.hpp" + +namespace tf { +namespace rocm { + +// A block of BM x BN outputs, WM x WN waves of (BM / WM) x (BN / WN), K steps of BK through double-buffered LDS. +// Staged rows are padded by 8 halves when that fits 64 KiB; past it they are unpadded with their 16-byte chunks +// XOR-swizzled by row (w12_at), which spreads the readers' banks without the pad. +template +struct W12Geo { + static constexpr int BM = BM_, BN = BN_, BK = BK_, WM = WM_, WN = WN_; + static constexpr bool Padded = 2 * (BM + BN) * (BK + 8) * 2 <= 64 * 1024; + static constexpr int Ld = Padded ? BK + 8 : BK; // halves a staged row, 16-byte aligned + static constexpr int Threads = 32 * WM * WN; + static_assert(BM % (16 * WM) == 0 && BN % (16 * WN) == 0, "a wave's sub-tile is whole 16 x 16 products"); + static_assert(BK % 16 == 0, "a K step is whole 16-deep products"); + static_assert(Padded || BK % 64 == 0, "an unpadded row holds whole groups of 8 chunks to swizzle"); + static_assert(2 * (BM + BN) * Ld * 2 <= 64 * 1024, "double-buffered x and W rows fit 64 KiB of LDS"); +}; + +typedef __bf16 bf16x8 __attribute__((ext_vector_type(8))); + +// The half offset of 16-byte chunk c of staged row r: in place when padded, else at c ^ (r % 8). +template +__device__ __forceinline__ int w12_at(int r, int c) { + if constexpr (G::Padded) return r * G::Ld + 8 * c; + else return r * G::Ld + 8 * (c ^ (r % 8)); +} + +// The served step, a 16-deep BF16 product into fp32 sums; the contract's control swaps in a less exact one. +struct W12Step { +#if TF_DEVICE_WMMA_GFX12 + __device__ static f32x8 mma(bf16x8 a, bf16x8 b, f32x8 c) { + return __builtin_amdgcn_wmma_f32_16x16x16_bf16_w32_gfx12(a, b, c); + } +#endif +}; + +// The served tile's staging: operand loads undo the stores' swizzle, and the K loop's barriers order LDS. The +// contract's controls each break one (a swizzle the loads ignore, a K loop without its barriers) and must go red. +struct W12Exact { + static constexpr bool swizzled_loads = true, ordered = true; +}; + +// The K loop's barrier: LDS stores before it are seen by LDS loads after it; global memory is not ordered (none moves). +// A control whose K loop is unordered gets no barrier. +template +__device__ __forceinline__ void w12_sync() { + if constexpr (Fault::ordered) { + __builtin_amdgcn_fence(__ATOMIC_RELEASE, "workgroup", "local"); + __builtin_amdgcn_s_barrier(); + __builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "workgroup", "local"); + } +} + +// Stores an operand's chunk c of staged row r where w12_load reads it. +template +__device__ __forceinline__ void w12_store(unsigned short* stage, int r, int c, u32x4 v) { + *reinterpret_cast(&stage[w12_at(r, c)]) = v; +} + +// An operand's chunk c of staged row r as the stores laid it out (a control's loads may ignore the swizzle). +template +__device__ __forceinline__ bf16x8 w12_load(const unsigned short* stage, int r, int c) { + const int at = Fault::swizzled_loads ? w12_at(r, c) : r * G::Ld + 8 * c; + return *reinterpret_cast(&stage[at]); +} + +} // namespace rocm +} // namespace tf diff --git a/zig/kernels/metal/glm_draft_accept.metal b/zig/kernels/metal/glm_draft_accept.metal new file mode 100644 index 00000000000..4732eed7fd1 --- /dev/null +++ b/zig/kernels/metal/glm_draft_accept.metal @@ -0,0 +1,17 @@ +// GLM's DFlash2 chains accepted on the GPU: a stream's kept drafts end at the first row whose pick differs. +#include +using namespace metal; + +// stream s: rows[s] rows at offsets[s] of tokens and picks; out[2s] drafts kept, out[2s + 1] the next pending token +kernel void glm_draft_accept(device const uint* tokens [[buffer(0)]], device const uint* picks [[buffer(1)]], + device const uint* offsets [[buffer(2)]], device const uint* rows [[buffer(3)]], + device uint* out [[buffer(4)]], constant uint& streams [[buffer(5)]], + uint s [[thread_position_in_grid]]) { + if (s >= streams) return; + const uint at = offsets[s]; + const uint n = rows[s]; + uint kept = 0; + while (kept + 1 < n && tokens[at + kept + 1] == picks[at + kept]) kept++; + out[2 * s] = kept; + out[2 * s + 1] = picks[at + kept]; +} diff --git a/zig/kernels/metal/glm_draft_attention.metal b/zig/kernels/metal/glm_draft_attention.metal new file mode 100644 index 00000000000..7f81b3701b2 --- /dev/null +++ b/zig/kernels/metal/glm_draft_attention.metal @@ -0,0 +1,138 @@ +// GLM's DFlash2 drafter attention: a block's rows over the rolling K/V ring and their own keys, a key a lane. +#include +using namespace metal; + +// TF_QH, TF_KVH and TF_D come from the host. +#define GLM_G (TF_QH / TF_KVH) +#define GLM_CHUNK 128 +#define GLM_BLOCK 32 +#define GLM_PART (TF_D + 4) +// a lane's slice of a head's output: TF_D / 32 consecutive dims (128: 4, 64: 2) +#if TF_D == 128 +typedef float4 glm_vec; +typedef bfloat4 glm_bvec; +#else +typedef float2 glm_vec; +typedef bfloat2 glm_bvec; +#endif + +// Rows: streams' blocks; stream s's keys: its context at ring slots (at + key) % window, then its own KO/VO rows. +struct glm_draft_args { uint rows, block, streams, mask_stride, scale_bits, window, chunks, pad; }; +struct glm_draft_stream { uint keys, context, at, pad; }; +#define GLM_STREAMS 8 + +inline const device bfloat* glm_key(const device bfloat* ring, const device bfloat* own, uint key, uint kh, uint s, + constant glm_draft_stream& st, constant glm_draft_args& a) { + const size_t row = key < st.context ? (size_t)((st.at + key) % a.window) : (size_t)(s * a.block + key - st.context); + return (key < st.context ? ring : own) + (row * TF_KVH + kh) * TF_D; +} + +// Stream s's ring among the eight bound (one buffer argument each). +#define GLM_RING(R, s) ((s) == 0 ? R##0 : (s) == 1 ? R##1 : (s) == 2 ? R##2 : (s) == 3 ? R##3 : (s) == 4 ? R##4 : (s) == 5 ? R##5 : (s) == 6 ? R##6 : R##7) +#define GLM_RINGS(R, at) const device bfloat* R##0 [[buffer(at)]], const device bfloat* R##1 [[buffer(at + 1)]], \ + const device bfloat* R##2 [[buffer(at + 2)]], const device bfloat* R##3 [[buffer(at + 3)]], \ + const device bfloat* R##4 [[buffer(at + 4)]], const device bfloat* R##5 [[buffer(at + 5)]], \ + const device bfloat* R##6 [[buffer(at + 6)]], const device bfloat* R##7 [[buffer(at + 7)]] + +// The NaN-keeping maximum: a NaN score or maximum stays NaN, so no chunk reads as empty. +inline float glm_max(float x, float y) { + return isnan(x) || isnan(y) ? NAN : max(x, y); +} + +// A simdgroup: a row's heads of a KV head over a chunk of its stream's keys; partials [row][kv head][chunk][head]. +[[kernel, max_total_threads_per_threadgroup(32)]] void glm_draft_attend( + const device bfloat* Q [[buffer(0)]], const device bfloat* KO [[buffer(1)]], const device bfloat* VO [[buffer(2)]], + const device uchar* mask [[buffer(3)]], constant glm_draft_args& a [[buffer(4)]], + constant glm_draft_stream* streams [[buffer(5)]], device float* part [[buffer(6)]], GLM_RINGS(K, 8), GLM_RINGS(V, 16), + uint lane [[thread_index_in_simdgroup]], uint3 tg [[threadgroup_position_in_grid]]) { + const uint kh = tg.x, row = tg.y, chunk = tg.z; + if (row >= a.rows) return; + const uint s = row / a.block; + constant glm_draft_stream& st = streams[s]; + if (chunk * GLM_CHUNK >= st.keys) return; + const device bfloat* K = GLM_RING(K, s); + const device bfloat* V = GLM_RING(V, s); + const float scale = as_type(a.scale_bits); + const device bfloat4* q = (const device bfloat4*)(Q + ((size_t)row * TF_QH + kh * GLM_G) * TF_D); + glm_vec out[GLM_G]; + float maximum[GLM_G], total[GLM_G]; + for (uint g = 0; g < GLM_G; ++g) { + maximum[g] = -INFINITY; + total[g] = 0.0f; + out[g] = glm_vec(0.0f); + } + const uint first = chunk * GLM_CHUNK, last = min(st.keys, first + GLM_CHUNK); + for (uint base = first; base < last; base += GLM_BLOCK) { + const uint key = base + lane; + const bool live = key < last && mask[(size_t)row * a.mask_stride + key] != 0; + float dot[GLM_G]; + for (uint g = 0; g < GLM_G; ++g) dot[g] = 0.0f; + if (key < last) { + const device bfloat4* k = (const device bfloat4*)glm_key(K, KO, key, kh, s, st, a); + for (uint d = 0; d < TF_D / 4; ++d) { + const float4 kv = float4(k[d]); + for (uint g = 0; g < GLM_G; ++g) { + const float4 qv = float4(q[g * (TF_D / 4) + d]); + dot[g] = fma(qv.w, kv.w, fma(qv.z, kv.z, fma(qv.y, kv.y, fma(qv.x, kv.x, dot[g])))); + } + } + } + float p[GLM_G]; + for (uint g = 0; g < GLM_G; ++g) { + const float score = live ? dot[g] * scale : -INFINITY; + // a NaN score keeps the maximum NaN, so the merge cannot skip its chunk as empty + const bool nan = simd_any(isnan(score)) || isnan(maximum[g]); + const float next = nan ? NAN : max(maximum[g], simd_max(score)); + const float old_weight = maximum[g] == -INFINITY ? 0.0f : precise::exp(maximum[g] - next); + p[g] = live ? precise::exp(score - next) : 0.0f; + total[g] = fma(total[g], old_weight, simd_sum(p[g])); + out[g] *= old_weight; + maximum[g] = next; + } + // a masked key's value is selected away, never multiplied, so whatever it holds never enters the sums + const uint count = min(uint(GLM_BLOCK), last - base); + // lane j's key address offset (elements past its buffer's start) and buffer, passed to every lane + const uint at = key < last ? uint(glm_key(V, VO, key, kh, s, st, a) - (key < st.context ? V : VO)) : 0u; + for (uint j = 0; j < count; ++j) { + const bool seen = simd_shuffle(uint(live), ushort(j)) != 0; + const device bfloat* row_j = (base + j < st.context ? V : VO) + simd_shuffle(at, ushort(j)); + const glm_vec v = glm_vec(((const device glm_bvec*)row_j)[lane]); + const glm_vec x = seen ? v : glm_vec(0.0f); + for (uint g = 0; g < GLM_G; ++g) out[g] = fma(glm_vec(simd_shuffle(p[g], ushort(j))), x, out[g]); + } + } + for (uint g = 0; g < GLM_G; ++g) { + device float* o = part + ((((size_t)row * TF_KVH + kh) * a.chunks + chunk) * GLM_G + g) * GLM_PART; + ((device glm_vec*)o)[lane] = out[g]; + if (lane == 0) { o[TF_D] = maximum[g]; o[TF_D + 1] = total[g]; } + } +} + +// One query head and row: its chunks' partials rescaled to the largest maximum and added in chunk order. +[[kernel, max_total_threads_per_threadgroup(32)]] void glm_draft_attend_merge( + const device float* part [[buffer(0)]], constant glm_draft_args& a [[buffer(1)]], device bfloat* O [[buffer(2)]], + constant glm_draft_stream* streams [[buffer(3)]], uint lane [[thread_index_in_simdgroup]], + uint2 tg [[threadgroup_position_in_grid]]) { + const uint head = tg.x, row = tg.y; + if (head >= TF_QH || row >= a.rows) return; + const uint chunks = (streams[row / a.block].keys + GLM_CHUNK - 1) / GLM_CHUNK; + const uint kh = head / GLM_G, g = head % GLM_G; + const device float* first = part + (((size_t)row * TF_KVH + kh) * a.chunks * GLM_G + g) * GLM_PART; + const size_t step = (size_t)GLM_G * GLM_PART; + float maximum = -INFINITY; + for (uint c = 0; c < chunks; ++c) { + const float m = first[c * step + TF_D]; + maximum = glm_max(maximum, m); + } + glm_vec out = glm_vec(0.0f); + float total = 0.0f; + for (uint c = 0; c < chunks; ++c) { + const device float* p = first + c * step; + if (p[TF_D] == -INFINITY) continue; + const float w = precise::exp(p[TF_D] - maximum); + total = fma(p[TF_D + 1], w, total); + out = fma(((const device glm_vec*)p)[lane], glm_vec(w), out); + } + const size_t qi = ((size_t)row * TF_QH + head) * TF_D; + ((device glm_bvec*)(O + qi))[lane] = glm_bvec(total == 0.0f ? glm_vec(0.0f) : out / total); +} diff --git a/zig/kernels/metal/glm_draft_follow.metal b/zig/kernels/metal/glm_draft_follow.metal new file mode 100644 index 00000000000..aee42a7eb3b --- /dev/null +++ b/zig/kernels/metal/glm_draft_follow.metal @@ -0,0 +1,35 @@ +// GLM's DFlash2 block after a window accepted on the GPU: its ids, rope positions and attention mask from the count. +#include +using namespace metal; + +// a stream's plan: window rows from `first`, context keys [lo, lo + context) then its block rows, `begin` its start +struct glm_follow_stream { ulong first, lo, begin; uint context, keys; }; +struct glm_follow_args { uint block, streams, trained, window, mask_token, mask_stride, rows, pad; }; + +// thread (key, row): row = stream * block + q; accepted[2s] drafts kept, accepted[2s + 1] the block's anchor +kernel void glm_draft_follow(device const uint* accepted [[buffer(0)]], constant glm_follow_args& a [[buffer(1)]], + constant glm_follow_stream* st [[buffer(2)]], device uint* ids [[buffer(3)]], + device ulong* positions [[buffer(4)]], device uchar* mask [[buffer(5)]], + uint2 at [[thread_position_in_grid]]) { + const uint key = at.x; + const uint row = at.y; + if (key >= a.mask_stride || row >= a.rows) return; + const uint s = row / a.block; + const uint q = row % a.block; + const glm_follow_stream t = st[s]; + const ulong end = t.first + accepted[2 * s] + 1; + if (key == 0) { + ids[row] = q == 0 ? accepted[2 * s + 1] : a.mask_token; + positions[row] = end + q; + } + const ulong reach = end + q + 1; + const ulong from = max(t.begin, reach > a.window ? reach - a.window : 0ul); + uchar visible = 0; + if (key < t.context) { + const ulong p = t.lo + key; + visible = p >= from && p < end; + } else if (key < t.keys) { + visible = !(q < a.trained && a.block > a.trained && key - t.context >= a.trained); + } + mask[row * a.mask_stride + key] = visible; +} diff --git a/zig/kernels/metal/glm_draft_topk.metal b/zig/kernels/metal/glm_draft_topk.metal new file mode 100644 index 00000000000..7d0740fe15e --- /dev/null +++ b/zig/kernels/metal/glm_draft_topk.metal @@ -0,0 +1,167 @@ +// GLM's DFlash2 drafter top-k: one threadgroup a row finds the k-th key by its two bytes, then sorts the few above it. +#include +using namespace metal; + +// The Row ABI of core/bf16_topk.metal: every entry at or past count is { 0xffffffff, 0 }. +#define GLM_MAX_K 16 +#define GLM_THREADS 512 +#define GLM_SIMDS (GLM_THREADS / 32) +// candidates the sort takes in one pass: more ties at the k-th key take the ordered path +#define GLM_PICKS 64 +struct Params { uint rows, vocab, k, stride; }; +struct Entry { uint token, score_bits; }; +struct Row { uint nonfinite, count; Entry entries[GLM_MAX_K]; }; + +// core's order: a larger key first, then the lower token; both zeros share one key +inline uint glm_key(ushort raw) { + const uint bits = (raw & 0x7fffu) == 0 ? 0u : uint(raw); + return (bits & 0x8000u) != 0 ? (~bits & 0xffffu) : (bits | 0x8000u); +} +inline bool glm_before(uint key, uint id, uint other_key, uint other_id) { + return key > other_key || (key == other_key && id < other_id); +} + +// Two 16-bit counters a word, one histogram a simdgroup; then the 256 bins' totals in `bins`. +inline void glm_bins(threadgroup atomic_uint* hist, threadgroup uint* bins, uint t) { + threadgroup_barrier(mem_flags::mem_threadgroup); + if (t < 256) { + uint n = 0; + for (uint s = 0; s < GLM_SIMDS; ++s) + n += (atomic_load_explicit(&hist[s * 128 + t / 2], memory_order_relaxed) >> (16 * (t & 1))) & 0xffffu; + bins[t] = n; + } + threadgroup_barrier(mem_flags::mem_threadgroup); +} + +// From the top bin down: the bin holding the k-th key past `above` keys, and the keys in bins above it. +inline uint2 glm_cut(const threadgroup uint* bins, uint above, uint k) { + uint cum = above; + for (int b = 255; b >= 0; --b) { + if (cum + bins[b] >= k) return uint2(uint(b), cum); + cum += bins[b]; + } + return uint2(0, cum); +} + +[[kernel, max_total_threads_per_threadgroup(GLM_THREADS)]] void glm_draft_topk( + const device ushort* logits [[buffer(0)]], device Row* output [[buffer(1)]], constant Params& p [[buffer(2)]], + uint row [[threadgroup_position_in_grid]], uint t [[thread_index_in_threadgroup]], + uint sg [[simdgroup_index_in_threadgroup]], uint lane [[thread_index_in_simdgroup]]) { + threadgroup atomic_uint hist[GLM_SIMDS * 128]; + threadgroup uint bins[256], keys[GLM_PICKS], ids[GLM_PICKS], scores[GLM_PICKS], counts[GLM_SIMDS]; + threadgroup atomic_uint flags, picked; + threadgroup uint cut[4]; + const device ushort* x = logits + (size_t)row * p.stride; + device Row& out = output[row]; + for (uint i = t; i < GLM_SIMDS * 128; i += GLM_THREADS) atomic_store_explicit(&hist[i], 0u, memory_order_relaxed); + if (t == 0) { + atomic_store_explicit(&flags, 0u, memory_order_relaxed); + atomic_store_explicit(&picked, 0u, memory_order_relaxed); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + // the high byte of every finite key, and what the row holds that is not finite + uint mask = 0; + for (uint tok = t; tok < p.vocab; tok += GLM_THREADS) { + const ushort raw = x[tok]; + if ((raw & 0x7f80u) == 0x7f80u) { + mask |= (raw & 0x7fu) != 0 ? 1u : (raw & 0x8000u) == 0 ? 2u : 4u; + continue; + } + const uint b = glm_key(raw) >> 8; + atomic_fetch_add_explicit(&hist[sg * 128 + b / 2], 1u << (16 * (b & 1)), memory_order_relaxed); + } + mask = simd_or(mask); + if (lane == 0 && mask != 0) atomic_fetch_or_explicit(&flags, mask, memory_order_relaxed); + glm_bins(hist, bins, t); + const uint held = atomic_load_explicit(&flags, memory_order_relaxed); + if (held != 0) { + if (t < GLM_MAX_K) out.entries[t] = { 0xffffffffu, 0u }; + if (t == 0) { out.nonfinite = held; out.count = 0; } + return; + } + if (t == 0) { + const uint2 h = glm_cut(bins, 0, p.k); + cut[0] = h.x; + cut[1] = h.y; + } + for (uint i = t; i < GLM_SIMDS * 128; i += GLM_THREADS) atomic_store_explicit(&hist[i], 0u, memory_order_relaxed); + threadgroup_barrier(mem_flags::mem_threadgroup); + // the low byte of the keys in the k-th key's high bin + const uint high = cut[0]; + for (uint tok = t; tok < p.vocab; tok += GLM_THREADS) { + const uint key = glm_key(x[tok]); + if ((key >> 8) != high) continue; + const uint b = key & 0xffu; + atomic_fetch_add_explicit(&hist[sg * 128 + b / 2], 1u << (16 * (b & 1)), memory_order_relaxed); + } + glm_bins(hist, bins, t); + if (t == 0) { + const uint2 l = glm_cut(bins, cut[1], p.k); + cut[2] = (high << 8) | l.x; + cut[3] = l.y + bins[l.x]; // keys above the k-th key's, and those equal to it + } + threadgroup_barrier(mem_flags::mem_threadgroup); + const uint kth = cut[2]; + if (cut[3] <= GLM_PICKS) { + // every key at or above the k-th: few enough to sort whole, whatever order they arrive in + for (uint tok = t; tok < p.vocab; tok += GLM_THREADS) { + const ushort raw = x[tok]; + const uint key = glm_key(raw); + if (key < kth) continue; + const uint at = atomic_fetch_add_explicit(&picked, 1u, memory_order_relaxed); + keys[at] = key; + ids[at] = tok; + scores[at] = uint(raw) << 16; + } + } else { + // many ties at the k-th key: the keys above it anywhere, then the lowest tokens equal to it, in token order + uint taken = 0; + for (uint first = 0; first < p.vocab; first += GLM_THREADS) { + const uint tok = first + t; + const ushort raw = tok < p.vocab ? x[tok] : ushort(0x7fc0); + const uint key = (raw & 0x7f80u) == 0x7f80u ? 0u : glm_key(raw); + const uint equal = key == kth ? 1u : 0u; + if (key > kth) { + const uint at = atomic_fetch_add_explicit(&picked, 1u, memory_order_relaxed); + keys[at] = key; + ids[at] = tok; + scores[at] = uint(raw) << 16; + } + const uint before = simd_prefix_exclusive_sum(equal); + if (lane == 31) counts[sg] = before + equal; + threadgroup_barrier(mem_flags::mem_threadgroup); + uint rank = taken + before; + for (uint s = 0; s < sg; ++s) rank += counts[s]; + uint all = 0; + for (uint s = 0; s < GLM_SIMDS; ++s) all += counts[s]; + // the equal ones fill the slots from the top down, after the at most k - 1 keys above + if (equal != 0 && rank < GLM_PICKS - GLM_MAX_K) { + keys[GLM_PICKS - 1 - rank] = key; + ids[GLM_PICKS - 1 - rank] = tok; + scores[GLM_PICKS - 1 - rank] = uint(raw) << 16; + } + taken += all; + threadgroup_barrier(mem_flags::mem_threadgroup); + } + if (t == 0) { + const uint above = atomic_load_explicit(&picked, memory_order_relaxed); + const uint equal = min(taken, uint(GLM_PICKS - GLM_MAX_K)); + for (uint i = 0; i < equal; ++i) { + keys[above + i] = keys[GLM_PICKS - 1 - i]; + ids[above + i] = ids[GLM_PICKS - 1 - i]; + scores[above + i] = scores[GLM_PICKS - 1 - i]; + } + atomic_store_explicit(&picked, above + equal, memory_order_relaxed); + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + // each candidate's place: the candidates before it in core's order + const uint n = atomic_load_explicit(&picked, memory_order_relaxed); + if (t < n) { + uint place = 0; + for (uint j = 0; j < n; ++j) place += glm_before(keys[j], ids[j], keys[t], ids[t]) ? 1u : 0u; + if (place < p.k) out.entries[place] = { ids[t], scores[t] }; + } + if (t >= p.k && t < GLM_MAX_K) out.entries[t] = { 0xffffffffu, 0u }; + if (t == 0) { out.nonfinite = 0; out.count = p.k; } +} diff --git a/zig/kernels/metal/idol_vae.metal b/zig/kernels/metal/idol_vae.metal new file mode 100644 index 00000000000..de517018b14 --- /dev/null +++ b/zig/kernels/metal/idol_vae.metal @@ -0,0 +1,446 @@ +// Idol's image encoder (FLUX.2's VAE encoder) in fp32, each picture tensor [rows, columns, channels]. + +#include +using namespace metal; + +#define TF_UNROLL_IV _Pragma("clang loop unroll(full)") + +struct IvConvIn { + uint rows; + uint cols; +}; + +// y [pixels, 128] = conv3x3(2 x - 1) + b of the picture x [pixels, 3] in [0, 1], zero padded; w [27, 128] by tap. +[[max_total_threads_per_threadgroup(256)]] [[kernel]] void iv_conv_in( + const device float* x [[buffer(0)]], const device float* w [[buffer(1)]], const device float* b [[buffer(2)]], + device float* y [[buffer(3)]], constant IvConvIn& p [[buffer(4)]], uint2 at [[thread_position_in_grid]]) { + if (at.y >= p.rows * p.cols) return; + const int py = int(at.y / p.cols); + const int px = int(at.y % p.cols); + float s = 0.0f; + TF_UNROLL_IV + for (int ky = 0; ky < 3; ky++) { + TF_UNROLL_IV + for (int kx = 0; kx < 3; kx++) { + const int iy = py + ky - 1; + const int ix = px + kx - 1; + if (iy < 0 || ix < 0 || iy >= int(p.rows) || ix >= int(p.cols)) continue; + const device float* v = x + ulong(uint(iy) * p.cols + uint(ix)) * 3; + TF_UNROLL_IV + for (int c = 0; c < 3; c++) s = fma(v[c] * 2.0f - 1.0f, w[((ky * 3 + kx) * 3 + c) * 128 + at.x], s); + } + } + y[ulong(at.y) * 128 + at.x] = s + b[at.x]; +} + +struct IvConv { + uint rows; + uint cols; + uint in_rows; + uint in_cols; + uint cin; + uint cout; + uint ldw; + uint taps; + uint add; +}; + +// y = conv(x) + b (+ r): a 1x1 (taps 1) or a 3x3 of stride 2 padded right and below (taps 9), w [taps * cin, ldw]. +[[max_total_threads_per_threadgroup(128)]] [[kernel]] void iv_conv( + const device float* x [[buffer(0)]], const device float* w [[buffer(1)]], const device float* b [[buffer(2)]], + const device float* r [[buffer(3)]], device float* y [[buffer(4)]], constant IvConv& p [[buffer(5)]], + uint2 tg [[threadgroup_position_in_grid]], uint t [[thread_index_in_threadgroup]], + uint sg [[simdgroup_index_in_threadgroup]]) { + constexpr uint BK = 32; + constexpr uint lda = BK + 4; + // an implicit GEMM, x [in_rows, in_cols, cin] read a tap at a time: a 64 x 64 tile a threadgroup, fp32 sums + threadgroup float As[64 * lda]; + threadgroup float Cs[64 * 68]; + const uint pixels = p.rows * p.cols; + const uint m0 = tg.y * 64; + const uint n0 = tg.x * 64; + const uint arow = t / 2; + const uint acol = (t % 2) * 16; + const uint pix = m0 + arow; + const uint oy = pix / p.cols; + const uint ox = pix % p.cols; + const uint stride = p.taps == 9 ? 2 : 1; + const uint sr = (sg / 2) * 32; + const uint sc = (sg % 2) * 32; + simdgroup_float8x8 acc[4][4]; + TF_UNROLL_IV + for (uint i = 0; i < 4; i++) { + TF_UNROLL_IV + for (uint j = 0; j < 4; j++) acc[i][j] = simdgroup_float8x8(0.0f); + } + const uint K = p.taps * p.cin; + for (uint k0 = 0; k0 < K; k0 += BK) { + const uint tap = k0 / p.cin; + const uint iy = oy * stride + tap / 3; + const uint ix = ox * stride + tap % 3; + threadgroup float4* dst = (threadgroup float4*)(As + arow * lda + acol); + if (pix < pixels && iy < p.in_rows && ix < p.in_cols) { + const device float4* src = (const device float4*)(x + ulong(iy * p.in_cols + ix) * p.cin + k0 % p.cin + acol); + TF_UNROLL_IV + for (uint i = 0; i < 4; i++) dst[i] = src[i]; + } else { + TF_UNROLL_IV + for (uint i = 0; i < 4; i++) dst[i] = float4(0.0f); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + const device float* wk = w + ulong(k0) * p.ldw + n0 + sc; + TF_UNROLL_IV + for (uint kk = 0; kk < BK; kk += 8) { + simdgroup_float8x8 am[4]; + simdgroup_float8x8 bm[4]; + TF_UNROLL_IV + for (uint i = 0; i < 4; i++) simdgroup_load(am[i], As + (sr + i * 8) * lda + kk, lda); + TF_UNROLL_IV + for (uint j = 0; j < 4; j++) simdgroup_load(bm[j], wk + ulong(kk) * p.ldw + j * 8, p.ldw); + TF_UNROLL_IV + for (uint i = 0; i < 4; i++) { + TF_UNROLL_IV + for (uint j = 0; j < 4; j++) simdgroup_multiply_accumulate(acc[i][j], am[i], bm[j], acc[i][j]); + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + } + TF_UNROLL_IV + for (uint i = 0; i < 4; i++) { + TF_UNROLL_IV + for (uint j = 0; j < 4; j++) simdgroup_store(acc[i][j], Cs + (sr + i * 8) * 68 + sc + j * 8, 68); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + for (uint e = t; e < 64 * 64; e += 128) { + const uint row = m0 + e / 64; + const uint col = n0 + e % 64; + if (row >= pixels || col >= p.cout) continue; + const ulong at = ulong(row) * p.cout + col; + float v = Cs[(e / 64) * 68 + e % 64] + b[col]; + if (p.add) v = v + r[at]; + y[at] = v; + } +} + +// The patch rows (or columns) a, b and b's sign that B^T's row i combines: (0, 2, -), (1, 2, +), (2, 1, -), (1, 3, -). +inline uint iv_wa(uint i) { return i == 2 ? 2 : (i == 0 ? 0 : 1); } +inline uint iv_wb(uint i) { return i == 0 ? 2 : (i == 3 ? 3 : (i == 1 ? 2 : 1)); } +inline float iv_ws(uint i) { return i == 1 ? 1.0f : -1.0f; } + +// y = conv3x3(x) + b (+ r) by Winograd F(2x2, 3x3), u = G g G^T [16, cin, ldw]; 16 tiles by 64 channels a group. +[[max_total_threads_per_threadgroup(512)]] [[kernel]] void iv_wino( + const device float* x [[buffer(0)]], const device float* u [[buffer(1)]], const device float* b [[buffer(2)]], + const device float* r [[buffer(3)]], device float* y [[buffer(4)]], constant IvConv& p [[buffer(5)]], + uint3 tg [[threadgroup_position_in_grid]], uint t [[thread_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]], uint sg [[simdgroup_index_in_threadgroup]]) { + constexpr uint NF = 8; + constexpr uint BK = 16; + constexpr uint TILES = 16; + constexpr uint PR = 6; + constexpr uint PC = 18; + // the input patch [6, 18, 16]; the epilogue's [16 points, 16 tiles, 32 channels] after + threadgroup float buf[16 * 16 * 32]; + const uint n0 = tg.x * NF * 8; + const int y0 = int(tg.y) * 4; + const int x0 = int(tg.z) * 16; + // this lane's two elements of every 8 x 8 fragment: row fm, columns fn and fn + 1 + const uint fm = ((lane / 4) & 4) + (lane / 2) % 4; + const uint fn = ((lane / 4) & 2) * 2 + (lane % 2) * 2; + const uint pi = sg / 4; + const uint pj = sg % 4; + simdgroup_float8x8 acc[2][NF]; + TF_UNROLL_IV + for (uint i = 0; i < 2; i++) { + TF_UNROLL_IV + for (uint j = 0; j < NF; j++) acc[i][j] = simdgroup_float8x8(0.0f); + } + for (uint c0 = 0; c0 < p.cin; c0 += BK) { + for (uint e = t; e < PR * PC * (BK / 4); e += 512) { + const uint px = e / (BK / 4); + const uint q = e % (BK / 4); + const int iy = y0 - 1 + int(px / PC); + const int ix = x0 - 1 + int(px % PC); + float4 v = float4(0.0f); + if (iy >= 0 && ix >= 0 && iy < int(p.rows) && ix < int(p.cols)) + v = *(const device float4*)(x + ulong(uint(iy) * p.cols + uint(ix)) * p.cin + c0 + q * 4); + *(threadgroup float4*)(buf + px * BK + q * 4) = v; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + TF_UNROLL_IV + for (uint kk = 0; kk < BK; kk += 8) { + simdgroup_float8x8 vm[2]; + TF_UNROLL_IV + for (uint i = 0; i < 2; i++) { + // B^T d B at this point, for tile i * 8 + fm and channels fn, fn + 1 + const uint tile = i * 8 + fm; + const threadgroup float* d = buf + (((tile / 8) * 2) * PC + (tile % 8) * 2) * BK + kk + fn; + TF_UNROLL_IV + for (uint c = 0; c < 2; c++) { + const threadgroup float* q = d + c; + const float wa = q[(iv_wa(pi) * PC + iv_wa(pj)) * BK] + iv_ws(pi) * q[(iv_wb(pi) * PC + iv_wa(pj)) * BK]; + const float wb = q[(iv_wa(pi) * PC + iv_wb(pj)) * BK] + iv_ws(pi) * q[(iv_wb(pi) * PC + iv_wb(pj)) * BK]; + vm[i].thread_elements()[c] = wa + iv_ws(pj) * wb; + } + } + const device float* up_ = u + (ulong(sg) * p.cin + c0 + kk) * p.ldw + n0; + TF_UNROLL_IV + for (uint j = 0; j < NF; j++) { + simdgroup_float8x8 um; + simdgroup_load(um, up_ + j * 8, p.ldw); + TF_UNROLL_IV + for (uint i = 0; i < 2; i++) simdgroup_multiply_accumulate(acc[i][j], vm[i], um, acc[i][j]); + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + } + // the output transform A^T M A, 32 channels at a time + for (uint h = 0; h < NF / 4; h++) { + TF_UNROLL_IV + for (uint i = 0; i < 2; i++) { + TF_UNROLL_IV + for (uint j = 0; j < 4; j++) simdgroup_store(acc[i][h * 4 + j], buf + (sg * TILES + i * 8) * 32 + j * 8, 32); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + { + // one tile and channel a thread: its 16 points, then the four outputs A^T M A, rows then columns + const uint co = t % 32; + const uint tile = t / 32; + const uint col = n0 + h * 32 + co; + const threadgroup float* m = buf + tile * 32 + co; + float s[4][2]; + TF_UNROLL_IV + for (uint j = 0; j < 4; j++) { + const float m0 = m[(0 * 4 + j) * TILES * 32]; + const float m1 = m[(1 * 4 + j) * TILES * 32]; + const float m2 = m[(2 * 4 + j) * TILES * 32]; + const float m3 = m[(3 * 4 + j) * TILES * 32]; + s[j][0] = (m0 + m1) + m2; + s[j][1] = (m1 - m2) - m3; + } + const int ty = y0 + int(tile / 8) * 2; + const int tx = x0 + int(tile % 8) * 2; + TF_UNROLL_IV + for (uint rr = 0; rr < 2; rr++) { + const float out[2] = {(s[0][rr] + s[1][rr]) + s[2][rr], (s[1][rr] - s[2][rr]) - s[3][rr]}; + TF_UNROLL_IV + for (uint cc = 0; cc < 2; cc++) { + const int oy = ty + int(rr); + const int ox = tx + int(cc); + if (col >= p.cout || oy >= int(p.rows) || ox >= int(p.cols)) continue; + const ulong at = ulong(uint(oy) * p.cols + uint(ox)) * p.cout + col; + float v = out[cc] + b[col]; + if (p.add) v = v + r[at]; + y[at] = v; + } + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + } +} + +struct IvNorm { + uint pixels; + uint channels; + uint silu; +}; + +// y = GroupNorm(x) by stats (mean, rstd per group) with g, beta, then SiLU when silu; x, y [pixels, channels]. +[[max_total_threads_per_threadgroup(256)]] [[kernel]] void iv_norm( + const device float* x [[buffer(0)]], const device float* stats [[buffer(1)]], const device float* g [[buffer(2)]], + const device float* beta [[buffer(3)]], device float* y [[buffer(4)]], constant IvNorm& p [[buffer(5)]], + uint2 at [[thread_position_in_grid]]) { + if (at.y >= p.pixels || at.x >= p.channels) return; + const uint grp = at.x / (p.channels / 32); + const ulong i = ulong(at.y) * p.channels + at.x; + float v = (x[i] - stats[grp]) * stats[32 + grp]; + v = v * g[at.x] + beta[at.x]; + y[i] = p.silu ? v / (1.0f + precise::exp(-v)) : v; +} + +struct IvGroups { + uint pixels; + uint channels; + uint chunk; + uint chunks; + uint centered; + float eps; +}; + +// One chunk of pixels' sums of x a group, or of (x - mean)^2 when centered, into part [32, chunks]: a thread a channel. +[[max_total_threads_per_threadgroup(512)]] [[kernel]] void iv_group_part( + const device float* x [[buffer(0)]], const device float* stats [[buffer(1)]], device float* part [[buffer(2)]], + constant IvGroups& p [[buffer(3)]], uint tg [[threadgroup_position_in_grid]], + uint t [[thread_index_in_threadgroup]]) { + threadgroup float sums[512]; + const uint size = p.channels / 32; + const uint first = tg * p.chunk; + const uint last = min(first + p.chunk, p.pixels); + const float mean = p.centered ? stats[t / size] : 0.0f; + float s = 0.0f; + for (uint px = first; px < last; px++) { + const float v = x[ulong(px) * p.channels + t]; + const float d = v - mean; + s += p.centered ? d * d : v; + } + sums[t] = s; + threadgroup_barrier(mem_flags::mem_threadgroup); + if (t < 32) { + float all = 0.0f; + for (uint c = 0; c < size; c++) all += sums[t * size + c]; + part[t * p.chunks + tg] = all; + } +} + +// stats from part's chunk sums, a simdgroup a group: mean[32] when not centered, else rstd[32] = rsqrt(var + eps). +[[max_total_threads_per_threadgroup(1024)]] [[kernel]] void iv_group_finish( + const device float* part [[buffer(0)]], device float* stats [[buffer(1)]], constant IvGroups& p [[buffer(2)]], + uint lane [[thread_index_in_simdgroup]], uint sg [[simdgroup_index_in_threadgroup]]) { + float s = 0.0f; + for (uint i = lane; i < p.chunks; i += 32) s += part[sg * p.chunks + i]; + s = simd_sum(s); + if (lane != 0) return; + const float n = float(p.pixels) * float(p.channels / 32); + if (p.centered) + stats[32 + sg] = metal::precise::rsqrt(s / n + p.eps); + else + stats[sg] = s / n; +} + +struct IvAttention { + uint rows; + float scale; +}; + +// o [rows, 512] = softmax(q k^T * scale) v of qkv rows [rows, 1536] (both padded to 32 rows): 8 queries a group. +[[max_total_threads_per_threadgroup(128)]] [[kernel]] void iv_attention( + const device float* qkv [[buffer(0)]], device float* o [[buffer(1)]], constant IvAttention& p [[buffer(2)]], + uint tg [[threadgroup_position_in_grid]], uint t [[thread_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]], uint sg [[simdgroup_index_in_threadgroup]]) { + constexpr uint D = 512; + constexpr uint Q = D / 4; + constexpr uint ld = 3 * D; + constexpr uint BK = 32; + threadgroup float Sp[4][8 * BK]; + threadgroup float Ps[8 * BK]; + threadgroup float As[8]; + threadgroup uint rescale; + // the rows of this lane's two elements of every 8 x 8 fragment + const uint fm = ((lane / 4) & 4) + (lane / 2) % 4; + const uint q0 = tg * 8; + const uint d0 = sg * Q; + simdgroup_float8x8 qm[Q / 8]; + simdgroup_float8x8 acc[Q / 8]; + TF_UNROLL_IV + for (uint d = 0; d < Q / 8; d++) { + simdgroup_load(qm[d], qkv + ulong(q0) * ld + d0 + d * 8, ld); + acc[d] = simdgroup_float8x8(0.0f); + } + const uint row = t / 16; + const uint col = (t % 16) * 2; + float best = -INFINITY; + float total = 0.0f; + for (uint k0 = 0; k0 < p.rows; k0 += BK) { + const device float* kp = qkv + ulong(k0) * ld + D + d0; + TF_UNROLL_IV + for (uint j = 0; j < BK / 8; j++) { + simdgroup_float8x8 s = simdgroup_float8x8(0.0f); + TF_UNROLL_IV + for (uint d = 0; d < Q / 8; d++) { + simdgroup_float8x8 km; + simdgroup_load(km, kp + ulong(j * 8) * ld + d * 8, ld, ulong2(0, 0), true); + simdgroup_multiply_accumulate(s, qm[d], km, s); + } + simdgroup_store(s, Sp[sg] + j * 8, BK); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + float v[2]; + float most = best; + TF_UNROLL_IV + for (uint c = 0; c < 2; c++) { + const uint i = row * BK + col + c; + const float sum = (Sp[0][i] + Sp[1][i]) + (Sp[2][i] + Sp[3][i]); + v[c] = k0 + col + c < p.rows ? sum * p.scale : -INFINITY; + most = max(most, v[c]); + } + TF_UNROLL_IV + for (ushort m = 1; m < 16; m <<= 1) most = max(most, simd_shuffle_xor(most, m)); + const float alpha = precise::exp(best - most); + float add = 0.0f; + TF_UNROLL_IV + for (uint c = 0; c < 2; c++) { + const float e = precise::exp(v[c] - most); + Ps[row * BK + col + c] = e; + add += e; + } + TF_UNROLL_IV + for (ushort m = 1; m < 16; m <<= 1) add += simd_shuffle_xor(add, m); + total = total * alpha + add; + best = most; + if (t % 16 == 0) As[row] = alpha; + if (t == 0) rescale = 0; + threadgroup_barrier(mem_flags::mem_threadgroup); + if (t % 16 == 0 && alpha != 1.0f) rescale = 1; + threadgroup_barrier(mem_flags::mem_threadgroup); + if (rescale) { + const float f = As[fm]; + TF_UNROLL_IV + for (uint d = 0; d < Q / 8; d++) { + acc[d].thread_elements()[0] *= f; + acc[d].thread_elements()[1] *= f; + } + } + const device float* vp = qkv + ulong(k0) * ld + 2 * D + d0; + TF_UNROLL_IV + for (uint j = 0; j < BK / 8; j++) { + simdgroup_float8x8 pm; + simdgroup_load(pm, Ps + j * 8, BK); + TF_UNROLL_IV + for (uint d = 0; d < Q / 8; d++) { + simdgroup_float8x8 vm; + simdgroup_load(vm, vp + ulong(j * 8) * ld + d * 8, ld); + simdgroup_multiply_accumulate(acc[d], pm, vm, acc[d]); + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + } + if (t % 16 == 0) As[row] = 1.0f / total; + threadgroup_barrier(mem_flags::mem_threadgroup); + const float inv = As[fm]; + TF_UNROLL_IV + for (uint d = 0; d < Q / 8; d++) { + acc[d].thread_elements()[0] *= inv; + acc[d].thread_elements()[1] *= inv; + simdgroup_store(acc[d], o + ulong(q0) * D + d0 + d * 8, D); + } +} + +struct IvTokens { + uint rows; + uint cols; + uint pad; +}; + +// Rows [pad + patches, 128]: pad zeros, then each 2 x 2 patch of z = mean + std * noise as (z - m) / s. +[[max_total_threads_per_threadgroup(256)]] [[kernel]] void iv_tokens( + const device float* moments [[buffer(0)]], const device float* noise [[buffer(1)]], + const device float* m [[buffer(2)]], const device float* s [[buffer(3)]], device float* out [[buffer(4)]], + constant IvTokens& p [[buffer(5)]], uint2 at [[thread_position_in_grid]]) { + const uint w2 = p.cols / 2; + if (at.x >= 128 || at.y >= p.pad + (p.rows / 2) * w2) return; + const ulong o = ulong(at.y) * 128 + at.x; + if (at.y < p.pad) { + out[o] = 0.0f; + return; + } + // moments [rows, cols, 64] as mean | logvar, noise [rows, cols, 32]; a patch's channel c * 4 + dy * 2 + dx + const uint patch = at.y - p.pad; + const uint c = at.x / 4; + const uint py = (patch / w2) * 2 + (at.x % 4) / 2; + const uint px = (patch % w2) * 2 + at.x % 2; + const uint pixel = py * p.cols + px; + // torch.clamp keeps a NaN, where Metal's clamp (fmin, fmax) would drop it + const float raw = moments[ulong(pixel) * 64 + 32 + c]; + const float logvar = isnan(raw) ? raw : clamp(raw, -30.0f, 20.0f); + const float z = moments[ulong(pixel) * 64 + c] + precise::exp(0.5f * logvar) * noise[ulong(pixel) * 32 + c]; + out[o] = (z - m[at.x]) / s[at.x]; +} diff --git a/zig/kernels/metal/lfm3/ops.metal b/zig/kernels/metal/lfm3/ops.metal index 3b9e89f7336..6674600bd67 100644 --- a/zig/kernels/metal/lfm3/ops.metal +++ b/zig/kernels/metal/lfm3/ops.metal @@ -197,13 +197,11 @@ inline void lfm3_head(const device bfloat* x, const device bfloat* gain, constan } } -[[kernel, max_total_threads_per_threadgroup(32)]] void lfm3_qk(const device bfloat* q [[buffer(0)]], const device bfloat* k [[buffer(1)]], - const device bfloat* v [[buffer(2)]], const device bfloat* qn [[buffer(3)]], - const device bfloat* kn [[buffer(4)]], constant lfm3_qk_args& p [[buffer(5)]], - device bfloat* queries [[buffer(6)]], device bfloat* keys [[buffer(7)]], - device bfloat* values [[buffer(8)]], uint2 tg [[threadgroup_position_in_grid]], - uint lane [[thread_index_in_simdgroup]]) { - const uint head = tg.x, row = tg.y, pos = p.len + row; +// One row's head: a query head normed and rotated into queries, or a key head into keys at len + row, with its values. +inline void lfm3_qk_row(const device bfloat* q, const device bfloat* k, const device bfloat* v, const device bfloat* qn, + const device bfloat* kn, constant lfm3_qk_args& p, uint len, uint cap, device bfloat* queries, + device bfloat* keys, device bfloat* values, uint head, uint row, uint lane) { + const uint pos = len + row; bfloat normed[4]; if (head < L3Q) { lfm3_head(q + (size_t(row) * L3Q + head) * L3H, qn, p, pos, lane, normed); @@ -212,13 +210,43 @@ inline void lfm3_head(const device bfloat* x, const device bfloat* gain, constan const uint kh = head - L3Q; lfm3_head(k + (size_t(row) * L3K + kh) * L3H, kn, p, pos, lane, normed); for (uint j = 0; j < 4; ++j) { - const size_t target = (size_t(kh) * p.cap + pos) * L3H + lane + 32 * j; + const size_t target = (size_t(kh) * cap + pos) * L3H + lane + 32 * j; keys[target] = normed[j]; values[target] = v[(size_t(row) * L3K + kh) * L3H + lane + 32 * j]; } } } +[[kernel, max_total_threads_per_threadgroup(32)]] void lfm3_qk(const device bfloat* q [[buffer(0)]], const device bfloat* k [[buffer(1)]], + const device bfloat* v [[buffer(2)]], const device bfloat* qn [[buffer(3)]], + const device bfloat* kn [[buffer(4)]], constant lfm3_qk_args& p [[buffer(5)]], + device bfloat* queries [[buffer(6)]], device bfloat* keys [[buffer(7)]], + device bfloat* values [[buffer(8)]], uint2 tg [[threadgroup_position_in_grid]], + uint lane [[thread_index_in_simdgroup]]) { + lfm3_qk_row(q, k, v, qn, kn, p, p.len, p.cap, queries, keys, values, tg.x, tg.y, lane); +} + +// kernels.zig's AttentionSegment (attention.metal's lfm3_attn_segment, declared after this file), field for field. +struct lfm3_qk_segment { ulong keys, values; uint base, rows, len, cap; float scale; uint window, chunk_base, pad; }; + +// lfm3_qk over a shared round's every row: row tg.y's stream from row_segments, its cache's len, cap, keys and values. +[[kernel, max_total_threads_per_threadgroup(32)]] void lfm3_qk_segments( + const device bfloat* q [[buffer(0)]], const device bfloat* k [[buffer(1)]], const device bfloat* v [[buffer(2)]], + const device bfloat* qn [[buffer(3)]], const device bfloat* kn [[buffer(4)]], constant lfm3_qk_args& p [[buffer(5)]], + device bfloat* queries [[buffer(6)]], constant lfm3_qk_segment* segments [[buffer(7)]], + const device uint* row_segments [[buffer(8)]], uint2 tg [[threadgroup_position_in_grid]], + uint lane [[thread_index_in_simdgroup]]) { +#ifdef L3_QK_BAD_STREAM + constant lfm3_qk_segment& seg = segments[0]; +#else + constant lfm3_qk_segment& seg = segments[row_segments[tg.y]]; +#endif + const size_t b = seg.base; + lfm3_qk_row(q + b * L3Q * L3H, k + b * L3K * L3H, v + b * L3K * L3H, qn, kn, p, seg.len, seg.cap, + queries + b * L3Q * L3H, reinterpret_cast(seg.keys), + reinterpret_cast(seg.values), tg.x, tg.y - seg.base, lane); +} + [[kernel, max_total_threads_per_threadgroup(256)]] void lfm3_gate(device bfloat* y [[buffer(0)]], const device bfloat* logits [[buffer(1)]], constant uint& count [[buffer(2)]], uint i [[thread_position_in_grid]]) { if (i >= count) return; diff --git a/zig/kernels/metal/sources.zig b/zig/kernels/metal/sources.zig index f78ea185572..db94659e847 100644 --- a/zig/kernels/metal/sources.zig +++ b/zig/kernels/metal/sources.zig @@ -178,6 +178,8 @@ pub const uocr_decoder = @embedFile("uocr/decoder.metal"); pub const moss_image_decoder = @embedFile("moss_image_decoder.metal"); /// Idol's decoders' own steps and attention (families/idol/decoder_kernels.zig); projections, norms: the denoiser's. pub const idol_decoder = @embedFile("idol_decoder.metal"); +/// Idol's image encoder (FLUX.2's VAE encoder) in fp32. +pub const idol_vae = @embedFile("idol_vae.metal"); /// A prompt chunk's KDA layer in three passes, appended to the generated kda_rows source (its helpers). pub const glm_kda_prompt = @embedFile("glm_kda_prompt.metal"); /// A decode window's fused KDA step, appended to kda_rows' source too: its arithmetic, rows' independent parts at once. @@ -289,3 +291,11 @@ pub const lfm2_prompt_masked = @import("lfm2/prompt_masked.zig"); /// Qwen3 embeddings' projected-head RMS norm (128-wide Q and K, V unchanged). pub const qwen3_heads = @embedFile("qwen3/heads.metal"); +/// GLM-5.3-Flash's DFlash2 drafter attention: Q/K rotary + normalized GQA partials and their merge. +pub const glm_draft_attention = @embedFile("glm_draft_attention.metal"); +/// GLM-5.3-Flash's DFlash2 drafter top-k: row-wise top 16 over vocabulary logits into packed candidates. +pub const glm_draft_topk = @embedFile("glm_draft_topk.metal"); +/// GLM-5.3-Flash's DFlash2 inline chain accept: compares verified picks against drafted tokens on the GPU. +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"); diff --git a/zig/kernels/xpu/flashnext/flashnext.cl b/zig/kernels/xpu/flashnext/flashnext.cl index 9ebe9cd732b..efd1d29fd2d 100644 --- a/zig/kernels/xpu/flashnext/flashnext.cl +++ b/zig/kernels/xpu/flashnext/flashnext.cl @@ -1,4 +1,4 @@ -// Qwen3.8 Flash Next (qwen4_exp) kernels for Intel Xe2 (Level Zero / OpenCL C), supporting TP={1,2,4}. Arithmetic and +// Qwen3.8 Flash Next (qwen4_exp) kernels for Intel Xe2 (Level Zero / OpenCL C), supporting TP={1,2,4}. #pragma OPENCL FP_CONTRACT OFF #pragma OPENCL EXTENSION cl_khr_fp16 : enable @@ -27,8 +27,6 @@ static inline float wg_sum(float v, local float *red, int nsg) { return tot; } -// 1. Embeddings, RMSNorm, Stream Add - // MLX affine 4-bit group-32 embedding copied into `copies` streams: out [rows, copies, D] bf16. KERNEL(256) void fn_embed_q4(global const int *IDS, global const uint *W, global const ushort *S, global const ushort *B, global ushort *OUT, int D, int copies) { @@ -37,7 +35,7 @@ KERNEL(256) void fn_embed_q4(global const int *IDS, global const uint *W, global const int words = D / 8, groups = D / 32; for (int d = get_local_id(0); d < D; d += 256) { const uint w = W[id * words + d / 8]; - const float q = (float)((w >> (4 * (d & 7))) & 0xFu); + const float q = (float)((w >> (4 * (d & 7))) & 15u); const int g = d / 32; const ushort val = to_bf(q * bf(S[id * groups + g]) + bf(B[id * groups + g])); for (int s = 0; s < copies; s++) { @@ -87,52 +85,36 @@ KERNEL(256) void fn_add_streams(global const ushort *E, global const ushort *HS, } } -// 2. Hyper-Connections (Writeback + Normalize, Down + ReduceAct, Up + Mix) - -// Fused hc_writeback + normalize for D=2560, S=4 (WIDE=10240): grid (rows). has_br == 0: mode 0 (no branch added, H +// Stream-parallel hc_writeback + normalize for D=2560, S=4 (WIDE=10240): grid (4, rows), WG = 256. KERNEL(256) void fn_hc_writeback_norm(global ushort *H, global const float *BR, global const ushort *INJ, global const float *SCALE, global ushort *NORM, float eps, int has_br) { - local float red[10][16][4]; - local float rinv[4]; - const int r = get_group_id(0), lid = get_local_id(0), sg = get_sub_group_id(), lane = get_sub_group_local_id(); + local float red[16]; + const int s = get_group_id(0), r = get_group_id(1), lid = get_local_id(0); const int D = 2560; - float hv[10][4]; + const float inj_v = has_br ? bf(INJ[(long)r * 4 + s]) : 0.0f; + const long base = (long)r * (4 * D) + (long)s * D; + float hv[10]; + float ss = 0.0f; for (int c = 0; c < 10; c++) { const int d = c * 256 + lid; - const float branch = has_br ? rbf(BR[(long)r * D + d]) : 0.0f; - for (int s = 0; s < 4; s++) { - const long at = (long)r * (4 * D) + (long)s * D + d; - float v = bf(H[at]); - if (has_br) { - v = rbf(fma(branch, bf(INJ[(long)r * 4 + s]), v)); - H[at] = to_bf(v); - } - hv[c][s] = v; - const float ss = sub_group_reduce_add(v * v); - if (lane == 0) red[c][sg][s] = ss; + float v = bf(H[base + d]); + if (has_br) { + const float branch = rbf(BR[(long)r * D + d]); + v = rbf(fma(branch, inj_v, v)); + H[base + d] = to_bf(v); } + hv[c] = v; + ss = fma(v, v, ss); } - barrier(CLK_LOCAL_MEM_FENCE); - if (lid < 4) { - float all = 0.0f; - for (int c = 0; c < 10; c++) { - float chunk_s = 0.0f; - for (int w = 0; w < 16; w++) chunk_s += red[c][w][lid]; - all += chunk_s; - } - rinv[lid] = rsqrt(all / (float)D + eps); - } - barrier(CLK_LOCAL_MEM_FENCE); + const float tot = wg_sum(ss, red, 16); + const float rinv = rsqrt(tot / (float)D + eps); for (int c = 0; c < 10; c++) { const int d = c * 256 + lid; - for (int s = 0; s < 4; s++) { - const int col = s * D + d; - NORM[(long)r * (4 * D) + col] = to_bf((hv[c][s] * rinv[s]) * SCALE[col]); - } + NORM[base + d] = to_bf((hv[c] * rinv) * SCALE[s * D + d]); } } -// Writeback only (without NORM), used before final head or PLE when needed: grid (rows, 10). +// Writeback only (without NORM), used before final head or Layer 1 PLE: grid (rows, 10), WG = 256. KERNEL(256) void fn_hc_writeback_only(global ushort *H, global const float *BR, global const ushort *INJ, int has_br) { if (!has_br) return; const int r = get_group_id(0), c = get_group_id(1), lid = get_local_id(0); @@ -145,262 +127,131 @@ KERNEL(256) void fn_hc_writeback_only(global ushort *H, global const float *BR, } } -// Helper: 4-bit group-32 dot of up to 16 rows at once for one output row `row_idx` of [N, K]. Each 16-lane subgroup -static inline void q4g32_dot16_range(global const uint *W, global const ushort *S, global const ushort *B, - global const ushort *X, int x_stride, int m, long row_idx, int K, - int wi_begin, int wi_end, float acc[16]) { - const int lane = get_sub_group_local_id(); - const int words = K / 8, groups = K / 32; - global const uint *wr = W + row_idx * words; - global const ushort *sr = S + row_idx * groups; - global const ushort *br = B + row_idx * groups; - for (int r = 0; r < m; r++) acc[r] = 0.0f; - for (int wi = wi_begin + lane; wi < wi_end; wi += SG) { - const uint pk = wr[wi]; - const int g = wi >> 2; - const float sc = bf(sr[g]), bi = bf(br[g]); - const float w0 = fma((float)(pk & 15u), sc, bi); - const float w1 = fma((float)((pk >> 4) & 15u), sc, bi); - const float w2 = fma((float)((pk >> 8) & 15u), sc, bi); - const float w3 = fma((float)((pk >> 12) & 15u), sc, bi); - const float w4 = fma((float)((pk >> 16) & 15u), sc, bi); - const float w5 = fma((float)((pk >> 20) & 15u), sc, bi); - const float w6 = fma((float)((pk >> 24) & 15u), sc, bi); - const float w7 = fma((float)((pk >> 28) & 15u), sc, bi); - for (int r = 0; r < m; r++) { - const ushort8 xv8 = vload8(0, X + (long)r * x_stride + wi * 8); - acc[r] = fma(bf(xv8.s0), w0, acc[r]); - acc[r] = fma(bf(xv8.s1), w1, acc[r]); - acc[r] = fma(bf(xv8.s2), w2, acc[r]); - acc[r] = fma(bf(xv8.s3), w3, acc[r]); - acc[r] = fma(bf(xv8.s4), w4, acc[r]); - acc[r] = fma(bf(xv8.s5), w5, acc[r]); - acc[r] = fma(bf(xv8.s6), w6, acc[r]); - acc[r] = fma(bf(xv8.s7), w7, acc[r]); +// Two-stage argmax + log-sum-exp over BF16 logits [R, V]: Stage 1 grid (256, R), WG = 256. +KERNEL(256) void fn_logits_part(global const ushort *L, int V, global float *PV, global int *PI, global float *PS) { + local float bv[256], bs[256]; + local int bi[256]; + const int lid = get_local_id(0), gid = get_group_id(0), row = get_group_id(1); + const int per = (V + 255) / 256, lo = gid * per, hi = min(V, lo + per); + float best = -INFINITY; + int idx = 0x7fffffff; + for (int i = lo + lid; i < hi; i += 256) { + const float v = bf(L[(long)row * V + i]); + if (v > best) { + best = v; + idx = i; } } - for (int r = 0; r < m; r++) acc[r] = sub_group_reduce_add(acc[r]); -} - -static inline void q4g32_dot16(global const uint *W, global const ushort *S, global const ushort *B, - global const ushort *X, int x_stride, int m, long row_idx, int K, float acc[16]) { - q4g32_dot16_range(W, S, B, X, x_stride, m, row_idx, K, 0, K / 8, acc); -} - -// Hyper-connection down projection + SiLU/inject activation (4-way Split-K for full EU occupancy!): NORM [R, 10240] x -KERNEL(64) void fn_hc_down_reduce(global const ushort *NORM, global const uint *W, global const ushort *S, - global const ushort *B, global ushort *ACT, global ushort *INJ, - int R, int ndn, int has_inj) { - local float kpart[4][16]; - const int col = get_group_id(0); - const int r0 = get_group_id(1) * 16; - const int sg = get_sub_group_id(), lane = get_sub_group_local_id(); - if (col >= ndn || r0 >= R) return; - const int m = min(16, R - r0); - float acc[16]; - q4g32_dot16_range(W, S, B, NORM + (long)r0 * 10240, 10240, m, col, 10240, sg * 320, (sg + 1) * 320, acc); - if (lane == 0) { - for (int r = 0; r < m; r++) kpart[sg][r] = acc[r]; - } + bv[lid] = best; + bi[lid] = idx; barrier(CLK_LOCAL_MEM_FENCE); - if (sg == 0 && lane < m) { - const float sum = kpart[0][lane] + kpart[1][lane] + kpart[2][lane] + kpart[3][lane]; - const float y = rbf(rbf(sum) * 0.25f); - if (col < 320) { - ACT[(long)(r0 + lane) * 320 + col] = to_bf(bsilu(y)); - } else if (has_inj) { - INJ[(long)(r0 + lane) * 4 + (col - 320)] = to_bf(2.0f * bsig(y)); + float gmax = bv[0]; + int gidx = bi[0]; + for (int i = 1; i < 256; i++) { + if (bv[i] > gmax || (bv[i] == gmax && bi[i] < gidx)) { + gmax = bv[i]; + gidx = bi[i]; } } -} - -// Hyper-connection up projection + stream sigmoid gating + 4-stream average: ACT [R, 320] x W [10240, 320], gated by -KERNEL(256) void fn_hc_upmix(global const ushort *ACT, global const ushort *NORM, global const uint *W, - global const ushort *S, global const ushort *B, global ushort *MIXED, int R) { - local ushort act_l[16 * 320]; - const int col = get_group_id(0) * 16 + get_sub_group_id(); - const int r0 = get_group_id(1) * 16; - const int lid = get_local_id(0), lane = get_sub_group_local_id(); - if (r0 >= R) return; - const int m = min(16, R - r0); - for (int e = lid; e < m * 320; e += 256) { - act_l[e] = ACT[(long)r0 * 320 + e]; + barrier(CLK_LOCAL_MEM_FENCE); + float s = 0.0f; + if (gmax > -INFINITY) { + for (int i = lo + lid; i < hi; i += 256) s += exp(bf(L[(long)row * V + i]) - gmax); } + bs[lid] = s; barrier(CLK_LOCAL_MEM_FENCE); - if (col >= 2560) return; + if (lid == 0) { + float tot = 0.0f; + for (int i = 0; i < 256; i++) tot += bs[i]; + PV[row * 256 + gid] = gmax; + PI[row * 256 + gid] = gidx; + PS[row * 256 + gid] = tot; + } +} - float total[16]; - for (int r = 0; r < m; r++) total[r] = 0.0f; - for (int s = 0; s < 4; s++) { - const long wrow = (long)s * 2560 + col; - global const uint *wr = W + wrow * 40; - global const ushort *sr = S + wrow * 10; - global const ushort *br = B + wrow * 10; - float acc[16]; - for (int r = 0; r < m; r++) acc[r] = 0.0f; - for (int wi = lane; wi < 40; wi += 16) { - const uint pk = wr[wi]; - const int g = wi >> 2; - const float sc = bf(sr[g]), bi = bf(br[g]); - const float w0 = fma((float)(pk & 15u), sc, bi); - const float w1 = fma((float)((pk >> 4) & 15u), sc, bi); - const float w2 = fma((float)((pk >> 8) & 15u), sc, bi); - const float w3 = fma((float)((pk >> 12) & 15u), sc, bi); - const float w4 = fma((float)((pk >> 16) & 15u), sc, bi); - const float w5 = fma((float)((pk >> 20) & 15u), sc, bi); - const float w6 = fma((float)((pk >> 24) & 15u), sc, bi); - const float w7 = fma((float)((pk >> 28) & 15u), sc, bi); - for (int r = 0; r < m; r++) { - const int base = r * 320 + wi * 8; - acc[r] = fma(bf(act_l[base + 0]), w0, acc[r]); - acc[r] = fma(bf(act_l[base + 1]), w1, acc[r]); - acc[r] = fma(bf(act_l[base + 2]), w2, acc[r]); - acc[r] = fma(bf(act_l[base + 3]), w3, acc[r]); - acc[r] = fma(bf(act_l[base + 4]), w4, acc[r]); - acc[r] = fma(bf(act_l[base + 5]), w5, acc[r]); - acc[r] = fma(bf(act_l[base + 6]), w6, acc[r]); - acc[r] = fma(bf(act_l[base + 7]), w7, acc[r]); +// Stage 2: grid (R), WG = 256 -> OUT_TOK[r] = argmax, OUT_BEST[r*4 + 0..2] = (max, lse, id_bits). +KERNEL(256) void fn_logits_best(global const float *PV, global const int *PI, global const float *PS, + global int *OUT_TOK, global float *OUT_BEST) { + local float bv[256], bs[256]; + local int bi[256]; + const int lid = get_local_id(0), row = get_group_id(0); + bv[lid] = PV[row * 256 + lid]; + bi[lid] = PI[row * 256 + lid]; + bs[lid] = PS[row * 256 + lid]; + barrier(CLK_LOCAL_MEM_FENCE); + if (lid == 0) { + float best = bv[0]; + int idx = bi[0]; + for (int i = 1; i < 256; i++) { + if (bv[i] > best || (bv[i] == best && bi[i] < idx)) { + best = bv[i]; + idx = bi[i]; } } - for (int r = 0; r < m; r++) { - const float u = rbf(sub_group_reduce_add(acc[r])); - if (lane == 0) { - const float nv = bf(NORM[(long)(r0 + r) * 10240 + wrow]); - total[r] += rbf(bsig(u) * nv); + float sum = 0.0f; + if (best > -INFINITY) { + for (int i = 0; i < 256; i++) { + if (bv[i] > -INFINITY) sum += bs[i] * exp(bv[i] - best); } } - } - if (lane == 0) { - for (int r = 0; r < m; r++) { - MIXED[(long)(r0 + r) * 2560 + col] = to_bf(total[r] * 0.25f); - } + OUT_TOK[row] = idx; + OUT_BEST[row * 4 + 0] = best; + OUT_BEST[row * 4 + 1] = best + log(sum); + OUT_BEST[row * 4 + 2] = as_float(idx); + OUT_BEST[row * 4 + 3] = 0.0f; } } -// 3. MLX q4g32 Dense Projections (Multi-row Subgroup GEMV & Xe2 BF16 DPAS GEMM) - -// Decode / Verify (1..16 rows in a single weight pass!): grid ((N + 15) / 16, (R + 15) / 16), WG = 256. -KERNEL(256) void fn_qmv4_g32_bf16(global const uint *W, global const ushort *S, global const ushort *B, - global const ushort *X, global ushort *Y, int K, int N, int R) { - const int col = get_group_id(0) * 16 + get_sub_group_id(); - const int r0 = get_group_id(1) * 16; - if (col >= N || r0 >= R) return; - const int m = min(16, R - r0); - float acc[16]; - q4g32_dot16(W, S, B, X + (long)r0 * K, K, m, col, K, acc); - if (get_sub_group_local_id() == 0) { - for (int r = 0; r < m; r++) Y[(long)(r0 + r) * N + col] = to_bf(acc[r]); +// Top-64 candidates of one BF16 logits row `L + row * V`: Stage 1 keeps top-64 per 256-slice. +KERNEL(64) void fn_topk64_part(global const ushort *L, int V, int row, global float *TV, global int *TI) { + local float sv[64]; + local int si[64]; + const int tid = get_local_id(0), gid = get_group_id(0); + const int per = (V + 255) / 256, lo = gid * per, hi = min(V, lo + per); + float my_v[32]; + int my_i[32]; + int cnt = 0; + for (int i = lo + tid; i < hi; i += 64) { + my_v[cnt] = bf(L[(long)row * V + i]); + my_i[cnt] = i; + cnt++; } -} - -KERNEL(256) void fn_qmv4_g32_f32(global const uint *W, global const ushort *S, global const ushort *B, - global const ushort *X, global float *Y, int K, int N, int R) { - const int col = get_group_id(0) * 16 + get_sub_group_id(); - const int r0 = get_group_id(1) * 16; - if (col >= N || r0 >= R) return; - const int m = min(16, R - r0); - float acc[16]; - q4g32_dot16(W, S, B, X + (long)r0 * K, K, m, col, K, acc); - if (get_sub_group_local_id() == 0) { - for (int r = 0; r < m; r++) Y[(long)(r0 + r) * N + col] = acc[r]; - } -} - -// Prompt GEMM on Intel Xe2 BF16 DPAS: Workgroup = 128 threads = 8 subgroups: 2 M-subgroups x 4 N-subgroups = [32 rows -#define FN_DPAS_GEMM_BODY(STORE_STMT) \ - local ushort xl[32][32]; \ - local float xsl[32]; \ - const int sg = get_sub_group_id(), lane = get_sub_group_local_id(), lid = get_local_id(0); \ - const int sg_m = sg >> 2, sg_n = sg & 3; \ - const int m0 = get_group_id(1) * 32, n0 = get_group_id(0) * 64; \ - const int col = n0 + sg_n * 16 + lane; \ - const bool col_ok = col < N; \ - const int words = K / 8, groups = K / 32; \ - const long safe_col = col_ok ? (long)col : 0; \ - global const uint *wc = W + safe_col * words; \ - global const ushort *sc_p = S + safe_col * groups; \ - global const ushort *bi_p = B + safe_col * groups; \ - float8 acc0 = 0.0f, acc1 = 0.0f; \ - for (int g = 0; g < groups; g++) { \ - for (int e = lid; e < 32 * 8; e += 128) { \ - const int rr = e >> 3, cc = (e & 7) * 4; \ - ushort4 v = (m0 + rr < R) ? vload4(0, X + (long)(m0 + rr) * K + g * 32 + cc) : (ushort4)(0); \ - xl[rr][cc + 0] = v.s0; xl[rr][cc + 1] = v.s1; xl[rr][cc + 2] = v.s2; xl[rr][cc + 3] = v.s3; \ - } \ - barrier(CLK_LOCAL_MEM_FENCE); \ - if (sg < 2) { \ - for (int rr = sg * 16 + lane; rr < 32; rr += 32) { \ - float s = 0.0f; \ - for (int k = 0; k < 32; k++) s += bf(xl[rr][k]); \ - xsl[rr] = s; \ - } \ - } \ - const uint4 w4 = col_ok ? vload4(0, wc + g * 4) : (uint4)(0); \ - const float sc = col_ok ? bf(sc_p[g]) : 0.0f; \ - const float bi = col_ok ? bf(bi_p[g]) : 0.0f; \ - int8 b0, b1; \ - for (int p = 0; p < 8; p++) { \ - const uint w_lo = (p < 4) ? w4.s0 : w4.s1; \ - const int sh = (p & 3) * 8; \ - const ushort q_ev = to_bf((float)((w_lo >> sh) & 15u)); \ - const ushort q_od = to_bf((float)((w_lo >> (sh + 4)) & 15u)); \ - b0[p] = (int)((uint)q_ev | ((uint)q_od << 16)); \ - const uint w_hi = (p < 4) ? w4.s2 : w4.s3; \ - const ushort q2_ev = to_bf((float)((w_hi >> sh) & 15u)); \ - const ushort q2_od = to_bf((float)((w_hi >> (sh + 4)) & 15u)); \ - b1[p] = (int)((uint)q2_ev | ((uint)q2_od << 16)); \ - } \ - barrier(CLK_LOCAL_MEM_FENCE); \ - short8 a0_0, a0_1, a1_0, a1_1; \ - for (int r = 0; r < 8; r++) { \ - a0_0[r] = (short)xl[sg_m * 16 + r][lane]; \ - a0_1[r] = (short)xl[sg_m * 16 + r][16 + lane]; \ - a1_0[r] = (short)xl[sg_m * 16 + 8 + r][lane]; \ - a1_1[r] = (short)xl[sg_m * 16 + 8 + r][16 + lane]; \ - } \ - float8 d0 = 0.0f, d1 = 0.0f; \ - d0 = intel_sub_group_bf16_bf16_matrix_mad_k16(a0_0, b0, d0); \ - d0 = intel_sub_group_bf16_bf16_matrix_mad_k16(a0_1, b1, d0); \ - d1 = intel_sub_group_bf16_bf16_matrix_mad_k16(a1_0, b0, d1); \ - d1 = intel_sub_group_bf16_bf16_matrix_mad_k16(a1_1, b1, d1); \ - for (int r = 0; r < 8; r++) { \ - acc0[r] = fma(xsl[sg_m * 16 + r], bi, fma(d0[r], sc, acc0[r])); \ - acc1[r] = fma(xsl[sg_m * 16 + 8 + r], bi, fma(d1[r], sc, acc1[r])); \ - } \ - barrier(CLK_LOCAL_MEM_FENCE); \ - } \ - if (col_ok) { \ - for (int r = 0; r < 8; r++) { \ - const int row0 = m0 + sg_m * 16 + r; \ - if (row0 < R) { const int row_i = row0; const float val = acc0[r]; const long idx = (long)row0 * N + col; STORE_STMT; } \ - const int row1 = row0 + 8; \ - if (row1 < R) { const int row_i = row1; const float val = acc1[r]; const long idx = (long)row1 * N + col; STORE_STMT; } \ - } \ + for (int k = 0; k < 64; k++) { + float bv = -INFINITY; + int bi = 0x7fffffff, bj = -1; + for (int j = 0; j < cnt; j++) { + if (my_v[j] > bv || (my_v[j] == bv && my_i[j] < bi)) { + bv = my_v[j]; + bi = my_i[j]; + bj = j; + } + } + sv[tid] = bv; + si[tid] = bi; + barrier(CLK_LOCAL_MEM_FENCE); + float wv = sv[0]; + int wi = si[0]; + for (int u = 1; u < 64; u++) { + if (sv[u] > wv || (sv[u] == wv && si[u] < wi)) { + wv = sv[u]; + wi = si[u]; + } + } + barrier(CLK_LOCAL_MEM_FENCE); + if (bj >= 0 && my_i[bj] == wi) my_v[bj] = -INFINITY; + if (tid == 0) { + TV[gid * 64 + k] = wv; + TI[gid * 64 + k] = wi; + } } - -KERNEL(128) void fn_qmm4_g32_dpas_bf16(global const uint *W, global const ushort *S, global const ushort *B, - global const ushort *X, global ushort *Y, int K, int N, int R) { - FN_DPAS_GEMM_BODY({ (void)row_i; Y[idx] = to_bf(val); }) } -KERNEL(128) void fn_qmm4_g32_dpas_f32(global const uint *W, global const ushort *S, global const ushort *B, - global const ushort *X, global float *Y, int K, int N, int R) { - FN_DPAS_GEMM_BODY({ (void)row_i; Y[idx] = val; }) +// Convert BF16 row [V] to FP32 row [V] (for full-vocab host sampling when top_k == 0 or top_k > 64). +KERNEL(256) void fn_bf16_to_f32(global const ushort *IN, global float *OUT, int N) { + const int i = get_global_id(0); + if (i < N) OUT[i] = bf(IN[i]); } -KERNEL(128) void fn_hc_down_dpas(global const ushort *X, global const uint *W, global const ushort *S, - global const ushort *B, global ushort *ACT, global ushort *INJ, - int R, int N, int has_inj) { - const int K = 10240; - FN_DPAS_GEMM_BODY({ - (void)idx; - const float y = rbf(rbf(val) * 0.25f); - if (col < 320) ACT[(long)row_i * 320 + col] = to_bf(bsilu(y)); - else if (has_inj) INJ[(long)row_i * 4 + (col - 320)] = to_bf(2.0f * bsig(y)); - }) -} - -// 4. Layer 1 Per-Layer N-Gram Embedding (PLE) Gate, Dilated Conv, Shift Window - +#include "fn_dpas.cl" #include "fn_mixers.cl" #include "fn_moe_head.cl" diff --git a/zig/kernels/xpu/flashnext/fn_dpas.cl b/zig/kernels/xpu/flashnext/fn_dpas.cl new file mode 100644 index 00000000000..ac53846e47c --- /dev/null +++ b/zig/kernels/xpu/flashnext/fn_dpas.cl @@ -0,0 +1,455 @@ +// Qwen3.8 Flash Next row-invariant Intel Xe2 BF16 XMX DPAS kernels (packed 16-col tile layout, 0-ULP across R=1..2048). + +#define ONES_BF16 ((int8)(0x3f803f80)) + +static inline float dpas32_1(short a0, short a1, int8 b0, int8 b1) { + const float d = intel_sub_group_bf16_bf16_matrix_mad_k16(a0, b0, 0.0f); + return intel_sub_group_bf16_bf16_matrix_mad_k16(a1, b1, d); +} + +static inline float8 dpas32_8(short8 a0, short8 a1, int8 b0, int8 b1) { + const float8 d = intel_sub_group_bf16_bf16_matrix_mad_k16(a0, b0, (float8)(0.0f)); + return intel_sub_group_bf16_bf16_matrix_mad_k16(a1, b1, d); +} + +static inline void unpack_q4_dpas(uint w0, uint w1, uint w2, uint w3, int8 *b0, int8 *b1) { + int8 lo, hi; + #pragma unroll + for (int p = 0; p < 4; p++) { + const int sh = p * 8; + lo[p] = (int)((uint)to_bf((float)((w0 >> sh) & 15u)) | ((uint)to_bf((float)((w0 >> (sh + 4)) & 15u)) << 16)); + lo[p + 4] = (int)((uint)to_bf((float)((w1 >> sh) & 15u)) | ((uint)to_bf((float)((w1 >> (sh + 4)) & 15u)) << 16)); + hi[p] = (int)((uint)to_bf((float)((w2 >> sh) & 15u)) | ((uint)to_bf((float)((w2 >> (sh + 4)) & 15u)) << 16)); + hi[p + 4] = (int)((uint)to_bf((float)((w3 >> sh) & 15u)) | ((uint)to_bf((float)((w3 >> (sh + 4)) & 15u)) << 16)); + } + *b0 = lo; + *b1 = hi; +} + +static inline void load_q4_tile(global const uint *W, global const ushort *S, global const ushort *B, + long nb, int groups, int g, int lane, int8 *b0, int8 *b1, float *sc, float *bi) { + const long tg = nb * (long)groups + g; + global const uint *wp = W + tg * 64 + lane; + unpack_q4_dpas(wp[0], wp[16], wp[32], wp[48], b0, b1); + const long sb = tg * 16 + lane; + *sc = bf(S[sb]); + *bi = bf(B[sb]); +} + +// 1-row Split-K Xe2 DPAS GEMV: WG = 64 (4 subgroups). Grid: ((ceil(N/16) + (ksplit==1?3:0)) / (ksplit==1?4:1)). +#define FN_QMV1_DPAS_BODY(STORE_STMT) \ + local float kpart[4][16]; \ + const int sg = get_sub_group_id(), lane = get_sub_group_local_id(); \ + const int groups = K / 32; \ + const bool split4 = (groups >= 16) && ((groups & 3) == 0); \ + const int nb = split4 ? (int)get_group_id(0) : ((int)get_group_id(0) * 4 + sg); \ + const int col = nb * 16 + lane; \ + const int nb_max = (N + 15) / 16; \ + if (!split4) { \ + if (nb >= nb_max) return; \ + float acc = 0.0f; \ + for (int g = 0; g < groups; g++) { \ + const short a_lo = (short)X[g * 32 + lane]; \ + const short a_hi = (short)X[g * 32 + 16 + lane]; \ + const float xs = dpas32_1(a_lo, \ + a_hi, ONES_BF16, ONES_BF16); \ + int8 b0, b1; float sc, bi; \ + load_q4_tile(W, S, B, nb, groups, g, lane, &b0, &b1, &sc, &bi); \ + const float d = dpas32_1(a_lo, \ + a_hi, b0, b1); \ + acc = fma(xs, bi, fma(d, sc, acc)); \ + } \ + if (col < N) { const int row_i = 0; const float val = acc; const long idx = col; STORE_STMT; } \ + return; \ + } \ + const int gp = groups >> 2, g0 = sg * gp, g1 = g0 + gp; \ + float qacc = 0.0f; \ + for (int g = g0; g < g1; g++) { \ + const short a_lo = (short)X[g * 32 + lane]; \ + const short a_hi = (short)X[g * 32 + 16 + lane]; \ + const float xs = dpas32_1(a_lo, \ + a_hi, ONES_BF16, ONES_BF16); \ + int8 b0, b1; float sc, bi; \ + load_q4_tile(W, S, B, nb, groups, g, lane, &b0, &b1, &sc, &bi); \ + const float d = dpas32_1(a_lo, \ + a_hi, b0, b1); \ + qacc = fma(xs, bi, fma(d, sc, qacc)); \ + } \ + kpart[sg][lane] = qacc; \ + barrier(CLK_LOCAL_MEM_FENCE); \ + if (sg == 0 && col < N) { \ + const int row_i = 0; \ + const float val = (((kpart[0][lane] + kpart[1][lane]) + kpart[2][lane] ) + kpart[3][lane]); \ + const long idx = col; \ + STORE_STMT; \ + } + +// 2..16-row Split-K Xe2 DPAS GEMV/GEMM: WG = 64 (4 subgroups). Processes up to 16 rows in 1 weight pass! +#define FN_QMV16_DPAS_BODY(STORE_STMT) \ + local float kpart0[4][8][16]; \ + local float kpart1[4][8][16]; \ + const int sg = get_sub_group_id(), lane = get_sub_group_local_id(); \ + const int r0 = (int)get_group_id(1) * 16; \ + if (r0 >= R) return; \ + const int m = min(16, R - r0); \ + const int groups = K / 32; \ + const bool split4 = (groups >= 16) && ((groups & 3) == 0); \ + const int nb = split4 ? (int)get_group_id(0) : ((int)get_group_id(0) * 4 + sg); \ + const int col = nb * 16 + lane; \ + const int nb_max = (N + 15) / 16; \ + if (!split4 && nb >= nb_max) return; \ + const int gp = split4 ? (groups >> 2) : groups; \ + const int g0 = split4 ? (sg * gp) : 0, g1 = g0 + gp; \ + float8 q0 = 0.0f, q1 = 0.0f; \ + for (int g = g0; g < g1; g++) { \ + int8 b0, b1; float sc, bi; \ + load_q4_tile(W, S, B, nb, groups, g, lane, &b0, &b1, &sc, &bi); \ + short8 a0_lo = 0, a0_hi = 0; \ + for (int r = 0; r < 8; r++) { \ + if (r < m) { \ + global const ushort *xr = X + (long)(r0 + r) * K + g * 32; \ + a0_lo[r] = (short)xr[lane]; \ + a0_hi[r] = (short)xr[16 + lane]; \ + } \ + } \ + const float8 xs0 = dpas32_8(a0_lo, \ + a0_hi, ONES_BF16, ONES_BF16); \ + const float8 d0 = dpas32_8(a0_lo, \ + a0_hi, b0, b1); \ + for (int r = 0; r < 8; r++) q0[r] = fma(xs0[r], bi, fma(d0[r], sc, q0[r])); \ + if (m > 8) { \ + short8 a1_lo = 0, a1_hi = 0; \ + for (int r = 0; r < 8; r++) { \ + if (8 + r < m) { \ + global const ushort *xr = X + (long)(r0 + 8 + r) * K + g * 32; \ + a1_lo[r] = (short)xr[lane]; \ + a1_hi[r] = (short)xr[16 + lane]; \ + } \ + } \ + const float8 xs1 = dpas32_8(a1_lo, \ + a1_hi, ONES_BF16, ONES_BF16); \ + const float8 d1 = dpas32_8(a1_lo, \ + a1_hi, b0, b1); \ + for (int r = 0; r < 8; r++) q1[r] = fma(xs1[r], bi, fma(d1[r], sc, q1[r])); \ + } \ + } \ + if (!split4) { \ + if (col < N) { \ + for (int r = 0; r < min(m, 8); r++) { const int row_i = r0 + r; const float val = q0[r]; const long idx = (long)row_i * N + col; STORE_STMT; } \ + for (int r = 0; r < m - 8; r++) { const int row_i = r0 + 8 + r; const float val = q1[r]; const long idx = (long)row_i * N + col; STORE_STMT; } \ + } \ + return; \ + } \ + for (int r = 0; r < 8; r++) { kpart0[sg][r][lane] = q0[r]; kpart1[sg][r][lane] = q1[r]; } \ + barrier(CLK_LOCAL_MEM_FENCE); \ + if (sg == 0 && col < N) { \ + for (int r = 0; r < min(m, 8); r++) { \ + const int row_i = r0 + r; \ + const float val = (((kpart0[0][r][lane] + kpart0[1][r][lane]) + kpart0[2][r][lane] ) + kpart0[3][r][lane]); \ + const long idx = (long)row_i * N + col; \ + STORE_STMT; \ + } \ + for (int r = 0; r < m - 8; r++) { \ + const int row_i = r0 + 8 + r; \ + const float val = (((kpart1[0][r][lane] + kpart1[1][r][lane]) + kpart1[2][r][lane] ) + kpart1[3][r][lane]); \ + const long idx = (long)row_i * N + col; \ + STORE_STMT; \ + } \ + } + +// Wide Prompt Xe2 DPAS GEMM (R > 16): WG = 128 (2 M-sgs x 4 N-sgs = [32x64]), K=64 SLM staging. +#define FN_QMM_TILE_DPAS_BODY(STORE_STMT) \ + local ushort xl[32][64]; \ + const int sg = get_sub_group_id(), lane = get_sub_group_local_id(), lid = get_local_id(0); \ + const int sg_m = sg >> 2, sg_n = sg & 3; \ + const int m0 = (int)get_group_id(1) * 32; \ + const int nb = (int)get_group_id(0) * 4 + sg_n; \ + const int col = nb * 16 + lane; \ + const int nb_max = (N + 15) / 16; \ + const long safe_nb = (nb < nb_max) ? (long)nb : 0; \ + const bool nb_ok = (nb < nb_max); \ + const int groups = K / 32; \ + const bool split4 = (groups >= 16) && ((groups & 3) == 0); \ + const int q_cnt = split4 ? 4 : 1; \ + const int gp = groups / q_cnt; \ + float8 acc0 = 0.0f, acc1 = 0.0f; \ + for (int q = 0; q < q_cnt; q++) { \ + float8 q0 = 0.0f, q1 = 0.0f; \ + const int g_end = (q + 1) * gp; \ + for (int g = q * gp; g < g_end; g += 2) { \ + const bool has2 = (g + 1 < g_end); \ + const int load_w = has2 ? 64 : 32; \ + for (int e = lid; e < 32 * (load_w / 4); e += 128) { \ + const int rr = e / (load_w / 4), cc = (e % (load_w / 4)) * 4; \ + const ushort4 v = (m0 + rr < R) ? vload4(0, X + (long)(m0 + rr) * K + g * 32 + cc) : (ushort4)(0); \ + xl[rr][cc + 0] = v.s0; xl[rr][cc + 1] = v.s1; xl[rr][cc + 2] = v.s2; xl[rr][cc + 3] = v.s3; \ + } \ + barrier(CLK_LOCAL_MEM_FENCE); \ + for (int sub = 0; sub < (has2 ? 2 : 1); sub++) { \ + int8 b0 = 0, b1 = 0; float sc = 0.0f, bi = 0.0f; \ + if (nb_ok) load_q4_tile(W, S, B, safe_nb, groups, g + sub, lane, &b0, &b1, &sc, &bi); \ + short8 a0_0, a0_1, a1_0, a1_1; \ + const int kbase = sub * 32; \ + for (int r = 0; r < 8; r++) { \ + a0_0[r] = (short)xl[sg_m * 16 + r][kbase + lane]; \ + a0_1[r] = (short)xl[sg_m * 16 + r][kbase + 16 + lane]; \ + a1_0[r] = (short)xl[sg_m * 16 + 8 + r][kbase + lane]; \ + a1_1[r] = (short)xl[sg_m * 16 + 8 + r][kbase + 16 + lane]; \ + } \ + const float8 xs0 = dpas32_8(a0_0, \ + a0_1, ONES_BF16, ONES_BF16); \ + const float8 xs1 = dpas32_8(a1_0, \ + a1_1, ONES_BF16, ONES_BF16); \ + const float8 d0 = dpas32_8(a0_0, \ + a0_1, b0, b1); \ + const float8 d1 = dpas32_8(a1_0, \ + a1_1, b0, b1); \ + for (int r = 0; r < 8; r++) { \ + q0[r] = fma(xs0[r], bi, fma(d0[r], sc, q0[r])); \ + q1[r] = fma(xs1[r], bi, fma(d1[r], sc, q1[r])); \ + } \ + } \ + barrier(CLK_LOCAL_MEM_FENCE); \ + } \ + acc0 = (q == 0) ? q0 : (acc0 + q0); \ + acc1 = (q == 0) ? q1 : (acc1 + q1); \ + } \ + if (col < N) { \ + for (int r = 0; r < 8; r++) { \ + const int row0 = m0 + sg_m * 16 + r; \ + if (row0 < R) { const int row_i = row0; const float val = acc0[r]; const long idx = (long)row0 * N + col; STORE_STMT; } \ + const int row1 = row0 + 8; \ + if (row1 < R) { const int row_i = row1; const float val = acc1[r]; const long idx = (long)row1 * N + col; STORE_STMT; } \ + } \ + } + +KERNEL(64) void fn_qmv1_dpas_bf16(global const uint *W, global const ushort *S, global const ushort *B, + global const ushort *X, global ushort *Y, int K, int N) { + FN_QMV1_DPAS_BODY({ (void)row_i; Y[idx] = to_bf(val); }) +} + +KERNEL(64) void fn_qmv1_dpas_f32(global const uint *W, global const ushort *S, global const ushort *B, + global const ushort *X, global float *Y, int K, int N) { + FN_QMV1_DPAS_BODY({ (void)row_i; Y[idx] = val; }) +} + +KERNEL(64) void fn_qmv16_dpas_bf16(global const uint *W, global const ushort *S, global const ushort *B, + global const ushort *X, global ushort *Y, int K, int N, int R) { + FN_QMV16_DPAS_BODY({ (void)row_i; Y[idx] = to_bf(val); }) +} + +KERNEL(64) void fn_qmv16_dpas_f32(global const uint *W, global const ushort *S, global const ushort *B, + global const ushort *X, global float *Y, int K, int N, int R) { + FN_QMV16_DPAS_BODY({ (void)row_i; Y[idx] = val; }) +} + +KERNEL(128) void fn_qmm_tile_dpas_bf16(global const uint *W, global const ushort *S, global const ushort *B, + global const ushort *X, global ushort *Y, int K, int N, int R) { + FN_QMM_TILE_DPAS_BODY({ (void)row_i; Y[idx] = to_bf(val); }) +} + +KERNEL(128) void fn_qmm_tile_dpas_f32(global const uint *W, global const ushort *S, global const ushort *B, + global const ushort *X, global float *Y, int K, int N, int R) { + FN_QMM_TILE_DPAS_BODY({ (void)row_i; Y[idx] = val; }) +} + +// Hyper-Connection Down (K=10240 = 320 groups, N=320 or 324) for 1..16 rows (grid: ((N+15)/16, R)). +KERNEL(64) void fn_hc_down_1(global const ushort *X, global const uint *W, global const ushort *S, + global const ushort *B, global ushort *ACT, global ushort *INJ, int N, int has_inj) { + local float kpart[4][16]; + const int sg = get_sub_group_id(), lane = get_sub_group_local_id(); + const int nb = (int)get_group_id(0), row_i = (int)get_group_id(1); + const int col = nb * 16 + lane; + global const ushort *xr = X + (long)row_i * 10240; + float qacc = 0.0f; + for (int g = sg * 80; g < (sg + 1) * 80; g++) { + const short a_lo = (short)xr[g * 32 + lane]; + const short a_hi = (short)xr[g * 32 + 16 + lane]; + const float xs = dpas32_1(a_lo, a_hi, ONES_BF16, ONES_BF16); + int8 b0, b1; float sc, bi; + load_q4_tile(W, S, B, nb, 320, g, lane, &b0, &b1, &sc, &bi); + const float d = dpas32_1(a_lo, a_hi, b0, b1); + qacc = fma(xs, bi, fma(d, sc, qacc)); + } + kpart[sg][lane] = qacc; + barrier(CLK_LOCAL_MEM_FENCE); + if (sg == 0 && col < N) { + const float sum = (((kpart[0][lane] + kpart[1][lane]) + kpart[2][lane]) + kpart[3][lane]); + const float y = rbf(rbf(sum) * 0.25f); + if (col < 320) ACT[(long)row_i * 320 + col] = to_bf(bsilu(y)); + else if (has_inj) INJ[(long)row_i * 4 + (col - 320)] = to_bf(2.0f * bsig(y)); + } +} + +// Wide HC Down (R > 16): WG = 128 ([32 rows x 64 cols], coalesced SLM staging). +KERNEL(128) void fn_hc_down_wide(global const ushort *X, global const uint *W, global const ushort *S, + global const ushort *B, global ushort *ACT, global ushort *INJ, + int R, int N, int has_inj) { + const int K = 10240; + FN_QMM_TILE_DPAS_BODY({ + (void)idx; + const float y = rbf(rbf(val) * 0.25f); + if (col < 320) ACT[(long)row_i * 320 + col] = to_bf(bsilu(y)); + else if (has_inj) INJ[(long)row_i * 4 + (col - 320)] = to_bf(2.0f * bsig(y)); + }) +} + +// 1..16-row Hyper-Connection UpMix on Xe2 DPAS (0 SLM, minimal GRF). Grid: (40, R). +KERNEL(64) void fn_hc_upmix_1(global const ushort *ACT, global const ushort *NORM, global const uint *W, + global const ushort *S, global const ushort *B, global ushort *MIXED) { + const int sg = get_sub_group_id(), lane = get_sub_group_local_id(); + const int nb0 = (int)get_group_id(0) * 4 + sg; + const int row_i = (int)get_group_id(1); + if (nb0 >= 160) return; + const int col = nb0 * 16 + lane; + global const ushort *ar = ACT + (long)row_i * 320; + global const ushort *nr = NORM + (long)row_i * 10240; + short a_lo[10], a_hi[10]; + float xs[10]; + for (int g = 0; g < 10; g++) { + a_lo[g] = (short)ar[g * 32 + lane]; + a_hi[g] = (short)ar[g * 32 + 16 + lane]; + xs[g] = dpas32_1(a_lo[g], a_hi[g], ONES_BF16, ONES_BF16); + } + float total = 0.0f; + for (int s = 0; s < 4; s++) { + const long nb = (long)s * 160 + nb0; + float acc = 0.0f; + for (int g = 0; g < 10; g++) { + int8 b0, b1; float sc, bi; + load_q4_tile(W, S, B, nb, 10, g, lane, &b0, &b1, &sc, &bi); + const float d = dpas32_1(a_lo[g], a_hi[g], b0, b1); + acc = fma(xs[g], bi, fma(d, sc, acc)); + } + total += rbf(bsig(rbf(acc)) * bf(nr[(long)s * 2560 + col])); + } + MIXED[(long)row_i * 2560 + col] = to_bf(total * 0.25f); +} + +// Wide HC UpMix on Xe2 DPAS (R > 16): WG = 128 ([32 rows x 64 cols], stages [32, 320] ACT in 20 KiB SLM once). +KERNEL(128) void fn_hc_upmix_dpas(global const ushort *ACT, global const ushort *NORM, global const uint *W, + global const ushort *S, global const ushort *B, global ushort *MIXED, int R) { + local ushort al[32][320]; + const int sg = get_sub_group_id(), lane = get_sub_group_local_id(), lid = get_local_id(0); + const int sg_m = sg >> 2, sg_n = sg & 3; + const int m0 = (int)get_group_id(1) * 32; + const int nb0 = (int)get_group_id(0) * 4 + sg_n; + const int col = nb0 * 16 + lane; + for (int e = lid; e < 32 * 80; e += 128) { + const int rr = e / 80, cc = (e % 80) * 4; + const ushort4 v = (m0 + rr < R) ? vload4(0, ACT + (long)(m0 + rr) * 320 + cc) : (ushort4)(0); + al[rr][cc + 0] = v.s0; al[rr][cc + 1] = v.s1; al[rr][cc + 2] = v.s2; al[rr][cc + 3] = v.s3; + } + barrier(CLK_LOCAL_MEM_FENCE); + + float8 tot0 = 0.0f, tot1 = 0.0f; + for (int s = 0; s < 4; s++) { + float8 acc0 = 0.0f, acc1 = 0.0f; + for (int g = 0; g < 10; g++) { + short8 a0_0, a0_1, a1_0, a1_1; + for (int r = 0; r < 8; r++) { + a0_0[r] = (short)al[sg_m * 16 + r][g * 32 + lane]; + a0_1[r] = (short)al[sg_m * 16 + r][g * 32 + 16 + lane]; + a1_0[r] = (short)al[sg_m * 16 + 8 + r][g * 32 + lane]; + a1_1[r] = (short)al[sg_m * 16 + 8 + r][g * 32 + 16 + lane]; + } + const float8 xs0 = dpas32_8(a0_0, a0_1, ONES_BF16, ONES_BF16); + const float8 xs1 = dpas32_8(a1_0, a1_1, ONES_BF16, ONES_BF16); + int8 b0, b1; float sc, bi; + load_q4_tile(W, S, B, (long)s * 160 + nb0, 10, g, lane, &b0, &b1, &sc, &bi); + const float8 d0 = dpas32_8(a0_0, a0_1, b0, b1); + const float8 d1 = dpas32_8(a1_0, a1_1, b0, b1); + for (int r = 0; r < 8; r++) { + acc0[r] = fma(xs0[r], bi, fma(d0[r], sc, acc0[r])); + acc1[r] = fma(xs1[r], bi, fma(d1[r], sc, acc1[r])); + } + } + for (int r = 0; r < 8; r++) { + const int row0 = m0 + sg_m * 16 + r; + if (row0 < R) { + const float nv = bf(NORM[(long)row0 * 10240 + (long)s * 2560 + col]); + tot0[r] += rbf(bsig(rbf(acc0[r])) * nv); + } + const int row1 = row0 + 8; + if (row1 < R) { + const float nv = bf(NORM[(long)row1 * 10240 + (long)s * 2560 + col]); + tot1[r] += rbf(bsig(rbf(acc1[r])) * nv); + } + } + } + for (int r = 0; r < 8; r++) { + const int row0 = m0 + sg_m * 16 + r; + if (row0 < R) MIXED[(long)row0 * 2560 + col] = to_bf(tot0[r] * 0.25f); + const int row1 = row0 + 8; + if (row1 < R) MIXED[(long)row1 * 2560 + col] = to_bf(tot1[r] * 0.25f); + } +} + +// Router Logits on Xe2 BF16 DPAS for 1..16 rows (grid: (33, R), 128 B SLM). +KERNEL(64) void fn_router_dpas_1(global const ushort *X, global const int *W, global float *OUT) { + local float kpart[4][16]; + const int sg = get_sub_group_id(), lane = get_sub_group_local_id(); + const int nb = (int)get_group_id(0), row_i = (int)get_group_id(1); + if (nb >= 33) return; + const int col = nb * 16 + lane; + global const ushort *xr = X + (long)row_i * 2560; + float qacc = 0.0f; + for (int kb = sg * 40; kb < (sg + 1) * 40; kb++) { + global const int *wp = W + ((long)nb * 160 + kb) * 128 + lane; + int8 b; + for (int p = 0; p < 8; p++) b[p] = wp[p * 16]; + const short a = (short)xr[kb * 16 + lane]; + qacc = intel_sub_group_bf16_bf16_matrix_mad_k16(a, b, qacc); + } + kpart[sg][lane] = qacc; + barrier(CLK_LOCAL_MEM_FENCE); + if (sg == 0 && col < 513) { + OUT[(long)row_i * 513 + col] = (((kpart[0][lane] + kpart[1][lane]) + kpart[2][lane]) + kpart[3][lane]); + } +} + +KERNEL(128) void fn_router_dpas_mm(global const ushort *X, global const int *W, global float *OUT, int R) { + local ushort xl[32][64]; + const int sg = get_sub_group_id(), lane = get_sub_group_local_id(), lid = get_local_id(0); + const int sg_m = sg >> 2, sg_n = sg & 3; + const int m0 = (int)get_group_id(1) * 32; + const int nb = (int)get_group_id(0) * 4 + sg_n; + const int col = nb * 16 + lane; + const bool nb_ok = (nb < 33); + const long safe_nb = nb_ok ? (long)nb : 0; + float8 acc0 = 0.0f, acc1 = 0.0f; + for (int q = 0; q < 4; q++) { + float8 q0 = 0.0f, q1 = 0.0f; + for (int kb = q * 40; kb < (q + 1) * 40; kb += 4) { + for (int e = lid; e < 32 * 16; e += 128) { + const int rr = e >> 4, cc = (e & 15) * 4; + const ushort4 v = (m0 + rr < R) ? vload4(0, X + (long)(m0 + rr) * 2560 + kb * 16 + cc) : (ushort4)(0); + xl[rr][cc + 0] = v.s0; xl[rr][cc + 1] = v.s1; xl[rr][cc + 2] = v.s2; xl[rr][cc + 3] = v.s3; + } + barrier(CLK_LOCAL_MEM_FENCE); + for (int sub = 0; sub < 4; sub++) { + int8 b = 0; + if (nb_ok) { + global const int *wp = W + (safe_nb * 160 + kb + sub) * 128 + lane; + for (int p = 0; p < 8; p++) b[p] = wp[p * 16]; + } + short8 a0, a1; + for (int r = 0; r < 8; r++) { + a0[r] = (short)xl[sg_m * 16 + r][sub * 16 + lane]; + a1[r] = (short)xl[sg_m * 16 + 8 + r][sub * 16 + lane]; + } + q0 = intel_sub_group_bf16_bf16_matrix_mad_k16(a0, b, q0); + q1 = intel_sub_group_bf16_bf16_matrix_mad_k16(a1, b, q1); + } + barrier(CLK_LOCAL_MEM_FENCE); + } + acc0 = (q == 0) ? q0 : (acc0 + q0); + acc1 = (q == 0) ? q1 : (acc1 + q1); + } + if (col < 513) { + for (int r = 0; r < 8; r++) { + if (m0 + sg_m * 16 + r < R) OUT[(long)(m0 + sg_m * 16 + r) * 513 + col] = acc0[r]; + if (m0 + sg_m * 16 + 8 + r < R) OUT[(long)(m0 + sg_m * 16 + 8 + r) * 513 + col] = acc1[r]; + } + } +} diff --git a/zig/kernels/xpu/flashnext/fn_mixers.cl b/zig/kernels/xpu/flashnext/fn_mixers.cl index c8e3ba951f0..d61645e07a8 100644 --- a/zig/kernels/xpu/flashnext/fn_mixers.cl +++ b/zig/kernels/xpu/flashnext/fn_mixers.cl @@ -140,7 +140,7 @@ KERNEL(256) void fn_gdn_front(global const ushort *P, global const ushort *cs, g } } -// Recurrence over `rows` tokens: 1 subgroup (16 lanes) per (8 V-rows, V-head); each lane holds 8 K-columns (16*8 = +// Recurrence over `rows` tokens: 1 subgroup (16 lanes) per (8 V-rows, V-head), 8 K-cols/lane. Grid: (16, NV). KERNEL(16) void fn_gdn_rows(global const float *qn, global const float *kn, global const float *v, global const float *gb, global const float *state_in, global float *state_out, int rows, global float *ys_out, int NK, int NV) { @@ -274,29 +274,38 @@ KERNEL(128) void fn_qsa_pool(global const ushort *IKC, global ushort *POOLED, in POOLED[(long)b * DI + d] = to_bf(apply_rope(xn, xpn, d, HALF, RATIO * b, INV)); } -// Score completed blocks past TOP=512: grid (R, (complete_max + 15) / 16), WG = 256 (16 subgroups, 1 block/subgroup). +// Score blocks past TOP=512: grid ((R + 15) / 16, (complete_max + 63) / 64), WG=256 (64 blocks x 16 queries). KERNEL(256) void fn_qsa_scores(global const ushort *IQ, global const ushort *POOLED, int pos0, global float *SC, - int NB) { - local float qs[4][128]; - const int r = get_group_id(0), j = get_group_id(1), lid = get_local_id(0); + int NB, int R) { + local ushort qs[16][512]; + const int r0 = (int)get_group_id(0) * 16, j = (int)get_group_id(1), lid = get_local_id(0); const int sg = get_sub_group_id(), lane = get_sub_group_local_id(); - const int complete = (pos0 + r + 1) / 4; - if (complete <= 512 || j * 16 >= complete) return; - for (int e = lid; e < 4 * 128; e += 256) qs[e / 128][e % 128] = bf(IQ[(long)r * 512 + e]); + if (r0 >= R) return; + const int m_rows = min(16, R - r0); + const int complete_max = (pos0 + r0 + m_rows) / 4; + if (complete_max <= 512 || j * 64 >= complete_max) return; + for (int e = lid; e < m_rows * 512; e += 256) qs[e >> 9][e & 511] = IQ[(long)r0 * 512 + e]; barrier(CLK_LOCAL_MEM_FENCE); - const int b = j * 16 + sg; - if (b >= complete) return; const float scale = sqrt(128.0f); - ushort8 kb = vload8(0, POOLED + (long)b * 128 + lane * 8); - float k8[8]; - for (int i = 0; i < 8; i++) k8[i] = bf(kb[i]); - float total = 0.0f; - for (int h = 0; h < 4; h++) { - float part = 0.0f; - for (int i = 0; i < 8; i++) part = fma(k8[i], qs[h][lane * 8 + i], part); - total += fmax(sub_group_reduce_add(part), 0.0f); + for (int bs = 0; bs < 4; bs++) { + const int b = j * 64 + bs * 16 + sg; + if (b >= complete_max) break; + ushort8 kb = vload8(0, POOLED + (long)b * 128 + lane * 8); + float k8[8]; + for (int i = 0; i < 8; i++) k8[i] = bf(kb[i]); + for (int rr = 0; rr < m_rows; rr++) { + const int r = r0 + rr; + const int complete_r = (pos0 + r + 1) / 4; + if (complete_r <= 512 || b >= complete_r) continue; + float total = 0.0f; + for (int h = 0; h < 4; h++) { + float part = 0.0f; + for (int i = 0; i < 8; i++) part = fma(k8[i], bf(qs[rr][h * 128 + lane * 8 + i]), part); + total += fmax(sub_group_reduce_add(part), 0.0f); + } + if (lane == 0) SC[(long)r * NB + b] = total / scale; + } } - if (lane == 0) SC[(long)r * NB + b] = total / scale; } static inline uint qsa_order_key(float v) { diff --git a/zig/kernels/xpu/flashnext/fn_moe_head.cl b/zig/kernels/xpu/flashnext/fn_moe_head.cl index 148bfb46a75..55648f31fe3 100644 --- a/zig/kernels/xpu/flashnext/fn_moe_head.cl +++ b/zig/kernels/xpu/flashnext/fn_moe_head.cl @@ -1,24 +1,6 @@ -// Qwen3.8 Flash Next MoE router, expert-grouped routed/shared MLP, and logits kernels. +// Qwen3.8 Flash Next MoE top-k, parallel expert compaction, Xe2 DPAS MoE projections, and logits kernels. -// Router logits [R, 513] f32 = X [R, 2560] bf16 . W [513, 2560] bf16. Grid: ((513 + 3) / 4, R), WG = 64 (4 subgroups). -KERNEL(64) void fn_router_logits(global const ushort *X, global const ushort *W, global float *OUT, int R) { - const int e = get_group_id(0) * 4 + get_sub_group_id(); - const int r = get_group_id(1); - if (e >= 513 || r >= R) return; - const int lane = get_sub_group_local_id(); - global const ushort *xr = X + (long)r * 2560; - global const ushort *wr = W + (long)e * 2560; - float acc = 0.0f; - for (int i = lane * 8; i < 2560; i += 16 * 8) { - const ushort8 xv = vload8(0, xr + i); - const ushort8 wv = vload8(0, wr + i); - for (int j = 0; j < 8; j++) acc = fma(bf(xv[j]), bf(wv[j]), acc); - } - acc = sub_group_reduce_add(acc); - if (lane == 0) OUT[(long)r * 513 + e] = acc; -} - -// Exact top-10 of 512 routed experts (ties: lowest id) + slot 10 shared-expert sigmoid gate. Grid: (R), WG = 128 (8 +// Exact top-10 of 512 routed experts (ties: lowest id) + slot 10 shared-expert sigmoid gate. Grid: (R), WG = 128. KERNEL(128) void fn_route_topk(global const float *L, global int *PICK, global float *WTS) { local float sv[8]; local int si[8]; @@ -38,7 +20,6 @@ KERNEL(128) void fn_route_topk(global const float *L, global int *PICK, global f bi = idx; } } - // Subgroup best (tie -> lower id) const float sg_max = sub_group_reduce_max(bv); const int sg_id = sub_group_reduce_min(bv == sg_max ? bi : 0x7fffffff); if (lane == 0) { @@ -76,13 +57,11 @@ KERNEL(128) void fn_route_topk(global const float *L, global int *PICK, global f } } -// Compact active (row, slot, local_expert) triples on this rank, grouped by local_expert (up to 16 rows/group) while -KERNEL(128) void fn_moe_compact(global const int *PICK, global int *ACTIVE, global int *EXP_GRP, global int *N_ACT, +// Parallel expert compaction for R = 1..2048 into 32-pair Xe2 DPAS tiles while preserving ascending slot order per row. +KERNEL(256) void fn_moe_compact(global const int *PICK, global int *ACTIVE, global int *EXP_GRP, global int *N_ACT, global int *ROW_LIST, int R, int first_e, int local_e) { - local int pick_s[64 * 10]; - local int slot_pair[64 * 10]; local int e_cnt[512]; - local int e_off[512]; + local int e_cur[512]; local int g_off[512]; const int tid = get_local_id(0); if (R == 1) { @@ -92,30 +71,26 @@ KERNEL(128) void fn_moe_compact(global const int *PICK, global int *ACTIVE, glob const int le = PICK[s] - first_e; if (le >= 0 && le < local_e) { ACTIVE[rc] = (s << 10) | le; - EXP_GRP[rc] = (le << 20) | (1 << 12) | rc; + EXP_GRP[rc] = (le << 22) | (1 << 16) | rc; ROW_LIST[rc] = rc; rc++; } } ROW_LIST[rc] = -1; N_ACT[0] = rc; + N_ACT[1] = rc; } return; } - const int total_slots = R * 10; - for (int idx = tid; idx < total_slots; idx += 128) { - const int r = idx / 10, s = idx % 10; - pick_s[idx] = PICK[(long)r * 11 + s] - first_e; - } - for (int le = tid; le < local_e; le += 128) e_cnt[le] = 0; + for (int le = tid; le < local_e; le += 256) e_cnt[le] = 0; barrier(CLK_LOCAL_MEM_FENCE); - for (int le = tid; le < local_e; le += 128) { - int c = 0; - for (int idx = 0; idx < total_slots; idx++) { - if (pick_s[idx] == le) c++; + for (int r = tid; r < R; r += 256) { + global const int *pr = PICK + (long)r * 11; + for (int s = 0; s < 10; s++) { + const int le = pr[s] - first_e; + if (le >= 0 && le < local_e) atomic_inc(&e_cnt[le]); } - e_cnt[le] = c; } barrier(CLK_LOCAL_MEM_FENCE); @@ -123,314 +98,340 @@ KERNEL(128) void fn_moe_compact(global const int *PICK, global int *ACTIVE, glob int p_acc = 0, g_acc = 0; for (int le = 0; le < local_e; le++) { const int c = e_cnt[le]; - e_off[le] = p_acc; + e_cur[le] = p_acc; g_off[le] = g_acc; p_acc += c; - g_acc += (c + 15) >> 4; + g_acc += (c + 31) >> 5; } N_ACT[0] = g_acc; + N_ACT[1] = p_acc; } barrier(CLK_LOCAL_MEM_FENCE); - for (int le = tid; le < local_e; le += 128) { + for (int le = tid; le < local_e; le += 256) { const int c = e_cnt[le]; if (c == 0) continue; - int p_at = e_off[le]; - for (int idx = 0; idx < total_slots; idx++) { - if (pick_s[idx] == le) { - const int r = idx / 10, s = idx % 10; - const int pair_idx = p_at++; - ACTIVE[pair_idx] = (r << 16) | (s << 10) | le; - slot_pair[idx] = pair_idx; - } - } - const int p0 = e_off[le], g0 = g_off[le]; - for (int g = 0; g * 16 < c; g++) { - const int m = min(16, c - g * 16); - EXP_GRP[g0 + g] = (le << 20) | (m << 12) | (p0 + g * 16); + const int p0 = e_cur[le], g0 = g_off[le]; + for (int g = 0; g * 32 < c; g++) { + const int m = min(32, c - g * 32); + EXP_GRP[g0 + g] = (le << 22) | (m << 16) | (p0 + g * 32); } } - barrier(CLK_LOCAL_MEM_FENCE); - for (int r = tid; r < R; r += 128) { + for (int r = tid; r < R; r += 256) { + global const int *pr = PICK + (long)r * 11; int rc = 0; for (int s = 0; s < 10; s++) { - const int le = pick_s[r * 10 + s]; + const int le = pr[s] - first_e; if (le >= 0 && le < local_e) { - ROW_LIST[r * 11 + rc++] = slot_pair[r * 10 + s]; + const int pair_idx = atomic_inc(&e_cur[le]); + ACTIVE[pair_idx] = (r << 14) | (s << 10) | le; + ROW_LIST[(long)r * 11 + rc++] = pair_idx; } } - ROW_LIST[r * 11 + rc] = -1; + ROW_LIST[(long)r * 11 + rc] = -1; } } -// Routed expert SwiGLU up projection grouped by local expert (up to 16 rows share 1 weight load!): Grid: (640 / 16, -KERNEL(256) void fn_moe_routed_up(global const ushort *X, global const int *ACTIVE, global const int *EXP_GRP, - global const int *N_ACT, - global const uint *GW, global const ushort *GS, global const ushort *GB, - global const uint *UW, global const ushort *US, global const ushort *UB, - global ushort *MOE_ACT) { - local int rows_s[16]; - const int grp_idx = get_group_id(1); - if (grp_idx >= N_ACT[0]) return; - const int grp = EXP_GRP[grp_idx]; - const int le = (grp >> 20) & 0x3FF; - const int m = (grp >> 12) & 0xFF; - const int p0 = grp & 0xFFF; - const int lid = get_local_id(0); - if (lid < m) rows_s[lid] = ACTIVE[p0 + lid] >> 16; - barrier(CLK_LOCAL_MEM_FENCE); - - const int col = get_group_id(0) * 16 + get_sub_group_id(); - const int lane = get_sub_group_local_id(); - const long erow = (long)le * 640 + col; - const int words = 2560 / 8, groups = 2560 / 32; - global const uint *gw = GW + erow * words, *uw = UW + erow * words; - global const ushort *gs = GS + erow * groups, *gb = GB + erow * groups; - global const ushort *us = US + erow * groups, *ub = UB + erow * groups; - float g_acc[16], u_acc[16]; - for (int j = 0; j < m; j++) { - g_acc[j] = 0.0f; - u_acc[j] = 0.0f; - } - for (int wi = lane; wi < words; wi += 16) { - const int g = wi >> 2; - const uint pg = gw[wi], pu = uw[wi]; - const float gs_v = bf(gs[g]), gb_v = bf(gb[g]); - const float us_v = bf(us[g]), ub_v = bf(ub[g]); - const float qg0 = (float)(pg & 15u), qg1 = (float)((pg >> 4) & 15u), qg2 = (float)((pg >> 8) & 15u), qg3 = (float)((pg >> 12) & 15u); - const float qg4 = (float)((pg >> 16) & 15u), qg5 = (float)((pg >> 20) & 15u), qg6 = (float)((pg >> 24) & 15u), qg7 = (float)((pg >> 28) & 15u); - const float qu0 = (float)(pu & 15u), qu1 = (float)((pu >> 4) & 15u), qu2 = (float)((pu >> 8) & 15u), qu3 = (float)((pu >> 12) & 15u); - const float qu4 = (float)((pu >> 16) & 15u), qu5 = (float)((pu >> 20) & 15u), qu6 = (float)((pu >> 24) & 15u), qu7 = (float)((pu >> 28) & 15u); - for (int j = 0; j < m; j++) { - const ushort8 xv = vload8(0, X + (long)rows_s[j] * 2560 + wi * 8); - const float x0 = bf(xv.s0), x1 = bf(xv.s1), x2 = bf(xv.s2), x3 = bf(xv.s3); - const float x4 = bf(xv.s4), x5 = bf(xv.s5), x6 = bf(xv.s6), x7 = bf(xv.s7); - const float sx = x0 + x1 + x2 + x3 + x4 + x5 + x6 + x7; - const float dg = x0 * qg0 + x1 * qg1 + x2 * qg2 + x3 * qg3 + x4 * qg4 + x5 * qg5 + x6 * qg6 + x7 * qg7; - const float du = x0 * qu0 + x1 * qu1 + x2 * qu2 + x3 * qu3 + x4 * qu4 + x5 * qu5 + x6 * qu6 + x7 * qu7; - g_acc[j] += gs_v * dg + gb_v * sx; - u_acc[j] += us_v * du + ub_v * sx; - } +// Per-pair Routed Gate+Up for R = 1..16 (WG = 64: 4-way Split-K over K=2560). Grid: (40, R * min(10, local_e)). +KERNEL(64) void fn_moe_up_1(global const ushort *X, global const int *ACTIVE, global const int *N_ACT, + global const uint *GW, global const ushort *GS, global const ushort *GB, + global const uint *UW, global const ushort *US, global const ushort *UB, + global ushort *MOE_ACT) { + local float gp[4][16], up[4][16]; + const int pair_idx = (int)get_group_id(1); + if (pair_idx >= N_ACT[1]) return; + const int pk = ACTIVE[pair_idx]; + const int row_i = (pk >> 14) & 0x3FFF; + const int le = pk & 0x3FF; + global const ushort *xr = X + (long)row_i * 2560; + const int nb_col = (int)get_group_id(0); + const int sg = get_sub_group_id(), lane = get_sub_group_local_id(); + const long nb = (long)le * 40 + nb_col; + float gq = 0.0f, uq = 0.0f; + for (int g = sg * 20; g < (sg + 1) * 20; g++) { + const short a_lo = (short)xr[g * 32 + lane]; + const short a_hi = (short)xr[g * 32 + 16 + lane]; + const float xs = dpas32_1(a_lo, a_hi, ONES_BF16, ONES_BF16); + int8 gb0, gb1, ub0, ub1; float gsc, gbi, usc, ubi; + load_q4_tile(GW, GS, GB, nb, 80, g, lane, &gb0, &gb1, &gsc, &gbi); + load_q4_tile(UW, US, UB, nb, 80, g, lane, &ub0, &ub1, &usc, &ubi); + const float gd = dpas32_1(a_lo, a_hi, gb0, gb1); + const float ud = dpas32_1(a_lo, a_hi, ub0, ub1); + gq = fma(xs, gbi, fma(gd, gsc, gq)); + uq = fma(xs, ubi, fma(ud, usc, uq)); } - for (int j = 0; j < m; j++) { - const float gr = sub_group_reduce_add(g_acc[j]); - const float ur = sub_group_reduce_add(u_acc[j]); - if (lane == 0) { - MOE_ACT[(long)(p0 + j) * 640 + col] = to_bf(bsilu(rbf(gr)) * rbf(ur)); - } + gp[sg][lane] = gq; + up[sg][lane] = uq; + barrier(CLK_LOCAL_MEM_FENCE); + if (sg == 0) { + const float gr = (((gp[0][lane] + gp[1][lane]) + gp[2][lane] ) + gp[3][lane]); + const float ur = (((up[0][lane] + up[1][lane]) + up[2][lane]) + up[3][lane]); + MOE_ACT[(long)pair_idx * 640 + nb_col * 16 + lane] = to_bf(bsilu(rbf(gr)) * rbf(ur)); } } -// Shared expert SwiGLU up projection over this rank's `sh_w` columns (640 / TP): Grid: ((sh_w + 15) / 16, (R + 15) / -KERNEL(256) void fn_moe_shared_up(global const ushort *X, global const uint *GW, global const ushort *GS, - global const ushort *GB, global const uint *UW, global const ushort *US, - global const ushort *UB, global ushort *SH_ACT, int sh_w, int R) { - const int col = get_group_id(0) * 16 + get_sub_group_id(); - const int r0 = get_group_id(1) * 16; - if (col >= sh_w || r0 >= R) return; - const int m = min(16, R - r0); - float g_acc[16], u_acc[16]; - q4g32_dot16(GW, GS, GB, X + (long)r0 * 2560, 2560, m, col, 2560, g_acc); - q4g32_dot16(UW, US, UB, X + (long)r0 * 2560, 2560, m, col, 2560, u_acc); - if (get_sub_group_local_id() == 0) { - for (int r = 0; r < m; r++) { - SH_ACT[(long)(r0 + r) * sh_w + col] = to_bf(bsilu(rbf(g_acc[r])) * rbf(u_acc[r])); - } - } -} +// Multi-row Expert-Grouped Routed Gate+Up on Xe2 DPAS: WG = 256 (4 M-sgs x 4 N-sgs = [32 pairs x 64 cols]). +KERNEL(256) void fn_moe_up_dpas(global const ushort *X, global const int *ACTIVE, global const int *EXP_GRP, + global const int *N_ACT, + global const uint *GW, global const ushort *GS, global const ushort *GB, + global const uint *UW, global const ushort *US, global const ushort *UB, + global ushort *MOE_ACT) { + local int rows_s[32]; + local ushort xl[32][160]; + const int grp_idx = (int)get_group_id(1); + if (grp_idx >= N_ACT[0]) return; + const uint grp = (uint)EXP_GRP[grp_idx]; + const int le = (int)((grp >> 22) & 0x1FFu); + const int m = (int)((grp >> 16) & 0x3Fu); + const int p0 = (int)(grp & 0xFFFFu); + const int sg = get_sub_group_id(), lane = get_sub_group_local_id(), lid = get_local_id(0); + if (lid < m) rows_s[lid] = (ACTIVE[p0 + lid] >> 14) & 0x3FFF; + barrier(CLK_LOCAL_MEM_FENCE); -// Combined local MoE down projection (routed active pairs + sharded shared expert) -> OUT [R, 2560] fp32! Grid: (2560 -KERNEL(256) void fn_moe_down_combine(global const ushort *MOE_ACT, global const ushort *SH_ACT, - global const int *ACTIVE, global const int *ROW_LIST, global const float *WTS, - global const uint *DW, global const ushort *DS, global const ushort *DB, - global const uint *SDW, global const ushort *SDS, global const ushort *SDB, - global float *OUT, int sh_w, int R) { - const int col = get_group_id(0) * 16 + get_sub_group_id(); - const int r = get_group_id(1); - if (col >= 2560 || r >= R) return; - const int lane = get_sub_group_local_id(); - float total = 0.0f; + const int sg_m = sg >> 2, sg_n = sg & 3; + const int nb_col = (int)get_group_id(0) * 4 + sg_n; + const bool nb_ok = (nb_col < 40); + const long safe_nb = nb_ok ? ((long)le * 40 + nb_col) : 0; + const int m_pad = min(32, (m + 7) & ~7); + float8 ga = 0.0f, ua = 0.0f; - // 1. Active local routed experts for row r in ascending slot order - for (int c = 0; c < 10; c++) { - const int pair_idx = ROW_LIST[r * 11 + c]; - if (pair_idx < 0) break; - const int packed = ACTIVE[pair_idx]; - const int slot = (packed >> 10) & 0x3F; - const int le = packed & 0x3FF; - const float wt = WTS[(long)r * 11 + slot]; - const long drow = (long)le * 2560 + col; - // K = 640 -> 80 words = 5 words per lane! - global const uint *wr = DW + drow * 80; - global const ushort *sr = DS + drow * 20, *br = DB + drow * 20; - global const ushort *xa = MOE_ACT + (long)pair_idx * 640; - float acc = 0.0f; - for (int wi = lane; wi < 80; wi += 16) { - const uint pk = wr[wi]; - const int g = wi >> 2; - const ushort8 xv = vload8(0, xa + wi * 8); - const float x0 = bf(xv.s0), x1 = bf(xv.s1), x2 = bf(xv.s2), x3 = bf(xv.s3); - const float x4 = bf(xv.s4), x5 = bf(xv.s5), x6 = bf(xv.s6), x7 = bf(xv.s7); - const float dot = x0 * (float)(pk & 15u) + x1 * (float)((pk >> 4) & 15u) + x2 * (float)((pk >> 8) & 15u) + - x3 * (float)((pk >> 12) & 15u) + x4 * (float)((pk >> 16) & 15u) + x5 * (float)((pk >> 20) & 15u) + - x6 * (float)((pk >> 24) & 15u) + x7 * (float)((pk >> 28) & 15u); - const float sx = x0 + x1 + x2 + x3 + x4 + x5 + x6 + x7; - acc += bf(sr[g]) * dot + bf(br[g]) * sx; + for (int q = 0; q < 4; q++) { + float8 g0 = 0.0f, u0 = 0.0f; + for (int g = q * 20; g < (q + 1) * 20; g += 5) { + for (int e = lid; e < m_pad * 40; e += 256) { + const int rr = e / 40, cc = (e % 40) * 4; + const ushort4 v = (rr < m) ? vload4(0, X + (long)rows_s[rr] * 2560 + g * 32 + cc) : (ushort4)(0); + xl[rr][cc + 0] = v.s0; xl[rr][cc + 1] = v.s1; xl[rr][cc + 2] = v.s2; xl[rr][cc + 3] = v.s3; + } + barrier(CLK_LOCAL_MEM_FENCE); + if (sg_m * 8 < m) { + for (int sub = 0; sub < 5; sub++) { + short8 a0, a1; + const int kb = sub * 32; + for (int r = 0; r < 8; r++) { + a0[r] = (short)xl[sg_m * 8 + r][kb + lane]; + a1[r] = (short)xl[sg_m * 8 + r][kb + 16 + lane]; + } + const float8 xs = dpas32_8(a0, a1, ONES_BF16, ONES_BF16); + int8 b0 = 0, b1 = 0; + float sc = 0.0f, bi = 0.0f; + if (nb_ok) load_q4_tile(GW, GS, GB, safe_nb, 80, g + sub, lane, &b0, &b1, &sc, &bi); + const float8 gd = dpas32_8(a0, a1, b0, b1); + for (int r = 0; r < 8; r++) g0[r] = fma(xs[r], bi, fma(gd[r], sc, g0[r])); + if (nb_ok) load_q4_tile(UW, US, UB, safe_nb, 80, g + sub, lane, &b0, &b1, &sc, &bi); + const float8 ud = dpas32_8(a0, a1, b0, b1); + for (int r = 0; r < 8; r++) u0[r] = fma(xs[r], bi, fma(ud[r], sc, u0[r])); + } + } + barrier(CLK_LOCAL_MEM_FENCE); } - acc = sub_group_reduce_add(acc); - total = fma(acc, wt, total); + ga = (q == 0) ? g0 : (ga + g0); + ua = (q == 0) ? u0 : (ua + u0); } - // 2. Shared expert slice (sh_w = 640 / TP -> sh_w/8 words, sh_w/32 groups) - if (sh_w > 0) { - const int swords = sh_w / 8, sgroups = sh_w / 32; - global const uint *swr = SDW + (long)col * swords; - global const ushort *ssr = SDS + (long)col * sgroups, *sbr = SDB + (long)col * sgroups; - global const ushort *sxa = SH_ACT + (long)r * sh_w; - float sacc = 0.0f; - for (int wi = lane; wi < swords; wi += 16) { - const uint pk = swr[wi]; - const int g = wi >> 2; - const ushort8 xv = vload8(0, sxa + wi * 8); - const float x0 = bf(xv.s0), x1 = bf(xv.s1), x2 = bf(xv.s2), x3 = bf(xv.s3); - const float x4 = bf(xv.s4), x5 = bf(xv.s5), x6 = bf(xv.s6), x7 = bf(xv.s7); - const float dot = x0 * (float)(pk & 15u) + x1 * (float)((pk >> 4) & 15u) + x2 * (float)((pk >> 8) & 15u) + - x3 * (float)((pk >> 12) & 15u) + x4 * (float)((pk >> 16) & 15u) + x5 * (float)((pk >> 20) & 15u) + - x6 * (float)((pk >> 24) & 15u) + x7 * (float)((pk >> 28) & 15u); - const float sx = x0 + x1 + x2 + x3 + x4 + x5 + x6 + x7; - sacc += bf(ssr[g]) * dot + bf(sbr[g]) * sx; + if (nb_ok) { + const int col = nb_col * 16 + lane; + for (int r = 0; r < 8; r++) { + const int j0 = sg_m * 8 + r; + if (j0 < m) MOE_ACT[(long)(p0 + j0) * 640 + col] = to_bf(bsilu(rbf(ga[r])) * rbf(ua[r])); } - sacc = sub_group_reduce_add(sacc); - total = fma(sacc, WTS[(long)r * 11 + 10], total); } - - if (lane == 0) OUT[(long)r * 2560 + col] = total; } -// 8. Logits Argmax, Log-Sum-Exp (MTP confidence), and Top-64 Candidates - -// Two-stage argmax + log-sum-exp over BF16 logits [R, V]: Stage 1: grid (256, R), WG = 256 -> PV[r*256 + g] = max, -KERNEL(256) void fn_logits_part(global const ushort *L, int V, global float *PV, global int *PI, global float *PS) { - local float bv[256], bs[256]; - local int bi[256]; - const int lid = get_local_id(0), gid = get_group_id(0), row = get_group_id(1); - const int per = (V + 255) / 256, lo = gid * per, hi = min(V, lo + per); - float best = -INFINITY; - int idx = 0x7fffffff; - for (int i = lo + lid; i < hi; i += 256) { - const float v = bf(L[(long)row * V + i]); - if (v > best) { - best = v; - idx = i; - } +// Per-pair Routed Down for R = 1..16 (K=640 -> 20 groups, N=2560 = 160 tiles). Grid: (160, R * min(10, local_e)). +KERNEL(64) void fn_moe_down_1(global const ushort *MOE_ACT, global const int *ACTIVE, global const int *N_ACT, + global const uint *DW, global const ushort *DS, global const ushort *DB, + global float *MOE_DOWN) { + local float kp[4][16]; + const int pair_idx = (int)get_group_id(1); + if (pair_idx >= N_ACT[1]) return; + const int le = ACTIVE[pair_idx] & 0x3FF; + const int nb_col = (int)get_group_id(0); + const int sg = get_sub_group_id(), lane = get_sub_group_local_id(); + const long nb = (long)le * 160 + nb_col; + global const ushort *xa = MOE_ACT + (long)pair_idx * 640; + float qacc = 0.0f; + for (int g = sg * 5; g < (sg + 1) * 5; g++) { + const short a_lo = (short)xa[g * 32 + lane]; + const short a_hi = (short)xa[g * 32 + 16 + lane]; + const float xs = dpas32_1(a_lo, a_hi, ONES_BF16, ONES_BF16); + int8 b0, b1; float sc, bi; + load_q4_tile(DW, DS, DB, nb, 20, g, lane, &b0, &b1, &sc, &bi); + const float d = dpas32_1(a_lo, a_hi, b0, b1); + qacc = fma(xs, bi, fma(d, sc, qacc)); } - bv[lid] = best; - bi[lid] = idx; + kp[sg][lane] = qacc; barrier(CLK_LOCAL_MEM_FENCE); - float gmax = bv[0]; - int gidx = bi[0]; - for (int i = 1; i < 256; i++) { - if (bv[i] > gmax || (bv[i] == gmax && bi[i] < gidx)) { - gmax = bv[i]; - gidx = bi[i]; - } - } - barrier(CLK_LOCAL_MEM_FENCE); - float s = 0.0f; - if (gmax > -INFINITY) { - for (int i = lo + lid; i < hi; i += 256) s += exp(bf(L[(long)row * V + i]) - gmax); - } - bs[lid] = s; - barrier(CLK_LOCAL_MEM_FENCE); - if (lid == 0) { - float tot = 0.0f; - for (int i = 0; i < 256; i++) tot += bs[i]; - PV[row * 256 + gid] = gmax; - PI[row * 256 + gid] = gidx; - PS[row * 256 + gid] = tot; + if (sg == 0) { + MOE_DOWN[(long)pair_idx * 2560 + nb_col * 16 + lane] = (((kp[0][lane] + kp[1][lane]) + kp[2][lane] ) + kp[3][lane]); } } -// Stage 2: grid (R), WG = 256 -> OUT_TOK[r] = argmax, OUT_BEST[r*4 + 0..2] = (max, lse, id_bits). -KERNEL(256) void fn_logits_best(global const float *PV, global const int *PI, global const float *PS, - global int *OUT_TOK, global float *OUT_BEST) { - local float bv[256], bs[256]; - local int bi[256]; - const int lid = get_local_id(0), row = get_group_id(0); - bv[lid] = PV[row * 256 + lid]; - bi[lid] = PI[row * 256 + lid]; - bs[lid] = PS[row * 256 + lid]; - barrier(CLK_LOCAL_MEM_FENCE); - if (lid == 0) { - float best = bv[0]; - int idx = bi[0]; - for (int i = 1; i < 256; i++) { - if (bv[i] > best || (bv[i] == best && bi[i] < idx)) { - best = bv[i]; - idx = bi[i]; - } +// Multi-row Expert-Grouped Routed Down on Xe2 DPAS: WG = 128 ([32 active pairs x 64 cols], K=640). +KERNEL(128) void fn_moe_down_dpas(global const ushort *MOE_ACT, global const int *EXP_GRP, global const int *N_ACT, + global const uint *DW, global const ushort *DS, global const ushort *DB, + global float *MOE_DOWN) { + local ushort xl[32][160]; + const int grp_idx = (int)get_group_id(1); + if (grp_idx >= N_ACT[0]) return; + const uint grp = (uint)EXP_GRP[grp_idx]; + const int le = (int)((grp >> 22) & 0x1FFu); + const int m = (int)((grp >> 16) & 0x3Fu); + const int p0 = (int)(grp & 0xFFFFu); + const int sg = get_sub_group_id(), lane = get_sub_group_local_id(), lid = get_local_id(0); + const int sg_m = sg >> 2, sg_n = sg & 3; + const int nb_col = (int)get_group_id(0) * 4 + sg_n; + const long nb = (long)le * 160 + nb_col; + const int m_pad = min(32, (m + 7) & ~7); + float8 acc0 = 0.0f, acc1 = 0.0f; + + for (int q = 0; q < 4; q++) { + for (int e = lid; e < m_pad * 40; e += 128) { + const int rr = e / 40, cc = (e % 40) * 4; + const ushort4 v = (rr < m) ? vload4(0, MOE_ACT + (long)(p0 + rr) * 640 + q * 160 + cc) : (ushort4)(0); + xl[rr][cc + 0] = v.s0; xl[rr][cc + 1] = v.s1; xl[rr][cc + 2] = v.s2; xl[rr][cc + 3] = v.s3; } - float sum = 0.0f; - if (best > -INFINITY) { - for (int i = 0; i < 256; i++) { - if (bv[i] > -INFINITY) sum += bs[i] * exp(bv[i] - best); + barrier(CLK_LOCAL_MEM_FENCE); + float8 q0 = 0.0f, q1 = 0.0f; + if (sg_m * 16 < m) { + for (int lg = 0; lg < 5; lg++) { + const int g = q * 5 + lg; + int8 b0, b1; float sc, bi; + load_q4_tile(DW, DS, DB, nb, 20, g, lane, &b0, &b1, &sc, &bi); + short8 a0_0, a0_1, a1_0, a1_1; + for (int r = 0; r < 8; r++) { + a0_0[r] = (short)xl[sg_m * 16 + r][lg * 32 + lane]; + a0_1[r] = (short)xl[sg_m * 16 + r][lg * 32 + 16 + lane]; + a1_0[r] = (short)xl[sg_m * 16 + 8 + r][lg * 32 + lane]; + a1_1[r] = (short)xl[sg_m * 16 + 8 + r][lg * 32 + 16 + lane]; + } + const float8 xs0 = dpas32_8(a0_0, a0_1, ONES_BF16, ONES_BF16); + const float8 d0 = dpas32_8(a0_0, a0_1, b0, b1); + for (int r = 0; r < 8; r++) q0[r] = fma(xs0[r], bi, fma(d0[r], sc, q0[r])); + if (sg_m * 16 + 8 < m) { + const float8 xs1 = dpas32_8(a1_0, a1_1, ONES_BF16, ONES_BF16); + const float8 d1 = dpas32_8(a1_0, a1_1, b0, b1); + for (int r = 0; r < 8; r++) q1[r] = fma(xs1[r], bi, fma(d1[r], sc, q1[r])); + } } } - OUT_TOK[row] = idx; - OUT_BEST[row * 4 + 0] = best; - OUT_BEST[row * 4 + 1] = best + log(sum); - OUT_BEST[row * 4 + 2] = as_float(idx); - OUT_BEST[row * 4 + 3] = 0.0f; + barrier(CLK_LOCAL_MEM_FENCE); + acc0 = (q == 0) ? q0 : (acc0 + q0); + acc1 = (q == 0) ? q1 : (acc1 + q1); + } + + const int col = nb_col * 16 + lane; + for (int r = 0; r < 8; r++) { + const int j0 = sg_m * 16 + r; + if (j0 < m) MOE_DOWN[(long)(p0 + j0) * 2560 + col] = acc0[r]; + const int j1 = j0 + 8; + if (j1 < m) MOE_DOWN[(long)(p0 + j1) * 2560 + col] = acc1[r]; } } -// Top-64 candidates of one BF16 logits row `L + row * V`: Stage 1 keeps top-64 per 256-slice, Stage 2 merges. Grid: -KERNEL(64) void fn_topk64_part(global const ushort *L, int V, int row, global float *TV, global int *TI) { - local float sv[64]; - local int si[64]; - const int tid = get_local_id(0), gid = get_group_id(0); - const int per = (V + 255) / 256, lo = gid * per, hi = min(V, lo + per); - float my_v[32]; - int my_i[32]; - int cnt = 0; - for (int i = lo + tid; i < hi; i += 64) { - my_v[cnt] = bf(L[(long)row * V + i]); - my_i[cnt] = i; - cnt++; +// 1..16-row Shared Expert SwiGLU Up on Xe2 DPAS (grid: (sh_w / 16, R), 128 B SLM). +KERNEL(64) void fn_moe_sh_up_1(global const ushort *X, + global const uint *GW, global const ushort *GS, global const ushort *GB, + global const uint *UW, global const ushort *US, global const ushort *UB, + global ushort *SH_ACT, int sh_w) { + local float gp[4][16], up[4][16]; + const int sg = get_sub_group_id(), lane = get_sub_group_local_id(); + const int nb = (int)get_group_id(0), row_i = (int)get_group_id(1); + if (nb >= sh_w / 16) return; + global const ushort *xr = X + (long)row_i * 2560; + float gq = 0.0f, uq = 0.0f; + for (int g = sg * 20; g < (sg + 1) * 20; g++) { + const short a_lo = (short)xr[g * 32 + lane]; + const short a_hi = (short)xr[g * 32 + 16 + lane]; + const float xs = dpas32_1(a_lo, a_hi, ONES_BF16, ONES_BF16); + int8 gb0, gb1, ub0, ub1; float gsc, gbi, usc, ubi; + load_q4_tile(GW, GS, GB, nb, 80, g, lane, &gb0, &gb1, &gsc, &gbi); + load_q4_tile(UW, US, UB, nb, 80, g, lane, &ub0, &ub1, &usc, &ubi); + const float gd = dpas32_1(a_lo, a_hi, gb0, gb1); + const float ud = dpas32_1(a_lo, a_hi, ub0, ub1); + gq = fma(xs, gbi, fma(gd, gsc, gq)); + uq = fma(xs, ubi, fma(ud, usc, uq)); } - for (int k = 0; k < 64; k++) { - float bv = -INFINITY; - int bi = 0x7fffffff, bj = -1; - for (int j = 0; j < cnt; j++) { - if (my_v[j] > bv || (my_v[j] == bv && my_i[j] < bi)) { - bv = my_v[j]; - bi = my_i[j]; - bj = j; + gp[sg][lane] = gq; + up[sg][lane] = uq; + barrier(CLK_LOCAL_MEM_FENCE); + if (sg == 0) { + const float gr = (((gp[0][lane] + gp[1][lane]) + gp[2][lane]) + gp[3][lane]); + const float ur = (((up[0][lane] + up[1][lane]) + up[2][lane]) + up[3][lane]); + SH_ACT[(long)row_i * sh_w + nb * 16 + lane] = to_bf(bsilu(rbf(gr)) * rbf(ur)); + } +} + +KERNEL(128) void fn_moe_sh_up_dpas(global const ushort *X, + global const uint *GW, global const ushort *GS, global const ushort *GB, + global const uint *UW, global const ushort *US, global const ushort *UB, + global ushort *SH_ACT, int sh_w, int R) { + local ushort xl[32][64]; + const int sg = get_sub_group_id(), lane = get_sub_group_local_id(), lid = get_local_id(0); + const int sg_m = sg >> 1, sg_n = sg & 1; + const int m0 = (int)get_group_id(1) * 32; + const int nb = (int)get_group_id(0) * 2 + sg_n; + const int col = nb * 16 + lane; + const int nb_max = sh_w / 16; + const bool nb_ok = (nb < nb_max); + const long safe_nb = nb_ok ? (long)nb : 0; + float8 ga = 0.0f, ua = 0.0f; + for (int q = 0; q < 4; q++) { + float8 g0 = 0.0f, u0 = 0.0f; + for (int g = q * 20; g < (q + 1) * 20; g += 2) { + for (int e = lid; e < 32 * 16; e += 128) { + const int rr = e >> 4, cc = (e & 15) * 4; + const ushort4 v = (m0 + rr < R) ? vload4(0, X + (long)(m0 + rr) * 2560 + g * 32 + cc) : (ushort4)(0); + xl[rr][cc + 0] = v.s0; xl[rr][cc + 1] = v.s1; xl[rr][cc + 2] = v.s2; xl[rr][cc + 3] = v.s3; } - } - sv[tid] = bv; - si[tid] = bi; - barrier(CLK_LOCAL_MEM_FENCE); - float wv = sv[0]; - int wi = si[0]; - for (int u = 1; u < 64; u++) { - if (sv[u] > wv || (sv[u] == wv && si[u] < wi)) { - wv = sv[u]; - wi = si[u]; + barrier(CLK_LOCAL_MEM_FENCE); + for (int sub = 0; sub < 2; sub++) { + short8 a0, a1; + const int kb = sub * 32; + for (int r = 0; r < 8; r++) { + a0[r] = (short)xl[sg_m * 8 + r][kb + lane]; + a1[r] = (short)xl[sg_m * 8 + r][kb + 16 + lane]; + } + const float8 xs = dpas32_8(a0, a1, ONES_BF16, ONES_BF16); + int8 b0 = 0, b1 = 0; + float sc = 0.0f, bi = 0.0f; + if (nb_ok) load_q4_tile(GW, GS, GB, safe_nb, 80, g + sub, lane, &b0, &b1, &sc, &bi); + const float8 gd = dpas32_8(a0, a1, b0, b1); + for (int r = 0; r < 8; r++) g0[r] = fma(xs[r], bi, fma(gd[r], sc, g0[r])); + if (nb_ok) load_q4_tile(UW, US, UB, safe_nb, 80, g + sub, lane, &b0, &b1, &sc, &bi); + const float8 ud = dpas32_8(a0, a1, b0, b1); + for (int r = 0; r < 8; r++) u0[r] = fma(xs[r], bi, fma(ud[r], sc, u0[r])); } + barrier(CLK_LOCAL_MEM_FENCE); } - barrier(CLK_LOCAL_MEM_FENCE); - if (bj >= 0 && my_i[bj] == wi) my_v[bj] = -INFINITY; - if (tid == 0) { - TV[gid * 64 + k] = wv; - TI[gid * 64 + k] = wi; + ga = (q == 0) ? g0 : (ga + g0); + ua = (q == 0) ? u0 : (ua + u0); + } + if (col < sh_w) { + for (int r = 0; r < 8; r++) { + const int row0 = m0 + sg_m * 8 + r; + if (row0 < R) SH_ACT[(long)row0 * sh_w + col] = to_bf(bsilu(rbf(ga[r])) * rbf(ua[r])); } } } -// Convert BF16 row [V] to FP32 row [V] (for full-vocab host sampling when top_k == 0 or top_k > 64). -KERNEL(256) void fn_bf16_to_f32(global const ushort *IN, global float *OUT, int N) { - const int i = get_global_id(0); - if (i < N) OUT[i] = bf(IN[i]); +// Pure-bandwidth MoE Combine in exact ascending slot order (0..9 + shared slot 10): Grid (10, R), WG = 256. +KERNEL(256) void fn_moe_combine(global const float *MOE_DOWN, global const float *SH_OUT, + global const int *ACTIVE, global const int *ROW_LIST, global const float *WTS, + global float *OUT, int has_sh, int R) { + const int col = (int)get_group_id(0) * 256 + (int)get_local_id(0); + const int r = (int)get_group_id(1); + if (col >= 2560 || r >= R) return; + float total = 0.0f; + for (int c = 0; c < 10; c++) { + const int pair_idx = ROW_LIST[(long)r * 11 + c]; + if (pair_idx < 0) break; + const int slot = (ACTIVE[pair_idx] >> 10) & 0xF; + total = fma(MOE_DOWN[(long)pair_idx * 2560 + col], WTS[(long)r * 11 + slot], total); + } + if (has_sh) { + total = fma(SH_OUT[(long)r * 2560 + col], WTS[(long)r * 11 + 10], total); + } + OUT[(long)r * 2560 + col] = total; } diff --git a/zig/load_prefetch_host.zig b/zig/load_prefetch_host.zig index 5ff7609096f..4db969c24e5 100644 --- a/zig/load_prefetch_host.zig +++ b/zig/load_prefetch_host.zig @@ -133,6 +133,26 @@ test "load prefetch: every family balances allocation failures while readers may } } +test "load prefetch: deepseek's pack reader allocates the same count every run" { + const Control = struct { + fn run(a: std.mem.Allocator, family: Family, input: *Fixture) !void { + var f = input.*; + f.ck.gpa = a; + var reading = try begin(family, &f, 1, 3); + defer reading.deinit(); + _ = try reading.check(); + } + }; + var f = try fixture(.deepseek); + defer f.deinit(); + var first = std.testing.FailingAllocator.init(t.allocator, .{}); + try Control.run(first.allocator(), .deepseek, &f); + var second = std.testing.FailingAllocator.init(t.allocator, .{}); + try Control.run(second.allocator(), .deepseek, &f); + try t.expectEqual(first.alloc_index, second.alloc_index); + try t.expectEqual(first.allocated_bytes, second.allocated_bytes); +} + test "load prefetch: new CUDA ports are opt-in while donor and GLM defaults stay unchanged" { try t.expectEqual(@as(usize, 0), try ahead.optInCount(null)); for (0..17) |count| { diff --git a/zig/prefill_widths_qwen_host.zig b/zig/prefill_widths_qwen_host.zig index 164692294b8..6f0fbd70505 100644 --- a/zig/prefill_widths_qwen_host.zig +++ b/zig/prefill_widths_qwen_host.zig @@ -10,6 +10,17 @@ const Engine = struct { scratch_rows: usize = q.engine.grid_rows, fail: bool = false, stream: ?cuda.Stream = null, + layers: [2]void = .{ {}, {} }, + taps: [8]u32 = undefined, + n_taps: usize = 0, + learning: ?*const anyopaque = null, + mlp: ?*const anyopaque = null, + pockets: struct { + pub fn any(_: @This()) bool { + return false; + } + } = .{}, + int8: struct { on: bool = false } = .{}, pub fn forward(e: *@This(), _: anytype, _: []const u32, _: q.engine.Keep) !void { if (e.fail) return error.PlantedForward; if (e.stream) |stream| try stream.synchronize(); diff --git a/zig/qwen27_bank_boundary_host.zig b/zig/qwen27_bank_boundary_host.zig index ecfa25e864b..cb3e51740a0 100644 --- a/zig/qwen27_bank_boundary_host.zig +++ b/zig/qwen27_bank_boundary_host.zig @@ -8,6 +8,9 @@ test "qwen27 bank boundary: a pending keep rejects resizing and trimming" { runner.active = @splat(0x17); runner.gdn.before = null; runner.gdn.before_slots = 7; + runner.gdn.scratch = @TypeOf(runner.gdn).emptyScratch(std.testing.allocator); + runner.gdn.lease = null; + defer runner.gdn.deinitScratch(); const round: q.round_plan.Round = undefined; try std.testing.expectError(error.RoundNotReady, runner.verify(&round)); try std.testing.expectError(error.RoundNotReady, runner.advance(&round, .all)); diff --git a/zig/qwen27_core.zig b/zig/qwen27_core.zig index 45c3f92c442..916ceeaa248 100644 --- a/zig/qwen27_core.zig +++ b/zig/qwen27_core.zig @@ -43,3 +43,4 @@ pub const bf16_topk_gpu = @import("bf16_topk_gpu"); pub const tree_commit_gpu = @import("tree_commit_gpu"); pub const tree_slots = @import("src/core/tree_slots.zig"); +pub const recurrent_workspace = @import("src/core/recurrent_workspace.zig"); diff --git a/zig/qwen27_speed_core.zig b/zig/qwen27_speed_core.zig index 2af57fa62d3..49c70e2b9bc 100644 --- a/zig/qwen27_speed_core.zig +++ b/zig/qwen27_speed_core.zig @@ -1,5 +1,6 @@ //! Shared host planning and profiling used by the recording Metal fixture. 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"); diff --git a/zig/qwen35_verify_host.zig b/zig/qwen35_verify_host.zig index 9e3e042308a..03c56ee7572 100644 --- a/zig/qwen35_verify_host.zig +++ b/zig/qwen35_verify_host.zig @@ -9,6 +9,7 @@ pub const Trace = struct { pub var count: usize = 0; pub var prompts: usize = 0; pub var grouped: usize = 0; + pub var segmented: usize = 0; // segmented launches of two or more parts, apart from the grouped kernels fn record(f: cuda.abi.Function, gx: u32, shared: u32, args: ?[*]?*anyopaque) cuda.abi.Result { const id = @intFromPtr(f); if (id == 4) { @@ -34,6 +35,7 @@ pub const Trace = struct { } if (id == 8) { const segs = @as(*const cuda.qlinear.Segs, @ptrCast(@alignCast(a[2].?))).*; + if (segs.count > 1) segmented += 1; for (segs.s[0..@intCast(segs.count)]) |seg| { calls[count] = .{ .id = id, .x = x, .xs = xs, .out = seg.p.out, .rows = rows, .sk = seg.p.sk, .row_tiles = 1, .grid = gx, .shared = shared }; count += 1; diff --git a/zig/residency_owner_tests.zig b/zig/residency_owner_tests.zig index d0566adffb2..de150cbf761 100644 --- a/zig/residency_owner_tests.zig +++ b/zig/residency_owner_tests.zig @@ -8,6 +8,7 @@ pub const checkpoint_host = @import("src/core/checkpoint.zig"); pub const Checkpoint = checkpoint_host.Checkpoint; pub const gpu_profile = @import("src/core/gpu_profile.zig"); pub const tree_slots = @import("src/core/tree_slots.zig"); +pub const recurrent_workspace = @import("src/core/recurrent_workspace.zig"); pub const draft_ops = @import("draft_ops"); pub const row_projection = @import("src/core/row_projection.zig"); pub const lane_projection = @import("src/core/lane_projection.zig"); @@ -58,6 +59,7 @@ test "residency owner GLM: actual arena slots tower and snapshots match live uni e.k = &kernels; e.fused_route = true; e.draft_vocab = 8; + e.dflash = null; e.ep = null; e.ev = 0; e.event = .{}; @@ -143,6 +145,7 @@ test "residency owner GLM: zero and a failed bound never publish a set or keepal e.arena = .{ .device = device, .gpa = a }; defer e.arena.deinit(); e.vision = null; + e.dflash = null; e.residency = null; e.residency_enabled = try glm.residency.policy.flag(if (enabled) "1" else "0"); e.limit = std.mem.zeroes(@TypeOf(e.limit)); diff --git a/zig/residency_qwen27_tests.zig b/zig/residency_qwen27_tests.zig index f0509758952..2e80f98d872 100644 --- a/zig/residency_qwen27_tests.zig +++ b/zig/residency_qwen27_tests.zig @@ -20,9 +20,9 @@ test "residency owner Qwen27: actual lazy rollback bank joins, grows and leaves const device = record.device(); const shape = try abi.Shape.init(geometry()); const budget = try Budget.init(shape, 1, 3, 16); - var pool: bank.Pool = .{ .budget = budget, .buffers = try bank.Pool.allocateBuffers(device, budget), .kernels = undefined }; + var pool: bank.Pool = .{ .budget = budget, .buffers = try bank.Pool.allocateBuffers(device, budget), .kernels = undefined, .scratch = bank.Pool.emptyScratch(a) }; defer { - pool.releaseBefore(); + pool.deinitScratch(); for (pool.buffers) |b| b.deinit(); } var owner = (try mtl.resident.Resident.hold(a, std.testing.io, device, record.queue(), &pool.buffers, "qwen27")).?; @@ -192,8 +192,9 @@ test "residency owner Qwen27: native inventory and lazy owners match every alloc .capacity = 16, }; const budget = try Budget.init(try abi.Shape.init(model.config), 1, 1, 16); - r.gdn = .{ .budget = budget, .buffers = try bank.Pool.allocateBuffers(device, budget), .kernels = undefined }; + r.gdn = .{ .budget = budget, .buffers = try bank.Pool.allocateBuffers(device, budget), .kernels = undefined, .scratch = bank.Pool.emptyScratch(a) }; defer for (r.gdn.buffers) |b| b.deinit(); + defer r.gdn.deinitScratch(); const limits: attn.Limits = .{ .rows = 16, .streams = 1, .keys = 32 }; r.scratch = try attn.Scratch.init(device, limits); defer r.scratch.deinit(); diff --git a/zig/src/cluster/bringup.zig b/zig/src/cluster/bringup.zig index ac5c57ffb5a..e0e69a083cb 100644 --- a/zig/src/cluster/bringup.zig +++ b/zig/src/cluster/bringup.zig @@ -113,12 +113,19 @@ pub const Live = struct { opts: Options, /// This node's beat counter when it set its plan; a mismatch is reported once a later beat carried the plan. plan_beat: ?u64 = null, - /// This node's beat counter when it marked itself planned; up once a later beat carried the mark. - planned_beat: ?u64 = null, + /// The agreed view when this node marked itself planned, before a goodbye can change membership. + planned: ?Planned = null, /// Membership events already read. seen: usize = 0, culprit: Culprit = .{}, + const Planned = struct { + beat: u64, + leader: node.NodeId, + epoch: u64, + view: u64, + }; + /// `inv.name` is this node's name in the file; its id is the name's, so each node checks the others by `names`. pub fn init(gpa: Allocator, inv: node.Inventory, t: transport.Transport, names: []const []const u8, plan: u64, opts: Options) Live { var me = inv; @@ -154,12 +161,12 @@ pub const Live = struct { } if (l.m.me.plan == l.plan) { try l.checkPlans(); - if (l.planned_beat == null and l.m.ids.items.len == n and l.m.agreed(l.plan)) { + if (l.planned == null and l.m.ids.items.len == n and l.m.agreed(l.plan)) { l.m.setProgress(.planned, 0); - l.planned_beat = l.m.me.counter; + l.planned = .{ .beat = l.m.me.counter, .leader = l.m.leader, .epoch = l.m.me.epoch, .view = l.m.me.digest }; } - if (l.planned_beat) |c| if (l.m.me.counter > c and l.allPlanned()) { - return .{ .nodes = @intCast(n), .leader = l.m.leader, .epoch = l.m.me.epoch, .plan = l.plan, .agreed_ms = (now - start) / std.time.ns_per_ms, .view = l.m.me.digest }; + if (l.planned) |planned| if (l.m.me.counter > planned.beat and l.allPlanned(planned)) { + return .{ .nodes = @intCast(n), .leader = planned.leader, .epoch = planned.epoch, .plan = l.plan, .agreed_ms = (now - start) / std.time.ns_per_ms, .view = planned.view }; }; } if (l.nextLost()) |x| { @@ -226,12 +233,13 @@ pub const Live = struct { } } - /// Every node marked planned with this plan; one that has since said goodbye counts (it agreed before leaving). - fn allPlanned(l: *Live) bool { + /// Count planned acknowledgments for this view, including peers that said goodbye after agreeing. + fn allPlanned(l: *Live, planned: Planned) bool { if (l.m.me.phase != .planned) return false; var k: usize = 1; for (l.m.members.items) |x| { const e = x.entry; + if (e.epoch != planned.epoch or e.digest != planned.view) continue; if (e.plan == l.plan and e.phase == .planned and (e.state == .alive or e.state == .suspect or e.state == .left)) k += 1; } return k >= l.names.len; diff --git a/zig/src/cluster/bringup_test.zig b/zig/src/cluster/bringup_test.zig index 0671b152a86..7e869c2a62b 100644 --- a/zig/src/cluster/bringup_test.zig +++ b/zig/src/cluster/bringup_test.zig @@ -169,6 +169,8 @@ test "two ranks settle on one lockstep clock and agree on one plan and view; a g const lost = p.ranks[1].lost.?; try std.testing.expectEqualStrings("a", lost.name.str()); try std.testing.expectEqual(@import("membership.zig").State.left, lost.state); + try std.testing.expectEqual(@as(usize, 1), p.ranks[1].live.m.ids.items.len); + try std.testing.expect(p.ranks[1].live.m.me.digest != y.view); try std.testing.expectEqualStrings("a", p.ranks[1].live.nameOf(node.idFrom("a"))); } diff --git a/zig/src/core/checkpoint_direct.zig b/zig/src/core/checkpoint_direct.zig index 1c4568eb9fe..3e671e97382 100644 --- a/zig/src/core/checkpoint_direct.zig +++ b/zig/src/core/checkpoint_direct.zig @@ -79,6 +79,15 @@ pub const Layers = struct { l.ahead = true; } + /// The tensors `get` returns from the mapping again (a layer too large to read whole), after any read under way. + pub fn mapped(l: *Layers) void { + const ck = l.ck orelse return; + l.pair.wait() catch {}; + l.ahead = false; + ck.copies = null; + l.current = null; + } + /// `enter` on `fmt`'s prefix for layer `i`, with layer `next`'s read begun (none on the last). pub fn layerAt(l: *Layers, comptime fmt: []const u8, i: usize, next: ?usize) !void { if (l.ck == null) return; @@ -268,6 +277,36 @@ test "layerAt names a layer and the next; repoint moves a map-first loader's vie } } +test "mapped puts a layer back on the mapping between read layers, the next one read again" { + const io = std.testing.io; + const gpa = std.testing.allocator; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const names = [_][]const u8{ "layers.0.a", "layers.1.a", "layers.2.a" }; + const image = try testImage(gpa, &names, 2 * 4096 + 9); + defer gpa.free(image); + try tmp.dir.writeFile(io, .{ .sub_path = "model.safetensors", .data = image }); + var path: [64]u8 = undefined; + var ck = try Checkpoint.openModel(gpa, io, try std.fmt.bufPrint(&path, ".zig-cache/tmp/{s}", .{tmp.sub_path})); + defer ck.close(); + var mapped: [3][]const u8 = undefined; + for (names, &mapped) |n, *m| m.* = (try ck.get(n)).bytes; + var l = Layers.init(gpa, &ck, 2); + defer l.deinit(); + if (!l.on()) return error.SkipZigTest; + // layer 0 read with layer 1's read ahead begun, then layer 1 kept on the mapping, then layer 2 read + try l.enter("layers.0.", "layers.1."); + try std.testing.expect((try ck.get("layers.0.a")).bytes.ptr != mapped[0].ptr); + l.mapped(); + try std.testing.expectEqual(mapped[1].ptr, (try ck.get("layers.1.a")).bytes.ptr); + try l.enter("layers.2.", null); + const two = try ck.get("layers.2.a"); + try std.testing.expect(two.bytes.ptr != mapped[2].ptr); + try std.testing.expectEqualSlices(u8, mapped[2], two.bytes); + l.mapped(); + try std.testing.expectEqual(mapped[2].ptr, (try ck.get("layers.2.a")).bytes.ptr); +} + test "a shard shortened after open stops the layer it cuts with EndOfFile, the layer before it read" { const io = std.testing.io; const gpa = std.testing.allocator; diff --git a/zig/src/core/checkpoint_metal.zig b/zig/src/core/checkpoint_metal.zig index b51deb4f6cb..39e081ba863 100644 --- a/zig/src/core/checkpoint_metal.zig +++ b/zig/src/core/checkpoint_metal.zig @@ -47,6 +47,7 @@ pub const Checkpoint = struct { shards: std.ArrayList(Shard) = .empty, tensors: std.StringHashMapUnmanaged(Tensor) = .empty, deferred: std.StringHashMapUnmanaged(Deferred) = .empty, + selected_bytes: usize = 0, // what addFileSelected would hold: each file's span from its first selected tensor to its last files: std.ArrayList(File) = .empty, pub fn init(allocator: std.mem.Allocator) Checkpoint { @@ -91,7 +92,6 @@ pub const Checkpoint = struct { defer arena.deinit(); const entries = try st.parseHeaderPrefix(arena.allocator(), header, data_len, selected); if (entries.count() == 0) return; - if (later) |pick| return self.split(device, fd, &held, data_start, entries, prefix, pick); var begin: usize = if (selected == null) 0 else data_len; var limit: usize = if (selected == null) data_len else 0; for (entries.values()) |e| { @@ -99,6 +99,8 @@ pub const Checkpoint = struct { limit = @max(limit, e.end); } const bytes = limit - begin; + self.selected_bytes += bytes; + if (later) |pick| return self.split(device, fd, &held, data_start, entries, prefix, pick); const buffer = try device.buffer(@max(bytes, 16), mtl.ResourceOptions.shared | mtl.ResourceOptions.untracked); var transferred = false; errdefer if (!transferred) buffer.deinit(); @@ -376,6 +378,7 @@ test "full and selected checkpoint views retain data, ownership and relative off try selected.addFileSelected(device, path, "", "text."); try std.testing.expectEqual(@as(usize, 30), full.residentBytes()); try std.testing.expectEqual(@as(usize, 26), selected.residentBytes()); + try std.testing.expectEqual(selected.residentBytes(), selected.selected_bytes); const a = try full.get("text.weight"); const b = try selected.get("text.weight"); try std.testing.expectEqual(@as(usize, 4), a.offset); @@ -410,6 +413,7 @@ test "a split checkpoint keeps later tensors in the file, packs the rest, and st defer split.deinit(); try split.addFileSplit(device, path, "", "text.", Weights.later); try std.testing.expectEqual(@as(usize, 2), split.residentBytes()); + try std.testing.expectEqual(@as(usize, 26), split.selected_bytes); // the span addFileSelected holds for "text." try std.testing.expect(split.has("text.weight")); try std.testing.expectError(error.DeferredTensor, split.get("text.weight")); try std.testing.expectEqualSlices(u16, (try full.get("text.scales")).host(u16), (try split.get("text.scales")).host(u16)); diff --git a/zig/src/core/checkpoint_read_ahead.zig b/zig/src/core/checkpoint_read_ahead.zig index 7492ab6e8d2..13e212e345f 100644 --- a/zig/src/core/checkpoint_read_ahead.zig +++ b/zig/src/core/checkpoint_read_ahead.zig @@ -175,7 +175,14 @@ fn packInner(gpa: std.mem.Allocator, io: std.Io, p: anytype, prefix: []const u8, var path: ?[:0]u8 = null; for (p.names.keys(), p.names.values()) |name, info| { if (info.file != i or !std.mem.startsWith(u8, name, prefix) or info.nbytes == 0) continue; - if (path == null) path = try std.fmt.allocPrintSentinel(a, "{s}/{s}", .{ p.dir, file }, 0); + if (path == null) { + // one exact-size alloc: allocPrintSentinel's growing writer ties the alloc count to remap + const buf = try a.allocSentinel(u8, p.dir.len + 1 + file.len, 0); + @memcpy(buf[0..p.dir.len], p.dir); + buf[p.dir.len] = '/'; + @memcpy(buf[p.dir.len + 1 ..][0..file.len], file); + path = buf; + } const end = try std.math.add(u64, info.start, info.nbytes); var lo = info.start; while (lo < end) { diff --git a/zig/src/core/contract.zig b/zig/src/core/contract.zig index 4fb42f60662..8ba693c4e59 100644 --- a/zig/src/core/contract.zig +++ b/zig/src/core/contract.zig @@ -45,6 +45,7 @@ test { _ = @import("contract/simd_pairs_records.zig"); _ = @import("contract/simd_half_records.zig"); _ = @import("contract/glm_rows_records.zig"); + _ = @import("contract/glm_dflash_records.zig"); _ = @import("contract/row_wide_records.zig"); _ = @import("contract/nemotron_experts_records.zig"); _ = @import("contract/moss_image_records.zig"); diff --git a/zig/src/core/contract/exl3_prompt_pending.zig b/zig/src/core/contract/exl3_prompt_pending.zig index aff7493ce36..7a4e979cbfa 100644 --- a/zig/src/core/contract/exl3_prompt_pending.zig +++ b/zig/src/core/contract/exl3_prompt_pending.zig @@ -5,6 +5,8 @@ const limits = @import("limits.zig"); pub const records = [_]registry.CudaRecord{ .{ .launch = .{ .name = "exl3_experts tf_exl3_prompt_gu", .symbol = "tf_exl3_prompt_gu", .image = "exl3_experts", .threads = 256 }, .usage = registry.none }, .{ .launch = .{ .name = "exl3_experts tf_exl3_prompt_down", .symbol = "tf_exl3_prompt_down", .image = "exl3_experts", .threads = 256 }, .usage = registry.none }, + .{ .launch = .{ .name = "exl3_experts tf_exl3_prompt_gu_k6", .symbol = "tf_exl3_prompt_gu_k6", .image = "exl3_experts", .threads = 256 }, .usage = registry.none }, + .{ .launch = .{ .name = "exl3_experts tf_exl3_prompt_down_k6", .symbol = "tf_exl3_prompt_down_k6", .image = "exl3_experts", .threads = 256 }, .usage = registry.none }, }; pub fn owns(name: []const u8) bool { @@ -16,5 +18,5 @@ test "EXL3 prompt: unmeasured compiler usage stays pending" { for (records) |r| for ([_]?limits.Nvcc{ null, .{ .major = 13, .minor = 0 }, .{ .major = 13, .minor = 1 }, .{ .major = 13, .minor = 2 }, .{ .major = 13, .minor = 3 } }) |version| { try std.testing.expectEqualDeep(registry.none, registry.usageFor(r, version)); }; - try std.testing.expectEqual(@as(usize, 10), try registry.checkCuda(std.testing.allocator, &records, true)); + try std.testing.expectEqual(@as(usize, 20), try registry.checkCuda(std.testing.allocator, &records, true)); } diff --git a/zig/src/core/contract/glm_dflash_records.zig b/zig/src/core/contract/glm_dflash_records.zig new file mode 100644 index 00000000000..0c5f125f519 --- /dev/null +++ b/zig/src/core/contract/glm_dflash_records.zig @@ -0,0 +1,14 @@ +//! GLM-5.3-Flash's DFlash2 drafter: attention (a row's heads of a KV head over a key chunk, then the merge) and top-k. +const std = @import("std"); +const M = @import("limits.zig").MetalLaunch; +pub const records = [_]M{ + .{ .name = "glm dflash2 attention glm_draft_attend", .threads = 32, .tg_memory = 0, .reserved = 32 }, + .{ .name = "glm dflash2 attention glm_draft_attend_merge", .threads = 32, .tg_memory = 0, .reserved = 32 }, + .{ .name = "glm dflash2 topk glm_draft_topk", .threads = 512, .tg_memory = 10080, .reserved = 512 }, + .{ .name = "glm dflash2 accept glm_draft_accept", .threads = 32, .tg_memory = 0, .reserved = 32 }, + .{ .name = "glm dflash2 follow glm_draft_follow", .threads = 32, .tg_memory = 0, .reserved = 32 }, +}; + +test "the GLM drafter launches fit every Apple family" { + try std.testing.expectEqual(@as(usize, 0), try @import("registry.zig").checkMetal(std.testing.allocator, &records, true)); +} diff --git a/zig/src/core/contract/idol_cuda_sets.zig b/zig/src/core/contract/idol_cuda_sets.zig index 35104f2a939..fcafb69a875 100644 --- a/zig/src/core/contract/idol_cuda_sets.zig +++ b/zig/src/core/contract/idol_cuda_sets.zig @@ -1,6 +1,8 @@ //! Every Idol component's CUDA records (nvcc 13.0, each SM), joined in the pipeline's order for registry.zig. -pub const cuda = @import("idol_cuda_records.zig").cuda; +pub const cuda = @import("idol_cuda_records.zig").cuda ++ + @import("idol_decoder_cuda_records.zig").cuda; test { _ = @import("idol_cuda_records.zig"); + _ = @import("idol_decoder_cuda_records.zig"); } diff --git a/zig/src/core/contract/idol_decoder_cuda_records.zig b/zig/src/core/contract/idol_decoder_cuda_records.zig new file mode 100644 index 00000000000..7d5132049cc --- /dev/null +++ b/zig/src/core/contract/idol_decoder_cuda_records.zig @@ -0,0 +1,20 @@ +//! Idol's decoder kernels on CUDA (idol_decoder.cu): every SM's compile records from nvcc 13.0, the release compiler. +const registry = @import("registry.zig"); + +/// nvcc 13.0's usage (cuobjdump -res-usage of the glue-flag image; sm_120's 1024 reserved shared bytes left out). +pub const cuda = [_]registry.CudaRecord{ + .{ .launch = .{ .name = "idol decoder tf_idol_dec_embed", .symbol = "tf_idol_dec_embed", .image = "idol_decoder", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 20, .static = 0, .bound = 256 }, .{ .regs = 22, .static = 0, .bound = 256 }, .{ .regs = 22, .static = 0, .bound = 256 }, .{ .regs = 22, .static = 0, .bound = 256 }, .{ .regs = 22, .static = 0, .bound = 256 } } }, + .{ .launch = .{ .name = "idol decoder tf_idol_dec_half", .symbol = "tf_idol_dec_half", .image = "idol_decoder", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 12, .static = 0, .bound = 256 }, .{ .regs = 12, .static = 0, .bound = 256 }, .{ .regs = 12, .static = 0, .bound = 256 }, .{ .regs = 12, .static = 0, .bound = 256 }, .{ .regs = 12, .static = 0, .bound = 256 } } }, + .{ .launch = .{ .name = "idol decoder tf_idol_dec_kv", .symbol = "tf_idol_dec_kv", .image = "idol_decoder", .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 = 40, .static = 0, .bound = 256 }, .{ .regs = 40, .static = 0, .bound = 256 } } }, + .{ .launch = .{ .name = "idol decoder tf_idol_dec_heads", .symbol = "tf_idol_dec_heads", .image = "idol_decoder", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 21, .static = 0, .bound = 256 }, .{ .regs = 21, .static = 0, .bound = 256 }, .{ .regs = 21, .static = 0, .bound = 256 }, .{ .regs = 21, .static = 0, .bound = 256 }, .{ .regs = 21, .static = 0, .bound = 256 } } }, + .{ .launch = .{ .name = "idol decoder tf_idol_dec_attention", .symbol = "tf_idol_dec_attention", .image = "idol_decoder", .threads = 256, .dynamic = 36864, .min_sm = 80 }, .usage = .{ .{ .regs = 128, .static = 0, .bound = 256 }, .{ .regs = 128, .static = 0, .bound = 256 }, .{ .regs = 128, .static = 0, .bound = 256 }, .{ .regs = 120, .static = 0, .bound = 256 }, .{ .regs = 120, .static = 0, .bound = 256 } } }, + .{ .launch = .{ .name = "idol decoder tf_idol_dec_few", .symbol = "tf_idol_dec_few", .image = "idol_decoder", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 128, .static = 2352, .bound = 256 }, .{ .regs = 128, .static = 2352, .bound = 256 }, .{ .regs = 128, .static = 2352, .bound = 256 }, .{ .regs = 128, .static = 2352, .bound = 256 }, .{ .regs = 128, .static = 2352, .bound = 256 } } }, +}; + +test "Idol decoder CUDA: measured launches fit their physical resource limits" { + const t = @import("std").testing; + for (cuda) |r| { + for (r.usage) |u| try t.expect(u.regs > 0); + try t.expectEqual(@as(usize, 0), try registry.checkCuda(t.allocator, &.{r}, true)); + } +} diff --git a/zig/src/core/contract/idol_records.zig b/zig/src/core/contract/idol_records.zig index 22a12df75a4..124347e4e13 100644 --- a/zig/src/core/contract/idol_records.zig +++ b/zig/src/core/contract/idol_records.zig @@ -1,7 +1,7 @@ -//! Idol's launches, each source-reserved: the denoiser's (idol.metal, idol_attention.metal), then idol_decoder.metal's. +//! Idol's launches, each source-reserved: the denoiser's (idol.metal, idol_attention.metal), the decoders', the VAE's. const std = @import("std"); const M = @import("limits.zig").MetalLaunch; -pub const records = denoiser ++ decoder; +pub const records = denoiser ++ decoder ++ vae; const denoiser = [_]M{ .{ .name = "idol id_linear_00", .threads = 256, .tg_memory = 0, .reserved = 256 }, @@ -42,7 +42,18 @@ const decoder = [_]M{ .{ .name = "idol decoder dec_attention_11", .threads = 128, .tg_memory = 0, .reserved = 128 }, }; +const vae = [_]M{ + .{ .name = "idol vae iv_conv_in", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "idol vae iv_conv", .threads = 128, .tg_memory = 26624, .reserved = 128 }, + .{ .name = "idol vae iv_wino", .threads = 512, .tg_memory = 32768, .reserved = 512 }, + .{ .name = "idol vae iv_norm", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "idol vae iv_group_part", .threads = 512, .tg_memory = 2048, .reserved = 512 }, + .{ .name = "idol vae iv_group_finish", .threads = 1024, .tg_memory = 0, .reserved = 1024 }, + .{ .name = "idol vae iv_attention", .threads = 128, .tg_memory = 5168, .reserved = 128 }, + .{ .name = "idol vae iv_tokens", .threads = 256, .tg_memory = 0, .reserved = 256 }, +}; + test "the Idol launches fit every Apple family, one record a pipeline" { try std.testing.expectEqual(@as(usize, 0), try @import("registry.zig").checkMetal(std.testing.allocator, &records, true)); - try std.testing.expectEqual(@as(usize, 24 + 9), records.len); + try std.testing.expectEqual(@as(usize, 24 + 9 + 8), records.len); } diff --git a/zig/src/core/contract/inkling2_cuda_records.zig b/zig/src/core/contract/inkling2_cuda_records.zig index cd79f3aec15..a448fb73d8d 100644 --- a/zig/src/core/contract/inkling2_cuda_records.zig +++ b/zig/src/core/contract/inkling2_cuda_records.zig @@ -1,6 +1,7 @@ //! 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"); -pub const cuda = attn.cuda; -pub const cuda_132 = attn.cuda_132; -pub const cuda_133 = attn.cuda_133; +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; diff --git a/zig/src/core/contract/inkling2_ops_records.zig b/zig/src/core/contract/inkling2_ops_records.zig new file mode 100644 index 00000000000..e5ce0103f66 --- /dev/null +++ b/zig/src/core/contract/inkling2_ops_records.zig @@ -0,0 +1,40 @@ +//! Inkling 2's inkling2_ops, inkling2_rows 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), 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_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 } } }, + .{ .launch = .{ .name = "inkling2 ops tf_ink2_gateup", .symbol = "tf_ink2_gateup", .image = "inkling2_ops", .threads = 32, .min_sm = 80 }, .usage = .{ .{ .regs = 38, .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 } } }, + .{ .launch = .{ .name = "inkling2 ops tf_ink2_conv", .symbol = "tf_ink2_conv", .image = "inkling2_ops", .threads = 128, .min_sm = 80 }, .usage = .{ .{ .regs = 48, .static = 0, .bound = 128 }, .{ .regs = 40, .static = 0, .bound = 128 }, .{ .regs = 40, .static = 0, .bound = 128 }, .{ .regs = 48, .static = 0, .bound = 128 }, .{ .regs = 48, .static = 0, .bound = 128 } } }, + .{ .launch = .{ .name = "inkling2 ops tf_ink2_conv_rewind", .symbol = "tf_ink2_conv_rewind", .image = "inkling2_ops", .threads = 128, .min_sm = 80 }, .usage = .{ .{ .regs = 26, .static = 0, .bound = 128 }, .{ .regs = 28, .static = 0, .bound = 128 }, .{ .regs = 28, .static = 0, .bound = 128 }, .{ .regs = 34, .static = 0, .bound = 128 }, .{ .regs = 34, .static = 0, .bound = 128 } } }, + .{ .launch = .{ .name = "inkling2 ops tf_ink2_softcap", .symbol = "tf_ink2_softcap", .image = "inkling2_ops", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 16, .static = 0, .bound = 0 }, .{ .regs = 18, .static = 0, .bound = 0 }, .{ .regs = 18, .static = 0, .bound = 0 }, .{ .regs = 16, .static = 0, .bound = 0 }, .{ .regs = 16, .static = 0, .bound = 0 } } }, + .{ .launch = .{ .name = "inkling2 ops tf_ink2_top1", .symbol = "tf_ink2_top1", .image = "inkling2_ops", .threads = 1024, .min_sm = 80 }, .usage = .{ .{ .regs = 13, .static = 256, .bound = 1024 }, .{ .regs = 16, .static = 256, .bound = 1024 }, .{ .regs = 16, .static = 256, .bound = 1024 }, .{ .regs = 18, .static = 256, .bound = 1024 }, .{ .regs = 18, .static = 256, .bound = 1024 } } }, + .{ .launch = .{ .name = "inkling2 ops tf_ink2_race1", .symbol = "tf_ink2_race1", .image = "inkling2_ops", .threads = 1024, .min_sm = 80 }, .usage = .{ .{ .regs = 19, .static = 256, .bound = 1024 }, .{ .regs = 20, .static = 256, .bound = 1024 }, .{ .regs = 20, .static = 256, .bound = 1024 }, .{ .regs = 24, .static = 256, .bound = 1024 }, .{ .regs = 24, .static = 256, .bound = 1024 } } }, + .{ .launch = .{ .name = "inkling2 ops tf_ink2_tobf", .symbol = "tf_ink2_tobf", .image = "inkling2_ops", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 12, .static = 0, .bound = 0 }, .{ .regs = 12, .static = 0, .bound = 0 }, .{ .regs = 12, .static = 0, .bound = 0 }, .{ .regs = 12, .static = 0, .bound = 0 }, .{ .regs = 12, .static = 0, .bound = 0 } } }, + .{ .launch = .{ .name = "inkling2 ops tf_ink2_put_words", .symbol = "tf_ink2_put_words", .image = "inkling2_ops", .threads = 128, .min_sm = 80 }, .usage = .{ .{ .regs = 8, .static = 0, .bound = 0 }, .{ .regs = 8, .static = 0, .bound = 0 }, .{ .regs = 8, .static = 0, .bound = 0 }, .{ .regs = 10, .static = 0, .bound = 0 }, .{ .regs = 10, .static = 0, .bound = 0 } } }, + .{ .launch = .{ .name = "inkling2 ops tf_ink2_rowdot_tiles", .symbol = "tf_ink2_rowdot_tiles", .image = "inkling2_rows", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 98, .static = 24576, .bound = 256 }, .{ .regs = 98, .static = 24576, .bound = 256 }, .{ .regs = 98, .static = 24576, .bound = 256 }, .{ .regs = 106, .static = 24576, .bound = 256 }, .{ .regs = 106, .static = 24576, .bound = 256 } } }, + .{ .launch = .{ .name = "inkling2 ops tf_ink2_prompt_tail", .symbol = "tf_ink2_prompt_tail", .image = "inkling2_rows", .threads = 32, .min_sm = 80 }, .usage = .{ .{ .regs = 26, .static = 0, .bound = 32 }, .{ .regs = 30, .static = 0, .bound = 32 }, .{ .regs = 26, .static = 0, .bound = 32 }, .{ .regs = 24, .static = 0, .bound = 32 }, .{ .regs = 24, .static = 0, .bound = 32 } } }, +}; +/// nvcc 13.2's, where it differs: pending (no 13.2 compiler measured). +pub const cuda_132 = [_]registry.Override{}; +/// nvcc 13.3's, where it differs. +pub const cuda_133 = [_]registry.Override{ + .{ .name = "inkling2 ops tf_ink2_mix", .usage = .{ .{ .regs = 76, .static = 45712, .bound = 512 }, .{ .regs = 76, .static = 45712, .bound = 512 }, .{ .regs = 76, .static = 45712, .bound = 512 }, .{ .regs = 74, .static = 45712, .bound = 512 }, .{ .regs = 74, .static = 45712, .bound = 512 } } }, + .{ .name = "inkling2 ops tf_ink2_rowdot", .usage = .{ .{ .regs = 32, .static = 0, .bound = 256 }, .{ .regs = 40, .static = 0, .bound = 256 }, .{ .regs = 40, .static = 0, .bound = 256 }, .{ .regs = 34, .static = 0, .bound = 256 }, .{ .regs = 34, .static = 0, .bound = 256 } } }, + .{ .name = "inkling2 ops tf_ink2_rowdot_tiles", .usage = .{ .{ .regs = 98, .static = 24576, .bound = 256 }, .{ .regs = 98, .static = 24576, .bound = 256 }, .{ .regs = 98, .static = 24576, .bound = 256 }, .{ .regs = 114, .static = 24576, .bound = 256 }, .{ .regs = 114, .static = 24576, .bound = 256 } } }, + .{ .name = "inkling2 ops tf_ink2_prompt_tail", .usage = .{ .{ .regs = 26, .static = 0, .bound = 32 }, .{ .regs = 30, .static = 0, .bound = 32 }, .{ .regs = 26, .static = 0, .bound = 32 }, .{ .regs = 23, .static = 0, .bound = 32 }, .{ .regs = 23, .static = 0, .bound = 32 } } }, +}; + +test "Inkling 2 glue: every launch is registered once and fits every SM" { + const std = @import("std"); + 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 std.testing.expectEqual(@as(usize, 1), found); + try std.testing.expectEqual(@as(usize, 0), try registry.checkCuda(std.testing.allocator, &.{r}, true)); + } +} diff --git a/zig/src/core/contract/lfm3_records.zig b/zig/src/core/contract/lfm3_records.zig index bef2d41b382..aee0d6f4fe0 100644 --- a/zig/src/core/contract/lfm3_records.zig +++ b/zig/src/core/contract/lfm3_records.zig @@ -58,6 +58,8 @@ pub const metal = [_]M{ .{ .name = "lfm3 conv-state-bad lfm3_conv_segments", .threads = 256, .tg_memory = 0, .reserved = 256 }, .{ .name = "lfm3 lfm3_conv", .threads = 256, .tg_memory = 0, .reserved = 256 }, .{ .name = "lfm3 lfm3_qk", .threads = 32, .tg_memory = 0, .reserved = 32 }, + .{ .name = "lfm3 lfm3_qk_segments", .threads = 32, .tg_memory = 0, .reserved = 32 }, + .{ .name = "lfm3 qk-stream-bad lfm3_qk_segments", .threads = 32, .tg_memory = 0, .reserved = 32 }, .{ .name = "lfm3 lfm3_gate", .threads = 256, .tg_memory = 0, .reserved = 256 }, .{ .name = "lfm3 lfm3_swiglu", .threads = 256, .tg_memory = 0, .reserved = 256 }, .{ .name = "lfm3 range-skip lfm3_attn_partial", .threads = 128, .tg_memory = 2096, .reserved = 128 }, diff --git a/zig/src/core/contract/nvcc_133_records.zig b/zig/src/core/contract/nvcc_133_records.zig index 349610d0f25..19ad81fb73d 100644 --- a/zig/src/core/contract/nvcc_133_records.zig +++ b/zig/src/core/contract/nvcc_133_records.zig @@ -15,7 +15,6 @@ pub const cuda_133 = [_]registry.Override{ .{ .name = "ck tf_ck4_up_nvfp4_prompt", .usage = .{ .{ .regs = 80, .static = 46080, .bound = 256 }, .{ .regs = 88, .static = 46080, .bound = 256 }, .{ .regs = 94, .static = 46080, .bound = 256 }, .{ .regs = 115, .static = 46080, .bound = 256 }, .{ .regs = 115, .static = 46080, .bound = 256 } } }, .{ .name = "dense rows tf_dense_rows_16", .usage = .{ .{ .regs = 79, .static = 0, .bound = 256 }, .{ .regs = 79, .static = 0, .bound = 256 }, .{ .regs = 79, .static = 0, .bound = 256 }, .{ .regs = 96, .static = 0, .bound = 256 }, .{ .regs = 96, .static = 0, .bound = 256 } } }, .{ .name = "dense rows tf_dense_rows_4", .usage = .{ .{ .regs = 38, .static = 0, .bound = 256 }, .{ .regs = 38, .static = 0, .bound = 256 }, .{ .regs = 38, .static = 0, .bound = 256 }, .{ .regs = 40, .static = 0, .bound = 256 }, .{ .regs = 40, .static = 0, .bound = 256 } } }, - .{ .name = "df_sumn", .usage = .{ .{ .regs = 32, .static = 0, .bound = 0 }, .{ .regs = 40, .static = 0, .bound = 0 }, .{ .regs = 40, .static = 0, .bound = 0 }, .{ .regs = 33, .static = 0, .bound = 0 }, .{ .regs = 33, .static = 0, .bound = 0 } } }, .{ .name = "drama3 d3_act_quant", .usage = .{ .{ .regs = 23, .static = 144, .bound = 0 }, .{ .regs = 25, .static = 144, .bound = 0 }, .{ .regs = 23, .static = 144, .bound = 0 }, .{ .regs = 22, .static = 144, .bound = 0 }, .{ .regs = 22, .static = 144, .bound = 0 } } }, .{ .name = "drama3_codec c_layernorm", .usage = .{ .{ .regs = 21, .static = 132, .bound = 0 }, .{ .regs = 23, .static = 132, .bound = 0 }, .{ .regs = 23, .static = 132, .bound = 0 }, .{ .regs = 25, .static = 132, .bound = 0 }, .{ .regs = 25, .static = 132, .bound = 0 } } }, .{ .name = "dsv41_attn _ZN10dsv41_attn11attn_kernelILi2ELb0ELb0EEEvNS_4ArgsE", .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 = 114, .static = 0, .bound = 256 } } }, diff --git a/zig/src/core/contract/registry_joins.zig b/zig/src/core/contract/registry_joins.zig index 83c0ea84b02..40ac9edcceb 100644 --- a/zig/src/core/contract/registry_joins.zig +++ b/zig/src/core/contract/registry_joins.zig @@ -70,6 +70,7 @@ pub const all_metal = @import("lane_q8_records.zig").records ++ @import("metal_pair_records.zig").records ++ @import("glm_rows_records.zig").records ++ @import("glm_launch_records.zig").records ++ + @import("glm_dflash_records.zig").records ++ @import("row_wide_records.zig").records ++ @import("weight_only_records.zig").metal ++ @import("grouped_records.zig").metal ++ diff --git a/zig/src/core/contract/registry_union.zig b/zig/src/core/contract/registry_union.zig index fa4deb8fd85..66f6f9e8e28 100644 --- a/zig/src/core/contract/registry_union.zig +++ b/zig/src/core/contract/registry_union.zig @@ -5,7 +5,7 @@ fn has(comptime prior: anytype, comptime record: anytype) bool { return false; } fn count(comptime prior: anytype, comptime additional: anytype) usize { - @setEvalBranchQuota(4000000); + @setEvalBranchQuota(8000000); var n: usize = 0; for (additional) |r| if (!has(prior, r)) { n += 1; @@ -13,7 +13,7 @@ fn count(comptime prior: anytype, comptime additional: anytype) usize { return n; } pub fn extra(comptime prior: anytype, comptime additional: anytype) [count(prior, additional)]@TypeOf(additional[0]) { - @setEvalBranchQuota(4000000); + @setEvalBranchQuota(8000000); var out: [count(prior, additional)]@TypeOf(additional[0]) = undefined; var n: usize = 0; for (additional) |r| if (!has(prior, r)) { diff --git a/zig/src/core/engine_api.zig b/zig/src/core/engine_api.zig index e5b98541c4d..fc3515fd841 100644 --- a/zig/src/core/engine_api.zig +++ b/zig/src/core/engine_api.zig @@ -16,6 +16,7 @@ pub const EmbeddingBatch = lanes.embedding.Batch; pub const embedding_vector = @import("embedding_vector.zig"); pub const load_ledger = @import("load_ledger.zig"); pub const kv_ledger = @import("kv_ledger.zig"); +pub const execution_witness = @import("engine_witness.zig"); /// One image of a request (``Request.images``): the tower's input and the placeholder rows its output replaces. pub const Image = lanes.stream.Image; @@ -91,6 +92,8 @@ pub const Request = struct { images: []const Image = &.{}, /// The prompt as the prompt cache matches it (each image's placeholders by its content); empty: ``prompt``. cache_key: []const u32 = &.{}, + /// A streamed reply's tokens its client has not read yet (the server's mailbox counts them); null: not watched. + unread: ?*const std.atomic.Value(u32) = null, /// The prompt as the prompt cache matches it: an image request's placeholders stand for their images. pub fn cacheKey(r: *const Request) []const u32 { @@ -241,6 +244,8 @@ pub const Info = struct { admit: ?Admit = null, /// A byte budget each request promises its caches from as it is admitted (null: none); never beside `admit`. ledger: ?Ledger = null, + /// --execution-witness: this engine's attestation of its supported path (null: an unsupported path). + witness: ?execution_witness.Source = null, pub const Capability = @import("engine_capabilities.zig").Capability; @@ -433,7 +438,7 @@ pub const Engine = struct { learn: ?*const fn (ctx: *anyopaque, request: *const LearnRequest, sink: LearnSink) LearnError!void = null, /// Recall's record for every later request's drafts and writes, before any request (null: no record read). recall: ?*const fn (ctx: *anyopaque, store: *lanes.recall_store.Store) void = null, - /// Queue a question about kept states for the engine thread (it stays valid until `done`); false: refused. + /// A kept-state question for the engine thread (valid until `done`, for good once withdrawn); false: refused. imprint: ?*const fn (ctx: *anyopaque, ask: *ImprintAsk) bool = null, /// A planned stop's first half: no more work, disk writes finished under a deadline, the engine thread joined. drain: ?*const fn (ctx: *anyopaque) void = null, @@ -573,6 +578,7 @@ pub const prompt_learn = @import("prompt_learn.zig"); /// A question about a conversation's kept states, in RAM and on disk (rows_ask.zig). pub const ImprintAsk = @import("rows_ask.zig").Ask; pub const ImprintOp = @import("rows_ask.zig").Op; +pub const ImprintClaim = @import("rows_ask.zig").Claim; pub const ImprintDisk = @import("rows_ask.zig").Disk; /// Recall's record of the ids earlier requests read and wrote, for drafts (not the prompt cache's learned states). diff --git a/zig/src/core/engine_witness.zig b/zig/src/core/engine_witness.zig new file mode 100644 index 00000000000..69eb719061e --- /dev/null +++ b/zig/src/core/engine_witness.zig @@ -0,0 +1,20 @@ +//! What an engine attests for the execution witness: its supported path and a digest of its facts, or why it cannot. + +/// Why a witness is unknown; the read endpoint names it. +pub const Reason = enum { pending, unsupported_path, feature_excluded, parked, reloading, files_changed, hash_failed }; + +/// A supported path's label (at most 64 bytes, static) and the digest of everything the engine binds for it. +pub const Known = struct { path: []const u8, digest: [32]u8 }; + +/// The engine's attestation now: still hashing, known, or unknown with its reason. +pub const Facts = union(enum) { pending, unknown: Reason, known: Known }; + +/// `Info.witness`: read on any thread while this engine is resident; the server never reads a parked engine's. +pub const Source = struct { + ctx: *anyopaque, + read: *const fn (ctx: *anyopaque) Facts, + + pub fn facts(s: Source) Facts { + return s.read(s.ctx); + } +}; diff --git a/zig/src/core/kv_pool_test.zig b/zig/src/core/kv_pool_test.zig index d2b21712df0..56b1401fb89 100644 --- a/zig/src/core/kv_pool_test.zig +++ b/zig/src/core/kv_pool_test.zig @@ -527,3 +527,12 @@ test "TF_KV_SHARE's slots alone (GLM): the cache keeps the slots it holds, the n many.cache = 16 * g; try expectEqual(@as(usize, kv.most_snaps), (try kv.plan(glm, many)).snaps); } + +test "kv safety: Qwen flag-unset plan keeps main's window and run figures at one and eight streams" { + const l: kv.Layout = .{ .fixed_bytes = 32, .token_bytes = 2, .page_tokens = 16, .snap_bytes = 0, .run_bytes = 64 }; + for ([_]u32{ 1, 8 }) |lanes| for ([_]bool{ false, true }) |all| { + const p = try kv.plan(l, .{ .room = 10000, .engine = 0, .lanes = lanes, .fixed = true, .window = 128, .engine_paged = all }); + const expected: usize = if (lanes == 1) (if (all) 8 else 0) else (if (all) 78 else 70); + try expectEqual(kv.Plan{ .lanes = lanes, .snaps = 0, .copied = 0, .pages = expected }, p); + }; +} diff --git a/zig/src/core/lane_host.zig b/zig/src/core/lane_host.zig index afd5830d2af..1811a856251 100644 --- a/zig/src/core/lane_host.zig +++ b/zig/src/core/lane_host.zig @@ -78,6 +78,7 @@ pub const LaneHost = struct { memory_lanes: ?usize = null, // lanes the backend had memory for at its last LaneMemory, until a job ends warm_quiet: u64 = 0, // ns a warm pass waits for other work before its first chunk (0: none), set by its family disk: rows_host.Disk = .{}, // the Mac app's questions about kept states, and the disk writer's quiet + unread_limits: @import("lane_host_backlog.zig").Limits = .{}, // how far a streamed reply's reader may fall behind scores: scoring.Queue = .{}, // decisions' label scores waiting for the engine thread (lane_host_score.zig) /// Runs first on the engine thread: a backend whose API state is per thread (a CUDA context) binds it there. on_thread: ?ThreadInit = null, @@ -519,6 +520,7 @@ pub const LaneHost = struct { // a family planner: prompt pieces and decode rows in one pass; else whole or `prefill_step` chunked prompts if (h.rounds) |rd| return rounds.run(h, rd); while (true) { + @import("lane_host_backlog.zig").step(h); // holds precede activity: waits are idle var activity = @import("lane_activity.zig").Activity.enter(h.activity); defer activity.end(); ends.takeCancels(h); @@ -591,8 +593,6 @@ test { _ = @import("lane_host_decode_share_test.zig"); _ = @import("lane_host_srpt.zig"); _ = @import("lane_host_env.zig"); -} -test { _ = @import("lane_host_frame_test.zig"); _ = @import("lane_host_tests.zig"); _ = @import("lane_host_fetch.zig"); diff --git a/zig/src/core/lane_host_admit.zig b/zig/src/core/lane_host_admit.zig index 9240480d2ff..c9117928fe9 100644 --- a/zig/src/core/lane_host_admit.zig +++ b/zig/src/core/lane_host_admit.zig @@ -11,6 +11,7 @@ const Wait = @import("wait_reason.zig").Wait; /// The queued job to admit (its index), or null to hold, each job held stores why; the caller holds the lock. 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 // a stale device takes no reply: `learn.refuse` ends the queued ones instead if (h.stale) return hold(h, .engine_unavailable); diff --git a/zig/src/core/lane_host_backlog.zig b/zig/src/core/lane_host_backlog.zig new file mode 100644 index 00000000000..bd6c786696a --- /dev/null +++ b/zig/src/core/lane_host_backlog.zig @@ -0,0 +1,94 @@ +//! Slow readers: a stream whose client is `limit` tokens behind sits out rounds; one stalled past `stall_ns` ends. +const std = @import("std"); +const LaneHost = @import("lane_host.zig").LaneHost; +const Job = LaneHost.Job; + +pub const Limits = struct { + limit: u32 = 1024, // a streamed reply's unread tokens at which its stream sits out rounds; it runs again at half + stall_ns: i96 = 60 * std.time.ns_per_s, // a held stream whose client reads nothing this long is cancelled + pauses: std.atomic.Value(u64) = .init(0), // streams held so far (counted on the engine thread) + stalls: std.atomic.Value(u64) = .init(0), // and cancelled for a stalled reader +}; + +/// One job's hold (engine thread only): this host paused its stream; at `since` its client had `seen` tokens unread. +pub const Watch = struct { held: bool = false, since: i96 = 0, seen: u32 = 0, stalled: bool = false }; + +/// A turn's started streams: held for their readers, and free to run (a backend's own pause is neither). +pub const Count = struct { held: usize = 0, running: usize = 0 }; + +/// Before each turn (engine thread): hold readers behind, release caught-up ones, cancel stalled; all held: wait 2 ms. +pub fn step(h: *LaneHost) void { + const c = watch(h, null); + if (c.held == 0 or c.running > 0) return; + 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 {}; +} + +/// Holds and releases the admitted jobs' streams by their readers' unread tokens, at `at` (null: the clock's now). +pub fn watch(h: *LaneHost, at: ?i96) Count { + const lim = &h.unread_limits; + var c: Count = .{}; + var now = at; + // `admitted` changes only on this thread: the scan takes no lock + for (h.admitted.items) |job| { + if (!job.started or job.stream.finished) continue; + const w = &job.backlog; + const n = if (job.request.unread) |u| u.load(.monotonic) else 0; + if (!w.held) { + if (job.stream.paused) continue; // its backend's own pause (a larger session to free): not this host's + if (n < lim.limit) { + c.running += 1; + continue; + } + if (job.stream.inflight != null) { + job.stream.mode = .drain; // its next round lands the step it queued ahead and queues none + c.running += 1; + continue; + } + job.stream.paused = true; + w.* = .{ .held = true, .since = clock(h, &now), .seen = n }; + _ = lim.pauses.fetchAdd(1, .monotonic); + c.held += 1; + continue; + } + if (n <= lim.limit / 2) { + job.stream.paused = false; + w.held = false; + c.running += 1; + continue; + } + c.held += 1; + const t = clock(h, &now); + if (n < w.seen) { + w.seen = n; // its client read: the stall's clock starts again + w.since = t; + } + if (w.stalled or t - w.since < lim.stall_ns) continue; + h.lock(); + const sent = if (h.cancels.append(h.gpa, job.id)) |_| true else |_| false; + h.unlock(); + if (!sent) continue; // no memory for the cancel: the next turn tries again + w.stalled = true; // takeCancels ends it as a disconnect's cancel does, and frees its lane + _ = lim.stalls.fetchAdd(1, .monotonic); + } + return c; +} + +/// Whether `job`'s reader is `limit` tokens behind: the lone driver hands such a stream back for the host to hold. +pub fn behind(h: *const LaneHost, job: *const Job) bool { + const unread = job.request.unread orelse return false; + return unread.load(.monotonic) >= h.unread_limits.limit; +} + +fn clock(h: *const LaneHost, now: *?i96) i96 { + if (now.*) |t| return t; + const t = std.Io.Clock.awake.now(h.io).toNanoseconds(); + now.* = t; + return t; +} + +test { + _ = @import("lane_host_backlog_test.zig"); +} diff --git a/zig/src/core/lane_host_backlog_test.zig b/zig/src/core/lane_host_backlog_test.zig new file mode 100644 index 00000000000..f6e9eb66efc --- /dev/null +++ b/zig/src/core/lane_host_backlog_test.zig @@ -0,0 +1,352 @@ +//! Slow readers on the lane host: a stream sits out while its client is behind, others keep their pace, stalls end. +const std = @import("std"); +const lanes = @import("lanes"); +const api = @import("engine_api.zig"); +const backlog = @import("lane_host_backlog.zig"); +const LaneHost = api.LaneHost; +const Request = api.Request; +const Reason = api.Reason; +const gpa = std.testing.allocator; +const io = std.testing.io; + +/// A client: the tokens it was sent, how many it has not read (Request.unread), and the most it ever left unread. +const Reader = struct { + mutex: std.Io.Mutex = .init, + tokens: std.ArrayList(u32) = .empty, + unread: std.atomic.Value(u32) = .init(0), + most: std.atomic.Value(u32) = .init(0), + done: ?Reason = null, + eager: bool = true, // reads each event as it lands (a normal client) + + fn event(ctx: *anyopaque, _: api.Id, e: *const api.Event) void { + const r: *@This() = @ptrCast(@alignCast(ctx)); + r.mutex.lockUncancelable(io); + defer r.mutex.unlock(io); + switch (e.*) { + .tokens => |t| { + r.tokens.appendSlice(gpa, t) catch {}; + const now = r.unread.fetchAdd(@intCast(t.len), .acq_rel) + @as(u32, @intCast(t.len)); + _ = r.most.fetchMax(now, .acq_rel); + if (r.eager) _ = r.unread.fetchSub(@intCast(t.len), .acq_rel); + }, + .finished => |f| r.done = f.reason, + else => {}, + } + } + fn count(r: *@This()) usize { + r.mutex.lockUncancelable(io); + defer r.mutex.unlock(io); + return r.tokens.items.len; + } + fn finished(r: *@This()) ?Reason { + r.mutex.lockUncancelable(io); + defer r.mutex.unlock(io); + return r.done; + } + fn wait(r: *@This()) Reason { + while (true) { + if (r.finished()) |d| return d; + std.Io.sleep(io, .fromMilliseconds(1), .awake) catch {}; + } + } + /// A slow client: two tokens every `ms` milliseconds until its reply ends. + fn trickle(r: *@This(), ms: u32) void { + while (r.finished() == null) { + std.Io.sleep(io, .fromMilliseconds(ms), .awake) catch {}; + const n = @min(r.unread.load(.acquire), 2); + _ = r.unread.fetchSub(n, .acq_rel); + } + } + fn request(r: *@This(), prompt: []const u32, max: u32, drafts: bool) Request { + return .{ .prompt = prompt, .max_tokens = max, .drafts = drafts, .unread = &r.unread }; + } +}; + +/// A lone driver that decodes by the fake's rule and hands its stream back whenever the host's yield asks. +const Lone = struct { + target: *lanes.fake.Fake, + handed: u32 = 0, // hand-backs in the middle of a reply + + fn run(ctx: *anyopaque, s: *lanes.Stream, hooks: api.LoneHooks) anyerror!bool { + const l: *Lone = @ptrCast(@alignCast(ctx)); + if (!hooks.resumed) { + _ = try l.target.backend().opening(gpa, s); + hooks.committed(hooks.ctx); + s.pending = s.context.items[s.context.items.len - 1]; + s.cache_len = s.prompt_len; // as a backend's hand-over leaves it: the first token not yet fed + return true; + } + const history = &l.target.lanes.getPtr(s).?.history; + while (!s.finished) { + if (hooks.yield(hooks.ctx)) { + l.handed += 1; + return true; // the fake's cache holds every token but the pending one, as the lane core takes it + } + try history.append(gpa, s.pending.?); + s.cache_len += 1; + const t = lanes.fake.next(history.items, null, history.items.len); + _ = try s.commit(gpa, &.{t}, &.{}); + s.pending = t; + hooks.committed(hooks.ctx); + } + l.target.backend().release(s); + return false; + } +}; + +/// `drafted`: a drafted family's windowed rounds (head drafts, 16-row windows); else one-token steps queued ahead. +const Options = struct { lanes: u32 = 1, limits: backlog.Limits = .{}, ring_len: ?usize = null, lone: bool = false, drafted: bool = false }; + +const Rig = struct { + cfg: lanes.Config, + target: lanes.fake.Fake, + clock: lanes.fake.FixedClock = .{}, + core: lanes.Engine, + host: LaneHost, + lone: Lone = undefined, + stopped: bool = false, + + fn init(r: *Rig, o: Options) !void { + 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)) }; + r.cfg = if (o.drafted) + try lanes.Config.init(gpa, .{ .exact_width = 16, .gpu_tokens = true, .mtp = true, .speculate = true, .speculate_early = false, .drafts = 4, .window_costs = &costs, .mtp_step_ms = 0.5, .hidden_rows = true, .batch_rows = 32, .max_streams = 8, .draft_streams = true }, 16, 15) + else + try lanes.Config.init(gpa, .{ .exact_width = 8, .gpu_tokens = true, .hidden_rows = true }, 8, 7); + r.target = .{ .gpa = gpa, .ring_len = o.ring_len }; + r.clock = .{}; + r.stopped = false; + r.core = lanes.Engine.init(gpa, &r.cfg, r.target.backend(), r.clock.clock()); + r.host = LaneHost.init(gpa, io, &r.core, .{ .lanes = o.lanes }); + r.host.unread_limits = o.limits; + r.lone = .{ .target = &r.target }; + if (o.lone) r.host.lone = .{ .ctx = &r.lone, .run = Lone.run, .resumes = true }; + try r.host.start(); + } + fn stop(r: *Rig) void { + if (!r.stopped) r.host.stop(); + r.stopped = true; + } + fn deinit(r: *Rig) void { + r.stop(); + r.core.deinit(); + r.target.deinit(); + r.cfg.deinit(gpa); + } + fn pauses(r: *Rig) u64 { + return r.host.unread_limits.pauses.load(.monotonic); + } +}; + +const p1 = [_]u32{ 3, 1, 4, 1, 5, 9, 2, 6 }; +const p2 = [_]u32{ 2, 7, 1, 8, 2, 8, 1, 8 }; + +/// One request with an eager reader on its own host: the reference tokens (the caller frees them). +fn reference(prompt: []const u32, max: u32) !std.ArrayList(u32) { + var rig: Rig = undefined; + try rig.init(.{}); + defer rig.deinit(); + var r: Reader = .{}; + const req = r.request(prompt, max, true); + try rig.host.engine().submit(1, &req, .{ .ctx = &r, .event = Reader.event }); + try std.testing.expectEqual(Reason.length, r.wait()); + return r.tokens; +} + +test "slow readers: a normal reader never pauses, even with a small limit" { + var r: Reader = .{}; + defer r.tokens.deinit(gpa); + var rig: Rig = undefined; + try rig.init(.{ .limits = .{ .limit = 8 } }); + defer rig.deinit(); + const req = r.request(&p1, 200, true); + try rig.host.engine().submit(1, &req, .{ .ctx = &r, .event = Reader.event }); + try std.testing.expectEqual(Reason.length, r.wait()); + try std.testing.expectEqual(@as(u64, 0), rig.pauses()); + try std.testing.expectEqual(@as(usize, 200), r.tokens.items.len); +} + +test "slow readers: the backlog stays within a round of the limit and the text is a fast reader's, byte for byte" { + var fast = try reference(&p1, 200); + defer fast.deinit(gpa); + const limit = 8; + for ([_]bool{ false, true }) |drafted| { + var r: Reader = .{ .eager = false }; + defer r.tokens.deinit(gpa); + var rig: Rig = undefined; + try rig.init(.{ .limits = .{ .limit = limit }, .drafted = drafted }); + defer rig.deinit(); + const req = r.request(&p1, 200, true); + try rig.host.engine().submit(1, &req, .{ .ctx = &r, .event = Reader.event }); + const t = try std.Thread.spawn(.{}, Reader.trickle, .{ &r, 1 }); + const reason = r.wait(); + t.join(); + try std.testing.expectEqual(Reason.length, reason); + try std.testing.expect(rig.pauses() > 0); + // the limit, plus at most the one round that crossed it (a window of the config's width) and one queued step + try std.testing.expect(r.most.load(.acquire) <= limit + rig.cfg.family_width + 1); + try std.testing.expectEqualSlices(u32, fast.items, r.tokens.items); + } +} + +test "slow readers: a stalled reader holds only its own stream, the other finishes, then the slow one ends unchanged" { + var solo = try reference(&p2, 120); + defer solo.deinit(gpa); + var slow_ref = try reference(&p1, 120); + defer slow_ref.deinit(gpa); + var slow: Reader = .{ .eager = false }; + defer slow.tokens.deinit(gpa); + var quick: Reader = .{}; + defer quick.tokens.deinit(gpa); + var rig: Rig = undefined; + try rig.init(.{ .lanes = 2, .limits = .{ .limit = 8 } }); + defer rig.deinit(); + const e = rig.host.engine(); + const a = slow.request(&p1, 120, true); + const b = quick.request(&p2, 120, true); + try e.submit(1, &a, .{ .ctx = &slow, .event = Reader.event }); + try e.submit(2, &b, .{ .ctx = &quick, .event = Reader.event }); + // the slow client reads nothing: the quick one still finishes, all its tokens, while the slow one waits + try std.testing.expectEqual(Reason.length, quick.wait()); + try std.testing.expect(slow.finished() == null); + try std.testing.expect(slow.count() < 120); + try std.testing.expectEqualSlices(u32, solo.items, quick.tokens.items); + // the client catches up: its stream resumes and ends as it would have + const t = try std.Thread.spawn(.{}, Reader.trickle, .{ &slow, 1 }); + const reason = slow.wait(); + t.join(); + try std.testing.expectEqual(Reason.length, reason); + try std.testing.expectEqualSlices(u32, slow_ref.items, slow.tokens.items); +} + +test "slow readers: a held stream's step queued ahead lands first, so a peer's draws never meet it in the ring" { + var slow_ref = try reference(&p1, 60); + defer slow_ref.deinit(gpa); + var quick_ref = try reference(&p2, 60); + defer quick_ref.deinit(gpa); + var slow: Reader = .{ .eager = false }; + defer slow.tokens.deinit(gpa); + var quick: Reader = .{}; + defer quick.tokens.deinit(gpa); + var rig: Rig = undefined; + // GLM's ring of four draws: an unread draw holds its slot, and a draw meeting it fails the round + try rig.init(.{ .lanes = 2, .limits = .{ .limit = 8 }, .ring_len = 4 }); + defer rig.deinit(); + const e = rig.host.engine(); + // drafts off: every round is a step queued ahead, so the slow stream holds a draw whenever it stops + const a = slow.request(&p1, 60, false); + try e.submit(1, &a, .{ .ctx = &slow, .event = Reader.event }); + var waited: u32 = 0; + while (rig.pauses() == 0) : (waited += 1) { + if (waited == 5000) return error.NeverHeld; + std.Io.sleep(io, .fromMilliseconds(1), .awake) catch {}; + } + const b = quick.request(&p2, 60, false); + try e.submit(2, &b, .{ .ctx = &quick, .event = Reader.event }); + try std.testing.expectEqual(Reason.length, quick.wait()); + try std.testing.expectEqualSlices(u32, quick_ref.items, quick.tokens.items); + const t = try std.Thread.spawn(.{}, Reader.trickle, .{ &slow, 1 }); + const reason = slow.wait(); + t.join(); + try std.testing.expectEqual(Reason.length, reason); + try std.testing.expectEqualSlices(u32, slow_ref.items, slow.tokens.items); +} + +test "slow readers: a reader stalled past the timeout is cancelled as a disconnect is, its lane to the next request" { + var next_ref = try reference(&p2, 40); + defer next_ref.deinit(gpa); + var stuck: Reader = .{ .eager = false }; + defer stuck.tokens.deinit(gpa); + var next: Reader = .{}; + defer next.tokens.deinit(gpa); + var rig: Rig = undefined; + try rig.init(.{ .limits = .{ .limit = 8, .stall_ns = 50 * std.time.ns_per_ms } }); + defer rig.deinit(); + const e = rig.host.engine(); + const a = stuck.request(&p1, 10_000, true); + const b = next.request(&p2, 40, true); + try e.submit(1, &a, .{ .ctx = &stuck, .event = Reader.event }); + try e.submit(2, &b, .{ .ctx = &next, .event = Reader.event }); // one lane: it waits behind the stuck stream + try std.testing.expectEqual(Reason.cancelled, stuck.wait()); + try std.testing.expect(stuck.count() < 10_000); + try std.testing.expectEqual(@as(u64, 1), rig.host.unread_limits.stalls.load(.monotonic)); + try std.testing.expectEqual(Reason.length, next.wait()); + try std.testing.expectEqualSlices(u32, next_ref.items, next.tokens.items); + rig.stop(); + // the held stream's 50 ms passed in 2 ms waits, not in empty rounds spun while the queued request waited + try std.testing.expect(rig.core.steps < 400); +} + +test "lone driver: a reader behind hands its stream back, the host holds it, and its reply is a fast reader's" { + var fast = try reference(&p1, 200); + defer fast.deinit(gpa); + const limit = 8; + var r: Reader = .{ .eager = false }; + defer r.tokens.deinit(gpa); + var rig: Rig = undefined; + try rig.init(.{ .limits = .{ .limit = limit }, .lone = true, .drafted = true }); + defer rig.deinit(); + const req = r.request(&p1, 200, true); + try rig.host.engine().submit(1, &req, .{ .ctx = &r, .event = Reader.event }); + const t = try std.Thread.spawn(.{}, Reader.trickle, .{ &r, 1 }); + const reason = r.wait(); + t.join(); + try std.testing.expectEqual(Reason.length, reason); + rig.stop(); + try std.testing.expect(rig.lone.handed > 0); + try std.testing.expect(rig.pauses() > 0); + try std.testing.expect(r.most.load(.acquire) <= limit + rig.cfg.family_width + 1); + try std.testing.expectEqualSlices(u32, fast.items, r.tokens.items); +} + +test "slow readers: the host lifts only its own holds, lands a queued step first and releases at half the limit" { + 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 host = LaneHost.init(gpa, io, &core, .{ .lanes = 1 }); // never started: watch runs on this thread + defer host.stop(); + host.unread_limits = .{ .limit = 8, .stall_ns = 100 }; + var unread: std.atomic.Value(u32) = .init(0); + const req: Request = .{ .prompt = &p1, .max_tokens = 40, .unread = &unread }; + var job: LaneHost.Job = .{ .host = &host, .id = 7, .request = &req, .sink = undefined, .started = true }; + job.stream = try lanes.Stream.init(gpa, .{ .id = "a", .prompt = &p1, .max_new = 40 }); + defer job.stream.deinit(gpa); + try host.admitted.append(gpa, &job); + defer host.admitted.clearRetainingCapacity(); + const s = &job.stream; + // its backend's pause (a larger session to free) stays, with the reader caught up or behind + s.paused = true; + _ = backlog.watch(&host, 0); + try std.testing.expect(s.paused and !job.backlog.held); + unread.store(8, .monotonic); + try std.testing.expectEqual(@as(usize, 0), backlog.watch(&host, 0).held); + try std.testing.expect(s.paused and !job.backlog.held); + // the backend lifts it with a step queued ahead: that step lands in the stream's next round, before any hold + s.paused = false; + s.inflight = 3; + _ = backlog.watch(&host, 0); + try std.testing.expect(!s.paused and s.mode == .drain); + s.inflight = null; + try std.testing.expectEqual(@as(usize, 1), backlog.watch(&host, 10).held); + try std.testing.expect(s.paused and job.backlog.held); + try std.testing.expectEqual(@as(u64, 1), host.unread_limits.pauses.load(.monotonic)); + // a read restarts the stall's clock; the hold lasts until half the limit is left + unread.store(5, .monotonic); + _ = backlog.watch(&host, 90); + _ = backlog.watch(&host, 150); + try std.testing.expect(s.paused and host.cancels.items.len == 0); + unread.store(4, .monotonic); + try std.testing.expectEqual(@as(usize, 1), backlog.watch(&host, 150).running); + try std.testing.expect(!s.paused and !job.backlog.held); + // held again and read no more: one cancel, named once + unread.store(9, .monotonic); + _ = backlog.watch(&host, 1000); + _ = backlog.watch(&host, 1100); + _ = backlog.watch(&host, 1200); + try std.testing.expectEqualSlices(api.Id, &.{7}, host.cancels.items); + try std.testing.expectEqual(@as(u64, 1), host.unread_limits.stalls.load(.monotonic)); +} diff --git a/zig/src/core/lane_host_flush_test.zig b/zig/src/core/lane_host_flush_test.zig new file mode 100644 index 00000000000..db871d6db08 --- /dev/null +++ b/zig/src/core/lane_host_flush_test.zig @@ -0,0 +1,281 @@ +//! A prompt-cache flush drops every kept state once the requests in flight end; a later turn prefills cold. +const std = @import("std"); +const lanes = @import("lanes"); +const api = @import("engine_api.zig"); +const pc = @import("prompt_cache.zig"); +const LaneHost = api.LaneHost; +const Id = api.Id; +const Event = api.Event; +const Request = api.Request; +const Reason = api.Reason; +const gpa = std.testing.allocator; +const io = std.testing.io; + +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; // lane-core backends restore inside their own prompt pass + } + fn drop(ptr: *anyopaque, saved: pc.Saved) void { + const f: *lanes.fake.Fake = @ptrCast(@alignCast(ptr)); + f.drop(saved); + } +}; + +/// A request's events; whether `flush` had answered when its prompt pass reported and when it ended, and `peer` ended. +const Box = struct { + mutex: std.Io.Mutex = .init, + tokens: std.ArrayList(u32) = .empty, + cached: ?u32 = null, + done: ?Reason = null, + ended: std.atomic.Value(bool) = .init(false), + flush: ?*const api.ImprintAsk = null, + peer: ?*const Box = null, + flushed_at_prefill: ?bool = null, + flushed_at_end: ?bool = null, + peer_ended_at_prefill: ?bool = null, + fn event(ctx: *anyopaque, _: Id, e: *const Event) void { + const b: *@This() = @ptrCast(@alignCast(ctx)); + b.mutex.lockUncancelable(io); + defer b.mutex.unlock(io); + const answered = if (b.flush) |f| f.done.load(.acquire) else null; + switch (e.*) { + .prefilled => |c| { + b.cached = c; + b.flushed_at_prefill = answered; + b.peer_ended_at_prefill = if (b.peer) |p| p.ended.load(.acquire) else null; + }, + .logprobs, .prompt_logprobs, .audio => {}, + .tokens => |t| b.tokens.appendSlice(gpa, t) catch {}, + .finished => |f| { + b.done = f.reason; + b.flushed_at_end = answered; + b.ended.store(true, .release); + }, + } + } + fn finished(b: *@This()) ?Reason { + b.mutex.lockUncancelable(io); + defer b.mutex.unlock(io); + return b.done; + } + fn wait(b: *@This()) !Reason { + for (0..5000) |_| { + if (b.finished()) |r| return r; + std.Io.sleep(io, .fromMilliseconds(1), .awake) catch {}; + } + return error.RequestTimedOut; + } +}; + +/// Holds the engine thread inside the first prompt pass after `armed`, until `open`. +const Gate = struct { + armed: std.atomic.Value(bool) = .init(false), + inside: std.atomic.Value(bool) = .init(false), + open: std.atomic.Value(bool) = .init(false), + fn chunk(ctx: *anyopaque, _: *lanes.Stream, _: usize) void { + const g: *@This() = @ptrCast(@alignCast(ctx)); + if (!g.armed.swap(false, .acq_rel)) return; + g.inside.store(true, .release); + while (!g.open.load(.acquire)) std.Io.sleep(io, .fromMilliseconds(1), .awake) catch {}; + } + fn entered(g: *@This()) !void { + for (0..5000) |_| { + if (g.inside.load(.acquire)) return; + std.Io.sleep(io, .fromMilliseconds(1), .awake) catch {}; + } + return error.GateNotReached; + } +}; + +/// A lane host over the fake target with a prompt cache (`cached`), two lanes; `gate` holds a prompt pass. +const Rig = struct { + cfg: lanes.Config, + target: lanes.fake.Fake = .{ .gpa = gpa }, + clock: lanes.fake.FixedClock = .{}, + core: lanes.Engine = undefined, + store: pc.Store = undefined, + host: LaneHost = undefined, + gate: Gate = .{}, + + fn start(r: *Rig, cached: bool) !void { + r.target.prefill_hook = Gate.chunk; + r.target.prefill_hook_ctx = &r.gate; + r.core = lanes.Engine.init(gpa, &r.cfg, r.target.backend(), r.clock.clock()); + const family: pc.Snapshots = .{ .ptr = &r.target, .vtable = &.{ .bytes = Snaps.bytes, .save = Snaps.save, .restore = Snaps.restore, .drop = Snaps.drop } }; + r.store = pc.Store.init(gpa, family, .{ .min_gap = 4, .min_prompt = 0 }, 1 << 20); + r.host = LaneHost.init(gpa, io, &r.core, .{ .lanes = 2 }); + if (cached) r.host.cache = &r.store; + try r.host.start(); + } + fn deinit(r: *Rig) void { + r.host.stop(); + r.store.deinit(); + r.core.deinit(); + r.target.deinit(); + r.cfg.deinit(gpa); + } + fn engine(r: *Rig) api.Engine { + return r.host.engine(); + } +}; + +fn rig() !Rig { + return .{ .cfg = try lanes.Config.init(gpa, .{ .exact_width = 8, .gpu_tokens = true, .hidden_rows = true }, 8, 7) }; +} + +/// One request run to its end; its tokens (the caller frees them) and where it resumed. +fn run(e: api.Engine, id: Id, r: *const Request) !struct { tokens: std.ArrayList(u32), cached: ?u32 } { + var b: Box = .{}; + try e.submit(id, r, .{ .ctx = &b, .event = Box.event }); + try std.testing.expectEqual(Reason.length, try b.wait()); + return .{ .tokens = b.tokens, .cached = b.cached }; +} + +const t1 = [_]u32{ 3, 1, 4, 1, 5, 9, 2, 6, 5, 3 }; + +/// The next turn after `t1` and its reply `first`: the history, four reply tokens, a tool result, a new prompt. +fn nextTurn(first: []const u32) ![]u32 { + return std.mem.concat(gpa, u32, &.{ &t1, first[0..4], &.{ 7, 7, 5, 3 } }); +} + +/// Two turns of one conversation, the second resumed from the first's kept state; its request and tokens. +const Warm = struct { + first: std.ArrayList(u32), + prompt: []u32, + second: std.ArrayList(u32), + fn request(w: *const Warm) Request { + return .{ .prompt = w.prompt, .max_tokens = 12, .history_len = @intCast(w.prompt.len - 2) }; + } + fn deinit(w: *Warm) void { + w.first.deinit(gpa); + gpa.free(w.prompt); + w.second.deinit(gpa); + } +}; + +fn warm(e: api.Engine) !Warm { + var first = try run(e, 1, &.{ .prompt = &t1, .max_tokens = 6, .history_len = 8 }); + errdefer first.tokens.deinit(gpa); + const prompt = try nextTurn(first.tokens.items); + errdefer gpa.free(prompt); + const r: Request = .{ .prompt = prompt, .max_tokens = 12, .history_len = @intCast(prompt.len - 2) }; + const second = try run(e, 2, &r); + try std.testing.expectEqual(@as(?u32, 8), second.cached); // resumed from the first turn's kept state + return .{ .first = first.tokens, .prompt = prompt, .second = second.tokens }; +} + +test "prompt cache flush: every kept state goes, and the resumed turn then prefills cold with the same tokens" { + var r = try rig(); + try r.start(true); + defer r.deinit(); + const e = r.engine(); + var w = try warm(e); + defer w.deinit(); + const kept = r.store.entries.items.len; + const held = r.store.held; + try std.testing.expect(kept >= 2); + var ask: api.ImprintAsk = .{ .op = .flush }; + try std.testing.expect(e.imprintAsk(&ask)); + try std.testing.expect(ask.wait(io, 5000)); + try std.testing.expectEqual(@as(u32, @intCast(kept)), ask.dropped); + try std.testing.expectEqual(held, ask.ram_freed); + try std.testing.expectEqual(@as(u64, 0), ask.freed); // no disk store here + try std.testing.expect(!ask.disk); + try std.testing.expectEqual(@as(usize, 0), r.store.entries.items.len); + try std.testing.expectEqual(@as(u64, 0), r.store.held); + const req = w.request(); + var cold = try run(e, 3, &req); + defer cold.tokens.deinit(gpa); + try std.testing.expectEqual(@as(?u32, 0), cold.cached); // nothing to resume: the whole prompt prefilled + try std.testing.expectEqualSlices(u32, w.second.items, cold.tokens.items); +} + +test "prompt cache flush: a request in flight finishes unchanged and the flush answers after it; arrivals wait" { + var r = try rig(); + try r.start(true); + defer r.deinit(); + const e = r.engine(); + var w = try warm(e); + defer w.deinit(); + const req = w.request(); + // the same turn again, held inside its prompt pass while two flushes are asked + var ask: api.ImprintAsk = .{ .op = .flush }; + var again: api.ImprintAsk = .{ .op = .flush }; + r.gate.armed.store(true, .release); + var b: Box = .{ .flush = &ask }; + defer b.tokens.deinit(gpa); + try e.submit(3, &req, .{ .ctx = &b, .event = Box.event }); + try r.gate.entered(); + try std.testing.expect(e.imprintAsk(&ask)); + try std.testing.expect(e.imprintAsk(&again)); + // a request submitted behind the flushes waits for them, though a lane is free: it starts after, and prefills cold + var later: Box = .{ .flush = &ask }; + defer later.tokens.deinit(gpa); + try e.submit(4, &req, .{ .ctx = &later, .event = Box.event }); + r.gate.open.store(true, .release); + try std.testing.expect(ask.wait(io, 5000)); + try std.testing.expect(again.wait(io, 5000)); + try std.testing.expectEqual(Reason.length, try b.wait()); + try std.testing.expectEqual(@as(?bool, false), b.flushed_at_end); // it ended before the flush ran + try std.testing.expect(b.cached.? > 0); // it resumed from a kept state, which the flush left alone while it ran + try std.testing.expectEqualSlices(u32, w.second.items, b.tokens.items); + try std.testing.expect(ask.dropped >= 2); + try std.testing.expectEqual(@as(u32, 0), again.dropped); // the second flush found nothing left + try std.testing.expectEqual(Reason.length, try later.wait()); + try std.testing.expectEqual(@as(?bool, true), later.flushed_at_prefill); + try std.testing.expectEqual(@as(?u32, 0), later.cached); + try std.testing.expectEqualSlices(u32, w.second.items, later.tokens.items); +} + +test "prompt cache flush: a withdrawn flush releases the hold at once and drops nothing" { + var r = try rig(); + try r.start(true); + defer r.deinit(); + const e = r.engine(); + var w = try warm(e); + defer w.deinit(); + const req = w.request(); + var ask: api.ImprintAsk = .{ .op = .flush }; + r.gate.armed.store(true, .release); + var b: Box = .{}; + defer b.tokens.deinit(gpa); + try e.submit(3, &req, .{ .ctx = &b, .event = Box.event }); + try r.gate.entered(); + try std.testing.expect(e.imprintAsk(&ask)); + var later: Box = .{ .peer = &b }; + defer later.tokens.deinit(gpa); + try e.submit(4, &req, .{ .ctx = &later, .event = Box.event }); + try std.testing.expect(ask.withdraw()); // its caller's wait ran out before any request ended + try std.testing.expect(!ask.withdraw()); + r.gate.open.store(true, .release); + try std.testing.expectEqual(Reason.length, try b.wait()); + try std.testing.expectEqual(Reason.length, try later.wait()); + try std.testing.expectEqual(@as(?bool, false), later.peer_ended_at_prefill); // admitted beside it: nothing held + try std.testing.expect(later.cached.? > 0); // it resumed from a kept state + try std.testing.expectEqualSlices(u32, w.second.items, later.tokens.items); + try std.testing.expect(!ask.done.load(.acquire)); + try std.testing.expect(r.store.entries.items.len >= 2); + var next = try run(e, 5, &req); // the host goes on admitting once it is idle and has dropped the withdrawn ask + defer next.tokens.deinit(gpa); + try std.testing.expect(next.cached.? > 0); + try std.testing.expect(!ask.done.load(.acquire)); +} + +test "prompt cache flush: a lane host without a prompt cache refuses it at once, holding nothing" { + var r = try rig(); + try r.start(false); + defer r.deinit(); + const e = r.engine(); + var ask: api.ImprintAsk = .{ .op = .flush }; + try std.testing.expect(!e.imprintAsk(&ask)); + var first = try run(e, 1, &.{ .prompt = &t1, .max_tokens = 6, .history_len = 8 }); + defer first.tokens.deinit(gpa); + try std.testing.expectEqual(@as(?u32, 0), first.cached); +} diff --git a/zig/src/core/lane_host_lone.zig b/zig/src/core/lane_host_lone.zig index 46cbf3172d3..fab4dbfd1e8 100644 --- a/zig/src/core/lane_host_lone.zig +++ b/zig/src/core/lane_host_lone.zig @@ -1,6 +1,7 @@ //! A lane host's lone driver: the backend's own loop runs a lone stream until a foreground request or a cancel waits. const LaneHost = @import("lane_host.zig").LaneHost; const status = @import("lane_host_status.zig"); +const backlog = @import("lane_host_backlog.zig"); const Job = LaneHost.Job; /// An idle driver takes a lone drafted request; plain, sampled, with logprobs, a budget or a grammar when supported. @@ -28,8 +29,8 @@ pub fn reclaim(h: *LaneHost) void { h.unlock(); const j = job orelse return; const s = &j.stream; - // a forced close the driver would hand straight back stays in the lane core - if (s.paused or s.force.items.len > 0 or s.budgetWithin(lone.min_budget) or !takes(h, j) or h.core.activeCount() != 1) return; + // a forced close, or a reader behind, the driver would hand straight back stays in the lane core + if (s.paused or s.force.items.len > 0 or s.budgetWithin(lone.min_budget) or backlog.behind(h, j) or !takes(h, j) or h.core.activeCount() != 1) return; if (!h.core.detach(s)) return; j.prefill_sent = true; // the lane core sent it _ = run(h, j, j.began, true); @@ -58,7 +59,8 @@ pub fn run(h: *LaneHost, job: *Job, began: i96, resumed: bool) bool { const host = c.host; host.lock(); defer host.unlock(); - return host.foregroundWaiting() or host.cancels.items.len > 0 or host.closing; + // 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.?); } fn prefillYield(ctx: *anyopaque) bool { if (!yield(ctx)) return false; diff --git a/zig/src/core/lane_host_prefix.zig b/zig/src/core/lane_host_prefix.zig index 1941b39a642..416df1b9013 100644 --- a/zig/src/core/lane_host_prefix.zig +++ b/zig/src/core/lane_host_prefix.zig @@ -1,16 +1,18 @@ -//! The prefix wait: a request whose prompt shares a cut another prompt is filling waits for that fill to keep it. +//! The prefix wait: a cut another prompt fills waits to keep it; an identical prompt joins the whole fill. const std = @import("std"); const api = @import("engine_api.zig"); const LaneHost = @import("lane_host.zig").LaneHost; const Job = LaneHost.Job; +const modes = @import("cache_modes.zig"); -/// A queued request's wait for `leader` (a filling job, while it is still named `id`) to stand at `at`, from `since`. -pub const Waiting = struct { leader: ?*const Job = null, id: api.Id = 0, at: u32 = 0, since: i96 = 0, waited: bool = false }; +/// A queued request's wait for `leader` to stand at `at` from `since`; `whole`: it covers the leader's whole fill. +pub const Waiting = struct { leader: ?*const Job = null, id: api.Id = 0, at: u32 = 0, since: i96 = 0, waited: bool = false, whole: bool = false }; /// The wait's bound (TENSORFOLD_PREFIX_WAIT_MS, 0: off) and what it did. pub const Wait = struct { ns: i96 = @as(i96, default_ms) * std.time.ns_per_ms, waits: u64 = 0, // requests that waited for another fill's cut + joins: u64 = 0, // of them, whole-fill joins: identical prompts that waited for a leader's whole fill timeouts: u64 = 0, // of them, released at the bound with the cut not reached pub const default_ms: u32 = 60_000; @@ -33,7 +35,7 @@ pub fn waiting(job: *const Job) bool { return job.prefix.leader != null; } -/// Whether `job`, picked for a lane, waits instead: a fill short of a cut its lookup would resume (lock held). +/// Whether `job`, picked for a lane, waits instead: a cut its lookup would resume, or its own whole fill (lock held). pub fn waits(h: *LaneHost, job: *Job) bool { if (job.prefix.waited or h.prefix.ns <= 0 or !h.core.fills()) return false; // a request waits once: no cycle const store = h.cache orelse return false; @@ -45,6 +47,11 @@ pub fn waits(h: *LaneHost, job: *Job) bool { var best: Waiting = .{}; for (h.filling.items) |l| { // admitted fills never wait, so the oldest always runs if (!l.started or l.prefilled != null or l.request.background or !keyed(l.request)) continue; + // a single-flight join: the leader's prompt is the waiter's own; armed only when its fill keeps anything + if (joinable(h, r, spans, l) and room(h, job, l) and l.marks.len > 0 and store.most != 0) { + best = .{ .leader = l, .id = l.id, .whole = true }; + break; // filling order: the oldest leader + } for (l.marks) |at| { if (at <= l.reached or at < least or at <= best.at) continue; if (store.wouldServe(r.cacheKey(), r.chunks, spans, l.request.cacheKey(), h.spans(l.request), at)) @@ -56,15 +63,34 @@ pub fn waits(h: *LaneHost, job: *Job) bool { best.waited = true; job.prefix = best; h.prefix.waits += 1; + if (best.whole) h.prefix.joins += 1; return true; } +/// Whether filling `l` is the waiter's own prompt: key tokens, raw tokens and spans, no mark consulted (lock held). +fn joinable(h: *LaneHost, r: *const api.Request, spans: []const [2]u32, l: *const Job) bool { + if (!std.mem.eql(u32, r.cacheKey(), l.request.cacheKey())) return false; + if (!std.mem.eql(u32, r.prompt, l.request.prompt)) return false; + return modes.equal(spans, h.spans(l.request), @intCast(l.request.prompt.len)); +} + +/// Whether `l` holds fewer whole-fill waiters than the admission cap (lock held). +fn room(h: *LaneHost, job: *const Job, l: *const Job) bool { + const cap = @min(h.info_.lanes, h.memory_lanes orelse h.info_.lanes); + var held: usize = 0; + for (h.queued.items) |j| { + if (j == job) continue; + if (j.prefix.whole and j.prefix.leader == l and j.prefix.id == l.id) held += 1; + } + return held < cap; +} + /// A request whose states the cache keys by its tokens alone, as the host's lookup does (no pictures). fn keyed(r: *const api.Request) bool { return !r.promptOnly() and r.prompt_logprobs == null and !r.untaught and r.images.len == 0 and r.cacheKey().len > 0; } -/// Waiting requests go on in queue order: their fill stood at the cut, left the fills, or the bound passed (lock held). +/// Waiting requests go on in queue order: the cut stood, the whole fill is done, the leader left, or the bound passed. pub fn release(h: *LaneHost) void { var now: ?i96 = null; for (h.queued.items) |job| { @@ -73,12 +99,15 @@ pub fn release(h: *LaneHost) void { const live = for (h.filling.items) |l| { if (l == leader and l.id == w.id) break l; // the same job, not a later one at its address } else null; - if (live) |l| if (l.reached < w.at and l.prefilled == null) { - const t = now orelse std.Io.Clock.awake.now(h.io).toNanoseconds(); - now = t; - if (t - w.since < h.prefix.ns) continue; - h.prefix.timeouts += 1; - }; + if (live) |l| { + const pending = if (w.whole) l.prefilled == null else (l.reached < w.at and l.prefilled == null); + if (pending) { + const t = now orelse std.Io.Clock.awake.now(h.io).toNanoseconds(); + now = t; + if (t - w.since < h.prefix.ns) continue; + h.prefix.timeouts += 1; + } + } job.prefix.leader = null; } } diff --git a/zig/src/core/lane_host_prefix_join_test.zig b/zig/src/core/lane_host_prefix_join_test.zig new file mode 100644 index 00000000000..051a53c8dca --- /dev/null +++ b/zig/src/core/lane_host_prefix_join_test.zig @@ -0,0 +1,251 @@ +//! The single-flight join: identical concurrent prompts join a filling leader (fake backend). +const std = @import("std"); +const lanes = @import("lanes"); +const api = @import("engine_api.zig"); +const pc = @import("prompt_cache.zig"); +const prefix = @import("lane_host_prefix.zig"); +const LaneHost = api.LaneHost; +const Id = api.Id; +const Event = api.Event; +const Request = api.Request; +const Reason = api.Reason; +const gpa = std.testing.allocator; + +const system_len = 1030; // the shared system prompt +const cut = 1024; // its last start on the store's 16-row grid, the cut the leader's fill keeps +const tail_len = 512; // the prompts' own tail: the rows past the cut a released waiter would prefill beside the leader +const prompt_len = system_len + tail_len; +const requests = 4; // the issue's shape: several identical prompts arrive together + +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; // lane-core backends restore inside their own prompt pass + } + fn drop(ptr: *anyopaque, saved: pc.Saved) void { + const f: *lanes.fake.Fake = @ptrCast(@alignCast(ptr)); + f.drop(saved); + } +}; + +const Box = struct { + mutex: std.Io.Mutex = .init, + tokens: std.ArrayList(u32) = .empty, + cached: ?u32 = null, + done: ?Reason = null, + fn event(ctx: *anyopaque, _: Id, e: *const Event) void { + const b: *Box = @ptrCast(@alignCast(ctx)); + b.mutex.lockUncancelable(std.testing.io); + defer b.mutex.unlock(std.testing.io); + switch (e.*) { + .prefilled => |c| b.cached = c, + .tokens => |t| b.tokens.appendSlice(gpa, t) catch {}, + .finished => |f| b.done = f.reason, + else => {}, + } + } + fn wait(b: *Box) Reason { + while (true) { + 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 {}; + } + } +}; + +/// Each prompt chunk sleeps `slow_ms` and records the call: the stream, and how many streams are open. +const Hook = struct { + fake: *lanes.fake.Fake, + slow_ms: i64 = 0, + cancel: ?struct { engine: api.Engine, id: Id, at: usize } = null, + streams: std.ArrayList(*lanes.Stream) = .empty, + open: std.ArrayList(usize) = .empty, + + fn call(ctx: *anyopaque, s: *lanes.Stream, chunk: usize) void { + const h: *Hook = @ptrCast(@alignCast(ctx)); + if (h.slow_ms > 0) std.Io.sleep(std.testing.io, .fromMilliseconds(h.slow_ms), .awake) catch {}; + h.streams.append(gpa, s) catch {}; + h.open.append(gpa, h.fake.lanes.count()) catch {}; + if (h.cancel) |c| if (chunk == c.at) c.engine.cancel(c.id); + } +}; + +const Run = struct { + boxes: [8]Box = @splat(.{}), + reasons: [8]Reason = undefined, + cached: [8]?u32 = @splat(null), + waits: u64 = 0, + joins: u64 = 0, + timeouts: u64 = 0, + queued_after: usize = 0, + leader_open_most: usize = 0, // the most streams open at any prompt call of the first filling stream + misses: u64 = 0, + + fn deinit(r: *Run) void { + for (&r.boxes) |*b| b.tokens.deinit(gpa); + } +}; + +/// The identical prompt every request names: the system prompt, then the same tail. +fn promptOf(buf: *[prompt_len]u32) []const u32 { + for (buf[0..system_len], 0..) |*t, k| t.* = 100 + @as(u32, @intCast(k % 97)); + for (buf[system_len..], 0..) |*t, k| t.* = 300 + @as(u32, @intCast(k)); + return buf; +} + +/// Identical requests queued before the host starts (together); `budget` 0 is a cold cache; `cancel_at` cancels. +fn fanout(wait_ms: ?u32, slow_ms: i64, cancel_at: ?usize, budget: u64, out: *Run) !void { + 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 = 13 }; + defer target.deinit(); + var clock: lanes.fake.FixedClock = .{}; + var core = lanes.Engine.init(gpa, &cfg, target.stepped(), clock.clock()); + defer core.deinit(); + const rules: pc.Rules = .{ .lookahead = 1, .min_prompt = 0, .planned = true, .grid = 16, .chunk = 16 }; + var store = pc.Store.init(gpa, .{ .ptr = &target, .vtable = &.{ .bytes = Snaps.bytes, .save = Snaps.save, .restore = Snaps.restore, .drop = Snaps.drop } }, rules, budget); + defer store.deinit(); + var host = LaneHost.init(gpa, std.testing.io, &core, .{ .lanes = 8 }); + host.cache = &store; + if (wait_ms) |ms| host.prefix.ns = @as(i96, ms) * std.time.ns_per_ms; + const e = host.engine(); + var hook = Hook{ .fake = &target, .slow_ms = slow_ms }; + if (cancel_at) |at| hook.cancel = .{ .engine = e, .id = 1, .at = at }; + defer { + hook.streams.deinit(gpa); + hook.open.deinit(gpa); + } + target.prefill_hook = Hook.call; + target.prefill_hook_ctx = &hook; + var buf: [prompt_len]u32 = undefined; + const prompt = promptOf(&buf); + var reqs: [requests]Request = undefined; + const shared = [_]u32{system_len}; + for (0..requests) |i| { + reqs[i] = .{ .prompt = prompt, .max_tokens = 6, .shared_prefixes = &shared }; + try e.submit(@intCast(i + 1), &reqs[i], .{ .ctx = &out.boxes[i], .event = Box.event }); + } + try host.start(); + defer host.stop(); + for (0..requests) |i| { + out.reasons[i] = out.boxes[i].wait(); + out.cached[i] = out.boxes[i].cached; + } + host.lock(); + out.queued_after = host.queued.items.len; + host.unlock(); + out.waits = host.prefix.waits; + out.joins = host.prefix.joins; + out.timeouts = host.prefix.timeouts; + out.misses = store.counts.misses; + if (hook.streams.items.len > 0) { + const leader = hook.streams.items[0]; + for (hook.streams.items, hook.open.items) |s, n| { + if (s == leader) out.leader_open_most = @max(out.leader_open_most, n); + } + } +} + +test "single-flight: identical prompts join the filling leader, whose whole fill runs alone" { + var on: Run = .{}; + defer on.deinit(); + try fanout(null, 1, null, 1 << 24, &on); + var off: Run = .{}; + defer off.deinit(); + try fanout(0, 1, null, 1 << 24, &off); + for (0..requests) |i| { + try std.testing.expectEqual(Reason.length, on.reasons[i]); + try std.testing.expectEqual(Reason.length, off.reasons[i]); + try std.testing.expectEqualSlices(u32, off.boxes[i].tokens.items, on.boxes[i].tokens.items); // joined == solo + } + // the leader prefills whole; each joiner waits for the whole fill and resumes the leader's kept cut + try std.testing.expectEqualSlices(?u32, &.{ 0, cut, cut, cut }, on.cached[0..requests]); + try std.testing.expectEqual(@as(u64, requests - 1), on.joins); + try std.testing.expectEqual(@as(u64, requests - 1), on.waits); + try std.testing.expectEqual(@as(u64, 0), on.timeouts); + try std.testing.expectEqual(@as(usize, 0), on.queued_after); + // the leader's whole fill ran with no joiner's stream open beside it: one identical prompt computes at a time + try std.testing.expectEqual(@as(usize, 1), on.leader_open_most); + // off (TENSORFOLD_PREFIX_WAIT_MS=0): every prompt fills side by side, its stream open beside the leader's + try std.testing.expectEqualSlices(?u32, &.{ 0, 0, 0, 0 }, off.cached[0..requests]); + try std.testing.expectEqual(@as(u64, 0), off.waits); + try std.testing.expect(off.leader_open_most > 1); // the check detects the side-by-side prefill this joins + try std.testing.expectEqual(@as(u64, requests), off.misses); // cold: every prompt missed, none waited + try std.testing.expectEqual(@as(u64, 1), on.misses); // only the leader's lookup missed; the joiners hit its cut +} + +test "single-flight: cold cache — nothing will be kept, so the join does not arm and the prompts run side by side" { + var on: Run = .{}; + defer on.deinit(); + try fanout(null, 1, null, 0, &on); + var off: Run = .{}; + defer off.deinit(); + try fanout(0, 1, null, 0, &off); + for (0..requests) |i| { + try std.testing.expectEqual(Reason.length, on.reasons[i]); + try std.testing.expectEqual(Reason.length, off.reasons[i]); + try std.testing.expectEqualSlices(u32, off.boxes[i].tokens.items, on.boxes[i].tokens.items); // == solo + } + // a zero budget plans no mark and keeps nothing: every lookup missed, nothing is resumable + try std.testing.expectEqual(@as(u64, requests), on.misses); + try std.testing.expectEqualSlices(?u32, &.{ 0, 0, 0, 0 }, on.cached[0..requests]); + // the join did not arm: with nothing kept a joiner would wait out the whole fill, then prefill from the start + try std.testing.expectEqual(@as(u64, 0), on.joins); + try std.testing.expectEqual(@as(u64, 0), on.waits); + try std.testing.expect(on.leader_open_most > 1); // every prompt's stream open beside the leader's +} + +test "single-flight: fail-open, the leader cancelled — every waiter prefills its own prompt and matches a solo run" { + const cancel_at = 2; // the leader dies on its second prompt chunk + var on: Run = .{}; + defer on.deinit(); + try fanout(null, 1, cancel_at, 1 << 24, &on); + var off: Run = .{}; + defer off.deinit(); + try fanout(0, 1, cancel_at, 1 << 24, &off); + // the leader's own reply is the cancellation in both runs + try std.testing.expectEqual(Reason.cancelled, on.reasons[0]); + try std.testing.expectEqual(Reason.cancelled, off.reasons[0]); + for (1..requests) |i| { + // each released waiter finished whole, token for token a no-join run's + try std.testing.expectEqual(Reason.length, on.reasons[i]); + try std.testing.expectEqual(Reason.length, off.reasons[i]); + try std.testing.expectEqualSlices(u32, off.boxes[i].tokens.items, on.boxes[i].tokens.items); + } + // the joiners armed on identity, then the leader's cancellation released them: no bound passed + try std.testing.expectEqual(@as(u64, requests - 1), on.joins); + try std.testing.expectEqual(@as(u64, requests - 1), on.waits); + try std.testing.expectEqual(@as(u64, 0), on.timeouts); + try std.testing.expectEqual(@as(u64, 0), off.joins); +} + +test "single-flight: fail-open, the bound passes — every waiter is released and prefills beside the leader" { + // a 1 ms bound against a leader whose chunks each take 30 ms: no waiter survives to the whole fill + var on: Run = .{}; + defer on.deinit(); + try fanout(1, 30, null, 1 << 24, &on); + var off: Run = .{}; + defer off.deinit(); + try fanout(0, 30, null, 1 << 24, &off); + for (0..requests) |i| { + try std.testing.expectEqual(Reason.length, on.reasons[i]); + try std.testing.expectEqual(Reason.length, off.reasons[i]); + try std.testing.expectEqualSlices(u32, off.boxes[i].tokens.items, on.boxes[i].tokens.items); // released == solo + } + // each joiner armed, then the bound released it: the timeouts counter carries the releases + try std.testing.expectEqual(@as(u64, requests - 1), on.joins); + try std.testing.expectEqual(@as(u64, requests - 1), on.timeouts); + // each released waiter left before the leader's first keep and does not re-lookup: it prefilled from zero + try std.testing.expectEqual(@as(u64, requests), on.misses); + try std.testing.expectEqualSlices(?u32, &.{ 0, 0, 0, 0 }, on.cached[0..requests]); + // the released waiters filled side by side: the bound gives back the throughput the join would have held + try std.testing.expect(on.leader_open_most > 1); +} diff --git a/zig/src/core/lane_host_rows.zig b/zig/src/core/lane_host_rows.zig index 19007002f00..bfeaf32aa2b 100644 --- a/zig/src/core/lane_host_rows.zig +++ b/zig/src/core/lane_host_rows.zig @@ -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 !h.disk.push(h.gpa, a)) return false; + if (h.closing 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; } @@ -40,9 +40,24 @@ pub fn answer(h: *LaneHost) void { }; h.lock(); const list = h.disk.take(h.gpa); + // a flush waits for the requests in flight to end; admit.pick and the planner hold new ones meanwhile + var flushes = if (h.admitted.items.len == 0 and h.core.activeCount() == 0) h.disk.takeFlushes() else Flushes.empty; h.unlock(); defer h.gpa.free(list); + defer flushes.deinit(h.gpa); for (list) |a| a.answer(h.cache, .{ .spans = h.decoded_rows }); // keyed as its lookups are + for (flushes.items) |a| a.answer(h.cache, .{}); + if (flushes.items.len > 0) published(h); +} + +const Flushes = std.ArrayList(*api.ImprintAsk); + +/// The status copies after a flush, whole at once: an idle planner publishes none until its next round. +fn published(h: *LaneHost) void { + h.lock(); + h.cache_at = 0; + h.unlock(); + @import("lane_host_status.zig").noteLive(h); } /// Asks left when the engine stops: answered as having no disk states. diff --git a/zig/src/core/lane_host_tests.zig b/zig/src/core/lane_host_tests.zig index fb77dfa0ddd..0e08638c83e 100644 --- a/zig/src/core/lane_host_tests.zig +++ b/zig/src/core/lane_host_tests.zig @@ -10,6 +10,7 @@ test { _ = @import("lane_init_test.zig"); _ = @import("lane_failure_review_test.zig"); _ = @import("lane_host_first_test.zig"); + _ = @import("lane_host_prefix_join_test.zig"); } test { @@ -29,6 +30,7 @@ test { test { _ = @import("lane_activity_test.zig"); + _ = @import("lane_host_flush_test.zig"); } test { diff --git a/zig/src/core/lane_job.zig b/zig/src/core/lane_job.zig index 38d8bdd8d4a..1eff738ab23 100644 --- a/zig/src/core/lane_job.zig +++ b/zig/src/core/lane_job.zig @@ -46,6 +46,7 @@ pub const Job = struct { lease: @import("kv_ledger.zig").Lease = .{}, // its caches' bytes in the host's ledger, from admission to its end wait_reason: @import("wait_reason.zig").Wait = .engine_busy, // while queued: the hold its last admission try met fell_back: bool = false, // its saved prefix's restore fallback is counted (once a request) + backlog: @import("lane_host_backlog.zig").Watch = .{}, // a slow reader's hold on its stream (engine thread only) /// Record first admission once (a family planner's too, a yielding background pass's kept) and clear its wait. pub fn noteAdmission(job: *Job) void { diff --git a/zig/src/core/lane_rounds.zig b/zig/src/core/lane_rounds.zig index 02dc8520a41..6a40762df2f 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)) { + 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()) { rd.vtable.begin_admit(rd.ctx); var free = h.info_.lanes - h.admitted.items.len; var i: usize = 0; @@ -295,6 +295,7 @@ fn runFinals(h: *LaneHost) void { /// The engine thread under a round planner; an idle round waits for an arrival, a cancel or a short timeout. pub fn run(h: *LaneHost, rd: Rounds) void { while (true) { + @import("lane_host_backlog.zig").step(h); // holds precede activity: waits are idle var activity = @import("lane_activity.zig").Activity.enter(h.activity); defer activity.end(); ends.takeCancels(h); diff --git a/zig/src/core/lanes/config.zig b/zig/src/core/lanes/config.zig index 09df22cb2bd..94c02370b2f 100644 --- a/zig/src/core/lanes/config.zig +++ b/zig/src/core/lanes/config.zig @@ -36,6 +36,7 @@ pub const Model = struct { window_costs: []const Cost = &.{}, // forward ms by exact window width (timed at load) window_costs_lone: bool = false, // window_costs price a lone stream only; shared forwards use shared_costs shared_drafts: u32 = 0, // allocate_shared_drafts: a shared round's most head drafts a stream (0: drafts) + shared_mtp_cap: u32 = 0, // most head drafts a stream chains in a shared round; a lone one chains `drafts` (0: off) mtp_step_ms: f64 = 0.0, // one chained head step (timed at load) shared_step_ms: ?f64 = null, // a separate shared head step; null keeps mtp_step_ms draft_step_ms: f64 = 0.0, // a shared round's draft past a stream's first, as the backend's head runs it (0: priced free) @@ -110,6 +111,7 @@ pub const Config = struct { mtp_step_ms: f64, draft_step_ms: f64 = 0, // Model.draft_step_ms shared_drafts: u32 = 0, // Model.shared_drafts + shared_mtp_cap: u32 = 0, // Model.shared_mtp_cap lone_cost_tile: u32 = 0, // Model.lone_cost_tile context_copies: bool = false, // Model.context_copies, within the existing verification width enter_match: i64 = 8, // matching tokens a copy needs (rejects coincidental indentation) @@ -200,6 +202,7 @@ pub const Config = struct { }, .draft_step_ms = m.draft_step_ms, .shared_drafts = m.shared_drafts, + .shared_mtp_cap = m.shared_mtp_cap, }; } diff --git a/zig/src/core/lanes/deep_chain_test.zig b/zig/src/core/lanes/deep_chain_test.zig new file mode 100644 index 00000000000..fc04e852164 --- /dev/null +++ b/zig/src/core/lanes/deep_chain_test.zig @@ -0,0 +1,156 @@ +//! A lone stream chains up to a model's most drafts while shared rounds keep the model's shared cap. +const std = @import("std"); +const depth = @import("depth.zig"); + +const empty: @import("table.zig").Table = .{}; +const high: [7]f64 = @splat(0.95); +const low: [7]f64 = @splat(0.5); + +const NoCopy = struct { + fn copy(_: *anyopaque, _: *const depth.Who) bool { + return false; + } +}; + +fn rule(prior: []const f64, shared_cap: u32) depth.Rule { + return .{ + .gpa = std.testing.allocator, + .prior = prior, + .most_drafts = 7, + .shared_cap = shared_cap, + .family_costs = &empty, + .shared_costs = &empty, + .mtp_step_ms = 0, + .plain_guard = false, + .node_probabilities = false, + .batch_rows = 16, + }; +} + +fn who(state: *?depth.State) depth.Who { + return .{ .state = state, .draft_room = 100, .finished = false, .forced = false }; +} + +test "a lone stream asks for most_drafts on a high first-draft acceptance and stays low on a low one" { + var unused: u8 = 0; + const probe: depth.Probe = .{ .ptr = &unused, .copy = NoCopy.copy }; + var r = rule(&high, 3); + defer r.deinit(); + var s: ?depth.State = null; + defer if (s) |*x| x.deinit(std.testing.allocator); + try std.testing.expectEqual(@as(i64, 7), try r.headDepth(&who(&s), null, probe)); + r.prior = &low; + var t: ?depth.State = null; + defer if (t) |*x| x.deinit(std.testing.allocator); + try std.testing.expectEqual(@as(i64, 1), try r.headDepth(&who(&t), null, probe)); +} + +test "streams that share a round chain at most the shared cap each" { + var unused: u8 = 0; + const probe: depth.Probe = .{ .ptr = &unused, .copy = NoCopy.copy }; + var r = rule(&high, 3); + defer r.deinit(); + var a: ?depth.State = null; + var b: ?depth.State = null; + defer if (a) |*x| x.deinit(std.testing.allocator); + defer if (b) |*x| x.deinit(std.testing.allocator); + var whos = [_]depth.Who{ who(&a), who(&b) }; + var out: [2]i64 = undefined; + try r.budgets(&whos, probe, false, &out); + try std.testing.expect(out[0] > 0 and out[1] > 0); + try std.testing.expect(out[0] <= 3 and out[1] <= 3); +} + +test "a zero shared cap keeps the ladder's top of three for a lone stream and most_drafts for shared budgets" { + var unused: u8 = 0; + const probe: depth.Probe = .{ .ptr = &unused, .copy = NoCopy.copy }; + var r = rule(&high, 0); + defer r.deinit(); + var a: ?depth.State = null; + var b: ?depth.State = null; + defer if (a) |*x| x.deinit(std.testing.allocator); + defer if (b) |*x| x.deinit(std.testing.allocator); + try std.testing.expectEqual(@as(i64, 3), try r.headDepth(&who(&a), null, probe)); + var whos = [_]depth.Who{ who(&a), who(&b) }; + var out: [2]i64 = undefined; + try r.budgets(&whos, probe, false, &out); + try std.testing.expect(out[0] > 3 or out[1] > 3); +} + +test "under a confidence floor or node probabilities a shared round chains at most the cap; a lone stream chains seven" { + var unused: u8 = 0; + const probe: depth.Probe = .{ .ptr = &unused, .copy = NoCopy.copy }; + inline for (.{ .{ 0.5, false }, .{ null, false }, .{ null, true } }) |c| { + for ([_]u32{ 3, 0 }) |cap| { + var r = rule(&high, cap); + defer r.deinit(); + r.node_probabilities = true; + r.confidence_floor = c[0]; + r.granted_depth = c[1]; + var a: ?depth.State = null; + var b: ?depth.State = null; + defer if (a) |*x| x.deinit(std.testing.allocator); + defer if (b) |*x| x.deinit(std.testing.allocator); + try std.testing.expectEqual(@as(i64, 7), try r.headDepth(&who(&a), null, probe)); + var whos = [_]depth.Who{ who(&a), who(&b) }; + var out: [2]i64 = undefined; + try r.budgets(&whos, probe, false, &out); + const want: i64 = if (cap == 0) 7 else 3; + try std.testing.expectEqualSlices(i64, &.{ want, want }, &out); + } + } +} + +test "allocated shared rows, granted or not, reserve at most the shared cap a stream" { + const a = std.testing.allocator; + const Cfg = @import("config.zig"); + const fake = @import("fake.zig"); + const S = @import("stream.zig").Stream; + const win = @import("windows.zig"); + for ([_]bool{ false, true }) |granted| { + for ([_]u32{ 3, 0 }) |cap| { + var cfg = try Cfg.Config.init(a, .{ .exact_width = 8, .drafts = 7, .shared_mtp_cap = cap, .allocate_shared_drafts = true, .draft_probabilities = granted, .granted_depth = granted, .batch_rows = 16 }, 8, 7); + defer cfg.deinit(a); + var back: fake.Fake = .{ .gpa = a }; + defer back.deinit(); + var clock: fake.FixedClock = .{}; + var e = @import("engine.zig").Engine.init(a, &cfg, back.backend(), clock.clock()); + defer e.deinit(); + var one = try S.init(a, .{ .id = "one", .prompt = &.{ 7, 13, 29 }, .max_new = 64 }); + defer one.deinit(a); + var two = try S.init(a, .{ .id = "two", .prompt = &.{ 7, 13, 29 }, .max_new = 64 }); + defer two.deinit(a); + try one.draft_chances.appendNTimes(a, 1, 7); + try two.draft_chances.appendNTimes(a, 1, 7); + const plans = [_]win.Plan{ .{ .stream = &one, .position = 0, .kind = .none }, .{ .stream = &two, .position = 0, .kind = .none } }; + var out: [2]i64 = undefined; + try @import("shared_drafts.zig").budgets(&e, &plans, &.{ 0, 1 }, &out); + const want: i64 = if (cap == 0) 7 else 3; + try std.testing.expectEqualSlices(i64, &.{ want, want }, &out); + } + } +} + +test "a stream that opens beside a live one takes at most the shared cap as its first drafts" { + const a = std.testing.allocator; + const Cfg = @import("config.zig"); + const fake = @import("fake.zig"); + const S = @import("stream.zig").Stream; + for ([_]u32{ 3, 0 }) |cap| { + var cfg = try Cfg.Config.init(a, .{ .exact_width = 8, .drafts = 7, .shared_mtp_cap = cap, .draft_probabilities = true, .batch_rows = 16 }, 8, 7); + defer cfg.deinit(a); + var back: fake.Fake = .{ .gpa = a }; + defer back.deinit(); + var clock: fake.FixedClock = .{}; + var e = @import("engine.zig").Engine.init(a, &cfg, back.backend(), clock.clock()); + defer e.deinit(); + var live = try S.init(a, .{ .id = "live", .prompt = &.{ 7, 13, 29 }, .max_new = 64 }); + defer live.deinit(a); + var s = try S.init(a, .{ .id = "new", .prompt = &.{ 7, 13, 29 }, .max_new = 64 }); + defer s.deinit(a); + try std.testing.expectEqual(@as(u32, 7), try @import("open.zig").firstDepth(&e, &s, .head)); + try e.live.append(a, &live); + defer e.live.clearRetainingCapacity(); + try std.testing.expectEqual(@as(u32, if (cap == 0) 7 else 3), try @import("open.zig").firstDepth(&e, &s, .head)); + } +} diff --git a/zig/src/core/lanes/depth.zig b/zig/src/core/lanes/depth.zig index b6eeeaf861e..11e11b6639c 100644 --- a/zig/src/core/lanes/depth.zig +++ b/zig/src/core/lanes/depth.zig @@ -58,6 +58,7 @@ pub const Rule = struct { k: Constants = .{}, prior: []const f64, most_drafts: u32, + shared_cap: u32 = 0, // Model.shared_mtp_cap: most a shared round chains a stream; a lone one chains most_drafts (0: off) family_costs: *const Table, shared_costs: *const Table, mtp_step_ms: f64, @@ -172,7 +173,7 @@ pub const Rule = struct { if (r.confidence_floor != null and !who.sampled and !r.k.floor_rates) return most; const p = try r.rates(who); if (r.family_costs.empty()) { - const want: i64 = if (p[0] < 0.8) 1 else if (p[0] < 0.9) 2 else 3; + const want: i64 = if (p[0] < 0.8) 1 else if (p[0] < 0.9) 2 else if (r.shared_cap != 0) r.most_drafts else 3; return @max(1, @min(most, want)); } const st = try r.state(who); @@ -390,15 +391,15 @@ pub const Rule = struct { const streams = if (paired != null) total_streams else whos.len; // drafts lose here: none asked, no head pass if (r.plain_streams > 0 and whos.len >= r.plain_streams) return @memset(out, 0); + const top: i64 = if (r.shared_cap != 0) @min(r.most_drafts, r.shared_cap) else r.most_drafts; if (r.confidence_floor != null) { - for (whos, out) |*w, *o| o.* = try r.headDepth(w, null, probe); + for (whos, out) |*w, *o| o.* = @min(try r.headDepth(w, null, probe), top); return; } if (r.node_probabilities) { for (whos, out) |*w, *o| { - const inner = try r.headDepth(w, null, probe); - const granted: i64 = if (w.granted) |g| g else r.most_drafts; - o.* = if (r.granted_depth) inner else try r.headDepth(w, @min(inner, granted + r.k.draft_slack), probe); + const inner = @min(try r.headDepth(w, null, probe), top); + o.* = if (r.granted_depth) inner else try r.headDepth(w, @min(inner, @as(i64, w.granted orelse r.most_drafts) + r.k.draft_slack), probe); } if (r.granted_depth) capPass(out, r.batch_rows); if (r.granted_depth and r.k.hold_costs.len > 0) try r.payHoldsFor(whos, sampled, out, total_streams); @@ -412,7 +413,7 @@ pub const Rule = struct { var made: usize = 0; defer for (probs[0..made]) |p| r.gpa.free(p); for (whos, most, probs[0..whos.len]) |w, *m, *p| { - m.* = @min(@as(i64, r.most_drafts), @max(1, w.draft_room - 1)); + m.* = @min(top, @max(1, w.draft_room - 1)); p.* = try alloc.chainProbabilities(r.gpa, try r.rates(w), @intCast(m.*)); made += 1; } diff --git a/zig/src/core/lanes/engine.zig b/zig/src/core/lanes/engine.zig index e29b22022c5..285fd9c9c27 100644 --- a/zig/src/core/lanes/engine.zig +++ b/zig/src/core/lanes/engine.zig @@ -66,6 +66,7 @@ pub const Engine = struct { .k = cfg.k, .prior = cfg.depth_prior, .most_drafts = cfg.most_drafts, + .shared_cap = cfg.shared_mtp_cap, .family_costs = &cfg.family_costs, .shared_costs = &cfg.shared_costs, .mtp_step_ms = cfg.mtp_step_ms, @@ -128,9 +129,7 @@ pub const Engine = struct { } if (live.items.len > 1 and e.cfg.family_streams) { // a shared round is synchronous: a stream that ran a step ahead lands its queued token first - for (live.items) |s| { - if (s.inflight != null) try e.landInflight(s); - } + for (live.items) |s| if (s.inflight != null) try e.landInflight(s); var kept: usize = 0; for (live.items) |s| { if (s.finished) continue; diff --git a/zig/src/core/lanes/lanes.zig b/zig/src/core/lanes/lanes.zig index 5dd92e910b6..2672ab245b9 100644 --- a/zig/src/core/lanes/lanes.zig +++ b/zig/src/core/lanes/lanes.zig @@ -63,6 +63,7 @@ test { std.testing.refAllDecls(@This()); _ = @import("engine_test.zig"); _ = @import("plain_streams_test.zig"); + _ = @import("deep_chain_test.zig"); _ = @import("late_draft_test.zig"); _ = @import("long_loop.zig"); _ = @import("long_loop_test.zig"); diff --git a/zig/src/core/lanes/lone_copy_price_test.zig b/zig/src/core/lanes/lone_copy_price_test.zig index e7acd461178..8299123b142 100644 --- a/zig/src/core/lanes/lone_copy_price_test.zig +++ b/zig/src/core/lanes/lone_copy_price_test.zig @@ -157,9 +157,9 @@ fn run(m: cfgs.Model, times: [2]f64, copier: ?Copier, streams: usize, max_new: u return out; } -/// hip_lanes.zig facts in small: 16-row windows, timed forwards; plain rounds compete with a head, lone copies always. +/// hip_lanes.zig facts in small: 16-row windows, timed forwards; plain rounds and lone copies always compete. fn hip(head: bool) cfgs.Model { - return .{ .exact_width = 16, .mtp = head, .speculate = head, .speculate_early = false, .drafts = 4, .plain_guard = head, .copy_guard = true, .window_costs = &startup, .mtp_step_ms = if (head) 0.5 else 0, .hidden_rows = true, .batch_rows = 32, .max_streams = 4 }; + return .{ .exact_width = 16, .mtp = head, .speculate = head, .speculate_early = false, .drafts = 4, .plain_guard = true, .copy_guard = true, .window_costs = &startup, .mtp_step_ms = if (head) 0.5 else 0, .hidden_rows = true, .batch_rows = 32, .max_streams = 4 }; } fn expectPlain(m: cfgs.Model, times: [2]f64, got: Run, streams: usize, max_new: u32) !void { @@ -244,29 +244,6 @@ test "lone copy price: shared rounds' copies stay as on main (the streams' lone } } -/// A hash of the trail's lines up to the first step without a shared round, and how many lines that is. -fn sharedPhase(log: *ev.Log) ![2]u64 { - var end: usize = log.events.items.len; - var step: ?usize = null; - var turns = false; - for (log.events.items, 0..) |fields, i| { - const kind = for (fields) |x| { - if (std.mem.eql(u8, x.k, "ev")) break x.v.str; - } else ""; - if (std.mem.eql(u8, kind, "turns")) turns = true; - if (!std.mem.eql(u8, kind, "step")) continue; - if (step) |at| if (!turns) { - end = at; - break; - }; - step = i; - turns = false; - } else if (step) |at| if (!turns) { - end = at; // the run's last step was a lone one - }; - return hashed(log, end); -} - /// A hash of the trail's first `end` lines, and `end`. fn hashed(log: *ev.Log, end: usize) ![2]u64 { var h = std.hash.Wyhash.init(0); @@ -279,25 +256,6 @@ fn hashed(log: *ev.Log, end: usize) ![2]u64 { return .{ h.final(), end }; } -test "lone copy price: HIP's facts without a head keep main's shared rounds, two and four streams" { - // main e7e24243d, its hip_lanes.zig facts without a head (no plain_guard): the shared phase's trail, hashed - const cases = [_]struct { streams: usize, copier: Copier, expected: [2]u64 }{ - .{ .streams = 2, .copier = .{}, .expected = .{ 12160614949009965908, 1276 } }, - .{ .streams = 2, .copier = .{ .land_from = 48 }, .expected = .{ 612887639395430184, 445 } }, - .{ .streams = 4, .copier = .{}, .expected = .{ 5045447432178392522, 1790 } }, - .{ .streams = 4, .copier = .{ .land_from = 80 }, .expected = .{ 5351245168654378449, 1104 } }, - }; - for (cases) |c| { - var log = ev.Log.init(gpa); - defer log.deinit(); - trail = &log; - defer trail = null; - _ = try run(hip(false), long_context, c.copier, c.streams, 128); - const got = try sharedPhase(&log); - try std.testing.expectEqual(c.expected, got); - } -} - test "lone copy price: copy_guard is off unless a family opts in, whatever plain_guard says" { for ([_]bool{ false, true }) |plain| { var unset = try cfgs.Config.init(gpa, .{ .exact_width = 16, .plain_guard = plain }, 16, 15); @@ -406,12 +364,12 @@ test "lone copy price: a request's first copies are priced from the copy rounds for (got, 0..) |r, i| try std.testing.expectEqualSlices(u32, plain.tokens[i][0..plain.lens[i]], r.tokens[0..r.len]); // the second request starts from the first's timed copies: its first copy is whole, as the first's later ones try std.testing.expectEqual(@as(?usize, 15), got[1].first); - // without a head the first request timed its plain rounds before any copy: the untimed price cut its first one + // without a head, copy pricing starts from probes; its first copy can be partial if (!head) try std.testing.expect(got[0].first.? < 15); } } -test "lone copy price: kept copy prices need two timed copies on a lone stream, leave a head's times, keep a stream's own" { +test "lone copy price: kept copy prices need two timed copies on a lone stream and leave depth-rule times out" { for ([_]bool{ false, true }) |head| { var cfg = try cfgs.Config.init(gpa, hip(head), 16, 15); defer cfg.deinit(gpa); @@ -438,8 +396,8 @@ test "lone copy price: kept copy prices need two timed copies on a lone stream, _ = try e.rule.rates(win.who(&next)); try lone_costs.seedCopies(gpa, lone_costs.slot(&e.lone_kept, &next).*, &next); try std.testing.expectEqual(@as(?f64, 11.6), next.depth.?.copy_ms.?.get(15)); - // a head's own round times are its depth rule's, never carried by copy pricing - try std.testing.expectEqual(@as(?f64, if (head) null else 10.1), if (next.depth.?.ms) |t| t.get(0) else null); + // plain and head round times belong to the depth rule, never carried by copy pricing + try std.testing.expectEqual(@as(?f64, null), if (next.depth.?.ms) |t| t.get(0) else null); const long = try gpa.alloc(u32, 8192); defer gpa.free(long); @memset(long, 1); @@ -453,7 +411,7 @@ test "lone copy price: kept copy prices need two timed copies on a lone stream, try copy_price.observeCopy(&e.rule, 15, 30, false, win.who(&timed)); try lone_costs.seedCopies(gpa, lone_costs.slot(&e.lone_kept, &timed).*, &timed); try std.testing.expectEqual(@as(?f64, 30), timed.depth.?.copy_ms.?.get(15)); // its own copy times stay - try std.testing.expectEqual(@as(?f64, if (head) null else 10.1), if (timed.depth.?.ms) |t| t.get(0) else null); + try std.testing.expectEqual(@as(?f64, null), if (timed.depth.?.ms) |t| t.get(0) else null); } } diff --git a/zig/src/core/lanes/lone_copy_sampled_test.zig b/zig/src/core/lanes/lone_copy_sampled_test.zig index 9818fbf63b3..c8095147165 100644 --- a/zig/src/core/lanes/lone_copy_sampled_test.zig +++ b/zig/src/core/lanes/lone_copy_sampled_test.zig @@ -132,9 +132,9 @@ fn serve(m: cfgs.Model, times: [2]f64, asks: []const Ask, out: []Reply, kept: ?* if (kept) |k| k.* = .{ e.lone_kept[0][0] != null, e.lone_kept[1][0] != null }; } -/// hip_lanes.zig facts in small (as lone_copy_price_test.zig's): 16-row windows, timed forwards, copies priced. +/// hip_lanes.zig facts in small (as lone_copy_price_test.zig's): timed plain rounds and copies priced. fn hip(head: bool, forwards: []const cfgs.Cost) cfgs.Model { - return .{ .exact_width = 16, .mtp = head, .speculate = head, .speculate_early = false, .drafts = 4, .plain_guard = head, .copy_guard = true, .window_costs = forwards, .mtp_step_ms = if (head) 0.5 else 0, .hidden_rows = true, .batch_rows = 32, .max_streams = 4 }; + return .{ .exact_width = 16, .mtp = head, .speculate = head, .speculate_early = false, .drafts = 4, .plain_guard = true, .copy_guard = true, .window_costs = forwards, .mtp_step_ms = if (head) 0.5 else 0, .hidden_rows = true, .batch_rows = 32, .max_streams = 4 }; } /// `asks` served drafts-off and with copies unpriced (main's path) give `got`'s replies, token for token. diff --git a/zig/src/core/lanes/open.zig b/zig/src/core/lanes/open.zig index 684ab6b10ba..fa389f34136 100644 --- a/zig/src/core/lanes/open.zig +++ b/zig/src/core/lanes/open.zig @@ -145,8 +145,8 @@ fn openedCommitted(e: *Engine, s: *Stream, reach: Reach, hook: ?be.Committed) !v /// The first drafts' depth for `reach`. pub fn firstDepth(e: *Engine, s: *Stream, reach: Reach) !u32 { var who = win.who(s); - if (reach == .head and e.cfg.node_probabilities) return @intCast(try e.rule.headDepth(&who, null, win.probe(e))); - return @intCast(try e.rule.depth(who)); + const d = if (reach == .head and e.cfg.node_probabilities) try e.rule.headDepth(&who, null, win.probe(e)) else try e.rule.depth(who); + return @intCast(if (e.cfg.shared_mtp_cap > 0 and e.live.items.len > 0) @min(d, e.cfg.shared_mtp_cap) else d); // joins a shared round } /// Whether the backend can run a prompt pass a chunk at a time between rounds (`fillStream`). diff --git a/zig/src/core/lanes/shared_drafts.zig b/zig/src/core/lanes/shared_drafts.zig index fb265130e14..2582513acc8 100644 --- a/zig/src/core/lanes/shared_drafts.zig +++ b/zig/src/core/lanes/shared_drafts.zig @@ -33,7 +33,8 @@ pub fn budgets(e: *Engine, plans: []const win.Plan, heads: []const usize, out: [ if (!s.drafts) continue; const cap = if (e.backend.vtable.draft_capacity) |f| f(e.backend.ptr, s) else e.cfg.most_drafts; const shared = if (e.cfg.shared_drafts > 0) e.cfg.shared_drafts else e.cfg.most_drafts; // Model.shared_drafts - const most = @min(cap, shared, e.cfg.most_drafts, if (limits) |l| l.depths[i] else e.cfg.most_drafts, @as(u32, @intCast(@max(0, s.draftRoom() - 1)))); + const chain = if (e.cfg.shared_mtp_cap > 0) e.cfg.shared_mtp_cap else e.cfg.most_drafts; // Model.shared_mtp_cap + const most = @min(cap, shared, chain, e.cfg.most_drafts, if (limits) |l| l.depths[i] else e.cfg.most_drafts, @as(u32, @intCast(@max(0, s.draftRoom() - 1)))); if (most == 0) continue; head.* = true; const cached = s.draft_chances.items; diff --git a/zig/src/core/profile.zig b/zig/src/core/profile.zig index 19f086d5a34..f4887940e0a 100644 --- a/zig/src/core/profile.zig +++ b/zig/src/core/profile.zig @@ -9,6 +9,7 @@ pub const Switch = enum { TF_QWEN_KV_PAGES, TF_QWEN_KV_PAGES_ALL, TF_QWEN_KV_SHARE, + TF_QWEN_KV_HOST, TF_QWEN_REQUEST_STARTS, TF_GLM_REQUEST_STARTS, TF_KV_SHARE, @@ -147,6 +148,7 @@ pub const entries = [_]Entry{ .{ .id = .TF_QWEN_KV_PAGES, .families = qwen, .class = .identical, .effect = "KV pool page size; memory and workload tradeoffs", .evidence = "#1357" }, .{ .id = .TF_QWEN_KV_PAGES_ALL, .families = qwen, .class = .debug, .syntax = .one, .effect = "Put the engine's own stream on pages too", .evidence = "#1357" }, .{ .id = .TF_QWEN_KV_SHARE, .families = qwen, .class = .identical, .effect = "Keep prompt pages and bounded recurrent snapshots", .evidence = "#1357" }, + .{ .id = .TF_QWEN_KV_HOST, .families = qwen, .class = .identical, .syntax = .one, .effect = "Keep KV pages in mapped host memory; one stream, state runs on the device", .evidence = "#2637" }, .{ .id = .TF_KV_SHARE, .families = &.{ "gemma4", "gemma4_unified", "kolibri1", "spark2_5", "glm5_next", "dory" }, .class = .identical, .effect = "Keep prompt states over the core KV pool", .evidence = "#1657" }, .{ .id = .TF_FLASHNEXT_KV_PAGES, .families = flash, .class = .experimental, .effect = "KV pool page size; no profile qualifies it yet", .evidence = "#1660" }, .{ .id = .TF_FLASHNEXT_KV_PAGES_ALL, .families = flash, .class = .debug, .syntax = .one, .effect = "Put every stream on pool pages for checks", .evidence = "#1660" }, diff --git a/zig/src/core/prompt_cache.zig b/zig/src/core/prompt_cache.zig index 6e776cb02cd..fef04126030 100644 --- a/zig/src/core/prompt_cache.zig +++ b/zig/src/core/prompt_cache.zig @@ -178,7 +178,8 @@ pub const Store = struct { const e = s.entries.orderedRemove(i); policy.unlink(s, e); s.held -= e.bytes; - if (s.disk) |r| if (!e.expired) rows.write.evicted(r, e); // --spill-gib: stage an owned copy before the entry goes + // Clear and failed restores must not publish invalid state; backend expiry is still spillable. + if (s.disk) |r| if (!e.expired or e.removed_as == .expired) rows.write.evicted(r, e); s.free(e); } diff --git a/zig/src/core/prompt_cache_lifetime_test.zig b/zig/src/core/prompt_cache_lifetime_test.zig index 756c00dba80..cc110ddeff4 100644 --- a/zig/src/core/prompt_cache_lifetime_test.zig +++ b/zig/src/core/prompt_cache_lifetime_test.zig @@ -144,3 +144,18 @@ test "GLM expiry: actual store borrow query lasts until the last release and exc s.release(second); try std.testing.expect(!s.borrowed(saved)); } + +test "an expired state reaches the eviction-only disk store before RAM releases it" { + const fixture = @import("rows_async_fixture.zig"); + const x = try fixture.Fixture.open("expired-spill", .evicted, true, 1 << 30); + defer x.close(); + var arena: std.heap.ArenaAllocator = .init(a); + defer arena.deinit(); + var p = fixture.prompt(71); + try x.keep(&p, 1000); + const entry = (try x.s.lookup(arena.allocator(), &p, 0, &.{}, x.f.starts, x.f.spans)).entry.?; + x.s.expired(entry.saved); + x.s.release(entry); + try std.testing.expectEqual(@as(usize, 0), x.s.entries.items.len); + try std.testing.expectEqual(@as(usize, 1), x.r.states.items.len); +} diff --git a/zig/src/core/prompt_cache_miss.zig b/zig/src/core/prompt_cache_miss.zig index 17ebb511734..fbaa58066e4 100644 --- a/zig/src/core/prompt_cache_miss.zig +++ b/zig/src/core/prompt_cache_miss.zig @@ -88,11 +88,16 @@ pub fn derive(s: *const pc.Store, prompt: []const u32, starts: []const u32, span var request: u32 = 0; for (s.by_position.items) |e| { // longest first, as find walks them if (e.expired) { - if (cause == null) { - cause = .expired; - n = @min(e.tokens.len, @as(u32, @intCast(prompt.len))); + const common = @min(e.tokens.len, prompt.len); + if (common == 0) continue; + if (std.mem.eql(u32, e.tokens[0..common], prompt[0..common])) { + if (cause == null) { + cause = .expired; + n = @intCast(common); + } + continue; } - continue; + // A divergent expired prefix is a changed prompt or reply, not an exact match that expired. } if (e.at >= prompt.len and std.mem.startsWith(u32, e.tokens, prompt[0..@min(prompt.len, e.tokens.len)])) { // the request ends inside this state, before its resume point diff --git a/zig/src/core/prompt_cache_miss_test.zig b/zig/src/core/prompt_cache_miss_test.zig index b2a5c002f26..620c9696c5b 100644 --- a/zig/src/core/prompt_cache_miss_test.zig +++ b/zig/src/core/prompt_cache_miss_test.zig @@ -279,9 +279,15 @@ test "miss reasons: an expired kept state says expired" { f.at = 8; _ = store.keep(prompt, 8, null, &.{}, &.{}); const saved = store.entries.items[0].saved; + const held = try store.lookup(arena.allocator(), prompt, 0, &.{}, &.{}, &.{}); + defer if (held.entry) |e| store.release(e); // keep the expired entry alive through both later lookups store.expired(saved); // hidden from lookups at once, still in by_position for derive const l = try store.lookup(arena.allocator(), prompt, 0, &.{}, &.{}, &.{}); try std.testing.expectEqual(miss.Reason.expired, l.miss.?.reason); + const foreign = tokens(12, 189); + defer gpa.free(foreign); + const unrelated = try store.lookup(arena.allocator(), foreign, 0, &.{}, &.{}, &.{}); + try std.testing.expectEqual(miss.Reason.cold, unrelated.miss.?.reason); } fn plan(a: std.mem.Allocator, s: *pc.Store, prompt: []const u32) !pc.Plan { diff --git a/zig/src/core/rows_ask.zig b/zig/src/core/rows_ask.zig index 4e42bb26d5c..77873afaac8 100644 --- a/zig/src/core/rows_ask.zig +++ b/zig/src/core/rows_ask.zig @@ -1,13 +1,17 @@ -//! The Mac app's questions about a conversation's kept states (/v1/imprint), answered on the engine thread. +//! Questions about kept states (/v1/imprint, /v1/prompt_cache/flush), answered on the engine thread. const std = @import("std"); const pc = @import("prompt_cache.zig"); const rows = pc.rows; -pub const Op = enum { where, load, forget }; +/// flush: every kept state dropped, in RAM and on disk, once no request is in flight (a waiting one holds admissions). +pub const Op = enum { where, load, forget, flush }; /// Which of a request's keys the host's cache lookups pass: its chunk starts, its decoded spans. pub const Keys = struct { starts: bool = true, spans: bool = true }; +/// A flush's claim: the engine thread takes a queued one, or its caller withdraws it first and it never runs. +pub const Claim = enum(u8) { queued, taken, withdrawn }; + /// One question: a rendered conversation (its tokens, chunk starts and decoded spans), and the answer once `done`. pub const Ask = struct { op: Op, @@ -17,12 +21,16 @@ pub const Ask = struct { out: rows.read.Resume = .{}, loaded: u32 = 0, // load: the tokens a disk read brought into RAM (0: none was needed, or it did not pay) load_seconds: f64 = 0, - freed: u64 = 0, // forget: bytes removed from disk + freed: u64 = 0, // forget, flush: bytes removed from disk + dropped: u32 = 0, // flush: states dropped from RAM + ram_freed: u64 = 0, // flush: the bytes those states held in the cache's budget disk: bool = false, // the engine keeps conversation states on disk + claim: std.atomic.Value(Claim) = .init(.queued), done: std.atomic.Value(bool) = .init(false), /// The engine thread's answer from its kept states (`store` null: it keeps none), keyed as its lookups are. pub fn answer(a: *Ask, store: ?*pc.Store, keys: Keys) void { + if (a.op == .flush and a.claim.cmpxchgStrong(.queued, .taken, .acq_rel, .acquire) != null) return; // withdrawn defer a.done.store(true, .release); const s = store orelse return; a.disk = s.disk != null; @@ -42,10 +50,16 @@ pub const Ask = struct { .forget => if (s.disk) |r| { a.freed = r.forgetAll(); }, + .flush => return flush(a, s), } a.out = rows.read.resumable(s, a.prompt, starts, spans); } + /// A flush's caller stops waiting: true when the engine had not taken it, so nothing is dropped and nothing holds. + pub fn withdraw(a: *Ask) bool { + return a.claim.cmpxchgStrong(.queued, .withdrawn, .acq_rel, .acquire) == null; + } + /// The answer within `ms` milliseconds (false: none came). pub fn wait(a: *const Ask, io: std.Io, ms: u32) bool { var waited: u32 = 0; @@ -57,9 +71,25 @@ pub const Ask = struct { } }; +/// Every kept state dropped and the store's plans reset, as on a fresh store; then its states on disk deleted. +fn flush(a: *Ask, s: *pc.Store) void { + const n = s.entries.items.len; + const bytes = s.held; + for (s.entries.items) |e| e.expired = true; // expired first: nothing is staged for disk on its way out + s.collectExpired(); // a borrowed one (none while no request is in flight) goes when its lookup ends + a.dropped = @intCast(n - s.entries.items.len); + a.ram_freed = bytes - s.held; + s.shared_keys.clearRetainingCapacity(); + s.repeat_log.keys.clearRetainingCapacity(); + s.active_rewind_at = 0; + s.active_rewind_key = 0; + if (s.disk) |r| a.freed = r.forgetAll(); // the store's own folder and names: DELETE /v1/imprint's call +} + /// A host's side of disk states: the asks waiting for its engine thread, and when the engine last went quiet. pub const Disk = struct { asks: std.ArrayList(*Ask) = .empty, + flushes: std.ArrayList(*Ask) = .empty, // while one waits unwithdrawn, the host admits nothing new seen: u64 = 0, // the host's admissions when the writer last looked: a new one restarts the quiet since: ?i96 = null, @@ -68,10 +98,28 @@ pub const Disk = struct { /// Queue `a` (the host's lock held). pub fn push(d: *Disk, gpa: std.mem.Allocator, a: *Ask) bool { - d.asks.append(gpa, a) catch return false; + (if (a.op == .flush) &d.flushes else &d.asks).append(gpa, a) catch return false; return true; } + /// Whether a flush waits for the requests in flight: admissions hold until it is answered (the host's lock held). + pub fn holding(d: *const Disk) bool { + for (d.flushes.items) |a| if (a.claim.load(.acquire) == .queued) return true; + return false; + } + + /// Whether any ask waits, a flush or another (the host's lock held). + pub fn waiting(d: *const Disk) bool { + return d.asks.items.len > 0 or d.flushes.items.len > 0; + } + + /// The waiting flushes, taken whole once no request is in flight (the host's lock held); the caller frees the list. + pub fn takeFlushes(d: *Disk) std.ArrayList(*Ask) { + const list = d.flushes; + d.flushes = .empty; + return list; + } + /// The queued asks, taken (the host's lock held); the caller frees the list. pub fn take(d: *Disk, gpa: std.mem.Allocator) []*Ask { if (d.asks.items.len == 0) return &.{}; @@ -94,5 +142,7 @@ pub const Disk = struct { pub fn close(d: *Disk, gpa: std.mem.Allocator) void { for (d.asks.items) |a| a.answer(null, .{}); d.asks.deinit(gpa); + for (d.flushes.items) |a| a.answer(null, .{}); + d.flushes.deinit(gpa); } }; diff --git a/zig/src/cuda/exl3_experts.zig b/zig/src/cuda/exl3_experts.zig index b907b3a3044..861bb7151e9 100644 --- a/zig/src/cuda/exl3_experts.zig +++ b/zig/src/cuda/exl3_experts.zig @@ -35,6 +35,8 @@ pub const Layer = struct { width: usize, // I (expert width) codebook: Codebook, uniform_k2: u32 = 0, // nonzero only when the loader verified this half-bit width for every projection + uniform_k2_gu: u32 = 0, // nonzero when the loader verified this half-bit width for every gate and up matrix + uniform_k2_d: u32 = 0, // nonzero when the loader verified this half-bit width for every down matrix shared_input: bool = false, // the loader verified identical gate/up input scales across every expert gu_stride: usize = 0, // gate/up trellis row stride in tiles (0: contiguous per projection) limit: f32 = 0, // the SwiGLU clamp (0: none) diff --git a/zig/src/cuda/exl3_prompt.zig b/zig/src/cuda/exl3_prompt.zig index 4b1b7908764..8720cda6c78 100644 --- a/zig/src/cuda/exl3_prompt.zig +++ b/zig/src/cuda/exl3_prompt.zig @@ -9,8 +9,21 @@ const Stream = @import("stream.zig").Stream; pub const tile = 64; pub const Scratch = struct { xg: u64, xu: u64, xd: u64, rows: usize, slots: usize }; +/// A group's verified half-bit width: its own field, else uniform_k2; 0 when unverified or the two disagree. +fn verified(group: u32, uniform: u32) u32 { + if (group == 0) return uniform; + return if (uniform == 0 or uniform == group) group else 0; +} +/// The verified widths of gate/up and of down (0: unverified); the prompt kernels take 6 (3 bits) and 8 (4 bits). +pub fn widths(l: ex.Layer) struct { gu: u32, d: u32 } { + return .{ .gu = verified(l.uniform_k2_gu, l.uniform_k2), .d = verified(l.uniform_k2_d, l.uniform_k2) }; +} +fn built(k2: u32) bool { + return k2 == 6 or k2 == 8; +} pub fn eligible(l: ex.Layer) bool { - return l.codebook == .mcg and l.uniform_k2 == 8 and l.gu_stride == 0 and l.dims > 0 and l.width > 0 and l.dims % 256 == 0 and l.width % 128 == 0 and (l.act_mode == 0 or l.act_mode == 1); + const w = widths(l); + return l.codebook == .mcg and built(w.gu) and built(w.d) and l.gu_stride == 0 and l.dims > 0 and l.width > 0 and l.dims % 256 == 0 and l.width % 128 == 0 and (l.act_mode == 0 or l.act_mode == 1); } fn mul(a: usize, b: usize) !usize { return std.math.mul(usize, a, b) catch error.Exl3Shape; @@ -50,10 +63,18 @@ fn i(n: usize) i32 { } pub const Kernels = struct { rotate: Function, - gateup: Function, - down: Function, + gateup: Function, // 4-bit gate and up + down: Function, // 4-bit down + gateup_k6: Function, // 3-bit gate and up, gateup's arguments + down_k6: Function, // 3-bit down, down's arguments pub fn resolve(mod: Module) !Kernels { - return .{ .rotate = try mod.function("tf_exl3_prompt_rotate"), .gateup = try mod.function("tf_exl3_prompt_gu"), .down = try mod.function("tf_exl3_prompt_down") }; + return .{ + .rotate = try mod.function("tf_exl3_prompt_rotate"), + .gateup = try mod.function("tf_exl3_prompt_gu"), + .down = try mod.function("tf_exl3_prompt_down"), + .gateup_k6 = try mod.function("tf_exl3_prompt_gu_k6"), + .down_k6 = try mod.function("tf_exl3_prompt_down_k6"), + }; } /// `skip` is the shared expert's id, equal to the routed count; its output slot stays owned by the caller. pub fn run(k: Kernels, e: *const ex.Experts, router: grouped.Router, s: Stream, l: ex.Layer, x: u64, stride: usize, picks: u64, rows: usize, sc: Scratch, p: grouped.Plan, y: u64, skip: ?usize) !void { @@ -63,6 +84,7 @@ pub const Kernels = struct { const count = l.experts + @intFromBool(skip != null); const skip_id: i32 = if (skip) |id| i(id) else -1; const pairs = rows * sc.slots; + const w = widths(l); try router.route(s, picks, pairs, count, tile, p); if (l.shared_input) { try go(k.rotate, s, .{ rows, l.dims / 128, 1 }, 32, .{ x, i(stride), l.suh_g, sc.xg, i(l.dims) }); @@ -72,7 +94,28 @@ pub const Kernels = struct { try launch.launch(e.rot_in, .{ .grid = .{ .x = @intCast(pairs), .y = @intCast(l.dims / 128), .z = 2 }, .block = .{ .x = 32 } }, s, &args); } const items = grouped.maxItems(pairs, count, tile); - try go(k.gateup, s, .{ l.width / 128, items, 1 }, 256, .{ sc.xg, sc.xu, l.gate, l.up, p.items, p.counts, p.members, l.svh_g, l.svh_u, l.suh_d, sc.xd, i(l.dims), i(l.width), i(if (l.shared_input) sc.slots else 1), l.limit, l.act_mode, skip_id }); - try go(k.down, s, .{ l.dims / 256, items, 1 }, 256, .{ sc.xd, l.down, p.items, p.counts, p.members, l.svh_d, y, i(l.width), i(l.dims), skip_id }); + try go(if (w.gu == 6) k.gateup_k6 else k.gateup, s, .{ l.width / 128, items, 1 }, 256, .{ sc.xg, sc.xu, l.gate, l.up, p.items, p.counts, p.members, l.svh_g, l.svh_u, l.suh_d, sc.xd, i(l.dims), i(l.width), i(if (l.shared_input) sc.slots else 1), l.limit, l.act_mode, skip_id }); + try go(if (w.d == 6) k.down_k6 else k.down, s, .{ l.dims / 256, items, 1 }, 256, .{ sc.xd, l.down, p.items, p.counts, p.members, l.svh_d, y, i(l.width), i(l.dims), skip_id }); } }; + +test "per-projection widths: the group fields, else uniform_k2, and a disagreement unverified" { + var l: ex.Layer = .{ .gate = 0, .up = 0, .down = 0, .gate_k2 = 0, .up_k2 = 0, .down_k2 = 0, .suh_g = 0, .suh_u = 0, .svh_g = 0, .svh_u = 0, .suh_d = 0, .svh_d = 0, .experts = 9, .dims = 512, .width = 256, .codebook = .mcg, .uniform_k2 = 8 }; + try std.testing.expectEqual(@as(u32, 8), widths(l).gu); + try std.testing.expectEqual(@as(u32, 8), widths(l).d); + l.uniform_k2 = 0; + l.uniform_k2_gu = 6; + l.uniform_k2_d = 8; + try std.testing.expectEqual(@as(u32, 6), widths(l).gu); + try std.testing.expectEqual(@as(u32, 8), widths(l).d); + try std.testing.expect(eligible(l)); + l.uniform_k2_d = 0; + try std.testing.expectEqual(@as(u32, 0), widths(l).d); + try std.testing.expect(!eligible(l)); + l.uniform_k2 = 8; + l.uniform_k2_d = 0; + try std.testing.expectEqual(@as(u32, 0), widths(l).gu); // gate/up 6 against every projection 8: unverified + try std.testing.expect(!eligible(l)); + l.uniform_k2_gu = 8; + try std.testing.expect(eligible(l)); +} diff --git a/zig/src/cuda/kernels.zig b/zig/src/cuda/kernels.zig index 6eb29fccc9d..68f917f8362 100644 --- a/zig/src/cuda/kernels.zig +++ b/zig/src/cuda/kernels.zig @@ -105,11 +105,15 @@ pub const hy4_attention_sink: []const u8 = if (available) &Blob("fatbin_hy4_atte pub const hy4_mla_project: []const u8 = if (available) &Blob("fatbin_hy4_mla_project").bytes else &.{}; pub const hy4_mla_attention: []const u8 = if (available) &Blob("fatbin_hy4_mla_attention").bytes else &.{}; pub const hy4_ihc: []const u8 = if (available) &Blob("fatbin_hy4_ihc").bytes else &.{}; +pub const hy4_engram: []const u8 = if (available) &Blob("fatbin_hy4_engram").bytes else &.{}; pub const minimax_m3: []const u8 = if (available) &Blob("fatbin_minimax_m3").bytes else &.{}; pub const minimax_m3_attn: []const u8 = if (available) &Blob("fatbin_minimax_m3_attn").bytes else &.{}; pub const idol: []const u8 = if (available) &Blob("fatbin_idol").bytes else &.{}; +pub const idol_decoder: []const u8 = if (available) &Blob("fatbin_idol_decoder").bytes else &.{}; pub const inkling2_attn: []const u8 = if (available) &Blob("fatbin_inkling2_attn").bytes else &.{}; 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 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/families/deepseek_v41/aot_needs.zig b/zig/src/families/deepseek_v41/aot_needs.zig index 798cbe6e8a8..33e2ed780c0 100644 --- a/zig/src/families/deepseek_v41/aot_needs.zig +++ b/zig/src/families/deepseek_v41/aot_needs.zig @@ -580,7 +580,7 @@ pub fn main(gpa: std.mem.Allocator, io: std.Io, sigs_path: []const u8, out_path: try log.print("aot-needs: limit {d}, {d} slot(s), rows cap {d}, prefill rows {d}, index budget {d} MiB, R1 {}, drafts {}, slot drafts {} (group {d}), world {d}, pool {s}\n", .{ sv.o.limit, sv.slots, sv.cap, sv.o.prefill_rows, sv.o.index_budget >> 20, sv.o.r1, sv.drafts, sv.slot_drafts, sv.group, sv.o.world, if (sv.o.pool) |p| (if (p.split) "split" else "on") else "none (contiguous slot)" }); var n: Needs = .{ .gpa = gpa, .sigs = &parsed.value.kernels }; defer n.deinit(); - try enumerate(gpa, &n, &cfg, &w, sv, log); + for (try @import("float_linear.zig").tables(a, &cfg, &w, &@import("serve_knobs.zig").env, log)) |t| try enumerate(gpa, &n, &cfg, &t, sv, log); var out: std.Io.Writer.Allocating = .init(gpa); defer out.deinit(); const ow = &out.writer; diff --git a/zig/src/families/deepseek_v41/block.zig b/zig/src/families/deepseek_v41/block.zig index f247daf1906..852ab13a4d3 100644 --- a/zig/src/families/deepseek_v41/block.zig +++ b/zig/src/families/deepseek_v41/block.zig @@ -7,6 +7,7 @@ const config = @import("config.zig"); const knob_types = @import("knob_types.zig"); const moe = @import("block_moe.zig"); const block_prefetch = @import("block_prefetch.zig"); +const float_linear = @import("float_linear.zig"); const partition = @import("partition.zig"); const block_attn = @import("block_attn.zig"); const block_index = @import("block_index.zig"); @@ -26,6 +27,11 @@ pub const Widths = struct { pub fn k2(w: *const Widths, name: []const u8) !u32 { return w.dense.get(name) orelse error.NoWidth; } + + /// A projection the pack keeps as a float matrix (`.plain`, no trellis): the width table records 0. + pub fn plain(w: *const Widths, name: []const u8) bool { + return (w.dense.get(name) orelse return false) == 0; + } }; /// Run-time sizes fixed at load (scratch and pools), and the L2 prefetch settings. @@ -312,6 +318,9 @@ pub const Emitter = struct { /// `r1`'s RMS_FOLD: rot_in norms its rows itself (rms(x, w, eps), rmsnorm's order) before the rotation. pub const Norm = struct { w: Arg, eps: f64 }; + /// TF_DSV41_FLOAT_LINEAR: one float projection, on `_plain` (float_linear.zig). + pub const plain = float_linear.plain; + /// x3seg rot_in, then dense3 a width: the group's projections in one rot_in launch, one linear launch a K2. pub fn fused(e: *Emitter, tag: []const u8, ps: []const Proj) !void { return e.fusedNorm(tag, ps, null); diff --git a/zig/src/families/deepseek_v41/block_attn.zig b/zig/src/families/deepseek_v41/block_attn.zig index 308d3b34b9e..8fd0db4bc9b 100644 --- a/zig/src/families/deepseek_v41/block_attn.zig +++ b/zig/src/families/deepseek_v41/block_attn.zig @@ -213,12 +213,22 @@ pub fn attention(e: *Emitter, L: u32) !void { // a KV source's compressor projection outlives its layer: keep() carries the accepted row (ratio 2) const comp = if (ratio == 2) try e.buf("w.L{d}.comp", .{L}, .bf16, &.{ n, cw }) else try e.buf("L.comp", .{}, .bf16, &.{ n, cw }); var ps: [4]Proj = undefined; - for (xg.ws, 0..) |w, i| ps[i] = .{ .w = w, .x = x, .k = @intCast(D), .n = @intCast(xg.ns[i]), .y = switch (i) { - 0 => qa, - 1 => kv, - else => comp, - }, .col = if (i == 3) @intCast(hd) else 0 }; - try e.fused("x", ps[0..xg.ws.len]); + var fused_n: usize = 0; + for (xg.ws, 0..) |w, i| { + const p: Proj = .{ .w = w, .x = x, .k = @intCast(D), .n = @intCast(xg.ns[i]), .y = switch (i) { + 0 => qa, + 1 => kv, + else => comp, + }, .col = if (i == 3) @intCast(hd) else 0 }; + // a float projection leaves the fused group for its own launch, into the same columns of the same buffer + if (e.w.plain(w)) { + try e.plain(p); + continue; + } + ps[fused_n] = p; + fused_n += 1; + } + if (fused_n > 0) try e.fused("x", ps[0..fused_n]); const qn = try e.buf("L.qn", .{}, .bf16, &.{ n, e.cfg.q_lora }); const kvn = try e.buf("L.kvn", .{}, .bf16, &.{ n, hd }); // `r1` (RMS_FOLD): no launch here; q_norm runs in its consumers' rot_in, kv_norm beside the SWA store @@ -255,7 +265,11 @@ pub fn attention(e: *Emitter, L: u32) !void { }); try e.kvStore(lat, L, ratio); const kp = try e.buf("L.ix_k", .{}, .bf16, &.{ n, ID }); - try e.upstream(try e.fmt("L{d}.attn.ix_wk", .{L}), lat, hd, ID, kp); + const ix_wk = try e.fmt("L{d}.attn.ix_wk", .{L}); + if (e.w.plain(ix_wk)) + try e.plain(.{ .w = ix_wk, .x = lat, .y = kp, .k = @intCast(hd), .n = @intCast(ID) }) + else + try e.upstream(ix_wk, lat, hd, ID, kp); const kpg = try e.paging(ratio, false); try e.triton("_index_k", .{ n, 1, 1 }, &.{ .{ .name = "KP", .arg = kp }, .{ .name = "k_stride", .arg = .{ .i = ID } }, diff --git a/zig/src/families/deepseek_v41/block_index.zig b/zig/src/families/deepseek_v41/block_index.zig index 3e5019c2827..6e622bd0537 100644 --- a/zig/src/families/deepseek_v41/block_index.zig +++ b/zig/src/families/deepseek_v41/block_index.zig @@ -45,7 +45,16 @@ pub fn index(e: *Emitter, L: u32, qn: Arg, iw: Arg, qnorm: ?Norm) !void { const IH: i64 = e.cfg.index_heads; const ID: i64 = e.cfg.index_dim; const qi = try e.buf("L.qi", .{}, .bf16, &.{ n, IH * ID }); - try e.fusedNorm("qi", &.{.{ .w = try e.fmt("L{d}.attn.ix_wq_b", .{L}), .x = qn, .y = qi, .k = e.cfg.q_lora, .n = @intCast(IH * ID) }}, qnorm); + const wq = try e.fmt("L{d}.attn.ix_wq_b", .{L}); + if (e.w.plain(wq)) { + // RMS_FOLD hands this path unnormed rows and no fused norm to fold into: the norm takes its own launch + var x = qn; + if (qnorm) |nm| { + x = try e.buf("L.qn", .{}, .bf16, &.{ n, e.cfg.q_lora }); + try e.rms(qn, nm.w, x, e.cfg.q_lora); + } + try e.plain(.{ .w = wq, .x = x, .y = qi, .k = e.cfg.q_lora, .n = @intCast(IH * ID) }); + } else try e.fusedNorm("qi", &.{.{ .w = wq, .x = qn, .y = qi, .k = e.cfg.q_lora, .n = @intCast(IH * ID) }}, qnorm); try e.rope(qi, IH, ID, ID - 64); const reindex = e.cfg.mode(L) == .reindex; const src = if (reindex) e.cfg.kvSource(L).? else L; diff --git a/zig/src/families/deepseek_v41/block_prefetch.zig b/zig/src/families/deepseek_v41/block_prefetch.zig index 3afd452f4a3..4f8b3aacca9 100644 --- a/zig/src/families/deepseek_v41/block_prefetch.zig +++ b/zig/src/families/deepseek_v41/block_prefetch.zig @@ -6,13 +6,15 @@ const Emitter = block.Emitter; const L2Src = block.Emitter.L2Src; const L2Site = block.Emitter.L2Site; -/// l2pf._lin_tensors: every projection's suh and svh, then their trellis words. +/// l2pf._lin_tensors: every projection's suh and svh, then their trellis words; a float projection's matrix whole. pub fn linSrcs(e: *Emitter, out: *std.ArrayList(L2Src), ws: []const []const u8, ks: []const i64, ns: []const i64) !void { - for (ws, ks, ns) |w, k, n| try out.appendSlice(e.a, &.{ + for (ws, ks, ns) |w, k, n| if (e.w.plain(w)) { + try out.append(e.a, .{ .kind = .weight, .name = try e.fmt("{s}.plain", .{w}), .bytes = @intCast(4 * k * n) }); + } else try out.appendSlice(e.a, &.{ .{ .kind = .weight, .name = try e.fmt("{s}.suh", .{w}), .bytes = @intCast(2 * k) }, .{ .kind = .weight, .name = try e.fmt("{s}.svh", .{w}), .bytes = @intCast(2 * n) }, }); - for (ws, ks, ns) |w, k, n| try out.append(e.a, .{ .kind = .words, .name = w, .bytes = try e.trellisBytes(w, k, n) }); + for (ws, ks, ns) |w, k, n| if (!e.w.plain(w)) try out.append(e.a, .{ .kind = .words, .name = w, .bytes = try e.trellisBytes(w, k, n) }); } /// Site `site`'s sources: "o" and "f" of block `L`, "x" of the block before `L` (its table is "s.L.pf.x"). diff --git a/zig/src/families/deepseek_v41/block_prefill.zig b/zig/src/families/deepseek_v41/block_prefill.zig index 888271fd72e..c0cfc3b53f9 100644 --- a/zig/src/families/deepseek_v41/block_prefill.zig +++ b/zig/src/families/deepseek_v41/block_prefill.zig @@ -121,6 +121,8 @@ pub const Seg = struct { pub fn matmul(s: *Seg, w: []const u8, form: Form, x: Arg, k: i64, n: i64, y: Out) !void { const e = s.e; const m = e.n; + // a float projection: one `_plain` launch over the segment's rows, into the same columns of `y` + if (e.w.plain(w)) return e.plain(.{ .w = w, .x = x, .k = @intCast(k), .n = @intCast(n), .y = try e.view(y.role, y.dt, &.{ m, n }, &.{ y.stride, 1 }, y.offset) }); const k2: i64 = try e.w.k2(w); const tw = 4 * k2; const nb = @divExact(n, 128); diff --git a/zig/src/families/deepseek_v41/block_test.zig b/zig/src/families/deepseek_v41/block_test.zig index 93a35896f5d..041802aea2a 100644 --- a/zig/src/families/deepseek_v41/block_test.zig +++ b/zig/src/families/deepseek_v41/block_test.zig @@ -107,3 +107,121 @@ test "branch row threshold falls back to the main stream above its limit" { const program = try block.emit(a, &cfg, &w, .{ .branches = true, .branch_rows = 1 }, &.{0}, 8, 0, false); for (program) |call| try std.testing.expect(!call.side and !call.fork and !call.join); } + +/// Every `_plain` launch of a float projection (`.plain`), by its weight's name. +fn plainLaunches(a: std.mem.Allocator, cs: []const calls.Call) !std.StringArrayHashMapUnmanaged(calls.Call) { + var out: std.StringArrayHashMapUnmanaged(calls.Call) = .empty; + for (cs) |call| { + if (!std.mem.eql(u8, call.name, "_plain")) continue; + const name = call.args[2].arg.t.role.weight; + if (!std.mem.endsWith(u8, name, ".plain")) continue; + try out.put(a, name, call); + // N is the row stride `_plain` stores with, and the grid's second dimension gives the outputs + try t.expectEqual(call.args[4].arg.t.stride[0], call.args[6].arg.i); + try t.expectEqual(@as(i64, 256), call.args[7].arg.i); + try t.expect(!call.args[8].arg.b and call.args[9].arg.b); + try t.expectEqual(call.args[4].arg.t.shape[1], call.grid[1]); + } + return out; +} + +/// Fails when an argument reads an EXL3 part of an L2 float projection: its trellis, scales or a repacked form. +fn expectNoExl3(arg: calls.Arg) anyerror!void { + const tensor = switch (arg) { + .t, .opaque_table => |x| x, + .list => |items| { + for (items) |item| try expectNoExl3(item); + return; + }, + else => return, + }; + const name = switch (tensor.role) { + .weight => |n| n, + .buf => |n| if (std.mem.startsWith(u8, n, "s.")) n[2..] else n, + .empty => return, + }; + var nb: [64]u8 = undefined; + for (@import("float_linear.zig").projections) |proj| + if (std.mem.startsWith(u8, name, try std.fmt.bufPrint(&nb, "L2.attn.{s}.", .{proj}))) + try t.expect(std.mem.endsWith(u8, name, ".plain")); +} + +test "a float projection runs on `_plain` into its own columns, in a decode window and in a prompt segment" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var w = try widths(a); + const c: Config = .{}; + const hd: i64 = c.head_dim; + // layer 2 is a ratio-2 KV and index source, so its block holds all five projections names.plainOf covers + for (@import("float_linear.zig").projections) |proj| try w.dense.put(a, try std.fmt.allocPrint(a, "L2.attn.{s}", .{proj}), 0); + const window_calls = try block.emit(a, &c, &w, .{}, &.{2}, 8, 0, false); + const window = try plainLaunches(a, window_calls); + try t.expectEqual(@as(usize, 5), window.count()); + const gate = window.get("L2.attn.comp_wgate.plain").?; + // the compressor's two projections share one row: the gate's half starts at its own column, with the row's stride + try t.expectEqual(2 * hd, gate.args[6].arg.i); + try t.expectEqual(2 * hd, gate.args[4].arg.t.offset); + try t.expectEqual(hd, gate.grid[1]); + try t.expectEqual(@as(i64, 0), window.get("L2.attn.comp_wkv.plain").?.args[4].arg.t.offset); + try t.expectEqual(@as(i64, c.hidden), window.get("L2.attn.wq_a.plain").?.args[5].arg.i); + try w.gm.put(a, 2, .{ (1 << 4) | (1 << 6) | (1 << 8), (1 << 4) | (1 << 10) }); + const segment_calls = try @import("block_prefill.zig").emitPrefill(a, &c, &w, .{}, &.{2}, 64, 0, false); + const segment = try plainLaunches(a, segment_calls); + for ([_][]const u8{ "L2.attn.wq_a.plain", "L2.attn.comp_wkv.plain", "L2.attn.comp_wgate.plain", "L2.attn.ix_wq_b.plain" }) |name| + try t.expect(segment.get(name) != null); + for ([_][]const calls.Call{ window_calls, segment_calls }) |program| for (program) |call| for (call.args) |named| try expectNoExl3(named.arg); + // the widths the fixture holds: every projection keeps its EXL3 group and no float launch is emitted + const kept = try plainLaunches(a, try block.emit(a, &c, &try widths(a), .{}, &.{2}, 8, 0, false)); + try t.expectEqual(@as(usize, 0), kept.count()); +} + +test "a float projection's L2 prefetch source is its fp32 matrix whole, never its EXL3 parts" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var w = try widths(a); + const c: Config = .{}; + for (@import("float_linear.zig").projections) |proj| try w.dense.put(a, try std.fmt.allocPrint(a, "L2.attn.{s}", .{proj}), 0); + var e: block.Emitter = .{ .a = a, .cfg = &c, .w = &w, .o = .{}, .n = 1, .start = 0 }; + const srcs = try e.l2pfSources(2, .x); + // the x and q groups' float members; ix_wk has no prefetch site + const want = [_]struct { []const u8, u64 }{ + .{ "L2.attn.wq_a", @as(u64, 4) * c.hidden * c.q_lora }, + .{ "L2.attn.comp_wkv", @as(u64, 4) * c.hidden * c.head_dim }, + .{ "L2.attn.comp_wgate", @as(u64, 4) * c.hidden * c.head_dim }, + .{ "L2.attn.ix_wq_b", @as(u64, 4) * c.q_lora * c.index_heads * c.index_dim }, + }; + for (want) |x| { + var found = false; + for (srcs) |s| if (std.mem.startsWith(u8, s.name, x[0])) { + try t.expect(s.kind == .weight and std.mem.endsWith(u8, s.name, ".plain") and !found); + try t.expectEqual(x[1], s.bytes); + found = true; + }; + try t.expect(found); + } +} + +test "with `r1` a float ix_wq_b reads the q rows its own `_rms` launch normed" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var w = try widths(a); + const c: Config = .{}; + for (@import("float_linear.zig").projections) |proj| try w.dense.put(a, try std.fmt.allocPrint(a, "L2.attn.{s}", .{proj}), 0); + // RMS_FOLD hands the indexer unnormed rows, and no rot_in is in a float projection's path to norm them + var normed: ?[]const u8 = null; + var plain_x: ?[]const u8 = null; + for (try block.emit(a, &c, &w, .{ .r1 = true }, &.{2}, 8, 0, false)) |call| { + if (std.mem.eql(u8, call.name, "_rms") and std.mem.eql(u8, call.args[2].arg.t.role.weight, "L2.attn.q_norm")) { + try t.expectEqualStrings("L.qa", call.args[0].arg.t.role.buf); + normed = call.args[3].arg.t.role.buf; + } + if (std.mem.eql(u8, call.name, "_plain") and std.mem.eql(u8, call.args[2].arg.t.role.weight, "L2.attn.ix_wq_b.plain")) { + try t.expect(normed != null); + plain_x = call.args[0].arg.t.role.buf; + } + } + try t.expectEqualStrings(normed orelse return error.TestUnexpectedResult, plain_x orelse return error.TestUnexpectedResult); +} diff --git a/zig/src/families/deepseek_v41/cuda_model.zig b/zig/src/families/deepseek_v41/cuda_model.zig index e4304af86f7..591163152e8 100644 --- a/zig/src/families/deepseek_v41/cuda_model.zig +++ b/zig/src/families/deepseek_v41/cuda_model.zig @@ -236,7 +236,8 @@ pub const Model = struct { }; var ds: [8]u32 = undefined; const blocks = if (o.drafts) try std.mem.concat(a, u32, &.{ backbone, dspark_emit.blocks(&m.cfg, &ds) }) else backbone; - m.pl = try plan.build(gpa, &m.cfg, &m.pack, .{ .rank = m.tcfg.rank, .world = world, .blocks = blocks, .top = true, .dspark = o.drafts }); + const float_linear = try @import("serve_knobs.zig").floatLinear(&@import("serve_knobs.zig").env); + m.pl = try plan.build(gpa, &m.cfg, &m.pack, .{ .rank = m.tcfg.rank, .world = world, .blocks = blocks, .top = true, .dspark = o.drafts, .float_linear = float_linear }); try load.admitPlan(io, &m.cfg, &m.pack, &m.pl); m.weights = .{ .gpa = gpa, .digest = false }; // no weights check reads the digests here (load.zig) // TF_DSV41_PREPARED (prepared.zig): each layer's host images read back instead of rebuilt from the pack diff --git a/zig/src/families/deepseek_v41/env_validate_test.zig b/zig/src/families/deepseek_v41/env_validate_test.zig index 2234e65e32e..ee54963ec74 100644 --- a/zig/src/families/deepseek_v41/env_validate_test.zig +++ b/zig/src/families/deepseek_v41/env_validate_test.zig @@ -35,13 +35,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 "DeepSeek strict env: the shared table holds all 81 settings: 48 switches, 14 integers, 16 reals and 3 structured" { +test "DeepSeek strict env: the shared table holds all 82 settings: 49 switches, 14 integers, 16 reals and 3 structured" { var counts: [4]usize = @splat(0); for (e.rules) |r| if (r.scope == .dsv41) { try t.expect(std.mem.startsWith(u8, r.name, "TF_DSV41_")); counts[@backingInt(group(r))] += 1; }; - try t.expectEqual([4]usize{ 48, 14, 16, 3 }, counts); + try t.expectEqual([4]usize{ 49, 14, 16, 3 }, counts); } test "DeepSeek strict env: unset and blank settings both read as the caller's default" { diff --git a/zig/src/families/deepseek_v41/float_linear.zig b/zig/src/families/deepseek_v41/float_linear.zig new file mode 100644 index 00000000000..c6b6b5c21ce --- /dev/null +++ b/zig/src/families/deepseek_v41/float_linear.zig @@ -0,0 +1,93 @@ +//! TF_DSV41_FLOAT_LINEAR: a projection a pack keeps as a float matrix alone, planned and run as that matrix. + +const std = @import("std"); +const block = @import("block.zig"); +const knobs = @import("serve_knobs.zig"); +const Config = @import("config.zig").Config; +const Emitter = block.Emitter; + +/// The width table's names, under a block, of the projections `names.plainOf` covers. +pub const projections = [_][]const u8{ "wq_a", "comp_wkv", "comp_wgate", "ix_wk", "ix_wq_b" }; + +/// plain_fp64.BK: the K step `_plain` accumulates in, ascending, whatever the row count. +const plain_bk: i64 = 256; + +/// A float projection: `_plain`'s fp64 sums, rounded to fp32 then bf16 in the launch, into `p.y` from column `p.col`. +pub fn plain(e: *Emitter, p: Emitter.Proj) !void { + const k: i64 = @intCast(p.k); + const n: i64 = @intCast(p.n); + const y = p.y.t; + if (y.dt != .bf16 or y.shape.len != 2 or p.x.t.shape.len != 2) return error.Unsupported; + // `_plain` has no output stride of its own: it stores at OUT + row * N + output, so N is `y`'s row stride + const stride = y.stride[0]; + const out = try e.view(y.role, .bf16, &.{ e.n, n }, &.{ stride, 1 }, y.offset + 2 * @as(i64, @intCast(p.col))); + try e.triton("_plain", .{ e.n, n, 1 }, &.{ + .{ .name = "X", .arg = p.x }, .{ .name = "x_rs", .arg = .{ .i = p.x.t.stride[0] } }, + .{ .name = "W", .arg = try e.weight("{s}.plain", .{p.w}, .f32, &.{ n, k }) }, .{ .name = "w_rs", .arg = .{ .i = k } }, + .{ .name = "OUT", .arg = out }, .{ .name = "K", .arg = .{ .i = k } }, + .{ .name = "N", .arg = .{ .i = stride } }, .{ .name = "BK", .arg = .{ .i = plain_bk } }, + .{ .name = "PDL", .arg = .{ .b = false } }, .{ .name = "BF16", .arg = .{ .b = true } }, + }); +} + +/// `w` with every projection a backbone block may keep float at width 0, which `block.Widths.plain` reads. +pub fn floatWidths(a: std.mem.Allocator, cfg: *const Config, w: *const block.Widths) !block.Widths { + var out: block.Widths = .{ .dense = try w.dense.clone(a), .experts = w.experts, .gm = w.gm }; + var nb: [64]u8 = undefined; + for (0..cfg.layers) |L| for (projections) |proj| { + if (out.dense.getPtr(try std.fmt.bufPrint(&nb, "L{d}.attn.{s}", .{ L, proj }))) |k2| k2.* = 0; + }; + return out; +} + +/// `aot-needs`: the width tables its programs are enumerated over, the second the setting's float projections. +pub fn tables(a: std.mem.Allocator, cfg: *const Config, w: *const block.Widths, get: knobs.Get, log: *std.Io.Writer) ![]const block.Widths { + if (!try knobs.floatLinear(get)) return a.dupe(block.Widths, &.{w.*}); + try log.print("aot-needs: TF_DSV41_FLOAT_LINEAR, a second pass with every projection a pack may keep float\n", .{}); + try log.flush(); + return a.dupe(block.Widths, &.{ w.*, try floatWidths(a, cfg, w) }); +} + +test "the float width table takes a backbone block's five projections to width 0, and nothing else" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const cfg: Config = .{}; + var w: block.Widths = .{}; + var nb: [64]u8 = undefined; + for (projections) |proj| { + try w.dense.put(a, try std.fmt.allocPrint(a, "L2.attn.{s}", .{proj}), 10); + try w.dense.put(a, try std.fmt.allocPrint(a, "L{d}.attn.{s}", .{ cfg.layers, proj }), 10); + } + try w.dense.put(a, "L2.attn.wkv", 10); + const f = try floatWidths(a, &cfg, &w); + for (projections) |proj| { + try std.testing.expect(f.plain(try std.fmt.bufPrint(&nb, "L2.attn.{s}", .{proj}))); + try std.testing.expect(!f.plain(try std.fmt.bufPrint(&nb, "L{d}.attn.{s}", .{ cfg.layers, proj }))); + try std.testing.expect(!w.plain(try std.fmt.bufPrint(&nb, "L2.attn.{s}", .{proj}))); + } + try std.testing.expect(!f.plain("L2.attn.wkv") and !f.plain("L2.attn.wq_b")); +} + +test "aot-needs enumerates the float width table only when TF_DSV41_FLOAT_LINEAR is set" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const cfg: Config = .{}; + var w: block.Widths = .{}; + try w.dense.put(a, "L2.attn.wq_a", 10); + var log: std.Io.Writer.Allocating = .init(a); + const Env = struct { + var value: ?[]const u8 = null; + fn get(name: []const u8) ?[]const u8 { + return if (std.mem.eql(u8, name, "TF_DSV41_FLOAT_LINEAR")) value else null; + } + }; + for ([_]?[]const u8{ null, "0", "1" }, [_]usize{ 1, 1, 2 }) |value, count| { + Env.value = value; + const ts = try tables(a, &cfg, &w, &Env.get, &log.writer); + try std.testing.expectEqual(count, ts.len); + try std.testing.expect(!ts[0].plain("L2.attn.wq_a")); + if (count == 2) try std.testing.expect(ts[1].plain("L2.attn.wq_a")); + } +} diff --git a/zig/src/families/deepseek_v41/gate_forward.zig b/zig/src/families/deepseek_v41/gate_forward.zig index aa75e0ef126..5d974503d5e 100644 --- a/zig/src/families/deepseek_v41/gate_forward.zig +++ b/zig/src/families/deepseek_v41/gate_forward.zig @@ -22,6 +22,8 @@ pub fn widths(a: std.mem.Allocator, w: *const load.Weights, p: *const plan.Plan) var it = w.map.iterator(); while (it.next()) |e| { const name = e.key_ptr.*; + // a float projection (`.plain`) has no K2: width 0 is what block.Widths.plain reads + if (std.mem.endsWith(u8, name, ".plain")) try out.dense.put(a, name[0 .. name.len - ".plain".len], 0); if (!std.mem.endsWith(u8, name, ".trellis") or e.value_ptr.rank != 3) continue; try out.dense.put(a, name[0 .. name.len - ".trellis".len], @intCast(e.value_ptr.shape[2] / 8)); } diff --git a/zig/src/families/deepseek_v41/metal/pick.zig b/zig/src/families/deepseek_v41/metal/pick.zig new file mode 100644 index 00000000000..c679a282650 --- /dev/null +++ b/zig/src/families/deepseek_v41/metal/pick.zig @@ -0,0 +1,50 @@ +// The greedy and sampled picks over a logits row; kept apart from target.zig to keep it under the 600-line cap. +const std = @import("std"); +const host = @import("dsv41"); +const target_ = @import("target.zig"); +const lanes = host.lanes; +const Target = target_.Target; + +/// The keyed choice of a logits row over the whole vocabulary (greedy: the first maximum, ties to the lower id). +pub fn choose(t: *const Target, row: []const f32, draw: u64, smp: ?lanes.Sampling) !u32 { + const s = smp orelse return argmax(row); + if (s.temperature <= 0) return argmax(row); + const vals = t.pick_vals[0..row.len]; + for (vals, row) |*v, x| v.* = x; + return @intCast(try lanes.sampling.choose(t.a, vals, t.pick_ids[0..row.len], draw, s)); +} + +/// The first maximum, ties to the lower id, in 16-wide steps; a row holding a NaN takes the scalar scan. +pub fn argmax(row: []const f32) u32 { + const L = 16; + const V = @Vector(L, f32); + var top: V = @splat(-std.math.inf(f32)); + var nan = false; + var i: usize = 0; + while (i + L <= row.len) : (i += L) { + const v: V = row[i..][0..L].*; + nan = nan or @reduce(.Or, v != v); + top = @max(top, v); + } + var m = @reduce(.Max, top); + for (row[i..]) |x| { + nan = nan or x != x; + m = @max(m, x); + } + if (nan) return scan(row); + var j: usize = 0; + while (j + L <= row.len) : (j += L) { + const v: V = row[j..][0..L].*; + if (@reduce(.Or, v == @as(V, @splat(m)))) break; + } + while (j < row.len) : (j += 1) if (row[j] == m) return @intCast(j); + return 0; +} + +pub fn scan(row: []const f32) u32 { + var best: usize = 0; + for (row, 0..) |x, i| if (x > row[best]) { + best = i; + }; + return @intCast(best); +} diff --git a/zig/src/families/deepseek_v41/metal/target.zig b/zig/src/families/deepseek_v41/metal/target.zig index 5575a44bd5e..ae1f2ed6659 100644 --- a/zig/src/families/deepseek_v41/metal/target.zig +++ b/zig/src/families/deepseek_v41/metal/target.zig @@ -17,6 +17,7 @@ const vw = @import("vision_weights.zig"); const vt = @import("vision_tower.zig"); const vrows = @import("vision_rows.zig"); const prep = @import("vision_prep.zig"); +const pick = @import("pick.zig"); const iface = host.iface; const lanes = host.lanes; @@ -75,6 +76,9 @@ pub const Target = struct { tree: tree_.Tree = .{}, /// the ViT and aligner, when the environment has a tower tower: ?vt.Tower = null, + /// a sampled pick's float64 logits and its ids 0 .. vocab - 1, kept between picks + pick_vals: []f64 = &.{}, + pick_ids: []u64 = &.{}, pub fn init(a: Allocator, env: Env, opt: Options) !*Target { const c = env.c; @@ -87,6 +91,11 @@ pub const Target = struct { errdefer t.b.deinit(); t.pr = try prompt.Prompt.init(env.device, c, opt.prompt, opt.limit); errdefer t.pr.deinit(); + t.pick_vals = try a.alloc(f64, c.vocab); + errdefer a.free(t.pick_vals); + t.pick_ids = try a.alloc(u64, c.vocab); + errdefer a.free(t.pick_ids); + for (t.pick_ids, 0..) |*id, i| id.* = i; const slots = try a.alloc(Slot, opt.slots); errdefer a.free(slots); var made: usize = 0; @@ -161,6 +170,8 @@ pub const Target = struct { t.cache.deinit(); t.pr.deinit(); t.b.deinit(); + t.a.free(t.pick_vals); + t.a.free(t.pick_ids); t.a.destroy(t); } @@ -276,7 +287,7 @@ pub const Target = struct { t.stats.cached_rows += at; } else snapshots.clear(c, &s.kv, s.high); if (images.len > 0) { - s.image_rows = try vrows.Rows.build(t.a, t.env.device, &t.tower.?, images, ids.len, t.opt.prompt.chunk, at); + s.image_rows = try vrows.Rows.build(t.a, t.env.device, &t.tower.?, images, @intCast(ids.len), t.opt.prompt.chunk, at); t.pr.images = if (s.image_rows) |*r| r else null; } s.resumed = at; @@ -317,7 +328,7 @@ pub const Target = struct { t.ringTaps(s, n); } t.promptTaps(s, n); - const choice = try t.choose(logits, draw, smp); + const choice = try pick.choose(t, logits, draw, smp); s.base = n; s.live = true; s.whole = true; @@ -366,29 +377,6 @@ pub const Target = struct { } } - /// The keyed choice of a logits row over the whole vocabulary (greedy: the first maximum, ties to the lower id). - pub fn choose(t: *const Target, row: []const f32, draw: u64, smp: ?lanes.Sampling) !u32 { - const s = smp orelse return argmax(row); - if (s.temperature <= 0) return argmax(row); - const vals = try t.a.alloc(f64, row.len); - defer t.a.free(vals); - const ids = try t.a.alloc(u64, row.len); - defer t.a.free(ids); - for (vals, ids, row, 0..) |*v, *id, x, i| { - v.* = x; - id.* = i; - } - return @intCast(try lanes.sampling.choose(t.a, vals, ids, draw, s)); - } - - fn argmax(row: []const f32) u32 { - var best: usize = 0; - for (row, 0..) |x, i| if (x > row[best]) { - best = i; - }; - return @intCast(best); - } - pub fn fail(t: *Target, e: anyerror) anyerror { if (e == error.CommandBufferFailed) t.failed = true; return e; @@ -457,7 +445,7 @@ pub const Target = struct { for (group, choices) |g, out| { const s = &t.slots[g.slot]; const n = g.tokens.len; - for (0..n) |r| out[r] = try t.choose(lg[(r0 + r) * V ..][0..V], g.draws[r], g.sampling); + for (0..n) |r| out[r] = try pick.choose(t, lg[(r0 + r) * V ..][0..V], g.draws[r], g.sampling); s.base = g.start; s.rows = @intCast(n); s.open = true; @@ -592,3 +580,19 @@ pub const Target = struct { return out.toOwnedSlice(t.a); } }; + +test "argmax: the first maximum, NaN rows as the scalar scan" { + const a = std.testing.allocator; + var prng = std.Random.DefaultPrng.init(7); + const rnd = prng.random(); + const row = try a.alloc(f32, 129280); + defer a.free(row); + for (0..200) |k| { + for (row) |*x| x.* = rnd.floatNorm(f32); + if (k % 5 == 1) row[rnd.uintLessThan(usize, row.len)] = 9.0; + if (k % 5 == 2) row[rnd.uintLessThan(usize, row.len)] = std.math.nan(f32); + if (k % 5 == 3) @memset(row, -std.math.inf(f32)); + if (k % 5 == 4) row[rnd.uintLessThan(usize, 7)] = std.math.nan(f32); + try std.testing.expectEqual(pick.scan(row), pick.argmax(row)); + } +} diff --git a/zig/src/families/deepseek_v41/metal/tree.zig b/zig/src/families/deepseek_v41/metal/tree.zig index 493825dc342..a6c6e7cb3cb 100644 --- a/zig/src/families/deepseek_v41/metal/tree.zig +++ b/zig/src/families/deepseek_v41/metal/tree.zig @@ -5,6 +5,7 @@ const host = @import("dsv41"); const kv = @import("kv.zig"); const snapshots = @import("snapshots.zig"); const pipelines = @import("pipelines.zig"); +const picks = @import("pick.zig"); const target_ = @import("target.zig"); const iface = host.iface; @@ -195,7 +196,7 @@ pub const Tree = struct { const o = &tr.open[trees[w[0]]]; const ch = &o.chains[w[1]]; for (ch.rows[0..ch.n], 0..) |row, i| { - const got = try t.choose(lg[(r0 + i) * V ..][0..V], o.draws[row], o.sampling); + const got = try picks.choose(t, lg[(r0 + i) * V ..][0..V], o.draws[row], o.sampling); // a row run again in front of a branch must choose as it did on its own chain if (o.done[row] and o.out[row] != got) return error.BranchUnstable; if (o.home[row] == w[1]) { diff --git a/zig/src/families/deepseek_v41/named.zig b/zig/src/families/deepseek_v41/named.zig index 7732c766026..b8dbfbacc88 100644 --- a/zig/src/families/deepseek_v41/named.zig +++ b/zig/src/families/deepseek_v41/named.zig @@ -50,6 +50,11 @@ const rules = std.StaticStringMap(Rule).initComptime(.{ .{ "attn.compressor.norm.weight", Rule{ .name = "attn.comp_norm", .out = .f32 } }, .{ "attn.indexer.k_norm.weight", Rule{ .name = "attn.ix_knorm", .out = .f32 } }, .{ "attn.indexer.weights_proj.weight", Rule{ .name = "attn.ix_wp", .out = .f32_via_bf16 } }, + .{ "attn.wq_a.weight", Rule{ .name = "attn.wq_a.plain", .out = .f32_via_bf16 } }, + .{ "attn.compressor.wkv.weight", Rule{ .name = "attn.comp_wkv.plain", .out = .f32_via_bf16 } }, + .{ "attn.compressor.wgate.weight", Rule{ .name = "attn.comp_wgate.plain", .out = .f32_via_bf16 } }, + .{ "attn.indexer.wk.weight", Rule{ .name = "attn.ix_wk.plain", .out = .f32_via_bf16 } }, + .{ "attn.indexer.wq_b.weight", Rule{ .name = "attn.ix_wq_b.plain", .out = .f32_via_bf16 } }, .{ "ffn.gate.weight", Rule{ .name = "moe.gate", .out = .bf16 } }, .{ "ffn.gate.bias", Rule{ .name = "moe.bias", .out = .f32 } }, .{ "engram.q_weight", Rule{ .name = "engram.qk", .out = .qk } }, @@ -371,3 +376,34 @@ test "an F16 router bias and confidence head reach the forward as exactly widene for (values, 0..) |v, i| try testing.expectEqual(@as(u32, @bitCast(@as(f32, v))), std.mem.readInt(u32, n.bytes[4 * i ..][0..4], .little)); } } + +test "a float projection loads as fp32 holding bf16 values, twice its stored bytes" { + const a = testing.allocator; + var tmp = testing.tmpDir(.{}); + defer tmp.cleanup(); + const data = try @import("pack.zig").image(a, &.{ + .{ .name = "b", .dtype = "BF16", .shape = &.{ 2, 8 }, .fill = 0x3f }, + .{ .name = "h", .dtype = "F16", .shape = &.{ 2, 8 }, .fill = 0x3c }, + }); + defer a.free(data); + try tmp.dir.writeFile(testing.io, .{ .sub_path = "model.safetensors", .data = data }); + const dir = try tmp.dir.realPathFileAlloc(testing.io, ".", a); + defer a.free(dir); + var p = try Pack.open(a, testing.io, dir); + defer p.deinit(); + // bf16 0x3f3f widens exactly; fp16 0x3c3c (1 + 60/1024) is a bf16 tie and rounds to even, 1.0625 + for ([_][]const u8{ "b", "h" }, [_]u32{ 0x3f3f0000, 0x3f880000 }) |stored, bits| { + const tensor: plan.NativePlan = .{ .name = stored, .info = p.get(stored).?, .slice = .whole, .bytes = 32 }; + for ([_][]const u8{ "attn.wq_a.weight", "attn.compressor.wkv.weight", "attn.compressor.wgate.weight", "attn.indexer.wk.weight", "attn.indexer.wq_b.weight" }) |suffix| { + const rule = rules.get(suffix).?; + var b: Builder = .{ .gpa = a, .io = testing.io, .pack = &p }; + defer b.deinit(); + var none: ?[]f32 = null; + try b.native(rule.name, rule, tensor, 0, 1, null, &none); + const n = b.find(rule.name).?; + try testing.expect(std.mem.endsWith(u8, n.name, ".plain") and n.kind == .f32); + try testing.expectEqual(2 * tensor.info.nbytes, @as(u64, n.bytes.len)); + for (0..16) |i| try testing.expectEqual(bits, std.mem.readInt(u32, n.bytes[4 * i ..][0..4], .little)); + } + } +} diff --git a/zig/src/families/deepseek_v41/names.zig b/zig/src/families/deepseek_v41/names.zig index 55a6e06aaaf..78d129d9d5f 100644 --- a/zig/src/families/deepseek_v41/names.zig +++ b/zig/src/families/deepseek_v41/names.zig @@ -72,6 +72,21 @@ pub fn groupName(spec: GroupSpec, block: []const u8, buf: []u8) ![]const u8 { return if (spec.proj == .wo_a) std.fmt.bufPrint(buf, "{s}.{s}.{d}", .{ block, spec.suffix, spec.slice }) else std.fmt.bufPrint(buf, "{s}.{s}", .{ block, spec.suffix }); } +/// TF_DSV41_FLOAT_LINEAR: the float matrix a pack may keep for a whole projection in place of its EXL3 group. +pub fn plainOf(spec: GroupSpec) ?NativeSpec { + if (spec.split != .whole) return null; + const suffix = switch (spec.proj) { + .wq_a => "attn.wq_a.weight", + .comp_wkv => "attn.compressor.wkv.weight", + .comp_wgate => "attn.compressor.wgate.weight", + .ix_wk => "attn.indexer.wk.weight", + .ix_wq_b => "attn.indexer.wq_b.weight", + else => return null, + }; + // `.half` is the indexer weights_proj's own storage rule: bf16 or fp16 in the pack, bf16 values in the forward + return NativeSpec.m(suffix, .half, spec.n, spec.k); +} + /// The release's own projections of a block: whole matrices, each with a `.scale` beside it. pub const ReleaseSpec = struct { proj: ReleaseProj, diff --git a/zig/src/families/deepseek_v41/plan.zig b/zig/src/families/deepseek_v41/plan.zig index 00d30899c94..5e23ce92d5d 100644 --- a/zig/src/families/deepseek_v41/plan.zig +++ b/zig/src/families/deepseek_v41/plan.zig @@ -119,6 +119,8 @@ pub const Options = struct { top: bool = false, /// with `blocks` and `top`: also DSpark's heads (main_proj, its norms, the Markov and confidence heads) dspark: bool = false, + /// TF_DSV41_FLOAT_LINEAR: a backbone projection the pack keeps as a float matrix alone is a native, not a group + float_linear: bool = false, }; const Builder = struct { @@ -198,18 +200,39 @@ const Builder = struct { return .{ .proj = proj, .parts = parts, .prefixes = prefixes, .layout = try exl3.Layout.of(b.a, parts) }; } + /// Whether the pack stores `prefix` as a float `.weight` alone: no trellis, and no rotation scales to apply. + fn plainOnly(b: *Builder, prefix: []const u8) !bool { + inline for (.{ "trellis", "suh", "svh", "su", "sv" }) |part| + if (b.pack.has(try std.fmt.bufPrint(&b.buf, "{s}." ++ part, .{prefix}))) return false; + return b.pack.has(try std.fmt.bufPrint(&b.buf, "{s}.weight", .{prefix})); + } + + /// The float matrix `s` is kept as instead of its EXL3 group; null when the setting is off or the group stands. + fn plainSpec(b: *Builder, s: names.GroupSpec, index: u32, name: []const u8) !?names.NativeSpec { + if (!b.o.float_linear or !b.c.isBackbone(index)) return null; + const spec = names.plainOf(s) orelse return null; + return if (try b.plainOnly(name)) spec else null; + } + fn layer(b: *Builder, index: u32) !LayerPlan { var pb: [32]u8 = undefined; const block = try b.dupe(try names.blockPrefix(b.c, index, &pb)); const has_shared = b.pack.has(try std.fmt.bufPrint(&b.buf, "{s}.ffn.shared_experts.w1.trellis", .{block})); const specs = try names.blockGroups(b.c, index, b.o.rank, b.o.world, has_shared); - const groups = try b.a.alloc(GroupPlan, specs.len); - for (specs.items(), groups) |s, *g| { + var nspecs = try names.blockNatives(b.c, index); + var kept: std.ArrayList(GroupPlan) = try .initCapacity(b.a, specs.len); + for (specs.items()) |s| { var nb: [128]u8 = undefined; - g.* = try b.group(s.proj, try names.groupName(s, block, &nb), s.split, s.k, s.n); + const name = try names.groupName(s, block, &nb); + if (try b.plainSpec(s, index, name)) |spec| { + try nspecs.push(spec); + continue; + } + var g = try b.group(s.proj, name, s.split, s.k, s.n); g.slice = s.slice; + kept.appendAssumeCapacity(g); } - const nspecs = try names.blockNatives(b.c, index); + const groups = kept.items; const natives = try b.a.alloc(NativePlan, nspecs.len); for (nspecs.items(), natives) |s, *v| { var nb: [128]u8 = undefined; @@ -394,3 +417,48 @@ test "CUDA rank planning selects EXL3 over a kept dense sibling from headers alo try p.addHeader("dense-only.safetensors", dense, 5242880); try testing.expectError(error.UnsupportedDenseProjection, p.group(prefix, &buf)); } + +test "TF_DSV41_FLOAT_LINEAR off refuses a float-only projection; on, it plans as a native matrix" { + const a = testing.allocator; + const prefix = "layers.2.attn.compressor.wkv"; + const c: Config = .{}; + var p = Pack.init(a); + defer p.deinit(); + try p.addHeader("float.safetensors", "{\"layers.2.attn.compressor.wkv.weight\":{\"dtype\":\"BF16\",\"shape\":[512,5120],\"data_offsets\":[0,5242880]}}", 5242880); + var arena = std.heap.ArenaAllocator.init(a); + defer arena.deinit(); + const spec: names.GroupSpec = .{ .proj = .comp_wkv, .suffix = "attn.compressor.wkv", .split = .whole, .k = c.hidden, .n = c.head_dim }; + // off (the default): the groups are planned as before, and a projection with no trellis is refused as before + var off: Builder = .{ .a = arena.allocator(), .c = &c, .pack = &p, .o = .{ .rank = 1, .world = 2 } }; + try testing.expect(try off.plainSpec(spec, 2, prefix) == null); + try testing.expectError(error.MissingTensor, off.group(spec.proj, prefix, spec.split, spec.k, spec.n)); + var on: Builder = .{ .a = arena.allocator(), .c = &c, .pack = &p, .o = .{ .rank = 1, .world = 2, .float_linear = true } }; + const v = try on.native("layers.2.attn.compressor.wkv.weight", (try on.plainSpec(spec, 2, prefix)).?); + try testing.expectEqual(@as(u64, 5242880), v.bytes); + try testing.expect(on.used.contains("layers.2.attn.compressor.wkv.weight")); + // these keep their group: a DSpark block, a rank-split or unlisted projection, one also stored as EXL3 + try testing.expect(try on.plainSpec(spec, c.layers, prefix) == null); + try testing.expect(names.plainOf(.{ .proj = .comp_wkv, .suffix = "attn.compressor.wkv", .split = .col, .k = c.hidden, .n = c.head_dim }) == null); + try testing.expect(names.plainOf(.{ .proj = .wkv, .suffix = "attn.wkv", .split = .whole, .k = c.hidden, .n = c.head_dim }) == null); + try p.addHeader("layer-02.safetensors", "{\"layers.2.attn.compressor.wkv.trellis\":{\"dtype\":\"I16\",\"shape\":[320,32,80],\"data_offsets\":[0,1638400]}}", 1638400); + try testing.expect(try on.plainSpec(spec, 2, prefix) == null); +} + +test "TF_DSV41_FLOAT_LINEAR leaves a dense projection with rotation scales refused, on or off" { + const a = testing.allocator; + const prefix = "layers.2.attn.compressor.wkv"; + const c: Config = .{}; + var p = Pack.init(a); + defer p.deinit(); + try p.addHeader("dense.safetensors", "{\"layers.2.attn.compressor.wkv.weight\":{\"dtype\":\"BF16\",\"shape\":[512,5120],\"data_offsets\":[0,5242880]}," ++ + "\"layers.2.attn.compressor.wkv.suh\":{\"dtype\":\"F16\",\"shape\":[5120],\"data_offsets\":[5242880,5253120]}," ++ + "\"layers.2.attn.compressor.wkv.svh\":{\"dtype\":\"F16\",\"shape\":[512],\"data_offsets\":[5253120,5254144]}}", 5254144); + var arena = std.heap.ArenaAllocator.init(a); + defer arena.deinit(); + const spec: names.GroupSpec = .{ .proj = .comp_wkv, .suffix = "attn.compressor.wkv", .split = .whole, .k = c.hidden, .n = c.head_dim }; + for ([_]bool{ false, true }) |on| { + var b: Builder = .{ .a = arena.allocator(), .c = &c, .pack = &p, .o = .{ .rank = 1, .world = 2, .float_linear = on } }; + try testing.expect(try b.plainSpec(spec, 2, prefix) == null); + try testing.expectError(error.UnsupportedDenseProjection, b.group(spec.proj, prefix, spec.split, spec.k, spec.n)); + } +} diff --git a/zig/src/families/deepseek_v41/serve_knobs.zig b/zig/src/families/deepseek_v41/serve_knobs.zig index 2fe21240e19..95a82ae57f9 100644 --- a/zig/src/families/deepseek_v41/serve_knobs.zig +++ b/zig/src/families/deepseek_v41/serve_knobs.zig @@ -173,6 +173,11 @@ pub fn kvNormStore(get: Get) !bool { return @import("sys").environment.value(bool, "TF_DSV41_KV_NORM_STORE", get("TF_DSV41_KV_NORM_STORE"), false); } +/// TF_DSV41_FLOAT_LINEAR=1: a projection a pack keeps as a float matrix alone is planned and run as one; default off. +pub fn floatLinear(get: Get) !bool { + return @import("sys").environment.value(bool, "TF_DSV41_FLOAT_LINEAR", get("TF_DSV41_FLOAT_LINEAR"), false); +} + /// TF_DSV41_ROUTER_GROUP_ROT=1: histogram grouping + input rotation, default off. pub fn routerGroupRot(get: Get) !bool { return @import("sys").environment.value(bool, "TF_DSV41_ROUTER_GROUP_ROT", get("TF_DSV41_ROUTER_GROUP_ROT"), false); diff --git a/zig/src/families/deepseek_v41/serve_knobs_test.zig b/zig/src/families/deepseek_v41/serve_knobs_test.zig index 4ef89bdd955..2fadf080f40 100644 --- a/zig/src/families/deepseek_v41/serve_knobs_test.zig +++ b/zig/src/families/deepseek_v41/serve_knobs_test.zig @@ -258,3 +258,19 @@ test "KV producer norm/store fusion is separately opt-in" { try testing.expect(!(try pk.routerGroupRot(&Fake.get))); Fake.pairs = &.{}; } + +test "float linear projections are opt-in" { + Fake.pairs = &.{}; + try testing.expect(!(try pk.floatLinear(&Fake.get))); + for ([_][]const u8{ "0", "", " " }) |value| { + Fake.pairs = &.{.{ "TF_DSV41_FLOAT_LINEAR", value }}; + try testing.expect(!(try pk.floatLinear(&Fake.get))); + } + for ([_][]const u8{ "false", "yes", "2" }) |value| { + Fake.pairs = &.{.{ "TF_DSV41_FLOAT_LINEAR", value }}; + try testing.expectError(error.InvalidEnvironment, pk.floatLinear(&Fake.get)); + } + Fake.pairs = &.{.{ "TF_DSV41_FLOAT_LINEAR", " 1 " }}; + try testing.expect((try pk.floatLinear(&Fake.get))); + Fake.pairs = &.{}; +} diff --git a/zig/src/families/flashnext/backend.zig b/zig/src/families/flashnext/backend.zig index b2b61e3857d..d7f7ad6c241 100644 --- a/zig/src/families/flashnext/backend.zig +++ b/zig/src/families/flashnext/backend.zig @@ -102,7 +102,7 @@ pub const Backend = struct { } pub fn backend(b: *Backend) be.Backend { - return .{ .ptr = b, .vtable = &.{ .prefill = fill.Callbacks(Backend).whole, .prefill_step = fill.Callbacks(Backend).one, .first = first, .queue = queue, .read = read, .verify = verify, .keep = keep, .draft = draft, .release = release, .first_masked = grammar.firstMasked, .held = grammar.held, .reports_fill = true } }; + return .{ .ptr = b, .vtable = &.{ .prefill = fill.Callbacks(Backend).whole, .prefill_step = fill.Callbacks(Backend).one, .cancel_prefill = fill.Callbacks(Backend).cancelPrompt, .first = first, .queue = queue, .read = read, .verify = verify, .keep = keep, .draft = draft, .release = release, .first_masked = grammar.firstMasked, .held = grammar.held, .reports_fill = true } }; } pub const facts = batch_costs.facts; @@ -232,8 +232,8 @@ pub const Backend = struct { pub fn chunkPrompt(b: *Backend, stream: *Stream, slot: usize, at: u32, rows: u32) !void { try prompt_gpu.chunk(b, stream, slot, at, rows); } - pub fn markPrompt(b: *Backend, stream: *Stream, at: u32) !void { - try prompt_gpu.mark(b, stream, at); + pub fn markPrompt(b: *Backend, stream: *Stream, at: u32, interrupted: bool) !void { + try prompt_gpu.mark(b, stream, at, interrupted); } pub fn finishPrompt(b: *Backend, stream: *Stream) !void { try prompt_gpu.finish(b, stream); diff --git a/zig/src/families/flashnext/cuda_lanes_load.zig b/zig/src/families/flashnext/cuda_lanes_load.zig index 9bc26ca994c..5ad7e03cda5 100644 --- a/zig/src/families/flashnext/cuda_lanes_load.zig +++ b/zig/src/families/flashnext/cuda_lanes_load.zig @@ -64,13 +64,13 @@ pub fn open(comptime F: type, gpa: std.mem.Allocator, io: std.Io, ctx: *const cu r.deinit(); }; own.engine = try prompt.Engine.initRank(gpa, io, driver, &own.stream, dir, o.tp, o.rank); + errdefer own.engine.deinit(); own.engine.chunk = chunk; if (own.ranks) |r| { r.engine = own.engine; own.engine.collective = &r.collective; - r.benchmark_group = try @import("core").benchmark_group.cuda(gpa, io, ctx, &r.collective, own.stream); + try r.afterLoad(io, ctx, own.stream); } - errdefer own.engine.deinit(); const e = own.engine; if (e.chunk != e.busy_chunk) std.log.info("flashnext: prompt passes of {d} rows, {d} while another stream decodes", .{ e.chunk, e.busy_chunk }); if (o.vision) |limits| { diff --git a/zig/src/families/flashnext/cuda_mtp.zig b/zig/src/families/flashnext/cuda_mtp.zig index 4d6f0424b4e..d81114959af 100644 --- a/zig/src/families/flashnext/cuda_mtp.zig +++ b/zig/src/families/flashnext/cuda_mtp.zig @@ -432,4 +432,5 @@ test "draft chains fit one verify window while the default stays six" { test { _ = @import("cuda_mtp_nonfinite_test.zig"); + _ = @import("cuda_mtp_load.zig"); } diff --git a/zig/src/families/flashnext/cuda_mtp_load.zig b/zig/src/families/flashnext/cuda_mtp_load.zig index 37062a694cd..eb91126cc57 100644 --- a/zig/src/families/flashnext/cuda_mtp_load.zig +++ b/zig/src/families/flashnext/cuda_mtp_load.zig @@ -4,14 +4,25 @@ const cuda = @import("cuda"); const wt = @import("cuda_prompt_wt.zig"); const core = @import("core"); const projection = @import("cuda_projection.zig"); +const environment = @import("sys").environment; +const name = "TF_FLASHNEXT_DRAFT_HEAD"; + +/// How a bf16 language head's draft rows are held; the order is the setting's accepted words. pub const Mode = enum { bf16, affine4 }; + +/// What an unset or blank TF_FLASHNEXT_DRAFT_HEAD selects: the rows as 4-bit affine groups of 32. +pub const default_mode: Mode = .affine4; + +/// The setting's text as its reader takes it: unset or blank is the default, anything malformed is refused by name. +fn parse(raw: ?[]const u8) !Mode { + return @fromBackingInt(@intCast(try environment.value(u1, name, raw, @backingInt(default_mode)))); +} + pub fn mode() !Mode { - const value = if (std.c.getenv("TF_FLASHNEXT_DRAFT_HEAD")) |v| std.mem.span(v) else "bf16"; - if (std.mem.eql(u8, value, "bf16")) return .bf16; - if (std.mem.eql(u8, value, "affine4")) return .affine4; - return error.BadDraftHead; + return @fromBackingInt(@intCast(try environment.read(u1, name, @backingInt(default_mode)))); } + pub fn draft(a: std.mem.Allocator, d: *cuda.Driver, store: *wt.Store, artifact: *const core.proposal_vocab.Artifact, role: Mode) !wt.Q4 { const ids = artifact.ids(); const affine = role == .affine4; @@ -47,3 +58,10 @@ fn quantized(a: std.mem.Allocator, d: *cuda.Driver, rows: []const u8, n: usize) for (0..n) |i| try @import("cuda_draft_affine.zig").row(rows[i * wt.dims * 2 ..][0 .. wt.dims * 2], words[i * wt.dims / 2 ..][0 .. wt.dims / 2], scales[i * wt.dims / 16 ..][0 .. wt.dims / 16], biases[i * wt.dims / 16 ..][0 .. wt.dims / 16]); return wt.uploadQ4(a, d, words, scales, biases, n, wt.dims / 8); } + +test "unset and blank read affine4, the two words read as themselves, and other text is refused" { + for ([_]?[]const u8{ null, "", " ", "\t", " \t\r\n" }) |raw| try std.testing.expectEqual(Mode.affine4, try parse(raw)); + try std.testing.expectEqual(Mode.bf16, try parse("bf16")); + try std.testing.expectEqual(Mode.affine4, try parse("affine4")); + for ([_][]const u8{ "BF16", "affine", "fp8", "1", "bf16 ", "checkpoint" }) |raw| try std.testing.expectError(error.InvalidEnvironment, parse(raw)); +} diff --git a/zig/src/families/flashnext/cuda_rank_engine.zig b/zig/src/families/flashnext/cuda_rank_engine.zig index 0da62811709..e5a7987d7f0 100644 --- a/zig/src/families/flashnext/cuda_rank_engine.zig +++ b/zig/src/families/flashnext/cuda_rank_engine.zig @@ -152,6 +152,12 @@ pub const Session = struct { return @min(local, peer.arg); } + /// The first collective once the peer has loaded: the load-ready exchange bounds the wait; a closed link ends it. + pub fn afterLoad(s: *Session, io: std.Io, ctx: *const cuda.Context, stream: cuda.Stream) !void { + _ = try s.room(std.math.maxInt(u64)); + s.benchmark_group = try @import("core").benchmark_group.cuda(s.gpa, io, ctx, &s.collective, stream); + } + pub fn command(s: *Session, input: wire.Header, payload: []const u8) !wire.Header { if (s.rank != 0 or s.stopped or s.collective.failed) return error.RankDisconnected; if (payload.len > wire.max_payload or input.bytes != payload.len) return error.BadRankFrame; @@ -552,3 +558,7 @@ test "rank identity: the cached full digest by default, a given digest when set, _ = env.setenv("TENSORFOLD_CHECKPOINT_SHA256", "ab", 1); try t.expectError(error.NoCheckpointIdentity, identity(t.allocator, t.io, dir, 4096, 64)); } + +test { + if (@import("builtin").os.tag != .windows) _ = @import("cuda_rank_start_test.zig"); // over a Unix socket pair +} diff --git a/zig/src/families/flashnext/cuda_rank_start_test.zig b/zig/src/families/flashnext/cuda_rank_start_test.zig new file mode 100644 index 00000000000..50f9a2b088a --- /dev/null +++ b/zig/src/families/flashnext/cuda_rank_start_test.zig @@ -0,0 +1,99 @@ +//! The first collective waits for the peer's load past the collective's own bound; a closed peer ends the wait. +const std = @import("std"); +const cuda = @import("cuda"); +const ranks = @import("cuda_rank_engine.zig"); +const wire = @import("cuda_rank_wire.zig"); +const nccl = cuda.nccl; + +// The first collective's first call records when it came and is refused, so the test stops there. +const Fake = struct { + var entered: ?u64 = null; + fn count(_: nccl.Comm, _: *c_int) callconv(.c) c_int { + entered = wire.now(); + return 1; + } + fn abort(_: nccl.Comm) callconv(.c) c_int { + return 0; + } +}; + +/// The peer still loading: after `delay_ms` it sends its load-ready frame, or closes its link as a failed load does. +const Peer = struct { + fd: c_int, + delay_ms: u64, + leaves: bool, + sent: u64 = 0, + fn run(p: *Peer) void { + const pause: std.c.timespec = .{ .sec = @intCast(p.delay_ms / 1000), .nsec = @intCast(p.delay_ms % 1000 * std.time.ns_per_ms) }; + _ = std.c.nanosleep(&pause, null); + p.sent = wire.now(); + if (p.leaves) { + _ = std.c.shutdown(p.fd, std.posix.SHUT.RDWR); + } else { + const link: wire.Link = .{ .fd = p.fd }; + link.sendHeader(.{ .kind = .ready, .arg = 7 }, wire.deadline(1000)) catch {}; + } + } +}; + +fn session(rank: usize, pair: *[2]c_int) !ranks.Session { + if (std.c.socketpair(std.posix.AF.UNIX, std.posix.SOCK.STREAM, 0, pair) != 0) return error.SocketPair; + const nonblock: c_int = @bitCast(@as(u32, @bitCast(std.c.O{ .NONBLOCK = true }))); + for (pair) |fd| { + const flags = std.c.fcntl(fd, std.c.F.GETFL); + if (flags < 0 or std.c.fcntl(fd, std.c.F.SETFL, flags | nonblock) < 0) return error.Nonblocking; + } + Fake.entered = null; + var s: ranks.Session = .{ .gpa = std.testing.allocator, .rank = rank, .link = .{ .fd = pair[0] }, .collective = undefined }; + s.collective.failed = false; + s.collective.comm = @ptrFromInt(0x1000); + s.collective.link = .{ .fd = pair[0] }; + s.collective.timeout_ms = 50; + s.collective.lib.api.ncclCommCount = Fake.count; + s.collective.api.ncclCommAbort = Fake.abort; + return s; +} + +fn afterPeer(rank: usize, delay_ms: u64, leaves: bool) !struct { s: ranks.Session, peer: Peer, result: anyerror!void, waited: u64 } { + var pair: [2]c_int = undefined; + var s = try session(rank, &pair); + defer for (pair) |fd| { + _ = std.c.close(fd); + }; + var peer: Peer = .{ .fd = pair[1], .delay_ms = delay_ms, .leaves = leaves }; + const thread = try std.Thread.spawn(.{}, Peer.run, .{&peer}); + var ctx: cuda.Context = undefined; + var d: cuda.Driver = undefined; + const started = wire.now(); + const result = s.afterLoad(std.testing.io, &ctx, .{ .d = &d, .handle = null }); + const waited = wire.now() - started; + thread.join(); + return .{ .s = s, .peer = peer, .result = result, .waited = waited }; +} + +test "rank start: a peer loading past the collective's bound is awaited before the first collective" { + for (0..2) |rank| { + const run = try afterPeer(rank, 400, false); + try std.testing.expectError(error.NcclFailed, run.result); + try std.testing.expect(run.waited > 4 * run.s.collective.timeout_ms * std.time.ns_per_ms); + try std.testing.expect(Fake.entered.? >= run.peer.sent); + } +} + +test "rank start: a peer that closes its link during the wait ends it at once, before any collective" { + for (0..2) |rank| { + const run = try afterPeer(rank, 100, true); + try std.testing.expectError(error.RankDisconnected, run.result); + try std.testing.expect(run.waited < 1100 * std.time.ns_per_ms); + try std.testing.expect(Fake.entered == null); + try std.testing.expect(run.s.stopped and run.s.collective.failed and run.s.collective.comm == null); + } +} + +test "rank start: the loader's first collective waits for the peer's load, and a failed wait frees the engine" { + const load = @embedFile("cuda_lanes_load.zig"); + try std.testing.expect(std.mem.indexOf(u8, load, "benchmark_group.") == null); + const wait = std.mem.indexOf(u8, load, "try r.afterLoad(io, ctx, own.stream);") orelse return error.TestUnexpectedResult; + const free = std.mem.indexOf(u8, load, "errdefer own.engine.deinit();") orelse return error.TestUnexpectedResult; + try std.testing.expect(free < wait); +} diff --git a/zig/src/families/flashnext/cuda_rank_wire.zig b/zig/src/families/flashnext/cuda_rank_wire.zig index 23fc60e5485..017b58aea5b 100644 --- a/zig/src/families/flashnext/cuda_rank_wire.zig +++ b/zig/src/families/flashnext/cuda_rank_wire.zig @@ -58,19 +58,33 @@ pub fn pause() void { _ = platform.c.nanosleep(&ts, null); } +/// How long a wait polls with a short timeout before it blocks: a core idle through a whole round wakes late. +pub const warm_ns = 50 * std.time.ns_per_ms; + fn wait(fd: p.socket_t, events: i16, until: ?u64) !void { + const start = now(); while (true) { const current = now(); if (until) |end| if (current >= end) return error.RankTimeout; const ms: i32 = if (until) |end| @intCast(@min(1000, (end - current + std.time.ns_per_ms - 1) / std.time.ns_per_ms)) else 1000; var fds = [_]p.pollfd{.{ .fd = fd, .events = events, .revents = 0 }}; - const count = try p.poll(&fds, ms); + const count = if (current - start < warm_ns) try shortPoll(&fds) else try p.poll(&fds, ms); if (count == 0) continue; if (fds[0].revents & events != 0) return; if (fds[0].revents & (p.POLL.ERR | p.POLL.HUP | p.POLL.NVAL) != 0) return error.RankDisconnected; } } +/// One poll ending within about 50 us: the core stays in a shallow idle state, and data wakes it at once. +fn shortPoll(fds: []p.pollfd) !usize { + if (builtin.os.tag != .linux) return p.poll(fds, 1); + const short: p.timespec = .{ .sec = 0, .nsec = 50_000 }; + return p.ppoll(fds, &short, null) catch |err| switch (err) { + error.SignalInterrupt => 0, + else => err, + }; +} + pub const Link = struct { fd: p.socket_t, @@ -220,3 +234,43 @@ test "rank frames are versioned, bounded and exact" { try std.testing.expectError(error.BadRankFrame, Header.decode(&raw)); try std.testing.expectError(error.BadRankFrame, (Header{ .kind = .forward, .bytes = max_payload + 1 }).encode()); } + +fn sendLater(fd: c_int, ms: u64, close: bool) void { + const ts: platform.c.timespec = .{ .sec = @intCast(ms / 1000), .nsec = @intCast((ms % 1000) * std.time.ns_per_ms) }; + _ = platform.c.nanosleep(&ts, null); + const byte: u8 = 7; + if (close) _ = std.c.close(fd) else _ = std.c.send(fd, &byte, 1, 0); +} + +fn sleeps() isize { + return if (builtin.os.tag == .linux) p.getrusage(p.rusage.THREAD).nvcsw else 0; +} + +test "a link wait polls briefly, then blocks, and still ends at its data, its deadline or its peer's exit" { + if (builtin.os.tag == .windows) return error.SkipZigTest; + var pair: [2]c_int = undefined; + if (std.c.socketpair(p.AF.UNIX, p.SOCK.STREAM, 0, &pair) != 0) return error.SocketPair; + defer _ = std.c.close(pair[0]); + const flags = std.c.fcntl(pair[0], p.F.GETFL); + _ = std.c.fcntl(pair[0], p.F.SETFL, flags | @as(c_int, @bitCast(@as(u32, @bitCast(p.O{ .NONBLOCK = true }))))); + const l: Link = .{ .fd = pair[0] }; + var byte: [1]u8 = .{0}; + var start = now(); + try std.testing.expectError(error.RankTimeout, l.receive(&byte, deadline(20))); + try std.testing.expect(now() - start >= 20 * std.time.ns_per_ms and now() - start < std.time.ns_per_s); + // a byte inside the short polls, then one after them: the short polls stop at warm_ns, then one poll blocks + for ([_]u64{ 5, 600 }) |late| { + start = now(); + const t = try std.Thread.spawn(.{}, sendLater, .{ pair[1], late, false }); + const before = sleeps(); + try l.receive(&byte, null); + const polls = sleeps() - before; + t.join(); + try std.testing.expect(byte[0] == 7 and now() - start >= late * std.time.ns_per_ms); + if (builtin.os.tag == .linux and late > 50) try std.testing.expect(polls > 20 and polls < 2000); + byte[0] = 0; + } + const t = try std.Thread.spawn(.{}, sendLater, .{ pair[1], 5, true }); + defer t.join(); + try std.testing.expectError(error.RankDisconnected, l.receive(&byte, deadline(1000))); +} diff --git a/zig/src/families/flashnext/hip.zig b/zig/src/families/flashnext/hip.zig index f60dc1f6547..affce8c9db0 100644 --- a/zig/src/families/flashnext/hip.zig +++ b/zig/src/families/flashnext/hip.zig @@ -40,4 +40,5 @@ test { _ = native; _ = @import("hip/state_test.zig"); _ = @import("hip/fused_prep_test.zig"); + _ = @import("hip/mtp_drafts_test.zig"); } diff --git a/zig/src/families/flashnext/hip/cache.zig b/zig/src/families/flashnext/hip/cache.zig index ee1c0167fb0..a62e89d2fa3 100644 --- a/zig/src/families/flashnext/hip/cache.zig +++ b/zig/src/families/flashnext/hip/cache.zig @@ -63,6 +63,11 @@ pub const Layout = struct { return l.conv_bytes + l.state_bytes; } + /// Device bytes of the caches past the sparse layers (linear, then the n-gram tail); also a side buffer's size. + pub fn restBytes(l: Layout) usize { + return l.linear * l.linearBytes() + l.tail_bytes; + } + /// Device bytes of a stream's caches at `cap` positions. pub fn bytes(l: Layout) usize { return l.sparse * l.sparseBytes() + l.linear * l.linearBytes() + l.tail_bytes; @@ -175,6 +180,19 @@ pub const Caches = struct { return .{ .conv = at, .state = at + l.conv_bytes }; } + /// Linear layer `layer`'s conv and state in a side buffer at `side` laid out as the caches past the sparse layers. + pub fn sideLinear(c: *const Caches, side: u64, layer: usize) LinearView { + const l = c.layout; + const at = side + c.slot[layer] * l.linearBytes(); + return .{ .conv = at, .state = at + l.conv_bytes }; + } + + /// The n-gram tail in such a side buffer. + pub fn sideTail(c: *const Caches, side: u64) u64 { + const l = c.layout; + return side + l.linear * l.linearBytes(); + } + /// The n-gram conv's tail rows (act dtype, (tail_rows, W)). pub fn tail(c: *const Caches) u64 { const l = c.layout; @@ -206,14 +224,8 @@ pub const Pool = struct { cap: usize, maker: anytype, ) !Caches { - while (p.slots.items.len <= slot) try p.slots.append(gpa, null); - while (p.made.items.len <= slot) try p.made.append(gpa, .{ 0, 0, 0 }); + try p.make(gpa, slot, cap, maker); const held = &p.slots.items[slot]; - if (held.* == null) { - held.* = try maker.caches(cap); - held.*.?.id = slot; - p.made.items[slot] = buffersOf(&held.*.?); - } try s.synchronize(); try held.*.?.reset(eos); const c = held.*.?; @@ -221,6 +233,17 @@ pub const Pool = struct { return c; } + /// Slot `slot`'s caches made if not yet: by its first lease, or ahead of it (at load). + pub fn make(p: *Pool, gpa: std.mem.Allocator, slot: u32, cap: usize, maker: anytype) !void { + while (p.slots.items.len <= slot) try p.slots.append(gpa, null); + while (p.made.items.len <= slot) try p.made.append(gpa, .{ 0, 0, 0 }); + const held = &p.slots.items[slot]; + if (held.* != null) return; + held.* = try maker.caches(cap); + held.*.?.id = slot; + p.made.items[slot] = buffersOf(&held.*.?); + } + /// A finished stream's caches back to their slot. pub fn unlease(p: *Pool, c: Caches) void { p.slots.items[c.id] = c; diff --git a/zig/src/families/flashnext/hip/engine.zig b/zig/src/families/flashnext/hip/engine.zig index e4cf3866bef..a4ce6a3f592 100644 --- a/zig/src/families/flashnext/hip/engine.zig +++ b/zig/src/families/flashnext/hip/engine.zig @@ -400,12 +400,17 @@ pub const Engine = struct { /// A prompt's `tokens` from `c.len` into `c`, kept: the final rows of the last of them. pub fn prompt(e: *Engine, c: *cache.Caches, tokens: []const u32) !forward.Out { + return e.promptMarked(c, tokens, &.{}); + } + + /// `prompt`, the state before each of `marks`' rows written aside (forward.Mark, rows ascending). + pub fn promptMarked(e: *Engine, c: *cache.Caches, tokens: []const u32, marks: []const forward.Mark) !forward.Out { if (e.stopped) return error.GroupStopped; // the staging is reused: the last forward's uploads must have left it try e.stream.synchronize(); e.host.used = 0; e.arena.reset(); - const segs = [_]forward.Seg{.{ .c = c, .tokens = tokens, .pos = c.len }}; + const segs = [_]forward.Seg{.{ .c = c, .tokens = tokens, .pos = c.len, .marks = marks }}; const staged = try forward.stage(&e.weights.model, &e.host, &segs, false); const out = try forward.run(e.ops(&e.arena), &e.weights.model, &e.host, &segs, false, staged); c.len += tokens.len; @@ -485,6 +490,11 @@ pub const Engine = struct { return e.pool.lease(e.gpa, slot, e.stream, e.eos, e.o.capacity, e); } + /// The first stream's caches made now (at load) rather than by the first prompt; later slots on their first lease. + pub fn makeFirstSlot(e: *Engine) !void { + try e.pool.make(e.gpa, 0, e.o.capacity, e); + } + /// A finished stream's caches back to their slot. pub fn unlease(e: *Engine, c: cache.Caches) void { e.pool.unlease(c); diff --git a/zig/src/families/flashnext/hip/facts.zig b/zig/src/families/flashnext/hip/facts.zig index fe82e50eab6..15378873419 100644 --- a/zig/src/families/flashnext/hip/facts.zig +++ b/zig/src/families/flashnext/hip/facts.zig @@ -1,10 +1,11 @@ //! The lane core's facts of a loaded Flash Next model, pure so a host test drives them without a device. const std = @import("std"); const lanes = @import("lanes"); +const hip = @import("hip"); const cache = @import("cache.zig"); -/// MTP drafts the HIP head takes at most: `--mtp-drafts` is refused past it (native/hip.zig's check). -pub const mtp_max_drafts: u32 = 3; +/// MTP drafts the HIP head takes at most: the window's rows less its pending token. +pub const mtp_max_drafts: u32 = cache.max_window - 1; /// The policy's `--mtp-drafts` capped at the head's. pub fn capDrafts(asked: u8) u32 { @@ -14,6 +15,9 @@ pub fn capDrafts(asked: u8) u32 { /// A shared round's copy window and a lone stream's first: the pending row and three copies; lone runs grow past it. const shared_copy_rows = 4; +/// Most head drafts a stream chains in a shared round; a lone stream chains the policy's drafts. +pub const shared_chain_drafts = 3; + /// The lane core's facts of a loaded model: `drafting` names a head that drafts, `drafts` its capped chains. pub fn factsFor(exact_width: u32, streams: usize, drafting: bool, drafts: u32) lanes.Model { return .{ @@ -24,6 +28,7 @@ pub fn factsFor(exact_width: u32, streams: usize, drafting: bool, drafts: u32) l .speculate = drafting, .speculate_early = false, .drafts = drafts, + .shared_mtp_cap = shared_chain_drafts, .hidden_rows = true, .batch_rows = @intCast(exact_width * streams), .max_streams = @intCast(streams), @@ -46,3 +51,16 @@ test "the extracted facts retain the loaded head drafting mode" { try std.testing.expectEqual(drafting, facts.draft_streams); } } + +test "the facts cap shared chains at three, and the default policy asks the lane core for three drafts" { + const a = std.testing.allocator; + const asked: u32 = (hip.Policy{}).mtp.drafts; + var cfg = try lanes.Config.init(a, factsFor(cache.max_window, 1, true, asked), cache.max_window, cache.max_window - 1); + defer cfg.deinit(a); + try std.testing.expectEqual(@as(u32, 3), cfg.most_drafts); + try std.testing.expectEqual(@as(u32, 3), cfg.shared_mtp_cap); + var deep = try lanes.Config.init(a, factsFor(cache.max_window, 1, true, 7), cache.max_window, cache.max_window - 1); + defer deep.deinit(a); + try std.testing.expectEqual(@as(u32, 7), deep.most_drafts); + try std.testing.expectEqual(@as(u32, 3), deep.shared_mtp_cap); +} diff --git a/zig/src/families/flashnext/hip/forward.zig b/zig/src/families/flashnext/hip/forward.zig index f7a7b9a682c..8044141863e 100644 --- a/zig/src/families/flashnext/hip/forward.zig +++ b/zig/src/families/flashnext/hip/forward.zig @@ -48,10 +48,13 @@ pub fn at(t: Tensor, n: usize) Tensor { } /// One call's rows: their tokens, the position of the first, and whether they are a window (else a prompt's). -pub const Call = struct { tokens: []const u32, pos: usize, window: bool }; +pub const Call = struct { tokens: []const u32, pos: usize, window: bool, marks: []const Mark = &.{} }; /// One stream's rows in a forward: its caches, its tokens and the position of its first row. -pub const Seg = struct { c: *cache.Caches, tokens: []const u32, pos: usize }; +pub const Seg = struct { c: *cache.Caches, tokens: []const u32, pos: usize, marks: []const Mark = &.{} }; + +/// A kept row inside a prompt chunk (a multiple of 64): its linear and n-gram state to `side`, as a chunk ending there. +pub const Mark = struct { row: usize, side: u64 }; /// The final mixer's rows (rows, hidden) for the head, and the residual streams (rows, wide) before it. pub const Out = struct { mixed: Tensor, streams: Tensor }; @@ -318,6 +321,13 @@ fn ple( tail, o.stream, ); + for (call.marks) |mk| try hip.raw.copy( + .{ .r = host.d, .ptr = @ptrFromInt(c.sideTail(mk.side)), .len = tail }, + 0, + cin + mk.row * d.wide() * m.act.size(), + tail, + o.stream, + ); c.history = ngram.after(c.history, call.tokens); } } @@ -359,7 +369,7 @@ pub fn run(ops: Ops, m: *const model.Model, host: *Host, segs: []const Seg, wind host, g.c, at(h, off * d.wide()), - .{ .tokens = g.tokens, .pos = g.pos, .window = window }, + .{ .tokens = g.tokens, .pos = g.pos, .window = window, .marks = g.marks }, cin, in, off, diff --git a/zig/src/families/flashnext/hip/fused_prep_test.zig b/zig/src/families/flashnext/hip/fused_prep_test.zig index 7b3df76e864..c79d048d65a 100644 --- a/zig/src/families/flashnext/hip/fused_prep_test.zig +++ b/zig/src/families/flashnext/hip/fused_prep_test.zig @@ -299,3 +299,67 @@ test "Flash Next fused prompt prep: one segment through linear() leaves the unfu test "Flash Next fused prompt prep: two segments through linear() leave the unfused chain's bytes" { try check(&.{ 45, 19 }); } + +/// Kept rows at `at` in one chunk of `n` rows: its bytes as without them, each side's state as after its rows alone. +fn checkMarks(n: usize, at: []const usize) !void { + var g: Gpu = undefined; + try g.open(64 << 20); + defer g.close(); + var prng: std.Random.DefaultPrng = .init(0x6b70); + const rng = prng.random(); + var w: Layer = undefined; + try w.init(&g, rng); + defer w.deinit(); + const d = w.m.dims; + const hx = try gpa.alloc(u16, n * d.hidden); + defer gpa.free(hx); + for (hx) |*v| v.* = bits(g.act, unit(rng)); + var dx = try hip.DeviceBuffer.fromHost(&g.r, std.mem.sliceAsBytes(hx)); + defer dx.free(); + const x: hip.ops.Tensor = .{ .ptr = dx.base(), .kind = g.act }; + const tokens = try gpa.alloc(u32, n); + defer gpa.free(tokens); + @memset(tokens, 0); + var c = try cache.Caches.init(gpa, &g.r, d, &.{true}, 64, g.act, 0); + defer c.deinit(gpa); + const start = try gpa.alloc(f32, (c.layout.conv_bytes + c.layout.state_bytes) / 4); + defer gpa.free(start); + const taps = c.layout.conv_bytes / 4; + for (start[0..taps]) |*v| v.* = unit(rng); + for (start[taps..]) |*v| v.* = 0.1 * unit(rng); + const starts = [_][]f32{start}; + // each kept row's side buffer, laid out as the caches past the sparse layers + const rest = std.mem.alignForward(usize, c.layout.restBytes(), 256); + var sides = try hip.DeviceBuffer.alloc(&g.r, at.len * rest); + defer sides.free(); + var marks: [4]forward.Mark = undefined; + for (at, 0..) |row, i| marks[i] = .{ .row = row, .side = sides.base() + i * rest }; + for ([_]*const hip.Launcher{ &g.on, &g.off }) |l| { + var taken: usize = 0; + try sides.fill8(0x3c); + var marked = try run(&g, &w, l, x, &.{.{ .c = &c, .tokens = tokens, .pos = 0, .marks = marks[0..at.len] }}, &starts, 0xa5, &taken); + defer freeParts(&marked); + var plain = try run(&g, &w, l, x, &.{.{ .c = &c, .tokens = tokens, .pos = 0 }}, &starts, 0x5a, &taken); + defer freeParts(&plain); + for (marked.items, plain.items) |a, b| { + if (std.mem.indexOfDiff(u8, a.bytes, b.bytes)) |i| std.debug.print("{s} with kept rows differs at byte {d}\n", .{ a.name, i }); + try std.testing.expectEqualSlices(u8, b.bytes, a.bytes); + } + for (at, 0..) |row, i| { + var before = try run(&g, &w, l, x, &.{.{ .c = &c, .tokens = tokens[0..row], .pos = 0 }}, &starts, 0x77, &taken); + defer freeParts(&before); + const view = c.sideLinear(marks[i].side, 0); + const conv = try fetch(sides, view.conv, c.layout.conv_bytes); + defer gpa.free(conv); + const state = try fetch(sides, view.state, c.layout.state_bytes); + defer gpa.free(state); + // the parts end with the stream's live conv tail and state + try std.testing.expectEqualSlices(u8, before.items[before.items.len - 2].bytes, conv); + try std.testing.expectEqualSlices(u8, before.items[before.items.len - 1].bytes, state); + } + } +} + +test "Flash Next fused prompt prep: kept rows inside a chunk leave its bytes, each side the state of the rows before it" { + try checkMarks(150, &.{ 64, 100, 128 }); +} diff --git a/zig/src/families/flashnext/hip/lanes.zig b/zig/src/families/flashnext/hip/lanes.zig index 8cd05d12829..d8fa79d9d18 100644 --- a/zig/src/families/flashnext/hip/lanes.zig +++ b/zig/src/families/flashnext/hip/lanes.zig @@ -12,6 +12,8 @@ const draft_batch = @import("draft_batch.zig"); const load = @import("load.zig"); const worker = @import("worker.zig"); const snapshot = @import("snapshot.zig"); +const states = @import("lanes_states.zig"); +const ngram = @import("ngram.zig"); const pc = @import("engine_api").prompt_cache; const be = lanes.backend; @@ -19,6 +21,8 @@ const draw = serve.draw; /// Drawn tokens a handle names, newest last. pub const ring = 1024; +/// The kept states' bounce buffer: one copy's chunk of a state. +const bounce_bytes = 32 << 20; /// Drafts the head holds for a stream at most. pub const max_depth = cache.max_window - 1; pub const Fill = struct { @@ -30,6 +34,9 @@ pub const Fill = struct { kept0: u64 = 0, }; +/// A kept row inside a prompt chunk (forward.Mark): its position, the n-gram history there and its side buffer. +pub const Marked = struct { at: usize, history: [2]i64, side: u64 }; + pub const Lane = struct { caches: cache.Caches, /// The head's caches (none on a rank that does not draft). @@ -67,6 +74,12 @@ pub const Fx = struct { /// The kept prompt states (null: no reuse), and the slot the next one takes on every rank. store: ?pc.Store = null, next_slot: u32 = 0, + /// The kept row inside the prompt chunk being saved (forward.Mark): its position, n-gram history and side buffer. + marked: ?Marked = null, + /// The last prompt chunk's keeps, saved as the next step begins: its first token goes out first. + keeps: ?states.Keeps = null, + /// Pinned host memory the kept states' copies pass through (snapshot.Copy), made with the store. + bounce: ?hip.HostBuffer = null, pub fn init(gpa: std.mem.Allocator, e: *Engine, streams: usize) !*Fx { const f = try gpa.create(Fx); @@ -90,7 +103,9 @@ pub const Fx = struct { } pub fn deinit(f: *Fx) void { + f.keeps = null; if (f.store) |*st| st.deinit(); + if (f.bounce) |*b| b.free(); if (f.link != null) f.send(&.{@backingInt(worker.Op.stop)}) catch {}; f.e.stream.synchronize() catch {}; var it = f.lanes.valueIterator(); @@ -109,87 +124,30 @@ pub const Fx = struct { /// Keep prompt states in `budget` host bytes on the prompt kernels' 64-row grid, each a token past its rows. pub fn keepPrompts(f: *Fx, budget: u64) void { if (budget == 0) return; + f.bounce = hip.HostBuffer.alloc(&f.e.driver, bounce_bytes) catch null; // none: the copies pin their pages f.store = pc.Store.init( f.gpa, .{ .ptr = f, - .vtable = &.{ .bytes = snapBytes, .save = snapSave, .restore = snapRestore, .drop = snapDrop }, + .vtable = &.{ .bytes = states.bytes, .save = states.save, .restore = states.restore, .drop = states.drop }, }, .{ .lookahead = 1, .planned = true, .grid = 64 }, budget, ); } - fn snapBytes(ptr: *anyopaque, at: u32) u64 { - const f: *Fx = @ptrCast(@alignCast(ptr)); - var buf: [64]bool = undefined; - const kinds = f.e.kinds(&buf) catch return std.math.maxInt(u64); - const main = cache.Layout.of(f.e.weights.model.dims, kinds, 64, f.e.act).stateBytes(at); - const head = if (f.e.weights.model.mtp) |h| - cache.Layout.of(h.dims, &.{false}, 64, f.e.act).stateBytes(at) - else - 0; - return main + head; - } - - fn snapSave(ptr: *anyopaque, owner: ?*anyopaque, at: u32) anyerror!pc.Saved { - const f = of(ptr); - const lane: *Lane = @ptrCast(@alignCast(owner orelse return error.NoOwner)); - const saved = try snapshot.save( - f.gpa, - &f.e.driver, - f.e.stream, - &lane.caches, - if (lane.head) |*h| h else null, - at, - f.e.cfg.index_ratio, - ); - saved.slot = f.next_slot; - f.next_slot += 1; - if (f.link != null) try f.send(&.{ @backingInt(worker.Op.snap), lane.id, saved.slot, at }); - return saved; + /// How the kept states are copied: through the bounce buffer when there is one. + pub fn copy(f: *Fx) snapshot.Copy { + return .{ .d = &f.e.driver, .bounce = if (f.bounce) |b| b.bytes else &.{} }; } - /// Every rank resumes from the state, or every rank starts the prompt over; a group that cannot do either stops. - fn snapRestore(ptr: *anyopaque, owner: ?*anyopaque, saved: pc.Saved) anyerror!void { - const f = of(ptr); - const lane: *Lane = @ptrCast(@alignCast(owner orelse return error.NoOwner)); - const s: *snapshot.Saved = @ptrCast(@alignCast(saved)); - // a follower that got the step waits for every rank's word on it: a rank 0 that cannot send stops too - if (f.link != null) f.send(&.{ @backingInt(worker.Op.restore), lane.id, s.slot }) catch |err| { - f.e.stopped = true; - return err; - }; - snapshot.restoreAgreed( - f.gpa, - &f.e.driver, - f.e.stream, - s, - &lane.caches, - if (lane.head) |*h| h else null, - f.e.cfg.index_ratio, - f.e.eos, - f.link, - ) catch |err| { - if (err == error.GroupStopped) f.e.stopped = true; - return err; - }; - } - - fn snapDrop(ptr: *anyopaque, saved: pc.Saved) void { - const f: *Fx = @ptrCast(@alignCast(ptr)); - const s: *snapshot.Saved = @ptrCast(@alignCast(saved)); - if (f.link != null) f.send(&.{ @backingInt(worker.Op.drop), s.slot }) catch {}; - snapshot.drop(f.gpa, s); - } - - fn send(f: *Fx, words: []const u32) !void { + pub fn send(f: *Fx, words: []const u32) !void { if (f.e.stopped) return error.GroupStopped; if (f.link) |l| try l.send(words); } pub fn backend(f: *Fx) be.Backend { - return .{ .ptr = f, .vtable = &.{ + return .{ .ptr = f, .first_before_draft = true, .vtable = &.{ .prefill = prefillFn, .prefill_step = prefillStepFn, .first = firstFn, @@ -209,6 +167,12 @@ pub const Fx = struct { return facts_mod.factsFor(cache.max_window, f.streams, f.e.weights.model.mtp != null and f.drafts > 0, f.drafts); } + /// Kept row `i`'s side buffer (forward.Mark): its part of the window snapshots, free while a prompt fills, or null. + fn sideBuffer(c: *const cache.Caches, i: usize) ?u64 { + const at = i * std.mem.alignForward(usize, c.layout.restBytes(), 256); + return if (at + c.layout.restBytes() <= c.window.len) c.window.base() + at else null; + } + fn free(f: *Fx, l: *Lane) void { f.e.stream.synchronize() catch {}; f.e.unlease(l.caches); @@ -218,7 +182,7 @@ pub const Fx = struct { f.gpa.destroy(l); } - fn of(ptr: *anyopaque) *Fx { + pub fn of(ptr: *anyopaque) *Fx { const f: *Fx = @ptrCast(@alignCast(ptr)); if (bound != f.e) { f.e.ctx.makeCurrent() catch |err| std.log.err("hipSetDevice on the lane thread: {s}", .{@errorName(err)}); @@ -320,6 +284,7 @@ pub const Fx = struct { /// One prompt chunk on the 64-row grid; the head absorbs its rows; the last draws the first token. `_: u32`. fn prefillStepFn(ptr: *anyopaque, s: *lanes.Stream, _: u32) anyerror!bool { const f = of(ptr); + states.settle(f); if (s.isCancelled()) return error.Cancelled; const lane = if (f.lanes.get(s)) |l| (if (l.fill != null) l else try f.begin(s)) else try f.begin(s); const e = f.e; @@ -330,7 +295,27 @@ pub const Fx = struct { const stop: usize = if (fill.next < fill.count) fill.stops[fill.next] else prompt.len; // the idle chunk alone, the shorter one while other streams decode between chunks (both on the 64-row grid) const chunk: usize = if (f.decoding(lane)) e.o.policy.fill_rows else e.o.chunk; - const to = @min(stop, at + chunk); + var to = @min(stop, at + chunk); + // the chunk goes on through each kept row its side buffers hold, writing the row's state aside (the same bytes) + var marks: [cache.max_window]forward.Mark = undefined; + var held: [cache.max_window]Marked = undefined; + var n_marks: usize = 0; + var taken = fill.next; // the stops the chunk's marks take, a duplicate's too + if (to == stop and stop > at and stop < prompt.len and f.link == null and f.store != null) { + const end = @min(prompt.len, at + chunk); + var j = fill.next; + while (j < fill.count and fill.stops[j] < end and n_marks < marks.len) : (j += 1) { + const row = fill.stops[j]; + if (n_marks > 0 and row <= held[n_marks - 1].at) continue; // a duplicate: kept once + const side = sideBuffer(&lane.caches, n_marks) orelse break; + marks[n_marks] = .{ .row = row - at, .side = side }; + held[n_marks] = .{ .at = row, .history = ngram.after(lane.caches.history, prompt[at..row]), .side = side }; + n_marks += 1; + } + taken = j; + to = if (j < fill.count and fill.stops[j] < end) fill.stops[j] else end; + } + defer f.marked = null; // a failed chunk's too const last = to == prompt.len; if (f.link != null) { f.msg.clearRetainingCapacity(); @@ -338,7 +323,7 @@ pub const Fx = struct { try f.msg.appendSlice(f.gpa, prompt[at..to]); try f.send(f.msg.items); } - const out = try e.prompt(&lane.caches, prompt[at..to]); + const out = try e.promptMarked(&lane.caches, prompt[at..to], marks[0..n_marks]); const rows = to - at; const row_bytes = m.dims.wide() * m.act.size(); if (lane.head) |*hc| { @@ -350,12 +335,12 @@ pub const Fx = struct { } } fill.at = to; - if (fill.next < fill.count and to == fill.stops[fill.next]) { - if (f.store) |*st| _ = st.keep(prompt, @intCast(to), lane, &.{}, &.{}); - fill.next += 1; - } + fill.next = taken; + const live = fill.next < fill.count and to == fill.stops[fill.next]; + if (live) fill.next += 1; + f.keeps = .{ .lane = lane, .s = s, .marks = held, .n = n_marks, .live = if (live) to else null, .last = last, .from = fill.from, .kept0 = fill.kept0 }; + if (!last or f.link != null) states.settle(f); // the other ranks take each keep in step order if (!last) return false; - if (f.store) |*st| st.report(prompt.len, @intCast(fill.from), st.counts.kept - fill.kept0); try hip.raw.copy(lane.streams, 0, out.streams.ptr + (rows - 1) * row_bytes, row_bytes, e.stream.handle); if (s.grammar != null and lane.first_row == null) lane.first_row = try f.gpa.alloc(u16, e.cfg.vocab); const o = e.ops(&e.arena); @@ -413,6 +398,7 @@ pub const Fx = struct { /// Every window in one forward, each from its stream's kept length; every row drawn at its position. fn verifyFn(ptr: *anyopaque, windows: []const be.Window, out: []be.Verified) anyerror!void { const f = of(ptr); + states.settle(f); const e = f.e; const m = &e.weights.model; if (windows.len > forward.max_segs) return error.WindowTooWide; @@ -486,6 +472,7 @@ pub const Fx = struct { fn keepFn(ptr: *anyopaque, windows: []const be.Window, paths: []const []const u32) anyerror!void { const f = of(ptr); + states.settle(f); for (windows, paths) |w, path| { const lane = f.lanes.get(w.stream) orelse return error.UnknownStream; for (path, 0..) |r, j| if (r != j) return error.TreesNotBuilt; @@ -495,7 +482,9 @@ pub const Fx = struct { /// The head absorbs each stream's kept rows (residual streams and the token after each), then chains its drafts. fn draftFn(ptr: *anyopaque, requests: []const be.DraftRequest) anyerror!void { - try draft_batch.draft(of(ptr), requests); + const f = of(ptr); + states.settle(f); + try draft_batch.draft(f, requests); } fn heldFn(ptr: *anyopaque, s: *lanes.Stream, _: std.mem.Allocator) anyerror!?lanes.stream.Held { @@ -505,19 +494,9 @@ pub const Fx = struct { fn releaseFn(ptr: *anyopaque, s: *lanes.Stream) void { const f = of(ptr); + states.settle(f); const kv = f.lanes.fetchRemove(s) orelse return; if (f.link != null) f.send(&.{ @backingInt(worker.Op.release), kv.value.id }) catch {}; f.free(kv.value); } }; - -test "MTP stays at three: the constant, the cap and the facts never report more" { - try std.testing.expectEqual(@as(u32, 3), facts_mod.mtp_max_drafts); - try std.testing.expectEqual(@as(u32, 3), facts_mod.capDrafts(3)); - try std.testing.expectEqual(@as(u32, 3), facts_mod.capDrafts(7)); - const m = facts_mod.factsFor(cache.max_window, 2, true, facts_mod.capDrafts(7)); - try std.testing.expectEqual(@as(u32, 3), m.drafts); - var cfg = try lanes.Config.init(std.testing.allocator, m, cache.max_window, cache.max_window - 1); - defer cfg.deinit(std.testing.allocator); - try std.testing.expectEqual(@as(u32, 3), cfg.most_drafts); -} diff --git a/zig/src/families/flashnext/hip/lanes_states.zig b/zig/src/families/flashnext/hip/lanes_states.zig new file mode 100644 index 00000000000..296f390aa00 --- /dev/null +++ b/zig/src/families/flashnext/hip/lanes_states.zig @@ -0,0 +1,98 @@ +//! The prompt cache's hooks for Flash Next's lanes: a kept state's bytes, its save, restore and drop on every rank. +const std = @import("std"); +const cache = @import("cache.zig"); +const snapshot = @import("snapshot.zig"); +const worker = @import("worker.zig"); +const lanes = @import("lanes.zig"); +const Stream = @import("lanes").Stream; +const pc = @import("engine_api").prompt_cache; + +const Fx = lanes.Fx; +const Lane = lanes.Lane; + +/// A prompt chunk's kept rows not saved yet: its marks, the row at its end, and the prompt's report after the last. +pub const Keeps = struct { + lane: *Lane, + s: *Stream, + marks: [cache.max_window]lanes.Marked, + n: usize, + live: ?usize, + last: bool, + from: usize, + kept0: u64, +}; + +/// The keeps a prompt chunk left (Fx.keeps) saved, before any step that writes a stream's caches or window. +pub fn settle(f: *Fx) void { + const k = f.keeps orelse return; + f.keeps = null; + if (f.lanes.get(k.s) != k.lane) return; // its stream gone without a release: nothing to save from + const st = if (f.store) |*st| st else return; + const prompt = k.s.prompt(); + for (k.marks[0..k.n]) |mk| { + f.marked = mk; + _ = st.keep(prompt, @intCast(mk.at), k.lane, &.{}, &.{}); + } + f.marked = null; // a kept row at the chunk's end saves the live caches + if (k.live) |at| _ = st.keep(prompt, @intCast(at), k.lane, &.{}, &.{}); + if (k.last) st.report(prompt.len, @intCast(k.from), st.counts.kept - k.kept0); +} + +pub fn bytes(ptr: *anyopaque, at: u32) u64 { + const f: *Fx = @ptrCast(@alignCast(ptr)); + var buf: [64]bool = undefined; + const kinds = f.e.kinds(&buf) catch return std.math.maxInt(u64); + const main = cache.Layout.of(f.e.weights.model.dims, kinds, 64, f.e.act).stateBytes(at); + const head = if (f.e.weights.model.mtp) |h| + cache.Layout.of(h.dims, &.{false}, 64, f.e.act).stateBytes(at) + else + 0; + return main + head; +} + +pub fn save(ptr: *anyopaque, owner: ?*anyopaque, at: u32) anyerror!pc.Saved { + const f = Fx.of(ptr); + const lane: *Lane = @ptrCast(@alignCast(owner orelse return error.NoOwner)); + const head = if (lane.head) |*h| h else null; + const saved = if (f.marked) |mk| if (mk.at == at) + try snapshot.saveMarked(f.gpa, f.copy(), f.e.stream, &lane.caches, head, at, f.e.cfg.index_ratio, mk.side, mk.history) + else + return error.SnapshotNotAtMark else try snapshot.save(f.gpa, f.copy(), f.e.stream, &lane.caches, head, at, f.e.cfg.index_ratio); + saved.slot = f.next_slot; + f.next_slot += 1; + if (f.link != null) try f.send(&.{ @backingInt(worker.Op.snap), lane.id, saved.slot, at }); + return saved; +} + +/// Every rank resumes from the state, or every rank starts the prompt over; a group that cannot do either stops. +pub fn restore(ptr: *anyopaque, owner: ?*anyopaque, saved: pc.Saved) anyerror!void { + const f = Fx.of(ptr); + const lane: *Lane = @ptrCast(@alignCast(owner orelse return error.NoOwner)); + const s: *snapshot.Saved = @ptrCast(@alignCast(saved)); + // a follower that got the step waits for every rank's word on it: a rank 0 that cannot send stops too + if (f.link != null) f.send(&.{ @backingInt(worker.Op.restore), lane.id, s.slot }) catch |err| { + f.e.stopped = true; + return err; + }; + snapshot.restoreAgreed( + f.gpa, + f.copy(), + f.e.stream, + s, + &lane.caches, + if (lane.head) |*h| h else null, + f.e.cfg.index_ratio, + f.e.eos, + f.link, + ) catch |err| { + if (err == error.GroupStopped) f.e.stopped = true; + return err; + }; +} + +pub fn drop(ptr: *anyopaque, saved: pc.Saved) void { + const f: *Fx = @ptrCast(@alignCast(ptr)); + const s: *snapshot.Saved = @ptrCast(@alignCast(saved)); + if (f.link != null) f.send(&.{ @backingInt(worker.Op.drop), s.slot }) catch {}; + snapshot.drop(f.gpa, s); +} diff --git a/zig/src/families/flashnext/hip/load.zig b/zig/src/families/flashnext/hip/load.zig index bc9eec1adf3..bb5843788b5 100644 --- a/zig/src/families/flashnext/hip/load.zig +++ b/zig/src/families/flashnext/hip/load.zig @@ -405,12 +405,22 @@ pub fn load(gpa: Allocator, d: *const hip.Runtime, ck: *core.checkpoint.Checkpoi const head = try l.proj(tensors.lm_head); w.layers = try gpa.alloc(model.Layer, c.layers); var ple: ?model.Ple = null; + // each layer read past the page cache by threads, the next while one uploads; the n-gram tables stay mapped + var direct = core.checkpoint.direct.Layers.init(gpa, ck, try core.checkpoint.loadReaders()); + defer direct.deinit(); for (0..c.layers) |i| { _ = arena.reset(.retain_capacity); var buf: [128]u8 = undefined; + var at: [2][136]u8 = undefined; + const name = try tensors.layer(&buf, i); + if (c.ple[i]) direct.mapped() else try direct.enter( + try std.fmt.bufPrint(&at[0], "{s}.", .{name}), + if (i + 1 < c.layers and !c.ple[i + 1]) try std.fmt.bufPrint(&at[1], "{s}.", .{try tensors.layer(&buf, i + 1)}) else null, + ); w.layers[i] = try l.layer(try tensors.layer(&buf, i), c, try c.kind(i), false); if (c.ple[i]) ple = try l.ple(i); } + direct.mapped(); _ = arena.reset(.retain_capacity); const embed = try l.proj(tensors.embed); if (embed.rows() != c.vocab) return error.UnexpectedShape; // `proj` checks MLX tables alone; a float table is read by id too diff --git a/zig/src/families/flashnext/hip/mixers.zig b/zig/src/families/flashnext/hip/mixers.zig index d1c9207551a..ac438346646 100644 --- a/zig/src/families/flashnext/hip/mixers.zig +++ b/zig/src/families/flashnext/hip/mixers.zig @@ -88,31 +88,16 @@ pub fn linear( const st = g.c.linearAt(index); const conv_bytes = (d.conv - 1) * ch * 4; const next = try o.arena.take(conv_bytes); - try o.l.tf_gdn_prompt_prep( - @ptrFromInt(forward.at(qkv, at_row * ch).ptr), - @backingInt(m.act), - @ptrFromInt(l.conv), - @ptrFromInt(st.conv), - @ptrFromInt(next), - @ptrFromInt(q + at_row * kw * 4), - @ptrFromInt(k + at_row * kw * 4), - @ptrFromInt(v + at_row * vw * 4), - @ptrFromInt(m.qk.q), - @ptrFromInt(m.qk.k), - m.qk.eps, - @intCast(n), - @intCast(kw), - @intCast(vw), - @intCast(d.conv), - @ptrFromInt(forward.at(a, at_row * d.value_heads).ptr), - @ptrFromInt(forward.at(b, at_row * d.value_heads).ptr), - @ptrFromInt(l.a_log), - @ptrFromInt(l.dt_bias), - @ptrFromInt(gate + at_row * d.value_heads * 4), - @ptrFromInt(beta + at_row * d.value_heads * 4), - @intCast(d.value_heads), - o.stream, - ); + // each kept row inside the chunk: the prep to it, its conv state aside, then on (a part's launches each) + var from: usize = 0; + var state = st.conv; + for (g.marks) |mk| { + const side = g.c.sideLinear(mk.side, index).conv; + try gdnPrep(o, m, l, qkv, a, b, q, k, v, gate, beta, at_row + from, mk.row - from, state, side); + from = mk.row; + state = side; + } + try gdnPrep(o, m, l, qkv, a, b, q, k, v, gate, beta, at_row + from, n - from, state, next); if (o.stream != hip.counting) try hip.runtime.check(o.l.r.api.hipMemcpyDtoDAsync(@ptrFromInt(st.conv), @ptrFromInt(next), conv_bytes, o.stream)); at_row += n; } @@ -126,7 +111,16 @@ pub fn linear( const out = mixed + off * ch * 4; const conv_bytes = (d.conv - 1) * ch * 4; const next = try o.arena.take(conv_bytes); - try o.convPrefill(forward.at(qkv, off * ch), l.conv, st.conv, out, next, n, ch, d.conv, null); + // each kept row inside the chunk: the conv to it, its state aside, then on (the sums of chunks split there) + var from: usize = 0; + var state = st.conv; + for (g.marks) |mk| { + const side = g.c.sideLinear(mk.side, index).conv; + try o.convPrefill(forward.at(qkv, (off + from) * ch), l.conv, state, out + from * ch * 4, side, mk.row - from, ch, d.conv, null); + from = mk.row; + state = side; + } + try o.convPrefill(forward.at(qkv, (off + from) * ch), l.conv, state, out + from * ch * 4, next, n - from, ch, d.conv, null); if (o.stream != hip.counting) try hip.runtime.check(o.l.r.api.hipMemcpyDtoDAsync( @ptrFromInt(st.conv), @ptrFromInt(next), @@ -161,6 +155,55 @@ pub fn linear( return recur(o, m, l, segs, index, q, k, v, gate, beta, z, rows, false); } +/// tf_gdn_prompt_prep over `n` rows from `row`: conv from `state` (its next state to `next`), split, q/k norms, gates. +fn gdnPrep( + o: Ops, + m: *const model.Model, + l: model.Linear, + qkv: Tensor, + a: Tensor, + b: Tensor, + q: u64, + k: u64, + v: u64, + gate: u64, + beta: u64, + row: usize, + n: usize, + state: u64, + next: u64, +) !void { + const d = m.dims; + const ch = d.convWidth(); + const kw = d.key_heads * d.key_dim; + const vw = d.value_heads * d.value_dim; + try o.l.tf_gdn_prompt_prep( + @ptrFromInt(forward.at(qkv, row * ch).ptr), + @backingInt(m.act), + @ptrFromInt(l.conv), + @ptrFromInt(state), + @ptrFromInt(next), + @ptrFromInt(q + row * kw * 4), + @ptrFromInt(k + row * kw * 4), + @ptrFromInt(v + row * vw * 4), + @ptrFromInt(m.qk.q), + @ptrFromInt(m.qk.k), + m.qk.eps, + @intCast(n), + @intCast(kw), + @intCast(vw), + @intCast(d.conv), + @ptrFromInt(forward.at(a, row * d.value_heads).ptr), + @ptrFromInt(forward.at(b, row * d.value_heads).ptr), + @ptrFromInt(l.a_log), + @ptrFromInt(l.dt_bias), + @ptrFromInt(gate + row * d.value_heads * 4), + @ptrFromInt(beta + row * d.value_heads * 4), + @intCast(d.value_heads), + o.stream, + ); +} + /// The delta rule a stream at a time (a window's rows each with its state kept aside), the gated norm, the out product. fn recur( o: Ops, @@ -185,15 +228,46 @@ fn recur( for (segs) |g| { const n = g.tokens.len; const snaps: ?u64 = if (window) g.c.snapshot(index, 0).state else null; + var from: usize = 0; + for (g.marks) |mk| { + // each kept row inside the chunk: the rule to it, its state aside, the rule on from there + const st = g.c.linearAt(index).state; + const part = o.arena.mark(); + const p0 = off + from; + try o.gatedDelta( + q + p0 * kw * 4, + k + p0 * kw * 4, + v + p0 * vw * 4, + gate + p0 * d.value_heads * 4, + beta + p0 * d.value_heads * 4, + st, + y + p0 * vw * 4, + mk.row - from, + d.key_heads, + d.value_heads, + d.key_dim, + d.value_dim, + null, + ); + o.arena.release(part); // its scratch: the next launches on the stream run after it + if (o.stream != hip.counting) try hip.runtime.check(o.l.r.api.hipMemcpyDtoDAsync( + @ptrFromInt(g.c.sideLinear(mk.side, index).state), + @ptrFromInt(st), + g.c.layout.state_bytes, + o.stream, + )); + from = mk.row; + } + const r0 = off + from; try o.gatedDelta( - q + off * kw * 4, - k + off * kw * 4, - v + off * vw * 4, - gate + off * d.value_heads * 4, - beta + off * d.value_heads * 4, + q + r0 * kw * 4, + k + r0 * kw * 4, + v + r0 * vw * 4, + gate + r0 * d.value_heads * 4, + beta + r0 * d.value_heads * 4, g.c.linearAt(index).state, - y + off * vw * 4, - n, + y + r0 * vw * 4, + n - from, d.key_heads, d.value_heads, d.key_dim, diff --git a/zig/src/families/flashnext/hip/mtp_drafts_test.zig b/zig/src/families/flashnext/hip/mtp_drafts_test.zig new file mode 100644 index 00000000000..e07da1050d4 --- /dev/null +++ b/zig/src/families/flashnext/hip/mtp_drafts_test.zig @@ -0,0 +1,17 @@ +//! The HIP head's MTP draft cap: the window's seven at most, the policy's default three. +const std = @import("std"); +const hip = @import("hip"); +const lanes = @import("lanes"); +const cache = @import("cache.zig"); +const facts_mod = @import("facts.zig"); + +test "MTP drafts reach the window's seven, and the policy's default stays three" { + try std.testing.expectEqual(@as(u32, 7), facts_mod.mtp_max_drafts); + try std.testing.expectEqual(@as(u32, 3), facts_mod.capDrafts((hip.Policy{}).mtp.drafts)); + try std.testing.expectEqual(@as(u32, 7), facts_mod.capDrafts(200)); + const m = facts_mod.factsFor(cache.max_window, 2, true, facts_mod.capDrafts(7)); + try std.testing.expectEqual(@as(u32, 7), m.drafts); + var cfg = try lanes.Config.init(std.testing.allocator, m, cache.max_window, cache.max_window - 1); + defer cfg.deinit(std.testing.allocator); + try std.testing.expectEqual(@as(u32, 7), cfg.most_drafts); +} diff --git a/zig/src/families/flashnext/hip/native.zig b/zig/src/families/flashnext/hip/native.zig index f326204c4ec..895f23a2405 100644 --- a/zig/src/families/flashnext/hip/native.zig +++ b/zig/src/families/flashnext/hip/native.zig @@ -12,6 +12,8 @@ const lanes_mod = @import("lanes.zig"); const worker = @import("worker.zig"); pub const model_type = "qwen4_exp"; +/// Most MTP drafts `--mtp-drafts` may ask of the head. +pub const mtp_max_drafts = @import("facts.zig").mtp_max_drafts; /// The MLX affine checkpoints the plan admits; the HIP products read 2- to 8-bit codes in groups of 32 to 128. pub const formats: []const []const u8 = &.{ "mlx-q3g32", "mlx-q4g32", "mlx-q6g32" }; /// Positions a stream holds when neither --context nor the checkpoint's config names a window. @@ -136,7 +138,7 @@ fn engineOf( } /// One rank's engine at the window every rank took, and the streams every rank's memory holds. -const Prepared = struct { e: *Engine, window: usize, fit: usize, per: usize, room: u64 }; +const Prepared = struct { e: *Engine, window: usize, fit: usize, per: usize, room: u64, shared: bool = false }; /// Every rank, in steps over the link: rank 0's window, this rank's admission and engine, then the streams that fit. fn prepare( @@ -186,7 +188,8 @@ fn prepare( "lower --context or add ranks (--tp)", .{ mine.window, gibs(per), gibs(room) }, ); - return .{ .e = e, .window = mine.window, .fit = fit, .per = per, .room = room }; + const shared = hip.admission.sharesHost(gpa, io, e.ctx); + return .{ .e = e, .window = mine.window, .fit = fit, .per = per, .room = room, .shared = shared }; } const Owned = struct { @@ -210,14 +213,37 @@ const Owned = struct { } }; +/// The prompt cache's bytes: the flag's, else 16 GiB; on shared pages no more than the room the streams leave. +fn promptCacheBytes(flag: ?f64, shared: bool, room: u64, streams: u64) u64 { + if (flag) |g| return @intFromFloat(g * (1 << 30)); + const most: u64 = 16 << 30; + return if (shared) @min(most, room -| streams) else most; +} + +test promptCacheBytes { + const g: u64 = 1 << 30; + // a card: host RAM is apart + try std.testing.expectEqual(@as(u64, 16 * g), promptCacheBytes(null, false, 20 * g, 16 * g)); + // shared: what the streams leave + try std.testing.expectEqual(@as(u64, 4 * g), promptCacheBytes(null, true, 20 * g, 16 * g)); + // shared, roomy: the default + try std.testing.expectEqual(@as(u64, 16 * g), promptCacheBytes(null, true, 40 * g, 8 * g)); + // nothing left: no cache + try std.testing.expectEqual(@as(u64, 0), promptCacheBytes(null, true, 16 * g, 16 * g)); + // the flag wins + try std.testing.expectEqual(@as(u64, 12 * g), promptCacheBytes(12.0, true, 16 * g, 16 * g)); +} + /// Rank 0's lanes over `p.e` for `streams` streams, with the server's startup line. fn lanesOf(gpa: std.mem.Allocator, dev: hip.Device, o: anytype, p: Prepared, streams: usize) !*Owned { const own = try gpa.create(Owned); errdefer gpa.destroy(own); const fx = try lanes_mod.Fx.init(gpa, p.e, streams); errdefer fx.deinit(); - // kept prompt states live in host memory: --prompt-cache-gib, else 16 GiB - fx.keepPrompts(@intFromFloat((o.cache_gib orelse 16.0) * (1 << 30))); + // the first stream's caches at load: a first prompt otherwise waits on allocating and clearing them + try p.e.makeFirstSlot(); + // kept prompt states live in host memory: --prompt-cache-gib, else 16 GiB (on shared pages, what the streams leave) + fx.keepPrompts(promptCacheBytes(o.cache_gib, p.shared, p.room, p.per * streams)); var why: [96]u8 = undefined; const narrowed = if (p.e.narrowed) |n| std.fmt.bufPrint(&why, " ({d}-row chunks would admit fewer of the streams asked for)", .{n}) catch "" diff --git a/zig/src/families/flashnext/hip/snapshot.zig b/zig/src/families/flashnext/hip/snapshot.zig index 7ca80f10e3f..d5b9492330c 100644 --- a/zig/src/families/flashnext/hip/snapshot.zig +++ b/zig/src/families/flashnext/hip/snapshot.zig @@ -1,8 +1,48 @@ //! A stream's state after its first `at` prompt tokens, copied to host memory and back: the prompt cache's entries. const std = @import("std"); +const builtin = @import("builtin"); const hip = @import("hip"); const cache = @import("cache.zig"); +/// The device and the pinned memory a state's copies pass through (empty: none, a big copy pins the pages it reads). +pub const Copy = struct { d: *const hip.Runtime, bounce: []u8 = &.{} }; + +/// `dst.len` bytes from device address `src`, through the bounce buffer when there is one. +fn down(x: Copy, dst: []u8, src: u64) !void { + if (x.bounce.len == 0) return hip.runtime.check(x.d.api.hipMemcpyDtoH(dst.ptr, @ptrFromInt(src), dst.len)); + var k: usize = 0; + while (k < dst.len) : (k += x.bounce.len) { + const n = @min(x.bounce.len, dst.len - k); + try hip.runtime.check(x.d.api.hipMemcpyDtoH(x.bounce.ptr, @ptrFromInt(src + k), n)); + @memcpy(dst[k..][0..n], x.bounce[0..n]); + } +} + +/// `src` to device address `dst`, through the bounce buffer when there is one. +fn up(x: Copy, dst: u64, src: []const u8) !void { + if (x.bounce.len == 0) return hip.runtime.check(x.d.api.hipMemcpyHtoD(@ptrFromInt(dst), @constCast(src.ptr), src.len)); + var k: usize = 0; + while (k < src.len) : (k += x.bounce.len) { + const n = @min(x.bounce.len, src.len - k); + @memcpy(x.bounce[0..n], src[k..][0..n]); + try hip.runtime.check(x.d.api.hipMemcpyHtoD(@ptrFromInt(dst + k), x.bounce.ptr, n)); + } +} + +/// A kept state's bytes on small pages of their own (Linux): a huge-page fault per state compacted under the kernels. +fn take(n: usize, gpa: std.mem.Allocator) ![]u8 { + if (comptime builtin.os.tag != .linux) return gpa.alloc(u8, n); + if (n == 0) return &.{}; + const m = try std.posix.mmap(null, n, .{ .READ = true, .WRITE = true }, .{ .TYPE = .PRIVATE, .ANONYMOUS = true }, -1, 0); + _ = std.os.linux.madvise(m.ptr, m.len, std.os.linux.MADV.NOHUGEPAGE); + return m; +} + +fn give(b: []u8, gpa: std.mem.Allocator) void { + if (comptime builtin.os.tag != .linux) return gpa.free(b); + if (b.len > 0) std.posix.munmap(@alignCast(b)); +} + /// One span of a cache's device memory a state at `at` holds. const Region = struct { offset: usize, len: usize }; @@ -38,28 +78,26 @@ pub const Saved = struct { } }; -fn copyOut(d: *const hip.Runtime, c: *const cache.Caches, at: usize, ratio: usize, gpa: std.mem.Allocator) ![]u8 { +/// `side`: the part past the sparse layers (the last region) from a side buffer instead (forward.Mark). +fn copyOut(x: Copy, c: *const cache.Caches, at: usize, ratio: usize, side: ?u64, gpa: std.mem.Allocator) ![]u8 { var list: std.ArrayList(Region) = .empty; defer list.deinit(gpa); try regions(c, at, ratio, &list, gpa); var n: usize = 0; for (list.items) |r| n += r.len; - const out = try gpa.alloc(u8, n); - errdefer gpa.free(out); + const out = try take(n, gpa); + errdefer give(out, gpa); var off: usize = 0; - for (list.items) |r| { - if (r.len > 0) try hip.runtime.check(d.api.hipMemcpyDtoH( - out[off..].ptr, - @ptrFromInt(c.mem.base() + r.offset), - r.len, - )); + for (list.items, 0..) |r, i| { + const src = if (side != null and i + 1 == list.items.len) side.? else c.mem.base() + r.offset; + if (r.len > 0) try down(x, out[off..][0..r.len], src); off += r.len; } return out; } fn copyIn( - d: *const hip.Runtime, + x: Copy, c: *const cache.Caches, at: usize, ratio: usize, @@ -72,11 +110,7 @@ fn copyIn( var off: usize = 0; for (list.items) |r| { if (off + r.len > bytes.len) return error.SnapshotMismatch; - if (r.len > 0) try hip.runtime.check(d.api.hipMemcpyHtoD( - @ptrFromInt(c.mem.base() + r.offset), - @constCast(bytes[off..].ptr), - r.len, - )); + if (r.len > 0) try up(x, c.mem.base() + r.offset, bytes[off..][0..r.len]); off += r.len; } if (off != bytes.len) return error.SnapshotMismatch; @@ -85,7 +119,7 @@ fn copyIn( /// The state of `c` (and the head's `head`) after `at` prompt tokens, copied to host memory; the stream is idle. pub fn save( gpa: std.mem.Allocator, - d: *const hip.Runtime, + x: Copy, s: hip.Stream, c: *const cache.Caches, head: ?*const cache.Caches, @@ -94,19 +128,50 @@ pub fn save( ) !*Saved { try s.synchronize(); if (c.len != at) return error.SnapshotNotAtMark; + return saveFrom(gpa, x, c, head, at, ratio, null, c.pooled, c.history); +} + +/// The state at `at` inside the last prompt chunk (forward.Mark): rows below it from the caches, the rest from `side`. +pub fn saveMarked( + gpa: std.mem.Allocator, + x: Copy, + s: hip.Stream, + c: *const cache.Caches, + head: ?*const cache.Caches, + at: usize, + ratio: usize, + side: u64, + history: [2]i64, +) !*Saved { + try s.synchronize(); + if (c.len <= at) return error.SnapshotNotAtMark; + return saveFrom(gpa, x, c, head, at, ratio, side, at / ratio, history); +} + +fn saveFrom( + gpa: std.mem.Allocator, + x: Copy, + c: *const cache.Caches, + head: ?*const cache.Caches, + at: usize, + ratio: usize, + side: ?u64, + pooled: usize, + history: [2]i64, +) !*Saved { const out = try gpa.create(Saved); errdefer gpa.destroy(out); - const main = try copyOut(d, c, at, ratio, gpa); - errdefer gpa.free(main); - const h: []u8 = if (head) |x| try copyOut(d, x, at, ratio, gpa) else &.{}; - out.* = .{ .at = @intCast(at), .pooled = c.pooled, .history = c.history, .main = main, .head = h }; + const main = try copyOut(x, c, at, ratio, side, gpa); + errdefer give(main, gpa); + const h: []u8 = if (head) |hc| try copyOut(x, hc, at, ratio, null, gpa) else &.{}; + out.* = .{ .at = @intCast(at), .pooled = pooled, .history = history, .main = main, .head = h }; return out; } /// `saved` made the live state of `c` and `head`, or a failure part way through that leaves either changed. fn restore( gpa: std.mem.Allocator, - d: *const hip.Runtime, + x: Copy, s: hip.Stream, saved: *const Saved, c: *cache.Caches, @@ -115,8 +180,8 @@ fn restore( ) !void { try s.synchronize(); if (saved.at + 1 > c.layout.cap) return error.SnapshotTooLong; - try copyIn(d, c, saved.at, ratio, saved.main, gpa); - if (head) |h| try copyIn(d, h, saved.at, ratio, saved.head, gpa); + try copyIn(x, c, saved.at, ratio, saved.main, gpa); + if (head) |h| try copyIn(x, h, saved.at, ratio, saved.head, gpa); c.len = saved.at; c.pooled = saved.pooled; c.history = saved.history; @@ -129,7 +194,7 @@ fn restore( /// `saved` (null: no copy here) restored on every rank or none: all resume from it, or all start over (RestoreRefused). pub fn restoreAgreed( gpa: std.mem.Allocator, - d: *const hip.Runtime, + x: Copy, s: hip.Stream, saved: ?*const Saved, c: *cache.Caches, @@ -138,7 +203,7 @@ pub fn restoreAgreed( eos: i64, link: ?hip.collective.Link, ) !void { - const mine = if (saved) |x| restore(gpa, d, s, x, c, head, ratio) else error.UnknownSnapshot; + const mine = if (saved) |v| restore(gpa, x, s, v, c, head, ratio) else error.UnknownSnapshot; if (hip.collective.everyRank(link, mine)) return; // a part-restored rank, and every rank that restored beside one that failed, starts the prompt over from zero if (!hip.collective.everyRank(link, fresh(s, c, head, eos))) return error.GroupStopped; @@ -153,7 +218,7 @@ fn fresh(s: hip.Stream, c: *cache.Caches, head: ?*cache.Caches, eos: i64) !void } pub fn drop(gpa: std.mem.Allocator, saved: *Saved) void { - gpa.free(saved.main); - if (saved.head.len > 0) gpa.free(saved.head); + give(saved.main, gpa); + give(saved.head, gpa); gpa.destroy(saved); } diff --git a/zig/src/families/flashnext/hip/state_test.zig b/zig/src/families/flashnext/hip/state_test.zig index 2d907ee4850..0169a369046 100644 --- a/zig/src/families/flashnext/hip/state_test.zig +++ b/zig/src/families/flashnext/hip/state_test.zig @@ -120,7 +120,7 @@ const Saved = struct { main.history = .{ 5, 6 }; head.len = at; const s: hip.Stream = .{ .r = r, .handle = null }; - const copy = try snapshot.save(std.testing.allocator, r, s, &main, &head, at, ratio); + const copy = try snapshot.save(std.testing.allocator, .{ .d = r }, s, &main, &head, at, ratio); return .{ .main = main, .head = head, .copy = copy }; } @@ -163,7 +163,7 @@ test "a lone rank's restore that fails at any copy or allocation leaves fresh ca defer head.deinit(std.testing.allocator); Host.copies = k; defer Host.copies = null; - snapshot.restoreAgreed(std.testing.allocator, &r, s, src.copy, &main, &head, ratio, eos, null) catch |err| { + snapshot.restoreAgreed(std.testing.allocator, .{ .d = &r }, s, src.copy, &main, &head, ratio, eos, null) catch |err| { try std.testing.expectEqual(error.RestoreRefused, err); try expectFresh(&main); try expectFresh(&head); @@ -185,7 +185,7 @@ test "a lone rank's restore that fails at any copy or allocation leaves fresh ca var head = try caches(&r); defer head.deinit(std.testing.allocator); const a = failing.allocator(); - snapshot.restoreAgreed(a, &r, s, src.copy, &main, &head, ratio, eos, null) catch { + snapshot.restoreAgreed(a, .{ .d = &r }, s, src.copy, &main, &head, ratio, eos, null) catch { try expectFresh(&main); try expectFresh(&head); continue; @@ -207,7 +207,7 @@ test "a lone rank whose caches cannot be made fresh after a failed restore stops Host.fail_fill = true; defer Host.fail_fill = false; defer Host.copies = null; - const got = snapshot.restoreAgreed(std.testing.allocator, &r, s, src.copy, &main, null, ratio, eos, null); + const got = snapshot.restoreAgreed(std.testing.allocator, .{ .d = &r }, s, src.copy, &main, null, ratio, eos, null); try std.testing.expectError(error.GroupStopped, got); } @@ -243,7 +243,7 @@ const Pair = struct { defer Host.fail_fill = false; const copy: ?*const snapshot.Saved = if (mine and p.fails == .missing) null else src.copy; const h: ?*cache.Caches = if (i == 0) &head else null; - snapshot.restoreAgreed(std.testing.allocator, &r, s, copy, &main, h, ratio, eos, l) catch |err| { + snapshot.restoreAgreed(std.testing.allocator, .{ .d = &r }, s, copy, &main, h, ratio, eos, l) catch |err| { p.got[i] = err; if (err == error.GroupStopped) return; expectFresh(&main) catch return; @@ -340,3 +340,23 @@ test "a round's graph is chosen for the pool's caches only: caches made elsewher try std.testing.expectEqual(engine.Pick.capture, try e.choose(&.{.{ .c = &c, .tokens = &step, .pos = 0 }})); e.pool.unlease(c); } + +test "a state copied through a bounce buffer smaller than its spans is the direct copy's bytes, and restores alike" { + var r = Host.runtime(); + const s: hip.Stream = .{ .r = &r, .handle = null }; + var src = try Saved.init(&r, 9); + defer src.deinit(); + var bounce: [1000]u8 = undefined; // no span a whole number of it + const through: snapshot.Copy = .{ .d = &r, .bounce = &bounce }; + const copy = try snapshot.save(std.testing.allocator, through, s, &src.main, &src.head, at, ratio); + defer snapshot.drop(std.testing.allocator, copy); + try std.testing.expectEqualSlices(u8, src.copy.main, copy.main); + try std.testing.expectEqualSlices(u8, src.copy.head, copy.head); + var main = try caches(&r); + defer main.deinit(std.testing.allocator); + var head = try caches(&r); + defer head.deinit(std.testing.allocator); + try snapshot.restoreAgreed(std.testing.allocator, through, s, copy, &main, &head, ratio, eos, null); + try expectRestored(&main, &src.main); + try expectRestored(&head, &src.head); +} diff --git a/zig/src/families/flashnext/hip/tables.zig b/zig/src/families/flashnext/hip/tables.zig index b4bc3aa6302..3e803543c4a 100644 --- a/zig/src/families/flashnext/hip/tables.zig +++ b/zig/src/families/flashnext/hip/tables.zig @@ -15,8 +15,8 @@ pub const Shard = struct { words: []const u8, scales: []const u8, biases: []cons /// A gather copies the checkpoint's rows in id order: a staging too small, or a row past the last shard. const Error = error{ StagingTooSmall, NgramRowOutOfRange }; -/// Parts a gather spreads over at most, and rows a part takes before the gather stops adding parts. -const max_parts = 32; +/// Parts a gather spreads over at most (all the pool's: its page reads wait together), and rows a part takes first. +const max_parts = pool.max_parts; const rows_per_part = 2; /// The shards' rows as mapped: what a gather reads, apart from the hasher that names the rows. diff --git a/zig/src/families/flashnext/hip/worker.zig b/zig/src/families/flashnext/hip/worker.zig index f28c49fd4c4..5d9ddf1222f 100644 --- a/zig/src/families/flashnext/hip/worker.zig +++ b/zig/src/families/flashnext/hip/worker.zig @@ -110,7 +110,7 @@ pub fn follow(gpa: std.mem.Allocator, e: *Engine, link: hip.collective.Link) !vo .snap => { const lane = lanes.get(w[1]) orelse return error.UnknownStream; // a copy this rank cannot keep is a restore it refuses later, which every rank then hears - const x = snapshot.save(gpa, &e.driver, e.stream, &lane.caches, null, w[3], ratio) catch continue; + const x = snapshot.save(gpa, .{ .d = &e.driver }, e.stream, &lane.caches, null, w[3], ratio) catch continue; saved.put(gpa, w[2], x) catch snapshot.drop(gpa, x); }, .restore => { @@ -118,7 +118,7 @@ pub fn follow(gpa: std.mem.Allocator, e: *Engine, link: hip.collective.Link) !vo // every rank resumes from the state, or every rank starts the prompt over snapshot.restoreAgreed( gpa, - &e.driver, + .{ .d = &e.driver }, e.stream, saved.get(w[2]), &lane.caches, diff --git a/zig/src/families/flashnext/prefill.zig b/zig/src/families/flashnext/prefill.zig index 53c12224f8c..32cefbb7c03 100644 --- a/zig/src/families/flashnext/prefill.zig +++ b/zig/src/families/flashnext/prefill.zig @@ -43,7 +43,10 @@ pub fn start(b: anytype, s: *Stream, slot: ?usize) !void { /// A nonzero `max_rows` caps the call in place of `besideRows`; only a prefill policy sends this family one. pub fn step(b: anytype, s: *Stream, max_rows: u32) !bool { errdefer b.abortPrompt(s); - if (s.isCancelled()) return error.Cancelled; + if (s.isCancelled()) { + try cancel(b, s); + return error.Cancelled; + } if (!b.filling.contains(s)) try start(b, s, null); var p = b.filling.get(s).?; const prompt = s.prompt(); @@ -70,7 +73,7 @@ pub fn step(b: anytype, s: *Stream, max_rows: u32) !bool { const entry = b.filling.getPtr(s) orelse return error.PromptOutOfStep; entry.* = p; s.fill_at.store(p.at, .monotonic); - if (std.mem.indexOfScalar(u32, s.reuse.marks, p.at) != null) try b.markPrompt(s, p.at); + if (std.mem.indexOfScalar(u32, s.reuse.marks, p.at) != null) try b.markPrompt(s, p.at, false); } if (p.at < prompt.len) return false; try b.finishPrompt(s); @@ -78,6 +81,15 @@ pub fn step(b: anytype, s: *Stream, max_rows: u32) !bool { return true; } +/// Retain only the completed prompt cursor while its recurrent and head state still belong to this session. +pub fn cancel(b: anytype, s: *Stream) !void { + const p = b.filling.get(s) orelse return; + if (p.at <= s.cached or p.at >= s.prompt_len) return; + if (std.mem.indexOfScalar(u32, s.chunks, p.at) == null) return; // this planned family resumes only canonical cuts + try b.settlePrompt(s); + try b.markPrompt(s, p.at, true); +} + // True means the prompt completed; false hands its unfinished cursor to the shared host after a completed call. pub fn lone(b: anytype, s: *Stream, hooks: anytype) !bool { try start(b, s, 0); @@ -90,6 +102,12 @@ pub fn lone(b: anytype, s: *Stream, hooks: anytype) !bool { // Both actual vtable entries use this driver; host controls replace only its engine boundary. pub fn Callbacks(comptime B: type) type { return struct { + pub fn cancelPrompt(ptr: *anyopaque, s: *Stream) anyerror!void { + const b = B.self(ptr); + const pool = b.promptPool(); + defer pool.pop(); + try cancel(b, s); + } pub fn whole(ptr: *anyopaque, s: *Stream) anyerror!void { const b = B.self(ptr); const pool = b.promptPool(); @@ -143,3 +161,35 @@ test "flashnext prefill: prompt head pairs cover P minus one across odd seams an try std.testing.expectEqual(@as(usize, 0), (try piece(0, 1, 1, 0, 1)).head_rows); try std.testing.expectError(error.ChunkOutOfStep, piece(1, 1, 1, 0, 1)); } + +test "flashnext prefill: cancellation preserves the last canonical mark instead of saving an unusable cut" { + const Fake = @import("prefill_test_engine.zig").Fake; + const Kept = struct { + at: u32 = 0, + fn hit(ptr: *anyopaque, _: *Stream, at: u32) void { + const k: *@This() = @ptrCast(@alignCast(ptr)); + k.at = at; + } + }; + const Cancel = struct { + fn yes(_: *anyopaque) bool { + return true; + } + }; + const a = std.testing.allocator; + const ids: [13]u32 = @splat(7); + var f: Fake = .{}; + defer f.deinit(); + var kept: Kept = .{}; + var s = try Stream.init(a, .{ .id = "canonical-cancel", .prompt = &ids, .max_new = 4 }); + defer s.deinit(a); + s.chunks = &.{ 4, 8, 12 }; + s.reuse.marks = &.{4}; + s.reuse.hook = .{ .ptr = &kept, .at = Kept.hit, .interrupted = Kept.hit }; + for (0..5) |_| try std.testing.expect(!try step(&f, &s, 1)); + try std.testing.expectEqual(@as(u32, 4), kept.at); + s.cancel_check = .{ .ptr = &kept, .check = Cancel.yes }; + try std.testing.expectError(error.Cancelled, step(&f, &s, 1)); + try std.testing.expectEqual(@as(u32, 4), kept.at); + try std.testing.expect(!f.filling.contains(&s)); +} diff --git a/zig/src/families/flashnext/prefill_metal.zig b/zig/src/families/flashnext/prefill_metal.zig index a705a3d2d69..47237d7dd18 100644 --- a/zig/src/families/flashnext/prefill_metal.zig +++ b/zig/src/families/flashnext/prefill_metal.zig @@ -98,13 +98,13 @@ pub fn chunk(b: anytype, stream: *lanes.Stream, i: usize, at: u32, n: u32) !void } } -pub fn mark(b: anytype, stream: *lanes.Stream, at: u32) !void { +pub fn mark(b: anytype, stream: *lanes.Stream, at: u32, interrupted: bool) !void { const i = b.by.get(stream) orelse return error.UnknownStream; const s = &b.sessions[i]; const old = try b.bind(s); defer old.restore(b.e); b.outputs(s, 0); - if (stream.reuse.hook) |hook| hook.at(hook.ptr, stream, at); + if (interrupted) stream.keepInterruptedPrefill(at) else if (stream.reuse.hook) |hook| hook.at(hook.ptr, stream, at); } fn dropImages(b: anytype, resource: ?*anyopaque) void { diff --git a/zig/src/families/flashnext/prefill_test.zig b/zig/src/families/flashnext/prefill_test.zig index f162dec038c..d3e798e105e 100644 --- a/zig/src/families/flashnext/prefill_test.zig +++ b/zig/src/families/flashnext/prefill_test.zig @@ -8,6 +8,7 @@ test "flashnext prefill: actual backend advertises completed prompt steps" { const callbacks = @import("prefill.zig").Callbacks(Backend); try std.testing.expect(b.backend().vtable.prefill_step == callbacks.one); try std.testing.expect(b.backend().vtable.prefill == callbacks.whole); + try std.testing.expect(b.backend().vtable.cancel_prefill != null); try std.testing.expect(b.backend().vtable.reports_fill); // the status page's totals and srpt's row time read it } else return error.SkipZigTest; } @@ -148,6 +149,18 @@ test "flashnext prefill: cancellation at every seam frees its owner without affe return c.stopped; } }; + const Kept = struct { + at: ?u32 = null, + normal: usize = 0, + fn hit(ptr: *anyopaque, _: *lanes.Stream, at: u32) void { + const k: *@This() = @ptrCast(@alignCast(ptr)); + k.at = at; + } + fn ordinary(ptr: *anyopaque, _: *lanes.Stream, _: u32) void { + const k: *@This() = @ptrCast(@alignCast(ptr)); + k.normal += 1; + } + }; const tokens: [33]u32 = @splat(5); for (0..4) |seam| { var f: Fake = .{}; @@ -157,6 +170,8 @@ test "flashnext prefill: cancellation at every seam frees its owner without affe defer s.deinit(a); s.chunks = &.{ 1, 7, 17, 32 }; s.cancel_check = .{ .ptr = &c, .check = Cancel.check }; + var kept: Kept = .{}; + s.reuse.hook = .{ .ptr = &kept, .at = Kept.ordinary, .interrupted = Kept.hit }; var other = try stream(&tokens, "survivor"); defer other.deinit(a); other.chunks = &.{17}; @@ -165,6 +180,8 @@ test "flashnext prefill: cancellation at every seam frees its owner without affe const before = s.fill_at.load(.monotonic); c.stopped = true; try std.testing.expectError(error.Cancelled, fill.step(&f, &s, 0)); + try std.testing.expectEqual(if (before == 0) @as(?u32, null) else before, kept.at); + try std.testing.expectEqual(@as(usize, 0), kept.normal); try std.testing.expectEqual(before, s.fill_at.load(.monotonic)); try std.testing.expectEqual(@as(u32, 17), other.fill_at.load(.monotonic)); try std.testing.expect(!f.filling.contains(&s)); diff --git a/zig/src/families/flashnext/prefill_test_engine.zig b/zig/src/families/flashnext/prefill_test_engine.zig index 6083334418b..d16e44d6c26 100644 --- a/zig/src/families/flashnext/prefill_test_engine.zig +++ b/zig/src/families/flashnext/prefill_test_engine.zig @@ -94,6 +94,7 @@ pub const Fake = struct { f.table = b.vtable.*; f.table.prefill = fill.Callbacks(Fake).whole; f.table.prefill_step = if (stepped) fill.Callbacks(Fake).one else null; + f.table.cancel_prefill = fill.Callbacks(Fake).cancelPrompt; f.table.release = release; f.table.verify = verify; f.table.keep = keep; @@ -219,11 +220,12 @@ pub const Fake = struct { if (o.pairs.items.len != @min(end, s.prompt_len - 1)) return error.LostPromptLookahead; o.normalized = true; } - pub fn markPrompt(f: *Fake, s: *Stream, at: u32) !void { + pub fn markPrompt(f: *Fake, s: *Stream, at: u32, interrupted: bool) !void { + if (interrupted) f.bound = s; if (f.fail_mark) return error.MarkFailed; if (f.bound != s or !f.owner(s).normalized) return error.WrongSession; if (f.target.lanes.get(s).?.history.items.len != at) return error.PositionMismatch; - if (s.reuse.hook) |hook| hook.at(hook.ptr, s, at); + if (interrupted) s.keepInterruptedPrefill(at) else if (s.reuse.hook) |hook| hook.at(hook.ptr, s, at); } pub fn finishPrompt(f: *Fake, s: *Stream) !void { const o = f.owner(s); diff --git a/zig/src/families/flashnext/xpu_engine.zig b/zig/src/families/flashnext/xpu_engine.zig index 265a00bb8f4..cc46ab9b2ff 100644 --- a/zig/src/families/flashnext/xpu_engine.zig +++ b/zig/src/families/flashnext/xpu_engine.zig @@ -23,6 +23,10 @@ pub const Options = struct { context: usize = 16384, tp: usize = 4, mtp: bool = true, + busy_rows: u32 = ld.chunk_rows, + solo_rows: u32 = ld.default_solo_rows, + mtp_drafts: u32 = 6, + mtp_conf: f64 = -0.4, }; pub const Engine = struct { @@ -32,6 +36,10 @@ pub const Engine = struct { gpa: std.mem.Allocator, r: *fwd.Runner, max_len: usize, + busy_rows: u32, + solo_rows: u32, + mtp_drafts: u32, + mtp_conf: f64, load_seconds: f64, head: ?u8 = null, own: fwd.Seq = undefined, @@ -42,11 +50,16 @@ pub const Engine = struct { const t0 = nowSec(); const e = try gpa.create(Engine); errdefer gpa.destroy(e); - const runner = try fwd.Runner.initTp(gpa, io, dir, o.context, o.tp, o.mtp); + const cap_in = @max(@as(usize, o.busy_rows), @as(usize, o.solo_rows)); + const runner = try fwd.Runner.initTp(gpa, io, dir, o.context, o.tp, o.mtp, cap_in); e.* = .{ .gpa = gpa, .r = runner, .max_len = o.context, + .busy_rows = @intCast(@min(@max(@as(usize, o.busy_rows), 1), runner.chunk_cap)), + .solo_rows = @intCast(@min(@max(@as(usize, o.solo_rows), 1), runner.chunk_cap)), + .mtp_drafts = @min(@max(o.mtp_drafts, 1), 15), + .mtp_conf = o.mtp_conf, .load_seconds = nowSec() - t0, .head = if (runner.has_mtp) 1 else null, .own = runner.own, @@ -58,6 +71,10 @@ pub const Engine = struct { return e; } + pub fn maxDrafts(e: *const Engine) u32 { + return e.mtp_drafts; + } + pub fn deinit(e: *Engine) void { const gpa = e.gpa; e.r.own = e.own; @@ -165,7 +182,7 @@ pub const Engine = struct { } pub fn prefillWindows(e: *Engine, head_ids: []const u32, rows: u32) !void { - const step = @min(@as(usize, @max(rows, 1)), ld.chunk_rows); + const step = @min(@as(usize, @max(rows, 1)), e.r.chunk_cap); var t: usize = 0; while (t < head_ids.len) { const n = @min(step, head_ids.len - t); @@ -177,7 +194,7 @@ pub const Engine = struct { pub fn prefillSpan(e: *Engine, prompt: []const u32, from: usize, to: usize, rows: u32) !void { if (e.m.pos != from) return error.PositionMismatch; - const step = @min(@as(usize, @max(rows, 1)), ld.chunk_rows); + const step = @min(@as(usize, @max(rows, 1)), e.r.chunk_cap); var save_dsts: [ld.max_tp]*anyopaque = undefined; for (0..e.r.tp) |rk| save_dsts[rk] = e.r.acts[rk].prompt_streams; @@ -195,31 +212,65 @@ pub const Engine = struct { } } - pub fn draftFirst(e: *Engine, first: u32, depth: u32, out: []u32) !usize { + pub fn draftFirstProbs(e: *Engine, first: u32, depth: u32, out: []u32, probs: []f64) !usize { var st: [ld.max_tp]*anyopaque = undefined; for (0..e.r.tp) |rk| st[rk] = e.r.cur.ranks[rk].last_streams; - const pk = try e.r.forwardMtp(&.{first}, st, e.m.pos - 1, true, depth > 0); - return e.chainDrafts(pk, depth, out); + const pk = try e.r.forwardMtp(&.{first}, st, e.m.pos - 1, depth > 0, depth > 0); + return e.chainDraftsProbs(pk, depth, out, probs); } - pub fn draftKept(e: *Engine, follow: []const u32, start: u32, depth: u32, out: []u32) !usize { + pub fn draftKeptProbs(e: *Engine, follow: []const u32, start: u32, depth: u32, out: []u32, probs: []f64) !usize { var st: [ld.max_tp]*anyopaque = undefined; for (0..e.r.tp) |rk| st[rk] = e.r.cur.ranks[rk].verify_streams; - const pk = try e.r.forwardMtp(follow, st, start, true, depth > 0); - return e.chainDrafts(pk, depth, out); + const pk = try e.r.forwardMtp(follow, st, start, depth > 0, depth > 0); + return e.chainDraftsProbs(pk, depth, out, probs); + } + + pub fn draftFirst(e: *Engine, first: u32, depth: u32, out: []u32) !usize { + var probs: [16]f64 = undefined; + return e.draftFirstProbs(first, depth, out, &probs); } - fn chainDrafts(e: *Engine, first: ?fwd.Runner.MtpPick, depth: u32, out: []u32) !usize { - if (depth == 0) return 0; - const n = @min(@as(usize, depth), out.len); - out[0] = first.?.token; + pub fn draftKept(e: *Engine, follow: []const u32, start: u32, depth: u32, out: []u32) !usize { + var probs: [16]f64 = undefined; + return e.draftKeptProbs(follow, start, depth, out, &probs); + } + + fn chainDraftsProbs(e: *Engine, first: ?fwd.Runner.MtpPick, depth: u32, out: []u32, probs: []f64) !usize { + const room = e.r.cur.cap -| (e.m.pos + 1); + const lim = @min(@min(@as(usize, depth), @as(usize, e.mtp_drafts)), @min(@min(out.len, probs.len), room)); + if (lim == 0 or first == null) return 0; + const conf = e.mtp_conf; + var prod: f64 = 1.0; + var n: usize = 0; + var cur = first.?; var mtp_st: [ld.max_tp]*anyopaque = undefined; for (0..e.r.tp) |rk| mtp_st[rk] = e.r.cur.ranks[rk].mtp_out; - var pos: usize = e.m.pos; - for (1..n) |i| { - const pk = (try e.r.forwardMtp(out[i - 1 .. i], mtp_st, pos, true, true)).?; - out[i] = pk.token; - pos += 1; + var j: usize = 0; + while (j < lim) : (j += 1) { + var propose = true; + var more = true; + if (conf > 0) { + const low = cur.prob < conf; + if (low and j > 0) { + propose = false; + more = false; + } else { + more = !low; + } + } else if (conf < 0) { + prod *= cur.prob; + if (prod < -conf) { + propose = (j == 0); + more = false; + } + } + if (!propose) break; + out[n] = cur.token; + probs[n] = cur.prob; + n += 1; + if (!more or j + 1 >= lim) break; + cur = (try e.r.forwardMtp(out[n - 1 .. n], mtp_st, e.m.pos + (n - 1), true, true)).?; } return n; } @@ -317,3 +368,48 @@ test "flashnext xpu: PLE n-gram hash resets across EOS boundary" { try ple.lastIds(h, &.{ 248044, 248044 }, 77, &b); try std.testing.expectEqualSlices(i64, &b, &a); } + +test "flashnext xpu: PackJob packs 16-column coalesced DPAS tiles and zero-pads partial tail columns" { + const n: usize = 19; + const groups: usize = 2; + const nb_total: usize = 2; + var w_in: [n * groups * 4]u32 = undefined; + var s_in: [n * groups]u16 = undefined; + var b_in: [n * groups]u16 = undefined; + for (0..n) |col| for (0..groups) |g| { + s_in[col * groups + g] = @intCast(col * 10 + g + 1); + b_in[col * groups + g] = @intCast(col * 20 + g + 3); + for (0..4) |q| w_in[(col * groups + g) * 4 + q] = @intCast((col + 1) * 1000 + g * 100 + q); + }; + var w_out: [nb_total * groups * 64]u32 = @splat(0xdeadbeef); + var s_out: [nb_total * groups * 16]u16 = @splat(0xffff); + var b_out: [nb_total * groups * 16]u16 = @splat(0xffff); + const job: ld.PackJob = .{ + .w_in = std.mem.sliceAsBytes(&w_in), + .s_in = std.mem.sliceAsBytes(&s_in), + .b_in = std.mem.sliceAsBytes(&b_in), + .w_out = &w_out, + .s_out = &s_out, + .b_out = &b_out, + .n = n, + .groups = groups, + .nb_total = nb_total, + .per = 1, + }; + job.packRange(0, nb_total); + for (0..nb_total) |nb| for (0..groups) |g| { + const tg = nb * groups + g; + for (0..16) |lane| { + const col = nb * 16 + lane; + if (col < n) { + try std.testing.expectEqual(@as(u16, @intCast(col * 10 + g + 1)), s_out[tg * 16 + lane]); + try std.testing.expectEqual(@as(u16, @intCast(col * 20 + g + 3)), b_out[tg * 16 + lane]); + for (0..4) |q| try std.testing.expectEqual(@as(u32, @intCast((col + 1) * 1000 + g * 100 + q)), w_out[tg * 64 + q * 16 + lane]); + } else { + try std.testing.expectEqual(@as(u16, 0), s_out[tg * 16 + lane]); + try std.testing.expectEqual(@as(u16, 0), b_out[tg * 16 + lane]); + for (0..4) |q| try std.testing.expectEqual(@as(u32, 0), w_out[tg * 64 + q * 16 + lane]); + } + } + }; +} diff --git a/zig/src/families/flashnext/xpu_forward.zig b/zig/src/families/flashnext/xpu_forward.zig index 250fa26b769..cf079050d52 100644 --- a/zig/src/families/flashnext/xpu_forward.zig +++ b/zig/src/families/flashnext/xpu_forward.zig @@ -26,7 +26,6 @@ const ple_layer = ld.ple_layer; const ple_tail_n = ld.ple_tail_n; const max_tp = ld.max_tp; const max_verify_rows = ld.max_verify_rows; -const chunk_rows = ld.chunk_rows; const Dev = ld.Dev; const TpShape = ld.TpShape; const off = ld.off; @@ -37,6 +36,7 @@ pub const Runner = struct { tp: usize, shp: TpShape, max_len: usize, + chunk_cap: usize, eos: i64, gpus: [max_tp]ze.Gpu = undefined, lists: [max_tp]ze.H = @splat(null), @@ -59,7 +59,8 @@ pub const Runner = struct { cur: *Seq = undefined, last_rows: u32 = 0, - pub fn initTp(gpa: std.mem.Allocator, io: std.Io, dir: []const u8, max_len: usize, tp: usize, want_mtp: bool) !*Runner { + pub fn initTp(gpa: std.mem.Allocator, io: std.Io, dir: []const u8, max_len: usize, tp: usize, want_mtp: bool, chunk_cap_in: usize) !*Runner { + const chunk_cap = @min(@max(chunk_cap_in, ld.chunk_rows), ld.max_chunk_rows); const shp = try TpShape.forTp(tp); const r = try gpa.create(Runner); errdefer gpa.destroy(r); @@ -69,6 +70,7 @@ pub const Runner = struct { .tp = tp, .shp = shp, .max_len = max_len, + .chunk_cap = chunk_cap, .eos = 0, .comm = undefined, .ngram = undefined, @@ -84,7 +86,7 @@ pub const Runner = struct { r.lists[rk] = r.devs[rk].list; } - r.comm = try tp_mod.TpComm.init(r.gpus[0..tp], &kbin.tp, chunk_rows * dims * 4); + r.comm = try tp_mod.TpComm.init(r.gpus[0..tp], &kbin.tp, chunk_cap * dims * 4); for (0..tp) |rk| r.devs[rk].g = r.gpus[rk]; r.ngram = try ple.Ngram.init(gpa, io, dir); @@ -96,13 +98,13 @@ pub const Runner = struct { } errdefer if (r.draft_ids.len > 0) gpa.free(r.draft_ids); - try ld.loadAllRanks(gpa, io, dir, r.devs[0..tp], shp, want_mtp, r.draft_ids, r.weights[0..tp]); + try ld.loadAllRanks(gpa, io, r.ngram.pool, dir, r.devs[0..tp], shp, want_mtp, r.draft_ids, r.weights[0..tp]); for (0..tp) |rk| r.gpus[rk] = r.devs[rk].g; r.has_mtp = r.weights[0].mtp != null; // Allocate shared USM host buffers for async DMA uploads & small token readbacks - r.host_ids = try st.allocHostSlice(i32, &r.devs[0], r.gpus[0..tp], chunk_rows); - r.host_ple = try st.allocHostSlice(u16, &r.devs[0], r.gpus[0..tp], chunk_rows * dims); + r.host_ids = try st.allocHostSlice(i32, &r.devs[0], r.gpus[0..tp], chunk_cap); + r.host_ple = try st.allocHostSlice(u16, &r.devs[0], r.gpus[0..tp], chunk_cap * dims); r.host_tok = try st.allocHostSlice(i32, &r.devs[0], r.gpus[0..tp], max_verify_rows); r.host_best = try st.allocHostSlice(f32, &r.devs[0], r.gpus[0..tp], max_verify_rows * 4); r.host_topv = try st.allocHostSlice(f32, &r.devs[0], r.gpus[0..tp], 256 * 64); @@ -111,7 +113,7 @@ pub const Runner = struct { // Allocate per-rank scratch buffers const nb_max = @max((max_len + index_ratio - 1) / index_ratio, 64); for (0..tp) |rk| { - r.acts[rk] = try st.allocRankActs(&r.devs[rk], shp, rk, nb_max, r.draft_ids.len, r.has_mtp); + r.acts[rk] = try st.allocRankActs(&r.devs[rk], shp, rk, chunk_cap, nb_max, r.draft_ids.len, r.has_mtp); } // Make shard_logits and shard_dlogits P2P-resident on Rank 0 for cross-GPU DMA gather! if (tp > 1) { @@ -170,7 +172,7 @@ pub const Runner = struct { if (s.win_open) try r.keepRows(s.win_rows); try ops.checkIds(ids); const rows = ids.len; - if (rows == 0 or rows > chunk_rows) return error.WindowTooWide; + if (rows == 0 or rows > r.chunk_cap) return error.WindowTooWide; if (@as(usize, s.pos) + rows > s.cap) return error.PromptTooLong; if (!inplace and rows > max_verify_rows) return error.WindowTooWide; @@ -386,7 +388,6 @@ pub const Runner = struct { // Keep last accepted row's streams in `last_streams` as well try d.copy(rs.last_streams, off(rs.verify_streams, (k - 1) * wide * 2), wide * 2); } - try r.syncAll(); if (kept < s.win_rows) { var hist = s.win_history; @@ -404,7 +405,7 @@ pub const Runner = struct { if (!r.has_mtp or tokens.len == 0) return null; try ops.checkIds(tokens); const m = tokens.len; - if (m > chunk_rows or mtp_pos0 + m > r.cur.cap) return error.PromptTooLong; + if (m > r.chunk_cap or mtp_pos0 + m > r.cur.cap) return error.PromptTooLong; for (tokens, 0..) |tok, i| r.host_ids[i] = @intCast(tok); var br_dst: [max_tp]*anyopaque = undefined; @@ -426,7 +427,7 @@ pub const Runner = struct { try d.launch(d.k.rmsnorm_rows, .{ .x = @intCast(m) }, .{ a.ple_keys, @as(i32, dims), mw.norm_e, a.mixed, eps, @as(i32, dims) }); try ops.linearBf16(d, mw.fc_e, a.mixed, a.mtp_branch, m); - // 2. Hidden branch: rmsnorm whole [10240] row -> fc_hidden on `4 * m` rows of [2560] -> ple_gated [m, + // 2. Hidden branch: rmsnorm whole [10240] row -> fc_hidden on `4 * m` rows -> ple_gated [m, 10240] try d.launch(d.k.rmsnorm_rows, .{ .x = @intCast(m) }, .{ in_streams[rk], @as(i32, wide), mw.norm_h, a.norm, eps, @as(i32, wide) }); try ops.linearBf16(d, mw.fc_h, a.norm, a.ple_gated, streams * m); diff --git a/zig/src/families/flashnext/xpu_load.zig b/zig/src/families/flashnext/xpu_load.zig index cdb4f787db8..b245183dcfb 100644 --- a/zig/src/families/flashnext/xpu_load.zig +++ b/zig/src/families/flashnext/xpu_load.zig @@ -1,7 +1,8 @@ -//! Qwen3.8 Flash Next device weight structures and TP={1,2,4} sharded safetensors loader. +//! Qwen3.8 Flash Next device weight structures and TP={1,2,4} sharded safetensors loader (Xe2 16-col DPAS tile layout). const std = @import("std"); const core = @import("core"); const ple = @import("xpu_ple.zig"); +const host_pool = @import("host_pool.zig"); const proposal_table = @import("proposal_table.zig"); const st = @import("xpu_store.zig"); @@ -34,6 +35,9 @@ pub const gdn_taps = st.gdn_taps; pub const max_tp = st.max_tp; pub const max_verify_rows = st.max_verify_rows; pub const chunk_rows = st.chunk_rows; +pub const default_solo_rows = st.default_solo_rows; +pub const max_chunk_rows = st.max_chunk_rows; +pub const attn_tile_rows = st.attn_tile_rows; pub const linearLayer = st.linearLayer; pub const linearIndex = st.linearIndex; pub const attnIndex = st.attnIndex; @@ -47,8 +51,6 @@ pub const Store = st.Store; pub const asF32 = st.asF32; const Tensor = st.Tensor; -// Device Weight Structures & TP Sharded Loaders - pub const Q4 = struct { w: ?*anyopaque = null, s: ?*anyopaque = null, @@ -79,25 +81,21 @@ pub const LayerW = struct { mlp_hc: HcW, proj: Q4, out: Q4, - router: *anyopaque, // [513, 2560] bf16 - // Linear (GDN) weights + router: *anyopaque, // [33, 160, 8, 16] i32 packed bf16 pairs for DPAS cw: ?*anyopaque = null, // [gdn_conv, 4] bf16 a_log: ?*anyopaque = null, // [nv] f32 dt: ?*anyopaque = null, // [nv] f32 norm: ?*anyopaque = null, // [128] bf16 - // Sparse Attention (QSA) weights q_scale: ?*anyopaque = null, // [256] f32 k_scale: ?*anyopaque = null, // [256] f32 i_scale: ?*anyopaque = null, // [128] f32 ik_scale: ?*anyopaque = null, // [128] f32 - // Layer 1 PLE weights ple_key: Q4 = .{}, ple_val: Q4 = .{}, ple_nk: ?*anyopaque = null, // [10240] f32 ple_nq: ?*anyopaque = null, // [10240] f32 ple_nc: ?*anyopaque = null, // [10240] f32 ple_cw: ?*anyopaque = null, // [10240, 4] bf16 - // Expert-parallel routed experts ([local_e, 640, 2560] / [local_e, 2560, 640]) + TP-sliced shared expert routed_gate: Q4, routed_up: Q4, routed_down: Q4, @@ -107,23 +105,23 @@ pub const LayerW = struct { }; pub const MtpW = struct { - norm_e: *anyopaque, // [2560] f32 - norm_h: *anyopaque, // [10240] f32 - fc_e: Q4, // [2560, 2560] - fc_h: Q4, // [2560, 2560] + norm_e: *anyopaque, + norm_h: *anyopaque, + fc_e: Q4, + fc_h: Q4, layer: LayerW, mixer: HcW, - draft: Q4, // [draft_slice_len, 2560] + draft: Q4, draft_lo: usize, draft_len: usize, }; pub const RankWeights = struct { embed: EmbedW, - inv_freq: *anyopaque, // [32] f32 + inv_freq: *anyopaque, layers: [layers_n]LayerW, mixer: HcW, - head: Q4, // [vocab / tp, 2560] + head: Q4, mtp: ?MtpW = null, }; @@ -136,46 +134,94 @@ fn holdTriple(store: *Store, buf: []u8, prefix: []const u8) !struct { w: Tensor, return .{ .w = w, .s = s, .b = b }; } -fn uploadFullQ4(d: *Dev, store: *Store, prefix: []const u8, n: usize, k: usize) !Q4 { +pub const PackJob = struct { + w_in: []const u8, + s_in: []const u8, + b_in: []const u8, + w_out: []u32, + s_out: []u16, + b_out: []u16, + n: usize, + groups: usize, + nb_total: usize, + per: usize, + + pub fn packRange(j: *const PackJob, nb_lo: usize, nb_hi: usize) void { + const groups = j.groups; + const words = groups * 4; + for (nb_lo..nb_hi) |nb| for (0..groups) |g| { + const tg = nb * groups + g; + const wp = j.w_out[tg * 64 ..][0..64]; + const sp = j.s_out[tg * 16 ..][0..16]; + const bp = j.b_out[tg * 16 ..][0..16]; + for (0..16) |lane| { + const col = nb * 16 + lane; + if (col < j.n) { + const wbase = (col * words + g * 4) * 4; + wp[0 + lane] = std.mem.readInt(u32, j.w_in[wbase + 0 ..][0..4], .little); + wp[16 + lane] = std.mem.readInt(u32, j.w_in[wbase + 4 ..][0..4], .little); + wp[32 + lane] = std.mem.readInt(u32, j.w_in[wbase + 8 ..][0..4], .little); + wp[48 + lane] = std.mem.readInt(u32, j.w_in[wbase + 12 ..][0..4], .little); + const sb_off = (col * groups + g) * 2; + sp[lane] = std.mem.readInt(u16, j.s_in[sb_off..][0..2], .little); + bp[lane] = std.mem.readInt(u16, j.b_in[sb_off..][0..2], .little); + } else { + wp[0 + lane] = 0; + wp[16 + lane] = 0; + wp[32 + lane] = 0; + wp[48 + lane] = 0; + sp[lane] = 0; + bp[lane] = 0; + } + } + }; + } + + fn part(ctx: *const anyopaque, idx: usize) anyerror!void { + const j: *const PackJob = @ptrCast(@alignCast(ctx)); + const lo = @min(j.nb_total, idx * j.per); + j.packRange(lo, @min(j.nb_total, lo + j.per)); + } +}; + +/// Pack row-major `[n, k]` Q4 weights into `[ceil(n/16), k/32, 4, 16]` coalesced Xe2 DPAS tile layout and upload. +fn packAndUploadQ4(gpa: std.mem.Allocator, pool: ?*host_pool.Pool, d: *Dev, w_raw: []const u8, s_raw: []const u8, b_raw: []const u8, n: usize, k: usize) !Q4 { + if (k == 0 or k % 32 != 0) return error.UnexpectedTensor; + const groups = k / 32; + const nb_total = (n + 15) / 16; + const w_out = try gpa.alloc(u32, nb_total * groups * 64); + defer gpa.free(w_out); + const s_out = try gpa.alloc(u16, nb_total * groups * 16); + defer gpa.free(s_out); + const b_out = try gpa.alloc(u16, nb_total * groups * 16); + defer gpa.free(b_out); + const n_parts = if (pool != null and nb_total >= 128) @min(@as(usize, 32), nb_total / 32) else 1; + const job: PackJob = .{ .w_in = w_raw, .s_in = s_raw, .b_in = b_raw, .w_out = w_out, .s_out = s_out, .b_out = b_out, .n = n, .groups = groups, .nb_total = nb_total, .per = (nb_total + n_parts - 1) / n_parts }; + if (n_parts > 1) try pool.?.run(n_parts, .{ .ctx = &job, .run = PackJob.part }) else job.packRange(0, nb_total); + return .{ .w = try d.upload(std.mem.sliceAsBytes(w_out)), .s = try d.upload(std.mem.sliceAsBytes(s_out)), .b = try d.upload(std.mem.sliceAsBytes(b_out)), .n = n, .k = k }; +} + +fn uploadFullQ4(gpa: std.mem.Allocator, pool: ?*host_pool.Pool, d: *Dev, store: *Store, prefix: []const u8, n: usize, k: usize) !Q4 { var buf: [256]u8 = undefined; const t = try holdTriple(store, &buf, prefix); - if (!t.w.is(.u32, &.{ n, k / 8 }) or !t.s.is(.bf16, &.{ n, k / 32 }) or !t.b.is(.bf16, &.{ n, k / 32 })) { - return error.UnexpectedTensor; - } - return .{ - .w = try d.upload(t.w.bytes), - .s = try d.upload(t.s.bytes), - .b = try d.upload(t.b.bytes), - .n = n, - .k = k, - }; + if (!t.w.is(.u32, &.{ n, k / 8 }) or !t.s.is(.bf16, &.{ n, k / 32 }) or !t.b.is(.bf16, &.{ n, k / 32 })) return error.UnexpectedTensor; + return packAndUploadQ4(gpa, pool, d, t.w.bytes, t.s.bytes, t.b.bytes, n, k); } -fn uploadRowSliceQ4(d: *Dev, store: *Store, prefix: []const u8, full_n: usize, k: usize, from: usize, len: usize) !Q4 { +fn uploadRowSliceQ4(gpa: std.mem.Allocator, pool: ?*host_pool.Pool, d: *Dev, store: *Store, prefix: []const u8, full_n: usize, k: usize, from: usize, len: usize) !Q4 { var buf: [256]u8 = undefined; const t = try holdTriple(store, &buf, prefix); - if (!t.w.is(.u32, &.{ full_n, k / 8 }) or !t.s.is(.bf16, &.{ full_n, k / 32 }) or !t.b.is(.bf16, &.{ full_n, k / 32 })) { - return error.UnexpectedTensor; - } - if (from + len > full_n) return error.UnexpectedTensor; + if (!t.w.is(.u32, &.{ full_n, k / 8 }) or !t.s.is(.bf16, &.{ full_n, k / 32 }) or !t.b.is(.bf16, &.{ full_n, k / 32 }) or from + len > full_n) return error.UnexpectedTensor; const wb = (k / 8) * 4; const gb = (k / 32) * 2; - return .{ - .w = try d.upload(t.w.bytes[from * wb ..][0 .. len * wb]), - .s = try d.upload(t.s.bytes[from * gb ..][0 .. len * gb]), - .b = try d.upload(t.b.bytes[from * gb ..][0 .. len * gb]), - .n = len, - .k = k, - }; + return packAndUploadQ4(gpa, pool, d, t.w.bytes[from * wb ..][0 .. len * wb], t.s.bytes[from * gb ..][0 .. len * gb], t.b.bytes[from * gb ..][0 .. len * gb], len, k); } -fn uploadColSliceQ4(gpa: std.mem.Allocator, d: *Dev, store: *Store, prefix: []const u8, n: usize, full_k: usize, col_from: usize, col_len: usize) !Q4 { +fn uploadColSliceQ4(gpa: std.mem.Allocator, pool: ?*host_pool.Pool, d: *Dev, store: *Store, prefix: []const u8, n: usize, full_k: usize, col_from: usize, col_len: usize) !Q4 { if (col_from % 32 != 0 or col_len % 32 != 0 or col_from + col_len > full_k) return error.UnexpectedTensor; var buf: [256]u8 = undefined; const t = try holdTriple(store, &buf, prefix); - if (!t.w.is(.u32, &.{ n, full_k / 8 }) or !t.s.is(.bf16, &.{ n, full_k / 32 }) or !t.b.is(.bf16, &.{ n, full_k / 32 })) { - return error.UnexpectedTensor; - } + if (!t.w.is(.u32, &.{ n, full_k / 8 }) or !t.s.is(.bf16, &.{ n, full_k / 32 }) or !t.b.is(.bf16, &.{ n, full_k / 32 })) return error.UnexpectedTensor; const full_wb = (full_k / 8) * 4; const full_gb = (full_k / 32) * 2; const part_wb = (col_len / 8) * 4; @@ -189,28 +235,17 @@ fn uploadColSliceQ4(gpa: std.mem.Allocator, d: *Dev, store: *Store, prefix: []co defer gpa.free(s_host); const b_host = try gpa.alloc(u8, n * part_gb); defer gpa.free(b_host); - for (0..n) |r| { @memcpy(w_host[r * part_wb ..][0..part_wb], t.w.bytes[r * full_wb + woff ..][0..part_wb]); @memcpy(s_host[r * part_gb ..][0..part_gb], t.s.bytes[r * full_gb + goff ..][0..part_gb]); @memcpy(b_host[r * part_gb ..][0..part_gb], t.b.bytes[r * full_gb + goff ..][0..part_gb]); } - return .{ - .w = try d.upload(w_host), - .s = try d.upload(s_host), - .b = try d.upload(b_host), - .n = n, - .k = col_len, - }; + return packAndUploadQ4(gpa, pool, d, w_host, s_host, b_host, n, col_len); } -const PartSlice = struct { - suffix: []const u8, - full_n: usize, - spans: []const Span, -}; +const PartSlice = struct { suffix: []const u8, full_n: usize, spans: []const Span }; -fn uploadStitchedQ4(gpa: std.mem.Allocator, d: *Dev, store: *Store, prefix: []const u8, k: usize, parts: []const PartSlice) !Q4 { +fn uploadStitchedQ4(gpa: std.mem.Allocator, pool: ?*host_pool.Pool, d: *Dev, store: *Store, prefix: []const u8, k: usize, parts: []const PartSlice) !Q4 { var total_n: usize = 0; for (parts) |p| for (p.spans) |sp| { total_n += sp.len; @@ -230,9 +265,7 @@ fn uploadStitchedQ4(gpa: std.mem.Allocator, d: *Dev, store: *Store, prefix: []co for (parts) |p| { const full_name = try std.fmt.bufPrint(&pbuf, "{s}{s}", .{ prefix, p.suffix }); const t = try holdTriple(store, &buf, full_name); - if (!t.w.is(.u32, &.{ p.full_n, k / 8 }) or !t.s.is(.bf16, &.{ p.full_n, k / 32 }) or !t.b.is(.bf16, &.{ p.full_n, k / 32 })) { - return error.UnexpectedTensor; - } + if (!t.w.is(.u32, &.{ p.full_n, k / 8 }) or !t.s.is(.bf16, &.{ p.full_n, k / 32 }) or !t.b.is(.bf16, &.{ p.full_n, k / 32 })) return error.UnexpectedTensor; for (p.spans) |sp| { if (sp.from + sp.len > p.full_n) return error.UnexpectedTensor; @memcpy(w_host[row_at * wb ..][0 .. sp.len * wb], t.w.bytes[sp.from * wb ..][0 .. sp.len * wb]); @@ -242,33 +275,19 @@ fn uploadStitchedQ4(gpa: std.mem.Allocator, d: *Dev, store: *Store, prefix: []co } } if (row_at != total_n) return error.UnexpectedTensor; - return .{ - .w = try d.upload(w_host), - .s = try d.upload(s_host), - .b = try d.upload(b_host), - .n = total_n, - .k = k, - }; + return packAndUploadQ4(gpa, pool, d, w_host, s_host, b_host, total_n, k); } -fn uploadRoutedSliceQ4(d: *Dev, store: *Store, prefix: []const u8, n: usize, k: usize, first_e: usize, local_e: usize) !Q4 { +fn uploadRoutedSliceQ4(gpa: std.mem.Allocator, pool: ?*host_pool.Pool, d: *Dev, store: *Store, prefix: []const u8, n: usize, k: usize, first_e: usize, local_e: usize) !Q4 { var buf: [256]u8 = undefined; const t = try holdTriple(store, &buf, prefix); - if (!t.w.is(.u32, &.{ experts_n, n, k / 8 }) or !t.s.is(.bf16, &.{ experts_n, n, k / 32 }) or !t.b.is(.bf16, &.{ experts_n, n, k / 32 })) { - return error.UnexpectedTensor; - } + if (!t.w.is(.u32, &.{ experts_n, n, k / 8 }) or !t.s.is(.bf16, &.{ experts_n, n, k / 32 }) or !t.b.is(.bf16, &.{ experts_n, n, k / 32 })) return error.UnexpectedTensor; const e_wb = n * (k / 8) * 4; const e_gb = n * (k / 32) * 2; - return .{ - .w = try d.upload(t.w.bytes[first_e * e_wb ..][0 .. local_e * e_wb]), - .s = try d.upload(t.s.bytes[first_e * e_gb ..][0 .. local_e * e_gb]), - .b = try d.upload(t.b.bytes[first_e * e_gb ..][0 .. local_e * e_gb]), - .n = local_e * n, - .k = k, - }; + return packAndUploadQ4(gpa, pool, d, t.w.bytes[first_e * e_wb ..][0 .. local_e * e_wb], t.s.bytes[first_e * e_gb ..][0 .. local_e * e_gb], t.b.bytes[first_e * e_gb ..][0 .. local_e * e_gb], local_e * n, k); } -fn loadHcW(gpa: std.mem.Allocator, d: *Dev, store: *Store, prefix: []const u8, inject: bool) !HcW { +fn loadHcW(gpa: std.mem.Allocator, pool: ?*host_pool.Pool, d: *Dev, store: *Store, prefix: []const u8, inject: bool) !HcW { var buf: [256]u8 = undefined; const gamma = try store.hold(try std.fmt.bufPrint(&buf, "{s}.hc_norm.weight", .{prefix})); const scale_host = try store.normScale(gpa, gamma); @@ -277,34 +296,51 @@ fn loadHcW(gpa: std.mem.Allocator, d: *Dev, store: *Store, prefix: []const u8, i const scale_dev = try d.upload(std.mem.sliceAsBytes(scale_host)); const down_q = if (inject) - try uploadStitchedQ4(gpa, d, store, prefix, wide, &.{ + try uploadStitchedQ4(gpa, pool, d, store, prefix, wide, &.{ .{ .suffix = ".input_mix_weight_down", .full_n = low, .spans = &.{.{ .from = 0, .len = low }} }, .{ .suffix = ".block_inject_weight", .full_n = streams, .spans = &.{.{ .from = 0, .len = streams }} }, }) else - try uploadFullQ4(d, store, try std.fmt.bufPrint(&buf, "{s}.input_mix_weight_down", .{prefix}), low, wide); - - const up_q = try uploadFullQ4(d, store, try std.fmt.bufPrint(&buf, "{s}.input_mix_weight_up", .{prefix}), wide, low); - return .{ - .scale = scale_dev, - .down = down_q, - .up = up_q, - .n_down = if (inject) low + streams else low, - .has_inj = @intFromBool(inject), - }; + try uploadFullQ4(gpa, pool, d, store, try std.fmt.bufPrint(&buf, "{s}.input_mix_weight_down", .{prefix}), low, wide); + + const up_q = try uploadFullQ4(gpa, pool, d, store, try std.fmt.bufPrint(&buf, "{s}.input_mix_weight_up", .{prefix}), wide, low); + return .{ .scale = scale_dev, .down = down_q, .up = up_q, .n_down = if (inject) low + streams else low, .has_inj = @intFromBool(inject) }; } -fn loadLayerRank(gpa: std.mem.Allocator, d: *Dev, store: *Store, root: []const u8, linear: bool, with_ple: bool, shp: TpShape, rk: usize) !LayerW { +fn packRouterTiles(gpa: std.mem.Allocator, d: *Dev, router_host: []const u16) !*anyopaque { + const packed_r = try gpa.alloc(u32, 33 * 160 * 8 * 16); + defer gpa.free(packed_r); + for (0..33) |nb| { + for (0..160) |kb| { + const base = (nb * 160 + kb) * 128; + for (0..8) |p| { + for (0..16) |lane| { + const col = nb * 16 + lane; + if (col < experts_n + 1) { + const r_off = col * dims + kb * 16 + p * 2; + const lo: u32 = router_host[r_off]; + const hi: u32 = router_host[r_off + 1]; + packed_r[base + p * 16 + lane] = lo | (hi << 16); + } else { + packed_r[base + p * 16 + lane] = 0; + } + } + } + } + } + return d.upload(std.mem.sliceAsBytes(packed_r)); +} + +fn loadLayerRank(gpa: std.mem.Allocator, pool: ?*host_pool.Pool, d: *Dev, store: *Store, root: []const u8, linear: bool, with_ple: bool, shp: TpShape, rk: usize) !LayerW { var buf: [256]u8 = undefined; var pbuf: [256]u8 = undefined; - const attn_hc = try loadHcW(gpa, d, store, try std.fmt.bufPrint(&pbuf, "{s}.attn_hyper_connection", .{root}), true); - const mlp_hc = try loadHcW(gpa, d, store, try std.fmt.bufPrint(&pbuf, "{s}.mlp_hyper_connection", .{root}), true); + const attn_hc = try loadHcW(gpa, pool, d, store, try std.fmt.bufPrint(&pbuf, "{s}.attn_hyper_connection", .{root}), true); + const mlp_hc = try loadHcW(gpa, pool, d, store, try std.fmt.bufPrint(&pbuf, "{s}.mlp_hyper_connection", .{root}), true); var mlp_buf: [160]u8 = undefined; const mlp_root = try std.fmt.bufPrint(&mlp_buf, "{s}.mlp", .{root}); - // Router [513, 2560] bf16: gate.weight [512, 2560] + shared_expert_gate [1, 2560] const router_host = try gpa.alloc(u16, (experts_n + 1) * dims); defer gpa.free(router_host); const gate_t = try store.hold(try std.fmt.bufPrint(&buf, "{s}.gate.weight", .{mlp_root})); @@ -319,9 +355,9 @@ fn loadLayerRank(gpa: std.mem.Allocator, d: *Dev, store: *Store, root: []const u } else { const sg_prefix = try std.fmt.bufPrint(&pbuf, "{s}.shared_expert_gate", .{mlp_root}); const sg = try holdTriple(store, &buf, sg_prefix); - try ple.dequantRow(sg.w.bytes, sg.s.bytes, sg.b.bytes, dims, 0, router_host[experts_n * dims ..][0..dims]); + try ple.dequantRow(sg.w.bytes, sg.s.bytes, sg.b.bytes, dims, 0, 1.0, router_host[experts_n * dims ..][0..dims]); } - const router_dev = try d.upload(std.mem.sliceAsBytes(router_host)); + const router_dev = try packRouterTiles(gpa, d, router_host); var lw: LayerW = .{ .linear = linear, @@ -344,7 +380,7 @@ fn loadLayerRank(gpa: std.mem.Allocator, d: *Dev, store: *Store, root: []const u const lp = try std.fmt.bufPrint(&lp_buf, "{s}.linear_attn", .{root}); const qk = shp.nk * 128; const v = shp.nv * 128; - const full_qk = 16 * 128; // 2048 + const full_qk = 16 * 128; const qkv_spans = [_]Span{ .{ .from = rk * qk, .len = qk }, .{ .from = full_qk + rk * qk, .len = qk }, @@ -352,13 +388,13 @@ fn loadLayerRank(gpa: std.mem.Allocator, d: *Dev, store: *Store, root: []const u }; const z_spans = [_]Span{.{ .from = rk * v, .len = v }}; const ba_spans = [_]Span{.{ .from = rk * shp.nv, .len = shp.nv }}; - lw.proj = try uploadStitchedQ4(gpa, d, store, lp, dims, &.{ + lw.proj = try uploadStitchedQ4(gpa, pool, d, store, lp, dims, &.{ .{ .suffix = ".in_proj_qkv", .full_n = 10240, .spans = &qkv_spans }, .{ .suffix = ".in_proj_z", .full_n = 6144, .spans = &z_spans }, .{ .suffix = ".in_proj_b", .full_n = 48, .spans = &ba_spans }, .{ .suffix = ".in_proj_a", .full_n = 48, .spans = &ba_spans }, }); - lw.out = try uploadColSliceQ4(gpa, d, store, try std.fmt.bufPrint(&pbuf, "{s}.out_proj", .{lp}), dims, 6144, rk * shp.gdn_vdim, shp.gdn_vdim); + lw.out = try uploadColSliceQ4(gpa, pool, d, store, try std.fmt.bufPrint(&pbuf, "{s}.out_proj", .{lp}), dims, 6144, rk * shp.gdn_vdim, shp.gdn_vdim); const conv_t = try store.hold(try std.fmt.bufPrint(&buf, "{s}.conv1d.weight", .{lp})); if (conv_t.dtype != .bf16 or conv_t.dim(0) != 10240 or conv_t.bytes.len != 10240 * gdn_taps * 2) return error.UnexpectedTensor; @@ -388,18 +424,17 @@ fn loadLayerRank(gpa: std.mem.Allocator, d: *Dev, store: *Store, root: []const u const ap = try std.fmt.bufPrint(&ap_buf, "{s}.self_attn", .{root}); const q_rows = shp.nq * 512; const kv_rows = shp.nkv * 256; - // Full model has kv_heads = 2: at TP=4, ranks {0,1} share KV head 0 and ranks {2,3} share KV head 1! const kv_idx = if (shp.tp == 1) 0 else (rk * 2) / shp.tp; const q_spans = [_]Span{.{ .from = rk * q_rows, .len = q_rows }}; const kv_spans = [_]Span{.{ .from = kv_idx * 256, .len = kv_rows }}; const idx_spans = [_]Span{.{ .from = 0, .len = 640 }}; - lw.proj = try uploadStitchedQ4(gpa, d, store, ap, dims, &.{ + lw.proj = try uploadStitchedQ4(gpa, pool, d, store, ap, dims, &.{ .{ .suffix = ".q_proj", .full_n = 12288, .spans = &q_spans }, .{ .suffix = ".k_proj", .full_n = 512, .spans = &kv_spans }, .{ .suffix = ".v_proj", .full_n = 512, .spans = &kv_spans }, .{ .suffix = ".indexer.index_qk_proj", .full_n = 640, .spans = &idx_spans }, }); - lw.out = try uploadColSliceQ4(gpa, d, store, try std.fmt.bufPrint(&pbuf, "{s}.o_proj", .{ap}), dims, 6144, rk * shp.attn_odim, shp.attn_odim); + lw.out = try uploadColSliceQ4(gpa, pool, d, store, try std.fmt.bufPrint(&pbuf, "{s}.o_proj", .{ap}), dims, 6144, rk * shp.attn_odim, shp.attn_odim); const qn = try store.normScale(gpa, try store.hold(try std.fmt.bufPrint(&buf, "{s}.q_norm.weight", .{ap}))); defer gpa.free(qn); @@ -419,8 +454,8 @@ fn loadLayerRank(gpa: std.mem.Allocator, d: *Dev, store: *Store, root: []const u if (with_ple) { var pp_buf: [160]u8 = undefined; const pp = try std.fmt.bufPrint(&pp_buf, "{s}.ple", .{root}); - lw.ple_key = try uploadFullQ4(d, store, try std.fmt.bufPrint(&pbuf, "{s}.key_proj", .{pp}), wide, dims); - lw.ple_val = try uploadFullQ4(d, store, try std.fmt.bufPrint(&pbuf, "{s}.value_proj", .{pp}), dims, dims); + lw.ple_key = try uploadFullQ4(gpa, pool, d, store, try std.fmt.bufPrint(&pbuf, "{s}.key_proj", .{pp}), wide, dims); + lw.ple_val = try uploadFullQ4(gpa, pool, d, store, try std.fmt.bufPrint(&pbuf, "{s}.value_proj", .{pp}), dims, dims); const nk = try store.normScale(gpa, try store.hold(try std.fmt.bufPrint(&buf, "{s}.norm_key.weight", .{pp}))); defer gpa.free(nk); const nq = try store.normScale(gpa, try store.hold(try std.fmt.bufPrint(&buf, "{s}.norm_query.weight", .{pp}))); @@ -436,33 +471,25 @@ fn loadLayerRank(gpa: std.mem.Allocator, d: *Dev, store: *Store, root: []const u lw.ple_cw = try d.upload(pconv.bytes); } - // Expert-parallel routed experts + TP-sliced shared expert const first_e = rk * shp.local_e; - lw.routed_gate = try uploadRoutedSliceQ4(d, store, try std.fmt.bufPrint(&pbuf, "{s}.switch_mlp.gate_proj", .{mlp_root}), moe_w, dims, first_e, shp.local_e); - lw.routed_up = try uploadRoutedSliceQ4(d, store, try std.fmt.bufPrint(&pbuf, "{s}.switch_mlp.up_proj", .{mlp_root}), moe_w, dims, first_e, shp.local_e); - lw.routed_down = try uploadRoutedSliceQ4(d, store, try std.fmt.bufPrint(&pbuf, "{s}.switch_mlp.down_proj", .{mlp_root}), dims, moe_w, first_e, shp.local_e); - - lw.shared_gate = try uploadRowSliceQ4(d, store, try std.fmt.bufPrint(&pbuf, "{s}.shared_expert.gate_proj", .{mlp_root}), moe_w, dims, rk * shp.sh_w, shp.sh_w); - lw.shared_up = try uploadRowSliceQ4(d, store, try std.fmt.bufPrint(&pbuf, "{s}.shared_expert.up_proj", .{mlp_root}), moe_w, dims, rk * shp.sh_w, shp.sh_w); - lw.shared_down = try uploadColSliceQ4(gpa, d, store, try std.fmt.bufPrint(&pbuf, "{s}.shared_expert.down_proj", .{mlp_root}), dims, moe_w, rk * shp.sh_w, shp.sh_w); + lw.routed_gate = try uploadRoutedSliceQ4(gpa, pool, d, store, try std.fmt.bufPrint(&pbuf, "{s}.switch_mlp.gate_proj", .{mlp_root}), moe_w, dims, first_e, shp.local_e); + lw.routed_up = try uploadRoutedSliceQ4(gpa, pool, d, store, try std.fmt.bufPrint(&pbuf, "{s}.switch_mlp.up_proj", .{mlp_root}), moe_w, dims, first_e, shp.local_e); + lw.routed_down = try uploadRoutedSliceQ4(gpa, pool, d, store, try std.fmt.bufPrint(&pbuf, "{s}.switch_mlp.down_proj", .{mlp_root}), dims, moe_w, first_e, shp.local_e); + lw.shared_gate = try uploadRowSliceQ4(gpa, pool, d, store, try std.fmt.bufPrint(&pbuf, "{s}.shared_expert.gate_proj", .{mlp_root}), moe_w, dims, rk * shp.sh_w, shp.sh_w); + lw.shared_up = try uploadRowSliceQ4(gpa, pool, d, store, try std.fmt.bufPrint(&pbuf, "{s}.shared_expert.up_proj", .{mlp_root}), moe_w, dims, rk * shp.sh_w, shp.sh_w); + lw.shared_down = try uploadColSliceQ4(gpa, pool, d, store, try std.fmt.bufPrint(&pbuf, "{s}.shared_expert.down_proj", .{mlp_root}), dims, moe_w, rk * shp.sh_w, shp.sh_w); return lw; } pub fn draftIds(gpa: std.mem.Allocator) ![]u32 { - return core.proposal_vocab.legacy.ids(gpa, proposal_table.text, .{ - .vocab = vocab, - .skip_past_vocab = true, - .delimiters = " \t\r\n,", - }); + return core.proposal_vocab.legacy.ids(gpa, proposal_table.text, .{ .vocab = vocab, .skip_past_vocab = true, .delimiters = " \t\r\n," }); } -fn uploadDraftSliceQ4(gpa: std.mem.Allocator, d: *Dev, store: *Store, ids: []const u32) !Q4 { +fn uploadDraftSliceQ4(gpa: std.mem.Allocator, pool: ?*host_pool.Pool, d: *Dev, store: *Store, ids: []const u32) !Q4 { var buf: [256]u8 = undefined; const t = try holdTriple(store, &buf, "language_model.lm_head"); - if (!t.w.is(.u32, &.{ vocab, dims / 8 }) or !t.s.is(.bf16, &.{ vocab, dims / 32 }) or !t.b.is(.bf16, &.{ vocab, dims / 32 })) { - return error.UnexpectedTensor; - } + if (!t.w.is(.u32, &.{ vocab, dims / 8 }) or !t.s.is(.bf16, &.{ vocab, dims / 32 }) or !t.b.is(.bf16, &.{ vocab, dims / 32 })) return error.UnexpectedTensor; const wb = (dims / 8) * 4; const gb = (dims / 32) * 2; const w_host = try gpa.alloc(u8, ids.len * wb); @@ -477,28 +504,18 @@ fn uploadDraftSliceQ4(gpa: std.mem.Allocator, d: *Dev, store: *Store, ids: []con @memcpy(s_host[i * gb ..][0..gb], t.s.bytes[row * gb ..][0..gb]); @memcpy(b_host[i * gb ..][0..gb], t.b.bytes[row * gb ..][0..gb]); } - return .{ - .w = try d.upload(w_host), - .s = try d.upload(s_host), - .b = try d.upload(b_host), - .n = ids.len, - .k = dims, - }; + return packAndUploadQ4(gpa, pool, d, w_host, s_host, b_host, ids.len, dims); } -/// Load all weights across `devs[0..tp]` in layer order so each safetensors shard is mapped once across all ranks and -pub fn loadAllRanks(gpa: std.mem.Allocator, io: std.Io, dir: []const u8, devs: []Dev, shp: TpShape, want_mtp: bool, draft_ids: []const u32, out: []RankWeights) !void { +/// Load all weights across `devs[0..tp]` in layer order into coalesced 16-column Xe2 DPAS tile layout. +pub fn loadAllRanks(gpa: std.mem.Allocator, io: std.Io, pool: ?*host_pool.Pool, dir: []const u8, devs: []Dev, shp: TpShape, want_mtp: bool, draft_ids: []const u32, out: []RankWeights) !void { var store = try Store.open(gpa, io, dir); defer store.deinit(); try store.detectNorms(); - // Inverse RoPE frequencies (rotary_dim = 64, half = 32, theta = 10,000,000) var inv: [half]f32 = undefined; - for (0..half) |i| { - inv[i] = @floatCast(1.0 / std.math.pow(f64, 10_000_000.0, @as(f64, @floatFromInt(2 * i)) / 64.0)); - } + for (0..half) |i| inv[i] = @floatCast(1.0 / std.math.pow(f64, 10_000_000.0, @as(f64, @floatFromInt(2 * i)) / 64.0)); - // 1. Embeddings + inv_freq on all ranks { var buf: [256]u8 = undefined; const ew = try store.hold("language_model.model.embed_tokens.weight"); @@ -510,41 +527,31 @@ pub fn loadAllRanks(gpa: std.mem.Allocator, io: std.Io, dir: []const u8, devs: [ } } else { const et = try holdTriple(&store, &buf, "language_model.model.embed_tokens"); - if (!et.w.is(.u32, &.{ vocab, dims / 8 }) or !et.s.is(.bf16, &.{ vocab, dims / 32 }) or !et.b.is(.bf16, &.{ vocab, dims / 32 })) { - return error.UnexpectedTensor; - } + if (!et.w.is(.u32, &.{ vocab, dims / 8 }) or !et.s.is(.bf16, &.{ vocab, dims / 32 }) or !et.b.is(.bf16, &.{ vocab, dims / 32 })) return error.UnexpectedTensor; for (devs, 0..) |*d, rk| { - out[rk].embed = .{ - .w = try d.upload(et.w.bytes), - .s = try d.upload(et.s.bytes), - .b = try d.upload(et.b.bytes), - .dense = false, - }; + out[rk].embed = .{ .w = try d.upload(et.w.bytes), .s = try d.upload(et.s.bytes), .b = try d.upload(et.b.bytes), .dense = false }; out[rk].inv_freq = try d.upload(std.mem.sliceAsBytes(&inv)); } } store.release(); } - // 2. All 48 decoder layers in order (releases non-PLE shard pages after each layer!) for (0..layers_n) |l| { var root_buf: [96]u8 = undefined; const root = try std.fmt.bufPrint(&root_buf, "language_model.model.layers.{d}", .{l}); for (devs, 0..) |*d, rk| { - out[rk].layers[l] = try loadLayerRank(gpa, d, &store, root, linearLayer(l), l == ple_layer, shp, rk); + out[rk].layers[l] = try loadLayerRank(gpa, pool, d, &store, root, linearLayer(l), l == ple_layer, shp, rk); } store.release(); } - // 3. Final hyper-connection mixer + TP-sliced lm_head for (devs, 0..) |*d, rk| { - out[rk].mixer = try loadHcW(gpa, d, &store, "language_model.model.hyper_connection_mixer", false); - out[rk].head = try uploadRowSliceQ4(d, &store, "language_model.lm_head", vocab, dims, rk * shp.vocab_per, shp.vocab_per); + out[rk].mixer = try loadHcW(gpa, pool, d, &store, "language_model.model.hyper_connection_mixer", false); + out[rk].head = try uploadRowSliceQ4(gpa, pool, d, &store, "language_model.lm_head", vocab, dims, rk * shp.vocab_per, shp.vocab_per); out[rk].mtp = null; } store.release(); - // 4. Optional MTP speculative layer & 79,591-row draft head if (want_mtp and store.has("language_model.mtp.pre_fc_norm_embedding.weight")) { const ne = try store.normScale(gpa, try store.hold("language_model.mtp.pre_fc_norm_embedding.weight")); defer gpa.free(ne); @@ -557,11 +564,11 @@ pub fn loadAllRanks(gpa: std.mem.Allocator, io: std.Io, dir: []const u8, devs: [ out[rk].mtp = .{ .norm_e = try d.upload(std.mem.sliceAsBytes(ne)), .norm_h = try d.upload(std.mem.sliceAsBytes(nh)), - .fc_e = try uploadFullQ4(d, &store, "language_model.mtp.fc_embedding", dims, dims), - .fc_h = try uploadFullQ4(d, &store, "language_model.mtp.fc_hidden", dims, dims), - .layer = try loadLayerRank(gpa, d, &store, "language_model.mtp.layers.0", false, false, shp, rk), - .mixer = try loadHcW(gpa, d, &store, "language_model.mtp.hyper_connection_mixer", false), - .draft = try uploadDraftSliceQ4(gpa, d, &store, draft_ids[sl.lo .. sl.lo + sl.len]), + .fc_e = try uploadFullQ4(gpa, pool, d, &store, "language_model.mtp.fc_embedding", dims, dims), + .fc_h = try uploadFullQ4(gpa, pool, d, &store, "language_model.mtp.fc_hidden", dims, dims), + .layer = try loadLayerRank(gpa, pool, d, &store, "language_model.mtp.layers.0", false, false, shp, rk), + .mixer = try loadHcW(gpa, pool, d, &store, "language_model.mtp.hyper_connection_mixer", false), + .draft = try uploadDraftSliceQ4(gpa, pool, d, &store, draft_ids[sl.lo .. sl.lo + sl.len]), .draft_lo = sl.lo, .draft_len = sl.len, }; diff --git a/zig/src/families/flashnext/xpu_main.zig b/zig/src/families/flashnext/xpu_main.zig index e28fc741838..379f87c5e82 100644 --- a/zig/src/families/flashnext/xpu_main.zig +++ b/zig/src/families/flashnext/xpu_main.zig @@ -19,6 +19,9 @@ pub fn main(init: std.process.Init) !void { const ctx: usize = try env.read(usize, "XPU_CTX", 16384); const want_mtp: bool = try env.read(bool, "XPU_MTP", true); const verify_test: bool = try env.read(bool, "XPU_VERIFY_TEST", false); + const chunk: u32 = try env.read(u32, "XPU_CHUNK", @intCast(eng.ld.default_solo_rows)); + const mtp_depth: u32 = try env.read(u32, "XPU_MTP_DEPTH", 6); + const mtp_conf: f64 = try env.read(f64, "XPU_MTP_CONF", -0.4); var bench_lens: std.ArrayList(usize) = .empty; defer bench_lens.deinit(gpa); @@ -34,13 +37,20 @@ pub fn main(init: std.process.Init) !void { while (it.next()) |w| try file_ids.append(gpa, try std.fmt.parseInt(u32, w, 10)); } - const e = try Engine.init(gpa, io, argv[1], .{ .context = ctx, .tp = tp, .mtp = want_mtp }); + const e = try Engine.init(gpa, io, argv[1], .{ + .context = ctx, + .tp = tp, + .mtp = want_mtp, + .solo_rows = chunk, + .mtp_drafts = mtp_depth, + .mtp_conf = mtp_conf, + }); defer e.deinit(); e.r.ngram.waitWarm(); std.debug.print( - "loaded Qwen3.8-Flash-Next (tp={d}, mtp={}, vram/rank={d:.2} GiB, ple_ram={d:.2} GiB) in {d:.1} s\n", - .{ tp, e.head != null, @as(f64, @floatFromInt(e.allocatedBytesPerRank())) / (1 << 30), @as(f64, @floatFromInt(e.r.ngram.total_bytes)) / (1 << 30), e.load_seconds }, + "loaded Qwen3.8-Flash-Next (tp={d}, chunk={d}, mtp={}, vram/rank={d:.2} GiB, ple_ram={d:.2} GiB) in {d:.1} s\n", + .{ tp, e.solo_rows, e.head != null, @as(f64, @floatFromInt(e.allocatedBytesPerRank())) / (1 << 30), @as(f64, @floatFromInt(e.r.ngram.total_bytes)) / (1 << 30), e.load_seconds }, ); if (bench_lens.items.len > 0) { @@ -78,28 +88,31 @@ fn runIncrementalSweep(e: *Engine, lens: []const usize, steps: usize) !void { var cum_plain_sec: f64 = 0; var cum_mtp_sec: f64 = 0; + const step_cap: usize = e.solo_rows; for (lens, 0..) |target_n, idx| { std.debug.print("\n=== Bench prompt_len={d} ===\n", .{target_n}); var t = prev_n; - while (t + 64 < target_n) : (t += 64) { + while (t + step_cap < target_n) { + const n = @min(step_cap, target_n - t); const tp0 = eng.nowSec(); - try e.r.forwardPass(ids[t .. t + 64], true, .none, if (e.r.has_mtp) save_dsts else null); + try e.r.forwardPass(ids[t .. t + n], true, .none, if (e.r.has_mtp) save_dsts else null); e.m.pos = e.r.cur.pos; cum_plain_sec += eng.nowSec() - tp0; if (e.r.has_mtp) { const tm0 = eng.nowSec(); - _ = try e.r.forwardMtp(ids[t + 1 .. t + 65], save_dsts, t, false, false); + _ = try e.r.forwardMtp(ids[t + 1 .. t + 1 + n], save_dsts, t, false, false); cum_mtp_sec += eng.nowSec() - tm0; } + t += n; } - // Final 64-token chunk `[target_n - 64 .. target_n]` + // Final chunk `[t .. target_n]` (<= `e.solo_rows`) const tp0 = eng.nowSec(); try e.r.forwardPass(ids[t..target_n], true, .last, if (e.r.has_mtp) save_dsts else null); e.m.pos = e.r.cur.pos; const dt_last_plain = eng.nowSec() - tp0; var dt_last_mtp: f64 = 0; - if (e.r.has_mtp) { + if (e.r.has_mtp and t + 1 < target_n) { const tm0 = eng.nowSec(); _ = try e.r.forwardMtp(ids[t + 1 .. target_n], save_dsts, t, false, false); dt_last_mtp = eng.nowSec() - tm0; @@ -155,9 +168,10 @@ fn runIncrementalSweep(e: *Engine, lens: []const usize, steps: usize) !void { } fn prefillPlain(e: *Engine, prompt_ids: []const u32) !void { + const step: usize = e.solo_rows; var t: usize = 0; while (t < prompt_ids.len) { - const n = @min(@as(usize, 64), prompt_ids.len - t); + const n = @min(step, prompt_ids.len - t); const last = (t + n == prompt_ids.len); try e.r.forwardPass(prompt_ids[t .. t + n], true, if (last) .last else .none, null); e.m.pos = e.r.cur.pos; @@ -230,16 +244,15 @@ fn runVerifyTest(e: *Engine, prompt: []const u32, serial: []const u32) !void { fn runMtpBench(e: *Engine, prompt: []const u32, serial: []const u32) !void { try e.reset(); - try e.prefillSpan(prompt, 0, prompt.len, 64); + try e.prefillSpan(prompt, 0, prompt.len, e.solo_rows); var g0: [1]i32 = undefined; try e.rowTokens(&g0); try runMtpFromReady(e, @intCast(g0[0]), serial); } fn runMtpFromReady(e: *Engine, first_tok: u32, serial: []const u32) !void { - const env = @import("sys").environment; - const depth: u32 = try env.read(u32, "XPU_MTP_DEPTH", 6); - const conf: f64 = try env.read(f64, "XPU_MTP_CONF", -0.4); + const depth = e.mtp_drafts; + const conf = e.mtp_conf; var got: std.ArrayList(u32) = .empty; defer got.deinit(gpa); @@ -263,8 +276,8 @@ fn runMtpFromReady(e: *Engine, first_tok: u32, serial: []const u32) !void { const d0 = eng.nowSec(); const nd = if (first_round) blk: { first_round = false; - break :blk try draftWithConf(e, true, got.items[0], &.{}, 0, depth, conf, &drafts); - } else try draftWithConf(e, false, 0, prev_kept[0..prev_kept_n], prev_start, depth, conf, &drafts); + break :blk try e.draftFirst(got.items[0], depth, &drafts); + } else try e.draftKept(prev_kept[0..prev_kept_n], prev_start, depth, &drafts); const d1 = eng.nowSec(); t_draft += d1 - d0; @@ -321,48 +334,3 @@ fn runMtpFromReady(e: *Engine, first_tok: u32, serial: []const u32) !void { ); if (!same) return error.MtpSerialMismatch; } - -fn draftWithConf(e: *Engine, is_first: bool, first_tok: u32, follow: []const u32, start: u32, max_d: u32, conf: f64, out: []u32) !usize { - if (max_d == 0) return 0; - var st: [eng.ld.max_tp]*anyopaque = undefined; - const pk0 = if (is_first) blk: { - for (0..e.r.tp) |rk| st[rk] = e.r.cur.ranks[rk].last_streams; - break :blk (try e.r.forwardMtp(&.{first_tok}, st, e.m.pos - 1, true, true)).?; - } else blk: { - for (0..e.r.tp) |rk| st[rk] = e.r.cur.ranks[rk].verify_streams; - break :blk (try e.r.forwardMtp(follow, st, start, true, true)).?; - }; - - var prod: f64 = 1.0; - var n: usize = 0; - var cur = pk0; - var mtp_st: [eng.ld.max_tp]*anyopaque = undefined; - for (0..e.r.tp) |rk| mtp_st[rk] = e.r.cur.ranks[rk].mtp_out; - - var j: usize = 0; - while (j < @min(@as(usize, max_d), 15)) : (j += 1) { - var propose = true; - var more = true; - if (conf > 0) { - const low = cur.prob < conf; - if (low and j > 0) { - propose = false; - more = false; - } else { - more = !low; - } - } else if (conf < 0) { - prod *= cur.prob; - if (prod < -conf) { - propose = (j == 0); - more = false; - } - } - if (!propose) break; - out[n] = cur.token; - n += 1; - if (!more or j + 1 >= @min(@as(usize, max_d), 15)) break; - cur = (try e.r.forwardMtp(out[n - 1 .. n], mtp_st, e.m.pos + (n - 1), true, true)).?; - } - return n; -} diff --git a/zig/src/families/flashnext/xpu_ops.zig b/zig/src/families/flashnext/xpu_ops.zig index a7769b411f4..250993274d2 100644 --- a/zig/src/families/flashnext/xpu_ops.zig +++ b/zig/src/families/flashnext/xpu_ops.zig @@ -24,6 +24,7 @@ const max_attn_slices = ld.max_attn_slices; const ple_tail_n = ld.ple_tail_n; const max_tp = ld.max_tp; const max_verify_rows = ld.max_verify_rows; +const attn_tile_rows = ld.attn_tile_rows; const Dev = ld.Dev; const Q4 = ld.Q4; const HcW = ld.HcW; @@ -39,8 +40,14 @@ pub fn linearBf16(d: *Dev, q: Q4, x: *anyopaque, y: *anyopaque, rows: usize) !vo const k_i: i32 = @intCast(q.k); const n_i: i32 = @intCast(q.n); const r_i: i32 = @intCast(rows); - if (rows <= 16) { - try d.launch(d.k.qmv_bf16, .{ .x = @intCast((q.n + 15) / 16), .y = @intCast((rows + 15) / 16) }, .{ q.w.?, q.s.?, q.b.?, x, y, k_i, n_i, r_i }); + const groups = q.k / 32; + const split4 = (groups >= 16) and ((groups & 3) == 0); + const nb_total = (q.n + 15) / 16; + const gx_small: u32 = @intCast(if (split4) nb_total else (nb_total + 3) / 4); + if (rows == 1) { + try d.launch(d.k.qmv1_bf16, .{ .x = gx_small }, .{ q.w.?, q.s.?, q.b.?, x, y, k_i, n_i }); + } else if (rows <= 16) { + try d.launch(d.k.qmv16_bf16, .{ .x = gx_small, .y = 1 }, .{ q.w.?, q.s.?, q.b.?, x, y, k_i, n_i, r_i }); } else { try d.launch(d.k.qmm_bf16, .{ .x = @intCast((q.n + 63) / 64), .y = @intCast((rows + 31) / 32) }, .{ q.w.?, q.s.?, q.b.?, x, y, k_i, n_i, r_i }); } @@ -51,29 +58,38 @@ pub fn linearF32(d: *Dev, q: Q4, x: *anyopaque, y: *anyopaque, rows: usize) !voi const k_i: i32 = @intCast(q.k); const n_i: i32 = @intCast(q.n); const r_i: i32 = @intCast(rows); - if (rows <= 16) { - try d.launch(d.k.qmv_f32, .{ .x = @intCast((q.n + 15) / 16), .y = @intCast((rows + 15) / 16) }, .{ q.w.?, q.s.?, q.b.?, x, y, k_i, n_i, r_i }); + const groups = q.k / 32; + const split4 = (groups >= 16) and ((groups & 3) == 0); + const nb_total = (q.n + 15) / 16; + const gx_small: u32 = @intCast(if (split4) nb_total else (nb_total + 3) / 4); + if (rows == 1) { + try d.launch(d.k.qmv1_f32, .{ .x = gx_small }, .{ q.w.?, q.s.?, q.b.?, x, y, k_i, n_i }); + } else if (rows <= 16) { + try d.launch(d.k.qmv16_f32, .{ .x = gx_small, .y = 1 }, .{ q.w.?, q.s.?, q.b.?, x, y, k_i, n_i, r_i }); } else { try d.launch(d.k.qmm_f32, .{ .x = @intCast((q.n + 63) / 64), .y = @intCast((rows + 31) / 32) }, .{ q.w.?, q.s.?, q.b.?, x, y, k_i, n_i, r_i }); } } pub fn hcReadout(d: *Dev, a: *RankActs, hc: HcW, h_ptr: *anyopaque, br_ptr: *anyopaque, inj_in: *anyopaque, has_br: i32, rows: usize) !void { - try d.launch(d.k.hc_writeback_norm, .{ .x = @intCast(rows) }, .{ h_ptr, br_ptr, inj_in, hc.scale, a.norm, eps, has_br }); + try d.launch(d.k.hc_writeback_norm, .{ .x = 4, .y = @intCast(rows) }, .{ h_ptr, br_ptr, inj_in, hc.scale, a.norm, eps, has_br }); const ndn_i: i32 = @intCast(hc.n_down); const r_i: i32 = @intCast(rows); if (rows <= 16) { - try d.launch(d.k.hc_down_reduce, .{ .x = @intCast(hc.n_down), .y = @intCast((rows + 15) / 16) }, .{ - a.norm, hc.down.w.?, hc.down.s.?, hc.down.b.?, a.act, a.inj, r_i, ndn_i, hc.has_inj, + try d.launch(d.k.hc_down_1, .{ .x = @intCast((hc.n_down + 15) / 16), .y = @intCast(rows) }, .{ + a.norm, hc.down.w.?, hc.down.s.?, hc.down.b.?, a.act, a.inj, ndn_i, hc.has_inj, + }); + try d.launch(d.k.hc_upmix_1, .{ .x = dims / 64, .y = @intCast(rows) }, .{ + a.act, a.norm, hc.up.w.?, hc.up.s.?, hc.up.b.?, a.mixed, }); } else { - try d.launch(d.k.hc_down_dpas, .{ .x = @intCast((hc.n_down + 63) / 64), .y = @intCast((rows + 31) / 32) }, .{ + try d.launch(d.k.hc_down_wide, .{ .x = @intCast((hc.n_down + 63) / 64), .y = @intCast((rows + 31) / 32) }, .{ a.norm, hc.down.w.?, hc.down.s.?, hc.down.b.?, a.act, a.inj, r_i, ndn_i, hc.has_inj, }); + try d.launch(d.k.hc_upmix_dpas, .{ .x = dims / 64, .y = @intCast((rows + 31) / 32) }, .{ + a.act, a.norm, hc.up.w.?, hc.up.s.?, hc.up.b.?, a.mixed, r_i, + }); } - try d.launch(d.k.hc_upmix, .{ .x = dims / 16, .y = @intCast((rows + 15) / 16) }, .{ - a.act, a.norm, hc.up.w.?, hc.up.s.?, hc.up.b.?, a.mixed, r_i, - }); } pub fn gdnRank(r: *Runner, rk: usize, lw: *const LayerW, li: usize, rs: *RankSeq, rows: usize, inplace: bool, out_f32: *anyopaque) !void { @@ -130,30 +146,41 @@ pub fn attnRank(r: *Runner, rk: usize, lw: *const LayerW, kc: *anyopaque, vc: *a } const nb_max: i32 = @intCast(@max((r.max_len + index_ratio - 1) / index_ratio, 64)); - const complete_max = (pos0 + rows) / index_ratio; - if (complete_max > ld.index_top) { - try d.launch(d.k.qsa_scores, .{ .x = @intCast(rows), .y = @intCast((complete_max + 15) / 16) }, .{ - a.iq, pooled, pos0_i, a.qsa_sc, nb_max, + var r0: usize = 0; + while (r0 < rows) : (r0 += attn_tile_rows) { + const sub = @min(attn_tile_rows, rows - r0); + const sub_pos0 = pos0 + r0; + const sub_pos0_i: i32 = @intCast(sub_pos0); + const iq_s = off(a.iq, r0 * index_heads * index_dim * 2); + const q_s = off(a.q, r0 * shp.nq * head_dim * 2); + const ao_s = off(a.ao, r0 * shp.nq * head_dim * 2); + const proj_s = off(a.proj, r0 * shp.attn_pw * 2); + const ag_s = off(a.agated, r0 * shp.attn_odim * 2); + + const complete_max = (sub_pos0 + sub) / index_ratio; + if (complete_max > ld.index_top) { + try d.launch(d.k.qsa_scores, .{ .x = @intCast((sub + 15) / 16), .y = @intCast((complete_max + 63) / 64) }, .{ + iq_s, pooled, sub_pos0_i, a.qsa_sc, nb_max, @as(i32, @intCast(sub)), + }); + } + try d.launch(d.k.qsa_select, .{ .x = @intCast(sub) }, .{ + a.qsa_sc, sub_pos0_i, a.qsa_ids, a.qsa_nkr, a.qsa_spr, nb_max, }); - } - try d.launch(d.k.qsa_select, .{ .x = @intCast(rows) }, .{ - a.qsa_sc, pos0_i, a.qsa_ids, a.qsa_nkr, a.qsa_spr, nb_max, - }); - - const max_nkeys = @min(pos0 + rows, 2051); - const ns = @max((max_nkeys + 31) / 32, 1); - const ns_i: i32 = @intCast(ns); + const max_nkeys = @min(sub_pos0 + sub, 2051); + const ns = @max((max_nkeys + 31) / 32, 1); + const ns_i: i32 = @intCast(ns); - try d.launch(d.k.attn_sparse, .{ .x = @intCast(ns), .y = @intCast(shp.nq), .z = @intCast(rows) }, .{ - a.q, kc, vc, a.qsa_ids, a.qsa_nkr, a.qsa_spr, a.pm, a.pl, a.po, ns_i, nq_i, nkv_i, - }); - try d.launch(d.k.attn_merge, .{ .x = @intCast(shp.nq), .y = @intCast(rows) }, .{ - a.pm, a.pl, a.po, a.qsa_nkr, a.ao, ns_i, nq_i, - }); - try d.launch(d.k.attn_gate, .{ .x = @intCast(rows), .y = @intCast(shp.nq) }, .{ - a.ao, a.proj, a.agated, pw_i, nq_i, - }); + try d.launch(d.k.attn_sparse, .{ .x = @intCast(ns), .y = @intCast(shp.nq), .z = @intCast(sub) }, .{ + q_s, kc, vc, a.qsa_ids, a.qsa_nkr, a.qsa_spr, a.pm, a.pl, a.po, ns_i, nq_i, nkv_i, + }); + try d.launch(d.k.attn_merge, .{ .x = @intCast(shp.nq), .y = @intCast(sub) }, .{ + a.pm, a.pl, a.po, a.qsa_nkr, ao_s, ns_i, nq_i, + }); + try d.launch(d.k.attn_gate, .{ .x = @intCast(sub), .y = @intCast(shp.nq) }, .{ + ao_s, proj_s, ag_s, pw_i, nq_i, + }); + } try linearF32(d, lw.out, a.agated, out_f32, rows); } @@ -166,32 +193,47 @@ pub fn moeRank(r: *Runner, rk: usize, lw: *const LayerW, rows: usize, out_f32: * const local_e: i32 = @intCast(shp.local_e); const sh_w_i: i32 = @intCast(shp.sh_w); - try d.launch(d.k.router_logits, .{ .x = (513 + 3) / 4, .y = @intCast(rows) }, .{ a.mixed, lw.router, a.router_l, r_i }); + if (rows <= 16) { + try d.launch(d.k.router_1, .{ .x = 33, .y = @intCast(rows) }, .{ a.mixed, lw.router, a.router_l }); + } else { + try d.launch(d.k.router_mm, .{ .x = 9, .y = @intCast((rows + 31) / 32) }, .{ a.mixed, lw.router, a.router_l, r_i }); + } try d.launch(d.k.route_topk, .{ .x = @intCast(rows) }, .{ a.router_l, a.picks, a.wts }); try d.launch(d.k.moe_compact, .{ .x = 1 }, .{ a.picks, a.active, a.exp_grp, a.n_act, a.row_list, r_i, first_e, local_e }); - try d.launch(d.k.moe_routed_up, .{ .x = moe_w / 16, .y = @intCast(rows * 10) }, .{ - a.mixed, a.active, a.exp_grp, a.n_act, - lw.routed_gate.w.?, lw.routed_gate.s.?, lw.routed_gate.b.?, lw.routed_up.w.?, - lw.routed_up.s.?, lw.routed_up.b.?, a.moe_act, - }); - if (shp.sh_w > 0) { - try d.launch(d.k.moe_shared_up, .{ .x = @intCast((shp.sh_w + 15) / 16), .y = @intCast((rows + 15) / 16) }, .{ - a.mixed, - lw.shared_gate.w.?, - lw.shared_gate.s.?, - lw.shared_gate.b.?, - lw.shared_up.w.?, - lw.shared_up.s.?, - lw.shared_up.b.?, - a.sh_act, - sh_w_i, - r_i, + + if (rows <= 16) { + const max_p: u32 = @intCast(rows * @min(@as(usize, 10), shp.local_e)); + try d.launch(d.k.moe_up_1, .{ .x = moe_w / 16, .y = max_p }, .{ + a.mixed, a.active, a.n_act, lw.routed_gate.w.?, lw.routed_gate.s.?, lw.routed_gate.b.?, lw.routed_up.w.?, lw.routed_up.s.?, lw.routed_up.b.?, a.moe_act, + }); + try d.launch(d.k.moe_down_1, .{ .x = dims / 16, .y = max_p }, .{ + a.moe_act, a.active, a.n_act, lw.routed_down.w.?, lw.routed_down.s.?, lw.routed_down.b.?, a.moe_down, + }); + } else { + const max_grp: u32 = @intCast(@min(rows * 10, shp.local_e + (rows * 10) / 32)); + try d.launch(d.k.moe_up_dpas, .{ .x = moe_w / 64, .y = max_grp }, .{ + a.mixed, a.active, a.exp_grp, a.n_act, lw.routed_gate.w.?, lw.routed_gate.s.?, lw.routed_gate.b.?, lw.routed_up.w.?, lw.routed_up.s.?, lw.routed_up.b.?, a.moe_act, + }); + try d.launch(d.k.moe_down_dpas, .{ .x = dims / 64, .y = max_grp }, .{ + a.moe_act, a.exp_grp, a.n_act, lw.routed_down.w.?, lw.routed_down.s.?, lw.routed_down.b.?, a.moe_down, }); } - try d.launch(d.k.moe_down_combine, .{ .x = dims / 16, .y = @intCast(rows) }, .{ - a.moe_act, a.sh_act, a.active, a.row_list, a.wts, - lw.routed_down.w.?, lw.routed_down.s.?, lw.routed_down.b.?, lw.shared_down.w.?, lw.shared_down.s.?, - lw.shared_down.b.?, out_f32, sh_w_i, r_i, + + if (shp.sh_w > 0) { + if (rows <= 16) { + try d.launch(d.k.moe_sh_up_1, .{ .x = @intCast(shp.sh_w / 16), .y = @intCast(rows) }, .{ + a.mixed, lw.shared_gate.w.?, lw.shared_gate.s.?, lw.shared_gate.b.?, lw.shared_up.w.?, lw.shared_up.s.?, lw.shared_up.b.?, a.sh_act, sh_w_i, + }); + } else { + try d.launch(d.k.moe_sh_up_dpas, .{ .x = @intCast((shp.sh_w + 31) / 32), .y = @intCast((rows + 31) / 32) }, .{ + a.mixed, lw.shared_gate.w.?, lw.shared_gate.s.?, lw.shared_gate.b.?, lw.shared_up.w.?, lw.shared_up.s.?, lw.shared_up.b.?, a.sh_act, sh_w_i, r_i, + }); + } + try linearF32(d, lw.shared_down, a.sh_act, a.sh_out, rows); + } + + try d.launch(d.k.moe_combine, .{ .x = dims / 256, .y = @intCast(rows) }, .{ + a.moe_down, a.sh_out, a.active, a.row_list, a.wts, out_f32, @as(i32, @intFromBool(shp.sh_w > 0)), r_i, }); } @@ -295,8 +337,8 @@ pub fn attnMultiRank(r: *Runner, rk: usize, lw: *const LayerW, ai: usize, seqs: } const complete_max = (pos0 + m) / index_ratio; if (complete_max > ld.index_top) { - try d.launch(d.k.qsa_scores, .{ .x = @intCast(m), .y = @intCast((complete_max + 15) / 16) }, .{ - iq_s, rs.pooled[ai], pos0_i, sc_s, nb_max, + try d.launch(d.k.qsa_scores, .{ .x = @intCast((m + 15) / 16), .y = @intCast((complete_max + 63) / 64) }, .{ + iq_s, rs.pooled[ai], pos0_i, sc_s, nb_max, m_i, }); } try d.launch(d.k.qsa_select, .{ .x = @intCast(m) }, .{ sc_s, pos0_i, ids_s, nkr_s, spr_s, nb_max }); diff --git a/zig/src/families/flashnext/xpu_ple.zig b/zig/src/families/flashnext/xpu_ple.zig index 4e815436838..db20c86c68a 100644 --- a/zig/src/families/flashnext/xpu_ple.zig +++ b/zig/src/families/flashnext/xpu_ple.zig @@ -19,8 +19,8 @@ fn f32FromBf16(b: []const u8, i: usize) f32 { return @bitCast(@as(u32, std.mem.readInt(u16, b[2 * i ..][0..2], .little)) << 16); } -/// Dequantize one MLX affine 4-bit group-32 row (`token`) of width `dims` into `out` (bf16 bits). -pub fn dequantRow(weight: []const u8, scales: []const u8, biases: []const u8, dims: usize, token: usize, out: []u16) !void { +/// Dequantize one MLX affine 4-bit group-32 row (`token`) of width `dims` into `out` (bf16 bits), folding `w_scale`. +pub fn dequantRow(weight: []const u8, scales: []const u8, biases: []const u8, dims: usize, token: usize, w_scale: f32, out: []u16) !void { if (dims == 0 or dims % 32 != 0 or out.len != dims) return error.UnexpectedTensor; const groups = dims / 32; const words = dims / 8; @@ -34,7 +34,8 @@ pub fn dequantRow(weight: []const u8, scales: []const u8, biases: []const u8, di const word = std.mem.readInt(u32, weight[woff + (g * 4 + i) * 4 ..][0..4], .little); for (0..8) |j| { const q: f32 = @floatFromInt((word >> @intCast(j * 4)) & 0xF); - out[g * 32 + i * 8 + j] = toBf16(q * scale + bias); + const raw = toBf16(q * scale + bias); + out[g * 32 + i * 8 + j] = if (w_scale == 1.0) raw else toBf16(@as(f32, @bitCast(@as(u32, raw) << 16)) * w_scale); } } } @@ -432,7 +433,7 @@ pub const Ngram = struct { for (lo..hi) |i| { const loc = try g.hash.locate(ids[i]); const row = out[i * dh ..][0..dh]; - try dequantRow(g.w[loc.shard], g.s[loc.shard], g.b[loc.shard], dh, loc.local, row); + try dequantRow(g.w[loc.shard], g.s[loc.shard], g.b[loc.shard], dh, loc.local, g.scale, row); } } @@ -471,12 +472,6 @@ pub const Ngram = struct { const split: Split = .{ .g = g, .ids = ids, .out = out, .per = (items + n_threads - 1) / n_threads }; try g.pool.?.run(n_threads, .{ .ctx = &split, .run = Split.part }); } - if (g.scale != 1.0) { - for (out) |*v| { - const f: f32 = @bitCast(@as(u32, v.*) << 16); - v.* = toBf16(f * g.scale); - } - } @memcpy(history, hist[0..history.len]); } }; diff --git a/zig/src/families/flashnext/xpu_state.zig b/zig/src/families/flashnext/xpu_state.zig index 362fb266629..c312c2fa575 100644 --- a/zig/src/families/flashnext/xpu_state.zig +++ b/zig/src/families/flashnext/xpu_state.zig @@ -24,7 +24,7 @@ const ple_tail_n = ld.ple_tail_n; const gdn_taps = ld.gdn_taps; const max_tp = ld.max_tp; const max_verify_rows = ld.max_verify_rows; -const chunk_rows = ld.chunk_rows; +const attn_tile_rows = ld.attn_tile_rows; const Dev = ld.Dev; const TpShape = ld.TpShape; @@ -127,9 +127,11 @@ pub const RankActs = struct { active: *anyopaque, // [chunk_rows * 10] i32 exp_grp: *anyopaque, // [chunk_rows * 10] i32 n_act: *anyopaque, // [4] i32 - row_list: *anyopaque, // [chunk_rows * 11] i32 - moe_act: *anyopaque, // [chunk_rows * 10, 640] bf16 - sh_act: *anyopaque, // [chunk_rows, sh_w] bf16 + row_list: *anyopaque, // [chunk_cap * 11] i32 + moe_act: *anyopaque, // [chunk_cap * 10, 640] bf16 + moe_down: *anyopaque, // [chunk_cap * 10, 2560] f32 + sh_act: *anyopaque, // [chunk_cap, sh_w] bf16 + sh_out: *anyopaque, // [chunk_cap, 2560] f32 // Logits & Draft Head scratch shard_logits: *anyopaque, // [max_verify_rows, vocab_per] bf16 shard_dlogits: ?*anyopaque = null, // [1, draft_len] bf16 @@ -155,52 +157,55 @@ pub fn allocHostSlice(comptime T: type, d0: *Dev, gpus: []ze.Gpu, count: usize) return slice; } -pub fn allocRankActs(d: *Dev, shp: TpShape, rk: usize, nb_max: usize, draft_total: usize, has_mtp: bool) !RankActs { +pub fn allocRankActs(d: *Dev, shp: TpShape, rk: usize, chunk_cap: usize, nb_max: usize, draft_total: usize, has_mtp: bool) !RankActs { const max_pw = @max(shp.gdn_pw, shp.attn_pw); + const mtp_fc_rows = streams * chunk_cap; var a: RankActs = .{ - .ids = try d.allocZero(chunk_rows * 4), + .ids = try d.allocZero(chunk_cap * 4), .dummy = try d.allocZero(4096), - .h = try d.allocZero(chunk_rows * wide * 2), - .prompt_streams = try d.allocZero(chunk_rows * wide * 2), - .norm = try d.allocZero(chunk_rows * wide * 2), - .act = try d.allocZero(chunk_rows * low * 2), - .inj = try d.allocZero(chunk_rows * streams * 2), - .mixed = try d.allocZero(chunk_rows * dims * 2), - .branch = try d.allocZero(chunk_rows * dims * 4), - .mtp_branch = try d.allocZero(chunk_rows * dims * 2), - .proj = try d.allocZero(chunk_rows * max_pw * 2), - .ple_emb = try d.allocZero(chunk_rows * dims * 2), - .ple_keys = try d.allocZero(chunk_rows * wide * 2), - .ple_vals = try d.allocZero(chunk_rows * dims * 2), - .ple_gated = try d.allocZero(chunk_rows * wide * 2), - .ple_pss = try d.allocZero(chunk_rows * streams * 4), - .ple_nrow = try d.allocZero(chunk_rows * wide * 2), - .gq = try d.allocZero(chunk_rows * shp.nk * 128 * 4), - .gk = try d.allocZero(chunk_rows * shp.nk * 128 * 4), - .gv = try d.allocZero(chunk_rows * shp.nv * 128 * 4), - .ggb = try d.allocZero(chunk_rows * shp.nv * 2 * 4), - .ys = try d.allocZero(chunk_rows * shp.nv * 128 * 4), - .gout = try d.allocZero(chunk_rows * shp.gdn_vdim * 2), - .q = try d.allocZero(chunk_rows * shp.nq * head_dim * 2), - .iq = try d.allocZero(chunk_rows * index_heads * index_dim * 2), - .qsa_sc = try d.allocZero(chunk_rows * nb_max * 4), - .qsa_ids = try d.allocZero(chunk_rows * index_idw * 4), - .qsa_nkr = try d.allocZero(chunk_rows * 4), - .qsa_spr = try d.allocZero(chunk_rows * 4), - .pm = try d.allocZero(chunk_rows * shp.nq * max_attn_slices * 4), - .pl = try d.allocZero(chunk_rows * shp.nq * max_attn_slices * 4), - .po = try d.allocZero(chunk_rows * shp.nq * max_attn_slices * head_dim * 4), - .ao = try d.allocZero(chunk_rows * shp.nq * head_dim * 2), - .agated = try d.allocZero(chunk_rows * shp.attn_odim * 2), - .router_l = try d.allocZero(chunk_rows * 513 * 4), - .picks = try d.allocZero(chunk_rows * slots * 4), - .wts = try d.allocZero(chunk_rows * slots * 4), - .active = try d.allocZero(chunk_rows * 10 * 4), - .exp_grp = try d.allocZero(chunk_rows * 10 * 4), + .h = try d.allocZero(chunk_cap * wide * 2), + .prompt_streams = try d.allocZero(chunk_cap * wide * 2), + .norm = try d.allocZero(chunk_cap * wide * 2), + .act = try d.allocZero(chunk_cap * low * 2), + .inj = try d.allocZero(chunk_cap * streams * 2), + .mixed = try d.allocZero(chunk_cap * dims * 2), + .branch = try d.allocZero(chunk_cap * dims * 4), + .mtp_branch = try d.allocZero(chunk_cap * dims * 2), + .proj = try d.allocZero(chunk_cap * max_pw * 2), + .ple_emb = try d.allocZero(chunk_cap * dims * 2), + .ple_keys = try d.allocZero(chunk_cap * wide * 2), + .ple_vals = try d.allocZero(chunk_cap * dims * 2), + .ple_gated = try d.allocZero(mtp_fc_rows * dims * 2), + .ple_pss = try d.allocZero(chunk_cap * streams * 4), + .ple_nrow = try d.allocZero(chunk_cap * wide * 2), + .gq = try d.allocZero(chunk_cap * shp.nk * 128 * 4), + .gk = try d.allocZero(chunk_cap * shp.nk * 128 * 4), + .gv = try d.allocZero(chunk_cap * shp.nv * 128 * 4), + .ggb = try d.allocZero(chunk_cap * shp.nv * 2 * 4), + .ys = try d.allocZero(chunk_cap * shp.nv * 128 * 4), + .gout = try d.allocZero(chunk_cap * shp.gdn_vdim * 2), + .q = try d.allocZero(chunk_cap * shp.nq * head_dim * 2), + .iq = try d.allocZero(chunk_cap * index_heads * index_dim * 2), + .qsa_sc = try d.allocZero(attn_tile_rows * nb_max * 4), + .qsa_ids = try d.allocZero(attn_tile_rows * index_idw * 4), + .qsa_nkr = try d.allocZero(attn_tile_rows * 4), + .qsa_spr = try d.allocZero(attn_tile_rows * 4), + .pm = try d.allocZero(attn_tile_rows * shp.nq * max_attn_slices * 4), + .pl = try d.allocZero(attn_tile_rows * shp.nq * max_attn_slices * 4), + .po = try d.allocZero(attn_tile_rows * shp.nq * max_attn_slices * head_dim * 4), + .ao = try d.allocZero(chunk_cap * shp.nq * head_dim * 2), + .agated = try d.allocZero(chunk_cap * shp.attn_odim * 2), + .router_l = try d.allocZero(chunk_cap * 513 * 4), + .picks = try d.allocZero(chunk_cap * slots * 4), + .wts = try d.allocZero(chunk_cap * slots * 4), + .active = try d.allocZero(chunk_cap * 10 * 4), + .exp_grp = try d.allocZero(chunk_cap * 10 * 4), .n_act = try d.allocZero(16), - .row_list = try d.allocZero(chunk_rows * slots * 4), - .moe_act = try d.allocZero(chunk_rows * 10 * moe_w * 2), - .sh_act = try d.allocZero(chunk_rows * shp.sh_w * 2), + .row_list = try d.allocZero(chunk_cap * slots * 4), + .moe_act = try d.allocZero(chunk_cap * 10 * moe_w * 2), + .moe_down = try d.allocZero(chunk_cap * 10 * dims * 4), + .sh_act = try d.allocZero(chunk_cap * @max(shp.sh_w, 16) * 2), + .sh_out = try d.allocZero(chunk_cap * dims * 4), .shard_logits = try d.allocZero(max_verify_rows * shp.vocab_per * 2), }; if (has_mtp) { diff --git a/zig/src/families/flashnext/xpu_store.zig b/zig/src/families/flashnext/xpu_store.zig index c2477765db3..ff3e380202d 100644 --- a/zig/src/families/flashnext/xpu_store.zig +++ b/zig/src/families/flashnext/xpu_store.zig @@ -34,6 +34,9 @@ pub const gdn_taps: usize = 4; pub const max_tp: usize = 4; pub const max_verify_rows: usize = 16; pub const chunk_rows: usize = 64; +pub const default_solo_rows: usize = 2048; +pub const max_chunk_rows: usize = 2048; +pub const attn_tile_rows: usize = 64; pub const Tensor = core.safetensors.Tensor; @@ -111,11 +114,14 @@ pub const Kernels = struct { add_streams: ze.H, hc_writeback_norm: ze.H, hc_writeback_only: ze.H, - hc_down_reduce: ze.H, - hc_down_dpas: ze.H, - hc_upmix: ze.H, - qmv_bf16: ze.H, - qmv_f32: ze.H, + hc_down_1: ze.H, + hc_down_wide: ze.H, + hc_upmix_1: ze.H, + hc_upmix_dpas: ze.H, + qmv1_bf16: ze.H, + qmv1_f32: ze.H, + qmv16_bf16: ze.H, + qmv16_f32: ze.H, qmm_bf16: ze.H, qmm_f32: ze.H, ple_gate: ze.H, @@ -131,12 +137,17 @@ pub const Kernels = struct { attn_sparse: ze.H, attn_merge: ze.H, attn_gate: ze.H, - router_logits: ze.H, + router_1: ze.H, + router_mm: ze.H, route_topk: ze.H, moe_compact: ze.H, - moe_routed_up: ze.H, - moe_shared_up: ze.H, - moe_down_combine: ze.H, + moe_up_1: ze.H, + moe_up_dpas: ze.H, + moe_down_1: ze.H, + moe_down_dpas: ze.H, + moe_sh_up_1: ze.H, + moe_sh_up_dpas: ze.H, + moe_combine: ze.H, logits_part: ze.H, logits_best: ze.H, topk64_part: ze.H, @@ -162,13 +173,16 @@ pub const Dev = struct { .add_streams = try d.loadK(m, "fn_add_streams", 256), .hc_writeback_norm = try d.loadK(m, "fn_hc_writeback_norm", 256), .hc_writeback_only = try d.loadK(m, "fn_hc_writeback_only", 256), - .hc_down_reduce = try d.loadK(m, "fn_hc_down_reduce", 64), - .hc_down_dpas = try d.loadK(m, "fn_hc_down_dpas", 128), - .hc_upmix = try d.loadK(m, "fn_hc_upmix", 256), - .qmv_bf16 = try d.loadK(m, "fn_qmv4_g32_bf16", 256), - .qmv_f32 = try d.loadK(m, "fn_qmv4_g32_f32", 256), - .qmm_bf16 = try d.loadK(m, "fn_qmm4_g32_dpas_bf16", 128), - .qmm_f32 = try d.loadK(m, "fn_qmm4_g32_dpas_f32", 128), + .hc_down_1 = try d.loadK(m, "fn_hc_down_1", 64), + .hc_down_wide = try d.loadK(m, "fn_hc_down_wide", 128), + .hc_upmix_1 = try d.loadK(m, "fn_hc_upmix_1", 64), + .hc_upmix_dpas = try d.loadK(m, "fn_hc_upmix_dpas", 128), + .qmv1_bf16 = try d.loadK(m, "fn_qmv1_dpas_bf16", 64), + .qmv1_f32 = try d.loadK(m, "fn_qmv1_dpas_f32", 64), + .qmv16_bf16 = try d.loadK(m, "fn_qmv16_dpas_bf16", 64), + .qmv16_f32 = try d.loadK(m, "fn_qmv16_dpas_f32", 64), + .qmm_bf16 = try d.loadK(m, "fn_qmm_tile_dpas_bf16", 128), + .qmm_f32 = try d.loadK(m, "fn_qmm_tile_dpas_f32", 128), .ple_gate = try d.loadK(m, "fn_ple_gate", 512), .ple_conv = try d.loadK(m, "fn_ple_conv", 512), .shift_window = try d.loadK(m, "fn_shift_window", 256), @@ -182,12 +196,17 @@ pub const Dev = struct { .attn_sparse = try d.loadK(m, "fn_attn_sparse", 16), .attn_merge = try d.loadK(m, "fn_attn_merge", 16), .attn_gate = try d.loadK(m, "fn_attn_gate", 256), - .router_logits = try d.loadK(m, "fn_router_logits", 64), + .router_1 = try d.loadK(m, "fn_router_dpas_1", 64), + .router_mm = try d.loadK(m, "fn_router_dpas_mm", 128), .route_topk = try d.loadK(m, "fn_route_topk", 128), - .moe_compact = try d.loadK(m, "fn_moe_compact", 128), - .moe_routed_up = try d.loadK(m, "fn_moe_routed_up", 256), - .moe_shared_up = try d.loadK(m, "fn_moe_shared_up", 256), - .moe_down_combine = try d.loadK(m, "fn_moe_down_combine", 256), + .moe_compact = try d.loadK(m, "fn_moe_compact", 256), + .moe_up_1 = try d.loadK(m, "fn_moe_up_1", 64), + .moe_up_dpas = try d.loadK(m, "fn_moe_up_dpas", 256), + .moe_down_1 = try d.loadK(m, "fn_moe_down_1", 64), + .moe_down_dpas = try d.loadK(m, "fn_moe_down_dpas", 128), + .moe_sh_up_1 = try d.loadK(m, "fn_moe_sh_up_1", 64), + .moe_sh_up_dpas = try d.loadK(m, "fn_moe_sh_up_dpas", 128), + .moe_combine = try d.loadK(m, "fn_moe_combine", 256), .logits_part = try d.loadK(m, "fn_logits_part", 256), .logits_best = try d.loadK(m, "fn_logits_best", 256), .topk64_part = try d.loadK(m, "fn_topk64_part", 64), diff --git a/zig/src/families/gemma4/gemma4.zig b/zig/src/families/gemma4/gemma4.zig index 75b13955841..67d7e2f7cf6 100644 --- a/zig/src/families/gemma4/gemma4.zig +++ b/zig/src/families/gemma4/gemma4.zig @@ -28,6 +28,7 @@ test { _ = image; _ = snapshot; _ = vision; + _ = weights; } pub const affine_mm = @import("affine_mm.zig"); diff --git a/zig/src/families/gemma4/model.zig b/zig/src/families/gemma4/model.zig index d9eeef3b66a..06cb8ef89bb 100644 --- a/zig/src/families/gemma4/model.zig +++ b/zig/src/families/gemma4/model.zig @@ -97,8 +97,10 @@ pub const Model = struct { errdefer m.checkpoint.deinit(); const files = try shards.shardFiles(gpa, io, dir); defer shards.freeShardFiles(gpa, files); - for (files) |path| try m.checkpoint.addFileSelected(m.device, path, "", "language_model."); + // the layers' linears stay in their files, read once into the packs: the shards keep the embed and norms alone + for (files) |path| try m.checkpoint.addFileSplit(m.device, path, "", "language_model.", weights.later); m.weights = try weights.load(gpa, m.device, &m.checkpoint, m.config.geo, &m.config.widths); + m.checkpoint.closeFiles(); errdefer m.weights.deinit(gpa); m.kernels = try kernels.Kernels.init(gpa, m.device, m.config.geo, m.weights.embed_bits); errdefer m.kernels.deinit(); @@ -148,6 +150,11 @@ pub const Model = struct { m.mm[i] = ps; } + /// Bytes a whole-span load held that this one does not: the linears' shard span, and the row path's copies. + pub fn released(m: *const Model) u64 { + return (m.checkpoint.selected_bytes -| m.checkpoint.residentBytes()) + m.weights.aliased; + } + /// affine_mm's pipelines for a linear of `bits`. pub fn pipes(m: *const Model, bits: u8) affine_mm.Pipes { return m.mm[std.mem.indexOfScalar(u8, &cfg.widths.bit_widths, bits).?].?; diff --git a/zig/src/families/gemma4/weights.zig b/zig/src/families/gemma4/weights.zig index 483a109f674..365fcacd375 100644 --- a/zig/src/families/gemma4/weights.zig +++ b/zig/src/families/gemma4/weights.zig @@ -121,6 +121,8 @@ pub const Weights = struct { embed_b: Ref, final_norm: Ref, owned: std.ArrayList(mtl.Buffer) = .empty, + /// Bytes the row path's aliases save: the per-member copies (`mlxCopy`) main also made without tensor units. + aliased: u64 = 0, pub fn deinit(w: *Weights, gpa: std.mem.Allocator) void { for (w.owned.items) |b| b.deinit(); @@ -128,34 +130,157 @@ pub const Weights = struct { } }; +/// Tensors left in their files at load (checkpoint_metal's `later`): the layers' linears, read once through a Stage. +pub fn later(name: []const u8, _: usize) bool { + const dot = std.mem.lastIndexOfScalar(u8, name, '.') orelse return false; + const leaf = name[dot + 1 ..]; + const linear = std.mem.eql(u8, leaf, "weight") or std.mem.eql(u8, leaf, "scales") or std.mem.eql(u8, leaf, "biases"); + return linear and std.mem.indexOf(u8, name, ".layers.") != null and std.mem.endsWith(u8, name[0..dot], "_proj"); +} + +/// The load's reader: kept tensors where they are, the linears staged from their files. +const Src = struct { + c: *const ckpt.Checkpoint, + stage: *Stage, + + /// A tensor's dtype and shape, kept or in its file. + fn meta(r: Src, name: []const u8) !ckpt.Deferred { + if (r.c.tensors.get(name)) |t| return .{ .file = 0, .at = 0, .bytes = t.bytes, .dtype = t.dtype, .shape = t.shape, .rank = t.rank }; + return r.c.deferred.get(name) orelse { + std.log.err("checkpoint has no tensor {s}", .{name}); + return error.MissingTensor; + }; + } +}; + +/// The linears' staging in host memory, not a Metal buffer: load makes its Metal buffers in main's order, no holes. +pub const Stage = struct { + gpa: std.mem.Allocator, + mem: []align(ckpt.alignment) u8 = &.{}, + used: usize = 0, + + /// A staged or kept tensor's bytes, valid until `reset`. + pub const View = struct { + base: [*]const u8, + bytes: usize, + shape: @FieldType(ckpt.Deferred, "shape"), + + pub fn host(v: View, comptime T: type) []const T { + return @as([*]const T, @ptrCast(@alignCast(v.base)))[0 .. v.bytes / @sizeOf(T)]; + } + }; + + /// Room for the deferred tensors among `names` (a kept one is read where it is), reserved while the stage is empty. + pub fn reserve(s: *Stage, ck: *const ckpt.Checkpoint, names: []const []const u8) !void { + if (s.used != 0) return error.StageInUse; + var bytes: usize = 0; + for (names) |name| { + const d = ck.deferred.get(name) orelse { + if (!ck.tensors.contains(name)) return error.MissingTensor; + continue; + }; + bytes = std.mem.alignForward(usize, bytes, ckpt.alignment) + d.bytes; + } + if (s.mem.len >= bytes) return; + s.gpa.free(s.mem); + s.mem = &.{}; + s.mem = try s.gpa.alignedAlloc(u8, .fromByteUnits(ckpt.alignment), bytes); + } + + /// `name`: a kept tensor where it is, a deferred one read into the stage. + pub fn read(s: *Stage, ck: *const ckpt.Checkpoint, name: []const u8) !View { + const d = ck.deferred.get(name) orelse { + const t = try ck.get(name); + return .{ .base = t.buffer.contents() + t.offset, .bytes = t.bytes, .shape = t.shape }; + }; + const at = std.mem.alignForward(usize, s.used, ckpt.alignment); + if (at + d.bytes > s.mem.len) return error.StageFull; + try ck.read(name, 0, s.mem[at..][0..d.bytes]); + s.used = at + d.bytes; + return .{ .base = s.mem[at..].ptr, .bytes = d.bytes, .shape = d.shape }; + } + + pub fn reset(s: *Stage) void { + s.used = 0; + } + + pub fn deinit(s: *Stage) void { + s.gpa.free(s.mem); + s.* = .{ .gpa = s.gpa }; + } +}; + +/// A member's three tensor names. +fn names3(buf: *[3][160]u8, prefix: []const u8, member: []const u8) ![3][]const u8 { + var out: [3][]const u8 = undefined; + for (&out, buf, [_][]const u8{ "weight", "scales", "biases" }) |*o, *b, leaf| o.* = try std.fmt.bufPrint(b, "{s}{s}.{s}", .{ prefix, member, leaf }); + return out; +} + /// A linear's three tensors copied into one aligned buffer: checkpoint tensors can sit at any byte offset in a shard. -fn mlxCopy(gpa: std.mem.Allocator, device: mtl.Device, c: *const ckpt.Checkpoint, owned: *std.ArrayList(mtl.Buffer), prefix: []const u8, member: []const u8, width: cfg.widths.Width) !Mlx { - var name: [160]u8 = undefined; - const w = try c.get(try std.fmt.bufPrint(&name, "{s}{s}.weight", .{ prefix, member })); - const k = try storedK(c, prefix, member, width); - const s = try c.get(try std.fmt.bufPrint(&name, "{s}{s}.scales", .{ prefix, member })); - const b = try c.get(try std.fmt.bufPrint(&name, "{s}{s}.biases", .{ prefix, member })); +fn mlxCopy(gpa: std.mem.Allocator, device: mtl.Device, r: Src, owned: *std.ArrayList(mtl.Buffer), prefix: []const u8, member: []const u8, width: cfg.widths.Width) !Mlx { + var buf: [3][160]u8 = undefined; + const ns = try names3(&buf, prefix, member); + const k = try storedK(r, prefix, member, width); + try r.stage.reserve(r.c, &ns); + defer r.stage.reset(); + const w = try r.stage.read(r.c, ns[0]); + const s = try r.stage.read(r.c, ns[1]); + const b = try r.stage.read(r.c, ns[2]); const sb_at = std.mem.alignForward(usize, w.bytes, 256); const bb_at = sb_at + std.mem.alignForward(usize, s.bytes, 256); - const buf = try device.buffer(bb_at + b.bytes, shared); - errdefer buf.deinit(); - const dst = buf.slice(u8, bb_at + b.bytes); + const out = try device.buffer(bb_at + b.bytes, shared); + errdefer out.deinit(); + const dst = out.slice(u8, bb_at + b.bytes); @memcpy(dst[0..w.bytes], w.host(u8)[0..w.bytes]); @memcpy(dst[sb_at..][0..s.bytes], s.host(u8)[0..s.bytes]); @memcpy(dst[bb_at..][0..b.bytes], b.host(u8)[0..b.bytes]); - try owned.append(gpa, buf); - return .{ .w = .{ .buf = buf }, .s = .{ .buf = buf, .off = sb_at }, .b = .{ .buf = buf, .off = bb_at }, .n = @intCast(w.shape[0]), .k = @intCast(k), .bits = width.bits }; + try owned.append(gpa, out); + return .{ .w = .{ .buf = out }, .s = .{ .buf = out, .off = sb_at }, .b = .{ .buf = out, .off = bb_at }, .n = @intCast(w.shape[0]), .k = @intCast(k), .bits = width.bits }; +} + +/// The bytes `mlxCopy` allocates for a member: its three tensors at 256-byte offsets in one buffer. +fn copyBytes(r: Src, prefix: []const u8, member: []const u8) !u64 { + var buf: [3][160]u8 = undefined; + const ns = try names3(&buf, prefix, member); + const sb_at = std.mem.alignForward(usize, (try r.meta(ns[0])).bytes, 256); + return sb_at + std.mem.alignForward(usize, (try r.meta(ns[1])).bytes, 256) + (try r.meta(ns[2])).bytes; +} + +/// A member's rows of a row-path pack as core/affine_mm reads it: the same bytes, no copy (no tensor units). +fn mlxAlias(x: Linear, row: usize, n: usize) Mlx { + const raw = x.raw.?; + const words = x.k * x.format.bits / 32; + const groups = x.k / x.format.group; + return .{ .w = .{ .buf = raw.w, .off = row * words * 4 }, .s = .{ .buf = raw.scales, .off = row * groups * 2 }, .b = .{ .buf = raw.biases, .off = row * groups * 2 }, .n = @intCast(n), .k = @intCast(x.k), .bits = x.format.bits }; +} + +/// A stack's members as aliases of its runs' rows, in `members`' order (runs of equal widths, as `stack` made them). +fn mlxStack(r: Src, s: *const Stack, prefix: []const u8, members: []const []const u8, ws: []const cfg.widths.Width, out: []Mlx) !void { + var buf: [3][160]u8 = undefined; + var run: usize = 0; + var row: usize = 0; + for (members, ws, out, 0..) |m, w, *o, i| { + if (i > 0 and !std.meta.eql(w, ws[i - 1])) { + run += 1; + row = 0; + } + const n = (try r.meta((try names3(&buf, prefix, m))[0])).shape[0]; + o.* = mlxAlias(s.runs[run], row, n); + row += n; + } } /// A member's K at its config width (words [N, K * bits / 32], tables [N, K / group]); other storage refused. -fn storedK(c: *const ckpt.Checkpoint, prefix: []const u8, member: []const u8, width: cfg.widths.Width) !usize { - var name: [160]u8 = undefined; - const w = try c.get(try std.fmt.bufPrint(&name, "{s}{s}.weight", .{ prefix, member })); - const s = try c.get(try std.fmt.bufPrint(&name, "{s}{s}.scales", .{ prefix, member })); - const b = try c.get(try std.fmt.bufPrint(&name, "{s}{s}.biases", .{ prefix, member })); +fn storedK(r: Src, prefix: []const u8, member: []const u8, width: cfg.widths.Width) !usize { + var buf: [3][160]u8 = undefined; + const ns = try names3(&buf, prefix, member); + const w = try r.meta(ns[0]); + const s = try r.meta(ns[1]); + const b = try r.meta(ns[2]); const ok = w.dtype == .u32 and w.rank == 2 and s.rank == 2 and b.rank == 2 and s.dtype == .bf16 and b.dtype == .bf16 and s.shape[0] == w.shape[0] and b.shape[0] == w.shape[0] and s.shape[1] == b.shape[1] and - w.count() == w.shape[0] * w.shape[1] and s.count() == s.shape[0] * s.shape[1] and b.count() == s.count(); + w.bytes == w.shape[0] * w.shape[1] * 4 and s.bytes == s.shape[0] * s.shape[1] * 2 and b.bytes == s.bytes; const k = s.shape[1] * width.group; if (!ok or w.shape[1] * 32 != k * width.bits) { std.log.warn("gemma4: {s}{s} is not stored at its config width, {d}-bit in groups of {d}", .{ prefix, member, width.bits, width.group }); @@ -170,14 +295,14 @@ fn ref(c: *const ckpt.Checkpoint, name: []const u8) !Ref { } /// Members of one width stacked along N into the lane layout; `interleave`: two members in alternate 16-row blocks. -fn pack(gpa: std.mem.Allocator, device: mtl.Device, c: *const ckpt.Checkpoint, owned: *std.ArrayList(mtl.Buffer), geo: cfg.Geometry, prefix: []const u8, members: []const []const u8, width: cfg.widths.Width, interleave: bool) !Linear { - var name: [160]u8 = undefined; +fn pack(gpa: std.mem.Allocator, device: mtl.Device, r: Src, owned: *std.ArrayList(mtl.Buffer), geo: cfg.Geometry, prefix: []const u8, members: []const []const u8, width: cfg.widths.Width, interleave: bool) !Linear { + var buf: [3][160]u8 = undefined; var n: usize = 0; var k: usize = 0; for (members) |m| { - const mk = try storedK(c, prefix, m, width); + const mk = try storedK(r, prefix, m, width); if (k != 0 and k != mk) return error.BadGemmaWeight; - n += (try c.get(try std.fmt.bufPrint(&name, "{s}{s}.weight", .{ prefix, m }))).shape[0]; + n += (try r.meta((try names3(&buf, prefix, m))[0])).shape[0]; k = mk; } const row_words = k * width.bits / 32; @@ -191,38 +316,46 @@ fn pack(gpa: std.mem.Allocator, device: mtl.Device, c: *const ckpt.Checkpoint, o if (interleave and (members.len != 2 or n % 32 != 0)) return error.BadGemmaWeight; var row: usize = 0; for (members, 0..) |m, mi| { - const w = (try c.get(try std.fmt.bufPrint(&name, "{s}{s}.weight", .{ prefix, m }))).host(u32); - const s = (try c.get(try std.fmt.bufPrint(&name, "{s}{s}.scales", .{ prefix, m }))).host(u16); - const b = (try c.get(try std.fmt.bufPrint(&name, "{s}{s}.biases", .{ prefix, m }))).host(u16); + const ns = try names3(&buf, prefix, m); + try r.stage.reserve(r.c, &ns); + defer r.stage.reset(); + const w = (try r.stage.read(r.c, ns[0])).host(u32); + const s = (try r.stage.read(r.c, ns[1])).host(u16); + const b = (try r.stage.read(r.c, ns[2])).host(u16); const rows = w.len / row_words; if (interleave and rows != n / 2) return error.BadGemmaWeight; - for (0..rows) |r| { - const dst = if (interleave) 32 * (r / 16) + 16 * mi + r % 16 else row + r; - @memcpy(words[dst * row_words ..][0..row_words], w[r * row_words ..][0..row_words]); - @memcpy(scales[dst * groups ..][0..groups], s[r * groups ..][0..groups]); - @memcpy(biases[dst * groups ..][0..groups], b[r * groups ..][0..groups]); + for (0..rows) |i| { + const dst = if (interleave) 32 * (i / 16) + 16 * mi + i % 16 else row + i; + @memcpy(words[dst * row_words ..][0..row_words], w[i * row_words ..][0..row_words]); + @memcpy(scales[dst * groups ..][0..groups], s[i * groups ..][0..groups]); + @memcpy(biases[dst * groups ..][0..groups], b[i * groups ..][0..groups]); } row += rows; } return packArrays(gpa, device, owned, geo, words, scales, biases, .{ .w = undefined, .sb = undefined, .n = n, .k = k, .format = .{ .bits = width.bits, .group = width.group } }); } +/// Whether gate|up packs as one run in alternate 16-row blocks (lane path); the row path keeps gate rows, then up's. +pub fn interleaves(tensor_units: bool, runs: usize) bool { + return tensor_units and runs == 1; +} + /// A q|k|v or gate|up stack: each run of members of one width packed as one linear writing its columns of the rows. -fn stack(gpa: std.mem.Allocator, device: mtl.Device, c: *const ckpt.Checkpoint, owned: *std.ArrayList(mtl.Buffer), geo: cfg.Geometry, prefix: []const u8, members: []const []const u8, ws: []const cfg.widths.Width, glu: bool) !Stack { +fn stack(gpa: std.mem.Allocator, device: mtl.Device, r: Src, owned: *std.ArrayList(mtl.Buffer), geo: cfg.Geometry, prefix: []const u8, members: []const []const u8, ws: []const cfg.widths.Width, glu: bool) !Stack { var s: Stack = .{}; var first: usize = 0; while (first < members.len) { var end = first + 1; while (end < members.len and std.meta.eql(ws[end], ws[first])) end += 1; const whole = first == 0 and end == members.len; - var x = try pack(gpa, device, c, owned, geo, prefix, members[first..end], ws[first], glu and whole); + var x = try pack(gpa, device, r, owned, geo, prefix, members[first..end], ws[first], glu and whole and interleaves(device.tensorUnits(), 1)); x.col = s.n; s.n += x.n; s.runs[s.count] = x; s.count += 1; first = end; } - s.interleaved = glu and s.count == 1; + s.interleaved = glu and interleaves(device.tensorUnits(), s.count); if (s.count > 1) for (s.runs[0..s.count]) |*x| { x.y_stride = s.n; // each run writes its columns of the stack's rows (the lane words do not depend on it) }; @@ -273,25 +406,40 @@ pub fn packRows(gpa: std.mem.Allocator, device: mtl.Device, owned: *std.ArrayLis pub fn load(gpa: std.mem.Allocator, device: mtl.Device, c: *const ckpt.Checkpoint, geo: cfg.Geometry, ws: *const cfg.widths.Widths) !Weights { var w: Weights = undefined; w.owned = .empty; + w.aliased = 0; errdefer w.deinit(gpa); + var stage = Stage{ .gpa = gpa }; + defer stage.deinit(); + const r: Src = .{ .c = c, .stage = &stage }; + const rows = !device.tensorUnits(); var p: [96]u8 = undefined; var name: [160]u8 = undefined; for (w.layers[0..geo.layers], 0..) |*l, i| { const pre = try std.fmt.bufPrint(&p, "language_model.model.layers.{d}.", .{i}); const lw = ws.layers[i]; const qkv: []const []const u8 = if (cfg.global(i)) &.{ "self_attn.q_proj", "self_attn.k_proj" } else &.{ "self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj" }; - l.qkv = try stack(gpa, device, c, &w.owned, geo, pre, qkv, lw[0..qkv.len], false); - l.o = try pack(gpa, device, c, &w.owned, geo, pre, &.{"self_attn.o_proj"}, lw[3], false); - l.gate_up = try stack(gpa, device, c, &w.owned, geo, pre, &.{ "mlp.gate_proj", "mlp.up_proj" }, lw[4..6], true); - l.down = try pack(gpa, device, c, &w.owned, geo, pre, &.{"mlp.down_proj"}, lw[6], false); - for (&l.mlx, cfg.widths.module_names, lw) |*x, member, width| { + const glu = [_][]const u8{ "mlp.gate_proj", "mlp.up_proj" }; + l.qkv = try stack(gpa, device, r, &w.owned, geo, pre, qkv, lw[0..qkv.len], false); + l.o = try pack(gpa, device, r, &w.owned, geo, pre, &.{"self_attn.o_proj"}, lw[3], false); + l.gate_up = try stack(gpa, device, r, &w.owned, geo, pre, &glu, lw[4..6], true); + l.down = try pack(gpa, device, r, &w.owned, geo, pre, &.{"mlp.down_proj"}, lw[6], false); + if (rows) { // the row packs hold the checkpoint's arrays as stored: prompt chunks read their rows in place + try mlxStack(r, &l.qkv, pre, qkv, lw[0..qkv.len], l.mlx[0..qkv.len]); + l.mlx[3] = mlxAlias(l.o, 0, l.o.n); + try mlxStack(r, &l.gate_up, pre, &glu, lw[4..6], l.mlx[4..6]); + l.mlx[6] = mlxAlias(l.down, 0, l.down.n); + if (cfg.global(i)) l.mlx[2] = l.mlx[1]; // global layers have no v_proj: k stands in, never read + for (cfg.widths.module_names) |member| if (!(cfg.global(i) and std.mem.eql(u8, member, "self_attn.v_proj"))) { + w.aliased += try copyBytes(r, pre, member); + }; + } else for (&l.mlx, cfg.widths.module_names, lw) |*x, member, width| { // global layers have no v_proj: k stands in, never read - x.* = if (cfg.global(i) and std.mem.eql(u8, member, "self_attn.v_proj")) l.mlx[1] else try mlxCopy(gpa, device, c, &w.owned, pre, member, width); + x.* = if (cfg.global(i) and std.mem.eql(u8, member, "self_attn.v_proj")) l.mlx[1] else try mlxCopy(gpa, device, r, &w.owned, pre, member, width); } inline for (.{ "q_norm", "k_norm", "input_norm", "post_attention", "pre_feedforward", "post_feedforward", "scalar" }, .{ "self_attn.q_norm.weight", "self_attn.k_norm.weight", "input_layernorm.weight", "post_attention_layernorm.weight", "pre_feedforward_layernorm.weight", "post_feedforward_layernorm.weight", "layer_scalar" }) |field, t| @field(l, field) = try ref(c, try std.fmt.bufPrint(&name, "{s}{s}", .{ pre, t })); } - w.head = try pack(gpa, device, c, &w.owned, geo, "language_model.model.", &.{"embed_tokens"}, ws.embed, false); + w.head = try pack(gpa, device, r, &w.owned, geo, "language_model.model.", &.{"embed_tokens"}, ws.embed, false); w.embed_bits = ws.embed.bits; w.embed_w = try ref(c, "language_model.model.embed_tokens.weight"); w.embed_s = try ref(c, "language_model.model.embed_tokens.scales"); @@ -361,3 +509,83 @@ pub const Projections = struct { ps.follow = hook; } }; + +test "later: the layers' linears stay in their files; the embed, norms and scalars stay in the shards" { + const pre = "language_model.model.layers.3."; + for ([_][]const u8{ pre ++ "self_attn.q_proj.weight", pre ++ "self_attn.k_proj.scales", pre ++ "mlp.gate_proj.biases", pre ++ "mlp.down_proj.weight" }) |t| + try std.testing.expect(later(t, 2)); + for ([_][]const u8{ "language_model.model.embed_tokens.weight", "language_model.model.embed_tokens.scales", "language_model.model.norm.weight", pre ++ "input_layernorm.weight", pre ++ "self_attn.q_norm.weight", pre ++ "layer_scalar" }) |t| + try std.testing.expect(!later(t, 1)); +} + +test "gate|up interleaves on tensor units alone: the row path keeps gate rows, then up's, as prompt chunks read them" { + try std.testing.expect(interleaves(true, 1)); + try std.testing.expect(!interleaves(false, 1)); + try std.testing.expect(!interleaves(true, 2)); +} + +/// Two 4-bit members (q, k: 16 rows of K 64) and a norm, at odd file offsets as MLX writes them. +fn fixture(gpa: std.mem.Allocator, tmp: *std.testing.TmpDir) ![:0]u8 { + const p = "language_model.model.layers.0."; + const header = "{\"pad\":{\"dtype\":\"U8\",\"shape\":[3],\"data_offsets\":[0,3]}," ++ + "\"" ++ p ++ "self_attn.q_proj.weight\":{\"dtype\":\"U32\",\"shape\":[16,8],\"data_offsets\":[3,515]}," ++ + "\"" ++ p ++ "self_attn.q_proj.scales\":{\"dtype\":\"BF16\",\"shape\":[16,1],\"data_offsets\":[515,547]}," ++ + "\"" ++ p ++ "self_attn.q_proj.biases\":{\"dtype\":\"BF16\",\"shape\":[16,1],\"data_offsets\":[547,579]}," ++ + "\"" ++ p ++ "self_attn.k_proj.weight\":{\"dtype\":\"U32\",\"shape\":[16,8],\"data_offsets\":[579,1091]}," ++ + "\"" ++ p ++ "self_attn.k_proj.scales\":{\"dtype\":\"BF16\",\"shape\":[16,1],\"data_offsets\":[1091,1123]}," ++ + "\"" ++ p ++ "self_attn.k_proj.biases\":{\"dtype\":\"BF16\",\"shape\":[16,1],\"data_offsets\":[1123,1155]}," ++ + "\"" ++ p ++ "input_layernorm.weight\":{\"dtype\":\"BF16\",\"shape\":[8],\"data_offsets\":[1155,1171]}}"; + var data: [8 + header.len + 1171]u8 = undefined; + std.mem.writeInt(u64, data[0..8], header.len, .little); + @memcpy(data[8..][0..header.len], header); + for (data[8 + header.len ..], 0..) |*b, i| b.* = @truncate(i * 7 + 1); + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "g.safetensors", .data = &data }); + return std.fmt.allocPrintSentinel(gpa, ".zig-cache/tmp/{s}/g.safetensors", .{tmp.sub_path}, 0); +} + +test "load: linears staged once, row-path prompt views alias the pack's bytes, and a freed linear is refused by name" { + if (comptime !@hasDecl(mtl.Device, "init")) return error.SkipZigTest; // a recording Metal stand-in has no device + const log_level = std.testing.log_level; + std.testing.log_level = .err; + defer std.testing.log_level = log_level; + const device = mtl.Device.init() catch return error.SkipZigTest; + defer device.deinit(); + const gpa = std.testing.allocator; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const path = try fixture(gpa, &tmp); + defer gpa.free(path); + var c = ckpt.Checkpoint.init(gpa); + defer c.deinit(); + try c.addFileSplit(device, path, "", "language_model.", later); + try std.testing.expectEqual(@as(usize, 16), c.residentBytes()); // the norm alone + const pre = "language_model.model.layers.0."; + // the planted stale pointer: a Ref into a linear's shard bytes is refused, not read from freed memory + try std.testing.expectError(error.DeferredTensor, ref(&c, pre ++ "self_attn.q_proj.weight")); + _ = try ref(&c, pre ++ "input_layernorm.weight"); + var stage = Stage{ .gpa = gpa }; + defer stage.deinit(); + const r: Src = .{ .c = &c, .stage = &stage }; + var owned: std.ArrayList(mtl.Buffer) = .empty; + defer { + for (owned.items) |b| b.deinit(); + owned.deinit(gpa); + } + const members = [_][]const u8{ "self_attn.q_proj", "self_attn.k_proj" }; + const ws = [_]cfg.widths.Width{ cfg.widths.fast, cfg.widths.fast }; + const s = try stack(gpa, device, r, &owned, cfg.dense31b, pre, &members, &ws, true); + try std.testing.expectEqual(device.tensorUnits(), s.interleaved); + if (!device.tensorUnits()) { + var views: [2]Mlx = undefined; + try mlxStack(r, &s, pre, &members, &ws, &views); + for (members, views) |m, v| { + const copy = try mlxCopy(gpa, device, r, &owned, pre, m, cfg.widths.fast); + try std.testing.expectEqual(copy.n, v.n); + try std.testing.expectEqual(@as(u64, copy.w.buf.length()), try copyBytes(r, pre, m)); // what `aliased` counts + for ([_][2]Ref{ .{ v.w, copy.w }, .{ v.s, copy.s }, .{ v.b, copy.b } }, [_]usize{ 512, 32, 32 }) |pair, n| + try std.testing.expectEqualSlices(u8, (pair[1].buf.contents() + pair[1].off)[0..n], (pair[0].buf.contents() + pair[0].off)[0..n]); + } + } + c.closeFiles(); // after load: the files are shut, and nothing reads a linear from them again + try std.testing.expectError(error.ShardClosed, mlxCopy(gpa, device, r, &owned, pre, "self_attn.q_proj", cfg.widths.fast)); +} diff --git a/zig/src/families/glm/backend.zig b/zig/src/families/glm/backend.zig index 494c8ba9a2c..9c3429cc602 100644 --- a/zig/src/families/glm/backend.zig +++ b/zig/src/families/glm/backend.zig @@ -13,12 +13,13 @@ const Engine = @import("engine.zig").Engine; const be = lanes.backend; const Stream = lanes.Stream; const fwd = @import("forward.zig"); +const dflash = @import("metal_dflash_rounds.zig"); /// One stream's window and a shared forward's rows, ms on one M5 Ultra (a pair times its own at load: timing.zig). -const one_mac_window_costs = costTable(13.0, 4.1); -const one_mac_shared_costs = costTable(8.4 + 4.1, 4.1); +pub const one_mac_window_costs = costTable(13.0, 4.1); +pub const one_mac_shared_costs = costTable(8.4 + 4.1, 4.1); /// The acceptance estimates' rate, below the core's 0.15: a stream takes about twice the misses in a row to go plain. -const depth_rate = 0.08; +pub const depth_rate = 0.08; fn costTable(comptime one: f64, comptime row: f64) [st.max_rows]lanes.config.Cost { var c: [st.max_rows]lanes.config.Cost = undefined; @@ -36,9 +37,11 @@ pub const Backend = struct { wins: std.ArrayList(slots_mod.Win) = .empty, drafts: std.ArrayList(slots_mod.Draft) = .empty, costs: ?timing.Costs = null, // a pair's rank 0: its windows and head step as timed (shared forwards priced the same) + rounds: ?*dflash.Rounds = null, // --drafter: DFlash2's per-stream rounds (null: the MTP head drafts) pub fn deinit(b: *Backend) void { if (b.image_owner != null) slot_images.end(b.sl); + if (b.rounds) |r| r.deinit(); b.filling.deinit(b.gpa); b.by.deinit(b.gpa); b.words.deinit(b.gpa); @@ -47,11 +50,17 @@ pub const Backend = struct { } pub fn backend(b: *Backend) be.Backend { - return .{ .ptr = b, .vtable = &.{ .prefill = prefill, .prefill_step = prefillStep, .first = first, .queue = queue, .read = read, .verify = verify, .keep = keep, .draft = draft, .release = release, .reports_fill = true } }; + return .{ .ptr = b, .vtable = &.{ .prefill = prefill, .prefill_step = prefillStep, .first = first, .queue = queue, .read = read, .verify = verify, .keep = keep, .draft = draft, .probabilities = chances, .tree = heldRows, .release = release, .reports_fill = true } }; } /// Windows of up to 16 rows (drafted == plain at every width), the MTP head's chains, every stream in one forward. pub fn facts(b: *const Backend) lanes.Model { + if (b.sl.e.dflash != null) return dflash.facts(b); + return b.headFacts(); + } + + /// The facts without the drafter: the MTP head's own, also what prices its rounds beside DFlash2. + pub fn headFacts(b: *const Backend) lanes.Model { return .{ .learn_row_costs = b.sl.e.ep == null and !b.sl.e.device.tensorUnits(), // the table is an M5 Ultra's: others pay more .allocate_shared_drafts = b.sl.e.hasMtp(), @@ -91,7 +100,7 @@ pub const Backend = struct { return @ptrCast(@alignCast(ptr)); } - fn slotOf(b: *Backend, s: *Stream) !u32 { + pub fn slotOf(b: *Backend, s: *Stream) !u32 { return b.by.get(s) orelse error.UnknownStream; } @@ -143,6 +152,7 @@ pub const Backend = struct { } // the images the restored state does not hold through the tower: the chunks inject their rows if (s.images.len > 0) try @import("prompt_images.zig").prepare(b, s, i, s.cached); + if (b.rounds) |r| _ = r.begin(i, at, b.by.count(), s.sampling != null); // after restore: drafter starts here s.fill_at.store(at, .monotonic); return .{ .stream = s, .slot = i, .at = at }; } @@ -160,6 +170,9 @@ pub const Backend = struct { const draws = @import("draw_rule.zig").promptDraws(s.sampling, @intCast(s.prompt_len), e.c.vocab); const chunk_draws: ?*const fwd.Draws = if (draws.n > 0 and at + n == s.prompt_len) &draws else null; try b.sl.chunk(i, at, n, chunk_draws); + if (b.rounds) |r| if (r.get(i)) |x| { // the chunk's tap rows are in the stream's own ring now + x.ctx.committed_end = at + n; + }; } pub fn encodeImages(b: *Backend, i: u32, images: []const lanes.stream.Image) !void { try slot_images.encode(b.sl, i, images); @@ -355,6 +368,20 @@ pub const Backend = struct { return try b.sl.queueRound(i, from, s.sampling); } + /// Each held draft's chance of landing, DFlash2's chained (false: none, so the per-depth rates stand). + fn chances(ptr: *anyopaque, s: *Stream, out: []f64) anyerror!bool { + const b = self(ptr); + const r = b.rounds orelse return false; + return dflash.chancesFor(r, b.by.get(s) orelse return false, out); + } + + /// The rows the next round verifies: DFlash2's held chain, cut to its priced prefix (null: the head's own). + fn heldRows(ptr: *anyopaque, s: *Stream, _: std.mem.Allocator) anyerror!?lanes.stream.Held { + const b = self(ptr); + const r = b.rounds orelse return null; + return r.heldRows(b.by.get(s) orelse return null); + } + fn read(ptr: *anyopaque, handle: u64) anyerror!u32 { return self(ptr).sl.ringGet(@intCast(handle)); } @@ -383,6 +410,7 @@ pub const Backend = struct { @memcpy(o.sampled, picks[row..][0..w.rows()]); @memcpy(o.drafts[0..w.held], Engine.u32s(b.sl.slots[win.slot].held, w.held)); @memcpy(o.drafts[w.held..], w.tokens); + if (b.rounds) |r| r.sawWindow(win.slot, @intCast(w.held + w.tokens.len)); row += w.rows(); } } @@ -401,6 +429,7 @@ pub const Backend = struct { fn draft(ptr: *anyopaque, requests: []const be.DraftRequest) anyerror!void { const b = self(ptr); + if (b.rounds) |r| return dflash.draft(b, r, requests); var ones: [st.max_rows]u32 = undefined; // a prompt's first token, the one its head absorbs with b.drafts.clearRetainingCapacity(); if (requests.len > ones.len) return error.DraftOutOfStep; @@ -418,6 +447,7 @@ pub const Backend = struct { break :blk ones[k .. k + 1]; } else r.follow; try b.drafts.append(b.gpa, .{ .slot = try b.slotOf(r.stream), .prompt = r.rows == null, .follow = follow, .depth = r.depth }); + if (b.sl.log) std.log.info("glm round: slot {d} source mtp gained {d} drafts {d}", .{ b.drafts.items[b.drafts.items.len - 1].slot, r.follow.len, r.depth }); } try b.sl.checkDrafts(b.drafts.items); // before rank 1 hears of them: it must never fail where rank 0 did not try mirror.draftWords(&b.words, b.gpa, b.drafts.items); @@ -431,6 +461,7 @@ pub const Backend = struct { b.finishPrompt(s) catch {}; const kv = b.by.fetchRemove(s) orelse return; mirror.send(b.sl.e, .release, &.{kv.value}) catch |err| std.log.err("glm: the peer missed a release: {s}", .{@errorName(err)}); + if (b.rounds) |r| r.release(kv.value); // the stream's drafter context and tap route go with it b.sl.release(kv.value); } }; @@ -441,6 +472,7 @@ test "zero grant: GLM Metal MTP resumes after a long priced skip" { var e: Engine = undefined; e.w = &w; e.ep = null; + e.dflash = null; const objc = @import("metal").objc; const no_arch = objc.msg(objc.Id, objc.class("NSObject"), "new", .{}); // facts() asks it for tensor units, no GPU defer objc.release(no_arch); @@ -461,6 +493,7 @@ test "shared head costs: GLM Metal MTP retains costed copy grants" { var e: Engine = undefined; e.w = &w; e.ep = null; + e.dflash = null; const objc = @import("metal").objc; const no_arch = objc.msg(objc.Id, objc.class("NSObject"), "new", .{}); // facts() asks it for tensor units, no GPU defer objc.release(no_arch); diff --git a/zig/src/families/glm/cuda_env_test.zig b/zig/src/families/glm/cuda_env_test.zig index cb407cb222b..9b70cb128c7 100644 --- a/zig/src/families/glm/cuda_env_test.zig +++ b/zig/src/families/glm/cuda_env_test.zig @@ -16,6 +16,7 @@ const switches = [_]Name{ .{ .name = "TF_GLM_PROMPT_STEPS", .default = true }, .{ .name = "TF_GLM_SHARED", .default = true }, .{ .name = "TF_GLM_DSEL", .default = true }, + .{ .name = "TF_GLM_DSCORES", .default = true }, }; const counts = [_][:0]const u8{"TF_GLM_DFLASH2_LOG"}; const reals = [_][:0]const u8{"TF_GLM_DRAFT_CONFIDENCE"}; diff --git a/zig/src/families/glm/cuda_exl3.zig b/zig/src/families/glm/cuda_exl3.zig index 9c30d912979..fce0f2234d8 100644 --- a/zig/src/families/glm/cuda_exl3.zig +++ b/zig/src/families/glm/cuda_exl3.zig @@ -1,7 +1,8 @@ -//! GLM-5.3-Flash's EXL3 routed experts on CUDA (Mia-AiLab's checkpoint: 4-bit mcg trellis experts, the rest bf16). +//! GLM's EXL3 routed experts on CUDA: "mcg" trellis experts at any whole-bit width, mixed per projection; rest bf16. const std = @import("std"); -const modelopt = @import("core").modelopt; +const core = @import("core"); +const modelopt = core.modelopt; const Span = @import("cuda_shard.zig").Span; const cuda = @import("cuda"); const experts = @import("cuda_experts.zig"); @@ -23,7 +24,28 @@ pub fn isExl3(gpa: std.mem.Allocator, config_json: []const u8) bool { return m == .string and std.mem.eql(u8, m.string, "exl3"); } -/// The EXL3 checkpoints the kernels read: 4-bit routed experts on the "mcg" codebook (everything else bf16). +/// The half-bit widths (2 * bits) the grouped kernels decode on mcg: whole bits from 1 to 8 (odd halves are mul1's). +pub const min_k2 = 2; +pub const max_k2 = 16; + +/// A trellis's half-bit width from its last dimension (16 * bits int16 a tile), null if the kernels skip it. +pub fn halves(last: usize) ?u32 { + if (last % 8 != 0) return null; + const k2 = last / 8; + if (k2 < min_k2 or k2 > max_k2 or k2 % 2 != 0) return null; + return @intCast(k2); +} + +/// A JSON number as f64, or null. +fn number(v: std.json.Value) ?f64 { + return switch (v) { + .integer => |i| @floatFromInt(i), + .float => |f| f, + else => null, + }; +} + +/// The EXL3 the kernels read: "mcg" routed experts at 1 to 8 bits, each trellis's width taken from its shape. pub fn admit(gpa: std.mem.Allocator, config_json: []const u8, why: *modelopt.Why) !void { const parsed = try std.json.parseFromSlice(std.json.Value, gpa, config_json, .{}); defer parsed.deinit(); @@ -31,10 +53,21 @@ pub fn admit(gpa: std.mem.Allocator, config_json: []const u8, why: *modelopt.Why why.set("no quantization_config", .{}); return error.UnsupportedQuant; }; - const bits = q.get("bits") orelse std.json.Value{ .null = {} }; - if (bits != .integer or bits.integer != 4) { - why.set("EXL3 at {f} bits: the CUDA family reads 4-bit EXL3 experts", .{std.json.fmt(bits, .{})}); - return error.UnsupportedQuant; + const lo: f64 = min_k2 / 2; + const hi: f64 = max_k2 / 2; + if (q.get("bits")) |bits| { + const b = number(bits); + if (b == null or b.? != @floor(b.?) or !(b.? >= lo and b.? <= hi)) { + why.set("EXL3 at {f} bits: the CUDA family reads mcg experts of 1 to 8 whole bits", .{std.json.fmt(bits, .{})}); + return error.UnsupportedQuant; + } + } + if (q.get("avg_bits")) |avg| { + const b = number(avg); + if (b == null or !(b.? >= lo and b.? <= hi)) { + why.set("EXL3 averaging {f} bits: the CUDA family reads mcg experts of 1 to 8 bits", .{std.json.fmt(avg, .{})}); + return error.UnsupportedQuant; + } } const book = q.get("codebook") orelse std.json.Value{ .null = {} }; if (book != .string or !std.mem.eql(u8, book.string, "mcg")) { @@ -43,9 +76,9 @@ pub fn admit(gpa: std.mem.Allocator, config_json: []const u8, why: *modelopt.Why } } -/// One layer's EXL3 experts on a rank: trellis words [E][K/16][N/16][32] and fp16 scales (suh [E][K], svh [E][N]). +/// One layer's EXL3 experts on a rank: trellis words [E][K/16][N/16][8 * k2] and fp16 scales (suh [E][K], svh [E][N]). pub const Experts = struct { - gt: u64, + gt: u64, // int64 [E]: each expert's gate trellis ut: u64, dt: u64, suh_g: u64, @@ -54,18 +87,49 @@ pub const Experts = struct { svh_u: u64, suh_d: u64, svh_d: u64, - k2: u64, // independent per-expert projection widths in the common module + k2: u64, // int32 [E]: every expert's gate half-bit width (2 * bits); up's and down's too unless theirs are set + k2_up: u64 = 0, // int32 [E]: up's widths (0: k2's) + k2_down: u64 = 0, // int32 [E]: down's widths (0: k2's) + // Widths the loader found across gate/up and down (0: they differ); a literal is upstream's 4-bit, 8 half-bits. + uniform_gu: u32 = 8, + uniform_d: u32 = 8, shx: bool, // every expert's gate and up share one input rotation: a prompt rotates a row once, not once a pick + + /// The gate, up and down width tables. + pub fn tables(w: Experts) [3]u64 { + return .{ w.k2, if (w.k2_up != 0) w.k2_up else w.k2, if (w.k2_down != 0) w.k2_down else w.k2 }; + } }; -const tile = 128; // a 16 x 16 tile's bytes at 4 bits +/// A 16 x 16 tile's bytes at `k2` half-bits a value (128 at 4 bits, 96 at 3). +pub fn tileBytes(k2: u32) usize { + return 16 * @as(usize, k2); +} + +/// The width every entry of `k2s` has, or 0 when they differ (or there are none). +fn uniform(k2s: []const i32) u32 { + if (k2s.len == 0) return 0; + for (k2s) |k| if (k != k2s[0]) return 0; + return @intCast(k2s[0]); +} -/// Layer `i`'s EXL3 experts through `L` (cuda_weights' loader): gate, up by `cut`'s tile columns, down by its rows. +/// Why trellis `t` of a K x N projection is not one the kernels read, or null when it is. +pub fn refusal(t: core.checkpoint.Tensor, k: usize, n: usize) ?[]const u8 { + if (t.dtype != .i16 or t.rank != 3) return "not an int16 trellis [K/16, N/16, 16 * bits]"; + if (t.dim(0) != k / 16 or t.dim(1) != n / 16) return "its tiles do not cover the projection's K x N"; + if (halves(t.dim(2)) == null) return "a width other than 1 to 8 whole bits (16 to 128 int16 a tile)"; + if (t.bytes.len != t.numel() * 2) return "its bytes do not match its shape"; + return null; +} + +/// Layer `i`'s experts via `L`: gate and up by `cut`'s tile columns, down by rows, each at its own trellis width. pub fn load(L: anytype, i: u32, count: usize, dims: usize, inter: usize, cut: Span) !Experts { - if (dims % 128 != 0 or cut.lo % 128 != 0 or cut.hi % 128 != 0) return error.NotExl3Mcg4; + if (dims % 128 != 0 or cut.lo % 128 != 0 or cut.hi % 128 != 0) return error.UnreadableExl3; const width = cut.len(); var out: Experts = undefined; out.shx = true; + const k2s = try L.gpa.alloc(i32, 3 * count); // gate's, up's, down's by expert + defer L.gpa.free(k2s); const Mat = struct { k: usize, n: usize, by_cols: bool }; const mats = [_]Mat{ .{ .k = dims, .n = inter, .by_cols = true }, @@ -73,51 +137,77 @@ pub fn load(L: anytype, i: u32, count: usize, dims: usize, inter: usize, cut: Sp .{ .k = inter, .n = dims, .by_cols = false }, }; var first_suh: ?[]const u8 = null; - inline for (mats, .{ "gate_proj", "up_proj", "down_proj" }, .{ "gt", "ut", "dt" }, .{ "suh_g", "suh_u", "suh_d" }, .{ "svh_g", "svh_u", "svh_d" }) |m, proj, tw, su, sv| { + inline for (mats, .{ "gate_proj", "up_proj", "down_proj" }, .{ "gt", "ut", "dt" }, .{ "suh_g", "suh_u", "suh_d" }, .{ "svh_g", "svh_u", "svh_d" }, 0..) |m, proj, tw, su, sv, pi| { const kt = (if (m.by_cols) m.k else width) / 16; // the rank's tiles const nt = (if (m.by_cols) width else m.n) / 16; - for (0..count) |e| { + const mine = k2s[pi * count ..][0..count]; + for (0..count, mine) |e, *k2| { const t = try L.get("layers.{d}.mlp.experts.{d}." ++ proj ++ ".trellis", .{ i, e }); - if (t.dtype != .i16 or t.rank != 3 or t.dim(0) != m.k / 16 or t.dim(1) != m.n / 16 or t.dim(2) != 64) return error.NotExl3Mcg4; - const marker = L.get("layers.{d}.mlp.experts.{d}." ++ proj ++ ".mcg", .{ i, e }) catch return error.NotExl3Mcg4; + if (refusal(t, m.k, m.n)) |why| { + std.log.err("{s}: {s} (shape {any}); GLM's CUDA experts read mcg trellises of 1 to 8 bits", .{ L.last, why, t.shape[0..t.rank] }); + return error.UnreadableExl3; + } + const h = halves(t.dim(2)).?; + const tile = tileBytes(h); + const marker = L.get("layers.{d}.mlp.experts.{d}." ++ proj ++ ".mcg", .{ i, e }) catch return error.UnreadableExl3; if (marker.dtype != .i32 or marker.numel() != 1 or marker.bytes.len != 4 or - std.mem.readInt(u32, marker.bytes[0..4], .little) != @import("core").exl3_load.markers[0].value) - return error.NotExl3Mcg4; + std.mem.readInt(u32, marker.bytes[0..4], .little) != core.exl3_load.markers[0].value) + return error.UnreadableExl3; if (m.by_cols) { // every tile row, the rank's tile columns const row = (m.n / 16) * tile; for (0..kt) |r| try L.host.appendSlice(L.gpa, t.bytes[r * row + (cut.lo / 16) * tile ..][0 .. nt * tile]); } else try L.host.appendSlice(L.gpa, t.bytes[(cut.lo / 16) * nt * tile ..][0 .. kt * nt * tile]); // its tile rows + k2.* = @intCast(h); } const base = try L.put("layers.{d}.moe.exl3." ++ tw, .{i}); - for (0..count) |e| { - const ptr = base + e * kt * nt * tile; + var ptr: u64 = base; + for (mine) |k2| { // each expert's trellis follows the one before, at its own width try L.host.appendSlice(L.gpa, std.mem.asBytes(&ptr)); + ptr += kt * nt * tileBytes(@intCast(k2)); } @field(out, tw) = try L.put("layers.{d}.moe.exl3." ++ tw ++ "_ptrs", .{i}); for (0..count) |e| { // suh: the input's scales (gate, up: every input; down: the rank's) const t = try L.get("layers.{d}.mlp.experts.{d}." ++ proj ++ ".suh", .{ i, e }); - if (t.dtype != .f16 or t.numel() != m.k) return error.NotExl3Mcg4; - const mine = if (m.by_cols) t.bytes else t.bytes[cut.lo * 2 .. cut.hi * 2]; + if (t.dtype != .f16 or t.numel() != m.k) return error.UnreadableExl3; + const own = if (m.by_cols) t.bytes else t.bytes[cut.lo * 2 .. cut.hi * 2]; if (m.by_cols) { // one rotation shared by the layer's every gate and up input? - if (first_suh) |f| (if (!std.mem.eql(u8, f, mine)) { + if (first_suh) |f| (if (!std.mem.eql(u8, f, own)) { out.shx = false; - }) else first_suh = mine; + }) else first_suh = own; } - try L.host.appendSlice(L.gpa, mine); + try L.host.appendSlice(L.gpa, own); } @field(out, su) = try L.put("layers.{d}.moe.exl3." ++ su, .{i}); for (0..count) |e| { // svh: the output's scales (gate, up: the rank's; down: every output) const t = try L.get("layers.{d}.mlp.experts.{d}." ++ proj ++ ".svh", .{ i, e }); - if (t.dtype != .f16 or t.numel() != m.n) return error.NotExl3Mcg4; + if (t.dtype != .f16 or t.numel() != m.n) return error.UnreadableExl3; try L.host.appendSlice(L.gpa, if (m.by_cols) t.bytes[cut.lo * 2 .. cut.hi * 2] else t.bytes); } @field(out, sv) = try L.put("layers.{d}.moe.exl3." ++ sv, .{i}); } - for (0..count) |_| { - const bits: i32 = 8; - try L.host.appendSlice(L.gpa, std.mem.asBytes(&bits)); + out.uniform_gu = uniform(k2s[0 .. 2 * count]); + out.uniform_d = uniform(k2s[2 * count ..]); + const tabs = [3][]const i32{ k2s[0..count], k2s[count .. 2 * count], k2s[2 * count ..] }; + // one table, as a 4-bit layer has it + if (std.mem.eql(i32, tabs[0], tabs[1]) and std.mem.eql(i32, tabs[0], tabs[2])) { + try L.host.appendSlice(L.gpa, std.mem.sliceAsBytes(tabs[0])); + out.k2 = try L.put("layers.{d}.moe.exl3.k2", .{i}); + out.k2_up = out.k2; + out.k2_down = out.k2; + return out; + } + var ptrs: [3]u64 = undefined; + inline for (tabs, .{ "k2_gate", "k2_up", "k2_down" }, 0..) |tab, name, p| { // a table a distinct projection + var same: ?u64 = null; + for (tabs[0..p], ptrs[0..p]) |before, ptr| if (same == null and std.mem.eql(i32, before, tab)) { + same = ptr; + }; + ptrs[p] = same orelse blk: { + try L.host.appendSlice(L.gpa, std.mem.sliceAsBytes(tab)); + break :blk try L.put("layers.{d}.moe.exl3." ++ name, .{i}); + }; } - out.k2 = try L.put("layers.{d}.moe.exl3.k2", .{i}); + out.k2, out.k2_up, out.k2_down = ptrs; return out; } @@ -130,15 +220,35 @@ pub const top_k = 8; pub const chunk_rows = 1024; /// The prompt item plan has no decode grouper's shared-memory cap; one call covers a supported whole prompt pass. pub const prompt_rows = 4096; -fn layer(w: Experts, count: usize, dims: usize, width: usize, limit: f32) common.Layer { - return .{ .gate = w.gt, .up = w.ut, .down = w.dt, .gate_k2 = w.k2, .up_k2 = w.k2, .down_k2 = w.k2, .suh_g = w.suh_g, .suh_u = w.suh_u, .svh_g = w.svh_g, .svh_u = w.svh_u, .suh_d = w.suh_d, .svh_d = w.svh_d, .experts = count, .dims = dims, .width = width, .codebook = .mcg, .limit = limit, .act_mode = 0, .uniform_k2 = 8, .shared_input = w.shx }; -} -fn shape(dims: usize, width: usize) common.Layer { - const w: Experts = .{ .gt = 0, .ut = 0, .dt = 0, .k2 = 0, .suh_g = 0, .suh_u = 0, .svh_g = 0, .svh_u = 0, .suh_d = 0, .svh_d = 0, .shx = false }; - return layer(w, cuda.grouped.max_experts, dims, width, 0); +/// The common module's layer: a width table a projection, and the widths the loader found uniform. +pub fn layer(w: Experts, count: usize, dims: usize, width: usize, limit: f32) common.Layer { + return .{ + .gate = w.gt, + .up = w.ut, + .down = w.dt, + .gate_k2 = w.tables()[0], + .up_k2 = w.tables()[1], + .down_k2 = w.tables()[2], + .suh_g = w.suh_g, + .suh_u = w.suh_u, + .svh_g = w.svh_g, + .svh_u = w.svh_u, + .suh_d = w.suh_d, + .svh_d = w.svh_d, + .experts = count, + .dims = dims, + .width = width, + .codebook = .mcg, + .limit = limit, + .act_mode = 0, + .uniform_k2 = if (w.uniform_gu == w.uniform_d) w.uniform_gu else 0, + .uniform_k2_gu = w.uniform_gu, + .uniform_k2_d = w.uniform_d, + .shared_input = w.shx, + }; } /// A chunk's compacted picks ahead of the common scratch, 256-aligned; the usize keeps @min from narrowing to u7. -fn picksBytes(rows: usize) usize { +pub fn picksBytes(rows: usize) usize { const cap: usize = @min(rows, chunk_rows); return std.mem.alignForward(usize, cap * top_k * 4, 256); } @@ -146,12 +256,20 @@ fn picksBytes(rows: usize) usize { fn decodeBytes(l: common.Layer, n: usize) !usize { return @max(try common.scratchBytes(l, n, top_k), try common.fusedBytes(l, n, top_k + 1)); } -pub fn scratchBytes(rows: usize, dims: usize, width: usize, prefill: bool, shx: bool) [4]usize { - var l = shape(dims, width); - l.shared_input = shx; +/// The scratch `run` takes: the prompt kernels' when `prefill` and they take the layer, else the grouped path's. +pub fn scratchFor(rows: usize, dims: usize, width: usize, prefill: bool, w: Experts) [4]usize { + const l = layer(w, cuda.grouped.max_experts, dims, width, 0); if (prefill and common.prompt.eligible(l)) return .{ common.prompt.bytes(l, @min(rows, prompt_rows), top_k + 1) catch unreachable, 4, 4, 4 }; const n: usize = @min(rows, chunk_rows); - return .{ picksBytes(rows) + (decodeBytes(shape(dims, width), n) catch unreachable), 4, 4, 4 }; + return .{ picksBytes(rows) + (decodeBytes(l, n) catch unreachable), 4, 4, 4 }; +} +/// `scratchFor` a 4-bit layer (every projection 8 half-bits), `shx` its shared rotation. +pub fn scratchBytes(rows: usize, dims: usize, width: usize, prefill: bool, shx: bool) [4]usize { + return scratchFor(rows, dims, width, prefill, .{ .gt = 0, .ut = 0, .dt = 0, .k2 = 0, .suh_g = 0, .suh_u = 0, .svh_g = 0, .svh_u = 0, .suh_d = 0, .svh_d = 0, .uniform_gu = 8, .uniform_d = 8, .shx = shx }); +} +/// `most` raised to `w`'s scratch, entry by entry: buffers every layer's experts run in take the largest. +pub fn mostScratch(most: *[4]usize, rows: usize, dims: usize, width: usize, prefill: bool, w: Experts) void { + for (most, scratchFor(rows, dims, width, prefill, w)) |*m, v| m.* = @max(m.*, v); } /// `height` rows of `width` bytes, `spitch` apart at `src`, to `dpitch` apart at `dst`, in one call. fn copyRows(stream: cuda.Stream, dst: u64, dpitch: usize, src: u64, spitch: usize, width: usize, height: usize, what: []const u8) !void { @@ -161,7 +279,7 @@ fn copyRows(stream: cuda.Stream, dst: u64, dpitch: usize, src: u64, spitch: usiz pub fn run(k: *const Kernels, ek: *const experts.Kernels, stream: cuda.Stream, w: Experts, sc: Scratch, plan_buf: cuda.grouped.Plan, x: u64, x_stride: usize, picks: u64, slots: usize, rows: usize, count: usize, dims: usize, width: usize, limit: f32, prompt: bool, ey: u64, xd: u64) !void { _ = xd; if (slots != top_k + 1) return error.UnsupportedTopK; - if (dims % 256 != 0 or width % 128 != 0) return error.NotExl3Mcg4; + if (dims % 256 != 0 or width % 128 != 0) return error.UnreadableExl3; const l = layer(w, count, dims, width, limit); if (prompt and common.prompt.eligible(l)) { const scratch = try common.prompt.scratch(sc.picks, l, @min(rows, prompt_rows), slots); @@ -201,20 +319,8 @@ fn compact(k: *const Kernels, stream: cuda.Stream, w: Experts, sc: Scratch, x: u } } -test "EXL3 admission: Mia-AiLab's block passes; other widths and codebooks are refused by name" { - const gpa = std.testing.allocator; - const mia = - \\{"quantization_config": {"quant_method": "exl3", "bits": 4, "codebook": "mcg", "head_bits": 16}} - ; - try std.testing.expect(isExl3(gpa, mia)); - var why: modelopt.Why = .{}; - try admit(gpa, mia, &why); - try std.testing.expect(!isExl3(gpa, "{\"quantization_config\": {\"quant_method\": \"modelopt\"}}")); - try std.testing.expect(!isExl3(gpa, "{}")); - try std.testing.expectError(error.UnsupportedQuant, admit(gpa, "{\"quantization_config\": {\"quant_method\": \"exl3\", \"bits\": 3, \"codebook\": \"mcg\"}}", &why)); - try std.testing.expectEqualStrings("EXL3 at 3 bits: the CUDA family reads 4-bit EXL3 experts", why.text()); - try std.testing.expectError(error.UnsupportedQuant, admit(gpa, "{\"text_config\": {\"quantization_config\": {\"quant_method\": \"exl3\", \"bits\": 4, \"codebook\": \"mul1\"}}}", &why)); - try std.testing.expectEqualStrings("EXL3 codebook \"mul1\": the CUDA family reads \"mcg\"", why.text()); +test { + _ = @import("cuda_exl3_test.zig"); } test "a chunk's compacted picks end before the common scratch at every row count" { diff --git a/zig/src/families/glm/cuda_exl3_test.zig b/zig/src/families/glm/cuda_exl3_test.zig new file mode 100644 index 00000000000..92e6d02b649 --- /dev/null +++ b/zig/src/families/glm/cuda_exl3_test.zig @@ -0,0 +1,360 @@ +//! GLM EXL3: admission, trellis widths, the loader's uploads (mixed widths, 4-bit bytes as upstream's) and scratch. +const std = @import("std"); +const core = @import("core"); +const cuda = @import("cuda"); +const x3 = @import("cuda_exl3.zig"); +const modelopt = core.modelopt; +const Tensor = core.checkpoint.Tensor; +const Span = @import("cuda_shard.zig").Span; +const testing = std.testing; + +test "GLM EXL3: Mia-AiLab's 4-bit block and a mixed block without bits pass; other widths and codebooks are refused by name" { + const gpa = testing.allocator; + const mia = + \\{"quantization_config": {"quant_method": "exl3", "bits": 4, "codebook": "mcg", "head_bits": 16}} + ; + try testing.expect(x3.isExl3(gpa, mia)); + var why: modelopt.Why = .{}; + try x3.admit(gpa, mia, &why); + const mixed = // the 3.5 bpw checkpoint's: no "bits", its average instead + \\{"quantization_config": {"quant_method": "exl3", "avg_bits": 3.5039, "codebook": "mcg", "head_bits": 16, "scope": "glm53_routed_experts_only"}} + ; + try testing.expect(x3.isExl3(gpa, mixed)); + try x3.admit(gpa, mixed, &why); + try x3.admit(gpa, "{\"quantization_config\": {\"quant_method\": \"exl3\", \"bits\": 3, \"codebook\": \"mcg\"}}", &why); + try x3.admit(gpa, "{\"quantization_config\": {\"quant_method\": \"exl3\", \"bits\": 8.0, \"codebook\": \"mcg\"}}", &why); + try x3.admit(gpa, "{\"quantization_config\": {\"quant_method\": \"exl3\", \"codebook\": \"mcg\"}}", &why); + try testing.expect(!x3.isExl3(gpa, "{\"quantization_config\": {\"quant_method\": \"modelopt\"}}")); + try testing.expect(!x3.isExl3(gpa, "{}")); + try testing.expectError(error.UnsupportedQuant, x3.admit(gpa, "{\"quantization_config\": {\"quant_method\": \"exl3\", \"bits\": 9, \"codebook\": \"mcg\"}}", &why)); + try testing.expectEqualStrings("EXL3 at 9 bits: the CUDA family reads mcg experts of 1 to 8 whole bits", why.text()); + try testing.expectError(error.UnsupportedQuant, x3.admit(gpa, "{\"quantization_config\": {\"quant_method\": \"exl3\", \"bits\": 3.5, \"codebook\": \"mcg\"}}", &why)); + try testing.expectEqualStrings("EXL3 at 3.5 bits: the CUDA family reads mcg experts of 1 to 8 whole bits", why.text()); + try testing.expectError(error.UnsupportedQuant, x3.admit(gpa, "{\"quantization_config\": {\"quant_method\": \"exl3\", \"bits\": \"4\", \"codebook\": \"mcg\"}}", &why)); + try testing.expectError(error.UnsupportedQuant, x3.admit(gpa, "{\"quantization_config\": {\"quant_method\": \"exl3\", \"avg_bits\": 0.5, \"codebook\": \"mcg\"}}", &why)); + try testing.expectEqualStrings("EXL3 averaging 0.5 bits: the CUDA family reads mcg experts of 1 to 8 bits", why.text()); + try testing.expectError(error.UnsupportedQuant, x3.admit(gpa, "{\"text_config\": {\"quantization_config\": {\"quant_method\": \"exl3\", \"bits\": 4, \"codebook\": \"mul1\"}}}", &why)); + try testing.expectEqualStrings("EXL3 codebook \"mul1\": the CUDA family reads \"mcg\"", why.text()); + try testing.expectError(error.UnsupportedQuant, x3.admit(gpa, "{\"quantization_config\": {\"quant_method\": \"exl3\", \"avg_bits\": 3.5}}", &why)); + try testing.expectEqualStrings("EXL3 codebook null: the CUDA family reads \"mcg\"", why.text()); +} + +test "GLM EXL3: a trellis's last dimension gives whole-bit mcg widths from 1 to 8; half steps and wider are refused" { + for ([_][2]usize{ .{ 16, 2 }, .{ 32, 4 }, .{ 48, 6 }, .{ 64, 8 }, .{ 80, 10 }, .{ 96, 12 }, .{ 112, 14 }, .{ 128, 16 } }) |c| + try testing.expectEqual(@as(?u32, @as(u32, @intCast(c[1]))), x3.halves(c[0])); + for ([_]usize{ 0, 8, 24, 40, 56, 50, 136, 144 }) |last| try testing.expectEqual(@as(?u32, null), x3.halves(last)); + try testing.expectEqual(@as(usize, 128), x3.tileBytes(8)); + try testing.expectEqual(@as(usize, 96), x3.tileBytes(6)); +} + +/// A checkpoint in memory and device uploads recorded on the host, as cuda_weights' loader is to `load`. +const Mock = struct { + gpa: std.mem.Allocator, + arena: std.heap.ArenaAllocator, + tensors: std.StringHashMapUnmanaged(Tensor) = .empty, + host: std.ArrayList(u8) = .empty, + puts: std.ArrayList(Put) = .empty, + name_buf: [192]u8 = undefined, + last: []const u8 = "", + next: u64 = 0x7f00_0000_0000, + + const Put = struct { name: []const u8, bytes: []const u8, ptr: u64 }; + + fn init(gpa: std.mem.Allocator) Mock { + return .{ .gpa = gpa, .arena = .init(gpa) }; + } + fn deinit(m: *Mock) void { + m.host.deinit(m.gpa); + m.arena.deinit(); + } + pub fn get(m: *Mock, comptime fmt: []const u8, args: anytype) !Tensor { + m.last = try std.fmt.bufPrint(&m.name_buf, fmt, args); + return m.tensors.get(m.last) orelse error.MissingTensor; + } + pub fn put(m: *Mock, comptime fmt: []const u8, args: anytype) !u64 { + const a = m.arena.allocator(); + const ptr = m.next; + m.next += std.mem.alignForward(u64, m.host.items.len + 1, 1 << 20); + try m.puts.append(a, .{ .name = try std.fmt.allocPrint(a, fmt, args), .bytes = try a.dupe(u8, m.host.items), .ptr = ptr }); + m.host.clearRetainingCapacity(); + return ptr; + } + fn add(m: *Mock, name: []const u8, dtype: core.checkpoint.DType, shape: []const usize, bytes: []const u8) !void { + const a = m.arena.allocator(); + var t: Tensor = .{ .dtype = dtype, .rank = @intCast(shape.len), .shape = @splat(0), .bytes = try a.dupe(u8, bytes) }; + @memcpy(t.shape[0..shape.len], shape); + try m.tensors.put(a, try a.dupe(u8, name), t); + } + fn find(m: *const Mock, name: []const u8) ?Put { + for (m.puts.items) |p| if (std.mem.eql(u8, p.name, name)) return p; + return null; + } +}; + +const projs = [_][]const u8{ "gate_proj", "up_proj", "down_proj" }; + +/// Layer `i`'s experts: p of e at `k2s[p][e]` half-bits, random mcg words and scales; `shared`: one input scale. +fn synth(m: *Mock, rng: std.Random, i: u32, count: usize, dims: usize, inter: usize, k2s: [3][]const u32, shared: bool) !void { + const a = m.arena.allocator(); + const rot = try a.alloc(u8, dims * 2); + rng.bytes(rot); + for (projs, 0..) |proj, p| { + const k = if (p < 2) dims else inter; + const n = if (p < 2) inter else dims; + for (0..count) |e| { + var buf: [128]u8 = undefined; + const k2 = k2s[p][e]; + const words = try a.alloc(u8, k / 16 * (n / 16) * 16 * k2); + rng.bytes(words); + try m.add(try std.fmt.bufPrint(&buf, "layers.{d}.mlp.experts.{d}.{s}.trellis", .{ i, e, proj }), .i16, &.{ k / 16, n / 16, 8 * k2 }, words); + var marker: [4]u8 = undefined; + std.mem.writeInt(u32, &marker, core.exl3_load.markers[0].value, .little); + try m.add(try std.fmt.bufPrint(&buf, "layers.{d}.mlp.experts.{d}.{s}.mcg", .{ i, e, proj }), .i32, &.{1}, &marker); + const suh = try a.alloc(u8, k * 2); + if (shared and p < 2) @memcpy(suh, rot) else rng.bytes(suh); + try m.add(try std.fmt.bufPrint(&buf, "layers.{d}.mlp.experts.{d}.{s}.suh", .{ i, e, proj }), .f16, &.{k}, suh); + const svh = try a.alloc(u8, n * 2); + rng.bytes(svh); + try m.add(try std.fmt.bufPrint(&buf, "layers.{d}.mlp.experts.{d}.{s}.svh", .{ i, e, proj }), .f16, &.{n}, svh); + } + } +} + +/// The rank's tiles of projection `p`, tile by tile (gate/up: every tile row, `cut`'s cols; down: `cut`'s rows). +fn expectedTiles(m: *Mock, i: u32, count: usize, dims: usize, inter: usize, cut: Span, p: usize) ![]u8 { + var out: std.ArrayList(u8) = .empty; + const k = if (p < 2) dims else inter; + const n = if (p < 2) inter else dims; + for (0..count) |e| { + var buf: [128]u8 = undefined; + const t = m.tensors.get(try std.fmt.bufPrint(&buf, "layers.{d}.mlp.experts.{d}.{s}.trellis", .{ i, e, projs[p] })).?; + const tile = t.dim(2) * 2; + const rows: [2]usize = if (p < 2) .{ 0, k / 16 } else .{ cut.lo / 16, cut.hi / 16 }; + const cols: [2]usize = if (p < 2) .{ cut.lo / 16, cut.hi / 16 } else .{ 0, n / 16 }; + for (rows[0]..rows[1]) |r| for (cols[0]..cols[1]) |c| + try out.appendSlice(m.arena.allocator(), t.bytes[(r * (n / 16) + c) * tile ..][0..tile]); + } + return out.items; +} + +fn ptrsOf(bytes: []const u8) []align(1) const u64 { + return std.mem.bytesAsSlice(u64, bytes); +} + +/// Every projection's tiles, pointers and width table as `load` uploaded them, vs the checkpoint, tile by tile. +fn expectUploads(m: *Mock, w: x3.Experts, i: u32, count: usize, dims: usize, inter: usize, cut: Span, k2s: [3][]const u32) !void { + for ([_][]const u8{ "gt", "ut", "dt" }, [_]u64{ w.gt, w.ut, w.dt }, 0..) |tw, ptrs_at, p| { + var buf: [96]u8 = undefined; + const words = m.find(try std.fmt.bufPrint(&buf, "layers.{d}.moe.exl3.{s}", .{ i, tw })).?; + try testing.expectEqualSlices(u8, try expectedTiles(m, i, count, dims, inter, cut, p), words.bytes); + const ptrs = m.find(try std.fmt.bufPrint(&buf, "layers.{d}.moe.exl3.{s}_ptrs", .{ i, tw })).?; + try testing.expectEqual(ptrs.ptr, ptrs_at); + const tiles = if (p < 2) dims / 16 * (cut.len() / 16) else cut.len() / 16 * (dims / 16); + var at = words.ptr; + for (ptrsOf(ptrs.bytes), 0..) |ptr, e| { + try testing.expectEqual(at, ptr); + at += tiles * 16 * k2s[p][e]; + } + try testing.expectEqual(words.ptr + words.bytes.len, at); + const table = for (m.puts.items) |put| { + if (put.ptr == w.tables()[p]) break put; + } else return error.NoTable; + for (std.mem.bytesAsSlice(i32, table.bytes), k2s[p]) |got, want| try testing.expectEqual(@as(i32, @intCast(want)), got); + } +} + +test "GLM EXL3: a mixed layer (3-bit gate and up, 4-bit down) loads each width's tiles, pointers and tables on either rank" { + const gpa = testing.allocator; + var prng = std.Random.DefaultPrng.init(53); + const count = 5; + const dims = 256; + const inter = 512; + const gu: [count]u32 = @splat(6); + const dn: [count]u32 = @splat(8); + const k2s: [3][]const u32 = .{ &gu, &gu, &dn }; + for ([_]Span{ .{ .lo = 0, .hi = 256 }, .{ .lo = 256, .hi = 512 }, .{ .lo = 128, .hi = 384 } }) |cut| { + var m = Mock.init(gpa); + defer m.deinit(); + try synth(&m, prng.random(), 4, count, dims, inter, k2s, true); + const w = try x3.load(&m, 4, count, dims, inter, cut); + try expectUploads(&m, w, 4, count, dims, inter, cut, k2s); + try testing.expectEqual(@as(u32, 6), w.uniform_gu); + try testing.expectEqual(@as(u32, 8), w.uniform_d); + try testing.expect(w.shx); + try testing.expectEqual(w.k2, w.k2_up); // gate and up's widths agree: one table + try testing.expect(w.k2 != w.k2_down); + try testing.expect(m.find("layers.4.moe.exl3.k2_gate") != null and m.find("layers.4.moe.exl3.k2_down") != null); + try testing.expect(m.find("layers.4.moe.exl3.k2_up") == null and m.find("layers.4.moe.exl3.k2") == null); + const l = x3.layer(w, count, dims, cut.len(), 10); + try testing.expectEqual(@as(u32, 0), l.uniform_k2); // gate/up and down differ: no one width + try testing.expectEqual(@as(u32, 6), l.uniform_k2_gu); + try testing.expectEqual(@as(u32, 8), l.uniform_k2_d); + try testing.expect(l.gate_k2 == w.k2 and l.up_k2 == w.k2_up and l.down_k2 == w.k2_down); + } +} + +test "GLM EXL3: widths that differ by expert and projection keep their own offsets; no uniform width is claimed" { + const gpa = testing.allocator; + var prng = std.Random.DefaultPrng.init(7); + const count = 4; + const g = [count]u32{ 6, 8, 2, 16 }; + const u = [count]u32{ 8, 8, 8, 8 }; + const d = [count]u32{ 4, 6, 8, 12 }; + const k2s: [3][]const u32 = .{ &g, &u, &d }; + var m = Mock.init(gpa); + defer m.deinit(); + try synth(&m, prng.random(), 9, count, 256, 256, k2s, false); + const cut: Span = .{ .lo = 128, .hi = 256 }; + const w = try x3.load(&m, 9, count, 256, 256, cut); + try expectUploads(&m, w, 9, count, 256, 256, cut, k2s); + try testing.expectEqual(@as(u32, 0), w.uniform_gu); + try testing.expectEqual(@as(u32, 0), w.uniform_d); + try testing.expect(!w.shx); + try testing.expect(w.k2 != w.k2_up and w.k2_up != w.k2_down and w.k2 != w.k2_down); + const l = x3.layer(w, count, 256, 128, 10); + try testing.expect(l.uniform_k2 == 0 and l.uniform_k2_gu == 0 and l.uniform_k2_d == 0); + try testing.expect(!cuda.exl3_experts.prompt.eligible(l)); +} + +test "GLM EXL3: a trellis at a width the kernels do not read, or of the wrong shape, is refused with its reason" { + const bytes: [72 * 2 * 2 * 2]u8 = @splat(0); + var t: Tensor = .{ .dtype = .i16, .rank = 3, .shape = .{ 2, 2, 40, 0, 0 }, .bytes = bytes[0 .. 2 * 2 * 40 * 2] }; + try testing.expect(x3.refusal(t, 32, 32) != null); // 2.5 bits: mul1's half steps + t.shape[2] = 72; // 4.5 bits + t.bytes = bytes[0 .. 2 * 2 * 72 * 2]; + try testing.expect(x3.refusal(t, 32, 32) != null); + t.shape[2] = 64; + t.bytes = bytes[0 .. 2 * 2 * 64 * 2]; + try testing.expectEqual(@as(?[]const u8, null), x3.refusal(t, 32, 32)); + try testing.expect(x3.refusal(t, 48, 32) != null); // tiles that do not cover K + t.dtype = .i32; + try testing.expect(x3.refusal(t, 32, 32) != null); + t.dtype = .i16; + t.bytes = bytes[0..10]; + try testing.expect(x3.refusal(t, 32, 32) != null); +} + +/// Upstream's 4-bit loader (f350cd3e), verbatim but its result's type: a 4-bit layer uploads exactly these bytes. +const Upstream = struct { gt: u64, ut: u64, dt: u64, suh_g: u64, suh_u: u64, svh_g: u64, svh_u: u64, suh_d: u64, svh_d: u64, k2: u64, shx: bool }; +fn upstream4(L: anytype, i: u32, count: usize, dims: usize, inter: usize, cut: Span) !Upstream { + const tile = 128; + if (dims % 128 != 0 or cut.lo % 128 != 0 or cut.hi % 128 != 0) return error.NotExl3Mcg4; + const width = cut.len(); + var out: Upstream = undefined; + out.shx = true; + const Mat = struct { k: usize, n: usize, by_cols: bool }; + const mats = [_]Mat{ + .{ .k = dims, .n = inter, .by_cols = true }, + .{ .k = dims, .n = inter, .by_cols = true }, + .{ .k = inter, .n = dims, .by_cols = false }, + }; + var first_suh: ?[]const u8 = null; + inline for (mats, .{ "gate_proj", "up_proj", "down_proj" }, .{ "gt", "ut", "dt" }, .{ "suh_g", "suh_u", "suh_d" }, .{ "svh_g", "svh_u", "svh_d" }) |m, proj, tw, su, sv| { + const kt = (if (m.by_cols) m.k else width) / 16; + const nt = (if (m.by_cols) width else m.n) / 16; + for (0..count) |e| { + const t = try L.get("layers.{d}.mlp.experts.{d}." ++ proj ++ ".trellis", .{ i, e }); + if (t.dtype != .i16 or t.rank != 3 or t.dim(0) != m.k / 16 or t.dim(1) != m.n / 16 or t.dim(2) != 64) return error.NotExl3Mcg4; + const marker = L.get("layers.{d}.mlp.experts.{d}." ++ proj ++ ".mcg", .{ i, e }) catch return error.NotExl3Mcg4; + if (marker.dtype != .i32 or marker.numel() != 1 or marker.bytes.len != 4 or + std.mem.readInt(u32, marker.bytes[0..4], .little) != core.exl3_load.markers[0].value) + return error.NotExl3Mcg4; + if (m.by_cols) { + const row = (m.n / 16) * tile; + for (0..kt) |r| try L.host.appendSlice(L.gpa, t.bytes[r * row + (cut.lo / 16) * tile ..][0 .. nt * tile]); + } else try L.host.appendSlice(L.gpa, t.bytes[(cut.lo / 16) * nt * tile ..][0 .. kt * nt * tile]); + } + const base = try L.put("layers.{d}.moe.exl3." ++ tw, .{i}); + for (0..count) |e| { + const ptr = base + e * kt * nt * tile; + try L.host.appendSlice(L.gpa, std.mem.asBytes(&ptr)); + } + @field(out, tw) = try L.put("layers.{d}.moe.exl3." ++ tw ++ "_ptrs", .{i}); + for (0..count) |e| { + const t = try L.get("layers.{d}.mlp.experts.{d}." ++ proj ++ ".suh", .{ i, e }); + if (t.dtype != .f16 or t.numel() != m.k) return error.NotExl3Mcg4; + const mine = if (m.by_cols) t.bytes else t.bytes[cut.lo * 2 .. cut.hi * 2]; + if (m.by_cols) { + if (first_suh) |f| (if (!std.mem.eql(u8, f, mine)) { + out.shx = false; + }) else first_suh = mine; + } + try L.host.appendSlice(L.gpa, mine); + } + @field(out, su) = try L.put("layers.{d}.moe.exl3." ++ su, .{i}); + for (0..count) |e| { + const t = try L.get("layers.{d}.mlp.experts.{d}." ++ proj ++ ".svh", .{ i, e }); + if (t.dtype != .f16 or t.numel() != m.n) return error.NotExl3Mcg4; + try L.host.appendSlice(L.gpa, if (m.by_cols) t.bytes[cut.lo * 2 .. cut.hi * 2] else t.bytes); + } + @field(out, sv) = try L.put("layers.{d}.moe.exl3." ++ sv, .{i}); + } + for (0..count) |_| { + const bits: i32 = 8; + try L.host.appendSlice(L.gpa, std.mem.asBytes(&bits)); + } + out.k2 = try L.put("layers.{d}.moe.exl3.k2", .{i}); + return out; +} + +test "GLM EXL3: a 4-bit layer uploads upstream's bytes, names and pointers, and keeps one width (8) for every path" { + const gpa = testing.allocator; + for ([_]bool{ true, false }, [_]Span{ .{ .lo = 256, .hi = 512 }, .{ .lo = 0, .hi = 512 } }) |shared, cut| { + var prng = std.Random.DefaultPrng.init(4); + const count = 6; + const four: [count]u32 = @splat(8); + var m = Mock.init(gpa); + defer m.deinit(); + try synth(&m, prng.random(), 3, count, 256, 512, .{ &four, &four, &four }, shared); + var old = Mock.init(gpa); + defer old.deinit(); + old.tensors = m.tensors; + const want = try upstream4(&old, 3, count, 256, 512, cut); + const got = try x3.load(&m, 3, count, 256, 512, cut); + try testing.expectEqual(old.puts.items.len, m.puts.items.len); + for (old.puts.items, m.puts.items) |a, b| { + try testing.expectEqualStrings(a.name, b.name); + try testing.expectEqual(a.ptr, b.ptr); + try testing.expectEqualSlices(u8, a.bytes, b.bytes); + } + inline for (.{ "gt", "ut", "dt", "suh_g", "suh_u", "svh_g", "svh_u", "suh_d", "svh_d", "k2", "shx" }) |f| try testing.expectEqual(@field(want, f), @field(got, f)); + try testing.expectEqual([3]u64{ want.k2, want.k2, want.k2 }, got.tables()); + try testing.expect(got.uniform_gu == 8 and got.uniform_d == 8); + const l = x3.layer(got, count, 256, cut.len(), 10); + try testing.expect(l.uniform_k2 == 8 and l.uniform_k2_gu == 8 and l.uniform_k2_d == 8); + try testing.expect(l.shared_input == shared); + } +} + +test "GLM EXL3: scratch covers the path each layer takes: the prompt kernels' when they take it, else the grouped path's" { + const dims = 4096; + const width = 1024; + const four: x3.Experts = .{ .gt = 0, .ut = 0, .dt = 0, .suh_g = 0, .suh_u = 0, .svh_g = 0, .svh_u = 0, .suh_d = 0, .svh_d = 0, .k2 = 0, .uniform_gu = 8, .uniform_d = 8, .shx = true }; + var mixed = four; + mixed.uniform_gu = 6; + var any = four; + any.uniform_gu = 0; + any.uniform_d = 0; + const common = cuda.exl3_experts; + for ([_]usize{ 1, 8, 200, 1024, 2048, 4102 }) |rows| { + const n: usize = @min(rows, x3.chunk_rows); + const whole: usize = @min(rows, x3.prompt_rows); // the prompt kernels take a whole pass of top_k + 1 slots + for ([_]x3.Experts{ four, mixed, any }) |w| for ([_]bool{ false, true }) |prefill| { + const l = x3.layer(w, cuda.grouped.max_experts, dims, width, 0); + const prompt = prefill and common.prompt.eligible(l); + const need = if (prompt) try common.prompt.bytes(l, whole, x3.top_k + 1) else x3.picksBytes(rows) + try common.scratchBytes(l, n, x3.top_k); + try testing.expectEqual(need, x3.scratchFor(rows, dims, width, prefill, w)[0]); + }; + // a 4-bit layer's scratch is upstream's: the prompt kernels', or picks then the grouped path's + const upstream: common.Layer = .{ .gate = 0, .up = 0, .down = 0, .gate_k2 = 0, .up_k2 = 0, .down_k2 = 0, .suh_g = 0, .suh_u = 0, .svh_g = 0, .svh_u = 0, .suh_d = 0, .svh_d = 0, .experts = cuda.grouped.max_experts, .dims = dims, .width = width, .codebook = .mcg, .act_mode = 0, .uniform_k2 = 8, .shared_input = true }; + try testing.expectEqual(try common.prompt.bytes(upstream, whole, x3.top_k + 1), x3.scratchFor(rows, dims, width, true, four)[0]); + try testing.expectEqual(x3.picksBytes(rows) + try common.scratchBytes(upstream, n, x3.top_k), x3.scratchFor(rows, dims, width, false, four)[0]); + for ([_]bool{ false, true }) |prefill| try testing.expectEqual(x3.scratchFor(rows, dims, width, prefill, four), x3.scratchBytes(rows, dims, width, prefill, true)); + // buffers for every layer take the largest: a 4-bit layer's prompt arena grows to the mixed layer's grouped one + var most: [4]usize = @splat(4); + x3.mostScratch(&most, rows, dims, width, true, four); + x3.mostScratch(&most, rows, dims, width, true, any); + try testing.expectEqual(@max(x3.scratchFor(rows, dims, width, true, four)[0], x3.scratchFor(rows, dims, width, true, any)[0]), most[0]); + try testing.expectEqual([3]usize{ 4, 4, 4 }, most[1..4].*); + } +} diff --git a/zig/src/families/glm/cuda_forward.zig b/zig/src/families/glm/cuda_forward.zig index 34ace9226db..fefb4ac197a 100644 --- a/zig/src/families/glm/cuda_forward.zig +++ b/zig/src/families/glm/cuda_forward.zig @@ -46,6 +46,7 @@ pub const Modules = struct { mm: mm_mod.Kernels, // glm_mm: the bf16 linears on tiled weights index: ?index_mod.Kernels, // TF_GLM_INDEX_CUDA: a prompt chunk's indexer scores and pools (glm_index) dsel: bool, // TF_GLM_DSEL (default on): a decode window's DSA select on many CTAs (cuda_sparse.decodeSelect) + dscore: ?index_mod.Kernels, // TF_GLM_DSCORES (default on): a decode window's index scores on glm_index_scores tiled: bool = false, // eligible bf16 linears are tiled; KDA inputs with uneven strides retain their row-major path packs: ?*const mm_mod.Packed = null, // the linears packed to 4, 6 or 8 bits (TF_GLM_DENSE_BITS, _HEAD_BITS) copy_rows: cuda.Function, @@ -91,6 +92,14 @@ pub const Modules = struct { }; m.dsel = try @import("sys").environment.read(bool, "TF_GLM_DSEL", true); if (!m.dsel) std.log.warn("TF_GLM_DSEL=0: a decode window's DSA select keeps one 1,024-thread CTA a row", .{}); + m.dscore = null; + errdefer if (m.dscore) |*x| x.unload(); + if (try @import("sys").environment.read(bool, "TF_GLM_DSCORES", true)) { + m.dscore = index_mod.Kernels.load(d, k.glm_index, .scores) catch |err| blk: { + std.log.warn("TF_GLM_DSCORES: glm_index is not loaded ({t}); decode windows keep tf_glm_scores", .{err}); + break :blk null; + }; + } else std.log.warn("TF_GLM_DSCORES=0: a decode window's index scores keep tf_glm_scores", .{}); m.tiled = false; m.packs = null; // `m` starts undefined: the field default does not apply return m; @@ -107,6 +116,7 @@ pub const Modules = struct { pub fn deinit(m: *Modules) void { if (m.index) |*x| x.unload(); + if (m.dscore) |*x| x.unload(); m.exl3.unload(); for (&m.mods) |*x| x.unload(); m.lane.unload(); @@ -165,7 +175,7 @@ pub const Forward = struct { } pub fn set(f: *const Forward) glue.Set { - return .{ .glue = &f.m.glue, .index = if (f.m.index) |*x| x else null, .mm = if (f.m.tiled) &f.m.mm else null, .packs = f.m.packs, .prompt = f.ranks[0].b.prefill, .linear = .{ .lane = &f.m.lane }, .copy_rows = f.m.copy_rows, .dsel = f.m.dsel }; + return .{ .glue = &f.m.glue, .index = if (f.m.index) |*x| x else null, .mm = if (f.m.tiled) &f.m.mm else null, .packs = f.m.packs, .prompt = f.ranks[0].b.prefill, .linear = .{ .lane = &f.m.lane }, .copy_rows = f.m.copy_rows, .dsel = f.m.dsel, .dscore = if (f.m.dscore) |*x| x else null }; } /// The layer sums' boundary (cuda_boundary.zig): every rank's fp32 partial into every gathered buffer. diff --git a/zig/src/families/glm/cuda_glue.zig b/zig/src/families/glm/cuda_glue.zig index b2b088ac715..631d570dcd1 100644 --- a/zig/src/families/glm/cuda_glue.zig +++ b/zig/src/families/glm/cuda_glue.zig @@ -17,6 +17,8 @@ pub const Set = struct { copy_rows: ?cuda.Function = null, /// A decode window's DSA select on many CTAs (cuda_sparse.decodeSelect; TF_GLM_DSEL, default on). dsel: bool = false, + /// A decode window's index scores on glm_index_scores (TF_GLM_DSCORES; null keeps tf_glm_scores). + dscore: ?*const index_mod.Kernels = null, }; /// A hidden-size norm's weight: bf16, or float32 (FP4-Local's) read as float32 by the _f32w kernels. diff --git a/zig/src/families/glm/cuda_index.zig b/zig/src/families/glm/cuda_index.zig index 70f986ce4e0..78b727bf681 100644 --- a/zig/src/families/glm/cuda_index.zig +++ b/zig/src/families/glm/cuda_index.zig @@ -38,6 +38,12 @@ pub const Mode = enum { } }; +/// A decode window's 64-pool tiles a CTA by its rows and blocks, fit to a sweep on GB10 (speed only). +pub fn decodeLoop(rows: usize, nb: usize) usize { + const want: usize = if (rows <= 4) 1 else if (rows <= 8) 2 else rows / 4 * ((nb + 1023) / 1024); + return @max(1, @min(@min(score_tiles, want), @max(1, nb / 32))); +} + /// glm_index_scores' grid: rows in CTAs of 8, the `nb` pool blocks in runs of score_tiles. pub fn scoresGrid(rows: usize, nb: usize) [2]u32 { return .{ @intCast(cdiv(rows, score_rows)), @intCast(@max(1, cdiv(nb, score_tiles))) }; @@ -77,11 +83,23 @@ pub const Kernels = struct { return rows >= rows_from and np >= topk and pk % 16 == 0 and ps % 16 == 0; } + /// Whether a decode window takes the scores kernel: under rows_from rows, 8 from 64 blocks (4 from 2,048), aligned. + pub fn takesDecode(k: *const Kernels, rows: usize, np: usize, nb: usize, pk: u64, ps: u64) bool { + _ = k; + const wide = (rows >= 8 and nb >= 64) or (rows >= 4 and nb >= 2048); + return wide and rows < rows_from and np >= topk and pk % 16 == 0 and ps % 16 == 0; + } + /// tf_glm_scores' launch for `rows` rows at `at` into out [rows][np]; the first `nb` 64-pool blocks are written. pub fn scores(k: *const Kernels, s: cuda.Stream, qi: u64, wts: u64, w_stride: usize, pk: u64, out: u64, at: u64, rows: usize, np: usize, nb: usize, scale: f32, wscale: f32, heads: usize, pt: u64, ps: u64) !void { - const g = scoresGrid(rows, nb); + return k.scoresTiles(s, qi, wts, w_stride, pk, out, at, rows, np, nb, scale, wscale, heads, pt, ps, score_tiles); + } + + /// As scores, `loop` 64-pool tiles a CTA (speed only: every tiling writes the same scores). + pub fn scoresTiles(k: *const Kernels, s: cuda.Stream, qi: u64, wts: u64, w_stride: usize, pk: u64, out: u64, at: u64, rows: usize, np: usize, nb: usize, scale: f32, wscale: f32, heads: usize, pt: u64, ps: u64, loop: usize) !void { + const g: [2]u32 = .{ @intCast(cdiv(rows, score_rows)), @intCast(@max(1, cdiv(nb, loop))) }; var a: cuda.Args = .{}; - inline for (.{ qi, wts, @as(i64, @intCast(w_stride)), pk, out, at, @as(i64, @intCast(rows)), @as(i64, @intCast(np)), @as(i64, @intCast(nb)), scale, wscale, @as(i64, @intCast(heads)), @as(c_int, score_tiles), pt, @as(i64, @intCast(ps)) }) |v| a.add(v); + inline for (.{ qi, wts, @as(i64, @intCast(w_stride)), pk, out, at, @as(i64, @intCast(rows)), @as(i64, @intCast(np)), @as(i64, @intCast(nb)), scale, wscale, @as(i64, @intCast(heads)), @as(c_int, @intCast(loop)), pt, @as(i64, @intCast(ps)) }) |v| a.add(v); try cuda_pdl.launch(k.scores_fn, .{ .grid = .{ .x = g[0], .y = g[1] }, .block = .{ .x = threads } }, s, &a); } @@ -125,6 +143,32 @@ test "GLM index: the candidate cap follows the pool count and stays in shared me try std.testing.expect(tile(1 << 30).cap <= cap_max); } +test "GLM index: a decode window's tiles a CTA follow its rows and blocks" { + try std.testing.expectEqual(@as(usize, 1), decodeLoop(4, 4064)); // 4 rows at 1M: a tile a CTA + try std.testing.expectEqual(@as(usize, 2), decodeLoop(8, 4064)); + try std.testing.expectEqual(@as(usize, 16), decodeLoop(16, 4064)); // 1M: 1,024 blocks round up + try std.testing.expectEqual(@as(usize, 8), decodeLoop(16, 2048)); // 512K + try std.testing.expectEqual(@as(usize, score_tiles), decodeLoop(32, 4064)); + try std.testing.expectEqual(@as(usize, 4), decodeLoop(16, 1024)); // 256K + try std.testing.expectEqual(@as(usize, 2), decodeLoop(32, 64)); // 16K: nb / 32 keeps the CTAs + try std.testing.expectEqual(@as(usize, 1), decodeLoop(8, 8)); + try std.testing.expectEqual(@as(usize, score_tiles), decodeLoop(48, 1 << 20)); +} + +test "GLM index: decode windows on aligned key caches take the scores kernel" { + const k: Kernels = undefined; + try std.testing.expect(k.takesDecode(8, 4096, 64, 0x1000, 32768)); // 16K: the contract's 8 rows over 4,096 pools + try std.testing.expect(!k.takesDecode(8, 4096, 63, 0x1000, 32768)); // under 64: tf_glm_scores, no slower on GB10 + try std.testing.expect(!k.takesDecode(rows_from - 1, 4096, 63, 0x1000, 32768)); + try std.testing.expect(k.takesDecode(rows_from - 1, 216080, 3376, 0x1000, 32768)); + try std.testing.expect(k.takesDecode(4, 216080, 2048, 0x1000, 32768)); // 4 rows from ~512K + try std.testing.expect(!k.takesDecode(4, 65536, 800, 0x1000, 32768)); + try std.testing.expect(!k.takesDecode(1, 216080, 3376, 0x1000, 32768)); // one row: tf_glm_scores + try std.testing.expect(!k.takesDecode(rows_from, 4096, 64, 0x1000, 32768)); // prompt-sized: Kernels.takes + try std.testing.expect(!k.takesDecode(16, 4096, 64, 0x1008, 32768)); + try std.testing.expect(!k.takesDecode(16, topk - 1, 64, 0x1000, 32768)); +} + test "GLM index: only prompt-sized launches on aligned key caches take the kernels" { const k: Kernels = undefined; try std.testing.expect(k.takes(rows_from, 1024, 0x1000, 32768)); diff --git a/zig/src/families/glm/cuda_native.zig b/zig/src/families/glm/cuda_native.zig index e933c6b4c81..783bddcac79 100644 --- a/zig/src/families/glm/cuda_native.zig +++ b/zig/src/families/glm/cuda_native.zig @@ -523,11 +523,9 @@ 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.NotModelOpt, error.UnsupportedQuant => "GLM-5.3-Flash on CUDA reads ModelOpt NVFP4 and MIXED_PRECISION checkpoints (the log names what config.json has)", + 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.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)", else => null, }; @@ -541,7 +539,7 @@ test "a place inside its world of at most 16 ranks serves; a larger world is ref } test "a checkpoint refused for its format, at the entry or by the loader, is explained" { - for ([_]anyerror{ error.NotModelOpt, error.UnsupportedQuant, error.UnreadableFormat }) |e| try std.testing.expect(explain(null, e) != null); + for ([_]anyerror{ error.NotModelOpt, error.UnsupportedQuant, error.UnreadableFormat, error.UnreadableExl3 }) |e| try std.testing.expect(explain(null, e) != null); } test "TF_KV_SHARE past the slots a startup plan holds is refused, and the refusal is explained" { diff --git a/zig/src/families/glm/cuda_ranks.zig b/zig/src/families/glm/cuda_ranks.zig index 4f8810f72ba..9de1ebb3726 100644 --- a/zig/src/families/glm/cuda_ranks.zig +++ b/zig/src/families/glm/cuda_ranks.zig @@ -30,6 +30,12 @@ pub const Settings = struct { kv_host_gib: f64 = 0, // TF_GLM_KV_HOST_GIB: the host pages' GiB (0: one full window) l2pf: l2pf.Options = .{}, // TF_GLM_L2PF and its knobs: a decode window's next weights read into L2 beside it kv_live_half: bool = false, // TF_GLM_KV_LIVE_HALF=1: a keep carries the live KDA half alone (cuda_snapshot_layout.zig) + draft_split: bool = false, // TF_GLM_DRAFT_SPLIT=1: three ranks or more split the drafter MLP without TF_ROCE=1 + + /// Whether three ranks or more split the DFlash2 drafter's MLP (dflash.mlpSplit's `wide`); two ranks always do. + pub fn draftWide(s: Settings) bool { + return s.roce_wide or s.draft_split; + } /// The settings `get` gives, blank text as unset; `problem` names a value that is not one of the choices. pub fn read(comptime get: *const fn ([:0]const u8) ?[]const u8, problem: *[]const u8) !Settings { @@ -167,6 +173,12 @@ pub const Settings = struct { return error.BadSetting; } } + if (get("TF_GLM_DRAFT_SPLIT")) |v| { + if (std.mem.eql(u8, v, "1")) s.draft_split = true else if (!std.mem.eql(u8, v, "0")) { + problem.* = "TF_GLM_DRAFT_SPLIT: 0 or 1"; + return error.BadSetting; + } + } if (get("TF_GLM_KV_LIVE_HALF")) |v| { if (std.mem.eql(u8, v, "1")) s.kv_live_half = true else if (!std.mem.eql(u8, v, "0")) { problem.* = "TF_GLM_KV_LIVE_HALF: 0 or 1"; @@ -207,7 +219,7 @@ fn wireOpens(get: *const fn ([:0]const u8) ?[]const u8) bool { /// What every rank must agree on, as bytes the communicator carries. pub const Fingerprint = extern struct { - layout: u32 = 21, // this struct's version (20, main's kv_live_half, plus roce_wide) + layout: u32 = 22, // this struct's version (21, roce_wide's, plus draft_split) world: u32, rank: u32, kv8: u32 = 0, @@ -229,6 +241,7 @@ pub const Fingerprint = extern struct { max_frames: u32 = 0, roce_multi: u32 = 0, // TF_GLM_ROCE_MULTI: every rank opens the borrowed wire or none does (a lone rank would wait on it) roce_wide: u32 = 0, // TF_ROCE=1: three ranks or more split the drafter MLP and gather by RoCE, or none does + draft_split: u32 = 0, // TF_GLM_DRAFT_SPLIT=1: three ranks or more split the drafter MLP, or none does kv_host: u32 = 0, // TF_GLM_KV_HOST(_SHARED): every rank sizes the pool alike and maps the shared file, or none does solo: u32 = 0, // TF_GLM_CHUNK_SOLO: rank 0's solo passes need the wider prompt buffers on every rank l2pf: [4]u32 = @splat(0), // TF_GLM_L2PF's words: every rank prefetches alike, so none waits on a slower one's windows @@ -264,6 +277,7 @@ pub const Fingerprint = extern struct { max_frames, roce_multi, roce_wide, + draft_split, kv_host, solo, l2pf, @@ -304,6 +318,7 @@ pub const Fingerprint = extern struct { .mtp = @intFromBool(mtp), .roce_multi = @intFromBool(s.roce_multi), .roce_wide = @intFromBool(s.roce_wide and world >= 3), // two ranks ask by default, so a lone TF_ROCE=1 there is no difference + .draft_split = @intFromBool(s.draft_split and world >= 3), // two ranks split whatever it says .kv_host = s.kv_host, .kv_host_gib = s.kv_host_gib, .solo = @intFromBool(s.solo), @@ -348,6 +363,7 @@ pub fn mismatch(all: []const Fingerprint) ?Mismatch { "max_frames", "roce_multi", "roce_wide", + "draft_split", "kv_host", "solo", "l2pf", @@ -472,6 +488,7 @@ fn explain(f: Fingerprint.Field) []const u8 { .max_frames => "the frame limit", .roce_multi => "TF_GLM_ROCE_MULTI", .roce_wide => "TF_ROCE=1 at three ranks or more (the RoCE gather and the drafter split)", + .draft_split => "TF_GLM_DRAFT_SPLIT=1 at three ranks or more (the drafter split)", .kv_host => "TF_GLM_KV_HOST or TF_GLM_KV_HOST_SHARED", .kv_host_gib => "TF_GLM_KV_HOST_GIB", .solo => "TF_GLM_CHUNK_SOLO", diff --git a/zig/src/families/glm/cuda_ranks_roce_test.zig b/zig/src/families/glm/cuda_ranks_roce_test.zig index 4d4cb6226ea..74abc68eb74 100644 --- a/zig/src/families/glm/cuda_ranks_roce_test.zig +++ b/zig/src/families/glm/cuda_ranks_roce_test.zig @@ -1,4 +1,4 @@ -//! TF_ROCE: the RoCE gather and the drafter split at three ranks or more, and how ranks agree on it. +//! TF_ROCE and TF_GLM_DRAFT_SPLIT: the RoCE gather and the drafter split at three ranks or more, and how ranks agree. const std = @import("std"); const cuda = @import("cuda"); const ranks = @import("cuda_ranks.zig"); @@ -80,3 +80,50 @@ test "RoCE all-gather on this fabric: a mesh of four reaches every rank; a ring Fabric.world = 2; for (0..2) |r| try std.testing.expectEqual(@as(?usize, null), cuda.roce.firstUnreachable(r, 2, {}, &Reach.reaches)); } + +test "TF_GLM_DRAFT_SPLIT: off by default, 1 or 0, refused otherwise" { + const Env = struct { + var value: ?[]const u8 = null; + fn get(name: [:0]const u8) ?[]const u8 { + return if (std.mem.eql(u8, name, "TF_GLM_DRAFT_SPLIT")) value else null; + } + }; + var problem: []const u8 = ""; + for ([_]?[]const u8{ null, "0" }) |v| { + Env.value = v; + try std.testing.expect(!(try Settings.read(&Env.get, &problem)).draft_split); + } + Env.value = "1"; + const on = try Settings.read(&Env.get, &problem); + try std.testing.expect(on.draft_split and !on.roce_wide); + Env.value = "yes"; + try std.testing.expectError(error.BadSetting, Settings.read(&Env.get, &problem)); + try std.testing.expectEqualStrings("TF_GLM_DRAFT_SPLIT: 0 or 1", problem); +} + +test "three ranks or more split the drafter MLP with TF_ROCE=1 or TF_GLM_DRAFT_SPLIT=1, where shares are 256-aligned" { + const df = @import("dflash.zig"); + for ([_]usize{ 1, 2, 3, 4, 5, 6, 8 }) |world| { + const fits = world >= 2 and df.FF % world == 0 and (df.FF / world) % 256 == 0; + try std.testing.expectEqual(world == 2, df.mlpSplit(world, (Settings{}).draftWide()).split); + for ([_]Settings{ .{ .draft_split = true }, .{ .roce_wide = true } }) |s| { + const m = df.mlpSplit(world, s.draftWide()); + try std.testing.expectEqual(fits, m.split); + try std.testing.expectEqual(if (fits) df.FF / world else df.FF, m.ff); + } + } +} + +test "TF_GLM_DRAFT_SPLIT=1 is in the ranks' agreement at three ranks or more, and two ranks agree whatever it says" { + var all = [_]Fingerprint{ + Fingerprint.of(3, 0, .{ .draft_split = true }, 8192, true, @splat(0), @splat(0), hashBytes("/same")), + Fingerprint.of(3, 1, .{}, 8192, true, @splat(0), @splat(0), hashBytes("/same")), + Fingerprint.of(3, 2, .{ .draft_split = true }, 8192, true, @splat(0), @splat(0), hashBytes("/same")), + }; + try std.testing.expectEqual(Mismatch{ .field = .draft_split, .rank = 1 }, mismatch(&all).?); + var two = [_]Fingerprint{ + Fingerprint.of(2, 0, .{ .draft_split = true }, 8192, true, @splat(0), @splat(0), hashBytes("/same")), + Fingerprint.of(2, 1, .{}, 8192, true, @splat(0), @splat(0), hashBytes("/same")), + }; + try std.testing.expectEqual(@as(?Mismatch, null), mismatch(&two)); +} diff --git a/zig/src/families/glm/cuda_ranks_test.zig b/zig/src/families/glm/cuda_ranks_test.zig index 5ef4b827561..0930fe83c64 100644 --- a/zig/src/families/glm/cuda_ranks_test.zig +++ b/zig/src/families/glm/cuda_ranks_test.zig @@ -190,7 +190,7 @@ test "every media limit is part of the ranks' agreement" { test "every scheduling and identity field that differs stops the ranks" { const zero = Fingerprint.of(2, 0, .{}, 8192, true, @splat(0), @splat(0), hashBytes("/same")); const one = Fingerprint.of(2, 1, .{}, 8192, true, @splat(0), @splat(0), hashBytes("/same")); - inline for (.{ "layout", "world", "rank", "pages", "split", "kda_wide", "kda_pad", "kv_live_half", "pieces", "solo", "pair", "layers", "mtp", "vision", "video_tokens", "max_images", "max_videos", "max_frames", "roce_multi", "roce_wide", "kv_host", "capacity", "heat_high", "heat_low", "kv_host_gib" }) |name| { + inline for (.{ "layout", "world", "rank", "pages", "split", "kda_wide", "kda_pad", "kv_live_half", "pieces", "solo", "pair", "layers", "mtp", "vision", "video_tokens", "max_images", "max_videos", "max_frames", "roce_multi", "roce_wide", "draft_split", "kv_host", "capacity", "heat_high", "heat_low", "kv_host_gib" }) |name| { var all = [_]Fingerprint{ zero, one }; @field(all[1], name) += 1; try std.testing.expectEqual(@field(Fingerprint.Field, name), mismatch(&all).?.field); diff --git a/zig/src/families/glm/cuda_sparse.zig b/zig/src/families/glm/cuda_sparse.zig index ec2555e4866..12764f5be62 100644 --- a/zig/src/families/glm/cuda_sparse.zig +++ b/zig/src/families/glm/cuda_sparse.zig @@ -5,6 +5,7 @@ const cuda = @import("cuda"); const cuda_pdl = @import("cuda_pdl.zig"); const glue = @import("cuda_glue.zig"); const latent = @import("cuda_latent.zig"); +const index_mod = @import("cuda_index.zig"); /// sparse.POOL, TOPK_POOLS, SELECT_LIST, SCORE_LOOP_FROM, SCORE_LOOP; geometry.MLA_SELECT_ROWS. pub const pool = 4; @@ -153,8 +154,10 @@ pub fn selectTokensProfile(set: glue.Set, ops: cuda.Module, stream: cuda.Stream, inline for (.{ qi + a * heads * d * 2, wts + a * w_stride * 2, @as(i64, @intCast(w_stride)), pk, s.scores, at, @as(i64, @intCast(np_max)), @as(i64, @intCast(nb)), scale, headScale(heads), @as(i64, @intCast(heads)), @as(c_int, @intCast(loop)), t.pt, @as(i64, @intCast(t.ps)) }) |v| sa.add(v); if (d != 128 or heads > 32) return error.IndexShape; const quick = if (set.index) |k| if (k.takes(rows, np_max, pk, t.ps)) k else null else null; + // a decode window's rows: the same scores from glm_index_scores (8 rows a CTA, key tiles staged once) + const dec = if (set.dscore) |k| if (k.takesDecode(rows, np_max, nb, pk, t.ps)) k else null else null; var stamp = prof.span(profile, stream, .index_score); - if (quick) |k| try k.scores(stream, qi + a * heads * d * 2, wts + a * w_stride * 2, w_stride, pk, s.scores, at, n, np_max, nb, scale, headScale(heads), heads, t.pt, t.ps) else try cuda_pdl.launch(set.glue.scores, .{ .grid = .{ .x = @intCast(n), .y = @intCast(cdiv(nb, loop)) }, .block = .{ .x = 128 } }, stream, &sa); + if (quick) |k| try k.scores(stream, qi + a * heads * d * 2, wts + a * w_stride * 2, w_stride, pk, s.scores, at, n, np_max, nb, scale, headScale(heads), heads, t.pt, t.ps) else if (dec) |k| try k.scoresTiles(stream, qi + a * heads * d * 2, wts + a * w_stride * 2, w_stride, pk, s.scores, at, n, np_max, nb, scale, headScale(heads), heads, t.pt, t.ps, index_mod.decodeLoop(n, nb)) else try cuda_pdl.launch(set.glue.scores, .{ .grid = .{ .x = @intCast(n), .y = @intCast(cdiv(nb, loop)) }, .block = .{ .x = 128 } }, stream, &sa); stamp.end(); stamp = prof.span(profile, stream, .index_select); if (quick) |k| if (k.select) { diff --git a/zig/src/families/glm/cuda_state.zig b/zig/src/families/glm/cuda_state.zig index 5a5c8919a69..633ea2e06a9 100644 --- a/zig/src/families/glm/cuda_state.zig +++ b/zig/src/families/glm/cuda_state.zig @@ -247,7 +247,10 @@ pub const Buffers = struct { var mm: usize = 4; // windows under rows_from rows keep their K slices apart (a prompt's tail chunk on the prefill buffers too) for (b16Shapes(w)) |sh_| mm = @max(mm, b16.partBytes(@min(rows, b16.rows_from - 1), sh_[0], sh_[1])); - const x3: [4]usize = if (c.exl3) exl3.scratchBytes(rows, D, ew, prefill, w.exl3_shx) else @splat(4); + // EXL3 experts: each layer's path (the prompt kernels', or the grouped one) sizes it + var x3: [4]usize = @splat(4); + for (w.layers) |l| if (l.ffn == .moe) if (l.ffn.moe.exl3) |x| exl3.mostScratch(&x3, rows, D, ew, prefill, x); + if (w.mtp) |m| if (m.layer.ffn == .moe) if (m.layer.ffn.moe.exl3) |x| exl3.mostScratch(&x3, rows, D, ew, prefill, x); var split = false; // a KDA stack in two parts moves each part's rows through one more buffer for (w.layers) |l| split = split or (l.mixer == .kda and l.mixer.kda.proj == .split); const hist_len = if (pairs > cuda.grouped.small) (pairs + cuda.grouped.small - 1) / cuda.grouped.small * (count + 1) else 1; diff --git a/zig/src/families/glm/cuda_weights.zig b/zig/src/families/glm/cuda_weights.zig index 696a4238146..438c71d93ad 100644 --- a/zig/src/families/glm/cuda_weights.zig +++ b/zig/src/families/glm/cuda_weights.zig @@ -43,7 +43,6 @@ pub const Weights = struct { norm: glue.Norm = .{ .bf16 = 0 }, head: projection.Proj = .{ .bf16 = 0 }, // [share.vocab][dims]: bf16, or MXFP8 for the lane mtp: ?Mtp = null, - exl3_shx: bool = true, // EXL3: every layer's gate and up share one input rotation (a prompt rotates each row once) buffers: std.ArrayList(cuda.DeviceBuffer) = .empty, named: std.ArrayList(Named) = .empty, @@ -441,7 +440,6 @@ const Loader = struct { var x3: ?exl3.Experts = null; if (c.exl3) { // the MTP layer's experts too x3 = try exl3.load(L, i, count, d, c.moe_inter, cut); - if (!x3.?.shx) L.w.exl3_shx = false; } else routed = try L.nvfp4Experts(i); const sh = L.w.share.shared; const sw: []const formats.Format = if (i == c.layers) &.{ .bf16, .fp8_pb, .mxfp8 } else &.{ .bf16, .fp8_pb }; // MTP's MXFP8 diff --git a/zig/src/families/glm/dflash.zig b/zig/src/families/glm/dflash.zig index aa039ffc299..9a66e875e70 100644 --- a/zig/src/families/glm/dflash.zig +++ b/zig/src/families/glm/dflash.zig @@ -44,7 +44,7 @@ pub fn confidence() !f64 { return @import("sys").environment.read(f64, "TF_GLM_DRAFT_CONFIDENCE", 0.7); } -/// The drafter MLP split: two ranks as before; three or more only with `wide` (TF_ROCE=1) and 256-aligned shares of FF. +/// The drafter MLP split: two ranks as before; three or more with `wide` (Settings.draftWide) and 256-aligned shares. pub const MlpSplit = struct { split: bool, ff: usize }; pub fn mlpSplit(world: usize, wide: bool) MlpSplit { if (world < 2 or (world > 2 and !wide) or FF % world != 0 or (FF / world) % 256 != 0) return .{ .split = false, .ff = FF }; diff --git a/zig/src/families/glm/dflash_load.zig b/zig/src/families/glm/dflash_load.zig index a2096579776..404bea9b6cb 100644 --- a/zig/src/families/glm/dflash_load.zig +++ b/zig/src/families/glm/dflash_load.zig @@ -145,7 +145,7 @@ pub fn load(gpa: std.mem.Allocator, io: std.Io, e: anytype, dir: []const u8, ran var ents = std.StringHashMap(Ent).init(gpa); defer ents.deinit(); try addEntries(names.allocator(), text, size - 8 - hlen, &ents); - const mlp = df.mlpSplit(world, e.settings.roce_wide); // the MLP split across the ranks, or whole + const mlp = df.mlpSplit(world, e.settings.draftWide()); // the MLP split across the ranks, or whole const split = mlp.split; const ff = mlp.ff; const small: u64 = 6 * 4096 * 2 + 2 * 128 * 2 + 2 * 2 * 2 * D * 2 + 16 * 256; @@ -156,7 +156,7 @@ pub fn load(gpa: std.mem.Allocator, io: std.Io, e: anytype, dir: []const u8, ran errdefer wbuf.free(); var tmp = try cuda.DeviceBuffer.alloc(d, 2 * FF * D * 2); // the largest linear as stored defer tmp.free(); - var raw = try cuda.DeviceBuffer.alloc(d, df.rawBytes(bits, world, e.settings.roce_wide)); + var raw = try cuda.DeviceBuffer.alloc(d, df.rawBytes(bits, world, e.settings.draftWide())); defer raw.free(); var module = try cuda.Module.load(d, cuda.kernels.glm_dflash); errdefer module.unload(); diff --git a/zig/src/families/glm/engine.zig b/zig/src/families/glm/engine.zig index fc60204cf0d..31b2e21c0f8 100644 --- a/zig/src/families/glm/engine.zig +++ b/zig/src/families/glm/engine.zig @@ -101,6 +101,7 @@ pub const Engine = struct { fused_route: bool = true, // GLM_ROUTE=0: the Python family's cast, router and top-k launches draft_vocab: u32 = 154880, // GLM_DRAFT_VOCAB: the MTP head drafts from the vocabulary's first this many tokens committed: u64 = 0, // when the last command buffer was committed (mach ticks) + dflash: ?*@import("metal_dflash_load.zig").Drafter = null, // --drafter: DFlash2 drafts in place of the MTP head /// Checkpoint `dir`, caches for `cap` tokens; GLM_LAYERS=N: the first N layers; GLM_EP=settings: half the experts. pub fn load(gpa: std.mem.Allocator, io: std.Io, dir: []const u8, cap: u32) !*Engine { @@ -124,6 +125,7 @@ pub const Engine = struct { e.fused_route = if (platform.c.getenv("GLM_ROUTE")) |v| v[0] != '0' else true; e.draft_vocab = if (platform.c.getenv("GLM_DRAFT_VOCAB")) |v| std.fmt.parseInt(u32, std.mem.span(v), 10) catch 0 else 0; e.committed = 0; + e.dflash = null; e.ep = null; e.pr = null; e.trace_last = null; @@ -273,6 +275,7 @@ pub const Engine = struct { pub fn deinit(e: *Engine) void { const gpa = e.gpa; residency.drop(e); + if (e.dflash) |d| d.deinit(); // before the device, kernels and weights it borrows if (e.ep) |ep| ep.deinit(gpa); if (e.vision) |v| v.deinit(); e.ep_arena.deinit(); @@ -310,7 +313,7 @@ pub const Engine = struct { } pub fn ctx(e: *Engine) fwd.Ctx { - return .{ .k = e.k, .c = &e.c, .w = e.w, .s = &e.s, .sc = &e.sc, .ep = e.ep, .fused_route = e.fused_route, .draft_vocab = e.draft_vocab }; + return .{ .k = e.k, .c = &e.c, .w = e.w, .s = &e.s, .sc = &e.sc, .ep = e.ep, .fused_route = e.fused_route, .taps = if (e.dflash) |d| d.taps else null, .draft_vocab = e.draft_vocab }; } /// A command buffer ordered after the last one this engine committed. diff --git a/zig/src/families/glm/forward.zig b/zig/src/families/glm/forward.zig index 834ae3c3696..105430e1dbf 100644 --- a/zig/src/families/glm/forward.zig +++ b/zig/src/families/glm/forward.zig @@ -11,6 +11,7 @@ const hc_shape = @import("kernels.zig").hc_shape; const hc_core = @import("../../core/hc.zig"); const wide = @import("wide.zig"); const Ref = wts.Ref; +const Taps = @import("metal_dflash_taps.zig").Taps; /// The MoE block (moe.zig). pub const moe = @import("moe.zig").moe; const moeBlock = @import("moe.zig").block; @@ -29,6 +30,7 @@ pub const Ctx = struct { skip: u32 = 0, // a profile's knock-outs: launch classes left out (Class bits) pskip: u32 = 0, // a profile's knock-outs by launch (Part bits) fused_route: bool = true, // the core route (two launches); false: the Python family's cast, router and top-k + taps: ?*const Taps = null, // the DFlash2 drafter's tap capture (null: no drafter) draft_vocab: u32 = 154880, // the MTP head's tokens: the vocabulary's first this many m_row: u32 = 0, // the MTP head's logits row in m_logits (a rank log keeps each depth's in its own row) segs: []const Seg = &.{}, // a shared window's streams in row order (empty: every row is `s`'s) @@ -40,7 +42,6 @@ pub const Ctx = struct { pub const Inject = struct { rows: Ref, spans: []const Span }; // tower rows: [at,at+n) -> [row,row+n) pub const Span = struct { at: u32, n: u32, row: u32 }; - /// The image rows among `rows` embedding rows (positions pos..) written over `out`; nothing without an injection. pub fn inject(x: *const Ctx, e: mtl.ComputeEncoder, out: Ref, rows: u32, pos: u32) void { const inj = x.inject orelse return; @@ -65,7 +66,6 @@ pub const rulesFor = @import("draw_rule.zig").rulesFor; pub const parseSampling = @import("draw_rule.zig").parseSampling; pub const envSampling = @import("draw_rule.zig").envSampling; pub const SamplingError = @import("draw_rule.zig").SamplingError; - /// One stream's rows in a shared window: its caches, its first row, its rows and the position of the first. pub const Seg = struct { s: *st.State, row0: u32, rows: u32, pos: u32 }; @@ -135,7 +135,6 @@ const MlaNorms = extern struct { x_stride: u32, kv_at: u32, ik_at: u32, iw_at: u const index_weight_scale: f32 = 1.0 / 64.0; const ScoreArgs = extern struct { p0: u32, q_stride: u32, w_stride: u32, s_stride: u32, rows: u32 }; const SelectArgs = extern struct { p0: u32, top: u32, width: u32, s_stride: u32, i_stride: u32 }; - pub fn bind(e: mtl.ComputeEncoder, first: usize, refs: anytype) void { inline for (refs, 0..) |r, i| e.setBuffer(r.buf, r.off, first + i); } @@ -512,6 +511,7 @@ pub fn backbone(x: *Ctx, e: mtl.ComputeEncoder, ids: Ref, rows: u32, pos: u32) v const L = &x.w.layers[li]; const hcs = L.hc.?; if (k & Class.hc == 0) boundary(x, e, rows, pending, hcs[0], L.in_norm); + if (x.taps) |t| if (li > 0) t.after(x, e, li - 1, rows, pos); snap(x, e, sc.normed, plane); switch (L.attn) { .kda => |*a| { diff --git a/zig/src/families/glm/glm.zig b/zig/src/families/glm/glm.zig index 86628016f2e..e96251d261a 100644 --- a/zig/src/families/glm/glm.zig +++ b/zig/src/families/glm/glm.zig @@ -22,6 +22,25 @@ pub const mm_groups = @import("mm_groups.zig"); pub const vision = @import("vision.zig"); pub const image = @import("image.zig"); pub const video = @import("video.zig"); +pub const metal_dflash_config = @import("metal_dflash_config.zig"); +pub const metal_dflash_weights = @import("metal_dflash_weights.zig"); +pub const metal_dflash_backend = @import("metal_dflash_backend.zig"); +pub const metal_dflash_model = @import("metal_dflash_model.zig"); +pub const metal_dflash_taps = @import("metal_dflash_taps.zig"); +pub const metal_dflash_rounds = @import("metal_dflash_rounds.zig"); +pub const metal_dflash_load = @import("metal_dflash_load.zig"); +pub const metal_dflash_prepared = @import("metal_dflash_prepared.zig"); +pub const metal_dflash_attention = @import("metal_dflash_attention.zig"); +pub const metal_dflash_context = @import("metal_dflash_context.zig"); +pub const metal_dflash_topk = @import("metal_dflash_topk.zig"); +pub const metal_dflash_source = @import("metal_dflash_source.zig"); +pub const metal_dflash_passes = @import("metal_dflash_passes.zig"); +pub const metal_dflash_accept = @import("metal_dflash_accept.zig"); +pub const metal_dflash_ahead = @import("metal_dflash_ahead.zig"); +pub const metal_dflash_follow = @import("metal_dflash_follow.zig"); +pub const metal_dflash_same = @import("metal_dflash_same.zig"); +pub const metal_dflash_inline = @import("metal_dflash_inline.zig"); +pub const metal_dflash_head_depth = @import("metal_dflash_head_depth.zig"); test { _ = backend; @@ -54,4 +73,23 @@ test { _ = vision; _ = image; _ = video; + _ = metal_dflash_config; + _ = metal_dflash_weights; + _ = metal_dflash_backend; + _ = metal_dflash_model; + _ = metal_dflash_taps; + _ = metal_dflash_rounds; + _ = metal_dflash_load; + _ = metal_dflash_prepared; + _ = metal_dflash_attention; + _ = metal_dflash_topk; + _ = metal_dflash_source; + _ = metal_dflash_passes; + _ = metal_dflash_accept; + _ = metal_dflash_context; + _ = metal_dflash_ahead; + _ = metal_dflash_follow; + _ = metal_dflash_same; + _ = metal_dflash_inline; + _ = metal_dflash_head_depth; } diff --git a/zig/src/families/glm/metal_dflash_accept.zig b/zig/src/families/glm/metal_dflash_accept.zig new file mode 100644 index 00000000000..b147b5fc98d --- /dev/null +++ b/zig/src/families/glm/metal_dflash_accept.zig @@ -0,0 +1,58 @@ +//! GLM's DFlash2 chains accepted on the GPU (glm_draft_accept.metal), as the lane core accepts them on the host. +const std = @import("std"); +const mtl = @import("metal"); +const sources = @import("kernel_sources"); + +pub const Ref = struct { buf: mtl.Buffer, off: usize = 0 }; + +/// Threads a threadgroup: one a stream. +pub const threads = 32; + +/// Rows `tokens` (pending, then drafts) against `picks`: drafts kept and the next pending token, as the host accepts. +pub fn accept(tokens: []const u32, picks: []const u32) [2]u32 { + var kept: usize = 0; + while (kept + 1 < tokens.len and tokens[kept + 1] == picks[kept]) kept += 1; + return .{ @intCast(kept), picks[kept] }; +} + +pub const Accept = struct { + pipe: mtl.Pipeline, + + /// `edit` replaces one text of the source (a contract control's planted fault), else null. + pub fn init(a: std.mem.Allocator, device: mtl.Device, edit: ?[2][]const u8) !Accept { + const text = if (edit) |x| blk: { + if (std.mem.indexOf(u8, sources.glm_draft_accept, x[0]) == null) return error.ControlEditMissing; + break :blk try std.mem.replaceOwned(u8, a, sources.glm_draft_accept, x[0], x[1]); + } else try a.dupe(u8, sources.glm_draft_accept); + defer a.free(text); + const lib = try mtl.Library.fromSource(device, text, mtl.CompileOptions.mlx()); + defer lib.deinit(); + return .{ .pipe = try mtl.Pipeline.init(device, lib, "glm_draft_accept", false) }; + } + + pub fn deinit(x: Accept) void { + x.pipe.deinit(); + } + + /// `streams` windows' acceptance into `out` (two u32 a stream): their rows at `offsets` in `tokens` and `picks`. + pub fn encode(x: Accept, e: mtl.ComputeEncoder, tokens: Ref, picks: Ref, offsets: Ref, rows: Ref, out: Ref, streams: u32) !void { + if (streams == 0) return error.BadAcceptShape; + for ([_]Ref{ tokens, picks, offsets, rows, out }) |r| if (r.off % 4 != 0) return error.BadAcceptBuffer; + if (out.off + @as(usize, streams) * 8 > out.buf.length() or offsets.off + @as(usize, streams) * 4 > offsets.buf.length() or rows.off + @as(usize, streams) * 4 > rows.buf.length()) return error.BadAcceptBuffer; + e.setPipeline(x.pipe); + e.setBuffer(tokens.buf, tokens.off, 0); + e.setBuffer(picks.buf, picks.off, 1); + e.setBuffer(offsets.buf, offsets.off, 2); + e.setBuffer(rows.buf, rows.off, 3); + e.setBuffer(out.buf, out.off, 4); + e.setValue(streams, 5); + e.dispatchThreads(mtl.Size.of(streams, 1, 1), mtl.Size.of(threads, 1, 1)); + } +}; + +test "host acceptance: drafts kept to the first differing pick, the next pending token the pick after them" { + try std.testing.expectEqual([2]u32{ 0, 9 }, accept(&.{ 5, 7, 8 }, &.{ 9, 1, 2 })); // the first draft missed + try std.testing.expectEqual([2]u32{ 2, 4 }, accept(&.{ 5, 7, 8 }, &.{ 7, 8, 4 })); // every draft kept + try std.testing.expectEqual([2]u32{ 1, 3 }, accept(&.{ 5, 7, 8 }, &.{ 7, 3, 8 })); + try std.testing.expectEqual([2]u32{ 0, 6 }, accept(&.{5}, &.{6})); // no drafts: the pick is the next token +} diff --git a/zig/src/families/glm/metal_dflash_ahead.zig b/zig/src/families/glm/metal_dflash_ahead.zig new file mode 100644 index 00000000000..66460628480 --- /dev/null +++ b/zig/src/families/glm/metal_dflash_ahead.zig @@ -0,0 +1,112 @@ +//! A window's rows absorbed into a stream's drafter context before its acceptance is known, then settled at it. +const std = @import("std"); +const op = @import("../qwen27/dflash/operators.zig"); +const cfg = @import("../qwen27/dflash/config.zig"); +const model_mod = @import("metal_dflash_model.zig"); +const Model = model_mod.Model; +const Context = model_mod.Context; + +/// A stream's window rows: taps at positions [first, first + rows) of its own ring, its caches the pass's batch. +pub const Ahead = struct { context: *Context, first: u64, rows: u32 }; + +/// The most rows a stream's window absorbs ahead: what its K/V ring holds past a full context. +pub const max_rows = 16; + +/// Whether `x` takes its window's rows ahead: it has absorbed every row before the window and holds none past it. +pub fn ready(c: cfg.Config, x: *const Context, first: u64, rows: u32) bool { + return x.session.ready and x.session.context.end == first and rows > 0 and rows <= max_rows and rows <= c.window; +} + +/// The context's end after its window kept `kept` drafts: the window's first row and the kept ones are its rows. +pub fn settle(c: cfg.Config, x: *Context, first: u64, kept: u32) void { + const end = first + kept + 1; + const next: op.Context = .{ .cache = x.session.context.cache, .begin = @max(x.session.context.begin, end -| (@as(u64, c.window) - 1)), .end = end }; + x.session.context = next; + x.context = next; + x.committed_end = end; +} + +/// Each stream's window rows into its caches at their positions; rows it rejects lie past its end until overwritten. +pub fn absorb(m: *Model, frame: u64, aheads: []const Ahead) !void { + const c = m.graph.config; + const g = &m.graph; + const ops = m.backend.ops(); + const b = &m.backend; + if (aheads.len == 0 or aheads.len > 8 or b.batch.len != aheads.len) return error.BadDraftContext; + var total: u32 = 0; + for (aheads, b.batch) |x, caches| { + if (!ready(c, x.context, x.first, x.rows) or caches.ptr != x.context.caches.ptr) return error.BadDraftContext; + total += x.rows; + } + var positions: [8 * max_rows]u64 = undefined; + const taps = try b.frame.alloc(total, c.tapWidth(), .bf16); + const to = try b.frame.ref(taps); + const e = try b.encoder(frame); + const stride = @as(usize, c.tapWidth()) * 2; + var at: u32 = 0; + for (aheads) |x| { + var done: u32 = 0; // the ring wraps at most once inside a window's rows + while (done < x.rows) { + const slot: u32 = @intCast((x.first + done) % c.window); + const n = @min(x.rows - done, c.window - slot); + try b.copy(e, .{ .buf = x.context.pending, .off = @as(usize, slot) * stride }, .{ .buf = to.buf, .off = to.off + @as(usize, at + done) * stride }, n, c.tapWidth()); + done += n; + } + for (positions[at..][0..x.rows], 0..) |*p, i| p.* = x.first + i; + at += x.rows; + } + const pos = positions[0..total]; + const mode = m.preparation.mode; + const fusion = try ops.vtable.project(ops.ptr, frame, taps, g.fusion, mode); + const hidden = try ops.vtable.norm(ops.ptr, frame, fusion, .{ .weight = g.hidden_norm, .eps = c.eps, .heads = 1, .head_dim = c.hidden }); + for (g.layers, 0..) |layer, i| { + const raw = try ops.vtable.project(ops.ptr, frame, hidden, layer.attention.k, mode); + const normed = try ops.vtable.norm(ops.ptr, frame, raw, .{ .weight = layer.attention.k_norm, .eps = c.eps, .heads = c.kv_heads, .head_dim = c.head_dim }); + const keys = try ops.vtable.rope(ops.ptr, frame, normed, .{ .positions = pos, .heads = c.kv_heads, .dim = c.head_dim, .theta = c.theta }); + const values = try ops.vtable.project(ops.ptr, frame, hidden, layer.attention.v, mode); + var first: u32 = 0; + for (aheads, 0..) |x, k| { + const kr = try b.frame.ref(keys); + const vr = try b.frame.ref(values); + const ks = try b.frame.add(.{ .buf = kr.buf, .off = kr.off + @as(usize, first) * keys.stride * 2 }, x.rows, keys.width, keys.stride, .bf16); + const vs = try b.frame.add(.{ .buf = vr.buf, .off = vr.off + @as(usize, first) * values.stride * 2 }, x.rows, values.width, values.stride, .bf16); + try ops.vtable.stream_append(ops.ptr, frame, @intCast(k), @intCast(i), ks, vs, pos[first..][0..x.rows]); + first += x.rows; + } + } +} + +/// The streams' window rows absorbed ahead in a frame of their own, the frame waited for (the checks' entry). +pub fn absorbNow(m: *Model, aheads: []const Ahead) !void { + var caches: [8][]@import("metal_dflash_backend.zig").Cache = undefined; + if (aheads.len > caches.len) return error.BadDraftContext; + for (aheads, caches[0..aheads.len]) |x, *c| c.* = x.context.caches; + m.backend.batch = caches[0..aheads.len]; + defer m.backend.batch = &.{}; + const ops = m.backend.ops(); + const frame = try ops.vtable.begin(ops.ptr); + defer ops.vtable.release(ops.ptr, frame); + try absorb(m, frame, aheads); + m.backend.frame.finish() catch |err| { + m.backend.failed = true; + return err; + }; +} + +test "a settled window keeps its first row and its kept drafts, the context's start sliding with its end" { + var c: cfg.Config = .{}; + c.window = 8; + var x: Context = .{ .pending = undefined, .caches = &.{}, .session = try @import("../qwen27/dflash/session.zig").Session.init(c, 1, 0) }; + x.session.context = .{ .cache = 1, .begin = 0, .end = 4 }; + x.session.ready = true; + try std.testing.expect(ready(c, &x, 4, 5)); + try std.testing.expect(!ready(c, &x, 3, 5)); // a row before the window is absorbed already + try std.testing.expect(!ready(c, &x, 6, 5)); // a row before the window is missing + try std.testing.expect(!ready(c, &x, 4, max_rows + 1)); + settle(c, &x, 4, 2); + try std.testing.expectEqual(op.Context{ .cache = 1, .begin = 0, .end = 7 }, x.session.context); + try std.testing.expectEqual(@as(u64, 7), x.committed_end); + settle(c, &x, 7, 4); + try std.testing.expectEqual(op.Context{ .cache = 1, .begin = 5, .end = 12 }, x.session.context); + try std.testing.expectEqualDeep(x.session.context, x.context); +} diff --git a/zig/src/families/glm/metal_dflash_attention.zig b/zig/src/families/glm/metal_dflash_attention.zig new file mode 100644 index 00000000000..2a7564eb5b6 --- /dev/null +++ b/zig/src/families/glm/metal_dflash_attention.zig @@ -0,0 +1,118 @@ +//! GLM's DFlash2 drafter attention launch (glm_draft_attention.metal): block rows over the K/V ring, a key a lane. +const std = @import("std"); +const mtl = @import("metal"); +const sources = @import("kernel_sources"); + +/// Keys a threadgroup takes, the most streams a pass and rows a block, threads a threadgroup (one simdgroup). +pub const chunk = 128; +pub const max_streams = 8; +pub const max_block = 16; +pub const threads = 32; + +/// glm_draft_args: `streams` blocks of `block` rows; mask rows `mask_stride` apart; `chunks` the longest stream's. +pub const Args = extern struct { rows: u32, block: u32, streams: u32, mask_stride: u32, scale_bits: u32, window: u32, chunks: u32, pad: u32 = 0 }; +/// glm_draft_stream: a stream's keys, [0, context) at its ring's slots (at + key) % window, the rest its own rows. +pub const Stream = extern struct { keys: u32, context: u32, at: u32, pad: u32 = 0 }; + +pub const Ref = struct { buf: mtl.Buffer, off: usize = 0 }; +/// A stream's rolling K/V for the layer. +pub const Ring = struct { k: Ref, v: Ref }; + +/// The query and KV heads and head dim the kernel is compiled for. +pub const Shape = struct { heads: u32, kv_heads: u32, dim: u32 }; + +pub fn chunks(keys: u32) u32 { + return (keys + chunk - 1) / chunk; +} + +/// A pass's arguments for `table`'s streams of `block` rows each, or the refusal of a table the kernel cannot read. +pub fn plan(table: []const Stream, block: u32, window: u32, scale: f32) !Args { + if (table.len == 0 or table.len > max_streams or block == 0 or block > max_block or window == 0) return error.InvalidDraftAttention; + var most: u32 = 0; + for (table) |t| { + if (t.context > window or t.keys != t.context + block or t.at >= window) return error.InvalidDraftAttention; + most = @max(most, t.keys); + } + return .{ .rows = @intCast(table.len * block), .block = block, .streams = @intCast(table.len), .mask_stride = most, .scale_bits = @bitCast(scale), .window = window, .chunks = chunks(most) }; +} + +/// fp32 partials the attend step leaves for the merge: [rows][kv heads][chunks][heads a kv head][dim + 4]. +pub fn partBytes(s: Shape, args: Args) usize { + return @as(usize, args.rows) * s.heads * args.chunks * (s.dim + 4) * 4; +} + +pub fn source(a: std.mem.Allocator, s: Shape) ![]u8 { + if (s.kv_heads == 0 or s.heads % s.kv_heads != 0 or (s.dim != 128 and s.dim != 64) or s.heads / s.kv_heads != 4) return error.InvalidDraftAttentionShape; + return std.fmt.allocPrint(a, "#define TF_QH {d}\n#define TF_KVH {d}\n#define TF_D {d}\n{s}", .{ s.heads, s.kv_heads, s.dim, sources.glm_draft_attention }); +} + +pub const Pipes = struct { + shape: Shape, + attend: mtl.Pipeline, + merge: mtl.Pipeline, + + /// `edit` replaces one text of the source (a contract control's planted fault), else null. + pub fn init(a: std.mem.Allocator, device: mtl.Device, s: Shape, edit: ?[2][]const u8) !Pipes { + const plain = try source(a, s); + defer a.free(plain); + const text = if (edit) |x| blk: { + if (std.mem.indexOf(u8, plain, x[0]) == null) return error.ControlEditMissing; + break :blk try std.mem.replaceOwned(u8, a, plain, x[0], x[1]); + } else try a.dupe(u8, plain); + defer a.free(text); + const lib = try mtl.Library.fromSource(device, text, .{ .language = mtl.CompileOptions.mlx().language, .math_functions = .precise }); + defer lib.deinit(); + const attend = try mtl.Pipeline.init(device, lib, "glm_draft_attend", false); + errdefer attend.deinit(); + const merge = try mtl.Pipeline.init(device, lib, "glm_draft_attend_merge", false); + errdefer merge.deinit(); + if (attend.maxThreads() < threads or attend.simdWidth() != 32) return error.UnsupportedDraftAttention; + return .{ .shape = s, .attend = attend, .merge = merge }; + } + + pub fn deinit(p: Pipes) void { + p.attend.deinit(); + p.merge.deinit(); + } + + /// Each stream's rows of `q` over its ring's context and own `ko`/`vo` rows into `out`, whatever streams share it. + pub fn encode(p: Pipes, e: mtl.ComputeEncoder, args: Args, table: []const Stream, rings: []const Ring, q: Ref, ko: Ref, vo: Ref, mask: Ref, part: Ref, out: Ref) !void { + if (table.len != args.streams or rings.len != table.len or args.rows != args.streams * args.block) return error.InvalidDraftAttention; + var t: [max_streams]Stream = @splat(.{ .keys = 0, .context = 0, .at = 0 }); + @memcpy(t[0..table.len], table); + e.setPipeline(p.attend); + for ([_]Ref{ q, ko, vo, mask }, 0..) |r, i| e.setBuffer(r.buf, r.off, i); + e.setValue(args, 4); + e.setValue(t, 5); + e.setBuffer(part.buf, part.off, 6); + // unused ring slots repeat stream 0's: bound, never read + for (0..max_streams) |s| { + const r = rings[if (s < rings.len) s else 0]; + e.setBuffer(r.k.buf, r.k.off, 8 + s); + e.setBuffer(r.v.buf, r.v.off, 16 + s); + } + e.dispatchGroups(mtl.Size.of(p.shape.kv_heads, args.rows, args.chunks), mtl.Size.of(threads, 1, 1)); + e.barrier(); + e.setPipeline(p.merge); + e.setBuffer(part.buf, part.off, 0); + e.setValue(args, 1); + e.setBuffer(out.buf, out.off, 2); + e.setValue(t, 3); + e.dispatchGroups(mtl.Size.of(p.shape.heads, args.rows, 1), mtl.Size.of(32, 1, 1)); + } +}; + +test "a pass's rows, mask stride and chunks follow its longest stream; a table the kernel cannot read is refused" { + const s = Shape{ .heads = 32, .kv_heads = 8, .dim = 128 }; + const table = [_]Stream{ .{ .keys = 2063, .context = 2047, .at = 5 }, .{ .keys = 316, .context = 300, .at = 0 }, .{ .keys = 16, .context = 0, .at = 0 } }; + const args = try plan(&table, 16, 2048, 0.088); + try std.testing.expectEqual(@as(u32, 48), args.rows); + try std.testing.expectEqual(@as(u32, 2063), args.mask_stride); + try std.testing.expectEqual(@as(u32, 17), args.chunks); + try std.testing.expectEqual(@as(usize, 48 * 32 * 17 * 132 * 4), partBytes(s, args)); + try std.testing.expectError(error.InvalidDraftAttention, plan(&.{.{ .keys = 20, .context = 2, .at = 0 }}, 16, 2048, 1)); + try std.testing.expectError(error.InvalidDraftAttention, plan(&table, 17, 2048, 1)); + try std.testing.expectEqual(@as(u32, 17), chunks(2047 + 16)); + try std.testing.expectEqual(@as(u32, 1), chunks(1)); + try std.testing.expectEqual(@as(u32, 2), chunks(129)); +} diff --git a/zig/src/families/glm/metal_dflash_backend.zig b/zig/src/families/glm/metal_dflash_backend.zig new file mode 100644 index 00000000000..6fa2465881a --- /dev/null +++ b/zig/src/families/glm/metal_dflash_backend.zig @@ -0,0 +1,409 @@ +//! GLM's DFlash2 draft adapter: the shared draft ops encoded over GLM's own kernels, frame and rolling caches. +const std = @import("std"); +const mtl = @import("metal"); +const core = @import("core"); +const op = @import("../qwen27/dflash/operators.zig"); +const draft_cfg = @import("../qwen27/dflash/config.zig"); +const ck = @import("../qwen27/checkpoint.zig"); +const frame_mod = @import("../qwen27/dflash/runtime_frame.zig"); +const context = @import("metal_dflash_context.zig"); +const fwd = @import("forward.zig"); +const cfg = @import("config.zig"); +const wts = @import("weights.zig"); +const kernels = @import("kernels.zig"); +const wide = @import("wide.zig"); +const affine_mm = @import("../../core/affine_mm.zig"); +const dtopk = @import("metal_dflash_topk.zig"); + +pub const Frame = frame_mod.Frame; +pub const Ref = core.draft_ops.Ref; +const caches_impl = @import("../qwen27/dflash/caches.zig"); +pub const Cache = caches_impl.Pair(mtl.Buffer); +pub fn newCaches(a: std.mem.Allocator, device: mtl.Device, c: draft_cfg.Config, layers: usize) ![]Cache { + return caches_impl.newCaches(mtl.Buffer, a, device, c, layers); +} +pub fn freeCaches(a: std.mem.Allocator, caches: []Cache) void { + caches_impl.freeCaches(mtl.Buffer, a, caches); +} + +/// The GLM target the drafter borrows: its device, queue, kernels, weights and shape (one Mac, TP1). +pub const Target = struct { + device: mtl.Device, + queue: mtl.Queue, + k: *kernels.Kernels, + w: *const wts.Weights, + c: cfg.Config, +}; + +/// Ops a draft frame encodes before committing them (`first_part_ops` opens the first commit earlier). +const part_ops = 40; +/// The first part is short, so the GPU starts while the rest is still being encoded. +const first_part_ops = 6; +/// A drafter pass's times: host ticks at its commit, its wait's return and its lattice read; its GPU span (seconds). +pub const Stamps = struct { + begin: u64 = 0, + first: u64 = 0, + commit: u64 = 0, + waited: u64 = 0, + read: u64 = 0, + gpu: [2]f64 = .{ 0, 0 }, + + /// GLM_WINDOWS' draft line: phases in ms after the last window returned (host) or ended (GPU span). + pub fn logPhases(s: Stamps, r: u64, last_end: f64, enter: u64, ahead: u64, passes: u64, done: u64) void { + const ms = struct { + fn of(t: u64, from: u64) f64 { + return if (t == 0 or t < from) -1 else @as(f64, @floatFromInt(t - from)) / 24e3; + } + }.of; + const drafted = s.begin >= enter; + std.log.info("glm draft: enter {d:.2} ahead {d:.2} begin {d:.2} commit {d:.2} gpu {d:.2}-{d:.2} waited {d:.2} read {d:.2} passes {d:.2} done {d:.2} ms start {d:.3} seen {d:.3} ms", .{ + ms(enter, r), ms(ahead, r), + if (drafted) ms(s.begin, r) else -1, if (drafted) ms(s.commit, r) else -1, + if (drafted) (s.gpu[0] - last_end) * 1e3 else -1, if (drafted) (s.gpu[1] - last_end) * 1e3 else -1, + if (drafted) ms(s.waited, r) else -1, if (drafted) ms(s.read, r) else -1, + ms(passes, r), ms(done, r), + if (drafted) (s.gpu[0] - @as(f64, @floatFromInt(s.first)) / 24e6) * 1e3 else -1, if (drafted) (@as(f64, @floatFromInt(s.waited)) / 24e6 - s.gpu[1]) * 1e3 else -1, + }); + } +}; +fn ticks() u64 { + return @import("sys").c.mach_absolute_time(); +} +/// The frame's GPU span: its first command buffer's start to its last one's end. +fn span(f: *const Frame) [2]f64 { + const first = if (f.part_count > 0) f.parts[0] else f.cb; + return .{ first.gpuStart(), f.cb.gpuEnd() }; +} +/// A block planned on the GPU (metal_dflash_follow): its ids, rope positions, mask and attention table. +pub const Device = struct { ids: Ref, positions: Ref, mask: Ref, keys: [8]@import("metal_dflash_attention.zig").Stream, streams: u32, mask_stride: u32 }; +pub const Backend = struct { + allocator: std.mem.Allocator, + target: *Target, + checkpoint: *core.checkpoint_metal.Checkpoint, + config: draft_cfg.Config, + primitives: core.draft_ops.Ops, + attention: core.shared_attention.Attention, + draft_attention: @import("metal_dflash_attention.zig").Pipes, + topk: core.bf16_topk_gpu.Ops, + draft_topk: dtopk.TopK, + frame: Frame, + queue: mtl.Queue, // the queue its passes commit to: the target's + caches: []Cache, + batch: []const []Cache = &.{}, // a batched pass's streams' caches, by stream + batch_block: u32 = 0, // a batched pass's rows a stream: the row kernels' head takes each stream's mask rows + context: op.Context = .{ .cache = 1, .begin = 0, .end = 0 }, + transaction: ?u64 = null, + staged: ?u64 = null, + appended: u32 = 0, + appended_rows: u32 = 0, + failed: bool = false, + copies: ?@import("metal_dflash_prepared.zig").Copies = null, // --drafter-bits 4: the linears' copies + stamps: Stamps = .{}, // the last pass's host and GPU times, for GLM_WINDOWS' draft line + follow: ?Device = null, // while set, the block reads its ids, positions and attention mask from these buffers + pub fn init(a: std.mem.Allocator, target: *Target, checkpoint: *core.checkpoint_metal.Checkpoint, c: draft_cfg.Config) !Backend { + try c.check(); + if (target.c.tp != 1 or target.c.tp_rank != 0) return error.TargetBinding; + // the drafter reads the target's own embedding and head: their widths' kernels load here once + if (!wide.native(target.w.embed) or !wide.native(target.w.head)) try target.k.widen(a, target.device); + const primitives = try core.draft_ops.Ops.init(target.device); + 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 draft_attention = try @import("metal_dflash_attention.zig").Pipes.init(a, target.device, .{ .heads = c.heads, .kv_heads = c.kv_heads, .dim = c.head_dim }, null); + errdefer draft_attention.deinit(); + const topk = try core.bf16_topk_gpu.Ops.init(target.device); + errdefer topk.deinit(); + const draft_topk = try dtopk.TopK.init(a, target.device, null); + errdefer draft_topk.deinit(); + const caches = try newCaches(a, target.device, c, c.layers); + return .{ .allocator = a, .target = target, .checkpoint = checkpoint, .config = c, .primitives = primitives, .attention = attention, .draft_attention = draft_attention, .topk = topk, .draft_topk = draft_topk, .frame = .{ .allocator = a, .device = target.device, .queue = target.queue }, .queue = target.queue, .caches = caches }; + } + pub fn deinit(b: *Backend) void { + if (b.copies) |*c| c.deinit(); + b.frame.deinit(); + freeCaches(b.allocator, b.caches); + b.draft_topk.deinit(); + b.topk.deinit(); + b.draft_attention.deinit(); + b.attention.deinit(); + b.primitives.deinit(); + } + /// The head the pass reads: the target's own output head weights. + pub fn headWeights(b: *const Backend, _: op.View) wts.Affine { + return b.target.w.head; + } + pub fn ops(b: *Backend) op.Ops { + return .{ .ptr = b, .vtable = &vtable }; + } + pub fn source(b: *Backend) ck.Source { + return .{ .ptr = b, .getFn = get }; + } + /// A tensor's host view; a linear left in the file names its copy by its view's address and has no bytes. + fn get(ptr: *anyopaque, name: []const u8) !ck.Tensor { + const b: *Backend = @ptrCast(@alignCast(ptr)); + const d = b.checkpoint.deferred.get(name) orelse return cpu(try b.checkpoint.get(name)); + var shape: @FieldType(ck.Tensor, "shape") = @splat(1); + @memcpy(shape[0..d.rank], d.shape[0..d.rank]); + return .{ .dtype = d.dtype, .rank = @intCast(d.rank), .shape = shape, .bytes = try b.checkpoint.view(name) }; + } + pub fn cpu(t: core.checkpoint_metal.Tensor) ck.Tensor { + var shape: @FieldType(ck.Tensor, "shape") = @splat(1); + @memcpy(shape[0..t.rank], t.shape[0..t.rank]); + return .{ .dtype = t.dtype, .rank = @intCast(t.rank), .shape = shape, .bytes = t.buffer.contents()[t.offset .. t.offset + t.bytes] }; + } + pub fn weight(b: *Backend, t: ck.Tensor) !Ref { + var it = b.checkpoint.tensors.valueIterator(); + while (it.next()) |candidate| if (candidate.buffer.contents() + candidate.offset == t.bytes.ptr and candidate.bytes == t.bytes.len and candidate.dtype == t.dtype) return .{ .buf = candidate.buffer, .off = candidate.offset }; + return error.UnownedDraftWeight; + } + pub fn encoder(b: *Backend, epoch: u64) !mtl.ComputeEncoder { + if (b.failed) return error.DraftBackendFailed; + try b.frame.require(epoch); + b.frame.ops += 1; + if (b.frame.ops == first_part_ops) b.stamps.first = ticks(); // the first part's commit, for GLM_WINDOWS + if (b.frame.ops == first_part_ops or b.frame.ops % part_ops == 0) try b.frame.part(); + return b.frame.encoder; + } + /// Rows of bf16 through `copy_u32` (whole u32s: every width here is even), then a barrier. + pub fn copy(b: *Backend, e: mtl.ComputeEncoder, x: Ref, y: Ref, rows: u32, width: u32) !void { + const words: u32 = @intCast(@as(usize, rows) * width * 2 / 4); + if (@as(usize, rows) * width * 2 % 4 != 0) return error.DraftOperatorShape; + e.setPipeline(b.target.k.copy_u32); + fwd.bind(e, 0, .{ .{ .buf = x.buf, .off = x.off }, .{ .buf = y.buf, .off = y.off } }); + e.setValue(words, 2); + e.dispatchThreads(fwd.size(words, 1, 1), fwd.size(256, 1, 1)); + e.barrier(); + } + /// The forward shim over the target's kernels and weights: embedding rows and the head's products. + fn shim(b: *const Backend) fwd.Ctx { + return .{ .k = b.target.k, .c = &b.target.c, .w = b.target.w, .s = undefined, .sc = undefined }; + } +}; + +fn backend(ptr: *anyopaque) *Backend { + return @ptrCast(@alignCast(ptr)); +} +fn begin(ptr: *anyopaque) !u64 { + const b = backend(ptr); + if (b.failed) return error.DraftBackendFailed; + b.stamps = .{ .begin = ticks() }; + return b.frame.begin(); +} +fn release(ptr: *anyopaque, epoch: u64) void { + const b = backend(ptr); + if (epoch == b.frame.epoch) b.frame.release(); +} +fn project(ptr: *anyopaque, epoch: u64, x: op.View, w: ck.Tensor, mode: op.Mode) !op.View { + const b = backend(ptr); + const e = try b.encoder(epoch); + const y = try b.frame.alloc(x.rows, @intCast(w.shape[0]), .bf16); + if (mode != .bf16_reference) { + const copies = b.copies orelse return error.DraftPreparationUnqualified; + return if (copies.project(e, w, x, try b.frame.ref(x), y, try b.frame.ref(y))) y else |err| err; + } + try b.primitives.linear(e, try b.frame.ref(x), try b.weight(w), try b.frame.ref(y), .{ .rows = x.rows, .n = y.width, .k = x.width, .x_stride = x.stride, .w_stride = x.width, .y_stride = y.stride }); + e.barrier(); + return y; +} +fn norm(ptr: *anyopaque, epoch: u64, x: op.View, p: op.Norm) !op.View { + const b = backend(ptr); + const e = try b.encoder(epoch); + const y = try b.frame.alloc(x.rows, x.width, .bf16); + try b.primitives.norm(e, try b.frame.ref(x), try b.weight(p.weight), try b.frame.ref(y), .{ .rows = x.rows, .heads = p.heads, .dim = p.head_dim, .x_stride = x.stride, .y_stride = y.stride, .eps = p.eps }); + e.barrier(); + return y; +} +/// The target's own embedding table reads the ids: GLM's mask token embeds in bounds, so no mapping rides along. +fn embed(ptr: *anyopaque, epoch: u64, _: ck.Linear, ids: []const u32) !op.View { + const b = backend(ptr); + const e = try b.encoder(epoch); + const r = if (b.follow) |f| f.ids else blk: { + const tokens = try b.frame.ref(try b.frame.alloc(@intCast(ids.len), 1, .u32)); + @memcpy(tokens.buf.slice(u32, ids.len), ids); + break :blk tokens; + }; + const y = try b.frame.alloc(@intCast(ids.len), b.config.hidden, .bf16); + const out = try b.frame.ref(y); + var x = b.shim(); + fwd.embedRows(&x, e, .{ .buf = r.buf, .off = r.off }, .{ .buf = out.buf, .off = out.off }, @intCast(ids.len)); + e.barrier(); + return y; +} +fn conv(ptr: *anyopaque, epoch: u64, x: op.View, p: op.Conv) !op.View { + const b = backend(ptr); + const e = try b.encoder(epoch); + const y = try b.frame.alloc(x.rows, x.width, .bf16); + try b.primitives.conv(e, try b.frame.ref(x), try b.frame.ref(p.dynamic), try b.weight(p.base), if (p.residual) |r| try b.frame.ref(r) else null, try b.frame.ref(y), .{ .rows = x.rows, .width = x.width, .group = p.group, .block = p.block, .branch = p.branch, .residual = @intFromBool(p.residual != null), .x_stride = x.stride, .dynamic_stride = p.dynamic.stride, .y_stride = y.stride }); + e.barrier(); + return y; +} +fn rope(ptr: *anyopaque, epoch: u64, x: op.View, p: op.Rotary) !op.View { + const b = backend(ptr); + const e = try b.encoder(epoch); + const r = if (b.follow) |f| f.positions else blk: { + const positions = try b.frame.ref(try b.frame.alloc(x.rows, 1, .u64)); + @memcpy(positions.buf.slice(u64, p.positions.len), p.positions); + break :blk positions; + }; + const y = try b.frame.alloc(x.rows, x.width, .bf16); + try b.primitives.rope(e, try b.frame.ref(x), r, try b.frame.ref(y), .{ .rows = x.rows, .heads = p.heads, .dim = p.dim, .x_stride = x.stride, .y_stride = y.stride, .theta = @floatCast(p.theta) }); + e.barrier(); + return y; +} +fn swiglu(ptr: *anyopaque, epoch: u64, g: op.View, u: op.View) !op.View { + const b = backend(ptr); + const e = try b.encoder(epoch); + const y = try b.frame.alloc(g.rows, g.width, .bf16); + try b.primitives.swiglu(e, try b.frame.ref(g), try b.frame.ref(u), try b.frame.ref(y), .{ .rows = g.rows, .width = g.width, .gate_stride = g.stride, .up_stride = u.stride, .y_stride = y.stride }); + e.barrier(); + return y; +} +fn maskRows(ptr: *anyopaque, epoch: u64, x: op.View, first: u32, rows: u32) !op.View { + const b = backend(ptr); + _ = try b.encoder(epoch); + if (first > x.rows or rows > x.rows - first) return error.DraftOperatorShape; + const r = try b.frame.ref(x); + return b.frame.add(.{ .buf = r.buf, .off = r.off + @as(usize, first) * x.stride * 2 }, rows, x.width, x.stride, .bf16); +} +/// Full-vocabulary logits through the target's own head: no span remap, so no token ids ride along. +fn head(ptr: *anyopaque, epoch: u64, x: op.View) !op.Head { + const b = backend(ptr); + const e = try b.encoder(epoch); + const y = try b.frame.alloc(x.rows, b.target.w.head.n, .bf16); + const input = try b.frame.ref(x); + const output = try b.frame.ref(y); + if (blockHead(b, x)) |pipes| { + const q = b.headWeights(x); + const sums = try b.frame.ref(try b.frame.alloc(x.rows, q.k / 64, .f32)); + const offsets = try b.frame.ref(try b.frame.alloc(1, 1, .u32)); + std.mem.writeInt(i32, offsets.buf.contents()[offsets.off..][0..4], 0, .little); + affine_mm.rowSums(e, pipes, 64, input, sums, x.rows, q.k); + e.barrier(); + headGather(e, pipes, input, sums, q, offsets, output, x.rows); + e.barrier(); + return .{ .logits = y, .token_ids = null }; + } + var x_ctx = b.shim(); + // the row kernels take a lone stream's mask rows as its own pass does: a batch heads each stream's apart + const block = if (b.batch_block > 1 and x.rows % b.batch_block == 0) b.batch_block else x.rows; + const first: u32 = if (block == x.rows) 0 else 1; + var s: u32 = 0; + while (s < x.rows) : (s += block) { + const at = (@as(usize, s) + first) * x.stride * 2; + const to = (@as(usize, s) + first) * b.target.w.head.n * 2; + fwd.qmv(&x_ctx, e, b.target.k.qmv_head, .{ .buf = input.buf, .off = input.off + at }, b.target.w.head, .{ .buf = output.buf, .off = output.off + to }, block - first); + } + e.barrier(); + return .{ .logits = y, .token_ids = null }; +} +/// x through the head as one matrix: affine_mm's 32-row gather tile to 32 rows, else its 64-row tile (same bits). +pub fn headGather(e: mtl.ComputeEncoder, p: affine_mm.Pipes, x: Ref, sums: Ref, q: wts.Affine, offsets: Ref, y: Ref, rows: u32) void { + const bm: u32 = if (rows <= 32) 32 else 64; + e.setPipeline(p[if (bm == 32) 2 else 3]); + e.setBuffer(x.buf, x.off, 0); + e.setBuffer(q.w.buf, q.w.off, 1); + e.setBuffer(q.s.buf, q.s.off, 2); + e.setBuffer(q.b.buf, q.b.off, 3); + e.setBuffer(sums.buf, sums.off, 4); + e.setValue(affine_mm.Args{ .rows = @intCast(rows), .n = @intCast(q.n), .k = @intCast(q.k), .experts = 1 }, 5); + e.setBuffer(y.buf, y.off, 6); + e.setBuffer(offsets.buf, offsets.off, 7); + e.dispatchGroups(mtl.Size.of(q.n / 64, (rows + bm - 1) / bm, 1), mtl.Size.of(32, 2, 2)); +} +/// Where the draft head runs: affine_mm's 4-bit or 8-bit g64 product on tensor units, else the decode row kernels. +pub const HeadPath = enum { block4, block8, rows }; +pub fn headPath(tensor_units: bool, q: wts.Affine, contiguous: bool) HeadPath { + if (!tensor_units or !contiguous or q.more != 0 or q.group != 64 or q.n % 64 != 0 or q.k % 64 != 0) return .rows; + if (wide.native(q)) return .block4; + return if (q.bits == 8) .block8 else .rows; +} +fn blockHead(b: *const Backend, x: op.View) ?affine_mm.Pipes { + return switch (headPath(b.target.device.tensorUnits(), b.headWeights(x), x.stride == x.width)) { + .block4 => b.target.k.mm_bf16, + .block8 => b.target.k.wide.?.mm8, + .rows => null, + }; +} +fn lattice(ptr: *anyopaque, epoch: u64, h: op.Head, projected: op.View, c: draft_cfg.Config) !op.Lattice { + const b = backend(ptr); + _ = try b.encoder(epoch); + const output = try b.frame.alloc(h.logits.rows, @sizeOf(core.bf16_topk.Row), .u8); + const logits = try b.frame.ref(h.logits); + const out = try b.frame.ref(output); + const p = core.bf16_topk.Params{ .rows = h.logits.rows, .vocab = h.logits.width, .k = c.topk, .stride = h.logits.stride }; + // the block rows' top k with core's bytes: a threadgroup a row, else core's spans and merge + if (dtopk.takes(p)) try b.draft_topk.encode(b.frame.encoder, .{ .buf = logits.buf, .off = logits.off }, .{ .buf = out.buf, .off = out.off }, p) else try b.topk.encode(b.frame.encoder, .{ .buf = logits.buf, .off = logits.off }, .{ .buf = out.buf, .off = out.off }, p); + b.frame.encoder.barrier(); + b.stamps.commit = ticks(); + b.frame.finish() catch |err| { + b.failed = true; + return err; + }; + b.stamps.waited = ticks(); + b.stamps.gpu = span(&b.frame); + defer b.stamps.read = ticks(); + return @import("../qwen27/dflash/runtime_lattice.zig").read(b.allocator, &b.frame, output, projected, c, h); +} +/// A pass's top k encoded with no wait: its rows' candidates, read once the frame's last buffer completes. +pub fn encodeTopk(b: *Backend, epoch: u64, h: op.Head, k: u32) !op.View { + _ = try b.encoder(epoch); + const output = try b.frame.alloc(h.logits.rows, @sizeOf(core.bf16_topk.Row), .u8); + const logits = try b.frame.ref(h.logits); + const out = try b.frame.ref(output); + const p = core.bf16_topk.Params{ .rows = h.logits.rows, .vocab = h.logits.width, .k = k, .stride = h.logits.stride }; + if (dtopk.takes(p)) try b.draft_topk.encode(b.frame.encoder, .{ .buf = logits.buf, .off = logits.off }, .{ .buf = out.buf, .off = out.off }, p) else try b.topk.encode(b.frame.encoder, .{ .buf = logits.buf, .off = logits.off }, .{ .buf = out.buf, .off = out.off }, p); + b.frame.encoder.barrier(); + return output; +} +/// A completed pass's lattices: a lone stream's headed rows, or each stream's block rows past its anchor. +pub fn readLattices(b: *Backend, h: op.Head, topk: op.View, projected: op.View, c: draft_cfg.Config, block: u32, out: []op.Lattice) !void { + const read = @import("../qwen27/dflash/runtime_lattice.zig").read; + if (out.len == 1 and h.logits.rows == block - 1) { + out[0] = try read(b.allocator, &b.frame, topk, projected, c, h); + return; + } + if (h.logits.rows != out.len * block) return error.DraftOperatorShape; + var made: usize = 0; + errdefer for (out[0..made]) |*l| l.deinit(); + for (out, 0..) |*l, k| { + const first: u32 = @intCast(k * block + 1); // a stream's anchor row drafts nothing + const hs: op.Head = .{ .logits = try rowsOf(b, h.logits, first, block - 1), .token_ids = h.token_ids }; + l.* = try read(b.allocator, &b.frame, try rowsOf(b, topk, first, block - 1), try rowsOf(b, projected, first, block - 1), c, hs); + made += 1; + } +} +/// Rows [first, first + rows) of `x`, an alias in the frame. +fn rowsOf(b: *Backend, x: op.View, first: u32, rows: u32) !op.View { + if (first > x.rows or rows > x.rows - first) return error.DraftOperatorShape; + const r = try b.frame.ref(x); + return b.frame.add(.{ .buf = r.buf, .off = r.off + @as(usize, first) * x.stride * x.dtype.size() }, rows, x.width, x.stride, x.dtype); +} +/// A batched pass's head: one top-k over every stream's rows and one wait, then each stream's lattice past its anchor. +fn lattices(ptr: *anyopaque, epoch: u64, h: op.Head, projected: op.View, c: draft_cfg.Config, block: u32, out: []op.Lattice) !void { + const b = backend(ptr); + _ = try b.encoder(epoch); + if (block < 2 or h.logits.rows != out.len * block or out.len > dtopk.max_rows / block) return error.DraftOperatorShape; + const output = try b.frame.alloc(h.logits.rows, @sizeOf(core.bf16_topk.Row), .u8); + const logits = try b.frame.ref(h.logits); + const rows = try b.frame.ref(output); + // a row's top k does not depend on the rows beside it: the anchors' rows are ranked and never read + try b.draft_topk.encode(b.frame.encoder, .{ .buf = logits.buf, .off = logits.off }, .{ .buf = rows.buf, .off = rows.off }, .{ .rows = h.logits.rows, .vocab = h.logits.width, .k = c.topk, .stride = h.logits.stride }); + b.frame.encoder.barrier(); + b.stamps.commit = ticks(); + b.frame.finish() catch |err| { + b.failed = true; + return err; + }; + b.stamps.waited = ticks(); + b.stamps.gpu = span(&b.frame); + defer b.stamps.read = ticks(); + var made: usize = 0; + errdefer for (out[0..made]) |*l| l.deinit(); + for (out, 0..) |*l, k| { + const first: u32 = @intCast(k * block + 1); // a stream's anchor row drafts nothing + const hs: op.Head = .{ .logits = try rowsOf(b, h.logits, first, block - 1), .token_ids = h.token_ids }; + l.* = try @import("../qwen27/dflash/runtime_lattice.zig").read(b.allocator, &b.frame, try rowsOf(b, output, first, block - 1), try rowsOf(b, projected, first, block - 1), c, hs); + 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 }; diff --git a/zig/src/families/glm/metal_dflash_config.zig b/zig/src/families/glm/metal_dflash_config.zig new file mode 100644 index 00000000000..11fa8efb0ba --- /dev/null +++ b/zig/src/families/glm/metal_dflash_config.zig @@ -0,0 +1,249 @@ +//! GLM-5.3-Flash's DFlash2 drafter config: incoai's five-tap contract read into the shared draft Config. +const std = @import("std"); +const draft = @import("../qwen27/dflash/config.zig"); + +pub const repository = "incoai/GLM-5.3-Flash-DFlash2"; +pub const tap_ids = [5]u32{ 5, 14, 24, 33, 42 }; +pub const Config = draft.Config; + +/// The five taps in the shared config's slots, the rest zero. +const tap_slots: [draft.max_taps]u32 = blk: { + var t: [draft.max_taps]u32 = @splat(0); + @memcpy(t[0..tap_ids.len], &tap_ids); + break :blk t; +}; + +/// The stock incoai drafter: the shared draft contract's fields at GLM-5.3-Flash's shape. +pub const stock = Config{ + .hidden = 4096, + .intermediate = 12288, + .layers = 5, + .vocab = 154880, + .heads = 32, + .kv_heads = 8, + .head_dim = 128, + .target_layers = 45, + .block = 8, + .mask = 154856, + .window = 2048, + .group = 16, + .conv = 2, + .rank = 256, + .topk = 16, + .eps = 1e-5, + .theta = 10000, + .taps = tap_slots, + .tap_count = tap_ids.len, +}; + +/// The GLM drafter's own refusals, each naming the field that is not incoai's five-tap contract. +pub const Refusal = error{ + GlmDflash2Schema, + GlmDflash2Architecture, + GlmDflash2ModelType, + GlmDflash2Dtype, + GlmDflash2Hidden, + GlmDflash2Intermediate, + GlmDflash2Layers, + GlmDflash2Vocab, + GlmDflash2Heads, + GlmDflash2KvHeads, + GlmDflash2HeadDim, + GlmDflash2TargetLayers, + GlmDflash2Block, + GlmDflash2Mask, + GlmDflash2Window, + GlmDflash2Group, + GlmDflash2Conv, + GlmDflash2Rank, + GlmDflash2Topk, + GlmDflash2Eps, + GlmDflash2Theta, + GlmDflash2Taps, + GlmDflash2Attention, + GlmDflash2Rope, +}; + +/// `c` is incoai's drafter for a 45-layer GLM-5.3-Flash target, or the field that is not. +pub fn check(c: Config) Refusal!void { + if (c.hidden != stock.hidden) return error.GlmDflash2Hidden; + if (c.intermediate != stock.intermediate) return error.GlmDflash2Intermediate; + if (c.layers != stock.layers) return error.GlmDflash2Layers; + if (c.vocab != stock.vocab) return error.GlmDflash2Vocab; + if (c.heads != stock.heads) return error.GlmDflash2Heads; + if (c.kv_heads != stock.kv_heads) return error.GlmDflash2KvHeads; + if (c.head_dim != stock.head_dim) return error.GlmDflash2HeadDim; + if (c.target_layers != stock.target_layers) return error.GlmDflash2TargetLayers; + if (c.block != stock.block) return error.GlmDflash2Block; + if (c.mask != stock.mask) return error.GlmDflash2Mask; + if (c.window != stock.window) return error.GlmDflash2Window; + if (c.group != stock.group) return error.GlmDflash2Group; + if (c.conv != stock.conv) return error.GlmDflash2Conv; + if (c.rank != stock.rank) return error.GlmDflash2Rank; + if (c.topk != stock.topk) return error.GlmDflash2Topk; + if (c.eps != stock.eps) return error.GlmDflash2Eps; + if (c.theta != stock.theta) return error.GlmDflash2Theta; + if (!std.mem.eql(u32, c.tapIds(), &tap_ids)) return error.GlmDflash2Taps; + c.check() catch return error.GlmDflash2Schema; +} + +/// The target's shape this drafter binds to: hidden, vocabulary and layer count, as the engine reads them. +pub const Target = struct { hidden: u32, vocab: u32, layers: u32 }; + +/// `t` is the GLM-5.3-Flash target this drafter's taps and vocabulary belong to. +pub fn bind(c: Config, t: Target) Refusal!void { + try check(c); + if (t.hidden != c.hidden) return error.GlmDflash2Hidden; + if (t.vocab != c.vocab) return error.GlmDflash2Vocab; + if (t.layers != c.target_layers) return error.GlmDflash2TargetLayers; +} + +fn object(v: std.json.Value) Refusal!std.json.ObjectMap { + return if (v == .object) v.object else error.GlmDflash2Schema; +} + +fn integer(o: std.json.ObjectMap, name: []const u8) Refusal!u32 { + const v = o.get(name) orelse return error.GlmDflash2Schema; + if (v != .integer or v.integer < 0 or v.integer > std.math.maxInt(u32)) return error.GlmDflash2Schema; + return @intCast(v.integer); +} + +fn number(o: std.json.ObjectMap, name: []const u8) Refusal!f64 { + const v = o.get(name) orelse return error.GlmDflash2Schema; + const value: f64 = switch (v) { + .integer => |n| @floatFromInt(n), + .float => |n| n, + else => return error.GlmDflash2Schema, + }; + return if (std.math.isFinite(value)) value else error.GlmDflash2Schema; +} + +fn text(o: std.json.ObjectMap, name: []const u8, wanted: []const u8) Refusal!void { + const v = o.get(name) orelse return error.GlmDflash2Schema; + if (v != .string or !std.mem.eql(u8, v.string, wanted)) return error.GlmDflash2Schema; +} + +fn flag(o: std.json.ObjectMap, name: []const u8, wanted: bool) Refusal!void { + const v = o.get(name) orelse return error.GlmDflash2Schema; + if (v != .bool or v.bool != wanted) return error.GlmDflash2Schema; +} + +/// The drafter's `config.json` text as incoai's five-tap contract, or the field that is not. +pub fn parse(gpa: std.mem.Allocator, raw: []const u8) !Config { + const p = try std.json.parseFromSlice(std.json.Value, gpa, raw, .{}); + defer p.deinit(); + const o = try object(p.value); + const d = try object(o.get("dflash_config") orelse return error.GlmDflash2Schema); + const architectures = o.get("architectures") orelse return error.GlmDflash2Schema; + if (architectures != .array or architectures.array.items.len != 1 or architectures.array.items[0] != .string) return error.GlmDflash2Schema; + if (!std.mem.eql(u8, architectures.array.items[0].string, "DFlash2DraftModel")) return error.GlmDflash2Architecture; + try text(o, "model_type", "qwen3"); + try text(o, "dtype", "bfloat16"); + try text(o, "hidden_act", "silu"); + try flag(o, "is_causal", false); + try flag(o, "attention_bias", false); + try flag(o, "tie_word_embeddings", false); + try flag(o, "use_sliding_window", true); + if (try number(o, "attention_dropout") != 0) return error.GlmDflash2Attention; + const rope = try object(o.get("rope_parameters") orelse return error.GlmDflash2Schema); + try text(rope, "rope_type", "default"); + if (o.get("rope_scaling")) |v| if (v != .null) return error.GlmDflash2Rope; + var c = Config{ + .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 = try integer(d, "conv_group_size"), + .conv = try integer(d, "conv_kernel_size"), + .rank = try integer(d, "selector_rank"), + .topk = try integer(d, "selector_top_k"), + .eps = @floatCast(try number(o, "rms_norm_eps")), + .theta = try number(rope, "rope_theta"), + }; + const taps = d.get("target_layer_ids") orelse return error.GlmDflash2Schema; + if (taps != .array or taps.array.items.len != tap_ids.len) return error.GlmDflash2Taps; + c.taps = @splat(0); + c.tap_count = tap_ids.len; + for (taps.array.items, 0..) |v, i| { + if (v != .integer or v.integer < 0 or v.integer > std.math.maxInt(u32)) return error.GlmDflash2Schema; + c.taps[i] = @intCast(v.integer); + } + const types = o.get("layer_types") orelse return error.GlmDflash2Schema; + if (types != .array or types.array.items.len != c.layers) return error.GlmDflash2Schema; + for (types.array.items) |v| if (v != .string or !std.mem.eql(u8, v.string, "sliding_attention")) return error.GlmDflash2Attention; + try check(c); + return c; +} + +const fixture = + \\{"architectures":["DFlash2DraftModel"],"model_type":"qwen3","dtype":"bfloat16","hidden_act":"silu", + \\"hidden_size":4096,"intermediate_size":12288,"num_hidden_layers":5,"vocab_size":154880, + \\"num_attention_heads":32,"num_key_value_heads":8,"head_dim":128,"num_target_layers":45, + \\"is_causal":false,"attention_bias":false,"tie_word_embeddings":false,"attention_dropout":0.0, + \\"use_sliding_window":true,"sliding_window":2048,"rms_norm_eps":0.00001, + \\"rope_parameters":{"rope_type":"default","rope_theta":10000.0}, + \\"layer_types":["sliding_attention","sliding_attention","sliding_attention","sliding_attention","sliding_attention"], + \\"dflash_config":{"block_size":8,"mask_token_id":154856,"conv_group_size":16,"conv_kernel_size":2, + \\"selector_rank":256,"selector_top_k":16,"target_layer_ids":[5,14,24,33,42]}} +; + +test "incoai's cached schema resolves the stock five-tap GLM drafter" { + const c = try parse(std.testing.allocator, fixture); + try std.testing.expectEqualDeep(stock, c); + try std.testing.expectEqual(@as(usize, 81), c.tensorCount()); + try std.testing.expectEqual(@as(usize, 47), c.linearCount()); + try std.testing.expectEqual(@as(u32, 20480), c.tapWidth()); +} + +test "a target of another shape is refused by the field that differs" { + try std.testing.expectError(error.GlmDflash2Hidden, bind(stock, .{ .hidden = 5120, .vocab = 154880, .layers = 45 })); + try std.testing.expectError(error.GlmDflash2Vocab, bind(stock, .{ .hidden = 4096, .vocab = 248320, .layers = 45 })); + try std.testing.expectError(error.GlmDflash2TargetLayers, bind(stock, .{ .hidden = 4096, .vocab = 154880, .layers = 64 })); + try bind(stock, .{ .hidden = 4096, .vocab = 154880, .layers = 45 }); +} + +test "qwen27's stock drafter is not a GLM drafter" { + try std.testing.expectError(error.GlmDflash2Hidden, check(draft.Config{})); +} + +test "a nine-tap or shifted-tap drafter is refused before any weight is read" { + var c = stock; + c.taps = .{ 5, 9, 14, 19, 24, 0, 0, 0 }; + try std.testing.expectError(error.GlmDflash2Taps, check(c)); + c = stock; + c.target_layers = 64; + try std.testing.expectError(error.GlmDflash2TargetLayers, check(c)); +} + +test "a causal reading, a scaled rope or a full-attention layer cannot become the default" { + const a = std.testing.allocator; + const causal = try std.mem.replaceOwned(u8, a, fixture, "\"is_causal\":false", "\"is_causal\":true"); + defer a.free(causal); + try std.testing.expectError(error.GlmDflash2Schema, parse(a, causal)); + const scaled = try std.mem.replaceOwned(u8, a, fixture, "\"layer_types\"", "\"rope_scaling\":{\"type\":\"yarn\",\"factor\":4.0},\"layer_types\""); + defer a.free(scaled); + try std.testing.expectError(error.GlmDflash2Rope, parse(a, scaled)); + const full = try std.mem.replaceOwned(u8, a, fixture, "\"sliding_attention\",\"sliding_attention\",\"sliding_attention\",\"sliding_attention\",\"sliding_attention\"", "\"full_attention\",\"sliding_attention\",\"sliding_attention\",\"sliding_attention\",\"sliding_attention\""); + defer a.free(full); + try std.testing.expectError(error.GlmDflash2Attention, parse(a, full)); +} + +test "a drafter of another vocabulary or norm epsilon is refused by name" { + const a = std.testing.allocator; + const vocab = try std.mem.replaceOwned(u8, a, fixture, "\"vocab_size\":154880", "\"vocab_size\":248320"); + defer a.free(vocab); + try std.testing.expectError(error.GlmDflash2Vocab, parse(a, vocab)); + const eps = try std.mem.replaceOwned(u8, a, fixture, "\"rms_norm_eps\":0.00001", "\"rms_norm_eps\":0.000001"); + defer a.free(eps); + try std.testing.expectError(error.GlmDflash2Eps, parse(a, eps)); + const theta = try std.mem.replaceOwned(u8, a, fixture, "\"rope_theta\":10000.0", "\"rope_theta\":10000000.0"); + defer a.free(theta); + try std.testing.expectError(error.GlmDflash2Theta, parse(a, theta)); +} diff --git a/zig/src/families/glm/metal_dflash_context.zig b/zig/src/families/glm/metal_dflash_context.zig new file mode 100644 index 00000000000..059504cd147 --- /dev/null +++ b/zig/src/families/glm/metal_dflash_context.zig @@ -0,0 +1,216 @@ +//! GLM's draft context: only completed committed-tap transactions advance the drafter's rolling window. +const std = @import("std"); +const mtl = @import("metal"); +const op = @import("../qwen27/dflash/operators.zig"); +const Backend = @import("metal_dflash_backend.zig").Backend; +const Cache = @import("metal_dflash_backend.zig").Cache; +const dattn = @import("metal_dflash_attention.zig"); + +/// Rows a stream's K/V ring cycles through: all its caches hold, so rows past the context's end miss its keys. +pub fn ring(c: @import("../qwen27/dflash/config.zig").Config) u32 { + return c.window + 16; +} + +fn cast(ptr: *anyopaque) *Backend { + return @ptrCast(@alignCast(ptr)); +} + +pub fn begin(ptr: *anyopaque, current: op.Context) !u64 { + const b = cast(ptr); + if (b.failed or b.transaction != null or !std.meta.eql(current, b.context)) return error.BadDraftContext; + try b.frame.require(b.frame.epoch); + b.transaction = b.frame.epoch; + b.appended = 0; + b.appended_rows = 0; + return b.frame.epoch; +} + +pub fn append(ptr: *anyopaque, transaction: u64, epoch: u64, layer: u32, keys: op.View, values: op.View, positions: []const u64) !void { + const b = cast(ptr); + const e = try b.encoder(epoch); + if (b.transaction != transaction or transaction != epoch or layer >= b.config.layers or b.appended & (@as(u32, 1) << @intCast(layer)) != 0 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); + 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); + b.appended |= @as(u32, 1) << @intCast(layer); + b.appended_rows = @intCast(positions.len); +} + +/// A batched pass's stream `stream`: its new taps' keys and values into its own caches (the backend's batch). +pub fn streamAppend(ptr: *anyopaque, epoch: u64, stream: u32, layer: u32, keys: op.View, values: op.View, positions: []const u64) !void { + const b = cast(ptr); + const e = try b.encoder(epoch); + 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); +} + +/// Rows' keys and values into `cache` at their positions' ring slots, 16 a dispatch. +fn appendRows(b: *Backend, e: mtl.ComputeEncoder, cache: Cache, keys: op.View, values: op.View, positions: []const u64) !void { + 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] % ring(b.config)); + 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 }); + 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; +} + +pub fn commit(ptr: *anyopaque, transaction: u64, epoch: u64, next: op.Context) !void { + const b = cast(ptr); + try ready(b, transaction, epoch, next); + b.frame.finish() catch |err| { + b.failed = true; + return err; + }; + b.context = next; + b.transaction = null; +} + +/// The context advances now and the frame stays open; if the frame then never completes, abort fails the backend. +pub fn stage(ptr: *anyopaque, transaction: u64, epoch: u64, next: op.Context) !void { + const b = cast(ptr); + try ready(b, transaction, epoch, next); + b.context = next; + b.transaction = null; + b.staged = transaction; +} + +pub fn abort(ptr: *anyopaque, transaction: u64) void { + const b = cast(ptr); + if (b.transaction == transaction) { + if (b.frame.completed) b.failed = true; + b.transaction = null; + } + if (b.staged == transaction) { + if (!b.frame.completed) b.failed = true; + b.staged = null; + } +} + +pub fn attention(ptr: *anyopaque, epoch: u64, p: op.Attention) !op.View { + const b = cast(ptr); + const e = try b.encoder(epoch); + if (b.transaction != null or p.layer >= b.config.layers or p.mask != .all_slots) return error.BadDraftContext; + if (b.follow) |f| return attendFollow(b, e, p, f); + var rings: [dattn.max_streams]dattn.Ring = undefined; + var contexts: [dattn.max_streams]op.Context = undefined; + var n: usize = 1; + var block = p.query.rows; + if (p.streams.len == 0) { + if (!std.meta.eql(p.context, b.context)) return error.BadDraftContext; + contexts[0] = p.context; + rings[0] = .{ .k = .{ .buf = b.caches[p.layer].keys }, .v = .{ .buf = b.caches[p.layer].values } }; + } else { + n = p.streams.len; + if (n > dattn.max_streams or n > b.batch.len or p.block == 0 or p.query.rows != n * p.block) return error.BadDraftContext; + block = p.block; + for (p.streams, 0..) |context, k| { + contexts[k] = context; + rings[k] = .{ .k = .{ .buf = b.batch[k][p.layer].keys }, .v = .{ .buf = b.batch[k][p.layer].values } }; + } + } + const result = try b.frame.alloc(p.query.rows, b.config.qWidth(), .bf16); + try attendStreams(b, e, p, contexts[0..n], rings[0..n], block, result); + e.barrier(); + return result; +} + +/// Each stream's block rows over its context's cached keys (read where its ring holds them) and its own, one launch. +fn attendStreams(b: *Backend, e: mtl.ComputeEncoder, p: op.Attention, contexts: []const op.Context, rings: []const dattn.Ring, block: u32, result: op.View) !void { + const width = b.config.kvWidth(); + if (p.keys.stride != width or p.values.stride != width or p.query.stride != b.config.qWidth() or result.stride != b.config.qWidth()) return error.DraftOperatorShape; + var table: [dattn.max_streams]dattn.Stream = undefined; + for (contexts, table[0..contexts.len]) |context, *t| { + const context_rows: u32 = @intCast(context.end - context.begin); + t.* = .{ .keys = context_rows + block, .context = context_rows, .at = @intCast(context.begin % ring(b.config)) }; + } + const scale = 1.0 / @sqrt(@as(f32, @floatFromInt(b.config.head_dim))); + const args = try dattn.plan(table[0..contexts.len], block, ring(b.config), scale); + const mask = try b.frame.ref(try b.frame.alloc(args.rows, args.mask_stride, .u8)); + const bytes = mask.buf.contents()[mask.off..][0 .. @as(usize, args.rows) * args.mask_stride]; + var one: [16 * (2048 + 16)]u8 = undefined; + for (table[0..contexts.len], 0..) |t, k| { + const m = one[0 .. @as(usize, block) * t.keys]; + try fillMask(m, t.context, block, b.config.window, b.config.block); + for (0..block) |r| @memcpy(bytes[(k * block + r) * args.mask_stride ..][0..t.keys], m[r * t.keys ..][0..t.keys]); + } + const part = try b.frame.ref(try b.frame.alloc(1, @intCast(dattn.partBytes(b.draft_attention.shape, args)), .u8)); + const q = try b.frame.ref(p.query); + const own_k = try b.frame.ref(p.keys); + const own_v = try b.frame.ref(p.values); + const y = try b.frame.ref(result); + try b.draft_attention.encode(e, args, table[0..contexts.len], rings, .{ .buf = q.buf, .off = q.off }, .{ .buf = own_k.buf, .off = own_k.off }, .{ .buf = own_v.buf, .off = own_v.off }, .{ .buf = mask.buf, .off = mask.off }, .{ .buf = part.buf, .off = part.off }, .{ .buf = y.buf, .off = y.off }); +} + +/// A block planned on the GPU: each stream's rows over its longest context, the mask the follow kernel wrote. +fn attendFollow(b: *Backend, e: mtl.ComputeEncoder, p: op.Attention, f: @import("metal_dflash_backend.zig").Device) !op.View { + const n = f.streams; + if (n == 0 or n > dattn.max_streams or n > b.batch.len or p.query.rows % n != 0) return error.BadDraftContext; + const block = p.query.rows / n; + const width = b.config.kvWidth(); + if (p.keys.stride != width or p.values.stride != width or p.query.stride != b.config.qWidth()) return error.DraftOperatorShape; + var rings: [dattn.max_streams]dattn.Ring = undefined; + for (rings[0..n], 0..) |*r, k| r.* = .{ .k = .{ .buf = b.batch[k][p.layer].keys }, .v = .{ .buf = b.batch[k][p.layer].values } }; + const scale = 1.0 / @sqrt(@as(f32, @floatFromInt(b.config.head_dim))); + const args = try dattn.plan(f.keys[0..n], block, ring(b.config), scale); + if (args.mask_stride != f.mask_stride) return error.BadDraftContext; + const result = try b.frame.alloc(p.query.rows, b.config.qWidth(), .bf16); + const part = try b.frame.ref(try b.frame.alloc(1, @intCast(dattn.partBytes(b.draft_attention.shape, args)), .u8)); + const q = try b.frame.ref(p.query); + const own_k = try b.frame.ref(p.keys); + const own_v = try b.frame.ref(p.values); + const y = try b.frame.ref(result); + try b.draft_attention.encode(e, args, f.keys[0..n], rings[0..n], .{ .buf = q.buf, .off = q.off }, .{ .buf = own_k.buf, .off = own_k.off }, .{ .buf = own_v.buf, .off = own_v.off }, .{ .buf = f.mask.buf, .off = f.mask.off }, .{ .buf = part.buf, .off = part.off }, .{ .buf = y.buf, .off = y.off }); + e.barrier(); + return result; +} + +/// 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; + const keys = try std.math.add(u32, context_rows, queries); + if (out.len != try std.math.mul(usize, queries, keys)) return error.BadDraftContext; + @memset(out, 1); + for (0..queries) |query| { + const hidden = @min(context_rows, (@as(usize, context_rows) + query + 1) -| window); + @memset(out[query * keys ..][0..hidden], 0); + if (query < trained and queries > trained) @memset(out[query * keys + context_rows + trained ..][0 .. queries - trained], 0); + } +} + +test "a stream's K/V ring cycles through every row its caches hold" { + const c: @import("../qwen27/dflash/config.zig").Config = .{}; + const caches = @as(usize, c.window + 16) * c.kvWidth() * 2; // caches.zig's rows a layer + try std.testing.expectEqual(caches, @as(usize, ring(c)) * c.kvWidth() * 2); + try std.testing.expect(ring(c) >= c.window - 1 + 16); // a full context plus a window's rows past its end +} + +test "GLM's sliding context advances per query and hides later slots from trained ones" { + const a = std.testing.allocator; + for ([_]u32{ 0, 1, 63, 2047 }) |context| { + const window: u32 = if (context == 2047) 2048 else 64; + for ([_]u32{ 8, 16 }) |queries| { + const keys = context + queries; + const mask = try a.alloc(u8, keys * queries); + defer a.free(mask); + try fillMask(mask, context, queries, window, 8); + for (0..queries) |query| for (0..keys) |key| { + const late = key >= context + 8 and query < 8; + const visible = (key >= context or context + query < key + window) and !late; + try std.testing.expectEqual(@as(u8, @intFromBool(visible)), mask[query * keys + key]); + }; + } + } +} diff --git a/zig/src/families/glm/metal_dflash_follow.zig b/zig/src/families/glm/metal_dflash_follow.zig new file mode 100644 index 00000000000..f111b6b1c3b --- /dev/null +++ b/zig/src/families/glm/metal_dflash_follow.zig @@ -0,0 +1,124 @@ +//! A DFlash2 block whose window was accepted on the GPU (glm_draft_follow.metal): ids, positions, mask from the count. +const std = @import("std"); +const mtl = @import("metal"); +const sources = @import("kernel_sources"); +const cfg = @import("../qwen27/dflash/config.zig"); +const dattn = @import("metal_dflash_attention.zig"); + +pub const Ref = struct { buf: mtl.Buffer, off: usize = 0 }; + +/// glm_follow_stream: window rows from `first`, context keys [lo, lo + context) then block rows; `begin` its start. +pub const Stream = extern struct { first: u64, lo: u64, begin: u64, context: u32, keys: u32 }; +/// glm_follow_args: `streams` blocks of `block` rows, the first `trained` blind to the rest; `mask_stride` keys a row. +pub const Args = extern struct { block: u32, streams: u32, trained: u32, window: u32, mask_token: u32, mask_stride: u32, rows: u32, pad: u32 = 0 }; + +/// A stream's window: its context's start before the window, the window's first position and its rows. +pub const Window = struct { begin: u64, first: u64, rows: u32 }; + +/// A pass planned at each stream's longest context (every window row kept): the kernel's and the attention's tables. +pub const Plan = struct { args: Args, streams: [dattn.max_streams]Stream, keys: [dattn.max_streams]dattn.Stream }; + +/// The plan for `windows` at `block` rows a stream over K/V rings of `ring` rows. +pub fn plan(c: cfg.Config, windows: []const Window, block: u32, ring: u32) !Plan { + if (windows.len == 0 or windows.len > dattn.max_streams or block < 2 or block > dattn.max_block) return error.BadFollowPlan; + var p: Plan = .{ .args = .{ .block = block, .streams = @intCast(windows.len), .trained = c.block, .window = c.window, .mask_token = c.mask, .mask_stride = 0, .rows = @intCast(windows.len * block) }, .streams = undefined, .keys = undefined }; + for (windows, 0..) |w, k| { + if (w.rows == 0 or w.begin > w.first) return error.BadFollowPlan; + const lo = @max(w.begin, (w.first + 1) -| (@as(u64, c.window) - 1)); // context start with zero kept drafts + const context: u32 = @intCast(w.first + w.rows - lo); + if (context > ring) return error.BadFollowPlan; + p.streams[k] = .{ .first = w.first, .lo = lo, .begin = w.begin, .context = context, .keys = context + block }; + p.keys[k] = .{ .keys = context + block, .context = context, .at = @intCast(lo % ring) }; + p.args.mask_stride = @max(p.args.mask_stride, context + block); + } + return p; +} + +/// The kernel's output on the host: `accepted` two words a stream (drafts kept, anchor) into ids, positions, mask. +pub fn fill(p: Plan, accepted: []const u32, ids: []u32, positions: []u64, mask: []u8) void { + const a = p.args; + for (0..a.rows) |row| { + const s = row / a.block; + const q: u32 = @intCast(row % a.block); + const t = p.streams[s]; + const end = t.first + accepted[2 * s] + 1; + ids[row] = if (q == 0) accepted[2 * s + 1] else a.mask_token; + positions[row] = end + q; + const reach = end + q + 1; + const from = @max(t.begin, reach -| a.window); + for (0..a.mask_stride) |key| { + const visible = if (key < t.context) blk: { + const pos = t.lo + key; + break :blk pos >= from and pos < end; + } else if (key < t.keys) !(q < a.trained and a.block > a.trained and key - t.context >= a.trained) else false; + mask[row * a.mask_stride + key] = @intFromBool(visible); + } + } +} + +pub const Follow = struct { + pipe: mtl.Pipeline, + + /// `edit` replaces one text of the source (a contract control's planted fault), else null. + pub fn init(a: std.mem.Allocator, device: mtl.Device, edit: ?[2][]const u8) !Follow { + const text = if (edit) |x| blk: { + if (std.mem.indexOf(u8, sources.glm_draft_follow, x[0]) == null) return error.ControlEditMissing; + break :blk try std.mem.replaceOwned(u8, a, sources.glm_draft_follow, x[0], x[1]); + } else try a.dupe(u8, sources.glm_draft_follow); + defer a.free(text); + const lib = try mtl.Library.fromSource(device, text, mtl.CompileOptions.mlx()); + defer lib.deinit(); + return .{ .pipe = try mtl.Pipeline.init(device, lib, "glm_draft_follow", false) }; + } + + pub fn deinit(x: Follow) void { + x.pipe.deinit(); + } + + /// `p`'s ids, positions and mask from `accepted` (two words a stream), a thread a key of a row. + pub fn encode(x: Follow, e: mtl.ComputeEncoder, p: Plan, accepted: Ref, ids: Ref, positions: Ref, mask: Ref) !void { + const a = p.args; + if (a.rows == 0 or a.mask_stride == 0 or positions.off % 8 != 0 or accepted.off % 4 != 0 or ids.off % 4 != 0) return error.BadFollowBuffer; + if (mask.off + @as(usize, a.rows) * a.mask_stride > mask.buf.length() or positions.off + @as(usize, a.rows) * 8 > positions.buf.length() or ids.off + @as(usize, a.rows) * 4 > ids.buf.length()) return error.BadFollowBuffer; + e.setPipeline(x.pipe); + e.setBuffer(accepted.buf, accepted.off, 0); + e.setValue(a, 1); + e.setValue(p.streams, 2); + e.setBuffer(ids.buf, ids.off, 3); + e.setBuffer(positions.buf, positions.off, 4); + e.setBuffer(mask.buf, mask.off, 5); + e.dispatchThreads(mtl.Size.of(a.mask_stride, a.rows, 1), mtl.Size.of(32, 1, 1)); + } +}; + +test "a plan at the longest context, filled at a kept count, masks as the context's own plan at that count does" { + var c: cfg.Config = .{}; + c.window = 64; + const fill_mask = @import("metal_dflash_context.zig").fillMask; + for ([_]u64{ 0, 30, 100 }) |first| for ([_]u32{ 8, 16 }) |block| for (0..8) |kept| { + const begin: u64 = if (first == 100) 40 else 0; + const p = try plan(c, &.{.{ .begin = begin, .first = first, .rows = 8 }}, block, c.window + 16); + var ids: [16]u32 = undefined; + var positions: [16]u64 = undefined; + var mask: [16 * 96]u8 = undefined; + const accepted = [2]u32{ @intCast(kept), 77 }; + fill(p, &accepted, ids[0..block], positions[0..block], mask[0 .. block * p.args.mask_stride]); + // the context's own plan at this count: [start, end) then the block + const end = first + kept + 1; + const start = @max(begin, end -| (c.window - 1)); + const rows: u32 = @intCast(end - start); + var own: [16 * 96]u8 = undefined; + try fill_mask(own[0 .. block * (rows + block)], rows, block, c.window, c.block); + for (0..block) |q| { + try std.testing.expectEqual(if (q == 0) @as(u32, 77) else c.mask, ids[q]); + try std.testing.expectEqual(end + q, positions[q]); + for (0..p.args.mask_stride) |key| { + const want: u8 = if (key < p.streams[0].context) blk: { + const pos = p.streams[0].lo + key; + break :blk if (pos < start or pos >= end) 0 else own[q * (rows + block) + (pos - start)]; + } else own[q * (rows + block) + rows + (key - p.streams[0].context)]; + try std.testing.expectEqual(want, mask[q * p.args.mask_stride + key]); + } + } + }; +} diff --git a/zig/src/families/glm/metal_dflash_head_depth.zig b/zig/src/families/glm/metal_dflash_head_depth.zig new file mode 100644 index 00000000000..5f002079b3f --- /dev/null +++ b/zig/src/families/glm/metal_dflash_head_depth.zig @@ -0,0 +1,151 @@ +//! The MTP head's depth for a GLM stream drafting with it beside DFlash2: main's own rule, so its rounds cost main's. +const std = @import("std"); +const lanes = @import("lanes"); +const st = @import("state.zig"); + +/// A stream's head rounds: the rule's state, and what its last head round asked and its window verified. +pub const Stream = struct { + state: ?lanes.depth.State = null, + asked: ?u32 = null, // the drafts its last round asked of the head (null: that round was not the head's) + first: bool = false, // that round was the prompt's first: its time carries the prefill-to-decode switch + held: ?u32 = null, // the drafts the window after it verified + cost: ?Cost = null, // that round's time, priced after the next depth as main's round loop prices it + + pub fn deinit(s: *Stream, gpa: std.mem.Allocator) void { + if (s.state) |*x| x.deinit(gpa); + s.* = .{}; + } +}; + +/// A head round's time waiting for the rule: main observes it after it has chosen the next round's depth. +pub const Cost = struct { held: u32, ms: f64, first: bool }; + +/// Main's depth rule, made from main's facts (no drafter loaded): its prior, window costs, head step and probes. +pub const Head = struct { + gpa: std.mem.Allocator, + cfg: lanes.Config, + rule: lanes.depth.Rule, + + pub fn init(gpa: std.mem.Allocator, m: lanes.Model) !*Head { + const h = try gpa.create(Head); + errdefer gpa.destroy(h); + h.gpa = gpa; + h.cfg = try lanes.Config.init(gpa, m, st.max_rows, st.max_rows - 1); + const c = &h.cfg; + h.rule = .{ .gpa = gpa, .k = c.k, .prior = c.depth_prior, .most_drafts = c.most_drafts, .family_costs = &c.family_costs, .shared_costs = &c.shared_costs, .mtp_step_ms = c.mtp_step_ms, .plain_guard = c.plain_guard, .node_probabilities = false, .batch_rows = c.batch_rows }; + return h; + } + + pub fn deinit(h: *Head) void { + h.rule.deinit(); + h.cfg.deinit(h.gpa); + h.gpa.destroy(h); + } + + fn who(s: *Stream, room: i64) lanes.depth.Who { + return .{ .state = &s.state, .draft_room = room, .finished = false, .forced = false }; + } + + /// The last head round's outcome: `accepted` of its window's drafts kept now, its `ms` once the next depth is set. + pub fn observe(h: *Head, s: *Stream, accepted: u32, ms: f64) !void { + try h.price(s); + const asked = s.asked orelse return; + const held = s.held orelse return; + s.asked = null; + s.held = null; + if (held > asked or accepted > held) return; // a copy window: the core prices copies, not the head + if (held > 0) try h.rule.observeDepth(who(s, st.max_rows), held, accepted); + if (ms > 0) s.cost = .{ .held = held, .ms = ms, .first = s.first }; + } + + /// The waiting round time goes into the rule (main's order: conclude, next depth, then the round's cost). + pub fn price(h: *Head, s: *Stream) !void { + const c = s.cost orelse return; + s.cost = null; + try h.rule.observeCost(c.held, c.ms, c.first, who(s, st.max_rows)); + } + + /// The head's drafts this round: main's priced depth, within what the core asked (`asked` 0: none). + pub fn depth(h: *Head, s: *Stream, asked: u32, first: bool) !u32 { + if (asked == 0) return 0; + // the core asks min(7, room - 1), or one with a copy ahead: only 2..6 says the cache's room binds + const room: i64 = if (asked >= 2 and asked < 7) @as(i64, asked) + 1 else st.max_rows; + const d: u32 = @intCast(@max(0, try h.rule.depth(who(s, room)))); + try h.price(s); + const out = @min(asked, d); + s.asked = out; + s.first = first; + s.held = null; + return out; + } +}; + +fn testModel(costs: []const lanes.config.Cost) lanes.Model { + return .{ .exact_width = st.max_rows, .mtp = true, .speculate = true, .plain_guard = true, .drafts = 4, .window_costs = costs, .mtp_step_ms = 1.3, .depth_rate = 0.08, .hidden_rows = true, .batch_rows = st.max_rows }; +} + +fn testCosts() [st.max_rows]lanes.config.Cost { + var c: [st.max_rows]lanes.config.Cost = undefined; + for (&c, 0..) |*x, i| x.* = .{ .width = @intCast(i + 1), .ms = 13.0 + 4.1 * @as(f64, @floatFromInt(i)) }; + return c; +} + +test "the head's depth is main's: the same rule, facts and order (a round priced after the next depth) round by round" { + const gpa = std.testing.allocator; + const costs = testCosts(); + const h = try Head.init(gpa, testModel(&costs)); + defer h.deinit(); + var main_cfg = try lanes.Config.init(gpa, testModel(&costs), st.max_rows, st.max_rows - 1); + defer main_cfg.deinit(gpa); + var main_rule: lanes.depth.Rule = .{ .gpa = gpa, .k = main_cfg.k, .prior = main_cfg.depth_prior, .most_drafts = main_cfg.most_drafts, .family_costs = &main_cfg.family_costs, .shared_costs = &main_cfg.shared_costs, .mtp_step_ms = main_cfg.mtp_step_ms, .plain_guard = true, .node_probabilities = false, .batch_rows = st.max_rows }; + defer main_rule.deinit(); + var s: Stream = .{}; + defer s.deinit(gpa); + var main_state: ?lanes.depth.State = null; + defer if (main_state) |*x| x.deinit(gpa); + const mw: lanes.depth.Who = .{ .state = &main_state, .draft_room = 8, .finished = false, .forced = false }; + var prng = std.Random.DefaultPrng.init(7); + var last: Cost = undefined; + for (0..200) |i| { + const d = try h.depth(&s, 7, i == 0); + const want = try main_rule.depth(mw); + try std.testing.expectEqual(@as(u32, @intCast(want)), d); + try std.testing.expect(d <= 4); // main's facts hold four at most, not the drafter's seven + const kept: u32 = @min(d, prng.random().uintLessThan(u32, 4)); + const ms = 13.0 + 5.4 * @as(f64, @floatFromInt(d)) + 8 * prng.random().float(f64); // jittered timing + if (i > 0) try main_rule.observeCost(last.held, last.ms, last.first, mw); // main prices next depth + s.held = d; + try h.observe(&s, kept, ms); + if (d > 0) try main_rule.observeDepth(mw, d, kept); + last = .{ .held = d, .ms = ms, .first = i == 0 }; + } +} + +test "the core's ask bounds the head: none when it asks none, one when a copy is ahead" { + const gpa = std.testing.allocator; + const costs = testCosts(); + const h = try Head.init(gpa, testModel(&costs)); + defer h.deinit(); + var s: Stream = .{}; + defer s.deinit(gpa); + try std.testing.expectEqual(@as(u32, 0), try h.depth(&s, 0, false)); + try std.testing.expect(try h.depth(&s, 1, false) <= 1); + try std.testing.expect(try h.depth(&s, 7, false) >= 1); // the prior pays for a draft at these costs +} + +test "a window holding more than the head asked is a copy: it moves neither acceptance nor cost" { + const gpa = std.testing.allocator; + const costs = testCosts(); + const h = try Head.init(gpa, testModel(&costs)); + defer h.deinit(); + var s: Stream = .{}; + defer s.deinit(gpa); + _ = try h.depth(&s, 7, false); + const before = try gpa.dupe(f64, s.state.?.p); + defer gpa.free(before); + s.held = 9; + try h.observe(&s, 9, 60); + try std.testing.expectEqualSlices(f64, before, s.state.?.p); + if (s.state.?.ms) |t| try std.testing.expect(t.get(9) == null); + try std.testing.expectEqual(@as(?u32, null), s.asked); +} diff --git a/zig/src/families/glm/metal_dflash_inline.zig b/zig/src/families/glm/metal_dflash_inline.zig new file mode 100644 index 00000000000..8e8d9fffaa3 --- /dev/null +++ b/zig/src/families/glm/metal_dflash_inline.zig @@ -0,0 +1,194 @@ +//! A round's DFlash2 pass encoded in the verify window's command buffer on one Mac, one wait a round. +const std = @import("std"); +const mtl = @import("metal"); +const op = @import("../qwen27/dflash/operators.zig"); +const rounds_mod = @import("metal_dflash_rounds.zig"); +const slots_mod = @import("slots.zig"); +const ahead = @import("metal_dflash_ahead.zig"); +const same = @import("metal_dflash_same.zig"); +const follow = @import("metal_dflash_follow.zig"); +const accept = @import("metal_dflash_accept.zig"); +const max_held = rounds_mod.max_held; + +/// A stream's window the pass follows: its rounds, slot, the window's first position and its rows. +const Entry = struct { sr: *rounds_mod.StreamRounds, slot: u32 = 0, first: u64, rows: u32 }; + +/// The pass in a window's buffer, its acceptance and lattices once the window completes, until the round takes them. +pub const Inline = struct { + gpa: std.mem.Allocator, + r: *rounds_mod.Rounds, + kernel: follow.Follow, + acc: accept.Accept, + table: mtl.Buffer, // u32 offsets[8] then rows[8]: each stream's rows in the window's ids and picks + words: mtl.Buffer, // the accept kernel's two words a stream + entries: [8]Entry = undefined, + n: u32 = 0, + pass: same.Pass = undefined, + armed: bool = false, // encoded in the open window, not yet landed + ready: bool = false, // landed: `kept` and `lattices` hold the pass's + kept: [16]u32 = undefined, + lattices: [8]op.Lattice = undefined, + window: u64 = 0, // the window the pass followed (Slots.windows after it) + served: u64 = 0, + missed: u64 = 0, + + pub fn init(gpa: std.mem.Allocator, r: *rounds_mod.Rounds, device: mtl.Device) !*Inline { + const x = try gpa.create(Inline); + errdefer gpa.destroy(x); + const kernel = try follow.Follow.init(gpa, device, null); + errdefer kernel.deinit(); + const acc = try accept.Accept.init(gpa, device, null); + errdefer acc.deinit(); + const table = try device.buffer(64, mtl.ResourceOptions.shared); + errdefer table.deinit(); + x.* = .{ .gpa = gpa, .r = r, .kernel = kernel, .acc = acc, .table = table, .words = try device.buffer(64, mtl.ResourceOptions.shared) }; + return x; + } + + pub fn deinit(x: *Inline) void { + x.drop(); + x.kernel.deinit(); + x.acc.deinit(); + x.table.deinit(); + x.words.deinit(); + x.gpa.destroy(x); + } + + /// The slots' hook: the pass encoded behind each window's forward, told when the window completed. + pub fn hook(x: *Inline) slots_mod.Follow { + return .{ .ctx = x, .encode = encode, .land = land }; + } + + fn of(ctx: *anyopaque) *Inline { + return @ptrCast(@alignCast(ctx)); + } + + fn encode(ctx: *anyopaque, sl: *slots_mod.Slots, cb: mtl.CommandBuffer, e: mtl.ComputeEncoder, wins: []const slots_mod.Win) void { + const x = of(ctx); + x.drop(); + x.encodeWins(sl, cb, e, wins) catch |err| { + std.log.warn("glm drafter: the pass in the window's buffer ({s}); the round drafts as before", .{@errorName(err)}); + }; + } + + /// Every stream of the window expecting DFlash2 and caught up to it: their block pass behind its forward. + fn encodeWins(x: *Inline, sl: *slots_mod.Slots, cb: mtl.CommandBuffer, e: mtl.ComputeEncoder, wins: []const slots_mod.Win) !void { + const r = x.r; + const c = r.model.graph.config; + const n: u32 = @intCast(wins.len); + const block = r.model.blockFor(max_held); + if (wins.len == 0 or wins.len > x.entries.len or n * block > 128) return; + if (!r.expectInlineDflash(wins)) return; + var aheads: [8]ahead.Ahead = undefined; + const table = x.table.slice(u32, 16); + for (wins, 0..) |w, k| { + const slot = &sl.slots[w.slot]; + const sr = r.get(w.slot) orelse return; + if (!sr.dflash or !ahead.ready(c, sr.ctx, slot.s.pos, slot.rows)) return; + x.entries[k] = .{ .sr = sr, .slot = w.slot, .first = slot.s.pos, .rows = slot.rows }; + aheads[k] = .{ .context = sr.ctx, .first = slot.s.pos, .rows = slot.rows }; + table[k] = slot.row0; + table[8 + k] = slot.rows; + } + const m = r.model; + const epoch = try same.beginOn(m, cb, e); + errdefer same.release(m); + const ids = sl.e.sc.ids; + const picks = sl.e.sc.picks; + try x.acc.encode(e, .{ .buf = ids.buf, .off = ids.off }, .{ .buf = picks.buf, .off = picks.off }, .{ .buf = x.table }, .{ .buf = x.table, .off = 32 }, .{ .buf = x.words }, n); + e.barrier(); + x.pass = try same.encode(m, &x.kernel, epoch, aheads[0..n], block, .{ .gpu = .{ .buf = x.words } }); + x.n = n; + x.armed = true; + } + + fn land(ctx: *anyopaque, sl: *slots_mod.Slots, ok: bool) void { + const x = of(ctx); + if (!x.armed) return; + x.armed = false; + const m = x.r.model; + defer same.release(m); + if (!ok) return; + same.landed(m) catch return; + same.lattices(m, &x.pass, x.lattices[0..x.n]) catch |err| { + std.log.warn("glm drafter: the pass in the window's buffer read back ({s}); the round drafts as before", .{@errorName(err)}); + return; + }; + @memcpy(x.kept[0 .. 2 * x.n], x.words.slice(u32, 2 * x.n)); + x.ready = true; + x.window = sl.windows + 1; // the window counts itself once it has landed + } + + /// The landed pass's lattices let go. + pub fn drop(x: *Inline) void { + if (x.ready) for (x.lattices[0..x.n]) |*l| l.deinit(); + x.ready = false; + } + + /// The round's `jobs` take their chains from the landed pass when every job matches; false: fallback. + pub fn serve(x: *Inline, sl: *const slots_mod.Slots, jobs: []const rounds_mod.Job, out: []rounds_mod.Round) !bool { + defer x.drop(); + if (!x.ready or x.window != sl.windows or jobs.len == 0) return false; + var at: [8]usize = undefined; + const fits = match(x.entries[0..x.n], x.kept[0 .. 2 * x.n], x.pass.block, x.r.model, jobs, at[0..jobs.len]); + if (sl.log) std.log.info("glm inline: streams {d} served {}", .{ jobs.len, fits }); + if (!fits) { + x.missed += 1; + return false; + } + const c = x.r.model.graph.config; + for (x.entries[0..x.n], 0..) |en, k| { + if (x.r.get(en.slot)) |live| if (live == en.sr) ahead.settle(c, live.ctx, en.first, x.kept[2 * k]); + } + for (jobs, at[0..jobs.len], out[0..jobs.len]) |j, s, *o| { + const kept = x.kept[2 * s]; + j.sr.held_n = 0; + var t = try same.tree(x.r.model, &x.pass, s, x.lattices[s], kept, x.kept[2 * s + 1], .{ .nodes = @min(j.depth, max_held), .children = 1 }); + defer t.deinit(); + x.r.holdChain(j.sr, &t, j.depth, o); + } + x.served += 1; + return true; + } +}; + +/// Whether every job in `jobs` matches a stream entry's GPU acceptance and anchor within the fixed block `block`. +pub fn match(entries: []const Entry, kept: []const u32, block: u32, model: anytype, jobs: []const rounds_mod.Job, at: []usize) bool { + _ = model; + if (jobs.len == 0 or jobs.len > entries.len) return false; + for (jobs, at) |j, *a| { + const s = for (entries, 0..) |en, k| { + if (en.sr == j.sr) break k; + } else return false; + // the core kept what the GPU kept, its next anchor is the pick after them, and the fixed block covers j.depth + if (j.anchor != kept[2 * s + 1] or j.position != entries[s].first + kept[2 * s] + 2) return false; + if (j.depth == 0 or @min(j.depth, max_held) + 1 > block) return false; + a.* = s; + } + return true; +} + +test "a landed pass serves every matching job up to the fixed block, and misses on count or anchor mismatch" { + const Blocks = struct { + fn blockFor(_: @This(), nodes: u32) u32 { + return @min(16, nodes + 1); + } + }; + var srs: [2]rounds_mod.StreamRounds = undefined; + const entries = [2]Entry{ .{ .sr = &srs[0], .first = 100, .rows = 8 }, .{ .sr = &srs[1], .first = 40, .rows = 5 } }; + const kept = [4]u32{ 3, 77, 0, 9 }; + var at: [2]usize = undefined; + // the core's requests in another order: stream 1's anchor at 40 + 0 + 1, stream 0's at 100 + 3 + 1 + var jobs = [2]rounds_mod.Job{ .{ .sr = &srs[1], .position = 42, .anchor = 9, .depth = 7 }, .{ .sr = &srs[0], .position = 105, .anchor = 77, .depth = 7 } }; + try std.testing.expect(match(&entries, &kept, 8, Blocks{}, &jobs, &at)); + try std.testing.expectEqualSlices(usize, &.{ 1, 0 }, &at); + jobs[1].position = 104; // the core kept fewer (a stop or a cut) + try std.testing.expect(!match(&entries, &kept, 8, Blocks{}, &jobs, &at)); + jobs[1].position = 105; + jobs[0].anchor = 8; // another anchor + try std.testing.expect(!match(&entries, &kept, 8, Blocks{}, &jobs, &at)); + jobs[0].anchor = 9; + jobs[0].depth = 3; // fixed-block pass covers any positive depth up to 7 + try std.testing.expect(match(&entries, &kept, 8, Blocks{}, &jobs, &at)); + try std.testing.expect(match(&entries, &kept, 8, Blocks{}, jobs[0..1], at[0..1])); // subset after sibling ends +} diff --git a/zig/src/families/glm/metal_dflash_load.zig b/zig/src/families/glm/metal_dflash_load.zig new file mode 100644 index 00000000000..9d05e157656 --- /dev/null +++ b/zig/src/families/glm/metal_dflash_load.zig @@ -0,0 +1,112 @@ +//! GLM-5.3-Flash's DFlash2 drafter on Metal (--drafter): its refusals, and the drafter loaded beside the engine. +const std = @import("std"); +const Engine = @import("engine.zig").Engine; +const model_mod = @import("metal_dflash_model.zig"); +const Taps = @import("metal_dflash_taps.zig").Taps; +const Target = @import("metal_dflash_backend.zig").Target; +const rounds = @import("metal_dflash_rounds.zig"); +const st = @import("state.zig"); +const vision = @import("vision.zig"); +const mtl = @import("metal"); + +/// The flags a GLM drafter is refused beside, before any weight loads (null: none of them). +pub const Flags = struct { speed_up: bool, drafter_bits: u8 }; + +/// Why the drafter cannot open with `f`, or null when it can. +pub fn refusal(f: Flags) ?[]const u8 { + if (f.speed_up) return "GLM-5.3-Flash's DFlash2 drafter runs on one Mac: serve the --speed-up pair without --drafter"; + if (f.drafter_bits != 0 and f.drafter_bits != 4) return "--drafter-bits takes 0 (GLM-5.3-Flash's DFlash2 drafter in bf16, as published) or 4 (quantized at load)"; + return null; +} + +/// The drafter, its tap capture and the target it borrows, freed with the engine before what it borrows. +pub const Drafter = struct { + gpa: std.mem.Allocator, + model: *model_mod.Model, + taps: *Taps, + target: *Target, + + pub fn deinit(d: *Drafter) void { + const gpa = d.gpa; + d.taps.deinit(gpa); + gpa.destroy(d.taps); + d.model.deinit(); + gpa.destroy(d.target); + gpa.destroy(d); + } +}; + +/// Device bytes the drafter holds beside the weights (none without one). +pub fn heldBytes(e: *const Engine) u64 { + const d = e.dflash orelse return 0; + return d.model.bytes + d.taps.stage.length(); +} + +/// Device bytes a stream's own drafter context takes (none without a drafter). +pub fn streamBytes(e: *const Engine) u64 { + const d = e.dflash orelse return 0; + return rounds.contextBytes(d.model.graph.config); +} + +/// The DFlash2 drafter of `dir` over the loaded engine, its bytes checked against the load limit beside the weights. +pub fn load(gpa: std.mem.Allocator, io: std.Io, e: *Engine, dir: []const u8, bits: u8) !void { + const target = try gpa.create(Target); + errdefer gpa.destroy(target); + target.* = .{ .device = e.device, .queue = e.queue, .k = e.k, .w = e.w, .c = e.c }; + const m = model_mod.Model.load(gpa, io, target, dir, if (bits == 4) .q4 else .bf16) catch |err| { + std.log.err("glm drafter: the --drafter checkpoint failed to load ({s})", .{@errorName(err)}); + return err; + }; + errdefer m.deinit(); + const taps = try gpa.create(Taps); + errdefer gpa.destroy(taps); + taps.* = try Taps.init(e.device, m.pending, m.graph.config.window, m.graph.config.hidden, gpa, st.max_rows); + errdefer taps.deinit(gpa); + const drafter_bytes = m.bytes + taps.stage.length(); + const used = e.w.bytes + e.arena.bytes + drafter_bytes + vision.heldBytes(e.vision); + if (used > e.limit.bytes) { + const gb = 1e9; + std.log.err("glm drafter: the --drafter checkpoint's {d:.1} GB pass the {d:.1} GB load limit beside the weights (lower --context, or unset --drafter)", .{ @as(f64, @floatFromInt(drafter_bytes)) / gb, @as(f64, @floatFromInt(e.limit.bytes)) / gb }); + return error.OverMemoryLimit; + } + const d = try gpa.create(Drafter); + d.* = .{ .gpa = gpa, .model = m, .taps = taps, .target = target }; + e.dflash = d; +} + +/// Add all loaded drafter weights, caches and scratch buffers to the target's residency set. +pub fn joinResidency(gpa: std.mem.Allocator, e: *Engine) !void { + const d = e.dflash orelse return; + const r = &(e.residency orelse return); + var list: std.ArrayList(mtl.Buffer) = .empty; + defer list.deinit(gpa); + for (d.model.checkpoint.shards.items) |s| try list.append(gpa, s.buffer); + if (d.model.backend.copies) |*c| try c.appendBuffers(&list); + for (d.model.backend.caches) |c| try list.appendSlice(gpa, &.{ c.keys, c.values }); + for (d.model.backend.frame.pool.items) |b| try list.append(gpa, b); + try list.appendSlice(gpa, &.{ d.model.pending, d.taps.stage }); + @import("residency.zig").joinDrafter(e, list.items); + d.model.backend.frame.setResident(r.follow()); +} + +test "heldBytes and load accounting include the tap-stage buffer beside drafter model bytes" { + const device = mtl.Device.init() catch return error.SkipZigTest; + defer device.deinit(); + const ring = try device.buffer(64 * 5 * 512 * 2, mtl.ResourceOptions.shared); + defer ring.deinit(); + var taps = try Taps.init(device, ring, 64, 512, std.testing.allocator, 1); + defer taps.deinit(std.testing.allocator); + var m: model_mod.Model = undefined; + m.bytes = 1024; + var d: Drafter = .{ .gpa = std.testing.allocator, .model = &m, .taps = &taps, .target = undefined }; + var e: Engine = undefined; + e.dflash = &d; + try std.testing.expectEqual(@as(u64, 1024 + taps.stage.length()), heldBytes(&e)); +} + +test "the drafter is refused beside the pair and with bits other than 0 or 4, and opens without them" { + try std.testing.expect(refusal(.{ .speed_up = false, .drafter_bits = 0 }) == null); + try std.testing.expect(std.mem.indexOf(u8, refusal(.{ .speed_up = true, .drafter_bits = 0 }).?, "--speed-up") != null); + try std.testing.expect(refusal(.{ .speed_up = false, .drafter_bits = 4 }) == null); + try std.testing.expect(std.mem.indexOf(u8, refusal(.{ .speed_up = false, .drafter_bits = 8 }).?, "--drafter-bits") != null); +} diff --git a/zig/src/families/glm/metal_dflash_model.zig b/zig/src/families/glm/metal_dflash_model.zig new file mode 100644 index 00000000000..480f8dd5701 --- /dev/null +++ b/zig/src/families/glm/metal_dflash_model.zig @@ -0,0 +1,333 @@ +//! A native GLM draft model: incoai's drafter checkpoint, the shared frame backend and its committed context. +const std = @import("std"); +const core = @import("core"); +const mtl = @import("metal"); +const cfg = @import("../qwen27/dflash/config.zig"); +const weights = @import("metal_dflash_weights.zig"); +const draft_cfg = @import("metal_dflash_config.zig"); +const backend_mod = @import("metal_dflash_backend.zig"); +const Backend = backend_mod.Backend; +const Target = backend_mod.Target; +const Session = @import("../qwen27/dflash/session.zig").Session; +const op = @import("../qwen27/dflash/operators.zig"); +const selector = @import("../qwen27/dflash/selector.zig"); +const catchup = @import("../qwen27/dflash/catchup.zig"); +const execution = @import("../qwen27/dflash/execution.zig"); +const Cache = backend_mod.Cache; +const prepared = @import("metal_dflash_prepared.zig"); +const opts = mtl.ResourceOptions.shared | mtl.ResourceOptions.untracked; +/// --drafter-bits: 0 reads the bf16 weights as published, 4 quantizes each linear at load. +pub const Bits = enum { bf16, q4 }; +pub const max_nodes = 63; // selected tree nodes, independent of the unchanged 16-row drafter block +/// The widest tap span one catch-up frame absorbs: a whole 2,048 ring (the positions buffer's size). +const catchup_cap = 2048; +pub const Model = struct { + allocator: std.mem.Allocator, + checkpoint: core.checkpoint_metal.Checkpoint, + backend: Backend, + graph: weights.Graph, + session: Session, + preparation: op.Preparation, + tree_block: u32 = 16, + pending: mtl.Buffer, + committed_end: u64 = 0, + /// Device bytes the drafter's checkpoint buffers, caches and pending ring hold. + bytes: usize = 0, + /// The drafter of `dir`'s checkpoint against `target`'s embedding and head: bf16 as published, or 4-bit copies. + pub fn load(a: std.mem.Allocator, io: std.Io, target: *Target, dir: []const u8, bits: Bits) !*Model { + 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 draft_cfg.parse(a, text); + try draft_cfg.bind(c, .{ .hidden = target.c.hidden, .vocab = target.c.vocab, .layers = target.c.layers }); + const shards = try core.checkpoint_host.shardFiles(a, io, dir); + defer core.checkpoint_host.freeShardFiles(a, shards); + return open(a, target, c, shards, bits); + } + /// The draft model of config `c` from its checkpoint `shards`; 4-bit linears stay in the file until copied. + pub fn open(a: std.mem.Allocator, target: *Target, c: cfg.Config, shards: []const [:0]const u8, bits: Bits) !*Model { + const model = try a.create(Model); + errdefer a.destroy(model); + model.allocator = a; + model.tree_block = 16; + model.committed_end = 0; + model.checkpoint = core.checkpoint_metal.Checkpoint.init(a); + errdefer model.checkpoint.deinit(); + const later: ?core.checkpoint_metal.Later = if (bits == .q4) prepared.linear else null; + for (shards) |file| try model.checkpoint.addFileSplit(target.device, file, "", null, later); + model.backend = try Backend.init(a, target, &model.checkpoint, c); + errdefer model.backend.deinit(); + model.graph = try loadGraph(a, &model.backend); + errdefer model.graph.deinit(); + if (bits == .q4) model.backend.copies = try prepared.Copies.prepare(a, target.device, &model.checkpoint, c.linearCount()); + model.checkpoint.closeFiles(); + model.pending = try target.device.buffer(@as(usize, c.window) * c.tapWidth() * 2, opts); + errdefer model.pending.deinit(); + model.session = try Session.init(c, 1, 0); + model.preparation = if (bits == .q4) .{ .mode = .prepared_q4_reference, .quantization_verified = true, .source_sha256 = core.affine4.signature() } else .{ .mode = .bf16_reference }; + model.bytes = model.checkpointBytes() + model.pending.length() + model.backendBytes(); + return model; + } + /// Device bytes the checkpoint's loaded shard buffers hold. + fn checkpointBytes(m: *const Model) usize { + var n: usize = 0; + for (m.checkpoint.shards.items) |s| n += s.bytes; + return n; + } + /// Device bytes the drafter's caches, scratch frame and 4-bit copies hold. + fn backendBytes(m: *const Model) usize { + var n: usize = 0; + if (m.backend.copies) |c| n += c.bytes(); + for (m.backend.frame.pool.items) |b| n += b.length(); + for (m.backend.caches) |c| n += c.keys.length() + c.values.length(); + return n; + } + pub fn deinit(m: *Model) void { + m.graph.deinit(); + m.backend.deinit(); + m.pending.deinit(); + m.checkpoint.deinit(); + m.allocator.destroy(m); + } + /// The model's own taps ring gets `rows` committed rows from `taps` (the synthetic check feeds it this way). + pub fn absorb(m: *Model, taps: backend_mod.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; + const ring: @import("../qwen27/tap_ring.zig").Ring = .{ .buf = m.pending, .end = &m.committed_end, .window = m.graph.config.window, .stride = @as(usize, m.graph.config.tapWidth()) * 2 }; + try ring.absorb(taps.buf, taps.off, rows); + } + /// Every committed tap the session lacks absorbed, 128 rows a frame, from where the window still holds them. + 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); + 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; + 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)); + 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()); + 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 }); + } + } + /// Exchange the drafting state with `x` (no frame or transaction open): swap a stream in, draft, swap it back. + pub fn swap(m: *Model, x: *Context) !void { + if (m.backend.failed or m.backend.frame.active or m.backend.transaction != null or m.backend.staged != null or x.caches.len != m.backend.caches.len) return error.BadDraftContext; + std.mem.swap(mtl.Buffer, &m.pending, &x.pending); + std.mem.swap(u64, &m.committed_end, &x.committed_end); + std.mem.swap([]Cache, &m.backend.caches, &x.caches); + std.mem.swap(Session, &m.session, &x.session); + std.mem.swap(op.Context, &m.backend.context, &x.context); + } + pub fn propose(m: *Model, pending: u32, nodes: u32) !selector.Tree { + return m.proposeOptions(pending, .{ .nodes = nodes }); + } + /// A tree from the masked block after `pending`, the taps the session lacks absorbed in the same frame. + pub fn proposeOptions(m: *Model, pending: u32, options: selector.Options) !selector.Tree { + const metric = mtl.pass_metrics.phase(.drafter); + defer metric.end(); + const nodes = options.nodes; + if (m.backend.failed or m.backend.frame.active or m.backend.transaction != null or pending >= m.graph.config.vocab or nodes > max_nodes or m.tree_block == 0 or m.tree_block > 16) return error.BadDraftOptions; + 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 stride = @as(usize, m.graph.config.tapWidth()) * 2; + if (m.session.ready and m.session.context.end >= m.committed_end -| (@as(u64, window) - 1) and m.committed_end > m.session.context.end and window <= catchup_cap) { + // the whole backlog sits contiguous in the ring: absorb it and draft the block in one frame + const end = m.session.context.end; + const behind: u32 = @intCast(m.committed_end - end); + const slot: u32 = @intCast(end % window); + if (slot + behind <= window) { + var positions: [catchup_cap]u64 = undefined; + for (positions[0..behind], 0..) |*position, i| position.* = end + i; + const view = try m.backend.frame.borrow(.{ .buf = m.pending, .off = @as(usize, slot) * stride }, behind, m.graph.config.tapWidth()); + return m.session.absorbTreeBlock(m.allocator, m.backend.ops(), &m.graph, m.preparation, .{ .values = view, .positions = positions[0..behind], .layers = m.graph.config.taps, .target_end = m.committed_end }, pending, block, options); + } + } + if (catchup.fresh(m.session.ready, m.session.context.begin, m.session.context.end, m.committed_end, window)) |span| { + const rows = span.rows; + var positions: [128]u64 = undefined; + for (positions[0..rows], 0..) |*position, i| position.* = m.session.context.end + i; + const view = try m.backend.frame.borrow(.{ .buf = m.pending, .off = @as(usize, span.slot) * stride }, rows, m.graph.config.tapWidth()); + 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(); + const first = try m.session.firstDraw(); + return m.session.treeBlock(m.allocator, m.backend.ops(), &m.graph, m.preparation, pending, first, block, options); + } + /// One stream of a batched pass: its parked context (null: the model's own), pending token and tree options. + pub const Proposal = struct { context: ?*Context, pending: u32, options: selector.Options }; + + /// The block rows a stream's tree of `nodes` drafts takes: a batch's streams share one block size. + pub fn blockFor(m: *const Model, nodes: u32) u32 { + return @min(m.tree_block, nodes + 1); + } + + /// Trees for 2 to 8 streams of one block size from one frame: their new taps, then one pass over all their rows. + pub fn proposeBatch(m: *Model, entries: []const Proposal, out: []selector.Tree) !void { + return m.proposeBatchOps(m.backend.ops(), entries, out); + } + /// proposeBatch through `ops`: the backend's own, or a wrapper over them (the speed harness times each call). + pub fn proposeBatchOps(m: *Model, ops: op.Ops, entries: []const Proposal, out: []selector.Tree) !void { + const metric = mtl.pass_metrics.phase(.drafter); + defer metric.end(); + const n = entries.len; + if (n < 2 or n > 8 or out.len != n or m.backend.failed or m.backend.frame.active or m.backend.transaction != null) return error.BadDraftOptions; + const c = m.graph.config; + const block = m.blockFor(entries[0].options.nodes); + if (block < 2 or n * block > 128) return error.BadDraftOptions; + var streams: [8]execution.Stream = undefined; + var caches: [8][]Cache = undefined; + var news: [8]?Fresh = @splat(null); + for (entries, 0..) |en, k| { + if (en.pending >= c.vocab or en.options.nodes > max_nodes or m.blockFor(en.options.nodes) != block) return error.BadDraftOptions; + if (en.context) |x| try m.swap(x); + const ready = m.committed_end > 0; + news[k] = if (ready) m.fresh() else null; + const flushed: anyerror!void = if (!ready) error.DraftContextNotReady else if (news[k] == null) m.flush() else {}; + if (en.context) |x| m.swap(x) catch { + m.backend.failed = true; // the model holds this stream's context: recovery resets both + return error.DraftContextSwap; + }; + try flushed; + const current = if (en.context) |x| x.session.context else m.session.context; + streams[k] = .{ .context = if (news[k]) |f| f.next else current, .anchor = en.pending }; + caches[k] = if (en.context) |x| x.caches else m.backend.caches; + } + m.backend.batch = caches[0..n]; + m.backend.batch_block = block; + defer { + m.backend.batch = &.{}; + m.backend.batch_block = 0; + } + const frame = try ops.vtable.begin(ops.ptr); + defer ops.vtable.release(ops.ptr, frame); + try m.absorbAll(ops, frame, news[0..n]); + const absorbs: [8]?execution.Absorb = @splat(null); // absorbed above, every stream's taps in one product + var lattices: [8]op.Lattice = undefined; + try execution.absorbBlocks(ops, &m.graph, m.preparation, frame, absorbs[0..n], streams[0..n], block, lattices[0..n]); + defer for (lattices[0..n]) |*l| l.deinit(); + // the frame completed, so an absorbing stream's context now covers its new taps + for (entries, news[0..n]) |en, f| if (f) |x| { + if (en.context) |ctx| { + ctx.session.context = x.next; + ctx.session.ready = true; + ctx.context = x.next; + } else { + m.session.context = x.next; + m.session.ready = true; + m.backend.context = x.next; + } + }; + const select = mtl.pass_metrics.phase(.selector); + defer select.end(); + var made: usize = 0; + errdefer for (out[0..made]) |*t| t.deinit(); + for (entries, streams[0..n], lattices[0..n], out) |en, s2, l, *t| { + t.* = try selector.propose(m.allocator, &m.graph, l, en.pending, s2.context.end + 1, en.options); + made += 1; + } + } + /// Every stream's new taps through the fusion and each layer's keys and values, one product each, into its caches. + fn absorbAll(m: *Model, ops: op.Ops, frame: u64, news: []const ?Fresh) !void { + const c = m.graph.config; + const g = &m.graph; + var total: u32 = 0; + for (news) |f| if (f) |x| { + total += x.rows; + }; + if (total == 0) return; + const b = &m.backend; + var positions: [8 * 128]u64 = undefined; + const taps = try b.frame.alloc(total, c.tapWidth(), .bf16); + const to = try b.frame.ref(taps); + const e = try b.encoder(frame); + const stride = @as(usize, c.tapWidth()) * 2; + var at: u32 = 0; + for (news) |f| if (f) |x| { + try b.copy(e, .{ .buf = x.ring, .off = @as(usize, x.slot) * stride }, .{ .buf = to.buf, .off = to.off + @as(usize, at) * stride }, x.rows, c.tapWidth()); + for (positions[at..][0..x.rows], 0..) |*p, i| p.* = x.first + i; + at += x.rows; + }; + const pos = positions[0..total]; + const mode = m.preparation.mode; + const fusion = try ops.vtable.project(ops.ptr, frame, taps, g.fusion, mode); + const hidden = try ops.vtable.norm(ops.ptr, frame, fusion, .{ .weight = g.hidden_norm, .eps = c.eps, .heads = 1, .head_dim = c.hidden }); + for (g.layers, 0..) |layer, i| { + const raw = try ops.vtable.project(ops.ptr, frame, hidden, layer.attention.k, mode); + const normed = try ops.vtable.norm(ops.ptr, frame, raw, .{ .weight = layer.attention.k_norm, .eps = c.eps, .heads = c.kv_heads, .head_dim = c.head_dim }); + const keys = try ops.vtable.rope(ops.ptr, frame, normed, .{ .positions = pos, .heads = c.kv_heads, .dim = c.head_dim, .theta = c.theta }); + const values = try ops.vtable.project(ops.ptr, frame, hidden, layer.attention.v, mode); + var first: u32 = 0; + for (news, 0..) |f, k| if (f) |x| { + const kr = try b.frame.ref(keys); + const vr = try b.frame.ref(values); + const ks = try b.frame.add(.{ .buf = kr.buf, .off = kr.off + @as(usize, first) * keys.stride * 2 }, x.rows, keys.width, keys.stride, .bf16); + const vs = try b.frame.add(.{ .buf = vr.buf, .off = vr.off + @as(usize, first) * values.stride * 2 }, x.rows, values.width, values.stride, .bf16); + try ops.vtable.stream_append(ops.ptr, frame, @intCast(k), @intCast(i), ks, vs, pos[first..][0..x.rows]); + first += x.rows; + }; + } + } + /// 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 span = catchup.fresh(m.session.ready, m.session.context.begin, m.session.context.end, m.committed_end, m.graph.config.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 } }; + } +}; +/// A stream's own drafter state, parked while another stream drafts: its taps ring, rolling K/V and session. +pub const Context = struct { + pending: mtl.Buffer, + committed_end: u64 = 0, + caches: []Cache, + session: Session, + context: op.Context = .{ .cache = 1, .begin = 0, .end = 0 }, + + /// The stream's taps ring and every layer's rolling K/V, empty. + pub fn init(a: std.mem.Allocator, m: *const Model) !*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); + errdefer pending.deinit(); + const caches = try backend_mod.newCaches(a, device, c, c.layers); + errdefer backend_mod.freeCaches(a, caches); + x.* = .{ .pending = pending, .caches = caches, .session = try Session.init(c, 1, 0) }; + return x; + } + pub fn deinit(x: *Context, a: std.mem.Allocator) void { + backend_mod.freeCaches(a, x.caches); + x.pending.deinit(); + a.destroy(x); + } + /// Empty, starting at `at`: the parked context and its session agree there, so the swapped-in backend accepts it. + pub fn reset(x: *Context, c: cfg.Config, at: u64) !void { + x.committed_end = at; + x.session = try Session.init(c, 1, 0); + x.session.context = .{ .cache = 1, .begin = at, .end = at }; + x.session.ready = false; + x.context = x.session.context; + } +}; + +/// The drafter graph from the backend's checkpoint; the embedding record is the target's table's shape alone. +pub fn loadGraph(a: std.mem.Allocator, b: *Backend) !weights.Graph { + var names: std.ArrayList([]const u8) = .empty; + var arena = std.heap.ArenaAllocator.init(a); + defer arena.deinit(); + const local = arena.allocator(); + var iterator = b.checkpoint.tensors.keyIterator(); + while (iterator.next()) |name| try names.append(local, name.*); + var later = b.checkpoint.deferred.keyIterator(); + while (later.next()) |name| try names.append(local, name.*); + return weights.load(a, .{ .source = b.source(), .names = names.items }, b.config, weights.embedBinding(b.config)); +} diff --git a/zig/src/families/glm/metal_dflash_passes.zig b/zig/src/families/glm/metal_dflash_passes.zig new file mode 100644 index 00000000000..c7a198041dc --- /dev/null +++ b/zig/src/families/glm/metal_dflash_passes.zig @@ -0,0 +1,68 @@ +//! How a round's drafting GLM streams group into DFlash2 passes: one pass at the deepest stream's block, eight at most. +const std = @import("std"); +const st = @import("state.zig"); +const StreamRounds = @import("metal_dflash_rounds.zig").StreamRounds; + +/// A drafting stream's round to run: its rounds, committed end, anchor and the depth the core asked for. +pub const Job = struct { + sr: *StreamRounds, + position: u64, + anchor: u32, + depth: u32, + pass: u32 = 0, // the drafts its pass runs for (0: its own depth): a shared pass takes its deepest stream's + + pub fn passDepth(j: Job) u32 { + return if (j.pass > 0) j.pass else j.depth; + } +}; + +/// One pass for every drafting stream of a round: each runs at the deepest one's block, its chain cut to its own depth. +pub fn sharePass(jobs: []Job) void { + var deepest: u32 = 0; + for (jobs) |j| deepest = @max(deepest, j.depth); + if (jobs.len > 1) for (jobs) |*j| { + j.pass = deepest; + }; +} + +/// Each job's pass (one block size, at most eight jobs a pass, passes in order of their first job), and the count. +pub const Plan = struct { group: [st.max_rows]u8 = @splat(0), count: usize = 0 }; +pub fn plan(blocks: []const u32) Plan { + var p: Plan = .{}; + var block: [st.max_rows]u32 = undefined; + var size: [st.max_rows]u8 = @splat(0); + for (blocks, 0..) |b, i| { + const g = for (0..p.count) |x| { + if (block[x] == b and size[x] < 8) break x; + } else blk: { + block[p.count] = b; + p.count += 1; + break :blk p.count - 1; + }; + p.group[i] = @intCast(g); + size[g] += 1; + } + return p; +} + +test "a round's drafting streams share one pass at the deepest one's depth, each chain cut to its own" { + var jobs = [_]Job{ .{ .sr = undefined, .position = 9, .anchor = 1, .depth = 1 }, .{ .sr = undefined, .position = 9, .anchor = 1, .depth = 7 }, .{ .sr = undefined, .position = 9, .anchor = 1, .depth = 3 } }; + sharePass(&jobs); + for (jobs) |j| try std.testing.expectEqual(@as(u32, 7), j.passDepth()); + try std.testing.expectEqual(@as(u32, 1), jobs[0].depth); // its held chain stops at its own + var one = [_]Job{.{ .sr = undefined, .position = 9, .anchor = 1, .depth = 2 }}; + sharePass(&one); + try std.testing.expectEqual(@as(u32, 2), one[0].passDepth()); // a lone stream keeps its own block +} + +test "a round's passes: streams of one block size share one, at most eight, in the order of their first stream" { + const p = plan(&.{ 8, 8, 4, 8, 4, 16 }); + try std.testing.expectEqual(@as(usize, 3), p.count); + try std.testing.expectEqualSlices(u8, &.{ 0, 0, 1, 0, 1, 2 }, p.group[0..6]); + const tens: [10]u32 = @splat(8); + const many = plan(&tens); + try std.testing.expectEqual(@as(usize, 2), many.count); + for (many.group[0..8]) |g| try std.testing.expectEqual(@as(u8, 0), g); + try std.testing.expectEqual(@as(u8, 1), many.group[8]); + try std.testing.expectEqual(@as(usize, 0), plan(&.{}).count); +} diff --git a/zig/src/families/glm/metal_dflash_prepared.zig b/zig/src/families/glm/metal_dflash_prepared.zig new file mode 100644 index 00000000000..a6808006daf --- /dev/null +++ b/zig/src/families/glm/metal_dflash_prepared.zig @@ -0,0 +1,113 @@ +//! GLM's DFlash2 drafter with --drafter-bits 4: each bf16 linear quantized at load, then read only through its copy. +const std = @import("std"); +const mtl = @import("metal"); +const core = @import("core"); +const op = @import("../qwen27/dflash/operators.zig"); +const ck = @import("../qwen27/checkpoint.zig"); +const Tiled = @import("../qwen27/dflash/runtime_backend.zig").Tiled; +const simd = core.row_projection.simd; + +/// The draft's linears: its rank-2 weights, which a 4-bit drafter reads only through their prepared copies. +pub fn linear(name: []const u8, rank: usize) bool { + return rank == 2 and std.mem.endsWith(u8, name, ".weight"); +} + +/// Every linear's 4-bit copy, keyed by its bf16 view's address: lane adapters with tensor units, else SIMD tiles. +pub const Copies = struct { + gpa: std.mem.Allocator, + adapters: std.AutoHashMapUnmanaged(usize, core.affine4_lane.Adapter) = .empty, + tiled: std.AutoHashMapUnmanaged(usize, Tiled) = .empty, + simd: ?simd.Pipelines = null, + + pub fn deinit(c: *Copies) void { + var adapters = c.adapters.valueIterator(); + while (adapters.next()) |a| a.deinit(); + c.adapters.deinit(c.gpa); + var tiled = c.tiled.valueIterator(); + while (tiled.next()) |t| t.deinit(); + c.tiled.deinit(c.gpa); + if (c.simd) |*p| p.deinit(); + } + + /// Device bytes the copies hold. + pub fn bytes(c: *const Copies) usize { + var n: usize = 0; + var adapters = c.adapters.valueIterator(); + while (adapters.next()) |a| n += a.words.length() + a.metadata.length(); + var tiled = c.tiled.valueIterator(); + while (tiled.next()) |t| n += t.w.length() + t.scales.length() + t.biases.length(); + return n; + } + + pub fn appendBuffers(c: *const Copies, out: *std.ArrayList(mtl.Buffer)) !void { + var adapters = c.adapters.valueIterator(); + while (adapters.next()) |a| try out.appendSlice(c.gpa, &.{ a.words, a.metadata }); + var tiled = c.tiled.valueIterator(); + while (tiled.next()) |t| try out.appendSlice(c.gpa, &.{ t.w, t.scales, t.biases }); + } + + /// The copies of `checkpoint`'s linears, `linear_count` of them, on `device`; any other count is refused. + pub fn prepare(gpa: std.mem.Allocator, device: mtl.Device, checkpoint: *core.checkpoint_metal.Checkpoint, linear_count: usize) !Copies { + var c: Copies = .{ .gpa = gpa }; + errdefer c.deinit(); + const units = device.tensorUnits(); + const order = if (units) try core.lane_projection.RegOrder.init(device) else null; + defer if (order) |o| o.deinit(); + if (!units) c.simd = try simd.Pipelines.load(device); + var rows: std.ArrayList(u16) = .empty; + defer rows.deinit(gpa); + var kept = checkpoint.tensors.iterator(); + while (kept.next()) |entry| if (linear(entry.key_ptr.*, entry.value_ptr.rank)) { + const t = entry.value_ptr.*; + try c.one(device, order, @intFromPtr(t.buffer.contents() + t.offset), t.dtype, t.shape, t.host(u16)); + }; + var later = checkpoint.deferred.iterator(); + while (later.next()) |entry| if (linear(entry.key_ptr.*, entry.value_ptr.rank)) { + const d = entry.value_ptr.*; + try rows.resize(gpa, d.bytes / 2); + try checkpoint.read(entry.key_ptr.*, 0, std.mem.sliceAsBytes(rows.items)); + try c.one(device, order, @intFromPtr((try checkpoint.view(entry.key_ptr.*)).ptr), d.dtype, d.shape, rows.items); + }; + if ((if (units) c.adapters.count() else c.tiled.count()) != linear_count) return error.DraftTensorCoverage; + return c; + } + + /// One bf16 [n][k] linear's 4-bit copy under `key`: a lane adapter with `order`, else the same bits on tiles. + fn one(c: *Copies, device: mtl.Device, order: ?core.lane_projection.RegOrder, key: usize, dtype: core.checkpoint_metal.DType, shape: @FieldType(core.checkpoint_metal.Tensor, "shape"), rows: []const u16) !void { + if (dtype != .bf16 or shape[0] % 32 != 0 or shape[1] % 64 != 0) return error.DraftPreparationUnqualified; + var words = try core.affine4.prepare(c.gpa, rows, shape[0], shape[1]); + defer words.deinit(); + if (order) |o| { + const adapter = try core.affine4_lane.Adapter.init(c.gpa, device, words, try @import("../qwen27/projection.zig").split(shape[0], shape[1]), o); + errdefer adapter.deinit(); + if (try c.adapters.fetchPut(c.gpa, key, adapter)) |old| old.value.deinit(); + } else { + const t = try Tiled.init(device, words); + errdefer t.deinit(); + if (try c.tiled.fetchPut(c.gpa, key, t)) |old| old.value.deinit(); + } + } + + /// `x` through `w`'s copy into `y` (bf16 rows), then a barrier; a linear without one is refused. + pub fn project(c: *const Copies, e: mtl.ComputeEncoder, w: ck.Tensor, x: op.View, input: core.draft_ops.Ref, y: op.View, output: core.draft_ops.Ref) !void { + if (c.tiled.get(@intFromPtr(w.bytes.ptr))) |t| { + if (x.stride != x.width or y.stride != y.width) return error.DraftPreparationUnqualified; + simd.encode(e, try simd.call(&c.simd.?, t.n, t.k, x.rows, false, false, 0), t.matrix(), input.buf, input.off, output.buf, output.off); + } else { + const adapter = c.adapters.get(@intFromPtr(w.bytes.ptr)) orelse return error.DraftPreparationUnqualified; + // the reg kernel takes up to 128 rows (a batch's blocks) in one weight read, a row's bits the same + const most = adapter.projection.max_rows; + var first: u32 = 0; + while (first < x.rows) : (first += most) { + try adapter.encode(e, .{ .buf = input.buf, .off = input.off + @as(usize, first) * x.stride * 2 }, .{ .buf = output.buf, .off = output.off + @as(usize, first) * y.stride * 2 }, @min(x.rows - first, most)); + } + } + e.barrier(); + } +}; + +test "only rank-2 weights are linears" { + try std.testing.expect(linear("layers.0.self_attn.q_proj.weight", 2)); + try std.testing.expect(!linear("layers.0.input_layernorm.weight", 1)); + try std.testing.expect(!linear("layers.0.attention_conv.base_kernel", 3)); +} diff --git a/zig/src/families/glm/metal_dflash_rounds.zig b/zig/src/families/glm/metal_dflash_rounds.zig new file mode 100644 index 00000000000..e651008298d --- /dev/null +++ b/zig/src/families/glm/metal_dflash_rounds.zig @@ -0,0 +1,587 @@ +//! GLM's DFlash2 draft rounds on Metal: per-stream drafter contexts, chain drafts, and their chances. +const std = @import("std"); +const lanes = @import("lanes"); +const be = lanes.backend; +const st = @import("state.zig"); +const slots_mod = @import("slots.zig"); +const engine_mod = @import("engine.zig"); +const taps_mod = @import("metal_dflash_taps.zig"); +const model_mod = @import("metal_dflash_model.zig"); +const selector = @import("../qwen27/dflash/selector.zig"); +const dflash_cfg = @import("../qwen27/dflash/config.zig"); +const host = @import("backend.zig"); +const source_mod = @import("metal_dflash_source.zig"); +const head_mod = @import("metal_dflash_head_depth.zig"); +const passes_mod = @import("metal_dflash_passes.zig"); +pub const Job = passes_mod.Job; +pub const sharePass = passes_mod.sharePass; +pub const Plan = passes_mod.Plan; +pub const plan = passes_mod.plan; + +/// The MTP head's chain when a stream drafts with it here and main's rule is not loaded: main's facts' drafts. +pub const mtp_drafts = 4; + +/// A chain holds at most this many drafts: the window's last row is the verify's own pick. +pub const max_held = 7; +/// The drafter's pass, priced per draft by the depth rule. +const draft_step_ms = 1.6; + +/// Where a chain's chance product stops it when TF_GLM_DRAFT_CONFIDENCE is unset on Metal. +pub const default_confidence = 0.5; + +/// TF_GLM_DRAFT_CONFIDENCE, read once at load: where a DFlash2 chain's chance product stops it. +pub fn confidence() !f64 { + return @import("sys").environment.read(f64, "TF_GLM_DRAFT_CONFIDENCE", default_confidence); +} + +/// Device bytes one stream's drafter context holds: its taps ring plus every layer's rolling K/V. +pub fn contextBytes(c: dflash_cfg.Config) usize { + const ring = @as(usize, c.window) * c.tapWidth() * 2; + const caches = @as(usize, c.layers) * 2 * (@as(usize, c.window) + 16) * c.kvWidth() * 2; + return ring + caches; +} + +/// The best chain of `tree`: best root, then each step's best child, its own chance from the cumulative scores. +pub fn flatten(tree: *const selector.Tree, tokens: []u32, chances: []f64) u32 { + if (tree.tokens.len == 0 or tokens.len == 0 or chances.len == 0) return 0; + const depth_max = @min(@min(tokens.len, chances.len), max_held); + var parent: i32 = -1; + var above: f64 = 0; // the parent's cumulative score (the root's own chance stands alone) + var depth: u32 = 0; + while (depth < depth_max) : (depth += 1) { + var best: ?usize = null; + for (tree.parents, 0..) |p, i| { + if (p != parent) continue; + if (best == null or tree.scores[i] > tree.scores[best.?]) best = i; + } + const at = best orelse break; + tokens[depth] = tree.tokens[at]; + chances[depth] = @exp(tree.scores[at] - above); + parent = @intCast(at); + above = tree.scores[at]; + } + return depth; +} + +/// The chain the lane core sizes windows from: the first draft stands, later ones stop under the cut. +pub fn cutChances(chances: []f64, cut: f64) void { + var chain: f64 = 1; + for (chances, 0..) |*c, j| { + chain *= c.*; + if (j > 0 and chain < cut) c.* = 0; + if (c.* == 0) chain = 0; + } +} + +/// The held chain stops at the first zeroed chance: drafts past it cost verify rows with no expected gain. +pub fn pricedPrefix(chances: []const f64) u32 { + var n: usize = 0; + while (n < chances.len and chances[n] > 0) n += 1; + return @intCast(n); +} + +/// A stream's parked drafter state: its context, and the chain the last round held with its chances. +pub const StreamRounds = struct { + ctx: *model_mod.Context, + tokens: [max_held]u32 = @splat(0), + chances: [max_held]f64 = @splat(0), + held_n: u32 = 0, + dflash: bool = true, // the policy at the prompt's start: false drafts this stream with the MTP head + sampled: bool = false, + used: ?source_mod.Source = null, // the source its current round drafts with + last: u64 = 0, // host ticks at its last round's draft hook + chooser: source_mod.Chooser = .{}, // its lone rounds' source chooser + alone: bool = false, // its last round was its own, not a shared window's + plain_next: bool = false, // lone stream's next round was asked zero drafts (skip inline pass) + head: head_mod.Stream = .{}, // its MTP head rounds, priced by main's rule +}; + +const dflash_prior = [_]f64{ 0.85, 0.80, 0.80, 0.80, 0.80, 0.75, 0.70 }; + +/// Prompts past this length draft with the MTP head (the head won at 64K). +pub const default_max_ctx = 32768; + +/// Which streams DFlash2 drafts for: prompts within `max_ctx`; longer prompts use the MTP head. +pub const Policy = struct { + max_ctx: u64 = default_max_ctx, + + pub fn ok(p: Policy, len: u64) bool { + return p.max_ctx == 0 or len <= p.max_ctx; + } +}; + +/// The rounds over the slots: a stream's StreamRounds by slot, its context made at its first token. +pub const Rounds = struct { + gpa: std.mem.Allocator, + sl: *slots_mod.Slots, + model: *model_mod.Model, + taps: *taps_mod.Taps, + streams: []?*StreamRounds, + cut: f64, // TF_GLM_DRAFT_CONFIDENCE, read once at load + policy: Policy = .{}, + rule: source_mod.Rule = .{}, + head: ?*head_mod.Head = null, // main's depth rule for the MTP head's rounds (null: the head drafts mtp_drafts) + follow: ?@import("metal").ResidencySet.Follow = null, // contexts join the target residency set + inline_pass: ?*@import("metal_dflash_inline.zig").Inline = null, // same-buffer pass hook + shared: source_mod.Shared = .{}, + shared_plain: bool = false, // multi-stream round asked zero drafts across all streams (skip inline pass) + + pub fn init(gpa: std.mem.Allocator, sl: *slots_mod.Slots, model: *model_mod.Model, taps: *taps_mod.Taps) !*Rounds { + const cut = try confidence(); + const r = try gpa.create(Rounds); + errdefer gpa.destroy(r); + const streams = try gpa.alloc(?*StreamRounds, sl.slots.len); + @memset(streams, null); + r.* = .{ .gpa = gpa, .sl = sl, .model = model, .taps = taps, .streams = streams, .cut = cut }; + return r; + } + + pub fn deinit(r: *Rounds) void { + if (r.inline_pass) |x| x.deinit(); + for (r.streams) |s| if (s) |x| r.drop(x); + if (r.head) |h| h.deinit(); + r.gpa.free(r.streams); + r.gpa.destroy(r); + } + + /// The MTP head's rounds take main's depth rule from main's facts (with no drafter loaded). + pub fn priceHead(r: *Rounds, m: lanes.Model) !void { + if (r.head) |h| h.deinit(); + r.head = null; + r.head = try head_mod.Head.init(r.gpa, m); + } + + fn drop(r: *Rounds, x: *StreamRounds) void { + if (r.follow) |f| for (contextBuffers(x.ctx)) |b| f.leave(f.ctx, b); + x.head.deinit(r.gpa); + x.ctx.deinit(r.gpa); + r.gpa.destroy(x); + } + + /// The slot's rounds, or null when it has none (its stream drafts with the MTP head instead). + pub fn get(r: *const Rounds, slot: u32) ?*StreamRounds { + if (slot >= r.streams.len) return null; + return r.streams[slot]; + } + + /// The slot's rounds, making them now; on failure null (the stream keeps the MTP head). + pub fn make(r: *Rounds, slot: u32) ?*StreamRounds { + if (slot >= r.streams.len) return null; + if (r.streams[slot]) |x| return x; + const x = r.create(slot) orelse return null; + r.taps.setRoute(slot, &r.sl.slots[slot].s, x.ctx.pending); + return x; + } + + /// Every slot's rounds made at load, so their contexts are in a residency set before the first request. + pub fn prepare(r: *Rounds) void { + for (0..r.streams.len) |slot| if (r.streams[slot] == null) { + _ = r.create(@intCast(slot)); + }; + } + + /// The slot's rounds and context, made now with no tap route. + fn create(r: *Rounds, slot: u32) ?*StreamRounds { + const x = r.gpa.create(StreamRounds) catch return null; + const ctx = model_mod.Context.init(r.gpa, r.model) catch |err| { + r.gpa.destroy(x); + std.log.err("glm drafter: stream {d}'s context ({s}); it drafts with the MTP head", .{ slot, @errorName(err) }); + return null; + }; + x.* = .{ .ctx = ctx }; + r.streams[slot] = x; + if (r.follow) |f| for (contextBuffers(ctx)) |b| f.join(f.ctx, b); + return x; + } + + /// A new prompt in `slot`, `at` rows restored (a cache hit), `active` streams counted: the policy decides. + pub fn begin(r: *Rounds, slot: u32, at: u64, active: u64, sampled: bool) ?*StreamRounds { + if (active <= 1) { + r.shared.reset(); + r.shared_plain = false; + } + const x = r.make(slot) orelse return null; + x.ctx.reset(r.model.graph.config, at) catch |err| { + std.log.err("glm drafter: stream {d}'s context reset ({s}); it drafts with the MTP head", .{ slot, @errorName(err) }); + r.discard(slot); + return null; + }; + x.held_n = 0; + x.dflash = r.policy.ok(r.sl.slots[slot].prompt_len); + x.sampled = sampled; + x.used = null; + x.last = 0; + x.plain_next = false; + x.chooser = .{}; + x.head.deinit(r.gpa); + // a capped stream captures no taps: its windows launch nothing for a drafter it never uses + if (x.dflash) r.taps.setRoute(slot, &r.sl.slots[slot].s, x.ctx.pending) else r.taps.clearRoute(&r.sl.slots[slot].s); + if (!x.dflash) std.log.info("glm drafter: stream {d} drafts with the MTP head (prompt {d}, max_ctx {d})", .{ slot, r.sl.slots[slot].prompt_len, r.policy.max_ctx }); + return x; + } + + /// The slot's window verified `drafts` drafts: what the head's last round, if it drafted, is priced by. + pub fn sawWindow(r: *Rounds, slot: u32, drafts: u32) void { + const x = r.get(slot) orelse return; + if (x.head.asked != null) x.head.held = drafts; + } + + /// The MTP head's drafts for `sr`'s round: main's priced depth within the core's ask. + pub fn headDepth(r: *Rounds, sr: ?*StreamRounds, req: be.DraftRequest) !u32 { + const h = r.head orelse return @min(req.depth, mtp_drafts); + const x = sr orelse return @min(req.depth, mtp_drafts); + return h.depth(&x.head, req.depth, req.rows == null); + } + + /// The rows the next round verifies: the slot's held chain, as its priced prefix left it. + pub fn heldRows(r: *Rounds, slot: u32) ?lanes.stream.Held { + if (slot >= r.streams.len) return null; + return .{ .count = r.sl.slots[slot].held_n }; + } + + /// The slot left the rounds: its tap route goes now. + pub fn release(r: *Rounds, slot: u32) void { + if (slot >= r.streams.len) return; + if (r.streams[slot] != null) r.taps.clearRoute(&r.sl.slots[slot].s); // keep context for slot's next stream + } + + /// The slot's rounds and context freed (a context that failed to reset). + fn discard(r: *Rounds, slot: u32) void { + r.release(slot); + if (r.streams[slot]) |x| r.drop(x); + r.streams[slot] = null; + } + + /// Whether the next round for `wins` is predicted to use DFlash2, so inline encoding only runs when needed. + pub fn expectInlineDflash(r: *const Rounds, wins: []const slots_mod.Win) bool { + if (wins.len == 0) return false; + if (wins.len == 1) { + const sr = r.get(wins[0].slot) orelse return false; + return !sr.plain_next and sr.dflash and sr.chooser.peek(r.rule, true) == .dflash; + } + if (r.shared_plain) return false; + var sampled = false; + for (wins) |w| { + const sr = r.get(w.slot) orelse return false; + if (!sr.dflash) return false; + if (sr.sampled) sampled = true; + } + return r.shared.expect(source_mod.shared_rule, wins.len, sampled) == .dflash; + } + + /// The stream's round: its committed taps end at `position - 1`, then a fixed block sliced to `depth` drafts. + pub fn round(r: *Rounds, sr: *StreamRounds, position: u64, anchor: u32, depth: u32, out: *Round) !void { + sr.ctx.committed_end = position - 1; + sr.held_n = 0; + const nodes = @min(depth, max_held); + if (nodes == 0) return; + const m = r.model; + try m.swap(sr.ctx); + var tree = m.proposeOptions(anchor, .{ .nodes = max_held, .children = 1 }) catch |err| { + m.swap(sr.ctx) catch { + m.backend.failed = true; // the model holds this stream's context: recovery resets both + }; + return err; + }; + m.swap(sr.ctx) catch { + tree.deinit(); // the tree was made: it goes before the context it was made in is lost + m.backend.failed = true; + return error.DraftContextSwap; + }; + defer tree.deinit(); + r.holdChain(sr, &tree, nodes, out); + } + + /// `sr`'s held chain from `tree`: its best chain, cut by the confidence, at most `depth` drafts. + pub fn holdChain(r: *Rounds, sr: *StreamRounds, tree: *const selector.Tree, depth: u32, out: *Round) void { + out.held_n = flatten(tree, &sr.tokens, &sr.chances); + cutChances(sr.chances[0..out.held_n], r.cut); + out.held_n = @min(pricedPrefix(sr.chances[0..out.held_n]), depth); // a shared pass's block may be longer + sr.held_n = out.held_n; + @memcpy(out.tokens[0..out.held_n], sr.tokens[0..out.held_n]); + } + + /// `sr`'s source for `req`: a shared round's `window` source, else DFlash2 or its chooser (caps first). + pub fn choose(r: *Rounds, sr: *StreamRounds, req: be.DraftRequest, t: u64, window: ?source_mod.Source) !source_mod.Source { + const ms: f64 = if (sr.last > 0 and t > sr.last) @as(f64, @floatFromInt(t - sr.last)) / 24e3 else 0; + if (window == null and sr.alone) if (r.head) |h| if (req.rows != null and req.follow.len > 0) try h.observe(&sr.head, @intCast(req.follow.len - 1), ms); + if (sr.used) |u| if (window == null and sr.alone and req.rows != null and ms > 0) sr.chooser.observe(u, @floatFromInt(req.follow.len), ms); + sr.last = t; + sr.alone = window == null; + const s: source_mod.Source = if (req.rows == null or !sr.dflash) .mtp else if (window) |w| w else sr.chooser.next(r.rule, true); + sr.used = s; + return s; + } + + /// The rounds of `jobs[members]` in one fixed-block batched pass: each chain slices its requested depth. + pub fn roundBatch(r: *Rounds, jobs: []const Job, members: []const usize, out: []Round) !void { + var entries: [8]model_mod.Model.Proposal = undefined; + for (members, entries[0..members.len]) |i, *en| { + const j = jobs[i]; + j.sr.ctx.committed_end = j.position - 1; + j.sr.held_n = 0; + en.* = .{ .context = j.sr.ctx, .pending = j.anchor, .options = .{ .nodes = max_held, .children = 1 } }; + } + var trees: [8]selector.Tree = undefined; + try r.model.proposeBatch(entries[0..members.len], trees[0..members.len]); + defer for (trees[0..members.len]) |*t| t.deinit(); + for (members, trees[0..members.len]) |i, *tree| r.holdChain(jobs[i].sr, tree, jobs[i].depth, &out[i]); + } +}; + +/// A stream's context buffers a residency set holds: its taps ring and each layer's K/V (at most 8 layers). +fn contextBuffers(ctx: *const model_mod.Context) []const @import("metal").Buffer { + const S = struct { + threadlocal var list: [17]@import("metal").Buffer = undefined; + }; + S.list[0] = ctx.pending; + const n = @min(ctx.caches.len, 8); + for (ctx.caches[0..n], 0..) |c, i| { + S.list[1 + 2 * i] = c.keys; + S.list[2 + 2 * i] = c.values; + } + return S.list[0 .. 1 + 2 * n]; +} + +/// A round's result: the held chain and its chances, for the slot's held rows and the core's sizing. +pub const Round = struct { + tokens: [max_held]u32 = @splat(0), + chances: [max_held]f64 = @splat(0), + held_n: u32 = 0, +}; + +/// The backend's draft hook with the drafter loaded: each request's kept rows committed, a chain round, MTP fallback. +pub fn draft(b: *host.Backend, r_: *Rounds, requests: []const be.DraftRequest) anyerror!void { + const sl = b.sl; + var ones: [st.max_rows]u32 = undefined; // a prompt's first token, the one its head absorbs with + var mtp: [st.max_rows]slots_mod.Draft = undefined; + var mtp_n: usize = 0; + if (requests.len > st.max_rows) return error.DraftOutOfStep; + const t_enter = now(); + var t_ahead: u64 = t_enter; + var t_passes: u64 = t_enter; + defer if (sl.log) r_.model.backend.stamps.logPhases(sl.last_ret, sl.last_end, t_enter, t_ahead, t_passes, now()); + var slots: [st.max_rows]u32 = undefined; + var jobs: [st.max_rows]Job = undefined; + var job_of: [st.max_rows]?usize = @splat(null); + var job_n: usize = 0; + const window = sharedSource(b, r_, requests, t_enter); + var all_plain = window != null; + for (requests, 0..) |req, k| { + if (req.early or req.lanes != null or req.ranks) return error.TreeDraftsUnsupported; + if (req.rows) |path| { + if (path.len != req.follow.len) return error.DraftOutOfStep; + for (path, 0..) |x, j| if (x != j) return error.TreeDraftsUnsupported; + } + slots[k] = try b.slotOf(req.stream); + const sr = r_.make(slots[k]); + if (sr) |x| if (window == null) { + x.plain_next = req.depth == 0; + }; + if (req.depth > 0) all_plain = false; + const drafted = if (sr) |x| try r_.choose(x, req, t_enter, window) == .dflash else false; + if (drafted and req.depth > 0) { + const anchor = if (req.rows == null) blk: { + const f = req.first orelse return error.NoFirstToken; + ones[k] = switch (f) { + .handle => |h| try sl.ringGet(@intCast(h)), + .value => |v| v, + }; + break :blk ones[k]; + } else req.follow[req.follow.len - 1]; + jobs[job_n] = .{ .sr = sr.?, .position = req.position, .anchor = anchor, .depth = req.depth }; + job_of[k] = job_n; + job_n += 1; + } else if (sr) |x| x.ctx.committed_end = req.position - 1; + } + if (window != null) r_.shared_plain = all_plain; + // the drafting streams' rounds: those of one block size in one pass; a stream drafting nothing costs nothing + var rounds: [st.max_rows]Round = @splat(.{}); + sharePass(jobs[0..job_n]); // streams of different depths in one pass, not one pass a block size + // a pass in the window's buffer serves the round when it followed exactly these streams; else today's passes + const served = if (r_.inline_pass) |x| try x.serve(sl, jobs[0..job_n], rounds[0..job_n]) else false; + if (job_n > 0 and !served) try sl.commitAhead(); // the keeps go ahead of the drafter's frames, on the same queue + t_ahead = now(); + var blocks: [st.max_rows]u32 = undefined; + const fixed_block = r_.model.blockFor(max_held); + for (blocks[0..job_n]) |*blk| blk.* = fixed_block; + const p = if (served) Plan{} else plan(blocks[0..job_n]); + for (0..p.count) |g| { + var members: [8]usize = undefined; + var n: usize = 0; + for (p.group[0..job_n], 0..) |x, i| if (x == g) { + members[n] = i; + n += 1; + }; + if (n == 1) { + const j = jobs[members[0]]; + try r_.round(j.sr, j.position, j.anchor, j.depth, &rounds[members[0]]); + } else try r_.roundBatch(jobs[0..job_n], members[0..n], rounds[0..job_n]); + } + if (p.count > 0) t_passes = now(); + for (requests, 0..) |req, k| { + const round = if (job_of[k]) |i| rounds[i] else Round{}; + const drafted = if (r_.get(slots[k])) |x| x.used == .dflash else false; + const slot_ref = &sl.slots[slots[k]]; + slot_ref.held_n = round.held_n; + if (round.held_n > 0) @memcpy(engine_mod.Engine.u32s(slot_ref.held, round.held_n), round.tokens[0..round.held_n]); + if (!drafted or round.held_n == 0) { + // clear stale DFlash2 chances on MTP or plain rounds so one low pick cannot freeze later rounds + req.stream.draft_chances.clearRetainingCapacity(); + req.stream.draft_chances_cut = null; + } + if (!drafted) { // no DFlash2 for this stream: its MTP head takes this round's shape + const follow: []const u32 = if (req.rows == null) blk: { + const f = req.first orelse return error.NoFirstToken; + ones[k] = switch (f) { + .handle => |h| try sl.ringGet(@intCast(h)), + .value => |v| v, + }; + break :blk ones[k .. k + 1]; + } else req.follow; + const d = if (window == null) try r_.headDepth(r_.get(slots[k]), req) else @min(req.depth, mtp_drafts); + mtp[mtp_n] = .{ .slot = slots[k], .prompt = req.rows == null, .follow = follow, .depth = d }; + mtp_n += 1; + } + // GLM_WINDOWS: the round's source, the tokens its stream's last round gained, the drafts it now holds or asks + if (sl.log) std.log.info("glm round: slot {d} source {s} gained {d} drafts {d}", .{ slots[k], if (drafted) "dflash" else "mtp", req.follow.len, if (drafted) round.held_n else mtp[mtp_n - 1].depth }); + } + if (mtp_n == 0) return; + try sl.checkDrafts(mtp[0..mtp_n]); + try sl.draftAll(mtp[0..mtp_n]); +} + +fn now() u64 { + return @import("sys").c.mach_absolute_time(); +} + +/// Observe shared-window yield per stream and pick `.dflash` or `.mtp` for multi-stream rounds. +fn sharedSource(b: *host.Backend, r_: *Rounds, requests: []const be.DraftRequest, t: u64) ?source_mod.Source { + if (requests.len <= 1) return null; + var eligible: usize = 0; + var decode_n: usize = 0; + var sum_tokens: usize = 0; + var sampled = false; + for (requests) |req| { + if (req.stream.sampling != null) sampled = true; + const sr = r_.get(b.slotOf(req.stream) catch continue) orelse continue; + if (!sr.dflash) continue; + eligible += 1; + if (req.rows != null) { + decode_n += 1; + sum_tokens += req.follow.len; + } + } + return if (eligible == 0) .mtp else r_.shared.step(source_mod.shared_rule, requests.len, eligible, decode_n, sum_tokens, sampled, t); +} + +/// The lane core's facts with the drafter loaded: chains of up to `max_held` drafts priced by their chances. +pub fn facts(b: *const host.Backend) lanes.Model { + const single = b.sl.e.ep == null; + return .{ + // shared_price fits per-row slope across DFlash2 and MTP without charging a fixed block penalty to MTP + .fixed_draft_block = false, + .allocate_shared_drafts = true, + .limit_shared_drafts = false, + .exact_width = st.max_rows, + .first_copy_rows = 4, + .mtp = true, // the drafter is the draft head: the lane core asks it for drafts + .speculate = true, + .speculate_early = false, + .plain_guard = true, + .drafts = max_held, + .draft_prior = &dflash_prior, + // the verify is the MTP head's forward: its one-Mac windows and shared forwards, learned where the head's are + .learn_row_costs = single and !b.sl.e.device.tensorUnits(), + .window_costs = &host.one_mac_window_costs, + .shared_costs = if (single) &host.one_mac_shared_costs else &.{}, + .mtp_step_ms = draft_step_ms / @as(f64, max_held), + .shared_step_ms = 0, + .depth_rate = host.depth_rate, + .streams_exact = true, + .hidden_rows = true, + .batch_rows = st.max_rows, + .max_streams = @intCast(b.sl.slots.len), + .draft_streams = true, + .draft_probabilities = true, + .gpu_tokens = single, // main's: a stream drafting nothing runs one-token rounds queued ahead + }; +} + +/// The core's chances hook: each held draft's chance of landing, its ancestors' chained. +pub fn chancesFor(r_: *Rounds, slot: u32, out: []f64) bool { + const sr = r_.get(slot) orelse return false; + if (sr.used != .dflash or sr.held_n == 0) return false; + const n = @min(out.len, sr.held_n); + var chain: f64 = 1; // a draft lands only if every one before it does: the selector's chances chained + for (out[0..n], sr.chances[0..n]) |*c, p| { + chain *= p; + c.* = chain; + } + for (out[n..]) |*c| c.* = 0; + return true; +} + +test "chain flatten takes the best root and best children, chances are the per-step own" { + const a = std.testing.allocator; + const tokens = [_]u32{ 3, 8, 8, 8, 8, 8, 8, 8, 8 }; + const parents = [_]i32{ -1, 0, 0, 0, 1, 1, 2, 2, 2 }; + const scores = [_]f64{ -0.5, -0.7, -1.4, -3.0, -0.9, -1.1, -1.5, -1.6, -2.5 }; + const tree: selector.Tree = .{ .gpa = a, .tokens = @constCast(&tokens), .parents = @constCast(&parents), .scores = @constCast(&scores) }; + var chain: [7]u32 = undefined; + var chances: [7]f64 = undefined; + const n = flatten(&tree, &chain, &chances); + try std.testing.expectEqual(@as(u32, 3), n); + try std.testing.expectEqual(@as(u32, 3), chain[0]); // root, then its best child, then that child's + try std.testing.expectEqual(@as(u32, 8), chain[1]); + try std.testing.expectEqual(@as(u32, 8), chain[2]); + try std.testing.expectApproxEqAbs(@exp(-0.5), chances[0], 1e-9); + try std.testing.expectApproxEqAbs(@exp(-0.2), chances[1], 1e-9); + try std.testing.expectApproxEqAbs(@exp(-0.2), chances[2], 1e-9); // node 4's own step, from -0.7 to -0.9 +} + +test "chain flatten stops where the tree has no child at the chain's depth" { + const a = std.testing.allocator; + const tokens = [_]u32{ 5, 6 }; + const parents = [_]i32{ -1, 0 }; + const scores = [_]f64{ -0.3, -0.4 }; + const tree: selector.Tree = .{ .gpa = a, .tokens = @constCast(&tokens), .parents = @constCast(&parents), .scores = @constCast(&scores) }; + var chain: [7]u32 = undefined; + var chances: [7]f64 = undefined; + try std.testing.expectEqual(@as(u32, 2), flatten(&tree, &chain, &chances)); +} + +test "the cut keeps the first draft always, later ones stop where the product falls under" { + var chances = [_]f64{ 0.9, 0.9, 0.9, 0.9 }; + cutChances(&chances, 0.7); // the products 0.9, 0.81, 0.729, 0.6561: only the fourth's own chance zeroes + try std.testing.expectEqual(@as(f64, 0.9), chances[0]); + try std.testing.expectEqual(@as(f64, 0.9), chances[1]); + try std.testing.expectEqual(@as(f64, 0.9), chances[2]); + try std.testing.expectEqual(@as(f64, 0), chances[3]); +} + +test "the held chain is the priced prefix: it stops at the first chance the cut zeroed" { + var chances = [_]f64{ 0.9, 0.9, 0.9, 0.9, 0.9 }; + cutChances(&chances, 0.7); + try std.testing.expectEqual(@as(u32, 3), pricedPrefix(&chances)); + try std.testing.expectEqual(@as(u32, 0), pricedPrefix(&.{})); + try std.testing.expectEqual(@as(u32, 2), pricedPrefix(&.{ 0.5, 0.4 })); +} + +test "a tiny first chance still keeps one draft, the rest stop" { + var chances = [_]f64{ 0.1, 0.9, 0.9 }; + cutChances(&chances, 0.7); + try std.testing.expectEqual(@as(f64, 0.1), chances[0]); + try std.testing.expectEqual(@as(f64, 0), chances[1]); + try std.testing.expectEqual(@as(f64, 0), chances[2]); +} + +test "the confidence cut reads TF_GLM_DRAFT_CONFIDENCE, its default without it" { + try std.testing.expectApproxEqAbs(@as(f64, default_confidence), try confidence(), 1e-9); +} + +comptime { + _ = st; + _ = engine_mod; + _ = dflash_cfg; +} diff --git a/zig/src/families/glm/metal_dflash_same.zig b/zig/src/families/glm/metal_dflash_same.zig new file mode 100644 index 00000000000..fef82f6bbea --- /dev/null +++ b/zig/src/families/glm/metal_dflash_same.zig @@ -0,0 +1,119 @@ +//! A DFlash2 pass that follows a window on the GPU: its rows absorbed ahead, its block from the window's acceptance. +const std = @import("std"); +const mtl = @import("metal"); +const op = @import("../qwen27/dflash/operators.zig"); +const execution = @import("../qwen27/dflash/execution.zig"); +const selector = @import("../qwen27/dflash/selector.zig"); +const model_mod = @import("metal_dflash_model.zig"); +const Model = model_mod.Model; +const ahead = @import("metal_dflash_ahead.zig"); +const follow = @import("metal_dflash_follow.zig"); +const backend_mod = @import("metal_dflash_backend.zig"); +const ring = @import("metal_dflash_context.zig").ring; + +/// Where the block's acceptance comes from: the accept kernel's words on the GPU, or the host's (the checks' plan). +pub const Source = union(enum) { gpu: follow.Ref, host: []const u32 }; + +/// An encoded pass, read once its frame's last buffer completes. +pub const Pass = struct { + streams: u32, + block: u32, + plan: follow.Plan, + head: op.Head, + projected: op.View, + topk: op.View, + windows: [8]follow.Window = undefined, +}; + +/// The streams' window rows absorbed ahead, then their blocks planned at their longest contexts, into `frame`. +pub fn encode(m: *Model, kernel: *const follow.Follow, frame: u64, aheads: []const ahead.Ahead, block: u32, src: Source) !Pass { + const b = &m.backend; + const c = m.graph.config; + const n: u32 = @intCast(aheads.len); + if (n == 0 or n > 8 or b.follow != null or n * block > 128) return error.BadDraftOptions; + var caches: [8][]backend_mod.Cache = undefined; + var windows: [8]follow.Window = undefined; + var streams: [8]execution.Stream = undefined; + for (aheads, 0..) |x, k| { + caches[k] = x.context.caches; + windows[k] = .{ .begin = x.context.session.context.begin, .first = x.first, .rows = x.rows }; + streams[k] = .{ .context = x.context.session.context, .anchor = 0 }; // read anchors from follow buffers + } + const p = try follow.plan(c, windows[0..n], block, ring(c)); + b.batch = caches[0..n]; + b.batch_block = if (n > 1) block else 0; + defer { + b.batch = &.{}; + b.batch_block = 0; + b.follow = null; + } + try ahead.absorb(m, frame, aheads); + const rows = p.args.rows; + const ids = try b.frame.ref(try b.frame.alloc(rows, 1, .u32)); + const positions = try b.frame.ref(try b.frame.alloc(rows, 1, .u64)); + const mask = try b.frame.ref(try b.frame.alloc(rows, p.args.mask_stride, .u8)); + switch (src) { + .gpu => |accepted| { + const e = try b.encoder(frame); + try kernel.encode(e, p, accepted, .{ .buf = ids.buf, .off = ids.off }, .{ .buf = positions.buf, .off = positions.off }, .{ .buf = mask.buf, .off = mask.off }); + e.barrier(); + }, + .host => |accepted| { + if (accepted.len != 2 * n) return error.BadDraftOptions; + const at = struct { + fn of(comptime T: type, r: backend_mod.Ref, count: usize) []T { + return @as([*]T, @ptrCast(@alignCast(r.buf.contents() + r.off)))[0..count]; + } + }.of; + follow.fill(p, accepted, at(u32, ids, rows), at(u64, positions, rows), at(u8, mask, @as(usize, rows) * p.args.mask_stride)); + }, + } + b.follow = .{ .ids = ids, .positions = positions, .mask = mask, .keys = p.keys, .streams = n, .mask_stride = p.args.mask_stride }; + const output = try execution.encodeStreams(b.ops(), &m.graph, m.preparation, streams[0..n], frame, block, &.{}); + b.follow = null; + const topk = try backend_mod.encodeTopk(b, frame, output.head, c.topk); + return .{ .streams = n, .block = block, .plan = p, .head = output.head, .projected = output.projected, .topk = topk, .windows = windows }; +} + +/// A completed pass's lattices, one a stream, in the order its windows were given. +pub fn lattices(m: *Model, pass: *const Pass, out: []op.Lattice) !void { + if (out.len != pass.streams) return error.BadDraftOptions; + try backend_mod.readLattices(&m.backend, pass.head, pass.topk, pass.projected, m.graph.config, pass.block, out); + for (out) |l| try l.check(m.graph.config); +} + +/// Stream `k`'s tree from its lattice, its window having kept `kept` drafts and drawn `anchor`. +pub fn tree(m: *Model, pass: *const Pass, k: usize, lattice: op.Lattice, kept: u32, anchor: u32, options: selector.Options) !selector.Tree { + const end = pass.windows[k].first + kept + 1; + return selector.propose(m.allocator, &m.graph, lattice, anchor, end + 1, options); +} + +/// A frame on a target window's open buffer and encoder: the pass encodes behind its work and commits nothing. +pub fn beginOn(m: *Model, cb: mtl.CommandBuffer, e: mtl.ComputeEncoder) !u64 { + if (m.backend.failed) return error.DraftBackendFailed; + return m.backend.frame.beginOn(cb, e); +} + +/// The window's buffer completed: the pass's lattices are readable until `release`. +pub fn landed(m: *Model) !void { + try m.backend.frame.landed(); +} + +/// Encode then wait in a frame of the pass's own (the checks' entry); `release` lets the frame go once it is read. +pub fn run(m: *Model, kernel: *const follow.Follow, aheads: []const ahead.Ahead, block: u32, src: Source) !Pass { + const ops = m.backend.ops(); + const frame = try ops.vtable.begin(ops.ptr); + errdefer ops.vtable.release(ops.ptr, frame); + const pass = try encode(m, kernel, frame, aheads, block, src); + m.backend.frame.finish() catch |err| { + m.backend.failed = true; + return err; + }; + return pass; +} + +/// The pass's frame let go: its lattices are read. +pub fn release(m: *Model) void { + const ops = m.backend.ops(); + ops.vtable.release(ops.ptr, m.backend.frame.epoch); +} diff --git a/zig/src/families/glm/metal_dflash_source.zig b/zig/src/families/glm/metal_dflash_source.zig new file mode 100644 index 00000000000..3613a9f2e88 --- /dev/null +++ b/zig/src/families/glm/metal_dflash_source.zig @@ -0,0 +1,335 @@ +//! Which draft source a GLM stream's next round uses: DFlash2 or the MTP head, by each one's measured tokens a ms. +const std = @import("std"); + +pub const Source = enum { dflash, mtp }; + +/// The rule's constants: DFlash2 rounds before the first choice, the tokens a round that keep it, probes, averaging. +pub const Rule = struct { + first_dflash: u32 = 8, // DFlash2 rounds a stream runs before its first choice + keep_tokens: f64 = 2.3, // DFlash2 stays, unprobed, at this many tokens a round times its rounds' ms over the head's + probe_mtp: u32 = 5, // MTP head rounds that settle a choice the drafter's tokens did not + probe_every: u32 = 128, // rounds between probes of the head while on DFlash2 + back_every: u32 = 64, // rounds between probes of DFlash2 while on the head + probe_len: u32 = 2, + watch: u32 = 8, // the latest rounds each source's yield averages (at most `Yield.most`) + reprobe_margin: f64 = 1.0, // periodic probe back from MTP to DFlash2 must beat MTP by this ratio +}; + +/// Multi-stream shared rounds settle faster on workload changes and avoid noisy re-probes back into DFlash2. +pub const shared_rule: Rule = .{ + .first_dflash = 4, + .probe_mtp = 4, + .back_every = 256, + .watch = 6, + .reprobe_margin = 1.05, +}; + +/// A source's latest rounds: tokens (kept drafts and the verify's own) and ms, the newest `most` of them. +pub const Yield = struct { + pub const most = 16; + tokens: [most]f64 = @splat(0), + ms: [most]f64 = @splat(0), + n: u32 = 0, + + pub fn add(y: *Yield, tokens: f64, ms: f64) void { + y.tokens[y.n % most] = tokens; + y.ms[y.n % most] = ms; + y.n += 1; + } + + fn sum(xs: *const [most]f64, n: u32, k: u32) f64 { + var total: f64 = 0; + var i: u32 = 0; + while (i < @min(k, @min(n, most))) : (i += 1) total += xs[(n - 1 - i) % most]; + return total; + } + + /// Tokens a round over the latest `k` rounds (0 before any). + pub fn perRound(y: *const Yield, k: u32) f64 { + const c = @min(k, @min(y.n, most)); + return if (c == 0) 0 else sum(&y.tokens, y.n, k) / @as(f64, @floatFromInt(c)); + } + + /// Ms a round over the latest `k` rounds (0 before any). + pub fn msRound(y: *const Yield, k: u32) f64 { + const c = @min(k, @min(y.n, most)); + return if (c == 0) 0 else sum(&y.ms, y.n, k) / @as(f64, @floatFromInt(c)); + } + + /// Tokens a ms over the latest `k` rounds (0 before any). + pub fn perMs(y: *const Yield, k: u32) f64 { + const ms = sum(&y.ms, y.n, k); + return if (ms <= 0) 0 else sum(&y.tokens, y.n, k) / ms; + } +}; + +fn other(s: Source) Source { + return if (s == .dflash) .mtp else .dflash; +} + +/// One stream's choice: DFlash2 first, kept on its own tokens a round, else settled by a short MTP probe. +pub const Chooser = struct { + current: Source = .dflash, + yields: [2]Yield = .{ .{}, .{} }, + chosen: bool = false, + probed: bool = false, // the first choice's MTP probe ran + since: u32 = 0, // rounds on `current` since the last probe ended + probing: u32 = 0, // probe rounds still to run on `probe` + probe: Source = .mtp, + settle: bool = false, // a probe just ended: its rounds decide before the next round + + /// The round that ran on `used` gained `tokens` (its kept drafts and the verify's own) in `ms` of wall time. + pub fn observe(c: *Chooser, used: Source, tokens: f64, ms: f64) void { + if (ms <= 0) return; + c.yields[@backingInt(used)].add(tokens, ms); + } + + fn y(c: *const Chooser, s: Source) *const Yield { + return &c.yields[@backingInt(s)]; + } + + /// DFlash2's tokens a round over `k` rounds clear the bar its rounds' extra time sets (none without head rounds). + fn drafterKeeps(c: *const Chooser, rule: Rule, k: u32) bool { + const d = c.y(.dflash); + const m = c.y(.mtp); + if (m.n == 0 or m.msRound(rule.watch) <= 0) return false; + return d.perRound(k) >= rule.keep_tokens * d.msRound(rule.watch) / m.msRound(rule.watch); + } + + fn probeOf(c: *Chooser, s: Source, rounds: u32) Source { + c.probe = s; + c.probing = rounds -| 1; + c.settle = true; + return s; + } + + /// What `next` will return when a round finishes without mutating the chooser state. + pub fn peek(c: *const Chooser, rule: Rule, dflash_ok: bool) Source { + if (!dflash_ok) return .mtp; + if (c.probing > 0) return c.probe; + if (!c.chosen) { + if (c.y(.dflash).n < rule.first_dflash) return .dflash; + if (!c.probed and !c.drafterKeeps(rule, rule.first_dflash)) return .mtp; + const d = c.y(.dflash); + const m = c.y(.mtp); + const cur: Source = if (!c.probed or d.perMs(rule.watch) >= m.perMs(rule.watch)) .dflash else .mtp; + return if (rule.probe_len > 0 and c.since + 1 >= (if (cur == .mtp) rule.back_every else rule.probe_every)) other(cur) else cur; + } + var cur = c.current; + if (c.settle) { + if (c.probe == .dflash and c.y(.dflash).perMs(rule.probe_len) > c.y(.mtp).perMs(rule.watch) * rule.reprobe_margin) cur = .dflash; + if (c.probe == .mtp and c.y(.mtp).perMs(rule.probe_len) > c.y(.dflash).perMs(rule.watch)) cur = .mtp; + } + if (cur == .dflash and c.since >= rule.watch and c.y(.mtp).n >= rule.probe_len and c.y(.dflash).n >= rule.watch and c.y(.mtp).perMs(rule.watch) > c.y(.dflash).perMs(rule.watch)) cur = .mtp; + if (c.since + 1 >= (if (cur == .mtp) rule.back_every else rule.probe_every) and rule.probe_len > 0) return other(cur); + return cur; + } + + /// The source the stream's next round uses. `dflash_ok`: the caps let it draft with DFlash2 at all. + pub fn next(c: *Chooser, rule: Rule, dflash_ok: bool) Source { + if (!dflash_ok) return .mtp; + if (c.probing > 0) { + c.probing -= 1; + return c.probe; + } + const d = c.y(.dflash); + const m = c.y(.mtp); + if (!c.chosen) { + if (d.n < rule.first_dflash) return .dflash; + if (!c.probed and !c.drafterKeeps(rule, rule.first_dflash)) { + c.probed = true; + return c.probeOf(.mtp, rule.probe_mtp); + } + c.chosen = true; + c.settle = false; + c.current = if (!c.probed or d.perMs(rule.watch) >= m.perMs(rule.watch)) .dflash else .mtp; + } + if (c.settle) { // a periodic probe ended: the source that yielded more tokens a ms takes the rounds + c.settle = false; + if (c.probe == .dflash and d.perMs(rule.probe_len) > m.perMs(rule.watch) * rule.reprobe_margin) c.current = .dflash; + if (c.probe == .mtp and m.perMs(rule.probe_len) > d.perMs(rule.watch)) c.current = .mtp; + } + if (c.current == .dflash and c.since >= rule.watch and m.n >= rule.probe_len and d.n >= rule.watch and m.perMs(rule.watch) > d.perMs(rule.watch)) c.current = .mtp; + c.since += 1; + if (c.since >= (if (c.current == .mtp) rule.back_every else rule.probe_every) and rule.probe_len > 0) { + c.since = 0; + return c.probeOf(other(c.current), rule.probe_len); + } + return c.current; + } +}; + +/// Multi-stream shared window source tracker, keyed by stream count (sampled shared rounds use MTP). +pub const Shared = struct { + choosers: [16]Chooser = @splat(.{}), + last: u64 = 0, + used: ?Source = null, + bucket: usize = 0, + n: usize = 0, + + pub fn reset(s: *Shared) void { + s.* = .{}; + } + + pub fn expect(s: *const Shared, rule: Rule, streams: usize, sampled: bool) Source { + if (sampled) return .mtp; + const b = @min(streams - 1, s.choosers.len - 1); + return s.choosers[b].peek(rule, true); + } + + pub fn step(s: *Shared, rule: Rule, streams: usize, eligible: usize, decode_n: usize, tokens: usize, sampled: bool, t: u64) Source { + if (sampled) { + s.used = .mtp; + s.last = 0; + return .mtp; + } + const b = @min(streams - 1, s.choosers.len - 1); + if (decode_n == eligible and s.used != null and s.last > 0 and t > s.last and + s.bucket == b and s.n == eligible) + { + const ms = @as(f64, @floatFromInt(t - s.last)) / 24e3; + const nf: f64 = @floatFromInt(eligible); + s.choosers[b].observe(s.used.?, @as(f64, @floatFromInt(tokens)) / nf, ms / nf); + } + const chosen: Source = if (decode_n == 0) .mtp else if (decode_n == eligible) + s.choosers[b].next(rule, true) + else + s.choosers[b].peek(rule, true); + s.used = chosen; + s.last = if (decode_n == eligible or decode_n == 0) t else 0; + s.bucket = b; + s.n = eligible; + return chosen; + } +}; + +/// A stream's sources yield `tokens` a round in `ms` (dflash, mtp), its first round on the head: the sources used. +fn run(rule: Rule, ok: bool, tokens: [2]u32, ms: [2]f64, rounds: usize, out: []Source) void { + var c: Chooser = .{}; + for (out[0..rounds], 0..) |*s, i| { + s.* = if (i == 0) .mtp else c.next(rule, ok); + c.observe(s.*, @floatFromInt(tokens[@backingInt(s.*)]), ms[@backingInt(s.*)]); + } +} + +fn count(xs: []const Source, s: Source) usize { + var n: usize = 0; + for (xs) |x| n += @intFromBool(x == s); + return n; +} + +test "a chat-like stream (the drafter's rounds cost more than they gain) moves to the MTP head within its first probe" { + var used: [130]Source = undefined; + run(.{}, true, .{ 2, 2 }, .{ 32.3, 24.7 }, 130, &used); // tokens a round 2.4 and 2.0 in the cells, rounded + try std.testing.expect(count(used[0..20], .dflash) <= 9); + try std.testing.expect(count(used[20..], .dflash) <= 2 * (110 / 64 + 1)); // only the periodic probes return +} + +test "a code-like stream keeps DFlash2 without an MTP probe, the head only in its rare probes" { + var used: [100]Source = undefined; + run(.{}, true, .{ 5, 2 }, .{ 43.7, 26.9 }, 100, &used); + try std.testing.expectEqual(@as(usize, 1), count(&used, .mtp)); // the prompt's first round: no probe within 128 + try std.testing.expectEqual(Source.dflash, used[99]); +} + +test "a sampled code stream that leaves DFlash2 on a poor start returns at its next probe, not never" { + var c: Chooser = .{}; + const rule = Rule{}; + var on_dflash: usize = 0; + var dflash_rounds: usize = 0; + for (0..200) |i| { + const s = if (i == 0) Source.mtp else c.next(rule, true); + dflash_rounds += @intFromBool(s == .dflash); + const tokens: u32 = if (s == .mtp) 2 else if (dflash_rounds <= 8) 1 else 4; // eight poor drafter rounds + c.observe(s, @floatFromInt(tokens), if (s == .mtp) 27.1 else 40.5); + if (i >= 100 and s == .dflash) on_dflash += 1; + } + try std.testing.expect(on_dflash >= 90); +} + +test "a stream on the MTP head returns to DFlash2 when a probe finds the drafter's tokens again" { + var c: Chooser = .{}; + const rule = Rule{}; + var on_dflash: usize = 0; + for (0..400) |i| { + const s = if (i == 0) Source.mtp else c.next(rule, true); + const code = i >= 150; + const tokens: u32 = if (s == .mtp) 2 else if (code) 5 else 2; + c.observe(s, @floatFromInt(tokens), if (s == .mtp) 24.7 else 32.3); + if (i >= 300 and s == .dflash) on_dflash += 1; + } + try std.testing.expect(on_dflash >= 90); +} + +test "a stream on DFlash2 leaves it when the head out-yields it over the watched rounds" { + var c: Chooser = .{}; + const rule = Rule{}; + var on_mtp: usize = 0; + for (0..400) |i| { + const s = if (i == 0) Source.mtp else c.next(rule, true); + const tokens: u32 = if (s == .mtp) 2 else if (i < 150) 5 else 2; + c.observe(s, @floatFromInt(tokens), if (s == .mtp) 24.7 else 32.3); + if (i >= 300 and s == .mtp) on_mtp += 1; + } + try std.testing.expect(on_mtp >= 90); +} + +test "dflash_ok false keeps a stream on the MTP head regardless of yield" { + var used: [64]Source = undefined; + run(.{}, false, .{ 9, 1 }, .{ 30, 30 }, 64, &used); + try std.testing.expectEqual(@as(usize, 64), count(&used, .mtp)); +} + +test "shared window chooser adapts per stream count and resets on new burst" { + var s: Shared = .{}; + const rule = Rule{}; + try std.testing.expectEqual(Source.mtp, s.expect(rule, 3, true)); + try std.testing.expectEqual(Source.mtp, s.step(rule, 3, 3, 0, 0, true, 24000)); + var mtp_rounds: usize = 0; + var t: u64 = 48000; + for (0..30) |i| { + const dt: u64 = if (s.used == .mtp) 24000 * 40 else 24000 * 60; + t += dt; + const src = if (i == 0) s.step(rule, 3, 3, 0, 0, false, t) else s.step(rule, 3, 3, 3, 6, false, t); + if (i > 0 and src == .mtp) mtp_rounds += 1; + if (i > rule.first_dflash + rule.probe_mtp + 2) try std.testing.expectEqual(src, s.expect(rule, 3, false)); + } + try std.testing.expect(mtp_rounds > 0); + try std.testing.expectEqual(Source.mtp, s.expect(rule, 3, true)); + try std.testing.expectEqual(Source.mtp, s.step(rule, 3, 3, 3, 6, true, t + 24000)); + s.reset(); + try std.testing.expectEqual(Source.dflash, s.expect(rule, 3, false)); +} + +test "a source's yield averages its latest rounds only" { + var y: Yield = .{}; + for (0..20) |_| y.add(1, 10); + for (0..4) |_| y.add(5, 10); + try std.testing.expectApproxEqAbs(@as(f64, 5), y.perRound(4), 1e-9); + try std.testing.expectApproxEqAbs(@as(f64, 2), y.perRound(16), 1e-9); // 4 x 5 and 12 x 1 over 16 + try std.testing.expectApproxEqAbs(@as(f64, 0.2), y.perMs(16), 1e-9); +} + +test "shared_rule switches to MTP after 4 losing DFlash2 rounds and reprobe_margin suppresses noisy switches" { + var used: [32]Source = undefined; + run(shared_rule, true, .{ 1, 1 }, .{ 35.0, 19.2 }, 32, &used); + try std.testing.expectEqual(@as(usize, 4), count(used[1..], .dflash)); + try std.testing.expectEqual(Source.mtp, used[31]); + var c: Chooser = .{}; + for (0..10) |_| { + _ = c.next(shared_rule, true); + c.observe(.dflash, 1.0, 35.0); + c.observe(.mtp, 1.0, 19.2); + } + var back: usize = 0; + for (0..shared_rule.back_every + 4) |_| { + const s = c.next(shared_rule, true); + if (s == .dflash) { + back += 1; + // Marginally above 1.0x (19.0 vs 19.2 -> 1.01x) does not clear reprobe_margin (1.05x). + c.observe(.dflash, 1.0, 19.0); + } else c.observe(.mtp, 1.0, 19.2); + } + try std.testing.expectEqual(@as(usize, shared_rule.probe_len), back); + try std.testing.expectEqual(Source.mtp, c.current); +} diff --git a/zig/src/families/glm/metal_dflash_taps.zig b/zig/src/families/glm/metal_dflash_taps.zig new file mode 100644 index 00000000000..798cd48cdd9 --- /dev/null +++ b/zig/src/families/glm/metal_dflash_taps.zig @@ -0,0 +1,126 @@ +//! Capture GLM-5.3-Flash's DFlash2 drafter taps during the target's Metal forward, opt-in. +const std = @import("std"); +const mtl = @import("metal"); +const fwd = @import("forward.zig"); +const st = @import("state.zig"); +const wts = @import("weights.zig"); +const draft = @import("metal_dflash_config.zig"); + +/// A tap capture writes selected layer residuals into the drafter's ring-shaped pending buffer; null disables it. +pub const Taps = struct { + layers: [5]u32 = draft.tap_ids, + ring: mtl.Buffer, + window: u32, + hidden: u32, + /// Scratch [window][hidden] bf16 for stream_mean output before scattering into the strided ring. + stage: mtl.Buffer, + /// Each drafting stream's own ring and state: a shared window's seg rows capture into their stream's. + routes: []Route = &.{}, + + /// One stream's route: the target state identifying it, and the ring its taps land in. + pub const Route = struct { + s: ?*const st.State, + ring: mtl.Buffer, + }; + + /// A capture over `ring` (the drafter's pending buffer), one row per window slot, with `streams` per-stream routes. + pub fn init(device: mtl.Device, ring: mtl.Buffer, window: u32, hidden: u32, gpa: std.mem.Allocator, streams: usize) !Taps { + const stage = try device.buffer(@as(usize, window) * hidden * 2, mtl.ResourceOptions.shared | mtl.ResourceOptions.untracked); + errdefer stage.deinit(); + const routes = try gpa.alloc(Route, streams); + @memset(routes, .{ .s = null, .ring = ring }); + return .{ + .ring = ring, + .window = window, + .hidden = hidden, + .stage = stage, + .routes = routes, + }; + } + + /// Byte offset of plane i for position `pos` in the ring, or null if `layer` is not tapped. + pub fn offset(t: *const Taps, layer: usize, pos: u32) ?usize { + const i = t.index(layer) orelse return null; + const slot: usize = @intCast(pos % t.window); + return slot * t.stride() + i * t.hidden * 2; + } + + /// After layer `layer`, the streams' mean of rows pos..pos+rows into plane i; a shared seg to its own ring. + pub fn after(t: *const Taps, x: *fwd.Ctx, e: mtl.ComputeEncoder, layer: usize, rows: u32, pos: u32) void { + const i = t.index(layer) orelse return; + if (x.segs.len == 0) { + const ring = t.ringFor(x.s) orelse return; // a stream with no route (capped, or drafting with the head) + t.route(x, e, ring, x.sc.x[x.xi], rows, pos, i); + return; + } + for (x.segs) |seg| { + const ring = t.routeRing(seg.s) orelse continue; + const src = wts.Ref{ .buf = x.sc.x[x.xi].buf, .off = x.sc.x[x.xi].off + @as(usize, seg.row0) * x.c.hidden * 8 }; + t.route(x, e, ring, src, seg.rows, seg.pos, i); + } + } + + /// A lone stream's ring: the shared one when no stream is routed (one drafter context), else its route's or none. + pub fn ringFor(t: *const Taps, s: ?*const st.State) ?mtl.Buffer { + if (t.routes.len == 0) return t.ring; + return t.routeRing(s); + } + + /// The stream's routed ring, or null when it drafts no chain (its seg is skipped). + pub fn routeRing(t: *const Taps, s: ?*const st.State) ?mtl.Buffer { + for (t.routes) |rt| if (rt.s == s) return rt.ring; + return null; + } + + /// The streams scratch's mean over `rows` from `pos`, scattered into `ring`'s plane `i` (null: t.ring). + fn route(t: *const Taps, x: *fwd.Ctx, e: mtl.ComputeEncoder, ring: ?mtl.Buffer, src: wts.Ref, rows: u32, pos: u32, i: usize) void { + const D = t.hidden; + const n = @min(rows, t.window); + const skip = rows - n; + e.setPipeline(x.k.stream_mean); + fwd.bind(e, 0, .{ src.at(@as(usize, skip) * 4 * D * 2), .{ .buf = t.stage, .off = 0 } }); + e.setValue([2]u32{ D, n }, 2); + e.dispatchThreads(fwd.size(D, n, 1), fwd.size(256, 1, 1)); + const words = D / 2; + e.setPipeline(x.k.copy_u32); + const dst = ring orelse t.ring; + for (0..n) |r| { + const slot: u32 = @intCast((pos + skip + r) % t.window); + const dst_off = @as(usize, slot) * t.stride() + @as(usize, i) * D * 2; + fwd.bind(e, 0, .{ .{ .buf = t.stage, .off = r * D * 2 }, .{ .buf = dst, .off = dst_off } }); + e.setValue(words, 2); + e.dispatchThreads(fwd.size(words, 1, 1), fwd.size(256, 1, 1)); + } + } + + pub fn stride(t: *const Taps) usize { + return @as(usize, t.layers.len) * t.hidden * 2; + } + + /// The stream's route into its own ring (null: no ring, its seg rows are skipped). + pub fn setRoute(t: *Taps, slot: usize, s: *const st.State, ring: mtl.Buffer) void { + if (slot >= t.routes.len) return; + t.routes[slot] = .{ .s = s, .ring = ring }; + } + + /// The stream's route gone: its rows capture into nothing. + pub fn clearRoute(t: *Taps, s: *const st.State) void { + for (t.routes) |*rt| { + if (rt.s != s) continue; + rt.s = null; + } + } + + /// The routes and the stage scratch go; the caller frees its ring. + pub fn deinit(t: *Taps, gpa: std.mem.Allocator) void { + gpa.free(t.routes); + t.stage.deinit(); + t.routes = &.{}; + } + + fn index(t: *const Taps, layer: usize) ?usize { + const li: u32 = @intCast(layer); + for (t.layers, 0..) |tap, i| if (tap == li) return i; + return null; + } +}; diff --git a/zig/src/families/glm/metal_dflash_topk.zig b/zig/src/families/glm/metal_dflash_topk.zig new file mode 100644 index 00000000000..389620f938c --- /dev/null +++ b/zig/src/families/glm/metal_dflash_topk.zig @@ -0,0 +1,67 @@ +//! GLM's DFlash2 drafter top-k (glm_draft_topk.metal): core bf16_topk's rows, bytes and all, a threadgroup a row. +const std = @import("std"); +const mtl = @import("metal"); +const sources = @import("kernel_sources"); +const contract = @import("core").bf16_topk_gpu.contract; + +/// Threads a row's threadgroup (GLM_THREADS) and the entries a row holds (GLM_MAX_K, core's max_k). +pub const threads = 512; +comptime { + if (contract.max_k != 16) @compileError("glm_draft_topk.metal's GLM_MAX_K is core bf16_topk's max_k"); +} + +pub const Ref = struct { buf: mtl.Buffer, off: usize = 0 }; + +/// Rows a launch takes: a batched pass's streams' blocks (eight of 16 rows), not only core's 16. +pub const max_rows = 128; + +/// Rows this kernel takes: core's checks but its row count, a vocabulary of at least k, 16-bit counters' bins. +pub fn takes(p: contract.Params) bool { + var one = p; + one.rows = @min(p.rows, contract.max_rows); + contract.check(one) catch return false; + return p.rows <= max_rows and p.vocab >= p.k and p.vocab / (threads / 32) < 0x10000; +} + +pub const TopK = struct { + pipe: mtl.Pipeline, + + /// `edit` replaces one text of the source (a contract control's planted fault), else null. + pub fn init(a: std.mem.Allocator, device: mtl.Device, edit: ?[2][]const u8) !TopK { + const text = if (edit) |x| blk: { + if (std.mem.indexOf(u8, sources.glm_draft_topk, x[0]) == null) return error.ControlEditMissing; + break :blk try std.mem.replaceOwned(u8, a, sources.glm_draft_topk, x[0], x[1]); + } else try a.dupe(u8, sources.glm_draft_topk); + defer a.free(text); + const lib = try mtl.Library.fromSource(device, text, mtl.CompileOptions.mlx()); + defer lib.deinit(); + const pipe = try mtl.Pipeline.init(device, lib, "glm_draft_topk", false); + errdefer pipe.deinit(); + if (pipe.maxThreads() < threads or pipe.simdWidth() != 32) return error.UnsupportedDraftTopK; + return .{ .pipe = pipe }; + } + + pub fn deinit(t: TopK) void { + t.pipe.deinit(); + } + + /// Each row's top k of bf16 `logits` into `output`'s rows, as core's tf_bf16_topk writes them. + pub fn encode(t: TopK, e: mtl.ComputeEncoder, logits: Ref, output: Ref, p: contract.Params) !void { + if (!takes(p)) return error.BadTopKShape; + const cells = @as(usize, p.rows - 1) * p.stride + p.vocab; + if (logits.off % 2 != 0 or logits.off + cells * 2 > logits.buf.length() or output.off % 4 != 0 or output.off + @as(usize, p.rows) * @sizeOf(contract.Row) > output.buf.length()) return error.BadTopKBuffer; + e.setPipeline(t.pipe); + e.setBuffer(logits.buf, logits.off, 0); + e.setBuffer(output.buf, output.off, 1); + e.setValue(p, 2); + e.dispatchGroups(mtl.Size.of(p.rows, 1, 1), mtl.Size.of(threads, 1, 1)); + } +}; + +test "the drafter's rows and a batch's fit; small, oversized or too many rows go back to core" { + try std.testing.expect(takes(.{ .rows = 15, .vocab = 154880, .k = 16, .stride = 154880 })); + try std.testing.expect(takes(.{ .rows = 48, .vocab = 154880, .k = 16, .stride = 154880 })); + try std.testing.expect(!takes(.{ .rows = 129, .vocab = 154880, .k = 16, .stride = 154880 })); + try std.testing.expect(!takes(.{ .rows = 15, .vocab = 8, .k = 16, .stride = 8 })); + try std.testing.expect(!takes(.{ .rows = 1, .vocab = 2_000_000, .k = 16, .stride = 2_000_000 })); +} diff --git a/zig/src/families/glm/metal_dflash_weights.zig b/zig/src/families/glm/metal_dflash_weights.zig new file mode 100644 index 00000000000..0e1b38d9d7e --- /dev/null +++ b/zig/src/families/glm/metal_dflash_weights.zig @@ -0,0 +1,166 @@ +//! GLM's DFlash2 drafter graph: incoai's tensor names and shapes, borrowed BF16, the target's embedding read elsewhere. +const std = @import("std"); +const ck = @import("../qwen27/checkpoint.zig"); +const shared = @import("../qwen27/dflash/weights.zig"); +const Config = @import("../qwen27/dflash/config.zig").Config; + +pub const Tensor = shared.Tensor; +pub const Layer = shared.Layer; +pub const Graph = shared.Graph; +pub const Inventory = shared.Inventory; +pub const names = shared.names; +pub const freeNames = shared.freeNames; + +/// The graph's embedding record: the GLM backend reads the target's own affine, so this carries the shape alone. +pub fn embedBinding(c: Config) ck.Linear { + return .{ .dense = .{ .dtype = .bf16, .rank = 2, .shape = .{ c.vocab, c.hidden, 1, 1, 1 }, .bytes = &.{} } }; +} + +fn inventory(gpa: std.mem.Allocator, list: []const []const u8, c: Config) !void { + const expected = try names(gpa, c); + defer freeNames(gpa, expected); + if (list.len != expected.len) return error.DraftTensorCoverage; + var seen = std.StringHashMap(void).init(gpa); + defer seen.deinit(); + for (list) |name| { + if ((try seen.getOrPut(name)).found_existing) return error.DraftTensorCoverage; + var found = false; + for (expected) |wanted| if (std.mem.eql(u8, wanted, name)) { + found = true; + break; + }; + if (!found) return error.DraftTensorCoverage; + } +} + +fn get(src: ck.Source, name: []const u8, dims: []const usize) !Tensor { + const t = try src.get(name); + if (t.dtype != .bf16) return error.DraftNativeDType; + try ck.shape(t, dims); + return t; +} + +fn layerTensor(src: ck.Source, i: usize, suffix: []const u8, dims: []const usize) !Tensor { + var name: [160]u8 = undefined; + return get(src, try std.fmt.bufPrint(&name, "layers.{d}.{s}", .{ i, suffix }), dims); +} + +/// The embedding record names the target's table; its bytes belong to the target, so only its shape is checked. +fn embedShape(p: ck.Linear, c: Config) !void { + switch (p) { + .dense => |t| { + if (t.rank != 2 or t.shape[0] != c.vocab or t.shape[1] != c.hidden) return error.TargetBinding; + }, + .quantized => return error.TargetBinding, + } +} + +/// incoai's drafter graph from `source`, whose tensors are borrowed BF16 views of the drafter's checkpoint. +pub fn load(gpa: std.mem.Allocator, source: Inventory, c: Config, embed: ck.Linear) !Graph { + try c.check(); + try inventory(gpa, source.names, c); + try embedShape(embed, c); + const src = source.source; + const layers = try gpa.alloc(Layer, c.layers); + errdefer gpa.free(layers); + 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 = .{ .projection = try layerTensor(src, i, "attention_conv.kernel_projection.weight", &.{ c.dynamicWidth(), c.hidden }), .base = try layerTensor(src, i, "attention_conv.base_kernel", &.{ 2, 2, c.hidden }) }, + .mlp_conv = .{ .projection = try layerTensor(src, i, "mlp_conv.kernel_projection.weight", &.{ c.dynamicWidth(), c.hidden }), .base = try layerTensor(src, i, "mlp_conv.base_kernel", &.{ 2, 2, c.hidden }) }, + }; + 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 }; +} + +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, .target_layers = 45, .taps = @import("metal_dflash_config.zig").stock.taps, .tap_count = 5 }; + +const Store = struct { + arena: std.heap.ArenaAllocator, + keys: [][]const u8, + tensors: []Tensor, + fn init(gpa: std.mem.Allocator) !Store { + var s = Store{ .arena = std.heap.ArenaAllocator.init(gpa), .keys = undefined, .tensors = undefined }; + errdefer s.deinit(); + const a = s.arena.allocator(); + s.keys = try names(a, toy); + s.tensors = try a.alloc(Tensor, s.keys.len); + for (s.keys, s.tensors) |name, *t| { + const shape = dims(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 }; + } + return s; + } + fn deinit(s: *Store) void { + s.arena.deinit(); + } + fn graph(s: *Store, gpa: std.mem.Allocator) !Graph { + return load(gpa, .{ .source = .{ .ptr = s, .getFn = read }, .names = s.keys }, toy, embedBinding(toy)); + } + fn read(ptr: *anyopaque, name: []const u8) !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) struct { values: @FieldType(Tensor, "shape"), rank: usize } { + 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 }; + } +}; + +test "incoai's names and shapes load as one borrowed BF16 graph" { + const a = std.testing.allocator; + var s = try Store.init(a); + defer s.deinit(); + var g = try s.graph(a); + defer g.deinit(); + try std.testing.expectEqual(@as(usize, 81), s.keys.len); + try std.testing.expectEqual(s.tensors[0].bytes.ptr, g.fusion.bytes.ptr); + try std.testing.expect(try g.nativeBytes() > 0); +} + +test "a missing, duplicated or foreign tensor name is refused before any weight is read" { + const a = std.testing.allocator; + var s = try Store.init(a); + defer s.deinit(); + const previous = s.keys[0]; + s.keys[0] = s.keys[1]; + defer s.keys[0] = previous; + try std.testing.expectError(error.DraftTensorCoverage, s.graph(a)); +} + +test "a tensor of another dtype or shape cannot be cast into the graph" { + const a = std.testing.allocator; + var s = try Store.init(a); + defer s.deinit(); + s.tensors[0].dtype = .f16; + try std.testing.expectError(error.DraftNativeDType, s.graph(a)); + s.tensors[0].dtype = .bf16; + s.tensors[0].shape[1] -= 1; + try std.testing.expectError(error.ProjectionShape, s.graph(a)); +} + +test "an embedding record of another vocabulary or width is refused by the target binding" { + const a = std.testing.allocator; + var s = try Store.init(a); + defer s.deinit(); + var wide = embedBinding(toy); + wide.dense.shape[0] += 1; + try std.testing.expectError(error.TargetBinding, load(a, .{ .source = .{ .ptr = &s, .getFn = Store.read }, .names = s.keys }, toy, wide)); + try std.testing.expectError(error.TargetBinding, load(a, .{ .source = .{ .ptr = &s, .getFn = Store.read }, .names = s.keys }, toy, .{ .quantized = undefined })); +} diff --git a/zig/src/families/glm/prompt.zig b/zig/src/families/glm/prompt.zig index a8fa3df9931..c5444c56219 100644 --- a/zig/src/families/glm/prompt.zig +++ b/zig/src/families/glm/prompt.zig @@ -534,6 +534,7 @@ pub fn backbone(p: *const Prompt, x: *fwd.Ctx, e: mtl.ComputeEncoder, ids: Ref, const L = &x.w.layers[li]; const hcs = L.hc.?; if (s & Class.hc == 0) fwd.boundary(x, e, M, pending, hcs[0], L.in_norm); + if (x.taps) |t| if (li > 0) t.after(x, e, li - 1, M, pos); fwd.snap(x, e, ss.normed, plane); switch (L.attn) { .kda => |*a| { diff --git a/zig/src/families/glm/residency.zig b/zig/src/families/glm/residency.zig index 5eb617d2bb2..9f6ed92fa03 100644 --- a/zig/src/families/glm/residency.zig +++ b/zig/src/families/glm/residency.zig @@ -36,7 +36,13 @@ fn skipped(err: anyerror) void { pub fn drop(e: *Engine) void { e.arena.follow = null; + if (e.dflash) |d| d.model.backend.frame.residency = null; if (e.residency) |*r| r.deinit(); e.residency = null; e.keepalive_target = .{ .queue = e.queue }; } + +/// Add `d`'s weights and model scratch buffers into `e`'s active residency set (`e.residency`). +pub fn joinDrafter(e: *Engine, list: []const mtl.Buffer) void { + if (e.residency) |*r| _ = r.tryAddNow(list); +} diff --git a/zig/src/families/glm/slots.zig b/zig/src/families/glm/slots.zig index 2d62ebec41f..498894344c2 100644 --- a/zig/src/families/glm/slots.zig +++ b/zig/src/families/glm/slots.zig @@ -19,6 +19,12 @@ const ring_len = 64; /// One stream's rows in a shared window: its pending token, then the drafts the slot holds, then host drafts. pub const Win = struct { slot: u32, pending: u32, held: u32, tokens: []const u32 }; +/// A pass encoded in each window's buffer behind its forward, and told whether that buffer completed. +pub const Follow = struct { + ctx: *anyopaque, + encode: *const fn (*anyopaque, *Slots, mtl.CommandBuffer, mtl.ComputeEncoder, []const Win) void, + land: *const fn (*anyopaque, *Slots, bool) void, +}; /// One stream's head: it absorbs the prompt's last row or the last window's first rows (a next token each), drafts. pub const Draft = struct { slot: u32, prompt: bool, follow: []const u32, depth: u32 }; @@ -54,6 +60,7 @@ pub const Slots = struct { picks: Ref, // u32 [max_rows]: a draft level's picks, a stream each open: ?Open = null, // keeps and drafts encode here; the next window commits them with its forward windows: u64 = 0, + follow: ?Follow = null, // the drafter's same-buffer pass behind each verify window log: bool = false, // GLM_WINDOWS=1: each window's streams, rows, GPU time and the GPU's idle gap before it last_end: f64 = 0, last_ret: u64 = 0, // when the last window's wait returned (host clock ticks) @@ -137,6 +144,11 @@ pub const Slots = struct { return sl.flushBy(false); } + /// The open buffer committed without a wait, ahead of a drafter that reads what it wrote; the next one reaps it. + pub fn commitAhead(sl: *Slots) !void { + try sl.launch(); + } + /// flush; `spin`: the host spins on the buffer's status (Engine.finishBy). fn flushBy(sl: *Slots, spin: bool) !void { const o = sl.open orelse return sl.land(); @@ -301,12 +313,17 @@ pub const Slots = struct { x.segs = segs[0..wins.len]; fwd.backbone(&x, enc, e.sc.ids, total, segs[0].pos); fwd.head(&x, enc, e.sc.hidden, e.sc.logits, e.sc.picks, total); + if (sl.follow) |f| f.encode(f.ctx, sl, sl.open.?.cb, enc, wins); sl.ahead = .{ 0, 0 }; - try sl.flushBy(true); + const waited = sl.flushBy(true); + if (sl.follow) |f| f.land(f.ctx, sl, if (waited) |_| true else |_| false); + try waited; const ret = platform.c.mach_absolute_time(); if (sl.log) { const first = if (sl.ahead[1] > 0) sl.ahead[0] else e.gpu[0]; - std.log.info("glm window: streams {d} rows {d} gpu {d:.2} ms gap {d:.2} ms ahead {d:.2} join {d:.3} host {d:.2} encode {d:.2} ms", .{ wins.len, total, (e.gpu[1] - e.gpu[0]) * 1e3, (first - sl.last_end) * 1e3, (sl.ahead[1] - sl.ahead[0]) * 1e3, if (sl.ahead[1] > 0) (e.gpu[0] - sl.ahead[1]) * 1e3 else 0, @as(f64, @floatFromInt(t_in -| sl.last_ret)) / 24e3, @as(f64, @floatFromInt(e.committed - t_in)) / 24e3 }); + // start: commit to GPU start; seen: GPU end to the host seeing it (GPU times are host-clock seconds) + const s_of = @as(f64, @floatFromInt(e.committed)) / 24e6; + std.log.info("glm window: streams {d} rows {d} gpu {d:.2} ms gap {d:.2} ms ahead {d:.2} join {d:.3} host {d:.2} encode {d:.2} ms start {d:.3} seen {d:.3} ms", .{ wins.len, total, (e.gpu[1] - e.gpu[0]) * 1e3, (first - sl.last_end) * 1e3, (sl.ahead[1] - sl.ahead[0]) * 1e3, if (sl.ahead[1] > 0) (e.gpu[0] - sl.ahead[1]) * 1e3 else 0, @as(f64, @floatFromInt(t_in -| sl.last_ret)) / 24e3, @as(f64, @floatFromInt(e.committed - t_in)) / 24e3, (e.gpu[0] - s_of) * 1e3, (@as(f64, @floatFromInt(ret)) / 24e6 - e.gpu[1]) * 1e3 }); } sl.last_ret = ret; sl.last_end = e.gpu[1]; diff --git a/zig/src/families/hy4_flash/bf16_rows.zig b/zig/src/families/hy4_flash/bf16_rows.zig new file mode 100644 index 00000000000..147f14adc54 --- /dev/null +++ b/zig/src/families/hy4_flash/bf16_rows.zig @@ -0,0 +1,333 @@ +//! Local BF16 Engram reader: 192-byte safetensors rows, aligned O_DIRECT extents, no fallback or decode. + +const std = @import("std"); +const builtin = @import("builtin"); +const linux = std.os.linux; +const engram = @import("engram.zig"); + +/// Logical block size an O_DIRECT read must align its offset, length and buffer to. +pub const alignment = 4096; +/// One embedding row: 96 BF16 values, as safetensors lays them out. +pub const row_bytes = 192; +pub const width = row_bytes / 2; +/// A header larger than this is refused before allocating memory for it. +pub const max_header_bytes = 16 * 1024 * 1024; + +/// A positioned read with a caller context; `sysPread` supplies it, fixtures inject a recording one. +pub const Pread = *const fn (ctx: *anyopaque, fd: linux.fd_t, buf: [*]u8, len: usize, off: i64) usize; + +pub const Error = std.mem.Allocator.Error || error{ + BadTable, // geometry, safetensors header or row width is not the BF16 table + MissingTensor, // the named tensor is not in the safetensors header + OpenFailed, // O_DIRECT open refused (never a buffered retry) + StatFailed, + ReadFailed, // pread failed, including O_DIRECT EINVAL (never a buffered retry) + ShortRow, // a selected row extends past end of file (truncated data) + BadOutput, // caller's output has the wrong length + RowCountMismatch, // the table's rows are not the count the config implies for this layer +}; + +/// File geometry a plan builds against; `data_start` (row 0) may be unaligned, extents are not. +pub const Geometry = struct { + fd: linux.fd_t, + size: u64, + data_start: u64, + count: u64, + ctx: *anyopaque = undefined, + read: Pread, + + /// Validate `row` and return its (possibly unaligned) file offset. + pub fn rowOffset(self: Geometry, row: u32) Error!u64 { + if (row >= self.count) return error.BadTable; + const begin = std.math.add(u64, self.data_start, std.math.mul(u64, row, row_bytes) catch return error.BadTable) catch return error.BadTable; + if (begin + row_bytes > self.size) return error.ShortRow; + return begin; + } +}; + +/// One merged extent: aligned file `[off, off+len)` into the arena at aligned `at`. +pub const Extent = struct { + off: u64, + len: usize, + at: usize, + first: usize = 0, + count: usize = 0, +}; + +/// A reusable read plan for one batch of windows: build once, execute as often as needed. +pub const Plan = struct { + /// Selected table row for each output, in token/head order. + rows: []u32, + /// Arena byte offset of each output's 192 bytes, in token/head order. + at: []usize, + /// Aligned, sorted, merged reads to issue. + ext: []Extent, + /// Padded length of the 4 KiB-aligned arena. + arena_len: usize = 0, + + pub fn deinit(self: *Plan, a: std.mem.Allocator) void { + a.free(self.rows); + a.free(self.at); + a.free(self.ext); + self.* = undefined; + } +}; + +const Pick = struct { off: u64, out: usize }; + +fn lessPick(_: void, x: Pick, y: Pick) bool { + return if (x.off != y.off) x.off < y.off else x.out < y.out; +} + +/// Hash windows into rows, then build sorted, merged, aligned extents; deterministic. +pub fn buildPlan(a: std.mem.Allocator, g: Geometry, map: engram.TokenMap, hash: engram.Layer, windows: []const [engram.order]u32) Error!Plan { + const outputs = std.math.mul(usize, windows.len, engram.columns) catch return error.BadTable; + var rows = try a.alloc(u32, outputs); + errdefer a.free(rows); + var at = try a.alloc(usize, outputs); + errdefer a.free(at); + var picks: std.ArrayList(Pick) = .empty; + defer picks.deinit(a); + try picks.ensureTotalCapacity(a, outputs); + + for (windows, 0..) |window, token| { + for (hash.hash(map, window), 0..) |row, head| { + const out = token * engram.columns + head; + rows[out] = row; + const off = try g.rowOffset(row); + picks.appendAssumeCapacity(.{ .off = off, .out = out }); + } + } + std.mem.sort(Pick, picks.items, {}, lessPick); + + var ext: std.ArrayList(Extent) = .empty; + errdefer ext.deinit(a); + var arena: usize = 0; + for (picks.items) |p| { + const lo = std.mem.alignBackward(u64, p.off, alignment); + const hi = std.mem.alignForward(u64, p.off + row_bytes, alignment); + if (ext.items.len > 0) { + const last = &ext.items[ext.items.len - 1]; + if (lo <= last.off + last.len) { + const end = @max(last.off + last.len, hi); + arena += @intCast(end - (last.off + last.len)); + last.len = @intCast(end - last.off); + last.count += 1; + at[p.out] = last.at + @as(usize, @intCast(p.off - last.off)); + continue; + } + } + const len: usize = @intCast(hi - lo); + // `lo` and `hi` are aligned, so `arena` stays 4 KiB-aligned. + try ext.append(a, .{ .off = lo, .len = len, .at = arena, .first = p.out, .count = 1 }); + at[p.out] = arena + @as(usize, @intCast(p.off - lo)); + arena += len; + } + return .{ + .rows = rows, + .at = at, + .ext = try ext.toOwnedSlice(a), + .arena_len = arena, + }; +} + +/// One aligned O_DIRECT read: EINVAL is fatal (no fallback), EOF short reads are accepted. +fn readExtent(g: Geometry, buf: []align(alignment) u8, off: u64, len: usize) Error!void { + const want: usize = @intCast(@min(@as(u64, len), g.size - off)); + var done: usize = 0; + while (done < want) { + const at = std.mem.alignBackward(usize, done, alignment); + const ask = len - at; // len is a multiple of alignment + const rc = g.read(g.ctx, g.fd, buf.ptr + at, ask, @intCast(off + at)); + switch (linux.errno(rc)) { + .SUCCESS => {}, + .INTR => continue, + else => return error.ReadFailed, + } + if (rc == 0) return error.ShortRow; + const next = at + @as(usize, @intCast(rc)); + if (next <= done) return error.ShortRow; + done = next; + } +} + +/// Execute `plan` into raw BF16 words `[token][head][width]`, in that order. +pub fn execute(a: std.mem.Allocator, g: Geometry, plan: Plan, output: []u16) Error!void { + if (output.len != plan.rows.len * width) return error.BadOutput; + if (plan.rows.len == 0) return; + const arena = try a.alignedAlloc(u8, .fromByteUnits(alignment), plan.arena_len); + defer a.free(arena); + try readRows(g, plan, output, arena); +} + +fn readRows(g: Geometry, plan: Plan, output: []u16, arena: []align(alignment) u8) Error!void { + for (plan.ext) |e| { + const buf: []align(alignment) u8 = @alignCast(arena[e.at..][0..e.len]); + try readExtent(g, buf, e.off, e.len); + } + // Little-endian host: copying bytes preserves each BF16 bit pattern. + for (plan.at, 0..) |src, i| { + @memcpy(std.mem.asBytes(output[i * width ..][0..width]), arena[src..][0..row_bytes]); + } +} + +/// In-flight direct read; keep the plan, file, and destination alive through deinit. +pub const Prefetch = struct { + arena: []align(alignment) u8, + future: std.Io.Future(Error!void), + + pub fn start(a: std.mem.Allocator, io: std.Io, g: Geometry, plan: Plan, output: []u16) !Prefetch { + if (output.len != plan.rows.len * width) return error.BadOutput; + const arena = try a.alignedAlloc(u8, .fromByteUnits(alignment), plan.arena_len); + errdefer a.free(arena); + return .{ .arena = arena, .future = try io.concurrent(readRows, .{ g, plan, output, arena }) }; + } + + pub fn finish(self: *Prefetch, io: std.Io) Error!void { + try self.future.await(io); + } + + pub fn deinit(self: *Prefetch, a: std.mem.Allocator, io: std.Io) void { + self.finish(io) catch {}; + a.free(self.arena); + self.* = undefined; + } +}; + +/// Batch read: hash the windows, plan once, then gather their 192-byte rows. +pub fn gatherRows(a: std.mem.Allocator, g: Geometry, map: engram.TokenMap, hash: engram.Layer, windows: []const [engram.order]u32, output: []u16) Error!void { + var plan = try buildPlan(a, g, map, hash, windows); + defer plan.deinit(a); + try execute(a, g, plan, output); +} + +pub fn tokenElements() usize { + return engram.columns * width; +} + +/// Production wrapper: geometry plus the released vocabulary map and layer hash. +pub const Table = struct { + geometry: Geometry, + map: engram.TokenMap, + hash: engram.Layer, + + pub fn gather(self: Table, a: std.mem.Allocator, windows: []const [engram.order]u32, output: []u16) Error!void { + return gatherRows(a, self.geometry, self.map, self.hash, windows, output); + } + + pub fn elementsPerToken(self: Table) usize { + _ = self; + return tokenElements(); + } + + pub fn close(self: *Table) void { + _ = linux.close(self.geometry.fd); + self.* = undefined; + } +}; + +/// The real positioned read: the context is unused. +fn sysPread(_: *anyopaque, fd: linux.fd_t, buf: [*]u8, len: usize, off: i64) usize { + return linux.pread(fd, buf, len, off); +} + +var no_ctx: u8 = 0; // stable, never-dereferenced context for the system reader + +/// Read `len` aligned bytes at `off` of an O_DIRECT `fd` into an aligned buffer. +fn readDirect(fd: linux.fd_t, buf: []align(alignment) u8, off: u64, len: usize, size: u64) Error!void { + const g: Geometry = .{ .fd = fd, .size = size, .data_start = 0, .count = 1, .ctx = &no_ctx, .read = sysPread }; + return readExtent(g, buf, off, len); +} + +/// Open a one-tensor BF16 table O_DIRECT; `expected_rows` is the count the config implies for this layer. +pub fn openDirect(a: std.mem.Allocator, path: [:0]const u8, tensor: []const u8, map: engram.TokenMap, hash: engram.Layer, expected_rows: usize) Error!Table { + const rc = linux.openat(linux.AT.FDCWD, path, .{ .ACCMODE = .RDONLY, .CLOEXEC = true, .DIRECT = true }, 0); + if (linux.errno(rc) != .SUCCESS) return error.OpenFailed; + const fd: linux.fd_t = @intCast(rc); + errdefer _ = linux.close(fd); + var st: linux.Statx = undefined; + if (linux.errno(linux.statx(fd, "", linux.AT.EMPTY_PATH, .{ .SIZE = true }, &st)) != .SUCCESS) return error.StatFailed; + const size = st.size; + if (size < 8) return error.BadTable; + + // First aligned block carries the header length; one bounded allocation follows. + var first_block: [alignment]u8 align(alignment) = undefined; + try readDirect(fd, &first_block, 0, alignment, size); + const header_len = std.mem.readInt(u64, first_block[0..8], .little); + if (header_len == 0 or header_len > max_header_bytes or header_len > size - 8) return error.BadTable; + const header_end = std.math.add(u64, 8, header_len) catch return error.BadTable; + const json_len: usize = @intCast(header_len); + const buf_len = std.mem.alignForward(u64, header_end, alignment); + const header_buf = try a.alignedAlloc(u8, .fromByteUnits(alignment), @intCast(buf_len)); + defer a.free(header_buf); // one allocation, one owner: no free-then-replace on OOM + try readDirect(fd, header_buf, 0, header_buf.len, size); + const json = header_buf[8..][0..json_len]; + + const parsed = std.json.parseFromSlice(std.json.Value, a, json, .{}) catch return error.BadTable; + defer parsed.deinit(); + if (parsed.value != .object) return error.BadTable; + const entry = parsed.value.object.get(tensor) orelse return error.MissingTensor; + if (entry != .object) return error.BadTable; + const dtype = entry.object.get("dtype") orelse return error.BadTable; + if (dtype != .string or !std.mem.eql(u8, dtype.string, "BF16")) return error.BadTable; + + const offsets = entry.object.get("data_offsets") orelse return error.BadTable; + if (offsets != .array or offsets.array.items.len != 2) return error.BadTable; + const begin = offsets.array.items[0]; + const last = offsets.array.items[1]; + if (begin != .integer or last != .integer) return error.BadTable; + if (begin.integer < 0 or last.integer < 0) return error.BadTable; // no negative offsets + const lo: u64 = @intCast(begin.integer); + const hi: u64 = @intCast(last.integer); + if (hi < lo) return error.BadTable; + const bytes = hi - lo; + if (bytes == 0 or bytes % row_bytes != 0) return error.BadTable; + const count = bytes / row_bytes; + + // Shape and byte range must describe [count, width] BF16 and fit the reported size. + const shape = entry.object.get("shape") orelse return error.BadTable; + if (shape != .array or shape.array.items.len != 2) return error.BadTable; + for (shape.array.items) |dim| if (dim != .integer or dim.integer < 0) return error.BadTable; + if (count > std.math.maxInt(i64)) return error.BadTable; + if (shape.array.items[0].integer != @as(i64, @intCast(count)) or + shape.array.items[1].integer != @as(i64, width)) return error.BadTable; + const expected = std.math.mul(u64, count, row_bytes) catch return error.BadTable; + if (expected != bytes) return error.BadTable; + + const data_start = std.math.add(u64, header_end, lo) catch return error.BadTable; + const payload_end = std.math.add(u64, data_start, bytes) catch return error.BadTable; + if (payload_end > size or count > std.math.maxInt(u32)) return error.BadTable; + if (count != expected_rows) return error.RowCountMismatch; + + return .{ + .geometry = .{ .fd = fd, .size = size, .data_start = data_start, .count = count, .ctx = &no_ctx, .read = sysPread }, + .map = map, + .hash = hash, + }; +} + +test "a plan's extents are aligned and cover every selected 192-byte row" { + const a = std.testing.allocator; + const g: Geometry = .{ .fd = -1, .size = 1 << 20, .data_start = 4096 - 100, .count = 1000, .read = undefined }; + const lookup = [4]u32{ 0, 1, 2, 3 }; + const map: engram.TokenMap = .{ .bytes = std.mem.asBytes(&lookup), .pad = 0 }; + const offsets = [engram.columns]u32{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }; + const hash: engram.Layer = .{ .multipliers = .{ 3, 5, 7 }, .primes = @splat(17), .offsets = offsets }; + var plan = try buildPlan(a, g, map, hash, &.{ .{ 1, 2, 3 }, .{ 3, 2, 1 } }); + defer plan.deinit(a); + try std.testing.expectEqual(@as(usize, 2 * engram.columns), plan.rows.len); + for (plan.ext) |e| { + try std.testing.expectEqual(@as(u64, 0), e.off % alignment); + try std.testing.expectEqual(@as(usize, 0), e.len % alignment); + try std.testing.expectEqual(@as(usize, 0), e.at % alignment); + try std.testing.expect(e.len > 0); + } + for (plan.rows, plan.at) |row, src| { + var found = false; + for (plan.ext) |e| { + const off = g.data_start + @as(u64, row) * row_bytes; + if (off >= e.off and off + row_bytes <= e.off + e.len and src == e.at + @as(usize, @intCast(off - e.off))) found = true; + } + try std.testing.expect(found); + } +} diff --git a/zig/src/families/hy4_flash/bf16_rows_test.zig b/zig/src/families/hy4_flash/bf16_rows_test.zig new file mode 100644 index 00000000000..a7157fb6df1 --- /dev/null +++ b/zig/src/families/hy4_flash/bf16_rows_test.zig @@ -0,0 +1,314 @@ +//! Focused host fixture for the BF16 Engram direct reader: crossing, tail, truncated data. +const std = @import("std"); +const linux = std.os.linux; +const bf16 = @import("bf16_rows.zig"); +const engram = @import("engram.zig"); + +test { + _ = @import("bf16_rows.zig"); +} + +const Call = struct { off: u64, len: usize }; + +/// In-memory file accepting only aligned positioned reads, recording them and returning offset-derived bytes. +const Mock = struct { + bytes: []const u8, + calls: [64]Call = undefined, + n: usize = 0, + misaligned: bool = false, + refuse: bool = false, + + fn pread(ctx: *anyopaque, _: linux.fd_t, buf: [*]u8, len: usize, off: i64) usize { + const self: *Mock = @ptrCast(@alignCast(ctx)); + const o: u64 = @bitCast(off); + if (o % bf16.alignment != 0 or len % bf16.alignment != 0 or @intFromPtr(buf) % bf16.alignment != 0) self.misaligned = true; + if (self.n < self.calls.len) { + self.calls[self.n] = .{ .off = o, .len = len }; + self.n += 1; + } + if (self.refuse) return @bitCast(-@as(isize, @backingInt(linux.E.INVAL))); + if (o >= self.bytes.len) return 0; + const want = @min(len, self.bytes.len - @as(usize, @intCast(o))); + @memcpy(buf[0..want], self.bytes[@intCast(o)..][0..want]); + return want; + } +}; + +fn geometry(bytes: []const u8, data_start: u64, count: u64, mock: *Mock) bf16.Geometry { + return .{ .fd = 0, .size = bytes.len, .data_start = data_start, .count = count, .ctx = mock, .read = Mock.pread }; +} + +/// Each row stores its index in its first two bytes and a per-row pattern after. +fn synth(a: std.mem.Allocator, size: usize, data_start: u64, count: u64) ![]u8 { + const bytes = try a.alloc(u8, size); + @memset(bytes, 0); + for (0..count) |r| { + const off: usize = @intCast(data_start + @as(u64, r) * bf16.row_bytes); + if (off + bf16.row_bytes > size) break; + for (0..bf16.row_bytes) |k| bytes[off + k] = @intCast((r *% 31 +% k) % 251); + std.mem.writeInt(u16, bytes[off..][0..2], @intCast(r), .little); + } + return bytes; +} + +fn fixtureHash() engram.Layer { + const offsets = [engram.columns]u32{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }; + return .{ .multipliers = .{ 3, 5, 7 }, .primes = @splat(17), .offsets = offsets }; +} + +fn fixtureMap() engram.TokenMap { + const lookup = [4]u32{ 0, 1, 2, 3 }; + return .{ .bytes = std.mem.asBytes(&lookup), .pad = 0 }; +} + +fn checkOutput(bytes: []const u8, data_start: u64, map: engram.TokenMap, hash: engram.Layer, windows: []const [engram.order]u32, out: []const u16) !void { + for (windows, 0..) |window, t| { + for (hash.hash(map, window), 0..) |row, head| { + const at: usize = @intCast(data_start + @as(u64, row) * bf16.row_bytes); + for (0..bf16.width) |k| { + const want = std.mem.readInt(u16, bytes[at + 2 * k ..][0..2], .little); + try std.testing.expectEqual(want, out[(t * engram.columns + head) * bf16.width + k]); + } + } + } +} + +test "a row that crosses a 4 KiB boundary is read in aligned extents and lands in token/head order" { + const a = std.testing.allocator; + const data_start: u64 = bf16.alignment - 100; // row 0 spans [3996, 4188) + const count: u64 = 32; + const bytes = try synth(a, 3 * bf16.alignment, data_start, count); + defer a.free(bytes); + var mock: Mock = .{ .bytes = bytes }; + const g = geometry(bytes, data_start, count, &mock); + const windows = [3][engram.order]u32{ .{ 0, 0, 0 }, .{ 2, 1, 3 }, .{ 3, 2, 1 } }; + const out = try a.alloc(u16, windows.len * bf16.tokenElements()); + defer a.free(out); + try bf16.gatherRows(a, g, fixtureMap(), fixtureHash(), &windows, out); + try std.testing.expect(!mock.misaligned); + try std.testing.expect(mock.n > 0); + var crossed = false; + for (mock.calls[0..mock.n]) |c| { + if (c.len > bf16.alignment) crossed = true; + } + try std.testing.expect(crossed); // evidence the boundary was spanned, not skipped + try checkOutput(bytes, data_start, fixtureMap(), fixtureHash(), &windows, out); +} + +test "a tail row ending exactly at EOF is read from a short final block without a fallback" { + const a = std.testing.allocator; + const data_start: u64 = 8; // unaligned, as a safetensors payload usually is + const count: u64 = 5; + const size: usize = @intCast(data_start + count * bf16.row_bytes); // 968, inside one block + const bytes = try synth(a, size, data_start, count); + defer a.free(bytes); + var mock: Mock = .{ .bytes = bytes }; + const g = geometry(bytes, data_start, count, &mock); + const windows = [1][engram.order]u32{.{ 0, 0, 0 }}; // selects rows 0..15, all present (0..4 used) + const out = try a.alloc(u16, windows.len * bf16.tokenElements()); + defer a.free(out); + // limit the fixture hash's rows to the five the file holds + const hash = fixtureHash(); + var limited = hash; + limited.offsets = @splat(0); + try bf16.gatherRows(a, g, fixtureMap(), limited, &windows, out); + try std.testing.expect(!mock.misaligned); + try std.testing.expectEqual(@as(usize, 1), mock.n); + try std.testing.expectEqual(@as(u64, 0), mock.calls[0].off); + try std.testing.expectEqual(@as(usize, bf16.alignment), mock.calls[0].len); + try checkOutput(bytes, data_start, fixtureMap(), limited, &windows, out); +} + +test "a truncated row past EOF is refused before any read" { + const a = std.testing.allocator; + const data_start: u64 = 8; + const count: u64 = 5; + const size: usize = @intCast(data_start + count * bf16.row_bytes - 50); // last row cut short + const bytes = try synth(a, size, data_start, count); + defer a.free(bytes); + var mock: Mock = .{ .bytes = bytes }; + const g = geometry(bytes, data_start, count, &mock); + const windows = [1][engram.order]u32{.{ 0, 0, 0 }}; + const out = try a.alloc(u16, windows.len * bf16.tokenElements()); + defer a.free(out); + try std.testing.expectError(error.ShortRow, bf16.gatherRows(a, g, fixtureMap(), fixtureHash(), &windows, out)); + try std.testing.expectEqual(@as(usize, 0), mock.n); // refused in planning, not after I/O +} + +test "one plan executes byte-identical reads twice, and rebuilds byte-identically" { + const a = std.testing.allocator; + const data_start: u64 = bf16.alignment - 64; + const count: u64 = 32; + const bytes = try synth(a, 4 * bf16.alignment, data_start, count); + defer a.free(bytes); + const windows = [2][engram.order]u32{ .{ 1, 2, 3 }, .{ 3, 1, 2 } }; + const map = fixtureMap(); + const hash = fixtureHash(); + + var plan_mock: Mock = .{ .bytes = bytes }; + var rebuild_mock: Mock = .{ .bytes = bytes }; + var plan = try bf16.buildPlan(a, geometry(bytes, data_start, count, &plan_mock), map, hash, &windows); + defer plan.deinit(a); + var rebuilt = try bf16.buildPlan(a, geometry(bytes, data_start, count, &rebuild_mock), map, hash, &windows); + defer rebuilt.deinit(a); + try std.testing.expectEqualSlices(u32, plan.rows, rebuilt.rows); + try std.testing.expectEqualSlices(usize, plan.at, rebuilt.at); + try std.testing.expectEqual(plan.arena_len, rebuilt.arena_len); + try std.testing.expectEqual(plan.ext.len, rebuilt.ext.len); + for (plan.ext, rebuilt.ext) |x, y| { + try std.testing.expectEqual(x.off, y.off); + try std.testing.expectEqual(x.len, y.len); + try std.testing.expectEqual(x.at, y.at); + } + + var m1: Mock = .{ .bytes = bytes }; + var m2: Mock = .{ .bytes = bytes }; + const o1 = try a.alloc(u16, windows.len * bf16.tokenElements()); + defer a.free(o1); + const o2 = try a.alloc(u16, windows.len * bf16.tokenElements()); + defer a.free(o2); + try bf16.execute(a, geometry(bytes, data_start, count, &m1), plan, o1); + try bf16.execute(a, geometry(bytes, data_start, count, &m2), plan, o2); + try std.testing.expectEqualSlices(u16, o1, o2); + try std.testing.expectEqual(m1.n, m2.n); + try std.testing.expectEqualSlices(Call, m1.calls[0..m1.n], m2.calls[0..m2.n]); + try std.testing.expect(!m1.misaligned and !m2.misaligned); +} + +test "an O_DIRECT read refusal is a hard error, never a buffered retry" { + const a = std.testing.allocator; + const bytes = try synth(a, 2 * bf16.alignment, 0, 32); + defer a.free(bytes); + var mock: Mock = .{ .bytes = bytes, .refuse = true }; + const g = geometry(bytes, 0, 32, &mock); + const windows = [1][engram.order]u32{.{ 0, 0, 0 }}; + const out = try a.alloc(u16, windows.len * bf16.tokenElements()); + defer a.free(out); + try std.testing.expectError(error.ReadFailed, bf16.gatherRows(a, g, fixtureMap(), fixtureHash(), &windows, out)); + try std.testing.expect(mock.n >= 1); // the read was attempted; no fallback path exists +} + +/// Build a one-tensor BF16 safetensors image; `pad` pushes the header past one block. +fn safetensorsImage(a: std.mem.Allocator, count: u64, pad: usize) !struct { bytes: []u8, header_end: usize } { + const data_len: usize = @intCast(count * bf16.row_bytes); + var header: std.ArrayList(u8) = .empty; + defer header.deinit(a); + var first_buf: [256]u8 = undefined; + const first = try std.fmt.bufPrint(&first_buf, "{{\"emb\":{{\"dtype\":\"BF16\",\"shape\":[{d},96],\"data_offsets\":[0,{d}]}}", .{ count, data_len }); + try header.appendSlice(a, first); + if (pad > 0) { + try header.appendSlice(a, ",\"pad\":{\"dtype\":\"U8\",\"shape\":[1],\"data_offsets\":[0,0],\"note\":\""); + try header.appendNTimes(a, 'x', pad); + try header.appendSlice(a, "\"}"); + } + try header.append(a, '}'); + const header_end = 8 + header.items.len; + var file = try a.alloc(u8, header_end + data_len); + std.mem.writeInt(u64, file[0..8], @intCast(header.items.len), .little); + @memcpy(file[8..header_end], header.items); + for (0..count) |r| { + const off = header_end + r * bf16.row_bytes; + for (0..bf16.row_bytes) |k| file[off + k] = @intCast((r *% 31 +% k) % 251); + std.mem.writeInt(u16, file[off..][0..2], @intCast(r), .little); + } + return .{ .bytes = file, .header_end = header_end }; +} + +test "openDirect reads a real safetensors table through O_DIRECT (small and multi-block header)" { + const a = std.testing.allocator; + const windows = [2][engram.order]u32{ .{ 0, 0, 0 }, .{ 2, 1, 3 } }; + const map = fixtureMap(); + const hash = fixtureHash(); + for ([_]usize{ 0, 6000 }) |pad| { + const image = try safetensorsImage(a, 32, pad); + defer a.free(image.bytes); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const io = std.testing.io; + try tmp.dir.writeFile(io, .{ .sub_path = "emb.safetensors", .data = image.bytes }); + const real = try tmp.dir.realPathFileAlloc(io, "emb.safetensors", a); + defer a.free(real); + const path = try a.dupeSentinel(u8, real, 0); + defer a.free(path); + var table = bf16.openDirect(a, path, "emb", map, hash, 32) catch |err| switch (err) { + error.OpenFailed, error.ReadFailed => return, // file system refuses O_DIRECT + else => return err, + }; + defer table.close(); + const out = try a.alloc(u16, windows.len * bf16.tokenElements()); + defer a.free(out); + try table.gather(a, &windows, out); + try checkOutput(image.bytes, @intCast(image.header_end), map, hash, &windows, out); + } +} + +fn rawImage(a: std.mem.Allocator, json: []const u8, data_len: usize) ![]u8 { + const header_end = 8 + json.len; + const file = try a.alloc(u8, header_end + data_len); + std.mem.writeInt(u64, file[0..8], @intCast(json.len), .little); + @memcpy(file[8..header_end], json); + @memset(file[header_end..], 0); + return file; +} + +fn expectBadTable(a: std.mem.Allocator, bytes: []const u8) !void { + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const io = std.testing.io; + try tmp.dir.writeFile(io, .{ .sub_path = "bad.safetensors", .data = bytes }); + const real = try tmp.dir.realPathFileAlloc(io, "bad.safetensors", a); + defer a.free(real); + const path = try a.dupeSentinel(u8, real, 0); + defer a.free(path); + var table = bf16.openDirect(a, path, "emb", fixtureMap(), fixtureHash(), 1) catch |err| switch (err) { + error.BadTable => return, + error.OpenFailed, error.ReadFailed => return, // file system refuses O_DIRECT + else => return err, + }; + table.close(); + return error.TestUnexpectedResult; +} + +test "openDirect refuses negative offsets, wrong shape, header overflow and truncated payload" { + const a = std.testing.allocator; + const cases = [_][]const u8{ + "{\"emb\":{\"dtype\":\"BF16\",\"shape\":[1,96],\"data_offsets\":[-1,191]}}", + "{\"emb\":{\"dtype\":\"BF16\",\"shape\":[1,96],\"data_offsets\":[0,-192]}}", + "{\"emb\":{\"dtype\":\"BF16\",\"shape\":[1,95],\"data_offsets\":[0,192]}}", + "{\"emb\":{\"dtype\":\"BF16\",\"shape\":[1,96],\"data_offsets\":[0,384]}}", + "{\"emb\":{\"dtype\":\"BF16\",\"shape\":[2,96],\"data_offsets\":[0,384]}}", + }; + for (cases, 0..) |json, i| { + const bytes = try rawImage(a, json, if (i == 4) 192 else 384); + defer a.free(bytes); + try expectBadTable(a, bytes); + } + // A header length larger than the file (and one past the configured bound). + var prefix: [8]u8 = undefined; + std.mem.writeInt(u64, &prefix, 1 << 20, .little); + try expectBadTable(a, &prefix); +} + +test "openDirect refuses a table whose row count is not the config's for that layer" { + const a = std.testing.allocator; + // Released tables hold 164,994,380 / 164,999,008 / 165,004,086 / 165,008,942 rows, so a wrong shard stays in range. + const image = try safetensorsImage(a, 32, 0); + defer a.free(image.bytes); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const io = std.testing.io; + try tmp.dir.writeFile(io, .{ .sub_path = "emb.safetensors", .data = image.bytes }); + const real = try tmp.dir.realPathFileAlloc(io, "emb.safetensors", a); + defer a.free(real); + const path = try a.dupeSentinel(u8, real, 0); + defer a.free(path); + for ([_]usize{ 31, 33 }) |wrong| { + var table = bf16.openDirect(a, path, "emb", fixtureMap(), fixtureHash(), wrong) catch |err| switch (err) { + error.RowCountMismatch => continue, + error.OpenFailed, error.ReadFailed => return, // file system refuses O_DIRECT + else => return err, + }; + table.close(); + return error.TestUnexpectedResult; + } +} diff --git a/zig/src/families/hy4_flash/cuda_generate.zig b/zig/src/families/hy4_flash/cuda_generate.zig new file mode 100644 index 00000000000..b7474841ce8 --- /dev/null +++ b/zig/src/families/hy4_flash/cuda_generate.zig @@ -0,0 +1,60 @@ +//! Greedy generation with the CUDA Hy4-flash text model: prefill token ids, decode N, write timings and logits. +const std = @import("std"); +const cuda = @import("cuda"); +const model = @import("cuda_model.zig"); + +pub fn main(init: std.process.Init) !void { + const a = init.arena.allocator(); + const io = init.io; + const args = try init.minimal.args.toSlice(a); + if (args.len != 5) { + std.debug.print("usage: tf-hy4-cuda-generate MODEL_DIR PROMPT_IDS.u32 NEW_TOKENS OUT_DIR\n", .{}); + return error.BadArgs; + } + const prompt_bytes = try std.Io.Dir.cwd().readFileAlloc(io, args[2], a, .limited(1 << 20)); + const prompt = try a.alloc(u32, prompt_bytes.len / 4); + @memcpy(std.mem.sliceAsBytes(prompt), prompt_bytes[0 .. prompt.len * 4]); + const new_tokens = try std.fmt.parseInt(usize, args[3], 10); + const out = try std.Io.Dir.cwd().openDir(io, args[4], .{}); + var driver = try cuda.Driver.open(); + defer driver.close(); + var ctx = try cuda.Context.init(&driver, 0); + defer ctx.deinit(); + if (try ctx.capability() != 121) return error.NeedGb10; + var s = try cuda.Stream.init(&driver, true); + defer s.deinit(); + var kernels = try model.Kernels.load(a, &driver); + const t0 = std.Io.Clock.awake.now(io); + const capacity = prompt.len + new_tokens; + const hy4 = try model.Model.open(a, io, &driver, s, &kernels, args[1], capacity, @max(prompt.len, 1)); + const load_ns = t0.durationTo(std.Io.Clock.awake.now(io)).toNanoseconds(); + std.debug.print("loaded {d} layers, {d:.2} GiB device weights in {d:.1} s\n", .{ hy4.layers.len, @as(f64, @floatFromInt(hy4.weight_bytes)) / (1 << 30), @as(f64, @floatFromInt(load_ns)) / 1e9 }); + const logits = try a.alloc(f32, hy4.text.vocab_size); + var copy: std.ArrayList(u32) = .empty; + const p0 = std.Io.Clock.awake.now(io); + var u32buf: [1]u32 = undefined; + try hy4.pass(prompt, logits); + const prefill_ns = p0.durationTo(std.Io.Clock.awake.now(io)).toNanoseconds(); + try out.writeFile(io, .{ .sub_path = "prefill-logits.f32", .data = std.mem.sliceAsBytes(logits) }); + const d0 = std.Io.Clock.awake.now(io); + for (0..new_tokens) |step| { + var best: usize = 0; + for (logits, 0..) |v, i| if (v > logits[best]) { + best = i; + }; + try copy.append(a, @intCast(best)); + if (step + 1 == new_tokens) break; + u32buf[0] = @intCast(best); + try hy4.pass(&u32buf, logits); + } + const decode_ns = d0.durationTo(std.Io.Clock.awake.now(io)).toNanoseconds(); + try out.writeFile(io, .{ .sub_path = "generated.u32", .data = std.mem.sliceAsBytes(copy.items) }); + std.debug.print("prompt {d} tokens: prefill {d:.1} ms ({d:.1} tok/s); decode {d} tokens {d:.1} ms/token\ngenerated={any}\n", .{ + prompt.len, + @as(f64, @floatFromInt(prefill_ns)) / 1e6, + @as(f64, @floatFromInt(prompt.len)) * 1e9 / @as(f64, @floatFromInt(prefill_ns)), + new_tokens, + @as(f64, @floatFromInt(decode_ns)) / 1e6 / @as(f64, @floatFromInt(@max(new_tokens, 2) - 1)), + copy.items, + }); +} diff --git a/zig/src/families/hy4_flash/cuda_model.zig b/zig/src/families/hy4_flash/cuda_model.zig new file mode 100644 index 00000000000..a6f4c24f012 --- /dev/null +++ b/zig/src/families/hy4_flash/cuda_model.zig @@ -0,0 +1,591 @@ +//! Hy4-flash text model on CUDA for EXL3 routed experts with BF16 elsewhere; one sequence, causal or windowed keys. +const std = @import("std"); +const core = @import("core"); +const cuda = @import("cuda"); +const config = @import("config.zig"); +const ihc = @import("ihc.zig"); +const ihc_cuda = @import("ihc_cuda.zig"); +const mla = @import("mla_cuda.zig"); +const m = @import("mla_weights.zig"); +const attn = @import("mla_attention.zig"); +const rope = @import("rope.zig"); +const exl3 = @import("moe_exl3_cuda.zig"); +const expert_weights = @import("exl3_weights.zig"); +const engram = @import("engram.zig"); +const engram_cuda = @import("engram_cuda.zig"); +const direct = @import("bf16_rows.zig"); + +const H = 3072; +const S = ihc.streams; +const L = 1536; +const D = 13824; +const E = 512; +const K = 16; +const Q = 1024; +const sparse_stride = 2048; +const sliding_stride = 512; + +pub const Kernels = struct { + gemm: cuda.vit.Gemms, + norms: cuda.norms.Norms, + project: mla.Projections, + attention: mla.Attention, + ihc: ihc_cuda.Kernels, + experts: cuda.exl3_experts.Experts, + act: cuda.act_rows.ActRows, + glue: cuda.moe_glue.MoeGlue, + router: cuda.route_rows.RouteRows, + engram: engram_cuda.Kernels, + + /// The kernel images embedded in this build (`-Dnvcc` or `-Dprebuilt`). + pub fn load(a: std.mem.Allocator, d: *const cuda.Driver) !Kernels { + return .{ + .gemm = try cuda.vit.Gemms.init(a, d), + .norms = try cuda.norms.Norms.load(d), + .project = try mla.Projections.load(d), + .attention = try mla.Attention.load(d), + .ihc = try ihc_cuda.Kernels.load(d), + .experts = try cuda.exl3_experts.Experts.load(d), + .act = try cuda.act_rows.ActRows.load(d), + .glue = try cuda.moe_glue.MoeGlue.load(d), + .router = try cuda.route_rows.RouteRows.load(d), + .engram = try engram_cuda.Kernels.load(d), + }; + } +}; + +const Hc = struct { project: u64, bias: u64, scale: u64 }; + +const Attention = struct { + sliding: bool, + heads: u32, + hc: Hc, + input_norm: u64, + q_a: u64, + q_norm: u64, + q_b: u64, + kv_a: u64, + kv_norm: u64, + key: u64, + value: u64, + gate: u64, + output: u64, + output_norm: u64, + sinks: u64, + cache: cuda.DeviceBuffer, +}; + +const Dense = struct { gate: u64, up: u64, down: u64 }; +const Sparse = struct { + latent_in: u64, + latent_out: u64, + shared_gate: u64, + shared_up: u64, + shared_down: u64, + router: u64, + router_bias: u64, + routed: exl3.Routed, +}; + +const Feed = struct { + hc: Hc, + input_norm: u64, + output_norm: u64, + mlp: union(enum) { dense: Dense, sparse: Sparse }, +}; + +const Engram = struct { + w: engram_cuda.Weights, + table: direct.Table, +}; + +const Layer = struct { engram: ?Engram, attention: Attention, feed: Feed }; + +/// Per-pass device scratch sized for `max_rows`. +const Scratch = struct { + streams: [3]cuda.DeviceBuffer, // [rows, 4, H], rotated through the layer halves + collapsed: u64, + post: u64, + hidden: u64, + norm_tmp: u64, + q_raw: u64, + q_tmp: u64, + q_resid: u64, + q: u64, + kv: u64, + gate: u64, + absorb: u64, + latent_out: u64, + values: u64, + branch: u64, + branch_norm: u64, + attn_scratch: u64, + attn_scratch_bytes: usize, + positions: cuda.DeviceBuffer, + table: u64, + slots: cuda.DeviceBuffer, + counts: cuda.DeviceBuffer, + write_slots: cuda.DeviceBuffer, + media: u64, + latent: u64, + logits: u64, + picks: u64, + probabilities: u64, + mix: u64, + route_out: u64, + ff_gate: u64, + ff_up: u64, + ff_inner: u64, + shared: u64, + e_raw: cuda.DeviceBuffer, + e_normalized: u64, + e_keys: u64, + e_value: u64, + head_hidden: u64, + head_norm: u64, + lm_logits: u64, +}; + +pub const Model = struct { + a: std.mem.Allocator, + d: *const cuda.Driver, + s: cuda.Stream, + k: *Kernels, + text: config.Text, + own: cuda.exl3_upload.Uploader, + layers: []Layer, + embed: u64, + head_hc: Hc, + final_norm: u64, + lm_head: u64, + scratch: Scratch, + max_rows: usize, + capacity: usize, + history: std.ArrayList(u32) = .empty, + weight_bytes: usize = 0, + + fn tensor(ck: *core.Checkpoint, name: []const u8, dtype: anytype, shape: []const usize) ![]const u8 { + const t = try ck.get(name); + if (!t.is(dtype, shape)) { + std.debug.print("unexpected tensor {s}: {any} {any}\n", .{ name, t.dtype, t.shape[0..t.rank] }); + return error.BadHy4CheckpointTensor; + } + return t.bytes; + } + + fn up(self: *Model, ck: *core.Checkpoint, comptime fmt: []const u8, args: anytype, dtype: anytype, shape: []const usize) !u64 { + var buf: [192]u8 = undefined; + const name = try std.fmt.bufPrint(&buf, fmt, args); + return self.own.dev(try tensor(ck, name, dtype, shape)); + } + + fn zeros(self: *Model, bytes: usize) !u64 { + const z = try std.heap.page_allocator.alloc(u8, bytes); + defer std.heap.page_allocator.free(z); + @memset(z, 0); + return self.own.dev(z); + } + + pub fn open(a: std.mem.Allocator, io: std.Io, d: *const cuda.Driver, s: cuda.Stream, k: *Kernels, dir: []const u8, capacity: usize, max_rows: usize) !*Model { + const cfg = try config.parse(a, try std.Io.Dir.cwd().readFileAlloc(io, try std.fs.path.join(a, &.{ dir, "config.json" }), a, .limited(1 << 20))); + const t = cfg.value.text_config; + if (t.hidden_size != H or t.hc_mult != S or t.routed_expert_hidden_size != L or t.moe_intermediate_size != L or + t.intermediate_size != D or t.n_routed_experts != E or t.num_experts_per_tok != K or t.q_lora_rank != Q) + return error.BadHy4ModelShape; + if (capacity > sparse_stride or max_rows == 0 or max_rows > 1024) return error.BadHy4RunnerCapacity; + const ck = try a.create(core.Checkpoint); + ck.* = try core.Checkpoint.openModel(a, io, dir); + const self = try a.create(Model); + self.* = .{ + .a = a, + .d = d, + .s = s, + .k = k, + .text = t, + // Upload tables and staging go through a freeing allocator: the arena would keep them all. + .own = .{ .d = d, .gpa = std.heap.page_allocator, .max_buffers = 1 << 20, .slab = 256 << 20 }, + .layers = try a.alloc(Layer, t.num_hidden_layers), + .embed = undefined, + .head_hc = undefined, + .final_norm = undefined, + .lm_head = undefined, + .scratch = undefined, + .max_rows = max_rows, + .capacity = capacity, + }; + const V: usize = t.vocab_size; + self.embed = try self.up(ck, "model.embed_tokens.weight", .{}, .bf16, &.{ V, H }); + self.head_hc = .{ + .project = try self.up(ck, "model.hc_head.hc_head_fn", .{}, .f32, &.{ S, S * H }), + .bias = try self.up(ck, "model.hc_head.hc_head_base", .{}, .f32, &.{S}), + .scale = try self.up(ck, "model.hc_head.hc_head_scale", .{}, .f32, &.{1}), + }; + self.final_norm = try self.up(ck, "model.norm.weight", .{}, .bf16, &.{H}); + self.lm_head = try self.up(ck, "lm_head.weight", .{}, .bf16, &.{ V, H }); + ck.release(); + // UMA guard: device memory is not charged to the cgroup, so stop before the system runs dry. + const floor_gib = try @import("sys").environment.read(usize, "TF_HY4_MEM_FLOOR_GIB", 10); + for (self.layers, 0..) |*layer, i| { + const avail = memAvailable(); + std.debug.print("layer {d:>2}: device {d:.2} GiB, MemAvailable {d:.2} GiB\n", .{ i, gib(self.own.bytes), gib(avail) }); + if (avail < floor_gib << 30) { + std.debug.print("stopping: MemAvailable below the {d} GiB floor\n", .{floor_gib}); + return error.Hy4MemoryFloor; + } + layer.* = try self.loadLayer(a, io, ck, dir, i); + // The layer is on the device: its mapped shard pages (and page cache) would otherwise stay resident. + ck.release(); + } + 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(); + return self; + } + + fn gib(bytes: usize) f64 { + return @as(f64, @floatFromInt(bytes)) / (1 << 30); + } + + /// MemAvailable from /proc/meminfo in bytes (0 when unreadable, which trips the floor). + fn memAvailable() usize { + var buf: [4096]u8 = undefined; + const fd = std.c.open("/proc/meminfo", .{}); + if (fd < 0) return 0; + defer _ = std.c.close(fd); + const got = std.c.read(fd, &buf, buf.len); + if (got <= 0) return 0; + const n: usize = @intCast(got); + var it = std.mem.tokenizeScalar(u8, buf[0..n], '\n'); + while (it.next()) |line| if (std.mem.startsWith(u8, line, "MemAvailable:")) { + var f = std.mem.tokenizeScalar(u8, line["MemAvailable:".len..], ' '); + const kb = std.fmt.parseInt(usize, f.next() orelse return 0, 10) catch return 0; + return kb * 1024; + }; + return 0; + } + + fn loadLayer(self: *Model, a: std.mem.Allocator, io: std.Io, ck: *core.Checkpoint, dir: []const u8, i: usize) !Layer { + const t = self.text; + const sliding = t.layer_types[i] == .sliding_attention; + const heads: u32 = if (sliding) t.swa_num_attention_heads else t.num_attention_heads; + const hh: usize = heads; + const p = "model.layers.{d}."; + var kv_b_name: [96]u8 = undefined; + const kv_b = try tensor(ck, try std.fmt.bufPrint(&kv_b_name, p ++ "self_attn.kv_b_proj.weight", .{i}), .bf16, &.{ hh * (m.nope + m.value_width), m.latent }); + const tmp = std.heap.page_allocator; + const split = try m.splitBf16(tmp, kv_b, heads); + defer tmp.free(split.key); + defer tmp.free(split.value); + var cache = try cuda.DeviceBuffer.alloc(self.d, self.capacity * m.absorbed_stride * 2); + try cache.fill8(0, null); + const att: Attention = .{ + .sliding = sliding, + .heads = heads, + .hc = .{ + .project = try self.up(ck, p ++ "hc_attn_layer.hc_pre.hc_fn", .{i}, .f32, &.{ 2 * S, S * H }), + .bias = try self.up(ck, p ++ "hc_attn_layer.hc_pre.hc_base", .{i}, .f32, &.{2 * S}), + .scale = try self.up(ck, p ++ "hc_attn_layer.hc_pre.hc_scale", .{i}, .f32, &.{2}), + }, + .input_norm = try self.up(ck, p ++ "input_layernorm.weight", .{i}, .bf16, &.{H}), + .q_a = try self.up(ck, p ++ "self_attn.q_a_proj.weight", .{i}, .bf16, &.{ Q, H }), + .q_norm = try self.up(ck, p ++ "self_attn.q_a_layernorm.weight", .{i}, .bf16, &.{Q}), + .q_b = try self.up(ck, p ++ "self_attn.q_b_proj.weight", .{i}, .bf16, &.{ hh * m.query_stride, Q }), + .kv_a = try self.up(ck, p ++ "self_attn.kv_a_proj_with_mqa.weight", .{i}, .bf16, &.{ m.absorbed_stride, H }), + .kv_norm = try self.up(ck, p ++ "self_attn.kv_a_layernorm.weight", .{i}, .bf16, &.{m.latent}), + .key = try self.own.dev(std.mem.sliceAsBytes(split.key)), + .value = try self.own.dev(std.mem.sliceAsBytes(split.value)), + .gate = try self.up(ck, p ++ "self_attn.linear_gate.weight", .{i}, .bf16, &.{ hh * m.value_width, H }), + .output = try self.up(ck, p ++ "self_attn.o_proj.weight", .{i}, .bf16, &.{ H, hh * m.value_width }), + .output_norm = try self.up(ck, p ++ "self_attn.post_proj_norm.weight", .{i}, .bf16, &.{H}), + .sinks = try self.up(ck, p ++ "self_attn.learnable_sink_param", .{i}, .f32, &.{hh}), + .cache = cache, + }; + const dense = t.mlp_layer_types[i] == .dense; + const feed: Feed = .{ + .hc = .{ + .project = try self.up(ck, p ++ "hc_mlp_layer.hc_pre.hc_fn", .{i}, .f32, &.{ 2 * S, S * H }), + .bias = try self.up(ck, p ++ "hc_mlp_layer.hc_pre.hc_base", .{i}, .f32, &.{2 * S}), + .scale = try self.up(ck, p ++ "hc_mlp_layer.hc_pre.hc_scale", .{i}, .f32, &.{2}), + }, + .input_norm = try self.up(ck, p ++ "post_attention_layernorm.weight", .{i}, .bf16, &.{H}), + .output_norm = if (dense) + try self.up(ck, p ++ "mlp.post_fc2_norm.weight", .{i}, .bf16, &.{H}) + else + try self.up(ck, p ++ "mlp.combine_output_norm.weight", .{i}, .bf16, &.{H}), + .mlp = if (dense) .{ .dense = .{ + .gate = try self.up(ck, p ++ "mlp.gate_proj.weight", .{i}, .bf16, &.{ D, H }), + .up = try self.up(ck, p ++ "mlp.up_proj.weight", .{i}, .bf16, &.{ D, H }), + .down = try self.up(ck, p ++ "mlp.down_proj.weight", .{i}, .bf16, &.{ H, D }), + } } else .{ .sparse = blk: { + const experts = try std.heap.page_allocator.alloc(expert_weights.Expert, E); + defer std.heap.page_allocator.free(experts); + for (experts, 0..) |*e, j| e.* = try expert_weights.readExpert(ck, i, j, L, L); + break :blk .{ + .latent_in = try self.up(ck, p ++ "mlp.routed_expert_down_proj.weight", .{i}, .bf16, &.{ L, H }), + .latent_out = try self.up(ck, p ++ "mlp.routed_expert_up_proj.weight", .{i}, .bf16, &.{ H, L }), + .shared_gate = try self.up(ck, p ++ "mlp.shared_experts.gate_proj.weight", .{i}, .bf16, &.{ L, H }), + .shared_up = try self.up(ck, p ++ "mlp.shared_experts.up_proj.weight", .{i}, .bf16, &.{ L, H }), + .shared_down = try self.up(ck, p ++ "mlp.shared_experts.down_proj.weight", .{i}, .bf16, &.{ H, L }), + .router = try self.up(ck, p ++ "mlp.gate.weight", .{i}, .bf16, &.{ E, H }), + .router_bias = try self.up(ck, p ++ "mlp.gate.e_score_correction_bias", .{i}, .f32, &.{E}), + .routed = try exl3.Routed.init(&self.own, experts, L, L, self.max_rows, K, t.swiglu_limit), + }; + } }, + }; + var eng: ?Engram = null; + if (std.mem.indexOfScalar(u32, t.engram_layer_ids, @intCast(i + 1)) != null) { + const e = "model.layers.{d}.engram_layer."; + const ein: usize = engram_cuda.input; + var key: [S]u64 = undefined; + for (&key, 0..) |*dst, j| dst.* = try self.up(ck, e ++ "key_projs.{d}.weight", .{ i, j }, .bf16, &.{ H, ein }); + const cat = struct { + fn run(mm: *Model, c: *core.Checkpoint, layer: usize, comptime fmt: []const u8, count: usize, size: usize) !u64 { + const out = try mm.a.alloc(u8, count * size * 2); + defer mm.a.free(out); + for (0..count) |j| { + var nb: [128]u8 = undefined; + @memcpy(out[j * size * 2 ..][0 .. size * 2], try tensor(c, try std.fmt.bufPrint(&nb, fmt, .{ layer, j }), .bf16, &.{size})); + } + return mm.own.dev(out); + } + }.run; + const w: engram_cuda.Weights = .{ + .lookup_gamma = try cat(self, ck, i, e ++ "lookup_per_head_norms.{d}.weight", engram_cuda.columns, engram_cuda.head_width), + .value = try self.up(ck, e ++ "value_proj.weight", .{i}, .bf16, &.{ H, ein }), + .value_bias = try self.up(ck, e ++ "value_proj.bias", .{i}, .bf16, &.{H}), + .value_gain = try self.up(ck, e ++ "unified_pre_gamma", .{i}, .bf16, &.{H}), + .key = key, + .key_bias = try cat(self, ck, i, e ++ "key_projs.{d}.bias", S, H), + .key_gain = try cat(self, ck, i, e ++ "norm_key.{d}.weight", S, H), + .query_gain = try cat(self, ck, i, e ++ "norm_query.{d}.weight", S, H), + .delta_gain = try cat(self, ck, i, e ++ "unified_per_hc_scales.{d}", S, H), + }; + var nb: [128]u8 = undefined; + const lookup = (try ck.get(try std.fmt.bufPrint(&nb, e ++ "lookup_table", .{i}))).bytes; + const map = try engram.TokenMap.open(lookup, t); + const hash = try engram.Layer.open(t, @intCast(i + 1)); + var tb: [128]u8 = undefined; + const table_name = try std.fmt.bufPrint(&tb, e ++ "multi_head_embedding.embedding.weight", .{i}); + 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) }; + } + return .{ .engram = eng, .attention = att, .feed = feed }; + } + + /// The safetensors file holding `name` (the Engram tables sit alone in their shards). + fn shardOf(a: std.mem.Allocator, io: std.Io, dir: []const u8, name: []const u8) ![:0]const u8 { + const index = try std.Io.Dir.cwd().readFileAlloc(io, try std.fs.path.join(a, &.{ dir, "model.safetensors.index.json" }), a, .limited(1 << 26)); + const parsed = try std.json.parseFromSliceLeaky(std.json.Value, a, index, .{}); + const file = parsed.object.get("weight_map").?.object.get(name) orelse return error.MissingHy4EngramTable; + return std.fmt.allocPrintSentinel(a, "{s}/{s}", .{ dir, file.string }, 0); + } + + fn allocScratch(self: *Model) !Scratch { + const r = self.max_rows; + const shape = try attn.Shape.init(@intCast(r), 64, sparse_stride); + var sc: Scratch = undefined; + for (&sc.streams) |*x| x.* = try cuda.DeviceBuffer.alloc(self.d, r * S * H * 2); + sc.collapsed = try self.zeros(r * H * 2); + sc.post = try self.zeros(r * S * 4); + sc.hidden = try self.zeros(r * H * 2); + sc.norm_tmp = try self.zeros(r * D * 2); + sc.q_raw = try self.zeros(r * Q * 2); + sc.q_tmp = try self.zeros(r * Q * 2); + sc.q_resid = try self.zeros(r * Q * 2); + sc.q = try self.zeros(r * 64 * m.query_stride * 2); + sc.kv = try self.zeros(r * m.absorbed_stride * 2); + sc.gate = try self.zeros(r * 64 * m.value_width * 2); + sc.absorb = try self.zeros(r * 64 * m.absorbed_stride * 2); + sc.latent_out = try self.zeros(r * 64 * m.latent * 2); + sc.values = try self.zeros(r * 64 * m.value_width * 2); + sc.branch = try self.zeros(r * H * 2); + sc.branch_norm = try self.zeros(r * H * 2); + sc.attn_scratch_bytes = shape.scratchBytes(); + sc.attn_scratch = try self.zeros(sc.attn_scratch_bytes); + sc.positions = try cuda.DeviceBuffer.alloc(self.d, r * 12); + sc.table = try self.zeros(r * 64 * 2); + sc.slots = try cuda.DeviceBuffer.alloc(self.d, r * sparse_stride * 4); + sc.counts = try cuda.DeviceBuffer.alloc(self.d, r * 4); + sc.write_slots = try cuda.DeviceBuffer.alloc(self.d, r * 4); + sc.media = try self.zeros(r * 4); + sc.latent = try self.zeros(r * L * 2); + sc.logits = try self.zeros(r * E * 4); + sc.picks = try self.zeros(r * K * 4); + sc.probabilities = try self.zeros(r * K * 4); + sc.mix = try self.zeros(r * L * 2); + sc.route_out = try self.zeros(r * H * 2); + sc.ff_gate = try self.zeros(r * D * 2); + sc.ff_up = try self.zeros(r * D * 2); + sc.ff_inner = try self.zeros(r * D * 2); + sc.shared = try self.zeros(r * H * 2); + sc.e_raw = try cuda.DeviceBuffer.alloc(self.d, r * engram_cuda.input * 2); + sc.e_normalized = try self.zeros(r * engram_cuda.input * 2); + sc.e_keys = try self.zeros(S * r * H * 2); + sc.e_value = try self.zeros(r * H * 2); + sc.head_hidden = try self.zeros(r * H * 2); + sc.head_norm = try self.zeros(r * H * 2); + sc.lm_logits = try self.zeros(@as(usize, self.text.vocab_size) * 4); + return sc; + } + + fn hcShape(self: *const Model, rows: usize, gates: u32) ihc.Shape { + return .{ .rows = @intCast(rows), .width = H, .gates = gates, .eps = self.text.rms_norm_eps, .gate_eps = self.text.hc_eps, .post_magnitude = self.text.hc_magnitude }; + } + + /// Run `tokens` (appended at the current history length) through the model; returns the last row's logits. + pub fn pass(self: *Model, tokens: []const u32, logits_out: []f32) !void { + const rows = tokens.len; + const start = self.history.items.len; + if (rows == 0 or rows > self.max_rows or start + rows > self.capacity) return error.BadHy4PassRows; + try self.history.appendSlice(self.a, tokens); + const sc = self.scratch; + const s = self.s; + const k = self.k; + const eps = self.text.rms_norm_eps; + // Embedding into four identical streams. + var x = sc.streams[0].ptr; + for (tokens, 0..) |tok, r| for (0..S) |st| { + try sc.streams[0].copyFrom((r * S + st) * H * 2, self.embed + @as(u64, tok) * H * 2, H * 2, s.handle); + }; + // Positions (text: t = h = w), write slots and key lists for both attention kinds. + const positions = try self.a.alloc(i32, rows * 3); + defer self.a.free(positions); + const writes = try self.a.alloc(u32, rows); + defer self.a.free(writes); + for (0..rows) |r| { + const p: i32 = @intCast(start + r); + positions[r * 3 ..][0..3].* = .{ p, p, p }; + writes[r] = @intCast(start + r); + } + try sc.positions.uploadAsync(0, std.mem.sliceAsBytes(positions), s.handle); + try sc.write_slots.uploadAsync(0, std.mem.sliceAsBytes(writes), s.handle); + const keys_sparse = try self.a.alloc(u32, rows * sparse_stride); + defer self.a.free(keys_sparse); + const keys_sliding = try self.a.alloc(u32, rows * sliding_stride); + defer self.a.free(keys_sliding); + const counts_sparse = try self.a.alloc(u32, rows); + defer self.a.free(counts_sparse); + const counts_sliding = try self.a.alloc(u32, rows); + defer self.a.free(counts_sliding); + @memset(keys_sparse, 0); + @memset(keys_sliding, 0); + for (0..rows) |r| { + const pos = start + r; + counts_sparse[r] = @intCast(pos + 1); + for (0..pos + 1) |j| keys_sparse[r * sparse_stride + j] = @intCast(j); + const first = if (pos + 1 > sliding_stride) pos + 1 - sliding_stride else 0; + counts_sliding[r] = @intCast(pos + 1 - first); + for (first..pos + 1, 0..) |j, n| keys_sliding[r * sliding_stride + n] = @intCast(j); + } + // Engram windows from the committed history. + const windows = try self.a.alloc([engram.order]u32, rows); + defer self.a.free(windows); + const pad = self.text.engram_pad_id; + for (windows, 0..) |*w, r| { + const pos = start + r; + for (w, 0..) |*v, back| v.* = if (pos >= back) self.history.items[pos - back] else pad; + } + const raw_rows = try self.a.alloc(u16, rows * engram_cuda.input); + defer self.a.free(raw_rows); + + var slot: usize = 0; // index of the stream buffer x lives in + for (self.layers) |*layer| { + // Engram residual into the streams. + if (layer.engram) |*e| { + try e.table.gather(self.a, windows, raw_rows); + try sc.e_raw.uploadAsync(0, std.mem.sliceAsBytes(raw_rows), s.handle); + const out = sc.streams[(slot + 1) % 3].ptr; + try k.engram.forward(s, &k.gemm, e.w, .{ + .raw = sc.e_raw.ptr, + .normalized = sc.e_normalized, + .keys = sc.e_keys, + .value = sc.e_value, + .media = sc.media, + .state = x, + .output = out, + }, @intCast(rows), @intCast(rows), H, self.text.engram_fp8_embedding); + slot = (slot + 1) % 3; + x = out; + } + // Attention half. + const at = &layer.attention; + const hh: usize = at.heads; + try k.ihc.collapse(s, .{ .hidden = x, .projection = at.hc.project, .bias = at.hc.bias, .scale = at.hc.scale, .output = sc.collapsed, .post = sc.post }, self.hcShape(rows, 2 * S)); + try k.norms.addRmsTail(s, sc.collapsed, null, at.input_norm, sc.norm_tmp, sc.hidden, null, rows, H, eps, .{ .round = true }); + try k.gemm.run(s, sc.hidden, at.q_a, sc.q_raw, rows, Q, H, .bf16); + try k.norms.addRmsTail(s, sc.q_raw, null, at.q_norm, sc.q_tmp, sc.q_resid, null, rows, Q, eps, .{ .round = true }); + try k.gemm.run(s, sc.q_resid, at.q_b, sc.q, rows, hh * m.query_stride, Q, .bf16); + try k.gemm.run(s, sc.hidden, at.kv_a, sc.kv, rows, m.absorbed_stride, H, .bf16); + try k.gemm.run(s, sc.hidden, at.gate, sc.gate, rows, hh * m.value_width, H, .bf16); + const stride: usize = if (at.sliding) sliding_stride else sparse_stride; + try sc.slots.uploadAsync(0, std.mem.sliceAsBytes(if (at.sliding) keys_sliding else keys_sparse), s.handle); + try sc.counts.uploadAsync(0, std.mem.sliceAsBytes(if (at.sliding) counts_sliding else counts_sparse), s.handle); + const shape = try attn.Shape.init(@intCast(rows), at.heads, @intCast(stride)); + try mla.forward(k.project, k.attention, s, .{ + .query = sc.q, + .key_weights = at.key, + .value_weights = at.value, + .value_logits = sc.gate, + .positions = sc.positions.ptr, + .rotary_table = sc.table, + .kv = .{ .projection = sc.kv, .gain = at.kv_norm, .write_slots = sc.write_slots.ptr, .capacity = @intCast(self.capacity), .epsilon = eps }, + .attention = .{ + .query = sc.absorb, + .cache = at.cache.ptr, + .slots = sc.slots.ptr, + .counts = sc.counts.ptr, + .sinks = at.sinks, + .scratch = sc.attn_scratch, + .scratch_bytes = sc.attn_scratch_bytes, + .output = sc.latent_out, + }, + .values = sc.values, + }, shape, try self.text.rotary(if (at.sliding) .sliding_attention else .deepseek_sparse_attention)); + try k.gemm.run(s, sc.values, at.output, sc.branch, rows, H, hh * m.value_width, .bf16); + try k.norms.addRmsTail(s, sc.branch, null, at.output_norm, sc.norm_tmp, sc.branch_norm, null, rows, H, eps, .{ .round = true }); + const after_attn = sc.streams[(slot + 1) % 3].ptr; + try k.ihc.add(s, .{ .residual = x, .branch = sc.branch_norm, .post = sc.post, .output = after_attn }, self.hcShape(rows, 2 * S)); + slot = (slot + 1) % 3; + x = after_attn; + // Feed-forward half. + const f = &layer.feed; + try k.ihc.collapse(s, .{ .hidden = x, .projection = f.hc.project, .bias = f.hc.bias, .scale = f.hc.scale, .output = sc.collapsed, .post = sc.post }, self.hcShape(rows, 2 * S)); + try k.norms.addRmsTail(s, sc.collapsed, null, f.input_norm, sc.norm_tmp, sc.hidden, null, rows, H, eps, .{ .round = true }); + switch (f.mlp) { + .dense => |dn| { + try k.gemm.run(s, sc.hidden, dn.gate, sc.ff_gate, rows, D, H, .bf16); + try k.gemm.run(s, sc.hidden, dn.up, sc.ff_up, rows, D, H, .bf16); + try k.act.swiglu(s, sc.ff_gate, D, sc.ff_up, D, sc.ff_inner, null, rows, D); + try k.gemm.run(s, sc.ff_inner, dn.down, sc.shared, rows, H, D, .bf16); + try k.norms.addRmsTail(s, sc.shared, null, f.output_norm, sc.norm_tmp, sc.branch_norm, null, rows, H, eps, .{ .round = true }); + }, + .sparse => |sp| { + try k.gemm.run(s, sc.hidden, sp.latent_in, sc.latent, rows, L, H, .bf16); + try k.router.logits(s, sc.hidden, H, sp.router, sc.logits, rows, H, E); + try k.glue.topk(s, sc.logits, sp.router_bias, .{ .experts = E, .topk = K, .shared = false, .score = true, .normalize = true, .scale = self.text.routed_scaling_factor }, sc.picks, sc.probabilities, rows); + const y = try sp.routed.run(&k.experts, s, sc.latent, sc.picks, rows); + try k.glue.combine(s, y, .f32, sc.probabilities, sc.mix, .bf16, rows, K, L); + try k.gemm.run(s, sc.mix, sp.latent_out, sc.route_out, rows, H, L, .bf16); + try k.gemm.run(s, sc.hidden, sp.shared_gate, sc.ff_gate, rows, L, H, .bf16); + try k.gemm.run(s, sc.hidden, sp.shared_up, sc.ff_up, rows, L, H, .bf16); + try k.act.swiglu(s, sc.ff_gate, L, sc.ff_up, L, sc.ff_inner, null, rows, L); + try k.gemm.run(s, sc.ff_inner, sp.shared_down, sc.shared, rows, H, L, .bf16); + try k.norms.addRmsTail(s, sc.route_out, sc.shared, f.output_norm, sc.norm_tmp, sc.branch_norm, null, rows, H, eps, .{ .round = true }); + }, + } + const after_ff = sc.streams[(slot + 1) % 3].ptr; + try k.ihc.add(s, .{ .residual = x, .branch = sc.branch_norm, .post = sc.post, .output = after_ff }, self.hcShape(rows, 2 * S)); + slot = (slot + 1) % 3; + x = after_ff; + } + // Hyper head, final norm and LM head on the last row. + const last = x + (rows - 1) * S * H * 2; + try k.ihc.collapse(s, .{ .hidden = last, .projection = self.head_hc.project, .bias = self.head_hc.bias, .scale = self.head_hc.scale, .output = sc.head_hidden, .post = 0 }, self.hcShape(1, S)); + try k.norms.addRmsTail(s, sc.head_hidden, null, self.final_norm, sc.norm_tmp, sc.head_norm, null, 1, H, eps, .{ .round = true }); + try k.gemm.run(s, sc.head_norm, self.lm_head, sc.lm_logits, 1, self.text.vocab_size, H, .f32); + try s.synchronize(); + try cuda.memory.download(self.d, sc.lm_logits, std.mem.sliceAsBytes(logits_out)); + } +}; diff --git a/zig/src/families/hy4_flash/engram_cuda.zig b/zig/src/families/hy4_flash/engram_cuda.zig new file mode 100644 index 00000000000..e104c1ee23f --- /dev/null +++ b/zig/src/families/hy4_flash/engram_cuda.zig @@ -0,0 +1,62 @@ +//! Hy4-flash's CUDA Engram branch: optional FP8 round trip, per-head norm, value and per-stream keys, gated add. +const std = @import("std"); +const cuda = @import("cuda"); +const engram = @import("engram.zig"); +const ihc = @import("ihc.zig"); + +pub const head_width = 96; +pub const columns = engram.columns; +pub const input = columns * head_width; + +pub const Weights = struct { + lookup_gamma: u64, // BF16 [16, 96] + value: u64, // BF16 [hidden, 1536] + value_bias: u64, + value_gain: u64, // unified_pre_gamma + key: [ihc.streams]u64, // BF16 [hidden, 1536] each + key_bias: u64, // BF16 [4, hidden] + key_gain: u64, + query_gain: u64, + delta_gain: u64, // unified_per_hc_scales +}; + +pub const Buffers = struct { + raw: u64, // BF16 [gemm_rows, 1536], gathered rows + normalized: u64, // BF16 [gemm_rows, 1536] + keys: u64, // BF16 [4, gemm_rows, hidden] + value: u64, // BF16 [gemm_rows, hidden] + media: u64, // u32 [gemm_rows] + state: u64, // BF16 [gemm_rows, 4, hidden] + output: u64, // BF16 [gemm_rows, 4, hidden] +}; + +pub const Kernels = struct { + module: cuda.Module, + lookup_fn: cuda.Function, + apply_fn: cuda.Function, + + pub fn load(driver: *const cuda.Driver) !Kernels { + if (!cuda.kernels.available) return error.BuiltWithoutKernels; + var module = try cuda.Module.load(driver, cuda.kernels.hy4_engram); + errdefer module.unload(); + return .{ .module = module, .lookup_fn = try module.function("tf_hy4_engram_lookup"), .apply_fn = try module.function("tf_hy4_engram_apply") }; + } + + pub fn deinit(self: *Kernels) void { + self.module.unload(); + self.* = undefined; + } + + /// The Engram residual added to `rows` rows of four hidden streams. GEMMs run on the fixed `gemm_rows`. + pub fn forward(self: Kernels, s: cuda.Stream, gemm: *cuda.vit.Gemms, w: Weights, b: Buffers, rows: u32, gemm_rows: u32, hidden: u32, fp8: bool) !void { + if (rows == 0 or rows > gemm_rows) return error.BadHy4EngramRows; + var lookup: cuda.Args = .{}; + inline for (.{ b.raw, w.lookup_gamma, b.normalized, @as(u32, @intFromBool(fp8)) }) |x| lookup.add(x); + try cuda.launch.launch(self.lookup_fn, .{ .grid = .{ .x = columns, .y = gemm_rows }, .block = .{ .x = 32 } }, s, &lookup); + try gemm.run(s, b.normalized, w.value, b.value, gemm_rows, hidden, input, .bf16); + for (w.key, 0..) |key, i| try gemm.run(s, b.normalized, key, b.keys + i * @as(u64, gemm_rows) * hidden * 2, gemm_rows, hidden, input, .bf16); + var apply: cuda.Args = .{}; + inline for (.{ b.state, b.keys, w.key_bias, w.key_gain, w.query_gain, w.delta_gain, b.value, w.value_bias, w.value_gain, b.media, b.output, gemm_rows, hidden }) |x| apply.add(x); + try cuda.launch.launch(self.apply_fn, .{ .grid = .{ .x = ihc.streams, .y = rows }, .block = .{ .x = 128 } }, s, &apply); + } +}; diff --git a/zig/src/families/hy4_flash/exl3_weights.zig b/zig/src/families/hy4_flash/exl3_weights.zig new file mode 100644 index 00000000000..44ee8032ff6 --- /dev/null +++ b/zig/src/families/hy4_flash/exl3_weights.zig @@ -0,0 +1,82 @@ +//! Split routed experts from the standard Hy4-flash EXL3 checkpoint. +const std = @import("std"); +const core = @import("core"); +const Tensor = core.safetensors.Tensor; + +pub const Projection = struct { + parts: core.exl3_load.Parts, + geometry: core.exl3_layout.Group, +}; + +pub const Expert = struct { gate: Projection, up: Projection, down: Projection }; + +pub fn readExpert(source: anytype, layer: usize, expert: usize, latent: usize, intermediate: usize) !Expert { + return .{ + .gate = try read(source, layer, expert, "gate", latent, intermediate), + .up = try read(source, layer, expert, "up", latent, intermediate), + .down = try read(source, layer, expert, "down", intermediate, latent), + }; +} + +fn read(source: anytype, layer: usize, expert: usize, name: []const u8, k: usize, n: usize) !Projection { + var buf: [160]u8 = undefined; + const prefix = try std.fmt.bufPrint(&buf, "model.layers.{d}.mlp.experts.{d}.{s}_proj", .{ layer, expert, name }); + for ([_][]const u8{ "mcg", "bias", "weight", "su", "sv" }) |suffix| { + var full: [192]u8 = undefined; + if (source.has(try std.fmt.bufPrint(&full, "{s}.{s}", .{ prefix, suffix }))) + return error.UnsupportedHy4Expert; + } + return validate( + try tensor(source, prefix, "trellis"), + try tensor(source, prefix, "suh"), + try tensor(source, prefix, "svh"), + try tensor(source, prefix, "mul1"), + k, + n, + ); +} + +fn tensor(source: anytype, prefix: []const u8, suffix: []const u8) !Tensor { + var buf: [192]u8 = undefined; + return source.get(try std.fmt.bufPrint(&buf, "{s}.{s}", .{ prefix, suffix })); +} + +fn validate(trellis: Tensor, suh: Tensor, svh: Tensor, marker: Tensor, k: usize, n: usize) !Projection { + if (trellis.dtype != .i16 or trellis.rank != 3 or k % 128 != 0 or n % 128 != 0) + return error.BadHy4Trellis; + const g = try core.exl3_layout.Group.fromShape(trellis.shape[0..trellis.rank]); + if (g.k() != k or g.n() != n or trellis.bytes.len != g.trellisBytes()) + return error.BadHy4Trellis; + if (!suh.is(.f16, &.{k}) or !svh.is(.f16, &.{n}) or suh.bytes.len != 2 * k or svh.bytes.len != 2 * n) + return error.BadHy4ExpertScales; + if ((!marker.is(.i32, &.{}) and !marker.is(.i32, &.{1})) or marker.bytes.len != 4) + return error.BadHy4ExpertMarker; + if (try core.exl3_layout.fromMarker(std.mem.readInt(u32, marker.bytes[0..4], .little)) != .mul1) + return error.BadHy4ExpertMarker; + return .{ .parts = .{ .trellis = trellis, .suh = suh, .svh = svh }, .geometry = g }; +} + +fn fixed(dtype: core.safetensors.DType, shape: []const usize, bytes: []const u8) Tensor { + var out: Tensor = .{ .dtype = dtype, .rank = @intCast(shape.len), .shape = @splat(1), .bytes = bytes }; + @memcpy(out.shape[0..shape.len], shape); + return out; +} + +test "Hy4 orders EXL3 axes as input then output and requires fp16 scales and mul1" { + const t = std.testing; + const words: [8 * 16 * 64 * 2]u8 = @splat(0); + const input: [128 * 2]u8 = @splat(0); + const output: [256 * 2]u8 = @splat(0); + const magic = &.{ 0x2d, 0xd1, 0xdc, 0x83 }; + const trellis = fixed(.i16, &.{ 8, 16, 64 }, &words); + const suh = fixed(.f16, &.{128}, &input); + const svh = fixed(.f16, &.{256}, &output); + const marker = fixed(.i32, &.{1}, magic); + const p = try validate(trellis, suh, svh, marker, 128, 256); + try t.expectEqual(@as(u32, 8), p.geometry.k2()); + _ = try validate(trellis, suh, svh, fixed(.i32, &.{}, magic), 128, 256); + try t.expectError(error.BadHy4Trellis, validate(trellis, suh, svh, marker, 256, 128)); + try t.expectError(error.BadHy4ExpertScales, validate(trellis, suh, suh, marker, 128, 256)); + try t.expectError(error.BadHy4ExpertMarker, validate(trellis, suh, svh, fixed(.u32, &.{1}, magic), 128, 256)); + try t.expectError(error.BadHy4ExpertMarker, validate(trellis, suh, svh, fixed(.i32, &.{}, &.{ 0xed, 0x1f, 0xac, 0xcb }), 128, 256)); +} diff --git a/zig/src/families/hy4_flash/host_tests.zig b/zig/src/families/hy4_flash/host_tests.zig index c5e1b265d1f..996eec1919c 100644 --- a/zig/src/families/hy4_flash/host_tests.zig +++ b/zig/src/families/hy4_flash/host_tests.zig @@ -12,6 +12,8 @@ test { _ = @import("rank_weights.zig"); _ = @import("index_recall.zig"); _ = @import("forward.zig"); + _ = @import("exl3_weights.zig"); + if (@import("builtin").os.tag == .linux) _ = @import("bf16_rows_test.zig"); } fn tensor(dtype: core.checkpoint_host.DType, rows: usize, width: usize, bytes: []const u8) core.checkpoint_host.Tensor { diff --git a/zig/src/families/hy4_flash/index_cuda.zig b/zig/src/families/hy4_flash/index_cuda.zig new file mode 100644 index 00000000000..f56cb72f8d0 --- /dev/null +++ b/zig/src/families/hy4_flash/index_cuda.zig @@ -0,0 +1,116 @@ +//! Hy4-flash's CUDA compressed indexer: cache token keys, pool closed groups, rank them, keep 511 plus its own. +const std = @import("std"); +const cuda = @import("cuda"); +const mla = @import("mla_cuda.zig"); +const rotary = @import("rope.zig"); +const recall = @import("index_recall.zig"); +const recall_cuda = @import("index_recall_cuda.zig"); +const groups = @import("index_groups.zig"); + +pub const heads = recall.heads; +pub const width = recall.width; +pub const nope = width - 2 * rotary.pairs; +pub const budget_groups: u32 = 512; + +/// Device weights: BF16 projections and norm, FP32 pooling parameters. +pub const Weights = struct { + token_keys: u64, // [128, hidden] + token_norm: u64, // [128] + query: u64, // [16 * 128, q_rank] + head_weights: u64, // [16, hidden] + values: u64, // f32 [128, 128] + gates: u64, // f32 [128, 128] + bias: u64, // f32 [4, 128] + norm: u64, // f32 [128] +}; + +pub const Indexer = struct { + pool: cuda.Module, + groups_fn: cuda.Function, + select_kernels: recall_cuda.Kernels, + + pub fn load(driver: *const cuda.Driver) !Indexer { + if (!cuda.kernels.available) return error.BuiltWithoutKernels; + var pool = try cuda.Module.load(driver, cuda.kernels.hy4_indexpool); + errdefer pool.unload(); + return .{ + .pool = pool, + .groups_fn = try pool.function("tf_hy4_index_groups"), + .select_kernels = try recall_cuda.Kernels.load(driver), + }; + } + + pub fn deinit(self: *Indexer) void { + self.select_kernels.deinit(); + self.pool.unload(); + self.* = undefined; + } + + pub const Keys = struct { + hidden: u64, // BF16 [gemm_rows, hidden], zero past the active rows + gemm_rows: usize, // fixed per lane class so cuBLASLt keeps one reduction order + count: usize, + projected: u64, // BF16 [gemm_rows, 128] + norm_tmp: u64, + staged: u64, // BF16 [gemm_rows, 128] + first_slot: usize, + }; + + /// Normalized BF16 token keys of the active rows into contiguous cache slots from `first_slot`. + pub fn cacheKeys(_: Indexer, s: cuda.Stream, gemm: *cuda.vit.Gemms, norms: *const cuda.norms.Norms, w: Weights, b: Keys, cache: cuda.DeviceBuffer, hidden_size: usize, eps: f32) !void { + if (b.count == 0 or b.count > b.gemm_rows) return error.BadHy4IndexRows; + try gemm.run(s, b.hidden, w.token_keys, b.projected, b.gemm_rows, width, hidden_size, .bf16); + try norms.addRmsTail(s, b.projected, null, w.token_norm, b.norm_tmp, b.staged, null, b.gemm_rows, width, eps, .{ .round = true }); + try cache.copyFrom(b.first_slot * width * 2, b.staged, b.count * width * 2, s.handle); + } + + /// Pool, normalize and rotate `count` closed groups from `first_group` (positions: each group's first token). + pub fn poolGroups(self: Indexer, s: cuda.Stream, project: mla.Projections, w: Weights, cache: u64, arena: u64, first_group: u32, count: u32, positions: u64, table: u64, p: rotary.Parameters, eps: f32) !void { + if (count == 0) return; + var args: cuda.Args = .{}; + inline for (.{ cache, w.values, w.gates, w.bias, w.norm, arena, first_group, eps }) |x| args.add(x); + try cuda.launch.launch(self.groups_fn, .{ .grid = .{ .x = count }, .block = .{ .x = width } }, s, &args); + try project.rotaryTable(s, positions, table, count, p); + const rope_base = arena + (@as(u64, first_group) * width + nope) * 2; + try project.rotate(s, rope_base, table, rope_base, .{ .rows = count, .heads = 1, .input_stride = width, .output_stride = width }); + } + + pub const Select = struct { + q_resid: u64, // BF16 [gemm_rows, q_rank], the q_a_layernorm output + hidden: u64, // BF16 [gemm_rows, hidden] + gemm_rows: usize, + positions: u64, // i32 [rows, 3] + table: u64, // BF16 [rows, 64] + query: u64, // BF16 [rows, 16 * 128] + head_weights: u64, // BF16 [rows, 16] + arena: u64, + rows: u64, // recall.Row [rows] + scores: u64, + tokens: u64, + counts: u64, + }; + + /// Rotated query heads, head weights, closed-group scores and the recalled slot list of each row. + pub fn select(self: Indexer, s: cuda.Stream, gemm: *cuda.vit.Gemms, project: mla.Projections, w: Weights, b: Select, shape: recall.Shape, q_rank: usize, hidden_size: usize, p: rotary.Parameters) !void { + if (shape.rows > b.gemm_rows) return error.BadHy4IndexRows; + try gemm.run(s, b.q_resid, w.query, b.query, b.gemm_rows, heads * width, q_rank, .bf16); + try project.rotaryTable(s, b.positions, b.table, shape.rows, p); + const rope_base = b.query + nope * 2; + try project.rotate(s, rope_base, b.table, rope_base, .{ .rows = shape.rows, .heads = heads, .input_stride = width, .output_stride = width }); + try gemm.run(s, b.hidden, w.head_weights, b.head_weights, b.gemm_rows, heads, hidden_size, .bf16); + try self.select_kernels.run(s, .{ + .query = b.query, + .keys = b.arena, + .weights = b.head_weights, + .rows = b.rows, + .scores = b.scores, + .tokens = b.tokens, + .counts = b.counts, + }, shape); + } +}; + +/// Closed groups a pass of `count` new slots after `previous` cached slots makes poolable. +pub fn closedBy(previous: usize, count: usize) !groups.Append { + return groups.append(previous, count); +} diff --git a/zig/src/families/hy4_flash/mla_weights.zig b/zig/src/families/hy4_flash/mla_weights.zig index 05be7294949..104bcdc34e1 100644 --- a/zig/src/families/hy4_flash/mla_weights.zig +++ b/zig/src/families/hy4_flash/mla_weights.zig @@ -63,6 +63,13 @@ fn split(a: std.mem.Allocator, input: Input, count: usize) !Weights { return .{ .key = keys, .value = values }; } +/// Split contiguous BF16 kv_b rows for the selected heads without changing their values. +pub fn splitBf16(a: std.mem.Allocator, raw: []const u8, count: usize) !Weights { + if (count == 0 or count > 64 or raw.len != count * per_head * latent * 2) + return error.BadHy4MlaWeight; + return split(a, .{ .bf16 = raw }, count); +} + /// The owning rank reads only its selected heads. DFly2 reads its own BF16 projection when sharing target KV. pub fn read(a: std.mem.Allocator, model: *loader.Loaded, kind: loader.Attention, layer: u32, range: HeadRange) !Weights { const index = try model.attentionTargetLayer(kind, layer); @@ -88,7 +95,7 @@ pub fn read(a: std.mem.Allocator, model: *loader.Loaded, kind: loader.Attention, .draft => { const raw = try model.checkpoint.expect(weight_key, .bf16, &.{ rows, latent }); const selected = try core.quant.slice.takeRows(a, raw, &.{span}); - return split(a, .{ .bf16 = selected.bytes }, range.count); + return splitBf16(a, selected.bytes, range.count); }, .target => { const word_count = latent * @as(usize, model.bits) / 32; diff --git a/zig/src/families/hy4_flash/moe_exl3_cuda.zig b/zig/src/families/hy4_flash/moe_exl3_cuda.zig new file mode 100644 index 00000000000..d84a955a64a --- /dev/null +++ b/zig/src/families/hy4_flash/moe_exl3_cuda.zig @@ -0,0 +1,102 @@ +//! Standard MUL1 routed experts for the Hy4 latent branch. +const std = @import("std"); +const cuda = @import("cuda"); +const weights = @import("exl3_weights.zig"); +const exl3 = cuda.exl3_experts; +const upload = cuda.exl3_upload; + +pub const Route = struct { + hidden: u64, + width: usize, + router: u64, + bias: u64, + logits: u64, + picks: u64, + probabilities: u64, + scale: f32, + output: u64, +}; + +pub const Routed = struct { + layer: exl3.Layer, + scratch: exl3.Scratch, + + pub fn init( + owner: *upload.Uploader, + experts: []const weights.Expert, + latent: usize, + intermediate: usize, + rows: usize, + slots: usize, + limit: f32, + ) !Routed { + if (experts.len == 0 or experts.len > 512 or rows == 0 or slots == 0 or slots > 32 or + rows > 16384 / slots or !std.math.isFinite(limit) or limit <= 0) + return error.BadHy4ExpertShape; + _ = try exl3.plan(latent, intermediate, true); + _ = try exl3.plan(intermediate, latent, false); + const a = owner.gpa; + const projections = try a.alloc(upload.Proj, 3 * experts.len); + defer a.free(projections); + const gate = projections[0..experts.len]; + const up = projections[experts.len..][0..experts.len]; + const down = projections[2 * experts.len ..]; + for (experts, gate, up, down) |e, *g, *u, *d| { + g.* = try projection(e.gate, latent, intermediate); + u.* = try projection(e.up, latent, intermediate); + d.* = try projection(e.down, intermediate, latent); + } + const mark = owner.bufs.items.len; + errdefer owner.rollback(mark); + const layer = try upload.layer(owner, a, latent, intermediate, .mul1, limit, 0, gate, up, down); + const size = try exl3.scratchBytes(layer, rows, slots); + const space = try a.alloc(u8, size); + defer a.free(space); + @memset(space, 0); + const base = try owner.dev(space); + return .{ .layer = layer, .scratch = try exl3.scratch(base, layer, rows, slots) }; + } + + pub fn forward( + self: Routed, + kernels: *const exl3.Experts, + router: *const cuda.route_rows.RouteRows, + glue: *const cuda.moe_glue.MoeGlue, + stream: cuda.Stream, + latent: u64, + rows: usize, + route: Route, + ) !void { + const slots = self.scratch.slots; + if (rows == 0 or rows > self.scratch.rows or slots > self.layer.experts or + route.width == 0 or !std.math.isFinite(route.scale) or route.scale <= 0) + return error.BadHy4Route; + try router.logits(stream, route.hidden, route.width, route.router, route.logits, rows, route.width, self.layer.experts); + try glue.topk(stream, route.logits, route.bias, .{ + .experts = self.layer.experts, + .topk = slots, + .score = true, + .shared = false, + .normalize = true, + .scale = route.scale, + }, route.picks, route.probabilities, rows); + const output = try self.run(kernels, stream, latent, route.picks, rows); + try glue.combine(stream, output, .f32, route.probabilities, route.output, .f32, rows, slots, self.layer.dims); + } + + pub fn run(self: Routed, kernels: *const exl3.Experts, stream: cuda.Stream, x: u64, picks: u64, rows: usize) !u64 { + if (rows == 0 or rows > self.scratch.rows) return error.BadHy4ExpertRows; + try kernels.runSlots(stream, self.layer, x, self.layer.dims, .bf16, picks, rows, self.scratch); + return self.scratch.y; + } +}; + +fn projection(p: weights.Projection, k: usize, n: usize) !upload.Proj { + if (p.geometry.k() != k or p.geometry.n() != n) return error.BadHy4ExpertShape; + return .{ + .trellis = p.parts.trellis.bytes, + .suh = p.parts.suh.bytes, + .svh = p.parts.svh.bytes, + .k2 = p.geometry.k2(), + }; +} diff --git a/zig/src/families/idol/cuda.zig b/zig/src/families/idol/cuda.zig index ea600075b4e..89bcad40c4f 100644 --- a/zig/src/families/idol/cuda.zig +++ b/zig/src/families/idol/cuda.zig @@ -1,4 +1,4 @@ -//! Idol's denoiser on CUDA: driven by tf-idol-cuda beside the lane engine, as the Metal family is by tf-idol. +//! Idol's denoiser and decoders on CUDA: driven by tf-idol and tf-idol-decode beside the lane engine, as on Metal. pub const config = @import("config.zig"); pub const host = @import("host.zig"); pub const reference = @import("reference.zig"); @@ -8,12 +8,27 @@ pub const Condition = @import("cuda_model.zig").Condition; pub const Timing = @import("cuda_model.zig").Timing; pub const seconds = @import("cuda_model.zig").seconds; pub const admitted = @import("cuda_model.zig").admitted; +pub const decoder_config = @import("decoder_config.zig"); +pub const decoder_kernels = @import("cuda_decoder_kernels.zig"); +pub const octree = @import("octree.zig"); +pub const gaussian = @import("gaussian.zig"); +pub const decode = @import("decode.zig"); +pub const decode_reference = @import("decode_reference.zig"); +pub const Decoder = @import("cuda_decoder.zig").Decoder; test { _ = @import("cuda_kernels.zig"); _ = @import("cuda_gemm.zig"); _ = @import("cuda_model.zig"); _ = @import("cuda_weights.zig"); + _ = @import("cuda_decoder.zig"); + _ = @import("cuda_decoder_kernels.zig"); + _ = @import("cuda_decoder_weights.zig"); + _ = decoder_config; + _ = octree; + _ = gaussian; + _ = decode; + _ = decode_reference; _ = config; _ = host; _ = reference; diff --git a/zig/src/families/idol/cuda_decoder.zig b/zig/src/families/idol/cuda_decoder.zig new file mode 100644 index 00000000000..fe3aa54c2b8 --- /dev/null +++ b/zig/src/families/idol/cuda_decoder.zig @@ -0,0 +1,324 @@ +//! Idol's two decoders on CUDA as decoder.zig runs them on Metal: idol.cu's linears, norms, attention, and our steps. +const std = @import("std"); +const cuda = @import("cuda"); +const dc = @import("decoder_config.zig"); +const ks = @import("cuda_kernels.zig"); +const dk = @import("cuda_decoder_kernels.zig"); +const dw = @import("cuda_decoder_weights.zig"); +const gm = @import("cuda_gemm.zig"); +const model = @import("cuda_model.zig"); +const octree = @import("octree.zig"); +const gaussian = @import("gaussian.zig"); + +const H = dc.hidden; +const F = dc.ffn; +const C = dc.context_rows; +const scale: f32 = 1.0 / 8.0; + +pub const Timing = struct { wall: f64, gpu: f64 }; + +/// The scratch's parts for `cap` rows in bytes, in the order of Decoder's views. +fn parts(cap: usize) [16]usize { + return .{ + cap * H * 2, cap * H * 2, cap * 3 * H * 2, cap * H * 2, C * 2 * H * 2, cap * H * 2, + cap * H * 2, cap * F * 2, cap * F * 4, cap * H * 4, cap * H * 4, cap * dc.raw_width * 4, + cap * 3 * 4, C * dc.context_channels * 2, dc.max_level * 6 * H * 2, H * 4 + H * 2 + 256 * 4, + }; +} + +/// Device scratch bytes for `cap` rows (anchors), each part 256-aligned. +pub fn scratchBytes(cap: usize) usize { + var total: usize = 0; + for (parts(cap)) |n| total += std.mem.alignForward(usize, n, 256); + return total; +} + +pub const Decoder = struct { + gpa: std.mem.Allocator, + d: *const cuda.Driver, + stream: cuda.Stream, + k: ks.Kernels, + dk: dk.Kernels, + gemms: gm.Gemms, + w: *dw.Weights, + scratch: cuda.DeviceBuffer, + marks: [2]cuda.Event, + cap: usize, + // fp16 rows: stream, norm, self qkv, cross q, a block's to_kv [8192, 2048], attention, projection, GELU rows + x: u64 = 0, + xn: u64 = 0, + qkv: u64 = 0, + q: u64 = 0, + kv: u64 = 0, + att: u64 = 0, + y: u64 = 0, + u: u64 = 0, + /// a block linear's fp32 sums before its bias + acc: u64 = 0, + /// fp32 rows: the stem's sums, then input_layer's (and the head's LayerNorm); the head's outputs; the points + e32: u64 = 0, + f32b: u64 = 0, + out: u64 = 0, + pts: u64 = 0, + /// the latent [8192, 16] in fp16 + ctx: u64 = 0, + /// each level's modulation [8][6][1024] fp16 + mods: u64 = 0, + /// fp32 zeros [1024], fp16 ones [1024], then the point embedding's frequencies [170] + consts: u64 = 0, + levels_ready: bool = false, + mods_host: [dc.max_level]octree.Mods = undefined, + freqs_host: [dc.pe_freqs]f32 = undefined, + /// The stream's rows downloaded for `octreeRows`. + rows_host: []f16 = &.{}, + + pub const seconds = model.seconds; + + /// The decoders of snapshot folder `dir` on `ctx`'s GPU, with scratch for up to `max_anchors` anchors. + pub fn load(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: []const u8, max_anchors: usize) !*Decoder { + const sm = try ctx.capability(); + if (!model.admitted(sm)) { + var buf: [256]u8 = undefined; + const name = ctx.name(&buf) catch "this GPU"; + std.log.err("idol: {s} (sm_{d}) is not a GPU this family admits; it runs on sm_120 and sm_121 alone", .{ name, sm }); + return error.UncheckedGpu; + } + if (max_anchors == 0 or max_anchors > dc.max_anchors) return error.AnchorCount; + const d = ctx.d; + const t = try gpa.create(Decoder); + errdefer gpa.destroy(t); + t.* = .{ .gpa = gpa, .d = d, .stream = undefined, .k = undefined, .dk = undefined, .gemms = undefined, .w = undefined, .scratch = undefined, .marks = undefined, .cap = max_anchors }; + t.rows_host = try gpa.alloc(f16, max_anchors * H); + errdefer gpa.free(t.rows_host); + t.stream = try cuda.Stream.init(d, false); + errdefer t.stream.deinit(); + t.k = try ks.Kernels.load(d); + errdefer t.k.unload(); + t.dk = try dk.Kernels.load(d); + errdefer t.dk.unload(); + t.gemms = try gm.Gemms.init(gpa, d); + errdefer t.gemms.deinit(); + t.w = try dw.load(gpa, io, d, dir); + errdefer { + t.w.deinit(); + gpa.destroy(t.w); + } + t.scratch = try cuda.DeviceBuffer.alloc(d, scratchBytes(max_anchors)); + errdefer t.scratch.free(); + t.marks[0] = try cuda.Event.init(d, true); + errdefer t.marks[0].deinit(); + t.marks[1] = try cuda.Event.init(d, true); + errdefer t.marks[1].deinit(); + var at: usize = t.scratch.ptr; + const views = [_]*u64{ &t.x, &t.xn, &t.qkv, &t.q, &t.kv, &t.att, &t.y, &t.u, &t.acc, &t.e32, &t.f32b, &t.out, &t.pts, &t.ctx, &t.mods, &t.consts }; + for (views, parts(max_anchors)) |view, n| { + view.* = at; + at += std.mem.alignForward(usize, n, 256); + } + const zero_row: [H]f32 = @splat(0); + const one_row: [H]f16 = @splat(1); + octree.pointFreqs(&t.freqs_host); + try t.upload(t.zeros(), std.mem.sliceAsBytes(&zero_row)); + try t.upload(t.ones(), std.mem.sliceAsBytes(&one_row)); + try t.upload(t.freqs(), std.mem.sliceAsBytes(&t.freqs_host)); + return t; + } + + pub fn deinit(t: *Decoder) void { + for (&t.marks) |*m| m.deinit(); + t.scratch.free(); + t.w.deinit(); + t.gpa.destroy(t.w); + t.gemms.deinit(); + t.dk.unload(); + t.k.unload(); + t.stream.deinit(); + t.gpa.free(t.rows_host); + t.gpa.destroy(t); + } + + fn upload(t: *const Decoder, at: u64, bytes: []const u8) !void { + try t.d.check(t.d.api.cuMemcpyHtoDAsync_v2(at, bytes.ptr, bytes.len, t.stream.handle), "cuMemcpyHtoDAsync"); + try t.stream.synchronize(); + } + + fn download(t: *const Decoder, out: []u8, at: u64) !void { + try t.d.check(t.d.api.cuMemcpyDtoHAsync_v2(out.ptr, at, out.len, t.stream.handle), "cuMemcpyDtoHAsync"); + try t.stream.synchronize(); + } + + fn zeros(t: *const Decoder) u64 { + return t.consts; + } + + fn ones(t: *const Decoder) u64 { + return t.consts + H * 4; + } + + fn freqs(t: *const Decoder) u64 { + return t.consts + H * 4 + H * 2; + } + + /// Level `level`'s (1 to 8) modulation part `part` (0 shift, 1 one plus scale, 2 gate; 3 to 5 the MLP's). + fn mod(t: *const Decoder, level: usize, part: usize) u64 { + return t.mods + ((level - 1) * 6 + part) * H * 2; + } + + /// The point embedding's frequencies as this decoder computes them. + pub fn pointFreqs(t: *const Decoder) []const f32 { + return &t.freqs_host; + } + + /// The activation's fixed inputs from decoder_gs.safetensors and config.json. + pub fn params(t: *const Decoder) gaussian.Params { + return .{ .rep = t.w.rep, .base_offset_scale = t.w.base_offset_scale, .perturbation = t.w.perturbation }; + } + + /// Level `level`'s modulation as the blocks read it. + pub fn levelMods(t: *const Decoder, level: usize) []const f16 { + return @as([*]const f16, @ptrCast(&t.mods_host[level - 1]))[0 .. 6 * H]; + } + + /// The latent both decoders attend to: [8192, 16] fp32, cast to fp16 as the SDK's `cond.type(fp16)`. + pub fn setLatent(t: *Decoder, latent: []const f32) !void { + if (latent.len != C * dc.context_channels) return error.LatentRows; + const half = try t.gpa.alloc(f16, latent.len); + defer t.gpa.free(half); + for (half, latent) |*o, v| o.* = @floatCast(v); + try t.upload(t.ctx, std.mem.sliceAsBytes(half)); + if (!t.levels_ready) { + for (&t.mods_host, 1..) |*m, l| octree.levelMods(t.w.level, @intCast(l), m); + try t.upload(t.mods, std.mem.sliceAsBytes(&t.mods_host)); + t.levels_ready = true; + } + } + + /// The octree decoder's logits [rows, 8] for parent centres [rows, 3] at `level` (1 to 8). + pub fn octreeLogits(t: *Decoder, centres: []const f32, level: usize, logits: []f32) !Timing { + const rows = centres.len / 3; + if (!t.levels_ready) return error.NoLatent; + if (rows == 0 or rows > t.cap or centres.len != rows * 3 or logits.len != rows * dc.children or level < 1 or level > dc.max_level) return error.OctreeRows; + const started = seconds(); + try t.upload(t.pts, std.mem.sliceAsBytes(centres)); + try t.marks[0].record(t.stream); + try t.stem(t.w.octree_stem, rows); + for (t.w.octree) |b| try t.octreeBlock(b, level, rows); + try t.head(t.w.octree_stem, rows, dc.children); + return t.finish(std.mem.sliceAsBytes(logits), started); + } + + /// The octree stream [rows, 1024] fp16 after its stem (`block` null), or after block `block` alone run on `input`. + pub fn octreeRows(t: *Decoder, centres: []const f32, input: []const f16, level: usize, block: ?usize) ![]const f16 { + const rows = centres.len / 3; + if (!t.levels_ready) return error.NoLatent; + if (rows == 0 or rows > t.cap or input.len != rows * H or level < 1 or level > dc.max_level) return error.OctreeRows; + try t.upload(t.pts, std.mem.sliceAsBytes(centres)); + try t.upload(t.x, std.mem.sliceAsBytes(input)); + if (block) |i| try t.octreeBlock(t.w.octree[i], level, rows) else try t.stem(t.w.octree_stem, rows); + const out = t.rows_host[0 .. rows * H]; + try t.download(std.mem.sliceAsBytes(out), t.x); + return out; + } + + /// One octree block: cross attention to the latent, then the MLP, each modulated by the level. + fn octreeBlock(t: *Decoder, b: dw.OctreeBlock, level: usize, rows: usize) !void { + const s = t.stream; + try ks.norm(&t.k, s, t.x, 0, 0, t.mod(level, 1), t.mod(level, 0), t.xn, rows, dc.block_eps, .modulated); + try t.cross(b.cross, rows); + try ks.gateAdd(&t.k, s, t.x, t.y, t.mod(level, 2), rows, H); + try ks.norm(&t.k, s, t.x, 0, 0, t.mod(level, 4), t.mod(level, 3), t.xn, rows, dc.block_eps, .modulated); + try t.mlp(b.mlp, rows); + try ks.gateAdd(&t.k, s, t.x, t.y, t.mod(level, 5), rows, H); + } + + /// The Gaussian decoder's raw rows [anchors, 480] fp32 for anchors [anchors, 3]. + pub fn gaussianRows(t: *Decoder, anchors: []const f32, raw: []f32) !Timing { + const rows = anchors.len / 3; + if (!t.levels_ready) return error.NoLatent; + if (rows == 0 or rows > t.cap or anchors.len != rows * 3 or raw.len != rows * dc.raw_width) return error.AnchorRows; + const started = seconds(); + try t.upload(t.pts, std.mem.sliceAsBytes(anchors)); + try t.marks[0].record(t.stream); + try t.stem(t.w.gaussian_stem, rows); + for (t.w.gaussian) |b| try t.gaussianBlock(b, rows); + try t.head(t.w.gaussian_stem, rows, dc.raw_width); + return t.finish(std.mem.sliceAsBytes(raw), started); + } + + /// One Gaussian decoder block: self attention over the anchors, cross attention to the latent, then the MLP. + fn gaussianBlock(t: *Decoder, b: dw.GaussianBlock, rows: usize) !void { + const s = t.stream; + try t.selfAttention(b.self_attn, rows); + try ks.norm(&t.k, s, t.x, b.norm2, b.norm2_b, t.ones(), t.ones(), t.xn, rows, dc.block_eps, .affine); + try t.cross(b.cross, rows); + try ks.gateAdd(&t.k, s, t.x, t.y, t.ones(), rows, H); + try ks.norm(&t.k, s, t.x, 0, 0, t.ones(), t.ones(), t.xn, rows, dc.block_eps, .plain); + try t.mlp(b.mlp, rows); + try ks.gateAdd(&t.k, s, t.x, t.y, t.ones(), rows, H); + } + + /// x += to_out(attention(q_rms, k_rms, v of to_qkv(LayerNorm(x)))) over the anchors, by idol.cu's attention. + fn selfAttention(t: *Decoder, sa: dw.SelfAttention, rows: usize) !void { + const s = t.stream; + try ks.norm(&t.k, s, t.x, 0, 0, t.ones(), t.ones(), t.xn, rows, dc.block_eps, .plain); + try t.linear(t.xn, sa.qkv, sa.qkv_b, t.qkv, rows, 3 * H, H, false); + try dk.rmsHeads(&t.dk, s, t.qkv, sa.gq, t.qkv, rows, 3 * H, 0); + try dk.rmsHeads(&t.dk, s, t.qkv, sa.gk, t.qkv, rows, 3 * H, H); + try ks.attention(&t.k, s, t.qkv, t.att, rows, dc.heads, scale); + try t.linear(t.att, sa.out, sa.out_b, t.y, rows, H, H, false); + try ks.gateAdd(&t.k, s, t.x, t.y, t.ones(), rows, H); + } + + /// x [rows, 1024] fp16 = fp16(input_layer(in_proj(p) + pe(p))), all fp32 before the cast. + fn stem(t: *Decoder, st: dw.Stem, rows: usize) !void { + try dk.embed(&t.dk, t.stream, t.pts, st.in_w, st.in_b, t.freqs(), t.e32, rows); + try t.gemms.run(t.stream, .f32, t.e32, st.input, t.f32b, rows, H, H); + try dk.toHalf(&t.dk, t.stream, t.f32b, st.input_b, t.x, rows, H); + } + + /// out [rows, n] fp32 = out_proj(F.layer_norm(x)) with the stream cast to fp32. + fn head(t: *Decoder, st: dw.Stem, rows: usize, n: usize) !void { + try ks.norm32(&t.k, t.stream, t.x, t.zeros(), t.zeros(), t.f32b, rows, dc.out_eps, .modulated); + try t.gemms.run(t.stream, .f32, t.f32b, st.out, t.out, rows, n, H); + try ks.bias32(&t.k, t.stream, t.out, st.out_b, rows, n); + } + + /// y = to_out(attention(q_rms(to_q(xn)), k_rms(to_kv(latent)), v)) over the latent's 8192 rows; fp32 for few rows. + fn cross(t: *Decoder, c: dw.Cross, rows: usize) !void { + const s = t.stream; + try t.linear(t.xn, c.q, c.q_b, t.q, rows, H, H, false); + try dk.rmsHeads(&t.dk, s, t.q, c.gq, t.q, rows, H, 0); + try dk.kv(&t.dk, s, t.ctx, c.kv, c.kv_b, t.kv, C); + try dk.rmsHeads(&t.dk, s, t.kv, c.gk, t.kv, C, 2 * H, 0); + try dk.attention(&t.dk, s, t.q, H, t.kv, 2 * H, t.att, rows, C, scale); + try t.linear(t.att, c.out, c.out_b, t.y, rows, H, H, false); + } + + /// y = down(GELU(up(xn))). + fn mlp(t: *Decoder, m: dw.Mlp, rows: usize) !void { + try t.linear(t.xn, m.up, m.up_b, t.u, rows, F, H, true); + try t.linear(t.u, m.down, m.down_b, t.y, rows, H, F, false); + } + + /// y fp16 [rows, n] = fp16(x w^T + b) from fp32 sums, then fp16(GELU) when `gelu`. + fn linear(t: *Decoder, x: u64, w: u64, b: u64, y: u64, rows: usize, n: usize, k: usize, gelu: bool) !void { + try t.gemms.run(t.stream, .f16, x, w, t.acc, rows, n, k); + try ks.bias(&t.k, t.stream, t.acc, b, y, rows, n, gelu); + } + + /// The pass's end marked, its fp32 outputs downloaded, and its wall and GPU time. + fn finish(t: *Decoder, out: []u8, started: f64) !Timing { + try t.marks[1].record(t.stream); + try t.download(out, t.out); + const gpu = @as(f64, try cuda.Event.elapsedMs(t.marks[0], t.marks[1])) / 1000; + return .{ .wall = seconds() - started, .gpu = gpu }; + } +}; + +test "decoder scratch: a million Gaussians' anchors fit, to_kv's rows beside the fewest, c_int indices" { + try std.testing.expect(scratchBytes(dc.max_anchors) < 2 << 30); + try std.testing.expect(scratchBytes(1) > C * 2 * H * 2); + // the kernels and cuBLASLt index a block's widest rows as c_int + try std.testing.expect(dc.max_anchors * F < std.math.maxInt(c_int)); + try std.testing.expect(parts(1).len == 16); +} diff --git a/zig/src/families/idol/cuda_decoder_kernels.zig b/zig/src/families/idol/cuda_decoder_kernels.zig new file mode 100644 index 00000000000..b26835da2d2 --- /dev/null +++ b/zig/src/families/idol/cuda_decoder_kernels.zig @@ -0,0 +1,137 @@ +//! The decoders' own CUDA kernels (idol_decoder.cu); their projections, norms and self attention are idol.cu's. +const std = @import("std"); +const cuda = @import("cuda"); + +pub const hidden = 1024; +pub const heads = 16; +pub const head_dim = 64; +/// The latent the cross attention reads: 8,192 rows of 16 channels. +pub const context_rows = 8192; + +/// Query rows the fp32 short form takes: torch on MPS (the cases' SDK) runs its fp32 vector kernel up to 8. +pub const few_rows = 8; +/// The short form's keys: 256 threads of 32 each. +pub const few_keys = 256 * 32; + +/// The tiled attention's geometry: idol.cu's (8 warps of 16 query rows, two buffers of 64 K and V rows). +pub const attention_warps = 8; +pub const attention_smem: u32 = 2 * 2 * 64 * (head_dim / 8 + 1) * 16; + +pub const Kernels = struct { + mod: cuda.Module, + embed: cuda.Function, + half: cuda.Function, + kv: cuda.Function, + heads: cuda.Function, + attention: cuda.Function, + few: 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.idol_decoder); + errdefer mod.unload(); + var k: Kernels = undefined; + k.mod = mod; + inline for (.{ "embed", "half", "kv", "heads", "attention", "few" }) |n| + @field(k, n) = try mod.function("tf_idol_dec_" ++ n); + return k; + } + + pub fn unload(k: *Kernels) void { + k.mod.unload(); + } +}; + +fn int(x: usize) c_int { + return @intCast(x); +} + +fn ceil(n: usize, d: usize) u32 { + return @intCast((n + d - 1) / d); +} + +fn go(f: cuda.Function, s: cuda.Stream, grid: cuda.Dim3, a: *cuda.Args) !void { + try cuda.launch.launch(f, .{ .grid = grid, .block = .{ .x = 256 } }, s, a); +} + +fn addAll(a: *cuda.Args, ptrs: []const u64) void { + for (ptrs) |p| a.add(p); +} + +/// h [rows, 1024] fp32 = in_proj(p) + the points' sinusoidal embedding, p [rows, 3] fp32, frequencies [170]. +pub fn embed(k: *const Kernels, s: cuda.Stream, p: u64, w: u64, b: u64, freqs: u64, h: u64, rows: usize) !void { + var a: cuda.Args = .{}; + addAll(&a, &.{ p, w, b, freqs, h }); + a.add(int(rows)); + try go(k.embed, s, .{ .x = @intCast(rows), .y = ceil(hidden, 256) }, &a); +} + +/// o [rows, width] fp16 = y + b by column, y and b fp32. +pub fn toHalf(k: *const Kernels, s: cuda.Stream, y: u64, b: u64, o: u64, rows: usize, width: usize) !void { + var a: cuda.Args = .{}; + addAll(&a, &.{ y, b, o }); + for ([_]usize{ width, rows }) |v| a.add(int(v)); + try go(k.half, s, .{ .x = @intCast(rows), .y = ceil(width, 256) }, &a); +} + +/// kv [rows, 2048] fp16 = to_kv of the fp16 latent rows [rows, 16] (fp16 weights and bias, fp32 sums). +pub fn kv(k: *const Kernels, s: cuda.Stream, ctx: u64, w: u64, b: u64, out: u64, rows: usize) !void { + var a: cuda.Args = .{}; + addAll(&a, &.{ ctx, w, b, out }); + a.add(int(rows)); + try go(k.kv, s, .{ .x = @intCast(rows), .y = ceil(2 * hidden, 256) }, &a); +} + +/// The 16 heads at column `offset` of rows `stride` apart RMS-normed by gamma [16, 64] times 8; dst may be src. +pub fn rmsHeads(k: *const Kernels, s: cuda.Stream, src: u64, gamma: u64, dst: u64, rows: usize, stride: usize, offset: usize) !void { + var a: cuda.Args = .{}; + addAll(&a, &.{ src, gamma, dst }); + for ([_]usize{ stride, offset, rows }) |v| a.add(int(v)); + try go(k.heads, s, .{ .x = @intCast(rows), .y = ceil(heads, 8) }, &a); +} + +/// The attention's forms: fp32 throughout for up to `few_rows` query rows, else tiled (P rounded to fp16). +pub const Form = enum { tiled, few }; + +pub fn form(lq: usize) Form { + return if (lq <= few_rows) .few else .tiled; +} + +/// o [lq, 1024] = softmax(q k^T scale) v: q rows `qs` apart, k rows `ks` apart in `kvp` with v at column 1024. +pub fn attention(k: *const Kernels, s: cuda.Stream, q: u64, qs: usize, kvp: u64, ks: usize, o: u64, lq: usize, lk: usize, scale: f32) !void { + return attentionAs(k, s, form(lq), q, qs, kvp, ks, o, lq, lk, scale); +} + +/// The attention in the form asked (the contract checks each at shapes the decoders never call). +pub fn attentionAs(k: *const Kernels, s: cuda.Stream, f: Form, q: u64, qs: usize, kvp: u64, ks: usize, o: u64, lq: usize, lk: usize, scale: f32) !void { + if (lq == 0 or lk == 0) return; + var a: cuda.Args = .{}; + a.add(q); + a.add(int(qs)); + a.add(kvp); + a.add(int(ks)); + a.add(o); + for ([_]usize{ lq, lk, heads }) |v| a.add(int(v)); + a.add(scale); + switch (f) { + .few => { + if (lq > few_rows or lk > few_keys) return error.ShortFormShape; + try go(k.few, s, .{ .x = @intCast(lq), .y = heads }, &a); + }, + .tiled => { + const grid: cuda.Dim3 = .{ .x = ceil(lq, 16 * attention_warps), .y = heads }; + try cuda.launch.launch(k.attention, .{ .grid = grid, .block = .{ .x = 32 * attention_warps }, .shared = attention_smem }, s, &a); + }, + } +} + +test "launch geometry: points on grid x, 256-column strips, 8 heads a block, attention's tile under 48 KiB" { + try std.testing.expectEqual(@as(u32, 4), ceil(hidden, 256)); + try std.testing.expectEqual(@as(u32, 8), ceil(2 * hidden, 256)); + try std.testing.expectEqual(@as(u32, 2), ceil(heads, 8)); + try std.testing.expectEqual(@as(u32, 256), ceil(32768, 16 * attention_warps)); + try std.testing.expectEqual(@as(u32, 36864), attention_smem); + try std.testing.expect(attention_smem <= 48 * 1024); + try std.testing.expect(form(1) == .few and form(8) == .few and form(9) == .tiled); + try std.testing.expect(context_rows <= few_keys); +} diff --git a/zig/src/families/idol/cuda_decoder_weights.zig b/zig/src/families/idol/cuda_decoder_weights.zig new file mode 100644 index 00000000000..c072059f4e1 --- /dev/null +++ b/zig/src/families/idol/cuda_decoder_weights.zig @@ -0,0 +1,196 @@ +//! Idol's decoders' tensors on CUDA: the blocks' linears and biases to fp16 at load as idol-sdk does, the rest fp32. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const dc = @import("decoder_config.zig"); +const octree = @import("octree.zig"); + +const H = dc.hidden; +const F = dc.ffn; + +/// Cross attention to the latent: fp16 to_q, to_kv, to_out and biases, fp32 RMSNorm gammas [16, 64]. +pub const Cross = struct { q: u64, q_b: u64, kv: u64, kv_b: u64, out: u64, out_b: u64, gq: u64, gk: u64 }; +/// Self attention over the anchors: fp16 to_qkv, to_out and biases, fp32 gammas. +pub const SelfAttention = struct { qkv: u64, qkv_b: u64, out: u64, out_b: u64, gq: u64, gk: u64 }; +pub const Mlp = struct { up: u64, up_b: u64, down: u64, down_b: u64 }; +pub const OctreeBlock = struct { cross: Cross, mlp: Mlp }; +/// A Gaussian decoder block; norm2 is its one affine LayerNorm32 (fp32). +pub const GaussianBlock = struct { self_attn: SelfAttention, cross: Cross, norm2: u64, norm2_b: u64, mlp: Mlp }; +/// The fp32 stem and head: in_proj [1024, 3], input_layer [1024, 1024], out_proj [N, 1024], and biases. +pub const Stem = struct { in_w: u64, in_b: u64, input: u64, input_b: u64, out: u64, out_b: u64 }; + +/// One decoder's file and the device copies made from it. +const File = struct { + gpa: std.mem.Allocator, + ck: *core.Checkpoint, + buffers: *std.ArrayList(cuda.DeviceBuffer), + bytes: *u64, + d: *const cuda.Driver, + stage: []f16, + name: [96]u8 = undefined, + + fn typed(f: *File, name: []const u8, shape: []const usize) !core.checkpoint.Tensor { + const t = try f.ck.get(name); + if (t.dtype != .f32 or t.rank != shape.len or !std.mem.eql(usize, t.shape[0..t.rank], shape)) { + std.log.err("idol: {s} is {t} {any}; the decoders read f32 {any}", .{ name, t.dtype, t.shape[0..t.rank], shape }); + return error.UnexpectedTensor; + } + if (@intFromPtr(t.bytes.ptr) % 4 != 0) return error.UnalignedTensor; + return t; + } + + /// The fp32 tensor `name` of `shape`, its values on the host (mapped from the checkpoint). + fn floats(f: *File, name: []const u8, shape: []const usize) ![]const f32 { + const t = try f.typed(name, shape); + return @alignCast(std.mem.bytesAsSlice(f32, t.bytes)); + } + + fn upload(f: *File, bytes: []const u8) !u64 { + var b = try cuda.DeviceBuffer.fromHost(f.d, bytes); + errdefer b.free(); + try f.buffers.append(f.gpa, b); + f.bytes.* += b.len; + return b.ptr; + } + + /// The fp32 tensor `prefix.leaf` of `shape` on the device as stored. + fn take(f: *File, prefix: []const u8, leaf: []const u8, shape: []const usize) !u64 { + const name = try std.fmt.bufPrint(&f.name, "{s}{s}", .{ prefix, leaf }); + return f.upload(std.mem.sliceAsBytes(try f.floats(name, shape))); + } + + /// The fp32 tensor `prefix.leaf` of `shape` on the device rounded to fp16. + fn half(f: *File, prefix: []const u8, leaf: []const u8, shape: []const usize) !u64 { + const name = try std.fmt.bufPrint(&f.name, "{s}{s}", .{ prefix, leaf }); + const src = try f.floats(name, shape); + for (f.stage[0..src.len], src) |*o, v| o.* = @floatCast(v); + return f.upload(std.mem.sliceAsBytes(f.stage[0..src.len])); + } + + fn cross(f: *File, block: []const u8) !Cross { + var p: [96]u8 = undefined; + const pre = try std.fmt.bufPrint(&p, "{s}.cross_attn.", .{block}); + return .{ + .q = try f.half(pre, "to_q.weight", &.{ H, H }), + .q_b = try f.half(pre, "to_q.bias", &.{H}), + .kv = try f.half(pre, "to_kv.weight", &.{ 2 * H, dc.context_channels }), + .kv_b = try f.half(pre, "to_kv.bias", &.{2 * H}), + .out = try f.half(pre, "to_out.weight", &.{ H, H }), + .out_b = try f.half(pre, "to_out.bias", &.{H}), + .gq = try f.take(pre, "q_rms_norm.gamma", &.{ dc.heads, H / dc.heads }), + .gk = try f.take(pre, "k_rms_norm.gamma", &.{ dc.heads, H / dc.heads }), + }; + } + + fn mlp(f: *File, block: []const u8) !Mlp { + var p: [96]u8 = undefined; + const pre = try std.fmt.bufPrint(&p, "{s}.mlp.mlp.", .{block}); + return .{ .up = try f.half(pre, "0.weight", &.{ F, H }), .up_b = try f.half(pre, "0.bias", &.{F}), .down = try f.half(pre, "2.weight", &.{ H, F }), .down_b = try f.half(pre, "2.bias", &.{H}) }; + } + + fn stem(f: *File, out: usize) !Stem { + return .{ + .in_w = try f.take("", "in_proj.weight", &.{ H, 3 }), + .in_b = try f.take("", "in_proj.bias", &.{H}), + .input = try f.take("", "input_layer.weight", &.{ H, H }), + .input_b = try f.take("", "input_layer.bias", &.{H}), + .out = try f.take("", "out_proj.weight", &.{ out, H }), + .out_b = try f.take("", "out_proj.bias", &.{out}), + }; + } + + /// Every tensor of the file read, or the load refused. + fn whole(f: *const File, file: []const u8) !void { + if (f.ck.unused() != 0) { + std.log.err("idol: {s} has {d} tensors the decoders do not read", .{ file, f.ck.unused() }); + return error.UnexpectedTensors; + } + } +}; + +pub const Weights = struct { + gpa: std.mem.Allocator, + oct: core.Checkpoint, + gs: core.Checkpoint, + buffers: std.ArrayList(cuda.DeviceBuffer) = .empty, + octree: [dc.octree_blocks]OctreeBlock = undefined, + gaussian: [dc.gs_blocks]GaussianBlock = undefined, + octree_stem: Stem = undefined, + gaussian_stem: Stem = undefined, + /// The level embedding and its modulation on the host (octree.levelMods), mapped from decoder.safetensors. + level: octree.LevelWeights = undefined, + base_offset_scale: f32 = 0, + /// points_offset_perturbation [32, 3], mapped from decoder_gs.safetensors. + perturbation: []const f32 = &.{}, + rep: dc.Representation = undefined, + bytes: u64 = 0, + + pub fn deinit(w: *Weights) void { + for (w.buffers.items) |*b| b.free(); + w.buffers.deinit(w.gpa); + w.gs.close(); + w.oct.close(); + } +}; + +/// The snapshot folder `dir`: config.json's decoders checked, then both decoders' safetensors, every tensor read. +pub fn load(gpa: std.mem.Allocator, io: std.Io, d: *const cuda.Driver, dir: []const u8) !*Weights { + var arena_state = std.heap.ArenaAllocator.init(gpa); + defer arena_state.deinit(); + const arena = arena_state.allocator(); + const config = try std.Io.Dir.cwd().readFileAlloc(io, try std.fs.path.join(arena, &.{ dir, "config.json" }), arena, .limited(1 << 20)); + const w = try gpa.create(Weights); + errdefer gpa.destroy(w); + w.* = .{ .gpa = gpa, .oct = .{ .gpa = gpa, .io = io }, .gs = .{ .gpa = gpa, .io = io } }; + errdefer w.deinit(); + w.rep = try dc.check(gpa, config); + try w.oct.add(dir, "decoder.safetensors"); + try w.gs.add(dir, "decoder_gs.safetensors"); + const stage = try arena.alloc(f16, F * H); + var name: [96]u8 = undefined; + var oct: File = .{ .gpa = gpa, .ck = &w.oct, .buffers = &w.buffers, .bytes = &w.bytes, .d = d, .stage = stage }; + for (&w.octree, 0..) |*b, i| { + const pre = try std.fmt.bufPrint(&name, "blocks.{d}", .{i}); + b.cross = try oct.cross(pre); + b.mlp = try oct.mlp(pre); + } + w.octree_stem = try oct.stem(dc.children); + w.level = .{ + .l1 = try oct.floats("l_embedder.mlp.0.weight", &.{ H, dc.level_freqs }), + .l1_b = try oct.floats("l_embedder.mlp.0.bias", &.{H}), + .l2 = try oct.floats("l_embedder.mlp.2.weight", &.{ H, H }), + .l2_b = try oct.floats("l_embedder.mlp.2.bias", &.{H}), + .ada = try oct.floats("adaLN_modulation.1.weight", &.{ 6 * H, H }), + .ada_b = try oct.floats("adaLN_modulation.1.bias", &.{6 * H}), + }; + try oct.whole("decoder.safetensors"); + var gsf: File = .{ .gpa = gpa, .ck = &w.gs, .buffers = &w.buffers, .bytes = &w.bytes, .d = d, .stage = stage }; + for (&w.gaussian, 0..) |*b, i| { + const pre = try std.fmt.bufPrint(&name, "blocks.{d}", .{i}); + var sp: [96]u8 = undefined; + const sa = try std.fmt.bufPrint(&sp, "{s}.self_attn.", .{pre}); + b.self_attn = .{ + .qkv = try gsf.half(sa, "to_qkv.weight", &.{ 3 * H, H }), + .qkv_b = try gsf.half(sa, "to_qkv.bias", &.{3 * H}), + .out = try gsf.half(sa, "to_out.weight", &.{ H, H }), + .out_b = try gsf.half(sa, "to_out.bias", &.{H}), + .gq = try gsf.take(sa, "q_rms_norm.gamma", &.{ dc.heads, H / dc.heads }), + .gk = try gsf.take(sa, "k_rms_norm.gamma", &.{ dc.heads, H / dc.heads }), + }; + b.cross = try gsf.cross(pre); + var np: [96]u8 = undefined; + const n2 = try std.fmt.bufPrint(&np, "{s}.norm2.", .{pre}); + b.norm2 = try gsf.take(n2, "weight", &.{H}); + b.norm2_b = try gsf.take(n2, "bias", &.{H}); + b.mlp = try gsf.mlp(pre); + } + w.gaussian_stem = try gsf.stem(dc.raw_width); + w.base_offset_scale = (try gsf.floats("base_offset_scale", &.{}))[0]; + w.perturbation = try gsf.floats("points_offset_perturbation", &.{ dc.per_anchor, 3 }); + try gsf.whole("decoder_gs.safetensors"); + return w; +} + +test "the fp16 stage holds the largest block linear the decoders round" { + try std.testing.expect(F * H >= 3 * H * H); +} diff --git a/zig/src/families/idol/decode.zig b/zig/src/families/idol/decode.zig index e80dacb6086..20a1eb7ea3c 100644 --- a/zig/src/families/idol/decode.zig +++ b/zig/src/families/idol/decode.zig @@ -1,10 +1,8 @@ -//! IdolPipeline.decode on Metal: the octree's 8 levels to anchors, the Gaussian decoder, then the Gaussians. +//! IdolPipeline.decode on Metal's or CUDA's decoder: the octree's 8 levels to anchors, the Gaussian decoder, then them. const std = @import("std"); -const mtl = @import("metal"); const dc = @import("decoder_config.zig"); const octree = @import("octree.zig"); const gs = @import("gaussian.zig"); -const Decoder = @import("decoder.zig").Decoder; pub const Timing = struct { octree: f64 = 0, octree_gpu: f64 = 0, gaussian: f64 = 0, gaussian_gpu: f64 = 0, activation: f64 = 0 }; @@ -37,8 +35,13 @@ pub const Result = struct { } }; -/// The anchors for `points` points: each level's probabilities on Metal, its split on the host. -pub fn anchors(gpa: std.mem.Allocator, t: *Decoder, points: usize, draws: *octree.Draws, trace: ?*Trace, time: *Timing) ![]f32 { +/// The decoder's clock (its `seconds`). +fn clock(t: anytype) f64 { + return @TypeOf(t.*).seconds(); +} + +/// 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)}) }; defer { gpa.free(level.coords); @@ -54,10 +57,10 @@ pub fn anchors(gpa: std.mem.Allocator, t: *Decoder, points: usize, draws: *octre const tm = try t.octreeLogits(centres, l, probs); time.octree += tm.wall; time.octree_gpu += tm.gpu; - const started = mtl.clock.seconds(); + const started = clock(t); octree.softmax(probs); const next = try octree.descend(gpa, level, probs, @intCast(l), draws, null); - time.octree += mtl.clock.seconds() - started; + 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); @@ -67,16 +70,16 @@ pub fn anchors(gpa: std.mem.Allocator, t: *Decoder, points: usize, draws: *octre gpa.free(level.counts); level = next; } - const started = mtl.clock.seconds(); + const started = clock(t); const out = try gpa.alloc(f32, points * 3); errdefer gpa.free(out); try octree.anchors(level, dc.max_level, draws, out); - time.octree += mtl.clock.seconds() - started; + time.octree += clock(t) - started; return out; } /// The Gaussians of `latent` [8192, 16]: `gaussians` (32,768 to 1,048,576, rounded down to whole anchors). -pub fn decode(gpa: std.mem.Allocator, t: *Decoder, latent: []const f32, gaussians: usize, draws: *octree.Draws, trace: ?*Trace) !Result { +pub fn decode(gpa: std.mem.Allocator, t: anytype, latent: []const f32, gaussians: usize, draws: *octree.Draws, trace: ?*Trace) !Result { const points = try dc.anchors(gaussians); if (points > t.cap) return error.AnchorCount; try t.setLatent(latent); @@ -88,10 +91,10 @@ pub fn decode(gpa: std.mem.Allocator, t: *Decoder, latent: []const f32, gaussian const tg = try t.gaussianRows(pts, raw); time.gaussian = tg.wall; time.gaussian_gpu = tg.gpu; - const started = mtl.clock.seconds(); + const started = clock(t); const g = try gs.Gaussians.alloc(gpa, points * dc.per_anchor); activateParallel(t.params(), raw, pts, g); - time.activation = mtl.clock.seconds() - started; + time.activation = clock(t) - started; return .{ .anchors = pts, .raw = raw, .gaussians = g, .time = time }; } diff --git a/zig/src/families/idol/decoder.zig b/zig/src/families/idol/decoder.zig index db519e4ebef..9c0d051d202 100644 --- a/zig/src/families/idol/decoder.zig +++ b/zig/src/families/idol/decoder.zig @@ -66,6 +66,8 @@ pub const Decoder = struct { consts: Ref, levels_ready: bool = false, + pub const seconds = mtl.clock.seconds; + /// The decoders of snapshot folder `dir`, with scratch for up to `max_anchors` anchors. pub fn load(gpa: std.mem.Allocator, io: std.Io, device: mtl.Device, dir: []const u8, max_anchors: usize) !*Decoder { if (!device.tensorUnits()) { diff --git a/zig/src/families/idol/idol.zig b/zig/src/families/idol/idol.zig index 5aee4da8cb3..84e7b07e512 100644 --- a/zig/src/families/idol/idol.zig +++ b/zig/src/families/idol/idol.zig @@ -1,4 +1,4 @@ -//! Idol image to 3D: its denoiser and decoders on Metal (beside the lane engine, not a token family). +//! Idol image to 3D: its denoiser, decoders and image encoder on Metal (beside the lane engine, not a token family). pub const config = @import("config.zig"); pub const host = @import("host.zig"); pub const weights = @import("weights.zig"); @@ -14,6 +14,9 @@ pub const gaussian = @import("gaussian.zig"); pub const decode = @import("decode.zig"); pub const decode_reference = @import("decode_reference.zig"); pub const Decoder = decoder.Decoder; +pub const vae = @import("vae.zig"); +pub const vae_kernels = @import("vae_kernels.zig"); +pub const vae_weights = @import("vae_weights.zig"); pub const Model = model.Model; pub const Condition = model.Condition; pub const Timing = model.Timing; @@ -33,4 +36,7 @@ test { _ = gaussian; _ = decode; _ = decode_reference; + _ = vae; + _ = vae_kernels; + _ = vae_weights; } diff --git a/zig/src/families/idol/vae.zig b/zig/src/families/idol/vae.zig new file mode 100644 index 00000000000..890cda28e4e --- /dev/null +++ b/zig/src/families/idol/vae.zig @@ -0,0 +1,233 @@ +//! Idol's image encoder on Metal: FLUX.2's VAE encoder in fp32, a 1024 x 1024 picture to the condition's 4,101 rows. +const std = @import("std"); +const mtl = @import("metal"); +const ks = @import("vae_kernels.zig"); +const wts = @import("vae_weights.zig"); +const ref = @import("reference.zig"); +const Ref = ks.Ref; + +/// The picture the encoder sees, its latent grid, and the condition rows: 5 zero rows, then a row a 2 x 2 patch. +pub const size = 1024; +pub const latent = size / 8; +pub const pad = 5; +pub const rows = pad + (latent / 2) * (latent / 2); +pub const channels = 4 * wts.latent_channels; + +pub const Timing = struct { wall: f64, gpu: f64 }; + +/// Where `encode` copies each stage's output when asked, [rows, columns, channels] fp32 (null: not wanted). +pub const Stages = struct { down: [4]?[]f32 = @splat(null), mid: ?[]f32 = null, moments: ?[]f32 = null }; + +/// The widest picture tensor: the first stage's 1024 x 1024 x 128. +const most = size * size * wts.widths[0]; + +pub const Encoder = struct { + gpa: std.mem.Allocator, + device: mtl.Device, + queue: mtl.Queue, + k: ks.Kernels, + w: wts.Weights, + scratch: mtl.Buffer, + image: Ref, + noise: Ref, + t: [4]Ref, + moments: Ref, + out: Ref, + stats: Ref, + part: Ref, + + /// The vae/ folder `dir` (FLUX.2-klein-4B's, or FLUX.2-dev's rounded to bf16 as the SDK loads it). + pub fn load(gpa: std.mem.Allocator, io: std.Io, device: mtl.Device, dir: []const u8) !*Encoder { + const v = try gpa.create(Encoder); + errdefer gpa.destroy(v); + v.* = undefined; + v.gpa = gpa; + v.device = device; + v.queue = try device.queue(); + errdefer v.queue.deinit(); + v.k = try ks.Kernels.load(device); + errdefer v.k.deinit(); + v.w = try wts.load(gpa, io, device, dir); + errdefer v.w.deinit(); + const L = latent * latent; + const parts = [_]usize{ size * size * 3, L * wts.latent_channels, most, most, most, most, L * 2 * wts.latent_channels, rows * channels, 2 * ks.groups, ks.groups * ks.chunks(size * size) }; + var total: usize = 0; + for (parts) |n| total += std.mem.alignForward(usize, n * 4, 256); + v.scratch = try device.buffer(total, mtl.ResourceOptions.shared | mtl.ResourceOptions.untracked); + var at: usize = 0; + const views = [_]*Ref{ &v.image, &v.noise, &v.t[0], &v.t[1], &v.t[2], &v.t[3], &v.moments, &v.out, &v.stats, &v.part }; + for (views, parts) |view, n| { + view.* = .{ .buf = v.scratch, .off = at }; + at += std.mem.alignForward(usize, n * 4, 256); + } + return v; + } + + pub fn deinit(v: *Encoder) void { + v.scratch.deinit(); + v.w.deinit(); + v.k.deinit(); + v.queue.deinit(); + v.gpa.destroy(v); + } + + /// The condition rows [4101, 128] of `image` [1024, 1024, 3] in [0, 1] with the posterior's `noise` [128, 128, 32]. + pub fn encode(v: *Encoder, image: []const f32, noise: []const f32, out: []f32, stages: Stages) !Timing { + if (image.len != size * size * 3) return error.PictureSize; + if (noise.len != latent * latent * wts.latent_channels or out.len != rows * channels) return error.LatentRows; + @memcpy(floats(v.image, image.len), image); + @memcpy(floats(v.noise, noise.len), noise); + const started = mtl.clock.seconds(); + var gpu: f64 = 0; + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + var cb = v.queue.commandBuffer(); + var e = cb.compute(.serial); + var R: usize = size; + ks.convIn(e, v.k.get("iv_conv_in"), v.image, v.w.conv_in.w, v.w.conv_in.b, v.t[0], R, R); + var x: usize = 0; + for (v.w.stages, 0..) |s, i| { + for (s.resnets) |r| x = v.resnet(e, r, x, R); + if (s.down) |d| { + const y = (x + 1) % v.t.len; + ks.conv(e, v.k.get("iv_conv"), v.t[x], d.w, d.b, null, v.t[y], .{ .rows = R / 2, .cols = R / 2, .in_rows = R, .in_cols = R, .cin = d.cin, .cout = d.cout, .ldw = d.ldw, .taps = 9 }); + x = y; + R /= 2; + } + if (stages.down[i]) |dst| { + gpu += try finish(cb, e); + @memcpy(dst, floats(v.t[x], dst.len)); + cb = v.queue.commandBuffer(); + e = cb.compute(.serial); + } + } + x = v.resnet(e, v.w.mid[0], x, R); + x = v.attention(e, x, R * R); + x = v.resnet(e, v.w.mid[1], x, R); + if (stages.mid) |dst| { + gpu += try finish(cb, e); + @memcpy(dst, floats(v.t[x], dst.len)); + cb = v.queue.commandBuffer(); + e = cb.compute(.serial); + } + const n = (x + 1) % v.t.len; + const o = (x + 2) % v.t.len; + v.norm(e, v.t[x], v.t[n], R * R, wts.widths[3], v.w.norm_out, true); + v.conv(e, v.w.conv_out, v.t[n], v.t[o], R, null); + v.conv(e, v.w.quant, v.t[o], v.moments, R, null); + ks.tokens(e, v.k.get("iv_tokens"), v.moments, v.noise, v.w.bn_mean, v.w.bn_std, v.out, R, R, pad); + gpu += try finish(cb, e); + if (stages.moments) |dst| @memcpy(dst, floats(v.moments, dst.len)); + @memcpy(out, floats(v.out, out.len)); + return .{ .wall = mtl.clock.seconds() - started, .gpu = gpu }; + } + + fn finish(cb: mtl.CommandBuffer, e: mtl.ComputeEncoder) !f64 { + e.end(); + cb.commit(); + cb.wait(); + if (cb.failure()) |msg| { + std.log.err("idol vae: a pass failed on the GPU: {s}", .{msg}); + return error.GpuFailure; + } + return cb.gpuSeconds(); + } + + /// One residual block on t[x] at R x R, its output in another of t; returns that one's index. + fn resnet(v: *const Encoder, e: mtl.ComputeEncoder, r: wts.Resnet, x: usize, R: usize) usize { + const n = (x + 1) % v.t.len; + const h = (x + 2) % v.t.len; + const s = (x + 3) % v.t.len; + v.norm(e, v.t[x], v.t[n], R * R, r.conv1.cin, r.norm1, true); + v.conv(e, r.conv1, v.t[n], v.t[h], R, null); + v.norm(e, v.t[h], v.t[n], R * R, r.conv1.cout, r.norm2, true); + const skip = if (r.shortcut) |sc| blk: { + v.conv(e, sc, v.t[x], v.t[s], R, null); + break :blk v.t[s]; + } else v.t[x]; + v.conv(e, r.conv2, v.t[n], v.t[h], R, skip); + return h; + } + + /// The mid block's self-attention on t[x] (`n` positions): GroupNorm, q | k | v, one head of 512, out + t[x]. + fn attention(v: *const Encoder, e: mtl.ComputeEncoder, x: usize, n: usize) usize { + const xn = (x + 1) % v.t.len; + const qkv = v.t[(x + 2) % v.t.len]; + const att = v.t[(x + 3) % v.t.len]; + const W = ks.width; + v.norm(e, v.t[x], v.t[xn], n, W, v.w.attn_norm, false); + ks.conv(e, v.k.get("iv_conv"), v.t[xn], v.w.qkv.w, v.w.qkv.b, null, qkv, .{ .rows = n, .cols = 1, .in_rows = n, .in_cols = 1, .cin = W, .cout = 3 * W, .ldw = 3 * W }); + ks.attend(e, v.k.get("iv_attention"), qkv, att, n); + ks.conv(e, v.k.get("iv_conv"), att, v.w.attn_out.w, v.w.attn_out.b, v.t[x], v.t[xn], .{ .rows = n, .cols = 1, .in_rows = n, .in_cols = 1, .cin = W, .cout = W, .ldw = W }); + return xn; + } + + /// y = GroupNorm(x) with `nm` (then SiLU when `silu`), x and y [pixels, channels], statistics in two passes. + fn norm(v: *const Encoder, e: mtl.ComputeEncoder, x: Ref, y: Ref, n: usize, ch: usize, nm: wts.Norm, silu: bool) void { + for ([_]bool{ false, true }) |centered| { + ks.groupPart(e, v.k.get("iv_group_part"), x, v.stats, v.part, n, ch, centered); + ks.groupFinish(e, v.k.get("iv_group_finish"), v.part, v.stats, n, ch, centered); + } + ks.normed(e, v.k.get("iv_norm"), x, v.stats, nm.g, nm.b, y, n, ch, silu); + } + + /// y = conv(x) + b (+ r) at R x R, a same-size 3x3 (Winograd) or a 1x1. + fn conv(v: *const Encoder, e: mtl.ComputeEncoder, c: wts.Conv, x: Ref, y: Ref, R: usize, r: ?Ref) void { + const s: ks.ConvShape = .{ .rows = R, .cols = R, .in_rows = R, .in_cols = R, .cin = c.cin, .cout = c.cout, .ldw = c.ldw }; + switch (c.kind) { + .wino => ks.winograd(e, v.k.get("iv_wino"), x, c.w, c.b, r, y, s), + .one => ks.conv(e, v.k.get("iv_conv"), x, c.w, c.b, r, y, s), + .strided, .input => unreachable, + } + } +}; + +fn floats(r: Ref, n: usize) []f32 { + return @as([*]f32, @ptrCast(@alignCast(r.addr())))[0..n]; +} + +/// The encoder's gate against the float64 ruler: worst row and 1 - cosine within twice the SDK's own, rows of 128. +pub const Verdict = struct { ours: ref.Match, sdk: ref.Match, pass: bool }; + +pub fn gate(ours: []const f32, sdk: []const f32, ruler: []const f32) Verdict { + const o = ref.match(ours[pad * channels ..], ruler[pad * channels ..], channels); + const s = ref.match(sdk[pad * channels ..], ruler[pad * channels ..], channels); + const zeros = for (ours[0 .. pad * channels]) |z| { + if (z != 0) break false; + } else true; + return .{ .ours = o, .sdk = s, .pass = zeros and ref.within(o, s) }; +} + +test "the encoder's scratch fits a GPU buffer and the rows are the denoiser's condition rows" { + try std.testing.expectEqual(@as(usize, 4101), rows); + try std.testing.expectEqual(@as(usize, 128), channels); + try std.testing.expect(4 * most * 4 < 1 << 33); +} + +test "a planted mismatch in one condition row fails the encoder's gate, as does a padding row not zero" { + const a = std.testing.allocator; + const n = rows * channels; + const ruler = try a.alloc(f32, n); + defer a.free(ruler); + const sdk = try a.alloc(f32, n); + defer a.free(sdk); + const ours = try a.alloc(f32, n); + defer a.free(ours); + var rng = std.Random.DefaultPrng.init(11); + for (ruler, sdk, ours, 0..) |*r, *s, *o, i| { + const z = i < pad * channels; + r.* = if (z) 0 else rng.random().floatNorm(f32); + s.* = r.* * (1 + 4e-3 * rng.random().floatNorm(f32)); + o.* = r.* * (1 + 1e-6 * rng.random().floatNorm(f32)); + } + try std.testing.expect(gate(ours, sdk, ruler).pass); + const row = 2000; + for (ours[row * channels ..][0..channels]) |*o| o.* *= 1.02; + const v = gate(ours, sdk, ruler); + try std.testing.expect(!v.pass); + try std.testing.expect(v.ours.worst_row > 0.019); + for (ours[row * channels ..][0..channels], ruler[row * channels ..][0..channels]) |*o, r| o.* = r; + try std.testing.expect(gate(ours, sdk, ruler).pass); + ours[3 * channels + 7] = 1e-3; + try std.testing.expect(!gate(ours, sdk, ruler).pass); +} diff --git a/zig/src/families/idol/vae_kernels.zig b/zig/src/families/idol/vae_kernels.zig new file mode 100644 index 00000000000..091005fee84 --- /dev/null +++ b/zig/src/families/idol/vae_kernels.zig @@ -0,0 +1,154 @@ +//! Idol's image encoder pipelines (idol_vae.metal, fp32): convolutions, GroupNorm, attention and the condition rows. +const std = @import("std"); +const mtl = @import("metal"); +const sources = @import("kernel_sources"); +pub const Ref = @import("../../core/qwen_vl/weights.zig").Ref; + +/// Each pipeline by its function. +pub const names = [_][]const u8{ "iv_conv_in", "iv_conv", "iv_wino", "iv_norm", "iv_group_part", "iv_group_finish", "iv_attention", "iv_tokens" }; + +/// GroupNorm's groups and epsilon, the pixels a statistics part sums, and the mid block's attention width. +pub const groups = 32; +pub const eps: f32 = 1e-6; +pub const chunk = 256; +pub const width = 512; + +pub const Kernels = struct { + lib: mtl.Library, + p: [names.len]mtl.Pipeline, + + pub fn load(device: mtl.Device) !Kernels { + return loadSource(device, sources.idol_vae); + } + + /// The pipelines of `text` (the served source, or a contract control's copy of it). + pub fn loadSource(device: mtl.Device, text: []const u8) !Kernels { + var k: Kernels = undefined; + k.lib = try mtl.Library.fromSource(device, text, mtl.CompileOptions.mlx()); + errdefer k.lib.deinit(); + var made: usize = 0; + errdefer for (k.p[0..made]) |p| p.deinit(); + for (names, 0..) |name, i| { + k.p[i] = try mtl.Pipeline.init(device, k.lib, name, false); + made += 1; + } + return k; + } + + pub fn deinit(k: *Kernels) void { + for (k.p) |p| p.deinit(); + k.lib.deinit(); + } + + pub fn get(k: *const Kernels, comptime name: []const u8) mtl.Pipeline { + inline for (names, 0..) |n, i| if (comptime std.mem.eql(u8, n, name)) return k.p[i]; + @compileError("no pipeline " ++ name); + } +}; + +/// One kernel's buffers in order, then its parameters at the next index. +pub fn bind(e: mtl.ComputeEncoder, p: mtl.Pipeline, refs: []const Ref, params: anytype) void { + e.setPipeline(p); + for (refs, 0..) |r, i| e.setBuffer(r.buf, r.off, i); + e.setValue(params, refs.len); +} + +/// iv_conv_in: y [rows * cols, 128] = conv3x3(2 x - 1) + b of the picture x [rows * cols, 3], w [27, 128]. +pub fn convIn(e: mtl.ComputeEncoder, p: mtl.Pipeline, x: Ref, w: Ref, b: Ref, y: Ref, rows: usize, cols: usize) void { + bind(e, p, &.{ x, w, b, y }, [2]u32{ @intCast(rows), @intCast(cols) }); + e.dispatchThreads(mtl.Size.of(128, rows * cols, 1), mtl.Size.of(128, 2, 1)); +} + +/// A convolution's size: the output picture, its input picture, channels, the weights' row length and taps (1 or 9). +pub const ConvShape = struct { rows: usize, cols: usize, in_rows: usize, in_cols: usize, cin: usize, cout: usize, ldw: usize, taps: usize = 1 }; + +fn convParams(s: ConvShape, add: bool) extern struct { rows: u32, cols: u32, in_rows: u32, in_cols: u32, cin: u32, cout: u32, ldw: u32, taps: u32, add: u32 } { + return .{ .rows = @intCast(s.rows), .cols = @intCast(s.cols), .in_rows = @intCast(s.in_rows), .in_cols = @intCast(s.in_cols), .cin = @intCast(s.cin), .cout = @intCast(s.cout), .ldw = @intCast(s.ldw), .taps = @intCast(s.taps), .add = @intFromBool(add) }; +} + +/// iv_conv: y = conv(x) + b (+ r when given), a 1x1 or a stride-2 3x3; cin % 32 = 0, ldw % 64 = 0. +pub fn conv(e: mtl.ComputeEncoder, p: mtl.Pipeline, x: Ref, w: Ref, b: Ref, r: ?Ref, y: Ref, s: ConvShape) void { + std.debug.assert(s.cin % 32 == 0 and s.ldw % 64 == 0 and (s.taps == 1 or s.taps == 9)); + bind(e, p, &.{ x, w, b, r orelse y, y }, convParams(s, r != null)); + e.dispatchGroups(mtl.Size.of(s.ldw / 64, (s.rows * s.cols + 63) / 64, 1), mtl.Size.of(128, 1, 1)); +} + +/// iv_wino: y = conv3x3(x) + b (+ r when given) by Winograd F(2x2, 3x3), same size; cin % 16 = 0, ldw % 64 = 0. +pub fn winograd(e: mtl.ComputeEncoder, p: mtl.Pipeline, x: Ref, u: Ref, b: Ref, r: ?Ref, y: Ref, s: ConvShape) void { + std.debug.assert(s.cin % 16 == 0 and s.ldw % 64 == 0); + bind(e, p, &.{ x, u, b, r orelse y, y }, convParams(s, r != null)); + e.dispatchGroups(mtl.Size.of(s.ldw / 64, (s.rows + 3) / 4, (s.cols + 15) / 16), mtl.Size.of(512, 1, 1)); +} + +/// The Winograd F(2x2, 3x3) form of one 3x3 kernel g: G g G^T in float64, each of its 16 values rounded once. +pub fn transform(g: *const [9]f32) [16]f32 { + const G = [4][3]f64{ .{ 1, 0, 0 }, .{ 0.5, 0.5, 0.5 }, .{ 0.5, -0.5, 0.5 }, .{ 0, 0, 1 } }; + var out: [16]f32 = undefined; + for (0..4) |i| for (0..4) |j| { + var v: f64 = 0; + for (0..3) |a| for (0..3) |b| { + v += G[i][a] * @as(f64, g[a * 3 + b]) * G[j][b]; + }; + out[i * 4 + j] = @floatCast(v); + }; + return out; +} + +/// iv_norm: y = GroupNorm(x) by stats (32 means, then 32 rstd) with g and beta, then SiLU when `silu`. +pub fn normed(e: mtl.ComputeEncoder, p: mtl.Pipeline, x: Ref, stats: Ref, g: Ref, beta: Ref, y: Ref, n: usize, channels: usize, silu: bool) void { + const params = extern struct { pixels: u32, channels: u32, silu: u32 }{ .pixels = @intCast(n), .channels = @intCast(channels), .silu = @intFromBool(silu) }; + bind(e, p, &.{ x, stats, g, beta, y }, params); + e.dispatchThreads(mtl.Size.of(channels, n, 1), mtl.Size.of(32, 8, 1)); +} + +/// GroupNorm's parts over `n` pixels: one sum a chunk of `chunk` pixels and a group. +pub fn chunks(n: usize) usize { + return (n + chunk - 1) / chunk; +} + +fn groupParams(n: usize, channels: usize, centered: bool) extern struct { pixels: u32, channels: u32, chunk: u32, chunks: u32, centered: u32, eps: f32 } { + return .{ .pixels = @intCast(n), .channels = @intCast(channels), .chunk = chunk, .chunks = @intCast(chunks(n)), .centered = @intFromBool(centered), .eps = eps }; +} + +/// iv_group_part: part [32, chunks] = each chunk's sum of a group's values, or (centered) of (x - mean)^2. +pub fn groupPart(e: mtl.ComputeEncoder, p: mtl.Pipeline, x: Ref, stats: Ref, part: Ref, n: usize, channels: usize, centered: bool) void { + std.debug.assert(channels % groups == 0 and channels <= 512); + bind(e, p, &.{ x, stats, part }, groupParams(n, channels, centered)); + e.dispatchGroups(mtl.Size.of(chunks(n), 1, 1), mtl.Size.of(channels, 1, 1)); +} + +/// iv_group_finish: stats' 32 means from part, or (centered) its 32 rstd. +pub fn groupFinish(e: mtl.ComputeEncoder, p: mtl.Pipeline, part: Ref, stats: Ref, n: usize, channels: usize, centered: bool) void { + bind(e, p, &.{ part, stats }, groupParams(n, channels, centered)); + e.dispatchGroups(mtl.Size.of(1, 1, 1), mtl.Size.of(32 * groups, 1, 1)); +} + +/// iv_attention: o [rows, 512] = softmax(q k^T / sqrt(512)) v of qkv rows [rows, 1536], both padded to 32 rows. +pub fn attend(e: mtl.ComputeEncoder, p: mtl.Pipeline, qkv: Ref, o: Ref, rows: usize) void { + const params = extern struct { rows: u32, scale: f32 }{ .rows = @intCast(rows), .scale = 1.0 / @sqrt(@as(f32, width)) }; + bind(e, p, &.{ qkv, o }, params); + e.dispatchGroups(mtl.Size.of((rows + 7) / 8, 1, 1), mtl.Size.of(128, 1, 1)); +} + +/// iv_tokens: out [pad + rows * cols / 4, 128] from moments [rows, cols, 64], noise [rows, cols, 32], m and s [128]. +pub fn tokens(e: mtl.ComputeEncoder, p: mtl.Pipeline, moments: Ref, noise: Ref, m: Ref, s: Ref, out: Ref, rows: usize, cols: usize, pad: usize) void { + bind(e, p, &.{ moments, noise, m, s, out }, [3]u32{ @intCast(rows), @intCast(cols), @intCast(pad) }); + e.dispatchThreads(mtl.Size.of(128, pad + rows * cols / 4, 1), mtl.Size.of(128, 2, 1)); +} + +test "every image encoder pipeline compiles and loads on this GPU" { + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const device = mtl.Device.init() catch return error.SkipZigTest; + defer device.deinit(); + var k = try Kernels.load(device); + k.deinit(); +} + +test "the Winograd transform of a delta kernel is G's outer products" { + var g: [9]f32 = @splat(0); + g[4] = 1; + const u = transform(&g); + const col = [4]f32{ 0, 0.5, -0.5, 0 }; + for (0..4) |i| for (0..4) |j| try std.testing.expectEqual(col[i] * col[j], u[i * 4 + j]); +} diff --git a/zig/src/families/idol/vae_weights.zig b/zig/src/families/idol/vae_weights.zig new file mode 100644 index 00000000000..817794aa396 --- /dev/null +++ b/zig/src/families/idol/vae_weights.zig @@ -0,0 +1,308 @@ +//! Idol's image encoder weights: FLUX.2's VAE encoder, quant_conv and batch norm statistics, as the SDK holds them. +const std = @import("std"); +const mtl = @import("metal"); +const ck = @import("../../core/checkpoint_metal.zig"); +const ks = @import("vae_kernels.zig"); +const Ref = ks.Ref; + +/// The encoder's widths by stage, and the rest of the released geometry. +pub const widths = [4]usize{ 128, 256, 512, 512 }; +pub const latent_channels = 32; +pub const resnets = 2; +pub const batch_norm_eps: f32 = 1e-4; + +/// Accepts vae/config.json at FLUX.2's released encoder geometry, else an error. +pub fn check(gpa: std.mem.Allocator, text: []const u8) !void { + const doc = try std.json.parseFromSlice(std.json.Value, gpa, text, .{}); + defer doc.deinit(); + if (doc.value != .object) return error.BadConfig; + const o = doc.value.object; + const name = o.get("_class_name") orelse return error.BadConfig; + if (name != .string or !std.mem.eql(u8, name.string, "AutoencoderKLFlux2")) return error.NotFlux2Vae; + const want = .{ .{ "in_channels", 3 }, .{ "latent_channels", latent_channels }, .{ "layers_per_block", resnets }, .{ "norm_num_groups", ks.groups } }; + inline for (want) |kv| { + const v = o.get(kv[0]) orelse return error.BadConfig; + if (v != .integer or v.integer != kv[1]) { + std.log.warn("idol vae: {s} is not {d}; the encoder runs the released geometry only", .{ kv[0], kv[1] }); + return error.UnsupportedGeometry; + } + } + const lists = .{ .{ "block_out_channels", [_]i64{ 128, 256, 512, 512 } }, .{ "patch_size", [_]i64{ 2, 2 } } }; + inline for (lists) |kv| { + const v = o.get(kv[0]) orelse return error.BadConfig; + if (v != .array or v.array.items.len != kv[1].len) return error.UnsupportedGeometry; + for (v.array.items, kv[1]) |item, n| if (item != .integer or item.integer != n) return error.UnsupportedGeometry; + } + inline for (.{ "mid_block_add_attention", "use_quant_conv" }) |f| { + const v = o.get(f) orelse return error.BadConfig; + if (v != .bool or !v.bool) return error.UnsupportedGeometry; + } + const blocks = o.get("down_block_types") orelse return error.BadConfig; + if (blocks != .array or blocks.array.items.len != widths.len) return error.UnsupportedGeometry; + for (blocks.array.items) |b| if (b != .string or !std.mem.eql(u8, b.string, "DownEncoderBlock2D")) return error.UnsupportedGeometry; + const act = o.get("act_fn") orelse return error.BadConfig; + if (act != .string or !std.mem.eql(u8, act.string, "silu")) return error.UnsupportedGeometry; + const bn = o.get("batch_norm_eps") orelse return error.BadConfig; + const bn_eps: f64 = switch (bn) { + .float => |f| f, + .integer => |n| @floatFromInt(n), + else => return error.BadConfig, + }; + if (@as(f32, @floatCast(bn_eps)) != batch_norm_eps) return error.UnsupportedGeometry; +} + +/// A convolution's weights (1x1 [cin, ldw], stride-2 3x3 [9 * cin, ldw], 3x3 G g G^T [16, cin, ldw]) and bias. +pub const Conv = struct { w: Ref, b: Ref, cin: usize, cout: usize, ldw: usize, kind: Kind }; +pub const Kind = enum { one, wino, strided, input }; +pub const Norm = struct { g: Ref, b: Ref }; +pub const Resnet = struct { norm1: Norm, conv1: Conv, norm2: Norm, conv2: Conv, shortcut: ?Conv }; +pub const Stage = struct { resnets: [resnets]Resnet, down: ?Conv }; + +pub const Weights = struct { + buf: mtl.Buffer, + conv_in: Conv, + stages: [4]Stage, + mid: [2]Resnet, + attn_norm: Norm, + qkv: Conv, + attn_out: Conv, + norm_out: Norm, + conv_out: Conv, + quant: Conv, + /// The batch norm's running mean and sqrt(running_var + eps), each of 128. + bn_mean: Ref, + bn_std: Ref, + + pub fn deinit(w: *Weights) void { + w.buf.deinit(); + } +}; + +/// The bf16 value an fp32 weight rounds to (to nearest, ties to even), as torch's cast to bf16 makes it. +pub fn bf16(v: f32) f32 { + if (std.math.isNan(v)) return v; + const bits: u32 = @bitCast(v); + const rounded = bits +% (0x7fff + ((bits >> 16) & 1)); + return @bitCast(rounded & 0xffff0000); +} + +/// The folder `dir` (config.json, diffusion_pytorch_model.safetensors in bf16 or f32): every encoder tensor, packed. +pub fn load(gpa: std.mem.Allocator, io: std.Io, device: mtl.Device, dir: []const u8) !Weights { + var arena_state = std.heap.ArenaAllocator.init(gpa); + defer arena_state.deinit(); + const arena = arena_state.allocator(); + const config = try std.Io.Dir.cwd().readFileAlloc(io, try std.fs.path.join(arena, &.{ dir, "config.json" }), arena, .limited(1 << 20)); + try check(gpa, config); + var c = ck.Checkpoint.init(gpa); + defer c.deinit(); + try c.addFile(device, try std.fmt.allocPrintSentinel(arena, "{s}/diffusion_pytorch_model.safetensors", .{dir}, 0), ""); + var w: Weights = undefined; + var p: Packer = .{ .c = &c, .arena = arena }; + try layout(&w, &p); + if (p.read != expected(&c)) { + std.log.err("idol vae: the checkpoint has {d} encoder tensors; the encoder reads {d}", .{ expected(&c), p.read }); + return error.UnexpectedTensors; + } + w.buf = try device.buffer(p.at * 4, mtl.ResourceOptions.shared); + errdefer w.buf.deinit(); + p.out = @as([*]f32, @ptrCast(@alignCast(w.buf.contents())))[0..p.at]; + p.at = 0; + p.read = 0; + p.buf = w.buf; + try layout(&w, &p); + return w; +} + +/// Walks every tensor in the order it is packed: sizes it on the first pass, copies it on the second. +fn layout(w: *Weights, p: *Packer) !void { + var name: [96]u8 = undefined; + w.conv_in = try p.conv("encoder.conv_in", 3, widths[0], .input); + var prev = widths[0]; + for (&w.stages, widths, 0..) |*s, out, i| { + for (&s.resnets, 0..) |*r, j| { + r.* = try p.resnet(try std.fmt.bufPrint(&name, "encoder.down_blocks.{d}.resnets.{d}", .{ i, j }), if (j == 0) prev else out, out); + } + s.down = if (i + 1 < widths.len) try p.conv(try std.fmt.bufPrint(&name, "encoder.down_blocks.{d}.downsamplers.0.conv", .{i}), out, out, .strided) else null; + prev = out; + } + const W = widths[3]; + for (&w.mid, 0..) |*r, i| r.* = try p.resnet(try std.fmt.bufPrint(&name, "encoder.mid_block.resnets.{d}", .{i}), W, W); + const at = "encoder.mid_block.attentions.0"; + w.attn_norm = try p.norm(at ++ ".group_norm", W); + w.qkv = try p.linears(&.{ at ++ ".to_q", at ++ ".to_k", at ++ ".to_v" }, W); + w.attn_out = try p.linears(&.{at ++ ".to_out.0"}, W); + w.norm_out = try p.norm("encoder.conv_norm_out", W); + w.conv_out = try p.conv("encoder.conv_out", W, 2 * latent_channels, .wino); + w.quant = try p.conv("quant_conv", 2 * latent_channels, 2 * latent_channels, .one); + const n = 4 * latent_channels; + const mean = try p.vector("bn.running_mean", n); + const var_ = try p.vector("bn.running_var", n); + w.bn_mean = p.alloc(n); + w.bn_std = p.alloc(n); + if (p.out) |out| { + // the SDK's sqrt(var + eps) in bf16, here in float64 rounded once + for (out[w.bn_mean.off / 4 ..][0..n], out[w.bn_std.off / 4 ..][0..n], mean, var_) |*mo, *so, mv, v| { + mo.* = mv; + so.* = @floatCast(@sqrt(@as(f64, v) + 1e-4)); + } + } +} + +/// The checkpoint's encoder-side tensors: the encoder's, quant_conv's and the batch norm's two statistics. +fn expected(c: *const ck.Checkpoint) usize { + var n: usize = 0; + var it = c.tensors.keyIterator(); + while (it.next()) |k| { + if (std.mem.startsWith(u8, k.*, "encoder.") or std.mem.startsWith(u8, k.*, "quant_conv.") or + std.mem.eql(u8, k.*, "bn.running_mean") or std.mem.eql(u8, k.*, "bn.running_var")) n += 1; + } + return n; +} + +/// Lays the encoder's tensors out in one fp32 buffer: sizes on the first pass (out null), copies on the second. +const Packer = struct { + c: *const ck.Checkpoint, + arena: std.mem.Allocator, + buf: mtl.Buffer = undefined, + out: ?[]f32 = null, + at: usize = 0, + read: usize = 0, + + fn alloc(p: *Packer, n: usize) Ref { + const r: Ref = .{ .buf = p.buf, .off = p.at * 4 }; + p.at = std.mem.alignForward(usize, p.at + n, 64); + return r; + } + + /// Tensor `name` of `shape` as the bf16 values the SDK computes with (a bf16 file's own, an f32 file's rounded). + fn tensor(p: *Packer, name: []const u8, shape: []const usize) ![]const f32 { + const t = try p.c.get(name); + if ((t.dtype != .f32 and t.dtype != .bf16) or t.rank != shape.len or !std.mem.eql(usize, t.shape[0..t.rank], shape)) { + std.log.err("idol vae: {s} is {t} {any}; the encoder reads bf16 or f32 {any}", .{ name, t.dtype, t.shape[0..t.rank], shape }); + return error.UnexpectedTensor; + } + p.read += 1; + if (p.out == null) return &.{}; + const n = t.count(); + const v = try p.arena.alloc(f32, n); + switch (t.dtype) { + .bf16 => for (v, t.host(u16)) |*o, h| { + o.* = @bitCast(@as(u32, h) << 16); + }, + else => for (v, t.host(f32)) |*o, f| { + o.* = bf16(f); + }, + } + return v; + } + + fn vector(p: *Packer, name: []const u8, n: usize) ![]const f32 { + return p.tensor(name, &.{n}); + } + + /// A copied vector `name` of n. + fn copy(p: *Packer, name: []const u8, n: usize) !Ref { + const v = try p.vector(name, n); + const r = p.alloc(n); + if (p.out) |out| @memcpy(out[r.off / 4 ..][0..n], v); + return r; + } + + /// Convolution `name` (.weight [cout, cin, k, k], .bias) in `kind`'s layout, its columns padded to ldw. + fn conv(p: *Packer, name: []const u8, cin: usize, cout: usize, kind: Kind) !Conv { + var buf: [96]u8 = undefined; + const taps: usize = if (kind == .one) 1 else 9; + const k: usize = if (kind == .one) 1 else 3; + const ldw = if (kind == .input) cout else std.mem.alignForward(usize, cout, 64); + const rows: usize = switch (kind) { + .one => cin, + .wino => 16 * cin, + .strided, .input => 9 * cin, + }; + const w = try p.tensor(try std.fmt.bufPrint(&buf, "{s}.weight", .{name}), &.{ cout, cin, k, k }); + const r = p.alloc(rows * ldw); + if (p.out) |out| { + const dst = out[r.off / 4 ..][0 .. rows * ldw]; + @memset(dst, 0); + for (0..cout) |o| for (0..cin) |i| { + const g = w[(o * cin + i) * taps ..][0..taps]; + switch (kind) { + .one => dst[i * ldw + o] = g[0], + .wino => for (ks.transform(g[0..9]), 0..) |v, pt| { + dst[(pt * cin + i) * ldw + o] = v; + }, + .strided, .input => for (g, 0..) |v, tap| { + dst[(tap * cin + i) * ldw + o] = v; + }, + } + }; + } + const b = try p.copy(try std.fmt.bufPrint(&buf, "{s}.bias", .{name}), cout); + return .{ .w = r, .b = b, .cin = cin, .cout = cout, .ldw = ldw, .kind = kind }; + } + + /// Linear layers `names` (.weight [width, width], .bias) stacked as one 1x1 convolution. + fn linears(p: *Packer, names_: []const []const u8, width: usize) !Conv { + var buf: [96]u8 = undefined; + const n = names_.len * width; + const r = p.alloc(width * n); + for (names_, 0..) |name, part| { + const w = try p.tensor(try std.fmt.bufPrint(&buf, "{s}.weight", .{name}), &.{ width, width }); + if (p.out) |out| { + const dst = out[r.off / 4 ..][0 .. width * n]; + for (0..width) |o| for (0..width) |i| { + dst[i * n + part * width + o] = w[o * width + i]; + }; + } + } + const b = p.alloc(n); + for (names_, 0..) |name, i| { + const v = try p.vector(try std.fmt.bufPrint(&buf, "{s}.bias", .{name}), width); + if (p.out) |out| @memcpy(out[b.off / 4 + i * width ..][0..width], v); + } + return .{ .w = r, .b = b, .cin = width, .cout = n, .ldw = n, .kind = .one }; + } + + fn norm(p: *Packer, name: []const u8, width: usize) !Norm { + var buf: [96]u8 = undefined; + return .{ .g = try p.copy(try std.fmt.bufPrint(&buf, "{s}.weight", .{name}), width), .b = try p.copy(try std.fmt.bufPrint(&buf, "{s}.bias", .{name}), width) }; + } + + fn resnet(p: *Packer, name: []const u8, cin: usize, cout: usize) !Resnet { + var buf: [96]u8 = undefined; + return .{ + .norm1 = try p.norm(try std.fmt.bufPrint(&buf, "{s}.norm1", .{name}), cin), + .conv1 = try p.conv(try std.fmt.bufPrint(&buf, "{s}.conv1", .{name}), cin, cout, .wino), + .norm2 = try p.norm(try std.fmt.bufPrint(&buf, "{s}.norm2", .{name}), cout), + .conv2 = try p.conv(try std.fmt.bufPrint(&buf, "{s}.conv2", .{name}), cout, cout, .wino), + .shortcut = if (cin != cout) try p.conv(try std.fmt.bufPrint(&buf, "{s}.conv_shortcut", .{name}), cin, cout, .one) else null, + }; + } +}; + +test "only FLUX.2's released encoder geometry passes" { + const a = std.testing.allocator; + const sample = + \\{"_class_name": "AutoencoderKLFlux2", "act_fn": "silu", "batch_norm_eps": 0.0001, "block_out_channels": [128, 256, 512, 512], + \\ "down_block_types": ["DownEncoderBlock2D", "DownEncoderBlock2D", "DownEncoderBlock2D", "DownEncoderBlock2D"], "in_channels": 3, + \\ "latent_channels": 32, "layers_per_block": 2, "mid_block_add_attention": true, "norm_num_groups": 32, + \\ "patch_size": [2, 2], "use_quant_conv": true} + ; + try check(a, sample); + const narrow = try std.mem.replaceOwned(u8, a, sample, "[128, 256, 512, 512]", "[96, 192, 384, 384]"); + defer a.free(narrow); + try std.testing.expectError(error.UnsupportedGeometry, check(a, narrow)); + const no_quant = try std.mem.replaceOwned(u8, a, sample, "\"use_quant_conv\": true", "\"use_quant_conv\": false"); + defer a.free(no_quant); + try std.testing.expectError(error.UnsupportedGeometry, check(a, no_quant)); + const other = try std.mem.replaceOwned(u8, a, sample, "AutoencoderKLFlux2", "AutoencoderKL"); + defer a.free(other); + try std.testing.expectError(error.NotFlux2Vae, check(a, other)); +} + +test "an f32 weight rounds to bf16 as torch's cast does: to nearest, ties to even" { + try std.testing.expectEqual(@as(f32, 1.0), bf16(1.0 + 0x1p-9)); + try std.testing.expectEqual(@as(f32, 1.0 + 0x1p-7), bf16(1.0 + 0x1p-7 + 0x1p-9)); + try std.testing.expectEqual(@as(f32, 1.0 + 0x1p-6), bf16(1.0 + 0x1p-7 + 0x1p-8)); + try std.testing.expectEqual(@as(f32, 1.0 + 0x1p-7), bf16(1.0 + 0x1p-7 + 0x1p-8 - 0x1p-20)); +} diff --git a/zig/src/families/inkling2/inkling2.zig b/zig/src/families/inkling2/inkling2.zig index f37ce4d9bcf..556bca61b13 100644 --- a/zig/src/families/inkling2/inkling2.zig +++ b/zig/src/families/inkling2/inkling2.zig @@ -1,10 +1,12 @@ //! Inkling 2 Small (model_type inkling2) on CUDA: config, chat, reply split, admission, kernels, EXL3 weights, forward. pub const kernels = @import("kernels.zig"); +pub const ops = @import("ops.zig"); /// config.json's name in the release. pub const model_type = "inkling2"; test { _ = kernels; + _ = ops; } diff --git a/zig/src/families/inkling2/ops.zig b/zig/src/families/inkling2/ops.zig new file mode 100644 index 00000000000..fb2bdeeabc6 --- /dev/null +++ b/zig/src/families/inkling2/ops.zig @@ -0,0 +1,254 @@ +//! Inkling 2's glue kernels (inkling2/ops.cu): embedding, residual mix, row dots, router, SwiGLU epilogue, convs. +const std = @import("std"); +const cuda = @import("cuda"); + +pub const max_blocks = 8; +pub const max_queries = 3; + +/// ops.cu's MixArgs, field for field. +pub const MixArgs = extern struct { + blocks: [max_blocks]u64 = @splat(0), + partial: u64, + query: u64, + norm: [max_queries]u64 = @splat(0), + out: u64, + n_blocks: i32, + partial_bf16: i32, + nq: i32, + rows: i32, + c: i32, + eps: f32, +}; + +/// ops.cu's ConvArgs, field for field. +pub const ConvArgs = extern struct { + x: u64, + state: u64, + w: u64, + dyn: u64 = 0, + base: u64 = 0, + resid: u64 = 0, + out: u64 = 0, + segs: u64 = 0, // int4 per stream: row0, rows, state slot (0: one stream) + hist: u64 = 0, // fp32 [rows][c]: each row's input as the state keeps it (0: none) + part_stride: i64 = 0, // elements between the ranks' partials of x (parts > 1) + state_stride: i64 = 0, // elements between the streams' states + parts: i32 = 1, + x_bf16: i32 = 0, + round_in: i32 = 0, + heads: i32 = 1, + c: i32, + rows: i32, + mode: i32, +}; + +/// ops.cu's GateUpArgs, field for field. +pub const GateUpArgs = extern struct { + z: u64, + pick: u64, + svh_g: u64, + svh_u: u64, + suh_d: u64, + xd: u64, + p: i32, + n: i32, + sk: i32, + experts: i32, + gate_cap: f32, + up_cap: f32, +}; + +pub const Kernels = struct { + mod: cuda.Module, + rows_mod: cuda.Module, + rowdot_tiles: cuda.Function, + prompt_tail: cuda.Function, + embed: cuda.Function, + mix: cuda.Function, + mix_rows: cuda.Function, + rowdot: cuda.Function, + topk: cuda.Function, + gateup: cuda.Function, + conv: cuda.Function, + softcap: cuda.Function, + top1: cuda.Function, + tobf: cuda.Function, + put_words: cuda.Function, + rewind: cuda.Function, + race1: 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_ops); + errdefer mod.unload(); + var rows_mod = try cuda.Module.load(d, cuda.kernels.inkling2_rows); + errdefer rows_mod.unload(); + return .{ + .mod = mod, + .rows_mod = rows_mod, + .rowdot_tiles = try rows_mod.function("tf_ink2_rowdot_tiles"), + .prompt_tail = try rows_mod.function("tf_ink2_prompt_tail"), + .embed = try mod.function("tf_ink2_embed"), + .mix = try mod.function("tf_ink2_mix"), + .mix_rows = try mod.function("tf_ink2_mix_rows"), + .rowdot = try mod.function("tf_ink2_rowdot"), + .topk = try mod.function("tf_ink2_topk"), + .gateup = try mod.function("tf_ink2_gateup"), + .conv = try mod.function("tf_ink2_conv"), + .softcap = try mod.function("tf_ink2_softcap"), + .top1 = try mod.function("tf_ink2_top1"), + .tobf = try mod.function("tf_ink2_tobf"), + .put_words = try mod.function("tf_ink2_put_words"), + .rewind = try mod.function("tf_ink2_conv_rewind"), + .race1 = try mod.function("tf_ink2_race1"), + }; + } + + pub fn unload(k: *Kernels) void { + k.rows_mod.unload(); + 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); +} + +/// Embedding rows of `ids` (int32 on the device) through embed_norm into bf16 [rows, c]. +pub fn embed(k: *const Kernels, s: cuda.Stream, ids: u64, rows: usize, table: u64, norm: u64, out: u64, c: usize, eps: f32) !void { + var a: cuda.Args = .{}; + for ([_]u64{ ids, table, norm, out }) |v| a.add(v); + a.add(int(c)); + a.add(eps); + try go(k.embed, s, .{ .x = @intCast(rows) }, 256, &a); +} + +/// The residual mix of each row and query, normed: a block a row. +pub fn mix(k: *const Kernels, s: cuda.Stream, m: MixArgs) !void { + if (m.c > 10 * 512 or @rem(m.c, 128) != 0) return error.Inkling2MixWidth; // ops.cu: kMixCache x 512 columns, 16-byte copies + var a: cuda.Args = .{}; + a.add(m); + try go(if (m.rows <= 16) k.mix else k.mix_rows, s, .{ .x = @intCast(m.rows) }, 512, &a); // equal bits either way +} + +/// out[row, j] = x[row] . w[j] over `c` (bf16 in), `j` outputs a row, bf16 or fp32 out, sigmoid when `sigmoid`. +pub fn rowdot(k: *const Kernels, s: cuda.Stream, x: u64, w: u64, out: u64, rows: usize, j: usize, c: usize, out_bf16: bool, sigmoid: bool) !void { + var a: cuda.Args = .{}; + for ([_]u64{ x, w, out }) |v| a.add(v); + if (rows >= 32 and !out_bf16 and c % 128 == 0) { // prompt rows: 32 x 16 tiles, the same sums in the same order + for ([_]i32{ int(rows), int(j), int(c), @intFromBool(sigmoid) }) |v| a.add(v); + return go(k.rowdot_tiles, s, .{ .x = @intCast((rows + 31) / 32), .y = @intCast((j + 15) / 16) }, 256, &a); + } + for ([_]i32{ int(j), int(c), @intFromBool(out_bf16), @intFromBool(sigmoid) }) |v| a.add(v); + try go(k.rowdot, s, .{ .x = @intCast(rows), .y = @intCast((j + 7) / 8) }, 256, &a); +} + +/// The router's picks and weights from fp32 sigmoid scores [rows, experts] and the selection bias. +pub fn topk(k: *const Kernels, s: cuda.Stream, scores: u64, bias: u64, pick: u64, wts: u64, rows: usize, experts: usize, top: usize, scale: f32) !void { + if (experts > 512 * 8 or top > 32) return error.Inkling2RouterShape; + var a: cuda.Args = .{}; + for ([_]u64{ scores, bias, pick, wts }) |v| a.add(v); + a.add(int(experts)); + a.add(int(top)); + a.add(scale); + try go(k.topk, s, .{ .x = @intCast(rows) }, 512, &a); +} + +/// The softcapped SwiGLU epilogue over `p` (row, slot) pairs, `n` wide: the grid of exl3_experts' gate/up epilogue. +pub fn gateup(k: *const Kernels, s: cuda.Stream, g: GateUpArgs) !void { + var a: cuda.Args = .{}; + a.add(g); + try go(k.gateup, s, .{ .x = @intCast(g.p), .y = @intCast(@divExact(g.n, 128)) }, 32, &a); +} + +/// A short convolution over each of `streams` streams' rows, their states carried (ops.cu's tf_ink2_conv). +pub fn conv(k: *const Kernels, s: cuda.Stream, c: ConvArgs, streams: usize) !void { + var a: cuda.Args = .{}; + a.add(c); + // a stream's rows in blocks of 32 (blocks past a stream's rows return at once) + const z: u32 = @intCast(std.math.divCeil(i32, c.rows, 32) catch unreachable); + try go(k.conv, s, .{ .x = @intCast(std.math.divCeil(i32, c.c, 128) catch unreachable), .y = @intCast(streams), .z = z }, 128, &a); +} + +/// ops.cu's RewindSite: a conv site's slot-0 state, byte offsets of its rows in a hist and in a slot's backup, its C. +pub const RewindSite = extern struct { state: u64, hist: i64, backup: i64, c: i32, pad: i32 = 0 }; + +/// A slot's last window keeps `n` rows: every site's state from its backup (`backup`: the slot's) and `hist` rows. +pub fn rewind(k: *const Kernels, s: cuda.Stream, sites: u64, n_sites: usize, widest: usize, backup: u64, hist: u64, slot: usize, row0: usize, n: usize) !void { + var a: cuda.Args = .{}; + for ([_]u64{ sites, backup, hist }) |v| a.add(v); + for ([_]i32{ int(slot), int(row0), int(n) }) |v| a.add(v); + try go(k.rewind, s, .{ .x = @intCast((widest + 127) / 128), .y = @intCast(n_sites) }, 128, &a); +} + +/// tanh(x / cap) * cap over `n` fp32 logits in place. +pub fn softcap(k: *const Kernels, s: cuda.Stream, x: u64, n: usize, cap: f32) !void { + var a: cuda.Args = .{}; + a.add(x); + a.add(@as(i64, @intCast(n))); + a.add(cap); + try go(k.softcap, s, .{ .x = @intCast((n + 255) / 256) }, 256, &a); +} + +/// Each of `rows` fp32 rows (`stride` apart): its largest value among the first `n` (lowest id on ties), id + `base`. +pub fn top1(k: *const Kernels, s: cuda.Stream, x: u64, rows: usize, stride: usize, n: usize, base: usize, val: u64, id: u64) !void { + var a: cuda.Args = .{}; + a.add(x); + a.add(@as(i64, @intCast(stride))); + a.add(int(n)); + a.add(int(base)); + a.add(val); + a.add(id); + try go(k.top1, s, .{ .x = @intCast(rows) }, 1024, &a); +} + +/// One fp32 row's keyed Gumbel race at position `pos` (sample.cu's keys, ids `base` + i): best score and id. +pub fn race1(k: *const Kernels, s: cuda.Stream, x: u64, n: usize, base: usize, seed: u64, inv_t: f32, pos: usize, val: u64, id: u64) !void { + var a: cuda.Args = .{}; + a.add(x); + a.add(int(n)); + a.add(int(base)); + a.add(seed); + a.add(inv_t); + a.add(@as(u32, @intCast(pos))); + a.add(val); + a.add(id); + try go(k.race1, s, .{ .x = 1 }, 1024, &a); +} + +/// `rows` fp32 rows into bf16 rows of `out` at column `col0`: `n` columns rounded, the rest of `width` set to -inf. +pub fn tobf(k: *const Kernels, s: cuda.Stream, x: u64, rows: usize, stride: usize, n: usize, out: u64, out_stride: usize, col0: usize, width: usize) !void { + var a: cuda.Args = .{}; + a.add(x); + a.add(@as(i64, @intCast(stride))); + a.add(int(n)); + a.add(out); + a.add(@as(i64, @intCast(out_stride))); + a.add(@as(i64, @intCast(col0))); + a.add(int(width)); + try go(k.tobf, s, .{ .x = @intCast((width + 255) / 256), .y = @intCast(rows) }, 256, &a); +} + +/// ops.cu's Ink2Words: a link step's header and ids, passed by value. +pub const Words = extern struct { w: [96]u32 }; + +/// The first `n` of `words` to `dst` on the stream (no host buffer to keep alive). +pub fn putWords(k: *const Kernels, s: cuda.Stream, dst: u64, n: usize, words: Words) !void { + var a: cuda.Args = .{}; + a.add(dst); + a.add(int(n)); + a.add(words); + try go(k.put_words, s, .{ .x = 1 }, 128, &a); +} + +test "ops: the argument structs keep ops.cu's layouts" { + try std.testing.expectEqual(@as(usize, 8 * 8 + 8 + 8 + 3 * 8 + 8 + 6 * 4), @sizeOf(MixArgs)); + try std.testing.expectEqual(@as(usize, 9 * 8 + 2 * 8 + 7 * 4 + 4), @sizeOf(ConvArgs)); + try std.testing.expectEqual(@as(usize, 32), @sizeOf(RewindSite)); + try std.testing.expectEqual(@as(usize, 6 * 8 + 6 * 4), @sizeOf(GateUpArgs)); +} diff --git a/zig/src/families/lfm2_moe/backend.zig b/zig/src/families/lfm2_moe/backend.zig index ffe1ffb88d3..858f8f45896 100644 --- a/zig/src/families/lfm2_moe/backend.zig +++ b/zig/src/families/lfm2_moe/backend.zig @@ -7,6 +7,7 @@ const c = @import("config.zig"); const st = @import("state.zig"); const fwd = @import("forward.zig"); const snapshot = @import("snapshot.zig"); +const steps = @import("prefill_steps.zig"); const Model = @import("model.zig").Model; const be = lanes.backend; @@ -25,6 +26,8 @@ pub const Metal = struct { timed: usize = 0, /// Forwards run so far: a stream's tapped rows in the scratch are current while their gen matches. gen: u64 = 0, + /// Streams whose prompt passes are in progress: each one's next row (prefill_step) and a mark kept late. + fills: std.AutoHashMapUnmanaged(*lanes.Stream, steps.Fill) = .empty, pub fn init(gpa: std.mem.Allocator, model: *Model, options: Options) !*Metal { const out = try gpa.create(Metal); @@ -51,6 +54,7 @@ pub const Metal = struct { self.gpa.destroy(cache.*); } self.caches.deinit(self.gpa); + self.fills.deinit(self.gpa); self.scratch.deinit(); self.gpa.destroy(self); } @@ -90,7 +94,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 { @@ -150,14 +154,22 @@ pub const Metal = struct { const t = self.scratch.taps orelse return error.UnpreparedLfmTaps; if (layers.len != t.count) return error.UnpreparedLfmTaps; const cache = try self.cacheOf(stream); - const held = cache.tap orelse return error.LfmTapsNotHeld; - if (count == 0 or start < held.start or start + count > held.start + held.rows) return error.LfmTapsNotHeld; const width = self.tapBytes(); + // a stepped pass's latest chunk: its rows stay in the scratch until the next forward (#3021) + if (cache.chunk_tap) |k| if (!within(cache.tap, start, count) and steps.holds(.{ .start = k.start, .rows = k.rows, .gen = k.gen }, self.gen, start, count)) + return .{ .buffer = @intFromPtr(t.buf.id), .offset = (k.row + @as(usize, @intCast(start - k.start))) * width, .rows = count, .row_bytes = @intCast(width), .space = .device, .dtype = .bf16 }; + const held = cache.tap orelse return error.LfmTapsNotHeld; + if (!within(held, start, count)) return error.LfmTapsNotHeld; const buf = if (held.gen == 0) cache.last_tap.? else if (held.gen == self.gen) t.buf else return error.StaleLfmTaps; const row = held.row + @as(usize, @intCast(start - held.start)); return .{ .buffer = @intFromPtr(buf.id), .offset = row * width, .rows = count, .row_bytes = @intCast(width), .space = .device, .dtype = .bf16 }; } + fn within(tap: ?st.TapRows, start: u64, count: u32) bool { + const h = tap orelse return false; + return count != 0 and start >= h.start and start + count <= h.start + h.rows; + } + /// The prompt's last row's taps, copied beside the stream's caches for its first draft (gen 0: kept there). fn keepLastTap(self: *Metal, cache: *st.Cache, row: usize, position: usize) !void { const width = self.tapBytes(); @@ -167,7 +179,42 @@ pub const Metal = struct { cache.tap = .{ .start = position, .row = 0, .rows = 1, .gen = 0 }; } + /// One chunk's work for `steps.step`: the forward, the drafter's rows (a sink, or `later` via featuresFn), marks. + const Run = struct { + m: *Metal, + cache: *st.Cache, + 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 self.run(&.{.{ .cache = r.cache, .rows = end - at }}, ids[at..end], false, .last); + if (r.sink) |k| { + const width = self.tapBytes(); + const f: be.Features = .{ .buffer = @intFromPtr(self.scratch.taps.?.buf.id), .rows = @intCast(end - at), .row_bytes = @intCast(width), .space = .device, .dtype = .bf16 }; + try k.take(k.ptr, stream, f, at); + } + if (r.later) r.cache.chunk_tap = .{ .start = at, .row = 0, .rows = end - at, .gen = self.gen }; + if ((r.sink != null or r.later) and end == ids.len) try self.keepLastTap(r.cache, end - 1 - at, end - 1); + lanes.prefill_widths.completed(self.gpa, stream, end - at); + } + + pub fn keep(_: Run, stream: *lanes.Stream, at: u32) void { + if (stream.reuse.hook) |hk| hk.at(hk.ptr, stream, at); + } + }; + fn prefillWith(self: *Metal, stream: *lanes.Stream, sink: ?be.FeatureSink) !void { + const f = try self.opening(stream, sink != null); + errdefer self.drop(stream); + const r: Run = .{ .m = self, .cache = try self.cacheOf(stream), .sink = sink, .later = false }; + while (!try steps.step(r, stream, f, self.options.chunk, false)) {} + _ = self.fills.remove(stream); + } + + /// The stream's cache made and a kept state restored into it: its pass from the returned fill's row. + fn opening(self: *Metal, stream: *lanes.Stream, drafting: bool) !*steps.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.InvalidLfmPrompt; const capacity = @min(self.options.capacity, ids.len + stream.max_new + st.window_rows); @@ -181,36 +228,46 @@ pub const Metal = struct { if (stream.reuse.saved) |saved| { // a kept state of this prompt's prefix: the pass starts there const snap: *snapshot.Snap = @ptrCast(@alignCast(saved)); // a drafting stream resumes only a state kept with its drafter's context - const drafter_less = sink != null and snap.draft == null; + const drafter_less = drafting and snap.draft == null; if (snap.at < ids.len and !drafter_less) if (snapshot.restore(cache, snap)) |_| { at = snap.at; } else |_| {}; stream.cached = @intCast(at); stream.reuse_failed = at == 0; } - var mark: usize = 0; - while (at < ids.len) { - var end: usize = @min(ids.len, at + self.options.chunk); - for (stream.chunks) |boundary| if (boundary > at) { - end = @min(end, boundary); - break; - }; - while (mark < stream.reuse.marks.len and stream.reuse.marks[mark] <= at) mark += 1; - if (mark < stream.reuse.marks.len) end = @min(end, stream.reuse.marks[mark]); - try self.run(&.{.{ .cache = cache, .rows = end - at }}, ids[at..end], false, .last); - if (sink) |k| { - const width = self.tapBytes(); - const f: be.Features = .{ .buffer = @intFromPtr(self.scratch.taps.?.buf.id), .rows = @intCast(end - at), .row_bytes = @intCast(width), .space = .device, .dtype = .bf16 }; - try k.take(k.ptr, stream, f, at); - if (end == ids.len) try self.keepLastTap(cache, end - 1 - at, end - 1); - } - lanes.prefill_widths.completed(self.gpa, stream, end - at); - at = end; - if (stream.reuse.hook) |hk| if (std.mem.indexOfScalar(u32, stream.reuse.marks, @intCast(at)) != null) - hk.at(hk.ptr, stream, @intCast(at)); + try self.fills.put(self.gpa, stream, .{ .at = at }); + stream.fill_at.store(@intCast(at), .monotonic); // what the restore kept: 0 when none + return self.fills.getPtr(stream).?; + } + + /// 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.fills.remove(stream); + if (self.caches.fetchRemove(stream)) |entry| { + entry.value.deinit(); + self.gpa.destroy(entry.value); } } + /// 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); + // 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.scratch.taps != null; + const f = self.fills.getPtr(stream) orelse try self.opening(stream, later); + errdefer self.drop(stream); + const r: Run = .{ .m = self, .cache = try self.cacheOf(stream), .sink = null, .later = later }; + const done = try steps.step(r, stream, f, self.options.chunk, later); + if (done) _ = self.fills.remove(stream); + return done; + } + + /// The host cancels between chunks: the last chunk's state is kept (its forward has waited; no prompt work runs). + fn cancelPrefillFn(ptr: *anyopaque, stream: *lanes.Stream) !void { + const self = cast(ptr); + steps.cancel(stream, self.fills.get(stream)); + } + fn firstFn(ptr: *anyopaque, stream: *lanes.Stream, position: u64) !u64 { const self = cast(ptr); const cache = try self.cacheOf(stream); @@ -296,6 +353,7 @@ pub const Metal = struct { fn releaseFn(ptr: *anyopaque, stream: *lanes.Stream) void { const self = cast(ptr); + _ = self.fills.remove(stream); // a stream that leaves mid-pass if (self.caches.fetchRemove(stream)) |entry| { entry.value.deinit(); self.gpa.destroy(entry.value); diff --git a/zig/src/families/lfm2_moe/prefill_steps.zig b/zig/src/families/lfm2_moe/prefill_steps.zig new file mode 100644 index 00000000000..c6e4fd35442 --- /dev/null +++ b/zig/src/families/lfm2_moe/prefill_steps.zig @@ -0,0 +1,54 @@ +//! LFM2-MoE 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 the next planned chunk start and the next kept mark (main's loop body). +pub fn chunkEnd(len: usize, at: usize, rows: usize, chunks: []const u32, marks: []const u32) usize { + var end: usize = @min(len, at + rows); + for (chunks) |boundary| if (boundary > at) { + end = @min(end, boundary); + break; + }; + // main carried `mark` across chunks; it only skips marks at or before `at`, so a fresh scan stops there too + var mark: usize = 0; + while (mark < marks.len and marks[mark] <= at) mark += 1; + if (mark < marks.len) end = @min(end, marks[mark]); + 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, 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); + try r.run(s, f.at, end); + s.fill_at.store(@intCast(end), .monotonic); // the forward waits on its command buffer: these rows are in + 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; +} + +/// The host cancels between chunks: the state at the pass's last chunk end is kept (no prompt work runs). +pub fn cancel(s: *Stream, f: ?Fill) void { + if (f) |x| s.keepInterruptedPrefill(@intCast(x.at)); +} + +/// Rows a tap holds: `rows` from `start`, written at forward `gen` (the scratch's rows until the next forward). +pub const Held = struct { start: u64 = 0, rows: usize = 0, gen: u64 = 0 }; + +/// Whether `h` holds [start, start + count) and no forward has rewritten the scratch since (its gen is `now`). +pub fn holds(h: Held, now: u64, start: u64, count: u32) bool { + return h.gen == now and 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/lfm2_moe/prefill_steps_test.zig b/zig/src/families/lfm2_moe/prefill_steps_test.zig new file mode 100644 index 00000000000..0cdbddb67f9 --- /dev/null +++ b/zig/src/families/lfm2_moe/prefill_steps_test.zig @@ -0,0 +1,292 @@ +//! LFM2-MoE Metal's stepped prompt pass on recording fakes: 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 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's prefillWith before #3021), copied as they were, `mark` carried. +fn mainCuts(a: std.mem.Allocator, total: usize, from: usize, rows: usize, planned: []const u32, kept_marks: []const u32) ![][2]usize { + var out: std.ArrayList([2]usize) = .empty; + var at = from; + var mark: usize = 0; + while (at < total) { + var end: usize = @min(total, at + rows); + for (planned) |boundary| if (boundary > at) { + end = @min(end, boundary); + break; + }; + while (mark < kept_marks.len and kept_marks[mark] <= at) mark += 1; + if (mark < kept_marks.len) end = @min(end, kept_marks[mark]); + try out.append(a, .{ at, end }); + at = end; + } + return out.toOwnedSlice(a); +} + +/// Records each chunk run and each kept mark, as backend.zig's 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 29-token prompt at an 8-row cap: planned starts at 3 and 20, a kept mark at 11. +const len = 29; +const cap = 8; +const chunks = [_]u32{ 3, 20 }; +const marks = [_]u32{11}; + +fn stream(prompt: []const u32, id: []const u8) !lanes.Stream { + return lanes.Stream.init(gpa, .{ .id = id, .prompt = prompt, .max_new = 4, .chunks = &chunks, .reuse = .{ .marks = &marks } }); +} + +test "LFM2-MoE Metal steps: one call runs one chunk at today's cut, and the calls' chunks are the whole loop's" { + var ids: [len]u32 = undefined; + for (&ids, 0..) |*x, i| x.* = @intCast(i % 97 + 3); + const want = try mainCuts(gpa, len, 0, cap, &chunks, &marks); + defer gpa.free(want); + try t.expectEqualSlices([2]usize, &.{ .{ 0, 3 }, .{ 3, 11 }, .{ 11, 19 }, .{ 19, 20 }, .{ 20, 28 }, .{ 28, 29 } }, want); + for ([_]bool{ false, true }) |later| { // the whole pass (prefillWith) 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, cap, 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 11: kept at once by the whole pass, at the next call's start by a drafting stream + if (i == 1) try t.expectEqual(@as(usize, if (later) 2 else 3), log.items.len); + } + try t.expectEqual(@as(usize, 7), log.items.len); + try t.expectEqual(Event{ .keep = 11 }, log.items[2]); // before the chunk after it, in both + } + // a pass resumed from a kept state at 11 cuts as main's loop does from there + const resumed = try mainCuts(gpa, len, 11, cap, &chunks, &marks); + 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 = 11 }; + while (!try steps.step(Rec{ .log = &log }, &s, &f, cap, 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); +} + +test "LFM2-MoE Metal steps: a cancel between chunks keeps the state at the last chunk's end" { + var ids: [len]u32 = undefined; + for (&ids, 0..) |*x, i| x.* = @intCast(i + 3); + var s = try lanes.Stream.init(gpa, .{ .id = "x", .prompt = &ids, .max_new = 4, .chunks = &chunks, .reuse = .{ .marks = &marks } }); + defer s.deinit(gpa); + var log: std.ArrayList(Event) = .empty; + defer log.deinit(gpa); + const Hook = struct { + var kept: ?u32 = null; + fn at(_: *anyopaque, _: *lanes.Stream, row: u32) void { + kept = row; + } + }; + var dummy: u8 = 0; + s.reuse.hook = .{ .ptr = &dummy, .at = Hook.at }; + var f: steps.Fill = .{ .at = 0 }; + _ = try steps.step(Rec{ .log = &log }, &s, &f, cap, false); + _ = try steps.step(Rec{ .log = &log }, &s, &f, cap, false); + _ = try steps.step(Rec{ .log = &log }, &s, &f, cap, false); + steps.cancel(&s, f); + try t.expectEqual(@as(?u32, 19), Hook.kept); // rows 0..19 are in; no chunk ran for the cancel + var n: usize = 0; + for (log.items) |e| n += @intFromBool(e == .chunk); + try t.expectEqual(@as(usize, 3), n); + Hook.kept = null; + steps.cancel(&s, null); // no pass in progress: nothing kept + try t.expectEqual(@as(?u32, null), Hook.kept); +} + +/// The lanes fake with LFM2-MoE's stepping in front: its prompt passes a chunk a call at `rows` (4 here), logged. +const Lfm = 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, + gen: u64 = 0, // Metal.gen: every forward, a prompt chunk's or a decode's, rewrites the scratch + vt: be.Backend.VTable = undefined, + + var current: *Lfm = undefined; + const rows = 4; + + fn init(x: *Lfm) 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: *Lfm) 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.gen += 1; + try x.held.put(gpa, s, .{ .start = at, .rows = end - at, .gen = x.gen }); // chunk_tap + 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, 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 { + current.gen += 1; + 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 { + current.gen += 1; + for (windows) |w| try current.log.append(gpa, .{ .decode = w.stream.id[0] }); + return current.inner.vtable.verify(ptr, windows, out); + } + + /// featuresFn's stepped rule: the latest chunk's rows, while no forward 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.LfmTapsNotHeld; + if (!steps.holds(h, x.gen, start, count)) return error.LfmTapsNotHeld; + return .{ .buffer = h.start, .rows = count, .row_bytes = 2, .space = .host, .dtype = .bf16 }; + } +}; + +test "LFM2-MoE 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 lfm: Lfm = .{ .fake = .{ .gpa = gpa } }; + defer lfm.deinit(); + var clock: lanes.fake.FixedClock = .{}; + var engine = lanes.Engine.init(gpa, &cfg, lfm.init(), clock.clock()); + defer engine.deinit(); + try t.expect(engine.fills()); // the lane host steps this backend's prompts (lane_host_fill.zig) + 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, lfm.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 (lfm.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 (lfm.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(); + // the decodes since rewrote the scratch: b's last chunk's rows are no longer served (StaleLfmTaps' rule) + try t.expect(!steps.holds(lfm.held.get(&b).?, lfm.gen, 8, 4)); +} + +/// 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 "LFM2-MoE Metal steps: a drafter absorbs every chunk's tapped rows, and a mark keeps after its chunk's absorb" { + var lfm: Lfm = .{ .fake = .{ .gpa = gpa } }; + defer lfm.deinit(); + var head: Head = .{ .log = &lfm.log }; + var wrapped = try lanes.drafted.Drafted.init(gpa, lfm.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, lfm.log.items.len); + for (want, lfm.log.items) |w, g| try t.expectEqual(w, g); +} diff --git a/zig/src/families/lfm2_moe/state.zig b/zig/src/families/lfm2_moe/state.zig index 9e7d898a2e3..d175a27b1dd 100644 --- a/zig/src/families/lfm2_moe/state.zig +++ b/zig/src/families/lfm2_moe/state.zig @@ -69,6 +69,8 @@ pub const Cache = struct { /// The stream's latest tapped rows in the scratch, and its prompt's last row's taps (kept for the first draft). tap: ?TapRows = null, last_tap: ?mtl.Buffer = null, + /// A stepped prompt pass's latest chunk's tapped rows in the scratch (#3021): featuresFn serves them while current. + chunk_tap: ?TapRows = null, pub fn init(gpa: std.mem.Allocator, device: mtl.Device, attention: *const [c.layers]bool, capacity: usize) !Cache { var out: Cache = .{ .memory = .{ .gpa = gpa, .device = device }, .capacity = capacity, .blocks = undefined, .logits = undefined }; @@ -107,11 +109,17 @@ pub const Cache = struct { const last = self.last orelse return error.NothingToKeep; if (path.len == 0 or path.len > last.rows) return error.NothingToKeep; for (path, 0..) |p, i| if (p != i) return error.UnsupportedLfmTree; - const row = last.base + path.len - 1; - self.restore(scratch, row); + self.last = null; + // The whole round kept: commit() restored its last row's conv state and run() copied its logits; len is right. + if (path.len == last.rows) return; + self.take(scratch, last.base + path.len - 1); self.len = last.start + path.len; + } + + /// A recorded call's scratch row as the stream's latest: that row's conv state and logits. + fn take(self: *Cache, scratch: *const Scratch, row: usize) void { + self.restore(scratch, row); @memcpy(self.logits.contents()[0 .. c.vocab * 2], (scratch.logits.contents() + row * c.vocab * 2)[0 .. c.vocab * 2]); - self.last = null; } }; @@ -261,3 +269,65 @@ test "a stream's cache bytes: logits and conv windows at any length, keys and va attention[3] = true; try std.testing.expectEqual(@as(u64, 2 * 2 * c.kv_heads * c.head_dim * 2), cacheBytes(&attention, 1) - cacheBytes(&attention, 0)); } + +/// As forward.run settles a recorded call once the GPU is done: each stream's last row's logits, then commit. +fn settle(s: *const Scratch, caches: []Cache, rows: []const usize) void { + var base: usize = 0; + for (caches, rows) |*cache, n| { + @memcpy(cache.logits.contents()[0 .. c.vocab * 2], (s.logits.contents() + (base + n - 1) * c.vocab * 2)[0 .. c.vocab * 2]); + cache.commit(s, base, n, true); + base += n; + } +} + +fn expectSameState(a: *const Cache, b: *const Cache) !void { + try std.testing.expectEqual(a.len, b.len); + try std.testing.expect(a.last == null and b.last == null); + try std.testing.expectEqualSlices(u8, a.logits.contents()[0 .. c.vocab * 2], b.logits.contents()[0 .. c.vocab * 2]); + for (a.blocks, b.blocks) |x, y| if (x == .conv) { + try std.testing.expectEqualSlices(u8, x.conv.contents()[0..conv_bytes], y.conv.contents()[0..conv_bytes]); + }; +} + +test "lfm2_moe: keeping a whole recorded round copies nothing and leaves the state the copy would; a partial path restores" { + const gpa = std.testing.allocator; + const device = mtl.Device.init() catch return error.SkipZigTest; + defer device.deinit(); + var attention: [c.layers]bool = @splat(false); + for (&attention, 0..) |*a, i| a.* = i % 4 == 2; + var s = try Scratch.init(gpa, device, &attention, batch_rows); + defer s.deinit(); + // The recorded rows' conv states and logits, as a two-stream round of 4 and 3 rows leaves them. + var prng = std.Random.DefaultPrng.init(820); + prng.random().bytes(s.logits.contents()[0 .. 7 * c.vocab * 2]); + for (s.snapshots) |snapshot| if (snapshot) |b| prng.random().bytes(b.contents()[0 .. 7 * conv_bytes]); + // The streams and their twins, which take the copying path. + var caches: [4]Cache = undefined; + var made: usize = 0; + defer for (caches[0..made]) |*cache| cache.deinit(); + while (made < caches.len) : (made += 1) caches[made] = try Cache.init(gpa, device, &attention, 64); + const rows = [_]usize{ 4, 3 }; + for ([_]usize{ 0, 2 }) |at| { + caches[at].len = 5; + caches[at + 1].len = 40; + settle(&s, caches[at..][0..2], &rows); + } + // The first stream keeps every row: no copy, and the state is the copy's, byte for byte. + try caches[0].keep(&s, &.{ 0, 1, 2, 3 }); + caches[2].last = null; + caches[2].take(&s, 3); + caches[2].len = 5 + 4; + try expectSameState(&caches[0], &caches[2]); + try std.testing.expectError(error.NothingToKeep, caches[0].keep(&s, &.{0})); + // The second keeps its first row: its conv state and logits come back from scratch row 4, not its last row 6. + try std.testing.expect(!std.mem.eql(u8, caches[1].logits.contents()[0 .. c.vocab * 2], (s.logits.contents() + 4 * c.vocab * 2)[0 .. c.vocab * 2])); + try caches[1].keep(&s, &.{0}); + caches[3].last = null; + caches[3].take(&s, 4); + caches[3].len = 40 + 1; + try expectSameState(&caches[1], &caches[3]); + try std.testing.expectEqualSlices(u8, (s.logits.contents() + 4 * c.vocab * 2)[0 .. c.vocab * 2], caches[1].logits.contents()[0 .. c.vocab * 2]); + for (caches[1].blocks, s.snapshots) |b, snapshot| if (b == .conv) { + try std.testing.expectEqualSlices(u8, (snapshot.?.contents() + 4 * conv_bytes)[0..conv_bytes], b.conv.contents()[0..conv_bytes]); + }; +} diff --git a/zig/src/families/lfm3/backend.zig b/zig/src/families/lfm3/backend.zig index c200e43082f..e83da99a0f6 100644 --- a/zig/src/families/lfm3/backend.zig +++ b/zig/src/families/lfm3/backend.zig @@ -10,6 +10,8 @@ const snapshot = @import("snapshot.zig"); const Model = @import("model.zig").Model; const be = lanes.backend; const prefill_control = @import("prefill_control.zig"); +const steps = @import("prefill_steps.zig"); +const image_rows = @import("image_rows.zig"); pub const greedy = @import("greedy.zig"); pub const Options = struct { capacity: usize, chunk: usize = 128, streams: u32 = 8 }; @@ -26,6 +28,11 @@ pub const Metal = struct { /// Forward ms by window width, timed at load: the lane core weighs drafts against them. costs: [st.window_rows]lanes.config.Cost = undefined, timed: usize = 0, + /// Streams whose prompt passes are in progress: each one's next row and its images, prepared once (#3021). + fills: std.AutoHashMapUnmanaged(*lanes.Stream, Pass) = .empty, + + /// A prompt pass in progress: the next chunk's first row, and the image rows prepared at its first call. + const Pass = struct { at: usize, images: ?image_rows.Images }; pub fn init(gpa: std.mem.Allocator, model: *Model, options: Options) !*Metal { if (options.chunk == 0 or options.capacity == 0 or options.capacity > st.max_context or options.streams == 0) @@ -48,6 +55,7 @@ pub const Metal = struct { self.gpa.destroy(cache.*); } self.caches.deinit(self.gpa); + self.fills.deinit(self.gpa); self.scratch.deinit(); self.gpa.destroy(self); } @@ -95,7 +103,7 @@ pub const Metal = struct { } pub fn backend(self: *Metal) be.Backend { - return .{ .ptr = self, .vtable = &.{ .prefill = prefillFn, .first = firstFn, .first_masked = firstMaskedFn, .queue = queueFn, .read = readFn, .verify = verifyFn, .keep = keepFn, .draft = draftFn, .release = releaseFn, .reports_fill = true } }; + return .{ .ptr = self, .vtable = &.{ .prefill = prefillFn, .prefill_step = prefillStepFn, .cancel_prefill = cancelPrefillFn, .first = firstFn, .first_masked = firstMaskedFn, .queue = queueFn, .read = readFn, .verify = verifyFn, .keep = keepFn, .draft = draftFn, .release = releaseFn, .reports_fill = true } }; } fn cast(ptr: *anyopaque) *Metal { @@ -116,10 +124,37 @@ pub const Metal = struct { fn prefillFn(ptr: *anyopaque, stream: *lanes.Stream) !void { const self = cast(ptr); + const p = try self.opening(stream, true); + errdefer self.drop(stream); + const r: Run = .{ .m = self, .cache = try self.cacheOf(stream), .images = p.images }; + while (!try steps.step(r, stream, &p.at, self.options.chunk, true)) {} + _ = self.fills.remove(stream); + try prefill_control.finished(stream); + } + + /// One chunk's forward for `steps.step`, and a kept mark's hook. + const Run = struct { + m: *Metal, + cache: *st.Cache, + images: ?image_rows.Images, + + pub fn run(r: Run, stream: *lanes.Stream, at: usize, end: usize) !void { + const ids = stream.prompt(); + try fwd.runWithImages(r.m.model, &r.m.scratch, &.{.{ .cache = r.cache, .rows = end - at }}, ids[at..end], false, .last, r.images); + } + + pub fn keep(_: Run, stream: *lanes.Stream, at: u32) void { + if (stream.reuse.hook) |hk| hk.at(hk.ptr, stream, at); + } + }; + + /// The stream's cache made, a kept state restored and its images prepared: its pass from the returned row. + fn opening(self: *Metal, stream: *lanes.Stream, whole: bool) !*Pass { const ids = stream.prompt(); if (stream.images.len != 0 and self.images == null) return error.Lfm3VisionNotImplemented; if (ids.len == 0 or ids.len + stream.max_new > self.options.capacity or self.caches.contains(stream)) return error.InvalidLfmPrompt; - try prefill_control.before(stream, 0); + // a step leaves yielding to the lane host, which runs other streams' rounds between chunks + if (whole) try prefill_control.before(stream, 0) else if (stream.isCancelled()) return error.Cancelled; const capacity = @min(self.options.capacity, ids.len + stream.max_new + st.window_rows); const cache = try self.newCache(capacity); errdefer self.gpa.destroy(cache); @@ -137,24 +172,35 @@ pub const Metal = struct { stream.reuse_failed = at == 0; } prefill_control.completed(stream, at); - const image_rows = if (self.images) |provider| try provider.prepare(provider.ctx, stream, at) else null; - var mark: usize = 0; - while (at < ids.len) { - try prefill_control.before(stream, at); - var end: usize = @min(ids.len, at + self.options.chunk); - for (stream.chunks) |boundary| if (boundary > at) { - end = @min(end, boundary); - break; - }; - while (mark < stream.reuse.marks.len and stream.reuse.marks[mark] <= at) mark += 1; - if (mark < stream.reuse.marks.len) end = @min(end, stream.reuse.marks[mark]); - try fwd.runWithImages(self.model, &self.scratch, &.{.{ .cache = cache, .rows = end - at }}, ids[at..end], false, .last, image_rows); - at = end; - prefill_control.completed(stream, at); - if (stream.reuse.hook) |hk| if (std.mem.indexOfScalar(u32, stream.reuse.marks, @intCast(at)) != null) - hk.at(hk.ptr, stream, @intCast(at)); + const images = if (self.images) |provider| try provider.prepare(provider.ctx, stream, at) else null; + try self.fills.put(self.gpa, stream, .{ .at = at, .images = images }); + return self.fills.getPtr(stream).?; + } + + /// 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.fills.remove(stream); + if (self.caches.fetchRemove(stream)) |entry| { + entry.value.deinit(); + self.gpa.destroy(entry.value); } - try prefill_control.finished(stream); + } + + /// 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 p = self.fills.getPtr(stream) orelse try self.opening(stream, false); + errdefer self.drop(stream); + const r: Run = .{ .m = self, .cache = try self.cacheOf(stream), .images = p.images }; + const done = try steps.step(r, stream, &p.at, self.options.chunk, false); + if (done) _ = self.fills.remove(stream); + return done; + } + + /// The host cancels between chunks: the last chunk's state is kept (its forward has waited; no prompt work runs). + fn cancelPrefillFn(ptr: *anyopaque, stream: *lanes.Stream) !void { + const self = cast(ptr); + steps.cancel(stream, if (self.fills.get(stream)) |p| p.at else null); } fn firstFn(ptr: *anyopaque, stream: *lanes.Stream, position: u64) !u64 { @@ -234,6 +280,7 @@ pub const Metal = struct { fn releaseFn(ptr: *anyopaque, stream: *lanes.Stream) void { const self = cast(ptr); + _ = self.fills.remove(stream); // a stream that leaves mid-pass if (self.caches.fetchRemove(stream)) |entry| { entry.value.deinit(); self.gpa.destroy(entry.value); diff --git a/zig/src/families/lfm3/forward.zig b/zig/src/families/lfm3/forward.zig index cae89f81a4f..78d34d3e885 100644 --- a/zig/src/families/lfm3/forward.zig +++ b/zig/src/families/lfm3/forward.zig @@ -346,7 +346,8 @@ fn conv(enc: *Encoder, s: *st.Scratch, cv: wts.Conv, layer: usize, segments: []c const AttentionSegment = @import("kernels.zig").AttentionSegment; -fn sharedAttention(enc: *Encoder, s: *st.Scratch, segments: []const Segment, layer: usize, sliding: bool, total: usize) !void { +/// The shared round's table at `layer` and each row's stream, for qk and attention; the most chunks a row reads. +fn segmentTable(s: *st.Scratch, segments: []const Segment, layer: usize, sliding: bool) usize { const table = s.attention_segments.slice(AttentionSegment, c.layers * st.batch_rows)[layer * st.batch_rows ..][0..st.batch_rows]; const row_segments = s.attention_rows.slice(u32, st.batch_rows); var base: usize = 0; @@ -360,6 +361,32 @@ fn sharedAttention(enc: *Encoder, s: *st.Scratch, segments: []const Segment, lay @memset(row_segments[base..][0..seg.rows], @intCast(i)); base += seg.rows; } + return used; +} + +/// lfm3_qk over every row of a shared round in one dispatch: each row's stream, len and cache come from the table. +fn sharedQk(enc: *Encoder, s: *st.Scratch, a: wts.Attention, segments: []const Segment, layer: usize, qk: QkArgs, total: usize) !void { + try enc.begin(.attention_prepare); + enc.pipe("lfm3_qk_segments"); + for (segments) |seg| { + const cache = seg.cache.blocks[layer].attention; + enc.e.useResource(cache.keys, mtl.ResourceUsage.write); + enc.e.useResource(cache.values, mtl.ResourceUsage.write); + } + enc.e.setBuffer(s.q, 0, 0); + enc.e.setBuffer(s.k, 0, 1); + enc.e.setBuffer(s.v, 0, 2); + enc.tensor(a.q_norm, 3); + enc.tensor(a.k_norm, 4); + enc.e.setBytes(std.mem.asBytes(&qk), 5); + enc.e.setBuffer(s.queries, 0, 6); + enc.e.setBuffer(s.attention_segments, layer * st.batch_rows * @sizeOf(AttentionSegment), 7); + enc.e.setBuffer(s.attention_rows, 0, 8); + enc.groups(.{ c.query_heads + c.kv_heads, total, 1 }, .{ 32, 1, 1 }); + try enc.end(); +} + +fn sharedAttention(enc: *Encoder, s: *st.Scratch, segments: []const Segment, layer: usize, used: usize, total: usize) !void { try enc.begin(.attention); enc.pipe("lfm3_attn_segments"); for (segments) |seg| { @@ -405,17 +432,26 @@ fn attention(enc: *Encoder, s: *st.Scratch, a: wts.Attention, segments: []const const sliding = enc.m.config.layer_types[layer] == .sliding_attention; const rotary = if (sliding) enc.m.config.sliding_rotary else enc.m.config.full_rotary; const shared = segments.len > 1 and total <= st.batch_rows; + const rope = QkArgs{ + .len = 0, + .cap = 0, + .eps = c.eps, + .log2_theta = std.math.log2(rotary.theta), + .rotary_pairs = @intFromFloat(c.head_dim * rotary.partial / 2), + }; + if (shared) { + const used = segmentTable(s, segments, layer, sliding); + try sharedQk(enc, s, a, segments, layer, rope, total); + try sharedAttention(enc, s, segments, layer, used, total); + } + // Otherwise each stream's qk, then its attention in slices. var base: usize = 0; - for (segments) |seg| { + for (if (shared) segments[0..0] else segments) |seg| { const cache = seg.cache.blocks[layer].attention; const cap: u32 = @intCast(seg.cache.capacity); - const qk = QkArgs{ - .len = @intCast(seg.cache.len), - .cap = cap, - .eps = c.eps, - .log2_theta = std.math.log2(rotary.theta), - .rotary_pairs = @intFromFloat(c.head_dim * rotary.partial / 2), - }; + var qk = rope; + qk.len = @intCast(seg.cache.len); + qk.cap = cap; try enc.begin(.attention_prepare); enc.pipe("lfm3_qk"); enc.e.setBuffer(s.q, base * c.hidden * 2, 0); @@ -429,10 +465,6 @@ fn attention(enc: *Encoder, s: *st.Scratch, a: wts.Attention, segments: []const enc.e.setBuffer(cache.values, 0, 8); enc.groups(.{ c.query_heads + c.kv_heads, seg.rows, 1 }, .{ 32, 1, 1 }); try enc.end(); - if (shared) { - base += seg.rows; - continue; - } var at: usize = 0; while (at < seg.rows) : (at += st.attn_slice) { const rows = @min(seg.rows - at, st.attn_slice); @@ -468,7 +500,6 @@ fn attention(enc: *Encoder, s: *st.Scratch, a: wts.Attention, segments: []const } base += seg.rows; } - if (shared) try sharedAttention(enc, s, segments, layer, sliding, total); try enc.begin(.activation); enc.pipe("lfm3_gate"); enc.e.setBuffer(s.y, 0, 0); diff --git a/zig/src/families/lfm3/kernels.zig b/zig/src/families/lfm3/kernels.zig index 3f7af9e9864..5d2e26ad39e 100644 --- a/zig/src/families/lfm3/kernels.zig +++ b/zig/src/families/lfm3/kernels.zig @@ -11,6 +11,11 @@ pub const QkArgs = extern struct { len: u32, cap: u32, eps: f32, log2_theta: f32 pub const AttentionArgs = extern struct { len: u32, cap: u32, scale: f32, window: u32, chunk_base: u32 = 0 }; pub const AttentionSegment = extern struct { keys: u64, values: u64, base: u32, rows: u32, args: AttentionArgs, pad: u32 = 0 }; +comptime { // ops.metal's lfm3_qk_segment reads this table too, field for field + std.debug.assert(@sizeOf(AttentionSegment) == 48 and @alignOf(AttentionSegment) == 8); + std.debug.assert(@offsetOf(AttentionSegment, "base") == 16 and @offsetOf(AttentionSegment, "args") == 24); + std.debug.assert(@offsetOf(AttentionArgs, "cap") == 4 and @offsetOf(AttentionArgs, "chunk_base") == 16); +} pub const ConvSegment = extern struct { state: u64, base: u32, rows: u32 }; comptime { @@ -20,9 +25,9 @@ comptime { } pub const names = [_][:0]const u8{ - "lfm3_embed_b4", "lfm3_embed_b6", "lfm3_embed_b8", "lfm3_norm", "lfm3_post_add", "lfm3_add", "lfm3_post_norm", - "lfm3_attn_segments", "lfm3_attn_segments_merge", "lfm3_conv", "lfm3_qk", "lfm3_gate", "lfm3_swiglu", "lfm3_attn_partial", - "lfm3_attn_merge", "lfm3_conv_segments", + "lfm3_embed_b4", "lfm3_embed_b6", "lfm3_embed_b8", "lfm3_norm", "lfm3_post_add", "lfm3_add", "lfm3_post_norm", + "lfm3_attn_segments", "lfm3_attn_segments_merge", "lfm3_conv", "lfm3_qk", "lfm3_gate", "lfm3_swiglu", "lfm3_attn_partial", + "lfm3_attn_merge", "lfm3_conv_segments", "lfm3_qk_segments", }; pub const Kernels = struct { diff --git a/zig/src/families/lfm3/prefill_steps.zig b/zig/src/families/lfm3/prefill_steps.zig new file mode 100644 index 00000000000..88744514f44 --- /dev/null +++ b/zig/src/families/lfm3/prefill_steps.zig @@ -0,0 +1,43 @@ +//! LFM3 Metal's prompt pass a chunk a call (#3021): today's cuts, one chunk a step, marks kept as each chunk lands. +const std = @import("std"); +const lanes = @import("lanes"); +const control = @import("prefill_control.zig"); +const Stream = lanes.Stream; + +/// A chunk from `at`: `rows` at most, cut at the next planned chunk start and the next kept mark (main's loop body). +pub fn chunkEnd(len: usize, at: usize, rows: usize, chunks: []const u32, marks: []const u32) usize { + var end: usize = @min(len, at + rows); + for (chunks) |boundary| if (boundary > at) { + end = @min(end, boundary); + break; + }; + // main carried `mark` across chunks; it only skips marks at or before `at`, so a fresh scan stops there too + var mark: usize = 0; + while (mark < marks.len and marks[mark] <= at) mark += 1; + if (mark < marks.len) end = @min(end, marks[mark]); + return end; +} + +/// One chunk from `at` through `r` (run, keep); true once all in. `whole` asks for a cancel or yield, a step a cancel. +pub fn step(r: anytype, s: *Stream, at: *usize, rows: usize, whole: bool) !bool { + if (whole) try control.before(s, at.*) else if (s.isCancelled()) { + s.keepInterruptedPrefill(@intCast(at.*)); + return error.Cancelled; + } + const len = s.prompt().len; + const end = chunkEnd(len, at.*, rows, s.chunks, s.reuse.marks); + try r.run(s, at.*, end); + at.* = end; + control.completed(s, end); // the forward waits on its command buffer: these rows are in + if (std.mem.indexOfScalar(u32, s.reuse.marks, @intCast(end)) != null) r.keep(s, @intCast(end)); + return end == len; +} + +/// The host cancels between chunks: the state at the pass's last chunk end is kept (no prompt work runs). +pub fn cancel(s: *Stream, at: ?usize) void { + if (at) |x| s.keepInterruptedPrefill(@intCast(x)); +} + +test { + _ = @import("prefill_steps_test.zig"); +} diff --git a/zig/src/families/lfm3/prefill_steps_test.zig b/zig/src/families/lfm3/prefill_steps_test.zig new file mode 100644 index 00000000000..2d9426eba73 --- /dev/null +++ b/zig/src/families/lfm3/prefill_steps_test.zig @@ -0,0 +1,255 @@ +//! LFM3 Metal's stepped prompt pass on recording fakes: today's cuts, a decode between chunks, cancel and yield. +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 Event = union(enum) { chunk: struct { id: u8, at: usize, end: usize }, keep: u32, decode: u8 }; + +/// The cuts of main's whole loop (backend.zig's prefillFn before #3021), copied as they were, `mark` carried. +fn mainCuts(a: std.mem.Allocator, total: usize, from: usize, rows: usize, planned: []const u32, kept_marks: []const u32) ![][2]usize { + var out: std.ArrayList([2]usize) = .empty; + var at = from; + var mark: usize = 0; + while (at < total) { + var end: usize = @min(total, at + rows); + for (planned) |boundary| if (boundary > at) { + end = @min(end, boundary); + break; + }; + while (mark < kept_marks.len and kept_marks[mark] <= at) mark += 1; + if (mark < kept_marks.len) end = @min(end, kept_marks[mark]); + try out.append(a, .{ at, end }); + at = end; + } + return out.toOwnedSlice(a); +} + +/// Records each chunk run and each kept mark, as backend.zig's 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 29-token prompt at an 8-row cap: planned starts at 3 and 20, a kept mark at 11. +const len = 29; +const cap = 8; +const chunks = [_]u32{ 3, 20 }; +const marks = [_]u32{11}; + +fn prompt() [len]u32 { + var ids: [len]u32 = undefined; + for (&ids, 0..) |*x, i| x.* = @intCast(i % 97 + 3); + return ids; +} + +/// The row a stream's reuse hook last kept, and whether its cancel or yield check answers yes. +const Flags = struct { + var kept: ?u32 = null; + var cancelled = false; + var yielding = false; + fn at(_: *anyopaque, _: *lanes.Stream, row: u32) void { + kept = row; + } + fn cancel(_: *anyopaque) bool { + return cancelled; + } + fn yields(_: *anyopaque) bool { + return yielding; + } + fn reset() void { + kept = null; + cancelled = false; + yielding = false; + } +}; +var dummy: u8 = 0; + +fn checked(ids: []const u32) !lanes.Stream { + var s = try lanes.Stream.init(gpa, .{ .id = "x", .prompt = ids, .max_new = 4, .chunks = &chunks, .reuse = .{ .marks = &marks }, .cancel_check = .{ .ptr = &dummy, .check = Flags.cancel }, .yield_check = .{ .ptr = &dummy, .check = Flags.yields } }); + s.reuse.hook = .{ .ptr = &dummy, .at = Flags.at }; + return s; +} + +test "LFM3 Metal steps: one call runs one chunk at today's cut, and the calls' chunks are the whole loop's" { + const ids = prompt(); + const want = try mainCuts(gpa, len, 0, cap, &chunks, &marks); + defer gpa.free(want); + try t.expectEqualSlices([2]usize, &.{ .{ 0, 3 }, .{ 3, 11 }, .{ 11, 19 }, .{ 19, 20 }, .{ 20, 28 }, .{ 28, 29 } }, want); + for ([_]bool{ true, false }) |whole| { // the whole pass (prefillFn) and the lane host's steps + var s = try lanes.Stream.init(gpa, .{ .id = "s", .prompt = &ids, .max_new = 4, .chunks = &chunks, .reuse = .{ .marks = &marks } }); + defer s.deinit(gpa); + var log: std.ArrayList(Event) = .empty; + defer log.deinit(gpa); + var at: usize = 0; + for (want, 0..) |w, i| { + const before = log.items.len; + const done = try steps.step(Rec{ .log = &log }, &s, &at, cap, whole); + try t.expectEqual(i + 1 == want.len, done); + try t.expectEqual(Event{ .chunk = .{ .id = 's', .at = w[0], .end = w[1] } }, log.items[before]); // 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 11 is kept right after the chunk that reaches it, as main's loop kept it + try t.expectEqual(@as(usize, 7), log.items.len); + try t.expectEqual(Event{ .keep = 11 }, log.items[2]); + } + // a pass resumed from a kept state at 11 cuts as main's loop does from there + const resumed = try mainCuts(gpa, len, 11, cap, &chunks, &marks); + defer gpa.free(resumed); + var s = try lanes.Stream.init(gpa, .{ .id = "s", .prompt = &ids, .max_new = 4, .chunks = &chunks, .reuse = .{ .marks = &marks } }); + defer s.deinit(gpa); + var log: std.ArrayList(Event) = .empty; + defer log.deinit(gpa); + var at: usize = 11; + while (!try steps.step(Rec{ .log = &log }, &s, &at, cap, 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); +} + +test "LFM3 Metal steps: a cancel between chunks keeps the state at the last chunk's end" { + const ids = prompt(); + Flags.reset(); + defer Flags.reset(); + var s = try checked(&ids); + defer s.deinit(gpa); + var log: std.ArrayList(Event) = .empty; + defer log.deinit(gpa); + var at: usize = 0; + for (0..3) |_| _ = try steps.step(Rec{ .log = &log }, &s, &at, cap, false); + Flags.kept = null; + steps.cancel(&s, at); // the host's cancel_prefill + try t.expectEqual(@as(?u32, 19), Flags.kept); // rows 0..19 are in; no chunk ran for the cancel + Flags.kept = null; + steps.cancel(&s, null); // no pass in progress: nothing kept + try t.expectEqual(@as(?u32, null), Flags.kept); + // a step asked after the cancel keeps the same rows and runs nothing, as prefill_control.before does + Flags.cancelled = true; + try t.expectError(error.Cancelled, steps.step(Rec{ .log = &log }, &s, &at, cap, false)); + try t.expectEqual(@as(?u32, 19), Flags.kept); + var n: usize = 0; + for (log.items) |e| n += @intFromBool(e == .chunk); + try t.expectEqual(@as(usize, 3), n); +} + +test "LFM3 Metal steps: the whole pass still yields at a chunk start with its prefix kept; a step leaves it to the host" { + const ids = prompt(); + Flags.reset(); + defer Flags.reset(); + var s = try checked(&ids); + defer s.deinit(gpa); + var log: std.ArrayList(Event) = .empty; + defer log.deinit(gpa); + var at: usize = 0; + for (0..3) |_| _ = try steps.step(Rec{ .log = &log }, &s, &at, cap, true); + Flags.yielding = true; + Flags.kept = null; + try t.expectError(error.Yielded, steps.step(Rec{ .log = &log }, &s, &at, cap, true)); + try t.expectEqual(@as(?u32, 19), Flags.kept); // prefill_control.before kept the prefix, as main's loop did + try t.expectEqual(@as(usize, 19), at); + // the lane host schedules a stepped pass itself: a yield check does not stop the next chunk + try t.expect(!try steps.step(Rec{ .log = &log }, &s, &at, cap, false)); + try t.expectEqual(@as(usize, 20), at); +} + +/// The lanes fake with LFM3's stepping in front: its prompt passes a chunk a call at `rows` (4 here), logged. +const Lfm = struct { + fake: lanes.fake.Fake, + inner: be.Backend = undefined, + fills: std.AutoHashMapUnmanaged(*lanes.Stream, usize) = .empty, + log: std.ArrayList(Event) = .empty, + vt: be.Backend.VTable = undefined, + + var current: *Lfm = undefined; + const rows = 4; + + fn init(x: *Lfm) 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; + return .{ .ptr = x.inner.ptr, .vtable = &x.vt }; + } + + fn deinit(x: *Lfm) void { + x.fills.deinit(gpa); + x.log.deinit(gpa); + x.fake.deinit(); + } + + 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.* = 0; + const done = try steps.step(Rec{ .log = &x.log }, s, got.value_ptr, rows, false); + 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); + } +}; + +test "LFM3 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 lfm: Lfm = .{ .fake = .{ .gpa = gpa } }; + defer lfm.deinit(); + var clock: lanes.fake.FixedClock = .{}; + var engine = lanes.Engine.init(gpa, &cfg, lfm.init(), clock.clock()); + defer engine.deinit(); + try t.expect(engine.fills()); // the lane host steps this backend's prompts (lane_host_fill.zig) + 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, lfm.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 (lfm.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 (lfm.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(); +} diff --git a/zig/src/families/lfm3/qk_segments_test.zig b/zig/src/families/lfm3/qk_segments_test.zig new file mode 100644 index 00000000000..faef735ba4e --- /dev/null +++ b/zig/src/families/lfm3/qk_segments_test.zig @@ -0,0 +1,131 @@ +//! A shared round's qk in one dispatch against lfm3_qk run stream by stream: queries, keys and values byte for byte. +const std = @import("std"); +const mtl = @import("metal"); +const c = @import("config.zig"); +const kernels = @import("kernels.zig"); + +const QkArgs = kernels.QkArgs; +const Segment = kernels.AttentionSegment; +const shared_memory = mtl.ResourceOptions.shared; + +/// Three streams at different lengths in caches of different sizes; rows 1, 4 and 3. +const lens = [_]usize{ 0, 37, 4099 }; +const caps = [_]usize{ 16, 64, 4200 }; +const rows = [_]usize{ 1, 4, 3 }; +const total = 8; +const kv_row = c.kv_heads * c.head_dim * 2; + +const Buffers = struct { + device: mtl.Device, + list: [48]mtl.Buffer = undefined, + count: usize = 0, + + fn make(self: *Buffers, bytes: usize) !mtl.Buffer { + const b = try self.device.buffer(bytes, shared_memory); + self.list[self.count] = b; + self.count += 1; + return b; + } + + fn deinit(self: *Buffers) void { + for (self.list[0..self.count]) |b| b.deinit(); + } +}; + +/// BF16 noise in [-2, 2): an f32's top half, never a NaN or an infinity. +fn noise(b: mtl.Buffer, words: usize, seed: u64) void { + var prng = std.Random.DefaultPrng.init(seed); + for (b.slice(u16, words)) |*w| w.* = @truncate(@as(u32, @bitCast(prng.random().float(f32) * 4 - 2)) >> 16); +} + +const Caches = struct { keys: [3]mtl.Buffer, values: [3]mtl.Buffer, queries: mtl.Buffer }; + +fn caches(pool: *Buffers) !Caches { + var out: Caches = undefined; + for (0..3) |i| { + out.keys[i] = try pool.make(caps[i] * kv_row); + out.values[i] = try pool.make(caps[i] * kv_row); + noise(out.keys[i], caps[i] * kv_row / 2, 100 + i); // the same old rows in both sets + noise(out.values[i], caps[i] * kv_row / 2, 200 + i); + } + out.queries = try pool.make(total * c.hidden * 2); + @memset(out.queries.contents()[0 .. total * c.hidden * 2], 0xff); + return out; +} + +test "LFM3: a shared round's qk in one dispatch writes the queries, keys and values lfm3_qk writes stream by stream" { + const device = mtl.Device.init() catch return error.SkipZigTest; + defer device.deinit(); + const queue = try device.queue(); + defer queue.deinit(); + var k = try kernels.load(device); + defer k.deinit(); + var pool: Buffers = .{ .device = device }; + defer pool.deinit(); + const q = try pool.make(total * c.hidden * 2); + const kx = try pool.make(total * kv_row); + const vx = try pool.make(total * kv_row); + const qn = try pool.make(c.head_dim * 2); + const kn = try pool.make(c.head_dim * 2); + noise(q, total * c.hidden, 1); + noise(kx, total * kv_row / 2, 2); + noise(vx, total * kv_row / 2, 3); + noise(qn, c.head_dim, 4); + noise(kn, c.head_dim, 5); + const table = try pool.make(3 * @sizeOf(Segment)); + const row_segments = try pool.make(total * 4); + // A full layer's partial rotation and a sliding layer's whole one. + for ([_]struct { theta: f32, pairs: u32 }{ .{ .theta = 1e6, .pairs = 16 }, .{ .theta = 1e4, .pairs = 64 } }) |rope| { + const serial = try caches(&pool); + const one = try caches(&pool); + const cb = queue.commandBuffer(); + const e = cb.compute(.serial); + var base: usize = 0; + e.setPipeline(k.get("lfm3_qk")); + for (0..3) |i| { + const args = QkArgs{ .len = @intCast(lens[i]), .cap = @intCast(caps[i]), .eps = c.eps, .log2_theta = std.math.log2(rope.theta), .rotary_pairs = rope.pairs }; + e.setBuffer(q, base * c.hidden * 2, 0); + e.setBuffer(kx, base * kv_row, 1); + e.setBuffer(vx, base * kv_row, 2); + e.setBuffer(qn, 0, 3); + e.setBuffer(kn, 0, 4); + e.setBytes(std.mem.asBytes(&args), 5); + e.setBuffer(serial.queries, base * c.hidden * 2, 6); + e.setBuffer(serial.keys[i], 0, 7); + e.setBuffer(serial.values[i], 0, 8); + e.dispatchGroups(.of(c.query_heads + c.kv_heads, rows[i], 1), .of(32, 1, 1)); + base += rows[i]; + } + const segments = table.slice(Segment, 3); + const map = row_segments.slice(u32, total); + base = 0; + for (segments, 0..) |*seg, i| { + seg.* = .{ .keys = one.keys[i].gpuAddress(), .values = one.values[i].gpuAddress(), .base = @intCast(base), .rows = @intCast(rows[i]), .args = .{ .len = @intCast(lens[i]), .cap = @intCast(caps[i]), .scale = 0, .window = 0 } }; + @memset(map[base..][0..rows[i]], @intCast(i)); + base += rows[i]; + } + const args = QkArgs{ .len = 0, .cap = 0, .eps = c.eps, .log2_theta = std.math.log2(rope.theta), .rotary_pairs = rope.pairs }; + e.setPipeline(k.get("lfm3_qk_segments")); + for (0..3) |i| { + e.useResource(one.keys[i], mtl.ResourceUsage.write); + e.useResource(one.values[i], mtl.ResourceUsage.write); + } + for ([_]mtl.Buffer{ q, kx, vx, qn, kn }, 0..) |b, slot| e.setBuffer(b, 0, slot); + e.setBytes(std.mem.asBytes(&args), 5); + e.setBuffer(one.queries, 0, 6); + e.setBuffer(table, 0, 7); + e.setBuffer(row_segments, 0, 8); + e.dispatchGroups(.of(c.query_heads + c.kv_heads, total, 1), .of(32, 1, 1)); + e.end(); + cb.commit(); + cb.wait(); + if (cb.failure()) |_| return error.GpuFailed; + try std.testing.expectEqualSlices(u8, serial.queries.contents()[0 .. total * c.hidden * 2], one.queries.contents()[0 .. total * c.hidden * 2]); + for (0..3) |i| { + try std.testing.expectEqualSlices(u8, serial.keys[i].contents()[0 .. caps[i] * kv_row], one.keys[i].contents()[0 .. caps[i] * kv_row]); + try std.testing.expectEqualSlices(u8, serial.values[i].contents()[0 .. caps[i] * kv_row], one.values[i].contents()[0 .. caps[i] * kv_row]); + } + // The queries were written: an unwritten word stays 0xffff. + try std.testing.expect(serial.queries.slice(u16, 1)[0] != 0xffff); + } +} diff --git a/zig/src/families/lfm3/state.zig b/zig/src/families/lfm3/state.zig index 0588041ebfa..1a568878801 100644 --- a/zig/src/families/lfm3/state.zig +++ b/zig/src/families/lfm3/state.zig @@ -92,11 +92,17 @@ pub const Cache = struct { const last = self.last orelse return error.NothingToKeep; if (path.len == 0 or path.len > last.rows) return error.NothingToKeep; for (path, 0..) |p, i| if (p != i) return error.UnsupportedLfmTree; - const row = last.base + path.len - 1; - self.restore(scratch, row); + self.last = null; + // The whole round kept: commit() restored its last row's conv state and run() copied its logits; len is right. + if (path.len == last.rows) return; + self.take(scratch, last.base + path.len - 1); self.len = last.start + path.len; + } + + /// A recorded call's scratch row as the stream's latest: that row's conv state and logits. + fn take(self: *Cache, scratch: *const Scratch, row: usize) void { + self.restore(scratch, row); @memcpy(self.logits.contents()[0 .. c.vocab * 2], (scratch.logits.contents() + row * c.vocab * 2)[0 .. c.vocab * 2]); - self.last = null; } }; @@ -213,3 +219,63 @@ test "LFM3 context and storage retain the full and sliding layers at the checkpo try std.testing.expectEqual(@as(usize, 24576), conv_bytes); try std.testing.expectEqual(@as(u64, 11 * 2 * c.kv_heads * c.head_dim * 2), cacheBytes(&c.schedule, 1) - cacheBytes(&c.schedule, 0)); } + +/// As forward.run settles a recorded call once the GPU is done: each stream's last row's logits, then commit. +fn settle(s: *const Scratch, caches: []Cache, rows: []const usize) void { + var base: usize = 0; + for (caches, rows) |*cache, n| { + @memcpy(cache.logits.contents()[0 .. c.vocab * 2], (s.logits.contents() + (base + n - 1) * c.vocab * 2)[0 .. c.vocab * 2]); + cache.commit(s, base, n, true); + base += n; + } +} + +fn expectSameState(a: *const Cache, b: *const Cache) !void { + try std.testing.expectEqual(a.len, b.len); + try std.testing.expect(a.last == null and b.last == null); + try std.testing.expectEqualSlices(u8, a.logits.contents()[0 .. c.vocab * 2], b.logits.contents()[0 .. c.vocab * 2]); + for (a.blocks, b.blocks) |x, y| if (x == .conv) { + try std.testing.expectEqualSlices(u8, x.conv.contents()[0..conv_bytes], y.conv.contents()[0..conv_bytes]); + }; +} + +test "LFM3: keeping a whole recorded round copies nothing and leaves the state the copy would; a partial path restores" { + const gpa = std.testing.allocator; + const device = mtl.Device.init() catch return error.SkipZigTest; + defer device.deinit(); + var s = try Scratch.init(gpa, device, &c.schedule, batch_rows); + defer s.deinit(); + // The recorded rows' conv states and logits, as a two-stream round of 4 and 3 rows leaves them. + var prng = std.Random.DefaultPrng.init(820); + prng.random().bytes(s.logits.contents()[0 .. 7 * c.vocab * 2]); + for (s.snapshots) |snapshot| if (snapshot) |b| prng.random().bytes(b.contents()[0 .. 7 * conv_bytes]); + // The streams and their twins, which take the copying path. + var caches: [4]Cache = undefined; + var made: usize = 0; + defer for (caches[0..made]) |*cache| cache.deinit(); + while (made < caches.len) : (made += 1) caches[made] = try Cache.init(gpa, device, &c.schedule, 64); + const rows = [_]usize{ 4, 3 }; + for ([_]usize{ 0, 2 }) |at| { + caches[at].len = 5; + caches[at + 1].len = 40; + settle(&s, caches[at..][0..2], &rows); + } + // The first stream keeps every row: no copy, and the state is the copy's, byte for byte. + try caches[0].keep(&s, &.{ 0, 1, 2, 3 }); + caches[2].last = null; + caches[2].take(&s, 3); + caches[2].len = 5 + 4; + try expectSameState(&caches[0], &caches[2]); + try std.testing.expectError(error.NothingToKeep, caches[0].keep(&s, &.{0})); + // The second keeps its first row: its conv state and logits come back from scratch row 4, not its last row 6. + try std.testing.expect(!std.mem.eql(u8, caches[1].logits.contents()[0 .. c.vocab * 2], (s.logits.contents() + 4 * c.vocab * 2)[0 .. c.vocab * 2])); + try caches[1].keep(&s, &.{0}); + caches[3].last = null; + caches[3].take(&s, 4); + caches[3].len = 40 + 1; + try expectSameState(&caches[1], &caches[3]); + try std.testing.expectEqualSlices(u8, (s.logits.contents() + 4 * c.vocab * 2)[0 .. c.vocab * 2], caches[1].logits.contents()[0 .. c.vocab * 2]); + for (caches[1].blocks, s.snapshots) |b, snapshot| if (b == .conv) { + try std.testing.expectEqualSlices(u8, (snapshot.?.contents() + 4 * conv_bytes)[0..conv_bytes], b.conv.contents()[0..conv_bytes]); + }; +} diff --git a/zig/src/families/ling/checkpoint.zig b/zig/src/families/ling/checkpoint.zig new file mode 100644 index 00000000000..5a8441dac3b --- /dev/null +++ b/zig/src/families/ling/checkpoint.zig @@ -0,0 +1,85 @@ +//! Ling's bf16 checkpoint tensors, validated by the shared safetensors reader and mapped without weight copies. +const std = @import("std"); +const mtl = @import("metal"); +const st = @import("safetensors"); +const config = @import("config.zig"); + +pub const Tensor = struct { + buffer: mtl.Buffer, + offset: usize, + entry: st.Entry, +}; +const File = struct { + path: [:0]const u8, + map: ?mtl.MappedFile = null, + buffer: ?mtl.Buffer = null, + header: st.Header = .empty, + data: usize = 0, +}; +pub const Checkpoint = struct { + arena: std.heap.ArenaAllocator, + device: mtl.Device, + config: ?config.Config = null, + files: std.ArrayList(File) = .empty, + where: std.StringHashMapUnmanaged(u32) = .empty, + + pub fn open(gpa: std.mem.Allocator, io: std.Io, device: mtl.Device, dir: []const u8) !Checkpoint { + var self = Checkpoint{ .arena = std.heap.ArenaAllocator.init(gpa), .device = device }; + errdefer self.deinit(); + const a = self.arena.allocator(); + const config_path = try std.fs.path.join(a, &.{ dir, "config.json" }); + const config_text = try std.Io.Dir.cwd().readFileAlloc(io, config_path, a, .limited(16 << 20)); + var why: config.Why = .{}; + self.config = try config.parse(a, config_text, &why); + const path = try std.fs.path.join(a, &.{ dir, "model.safetensors.index.json" }); + const text = try std.Io.Dir.cwd().readFileAlloc(io, path, a, .limited(st.index.max_bytes)); + const parsed = try std.json.parseFromSliceLeaky(std.json.Value, a, text, .{}); + const index = try st.index.weightMap(parsed); + var file_of: std.StringHashMapUnmanaged(u32) = .empty; + for (index.keys(), index.values()) |name, value| { + const file = value.string; + if (std.fs.path.isAbsolute(file) or std.mem.indexOf(u8, file, "..") != null) return error.BadShardPath; + const slot = try file_of.getOrPut(a, file); + if (!slot.found_existing) { + slot.value_ptr.* = @intCast(self.files.items.len); + try self.files.append(a, .{ .path = try std.fs.path.joinZ(a, &.{ dir, file }) }); + } + try self.where.put(a, name, slot.value_ptr.*); + } + return self; + } + + pub fn get(self: *Checkpoint, name: []const u8, dtype: st.DType, shape: []const usize) !Tensor { + const id = self.where.get(name) orelse return error.MissingTensor; + const f = &self.files.items[id]; + if (f.buffer == null) { + const map = try mtl.MappedFile.open(f.path); + errdefer map.deinit(); + if (map.size < 8) return error.BadSafetensors; + const n = try st.headerSize(std.mem.readInt(u64, map.bytes[0..8], .little), map.size); + f.data = 8 + n; + f.header = try st.parseHeader(self.arena.allocator(), map.bytes[8..f.data], map.size - f.data); + for (f.header.values()) |entry| { + if (entry.dtype != .bf16 and entry.dtype != .f32) return error.UnsupportedDType; + if ((f.data + entry.begin) % entry.dtype.size() != 0) return error.MisalignedTensor; + } + f.buffer = try self.device.bufferNoCopy(map.bytes.ptr, map.bytes.len, mtl.ResourceOptions.shared | mtl.ResourceOptions.untracked); + f.map = map; + } + const entry = f.header.get(name) orelse return error.MissingTensor; + if (entry.dtype != dtype or entry.rank != shape.len or !std.mem.eql(usize, entry.shape[0..entry.rank], shape)) return error.TensorShape; + return .{ .buffer = f.buffer.?, .offset = f.data + entry.begin, .entry = entry }; + } + + pub fn deinit(self: *Checkpoint) void { + for (self.files.items) |file| { + if (file.buffer) |b| b.deinit(); + if (file.map) |m| m.deinit(); + } + self.arena.deinit(); + } +}; + +test { + std.testing.refAllDecls(Checkpoint); +} diff --git a/zig/src/families/ling/metal_forward.zig b/zig/src/families/ling/metal_forward.zig new file mode 100644 index 00000000000..5cb054fc664 --- /dev/null +++ b/zig/src/families/ling/metal_forward.zig @@ -0,0 +1,180 @@ +//! Ling tiny's 24-layer bf16 backbone over the existing Metal row, KDA, MLA and route operations. +const std = @import("std"); +const mtl = @import("metal"); +const ck = @import("ling_checkpoint"); +const Rows = @import("ling_rows").Rows; +const Kda = @import("ling_kda").Kda; +const Mla = @import("ling_mla").Mla; +const Moe = @import("ling_moe").Moe; +const Attention = union(enum) { kda: Kda, mla: Mla }; + +pub const Forward = struct { + rows: *Rows, + model: *ck.Checkpoint, + attention: [24]Attention, + moe: Moe, + x: mtl.Buffer, + normed: mtl.Buffer, + delta: mtl.Buffer, + gate: mtl.Buffer, + up: mtl.Buffer, + activation: mtl.Buffer, + logits: mtl.Buffer, + picks: mtl.Buffer, + position: u32 = 0, + + pub fn init(rows: *Rows, model: *ck.Checkpoint, capacity: u32) !Forward { + const buffer_mark = rows.owned.items.len; + errdefer rows.rollbackBuffers(buffer_mark); + const c = model.config orelse return error.MissingConfig; + if (c.quant != .bf16 or c.layers != 24 or c.hidden != 1536 or c.vocab != 157184 or c.group != 4 or + c.kda_heads != 16 or c.kda_dim != 128 or c.mla_heads != 16 or c.q_lora != 256 or c.kv_lora != 512 or + c.nope != 128 or c.rope_dim != 64 or c.v_dim != 128 or c.dense_layers != 1 or c.dense_inter != 4608 or + c.experts != 128 or c.topk != 8 or c.n_group != 8 or c.topk_group != 4 or c.moe_inter != 512 or + c.shared_inter != 512 or c.routed_scale != 2.5 or c.eps != 1e-6 or c.rope_theta != 6000000 or + c.lower_bound != -5 or c.mtp != 0 or !c.head_gate or c.tie or c.rope_style != .gptj or !c.norm_topk or !c.expert_bias) return error.UnsupportedLingGeometry; + for (0..24) |i| if (c.expert_limit[i] != 0 or c.shared_limit[i] != 0) return error.UnsupportedLingGeometry; + if (capacity == 0 or rows.max_rows == 0) return error.ContextCapacity; + var attention: [24]Attention = undefined; + var initialized: usize = 0; + errdefer for (attention[0..initialized]) |*a| switch (a.*) { + .mla => |*m| m.deinit(), + .kda => {}, + }; + for (&attention, 0..) |*a, i| { + const prefix = try std.fmt.allocPrint(rows.allocator, "model.layers.{d}.attention.", .{i}); + defer rows.allocator.free(prefix); + a.* = if (i % 4 == 3) .{ .mla = try Mla.init(rows, 16, capacity) } else .{ .kda = try Kda.init(rows, model, prefix, 16) }; + initialized += 1; + } + const r: usize = rows.max_rows; + var moe = try Moe.init(rows, 1536, 512); + errdefer moe.deinit(); + const x = try rows.buffer(r * 1536 * 2); + const normed = try rows.buffer(r * 1536 * 2); + const delta = try rows.buffer(r * 1536 * 2); + const gate = try rows.buffer(r * 4608 * 2); + const up = try rows.buffer(r * 4608 * 2); + const activation = try rows.buffer(r * 4608 * 2); + const logits = try rows.buffer(r * 157184 * 4); + const picks = try rows.buffer(23 * r * 8 * 4); + return .{ + .rows = rows, + .model = model, + .attention = attention, + .moe = moe, + .x = x, + .normed = normed, + .delta = delta, + .gate = gate, + .up = up, + .activation = activation, + .logits = logits, + .picks = picks, + }; + } + + pub fn run(self: *Forward, ids: []const u32) ![]const f32 { + const r = self.rows; + if (ids.len == 0 or ids.len > r.max_rows) return error.RowCapacity; + const n: u32 = @intCast(ids.len); + for (&self.attention) |*a| if (a.* == .mla and (self.position > a.mla.capacity or n > a.mla.capacity - self.position)) return error.ContextCapacity; + + const embedding = try self.model.get("model.word_embeddings.weight", .bf16, &.{ 157184, 1536 }); + for (ids, 0..) |id, i| { + if (id >= 157184) return error.InvalidToken; + const offset = embedding.offset + @as(usize, id) * 1536 * 2; + @memcpy(self.x.contents()[i * 1536 * 2 ..][0 .. 1536 * 2], embedding.buffer.contents()[offset..][0 .. 1536 * 2]); + } + for (&self.attention, 0..) |*attention, i| { + const pre = try std.fmt.allocPrint(r.allocator, "model.layers.{d}.", .{i}); + defer r.allocator.free(pre); + const norm = try std.mem.concat(r.allocator, u8, &.{ pre, "input_layernorm.weight" }); + defer r.allocator.free(norm); + try r.norm(self.model, norm, .{ .buf = self.x }, .{ .buf = self.normed }, n, 1536, 1e-6); + const a = try std.mem.concat(r.allocator, u8, &.{ pre, "attention." }); + defer r.allocator.free(a); + switch (attention.*) { + .kda => |*k| try k.forward(r, self.model, a, .{ .buf = self.normed }, .{ .buf = self.delta }, n, 1536, -5, 1e-6), + .mla => |*m| try m.forward(r, self.model, a, .{ .buf = self.normed }, .{ .buf = self.delta }, n, 1536, 1e-6, 6000000), + } + try r.add(.{ .buf = self.x }, .{ .buf = self.delta }, .{ .buf = self.x }, n * 1536); + const post = try std.mem.concat(r.allocator, u8, &.{ pre, "post_attention_layernorm.weight" }); + defer r.allocator.free(post); + try r.norm(self.model, post, .{ .buf = self.x }, .{ .buf = self.normed }, n, 1536, 1e-6); + const mlp = try std.mem.concat(r.allocator, u8, &.{ pre, "mlp." }); + defer r.allocator.free(mlp); + if (i == 0) { + try r.mlp(self.model, mlp, .{ .buf = self.normed }, .{ .buf = self.delta }, .{ .buf = self.gate }, .{ .buf = self.up }, .{ .buf = self.activation }, n, 1536, 4608); + } else { + try self.moe.forward(r, self.model, mlp, .{ .buf = self.normed }, .{ .buf = self.delta }, n); + @memcpy(self.picks.contents()[(i - 1) * n * 8 * 4 ..][0 .. n * 8 * 4], self.moe.ids.contents()[0 .. n * 8 * 4]); + } + try r.add(.{ .buf = self.x }, .{ .buf = self.delta }, .{ .buf = self.x }, n * 1536); + } + try r.norm(self.model, "model.norm.weight", .{ .buf = self.x }, .{ .buf = self.normed }, n, 1536, 1e-6); + try r.linear(self.model, "lm_head.weight", .{ .buf = self.normed }, .{ .buf = self.logits }, n, 1536, 157184, true); + self.position += n; + return self.logits.slice(f32, n * 157184); + } + + fn stateBytes(position: u32) usize { + return 12 + 18 * (16 * 128 * 128 * 4 + 9 * 2048 * 2) + 6 * @as(usize, position) * 576 * 2; + } + + pub fn snapshot(self: *const Forward, allocator: std.mem.Allocator) ![]u8 { + const data = try allocator.alloc(u8, stateBytes(self.position)); + @memcpy(data[0..8], "TFLINGS1"); + std.mem.writeInt(u32, data[8..12], self.position, .little); + var at: usize = 12; + for (&self.attention) |*attention| switch (attention.*) { + .kda => |*k| { + const state = k.state.contents()[0 .. 16 * 128 * 128 * 4]; + const conv = k.conv.contents()[0 .. 9 * 2048 * 2]; + @memcpy(data[at..][0..state.len], state); + at += state.len; + @memcpy(data[at..][0..conv.len], conv); + at += conv.len; + }, + .mla => |*m| { + const cache = m.cache.contents()[0 .. @as(usize, self.position) * 576 * 2]; + @memcpy(data[at..][0..cache.len], cache); + at += cache.len; + }, + }; + return data; + } + + pub fn restore(self: *Forward, data: []const u8) !void { + if (data.len < 12 or !std.mem.eql(u8, data[0..8], "TFLINGS1")) return error.BadLingState; + const position = std.mem.readInt(u32, data[8..12], .little); + if (data.len != stateBytes(position)) return error.BadLingState; + for (&self.attention) |*a| if (a.* == .mla and position > a.mla.capacity) return error.ContextCapacity; + var at: usize = 12; + for (&self.attention) |*attention| switch (attention.*) { + .kda => |*k| { + const state = k.state.contents()[0 .. 16 * 128 * 128 * 4]; + const conv = k.conv.contents()[0 .. 9 * 2048 * 2]; + @memcpy(state, data[at..][0..state.len]); + at += state.len; + @memcpy(conv, data[at..][0..conv.len]); + at += conv.len; + }, + .mla => |*m| { + const cache = m.cache.contents()[0 .. @as(usize, position) * 576 * 2]; + @memcpy(cache, data[at..][0..cache.len]); + at += cache.len; + m.position = position; + }, + }; + self.position = position; + } + + pub fn deinit(self: *Forward) void { + for (&self.attention) |*a| switch (a.*) { + .mla => |*m| m.deinit(), + .kda => {}, + }; + self.moe.deinit(); + } +}; diff --git a/zig/src/families/ling/metal_kda.zig b/zig/src/families/ling/metal_kda.zig new file mode 100644 index 00000000000..e667b597ecc --- /dev/null +++ b/zig/src/families/ling/metal_kda.zig @@ -0,0 +1,121 @@ +//! Ling KDA state and unchanged k3_kda dispatch, with bf16 checkpoint vectors widened exactly to fp32. +const std = @import("std"); +const mtl = @import("metal"); +const kernels = @import("kimi_kernels"); +const ck = @import("ling_checkpoint"); +const Rows = @import("ling_rows").Rows; +const Ref = kernels.Ref; + +pub const Kda = struct { + state: mtl.Buffer, + conv: mtl.Buffer, + segment: mtl.Buffer, + dummy: mtl.Buffer, + weights: kernels.KdaWeights, + heads: u32, + readers: [6]Ref, + proj: mtl.Buffer, + f: mtl.Buffer, + b: mtl.Buffer, + g: mtl.Buffer, + y: mtl.Buffer, + + fn vector(rows: *Rows, model: *ck.Checkpoint, prefix: []const u8, name: []const u8, shape: []const usize, bf16: bool) !Ref { + const full = try std.mem.concat(rows.allocator, u8, &.{ prefix, name }); + defer rows.allocator.free(full); + const t = try model.get(full, if (bf16) .bf16 else .f32, shape); + if (!bf16) return .{ .buf = t.buffer, .off = t.offset }; + var count: usize = 1; + for (shape) |dim| count *= dim; + const out = try rows.buffer(count * 4); + const data = std.mem.bytesAsSlice(u16, t.buffer.contents()[t.offset..][0 .. count * 2]); + for (data, out.slice(f32, count)) |h, *f| f.* = @bitCast(@as(u32, h) << 16); + return .{ .buf = out }; + } + + pub fn init(rows: *Rows, model: *ck.Checkpoint, prefix: []const u8, heads: u32) !Kda { + const width = heads * 128; + const state = try rows.buffer(@as(usize, width) * 128 * 4); + const conv = try rows.buffer(9 * width * 2); + @memset(state.slice(f32, width * 128), 0); + @memset(conv.slice(u16, 9 * width), 0); + const readers = [6]Ref{ + try vector(rows, model, prefix, "q_conv1d.weight", &.{ width, 1, 4 }, true), + try vector(rows, model, prefix, "k_conv1d.weight", &.{ width, 1, 4 }, true), + try vector(rows, model, prefix, "v_conv1d.weight", &.{ width, 1, 4 }, true), + try vector(rows, model, prefix, "A_log", &.{heads}, false), + try vector(rows, model, prefix, "dt_bias", &.{width}, false), + try vector(rows, model, prefix, "o_norm.weight", &.{128}, true), + }; + return .{ + .state = state, + .conv = conv, + .segment = try rows.buffer(@sizeOf(kernels.KdaSeg)), + .dummy = try rows.buffer(16), + .heads = heads, + .proj = try rows.buffer(@as(usize, rows.max_rows) * 3 * width * 2), + .f = try rows.buffer(@as(usize, rows.max_rows) * width * 2), + .b = try rows.buffer(@as(usize, rows.max_rows) * heads * 2), + .g = try rows.buffer(@as(usize, rows.max_rows) * width * 2), + .y = try rows.buffer(@as(usize, rows.max_rows) * width * 2), + .readers = readers, + .weights = .{ .conv_q = kernels.addr(readers[0]), .conv_k = kernels.addr(readers[1]), .conv_v = kernels.addr(readers[2]), .A_log = kernels.addr(readers[3]), .dt_bias = kernels.addr(readers[4]), .o_norm = kernels.addr(readers[5]) }, + }; + } + + pub fn forward(self: *Kda, rows: *Rows, model: *ck.Checkpoint, prefix: []const u8, x: Ref, out: Ref, n: u32, hidden: u32, lower_bound: f32, eps: f32) !void { + const width = self.heads * 128; + for ([_][]const u8{ "q_proj.weight", "k_proj.weight", "v_proj.weight" }, 0..) |part, j| { + const name = try std.mem.concat(rows.allocator, u8, &.{ prefix, part }); + defer rows.allocator.free(name); + try rows.linearInto(model, name, x, .{ .buf = self.proj, .off = j * width * 2 }, n, hidden, width, hidden, 3 * width, false); + } + for ([_]struct { name: []const u8, buffer: mtl.Buffer, width: u32 }{ + .{ .name = "f_proj.weight", .buffer = self.f, .width = width }, + .{ .name = "b_proj.weight", .buffer = self.b, .width = self.heads }, + .{ .name = "g_proj.weight", .buffer = self.g, .width = width }, + }) |p| { + const name = try std.mem.concat(rows.allocator, u8, &.{ prefix, p.name }); + defer rows.allocator.free(name); + try rows.linear(model, name, x, .{ .buf = p.buffer }, n, hidden, p.width, false); + } + try self.mix(rows, .{ .buf = self.proj }, .{ .buf = self.f }, .{ .buf = self.b }, .{ .buf = self.g }, .{ .buf = self.y }, n, lower_bound, eps); + const name = try std.mem.concat(rows.allocator, u8, &.{ prefix, "o_proj.weight" }); + defer rows.allocator.free(name); + try rows.linear(model, name, .{ .buf = self.y }, out, n, width, hidden, false); + } + + pub fn mix(self: *Kda, rows: *Rows, qkv: Ref, f: Ref, b: Ref, g: Ref, out: Ref, n: u32, lower_bound: f32, eps: f32) !void { + if (n == 0 or n > rows.max_rows) return error.RowCapacity; + self.segment.slice(kernels.KdaSeg, 1)[0] = .{ .first = 0, .rows = n, .kept = 0, .flags = kernels.seg_commit, .slot = 0 }; + const state = kernels.KdaState{ + .S = self.state.gpuAddress(), + .conv = self.conv.gpuAddress(), + .log_a = self.dummy.gpuAddress(), + .log_k = self.dummy.gpuAddress(), + .log_u = self.dummy.gpuAddress(), + .log_x = self.dummy.gpuAddress(), + }; + const width = self.heads * 128; + const cb = rows.queue.commandBuffer(); + const e = cb.compute(.serial); + e.useResource(self.state, mtl.ResourceUsage.read | mtl.ResourceUsage.write); + e.useResource(self.conv, mtl.ResourceUsage.read | mtl.ResourceUsage.write); + e.useResource(self.dummy, mtl.ResourceUsage.read); + for (self.readers) |r| e.useResource(r.buf, mtl.ResourceUsage.read); + rows.k.kdaRound(e, qkv, f, b, g, out, .{ .buf = self.segment }, 1, state, self.weights, .{ + .heads = self.heads, + .head0 = 0, + .proj_stride = 3 * width, + .gate_stride = width, + .out_stride = width, + .log_rows = 1, + .lower_bound = lower_bound, + .eps = eps, + }); + e.end(); + cb.commit(); + cb.wait(); + if (cb.failure() != null) return error.GpuFailed; + } +}; diff --git a/zig/src/families/ling/metal_mla.zig b/zig/src/families/ling/metal_mla.zig new file mode 100644 index 00000000000..75c075f1bcf --- /dev/null +++ b/zig/src/families/ling/metal_mla.zig @@ -0,0 +1,154 @@ +//! Ling MLA projections, latent cache and unchanged Kimi mixer with the three Ling RoPE/gate kernels. +const std = @import("std"); +const mtl = @import("metal"); +const kernels = @import("kimi_kernels"); +const ck = @import("ling_checkpoint"); +const Rows = @import("ling_rows").Rows; +const Ref = kernels.Ref; + +pub const Mla = struct { + library: mtl.Library, + rope_cache: mtl.Pipeline, + rope_q: mtl.Pipeline, + gate_expand: mtl.Pipeline, + cache: mtl.Buffer, + positions: mtl.Buffer, + angles: mtl.Buffer, + qa: mtl.Buffer, + qan: mtl.Buffer, + q: mtl.Buffer, + kv: mtl.Buffer, + gate: mtl.Buffer, + expanded: mtl.Buffer, + qlat: mtl.Buffer, + partial: mtl.Buffer, + olat: mtl.Buffer, + y: mtl.Buffer, + heads: u32, + capacity: u32, + position: u32 = 0, + + pub fn init(rows: *Rows, heads: u32, capacity: u32) !Mla { + const buffer_mark = rows.owned.items.len; + errdefer rows.rollbackBuffers(buffer_mark); + const library = try mtl.Library.fromSource(rows.device, @import("ling_sources").mla, mtl.CompileOptions.mlx()); + errdefer library.deinit(); + const rope_cache = try mtl.Pipeline.init(rows.device, library, "tf_ling_mla_rope_cache", false); + errdefer rope_cache.deinit(); + const rope_q = try mtl.Pipeline.init(rows.device, library, "tf_ling_mla_rope_q", false); + errdefer rope_q.deinit(); + const gate_expand = try mtl.Pipeline.init(rows.device, library, "tf_ling_mla_gate_expand", false); + errdefer gate_expand.deinit(); + const r: usize = rows.max_rows; + const cache = try rows.buffer(@as(usize, capacity) * 576 * 2); + @memset(cache.slice(u16, capacity * 576), 0); + const positions = try rows.buffer(r * @sizeOf(kernels.MlaRow)); + const angles = try rows.buffer(r * 64 * 4); + const qa = try rows.buffer(r * 256 * 2); + const qan = try rows.buffer(r * 256 * 2); + const q = try rows.buffer(r * heads * 192 * 2); + const kv = try rows.buffer(r * 576 * 2); + const gate = try rows.buffer(r * heads * 2); + const expanded = try rows.buffer(r * heads * 128 * 2); + const qlat = try rows.buffer(r * heads * 512 * 4); + const partial = try rows.buffer(r * heads * 16 * 514 * 4); + const olat = try rows.buffer(r * heads * 512 * 4); + const y = try rows.buffer(r * heads * 128 * 2); + return .{ + .library = library, + .rope_cache = rope_cache, + .rope_q = rope_q, + .gate_expand = gate_expand, + .cache = cache, + .heads = heads, + .capacity = capacity, + .positions = positions, + .angles = angles, + .qa = qa, + .qan = qan, + .q = q, + .kv = kv, + .gate = gate, + .expanded = expanded, + .qlat = qlat, + .partial = partial, + .olat = olat, + .y = y, + }; + } + + fn name(rows: *Rows, prefix: []const u8, part: []const u8) ![]u8 { + return std.mem.concat(rows.allocator, u8, &.{ prefix, part }); + } + + fn project(self: *Mla, rows: *Rows, model: *ck.Checkpoint, prefix: []const u8, part: []const u8, x: Ref, y: mtl.Buffer, n: u32, width: u32, out_width: u32) !void { + _ = self; + const full = try name(rows, prefix, part); + defer rows.allocator.free(full); + try rows.linear(model, full, x, .{ .buf = y }, n, width, out_width, false); + } + + pub fn forward(self: *Mla, rows: *Rows, model: *ck.Checkpoint, prefix: []const u8, x: Ref, out: Ref, n: u32, hidden: u32, eps: f32, theta: f64) !void { + if (n == 0 or n > rows.max_rows or self.position > self.capacity or n > self.capacity - self.position) return error.ContextCapacity; + try self.project(rows, model, prefix, "q_a_proj.weight", x, self.qa, n, hidden, 256); + const qa_norm = try name(rows, prefix, "q_a_layernorm.weight"); + defer rows.allocator.free(qa_norm); + try rows.norm(model, qa_norm, .{ .buf = self.qa }, .{ .buf = self.qan }, n, 256, eps); + try self.project(rows, model, prefix, "q_b_proj.weight", .{ .buf = self.qan }, self.q, n, 256, self.heads * 192); + try self.project(rows, model, prefix, "kv_a_proj_with_mqa.weight", x, self.kv, n, hidden, 576); + try self.project(rows, model, prefix, "g_proj.weight", x, self.gate, n, hidden, self.heads); + const wn = try name(rows, prefix, "kv_a_layernorm.weight"); + defer rows.allocator.free(wn); + const w = try model.get(wn, .bf16, &.{512}); + const bn = try name(rows, prefix, "kv_b_proj.weight"); + defer rows.allocator.free(bn); + const b = try model.get(bn, .bf16, &.{ self.heads * 256, 512 }); + for (self.positions.slice(kernels.MlaRow, n), 0..) |*p, t| { + p.* = .{ .slot = 0, .pos = self.position + @as(u32, @intCast(t)) }; + for (0..32) |i| { + const angle = @as(f64, @floatFromInt(p.pos)) / std.math.pow(f64, theta, @as(f64, @floatFromInt(2 * i)) / 64.0); + self.angles.slice(f32, n * 64)[t * 64 + i * 2] = @floatCast(@cos(angle)); + self.angles.slice(f32, n * 64)[t * 64 + i * 2 + 1] = @floatCast(@sin(angle)); + } + } + const a = kernels.MlaArgs{ .cache = self.cache.gpuAddress(), .slot_keys = self.capacity, .heads = self.heads, .head0 = 0, .rows = n, .q_stride = self.heads * 192, .kv_stride = 576, .gate_stride = self.heads * 128, .out_stride = self.heads * 128, .eps = eps, .scale = 1.0 / @sqrt(@as(f32, 192)) }; + const cb = rows.queue.commandBuffer(); + const e = cb.compute(.serial); + e.useResource(self.cache, mtl.ResourceUsage.read | mtl.ResourceUsage.write); + rows.k.mlaCache(e, .{ .buf = self.kv }, .{ .buf = w.buffer, .off = w.offset }, .{ .buf = self.positions }, a); + e.setPipeline(self.rope_cache); + e.setBuffer(self.positions, 0, 0); + e.setValue(a, 1); + e.setBuffer(self.angles, 0, 2); + e.dispatchGroups(mtl.Size.of(n, 1, 1), mtl.Size.of(32, 1, 1)); + rows.k.mlaQlat(e, .{ .buf = self.q }, .{ .buf = b.buffer, .off = b.offset }, .{ .buf = self.qlat }, a); + e.setPipeline(self.rope_q); + e.setBuffer(self.q, 0, 0); + e.setValue(a, 1); + e.setBuffer(self.angles, 0, 2); + e.dispatchGroups(mtl.Size.of(self.heads, n, 1), mtl.Size.of(32, 1, 1)); + rows.k.mlaAttend(e, .{ .buf = self.q }, .{ .buf = self.qlat }, .{ .buf = self.positions }, .{ .buf = self.partial }, a); + rows.k.mlaMerge(e, .{ .buf = self.partial }, .{ .buf = self.positions }, .{ .buf = self.olat }, a); + e.setPipeline(self.gate_expand); + e.setBuffer(self.gate, 0, 0); + e.setBuffer(self.expanded, 0, 1); + e.setValue(a, 2); + e.dispatchThreads(mtl.Size.of(self.heads * 128, n, 1), mtl.Size.of(128, 1, 1)); + rows.k.mlaUv(e, .{ .buf = self.olat }, .{ .buf = b.buffer, .off = b.offset }, .{ .buf = self.expanded }, .{ .buf = self.y }, a); + e.end(); + cb.commit(); + cb.wait(); + if (cb.failure() != null) return error.GpuFailed; + const dense = try name(rows, prefix, "dense.weight"); + defer rows.allocator.free(dense); + try rows.linear(model, dense, .{ .buf = self.y }, out, n, self.heads * 128, hidden, false); + self.position += n; + } + + pub fn deinit(self: *Mla) void { + self.gate_expand.deinit(); + self.rope_q.deinit(); + self.rope_cache.deinit(); + self.library.deinit(); + } +}; diff --git a/zig/src/families/ling/metal_moe.zig b/zig/src/families/ling/metal_moe.zig new file mode 100644 index 00000000000..a95dd8af619 --- /dev/null +++ b/zig/src/families/ling/metal_moe.zig @@ -0,0 +1,97 @@ +//! Ling bf16 routed experts using the existing grouped router, row MLPs and Kimi weighted combine. +const std = @import("std"); +const mtl = @import("metal"); +const ck = @import("ling_checkpoint"); +const kernels = @import("kimi_kernels"); +const Rows = @import("ling_rows").Rows; +const Ref = kernels.Ref; +const RouteArgs = extern struct { rows: i32, ne: i32, topk: i32, ng: i32, keep: i32, scale: f32 }; + +pub const Moe = struct { + library: mtl.Library, + route: mtl.Pipeline, + logits: mtl.Buffer, + ids: mtl.Buffer, + weights: mtl.Buffer, + where: mtl.Buffer, + experts: mtl.Buffer, + routed: mtl.Buffer, + shared: mtl.Buffer, + gate: mtl.Buffer, + up: mtl.Buffer, + activation: mtl.Buffer, + hidden: u32, + inter: u32, + + pub fn init(rows: *Rows, hidden: u32, inter: u32) !Moe { + const library = try mtl.Library.fromSource(rows.device, @import("ling_sources").route, mtl.CompileOptions.mlx()); + errdefer library.deinit(); + const route = try mtl.Pipeline.init(rows.device, library, "tf_ling_route", false); + errdefer route.deinit(); + const r: usize = rows.max_rows; + return .{ + .library = library, + .route = route, + .hidden = hidden, + .inter = inter, + .logits = try rows.buffer(r * 128 * 4), + .ids = try rows.buffer(r * 8 * 4), + .weights = try rows.buffer(r * 8 * 4), + .where = try rows.buffer(r * 8 * 4), + .experts = try rows.buffer(r * 8 * hidden * 2), + .routed = try rows.buffer(r * hidden * 2), + .shared = try rows.buffer(r * hidden * 2), + .gate = try rows.buffer(r * inter * 2), + .up = try rows.buffer(r * inter * 2), + .activation = try rows.buffer(r * inter * 2), + }; + } + + pub fn forward(self: *Moe, rows: *Rows, model: *ck.Checkpoint, prefix: []const u8, x: Ref, out: Ref, n: u32) !void { + if (n == 0 or n > rows.max_rows) return error.RowCapacity; + const router = try std.mem.concat(rows.allocator, u8, &.{ prefix, "gate.weight" }); + defer rows.allocator.free(router); + try rows.linear(model, router, x, .{ .buf = self.logits }, n, self.hidden, 128, true); + const bias_name = try std.mem.concat(rows.allocator, u8, &.{ prefix, "gate.expert_bias" }); + defer rows.allocator.free(bias_name); + const bias = try model.get(bias_name, .f32, &.{128}); + const cb = rows.queue.commandBuffer(); + const e = cb.compute(.serial); + e.setPipeline(self.route); + e.setBuffer(self.logits, 0, 0); + e.setBuffer(bias.buffer, bias.offset, 1); + e.setValue(RouteArgs{ .rows = @intCast(n), .ne = 128, .topk = 8, .ng = 8, .keep = 4, .scale = 2.5 }, 2); + e.setBuffer(self.ids, 0, 3); + e.setBuffer(self.weights, 0, 4); + e.dispatchGroups(mtl.Size.of(n, 1, 1), mtl.Size.of(32, 1, 1)); + e.end(); + cb.commit(); + cb.wait(); + if (cb.failure() != null) return error.GpuFailed; + for (0..n) |t| for (0..8) |j| { + const at = t * 8 + j; + const id = self.ids.slice(i32, n * 8)[at]; + if (id < 0 or id >= 128) return error.InvalidExpert; + const expert = try std.fmt.allocPrint(rows.allocator, "{s}experts.{d}.", .{ prefix, id }); + defer rows.allocator.free(expert); + try rows.mlp(model, expert, x.at(t * self.hidden * 2), .{ .buf = self.experts, .off = at * self.hidden * 2 }, .{ .buf = self.gate }, .{ .buf = self.up }, .{ .buf = self.activation }, 1, self.hidden, self.inter); + self.where.slice(u32, n * 8)[at] = @intCast(at); + }; + const shared = try std.mem.concat(rows.allocator, u8, &.{ prefix, "shared_experts." }); + defer rows.allocator.free(shared); + try rows.mlp(model, shared, x, .{ .buf = self.shared }, .{ .buf = self.gate }, .{ .buf = self.up }, .{ .buf = self.activation }, n, self.hidden, self.inter); + const sum_cb = rows.queue.commandBuffer(); + const sum_e = sum_cb.compute(.serial); + rows.k.combine(sum_e, .{ .buf = self.experts }, .{ .buf = self.where }, .{ .buf = self.weights }, .{ .buf = self.routed }, .{ .buf = self.ids }, n, false, 128, 0, 1, .{ .K = self.inter, .N = self.hidden, .topk = 8, .rows_max = rows.max_rows, .beta = 0, .lin = 0 }); + sum_e.end(); + sum_cb.commit(); + sum_cb.wait(); + if (sum_cb.failure() != null) return error.GpuFailed; + try rows.add(.{ .buf = self.routed }, .{ .buf = self.shared }, out, n * self.hidden); + } + + pub fn deinit(self: *Moe) void { + self.route.deinit(); + self.library.deinit(); + } +}; diff --git a/zig/src/families/ling/metal_rows.zig b/zig/src/families/ling/metal_rows.zig new file mode 100644 index 00000000000..2559bec6d22 --- /dev/null +++ b/zig/src/families/ling/metal_rows.zig @@ -0,0 +1,139 @@ +//! Ling's bf16 row operations over existing Kimi kernels, retaining checkpoint weights in mapped buffers. +const std = @import("std"); +const mtl = @import("metal"); +const kernels = @import("kimi_kernels"); +const ck = @import("ling_checkpoint"); +const Ref = kernels.Ref; + +pub const Rows = struct { + allocator: std.mem.Allocator, + device: mtl.Device, + queue: mtl.Queue, + library: mtl.Library, + glue: mtl.Library, + swiglu: mtl.Pipeline, + k: kernels.Kernels, + scratch: mtl.Buffer, + owned: std.ArrayList(mtl.Buffer) = .empty, + weights: std.StringHashMapUnmanaged(mtl.Buffer) = .empty, + max_rows: u32, + fail_buffer_at: ?usize = null, + + pub fn init(a: std.mem.Allocator, device: mtl.Device, max_rows: u32) !Rows { + const library = try mtl.Library.fromBytes(device, @import("kimi_metallib").bytes); + errdefer library.deinit(); + var k = try kernels.Kernels.init(device, library); + errdefer k.deinit(); + const queue = try device.queue(); + errdefer queue.deinit(); + const glue = try mtl.Library.fromSource(device, @import("kernel_sources").lfm3, mtl.CompileOptions.mlx()); + errdefer glue.deinit(); + const swiglu = try mtl.Pipeline.init(device, glue, "lfm3_swiglu", false); + errdefer swiglu.deinit(); + const scratch = try device.buffer(kernels.partFloats(max_rows) * 4, mtl.ResourceOptions.shared); + return .{ .allocator = a, .device = device, .queue = queue, .library = library, .glue = glue, .swiglu = swiglu, .k = k, .scratch = scratch, .max_rows = max_rows }; + } + + pub fn buffer(self: *Rows, bytes: usize) !mtl.Buffer { + if (self.fail_buffer_at) |at| if (self.owned.items.len >= at) return error.OutOfMemory; + const b = try self.device.buffer(@max(bytes, 16), mtl.ResourceOptions.shared); + errdefer b.deinit(); + try self.owned.append(self.allocator, b); + return b; + } + + pub fn rollbackBuffers(self: *Rows, mark: usize) void { + for (self.owned.items[mark..]) |b| b.deinit(); + self.owned.shrinkRetainingCapacity(mark); + } + + fn finish(cb: mtl.CommandBuffer, e: mtl.ComputeEncoder) !void { + e.end(); + cb.commit(); + cb.wait(); + if (cb.failure() != null) return error.GpuFailed; + } + + pub fn weight(self: *Rows, model: *ck.Checkpoint, name: []const u8, n: u32, width: u32) !mtl.Buffer { + if (width % 64 != 0) return error.UnsupportedProjectionWidth; + const source = try model.get(name, .bf16, &.{ n, width }); + if (self.weights.get(name)) |w| return w; + const w = try self.buffer(@as(usize, n) * width * 2); + const cb = self.queue.commandBuffer(); + const e = cb.compute(.serial); + self.k.interleaved(e, .{ .buf = source.buffer, .off = source.offset }, .{ .buf = w }, n, width); + try finish(cb, e); + const key = try self.allocator.dupe(u8, name); + errdefer self.allocator.free(key); + try self.weights.put(self.allocator, key, w); + return w; + } + + pub fn linear(self: *Rows, model: *ck.Checkpoint, name: []const u8, x: Ref, y: Ref, rows: u32, width: u32, n: u32, fp32: bool) !void { + return self.linearInto(model, name, x, y, rows, width, n, width, n, fp32); + } + + pub fn linearInto(self: *Rows, model: *ck.Checkpoint, name: []const u8, x: Ref, y: Ref, rows: u32, width: u32, n: u32, x_stride: u32, y_stride: u32, fp32: bool) !void { + if (rows == 0 or rows > self.max_rows) return error.RowCapacity; + const w = try self.weight(model, name, n, width); + const cb = self.queue.commandBuffer(); + const e = cb.compute(.serial); + self.k.rows(e, x, .{ .buf = w }, y, .{ .buf = self.scratch }, fp32, .{ .K = width, .N = n, .rows = rows, .x_stride = x_stride, .y_stride = y_stride }); + try finish(cb, e); + } + + pub fn norm(self: *Rows, model: *ck.Checkpoint, name: []const u8, x: Ref, y: Ref, rows: u32, width: u32, eps: f32) !void { + if (rows == 0 or rows > self.max_rows) return error.RowCapacity; + const w = try model.get(name, .bf16, &.{width}); + const cb = self.queue.commandBuffer(); + const e = cb.compute(.serial); + self.k.rmsNorm(e, x, .{ .buf = w.buffer, .off = w.offset }, y, rows, .{ .D = width, .x_stride = width, .y_stride = width, .eps = eps }); + try finish(cb, e); + } + + pub fn add(self: *Rows, x: Ref, delta: Ref, out: Ref, count: u32) !void { + const cb = self.queue.commandBuffer(); + const e = cb.compute(.serial); + self.k.add(e, x, delta, out, count); + try finish(cb, e); + } + + pub fn mlp(self: *Rows, model: *ck.Checkpoint, prefix: []const u8, x: Ref, out: Ref, gate: Ref, up: Ref, activation: Ref, rows: u32, hidden: u32, inter: u32) !void { + const g = try std.fmt.allocPrint(self.allocator, "{s}gate_proj.weight", .{prefix}); + defer self.allocator.free(g); + const u = try std.fmt.allocPrint(self.allocator, "{s}up_proj.weight", .{prefix}); + defer self.allocator.free(u); + const d = try std.fmt.allocPrint(self.allocator, "{s}down_proj.weight", .{prefix}); + defer self.allocator.free(d); + try self.linear(model, g, x, gate, rows, hidden, inter, false); + try self.linear(model, u, x, up, rows, hidden, inter, false); + try self.siluMul(gate, up, activation, rows * inter); + try self.linear(model, d, activation, out, rows, inter, hidden, false); + } + + pub fn siluMul(self: *Rows, gate: Ref, up: Ref, out: Ref, count: u32) !void { + const cb = self.queue.commandBuffer(); + const e = cb.compute(.serial); + e.setPipeline(self.swiglu); + e.setBuffer(gate.buf, gate.off, 0); + e.setBuffer(up.buf, up.off, 1); + e.setBuffer(out.buf, out.off, 2); + e.setValue(count, 3); + e.dispatchThreads(mtl.Size.of((count + 7) / 8, 1, 1), mtl.Size.of(256, 1, 1)); + try finish(cb, e); + } + + pub fn deinit(self: *Rows) void { + var keys = self.weights.keyIterator(); + while (keys.next()) |key| self.allocator.free(key.*); + self.weights.deinit(self.allocator); + for (self.owned.items) |b| b.deinit(); + self.owned.deinit(self.allocator); + self.scratch.deinit(); + self.k.deinit(); + self.swiglu.deinit(); + self.glue.deinit(); + self.library.deinit(); + self.queue.deinit(); + } +}; diff --git a/zig/src/families/ling/oracle/ling_forward.py b/zig/src/families/ling/oracle/ling_forward.py index aab4c520286..6f2d520ba54 100644 --- a/zig/src/families/ling/oracle/ling_forward.py +++ b/zig/src/families/ling/oracle/ling_forward.py @@ -155,7 +155,7 @@ def moe(self, x, p, i): y[t] += self.mlp(x[t:t + 1], f"{p}experts.{int(idx[t, j])}.", le)[0] * w[t, j] return r(r(y) + self.mlp(x, p + "shared_experts.", ls)) - def logits(self, ids): + def logits(self, ids, trace=None): c, ck = self.c, self.ck x = ck.t("model.word_embeddings.weight").double()[ids] for i in range(c["num_hidden_layers"]): @@ -166,6 +166,8 @@ def logits(self, ids): x = self.r(x + (self.mla(h, p + "attention.") if mla else self.kda(h, p + "attention."))) h = self.norm(x, ck.t(p + "post_attention_layernorm.weight")) x = self.r(x + (self.moe(h, p + "mlp.", i) if i >= c["first_k_dense_replace"] else self.mlp(h, p + "mlp.", 0))) + if trace is not None: + trace(i, x) self.hidden = self.norm(x, ck.t("model.norm.weight")) return self.hidden @ ck.lin("lm_head").T @@ -192,6 +194,7 @@ def main(): a.add_argument("ckpt", help="a ling-synth directory (config.json, model.safetensors) or a sharded checkpoint's") a.add_argument("out", help="the reference file: ids, float64 and bf16-point logits, the picks it routed on") a.add_argument("--tokens", type=int, default=88) + a.add_argument("--layer-trace", help="write per-layer float64 and bf16-point hidden rows beside logits") a.add_argument("--picks", help="route on these picks (i32 [MoE layers][tokens][top_k], the graph's) instead") a.add_argument("--mtp", help="also the MTP layer's logits (float64, bf16 points) and its own picks, to this file") a.add_argument("--ids", help="these tokens (i32, ling-lanes' OUT.ids) instead of the fixed walk; --tokens follows") @@ -235,8 +238,17 @@ def main(): forced = torch.frombuffer(bytearray(open(o.picks, "rb").read()), dtype=torch.int32).view(nm, T, -1) with torch.no_grad(): exact = Model(ck, c, lambda z: z, forced) - l64 = exact.logits(ids) - lbf = Model(ck, c, bf16, forced).logits(ids) + traces = [[], []] + def capture(which): + return lambda layer, x: traces[which].append(x.clone()) + l64 = exact.logits(ids, capture(0) if o.layer_trace else None) + lbf = Model(ck, c, bf16, forced).logits(ids, capture(1) if o.layer_trace else None) + if o.layer_trace: + with open(o.layer_trace, "wb") as f: + f.write(b"TFLINGH1" + struct.pack("<3I", c["num_hidden_layers"], T, c["hidden_size"])) + for layers in traces: + for x in layers: + f.write(x.contiguous().numpy().tobytes()) if o.mtp: # the bf16-point model's own picks route its MTP layer; float64's are written for the flips rounded = Model(ck, c, bf16, forced) rounded.logits(ids) diff --git a/zig/src/families/minimax_m3/backend.zig b/zig/src/families/minimax_m3/backend.zig index fc68870438e..0c9dd88d78e 100644 --- a/zig/src/families/minimax_m3/backend.zig +++ b/zig/src/families/minimax_m3/backend.zig @@ -6,6 +6,7 @@ const st = @import("state.zig"); const fwd = @import("forward.zig"); const Model = @import("model.zig").Model; const snapshot = @import("snapshot.zig"); +const pass = @import("prompt_pass.zig"); const row = @import("../step5/backend.zig").row; const be = lanes.backend; @@ -42,6 +43,8 @@ pub const Metal = struct { costs: [max_window]lanes.config.Cost = undefined, // window forward ms by rows, timed by measure() for the depth rule timed: usize = 0, values: []f32, // a logits row as f32, for the host twin of the GPU draw + 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 pub fn init(gpa: std.mem.Allocator, model: *Model, options: Options) !*Metal { const out = try gpa.create(Metal); @@ -68,6 +71,9 @@ pub const Metal = struct { self.gpa.destroy(cache.*); } self.caches.deinit(self.gpa); + var passes = self.passes.valueIterator(); + while (passes.next()) |p| p.deinit(self.gpa); + self.passes.deinit(self.gpa); self.scratch.deinit(); self.prompt.deinit(); self.gpa.destroy(self); @@ -114,6 +120,7 @@ pub const Metal = struct { var ts0: std.c.timespec = undefined; _ = std.c.clock_gettime(.MONOTONIC, &ts0); try fwd.run(self.model, &self.scratch, &cache, ids[0..rows], .{ .all = true }); + self.gen +%= 1; 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; @@ -124,7 +131,7 @@ pub const Metal = struct { } /// A tapped row's bytes: every tap's hidden row, bf16. - fn tapBytes(self: *const Metal) usize { + pub fn tapBytes(self: *const Metal) usize { return @as(usize, self.model.taps) * self.model.config.hidden * 2; } @@ -148,30 +155,40 @@ 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 tp = (try self.cacheOf(stream)).tap; - if (taps.len != self.model.taps or tp.buf == null) return error.UnpreparedMiniMaxTaps; - if (count == 0 or start < tp.start or start + count > tp.start + tp.rows) return error.MiniMaxTapsNotHeld; + const cache = try self.cacheOf(stream); + var tp = cache.tap; + if (taps.len != self.model.taps) return error.UnpreparedMiniMaxTaps; + // a stepped pass's latest chunk (#3021): its rows stay in the scratch until the next forward + if (cache.chunk_tap) |k| if (!within(tp, start, count) and pass.within(k.tap, k.gen, self.gen, start, count)) { + tp = k.tap; + }; + if (tp.buf == null) return error.UnpreparedMiniMaxTaps; + if (!within(tp, start, count)) return error.MiniMaxTapsNotHeld; const width = self.tapBytes(); return .{ .buffer = @intFromPtr(tp.buf.?.id), .offset = tp.off + (start - tp.start) * width, .rows = count, .row_bytes = @intCast(width), .space = .device, .dtype = .bf16 }; } + fn within(tp: st.Tap, start: u64, count: u32) bool { + return count != 0 and start >= tp.start and start + count <= tp.start + tp.rows; + } + fn prefillFeaturesFn(ptr: *anyopaque, stream: *lanes.Stream, taps: []const u32, sink: be.FeatureSink) !void { const self = cast(ptr); if (taps.len != self.model.taps) return error.UnpreparedMiniMaxTaps; self.sink = sink; defer self.sink = null; - return prefillFn(ptr, stream); + return pass.whole(self, stream); } pub fn backend(self: *Metal) be.Backend { - return .{ .ptr = self, .vtable = &.{ .prefill = prefillFn, .prepare_features = prepareFn, .features = featuresFn, .prefill_features = prefillFeaturesFn, .first = firstFn, .first_masked = firstMaskedFn, .queue = queueFn, .read = readFn, .verify = verifyFn, .keep = keepFn, .draft = draftFn, .release = releaseFn, .first_row = firstRowFn, .held = heldFn } }; + 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, .first_row = firstRowFn, .held = heldFn } }; } fn cast(ptr: *anyopaque) *Metal { return @ptrCast(@alignCast(ptr)); } - fn cacheOf(self: *Metal, stream: *lanes.Stream) !*st.Cache { + pub fn cacheOf(self: *Metal, stream: *lanes.Stream) !*st.Cache { return self.caches.get(stream) orelse error.UnknownMiniMaxStream; } @@ -226,112 +243,33 @@ pub const Metal = struct { } /// Every step in flight landed: before the host reads caches or logits, or the GPU runs anything else. - fn drain(self: *Metal) !void { + pub fn drain(self: *Metal) !void { while (self.flights.items.len > 0) try self.land(); } - /// Run `ids` at the cache's end in prompt chunks; a stream's pass stops at its chunk starts and reuse marks. - fn feed(self: *Metal, cache: *st.Cache, ids: []const u32, stream: ?*lanes.Stream, images: []const fwd.Span) !void { - const base = cache.len; + /// Run `ids` at the cache's end in prompt chunks, with no stream (warm): the stream's pass is prompt_pass.zig's. + fn feed(self: *Metal, cache: *st.Cache, ids: []const u32) !void { 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 end = @min(ids.len, at + st.prompt_rows); const s = if (end - at > st.batch_rows) &self.prompt else &self.scratch; - const taps = if (stream != null) s.taps else null; - try fwd.run(self.model, s, cache, ids[at..end], .{ .taps = if (taps) |x| fwd.b(x) else null, .images = images }); - if (taps) |x| { - if (self.sink) |k| try k.take(k.ptr, stream.?, .{ .buffer = @intFromPtr(x.id), .rows = @intCast(end - at), .row_bytes = @intCast(self.tapBytes()), .space = .device, .dtype = .bf16 }, cache.len); - if (base + end == stream.?.prompt().len) { // the prompt's last row, kept for the first draft - const width = self.tapBytes(); - if (cache.last_tap == null) cache.last_tap = try self.model.device.buffer(width, mtl.ResourceOptions.shared); - @memcpy(cache.last_tap.?.slice(u8, width), x.slice(u8, (end - at) * width)[(end - at - 1) * width ..][0..width]); - cache.tap = .{ .buf = cache.last_tap, .start = cache.len + (end - at) - 1, .rows = 1 }; - } - } + try fwd.run(self.model, s, cache, ids[at..end], .{ .taps = null, .images = &.{} }); + self.gen +%= 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); - try self.drain(); - const ids = stream.prompt(); - if (ids.len == 0 or ids.len + stream.max_new > self.options.capacity or self.caches.contains(stream)) return error.InvalidMiniMaxPrompt; - const capacity = ids.len + stream.max_new + 1; - const need = st.cacheBytes(&self.model.config, capacity); - if (self.held + need > self.options.budget) { - std.log.warn("minimax_m3: a {d}-token stream needs {d:.1} GiB of caches; {d:.1} of {d:.1} GiB are held", .{ capacity, gib(need), gib(self.held), gib(self.options.budget) }); - return error.MiniMaxCachesFull; - } - self.held += need; - errdefer self.held -= need; - if (stream.reuse.saved) |saved| { // a state the stream cannot hold beside its caches: freed now, no restore - const snap: *snapshot.Snap = @ptrCast(@alignCast(saved)); - if (self.held + snap.bytes > self.options.budget) snap.free(); - } - // kept states give way first - if (self.room) |r| r.fit(r.ctx, self.options.budget - self.held, stream.reuse.saved, ids); - const cache = try self.createCache(capacity); - errdefer self.gpa.destroy(cache); - errdefer cache.deinit(); - try self.caches.put(self.gpa, stream, cache); // a mark's save finds it there - errdefer _ = self.caches.remove(stream); - stream.cached = 0; - if (stream.reuse.saved) |saved| { // a kept state of this prompt's prefix: the pass starts there - const snap: *const snapshot.Snap = @ptrCast(@alignCast(saved)); - if (snap.at < ids.len) { - if (snapshot.restore(self.model.queue, &self.model.config, snap, cache)) stream.cached = snap.at else |_| stream.reuse_failed = true; - } else stream.reuse_failed = true; - } - var spans: std.ArrayList(fwd.Span) = .empty; - defer spans.deinit(self.gpa); - const rows_buf = try self.encodeImages(stream, cache.len, &spans); - defer if (rows_buf) |b| b.deinit(); - try self.feed(cache, ids[cache.len..], stream, spans.items); + return pass.whole(cast(ptr), stream); } - /// The tower's rows of the stream's images past `from` (one before it is in the restored state), a span each. - fn encodeImages(self: *Metal, stream: *const lanes.Stream, from: usize, spans: *std.ArrayList(fwd.Span)) !?mtl.Buffer { - var total: usize = 0; - for (stream.images) |im| { - if (im.at + im.tokens > stream.prompt().len or im.tokens * 4 != im.gh * im.gw) return error.InvalidMiniMaxImage; - if (im.at + im.tokens > from) total += im.tokens; - } - if (total == 0) return null; - const v = self.model.vision orelse return error.NoMiniMaxVision; - const width: usize = self.model.config.hidden; - const buf = try self.model.device.buffer(total * width * 2, mtl.ResourceOptions.private | mtl.ResourceOptions.untracked); - errdefer buf.deinit(); - var done: usize = 0; - for (stream.images) |im| { // one command buffer an image: the tower's host-written tables are one image's - if (im.at + im.tokens <= from) continue; - const span: fwd.Span = .{ .at = im.at, .n = im.tokens, .rows = .{ .buf = buf, .off = done * width * 2 } }; - const cb = self.model.queue.commandBuffer(); - const e = cb.compute(.serial); - try v.encode(e, im.pixels, im.gh, im.gw, span.rows); - e.end(); - cb.commit(); - cb.wait(); - if (cb.failure()) |msg| { - std.log.err("minimax_m3: the image tower failed: {s}", .{msg}); - return error.GpuFailed; - } - try spans.append(self.gpa, span); - done += im.tokens; - } - return buf; + fn prefillStepFn(ptr: *anyopaque, stream: *lanes.Stream, _: u32) !bool { + return pass.step(cast(ptr), stream); + } + + fn cancelPrefillFn(ptr: *anyopaque, stream: *lanes.Stream) !void { + return pass.cancel(cast(ptr), stream); } /// A prompt chunk and a decode window once: the first request skips the GPU's first touch. @@ -342,8 +280,9 @@ pub const Metal = struct { var ids: [st.prompt_rows]u32 = undefined; for (&ids, 0..) |*t, i| t.* = @intCast(1000 + i * 37 % 20000); const n = cache.capacity - st.window_rows; - try self.feed(&cache, ids[0..n], null, &.{}); + try self.feed(&cache, ids[0..n]); try fwd.run(self.model, &self.scratch, &cache, ids[0..st.window_rows], .{ .all = true }); + self.gen +%= 1; } /// The first token, drawn on the host from the prompt's last row into a fresh slot. @@ -382,6 +321,7 @@ pub const Metal = struct { const how: @FieldType(fwd.Draw, "how") = if (sampled(stream.sampling)) |t| .{ .sampled = .{ .sampling = t, .position = position } } else .greedy; var cb: mtl.CommandBuffer = undefined; try fwd.run(self.model, &self.scratch, cache, &.{0}, .{ .ids = self.slotOf(in), .draw = .{ .how = how, .out = self.slotOf(out) }, .flight = &cb }); + self.gen +%= 1; self.flights.append(self.gpa, .{ .end = out + 1, .cb = cb }) catch |err| { cb.wait(); cb.release(); @@ -428,6 +368,7 @@ pub const Metal = struct { total += rows; } try fwd.runShared(self.model, &self.scratch, segments[0..windows.len], ids[0..total], .{ .all = true, .taps = if (self.scratch.taps) |x| fwd.b(x) else null }); + self.gen +%= 1; if (self.scratch.taps) |x| { var at: usize = 0; for (segments[0..windows.len]) |seg| { @@ -477,6 +418,7 @@ pub const Metal = struct { fn releaseFn(ptr: *anyopaque, stream: *lanes.Stream) void { const self = cast(ptr); self.drain() catch |err| std.log.err("minimax_m3: a step in flight failed at release: {s}", .{@errorName(err)}); + pass.forget(self, stream); // a stream that leaves mid-pass if (self.caches.fetchRemove(stream)) |entry| { self.held -= st.cacheBytes(&self.model.config, entry.value.capacity); entry.value.deinit(); @@ -512,10 +454,6 @@ pub const Metal = struct { } }; -fn gib(bytes: u64) f64 { - return @as(f64, @floatFromInt(bytes)) / (1 << 30); -} - fn logit(word: u16) f32 { return @bitCast(@as(u32, word) << 16); } diff --git a/zig/src/families/minimax_m3/dflash2.zig b/zig/src/families/minimax_m3/dflash2.zig index 58dcbf3a2f6..48e838af538 100644 --- a/zig/src/families/minimax_m3/dflash2.zig +++ b/zig/src/families/minimax_m3/dflash2.zig @@ -8,6 +8,7 @@ const wts = @import("weights.zig"); const fwd = @import("forward.zig"); const Model = @import("model.zig").Model; const now = @import("dspark.zig").now; +const batch = @import("hold_batch.zig"); const dr = lanes.drafter; const Stream = lanes.Stream; @@ -184,6 +185,8 @@ pub const Drafter = struct { lanes: std.AutoHashMapUnmanaged(*Stream, *Lane) = .empty, follow: ?mtl.ResidencySet.Follow = null, step_ms: f64 = 0, + /// Absorb's last command buffer, committed without a wait: settled before the next pass reads what it wrote. + pending: ?mtl.CommandBuffer = null, s: [fields.len]mtl.Buffer = undefined, pub fn init(gpa: std.mem.Allocator, target: *Model, config: Config) !*Drafter { @@ -207,14 +210,15 @@ pub const Drafter = struct { } errdefer for (d.pipes) |p| p.deinit(); const h: usize = c.hidden; - const r: usize = max_block; + const r: usize = max_block * batch.max_blocks; // a pass's stacked blocks + const one: usize = max_block; // a block's attention partials, reused block after block const qw: usize = c.heads * 128; const kvw: usize = c.kv_heads * 128; const nblk: usize = c.ring() / 128 + 1; const vocab: usize = target.config.vocab; const chunks: usize = (vocab + 2047) / 2048; const dyn: usize = 4 * (h / c.group); - const sizes = [fields.len]usize{ r * 4, r * h * 4, r * h * 2, r * h * 2, r * dyn * 2, r * (qw + 2 * kvw) * 2, r * qw * 2, r * qw * 2, r * h * 2, r * h * 2, r * 2 * c.ffn * 2, r * c.ffn * 2, r * vocab * 2, c.heads * r * nblk * 4, c.heads * r * nblk * 4, c.heads * r * nblk * 128 * 4, r * chunks * 32 * 4, r * chunks * 32 * 4, r * 64 * 4, r * 64 * 4, r * 32 * 4, r * 32 * 4, r * c.rank * 2, 16 * 4, absorb_rows * h * 2, absorb_rows * h * 2, absorb_rows * c.layers * 2 * kvw * 2, absorb_rows * h * c.taps.len / 32 * 4, 16, 16 }; + const sizes = [fields.len]usize{ r * 4, r * h * 4, r * h * 2, r * h * 2, r * dyn * 2, r * (qw + 2 * kvw) * 2, r * qw * 2, r * qw * 2, r * h * 2, r * h * 2, r * 2 * c.ffn * 2, r * c.ffn * 2, r * vocab * 2, c.heads * one * nblk * 4, c.heads * one * nblk * 4, c.heads * one * nblk * 128 * 4, r * chunks * 32 * 4, r * chunks * 32 * 4, r * 64 * 4, r * 64 * 4, r * 32 * 4, r * 32 * 4, r * c.rank * 2, batch.max_blocks * 16 * 4, absorb_rows * h * 2, absorb_rows * h * 2, absorb_rows * c.layers * 2 * kvw * 2, absorb_rows * h * c.taps.len / 32 * 4, 16, 16 }; var made: usize = 0; errdefer for (d.s[0..made]) |x| x.deinit(); for (sizes, 0..) |n, i| { @@ -226,6 +230,7 @@ pub const Drafter = struct { } pub fn deinit(d: *Drafter) void { + d.settle() catch {}; // an absorb in flight writes the lanes freed below d.setResident(null); var it = d.lanes.valueIterator(); while (it.next()) |l| d.dropLane(l.*); @@ -282,7 +287,7 @@ pub const Drafter = struct { fn factsFn(ptr: *anyopaque) dr.Facts { const d = cast(ptr); - return .{ .depth = d.config.block - 1, .step_ms = d.step_ms, .plain_guard = true, .stream_bytes = d.laneBytes() }; + return .{ .depth = d.config.block - 1, .step_ms = d.step_ms, .plain_guard = true, .batched = true, .stream_bytes = d.laneBytes() }; } fn newLane(d: *Drafter) !*Lane { @@ -377,6 +382,7 @@ pub const Drafter = struct { fn absorbFn(ptr: *anyopaque, items: []const dr.Absorb) anyerror!void { const d = cast(ptr); const c = &d.config; + try d.settle(); const pool = mtl.objc.Pool.push(); defer pool.pop(); const cb = d.target.queue.commandBuffer(); @@ -401,6 +407,14 @@ pub const Drafter = struct { } e.end(); cb.commit(); + d.pending = cb.retain(); // the queue runs the next hold after it: no wait here + } + + /// Waits for absorb's command buffer and reports its failure, before anything reads what it wrote. + fn settle(d: *Drafter) !void { + const cb = d.pending orelse return; + d.pending = null; + defer cb.release(); cb.wait(); if (cb.failure()) |msg| return failed(msg); } @@ -412,89 +426,118 @@ pub const Drafter = struct { threads(e, d.pipe(.conv), CArgs{ .rows = @intCast(n), .width = c.hidden, .block = c.block, .groups = c.hidden / c.group, .side = 0 }, &.{ b(d.buf("x")), b(d.buf("dyn")), t(conv.base), A, b(d.buf("xc")) }, .{ c.hidden, n, 1 }); } - /// The block [pending, mask x 7] at positions anchor.. through the drafter; seq[1..] its drafts (rows 1-7's path). - fn encodeBlock(d: *const Drafter, e: mtl.ComputeEncoder, l: *const Lane, pending: u32, anchor: u64) !void { + /// A pass's block: the stream's lane, its pending token and the row before it. + const Blk = struct { lane: *const Lane, pending: u32, anchor: u64 }; + + /// Each block [pending, mask x 7] at anchor.. through the drafter, stacked; seq at seqAt(slot) holds its drafts. + fn encodeBlocks(d: *const Drafter, e: mtl.ComputeEncoder, blocks: []const Blk) !void { const c = &d.config; const m = d.target; const n: usize = c.block; + const rows: usize = blocks.len * n; const h: usize = c.hidden; - const qw: usize = c.heads * 128; - const kvw: usize = c.kv_heads * 128; - const ids = d.buf("ids").slice(u32, max_block); - ids[0] = pending; - @memset(ids[1..n], c.mask); - d.buf("seq").slice(u32, 16)[0] = pending; + var pendings: [batch.max_blocks]u32 = undefined; + for (blocks, 0..) |k, s| pendings[s] = k.pending; + batch.fillIds(d.buf("ids").slice(u32, rows), pendings[0..blocks.len], n, c.mask); + const seq = d.buf("seq").slice(u32, batch.max_blocks * 16); + for (blocks, 0..) |k, s| seq[batch.seqAt(s)] = k.pending; const E = m.weights.embed; const MArgs = extern struct { rows: u32 = 0, width: u32 = 0, heads: u32 = 0, dim: u32 = 0, pos: u32 = 0, stride: u32 = 0, bits: u32 = 0, group: u32 = 0, eps: f32 = 0, alpha: f32 = 0, limit: f32 = 0, scale: f32 = 0 }; - glue(e, m.pipe(.embed), MArgs{ .rows = @intCast(n), .width = c.hidden, .bits = E.bits, .group = @intCast(E.group) }, &.{ b(d.buf("ids")), bo(E.w, E.w_off), bo(E.scales, E.s_off), bo(E.biases, E.b_off), A, b(d.buf("resid")) }, .{ (h + 255) / 256, n, 1 }, .{ 256, 1, 1 }); - const lo = @max((anchor + 1) -| c.window, l.from); - const hi = anchor + n; - const first = lo / 128; - const blocks = (hi - 1) / 128 - first + 1; + glue(e, m.pipe(.embed), MArgs{ .rows = @intCast(rows), .width = c.hidden, .bits = E.bits, .group = @intCast(E.group) }, &.{ b(d.buf("ids")), bo(E.w, E.w_off), bo(E.scales, E.s_off), bo(E.biases, E.b_off), A, b(d.buf("resid")) }, .{ (h + 255) / 256, rows, 1 }, .{ 256, 1, 1 }); const groups: u32 = c.hidden / c.group; for (0..c.layers) |i| { const L = &d.w.layers[i]; // input norm (the residual takes the last sublayer's output first, from the second layer on) - glue(e, d.pipe(.norm), NArgs{ .rows = @intCast(n), .width = c.hidden, .eps = c.eps, .add = @intFromBool(i > 0) }, &.{ b(d.buf("resid")), b(d.buf("yc")), t(L.in_norm), A, b(d.buf("x")) }, .{ n, 1, 1 }, .{ 256, 1, 1 }); - try d.convPrepare(e, L.attn_conv, n); - try d.project(e, L.qkv, b(d.buf("xc")), b(d.buf("qkv")), n); - const pa = PArgs{ .rows = @intCast(n), .heads = c.heads, .kv_heads = c.kv_heads, .pos0 = @intCast(anchor), .stride = @intCast(qw + 2 * kvw), .q_off = 0, .k_off = @intCast(qw), .v_off = @intCast(qw + kvw), .ring = c.ring(), .eps = c.eps, .theta = c.theta }; - glue(e, d.pipe(.prep), pa, &.{ b(d.buf("qkv")), t(L.q_norm), t(L.k_norm), A, b(d.buf("q")), b(l.k[i]), b(l.v[i]) }, .{ c.heads + c.kv_heads, n, 1 }, .{ 32, 1, 1 }); - const va = VArgs{ .rows = @intCast(n), .pos0 = @intCast(anchor), .heads = c.heads, .groups = c.kv_heads, .blocks = @intCast(blocks), .first = @intCast(first), .hi = @intCast(hi), .window = c.window, .ring = c.ring(), .scale = 1.0 / @sqrt(128.0) }; - glue(e, m.draft_vec, va, &.{ b(d.buf("q")), b(l.k[i]), b(l.v[i]), A, b(d.buf("pm")), b(d.buf("pl")), b(d.buf("po")) }, .{ c.kv_heads, n, blocks }, .{ 32, c.heads / c.kv_heads, 1 }); - const ma = extern struct { rows: u32, pos: u32, heads: u32, groups: u32, topk: u32, scale: f32, sel: u32, all: u32 }{ .rows = @intCast(n), .pos = 0, .heads = c.heads, .groups = c.kv_heads, .topk = @intCast(blocks), .scale = 0, .sel = 0, .all = 0 }; - glue(e, m.pipe(.merge_vec), ma, &.{ b(d.buf("pm")), b(d.buf("pl")), b(d.buf("po")), A, b(d.buf("attn")) }, .{ c.heads, n, 1 }, .{ 32, 1, 1 }); - try d.project(e, L.o, b(d.buf("attn")), b(d.buf("y")), n); + glue(e, d.pipe(.norm), NArgs{ .rows = @intCast(rows), .width = c.hidden, .eps = c.eps, .add = @intFromBool(i > 0) }, &.{ b(d.buf("resid")), b(d.buf("yc")), t(L.in_norm), A, b(d.buf("x")) }, .{ rows, 1, 1 }, .{ 256, 1, 1 }); + try d.convPrepare(e, L.attn_conv, rows); // the conv mixes rows within a block only (r % block) + try d.project(e, L.qkv, b(d.buf("xc")), b(d.buf("qkv")), rows); + for (blocks, 0..) |k, s| try d.attend(e, k, i, batch.row(s, n)); + try d.project(e, L.o, b(d.buf("attn")), b(d.buf("y")), rows); // the attention conv's finish (side 1, its prepare's coefficients), then the post-attention norm - threads(e, d.pipe(.conv), CArgs{ .rows = @intCast(n), .width = c.hidden, .block = c.block, .groups = groups, .side = 1 }, &.{ b(d.buf("y")), b(d.buf("dyn")), t(L.attn_conv.base), A, b(d.buf("yc")) }, .{ c.hidden, n, 1 }); - glue(e, d.pipe(.norm), NArgs{ .rows = @intCast(n), .width = c.hidden, .eps = c.eps, .add = 1 }, &.{ b(d.buf("resid")), b(d.buf("yc")), t(L.post_norm), A, b(d.buf("x")) }, .{ n, 1, 1 }, .{ 256, 1, 1 }); - try d.convPrepare(e, L.mlp_conv, n); - try d.project(e, L.gu, b(d.buf("xc")), b(d.buf("gu")), n); - threads(e, d.pipe(.silu), extern struct { rows: u32, width: u32 }{ .rows = @intCast(n), .width = c.ffn }, &.{ b(d.buf("gu")), A, b(d.buf("act")) }, .{ c.ffn, n, 1 }); - try d.project(e, L.down, b(d.buf("act")), b(d.buf("y")), n); - threads(e, d.pipe(.conv), CArgs{ .rows = @intCast(n), .width = c.hidden, .block = c.block, .groups = groups, .side = 1 }, &.{ b(d.buf("y")), b(d.buf("dyn")), t(L.mlp_conv.base), A, b(d.buf("yc")) }, .{ c.hidden, n, 1 }); + threads(e, d.pipe(.conv), CArgs{ .rows = @intCast(rows), .width = c.hidden, .block = c.block, .groups = groups, .side = 1 }, &.{ b(d.buf("y")), b(d.buf("dyn")), t(L.attn_conv.base), A, b(d.buf("yc")) }, .{ c.hidden, rows, 1 }); + glue(e, d.pipe(.norm), NArgs{ .rows = @intCast(rows), .width = c.hidden, .eps = c.eps, .add = 1 }, &.{ b(d.buf("resid")), b(d.buf("yc")), t(L.post_norm), A, b(d.buf("x")) }, .{ rows, 1, 1 }, .{ 256, 1, 1 }); + try d.convPrepare(e, L.mlp_conv, rows); + try d.project(e, L.gu, b(d.buf("xc")), b(d.buf("gu")), rows); + threads(e, d.pipe(.silu), extern struct { rows: u32, width: u32 }{ .rows = @intCast(rows), .width = c.ffn }, &.{ b(d.buf("gu")), A, b(d.buf("act")) }, .{ c.ffn, rows, 1 }); + try d.project(e, L.down, b(d.buf("act")), b(d.buf("y")), rows); + threads(e, d.pipe(.conv), CArgs{ .rows = @intCast(rows), .width = c.hidden, .block = c.block, .groups = groups, .side = 1 }, &.{ b(d.buf("y")), b(d.buf("dyn")), t(L.mlp_conv.base), A, b(d.buf("yc")) }, .{ c.hidden, rows, 1 }); } - glue(e, d.pipe(.norm), NArgs{ .rows = @intCast(n), .width = c.hidden, .eps = c.eps, .add = 1 }, &.{ b(d.buf("resid")), b(d.buf("yc")), t(d.w.norm), A, b(d.buf("x")) }, .{ n, 1, 1 }, .{ 256, 1, 1 }); - // rows 1-7: the head, each row's top 32 (three passes of 2048), the selector's projection and path - const slots = n - 1; - const xr = bo(d.buf("x"), h * 2); - try d.project(e, m.weights.head, xr, b(d.buf("logits")), slots); - try d.project(e, d.w.hproj, xr, b(d.buf("hid")), slots); + glue(e, d.pipe(.norm), NArgs{ .rows = @intCast(rows), .width = c.hidden, .eps = c.eps, .add = 1 }, &.{ b(d.buf("resid")), b(d.buf("yc")), t(d.w.norm), A, b(d.buf("x")) }, .{ rows, 1, 1 }, .{ 256, 1, 1 }); + // every row through the head and its top 32 (a block's row 0 unread), then each block's rows 1-7 to its walk + try d.project(e, m.weights.head, b(d.buf("x")), b(d.buf("logits")), rows); + try d.project(e, d.w.hproj, b(d.buf("x")), b(d.buf("hid")), rows); const vocab: u32 = m.config.vocab; const chunks: u32 = (vocab + 2047) / 2048; const TArgs = extern struct { n: u32, stride: u32, chunks: u32, from_ids: u32 }; - glue(e, d.pipe(.topk), TArgs{ .n = vocab, .stride = vocab, .chunks = chunks, .from_ids = 0 }, &.{ b(d.buf("logits")), b(d.buf("tv")), b(d.buf("ti")), A, b(d.buf("tv")), b(d.buf("ti")) }, .{ chunks, slots, 1 }, .{ 1024, 1, 1 }); + glue(e, d.pipe(.topk), TArgs{ .n = vocab, .stride = vocab, .chunks = chunks, .from_ids = 0 }, &.{ b(d.buf("logits")), b(d.buf("tv")), b(d.buf("ti")), A, b(d.buf("tv")), b(d.buf("ti")) }, .{ chunks, rows, 1 }, .{ 1024, 1, 1 }); const second: u32 = (chunks * 32 + 2047) / 2048; - glue(e, d.pipe(.topk), TArgs{ .n = chunks * 32, .stride = chunks * 32, .chunks = second, .from_ids = 1 }, &.{ b(d.buf("logits")), b(d.buf("tv")), b(d.buf("ti")), A, b(d.buf("tv2")), b(d.buf("ti2")) }, .{ second, slots, 1 }, .{ 1024, 1, 1 }); - glue(e, d.pipe(.topk), TArgs{ .n = second * 32, .stride = second * 32, .chunks = 1, .from_ids = 1 }, &.{ b(d.buf("logits")), b(d.buf("tv2")), b(d.buf("ti2")), A, b(d.buf("uv")), b(d.buf("ui")) }, .{ 1, slots, 1 }, .{ 1024, 1, 1 }); + glue(e, d.pipe(.topk), TArgs{ .n = chunks * 32, .stride = chunks * 32, .chunks = second, .from_ids = 1 }, &.{ b(d.buf("logits")), b(d.buf("tv")), b(d.buf("ti")), A, b(d.buf("tv2")), b(d.buf("ti2")) }, .{ second, rows, 1 }, .{ 1024, 1, 1 }); + glue(e, d.pipe(.topk), TArgs{ .n = second * 32, .stride = second * 32, .chunks = 1, .from_ids = 1 }, &.{ b(d.buf("logits")), b(d.buf("tv2")), b(d.buf("ti2")), A, b(d.buf("uv")), b(d.buf("ui")) }, .{ 1, rows, 1 }, .{ 1024, 1, 1 }); const WArgs = extern struct { slots: u32, rank: u32, top: u32, vocab: u32 }; - glue(e, d.pipe(.walk), WArgs{ .slots = @intCast(slots), .rank = c.rank, .top = c.top, .vocab = vocab }, &.{ b(d.buf("uv")), b(d.buf("ui")), b(d.buf("hid")), t(d.w.pred), t(d.w.succ), A, b(d.buf("seq")) }, .{ 1, 1, 1 }, .{ c.rank, 1, 1 }); + for (0..blocks.len) |s| { + const first_row = batch.row(s, n) + 1; + glue(e, d.pipe(.walk), WArgs{ .slots = @intCast(n - 1), .rank = c.rank, .top = c.top, .vocab = vocab }, &.{ bo(d.buf("uv"), first_row * 32 * 4), bo(d.buf("ui"), first_row * 32 * 4), bo(d.buf("hid"), first_row * c.rank * 2), t(d.w.pred), t(d.w.succ), A, bo(d.buf("seq"), batch.seqAt(s) * 4) }, .{ 1, 1, 1 }, .{ c.rank, 1, 1 }); + } + } + + /// Layer `i`'s attention for one block at row `row` of the pass: its q and k/v into its lane, then its keys. + fn attend(d: *const Drafter, e: mtl.ComputeEncoder, k: Blk, i: usize, row: usize) !void { + const c = &d.config; + const m = d.target; + const l = k.lane; + const L = &d.w.layers[i]; + const n: usize = c.block; + const qw: usize = c.heads * 128; + const kvw: usize = c.kv_heads * 128; + const lo = @max((k.anchor + 1) -| c.window, l.from); + const hi = k.anchor + n; + const first = lo / 128; + const blocks = (hi - 1) / 128 - first + 1; + const pa = PArgs{ .rows = @intCast(n), .heads = c.heads, .kv_heads = c.kv_heads, .pos0 = @intCast(k.anchor), .stride = @intCast(qw + 2 * kvw), .q_off = 0, .k_off = @intCast(qw), .v_off = @intCast(qw + kvw), .ring = c.ring(), .eps = c.eps, .theta = c.theta }; + const q = bo(d.buf("q"), row * qw * 2); + glue(e, d.pipe(.prep), pa, &.{ bo(d.buf("qkv"), row * (qw + 2 * kvw) * 2), t(L.q_norm), t(L.k_norm), A, q, b(l.k[i]), b(l.v[i]) }, .{ c.heads + c.kv_heads, n, 1 }, .{ 32, 1, 1 }); + const va = VArgs{ .rows = @intCast(n), .pos0 = @intCast(k.anchor), .heads = c.heads, .groups = c.kv_heads, .blocks = @intCast(blocks), .first = @intCast(first), .hi = @intCast(hi), .window = c.window, .ring = c.ring(), .scale = 1.0 / @sqrt(128.0) }; + glue(e, m.draft_vec, va, &.{ q, b(l.k[i]), b(l.v[i]), A, b(d.buf("pm")), b(d.buf("pl")), b(d.buf("po")) }, .{ c.kv_heads, n, blocks }, .{ 32, c.heads / c.kv_heads, 1 }); + const ma = extern struct { rows: u32, pos: u32, heads: u32, groups: u32, topk: u32, scale: f32, sel: u32, all: u32 }{ .rows = @intCast(n), .pos = 0, .heads = c.heads, .groups = c.kv_heads, .topk = @intCast(blocks), .scale = 0, .sel = 0, .all = 0 }; + glue(e, m.pipe(.merge_vec), ma, &.{ b(d.buf("pm")), b(d.buf("pl")), b(d.buf("po")), A, bo(d.buf("attn"), row * qw * 2) }, .{ c.heads, n, 1 }, .{ 32, 1, 1 }); } - /// Each stream's `depth` drafts after `pending` at `position`: a whole block each (its rows see each other). + /// Each stream's `depth` drafts after `pending` at `position`: a whole block each, stacked, one wait a pass. fn holdFn(ptr: *anyopaque, items: []const dr.Hold) anyerror!void { const d = cast(ptr); const c = &d.config; - for (items) |it| { - const l = d.lanes.get(it.stream) orelse return error.DraftStreamUnknown; - if (it.depth == 0 or it.depth > c.block - 1 or it.position == 0) return error.DraftDepth; - const anchor = it.position - 1; - if (l.end != anchor) return error.DraftContextGap; + try d.settle(); + var at: usize = 0; + while (at < items.len) { + const count = batch.take(items.len - at); + const pass = items[at..][0..count]; + var blocks: [batch.max_blocks]Blk = undefined; + for (pass, blocks[0..count]) |it, *k| { + const l = d.lanes.get(it.stream) orelse return error.DraftStreamUnknown; + if (it.depth == 0 or it.depth > c.block - 1 or it.position == 0) return error.DraftDepth; + const anchor = it.position - 1; + if (l.end != anchor) return error.DraftContextGap; + k.* = .{ .lane = l, .pending = it.pending, .anchor = anchor }; + } const pool = mtl.objc.Pool.push(); defer pool.pop(); const cb = d.target.queue.commandBuffer(); const e = cb.compute(.serial); - try d.encodeBlock(e, l, it.pending, anchor); + try d.encodeBlocks(e, blocks[0..count]); e.end(); cb.commit(); cb.wait(); if (cb.failure()) |msg| return failed(msg); - const seq = d.buf("seq").slice(u32, 16); - for (seq[1..][0..it.depth], l.held[0..it.depth]) |x, *y| { - if (x >= d.target.config.vocab) return error.DraftNonfinite; - y.* = x; + const seq = d.buf("seq").slice(u32, batch.max_blocks * 16); + for (pass, 0..) |it, s| { + const l = d.lanes.get(it.stream).?; + for (seq[batch.seqAt(s) + 1 ..][0..it.depth], l.held[0..it.depth]) |x, *y| { + if (x >= d.target.config.vocab) return error.DraftNonfinite; + y.* = x; + } + l.held_len = it.depth; } - l.held_len = it.depth; + at += count; } } @@ -509,7 +552,7 @@ pub const Drafter = struct { defer pool.pop(); const cb = d.target.queue.commandBuffer(); const e = cb.compute(.serial); - try d.encodeBlock(e, l, 2, 0); + try d.encodeBlocks(e, &.{.{ .lane = l, .pending = 2, .anchor = 0 }}); e.end(); cb.commit(); cb.wait(); diff --git a/zig/src/families/minimax_m3/dspark.zig b/zig/src/families/minimax_m3/dspark.zig index 1270f274d29..2794a42cff2 100644 --- a/zig/src/families/minimax_m3/dspark.zig +++ b/zig/src/families/minimax_m3/dspark.zig @@ -1,5 +1,6 @@ //! MiniMax-M3.1's DSpark drafter (ref/dspark.py): 7-row blocks through five layers over the target's taps. const std = @import("std"); +const batch = @import("hold_batch.zig"); const mtl = @import("metal"); const lanes = @import("lanes"); const ks = @import("kernel_sources"); @@ -180,6 +181,8 @@ pub const Drafter = struct { follow: ?mtl.ResidencySet.Follow = null, step_ms: f64 = 0, s: [fields.len]mtl.Buffer = undefined, + /// Absorb's last command buffer, committed without a wait: settled before the next pass reads what it wrote. + pending: ?mtl.CommandBuffer = null, pub fn init(gpa: std.mem.Allocator, target: *Model, config: Config) !*Drafter { const pool = mtl.objc.Pool.push(); @@ -202,12 +205,13 @@ pub const Drafter = struct { } errdefer for (d.pipes) |p| p.deinit(); const h: usize = c.hidden; - const r: usize = max_block; + const r: usize = max_block * batch.max_blocks; // a pass's stacked blocks + const one: usize = max_block; // a block's attention partials, reused block after block const qw: usize = c.heads * 128; const kvw: usize = c.kv_heads * 128; const nblk: usize = c.ring() / 128 + 1; const vocab: usize = target.config.vocab; - const sizes = [fields.len]usize{ r * 4, r * h * 4, r * h * 2, r * (qw + 2 * kvw) * 2, r * qw * 2, r * qw * 2, r * h * 2, r * 2 * c.ffn * 2, r * c.ffn * 2, r * vocab * 2, c.heads * r * nblk * 4, c.heads * r * nblk * 4, c.heads * r * nblk * 128 * 4, (vocab + 255) / 256 * 4, (vocab + 255) / 256 * 4, 16 * 4, absorb_rows * h * 2, absorb_rows * h * 2, absorb_rows * c.layers * 2 * kvw * 2, absorb_rows * h * c.taps.len / 32 * 4 }; + const sizes = [fields.len]usize{ r * 4, r * h * 4, r * h * 2, r * (qw + 2 * kvw) * 2, r * qw * 2, r * qw * 2, r * h * 2, r * 2 * c.ffn * 2, r * c.ffn * 2, r * vocab * 2, c.heads * one * nblk * 4, c.heads * one * nblk * 4, c.heads * one * nblk * 128 * 4, (vocab + 255) / 256 * 4, (vocab + 255) / 256 * 4, batch.max_blocks * 16 * 4, absorb_rows * h * 2, absorb_rows * h * 2, absorb_rows * c.layers * 2 * kvw * 2, absorb_rows * h * c.taps.len / 32 * 4 }; var made: usize = 0; errdefer for (d.s[0..made]) |x| x.deinit(); for (sizes, 0..) |n, i| { @@ -219,6 +223,7 @@ pub const Drafter = struct { } pub fn deinit(d: *Drafter) void { + d.settle() catch {}; // an absorb in flight writes the lanes freed below d.setResident(null); var it = d.lanes.valueIterator(); while (it.next()) |l| d.dropLane(l.*); @@ -275,7 +280,7 @@ pub const Drafter = struct { fn factsFn(ptr: *anyopaque) dr.Facts { const d = cast(ptr); - return .{ .depth = d.config.block, .step_ms = d.step_ms, .plain_guard = true, .stream_bytes = d.laneBytes() }; + return .{ .depth = d.config.block, .step_ms = d.step_ms, .plain_guard = true, .batched = true, .stream_bytes = d.laneBytes() }; } fn newLane(d: *Drafter) !*Lane { @@ -359,6 +364,7 @@ pub const Drafter = struct { fn absorbFn(ptr: *anyopaque, items: []const dr.Absorb) anyerror!void { const d = cast(ptr); const c = &d.config; + try d.settle(); const pool = mtl.objc.Pool.push(); defer pool.pop(); const cb = d.target.queue.commandBuffer(); @@ -384,6 +390,14 @@ pub const Drafter = struct { } e.end(); cb.commit(); + d.pending = cb.retain(); // the queue runs the next hold after it: no wait here + } + + /// Waits for absorb's command buffer and reports its failure, before anything reads what it wrote. + fn settle(d: *Drafter) !void { + const cb = d.pending orelse return; + d.pending = null; + defer cb.release(); cb.wait(); if (cb.failure()) |msg| return failed(msg); } @@ -392,83 +406,115 @@ pub const Drafter = struct { const VArgs = extern struct { rows: u32, pos0: u32, heads: u32, groups: u32, blocks: u32, first: u32, hi: u32, window: u32, ring: u32, scale: f32 }; const MArgs = extern struct { rows: u32 = 0, width: u32 = 0, heads: u32 = 0, dim: u32 = 0, pos: u32 = 0, stride: u32 = 0, bits: u32 = 0, group: u32 = 0, eps: f32 = 0, alpha: f32 = 0, limit: f32 = 0, scale: f32 = 0 }; - /// The block [pending, noise x (block - 1)] at positions anchor.. through the drafter; seq[1..] its drafts. - fn encodeBlock(d: *const Drafter, e: mtl.ComputeEncoder, l: *const Lane, pending: u32, anchor: u64) !void { + /// A pass's block: the stream's lane, its pending token and the row before it. + const Blk = struct { lane: *const Lane, pending: u32, anchor: u64 }; + + /// Each block [pending, noise..] at anchor.. through the drafter, stacked; seq at seqAt(slot) holds its drafts. + fn encodeBlocks(d: *const Drafter, e: mtl.ComputeEncoder, blocks: []const Blk) !void { const c = &d.config; const m = d.target; const n: usize = c.block; + const rows: usize = blocks.len * n; const h: usize = c.hidden; - const qw: usize = c.heads * 128; - const kvw: usize = c.kv_heads * 128; - const ids = d.buf("ids").slice(u32, max_block); - ids[0] = pending; - @memset(ids[1..n], c.noise); - d.buf("seq").slice(u32, 16)[0] = pending; + var pendings: [batch.max_blocks]u32 = undefined; + for (blocks, 0..) |k, s| pendings[s] = k.pending; + batch.fillIds(d.buf("ids").slice(u32, rows), pendings[0..blocks.len], n, c.noise); + const seq = d.buf("seq").slice(u32, batch.max_blocks * 16); + for (blocks, 0..) |k, s| seq[batch.seqAt(s)] = k.pending; const E = m.weights.embed; - glue(e, m.pipe(.embed), MArgs{ .rows = @intCast(n), .width = c.hidden, .bits = E.bits, .group = @intCast(E.group) }, &.{ b(d.buf("ids")), bo(E.w, E.w_off), bo(E.scales, E.s_off), bo(E.biases, E.b_off), A, b(d.buf("resid")) }, .{ (h + 255) / 256, n, 1 }, .{ 256, 1, 1 }); - const nm = MArgs{ .rows = @intCast(n), .width = c.hidden, .eps = c.eps }; - glue(e, m.pipe(.norm), nm, &.{ b(d.buf("resid")), t(d.w.layers[0].in_norm), A, b(d.buf("x")) }, .{ n, 1, 1 }, .{ 256, 1, 1 }); - const lo = @max((anchor + 1) -| c.window, l.from); - const hi = anchor + n; - const first = lo / 128; - const blocks = (hi - 1) / 128 - first + 1; + glue(e, m.pipe(.embed), MArgs{ .rows = @intCast(rows), .width = c.hidden, .bits = E.bits, .group = @intCast(E.group) }, &.{ b(d.buf("ids")), bo(E.w, E.w_off), bo(E.scales, E.s_off), bo(E.biases, E.b_off), A, b(d.buf("resid")) }, .{ (h + 255) / 256, rows, 1 }, .{ 256, 1, 1 }); + const nm = MArgs{ .rows = @intCast(rows), .width = c.hidden, .eps = c.eps }; + glue(e, m.pipe(.norm), nm, &.{ b(d.buf("resid")), t(d.w.layers[0].in_norm), A, b(d.buf("x")) }, .{ rows, 1, 1 }, .{ 256, 1, 1 }); for (0..c.layers) |i| { const L = &d.w.layers[i]; - try d.project(e, L.qkv, b(d.buf("x")), b(d.buf("qkv")), n); - const pa = PArgs{ .rows = @intCast(n), .heads = c.heads, .kv_heads = c.kv_heads, .pos0 = @intCast(anchor), .rotary = c.rotary, .stride = @intCast(qw + 2 * kvw), .q_off = 0, .k_off = @intCast(qw), .v_off = @intCast(qw + kvw), .ring = c.ring(), .eps = c.eps, .theta = c.theta }; - glue(e, d.pipe(.prep), pa, &.{ b(d.buf("qkv")), t(L.q_norm), t(L.k_norm), A, b(d.buf("q")), b(l.k[i]), b(l.v[i]) }, .{ c.heads + c.kv_heads, n, 1 }, .{ 32, 1, 1 }); - const va = VArgs{ .rows = @intCast(n), .pos0 = @intCast(anchor), .heads = c.heads, .groups = c.kv_heads, .blocks = @intCast(blocks), .first = @intCast(first), .hi = @intCast(hi), .window = c.window, .ring = c.ring(), .scale = 1.0 / @sqrt(128.0) }; - glue(e, d.pipe(.vec), va, &.{ b(d.buf("q")), b(l.k[i]), b(l.v[i]), A, b(d.buf("pm")), b(d.buf("pl")), b(d.buf("po")) }, .{ c.kv_heads, n, blocks }, .{ 32, c.heads / c.kv_heads, 1 }); - const ma = extern struct { rows: u32, pos: u32, heads: u32, groups: u32, topk: u32, scale: f32, sel: u32, all: u32 }{ .rows = @intCast(n), .pos = 0, .heads = c.heads, .groups = c.kv_heads, .topk = @intCast(blocks), .scale = 0, .sel = 0, .all = 0 }; - glue(e, m.pipe(.merge_vec), ma, &.{ b(d.buf("pm")), b(d.buf("pl")), b(d.buf("po")), A, b(d.buf("attn")) }, .{ c.heads, n, 1 }, .{ 32, 1, 1 }); - try d.project(e, L.o, b(d.buf("attn")), b(d.buf("y")), n); - glue(e, m.pipe(.add_norm), nm, &.{ b(d.buf("resid")), b(d.buf("y")), t(L.post_norm), A, b(d.buf("x")) }, .{ n, 1, 1 }, .{ 256, 1, 1 }); - try d.project(e, L.gu, b(d.buf("x")), b(d.buf("gu")), n); - const act = MArgs{ .rows = @intCast(n), .width = c.ffn, .stride = 2 * c.ffn, .alpha = c.alpha, .limit = c.limit }; + try d.project(e, L.qkv, b(d.buf("x")), b(d.buf("qkv")), rows); + for (blocks, 0..) |k, s| d.attend(e, k, i, batch.row(s, n)); + try d.project(e, L.o, b(d.buf("attn")), b(d.buf("y")), rows); + glue(e, m.pipe(.add_norm), nm, &.{ b(d.buf("resid")), b(d.buf("y")), t(L.post_norm), A, b(d.buf("x")) }, .{ rows, 1, 1 }, .{ 256, 1, 1 }); + try d.project(e, L.gu, b(d.buf("x")), b(d.buf("gu")), rows); + const act = MArgs{ .rows = @intCast(rows), .width = c.ffn, .stride = 2 * c.ffn, .alpha = c.alpha, .limit = c.limit }; e.setPipeline(m.pipe(.swiglu)); e.setBuffer(d.buf("gu"), 0, 0); e.setValue(act, 1); e.setBuffer(d.buf("act"), 0, 2); - e.dispatchThreads(mtl.Size.of(c.ffn, n, 1), mtl.Size.of(256, 1, 1)); - try d.project(e, L.down, b(d.buf("act")), b(d.buf("y")), n); + e.dispatchThreads(mtl.Size.of(c.ffn, rows, 1), mtl.Size.of(256, 1, 1)); + try d.project(e, L.down, b(d.buf("act")), b(d.buf("y")), rows); const next = if (i + 1 < c.layers) d.w.layers[i + 1].in_norm else d.w.norm; - glue(e, m.pipe(.add_norm), nm, &.{ b(d.buf("resid")), b(d.buf("y")), t(next), A, b(d.buf("x")) }, .{ n, 1, 1 }, .{ 256, 1, 1 }); + glue(e, m.pipe(.add_norm), nm, &.{ b(d.buf("resid")), b(d.buf("y")), t(next), A, b(d.buf("x")) }, .{ rows, 1, 1 }, .{ 256, 1, 1 }); } - try d.project(e, m.weights.head, b(d.buf("x")), b(d.buf("logits")), n); + try d.project(e, m.weights.head, b(d.buf("x")), b(d.buf("logits")), rows); const vocab: u32 = m.config.vocab; const groups: u32 = (vocab + 255) / 256; const w2 = d.w.w2; - for (0..n) |j| { - const sa = extern struct { vocab: u32, rank: u32, step: u32 }{ .vocab = vocab, .rank = c.rank, .step = @intCast(j) }; - glue(e, d.pipe(.markov_step), sa, &.{ b(d.buf("logits")), t(d.w.w1), bo(w2.w, w2.w_off), bo(w2.scales, w2.s_off), bo(w2.biases, w2.b_off), b(d.buf("seq")), A, b(d.buf("best")), b(d.buf("best_id")) }, .{ groups, 1, 1 }, .{ 256, 1, 1 }); - glue(e, d.pipe(.markov_pick), [2]u32{ groups, @intCast(j) }, &.{ b(d.buf("best")), b(d.buf("best_id")), A, b(d.buf("seq")) }, .{ 1, 1, 1 }, .{ 1024, 1, 1 }); + for (0..blocks.len) |s| { // a block's steps read its logits and write its sequence; best is reused block after block + const logits = bo(d.buf("logits"), batch.row(s, n) * vocab * 2); + const own = bo(d.buf("seq"), batch.seqAt(s) * 4); + for (0..n) |j| { + const sa = extern struct { vocab: u32, rank: u32, step: u32 }{ .vocab = vocab, .rank = c.rank, .step = @intCast(j) }; + glue(e, d.pipe(.markov_step), sa, &.{ logits, t(d.w.w1), bo(w2.w, w2.w_off), bo(w2.scales, w2.s_off), bo(w2.biases, w2.b_off), own, A, b(d.buf("best")), b(d.buf("best_id")) }, .{ groups, 1, 1 }, .{ 256, 1, 1 }); + glue(e, d.pipe(.markov_pick), [2]u32{ groups, @intCast(j) }, &.{ b(d.buf("best")), b(d.buf("best_id")), A, own }, .{ 1, 1, 1 }, .{ 1024, 1, 1 }); + } } } - /// Each stream's `depth` drafts after `pending` at `position`: a whole block each (its rows see each other). + /// Layer `i`'s attention for one block at row `row` of the pass: its q and k/v into its lane, then its keys. + fn attend(d: *const Drafter, e: mtl.ComputeEncoder, k: Blk, i: usize, row: usize) void { + const c = &d.config; + const m = d.target; + const l = k.lane; + const L = &d.w.layers[i]; + const n: usize = c.block; + const qw: usize = c.heads * 128; + const kvw: usize = c.kv_heads * 128; + const lo = @max((k.anchor + 1) -| c.window, l.from); + const hi = k.anchor + n; + const first = lo / 128; + const blocks = (hi - 1) / 128 - first + 1; + const pa = PArgs{ .rows = @intCast(n), .heads = c.heads, .kv_heads = c.kv_heads, .pos0 = @intCast(k.anchor), .rotary = c.rotary, .stride = @intCast(qw + 2 * kvw), .q_off = 0, .k_off = @intCast(qw), .v_off = @intCast(qw + kvw), .ring = c.ring(), .eps = c.eps, .theta = c.theta }; + const q = bo(d.buf("q"), row * qw * 2); + glue(e, d.pipe(.prep), pa, &.{ bo(d.buf("qkv"), row * (qw + 2 * kvw) * 2), t(L.q_norm), t(L.k_norm), A, q, b(l.k[i]), b(l.v[i]) }, .{ c.heads + c.kv_heads, n, 1 }, .{ 32, 1, 1 }); + const va = VArgs{ .rows = @intCast(n), .pos0 = @intCast(k.anchor), .heads = c.heads, .groups = c.kv_heads, .blocks = @intCast(blocks), .first = @intCast(first), .hi = @intCast(hi), .window = c.window, .ring = c.ring(), .scale = 1.0 / @sqrt(128.0) }; + glue(e, d.pipe(.vec), va, &.{ q, b(l.k[i]), b(l.v[i]), A, b(d.buf("pm")), b(d.buf("pl")), b(d.buf("po")) }, .{ c.kv_heads, n, blocks }, .{ 32, c.heads / c.kv_heads, 1 }); + const ma = extern struct { rows: u32, pos: u32, heads: u32, groups: u32, topk: u32, scale: f32, sel: u32, all: u32 }{ .rows = @intCast(n), .pos = 0, .heads = c.heads, .groups = c.kv_heads, .topk = @intCast(blocks), .scale = 0, .sel = 0, .all = 0 }; + glue(e, m.pipe(.merge_vec), ma, &.{ b(d.buf("pm")), b(d.buf("pl")), b(d.buf("po")), A, bo(d.buf("attn"), row * qw * 2) }, .{ c.heads, n, 1 }, .{ 32, 1, 1 }); + } + + /// Each stream's `depth` drafts after `pending` at `position`: a whole block each, stacked, one wait a pass. fn holdFn(ptr: *anyopaque, items: []const dr.Hold) anyerror!void { const d = cast(ptr); const c = &d.config; - for (items) |it| { - const l = d.lanes.get(it.stream) orelse return error.DraftStreamUnknown; - if (it.depth == 0 or it.depth > c.block or it.position == 0) return error.DraftDepth; - const anchor = it.position - 1; - if (l.end != anchor) return error.DraftContextGap; + try d.settle(); + var at: usize = 0; + while (at < items.len) { + const count = batch.take(items.len - at); + const pass = items[at..][0..count]; + var blocks: [batch.max_blocks]Blk = undefined; + for (pass, blocks[0..count]) |it, *k| { + const l = d.lanes.get(it.stream) orelse return error.DraftStreamUnknown; + if (it.depth == 0 or it.depth > c.block or it.position == 0) return error.DraftDepth; + const anchor = it.position - 1; + if (l.end != anchor) return error.DraftContextGap; + k.* = .{ .lane = l, .pending = it.pending, .anchor = anchor }; + } const pool = mtl.objc.Pool.push(); defer pool.pop(); const cb = d.target.queue.commandBuffer(); const e = cb.compute(.serial); - try d.encodeBlock(e, l, it.pending, anchor); + try d.encodeBlocks(e, blocks[0..count]); e.end(); cb.commit(); cb.wait(); if (cb.failure()) |msg| return failed(msg); - const seq = d.buf("seq").slice(u32, 16); - for (seq[1..][0..it.depth], l.held[0..it.depth]) |x, *y| { - if (x >= d.target.config.vocab) return error.DraftNonfinite; - y.* = x; + const seq = d.buf("seq").slice(u32, batch.max_blocks * 16); + for (pass, 0..) |it, s| { + const l = d.lanes.get(it.stream).?; + for (seq[batch.seqAt(s) + 1 ..][0..it.depth], l.held[0..it.depth]) |x, *y| { + if (x >= d.target.config.vocab) return error.DraftNonfinite; + y.* = x; + } + l.held_len = it.depth; } - l.held_len = it.depth; + at += count; } } @@ -484,7 +530,7 @@ pub const Drafter = struct { defer pool.pop(); const cb = d.target.queue.commandBuffer(); const e = cb.compute(.serial); - try d.encodeBlock(e, l, 2, 0); + try d.encodeBlocks(e, &.{.{ .lane = l, .pending = 2, .anchor = 0 }}); e.end(); cb.commit(); cb.wait(); diff --git a/zig/src/families/minimax_m3/hold_batch.zig b/zig/src/families/minimax_m3/hold_batch.zig new file mode 100644 index 00000000000..4ba8a9a24ad --- /dev/null +++ b/zig/src/families/minimax_m3/hold_batch.zig @@ -0,0 +1,60 @@ +//! A MiniMax-M3 drafter's hold as one pass over several streams' blocks: each block stacked at its row offset. +const std = @import("std"); + +/// Blocks a pass takes: the default 8 streams' 64 rows, one 64-row tile of the tensor product; more take more passes. +pub const max_blocks = 8; + +/// Items the next pass takes of `left`. +pub fn take(left: usize) usize { + return @min(left, max_blocks); +} + +/// The first row of the pass's block `slot`: per-row work runs over every block at once, the rest at this offset. +pub fn row(slot: usize, block: usize) usize { + return slot * block; +} + +/// Each block's ids: its pending token, then `fill` (the mask or noise token) through its block's rows. +pub fn fillIds(ids: []u32, pendings: []const u32, block: usize, fill: u32) void { + for (pendings, 0..) |p, s| { + const at = row(s, block); + ids[at] = p; + @memset(ids[at + 1 ..][0 .. block - 1], fill); + } +} + +/// A block's sequence slot: 16 words each, its pending token first, the drafts after (the walk's or the steps' output). +pub fn seqAt(slot: usize) usize { + return slot * 16; +} + +test "MiniMax-M3 hold batch: two streams' ids are the two single holds' ids, block after block" { + var two: [2 * 8]u32 = undefined; + fillIds(&two, &.{ 11, 22 }, 8, 7); + var a: [8]u32 = undefined; + var b: [8]u32 = undefined; + fillIds(&a, &.{11}, 8, 7); + fillIds(&b, &.{22}, 8, 7); + try std.testing.expectEqualSlices(u32, &a, two[0..8]); + try std.testing.expectEqualSlices(u32, &b, two[8..16]); + // a shorter DSpark block stacks the same way + var three: [3 * 5]u32 = undefined; + fillIds(&three, &.{ 1, 2, 3 }, 5, 9); + try std.testing.expectEqualSlices(u32, &.{ 1, 9, 9, 9, 9, 2, 9, 9, 9, 9, 3, 9, 9, 9, 9 }, &three); +} + +test "MiniMax-M3 hold batch: blocks and sequences never overlap, and passes take eight streams at a time" { + for (0..max_blocks - 1) |s| { + try std.testing.expectEqual(row(s, 8) + 8, row(s + 1, 8)); + try std.testing.expectEqual(seqAt(s) + 16, seqAt(s + 1)); + } + try std.testing.expectEqual(@as(usize, 64), row(max_blocks, 8)); + var left: usize = 17; + var passes: [3]usize = undefined; + var n: usize = 0; + while (left > 0) : (n += 1) { + passes[n] = take(left); + left -= passes[n]; + } + try std.testing.expectEqualSlices(usize, &.{ 8, 8, 1 }, passes[0..n]); +} diff --git a/zig/src/families/minimax_m3/prefill_steps.zig b/zig/src/families/minimax_m3/prefill_steps.zig new file mode 100644 index 00000000000..02dbde4a1fd --- /dev/null +++ b/zig/src/families/minimax_m3/prefill_steps.zig @@ -0,0 +1,52 @@ +//! MiniMax-M3 Metal's prompt pass a chunk a call (#3021): today's cuts, a chunk a step, marks after the absorb. +const std = @import("std"); +const lanes = @import("lanes"); +const Stream = lanes.Stream; + +/// A chunk from `at`: `rows` at most, cut at a planned chunk start and a kept mark inside it (main's feed loop body). +pub fn chunkEnd(len: usize, at: usize, rows: usize, chunks: []const u32, marks: []const u32) usize { + var end = @min(len, at + rows); + for (chunks) |x| if (x > at and x < end) { + end = x; + }; + for (marks) |x| if (x > at and x < end) { + end = x; + }; + 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, 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); + try r.run(s, f.at, end); + s.fill_at.store(@intCast(end), .monotonic); // the forward waits on its command buffer: these rows are in + 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; +} + +/// The host cancels between chunks: the state at the pass's last chunk end is kept (no prompt work runs). +pub fn cancel(s: *Stream, f: ?Fill) void { + if (f) |x| s.keepInterruptedPrefill(@intCast(x.at)); +} + +/// Rows a scratch holds: `rows` from `start`, written at forward `gen` (until the next forward rewrites it). +pub const Held = struct { start: u64 = 0, rows: usize = 0, gen: u64 = 0 }; + +/// Whether `h` holds [start, start + count) and no forward has rewritten the scratch since (its gen is `now`). +pub fn holds(h: Held, now: u64, start: u64, count: u32) bool { + return h.gen == now and 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/minimax_m3/prefill_steps_test.zig b/zig/src/families/minimax_m3/prefill_steps_test.zig new file mode 100644 index 00000000000..40fd98fc7bb --- /dev/null +++ b/zig/src/families/minimax_m3/prefill_steps_test.zig @@ -0,0 +1,292 @@ +//! MiniMax-M3 Metal's stepped prompt pass on recording fakes: today's cuts, decodes between chunks, each 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 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 feed loop (backend.zig before #3021), copied as they were: rows from `base`, cuts inside a chunk. +fn mainCuts(a: std.mem.Allocator, total: usize, base: usize, rows: usize, planned: []const u32, kept_marks: []const u32) ![][2]usize { + var out: std.ArrayList([2]usize) = .empty; + const n = total - base; // feed's ids: the prompt past the restored state + var at: usize = 0; + while (at < n) { + var end = @min(n, at + rows); + for (planned) |x| if (x > base + at and x < base + end) { + end = x - base; + }; + for (kept_marks) |x| if (x > base + at and x < base + end) { + end = x - base; + }; + try out.append(a, .{ base + at, base + end }); + at = end; + } + return out.toOwnedSlice(a); +} + +/// Records each chunk run and each kept mark, as prompt_pass.zig's 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 29-token prompt at an 8-row cap: planned starts at 3 and 20, a kept mark at 11. +const len = 29; +const cap = 8; +const chunks = [_]u32{ 3, 20 }; +const marks = [_]u32{11}; + +fn stream(prompt: []const u32, id: []const u8) !lanes.Stream { + return lanes.Stream.init(gpa, .{ .id = id, .prompt = prompt, .max_new = 4, .chunks = &chunks, .reuse = .{ .marks = &marks } }); +} + +test "MiniMax-M3 Metal steps: one call runs one chunk at today's cut, and the calls' chunks are the whole loop's" { + var ids: [len]u32 = undefined; + for (&ids, 0..) |*x, i| x.* = @intCast(i % 97 + 3); + const want = try mainCuts(gpa, len, 0, cap, &chunks, &marks); + defer gpa.free(want); + try t.expectEqualSlices([2]usize, &.{ .{ 0, 3 }, .{ 3, 11 }, .{ 11, 19 }, .{ 19, 20 }, .{ 20, 28 }, .{ 28, 29 } }, want); + for ([_]bool{ false, true }) |later| { // the whole pass (prompt_pass.whole) 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, cap, 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 11: kept at once by the whole pass, at the next call's start by a drafting stream + if (i == 1) try t.expectEqual(@as(usize, if (later) 2 else 3), log.items.len); + } + try t.expectEqual(@as(usize, 7), log.items.len); + try t.expectEqual(Event{ .keep = 11 }, log.items[2]); // before the chunk after it, in both + } + // a pass resumed from a kept state at 11 cuts as main's loop does from there + const resumed = try mainCuts(gpa, len, 11, cap, &chunks, &marks); + 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 = 11 }; + while (!try steps.step(Rec{ .log = &log }, &s, &f, cap, 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); +} + +test "MiniMax-M3 Metal steps: a cancel between chunks keeps the state at the last chunk's end" { + var ids: [len]u32 = undefined; + for (&ids, 0..) |*x, i| x.* = @intCast(i + 3); + var s = try lanes.Stream.init(gpa, .{ .id = "x", .prompt = &ids, .max_new = 4, .chunks = &chunks, .reuse = .{ .marks = &marks } }); + defer s.deinit(gpa); + var log: std.ArrayList(Event) = .empty; + defer log.deinit(gpa); + const Hook = struct { + var kept: ?u32 = null; + fn at(_: *anyopaque, _: *lanes.Stream, row: u32) void { + kept = row; + } + }; + var dummy: u8 = 0; + s.reuse.hook = .{ .ptr = &dummy, .at = Hook.at }; + var f: steps.Fill = .{ .at = 0 }; + _ = try steps.step(Rec{ .log = &log }, &s, &f, cap, false); + _ = try steps.step(Rec{ .log = &log }, &s, &f, cap, false); + _ = try steps.step(Rec{ .log = &log }, &s, &f, cap, false); + steps.cancel(&s, f); + try t.expectEqual(@as(?u32, 19), Hook.kept); // rows 0..19 are in; no chunk ran for the cancel + var n: usize = 0; + for (log.items) |e| n += @intFromBool(e == .chunk); + try t.expectEqual(@as(usize, 3), n); + Hook.kept = null; + steps.cancel(&s, null); // no pass in progress: nothing kept + try t.expectEqual(@as(?u32, null), Hook.kept); +} + +/// The lanes fake with MiniMax-M3's stepping in front: its prompt passes a chunk a call at `rows` (4 here), logged. +const Mm = 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, + gen: u64 = 0, // Metal.gen: every forward, a prompt chunk's or a decode's, rewrites a scratch + vt: be.Backend.VTable = undefined, + + var current: *Mm = undefined; + const rows = 4; + + fn init(x: *Mm) 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: *Mm) 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.gen += 1; + try x.held.put(gpa, s, .{ .start = at, .rows = end - at, .gen = x.gen }); // the cache's chunk_tap + 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, 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 { + current.gen += 1; + 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 { + current.gen += 1; + for (windows) |w| try current.log.append(gpa, .{ .decode = w.stream.id[0] }); + return current.inner.vtable.verify(ptr, windows, out); + } + + /// featuresFn's stepped rule: the latest chunk's rows, while no forward has rewritten their 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.MiniMaxTapsNotHeld; + if (!steps.holds(h, x.gen, start, count)) return error.MiniMaxTapsNotHeld; + return .{ .buffer = h.start, .rows = count, .row_bytes = 2, .space = .host, .dtype = .bf16 }; + } +}; + +test "MiniMax-M3 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 mm: Mm = .{ .fake = .{ .gpa = gpa } }; + defer mm.deinit(); + var clock: lanes.fake.FixedClock = .{}; + var engine = lanes.Engine.init(gpa, &cfg, mm.init(), clock.clock()); + defer engine.deinit(); + try t.expect(engine.fills()); // the lane host steps this backend's prompts (lane_host_fill.zig) + 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, mm.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 (mm.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 (mm.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(); + // the decodes since rewrote the scratch: b's last chunk's rows are no longer served (featuresFn's gen rule) + try t.expect(!steps.holds(mm.held.get(&b).?, mm.gen, 8, 4)); +} + +/// 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 "MiniMax-M3 Metal steps: a drafter absorbs every chunk's tapped rows, and a mark keeps after its chunk's absorb" { + var mm: Mm = .{ .fake = .{ .gpa = gpa } }; + defer mm.deinit(); + var head: Head = .{ .log = &mm.log }; + var wrapped = try lanes.drafted.Drafted.init(gpa, mm.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, mm.log.items.len); + for (want, mm.log.items) |w, g| try t.expectEqual(w, g); +} diff --git a/zig/src/families/minimax_m3/prompt_pass.zig b/zig/src/families/minimax_m3/prompt_pass.zig new file mode 100644 index 00000000000..a46b9dbec1e --- /dev/null +++ b/zig/src/families/minimax_m3/prompt_pass.zig @@ -0,0 +1,181 @@ +//! MiniMax-M3 Metal's prompt pass, whole or a chunk a call (#3021), moved out of backend.zig: main's cuts and taps. +const std = @import("std"); +const mtl = @import("metal"); +const lanes = @import("lanes"); +const st = @import("state.zig"); +const fwd = @import("forward.zig"); +const snapshot = @import("snapshot.zig"); +const steps = @import("prefill_steps.zig"); +const Metal = @import("backend.zig").Metal; + +/// A pass in progress: its row and late mark, and the image rows its chunks read, made once at its first call. +pub const Pass = struct { + fill: steps.Fill, + rows: ?mtl.Buffer = null, + spans: std.ArrayList(fwd.Span) = .empty, + + pub fn deinit(p: *Pass, gpa: std.mem.Allocator) void { + if (p.rows) |b| b.deinit(); + p.spans.deinit(gpa); + } +}; + +/// The whole pass (prefill, and prefill_features with `self.sink` set): every chunk, marks kept as each lands. +pub fn whole(self: *Metal, stream: *lanes.Stream) !void { + try self.drain(); + const p = try opening(self, stream); + errdefer drop(self, stream); + const r: Run = .{ .m = self, .cache = try self.cacheOf(stream), .spans = p.spans.items, .later = false }; + while (!try steps.step(r, stream, &p.fill, st.prompt_rows, false)) {} + forget(self, stream); +} + +/// One chunk a call at the whole pass's cuts (`max_rows` is never set: this family declares no chunk_invariant). +pub fn step(self: *Metal, stream: *lanes.Stream) !bool { + try self.drain(); // other streams' steps in flight land before this chunk's forward + // 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.scratch.taps != null; + const p = self.passes.getPtr(stream) orelse try opening(self, stream); + errdefer drop(self, stream); + const r: Run = .{ .m = self, .cache = try self.cacheOf(stream), .spans = p.spans.items, .later = later }; + const done = try steps.step(r, stream, &p.fill, st.prompt_rows, later); + if (done) forget(self, stream); + return done; +} + +/// The host cancels between chunks: the last chunk's state is kept (its forward has waited; no prompt work runs). +pub fn cancel(self: *Metal, stream: *lanes.Stream) !void { + try self.drain(); // the kept state is copied on the GPU, after any step in flight + steps.cancel(stream, if (self.passes.get(stream)) |p| p.fill else null); +} + +/// A stream that leaves: its pass, if any, goes with it. +pub fn forget(self: *Metal, stream: *lanes.Stream) void { + if (self.passes.fetchRemove(stream)) |kv| { + var p = kv.value; + p.deinit(self.gpa); + } +} + +/// Whether a chunk's rows `tap`, written at forward `gen`, hold [start, start + count) at forward `now`. +pub fn within(tap: st.Tap, gen: u64, now: u64, start: u64, count: u32) bool { + return tap.buf != null and steps.holds(.{ .start = tap.start, .rows = tap.rows, .gen = gen }, now, start, count); +} + +/// A pass that failed: its record and its cache go, as the whole pass's error left them. +fn drop(self: *Metal, stream: *lanes.Stream) void { + forget(self, stream); + if (self.caches.fetchRemove(stream)) |entry| { + self.held -= st.cacheBytes(&self.model.config, entry.value.capacity); + entry.value.deinit(); + self.gpa.destroy(entry.value); + } +} + +/// One chunk's work for `steps.step`: the forward, the drafter's rows (a sink, or `later` via featuresFn), marks. +const Run = struct { + m: *Metal, + cache: *st.Cache, + spans: []const fwd.Span, + later: bool, + + pub fn run(r: Run, stream: *lanes.Stream, at: usize, end: usize) !void { + const self = r.m; + const cache = r.cache; + const ids = stream.prompt(); + const s = if (end - at > st.batch_rows) &self.prompt else &self.scratch; + const taps = s.taps; + try fwd.run(self.model, s, cache, ids[at..end], .{ .taps = if (taps) |x| fwd.b(x) else null, .images = r.spans }); + self.gen +%= 1; + if (taps) |x| { + const width = self.tapBytes(); + if (self.sink) |k| try k.take(k.ptr, stream, .{ .buffer = @intFromPtr(x.id), .rows = @intCast(end - at), .row_bytes = @intCast(width), .space = .device, .dtype = .bf16 }, cache.len); + if (r.later) cache.chunk_tap = .{ .tap = .{ .buf = x, .start = cache.len, .rows = end - at }, .gen = self.gen }; + if (end == ids.len) { // the prompt's last row, kept for the first draft + if (cache.last_tap == null) cache.last_tap = try self.model.device.buffer(width, mtl.ResourceOptions.shared); + @memcpy(cache.last_tap.?.slice(u8, width), x.slice(u8, (end - at) * width)[(end - at - 1) * width ..][0..width]); + cache.tap = .{ .buf = cache.last_tap, .start = cache.len + (end - at) - 1, .rows = 1 }; + } + } + cache.len += end - at; + lanes.prefill_widths.completed(self.gpa, stream, end - at); + } + + pub fn keep(_: Run, stream: *lanes.Stream, at: u32) void { + if (stream.reuse.hook) |k| k.at(k.ptr, stream, at); + } +}; + +/// main's prefillFn up to its feed: the budget, the cache, a restored state and the images; the pass's record. +fn opening(self: *Metal, stream: *lanes.Stream) !*Pass { + const ids = stream.prompt(); + if (ids.len == 0 or ids.len + stream.max_new > self.options.capacity or self.caches.contains(stream)) return error.InvalidMiniMaxPrompt; + const capacity = ids.len + stream.max_new + 1; + const need = st.cacheBytes(&self.model.config, capacity); + if (self.held + need > self.options.budget) { + std.log.warn("minimax_m3: a {d}-token stream needs {d:.1} GiB of caches; {d:.1} of {d:.1} GiB are held", .{ capacity, gib(need), gib(self.held), gib(self.options.budget) }); + return error.MiniMaxCachesFull; + } + self.held += need; + errdefer self.held -= need; + if (stream.reuse.saved) |saved| { // a state the stream cannot hold beside its caches: freed now, no restore + const snap: *snapshot.Snap = @ptrCast(@alignCast(saved)); + if (self.held + snap.bytes > self.options.budget) snap.free(); + } + // kept states give way first + if (self.room) |r| r.fit(r.ctx, self.options.budget - self.held, stream.reuse.saved, ids); + const cache = try self.createCache(capacity); + errdefer self.gpa.destroy(cache); + errdefer cache.deinit(); + try self.caches.put(self.gpa, stream, cache); // a mark's save finds it there + errdefer _ = self.caches.remove(stream); + stream.cached = 0; + if (stream.reuse.saved) |saved| { // a kept state of this prompt's prefix: the pass starts there + const snap: *const snapshot.Snap = @ptrCast(@alignCast(saved)); + if (snap.at < ids.len) { + if (snapshot.restore(self.model.queue, &self.model.config, snap, cache)) stream.cached = snap.at else |_| stream.reuse_failed = true; + } else stream.reuse_failed = true; + } + var p: Pass = .{ .fill = .{ .at = cache.len } }; + errdefer p.deinit(self.gpa); + p.rows = try encodeImages(self, stream, cache.len, &p.spans); + try self.passes.put(self.gpa, stream, p); + stream.fill_at.store(@intCast(cache.len), .monotonic); // what the restore kept: 0 when none + return self.passes.getPtr(stream).?; +} + +fn gib(bytes: u64) f64 { + return @as(f64, @floatFromInt(bytes)) / (1 << 30); +} + +/// The tower's rows of the stream's images past `from` (one before it is in the restored state), a span each. +fn encodeImages(self: *Metal, stream: *const lanes.Stream, from: usize, spans: *std.ArrayList(fwd.Span)) !?mtl.Buffer { + var total: usize = 0; + for (stream.images) |im| { + if (im.at + im.tokens > stream.prompt().len or im.tokens * 4 != im.gh * im.gw) return error.InvalidMiniMaxImage; + if (im.at + im.tokens > from) total += im.tokens; + } + if (total == 0) return null; + const v = self.model.vision orelse return error.NoMiniMaxVision; + const width: usize = self.model.config.hidden; + const buf = try self.model.device.buffer(total * width * 2, mtl.ResourceOptions.private | mtl.ResourceOptions.untracked); + errdefer buf.deinit(); + var done: usize = 0; + for (stream.images) |im| { // one command buffer an image: the tower's host-written tables are one image's + if (im.at + im.tokens <= from) continue; + const span: fwd.Span = .{ .at = im.at, .n = im.tokens, .rows = .{ .buf = buf, .off = done * width * 2 } }; + const cb = self.model.queue.commandBuffer(); + const e = cb.compute(.serial); + try v.encode(e, im.pixels, im.gh, im.gw, span.rows); + e.end(); + cb.commit(); + cb.wait(); + if (cb.failure()) |msg| { + std.log.err("minimax_m3: the image tower failed: {s}", .{msg}); + return error.GpuFailed; + } + try spans.append(self.gpa, span); + done += im.tokens; + } + return buf; +} diff --git a/zig/src/families/minimax_m3/state.zig b/zig/src/families/minimax_m3/state.zig index a6ee87a5296..5bd1b6cb161 100644 --- a/zig/src/families/minimax_m3/state.zig +++ b/zig/src/families/minimax_m3/state.zig @@ -34,6 +34,8 @@ pub const Cache = struct { tap: Tap = .{}, /// The prompt's last tapped row, kept for the first draft (the prompt scratch serves the next pass). last_tap: ?mtl.Buffer = null, + /// A stepped prompt pass's latest chunk's tapped rows in a scratch, written at forward `gen` (#3021). + chunk_tap: ?struct { tap: Tap, gen: u64 } = null, layer_at: [cfg.max_layers]usize = @splat(0), capacity: usize, len: usize = 0, diff --git a/zig/src/families/muse_spark/forward.zig b/zig/src/families/muse_spark/forward.zig index da1a7921f14..d2a802e29e8 100644 --- a/zig/src/families/muse_spark/forward.zig +++ b/zig/src/families/muse_spark/forward.zig @@ -133,6 +133,15 @@ pub const Model = struct { h_erow: []u16 = &.{}, // host staging of the window's embedding rows dr: ?*dflash2.Drafter = null, // fed inside run: taps after its layers, the context update after the last layer + const CacheLists = struct { kc: []u64, vc: []u64 }; + + fn cacheLists(gpa: std.mem.Allocator, layers: usize) !CacheLists { + const kc = try gpa.alloc(u64, layers); + errdefer gpa.free(kc); + const vc = try gpa.alloc(u64, layers); + return .{ .kc = kc, .vc = vc }; + } + /// fp16 K/V caches: full layers [slots, context, HK, 64], sliding layers rings of ringSize rows. pub fn init(gpa: std.mem.Allocator, d: *const cuda.Driver, w: *const Weights, k3: *const exl3.Kernels, comm: ?tp.Collective, context: usize, rows: usize, slots: usize, s: Stream) !Model { const cfg = w.cfg; @@ -184,8 +193,11 @@ pub const Model = struct { const L = w.layers.len; const HK = cfg.kv_heads; const hd = cfg.head_dim; - m.kc = try gpa.alloc(u64, L); - m.vc = try gpa.alloc(u64, L); + const lists = try cacheLists(gpa, L); + m.kc = lists.kc; + errdefer gpa.free(m.kc); + m.vc = lists.vc; + errdefer gpa.free(m.vc); for (0..L) |i| { const n = if (cfg.full[i]) context else m.ring; m.kc[i] = try ar.zeros(slots * n * HK * hd * 2); @@ -261,6 +273,7 @@ pub const Model = struct { b.iota = try ar.upload(std.mem.sliceAsBytes(io_)); } m.h_erow = try gpa.alloc(u16, R * D); + errdefer gpa.free(m.h_erow); const first = w.layers[0].experts; const sz = try exl3.sizes(first, R, cfg.top_k); b.sc = .{ .xg = try ar.zeros(sz.xg), .xu = try ar.zeros(sz.xg), .xd = try ar.zeros(sz.xd), .z = try ar.zeros(sz.z), .y = try ar.zeros(sz.y), .ids = try ar.zeros(sz.ids), .count = try ar.zeros(4), .members = try ar.alloc(sz.members), .rows = R, .slots = cfg.top_k }; @@ -483,3 +496,12 @@ test "ring" { try std.testing.expectEqual(@as(usize, 2176), ringSize(2047, 128)); try std.testing.expectEqual(@as(usize, 2112), ringSize(2047, 1)); } + +test "Muse Spark host cache lists: a refused second list frees the first" { + for (0..2) |fail_at| { + var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{ .fail_index = fail_at }); + const gpa = failing.allocator(); + try std.testing.expectError(error.OutOfMemory, Model.cacheLists(gpa, 4)); + try std.testing.expectEqual(failing.allocated_bytes, failing.freed_bytes); + } +} diff --git a/zig/src/families/nemotron/hip.zig b/zig/src/families/nemotron/hip.zig index 46ee4298c98..87b332d7f66 100644 --- a/zig/src/families/nemotron/hip.zig +++ b/zig/src/families/nemotron/hip.zig @@ -27,6 +27,7 @@ pub const native = @import("hip/native.zig"); test { _ = @import("hip/prompt_test.zig"); + _ = @import("hip/deep_drafts_test.zig"); _ = config; _ = tensors; _ = plan; diff --git a/zig/src/families/nemotron/hip/admit.zig b/zig/src/families/nemotron/hip/admit.zig index 4128a784b87..86082fee3d5 100644 --- a/zig/src/families/nemotron/hip/admit.zig +++ b/zig/src/families/nemotron/hip/admit.zig @@ -22,6 +22,8 @@ pub const Facts = struct { index: []const u8, /// The tensor names of mtp-4bit.safetensors; null when the file is not there (no drafts). mtp: ?[]const []const u8 = null, + /// The quantization the MTP head's file states in its metadata; null: none stated (the stock 4-bit head). + mtp_quantization: ?[]const u8 = null, /// A living-weights file (a lesson Sliding Weights saved) sits beside the shards. living: bool = false, }; @@ -32,6 +34,8 @@ pub const Ask = struct { world: u32 = 1, rank: u32 = 0, window: u64, room: u64, pub const Verdict = struct { config: Config, mtp: bool, + /// The MTP head's own width, as its file states. + head: config.Width = .{}, weights: u64, token: u64, stream: u64, @@ -199,22 +203,32 @@ pub fn checkpoint(a: std.mem.Allocator, f: Facts, problem: *[]const u8) Refused! var head: std.StringHashMapUnmanaged(void) = .empty; for (list) |n| head.put(a, n, {}) catch return error.Refused; try names(a, &head, &c, true, tensors.mtp_file, problem); - if (c.bits != 4 or c.group_size != 64) return refuse( - a, - problem, - "{s} sits beside a model stored {d}-bit in groups of {d}: Nemotron on HIP reads the MTP head beside " ++ - "a model stored 4-bit in groups of 64 only; move {s} out of the folder to serve it without drafts", - .{ tensors.mtp_file, c.bits, c.group_size, tensors.mtp_file }, - ); } return c; } +/// The MTP head's width from its file's metadata, refused by name unless the launches read it. +fn headWidth(a: std.mem.Allocator, f: Facts, problem: *[]const u8) Refused!config.Width { + const w = widths.headOf(a, f.mtp_quantization) catch return refuse( + a, + problem, + "{s} states its quantization as {s}: Nemotron on HIP reads the head as MLX affine bits and group_size", + .{ tensors.mtp_file, f.mtp_quantization orelse "" }, + ); + if (!widths.served(w)) return refuse( + a, + problem, + "{s} is {d}-bit in groups of {d}: Nemotron on HIP reads " ++ widths.served_text, + .{ tensors.mtp_file, w.bits, w.group }, + ); + return w; +} + /// Admits the checkpoint of `f` on rank `ask.rank` of `ask.world` at `ask.window` positions in `ask.room` bytes. pub fn admit(a: std.mem.Allocator, f: Facts, ask: Ask, problem: *[]const u8) Refused!Verdict { const c = try checkpoint(a, f, problem); const mtp = f.mtp != null; - const head: config.Width = .{ .bits = @intCast(c.bits), .group = @intCast(c.group_size) }; + const head = try headWidth(a, f, problem); const want: plan.Head = .{ .mtp = mtp, .drafts = if (mtp) draft_rows else 0, .width = head }; const w = plan.weights(&c, ask.world, .device, want) catch return refuse( @@ -241,6 +255,7 @@ pub fn admit(a: std.mem.Allocator, f: Facts, ask: Ask, problem: *[]const u8) Ref return .{ .config = c, .mtp = mtp, + .head = head, .weights = bytes, .token = token, .stream = stream, @@ -261,305 +276,6 @@ pub fn tooBig(a: std.mem.Allocator, v: Verdict, ask: Ask, problem: *[]const u8) ); } -const testing = std.testing; -const stock_config = @embedFile("../fixtures/config.json"); -const stock_index = @embedFile("../fixtures/index.json"); -const gib: u64 = 1 << 30; - -/// The stock MTP file's names, from the fixture's lines. -fn stockMtp(a: std.mem.Allocator) ![]const []const u8 { - var list: std.ArrayList([]const u8) = .empty; - var it = std.mem.tokenizeAny(u8, @embedFile("../fixtures/mtp_names.txt"), "\n\r "); - while (it.next()) |n| try list.append(a, n); - return list.items; -} - -/// `text` with every `from` replaced by `to`. -fn edit(a: std.mem.Allocator, text: []const u8, from: []const u8, to: []const u8) ![]const u8 { - try testing.expect(std.mem.indexOf(u8, text, from) != null); - return std.mem.replaceOwned(u8, a, text, from, to); -} - -/// The stock config with module `name` at `bits` in groups of `group`. -fn module(a: std.mem.Allocator, name: []const u8, bits: u8, group: u16) ![]const u8 { - const entry = try std.fmt.allocPrint(a, "\"group_size\": 64, \"{s}\": {{\"bits\": {d}, \"group_size\": {d}}},", .{ - name, - bits, - group, - }); - return edit(a, stock_config, "\"group_size\": 64,", entry); -} - -/// admit() must refuse with a reason naming each of `words`. -fn expectRefused(a: std.mem.Allocator, f: Facts, ask: Ask, words: []const []const u8) !void { - var problem: []const u8 = ""; - try testing.expectError(error.Refused, admit(a, f, ask, &problem)); - for (words) |w| if (std.mem.indexOf(u8, problem, w) == null) { - std.debug.print("refusal \"{s}\" does not name \"{s}\"\n", .{ problem, w }); - return error.TestUnexpectedResult; - }; -} - -test "the stock checkpoint and its MTP head are admitted; on one V620 a stream takes the model's window" { - var arena: std.heap.ArenaAllocator = .init(testing.allocator); - defer arena.deinit(); - const a = arena.allocator(); - var problem: []const u8 = ""; - const f: Facts = .{ .config = stock_config, .index = stock_index, .mtp = try stockMtp(a) }; - const one = try admit(a, f, .{ .window = 262144, .room = 30 * gib }, &problem); - try testing.expect(one.fits and one.mtp); - try testing.expectEqual(@as(usize, 52), one.config.layers); - const two = try admit(a, f, .{ .world = 2, .rank = 1, .window = 262144, .room = 30 * gib }, &problem); - try testing.expect(two.fits and two.weights < one.weights / 2); - const lone = try admit( - a, - .{ .config = stock_config, .index = stock_index }, - .{ .window = 4096, .room = 30 * gib }, - &problem, - ); - try testing.expect(!lone.mtp and lone.weights < one.weights); - const small = try admit(a, f, .{ .window = 4096, .room = 16 * gib }, &problem); - try testing.expect(!small.fits); - try testing.expectEqual(error.Refused, tooBig(a, small, .{ .window = 4096, .room = 16 * gib }, &problem)); - try testing.expect(std.mem.indexOf(u8, problem, "16.00 GiB this card grants") != null); -} - -test "uniform 8-bit and mixed 4/5/6/8-bit checkpoints in groups of 64 are admitted, their bytes at their widths" { - var arena: std.heap.ArenaAllocator = .init(testing.allocator); - defer arena.deinit(); - const a = arena.allocator(); - var problem: []const u8 = ""; - const ask: Ask = .{ .window = 4096, .room = 60 * gib }; - const four = try admit(a, .{ .config = stock_config, .index = stock_index }, ask, &problem); - const eight_text = try edit(a, stock_config, "\"bits\": 4", "\"bits\": 8"); - const eight = try admit(a, .{ .config = eight_text, .index = stock_index }, ask, &problem); - try testing.expect(eight.fits and eight.weights > four.weights + four.weights / 2); - var text: []const u8 = stock_config; - for ([_][]const u8{ "backbone.embeddings", "lm_head", "backbone.layers.1.mixer.shared_experts.up_proj" }) |n| { - const entry = try std.fmt.allocPrint(a, "\"group_size\": 64, \"{s}\": {{\"bits\": 8}},", .{n}); - text = try edit(a, text, "\"group_size\": 64,", entry); - } - text = try edit(a, text, "\"group_size\": 64,", "\"group_size\": 64, " ++ - "\"backbone.layers.0.mixer.in_proj\": {\"bits\": 5}, " ++ - "\"backbone.layers.0.mixer.out_proj\": {\"bits\": 6},"); - const mixed = try admit(a, .{ .config = text, .index = stock_index }, ask, &problem); - try testing.expect(mixed.fits and mixed.weights > four.weights and mixed.weights < eight.weights); - try testing.expectEqual(@as(u8, 5), mixed.config.widths[0][0].bits); -} - -test "the MTP head file is refused by name beside a model not stored 4-bit in groups of 64" { - var arena: std.heap.ArenaAllocator = .init(testing.allocator); - defer arena.deinit(); - const a = arena.allocator(); - var problem: []const u8 = ""; - const ask: Ask = .{ .window = 4096, .room = 60 * gib }; - const mtp = try stockMtp(a); - for ([_][]const u8{ "\"bits\": 6", "\"bits\": 8" }, [_][]const u8{ "6-bit", "8-bit" }) |bits, said| { - const text = try edit(a, stock_config, "\"bits\": 4", bits); - _ = try admit(a, .{ .config = text, .index = stock_index }, ask, &problem); - try expectRefused(a, .{ .config = text, .index = stock_index, .mtp = mtp }, ask, &.{ - tensors.mtp_file, - said, - "without drafts", - }); - } - const mixed = try module(a, "lm_head", 8, 64); - const v = try admit(a, .{ .config = mixed, .index = stock_index, .mtp = mtp }, ask, &problem); - try testing.expect(v.mtp and v.fits); -} - -test "altered checkpoints are refused with a reason" { - var arena: std.heap.ArenaAllocator = .init(testing.allocator); - defer arena.deinit(); - const a = arena.allocator(); - const ask: Ask = .{ .window = 4096, .room = 30 * gib }; - const mtp = try stockMtp(a); - const gone = "backbone.layers.7.mixer.A_log"; - try expectRefused( - a, - .{ - .config = stock_config, - .index = try edit(a, stock_index, "\"" ++ gone ++ "\"", "\"backbone.layers.7.mixer.B_log\""), - }, - ask, - &.{gone}, - ); - const scales = "backbone.layers.12.mixer.o_proj.scales"; - try expectRefused( - a, - .{ .config = stock_config, .index = try edit(a, stock_index, "\"" ++ scales ++ "\"", "\"x\"") }, - ask, - &.{ "backbone.layers.12.mixer.o_proj", "Living Weights" }, - ); - try expectRefused( - a, - .{ - .config = stock_config, - .index = try edit(a, stock_index, "\"lm_head.weight\"", "\"lm_head.weight\": \"a\", \"vision.w\""), - }, - ask, - &.{"vision.w"}, - ); - try expectRefused( - a, - .{ .config = try edit(a, stock_config, "\"group_size\": 64", "\"group_size\": 32"), .index = stock_index }, - ask, - &.{ "backbone.embeddings is 4-bit in groups of 32", "groups of 64" }, - ); - const three = try module(a, "backbone.layers.4.mixer.in_proj", 3, 64); - try expectRefused(a, .{ .config = three, .index = stock_index }, ask, &.{ - "backbone.layers.4.mixer.in_proj is 3-bit in groups of 64", - }); - try expectRefused(a, .{ .config = try module(a, "lm_head", 8, 128), .index = stock_index }, ask, &.{ - "lm_head is 8-bit in groups of 128", - }); - try expectRefused( - a, - .{ .config = try module(a, "backbone.layers.1.mixer.switch_mlp.fc1", 2, 64), .index = stock_index }, - ask, - &.{"backbone.layers.1.mixer.switch_mlp.fc1 is 2-bit"}, - ); - try expectRefused( - a, - .{ - .config = try edit(a, stock_config, "\"group_size\": 64,", "\"group_size\": 64, " ++ - "\"backbone.layers.5.mixer.q_proj\": false,"), - .index = stock_index, - }, - ask, - &.{ "backbone.layers.5.mixer.q_proj", "unquantized" }, - ); - try expectRefused( - a, - .{ - .config = stock_config, - .index = try edit(a, stock_index, "\"lm_head.weight\"", "\"lm_head.weight\": \"a\", " ++ - "\"mtp.layers.0.eh_proj.weight\""), - }, - ask, - &.{ "mtp.layers.0.eh_proj.weight", "inside the model's shards", tensors.mtp_file }, - ); - try expectRefused( - a, - .{ - .config = try edit( - a, - stock_config, - "\"quantization\": {", - "\"quantization\": {\"quant_method\": \"modelopt\",", - ), - .index = stock_index, - }, - ask, - &.{ "ModelOpt", "CUDA" }, - ); - try expectRefused( - a, - .{ .config = try edit(a, stock_config, "\"mode\": \"affine\"", "\"mode\": \"nvfp4\""), .index = stock_index }, - ask, - &.{"nvfp4"}, - ); - try expectRefused( - a, - .{ - .config = try edit( - a, - stock_config, - "\"model_type\": \"nemotron_h\"", - "\"model_type\": \"nemotron_h\", \"tensorfold_learned_neurons\": 64", - ), - .index = stock_index, - }, - ask, - &.{"pocket"}, - ); - try expectRefused(a, .{ .config = stock_config, .index = stock_index, .living = true }, ask, &.{"Living Weights"}); - try expectRefused(a, .{ .config = stock_config, .index = stock_index, .mtp = mtp[1..] }, ask, &.{tensors.mtp_file}); - try expectRefused( - a, - .{ .config = stock_config, .index = stock_index }, - .{ .world = 3, .window = 4096, .room = 30 * gib }, - &.{"--tp 3"}, - ); -} - -/// The stock config with the raw quantization entries `raw` added to its block. -fn entries(a: std.mem.Allocator, raw: []const u8) ![]const u8 { - return edit(a, stock_config, "\"group_size\": 64,", try std.fmt.allocPrint(a, "\"group_size\": 64, {s},", .{raw})); -} - -/// The stock index without the embedding's scales and biases: a bf16 token table's tensors. -fn bf16Index(a: std.mem.Allocator) ![]const u8 { - const biases = "\"backbone.embeddings.biases\": \"model-00001-of-00004.safetensors\","; - const scales = "\"backbone.embeddings.scales\": \"model-00001-of-00004.safetensors\","; - return edit(a, try edit(a, stock_index, biases, ""), scales, ""); -} - -test "a bf16 token table beside quantized projections is admitted, its bytes counted as stored" { - var arena: std.heap.ArenaAllocator = .init(testing.allocator); - defer arena.deinit(); - const a = arena.allocator(); - var problem: []const u8 = ""; - const ask: Ask = .{ .window = 4096, .room = 60 * gib }; - const text = try entries(a, "\"backbone.embeddings\": false"); - const mtp = try stockMtp(a); - const stock = try admit(a, .{ .config = stock_config, .index = stock_index, .mtp = mtp }, ask, &problem); - const v = try admit(a, .{ .config = text, .index = try bf16Index(a), .mtp = mtp }, ask, &problem); - try testing.expect(v.fits and v.mtp and v.config.embed_bf16); - const quantized = plan.affine(.{}, v.config.vocab, v.config.hidden); - try testing.expectEqual(stock.weights - quantized + v.config.vocab * v.config.hidden * 2, v.weights); - // as MLX loads it, no scales in the files is enough: config.json need not list the table - const unlisted = try admit(a, .{ .config = stock_config, .index = try bf16Index(a), .mtp = mtp }, ask, &problem); - try testing.expect(unlisted.config.embed_bf16); - try testing.expectEqual(v.weights, unlisted.weights); - // the same text still refuses where the token table is not the engine's to read bare - var why: config.Why = .{}; - try testing.expectError(error.UnsupportedQuantization, config.parse(a, text, &why)); - try testing.expect(std.mem.indexOf(u8, why.text(), "backbone.embeddings") != null); -} - -test "with a bf16 token table, every other unquantized or unread tensor is still refused by name" { - var arena: std.heap.ArenaAllocator = .init(testing.allocator); - defer arena.deinit(); - const a = arena.allocator(); - const ask: Ask = .{ .window = 4096, .room = 60 * gib }; - const bare = "\"backbone.embeddings\": false"; - const index = try bf16Index(a); - // the table's own mismatches: scales left in the index, or none behind a quantized config - try expectRefused(a, .{ .config = try entries(a, bare), .index = stock_index }, ask, &.{ - "backbone.embeddings.scales", - "does not read", - }); - try expectRefused(a, .{ .config = stock_config, .index = try edit(a, index, "\"backbone.embeddings.weight\"", "\"x\"") }, ask, &.{ - "backbone.embeddings.weight", - }); - try expectRefused(a, .{ .config = try entries(a, "\"backbone.embeddings\": {}"), .index = index }, ask, &.{ - "backbone.embeddings", - "unquantized", - }); - // a bf16 head, projection or attention matrix is not the table - for ([_][]const u8{ "lm_head", "backbone.layers.1.mixer.shared_experts.up_proj", "backbone.layers.5.mixer.q_proj" }) |n| { - const text = try entries(a, try std.fmt.allocPrint(a, "{s}, \"{s}\": false", .{ bare, n })); - try expectRefused(a, .{ .config = text, .index = index }, ask, &.{ n, "unquantized" }); - } - const o_proj = "backbone.layers.12.mixer.o_proj.scales"; - try expectRefused(a, .{ - .config = try entries(a, bare), - .index = try edit(a, index, "\"" ++ o_proj ++ "\"", "\"x\""), - }, ask, &.{ "backbone.layers.12.mixer.o_proj", "Living Weights" }); - // other widths and group sizes - const three = try entries(a, bare ++ ", \"backbone.layers.4.mixer.in_proj\": {\"bits\": 3}"); - try expectRefused(a, .{ .config = three, .index = index }, ask, &.{"backbone.layers.4.mixer.in_proj is 3-bit in groups of 64"}); - const wide = try entries(a, bare ++ ", \"lm_head\": {\"bits\": 8, \"group_size\": 128}"); - try expectRefused(a, .{ .config = wide, .index = index }, ask, &.{"lm_head is 8-bit in groups of 128"}); - const grouped = try edit(a, try entries(a, bare), "\"group_size\": 64,", "\"group_size\": 32,"); - try expectRefused(a, .{ .config = grouped, .index = index }, ask, &.{"groups of 32"}); - // the MTP head inside the shards, and its file beside a model not stored 4-bit - const inside = try edit(a, index, "\"lm_head.weight\"", "\"lm_head.weight\": \"a\", \"mtp.layers.0.eh_proj.weight\""); - try expectRefused(a, .{ .config = try entries(a, bare), .index = inside }, ask, &.{ - "mtp.layers.0.eh_proj.weight", - "inside the model's shards", - }); - const eight = try edit(a, try entries(a, bare), "\"bits\": 4", "\"bits\": 8"); - try expectRefused(a, .{ .config = eight, .index = index, .mtp = try stockMtp(a) }, ask, &.{ tensors.mtp_file, "8-bit" }); +test { + _ = @import("admit_test.zig"); } diff --git a/zig/src/families/nemotron/hip/admit_test.zig b/zig/src/families/nemotron/hip/admit_test.zig new file mode 100644 index 00000000000..59c05948863 --- /dev/null +++ b/zig/src/families/nemotron/hip/admit_test.zig @@ -0,0 +1,350 @@ +//! Admission tests for Nemotron-H on HIP: widths, BF16 embeddings, refusals, and MTP head metadata. +const std = @import("std"); +const config = @import("../config.zig"); +const tensors = @import("tensors.zig"); +const plan = @import("plan.zig"); +const admit_mod = @import("admit.zig"); + +const Facts = admit_mod.Facts; +const Ask = admit_mod.Ask; +const admit = admit_mod.admit; +const tooBig = admit_mod.tooBig; + +const testing = std.testing; +const stock_config = @embedFile("../fixtures/config.json"); +const stock_index = @embedFile("../fixtures/index.json"); +const gib: u64 = 1 << 30; + +/// The stock MTP file's names, from the fixture's lines. +fn stockMtp(a: std.mem.Allocator) ![]const []const u8 { + var list: std.ArrayList([]const u8) = .empty; + var it = std.mem.tokenizeAny(u8, @embedFile("../fixtures/mtp_names.txt"), "\n\r "); + while (it.next()) |n| try list.append(a, n); + return list.items; +} + +/// `text` with every `from` replaced by `to`. +fn edit(a: std.mem.Allocator, text: []const u8, from: []const u8, to: []const u8) ![]const u8 { + try testing.expect(std.mem.indexOf(u8, text, from) != null); + return std.mem.replaceOwned(u8, a, text, from, to); +} + +/// The stock config with module `name` at `bits` in groups of `group`. +fn module(a: std.mem.Allocator, name: []const u8, bits: u8, group: u16) ![]const u8 { + const entry = try std.fmt.allocPrint(a, "\"group_size\": 64, \"{s}\": {{\"bits\": {d}, \"group_size\": {d}}},", .{ + name, + bits, + group, + }); + return edit(a, stock_config, "\"group_size\": 64,", entry); +} + +/// admit() must refuse with a reason naming each of `words`. +fn expectRefused(a: std.mem.Allocator, f: Facts, ask: Ask, words: []const []const u8) !void { + var problem: []const u8 = ""; + try testing.expectError(error.Refused, admit(a, f, ask, &problem)); + for (words) |w| if (std.mem.indexOf(u8, problem, w) == null) { + std.debug.print("refusal \"{s}\" does not name \"{s}\"\n", .{ problem, w }); + return error.TestUnexpectedResult; + }; +} + +test "the stock checkpoint and its MTP head are admitted; on one V620 a stream takes the model's window" { + var arena: std.heap.ArenaAllocator = .init(testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var problem: []const u8 = ""; + const f: Facts = .{ .config = stock_config, .index = stock_index, .mtp = try stockMtp(a) }; + const one = try admit(a, f, .{ .window = 262144, .room = 30 * gib }, &problem); + try testing.expect(one.fits and one.mtp); + try testing.expectEqual(@as(usize, 52), one.config.layers); + const two = try admit(a, f, .{ .world = 2, .rank = 1, .window = 262144, .room = 30 * gib }, &problem); + try testing.expect(two.fits and two.weights < one.weights / 2); + const lone = try admit( + a, + .{ .config = stock_config, .index = stock_index }, + .{ .window = 4096, .room = 30 * gib }, + &problem, + ); + try testing.expect(!lone.mtp and lone.weights < one.weights); + const small = try admit(a, f, .{ .window = 4096, .room = 16 * gib }, &problem); + try testing.expect(!small.fits); + try testing.expectEqual(error.Refused, tooBig(a, small, .{ .window = 4096, .room = 16 * gib }, &problem)); + try testing.expect(std.mem.indexOf(u8, problem, "16.00 GiB this card grants") != null); +} + +test "uniform 8-bit and mixed 4/5/6/8-bit checkpoints in groups of 64 are admitted, their bytes at their widths" { + var arena: std.heap.ArenaAllocator = .init(testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var problem: []const u8 = ""; + const ask: Ask = .{ .window = 4096, .room = 60 * gib }; + const four = try admit(a, .{ .config = stock_config, .index = stock_index }, ask, &problem); + const eight_text = try edit(a, stock_config, "\"bits\": 4", "\"bits\": 8"); + const eight = try admit(a, .{ .config = eight_text, .index = stock_index }, ask, &problem); + try testing.expect(eight.fits and eight.weights > four.weights + four.weights / 2); + var text: []const u8 = stock_config; + for ([_][]const u8{ "backbone.embeddings", "lm_head", "backbone.layers.1.mixer.shared_experts.up_proj" }) |n| { + const entry = try std.fmt.allocPrint(a, "\"group_size\": 64, \"{s}\": {{\"bits\": 8}},", .{n}); + text = try edit(a, text, "\"group_size\": 64,", entry); + } + text = try edit(a, text, "\"group_size\": 64,", "\"group_size\": 64, " ++ + "\"backbone.layers.0.mixer.in_proj\": {\"bits\": 5}, " ++ + "\"backbone.layers.0.mixer.out_proj\": {\"bits\": 6},"); + const mixed = try admit(a, .{ .config = text, .index = stock_index }, ask, &problem); + try testing.expect(mixed.fits and mixed.weights > four.weights and mixed.weights < eight.weights); + try testing.expectEqual(@as(u8, 5), mixed.config.widths[0][0].bits); +} + +test "the MTP head file is admitted beside a model not stored 4-bit in groups of 64" { + var arena: std.heap.ArenaAllocator = .init(testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var problem: []const u8 = ""; + const ask: Ask = .{ .window = 4096, .room = 60 * gib }; + const mtp = try stockMtp(a); + for ([_][]const u8{ "\"bits\": 6", "\"bits\": 8" }) |bits| { + const text = try edit(a, stock_config, "\"bits\": 4", bits); + const v = try admit(a, .{ .config = text, .index = stock_index, .mtp = mtp }, ask, &problem); + try testing.expect(v.mtp and v.fits); + try testing.expectEqual(config.Width{ .bits = 4, .group = 64 }, v.head); + } + const mixed = try module(a, "lm_head", 8, 64); + const v = try admit(a, .{ .config = mixed, .index = stock_index, .mtp = mtp }, ask, &problem); + try testing.expect(v.mtp and v.fits); +} + +test "altered checkpoints are refused with a reason" { + var arena: std.heap.ArenaAllocator = .init(testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const ask: Ask = .{ .window = 4096, .room = 30 * gib }; + const mtp = try stockMtp(a); + const gone = "backbone.layers.7.mixer.A_log"; + try expectRefused( + a, + .{ + .config = stock_config, + .index = try edit(a, stock_index, "\"" ++ gone ++ "\"", "\"backbone.layers.7.mixer.B_log\""), + }, + ask, + &.{gone}, + ); + const scales = "backbone.layers.12.mixer.o_proj.scales"; + try expectRefused( + a, + .{ .config = stock_config, .index = try edit(a, stock_index, "\"" ++ scales ++ "\"", "\"x\"") }, + ask, + &.{ "backbone.layers.12.mixer.o_proj", "Living Weights" }, + ); + try expectRefused( + a, + .{ + .config = stock_config, + .index = try edit(a, stock_index, "\"lm_head.weight\"", "\"lm_head.weight\": \"a\", \"vision.w\""), + }, + ask, + &.{"vision.w"}, + ); + try expectRefused( + a, + .{ .config = try edit(a, stock_config, "\"group_size\": 64", "\"group_size\": 32"), .index = stock_index }, + ask, + &.{ "backbone.embeddings is 4-bit in groups of 32", "groups of 64" }, + ); + const three = try module(a, "backbone.layers.4.mixer.in_proj", 3, 64); + try expectRefused(a, .{ .config = three, .index = stock_index }, ask, &.{ + "backbone.layers.4.mixer.in_proj is 3-bit in groups of 64", + }); + try expectRefused(a, .{ .config = try module(a, "lm_head", 8, 128), .index = stock_index }, ask, &.{ + "lm_head is 8-bit in groups of 128", + }); + try expectRefused( + a, + .{ .config = try module(a, "backbone.layers.1.mixer.switch_mlp.fc1", 2, 64), .index = stock_index }, + ask, + &.{"backbone.layers.1.mixer.switch_mlp.fc1 is 2-bit"}, + ); + try expectRefused( + a, + .{ + .config = try edit(a, stock_config, "\"group_size\": 64,", "\"group_size\": 64, " ++ + "\"backbone.layers.5.mixer.q_proj\": false,"), + .index = stock_index, + }, + ask, + &.{ "backbone.layers.5.mixer.q_proj", "unquantized" }, + ); + try expectRefused( + a, + .{ + .config = stock_config, + .index = try edit(a, stock_index, "\"lm_head.weight\"", "\"lm_head.weight\": \"a\", " ++ + "\"mtp.layers.0.eh_proj.weight\""), + }, + ask, + &.{ "mtp.layers.0.eh_proj.weight", "inside the model's shards", tensors.mtp_file }, + ); + try expectRefused( + a, + .{ + .config = try edit( + a, + stock_config, + "\"quantization\": {", + "\"quantization\": {\"quant_method\": \"modelopt\",", + ), + .index = stock_index, + }, + ask, + &.{ "ModelOpt", "CUDA" }, + ); + try expectRefused( + a, + .{ .config = try edit(a, stock_config, "\"mode\": \"affine\"", "\"mode\": \"nvfp4\""), .index = stock_index }, + ask, + &.{"nvfp4"}, + ); + try expectRefused( + a, + .{ + .config = try edit( + a, + stock_config, + "\"model_type\": \"nemotron_h\"", + "\"model_type\": \"nemotron_h\", \"tensorfold_learned_neurons\": 64", + ), + .index = stock_index, + }, + ask, + &.{"pocket"}, + ); + try expectRefused(a, .{ .config = stock_config, .index = stock_index, .living = true }, ask, &.{"Living Weights"}); + try expectRefused(a, .{ .config = stock_config, .index = stock_index, .mtp = mtp[1..] }, ask, &.{tensors.mtp_file}); + try expectRefused( + a, + .{ .config = stock_config, .index = stock_index }, + .{ .world = 3, .window = 4096, .room = 30 * gib }, + &.{"--tp 3"}, + ); +} + +/// The stock config with the raw quantization entries `raw` added to its block. +fn entries(a: std.mem.Allocator, raw: []const u8) ![]const u8 { + return edit(a, stock_config, "\"group_size\": 64,", try std.fmt.allocPrint(a, "\"group_size\": 64, {s},", .{raw})); +} + +/// The stock index without the embedding's scales and biases: a bf16 token table's tensors. +fn bf16Index(a: std.mem.Allocator) ![]const u8 { + const biases = "\"backbone.embeddings.biases\": \"model-00001-of-00004.safetensors\","; + const scales = "\"backbone.embeddings.scales\": \"model-00001-of-00004.safetensors\","; + return edit(a, try edit(a, stock_index, biases, ""), scales, ""); +} + +test "a bf16 token table beside quantized projections is admitted, its bytes counted as stored" { + var arena: std.heap.ArenaAllocator = .init(testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var problem: []const u8 = ""; + const ask: Ask = .{ .window = 4096, .room = 60 * gib }; + const text = try entries(a, "\"backbone.embeddings\": false"); + const mtp = try stockMtp(a); + const stock = try admit(a, .{ .config = stock_config, .index = stock_index, .mtp = mtp }, ask, &problem); + const v = try admit(a, .{ .config = text, .index = try bf16Index(a), .mtp = mtp }, ask, &problem); + try testing.expect(v.fits and v.mtp and v.config.embed_bf16); + const quantized = plan.affine(.{}, v.config.vocab, v.config.hidden); + try testing.expectEqual(stock.weights - quantized + v.config.vocab * v.config.hidden * 2, v.weights); + // as MLX loads it, no scales in the files is enough: config.json need not list the table + const unlisted = try admit(a, .{ .config = stock_config, .index = try bf16Index(a), .mtp = mtp }, ask, &problem); + try testing.expect(unlisted.config.embed_bf16); + try testing.expectEqual(v.weights, unlisted.weights); + // the same text still refuses where the token table is not the engine's to read bare + var why: config.Why = .{}; + try testing.expectError(error.UnsupportedQuantization, config.parse(a, text, &why)); + try testing.expect(std.mem.indexOf(u8, why.text(), "backbone.embeddings") != null); +} + +test "with a bf16 token table, every other unquantized or unread tensor is still refused by name" { + var arena: std.heap.ArenaAllocator = .init(testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var problem: []const u8 = ""; + const ask: Ask = .{ .window = 4096, .room = 60 * gib }; + const bare = "\"backbone.embeddings\": false"; + const index = try bf16Index(a); + // the table's own mismatches: scales left in the index, or none behind a quantized config + try expectRefused(a, .{ .config = try entries(a, bare), .index = stock_index }, ask, &.{ + "backbone.embeddings.scales", + "does not read", + }); + try expectRefused(a, .{ .config = stock_config, .index = try edit(a, index, "\"backbone.embeddings.weight\"", "\"x\"") }, ask, &.{ + "backbone.embeddings.weight", + }); + try expectRefused(a, .{ .config = try entries(a, "\"backbone.embeddings\": {}"), .index = index }, ask, &.{ + "backbone.embeddings", + "unquantized", + }); + // a bf16 head, projection or attention matrix is not the table + for ([_][]const u8{ "lm_head", "backbone.layers.1.mixer.shared_experts.up_proj", "backbone.layers.5.mixer.q_proj" }) |n| { + const text = try entries(a, try std.fmt.allocPrint(a, "{s}, \"{s}\": false", .{ bare, n })); + try expectRefused(a, .{ .config = text, .index = index }, ask, &.{ n, "unquantized" }); + } + const o_proj = "backbone.layers.12.mixer.o_proj.scales"; + try expectRefused(a, .{ + .config = try entries(a, bare), + .index = try edit(a, index, "\"" ++ o_proj ++ "\"", "\"x\""), + }, ask, &.{ "backbone.layers.12.mixer.o_proj", "Living Weights" }); + // other widths and group sizes + const three = try entries(a, bare ++ ", \"backbone.layers.4.mixer.in_proj\": {\"bits\": 3}"); + try expectRefused(a, .{ .config = three, .index = index }, ask, &.{"backbone.layers.4.mixer.in_proj is 3-bit in groups of 64"}); + const wide = try entries(a, bare ++ ", \"lm_head\": {\"bits\": 8, \"group_size\": 128}"); + try expectRefused(a, .{ .config = wide, .index = index }, ask, &.{"lm_head is 8-bit in groups of 128"}); + const grouped = try edit(a, try entries(a, bare), "\"group_size\": 64,", "\"group_size\": 32,"); + try expectRefused(a, .{ .config = grouped, .index = index }, ask, &.{"groups of 32"}); + // the MTP head inside the shards stays refused; its file drafts beside 8-bit unless the head itself is unserved + const inside = try edit(a, index, "\"lm_head.weight\"", "\"lm_head.weight\": \"a\", \"mtp.layers.0.eh_proj.weight\""); + try expectRefused(a, .{ .config = try entries(a, bare), .index = inside }, ask, &.{ + "mtp.layers.0.eh_proj.weight", + "inside the model's shards", + }); + const eight = try edit(a, try entries(a, bare), "\"bits\": 4", "\"bits\": 8"); + const stock_head = try stockMtp(a); + const v8 = try admit(a, .{ .config = eight, .index = index, .mtp = stock_head }, ask, &problem); + try testing.expect(v8.fits and v8.mtp and v8.config.embed_bf16 and v8.head.bits == 4); + try expectRefused( + a, + .{ .config = eight, .index = index, .mtp = stock_head, .mtp_quantization = "{\"group_size\": 32, \"bits\": 4}" }, + ask, + &.{ tensors.mtp_file, "4-bit in groups of 32" }, + ); +} + +test "the MTP head is read at the width its own file states, beside a model of any width" { + var arena: std.heap.ArenaAllocator = .init(testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var problem: []const u8 = ""; + const ask: Ask = .{ .window = 4096, .room = 60 * gib }; + const mtp = try stockMtp(a); + const eight = try edit(a, stock_config, "\"bits\": 4", "\"bits\": 8"); + const stock_head = "{\"group_size\": 64, \"bits\": 4}"; + const f: Facts = .{ .config = eight, .index = stock_index, .mtp = mtp, .mtp_quantization = stock_head }; + const v = try admit(a, f, ask, &problem); + try testing.expectEqual(config.Width{ .bits = 4, .group = 64 }, v.head); + const lone = try admit(a, .{ .config = eight, .index = stock_index }, ask, &problem); + // the head at 4/64 and its draft rows at the 8-bit vocabulary head's width + const want = (try plan.weights(&v.config, 1, .device, .{ .mtp = true, .drafts = admit_mod.draft_rows })).head; + try testing.expectEqual(lone.weights + want, v.weights); + const unstated = try admit(a, .{ .config = eight, .index = stock_index, .mtp = mtp }, ask, &problem); + try testing.expectEqual(v.weights, unstated.weights); + const six = "{\"group_size\": 64, \"bits\": 6}"; + var g = f; + g.mtp_quantization = six; + const wide = try admit(a, g, ask, &problem); + try testing.expectEqual(config.Width{ .bits = 6, .group = 64 }, wide.head); + try testing.expect(wide.weights > v.weights); + g.mtp_quantization = "{\"group_size\": 32, \"bits\": 4}"; + try expectRefused(a, g, ask, &.{ tensors.mtp_file, "4-bit in groups of 32" }); + g.mtp_quantization = "nvfp4"; + try expectRefused(a, g, ask, &.{ tensors.mtp_file, "nvfp4" }); +} diff --git a/zig/src/families/nemotron/hip/costs.zig b/zig/src/families/nemotron/hip/costs.zig index bbfa75368fb..e21a2506b47 100644 --- a/zig/src/families/nemotron/hip/costs.zig +++ b/zig/src/families/nemotron/hip/costs.zig @@ -13,6 +13,7 @@ pub const Costs = shared.Costs; /// A scratch lane's kept length in the timings, and the positions it covers past it (the head steps' too). const at = 16; const room = 2 * shared.window * 4; +const timed_depth = 3; const Rig = struct { h: *Hip, @@ -63,10 +64,10 @@ const Rig = struct { } }; - /// One chained head step: a lone chain of the deepest depth from a scratch lane's (garbage) row. + /// One chained head step: a chain of `timed_depth` from a scratch lane's (garbage) row. fn step(r: *Rig, hd: *head.Head) !f64 { const run: Chain = .{ .r = r, .hd = hd }; - return try shared.mean(run, Chain.go) / head.max_depth; + return try shared.mean(run, Chain.go) / timed_depth; } const Chain = struct { @@ -78,7 +79,7 @@ const Rig = struct { const l = x.r.ls[0]; l.s.len = at; l.s.mtp_len = at; - var out: [head.max_depth]u32 = undefined; + var out: [timed_depth]u32 = undefined; var jobs = [_]head.Job{.{ .s = &l.s, .hidden = l.hidden.base(), .next = x.r.tokens[0][0..1], .out = &out }}; try h.e.fresh(); try x.hd.chains(h.e.ops(&h.e.arena), &jobs); @@ -98,6 +99,6 @@ pub fn measure(h: *Hip, out: *Costs) !void { try l.s.cover(&e.pool, at + room); l.s.len = at; } - try shared.forwards(&r, @min(lanes.max_window, e.plan.rows), streams, e.plan.rows, out); + try shared.forwards(&r, @min(e.window, e.plan.rows), streams, e.plan.rows, out); if (h.head) |hd| out.step_ms = try r.step(hd); } diff --git a/zig/src/families/nemotron/hip/deep_drafts_test.zig b/zig/src/families/nemotron/hip/deep_drafts_test.zig new file mode 100644 index 00000000000..f94beafae54 --- /dev/null +++ b/zig/src/families/nemotron/hip/deep_drafts_test.zig @@ -0,0 +1,151 @@ +//! Nemotron's deeper MTP windows: without --mtp-drafts past three the facts and lane bytes keep the four-row ones. +const std = @import("std"); +const hip = @import("hip"); +const lanes = @import("lanes"); +const round = @import("round.zig"); +const head = @import("head.zig"); +const hip_lanes = @import("lanes.zig"); +const native = @import("native.zig"); +const costs = @import("costs.zig"); + +const depth = lanes.depth; +const Table = lanes.table.Table; + +/// Representative forward ms by window rows and shared rows for depth-rule equivalence tests. +fn timed() costs.Costs { + var c: costs.Costs = .{ .step_ms = 0.83 }; + for ([_]f64{ 13.9, 15.1, 16.0, 16.9 }, 0..) |ms, i| c.window[i] = .{ .width = @intCast(i + 1), .ms = ms }; + c.windows = 4; + for ([_]u32{ 2, 4, 8, 12 }, [_]f64{ 15.0, 17.0, 21.5, 26.0 }, 0..) |w, ms, i| c.shared[i] = .{ .width = w, .ms = ms }; + c.shareds = 4; + return c; +} + +/// The facts as the engine reported them before deeper windows: four rows a window, three drafts, no shared cap. +fn before(streams: usize, c: *const costs.Costs) lanes.Model { + return .{ + .exact_width = 4, + .gpu_tokens = false, + .mtp = true, + .speculate = true, + .speculate_early = false, + .drafts = 3, + .hidden_rows = true, + .batch_rows = @intCast(4 * streams), + .max_streams = @intCast(streams), + .draft_streams = true, + .plain_guard = c.windows > 0, + .window_costs = c.window[0..c.windows], + .shared_costs = c.shared[0..c.shareds], + .mtp_step_ms = c.step_ms, + }; +} + +test "without --mtp-drafts the window, lane bytes and facts are the four-row ones plus a shared cap of three" { + const a = std.testing.allocator; + const asked = (hip.Policy{}).mtp.drafts; + const window = round.windowFor(asked); + try std.testing.expectEqual(@as(usize, 4), window); + try std.testing.expectEqual(native.laneBytesFor(32768, 4, 65536, 24_541_184, 2688, 2), native.laneBytesFor(32768, window, 65536, 24_541_184, 2688, 2)); + var c = timed(); + for ([_]usize{ 1, 3, 4 }) |streams| { + const at: hip_lanes.Setup = .{ .window = window, .rows = round.planRows(streams, window), .slots = streams }; + try std.testing.expectEqual(streams * window, at.rows); + var got = hip_lanes.factsFor(at, true, asked, &c); + try std.testing.expectEqual(@as(u32, 3), got.shared_mtp_cap); + got.shared_mtp_cap = 0; + try std.testing.expectEqualDeep(before(streams, &c), got); + var cfg = try lanes.Config.init(a, hip_lanes.factsFor(at, true, asked, &c), @intCast(window), @intCast(window - 1)); + defer cfg.deinit(a); + try std.testing.expectEqual(@as(u32, 3), cfg.most_drafts); + try std.testing.expectEqual(@as(u32, 4), cfg.family_width); + try std.testing.expectEqual(@as(u32, 3), cfg.shared_mtp_cap); + try std.testing.expectEqual(@as(u32, @intCast(4 * streams)), cfg.batch_rows); + } +} + +const NoCopy = struct { + fn copy(_: *anyopaque, _: *const depth.Who) bool { + return false; + } +}; + +fn ruleOf(prior: []const f64, family: *const Table, shared: *const Table, cap: u32, guard: bool) depth.Rule { + return .{ + .gpa = std.testing.allocator, + .prior = prior, + .most_drafts = 3, + .shared_cap = cap, + .family_costs = family, + .shared_costs = shared, + .mtp_step_ms = 0.83, + .plain_guard = guard, + .node_probabilities = false, + .batch_rows = 16, + }; +} + +fn whoOf(state: *?depth.State) depth.Who { + return .{ .state = state, .draft_room = 100, .finished = false, .forced = false }; +} + +test "at three drafts the shared cap of three changes no lone depth and no shared budget" { + const a = std.testing.allocator; + var unused: u8 = 0; + const probe: depth.Probe = .{ .ptr = &unused, .copy = NoCopy.copy }; + var family: Table = .{}; + defer family.deinit(a); + var shared: Table = .{}; + defer shared.deinit(a); + const c = timed(); + for (c.window[0..c.windows]) |x| try family.put(a, x.width, x.ms); + for (1..17) |w| try shared.put(a, @intCast(w), 13.0 + @as(f64, @floatFromInt(w))); + var none: Table = .{}; + defer none.deinit(a); + const priors = [_][3]f64{ .{ 0.95, 0.9, 0.85 }, .{ 0.85, 0.7, 0.6 }, .{ 0.5, 0.4, 0.3 } }; + for (&priors) |*prior| for ([_]*const Table{ &family, &none }) |fam| for ([_]bool{ false, true }) |guard| { + var old = ruleOf(prior, fam, &shared, 0, guard); + defer old.deinit(); + var new = ruleOf(prior, fam, &shared, 3, guard); + defer new.deinit(); + var so: [3]?depth.State = @splat(null); + var sn: [3]?depth.State = @splat(null); + defer for (&so, &sn) |*x, *y| { + if (x.*) |*s| s.deinit(a); + if (y.*) |*s| s.deinit(a); + }; + for (0..24) |r| { + const lone_old = try old.headDepth(&whoOf(&so[0]), null, probe); + try std.testing.expectEqual(lone_old, try new.headDepth(&whoOf(&sn[0]), null, probe)); + try old.observeDepth(whoOf(&so[0]), lone_old, @intCast(r % 4)); + try new.observeDepth(whoOf(&sn[0]), lone_old, @intCast(r % 4)); + var wo = [_]depth.Who{ whoOf(&so[1]), whoOf(&so[2]) }; + var wn = [_]depth.Who{ whoOf(&sn[1]), whoOf(&sn[2]) }; + var bo: [2]i64 = undefined; + var bn: [2]i64 = undefined; + try old.budgets(&wo, probe, false, &bo); + try new.budgets(&wn, probe, false, &bn); + try std.testing.expectEqualSlices(i64, &bo, &bn); + } + }; +} + +test "--mtp-drafts 4 to 15 widens the window to 16; shared rounds keep 3 drafts and at least default plan rows" { + const a = std.testing.allocator; + try std.testing.expectEqual(@as(usize, 15), head.max_depth); + try std.testing.expectEqual(@as(u32, 15), native.mtp_max_drafts); + var c = timed(); + for (4..16) |n| for ([_]usize{ 1, 2, 4, 8, 16 }) |streams| { + const asked: u8 = @intCast(n); + const window = round.windowFor(asked); + try std.testing.expectEqual(n + 1, window); + const at: hip_lanes.Setup = .{ .window = window, .rows = round.planRows(streams, window), .slots = streams }; + try std.testing.expectEqual(@max(streams * 4, @min(streams * window, 32)), at.rows); + var cfg = try lanes.Config.init(a, hip_lanes.factsFor(at, true, asked, &c), @intCast(window), @intCast(window - 1)); + defer cfg.deinit(a); + try std.testing.expectEqual(@as(u32, asked), cfg.most_drafts); + try std.testing.expectEqual(@as(u32, @intCast(window)), cfg.family_width); + try std.testing.expectEqual(@as(u32, 3), cfg.shared_mtp_cap); + try std.testing.expectEqual(@as(u32, @intCast(at.rows)), cfg.batch_rows); + }; +} diff --git a/zig/src/families/nemotron/hip/engine.zig b/zig/src/families/nemotron/hip/engine.zig index 25b53c2500a..a781e8eb679 100644 --- a/zig/src/families/nemotron/hip/engine.zig +++ b/zig/src/families/nemotron/hip/engine.zig @@ -75,7 +75,8 @@ pub const Engine = struct { comm: ?hip.collective.Comm = null, arena: hip.Arena, pool: pages.Pool, - /// A lane round's plan and its windows, sized with the pool for `o.streams` streams of `rounds.max_window` rows. + /// A stream's window, its round plan and its windows, sized with the pool for `o.streams` streams. + window: usize, plan: rounds.Plan, wins: []rounds.Window, sized: bool, @@ -110,6 +111,7 @@ pub const Engine = struct { e.gpa = gpa; e.io = io; e.o = o; + e.window = rounds.windowFor(o.policy.mtp.drafts); e.stopped = false; e.driver = try hip.Runtime.open(); errdefer e.driver.close(); @@ -175,7 +177,7 @@ pub const Engine = struct { head_kv, ); errdefer e.pool.deinit(); - e.plan = try rounds.Plan.init(&e.driver, &e.pool, streams * rounds.max_window, streams, d.vocab); + e.plan = try rounds.Plan.init(&e.driver, &e.pool, rounds.planRows(streams, e.window), streams, d.vocab); errdefer e.plan.deinit(); e.wins = try e.gpa.alloc(rounds.Window, streams); e.sized = true; diff --git a/zig/src/families/nemotron/hip/head.zig b/zig/src/families/nemotron/hip/head.zig index e5d00fd0e3f..c9b4b0beb38 100644 --- a/zig/src/families/nemotron/hip/head.zig +++ b/zig/src/families/nemotron/hip/head.zig @@ -8,8 +8,8 @@ const pages = @import("pages.zig"); const Tensor = hip.ops.Tensor; -/// Drafts a chain holds at most. -pub const max_depth = 3; +/// Drafts a lone stream's chain holds at most. +pub const max_depth = 15; /// One stream's work of a head round: its model rows and the token after each, then the drafts chained from the last. pub const Job = struct { s: *pages.Stream, hidden: u64, next: []const u32, out: []u32, got: usize = 0 }; diff --git a/zig/src/families/nemotron/hip/lanes.zig b/zig/src/families/nemotron/hip/lanes.zig index afff904588a..f368e34fc15 100644 --- a/zig/src/families/nemotron/hip/lanes.zig +++ b/zig/src/families/nemotron/hip/lanes.zig @@ -20,6 +20,12 @@ const Tensor = hip.ops.Tensor; /// Rows a window holds at most: the pending token and the drafts (every width reproduces one-token steps). pub const max_window = round.max_window; +/// Most head drafts a stream chains in a round it shares; a lone stream chains up to `--mtp-drafts`. +pub const shared_chain_drafts = 3; + +/// Pure window and plan sizes passed to `factsFor` so host tests check `lanes.Model` without a device. +pub const Setup = struct { window: usize, rows: usize, slots: usize }; + pub const Lane = struct { s: pages.Stream, /// Each row's Mamba states of the last verify (slot 0 the state before it), for a keep of fewer rows. @@ -82,6 +88,29 @@ const Scratch = struct { } }; +/// The lane core's facts from window/plan sizes, drafting toggle, requested depth and timed costs. +pub fn factsFor(at: Setup, drafting: bool, drafts: u8, c: *const costs.Costs) lanes.Model { + // plain rounds compete with drafted ones once the forwards are timed + const timed = drafting and c.windows > 0; + return .{ + .exact_width = @intCast(at.window), + .gpu_tokens = false, + .mtp = drafting, + .speculate = drafting, + .speculate_early = false, + .drafts = @min(head.max_depth, drafts), + .shared_mtp_cap = shared_chain_drafts, + .hidden_rows = true, + .batch_rows = @intCast(at.rows), + .max_streams = @intCast(at.slots), + .draft_streams = drafting, + .plain_guard = timed, + .window_costs = c.window[0..c.windows], + .shared_costs = c.shared[0..c.shareds], + .mtp_step_ms = c.step_ms, + }; +} + pub const Hip = struct { gpa: std.mem.Allocator, e: *Engine, @@ -163,30 +192,14 @@ pub const Hip = struct { pub fn laneBytes(e: *const Engine) usize { const m = e.model_(); const state = pages.Stream.stateBytes(m.dims, e.act, e.cfg.count(.mamba)); - return state * (max_window + 2) + max_window * m.dims.hidden * e.act.size() + 4 * pages.pagesFor(e.o.capacity); + return state * (e.window + 2) + e.window * m.dims.hidden * e.act.size() + 4 * pages.pagesFor(e.o.capacity); } /// The facts the round loop reads at setup: exact windows, every stream's window in one round, batched drafts. pub fn facts(h: *const Hip) lanes.Model { - const drafting = h.head != null and h.e.o.policy.mtp.drafts > 0; - // plain rounds compete with drafted ones once the forwards are timed - const timed = drafting and h.costs.windows > 0; - return .{ - .exact_width = max_window, - .gpu_tokens = false, - .mtp = drafting, - .speculate = drafting, - .speculate_early = false, - .drafts = @min(head.max_depth, h.e.o.policy.mtp.drafts), - .hidden_rows = true, - .batch_rows = @intCast(h.e.plan.rows), - .max_streams = @intCast(h.e.plan.slots), - .draft_streams = drafting, - .plain_guard = timed, - .window_costs = h.costs.window[0..h.costs.windows], - .shared_costs = h.costs.shared[0..h.costs.shareds], - .mtp_step_ms = h.costs.step_ms, - }; + const e = h.e; + const drafting = h.head != null and e.o.policy.mtp.drafts > 0; + return factsFor(.{ .window = e.window, .rows = e.plan.rows, .slots = e.plan.slots }, drafting, e.o.policy.mtp.drafts, &h.costs); } pub fn drawer(h: *Hip) *draw.Drawer { @@ -231,9 +244,9 @@ pub const Hip = struct { errdefer h.gpa.destroy(l); var st = try e.openStream(); errdefer st.deinit(&e.pool); - var snaps = try hip.DeviceBuffer.alloc(&e.driver, (max_window + 1) * h.state_bytes); + var snaps = try hip.DeviceBuffer.alloc(&e.driver, (e.window + 1) * h.state_bytes); errdefer snaps.free(); - var hidden = try hip.DeviceBuffer.alloc(&e.driver, max_window * m.dims.hidden * e.act.size()); + var hidden = try hip.DeviceBuffer.alloc(&e.driver, e.window * m.dims.hidden * e.act.size()); errdefer hidden.free(); l.* = .{ .s = st, .snaps = snaps, .hidden = hidden }; return l; @@ -264,7 +277,7 @@ pub const Hip = struct { pub fn begin(h: *Hip, s: *lanes.Stream) !*Lane { const e = h.e; const prompt = s.prompt(); - if (prompt.len == 0 or prompt.len + s.max_new + max_window + 1 > e.o.capacity) return error.PromptTooLong; + if (prompt.len == 0 or prompt.len + s.max_new + e.window + 1 > e.o.capacity) return error.PromptTooLong; // refused before the other ranks hear the prompt: a rank that fails a step it was sent leaves the group for (prompt) |t| if (t >= e.model_().dims.vocab) return error.TokenOutsideVocabulary; const gop = try h.streams.map.getOrPut(h.gpa, s); @@ -275,7 +288,7 @@ pub const Hip = struct { gop.value_ptr.* = l; l.id = try h.streams.idOf(s); // pages for the whole request are promised now, so no round runs out of them - const total = prompt.len + s.max_new + max_window + 1; + const total = prompt.len + s.max_new + e.window + 1; const need = pages.pagesFor(total); if (!h.prefix.store.reclaim(need)) return error.OutOfPages; l.s.promised = need; @@ -382,7 +395,7 @@ pub const Hip = struct { for (ws, 0..) |w, i| { const l = try h.streams.get(w.stream); try glue.settle(h, l); - const n = try glue.windowTokens(w, l.held[0..l.held_n], l.s.len, &h.sc.tokens[i]); + const n = try glue.windowTokens(w, l.held[0..l.held_n], l.s.len, h.sc.tokens[i][0..e.window]); try l.s.cover(&e.pool, l.s.len + n); try h.syncPages(l); h.sc.lanes[i] = l; @@ -429,9 +442,9 @@ pub const Hip = struct { h.sc.firsts[i] = try glue.firstToken(&h.streams.drawn, r); break :blk h.sc.firsts[i..][0..1]; }; - if (next.len == 0 or next.len > max_window) return error.PositionMismatch; + if (next.len == 0 or next.len > e.window) return error.PositionMismatch; // the chained steps write the head's keys past the kept rows: their pages must be the stream's own - try l.s.cover(&e.pool, l.s.len + head.max_depth); + try l.s.cover(&e.pool, l.s.len + e.window - 1); try h.syncPages(l); if (tracing()) std.log.info( "trace {s} draft at {d}: pairs {any}, depth {d}", @@ -442,7 +455,7 @@ pub const Hip = struct { .s = &l.s, .hidden = l.hidden.base(), .next = next, - .out = l.held[0..@min(r.depth, head.max_depth)], + .out = l.held[0..@min(r.depth, e.window - 1)], }; } try e.fresh(); diff --git a/zig/src/families/nemotron/hip/load.zig b/zig/src/families/nemotron/hip/load.zig index eedd5a8137d..aca4dcb26d0 100644 --- a/zig/src/families/nemotron/hip/load.zig +++ b/zig/src/families/nemotron/hip/load.zig @@ -247,12 +247,15 @@ fn draftSpans(a: Allocator, ids: []const u32) ![]Span { return list.toOwnedSlice(a); } -/// The MTP head from mtp-4bit.safetensors, whole, and the vocabulary head's draft rows. +/// The MTP head from mtp-4bit.safetensors, whole at the width its file states, and the vocabulary head's draft rows. fn loadMtp(gpa: Allocator, io: std.Io, l: *Loader, dir: []const u8, c: *const config.Config, head: Host) !model.Mtp { var ck: Checkpoint = .{ .gpa = gpa, .io = io }; defer ck.close(); try ck.add(dir, tensors.mtp_file); - const t: Tables = .{ .ck = &ck, .w = l.t.w }; + const path = try std.fs.path.join(l.a, &.{ dir, tensors.mtp_file }); + const hw = try widths.headOf(l.a, try widths.headQuantization(l.a, io, path)); + if (!widths.served(hw)) return error.UnsupportedQuantization; + const t: Tables = .{ .ck = &ck, .w = .{ .bits = hw.bits, .group = hw.group } }; const main_t = l.t; l.t = &t; defer l.t = main_t; diff --git a/zig/src/families/nemotron/hip/native.zig b/zig/src/families/nemotron/hip/native.zig index 5b737c02832..36d7b818794 100644 --- a/zig/src/families/nemotron/hip/native.zig +++ b/zig/src/families/nemotron/hip/native.zig @@ -16,6 +16,13 @@ const widths = @import("widths.zig"); pub const model_type = "nemotron_h"; pub const formats = admit.formats; +/// MTP drafts the HIP head chains on one rank: `--mtp-drafts` is refused past this. +pub const mtp_max_drafts: u32 = @import("head.zig").max_depth; + +/// Device bytes one lane holds (`window` tokens, `rw` window rows); `pub` so `deep_drafts_test.zig` checks it. +pub fn laneBytesFor(window: usize, rw: usize, page: u64, state: u64, hidden: u64, act: u64) u64 { + return pages.pagesFor(window + rw + 1) * page + state * (rw + 2) + rw * hidden * act; +} /// Positions a stream holds when neither --context nor the checkpoint's config names a window. pub const default_context: i64 = 32768; /// The engine cuts prompts itself. @@ -65,6 +72,12 @@ fn mtpNames(a: std.mem.Allocator, io: std.Io, dir: []const u8) !?[]const []const return out.items; } +/// The quantization the MTP head's file states, or null when the file is not there or states none. +fn mtpQuantization(a: std.mem.Allocator, io: std.Io, dir: []const u8) !?[]const u8 { + if (!exists(a, dir, tensors.mtp_file)) return null; + return widths.headQuantization(a, io, try std.fs.path.join(a, &.{ dir, tensors.mtp_file })); +} + /// What admission reads from `dir`. pub fn factsOf(a: std.mem.Allocator, io: std.Io, dir: []const u8, problem: *[]const u8) Refused!admit.Facts { var lesson: [64]u8 = undefined; @@ -87,6 +100,12 @@ pub fn factsOf(a: std.mem.Allocator, io: std.Io, dir: []const u8, problem: *[]co "cannot read {s}/{s} ({t})", .{ dir, tensors.mtp_file, err }, ), + .mtp_quantization = mtpQuantization(a, io, dir) catch |err| return refuse( + a, + problem, + "cannot read {s}/{s}'s header ({t})", + .{ dir, tensors.mtp_file, err }, + ), .living = exists(a, dir, living.fileName(&lesson, 0) catch unreachable), }; } @@ -194,14 +213,13 @@ fn prepare( else => steps.refuseAll(a, problem, "the native HIP engine cannot load {s} ({t})", .{ dir, err }), }; errdefer e.deinit(); - const capacity: usize = window + hip_lanes.max_window + 1; + const capacity: usize = window + e.window + 1; const token = try plan.tokenBytes(c, o.world, act, v.mtp); const state = try plan.streamBytes(c, o.world, act); const page = token * pages.tokens; const snap = state + c.hidden * act; // a lane: its pages, its Mamba state, its window's snapshots and the head's rows - const lane: u64 = pages.pagesFor(capacity) * page + state * (hip_lanes.max_window + 2) + - hip_lanes.max_window * c.hidden * act; + const lane: u64 = laneBytesFor(window, e.window, page, state, c.hidden, act); const fixed: u64 = v.weights + admit.scratch_bytes + (64 << 20); if (fixed >= room) return heard(steps, problem, admit.tooBig(a, v, .{ .window = window, .room = room }, problem)); const left = room - fixed; @@ -260,7 +278,7 @@ fn prepare( cache.pages, cache.snaps, e.o.chunk, - hip_lanes.max_window, + e.window, }); return .{ .e = e, .streams = streams, .cache = cache, .startup = startup }; } @@ -314,7 +332,7 @@ pub fn open( return .{ .backend = backend.backend(), .facts = backend.facts(), - .rows = hip_lanes.max_window, + .rows = @intCast(p.e.window), .ctx = own, .deinit = release, .streams = p.streams, diff --git a/zig/src/families/nemotron/hip/round.zig b/zig/src/families/nemotron/hip/round.zig index 2eac1a16c7f..182bdc5f1c7 100644 --- a/zig/src/families/nemotron/hip/round.zig +++ b/zig/src/families/nemotron/hip/round.zig @@ -10,8 +10,25 @@ const Ops = hip.ops.Ops; const Tensor = hip.ops.Tensor; const pops = hip.plan_ops; -/// Rows a stream's window holds at most: the pending token and the drafts (every width reproduces one-token steps). -pub const max_window = 4; +/// Rows a stream's window holds by default: the pending token and three drafts. +pub const default_window = 4; + +/// Rows a lone stream's window holds at most when `--mtp-drafts` opts in past three. +pub const max_window = 16; + +/// Shared round row ceiling up to eight streams (above eight, `planRows` keeps `streams * default_window`). +pub const shared_cap_rows = 32; + +/// Window rows for a policy's `--mtp-drafts`: four up to three drafts (exact baseline), else `asked + 1` up to sixteen. +pub fn windowFor(asked: u8) usize { + return if (asked <= 3) default_window else @min(max_window, @as(usize, asked) + 1); +} + +/// Plan rows for `streams` and `window`: at least `streams * default_window`, and up to `shared_cap_rows` past four. +pub fn planRows(streams: usize, window: usize) usize { + if (window <= default_window) return streams * window; + return @max(streams * default_window, @min(streams * window, shared_cap_rows)); +} /// Shortest span the attention walk covers; spans double from here (a row's bits do not depend on the span). pub const min_span = 128; @@ -267,3 +284,17 @@ test "security: a round refuses a token at or past the vocabulary before its pla const win: Window = .{ .s = undefined, .pos = 0, .tokens = &.{ 7, 8 } }; try std.testing.expectError(error.TokenOutsideVocabulary, p.send(&.{win}, 4096, undefined)); } + +test "windowFor holds four up to three drafts and tracks --mtp-drafts up to 16; planRows keeps shared floor" { + for (0..4) |n| try std.testing.expectEqual(@as(usize, 4), windowFor(@intCast(n))); + for (4..16) |n| try std.testing.expectEqual(n + 1, windowFor(@intCast(n))); + try std.testing.expectEqual(@as(usize, 16), windowFor(16)); + try std.testing.expectEqual(@as(usize, 16), windowFor(255)); + for ([_]usize{ 1, 2, 4, 8, 16 }) |s| try std.testing.expectEqual(4 * s, planRows(s, 4)); + try std.testing.expectEqual(@as(usize, 16), planRows(1, 16)); + try std.testing.expectEqual(@as(usize, 32), planRows(2, 16)); + try std.testing.expectEqual(@as(usize, 32), planRows(4, 16)); + try std.testing.expectEqual(@as(usize, 32), planRows(8, 8)); + try std.testing.expectEqual(@as(usize, 64), planRows(16, 8)); + try std.testing.expectEqual(@as(usize, 64), planRows(16, 16)); +} diff --git a/zig/src/families/nemotron/hip/widths.zig b/zig/src/families/nemotron/hip/widths.zig index c893236a0a1..949ee9d8908 100644 --- a/zig/src/families/nemotron/hip/widths.zig +++ b/zig/src/families/nemotron/hip/widths.zig @@ -61,6 +61,44 @@ pub fn label(c: *const Config, buf: []u8) []const u8 { return w.buffered(); } +/// The MTP head file's width from its `__metadata__` quantization text (null: the stock head, 4-bit in groups of 64). +pub fn headOf(a: std.mem.Allocator, quantization: ?[]const u8) !Width { + const text = quantization orelse return .{}; + const doc = std.json.parseFromSliceLeaky(std.json.Value, a, text, .{}) catch return error.BadHeadWidth; + if (doc != .object) return error.BadHeadWidth; + const bits = doc.object.get("bits") orelse return error.BadHeadWidth; + const group = doc.object.get("group_size") orelse return error.BadHeadWidth; + if (bits != .integer or group != .integer) return error.BadHeadWidth; + if (doc.object.get("mode")) |m| if (m != .string or !std.mem.eql(u8, m.string, "affine")) return error.BadHeadWidth; + return .{ + .bits = std.math.cast(u8, bits.integer) orelse return error.BadHeadWidth, + .group = std.math.cast(u16, group.integer) orelse return error.BadHeadWidth, + }; +} + +/// The `__metadata__` quantization text of the safetensors file at `path`, or null when it states none. +pub fn headQuantization(a: std.mem.Allocator, io: std.Io, path: []const u8) !?[]const u8 { + var f = try std.Io.Dir.cwd().openFile(io, path, .{}); + defer f.close(io); + var lead: [8]u8 = undefined; + if (try f.readPositionalAll(io, &lead, 0) != 8) return error.BadHeader; + const n = std.mem.readInt(u64, &lead, .little); + if (n > 1 << 26) return error.BadHeader; + const text = try a.alloc(u8, @intCast(n)); + if (try f.readPositionalAll(io, text, 8) != n) return error.BadHeader; + return metadataQuantization(a, text); +} + +/// `__metadata__.quantization` of a safetensors header's JSON, or null. +pub fn metadataQuantization(a: std.mem.Allocator, header: []const u8) !?[]const u8 { + const doc = try std.json.parseFromSliceLeaky(std.json.Value, a, header, .{}); + if (doc != .object) return error.BadHeader; + const meta = doc.object.get("__metadata__") orelse return null; + if (meta != .object) return null; + const q = meta.object.get("quantization") orelse return null; + return if (q == .string) q.string else null; +} + const testing = std.testing; fn parsed(a: std.mem.Allocator, text: []const u8) !Config { @@ -132,3 +170,19 @@ test "a bf16 token table has no width: its matrix is unnamed, never unserved, an try testing.expectEqual(@as(?config.Named, null), unserved(&c, &buf)); try testing.expectEqualStrings("mlx-q4g64+bf16-embed", label(&c, &buf)); } + +test "the MTP head's width comes from its own metadata, the stock 4/64 when it states none" { + var arena: std.heap.ArenaAllocator = .init(testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + try testing.expectEqual(Width{ .bits = 4, .group = 64 }, try headOf(a, null)); + try testing.expectEqual(Width{ .bits = 4, .group = 64 }, try headOf(a, "{\"group_size\": 64, \"bits\": 4}")); + try testing.expectEqual(Width{ .bits = 8, .group = 32 }, try headOf(a, "{\"group_size\": 32, \"bits\": 8}")); + try testing.expectError(error.BadHeadWidth, headOf(a, "{\"bits\": 4}")); + try testing.expectError(error.BadHeadWidth, headOf(a, "{\"bits\": 4, \"group_size\": 64, \"mode\": \"mxfp4\"}")); + const header = "{\"__metadata__\": {\"format\": \"tensorfold-nemotron-mtp\", " ++ + "\"quantization\": \"{\\\"group_size\\\": 64, \\\"bits\\\": 4}\"}, \"a\": {}}"; + const q = (try metadataQuantization(a, header)).?; + try testing.expectEqual(Width{ .bits = 4, .group = 64 }, try headOf(a, q)); + try testing.expectEqual(@as(?[]const u8, null), try metadataQuantization(a, "{\"a\": {}}")); +} diff --git a/zig/src/families/nemotron/hip/worker.zig b/zig/src/families/nemotron/hip/worker.zig index 544dfc1e16d..df27d9e690b 100644 --- a/zig/src/families/nemotron/hip/worker.zig +++ b/zig/src/families/nemotron/hip/worker.zig @@ -64,10 +64,7 @@ pub const Worker = struct { if (n > ls.len) return error.WindowTooWide; var at: usize = 2; for (0..n) |i| { - if (at + 2 > m.len or m[at + 1] > lanes.max_window or at + 2 + m[ - at + - 1 - ] > m.len) return error.WindowTooWide; + if (at + 2 > m.len or m[at + 1] > w.h.e.window or at + 2 + m[at + 1] > m.len) return error.WindowTooWide; ls[i] = try f.lane(m[at]); toks[i] = m[at + 2 ..][0..m[at + 1]]; at += 2 + m[at + 1]; diff --git a/zig/src/families/qwen27/decode_round.zig b/zig/src/families/qwen27/decode_round.zig index 57b1bc273be..5ecf9077104 100644 --- a/zig/src/families/qwen27/decode_round.zig +++ b/zig/src/families/qwen27/decode_round.zig @@ -18,6 +18,7 @@ const Taps = @import("taps.zig").Taps; const image_rows = @import("image_rows.zig"); const mrope = @import("core").qwen_vl.rope; const kv_pages = @import("kv_pages.zig"); +const slot_pages = @import("slot_pages.zig"); pub const pagesOn = kv_pages.on; pub const KvPages = kv_pages.KvPages; pub const KvSpan = kv_pages.KvSpan; @@ -113,7 +114,7 @@ pub const Runner = struct { attention_index[m.config.layers] = na; na += 1; } - var pool = try GdnPool.init(m.device, try abi.Shape.init(m.config), ng, slots, m.frame.capacity); + var pool = try GdnPool.init(a, m.device, try abi.Shape.init(m.config), ng, slots, m.frame.capacity); errdefer pool.deinit(); const pipelines = @import("core").startup_receipt.span(.runtime_pipelines); const units = m.device.tensorUnits(); @@ -169,11 +170,10 @@ pub const Runner = struct { 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 }; } - /// Slot `slot` holds the pages of its first `rows` rows before a pass or a copy writes them (paged runners). - pub fn cover(r: *Runner, slot: u32, rows: u32) !void { - const k = r.kv orelse return; - try k.pages.cover(slot, @min(rows, r.capacity)); - } + pub const cover = slot_pages.cover; + pub const promise = slot_pages.promiseRows; + pub const release = slot_pages.release; + pub const reset = slot_pages.reset; /// Slot `slot`'s pages past its committed rows go back to its promise; no GPU work in flight reads them. fn trimSlot(r: *Runner, slot: u32) void { @@ -469,7 +469,8 @@ pub const Runner = struct { r.reading[slot] = cb.retain(); } - pub fn reset(r: *Runner, slot: u32) !void { + /// `reset` that keeps the slot's pages: a rewind writes its K/V rows again only from its rewind point on. + pub fn clearState(r: *Runner, slot: u32) !void { r.settleSlot(slot); if (r.failed or r.active != null or slot >= r.ready) return error.RoundNotReady; const pool = mtl.objc.Pool.push(); diff --git a/zig/src/families/qwen27/dflash/execution.zig b/zig/src/families/qwen27/dflash/execution.zig index e7cbe2a0288..78a3e84dd0e 100644 --- a/zig/src/families/qwen27/dflash/execution.zig +++ b/zig/src/families/qwen27/dflash/execution.zig @@ -109,7 +109,7 @@ fn encode(ops: op.Ops, g: *const w.Graph, preparation: op.Preparation, context: pub const Stream = struct { context: op.Context, anchor: u32 }; /// Every stream's block stacked in one pass, weights read once; each stream attends to its own context. -fn encodeStreams(ops: op.Ops, g: *const w.Graph, preparation: op.Preparation, streams: []const Stream, frame: u64, block: u32, given: []const u32) !Output { +pub fn encodeStreams(ops: op.Ops, g: *const w.Graph, preparation: op.Preparation, streams: []const Stream, frame: u64, block: u32, given: []const u32) !Output { const c = g.config; const n: u32 = @intCast(streams.len); const rows = n * block; diff --git a/zig/src/families/qwen27/dflash/execution_test.zig b/zig/src/families/qwen27/dflash/execution_test.zig index d21f3866a2e..a049b7ad188 100644 --- a/zig/src/families/qwen27/dflash/execution_test.zig +++ b/zig/src/families/qwen27/dflash/execution_test.zig @@ -397,6 +397,46 @@ test "qwen27 window: priced siblings match exhaustive expected accepted tokens p try std.testing.expectError(error.BadDraftCosts, selector.propose(a, &graph, lattice, 3, 2, .{ .nodes = 6, .costs = &invalid })); } +const Favour = struct { + token: u32, + seen: f64 = 0, + fn draw(ptr: *anyopaque, position: u64, token: u32) anyerror!f64 { + const f: *Favour = @ptrCast(@alignCast(ptr)); + f.seen += 1; + return if (position == 2 and token == f.token) 64 else 0; + } +}; + +test "qwen27 window: a sampled proposal's selection ranks its roots with the draw's noise" { + const a = std.testing.allocator; + var store = try fixtures.Store.init(a); + defer store.deinit(); + var graph = try store.graph(a); + defer graph.deinit(); + graph.config.topk = 16; + var fake: Fake = .{}; + var lattice = try Fake.lattice(&fake, 1, undefined, .{ .handle = 1, .rows = 2, .width = graph.config.rank, .stride = graph.config.rank, .dtype = .bf16 }, graph.config); + defer lattice.deinit(); + const model = @import("runtime_model.zig").Model; + const prices: [16]f64 = @splat(1); + var plain = try selector.propose(a, &graph, lattice, 3, 2, model.selection(.{ .context = null, .pending = 3, .nodes = 15, .costs = &prices })); + defer plain.deinit(); + // the last root the greedy ranking kept is the token the keyed draw is told to favour + var last: u32 = plain.tokens[0]; + for (plain.tokens, plain.parents) |token, parent| if (parent == -1) { + last = token; + }; + try std.testing.expect(last != plain.tokens[0]); + var favour: Favour = .{ .token = last }; + const sampled = model.selection(.{ .context = null, .pending = 3, .nodes = 15, .costs = &prices, .noise = .{ .ptr = &favour, .draw = Favour.draw }, .temperature = 0.5 }); + try std.testing.expectEqual(@as(f64, 0.5), sampled.temperature); + var tree = try selector.propose(a, &graph, lattice, 3, 2, sampled); + defer tree.deinit(); + try std.testing.expect(favour.seen > 0); + try std.testing.expectEqual(last, tree.tokens[0]); + try std.testing.expectEqual(@as(i32, -1), tree.parents[0]); +} + test "qwen27 window: lone callback retains the lane's wide sibling candidates" { const a = std.testing.allocator; var store = try fixtures.Store.init(a); diff --git a/zig/src/families/qwen27/dflash/runtime_frame.zig b/zig/src/families/qwen27/dflash/runtime_frame.zig index 29243e4a5bc..5998bdc9eee 100644 --- a/zig/src/families/qwen27/dflash/runtime_frame.zig +++ b/zig/src/families/qwen27/dflash/runtime_frame.zig @@ -34,6 +34,7 @@ pub const Frame = struct { residency: ?mtl.ResidencySet.Follow = null, profiler: ?*@import("core").gpu_profile.Trace = null, // TF_Q27_PROFILE: each pass's buffers time its `drafter` class hold: @import("core").gpu_profile.Hold = .{}, // while open, the trace's spans keep this frame's encoder + borrowed: bool = false, // open on another's buffer: its owner commits and waits for it pub fn setResident(f: *Frame, hook: ?mtl.ResidencySet.Follow) void { for (f.pool.items) |buffer| { if (f.residency) |h| h.leave(h.ctx, buffer); @@ -64,9 +65,30 @@ pub const Frame = struct { f.hold.take(f.profiler); // a span's own buffer would overtake this frame's pending ops return f.epoch; } + /// Opens on another's open buffer (a target window's): ops encode into its encoder, its owner commits and waits. + pub fn beginOn(f: *Frame, cb: mtl.CommandBuffer, encoder: mtl.ComputeEncoder) !u64 { + if (f.active or f.epoch >= 0x7fffffff) return error.DraftFrameBusy; + f.epoch += 1; + if (f.external_epoch != f.epoch) f.external = null; + f.cursor = 0; + f.entries.clearRetainingCapacity(); + f.cb = cb; + f.encoder = encoder; + f.active = true; + f.completed = false; + f.borrowed = true; + f.part_count = 0; + f.ops = 0; + return f.epoch; + } + /// A borrowed frame's owner saw its buffer complete: its outputs are readable until release. + pub fn landed(f: *Frame) !void { + if (!f.active or !f.borrowed or f.completed) return error.DraftFrameNotActive; + f.completed = true; + } /// Commits the work so far and opens the next buffer behind a fence, so the GPU starts early; between ops only. pub fn part(f: *Frame) !void { - if (!f.active or f.completed or f.part_count == f.parts.len) return; + if (!f.active or f.completed or f.borrowed or f.part_count == f.parts.len) return; if (f.fence == null) f.fence = mtl.objc.msg(?mtl.objc.Id, f.device.id, "newFence", .{}) orelse return error.NoFence; mtl.objc.msg(void, f.encoder.id, "updateFence:", .{f.fence.?}); f.encoder.end(); @@ -78,7 +100,7 @@ pub const Frame = struct { mtl.objc.msg(void, f.encoder.id, "waitForFence:", .{f.fence.?}); } pub fn finish(f: *Frame) !void { - if (!f.active or f.completed) return error.DraftFrameNotActive; + if (!f.active or f.completed or f.borrowed) return error.DraftFrameNotActive; f.encoder.end(); f.cb.commit(); f.cb.wait(); @@ -95,12 +117,13 @@ pub const Frame = struct { } } pub fn release(f: *Frame) void { - if (f.active and !f.completed) { + if (f.active and !f.completed and !f.borrowed) { f.encoder.end(); for (f.parts[0..f.part_count]) |cb| cb.wait(); // committed parts still use the pool } f.hold.release(); f.active = false; + f.borrowed = false; f.external = null; } pub fn require(f: *const Frame, epoch: u64) !void { diff --git a/zig/src/families/qwen27/dflash/runtime_model.zig b/zig/src/families/qwen27/dflash/runtime_model.zig index d419b5ee6c0..30a35f7978c 100644 --- a/zig/src/families/qwen27/dflash/runtime_model.zig +++ b/zig/src/families/qwen27/dflash/runtime_model.zig @@ -140,6 +140,8 @@ pub const Model = struct { overhead_ms: f64 = 0, defer_price: bool = true, chain: bool = false, + noise: ?selector.Noise = null, // a sampled stream's keyed draw noise for a token at a position + temperature: f64 = 1, }; /// The lane core prices complete candidate prefixes with its calibrated landing rates. pub fn selection(p: Proposal) selector.Options { @@ -147,6 +149,8 @@ pub const Model = struct { if (p.chain) options.children = 1; options.costs = if (p.defer_price) &.{} else p.costs; options.overhead_ms = if (p.defer_price) 0 else p.overhead_ms; + options.noise = p.noise; + options.temperature = p.temperature; return options; } /// A lone lane's full candidate tree, before the core prices its prefixes. diff --git a/zig/src/families/qwen27/gdn_pool_gpu.zig b/zig/src/families/qwen27/gdn_pool_gpu.zig index 5d8931162d3..4573c4a1233 100644 --- a/zig/src/families/qwen27/gdn_pool_gpu.zig +++ b/zig/src/families/qwen27/gdn_pool_gpu.zig @@ -9,6 +9,9 @@ const Ref = @import("projection.zig").Ref; const Tensor = @import("gpu_weights.zig").Tensor; const profile = @import("core").gpu_profile; const Kernels = @import("gdn_library.zig").Kernels; +/// The rollback bank is a lease from the recurrent scratch owner CUDA's windows use (core/recurrent_workspace.zig). +const Scratch = @import("core").recurrent_workspace.Workspace(metal.Buffer); +const queue = 0; // one pool, one queue: the model's pub const PromptMarks = @import("gdn_marks_gpu.zig").Bank; @@ -57,7 +60,9 @@ pub const Pool = struct { budget: Budget, buffers: [std.enums.values(Field).len]metal.Buffer, kernels: Kernels, - before: ?metal.Buffer = null, + before: ?metal.Buffer = null, // the leased bank's buffer, while `lease` holds it + scratch: Scratch, + lease: ?Scratch.Lease = null, marks: ?*PromptMarks = null, // borrowed through one synchronous plain prompt and its cache callbacks before_slots: usize = 0, profiler: ?*profile.Trace = null, @@ -71,13 +76,13 @@ pub const Pool = struct { } /// One state a slot: every round's keeps stay in their slots and update them in place. - pub fn init(device: metal.Device, shape: abi.Shape, layers: usize, slots: usize, capacity: usize) !Pool { + pub fn init(gpa: std.mem.Allocator, device: metal.Device, shape: abi.Shape, layers: usize, slots: usize, capacity: usize) !Pool { const budget = try Budget.init(shape, layers, slots, capacity); if (capacity % 16 != 0) return error.BadGdnProjectionCapacity; const buffers = try allocateBuffers(device, budget); errdefer for (buffers) |buffer| buffer.deinit(); const kernels = try Kernels.init(device); - return .{ .budget = budget, .buffers = buffers, .kernels = kernels }; + return .{ .budget = budget, .buffers = buffers, .kernels = kernels, .scratch = emptyScratch(gpa) }; } pub fn allocateBuffers(device: metal.Device, budget: Budget) !@FieldType(Pool, "buffers") { @@ -95,7 +100,7 @@ pub const Pool = struct { pub fn deinit(pool: *Pool) void { pool.setResident(null); - pool.releaseBefore(); + pool.deinitScratch(); pool.kernels.deinit(); for (pool.buffers) |buffer| buffer.deinit(); } @@ -110,21 +115,54 @@ pub const Pool = struct { // The old bank has no readers now; drop it first so growth never holds two rollback banks. pool.releaseBefore(); if (slots == 0) return; - pool.before = try device.buffer(bytes, metal.ResourceOptions.shared | metal.ResourceOptions.untracked); + const lease = try pool.scratch.acquire(queue, bytes, pool.provider(device)); // cap 0: idle banks go first + pool.scratch.markUsed(queue, lease) catch unreachable; + pool.lease = lease; + pool.before = pool.scratch.view(queue, lease) catch unreachable; pool.before_slots = slots; - if (pool.residency) |f| f.join(f.ctx, pool.before.?); + } + + /// The rollback bank's lease owner, empty: what a pool built field by field (tests) takes. + pub fn emptyScratch(gpa: std.mem.Allocator) Scratch { + return .init(gpa, queue); + } + + /// The bank and the lease owner's own list go: the pool's last use of its scratch. + pub fn deinitScratch(pool: *Pool) void { + pool.releaseBefore(); + pool.scratch.deinit(queue, pool.provider(null)) catch unreachable; // released and completed just above } /// No submitted work or pending keep may reference the bank when its owner calls this. pub fn releaseBefore(pool: *Pool) void { - if (pool.before) |buffer| { - if (pool.residency) |f| f.leave(f.ctx, buffer); - buffer.deinit(); - } + pool.scratch.complete(queue) catch unreachable; + if (pool.lease) |lease| pool.scratch.release(queue, lease) catch unreachable; + pool.scratch.collect(queue, pool.provider(null)) catch unreachable; + pool.lease = null; pool.before = null; pool.before_slots = 0; } + /// Allocates a bank into the residency set the pool follows, and takes it out before freeing it. + const Provider = struct { + device: ?metal.Device, // null: a release or collect, which never allocates + residency: ?metal.ResidencySet.Follow, + pub fn allocate(p: Provider, bytes: usize) !metal.Buffer { + const device = p.device orelse return error.NoGdnBeforeDevice; + const buffer = try device.buffer(bytes, metal.ResourceOptions.shared | metal.ResourceOptions.untracked); + if (p.residency) |f| f.join(f.ctx, buffer); + return buffer; + } + pub fn dispose(p: Provider, buffer: *metal.Buffer) void { + if (p.residency) |f| f.leave(f.ctx, buffer.*); + buffer.deinit(); + } + }; + + fn provider(pool: *const Pool, device: ?metal.Device) Provider { + return .{ .device = device, .residency = pool.residency }; + } + /// Reserve the still-unallocated peak bank beside prompt caches and future stream buffers. pub fn missingBeforeBytes(pool: *const Pool) usize { if (pool.budget.slots < 2 or pool.budget.shape.c.dk != 128 or pool.tree_mode == .snapshot) return 0; diff --git a/zig/src/families/qwen27/kv_pages.zig b/zig/src/families/qwen27/kv_pages.zig index 7bbf9bfc114..359f0a3f9aa 100644 --- a/zig/src/families/qwen27/kv_pages.zig +++ b/zig/src/families/qwen27/kv_pages.zig @@ -17,7 +17,7 @@ pub fn pagedLayout(config: anytype, attention_layers: usize) kv_pool.Layout { return .{ .fixed_bytes = 0, .token_bytes = attention_layers * 2 * config.kvDim() * 2, .page_tokens = kvp.page_tokens, .snap_bytes = 0 }; } -/// The pool's pages, arena and tables a paged runner holds; slot i is lane i, promised its whole capacity. +/// The pool's pages, arena and tables a paged runner holds; slot i is lane i, promised as its stream's rows come. pub const KvPages = struct { pages: *kvp.Pages, arena: mtl.Buffer, tables: mtl.Buffer }; /// A span of a slot's K/V rows in a buffer, as snapshot and digest copy and hash them. @@ -49,7 +49,7 @@ pub fn spans(r: anytype, a: std.mem.Allocator, slot: u32, at: u32, list: *std.Ar } } -/// The pool over `slots` lanes of `capacity` rows, every lane promised them; each layer's caches its part of a page. +/// The pool over `slots` lanes of `capacity` rows each at most; each layer's caches its part of a page. pub fn caches(a: std.mem.Allocator, m: *Model, layers: usize, slots: u32, capacity: u32, out: []attn.Cache) !KvPages { const l = pagedLayout(m.config, layers); const pages = @as(usize, slots) * l.pages(capacity); @@ -62,7 +62,6 @@ pub fn caches(a: std.mem.Allocator, m: *Model, layers: usize, slots: u32, capaci errdefer tables.deinit(); const p = try kvp.Pages.initIn(a, l, slots, pages, capacity, arena, tables); errdefer p.deinit(); - for (0..slots) |slot| try p.admit(slot, l.pages(capacity)); const part = @as(usize, kvp.page_tokens) * m.config.kvDim() * 2; for (0..layers) |layer| for (0..slots) |slot| { const table: Ref = .{ .buffer = tables, .offset = p.tables.offset(slot) }; diff --git a/zig/src/families/qwen27/qwen27.zig b/zig/src/families/qwen27/qwen27.zig index 86387b408d6..4f79d9f2190 100644 --- a/zig/src/families/qwen27/qwen27.zig +++ b/zig/src/families/qwen27/qwen27.zig @@ -75,6 +75,7 @@ test { _ = @import("weights_test.zig"); _ = @import("geometry_test.zig"); _ = @import("mtp_test.zig"); + _ = @import("slot_pages_test.zig"); } pub const residency = @import("residency.zig"); diff --git a/zig/src/families/qwen27/slot_pages.zig b/zig/src/families/qwen27/slot_pages.zig new file mode 100644 index 00000000000..b92fc1bf2cb --- /dev/null +++ b/zig/src/families/qwen27/slot_pages.zig @@ -0,0 +1,53 @@ +//! A paged slot's KV pages over its stream's life: promised as it opens, grown as rows come, given back as it goes. +const kvp = @import("core").metal_kv_pages; + +/// The stream opening lane `slot` is promised the pages of `rows` rows past those it holds; LaneMemory: not now. +pub fn promise(p: *kvp.Pages, slot: usize, rows: u64) !void { + const l = &p.leases[slot]; + p.pool.unpromise(l); + const need = p.layout.pages(rows); + if (need > l.ids.items.len) try p.admit(slot, need - l.ids.items.len); +} + +/// Lane `slot` holds the pages of `rows` rows; a pass past its promise promises the rest first (LaneMemory: none). +pub fn grow(p: *kvp.Pages, slot: usize, rows: u64) !void { + const l = &p.leases[slot]; + const short = p.layout.pages(rows) -| (l.ids.items.len + l.promised); + if (short > 0) try p.admit(slot, short); // fails before cover: no page taken, no table entry written + try p.cover(slot, rows); +} + +/// Lane `slot`'s stream left: every page and its promise go back, or with `kept`, the pages of those rows stay. +pub fn leave(p: *kvp.Pages, slot: usize, kept: ?u64) void { + const rows = kept orelse return p.finish(slot); + p.trim(slot, rows); + p.pool.unpromise(&p.leases[slot]); +} + +/// Lane `slot` starts over at row 0: its pages go back to its promise (a kept holder's page stays held). +pub fn startOver(p: *kvp.Pages, slot: usize) void { + p.trim(slot, 0); +} + +/// Runner.cover: slot `slot` holds the pages of its first `rows` rows before a pass or a copy writes them. +pub fn cover(r: anytype, slot: u32, rows: u32) !void { + if (r.kv) |k| try grow(k.pages, slot, @min(rows, r.capacity)); +} + +/// Runner.promise: a stream opens in slot `slot`, the pages of `rows` rows promised; LaneMemory: not now. +pub fn promiseRows(r: anytype, slot: u32, rows: u32) !void { + if (r.kv) |k| try promise(k.pages, slot, @min(rows, r.capacity)); +} + +/// Runner.release: slot `slot`'s stream left; `standing`, the pages of its committed rows stay for a resume. +pub fn release(r: anytype, slot: u32, standing: bool) void { + const k = r.kv orelse return; + if (!standing) r.settleSlot(slot); // a keep's blit still reading the slot lands before its pages go back + leave(k.pages, slot, if (standing) r.offsets[slot] else null); +} + +/// Runner.reset: slot `slot` starts over at row 0, its DeltaNet state cleared and its pages given back. +pub fn reset(r: anytype, slot: u32) !void { + try r.clearState(slot); + if (r.kv) |k| startOver(k.pages, slot); +} diff --git a/zig/src/families/qwen27/slot_pages_test.zig b/zig/src/families/qwen27/slot_pages_test.zig new file mode 100644 index 00000000000..814a9295664 --- /dev/null +++ b/zig/src/families/qwen27/slot_pages_test.zig @@ -0,0 +1,160 @@ +//! slot_pages over a host pool: promised on open, grown as rows come, every page and promise back as a stream goes. +const std = @import("std"); +const kvp = @import("core").metal_kv_pages; +const kv_pool = @import("core").kv_pool; +const sp = @import("slot_pages.zig"); +const t = std.testing; +const page = kvp.page_tokens; +const pass = 512; // one widest pass past a prompt, as qwen27_slots.promiseRows adds + +/// `lanes` lanes of `capacity` rows each at most over `pages` pages. +fn pool(lanes: usize, capacity: u32, pages: usize) !*kvp.Pages { + const l: kv_pool.Layout = .{ .fixed_bytes = 0, .token_bytes = 64, .page_tokens = page, .snap_bytes = 0 }; + return kvp.Pages.init(t.allocator, null, l, lanes, pages, capacity, 0); +} + +/// Nothing held, nothing promised, every page free. +fn empty(p: *kvp.Pages) !void { + const c = p.pool.census(); + try t.expect(p.idle()); + try t.expectEqual(c.total, c.free); + try t.expectEqual(@as(usize, 0), c.promised); +} + +test "two streams promised their prompts open on a pool short of two windows, each grows as its rows come" { + const window: u32 = 64 * page; + const p = try pool(2, window, 96); // one and a half windows + defer p.deinit(); + try sp.promise(p, 0, 20 * page + pass); + try sp.promise(p, 1, 30 * page + pass); + try sp.grow(p, 0, 20 * page); + try sp.grow(p, 1, 30 * page); + try sp.grow(p, 0, 40 * page); // a reply past its promise takes its pages as it writes them + try t.expectEqual(@as(usize, 40), p.ids(0).len); + for (0..2) |lane| try t.expectEqualSlices(u32, p.ids(lane), p.tables.entries(lane, p.ids(lane).len)); + for (0..2) |lane| sp.leave(p, lane, null); + try empty(p); +} + +test "two streams grow in turn to their whole windows, and leaving gives every page back" { + const capacity: u32 = 262144 + 16; // --context 262144 and a 16-row window + const p = try pool(2, capacity, 2 * ((capacity + page - 1) / page)); + defer p.deinit(); + try sp.promise(p, 0, 1000 + pass); + try sp.promise(p, 1, 30_000 + pass); + var rows = [2]u64{ 1000, 30_000 }; + for (0..2) |lane| try sp.grow(p, lane, rows[lane]); + while (rows[0] < capacity or rows[1] < capacity) for (0..2) |lane| { + rows[lane] = @min(rows[lane] + page, capacity); + try sp.grow(p, lane, rows[lane]); + try t.expectEqualSlices(u32, p.ids(lane), p.tables.entries(lane, p.ids(lane).len)); + }; + try t.expectEqual(@as(usize, 0), p.pool.census().free); // both windows whole: the pool's every page + for (0..2) |lane| sp.leave(p, lane, null); + try empty(p); +} + +test "a promise or a growth the pool cannot meet fails with LaneMemory before a page is taken or an entry written" { + const window: u32 = 32 * page; + const p = try pool(2, window, 40); + defer p.deinit(); + try sp.promise(p, 0, 30 * page); + try sp.grow(p, 0, 30 * page); + try t.expectError(error.LaneMemory, sp.promise(p, 1, 20 * page)); // 10 pages left + try t.expectEqual(@as(usize, 0), p.leases[1].promised); + try sp.promise(p, 1, 4 * page); + try sp.grow(p, 1, 4 * page); + const before = p.pool.census(); + const next = p.tables.entries(1, 5)[4]; + try t.expectError(error.LaneMemory, sp.grow(p, 1, 16 * page)); + try t.expectEqual(@as(usize, 4), p.ids(1).len); + try t.expectEqual(next, p.tables.entries(1, 5)[4]); // its next entry as it was + try t.expectEqual(before.free, p.pool.census().free); + try t.expectEqual(before.promised, p.pool.census().promised); + for (0..2) |lane| sp.leave(p, lane, null); + try empty(p); +} + +test "a stream that leaves mid-prompt, cancelled or failed, gives every page and its promise back" { + const p = try pool(2, 16 * page, 32); + defer p.deinit(); + try sp.promise(p, 1, 3 * page); + try sp.grow(p, 1, 3 * page); + try sp.promise(p, 0, 12 * page + pass); + try sp.grow(p, 0, 5 * page); // five of its twelve prompt pages written + sp.leave(p, 0, null); + try t.expectEqual(@as(usize, 0), p.ids(0).len); + try t.expectEqual(@as(usize, 0), p.leases[0].promised); + try t.expectEqual(@as(usize, 3), p.ids(1).len); // the other stream keeps its own + sp.leave(p, 1, null); + try empty(p); +} + +test "a reset mid-prompt gives the slot's pages back before the new prompt takes its own; a kept holder's page stays" { + const p = try pool(2, 4 * page, 8); + defer p.deinit(); + try sp.promise(p, 0, 3 * page); + try sp.grow(p, 0, 3 * page); + var old: [3]u32 = undefined; + @memcpy(&old, p.ids(0)); + p.pool.retain(old[1]); // a kept state's hold on one of them + sp.startOver(p, 0); + try t.expectEqual(@as(usize, 0), p.ids(0).len); + try t.expectEqual(@as(u32, 0), p.pool.holders(old[0])); + try t.expectEqual(@as(u32, 1), p.pool.holders(old[1])); + try t.expectEqual(@as(u32, 0), p.pool.holders(old[2])); + try sp.promise(p, 0, 2 * page); // the new prompt + try sp.grow(p, 0, 2 * page); + for (p.ids(0)) |id| try t.expect(id != old[1]); + try t.expectEqual(@as(usize, 2), p.ids(0).len); + sp.leave(p, 0, null); + p.pool.release(old[1]); + try empty(p); +} + +test "a stream moving to slot 0 leaves its old slot empty and unpromised; slot 0 holds its rows" { + const p = try pool(2, 16 * page, 24); + defer p.deinit(); + try sp.promise(p, 0, 6 * page); + try sp.grow(p, 0, 6 * page); + try sp.promise(p, 1, 8 * page + pass); + try sp.grow(p, 1, 8 * page); + sp.leave(p, 0, null); // slot 0's reply ended + try sp.grow(p, 0, 8 * page); // qwen27_slots.promote: the copy covers slot 0 first + sp.leave(p, 1, null); + try sp.promise(p, 0, 8 * page + pass); + try t.expectEqual(@as(usize, 0), p.ids(1).len); + try t.expectEqual(@as(usize, 0), p.leases[1].promised); + try t.expectEqual(@as(usize, 8), p.ids(0).len); + try t.expectEqual(@as(usize, 2), p.leases[0].promised); + sp.leave(p, 0, null); + try empty(p); +} + +test "a reply that finds no page mid-run fails its growth; its round's streams leave and no page or promise stays" { + const p = try pool(2, 32 * page, 36); + defer p.deinit(); + try sp.promise(p, 0, 20 * page + pass); + try sp.grow(p, 0, 20 * page); + try sp.promise(p, 1, 12 * page + pass); + try sp.grow(p, 1, 12 * page); + try sp.grow(p, 0, 22 * page); + try t.expectError(error.LaneMemory, sp.grow(p, 1, 16 * page)); // Runner.cover in the round fails the verify + for (0..2) |lane| sp.leave(p, lane, null); // lane_host_end.failRound ends both; each unbind releases its slot + try empty(p); +} + +test "a standing slot 0 keeps the pages of its committed rows, nothing past them and no promise" { + const p = try pool(2, 16 * page, 16); + defer p.deinit(); + try sp.promise(p, 0, 6 * page + pass); + try sp.grow(p, 0, 8 * page); + sp.leave(p, 0, 6 * page + 9); // its rows stay for the next prompt's resume + try t.expectEqual(@as(usize, 7), p.ids(0).len); + try t.expectEqual(@as(usize, 0), p.leases[0].promised); + try t.expectEqual(@as(usize, 0), p.pool.census().promised); + try sp.promise(p, 0, 7 * page + pass); // the resume's promise counts the pages it holds + try t.expectEqual(@as(usize, 2), p.leases[0].promised); + sp.leave(p, 0, null); + try empty(p); +} diff --git a/zig/src/families/qwen27/snapshot.zig b/zig/src/families/qwen27/snapshot.zig index 660d0bce0af..695e712bc08 100644 --- a/zig/src/families/qwen27/snapshot.zig +++ b/zig/src/families/qwen27/snapshot.zig @@ -293,7 +293,7 @@ pub fn saveRewind(a: std.mem.Allocator, r: *const Runner, slot: u32, ring: ?Ring /// Slot `slot` (reset first) goes back to its rewind point at `at`: no later round wrote its K/V rows before `at`. pub fn rewindSlot(a: std.mem.Allocator, r: *Runner, slot: u32, ring: ?Ring, at: u32, buf: mtl.Buffer) !void { - try r.reset(slot); + try r.clearState(slot); // its pages stay: rows before `at` are the rewind's try rewindCopy(a, r, slot, ring, at, buf, false); r.offsets[slot] = at; if (ring) |g| g.end.* = at; diff --git a/zig/src/families/qwen3_5/backend.zig b/zig/src/families/qwen3_5/backend.zig index 6ffe0fedd3c..62345a3bee7 100644 --- a/zig/src/families/qwen3_5/backend.zig +++ b/zig/src/families/qwen3_5/backend.zig @@ -17,6 +17,7 @@ test "zero grant: an attached Qwen drafter resumes after a long shared skip" { try lanes.shared_draft_check.check(b.facts(), true); } const snapshot = @import("snapshot.zig"); +const prefill = @import("prefill.zig"); pub const Options = struct { capacity: usize, chunk: usize = 128, streams: u32 = 8 }; @@ -30,6 +31,7 @@ pub const Metal = struct { caches: std.AutoHashMapUnmanaged(*lanes.Stream, *st.Cache) = .empty, pages: ?*kvp.Pages = null, // TF_QWEN35_METAL_KV_PAGES=1: the streams' keys and values in the core pool's pages taken: []bool = &.{}, // a lane a paged stream holds + fills: std.AutoHashMapUnmanaged(*lanes.Stream, usize) = .empty, // each stepped prompt pass's next row (#3021) pub fn init(gpa: std.mem.Allocator, model: *Model, options: Options) !*Metal { const out = try gpa.create(Metal); @@ -55,6 +57,7 @@ pub const Metal = struct { self.gpa.destroy(cache.*); } self.caches.deinit(self.gpa); + self.fills.deinit(self.gpa); if (self.pages) |p| p.deinit(); self.gpa.free(self.taken); self.scratch.deinit(); @@ -66,7 +69,7 @@ pub const Metal = struct { } pub fn backend(self: *Metal) be.Backend { - return .{ .ptr = self, .vtable = &.{ .prefill = prefillFn, .first = firstFn, .first_masked = firstMaskedFn, .queue = queueFn, .read = readFn, .verify = verifyFn, .keep = keepFn, .draft = draftFn, .release = releaseFn, .reports_fill = true } }; + return .{ .ptr = self, .vtable = &.{ .prefill = prefillFn, .prefill_step = prefillStepFn, .cancel_prefill = cancelPrefillFn, .first = firstFn, .first_masked = firstMaskedFn, .queue = queueFn, .read = readFn, .verify = verifyFn, .keep = keepFn, .draft = draftFn, .release = releaseFn, .reports_fill = true } }; } fn cast(ptr: *anyopaque) *Metal { @@ -103,6 +106,13 @@ pub const Metal = struct { fn prefillFn(ptr: *anyopaque, stream: *lanes.Stream) !void { const self = cast(ptr); + const cache = try self.opening(stream); + errdefer self.drop(stream); + try prefill.run(cache, stream, self.options.chunk, self, promptChunk); + } + + /// The prompt checked, a lane admitted (paged) and the stream's cache made: what a pass runs on. + fn opening(self: *Metal, stream: *lanes.Stream) !*st.Cache { const ids = stream.prompt(); if (ids.len == 0 or ids.len + stream.max_new > self.options.capacity or self.caches.contains(stream)) return error.InvalidQwenPrompt; const capacity = @min(self.options.capacity, ids.len + stream.max_new + st.window_rows); @@ -112,8 +122,37 @@ pub const Metal = struct { errdefer self.gpa.destroy(cache); errdefer cache.deinit(); try self.caches.put(self.gpa, stream, cache); - errdefer _ = self.caches.remove(stream); - try @import("prefill.zig").run(cache, stream, self.options.chunk, self, promptChunk); + return cache; + } + + /// One chunk a call at the whole pass's cuts, each through promptChunk (no chunk_invariant: `max_rows` unused). + fn prefillStepFn(ptr: *anyopaque, stream: *lanes.Stream, _: u32) !bool { + const self = cast(ptr); + if (!self.fills.contains(stream)) { + const cache = try self.opening(stream); + errdefer self.drop(stream); + try self.fills.put(self.gpa, stream, prefill.open(cache, stream)); + } + errdefer self.drop(stream); + const done = try prefill.step(try self.cacheOf(stream), stream, self.fills.getPtr(stream).?, self.options.chunk, self, promptChunk); + if (done) _ = self.fills.remove(stream); + return done; + } + + /// The host cancels between chunks: the state at the last chunk's end is kept (no prompt work runs). + fn cancelPrefillFn(ptr: *anyopaque, stream: *lanes.Stream) !void { + const self = cast(ptr); + if (self.fills.get(stream)) |at| stream.keepInterruptedPrefill(@intCast(at)); + } + + /// A pass that failed, or a stream that leaves (mid-pass too): its row, lane and cache go. + fn drop(self: *Metal, stream: *lanes.Stream) void { + _ = self.fills.remove(stream); + if (self.caches.fetchRemove(stream)) |entry| { + if (entry.value.paged) |p| leaveLane(self, p.lane); + entry.value.deinit(); + self.gpa.destroy(entry.value); + } } fn promptChunk(self: *Metal, cache: *st.Cache, ids: []const u32) !void { @@ -195,12 +234,7 @@ pub const Metal = struct { } fn releaseFn(ptr: *anyopaque, stream: *lanes.Stream) void { - const self = cast(ptr); - if (self.caches.fetchRemove(stream)) |entry| { - if (entry.value.paged) |p| leaveLane(self, p.lane); - entry.value.deinit(); - self.gpa.destroy(entry.value); - } + cast(ptr).drop(stream); } }; 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 04dbc827ba5..af8589ed32f 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 @@ -179,8 +179,8 @@ pub const Hip = struct { /// The facts the round loop reads at setup: shared rounds of exact windows, and the MTP head's batched chains. pub fn facts(h: *const Hip) lanes.Model { const drafting = h.head != null and h.e.o.policy.mtp.drafts > 0; - // plain rounds compete with drafted ones once the forwards are timed - const plain_guard = drafting and h.costs.windows > 0; + // plain rounds compete with drafted or copy-only ones once the forwards are timed + const plain_guard = h.costs.windows > 0; return .{ .exact_width = max_window, .gpu_tokens = false, @@ -522,3 +522,19 @@ test "Qwen HIP image begin receives the stream's original cancellation hook" { stopped = true; try std.testing.expectError(error.Cancelled, serve.cancel.poll(hook)); } + +test "Qwen HIP facts price plain rounds for a copies-only engine" { + var engine: Engine = undefined; + engine.o = .{}; + engine.o.policy.mtp.drafts = 3; + var h: Hip = undefined; + h.e = &engine; + h.head = null; + h.costs = .{}; + h.costs.windows = 1; + h.costs.window[0] = .{ .width = 1, .ms = 1 }; + const facts = h.facts(); + try std.testing.expect(facts.plain_guard); + try std.testing.expect(facts.copy_guard); + try std.testing.expect(!facts.mtp and !facts.speculate and !facts.draft_streams); +} diff --git a/zig/src/families/qwen3_5/cuda.zig b/zig/src/families/qwen3_5/cuda.zig index d472f112049..aeef751d903 100644 --- a/zig/src/families/qwen3_5/cuda.zig +++ b/zig/src/families/qwen3_5/cuda.zig @@ -49,6 +49,7 @@ test { _ = @import("cuda_pages.zig"); _ = @import("cuda_penalties.zig"); _ = @import("cuda_pages_init_test.zig"); + _ = @import("cuda_kv_host_test.zig"); _ = @import("cuda_pages_lifetime_test.zig"); _ = @import("cuda_mtp_area_test.zig"); _ = @import("cuda_prefix.zig"); diff --git a/zig/src/families/qwen3_5/cuda_engine.zig b/zig/src/families/qwen3_5/cuda_engine.zig index 36205cb83be..2a85221e456 100644 --- a/zig/src/families/qwen3_5/cuda_engine.zig +++ b/zig/src/families/qwen3_5/cuda_engine.zig @@ -58,10 +58,11 @@ pub const Keep = union(enum) { logits, hidden, rows, + none, // a prompt chunk nothing reads: its last layer stops at the state writes - /// Whether the forward is a verify window (recorded, one-row bits); `last` and `rows` are prompt chunks. + /// Whether the forward is a verify window (recorded, one-row bits); `last`, `rows` and `none` are prompt chunks. pub fn verifies(k: Keep) bool { - return k != .last and k != .rows; + return k != .last and k != .rows and k != .none; } }; @@ -386,12 +387,18 @@ pub const Engine = struct { } pub fn run(e: *Engine, f: cuda.Function, grid: [3]usize, block: [3]usize, args: anytype) !void { + if (@import("cuda_launch_trace.zig").active) |t| return t.note(.{ .launch = if (f.handle) |h| @intFromPtr(h) else 0 }); var a: cuda.Args = .{}; inline for (args) |v| a.add(v); const cfg: cuda.Config = .{ .grid = .{ .x = @intCast(grid[0]), .y = @intCast(grid[1]), .z = @intCast(grid[2]) }, .block = .{ .x = @intCast(block[0]), .y = @intCast(block[1]), .z = @intCast(block[2]) } }; try cuda.launch.launch(f, cfg, e.stream, &a); } + pub fn promptAttention(e: *Engine, layer: usize, from: usize, end: usize) !void { + if (@import("cuda_launch_trace.zig").active) |t| return t.note(.attn); + return @import("cuda_prompt.zig").runFrom(e, layer, from, end); + } + /// The projections: the row tiles, the prompt GEMM and the grouped form, in their own file. pub const proj = @import("cuda_projection.zig").proj; pub const projSums = @import("cuda_projection.zig").projSums; @@ -421,6 +428,7 @@ pub const Engine = struct { } pub fn norm(e: *Engine, residual: bool, w: u64, rows: usize) !void { + if (@import("cuda_launch_trace.zig").active) |t| return t.note(.norm); try e.run(if (e.g.bf16) e.fns.norm_shift else e.fns.norm, .{ rows, 1, 1 }, .{ 256, 1, 1 }, .{ e.h, if (residual) e.r else @as(u64, 0), w, e.x, e.g.eps, @as(c_int, @intCast(e.g.hidden)), e.tables.ptr + params_at, e.xs }); } @@ -512,6 +520,7 @@ pub const Engine = struct { }; shape.hidden = keep == .hidden; shape.rows = keep == .rows; + shape.unread = keep == .none; shape.paged = @import("cuda_attention.zig").hasPages(segs); shape.join = shape.paged and caches.anyShares(parts); shape.mt2 = @import("cuda_shapes.zig").useMt2(e.mt2.enabled, e.kv8, !record, total, parts.len, parts[0].cache.len); @@ -552,6 +561,7 @@ pub const Engine = struct { @memcpy(e.tokens[0..total], e.host_logits.slice(u32)[0..total]); }, .rows => {}, // the rows stay in `x` for the readout that runs next on the stream + .none => {}, // nothing to copy back .logits, .last => { const out = e.host_logits.bytes[0 .. heads * g.vocab * 2]; try e.d.check(e.d.api.cuMemcpyDtoHAsync_v2(out.ptr, e.logits, out.len, e.stream.handle), "cuMemcpyDtoHAsync"); @@ -568,21 +578,7 @@ pub const Engine = struct { /// One shape's launches: uncaptured for a prompt chunk or the exact path, else its captured graph replayed. pub const launchShape = @import("cuda_shapes.zig").launch; - /// The same scan selected by body, exposed for host launch-contract fixtures. - pub fn deltaScan(e: *Engine, record: bool, slot_count: u8, segments: usize, layer: c_int) !void { - const scan = if (!record) e.fns.gdn_chain else switch (slot_count) { - 1 => e.fns.gdn_slots_1, - 2 => e.fns.gdn_slots_2, - 4 => e.fns.gdn_slots_4, - 8 => e.fns.gdn_slots_8, - 16 => e.fns.gdn_slots_16, - else => return error.InvalidGdnSlots, - }; - const input = e.tables.ptr + @as(usize, if (record) Round.steps_at else rowpar_at); - // qwen35_slots.cuh: up to four slots scan two value rows a warp, so a block covers eight - const rows_a_warp: usize = if (record and slot_count <= 4) 2 else 1; - try e.run(scan, .{ 1, geometry.dk / (4 * rows_a_warp), e.g.v_heads * segments }, .{ 32, 4, 1 }, .{ e.geo, e.q, e.k, e.v, e.g_, e.beta, e.tables.ptr + segs_at, input, layer, e.y, e.tables.ptr + params_at }); - } + pub const deltaScan = @import("cuda_forward.zig").deltaScan; /// The launches of a forward of `shape`, from the embedding to the kept rows' logits (captured once a shape). pub const body = @import("cuda_forward.zig").body; diff --git a/zig/src/families/qwen3_5/cuda_exl3_admit.zig b/zig/src/families/qwen3_5/cuda_exl3_admit.zig index 9c93fcfddee..780fa88e536 100644 --- a/zig/src/families/qwen3_5/cuda_exl3_admit.zig +++ b/zig/src/families/qwen3_5/cuda_exl3_admit.zig @@ -3,33 +3,47 @@ const std = @import("std"); const core = @import("core"); const cuda = @import("cuda"); const mul1_magic: u32 = 0x83DCD12D; +const mcg_magic: u32 = 0xCBAC1FED; fn name(buf: []u8, comptime fmt: []const u8, args: anytype) ![]const u8 { return std.fmt.bufPrint(buf, fmt, args); } -/// One EXL3 group's tensors, checked: trellis [k/16][n/16][16 * bits] i16, the mul1 marker, fp16 suh [k] and svh [n]. -pub const Group = struct { trellis: core.checkpoint.Tensor, suh: core.checkpoint.Tensor, svh: core.checkpoint.Tensor, halves: u32 }; +/// One EXL3 group's tensors: trellis [k/16][n/16][16*bits] i16, a mul1/mcg marker, fp16 suh [k] and svh [n]. +pub const Group = struct { trellis: core.checkpoint.Tensor, suh: core.checkpoint.Tensor, svh: core.checkpoint.Tensor, halves: u32, codebook: cuda.exl3.Codebook }; pub fn group(ck: *core.Checkpoint, base: []const u8, n: usize, k: usize) !Group { if (n == 0 or k == 0 or n % 128 != 0 or k % 128 != 0 or n > std.math.maxInt(u32) or k > std.math.maxInt(u32)) return error.UnexpectedTensor; var buf: [240]u8 = undefined; + var mcg_buf: [240]u8 = undefined; const t = try ck.get(try name(&buf, "{s}.trellis", .{base})); if (t.dtype != .i16 or t.rank != 3 or t.dim(0) != k / 16 or t.dim(1) != n / 16 or t.dim(2) % 8 != 0) { return error.UnexpectedTensor; } const halves = t.dim(2) / 8; if (halves < 2 or halves > 16) return error.UnsupportedQwenQuantization; - const marker = try ck.get(try name(&buf, "{s}.mul1", .{base})); - if ((marker.dtype != .i32 and marker.dtype != .u32) or marker.numel() != 1 or marker.bytes.len != 4 or std.mem.readInt(u32, marker.bytes[0..4], .little) != mul1_magic) return error.UnsupportedQwenQuantization; + // Accept .mul1 (magic 0x83DCD12D) or .mcg (magic 0xCBAC1FED); exactly one marker tensor per group. + const mul1_name = try name(&buf, "{s}.mul1", .{base}); + const mcg_name = try name(&mcg_buf, "{s}.mcg", .{base}); + if (ck.has(mul1_name) and ck.has(mcg_name)) return error.UnsupportedQwenQuantization; + const cb: cuda.exl3.Codebook = if (ck.has(mul1_name)) blk: { + const marker = try ck.get(mul1_name); + if ((marker.dtype != .i32 and marker.dtype != .u32) or marker.numel() != 1 or marker.bytes.len != 4 or std.mem.readInt(u32, marker.bytes[0..4], .little) != mul1_magic) return error.UnsupportedQwenQuantization; + break :blk .mul1; + } else blk: { + if (!ck.has(mcg_name)) return error.UnsupportedQwenQuantization; + const marker = try ck.get(mcg_name); + if ((marker.dtype != .i32 and marker.dtype != .u32) or marker.numel() != 1 or marker.bytes.len != 4 or std.mem.readInt(u32, marker.bytes[0..4], .little) != mcg_magic) return error.UnsupportedQwenQuantization; + break :blk .mcg; + }; const suh = try ck.get(try name(&buf, "{s}.suh", .{base})); const svh = try ck.get(try name(&buf, "{s}.svh", .{base})); if (!suh.is(.f16, &.{k}) or !svh.is(.f16, &.{n})) return error.UnexpectedTensor; - return .{ .trellis = t, .suh = suh, .svh = svh, .halves = @intCast(halves) }; + return .{ .trellis = t, .suh = suh, .svh = svh, .halves = @intCast(halves), .codebook = cb }; } /// Dense projections must also have a compiled linear variant. pub fn denseGroup(ck: *core.Checkpoint, base: []const u8, n: usize, k: usize) !Group { const g = try group(ck, base, n, k); - if (cuda.exl3.variantIndex(g.halves, .mul1, 4) == null) return error.UnsupportedQwenQuantization; + if (cuda.exl3.variantIndex(g.halves, g.codebook, 4) == null) return error.UnsupportedQwenQuantization; return g; } diff --git a/zig/src/families/qwen3_5/cuda_exl3_loader_test.zig b/zig/src/families/qwen3_5/cuda_exl3_loader_test.zig index 73c9a5940b2..621eb0dc849 100644 --- a/zig/src/families/qwen3_5/cuda_exl3_loader_test.zig +++ b/zig/src/families/qwen3_5/cuda_exl3_loader_test.zig @@ -82,3 +82,79 @@ test "EXL3 admission: mixed supported widths and allocator failures stay host ow try write(tmp.dir, .{ .scale = "F32" }); try t.expectError(error.UnexpectedTensor, read(t.allocator, path)); } + +// --- Stage 6c: mcg codebook admission tests --- + +const cuda_exl3 = @import("cuda").exl3; + +fn writeMcg(dir: std.Io.Dir, halves: usize, magic: u32) !void { + const tn = 8 * 8 * halves * 8 * 2; + const sn: usize = 256; + const header = try std.fmt.allocPrint(t.allocator, "{{\"p.trellis\":{{\"dtype\":\"I16\",\"shape\":[8,8,{d}],\"data_offsets\":[0,{d}]}}," ++ + "\"p.mcg\":{{\"dtype\":\"I32\",\"shape\":[],\"data_offsets\":[{d},{d}]}}," ++ + "\"p.suh\":{{\"dtype\":\"F16\",\"shape\":[128],\"data_offsets\":[{d},{d}]}}," ++ + "\"p.svh\":{{\"dtype\":\"F16\",\"shape\":[128],\"data_offsets\":[{d},{d}]}}}}", .{ halves * 8, tn, tn, tn + 4, tn + 4, tn + 4 + sn, tn + 4 + sn, tn + 4 + sn + 256 }); + defer t.allocator.free(header); + const data = try t.allocator.alloc(u8, 8 + header.len + tn + 4 + sn + 256); + defer t.allocator.free(data); + @memset(data, 0); + std.mem.writeInt(u64, data[0..8], header.len, .little); + @memcpy(data[8..][0..header.len], header); + std.mem.writeInt(u32, data[8 + header.len + tn ..][0..4], magic, .little); + try dir.writeFile(t.io, .{ .sub_path = "model.safetensors", .data = data }); +} + +test "EXL3 admission: an mcg-codebook group admits and reports codebook .mcg" { + var tmp = t.tmpDir(.{}); + defer tmp.cleanup(); + const path = try pathOf(tmp); + defer t.allocator.free(path); + try writeMcg(tmp.dir, 16, 0xCBAC1FED); + var ck = try core.Checkpoint.openModel(t.allocator, t.io, path); + defer ck.close(); + const g = try admit.group(&ck, "p", 128, 128); + try t.expectEqual(cuda_exl3.Codebook.mcg, g.codebook); + try t.expectEqual(@as(u32, 16), g.halves); + _ = try admit.denseGroup(&ck, "p", 128, 128); +} + +test "EXL3 admission: an mcg marker with the wrong magic is refused" { + var tmp = t.tmpDir(.{}); + defer tmp.cleanup(); + const path = try pathOf(tmp); + defer t.allocator.free(path); + try writeMcg(tmp.dir, 16, 0xDEADBEEF); + var ck = try core.Checkpoint.openModel(t.allocator, t.io, path); + defer ck.close(); + try t.expectError(error.UnsupportedQwenQuantization, admit.group(&ck, "p", 128, 128)); +} + +fn writeBoth(dir: std.Io.Dir, halves: usize) !void { + const tn = 8 * 8 * halves * 8 * 2; + const sn: usize = 256; + const header = try std.fmt.allocPrint(t.allocator, "{{\"p.trellis\":{{\"dtype\":\"I16\",\"shape\":[8,8,{d}],\"data_offsets\":[0,{d}]}}," ++ + "\"p.mul1\":{{\"dtype\":\"I32\",\"shape\":[],\"data_offsets\":[{d},{d}]}}," ++ + "\"p.mcg\":{{\"dtype\":\"I32\",\"shape\":[],\"data_offsets\":[{d},{d}]}}," ++ + "\"p.suh\":{{\"dtype\":\"F16\",\"shape\":[128],\"data_offsets\":[{d},{d}]}}," ++ + "\"p.svh\":{{\"dtype\":\"F16\",\"shape\":[128],\"data_offsets\":[{d},{d}]}}}}", .{ halves * 8, tn, tn, tn + 4, tn + 4, tn + 8, tn + 8, tn + 8 + sn, tn + 8 + sn, tn + 8 + sn + 256 }); + defer t.allocator.free(header); + const data = try t.allocator.alloc(u8, 8 + header.len + tn + 8 + sn + 256); + defer t.allocator.free(data); + @memset(data, 0); + std.mem.writeInt(u64, data[0..8], header.len, .little); + @memcpy(data[8..][0..header.len], header); + std.mem.writeInt(u32, data[8 + header.len + tn ..][0..4], 0x83DCD12D, .little); + std.mem.writeInt(u32, data[8 + header.len + tn + 4 ..][0..4], 0xCBAC1FED, .little); + try dir.writeFile(t.io, .{ .sub_path = "model.safetensors", .data = data }); +} + +test "EXL3 admission: a group carrying both mul1 and mcg markers is refused" { + var tmp = t.tmpDir(.{}); + defer tmp.cleanup(); + const path = try pathOf(tmp); + defer t.allocator.free(path); + try writeBoth(tmp.dir, 16); + var ck = try core.Checkpoint.openModel(t.allocator, t.io, path); + defer ck.close(); + try t.expectError(error.UnsupportedQwenQuantization, admit.group(&ck, "p", 128, 128)); +} diff --git a/zig/src/families/qwen3_5/cuda_exl3_weights.zig b/zig/src/families/qwen3_5/cuda_exl3_weights.zig index def3e5579b3..491688c51ac 100644 --- a/zig/src/families/qwen3_5/cuda_exl3_weights.zig +++ b/zig/src/families/qwen3_5/cuda_exl3_weights.zig @@ -138,7 +138,7 @@ fn dense(s: *Sink, kit: ?*Kit, ck: *core.Checkpoint, prefix: []const u8, mod: [] .k = @intCast(k), .n = @intCast(n), .halves = gr.halves, - .codebook = .mul1, + .codebook = gr.codebook, .stride_k = st.k, .stride_nb = st.nb, }; @@ -180,6 +180,7 @@ fn experts(s: *Sink, ck: *core.Checkpoint, p: []const u8) !cuda.experts.Layer { var suh: [3]u64 = undefined; var svh: [3]u64 = undefined; var buf: [200]u8 = undefined; + var expert_cb: ?cuda.exl3.Codebook = null; for (mods, 0..) |mod, m| { const k = if (m == 2) g.intermediate else g.hidden; const n = if (m == 2) g.hidden else g.intermediate; @@ -194,6 +195,11 @@ fn experts(s: *Sink, ck: *core.Checkpoint, p: []const u8) !cuda.experts.Layer { for (0..count) |e| { const base = if (e < g.experts) try name(&buf, "{s}mlp.experts.{d}.{s}", .{ p, e, mod }) else try name(&buf, "{s}mlp.shared_expert.{s}", .{ p, mod }); const gr = try group(ck, base, n, k); + if (expert_cb) |ecb| { + if (ecb != gr.codebook) return error.UnsupportedQwenQuantization; + } else { + expert_cb = gr.codebook; + } tp[e] = try s.put(gr.trellis.bytes); widths[e] = @intCast(gr.halves); @memcpy(su[e * k * 2 ..][0 .. k * 2], gr.suh.bytes); @@ -220,7 +226,7 @@ fn experts(s: *Sink, ck: *core.Checkpoint, p: []const u8) !cuda.experts.Layer { .experts = count, .dims = g.hidden, .width = g.intermediate, - .codebook = .mul1, + .codebook = expert_cb orelse return error.UnsupportedQwenQuantization, .limit = 0, // Qwen's SwiGLU is unclamped .act_mode = 1, // fp32 silu(gate) * up }; diff --git a/zig/src/families/qwen3_5/cuda_forward.zig b/zig/src/families/qwen3_5/cuda_forward.zig index 1730be80f1f..aceb5594fbc 100644 --- a/zig/src/families/qwen3_5/cuda_forward.zig +++ b/zig/src/families/qwen3_5/cuda_forward.zig @@ -52,9 +52,11 @@ pub fn body(e: *E.Engine, shape: anytype) !void { var ai: c_int = 0; // a prompt chunk keeps its last row: past the last layer's keys and values, the kept row's tile runs alone const ends = g.whole == 0 or g.first + g.layers == g.whole; // an earlier stage sends every row on: no tail - const tail_at: ?usize = if (prompt and ends) @import("cuda_prompt_tail.zig").first(e, total, nseg, shape.hidden or shape.rows) else null; + const unread = prompt and ends and shape.unread; // nothing reads this chunk: its last layer stops after its keys and values + const tail_at: ?usize = if (prompt and ends and !unread) @import("cuda_prompt_tail.zig").first(e, total, nseg, shape.hidden or shape.rows) else null; for (e.layers, 0..) |l, i| { - const tail = tail_at != null and i + 1 == e.layers.len; + const last_layer = i + 1 == e.layers.len; + const tail = last_layer and tail_at != null; const t0: usize = if (tail) tail_at.? else 0; const rows: usize = total - t0; try e.norm(g.first + i != 0, l.input_norm, total); @@ -74,18 +76,19 @@ pub fn body(e: *E.Engine, shape: anytype) !void { }, .attention => |m| { const aw = g.attnWidth(); - if (tail) { + if (tail or (unread and last_layer)) { try e.projManyPrompt(&.{ m.k, m.v }, e.x, &.{ e.kraw, e.vraw }, total, prompt); - try e.projAgain(m.q, e.x + t0 * g.hidden * 2, e.qraw + t0 * 2 * aw * 2, rows, prompt); + if (tail) try e.projAgain(m.q, e.x + t0 * g.hidden * 2, e.qraw + t0 * 2 * aw * 2, rows, prompt); } else try e.projManyPrompt(&.{ m.q, m.k, m.v }, e.x, &.{ e.qraw, e.kraw, e.vraw }, total, prompt); if (e.learning) |k| try k.attention(i, e.qraw, e.kraw, e.vraw, total); const head_norm = if (g.bf16) e.fns.head_norm_shift else e.fns.head_norm; try e.run(head_norm, .{ total * g.q_heads, 1, 1 }, .{ 64, 1, 1 }, .{ e.qraw, m.q_norm, e.qn, @as(c_int, @intCast(g.q_heads)), @as(c_int, @intCast(2 * aw)), @as(c_int, 2 * head_dim), g.eps, t_params }); try e.run(head_norm, .{ total * g.kv_heads, 1, 1 }, .{ 64, 1, 1 }, .{ e.kraw, m.k_norm, e.kn, @as(c_int, @intCast(g.kv_heads)), @as(c_int, @intCast(g.kv_heads * head_dim)), @as(c_int, head_dim), g.eps, t_params }); try launch(e, if (e.kv8) e.fp8.rope else e.fns.rope, sig.rope, .{ total, g.q_heads + g.kv_heads, 1 }, .{ head_dim, 1, 1 }, .{ geo, e.qn, e.kn, e.vraw, t_segs, t_rows, t_anc, @as(c_int, ai), t_params, mpos, e.rope_table }); + if (unread and last_layer) return; // the keys, values and their rotary rows are all this chunk keeps if (prompt and nseg == 1 and (g.q_heads / g.kv_heads) % 2 == 0) { // a prompt chunk's rows over its own cache: tensor-core tiles in place of the decode partials - try @import("cuda_prompt.zig").runFrom(e, @intCast(ai), t0, total); + try e.promptAttention(@intCast(ai), t0, total); } else { const args = .{ geo, e.qn, t_segs, t_rows, t_anc, @as(c_int, ai), t_params, @as(f32, 1.0 / 16.0), e.pm, e.pl, e.po }; const tile_rows: usize = if (shape.mt2) 32 / group else 64 / group; @@ -198,3 +201,19 @@ test "prompt MoE precision: every prompt piece through 128 and admitted verify w for (1..129) |rows| try std.testing.expectEqual(rows > 16, promptMoe(true, rows)); for (1..E.most_window + 1) |rows| try std.testing.expect(!promptMoe(false, rows)); } + +/// The same scan selected by body, exposed for host launch-contract fixtures. +pub fn deltaScan(e: *E.Engine, record: bool, slot_count: u8, segments: usize, layer: c_int) !void { + const scan = if (!record) e.fns.gdn_chain else switch (slot_count) { + 1 => e.fns.gdn_slots_1, + 2 => e.fns.gdn_slots_2, + 4 => e.fns.gdn_slots_4, + 8 => e.fns.gdn_slots_8, + 16 => e.fns.gdn_slots_16, + else => return error.InvalidGdnSlots, + }; + const input = e.tables.ptr + @as(usize, if (record) @import("cuda_round.zig").steps_at else rowpar_at); + // qwen35_slots.cuh: up to four slots scan two value rows a warp, so a block covers eight + const rows_a_warp: usize = if (record and slot_count <= 4) 2 else 1; + try e.run(scan, .{ 1, geometry.dk / (4 * rows_a_warp), e.g.v_heads * segments }, .{ 32, 4, 1 }, .{ e.geo, e.q, e.k, e.v, e.g_, e.beta, e.tables.ptr + segs_at, input, layer, e.y, e.tables.ptr + params_at }); +} diff --git a/zig/src/families/qwen3_5/cuda_kv_host.zig b/zig/src/families/qwen3_5/cuda_kv_host.zig new file mode 100644 index 00000000000..f6df2cfdbc6 --- /dev/null +++ b/zig/src/families/qwen3_5/cuda_kv_host.zig @@ -0,0 +1,45 @@ +//! Opt-in mapped-host KV pages; recurrent state and verify runs stay on the device. +const std = @import("std"); +const environment = @import("sys").environment; + +pub fn onHost() bool { + const v = @import("profile").get(.TF_QWEN_KV_HOST) orelse return false; + return std.mem.eql(u8, v, "1"); +} + +/// Only the explicit host path reads the GiB cap or the model's geometry. +pub fn room(l: anytype) !u64 { + if (!onHost()) return 0; + const cap = try environment.read(u64, "TF_QWEN_KV_HOST_GIB", 0); + const p = @import("cuda_pages.zig"); + const layout = p.layout(l.e, l.capacity, l.page_tokens, l.ringBytes(), l.extra); + return bytes(l.capacity + p.window_rows, l.page_tokens, layout.pageBytes(), if (cap == 0) null else cap << 30); +} + +/// A whole window of KV pages, never state runs or unused host placeholders for them. +pub fn bytes(rows: usize, tokens: usize, page_bytes: u64, cap: ?u64) !u64 { + if (tokens == 0 or page_bytes == 0) return error.QwenKvHostNeedsPages; + const n = try std.math.divCeil(u64, rows, tokens); + const total = try std.math.mul(u64, n, page_bytes); + if (cap) |limit| if (limit < total) return error.QwenKvHostCap; + return total; +} + +pub fn checkDevice(integrated: bool, pages: usize, all: bool) !void { + if (pages == 0) return error.QwenKvHostNeedsPages; + if (!all) return error.QwenKvHostNeedsPagedEngine; + if (integrated) return error.QwenKvHostIntegrated; +} + +pub fn checkShared(snaps: usize) !void { + if (snaps > 0) return error.QwenKvHostShare; +} + +/// Host capacity mode admits one stream and no disk-backed prompt snapshots. +pub fn refusal(o: anytype) ?[]const u8 { + if (!onHost()) return null; + if (o.lanes != 1) return "TF_QWEN_KV_HOST supports one stream: set --parallel 1"; + if (o.spill != .off) return "TF_QWEN_KV_HOST cannot use --spill-gib; serve without spill"; + if (o.learn != null or o.learn_conversations) return "TF_QWEN_KV_HOST cannot use disk snapshots; serve without --learn or --learn-conversations"; + return null; +} diff --git a/zig/src/families/qwen3_5/cuda_kv_host_test.zig b/zig/src/families/qwen3_5/cuda_kv_host_test.zig new file mode 100644 index 00000000000..3cb3c159c80 --- /dev/null +++ b/zig/src/families/qwen3_5/cuda_kv_host_test.zig @@ -0,0 +1,89 @@ +//! Host page geometry, allocation rollback and KV-only leases through the production constructors. +const std = @import("std"); +const cuda = @import("cuda"); +const host = @import("cuda_kv_host.zig"); +const pages = @import("cuda_pages.zig"); +const Storage = @import("cuda_pages_storage.zig").Storage; +const E = @import("cuda_engine.zig").Engine; +const D = cuda.paging_test_device.Device; +const t = std.testing; +const env = @import("sys").env; + +fn mapped(out: *u64, _: ?*anyopaque, _: c_uint) callconv(.c) c_int { + out.* = 0x800000; + return 0; +} +fn noMap(_: *u64, _: ?*anyopaque, _: c_uint) callconv(.c) c_int { + return cuda.abi.error_not_ready; +} +fn noDevice(_: *u64, _: usize) callconv(.c) c_int { + return cuda.abi.error_not_ready; +} +fn noHost(_: *?*anyopaque, _: usize, _: c_uint) callconv(.c) c_int { + return cuda.abi.error_not_ready; +} + +pub fn engine(d: *cuda.Driver) E { + var e: E = undefined; + e.d = d; + e.stream = .{ .d = d, .handle = D.stream }; + e.kv8 = false; + e.n_taps = 0; + e.g = .{ .hidden = 256, .intermediate = 256, .layers = 2, .vocab = 8, .k_heads = 1, .v_heads = 1, .q_heads = 1, .kv_heads = 1, .eps = 1e-6, .tied = true, .context = 64, .linear = @splat(false) }; + e.g.linear[0] = true; + return e; +} + +test "kv safety: Qwen host KV frees pinned storage after failed mapping or device run allocation" { + for (0..3) |failure| { + var d = D.driver(); + d.api.cuMemHostGetDevicePointer_v2 = if (failure == 1) noMap else mapped; + if (failure == 0) d.api.cuMemHostAlloc = noHost; + if (failure == 2) d.api.cuMemAlloc_v2 = noDevice; + const before = cuda.usage(false); + const want = [_]anyerror{ error.QwenKvHostAllocation, error.QwenKvHostMapping, error.QwenKvHostRunAllocation }; + try t.expectError(want[failure], Storage.init(&d, 4096, 1024, true)); + try t.expectEqual(@as(usize, 0), D.hosts); + try t.expectEqual(before.host, cuda.usage(false).host); + try t.expectEqual(before.device, cuda.usage(false).device); + } +} + +test "kv safety: Qwen host KV pool contains only KV and maps its separately sized device run" { + _ = env.setenv("TF_QWEN_KV_HOST", "1", 1); + defer _ = env.unsetenv("TF_QWEN_KV_HOST"); + var d = D.driver(); + d.api.cuMemHostGetDevicePointer_v2 = mapped; + var e = engine(&d); + const l = pages.layout(&e, 64, 16, 0, 0); + const count = l.pages(64 + pages.window_rows); + const before = cuda.usage(false); + const p = try pages.Pages.init(t.allocator, &e, l, 64, 0, 1, count); + try t.expectEqual(count * l.pageBytes(), p.host.?.bytes.len); + try t.expectEqual(l.runPages() * l.pageBytes(), p.run_dev.?.len); + try t.expectEqual(count, p.pool.total()); + const c = try p.open(64, 0); + try t.expectEqual(count, p.pool.census().leased); + try t.expectEqual(@as(usize, 0), p.pool.census().free); + try t.expect(p.close(c)); + try t.expect(p.pool.idle()); + p.deinit(); + try t.expectEqual(@as(usize, 0), D.hosts); + try t.expectEqual(before.host, cuda.usage(false).host); + try t.expectEqual(before.device, cuda.usage(false).device); + try t.expectEqual(@as(usize, 0), D.freed_pending); +} + +test "kv safety: Qwen host KV cap includes lookahead but no run pages and refuses unsupported geometry" { + try t.expectEqual(@as(u64, 504), try host.bytes(129, 16, 56, null)); + try t.expectError(error.QwenKvHostCap, host.bytes(129, 16, 56, 503)); + try t.expectEqual(@as(u64, 504), try host.bytes(129, 16, 56, 504)); + try t.expectError(error.QwenKvHostNeedsPages, host.bytes(128, 0, 56, null)); + try t.expectError(error.Overflow, host.bytes(129, 16, std.math.maxInt(u64), null)); + try t.expectError(error.QwenKvHostNeedsPages, host.checkDevice(false, 0, false)); + try t.expectError(error.QwenKvHostNeedsPagedEngine, host.checkDevice(false, 16, false)); + try t.expectError(error.QwenKvHostIntegrated, host.checkDevice(true, 16, true)); + try host.checkDevice(false, 16, true); + try host.checkShared(0); + try t.expectError(error.QwenKvHostShare, host.checkShared(1)); +} diff --git a/zig/src/families/qwen3_5/cuda_launch_trace.zig b/zig/src/families/qwen3_5/cuda_launch_trace.zig new file mode 100644 index 00000000000..6aa36a60e43 --- /dev/null +++ b/zig/src/families/qwen3_5/cuda_launch_trace.zig @@ -0,0 +1,24 @@ +//! Host tests of a forward's launches: a trace records tags instead of issuing kernels. +const std = @import("std"); + +/// Host tests record here; null in serving and in every other test. +pub var active: ?*Trace = null; + +pub const Trace = struct { + gpa: std.mem.Allocator, + tags: std.ArrayListUnmanaged(Tag) = .empty, + + pub const Tag = union(enum) { norm, kv, o, attn, launch: usize }; + + pub fn init(gpa: std.mem.Allocator) Trace { + return .{ .gpa = gpa }; + } + + pub fn deinit(t: *Trace) void { + t.tags.deinit(t.gpa); + } + + pub fn note(t: *Trace, tag: Tag) !void { + try t.tags.append(t.gpa, tag); + } +}; diff --git a/zig/src/families/qwen3_5/cuda_native.zig b/zig/src/families/qwen3_5/cuda_native.zig index 18de5fdad28..62d22a7a583 100644 --- a/zig/src/families/qwen3_5/cuda_native.zig +++ b/zig/src/families/qwen3_5/cuda_native.zig @@ -20,6 +20,7 @@ const Fill = prefill.Fill; const reuse = @import("cuda_reuse.zig"); const Mtp = @import("cuda_mtp.zig").Mtp; const pages_mod = @import("cuda_pages.zig"); +const kv_host_mod = @import("cuda_kv_host.zig"); const cache_mod = @import("cuda_cache.zig"); const prefix_mod = @import("cuda_prefix.zig"); const kv_pool = @import("core").kv_pool; @@ -29,7 +30,8 @@ pub const vision = @import("cuda_vision.zig"); pub const slide = @import("cuda_slide.zig"); pub const linked = slide.linked; pub const model_type = "qwen3_5"; -pub const formats: []const []const u8 = &.{ "mlx-q4g64", "exl3" }; +/// MLX's 4-bit tables, EXL3; ModelOpt's MIXED_PRECISION (nvidia/Qwen3.8-27B-NVFP4) and single-format NVFP4. +pub const formats: []const []const u8 = &.{ "mlx-q4g64", "exl3", "modelopt-mixed", "modelopt-nvfp4" }; pub const default_context: i64 = 32768; /// A plain BF16 checkpoint's preflight counts its text tensors, not the tower and MTP in its shards. pub const textWeightBytes = @import("cuda_bf16_bytes.zig").textWeightBytes; @@ -44,7 +46,6 @@ pub const prompt_rows: u32 = E.grid_rows; pub const takes_drafter = true; /// A request's pages hold one more forward past its prompt and reply (TF_QWEN_KV_PAGES). pub const window_rows: u32 = pages_mod.window_rows; - /// Kept prompt states for the shared cache (cuda_reuse.zig) on the host budget, on the zero-anchored chunk grid. pub const snap_bytes = reuse.bytes; pub const snap_save = reuse.save; @@ -62,14 +63,12 @@ pub const warm_quiet: u64 = 150 * std.time.ns_per_ms; pub const warm_usable = true; /// --learn-conversations: the kept states' disk image, the probe their identity hashes, the facts they depend on. pub const kept_disk = @import("cuda_disk.zig"); - /// cuda_prefill cuts a cold pass at the request's chunk starts too, so the server may send its message starts. pub const request_starts = true; const starts = @import("cuda_request_starts.zig"); pub const request_starts_default_on = starts.default_on; pub const request_starts_switch = starts.switch_name; pub const requestStartsOn = starts.on; - /// explain() words open refusals too (--vision on a checkpoint without a tower it reads). pub const explains_open = true; @@ -145,6 +144,12 @@ pub fn attach(p: *anyopaque, streams: u32, pages: usize) !void { if (l.prefix != null and prefix_mod.fewSnapshots(l.share_snaps, streams + 1)) std.log.warn("TF_QWEN_KV_SHARE={d} keeps under 4 recurrent-state snapshots a stream at --parallel {d}: live streams evict each other's before a resume; set it to {d} or more", .{ l.share_snaps, streams + 1, 4 * (streams + 1) }); } +pub const kvHostRefusal = kv_host_mod.refusal; +/// Host bytes are absent before any geometry or cap read when the switch is unset. +pub fn kvHostRoom(p: *anyopaque) !u64 { + return kv_host_mod.room(@as(*Lanes, @ptrCast(@alignCast(p)))); +} + /// The lane host's admission: the first stream's window is free, or a lane and the request's pages are. pub fn fits(p: *anyopaque, prompt: u32, max_tokens: u32) bool { const l: *Lanes = @ptrCast(@alignCast(p)); @@ -185,9 +190,12 @@ pub fn openLanes(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, d const page_test = try cache_mod.pageTest(); _ = try cache_mod.cacheRows(o.context, page_test); if (page_tokens > 0 and o.slide) return error.QwenPagesNoLearner; + if (kv_host_mod.onHost()) try kv_host_mod.checkDevice(try ctx.attribute(.integrated) != 0, page_tokens, engine_paged); const share_snaps = try prefix_mod.sharing(); + if (kv_host_mod.onHost()) try kv_host_mod.checkShared(share_snaps); // a kept state sits on a cold pass's chunk cut, so later chunks keep a cold pass's bits: pages divide the chunk if (share_snaps > 0 and (page_tokens == 0 or E.grid_rows % page_tokens != 0)) return error.QwenShareNeedsPages; + if (kv_host_mod.onHost() and share_snaps == 0) std.log.warn("TF_QWEN_KV_HOST pins the KV pages in host memory; the prompt cache would pin more beside them: set --prompt-cache-gib to bound it", .{}); const e = try E.Engine.init(gpa, io, ctx, dir, o.kv8, fitOf(o), o.context); errdefer e.deinit(); if (o.rope_yarn) |f| { // --rope-yarn over the downloaded config: its table, and the window it allows @@ -398,7 +406,7 @@ pub const Lanes = struct { } /// A drafter's bytes in each lane's run: DFlash2's ring, or MTP's ring and state (0: no drafter). - fn ringBytes(self: *const Lanes) usize { + pub fn ringBytes(self: *const Lanes) usize { if (self.draft) |d| return d.c.ringBytes(); return if (self.mtp) |m| m.areaBytes() else 0; } @@ -555,7 +563,6 @@ pub const Lanes = struct { if (self.caches.count() != 0 or self.pool.items.len != 0) return error.TapsAfterStreams; try self.e.setTaps(taps); } - /// Rows [start, start + count) of a stream's tap ring (slot position % tapRows()), the newest tapRows() rows kept. fn featuresFn(ptr: *anyopaque, stream: *lanes.Stream, taps: []const u32, start: u64, count: u32) !be.Features { const self = cast(ptr); @@ -567,7 +574,6 @@ pub const Lanes = struct { if (start + count > cache.written or start + count <= held_from) return error.RowsNotHeld; return .{ .buffer = ring.ptr, .offset = start, .rows = count, .row_bytes = @intCast(self.e.n_taps * self.e.g.hidden * 2), .space = .device, .dtype = .bf16 }; } - fn releaseFn(ptr: *anyopaque, stream: *lanes.Stream) void { const self = cast(ptr); readout.release(self, stream); @@ -575,7 +581,6 @@ pub const Lanes = struct { if (self.seen.fetchRemove(stream)) |entry| self.gpa.free(entry.value); self.endFill(stream); } - /// Each image's first placeholder row and identity: a kept state resumes only the same images. pub fn seenOf(self: *Lanes, images: []const lanes.stream.Image) ![]reuse.Seen { const seen = try self.gpa.alloc(reuse.Seen, images.len); @@ -583,15 +588,12 @@ pub const Lanes = struct { return seen; } }; - test "Qwen stepped prefill: cancel between host iterations retains only the last completed cut" { try @import("cuda_prefill_test.zig").cancelled(Lanes, Lanes.backend); } - test "Qwen stepped prefill: a cap (the flag's or fcfs's) cuts on the 128 grid in cold chunks; marks keep at cold cuts" { try @import("cuda_prefill_test.zig").capped(Lanes, Lanes.backend); } - test { _ = @import("cuda_admit_test.zig"); _ = @import("cuda_mtp_budget.zig"); diff --git a/zig/src/families/qwen3_5/cuda_native_explain.zig b/zig/src/families/qwen3_5/cuda_native_explain.zig index 8b7bf48c503..7d9e7137728 100644 --- a/zig/src/families/qwen3_5/cuda_native_explain.zig +++ b/zig/src/families/qwen3_5/cuda_native_explain.zig @@ -15,6 +15,15 @@ pub fn explain(ctx: ?*anyopaque, err: anyerror) ?[]const u8 { error.BadChunkSolo => "TF_QWEN35_CHUNK_SOLO: a solo prompt pass's rows, 4096 (off) or 8192", error.QwenSoloStage => "TF_QWEN35_CHUNK_SOLO: a pipeline stage runs 4096-row prompt chunks; unset it on stages", error.BadQwenKvPages => "TF_QWEN_KV_PAGES takes the positions a page holds (a whole number; 0 or unset: a window each)", + error.QwenKvHostShare => "TF_QWEN_KV_HOST uses the host prompt cache, not shared KV snapshots: unset TF_QWEN_KV_SHARE", + error.QwenKvHostCap => "TF_QWEN_KV_HOST_GIB is below one full KV window including lookahead; raise the cap or lower --context", + error.QwenKvHostNeedsPagedEngine => "TF_QWEN_KV_HOST requires TF_QWEN_KV_PAGES_ALL=1 for its single paged stream", + error.QwenKvHostIntegrated => "TF_QWEN_KV_HOST requires a discrete GPU; integrated host and device memory share one pool", + error.QwenKvHostAllocation => "TF_QWEN_KV_HOST could not allocate pinned host KV pages; lower --context or free pinned memory", + error.QwenKvHostMapping => "TF_QWEN_KV_HOST could not map pinned KV pages into device memory", + error.QwenKvHostRunAllocation => "TF_QWEN_KV_HOST could not allocate its device state run; lower --context or free device memory", + error.QwenKvHostParallel => "TF_QWEN_KV_HOST supports one stream: set --parallel 1", + error.QwenKvHostNeedsPages => "TF_QWEN_KV_HOST keeps the KV pages in pinned host memory: set TF_QWEN_KV_PAGES (with TF_QWEN_KV_PAGES_ALL=1 for a single stream) so there are pages to place", error.UnsupportedQwenVision => "--vision: this checkpoint's image tower or text M-RoPE is not one the CUDA engine reads", else => sm110_modes.explain(err), }; diff --git a/zig/src/families/qwen3_5/cuda_native_moe.zig b/zig/src/families/qwen3_5/cuda_native_moe.zig index 74b3e5ad448..715d0df46ee 100644 --- a/zig/src/families/qwen3_5/cuda_native_moe.zig +++ b/zig/src/families/qwen3_5/cuda_native_moe.zig @@ -12,6 +12,8 @@ pub const takes_drafter = true; pub const Options = native.Options; pub const open = native.open; pub const attach = native.attach; +pub const kvHostRoom = native.kvHostRoom; +pub const kvHostRefusal = native.kvHostRefusal; pub const pagedLayout = native.pagedLayout; // TF_QWEN_KV_PAGES: the same pool as the dense models' pub const fits = native.fits; pub const contextCeiling = native.contextCeiling; diff --git a/zig/src/families/qwen3_5/cuda_pages.zig b/zig/src/families/qwen3_5/cuda_pages.zig index 8ce9d208087..182810ff731 100644 --- a/zig/src/families/qwen3_5/cuda_pages.zig +++ b/zig/src/families/qwen3_5/cuda_pages.zig @@ -5,6 +5,8 @@ const kv = @import("core").kv_pool; const engine = @import("cuda_engine.zig"); const caches = @import("cuda_cache.zig"); const platform = @import("sys"); +const kv_host = @import("cuda_kv_host.zig"); +const Storage = @import("cuda_pages_storage.zig").Storage; const Engine = engine.Engine; const Cache = caches.Cache; @@ -59,7 +61,13 @@ pub const Pages = struct { capacity: usize, ring: usize, pool: kv.Pool, + /// KV pages use a device arena by default, or mapped host memory in capacity mode. arena: cuda.DeviceBuffer, + host: ?cuda.HostBuffer = null, + /// The arena's device address: `arena.ptr`, or the mapped host pointer when host-funded. + base: u64 = 0, + /// Host capacity mode keeps its state run on the device. + run_dev: ?cuda.DeviceBuffer = null, lanes: []Lane, /// `streams` lanes and `pages` pages of layout `l`, made and touched now; each run holds a `ring`-byte ring. @@ -72,9 +80,13 @@ pub const Pages = struct { _ = try std.math.add(u64, l.run_bytes, page_bytes - 1); const p = try gpa.create(Pages); errdefer gpa.destroy(p); - var arena = try cuda.DeviceBuffer.alloc(e.d, try std.math.mul(usize, pages, page_bytes)); - errdefer arena.free(); - p.* = .{ .gpa = gpa, .e = e, .layout = l, .capacity = capacity, .ring = ring, .pool = try kv.Pool.init(gpa, pages, page_bytes), .arena = arena, .lanes = &.{} }; + const total = try std.math.mul(usize, pages, page_bytes); + const host_mode = kv_host.onHost(); + if (host_mode and streams != 1) return error.QwenKvHostParallel; + const run_bytes = if (host_mode) try std.math.mul(usize, streams, try std.math.mul(usize, l.runPages(), page_bytes)) else 0; + var storage = try Storage.init(e.d, total, run_bytes, host_mode); + errdefer storage.deinit(); + p.* = .{ .gpa = gpa, .e = e, .layout = l, .capacity = capacity, .ring = ring, .pool = try kv.Pool.init(gpa, pages, page_bytes), .arena = storage.arena, .host = storage.host, .base = storage.base, .run_dev = storage.run_dev, .lanes = &.{} }; errdefer p.pool.deinit(); p.lanes = try gpa.alloc(Lane, streams); errdefer gpa.free(p.lanes); @@ -86,14 +98,20 @@ pub const Pages = struct { for (p.lanes) |*x| { const c = try gpa.create(Cache); errdefer gpa.destroy(c); - c.* = try Cache.initPaged(gpa, e, mostPages(capacity, tokens), tokens, arena.ptr); + c.* = try Cache.initPaged(gpa, e, mostPages(capacity, tokens), tokens, storage.base); x.* = .{ .cache = c }; made += 1; } errdefer cuda.completion.drain(e.d, e.stream, "qwen3_5: a failed pool initialization did not drain"); - try arena.fill8(0, e.stream.handle); + if (p.host) |h| { + // The host pages zero through the device's view of them, on the engine's stream like every fill. + const view = cuda.DeviceBuffer{ .d = e.d, .ptr = p.base, .len = h.bytes.len, .borrowed = true }; + try view.fill8(0, e.stream.handle); + } else try p.arena.fill8(0, e.stream.handle); + if (p.run_dev) |rd| try rd.fill8(0, e.stream.handle); for (p.lanes) |x| try x.cache.paged.?.table.fill8(0, e.stream.handle); try e.stream.synchronize(); + if (p.host != null) std.log.info("qwen3_5 host KV: {d} pinned KV bytes, {d} device run bytes", .{ total, run_bytes }); return p; } @@ -101,26 +119,31 @@ pub const Pages = struct { cuda.completion.drain(p.e.d, p.e.stream, "qwen3_5: the pool did not drain at close"); for (p.lanes) |*x| { if (x.used) { - p.pool.releaseRun(x.run, p.layout.runPages()); + if (p.host == null) p.pool.releaseRun(x.run, p.layout.runPages()); p.pool.finish(&x.lease); } x.cache.deinit(p.gpa); p.gpa.destroy(x.cache); } p.gpa.free(p.lanes); - p.arena.free(); + if (p.host != null) p.host.?.free() else p.arena.free(); + if (p.run_dev != null) p.run_dev.?.free(); p.pool.deinit(); p.gpa.destroy(p); } fn need(p: *const Pages, prompt: usize, max_tokens: usize) usize { - return p.layout.need(prompt, max_tokens, window_rows); + return p.layout.pages(prompt + max_tokens + window_rows) + p.runPages(); + } + + fn runPages(p: *const Pages) usize { + return if (p.host != null) 0 else p.layout.runPages(); } /// Whether a lane is free, the pool can promise a request's pages now and a run of them is free. pub fn fits(p: *const Pages, prompt: usize, max_tokens: usize) bool { if (prompt > p.capacity or max_tokens > p.capacity - prompt) return false; - for (p.lanes) |x| if (!x.used) return p.pool.fits(p.need(prompt, max_tokens)) and p.pool.findRun(p.layout.runPages()) != null; + for (p.lanes) |x| if (!x.used) return p.pool.fits(p.need(prompt, max_tokens)) and (p.runPages() == 0 or p.pool.findRun(p.runPages()) != null); return false; } @@ -137,7 +160,7 @@ pub const Pages = struct { const x = for (p.lanes) |*x| { if (!x.used) break x; } else return error.LaneMemory; - const k = p.layout.runPages(); + const k = p.runPages(); const n = p.need(prompt, max_tokens) - k; // keys and values if (n > mostPages(p.capacity, p.layout.page_tokens) or adopted.len > n or n * p.layout.page_tokens > std.math.maxInt(c_int)) return error.InvalidQwenPrompt; try p.pool.promise(&x.lease, n - adopted.len + k); @@ -147,13 +170,14 @@ pub const Pages = struct { try p.pool.adopt(&x.lease, adopted); // the lease holds them now (its finish releases them) } // the run first: KV pages fill from the bottom, runs from the top; a fragmented pool waits (LaneMemory) - const run = p.pool.claimRun(&x.lease, k) orelse return error.LaneMemory; - errdefer p.pool.releaseRun(run, k); + const run = if (k == 0) 0 else p.pool.claimRun(&x.lease, k) orelse return error.LaneMemory; + errdefer if (k > 0) p.pool.releaseRun(run, k); errdefer cuda.completion.drain(p.e.d, p.e.stream, "qwen3_5: a failed lane open did not drain"); var up: Upload = .{ .p = p, .cache = x.cache }; if (adopted.len > 0) try Upload.write(&up, x.lease.ids.items, 0); try p.pool.cover(&x.lease, n, .{ .ctx = &up, .write = Upload.write }); - try x.cache.mapRun(p.e, p.arena.ptr + run * p.layout.pageBytes(), k * p.layout.pageBytes(), p.ring); + const run_base = if (p.run_dev) |rd| rd.ptr else p.base + run * p.layout.pageBytes(); + try x.cache.mapRun(p.e, run_base, p.layout.runPages() * p.layout.pageBytes(), p.ring); try x.cache.reset(p.e); x.cache.paged.?.ids = x.lease.ids.items; x.cache.cap = n * p.layout.page_tokens; @@ -169,7 +193,7 @@ pub const Pages = struct { } else return false; if (!x.used) return true; cuda.completion.drain(p.e.d, p.e.stream, "qwen3_5: a closed stream did not drain"); - p.pool.releaseRun(x.run, p.layout.runPages()); + if (p.host == null) p.pool.releaseRun(x.run, p.layout.runPages()); p.pool.finish(&x.lease); cache.unmapRun(p.e); cache.paged.?.ids = &.{}; diff --git a/zig/src/families/qwen3_5/cuda_pages_storage.zig b/zig/src/families/qwen3_5/cuda_pages_storage.zig new file mode 100644 index 00000000000..6d970ae8e9f --- /dev/null +++ b/zig/src/families/qwen3_5/cuda_pages_storage.zig @@ -0,0 +1,27 @@ +//! Page storage owns a mapped host allocation before mapping it or allocating its device state run. +const cuda = @import("cuda"); + +pub const Storage = struct { + arena: cuda.DeviceBuffer, + host: ?cuda.HostBuffer = null, + base: u64, + run_dev: ?cuda.DeviceBuffer = null, + + pub fn init(d: *const cuda.Driver, bytes: usize, run_bytes: usize, host: bool) !Storage { + if (!host) { + const arena = try cuda.DeviceBuffer.alloc(d, bytes); + return .{ .arena = arena, .base = arena.ptr }; + } + var h = cuda.HostBuffer.allocMapped(d, bytes) catch return error.QwenKvHostAllocation; + errdefer h.free(); + const base = h.device() catch return error.QwenKvHostMapping; + var run = cuda.DeviceBuffer.alloc(d, run_bytes) catch return error.QwenKvHostRunAllocation; + errdefer run.free(); + return .{ .arena = .{ .d = d, .ptr = 0, .len = 0 }, .host = h, .base = base, .run_dev = run }; + } + + pub fn deinit(s: *Storage) void { + if (s.run_dev) |*r| r.free(); + if (s.host) |*h| h.free() else s.arena.free(); + } +}; diff --git a/zig/src/families/qwen3_5/cuda_prefill.zig b/zig/src/families/qwen3_5/cuda_prefill.zig index 099c4d2213d..07de0e69d7b 100644 --- a/zig/src/families/qwen3_5/cuda_prefill.zig +++ b/zig/src/families/qwen3_5/cuda_prefill.zig @@ -2,6 +2,7 @@ const std = @import("std"); const lanes = @import("lanes"); const E = @import("cuda_engine.zig"); +const prompt_tail = @import("cuda_prompt_tail.zig"); const vision_prompt = @import("cuda_vision_prompt.zig"); const readout = @import("cuda_readout.zig"); const cuda_solo = @import("cuda_solo.zig"); @@ -71,6 +72,17 @@ test "a yielded pass keeps its completed prefix and stops before the next chunk, const FakeEngine = struct { scratch_rows: usize = 2 * E.grid_rows, // TF_QWEN35_CHUNK_SOLO=8192 forwards: usize = 0, + layers: [2]void = .{ {}, {} }, + taps: [1]u32 = undefined, + n_taps: usize = 0, + learning: ?*const anyopaque = null, + mlp: ?*const anyopaque = null, + pockets: struct { + pub fn any(_: *const @This()) bool { + return false; + } + } = .{}, + int8: struct { on: bool = false } = .{}, fn forward(self: *@This(), parts: []const E.Part, ids_: []const u32, _: E.Keep) !void { self.forwards += 1; parts[0].cache.len += ids_.len; @@ -297,7 +309,9 @@ pub fn chunk(self: anytype, stream: *lanes.Stream, f: *Fill, max_rows: u32) !boo !cuda_solo.othersDecode(self, stream); const marks = if (f.kept) |k| k.marks else stream.reuse.marks; const end = if (solo) soloEnd(ids.len, stream.chunks, f, rows, marks) else capped(ids.len, stream.chunks, f, max_rows); - try self.e.forward(&.{.{ .cache = cache, .rows = end - f.at, .images = if (images) |*im| im else null }}, ids[f.at..end], .last); + // a non-final chunk's rows feed only a head nobody reads: its last layer stops at its keys and values + const unread = end < ids.len and prompt_tail.unread(self.e, images != null); + try self.e.forward(&.{.{ .cache = cache, .rows = end - f.at, .images = if (images) |*im| im else null }}, ids[f.at..end], if (unread) .none else .last); lanes.prefill_widths.completed(self.gpa, stream, end - f.at); f.at = end; stream.fill_at.store(@intCast(end), .monotonic); diff --git a/zig/src/families/qwen3_5/cuda_prefill_test.zig b/zig/src/families/qwen3_5/cuda_prefill_test.zig index f934e7986f7..938b255b8cc 100644 --- a/zig/src/families/qwen3_5/cuda_prefill_test.zig +++ b/zig/src/families/qwen3_5/cuda_prefill_test.zig @@ -62,6 +62,14 @@ const Fake = struct { const Pages = struct { pub fn log(_: *Pages, _: usize, _: usize) void {} }; + const Pockets = struct { + held: bool = false, + pub fn any(p: *const Pockets) bool { + return p.held; + } + }; + const Int8 = struct { on: bool = false }; + const Keep = @import("cuda_engine.zig").Keep; const Engine = struct { scratch_rows: usize = E.grid_rows, rows: std.ArrayList(usize) = .empty, @@ -72,11 +80,20 @@ const Fake = struct { piece_calls: usize = 0, piece_rows: usize = 0, reset_fails: bool = false, + keeps: std.ArrayList(Keep) = .empty, + layers: [2]void = .{ {}, {} }, + taps: [8]u32 = undefined, + n_taps: usize = 0, + learning: ?*const anyopaque = null, + mlp: ?*const anyopaque = null, + pockets: Pockets = .{}, + int8: Int8 = .{}, pub fn forward(e: *Engine, parts: anytype, ids: []const u32, keep: E.Keep) !void { var rows: usize = 0; inline for (parts) |p| rows += p.rows; try t.expectEqual(rows, ids.len); try e.rows.append(t.allocator, ids.len); + try e.keeps.append(t.allocator, keep); if (keep == .rows) { e.piece_calls += 1; e.piece_rows += rows; @@ -85,6 +102,10 @@ const Fake = struct { e.whole_rows += rows; } } + fn deinit(e: *Engine) void { + e.rows.deinit(t.allocator); + e.keeps.deinit(t.allocator); + } }; gpa: std.mem.Allocator = t.allocator, capacity: usize = 1 << 16, @@ -124,7 +145,7 @@ const Fake = struct { /// One stepped pass at the caps in turn, a forward a step of at most its cap's rows: where each forward ended. fn pass(prompt: []const u32, chunks: []const u32, caps: []const u32, ends: *std.ArrayList(usize)) !void { var e: Fake.Engine = .{}; - defer e.rows.deinit(t.allocator); + defer e.deinit(); var f: Fake = .{ .e = &e }; defer f.deinit(); var s = try lanes.Stream.init(t.allocator, .{ .id = "cap", .prompt = prompt, .max_new = 1, .chunks = chunks }); @@ -191,7 +212,7 @@ fn marks() !void { @memset(prompt, 3); for ([_]u32{ 0, 512 }) |cap| { var e: Fake.Engine = .{}; - defer e.rows.deinit(t.allocator); + defer e.deinit(); var f: Fake = .{ .e = &e }; defer f.deinit(); var probe: Probe = .{}; @@ -256,7 +277,7 @@ pub fn whole() !void { } }; var eng: Fake.Engine = .{}; - defer eng.rows.deinit(t.allocator); + defer eng.deinit(); var toks: [E.grid_rows + 8]u32 = undefined; for (&toks, 0..) |*x, i| x.* = @intCast(i % 7); var fake: Fake = .{ .e = &eng, .capacity = toks.len + 1 }; @@ -301,7 +322,7 @@ test "Qwen whole prefill: a text stream runs its pass once and a readout only it /// A failed restore resets the cache under `try`: a reset error leaves opening instead of filling from row 0. pub fn reset() !void { var eng: Fake.Engine = .{ .reset_fails = true }; - defer eng.rows.deinit(t.allocator); + defer eng.deinit(); var fake: Fake = .{ .e = &eng, .restore_ok = false }; defer fake.deinit(); var toks: [3 * E.grid_rows]u32 = @splat(3); @@ -315,3 +336,114 @@ pub fn reset() !void { test "Qwen prefill opening: a failed reset propagates out of the opening" { try reset(); } + +/// A 32K fill: every chunk but the last is unread, and a reader on the last layer keeps every chunk's rows. +fn unread() !void { + const m = @import("cuda_engine.zig").grid_rows; + const prompt = try t.allocator.alloc(u32, 8 * m); + defer t.allocator.free(prompt); + @memset(prompt, 3); + const Reader = enum { none, tap, learning, mlp, pockets, int8 }; + for (std.enums.values(Reader)) |reader| { + var e: Fake.Engine = .{}; + defer e.deinit(); + switch (reader) { + .none => {}, + .tap => { + e.taps[0] = 1; // the last layer's tap + e.n_taps = 1; + }, + .learning => e.learning = @ptrCast(&e), + .mlp => e.mlp = @ptrCast(&e), + .pockets => e.pockets.held = true, + .int8 => e.int8.on = true, + } + var f: Fake = .{ .e = &e }; + defer f.deinit(); + var s = try lanes.Stream.init(t.allocator, .{ .id = "unread", .prompt = prompt, .max_new = 1 }); + defer s.deinit(t.allocator); + while (!try prefill.step(&f, &s, 0)) {} + try t.expectEqual(@as(usize, 8), e.keeps.items.len); + for (e.keeps.items, 0..) |keep, i| { + const want_none = reader == .none and i + 1 < e.keeps.items.len; + if (want_none) try t.expect(keep == .none) else try t.expect(keep == .last); + } + } +} + +test "Qwen stepped prefill: a chunk nothing reads stops its last layer at the keys" { + try unread(); +} + +const forward = @import("cuda_forward.zig"); +const engine = @import("cuda_engine.zig"); +const geom = @import("cuda_geometry.zig"); +const layer_defs = @import("cuda_layers.zig"); +const Trace = @import("cuda_launch_trace.zig").Trace; + +fn fnHandle(n: usize) @import("cuda").Function { + return .{ .d = undefined, .handle = @ptrFromInt(n) }; +} + +test "Qwen stepped prefill: an unread chunk's last layer launches K/V, both head norms and RoPE, then stops" { + var trace = Trace.init(t.allocator); + defer trace.deinit(); + @import("cuda_launch_trace.zig").active = &trace; + defer @import("cuda_launch_trace.zig").active = null; + const bf: layer_defs.Proj = .{ .bf = .{ .w = 0, .n = 1, .k = 1 } }; + const attn: layer_defs.Attention = .{ .q = bf, .k = bf, .v = bf, .o = bf, .q_norm = 0, .k_norm = 0 }; + const mlp: layer_defs.Mlp = .{ .dense = .{ .gate = bf, .up = bf, .down = bf } }; + const one = layer_defs.Layer{ .input_norm = 0, .post_norm = 0, .mlp = mlp, .mixer = .{ .attention = attn } }; + var ls = [_]layer_defs.Layer{one}; + const g: geom.Geometry = .{ + .hidden = 64, + .intermediate = 128, + .layers = 1, + .vocab = 16, + .k_heads = 1, + .v_heads = 1, + .q_heads = 2, + .kv_heads = 1, + .eps = 1e-6, + .tied = true, + .context = 4096, + .linear = @splat(false), + .embeds = false, + }; + var e: engine.Engine = undefined; + e.gpa = t.allocator; + e.g = g; + e.layers = &ls; + e.fns = undefined; + e.fns.head_norm = fnHandle(1); + e.fns.head_norm_shift = fnHandle(2); + e.fns.rope = fnHandle(3); + e.fp8 = undefined; + e.fp8.rope = fnHandle(3); + e.kv8 = false; + e.rope_table = 0; + e.tables.ptr = 0; + e.features = 0; + e.int8 = .{}; + e.learning = null; + e.mlp = null; + e.pockets = .{ .gpa = t.allocator, .d = undefined, .hidden = 64 }; + e.taught = 0; + e.n_taps = 0; + e.x = 0; + e.xs = 0; + e.kraw = 0; + e.vraw = 0; + e.qraw = 0; + e.qn = 0; + e.kn = 0; + e.y = 0; + e.mix = 0; + e.r = 0; + var shape = engine.Engine.Shape.init(32, 1, false, false, 1); + shape.unread = true; + try forward.body(&e, shape); + const want = [_]Trace.Tag{ .norm, .kv, .{ .launch = 1 }, .{ .launch = 1 }, .{ .launch = 3 } }; + try t.expectEqual(want.len, trace.tags.items.len); + for (want, trace.tags.items) |w, got| try t.expect(std.meta.eql(w, got)); +} diff --git a/zig/src/families/qwen3_5/cuda_projection.zig b/zig/src/families/qwen3_5/cuda_projection.zig index a033162d9a7..50f340dd9d6 100644 --- a/zig/src/families/qwen3_5/cuda_projection.zig +++ b/zig/src/families/qwen3_5/cuda_projection.zig @@ -9,6 +9,7 @@ const Proj = engine.Proj; /// out (rows, n) = x (rows, k) through `l`: row tiles with batch-independent bits or a prompt GEMM. pub fn proj(e: *Engine, l: Proj, x: u64, out: u64, rows: usize, prompt: bool) !void { + if (@import("cuda_launch_trace.zig").active) |t| return t.note(.o); return projSums(e, l, x, e.xs, out, rows, prompt, e.tables.ptr + Engine.params_at); } @@ -18,16 +19,19 @@ pub fn projSums(e: *Engine, l: Proj, x: u64, xs: u64, out: u64, rows: usize, pro } pub fn projAgain(e: *Engine, l: Proj, x: u64, out: u64, rows: usize, prompt: bool) !void { + if (@import("cuda_launch_trace.zig").active) |t| return t.note(.o); return project(e, l, x, e.xs, out, rows, prompt, e.tables.ptr + Engine.params_at, false); } /// `projAgain` of each of `ls` into `outs` over one x; on the split form's GPUs one segmented launch a row tile. pub fn projMany(e: *Engine, ls: []const Proj, x: u64, outs: []const u64, rows: usize, prompt: bool) !void { + if (@import("cuda_launch_trace.zig").active) |t| return t.note(.kv); return projectMany(e, ls, x, e.xs, outs, rows, prompt, e.tables.ptr + Engine.params_at, false, false); } /// The landed forward's shared-input projections; on GB10 their prompt CTAs may share one launch. pub fn projManyPrompt(e: *Engine, ls: []const Proj, x: u64, outs: []const u64, rows: usize, prompt: bool) !void { + if (@import("cuda_launch_trace.zig").active) |t| return t.note(.kv); return projectMany(e, ls, x, e.xs, outs, rows, prompt, e.tables.ptr + Engine.params_at, false, true); } diff --git a/zig/src/families/qwen3_5/cuda_prompt_tail.zig b/zig/src/families/qwen3_5/cuda_prompt_tail.zig index 7b455df3691..494781d7bc8 100644 --- a/zig/src/families/qwen3_5/cuda_prompt_tail.zig +++ b/zig/src/families/qwen3_5/cuda_prompt_tail.zig @@ -25,11 +25,21 @@ pub const Facts = struct { } }; +/// Whether something reads the last layer's rows in a prompt chunk besides the head. +fn lastTapped(e: anytype) bool { + const last = e.layers.len - 1; + for (e.taps[0..e.n_taps]) |t| if (t == last) return true; + return false; +} + +/// True when nothing reads this prompt chunk's rows: its last layer stops at the state writes. +pub fn unread(e: anytype, images: bool) bool { + return !lastTapped(e) and e.learning == null and e.mlp == null and !e.pockets.any() and !e.int8.on and !images; +} + /// The tail's first row for engine `e`'s prompt chunk of `total` rows in `nseg` parts, or null. pub fn first(e: anytype, total: usize, nseg: usize, hidden: bool) ?usize { const last = e.layers.len - 1; - var tapped = false; - for (e.taps[0..e.n_taps]) |t| tapped = tapped or t == last; const f: Facts = .{ .hidden = hidden, .hooks = e.learning != null or e.mlp != null or e.pockets.any(), @@ -37,11 +47,48 @@ pub fn first(e: anytype, total: usize, nseg: usize, hidden: bool) ?usize { .images = e.features != 0, .odd_group = (e.g.q_heads / e.g.kv_heads) % 2 != 0, .last_attention = e.layers[last].mixer == .attention, - .last_tapped = tapped, + .last_tapped = lastTapped(e), }; return tail.start(f.of(total, nseg)); } +test "qwen3_5 prompt tail: a chunk is unread only when no reader is armed" { + const Fake = struct { + layers: [2]void = .{ {}, {} }, + taps: [4]u32 = undefined, + n_taps: usize = 0, + learning: ?*const anyopaque = null, + mlp: ?*const anyopaque = null, + pockets: struct { + held: bool = false, + pub fn any(p: @This()) bool { + return p.held; + } + } = .{}, + int8: struct { on: bool = false } = .{}, + }; + var e: Fake = .{}; + try std.testing.expect(unread(&e, false)); + try std.testing.expect(!unread(&e, true)); + e.taps[0] = 0; // an earlier layer's tap still reads its own rows + e.n_taps = 1; + try std.testing.expect(unread(&e, false)); + e.taps[0] = 1; // the last layer's tap reads every row + try std.testing.expect(!unread(&e, false)); + e.n_taps = 0; + e.learning = @ptrCast(&e); + try std.testing.expect(!unread(&e, false)); + e.learning = null; + e.mlp = @ptrCast(&e); + try std.testing.expect(!unread(&e, false)); + e.mlp = null; + e.pockets.held = true; + try std.testing.expect(!unread(&e, false)); + e.pockets.held = false; + e.int8.on = true; + try std.testing.expect(!unread(&e, false)); +} + test "qwen3_5 prompt tail: each planted reader of the other rows refuses it" { const open: Facts = .{}; try std.testing.expect(tail.start(open.of(4096, 1)) != null); diff --git a/zig/src/families/qwen3_5/cuda_shapes.zig b/zig/src/families/qwen3_5/cuda_shapes.zig index 1f606e3fea8..f72affc95f4 100644 --- a/zig/src/families/qwen3_5/cuda_shapes.zig +++ b/zig/src/families/qwen3_5/cuda_shapes.zig @@ -15,6 +15,7 @@ pub const Shape = struct { paged: bool = false, mt2: bool = false, join: bool = false, // a paged forward whose streams share pages (Seg.share): the rows kernels' join variants + unread: bool = false, // a prompt chunk nothing reads: its last layer stops at the state writes /// A pipeline stage's piece of the forward (cuda_stage_forward.zig); one engine runs the whole. part: @import("cuda_stage_forward.zig").Part = .whole, diff --git a/zig/src/families/qwen3_5/prefill.zig b/zig/src/families/qwen3_5/prefill.zig index f5b7c9b61da..a72eab36187 100644 --- a/zig/src/families/qwen3_5/prefill.zig +++ b/zig/src/families/qwen3_5/prefill.zig @@ -1,10 +1,16 @@ -//! Prompt reuse and capture hooks around the unchanged Qwen forward, also exercised with a host reference. +//! Prompt reuse and capture hooks around the unchanged Qwen forward: a pass whole, or a chunk a call (#3021). const std = @import("std"); const lanes = @import("lanes"); const st = @import("state.zig"); const snapshot = @import("snapshot.zig"); pub fn run(cache: *st.Cache, stream: *lanes.Stream, chunk: usize, ctx: anytype, comptime advance: anytype) !void { + var at = open(cache, stream); + while (!try step(cache, stream, &at, chunk, ctx, advance)) {} +} + +/// The pass's first row: a kept state of the prompt's prefix restored into `cache`, or 0. +pub fn open(cache: *st.Cache, stream: *lanes.Stream) usize { const ids = stream.prompt(); var at: usize = 0; stream.cached = 0; @@ -19,30 +25,42 @@ pub fn run(cache: *st.Cache, stream: *lanes.Stream, chunk: usize, ctx: anytype, stream.reuse_failed = at == 0; } stream.fill_at.store(@intCast(at), .monotonic); - var mark: usize = 0; - while (at < ids.len) { - if (stream.isCancelled()) { - stream.keepInterruptedPrefill(@intCast(at)); - return error.Cancelled; - } + return at; +} - // A background pass steps aside when real work waits: the kept prefix is what the next pass resumes. - if (stream.yields()) { - stream.keepInterruptedPrefill(@intCast(at)); - return error.Yielded; - } - var end = @min(ids.len, at + chunk); - for (stream.chunks) |boundary| if (boundary > at) { - end = @min(end, boundary); - break; - }; - while (mark < stream.reuse.marks.len and stream.reuse.marks[mark] <= at) mark += 1; - if (mark < stream.reuse.marks.len) end = @min(end, stream.reuse.marks[mark]); - try advance(ctx, cache, ids[at..end]); - lanes.prefill_widths.completed(ctx.gpa, stream, end - at); - at = end; - stream.fill_at.store(@intCast(at), .monotonic); - if (stream.reuse.hook) |hook| if (std.mem.indexOfScalar(u32, stream.reuse.marks, @intCast(at)) != null) - hook.at(hook.ptr, stream, @intCast(at)); +/// One chunk from `at` through `advance`, at the whole pass's cut; true once the prompt is in (at once if it is). +pub fn step(cache: *st.Cache, stream: *lanes.Stream, at: *usize, chunk: usize, ctx: anytype, comptime advance: anytype) !bool { + const ids = stream.prompt(); + if (at.* >= ids.len) return true; + if (stream.isCancelled()) { + stream.keepInterruptedPrefill(@intCast(at.*)); + return error.Cancelled; } + // A background pass steps aside when real work waits: the kept prefix is what the next pass resumes. + if (stream.yields()) { + stream.keepInterruptedPrefill(@intCast(at.*)); + return error.Yielded; + } + const end = chunkEnd(ids.len, at.*, chunk, stream.chunks, stream.reuse.marks); + try advance(ctx, cache, ids[at.*..end]); + lanes.prefill_widths.completed(ctx.gpa, stream, end - at.*); + at.* = end; + stream.fill_at.store(@intCast(end), .monotonic); + if (stream.reuse.hook) |hook| if (std.mem.indexOfScalar(u32, stream.reuse.marks, @intCast(end)) != null) + hook.at(hook.ptr, stream, @intCast(end)); + return end == ids.len; +} + +/// A chunk from `at`: `chunk` rows at most, cut at the next planned chunk start and the next kept mark. +pub fn chunkEnd(len: usize, at: usize, chunk: usize, chunks: []const u32, marks: []const u32) usize { + var end = @min(len, at + chunk); + for (chunks) |boundary| if (boundary > at) { + end = @min(end, boundary); + break; + }; + // the whole loop carried `mark`; it skipped only marks at or before `at`, so a fresh scan stops there too + var mark: usize = 0; + while (mark < marks.len and marks[mark] <= at) mark += 1; + if (mark < marks.len) end = @min(end, marks[mark]); + return end; } diff --git a/zig/src/families/spark25/forward.zig b/zig/src/families/spark25/forward.zig index 7e89356d226..f5d6e8b2227 100644 --- a/zig/src/families/spark25/forward.zig +++ b/zig/src/families/spark25/forward.zig @@ -324,11 +324,11 @@ pub const Model = struct { } } - /// Same-input affine-4 native projections share the GB10 grid; prompt and mixed widths keep their launches. + /// Same-input affine-4 decode projections share a grid on PDL or segmented-split devices; prompt routes stay put. pub fn projectMany(m: *const Model, k: *const kern.Kernels, s: cuda.Stream, ls: []const wts.Proj, x: u64, xs: u64, outs: []const u64, rows: usize, prompt: bool) !void { if (ls.len == 0 or ls.len != outs.len) return error.ShapeMismatch; const A = cuda.qlinear.Affine4Kernels; - if (k.affine.pdl and !prompt and ls.len >= 2 and ls.len <= A.segs_max) grouped: { + if ((k.affine.pdl or k.affine.split != null) and !prompt and ls.len >= 2 and ls.len <= A.segs_max) grouped: { var many: [A.segs_max]A.Out = undefined; for (ls, outs, many[0..ls.len]) |l, out, *v| { if (l != .a4 or l.k() != ls[0].k()) break :grouped; diff --git a/zig/src/families/spark25/weights.zig b/zig/src/families/spark25/weights.zig index 2f286738870..e0a571641de 100644 --- a/zig/src/families/spark25/weights.zig +++ b/zig/src/families/spark25/weights.zig @@ -183,8 +183,15 @@ pub fn load(gpa: std.mem.Allocator, io: std.Io, d: *const cuda.Driver, s: cuda.S const qkv = geo.queryWidth() + 2 * geo.kvWidth(); l.qkvg = try x.linear(&.{ try name(&b1, i, "self_attn.q_k_v_proj"), try name(&b2, i, "self_attn.g_proj") }, &.{ qkv, geo.query_heads }, h); l.out = try x.linear(&.{try name(&b1, i, "self_attn.out_proj")}, &.{h}, geo.queryWidth()); - l.gate = try x.linear(&.{try name(&b1, i, "mlp.gate_proj")}, &.{geo.intermediate}, h); - l.up = try x.linear(&.{try name(&b1, i, "mlp.up_proj")}, &.{geo.intermediate}, h); + if (cuda.qlinear.servedBits(c.bits) == 4) { + const gu = try x.linear(&.{ try name(&b1, i, "mlp.gate_proj"), try name(&b2, i, "mlp.up_proj") }, &.{ geo.intermediate, geo.intermediate }, h); + const views = try gateUpViews(gu.a4, geo.intermediate); + l.gate = .{ .a4 = views[0] }; + l.up = .{ .a4 = views[1] }; + } else { + l.gate = try x.linear(&.{try name(&b1, i, "mlp.gate_proj")}, &.{geo.intermediate}, h); + l.up = try x.linear(&.{try name(&b1, i, "mlp.up_proj")}, &.{geo.intermediate}, h); + } l.down = try x.linear(&.{try name(&b1, i, "mlp.down_proj")}, &.{h}, geo.intermediate); l.input_norm = try x.widened(try name(&b1, i, "input_layernorm.weight"), h); l.post_attention = try x.widened(try name(&b1, i, "post_attention_layernorm.weight"), h); @@ -192,3 +199,44 @@ pub fn load(gpa: std.mem.Allocator, io: std.Io, d: *const cuda.Driver, s: cuda.S } return w; } + +/// Two aligned members of one packed gate|up allocation, retaining each member's n and the stack's metadata stride. +pub fn gateUpViews(stack: Affine4, n: usize) ![2]Affine4 { + if (n == 0 or n % 128 != 0 or stack.n != 2 * n or stack.npad < stack.n or stack.npad % 128 != 0 or stack.k == 0 or stack.k % 64 != 0) + return error.UnsupportedGateUpStack; + var gate = stack; + gate.n = n; + var up = gate; + up.w += n * stack.k / 2; + up.s += n * 2; + up.b += n * 2; + return .{ gate, up }; +} + +test "Spark gate-up stack preserves each member's codes metadata stride and split-K" { + const n = cfg.spark4b.intermediate; + const k = cfg.spark4b.hidden; + const stack: Affine4 = .{ .w = 0x100000, .s = 0x2000000, .b = 0x3000000, .n = 2 * n, .k = k, .npad = 2 * n }; + const views = try gateUpViews(stack, n); + for (views, 0..) |view, member| { + try std.testing.expectEqual(n, view.n); + try std.testing.expectEqual(k, view.k); + try std.testing.expectEqual(stack.npad, view.npad); + try std.testing.expectEqual(@as(usize, 2), cuda.qlinear.splitK(view.n, view.k)); + for (0..k / 64) |g| { + for (0..n) |col| { + const absolute = g * stack.npad + member * n + col; + try std.testing.expectEqual(stack.s + absolute * 2, view.s + (g * view.npad + col) * 2); + try std.testing.expectEqual(stack.b + absolute * 2, view.b + (g * view.npad + col) * 2); + } + for (0..n / 64) |tile| for ([_]usize{ 0, 17, 511 }) |word| { + const local = (tile * (k / 64) + g) * 512 + word; + const absolute = ((member * n / 64 + tile) * (k / 64) + g) * 512 + word; + try std.testing.expectEqual(stack.w + absolute * 4, view.w + local * 4); + }; + } + } + try std.testing.expectEqual(@as(usize, 1), cuda.qlinear.splitK(stack.n, stack.k)); + try std.testing.expectError(error.UnsupportedGateUpStack, gateUpViews(stack, n - 1)); + try std.testing.expectError(error.UnsupportedGateUpStack, gateUpViews(stack, n / 2)); +} diff --git a/zig/src/glm_restore_compile.zig b/zig/src/glm_restore_compile.zig index be676f6f94a..b7e6b1cd01c 100644 --- a/zig/src/glm_restore_compile.zig +++ b/zig/src/glm_restore_compile.zig @@ -1,4 +1,19 @@ //! Compile the actual GLM restoration entry, including its default drained pool mover; never run this object. +pub const safetensors = @import("core/safetensors.zig"); +pub const checkpoint_host = @import("core/checkpoint.zig"); +pub const Checkpoint = checkpoint_host.Checkpoint; +pub const checkpoint_metal = @import("core/checkpoint_metal.zig"); +pub const quant = @import("core/quant/quant.zig"); +pub const row_projection = @import("core/row_projection.zig"); +pub const lane_projection = @import("core/lane_projection.zig"); +pub const affine4 = @import("core/affine4.zig"); +pub const affine4_lane = @import("core/affine4_lane.zig"); +pub const gpu_profile = @import("core/gpu_profile.zig"); +pub const shared_attention = @import("core/shared_attention.zig"); +pub const bf16_topk = @import("bf16_topk"); +pub const bf16_topk_gpu = @import("bf16_topk_gpu"); +pub const draft_ops = @import("draft_ops"); + const Backend = @import("families/glm/backend.zig").Backend; const Stream = @import("lanes").Stream; diff --git a/zig/src/glm_schedule_tests.zig b/zig/src/glm_schedule_tests.zig index 8e0ffe0d5c0..46b9131e1b9 100644 --- a/zig/src/glm_schedule_tests.zig +++ b/zig/src/glm_schedule_tests.zig @@ -1,4 +1,19 @@ //! GLM's actual prefill capability and chunk driver behind the real shared lane host, without Metal execution. +pub const safetensors = @import("core/safetensors.zig"); +pub const checkpoint_host = @import("core/checkpoint.zig"); +pub const Checkpoint = checkpoint_host.Checkpoint; +pub const checkpoint_metal = @import("core/checkpoint_metal.zig"); +pub const quant = @import("core/quant/quant.zig"); +pub const row_projection = @import("core/row_projection.zig"); +pub const lane_projection = @import("core/lane_projection.zig"); +pub const affine4 = @import("core/affine4.zig"); +pub const affine4_lane = @import("core/affine4_lane.zig"); +pub const gpu_profile = @import("core/gpu_profile.zig"); +pub const shared_attention = @import("core/shared_attention.zig"); +pub const bf16_topk = @import("bf16_topk"); +pub const bf16_topk_gpu = @import("bf16_topk_gpu"); +pub const draft_ops = @import("draft_ops"); + test { _ = @import("families/glm/prefill_test.zig"); _ = @import("families/glm/prompt_images_test.zig"); diff --git a/zig/src/hip/admission.zig b/zig/src/hip/admission.zig index dd612d46e85..a9a8e3e27b9 100644 --- a/zig/src/hip/admission.zig +++ b/zig/src/hip/admission.zig @@ -70,6 +70,13 @@ pub fn budget(gpa: Allocator, io: std.Io, ctx: Context) !Pool { return p.pool; } +/// Whether `ctx`'s budget counts the host's pages: an integrated GPU without a carve-out shares them with host buffers. +pub fn sharesHost(gpa: Allocator, io: std.Io, ctx: Context) bool { + const integrated = (ctx.attribute(.integrated) catch return false) != 0; + const card = ctx.memInfo() catch return false; + return sourceOf(integrated, .{ .total = card.total, .available = card.free }, vramBytes(gpa, io, ctx)) == .host; +} + /// Where a budget's count comes from: a discrete card, an integrated GPU's firmware carve-out, or the host's pages. pub const Source = enum { card, carve_out, host }; diff --git a/zig/src/hip/kernel_tests/nemotron/window.zig b/zig/src/hip/kernel_tests/nemotron/window.zig index 2d4bc3d5363..3e58bfddcd7 100644 --- a/zig/src/hip/kernel_tests/nemotron/window.zig +++ b/zig/src/hip/kernel_tests/nemotron/window.zig @@ -158,7 +158,7 @@ test "the Mamba window's two launches write the bytes of the mixer a row at a ti .{ .heads = 4, .dh = 64, .groups = 2 }, }; var cases: usize = 0; - for (shapes) |sh| for ([_]usize{ 1, 2, 3, 4, 7, 17 }) |rows| for ([_]bool{ true, false }) |snaps| { + for (shapes) |sh| for ([_]usize{ 1, 2, 3, 4, 5, 6, 7, 8, 12, 15, 16, 17 }) |rows| for ([_]bool{ true, false }) |snaps| { try rig.expect( try window(t, &rng, sh, rows, snaps), "mamba window {d} heads, {d} groups, {d} rows, snapshots {}: the bytes differ", diff --git a/zig/src/metal/metal4_timeline.zig b/zig/src/metal/metal4_timeline.zig index 3f6d1b32e1a..ca65d402aa4 100644 --- a/zig/src/metal/metal4_timeline.zig +++ b/zig/src/metal/metal4_timeline.zig @@ -59,12 +59,21 @@ pub const Timeline = struct { std.log.warn("metal 4 timeline: no timestamp heap ({s})", .{objc.errorText(err)}); return null; }; - const t = heap.create(Timeline) catch return null; + const freq: f64 = @floatFromInt(objc.msg(u64, device, "queryTimestampFrequency", .{})); + return initHeap(counters, freq, want, heap) catch { + objc.release(counters); + return null; + }; + } + + fn initHeap(counters: Id, freq: f64, want: u32, a: std.mem.Allocator) !*Timeline { + const t = try a.create(Timeline); + errdefer a.destroy(t); t.* = .{ .counters = counters, - .freq = @floatFromInt(objc.msg(u64, device, "queryTimestampFrequency", .{})), + .freq = freq, .want = want, - .marks = heap.alloc(Mark, cap) catch return null, + .marks = try a.alloc(Mark, cap), }; return t; } @@ -102,10 +111,16 @@ pub const Timeline = struct { } fn find(t: *Timeline, name: []const u8) ?*Rounds { + return t.findUsing(heap, name) catch null; + } + + fn findUsing(t: *Timeline, a: std.mem.Allocator, name: []const u8) !*Rounds { for (t.rounds.items) |r| if (std.mem.eql(u8, r.name, name)) return r; - const r = heap.create(Rounds) catch return null; - r.* = .{ .name = heap.dupe(u8, name) catch return null }; - t.rounds.append(heap, r) catch return null; + const r = try a.create(Rounds); + errdefer a.destroy(r); + r.* = .{ .name = try a.dupe(u8, name) }; + errdefer a.free(r.name); + try t.rounds.append(a, r); return r; } @@ -176,14 +191,11 @@ pub const Timeline = struct { r.inside += d; r.dispatches += m.n; const key = t.keyOf(m) catch continue; - const g = r.kernels.getOrPut(heap, key) catch continue; - if (g.found_existing) heap.free(key) else g.value_ptr.* = .{}; - g.value_ptr.s += d; - g.value_ptr.stages += 1; + const kernel = Timeline.addKernel(r, heap, key, d) catch continue; if (first) { - r.each.append(heap, d) catch {}; - r.keys.append(heap, heap.dupe(u8, g.key_ptr.*) catch "") catch {}; - r.encs.append(heap, m.enc) catch {}; + Timeline.appendStage(r, heap, d, kernel, m.enc) catch { + r.fits = false; + }; } else if (j < r.each.items.len) r.each.items[j] += d else r.fits = false; j += 1; } @@ -195,6 +207,17 @@ pub const Timeline = struct { return if (b > a) @as(f64, @floatFromInt(b - a)) / t.freq else 0; } + fn addKernel(r: *Rounds, a: std.mem.Allocator, key: []u8, d: f64) ![]const u8 { + const g = r.kernels.getOrPut(a, key) catch |err| { + a.free(key); + return err; + }; + if (g.found_existing) a.free(key) else g.value_ptr.* = .{}; + g.value_ptr.s += d; + g.value_ptr.stages += 1; + return g.key_ptr.*; + } + /// The stage's kernels by label, joined. fn keyOf(t: *Timeline, m: Mark) ![]u8 { var out: std.ArrayList(u8) = .empty; @@ -208,13 +231,31 @@ pub const Timeline = struct { } fn label(t: *Timeline, id: Id) []const u8 { - const g = t.labels.getOrPut(heap, @intFromPtr(id)) catch return "?"; - if (g.found_existing) return g.value_ptr.*; + if (t.labels.get(@intFromPtr(id))) |known| return known; const text = if (objc.msg(?Id, id, "label", .{})) |s| std.mem.span(objc.utf8(s)) else "unnamed kernel"; - g.value_ptr.* = heap.dupe(u8, text) catch "?"; + return t.rememberLabel(heap, id, text); + } + + fn rememberLabel(t: *Timeline, a: std.mem.Allocator, id: Id, text: []const u8) []const u8 { + const g = t.labels.getOrPut(a, @intFromPtr(id)) catch return "?"; + if (g.found_existing) return g.value_ptr.*; + g.value_ptr.* = a.dupe(u8, text) catch { + _ = t.labels.remove(@intFromPtr(id)); + return "?"; + }; return g.value_ptr.*; } + fn appendStage(r: *Rounds, a: std.mem.Allocator, d: f64, key: []const u8, enc: u32) !void { + const owned = try a.dupe(u8, key); + errdefer a.free(owned); + try r.each.append(a, d); + errdefer _ = r.each.pop(); + try r.keys.append(a, owned); + errdefer _ = r.keys.pop(); + try r.encs.append(a, enc); + } + fn report(t: *Timeline, r: *Rounds) void { _ = t; const n: f64 = @floatFromInt(r.done); @@ -253,3 +294,62 @@ pub const Timeline = struct { } } }; + +test "timeline stage records: allocation failures keep parallel arrays valid" { + for (0..4) |fail_at| { + var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{ .fail_index = fail_at }); + const a = failing.allocator(); + var r: Rounds = .{ .name = @constCast("test") }; + defer { + for (r.keys.items) |key| a.free(key); + r.each.deinit(a); + r.keys.deinit(a); + r.encs.deinit(a); + } + Timeline.appendStage(&r, a, 1.0, "kernel", 2) catch |err| try std.testing.expectEqual(error.OutOfMemory, err); + try std.testing.expectEqual(r.each.items.len, r.keys.items.len); + try std.testing.expectEqual(r.each.items.len, r.encs.items.len); + } +} + +test "timeline rounds: failed construction releases every allocation" { + for (0..3) |fail_at| { + var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{ .fail_index = fail_at }); + const a = failing.allocator(); + var timeline: Timeline = undefined; + timeline.rounds = .empty; + defer timeline.rounds.deinit(a); + try std.testing.expectError(error.OutOfMemory, timeline.findUsing(a, "round")); + try std.testing.expectEqual(failing.allocated_bytes, failing.freed_bytes); + } +} + +test "timeline init: failed host storage releases its allocations" { + for (0..2) |fail_at| { + var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{ .fail_index = fail_at }); + const a = failing.allocator(); + const counters: Id = @ptrFromInt(16); + try std.testing.expectError(error.OutOfMemory, Timeline.initHeap(counters, 1.0, 1, a)); + try std.testing.expectEqual(failing.allocated_bytes, failing.freed_bytes); + } +} + +test "timeline kernels: failed insertion releases the owned key" { + var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{ .fail_index = 1 }); + const a = failing.allocator(); + var r: Rounds = .{ .name = @constCast("test") }; + defer r.kernels.deinit(a); + const key = try a.dupe(u8, "kernel"); + try std.testing.expectError(error.OutOfMemory, Timeline.addKernel(&r, a, key, 1.0)); + try std.testing.expectEqual(failing.allocated_bytes, failing.freed_bytes); +} + +test "timeline labels: a refused copy leaves no borrowed entry" { + var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{ .fail_index = 1 }); + const a = failing.allocator(); + var t: Timeline = undefined; + t.labels = .empty; + defer t.labels.deinit(a); + try std.testing.expectEqualStrings("?", t.rememberLabel(a, @ptrFromInt(16), "kernel")); + try std.testing.expectEqual(@as(u32, 0), t.labels.count()); +} diff --git a/zig/src/metal_prefill_rest_compile.zig b/zig/src/metal_prefill_rest_compile.zig index e672039eba4..a3ac1efc5f6 100644 --- a/zig/src/metal_prefill_rest_compile.zig +++ b/zig/src/metal_prefill_rest_compile.zig @@ -8,7 +8,20 @@ export fn gemma4PrefillCompile(b: *tf.gemma4.backend.Metal, s: *lanes.Stream) bo } export fn lfm2PrefillCompile(b: *tf.lfm2_moe.backend.Metal, s: *lanes.Stream) bool { - b.backend().prefill(s) catch return false; + const backend = b.backend(); + backend.prefill(s) catch return false; + // the stepped pass and its cancel (#3021), which the lane host calls between rounds + _ = backend.vtable.prefill_step.?(backend.ptr, s, 0) catch return false; + backend.vtable.cancel_prefill.?(backend.ptr, s) catch return false; + return true; +} + +export fn lfm3PrefillCompile(b: *tf.lfm3.backend.Metal, s: *lanes.Stream) bool { + const backend = b.backend(); + backend.prefill(s) catch return false; + // the stepped pass and its cancel (#3021), which the lane host calls between rounds + _ = backend.vtable.prefill_step.?(backend.ptr, s, 0) catch return false; + backend.vtable.cancel_prefill.?(backend.ptr, s) catch return false; return true; } @@ -23,7 +36,11 @@ export fn sparkPrefillCompile(b: *tf.spark25_metal.backend.Metal, s: *lanes.Stre } export fn minimaxPrefillCompile(b: *tf.minimax_m3.backend.Metal, s: *lanes.Stream) bool { - b.backend().prefill(s) catch return false; + const backend = b.backend(); + backend.prefill(s) catch return false; + // the stepped pass and its cancel (#3021), which the lane host calls between rounds + _ = backend.vtable.prefill_step.?(backend.ptr, s, 0) catch return false; + backend.vtable.cancel_prefill.?(backend.ptr, s) catch return false; return true; } @@ -33,7 +50,11 @@ export fn llamaPrefillCompile(b: *tf.llama.backend.Metal, s: *lanes.Stream) bool } export fn qwen35PrefillCompile(b: *tf.qwen35.backend.Metal, s: *lanes.Stream) bool { - b.backend().prefill(s) catch return false; + const backend = b.backend(); + backend.prefill(s) catch return false; + // the stepped pass and its cancel (#3021), which the lane host calls between rounds + _ = backend.vtable.prefill_step.?(backend.ptr, s, 0) catch return false; + backend.vtable.cancel_prefill.?(backend.ptr, s) catch return false; return true; } diff --git a/zig/src/native/cuda.zig b/zig/src/native/cuda.zig index f222c979d8a..59cea16eb43 100644 --- a/zig/src/native/cuda.zig +++ b/zig/src/native/cuda.zig @@ -8,6 +8,7 @@ const lanes = @import("lanes"); const nemotron = @import("nemotron"); const family_memory = @import("cuda_family_memory.zig"); const pool = family_memory.pool; +const page_drop = @import("cuda_page_drop.zig"); const family_options = @import("cuda_options.zig"); pub const follow = @import("cuda_follow.zig").follow; const lfm2 = @import("lfm2.zig"); @@ -208,8 +209,7 @@ fn openWith(comptime F: type, a: Allocator, gpa: Allocator, io: std.Io, asked: a return null; }; if (raised.window != null and window > own) std.log.info("{s}", .{try windows.pastTrained(a, window, own, raised.switch_name)}); - if (o.slide) { - // a family learns once its module declares `slide` (its learner), `learnModel` and `linked` + if (o.slide) { // a family learns once its module declares `slide` (its learner), `learnModel` and `linked` if (!@hasDecl(F, "slide")) { problem.* = try std.fmt.allocPrint(a, "--slide: {s} checkpoints do not learn on CUDA yet", .{o.model_type}); return null; @@ -269,6 +269,7 @@ fn openWith(comptime F: type, a: Allocator, gpa: Allocator, io: std.Io, asked: a return null; }, }; + if ((try g.ctx.attribute(.integrated)) != 0) _ = page_drop.drop(a, io, o.dir); // GB10: drop cached shards (#1857) const before = try pool(a, io, &g.ctx, problem) orelse return null; // a family split over hosts holds only its rank's share (GLM-5.3-Flash's TP) const weights = try family_memory.weights(F, a, io, o, problem) orelse return null; @@ -382,8 +383,7 @@ fn openWith(comptime F: type, a: Allocator, gpa: Allocator, io: std.Io, asked: a errdefer gpa.destroy(h); h.* = .{ .gpa = gpa, .gpu = g, .family = loaded.ctx, .release = loaded.deinit, .inner = served.backend, .served = served, .vtable = undefined, .cfg = undefined, .clock = undefined, .core = undefined, .host = undefined, .lone = if (@hasField(L, "lone")) loaded.lone else null }; h.readiness(F); - h.kv_plan = counted.ledger; - // a ledger's plan placed the cache already, beside --parallel full-window requests + h.kv_plan = counted.ledger; // a ledger's plan placed the cache already, beside --parallel full-window requests const kept = if (host_cache) kv_pages.kept(F, loaded, paged, o, room, held, final_host_budget, true) else if (counted.ledger) |lp| lp.kept else kv_pages.kept(F, loaded, paged, o, room, held, 0, false); if (h.kv_plan) |*lp| lp.kept = kept; const cache = kept.copied; @@ -497,12 +497,14 @@ const toGib = family_memory.toGib; const familyInfo = @import("cuda_family_info.zig").familyInfo; test { + _ = @import("cuda_qwen_host_test.zig"); _ = @import("cuda_family_info.zig"); _ = @import("draft_sources_cuda_test.zig"); _ = @import("copy_drafts_nemotron_test.zig"); _ = windows; _ = @import("cuda_startup_test.zig"); _ = budget; // cuda_memory.zig's own tests, which no other test binary reaches + _ = page_drop; _ = refusals; _ = lane_backend; _ = snaps; diff --git a/zig/src/native/cuda_families.zig b/zig/src/native/cuda_families.zig index bbcfc640a25..6741ad5526a 100644 --- a/zig/src/native/cuda_families.zig +++ b/zig/src/native/cuda_families.zig @@ -66,3 +66,17 @@ test "capability audit: CUDA Qwen3.5 lists BF16 under decisions only, the MoE en } else try std.testing.expectEqual(@as(usize, 0), f.decision_formats.len); } } + +test "capability audit: dense Qwen3.5 lists the ModelOpt formats its loader reads" { + for (families) |f| if (std.mem.eql(u8, f.model_type, "qwen3_5")) { + var nvfp4 = false; + var mixed = false; + for (f.formats) |format| { + nvfp4 = nvfp4 or std.mem.eql(u8, format, "modelopt-nvfp4"); + mixed = mixed or std.mem.eql(u8, format, "modelopt-mixed"); + } + try std.testing.expect(nvfp4 and mixed); + return; + }; + return error.NoQwen35Family; +} diff --git a/zig/src/native/cuda_family_memory.zig b/zig/src/native/cuda_family_memory.zig index 56db251f435..ae03435ec05 100644 --- a/zig/src/native/cuda_family_memory.zig +++ b/zig/src/native/cuda_family_memory.zig @@ -34,7 +34,7 @@ pub fn poolFor(comptime windows: bool, comptime Host: type, a: Allocator, io: st return null; }; const available = budget.counting(measured, zones); - const free = available.available; + const free = budget.boundFree(host_counts, available.available, card.free); const total = available.total; const reserve = budget.reserveBytes(Host.env("TENSORFOLD_MEMORY_RESERVE_GIB"), total, unified) catch { problem.* = try std.fmt.allocPrint(a, "TENSORFOLD_MEMORY_RESERVE_GIB={s}: a number of GiB from {d} to the memory's size", .{ Host.env("TENSORFOLD_MEMORY_RESERVE_GIB").?, budget.floor(unified).least }); @@ -44,7 +44,7 @@ pub fn poolFor(comptime windows: bool, comptime Host: type, a: Allocator, io: st problem.* = try std.fmt.allocPrint(a, "TENSORFOLD_CUDA_MEMORY_LIMIT_GB={s}: a positive number of GiB whose byte count fits in a 64-bit size", .{Host.env("TENSORFOLD_CUDA_MEMORY_LIMIT_GB").?}); return null; }; - return .{ .free = free, .total = total, .reserve = reserve, .limit = limit, .unified = unified, .parked = free - measured.available }; + return .{ .free = free, .total = total, .reserve = reserve, .limit = limit, .unified = unified, .parked = free -| measured.available }; } /// `F`'s weight bytes on this rank: tensors or files, a split's share, a tower beside; null if tensors are unreadable. diff --git a/zig/src/native/cuda_family_memory_test.zig b/zig/src/native/cuda_family_memory_test.zig index e4a836240cf..b696dac12f9 100644 --- a/zig/src/native/cuda_family_memory_test.zig +++ b/zig/src/native/cuda_family_memory_test.zig @@ -1,14 +1,17 @@ const std = @import("std"); const cuda = @import("cuda"); const poolFor = @import("cuda_family_memory.zig").poolFor; +const toGib = @import("cuda_family_memory.zig").toGib; const t = std.testing; const Fake = struct { var integrated: c_int = 1; + var card_free: usize = 40 << 30; // what cuMemGetInfo reports free var missing = false; var text: ?[]const u8 = null; var zones: ?[]const u8 = null; var probes: usize = 0; var zone_probes: usize = 0; + var reserve: ?[:0]const u8 = null; // TENSORFOLD_MEMORY_RESERVE_GIB fn attribute(out: *c_int, _: cuda.abi.DeviceAttribute, _: c_int) callconv(.c) cuda.abi.Result { out.* = integrated; return 0; @@ -16,7 +19,7 @@ const Fake = struct { fn memInfo(free: *usize, total: *usize) callconv(.c) cuda.abi.Result { if (missing) return cuda.abi.error_not_ready; total.* = 64 << 30; - free.* = 40 << 30; + free.* = card_free; return 0; } pub fn procText(a: std.mem.Allocator, _: std.Io, path: []const u8) ?[]u8 { @@ -33,6 +36,7 @@ const Fake = struct { const n = std.mem.span(name); if (std.mem.eql(u8, n, "TENSORFOLD_UNIFIED_HOST_COUNTS")) return host_counts; if (std.mem.eql(u8, n, "WSL_DISTRO_NAME")) return wsl_distro; + if (std.mem.eql(u8, n, "TENSORFOLD_MEMORY_RESERVE_GIB")) return reserve; return null; } }; @@ -58,7 +62,9 @@ test "Windows pool: real CUDA counts, OS selection, unified reserves and missing Fake.text = "MemTotal: broken\n"; try t.expect((try poolFor(false, Fake, t.allocator, t.io, &ctx, &problem)) == null); Fake.text = "MemTotal: 134217728 kB\nMemAvailable: 100663296 kB\n"; + Fake.card_free = 128 << 30; // a card with more free than the host counts: the host's figure stands const linux = (try poolFor(false, Fake, t.allocator, t.io, &ctx, &problem)).?; + Fake.card_free = 40 << 30; try t.expect(linux.unified); try t.expectEqual(@as(u64, 128 << 30), linux.total); try t.expectEqual(@as(u64, 96 << 30), linux.free); @@ -97,6 +103,8 @@ test "a Linux unified pool counts the free pages parked on the per-CPU lists, at Fake.integrated = 1; Fake.text = "MemTotal: 134217728 kB\nMemAvailable: 100663296 kB\n"; defer Fake.zones = null; + Fake.card_free = 128 << 30; // the host's counts stand below the card's free + defer Fake.card_free = 40 << 30; const six = try zoneinfo(t.allocator, 6 * g); defer t.allocator.free(six); Fake.zones = six; @@ -111,6 +119,7 @@ test "a Linux unified pool counts the free pages parked on the per-CPU lists, at } Fake.zones = six; Fake.zone_probes = 0; + Fake.card_free = 40 << 30; const windows = (try poolFor(true, Fake, t.allocator, t.io, &ctx, &problem)).?; try t.expectEqual(@as(u64, 40 << 30), windows.free); Fake.integrated = 0; @@ -130,16 +139,72 @@ test "the pool names the parked share it counted, for the debug log line" { Fake.integrated = 1; Fake.text = "MemTotal: 134217728 kB\nMemAvailable: 130023424 kB\n"; defer Fake.zones = null; + Fake.card_free = 128 << 30; + defer Fake.card_free = 40 << 30; const six = try zoneinfo(t.allocator, 6 * g); defer t.allocator.free(six); Fake.zones = six; try t.expectEqual(4 * g, (try poolFor(false, Fake, t.allocator, t.io, &ctx, &problem)).?.parked); // to MemTotal Fake.text = "MemTotal: 134217728 kB\nMemAvailable: 100663296 kB\n"; try t.expectEqual(6 * g, (try poolFor(false, Fake, t.allocator, t.io, &ctx, &problem)).?.parked); + Fake.card_free = 100 << 30; // CUDA's free bounds the pool: only the parked pages within it are counted + try t.expectEqual(4 * g, (try poolFor(false, Fake, t.allocator, t.io, &ctx, &problem)).?.parked); + Fake.card_free = 90 << 30; + try t.expectEqual(@as(u64, 0), (try poolFor(false, Fake, t.allocator, t.io, &ctx, &problem)).?.parked); + Fake.card_free = 128 << 30; Fake.zones = null; try t.expectEqual(@as(u64, 0), (try poolFor(false, Fake, t.allocator, t.io, &ctx, &problem)).?.parked); } +fn unifiedCtx(driver: *cuda.Driver) cuda.Context { + driver.api.cuDeviceGetAttribute = Fake.attribute; + driver.api.cuMemGetInfo_v2 = Fake.memInfo; + return .{ .d = driver, .device = 0, .handle = null }; +} + +test "a GB10 after a 60 GB checkpoint read (6 Nov): CUDA's free bounds the pool, not MemAvailable's page cache" { + var driver: cuda.Driver = undefined; + const ctx = unifiedCtx(&driver); + var problem: []const u8 = ""; + const g: u64 = 1 << 30; + Fake.missing = false; + Fake.integrated = 1; + Fake.zones = null; + defer Fake.card_free = 40 << 30; + defer Fake.reserve = null; + Fake.text = "MemTotal: 127535276 kB\nMemAvailable: 121477530 kB\n"; // a GB10's 121.63 GiB, 115.85 GiB available + Fake.card_free = 6017 * g / 100; // CUDA's 60.17 GiB free + Fake.reserve = "12.41"; // the reserve 6 Nov's 103.44 GiB grant implies + const p = (try poolFor(false, Fake, t.allocator, t.io, &ctx, &problem)).?; + const host: u64 = 121477530 * 1024; + try t.expect(p.unified); + try t.expectEqual(@as(u64, Fake.card_free), p.free); + try t.expectApproxEqAbs(103.44, toGib(host - p.reserve), 0.005); // the grant MemAvailable alone gave + try t.expectApproxEqAbs(43.27, toGib(host - p.reserve - p.free), 0.005); // above CUDA's free + try t.expectEqual(p.free - p.reserve, p.room(0)); // now CUDA's free less the reserve: 47.76 GiB + try t.expectApproxEqAbs(47.76, toGib(p.room(0)), 0.005); +} + +test "a discrete card keeps its own counts: /proc is not read and its free is taken as reported" { + var driver: cuda.Driver = undefined; + const ctx = unifiedCtx(&driver); + var problem: []const u8 = ""; + Fake.missing = false; + Fake.integrated = 0; + defer Fake.integrated = 1; + defer Fake.card_free = 40 << 30; + Fake.text = "MemTotal: 134217728 kB\nMemAvailable: 1048576 kB\n"; // a host figure far below: never read + Fake.card_free = 30 << 30; + Fake.probes = 0; + inline for (.{ false, true }) |windows| { + const p = (try poolFor(windows, Fake, t.allocator, t.io, &ctx, &problem)).?; + try t.expect(!p.unified); + try t.expectEqual(@as(u64, 30 << 30), p.free); + try t.expectEqual(@as(u64, 64 << 30), p.total); + } + try t.expectEqual(@as(usize, 0), Fake.probes); +} + test "Windows pool: WSL2 reads it too, TENSORFOLD_UNIFIED_HOST_COUNTS takes only 0 or 1, and refuses a typo by name" { var driver: cuda.Driver = undefined; driver.api.cuDeviceGetAttribute = Fake.attribute; diff --git a/zig/src/native/cuda_kv_host.zig b/zig/src/native/cuda_kv_host.zig new file mode 100644 index 00000000000..3ce31a405b6 --- /dev/null +++ b/zig/src/native/cuda_kv_host.zig @@ -0,0 +1,21 @@ +//! One host-backed Qwen window, with its table and state run charged to device memory. +const std = @import("std"); +const api = @import("engine_api"); +const kv = @import("core").kv_pool; + +pub fn plan(a: std.mem.Allocator, l: kv.Layout, room: u64, o: api.Open, host: u64, problem: *[]const u8) !?kv.Plan { + if (o.lanes != 1) { + problem.* = "TF_QWEN_KV_HOST supports one stream: set --parallel 1"; + return null; + } + const device = try deviceBytes(l); + if (device > room) { + problem.* = try std.fmt.allocPrint(a, "TF_QWEN_KV_HOST needs {d} device bytes for its table and state run; the budget leaves {d}", .{ device, room }); + return null; + } + return .{ .lanes = 1, .pages = @intCast(host / l.pageBytes()), .snaps = 0, .copied = 0 }; +} + +pub fn deviceBytes(l: kv.Layout) !u64 { + return std.math.add(u64, try std.math.mul(u64, l.runPages(), l.pageBytes()), l.fixed_bytes); +} diff --git a/zig/src/native/cuda_kv_pool.zig b/zig/src/native/cuda_kv_pool.zig index b02d2e47766..c85ae511608 100644 --- a/zig/src/native/cuda_kv_pool.zig +++ b/zig/src/native/cuda_kv_pool.zig @@ -195,6 +195,10 @@ pub fn attach(comptime F: type, a: Allocator, ctx: *anyopaque, paged: ?Plan, pla if (comptime !@hasDecl(F, "attach")) return true; const p = paged orelse return true; F.attach(ctx, p.lanes - 1, p.pages) catch |e| { + if (comptime @hasDecl(F, "kvHostRefusal")) if (F.explain(null, e)) |why| { + problem.* = why; + return false; + }; problem.* = try std.fmt.allocPrint(a, "the CUDA engine could not make its {d} streams' pages ({s})", .{ p.lanes - 1, @errorName(e) }); return false; }; @@ -520,7 +524,6 @@ test "CUDA cache default leaves seven full windows beside an unpaged engine" { explicit.prompt_cache_gib = 40; try std.testing.expectEqual(@as(u64, 40 * GiB), budgetOf(struct {}, l, 88 * GiB, explicit, 8192, false, false, 0, null).cache); } - test "CUDA cache default uses half of unpaged room when it exceeds the floor" { const GiB: u64 = 1 << 30; const l: kv_pool.Layout = .{ .fixed_bytes = 0, .token_bytes = 1 << 20, .page_tokens = 1, .snap_bytes = 0 }; @@ -532,7 +535,6 @@ test "CUDA cache default uses half of unpaged room when it exceeds the floor" { try std.testing.expectEqual(@as(usize, 7 * 8192), p.pages); try std.testing.expectEqual(@as(u64, 24 * GiB), p.copied); } - test "CUDA cache default leaves no copies when unpaged windows use all room" { const GiB: u64 = 1 << 30; const l: kv_pool.Layout = .{ .fixed_bytes = 0, .token_bytes = 1 << 20, .page_tokens = 1, .snap_bytes = 0 }; @@ -544,7 +546,6 @@ test "CUDA cache default leaves no copies when unpaged windows use all room" { try std.testing.expectEqual(@as(usize, 7 * 8192), p.pages); try std.testing.expectEqual(@as(u64, 0), p.copied); } - const Promptless = struct { pub const keeps_no_prompts = true; }; diff --git a/zig/src/native/cuda_memory.zig b/zig/src/native/cuda_memory.zig index a48cd5b9b5a..63794c85f5a 100644 --- a/zig/src/native/cuda_memory.zig +++ b/zig/src/native/cuda_memory.zig @@ -254,6 +254,11 @@ pub fn counts(unified: bool, card: MemInfo, text: ?[]const u8) error{HostMemoryU return card; } +/// The pool's free: on unified Linux at most CUDA's, as MemAvailable counts page cache CUDA can't allocate (#1857). +pub fn boundFree(host_counts: bool, counted: u64, card_free: u64) u64 { + return if (host_counts) @min(counted, card_free) else counted; +} + test "the memory plan: reserve, cap, and admission that fails closed" { const g: u64 = 1 << 30; try std.testing.expectEqual(4 * g, try reserveBytes(null, 24 * g, true)); // unified: at least 4 GiB @@ -381,6 +386,7 @@ pub fn readPool(a: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, prob return null; }; const available = counting(measured, zones); + const free = boundFree(host_counts, available.available, card.free); const reserve_text = if (std.c.getenv("TENSORFOLD_MEMORY_RESERVE_GIB")) |p| std.mem.span(p) else null; const limit_text = if (std.c.getenv("TENSORFOLD_CUDA_MEMORY_LIMIT_GB")) |p| std.mem.span(p) else null; const reserve = reserveBytes(reserve_text, available.total, unified) catch { @@ -391,7 +397,7 @@ pub fn readPool(a: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, prob problem.* = try std.fmt.allocPrint(a, "TENSORFOLD_CUDA_MEMORY_LIMIT_GB={s}: a positive number of GiB whose byte count fits in a 64-bit size", .{limit_text orelse ""}); return null; }; - return .{ .free = available.available, .total = available.total, .reserve = reserve, .limit = limit, .unified = unified, .parked = available.available - measured.available }; + return .{ .free = free, .total = available.total, .reserve = reserve, .limit = limit, .unified = unified, .parked = free -| measured.available }; } test "the weights' bytes: each file the weight map names once, under a folder too; without an index the folder's own" { @@ -466,6 +472,13 @@ test "a GB10's /proc files: its lists' parked pages raise MemAvailable and stay try std.testing.expect(meminfo(@embedFile("fixtures/gb10_parked/meminfo_at_budget")) != null); } +test "CUDA's free bounds a unified Linux pool only: Windows and discrete cards keep their counts" { + const g: u64 = 1 << 30; + try std.testing.expectEqual(60 * g, boundFree(true, 115 * g, 60 * g)); // MemAvailable held the page cache + try std.testing.expectEqual(96 * g, boundFree(true, 96 * g, 128 * g)); + try std.testing.expectEqual(40 * g, boundFree(false, 40 * g, 30 * g)); // `counted` is already the card's own +} + test "CUDA cache default counts streams before taking half the unified room" { const GiB: u64 = 1 << 30; const room = 88 * GiB; diff --git a/zig/src/native/cuda_page_drop.zig b/zig/src/native/cuda_page_drop.zig new file mode 100644 index 00000000000..77d08d8c018 --- /dev/null +++ b/zig/src/native/cuda_page_drop.zig @@ -0,0 +1,41 @@ +//! Unified memory (GB10): the checkpoint's cached pages leave the page cache before admission reads CUDA's free. +const std = @import("std"); +const core = @import("core"); + +/// The shards core's loader opens (shardFiles), advised DONTNEED before the load reads them; count of files advised. +pub fn drop(a: std.mem.Allocator, io: std.Io, dir: []const u8) usize { + if (@import("builtin").os.tag != .linux) return 0; + const files = core.checkpoint.shardFiles(a, io, dir) catch return 0; // an index naming files outside: none + defer core.checkpoint.freeShardFiles(a, files); + var n: usize = 0; + for (files) |path| { + const f = std.Io.Dir.cwd().openFile(io, path, .{}) catch continue; // the load reports a missing shard + defer f.close(io); + core.checkpoint.cache.drop(f); // clean cached pages only, held while a TP load is in flight + n += 1; + } + return n; +} + +test "the shards the index names leave the page cache before a load, their bytes unchanged; no other file" { + const a = std.testing.allocator; + const io = std.testing.io; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + try tmp.dir.writeFile(io, .{ .sub_path = "a.safetensors", .data = &@as([4096]u8, @splat('a')) }); + try tmp.dir.writeFile(io, .{ .sub_path = "stray.safetensors", .data = "s" }); + try tmp.dir.writeFile(io, .{ .sub_path = "model.safetensors.index.json", .data = + \\{"weight_map":{"x":"a.safetensors","y":"missing.safetensors","z":"a.safetensors"}} + }); + var path: [64]u8 = undefined; + const dir = try std.fmt.bufPrint(&path, ".zig-cache/tmp/{s}", .{tmp.sub_path}); + const linux = @import("builtin").os.tag == .linux; + try std.testing.expectEqual(@as(usize, if (linux) 1 else 0), drop(a, io, dir)); // a once, the stray never + const kept = try tmp.dir.readFileAlloc(io, "a.safetensors", a, .limited(8192)); + defer a.free(kept); + try std.testing.expectEqualSlices(u8, &@as([4096]u8, @splat('a')), kept); + try tmp.dir.writeFile(io, .{ .sub_path = "model.safetensors.index.json", .data = + \\{"weight_map":{"x":"../a.safetensors"}} + }); + try std.testing.expectEqual(@as(usize, 0), drop(a, io, dir)); // a name outside the folder: nothing advised +} diff --git a/zig/src/native/cuda_qwen_host_test.zig b/zig/src/native/cuda_qwen_host_test.zig new file mode 100644 index 00000000000..e0853412351 --- /dev/null +++ b/zig/src/native/cuda_qwen_host_test.zig @@ -0,0 +1,76 @@ +//! The real Qwen exports guard all geometry reads; host-only admission stays outside the unchanged plan. +const std = @import("std"); +const api = @import("engine_api"); +const qwen = @import("qwen35"); +const kv = @import("core").kv_pool; +const pages = @import("cuda_kv_pool.zig"); +const streams = @import("cuda_streams.zig"); +const host_plan = @import("cuda_kv_host.zig"); +const refusal = @import("cuda_refusal.zig"); +const env = @import("sys").env; +const t = std.testing; + +const Dense = struct { + pub const Options = struct {}; + pub const kvHostRoom = qwen.native.kvHostRoom; +}; +const Moe = struct { + pub const Options = struct {}; + pub const kvHostRoom = qwen.native_moe.kvHostRoom; +}; + +test "kv safety: Qwen host KV unset preserves dense and MoE plans with pages off or on, one and eight streams" { + _ = env.unsetenv("TF_QWEN_KV_HOST"); + _ = env.setenv("TF_QWEN_KV_HOST_GIB", "bad", 1); + defer _ = env.unsetenv("TF_QWEN_KV_HOST_GIB"); + const l: kv.Layout = .{ .fixed_bytes = 32, .token_bytes = 2, .page_tokens = 16, .snap_bytes = 0, .run_bytes = 64 }; + inline for (.{ Dense, Moe }) |F| { + try t.expectEqual(@as(u64, 0), try F.kvHostRoom(@ptrFromInt(0x1000))); + for ([_]u32{ 1, 8 }) |lanes| for ([_]bool{ false, true }) |on_pages| { + var problem: []const u8 = ""; + const o: api.Open = .{ .dir = "", .model_type = "qwen3_5", .lanes = lanes, .lanes_fixed = true }; + const loaded = .{ .ctx = @as(*anyopaque, @ptrFromInt(0x1000)), .layout = if (on_pages) @as(?kv.Layout, l) else null, .engine_paged = on_pages, .free_streams = @as(u32, 1), .stream_bytes = @as(u64, 64) }; + const got = (try streams.count(F, t.allocator, loaded, o, .{ .room = 10000, .model = 0, .reserve = 0, .low = "", .window = 128, .stream_bytes = 64, .host_cache = true, .host_budget = 0, .share = false }, &problem)).?; + try t.expectEqual(lanes, got.streams); + try t.expectEqual(@as(u64, 0), got.extra_device); + if (on_pages) { + const want = (try pages.plan(F, t.allocator, l, 10000, o, 128, &problem, true, true, 0, null)).?; + try t.expectEqual(want, got.paged.?); + try t.expectEqual(@as(usize, if (lanes == 1) 8 else 78), got.paged.?.pages); + } else try t.expect(got.paged == null); + }; + } +} + +test "kv safety: Qwen host KV refuses parallel and disk before device work for dense and MoE" { + _ = env.setenv("TF_QWEN_KV_HOST", "1", 1); + defer _ = env.unsetenv("TF_QWEN_KV_HOST"); + inline for (.{ qwen.native, qwen.native_moe }) |F| { + var o: api.Open = .{ .dir = "", .model_type = F.model_type, .lanes = 8 }; + try t.expectStringStartsWith(refusal.family(F, o).?, "TF_QWEN_KV_HOST supports one stream"); + o.lanes = 1; + o.spill = .evicted; + try t.expectStringStartsWith(refusal.family(F, o).?, "TF_QWEN_KV_HOST cannot use --spill-gib"); + o.spill = .off; + o.learn_conversations = true; + try t.expectStringStartsWith(refusal.family(F, o).?, "TF_QWEN_KV_HOST cannot use disk snapshots"); + o.learn_conversations = false; + try t.expect(refusal.family(F, o) == null); + } +} + +test "kv safety: Qwen host KV charges one device run and table before the host prompt cache" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const l: kv.Layout = .{ .fixed_bytes = 32, .token_bytes = 2, .page_tokens = 16, .snap_bytes = 0, .run_bytes = 64 }; + const o: api.Open = .{ .dir = "", .model_type = "qwen3_5", .lanes = 1 }; + var problem: []const u8 = ""; + try t.expectEqual(@as(u64, 96), try host_plan.deviceBytes(l)); + try t.expect((try host_plan.plan(arena.allocator(), l, 95, o, 256, &problem)) == null); + try t.expect(std.mem.indexOf(u8, problem, "TF_QWEN_KV_HOST") != null); + const p = (try host_plan.plan(arena.allocator(), l, 96, o, 256, &problem)).?; + try t.expectEqual(kv.Plan{ .lanes = 1, .pages = 8, .snaps = 0, .copied = 0 }, p); + const c = streams.cacheRoom(1000, 64, 1, .{ .streams = 1, .paged = p, .layout = l, .extra_device = 96 }); + try t.expectEqual(@as(u64, 904), c.room); + try t.expectEqual(@as(u64, 0), c.streams); +} diff --git a/zig/src/native/cuda_refusal.zig b/zig/src/native/cuda_refusal.zig index bf2d0c67617..921f5afed97 100644 --- a/zig/src/native/cuda_refusal.zig +++ b/zig/src/native/cuda_refusal.zig @@ -57,6 +57,7 @@ pub fn place(comptime F: type, a: std.mem.Allocator, o: api.Open) !?[]const u8 { /// A family takes --drafter only if it says so, and --learn-conversations only as Nemotron; null: `o` may open `F`. 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 if (o.vision != null and !(@hasDecl(F, "Options") and @hasField(F.Options, "vision"))) return "--vision: this CUDA family reads no images; serve it without --vision"; diff --git a/zig/src/native/cuda_streams.zig b/zig/src/native/cuda_streams.zig index 303354eb1a2..ef733adfaed 100644 --- a/zig/src/native/cuda_streams.zig +++ b/zig/src/native/cuda_streams.zig @@ -29,7 +29,7 @@ pub const Budget = struct { }; /// The streams served, the page plan and layout or the KV ledger plan, and TF_KV_SHARE's count when states take slots. -pub const Count = struct { streams: u32, paged: ?kv_pages.Plan, layout: ?kv_pool.Layout, ledger: ?ledger.Plan = null, slots: ?usize = null, planned: ?kv_pool.Budget = null }; +pub const Count = struct { streams: u32, paged: ?kv_pages.Plan, layout: ?kv_pool.Layout, ledger: ?ledger.Plan = null, slots: ?usize = null, planned: ?kv_pool.Budget = null, extra_device: u64 = 0 }; pub const CacheRoom = struct { room: u64, streams: u64 }; @@ -39,7 +39,7 @@ pub fn cacheRoom(room: u64, stream_bytes: u64, free: u32, counted: Count) CacheR .room = room -| p.cost.each.scratch, .streams = p.one_full *| (counted.streams -| p.standing.streams), }; - return .{ .room = room, .streams = stream_bytes *| (counted.streams -| free) }; + return .{ .room = room -| counted.extra_device, .streams = stream_bytes *| (counted.streams -| free) }; } /// TF_KV_SHARE: the cache's part made pool pages, all of it unless the family keeps its states' rest elsewhere (GLM). @@ -65,9 +65,16 @@ pub fn count(comptime F: type, a: Allocator, loaded: anytype, o: api.Open, b: Bu const wrapped = kv_pages.wrapped(F, loaded, free, b.stream_bytes, b.room); if (wrapped.layout) |l| { const slots = try shareSlots(b.share, l.snap_bytes, b.host_cache); // GLM: a slot a state - const paged = try kv_pages.plan(F, a, l, wrapped.room, o, @intCast(b.window), problem, b.host_cache, kv_pages.enginePaged(loaded), keptPpm(F, b.share), slots) orelse return null; + const host = if (comptime @hasDecl(F, "kvHostRoom")) F.kvHostRoom(loaded.ctx) catch |err| { + problem.* = if (comptime @hasDecl(F, "explain")) F.explain(null, err) orelse @errorName(err) else @errorName(err); + return null; + } else 0; + const paged = if (host > 0) + try @import("cuda_kv_host.zig").plan(a, l, wrapped.room, o, host, problem) orelse return null + else + try kv_pages.plan(F, a, l, wrapped.room, o, @intCast(b.window), problem, b.host_cache, kv_pages.enginePaged(loaded), keptPpm(F, b.share), slots) orelse return null; const planned = kv_pages.budgetOf(F, l, wrapped.room, o, @intCast(b.window), b.host_cache, kv_pages.enginePaged(loaded), keptPpm(F, b.share), slots); - return .{ .streams = paged.lanes, .paged = paged, .layout = l, .slots = slots, .planned = if (slots != null) planned else null }; + return .{ .streams = paged.lanes, .paged = paged, .layout = l, .slots = slots, .planned = if (slots != null) planned else null, .extra_device = if (host > 0) try @import("cuda_kv_host.zig").deviceBytes(l) else 0 }; } // --parallel caps the streams; each request reserves its own bytes (a family that allocates per request) if (ledger.wanted(F, loaded, b.stream_bytes)) { diff --git a/zig/src/native/draft_sources_hip_test.zig b/zig/src/native/draft_sources_hip_test.zig index 475b23d0c5a..f9b1e123be4 100644 --- a/zig/src/native/draft_sources_hip_test.zig +++ b/zig/src/native/draft_sources_hip_test.zig @@ -24,6 +24,7 @@ test "draft sources: HIP Nemotron checkpoint head and explicit zero" { var b: n.lanes.Hip = undefined; b.e = &e; b.costs = .{}; + e.window = 4; e.plan.rows = 16; e.plan.slots = 4; e.o.policy.mtp.drafts = 3; diff --git a/zig/src/native/draft_sources_metal_test.zig b/zig/src/native/draft_sources_metal_test.zig index 4359c02c9f8..39aa72709b0 100644 --- a/zig/src/native/draft_sources_metal_test.zig +++ b/zig/src/native/draft_sources_metal_test.zig @@ -114,6 +114,7 @@ test "draft sources: Metal GLM and GLM DSA follow actual MTP weights" { var weights: @typeInfo(@TypeOf(e.w)).pointer.child = undefined; e.w = &weights; e.ep = null; + e.dflash = null; e.device = .{ .id = no_arch }; var slots: tf.glm.slots.Slots = undefined; var b: tf.glm.backend.Backend = .{ .gpa = std.testing.allocator, .sl = &slots }; @@ -125,6 +126,9 @@ test "draft sources: Metal GLM and GLM DSA follow actual MTP weights" { try check(facts, null, true, false); e.w.mtp = @as(@TypeOf(e.w.mtp.?), undefined); try check(b.facts(), null, true, true); + e.dflash = present(@TypeOf(e.dflash.?)); // the DFlash2 drafter's own facts branch + try check(b.facts(), .{ .kind = "DFlash2", .name = "example/draft" }, true, false); + e.dflash = null; var d: tf.glm_dsa.engine.Engine = undefined; var db: tf.glm_dsa.backend.Backend = undefined; db.e = &d; diff --git a/zig/src/native/flashnext_cancel.zig b/zig/src/native/flashnext_cancel.zig new file mode 100644 index 00000000000..b1ff321f02f --- /dev/null +++ b/zig/src/native/flashnext_cancel.zig @@ -0,0 +1,43 @@ +//! The single-reply host offers only landed prompt state to the same cancellation hook as lane backends. +const std = @import("std"); +const lanes = @import("tensorfold").lanes; +const Mark = *const fn (*anyopaque, usize) void; + +const Bridge = struct { + ptr: *anyopaque, + mark: Mark, + fn kept(ptr: *anyopaque, _: *lanes.Stream, at: u32) void { + const b: *Bridge = @ptrCast(@alignCast(ptr)); + b.mark(b.ptr, at); + } +}; + +pub fn keep(gpa: std.mem.Allocator, prefilling: bool, at: u32, cached: u32, prompt_len: usize, ptr: *anyopaque, mark: Mark) void { + if (!prefilling) return; + var bridge: Bridge = .{ .ptr = ptr, .mark = mark }; + var stream = lanes.Stream.init(gpa, .{ .id = "cancelled-prompt", .prompt = &.{}, .max_new = 0, .reuse = .{ .hook = .{ .ptr = &bridge, .at = Bridge.kept } } }) catch return; + defer stream.deinit(gpa); + stream.cached = cached; + stream.prompt_len = prompt_len; + stream.keepInterruptedPrefill(at); +} + +test "Flash Next cancellation: only a newly landed prompt prefix reaches the existing keep callback" { + const Heard = struct { + at: ?usize = null, + fn mark(ptr: *anyopaque, at: usize) void { + const h: *@This() = @ptrCast(@alignCast(ptr)); + h.at = at; + } + }; + const Case = struct { prefilling: bool = true, at: u32, cached: u32 = 0, want: ?usize = null }; + for ([_]Case{ + .{ .at = 0 }, .{ .at = 4, .want = 4 }, .{ .at = 8, .want = 8 }, + .{ .at = 4, .cached = 4 }, .{ .at = 10 }, .{ .at = 11 }, + .{ .prefilling = false, .at = 4 }, .{ .prefilling = false, .at = 11 }, + }) |case| { + var heard: Heard = .{}; + keep(std.testing.allocator, case.prefilling, case.at, case.cached, 10, &heard, Heard.mark); + try std.testing.expectEqual(case.want, heard.at); + } +} diff --git a/zig/src/native/flashnext_disk.zig b/zig/src/native/flashnext_disk.zig index b2ce19010f4..6b85fb1784a 100644 --- a/zig/src/native/flashnext_disk.zig +++ b/zig/src/native/flashnext_disk.zig @@ -18,7 +18,7 @@ pub fn ask(comptime H: type) *const fn (*anyopaque, *api.ImprintAsk) bool { const h: *H = @ptrCast(@alignCast(ctx)); h.lock(); defer h.unlock(); - if (h.closing or !h.disk.push(h.gpa, a)) return false; + if (h.closing 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; } @@ -29,19 +29,28 @@ pub fn ask(comptime H: type) *const fn (*anyopaque, *api.ImprintAsk) bool { pub fn idleStep(h: anytype) bool { h.lock(); const asks = h.disk.take(h.gpa); + var flushes = h.disk.takeFlushes(); // between requests: none is in flight const store = if (h.cache) |*c| c else null; const write = if (store) |c| c.disk != null and rows.write.ready(c.disk.?) and h.queued.items.len == 0 and !h.closing and h.disk.quiet(h.served, h.now()) else false; h.unlock(); defer h.gpa.free(asks); + defer flushes.deinit(h.gpa); for (asks) |a| a.answer(store, .{ .starts = false, .spans = false }); // its lookups pass neither + for (flushes.items) |a| a.answer(store, .{}); + if (flushes.items.len > 0) if (store) |s| { // a reply's end publishes these; with none to come, the flush does + h.lock(); + h.cache_status = api.prompt_cache.status.PromptCache(s); + h.disk_status = api.prompt_cache.status.Disk(s); + h.unlock(); + }; if (write) _ = rows.write.step(store.?.disk.?); - return write or asks.len > 0; + return write or asks.len > 0 or flushes.items.len > 0; } /// Whether the idle loop has work: asks, or kept states waiting for disk (under the lock). pub fn idleWork(h: anytype) bool { - const store = if (h.cache) |*c| c else return h.disk.asks.items.len > 0; - return h.disk.asks.items.len > 0 or (store.disk != null and rows.write.ready(store.disk.?)); + const store = if (h.cache) |*c| c else return h.disk.waiting(); + return h.disk.waiting() or (store.disk != null and rows.write.ready(store.disk.?)); } /// The store's view of a kept state: the n-gram history at it (16 bytes), then its buffer as snapshot.zig lays it out. diff --git a/zig/src/native/flashnext_host.zig b/zig/src/native/flashnext_host.zig index ac34edad27e..1b26eab4379 100644 --- a/zig/src/native/flashnext_host.zig +++ b/zig/src/native/flashnext_host.zig @@ -220,7 +220,7 @@ pub const Host = struct { fn run(h: *Host) void { while (true) { h.lock(); - if (h.queued.items.len == 0 and !h.closing) { + if ((h.queued.items.len == 0 or h.disk.holding()) and !h.closing) { // a flush goes before the next request const ms_: i64 = if (disk.idleWork(h)) 10 else 100; // writes waiting for the quiet look again soon if (ms_ == 100 or !h.disk.quiet(h.served, h.now())) h.wake.waitTimeout(h.io, &h.mutex, .{ .duration = .{ .raw = .fromMilliseconds(ms_), .clock = .awake } }) catch {}; h.unlock(); @@ -410,6 +410,7 @@ pub const Host = struct { fin.message = @errorName(e); return; }; + if (res.reason == .cancelled and h.eng.r.tp == null) @import("flashnext_cancel.zig").keep(h.gpa, job.prefilled == null, @intCast(h.eng.m.pos), job.cached, r.prompt.len, &c, Ctx.marked); if (!job.prefill_sent) emit(job, .{ .prefilled = 0 }); fin.reason = switch (res.reason) { .stop => .stop, diff --git a/zig/src/native/gemma4.zig b/zig/src/native/gemma4.zig index 88472fd18de..3dddc3e820e 100644 --- a/zig/src/native/gemma4.zig +++ b/zig/src/native/gemma4.zig @@ -171,7 +171,8 @@ const Snaps = struct { /// Prompt reuse in what 70% of RAM leaves beside the streams' caches (16 GiB by default), at planned chunk starts. fn enableCache(h: *Host, a: std.mem.Allocator, o: api.Open, served: u32, window: usize, problem: *[]const u8) !void { - const later = @as(u64, @max(served, 2)) * g.state.cacheBytes(h.model.config.geo, window); + // the default stays the size it had while the linears' shard bytes were resident: no default cell gets slower + const later = reserved(@as(u64, @max(served, 2)) * g.state.cacheBytes(h.model.config.geo, window), h.model.released(), o.prompt_cache_gib); const room = h.model.device.maxWorkingSet() -| h.model.device.allocated() -| (8 << 30) -| later; var why: []const u8 = ""; const plan = cache_fit.budgetBeside(o.prompt_cache_gib, o.prompt_cache_over_cap, room, later, a, &why, "") catch |err| switch (err) { @@ -190,6 +191,25 @@ fn enableCache(h: *Host, a: std.mem.Allocator, o: api.Open, served: u32, window: h.host.info_.prompt_cache_plan = plan; } +/// Memory the budget counts beside the load: the streams' caches, and for the default the bytes this load released. +fn reserved(streams: u64, released: u64, gib: ?f64) u64 { + return streams + if (gib == null) released else 0; +} + +test "the default prompt-cache budget counts the released bytes as still held; an explicit budget is unchanged" { + const GiB: u64 = 1 << 30; + const cap: u64 = 36 * GiB / 100 * cache_fit.SHARE_PERCENT; // a 36 GB Mac + const streams = 2 * GiB + GiB / 2; + const released = 11 * GiB + GiB / 3; // the 12B 4-bit's shard span and row copies + const now = 7 * GiB + GiB / 2; // the footprint once loaded, without them + const before = try cache_fit.fitUnderDefault(cap, now + released + streams, null, false, null); + const after = try cache_fit.fitUnderDefault(cap, now + reserved(streams, released, null), null, false, null); + try std.testing.expectEqual(before.budget, after.budget); + try std.testing.expect(after.budget < (try cache_fit.fitUnderDefault(cap, now + streams, null, false, null)).budget); + try std.testing.expectEqual(streams, reserved(streams, released, 4)); + try std.testing.expectEqual(streams, reserved(streams, released, 0)); +} + /// Info.vision's prepare (on the HTTP thread); the template writes <|image|> alone: the server adds boi and eoi. fn prepareImage(ctx: *anyopaque, a: std.mem.Allocator, bytes: []const u8, max_tokens: u32) anyerror!api.PreparedImage { const h: *Host = @ptrCast(@alignCast(ctx)); diff --git a/zig/src/native/glm_host.zig b/zig/src/native/glm_host.zig index b48c273e4cb..c9fdffb2d6c 100644 --- a/zig/src/native/glm_host.zig +++ b/zig/src/native/glm_host.zig @@ -47,8 +47,8 @@ fn words(_: ?*anyopaque, err: anyerror) ?[]const u8 { /// Streams fitting beside the weights under the load limit, at most `want` (`fixed`: all or none); pooled: KDA only. fn fit(eng: *const ge.Engine, want: u32, fixed: bool) !u32 { - const per = glm.state.stateBytes(&eng.c, if (glm.pool.on(eng)) 0 else eng.s.cap, true) + 64 * 1024; - const used = eng.w.bytes + eng.arena.bytes + glm.vision.heldBytes(eng.vision); + const per = glm.state.stateBytes(&eng.c, if (glm.pool.on(eng)) 0 else eng.s.cap, true) + 64 * 1024 + glm.metal_dflash_load.streamBytes(eng); + const used = eng.w.bytes + eng.arena.bytes + glm.vision.heldBytes(eng.vision) + glm.metal_dflash_load.heldBytes(eng); const limit = eng.limit.bytes; const room: u64 = if (limit > used) (limit - used) / per else 0; const n: u32 = @intCast(@min(@as(u64, @max(want, 1)), 1 + room)); @@ -65,7 +65,7 @@ const cache_rules: api.prompt_cache.Rules = .{ .lookahead = 1, .planned = true, /// Kept prompt states' room: --prompt-cache-gib, else 16 GiB, inside what the load limit read at load leaves. fn cacheBudget(eng: *const ge.Engine, gib: ?f64) u64 { const want: u64 = @intFromFloat((gib orelse 16) * (1 << 30)); - const used = eng.w.bytes + eng.arena.bytes + glm.vision.heldBytes(eng.vision); + const used = eng.w.bytes + eng.arena.bytes + glm.vision.heldBytes(eng.vision) + glm.metal_dflash_load.heldBytes(eng); const limit = eng.limit.bytes; return if (limit > used) @min(want, limit - used) else 0; } @@ -84,11 +84,12 @@ fn learnedStates(gpa: Allocator, io: std.Io, dir: []const u8, eng: *const ge.Eng } /// A GLM-5.3-Flash checkpoint served: `window` tokens of cache a stream, warmed first (the pair: `speed_up`). -pub fn open(gpa: Allocator, io: std.Io, dir: []const u8, window: u32, speed_up: ?[]const u8, streams: u32, fixed: bool, cache_gib: ?f64, decode_share: ?f64, learn: ?Learn, vision: ?api.VisionOpen) !*Host { +pub fn open(gpa: Allocator, io: std.Io, dir: []const u8, window: u32, speed_up: ?[]const u8, streams: u32, fixed: bool, cache_gib: ?f64, decode_share: ?f64, learn: ?Learn, vision: ?api.VisionOpen, drafter: ?[]const u8, drafter_name: ?[]const u8, drafter_bits: u8) !*Host { // a prompt's tower rows and images: the images' budget, and every video's frame groups beside it const limits: ?glm.vision.Limits = if (vision) |v| .{ .image_tokens = v.image_tokens + v.video_tokens, .max_images = v.max_images + v.max_videos * ((v.max_frames + 1) / 2) } else null; const eng = try ge.Engine.loadWith(gpa, io, dir, window + 64, speed_up, learn != null, limits, true); errdefer eng.deinit(); + if (drafter) |d| try glm.metal_dflash_load.load(gpa, io, eng, d, drafter_bits); // freed with the engine var toks: [96]u32 = undefined; for (&toks, 0..) |*t, i| t.* = @intCast(1000 + i); var dummy: u8 = 0; @@ -102,10 +103,24 @@ pub fn open(gpa: Allocator, io: std.Io, dir: []const u8, window: u32, speed_up: h.slots = try glm.slots.Slots.init(gpa, eng, try fit(eng, streams, fixed)); errdefer h.slots.deinit(gpa); glm.residency.wire(eng, io); + try glm.metal_dflash_load.joinResidency(gpa, eng); const n: u32 = @intCast(h.slots.slots.len); h.back = .{ .gpa = gpa, .sl = &h.slots }; errdefer h.back.deinit(); + if (eng.dflash) |d| { + const r = try glm.metal_dflash_rounds.Rounds.init(gpa, &h.slots, d.model, d.taps); + h.back.rounds = r; + if (eng.residency) |*res| r.follow = res.follow(); + r.prepare(); // every slot's context made now, so it joins the target residency set + if (eng.residency) |*res| _ = res.tryAddNow(&.{}); + if (eng.ep == null) { + const x = try glm.metal_dflash_inline.Inline.init(gpa, r, eng.device); + r.inline_pass = x; + h.slots.follow = x.hook(); + } + } if (eng.ep != null) h.back.costs = try glm.timing.measure(&h.slots, gpa, io); // both Macs in step, as the warm-up + if (h.back.rounds) |r| try r.priceHead(h.back.headFacts()); // the MTP head's rounds beside DFlash2 cost main's h.cfg = try lanes.Config.init(gpa, h.back.facts(), glm.state.max_rows, glm.state.max_rows - 1); errdefer h.cfg.deinit(gpa); h.wall = .{ .io = io }; @@ -124,7 +139,7 @@ pub fn open(gpa: Allocator, io: std.Io, dir: []const u8, window: u32, speed_up: } } // sampled draws on one Mac (the pair refuses them per request) - h.host = api.LaneHost.init(gpa, io, &h.core, .{ .benchmark_ranks = if (eng.ep != null) 2 else 1, .benchmark_group = if (eng.ep) |p| p.benchmark_group else null, .name = "glm-zig", .lanes = n, .context_window = serves, .prefill_step = eng.chunk_rows, .decode_share = decode_share, .greedy_only = eng.ep != null, .admit = if (h.slots.pool != null) .{ .ctx = &h.back, .fits = glm.backend.Backend.fits } else null, .vision = offer }); + h.host = api.LaneHost.init(gpa, io, &h.core, .{ .benchmark_ranks = if (eng.ep != null) 2 else 1, .benchmark_group = if (eng.ep) |p| p.benchmark_group else null, .name = "glm-zig", .lanes = n, .context_window = serves, .prefill_step = eng.chunk_rows, .decode_share = decode_share, .greedy_only = eng.ep != null, .draft_sources = .{ .drafter = if (drafter) |d| .{ .kind = "DFlash2", .name = drafter_name orelse d } else null }, .admit = if (h.slots.pool != null) .{ .ctx = &h.back, .fits = glm.backend.Backend.fits } else null, .vision = offer }); h.host.memory = .{ .ctx = h, .read = readMemory }; h.cache = null; const budget = cacheBudget(eng, cache_gib); diff --git a/zig/src/native/hip.zig b/zig/src/native/hip.zig index eed8a2d8eec..47d58449a2f 100644 --- a/zig/src/native/hip.zig +++ b/zig/src/native/hip.zig @@ -59,7 +59,7 @@ fn matrixRefused(comptime F: type, policy: hip.Policy, caps: hip.Caps) ?[]const } /// The tensor-parallel flags as the Python ROCm server checks them, and the flags this engine cannot take. -fn checkGroup(a: Allocator, o: api.Open, problem: *[]const u8) Refused!void { +pub fn checkGroup(comptime F: type, a: Allocator, o: api.Open, problem: *[]const u8) Refused!void { if (o.drafter != null) return refuse(a, problem, "--drafter: the HIP engine runs no DFlash2 drafter yet; serve without --drafter", .{}); if (o.tp != 1 and o.tp != 2 and o.tp != 4 and o.tp != 8) return refuse(a, problem, "--tp {d} is not a supported ROCm world size; choose 1, 2, 4 or 8", .{o.tp}); if (o.tp > 1 and o.master.len == 0) return refuse(a, problem, "--tp > 1 needs --master: rank 0's address on the link between the machines", .{}); @@ -68,7 +68,7 @@ fn checkGroup(a: Allocator, o: api.Open, problem: *[]const u8) Refused!void { if (o.tp == 1 and o.rank != 0) return refuse(a, problem, "--rank must be 0 when --tp 1", .{}); if (o.rank >= o.tp) return refuse(a, problem, "--rank {d} not in [0, --tp {d})", .{ o.rank, o.tp }); if (o.keep) |n| if (n < 0) return refuse(a, problem, "--checkpoint-slots must be 0 or more", .{}); - if (o.mtp_drafts) |n| if (n > 3) return refuse(a, problem, "--mtp-drafts {d}: the HIP engine drafts at most 3", .{n}); + if (o.mtp_drafts) |n| if (n > fam.mtpMost(F, o.tp)) return refuse(a, problem, "--mtp-drafts {d}: the HIP engine drafts at most {d}{s}", .{ n, fam.mtpMost(F, o.tp), if (fam.mtpMost(F, o.tp) < fam.mtpMost(F, 1)) " with --tp above 1" else "" }); if (o.mtp_confidence) |c| if (c < 0 or c > 1) return refuse(a, problem, "--mtp-confidence must be from 0 to 1", .{}); if (o.prompt_cache_gib) |g| if (g < 0) return refuse(a, problem, "--prompt-cache-gib must be 0 or more", .{}); } @@ -99,7 +99,7 @@ fn cacheRefused(o: api.Open) ?[]const u8 { /// Resolves the policy on rank 0 (defaults, flags, old variables, TF_POLICY), joins the group, sends it to the others. fn ready(comptime F: type, a: Allocator, gpa: Allocator, io: std.Io, o: api.Open, problem: *[]const u8) (Refused || Allocator.Error)!Ready { - try checkGroup(a, o, problem); + try checkGroup(F, a, o, problem); if (cacheRefused(o)) |why| return refuse(a, problem, "{s}", .{why}); const native = modelContext(a, io, o.dir); const window = admission.contextWindow(o.context, native, F.default_context) catch |err| return switch (err) { @@ -499,48 +499,42 @@ test "the group flags: one rank source, a supported world, a master past one ran const a = arena.allocator(); var problem: []const u8 = ""; const base: api.Open = .{ .dir = "d", .model_type = "qwen3_5" }; - try checkGroup(a, base, &problem); + try checkGroup(qwen35.native, a, base, &problem); var two = base; two.tp = 2; two.master = "node0"; - try checkGroup(a, two, &problem); + try checkGroup(qwen35.native, a, two, &problem); var speed = base; speed.speed_up = "settings.json"; - try std.testing.expectError(error.Refused, checkGroup(a, speed, &problem)); + try std.testing.expectError(error.Refused, checkGroup(qwen35.native, a, speed, &problem)); try std.testing.expect(std.mem.indexOf(u8, problem, "--speed-up") != null); speed.tp = 2; speed.master = "node0"; - try std.testing.expectError(error.Refused, checkGroup(a, speed, &problem)); + try std.testing.expectError(error.Refused, checkGroup(qwen35.native, a, speed, &problem)); var three = two; three.tp = 3; - try std.testing.expectError(error.Refused, checkGroup(a, three, &problem)); + try std.testing.expectError(error.Refused, checkGroup(qwen35.native, a, three, &problem)); var lone = two; lone.master = ""; - try std.testing.expectError(error.Refused, checkGroup(a, lone, &problem)); + try std.testing.expectError(error.Refused, checkGroup(qwen35.native, a, lone, &problem)); var outside = two; outside.rank = 2; - try std.testing.expectError(error.Refused, checkGroup(a, outside, &problem)); + try std.testing.expectError(error.Refused, checkGroup(qwen35.native, a, outside, &problem)); } -test "--drafter, and --mtp-drafts past three, are refused before any load, on every rank" { +test "--drafter is refused before any load, on every rank, until the HIP engine runs DFlash2" { var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); defer arena.deinit(); const a = arena.allocator(); var problem: []const u8 = ""; const drafted: api.Open = .{ .dir = "d", .model_type = "qwen3_5", .drafter = "/models/drafter" }; - try std.testing.expectError(error.Refused, checkGroup(a, drafted, &problem)); + try std.testing.expectError(error.Refused, checkGroup(qwen35.native, a, drafted, &problem)); try std.testing.expectStringStartsWith(problem, "--drafter: the HIP engine runs no DFlash2 drafter yet"); var follower = drafted; follower.tp = 2; follower.rank = 1; follower.master = "node0"; - try std.testing.expectError(error.Refused, checkGroup(a, follower, &problem)); - // three drafts and fewer are not refused - var o: api.Open = .{ .dir = "d", .model_type = "qwen4_exp", .mtp_drafts = 3 }; - try checkGroup(a, o, &problem); - o.mtp_drafts = 4; - try std.testing.expectError(error.Refused, checkGroup(a, o, &problem)); - try std.testing.expectEqualStrings("--mtp-drafts 4: the HIP engine drafts at most 3", problem); + try std.testing.expectError(error.Refused, checkGroup(qwen35.native, a, follower, &problem)); } test "--kv-cache fp8 is refused by name on HIP; bf16 caches are not" { @@ -567,6 +561,7 @@ test "matrix=on runs only where the matrix-core tiles exist; auto runs everywher test { _ = @import("draft_sources_hip_test.zig"); + _ = @import("mtp_drafts_hip_test.zig"); _ = @import("hip_confidence_test.zig"); } diff --git a/zig/src/native/hip_families.zig b/zig/src/native/hip_families.zig index 578661dc06f..30ae7b42e9b 100644 --- a/zig/src/native/hip_families.zig +++ b/zig/src/native/hip_families.zig @@ -50,6 +50,11 @@ pub fn confidenceFloor(comptime F: type, o: api.Open, rdna3_5_alone: bool, fallb return if (rdna3_5_alone) F.mtp_confidence_rdna3_5 else fallback; } +/// Most `--mtp-drafts` the family's head takes at `tp` ranks: its `mtp_max_drafts` on one rank, else three. +pub fn mtpMost(comptime F: type, tp: u32) u32 { + return if (@hasDecl(F, "mtp_max_drafts") and tp == 1) F.mtp_max_drafts else 3; +} + /// The family's offer, or the empty one (text, the host's defaults) when its Loaded carries none. pub fn offerOf(loaded: anytype) Offer { return if (comptime @hasField(@TypeOf(loaded), "offer")) loaded.offer else .{}; @@ -119,3 +124,13 @@ test "a Loaded without an offer gives the empty one; --vision with no offered im try std.testing.expect(textOnly(seen, empty)); try std.testing.expect(!textOnly(.{ .dir = "d", .model_type = "plain" }, empty)); } + +test "a family takes three MTP drafts unless it declares `mtp_max_drafts`, and three past one rank" { + const Deep = struct { + pub const mtp_max_drafts: u32 = 7; + }; + try std.testing.expectEqual(@as(u32, 3), mtpMost(Plain, 1)); + try std.testing.expectEqual(@as(u32, 7), mtpMost(Deep, 1)); + try std.testing.expectEqual(@as(u32, 3), mtpMost(Deep, 2)); + try std.testing.expectEqual(@as(u32, 3), mtpMost(Plain, 2)); +} diff --git a/zig/src/native/metal.zig b/zig/src/native/metal.zig index cedd5bbdef7..5d737b03ed5 100644 --- a/zig/src/native/metal.zig +++ b/zig/src/native/metal.zig @@ -25,13 +25,11 @@ pub const deviceName = metal_shared.deviceName; const prefillStep = metal_shared.prefillStep; const modelContext = metal_shared.modelContext; const gibBytes = metal_shared.gibBytes; - pub const backends: []const []const u8 = &.{"metal"}; /// `tensorfold device`: the share of RAM the load limit grants (cache_fit's ceiling). pub const load_share_percent: u64 = cache_fit.SHARE_PERCENT; pub const serves: []const []const u8 = &.{ "--checkpoint-slots", "--spill-gib", "--mtp-drafts" }; const spill = @import("metal_spill.zig"); - /// Every checkpoint-wide MLX affine width the per-module readers take (oQ quants): 2-8 bits but 7, groups 32-128. const affine_widths = blk: { var out: [18][]const u8 = undefined; @@ -41,7 +39,6 @@ const affine_widths = blk: { const done = out; break :blk &done; }; - /// Gemma 4's: MLX affine 2-6 or 8 bits in groups of 64, uniform or per module (oQ packs). const gemma4_widths: []const []const u8 = &.{ "mlx-q2g64", "mlx-q3g64", "mlx-q4g64", "mlx-q5g64", "mlx-q6g64", "mlx-q8g64" }; @@ -308,7 +305,7 @@ fn refusal(a: Allocator, o: api.Open, dense: bool) !?[]const u8 { if (o.kv8) return "--kv-cache fp8 keeps fp8 caches on CUDA; the Metal engines keep bf16: serve without it"; if (o.prompt_int8) return prompt_int8_refusal; if (!learners.supports(t)) if (try o.slideRefusal(a, "Macs")) |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")) return "--drafter is supported for Qwen3.8-27B-class checkpoints (qwen3_5 with its own output head), Qwen3.5-MoE (qwen3_5_moe), 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")) 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)"; 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, "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; @@ -438,7 +435,6 @@ test { /// GLM-5.3-Flash's caches hold this many tokens unless --context asks otherwise (its window is 1,048,576). const glm_window: i64 = 131072; - fn openGlm(a: Allocator, gpa: Allocator, io: std.Io, o: api.Open, problem: *[]const u8) !?api.Opened { const native = modelContext(a, io, o.dir); const window: i64 = o.context orelse @min(glm_window, if (native > 0) native else glm_window); @@ -452,8 +448,13 @@ fn openGlm(a: Allocator, gpa: Allocator, io: std.Io, o: api.Open, problem: *[]co problem.* = try std.fmt.allocPrint(a, "--vision is served on one Mac; the --speed-up pair reads text only", .{}); return null; } + const drafter = if (o.drafts) o.drafter else null; + if (drafter != null) if (tf.glm.metal_dflash_load.refusal(.{ .speed_up = o.speed_up != null, .drafter_bits = o.drafter_bits })) |why| { + problem.* = why; + return null; + }; const learn: ?glm.Learn = if (o.learn) |root| .{ .root = root, .cap = gibBytes(o.learn_gib), .floor = gibBytes(o.learn_min_free_gib), .daily = gibBytes(o.learn_daily_gib), .conversations = o.learn_conversations, .spill = o.spill, .slots = spill.slots(o) } else null; - const h = glm.open(gpa, io, o.dir, @intCast(window), o.speed_up, o.lanes, o.lanes_fixed, o.prompt_cache_gib, o.decode_share, learn, o.vision) catch |e| { + const h = glm.open(gpa, io, o.dir, @intCast(window), o.speed_up, o.lanes, o.lanes_fixed, o.prompt_cache_gib, o.decode_share, learn, o.vision, drafter, o.drafter_name orelse drafter, o.drafter_bits) catch |e| { if (e == error.BadResidency) problem.* = mtl.residency_policy.invalid_flag else if (e == error.LearnConversationsOnPair) problem.* = "--learn-conversations keeps states on one Mac only: serve GLM-5.3-Flash without --speed-up, or without the flag" else if (e == error.BadLoadLimit) problem.* = "GLM_LOAD_LIMIT_GB is not a load limit: give a number of GB above 0, or unset it for 70% of RAM" else problem.* = if (linkProblem(e)) |link| try std.fmt.allocPrint(a, "the native GLM-5.3-Flash engine cannot load {s}: {s}", .{ o.dir, link }) else try std.fmt.allocPrint(a, "the native GLM-5.3-Flash engine cannot load {s} ({s})", .{ o.dir, @errorName(e) }); return null; }; diff --git a/zig/src/native/mtp_drafts_hip_test.zig b/zig/src/native/mtp_drafts_hip_test.zig new file mode 100644 index 00000000000..8ac86a5913b --- /dev/null +++ b/zig/src/native/mtp_drafts_hip_test.zig @@ -0,0 +1,28 @@ +//! The `--mtp-drafts` refusal by family and world size, before any load. +const std = @import("std"); +const api = @import("engine_api"); +const qwen35 = @import("qwen3_5"); +const flashnext = @import("flashnext"); +const nemotron = @import("nemotron"); +const hip = @import("hip.zig"); + +test "--mtp-drafts: Flash Next takes seven and Nemotron fifteen at --tp 1, three above it, others three; past that refused by name" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var problem: []const u8 = ""; + inline for (.{ + .{ flashnext.native, "qwen4_exp", 7, 1, "" }, + .{ nemotron.native, "nemotron_h", 15, 1, "" }, + .{ qwen35.native, "qwen3_5", 3, 1, "" }, + .{ flashnext.native, "qwen4_exp", 3, 2, " with --tp above 1" }, + .{ nemotron.native, "nemotron_h", 3, 2, " with --tp above 1" }, + .{ qwen35.native, "qwen3_5", 3, 2, "" }, + }) |c| { + var o: api.Open = .{ .dir = "d", .model_type = c[1], .mtp_drafts = c[2], .tp = c[3], .master = if (c[3] > 1) "node0" else "" }; + try hip.checkGroup(c[0], a, o, &problem); + o.mtp_drafts = c[2] + 1; + try std.testing.expectError(error.Refused, hip.checkGroup(c[0], a, o, &problem)); + try std.testing.expectEqualStrings(try std.fmt.allocPrint(a, "--mtp-drafts {d}: the HIP engine drafts at most {d}{s}", .{ c[2] + 1, c[2], c[4] }), problem); + } +} diff --git a/zig/src/native/qwen27_drafts.zig b/zig/src/native/qwen27_drafts.zig index 9e4c839e8a5..0bdac7546b1 100644 --- a/zig/src/native/qwen27_drafts.zig +++ b/zig/src/native/qwen27_drafts.zig @@ -11,6 +11,23 @@ const Metal = lb.Metal; const Tree = q.dflash.selector.Tree; const Proposal = q.dflash.runtime_model.Model.Proposal; +/// The target draw's keyed Gumbel noise for a token at a position (lanes.sampling.sample), finite for the selector. +pub const Draw = struct { + seed: u64, + pub fn noise(d: *Draw) q.dflash.selector.Noise { + return .{ .ptr = d, .draw = draw }; + } + fn draw(ptr: *anyopaque, position: u64, token: u32) anyerror!f64 { + const d: *const Draw = @ptrCast(@alignCast(ptr)); + return -@log(-@log(@min(lanes.sampling.uniform(d.seed, position, token), 1.0 - 0x1p-53))); + } +}; + +/// A shared round reads each node's chance from its tree's scores, so only a lone stream's tree takes the noise. +pub fn followsDraw(lone: bool, s: *const lanes.Stream) bool { + return lone and s.sampling != null; +} + /// Only slots that currently draft compete for rows in the next shared allocation. fn live(b: *const Metal) usize { var n: usize = 0; @@ -32,6 +49,7 @@ pub fn draftFn(ptr: *anyopaque, requests: []const be.DraftRequest) anyerror!void @import("qwen27_slots.zig").promoteDue(b); // a stream moves into a freed slot 0 before it drafts var batch: [8]Proposal = undefined; var owners: [8]u32 = undefined; + var draws: [8]Draw = undefined; var n: usize = 0; const lone = live(b) == 1; var costs: [lb.max_rows]f64 = undefined; @@ -63,6 +81,13 @@ pub fn draftFn(ptr: *anyopaque, requests: []const be.DraftRequest) anyerror!void continue; }; batch[n] = .{ .context = if (slot == 0) null else b.contexts[slot].?, .pending = pending, .nodes = nodes, .costs = if (lone) costs[0..b.window] else &.{}, .overhead_ms = if (lone) @max(0, r.stream.tree_over orelse r.stream.round_over orelse 0) else 0, .defer_price = lone }; + // a lone sampled stream's tree ranks its candidates as the target's keyed race will draw them + if (r.position == stands + 1 and followsDraw(lone, r.stream)) { + const x = r.stream.sampling.?; + draws[n] = .{ .seed = x.seed }; + batch[n].noise = draws[n].noise(); + batch[n].temperature = x.temperature; + } owners[n] = slot; n += 1; if (n == batch.len) { diff --git a/zig/src/native/qwen27_shared_policy_test.zig b/zig/src/native/qwen27_shared_policy_test.zig index df70640ff88..a63c37596f4 100644 --- a/zig/src/native/qwen27_shared_policy_test.zig +++ b/zig/src/native/qwen27_shared_policy_test.zig @@ -122,3 +122,14 @@ test "qwen27 grants: lone landing history cannot reprice shared proposals or the try std.testing.expect(out[0] < root / 50); } } + +test "qwen27 grants: a shared round's sampled proposals keep the drafter's scores free of the draw's noise" { + var s = try lanes.Stream.init(a, .{ .id = "sampled", .prompt = &.{1}, .max_new = 64 }); + defer s.deinit(a); + const follows = @import("qwen27_drafts.zig").followsDraw; + try std.testing.expect(!follows(true, &s)); + try std.testing.expect(!follows(false, &s)); + s.sampling = .{ .seed = 7 }; + try std.testing.expect(follows(true, &s)); + try std.testing.expect(!follows(false, &s)); +} diff --git a/zig/src/native/qwen27_slots.zig b/zig/src/native/qwen27_slots.zig index e1865ac9496..f7bc94341b9 100644 --- a/zig/src/native/qwen27_slots.zig +++ b/zig/src/native/qwen27_slots.zig @@ -170,11 +170,18 @@ pub fn chunk(b: *Metal, s: *lanes.Stream, f: *Fill, _: u32) !bool { pub fn bind(b: *Metal, s: *lanes.Stream) !u32 { const slot = b.slotOf(s) orelse (free(b) orelse return error.NoFreeSlot); try ready(b, slot, s); + if (b.owners[slot] != s) try b.runner.promise(slot, promiseRows(b, s)); b.dropTreeOf(slot); b.owners[slot] = s; return slot; } +/// Rows a paged slot promises `s` as it opens: its prompt and one widest pass; its reply's are promised as they come. +fn promiseRows(b: *const Metal, s: *const lanes.Stream) u32 { + const rows = @as(u64, s.prompt().len) + b.runner.model.frame.capacity; + return @intCast(@min(rows, b.runner.capacity)); +} + /// One chunk of `s`'s prompt pass a call (the lane host's prefill_step), the others' rounds kept first. pub fn prefillStep(ptr: *anyopaque, s: *lanes.Stream, _: u32) anyerror!bool { const b: *Metal = @ptrCast(@alignCast(ptr)); @@ -185,7 +192,7 @@ pub fn prefillStep(ptr: *anyopaque, s: *lanes.Stream, _: u32) anyerror!bool { defer pool.pop(); if (!b.fills.contains(s)) { const slot = try bind(b, s); - errdefer b.owners[slot] = null; + errdefer drop(b, slot); const f = try opening(b, s, slot); errdefer closing(b, s); try b.fills.put(b.gpa, s, f); @@ -195,7 +202,7 @@ pub fn prefillStep(ptr: *anyopaque, s: *lanes.Stream, _: u32) anyerror!bool { const done = chunk(b, s, f, 0) catch |err| { if (err == error.Cancelled and slot == 0) leave(b, s); endFill(b, s); - b.owners[slot] = null; + drop(b, slot); return err; }; if (done) endFill(b, s); @@ -208,6 +215,12 @@ pub fn cancelPrefill(ptr: *anyopaque, s: *lanes.Stream) anyerror!void { if (b.fills.get(s)) |f| s.keepInterruptedPrefill(@intCast(f.at)); } +/// 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.runner.release(slot, slot == 0 and b.standing.tokens.len > 0); + b.owners[slot] = null; +} + /// A stepped pass is over, or its stream left mid-pass. pub fn endFill(b: *Metal, s: *lanes.Stream) void { if (b.fills.remove(s)) closing(b, s); @@ -423,6 +436,7 @@ pub fn unbind(b: *Metal, s: *lanes.Stream) void { b.dropTreeOf(slot); if (b.release_hook) |hook| if (!b.runner.failed and s.finished and s.reason != .cancelled and s.reason != .@"error") hook.kept(hook.ctx, s, slot); if (slot == 0) leave(b, s); + b.runner.release(slot, slot == 0 and b.standing.tokens.len > 0); // a standing slot 0 keeps its rows for a resume b.owners[slot] = null; b.runner.rope[slot] = .{}; if (slot == 0) b.promote_due = b.draft != null; // the next backend call moves a stream in, after this reply is out @@ -457,6 +471,8 @@ pub fn promote(b: *Metal) void { }; b.owners[0] = s; b.owners[k] = null; + b.runner.release(from, false); // slot 0 holds its rows now, and the stream's promise with them + b.runner.promise(0, promiseRows(b, s)) catch {}; // the pages slot `from` gave back hold it b.runner.rope[0] = b.runner.rope[k]; b.runner.rope[k] = .{}; clearContext(b, from) catch {}; @@ -495,6 +511,7 @@ pub fn lone(b: *Metal, s: *lanes.Stream, hooks: api.LoneHooks) !bool { b.owners[0] = s; var handed = false; defer if (!handed) unbind(b, s); + try b.runner.promise(0, promiseRows(b, s)); const pool = mtl.objc.Pool.push(); defer pool.pop(); try d.generation.settle(); diff --git a/zig/src/native/xpu_flashnext.zig b/zig/src/native/xpu_flashnext.zig index 45f91df3a07..43752fe4eb2 100644 --- a/zig/src/native/xpu_flashnext.zig +++ b/zig/src/native/xpu_flashnext.zig @@ -14,13 +14,32 @@ const Spec = struct { pub const model_type = "qwen4_exp"; pub const name = "flashnext-xpu"; pub const Engine = fn_xpu.Engine; - pub const cache_rules: api.prompt_cache.Rules = .{ .planned = true, .grid = 64 }; + pub const chunk_invariant = true; + pub const cache_rules: api.prompt_cache.Rules = .{ .lookahead = 1, .planned = false, .chunk = 1, .chunk_starts = false }; - pub fn promptRows(_: *const Engine) u32 { - return 64; + pub fn promptRows(e: *const Engine) u32 { + return e.busy_rows; + } + + pub fn soloRows(e: *const Engine) u32 { + return e.solo_rows; } }; +pub fn parseChunkOpts(chunk_raw: ?[]const u8, solo_raw: ?[]const u8) !struct { busy: u32, solo: u32 } { + const max_c = fn_xpu.ld.max_chunk_rows; + const busy: usize = if (chunk_raw) |s| blk: { + const n = std.fmt.parseInt(usize, s, 10) catch return error.BadChunk; + if (n == 0 or n > max_c) return error.BadChunk; + break :blk n; + } else fn_xpu.ld.chunk_rows; + const solo: usize = if (solo_raw) |s| + lanes.solo_chunk.parse(s, .{ .busy = busy, .most = max_c }) catch return error.BadChunkSolo + else + @max(busy, fn_xpu.ld.default_solo_rows); + return .{ .busy = @intCast(busy), .solo = @intCast(solo) }; +} + var stopping = std.atomic.Value(bool).init(false); var prev_int: std.posix.Sigaction = undefined; var prev_term: std.posix.Sigaction = undefined; @@ -95,11 +114,29 @@ pub fn open(a: Allocator, gpa: Allocator, io: std.Io, o: api.Open, problem: *[]c } const mtp_env = try settings.read(?bool, "XPU_MTP", null); const want_mtp = if (mtp_env == false) false else o.drafts; + const chunk_busy: u32 = try settings.read(u32, "XPU_CHUNK", @intCast(fn_xpu.ld.chunk_rows)); + const solo_default: u32 = @max(chunk_busy, @as(u32, @intCast(fn_xpu.ld.default_solo_rows))); + const chunk_solo: u32 = try settings.read(u32, "XPU_CHUNK_SOLO", solo_default); + if (chunk_solo < chunk_busy or chunk_solo > fn_xpu.ld.max_chunk_rows) { + problem.* = try std.fmt.allocPrint( + a, + "invalid XPU_CHUNK_SOLO: expected a whole row count from {d} to {d}", + .{ chunk_busy, fn_xpu.ld.max_chunk_rows }, + ); + return null; + } + const chunks = .{ .busy = chunk_busy, .solo = chunk_solo }; + const mtp_depth: u32 = try settings.read(u32, "XPU_MTP_DEPTH", 6); + const mtp_conf: f64 = try settings.read(f64, "XPU_MTP_CONF", -0.4); const engine = fn_xpu.Engine.init(gpa, io, o.dir, .{ .context = @intCast(window), .tp = tp, .mtp = want_mtp, + .busy_rows = chunks.busy, + .solo_rows = chunks.solo, + .mtp_drafts = mtp_depth, + .mtp_conf = mtp_conf, }) catch |err| { problem.* = try std.fmt.allocPrint(a, "the XPU engine could not load Qwen3.8 Flash Next from {s} at tp={d}: {s}", .{ o.dir, tp, @errorName(err) }); return null; @@ -167,7 +204,6 @@ pub fn open(a: Allocator, gpa: Allocator, io: std.Io, o: api.Open, problem: *[]c .context_window = @intCast(window), .context_fitted = true, .startup = h.startup, - .prefill_step = if (drafted) Spec.promptRows(engine) else 0, }); const left_after_streams = mem_free -| (@as(u64, extra) * per_seq); diff --git a/zig/src/native/xpu_lane.zig b/zig/src/native/xpu_lane.zig index c051e2836bd..31ab281e9aa 100644 --- a/zig/src/native/xpu_lane.zig +++ b/zig/src/native/xpu_lane.zig @@ -47,8 +47,20 @@ pub fn Xpu(comptime S: type) type { const Self = @This(); /// The family's engine has drafted rounds (Nemotron: verifyRows, keepRows, draftKept, draftFirst). const has_head = @hasDecl(S.Engine, "verifyRows"); + const has_probs = @hasDecl(S.Engine, "draftFirstProbs"); + const has_solo = @hasDecl(S, "soloRows"); /// A stream's sequence, its held drafts, its last window's unkept rows and where that window started. - const Lane = struct { seq: *Seq, held: [max_rows]u32 = undefined, held_n: usize = 0, pending: ?u32 = null, start: u32 = 0 }; + pub const Lane = struct { + seq: *Seq, + held: [max_rows]u32 = undefined, + probs: [max_rows]f64 = @splat(0), + held_n: usize = 0, + pending: ?u32 = null, + start: u32 = 0, + filled: ?usize = null, + first_handle: u64 = 0, + }; + const P = if (has_head) @import("xpu_lane_prompt.zig").Prompt(Self, S) else void; const Seq = if (has_head) S.Engine.Sequence else void; gpa: std.mem.Allocator, e: *S.Engine, @@ -102,17 +114,26 @@ pub fn Xpu(comptime S: type) type { } pub fn backend(self: *Self) be.Backend { - return .{ .ptr = self, .vtable = &.{ - .prefill = prefillFn, - .first = firstFn, - .queue = queueFn, - .read = readFn, - .verify = verifyFn, - .keep = keepFn, - .draft = draftFn, - .release = releaseFn, - .score = if (@hasDecl(S.Engine, "score")) scoreFn else null, - } }; + return .{ + .ptr = self, + .chunk_invariant = @hasDecl(S, "chunk_invariant") and S.chunk_invariant, + .vtable = &.{ + .prefill = prefillFn, + .prefill_step = if (has_head) prefillStepFn else null, + .cancel_prefill = if (has_head) cancelPrefillFn else null, + .reports_fill = has_head, + .first = firstFn, + .queue = queueFn, + .read = readFn, + .verify = verifyFn, + .keep = keepFn, + .draft = draftFn, + .tree = if (has_probs) treeFn else null, + .probabilities = if (has_probs) probabilitiesFn else null, + .release = releaseFn, + .score = if (@hasDecl(S.Engine, "score")) scoreFn else null, + }, + }; } /// What the round loop reads at setup: one stream; with a head, drafted windows of up to 16 rows. @@ -126,7 +147,9 @@ pub fn Xpu(comptime S: type) type { .speculate = true, .speculate_early = false, .plain_guard = true, // a round drafts only when its depth beats the decode step on the measured costs - .drafts = max_rows - 1, + .drafts = if (@hasDecl(S.Engine, "maxDrafts")) S.Engine.maxDrafts(self.e) else max_rows - 1, + .draft_probabilities = has_probs, + .plain_streams = if (has_probs) 16 else 0, .window_costs = self.costs[0..max_rows], .mtp_step_ms = self.mtp_ms, .hidden_rows = self.streams > 1, // a round's windows of several streams, one after another @@ -143,7 +166,7 @@ pub fn Xpu(comptime S: type) type { } /// The window's rows drawn: greedy on the device, else each row's logits drawn at its keyed position. - fn drawRows(self: *Self, base: usize, rows: usize, sampling: ?lanes.Sampling, positions: []const u64, out: []u32) !void { + pub fn drawRows(self: *Self, base: usize, rows: usize, sampling: ?lanes.Sampling, positions: []const u64, out: []u32) !void { if (comptime !has_head) unreachable; const greedy = if (sampling) |s| s.temperature <= 0 else true; if (greedy) { @@ -194,11 +217,11 @@ pub fn Xpu(comptime S: type) type { return @ptrCast(@alignCast(ptr)); } - fn stopped(self: *const Self) bool { + pub fn stopped(self: *const Self) bool { return if (self.halt) |h| h.load(.acquire) else false; } - fn take(self: *Self, token: u32) u64 { + pub fn take(self: *Self, token: u32) u64 { const h = self.next; self.drawn[h % ring] = token; self.next += 1; @@ -242,27 +265,14 @@ pub fn Xpu(comptime S: type) type { const ids = s.prompt(); if (ids.len == 0 or ids.len + s.max_new + 1 > e.max_len) return error.PromptTooLong; if (comptime has_head) if (self.drafting()) { - // the stream's sequence (the engine's own while free), then the prompt in prompt windows - const gop = try self.lane_of.getOrPut(self.gpa, s); - if (gop.found_existing) self.dropSeq(gop.value_ptr.seq); - const own = self.own_free; - gop.value_ptr.* = .{ .seq = if (own) &e.own else e.newSeq() catch |err| { - self.lane_of.removeByPtr(gop.key_ptr); - return err; - } }; - if (own) self.own_free = false; - e.bind(gop.value_ptr.seq); - try self.prefillPlanned(s, ids); - if (s.isCancelled()) return error.Cancelled; - var first: [1]u32 = undefined; - try self.drawRows(0, 1, s.sampling, &.{ids.len}, &first); - _ = self.take(first[0]); + const l = try P.open(self, s, ids); + while (!try P.step(self, s, l, 0)) {} return; }; try e.reset(); const head = ids[0 .. ids.len - 1]; if (head.len > 16) { - const window = S.promptRows(e); + const window = if (comptime has_solo) S.soloRows(e) else S.promptRows(e); var t: usize = 0; while (t < head.len) : (t += window) { if (s.isCancelled()) return error.Cancelled; @@ -277,37 +287,24 @@ pub fn Xpu(comptime S: type) type { _ = self.take(try self.step(ids[ids.len - 1], s.sampling, ids.len)); } - /// A bound sequence's prompt pass: from a kept state if the cache has one, planned chunks, the cache's marks. - fn prefillPlanned(self: *Self, s: *lanes.Stream, ids: []const u32) !void { + fn prefillStepFn(ptr: *anyopaque, s: *lanes.Stream, max_rows_cap: u32) anyerror!bool { if (comptime !has_head) unreachable; - const e = self.e; - const rows = S.promptRows(e); - s.cached = 0; - var at: u32 = 0; - if (s.reuse.saved) |saved| { - const snap: *S.Engine.Snapshot = @ptrCast(@alignCast(saved)); - if (snap.at < ids.len) { - try e.snapRestore(snap); - at = snap.at; - s.cached = at; - } else s.reuse_failed = true; + const self = of(ptr); + if (!self.drafting()) { + try prefillFn(ptr, s); + return true; } - if (at == 0) try e.reset(); - var next: usize = 0; - while (at < ids.len) { - if (s.isCancelled()) return error.Cancelled; - if (self.stopped()) return error.ShuttingDown; - while (next < s.chunks.len and s.chunks[next] <= at) next += 1; - const end: u32 = if (next < s.chunks.len) s.chunks[next] else @intCast(ids.len); - var n = @min(end - at, rows); - if (comptime @hasDecl(S.Engine, "copy_only")) for (s.reuse.marks) |m| if (m > at and m < at + n) { - n = m - at; // an unplanned family cuts where the cache keeps a state - break; - }; - try e.prefillSpan(ids, at, at + n, rows); - at += n; - if (std.mem.indexOfScalar(u32, s.reuse.marks, at) != null) if (s.reuse.hook) |k| k.at(k.ptr, s, at); + if (self.started) |f| { + self.started = null; + f(); } + const ids = s.prompt(); + const l = if (self.lane_of.getPtr(s)) |x| (if (x.filled != null) x else try P.open(self, s, ids)) else try P.open(self, s, ids); + return P.step(self, s, l, max_rows_cap); + } + + fn cancelPrefillFn(ptr: *anyopaque, s: *lanes.Stream) anyerror!void { + if (comptime has_head) P.cancel(of(ptr), s); } // -- the prompt cache's Snapshots: a stream's sequence at a prompt chunk end --------------------------------- @@ -344,6 +341,11 @@ pub fn Xpu(comptime S: type) type { fn firstFn(ptr: *anyopaque, s: *lanes.Stream, position: u64) anyerror!u64 { const self = of(ptr); if (position != s.prompt_len) return error.PositionMismatch; + if (comptime has_head) if (self.drafting()) { + const l = self.lane_of.getPtr(s) orelse return error.UnknownStream; + if (l.filled != null) return error.PositionMismatch; + return l.first_handle; + }; return self.next - 1; } @@ -479,18 +481,44 @@ pub fn Xpu(comptime S: type) type { const depth = @min(r.depth, max_rows - 1); if (r.rows) |path| { for (path, 0..) |row, i| if (row != i) return error.TreesNotBuilt; - l.held_n = try self.e.draftKept(r.follow[0..path.len], l.start, depth, &l.held); + l.held_n = if (comptime has_probs) + try self.e.draftKeptProbs(r.follow[0..path.len], l.start, depth, &l.held, &l.probs) + else + try self.e.draftKept(r.follow[0..path.len], l.start, depth, &l.held); } else { const first = r.first orelse return error.NoFirstToken; const t = switch (first) { .handle => |h| self.drawn[h % ring], .value => |v| v, }; - l.held_n = try self.e.draftFirst(t, depth, &l.held); + l.held_n = if (comptime has_probs) + try self.e.draftFirstProbs(t, depth, &l.held, &l.probs) + else + try self.e.draftFirst(t, depth, &l.held); } } } + fn treeFn(ptr: *anyopaque, s: *lanes.Stream, gpa: std.mem.Allocator) anyerror!?lanes.stream.Held { + if (comptime !(has_head and has_probs)) unreachable; + const self = of(ptr); + const l = self.lane_of.getPtr(s) orelse return error.UnknownStream; + return .{ .count = @intCast(l.held_n), .tokens = try gpa.dupe(u32, l.held[0..l.held_n]) }; + } + + fn probabilitiesFn(ptr: *anyopaque, s: *lanes.Stream, out: []f64) anyerror!bool { + if (comptime !(has_head and has_probs)) unreachable; + const self = of(ptr); + const l = self.lane_of.getPtr(s) orelse return error.UnknownStream; + if (out.len > l.held_n) return false; + var chance: f64 = 1.0; + for (out, l.probs[0..out.len]) |*o, p| { + chance *= p; + o.* = chance; + } + return true; + } + fn releaseFn(ptr: *anyopaque, s: *lanes.Stream) void { const self = of(ptr); self.e.sync() catch {}; @@ -498,7 +526,7 @@ pub fn Xpu(comptime S: type) type { } /// A stream's sequence back: the engine's own is free again, another is freed. - fn dropSeq(self: *Self, seq: *Seq) void { + pub fn dropSeq(self: *Self, seq: *Seq) void { if (comptime !has_head) return; if (seq == &self.e.own) self.own_free = true else self.e.freeSeq(seq); } diff --git a/zig/src/native/xpu_lane_prompt.zig b/zig/src/native/xpu_lane_prompt.zig new file mode 100644 index 00000000000..5c485cce032 --- /dev/null +++ b/zig/src/native/xpu_lane_prompt.zig @@ -0,0 +1,79 @@ +//! Stepped and solo-chunked prompt fill for `native/xpu_lane.zig` sequence backends. +const std = @import("std"); +const lanes = @import("lanes"); + +pub fn Prompt(comptime Self: type, comptime S: type) type { + return struct { + const has_solo = @hasDecl(S, "soloRows"); + + pub fn open(self: *Self, s: *lanes.Stream, ids: []const u32) !*Self.Lane { + const e = self.e; + if (ids.len == 0 or ids.len + s.max_new + 1 > e.max_len) return error.PromptTooLong; + const gop = try self.lane_of.getOrPut(self.gpa, s); + if (gop.found_existing) self.dropSeq(gop.value_ptr.seq); + const own = self.own_free; + gop.value_ptr.* = .{ .seq = if (own) &e.own else e.newSeq() catch |err| { + self.lane_of.removeByPtr(gop.key_ptr); + return err; + } }; + if (own) self.own_free = false; + const l = gop.value_ptr; + e.bind(l.seq); + s.cached = 0; + var at: usize = 0; + if (s.reuse.saved) |saved| { + const snap: *S.Engine.Snapshot = @ptrCast(@alignCast(saved)); + if (snap.at < ids.len) { + try e.snapRestore(snap); + at = snap.at; + s.cached = snap.at; + } else s.reuse_failed = true; + } + if (at == 0) try e.reset(); + l.filled = at; + s.fill_at.store(@intCast(at), .release); + return l; + } + + pub fn step(self: *Self, s: *lanes.Stream, l: *Self.Lane, max_rows_cap: u32) !bool { + const ids = s.prompt(); + const at = l.filled orelse return true; + if (s.isCancelled()) { + s.keepInterruptedPrefill(@intCast(at)); + return error.Cancelled; + } + if (self.stopped()) return error.ShuttingDown; + const e = self.e; + e.bind(l.seq); + const busy: usize = S.promptRows(e); + const solo: usize = if (comptime has_solo) S.soloRows(e) else busy; + var rows = lanes.solo_chunk.passRows(&self.lane_of, s, "filled", solo, busy); + if (max_rows_cap > 0) rows = @min(rows, max_rows_cap); + var stop = @min(ids.len, at + @max(rows, 1)); + for (s.chunks) |c| if (c > at and c < stop) { + stop = c; + break; + }; + for (s.reuse.marks) |m| if (m > at and m < stop) { + stop = m; + break; + }; + try e.prefillSpan(ids, at, stop, @intCast(stop - at)); + s.fill_at.store(@intCast(stop), .release); + const last = stop == ids.len; + l.filled = if (last) null else stop; + if (std.mem.indexOfScalar(u32, s.reuse.marks, @intCast(stop)) != null) if (s.reuse.hook) |k| k.at(k.ptr, s, @intCast(stop)); + if (last) { + if (s.isCancelled()) return error.Cancelled; + var first: [1]u32 = undefined; + try self.drawRows(0, 1, s.sampling, &.{ids.len}, &first); + l.first_handle = self.take(first[0]); + } + return last; + } + + pub fn cancel(self: *Self, s: *lanes.Stream) void { + if (self.lane_of.getPtr(s)) |l| if (l.filled) |at| s.keepInterruptedPrefill(@intCast(at)); + } + }; +} diff --git a/zig/src/native/xpu_tp_refusal_test.zig b/zig/src/native/xpu_tp_refusal_test.zig index a3203430f3d..1359708da72 100644 --- a/zig/src/native/xpu_tp_refusal_test.zig +++ b/zig/src/native/xpu_tp_refusal_test.zig @@ -20,6 +20,19 @@ test "draft sources: XPU refuses --vision and unsupported --tp before device acc } } } + if (@import("xpu_engine_options").qwen27) { + const fn_nat = @import("xpu_flashnext.zig"); + const d = try fn_nat.parseChunkOpts(null, null); + try std.testing.expectEqual(@as(u32, 64), d.busy); + try std.testing.expectEqual(@as(u32, 2048), d.solo); + const hi = try fn_nat.parseChunkOpts("128", "1024"); + try std.testing.expectEqual(@as(u32, 128), hi.busy); + try std.testing.expectEqual(@as(u32, 1024), hi.solo); + try std.testing.expectError(error.BadChunk, fn_nat.parseChunkOpts("0", null)); + try std.testing.expectError(error.BadChunk, fn_nat.parseChunkOpts("2049", null)); + try std.testing.expectError(error.BadChunkSolo, fn_nat.parseChunkOpts("128", "64")); + try std.testing.expectError(error.BadChunkSolo, fn_nat.parseChunkOpts(null, "4096")); + } const env = @import("sys").environment; try std.testing.expectError(error.InvalidEnvironment, env.parse("XPU_TP", "3")); try std.testing.expectEqual(@as(?u64, 4), try env.parse("XPU_TP", "4")); diff --git a/zig/src/platform/environment.zig b/zig/src/platform/environment.zig index b88cbd6c0e8..c36b2f54a25 100644 --- a/zig/src/platform/environment.zig +++ b/zig/src/platform/environment.zig @@ -4,10 +4,9 @@ const sys = @import("sys.zig"); pub const Error = error{InvalidEnvironment}; pub const Scope = enum { common, cuda, metal, xpu, slide, hooks, dsv41, gemma4, drama3, glm, flashnext, nemotron, minimax_m3, chat, hub }; -pub const Kind = enum { u32, u64, size, percent, positive, device, segments, mib, bit_width, word, prompt, flag, toggle, real, positive_real, signed_real, range, path }; +pub const Kind = enum { u32, u64, size, percent, positive, device, segments, mib, bit_width, word, prompt, flag, toggle, real, positive_real, signed_real, range, path, parallel }; /// The release from which the server refuses the rank aliases: the one after the release that first ships the flags. pub const alias_retire = "1.4.0"; - pub const Rule = struct { name: [:0]const u8, scope: Scope, @@ -39,6 +38,7 @@ pub fn isReal(kind: Kind) bool { } 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_STARTUP_RECEIPT", .scope = .common, .kind = .flag, .forms = "0 or 1 (opt-in startup and first completion receipts)" }, @@ -46,6 +46,7 @@ pub const rules = [_]Rule{ .{ .name = "TENSORFOLD_DEVICE_CHECK", .scope = .common, .kind = .flag, .forms = "0 or 1 (0 skips serve's device-profile check; default 1)" }, .{ .name = "TENSORFOLD_VIDEO_TOKENS", .scope = .common, .kind = .u64, .forms = "a nonnegative whole video-token budget (default 16384; unsigned 64-bit count)" }, .{ .name = "TENSORFOLD_MAX_PDF_PAGES", .scope = .common, .kind = .positive, .forms = "a whole number from 1 to 4294967295 (capped by --vision-max-images)" }, + .{ .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_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)" }, @@ -62,6 +63,7 @@ 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_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)" }, @@ -113,6 +115,8 @@ pub const rules = [_]Rule{ .{ .name = "XPU_MTP", .scope = .xpu, .kind = .flag, .forms = "0 or 1 (0 disables MTP drafting; default 1)" }, .{ .name = "XPU_MTP_DEPTH", .scope = .xpu, .kind = .u32, .min = 1, .max = 15, .forms = "a whole draft depth from 1 to 15 (default 6)" }, .{ .name = "XPU_MTP_CONF", .scope = .xpu, .kind = .signed_real, .forms = "a finite cumulative log-probability cut (default -0.4)" }, + .{ .name = "XPU_CHUNK", .scope = .xpu, .kind = .u32, .min = 1, .max = 2048, .forms = "a whole busy prompt row count from 1 to 2048 (default 64)" }, + .{ .name = "XPU_CHUNK_SOLO", .scope = .xpu, .kind = .u32, .min = 1, .max = 2048, .forms = "a whole solo prompt row count from busy to 2048 (default 2048)" }, .{ .name = "XPU_VERIFY_TEST", .scope = .xpu, .kind = .flag, .forms = "0 or 1 (1 runs stand-in verify checks)" }, .{ .name = "XPU_FLASHNEXT_WARM", .scope = .xpu, .kind = .flag, .forms = "0 or 1 (0 skips host PLE warmup; 1 forces it)" }, .{ .name = "XPU_DEVICE_ID", .scope = .xpu, .kind = .positive, .base = 0, .forms = "a nonzero PCI device id in decimal or 0x hex" }, @@ -137,8 +141,9 @@ pub const rules = [_]Rule{ .{ .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_DSEL", .scope = .glm, .kind = .flag, .forms = "0 or 1" }, + .{ .name = "TF_GLM_DSCORES", .scope = .glm, .kind = .flag, .forms = "0 or 1" }, .{ .name = "TF_GLM_DFLASH2_LOG", .scope = .glm, .kind = .u64, .forms = "a whole unsigned 64-bit round count (0 logs no drafts)" }, - .{ .name = "TF_GLM_DRAFT_CONFIDENCE", .scope = .glm, .kind = .real, .max = 1, .forms = "a finite chain-chance cut from 0 to 1 (default 0.7)" }, + .{ .name = "TF_GLM_DRAFT_CONFIDENCE", .scope = .glm, .kind = .real, .max = 1, .forms = "a finite chain-chance cut from 0 to 1 (default 0.7 on CUDA, 0.5 on Metal)" }, // 2^31 - 32: GLM's slots, the window and its 32 verify rows (glm/cuda_native.zig's capacity), keep i32 positions .{ .name = "TF_GLM_CONTEXT_CEILING", .scope = .glm, .kind = .u64, .first_digit = true, .min = 1, .max = 2147483616, .forms = "a whole token count from 1 to 2147483616 (the window GLM-5.3-Flash may serve in place of config.json's)" }, .{ .name = "TF_GLM_EXPERT_FORM", .scope = .glm, .kind = .word, .words = &.{ "classic", "factored" }, .forms = "classic or factored at every width (unset races the two at each width when a build first loads)" }, @@ -179,6 +184,7 @@ pub const rules = [_]Rule{ .{ .name = "TF_DSV41_R1", .scope = .dsv41, .kind = .flag, .trim = " ", .forms = "0 or 1" }, .{ .name = "TF_DSV41_PREFETCH_AHEAD", .scope = .dsv41, .kind = .flag, .trim = " ", .forms = "0 or 1" }, .{ .name = "TF_DSV41_KV_NORM_STORE", .scope = .dsv41, .kind = .flag, .trim = " ", .forms = "0 or 1" }, + .{ .name = "TF_DSV41_FLOAT_LINEAR", .scope = .dsv41, .kind = .flag, .trim = " ", .forms = "0 or 1" }, .{ .name = "TF_DSV41_ROUTER_GROUP_ROT", .scope = .dsv41, .kind = .flag, .trim = " ", .forms = "0 or 1" }, .{ .name = "TF_DSV41_SCHEMA_PROMPT", .scope = .dsv41, .kind = .flag, .trim = " \t\r\n", .forms = "0 or 1" }, .{ .name = "TF_DSV41_TOOL_GRAMMAR", .scope = .dsv41, .kind = .flag, .trim = " ", .alias_of = "TENSORFOLD_TOOL_GRAMMAR", .forms = "0 or 1 (ignored while TENSORFOLD_TOOL_GRAMMAR is set)" }, @@ -263,6 +269,7 @@ pub const rules = [_]Rule{ .{ .name = "HF_TOKEN", .scope = .hub, .kind = .path, .trim = " \t\n\r\x0b\x0c", .forms = "a Hugging Face token without control characters (pull only)" }, .{ .name = "HUGGING_FACE_HUB_TOKEN", .scope = .hub, .kind = .path, .trim = " \t\n\r\x0b\x0c", .forms = "a Hugging Face token without control characters (pull only)" }, .{ .name = "HF_TOKEN_PATH", .scope = .hub, .kind = .path, .forms = "a path without control characters to the Hugging Face token file (pull only)" }, + .{ .name = "TF_FLASHNEXT_DRAFT_HEAD", .scope = .flashnext, .kind = .word, .words = &.{ "bf16", "affine4" }, .forms = "bf16 or affine4 (unset or blank keeps affine4, a bf16 language head's draft rows as 4-bit groups of 32; bf16 keeps the rows as stored)" }, // Family rank and prompt settings below are read through their own family's startup scope. .{ .name = "TF_GLM_INDEX_CUDA", .scope = .glm, .kind = .word, .words = &.{ "1", "0", "scores" }, .forms = "1 (both kernels), 0 (neither) or scores (scores only; unset or blank is both)" }, .{ .name = "TF_GLM_KV_HOST_GIB", .scope = .glm, .kind = .real, .forms = "a finite GiB amount of at least 0 (unset or blank uses one full window and 16 rows a page)" }, @@ -300,6 +307,13 @@ pub fn parse(name: []const u8, raw: ?[]const u8) Error!?u64 { for (r.words, 0..) |v, i| if (std.mem.eql(u8, text, v)) return i; return error.InvalidEnvironment; } + // "auto" travels as 0: the caller reads it back through `parallel`, never the raw number + if (r.kind == .parallel) { + if (std.ascii.eqlIgnoreCase(text, "auto")) return 0; + const n = std.fmt.parseInt(u64, text, 10) catch return error.InvalidEnvironment; + if (n < r.min or n > r.max) return error.InvalidEnvironment; + return n; + } if (r.kind == .toggle) return toggle(r, text) orelse error.InvalidEnvironment; // a path travels as 0, its text read by `path`; the file itself is its reader's to check if (r.kind == .path) return if (for (text) |ch| { @@ -433,6 +447,14 @@ pub fn device(flag: ?u32, raw: ?[]const u8) Error!u32 { return @intCast((try checked("TF_CUDA_DEVICE", raw)) orelse 0); } +/// TENSORFOLD_PARALLEL's text: the flag wins, else the trimmed setting, else null; bad values are refused by name. +pub fn parallel(flag: ?[]const u8, raw: ?[]const u8) Error!?[]const u8 { + if (flag) |f| return f; + _ = try checked("TENSORFOLD_PARALLEL", raw); + const text = std.mem.trim(u8, raw orelse return null, rule("TENSORFOLD_PARALLEL").trim); + return if (text.len == 0) null else text; +} + pub const Flags = struct { cuda: bool = false, metal: bool = false, @@ -451,6 +473,8 @@ pub const Flags = struct { device: ?u32 = null, segments: ?u32 = null, carveout: bool = false, + /// --parallel named: TENSORFOLD_PARALLEL then stays out of the way, as a flag-named device does. + parallel_named: bool = false, fn includes(f: Flags, scope: Scope) bool { return switch (scope) { @@ -479,6 +503,7 @@ pub fn refusal(a: std.mem.Allocator, environment: anytype, flags: Flags) !?[]con if (!flags.includes(r.scope) or masked(r, environment)) continue; if (std.mem.eql(u8, r.name, "TF_CUDA_DEVICE") and flags.device != null) continue; if (std.mem.eql(u8, r.name, "TF_CUDA_SEGMENTS") and flags.segments != null) continue; + if (std.mem.eql(u8, r.name, "TENSORFOLD_PARALLEL") and flags.parallel_named) continue; if (std.mem.eql(u8, r.name, "TF_CUDA_CARVEOUT") and flags.carveout) continue; if (std.mem.eql(u8, r.name, "TF_CUDA_CARVEOUT_MIB") and !flags.carveout and !std.mem.eql(u8, environment.get("TF_CUDA_CARVEOUT") orelse "0", "1")) continue; diff --git a/zig/src/platform/environment_flashnext_test.zig b/zig/src/platform/environment_flashnext_test.zig index 6553fb344b8..bf2f77352f7 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 34 settings: 23 switches, 9 integers, 1 real, 1 structured" { +test "Flash Next strict env: the table holds all 35 settings: 23 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{ 23, 9, 1, 1 }, counts); + try t.expectEqual([4]usize{ 23, 9, 1, 2 }, counts); } test "Flash Next strict env: unset and blank settings both read as the caller's default" { @@ -130,6 +130,16 @@ test "Flash Next strict env: the prompt word keeps rows as a present index and r try t.expect((try e.value(?u64, name, null, null)) == null); } +test "Flash Next strict env: the draft head keeps bf16 and affine4 in the reader's order and refuses other text" { + const name = "TF_FLASHNEXT_DRAFT_HEAD"; + try check(name, "bf16", true); + try check(name, "affine4", true); + // the words' order is the reader's: bf16 is 0 and affine4 is 1, its default + try t.expectEqual(@as(u1, 0), try e.value(u1, name, "bf16", 1)); + try t.expectEqual(@as(u1, 1), try e.value(u1, name, "affine4", 0)); + for ([_][]const u8{ "BF16", "affine", "fp8", "1", "affine4 " }) |raw| try check(name, raw, false); +} + test "Flash Next strict env: the late keep reads unset and blank as null, and 0 and 1 as false and true" { const name = "TF_FLASHNEXT_KEEP_LATE"; for ([_]?[]const u8{ null, "", " ", "\t", " \t\r\n" }) |raw| diff --git a/zig/src/platform/environment_test.zig b/zig/src/platform/environment_test.zig index 353ae012e9c..9a6c27202ab 100644 --- a/zig/src/platform/environment_test.zig +++ b/zig/src/platform/environment_test.zig @@ -36,6 +36,7 @@ test "environment: every strict reader refuses bad text before opening a model, const Case = struct { name: []const u8, raw: []const u8, n: u64 }; const valid = [_]Case{ + .{ .name = "TF_QWEN_KV_HOST_GIB", .raw = "8", .n = 8 }, .{ .name = "TF_CACHE_EVICT", .raw = "main", .n = 0 }, .{ .name = "TF_CACHE_EVICT", .raw = "decayed_resume", .n = 1 }, .{ .name = "TF_FLASHNEXT_BATCH_DRAWS", .raw = "0", .n = 0 }, @@ -97,6 +98,7 @@ 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_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 }, .{ .name = "TF_PROMPT_INTERMEDIATE", .raw = "0", .n = 0 }, @@ -154,6 +156,8 @@ const valid = [_]Case{ .{ .name = "XPU_MTP", .raw = "1", .n = 1 }, .{ .name = "XPU_MTP_DEPTH", .raw = "6", .n = 6 }, .{ .name = "XPU_MTP_CONF", .raw = "-0.4", .n = @bitCast(@as(f64, -0.4)) }, + .{ .name = "XPU_CHUNK", .raw = "64", .n = 64 }, + .{ .name = "XPU_CHUNK_SOLO", .raw = "2048", .n = 2048 }, .{ .name = "XPU_VERIFY_TEST", .raw = "0", .n = 0 }, .{ .name = "XPU_VERIFY_TEST", .raw = "1", .n = 1 }, .{ .name = "XPU_FLASHNEXT_WARM", .raw = "0", .n = 0 }, @@ -194,6 +198,11 @@ const valid = [_]Case{ .{ .name = "TF_MINIMAX_WORLD", .raw = "2", .n = 2 }, .{ .name = "TF_HY4_ENGRAM", .raw = "gpu", .n = 2 }, .{ .name = "TF_HY4_DRAFT_BITS", .raw = "8", .n = 8 }, + .{ .name = "TENSORFOLD_PARALLEL", .raw = "4", .n = 4 }, + .{ .name = "TENSORFOLD_PARALLEL", .raw = " 8\t", .n = 8 }, + .{ .name = "TENSORFOLD_PARALLEL", .raw = "4096", .n = 4096 }, + .{ .name = "TENSORFOLD_PARALLEL", .raw = "auto", .n = 0 }, + .{ .name = "TENSORFOLD_PARALLEL", .raw = "AUTO", .n = 0 }, }; test "environment: valid forms remain raw numbers before existing consumer clamps and defaults" { @@ -230,6 +239,8 @@ test "environment: range, enum, whitespace and native prompt geometry refusals a .{ "XPU_A8_BITS", "16" }, .{ "XPU_TP", "0" }, .{ "XPU_TP", "3" }, .{ "XPU_TP", " 4" }, .{ "XPU_CTX", "0" }, .{ "XPU_CTX", "262145" }, + .{ "XPU_CHUNK", "0" }, .{ "XPU_CHUNK", "2049" }, + .{ "XPU_CHUNK_SOLO", "0" }, .{ "XPU_CHUNK_SOLO", "2049" }, .{ "XPU_MTP_DEPTH", "0" }, .{ "XPU_MTP_DEPTH", "16" }, .{ "XPU_DEVICE_ID", "0" }, .{ "XPU_DEVICE_ID", "0xzz" }, .{ "TF_SLIDE_POCKET_KEY", "AUTO" }, .{ "TF_DRAMA_PREFILL_ROWS", "4096x" }, @@ -448,3 +459,27 @@ test "rank aliases name their flag and refuse from their retirement release" { try t.expect(e.retired("TF_GLM_PROF", "9.9.9") == null); try t.expect(e.retired("TF_NOT_A_ROW", "9.9.9") == null); } + +test "environment: TENSORFOLD_PARALLEL takes the flag over the setting, blank keeps the default, garbage is refused" { + try t.expectEqualStrings("4", (try e.parallel("4", "8")).?); + try t.expectEqualStrings("auto", (try e.parallel("auto", "8")).?); + try t.expectEqualStrings("8", (try e.parallel(null, " 8 ")).?); + try t.expectEqualStrings("Auto", (try e.parallel(null, "Auto")).?); // the text passes through; cli.parallel matches it without case + try t.expect((try e.parallel(null, null)) == null); + try t.expect((try e.parallel(null, " \t")) == null); + for ([_][]const u8{ "0", "4097", "typo", "-1", "8\nwrong" }) |raw| { + try t.expectError(error.InvalidEnvironment, e.parallel(null, raw)); + const why = (try e.refusal(a, Env{ .name = "TENSORFOLD_PARALLEL", .raw = raw }, all)).?; + defer a.free(why); + try t.expect(std.mem.indexOf(u8, why, "TENSORFOLD_PARALLEL") != null); + try t.expect(std.mem.indexOf(u8, why, "or auto") != null); + } +} + +test "environment: Qwen host GiB cap is strict, bounded and blank as unset" { + const name = "TF_QWEN_KV_HOST_GIB"; + for ([_]?[]const u8{ null, "", " \t\r\n" }) |raw| try t.expectEqual(@as(u64, 0), try e.value(u64, name, raw, 0)); + try t.expectEqual(@as(u64, 8), try e.value(u64, name, "8", 0)); + try t.expectEqual(@as(u64, std.math.maxInt(u64) >> 30), try e.value(u64, name, "17179869183", 0)); + for ([_][]const u8{ "0", "-1", "bad", "1.5", "17179869184" }) |raw| try t.expectError(error.InvalidEnvironment, e.value(u64, name, raw, 0)); +} diff --git a/zig/src/platform/file_identity.zig b/zig/src/platform/file_identity.zig index 4c126ed767a..03d0929bedf 100644 --- a/zig/src/platform/file_identity.zig +++ b/zig/src/platform/file_identity.zig @@ -4,12 +4,23 @@ const std = @import("std"); pub fn hash(io: std.Io, path: []const u8, maximum: u64) ![32]u8 { const file = try std.Io.Dir.cwd().openFile(io, path, .{}); defer file.close(io); + return hashFile(io, file, maximum); +} + +/// An open file's bytes, checked against its stamps across the read; an open file keeps its inode if its path moves. +pub fn hashFile(io: std.Io, file: std.Io.File, maximum: u64) ![32]u8 { + return hashUntil(io, file, maximum, null); +} + +/// `hashFile`, ending with error.Stopped at the next block once `stop` is set. +pub fn hashUntil(io: std.Io, file: std.Io.File, maximum: u64, stop: ?*const std.atomic.Value(bool)) ![32]u8 { const before = try file.stat(io); if (before.size > maximum) return error.IdentityFileTooLarge; var h = std.crypto.hash.sha2.Sha256.init(.{}); var buf: [32768]u8 = undefined; var at: u64 = 0; while (at < before.size) { + if (stop) |s| if (s.load(.acquire)) return error.Stopped; const n = try file.readPositionalAll(io, buf[0..@intCast(@min(buf.len, before.size - at))], at); if (n == 0) return error.IdentityFileChanged; h.update(buf[0..n]); diff --git a/zig/src/qwen27_bank_test.zig b/zig/src/qwen27_bank_test.zig index f9f92db2831..856ab29c6be 100644 --- a/zig/src/qwen27_bank_test.zig +++ b/zig/src/qwen27_bank_test.zig @@ -20,7 +20,7 @@ fn shape() !abi.Shape { test "qwen27 bank: construction does not allocate rollback storage for idle or lone use" { var allocations: metal.Allocations = .{}; const device = metal.Device{ .allocations = &allocations }; - var pool = try gpu.Pool.init(device, try shape(), 2, 8, 16); + var pool = try gpu.Pool.init(a, device, try shape(), 2, 8, 16); defer pool.deinit(); try std.testing.expect(allocations.bytes <= pool.budget.totalBytes() - pool.budget.state); } @@ -40,14 +40,14 @@ test "qwen27 bank: constructor allocation failures unwind every earlier buffer" var count: usize = 0; { var allocations: metal.Allocations = .{}; - var pool = try gpu.Pool.init(.{ .allocations = &allocations }, try shape(), 2, 8, 16); + var pool = try gpu.Pool.init(a, .{ .allocations = &allocations }, try shape(), 2, 8, 16); count = allocations.calls; pool.deinit(); try std.testing.expectEqual(@as(usize, 0), allocations.live); } for (0..count) |fail| { var allocations: metal.Allocations = .{ .fail = fail }; - try std.testing.expectError(error.NoBuffer, gpu.Pool.init(.{ .allocations = &allocations }, try shape(), 2, 8, 16)); + try std.testing.expectError(error.NoBuffer, gpu.Pool.init(a, .{ .allocations = &allocations }, try shape(), 2, 8, 16)); try std.testing.expectEqual(@as(usize, 0), allocations.live); try std.testing.expectEqual(@as(usize, 0), allocations.bytes); } @@ -56,7 +56,7 @@ test "qwen27 bank: constructor allocation failures unwind every earlier buffer" test "qwen27 bank: actual plans allocate only the one-row rollback extent" { var allocations: metal.Allocations = .{}; const device = metal.Device{ .allocations = &allocations }; - var pool = try gpu.Pool.init(device, try shape(), 2, 8, 16); + var pool = try gpu.Pool.init(a, device, try shape(), 2, 8, 16); defer pool.deinit(); var one = try Window.init(a, 3, &.{-1}, 2, 64); defer one.deinit(); @@ -99,7 +99,7 @@ test "qwen27 bank: actual plans allocate only the one-row rollback extent" { test "qwen27 bank: growth shrink reuse and failed allocation leave committed words intact" { var allocations: metal.Allocations = .{}; const device = metal.Device{ .allocations = &allocations }; - var pool = try gpu.Pool.init(device, try shape(), 2, 8, 16); + var pool = try gpu.Pool.init(a, device, try shape(), 2, 8, 16); defer pool.deinit(); const base_bytes = allocations.bytes; var one = try Window.init(a, 3, &.{-1}, 2, 64); @@ -141,6 +141,35 @@ test "qwen27 bank: growth shrink reuse and failed allocation leave committed wor for (state) |word| try std.testing.expectEqual(@as(u8, 0x59), word); } +test "qwen27 bank: the rollback bank is the recurrent workspace's one lease; nothing else stays resident" { + var allocations: metal.Allocations = .{}; + const device = metal.Device{ .allocations = &allocations }; + var pool = try gpu.Pool.init(a, device, try shape(), 2, 8, 16); + defer pool.deinit(); + const live = allocations.live; + var one = try Window.init(a, 3, &.{-1}, 2, 64); + defer one.deinit(); + var small = try makePlan(&pool, &.{ + .{ .window = one, .state_slot = 0, .next_slot = 0, .path = &.{0} }, + .{ .window = one, .state_slot = 1, .next_slot = 1, .path = &.{0} }, + }); + defer small.deinit(); + var high = try makePlan(&pool, &.{ + .{ .window = one, .state_slot = 0, .next_slot = 0, .path = &.{0} }, + .{ .window = one, .state_slot = 7, .next_slot = 7, .path = &.{0} }, + }); + defer high.deinit(); + try pool.prepare(device, small, false); + try std.testing.expectEqual(pool.before.?.length(), pool.scratch.residentBytes()); + try std.testing.expectEqual(live + 1, allocations.live); + try pool.prepare(device, high, false); + try std.testing.expectEqual(pool.budget.state, pool.scratch.residentBytes()); // the smaller bank went first + try std.testing.expectEqual(live + 1, allocations.live); + try pool.prepare(device, high, true); + try std.testing.expectEqual(@as(usize, 0), pool.scratch.residentBytes()); + try std.testing.expectEqual(live, allocations.live); +} + const Fixture = struct { pool: gpu.Pool, metadata: gpu.Metadata, @@ -148,7 +177,7 @@ const Fixture = struct { output: metal.Buffer, fn init(device: metal.Device) !Fixture { var f: Fixture = undefined; - f.pool = try gpu.Pool.init(device, try shape(), 2, 8, 16); + f.pool = try gpu.Pool.init(a, device, try shape(), 2, 8, 16); errdefer f.pool.deinit(); inline for (@typeInfo(gpu.Metadata).@"struct".field_names) |name| @field(f.metadata, name) = .{ .buffer = try device.buffer(4096, 0) }; diff --git a/zig/src/qwen27_keep_test.zig b/zig/src/qwen27_keep_test.zig index 5bb0fb3f31e..2db3c656283 100644 --- a/zig/src/qwen27_keep_test.zig +++ b/zig/src/qwen27_keep_test.zig @@ -32,6 +32,7 @@ test "qwen27 speed: shared in-place verify then empty and full keeps restore sta .budget = try @import("families/qwen27/gdn_pool.zig").Budget.init(shape, 1, 2, 2), .buffers = undefined, .kernels = undefined, + .scratch = gpu.Pool.emptyScratch(a), }; for (&pool.buffers, 0..) |*b, i| { b.* = .{ .id = i + 1, .data = try a.alignedAlloc(u8, .@"16", 2 * shape.state * 4) }; @@ -76,7 +77,7 @@ test "qwen27 speed: shared in-place verify then empty and full keeps restore sta var record: metal.Recorder = .{}; const e = metal.ComputeEncoder{ .record = &record }; var allocations: metal.Allocations = .{}; - defer pool.releaseBefore(); + defer pool.deinitScratch(); try pool.prepare(.{ .allocations = &allocations }, plan, false); try pool.forward(0, .{ .host = plan, .metadata = metadata }, refs, e); try std.testing.expect(!std.mem.eql(u8, original, state)); diff --git a/zig/src/qwen35_prefill_steps_test.zig b/zig/src/qwen35_prefill_steps_test.zig new file mode 100644 index 00000000000..5cb43c21e45 --- /dev/null +++ b/zig/src/qwen35_prefill_steps_test.zig @@ -0,0 +1,300 @@ +//! Qwen2B Metal's stepped prompt pass (#3021) on host-backed caches with a sentinel forward: cuts, state, decodes. +const std = @import("std"); +const mtl = @import("metal"); +const lanes = @import("lanes"); +const st = @import("families/qwen3_5/state.zig"); +const snapshot = @import("families/qwen3_5/snapshot.zig"); +const prefill = @import("families/qwen3_5/prefill.zig"); +const be = lanes.backend; +const t = std.testing; +const a = t.allocator; + +/// The cuts of main's whole loop (prefill.zig's run before #3021), copied as they were, `mark` carried. +fn mainCuts(total: usize, from: usize, cap: usize, planned: []const u32, kept_marks: []const u32) ![][2]usize { + var out: std.ArrayList([2]usize) = .empty; + var at = from; + var mark: usize = 0; + while (at < total) { + var end = @min(total, at + cap); + for (planned) |boundary| if (boundary > at) { + end = @min(end, boundary); + break; + }; + while (mark < kept_marks.len and kept_marks[mark] <= at) mark += 1; + if (mark < kept_marks.len) end = @min(end, kept_marks[mark]); + try out.append(a, .{ at, end }); + at = end; + } + return out.toOwnedSlice(a); +} + +/// A forward stand-in whose state depends on every token in order: the GDN recurrences, the conv rows and the logits. +fn sentinel(cache: *st.Cache, ids: []const u32) void { + for (ids) |id| { + for (cache.blocks, 0..) |block, layer| if (block == .delta) { + const state = block.delta.recurrence.slice(u32, st.delta_bytes / 4); + state[0] = state[0] *% 31 +% id +% @as(u32, @intCast(layer)); + state[state.len - 1] +%= state[0]; + const conv = block.delta.conv.slice(u16, st.conv_bytes / 2); + conv[0] +%= @truncate(id); + }; + const logits = cache.logits.slice(u32, 1); + logits[0] = logits[0] *% 131 +% id; + cache.len += 1; + } +} + +/// promptChunk's stand-in: each chunk logged by stream, then the sentinel forward. +const Rec = struct { + gpa: std.mem.Allocator = a, + log: *std.ArrayList(Event), + id: u8, + fn advance(r: Rec, cache: *st.Cache, ids: []const u32) !void { + try r.log.append(a, .{ .chunk = .{ .id = r.id, .at = cache.len, .end = cache.len + ids.len } }); + sentinel(cache, ids); + } +}; + +const Event = union(enum) { chunk: struct { id: u8, at: usize, end: usize }, decode: u8 }; + +fn seeded(device: mtl.Device, capacity: usize) !st.Cache { + var cache = try st.Cache.init(a, device, capacity); + @memset(cache.logits.contents()[0 .. 4 * 2], 0); + for (cache.blocks) |block| if (block == .delta) { + @memset(block.delta.recurrence.contents()[0..st.delta_bytes], 0); + @memset(block.delta.conv.contents()[0..st.conv_bytes], 0); + }; + return cache; +} + +/// The bytes the sentinel writes, and the length, equal in two caches. +fn expectSame(x: *const st.Cache, y: *const st.Cache) !void { + try t.expectEqual(x.len, y.len); + try t.expectEqualSlices(u8, x.logits.contents()[0..4], y.logits.contents()[0..4]); + for (x.blocks, y.blocks) |p, q| if (p == .delta) { + try t.expectEqualSlices(u8, p.delta.recurrence.contents()[0..st.delta_bytes], q.delta.recurrence.contents()[0..st.delta_bytes]); + try t.expectEqualSlices(u8, p.delta.conv.contents()[0..st.conv_bytes], q.delta.conv.contents()[0..st.conv_bytes]); + }; +} + +fn cutsOf(log: []const Event, id: u8) ![][2]usize { + var out: std.ArrayList([2]usize) = .empty; + for (log) |e| if (e == .chunk and e.chunk.id == id) try out.append(a, .{ e.chunk.at, e.chunk.end }); + return out.toOwnedSlice(a); +} + +/// A 29-token prompt at an 8-row chunk: planned starts at 3 and 20, a kept mark at 11. +const len = 29; +const rows = 8; +const chunks = [_]u32{ 3, 20 }; +const marks = [_]u32{11}; + +fn prompt() [len]u32 { + var ids: [len]u32 = undefined; + for (&ids, 0..) |*x, i| x.* = @intCast(i * 17 % 101 + 1); + return ids; +} + +test "Qwen2B Metal steps: one call runs one chunk at today's cut, and the steps leave the whole pass's state" { + var allocations: mtl.Allocations = .{}; + const device: mtl.Device = .{ .allocations = &allocations }; + const ids = prompt(); + const want = try mainCuts(len, 0, rows, &chunks, &marks); + defer a.free(want); + try t.expectEqualSlices([2]usize, &.{ .{ 0, 3 }, .{ 3, 11 }, .{ 11, 19 }, .{ 19, 20 }, .{ 20, 28 }, .{ 28, 29 } }, want); + var log: std.ArrayList(Event) = .empty; + defer log.deinit(a); + // the whole pass, as prefillFn runs it + var whole = try seeded(device, 64); + defer whole.deinit(); + var s = try lanes.Stream.init(a, .{ .id = "w", .prompt = &ids, .max_new = 4, .chunks = &chunks, .reuse = .{ .marks = &marks } }); + defer s.deinit(a); + try prefill.run(&whole, &s, rows, Rec{ .log = &log, .id = 'w' }, Rec.advance); + // the same prompt a chunk a call, as prefillStepFn runs it + var stepped = try seeded(device, 64); + defer stepped.deinit(); + var u = try lanes.Stream.init(a, .{ .id = "s", .prompt = &ids, .max_new = 4, .chunks = &chunks, .reuse = .{ .marks = &marks } }); + defer u.deinit(a); + var at = prefill.open(&stepped, &u); + for (want, 0..) |w, i| { + const before = log.items.len; + try t.expectEqual(i + 1 == want.len, try prefill.step(&stepped, &u, &at, rows, Rec{ .log = &log, .id = 's' }, Rec.advance)); + try t.expectEqual(before + 1, log.items.len); // one chunk a call + try t.expectEqual(@as(u32, @intCast(w[1])), u.fill_at.load(.monotonic)); + } + const got_whole = try cutsOf(log.items, 'w'); + defer a.free(got_whole); + const got_steps = try cutsOf(log.items, 's'); + defer a.free(got_steps); + try t.expectEqualSlices([2]usize, want, got_whole); + try t.expectEqualSlices([2]usize, want, got_steps); + try t.expectEqualSlices(u32, s.prefill_widths.items, u.prefill_widths.items); + try expectSame(&whole, &stepped); + // a call after the last chunk has nothing left: done, and no chunk runs + try t.expect(try prefill.step(&stepped, &u, &at, rows, Rec{ .log = &log, .id = 's' }, Rec.advance)); + try t.expectEqual(want.len, got_steps.len); +} + +test "Qwen2B Metal steps: a pass resumed from a kept state cuts as main's loop does, and a cancel keeps the last chunk's end" { + var allocations: mtl.Allocations = .{}; + const device: mtl.Device = .{ .allocations = &allocations }; + const ids = prompt(); + var log: std.ArrayList(Event) = .empty; + defer log.deinit(a); + // the state after rows 0..11, kept + var source = try seeded(device, 64); + defer source.deinit(); + sentinel(&source, ids[0..11]); + const snap = try snapshot.save(a, &source, 11); + defer snapshot.drop(a, snap); + var resumed = try seeded(device, 64); + defer resumed.deinit(); + var s = try lanes.Stream.init(a, .{ .id = "r", .prompt = &ids, .max_new = 4, .chunks = &chunks, .reuse = .{ .saved = @ptrCast(snap), .at = 11, .marks = &marks } }); + defer s.deinit(a); + var at = prefill.open(&resumed, &s); + try t.expectEqual(@as(usize, 11), at); + try t.expectEqual(@as(u32, 11), s.cached); + while (!try prefill.step(&resumed, &s, &at, rows, Rec{ .log = &log, .id = 'r' }, Rec.advance)) {} + const want = try mainCuts(len, 11, rows, &chunks, &marks); + defer a.free(want); + const got = try cutsOf(log.items, 'r'); + defer a.free(got); + try t.expectEqualSlices([2]usize, want, got); + var fresh = try seeded(device, 64); + defer fresh.deinit(); + sentinel(&fresh, &ids); + try expectSame(&fresh, &resumed); + + // a cancel asked before the fourth chunk: the rows in (0..19) are kept and no chunk runs + const Flags = struct { + var kept: ?u32 = null; + var cancelled = false; + fn keep(_: *anyopaque, _: *lanes.Stream, row: u32) void { + kept = row; + } + fn check(_: *anyopaque) bool { + return cancelled; + } + }; + var dummy: u8 = 0; + var cut = try seeded(device, 64); + defer cut.deinit(); + var c = try lanes.Stream.init(a, .{ .id = "c", .prompt = &ids, .max_new = 4, .chunks = &chunks, .reuse = .{ .marks = &marks }, .cancel_check = .{ .ptr = &dummy, .check = Flags.check } }); + defer c.deinit(a); + c.reuse.hook = .{ .ptr = &dummy, .at = Flags.keep }; + var row = prefill.open(&cut, &c); + for (0..3) |_| _ = try prefill.step(&cut, &c, &row, rows, Rec{ .log = &log, .id = 'c' }, Rec.advance); + Flags.cancelled = true; + Flags.kept = null; + try t.expectError(error.Cancelled, prefill.step(&cut, &c, &row, rows, Rec{ .log = &log, .id = 'c' }, Rec.advance)); + try t.expectEqual(@as(?u32, 19), Flags.kept); + try t.expectEqual(@as(usize, 19), cut.len); + // cancel_prefill between calls keeps the same row (cancelPrefillFn: keepInterruptedPrefill at the fill's row) + Flags.kept = null; + c.keepInterruptedPrefill(@intCast(row)); + try t.expectEqual(@as(?u32, 19), Flags.kept); +} + +/// The lanes fake with Qwen2B's stepping in front: each stream's host cache, its prompt a chunk a call at 4 rows. +const Q = struct { + fake: lanes.fake.Fake, + device: mtl.Device, + inner: be.Backend = undefined, + passes: std.AutoHashMapUnmanaged(*lanes.Stream, struct { cache: *st.Cache, at: usize }) = .empty, + log: std.ArrayList(Event) = .empty, + vt: be.Backend.VTable = undefined, + + var current: *Q = undefined; + + fn init(x: *Q) 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; + return .{ .ptr = x.inner.ptr, .vtable = &x.vt }; + } + + fn deinit(x: *Q) void { + var it = x.passes.valueIterator(); + while (it.next()) |p| { + p.cache.deinit(); + a.destroy(p.cache); + } + x.passes.deinit(a); + x.log.deinit(a); + x.fake.deinit(); + } + + fn prefillStep(ptr: *anyopaque, s: *lanes.Stream, _: u32) anyerror!bool { + const x = current; + const got = try x.passes.getOrPut(a, s); + if (!got.found_existing) { + const cache = try a.create(st.Cache); + cache.* = try seeded(x.device, 64); + got.value_ptr.* = .{ .cache = cache, .at = prefill.open(cache, s) }; + } + const p = got.value_ptr; + const done = try prefill.step(p.cache, s, &p.at, 4, Rec{ .log = &x.log, .id = s.id[0] }, Rec.advance); + if (done) 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(a, .{ .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(a, .{ .decode = w.stream.id[0] }); + return current.inner.vtable.verify(ptr, windows, out); + } +}; + +test "Qwen2B Metal steps: another stream decodes between two chunks, and the long prompt's state is the whole pass's" { + var allocations: mtl.Allocations = .{}; + const device: mtl.Device = .{ .allocations = &allocations }; + var costs: [16]lanes.config.Cost = undefined; + for (&costs, 1..) |*cost, w| cost.* = .{ .width = @intCast(w), .ms = 5.0 + 0.8 * @as(f64, @floatFromInt(w)) }; + var cfg = try lanes.config.Config.init(a, .{ .exact_width = 16, .gpu_tokens = true, .window_costs = &costs, .hidden_rows = true, .batch_rows = 32, .max_streams = 8 }, 16, 15); + defer cfg.deinit(a); + var q: Q = .{ .fake = .{ .gpa = a }, .device = device }; + defer q.deinit(); + var clock: lanes.fake.FixedClock = .{}; + var engine = lanes.Engine.init(a, &cfg, q.init(), clock.clock()); + defer engine.deinit(); + try t.expect(engine.fills()); // the lane host steps this backend's prompts (lane_host_fill.zig) + const short = [_]u32{ 5, 6, 7 }; + const long = [_]u32{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }; + var x = try lanes.Stream.init(a, .{ .id = "a", .prompt = &short, .max_new = 20, .drafts = false }); + defer x.deinit(a); + var y = try lanes.Stream.init(a, .{ .id = "b", .prompt = &long, .max_new = 4, .drafts = false }); + defer y.deinit(a); + while (!try engine.fillStream(&x, q.fake.prefill_count == 0)) {} + var first = true; + while (!try engine.fillStream(&y, first)) { + first = false; + try engine.step(); // stream a's round between b's chunks + } + var seen: [3]usize = undefined; + var n: usize = 0; + for (q.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 (q.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(); + // b's cache after three stepped chunks with decodes between them: the whole prompt's state + var whole = try seeded(device, 64); + defer whole.deinit(); + sentinel(&whole, &long); + try expectSame(&whole, q.passes.get(&y).?.cache); +} diff --git a/zig/src/server/anthropic.zig b/zig/src/server/anthropic.zig index 8f4408100ac..155eff605e0 100644 --- a/zig/src/server/anthropic.zig +++ b/zig/src/server/anthropic.zig @@ -53,7 +53,8 @@ fn countTokens(srv: *Server, cx: *Cx, chat: Value, client_thinking: bool) errors cx.clear_thinking = thinking.clear; cx.named_effort = fields.namedEffort(thinking.effort, srv.effort_levels); // as the chat route sets it const tools = try tool_specs.active(cx, chat.get("tools"), chat.get("tool_choice")); - const msgs = try messages_mod.normalizeWith(cx, chat.get("messages"), "system", srv.needs_user_after_tool, srv.media()); + const normalized = try messages_mod.normalizeWith(cx, chat.get("messages"), "system", srv.needs_user_after_tool, srv.media()); + const msgs = try @import("deferred_tools.zig").resolve(cx, normalized, chat.get("tools"), srv.text.deferred_native); const explicit_off = client_thinking and !(thinking.enable orelse true); const ids_ = prompt.renderRequest(srv, cx, msgs, tools, on, srv.effortFor(thinking.effort), true, explicit_off) catch |e| switch (e) { error.Refused => return cx.other(cx.message), diff --git a/zig/src/server/anthropic_translate.zig b/zig/src/server/anthropic_translate.zig index 92831f562f4..e0ccceb598a 100644 --- a/zig/src/server/anthropic_translate.zig +++ b/zig/src/server/anthropic_translate.zig @@ -153,6 +153,7 @@ fn messages(cx: *Cx, value: ?Value, system: ?Value) errors.Refused!Value { var texts: std.ArrayList([]const u8) = .empty; var result_parts: std.ArrayList(Value) = .empty; var has_image = false; + var has_reference = false; for (try parts(cx, block.get("content") orelse Value{ .string = "" })) |part| { if (part.typeIs("text")) { const t = try string(cx, part.get("text"), "tool_result.text", true); @@ -164,6 +165,13 @@ fn messages(cx: *Cx, value: ?Value, system: ?Value) errors.Refused!Value { } else if (part.typeIs("document")) { try result_parts.append(a, try document(cx, part)); has_image = true; + } else if (part.typeIs("tool_reference")) { + const name = try string(cx, part.get("tool_name"), "tool_reference.tool_name", false); + const ref = try json.newObject(a); + try ref.put(a, "type", .{ .string = "tool_reference" }); + try ref.put(a, "name", .{ .string = name }); + try result_parts.append(a, .{ .object = ref }); + has_reference = true; } else return cx.fail(.request, "unsupported tool_result content type {s}", .{try pyrepr.repr(a, part.get("type"))}); } var text = try std.mem.join(a, "\n", texts.items); @@ -174,7 +182,7 @@ fn messages(cx: *Cx, value: ?Value, system: ?Value) errors.Refused!Value { const m = try json.newObject(a); try m.put(a, "role", .{ .string = "tool" }); try m.put(a, "tool_call_id", .{ .string = try string(cx, block.get("tool_use_id"), "tool_use_id", false) }); - try m.put(a, "content", if (has_image) .{ .array = result_parts.items } else .{ .string = text }); + try m.put(a, "content", if (has_image or has_reference) .{ .array = result_parts.items } else .{ .string = text }); try out.append(a, .{ .object = m }); } else return cx.fail(.request, "unsupported {s} content block type {s}", .{ role, try pyrepr.repr(a, kind) }); } @@ -206,6 +214,7 @@ fn positiveInt(v: ?Value) ?i64 { pub fn translate(cx: *Cx, body: Value, count: bool) errors.Refused!Value { const a = cx.a; if (body != .object) return cx.refuse("request body must be an object"); + if (json.truthyField(body, "execution_witness")) return cx.refuse("execution_witness is supported on /v1/chat/completions and /v1/completions only"); const model = try string(cx, body.get("model"), "model", false); const chat = try json.newObject(a); try chat.put(a, "model", .{ .string = model }); @@ -241,6 +250,7 @@ pub fn translate(cx: *Cx, body: Value, count: bool) errors.Refused!Value { const tools = body.get("tools") orelse Value{ .array = &.{} }; if (tools != .array) return cx.refuse("tools must be an array"); var translated: std.ArrayList(Value) = .empty; + var deferred: usize = 0; for (tools.array) |tool| { const kind = if (tool == .object) tool.get("type") orelse Value{ .string = "custom" } else Value.null; if (tool != .object or kind != .string or !std.mem.eql(u8, kind.string, "custom")) return cx.refuse("only client-defined function tools are supported"); @@ -251,11 +261,19 @@ pub fn translate(cx: *Cx, body: Value, count: bool) errors.Refused!Value { try function.put(a, "name", .{ .string = name }); try function.put(a, "parameters", schema); if (tool.has("description")) try function.put(a, "description", .{ .string = try string(cx, tool.get("description"), "tool.description", true) }); + if (tool.get("defer_loading")) |d| { + if (d != .bool) return cx.refuse("tool.defer_loading must be a boolean"); + if (d.bool) { // false is the default: the tool translates as it does without the field + try function.put(a, "defer_loading", d); + deferred += 1; + } + } const t = try json.newObject(a); try t.put(a, "type", .{ .string = "function" }); try t.put(a, "function", .{ .object = function }); try translated.append(a, .{ .object = t }); } + if (deferred > 0 and deferred == translated.items.len) return cx.refuse("At least one tool must have defer_loading=false. All tools cannot be deferred."); if (translated.items.len > 0) try chat.put(a, "tools", .{ .array = translated.items }); if (body.field("tool_choice")) |choice| { if (choice != .object) return cx.refuse("tool_choice must be an object"); diff --git a/zig/src/server/auth_scope.zig b/zig/src/server/auth_scope.zig index fb81ae6e699..fd353e6cdce 100644 --- a/zig/src/server/auth_scope.zig +++ b/zig/src/server/auth_scope.zig @@ -57,7 +57,7 @@ fn validLabel(label: []const u8) bool { } const listing = [_][]const u8{ "/models", "/v1/models", "/v1/voices", "/api/tags", "/api/ps", "/api/version" }; -const reading = [_][]const u8{ "/memory", "/v1/memory", "/metrics", "/v1/metrics", "/v1/load", "/stats", "/dashboard", "/v1/benchmark/manifest", "/api/show" }; +const reading = [_][]const u8{ "/memory", "/v1/memory", "/metrics", "/v1/metrics", "/v1/load", "/stats", "/dashboard", "/v1/benchmark/manifest", "/api/show", "/v1/execution/witness" }; const inferring = [_][]const u8{ "/chat/completions", "/v1/chat/completions", "/completions", "/v1/completions", "/messages", "/v1/messages", "/messages/count_tokens", "/v1/messages/count_tokens", @@ -106,7 +106,7 @@ fn oneOf(route: []const u8, names: []const []const u8) bool { return false; } -pub const Denial = enum { route, response_history, response_storage }; +pub const Denial = enum { route, response_history, response_storage, execution_witness }; /// The stored Responses are the server's, so a restricted key's request must be stateless: store false, no parent. pub fn responseDenial(scopes: Scopes, body: json.Value) ?Denial { @@ -116,3 +116,10 @@ pub fn responseDenial(scopes: Scopes, body: json.Value) ?Denial { if (store != .bool or store.bool) return .response_storage; return null; } + +/// The witness is read-scoped, so a reply binds it only for a key that may read it: admin, or one with read. +pub fn witnessDenial(scopes: Scopes, body: json.Value) ?Denial { + if (scopes.admin or scopes.read or body != .object) return null; + const asked = body.get("execution_witness") orelse return null; + return if (asked == .bool and asked.bool) .execution_witness else null; +} diff --git a/zig/src/server/auth_scope_http_test.zig b/zig/src/server/auth_scope_http_test.zig index c50543995fe..081108d39e2 100644 --- a/zig/src/server/auth_scope_http_test.zig +++ b/zig/src/server/auth_scope_http_test.zig @@ -41,8 +41,14 @@ const Text = struct { const Engine = struct { calls: std.atomic.Value(u32) = .init(0), reads: std.atomic.Value(u32) = .init(0), + flushes: std.atomic.Value(u32) = .init(0), fn engine(e: *Engine) api.Engine { - return .{ .ctx = e, .vtable = &.{ .info = info, .submit = submit, .cancel = cancel, .status = status, .memory = memory } }; + return .{ .ctx = e, .vtable = &.{ .info = info, .submit = submit, .cancel = cancel, .status = status, .memory = memory, .imprint = imprint } }; + } + fn imprint(ptr: *anyopaque, ask: *api.ImprintAsk) bool { + _ = cast(ptr).flushes.fetchAdd(1, .monotonic); + ask.done.store(true, .release); + return true; } fn cast(ptr: *anyopaque) *Engine { return @ptrCast(@alignCast(ptr)); @@ -405,6 +411,34 @@ test "auth scopes HTTP: the request cancel route needs a full key, a loopback ca try expectStatus(try h.ask(a, "POST", "/v1/requests/chatcmpl-nobody/cancel", "admin-secret", ""), 404); } +test "auth scopes HTTP: the prompt cache flush route needs a full key, a loopback caller's included" { + var file = try KeyFile.init(key_text); + defer file.deinit(); + var keys: auth.Store = undefined; + var engine: Engine = .{}; + var h: Harness = .{}; + try start(&file, &keys, &engine, &h); + defer keys.deinit(); + defer h.deinit(); + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const path = "/v1/prompt_cache/flush"; + for (restricted) |key| { + const denied = try h.ask(a, "POST", path, key, ""); + try expectStatus(denied, 403); + try t.expect(std.mem.indexOf(u8, denied, "\"code\": \"insufficient_scope\"") != null); + } + try expectStatus(try h.ask(a, "POST", path, "", ""), 401); + try t.expectEqual(@as(u32, 0), engine.flushes.load(.monotonic)); + for (full_keys) |key| { + const done = try h.ask(a, "POST", path, key, "{}"); + try expectStatus(done, 200); + try t.expectEqualStrings("prompt_cache.flush", (try payload(a, done)).strField("object").?); + } + try t.expectEqual(@as(u32, full_keys.len), engine.flushes.load(.monotonic)); +} + test "CORS HTTP: a listed origin's preflight is answered before keys, its requests still need one, and its replies and streams carry the origin" { var file = try KeyFile.init(key_text); defer file.deinit(); diff --git a/zig/src/server/auth_scope_reply.zig b/zig/src/server/auth_scope_reply.zig index c68efce1a1e..6038ee11f38 100644 --- a/zig/src/server/auth_scope_reply.zig +++ b/zig/src/server/auth_scope_reply.zig @@ -22,5 +22,6 @@ pub fn text(anthropic_shape: bool, reason: scope.Denial) []const u8 { .route => "{\"error\": {\"message\": \"This API key does not permit this operation\", \"type\": \"permission_error\", \"param\": null, \"code\": \"insufficient_scope\"}}", .response_history => "{\"error\": {\"message\": \"This API key cannot read stored responses: send the whole conversation without previous_response_id\", \"type\": \"permission_error\", \"param\": \"previous_response_id\", \"code\": \"insufficient_scope\"}}", .response_storage => "{\"error\": {\"message\": \"This API key cannot store responses: send \\\"store\\\": false\", \"type\": \"permission_error\", \"param\": \"store\", \"code\": \"insufficient_scope\"}}", + .execution_witness => "{\"error\": {\"message\": \"This API key cannot read the execution witness: send the request without execution_witness\", \"type\": \"permission_error\", \"param\": \"execution_witness\", \"code\": \"insufficient_scope\"}}", }; } diff --git a/zig/src/server/auth_scope_test.zig b/zig/src/server/auth_scope_test.zig index 997d04f6225..0ba177feaab 100644 --- a/zig/src/server/auth_scope_test.zig +++ b/zig/src/server/auth_scope_test.zig @@ -141,6 +141,16 @@ test "auth scopes: restricted Responses requests must be stateless and full keys try t.expectEqual(@as(?scope.Denial, null), try denial(scope.full, body)); } +test "auth scopes: a reply's execution witness needs read beside inference; admin and full keys keep it" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const asked = (try json.parse(arena.allocator(), "{\"prompt\":\"x\",\"execution_witness\":true}")).ok; + try t.expectEqual(@as(?scope.Denial, .execution_witness), scope.witnessDenial(.{ .inference = true }, asked)); + for ([_]scope.Scopes{ .{ .inference = true, .read = true }, scope.full }) |s| try t.expectEqual(@as(?scope.Denial, null), scope.witnessDenial(s, asked)); + for ([_][]const u8{ "{\"prompt\":\"x\"}", "{\"execution_witness\":false}", "{\"execution_witness\":1}", "[1]" }) |body| + try t.expectEqual(@as(?scope.Denial, null), scope.witnessDenial(.{ .inference = true }, (try json.parse(arena.allocator(), body)).ok)); +} + test "auth scopes: flags, environment and plain file lines keep every route; the first configured key wins" { var file = try KeyFile.init("ops: file-secret\nplain-secret\nworker[inference]: app-secret\n"); defer file.deinit(); diff --git a/zig/src/server/cache_flush.zig b/zig/src/server/cache_flush.zig new file mode 100644 index 00000000000..2ba1edc3038 --- /dev/null +++ b/zig/src/server/cache_flush.zig @@ -0,0 +1,82 @@ +//! POST /v1/prompt_cache/flush: every kept prompt state dropped, in RAM and on disk, after the requests in flight end. +const std = @import("std"); +const api = @import("engine_api"); +const json = @import("json"); +const cancel_ids = @import("cancel_ids.zig"); +const log = @import("log.zig"); +const routes = @import("routes.zig"); +const Server = @import("server.zig").Server; +const Conn = @import("http_conn.zig").Conn; +const Allocator = std.mem.Allocator; +const Ask = api.ImprintAsk; + +pub const path = "/v1/prompt_cache/flush"; + +/// The engine answers once the requests in flight have ended; a long reply can hold it this long. +pub const wait_ms = 10 * 60 * 1000; + +pub const Reply = struct { status: u16, body: json.Value }; + +/// The flush asked of `engine` and waited for: 200 with what it dropped, 501 where no store keeps states, else 503. +pub fn answer(gpa: Allocator, io: std.Io, a: Allocator, engine: api.Engine, ms: u32) !Reply { + // the ask lives in the server's memory: once the engine holds it past a 503, it leaks rather than be freed under it + const ask = try gpa.create(Ask); + ask.* = .{ .op = .flush }; + const t0 = std.Io.Clock.awake.now(io); + if (!engine.imprintAsk(ask)) { + gpa.destroy(ask); + return .{ .status = 501, .body = try failure(a, "this engine keeps no prompt states it can drop", "invalid_request_error", "not_supported") }; + } + if (!ask.wait(io, ms)) { + const withdrawn = ask.withdraw(); // not yet taken: it never runs, and admissions go on at once + if (withdrawn or !ask.wait(io, ms)) { + log.line("prompt cache flush: the engine did not answer in {d} s", .{ms / 1000}); + const why = if (withdrawn) "the requests in flight did not end in time: the flush was withdrawn and nothing was dropped" else "the engine did not finish the flush in time"; + return .{ .status = 503, .body = try failure(a, why, "server_error", "timeout") }; + } + } + defer gpa.destroy(ask); + const o = try json.newObject(a); + try o.put(a, "object", .{ .string = "prompt_cache.flush" }); + try o.put(a, "states", try json.intValue(a, ask.dropped)); + try o.put(a, "ram_bytes", try json.intValue(a, ask.ram_freed)); + try o.put(a, "disk_bytes", try json.intValue(a, ask.freed)); + try o.put(a, "disk", .{ .bool = ask.disk }); + const ns = t0.durationTo(std.Io.Clock.awake.now(io)).toNanoseconds(); + try o.put(a, "waited_seconds", .{ .float = @as(f64, @floatFromInt(ns)) / 1e9 }); + return .{ .status = 200, .body = .{ .object = o } }; +} + +fn failure(a: Allocator, message: []const u8, kind: []const u8, code: []const u8) !json.Value { + const err = try json.newObject(a); + try err.put(a, "message", .{ .string = message }); + try err.put(a, "type", .{ .string = kind }); + try err.put(a, "code", .{ .string = code }); + const o = try json.newObject(a); + try o.put(a, "error", .{ .object = err }); + return .{ .object = o }; +} + +/// POST /v1/prompt_cache/flush under the request cancel route's rule: an admin key, or a direct loopback caller. +pub fn post(srv: *Server, conn: *Conn, a: Allocator) void { + const keyed = if (srv.keys) |k| k.enabled() else false; + if (!cancel_ids.allowed(keyed, conn)) { + if (keyed) return @import("auth_scope_reply.zig").deny(conn, false, .route); + const message = "without API keys, only a direct loopback caller may flush the prompt cache"; + return routes.sendValue(conn, a, 403, failure(a, message, "permission_error", "loopback_only") catch return); + } + // --idle-unload: a resident engine is not parked under the flush; a parked one is not loaded for it + const idle = srv.idle_manager; + if (idle) |m| m.begin(); + defer if (idle) |m| m.end(); + if (idle) |m| if (m.isParked()) { + const message = "the model is unloaded: no state is in RAM, and those on disk stay until a flush while it is loaded"; + return routes.sendValue(conn, a, 503, failure(a, message, "server_error", "model_unloaded") catch return); + }; + const got = answer(srv.gpa, srv.io, a, srv.engine, wait_ms) catch return conn.sendError(a, 500, "out of memory", null) catch {}; + routes.sendValue(conn, a, got.status, got.body); +} + +test { + _ = @import("cache_flush_test.zig"); +} diff --git a/zig/src/server/cache_flush_test.zig b/zig/src/server/cache_flush_test.zig new file mode 100644 index 00000000000..ff124f58eaa --- /dev/null +++ b/zig/src/server/cache_flush_test.zig @@ -0,0 +1,190 @@ +//! POST /v1/prompt_cache/flush through the dispatcher: who may flush, the engine's answer, 501 and a withdrawn 503. +const std = @import("std"); +const api = @import("engine_api"); +const json = @import("json"); +const auth = @import("auth.zig"); +const scope = @import("auth_scope.zig"); +const flush = @import("cache_flush.zig"); +const routes = @import("routes.zig"); +const http = @import("http_conn.zig"); +const Server = @import("server.zig").Server; +const Allocator = std.mem.Allocator; +const Ask = api.ImprintAsk; +const t = std.testing; + +/// An engine whose flush answers at once with fixed counts, or (`answers` false) holds the ask as long requests would. +const Engine = struct { + asks: u32 = 0, + answers: bool = true, + takes: bool = false, // with `answers` false: taken by the engine thread, so its caller cannot withdraw it + held: ?*Ask = null, + fn engine(e: *Engine) api.Engine { + return .{ .ctx = e, .vtable = &.{ .info = info, .submit = submit, .cancel = cancel, .status = status, .memory = memory, .imprint = imprint } }; + } + fn bare(e: *Engine) api.Engine { + return .{ .ctx = e, .vtable = &.{ .info = info, .submit = submit, .cancel = cancel, .status = status, .memory = memory } }; + } + fn imprint(ctx: *anyopaque, ask: *Ask) bool { + const e: *Engine = @ptrCast(@alignCast(ctx)); + e.asks += 1; + if (!e.answers) { + if (e.takes) ask.claim.store(.taken, .release); + e.held = ask; + return true; + } + ask.dropped = 3; + ask.ram_freed = 4096; + ask.freed = 512; + ask.disk = true; + ask.done.store(true, .release); + return true; + } + fn info(_: *anyopaque) api.Info { + return .{}; + } + fn submit(_: *anyopaque, _: api.Id, _: *const api.Request, _: api.Sink) api.SubmitError!void { + return error.Busy; + } + fn cancel(_: *anyopaque, _: api.Id) void {} + fn status(_: *anyopaque, out: *api.Status, _: []u32) void { + out.* = .{}; + } + fn memory(_: *anyopaque, _: bool) ?api.Memory { + return null; + } +}; + +fn serve(engine: api.Engine, keys: ?*auth.Store) !*Server { + const text = @import("embedding_protocol_test.zig").ByteText.model(); + return Server.init(t.allocator, t.io, engine, text, .{ .served_name = "m", .model_ids = &.{"m"}, .enable_thinking = false, .use_drafts = false }, keys); +} + +/// The bytes a route writes, in place of a socket. +const Wire = struct { + a: Allocator, + bytes: std.ArrayList(u8) = .empty, + fn write(p: *anyopaque, bytes: []const u8) error{Closed}!void { + const w: *Wire = @ptrCast(@alignCast(p)); + w.bytes.appendSlice(w.a, bytes) catch return error.Closed; + } +}; + +const Caller = struct { peer: []const u8 = "127.0.0.1", headers: []const http.Header = &.{}, key: ?[]const u8 = null, scopes: scope.Scopes = scope.full }; + +/// One flush through the dispatcher, as the connection thread hands it over after the key gate; status and body. +fn call(srv: *Server, a: Allocator, c: Caller) !struct { status: u16, body: json.Value } { + var wire: Wire = .{ .a = a }; + const headers = try std.mem.concat(a, http.Header, &.{ &.{.{ .name = "Content-Length", .value = "2" }}, c.headers }); + var conn: http.Conn = .{ .fd = -1, .peer = c.peer, .buf = try a.dupe(u8, "{}"), .end = 2, .gpa = a, .version = "HTTP/1.1", .method = "POST", .path = flush.path, .headers = headers, .write_hooks = .{ .ctx = &wire, .write = Wire.write }, .key_label = c.key, .key_scopes = c.scopes }; + routes.dispatch(srv, &conn, a); + const out = wire.bytes.items; + const at = std.mem.indexOf(u8, out, "\r\n\r\n") orelse return error.MissingHttpHead; + return .{ .status = try std.fmt.parseInt(u16, out["HTTP/1.1 ".len..][0..3], 10), .body = (try json.parse(a, out[at + 4 ..])).ok }; +} + +fn code(body: json.Value) []const u8 { + return body.get("error").?.strField("code").?; +} + +test "security: prompt cache flush: a keyless server answers only a direct loopback caller" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var e: Engine = .{}; + const srv = try serve(e.engine(), null); + defer srv.deinit(); + for ([_][]const u8{ "10.1.2.3", "172.16.0.7", "2001:db8::1", "::ffff:a00:1", "localhost", "0.0.0.0", "" }) |peer| { + const got = try call(srv, a, .{ .peer = peer }); + try t.expectEqual(@as(u16, 403), got.status); + try t.expectEqualStrings("loopback_only", code(got.body)); + } + // a reverse proxy on the same machine: its loopback socket is refused, whatever address it forwards + for ([_][]const u8{ "Forwarded", "X-Forwarded-For", "x-real-ip", "Via", "CF-Connecting-IP", "True-Client-IP", "X-Forwarded-Host" }) |name| { + const got = try call(srv, a, .{ .headers = &.{.{ .name = name, .value = "127.0.0.1" }} }); + try t.expectEqual(@as(u16, 403), got.status); + try t.expectEqualStrings("loopback_only", code(got.body)); + } + try t.expectEqual(@as(u32, 0), e.asks); // no refused caller reached the engine + for ([_][]const u8{ "127.0.0.1", "127.8.9.10", "::1", "::ffff:7f00:1" }) |peer| { + const got = try call(srv, a, .{ .peer = peer }); + try t.expectEqual(@as(u16, 200), got.status); + try t.expectEqualStrings("prompt_cache.flush", got.body.strField("object").?); + try t.expectEqualStrings("3", got.body.get("states").?.int); + try t.expectEqualStrings("4096", got.body.get("ram_bytes").?.int); + try t.expectEqualStrings("512", got.body.get("disk_bytes").?.int); + try t.expect(got.body.get("disk").?.bool); + try t.expect(got.body.get("waited_seconds") != null); + } + try t.expectEqual(@as(u32, 4), e.asks); +} + +test "security: prompt cache flush: with API keys the route checks the matched key's admin scope itself" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var problem: []const u8 = ""; + var keys = try auth.Store.init(t.allocator, &.{"sk-flush-test"}, "", null, false, &problem); + defer keys.deinit(); + var e: Engine = .{}; + const srv = try serve(e.engine(), &keys); + defer srv.deinit(); + // the key gate refuses these before routing; if one got past it, the route refuses it too, from loopback as well + const refused = [_]Caller{ .{}, .{ .key = "app", .scopes = .{ .inference = true } }, .{ .key = "grafana", .scopes = .{ .read = true } }, .{ .key = "both", .scopes = .{ .inference = true, .read = true } } }; + for (refused) |c| { + const got = try call(srv, a, c); + try t.expectEqual(@as(u16, 403), got.status); + try t.expectEqualStrings("insufficient_scope", code(got.body)); + } + try t.expectEqual(@as(u32, 0), e.asks); + const admin = try call(srv, a, .{ .peer = "10.1.2.3", .key = "ops", .headers = &.{.{ .name = "X-Forwarded-For", .value = "10.9.9.9" }} }); + try t.expectEqual(@as(u16, 200), admin.status); // an admin key may flush from any address, through a proxy too + try t.expectEqual(@as(u32, 1), e.asks); +} + +test "prompt cache flush: 501 where no store keeps states, and a 503 whose flush was withdrawn" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var e: Engine = .{}; + const bare = try flush.answer(t.allocator, t.io, a, e.bare(), 20); + try t.expectEqual(@as(u16, 501), bare.status); + try t.expectEqualStrings("not_supported", code(bare.body)); + // requests that do not end within the wait: the flush is withdrawn untaken, so the engine never runs it + e.answers = false; + const late = try flush.answer(t.allocator, t.io, a, e.engine(), 20); + try t.expectEqual(@as(u16, 503), late.status); + try t.expectEqualStrings("timeout", code(late.body)); + const withdrawn = e.held.?; + defer t.allocator.destroy(withdrawn); // the engine's to drop: the route leaves it, never frees it under the engine + try t.expectEqual(api.ImprintClaim.withdrawn, withdrawn.claim.load(.acquire)); + try t.expect(!withdrawn.done.load(.acquire)); + // one the engine took cannot be withdrawn: the route waits once more for it, then answers 503 and leaves it + e.takes = true; + const taken = try flush.answer(t.allocator, t.io, a, e.engine(), 20); + try t.expectEqual(@as(u16, 503), taken.status); + defer t.allocator.destroy(e.held.?); + try t.expectEqual(api.ImprintClaim.taken, e.held.?.claim.load(.acquire)); + try t.expect(std.mem.indexOf(u8, taken.body.get("error").?.strField("message").?, "withdrawn") == null); +} + +test "prompt cache flush: a model --idle-unload parked answers 503 unloaded, neither asked nor woken" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var e: Engine = .{}; + const srv = try serve(e.engine(), null); + defer srv.deinit(); + var manager: @import("idle_unload.zig").Manager = .{ .gpa = t.allocator, .io = t.io, .args = .{}, .re = undefined, .dir = "m", .model_type = "m", .idle_s = 60, .parked = true, .state = .unloaded }; + srv.idle_manager = &manager; + defer srv.idle_manager = null; + const got = try call(srv, a, .{}); + try t.expectEqual(@as(u16, 503), got.status); + try t.expectEqualStrings("model_unloaded", code(got.body)); + try t.expectEqual(@as(u32, 0), e.asks); + try t.expectEqual(@as(u32, 0), manager.active); // the flush's lease on the engine ended with it + manager.parked = false; + manager.state = .resident; + try t.expectEqual(@as(u16, 200), (try call(srv, a, .{})).status); + try t.expectEqual(@as(u32, 1), e.asks); + try t.expectEqual(@as(u32, 0), manager.active); +} diff --git a/zig/src/server/cancel_ids.zig b/zig/src/server/cancel_ids.zig index a520898a2d0..3ff69747874 100644 --- a/zig/src/server/cancel_ids.zig +++ b/zig/src/server/cancel_ids.zig @@ -102,7 +102,7 @@ pub fn answer(io: std.Io, a: Allocator, id: []const u8, owner: ?[32]u8) !struct /// Headers a proxy adds: a keyless server's loopback peer may be a proxy relaying anyone, so they refuse. const relayed = [_][]const u8{ "Forwarded", "X-Forwarded-For", "X-Forwarded-Host", "X-Real-IP", "Via", "CF-Connecting-IP", "True-Client-IP" }; -/// Who may cancel: with keys, an admin key; without, a loopback peer whose request no proxy relayed. +/// Who may cancel or flush the prompt cache: with keys, an admin key; without, a loopback peer no proxy relayed. pub fn allowed(keyed: bool, conn: *const Conn) bool { if (keyed) return conn.key_label != null and conn.key_scopes.admin; // authenticate matched it before routing for (relayed) |name| if (conn.headerCount(name) > 0) return false; diff --git a/zig/src/server/chat.zig b/zig/src/server/chat.zig index 530b4c05c49..8f8c802050a 100644 --- a/zig/src/server/chat.zig +++ b/zig/src/server/chat.zig @@ -20,6 +20,7 @@ const Server = server_mod.Server; const Mailbox = @import("mailbox.zig").Mailbox; const StopHook = @import("stop_hook.zig").StopHook; const engine_refusal = @import("engine_refusal.zig"); +const witness_reply = @import("witness_reply.zig"); const Value = json.Value; const Cx = errors.Cx; const Allocator = std.mem.Allocator; @@ -52,6 +53,8 @@ pub const Input = struct { image_bytes: images.ByteLimits = .{}, /// With a known window, the reply may fill all the room the prompt leaves; max_tokens otherwise. fill_room: bool = false, + /// ``"execution_witness": true``: the reply binds the witness, its prompt, resolved request and tokens. + execution_witness: bool = false, }; /// A streamed piece: content text (a string) or a delta object (reasoning or tool calls). @@ -94,6 +97,7 @@ pub const Reply = struct { prompt_logprobs: ?Value = null, loop_stop: ?u32 = null, // the loop period when --loop-guard-stop ended the reply in its reasoning reasoning_recovered: bool = false, // ended at its end token in an unclosed think block: content repeats it + execution_witness: ?Value = null, // the reply binding, when the request asked (witness_reply.zig) }; pub const Failure = error{ Refused, Cancelled, Failed, OutOfMemory }; @@ -141,6 +145,7 @@ pub const Prepared = struct { stops: fields_mod.Stops, preparing: bool, frames: []const ?api.Size = &.{}, // each image part's tower input size, in part order (prompt.Rendered.frames) + deadline_ns: ?i96 = null, // "deadline_s": the server ends the reply there itself (finish_reason "deadline") }; /// Render ``input`` and run every check that can refuse it, before anything reaches the client or the engine. @@ -223,14 +228,20 @@ pub fn prepare(srv: *Server, cx: *Cx, input: Input, gone: anytype) Failure!Prepa request.think_close = srv.think_close; request.think_end = srv.think_close_end; } + @import("tool_think.zig").apply(&request, srv.config.tool_think_close and srv.info.capability(.thinking_budget) and (fields_mod.flag(f, "tool_call_required") orelse false), srv.think_close, srv.think_close_end); // The answer quota is separate only on engines that enforce it. if (srv.info.capability(.answer_limit)) @import("thinking_reserve.zig").apply(&request, srv.config.thinking_reserve, if (window > 0) window - n else std.math.maxInt(u32), srv.think_close_end); } request.logprobs = input.logprobs; request.prompt_logprobs = input.prompt_logprobs; if (try engine_refusal.of(srv.engine, cx, &request)) |message| return cx.refuse(message); + const deadline: ?i96 = if (f.get("deadline_s")) |v| blk: { + const s = (if (v == .bool) null else v.float64()) orelse return cx.refuse("deadline_s must be a number of seconds"); + if (!(s > 0 and s <= 1e6)) return cx.refuse("deadline_s must be more than 0 and at most 1000000 seconds"); + break :blk received + @as(i96, @intFromFloat(s * std.time.ns_per_s)); + } else null; if (input.trace) |trace| trace.prepared(&request, thinking, effort); - return .{ .input = input, .request = request, .prompt_len = rendered.ids.len, .received = received, .thinking = thinking, .reasoning = reasoning, .effort = effort, .sampled = sampling != null, .drafts = drafts, .token_ids = fields_mod.flag(f, "return_token_ids") orelse false, .stops = stops_opt, .preparing = preparing, .frames = rendered.frames }; + return .{ .input = input, .request = request, .prompt_len = rendered.ids.len, .received = received, .thinking = thinking, .reasoning = reasoning, .effort = effort, .sampled = sampling != null, .drafts = drafts, .token_ids = fields_mod.flag(f, "return_token_ids") orelse false, .stops = stops_opt, .preparing = preparing, .frames = rendered.frames, .deadline_ns = deadline }; } /// Submit a prepared request and collect its reply; ``sink`` hears the stream (null: not streamed). @@ -260,9 +271,11 @@ pub fn generate(srv: *Server, cx: *Cx, prepared: Prepared, sink: ?Sink, gone: an if (stops_opt.strings.len > 0) request.stop = .{ .ctx = &stop_hook, .check = StopHook.check }; var box: Mailbox = .{ .io = io, .gpa = srv.gpa }; defer box.deinit(); + if (sink != null) request.unread = &box.unread; // a streamed reply's reader can fall behind; a whole one cannot const id = srv.next_id.fetchAdd(1, .monotonic); if (srv.keepalive) |k| k.begin(); // the GPU is busy: the idle ticker holds its commits defer if (srv.keepalive) |k| k.end(); + const bound = if (input.execution_witness and srv.witness != null) try witness_reply.admit(srv, a, &request, stops_opt.strings) else null; srv.engine.submit(id, &request, .{ .ctx = &box, .event = Mailbox.onEvent }) catch |e| return switch (e) { error.Busy => refusals.count(srv, .engine_busy, cx.wait(wait.engine_busy, "the engine is busy; retry shortly", .{})), error.Closed => refusals.count(srv, .engine_unavailable, cx.wait(wait.engine_unavailable, "the engine is unavailable; retry after it restarts", .{})), @@ -273,7 +286,7 @@ 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, .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, .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 }; + 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, .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, .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 }; 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); @@ -283,10 +296,13 @@ pub fn generate(srv: *Server, cx: *Cx, prepared: Prepared, sink: ?Sink, gone: an 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); }; - if (result) |r| { - if (input.trace) |trace| trace.timed(r); - } else |e| logEnded(input.id, e, cx.message, prepared.prompt_len, gen.collected.items.len, seconds(nowNs(io) - received)); - return result; + var reply = result catch |e| { + logEnded(input.id, e, cx.message, prepared.prompt_len, gen.collected.items.len, seconds(nowNs(io) - received)); + return e; + }; + if (input.trace) |trace| trace.timed(reply); + if (bound) |b| reply.execution_witness = try witness_reply.value(a, srv, b, gen.collected.items, reply.finish_reason); + return reply; } /// The ``ended`` line of a submitted reply that ends without one: its client left, or it failed. diff --git a/zig/src/server/chat_generation.zig b/zig/src/server/chat_generation.zig index 5405ad1999a..c8ea9951627 100644 --- a/zig/src/server/chat_generation.zig +++ b/zig/src/server/chat_generation.zig @@ -75,6 +75,8 @@ pub const Generation = struct { lp: ?@import("logprob_parts.zig").Live = null, // the request asked for logprobs: its rows, copied with each round loop_stop: bool = false, // --loop-guard-stop: the engine ends the reply where the loop guard fires recover: bool = false, // a chat request with no forced tool or structure: an unclosed think block may be the answer + deadline_ns: ?i96 = null, // "deadline_s": when the server ends the reply itself + deadline_hit: bool = false, // it did: the engine was cancelled there; what it gave before its end still lands fn eos(g: *const Generation, t: u32) bool { return !g.ignore_eos and std.mem.indexOfScalar(u32, g.srv.eos, t) != null; @@ -264,6 +266,16 @@ pub const Generation = struct { g.srv.engine.cancel(g.id); g.cancel_sent = true; }; + // a client's cancel came first: the reply ends "cancelled", not at a deadline that passes afterwards + if (g.deadline_ns) |d| if (!g.deadline_hit and !g.cancel_sent and g.reason == null and nowNs(g.srv.io) >= d) { + m.mutex.lockUncancelable(m.io); + const ended_first = m.finished; // still draining a reply the engine already ended: it keeps that end + m.mutex.unlock(m.io); + if (ended_first) g.deadline_ns = null else { + g.deadline_hit = true; + g.srv.engine.cancel(g.id); // the engine ends the stream: its tokens and usage stay whole + } + }; if (chunk == null and @hasDecl(Gone, "beat")) { // queueing and a long prefill send nothing: a client that times out a silent stream would leave const now = nowNs(g.srv.io); @@ -276,6 +288,7 @@ pub const Generation = struct { } const tokens = chunk orelse continue; if (g.reason == null) try g.commit(tokens); + _ = m.unread.fetchSub(@intCast(tokens.len), .monotonic); // written out: the lane host may run it again } } @@ -283,13 +296,15 @@ pub const Generation = struct { const a = g.a; const m = g.box; if (!g.engine_done) g.drain(); - const ended: []const u8 = g.reason orelse switch (m.reason) { + const natural: []const u8 = g.reason orelse switch (m.reason) { .stop => "stop", .length => "length", .silence => return cx.other("the text engine returned a speech-only finish reason"), .cancelled => "cancelled", .failed => return cx.other(if (m.message.len > 0) try a.dupe(u8, m.message) else "the reply failed"), }; + // the server ended the reply at its deadline: a late token's EOS, stop string or cap never hides that + const ended = if (g.deadline_hit) "deadline" else natural; const stopped: ?u32 = if (g.loop_stop) m.stats.loop_period else null; const reason = if (stopped != null) @import("loop_stop.zig").finish_reason else ended; const finished_ns = nowNs(g.srv.io); diff --git a/zig/src/server/cli.zig b/zig/src/server/cli.zig index bfce1fad1e2..26c45d8f65b 100644 --- a/zig/src/server/cli.zig +++ b/zig/src/server/cli.zig @@ -12,12 +12,10 @@ pub const Kind = enum { pub const Flag = struct { name: []const u8, kind: Kind = .value, - /// argparse's choices; empty: any value of the flag's type. - choices: []const []const u8 = &.{}, + choices: []const []const u8 = &.{}, // argparse's choices; empty: any value of the flag's type. /// This binary honours the flag (and lists it in ``capabilities``); the rest are refused as unsupported. native: bool = false, - /// The values it honours when only some of the choices. - native_values: ?[]const []const u8 = null, + native_values: ?[]const []const u8 = null, // The values it honours when only some of the choices. /// The value names a file or folder: a config file's relative one is read from that file's folder (cli_config.zig). path: bool = false, }; @@ -85,6 +83,7 @@ pub const flags = [_]Flag{ .{ .name = "--thinking-reserve", .native = true }, .{ .name = "--loop-guard", .kind = .store_true, .native = true }, .{ .name = "--loop-guard-stop", .kind = .store_true, .native = true }, + .{ .name = "--tool-think-close", .kind = .store_true, .native = true }, .{ .name = "--no-drafts", .kind = .store_true, .native = true }, .{ .name = "--keep-warm", .native = true }, .{ .name = "--silence-floor-dbfs", .native = true }, @@ -163,6 +162,7 @@ pub const flags = [_]Flag{ .{ .name = "--recall-read-only", .kind = .store_true, .native = true }, // the native server's own: Cortheon's reasoning program and server-run web research for every chat request .{ .name = "--cortheon", .kind = .store_true, .native = true }, + .{ .name = "--execution-witness", .kind = .store_true, .native = true }, // GET /v1/execution/witness (witness.zig) }; /// The variables this binary honours as the Python engine does, then the CUDA build's or the Metal build's. @@ -228,6 +228,7 @@ pub const Args = struct { thinking_reserve: i64 = 0, loop_guard: bool = false, loop_guard_stop: bool = false, // the reply ends where the loop guard fires (implies --loop-guard) + tool_think_close: bool = false, // a required or named tool call closes thinking in time for the call no_drafts: bool = false, keep_warm: i64 = 900, // seconds the idle keepalive runs after the last request ends (0: off) idle_unload: i64 = 0, // seconds of idle past the last request before the engine closes (0: never; the next request reloads) @@ -246,6 +247,7 @@ pub const Args = struct { slide_drift_gate: bool = false, slide_graph: ?[]const u8 = null, // the Sliding Weights fact graph's file (null: memory only) parallel: []const u8 = "auto", + parallel_named: bool = false, // --parallel was on the command line: TENSORFOLD_PARALLEL then stays out of the way backend: []const u8 = "auto", device: ?u32 = null, segments: ?u32 = null, @@ -262,6 +264,7 @@ pub const Args = struct { master: []const u8 = "", master_port: u16 = 29551, policy: []const u8 = "", // every --policy joined by commas + execution_witness: bool = false, // a read-scoped snapshot of the engine, binary, text and settings that serve cortheon: bool = false, // Cortheon's program, research before building, and cortheon_search/cortheon_fetch run by the server vision: bool = false, // image input (GLM-5.3-Flash): data-URL image_url parts in user messages vision_urls: bool = false, // with --vision, public HTTPS image URLs too (media_fetch.zig) @@ -370,11 +373,9 @@ fn spillWith(u: *Usage, a: Allocator, out: Args) error{ Usage, OutOfMemory }!voi fn spills(args: Args) bool { return (args.spill_gib orelse 0) > 0; } - pub fn int(u: *Usage, a: Allocator, name: []const u8, v: []const u8) error{ Usage, OutOfMemory }!i64 { return std.fmt.parseInt(i64, std.mem.trim(u8, v, " "), 10) catch fail(u, a, "argument {s}: invalid int value: '{s}'", .{ name, v }); } - pub fn float(u: *Usage, a: Allocator, name: []const u8, v: []const u8) error{ Usage, OutOfMemory }!f64 { return @import("fields.zig").pyFloat(v) orelse fail(u, a, "argument {s}: invalid float value: '{s}'", .{ name, v }); } @@ -480,7 +481,7 @@ fn apply(a: Allocator, out: *Args, name: []const u8, value: ?[]const u8, u: *Usa } else if (is(name, "--decode-share")) { out.decode_share = try float(u, a, name, v); if (!(out.decode_share.? >= 0 and out.decode_share.? < 1)) return fail(u, a, "argument --decode-share: expected a share from 0 to under 1: '{s}'", .{v}); - } else if (is(name, "--prompt-seed")) out.prompt_seed = true else if (is(name, "--max-tokens")) out.max_tokens = try int(u, a, name, v) else if (is(name, "--temperature")) out.temperature = try float(u, a, name, v) else if (is(name, "--top-p")) out.top_p = try float(u, a, name, v) else if (is(name, "--top-k")) out.top_k = try int(u, a, name, v) else if (is(name, "--min-p")) out.min_p = try float(u, a, name, v) else if (is(name, "--instruct-sampling")) out.instruct_sampling = if (try @import("family_sampling.zig").pairsProblem(a, v)) |why| return fail(u, a, "argument {s}: {s}: '{s}'", .{ name, why, v }) else v else if (is(name, "--thinking")) out.thinking = true else if (is(name, "--no-thinking")) out.thinking = false else if (is(name, "--reasoning-effort")) out.reasoning_effort = v else if (is(name, "--thinking-budget")) out.thinking_budget = try int(u, a, name, v) else if (is(name, "--thinking-reserve")) out.thinking_reserve = try int(u, a, name, v) else if (is(name, "--loop-guard")) out.loop_guard = true else if (is(name, "--loop-guard-stop")) out.loop_guard_stop = true else if (is(name, "--drafter")) out.drafter = v else if (is(name, "--drafter-bits")) out.drafter_bits = @intCast(try int(u, a, name, v)) else if (is(name, "--record")) out.record = v else if (is(name, "--kv-cache")) out.kv_cache = v else if (is(name, "--prompt-precision")) out.prompt_precision = v else if (is(name, "--no-drafts")) out.no_drafts = true else if (is(name, "--keep-warm")) out.keep_warm = try int(u, a, name, v) else if (is(name, "--idle-unload")) out.idle_unload = try int(u, a, name, v) else if (is(name, "--compact-at")) { + } else if (is(name, "--prompt-seed")) out.prompt_seed = true else if (is(name, "--max-tokens")) out.max_tokens = try int(u, a, name, v) else if (is(name, "--temperature")) out.temperature = try float(u, a, name, v) else if (is(name, "--top-p")) out.top_p = try float(u, a, name, v) else if (is(name, "--top-k")) out.top_k = try int(u, a, name, v) else if (is(name, "--min-p")) out.min_p = try float(u, a, name, v) else if (is(name, "--instruct-sampling")) out.instruct_sampling = if (try @import("family_sampling.zig").pairsProblem(a, v)) |why| return fail(u, a, "argument {s}: {s}: '{s}'", .{ name, why, v }) else v else if (is(name, "--thinking")) out.thinking = true else if (is(name, "--no-thinking")) out.thinking = false else if (is(name, "--reasoning-effort")) out.reasoning_effort = v else if (is(name, "--thinking-budget")) out.thinking_budget = try int(u, a, name, v) else if (is(name, "--thinking-reserve")) out.thinking_reserve = try int(u, a, name, v) else if (is(name, "--loop-guard")) out.loop_guard = true else if (is(name, "--loop-guard-stop")) out.loop_guard_stop = true else if (is(name, "--tool-think-close")) out.tool_think_close = true else if (is(name, "--execution-witness")) out.execution_witness = true else if (is(name, "--drafter")) out.drafter = v else if (is(name, "--drafter-bits")) out.drafter_bits = @intCast(try int(u, a, name, v)) else if (is(name, "--record")) out.record = v else if (is(name, "--kv-cache")) out.kv_cache = v else if (is(name, "--prompt-precision")) out.prompt_precision = v else if (is(name, "--no-drafts")) out.no_drafts = true else if (is(name, "--keep-warm")) out.keep_warm = try int(u, a, name, v) else if (is(name, "--idle-unload")) out.idle_unload = try int(u, a, name, v) else if (is(name, "--compact-at")) { out.compact_auto = std.mem.eql(u8, v, "auto"); // each occurrence replaces both fields, so the last one wins out.compact_fraction = null; if (!out.compact_auto) { @@ -492,7 +493,7 @@ fn apply(a: Allocator, out: *Args, name: []const u8, value: ?[]const u8, u: *Usa const n = try int(u, a, name, v); if (n < 0) return fail(u, a, "argument --compact-keep: expected a token count from 0: '{s}'", .{v}); out.compact_keep = @intCast(n); - } else if (is(name, "--compact-memory")) out.compact_memory = v else if (is(name, "--slide")) out.slide = true else if (is(name, "--slide-drift-gate")) out.slide_drift_gate = true else if (is(name, "--slide-graph")) out.slide_graph = v else if (is(name, "--parallel")) out.parallel = v else if (is(name, "--backend")) out.backend = v else if (is(name, "--cortheon")) out.cortheon = true else if (is(name, "--vision")) out.vision = true else if (is(name, "--vision-urls")) out.vision_urls = true else if (is(name, "--vision-pdf")) out.vision_pdf = true else if (is(name, "--vision-max-images")) { + } else if (is(name, "--compact-memory")) out.compact_memory = v else if (is(name, "--slide")) out.slide = true else if (is(name, "--slide-drift-gate")) out.slide_drift_gate = true else if (is(name, "--slide-graph")) out.slide_graph = v else if (is(name, "--parallel")) out.parallel, out.parallel_named = .{ v, true } else if (is(name, "--backend")) out.backend = v else if (is(name, "--cortheon")) out.cortheon = true else if (is(name, "--vision")) out.vision = true else if (is(name, "--vision-urls")) out.vision_urls = true else if (is(name, "--vision-pdf")) out.vision_pdf = true else if (is(name, "--vision-max-images")) { const n = try int(u, a, name, v); if (n < 1 or n > 64) return fail(u, a, "argument --vision-max-images: expected 1 to 64 images: '{s}'", .{v}); out.vision_max_images = @intCast(n); @@ -583,7 +584,6 @@ pub fn request(a: Allocator, dir: []const u8, model_type: []const u8, args: Args /// ``capabilities --json`` (cli_capabilities.zig): the engine side, then the table's native flags and variables. pub const Engines = @import("cli_capabilities.zig").Engines; pub const capabilities = @import("cli_capabilities.zig").capabilities; - /// The CUDA build's and GPU engine's flag parsers (cli_gpu_flags.zig). pub const cudaFlag = @import("cli_gpu_flags.zig").cudaFlag; pub const gpuFlag = @import("cli_gpu_flags.zig").gpuFlag; diff --git a/zig/src/server/deferred_tools.zig b/zig/src/server/deferred_tools.zig new file mode 100644 index 00000000000..94eb44e9e87 --- /dev/null +++ b/zig/src/server/deferred_tools.zig @@ -0,0 +1,101 @@ +//! Deferred tools (``defer_loading``) and the ``tool_reference`` parts a tool result loads them with. +const std = @import("std"); +const json = @import("json"); +const errors = @import("errors.zig"); +const Value = json.Value; +const Cx = errors.Cx; +const Allocator = std.mem.Allocator; +const textPart = @import("messages.zig").textPart; + +/// A template that names both fields renders them itself (GLM-5.3); any other gets the text form. +pub fn native(source: []const u8) bool { + return std.mem.indexOf(u8, source, "tool_reference") != null and std.mem.indexOf(u8, source, "defer_loading") != null; +} + +/// A tool's function object: an OpenAI ``{"function": {...}}`` entry's, or a bare spec. +fn function(tool: Value) ?Value { + if (tool != .object) return null; + const inner = tool.get("function") orelse return tool; + return if (inner == .object) inner else null; +} + +fn deferred(tool: Value) bool { + const f = function(tool) orelse return false; + const flag = f.get("defer_loading") orelse return false; + return flag == .bool and flag.bool; +} + +/// The tools a template that cannot read ``defer_loading`` lists: the deferred ones left out, none as null. +pub fn shown(a: Allocator, tools: ?Value) Allocator.Error!?Value { + const list = tools orelse return null; + if (list != .array) return tools; + for (list.array) |tool| { + if (deferred(tool)) break; + } else return tools; + var kept: std.ArrayList(Value) = .empty; + for (list.array) |tool| if (!deferred(tool)) try kept.append(a, tool); + return if (kept.items.len > 0) Value{ .array = kept.items } else null; +} + +fn spec(tools: ?Value, name: []const u8) ?Value { + const list = tools orelse return null; + if (list != .array) return null; + for (list.array) |tool| { + const f = function(tool) orelse continue; + const n = f.get("name") orelse continue; + if (n == .string and std.mem.eql(u8, n.string, name)) return f; + } + return null; +} + +/// A referenced tool as text: its name, description and parameters as a template's ``tojson`` writes them. +fn spelled(a: Allocator, f: Value) Allocator.Error![]const u8 { + const o = try json.newObject(a); + for ([_][]const u8{ "name", "description", "parameters" }) |key| if (f.get(key)) |v| try o.put(a, key, v); + return json.stringify(a, .{ .object = o }, .{ .ascii = false }); +} + +fn hasReference(content: Value) bool { + if (content != .array) return false; + for (content.array) |part| if (part.typeIs("tool_reference")) return true; + return false; +} + +/// Every ``tool_reference`` checked against all offered tools; a template that can't read one gets its spec as text. +pub fn resolve(cx: *Cx, messages: Value, tools: ?Value, template_reads: bool) errors.Refused!Value { + if (messages != .array) return messages; + for (messages.array) |m| { + if (m.get("content")) |c| if (hasReference(c)) break; + } else return messages; + const a = cx.a; + const out = try a.dupe(Value, messages.array); + for (out) |*slot| { + const content = slot.get("content") orelse continue; + if (!hasReference(content)) continue; + var parts: std.ArrayList(Value) = .empty; + var texts: std.ArrayList([]const u8) = .empty; + for (content.array) |part| { + if (!part.typeIs("tool_reference")) { + try parts.append(a, part); + if (part.typeIs("text")) if (part.get("text")) |t| if (t == .string) try texts.append(a, t.string); + continue; + } + const n = part.get("name") orelse Value.null; + if (n != .string or n.string.len == 0) return cx.refuse("a tool_reference part must name a tool"); + const name = n.string; + const f = spec(tools, name) orelse return cx.fail(.request, "Tool reference '{s}' not found in available tools", .{name}); + if (template_reads) { + try parts.append(a, part); + continue; + } + const text = try spelled(a, f); + try parts.append(a, try textPart(a, text)); + try texts.append(a, text); + } + const copy = try json.copyObject(a, slot.object); + const all_text = texts.items.len == parts.items.len; + try copy.put(a, "content", if (!template_reads and all_text) .{ .string = try std.mem.join(a, "\n", texts.items) } else .{ .array = parts.items }); + slot.* = .{ .object = copy }; + } + return .{ .array = out }; +} diff --git a/zig/src/server/deferred_tools_test.zig b/zig/src/server/deferred_tools_test.zig new file mode 100644 index 00000000000..9f132bed4e6 --- /dev/null +++ b/zig/src/server/deferred_tools_test.zig @@ -0,0 +1,264 @@ +//! Deferred tools and tool references from the Messages translation through normalization, templates and the routes. +const std = @import("std"); +const api = @import("engine_api"); +const json = @import("json"); +const errors = @import("errors.zig"); +const messages = @import("messages.zig"); +const model_text = @import("model_text.zig"); +const deferred_tools = @import("deferred_tools.zig"); +const translate = @import("anthropic_translate.zig").translate; +const HfText = @import("hf_text.zig").HfText; +const Server = @import("server.zig").Server; +const exchange = @import("late_system_test.zig").exchange; +const family = @import("thinking_family_fixture.zig"); +const Value = json.Value; +const Cx = errors.Cx; +const t = std.testing; + +const glm = .{ @embedFile("fixtures/thinking/glm53.jinja"), "glm5_next" }; +const config = @embedFile("fixtures/thinking/glm53-tokenizer_config.json"); +const plain = "{% if tools %}{{ tools | tojson }}{% endif %}{% for m in messages %}<|{{ m.role }}|>{{ m.content }}" ++ + "{% if m.tool_calls %}{{ m.tool_calls | tojson }}{% endif %}{% endfor %}{% if add_generation_prompt %}<|assistant|>{% endif %}"; +const off_text = "{\"name\": \"off\", \"description\": \"E\", \"parameters\": {\"type\": \"object\"}}"; +const tools_src = + \\[{"type":"function","function":{"name":"on","description":"D","parameters":{"type":"object"}}}, + \\ {"type":"function","function":{"name":"off","description":"E","parameters":{"type":"object"},"defer_loading":true}}] +; + +fn parse(a: std.mem.Allocator, text: []const u8) !Value { + return (try json.parse(a, text)).ok; +} + +fn str(a: std.mem.Allocator, v: Value) ![]const u8 { + return json.stringify(a, v, .{ .ascii = false, .compact = true }); +} + +test "deferred tools: Messages translation carries defer_loading and tool_reference, and refuses what Anthropic does" { + var arena: std.heap.ArenaAllocator = .init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var cx: Cx = .{ .a = a }; + const head = "{\"model\":\"m\",\"max_tokens\":16,\"messages\":[{\"role\":\"user\",\"content\":\"H\"}],\"tools\":["; + const chat = try translate(&cx, try parse(a, + \\{"model":"m","max_tokens":16,"tools":[{"name":"on","input_schema":{"type":"object"}}, + \\ {"name":"off","description":"E","input_schema":{"type":"object"},"defer_loading":true}], + \\ "messages":[{"role":"user","content":"H"},{"role":"assistant","content":[{"type":"tool_use","id":"c1","name":"on","input":{}}]}, + \\ {"role":"user","content":[{"type":"tool_result","tool_use_id":"c1","content":[{"type":"text","text":"found"},{"type":"tool_reference","tool_name":"off"}]}]}]} + ), false); + try t.expectEqualStrings( + \\[{"type":"function","function":{"name":"on","parameters":{"type":"object"}}},{"type":"function","function":{"name":"off","parameters":{"type":"object"},"description":"E","defer_loading":true}}] + , try str(a, chat.get("tools").?)); + try t.expectEqualStrings( + \\{"role":"tool","tool_call_id":"c1","content":[{"type":"text","text":"found"},{"type":"tool_reference","name":"off"}]} + , try str(a, chat.get("messages").?.array[2])); + // defer_loading false is the default, so the request is main's own + const off = try translate(&cx, try parse(a, head ++ "{\"name\":\"t\",\"input_schema\":{},\"defer_loading\":false}]}"), false); + const bare = try translate(&cx, try parse(a, head ++ "{\"name\":\"t\",\"input_schema\":{}}]}"), false); + try t.expectEqualStrings(try str(a, bare), try str(a, off)); + const refused = [_][2][]const u8{ + .{ "{\"name\":\"t\",\"input_schema\":{},\"defer_loading\":\"yes\"}]}", "tool.defer_loading must be a boolean" }, + .{ "{\"name\":\"t\",\"input_schema\":{},\"defer_loading\":true}]}", "At least one tool must have defer_loading=false. All tools cannot be deferred." }, + .{ "{\"type\":\"tool_search_tool_regex_20251119\",\"name\":\"tool_search_tool_regex\"}]}", "only client-defined function tools are supported" }, + }; + inline for (refused) |case| { + try t.expectError(error.Refused, translate(&cx, try parse(a, head ++ case[0]), false)); + try t.expectEqualStrings(case[1], cx.message); + try t.expectEqual(@as(u16, 400), cx.status()); + } + const nameless = try parse(a, + \\{"model":"m","max_tokens":16,"tools":[{"name":"on","input_schema":{}}],"messages":[{"role":"user","content":[{"type":"tool_result","tool_use_id":"c1","content":[{"type":"tool_reference"}]}]}]} + ); + try t.expectError(error.Refused, translate(&cx, nameless, false)); + try t.expectEqualStrings("tool_reference.tool_name must be a nonempty string", cx.message); +} + +test "deferred tools: normalization keeps a tool result's references on both passes and refuses one elsewhere" { + var arena: std.heap.ArenaAllocator = .init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var cx: Cx = .{ .a = a }; + const once = try messages.normalize(&cx, try parse(a, + \\[{"role":"user","content":"H"},{"role":"tool","tool_call_id":"c1","content":[{"type":"text","text":"a"},{"type":"tool_reference","name":"off","x":1}]}, + \\ {"role":"tool","tool_call_id":"c2","content":[{"type":"text","text":"b"},{"type":"text","text":"c"}]}] + ), "system", false); + const want = + \\[{"role":"user","content":"H"},{"role":"tool","tool_call_id":"c1","content":[{"type":"text","text":"a"},{"type":"tool_reference","name":"off"}]},{"role":"tool","tool_call_id":"c2","content":"bc"}] + ; + try t.expectEqualStrings(want, try str(a, once)); + try t.expectEqualStrings(want, try str(a, try messages.normalize(&cx, once, "system", false))); + for ([_][]const u8{ + \\[{"role":"tool","tool_call_id":"c1","content":[{"type":"tool_reference"}]}] + , + \\[{"role":"tool","tool_call_id":"c1","content":[{"type":"tool_reference","name":""}]}] + , + \\[{"role":"user","content":[{"type":"tool_reference","name":"off"}]}] + }, [_][]const u8{ "a tool_reference part must name a tool", "a tool_reference part must name a tool", "this server accepts text parts only; image, audio and video inputs are unsupported" }) |raw, message| { + try t.expectError(error.Refused, messages.normalize(&cx, try parse(a, raw), "system", false)); + try t.expectEqualStrings(message, cx.message); + } +} + +test "deferred tools: references resolve against every offered tool, as text where the template cannot read them" { + var arena: std.heap.ArenaAllocator = .init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var cx: Cx = .{ .a = a }; + const tools = try parse(a, tools_src); + const history = try parse(a, + \\[{"role":"user","content":"H"},{"role":"tool","tool_call_id":"c1","content":[{"type":"text","text":"found"},{"type":"tool_reference","name":"off"}]}] + ); + const kept = try deferred_tools.resolve(&cx, history, tools, true); + try t.expectEqualStrings(try str(a, history), try str(a, kept)); + const spelled = try deferred_tools.resolve(&cx, history, tools, false); + try t.expectEqualStrings("found\n" ++ off_text, spelled.array[1].get("content").?.string); + try t.expectEqualStrings("H", spelled.array[0].get("content").?.string); + // a reference to a tool the request never offered is refused by name, as Anthropic refuses it + const unknown = try parse(a, + \\[{"role":"tool","tool_call_id":"c1","content":[{"type":"tool_reference","name":"missing"}]}] + ); + for ([_]bool{ true, false }) |reads| { + try t.expectError(error.Refused, deferred_tools.resolve(&cx, unknown, tools, reads)); + try t.expectEqualStrings("Tool reference 'missing' not found in available tools", cx.message); + try t.expectEqual(errors.Kind.request, cx.kind); + } + const plain_history = try parse(a, + \\[{"role":"user","content":"H"},{"role":"tool","tool_call_id":"c1","content":"done"}] + ); + try t.expectEqual(plain_history.array.ptr, (try deferred_tools.resolve(&cx, plain_history, tools, false)).array.ptr); + const listed = (try deferred_tools.shown(a, tools)).?; + try t.expectEqual(@as(usize, 1), listed.array.len); + try t.expectEqualStrings("on", listed.array[0].get("function").?.get("name").?.string); + const loaded = try parse(a, "[{\"type\":\"function\",\"function\":{\"name\":\"on\",\"defer_loading\":false}}]"); + try t.expectEqual(loaded.array.ptr, (try deferred_tools.shown(a, loaded)).?.array.ptr); + try t.expect(try deferred_tools.shown(a, .{ .array = tools.array[1..] }) == null); +} + +/// A chat as the routes render it: normalized, references resolved, normalized again, call arguments as objects. +fn rendered(cx: *Cx, text: model_text.Text, raw: []const u8, tools: Value, generation: bool) ![]const u8 { + const once = try messages.normalize(cx, try parse(cx.a, raw), "system", false); + const resolved = try deferred_tools.resolve(cx, once, tools, text.deferred_native); + const ready = try messages.toolArguments(cx, try messages.normalize(cx, resolved, "system", false)); + var problem: []const u8 = ""; + const out = text.render(cx.a, ready, .{ .tools = tools, .add_generation_prompt = generation }, &problem) catch |e| { + std.debug.print("render: {s}\n", .{problem}); + return e; + }; + return out.text; +} + +test "deferred tools: GLM-5.3 renders them its own way, others get the spec at the reference, and earlier text is kept" { + var arena: std.heap.ArenaAllocator = .init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const call = "[{\"role\":\"user\",\"content\":\"H\"},{\"role\":\"assistant\",\"content\":\"\",\"tool_calls\":[{\"id\":\"c1\"," ++ + "\"type\":\"function\",\"function\":{\"name\":\"on\",\"arguments\":\"{}\"}}]}"; + const loaded = call ++ ",{\"role\":\"tool\",\"tool_call_id\":\"c1\",\"content\":[{\"type\":\"tool_reference\",\"name\":\"off\"}]}]"; + for ([_][2][]const u8{ glm, .{ plain, "plain_test" } }, [_]bool{ true, false }) |case, native| { + var f = try family.init(t.allocator, t.io, case[0], config, case[1]); + defer f.deinit(); + var problem: []const u8 = ""; + const hf = try HfText.load(t.allocator, t.io, f.path, null, a, &problem); + defer hf.deinit(); + const text = hf.text(); + try t.expectEqual(native, text.deferred_native); + var cx: Cx = .{ .a = a }; + const tools = try parse(a, tools_src); + const without = try rendered(&cx, text, call ++ "]", .{ .array = tools.array[0..1] }, false); + // a deferred tool is out of the prompt until a reference loads it, which leaves the text before it as it was + try t.expectEqualStrings(without, try rendered(&cx, text, call ++ "]", tools, false)); + try t.expectEqualStrings(without, (try rendered(&cx, text, call ++ "]", tools, true))[0..without.len]); + const got = try rendered(&cx, text, loaded, tools, true); + try t.expect(std.mem.startsWith(u8, got, without)); + try t.expect(std.mem.indexOf(u8, without, "\"off\"") == null); + const after = got[without.len..]; + if (native) { + try t.expect(std.mem.indexOf(u8, after, "\n" ++ off_text ++ "\n") != null); + } else { + try t.expect(std.mem.indexOf(u8, after, "<|tool|>" ++ off_text ++ "<|assistant|>") != null); + } + } +} + +const Script = struct { + reply: []const u32 = &.{}, + seen: bool = false, + count: usize = 0, + prompt: [8192]u32 = undefined, + + fn engine(s: *Script) api.Engine { + return .{ .ctx = s, .vtable = &.{ .info = info, .submit = submit, .cancel = cancel, .status = status, .memory = memory } }; + } + fn info(_: *anyopaque) api.Info { + return .{ .context_window = 65536 }; + } + fn submit(ctx: *anyopaque, id: api.Id, request: *const api.Request, sink: api.Sink) api.SubmitError!void { + const s: *Script = @ptrCast(@alignCast(ctx)); + s.seen = true; + s.count = request.prompt.len; + @memcpy(s.prompt[0..s.count], request.prompt); + sink.event(sink.ctx, id, &.{ .prefilled = 0 }); + for (s.reply) |token| sink.event(sink.ctx, id, &.{ .tokens = &.{token} }); + sink.event(sink.ctx, id, &.{ .finished = .{ .reason = .stop } }); + } + fn cancel(_: *anyopaque, _: api.Id) void {} + fn status(_: *anyopaque, out: *api.Status, _: []u32) void { + out.* = .{}; + } + fn memory(_: *anyopaque, _: bool) ?api.Memory { + return null; + } +}; + +const request_head = + \\{"model":"m","max_tokens":256,"tools":[{"name":"on","description":"D","input_schema":{"type":"object"}}, + \\ {"name":"off","description":"E","input_schema":{"type":"object"},"defer_loading":true}], + \\ "messages":[{"role":"user","content":"H"},{"role":"assistant","content":[{"type":"tool_use","id":"c1","name":"on","input":{}}]}, + \\ {"role":"user","content":[{"type":"tool_result","tool_use_id":"c1","content":[{"type":"tool_reference","tool_name":" +; + +test "deferred tools: a Messages request loads a tool by reference, count_tokens agrees, and its later call is returned" { + var arena: std.heap.ArenaAllocator = .init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + // GLM-5.3 lists the translated spec in its own key order; the text form names, describes, then gives parameters + const glm_text = "\n{\"name\": \"off\", \"parameters\": {\"type\": \"object\"}, \"description\": \"E\"}\n"; + for ([_][2][]const u8{ glm, .{ plain, "plain_test" } }, [_][]const u8{ glm_text, off_text }) |case, loaded| { + var f = try family.init(t.allocator, t.io, case[0], config, case[1]); + defer f.deinit(); + var problem: []const u8 = ""; + const hf = try HfText.load(t.allocator, t.io, f.path, null, a, &problem); + defer hf.deinit(); + const text = hf.text(); + var script: Script = .{ .reply = try text.encode(a, "offxv", false) }; + const srv = try Server.init(t.allocator, t.io, script.engine(), text, .{ .served_name = "m", .model_ids = &.{"m"}, .use_drafts = false }, null); + defer srv.deinit(); + const body = request_head ++ "off\"}]}]}]}"; + const sent = try exchange(srv, "/v1/messages", body); + defer t.allocator.free(sent.body); + try t.expectEqual(@as(u16, 200), sent.status); + const prompt = try text.decode(a, script.prompt[0..script.count]); + try t.expectEqual(@as(usize, 1), std.mem.count(u8, prompt, loaded)); + try t.expectEqual(@as(usize, 1), std.mem.count(u8, prompt, "\"off\"")); + try t.expect(std.mem.indexOf(u8, prompt, "defer_loading") == null); + const reply = try parse(a, sent.body); + try t.expectEqualStrings("tool_use", reply.get("stop_reason").?.string); + const use = reply.get("content").?.array[0]; + try t.expectEqualStrings("tool_use", use.get("type").?.string); + try t.expectEqualStrings("off", use.get("name").?.string); + try t.expectEqualStrings("{\"x\":\"v\"}", try str(a, use.get("input").?)); + const counted = try exchange(srv, "/v1/messages/count_tokens", body); + defer t.allocator.free(counted.body); + try t.expectEqual(@as(u16, 200), counted.status); + try t.expectEqual(@as(?i64, @intCast(script.count)), (try parse(a, counted.body)).get("input_tokens").?.int64()); + script.seen = false; + for ([_][]const u8{ "/v1/messages", "/v1/messages/count_tokens" }) |path| { + const missing = try exchange(srv, path, request_head ++ "missing\"}]}]}]}"); + defer t.allocator.free(missing.body); + try t.expectEqual(@as(u16, 400), missing.status); + const problem_reply = (try parse(a, missing.body)).get("error").?; + try t.expectEqualStrings("invalid_request_error", problem_reply.get("type").?.string); + try t.expectEqualStrings("Tool reference 'missing' not found in available tools", problem_reply.get("message").?.string); + } + try t.expect(!script.seen); + } +} diff --git a/zig/src/server/engines.zig b/zig/src/server/engines.zig index 7aa4f7f8f57..e7e199d6cd5 100644 --- a/zig/src/server/engines.zig +++ b/zig/src/server/engines.zig @@ -13,7 +13,7 @@ pub const Opened = api.Opened; /// Refuse malformed settings before resolving checkpoints and again before an idle reload. pub fn environment(a: Allocator, args: cli.Args) !?[]const u8 { const settings = @import("sys").environment; - var flags: settings.Flags = .{ .slide = args.slide, .device = args.device, .segments = args.segments, .hooks = @import("build_options").slide_test_hooks }; + var flags: settings.Flags = .{ .slide = args.slide, .device = args.device, .segments = args.segments, .hooks = @import("build_options").slide_test_hooks, .parallel_named = args.parallel_named }; for (native.backends) |backend| { if (std.mem.eql(u8, backend, "cuda")) flags.cuda = true; if (std.mem.eql(u8, backend, "metal")) flags.metal = true; diff --git a/zig/src/server/grammar.zig b/zig/src/server/grammar.zig index 9a542827e0b..533300ce6ae 100644 --- a/zig/src/server/grammar.zig +++ b/zig/src/server/grammar.zig @@ -5,6 +5,7 @@ const json = @import("json"); const errors = @import("errors.zig"); const pyrepr = @import("pyrepr.zig"); const tool_specs = @import("tool_specs.zig"); +const structural_tag = @import("structural_tag.zig"); const Value = json.Value; const Cx = errors.Cx; @@ -33,6 +34,11 @@ fn bareMessage(full: []const u8) []const u8 { } fn schemaText(cx: *Cx, raw: Value, where: []const u8) errors.Refused![]const u8 { + return json.stringify(cx.a, try schemaValue(cx, raw, where), .{ .ascii = false }); +} + +/// A schema field as its object: JSON text parsed, true as {}, anything else but an object refused. +pub fn schemaValue(cx: *Cx, raw: Value, where: []const u8) errors.Refused!Value { var value = raw; if (raw == .string) value = switch (try json.parseText(cx.a, raw.string)) { .ok => |v| v, @@ -40,7 +46,7 @@ fn schemaText(cx: *Cx, raw: Value, where: []const u8) errors.Refused![]const u8 }; if (value == .bool) value = if (value.bool) .{ .object = try json.newObject(cx.a) } else .null; if (value != .object) return cx.fail(.request, "{s} must be a JSON schema object", .{where}); - return json.stringify(cx.a, value, .{ .ascii = false }); + return value; } fn text(cx: *Cx, v: Value, where: []const u8) errors.Refused![]const u8 { @@ -76,6 +82,7 @@ pub fn spec(cx: *Cx, body: Value) errors.Refused!?Spec { if (js == null or js.? != .object or js.?.field("schema") == null) return cx.refuse("response_format json_schema needs json_schema.schema (a JSON schema object)"); return .{ .kind = .json_schema, .text = try schemaText(cx, js.?.get("schema").?, "response_format json_schema.schema") }; } + if (kind != null and kind.? == .string and std.mem.eql(u8, name, "structural_tag")) return .{ .kind = .structural_tag, .text = try structural_tag.build(cx, rf) }; if (!(kind != null and kind.? == .string and std.mem.eql(u8, name, "text"))) return cx.fail(.request, "response_format type must be text, json_object or json_schema, not {s}", .{try pyrepr.repr(cx.a, kind)}); } diff --git a/zig/src/server/hf_text.zig b/zig/src/server/hf_text.zig index e1b0022d17a..204046b33ca 100644 --- a/zig/src/server/hf_text.zig +++ b/zig/src/server/hf_text.zig @@ -287,7 +287,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, .ctx = t, .vtable = &.{ + 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 = &.{ .encode = encodeFn, .decode = decodeFn, .token_id = tokenIdFn, diff --git a/zig/src/server/idle_unload.zig b/zig/src/server/idle_unload.zig index 4200b07144b..3f5a3b9e31c 100644 --- a/zig/src/server/idle_unload.zig +++ b/zig/src/server/idle_unload.zig @@ -273,6 +273,7 @@ pub fn reload(m: *Manager, srv: *server_mod.Server, reply: Allocator, problem_ou m.last_activity_ns = now(m.io); srv.engine = opened.engine; srv.info = info; + if (srv.witness) |w| w.bump(); // the new engine's facts and its epoch publish under the same lock srv.load.attach(opened.engine); // only the engine that serves publishes: a failed candidate never attached srv.keepalive = keepalive; m.re.replace(m.re.ctx, opened, scratch); // shutdown closes this engine, not the long-gone startup one diff --git a/zig/src/server/imprint_routes.zig b/zig/src/server/imprint_routes.zig index ad08b0d5fc4..d0d3c4d98cd 100644 --- a/zig/src/server/imprint_routes.zig +++ b/zig/src/server/imprint_routes.zig @@ -86,6 +86,7 @@ fn reply(a: Allocator, ask: *const Ask) !Value { .where => "imprint.resume", .load => "imprint.load", .forget => "imprint.forget", + .flush => "prompt_cache.flush", } }); try o.put(a, "disk", .{ .bool = ask.disk }); if (ask.op == .forget) { diff --git a/zig/src/server/mailbox.zig b/zig/src/server/mailbox.zig index dcff5cef608..df3aa90b668 100644 --- a/zig/src/server/mailbox.zig +++ b/zig/src/server/mailbox.zig @@ -11,6 +11,7 @@ pub const Mailbox = struct { audio: usize = 0, tokens: std.ArrayList(u32) = .empty, chunks: std.ArrayList(usize) = .empty, // where each round's tokens end + unread: std.atomic.Value(u32) = .init(0), // tokens landed and not yet written to the client (Request.unread) rows: std.ArrayList(api.LogprobRow) = .empty, // one a token of `tokens`, for requests with logprobs prompt_rows: ?[]api.LogprobRow = null, // one a prompt token after the first, for requests with prompt_logprobs cached: ?u32 = null, @@ -34,10 +35,10 @@ pub const Mailbox = struct { }, .logprobs => |r| m.rows.appendSlice(m.gpa, r) catch {}, .prompt_logprobs => |r| m.prompt_rows = m.gpa.dupe(api.LogprobRow, r) catch null, - .tokens => |t| { - m.tokens.appendSlice(m.gpa, t) catch {}; + .tokens => |t| if (m.tokens.appendSlice(m.gpa, t)) |_| { + _ = m.unread.fetchAdd(@intCast(t.len), .monotonic); // only tokens the reader will take and count down m.chunks.append(m.gpa, m.tokens.items.len) catch {}; - }, + } else |_| {}, .audio => |n| m.audio = n, .finished => |f| { m.finished = true; diff --git a/zig/src/server/main.zig b/zig/src/server/main.zig index 13435934f36..d7d3b3d17b9 100644 --- a/zig/src/server/main.zig +++ b/zig/src/server/main.zig @@ -10,6 +10,7 @@ const engines = @import("engines.zig"); const serve = @import("serve.zig"); const hf_text = @import("hf_text.zig"); const model_text = @import("model_text.zig"); +const witness = @import("witness.zig"); const startup = @import("startup.zig"); const slide_cli = @import("slide_cli.zig"); const slide_key = @import("slide_key.zig"); @@ -33,7 +34,7 @@ const usage_line = "usage: tensorfold serve [-h] [--config FILE.toml] [--host HO " [--recall-gib RECALL_GIB] [--recall-read-only] [--max-tokens MAX_TOKENS]" ++ " [--temperature TEMPERATURE] [--top-p TOP_P] [--top-k TOP_K] [--min-p MIN_P] [--prompt-seed]" ++ " [--thinking | --no-thinking] [--reasoning-effort {low,medium,high,xhigh}]" ++ - " [--thinking-budget THINKING_BUDGET] [--thinking-reserve THINKING_RESERVE] [--loop-guard] [--loop-guard-stop] [--no-drafts]" ++ + " [--thinking-budget THINKING_BUDGET] [--thinking-reserve THINKING_RESERVE] [--loop-guard] [--loop-guard-stop] [--tool-think-close] [--no-drafts]" ++ " [--drafter DRAFTER]" ++ " [--drafter-bits {0,4}] [--record RECORD] [--keep-warm SECONDS] [--idle-unload SECONDS]" ++ " [--silence-floor-dbfs DBFS] [--silence-seconds SECONDS]" ++ @@ -44,7 +45,7 @@ const usage_line = "usage: tensorfold serve [-h] [--config FILE.toml] [--host HO " [--register-redraw-st ST] [--register-redraw-high PERCENT] [--register-high-hz HZ]" ++ " [--compact-at COMPACT_AT] [--compact-keep COMPACT_KEEP]" ++ " [--compact-memory COMPACT_MEMORY] [--slide] [--slide-graph SLIDE_GRAPH] [--slide-drift-gate] [--parallel PARALLEL]" ++ - " [--cortheon] [--no-update-check] [--backend {auto,mlx,cuda}] [--device DEVICE]" ++ + " [--cortheon] [--execution-witness] [--no-update-check] [--backend {auto,mlx,cuda}] [--device DEVICE]" ++ " [--segments SEGMENTS] model\n"; const not_lanes = "--recall drafts from a record in the lane engine's rounds, " ++ "which this model's engine does not run: serve it without --recall, --recall-dir, " ++ @@ -139,6 +140,8 @@ pub fn main(init: std.process.Init) !u8 { }; if (expanded.path) |path| log.line("config: {s} ({d} options)", .{ path, expanded.options }); if (try engines.environment(a, args)) |why| return fail(why); + // TENSORFOLD_PARALLEL names the default lanes once the environment check passed; the flag wins. + if (try @import("sys").environment.parallel(if (args.parallel_named) args.parallel else null, @import("sys").environment.Process.get(.{}, "TENSORFOLD_PARALLEL"))) |text| args.parallel = text; const receipt = @import("core").startup_receipt; receipt.enable(io, entry, try @import("sys").environment.read(bool, "TF_STARTUP_RECEIPT", false)); defer receipt.disable(); @@ -148,6 +151,10 @@ pub fn main(init: std.process.Init) !u8 { return 2; } api.prompt_cache.status.named.store(args.dashboard, .monotonic); // before any store keeps a state + if (witness.refusal(args, witness.keysNamed(a, args, init.environ_map.get("TENSORFOLD_API_KEY") orelse ""))) |why| { + std.debug.print("tensorfold: {s}\n", .{why}); + return 2; + } if (args.vision) for (@import("core").picture.runtime.warnings(io, a)) |warning| { if (warning) |message| log.line("warning: {s}", .{message}); }; @@ -186,6 +193,11 @@ pub fn main(init: std.process.Init) !u8 { var text_arena: std.heap.ArenaAllocator = .init(gpa); // the text's problem, written on its own thread defer text_arena.deinit(); var text_problem: []const u8 = ""; + // --execution-witness: the running binary and the text files' stamps before the load, hashed once serving is ready + const witness_binary = if (args.execution_witness) witness.openBinary(a, io) else null; + defer if (witness_binary) |b| b.close(io); + const witness_text = if (args.execution_witness) witness.stampText(gpa, io, dir, args.chat_template) else null; + defer if (witness_text) |w| w.deinit(); const up = startup.both(io, loadText, .{ gpa, io, dir, args.chat_template, model_type, text_arena.allocator(), &text_problem }, openEngine, .{ a, gpa, io, dir, model_type, &args, draft.automatic, &problem }) catch |e| { if (text_problem.len > 0) return fail(text_problem); if (problem.len > 0) return fail(problem); // an engine that failed after saying why @@ -226,6 +238,8 @@ pub fn main(init: std.process.Init) !u8 { .identity = engines.identity(a, args), .forget_fail = if (comptime @import("build_options").slide_test_hooks) try forgetFail(init.environ_map) else 0, .tool_id_key = if (tool_ids) |*key| key else null, + .witness_binary = witness_binary, + .witness_text = witness_text, }); } diff --git a/zig/src/server/messages.zig b/zig/src/server/messages.zig index 15d9f623a2f..7489ee123de 100644 --- a/zig/src/server/messages.zig +++ b/zig/src/server/messages.zig @@ -103,8 +103,10 @@ pub fn normalizeWith(cx: *Cx, messages: ?Value, late_system: []const u8, needs_u var item: *json.Object = message.object; if (content != null and content.? == .array) { var text: std.ArrayList(u8) = .empty; - var parts: std.ArrayList(Value) = .empty; // with images: text and image parts in order + var parts: std.ArrayList(Value) = .empty; // with images or in a tool result: text and other parts in order + var has_reference = false; var has_image = false; + const tool = std.mem.eql(u8, role.?.string, "tool"); for (content.?.array, 0..) |part, part_index| { const kind = if (part == .object and part.get("type") != null and part.get("type").? == .string) part.get("type").?.string else ""; // an image part, or one this normalization already wrote with the template's type (it runs twice) @@ -135,19 +137,29 @@ pub fn normalizeWith(cx: *Cx, messages: ?Value, late_system: []const u8, needs_u has_image = true; continue; } + if (tool and std.mem.eql(u8, kind, "tool_reference")) { + const name = part.get("name") orelse Value.null; + if (name != .string or name.string.len == 0) return cx.refuse("a tool_reference part must name a tool"); + const ref = try json.newObject(cx.a); + try ref.put(cx.a, "type", .{ .string = "tool_reference" }); + try ref.put(cx.a, "name", name); + try parts.append(cx.a, .{ .object = ref }); + has_reference = true; + continue; + } if (!std.mem.eql(u8, kind, "text") or fields.hasMedia(part)) return cx.refuse(if (media.videos) "content parts must be text, image_url or video_url; audio is unsupported" else if (images) "content parts must be text or image_url; audio and video inputs are unsupported" else "this server accepts text parts only; image, audio and video inputs are unsupported"); const t = part.get("text") orelse return cx.refuse("a text content part must contain a text string"); if (t != .string) return cx.refuse("a text content part must contain a text string"); if (media.native_deepseek and part_index > 0) try text.appendSlice(cx.a, "\n\n"); try text.appendSlice(cx.a, t.string); - if (images) { + if (images or tool) { const tp = try json.newObject(cx.a); try tp.put(cx.a, "type", .{ .string = "text" }); try tp.put(cx.a, "text", t); try parts.append(cx.a, .{ .object = tp }); } } - item = try withField(cx, message.object, "content", if (has_image) Value{ .array = parts.items } else Value{ .string = text.items }); + item = try withField(cx, message.object, "content", if (has_image or has_reference) Value{ .array = parts.items } else Value{ .string = text.items }); } else if (content == null or content.? == .null) { item = try withField(cx, message.object, "content", .{ .string = "" }); } else if (content.? != .string) { diff --git a/zig/src/server/model_text.zig b/zig/src/server/model_text.zig index b21306e43a7..cc5a61552b7 100644 --- a/zig/src/server/model_text.zig +++ b/zig/src/server/model_text.zig @@ -145,6 +145,8 @@ pub const Rendered = struct { pub const Text = struct { native_deepseek: bool = false, + /// The chat template renders ``defer_loading`` and ``tool_reference`` itself (deferred_tools.zig). + deferred_native: bool = false, ctx: *anyopaque, vtable: *const VTable, @@ -213,7 +215,9 @@ pub const Text = struct { } pub fn render(t: Text, a: Allocator, messages: json.Value, options: RenderOptions, problem: *[]const u8) Error!Rendered { - return t.vtable.render(t.ctx, a, messages, options, problem); + var shown = options; + if (!t.deferred_native) shown.tools = try @import("deferred_tools.zig").shown(a, options.tools); + return t.vtable.render(t.ctx, a, messages, shown, problem); } /// The chat template's ids, as ``apply_chat_template(tokenize=True)`` gives them. diff --git a/zig/src/server/ollama.zig b/zig/src/server/ollama.zig index 2e36678eb1d..88d35541f3f 100644 --- a/zig/src/server/ollama.zig +++ b/zig/src/server/ollama.zig @@ -47,6 +47,7 @@ pub fn options(a: Allocator, window: u32, raw: Value, out: *json.Object, cx: *Cx /// `/api/chat` and `/api/generate` body as a chat request with `return_token_ids` on. pub fn chatBody(a: Allocator, model: []const u8, window: u32, raw: Value, cx: *Cx) errors.Refused!Value { if (raw != .object) return cx.refuse("request body must be an object"); + if (json.truthyField(raw, "execution_witness")) return cx.refuse("execution_witness is supported on /v1/chat/completions and /v1/completions only"); const out = try json.newObject(a); try out.put(a, "model", .{ .string = model }); if (raw.get("messages")) |messages| { diff --git a/zig/src/server/openai.zig b/zig/src/server/openai.zig index 3b23478828c..041affbce6c 100644 --- a/zig/src/server/openai.zig +++ b/zig/src/server/openai.zig @@ -28,7 +28,6 @@ const Conn = @import("http_conn.zig").Conn; const Value = json.Value; const Cx = errors.Cx; const Allocator = std.mem.Allocator; - /// Where a chat reply goes: the client's socket, or a Responses or Messages translation of it. pub const Out = struct { ctx: *anyopaque, @@ -54,6 +53,7 @@ pub fn post(srv: *Server, conn: *Conn, a: Allocator, is_chat: bool) void { const err = errorBody(a, &cx, if (is_chat) "messages" else "prompt") catch return; return routes.sendValue(conn, a, cx.status(), wrapError(a, err) catch return); }; + if (@import("auth_scope.zig").witnessDenial(conn.key_scopes, body)) |why| return @import("auth_scope_reply.zig").deny(conn, false, why); var client: ClientOut = .{ .conn = conn, .a = a, .startup_at = startup_at }; run(srv, a, client.out(), .{ .conn = conn }, is_chat, body); } @@ -108,13 +108,14 @@ pub fn plan(srv: *Server, cx: *Cx, is_chat: bool, raw: Value, format: ?[]const u const exact_bytes = asked and try @import("logprobs.zig").offered(srv, cx.a); const logprobs = if (is_chat) try fields.probabilityOptions(cx, body, exact_bytes) else try fields.legacyLogprobs(cx, body, exact_bytes); if (!cx.skip_request_log) if (srv.config.request_log) |path| request_log.append(cx.a, path, body); - var input: chat.Input = .{ .fields = undefined, .format = format }; + var input: chat.Input = .{ .fields = undefined, .format = format, .execution_witness = try @import("witness_reply.zig").asked(srv, cx, body) }; if (is_chat) { input.messages = try messages.normalizeWith(cx, body.get("messages"), "system", srv.needs_user_after_tool, srv.media()); input.tools = if (srv.text.native_deepseek) try @import("deepseek_request.zig").active(cx, body.get("tools"), body.get("tool_choice")) else try tool_specs.active(cx, body.get("tools"), body.get("tool_choice")); } else if (body.get("messages")) |m| if (m == .array and m.array.len > 0) { input.messages = try messages.normalizeWith(cx, m, "system", srv.needs_user_after_tool, srv.media()); }; + input.messages = try @import("deferred_tools.zig").resolve(cx, input.messages, body.get("tools"), srv.text.deferred_native); const prompts: []const []const u8 = if (!is_chat and input.messages.array.len == 0) try prompt_list.texts(cx, body.get("prompt")) else &.{}; if (!is_chat and input.messages.array.len == 0) input.prompt = if (prompts.len > 0) .{ .text = prompts[0] } else try completion_prompt.legacyPrompt(srv, cx, body.get("prompt")); // ``body.get("max_tokens") or body.get("max_completion_tokens")``: both are ints or None by now @@ -129,7 +130,7 @@ pub fn plan(srv: *Server, cx: *Cx, is_chat: bool, raw: Value, format: ?[]const u input.temperature = if (t == .float) t.float else std.fmt.parseFloat(f64, t.int) catch 0; }; const sampling = try json.newObject(cx.a); - for ([_][]const u8{ "temperature", "top_p", "top_k", "min_p", "presence_penalty", "frequency_penalty", "seed", "priority", "model", "draft", "thinking_budget", "ignore_eos", "return_token_ids", "stop", "grammar_budget" } ++ grammar.fields) |k| if (body.get(k)) |v| try sampling.put(cx.a, k, v); + for ([_][]const u8{ "temperature", "top_p", "top_k", "min_p", "presence_penalty", "frequency_penalty", "seed", "priority", "model", "draft", "thinking_budget", "ignore_eos", "return_token_ids", "stop", "grammar_budget", "deadline_s" } ++ grammar.fields) |k| if (body.get(k)) |v| try sampling.put(cx.a, k, v); try grammar.refusal(cx, body); if (input.tools.len > 0 and try tool_specs.choiceRequiresCall(cx.a, body.get("tool_choice"))) try sampling.put(cx.a, "tool_call_required", .{ .bool = true }); if (body.field("parallel_tool_calls")) |p| if (p == .bool and !p.bool) try sampling.put(cx.a, "tool_call_single", .{ .bool = true }); @@ -273,6 +274,7 @@ pub const Run = struct { try o.put(r.a, "tensorfold", reply.runtime); try o.put(r.a, "speculative", reply.speculative); if (r.turn) |t| try o.put(r.a, "cortheon", try t.summary(r.a)); + if (reply.execution_witness) |w| try o.put(r.a, "execution_witness", w) else if (r.plan.input.execution_witness) try o.put(r.a, "execution_witness", try @import("witness_reply.zig").missing(r.a, r.srv)); } /// ``ToolCallPolicy.finish``: the reply's calls parsed out of its content. diff --git a/zig/src/server/request_deadline_http_test.zig b/zig/src/server/request_deadline_http_test.zig new file mode 100644 index 00000000000..670968a0ffe --- /dev/null +++ b/zig/src/server/request_deadline_http_test.zig @@ -0,0 +1,253 @@ +//! "deadline_s" through the OpenAI HTTP handler: chat and completions, whole and streamed, no sockets or GPU. +const std = @import("std"); +const api = @import("engine_api"); +const json = @import("json"); +const openai = @import("openai.zig"); +const Server = @import("server.zig").Server; +const Conn = @import("http_conn.zig").Conn; +const model_text = @import("model_text.zig"); +const Allocator = std.mem.Allocator; + +const eos_id: u32 = 'z'; + +/// One byte a token; `z` is EOS. +const Bytes = struct { + fn text(t: *Bytes) model_text.Text { + return .{ .ctx = t, .vtable = &.{ .encode = encode, .decode = decode, .token_id = tokenId, .token_string = tokenString, .vocab_size = vocab, .eos_ids = eos, .render = render, .template_source = template } }; + } + fn encode(_: *anyopaque, a: Allocator, input: []const u8, _: bool) model_text.Error![]u32 { + const ids = try a.alloc(u32, input.len); + for (input, ids) |byte, *id| id.* = byte; + return ids; + } + fn decode(_: *anyopaque, a: Allocator, ids: []const u32) Allocator.Error![]u8 { + const out = try a.alloc(u8, ids.len); + for (out, ids) |*v, id| v.* = @intCast(id); + return out; + } + fn tokenId(_: *anyopaque, _: []const u8) ?u32 { + return null; + } + fn tokenString(_: *anyopaque, a: Allocator, id: u32) ![]u8 { + return std.fmt.allocPrint(a, "{d}", .{id}); + } + fn vocab(_: *anyopaque) u32 { + return 256; + } + fn eos(_: *anyopaque) []const u32 { + return &.{eos_id}; + } + fn render(_: *anyopaque, a: Allocator, _: json.Value, _: model_text.RenderOptions, _: *[]const u8) model_text.Error!model_text.Rendered { + return .{ .text = try a.dupe(u8, "prompt") }; + } + fn template(_: *anyopaque) []const u8 { + return ""; + } +}; + +/// Gives `abc`; `hangs`: then waits for a cancel and gives `late` before its end, else ends by itself with `de` (stop). +const Script = struct { + hangs: bool, + late: []const u32 = &.{'d'}, + sink: ?api.Sink = null, + id: api.Id = 0, + mutex: std.Io.Mutex = .init, + done: std.atomic.Value(bool) = .init(false), + submitted: bool = false, + cancelled: bool = false, + linger_ms: u32 = 0, // after ending by itself, submit returns this late: the server first reads past the deadline + fn engine(s: *Script) api.Engine { + return .{ .ctx = s, .vtable = &.{ .info = info, .submit = submit, .cancel = cancel, .status = status, .memory = memory } }; + } + fn info(_: *anyopaque) api.Info { + return .{ .context_window = 8192 }; + } + fn submit(ctx: *anyopaque, id: api.Id, _: *const api.Request, sink: api.Sink) api.SubmitError!void { + const s: *Script = @ptrCast(@alignCast(ctx)); + s.sink = sink; + s.id = id; + s.submitted = true; + sink.event(sink.ctx, id, &.{ .prefilled = 0 }); + sink.event(sink.ctx, id, &.{ .tokens = &.{ 'a', 'b', 'c' } }); + if (!s.hangs) s.end(&.{ 'd', 'e' }, .stop); + if (s.linger_ms > 0) std.Io.sleep(std.testing.io, .fromMilliseconds(s.linger_ms), .awake) catch {}; + } + fn end(s: *Script, tokens: []const u32, reason: api.Reason) void { + s.mutex.lockUncancelable(std.testing.io); + defer s.mutex.unlock(std.testing.io); + if (s.done.load(.acquire)) return; + s.done.store(true, .release); + const sink = s.sink.?; + sink.event(sink.ctx, s.id, &.{ .tokens = tokens }); + sink.event(sink.ctx, s.id, &.{ .finished = .{ .reason = reason } }); + } + fn cancel(ctx: *anyopaque, _: api.Id) void { + const s: *Script = @ptrCast(@alignCast(ctx)); + if (!s.done.load(.acquire)) s.cancelled = true; + s.end(s.late, .cancelled); + } + fn status(_: *anyopaque, out: *api.Status, _: []u32) void { + out.* = .{}; + } + fn memory(_: *anyopaque, _: bool) ?api.Memory { + return null; + } + /// A hung reply the deadline never ended ends after 3 s with `XY` (stop), so a lost field fails instead of hanging. + fn watchdog(s: *Script) void { + var waited: u32 = 0; + while (!s.done.load(.acquire) and waited < 3000) : (waited += 10) std.Io.sleep(std.testing.io, .fromMilliseconds(10), .awake) catch {}; + if (s.sink != null) s.end(&.{ 'X', 'Y' }, .stop); + } +}; + +const Reply = struct { + a: Allocator, + slow: bool = false, // the first streamed event takes 100 ms to write + status: ?u16 = null, + whole: ?json.Value = null, + events: std.ArrayList(json.Value) = .empty, + fn out(r: *Reply) openai.Out { + return .{ .ctx = r, .vt = &.{ .open = open, .event = event, .reply = reply } }; + } + fn open(_: *anyopaque, _: usize) error{Closed}!void {} + fn event(ctx: *anyopaque, value: ?json.Value) error{Closed}!void { + const r: *Reply = @ptrCast(@alignCast(ctx)); + if (r.slow and r.events.items.len == 0) std.Io.sleep(std.testing.io, .fromMilliseconds(100), .awake) catch {}; + if (value) |v| r.events.append(r.a, v) catch return error.Closed; + } + fn reply(ctx: *anyopaque, status_code: u16, value: json.Value) void { + const r: *Reply = @ptrCast(@alignCast(ctx)); + r.status = status_code; + r.whole = value; + } +}; + +/// What a client reads: the finish, the text, usage, the tensorfold block and (streamed) each event's choices. +const Got = struct { status: u16, finish: []const u8 = "", text: []const u8 = "", tokens: i64 = 0, ids: []const u8 = "", tensorfold: ?json.Value = null, choices: []const []const u8 = &.{} }; + +const Case = struct { chat: bool, stream: bool }; +const cases = [_]Case{ .{ .chat = true, .stream = false }, .{ .chat = true, .stream = true }, .{ .chat = false, .stream = false }, .{ .chat = false, .stream = true } }; + +/// POSTs one body through openai.run; `extra`: more fields, each led by a comma. +fn post(a: Allocator, s: *Script, c: Case, max_tokens: u32, extra: []const u8) !Got { + var bytes: Bytes = .{}; + const srv = try Server.init(std.testing.allocator, std.testing.io, s.engine(), bytes.text(), .{ .served_name = "m", .model_ids = &.{"m"}, .enable_thinking = false, .use_drafts = false }, null); + defer srv.deinit(); + const input = if (c.chat) "\"messages\":[{\"role\":\"user\",\"content\":\"hi\"}]" else "\"prompt\":\"hi\""; + const text = try std.fmt.allocPrint(a, "{{\"model\":\"m\",{s},\"max_tokens\":{d},\"stream\":{},\"return_token_ids\":true{s}}}", .{ input, max_tokens, c.stream, extra }); + const body = (try json.parse(a, text)).ok; + var conn = Conn{ .fd = -1, .peer = "", .buf = &.{}, .gpa = a }; + var response = Reply{ .a = a, .slow = s.linger_ms > 0 }; + const dog = try std.Thread.spawn(.{}, Script.watchdog, .{s}); + openai.run(srv, a, response.out(), .{ .conn = &conn }, c.chat, body); + s.done.store(true, .release); + dog.join(); + if (response.status) |code| if (code != 200) return .{ .status = code }; + var got: Got = .{ .status = 200 }; + var content: std.ArrayList(u8) = .empty; + var choices: std.ArrayList([]const u8) = .empty; + var final: ?json.Value = response.whole; + for (response.events.items) |v| { + const cs = v.get("choices") orelse continue; + try choices.append(a, try json.stringify(a, cs, .{})); + if (cs.array.len == 0) continue; + const ch = cs.array[0]; + try content.appendSlice(a, json.strOr(if (c.chat) (ch.get("delta") orelse continue).get("content") else ch.get("text"))); + if (ch.get("finish_reason")) |r| if (r == .string) { + final = v; + }; + } + const value = final orelse return error.MissingFinalReply; + const ch = value.get("choices").?.array[0]; + got.finish = json.strOr(ch.get("finish_reason")); + got.text = if (c.stream) content.items else json.strOr(if (c.chat) ch.get("message").?.get("content") else ch.get("text")); + got.tokens = value.get("usage").?.get("completion_tokens").?.int64().?; + got.tensorfold = value.get("tensorfold"); + got.ids = try json.stringify(a, (got.tensorfold orelse return error.MissingTensorfold).get("token_ids") orelse return error.MissingTokenIds, .{}); + got.choices = choices.items; + return got; +} + +test "request deadline: HTTP deadline_s reaches the engine, finish deadline with the late token, usage and ids" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + for (cases) |c| { + var s: Script = .{ .hangs = true }; + const got = try post(a, &s, c, 100, ",\"deadline_s\":0.05"); + try std.testing.expect(s.cancelled); + try std.testing.expectEqualStrings("deadline", got.finish); + try std.testing.expectEqualStrings("abcd", got.text); + try std.testing.expectEqual(4, got.tokens); + try std.testing.expectEqualStrings("[97, 98, 99, 100]", got.ids); + } +} + +test "request deadline: HTTP without deadline_s, or with one the reply never meets, the reply and stream are the same" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + for (cases) |c| { + var s_off: Script = .{ .hangs = false }; + var s_late: Script = .{ .hangs = false }; + const off = try post(a, &s_off, c, 100, ""); + // the largest deadline_s (11.6 days): a paused test process never reaches it before the script ends by itself + const late = try post(a, &s_late, c, 100, ",\"deadline_s\":1000000"); + for ([_]Got{ off, late }, [_]*Script{ &s_off, &s_late }) |g, s| { + try std.testing.expect(!s.cancelled); + try std.testing.expectEqualStrings("stop", g.finish); + try std.testing.expectEqualStrings("abcde", g.text); + try std.testing.expectEqualStrings("[97, 98, 99, 100, 101]", g.ids); + } + try std.testing.expectEqualStrings(off.tensorfold.?.get("token_sha256").?.string, late.tensorfold.?.get("token_sha256").?.string); + try std.testing.expectEqual(off.choices.len, late.choices.len); + for (off.choices, late.choices) |x, y| try std.testing.expectEqualStrings(x, y); + } +} + +test "request deadline: HTTP refuses deadline_s that is not a positive number of seconds, before the engine" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + for (cases) |c| for ([_][]const u8{ "0", "-1", "\"300\"", "true", "1e7" }) |bad| { + var s: Script = .{ .hangs = false }; + const got = try post(a, &s, c, 100, try std.fmt.allocPrint(a, ",\"deadline_s\":{s}", .{bad})); + try std.testing.expectEqual(400, got.status); + try std.testing.expect(!s.submitted); + }; +} + +test "request deadline: HTTP a late EOS, stop string or token cap after the deadline still ends deadline, every token kept" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const Collision = struct { late: []const u32, max: u32, extra: []const u8, text: []const u8, ids: []const u8 }; + const all = [_]Collision{ + .{ .late = &.{eos_id}, .max = 100, .extra = "", .text = "abc", .ids = "[97, 98, 99, 122]" }, + .{ .late = &.{'d'}, .max = 100, .extra = ",\"stop\":[\"d\"]", .text = "abc", .ids = "[97, 98, 99, 100]" }, + .{ .late = &.{ 'd', 'e' }, .max = 4, .extra = "", .text = "abcd", .ids = "[97, 98, 99, 100]" }, + }; + for (cases) |c| for (all) |x| { + var s: Script = .{ .hangs = true, .late = x.late }; + const got = try post(a, &s, c, x.max, try std.fmt.allocPrint(a, ",\"deadline_s\":0.05{s}", .{x.extra})); + try std.testing.expect(s.cancelled); + try std.testing.expectEqualStrings("deadline", got.finish); + try std.testing.expectEqualStrings(x.text, got.text); + try std.testing.expectEqual(4, got.tokens); + try std.testing.expectEqualStrings(x.ids, got.ids); + }; +} + +test "request deadline: HTTP a reply the engine ended before the deadline keeps finish stop when the server reads it late" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + for (cases) |c| { + var s: Script = .{ .hangs = false, .linger_ms = 100 }; + const got = try post(a, &s, c, 100, ",\"deadline_s\":0.05"); + try std.testing.expect(!s.cancelled); + try std.testing.expectEqualStrings("stop", got.finish); + try std.testing.expectEqualStrings("abcde", got.text); + try std.testing.expectEqualStrings("[97, 98, 99, 100, 101]", got.ids); + } +} diff --git a/zig/src/server/request_deadline_test.zig b/zig/src/server/request_deadline_test.zig new file mode 100644 index 00000000000..bc5153c7c1d --- /dev/null +++ b/zig/src/server/request_deadline_test.zig @@ -0,0 +1,198 @@ +//! "deadline_s": the server ends a reply at its deadline itself, with finish_reason "deadline", usage and ids. +const std = @import("std"); +const api = @import("engine_api"); +const json = @import("json"); +const server = @import("server.zig"); +const chat = @import("chat.zig"); +const model_text = @import("model_text.zig"); +const Cx = @import("errors.zig").Cx; + +const gpa = std.testing.allocator; + +/// One byte a token. +const Bytes = struct { + fn text(t: *Bytes) model_text.Text { + return .{ .ctx = t, .vtable = &.{ .encode = encode, .decode = decode, .token_id = tokenId, .token_string = tokenString, .vocab_size = vocab, .eos_ids = eos, .render = render, .template_source = template } }; + } + fn encode(_: *anyopaque, a: std.mem.Allocator, input: []const u8, _: bool) model_text.Error![]u32 { + const ids = try a.alloc(u32, input.len); + for (input, ids) |byte, *id| id.* = byte; + return ids; + } + fn decode(_: *anyopaque, a: std.mem.Allocator, ids: []const u32) std.mem.Allocator.Error![]u8 { + const out = try a.alloc(u8, ids.len); + for (out, ids) |*v, id| v.* = @intCast(id); + return out; + } + fn tokenId(_: *anyopaque, _: []const u8) ?u32 { + return null; + } + fn tokenString(_: *anyopaque, a: std.mem.Allocator, id: u32) ![]u8 { + return std.fmt.allocPrint(a, "{d}", .{id}); + } + fn vocab(_: *anyopaque) u32 { + return 256; + } + fn eos(_: *anyopaque) []const u32 { + return &.{}; + } + fn render(_: *anyopaque, a: std.mem.Allocator, _: json.Value, _: model_text.RenderOptions, _: *[]const u8) model_text.Error!model_text.Rendered { + return .{ .text = try a.dupe(u8, "prompt") }; + } + fn template(_: *anyopaque) []const u8 { + return ""; + } +}; + +/// Gives `abc`; then ends by itself later (`de`, stop), or, cancelled, gives the `d` it had made. +const Script = struct { + sink: ?api.Sink = null, + id: api.Id = 0, + done: bool = false, + cancelled: bool = false, + cancels: usize = 0, // every cancel the server sent, before or after the end + lazy: bool = false, // a cancel is only noted; the stream ends at the 40th check, as a slow engine's would + quick: bool = false, // ends by itself (`de`, stop) inside submit, before any deadline + fn engine(s: *Script) api.Engine { + return .{ .ctx = s, .vtable = &.{ .info = info, .submit = submit, .cancel = cancel, .status = status, .memory = memory } }; + } + fn info(_: *anyopaque) api.Info { + return .{ .context_window = 8192 }; + } + fn submit(ctx: *anyopaque, id: api.Id, _: *const api.Request, sink: api.Sink) api.SubmitError!void { + const s: *Script = @ptrCast(@alignCast(ctx)); + s.* = .{ .sink = sink, .id = id, .lazy = s.lazy, .quick = s.quick }; + sink.event(sink.ctx, id, &.{ .prefilled = 0 }); + sink.event(sink.ctx, id, &.{ .tokens = &.{ 'a', 'b', 'c' } }); + if (s.quick) s.end(&.{ 'd', 'e' }, .stop); + } + fn end(s: *Script, tokens: []const u32, reason: api.Reason) void { + if (s.done) return; + s.done = true; + const sink = s.sink.?; + sink.event(sink.ctx, s.id, &.{ .tokens = tokens }); + sink.event(sink.ctx, s.id, &.{ .finished = .{ .reason = reason } }); + } + fn cancel(ctx: *anyopaque, _: api.Id) void { + const s: *Script = @ptrCast(@alignCast(ctx)); + s.cancels += 1; + if (!s.done) s.cancelled = true; + if (!s.lazy) s.end(&.{'d'}, .cancelled); + } + fn status(_: *anyopaque, out: *api.Status, _: []u32) void { + out.* = .{}; + } + fn memory(_: *anyopaque, _: bool) ?api.Memory { + return null; + } +}; + +/// The client never leaves; the engine ends by itself at the 40th check (~2 s), a stuck reply fails at the 400th. +const Gone = struct { + s: *Script, + checks: *usize, + pub fn check(g: @This()) bool { + if (g.s.sink == null) return false; + g.checks.* += 1; + if (g.checks.* == 40) if (g.s.cancelled) g.s.end(&.{'d'}, .cancelled) else g.s.end(&.{ 'd', 'e' }, .stop); + return g.checks.* > 400; + } +}; + +const Deltas = struct { + a: std.mem.Allocator, + out: std.ArrayList([]const u8) = .empty, + slow: bool = false, // the first write takes 100 ms, as a slow client's would + fn call(ctx: *anyopaque, delta: json.Value) error{Closed}!void { + const d: *Deltas = @ptrCast(@alignCast(ctx)); + if (d.slow and d.out.items.len == 0) std.Io.sleep(std.testing.io, .fromMilliseconds(100), .awake) catch {}; + d.out.append(d.a, json.stringify(d.a, delta, .{}) catch return error.Closed) catch return error.Closed; + } +}; + +const Run = struct { reply: chat.Reply, deltas: []const []const u8, cancelled: bool, cancels: usize }; + +fn run(a: std.mem.Allocator, deadline: ?json.Value) !Run { + return runAsked(a, deadline, null, false); +} + +/// `asked`: the cancel route's ask (the engine then ends late on cancel); `slow`: ends in submit, first write 100 ms. +fn runAsked(a: std.mem.Allocator, deadline: ?json.Value, asked: ?*const std.atomic.Value(bool), slow: bool) !Run { + var script: Script = .{ .lazy = asked != null, .quick = slow }; + var bytes: Bytes = .{}; + const srv = try server.Server.init(gpa, std.testing.io, script.engine(), bytes.text(), .{ .served_name = "test", .model_ids = &.{"test"}, .enable_thinking = false }, null); + defer srv.deinit(); + const fields = try json.newObject(a); + try fields.put(a, "return_token_ids", .{ .bool = true }); + if (deadline) |d| try fields.put(a, "deadline_s", d); + var deltas: Deltas = .{ .a = a, .slow = slow }; + var checks: usize = 0; + var cx: Cx = .{ .a = a }; + const input: chat.Input = .{ .id = "chatcmpl-deadline", .prompt = .{ .text = "prompt" }, .max_tokens = 100, .fields = .{ .object = fields }, .cancel = asked }; + const reply = try chat.run(srv, &cx, input, .{ .ctx = &deltas, .call = Deltas.call }, Gone{ .s = &script, .checks = &checks }); + return .{ .reply = reply, .deltas = deltas.out.items, .cancelled = script.cancelled, .cancels = script.cancels }; +} + +fn tokenIds(a: std.mem.Allocator, reply: chat.Reply) ![]const u8 { + return json.stringify(a, reply.runtime.get("token_ids").?, .{}); +} + +test "request deadline: the server ends the reply at deadline_s with finish deadline, every token and its ids" { + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + const a = arena.allocator(); + const got = try run(a, .{ .float = 0.05 }); + try std.testing.expect(got.cancelled); + try std.testing.expectEqualStrings("deadline", got.reply.finish_reason); + try std.testing.expectEqualStrings("abcd", got.reply.content); // the token the engine made before its end lands + try std.testing.expectEqual(4, got.reply.completion_tokens); + try std.testing.expectEqualStrings("[97, 98, 99, 100]", try tokenIds(a, got.reply)); +} + +test "request deadline: without deadline_s, or with one the reply ends before, the reply and stream are the same" { + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + const a = arena.allocator(); + const off = try run(a, null); + // the largest deadline_s (11.6 days): a paused test process never reaches it before the script ends by itself + const late = try run(a, .{ .int = "1000000" }); + for ([_]Run{ off, late }) |r| { + try std.testing.expect(!r.cancelled); + try std.testing.expectEqualStrings("stop", r.reply.finish_reason); + try std.testing.expectEqualStrings("abcde", r.reply.content); + try std.testing.expectEqualStrings("[97, 98, 99, 100, 101]", try tokenIds(a, r.reply)); + } + try std.testing.expectEqualStrings(off.reply.runtime.get("token_sha256").?.string, late.reply.runtime.get("token_sha256").?.string); + try std.testing.expectEqual(off.deltas.len, late.deltas.len); + for (off.deltas, late.deltas) |x, y| try std.testing.expectEqualStrings(x, y); +} + +test "request deadline: deadline_s that is not a positive number of seconds is refused" { + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + const a = arena.allocator(); + for ([_]json.Value{ .{ .int = "0" }, .{ .float = -1 }, .{ .string = "300" }, .{ .bool = true } }) |bad| + try std.testing.expectError(error.Refused, run(a, bad)); +} + +test "request deadline: a client's cancel that came first keeps finish cancelled when the deadline passes later" { + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + const a = arena.allocator(); + const asked: std.atomic.Value(bool) = .init(true); + const got = try runAsked(a, .{ .float = 0.05 }, &asked, false); + try std.testing.expect(got.cancelled); + try std.testing.expectEqualStrings("cancelled", got.reply.finish_reason); + try std.testing.expectEqualStrings("abcd", got.reply.content); +} + +test "request deadline: a slow writer draining a reply the engine already ended keeps finish stop and sends no cancel" { + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + const a = arena.allocator(); + const got = try runAsked(a, .{ .float = 0.05 }, null, true); + try std.testing.expectEqualStrings("stop", got.reply.finish_reason); + try std.testing.expectEqual(0, got.cancels); + try std.testing.expectEqualStrings("abcde", got.reply.content); + try std.testing.expectEqualStrings("[97, 98, 99, 100, 101]", try tokenIds(a, got.reply)); +} diff --git a/zig/src/server/responses_translate.zig b/zig/src/server/responses_translate.zig index 911b68f0cf8..c5fcdfa44c7 100644 --- a/zig/src/server/responses_translate.zig +++ b/zig/src/server/responses_translate.zig @@ -15,6 +15,7 @@ const refused = [_][2][]const u8{ .{ "conversation", "conversations are not supported: send previous_response_id or the items" }, .{ "prompt", "prompt templates are not supported: send input and instructions" }, .{ "context_management", "context management is not supported" }, + .{ "execution_witness", "execution_witness is supported on /v1/chat/completions and /v1/completions only" }, }; pub const Request = struct { diff --git a/zig/src/server/root.zig b/zig/src/server/root.zig index 878428d8b47..e0733b13766 100644 --- a/zig/src/server/root.zig +++ b/zig/src/server/root.zig @@ -17,6 +17,7 @@ pub const Server = server.Server; pub const Config = server.Config; test { + _ = @import("cache_flush.zig"); _ = @import("drafter_test.zig"); _ = @import("startup_receipt.zig"); _ = @import("kimi_prompt_test.zig"); @@ -39,9 +40,12 @@ test { _ = @import("http_limits_test.zig"); _ = @import("env_defaults_test.zig"); _ = @import("done_times_test.zig"); + _ = @import("unread_test.zig"); _ = @import("drain_test.zig"); _ = @import("keepalive_test.zig"); _ = @import("gpu_turn.zig"); + _ = @import("request_deadline_test.zig"); + _ = @import("request_deadline_http_test.zig"); _ = @import("idle_unload.zig"); _ = @import("idle_unload_test.zig"); _ = @import("wait_reason_test.zig"); @@ -73,9 +77,11 @@ test { _ = @import("tool_grammar_lfm2.zig"); _ = @import("tool_grammar_lfm2_test.zig"); _ = @import("tool_required_test.zig"); + _ = @import("tool_think_test.zig"); _ = @import("structure_field_test.zig"); _ = @import("grammar.zig"); _ = @import("grammar_compile_test.zig"); + _ = @import("structural_tag.zig"); _ = @import("pyrepr.zig"); _ = @import("metrics.zig"); _ = @import("load_metrics.zig"); @@ -128,6 +134,8 @@ test { _ = @import("request_log.zig"); _ = @import("request_journal_test.zig"); _ = @import("messages.zig"); + _ = @import("deferred_tools.zig"); + _ = @import("deferred_tools_test.zig"); _ = @import("pdf.zig"); _ = @import("pdf_flags_test.zig"); _ = @import("pdf_measure_test.zig"); @@ -358,3 +366,10 @@ test { _ = @import("ollama_e2e_test.zig"); _ = @import("open_connections_route_test.zig"); } + +test { + _ = @import("witness_test.zig"); + _ = @import("witness_http_test.zig"); + _ = @import("witness_race_test.zig"); + _ = @import("witness_reply_test.zig"); +} diff --git a/zig/src/server/routes.zig b/zig/src/server/routes.zig index 6748b0bd098..dbc6c62e75d 100644 --- a/zig/src/server/routes.zig +++ b/zig/src/server/routes.zig @@ -18,10 +18,12 @@ const tokens = @import("tokens.zig"); const decisions = @import("decisions.zig"); const systemone = @import("systemone.zig"); const status = @import("status_routes.zig"); +const witness = @import("witness.zig"); const memory = @import("memory_routes.zig"); const slide = @import("slide.zig"); const recall = @import("recall_routes.zig"); const imprint = @import("imprint_routes.zig"); +const flush = @import("cache_flush.zig"); const slide_forget = @import("slide_forget.zig"); const voice_routes = @import("drama_voice_routes.zig"); const Server = @import("server.zig").Server; @@ -110,6 +112,7 @@ fn get(srv: *Server, conn: *Conn, a: Allocator) void { if (std.mem.eql(u8, route, "/v1/slide/graph")) return slide.graph(srv, conn, a); if (std.mem.eql(u8, route, recall.path)) return recall.get(srv, conn, a); if (std.mem.eql(u8, route, "/v1/benchmark/manifest")) return status.manifestRoute(srv, conn, a) catch {}; + if (std.mem.eql(u8, route, witness.path)) return witness.route(srv, conn, a); if (route.len == 0 or std.mem.eql(u8, route, "/health")) return status.health(srv, conn, a) catch {}; if (std.mem.eql(u8, route, "/api/tags")) return ollama.tags(srv, conn, a); if (std.mem.eql(u8, route, "/api/show")) return ollama.show(srv, conn, a); @@ -135,6 +138,10 @@ fn post(srv: *Server, conn: *Conn, a: Allocator) void { discardBody(conn, a); return @import("responses_background.zig").cancel(srv, conn, a, rid); } + if (std.mem.eql(u8, route, flush.path)) { // an admin action outside admission: it waits for requests, holding no slot + discardBody(conn, a); + return flush.post(srv, conn, a); + } for (tokens.paths) |r| if (std.mem.eql(u8, route, r)) return tokens.post(srv, conn, a, route); const is_speech = std.mem.eql(u8, route, "/v1/audio/speech"); const is_voices = srv.config.voice.manage and std.mem.eql(u8, route, "/v1/voices"); diff --git a/zig/src/server/serve.zig b/zig/src/server/serve.zig index b3e37c27ca6..dc684a8475c 100644 --- a/zig/src/server/serve.zig +++ b/zig/src/server/serve.zig @@ -14,6 +14,7 @@ const idle_unload = @import("idle_unload.zig"); const hf_text = @import("hf_text.zig"); const routes = @import("routes.zig"); const recall_routes = @import("recall_routes.zig"); +const witness = @import("witness.zig"); const Allocator = std.mem.Allocator; const posix = platform.posix; @@ -106,6 +107,9 @@ pub const Setup = struct { stop: ?EngineStop = null, /// TENSORFOLD_TOOL_ID_KEY_FILE's key, read by `main` before the model, for the server to take; null: its own. tool_id_key: ?*@import("ids.zig").Key = null, + /// --execution-witness: the binary `main` opened and the text stamps it took before the load (null: unknown). + witness_binary: ?@import("witness_parts.zig").Binary = null, + witness_text: ?*const @import("witness_parts.zig").Text = null, }; /// `halt` (optional) ends the rounds at a boundary at the drain's deadline, so `close` never meets a running round. @@ -146,6 +150,10 @@ pub fn run(gpa: Allocator, io: std.Io, args: cli.Args, s: Setup) u8 { return 1; }; defer store.deinit(); + if (witness.refusal(args, store.enabled())) |why| { + std.debug.print("tensorfold: {s}\n", .{why}); + return 2; + } if (!store.enabled() and !auth.loopback(args.host)) log.line("warning: non-loopback server has no API key; requests are open", .{}); var ids: std.ArrayList([]const u8) = .empty; for ([_][]const []const u8{ &.{s.served}, args.alias }) |group| for (group) |raw| { @@ -201,6 +209,7 @@ pub fn run(gpa: Allocator, io: std.Io, args: cli.Args, s: Setup) u8 { .thinking_reserve = args.thinking_reserve, .loop_guard = args.loop_guard or args.loop_guard_stop, .loop_stop = args.loop_guard_stop, + .tool_think_close = args.tool_think_close, .keep_warm_s = args.keep_warm, .idle_unload_s = args.idle_unload, .admission = args.admission, @@ -244,6 +253,11 @@ pub fn run(gpa: Allocator, io: std.Io, args: cli.Args, s: Setup) u8 { return 1; }; defer srv.deinit(); + srv.witness = if (args.execution_witness) witness.State.init(gpa, io, srv, args, s.witness_binary, s.witness_text) catch { + std.debug.print("tensorfold: --execution-witness could not start\n", .{}); + return 1; + } else null; + defer if (srv.witness) |w| w.deinit(); srv.load.attach(srv.engine); srv.recall = s.recall; switch (idle_unload.startServer(srv, args, s.reopen, s.model_dir, s.model_type)) { @@ -292,6 +306,7 @@ pub fn run(gpa: Allocator, io: std.Io, args: cli.Args, s: Setup) u8 { if (s.recall) |r| recall_routes.line(r); if (srv.idle_manager != null) log.line("idle unload on: the engine closes after {d} s idle and the next request reloads it (a full model load)", .{args.idle_unload}); if (srv.cortheon) |c| log.line("cortheon on: chat requests get Cortheon's reasoning program, web research before building, and cortheon_search/cortheon_fetch run here ({s}); a request can send \"cortheon\": false", .{c.engine}); + if (srv.witness) |w| log.line("execution witness on: GET {s} with a read key{s}{s}", .{ witness.path, if (w.excluded != null) "; unknown while serving with " else "", w.excluded orelse "" }); live.columns_env = env(s, "COLUMNS"); var ticker: live.Ticker = .{ .read_status = readCurrentStatus, .ctx = srv }; const drawing = live.wanted(io, if (env(s, "TENSORFOLD_NO_LIVE")) |v| std.mem.eql(u8, v, "1") else false); @@ -300,6 +315,7 @@ pub fn run(gpa: Allocator, io: std.Io, args: cli.Args, s: Setup) u8 { var accept_stop: std.atomic.Value(bool) = .init(false); const accept = std.Thread.spawn(.{}, server_mod.Server.serve, .{ srv, lis, &accept_stop }) catch return 1; @import("startup_receipt.zig").ready(port); + if (srv.witness) |w| w.start(); // hashing starts after ready, on its own thread, never on the startup path while (!stop_requested.load(.acquire)) std.Io.sleep(io, .fromMilliseconds(50), .awake) catch {}; drain(srv, io, s.stop, drain_s); if (journal) |j| j.stopped(); // a stop, not a crash: requests still open are not quarantined diff --git a/zig/src/server/server.zig b/zig/src/server/server.zig index ed30695d572..96b2683dd24 100644 --- a/zig/src/server/server.zig +++ b/zig/src/server/server.zig @@ -58,8 +58,8 @@ pub const Config = struct { loop_guard: bool = false, /// --loop-guard-stop: a guarded reply ends where the guard fires, with a loop error and no answer or calls. loop_stop: bool = false, - /// Seconds the idle keepalive runs after the last request ends (0: off). - keep_warm_s: i64 = 900, + tool_think_close: bool = false, // --tool-think-close: a required or named call closes thinking in time + keep_warm_s: i64 = 900, // seconds the idle keepalive runs after the last request ends (0: off) /// Seconds of idle past the last request before the engine closes; the next request reloads it (0: never). idle_unload_s: i64 = 0, dashboard: bool = false, @@ -124,7 +124,6 @@ pub fn namedBackground(config: Config, f: Value) bool { for (config.background_ids) |id| if (std.mem.eql(u8, id, asked)) return true; return false; } - /// Name the compiled structure with the client's own field when its route carried one (a borrowed static literal). pub fn nameStructure(format: ?[]const u8, request: *api.Request) void { const name = format orelse return; @@ -193,6 +192,7 @@ pub const Server = struct { cortheon: ?*cortheon.State = null, /// Recall's record (--recall), which GET and DELETE /v1/recall read and empty; main opens and closes it. recall: ?*api.recall_store.Store = null, + witness: ?*@import("witness.zig").State = null, // serve owns GET /v1/execution/witness state; null: off /// Reads what the template and tokenizer decide once: late system role, think markers, efforts, the forced close. pub fn media(srv: *const Server) @import("messages.zig").Media { diff --git a/zig/src/server/structural_tag.zig b/zig/src/server/structural_tag.zig new file mode 100644 index 00000000000..3b9e43a9fe8 --- /dev/null +++ b/zig/src/server/structural_tag.zig @@ -0,0 +1,211 @@ +//! response_format structural_tag: free text; each structure's begin opens a region its schema holds to its end. +const std = @import("std"); +const json = @import("json"); +const errors = @import("errors.zig"); +const grammar = @import("grammar.zig"); +const node = @import("tool_grammar.zig").node; +const Value = json.Value; +const Cx = errors.Cx; +const Allocator = std.mem.Allocator; + +/// The most structures one request may list, and the most triggers. +pub const most = 64; + +/// The longest begin, end or trigger, in bytes. +pub const longest = 256; + +/// The most blanks a region's JSON takes between two tokens: the json_schema format's cap (tf_grammar.cc BLANKS). +const blanks = 32; + +const field = "response_format structural_tag"; +const no_structures = field ++ " needs structures: a non-empty list of {\"begin\", \"schema\", \"end\"}"; +const bad_triggers = field ++ " triggers must be a non-empty list of non-empty strings"; + +/// xgrammar's structural tag for `rf` (triggered_tags: text, and a tag wherever a trigger starts), or its refusal. +pub fn build(cx: *Cx, rf: Value) errors.Refused![]const u8 { + const a = cx.a; + const list = rf.field("structures") orelse { + if (rf.field("format") != null) return cx.refuse(field ++ " takes structures and triggers, not xgrammar's format object"); + return cx.refuse(no_structures); + }; + if (list != .array or list.array.len == 0) return cx.refuse(no_structures); + if (list.array.len > most) return cx.fail(.request, field ++ " takes at most {d} structures", .{most}); + const tags = try a.alloc(Value, list.array.len); + const begins = try a.alloc([]const u8, list.array.len); + const ws = try json.intValue(a, blanks); + for (list.array, tags, begins, 0..) |s, *tag, *begin, i| { + if (s != .object) return cx.fail(.request, field ++ " structures[{d}] must be an object with begin, schema and end", .{i}); + begin.* = try tagText(cx, s.get("begin"), i, "begin"); + const end = try tagText(cx, s.get("end"), i, "end"); + const raw = s.field("schema") orelse return cx.fail(.request, field ++ " structures[{d}] needs schema (a JSON schema object)", .{i}); + const where = try std.fmt.allocPrint(a, field ++ " structures[{d}].schema", .{i}); + const content = try node(a, "json_schema", &.{ .{ "json_schema", try grammar.schemaValue(cx, raw, where) }, .{ "max_whitespace_cnt", ws } }); + tag.* = try node(a, "tag", &.{ .{ "begin", .{ .string = begin.* } }, .{ "content", content }, .{ "end", .{ .string = end } } }); + } + const format = try node(a, "triggered_tags", &.{ + .{ "triggers", if (rf.field("triggers")) |t| try triggers(cx, t, begins) else try defaults(a, begins) }, + .{ "tags", .{ .array = tags } }, + .{ "stop_after_first", .{ .bool = false } }, + }); + const text = try json.stringify(a, try node(a, "structural_tag", &.{.{ "format", format }}), .{ .ascii = false, .compact = true }); + if (text.len > grammar.max_text) return cx.fail(.request, field ++ " compiles to {d} bytes of grammar, past the {d}-byte limit: send fewer or smaller schemas", .{ text.len, grammar.max_text }); + return text; +} + +/// A structure's begin or end: a non-empty string of at most `longest` bytes. +fn tagText(cx: *Cx, v: ?Value, i: usize, key: []const u8) errors.Refused![]const u8 { + const s = v orelse Value.null; + if (s != .string or s.string.len == 0) return cx.fail(.request, field ++ " structures[{d}].{s} must be a non-empty string", .{ i, key }); + if (s.string.len > longest) return cx.fail(.request, field ++ " structures[{d}].{s} is {d} bytes, past the {d}-byte limit", .{ i, key, s.string.len, longest }); + return s.string; +} + +/// Without triggers: each distinct begin no shorter begin starts, so every begin starts with exactly one trigger. +fn defaults(a: Allocator, begins: []const []const u8) Allocator.Error!Value { + var out: std.ArrayList(Value) = .empty; + for (begins, 0..) |b, i| { + const held = for (begins, 0..) |x, j| { + if (std.mem.startsWith(u8, b, x) and (x.len < b.len or j < i)) break true; + } else false; + if (!held) try out.append(a, .{ .string = b }); + } + return .{ .array = out.items }; +} + +/// Given triggers: distinct, each starting some begin, and every begin starting with exactly one (as xgrammar needs). +fn triggers(cx: *Cx, v: Value, begins: []const []const u8) errors.Refused!Value { + if (v != .array or v.array.len == 0) return cx.refuse(bad_triggers); + if (v.array.len > most) return cx.fail(.request, field ++ " takes at most {d} triggers", .{most}); + for (v.array, 0..) |t, k| { + if (t != .string or t.string.len == 0) return cx.refuse(bad_triggers); + if (t.string.len > longest) return cx.fail(.request, field ++ " triggers[{d}] is {d} bytes, past the {d}-byte limit", .{ k, t.string.len, longest }); + for (v.array[0..k]) |x| if (std.mem.eql(u8, x.string, t.string)) return cx.fail(.request, field ++ " trigger {s} is listed twice", .{t.string}); + const used = for (begins) |b| { + if (std.mem.startsWith(u8, b, t.string)) break true; + } else false; + if (!used) return cx.fail(.request, field ++ " trigger {s} starts no structure's begin", .{t.string}); + } + for (begins, 0..) |b, i| { + var first: ?[]const u8 = null; + for (v.array) |t| { + if (!std.mem.startsWith(u8, b, t.string)) continue; + if (first) |f| return cx.fail(.request, field ++ " structures[{d}].begin {s} starts with two triggers, {s} and {s}", .{ i, b, f, t.string }); + first = t.string; + } + if (first == null) return cx.fail(.request, field ++ " structures[{d}].begin {s} starts with none of the triggers", .{ i, b }); + } + return v; +} + +fn specOf(cx: *Cx, body: []const u8) errors.Refused!?grammar.Spec { + return grammar.spec(cx, (try json.parse(cx.a, body)).ok); +} + +const weather = "{\"begin\":\"\",\"schema\":{\"type\":\"object\",\"required\":[\"city\"]},\"end\":\"\"}"; +const time = "{\"begin\":\"\"}"; +const short = "{\"begin\":\""}, .begins = &.{""} }, + // a begin listed twice is one trigger; a schema given as JSON text is parsed + .{ .body = head ++ ",\"structures\":[" ++ weather ++ "," ++ time ++ "," ++ weather ++ "]}}", .triggers = &.{ "", "