diff --git a/.gitignore b/.gitignore index 6e647ef2c26..6361b088bf9 100644 --- a/.gitignore +++ b/.gitignore @@ -28,6 +28,8 @@ zig-out/ # Versioned GUI build resources, generated app engines stay ignored in app/.gitignore. !app/build/ +# mHC fp64 qualification receipts. +/receipts/ # The full E4B per-layer input oracle outputs (tools/zig/gemma4_e4b_layer_input_oracle.py --full); the committed fixture is the .json of SHA-256 prints. tools/zig/fixtures/e4b_layer_input_mlx.bin diff --git a/CHANGELOG.md b/CHANGELOG.md index 1c88adeca12..e09a72d81c3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,9 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel ## Unreleased +- DeepSeek V4.1 on Metal: the EXL3 register-only decode body now serves every speculative window's fused gate+up call, up to the eight-token window; a four-draft window no longer switches to the tensor-unit compact body for its seventy rows, so its replies match plain decode again (the 8 reference and the 10 code prompts, four-draft against plain), its 5-row round's event p50 falls from ~104 ms to 61 ms, and the default config's hashes and timings are unchanged. +- Metal: DeepSeek V4.1's concurrent dispatch mode (`TF_DSV41_CONCURRENT=1`) put the attention sparse scan before the dense-table pass and the split merge before the scan that feeds it; both barriers are now explicit, so the mode no longer changes the reply. + - Ripple-65B-Preview on Metal: `--drafter` takes the publisher's DFlash2 drafter (`ricursiveAI/Ripple-65B-Preview-DFlash2`) beside either release, with drafted replies equal to plain ones; with the drafter the server opens two streams unless `--parallel` is named, and refuses a named `--parallel` above 2 (#2260, fixes #2259). Thanks to @BobClawblaw. - Inkling 2 Mini: `enable_thinking: false` and `reasoning_effort: "none"` now reach the chat template as thinking effort 0 instead of the default 0.9; thinking-on replies are unchanged (#4876). @@ -236,6 +239,24 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - Qwen3.5/3.8 on CUDA: `TF_Q35_DFLASH_ABSORB_BATCH=1` (opt-in) absorbs a DFlash2 round's streams in one pass, reading the drafter's weights once a round; about 1-2% faster at 4 streams on GB10, tokens unchanged. +- DeepSeek-V4.1 EXL3 on Metal: the indexer's one-shot select also runs for prefill chunks past 4096 keys, in row sub-blocks, instead of the one-thread-per-row heap select, with the same selected indices (#3734). +- DeepSeek-V4.1 EXL3 on Metal: exact tiled half-FMA decode, fused projection chains, batched decode attention (#3382), + per-prompt suffix-cone prefill, next-chunk Engram staging and bounded vocabulary-head scratch. + Prompt chunks adapt to admitted memory and live decoders; incompatible shapes retain the generic projection body. + Small dense, filtered and indexed projections retain matching reduction orders and logical output bounds. + Attention tiles stop at their split boundary instead of counting some keys twice, and packed NaNs survive BF16 decoding. + Draft embedding IDs grow without replacing Markov picks; unload releases host state, Markov IDs and drafter scratch. + MTP-only configurations no longer depend on lookup drafting; proposal depth is capped at the four-ID capacity. + Adaptive trained depth remains available with lookup disabled; suffix lookup reads the committed stream context. + Matching suffix proposals take precedence over paid trained proposals. + The diagnostic runner honors an explicit prefill-workspace setting without changing its unset default. + GPU profiling starts deferred mHC spans only when work is encoded, avoiding empty counter samples. + Last-row logits expand the selected final stream row rather than row zero of a multi-row window. + Fused mHC Sinkhorn uses the unfused split's FP32 row and column reduction order. + Stacked on #2373; whole-model qualification is still incomplete. + See [scope and qualification limits](docs/deepseek-v41.md#exl3-optimization-follow-up) + and [full-window fidelity](docs/receipts/dsv41-exl3-metal/fidelity-128.json). + ## 1.3.4 - Lanes: #3728's lone-stream copy pricing applies only to a family that opts in and serves without a model drafter (Qwen3.5/3.8 on HIP with copies only), so copies-only decode on AMD Strix Halo keeps 1.3.3's speed, while streams with a model drafter price their drafts as before; tokens are unchanged. diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index bb3efe49a8f..0635a9ca15b 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -217,7 +217,7 @@ MIT License, Copyright © 2025 Turboderp. TensorFold's decoders and kernels are checked bit for bit against ExLlamaV3's dequantization. The native `zig/src/core/exl3_format.zig` reference decoder, the `zig/src/core/exl3_projection*.zig` decoder and -`zig/kernels/metal/core/exl3_projection.metal` separately implement the same format and codebooks +`zig/kernels/metal/core/exl3_projection_core.metal` and `_wide.metal` separately implement the same format and codebooks under the Turboderp attribution above. So do the native checkpoint scan (`zig/src/core/exl3_load.zig`, `exl3_metal_load.zig`), the CUDA kernels (`zig/kernels/cuda/exl3_*.cu`, `exl3_decode.cuh`, `exl3_candidate.cuh`) and their Zig side (`zig/src/cuda/exl3*.zig`), and GLM's reader of its EXL3 experts (`zig/src/families/glm/cuda_exl3.zig`). @@ -294,6 +294,13 @@ Bolt's GGML checkpoints (`zig/kernels/cuda/ggml.cu`, `zig/src/cuda/ggml.zig`) ar TensorFold ships no model weights. The `z-lab/Qwen3.8-27B-DFlash2` model card states Apache-2.0. The optional `incoai/GLM-5.3-Flash-DFlash2` model card states Apache-2.0 too. Each checkpoint keeps its own license. +The native `zig/src/families/deepseek_v41/` implementation and `zig/tests/deepseek_v41_reference/` +follow [DeepSeek-V4.1-Flash's official inference](https://huggingface.co/deepseek-ai/DeepSeek-V4.1-Flash/tree/2cba9e42aa026125f3ed06c6d98c1db82f7ca027/inference), +MIT License, Copyright (c) 2023 DeepSeek: the reference's equations, the Engram normalization, +PCG64 multipliers and prime bucket layout, and the pinned chat template come from that revision. +The EXL3 checkpoint reads through the ExLlamaV3 format covered above; no captured CUDA/Triton +kernel assets, full model shards or binary traces are bundled. + ## Structured output: libtfgrammar `lib/libtfgrammar` in the release archives is `zig/src/grammar/tf_grammar.cc` compiled with the C++ sources of diff --git a/build.zig b/build.zig index 841e2c3fc54..fa7b82ff0ff 100644 --- a/build.zig +++ b/build.zig @@ -113,7 +113,7 @@ pub fn build(b: *std.Build) void { @import("zig/build/quant_geometry_host.zig").steps(b, test_step); @import("zig/build/stage.zig").steps(b, test_step); if (b.graph.host.result.os.tag == .macos) { - const step5_mods = metalEngineModules(b, b.graph.host, .Debug, draft_ids); + const step5_mods = metalEngineModules(b, b.graph.host, .Debug, draft_ids, b.createModule(.{ .root_source_file = b.path("zig/src/core/tokenizer/tokenizer.zig"), .target = b.graph.host, .optimize = .Debug, .link_libc = true })); const empty = b.addWriteFiles().add("step5-compile-only.metallib", ""); step5_mods.sources.addImport("nemotron_packed_metallib", embedded(b, empty, "nemotron_packed.metallib")); @import("zig/build/step5_host.zig").steps(b, step5_mods.metal, step5_mods.engine, step5_mods.lanes); @@ -132,7 +132,7 @@ pub fn build(b: *std.Build) void { @import("zig/build/lfm3_host.zig").steps(b, test_step); @import("zig/build/qwen3_asr_host.zig").steps(b, test_step); if (b.graph.host.result.os.tag == .macos) { - const budget_mods = metalEngineModules(b, b.graph.host, .Debug, draft_ids); + const budget_mods = metalEngineModules(b, b.graph.host, .Debug, draft_ids, b.createModule(.{ .root_source_file = b.path("zig/src/core/tokenizer/tokenizer.zig"), .target = b.graph.host, .optimize = .Debug, .link_libc = true })); const budget_empty = b.addWriteFiles().add("budget-compile-only.metallib", ""); budget_mods.sources.addImport("nemotron_packed_metallib", embedded(b, budget_empty, "nemotron_packed.metallib")); @import("zig/build/metal_prompt_sources.zig").steps(b, budget_mods.metal, budget_mods.engine, test_step); @@ -199,7 +199,7 @@ pub fn build(b: *std.Build) void { const gemma4_contract_host = @import("zig/build/gemma4_host.zig").tests(b, gemma4_host_sources); gemma4_contract_host.dependOn(@import("zig/build/glm_rows_contract.zig").host(b, gemma4_host_sources)); if (b.graph.host.result.os.tag == .macos) { - const gemma4_host_mods = metalEngineModules(b, b.graph.host, .Debug, draft_ids); + const gemma4_host_mods = metalEngineModules(b, b.graph.host, .Debug, draft_ids, b.createModule(.{ .root_source_file = b.path("zig/src/core/tokenizer/tokenizer.zig"), .target = b.graph.host, .optimize = .Debug, .link_libc = true })); gemma4_host_mods.sources.addImport("nemotron_packed_metallib", embedded(b, b.addWriteFiles().add("gemma4-compile-empty.metallib", ""), "nemotron_packed.metallib")); @import("zig/build/gemma4_host.zig").compileHost(b, gemma4_host_mods.metal, gemma4_host_mods.engine, gemma4_host_mods.lanes, gemma4_host_mods.sources); @import("zig/build/qwen27_host.zig").compileHost(b, gemma4_host_mods.metal, gemma4_host_mods.engine, gemma4_host_mods.lanes); diff --git a/docs/deepseek-v41-mhc-fp64.json b/docs/deepseek-v41-mhc-fp64.json new file mode 100644 index 00000000000..833a67ae98c --- /dev/null +++ b/docs/deepseek-v41-mhc-fp64.json @@ -0,0 +1,103 @@ +{ + "scope": "mHC (hyperconnection mix) stage fp64 qualification: rounding level, Metal deltas and 1-ULP input amplification. Independent CPU reference parameterized comptime (math.zig MixOf/denseOf/mixesOf/splitOf/inverseOf/collapseOf/expandOf, f32 source-contract path bit-identical, f64 ideal path); harness zig/tests/deepseek_v41_reference/operator_hc_fp64.zig; fixtures hc_attention_rms.json and hc_fp64_rows.json (retained inputs only).", + "nrms_definition": "sqrt(sum(delta^2)/sum(ref^2)) in f64; ULP = |delta| / fp32 spacing at the fp64 reference value.", + "inputs": [ + "token671_attention (retained token-671 embedding, four copies)", + "token1_ffn (retained token-1 FFN stream and branch, real hc_ffn scale/base)", + "eight_teacher_rows (the eight retained teacher embeddings)", + "wide_dynamic_range (copy magnitudes 2^24..2^-12, rotating signs)", + "split_args (16 retained unary arguments incl. 1.4393715858459473, controlling post argument, integer exp sweep -32..32, plus sigmoid/softmax spans)", + "cancellation fixtures (half-ULP terms after 1.0)" + ], + "rounding_level_fp32_reference_vs_fp64": { + "inverse_statistic_nrms": [ + 2.7e-09, + 2.8e-08 + ], + "projection_dense_nrms": [ + 2.2e-08, + 2.9e-08 + ], + "pre_sigmoid_nrms": [ + 1.1e-08, + 4.2e-08 + ], + "post_nrms": [ + 3.9e-08, + 7.2e-08 + ], + "comb_sinkhorn_nrms": [ + 1.4e-08, + 6.8e-08 + ], + "collapse_bf16_unequal_cells": 0, + "post_expand_bf16_unequal_cells": [ + 0, + 5 + ] + }, + "metal_vs_fp64": { + "inverse_max_ulp": 0.6, + "projection_max_ulp": 0.5, + "pre_max_ulp": 2.75, + "post_max_ulp": 2.29, + "comb_max_ulp_near_cancelled_cells_only": 34.2, + "comb_max_abs": 1.5e-07, + "post_controlling_exponent_row_max_ulp": 1.61, + "exponent_sweep_minus32_to_32_worst_stage_nrms": 9e-08, + "bf16_unequal_cells": { + "token671": 0, + "token1_ffn": "3 of 20480", + "eight_teacher_rows": "8 of 163840", + "wide_dynamic_range": 0 + }, + "verdict": "every sub-stage sits at the fp32 source-contract rounding level; Metal exceeds the fp32 reference by at most ~1 ULP at the documented Metal exp boundary" + }, + "cancellation_boundaries": [ + { + "fixture": "collapse_half_ulps", + "metal": "0x3500", + "f32_ref": "0x3500", + "f64_ideal": "0x34c0" + }, + { + "fixture": "post_half_ulps", + "metal": "0x0", + "f32_ref": "0x0", + "f64_ideal": "0x3400" + }, + { + "fixture": "branch_product", + "metal": "0x3500", + "f32_ref": "0x3500", + "f64_ideal": "0x34c0" + } + ], + "amplification_1ulp_input": { + "method": "perturb one bf16 stream cell (or branch cell) by 1 ULP, propagate the ideal fp64 stage, output NRMS growth = sqrt(sum(dy^2)/sum(y^2)) / (|dx|/sqrt(sum(x^2))); 256 sampled cells per row; 8 teacher positions plus the token-1 FFN row", + "analog_fp64_gain_mean_per_row": [ + 0.182, + 0.76 + ], + "analog_fp64_gain_max_overall": 0.762, + "collapse_gain_mean": 0.5003, + "collapse_gain_max": 1.944, + "bf16_visible_gain_mean_per_row": [ + 0.74, + 2.382 + ], + "bf16_visible_gain_max": 34.5, + "bf16_rows_changed_fraction": "224-250 of 256 perturbations change at least one of 20480 output cells", + "mean_changed_cells": "8.1-13.1 of 20480", + "statistic_relative_shift_mean": 3.6e-07, + "comb_nrms_shift_mean": 3.6e-08, + "metal_confirmation_row0": { + "amp_mean": 1.886, + "fp64_bf16_amp_mean": 1.945, + "mean_changed_cells": 12.06 + } + }, + "gate_reading": "A single-ULP input difference is attenuated by the mix in exact arithmetic (gain < 1) and appears as 1-bf16-ULP flips on about 0.06 percent of output cells; the stage's own rounding-level output NRMS is 0 to 2.5e-5. Hyperconnection mixing therefore cannot turn fp32 ULP noise into the observed 4.096 percent whole-model NRMS; a specific operator-level difference elsewhere (sparse/compressed attention candidates) remains the plausible cause.", + "kernel_changes": "none required; no tolerance relaxed, no source coefficient injected", + "receipts": "gitignored receipts/ (mhc-fp64-run.log, mhc-fp64-parsed.json, build-summary.log); commit contains code, fixture and this summary" +} \ No newline at end of file diff --git a/docs/deepseek-v41.md b/docs/deepseek-v41.md new file mode 100644 index 00000000000..b7de8402200 --- /dev/null +++ b/docs/deepseek-v41.md @@ -0,0 +1,176 @@ +# DeepSeek-V4.1-Flash on Apple Silicon (EXL3, Metal) + +TensorFold serves DeepSeek-V4.1-Flash from resident EXL3 packs on Apple Silicon through the +Metal engine. **Scope: a DeepSeek-only family.** The kernels below are specific to the EXL3 +2.9 bpw pack format (trellis-coded weights the GPU decodes at use time). The parent's historical +receipts below use an M5 Ultra with 256 GB unified memory and an 80-core GPU. +The [optimization follow-up receipt](receipts/dsv41-exl3-metal/README.md) names its separate 64-core machine; +neither receipt qualifies other checkpoints or chips. + +The lane core runs one stream per slot and windows of rows, so concurrent requests keep +their own caches and Engram cursor. The parent's recorded served checks report: a drafted request equals the +no-drafts reply token for token (the 20-prompt band reads 329/329), a resumed conversation +equals the fresh one, concurrent lanes equal their solo runs (12/12 under sampled draws), +and the retained prompt cache is bounded by its own budget. These are not new follow-up measurements. + +## What you need + +- **256 GB machine (this lane):** the 2.9 bpw pack (~197 GB) resident plus the two Engram + tables (~189 GB, the model's external memory) streamed from disk by address. The full + resident admission (~386 GB) needs a 512 GB-class machine; on 256 GB the tables stream. +- **512 GB machine:** the same pack fully resident with `--engram-table-dir`; the loader's + 70%-of-RAM cap applies unless `GLM_LOAD_LIMIT_GB` opts past it. +- The original release's inference directory — `tokenizer.json`, `config.json`, + `chat_template.jinja` and the two Engram tables — beside the pack or passed with + `--engram-table-dir` / `--engram-stream-dir`. The weights come under DeepSeek's own + terms; DeepSeek's reference inference code is MIT and the native reference follows it (see + THIRD_PARTY_NOTICES). TensorFold itself is Apache-2.0. +- An EXL3 pack of the checkpoint. Pack provenance is the pack's own business: read the + `provenance/` note that ships beside it before comparing any two packs' numbers. + +## The token map + +The Engram tables are keyed by a compressed vocabulary derived from the release's own +tokenizer and inference config. The native engine builds the map itself — decode each id, +fall back to the raw token when the decoder emits U+FFFD, normalize through the release's +chain (NFKD, strip marks, lowercase, the whitespace replaces), dedupe — with the multipliers +drawn from NumPy's PCG64 exactly as the source does. When `engram-token-map.bin` is missing +beside the checkpoint and the original's tokenizer sits beside the tables, the engine +builds it at open; no Python step. To build it by hand: + +```sh +zig build tf-dsv41-token-map && ./zig-out/bin/tf-dsv41-token-map \ + --tokenizer /tokenizer.json --config /config.json --output /engram-token-map.bin +``` + +## Serve + +The 256 GB streamed line the campaign receipts use (drafts on; the `TF_DSV41_` prefix on +the draft flags is mandatory — the shorthand names silently serve plain): + +```sh +GLM_LOAD_LIMIT_GB=240 TF_DSV41_MTP_DRAFTS=1 TF_DSV41_TAPS=1 TF_DSV41_LOOKUP_DRAFTS=3 \ +tensorfold-native serve \ + --engram-stream-dir --chat-template /chat_template.jinja \ + --context 65536 --parallel 1 --prompt-cache-gib 4 \ + --host 127.0.0.1 --port 8899 --name DeepSeek-V4.1-Flash --keep-warm 0 +``` + +The 512 GB resident line (drafts off unless the machine has the headroom; retained caches +refuse to boot in resident mode without the streamed tables): + +```sh +GLM_LOAD_LIMIT_GB=430 tensorfold-native serve \ + --engram-table-dir --chat-template /chat_template.jinja \ + --context 65536 --parallel 2 --prompt-cache-gib 0 \ + --host 127.0.0.1 --port 8099 --name DeepSeek-V4.1-Flash --keep-warm 0 +``` + +`--parallel` is the lane count: each lane is one stream with its own caches and Engram +cursor. `--prompt-cache-gib` sizes the retained prompt cache (a resumed turn processes only +the suffix — 78 of 21,966 rows in 0.85 s on the receipt prompt). + +## The kernels + +EXL3 projections decode trellis weights at use time. The follow-up adds exact half-FMA decode bodies, +projection-chain fusions and batched one-row attention, retaining the parent's format and device admission paths. +Tensor-unit prefill is restricted to compatible geometry and whole-bit widths; half-bit widths keep the shared +or plain body. The vocabulary head scores at most 1024 rows per `.all` call; larger prompt chunks request only +their final row's logits. + +## EXL3 optimization follow-up + +This contribution is based on the EXL3 lane in upstream [#2373](https://github.com/ashhart/TensorFold/pull/2373). +It does not add CUDA serving, remote prefill, transport or approximate arithmetic. + +- Decode uses pipelined half-FMA trellis values, column tiles and matching dense multi-row bodies. +- MoE and attention chains fuse adjacent operations while preserving their rounding points and fallback paths. +- One-row attention stages can batch across slots; request state remains separate. +- Small dense, filtered and grouped projections share the same sixteen-warp reduction on tensor-unit devices; + scalar indexed windows use the dense split order and honor each descriptor's logical output width. +- Split attention masks each final key tile at its own boundary. Draft embedding IDs grow without replacing + pending Markov picks; teardown releases both owners and the taps, conditioning and draft-logit buffers. +- `TF_DSV41_MTP_DRAFTS=1` enables trained proposals independently of lookup drafting when DSpark weights exist. + Proposal depth is capped at four IDs. Served plain/drafted hashes match in the exercised greedy and sampled + cases, but the measured acceptance and verify costs do not establish a speedup or clear the no-slowdown gate. +- Exact suffix-cone prefill retains each interleaved prompt's pending encoder run. +- Engram lookahead reads the next chunk while the current chunk's GPU work runs; rows are consumed only when + their hashed IDs match the current chunk. The worker is joined before the forward returns. +- Head scratch is capped independently of chunk rows. An unset prefill step tries an admitted 8192-row workspace, + otherwise 4096, and caps prompt chunks at 4096 while another stream decodes. +- Two-k-block tensor-unit prefill preserves accumulation order. Its historical standalone speedup is not an + isolated served-engine speed claim. + +Controls and defaults are listed in [environment validation](environment.md#deepseek-exl3-metal-controls). +Operator checks are `zig build test-exl3-gpu` and `zig build test-deepseek-v41`; they do not establish whole-model +fidelity, every chip's performance, or complete kernel-contract qualification for the added bodies. +The parent's historical kernel-contract counts do not qualify these new kernels. +The follow-up remains a draft until its remaining kernel-contract and model gates are agreed and completed. + +The follow-up's [reproduction commands and raw token/timing receipts](receipts/dsv41-exl3-metal/README.md) +separate the newly exercised checks from the parent's historical results. + +## Known issues (honest) + +- **Governor first-touch.** The Engram gather keeps a 64-sample latency probe: if any + sample exceeds 20 µs the table is called cold and the prompt reads positionally, + uncached above 256k ids. The probe warms on its own sample byte, so the FIRST pass over + novel text pays the cold path by construction (a 35k-token first touch measured 968 + tok/s vs ~1,300 page-warm); repeats keep the mapped path. This is the measured trade + that removed a 24 GB page-cache pollution stall, not a defect to tune around. +- **Shared rounds decode plain.** A multi-lane batch round runs the exact plain window for + every lane (drafted requests in a shared round answer `"draft": false` with the same + tokens); drafting is a solo-lane property. +- **Cold concurrent prefill serializes.** Four simultaneous cold 22k prefills put up to + ~73 s of first-token wait on the last lane; only a prompt merge would compress + it, and the merge moves the reply, so it stays closed. +- **Long-context decode falls with context.** Drafted decode holds the 30+ tok/s bar to + ~41k and reads ~25 tok/s at 62k; the collapse is context length, not sampling. +- **The 2.8 bpw pack's duplicated tensors** are owned by the index, so a shard contributes + only the tensors the index maps to it. +- **The pack-format ceiling is a decision, not a kernel.** The measured path to ~1,400 + prefill / 70 decode is a 3-bit affine expert repack whose quality ratio (1.095) misses + the 1.05 band; it ships only if the maintainer accepts that band. + +## The numbers + +The per-operator reference tests run every stage against an FP64 ideal at three sides — kernel, FP32 +source contract, FP64 ideal — and assert rounding level. The whole-model picture is +sensitivity-dominated, and the floor-relative band is not stable across the fixed release-quality +window. On the full 128-token window (`release-quality-128.json` in the reference tests) the FP32 +contract chain reads 0.1622 NRMS against FP64 and the engine 0.2671, a ratio of 1.647x: the band +fails (1.05 clears, 1.10 reviews). The 16-token blocks after the first read 1.66-2.45x and the +32-token prefix 1.180x; only the first 16 tokens clear, at 1.006x (floor 0.4074, engine 0.4100), +because that block's floor is unusually noisy. The floor is not a rounding-level bound: on the first +token, with no cache history, the FP32 contract and FP64 ideal already differ by 0.519 NRMS, while +the engine differs by 0.517 from the ideal and 0.510 from the contract. The ratios therefore measure +the model's whole-model sensitivity to any arithmetic change, not an engine-only bf16 dequant class. +The 1% absolute figure is a reported trip-wire, not the arbiter. The band is a fixed-history +receipt, and the floor manifest binds the window, the exact FP32 logits and the checkpoint metadata +identity (config, index, present shard headers, token map). The 128-token window is the +qualification measurement this record reports; the 16-token window is fixed in the tree as +`release-quality-16.json`. The streamed run's execution reads also +fail the zero-disk-read residency clause (20 KB on the FP32 half, 67.8 MB on the FP64 +half); the receipt now reports the Engram stream's own logical rows and syscalls beside the +total. A cold rerun of the 16-token +window on the same tree reads 8.3 MB and fails that clause too, so the earlier 0-read +receipt was page warmth, not a property of the window. The operator self-check now runs +before the measured window (`06518d523`): a one-token qualification on that head records +`measurement_scope "model_execution"` and zero execution reads on a page-warm probe, and +the receipt names the self-check it excludes. On the same head a cold 16-token engine run +reads 24.1 MB for 1,536 stream reads — 15,691 bytes a read for a 264-byte row, the page +granularity of the stream's own positional reads, not a weight re-read. A page-warm repeat +reads 0. + +Context-labelled standing (M5 Ultra, 256 GB, the streamed line above; run-to-run rates +rounded): prefill ~930 tok/s warm at 3,002 tokens; plain decode ~44 tok/s at 4.5k and ~43 +at 21k, flat to 42k; drafted decode ~45 at 4.5k / ~55 at 21k; batched four-lane aggregate +59.3 tok/s; a resumed 21,966-token turn reads its 78-row suffix in 0.85 s. + +## Receipts + +The qualification receipts — the served parity legs, the lane bit-equality, the oracle and +margin captures — live beside the PRs on the fork; the tree carries the tests that +regenerate them: the FP64 reference suite (`test-deepseek-v41-reference`), the kernel +contract (`tf-kernel-contract`), and the ten-second select-determinism probe +(`test-deepseek-v41-index-probe`). diff --git a/docs/environment.md b/docs/environment.md index 7c21e763c9b..d9e006ea893 100644 --- a/docs/environment.md +++ b/docs/environment.md @@ -165,6 +165,28 @@ The `TF_GLM_*` rows are checked when GLM's CUDA family opens, on every rank, so 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. +## DeepSeek EXL3 Metal controls + +These controls use the shared parser. Empty or whitespace-only values keep the default; malformed values stop startup. + +| Variable | Accepted explicit value and default | +| --- | --- | +| `TF_DSV41_EXL3_FMA_TILES` | `0`, `1`, `2` or `4`; default `2`. Zero disables column tiling; dispatch still respects the projection's geometry. | +| `TF_DSV41_BATCH_MAX` | Whole row count `1` through `8`; default `4`. | +| `TF_DSV41_BATCH_ATTN` | `0` or `1`; default `1`. Zero restores the per-slot attention chain. | +| `TF_DSV41_MTP_DRAFTS` | `0` or `1`; default `0`. Enables the trained Metal drafter without requiring lookup drafts; `0` disables it. | +| `TF_DSV41_CONE` | `0`, `1` or `2`; default `2`. Zero uses the full forward, one uses one replay program, two uses layer groups. | +| `TF_DSV41_CONE_PARK` | Whole count `0` through `3`; default `3`. Other prompts' pending encoder runs retained beside the active run. | + +Unset `TF_DSV41_PREFILL_STEP` tries 8192 workspace rows and falls back to 4096 only on memory admission refusal. +The admitted wide workspace uses chunks of at most 4096 rows while another stream decodes. +An explicit step keeps the parent's parsing and disables this automatic choice. + +`tf-dsv41-run` also honors an explicit step, using the existing lenient parser and recording `workspace_rows`. +Its unset diagnostic default remains 15872 rows; the server's automatic admission policy above is unchanged. + +The Metal MTP proposal has four draft-token slots. `TF_DSV41_MTP_DEPTH_MAX` defaults to three and is capped at four. + ## Pull behind a proxy `tensorfold pull` reads the proxy variables the Hugging Face CLI reads: `HTTPS_PROXY` for https requests, @@ -254,6 +276,52 @@ These settings retain their existing boolean policies rather than gaining new al and the tool-only sampling settings of the MTP check and the `FZ_` developer switches keep their semantics. The fabric/tp config helper keeps its runtime-name lookup instead of gaining a startup row: it carries the lenient switches above and transport names read only by tools, which no server would set. +- The DeepSeek-V4.1 lane's existing experimental and diagnostic switches keep their own readers + (presence, exact `0`, or lenient numeric parsing), so they are listed here rather than gaining refusals: + `TF_DSV41_CONE_CHECK` (a comma-separated list of diagnostic prompt sizes), + `TF_DSV41_ATTN_COUNT`, `TF_DSV41_ATTN_COUNT_LAYERS`, `TF_DSV41_ATTN_DENSE_VALUES`, `TF_DSV41_ATTN_PROF`, `TF_DSV41_ATTN_PROF_LAYERS`, + `TF_DSV41_ATTN_SPLITS`, `TF_DSV41_BATCH`, `TF_DSV41_BATCH_DEBUG`, `TF_DSV41_BLOCK_FILTER`, + `TF_DSV41_BLOCK_PROF`, `TF_DSV41_CLEAR_PARTIALS`, `TF_DSV41_CLEAR_STALE`, `TF_DSV41_CONCURRENT`, `TF_DSV41_COND_NOALIGN`, + `TF_DSV41_COND_NOROPE`, `TF_DSV41_COND_ONE`, `TF_DSV41_COND_PROF`, `TF_DSV41_COND_ROWS`, `TF_DSV41_CPU_HASH`, + `TF_DSV41_DENSE_COL`, `TF_DSV41_DENSE_COL_SPEC`, `TF_DSV41_DOUBLE_ATTN_COMPRESSOR`, `TF_DSV41_DOUBLE_ATTN_DENSE`, `TF_DSV41_DOUBLE_ATTN_INDEXER`, + `TF_DSV41_DOUBLE_ATTN_MERGE`, `TF_DSV41_DOUBLE_ATTN_NORM`, `TF_DSV41_DOUBLE_ATTN_PACK`, `TF_DSV41_DOUBLE_ATTN_POOL`, `TF_DSV41_DOUBLE_ATTN_PUBLISH`, + `TF_DSV41_DOUBLE_ATTN_QKV`, `TF_DSV41_DOUBLE_ATTN_SCAN`, `TF_DSV41_DOUBLE_ATTN_SCANX`, `TF_DSV41_DOUBLE_ATTN_WOA`, `TF_DSV41_DOUBLE_CLEAR`, + `TF_DSV41_DOUBLE_COMBINE`, `TF_DSV41_DOUBLE_COND_PROWS`, `TF_DSV41_DOUBLE_COND_WKV`, `TF_DSV41_DOUBLE_DENSEKV`, `TF_DSV41_DOUBLE_ENGRAM`, + `TF_DSV41_DOUBLE_EXPERTS`, `TF_DSV41_DOUBLE_FINISH`, `TF_DSV41_DOUBLE_HC_EXPAND`, `TF_DSV41_DOUBLE_HC_SPLIT`, `TF_DSV41_DOUBLE_HEAD`, + `TF_DSV41_DOUBLE_INDEX`, `TF_DSV41_DOUBLE_INDEX_W`, `TF_DSV41_DOUBLE_KEYS`, `TF_DSV41_DOUBLE_MERGE`, `TF_DSV41_DOUBLE_MLP`, + `TF_DSV41_DOUBLE_ROPE`, `TF_DSV41_DOUBLE_SCORE`, `TF_DSV41_DOUBLE_SPARSE`, `TF_DSV41_DRAFT_COPY`, `TF_DSV41_DRAFT_OFF`, + `TF_DSV41_DRAFT_OFF_AFTER`, `TF_DSV41_DRAFT_OFF_BELOW`, `TF_DSV41_DRAFT_OFF_GATE_CTX`, `TF_DSV41_DRAFT_OFF_SAMPLE_LOW`, `TF_DSV41_DRAFT_PUBLISH`, + `TF_DSV41_DSPARK_CAPTURE_ALL`, `TF_DSV41_DSPARK_CHUNK_ALL`, `TF_DSV41_DSPARK_COND_ONE`, `TF_DSV41_DSPARK_NO_CHUNK_MASK`, `TF_DSV41_DSPARK_NO_COND`, + `TF_DSV41_DSPARK_NO_RING_ROPE`, `TF_DSV41_DSPARK_NO_ROPE`, `TF_DSV41_DSPARK_POS1`, `TF_DSV41_DSPARK_SCALE1`, `TF_DSV41_DSPARK_TRUE_POS`, + `TF_DSV41_DUMP_SELECT`, `TF_DSV41_DUMP_SELECT_REF`, `TF_DSV41_END_MARK`, `TF_DSV41_ENGRAM_ADAPT`, `TF_DSV41_ENGRAM_CACHE`, + `TF_DSV41_ENGRAM_LARGE`, `TF_DSV41_ENGRAM_LATCH`, `TF_DSV41_ENGRAM_MMAP`, `TF_DSV41_ENGRAM_NOCACHE`, `TF_DSV41_ENGRAM_PEND`, + `TF_DSV41_ENGRAM_PF`, `TF_DSV41_ENGRAM_PIPE`, `TF_DSV41_ENGRAM_POS_THREADS`, `TF_DSV41_ENGRAM_SMALL_THREADS`, `TF_DSV41_ENGRAM_STAGE_HASH`, + `TF_DSV41_ENGRAM_STREAM_DIR`, `TF_DSV41_ENGRAM_THREADS`, `TF_DSV41_ENGRAM_TRACE`, `TF_DSV41_EXL3_FMA`, `TF_DSV41_EXL3_FMA_DENSE_MULTI`, + `TF_DSV41_FAST_ARGMAX`, `TF_DSV41_FMA_WARPS`, `TF_DSV41_FUSE_UP_SIX`, `TF_DSV41_GATE_DUMP`, `TF_DSV41_GATE_DUMP_ROWS`, + `TF_DSV41_GATE_TREE`, `TF_DSV41_GATE_WIDE`, `TF_DSV41_GROUP_MIN_ROWS`, `TF_DSV41_HC_PROBE`, `TF_DSV41_HC_PROBE_INDEP`, + `TF_DSV41_HC_PROBE_THREADS`, `TF_DSV41_HID_FULL`, `TF_DSV41_HID_HASH`, `TF_DSV41_HID_ROWS`, `TF_DSV41_HOST_PROF`, + `TF_DSV41_I8_DIR`, `TF_DSV41_I8_ONLY`, `TF_DSV41_I8_PREFILL`, `TF_DSV41_I8_ROT`, `TF_DSV41_INDEX_KEYS`, + `TF_DSV41_INDEX_KEYS_SCORE`, `TF_DSV41_INDEX_PARALLEL_FINISH`, `TF_DSV41_INDEX_PARALLEL_MERGE`, `TF_DSV41_INDEX_ROW_SCORE`, `TF_DSV41_INDEX_SCORE_ONE`, + `TF_DSV41_INDEX_SELECT_ONE`, `TF_DSV41_INDEX_SELECT_ONE_ROWS`, `TF_DSV41_INDEX_SELECT_V`, `TF_DSV41_INDEX_SERIAL_MERGE`, `TF_DSV41_INDEX_WARPS`, + `TF_DSV41_KROW_CHECK`, `TF_DSV41_LAYER_CB`, `TF_DSV41_LOGIT_DUMP`, `TF_DSV41_LOOKUP_DRAFTS`, `TF_DSV41_MTP_ADAPT`, + `TF_DSV41_MTP_ADAPT_CONFIRM`, `TF_DSV41_MTP_ADAPT_DEBUG`, `TF_DSV41_MTP_ADAPT_DOWN`, `TF_DSV41_MTP_ADAPT_RATCHET`, `TF_DSV41_MTP_ADAPT_SIGNAL`, + `TF_DSV41_MTP_ADAPT_UP`, `TF_DSV41_MTP_ADAPT_WARM`, `TF_DSV41_MTP_DEBUG_LOGITS`, `TF_DSV41_MTP_DEBUG_ROWS`, `TF_DSV41_MTP_DEBUG_TOP`, + `TF_DSV41_MTP_DEPTH_MAX`, `TF_DSV41_MTP_DRAFT_ROWS`, `TF_DSV41_MTP_PIPE`, `TF_DSV41_MTP_ROPE_ALL`, + `TF_DSV41_MTP_ROWS`, `TF_DSV41_MTP_STOP`, `TF_DSV41_MTP_STUB`, `TF_DSV41_MTP_STUB_BLOCKS`, `TF_DSV41_MTP_STUB_COND`, + `TF_DSV41_MTP_STUB_HEAD`, `TF_DSV41_MTP_TRUNK_RING`, `TF_DSV41_NAX_MIN_ROWS`, `TF_DSV41_NO_COND_WKV_FUSE`, `TF_DSV41_NO_ENGRAM_FLUSH`, + `TF_DSV41_NO_FUSE_DRAFT_WO_A`, `TF_DSV41_NO_FUSE_KVGLUE`, `TF_DSV41_NO_FUSE_MOE_UP`, `TF_DSV41_NO_FUSE_QKV`, `TF_DSV41_NO_FUSE_SHARED`, + `TF_DSV41_NO_FUSE_SHARED_ROT`, `TF_DSV41_NO_FUSE_WO_A`, `TF_DSV41_NO_GATE_UP_FUSION`, `TF_DSV41_NO_HC_BOUNDARY`, `TF_DSV41_NO_INDEX_NAX`, + `TF_DSV41_NO_MARKOV`, `TF_DSV41_NO_REFEED`, `TF_DSV41_NO_SWIGLU_ROT`, `TF_DSV41_NO_TAIL_SNAP`, `TF_DSV41_PARTIAL_TXN`, + `TF_DSV41_PEN_DEBUG`, `TF_DSV41_PIPE_LAYERS`, `TF_DSV41_PREFILL_STEP`, `TF_DSV41_PROFILE_GPU`, `TF_DSV41_RESUMED_TAIL`, + `TF_DSV41_RING_KEEP`, `TF_DSV41_ROUTE_DEBUG`, `TF_DSV41_ROUTE_DEBUG2`, `TF_DSV41_ROUTE_DEBUG3`, `TF_DSV41_ROUTE_DEBUG4`, + `TF_DSV41_ROUTE_DEBUG5`, `TF_DSV41_ROUTE_DUMP`, `TF_DSV41_ROUTE_GEMM`, `TF_DSV41_ROUTE_GEMM_MINROWS`, `TF_DSV41_ROUTE_GEMM_PRIVATE`, + `TF_DSV41_ROUTE_GEMM_SCRATCH`, `TF_DSV41_ROUTE_HIST`, `TF_DSV41_ROUTE_IDS`, `TF_DSV41_ROUTE_TENSOR`, `TF_DSV41_SCAN_PROBE`, + `TF_DSV41_SCAN_TWICE`, `TF_DSV41_SELECT_TWICE`, `TF_DSV41_SHARED_DENSE`, `TF_DSV41_SKIP_ATTN`, `TF_DSV41_SKIP_COMBINE`, + `TF_DSV41_SKIP_DENSEKV`, `TF_DSV41_SKIP_ENGRAM`, `TF_DSV41_SKIP_EXPERTS`, `TF_DSV41_SKIP_HC_EXPAND`, `TF_DSV41_SKIP_HC_SPLIT`, + `TF_DSV41_SKIP_INDEX`, `TF_DSV41_SKIP_MERGE`, `TF_DSV41_SKIP_MHC`, `TF_DSV41_SKIP_MOE`, `TF_DSV41_SKIP_SELECT`, + `TF_DSV41_SKIP_SHARED`, `TF_DSV41_SKIP_SPARSE`, `TF_DSV41_SKIP_SWIGLU`, `TF_DSV41_SNAP_COLD`, `TF_DSV41_SNAP_HASH`, + `TF_DSV41_SPARSE_MERGE_SPLIT`, `TF_DSV41_STAGE_CB`, `TF_DSV41_TAPS`, `TF_DSV41_TAPS_SHARED_BASE`, `TF_DSV41_TREE_PRICE` + The profile registry reports selected arithmetic/experimental overrides; it does not change their parsing or defaults. 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. diff --git a/docs/kernel-contract.md b/docs/kernel-contract.md index 55b60422ca8..dc3c704a00c 100644 --- a/docs/kernel-contract.md +++ b/docs/kernel-contract.md @@ -61,8 +61,10 @@ Direct `one` callers remain responsible for cleanup. 5. Limits. Every registered launch against each chip we serve, from its declaration and recorded compiles, so this part runs with no GPU in `zig build test`. Metal: threads a group and threadgroup bytes against M1 to M5; on M1 and M2 a pipeline's thread limit falls as its registers rise (simd_qmm_bits' 8-bit tiles compile for 224), so every launch - records its M1/M2 limit, unless its launcher sizes its groups to the pipeline or its source reserves the threads. A - tensor-op kernel, which cannot be built for M1/M2 ahead of time, stays at 256 threads. CUDA: registers a thread + records its M1/M2 limit, unless its launcher sizes its groups to the pipeline or its source reserves the threads. + A tensor-op kernel served on those chips but not buildable offline stays at 256 threads. `min_gen` records an + engine-enforced generation boundary; earlier chips are explicitly skipped, not reported as qualified. It defaults + to M1 (13); the EXL3 tensor-unit-only projection paths start at M5 (17). CUDA: registers a thread (rounded per warp), static plus dynamic shared bytes, launch bounds and clusters against sm_80, sm_86, sm_89, sm_120 and sm_121. HIP: VGPRs a wave (a workgroup's waves spread over the WGP's four SIMDs, each rounded to the chip's allocation step), static plus dynamic LDS bytes, the kernel's `__launch_bounds__` and its wave size against gfx1030, diff --git a/docs/optimization-ledger.md b/docs/optimization-ledger.md index f87341fe5c5..3caab396bc1 100644 --- a/docs/optimization-ledger.md +++ b/docs/optimization-ledger.md @@ -91,7 +91,7 @@ last two hold the families with only a Metal, HIP or scoring backend. | Optimization | kol1 | spk25 | dory | mm3 | dsv41 | | --- | --- | --- | --- | --- | --- | -| 1. Prompt tail | yes | yes | yes | yes | yes | +| 1. Prompt tail | yes | yes | yes | yes | open M EXL3 [cone follow-up](deepseek-v41.md#exl3-optimization-follow-up) | | 2. Paged KV | done [#1620] | done [#1653] | done [#1284] | yes | yes (own pool) | | 3. Prompt store | done [#1755] | done [#1756] | done [#2430] | yes | yes | | 4. iGPU states | done¹ | done¹ | done¹ | done¹ | yes | @@ -101,7 +101,7 @@ last two hold the families with only a Metal, HIP or scoring backend. | 8. Disk cache | yes | done [#3135] | done [#3135] | yes | done¹ | | 9. FP8 KV | yes | yes | yes | yes | no (FP8 by design) | | 10. FP4/FP8 decode | failed [#1448] | no (bf16) | yes | no (EXL3) | yes | -| 11. Fused proj. | done¹ | done [#1783] | yes | done¹ | done¹ | +| 11. Fused proj. | done¹ | done [#1783] | yes | done¹ | done¹; open M EXL3 [chains](deepseek-v41.md#exl3-optimization-follow-up) | | 12. Add + norm | done¹ | done¹ | done [#1256] | done¹ | done M[#1714] ? C | | 13. MoE grouped | done¹ | no (dense) | no (dense) | done [#1388] | done M[#1707] | | 14. CUDA graphs | done¹ | done¹ | done¹ | yes | done¹ | @@ -110,7 +110,7 @@ last two hold the families with only a Metal, HIP or scoring backend. | 17. DSpark | yes | yes | yes | done¹ | done [#1751] | | 18. Copy drafts | done [#2022] | done [#2022] | done [#2022] | done [#2022] | done¹ | | 19. Shared drafts | no (copies) | no (copies) | no (copies) | done [#1426] | done¹ (opt-in) | -| 20. Solo chunks | yes | yes | yes | yes | done M[#2950] | +| 20. Solo chunks | yes | yes | yes | yes | done M[#2950] EXL3 [load-aware chunks](deepseek-v41.md#exl3-optimization-follow-up) | | 21. Read-ahead | done [#2033] | done [#2033] | yes | done [#2033] | done [#2033] | | 22. Direct load | yes | done [#2449] | done [#2449] | yes | open [#1924] | | 23. Page drop | done [#1884] | done [#1884] | done [#1884] | done [#1884] | done [#1884] | diff --git a/docs/receipts/dsv41-exl3-metal/README.md b/docs/receipts/dsv41-exl3-metal/README.md new file mode 100644 index 00000000000..b9062a0e785 --- /dev/null +++ b/docs/receipts/dsv41-exl3-metal/README.md @@ -0,0 +1,549 @@ +# EXL3 Metal follow-up qualification + +This is a follow-up to [#2373](https://github.com/ashhart/TensorFold/pull/2373), not release qualification. +The parent is `bec140d545aa50b765f26cf295b43179c6b2834f`. +The initial served comparison used `e070123319b69e73c969b91409dd7195fbbef93e` production sources and +`128cfe743a76f59b350d0c750a12669708029ff3` qualification fixtures. +Projection contracts and the first batched-head repair were recorded at `6aa834fdb4c58192a21a31524a5bf298b7b7ecec`. +Later attention repairs change numerical results: the earlier served hashes and timings are historical, not final qualification. +[fidelity-128.json](fidelity-128.json) identifies the repaired capture's production files by SHA256. + +The [maintainer's parent review](https://github.com/ashhart/TensorFold/pull/2373#issuecomment-6730527087) +still disputes code provenance and lists integration gates. This dependent delta does not establish the parent's copy-rule compliance. + +[environment.json](environment.json) records the checkpoint metadata fingerprints, source revision, build settings +and hardware: **M5 Ultra, 64 GPU cores, 256 GiB**, not the parent's historical 80-core machine. +The pack is pinned to `45ee5d0fd106c94a3d77f721e09cbb2f50e5a16b`. +[model-fingerprints.json](model-fingerprints.json) binds all 39 weight shards, both streamed source shards, +the pack/source metadata and tokenizers, the chat template and the generated token map. + +## Checks already exercised + +- `zig build test-lane-api-host -j4 --summary all`: 545 passed. +- The initial host EXL3 and environment checks passed (environment 12/12); a temporary `xcrun` shim blocked native + compilation. With the real Metal 27.2.47 compiler, M4 native checks subsequently passed 118 tests with 3 skips. +- On the M5, `zig build native test-exl3 test-environment-host test-native test-deepseek-v41 + -Dcpu=apple_m1 -Doptimize=ReleaseSafe -j8 --summary all` at `59535dad914819ea4d281f87c81a138c4f2c4e1b`: + the family GPU target passed 73/73, EXL3 host checks passed, and environment checks passed 12/12. + The combined command failed because the native cone diagnostic imported an excluded transport module. +- After removing that dependency and making cone mismatches fail closed, `zig build native test-native + -Dcpu=apple_m1 -Doptimize=ReleaseSafe -j8 --summary all` at the serving revision passed: + 69/69 build steps, 118 tests passed, 3 skipped. +- An actual `GLM_LOAD_LIMIT_GB=1` candidate startup refused both workspace sizes with `LoadLimitExceeded`, exit 1, + without an allocator abort. The wide plan requested 217556406008 bytes and the narrow plan 214737522424 bytes. +- At the common four-slot, 32768-context geometry with `GLM_LOAD_LIMIT_GB=240`, the parent default workspace + refused admission: 235727027864 resident bytes plus 8589934592 margin exceeded the 230553780224-byte allowance. + The comparison therefore pins **4096 workspace rows in both arms** instead of raising the machine's limit. + +The 73-test family record predates the final core fallback fix. On the qualification tree `128cfe743a`, +`zig build test-exl3-gpu -Dcpu=apple_m1 -Doptimize=ReleaseSafe -j8 --summary all` returned +**36 passed, 3 failed, 39 total; exit 1**; the parent returned **21 passed, 6 failed, 27 total; exit 1**. +The three failures, which also fail on the parent, were these tests in `zig/src/core/exl3_projection_gpu_test_decode.zig`: + +| Failure | Test | Line | +|---|---|---| +| mixed-width routed/dense bit parity | `GPU router descriptors select mixed-width experts with gather and scatter without host routing` | 135 | +| packed-sign filtered/dense BF16 parity | `packed signs and GPU expert filtering preserve untouched output slots` | 182 | +| grouped/scattered versus separate projection bit parity | `caller-prepared grouped expert tiles preserve scatter slots and ignore padding` | 280 | + +Their assertions have not changed since; the projection-order repair below makes all three pass. +Current results are under "Projection suites at the current head". +The indexed odd/wide scalar-reference check, tiled/table bit checks and new chain/MoE fusion checks pass. +The final native rebuild passed 66/66 build steps. Raw build/server logs are not published because they contain +local filesystem paths; [operator-checks.json](operator-checks.json) records the scoped outcomes. +Both historical served revisions reported a 16-byte allocator leak on shutdown. The backend now frees its per-slot +`last_depth` allocation, and the allocator regression passes; final served shutdown with explicit drafts remains a separate gate. + +## Reproduce the served comparison + +Use separate checkouts at the parent and serving revisions, the same pack and original Engram tables, Zig 0.17.0, +an installed Metal compiler, and Python 3.10 or later. Build each with: + +```sh +zig build native -Dcpu=apple_m1 -Doptimize=ReleaseSafe -j8 +python3 docs/receipts/dsv41-exl3-metal/prompts.py /tmp/exl3-prompts +``` + +Run the prompt generator from the candidate checkout; the parent does not contain it. +Run only one server at a time. For each checkout, use this common command; on the candidate add +`TF_DSV41_CONE_CHECK=4096,16384` to run full/cone logits, cursor and rollback checks before readiness. +The checker restores the configured cone mode afterwards; any mismatch fails startup. + +```sh +GLM_LOAD_LIMIT_GB=240 TF_DSV41_PREFILL_STEP=4096 \ +./zig-out/native/bin/tensorfold-native serve \ + --engram-stream-dir --chat-template /chat_template.jinja \ + --context 32768 --parallel 4 --prompt-cache-gib 0 \ + --host 127.0.0.1 --port 8941 --name exl3-qualification --keep-warm 0 +``` + +Once `/v1/models` is ready, run the existing client from a checkout containing it; set `ARM=base` or `ARM=candidate` +for the currently running server: + +```sh +python3 tools/bench_concurrent.py http://127.0.0.1:8941 exl3-qualification \ + --tokens 64 --reps 1 --temperatures 0,1.0 --levels 1,4 --alone --serial \ + --prompts /tmp/exl3-prompts/short-prompts.json --label "$ARM-short" --output "$ARM-short.json" +python3 tools/bench_concurrent.py http://127.0.0.1:8941 exl3-qualification \ + --tokens 64 --reps 1 --temperatures 0 --levels 1,4 --alone --serial \ + --prompts /tmp/exl3-prompts/long-prompts.json --label "$ARM-long" --output "$ARM-long.json" +``` + +The client can finish without rejecting unequal tokens. Require complete full-token hashes and compare both arms: + +```sh +python3 tools/bench_exl3_compare.py base-short.json candidate-short.json +python3 tools/bench_exl3_compare.py base-long.json candidate-long.json +``` + +## Formal projection and batched-state checks + +On the same 64-core M5, the projection contract passed 219 width/codebook registrations over 13 entrypoints: +all gates 1–4 passed, with 876/876 real GPU fault controls caught and no known findings. +The fixtures compare every output column to independently scalar-decoded FP64 rows and require the replaced +sixteen-warp reduction's exact bytes. KU2 prompt tiles additionally equal the KU1 template's bytes. +Structured full-sized matrices vary three K bands independently; precision plants repeat a random decoded tile. +The reported FP64 worst column and squared error are retained separately for each shape and comparator. +The native grouped-output bindings use 344 named `wo_a.slice` matrices: eight per backbone/DSpark block. +They are 4096-by-1024 dots (320 at ten half-bits, 24 at eight), already included in the geometry list; +joining the eight groups does not introduce a different unqualified reduction width. + +```sh +zig build tf-kernel-contract -Dcpu=apple_m1 -Doptimize=ReleaseSafe -j8 +./zig-out/bin/tf-kernel-contract --only exl3-metal --no-limits +./zig-out/bin/tf-kernel-contract --only exl3-metal --no-gates --offline /tmp/exl3-offline +``` + +The separate resource run passed all 13 live launches, with zero limit problems and both resource controls caught. +These projection pipelines are selected only with M5 tensor units; M1/M2 projections are explicitly unserved, +not claimed to have passed offline or runtime checks there. The offline resource controls did run. +`zig build test-exl3-contract-host test-kernel-contract -Dcpu=apple_m1 -j4 --summary all` +passed 232/232 host tests in 33/33 build steps. + +Finite packed-key fixtures exposed a batched split-merge bug at 16 heads: the merger retained the 64-head defaults. +It now receives the actual head count and width. The same test checks four independent slots at 16, 32 and 64 heads, +including wrapped/long positions, both RoPE directions, KV glue and publication against the per-slot path. +`zig build test-deepseek-v41-rows -Dcpu=apple_m1 -Doptimize=ReleaseSafe -j8 --summary all` +failed before the repair and then passed 6/6 tests in 41/41 build steps. +The fixture excludes E4 NaN codes from its finite-data leg and explicitly requires finite attention outputs. + +The M4 source-built suite found a separate shared-down fusion mismatch: a separate dense call uses split sums, +while joining it to routed rows selects an unsplit body. Shared-down merging now requires the qualified +sixteen-warp FP32 path for both calls; other devices, row counts and incompatible knobs keep separate calls. +The focused `test-exl3-moe` run on M4 passed 3 tests and skipped the unserved merged-down path (4 total). +The full M4 run before this eligibility repair was 35 passed, 4 failed; three are the inherited parity failures above. +The focused M5 `test-exl3-moe` run passed 4/4 tests, including the merged-down path. +On M4, `test-deepseek-v41-lifetime` passed 2/2 tests in 43/43 build steps: backend host-state release and real Metal +draft-ID capacity growth without corrupting pending Markov picks. It does not prove a served MTP shutdown. + +The later projection-order repair passes `test-exl3-gpu` on M4: **38 passed, one unserved tensor-path skip**. +The fused-QKV target also passes both tests, with **1792/1792 output cells bit-identical** to separate projections. +Indexed scalar windows now use the same split order and sufficient scratch as dense calls, with per-descriptor +column bounds. A scratch-size assertion tied to the previous allocation formula was removed; numerical bounds +and the valid parity assertions were not changed. M5 validation of the sixteen-warp path is recorded separately. +The M5 standalone suite passes **39/39**, and its fused-QKV target passes **2/2** with all 1792 cells exact. +The expanded tensor-unit contract covers every valid width/codebook tuple for the dense base and multi-row bodies: +**261 registrations pass gates 1–4; all 1044 planted controls are caught, with zero real failures or known findings**. +The static-specialized variants retain their narrower registered domain. + +The scalar split-window shader is registered separately on both M4 and M5: **27 registrations and 108 planted +controls pass gates 1–4 per chip**. Together, the M5 tensor and scalar projection suites cover **288 registrations, +14 entrypoints and 1152 caught numerical controls**. No numerical tolerance was relaxed. +Scalar gate 5 passes with 32 launch threads, 1536 threadgroup bytes and a live 1024-thread limit on both chips. +The actual M1/M2 offline compiler also reports 1024 for this body; that is not M1/M2 runtime qualification. +Final integrated M5 projection/chain/native checks pass 47/47 tests in 63/63 build steps. Their resource checks +report no findings; each limits run catches both real oversized-resource controls. + +#### Projection suites at the current head + +`zig build test-exl3-gpu test-deepseek-v41 -Dcpu=apple_m1 -Doptimize=ReleaseSafe -j8 --summary all` at `bab2613de8`: + +| Machine | `test-exl3-gpu` | `test-deepseek-v41` | +|---|---|---| +| M5 Ultra, 64 GPU cores | 41 passed, 0 skipped | 74 passed, 0 skipped | +| M4 Pro, no tensor units | 40 passed, 1 skipped | 70 passed, 4 skipped | + +At #3736's head `e880b33471` the M5 Ultra runs pass 41/41 and 77/77, with no skips. +Every M4 skip is a tensor-unit path that M4 never selects, so the M4 runs say nothing about the tensor path: + +- `the shared expert's down inside the routed down call keeps every bit of the two separate calls`: the merged shared-down + call is taken only when the tensor-unit decode pipelines exist (`canMergeDenseRows`); +- `the decode chain is bit-identical on a concurrent encoder`; +- `the tensor-unit prompt kernel matches the scalar kernel on constant keys` and `... on random packed keys`; +- `batched decode windows match the per-slot chain bit for bit` (`attention_rows_test.zig`, gated on `device.tensorUnits()`). + +The M5 Ultra runs execute all of them. The two prompt-kernel tests are tolerance tests, not exactness tests: on the +M5 Ultra the tensor-unit sparse prompt kernel matches the scalar kernel on 257024 of 262144 outputs (98.05%) with +constant keys, worst relative error 7.7e-3, and on every output with random, huge and tiny keys; the bounds are 98% +and 0.02. No exactness claim is made for that kernel. + +## Chain contract on M4 + +The eight chain/MoE entrypoints pass the same gates 1–4 on an M4 Pro: + +```text +SUMMARY 8 kernels: 8 pass gates 1-4, 0 fail, 0 known; 34 controls: 34 red, 0 missed +``` + +```sh +zig build test-exl3-chain-contract test-exl3-chain-host \ + -Dcpu=apple_m1 -Doptimize=ReleaseSafe -j4 --summary all +``` + +The source-only runner uses the shared kernel-contract harness, without unrelated bundled shader dependencies. +It checks exact unfused GPU outputs, FP64 classes, explicit activation rounding, all three accumulator replay orders, +input immutability, guards and untouched padding. Cases include 384 experts, six picks plus shared rows, full +32768-column outputs, grouped output rotation, in-place RMS and independent long RoPE positions. +FP16/BF16 Hadamard and ordered-combine plants miss by at least 256 times the declared bound; +separate rounded-norm controls are caught by the exact unfused comparison. +The BF16 midpoint/subnormal oracle and accumulator plants also passed two host tests. +M4 reflection reports 1024 maximum threads for all eight pipelines; static threadgroup storage is 32 bytes for RMS, +4144 for down-combine, 2592 for QKV, and zero for the other five. +The M5 chain run also passed all eight registrations and 34 controls, with the same live resource limits. +The resource pass measured M1/M2 compiled maxima: 832 for out/in rotation, 928 for RMS and 1024 for the other six. +RMS launch sizing adapts to its pipeline limit. Both offline resource controls were caught; no M1/M2 runtime numeric claim is made. + +The earlier CUDA host subset passed 5540 tests with 32 skips in 345/345 build steps, before the new chain launch records. +The current source is checked again after the final-row repair: **345/345 steps**, **131 reported passed tests**, +with unchanged work cached. This is the device-free `test-cuda-host` target on M5/macOS, not CUDA GPU execution or Linux-runtime qualification. + +## Native batched rotation and packed-cache contract on M4 + +The native batched RoPE, KV-glue and ring-publication entrypoints pass gates 1–4, with separate forward/inverse +rotation registrations: **4 passed, zero failures or known findings; 13/13 actual GPU fault controls caught**. +`zig build test-deepseek-v41-rows-contract -Dcpu=apple_m1 -Doptimize=ReleaseSafe -j4 --summary all` +passed 4/4 tests in 4/4 build steps without requiring unrelated offline-compiled shaders. + +The exact per-slot GPU comparisons cover 1–8 slots, 16/32/64 heads, padded strides and positions through 1048575. +Publication permutes the indirect ring addresses and checks each complete ring image, including all untouched slots. +Packed non-finite inputs retain the per-slot byte encoding; raw cache bytes are not claimed to propagate IEEE classes. +The FP16 norm plant misses by 1398101 times the bound across all three replay orders. No BF16 separation is claimed +for that plant: balanced positive-square sums can be exact, and FP8 storage hides small norm errors. +M4 reflection reports 1024 maximum threads for each entrypoint and static storage of 0/32/0 bytes respectively. +The M5 rotation/KV run also passed all four registrations and 13 controls, with the same live limits. +The resource pass measured 1024 compiled threads for all three entrypoints on both M1 and M2, with zero limit problems. +The native attention runner compiles separately on M4 and correctly skips its unserved tensor-unit test. +`test-deepseek-v41-attention-rows-host` passed two independent decoder/precision-plant tests in 3/3 build steps. + +## Native attention and whole-model fidelity + +The M5 dense/scan contract passes eight registrations and all 34 real GPU controls. +Cases cover 1–8 slots, 16/32/64 heads, independent positions, indirect owner planes and both split-merge launch forms. +The exact per-slot baseline is paired with independent packed-code classes and an FP32 value-cancellation oracle. +M5 reflection reports 1024 threads for both entrypoints and 0/8448 bytes of static threadgroup storage. + +The cancellation oracle exposed a real bug in both scan bodies: the final 32-key tile could cross `j_end`, +so adjacent splits counted some keys repeatedly. Both now mask at the split boundary, including the per-slot baseline. +Two controls restore the old predicate and reproduce the failures at 32 and 8 splits. +Reserved E4M3 NaN codes and NaNs passed through BF16 rounding now retain their non-finite class. +The fixture's own dense decoder also needed braces to bind its `else` to the visibility test rather than the inner loop. +No tolerance was widened. + +The full 128-token check is still **failing**, despite the attention repair: + +| Measure | Before repair | After repair | +|---|---:|---:| +| NRMS against independent FP64 | 0.279974 | 0.172070 | +| Ratio to the fixed FP32/FP64 floor | 1.854916 | 1.140019 | +| Mean KL | 0.099111 | 0.062856 | +| Worst-row KL | 1.502481 | 2.151304 | +| Greedy disagreements | 7/128 | 6/128 | +| Execution-time disk reads | 4096 bytes | 0 bytes | + +The clear/review boundaries remain 1.05/1.10; 1.140019 fails. Some remaining disagreements have substantial reference +margins, so they are not dismissed as ties. The original full FP32 and FP64 CPU captures are reused explicitly: +their equations, checkpoint and 128-token history are unchanged, and the floor's input/logit hashes were verified. +An offline comparator reproduces the original native NRMS and mean KL within 1e-10 before assessing the repaired GPU capture. +The GPU-only command's exit 0 is not a numeric verdict. Full source fingerprints, margins and memory scope are in +[fidelity-128.json](fidelity-128.json). CPU-interleaved and contiguous GPU timings are not a controlled speed comparison. + +A later full 128-token replay after the projection-order repair gives the same fidelity metrics and six disagreements. +Its residency gate fails: **4096 execution-time disk bytes, zero pageins**. The earlier zero-read window is retained +as historical evidence, not substituted for this result. Neither model qualification nor publication is cleared. + +The comparator now also runs the actual #2373 parent, `bec140d545aa50b765f26cf295b43179c6b2834f`: +all 4695 production-source files were checked byte-for-byte against that tree. The parent reproduces the table's +before-repair metrics; the candidate reproduces its after-repair metrics. Both retain the default 1048576-token +model context and run one teacher token per forward. Identical throwaway CLI harnesses reserve 128 workspace rows +instead of the unused 15872-row prefill capacity, which otherwise prevents the parent from fitting admission. +No production source or admission limit was changed for this control; the original refusal is preserved. +Both controlled execution windows read 4096 disk bytes and fail residency. The parent already fails the numerical +band; the candidate improves NRMS and mean KL but worsens worst-row KL, and still fails the unchanged band. +Teacher argmax differences are reported separately from the engine's own-path token-equality invariants. + +## Served trained MTP and ownership + +Draft embedding IDs grow for the requested arm before host writes without replacing pending Markov picks. +Model teardown releases Markov IDs, taps, conditioning and draft-logit scratch. The repaired scratch has one +error cleanup. Five directly executed lifetime cases cover host ownership, real Metal ID-buffer growth, trained-only +adaptive depth, committed-context suffix lookup and lookup precedence over a bound trained proposal. +The final M5 full corpus includes these cases; the matching policy fixtures also pass on M4. + +The adaptive cap no longer falls to zero merely because lookup is disabled. Lookup no longer keeps a second token +history: it borrows the stream's canonical committed context, including accepted windows and restored prefixes. +A real matching suffix now takes precedence over paying for a trained proposal, without bypassing the cost governor. +The served measurements below predate these final policy/context/selection repairs; they are not current-source speed claims. + +The first MTP-only served probe drafted nothing: backend capability admission incorrectly depended on lookup depth. +The repair reads the registered `TF_DSV41_MTP_DRAFTS` boolean once at model open and admits trained proposals when +DSpark weights exist, independently of lookup drafting. Proposal depth cannot exceed the four-ID proposal buffer. +The corrected run uses lookup unset, MTP and taps enabled, context 65536, four lanes and zero retained prompt cache. +The standard `bench_openai.py --tokens 256 --reps 3 --temperatures 0` command passes. +Twelve plain/drafted pairs (code completion and prose chat, greedy and temperature 0.8, three seeds) have identical +full token and output hashes. Eight c4 replies match their solo hashes; shared rounds remain plain by contract. +A cancelled stream does not change the following 256-token sampled-state-independent greedy reply. +There are no trained-proposer-unavailable warnings. + +This is **not a speedup**: greedy code accepts 3/10 proposals and decodes at about 51.60 tok/s versus plain 52.23; +prose accepts 6/10 and measures about 52.19 versus 52.20. The cost governor stops unsuccessful drafting after eight +rounds. Sampled code also loses throughput. The no-slowdown gate remains uncleared. +These token-equality checks do not clear the independent whole-model fidelity failure above. + +Two actual idle-unload cycles pass after drafter scratch ownership is repaired. The 256-token sampled reply's full +token and output hashes remain exact after reload; trained proposals are active before and after it. +Current physical footprint falls below 121 MB on both completed unloads, and graceful SIGTERM exits 0. +The probe waits for `/v1/load` to report `parked=true`, published only after engine close. HTTP 503 can precede +completed unload; lifetime-maximum footprint cannot measure released memory. Exact bytes are in `operator-checks.json`. + +## Cold default policy and retained native window + +The actual default-policy server passes `bench_cache.py --require-cold` at exactly **2048, 8192, 32768 and 65536 +input tokens**, with context 131072, four lanes, zero retained prompt cache, MTP off and no prefill-step override. +Each case has one first request, two repetitions and four concurrent requests; every reply has 256 tokens, +zero cached input tokens and identical full token/output hashes. Graceful shutdown exits 0. +The token arrays and exact request bodies are retained with the run. Timings and fixture/token SHA256 values +are recorded in `operator-checks.json`; this synthetic fixture is not a language-quality comparison. + +The fixture uses the pinned checkpoint's `tokenizer.json` through `tokenizers.Tokenizer.encode` with +`add_special_tokens=True`, repeats the following block 12000 times, then takes the first requested number of IDs: + +```text +A public GPU performance fixture. A matrix product combines rows and columns. Each independent request has its own token history, cache positions and reproducible seed. The benchmark measures prefill latency and exact repeated replies, not language quality. +``` + +Each block ends with a newline. For each array, the exercised command is +`bench_cache.py URL MODEL --tokens 256 --repeats 2 --streams 4 --prompt-file ARRAY.json +--expected-prompt-tokens N --require-cold --output RECEIPT.json`. + +The native server also admits context **1048576 with four lanes, a 2 GiB retained cache and trained MTP enabled**. +An 8192-token prompt restores 8064 cached tokens. Eight greedy/sampled plain-versus-drafted pairs, eight c4 replies +and the sampled reply following cancellation have exact full token/output hashes. +The original one-off probe exits 1 because it incorrectly demanded reuse for a 22-token prose prompt. +Existing cache rules require more than 4096 tokens for tail/end marks; those short requests correctly remain fresh. +The original HTTP records were checked against that eligibility rule without changing production code or thresholds. +The raw failed assertions remain recorded; they are not presented as a passing command. + +Before the final-row repair below, the requested corpus, native and diagnostic binaries, and five lifetime cases succeed: +**977/977 build steps**; the build reports **1603 passed and 53 skipped tests**, with other unchanged steps cached. +The preceding 973-step run reported 1529 passed and 53 skipped; the earlier 970-step run reported 11884 passed and +114 skipped before the final policy/context repairs. One QKV diagnostic has one differing cell out of 1792 and +passes the unchanged NRMS, mismatch-count and worst-error bounds; the earlier standalone exact fixture is not +a universal bit-exact claim. + +`tf-dsv41-run` honors an explicit `TF_DSV41_PREFILL_STEP` using the server's existing parsing semantics, +records the effective workspace rows, and retains its original unset default. The initial workspace-admitted +run then failed with `InvalidCounterSample`; deferred mHC was opening a span before encoding any work. +Spans now begin at the actual mHC encoding site. Invalid-sample checks remain unchanged. + +Before the final-row repair, the native-context 1048576, 16-workspace-row profile passes for **one input row**: +grouping on/off and profiled last logits are exact, with zero execution disk reads and zero page-ins in that invocation. +The two- and four-row commands fail **`ProfileChangedLogits`**; both report zero execution reads/page-ins. +Those negative results remain in `final_strict_profile_matrix`; they are not overwritten. + +The final fused expansion dispatched one row for `.last` without shifting its input/output views to the selected last row. +It expanded row zero, then the head collapsed a different, unexpanded row. All per-row views now select the requested row; +the kernel arithmetic, launch width and strict bit-equality assertions are unchanged, and no extra rows are computed. +The corrected two- and four-row full-model profiles **pass**, including exact grouped/ungrouped/profiled-last logits, +zero execution disk reads and zero page-ins. The one-row logits are also exact, but that invocation's independent +residency gate **fails**: 3,080,192 execution disk bytes and 45 page-ins. It is not a passing qualification command. +After the repair, the complete requested corpus is rebuilt: **977/977 steps**, **1588/1641 reported tests passed, 53 skipped**; +unchanged steps may be cached. The native and diagnostic binaries and five lifetime cases are included. +The fresh full 128-token GPU capture is byte-identical to the preceding matched capture, so the independently measured +**1.140019 band still fails the unchanged 1.10 bound**. This invocation also fails execution residency: +**154,669,056 disk bytes and 8,912 page-ins**. CPU references are explicitly reused, not recomputed or silently replaced. +The separate earlier 128-row fidelity and execution-read residency failures remain recorded above. + +Before the Sinkhorn repair below, the contribution's served path is checked at context **1048576**, four lanes and a 4 GiB retained cache: +**41 completed replies** retain full token/output hashes across plain/drafted, greedy/sampled and solo/shared paths. +An 8192-token request is cancelled after generated content; its following sampled reply matches the plain control. +Two actual idle unload/reload cycles preserve that sampled reply and release the model's bulk memory: +current process footprint falls from 226,962,856,920 / 222,969,100,760 bytes loaded to 147,244,328 / 149,833,024 bytes fully parked. +The parked flag and current footprint must both be observed; no lifetime-maximum RSS substitution is used. +With lookup disabled, real trained MTP proposes **370 tokens** and preserves the same full reply hashes. +Both mixed and trained-only servers exit gracefully. These current-source invariants do not waive the numerical band, +residency, source-matched no-slowdown, release or unavailable-chip/parent gates. + +### Fused Sinkhorn reduction-order repair + +The fused boundary used row XOR offsets 1,2 and column offsets 4,8, unlike the unfused split and pinned reference. +It now uses their FP32 butterfly order. An isolated retained-argument regression fails before the repair and passes +after it, with all 1728 FP32 pre/post/comb coefficients bit-identical to the unfused split and unchanged FP64 bounds. +The reference target reports **41 passed, 15 skipped of 56**. The complete requested build succeeds again: +**977/977 steps**, **422/435 reported tests passed, 13 skipped**; other unchanged work is cached. + +The unchanged full 128-token comparison now clears the numerical band: **0.967305**, below the existing 1.05 clear +boundary. Mean KL is **0.042165**, worst-row KL **0.832581**, with **five** teacher argmax differences; all margins +are recorded in [fidelity-128.json](fidelity-128.json). CPU reference files and thresholds are unchanged. +The command still exits 1 on **4096 execution disk bytes**, with zero page-ins. Strict one-, two- and four-row +profile commands all pass exact logits and zero-read/zero-page-in execution on this source. These short windows +do not replace the failed full-history residency result. Post-repair serving also passes 41 full-hash replies, cancellation recovery, +two real idle unload/reloads and trained-only lookup0 with 367 actual proposals; both servers exit0. These runs were under filesystem +tracing, not controlled performance measurements. The fused boundary's contract registration and the final tree's results follow. + +### Final qualification + +Environment: M5 Ultra (64 GPU cores, 256 GiB), macOS 27.0 (26A428), Xcode 27.1, Metal compiler 32023.921, Zig 0.17.0, +checkpoint `deepseek-ai/DeepSeek-V4.1-Flash-1017` at `1bae0e1088993b9b82de08f59de5be5a34e42170` as an EAQ v1 EXL3 2.9 bpw pack with the +original Engram shards; the M4 Pro (48 GiB, no tensor units) ran the kernel contract and the device-free checks. The code of the +head commit `a80eddd9a6` is the tree every result below names unless another tree is stated. Three earlier trees contributed: +`efdf7a464e` (the parent comparison, the cold prompt and decode comparison against the parent), `e9e06ee0b1` (the first drafter-log +change) and `dd80dd7164` (the settings sweep and the first resumed and 128k runs). `a80eddd9a6` differs from `dd80dd7164` by one +commit that removes three settings the sweep showed no benefit for; the code was then rebuilt and every M5 qualification below +except the sweep was repeated on it. + +- Build and test corpus on `a80eddd9a6`, M5 Ultra, `zig build test test-golden dev-tools native tf-dsv41-run + test-deepseek-v41-lifetime -Dcpu=apple_m1 -Doptimize=ReleaseSafe`: exit 0, **977/977 steps; 11392 of 11503 tests passed, 111 skipped**. + `zig build test-cuda-host`: 345/345 steps, 131 tests. +- Kernel contract, M5 Ultra: `--only dsv41` **102 kernels pass gates 1-4**, 237 controls red as planted, 0 missed; `--only exl3` + **296 kernels pass**, 1186 controls red as planted, 0 limit problems. The six dsv41 offline M1/M2 limit problems (`xp_quant`, `fp4pack`, + `fp4rt`, `hcmix`, `hcpost`, `joinpost`) are identical at the parent `bec140d545` (89 kernels pass there). The unfiltered contract + aborts in `metal_lfm3_attention_sums.zig:39` (integer overflow in `valuesDepth`), a file this delta does not touch, so it was not + completed. The exhaustive rotary sweep covers 302,008,320 cases. +- M4 Pro (no tensor units), the same build and test command plus `tf-kernel-contract` with `-j4`: exit 0, **979/979 steps; 11874 of + 11984 tests passed, 110 skipped**; `test-cuda-host` 345/345 steps, 131 tests. Kernel contract: `--only dsv41` 94 kernels pass, + 203 controls red as planted, 0 missed, the same six limit problems; `--only exl3` 35 kernels pass, 142 controls, 0 limit problems. +- The pull-request workflow's device-free steps, run locally on `a80eddd9a6` with `-Dfixed-cpu`: the bench, build-option and + flashnext unittests (90, 5 and 8 tests), `test-server-security test-pull-security`, `fuzz-cortheon`, `test-kernel-contract`, + `test-golden` and `test` all exit 0. `check-release-paths` fails with `file exists in modules 'tokenizer' and 'tokenizer0'` + (`zig/src/core/tokenizer/tokenizer.zig:1`); it fails the same way at the parent `bec140d545` and passes on `main`, so it is inherited. +- Strict one-, two- and four-row profiles return identical grouped and ungrouped logits and read 0 bytes with 0 page-ins in all + three runs (a first run and two warm reruns). The gate measures cache temperature at execution time; on `efdf7a464e` a first run + right after a build read 7.7 to 15.5 MB and failed it, then passed. A warm pass does not prove every Engram page is resident. +- The unchanged full 128-token comparison: band ratio **0.967305** (limit 1.10, clear at 1.05), mean KL 0.042165, worst-row KL + 0.832581, five teacher argmax differences; the parent's ratio is 1.855. +- Served checks: 33 plain, drafted and shared replies with equal full hashes, 41 completed responses, a cancelled 8192-token + request, two idle unload/reload cycles (loaded 226,960,252,128 and 222,895,034,360 bytes; parked 144,491,864 and 148,014,472), + trained-only lookup0 with 367 proposals. Greedy decode with drafts 95.2 tok/s against 52.5 plain, sampled 94.3 against 52.2. +- Resumed against fresh, `bench_cache.py --require-cold --require-reuse`, `--prompt-cache-gib 8`, a fresh server for each size: + the first request is cold and the next three reuse the cache (8064 of 8192 tokens; 32640 of 32768). Every reply has the token hash of + the cold run (`d782a1946504` and `7424b0c34a8e`, equal to the parent's cold replies). A 2048-token prompt is below the + cache's reuse size (`cached_tokens` is 0), so that size has no resumed arm. +- 128k, one lane, context 131072, 131008 prompt tokens, cold: first-token latency **56.1 s** for this head against **119.7 s** for + the parent, reply hashes equal (`db79fedfbfc5`); decode at that depth 45.9 against 36.3 tok/s. The parent was measured once, in the + run that accompanied `dd80dd7164`; its server exits with a leaked-allocation report from its own allocator at shutdown. +- Parent against this tree, same machine, 4096 workspace rows and prefill step 4096 in both arms, 64 tokens, three repetitions, + measured on `efdf7a464e`; the default arm of the settings table below, on `dd80dd7164`, reproduces these cells within 2%. Solo, + serial and concurrent hashes are equal inside each build. Tokens differ between the builds in long greedy decodes because the + arithmetic changed (the parent fails the band at 1.855), so `tools/bench_exl3_compare.py` refuses the pair and this is an + observation, not a no-slowdown qualification: + +| Cell | Parent tok/s | This tree tok/s | +|---|---|---| +| short, 1 stream | 40.6 | 52.5 | +| short, 4 streams, aggregate / steady | 43.5 / 61.0 | 59.0 / 93.9 | +| long, 1 stream | 38.5 | 49.1 | +| long, 4 streams, aggregate / steady | 6.1 / 58.1 | 11.1 / 88.4 | +| long TTFT max, 1 / 4 streams | 12.34 s / 48.87 s | 6.53 s / 26.47 s | + +- Cold prompt speed and decode, `bench_cache.py --require-cold` and `bench_openai.py`, context 70000, one lane, `--prompt-cache-gib 0`, + prefill step 4096 in both arms, one request per size with 16 reply tokens. The 16-token replies are token-equal between the + builds at every size; 256-token greedy decodes are not (both public prompts differ). The 2048 row of this head follows the decode + run on the same server, as the parent's did; a cold first request on a fresh server measured 3.48 s: + +| Cold prompt tokens | Parent TTFT | This head TTFT | +|---|---|---| +| 2048 | 1.98 s | 1.81 s | +| 8192 | 6.86 s | 3.94 s | +| 32768 | 28.06 s | 13.79 s | +| 65536 | 57.39 s | 27.16 s | + + Greedy decode over 256 tokens, median of three: 40.23 / 40.22 tok/s for the parent against 52.37 / 52.35 for this head + (code and chat prompts). + +#### Settings evidence + +Every new setting was measured on `dd80dd7164` with the others at their defaults: `bench_concurrent.py` with 64 tokens, three +repetitions, temperature 0, 1 and 4 streams, `--alone --serial`, short and long prompts, and one cold 8192-token request, aggregate +decode tok/s. All 13 non-default arms were exact: 0 unequal or failed cells and the same cold reply hash. The default arm ran first, so +its numbers are about 1% low against arms that changed nothing (compare `TILES=4`, `BATCH_MAX=8`). Each cell is one run of three +repetitions; the arms kept below differ by 4% or more from the default in a cell where they act. + +| Arm | short, 1 | short, 4 | long, 1 | long, 4 | cold 8192 TTFT | +|---|---|---|---|---|---| +| default | 52.4 | 59.0 | 49.0 | 10.9 | 3.94 s | +| `EXL3_FMA_TILES=0` | 44.2 (-15.6%) | 48.9 (-17.1%) | 41.8 (-14.7%) | 10.7 (-1.8%) | 3.89 s (-1.2%) | +| `EXL3_FMA_TILES=1` | 50.3 (-4.0%) | 56.0 (-5.1%) | 47.6 (-2.9%) | 11.0 (+0.9%) | 3.90 s (-1.1%) | +| `EXL3_FMA_TILES=4` | 52.3 (-0.2%) | 59.2 (+0.3%) | 48.9 (-0.2%) | 11.1 (+1.8%) | 3.89 s (-1.2%) | +| `EXL3_FMA_TILE_GROUPS=0` | 51.9 (-1.0%) | 59.2 (+0.3%) | 48.8 (-0.4%) | 11.1 (+1.8%) | 3.90 s (-1.1%) | +| `EXL3_FMA_TILE_GROUPS=4294967295` | 50.7 (-3.2%) | 56.1 (-4.9%) | 47.6 (-2.9%) | 11.0 (+0.9%) | 3.90 s (-1.1%) | +| `BATCH_MAX=1` | 52.8 (+0.8%) | 39.7 (-32.7%) | 49.5 (+1.0%) | 10.2 (-6.4%) | 3.90 s (-1.1%) | +| `BATCH_MAX=8` | 52.9 (+1.0%) | 59.2 (+0.3%) | 49.5 (+1.0%) | 11.1 (+1.8%) | 3.90 s (-1.1%) | +| `BATCH_ATTN=0` | 52.9 (+1.0%) | 55.0 (-6.8%) | 49.5 (+1.0%) | 11.0 (+0.9%) | 3.90 s (-1.1%) | +| `PREFILL_INTERLEAVE=0` | 52.9 (+1.0%) | 59.1 (+0.2%) | 49.5 (+1.0%) | 11.2 (+2.8%) | 3.89 s (-1.2%) | +| `ENGRAM_LOOKAHEAD=0` | 52.8 (+0.8%) | 59.2 (+0.3%) | 49.4 (+0.8%) | 11.1 (+1.8%) | 3.90 s (-1.1%) | +| `CONE=0` | 52.8 (+0.8%) | 59.2 (+0.3%) | 49.4 (+0.8%) | 6.7 (-38.5%) | 6.49 s (+64.7%) | +| `CONE=1` | 52.8 (+0.8%) | 59.2 (+0.3%) | 49.5 (+1.0%) | 10.5 (-3.7%) | 4.25 s (+7.9%) | +| `CONE_PARK=0` | 52.9 (+1.0%) | 59.2 (+0.3%) | 49.4 (+0.8%) | 10.4 (-4.6%) | 3.90 s (-1.1%) | + +Kept, with the arm that shows the benefit: `TF_DSV41_EXL3_FMA_TILES` (0 and 1 are slower), `TF_DSV41_BATCH_MAX` (1 is 33% slower with four +short streams), `TF_DSV41_BATCH_ATTN` (0 is 7% slower), `TF_DSV41_CONE` (0 and 1 are slower, 0 by 38% on four long prompts and 65% in +cold TTFT) and `TF_DSV41_CONE_PARK` (0 is 5% slower on four long prompts; the weakest of the five). Removed, because no arm +was slower: `TF_DSV41_EXL3_FMA_TILE_GROUPS` (the threshold stays 400; its only slower arm turns tiling off, which `TILES=1` already +does), `TF_DSV41_PREFILL_INTERLEAVE` and `TF_DSV41_ENGRAM_LOOKAHEAD` (both behaviors are now always on). The nine +`TF_DSV41_NO_FUSE_*` fusion switches were removed earlier for the same reason: a fusion is taken when its shape and pipeline checks +admit it. `TF_DSV41_MTP_DRAFTS` already existed in the parent and is only registered here. + +#### Eight concurrent streams against the parent + +The widest stream count the lane takes (`--parallel 8`, context 32768) on the same machine, with `bench_concurrent.py` at 64 tokens, +three repetitions, temperature 0, 1, 4 and 8 streams, `--alone --serial`, aggregate decode tok/s with the slowest first token. The +prompt files hold four prompts, so at eight streams each prompt is sent twice. 0 failed or unmeasured cells in every arm. The +candidate is the final tree and the parent is #2373's head; the arithmetic differs between them, so only speed is compared here. + +| Arm | short, 1 | short, 4 | short, 8 | long, 1 | long, 4 | long, 8 | +|---|---|---|---|---|---|---| +| parent | 40.6 | 43.5 | 41.7 (first token 4.38 s) | 38.5 | 6.2 | 5.4 (97.4 s) | +| candidate | 52.5 | 59.0 | 56.1 (4.15 s) | 49.1 | 11.1 | 8.8 (59.4 s) | +| candidate, `BATCH_MAX=8` | 52.5 | 59.1 | 48.8 (4.15 s) | 49.1 | 11.1 | 8.5 (59.7 s) | + +The candidate is faster than the parent at every count, by 35% at eight short streams and 63% at eight long ones. Raising +`BATCH_MAX` to 8 is 13% slower at eight short streams and 3% slower at eight long ones, so the default of 4 stays. + +#### Which served results describe the current head + +The attention repairs (the batched split-merge head count, `6aa834fdb4`, and the split-boundary scan mask, `efdf7a464e`) +and the last-row and Sinkhorn repairs (`efdf7a464e`) change served arithmetic. Results measured before them are history: +the initial served comparison (`e070123319`), the first MTP-only probe, the cold default-policy and 1048576-context runs, +and the 41 replies measured before the Sinkhorn repair. + +The final qualification on `a80eddd9a6` has all four repairs. Two later commits change engine arithmetic: +`d62498c304` (a fused gate+up call of 65 to 112 descriptors, a window or prompt chunk of five to eight tokens, now keeps +the one-row body) and `c56e962f4f` (barriers that act only under `TF_DSV41_CONCURRENT`). + +- Measured on `a80eddd9a6`, not re-measured on this head: the plain greedy and sampled hashes, resumed against fresh, + the 128k run, the cold-prompt table, the parent table and the eight-stream table. Plain decode makes one-row calls, + which neither commit changes; `d62498c304` reaches these runs only where a prompt call had five to seven rows. + On the eight reference and ten code prompts the default configuration's hashes were unchanged by it. +- No longer describe this head: the drafted replies and their speed (95.2 and 94.3 tok/s). Before `d62498c304` a + four-draft window switched bodies mid-window; they need a rerun. + +Still open: +- Copy rule from #2373: the projection kernels and Metal drafter its review traced to mlx-serve are #2373's code + (authors preserved in this branch's history); their independence is not shown. This stack's own commits are separate + and proposed on top of them. +- The served drafted results need a rerun after `d62498c304`; the receipts README lists which served results + still describe this head. +- Runtime on M1, M2 and M3, a comparison against `mlx_lm`, and a source-matched no-slowdown comparator against the parent. + + + +## Limits + +These are single-run synthetic correctness/timing probes, not representative throughput or quality gates. +The long fixture repeats public prose; the short fixture mixes completion and chat requests. +The client warms the server; disabling prompt retention does not make disk/Engram pages cold. +`aggregate_tps` sums per-stream decode rates; use `end_to_end_tps` for completed tokens per concurrent request window. +Historical pinned-workspace comparisons, current default-policy cold runs and explicit trained-MTP checks have +different source/settings scopes; none substitutes for another. The final section above is the current scope. Unavailable-chip +runtime checks, a token-equal no-slowdown comparator and the parent's remaining integration gates remain uncleared. +The new family controls use shared strict validation, not a global profile. diff --git a/docs/receipts/dsv41-exl3-metal/environment.json b/docs/receipts/dsv41-exl3-metal/environment.json new file mode 100644 index 00000000000..a2611a9ba23 --- /dev/null +++ b/docs/receipts/dsv41-exl3-metal/environment.json @@ -0,0 +1,75 @@ +{ + "recorded_at_utc": "2026-11-14T01:35:55.046425+00:00", + "base_commit": "bec140d545aa50b765f26cf295b43179c6b2834f", + "native_and_serving_commit": "e070123319b69e73c969b91409dd7195fbbef93e", + "source_note": "Family GPU checks were run before the final core mixed-width fallback fix. The native binary was rebuilt at e070123319b69e73c969b91409dd7195fbbef93e; 128cfe743a76f59b350d0c750a12669708029ff3 changes only the shared-down test fixture after that.", + "machine": { + "soc": "Apple M5 Ultra", + "gpu_cores": 64, + "memory_bytes": 274877906944, + "macos": "27.0", + "macos_build": "26A428", + "metal_support": "Metal 4" + }, + "toolchain": { + "zig": "0.17.0", + "metal_toolchain_asset": "27.1.266.1", + "cpu_target": "apple_m1", + "optimize": "ReleaseSafe", + "benchmark_python": "3.12.14" + }, + "checkpoint": { + "pack": "Mia-AiLab/DeepSeek-V4.1-Flash-1017-EXL3-EAQ-v1-2.9-bpw", + "pack_revision": "45ee5d0fd106c94a3d77f721e09cbb2f50e5a16b", + "source": "deepseek-ai/DeepSeek-V4.1-Flash-1017", + "source_revision": "1bae0e1088993b9b82de08f59de5be5a34e42170", + "format": "EXL3 EAQ v1, average 2.9 bpw, mul1, out_scales=always; MTP 4 bit", + "pack_license": "MIT", + "metadata_sha256": { + "config.json": "4eac47f0da99a65f2bcfb97ca357f7d5388a79c9b377d6dd65b1ed18548d846d", + "model.safetensors.index.json": "6c4679e6407806ab4e63f9a2a46a825c5cab4990cd916723721e7ba0c6bb7d77", + "engram-token-map.bin": "b9a7cf9d341f5daf8fc435dbc36153bf4b28c1b8075be20de30d0556fb910511" + }, + "fingerprint_scope": "All 39 EXL3 weight shards and five pack metadata/tokenizer/template files match the pinned public snapshot. Both streamed original shards and three original metadata/tokenizer files match the pinned source revision. The generated token map is bound separately by SHA256.", + "fingerprint_receipt": "model-fingerprints.json" + }, + "matched_serve": { + "environment": { + "GLM_LOAD_LIMIT_GB": "240", + "TF_DSV41_PREFILL_STEP": "4096" + }, + "arguments": [ + "serve", + "", + "--engram-stream-dir", + "", + "--chat-template", + "/chat_template.jinja", + "--context", + "32768", + "--parallel", + "4", + "--prompt-cache-gib", + "0", + "--host", + "127.0.0.1", + "--port", + "8941", + "--name", + "exl3-qualification", + "--keep-warm", + "0" + ], + "candidate_startup_diagnostic": { + "TF_DSV41_CONE_CHECK": "4096,16384" + }, + "notes": [ + "Identical explicit 4096-row workspace in both arms; this comparison does not measure the automatic 8192-row policy.", + "The default copy-draft policy is checked against draft:false; this does not qualify explicit MTP/DSpark settings.", + "Prompt cache disabled, but benchmark warm-up and OS/Engram page warmth mean this is not a cold-TTFT gate." + ] + }, + "family_operator_check_commit": "59535dad914819ea4d281f87c81a138c4f2c4e1b", + "exl3_projection_check_commit": "128cfe743a76f59b350d0c750a12669708029ff3", + "qualification_tree_commit": "128cfe743a76f59b350d0c750a12669708029ff3" +} diff --git a/docs/receipts/dsv41-exl3-metal/fidelity-128.json b/docs/receipts/dsv41-exl3-metal/fidelity-128.json new file mode 100644 index 00000000000..aedeab8053e --- /dev/null +++ b/docs/receipts/dsv41-exl3-metal/fidelity-128.json @@ -0,0 +1,237 @@ +{ + "scope": "Full 128-token teacher history, not a shortened qualification window", + "release_qualified": false, + "tokens": 128, + "vocab": 129280, + "reference_source_commit": "6aa834fdb4c58192a21a31524a5bf298b7b7ecec", + "reference_reuse_explicit": true, + "reference_description": "Independent CPU FP32 contract and FP64 ideal captures; unchanged reference equations, pinned checkpoint and teacher history. The repaired GPU capture is compared offline using qualify.zig's NRMS, KL and floor-band equations. GPU-only mode does not enforce the numeric gate.", + "offline_comparator_validation": "Reproduces the original native NRMS and mean KL within 1e-10", + "teacher_input": "zig/tests/deepseek_v41_reference/release-quality-128.json", + "teacher_input_sha256": "7a658a98e52ff3f7b8a7862260657915efabf5128e0d6374ce44910550bc6ca5", + "teacher_window_fnv1a_verified": "67323ba89384ac3", + "contract_logits_fnv1a_verified": "b5cc2c9bcbec96a9", + "checkpoint_metadata_identity_hex": "08f1656b9ad8747a7b573fc9f24dc84bfd6944b3a183becffc3ae5e594aa081f", + "reference_sha256": { + "contract": "9a502c7435a529ce9a820e8030c25ffd2294df645248b20992cd38aaffd1f6d8", + "ideal": "d6f207a47851781979c47540e122055094647109fcf8b7c752176927e56f7e8a" + }, + "floor": { + "normalized_rms_error": 0.15093634292089003, + "mean_kl": 0.04817871145700856, + "max_kl": 0.7008781518460677, + "greedy_disagreements": 0 + }, + "limits": {"clear_ratio": 1.05, "review_ratio": 1.10}, + "before": { + "source_commit": "6aa834fdb4c58192a21a31524a5bf298b7b7ecec", + "native_oracle_exit_code": 1, + "native_oracle_fp64_exit_code": 1, + "max_absolute_error": 11.779722882376396, + "normalized_rms_error": 0.2799741792358492, + "mean_kl": 0.09911078223043536, + "max_kl": 1.5024810205638959, + "band_ratio": 1.854915614210866, + "band_verdict": "fail", + "greedy_disagreements": 7, + "disagreement_columns": ["teacher_step_one_based", "gpu_token", "reference_token", "gpu_top1_margin", "reference_top1_margin"], + "disagreements": [ + [6, 102771, 1004, 0.2098064422607422, 0.07823598830092138], + [8, 438, 31, 0.3913841247558594, 1.0806256598025143], + [24, 1004, 20521, 1.4325618743896484, 1.151437312693247], + [25, 12612, 2390, 0.37141990661621094, 1.7041245408700334], + [50, 223, 1946, 0.8264656066894531, 6.18904453168026], + [92, 23, 22, 0.2922801971435547, 7.598930213905987], + [116, 10987, 9266, 0.6146087646484375, 0.10188950801642349] + ], + "execution_disk_read_bytes": 4096, + "execution_pageins": 0, + "resident_gate_passed": false, + "observed_lifetime_peak_phys_footprint_bytes": 234791952104 + }, + "after": { + "source_base": "6aa834fdb4c58192a21a31524a5bf298b7b7ecec", + "source_description": "Base plus guarded shared-down fusion, backend lifetime repair, split-tail masking in both native attention scans, reserved E4M3 NaN decoding and NaN-safe BF16 rounding. Later drafter-buffer ownership changes are not part of this capture.", + "production_delta_sha256": { + "zig/src/families/deepseek_v41/backend.zig": "a83579a0a167fe6a4a4bdae1812f3ff9713caba4420e5e217780014b7835d620", + "zig/src/core/exl3_projection_pipelines.zig": "d38ae45f10ff10e19af20408d3960fab32e5f1297c107a4aeeea5ad4d3541cd9", + "zig/src/core/exl3_projection_swiglu.zig": "bc19fef430ae3d9a75386d6aa9c54c90b28f54e5bdaff6086143aece1f3b947e", + "zig/src/core/exl3_projection.zig": "09914e111927aaf1a7981e41a1268bd2536cb37de17cfbb432b3516b32afe647", + "zig/src/families/deepseek_v41/model_moe_fuse.zig": "0b018b82020c7fc43e711b011443e797b05bf87a69e72a6ae932de6a7418a900", + "zig/src/families/deepseek_v41/model_moe.zig": "2c4b3af2436fc7e48cd2d3c6221f6380ea5709a546b73836cfcda785d7e08efe", + "zig/kernels/metal/deepseek_v41/csa2_rows.metal": "b84d40134147ddfbd5c42661750ce3a1ef683ecfeee0f64eb76c18dbec2c280c", + "zig/kernels/metal/deepseek_v41/csa2_nax.metal": "de471abca7bd9f6e690d80251aaa17f4339dd7e370b5bc9375ab06aefb46b65e", + "zig/kernels/metal/deepseek_v41/kv.metal": "325a2afb2447f1e011490ec01a00e0e517a18f8d03f6e907f9bdeea9d7eef66a" + }, + "gpu_capture_exit_code": 0, + "numeric_gate_evaluated_separately": true, + "max_absolute_error": 12.225529751416023, + "normalized_rms_error": 0.17207024141616578, + "mean_kl": 0.0628563818603372, + "max_kl": 2.1513042034034084, + "band_ratio": 1.1400186203421705, + "band_verdict": "fail", + "band_gate_passed": false, + "greedy_disagreements": 6, + "greedy_gate_passed": false, + "disagreement_columns": ["teacher_step_one_based", "gpu_token", "reference_token", "gpu_top1_margin", "reference_top1_margin"], + "disagreements": [ + [6, 223, 1004, 0.44847965240478516, 0.07823598830092138], + [7, 818, 271, 0.2050914764404297, 0.16438415909977167], + [8, 1, 31, 0.6085376739501953, 1.0806256598025143], + [12, 411, 260, 0.00017547607421875, 3.5713367531295397], + [15, 14, 305, 0.2400188446044922, 4.231678817328881], + [116, 10987, 9266, 0.10785675048828125, 0.10188950801642349] + ], + "fp32_contract_normalized_rms_error": 0.17858910575824752, + "fp32_contract_greedy_disagreements": 6, + "context_capacity": 1048576, + "weight_bytes": 210580703416, + "resident_allocation_bytes": 234054696960, + "ready_footprint_bytes": 234264483456, + "final_footprint_bytes": 234486708808, + "observed_lifetime_peak_phys_footprint_bytes": 234643396488, + "engram_streaming": true, + "engram_stream_logical_bytes": 1622016, + "engram_stream_misses": 6144, + "execution_disk_read_bytes": 0, + "execution_pageins": 0, + "resident_gate_passed": true + }, + "later_projection_order_capture": { + "tokens": 128, + "reference_reuse_explicit": true, + "normalized_rms_error": 0.17207024141616578, + "band_ratio": 1.1400186203421705, + "band_gate_passed": false, + "mean_kl": 0.0628563818603372, + "max_kl": 2.1513042034034084, + "greedy_disagreements": 6, + "disagreement_rows": "Same six rows and margins as the preceding after capture.", + "gpu_capture_exit_code": 1, + "execution_disk_read_bytes": 4096, + "execution_pageins": 0, + "resident_gate_passed": false, + "observed_lifetime_peak_phys_footprint_bytes": 234643298256, + "footprint_observations": 76, + "release_qualified": false + }, + "matched_parent_teacher_window": { + "tokens": 128, + "vocab": 129280, + "diagnostic_workspace_rows": 128, + "context_capacity": 1048576, + "parent_source": "bec140d545aa50b765f26cf295b43179c6b2834f", + "harness_only_delta": "Both actual one-row oracle runs reserve128 workspace rows instead of15872; model context remains1048576.", + "production_sources_unchanged_by_harness": true, + "parent_production_source_files_verified": 4695, + "active_oracle_rows_per_forward": 1, + "diagnostic_harness_sha256": "a193e15c6a83c8412ec2b036b102689f0b50f13a630b3409be64a46488f05cd6", + "reference_source_commit": "6aa834fdb4c58192a21a31524a5bf298b7b7ecec", + "reference_equations_checkpoint_and_history_unchanged": true, + "parent_default_workspace_admission": { + "workspace_rows": 15872, + "needed_bytes": 237029421640, + "margin_bytes": 8589934592, + "available_after_margin_bytes": 230553780224, + "admitted": false + }, + "parent": { + "normalized_rms_error": 0.2799741792358784, + "band_ratio": 1.8549156142110899, + "mean_kl": 0.09911078223036636, + "max_kl": 1.5024810205632118, + "greedy_disagreements": 7 + }, + "candidate": { + "normalized_rms_error": 0.17207024141616578, + "band_ratio": 1.1400186203421705, + "mean_kl": 0.0628563818603372, + "max_kl": 2.1513042034034084, + "greedy_disagreements": 6 + }, + "execution_disk_read_bytes_per_arm": 4096, + "execution_pageins_per_arm": 0, + "both_resident_gates_passed": false, + "numerical_band_limit_unchanged": 1.1, + "both_numerical_band_gates_passed": false, + "candidate_worst_row_kl_worsened": true, + "release_qualified": false + }, + "argmax_scope": "FP64 teacher argmax differences are reported, not independently thresholded by enforceGate. They do not replace the engine's own plain/drafted, retained, cancelled and concurrent path invariants.", + "performance_comparison_claimed": false, + "performance_warning": "The original captures interleave CPU and GPU steps; the repaired GPU-only replay is contiguous. Their GPU timings are not a controlled speed comparison.", + "residency_scope": "Only this measured execution window: zero disk reads/pageins does not establish that the full external Engram tables are resident on the 256 GiB machine.", + "after_selected_final_row_repair": { + "forward_impl_sha256": "addc00ce671f94a893270618adee22ced74998ba6d728c1498dc45fbe140c4bb", + "tokens": 128, + "context_capacity": 1048576, + "diagnostic_workspace_rows": 128, + "gpu_capture_exit_code": 1, + "gpu_sha256": "0f598c25d3c76e8f3e639c086838938377e46f2c3da4f2d9c6b1c0c42b8b704e", + "byte_identical_to_matched_candidate_capture": true, + "reference_CPU_recomputed": false, + "reference_reuse_explicit": true, + "numeric_metrics_reference": "matched_parent_teacher_window.candidate; current full GPU bytes are identical, so its failed band and KL metrics are unchanged", + "numeric_gate_evaluated_separately": true, + "execution_disk_read_bytes": 154669056, + "execution_pageins": 8912, + "resident_gate_passed": false, + "measurement_scope": "model_execution", + "diagnostic_self_check_outside_window": true, + "release_qualified": false + }, + "projection_body_diagnostics": { + "scope": "Full unchanged 128-token teacher, context 1048576, workspace 128, same verified CPU references; diagnostic switches only, no production configuration changes.", + "untiled_fma": { + "override": "TF_DSV41_EXL3_FMA_TILES=0", + "gpu_capture_identical_to_default": true, + "band_ratio": 1.1400186203421698, + "mean_kl": 0.06285638186033718, + "max_kl": 2.1513042034034084, + "execution_disk_read_bytes": 0, + "execution_pageins": 0, + "numerical_band_passed": false + }, + "mma_decode": { + "override": "TF_DSV41_EXL3_FMA=0", + "gpu_sha256": "af06a0cc64cb25ed32c84a8a3697aab6b9670869bfbb4ae4b66da8d9b83d21f6", + "band_ratio": 1.1687519315836317, + "mean_kl": 0.06755244053853024, + "max_kl": 2.3762145519643143, + "execution_disk_read_bytes": 4096, + "execution_pageins": 0, + "numerical_band_passed": false + }, + "qualification": "Neither mode clears the unchanged numerical band. A warm zero-read capture does not prove full Engram table residency." + }, + "after_sinkhorn_butterfly_repair": { + "change": "Match the unfused split's FP32 butterfly: row XOR 2 then 1, column XOR 8 then 4.", + "shader_sha256": "f12c9c94be85f5878d137ad2d634629b527bc772c53a7d1174394c02d5d4f4ee", + "regression_sha256": "b012ba69ba34d2a160f4031f3490ebffee38007caf81704fa9722c9c8e4b426f", + "regression": "Fails before repair on comb coefficients; after repair all 1728 retained-argument FP32 coefficients match the unfused split bitwise. Reference target reports 41 passed and 15 skipped of 56; existing FP64 bounds are unchanged.", + "reference_reuse_explicit": true, + "gpu_sha256": "bc612e0d0a9d6e140d1451ccc66c19d526419fce23dfb0f30740b68c07a947c2", + "normalized_rms_error": 0.14600144548737998, + "band_ratio": 0.9673047767157269, + "band_verdict": "clear", + "mean_kl": 0.04216465510149513, + "max_kl": 0.832580516601873, + "greedy_disagreements": 5, + "disagreement_columns": ["teacher_step_one_based", "gpu_token", "reference_token", "gpu_top1_margin", "reference_top1_margin"], + "disagreements": [ + [6, 223, 1004, 0.08385372161865234, 0.07823598830092138], + [7, 1, 271, 0.17816162109375, 0.16438415909977167], + [8, 438, 31, 0.03397560119628906, 1.0806256598025143], + [14, 22361, 22491, 0.28827476501464844, 0.032542251811168654], + [116, 10987, 9266, 0.5686531066894531, 0.10188950801642349] + ], + "native_gpu_only_exit_code": 1, + "execution_disk_read_bytes": 4096, + "execution_pageins": 0, + "measurement_scope": "model_execution", + "diagnostic_self_check_outside_window": true, + "resident_gate_passed": false, + "release_qualified": false + } +} diff --git a/docs/receipts/dsv41-exl3-metal/model-fingerprints.json b/docs/receipts/dsv41-exl3-metal/model-fingerprints.json new file mode 100644 index 00000000000..1e65a907edb --- /dev/null +++ b/docs/receipts/dsv41-exl3-metal/model-fingerprints.json @@ -0,0 +1,103 @@ +{ + "pack": { + "repository": "Mia-AiLab/DeepSeek-V4.1-Flash-1017-EXL3-EAQ-v1-2.9-bpw", + "revision": "45ee5d0fd106c94a3d77f721e09cbb2f50e5a16b", + "weight_shard_sha256": { + "model-00001-of-00039.safetensors": "7d18021abd2971d7a1986507e0777f2d49d046ad6ac24f5fe70588cebdcf1910", + "model-00002-of-00039.safetensors": "e24859cfbd8ebd4bc24b8579a2992da284ab002015847c6295009d4fea00c711", + "model-00003-of-00039.safetensors": "bb4edfb31a01ecd74a2d8091945fa24f02d8c64397876d39e0c4ea104bd1b0e5", + "model-00004-of-00039.safetensors": "3ef8a8bed655b747550154d0bca71267fcb46239e35a990db9f373c7bfda3f94", + "model-00005-of-00039.safetensors": "87366b18c6e49c5143c0a1afef189ef170de8dfb78a47ba14edfb6cc7ebf2753", + "model-00006-of-00039.safetensors": "3ba7c830ef44613ee1ab9c9f6a796f813f42f0519053ebbec03514a6d8714349", + "model-00007-of-00039.safetensors": "6b4c8d0b081f27e6288a66626be2c11515e9280a3086d0925670a571e40a1ad4", + "model-00008-of-00039.safetensors": "6e6c204a67d66ce98c9f6188816c3535f11af0f6db98c562228af4b27dcc9a2d", + "model-00009-of-00039.safetensors": "ed0a69b7307076462b9d4578839c9956c198f716b857a6fc6aeea95fbdd0ff9e", + "model-00010-of-00039.safetensors": "45a621997686e51648c54333ddd309521cbc4fb54debd7a65fb293085cfb9694", + "model-00011-of-00039.safetensors": "348d4b250f86b21f9793be736c5d05a29da14357ddce6bf635d23b47b10f1eec", + "model-00012-of-00039.safetensors": "e4d04c60e5e88c2fa2a2fd1c0af9d45018f5092411aad87087693bbe74119300", + "model-00013-of-00039.safetensors": "978514e757cdafd2cd506c98bccb51e488cebd62caa215034fca0d401f8be1d7", + "model-00014-of-00039.safetensors": "b0fdb9d59a46d4c15140a406cb796ea41de41961537b6abff5b712555847e984", + "model-00015-of-00039.safetensors": "b7b11a4b2823bd3b9186c97905416867a71c270cc058287f88517f8a1caf3e87", + "model-00016-of-00039.safetensors": "584e16c28ba6e800c6e22a4f660aa6bb257f7ea9bd4a140d9ecd5427f16aff66", + "model-00017-of-00039.safetensors": "a584ba0235153a2d042873200707a3705a0cb7c7ef5741b176578e560c390b27", + "model-00018-of-00039.safetensors": "1c29b236ec0d7b7e853eb5794c47845ef9fee0dc24112e83238279c0db31b273", + "model-00019-of-00039.safetensors": "468e038fa7ece5329b49114aaf6ed43f159919db4d328adac6390deb565edbaf", + "model-00020-of-00039.safetensors": "9e4edbaefb94a853c16ced7d82cc0b0c0fac010a638007dece005aa6e0400842", + "model-00021-of-00039.safetensors": "b4ca1f13b6c84544018ba479e996de40a49e3f4700370048d2f50006ba304aef", + "model-00022-of-00039.safetensors": "7145fe502df043f952f6635e05cf08cd5f12b00b123117eb36f6aa1ec1932dad", + "model-00023-of-00039.safetensors": "786449496a8d466a9fd350c0bd8fa1aa9ec40c3e1e2ecb1f1f2e186e53fa40fd", + "model-00024-of-00039.safetensors": "9149b4f9b5b9bbfa24f7344ce31421237bbade2bb59e991493ef3cf3de931ae7", + "model-00025-of-00039.safetensors": "6bfa439fe9797eafede930a049270983bf7102e2f57801a0cb674a9fa8a6f137", + "model-00026-of-00039.safetensors": "1ec3a165626069f904966540b0d0f43b47a58808b5bfb696c382fd6d118adf29", + "model-00027-of-00039.safetensors": "25029c1fe6e177931608d8fbc7a2202de2e3d614b12ff37c8299038a24ec8537", + "model-00028-of-00039.safetensors": "9e861f7437be6274c7e5ac106597bd8571fea4c915f9db86790710dfc5cc73f9", + "model-00029-of-00039.safetensors": "059aa4933a7e5cbde98f69797bf6a2a6163bd0a8a3280613e57699ce295f7c64", + "model-00030-of-00039.safetensors": "4b1825b7fbf71c01dcde9e8b8f6dbc34778d7b33998c33e962bc0c72c282f214", + "model-00031-of-00039.safetensors": "be975db269aad71de4134d3f5295e4a30b75171c959b52ecff74e6af3b009626", + "model-00032-of-00039.safetensors": "99acb8bcff210fc016f4308edd6f1c6acd6ffb73c655e058bf65a302c1919a27", + "model-00033-of-00039.safetensors": "6fa29eb49ddcd74a226442b22563426a231dfdf33bd813fd731039151a7edf95", + "model-00034-of-00039.safetensors": "bc80bf84d7f88b66e906eeab7fe345efb2335075e02aaa66993053fcb6ff51ed", + "model-00035-of-00039.safetensors": "7b51f60e19164fa57a9dc3fa451a61af5acb224944d7cb65f242e45cc80d2f21", + "model-00036-of-00039.safetensors": "e291dd4ac2633bf86a4415b3fda2bfe51bba05406a9885f3070220c72b17b313", + "model-00037-of-00039.safetensors": "b16e8fb4010d2bc8cf6e6f59dd26bd36ab77b97584c0bcc6762aac5cdd459a88", + "model-00038-of-00039.safetensors": "aa4e072510ae20240222f95f5dfc37fa103d8a8bc433315844f2cd4f566ec6ab", + "model-00039-of-00039.safetensors": "2e363ac298b1f59f6a788c404f5b97622c72bfa39818c317dea40f7f518d27b9" + }, + "metadata": { + "config.json": { + "sha256": "4eac47f0da99a65f2bcfb97ca357f7d5388a79c9b377d6dd65b1ed18548d846d", + "git_blob_sha1": "14e367895dbf40db85380acc67b2af38d9744d03", + "size": 3563 + }, + "model.safetensors.index.json": { + "sha256": "6c4679e6407806ab4e63f9a2a46a825c5cab4990cd916723721e7ba0c6bb7d77", + "git_blob_sha1": "0e63aa262cee29350edf1e734c76871d189166c9", + "size": 15504210 + }, + "tokenizer.json": { + "sha256": "c90dfa01249db1be4245780a052ede752e1361c612ac6d08e2bdada7d599476b", + "git_blob_sha1": "6a15814dd25c934028034531da744c689f87ff21", + "size": 6367257 + }, + "tokenizer_config.json": { + "sha256": "6ac8c8dc065ed118161d02dd532749ae3f52c243deac27872134fae2f50d8547", + "git_blob_sha1": "f3dad388a2bbfd6a8605bd02754acd86d9ca5112", + "size": 801 + }, + "chat_template.jinja": { + "sha256": "3e0c2a31ea12b1d7c02319e20356e2e2bc46da2638e4bae6980493329efeca73", + "git_blob_sha1": "c5d8fa8a9d8b8054f0a077201df3c0c2cdaa6033", + "size": 34236 + } + } + }, + "source": { + "repository": "deepseek-ai/DeepSeek-V4.1-Flash-1017", + "revision": "1bae0e1088993b9b82de08f59de5be5a34e42170", + "streamed_shard_sha256": { + "model-00047-of-00048.safetensors": "76a05106ece259be83d1bfea0dcb54f23377864ee60fd321690f35e6698a2af5", + "model-00048-of-00048.safetensors": "9dc51433e195bc78b5ad846b68643cc0351d3b174e5e4309222d3b7402c83afd" + }, + "metadata": { + "config.json": { + "sha256": "8be45ce0476004a3f529fd896115a4a2e800a129ad2d3ec05b16050f52e21879", + "git_blob_sha1": "09917a9139b22d5bf8be52132787f435147b1020", + "size": 3311 + }, + "tokenizer.json": { + "sha256": "c90dfa01249db1be4245780a052ede752e1361c612ac6d08e2bdada7d599476b", + "git_blob_sha1": "6a15814dd25c934028034531da744c689f87ff21", + "size": 6367257 + }, + "tokenizer_config.json": { + "sha256": "6ac8c8dc065ed118161d02dd532749ae3f52c243deac27872134fae2f50d8547", + "git_blob_sha1": "f3dad388a2bbfd6a8605bd02754acd86d9ca5112", + "size": 801 + } + } + }, + "generated": { + "engram-token-map.bin": "b9a7cf9d341f5daf8fc435dbc36153bf4b28c1b8075be20de30d0556fb910511" + }, + "verification": "Hugging Face pinned tree LFS SHA256 where present; otherwise Git blob SHA1. All listed files verified. Generated token map has no public repository object." +} diff --git a/docs/receipts/dsv41-exl3-metal/operator-checks.json b/docs/receipts/dsv41-exl3-metal/operator-checks.json new file mode 100644 index 00000000000..d1bfbd72715 --- /dev/null +++ b/docs/receipts/dsv41-exl3-metal/operator-checks.json @@ -0,0 +1,652 @@ +{ + "exl3_projection": { + "command": "zig build test-exl3-gpu -Dcpu=apple_m1 -Doptimize=ReleaseSafe -j8 --summary all", + "base": { + "commit": "bec140d545aa50b765f26cf295b43179c6b2834f", + "passed": 21, + "failed": 6, + "total": 27, + "exit_code": 1 + }, + "candidate": { + "commit": "128cfe743a76f59b350d0c750a12669708029ff3", + "passed": 36, + "failed": 3, + "total": 39, + "exit_code": 1 + }, + "remaining_failing_tests_also_failed_on_base": [ + "GPU router descriptors select mixed-width experts with gather and scatter without host routing", + "packed signs and GPU expert filtering preserve untouched output slots", + "caller-prepared grouped expert tiles preserve scatter slots and ignore padding" + ], + "notes": [ + "The complete target is NOT passing on either revision.", + "The unsupported indexed-width scalar-reference regression, tiled/table bit checks and chain/MoE fusion checks pass.", + "The shared-down fixture must reserve the maximum scratch of its gate/up, routed-down and shared-down stages." + ] + }, + "native_build": { + "commit": "e070123319b69e73c969b91409dd7195fbbef93e", + "command": "zig build native -Dcpu=apple_m1 -Doptimize=ReleaseSafe -j8 --summary all", + "steps_succeeded": 66, + "steps_total": 66, + "exit_code": 0 + }, + "native_host": { + "commit": "0870c860f48ba88a53e72b14dafa0434a01dbd84", + "command": "zig build native test-native -Dcpu=apple_m1 -Doptimize=ReleaseSafe -j8 --summary all", + "passed": 118, + "skipped": 3, + "total": 121, + "exit_code": 0 + }, + "earlier_family_gpu": { + "commit": "59535dad914819ea4d281f87c81a138c4f2c4e1b", + "target": "test-deepseek-v41", + "passed": 73, + "total": 73, + "notes": "This target passed within a combined invocation that failed native compilation. The native dependency was fixed and checked separately. This is not a rerun of the family suite after the core fallback fix." + }, + "host_lane_api": { + "target": "test-lane-api-host", + "passed": 545, + "total": 545, + "exit_code": 0, + "notes": "Scheduler/interface sources unchanged since this host check." + }, + "environment_host": { + "target": "test-environment-host", + "passed": 12, + "total": 12, + "exit_code": 0 + }, + "receipt_checker_controls": { + "changed_complete_token_hash_exit_code": 1, + "missing_complete_token_hash_exit_code": 1, + "temporary_control_files_removed": true + }, + "release_qualified": false, + "projection_contract": { + "command": "tf-kernel-contract --only exl3-metal --no-limits", + "kernels": 219, + "entrypoints": 13, + "passed": 219, + "failed": 0, + "known_findings": 0, + "controls": 876, + "caught": 876, + "missed": 0, + "gate_ms": 183561, + "scope": "Registered default-sixteen-warp decode width/codebook cases and KU2 prompt cases; independent scalar-decoded FP64, exact parent reduction and KU1 replacement, full output columns and served dimensions." + }, + "projection_resources": { + "command": "tf-kernel-contract --only exl3-metal --no-gates --offline OFFLINE_DIR", + "selected_launches": 13, + "live_passed": 13, + "limit_problems": 0, + "resource_controls_caught": 2, + "m1_m2": "Not served: projection pipeline selection requires tensor units (GPU generation 17). Offline controls exercised on M1/M2 targets; no claim of projection execution there." + }, + "contract_host": { + "command": "zig build test-exl3-contract-host test-kernel-contract -Dcpu=apple_m1 -j4 --summary all", + "passed": 232, + "failed": 0, + "build_steps": 33 + }, + "cuda_host_subset": { + "command": "zig build test-cuda-host -Dcpu=apple_m1 -j4 --summary all", + "passed": 5540, + "skipped": 32, + "total": 5572, + "build_steps_succeeded": 345, + "build_steps_total": 345, + "exit_code": 0, + "scope": "Before the new chain launch records; not a claim that the final host registry has been requalified." + }, + "chain_contract_m4": { + "command": "zig build test-exl3-chain-contract test-exl3-chain-host -Dcpu=apple_m1 -Doptimize=ReleaseSafe -j4 --summary all", + "kernels": 8, + "passed": 8, + "failed": 0, + "known_findings": 0, + "controls": 34, + "caught": 34, + "missed": 0, + "build_steps_succeeded": 7, + "build_steps_total": 7, + "exit_code": 0, + "scope": "FP64 classes and explicit activation rounding; exact independent unfused GPU bytes; FP32 cancellation and ordered-combine plants; separate rounded-norm controls. Includes 384 experts, six routed picks plus shared rows, 32768-column outputs, grouped output rotation, in-place RMS and long independent RoPE positions.", + "m5_run": "See chain_contract_m5.", + "resources": { + "native_max_threads_all_eight": 1024, + "static_threadgroup_bytes": { + "swiglu": 0, + "out_in": 0, + "rms": 32, + "out_rope": 0, + "rope_in": 0, + "gate_up": 0, + "down": 4144, + "qkv": 2592 + }, + "formal_gate5": "M4/M5 live limits and M1/M2 offline compilation passed. RMS adapts to its pipeline limit; no M1/M2 runtime numeric claim." + } + }, + "chain_reference_host": { + "command": "zig build test-exl3-chain-host -Dcpu=apple_m1 -j4 --summary all", + "passed": 2, + "failed": 0, + "scope": "Direct float64-to-BF16 midpoint and subnormal rounding; FP32 versus FP16/BF16 cancellation across all three replay orders. Cached in the later combined invocation." + }, + "shared_down_m4_eligibility": { + "target": "test-exl3-moe", + "passed": 3, + "skipped": 1, + "total": 4, + "scope": "M4 keeps separate shared-down arithmetic. The merged-down differential is explicitly unserved there; the focused M5 target passed 4/4." + }, + "native_rows_contract_m4": { + "command": "zig build test-deepseek-v41-rows-contract -Dcpu=apple_m1 -Doptimize=ReleaseSafe -j4 --summary all", + "registrations_passed": 4, + "entrypoints": 3, + "failed": 0, + "known": 0, + "controls_caught": 13, + "controls_missed": 0, + "build_steps_succeeded": 4, + "tests_passed": 4, + "scope": "Forward and inverse native batched RoPE, packed KV glue and per-slot ring publication; exact per-slot GPU outputs for 1-8 slots, 16/32/64 heads and absolute positions through 1048575. Complete ring images and untouched padding are checked.", + "fp16_norm_stress_minimum_margin": 1398101, + "bf16_norm_stress": "Not claimed: equal positive squares sum exactly under balanced BF16, and packed FP8 hides small norm errors.", + "native_max_threads": 1024, + "static_threadgroup_bytes": { "rope": 0, "glue": 32, "publish": 0 }, + "m5_runtime": "See native_rows_contract_m5.", + "gate_5": "Live M4/M5 limits and M1/M2 offline limits passed; all three compile to 1024 threads on M1/M2." + }, + "native_attention_reference_host": { + "command": "zig build test-deepseek-v41-attention-rows-host -Dcpu=apple_m1 -Doptimize=ReleaseSafe -j4 --summary all", + "passed": 2, + "failed": 0, + "build_steps_succeeded": 3, + "scope": "Independent packed E4/E2 decoding boundaries and a full-width value cancellation plant. FP32 is exact and both FP16/BF16 miss by over 100 bounds in all three replay orders." + }, + "native_attention_runner_m4": { + "command": "zig build test-deepseek-v41-attention-rows-contract -Dcpu=apple_m1 -Doptimize=ReleaseSafe -j4 --summary all", + "build_steps_succeeded": 4, + "passed": 0, + "skipped": 1, + "scope": "Runner and native parameter ABI compiled. The tensor-unit attention contract is explicitly unserved on M4; no numeric GPU qualification is claimed.", + "m5_runtime": "See native_attention_contract_m5.", + "gate_5": "M5 live limits passed; these generation-17-only launches are explicitly unserved on M1/M2." + }, + "logical_projection_audit": { + "physical_shape_classes": 26, + "grouped_wo_a_matrices": 344, + "backbone_groups": { "blocks": 40, "groups_per_block": 8, "k": 4096, "n": 1024, "halves": 10 }, + "dspark_groups": { "blocks": 3, "groups_per_block": 8, "k": 4096, "n": 1024, "halves": 8 }, + "scope": "Native weights bind each named wo_a.slice matrix as 4096x1024; both width classes already occur in the qualified projection geometry list. The eight groups do not introduce an unregistered larger dot shape." + }, + "chain_contract_m5": { + "kernels": 8, + "passed": 8, + "failed": 0, + "known_findings": 0, + "controls_caught": 34, + "controls_missed": 0, + "max_threads_all_eight": 1024, + "scope": "Same source-only chain contract as M4; exercised before the later cache decoder NaN repair." + }, + "native_rows_contract_m5": { + "registrations_passed": 4, + "failed": 0, + "known_findings": 0, + "controls_caught": 13, + "controls_missed": 0, + "max_threads_all_three": 1024 + }, + "native_attention_contract_m5": { + "command": "zig build test-deepseek-v41-attention-rows-contract -Dcpu=apple_m1 -Doptimize=ReleaseSafe -j8 --summary all", + "registrations_passed": 8, + "failed": 0, + "known_findings": 0, + "controls_caught": 34, + "controls_missed": 0, + "build_steps_succeeded": 4, + "tests_passed": 1, + "exit_code": 0, + "max_threads": { "dense": 1024, "scan": 1024 }, + "static_threadgroup_bytes": { "dense": 0, "scan": 8448 }, + "scope": "Independent packed-code non-finite classes, exact per-slot dense/scan bytes, both split merges and full-width FP32 cancellation at 1-8 slots and 16/32/64 heads. Two controls restore the old split-tail predicate and reproduce both misaligned-split failures.", + "repairs": [ + "Both scans mask each tile at its split's j_end, not merely the total key count.", + "Reserved E4M3 NaNs and BF16 rounding preserve non-finite classes.", + "The independent dense reference binds else to the visibility test, not the inner loop." + ] + }, + "offline_limits_m4": { + "compiler": "Metal 27.2.47; real /usr/bin/xcrun rather than the earlier temporary shim", + "chain_launches": 8, + "native_pointwise_launches": 3, + "limit_problems": 0, + "resource_controls_caught_per_run": 2, + "m1_m2_compiled_minima": { "out_in": 832, "rms": 928, "other_six_chain": 1024, "rope": 1024, "glue": 1024, "publish": 1024 }, + "scope": "Actual M1/M2 offline pipeline limits; not runtime numerical execution on those chips." + }, + "later_contract_host": { + "command": "zig build test-kernel-contract tf-kernel-contract -Dcpu=apple_m1 -Doptimize=ReleaseSafe -j4 --summary all", + "tests_passed": 230, + "build_steps_succeeded": 73, + "exit_code": 0 + }, + "native_host_m4": { + "tests_passed": 118, + "tests_skipped": 3, + "scope": "Real Metal offline compiler; this native run predates the later attention and drafter-buffer changes." + }, + "lifetime_m4": { + "command": "zig build test-deepseek-v41-lifetime -Dcpu=apple_m1 -Doptimize=ReleaseSafe -j4 --summary all", + "tests_passed": 2, + "build_steps_succeeded": 43, + "exit_code": 0, + "scope": "Backend allocator release and real Metal ID-buffer growth from one-token use to 5- and 17-row arms, preserving existing Markov picks. Does not establish served MTP shutdown." + }, + "full_host_before_projection_order_repair": { + "command": "zig build test test-golden dev-tools -Dcpu=apple_m1 -Doptimize=ReleaseSafe -j4 --summary all", + "build_steps_succeeded": 965, + "build_steps_total": 968, + "tests_passed": 11884, + "tests_skipped": 110, + "tests_failed": 1, + "test_golden_passed": true, + "dev_tools_passed": true, + "failure": "one-row fused wq_a+wkv: 2 unequal BF16 cells; numerical tolerances preserved" + }, + "projection_order_repair_m4": { + "standalone_tests_passed": 38, + "standalone_tests_skipped": 1, + "standalone_tests_failed": 0, + "qkv_tests_passed": 2, + "qkv_cells": 1792, + "qkv_unequal_cells": 0, + "qkv_normalized_rms_error": 0, + "scope": "Actual M4 scalar execution; not a tensor-unit or model-fidelity qualification. Existing valid numerical parity assertions were retained." + }, + "projection_order_repair_m5": { + "standalone_tests_passed": 39, + "standalone_tests_failed": 0, + "qkv_tests_passed": 2, + "qkv_cells": 1792, + "qkv_unequal_cells": 0, + "registrations_passed": 261, + "registrations_failed": 0, + "known_findings": 0, + "controls_caught": 1044, + "controls_missed": 0, + "gate_scope": "Gates 1-4; final integrated launch-resource checks are recorded separately." + }, + "integrated_host_after_projection_order_repair": { + "command": "zig build native dev-tools test-kernel-contract -Dcpu=apple_m1 -Dversion=1.0.0 -Doptimize=ReleaseSafe -j4 --summary all", + "build_steps_succeeded": 291, + "tests_passed": 193, + "exit_code": 0, + "scope": "Real native and all developer-tool links plus contract host tests; not a rerun of the full test corpus." + }, + "whole_model_fidelity": { + "receipt": "fidelity-128.json", + "tokens": 128, + "band_ratio_before": 1.854915614210866, + "band_ratio_after": 1.1400186203421705, + "band_gate_passed": false, + "greedy_disagreements_after": 6, + "resident_execution_window_passed_after": true, + "release_qualified": false, + "latest_projection_order_capture": { + "band_ratio": 1.1400186203421705, + "greedy_disagreements": 6, + "execution_disk_read_bytes": 4096, + "execution_pageins": 0, + "resident_execution_window_passed": false, + "release_qualified": false + } + }, + "scalar_projection_m4_and_m5": { + "registrations_passed_per_chip": 27, + "registrations_failed": 0, + "known_findings": 0, + "controls_caught_per_chip": 108, + "controls_missed": 0, + "gate_1_through_4_passed": true, + "gate_5_passed": true, + "launch_threads": 32, + "threadgroup_bytes": 1536, + "live_max_threads_m4": 1024, + "live_max_threads_m5": 1024, + "offline_max_threads_m1": 1024, + "offline_max_threads_m2": 1024, + "scope": "Actual scalar execution and resource reflection on M4 and M5; M1/M2 are offline compilation only." + }, + "combined_projection_m5": { + "tensor_registrations": 261, + "scalar_registrations": 27, + "total_registrations": 288, + "entrypoints": 14, + "numerical_controls_caught": 1152, + "numerical_controls_missed": 0, + "real_findings": 0, + "known_findings": 0 + }, + "final_integrated_m5_before_mtp_admission": { + "build_steps_succeeded": 63, + "tests_passed": 47, + "projection_chain_and_native_resource_findings": 0, + "actual_resource_controls_caught_per_limits_run": 2 + }, + "served_trained_mtp": { + "context": 65536, + "parallel": 4, + "prompt_cache_gib": 0, + "lookup": null, + "mtp_enabled": true, + "taps_enabled": true, + "proposal_capacity": 4, + "standard_benchmark": { + "max_tokens": 256, + "repetitions": 3, + "temperatures": [0], + "exit_code": 0 + }, + "plain_versus_drafted_full_hash_pairs_passed": 12, + "concurrent_versus_solo_full_token_hashes_passed": 8, + "post_cancel_full_token_hash_passed": true, + "trained_proposer_unavailable_warnings": 0, + "greedy_code": { + "accepted": 3, + "drafted": 10, + "plain_decode_tps_rounded": 52.23, + "mtp_decode_tps_rounded": 51.60 + }, + "greedy_prose": { + "accepted": 6, + "drafted": 10, + "plain_decode_tps_rounded": 52.20, + "mtp_decode_tps_rounded": 52.19 + }, + "speedup_proven": false, + "no_slowdown_gate_passed": false, + "scope": "Actual MTP capability admission and proposals with lookup unset; shared rounds stay plain. Does not qualify independent whole-model fidelity." + }, + "served_mtp_unload_reload": { + "native_build_steps_succeeded": 66, + "temperature": 0.8, + "seed": 1234, + "completion_tokens_per_reply": 256, + "full_token_sha256": "f8609e4a5d0509a12f66e98c432edf7eda1bf823f8bf1cdf667f39a278643cdd", + "full_output_hash_equal_after_reload": true, + "mtp_accepted_total_after_reload": 6, + "mtp_drafted_total_after_reload": 20, + "cycles": [ + { + "resident_phys_footprint_bytes": 218901594680, + "unloaded_phys_footprint_bytes": 119178512, + "released_phys_footprint_bytes": 218782416168 + }, + { + "resident_phys_footprint_bytes": 218907165432, + "unloaded_phys_footprint_bytes": 120227112, + "released_phys_footprint_bytes": 218786938320 + } + ], + "fully_parked_state_verified_from_load_ledger": true, + "server_survived_unload": true, + "graceful_shutdown_exit_code": 0, + "trained_proposer_unavailable_warnings": 0, + "probe_correction": "Uses current ri_phys_footprint, not lifetime maximum, and waits for /v1/load parked=true after engine close. HTTP 503 alone also describes the still-unloading transition.", + "scope": "Actual served MTP unload, reload, exact sampled response and shutdown; not a model-fidelity or no-slowdown verdict." + }, + "cold_default_policy": { + "context": 131072, + "parallel": 4, + "prompt_cache_gib": 0, + "mtp_enabled": false, + "prefill_step_override": null, + "cases": [ + { + "prompt_tokens": 2048, + "replies": 7, + "generated_tokens_per_reply": 256, + "cached_tokens_every_reply": 0, + "full_hashes_equal": true, + "first_ttft_seconds": 1.7693967500235885, + "first_decode_tps": 49.47872025118041, + "fixture_sha256": "a9c55dc5966cd194041aad9ac8f03de7ca81f1e461d387c5253c2ac6ea4416f0", + "full_token_sha256": "9ef3cc1f6f11485131c610033fbf2a7bbb6aee4733c810757209ce80cd90e15b", + "concurrent_timing": { + "requested_requests": 4, + "timed_requests": 4, + "makespan_s": 18.439526708971243, + "end_to_end_tps": 55.53287869920224, + "timing_valid": true + } + }, + { + "prompt_tokens": 8192, + "replies": 7, + "generated_tokens_per_reply": 256, + "cached_tokens_every_reply": 0, + "full_hashes_equal": true, + "first_ttft_seconds": 3.70275529200444, + "first_decode_tps": 49.172771365517484, + "fixture_sha256": "4639f4b9e6a7560fbc4317c8b7efbf5d130e78caa423cfee7d3d59158844a5da", + "full_token_sha256": "8c42a6046105386a0b850d0498a8165d35a2ff6b8c22ede1c092e7e6042865e5", + "concurrent_timing": { + "requested_requests": 4, + "timed_requests": 4, + "makespan_s": 26.719819499994628, + "end_to_end_tps": 38.323612178600456, + "timing_valid": true + } + }, + { + "prompt_tokens": 32768, + "replies": 7, + "generated_tokens_per_reply": 256, + "cached_tokens_every_reply": 0, + "full_hashes_equal": true, + "first_ttft_seconds": 12.759616958966944, + "first_decode_tps": 48.560730179653405, + "fixture_sha256": "d0795240ae881e529754bd9146e5588084706465b0773e554e6547b630c38f1f", + "full_token_sha256": "7025b3d9b6e542d6e04d9682ed6a6ae59c43d1c5c64443f2ed807e731cdebb4c", + "concurrent_timing": { + "requested_requests": 4, + "timed_requests": 4, + "makespan_s": 64.57552454195684, + "end_to_end_tps": 15.8574011943902, + "timing_valid": true + } + }, + { + "prompt_tokens": 65536, + "replies": 7, + "generated_tokens_per_reply": 256, + "cached_tokens_every_reply": 0, + "full_hashes_equal": true, + "first_ttft_seconds": 25.093715041002724, + "first_decode_tps": 47.634514745820816, + "fixture_sha256": "c8dfe7fc845d3b05d9d0deedc21bfb3498bcf05baaedaad5a834e4874cee9a9f", + "full_token_sha256": "6e6b46485f7c3afd309b3b932dde895c48933050c4d5a7d76f5bf61403a1e87f", + "concurrent_timing": { + "requested_requests": 4, + "timed_requests": 4, + "makespan_s": 116.46250274998602, + "end_to_end_tps": 8.792529576650567, + "timing_valid": true + } + } + ], + "graceful_shutdown_exit_code": 0, + "lifetime_peak_phys_footprint_bytes": 225854658488 + }, + "retained_mtp_native_window": { + "context": 1048576, + "parallel": 4, + "prompt_cache_gib": 2, + "native_window_admitted": true, + "plain_versus_drafted_full_hash_pairs": 8, + "concurrent_versus_solo_full_hashes": 8, + "sampled_retained_post_cancel_full_hash_equal": true, + "long_prompt_tokens": 8192, + "long_first_cached_tokens": 0, + "long_subsequent_cached_tokens": 8064, + "short_prompt_tokens": [ + 22 + ], + "short_cached_tokens": 0, + "actual_trained_mtp_drafts_in_solo_pairs": 80.0, + "original_probe_failed": [ + "retention_not_observed:prose", + "retention_not_observed:prose", + "retention_not_observed:prose", + "retention_not_observed:prose", + "concurrent_retention_not_observed:prose", + "concurrent_retention_not_observed:prose", + "concurrent_retention_not_observed:prose", + "concurrent_retention_not_observed:prose" + ], + "probe_correction": "Original probe incorrectly demanded short prose retention; existing tail/end mark rules require prompt>4096. Original HTTP replies audited against real policy without rerunning or changing code/defaults.", + "original_probe_exit_code": 1, + "corrected_recorded_observations_passed": true, + "scope": "Original real HTTP records; eligible 8k retention and full hashes audited without a rerun. The original command did not pass its invalid short-prompt retention assertions." + }, + "final_full_contributing_build": { + "command": "zig build test test-golden dev-tools native tf-dsv41-run test-deepseek-v41-lifetime -Dcpu=apple_m1 -Dversion=1.0.0 -Doptimize=ReleaseSafe -j4 --summary all", + "hardware": "M5 Ultra", + "zig_version": "0.17.0", + "exit_code": 0, + "steps_succeeded": 977, + "steps_total": 977, + "reported_tests_passed": 1603, + "reported_tests_skipped": 53, + "reported_tests_total": 1656, + "unchanged_steps_cached": true, + "direct_lifetime_cases_passed": 5, + "elapsed_seconds": 486.02301579201594, + "qkv_diagnostic": {"cells": 1792, "unequal": 1, "nrms": 0.0000001201090447169946, "worst": 0.006024096385542169, "unchanged_bounds_passed": true}, + "source_sha256": { + "backend_run.zig": "4a9cf06bbe8fe0c2685d707e4c53a3219af912a6750e2c72550497971c59632e", + "deepseek_v41_lifetime_checks.zig": "0b4571bf0e8164fbe155d1689f6b8e375c90e38eea7b8ca4c4c81d4575c2fde5", + "build_deepseek_v41.zig": "2c19585de8a1b725407f8e6d24b75c9bb4ea28971094b79b285673c2022c6952", + "deepseek_v41_run.zig": "450155183844565b08181b4a9104e98f6f34a73b8b1d99d35e859ad17dd440b8", + "forward_impl.zig": "e0c4eec4a305e31d2771007f4c3ec670fcb5d385e979a38a5c528b85145e9126" + }, + "source_scope": "Includes final lookup preference, canonical context, trained depth, diagnostic workspace and deferred mHC counter-span repairs.", + "scope": "Full requested corpus passes; cached counts and subsequent strict profile results are separate from independent model fidelity and release gates." + }, + "post_policy_full_contributing_build": { + "command": "zig build test test-golden dev-tools native test-deepseek-v41-lifetime -Dcpu=apple_m1 -Dversion=1.0.0 -Doptimize=ReleaseSafe -j4 --summary all", + "hardware": "M5 Ultra", + "exit_code": 0, + "steps_succeeded": 973, + "steps_total": 973, + "reported_tests_passed": 1529, + "reported_tests_skipped": 53, + "unchanged_steps_cached": true, + "direct_lifetime_cases_passed": 4, + "lifetime_cases": ["host ownership", "Metal ID-buffer growth preserves pending Markov picks", "trained-only adaptive depth", "lookup uses committed stream context"], + "source_sha256": { + "backend.zig": "b4150156e9bc9e3cc1725298432a6ae90f468bafcc90c9c9b0cf9d3b5531d23c", + "backend_run.zig": "556660b1c6a7a55c36ebcde3d24ab61ab81a2a601dcee43e8c62cb2e459a6045", + "backend_policy.zig": "5bd8478dd7a74b352f413bbb23b75832b51da9525da687ca97d42efc26f12c9d", + "backend_prefill.zig": "6ca7b78b8f0aa89adb35a1abf2267746b81af222d37f94399ec03a4660467a40", + "build_deepseek_v41.zig": "8c893f7beeecc263999db687819732cf6abc61bff784914310c3907686b08dc8", + "deepseek_v41_lifetime_checks.zig": "20f435e99351d4bbcca7181945d7479219eddf35bb6ac7166acaf5220baefc9f" + }, + "qkv_diagnostic": { + "cells": 1792, + "unequal": 1, + "nrms": 0.0000001201090447169946, + "worst": 0.006024096385542169, + "unchanged_bounds_passed": true + }, + "scope": "All requested steps pass; reported counts include caching. Served evidence predates these final policy/context repairs. Does not qualify the later diagnostic workspace adapter or clear independent full-model gates." + }, + "final_strict_profile_matrix": { + "hardware": "M5 Ultra", + "source": "final_full_contributing_build", + "command": "TF_DSV41_PREFILL_STEP=16 tf-dsv41-run profile PACK STREAM tokens-N.json OUT", + "context_capacity": 1048576, + "workspace_rows": 16, + "results": [ + {"rows": 1, "exit_code": 0, "same_logits": true, "gpu_profile_published": true, "sampled_span_gpu_seconds": 0.018823253, "resident_gate_passed": true, "execution_disk_read_bytes": 0, "execution_pageins": 0}, + {"rows": 2, "exit_code": 1, "error": "ProfileChangedLogits", "gpu_profile_published": false, "resident_gate_passed": true, "execution_disk_read_bytes": 0, "execution_pageins": 0}, + {"rows": 4, "exit_code": 1, "error": "ProfileChangedLogits", "gpu_profile_published": false, "resident_gate_passed": true, "execution_disk_read_bytes": 0, "execution_pageins": 0} + ], + "scope": "One-row strict profile passes in this invocation; multirow exactness fails. Does not clear earlier 128-row fidelity/residency, no-slowdown or release gates." + }, + "final_row_repair_profile_matrix": { + "hardware": "M5 Ultra", + "forward_impl_sha256": "addc00ce671f94a893270618adee22ced74998ba6d728c1498dc45fbe140c4bb", + "repair": "Shift every per-row fused final-expansion view to the selected output row before the unchanged kernel dispatch.", + "diagnostic_build_exit_code": 0, + "prior_full_corpus_source_scope": "The preceding 977-step corpus predates this repair.", + "command": "TF_DSV41_ENGRAM_STREAM_DIR=STREAM TF_DSV41_PREFILL_STEP=16 tf-dsv41-run profile PACK STREAM tokens-N.json OUT", + "context_capacity": 1048576, + "workspace_rows": 16, + "strict_logit_gate_unchanged": true, + "results": [ + {"rows": 1, "exit_code": 1, "same_logits": true, "gpu_profile_published": true, "sampled_span_gpu_seconds": 0.01879571, "resident_gate_passed": false, "execution_disk_read_bytes": 3080192, "execution_pageins": 45}, + {"rows": 2, "exit_code": 0, "same_logits": true, "gpu_profile_published": true, "sampled_span_gpu_seconds": 0.027028085, "resident_gate_passed": true, "execution_disk_read_bytes": 0, "execution_pageins": 0}, + {"rows": 4, "exit_code": 0, "same_logits": true, "gpu_profile_published": true, "sampled_span_gpu_seconds": 0.041256751, "resident_gate_passed": true, "execution_disk_read_bytes": 0, "execution_pageins": 0} + ], + "model_qualified": false, + "scope": "Clears the concrete multirow last-logit bug, not the independent full-model band, residency, no-slowdown, parent or hardware gates." + }, + "after_final_row_full_contributing_build": { + "command": "zig build test test-golden dev-tools native tf-dsv41-run test-deepseek-v41-lifetime -Dcpu=apple_m1 -Dversion=1.0.0 -Doptimize=ReleaseSafe -j4 --summary all", + "exit_code": 0, + "steps_succeeded": 977, + "steps_total": 977, + "reported_tests_passed": 1588, + "reported_tests_skipped": 53, + "reported_tests_total": 1641, + "unchanged_steps_may_be_cached": true, + "forward_impl_sha256": "addc00ce671f94a893270618adee22ced74998ba6d728c1498dc45fbe140c4bb", + "source_scope": "Includes the selected-final-row correction in addition to the earlier policy/context/workspace/counter-span repairs.", + "full_model_qualified": false, + "scope": "Current-source requested corpus succeeds. The fresh 128-token GPU capture is byte-identical to the earlier failed-band capture and independently fails execution residency." + }, + "current_source_serving_lifecycle": { + "forward_impl_sha256": "addc00ce671f94a893270618adee22ced74998ba6d728c1498dc45fbe140c4bb", + "context_capacity": 1048576, + "parallel": 4, + "retained_cache_gib": 4, + "completed_replies": 41, + "cancelled_after_generated_content": 1, + "actual_capacity_input_tokens": 65536, + "full_token_and_output_hashes_match_own_plain_controls": true, + "sampled_reply_after_cancellation_exact": true, + "unload_reload_cycles": 2, + "sampled_replies_after_reload_exact": true, + "loaded_phys_footprint_bytes": [226962856920, 222969100760], + "fully_parked_phys_footprint_bytes": [147244328, 149833024], + "fully_parked_state_observed": true, + "trained_only_lookup_depth": 0, + "trained_only_actual_mtp_drafted_total": 370, + "trained_only_full_hashes_match_plain": true, + "mixed_server_exit_code": 0, + "trained_only_server_exit_code": 0, + "scope": "Current contribution engine's own greedy/sampled, solo/shared, cancellation, reload and trained-only invariants. Not cross-engine equality, universal performance, no-slowdown, release or full-model fidelity qualification." + }, + "current_source_cuda_host_subset": { + "command": "zig build test-cuda-host -Dcpu=apple_m1 -Dversion=1.0.0 -Doptimize=ReleaseSafe -j4 --summary all", + "hardware": "M5 Ultra", + "host_os": "macOS", + "gpu_work": false, + "exit_code": 0, + "steps_succeeded": 345, + "steps_total": 345, + "reported_tests_passed": 131, + "unchanged_steps_may_be_cached": true, + "scope": "Required device-free CUDA host subset on the current source; reported counts exclude unchanged cached work. No CUDA GPU or Linux-runtime qualification claim." + } +} diff --git a/docs/receipts/dsv41-exl3-metal/prompts.py b/docs/receipts/dsv41-exl3-metal/prompts.py new file mode 100644 index 00000000000..9b9b1f6f495 --- /dev/null +++ b/docs/receipts/dsv41-exl3-metal/prompts.py @@ -0,0 +1,44 @@ +"""Generate the public short and synthetic long EXL3 qualification prompts.""" +import json +from pathlib import Path +import sys + +SHORT = [ + { + "name": "code-quicksort", + "kind": "completion", + "prompt": "def quicksort(xs):\n \"\"\"Sort a list with quicksort.\"\"\"\n" + }, + { + "name": "rust-reverse", + "kind": "chat", + "prompt": "Write a Rust function that reverses the words of a sentence, with a unit test." + }, + { + "name": "network-protocols", + "kind": "chat", + "prompt": "Compare TCP and UDP: reliability, ordering, congestion control, and typical uses." + }, + { + "name": "database-join", + "kind": "chat", + "prompt": "Explain what a SQL LEFT JOIN returns compared with an INNER JOIN, with a tiny example table." + } +] +PARAGRAPH = 'A cache stores recently used values so a later request can avoid repeating expensive work. Each entry has a key, a value and a version. Readers check the version before reusing an entry. A writer publishes the new value before making its version visible. Independent requests keep their own state.\n' + + +def main(): + directory = Path(sys.argv[1]) + directory.mkdir(parents=True, exist_ok=True) + long = [{"name": f"long-cache-{i}", "kind": "chat", + "prompt": f"Document {i}. Read the following engineering notes.\n" + + PARAGRAPH * 250 + + f"\nFor document {i}, explain why checking a cached entry version matters. Give a concrete example."} + for i in range(4)] + for name, prompts in (("short", SHORT), ("long", long)): + (directory / f"{name}-prompts.json").write_text(json.dumps(prompts, indent=2) + "\n", encoding="utf-8") + + +if __name__ == "__main__": + main() diff --git a/tools/bench_exl3_compare.py b/tools/bench_exl3_compare.py new file mode 100644 index 00000000000..e0d74f2af29 --- /dev/null +++ b/tools/bench_exl3_compare.py @@ -0,0 +1,92 @@ +"""Compare two bench_concurrent receipts; missing or unequal token evidence fails closed.""" +import argparse +import json +import sys + + +def cells(report): + result = {} + for cell in report["cells"]: + key = (cell["prompt"], cell["temperature"], cell["streams"]) + if key in result: + raise ValueError("duplicate benchmark cell") + result[key] = cell + if not result: + raise ValueError("empty benchmark receipt") + return result + + +def hashes(cell): + if cell["failed"] or cell["unmeasured"] or not cell["timing_valid"]: + raise ValueError("failed, unmeasured or invalid-timing requests") + for name in ("alone", "serial"): + checks = cell[name] + if checks["unequal"] or checks["failed"] or checks["equal"] < 1: + raise ValueError(f"{name} token equality did not pass") + result = [] + for rep in cell["reps"]: + pairs = rep["comparisons"] + if len(pairs) != cell["streams"]: + raise ValueError("missing stream comparisons") + for pair in pairs: + values = [] + for mode in ("serial", "alone", "concurrent"): + run = pair[mode] + digest = run["token_sha256"] + if (not run["complete"] or run["error"] or not run["tokens"] + or not isinstance(digest, str) or len(digest) != 64): + raise ValueError("missing complete full-token-hash evidence") + int(digest, 16) + values.append((run["tokens"], digest)) + if values[0] != values[1] or values[1] != values[2]: + raise ValueError("serial, solo and concurrent tokens differ") + result.append(values[2]) + if not result: + raise ValueError("no measured replies") + return result + + +def timing(cell): + return {name: cell.get(name) for name in ( + "aggregate_tps", "per_stream_tps", "end_to_end_tps", "steady_tps", "ttft_s_max")} + + +def compare(before, after): + if before["tokens"] != after["tokens"]: + raise ValueError("different requested output lengths") + if before.get("prompts") != after.get("prompts"): + raise ValueError("different prompt identities") + old, new = cells(before), cells(after) + if old.keys() != new.keys(): + raise ValueError("different benchmark cells") + rows = [] + for key, a in old.items(): + b = new[key] + ah, bh = hashes(a), hashes(b) + if ah != bh: + raise ValueError(f"baseline/candidate token mismatch: {key}") + rows.append({"prompt": key[0], "temperature": key[1], "streams": key[2], + "equal_replies": len(ah), "before": timing(a), "after": timing(b)}) + return {"token_equal": True, "rows": rows} + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("before") + parser.add_argument("after") + args = parser.parse_args() + try: + with open(args.before, encoding="utf-8") as f: + before = json.load(f) + with open(args.after, encoding="utf-8") as f: + after = json.load(f) + result = compare(before, after) + except (OSError, ValueError, KeyError, TypeError) as exc: + print(f"comparison failed: {exc}", file=sys.stderr) + return 1 + print(json.dumps(result, indent=2)) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/zig/check_dsv41_metal_mirrors.sh b/tools/zig/check_dsv41_metal_mirrors.sh new file mode 100755 index 00000000000..106aabcb4f9 --- /dev/null +++ b/tools/zig/check_dsv41_metal_mirrors.sh @@ -0,0 +1,11 @@ +#!/bin/sh +# Compile the DeepSeek V4.1 family's Metal sources at build time. +set -eu +root=$(CDPATH= cd -- "$(dirname -- "$0")/../.." && pwd) +dir="$root/zig/kernels/metal/deepseek_v41" +[ -d "$dir" ] || { echo "metal mirrors: $dir not found"; exit 2; } +[ -f "$root/zig/kernels/metal/nax.h" ] || { echo "metal mirrors: nax.h not found"; exit 2; } +command -v xcrun >/dev/null 2>&1 || { echo "metal mirrors: xcrun not on PATH"; exit 2; } +command -v python3 >/dev/null 2>&1 || { echo "metal mirrors: python3 not on PATH"; exit 2; } + +exec python3 "$root/tools/zig/dsv41_metal_struct_sizes.py" "$dir" diff --git a/tools/zig/dsv41_metal_struct_sizes.py b/tools/zig/dsv41_metal_struct_sizes.py new file mode 100755 index 00000000000..a6d5bd4b902 --- /dev/null +++ b/tools/zig/dsv41_metal_struct_sizes.py @@ -0,0 +1,210 @@ +#!/usr/bin/env python3 +"""The DeepSeek V4.1 Metal struct manifest: compile every struct in its engine unit, fail on size drift.""" +import os +import re +import shutil +import subprocess +import sys +import tempfile + +# The engine's run-time joins (csa2.zig:91, csa2_index.zig:164, metal/pipelines.zig:122). +JOINS = [ + ("csa2-kv-join", ["kv.metal", "csa2.metal", "csa2_nax.metal", "csa2_rows.metal"], None), + ("index-kv-join", ["kv.metal", "index_exl3.metal", "index_exl3_nax.metal"], None), + ("route-defines", ["route.metal"], "#define TF_DSV41_E 384\n#define TF_DSV41_TOPK 6\n"), + ("experts-units-join", ["experts_mma.metal", "experts_units.metal"], None), +] +JOIN_ONLY = {"csa2.metal", "csa2_nax.metal", "csa2_rows.metal", "index_exl3.metal", "index_exl3_nax.metal", "route.metal", "experts_units.metal"} +# The sources `sources.zig` embeds as `segs_h ++ @embedFile(...)`: the slot table's record first. +SEGS_PREPEND = {"csa2_attn.metal", "fused.metal", "compress.metal", "cand.metal", "index.metal"} +# The units the engine compiles after keyed.metal (early_picks.zig, markov.zig): its tf_key_* helpers first. +KEYED_PREPEND = {"early.metal", "markov.metal"} + +STRUCT_DEF = re.compile(r"\bstruct\s+([A-Za-z_]\w*)\s*\{") +TEMPLATE_DEF = re.compile(r"\btemplate\s*<[^>]*>\s*struct\s+([A-Za-z_]\w*)\s*\{") +KERNEL = re.compile(r"(?:\[\[\s*kernel[^\]]*\]\]\s*|\bkernel\s+)void\s+([A-Za-z_]\w*)\s*\(") +ARG = re.compile(r"\b(?:constant|device)\s+(?:const\s+)?([A-Za-z_]\w*)\s*[&*]") +LAYOUT = re.compile(r"^\s*\|\s*\[sizeof=(\d+),") +LAYOUT_NAME = re.compile(r"^\s*\d+\s*\|\s*struct\s+([A-Za-z_]\w*)\s*$") + + +def unit_texts(directory): + """The text of every compiled unit: each standalone source plus the three joins.""" + texts = {} + for name, parts, prefix in JOINS: + body = "".join(open(os.path.join(directory, p), encoding="utf-8").read() for p in parts) + texts[name] = (prefix or "") + body + segs = open(os.path.join(directory, "segs.h"), encoding="utf-8").read() + keyed = open(os.path.join(directory, "keyed.metal"), encoding="utf-8").read() + for entry in sorted(os.listdir(directory)): + if not entry.endswith(".metal") or entry in JOIN_ONLY: + continue + body = open(os.path.join(directory, entry), encoding="utf-8").read() + prefix = segs if entry in SEGS_PREPEND else (keyed if entry in KEYED_PREPEND else "") + texts[entry[:-6]] = prefix + body + return texts + + +def unit_of_source(source, sources): + """The unit name that compiles `source` (a join if it is join-only, else its own).""" + for name, parts, _ in JOINS: + if source in parts: + return name + assert source in sources, source + return source[:-6] + + +def dump(directory, work, unit, text): + """Compile one unit with the record-layout dump; return (sizes, error text or None).""" + path = os.path.join(work, "deepseek_v41", unit + ".metal") + with open(path, "w", encoding="utf-8") as f: + f.write(text) + run = subprocess.run( + ["xcrun", "-sdk", "macosx", "metal", "-Xclang", "-fdump-record-layouts", "-c", path, + "-o", os.path.join(work, "deepseek_v41", unit + ".air")], + capture_output=True, text=True) + if run.returncode != 0: + return None, run.stderr + sizes = {} + current = None + for line in run.stdout.splitlines(): + match = LAYOUT_NAME.match(line) + if match: + current = match.group(1) + continue + match = LAYOUT.match(line) + if match and current: + sizes[current] = int(match.group(1)) + current = None + return sizes, None + + +def kernel_arg_structs(text, defined): + """Every struct type a kernel in `text` takes by reference or pointer.""" + found = set() + for match in KERNEL.finditer(text): + start = match.end() + depth, at = 1, start + while at < len(text) and depth: + if text[at] == "(": + depth += 1 + elif text[at] == ")": + depth -= 1 + at += 1 + for arg in ARG.finditer(text[start:at]): + if arg.group(1) in defined: + found.add(arg.group(1)) + return found + + +def main(argv): + update = "--update" in argv + args = [a for a in argv[1:] if not a.startswith("--")] + root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + directory = args[0] if args else os.path.join(root, "zig", "kernels", "metal", "deepseek_v41") + manifest_path = os.path.join(directory, "struct_sizes.txt") + if not os.path.isdir(directory): + print(f"metal struct sizes: {directory} not found") + return 2 + if not shutil.which("xcrun"): + print("metal struct sizes: xcrun not on PATH") + return 2 + + sources = [e for e in sorted(os.listdir(directory)) if e.endswith(".metal")] + texts = unit_texts(directory) + work = tempfile.mkdtemp(prefix="dsv41-struct-sizes.") + try: + nax = os.path.join(root, "zig", "kernels", "metal", "nax.h") + if not os.path.exists(nax): + nax = os.path.join(directory, "..", "nax.h") + shutil.copy(nax, os.path.join(work, "nax.h")) + # The sources `#include "../nax.h"` and at least one includes another source by name. + os.makedirs(os.path.join(work, "deepseek_v41"), exist_ok=True) + for source in sources: + shutil.copy(os.path.join(directory, source), os.path.join(work, "deepseek_v41", source)) + + layouts, failures = {}, {} + for unit, text in texts.items(): + sizes, error = dump(directory, work, unit, text) + if sizes is None: + failures[unit] = error + else: + layouts[unit] = sizes + + # The manifest: one line a struct, keyed by the file that defines it. + lines = {} + for source in sources: + unit = unit_of_source(source, sources) + if unit not in layouts: + continue + text = open(os.path.join(directory, source), encoding="utf-8").read() + for name in set(STRUCT_DEF.findall(text)) - set(TEMPLATE_DEF.findall(text)): + if name not in layouts[unit]: + failures.setdefault(unit, f"no record layout for struct {name} ({source})") + continue + lines[(source, name)] = layouts[unit][name] + manifest = "".join(f"{source} {name} {lines[(source, name)]}\n" for source, name in sorted(lines)) + + fail = 0 + for unit, error in sorted(failures.items()): + print(f"FAIL {unit}") + for line in (error or "").splitlines()[:12]: + print(" " + line) + fail = 1 + + # Every kernel argument struct must assert its own size in the unit that compiles it. + for unit, text in texts.items(): + if unit not in layouts: + continue + defined = set(STRUCT_DEF.findall(text)) - set(TEMPLATE_DEF.findall(text)) + asserted = set(re.findall(r"static_assert\s*\(\s*sizeof\s*\(\s*([A-Za-z_]\w*)\s*\)", text)) + for name in sorted(kernel_arg_structs(text, defined) - asserted): + print(f"FAIL {unit}: kernel argument struct `{name}` has no " + f"static_assert(sizeof({name}) == N) in this unit") + fail = 1 + + if update and not fail: + with open(manifest_path, "w", encoding="utf-8") as f: + f.write("# DeepSeek V4.1 Metal struct sizes: one `source struct bytes` a line.\n") + f.write("# Generated by tools/zig/dsv41_metal_struct_sizes.py --update from the Metal\n") + f.write("# compiler's own record layouts. `zig build` fails when this file goes stale.\n") + f.write(manifest) + print(f"metal struct sizes: wrote {manifest_path} ({len(lines)} structs)") + return 0 + + try: + current = open(manifest_path, encoding="utf-8").read() + except FileNotFoundError: + print(f"FAIL metal struct sizes: {manifest_path} is missing (regenerate with --update)") + return 1 + recorded = {} + for line in current.splitlines(): + if not line or line.startswith("#"): + continue + source, name, size = line.split() + recorded[(source, name)] = int(size) + failed = {unit for unit in failures} + def known(key): + return unit_of_source(key[0], sources) not in failed + keys = {k for k in set(recorded) | set(lines) if known(k)} + for key in sorted(keys): + if key not in lines: + print(f"FAIL struct sizes: {key[0]} {key[1]} is in the manifest but no longer defined") + fail = 1 + elif key not in recorded: + print(f"FAIL struct sizes: {key[0]} {key[1]} {lines[key]} is new (regenerate the manifest)") + fail = 1 + elif recorded[key] != lines[key]: + print(f"FAIL struct sizes: {key[0]} {key[1]} {recorded[key]} -> {lines[key]}") + fail = 1 + if fail: + print("metal struct sizes: a shared struct's size moved, or a kernel argument has no assert") + return 1 + print(f"metal struct sizes: {len(lines)} structs match the manifest; every kernel argument asserts its size") + return 0 + finally: + shutil.rmtree(work, ignore_errors=True) + + +if __name__ == "__main__": + sys.exit(main(sys.argv)) diff --git a/tools/zig/lean_check.py b/tools/zig/lean_check.py index f56728f6cf8..a9130ff2b14 100644 --- a/tools/zig/lean_check.py +++ b/tools/zig/lean_check.py @@ -13,9 +13,9 @@ ".sh": re.compile(r"^\s*#(?!!)")} BLOCK = re.compile(r"/\*") DOCSTRING = re.compile(r'^\s*(?:[rubf]{0,2})("""|\'\'\')') -GENERATED = ("unicode_data.zig",) +GENERATED = ("unicode_data.zig", "nfkd_data.zig") HEX_METAL = re.compile(r"_[0-9a-f]{16}\.metal$") -# Generated outputs are skipped entirely. unicode_data.zig has only the length exemption. +# Generator outputs are skipped entirely, including the Unicode table files built from the release's tables. GENERATOR_OUTPUT = ( "zig/src/core/tokenizer/nfkd_data.zig", "zig/src/families/flashnext/roles_gen.zig", @@ -25,9 +25,9 @@ DIRECT_GETENV = re.compile(r'\bgetenv\(\s*"((?:TF|TENSORFOLD)_[A-Za-z0-9_]*)"') # A getenv of a name that is not a literal: a new wrapper or a held name would hide its setting from DIRECT_GETENV. HIDDEN_GETENV = re.compile(r'(? score) { + best = @intCast(i); + score = v; + } + } + return best; +} +fn write(io: std.Io, a: std.mem.Allocator, dir: []const u8, name: []const u8, data: []const u8) !void { + const path = try std.fs.path.join(a, &.{ dir, name }); + defer a.free(path); + try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = path, .data = data }); +} +const Counters = struct { disk_read: u64, pageins: u64, footprint: u64 }; +/// Darwin's full rusage_info_v4: the kernel writes all 336 bytes, so every field must be here. +const RUsage = extern struct { + uuid: [16]u8, + user_time: u64, + system_time: u64, + pkg_idle_wkups: u64, + interrupt_wkups: u64, + pageins: u64, + wired_size: u64, + resident_size: u64, + phys_footprint: u64, + proc_start_abstime: u64, + proc_exit_abstime: u64, + child_user_time: u64, + child_system_time: u64, + child_pkg_idle_wkups: u64, + child_interrupt_wkups: u64, + child_pageins: u64, + child_elapsed_abstime: u64, + diskio_bytesread: u64, + diskio_byteswritten: u64, + cpu_time_qos_default: u64, + cpu_time_qos_maintenance: u64, + cpu_time_qos_background: u64, + cpu_time_qos_utility: u64, + cpu_time_qos_legacy: u64, + cpu_time_qos_user_initiated: u64, + cpu_time_qos_user_interactive: u64, + billed_system_time: u64, + serviced_system_time: u64, + logical_writes: u64, + lifetime_max_phys_footprint: u64, + instructions: u64, + cycles: u64, + billed_energy: u64, + serviced_energy: u64, + interval_max_phys_footprint: u64, + runnable_time: u64, +}; +fn counters() !Counters { + const proc_pid_rusage = struct { + extern "c" fn proc_pid_rusage(pid: c_int, flavor: c_int, buffer: *anyopaque) c_int; + }.proc_pid_rusage; + const getpid = struct { + extern "c" fn getpid() c_int; + }.getpid; + var r: RUsage = undefined; + if (proc_pid_rusage(getpid(), 4, &r) != 0) return error.MemoryCountersUnavailable; + return .{ .disk_read = r.diskio_bytesread, .pageins = r.pageins, .footprint = r.phys_footprint }; +} +fn teacher(m: *ds.Model, ids: []const u32, chunk: u32, out: []f32) !f64 { + if (chunk == 0 or chunk > m.workspace.plan.rows or ids.len > m.cache.plan.capacity) + return error.InvalidTeacherWindow; + if (out.len != ids.len * 129280) return error.InvalidTeacherOutputLength; + try m.reset(); + var elapsed: f64 = 0; + var start: usize = 0; + while (start < ids.len) { + const end = @min(start + chunk, ids.len); + const row = try m.forward(ids[start..end], .all); + @memcpy(out[start * 129280 .. end * 129280], row); + for (row) |value| if (!std.math.isFinite(value)) return error.NonfiniteLogits; + elapsed += m.last_gpu_seconds; + start = end; + } + return elapsed; +} + +fn teacherOn(m: *ds.Model, slot: u32, ids: []const u32, chunk: u32, out: []f32) !f64 { + if (chunk == 0 or chunk > m.workspace.plan.rows or ids.len > m.caches[slot].plan.capacity) + return error.InvalidTeacherWindow; + if (out.len != ids.len * 129280) return error.InvalidTeacherOutputLength; + try m.resetSlot(slot); + var elapsed: f64 = 0; + var start: usize = 0; + while (start < ids.len) { + const end = @min(start + chunk, ids.len); + const row = try m.forwardOn(slot, ids[start..end], .all); + @memcpy(out[start * 129280 .. end * 129280], row); + for (row) |value| if (!std.math.isFinite(value)) return error.NonfiniteLogits; + elapsed += m.last_gpu_seconds; + start = end; + } + return elapsed; +} + +pub fn main(init: std.process.Init) !void { + const a = init.gpa; + const io = init.io; + const args = try init.minimal.args.toSlice(init.arena.allocator()); + if (args.len == 2 and (std.mem.eql(u8, args[1], "--help") or std.mem.eql(u8, args[1], "-h"))) usage(0); + if (!validArguments(args)) usage(2); + const arena = init.arena.allocator(); + const mode = args[1]; + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + if (std.mem.eql(u8, mode, "plan")) { + const cfg = try config.Config.read(arena, io, args[2]); + var plan = try load.Plan.open(a, io, args[2], args[3]); + defer plan.deinit(); + try weights.validate(&plan, false); + const device = try mtl.Device.init(); + defer device.deinit(); + std.debug.print("{{\"mode\":\"plan\",\"weight_bytes\":{d},\"shards\":{d},\"tensors\":{d},\"context\":{d},\"metal_working_set_bytes\":{d}}}\n", .{ plan.bytes, plan.shards.items.len, plan.tensors.count(), cfg.rope.max_positions, device.maxWorkingSet() }); + return; + } + const is_operators = std.mem.eql(u8, mode, "operators"); + const is_attention = std.mem.eql(u8, mode, "attention-sameinput"); + const is_attention_history = std.mem.eql(u8, mode, "attention-history-sameinput"); + const is_hc = std.mem.eql(u8, mode, "hc-sameinput"); + const is_moe = std.mem.eql(u8, mode, "moe-sameinput"); + const is_lanes = std.mem.eql(u8, mode, "lanes"); + const is_draftloop = std.mem.eql(u8, mode, "draftloop"); + const max_ids: usize = if (std.mem.eql(u8, mode, "margins")) 1048576 else if (std.mem.eql(u8, mode, "oracle") or std.mem.eql(u8, mode, "oracle-fp64")) 256 else if (std.mem.eql(u8, mode, "trace") or std.mem.eql(u8, mode, "gate")) 16 else if (std.mem.eql(u8, mode, "profile")) ds.prefill_step else if (std.mem.eql(u8, mode, "teacher") or std.mem.eql(u8, mode, "seams") or is_lanes) 4096 else 1048576; + const input = if (is_operators or is_attention or is_attention_history or is_hc or is_moe) &.{} else try std.Io.Dir.cwd().readFileAlloc(io, args[4], arena, .limited(max_ids * 12 + 2)); + const ids: []const u32 = if (is_operators or is_attention or is_attention_history or is_hc or is_moe) &.{} else try std.json.parseFromSliceLeaky([]const u32, arena, input, .{}); + if (!is_operators and !is_attention and !is_attention_history and !is_hc and !is_moe and (ids.len == 0 or ids.len > 1048576)) return error.InvalidPrompt; + if (ids.len > max_ids) return error.InvalidPrompt; + for (ids) |id| if (id >= 129280) return error.InvalidToken; + const is_oracle = std.mem.eql(u8, mode, "oracle"); + const is_oracle_fp64 = std.mem.eql(u8, mode, "oracle-fp64"); + // The floor is bound to the checkpoint metadata that produced it, not just to the token window. + const identity: [32]u8 = if (is_oracle or is_oracle_fp64) + try checkpointMetadataIdentity(a, io, args[2], args[3]) + else + @splat(0); + const is_trace = std.mem.eql(u8, mode, "trace"); + const is_gate = std.mem.eql(u8, mode, "gate"); + const dir = args[if (is_operators) @as(usize, 4) else 5]; + try std.Io.Dir.cwd().createDirPath(io, dir); + const map = try std.fs.path.join(arena, &.{ args[2], "engram-token-map.bin" }); + const map_blob = if (is_oracle or is_oracle_fp64 or is_trace or is_gate) + try std.Io.Dir.cwd().readFileAlloc(io, map, arena, .limited(2 << 20)) + else + &.{}; + const model = try a.create(ds.Model); + defer a.destroy(model); + const begin = mtl.clock.seconds(); + model.* = try ds.Model.open(a, io, .{ + .dir = args[2], + .table_dir = args[3], + .stream_dir = if (std.c.getenv("TF_DSV41_ENGRAM_STREAM_DIR")) |d| std.mem.span(d) else null, + .token_map = map, + .chunk_rows = blk: { + const raw = std.c.getenv("TF_DSV41_PREFILL_STEP") orelse break :blk ds.prefill_step; + const n = std.fmt.parseInt(u32, std.mem.span(raw), 10) catch break :blk ds.prefill_step; + if (n < 16) break :blk ds.prefill_step; + break :blk @min(n, 16384); + }, + .lanes = if (is_lanes or is_draftloop) 2 else 1, + .context = if (is_lanes and args.len > 7) try number(args[7]) else if (is_draftloop) 4096 else 0, + }); + defer model.deinit(); + const ready = mtl.clock.seconds(); + // The operator self-check runs before the measured window: its fixture I/O is diagnosis, not model execution. + if (is_oracle or is_oracle_fp64) try operators.run(a, io, model, dir); + const before = try counters(); + var execution_after: ?Counters = null; + var execution_error: ?anyerror = null; + execute(a, io, model, args, ids, map_blob, dir, before, identity, &execution_after) catch |err| { + execution_error = err; + }; + const after = execution_after orelse try counters(); + if (after.disk_read < before.disk_read or after.pageins < before.pageins) return error.NonmonotonicCounters; + const resident_gate_passed = after.disk_read == before.disk_read; + // The Engram stream is by design; its own logical rows and syscalls are reported beside the execution total. + const execution_bytes = after.disk_read - before.disk_read; + const stream_bytes: u64 = if (model.stream) |s| s.stats.bytes else 0; + const stream_syscalls: u64 = if (model.stream) |s| s.stats.syscalls else 0; + const stream_misses: u64 = if (model.stream) |s| s.stats.misses else 0; + const receipt = try std.json.Stringify.valueAlloc(a, .{ + .mode = mode, + .evidence_origin = "current_invocation_not_historical_qualification", + .context_capacity = model.cache.plan.capacity, + .workspace_rows = model.workspace.plan.rows, + .consumed_tokens = model.cache.position, + .weight_bytes = model.checkpoint.residentBytes(), + .resident_allocation_bytes = model.residency.allocatedSize(), + .ready_footprint_bytes = before.footprint, + .final_footprint_bytes = after.footprint, + .load_seconds = ready - begin, + .measurement_scope = if (execution_after != null) "model_execution" else "execution_and_diagnostic_io", + .diagnostic_self_check_outside_window = is_oracle or is_oracle_fp64, + .engram_streaming = model.stream != null, + .engram_stream_logical_bytes = stream_bytes, + .engram_stream_syscalls = stream_syscalls, + .engram_stream_misses = stream_misses, + .execution_disk_read_bytes = execution_bytes, + .execution_pageins = after.pageins - before.pageins, + .resident_gate_passed = resident_gate_passed, + .execution_error = if (execution_error) |err| @as(?[]const u8, @errorName(err)) else null, + }, .{}); + defer a.free(receipt); + std.debug.print("{s}\n", .{receipt}); + try write(io, a, dir, "residency.json", receipt); + if (!resident_gate_passed) std.debug.print("residency gate failed: ResidentExecutionReadFromDisk\n", .{}); + if (execution_error) |err| return err; + if (!resident_gate_passed) return error.ResidentExecutionReadFromDisk; +} + +/// Binds every oracle input: config, index, present shard headers, the token map and the Engram source opened. +fn checkpointMetadataIdentity(a: std.mem.Allocator, io: std.Io, pack: []const u8, tables: []const u8) ![32]u8 { + var arena: std.heap.ArenaAllocator = .init(a); + defer arena.deinit(); + const ar = arena.allocator(); + const Sha256 = std.crypto.hash.sha2.Sha256; + var h = Sha256.init(.{}); + const p = try checkpoint_identity.identityPresent(ar, io, pack); + h.update(&p); + // The token map is small and changes which Engram rows every token selects, so it is bound whole. + const map = try std.fs.path.join(ar, &.{ pack, "engram-token-map.bin" }); + if (std.Io.Dir.cwd().readFileAlloc(io, map, ar, .limited(2 << 20))) |bytes| { + h.update("engram-token-map.bin"); + h.update(std.mem.asBytes(&bytes.len)); + h.update(bytes); + } else |err| switch (err) { + error.FileNotFound => {}, + else => return err, + } + // A streamed run ignores table_dir; bind the directory the model and the reference actually read. + if (std.c.getenv("TF_DSV41_ENGRAM_STREAM_DIR")) |dir| { + const streamed = try checkpoint_identity.identityPresent(ar, io, std.mem.span(dir)); + h.update(&streamed); + } else { + const t = try checkpoint_identity.identityPresent(ar, io, tables); + h.update(&t); + } + return h.finalResult(); +} + +fn execute(a: std.mem.Allocator, io: std.Io, model: *ds.Model, args: []const [:0]const u8, ids: []const u32, map_blob: []const u8, dir: []const u8, before: Counters, identity: [32]u8, execution_after: *?Counters) !void { + const mode = args[1]; + const is_operators = std.mem.eql(u8, mode, "operators"); + const is_attention = std.mem.eql(u8, mode, "attention-sameinput"); + const is_attention_history = std.mem.eql(u8, mode, "attention-history-sameinput"); + const is_hc = std.mem.eql(u8, mode, "hc-sameinput"); + const is_moe = std.mem.eql(u8, mode, "moe-sameinput"); + const is_stagediff = std.mem.eql(u8, mode, "stagediff"); + const is_draftloop = std.mem.eql(u8, mode, "draftloop"); + const is_oracle = std.mem.eql(u8, mode, "oracle"); + const is_oracle_fp64 = std.mem.eql(u8, mode, "oracle-fp64"); + const is_profile = std.mem.eql(u8, mode, "profile"); + const is_trace = std.mem.eql(u8, mode, "trace"); + const is_gate = std.mem.eql(u8, mode, "gate"); + const is_teacher = std.mem.eql(u8, mode, "teacher"); + const is_seams = std.mem.eql(u8, mode, "seams"); + const is_lanes = std.mem.eql(u8, mode, "lanes"); + if (is_operators) { + try operators.run(a, io, model, dir); + } else if (is_attention) { + try attention_operators.runAttention(a, io, model, args[4], dir, if (args.len > 6) try number(args[6]) else 0); + } else if (is_attention_history) { + try history_operators.runAttentionHistory(a, io, model, args[4], dir, try number(args[6]), try number(args[7])); + } else if (is_hc) { + try hc_operators.runHyperconnections(a, io, model, args[4], dir, if (args.len > 6) try number(args[6]) else 0); + } else if (is_moe) { + try moe_operators.runMoe(a, io, model, args[4], dir, if (args.len > 6) try number(args[6]) else 21); + } else if (is_stagediff) { + try stagediff.run(a, io, model, ids, dir, if (args.len > 6) try number(args[6]) else null, if (args.len > 7) try number(args[7]) else null); + } else if (is_draftloop) { + try stagediff.loop(a, io, model, ids, dir, if (args.len > 6) try number(args[6]) else null, if (args.len > 7) try number(args[7]) else null); + } else if (is_oracle) { + defer execution_after.* = counters() catch null; + _ = try oracle.run(a, io, model, ids, map_blob, dir, identity); + } else if (is_oracle_fp64) { + // The same window against the FP64 chain (the reference chain at its ideal contract). + defer execution_after.* = counters() catch null; + _ = try oracle.runF64(a, io, model, ids, map_blob, dir, identity); + } else if (std.mem.eql(u8, mode, "margins")) { + try margins.run(a, io, model, ids, dir, if (args.len > 6) try number(args[6]) else 1536); + } else if (is_profile) { + try profile.run(a, io, model, ids, dir); + } else if (is_lanes) { + // Two lane slots, interleaved: each slot's rows and logits equal its own solo run's bits. + if (ids.len < 4) return error.InvalidPrompt; + const split = ids.len / 2; + const chunk = if (args.len > 6) try number(args[6]) else 1; + if (chunk == 0 or chunk > model.workspace.plan.rows) return error.InvalidPrefillChunk; + const solo_a = try a.alloc(f32, split * 129280); + defer a.free(solo_a); + const solo_b = try a.alloc(f32, (ids.len - split) * 129280); + defer a.free(solo_b); + var elapsed: f64 = 0; + elapsed += try teacherOn(model, 0, ids[0..split], chunk, solo_a); + elapsed += try teacherOn(model, 1, ids[split..], chunk, solo_b); + const position_a: u32 = model.caches[0].position; + const position_b: u32 = model.caches[1].position; + try model.reset(); + const mixed_a = try a.alloc(f32, solo_a.len); + defer a.free(mixed_a); + const mixed_b = try a.alloc(f32, solo_b.len); + defer a.free(mixed_b); + var at_a: usize = 0; + var at_b: usize = 0; + while (at_a < split or at_b < ids.len - split) { + if (at_a < split) { + const end = @min(at_a + chunk, split); + const row = try model.forwardOn(0, ids[at_a..end], .all); + @memcpy(mixed_a[at_a * 129280 .. end * 129280], row); + at_a = end; + } + if (at_b < ids.len - split) { + const end = @min(at_b + chunk, ids.len - split); + const row = try model.forwardOn(1, ids[split + at_b .. split + end], .all); + @memcpy(mixed_b[at_b * 129280 .. end * 129280], row); + at_b = end; + } + } + var error_a: f64 = 0; + var error_b: f64 = 0; + var bit_disagreements: usize = 0; + for (solo_a, mixed_a) |x, y| { + error_a = @max(error_a, @abs(@as(f64, x) - y)); + bit_disagreements += @intFromBool(@as(u32, @bitCast(x)) != @as(u32, @bitCast(y))); + } + for (solo_b, mixed_b) |x, y| { + error_b = @max(error_b, @abs(@as(f64, x) - y)); + bit_disagreements += @intFromBool(@as(u32, @bitCast(x)) != @as(u32, @bitCast(y))); + } + execution_after.* = try counters(); + std.debug.print("{{\"mode\":\"lanes\",\"slots\":2,\"chunk\":{d},\"max_logit_error_slot0\":{d},\"max_logit_error_slot1\":{d},\"bit_disagreements\":{d},\"position_slot0\":{d},\"position_slot1\":{d},\"gpu_seconds\":{d:.3}}}\n", .{ chunk, error_a, error_b, bit_disagreements, position_a, position_b, elapsed }); + if (bit_disagreements != 0) return error.LaneInterference; + } else if (is_trace) { + try trace.run(a, io, model, ids, map_blob, dir); + } else if (is_gate) { + // Same capture as `trace`, but ids are pinned to the engine's own selection. + try trace.runGate(a, io, model, ids, map_blob, dir); + } else if (is_teacher or is_seams) { + const chunk = if (args.len > 6) try number(args[6]) else model.workspace.plan.rows; + if (chunk == 0 or chunk > model.workspace.plan.rows) return error.InvalidPrefillChunk; + const outputs = try a.alloc(f32, ids.len * 129280); + defer a.free(outputs); + const elapsed = try teacher(model, ids, chunk, outputs); + if (is_seams) { + const alternative = try a.alloc(f32, outputs.len); + defer a.free(alternative); + for ([_]u32{ 1, 2, 3, 7, 31, 127, 128, 129, 255, 256 }) |split| { + if (split > model.workspace.plan.rows) continue; + _ = try teacher(model, ids, split, alternative); + var error_max: f64 = 0; + var disagreements: usize = 0; + var bit_disagreements: usize = 0; + for (outputs, alternative) |x, y| { + error_max = @max(error_max, @abs(@as(f64, x) - y)); + bit_disagreements += @intFromBool(@as(u32, @bitCast(x)) != @as(u32, @bitCast(y))); + } + for (0..ids.len) |i| { + if (try argmax(outputs[i * 129280 ..][0..129280]) != try argmax(alternative[i * 129280 ..][0..129280])) + disagreements += 1; + } + std.debug.print("{{\"mode\":\"seam\",\"chunk\":{d},\"max_logit_error\":{d},\"bit_disagreements\":{d},\"greedy_disagreements\":{d}}}\n", .{ split, error_max, bit_disagreements, disagreements }); + if (disagreements != 0 or bit_disagreements != 0) { + var name: [48]u8 = undefined; + const file = try std.fmt.bufPrint(&name, "seam-{d}-logits.f32", .{split}); + execution_after.* = try counters(); + try write(io, a, dir, file, std.mem.sliceAsBytes(alternative)); + return error.ChunkSeamMismatch; + } + } + } + std.debug.print("{{\"mode\":\"teacher\",\"tokens\":{d},\"gpu_seconds\":{d}}}\n", .{ ids.len, elapsed }); + execution_after.* = try counters(); + try write(io, a, dir, "logits.f32", std.mem.sliceAsBytes(outputs)); + } else if (std.mem.eql(u8, mode, "generate")) { + const n = if (args.len > 6) try number(args[6]) else 64; + if (ids.len > model.cache.plan.capacity or n == 0 or n > model.cache.plan.capacity - ids.len) + return error.ContextFull; + try model.reset(); + const prefill_start = mtl.clock.seconds(); + var row: []const f32 = &.{}; + var start: usize = 0; + var progress_at = prefill_start; + while (start < ids.len) { + const end = @min(start + model.workspace.plan.rows, ids.len); + row = try model.forward(ids[start..end], if (end == ids.len) .last else .none); + start = end; + const now = mtl.clock.seconds(); + if (now - progress_at >= 60 or start == ids.len) { + const memory = try counters(); + std.debug.print("{{\"mode\":\"prefill_progress\",\"completed_tokens\":{d},\"prompt_tokens\":{d},\"elapsed_seconds\":{d},\"footprint_bytes\":{d},\"disk_read_bytes\":{d},\"pageins\":{d}}}\n", .{ start, ids.len, now - prefill_start, memory.footprint, memory.disk_read - before.disk_read, memory.pageins - before.pageins }); + progress_at = now; + } + } + const prefill_end = mtl.clock.seconds(); + const generated = try a.alloc(u32, n); + defer a.free(generated); + var gpu_seconds: f64 = 0; + const decode_start = mtl.clock.seconds(); + for (generated, 0..) |*token, i| { + token.* = try argmax(row); + if (i + 1 < generated.len) { + row = try model.forward(&.{token.*}, .last); + gpu_seconds += model.last_gpu_seconds; + } + } + const decode_end = mtl.clock.seconds(); + execution_after.* = try counters(); + const json = try std.json.Stringify.valueAlloc(a, generated, .{}); + defer a.free(json); + try write(io, a, dir, "tokens.json", json); + std.debug.print("{{\"mode\":\"generate\",\"prompt_tokens\":{d},\"completion_tokens\":{d},\"prefill_seconds\":{d},\"decode_seconds\":{d},\"decode_gpu_seconds\":{d}}}\n", .{ ids.len, n, prefill_end - prefill_start, decode_end - decode_start, gpu_seconds }); + } else usage(2); +} diff --git a/zig/deepseek_v41_weights_checks.zig b/zig/deepseek_v41_weights_checks.zig new file mode 100644 index 00000000000..83eab08c1b0 --- /dev/null +++ b/zig/deepseek_v41_weights_checks.zig @@ -0,0 +1,8 @@ +//! Host checks for V4.1 configuration, Engram table plans and resident weight staging; no kernels compiled. +test { + _ = @import("src/families/deepseek_v41/config.zig"); + _ = @import("src/families/deepseek_v41/view.zig"); + _ = @import("src/families/deepseek_v41/engram_hash.zig"); + _ = @import("src/families/deepseek_v41/load_metal.zig"); + _ = @import("src/families/deepseek_v41/weights.zig"); +} diff --git a/zig/dsv41_core_family.zig b/zig/dsv41_core_family.zig new file mode 100644 index 00000000000..9f5a3dcdcb6 --- /dev/null +++ b/zig/dsv41_core_family.zig @@ -0,0 +1,13 @@ +//! The core modules the DeepSeek V4.1 family names as `core`: the family is its own module, so it cannot climb out. +pub const contract = @import("src/core/contract.zig"); +pub const exl3_layout = @import("src/core/exl3_layout.zig"); +pub const exl3_load = @import("src/core/exl3_load.zig"); +pub const exl3_prepare = @import("src/core/exl3_prepare.zig"); +pub const exl3_projection = @import("src/core/exl3_projection.zig"); +pub const exl3_projection_gpu_test = @import("src/core/exl3_projection_gpu_test.zig"); +pub const frags = @import("src/core/frags.zig"); +pub const expert_groups = @import("src/core/expert_groups.zig"); +pub const gpu_counters = @import("src/core/gpu_counters.zig"); +pub const paced_read = @import("src/core/paced_read.zig"); +pub const safetensors = @import("src/core/safetensors.zig"); +pub const safetensors_security_test = @import("src/core/safetensors_security_test.zig"); diff --git a/zig/dsv41_token_map.zig b/zig/dsv41_token_map.zig index 0bbd2008642..67bca37cff0 100644 --- a/zig/dsv41_token_map.zig +++ b/zig/dsv41_token_map.zig @@ -10,19 +10,20 @@ const Layer = struct { layer_id: u64, rows: u64, primes: [24]u32, offsets: [24]u const magic = "DSENGR01"; const source = "https://huggingface.co/deepseek-ai/DeepSeek-V4.1-Flash/blob/2cba9e42aa026125f3ed06c6d98c1db82f7ca027/inference/engram.py"; +/// The same build the lane host runs when the map is missing and the original's tokenizer sits beside the tables. pub fn main(init: std.process.Init) !void { - const a = init.gpa; - const io = init.io; const args = try init.minimal.args.toSlice(init.arena.allocator()); const paths = try parseArgs(args); - const tokenizer_path: ?[]const u8 = paths.tokenizer; - const config_path: ?[]const u8 = paths.config; - const output_path: ?[]const u8 = paths.output; - const tokenizer_bytes = try std.Io.Dir.cwd().readFileAlloc(io, tokenizer_path.?, a, .limited(64 << 20)); + try build(init.gpa, init.io, paths.tokenizer, paths.config, paths.output); +} + +/// Writes the map and its manifest for one release tokenizer and config, so the lane host can build it at open. +pub fn build(a: std.mem.Allocator, io: std.Io, tokenizer_path: []const u8, config_path: []const u8, output_path: []const u8) !void { + const tokenizer_bytes = try std.Io.Dir.cwd().readFileAlloc(io, tokenizer_path, a, .limited(64 << 20)); defer a.free(tokenizer_bytes); - const config_bytes = try std.Io.Dir.cwd().readFileAlloc(io, config_path.?, a, .limited(16 << 20)); + const config_bytes = try std.Io.Dir.cwd().readFileAlloc(io, config_path, a, .limited(16 << 20)); defer a.free(config_bytes); - var t = try tok.loadTokenizer(io, a, tokenizer_path.?); + var t = try tok.loadTokenizer(io, a, tokenizer_path); defer t.deinit(); const config = try @import("src/families/deepseek_v41/config.zig").Config.parseMetadata(a, config_bytes); @@ -128,7 +129,7 @@ pub fn main(init: std.process.Init) !void { } for (lookup) |v| try appendU32(&packed_buf, a, v); - var out_file = try std.Io.Dir.cwd().createFile(io, output_path.?, .{}); + var out_file = try std.Io.Dir.cwd().createFile(io, output_path, .{}); defer out_file.close(io); try out_file.writeStreamingAll(io, packed_buf.items); @@ -137,13 +138,13 @@ pub fn main(init: std.process.Init) !void { std.crypto.hash.sha2.Sha256.hash(packed_buf.items, &packed_sha, .{}); const manifest = try writeManifest(a, tokenizer_sha, config_sha, packed_sha, raw_vocab, compressed, pad, order, heads, layers); defer a.free(manifest); - const manifest_path = try std.fmt.allocPrint(a, "{s}.json", .{output_path.?}); + const manifest_path = try std.fmt.allocPrint(a, "{s}.json", .{output_path}); defer a.free(manifest_path); var m_file = try std.Io.Dir.cwd().createFile(io, manifest_path, .{}); defer m_file.close(io); try m_file.writeStreamingAll(io, manifest); - std.debug.print("token map: {d} raw ids -> {d} keys, {d} layers, {d} bytes written to {s}\n", .{ raw_vocab, compressed, layer_count, packed_buf.items.len, output_path.? }); + std.debug.print("token map: {d} raw ids -> {d} keys, {d} layers, {d} bytes written to {s}\n", .{ raw_vocab, compressed, layer_count, packed_buf.items.len, output_path }); } fn writeManifest(a: std.mem.Allocator, tokenizer_sha: [32]u8, config_sha: [32]u8, packed_sha: [32]u8, raw_vocab: usize, compressed: usize, pad: usize, order: u64, heads: u64, layers: []const Layer) ![]u8 { diff --git a/zig/exl3_chain_checks.zig b/zig/exl3_chain_checks.zig new file mode 100644 index 00000000000..70f9e3806f4 --- /dev/null +++ b/zig/exl3_chain_checks.zig @@ -0,0 +1,26 @@ +//! The registered EXL3 chain gates without unrelated bundled shader or checkpoint dependencies. +const std = @import("std"); +const mtl = @import("metal"); +const contract = @import("contract"); +const ex = @import("exl3_projection"); +const Suite = @import("chain_contract").For(ex); + +test "EXL3 chain contract: fused outputs, FP32 accumulators, immutable inputs and fault controls" { + const a = std.testing.allocator; + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const device = try mtl.Device.init(); + defer device.deinit(); + const queue = try device.queue(); + defer queue.deinit(); + var kernels: std.ArrayList(contract.gates.Kernel) = .empty; + defer kernels.deinit(a); + const suite = try Suite.create(a, device, queue, &kernels, null); + defer suite.destroy(); + var tally = contract.gates.Tally{}; + try contract.gates.runAll(a, kernels.items, 0x6b63, &tally); + std.debug.print("SUMMARY {d} kernels: {d} pass gates 1-4, {d} fail, {d} known; {d} controls: {d} red, {d} missed\n", .{ + tally.kernels, tally.passed, tally.failed, tally.known, tally.controls, tally.caught, tally.missed, + }); + try std.testing.expectEqual(@as(usize, 0), tally.problems()); +} diff --git a/zig/exl3_projection_bench.zig b/zig/exl3_projection_bench.zig index 5569cee9fd6..cb8bb68bddd 100644 --- a/zig/exl3_projection_bench.zig +++ b/zig/exl3_projection_bench.zig @@ -301,7 +301,7 @@ pub fn main(init: std.process.Init) !void { if (std.mem.eql(u8, args[i], "--repeats")) settings.repeats = v else if (std.mem.eql(u8, args[i], "--warmup")) settings.warmup = v else if (std.mem.eql(u8, args[i], "--prefill")) settings.prefill = v else if (std.mem.eql(u8, args[i], "--shape")) shape_index = v else if (std.mem.eql(u8, args[i], "--qualify-only") and v <= 1) settings.qualify_only = v == 1 else return error.UnknownOption; } if (settings.repeats == 0 or settings.repeats > 100 or settings.warmup > 100 or - settings.prefill == 0 or settings.prefill > 128 or + settings.prefill == 0 or settings.prefill > 4096 or (shape_index != null and shape_index.? >= shapes.len)) return error.InvalidBenchmarkSettings; const pool = mtl.objc.Pool.push(); defer pool.pop(); diff --git a/zig/kernels/metal/core/exl3_projection_chain.metal b/zig/kernels/metal/core/exl3_projection_chain.metal new file mode 100644 index 00000000000..deb7d4263c7 --- /dev/null +++ b/zig/kernels/metal/core/exl3_projection_chain.metal @@ -0,0 +1,354 @@ +// Chain kernels: the epilogue of one EXL3 projection fused with the block-local work that follows it. + +// A bf16 value as a float: the load tf_exl3_rotate_in does of a stored activation. +inline float tf_exl3_chain_bf(ushort bits) { return as_type(uint(bits) << 16); } + +// The next projection's rotate_in applied to a block whose bf16 values the lanes hold (lane l: l, l + 32, ...). +inline void tf_exl3_chain_rotate_in(thread float (&v)[4], uint lane, const device ushort* su, uint su_signs, + uint first, device half* rotated, ulong dest) { + for (uint j = 0; j < 4; ++j) v[j] = v[j] * tf_exl3_scale(su, first + 32 * j, su_signs); + tf_exl3_hadamard(v, lane); + for (uint j = 0; j < 4; ++j) rotated[dest + 32 * j] = half(v[j] * 0.08838834764831845f); +} + +struct TfExl3Next { + uint k, su_signs, reserved0, reserved1; +}; + +// rotate_out of a projection, then the next projection's rotate_in on the bf16 values it stores (y keeps them). +kernel void tf_exl3_rotate_out_in(const device float* sums [[buffer(0)]], + const device ushort* sv [[buffer(1)]], + const device half* bias [[buffer(2)]], + device uchar* y [[buffer(3)]], + constant TfExl3Args& a [[buffer(4)]], + const device uint* output_ids [[buffer(5)]], + const device uint* routes [[buffer(6)]], + const device TfExl3Expert* descriptors [[buffer(7)]], + const device ushort* su_next [[buffer(8)]], + constant TfExl3Next& next [[buffer(9)]], + device half* rotated [[buffer(10)]], + uint lane [[thread_index_in_simdgroup]], + uint sg [[simdgroup_index_in_threadgroup]], + uint3 tptg [[threads_per_threadgroup]], + uint3 tg [[threadgroup_position_in_grid]]) { + const uint row = tg.y, base = (tg.x * (tptg.x / 32u) + sg) * 128; + const bool active = tf_exl3_active(routes, a, row); + const uint id = a.indexed ? routes[row] : 0; + const uint width = (a.indexed && active && descriptors[id].reserved != 0) ? descriptors[id].reserved : a.n; + if (base >= width || !active) return; + const device ushort* scales = a.indexed ? descriptors[id].sv : sv; + const device half* biases = a.indexed ? descriptors[id].bias : bias; + const uint signs = a.indexed ? descriptors[id].sv_signs : a.sv_signs; + const uint has_bias = a.indexed ? descriptors[id].has_bias : a.has_bias; + float v[4]; + for (uint j = 0; j < 4; ++j) v[j] = sums[ulong(row) * a.n + base + lane + 32 * j]; + tf_exl3_hadamard(v, lane); + const uint dest = a.output_ids ? output_ids[row] : row; + const ulong first = ulong(dest) * a.y_stride + base; + for (uint j = 0; j < 4; ++j) { + const uint n = base + lane + 32 * j; + float out = (v[j] * 0.08838834764831845f) * tf_exl3_scale(scales, n, signs); + if (has_bias) out += float(biases[n]); + const bfloat stored = bfloat(out); + reinterpret_cast(y)[ulong(dest) * a.y_stride + n] = stored; + v[j] = tf_exl3_chain_bf(as_type(stored)); + } + tf_exl3_chain_rotate_in(v, lane, su_next, next.su_signs, uint(first % next.k) + lane, rotated, first + lane); +} + +struct TfExl3RmsRot { + uint rows, width, x_stride, y_stride; + float eps; + uint weight_f32, su_signs, reserved; +}; + +inline float tf_exl3_chain_weight(const device uchar* w, ulong i, uint f32) { + if (f32) return reinterpret_cast(w)[i]; + return tf_exl3_chain_bf(reinterpret_cast(w)[i]); +} + +// dsv41_rms over a row, then the next projection's rotate_in on the rounded row; contraction off as in dsv41_rms. +#pragma clang fp contract(off) +kernel void tf_exl3_rms_rotate_in(const device ushort* x [[buffer(0)]], + const device uchar* w [[buffer(1)]], + device ushort* y [[buffer(2)]], + constant TfExl3RmsRot& d [[buffer(3)]], + const device ushort* su [[buffer(4)]], + device half* rotated [[buffer(5)]], + uint row [[threadgroup_position_in_grid]], + uint t [[thread_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]], + uint sg [[simdgroup_index_in_threadgroup]], + uint threads [[threads_per_threadgroup]]) { + threadgroup float sums[8]; + if (row >= d.rows) return; + if (t < 256) { + float s = 0; + for (uint i = t; i < d.width; i += 256) { float a = tf_exl3_chain_bf(x[ulong(row) * d.x_stride + i]); s += a * a; } + s = simd_sum(s); + if (lane == 0) sums[sg] = s; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (sg == 0) { + float total = simd_sum(lane < 8 ? sums[lane] : 0.0f); + const float factor = 1.0f / float(d.width); + if (lane == 0) sums[0] = rsqrt(total * factor + d.eps); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + const float scale = sums[0]; + for (uint block = sg; block < d.width / 128u; block += threads / 32u) { + const uint first = block * 128u + lane; + float v[4]; + for (uint j = 0; j < 4; ++j) { + const uint i = first + 32 * j; + const ushort bits = tf_exl3_round_bf16((tf_exl3_chain_bf(x[ulong(row) * d.x_stride + i]) * scale) * tf_exl3_chain_weight(w, i, d.weight_f32)); + y[ulong(row) * d.y_stride + i] = bits; + v[j] = tf_exl3_chain_bf(bits); + } + tf_exl3_chain_rotate_in(v, lane, su, d.su_signs, first, rotated, ulong(row) * d.width + first); + } +} +#pragma clang fp contract(on) + +struct TfExl3Rope { + uint width, rotary, position, step, inverse, reserved0, reserved1, reserved2; +}; + +// rotate_out, then dsv41_rope over each head's last rotary columns (a multiple of 32) on the stored bf16 values. +kernel void tf_exl3_rotate_out_rope(const device float* sums [[buffer(0)]], + const device ushort* sv [[buffer(1)]], + const device half* bias [[buffer(2)]], + device uchar* y [[buffer(3)]], + constant TfExl3Args& a [[buffer(4)]], + const device uint* output_ids [[buffer(5)]], + const device uint* routes [[buffer(6)]], + const device TfExl3Expert* descriptors [[buffer(7)]], + const device float2* factors [[buffer(8)]], + constant TfExl3Rope& rp [[buffer(9)]], + uint lane [[thread_index_in_simdgroup]], + uint sg [[simdgroup_index_in_threadgroup]], + uint3 tptg [[threads_per_threadgroup]], + uint3 tg [[threadgroup_position_in_grid]]) { + const uint row = tg.y, base = (tg.x * (tptg.x / 32u) + sg) * 128; + const bool active = tf_exl3_active(routes, a, row); + const uint id = a.indexed ? routes[row] : 0; + const uint width = (a.indexed && active && descriptors[id].reserved != 0) ? descriptors[id].reserved : a.n; + if (base >= width || !active) return; + const device ushort* scales = a.indexed ? descriptors[id].sv : sv; + const device half* biases = a.indexed ? descriptors[id].bias : bias; + const uint signs = a.indexed ? descriptors[id].sv_signs : a.sv_signs; + const uint has_bias = a.indexed ? descriptors[id].has_bias : a.has_bias; + float v[4]; + for (uint j = 0; j < 4; ++j) v[j] = sums[ulong(row) * a.n + base + lane + 32 * j]; + tf_exl3_hadamard(v, lane); + const uint dest = a.output_ids ? output_ids[row] : row; + for (uint j = 0; j < 4; ++j) { + const uint n = base + lane + 32 * j; + float out = (v[j] * 0.08838834764831845f) * tf_exl3_scale(scales, n, signs); + if (has_bias) out += float(biases[n]); + ushort bits = as_type(bfloat(out)); + // The pair's other element, fetched by every lane (the rotary columns are SIMDgroup uniform). + const float other = tf_exl3_chain_bf(ushort(simd_shuffle_xor(uint(bits), 1))); + const uint d = n % rp.width; + if (d >= rp.width - rp.rotary) { + const float2 rotation = factors[(ulong(rp.position) + ulong(dest) * rp.step) * (rp.rotary / 2) + (d - (rp.width - rp.rotary)) / 2]; + const float c = rotation.x, s = rp.inverse ? -rotation.y : rotation.y; + const float own = tf_exl3_chain_bf(bits); + uint u; + if ((n & 1u) == 0u) u = as_type(own * c - other * s); + else u = as_type(other * s + own * c); + bits = ushort((u + 0x7fff + ((u >> 16) & 1)) >> 16); + } + reinterpret_cast(y)[ulong(dest) * a.y_stride + n] = bits; + } +} + +struct TfExl3RopeIn { + uint width, rotary, stride, position, step, inverse, reserved0, reserved1; +}; + +// dsv41_rope over the heads of x in place, then rotate_in of the projection that reads x. +kernel void tf_exl3_rope_rotate_in(device ushort* x [[buffer(0)]], + const device ushort* su [[buffer(1)]], + device half* rotated [[buffer(2)]], + constant TfExl3Args& a [[buffer(3)]], + const device uint* input_ids [[buffer(4)]], + const device uint* routes [[buffer(5)]], + const device TfExl3Expert* descriptors [[buffer(6)]], + const device float2* factors [[buffer(7)]], + constant TfExl3RopeIn& rp [[buffer(8)]], + uint lane [[thread_index_in_simdgroup]], + uint sg [[simdgroup_index_in_threadgroup]], + uint3 tptg [[threads_per_threadgroup]], + uint3 tg [[threadgroup_position_in_grid]]) { + const uint row = tg.y; + if (!tf_exl3_active(routes, a, row)) return; + const device ushort* scales = a.indexed ? descriptors[routes[row]].su : su; + const uint signs = a.indexed ? descriptors[routes[row]].su_signs : a.su_signs; + const uint source = a.input_ids ? input_ids[row] : row / a.repeat; + const uint base = (tg.x * (tptg.x / 32u) + sg) * 128; + if (base >= a.k) return; + float v[4]; + ushort bits[4]; + for (uint j = 0; j < 4; ++j) { + const uint k = base + lane + 32 * j; + const ulong at = ulong(source) * a.x_stride + k; + bits[j] = x[at]; + // The pair's other element, fetched by every lane (the rotary columns are SIMDgroup uniform). + const float other = tf_exl3_chain_bf(ushort(simd_shuffle_xor(uint(bits[j]), 1))); + const uint d = uint(at % rp.stride) % rp.width; + if (d >= rp.width - rp.rotary) { + const ulong z = at / rp.stride; + const float2 rotation = factors[(ulong(rp.position) + z * rp.step) * (rp.rotary / 2) + (d - (rp.width - rp.rotary)) / 2]; + const float c = rotation.x, s = rp.inverse ? -rotation.y : rotation.y; + const float own = tf_exl3_chain_bf(bits[j]); + uint u; + if ((k & 1u) == 0u) u = as_type(own * c - other * s); + else u = as_type(other * s + own * c); + bits[j] = ushort((u + 0x7fff + ((u >> 16) & 1)) >> 16); + x[at] = bits[j]; + } + v[j] = tf_exl3_chain_bf(bits[j]) * tf_exl3_scale(scales, k, signs); + } + tf_exl3_hadamard(v, lane); + for (uint j = 0; j < 4; ++j) + rotated[ulong(row) * a.k + base + lane + 32 * j] = half(v[j] * 0.08838834764831845f); +} + +struct TfExl3Qkv { + uint q_width, q_su_signs, q_weight_f32, kv_width; + uint position, rotary, packed_stride, block; + float eps; + uint reserved0, reserved1, reserved2; +}; + +// dsv41_rms's scalars (contraction off): a thread's sum of squares over i = t, t + 256, ..., and the factor. +#pragma clang fp contract(off) +inline float tf_exl3_chain_square_sum(threadgroup const ushort* row, uint width, uint t) { + float s = 0; + for (uint i = t; i < width; i += 256) { float a = tf_exl3_chain_bf(row[i]); s += a * a; } + return s; +} +inline float tf_exl3_chain_rms_factor(float total, uint width, float eps) { + const float factor = 1.0f / float(width); + return rsqrt(total * factor + eps); +} +#pragma clang fp contract(on) + +inline ushort tf_exl3_chain_round_plain(float x) { + const uint u = as_type(x); + return ushort((u + 0x7fff + ((u >> 16) & 1)) >> 16); +} + +inline uchar tf_exl3_chain_e4code(float x) { + float a = min(abs(x), 448.0f); + if (a == 0) return signbit(x) ? 128 : 0; + int e = max(-6, int((as_type(a) >> 23) & 255) - 127); + int q = int(rint(ldexp(a, 3 - e))); + uint c = e == -6 && q < 8 ? uint(q) : uint((e + 7) * 8 + q - 8); + return uchar(min(c, 126u) | (signbit(x) ? 128u : 0u)); +} + +// The merged wq_a + wkv epilogue: row 0 rms + wq_b rotate_in, row 1 raw key + kv_glue pack; a threadgroup a row. +kernel void tf_exl3_qkv_epilogue(const device float* sums [[buffer(0)]], + device uchar* y [[buffer(1)]], + constant TfExl3Args& a [[buffer(2)]], + const device uint* output_ids [[buffer(3)]], + const device uint* routes [[buffer(4)]], + const device TfExl3Expert* descriptors [[buffer(5)]], + const device uchar* q_weight [[buffer(6)]], + const device ushort* q_su [[buffer(7)]], + device half* rotated [[buffer(8)]], + const device ushort* kv_weight [[buffer(9)]], + const device float2* factors [[buffer(10)]], + device uchar* packed [[buffer(11)]], + constant TfExl3Qkv& d [[buffer(12)]], + uint row [[threadgroup_position_in_grid]], + uint t [[thread_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]], + uint sg [[simdgroup_index_in_threadgroup]], + uint threads [[threads_per_threadgroup]]) { + threadgroup ushort bits[1280]; + threadgroup float part[8]; + if (!tf_exl3_active(routes, a, row)) return; + const uint id = routes[row]; + const uint width = descriptors[id].reserved != 0 ? descriptors[id].reserved : a.n; + const device ushort* scales = descriptors[id].sv; + const device half* biases = descriptors[id].bias; + const uint signs = descriptors[id].sv_signs; + const uint has_bias = descriptors[id].has_bias; + const uint dest = a.output_ids ? output_ids[row] : row; + const uint groups = threads / 32u; + for (uint base = sg * 128; base < width; base += groups * 128) { + float v[4]; + for (uint j = 0; j < 4; ++j) v[j] = sums[ulong(row) * a.n + base + lane + 32 * j]; + tf_exl3_hadamard(v, lane); + for (uint j = 0; j < 4; ++j) { + const uint n = base + lane + 32 * j; + float out = (v[j] * 0.08838834764831845f) * tf_exl3_scale(scales, n, signs); + if (has_bias) out += float(biases[n]); + const bfloat stored = bfloat(out); + bits[n] = as_type(stored); + if (row != 0) reinterpret_cast(y)[ulong(dest) * a.y_stride + n] = stored; + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (row == 0) { + if (t < 256) { + float s = simd_sum(tf_exl3_chain_square_sum(bits, width, t)); + if (lane == 0) part[sg] = s; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (sg == 0) { + float total = simd_sum(lane < 8 ? part[lane] : 0.0f); + if (lane == 0) part[0] = tf_exl3_chain_rms_factor(total, width, d.eps); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + const float scale = part[0]; + for (uint base = sg * 128; base < width; base += groups * 128) { + float v[4]; + for (uint j = 0; j < 4; ++j) { + const uint i = base + lane + 32 * j; + const ushort out = tf_exl3_round_bf16((tf_exl3_chain_bf(bits[i]) * scale) * tf_exl3_chain_weight(q_weight, i, d.q_weight_f32)); + reinterpret_cast(y)[ulong(dest) * a.y_stride + i] = out; + v[j] = tf_exl3_chain_bf(out); + } + tf_exl3_chain_rotate_in(v, lane, q_su, d.q_su_signs, base + lane, rotated, base + lane); + } + return; + } + // The key: dsv41_kv_glue_body over the stored bits (its norm sums columns t, t + 256 with fused multiply-adds). + if (t < 256) { + const float v0 = tf_exl3_chain_bf(bits[t]), v1 = tf_exl3_chain_bf(bits[t + 256u]); + float s = fma(v0, v0, 0.0f); + s = fma(v1, v1, s); + for (uint m = 16; m > 0; m >>= 1) s += simd_shuffle_xor(s, m); + if (lane == 0) part[sg] = s; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + float total = part[0]; + for (uint j = 1; j < 8; ++j) total += part[j]; + const float r = precise::rsqrt(precise::divide(total, float(d.kv_width)) + d.eps); + for (uint blk = sg; blk < d.kv_width / d.block; blk += groups) { + const uint col = blk * d.block + lane; + ushort yb = tf_exl3_chain_round_plain(tf_exl3_chain_bf(kv_weight[col]) * (tf_exl3_chain_bf(bits[col]) * r)); + if (col >= d.kv_width - d.rotary) { + const float a0 = tf_exl3_chain_bf(yb); + const float other = tf_exl3_chain_bf(ushort(simd_shuffle_xor(uint(yb), 1))); + const uint pr = (col - (d.kv_width - d.rotary)) / 2u; + const float2 cs = factors[ulong(d.position) * (d.rotary / 2u) + pr]; + uint u; + if ((col & 1u) == 0u) u = as_type(a0 * cs.x - other * cs.y); + else u = as_type(other * cs.y + a0 * cs.x); + yb = ushort((u + 0x7fff + ((u >> 16) & 1)) >> 16); + } + const float val = tf_exl3_chain_bf(yb); + const float amax = simd_max(abs(val)); + const float z = max(amax, 1e-4f) / 448.0f; + const uint zbits = as_type(z); + const int exponent = int((zbits >> 23) & 255) - 127 + ((zbits & 0x7fffff) != 0); + const float scale = ldexp(1.0f, exponent); + packed[col] = tf_exl3_chain_e4code(val / scale); + if (lane == 0) packed[d.kv_width + blk] = uchar(exponent + 127); + } +} diff --git a/zig/kernels/metal/core/exl3_projection.metal b/zig/kernels/metal/core/exl3_projection_core.metal similarity index 53% rename from zig/kernels/metal/core/exl3_projection.metal rename to zig/kernels/metal/core/exl3_projection_core.metal index 0eca0d80c57..dc85961335f 100644 --- a/zig/kernels/metal/core/exl3_projection.metal +++ b/zig/kernels/metal/core/exl3_projection_core.metal @@ -1,4 +1,6 @@ // Native EXL3: stored trellis tiles, row-independent compensated dots, and normalized Sylvester rotations. + +// Provenance: the model-facing order follows the release's inference/model.py (revision 314113f8). #include using namespace metal; @@ -6,7 +8,7 @@ struct TfExl3Args { uint k, n, rows, halves; uint codebook, su_signs, sv_signs, has_bias; uint output_f32, input_ids, output_ids, routed; - uint expert_id, repeat, indexed, experts; + uint expert_id, repeat, indexed, experts, splits; ulong x_stride, y_stride, tile_k_stride, tile_n_stride; }; @@ -37,11 +39,13 @@ inline uint tf_exl3_word(const device ushort* tile, uint i) { inline ushort tf_exl3_state(const device ushort* tile, uint halves, uint p) { const uint ring = 128 * halves; const uint end = ((p + 1) * halves - ((halves & 1u) ? ((p + 1) & 1u) : 0u)) / 2; - const uint start = (end + ring - 16) % ring; - const uint wi = start / 32, off = start % 32; + uint start = end + ring - 16; + if (start >= ring) start -= ring; + const uint wi = start >> 5, off = start & 31u; const uint lo = tf_exl3_word(tile, wi); if (off <= 16) return ushort(lo >> (16 - off)); - const uint hi = tf_exl3_word(tile, (wi + 1) % (ring / 32)); + const uint next = wi + 1 == 4 * halves ? 0 : wi + 1; + const uint hi = tf_exl3_word(tile, next); return ushort((lo << (off - 16)) | (hi >> (48 - off))); } @@ -65,6 +69,32 @@ inline half tf_exl3_value(ushort state, uint codebook) { return half(float(as_type(ushort(x))) + float(as_type(ushort(x >> 16)))); } +// A scalar lane's state window: the ring word, its bit offset and the next ring word. +struct TfExl3ScalarWindow { + uint word, bit, next; +}; + +inline TfExl3ScalarWindow tf_exl3_scalar_window(uint p, uint halves) { + const uint ring = 128 * halves; + const uint end = ((p + 1) * halves - ((halves & 1u) ? ((p + 1) & 1u) : 0u)) / 2; + uint start = end + ring - 16; + if (start >= ring) start -= ring; + const uint word = start >> 5, bit = start & 31u; + TfExl3ScalarWindow w; + w.word = word; + w.bit = bit; + w.next = word + 1 == 4 * halves ? 0 : word + 1; + return w; +} + +inline half tf_exl3_scalar_value(const device ushort* tile, TfExl3ScalarWindow w, uint codebook) { + const uint lo = tf_exl3_word(tile, w.word); + const uint hi = tf_exl3_word(tile, w.next); + const uint carry = (hi >> ((32 - w.bit) & 31u)) & (0u - uint(w.bit != 0)); + return tf_exl3_value(ushort(((lo << w.bit) | carry) >> 16), codebook); +} + + // Lane l holds indices l, l+32, l+64, l+96; all seven butterfly stages have a fixed FP32 order. inline void tf_exl3_hadamard(thread float (&v)[4], uint lane) { for (uint d = 1; d < 32; d *= 2) { @@ -87,13 +117,17 @@ kernel void tf_exl3_rotate_in(const device ushort* x [[buffer(0)]], const device uint* routes [[buffer(5)]], const device TfExl3Expert* descriptors [[buffer(6)]], uint lane [[thread_index_in_simdgroup]], + uint sg [[simdgroup_index_in_threadgroup]], + uint3 tptg [[threads_per_threadgroup]], uint3 tg [[threadgroup_position_in_grid]]) { + // Four SIMDgroups a threadgroup, each a 128-element block of the same row. const uint row = tg.y; if (!tf_exl3_active(routes, a, row)) return; const device ushort* scales = a.indexed ? descriptors[routes[row]].su : su; const uint signs = a.indexed ? descriptors[routes[row]].su_signs : a.su_signs; const uint source = a.input_ids ? input_ids[row] : row / a.repeat; - const uint base = tg.x * 128; + const uint base = (tg.x * (tptg.x / 32u) + sg) * 128; + if (base >= a.k) return; float v[4]; for (uint j = 0; j < 4; ++j) { const uint k = base + lane + 32 * j; @@ -104,41 +138,142 @@ kernel void tf_exl3_rotate_in(const device ushort* x [[buffer(0)]], rotated[ulong(row) * a.k + base + lane + 32 * j] = half(v[j] * 0.08838834764831845f); } +#ifndef TF_UNROLL +#define TF_UNROLL _Pragma("clang loop unroll(full)") +#endif + +// The bit cursor for element p, as the prompt kernels' map: word, bit offset and wrap word in one integer. +inline uint tf_exl3_map_of(uint p, uint halves) { + const uint ring = 128 * halves; + const uint end = ((p + 1) * halves - ((halves & 1u) ? ((p + 1) & 1u) : 0u)) / 2; + uint start = end + ring - 16; + if (start >= ring) start -= ring; + const uint wi = start >> 5, off = start & 31u, next = wi + 1 == 4 * halves ? 0 : wi + 1; + return wi | (off << 6) | (next << 11); +} + +// The same value as tf_exl3_value, read from the 3 x 65536-half table the engine already binds at buffer 7. +inline half tf_exl3_table_value(const device half* table, uint codebook, ushort state) { + return table[codebook * 65536u + uint(state)]; +} + +// The mul1 value depends only on the state's byte sum. +inline uint tf_exl3_mul1_index(ushort state) { + const uint x = uint(state) * 0x83DCD12Du; + const uint bs = (x & 0x00FF00FFu) + ((x >> 8u) & 0x00FF00FFu); + return (bs * 0x00010001u) >> 16u; +} + +// The mul1 value for a byte sum: the same half the arithmetic path and the resident table hold. +inline half tf_exl3_mul1_value(uint bs) { + const half hs = as_type(ushort(bs + 0x6400u)); + return half(fma(float(hs), float(as_type(ushort(0x1EEEu))), float(as_type(ushort(0xC931u))))); +} + +// The lane's eight windows at compile-time shifts. +template +inline ushort tf_exl3_state_static(uint c_cur, uint c_next) { + const uint bit = S * J; + if (bit <= 16u) return ushort((c_cur >> (16u - bit)) & 0xFFFFu); + if (bit <= 31u) return ushort(((c_cur << (bit - 16u)) | (c_next >> (48u - bit))) & 0xFFFFu); + return ushort((c_next >> (48u - bit)) & 0xFFFFu); +} + // One SIMDgroup owns eight rows and sixteen columns. Only its current 16x16 weight tile is decoded. -template +template inline void tf_exl3_matmul_impl(const device half* x, const device uchar* trellis, device float* sums, constant TfExl3Args& a, const device uint* routes, const device TfExl3Expert* descriptors, + device float* partials, const device half* table, uint lane, uint3 tg, threadgroup float* wx, threadgroup float* xx) { - const uint rb = a.indexed == 1 ? tg.y : tg.y * 8, nb = tg.x * 16; + const uint split = a.splits > 1 ? tg.y : 0; + // A split dispatch carries a row group in tg.z (the tile already spans eight rows). + const uint rb = a.splits > 1 ? (a.indexed == 1 ? tg.z : tg.z * 8) : (a.indexed == 1 ? tg.y : tg.y * 8), nb = tg.x * 16; if (!simd_any(tf_exl3_active(routes, a, rb + (a.indexed == 1 ? 0 : lane % 8)))) return; const uint id = a.indexed ? routes[rb] : 0; + if (a.indexed && descriptors[id].reserved != 0 && nb >= descriptors[id].reserved) return; const device uchar* data = a.indexed ? descriptors[id].trellis : trellis; const ulong ks = a.indexed ? descriptors[id].tile_k_stride : a.tile_k_stride; const ulong ns = a.indexed ? descriptors[id].tile_n_stride : a.tile_n_stride; const uint halves = a.indexed ? descriptors[id].halves : a.halves; const uint codebook = a.indexed ? descriptors[id].codebook : a.codebook; uint maps[8]; + // Eight consecutive states a lane of the sixteen-column tile: the three stream words their windows can touch. + uint at[8], off[8], sh[8], rel[8]; + const uint words = 4 * halves; + const uint ring = 128 * halves; + const uint wi0 = tf_exl3_map_of(lane * 8, halves) & 63u; if (Hoist) { + const uint cur = (wi0 << 5) | ((tf_exl3_map_of(lane * 8, halves) >> 6) & 31u); + TF_UNROLL + for (uint j = 0; j < 8; ++j) { + const uint p = lane * 8 + j, l = p / 8, e = p % 8; + uint c8 = cur + j * (halves >> 1); + if (c8 >= ring) c8 -= ring; + off[j] = c8 & 31u; + sh[j] = (32u - off[j]) & 31u; + rel[j] = (c8 >> 5) >= wi0 ? (c8 >> 5) - wi0 : (c8 >> 5) + words - wi0; + at[j] = (2 * (l % 4) + (e & 1u) + 8 * ((e >> 1) & 1u)) * 16u + (l / 4 + 8 * (e >> 2)); + } + } + { + // The odd-width fallback still needs the per-state map. for (uint j = 0; j < 8; ++j) { - const uint p = lane + 32 * j, ring = 128 * halves; + const uint p = lane + 32 * j, ring2 = 128 * halves; const uint end = ((p + 1) * halves - ((halves & 1u) ? ((p + 1) & 1u) : 0u)) / 2; - const uint start = (end + ring - 16) % ring; - const uint wi = start / 32, off = start % 32, next = wi + 1 == 4 * halves ? 0 : wi + 1; - maps[j] = wi | (off << 6) | (next << 11); + uint start = end + ring2 - 16; + if (start >= ring2) start -= ring2; + const uint wi = start >> 5, o = start & 31u, next = wi + 1 == 4 * halves ? 0 : wi + 1; + maps[j] = wi | (o << 6) | (next << 11); } } float high[4]={0,0,0,0}, low[4]={0,0,0,0}; - for (uint kb = 0; kb < a.k; kb += 16) { + const uint blocks = a.k / 16; + const uint b0 = a.splits > 1 ? blocks * split / a.splits : 0; + const uint b1 = a.splits > 1 ? blocks * (split + 1) / a.splits : blocks; + uint prefetch[4]; + { + uint a1 = wi0 + 1; if (a1 >= words) a1 -= words; + uint a2 = wi0 + 2; if (a2 >= words) a2 -= words; + uint a3 = wi0 + 3; if (a3 >= words) a3 -= words; + const device ushort* t0 = reinterpret_cast(data + ulong(b0) * ks + ulong(nb / 16) * ns); + prefetch[0] = tf_exl3_word(t0, wi0); + prefetch[1] = tf_exl3_word(t0, a1); + prefetch[2] = tf_exl3_word(t0, a2); + prefetch[3] = tf_exl3_word(t0, a3); + } + for (uint b = b0; b < b1; ++b) { + const uint kb = b * 16; const device ushort* tile = reinterpret_cast( data + ulong(kb / 16) * ks + ulong(nb / 16) * ns); - for (uint j = 0; j < 8; ++j) { + if (Hoist and (halves & 1u) == 0 and halves <= 16) { + // A block early, as the prompt tile does: the words' latency overlaps the multiply instead of stalling. + uint at1 = wi0 + 1; if (at1 >= words) at1 -= words; + uint at2 = wi0 + 2; if (at2 >= words) at2 -= words; + uint at3 = wi0 + 3; if (at3 >= words) at3 -= words; + const uint w0 = prefetch[0], w1 = prefetch[1], w2 = prefetch[2], w3 = prefetch[3]; + if (b + 1 < b1) { + const device ushort* tn = reinterpret_cast(data + ulong(b + 1) * ks + ulong(nb / 16) * ns); + prefetch[0] = tf_exl3_word(tn, wi0); + prefetch[1] = tf_exl3_word(tn, at1); + prefetch[2] = tf_exl3_word(tn, at2); + prefetch[3] = tf_exl3_word(tn, at3); + } + TF_UNROLL + for (uint j = 0; j < 8; ++j) { + const uint lo = rel[j] == 0 ? w0 : rel[j] == 1 ? w1 : w2; + const uint hi = rel[j] == 0 ? w1 : rel[j] == 1 ? w2 : w3; + const uint carry = (hi >> sh[j]) & (0u - uint(off[j] != 0)); + const ushort s = ushort(((lo << off[j]) | carry) >> 16); + wx[at[j]] = float(Table ? tf_exl3_table_value(table, codebook, s) : tf_exl3_value(s, codebook)); + } + } else for (uint j = 0; j < 8; ++j) { const uint p = lane + 32 * j, l = p / 8, e = p % 8; const uint r = 2 * (l % 4) + (e & 1u) + 8 * ((e >> 1) & 1u); const uint c = l / 4 + 8 * (e >> 2); const ushort state = Hoist ? tf_exl3_mapped_state(tile, maps[j]) : tf_exl3_state(tile, halves, p); - wx[r * 16 + c] = float(tf_exl3_value(state, codebook)); + wx[r * 16 + c] = float(Table ? tf_exl3_table_value(table, codebook, state) : tf_exl3_value(state, codebook)); } for (uint j = lane; j < 128; j += 32) { const uint row = rb + j / 16; @@ -150,20 +285,17 @@ inline void tf_exl3_matmul_impl(const device half* x, const device uchar* trelli const uint at=lane+32*i, row=rb+at/16, col=at%16; if ((a.indexed==1 && at/16!=0) || !tf_exl3_active(routes,a,row)) continue; for (uint k=0;k<16;++k) { - // FP16 products are exact in FP32. TwoSum retains each addition's rounding error. - const float product=xx[(at/16)*16+k]*wx[k*16+col]; - const float next=high[i]+product; - const float borrowed=next-high[i]; - low[i]+=(high[i]-(next-borrowed))+(product-borrowed); - high[i]=next; + high[i] += xx[(at/16)*16+k]*wx[k*16+col]; } } threadgroup_barrier(mem_flags::mem_threadgroup); } for (uint i=0;i<4;++i) { const uint at=lane+32*i, row=rb+at/16; - if ((a.indexed!=1 || at/16==0) && tf_exl3_active(routes,a,row)) - sums[ulong(row)*a.n+nb+at%16]=high[i]+low[i]; + if ((a.indexed!=1 || at/16==0) && tf_exl3_active(routes,a,row)) { + if (a.splits > 1) partials[(ulong(split) * a.rows + rb + at / 16) * a.n + nb + at % 16] = high[i] + low[i]; + else sums[ulong(row)*a.n+nb+at%16]=high[i]+low[i]; + } } } @@ -173,10 +305,11 @@ kernel void tf_exl3_matmul(const device half* x [[buffer(0)]], constant TfExl3Args& a [[buffer(3)]], const device uint* routes [[buffer(4)]], const device TfExl3Expert* descriptors [[buffer(5)]], + device float* partials [[buffer(6)]], uint lane [[thread_index_in_simdgroup]], uint3 tg [[threadgroup_position_in_grid]]) { threadgroup float wx[256], xx[128]; - tf_exl3_matmul_impl(x, trellis, sums, a, routes, descriptors, lane, tg, wx, xx); + tf_exl3_matmul_impl(x, trellis, sums, a, routes, descriptors, partials, nullptr, lane, tg, wx, xx); } @@ -186,10 +319,26 @@ kernel void tf_exl3_matmul_hoisted(const device half* x [[buffer(0)]], constant TfExl3Args& a [[buffer(3)]], const device uint* routes [[buffer(4)]], const device TfExl3Expert* descriptors [[buffer(5)]], + device float* partials [[buffer(6)]], uint lane [[thread_index_in_simdgroup]], uint3 tg [[threadgroup_position_in_grid]]) { threadgroup float wx[256], xx[128]; - tf_exl3_matmul_impl(x, trellis, sums, a, routes, descriptors, lane, tg, wx, xx); + tf_exl3_matmul_impl(x, trellis, sums, a, routes, descriptors, partials, nullptr, lane, tg, wx, xx); +} + +// The one-row / narrow-window arm of the same body with the codebook as a table read (buffer 7). +kernel void tf_exl3_matmul_tab(const device half* x [[buffer(0)]], + const device uchar* trellis [[buffer(1)]], + device float* sums [[buffer(2)]], + constant TfExl3Args& a [[buffer(3)]], + const device uint* routes [[buffer(4)]], + const device TfExl3Expert* descriptors [[buffer(5)]], + device float* partials [[buffer(6)]], + const device half* table [[buffer(7)]], + uint lane [[thread_index_in_simdgroup]], + uint3 tg [[threadgroup_position_in_grid]]) { + threadgroup float wx[256], xx[128]; + tf_exl3_matmul_impl(x, trellis, sums, a, routes, descriptors, partials, table, lane, tg, wx, xx); } // Qualification only: compare every arithmetic state against the independent CPU-generated FP16 table. @@ -198,6 +347,13 @@ kernel void tf_exl3_codebook_check(device half* arithmetic [[buffer(0)]], if (i < 3 * 65536) arithmetic[i] = tf_exl3_value(ushort(i % 65536), i / 65536); } +// The rotate_out value of one output: the Hadamard result scaled, signed by sv, plus the bias; the caller rounds it. +inline float tf_exl3_out_value(float v, const device ushort* scales, const device half* biases, uint n, uint signs, uint has_bias) { + float out = (v * 0.08838834764831845f) * tf_exl3_scale(scales, n, signs); + if (has_bias) out += float(biases[n]); + return out; +} + kernel void tf_exl3_rotate_out(const device float* sums [[buffer(0)]], const device ushort* sv [[buffer(1)]], const device half* bias [[buffer(2)]], @@ -207,10 +363,15 @@ kernel void tf_exl3_rotate_out(const device float* sums [[buffer(0)]], const device uint* routes [[buffer(6)]], const device TfExl3Expert* descriptors [[buffer(7)]], uint lane [[thread_index_in_simdgroup]], + uint sg [[simdgroup_index_in_threadgroup]], + uint3 tptg [[threads_per_threadgroup]], uint3 tg [[threadgroup_position_in_grid]]) { - const uint row = tg.y, base = tg.x * 128; - if (!tf_exl3_active(routes, a, row)) return; + const uint row = tg.y, base = (tg.x * (tptg.x / 32u) + sg) * 128; + const bool active = tf_exl3_active(routes, a, row); const uint id = a.indexed ? routes[row] : 0; + // An indexed batch may carry entries of different output width (descriptor.reserved, 0 = the call's n). + const uint width = (a.indexed && active && descriptors[id].reserved != 0) ? descriptors[id].reserved : a.n; + if (base >= width || !active) return; const device ushort* scales = a.indexed ? descriptors[id].sv : sv; const device half* biases = a.indexed ? descriptors[id].bias : bias; const uint signs = a.indexed ? descriptors[id].sv_signs : a.sv_signs; @@ -221,14 +382,23 @@ kernel void tf_exl3_rotate_out(const device float* sums [[buffer(0)]], const uint dest = a.output_ids ? output_ids[row] : row; for (uint j = 0; j < 4; ++j) { const uint n = base + lane + 32 * j; - float out = (v[j] * 0.08838834764831845f) * tf_exl3_scale(scales, n, signs); - if (has_bias) out += float(biases[n]); + const float out = tf_exl3_out_value(v[j], scales, biases, n, signs, has_bias); const ulong at = ulong(dest) * a.y_stride + n; if (a.output_f32) reinterpret_cast(y)[at] = out; else reinterpret_cast(y)[at] = bfloat(out); } } +// The pre-rotated int8 pack's epilogue. +kernel void tf_exl3_epilogue(const device float* sums [[buffer(0)]], + device uchar* y [[buffer(1)]], + constant TfExl3Args& a [[buffer(2)]], + uint2 gid [[thread_position_in_grid]]) { + const uint r = gid.y, c = gid.x; + if (r >= a.rows || c >= a.n) return; + reinterpret_cast(y)[ulong(r) * a.y_stride + c] = bfloat(sums[ulong(r) * a.n + c]); +} + // Qualification only: compare mapped windows with independent CPU 64-bit concatenation. kernel void tf_exl3_state_window_check(const device uint4* inputs [[buffer(0)]], @@ -241,6 +411,20 @@ kernel void tf_exl3_state_window_check(const device uint4* inputs [[buffer(0)]], outputs[tid] = tf_exl3_mapped_state(tile, (off << 6) | (1u << 11)); } +// Kept-dense: rotated rows x bf16 weight, f32 in rotate_out sums; sequential k, one thread an output, in fp64 order. +kernel void tf_exl3_dense(const device half* rotated [[buffer(0)]], + const device bfloat* weight [[buffer(1)]], + device float* sums [[buffer(2)]], + constant TfExl3Args& a [[buffer(3)]], + const device uint* input_ids [[buffer(4)]], + uint2 g [[thread_position_in_grid]]) { + const uint row = a.input_ids ? input_ids[g.y] : g.y; + float acc = 0; + for (uint k = 0; k < a.k; ++k) + acc += float(rotated[ulong(g.y) * a.k + k]) * float(weight[ulong(g.x) * a.k + k]); + sums[ulong(g.y) * a.n + g.x] = acc; +} + // Four SIMDgroups share decoded weights while each retains its original eight-row compensated dots. kernel void tf_exl3_matmul_prefill(const device half* x [[buffer(0)]], const device uchar* trellis [[buffer(1)]], @@ -248,21 +432,16 @@ kernel void tf_exl3_matmul_prefill(const device half* x [[buffer(0)]], constant TfExl3Args& a [[buffer(3)]], const device uint* routes [[buffer(4)]], const device TfExl3Expert* descriptors [[buffer(5)]], + device float* partials [[buffer(6)]], uint lane [[thread_index_in_simdgroup]], uint sg [[simdgroup_index_in_threadgroup]], uint3 tg [[threadgroup_position_in_grid]]) { threadgroup float wx[256], xx[512]; const uint rb = tg.y * 32, nb = tg.x * 16; if (a.indexed || a.routed || rb >= a.rows) return; - uint maps[8]; + TfExl3ScalarWindow win[8]; if (sg == 0) { - for (uint j = 0; j < 8; ++j) { - const uint p = lane + 32 * j, ring = 128 * a.halves; - const uint end = ((p + 1) * a.halves - ((a.halves & 1u) ? ((p + 1) & 1u) : 0u)) / 2; - const uint start = (end + ring - 16) % ring; - const uint wi = start / 32, off = start % 32, next = wi + 1 == 4 * a.halves ? 0 : wi + 1; - maps[j] = wi | (off << 6) | (next << 11); - } + for (uint j = 0; j < 8; ++j) win[j] = tf_exl3_scalar_window(lane + 32 * j, a.halves); } float high[4] = {0,0,0,0}, low[4] = {0,0,0,0}; for (uint kb = 0; kb < a.k; kb += 16) { @@ -273,7 +452,7 @@ kernel void tf_exl3_matmul_prefill(const device half* x [[buffer(0)]], const uint p = lane + 32 * j, l = p / 8, e = p % 8; const uint r = 2 * (l % 4) + (e & 1u) + 8 * ((e >> 1) & 1u); const uint c = l / 4 + 8 * (e >> 2); - wx[r * 16 + c] = float(tf_exl3_value(tf_exl3_mapped_state(tile, maps[j]), a.codebook)); + wx[r * 16 + c] = float(tf_exl3_scalar_value(tile, win[j], a.codebook)); } } for (uint j = lane; j < 128; j += 32) { @@ -300,3 +479,14 @@ kernel void tf_exl3_matmul_prefill(const device half* x [[buffer(0)]], if (tf_exl3_active(routes, a, row)) sums[ulong(row) * a.n + nb + at % 16] = high[i] + low[i]; } } + +// Split-K reduction: one row's partial dot products, summed in split order. +kernel void tf_exl3_splitk_reduce(const device float* partials [[buffer(0)]], + device float* sums [[buffer(1)]], + constant uint2& d [[buffer(2)]], + uint i [[thread_position_in_grid]]) { + if (i >= d.y) return; + float s = 0; + for (uint k = 0; k < d.x; ++k) s += partials[ulong(k) * d.y + i]; + sums[i] = s; +} diff --git a/zig/kernels/metal/core/exl3_projection_i8.metal b/zig/kernels/metal/core/exl3_projection_i8.metal new file mode 100644 index 00000000000..8d1b23bd956 --- /dev/null +++ b/zig/kernels/metal/core/exl3_projection_i8.metal @@ -0,0 +1,113 @@ +//! The int8 trellis tile with its own per-tile scale, on the GPU against the CPU int8 oracle. +#include +using namespace metal; +#include "../nax.h" + +struct TfExl3Args { + uint k, n, rows, halves; + uint codebook, su_signs, sv_signs, has_bias; + uint output_f32, input_ids, output_ids, routed; + uint expert_id, repeat, indexed, experts, splits; + ulong x_stride, y_stride, tile_k_stride, tile_n_stride; +}; + +// A little-endian int16 pair as one stream word (the same read tf_exl3_word makes). +inline uint tf_i8_word(const device ushort* tile, uint i) { + return uint(tile[2 * i]) | (uint(tile[2 * i + 1]) << 16); +} + +// Where state p's window starts: the word index in the low 6 bits, the bit offset next, the next word after. +inline uint tf_i8_map(uint p, uint halves) { + const uint ring = 128 * halves; + const uint end = ((p + 1) * halves - ((halves & 1u) ? ((p + 1) & 1u) : 0u)) / 2; + uint start = end + ring - 16; + if (start >= ring) start -= ring; + const uint wi = start >> 5, o = start & 31u, next = wi + 1 == 4 * halves ? 0 : wi + 1; + return wi | (o << 6) | (next << 11); +} + +// The state at a map: the two words it can span, shifted and carried into the top half. +inline ushort tf_i8_state(const device ushort* tile, uint map) { + const uint lo = tf_i8_word(tile, map & 63u); + const uint hi = tf_i8_word(tile, map >> 11); + const uint off = (map >> 6) & 31u; + const uint carry = (hi >> ((32 - off) & 31u)) & (0u - uint(off != 0)); + return ushort(((lo << off) | carry) >> 16); +} + +// One 16x16 weight tile as int8 by its own peak, then a cell's dot with int8 x, scaled by both peaks. +kernel void tf_exl3_int8_tile(const device half* x [[buffer(0)]], + const device uchar* trellis [[buffer(1)]], + device float* sums [[buffer(2)]], + constant TfExl3Args& a [[buffer(3)]], + const device uchar* descriptors [[buffer(5)]], + const device half* codebook [[buffer(7)]], + uint lane [[thread_index_in_simdgroup]], + uint3 tg [[threadgroup_position_in_grid]]) { + const uint row0 = tg.y * 16u, col0 = tg.x * 16u; + if (row0 >= a.rows || col0 >= a.n) return; + threadgroup char wq[16 * 16]; + threadgroup char xq[16 * 16]; + threadgroup float wscale; + threadgroup float xscale; + const uint ks = a.tile_k_stride, ns = a.tile_n_stride, halves = a.halves, codebook_id = a.codebook; + // x's 16 values a block, per live row: quantized by the block's peak over the live rows. + const uint rows_here = min(16u, a.rows - row0); + const uint cols_here = min(16u, a.n - col0); + for (uint kb = 0; kb < a.k; kb += 16) { + const device ushort* tile = reinterpret_cast( + trellis + ulong(kb / 16) * ks + ulong(col0 / 16) * ns); + // Eight states a lane: decode, then the tile's peak and its quantized copy. + float mine[8]; + uint at[8]; + TF_UNROLL + for (uint j = 0; j < 8; ++j) { + const uint p = lane * 8u + j, l = p / 8u, e = p % 8u; + const uint r = 2 * (l % 4) + (e & 1u) + 8 * ((e >> 1) & 1u); // the state's k index + const uint c = l / 4 + 8 * (e >> 2); // its column + const ushort state = tf_i8_state(tile, tf_i8_map(p, halves)); + mine[j] = float(codebook[ulong(codebook_id) * 65536u + uint(state)]); + at[j] = r * 16u + c; + } + float peak = 0; + TF_UNROLL + for (uint j = 0; j < 8; ++j) peak = max(peak, fabs(mine[j])); + peak = simd_max(peak); + const float ws = peak > 0 ? peak / 127.0f : 0.0f; + TF_UNROLL + for (uint j = 0; j < 8; ++j) wq[at[j]] = ws > 0 ? char(clamp(rint(mine[j] / ws), -127.0f, 127.0f)) : char(0); + if (lane == 0) wscale = ws; + // One lane loads and quantizes the 16 rows' 16 values (the tile is 256 values, 8 a lane). + float xm[8]; + uint xat[8]; + TF_UNROLL + for (uint j = 0; j < 8; ++j) { + const uint p = lane * 8u + j; + const uint r = p / 16u, c = p % 16u; + xm[j] = (r < rows_here) ? float(x[ulong(row0 + r) * a.k + kb + c]) : 0.0f; + xat[j] = r * 16u + c; + } + float xpeak = 0; + TF_UNROLL + for (uint j = 0; j < 8; ++j) xpeak = max(xpeak, fabs(xm[j])); + xpeak = simd_max(xpeak); + const float xs = xpeak > 0 ? xpeak / 127.0f : 1.0f; + TF_UNROLL + for (uint j = 0; j < 8; ++j) xq[xat[j]] = xs > 0 ? char(clamp(rint(xm[j] / xs), -127.0f, 127.0f)) : char(0); + if (lane == 0) xscale = xs; + threadgroup_barrier(mem_flags::mem_threadgroup); + // Eight output cells a lane, each the 16-deep int8 dot scaled by both peaks. + TF_UNROLL + for (uint j = 0; j < 8; ++j) { + const uint p = lane * 8u + j; + const uint r = p / 16u, c = p % 16u; + if (r >= rows_here || c >= cols_here) continue; + int acc = 0; + for (uint kk = 0; kk < 16; ++kk) acc += int(xq[r * 16u + kk]) * int(wq[kk * 16u + c]); + const ulong at_sum = ulong(row0 + r) * a.n + col0 + c; + // The first k block writes, the rest add: the caller need not clear the sums. + if (kb == 0) sums[at_sum] = float(acc) * wscale * xscale; else sums[at_sum] += float(acc) * wscale * xscale; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + } +} diff --git a/zig/kernels/metal/core/exl3_projection_nax_base.metal b/zig/kernels/metal/core/exl3_projection_nax_base.metal new file mode 100644 index 00000000000..e0fb8eb2e40 --- /dev/null +++ b/zig/kernels/metal/core/exl3_projection_nax_base.metal @@ -0,0 +1,305 @@ +// Native EXL3 on the tensor units: the trellis decoded into a threadgroup tile and reduced by cooperative matmul. + +// Provenance: the model-facing order follows the release's inference/model.py (revision 314113f8). +#include +using namespace metal; +#include "../nax.h" +using namespace tfp; + +struct TfExl3Args { + uint k, n, rows, halves; + uint codebook, su_signs, sv_signs, has_bias; + uint output_f32, input_ids, output_ids, routed; + uint expert_id, repeat, indexed, experts, splits; + ulong x_stride, y_stride, tile_k_stride, tile_n_stride; +}; + +// Metal 3 / argument-buffer tier 2 descriptors are populated once from resident buffers' GPU addresses. +struct TfExl3Expert { + const device uchar* trellis; + const device ushort* su; + const device ushort* sv; + const device half* bias; + ulong tile_k_stride, tile_n_stride; + uint halves, codebook, su_signs, sv_signs, has_bias, reserved; +}; + +inline bool tf_exl3_active(const device uint* routes, constant TfExl3Args& a, uint row) { + return row < a.rows && (a.indexed ? routes[row] < a.experts : (!a.routed || routes[row] == a.expert_id)); +} + +// Two little-endian int16 words form one MSB-first stream word, including unaligned borrowed tiles. +inline uint tf_exl3_word(const device ushort* tile, uint i) { + return uint(tile[2 * i]) | (uint(tile[2 * i + 1]) << 16); +} + +inline ushort tf_exl3_state(const device ushort* tile, uint halves, uint p) { + const uint ring = 128 * halves; + const uint end = ((p + 1) * halves - ((halves & 1u) ? ((p + 1) & 1u) : 0u)) / 2; + uint start = end + ring - 16; + if (start >= ring) start -= ring; + const uint wi = start >> 5, off = start & 31u; + const uint lo = tf_exl3_word(tile, wi); + if (off <= 16) return ushort(lo >> (16 - off)); + const uint next = wi + 1 == 4 * halves ? 0 : wi + 1; + const uint hi = tf_exl3_word(tile, next); + return ushort((lo << (off - 16)) | (hi >> (48 - off))); +} + +inline ushort tf_exl3_mapped_state(const device ushort* tile, uint map) { + const uint wi = map & 63u, off = (map >> 6) & 31u; + const uint lo = tf_exl3_word(tile, wi); + const uint hi = tf_exl3_word(tile, map >> 11); + const uint carry = (hi >> ((32 - off) & 31u)) & (0u - uint(off != 0)); + return ushort(((lo << off) | carry) >> 16); +} + +// The codebook as a table: the same value tf_exl3_value computes, read instead of derived. +inline half tf_exl3_table_value(const device half* table, ushort state, uint codebook) { + return table[codebook * 65536u + uint(state)]; +} + +// Both operations are exact in FP32 before the single FP16 round; do not split the mul1 FMA. +inline half tf_exl3_value(ushort state, uint codebook) { + uint x = uint(state) * (codebook == 2 ? 0x83DCD12Du : codebook == 1 ? 0xCBAC1FEDu : 89226354u); + if (codebook == 2) { + // The four byte sums collapse into one 16-bit lane and the +1024 bias is added as half 0x6400. + const uint bs = (x & 0x00FF00FFu) + ((x >> 8u) & 0x00FF00FFu); + const half hs = as_type(ushort((bs * 0x00010001u + 0x64000000u) >> 16u)); + return half(fma(float(hs), float(as_type(ushort(0x1EEE))), float(as_type(ushort(0xC931))))); + } + if (codebook == 0) x += 64248484u; + x = (x & 0x8FFF8FFFu) ^ 0x3B603B60u; + return half(float(as_type(ushort(x))) + float(as_type(ushort(x >> 16)))); +} + +// The mul1 value from a 1024-entry threadgroup LUT indexed by the byte sum: four ALU ops and a shared load. +inline half tf_exl3_value_lut(const threadgroup half* lut, ushort state) { + const uint x = uint(state) * 0x83DCD12Du; + const uint bs = (x & 0x00FF00FFu) + ((x >> 8u) & 0x00FF00FFu); + return lut[(bs * 0x00010001u) >> 16u]; +} + +// The lane's eight windows at compile-time shifts. +template +inline ushort tf_exl3_state_static(uint c_cur, uint c_next) { + const uint bit = S * J; + if (bit <= 16u) return ushort((c_cur >> (16u - bit)) & 0xFFFFu); + if (bit <= 31u) return ushort(((c_cur << (bit - 16u)) | (c_next >> (48u - bit))) & 0xFFFFu); + return ushort((c_next >> (48u - bit)) & 0xFFFFu); +} + +// The value either way: the resident table when one is bound, the arithmetic otherwise. +inline half tf_exl3_pick(const device half* table, const threadgroup half* lut, ushort state, uint codebook) { + if (lut != nullptr and codebook == 2) return tf_exl3_value_lut(lut, state); + return table != nullptr ? tf_exl3_table_value(table, state, codebook) : tf_exl3_value(state, codebook); +} + +// The device-side twin of frag_get_tg4: two 8-byte loads for a full 16-row tile. +inline void tf_frag_get_dev4(thread frag& f, const device half* p, int ld, int r, int c, short2 home, int nr) { + const int r0 = r + home.y, r1 = r0 + 8, c0 = c + home.x; + if (r1 < nr) { + f = frag(*(const device half4*)(p + r0 * ld + c0), *(const device half4*)(p + r1 * ld + c0)); + } else { + TF_UNROLL + for (short e = 0; e < 8; ++e) { + const int rr = r0 + (e >> 2) * 8; + f[e] = rr < nr ? p[rr * ld + c0 + (e & 3)] : half(0); + } + } +} + +// Two 8-byte loads, one per fragment row, as nax.h's frag_get_tg does for bfloat: rows home.y and home.y + 8. +inline void tf_frag_get_tg4(thread frag& f, const threadgroup half* p, int ld, int r, int c, short2 home) { + const threadgroup half* q = p + (r + home.y) * ld + (c + home.x); + f = frag(*(const threadgroup half4*)q, *(const threadgroup half4*)(q + 8 * ld)); +} + +// The bit-stream map for element index p, the same value the old per-lane precompute produced. +inline uint tf_exl3_map_for(uint p, uint halves) { + const uint ring = 128 * halves; + const uint end = ((p + 1) * halves - ((halves & 1u) ? ((p + 1) & 1u) : 0u)) / 2; + // End + ring - 16 is below twice the ring, so one conditional subtract replaces the modulo by a runtime divisor. + uint start = end + ring - 16; + if (start >= ring) start -= ring; + const uint wi = start >> 5, off = start & 31u, next = wi + 1 == 4 * halves ? 0 : wi + 1; + return wi | (off << 6) | (next << 11); +} + +// A routed prompt tile's decode job: one expert block's row and column window, weights from the routed slice. +struct TfExl3DigJob { + const device uchar* trellis; + ulong tile_k_stride, tile_n_stride; + uint halves, codebook; + uint row_block, col_block, tile_rows; + uint rows_here, cols_here; +}; + +template +inline TfExl3DigJob tf_exl3_dig_job(const device uchar* trellis, constant TfExl3Args& a, + const device uint* routes, const device TfExl3Expert* descriptors, + uint row_block, uint col_block, uint tile_rows) { + const uint expert = a.indexed ? routes[row_block] : a.expert_id; + const uint didx = a.indexed ? expert : 0; + TfExl3DigJob job; + job.trellis = a.indexed ? descriptors[didx].trellis : trellis; + job.tile_k_stride = a.indexed ? descriptors[didx].tile_k_stride : a.tile_k_stride; + job.tile_n_stride = a.indexed ? descriptors[didx].tile_n_stride : a.tile_n_stride; + job.halves = a.indexed ? descriptors[didx].halves : a.halves; + job.codebook = a.indexed ? descriptors[didx].codebook : a.codebook; + job.row_block = row_block; + job.col_block = col_block; + job.tile_rows = tile_rows; + job.rows_here = min(tile_rows, a.rows - row_block); + job.cols_here = min(64u * CG, a.n - col_block); + return job; +} + +// The lane's window walk over one pack tile: the stream is a ring of 128*halves sixteen-bit states. +struct TfExl3DigWindows { + uint at[8], off[8], sh[8], rel[8]; + uint first_word, first_bit, words, next1, next2, next3; +}; + +template +inline TfExl3DigWindows tf_exl3_dig_windows(uint p0, uint halves, uint hg, uint h, bool cursor) { + TfExl3DigWindows walk; + walk.words = 4u * halves; + const uint map = tf_exl3_map_for(p0, halves); + walk.first_word = map & 63u; + walk.first_bit = (map >> 6) & 31u; + walk.next1 = walk.first_word + 1u; + if (walk.next1 >= walk.words) walk.next1 -= walk.words; + walk.next2 = walk.first_word + 2u; + if (walk.next2 >= walk.words) walk.next2 -= walk.words; + walk.next3 = walk.first_word + 3u; + if (walk.next3 >= walk.words) walk.next3 -= walk.words; + const uint ring = 128u * halves; + const uint origin = (walk.first_word << 5) | walk.first_bit; + TF_UNROLL + for (uint k = 0; k < States; ++k) { + const uint p = p0 + k, l = p / 8, e = p % 8; + walk.at[k] = (2 * (l % 4) + (e & 1u) + 8 * ((e >> 1) & 1u)) * Cols + hg + h * 16u + (l / 4 + 8 * (e >> 2)); + if (cursor) { + uint c8 = origin + k * (halves >> 1); + if (c8 >= ring) c8 -= ring; + const uint wi = c8 >> 5; + walk.off[k] = c8 & 31u; + walk.sh[k] = (32u - walk.off[k]) & 31u; + walk.rel[k] = wi >= walk.first_word ? wi - walk.first_word : wi + walk.words - walk.first_word; + } + } + return walk; +} + +// One routed or dense row's decode job: the pack slice a route names (or the dense call's own trellis). +struct TfExl3DecodeJob { + const device uchar* trellis; + ulong tile_k_stride, tile_n_stride; + uint halves, codebook, width; +}; + +inline TfExl3DecodeJob tf_exl3_dense_decode_job(const device uchar* trellis, constant TfExl3Args& a) { + TfExl3DecodeJob job; + job.trellis = trellis; + job.tile_k_stride = a.tile_k_stride; + job.tile_n_stride = a.tile_n_stride; + job.halves = a.halves; + job.codebook = a.codebook; + job.width = a.n; + return job; +} + +inline TfExl3DecodeJob tf_exl3_routed_decode_job(const device uchar* trellis, constant TfExl3Args& a, + const device TfExl3Expert* descriptors, uint expert) { + (void)trellis; + TfExl3DecodeJob job; + job.trellis = descriptors[expert].trellis; + job.tile_k_stride = descriptors[expert].tile_k_stride; + job.tile_n_stride = descriptors[expert].tile_n_stride; + job.halves = descriptors[expert].halves; + job.codebook = descriptors[expert].codebook; + job.width = descriptors[expert].reserved != 0 ? descriptors[expert].reserved : a.n; + return job; +} + +// The lane's row walk through one pack tile: its first word, the bit offset, the shift/mask and the next two words. +struct TfExl3RowWalk { + uint words, first_word, first_bit, shift, mask, next1, next2; +}; + +inline TfExl3RowWalk tf_exl3_row_walk(uint lane, uint halves) { + TfExl3RowWalk walk; + walk.words = 4u * halves; + const uint map = tf_exl3_map_for(lane * 8u, halves); + walk.first_word = map & 63u; + walk.first_bit = (map >> 6) & 31u; + walk.shift = (32u - walk.first_bit) & 31u; + walk.mask = 0u - uint(walk.first_bit != 0u); + walk.next1 = walk.first_word + 1u; + if (walk.next1 >= walk.words) walk.next1 -= walk.words; + walk.next2 = walk.first_word + 2u; + if (walk.next2 >= walk.words) walk.next2 -= walk.words; + return walk; +} + +// One state block's four stream words from the next 16-row tile, with the ring's wrap folded in once. +inline uint tf_exl3_block_word(const device uchar* data, ulong ks, ulong ns, uint kb, uint nb, uint hg, uint h, + uint wi, uint words) { + const device ushort* tile = reinterpret_cast( + data + ulong(kb / 16) * ks + ulong(nb / 16 + hg / 16u + h) * ns); + return tf_exl3_word(tile, wi < words ? wi : wi - words); +} + +// The eight (or four, or two) states a lane owns, from four words already in registers. +template +inline void tf_exl3_decode_fast(threadgroup half* wx, uint codebook, const uint* at, const uint* off, + const uint* sh, const uint* rel, uint w0, uint w1, uint w2, uint w3) { + TF_UNROLL + for (uint k = 0; k < States; ++k) { + const uint lo = rel[k] == 0 ? w0 : rel[k] == 1 ? w1 : w2; + const uint hi = rel[k] == 0 ? w1 : rel[k] == 1 ? w2 : w3; + const uint carry = (hi >> sh[k]) & (0u - uint(off[k] != 0)); + wx[at[k]] = tf_exl3_value(ushort(((lo << off[k]) | carry) >> 16), codebook); + } +} + +// The same decode through the resident codebook table: one load replaces the mul1's four byte sums and fma. +template +inline void tf_exl3_decode_table(threadgroup half* wx, const device half* table, uint codebook, + const uint* at, const uint* off, const uint* sh, const uint* rel, + uint w0, uint w1, uint w2, uint w3) { + TF_UNROLL + for (uint k = 0; k < States; ++k) { + const uint lo = rel[k] == 0 ? w0 : rel[k] == 1 ? w1 : w2; + const uint hi = rel[k] == 0 ? w1 : rel[k] == 1 ? w2 : w3; + const uint carry = (hi >> sh[k]) & (0u - uint(off[k] != 0)); + wx[at[k]] = tf_exl3_table_value(table, ushort(((lo << off[k]) | carry) >> 16), codebook); + } +} + +// The funnel read in the prompt body, on our map and our ring. +template +inline void tf_exl3_decode_funnel(threadgroup half* wx, const device half* table, const threadgroup half* lut, + uint codebook, const uint* at, uint b0, uint stride, uint w0, uint w1) { + // The windows are Stride bits apart, so the run is 16 + Stride * (States - 1) bits. + (void)stride; + constexpr uint run = 16u + Stride * (States - 1u); + // The run's first bit is w0's bit (31 - b0) and it has to land on r's bit (run - 1). + ulong r; + if (run >= 32u) { + r = (ulong(w0) << (run - 32u + b0)) | (ulong(w1) >> (64u - run - b0)); + } else if (b0 <= 32u - run) { + r = ulong(w0) >> (32u - run - b0); + } else { + r = (ulong(w0) << (b0 + run - 32u)) | (ulong(w1) >> (64u - run - b0)); + } + TF_UNROLL + for (uint k = 0; k < States; ++k) { + const ushort state = ushort((r >> (Stride * (States - 1u - k))) & 0xffff); + wx[at[k]] = tf_exl3_pick(table, lut, state, codebook); + } +} + +// A threadgroup owns RG sixteen-row groups by CG sixty-four-column groups, one SIMDgroup a (row group, column group). +template diff --git a/zig/kernels/metal/core/exl3_projection_nax_fma.metal b/zig/kernels/metal/core/exl3_projection_nax_fma.metal new file mode 100644 index 00000000000..8d7da037a00 --- /dev/null +++ b/zig/kernels/metal/core/exl3_projection_nax_fma.metal @@ -0,0 +1,312 @@ +kernel void tf_exl3_matmul_decode_fma(const device half* x [[buffer(0)]], + const device uchar* trellis [[buffer(1)]], + device float* sums [[buffer(2)]], + constant TfExl3Args& a [[buffer(3)]], + const device uint* routes [[buffer(4)]], + const device TfExl3Expert* descriptors [[buffer(5)]], + device float* partials [[buffer(6)]], +#if defined(TF_DECODE_TABLE) + const device half* table [[buffer(7)]], +#endif + uint lane [[thread_index_in_simdgroup]], + uint sg [[simdgroup_index_in_threadgroup]], + uint tid [[thread_index_in_threadgroup]], + uint3 tptg [[threads_per_threadgroup]], + uint3 tg [[threadgroup_position_in_grid]]) { +#if TF_FMA_WARPS > 1 + // The warps' partial sums: two columns a lane, one entry a warp a lane. + threadgroup float red[TF_FMA_WARPS][64]; +#endif + const uint row = tg.y; + const uint nb = tg.x * 16u; + if (row >= a.rows) return; + const uint expert = routes[row]; + if (expert >= a.experts) return; + // The entry's own output width bounds this row's column tiles (0 = the call's n). + if (nb >= (descriptors[expert].reserved != 0 ? descriptors[expert].reserved : a.n)) return; + const device uchar* data = descriptors[expert].trellis; + const ulong ks = descriptors[expert].tile_k_stride; + const ulong ns = descriptors[expert].tile_n_stride; + const uint halves = descriptors[expert].halves; + const uint codebook = descriptors[expert].codebook; + const uint blocks = a.k / 16; + const uint W = TF_FMA_WARPS; + const uint b0 = blocks * sg / W, b1 = blocks * (sg + 1u) / W; + // The lane's eight states: the same cursor, word and bit offsets the tensor-unit body computes. + uint off[8], sh[8], rel[8]; + const uint words = 4 * halves; + const uint ring = 128 * halves; + const uint wi0 = tf_exl3_map_for(lane * 8u, halves) & 63u; +#if defined(TF_DECODE_FUNNEL) + // The routed pack's halves = 6: two 32-bit stream words cover the lane's eight states. + const bool funnel = halves == 6u; +#else + const bool funnel = false; +#endif + { + const uint cur = (wi0 << 5) | ((tf_exl3_map_for(lane * 8u, halves) >> 6) & 31u); + TF_UNROLL + for (uint k = 0; k < 8; ++k) { + const uint c8 = (cur + k * (halves >> 1)) % ring; + off[k] = c8 & 31u; + sh[k] = (32u - off[k]) & 31u; + rel[k] = (c8 >> 5) >= wi0 ? (c8 >> 5) - wi0 : (c8 >> 5) + words - wi0; + } + } + uint a1 = wi0 + 1; if (a1 >= words) a1 -= words; + uint a2 = wi0 + 2; if (a2 >= words) a2 -= words; + uint a3 = wi0 + 3; if (a3 >= words) a3 -= words; + // The words a block needs are loaded a block early, so their latency overlaps the multiply. + uint pre[4]; + { + const device ushort* t0 = reinterpret_cast(data + ulong(b0) * ks + ulong(nb / 16) * ns); + pre[0] = tf_exl3_word(t0, wi0); + pre[1] = tf_exl3_word(t0, a1); + if (!funnel) { + pre[2] = tf_exl3_word(t0, a2); + pre[3] = tf_exl3_word(t0, a3); + } + } + // The four-word pipeline read covers an even width up to sixteen halves; the general path reads the tile per state. + const bool pipeline = (halves & 1u) == 0 and halves <= 16; + // One accumulator a state, so the eight products of a block meet in a tree at the end instead of in two chains. + float acc[8] = {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}; + for (uint bb = b0; bb < b1; ++bb) { + const uint kb = bb * 16; + const uint w0 = pre[0], w1 = pre[1]; + uint w2 = 0, w3 = 0; + if (!funnel) { + w2 = pre[2]; + w3 = pre[3]; + } + if (bb + 1 < b1) { + const device ushort* tn = reinterpret_cast(data + ulong(bb + 1) * ks + ulong(nb / 16) * ns); + pre[0] = tf_exl3_word(tn, wi0); + pre[1] = tf_exl3_word(tn, a1); + if (!funnel) { + pre[2] = tf_exl3_word(tn, a2); + pre[3] = tf_exl3_word(tn, a3); + } + } + // The lane's four k rows of this block, read as two halves each (the rows are adjacent in pairs). +#if defined(TF_DIAG_DECODE) && TF_DIAG_DECODE == 4 + // The FMA stays (the weight is still needed) and the constant is a RUNTIME value (the args' rows). + const float x0 = float(a.rows), x1 = float(a.rows), x2 = float(a.rows), x3 = float(a.rows); +#else + const device half* xr = x + ulong(row) * a.k + kb + 2 * (lane & 3u); + const half2 xa = *(const device half2*)xr; + const half2 xb = *(const device half2*)(xr + 8); + const float x0 = float(xa.x), x1 = float(xa.y), x2 = float(xb.x), x3 = float(xb.y); +#endif + if (pipeline) { + TF_UNROLL + for (uint k = 0; k < 8; ++k) { + const uint lo8 = funnel ? (rel[k] == 0 ? w0 : w1) : (rel[k] == 0 ? w0 : rel[k] == 1 ? w1 : w2); + const uint hi8 = funnel ? (rel[k] == 0 ? w1 : 0) : (rel[k] == 0 ? w1 : rel[k] == 1 ? w2 : w3); + const uint carry = (hi8 >> sh[k]) & (0u - uint(off[k] != 0)); + const ushort s = ushort(((lo8 << off[k]) | carry) >> 16); +#if defined(TF_DECODE_TABLE) + const float w = float(tf_exl3_table_value(table, s, codebook)); +#else + const float w = float(tf_exl3_value(s, codebook)); +#endif + // The state's row (four of them a lane) and its column (two of them a lane) in the tile. + const uint odd = k & 1u, up = (k >> 1) & 1u; + const float xv = odd == 0 ? (up == 0 ? x0 : x2) : (up == 0 ? x1 : x3); + acc[k] = fma(xv, w, acc[k]); + } + } else { + const device ushort* tile = reinterpret_cast(data + ulong(bb) * ks + ulong(nb / 16) * ns); + TF_UNROLL + for (uint k = 0; k < 8; ++k) { + const ushort s = tf_exl3_mapped_state(tile, tf_exl3_map_for(lane * 8u + k, halves)); +#if defined(TF_DECODE_TABLE) + const float w = float(tf_exl3_table_value(table, s, codebook)); +#else + const float w = float(tf_exl3_value(s, codebook)); +#endif + const uint odd = k & 1u, up = (k >> 1) & 1u; + const float xv = odd == 0 ? (up == 0 ? x0 : x2) : (up == 0 ? x1 : x3); + acc[k] = fma(xv, w, acc[k]); + } + } + } + // The eight accumulators meet in a tree; the first four are the near column, the last four the far one. + float acc0 = (acc[0] + acc[1]) + (acc[2] + acc[3]); + float acc1 = (acc[4] + acc[5]) + (acc[6] + acc[7]); +#if TF_FMA_WARPS > 1 + // The warps' partial sums meet once, here, and the four lanes that share a column meet once, here. + red[sg][lane] = acc0; + red[sg][32 + lane] = acc1; + threadgroup_barrier(mem_flags::mem_threadgroup); + if (sg != 0) return; + acc0 = 0.0f; + acc1 = 0.0f; + for (uint w = 0; w < W; ++w) { + acc0 += red[w][lane]; + acc1 += red[w][32 + lane]; + } +#endif + acc0 += simd_shuffle_xor(acc0, 1); + acc0 += simd_shuffle_xor(acc0, 2); + acc1 += simd_shuffle_xor(acc1, 1); + acc1 += simd_shuffle_xor(acc1, 2); + if ((lane & 3u) == 0u) { + sums[ulong(row) * a.n + nb + lane / 4] = acc0; + sums[ulong(row) * a.n + nb + 8 + lane / 4] = acc1; + } +} + +// One state, one product: the state's window at a compile-time shift. +template +inline float tf_exl3_fma_weight(uint c_cur, uint c_next, const device half* table, uint codebook, + const threadgroup half* lut = nullptr) { + const ushort s = tf_exl3_state_static(c_cur, c_next); +#if defined(TF_DIAG_DECODE) && (TF_DIAG_DECODE == 1 || TF_DIAG_DECODE == 2) + // TF_DIAG_DECODE = 1 keeps the state's extraction and the trellis read and drops the VALUE path. + if (TF_DIAG_DECODE == 1) return float(half(float(s & 0xFFu))); + return 1.0f; +#elif defined(TF_DIAG_DECODE) && (TF_DIAG_DECODE == 6 || TF_DIAG_DECODE == 7) + // The ladder (TF_DIAG_DECODE = 1) isolates the whole value path. + if (codebook == 2u) { +#if TF_DIAG_DECODE == 6 + // The LOAD kept, the index arithmetic gone. + return float(Lut ? lut[s & 1023u] : table[codebook * 65536u + uint(s)]); +#else + // The index arithmetic kept, the LOAD gone. + const uint x = uint(s) * 0x83DCD12Du; + const uint bs = (x & 0x00FF00FFu) + ((x >> 8u) & 0x00FF00FFu); + const uint idx = (bs * 0x00010001u) >> 16u; + return float(half(float(idx & 1u))); +#endif + } +#if TF_DIAG_DECODE == 6 + // The table codebooks: the value IS the load -- the shipped arm. + return float(table[codebook * 65536u + uint(s)]); +#else + // The table codebooks: the load alone (no index arithmetic exists). + return float(half(float(s & 1u))); +#endif +// THE BRANCH MUST TEST THE VALUE, NOT defined: the define defaults to 0, and defined is true for 0. +#elif defined(TF_FMA_VALUE_ARITH) && TF_FMA_VALUE_ARITH + // The ARITHMETIC value path (the format's own decoder) instead of the shared LUT. + return float(tf_exl3_value(s, codebook)); +#elif defined(TF_DECODE_TABLE) + return Lut ? float(tf_exl3_value_lut(lut, s)) : float(tf_exl3_table_value(table, s, codebook)); +#else + return float(tf_exl3_value(s, codebook)); +#endif +} + +// One state, one product, with the weight already decoded. +template +inline void tf_exl3_fma_step_w(float* acc_j, float w, float x0, float x1, float x2, float x3) { + const uint odd = J & 1u, up = (J >> 1) & 1u; + const float xv = odd == 0 ? (up == 0 ? x0 : x2) : (up == 0 ? x1 : x3); +#if defined(TF_DIAG_DECODE) && TF_DIAG_DECODE == 3 + // A removal arm would let the compiler delete the whole decode (the weight would be dead). + *acc_j = fma(xv, w, *acc_j); +#endif + *acc_j = fma(xv, w, *acc_j); +} + +template +inline void tf_exl3_fma_step(float* acc_j, uint c_cur, uint c_next, const device half* table, uint codebook, + float x0, float x1, float x2, float x3, const threadgroup half* lut = nullptr) { + const float w = tf_exl3_fma_weight(c_cur, c_next, table, codebook, lut); + tf_exl3_fma_step_w(acc_j, w, x0, x1, x2, x3); +} + +// The register-only routed decode with the static state selection. +template +inline void tf_exl3_decode_fma_static_body(const device half* x, const device uchar* trellis, + device float* sums, constant TfExl3Args& a, + const device uint* routes, const device TfExl3Expert* descriptors, + device float* partials, const device half* table, + uint lane, uint sg, uint3 tg, threadgroup float* red_all, + threadgroup half* lut = nullptr) { + const uint row = tg.y; + const uint nb = tg.x * 16u; + if (row >= a.rows) return; + if (!Dense) { + const uint expert = routes[row]; + if (expert >= a.experts) return; + } + TfExl3DecodeJob job; + if (Dense) job = tf_exl3_dense_decode_job(trellis, a); + else job = tf_exl3_routed_decode_job(trellis, a, descriptors, routes[row]); + if (nb >= job.width) return; + const uint blocks = a.k / 16; + const uint W = TF_FMA_WARPS; + const uint b0 = blocks * sg / W, b1 = blocks * (sg + 1u) / W; + const TfExl3RowWalk walk = tf_exl3_row_walk(lane, job.halves); + // Three stream words: the lane's window spans at most 7*S + 16 bits from its first state. + uint pre[3]; + { + const device ushort* t0 = reinterpret_cast(job.trellis + ulong(b0) * job.tile_k_stride + ulong(nb / 16) * job.tile_n_stride); + pre[0] = tf_exl3_word(t0, walk.first_word); + pre[1] = tf_exl3_word(t0, walk.next1); + pre[2] = Two ? 0u : tf_exl3_word(t0, walk.next2); + } + float acc[8] = {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}; + for (uint bb = b0; bb < b1; ++bb) { + const uint kb = bb * 16; + const uint w0 = pre[0], w1 = pre[1], w2 = pre[2]; + if (bb + 1 < b1) { + const device ushort* tn = reinterpret_cast(job.trellis + ulong(bb + 1) * job.tile_k_stride + ulong(nb / 16) * job.tile_n_stride); + pre[0] = tf_exl3_word(tn, walk.first_word); + pre[1] = tf_exl3_word(tn, walk.next1); + pre[2] = Two ? 0u : tf_exl3_word(tn, walk.next2); + } + // The lane's window: one runtime funnel shift, then the eight windows at compile-time shifts. + const uint c_cur = (w0 << walk.first_bit) | ((w1 >> walk.shift) & walk.mask); + const uint c_next = Two ? (w1 << walk.first_bit) : ((w1 << walk.first_bit) | ((w2 >> walk.shift) & walk.mask)); + // The lane's four k rows of this block, read as two halves each (the rows are adjacent in pairs). +#if defined(TF_DIAG_DECODE) && TF_DIAG_DECODE == 4 + // The FMA stays (the weight is still needed) and the constant is a RUNTIME value (the args' rows). + const float x0 = float(a.rows), x1 = float(a.rows), x2 = float(a.rows), x3 = float(a.rows); +#else + const device half* xr = x + ulong(row) * a.k + kb + 2 * (lane & 3u); + const half2 xa = *(const device half2*)xr; + const half2 xb = *(const device half2*)(xr + 8); + const float x0 = float(xa.x), x1 = float(xa.y), x2 = float(xb.x), x3 = float(xb.y); +#endif + tf_exl3_fma_step(&acc[0], c_cur, c_next, table, job.codebook, x0, x1, x2, x3, lut); + tf_exl3_fma_step(&acc[1], c_cur, c_next, table, job.codebook, x0, x1, x2, x3, lut); + tf_exl3_fma_step(&acc[2], c_cur, c_next, table, job.codebook, x0, x1, x2, x3, lut); + tf_exl3_fma_step(&acc[3], c_cur, c_next, table, job.codebook, x0, x1, x2, x3, lut); + tf_exl3_fma_step(&acc[4], c_cur, c_next, table, job.codebook, x0, x1, x2, x3, lut); + tf_exl3_fma_step(&acc[5], c_cur, c_next, table, job.codebook, x0, x1, x2, x3, lut); + tf_exl3_fma_step(&acc[6], c_cur, c_next, table, job.codebook, x0, x1, x2, x3, lut); + tf_exl3_fma_step(&acc[7], c_cur, c_next, table, job.codebook, x0, x1, x2, x3, lut); + } + // The eight accumulators meet in a tree: the first four are the near column, the last four the far one. + float acc0 = (acc[0] + acc[1]) + (acc[2] + acc[3]); + float acc1 = (acc[4] + acc[5]) + (acc[6] + acc[7]); +#if defined(TF_DIAG_DECODE) && TF_DIAG_DECODE == 5 +#elif TF_FMA_WARPS > 1 + red_all[sg * 64u + lane] = acc0; + red_all[sg * 64u + 32u + lane] = acc1; + threadgroup_barrier(mem_flags::mem_threadgroup); + if (sg != 0) return; + acc0 = 0.0f; + acc1 = 0.0f; + for (uint w = 0; w < W; ++w) { + acc0 += red_all[w * 64u + lane]; + acc1 += red_all[w * 64u + 32u + lane]; + } +#endif + acc0 += simd_shuffle_xor(acc0, 1); + acc0 += simd_shuffle_xor(acc0, 2); + acc1 += simd_shuffle_xor(acc1, 1); + acc1 += simd_shuffle_xor(acc1, 2); + const bool store_it = (lane & 3u) == 0u +#if defined(TF_DIAG_DECODE) && TF_DIAG_DECODE == 5 + and sg == 0 +#endif + ; + if (store_it) { + sums[ulong(row) * a.n + nb + lane / 4] = acc0; + sums[ulong(row) * a.n + nb + 8 + lane / 4] = acc1; + } +} diff --git a/zig/kernels/metal/core/exl3_projection_nax_fma_static_a.metal b/zig/kernels/metal/core/exl3_projection_nax_fma_static_a.metal new file mode 100644 index 00000000000..aa69f7ec1e2 --- /dev/null +++ b/zig/kernels/metal/core/exl3_projection_nax_fma_static_a.metal @@ -0,0 +1,253 @@ +kernel void tf_exl3_matmul_decode_fma_static_lut(const device half* x [[buffer(0)]], + const device uchar* trellis [[buffer(1)]], + device float* sums [[buffer(2)]], + constant TfExl3Args& a [[buffer(3)]], + const device uint* routes [[buffer(4)]], + const device TfExl3Expert* descriptors [[buffer(5)]], + device float* partials [[buffer(6)]], +#if defined(TF_DECODE_TABLE) + const device half* table [[buffer(7)]], +#endif + uint lane [[thread_index_in_simdgroup]], + uint sg [[simdgroup_index_in_threadgroup]], + uint tid [[thread_index_in_threadgroup]], + uint3 tptg [[threads_per_threadgroup]], + uint3 tg [[threadgroup_position_in_grid]]) { + threadgroup float red[TF_FMA_WARPS][64]; + threadgroup half lut[1024]; + const uint row = tg.y; + if (row >= a.rows) return; + const uint expert = routes[row]; + if (expert >= a.experts) return; + const uint halves = descriptors[expert].halves; + // The LUT holds the mul1 values, so it is only the right table for that codebook. + const bool mul1 = descriptors[expert].codebook == 2u; + if (mul1) { + const float scale = float(as_type(ushort(0x1EEEu))); + const float bias = float(as_type(ushort(0xC931u))); + for (uint b = tid; b < 1024u; b += tptg.x) lut[b] = half(fma(float(b + 1024u), scale, bias)); + threadgroup_barrier(mem_flags::mem_threadgroup); + } + if (halves == 6u) { + if (mul1) tf_exl3_decode_fma_static_body(x, trellis, sums, a, routes, descriptors, partials, +#if defined(TF_DECODE_TABLE) + table, +#else + nullptr, +#endif + lane, sg, tg, &red[0][0], lut); + else tf_exl3_decode_fma_static_body(x, trellis, sums, a, routes, descriptors, partials, +#if defined(TF_DECODE_TABLE) + table, +#else + nullptr, +#endif + lane, sg, tg, &red[0][0]); + } else if (halves == 10u) { + if (mul1) tf_exl3_decode_fma_static_body(x, trellis, sums, a, routes, descriptors, partials, +#if defined(TF_DECODE_TABLE) + table, +#else + nullptr, +#endif + lane, sg, tg, &red[0][0], lut); + else tf_exl3_decode_fma_static_body(x, trellis, sums, a, routes, descriptors, partials, +#if defined(TF_DECODE_TABLE) + table, +#else + nullptr, +#endif + lane, sg, tg, &red[0][0]); + } else if (halves == 12u) { + if (mul1) tf_exl3_decode_fma_static_body(x, trellis, sums, a, routes, descriptors, partials, +#if defined(TF_DECODE_TABLE) + table, +#else + nullptr, +#endif + lane, sg, tg, &red[0][0], lut); + else tf_exl3_decode_fma_static_body(x, trellis, sums, a, routes, descriptors, partials, +#if defined(TF_DECODE_TABLE) + table, +#else + nullptr, +#endif + lane, sg, tg, &red[0][0]); + } else if (halves == 8u) { + if (mul1) tf_exl3_decode_fma_static_body(x, trellis, sums, a, routes, descriptors, partials, +#if defined(TF_DECODE_TABLE) + table, +#else + nullptr, +#endif + lane, sg, tg, &red[0][0], lut); + else tf_exl3_decode_fma_static_body(x, trellis, sums, a, routes, descriptors, partials, +#if defined(TF_DECODE_TABLE) + table, +#else + nullptr, +#endif + lane, sg, tg, &red[0][0]); + } else if (halves == 4u) { + if (mul1) tf_exl3_decode_fma_static_body(x, trellis, sums, a, routes, descriptors, partials, +#if defined(TF_DECODE_TABLE) + table, +#else + nullptr, +#endif + lane, sg, tg, &red[0][0], lut); + else tf_exl3_decode_fma_static_body(x, trellis, sums, a, routes, descriptors, partials, +#if defined(TF_DECODE_TABLE) + table, +#else + nullptr, +#endif + lane, sg, tg, &red[0][0]); + } else if (halves == 2u) { + if (mul1) tf_exl3_decode_fma_static_body(x, trellis, sums, a, routes, descriptors, partials, +#if defined(TF_DECODE_TABLE) + table, +#else + nullptr, +#endif + lane, sg, tg, &red[0][0], lut); + else tf_exl3_decode_fma_static_body(x, trellis, sums, a, routes, descriptors, partials, +#if defined(TF_DECODE_TABLE) + table, +#else + nullptr, +#endif + lane, sg, tg, &red[0][0]); + } +} + +#if TF_FMA_WARPS != 16 +// The register-only body on the DENSE one-row path. +kernel void tf_exl3_matmul_decode_fma_dense(const device half* x [[buffer(0)]], + const device uchar* trellis [[buffer(1)]], + device float* sums [[buffer(2)]], + constant TfExl3Args& a [[buffer(3)]], + const device uint* routes [[buffer(4)]], + const device TfExl3Expert* descriptors [[buffer(5)]], + device float* partials [[buffer(6)]], +#if defined(TF_DECODE_TABLE) + const device half* table [[buffer(7)]], +#endif + uint lane [[thread_index_in_simdgroup]], + uint sg [[simdgroup_index_in_threadgroup]], + uint tid [[thread_index_in_threadgroup]], + uint3 tptg [[threads_per_threadgroup]], + uint3 tg [[threadgroup_position_in_grid]]) { + threadgroup float red[TF_FMA_WARPS][64]; + threadgroup half lut[1024]; + const uint row = tg.y; + if (row >= a.rows) return; + const uint nb = tg.x * 16u; + if (nb >= a.n) return; + const uint halves = a.halves; + // The mul1 codebook's values depend only on the state's byte sum, so 1,024 entries hold every value. + const bool mul1 = a.codebook == 2u; + if (mul1) { + const float scale = float(as_type(ushort(0x1EEEu))); + const float bias = float(as_type(ushort(0xC931u))); + for (uint b = tid; b < 1024u; b += tptg.x) lut[b] = half(fma(float(b + 1024u), scale, bias)); + threadgroup_barrier(mem_flags::mem_threadgroup); + } + if (halves == 6u) { + if (mul1) tf_exl3_decode_fma_static_body(x, trellis, sums, a, routes, descriptors, partials, +#if defined(TF_DECODE_TABLE) + table, +#else + nullptr, +#endif + lane, sg, tg, &red[0][0], lut); + else tf_exl3_decode_fma_static_body(x, trellis, sums, a, routes, descriptors, partials, +#if defined(TF_DECODE_TABLE) + table, +#else + nullptr, +#endif + lane, sg, tg, &red[0][0]); + } else + if (halves == 10u) { + if (mul1) tf_exl3_decode_fma_static_body(x, trellis, sums, a, routes, descriptors, partials, +#if defined(TF_DECODE_TABLE) + table, +#else + nullptr, +#endif + lane, sg, tg, &red[0][0], lut); + else tf_exl3_decode_fma_static_body(x, trellis, sums, a, routes, descriptors, partials, +#if defined(TF_DECODE_TABLE) + table, +#else + nullptr, +#endif + lane, sg, tg, &red[0][0]); + } else + if (halves == 12u) { + if (mul1) tf_exl3_decode_fma_static_body(x, trellis, sums, a, routes, descriptors, partials, +#if defined(TF_DECODE_TABLE) + table, +#else + nullptr, +#endif + lane, sg, tg, &red[0][0], lut); + else tf_exl3_decode_fma_static_body(x, trellis, sums, a, routes, descriptors, partials, +#if defined(TF_DECODE_TABLE) + table, +#else + nullptr, +#endif + lane, sg, tg, &red[0][0]); + } else + if (halves == 8u) { + if (mul1) tf_exl3_decode_fma_static_body(x, trellis, sums, a, routes, descriptors, partials, +#if defined(TF_DECODE_TABLE) + table, +#else + nullptr, +#endif + lane, sg, tg, &red[0][0], lut); + else tf_exl3_decode_fma_static_body(x, trellis, sums, a, routes, descriptors, partials, +#if defined(TF_DECODE_TABLE) + table, +#else + nullptr, +#endif + lane, sg, tg, &red[0][0]); + } else + if (halves == 4u) { + if (mul1) tf_exl3_decode_fma_static_body(x, trellis, sums, a, routes, descriptors, partials, +#if defined(TF_DECODE_TABLE) + table, +#else + nullptr, +#endif + lane, sg, tg, &red[0][0], lut); + else tf_exl3_decode_fma_static_body(x, trellis, sums, a, routes, descriptors, partials, +#if defined(TF_DECODE_TABLE) + table, +#else + nullptr, +#endif + lane, sg, tg, &red[0][0]); + } else + if (halves == 2u) { + if (mul1) tf_exl3_decode_fma_static_body(x, trellis, sums, a, routes, descriptors, partials, +#if defined(TF_DECODE_TABLE) + table, +#else + nullptr, +#endif + lane, sg, tg, &red[0][0], lut); + else tf_exl3_decode_fma_static_body(x, trellis, sums, a, routes, descriptors, partials, +#if defined(TF_DECODE_TABLE) + table, +#else + nullptr, +#endif + lane, sg, tg, &red[0][0]); + } +} +#endif diff --git a/zig/kernels/metal/core/exl3_projection_nax_fma_static_b.metal b/zig/kernels/metal/core/exl3_projection_nax_fma_static_b.metal new file mode 100644 index 00000000000..d76f0eb8f06 --- /dev/null +++ b/zig/kernels/metal/core/exl3_projection_nax_fma_static_b.metal @@ -0,0 +1,71 @@ +// The width is the expert descriptor's (the routed pack's is 6 halves), so the body is specialised on it at dispatch. +kernel void tf_exl3_matmul_decode_fma_static(const device half* x [[buffer(0)]], + const device uchar* trellis [[buffer(1)]], + device float* sums [[buffer(2)]], + constant TfExl3Args& a [[buffer(3)]], + const device uint* routes [[buffer(4)]], + const device TfExl3Expert* descriptors [[buffer(5)]], + device float* partials [[buffer(6)]], +#if defined(TF_DECODE_TABLE) + const device half* table [[buffer(7)]], +#endif + uint lane [[thread_index_in_simdgroup]], + uint sg [[simdgroup_index_in_threadgroup]], + uint tid [[thread_index_in_threadgroup]], + uint3 tptg [[threads_per_threadgroup]], + uint3 tg [[threadgroup_position_in_grid]]) { + threadgroup float red[TF_FMA_WARPS][64]; + const uint row = tg.y; + if (row >= a.rows) return; + const uint expert = routes[row]; + if (expert >= a.experts) return; + const uint halves = descriptors[expert].halves; + if (halves == 6u) + tf_exl3_decode_fma_static_body(x, trellis, sums, a, routes, descriptors, partials, +#if defined(TF_DECODE_TABLE) + table, +#else + nullptr, +#endif + lane, sg, tg, &red[0][0]); + else if (halves == 10u) + tf_exl3_decode_fma_static_body(x, trellis, sums, a, routes, descriptors, partials, +#if defined(TF_DECODE_TABLE) + table, +#else + nullptr, +#endif + lane, sg, tg, &red[0][0]); + else if (halves == 12u) + tf_exl3_decode_fma_static_body(x, trellis, sums, a, routes, descriptors, partials, +#if defined(TF_DECODE_TABLE) + table, +#else + nullptr, +#endif + lane, sg, tg, &red[0][0]); + else if (halves == 8u) + tf_exl3_decode_fma_static_body(x, trellis, sums, a, routes, descriptors, partials, +#if defined(TF_DECODE_TABLE) + table, +#else + nullptr, +#endif + lane, sg, tg, &red[0][0]); + else if (halves == 4u) + tf_exl3_decode_fma_static_body(x, trellis, sums, a, routes, descriptors, partials, +#if defined(TF_DECODE_TABLE) + table, +#else + nullptr, +#endif + lane, sg, tg, &red[0][0]); + else if (halves == 2u) + tf_exl3_decode_fma_static_body(x, trellis, sums, a, routes, descriptors, partials, +#if defined(TF_DECODE_TABLE) + table, +#else + nullptr, +#endif + lane, sg, tg, &red[0][0]); +} diff --git a/zig/kernels/metal/core/exl3_projection_nax_fma_t.metal b/zig/kernels/metal/core/exl3_projection_nax_fma_t.metal new file mode 100644 index 00000000000..03f82a8c1c7 --- /dev/null +++ b/zig/kernels/metal/core/exl3_projection_nax_fma_t.metal @@ -0,0 +1,266 @@ +// The register-only decode, T column tiles and R rows a threadgroup, the mul1 value by one exact half FMA (no table). + +// A state's value: the table entry fma(half(1024 + sum), 0x1EEE, 0xC931), by 2 * sum as subnormal half bits, exactly. +inline float tf_exl3_t_value(ushort s) { + const uint x = uint(s) * 0x83DCD12Du; + const ushort2 u = as_type(((x >> 7u) & 0x01FE01FEu) + ((x & 0x00FF00FFu) << 1u)); + const half sum = as_type(ushort(u.x + u.y)); + return float(fma(sum, as_type(ushort(0x7AEEu)), as_type(ushort(0xC2E8u)))); +} + +// The value of a state of any codebook: mul1 by arithmetic, the others from the resident table. +template +inline float tf_exl3_t_load(ushort state, const device half* table, uint codebook) { + if (Mul1) return tf_exl3_t_value(state); + return float(table[codebook * 65536u + state]); +} + +// State J of a lane's run: its sixteen bits are the top half of a shifted word, read free as the high half. +template +inline ushort tf_exl3_t_state(uint c0, uint c1, uint mid) { + constexpr uint bit = S * J; + constexpr uint k = bit / 16u; + constexpr uint r = bit % 16u; + static_assert(k <= 2u, "the run is at most three half-word windows"); + const uint base = k == 0u ? c0 : (k == 1u ? mid : c1); + return as_type(base << r).y; +} + +// The decode of one block's eight weights of a lane, then each row's eight products. +template +inline void tf_exl3_t_block(thread float (*acc)[8], uint c0, uint c1, const device half* x, const thread uint* xo, + const device half* table, uint codebook, const device ushort* tile, uint halves, + uint lane) { + const uint mid = (c0 << 16) | (c1 >> 16); + float w[8]; + if (S == 0u) { + for (uint j = 0; j < 8u; ++j) + w[j] = tf_exl3_t_load(tf_exl3_mapped_state(tile, tf_exl3_map_for(lane * 8u + j, halves)), table, codebook); + } else { + w[0] = tf_exl3_t_load(tf_exl3_t_state(c0, c1, mid), table, codebook); + w[1] = tf_exl3_t_load(tf_exl3_t_state(c0, c1, mid), table, codebook); + w[2] = tf_exl3_t_load(tf_exl3_t_state(c0, c1, mid), table, codebook); + w[3] = tf_exl3_t_load(tf_exl3_t_state(c0, c1, mid), table, codebook); + w[4] = tf_exl3_t_load(tf_exl3_t_state(c0, c1, mid), table, codebook); + w[5] = tf_exl3_t_load(tf_exl3_t_state(c0, c1, mid), table, codebook); + w[6] = tf_exl3_t_load(tf_exl3_t_state(c0, c1, mid), table, codebook); + w[7] = tf_exl3_t_load(tf_exl3_t_state(c0, c1, mid), table, codebook); + } + for (uint r = 0; r < R; ++r) { + // The lane's four k rows of this block, read as two halves each (the rows are adjacent in pairs). + const half2 xa = *(const device half2*)(x + xo[r]); + const half2 xb = *(const device half2*)(x + xo[r] + 8); + const float x0 = float(xa.x), x1 = float(xa.y), x2 = float(xb.x), x3 = float(xb.y); + tf_exl3_fma_step_w<0>(&acc[r][0], w[0], x0, x1, x2, x3); + tf_exl3_fma_step_w<1>(&acc[r][1], w[1], x0, x1, x2, x3); + tf_exl3_fma_step_w<2>(&acc[r][2], w[2], x0, x1, x2, x3); + tf_exl3_fma_step_w<3>(&acc[r][3], w[3], x0, x1, x2, x3); + tf_exl3_fma_step_w<4>(&acc[r][4], w[4], x0, x1, x2, x3); + tf_exl3_fma_step_w<5>(&acc[r][5], w[5], x0, x1, x2, x3); + tf_exl3_fma_step_w<6>(&acc[r][6], w[6], x0, x1, x2, x3); + tf_exl3_fma_step_w<7>(&acc[r][7], w[7], x0, x1, x2, x3); + } +} + +// A lane's run in one tile: the stream words it spans, then the two 32-bit windows its eight states are cut from. +template +inline void tf_exl3_t_read(const device ushort* tile, const TfExl3RowWalk walk, thread uint* p) { + p[0] = tf_exl3_word(tile, walk.first_word); + p[1] = tf_exl3_word(tile, walk.next1); + p[2] = Two ? 0u : tf_exl3_word(tile, walk.next2); +} + +template +inline uint2 tf_exl3_t_funnel(const thread uint* p, uint first_bit) { + const uint down = 32u - first_bit; + const uint c0 = uint(((ulong(p[0]) << 32) | p[1]) >> down); + return uint2(c0, Two ? (p[1] << first_bit) : uint(((ulong(p[1]) << 32) | p[2]) >> down)); +} + +// One threadgroup: T tiles of sixteen columns of up to R rows; k is cut into sixteen ranges whatever the warp count. +constant constexpr uint TF_EXL3_T_RANGES = 16u; + +template +inline void tf_exl3_t_body(const device half* x, const TfExl3DecodeJob job, device float* sums, constant TfExl3Args& a, + const device half* table, uint row0, uint nb, uint lane, uint sg, threadgroup float* red) { + constexpr bool Two = S <= 4u; + constexpr uint W = TF_EXL3_T_RANGES; + const uint blocks = a.k / 16; + const TfExl3RowWalk walk = tf_exl3_row_walk(lane, job.halves); + // A block row is a 32-bit step in ushorts (a pack is far below 8 GiB), so the pointers advance by one add. + const uint block_step = uint(job.tile_k_stride >> 1); + uint xrow[R]; + for (uint r = 0; r < R; ++r) xrow[r] = min(row0 + r, a.rows - 1u) * a.k + 2 * (lane & 3u); + for (uint g = sg; g < W; g += TF_FMA_WARPS) { + const uint b0 = blocks * g / W, b1 = blocks * (g + 1u) / W; + const device ushort* tile[T]; + uint c0[T], c1[T]; + for (uint t = 0; t < T; ++t) { + tile[t] = reinterpret_cast(job.trellis + ulong(b0) * job.tile_k_stride + + ulong(nb / 16 + t) * job.tile_n_stride); + if (S != 0u) { + uint p[3]; + tf_exl3_t_read(tile[t], walk, p); + const uint2 c = tf_exl3_t_funnel(p, walk.first_bit); + c0[t] = c.x; + c1[t] = c.y; + } else { + c0[t] = c1[t] = 0u; + } + } + float acc[T][R][8]; + for (uint t = 0; t < T; ++t) + for (uint r = 0; r < R; ++r) + for (uint j = 0; j < 8u; ++j) acc[t][r][j] = 0.0f; + uint xo[R]; + for (uint r = 0; r < R; ++r) xo[r] = xrow[r] + b0 * 16u; + for (uint bb = b0; bb < b1; ++bb) { + uint pre[T][3]; + const bool more = bb + 1 < b1; + if (more and S != 0u) { + for (uint t = 0; t < T; ++t) { + tile[t] += block_step; + tf_exl3_t_read(tile[t], walk, pre[t]); + } + } + for (uint t = 0; t < T; ++t) + tf_exl3_t_block(acc[t], c0[t], c1[t], x, xo, table, job.codebook, tile[t], job.halves, lane); + if (more and S != 0u) { + for (uint t = 0; t < T; ++t) { + const uint2 c = tf_exl3_t_funnel(pre[t], walk.first_bit); + c0[t] = c.x; + c1[t] = c.y; + } + } + if (S == 0u) for (uint t = 0; t < T; ++t) tile[t] += block_step; + for (uint r = 0; r < R; ++r) xo[r] += 16u; + } + for (uint r = 0; r < R; ++r) { + for (uint t = 0; t < T; ++t) { + const uint slot = ((g * R + r) * T + t) * 64u; + red[slot + lane] = (acc[t][r][0] + acc[t][r][1]) + (acc[t][r][2] + acc[t][r][3]); + red[slot + 32u + lane] = (acc[t][r][4] + acc[t][r][5]) + (acc[t][r][6] + acc[t][r][7]); + } + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (sg != 0) return; + for (uint r = 0; r < R; ++r) { + if (row0 + r >= a.rows) break; + for (uint t = 0; t < T; ++t) { + float acc0 = 0.0f, acc1 = 0.0f; + for (uint w = 0; w < W; ++w) { + const uint slot = ((w * R + r) * T + t) * 64u; + acc0 += red[slot + lane]; + acc1 += red[slot + 32u + lane]; + } + acc0 += simd_shuffle_xor(acc0, 1); + acc0 += simd_shuffle_xor(acc0, 2); + acc1 += simd_shuffle_xor(acc1, 1); + acc1 += simd_shuffle_xor(acc1, 2); + if ((lane & 3u) == 0u) { + sums[ulong(row0 + r) * a.n + nb + t * 16u + lane / 4] = acc0; + sums[ulong(row0 + r) * a.n + nb + t * 16u + 8 + lane / 4] = acc1; + } + } + } +} + +template +inline void tf_exl3_t_halves(const device half* x, const TfExl3DecodeJob job, device float* sums, + constant TfExl3Args& a, const device half* table, uint row, uint nb, uint lane, uint sg, + threadgroup float* red) { + switch (job.halves) { + case 6u: tf_exl3_t_body<3, T, R, Mul1>(x, job, sums, a, table, row, nb, lane, sg, red); break; + case 10u: tf_exl3_t_body<5, T, R, Mul1>(x, job, sums, a, table, row, nb, lane, sg, red); break; + case 12u: tf_exl3_t_body<6, T, R, Mul1>(x, job, sums, a, table, row, nb, lane, sg, red); break; + case 8u: tf_exl3_t_body<4, T, R, Mul1>(x, job, sums, a, table, row, nb, lane, sg, red); break; + case 4u: tf_exl3_t_body<2, T, R, Mul1>(x, job, sums, a, table, row, nb, lane, sg, red); break; + case 2u: tf_exl3_t_body<1, T, R, Mul1>(x, job, sums, a, table, row, nb, lane, sg, red); break; + default: tf_exl3_t_body<0, T, R, Mul1>(x, job, sums, a, table, row, nb, lane, sg, red); break; + } +} + +// The routed body: a row's expert names the pack slice; mul1 is computed, other codebooks read the table. +template +inline void tf_exl3_t_routed_kernel(const device half* x, const device uchar* trellis, device float* sums, + constant TfExl3Args& a, const device uint* routes, + const device TfExl3Expert* descriptors, const device half* table, uint lane, + uint sg, uint3 tg, threadgroup float* red) { + const uint row = tg.y; + if (row >= a.rows) return; + const uint expert = routes[row]; + if (expert >= a.experts) return; + const TfExl3DecodeJob job = tf_exl3_routed_decode_job(trellis, a, descriptors, expert); + const uint nb = tg.x * 16u * T; + if (nb >= job.width) return; + if (job.codebook == 2u) tf_exl3_t_halves(x, job, sums, a, table, row, nb, lane, sg, red); + else tf_exl3_t_halves(x, job, sums, a, table, row, nb, lane, sg, red); +} + +// The dense body: one matrix, one row a threadgroup. +template +inline void tf_exl3_t_dense_kernel(const device half* x, const device uchar* trellis, device float* sums, + constant TfExl3Args& a, const device uint* routes, uint lane, uint sg, uint3 tg, threadgroup float* red) { + const uint row = tg.y; + if (!tf_exl3_active(routes, a, row)) return; + const TfExl3DecodeJob job = tf_exl3_dense_decode_job(trellis, a); + const uint nb = tg.x * 16u * T; + if (nb >= job.width) return; + tf_exl3_t_halves(x, job, sums, a, nullptr, row, nb, lane, sg, red); +} + +// The multi-row dense body: R rows a threadgroup share one decode of the matrix (any codebook), one tile wide. +template +inline void tf_exl3_t_multi_kernel(const device half* x, const device uchar* trellis, device float* sums, + constant TfExl3Args& a, const device uint* routes, const device half* table, uint lane, uint sg, uint3 tg, + threadgroup float* red) { + const uint row0 = tg.y * R; + if (row0 >= a.rows) return; + if (R == 1u && !tf_exl3_active(routes, a, row0)) return; + const TfExl3DecodeJob job = tf_exl3_dense_decode_job(trellis, a); + const uint nb = tg.x * 16u * T; + if (nb >= job.width) return; + if (job.codebook == 2u) tf_exl3_t_halves(x, job, sums, a, table, row0, nb, lane, sg, red); + else tf_exl3_t_halves(x, job, sums, a, table, row0, nb, lane, sg, red); +} + +#define TF_EXL3_T_MULTI(NAME, T, R) \ + kernel void NAME(const device half* x [[buffer(0)]], const device uchar* trellis [[buffer(1)]], \ + device float* sums [[buffer(2)]], constant TfExl3Args& a [[buffer(3)]], \ + const device uint* routes [[buffer(4)]], \ + const device half* table [[buffer(7)]], uint lane [[thread_index_in_simdgroup]], \ + uint sg [[simdgroup_index_in_threadgroup]], uint3 tg [[threadgroup_position_in_grid]]) { \ + threadgroup float red[TF_EXL3_T_RANGES * 64 * T * R]; \ + tf_exl3_t_multi_kernel(x, trellis, sums, a, routes, table, lane, sg, tg, red); \ + } + +#if TF_FMA_WARPS == 16 +TF_EXL3_T_MULTI(tf_exl3_matmul_decode_fma_dense, 1, 1) +#endif + +TF_EXL3_T_MULTI(tf_exl3_matmul_decode_fma_dense_multi2, 1, 2) +TF_EXL3_T_MULTI(tf_exl3_matmul_decode_fma_dense_multi4, 1, 4) + +#define TF_EXL3_T_KERNELS(T) \ + kernel void tf_exl3_matmul_decode_fma_t##T( \ + const device half* x [[buffer(0)]], const device uchar* trellis [[buffer(1)]], device float* sums [[buffer(2)]], \ + constant TfExl3Args& a [[buffer(3)]], const device uint* routes [[buffer(4)]], \ + const device TfExl3Expert* descriptors [[buffer(5)]], const device half* table [[buffer(7)]], \ + uint lane [[thread_index_in_simdgroup]], uint sg [[simdgroup_index_in_threadgroup]], \ + uint3 tg [[threadgroup_position_in_grid]]) { \ + threadgroup float red[TF_EXL3_T_RANGES * 64 * T]; \ + tf_exl3_t_routed_kernel(x, trellis, sums, a, routes, descriptors, table, lane, sg, tg, red); \ + } \ + kernel void tf_exl3_matmul_decode_fma_t_dense##T( \ + const device half* x [[buffer(0)]], const device uchar* trellis [[buffer(1)]], device float* sums [[buffer(2)]], \ + constant TfExl3Args& a [[buffer(3)]], const device uint* routes [[buffer(4)]], uint lane [[thread_index_in_simdgroup]], \ + uint sg [[simdgroup_index_in_threadgroup]], uint3 tg [[threadgroup_position_in_grid]]) { \ + threadgroup float red[TF_EXL3_T_RANGES * 64 * T]; \ + tf_exl3_t_dense_kernel(x, trellis, sums, a, routes, lane, sg, tg, red); \ + } + +// More tiles a threadgroup share a block's x loads and conversions; fewer threadgroups fill the GPU. +TF_EXL3_T_KERNELS(1) +TF_EXL3_T_KERNELS(2) +TF_EXL3_T_KERNELS(4) diff --git a/zig/kernels/metal/core/exl3_projection_nax_fp8.metal b/zig/kernels/metal/core/exl3_projection_nax_fp8.metal new file mode 100644 index 00000000000..d1423ffba06 --- /dev/null +++ b/zig/kernels/metal/core/exl3_projection_nax_fp8.metal @@ -0,0 +1,97 @@ +inline void tf_fp8_expand4(threadgroup half* wx, uint tid, uint u) { + const half2 a = as_type(((u & 0x007F007Fu) << 7) | ((u << 8) & 0x80008000u)); + const half2 b = as_type(((u >> 1) & 0x3F803F80u) | (u & 0x80008000u)); + const half2 k256 = half2(256.0h, 256.0h); + threadgroup half2* o = (threadgroup half2*)(wx + 4u * tid); + o[0] = half2(a.x, b.x) * k256; + o[1] = half2(a.y, b.y) * k256; +} + +inline void tf_i8_expand4(threadgroup half* wx, uint tid, uint u) { + const int b0 = int(u << 24) >> 24, b1 = int(u << 16) >> 24, b2 = int(u << 8) >> 24, b3 = int(u) >> 24; + threadgroup half2* o = (threadgroup half2*)(wx + 4u * tid); + o[0] = half2(half(float(b0)), half(float(b1))); + o[1] = half2(half(float(b2)), half(float(b3))); +} + +template +inline void tf_exl3_prefill_body_fp8(threadgroup half* wx, const device half* x, const device uchar* w8, + const device float* scales, device O* sums, constant TfExl3Args& a, + uint lane, uint sg, uint tid, uint3 tg) { + constexpr uint RG = 8u, CG = 1u; + const uint trows = RG * 16u; + const uint rb = tg.y * trows, nb = tg.x * 64u; + if (rb >= a.rows) return; + const uint rows_here = min(trows, a.rows - rb); + const uint cols_here = min(64u, a.n - nb); + const short2 home = frag_home(ushort(lane)); + const uint nb64 = a.n >> 6, block = nb >> 6; + const uint sgr = sg % RG, sgc = sg / RG; + frag lo0, hi0, lo1, hi1; + lo0 = frag(0); hi0 = frag(0); lo1 = frag(0); hi1 = frag(0); + if (tid < 256u) { + const uint u = *reinterpret_cast(w8 + ((block) << 10) + 4u * tid); + if (a.halves == 0u) tf_i8_expand4(wx, tid, u); else tf_fp8_expand4(wx, tid, u); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + uint cur_buf = 0; + for (uint kb = 0; kb < a.k; kb += 16u) { + const uint nkb = kb + 16u; + uint nu = 0u; + if (nkb < a.k) { + if (tid < 256u) { + nu = *reinterpret_cast(w8 + (((nkb >> 4) * nb64 + block) << 10) + 4u * tid); + } + } + frag av; + tf_frag_get_dev4(av, x, int(a.x_stride), int(rb + sgr * 16u), int(kb), home, int(rb + rows_here)); + threadgroup half* cur = wx + cur_buf * 1024u; + frag b0, b1; + const int wc = int(sgc * 64u); + tf_frag_get_tg4(b0, cur, 64, 0, wc, home); + tf_frag_get_tg4(b1, cur, 64, 0, wc + 16, home); + mma_16x32(lo0, hi0, av, b0, b1); + tf_frag_get_tg4(b0, cur, 64, 0, wc + 32, home); + tf_frag_get_tg4(b1, cur, 64, 0, wc + 48, home); + mma_16x32(lo1, hi1, av, b0, b1); + if (nkb < a.k) { + if (tid < 256u) { + if (a.halves == 0u) tf_i8_expand4(wx + (cur_buf ^ 1u) * 1024u, tid, nu); + else tf_fp8_expand4(wx + (cur_buf ^ 1u) * 1024u, tid, nu); + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + cur_buf ^= 1u; + } + const int c0 = int(nb + sgc * 64u); + const int r0 = int(rb + sgr * 16u); + // A bf16 destination is the caller's final output (the pre-rotated pack has no epilogue transform). + const int out_ld = (sizeof(O) == 4) ? int(a.n) : int(a.y_stride); + if (scales != nullptr) { + // The per-output-row E4M3 scale. + TF_UNROLL + for (short e = 0; e < 8; e++) { + lo0[e] *= scales[c0 + home.x + (e & 3)]; + hi0[e] *= scales[c0 + 16 + home.x + (e & 3)]; + lo1[e] *= scales[c0 + 32 + home.x + (e & 3)]; + hi1[e] *= scales[c0 + 48 + home.x + (e & 3)]; + } + } + frag_put_in(lo0, sums, out_ld, r0, c0, home, int(rb + rows_here), int(nb + cols_here)); + frag_put_in(hi0, sums, out_ld, r0, c0 + 16, home, int(rb + rows_here), int(nb + cols_here)); + frag_put_in(lo1, sums, out_ld, r0, c0 + 32, home, int(rb + rows_here), int(nb + cols_here)); + frag_put_in(hi1, sums, out_ld, r0, c0 + 48, home, int(rb + rows_here), int(nb + cols_here)); +} + +kernel void tf_exl3_matmul_prefill_fp8(const device half* const x [[buffer(0)]], + const device uchar* const w8 [[buffer(1)]], + device float* const sums [[buffer(2)]], + constant TfExl3Args& a [[buffer(3)]], + const device float* const scales [[buffer(4)]], + uint lane [[thread_index_in_simdgroup]], + uint sg [[simdgroup_index_in_threadgroup]], + uint tid [[thread_index_in_threadgroup]], + uint3 tg [[threadgroup_position_in_grid]]) { + threadgroup half wx[2 * 16 * 64]; + tf_exl3_prefill_body_fp8(wx, x, w8, scales, sums, a, lane, sg, tid, tg); +} diff --git a/zig/kernels/metal/core/exl3_projection_nax_prefill.metal b/zig/kernels/metal/core/exl3_projection_nax_prefill.metal new file mode 100644 index 00000000000..3eef1a4adb5 --- /dev/null +++ b/zig/kernels/metal/core/exl3_projection_nax_prefill.metal @@ -0,0 +1,190 @@ +// The routed prompt tile's job follows the release's expert blocks; the pack layout and row walk are our own. + +kernel void tf_exl3_matmul_prefill_nax2(const device half* x [[buffer(0)]], + const device uchar* trellis [[buffer(1)]], + device float* sums [[buffer(2)]], + constant TfExl3Args& a [[buffer(3)]], + const device uint* routes [[buffer(4)]], + const device TfExl3Expert* descriptors [[buffer(5)]], + uint lane [[thread_index_in_simdgroup]], + uint sg [[simdgroup_index_in_threadgroup]], + uint tid [[thread_index_in_threadgroup]], + uint3 tptg [[threads_per_threadgroup]], + uint3 tg [[threadgroup_position_in_grid]]) { + threadgroup half wx[16 * 64]; + tf_exl3_prefill_body(wx, x, trellis, sums, a, routes, descriptors, nullptr, nullptr, lane, sg, tid, tptg.x, tg); +} + +// One row an expert, four rows a threadgroup. +kernel void tf_exl3_matmul_decode_nax(const device half* x [[buffer(0)]], + const device uchar* trellis [[buffer(1)]], + device float* sums [[buffer(2)]], + constant TfExl3Args& a [[buffer(3)]], + const device uint* routes [[buffer(4)]], + const device TfExl3Expert* descriptors [[buffer(5)]], + device float* partials [[buffer(6)]], +#if defined(TF_DECODE_TABLE) + const device half* table [[buffer(7)]], +#endif + uint lane [[thread_index_in_simdgroup]], + uint sg [[simdgroup_index_in_threadgroup]], + uint tid [[thread_index_in_threadgroup]], + uint3 tptg [[threads_per_threadgroup]], + uint3 tg [[threadgroup_position_in_grid]]) { + // Two weight tiles a SIMDgroup: the next block decodes while this one multiplies. +#if defined(TF_DECODE_COMPACT) + // Compact: one row a threadgroup, two 16x32 tiles only (1 KB). + threadgroup half wx[2 * 16 * 32]; +#else + threadgroup half wx[2 * 4 * 16 * 32]; +#endif + const uint nb = tg.x * 32; + // One SIMDgroup a row: a threadgroup of four warps takes four rows, one of a single warp takes one. +#if defined(TF_DECODE_COMPACT) + const uint rpt = 1; + const uint row = tg.y; + threadgroup half* wxa = wx; + threadgroup half* wxb = wx + 16 * 32; +#else + const uint rpt = tptg.x / 32u; + const uint row = tg.y * rpt + sg; + threadgroup half* wxa = wx + sg * (16 * 32); + threadgroup half* wxb = wx + (4 + sg) * (16 * 32); +#endif + if (row >= a.rows) return; + const uint expert = routes[row]; + if (expert >= a.experts) return; + // One routed row's pack slice: the expert's trellis, k/n strides, width and codebook. + const TfExl3DecodeJob job = tf_exl3_routed_decode_job(trellis, a, descriptors, expert); + const short2 home = frag_home(ushort(lane)); + const uint cols_here = min(32u, a.n - nb); + // A decode tile has a handful of rows and one threadgroup a layer for the whole k range. + const uint split = tg.z; + const uint blocks = a.k / 16; + const uint b0 = a.splits > 1 ? blocks * split / a.splits : 0; + const uint b1 = a.splits > 1 ? blocks * (split + 1) / a.splits : blocks; + // Eight consecutive states a thread of each sixteen-column tile, so the stream words they can touch are read once. + const TfExl3DigWindows walk = tf_exl3_dig_windows<8u, 1u, 32u>(lane * 8u, job.halves, 0u, 0u, true); + // TF_DECODE_FUNNEL: the routed pack's halves = 6. +#if defined(TF_DECODE_FUNNEL) + // Halves = 8 (the drafter's routed pack) joins halves = 6 ONLY under TF_DECODE_FUNNEL_H8, an optional arm. +#if defined(TF_DECODE_FUNNEL_H8) + const bool funnel = job.halves == 6u or job.halves == 8u; +#else + const bool funnel = job.halves == 6u; +#endif +#else + const bool funnel = false; +#endif +// THE TWO-WORD READ AT halves = 8 WITHOUT THE FUNNEL'S ASSEMBLY. +#if defined(TF_DECODE_TWO) + const bool two_word = job.halves == 8u; +#else + const bool two_word = false; +#endif + frag lo = frag(0), hi = frag(0); + // The words a block needs are loaded a block early, so their latency overlaps the multiply instead of stalling. + uint pre[2][4]; + const bool pipeline = (job.halves & 1u) == 0 and job.halves <= 16; + if (pipeline) { + const device ushort* t0 = reinterpret_cast(job.trellis + ulong(b0) * job.tile_k_stride + ulong(nb / 16) * job.tile_n_stride); + pre[0][0] = tf_exl3_word(t0, walk.first_word); + pre[0][1] = tf_exl3_word(t0, walk.next1); + if (!funnel and !two_word) { + pre[0][2] = tf_exl3_word(t0, walk.next2); + pre[0][3] = tf_exl3_word(t0, walk.next3); + } + if (nb + 16 < a.n) { + const device ushort* t1 = reinterpret_cast(job.trellis + ulong(b0) * job.tile_k_stride + ulong(nb / 16 + 1) * job.tile_n_stride); + pre[1][0] = tf_exl3_word(t1, walk.first_word); + pre[1][1] = tf_exl3_word(t1, walk.next1); + if (!funnel and !two_word) { + pre[1][2] = tf_exl3_word(t1, walk.next2); + pre[1][3] = tf_exl3_word(t1, walk.next3); + } + } + } + for (uint bb = b0; bb < b1; ++bb) { + const uint kb = bb * 16; + threadgroup half* wxc = ((bb - b0) & 1u) ? wxb : wxa; + if (pipeline) { + TF_UNROLL + for (uint h = 0; h < 2; ++h) { + if (nb + h * 16 >= a.n) continue; + const uint w0 = pre[h][0], w1 = pre[h][1]; + uint w2 = 0, w3 = 0; + if (!funnel and !two_word) { + w2 = pre[h][2]; + w3 = pre[h][3]; + } + const uint nxt = bb + 1; + if (nxt < b1) { + const device ushort* tn = reinterpret_cast(job.trellis + ulong(nxt) * job.tile_k_stride + ulong(nb / 16 + h) * job.tile_n_stride); + pre[h][0] = tf_exl3_word(tn, walk.first_word); + pre[h][1] = tf_exl3_word(tn, walk.next1); + if (!funnel and !two_word) { + pre[h][2] = tf_exl3_word(tn, walk.next2); + pre[h][3] = tf_exl3_word(tn, walk.next3); + } + } + if (funnel) { + // Two words a lane, on our map and with our left-shift funnel. + TF_UNROLL + for (uint k = 0; k < 8; ++k) { + const uint lo8 = walk.rel[k] == 0 ? w0 : w1; + const uint hi8 = walk.rel[k] == 0 ? w1 : 0; + const uint carry = (hi8 >> walk.sh[k]) & (0u - uint(walk.off[k] != 0)); +#if defined(TF_DECODE_TABLE) + wxc[walk.at[k] + h * 16] = tf_exl3_table_value(table, ushort(((lo8 << walk.off[k]) | carry) >> 16), job.codebook); +#else + wxc[walk.at[k] + h * 16] = tf_exl3_value(ushort(((lo8 << walk.off[k]) | carry) >> 16), job.codebook); +#endif + } + } else { + TF_UNROLL + for (uint k = 0; k < 8; ++k) { + const uint lo8 = walk.rel[k] == 0 ? w0 : walk.rel[k] == 1 ? w1 : w2; + const uint hi8 = walk.rel[k] == 0 ? w1 : walk.rel[k] == 1 ? w2 : w3; + const uint carry = (hi8 >> walk.sh[k]) & (0u - uint(walk.off[k] != 0)); +#if defined(TF_DECODE_TABLE) + wxc[walk.at[k] + h * 16] = tf_exl3_table_value(table, ushort(((lo8 << walk.off[k]) | carry) >> 16), job.codebook); +#else + wxc[walk.at[k] + h * 16] = tf_exl3_value(ushort(((lo8 << walk.off[k]) | carry) >> 16), job.codebook); +#endif + } + } + } + } else { + TF_UNROLL + for (uint t = 0; t < 16; ++t) { + const uint idx = lane + 32 * t, h = idx / 256, p = idx % 256; + if (nb + h * 16 >= a.n) continue; + const device ushort* tile = reinterpret_cast( + job.trellis + ulong(kb / 16) * job.tile_k_stride + ulong(nb / 16 + h) * job.tile_n_stride); + const uint l = p / 8, e = p % 8; + const uint r = 2 * (l % 4) + (e & 1u) + 8 * ((e >> 1) & 1u); + const uint c = l / 4 + 8 * (e >> 2); +#if defined(TF_DECODE_TABLE) + wxc[r * 32 + h * 16 + c] = tf_exl3_table_value(table, tf_exl3_mapped_state(tile, tf_exl3_map_for(p, job.halves)), job.codebook); +#else + wxc[r * 32 + h * 16 + c] = tf_exl3_value(tf_exl3_mapped_state(tile, tf_exl3_map_for(p, job.halves)), job.codebook); +#endif + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + // A tile's first row is the token; the bound makes every other row read zero, so only row 0 is live. + frag av, b0f, b1f; + frag_get_in(av, (const device half*)x, int(a.k), int(row), int(kb), home, int(row) + 1, int(kb) + 16); + tf_frag_get_tg4(b0f, wxc, 32, 0, 0, home); + tf_frag_get_tg4(b1f, wxc, 32, 0, 16, home); + mma_16x32(lo, hi, av, b0f, b1f); + } + if (a.splits > 1) { + device float* part = partials + (ulong(split) * a.rows + ulong(row)) * a.n; + frag_put_in(lo, part, int(a.n), 0, int(nb), home, 1, int(nb) + int(cols_here)); + frag_put_in(hi, part, int(a.n), 0, int(nb + 16), home, 1, int(nb) + int(cols_here)); + return; + } + frag_put_in(lo, sums, int(a.n), int(row), int(nb), home, int(row) + 1, int(nb) + int(cols_here)); + frag_put_in(hi, sums, int(a.n), int(row), int(nb + 16), home, int(row) + 1, int(nb) + int(cols_here)); +} diff --git a/zig/kernels/metal/core/exl3_projection_nax_prefill_body.metal b/zig/kernels/metal/core/exl3_projection_nax_prefill_body.metal new file mode 100644 index 00000000000..f174e2f1723 --- /dev/null +++ b/zig/kernels/metal/core/exl3_projection_nax_prefill_body.metal @@ -0,0 +1,291 @@ +inline void tf_exl3_prefill_body(threadgroup half* wx, const device half* x, const device uchar* trellis, + device float* sums, constant TfExl3Args& a, const device uint* routes, + const device TfExl3Expert* descriptors, const device half* table, + const threadgroup half* lut, + uint lane, uint sg, uint tid, uint tptg, uint3 tg) { + const uint trows = RG * 16u; + const uint rb = tg.y * trows, nb = tg.x * (64u * CG); + if (a.indexed == 1 || rb >= a.rows) return; + const uint tile_expert = a.indexed ? routes[rb] : a.expert_id; + if (a.indexed && tile_expert >= a.experts) return; + const TfExl3DigJob job = tf_exl3_dig_job(trellis, a, routes, descriptors, rb, nb, trows); + const short2 home = frag_home(ushort(lane)); + // Four warps decode a sixty-four-column group; more warps split each lane's sixteen states instead of waiting. + constexpr uint wpg = RG / (4u * Rpg); // warps decoding one column group + constexpr uint states = 8u / wpg; // consecutive states a lane owns + const uint gwarp = tid / 32u, group = gwarp / wpg, wg = gwarp % wpg; + const uint h = group % 4u, hg = (group / 4u) * 64u; + const uint p0 = (wg * 32u + tid % 32u) * states; + const bool decodes = group < 4u * CG and nb + hg + h * 16u < a.n; + const uint words = 4 * job.halves; + const uint wi0 = tf_exl3_map_for(p0, job.halves) & 63u; + // The Fast path's cursor is the shared walk; with F6 the funnel path is the only one. + TfExl3DigWindows walk; + if (Fast) walk = tf_exl3_dig_windows(p0, job.halves, hg, h, !F6); + // This SIMDgroup's row groups (Rpg of them) and its column group. + const uint sgr = Rpg * (sg % (RG / Rpg)), sgc = sg / (RG / Rpg); + // The routed tile's padded rows need no multiply. + uint real_mask = (1u << Rpg) - 1u; + if (SkipPad and a.indexed != 0) { + real_mask = 0u; + if (lane < 16u * Rpg) { + const uint grow = rb + (sgr + lane / 16u) * 16u + (lane % 16u); + if (grow < a.rows and routes[grow] != 0xffffffffu) real_mask = 1u << (lane / 16u); + } + } + bool group_live[Rpg]; + bool any_live = false; + TF_UNROLL + for (uint r = 0; r < Rpg; ++r) { + group_live[r] = simd_any((real_mask & (1u << r)) != 0u); + any_live = any_live or group_live[r]; + } + frag lo0[Rpg], hi0[Rpg], lo1[Rpg], hi1[Rpg]; + TF_UNROLL + for (uint r = 0; r < Rpg; ++r) { + lo0[r] = frag(0); + hi0[r] = frag(0); + lo1[r] = frag(0); + hi1[r] = frag(0); + } + // The four stream words a block needs are loaded a block early: issued before the barrier. + uint p0v = 0, p1v = 0, p2v = 0, p3v = 0; + if (Fast and decodes) { + const device ushort* tile0 = reinterpret_cast(job.trellis + ulong(nb / 16 + hg / 16u + h) * job.tile_n_stride); + uint a1 = wi0 + 1; if (a1 >= words) a1 -= words; + uint a2 = wi0 + 2; if (a2 >= words) a2 -= words; + uint a3 = wi0 + 3; if (a3 >= words) a3 -= words; + p0v = tf_exl3_word(tile0, wi0); + p1v = tf_exl3_word(tile0, a1); + p2v = tf_exl3_word(tile0, a2); + p3v = tf_exl3_word(tile0, a3); + } + for (uint kb = 0; kb < a.k; kb += 16) { + // One thread owns 8 consecutive states of one 16x16 tile. + if (decodes) { + { + const device ushort* tile = reinterpret_cast( + job.trellis + ulong(kb / 16) * job.tile_k_stride + ulong(nb / 16 + hg / 16u + h) * job.tile_n_stride); + if (Funnel and (F6 or job.halves == 6) and (states == 8 or states == 4)) { + // Two words a lane: the funnel holds the lane's eight windows (three bits apart). + const uint nkb = kb + 16; + const uint w0 = p0v, w1 = p1v; + if (nkb < a.k) { + const device ushort* tile_n = reinterpret_cast( + job.trellis + ulong(nkb / 16) * job.tile_k_stride + ulong(nb / 16 + hg / 16u + h) * job.tile_n_stride); + p0v = tf_exl3_word(tile_n, wi0); + p1v = tf_exl3_word(tile_n, wi0 + 1 < words ? wi0 + 1 : wi0 + 1 - words); + } + tf_exl3_decode_funnel(wx, table, lut, job.codebook, walk.at, walk.first_bit, job.halves >> 1, w0, w1); + } else if (Fast and (job.halves & 1u) == 0 and job.halves <= 16) { + // Eight states span seven steps, so at 8 bits a value their cursors reach three words past the first. + const uint w0 = p0v, w1 = p1v, w2 = p2v, w3 = p3v; + const uint nkb = kb + 16; + if (nkb < a.k) { + const device ushort* tile_n = reinterpret_cast( + job.trellis + ulong(nkb / 16) * job.tile_k_stride + ulong(nb / 16 + hg / 16u + h) * job.tile_n_stride); + p0v = tf_exl3_word(tile_n, wi0); + p1v = tf_exl3_word(tile_n, wi0 + 1 < words ? wi0 + 1 : wi0 + 1 - words); + p2v = tf_exl3_word(tile_n, wi0 + 2 < words ? wi0 + 2 : wi0 + 2 - words); + p3v = tf_exl3_word(tile_n, wi0 + 3 < words ? wi0 + 3 : wi0 + 3 - words); + } + TF_UNROLL + for (uint k = 0; k < states; ++k) { + const uint lo = walk.rel[k] == 0 ? w0 : walk.rel[k] == 1 ? w1 : w2; + const uint hi = walk.rel[k] == 0 ? w1 : walk.rel[k] == 1 ? w2 : w3; + const uint carry = (hi >> walk.sh[k]) & (0u - uint(walk.off[k] != 0)); + wx[walk.at[k]] = tf_exl3_pick(table, lut, ushort(((lo << walk.off[k]) | carry) >> 16), job.codebook); + } + } else if (job.halves <= 16 and (job.halves & 1u) == 0 and states == 8) { + const uint ring = 128 * job.halves; + uint at1 = wi0 + 1; if (at1 >= words) at1 -= words; + uint at2 = wi0 + 2; if (at2 >= words) at2 -= words; + uint at3 = wi0 + 3; if (at3 >= words) at3 -= words; + uint at4 = wi0 + 4; if (at4 >= words) at4 -= words; + const uint w0 = tf_exl3_word(tile, wi0); + const uint w1 = tf_exl3_word(tile, at1), w2 = tf_exl3_word(tile, at2); + const uint w3 = tf_exl3_word(tile, at3), w4 = tf_exl3_word(tile, at4); + uint cur = (wi0 << 5) | ((tf_exl3_map_for(p0, job.halves) >> 6) & 31u); + TF_UNROLL + for (uint k = 0; k < 8; ++k) { + // Each state's cursor comes from the block's origin: the eight decodes are independent. + uint c8 = cur + k * (job.halves >> 1); + if (c8 >= ring) c8 -= ring; + const uint wi = c8 >> 5, off = c8 & 31u; + const uint rel = wi >= wi0 ? wi - wi0 : wi + words - wi0; + const uint lo = rel == 0 ? w0 : rel == 1 ? w1 : rel == 2 ? w2 : w3; + const uint hi = rel == 0 ? w1 : rel == 1 ? w2 : rel == 2 ? w3 : w4; + const uint carry = (hi >> ((32 - off) & 31u)) & (0u - uint(off != 0)); + const uint p = p0 + k, l = p / 8, e = p % 8; + const uint r = 2 * (l % 4) + (e & 1u) + 8 * ((e >> 1) & 1u); + const uint c = l / 4 + 8 * (e >> 2); + wx[r * (64u * CG) + hg + h * 16 + c] = tf_exl3_pick(table, lut, ushort(((lo << off) | carry) >> 16), job.codebook); + } + } else { + TF_UNROLL + for (uint k = 0; k < 8; ++k) { + const uint p = p0 + k; + const uint l = p / 8, e = p % 8; + const uint r = 2 * (l % 4) + (e & 1u) + 8 * ((e >> 1) & 1u); + const uint c = l / 4 + 8 * (e >> 2); + wx[r * (64u * CG) + hg + h * 16 + c] = tf_exl3_pick(table, lut, tf_exl3_mapped_state(tile, tf_exl3_map_for(p, job.halves)), job.codebook); + } + } + } + } + // This SIMDgroup's rows of the k block, read straight into fragments: no staging buffer, one barrier. + frag av[Rpg]; + if (any_live) { + TF_UNROLL + for (uint r = 0; r < Rpg; ++r) { + if (group_live[r]) tf_frag_get_dev4(av[r], (const device half*)x, int(a.k), int(rb + (sgr + r) * 16), int(kb), home, int(rb + job.rows_here)); + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (any_live) { + frag b0, b1; + const int wc = int(sgc * 64u); + tf_frag_get_tg4(b0, wx, int(64u * CG), 0, wc, home); + tf_frag_get_tg4(b1, wx, int(64u * CG), 0, wc + 16, home); + TF_UNROLL + for (uint r = 0; r < Rpg; ++r) { + if (group_live[r]) mma_16x32(lo0[r], hi0[r], av[r], b0, b1); + } + tf_frag_get_tg4(b0, wx, int(64u * CG), 0, wc + 32, home); + tf_frag_get_tg4(b1, wx, int(64u * CG), 0, wc + 48, home); + TF_UNROLL + for (uint r = 0; r < Rpg; ++r) { + if (group_live[r]) mma_16x32(lo1[r], hi1[r], av[r], b0, b1); + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + } + const int r0 = int(rb + sgr * 16); + const int c0 = int(nb + sgc * 64u); + // `sums` is the whole [rows, n] buffer and frag_put_in indexes it absolutely (rr, cc). + TF_UNROLL + for (uint r = 0; r < Rpg; ++r) { + if (group_live[r]) { + frag_put_in(lo0[r], sums, int(a.n), r0 + int(r * 16), c0, home, int(rb + job.rows_here), int(nb + job.cols_here)); + frag_put_in(hi0[r], sums, int(a.n), r0 + int(r * 16), c0 + 16, home, int(rb + job.rows_here), int(nb + job.cols_here)); + frag_put_in(lo1[r], sums, int(a.n), r0 + int(r * 16), c0 + 32, home, int(rb + job.rows_here), int(nb + job.cols_here)); + frag_put_in(hi1[r], sums, int(a.n), r0 + int(r * 16), c0 + 48, home, int(rb + job.rows_here), int(nb + job.cols_here)); + } + } +} + + +// Double-buffered prompt body: the next k block decodes into the tile the multiply is not reading. +template +inline void tf_exl3_prefill_body_db(threadgroup half* wx, const device half* x, const device uchar* trellis, + device float* sums, constant TfExl3Args& a, const device uint* routes, + const device TfExl3Expert* descriptors, const device half* table, + uint lane, uint sg, uint tid, uint tptg, uint3 tg) { + const uint trows = RG * 16u; + const uint rb = tg.y * trows, nb = tg.x * (64u * CG); + if (a.indexed == 1 || rb >= a.rows) return; + const uint tile_expert = a.indexed ? routes[rb] : a.expert_id; + if (a.indexed && tile_expert >= a.experts) return; + const TfExl3DigJob job = tf_exl3_dig_job(trellis, a, routes, descriptors, rb, nb, trows); + const short2 home = frag_home(ushort(lane)); + // With Rpg row groups a SIMDgroup (a SIMDgroup owns thirty-two rows in the wide tile). + constexpr uint wpg = RG / (4u * Rpg); + constexpr uint states = 8u / wpg; + const uint gwarp = tid / 32u, group = gwarp / wpg, wg = gwarp % wpg; + const uint h = group % 4u, hg = (group / 4u) * 64u; + const uint p0 = (wg * 32u + tid % 32u) * states; + const bool decodes = group < 4u * CG and nb + hg + h * 16u < a.n; + // The funnel is admissible where the lane's run fits two 32-bit words: halves = 6. + const bool use_funnel = Funnel and ((job.halves == 6u and (states == 8u or states == 4u)) or + (job.halves == 8u and states == 4u)); + if ((job.halves & 1u) != 0 or job.halves > 16) { + tf_exl3_prefill_body(wx, x, trellis, sums, a, routes, descriptors, table, nullptr, lane, sg, tid, tptg, tg); + return; + } + const TfExl3DigWindows walk = tf_exl3_dig_windows(p0, job.halves, hg, h, true); + const uint words = walk.words; + const uint wi0 = walk.first_word; + const uint sgr = Rpg * (sg % (RG / Rpg)), sgc = sg / (RG / Rpg); + frag lo0[Rpg], hi0[Rpg], lo1[Rpg], hi1[Rpg]; + TF_UNROLL + for (uint r = 0; r < Rpg; ++r) { + lo0[r] = frag(0); + hi0[r] = frag(0); + lo1[r] = frag(0); + hi1[r] = frag(0); + } + // Prologue: block 0 into buffer 0, then one barrier before the first multiply. + if (decodes) { + const uint w0 = tf_exl3_block_word(job.trellis, job.tile_k_stride, job.tile_n_stride, 0, nb, hg, h, wi0, words); + const uint w1 = tf_exl3_block_word(job.trellis, job.tile_k_stride, job.tile_n_stride, 0, nb, hg, h, wi0 + 1, words); + if (use_funnel) { + if (job.halves == 8u) tf_exl3_decode_funnel(wx, table, nullptr, job.codebook, walk.at, walk.first_bit, 4, w0, w1); + else tf_exl3_decode_funnel(wx, table, nullptr, job.codebook, walk.at, walk.first_bit, job.halves >> 1, w0, w1); + } else { + const uint w2 = tf_exl3_block_word(job.trellis, job.tile_k_stride, job.tile_n_stride, 0, nb, hg, h, wi0 + 2, words); + const uint w3 = tf_exl3_block_word(job.trellis, job.tile_k_stride, job.tile_n_stride, 0, nb, hg, h, wi0 + 3, words); + if (UseTable) tf_exl3_decode_table(wx, table, job.codebook, walk.at, walk.off, walk.sh, walk.rel, w0, w1, w2, w3); + else tf_exl3_decode_fast(wx, job.codebook, walk.at, walk.off, walk.sh, walk.rel, w0, w1, w2, w3); + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + uint cur_buf = 0; + for (uint kb = 0; kb < a.k; kb += 16) { + const uint nkb = kb + 16; + // Issue the next block's stream loads before the multiply, so their latency overlaps the tensor work. + uint nw0 = 0, nw1 = 0, nw2 = 0, nw3 = 0; + if (nkb < a.k and decodes and DoDecode) { + nw0 = tf_exl3_block_word(job.trellis, job.tile_k_stride, job.tile_n_stride, nkb, nb, hg, h, wi0, words); + nw1 = tf_exl3_block_word(job.trellis, job.tile_k_stride, job.tile_n_stride, nkb, nb, hg, h, wi0 + 1, words); + if (!use_funnel) { + nw2 = tf_exl3_block_word(job.trellis, job.tile_k_stride, job.tile_n_stride, nkb, nb, hg, h, wi0 + 2, words); + nw3 = tf_exl3_block_word(job.trellis, job.tile_k_stride, job.tile_n_stride, nkb, nb, hg, h, wi0 + 3, words); + } + } + frag av[Rpg]; + TF_UNROLL + for (uint r = 0; r < Rpg; ++r) + tf_frag_get_dev4(av[r], (const device half*)x, int(a.k), int(rb + (sgr + r) * 16), int(kb), home, int(rb + job.rows_here)); + if (Mmas > 0) { + threadgroup half* cur = wx + cur_buf * (16u * 64u * CG); + frag b0, b1; + const int wc = int(sgc * 64u); + tf_frag_get_tg4(b0, cur, int(64u * CG), 0, wc, home); + tf_frag_get_tg4(b1, cur, int(64u * CG), 0, wc + 16, home); + TF_UNROLL + for (uint r = 0; r < Rpg; ++r) mma_16x32(lo0[r], hi0[r], av[r], b0, b1); + if (Mmas > 1) { + tf_frag_get_tg4(b0, cur, int(64u * CG), 0, wc + 32, home); + tf_frag_get_tg4(b1, cur, int(64u * CG), 0, wc + 48, home); + TF_UNROLL + for (uint r = 0; r < Rpg; ++r) mma_16x32(lo1[r], hi1[r], av[r], b0, b1); + } + } + if (nkb < a.k and decodes and DoDecode) { + threadgroup half* nxt = wx + (cur_buf ^ 1u) * (16u * 64u * CG); + if (use_funnel) { + if (job.halves == 8u) tf_exl3_decode_funnel(nxt, table, nullptr, job.codebook, walk.at, walk.first_bit, 4, nw0, nw1); + else tf_exl3_decode_funnel(nxt, table, nullptr, job.codebook, walk.at, walk.first_bit, job.halves >> 1, nw0, nw1); + } else if (UseTable) tf_exl3_decode_table(nxt, table, job.codebook, walk.at, walk.off, walk.sh, walk.rel, nw0, nw1, nw2, nw3); + else tf_exl3_decode_fast(nxt, job.codebook, walk.at, walk.off, walk.sh, walk.rel, nw0, nw1, nw2, nw3); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (DoDecode) cur_buf ^= 1u; + } + const int c0 = int(nb + sgc * 64u); + TF_UNROLL + for (uint r = 0; r < Rpg; ++r) { + const int r0 = int(rb + (sgr + r) * 16); + frag_put_in(lo0[r], sums, int(a.n), r0, c0, home, int(rb + job.rows_here), int(nb + job.cols_here)); + frag_put_in(hi0[r], sums, int(a.n), r0, c0 + 16, home, int(rb + job.rows_here), int(nb + job.cols_here)); + frag_put_in(lo1[r], sums, int(a.n), r0, c0 + 32, home, int(rb + job.rows_here), int(nb + job.cols_here)); + frag_put_in(hi1[r], sums, int(a.n), r0, c0 + 48, home, int(rb + job.rows_here), int(nb + job.cols_here)); + } + if (Mmas == 0 and tid < 256u) { + // Keep every decoded store live: read the states this thread wrote, not just the first. + float acc = 0; + TF_UNROLL + for (uint k = 0; k < states; ++k) acc += float(wx[cur_buf * (16u * 64u * CG) + walk.at[k]]); + sums[tid] = acc; + } +} diff --git a/zig/kernels/metal/core/exl3_projection_nax_prefill_ku.metal b/zig/kernels/metal/core/exl3_projection_nax_prefill_ku.metal new file mode 100644 index 00000000000..add271b1832 --- /dev/null +++ b/zig/kernels/metal/core/exl3_projection_nax_prefill_ku.metal @@ -0,0 +1,120 @@ +// KU k blocks a barrier pair: the next group decodes while this one multiplies; accumulation order is unchanged. +constexpr constant uint TF_KU = 2; +template +inline void tf_exl3_prefill_body_ku(threadgroup half* wx, const device half* x, const device uchar* trellis, + device float* sums, constant TfExl3Args& a, const device uint* routes, + const device TfExl3Expert* descriptors, uint lane, uint sg, uint tid, + uint tptg, uint3 tg) { + const uint trows = RG * 16u; + const uint rb = tg.y * trows, nb = tg.x * (64u * CG); + if (a.indexed == 1 || rb >= a.rows) return; + const uint tile_expert = a.indexed ? routes[rb] : a.expert_id; + if (a.indexed && tile_expert >= a.experts) return; + const TfExl3DigJob job = tf_exl3_dig_job(trellis, a, routes, descriptors, rb, nb, trows); + constexpr uint slab = 16u * 64u * CG; + const short2 home = frag_home(ushort(lane)); + constexpr uint wpg = RG / (4u * Rpg); + constexpr uint states = 8u / wpg; + const uint gwarp = tid / 32u, group = gwarp / wpg, wg = gwarp % wpg; + const uint h = group % 4u, hg = (group / 4u) * 64u; + const uint p0 = (wg * 32u + tid % 32u) * states; + const bool decodes = group < 4u * CG and nb + hg + h * 16u < a.n; + const TfExl3DigWindows walk = tf_exl3_dig_windows(p0, 6u, hg, h, false); + const uint words = walk.words; + const uint wi0 = walk.first_word; + const uint sgr = Rpg * (sg % (RG / Rpg)), sgc = sg / (RG / Rpg); + // The routed tile's padded rows need no multiply. + uint real_mask = (1u << Rpg) - 1u; + if (SkipPad and a.indexed != 0) { + real_mask = 0u; + if (lane < 16u * Rpg) { + const uint grow = rb + (sgr + lane / 16u) * 16u + (lane % 16u); + if (grow < a.rows and routes[grow] != 0xffffffffu) real_mask = 1u << (lane / 16u); + } + } + bool group_live[Rpg]; + bool any_live = false; + TF_UNROLL + for (uint r = 0; r < Rpg; ++r) { + group_live[r] = simd_any((real_mask & (1u << r)) != 0u); + any_live = any_live or group_live[r]; + } + frag lo0[Rpg], hi0[Rpg], lo1[Rpg], hi1[Rpg]; + TF_UNROLL + for (uint r = 0; r < Rpg; ++r) { + lo0[r] = frag(0); + hi0[r] = frag(0); + lo1[r] = frag(0); + hi1[r] = frag(0); + } + // Prologue: the first KU blocks into buffer 0. + if (decodes) { + TF_UNROLL + for (uint s = 0; s < KU; ++s) { + const uint w0 = tf_exl3_block_word(job.trellis, job.tile_k_stride, job.tile_n_stride, 16u * s, nb, hg, h, wi0, words); + const uint w1 = tf_exl3_block_word(job.trellis, job.tile_k_stride, job.tile_n_stride, 16u * s, nb, hg, h, wi0 + 1, words); + tf_exl3_decode_funnel(wx + s * slab, nullptr, nullptr, job.codebook, walk.at, walk.first_bit, 3, w0, w1); + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + uint cur_buf = 0; + for (uint kb = 0; kb < a.k; kb += 16u * KU) { + const uint nkb = kb + 16u * KU; + // The next group's stream words are issued before the multiply, so their latency hides behind the tensor work. + uint nw0[KU], nw1[KU]; + if (nkb < a.k and decodes) { + TF_UNROLL + for (uint s = 0; s < KU; ++s) { + nw0[s] = tf_exl3_block_word(job.trellis, job.tile_k_stride, job.tile_n_stride, nkb + 16u * s, nb, hg, h, wi0, words); + nw1[s] = tf_exl3_block_word(job.trellis, job.tile_k_stride, job.tile_n_stride, nkb + 16u * s, nb, hg, h, wi0 + 1, words); + } + } + if (any_live) { + frag av[KU][Rpg]; + TF_UNROLL + for (uint s = 0; s < KU; ++s) { + TF_UNROLL + for (uint r = 0; r < Rpg; ++r) { + if (group_live[r]) tf_frag_get_dev4(av[s][r], (const device half*)x, int(a.k), int(rb + (sgr + r) * 16), int(kb + 16u * s), home, int(rb + job.rows_here)); + } + } + const int wc = int(sgc * 64u); + TF_UNROLL + for (uint s = 0; s < KU; ++s) { + const threadgroup half* cur = wx + (cur_buf * KU + s) * slab; + frag b0, b1; + tf_frag_get_tg4(b0, cur, int(64u * CG), 0, wc, home); + tf_frag_get_tg4(b1, cur, int(64u * CG), 0, wc + 16, home); + TF_UNROLL + for (uint r = 0; r < Rpg; ++r) { + if (group_live[r]) mma_16x32(lo0[r], hi0[r], av[s][r], b0, b1); + } + tf_frag_get_tg4(b0, cur, int(64u * CG), 0, wc + 32, home); + tf_frag_get_tg4(b1, cur, int(64u * CG), 0, wc + 48, home); + TF_UNROLL + for (uint r = 0; r < Rpg; ++r) { + if (group_live[r]) mma_16x32(lo1[r], hi1[r], av[s][r], b0, b1); + } + } + } + if (nkb < a.k and decodes) { + threadgroup half* nxt = wx + (cur_buf ^ 1u) * KU * slab; + TF_UNROLL + for (uint s = 0; s < KU; ++s) + tf_exl3_decode_funnel(nxt + s * slab, nullptr, nullptr, job.codebook, walk.at, walk.first_bit, 3, nw0[s], nw1[s]); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + cur_buf ^= 1u; + } + const int r0 = int(rb + sgr * 16); + const int c0 = int(nb + sgc * 64u); + TF_UNROLL + for (uint r = 0; r < Rpg; ++r) { + if (group_live[r]) { + frag_put_in(lo0[r], sums, int(a.n), r0 + int(r * 16), c0, home, int(rb + job.rows_here), int(nb + job.cols_here)); + frag_put_in(hi0[r], sums, int(a.n), r0 + int(r * 16), c0 + 16, home, int(rb + job.rows_here), int(nb + job.cols_here)); + frag_put_in(lo1[r], sums, int(a.n), r0 + int(r * 16), c0 + 32, home, int(rb + job.rows_here), int(nb + job.cols_here)); + frag_put_in(hi1[r], sums, int(a.n), r0 + int(r * 16), c0 + 48, home, int(rb + job.rows_here), int(nb + job.cols_here)); + } + } +} diff --git a/zig/kernels/metal/core/exl3_projection_nax_variants_a.metal b/zig/kernels/metal/core/exl3_projection_nax_variants_a.metal new file mode 100644 index 00000000000..08097377938 --- /dev/null +++ b/zig/kernels/metal/core/exl3_projection_nax_variants_a.metal @@ -0,0 +1,76 @@ +kernel void tf_exl3_matmul_prefill_nax3(const device half* x [[buffer(0)]], + const device uchar* trellis [[buffer(1)]], + device float* sums [[buffer(2)]], + constant TfExl3Args& a [[buffer(3)]], + const device uint* routes [[buffer(4)]], + const device TfExl3Expert* descriptors [[buffer(5)]], + uint lane [[thread_index_in_simdgroup]], + uint sg [[simdgroup_index_in_threadgroup]], + uint tid [[thread_index_in_threadgroup]], + uint3 tptg [[threads_per_threadgroup]], + uint3 tg [[threadgroup_position_in_grid]]) { + threadgroup half wx[16 * 128]; + tf_exl3_prefill_body(wx, x, trellis, sums, a, routes, descriptors, nullptr, nullptr, lane, sg, tid, tptg.x, tg); +} + +kernel void tf_exl3_matmul_prefill_nax4(const device half* x [[buffer(0)]], + const device uchar* trellis [[buffer(1)]], + device float* sums [[buffer(2)]], + constant TfExl3Args& a [[buffer(3)]], + const device uint* routes [[buffer(4)]], + const device TfExl3Expert* descriptors [[buffer(5)]], + uint lane [[thread_index_in_simdgroup]], + uint sg [[simdgroup_index_in_threadgroup]], + uint tid [[thread_index_in_threadgroup]], + uint3 tptg [[threads_per_threadgroup]], + uint3 tg [[threadgroup_position_in_grid]]) { + threadgroup half wx[16 * 128]; + tf_exl3_prefill_body(wx, x, trellis, sums, a, routes, descriptors, nullptr, nullptr, lane, sg, tid, tptg.x, tg); +} + +kernel void tf_exl3_matmul_prefill_nax5(const device half* x [[buffer(0)]], + const device uchar* trellis [[buffer(1)]], + device float* sums [[buffer(2)]], + constant TfExl3Args& a [[buffer(3)]], + const device uint* routes [[buffer(4)]], + const device TfExl3Expert* descriptors [[buffer(5)]], + uint lane [[thread_index_in_simdgroup]], + uint sg [[simdgroup_index_in_threadgroup]], + uint tid [[thread_index_in_threadgroup]], + uint3 tptg [[threads_per_threadgroup]], + uint3 tg [[threadgroup_position_in_grid]]) { + threadgroup half wx[16 * 64]; + tf_exl3_prefill_body(wx, x, trellis, sums, a, routes, descriptors, nullptr, nullptr, lane, sg, tid, tptg.x, tg); +} + + +// The engine's routed 64 x 64 prompt tile with the funnel read. +kernel void tf_exl3_matmul_prefill_nax42(const device half* x [[buffer(0)]], + const device uchar* trellis [[buffer(1)]], + device float* sums [[buffer(2)]], + constant TfExl3Args& a [[buffer(3)]], + const device uint* routes [[buffer(4)]], + const device TfExl3Expert* descriptors [[buffer(5)]], + uint lane [[thread_index_in_simdgroup]], + uint sg [[simdgroup_index_in_threadgroup]], + uint tid [[thread_index_in_threadgroup]], + uint3 tptg [[threads_per_threadgroup]], + uint3 tg [[threadgroup_position_in_grid]]) { + threadgroup half wx[16 * 64]; + tf_exl3_prefill_body(wx, x, trellis, sums, a, routes, descriptors, nullptr, nullptr, lane, sg, tid, tptg.x, tg); +} + +kernel void tf_exl3_matmul_prefill_nax48(const device half* x [[buffer(0)]], + const device uchar* trellis [[buffer(1)]], + device float* sums [[buffer(2)]], + constant TfExl3Args& a [[buffer(3)]], + const device uint* routes [[buffer(4)]], + const device TfExl3Expert* descriptors [[buffer(5)]], + uint lane [[thread_index_in_simdgroup]], + uint sg [[simdgroup_index_in_threadgroup]], + uint tid [[thread_index_in_threadgroup]], + uint3 tptg [[threads_per_threadgroup]], + uint3 tg [[threadgroup_position_in_grid]]) { + threadgroup half wx[16 * 64]; + tf_exl3_prefill_body(wx, x, trellis, sums, a, routes, descriptors, nullptr, nullptr, lane, sg, tid, tptg.x, tg); +} diff --git a/zig/kernels/metal/core/exl3_projection_nax_variants_b.metal b/zig/kernels/metal/core/exl3_projection_nax_variants_b.metal new file mode 100644 index 00000000000..64bf2dc7965 --- /dev/null +++ b/zig/kernels/metal/core/exl3_projection_nax_variants_b.metal @@ -0,0 +1,76 @@ +// The routed 64x64 prompt tile with the funnel path as the only path. +kernel void tf_exl3_matmul_prefill_nax59(const device half* x [[buffer(0)]], + const device uchar* trellis [[buffer(1)]], + device float* sums [[buffer(2)]], + constant TfExl3Args& a [[buffer(3)]], + const device uint* routes [[buffer(4)]], + const device TfExl3Expert* descriptors [[buffer(5)]], + uint lane [[thread_index_in_simdgroup]], + uint sg [[simdgroup_index_in_threadgroup]], + uint tid [[thread_index_in_threadgroup]], + uint3 tptg [[threads_per_threadgroup]], + uint3 tg [[threadgroup_position_in_grid]]) { + threadgroup half wx[2 * TF_KU * 16 * 64]; + // The funnel path is the one the routed pack's width (halves = 6) takes; the expert's own descriptor says so. + const uint rb = tg.y * 64u; + uint e = 0u; + if (a.indexed != 1u and rb < a.rows) e = routes[rb]; + if (a.experts != 0u and e >= a.experts) e = 0u; + const uint halves = (a.indexed != 0u) ? descriptors[e].halves : a.halves; + if (halves == 6u and a.k % (16u * TF_KU) == 0u) { + tf_exl3_prefill_body_ku<4, 1, TF_KU, 1, true>(wx, x, trellis, sums, a, routes, descriptors, lane, sg, tid, tptg.x, tg); + } else if (halves == 6u) { + tf_exl3_prefill_body(wx, x, trellis, sums, a, routes, descriptors, nullptr, nullptr, lane, sg, tid, tptg.x, tg); + } else { + tf_exl3_prefill_body(wx, x, trellis, sums, a, routes, descriptors, nullptr, nullptr, lane, sg, tid, tptg.x, tg); + } +} + +// The routed 128-row tile (eight row groups, eight warps): twice the rows a tile, so half the per-tile weight decodes. +kernel void tf_exl3_matmul_prefill_nax49(const device half* x [[buffer(0)]], + const device uchar* trellis [[buffer(1)]], + device float* sums [[buffer(2)]], + constant TfExl3Args& a [[buffer(3)]], + const device uint* routes [[buffer(4)]], + const device TfExl3Expert* descriptors [[buffer(5)]], + uint lane [[thread_index_in_simdgroup]], + uint sg [[simdgroup_index_in_threadgroup]], + uint tid [[thread_index_in_threadgroup]], + uint3 tptg [[threads_per_threadgroup]], + uint3 tg [[threadgroup_position_in_grid]]) { + threadgroup half wx[16 * 64]; + tf_exl3_prefill_body(wx, x, trellis, sums, a, routes, descriptors, nullptr, nullptr, lane, sg, tid, tptg.x, tg); +} + +// The routed 128-row tile with a warp doing thirty-two rows: one warp decodes the block and a lane keeps eight states. +kernel void tf_exl3_matmul_prefill_nax54(const device half* x [[buffer(0)]], + const device uchar* trellis [[buffer(1)]], + device float* sums [[buffer(2)]], + constant TfExl3Args& a [[buffer(3)]], + const device uint* routes [[buffer(4)]], + const device TfExl3Expert* descriptors [[buffer(5)]], + uint lane [[thread_index_in_simdgroup]], + uint sg [[simdgroup_index_in_threadgroup]], + uint tid [[thread_index_in_threadgroup]], + uint3 tptg [[threads_per_threadgroup]], + uint3 tg [[threadgroup_position_in_grid]]) { + threadgroup half wx[16 * 64]; + tf_exl3_prefill_body(wx, x, trellis, sums, a, routes, descriptors, nullptr, nullptr, lane, sg, tid, tptg.x, tg); +} + + +// Sixteen row groups by one column group, every warp decoding: a long chunk's expert tile. +kernel void tf_exl3_matmul_prefill_nax6(const device half* const x [[buffer(0)]], + const device uchar* const trellis [[buffer(1)]], + device float* const sums [[buffer(2)]], + constant TfExl3Args& a [[buffer(3)]], + const device uint* const routes [[buffer(4)]], + const device TfExl3Expert* const descriptors [[buffer(5)]], + uint lane [[thread_index_in_simdgroup]], + uint sg [[simdgroup_index_in_threadgroup]], + uint tid [[thread_index_in_threadgroup]], + uint3 tptg [[threads_per_threadgroup]], + uint3 tg [[threadgroup_position_in_grid]]) { + threadgroup half wx[16 * 64]; + tf_exl3_prefill_body(wx, x, trellis, sums, a, routes, descriptors, nullptr, nullptr, lane, sg, tid, tptg.x, tg); +} diff --git a/zig/kernels/metal/core/exl3_projection_nax_variants_c.metal b/zig/kernels/metal/core/exl3_projection_nax_variants_c.metal new file mode 100644 index 00000000000..29150baed03 --- /dev/null +++ b/zig/kernels/metal/core/exl3_projection_nax_variants_c.metal @@ -0,0 +1,32 @@ +kernel void tf_exl3_matmul_prefill_nax31(const device half* const x [[buffer(0)]], + const device uchar* const trellis [[buffer(1)]], + device float* const sums [[buffer(2)]], + constant TfExl3Args& a [[buffer(3)]], + const device uint* const routes [[buffer(4)]], + const device TfExl3Expert* const descriptors [[buffer(5)]], + uint lane [[thread_index_in_simdgroup]], + uint sg [[simdgroup_index_in_threadgroup]], + uint tid [[thread_index_in_threadgroup]], + uint3 tptg [[threads_per_threadgroup]], + uint3 tg [[threadgroup_position_in_grid]]) { + threadgroup half wx[2 * TF_KU * 16 * 64]; + if (a.halves == 6u and a.k % (16u * TF_KU) == 0u) { + tf_exl3_prefill_body_ku<8, 1, TF_KU, 1, false>(wx, x, trellis, sums, a, routes, descriptors, lane, sg, tid, tptg.x, tg); + } else { + tf_exl3_prefill_body_db<8, 1, true, 4, false>(wx, x, trellis, sums, a, routes, descriptors, nullptr, lane, sg, tid, tptg.x, tg); + } +} + +// The register-only decode on our map: one threadgroup a sixteen-column tile, one k walk, no split-K or reduce. +#ifndef TF_FMA_WARPS +#define TF_FMA_WARPS 1 +#endif + +// THE TWO-WORD FUNNEL AT halves = 6 IN THE STATIC BODY: every lane run fits two words, so the third is dead. +#ifndef TF_FMA_TWO +#define TF_FMA_TWO 0 +#endif +// THE VALUE PATH'S FORM: the arithmetic decoder and the LUT hold the same values, so the choice is pure cost. +#ifndef TF_FMA_VALUE_ARITH +#define TF_FMA_VALUE_ARITH 0 +#endif diff --git a/zig/kernels/metal/core/exl3_projection_wide.metal b/zig/kernels/metal/core/exl3_projection_wide.metal new file mode 100644 index 00000000000..79ac033898f --- /dev/null +++ b/zig/kernels/metal/core/exl3_projection_wide.metal @@ -0,0 +1,395 @@ +inline float tf_exl3_bf(ushort x) { return as_type(uint(x) << 16); } +inline ushort tf_exl3_round_bf16(float x) { + uint u = as_type(x); + if ((u & 0x7fffffffu) > 0x7f800000u) return ushort((u >> 16) | 0x40u); + return ushort((u + 0x7fffu + ((u >> 16) & 1u)) >> 16); +} +struct TfExl3SwiGLURot { uint rows, k, input_stride, output_stride, weighted, scatter, experts, reserved; }; +kernel void tf_exl3_swiglu_prerotate(const device ushort* gate [[buffer(0)]], + const device ushort* up [[buffer(1)]], + const device float* weights [[buffer(2)]], + const device uint* routes [[buffer(3)]], + const device uint* destinations [[buffer(4)]], + const device TfExl3Expert* descriptors [[buffer(5)]], + device half* rotated [[buffer(6)]], + constant TfExl3SwiGLURot& d [[buffer(7)]], + uint lane [[thread_index_in_simdgroup]], + uint sg [[simdgroup_index_in_threadgroup]], + uint3 tptg [[threads_per_threadgroup]], + uint3 tg [[threadgroup_position_in_grid]]) { + const uint row = tg.y; + if (row >= d.rows) return; + const uint expert = routes[row]; + if (expert >= d.experts) return; + const uint base = (tg.x * (tptg.x / 32u) + sg) * 128u; + if (base >= d.k) return; + const device ushort* scales = descriptors[expert].su; + const uint signs = descriptors[expert].su_signs; + const float weight = d.weighted ? weights[row] : 1.0f; + float v[4]; + for (uint j = 0; j < 4; ++j) { + const uint k = base + lane + 32u * j; + const ulong at = ulong(row) * d.input_stride + k; + const float g = min(tf_exl3_bf(gate[at]), 10.0f); + const float u = clamp(tf_exl3_bf(up[at]), -10.0f, 10.0f); + float s = (g / (1.0f + exp(-g))) * u; + if (d.weighted) s = weight * s; + v[j] = tf_exl3_bf(tf_exl3_round_bf16(s)) * tf_exl3_scale(scales, k, signs); + } + tf_exl3_hadamard(v, lane); + const uint dst = d.scatter ? destinations[row] : row; + for (uint j = 0; j < 4; ++j) + rotated[ulong(dst) * d.output_stride + base + lane + 32u * j] = half(v[j] * 0.08838834764831845f); +} + +// The gate+up call's rotate_out and the SwiGLU-plus-rotate in one pass, over the call's f32 sums. +struct TfExl3GateUpRot { uint rows, shared_rows, k, sums_stride, experts, fused_experts, shared_dst, weighted, shared_id; }; +kernel void tf_exl3_gateup_swiglu_prerotate(const device float* sums [[buffer(0)]], + const device uint* fused_ids [[buffer(1)]], + const device float* weights [[buffer(2)]], + device uint* routes [[buffer(3)]], + const device TfExl3Expert* fused [[buffer(4)]], + const device TfExl3Expert* down [[buffer(5)]], + const device TfExl3Expert* shared_down [[buffer(6)]], + device half* rotated [[buffer(7)]], + constant TfExl3GateUpRot& d [[buffer(8)]], + uint lane [[thread_index_in_simdgroup]], + uint sg [[simdgroup_index_in_threadgroup]], + uint3 tptg [[threads_per_threadgroup]], + uint3 tg [[threadgroup_position_in_grid]]) { + const uint row = tg.y; + if (row >= d.rows + d.shared_rows) return; + const bool routed = row < d.rows; + const uint slot = routed ? row : row - d.rows; + // The down call reads the shared rows' table entry from the id row after the routed picks. + if (!routed && lane == 0u && sg == 0u && tg.x == 0u && d.shared_id != 0xffffffffu) routes[row] = d.shared_id; + const uint base = (tg.x * (tptg.x / 32u) + sg) * 128u; + if (base >= d.k) return; + // Gate rows lead the call, up rows follow the routed gate rows; the shared pair sits after both routed halves. + const uint gate_row = routed ? row : 2u * d.rows + slot; + const uint up_row = routed ? d.rows + row : gate_row + d.shared_rows; + const uint expert = routed ? routes[row] : 0u; + if (routed && expert >= d.experts) return; + const uint gate_id = routed ? fused_ids[gate_row] : d.fused_experts - 2u; + const uint up_id = routed ? fused_ids[up_row] : d.fused_experts - 1u; + if (gate_id >= d.fused_experts || up_id >= d.fused_experts) return; + const device ushort* scales = routed ? down[expert].su : shared_down[0].su; + const uint signs = routed ? down[expert].su_signs : shared_down[0].su_signs; + const float weight = (routed && d.weighted) ? weights[row] : 1.0f; + float gv[4], uv[4], v[4]; + for (uint j = 0; j < 4; ++j) { + gv[j] = sums[ulong(gate_row) * d.sums_stride + base + lane + 32u * j]; + uv[j] = sums[ulong(up_row) * d.sums_stride + base + lane + 32u * j]; + } + tf_exl3_hadamard(gv, lane); + tf_exl3_hadamard(uv, lane); + for (uint j = 0; j < 4; ++j) { + const uint n = base + lane + 32u * j; + const float gate_out = tf_exl3_out_value(gv[j], fused[gate_id].sv, fused[gate_id].bias, n, fused[gate_id].sv_signs, fused[gate_id].has_bias); + const float up_out = tf_exl3_out_value(uv[j], fused[up_id].sv, fused[up_id].bias, n, fused[up_id].sv_signs, fused[up_id].has_bias); + const float g = min(tf_exl3_bf(as_type(bfloat(gate_out))), 10.0f); + const float u = clamp(tf_exl3_bf(as_type(bfloat(up_out))), -10.0f, 10.0f); + float s = (g / (1.0f + exp(-g))) * u; + if (routed && d.weighted) s = weight * s; + v[j] = tf_exl3_bf(tf_exl3_round_bf16(s)) * tf_exl3_scale(scales, n, signs); + } + tf_exl3_hadamard(v, lane); + const uint dst = routed ? row : d.shared_dst + slot; + for (uint j = 0; j < 4; ++j) + rotated[ulong(dst) * d.k + base + lane + 32u * j] = half(v[j] * 0.08838834764831845f); +} + +// The down call's rotate_out and the routed-plus-shared combine in one pass: a threadgroup is one token's 128 columns. +struct TfExl3DownCombine { uint rows, picks, width, sums_stride, experts, y_stride, shared_row, reserved; }; +kernel void tf_exl3_down_combine(const device float* sums [[buffer(0)]], + const device uint* ids [[buffer(1)]], + const device TfExl3Expert* down [[buffer(2)]], + device ushort* y [[buffer(3)]], + constant TfExl3DownCombine& d [[buffer(4)]], + uint lane [[thread_index_in_simdgroup]], + uint sg [[simdgroup_index_in_threadgroup]], + uint3 tg [[threadgroup_position_in_grid]]) { + threadgroup uint slots[8]; + threadgroup uint invalid; + threadgroup float values[8][128]; + const uint token = tg.y, base = tg.x * 128u; + const ulong id_row = ulong(token) * d.picks; + // The picks in ascending expert id, ties by slot, as the combine orders them; any id past 383 poisons the row. + if (sg == 0u && lane == 0u) { + invalid = 0u; + for (uint a = 0; a < d.picks; a++) slots[a] = a; + for (uint a = 1; a < d.picks; a++) { + const uint slot = slots[a]; + uint j = a; + while (j > 0 && ids[id_row + slots[j - 1]] > ids[id_row + slot]) { + slots[j] = slots[j - 1]; + j--; + } + slots[j] = slot; + } + for (uint a = 0; a < d.picks; a++) if (ids[id_row + a] >= 384u) invalid = 1u; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (base >= d.width || token >= d.rows) return; + if (invalid != 0u) { + if (sg == 0u) + for (uint j = 0; j < 4; ++j) y[ulong(token) * d.y_stride + base + lane + 32u * j] = tf_exl3_round_bf16(NAN); + return; + } + // Simdgroup r finishes the r-th pick in id order, simdgroup `picks` the shared expert's row. + if (sg <= d.picks) { + const bool shared = sg == d.picks; + const uint slot = shared ? 0u : slots[sg]; + const ulong row = shared ? ulong(d.shared_row) + token : id_row + slot; + const uint id = shared ? d.experts : ids[id_row + slot]; + float v[4]; + for (uint j = 0; j < 4; ++j) v[j] = sums[row * d.sums_stride + base + lane + 32u * j]; + tf_exl3_hadamard(v, lane); + for (uint j = 0; j < 4; ++j) { + const uint n = base + lane + 32u * j; + const float out = tf_exl3_out_value(v[j], down[id].sv, down[id].bias, n, down[id].sv_signs, down[id].has_bias); + values[sg][lane + 32u * j] = tf_exl3_bf(as_type(bfloat(out))); + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (sg != 0u) return; + for (uint j = 0; j < 4; ++j) { + float s = 0; + for (uint rank = 0; rank < d.picks; rank++) s += values[rank][lane + 32u * j]; + s += values[d.picks][lane + 32u * j]; + y[ulong(token) * d.y_stride + base + lane + 32u * j] = tf_exl3_round_bf16(s); + } +} + +// Wide one-row tile: eight SIMDgroups each own a 16-column tile, and the shared activation tile is double buffered. +template +inline void tf_exl3_matmul_wide_impl(const device half* x, const device uchar* trellis, + device float* sums, constant TfExl3Args& a, + const device uint* routes, const device TfExl3Expert* descriptors, + device float* partials, const device half* table, + uint lane, uint sg, uint3 tg, + threadgroup half* wx_all, threadgroup float* xx_all) { + const uint split = a.splits > 1 ? tg.y : 0; + const uint rb = a.splits > 1 ? tg.z * 8 : tg.y * 8, nb = tg.x * 128 + sg * 16; + if (!simd_any(tf_exl3_active(routes, a, rb + lane % 8))) return; + const device uchar* data = trellis; + const ulong ks = a.tile_k_stride; + const ulong ns = a.tile_n_stride; + const uint halves = a.halves; + const uint codebook = a.codebook; + threadgroup half* wx = wx_all + sg * 256; + uint maps[8], at[8], off[8], sh[8], rel[8]; + const uint words = 4 * halves; + const uint ring = 128 * halves; + const uint wi0 = tf_exl3_map_of(lane * 8, halves) & 63u; + const uint cur0 = (wi0 << 5) | ((tf_exl3_map_of(lane * 8, halves) >> 6) & 31u); + TF_UNROLL + for (uint j = 0; j < 8; ++j) { + const uint p = lane * 8 + j, l = p / 8, e = p % 8; + uint c8 = cur0 + j * (halves >> 1); + if (c8 >= ring) c8 -= ring; + off[j] = c8 & 31u; + sh[j] = (32u - off[j]) & 31u; + rel[j] = (c8 >> 5) >= wi0 ? (c8 >> 5) - wi0 : (c8 >> 5) + words - wi0; + at[j] = (2 * (l % 4) + (e & 1u) + 8 * ((e >> 1) & 1u)) * 16u + (l / 4 + 8 * (e >> 2)); + } + { + for (uint j = 0; j < 8; ++j) { + const uint p = lane + 32 * j, ring2 = 128 * halves; + const uint end = ((p + 1) * halves - ((halves & 1u) ? ((p + 1) & 1u) : 0u)) / 2; + uint start = end + ring2 - 16; + if (start >= ring2) start -= ring2; + const uint wi = start >> 5, o = start & 31u, next = wi + 1 == 4 * halves ? 0 : wi + 1; + maps[j] = wi | (o << 6) | (next << 11); + } + } + float high[4] = {0,0,0,0}, low[4] = {0,0,0,0}; + const uint blocks = a.k / 16; + const uint b0 = a.splits > 1 ? blocks * split / a.splits : 0; + const uint b1 = a.splits > 1 ? blocks * (split + 1) / a.splits : blocks; + uint prefetch[4]; + { + uint a1 = wi0 + 1; if (a1 >= words) a1 -= words; + uint a2 = wi0 + 2; if (a2 >= words) a2 -= words; + uint a3 = wi0 + 3; if (a3 >= words) a3 -= words; + const device ushort* t0 = reinterpret_cast(data + ulong(b0) * ks + ulong(nb / 16) * ns); + prefetch[0] = tf_exl3_word(t0, wi0); + prefetch[1] = tf_exl3_word(t0, a1); + prefetch[2] = tf_exl3_word(t0, a2); + prefetch[3] = tf_exl3_word(t0, a3); + } + for (uint b = b0; b < b1; ++b) { + threadgroup float* xx = xx_all + ((b - b0) & 1u) * 128; + // One warp loads the activation tile for all eight: 8 rows x 16 k, zeros past a.rows. + if (sg == 0) { + for (uint j = lane; j < 128; j += 32) { + const uint row = rb + j / 16; + xx[j] = tf_exl3_active(routes, a, row) ? float(x[ulong(row) * a.k + b * 16 + j % 16]) : 0.0f; + } + } + const device ushort* tile = reinterpret_cast( + data + ulong(b) * ks + ulong(nb / 16) * ns); + if ((halves & 1u) == 0 and halves <= 16) { + uint at1 = wi0 + 1; if (at1 >= words) at1 -= words; + uint at2 = wi0 + 2; if (at2 >= words) at2 -= words; + uint at3 = wi0 + 3; if (at3 >= words) at3 -= words; + const uint w0 = prefetch[0], w1 = prefetch[1], w2 = prefetch[2], w3 = prefetch[3]; + if (b + 1 < b1) { + const device ushort* tn = reinterpret_cast(data + ulong(b + 1) * ks + ulong(nb / 16) * ns); + prefetch[0] = tf_exl3_word(tn, wi0); + prefetch[1] = tf_exl3_word(tn, at1); + prefetch[2] = tf_exl3_word(tn, at2); + prefetch[3] = tf_exl3_word(tn, at3); + } + TF_UNROLL + for (uint j = 0; j < 8; ++j) { + const uint lo = rel[j] == 0 ? w0 : rel[j] == 1 ? w1 : w2; + const uint hi = rel[j] == 0 ? w1 : rel[j] == 1 ? w2 : w3; + const uint carry = (hi >> sh[j]) & (0u - uint(off[j] != 0)); + const ushort s = ushort(((lo << off[j]) | carry) >> 16); + wx[at[j]] = Table ? tf_exl3_table_value(table, codebook, s) : tf_exl3_value(s, codebook); + } + } else for (uint j = 0; j < 8; ++j) { + const uint p = lane + 32 * j, l = p / 8, e = p % 8; + const uint r = 2 * (l % 4) + (e & 1u) + 8 * ((e >> 1) & 1u); + const uint c = l / 4 + 8 * (e >> 2); + const ushort state = tf_exl3_mapped_state(tile, maps[j]); + wx[r * 16 + c] = Table ? tf_exl3_table_value(table, codebook, state) : tf_exl3_value(state, codebook); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + for (uint i = 0; i < 4; ++i) { + const uint at_i = lane + 32 * i, row = rb + at_i / 16, col = at_i % 16; + if (!tf_exl3_active(routes, a, row)) continue; + for (uint k = 0; k < 16; ++k) high[i] += xx[(at_i / 16) * 16 + k] * float(wx[k * 16 + col]); + } + // No second barrier: the next block writes the other activation buffer, and this one is read no more. + } + for (uint i = 0; i < 4; ++i) { + const uint at_i = lane + 32 * i, row = rb + at_i / 16; + if (tf_exl3_active(routes, a, row)) { + if (a.splits > 1) partials[(ulong(split) * a.rows + row) * a.n + nb + at_i % 16] = high[i] + low[i]; + else sums[ulong(row) * a.n + nb + at_i % 16] = high[i] + low[i]; + } + } +} + +// The wide one-row body with static state selection: the cursor leaves the inner loop, reading three words not four. +template +inline void tf_exl3_matmul_wide_static_impl(const device half* x, const device uchar* trellis, + device float* sums, constant TfExl3Args& a, + const device uint* routes, const device TfExl3Expert* descriptors, + device float* partials, + uint lane, uint sg, uint3 tg, + threadgroup half* wx_all, threadgroup float* xx_all, + threadgroup half* lut) { + const uint split = a.splits > 1 ? tg.y : 0; + const uint rb = a.splits > 1 ? tg.z * 8 : tg.y * 8, nb = tg.x * 128 + sg * 16; + if (!simd_any(tf_exl3_active(routes, a, rb + lane % 8))) return; + const device uchar* data = trellis; + const ulong ks = a.tile_k_stride; + const ulong ns = a.tile_n_stride; + const uint halves = a.halves; + const uint codebook = a.codebook; + threadgroup half* wx = wx_all + sg * 256; + uint at[8]; + const uint words = 4 * halves; + const uint wi0 = tf_exl3_map_of(lane * 8, halves) & 63u; + const uint off0 = (tf_exl3_map_of(lane * 8, halves) >> 6) & 31u; + TF_UNROLL + for (uint j = 0; j < 8; ++j) { + const uint p = lane * 8 + j, l = p / 8, e = p % 8; + at[j] = (2 * (l % 4) + (e & 1u) + 8 * ((e >> 1) & 1u)) * 16u + (l / 4 + 8 * (e >> 2)); + } + float high[4] = {0,0,0,0}, low[4] = {0,0,0,0}; + const uint blocks = a.k / 16; + const uint b0 = a.splits > 1 ? blocks * split / a.splits : 0; + const uint b1 = a.splits > 1 ? blocks * (split + 1) / a.splits : blocks; + // Three stream words: the lane's window spans at most 7*S + 16 bits from its first state. + uint a1 = wi0 + 1; if (a1 >= words) a1 -= words; + uint a2 = wi0 + 2; if (a2 >= words) a2 -= words; + uint prefetch[3]; + { + const device ushort* t0 = reinterpret_cast(data + ulong(b0) * ks + ulong(nb / 16) * ns); + prefetch[0] = tf_exl3_word(t0, wi0); + prefetch[1] = tf_exl3_word(t0, a1); + prefetch[2] = tf_exl3_word(t0, a2); + } + // The lane's bit offset inside its first word: the one runtime shift of the body. + const uint sh0 = (32u - off0) & 31u; + const uint m0 = 0u - uint(off0 != 0u); + for (uint b = b0; b < b1; ++b) { + threadgroup float* xx = xx_all + ((b - b0) & 1u) * 128; + if (sg == 0) { + for (uint j = lane; j < 128; j += 32) { + const uint row = rb + j / 16; + xx[j] = tf_exl3_active(routes, a, row) ? float(x[ulong(row) * a.k + b * 16 + j % 16]) : 0.0f; + } + } + const uint w0 = prefetch[0], w1 = prefetch[1], w2 = prefetch[2]; + if (b + 1 < b1) { + const device ushort* tn = reinterpret_cast(data + ulong(b + 1) * ks + ulong(nb / 16) * ns); + prefetch[0] = tf_exl3_word(tn, wi0); + prefetch[1] = tf_exl3_word(tn, a1); + prefetch[2] = tf_exl3_word(tn, a2); + } + // The lane's window: C_cur is the 32-bit window at the lane's first state. + const uint c_cur = (w0 << off0) | ((w1 >> sh0) & m0); + const uint c_next = (w1 << off0) | ((w2 >> sh0) & m0); + #define TF_EXL3_W(J) tf_exl3_state_static(c_cur, c_next) + #define TF_EXL3_V(J) lut[tf_exl3_mul1_index(TF_EXL3_W(J))] + wx[at[0]] = TF_EXL3_V(0); + wx[at[1]] = TF_EXL3_V(1); + wx[at[2]] = TF_EXL3_V(2); + wx[at[3]] = TF_EXL3_V(3); + wx[at[4]] = TF_EXL3_V(4); + wx[at[5]] = TF_EXL3_V(5); + wx[at[6]] = TF_EXL3_V(6); + wx[at[7]] = TF_EXL3_V(7); + #undef TF_EXL3_V + #undef TF_EXL3_W + threadgroup_barrier(mem_flags::mem_threadgroup); + for (uint i = 0; i < 4; ++i) { + const uint at_i = lane + 32 * i, row = rb + at_i / 16, col = at_i % 16; + if (!tf_exl3_active(routes, a, row)) continue; + for (uint k = 0; k < 16; ++k) high[i] += xx[(at_i / 16) * 16 + k] * float(wx[k * 16 + col]); + } + } + for (uint i = 0; i < 4; ++i) { + const uint at_i = lane + 32 * i, row = rb + at_i / 16; + if (tf_exl3_active(routes, a, row)) { + if (a.splits > 1) partials[(ulong(split) * a.rows + row) * a.n + nb + at_i % 16] = high[i] + low[i]; + else sums[ulong(row) * a.n + nb + at_i % 16] = high[i] + low[i]; + } + } +} + +kernel void tf_exl3_matmul_wide_static_lut(const device half* x [[buffer(0)]], + const device uchar* trellis [[buffer(1)]], + device float* sums [[buffer(2)]], + constant TfExl3Args& a [[buffer(3)]], + const device uint* routes [[buffer(4)]], + const device TfExl3Expert* descriptors [[buffer(5)]], + device float* partials [[buffer(6)]], + const device half* table [[buffer(7)]], + uint lane [[thread_index_in_simdgroup]], + uint sg [[simdgroup_index_in_threadgroup]], + uint3 tg [[threadgroup_position_in_grid]]) { + threadgroup half wx[8 * 256]; + threadgroup float xx[2 * 128]; + threadgroup half lut[1024]; + // The LUT holds the mul1 values (the value depends only on the state's byte sum). + if (a.codebook != 2u) { + tf_exl3_matmul_wide_impl(x, trellis, sums, a, routes, descriptors, partials, table, lane, sg, tg, wx, xx); + return; + } + for (uint b = sg * 32u + lane; b < 1024u; b += 256u) lut[b] = tf_exl3_mul1_value(b); + threadgroup_barrier(mem_flags::mem_threadgroup); + if (a.halves == 12u) + tf_exl3_matmul_wide_static_impl<6>(x, trellis, sums, a, routes, descriptors, partials, lane, sg, tg, wx, xx, lut); + else if (a.halves == 10u) + tf_exl3_matmul_wide_static_impl<5>(x, trellis, sums, a, routes, descriptors, partials, lane, sg, tg, wx, xx, lut); + else if (a.halves == 6u) + tf_exl3_matmul_wide_static_impl<3>(x, trellis, sums, a, routes, descriptors, partials, lane, sg, tg, wx, xx, lut); + else + tf_exl3_matmul_wide_impl(x, trellis, sums, a, routes, descriptors, partials, table, lane, sg, tg, wx, xx); +} diff --git a/zig/kernels/metal/core/expert_groups.metal b/zig/kernels/metal/core/expert_groups.metal new file mode 100644 index 00000000000..e1b33c3f51b --- /dev/null +++ b/zig/kernels/metal/core/expert_groups.metal @@ -0,0 +1,41 @@ +// Group routed slots into padded expert tiles; scatter preserves original token and output IDs. +#include +using namespace metal; +struct TfExpertGroups { uint rows, experts, repeat, padded, block, tile; }; +#define TF_GROUP_ARGS \ + const device uint* ids [[buffer(0)]], device atomic_uint* counts [[buffer(1)]], \ + device uint* offsets [[buffer(2)]], device uint* ranks [[buffer(3)]], \ + device uint* expert_ids [[buffer(4)]], device uint* token_ids [[buffer(5)]], \ + device uint* slot_ids [[buffer(6)]], device uint* destinations [[buffer(7)]], \ + constant TfExpertGroups& d [[buffer(8)]], uint i [[thread_position_in_grid]] + +kernel void tf_expert_group_clear(TF_GROUP_ARGS) { + if (i < d.experts) atomic_store_explicit(counts + i, 0u, memory_order_relaxed); + if (i < d.padded) expert_ids[i] = 0xffffffffu; +} +kernel void tf_expert_group_count(TF_GROUP_ARGS) { + if (i >= d.rows || ids[i] >= d.experts) return; + ranks[i] = atomic_fetch_add_explicit(counts + ids[i], 1u, memory_order_relaxed); +} +kernel void tf_expert_group_prefix(TF_GROUP_ARGS) { + if (i != 0) return; + uint offset = 0; + // Each expert's block is padded to a multiple of the tile's rows. + const uint tile = d.tile == 0u ? 64u : d.tile; + for (uint expert = 0; expert < d.experts; ++expert) { + offsets[expert] = offset; + const uint count = atomic_load_explicit(counts + expert, memory_order_relaxed); + offset += (count + tile - 1u) & ~(tile - 1u); + } +} +kernel void tf_expert_group_scatter(TF_GROUP_ARGS) { + if (i >= d.rows || ids[i] >= d.experts) return; + const uint destination = offsets[ids[i]] + ranks[i]; + if (destination >= d.padded) return; + expert_ids[destination] = ids[i]; + // A fused gate+up table is two blocks of `repeat` slots a token. + token_ids[destination] = d.block == 0 ? i / d.repeat : (i % d.block) / d.repeat; + slot_ids[destination] = i; + // The inverse map, token-major slot to expert-tile destination. + destinations[i] = destination; +} diff --git a/zig/kernels/metal/deepseek_v41/cand.metal b/zig/kernels/metal/deepseek_v41/cand.metal index a6998170748..d4dc762030a 100644 --- a/zig/kernels/metal/deepseek_v41/cand.metal +++ b/zig/kernels/metal/deepseek_v41/cand.metal @@ -15,6 +15,7 @@ struct TfCandArgs { uint blocks; // the row stride of the keyed scratch and of the mask uint topk; // blocks kept, at most 2048 }; +static_assert(sizeof(TfCandArgs) == 12, "TfCandArgs must mirror metal/cand.zig's Args"); // Order-preserving key of a float's bits: NaN as -inf (control 1: +inf), -0 as +0. inline uint tf_cand_key(uint u) { diff --git a/zig/kernels/metal/deepseek_v41/compress.metal b/zig/kernels/metal/deepseek_v41/compress.metal index 93efaaf4557..cc9b6cad42b 100644 --- a/zig/kernels/metal/deepseek_v41/compress.metal +++ b/zig/kernels/metal/deepseek_v41/compress.metal @@ -47,6 +47,7 @@ inline float tf_c_e2m1v(uint c) { struct TfCPoolArgs { uint rows, dim; }; +static_assert(sizeof(TfCPoolArgs) == 8, "TfCPoolArgs must mirror metal/compress.zig's PoolArgs"); // Compressor ratio 2 (model.py:429-487): a column a thread, rows in order; odd positions pool the two slots. inline void tf_c_pool2_col(const device float* KV, const device float* SC, device float* ST, const device int* P, @@ -83,6 +84,7 @@ inline void tf_c_pool2_col(const device float* KV, const device float* SC, devic struct TfCRtArgs { uint blocks, in_stride, out_row; }; +static_assert(sizeof(TfCRtArgs) == 12, "TfCRtArgs must mirror metal/compress.zig's RtArgs"); // The compressed KV's fp4_act_quant round trip (kernel.py:184), 16-value blocks, E4M3 scales, to row D[r] (< 0 skips). inline void tf_c_fp4rt_block(const device bfloat* X, device bfloat* Y, const device int* D, constant TfCRtArgs& a, @@ -118,6 +120,7 @@ inline void tf_c_fp4rt_block(const device bfloat* X, device bfloat* Y, const dev struct TfCPackArgs { uint blocks, in_stride, code_row, scale_row, scale_off, use_dest; }; +static_assert(sizeof(TfCPackArgs) == 24, "TfCPackArgs must mirror metal/compress.zig's PackArgs"); // Index keys and queries, fp4_act_quant: 32-value blocks, E8M0 scales, E2M1 nibbles, to row D[r] (< 0 skips). inline void tf_c_fp4pack_block(const device bfloat* X, device uchar* C, device uchar* S, const device int* D, @@ -158,6 +161,7 @@ inline uint tf_c_slot(const device int* RS, uint r) { return TF_CTL == 6 ? 0u : struct TfCPoolSegArgs { uint keep, dim; // rows a slot's kept inputs hold (its score half starts keep rows on), columns }; +static_assert(sizeof(TfCPoolSegArgs) == 8, "TfCPoolSegArgs must mirror metal/compress.zig's PoolSegArgs"); // tf_dsv41_c_pool2 over several slots, slot g.y over its rows and carry; its kv and score rows kept in its inputs. [[kernel, max_total_threads_per_threadgroup(32)]] void tf_dsv41_c_pool2_segs( diff --git a/zig/kernels/metal/deepseek_v41/csa2.metal b/zig/kernels/metal/deepseek_v41/csa2.metal new file mode 100644 index 00000000000..8526bb2a86a --- /dev/null +++ b/zig/kernels/metal/deepseek_v41/csa2.metal @@ -0,0 +1,105 @@ +// Source is compiled after kv.metal, which provides exact packed-cache decoders. +struct Dsv41Attention { + uint rows, heads, width, q_stride, position, chunk_rows, window, ring_stride; + uint chunk_stride, main_stride, main_block, ratio, compressed_rows, topk, index_stride; + float scale; + uint splits; // 1 unless a decode layer's key scan is split across threadgroups + uint chunk_all; // Every row sits at p.position and sees every chunk row (the drafter's form) +}; +static_assert(sizeof(Dsv41Attention) == 72, "Dsv41Attention must mirror csa2.zig's Params"); +// BF16 query/key products are exact in FP32; compensate accumulation and lane reduction. +inline void dsv41_dot_add(thread float &sum, thread float &error, float value) { + float next = sum + value; + float recovered = next - sum; + error += (sum - (next - recovered)) + (value - recovered); + sum = next; +} +inline float dsv41_dot_reduce(float sum, float error) { + for (uint offset = 16; offset != 0; offset >>= 1) { + float other = simd_shuffle_xor(sum, offset); + float other_error = simd_shuffle_xor(error, offset); + dsv41_dot_add(sum, error, other); + dsv41_dot_add(sum, error, other_error); + } + return sum + error; +} +// BF16 probability rounding uses fixed query-based tiles, never a chunk-dependent physical key layout. +inline uint dsv41_window_columns(constant Dsv41Attention &p, uint row) { + return (p.chunk_all ? p.position : p.position + row) == 0 ? 1 : p.window; +} +inline device const uchar *dsv41_attn_key(uint slot, uint row, device const uchar *ring, + device const uchar *chunk, device const uchar *main, device const int *indices, + constant Dsv41Attention &p, thread uint &kind) { + uint query = p.chunk_all ? p.position : p.position + row; + uint columns = dsv41_window_columns(p, row); + if (slot < columns) { + uint pos; + if (query == 0) { + pos = 0; + } else if (query + 1 < p.window) { + pos = (query + 1 + slot) % p.window; + } else { + uint begin = query + 1 > p.window ? query + 1 - p.window : 0; + pos = begin + slot; + } + if (!p.chunk_all && pos > query) return nullptr; + kind = 0; + return pos >= p.position ? chunk + (pos - p.position) * p.chunk_stride + : ring + (pos % p.window) * p.ring_stride; + } + if (!p.ratio) return nullptr; + int pos = indices[row * p.index_stride + slot - columns]; + if (pos < 0 || uint(pos) >= min(p.compressed_rows, (query + 1) / p.ratio)) return nullptr; + kind = 1; + return main + uint(pos) * p.main_stride; +} +kernel void dsv41_sparse_attention(device const ushort *q [[buffer(0)]], device const uchar *ring [[buffer(1)]], + device const uchar *chunk [[buffer(2)]], device const uchar *main [[buffer(3)]], + device const int *indices [[buffer(4)]], device const float *sink [[buffer(5)]], + device ushort *out [[buffer(6)]], constant Dsv41Attention &p [[buffer(7)]], + uint2 g [[threadgroup_position_in_grid]], uint lane [[thread_index_in_threadgroup]]) { + uint head = g.x, row = g.y; + if (head >= p.heads || row >= p.rows) return; + threadgroup float scores[64]; + float query[16], acc[16]; + for (uint j = 0; j < p.width / 32; ++j) { + query[j] = dsv41_bf(q[row * p.q_stride + head * p.width + lane + j * 32]); acc[j] = 0; + } + float mx = -1e30f, sum = 0; + uint query_position = p.chunk_all ? p.position : p.position + row; + uint compressed_columns = p.ratio ? min(p.topk, min(p.compressed_rows, (query_position + 1) / p.ratio)) : 0; + uint count = dsv41_window_columns(p, row) + compressed_columns; + for (uint base = 0; base < count; base += 64) { + float next_max = mx; + for (uint j = 0; j < 64; ++j) { + uint kind = 0; + device const uchar *key = base + j < count ? dsv41_attn_key(base + j, row, ring, chunk, main, indices, p, kind) : nullptr; + float dot = 0, dot_error = 0; + if (key) for (uint d = 0; d < p.width / 32; ++d) + dsv41_dot_add(dot, dot_error, query[d] * dsv41_unpack(key, lane + d * 32, p.width, kind ? p.main_block : 32, kind)); + dot = key ? dsv41_dot_reduce(dot, dot_error) * p.scale : -INFINITY; + next_max = max(next_max, dot); + if (lane == 0) scores[j] = dot; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + float correction = exp(mx - next_max); + float tile_sum = 0; + for (uint d = 0; d < p.width / 32; ++d) acc[d] *= correction; + for (uint j = 0; j < 64; ++j) { + float probability = exp(scores[j] - next_max); + tile_sum += probability; + float rounded = dsv41_bf(dsv41_round(probability)); + uint kind = 0; + device const uchar *key = base + j < count ? dsv41_attn_key(base + j, row, ring, chunk, main, indices, p, kind) : nullptr; + if (key) for (uint d = 0; d < p.width / 32; ++d) + acc[d] += rounded * dsv41_unpack(key, lane + d * 32, p.width, kind ? p.main_block : 32, kind); + } + sum = sum * correction + tile_sum; + mx = next_max; + threadgroup_barrier(mem_flags::mem_threadgroup); + } + // The source adds sink mass to the completed online denominator before the FP32 division. + float denom = sum + exp(sink[head] - mx); + for (uint d = 0; d < p.width / 32; ++d) + out[row * p.q_stride + head * p.width + lane + d * 32] = dsv41_round(acc[d] / denom); +} diff --git a/zig/kernels/metal/deepseek_v41/csa2_attn.metal b/zig/kernels/metal/deepseek_v41/csa2_attn.metal index e864455b051..4a20f505efe 100644 --- a/zig/kernels/metal/deepseek_v41/csa2_attn.metal +++ b/zig/kernels/metal/deepseek_v41/csa2_attn.metal @@ -30,6 +30,7 @@ struct TfAttnArgs { float scale; uint pad; }; +static_assert(sizeof(TfAttnArgs) == 16, "TfAttnArgs must mirror metal/csa2_attn.zig's Args"); // A row's record (ints): position, window row base, window base position (-1: ring of 128), cache row base, count. @@ -37,6 +38,7 @@ struct TfAttnArgs { struct TfAttnMeta { int pos, wofs, wbase, cofs, ncomp, rope, p1, p2; }; +static_assert(sizeof(TfAttnMeta) == 32, "TfAttnMeta must mirror metal/csa2_attn.zig's Meta"); // One lane's 16 dims of a key: 32 bytes of bf16. struct TfKey { diff --git a/zig/kernels/metal/deepseek_v41/csa2_nax.metal b/zig/kernels/metal/deepseek_v41/csa2_nax.metal new file mode 100644 index 00000000000..352431d3b17 --- /dev/null +++ b/zig/kernels/metal/deepseek_v41/csa2_nax.metal @@ -0,0 +1,476 @@ +// DSV41's prompt sparse attention on the tensor units: GLM's fragment structure over the packed cache. +#include "../nax.h" +using namespace tfp; + +#ifndef DSV41_HEADS +#define DSV41_HEADS 64 +#endif +constant constexpr int HEADS = DSV41_HEADS, RANK = 512, GROUP = 16, BLOCK = 32, SLICE = RANK / 4; +constant constexpr float NO_SCORE = -INFINITY; // the scalar kernel's score for a missing key + +// A transposed right operand's element e: the row it comes from (here a key) and its column (a latent dim). +#ifndef TF_SIMD_FRAGS +inline short t_key(short e, short2 home) { return home.y + (e >> 2) * 8; } +inline short t_dim(short e, short2 home) { return home.x + (e & 3); } +#else +inline short t_key(short e, short2 home) { return home.x + TF_COL(e); } +inline short t_dim(short e, short2 home) { return home.y + (e >> 2) * 8; } +#endif +// A plain operand's or an accumulator's element e: its row (a head, or a key for the values) and column. +inline short p_row(short e, short2 home) { return home.y + (e >> 2) * 8; } +inline short p_col(short e, short2 home) { return home.x + (e & 3); } + +// The max (or sum) of a head's values across the four lanes that hold its other keys. +inline float row_max(float v) { + v = max(v, simd_shuffle_xor(v, ushort(1))); + return max(v, simd_shuffle_xor(v, ushort(8))); +} +inline float row_sum(float v) { + v += simd_shuffle_xor(v, ushort(1)); + return v + simd_shuffle_xor(v, ushort(8)); +} + +// The scalar dsv41_attn_key's slot as one int: -1 for no key, bit 30 set with the row index for a compressed one. +inline int dsv41_slot_at(constant Dsv41Attention &p, uint row, uint query, uint columns, uint slot, + device const int *indices) { + if (slot < columns) { + uint pos; + if (query == 0) { + pos = 0; + } else if (query + 1 < p.window) { + pos = (query + 1 + slot) % p.window; + } else { + uint begin = query + 1 > p.window ? query + 1 - p.window : 0; + pos = begin + slot; + } + if (!p.chunk_all && pos > query) return -1; + return int(pos); + } + if (!p.ratio) return -1; + int pos = indices[row * p.index_stride + slot - columns]; + if (pos < 0 || uint(pos) >= min(p.compressed_rows, (query + 1) / p.ratio)) return -1; + return int(0x40000000u | uint(pos)); +} + +// A slot descriptor's packed row and its kind (0: the window's e4 rows, 1: the compressed e2 rows). +inline device const uchar *dsv41_key_ptr(int enc, device const uchar *ring, device const uchar *chunk, + device const uchar *main, constant Dsv41Attention &p, thread uint &kind) { + if (enc & (1 << 30)) { + kind = 1; + return main + uint(enc & 0x3FFFFFFF) * p.main_stride; + } + kind = 0; + const uint pos = uint(enc); + return pos >= p.position ? chunk + (pos - p.position) * p.chunk_stride + : ring + (pos % p.window) * p.ring_stride; +} + +// One dim's exact packed decode through a slot descriptor (dsv41_unpack with the slot's block). +inline bfloat dsv41_decode_at(int enc, device const uchar *ring, device const uchar *chunk, + device const uchar *main, uint d, constant Dsv41Attention &p) { + if (enc < 0) return bfloat(0); + uint kind; + device const uchar *k = dsv41_key_ptr(enc, ring, chunk, main, p, kind); + return bfloat(dsv41_unpack(k, d, p.width, kind != 0u ? p.main_block : 32u, kind)); +} + +// Aligned-when-possible small vector loads: the packed rows keep every dec4 address a multiple of 4. +inline uchar4 dsv41_load4(device const uchar *k) { + if (((unsigned long)k & 3u) == 0u) return *(const device uchar4 *)k; + return uchar4(k[0], k[1], k[2], k[3]); +} +inline uchar2 dsv41_load2(device const uchar *k) { + if (((unsigned long)k & 1u) == 0u) return *(const device uchar2 *)k; + return uchar2(k[0], k[1]); +} + +// Four consecutive dims of one key as the scalar decodes them: every value rounded to bf16 exactly. +inline bfloat4 dsv41_dec4(int enc, device const uchar *ring, device const uchar *chunk, device const uchar *main, + uint d, constant Dsv41Attention &p) { + if (enc < 0) return bfloat4(float4(0.0f)); + uint kind; + device const uchar *k = dsv41_key_ptr(enc, ring, chunk, main, p, kind); + if (kind == 0) { + const float s = as_type(uint(k[p.width + (d >> 5)]) << 23); + const uchar4 c = dsv41_load4(k + d); + bfloat4 v; + TF_UNROLL + for (short i = 0; i < 4; i++) v[i] = bfloat(dsv41_bf(dsv41_round(dsv41_e4(c[i]) * s))); + return v; + } + const float s = dsv41_e4(k[p.width / 2 + (d >> 4)]); + const uchar2 c = dsv41_load2(k + d / 2); // d is even on every dec4 call (d0, the strides and home.x are multiples of 4) + bfloat4 v; + v[0] = bfloat(dsv41_bf(dsv41_round(dsv41_e2(c[0] & 15) * s))); + v[1] = bfloat(dsv41_bf(dsv41_round(dsv41_e2(c[0] >> 4) * s))); + v[2] = bfloat(dsv41_bf(dsv41_round(dsv41_e2(c[1] & 15) * s))); + v[3] = bfloat(dsv41_bf(dsv41_round(dsv41_e2(c[1] >> 4) * s))); + return v; +} + +// The scalar epilogue's store: each value rounded to bf16 with dsv41_round, never a float conversion. +inline void dsv41_frag_put(thread const frag &f, device ushort *p, int ld, int r, int c, short2 home) { + device ushort *q = p + (r + home.y) * ld + (c + home.x); + TF_UNROLL + for (short e = 0; e < 8; e++) q[(e >> 2) * 8 * ld + TF_COL(e)] = dsv41_round(f[e]); +} + + +// Dense KV: each visible key decoded once per layer, so attention reads bf16 instead of unpacking per row. +struct DenseKv { uint rows, width, stride, first_row, source; }; +static_assert(sizeof(DenseKv) == 20, "DenseKv must mirror csa2.zig's DenseKv"); +kernel void dsv41_dense_kv(const device uchar *src [[buffer(0)]], device ushort *dense [[buffer(1)]], + constant DenseKv &d [[buffer(2)]], uint2 gid [[thread_position_in_grid]]) { + if (gid.x >= d.rows || gid.y * 4 >= d.width) return; + const device uchar *k = src + ulong(gid.x) * d.stride; + const uint dd = gid.y * 4; + device ushort *o = dense + ulong(d.first_row + gid.x) * d.width + dd; + bfloat4 v; + if (d.source == 0) { + const float s = as_type(uint(k[d.width + (dd >> 5)]) << 23); + const uchar4 c = *(const device uchar4 *)(k + dd); + TF_UNROLL + for (short i = 0; i < 4; i++) v[i] = bfloat(dsv41_bf(dsv41_round(dsv41_e4(c[i]) * s))); + } else { + const float s = dsv41_e4(k[d.width / 2 + (dd >> 4)]); + const uchar2 c = *(const device uchar2 *)(k + dd / 2); + v[0] = bfloat(dsv41_bf(dsv41_round(dsv41_e2(c[0] & 15) * s))); + v[1] = bfloat(dsv41_bf(dsv41_round(dsv41_e2(c[0] >> 4) * s))); + v[2] = bfloat(dsv41_bf(dsv41_round(dsv41_e2(c[1] & 15) * s))); + v[3] = bfloat(dsv41_bf(dsv41_round(dsv41_e2(c[1] >> 4) * s))); + } + *(device bfloat4 *)o = v; +} + +// The dense row a slot descriptor names: the window ring, this chunk, or the compressed picks. +inline ulong dsv41_dense_row(int enc, constant Dsv41Attention &p) { + if (enc & (1 << 30)) return ulong(p.window) + ulong(p.chunk_rows) + uint(enc & 0x3FFFFFFF); + const uint pos = uint(enc); + return pos >= p.position ? ulong(p.window) + (pos - p.position) : ulong(pos % p.window); +} + +inline bfloat4 dsv41_dense4(int enc, device const ushort *dense, uint d, constant Dsv41Attention &p) { + if (enc < 0) return bfloat4(float4(0.0f)); + return *(const device bfloat4 *)(dense + dsv41_dense_row(enc, p) * p.width + d); +} + +inline bfloat dsv41_dense_at(int enc, device const ushort *dense, uint d, constant Dsv41Attention &p) { + if (enc < 0) return bfloat(0); + return as_type(dense[dsv41_dense_row(enc, p) * p.width + d]); +} + +// The same loads from a row offset a block staged once (see `keyoff`): no branchy resolution a fragment. +inline bfloat4 dsv41_dense4_off(int enc, uint off, device const ushort *dense, uint d) { + if (enc < 0) return bfloat4(float4(0.0f)); + return *(const device bfloat4 *)(dense + ulong(off) + d); +} + +inline bfloat dsv41_dense_at_off(int enc, uint off, device const ushort *dense, uint d) { + if (enc < 0) return bfloat(0); + return as_type(dense[ulong(off) + d]); +} + +// A prompt chunk's rows: 16 heads at a time, 32 keys at a time, out [rows, heads, 512] bf16. +[[kernel]] void dsv41_sparse_nax(device const ushort *q [[buffer(0)]], device const uchar *ring [[buffer(1)]], + device const uchar *chunk [[buffer(2)]], device const uchar *main [[buffer(3)]], + device const int *indices [[buffer(4)]], device const float *sink [[buffer(5)]], + device ushort *out [[buffer(6)]], constant Dsv41Attention &p [[buffer(7)]], + device const ushort *dense [[buffer(8)]], device float *parts [[buffer(9)]], + uint s [[simdgroup_index_in_threadgroup]], uint lane [[thread_index_in_simdgroup]], + uint3 tg [[threadgroup_position_in_grid]]) { + threadgroup float partial[4][32][16]; // each simdgroup's scores, by lane (every simdgroup's lanes hold the same cells) + threadgroup int keyrow[BLOCK]; + threadgroup uint keyoff[BLOCK]; // the row's offset into `dense`, resolved once a key + if (tg.x * GROUP >= p.heads || tg.y >= p.rows) return; + const uint row = tg.y, query = p.chunk_all ? p.position : p.position + row; + const uint columns = query == 0 ? 1u : p.window; // dsv41_window_columns + const uint compressed = p.ratio ? min(p.topk, min(p.compressed_rows, (query + 1) / p.ratio)) : 0u; + const uint count = columns + compressed; + const int h0 = int(tg.x) * GROUP, d0 = int(s) * SLICE; + const short2 home = frag_home(ushort(lane)); + // this simdgroup's 128 dims of its 16 heads' queries + const device bfloat *qb = reinterpret_cast(q + ulong(row) * p.q_stride + ulong(h0) * RANK + uint(d0)); + frag qf[8]; + TF_UNROLL + for (short t = 0; t < 8; t++) frag_get(qf[t], qb, RANK, 0, 16 * t, home); + frag acc[4][2]; + float m[2], l[2]; + TF_UNROLL + for (short c = 0; c < 4; c++) { + acc[c][0] = frag(0); + acc[c][1] = frag(0); + } + m[0] = m[1] = -1e30f; + l[0] = l[1] = 0.0f; + // A decode layer's whole key scan would run four threadgroups. + const uint split = tg.z, per = (count + p.splits - 1) / max(p.splits, 1u); + const uint j_begin = split * per, j_end = min(count, j_begin + per); + for (uint j0 = j_begin; j0 < j_end; j0 += BLOCK) { + // One lane a key: the same values, a thirty-second of the work (every lane used to run all BLOCK steps). + if (s == 0 && lane < uint(BLOCK)) { + const int enc = j0 + lane < j_end ? dsv41_slot_at(p, row, query, columns, j0 + lane, indices) : -1; + keyrow[lane] = enc; + keyoff[lane] = enc < 0 ? 0u : uint(dsv41_dense_row(enc, p) * p.width); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + // scores: this simdgroup's 128 dims of the block's 32 keys + frag lo_s = frag(0), hi_s = frag(0); +#ifndef TF_SIMD_FRAGS + TF_UNROLL + for (short t = 0; t < 8; t++) { + const uint d = uint(d0) + 16u * uint(t) + uint(home.x); + const bfloat4 a = dsv41_dense4_off(keyrow[home.y], keyoff[home.y], dense, d); + const bfloat4 b = dsv41_dense4_off(keyrow[short(home.y + 8)], keyoff[short(home.y + 8)], dense, d); + const bfloat4 c = dsv41_dense4_off(keyrow[short(16 + home.y)], keyoff[short(16 + home.y)], dense, d); + const bfloat4 e = dsv41_dense4_off(keyrow[short(24 + home.y)], keyoff[short(24 + home.y)], dense, d); + mma_16x32(lo_s, hi_s, qf[t], frag(a, b), frag(c, e)); + } +#else + TF_UNROLL + for (short t = 0; t < 8; t++) { + frag b0, b1; + TF_UNROLL + for (short e = 0; e < 8; e++) { + const int k0 = keyrow[t_key(e, home)], k1 = keyrow[16 + t_key(e, home)]; + const uint d = uint(d0) + 16u * uint(t) + uint(t_dim(e, home)); + b0[e] = dsv41_dense_at_off(k0, keyoff[t_key(e, home)], dense, d); + b1[e] = dsv41_dense_at_off(k1, keyoff[16 + t_key(e, home)], dense, d); + } + mma_16x32(lo_s, hi_s, qf[t], b0, b1); + } +#endif + TF_UNROLL + for (short e = 0; e < 8; e++) { + partial[s][lane][e] = lo_s[e]; + partial[s][lane][8 + e] = hi_s[e]; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + float sc[16]; + TF_UNROLL + for (short i = 0; i < 16; i++) { + const float v = ((partial[0][lane][i] + partial[1][lane][i]) + partial[2][lane][i]) + partial[3][lane][i]; + const short e = i & 7; + const int key = (i < 8 ? 0 : 16) + p_col(e, home); + sc[i] = keyrow[key] >= 0 ? v * p.scale : NO_SCORE; + } + // the online softmax, a head at a time (elements 0-3 and 8-11 are this lane's first head, 4-7 and 12-15 its second) + float factor[2]; + TF_UNROLL + for (short h = 0; h < 2; h++) { + float bmax = NO_SCORE; + TF_UNROLL + for (short i = 0; i < 4; i++) bmax = max(bmax, max(sc[4 * h + i], sc[8 + 4 * h + i])); + const float new_max = max(m[h], row_max(bmax)); + factor[h] = fast::exp(m[h] - new_max); + m[h] = new_max; + } + frag p1[2]; // the probabilities' one bf16 part, exactly the scalar's dsv41_round + float bsum[2] = {0.0f, 0.0f}; + TF_UNROLL + for (short i = 0; i < 16; i++) { + const short e = i & 7, h = e >> 2, kb = i < 8 ? 0 : 1; + const float pp = sc[i] > NO_SCORE ? fast::exp(sc[i] - m[h]) : 0.0f; + bsum[h] += pp; + p1[kb][e] = bfloat(dsv41_bf(dsv41_round(pp))); + } + TF_UNROLL + for (short h = 0; h < 2; h++) l[h] = l[h] * factor[h] + row_sum(bsum[h]); + if (!simd_all(factor[0] == 1.0f && factor[1] == 1.0f)) // a factor of 1 leaves every value as it is + TF_UNROLL + for (short c = 0; c < 4; c++) { + TF_UNROLL + for (short e = 0; e < 8; e++) { + acc[c][0][e] *= factor[e >> 2]; + acc[c][1][e] *= factor[e >> 2]; + } + } + // values: keys 0-15 then 16-31, each part in turn, into this simdgroup's 128 dims + TF_UNROLL + for (short kb = 0; kb < 2; kb++) { + TF_UNROLL + for (short c = 0; c < 4; c++) { + const uint d = uint(d0) + 32u * uint(c) + uint(home.x); +#ifndef TF_SIMD_FRAGS + // The dense pass already rounded every key this window reads. + const bfloat4 a = dsv41_dense4_off(keyrow[16 * kb + home.y], keyoff[16 * kb + home.y], dense, d); + const bfloat4 b = dsv41_dense4_off(keyrow[16 * kb + short(home.y + 8)], keyoff[16 * kb + short(home.y + 8)], dense, d); + frag v0(a, b); + const bfloat4 a2 = dsv41_dense4_off(keyrow[16 * kb + home.y], keyoff[16 * kb + home.y], dense, d + 16); + const bfloat4 b2 = dsv41_dense4_off(keyrow[16 * kb + short(home.y + 8)], keyoff[16 * kb + short(home.y + 8)], dense, d + 16); + frag v1(a2, b2); +#else + frag v0, v1; + TF_UNROLL + for (short e = 0; e < 8; e++) { + const int k = keyrow[16 * kb + p_row(e, home)]; + const uint dd = uint(d0) + 32u * uint(c) + uint(p_col(e, home)); + v0[e] = dsv41_decode_at(k, ring, chunk, main, dd, p); + v1[e] = dsv41_decode_at(k, ring, chunk, main, dd + 16, p); + } +#endif + mma_16x32(acc[c][0], acc[c][1], p1[kb], v0, v1); + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + } + if (p.splits > 1) { + // This split's (max, sum, accumulators) by head group, then split order; a decode window is one row. + device float *part = parts + ((((ulong(tg.y) * ulong(p.splits) + ulong(split)) * ulong(p.heads / GROUP) + ulong(tg.x)) * 4 + ulong(s)) * 32 + ulong(lane)) * 68; + part[0] = m[0]; + part[1] = m[1]; + part[2] = l[0]; + part[3] = l[1]; + TF_UNROLL + for (short c = 0; c < 4; c++) + TF_UNROLL + for (short j = 0; j < 2; j++) + TF_UNROLL + for (short e = 0; e < 8; e++) part[4 + c * 16 + j * 8 + e] = acc[c][j][e]; + return; + } + // The source adds sink mass to the completed online denominator before the division; every store is dsv41_round. + device ushort *obase = out + ulong(row) * p.q_stride + ulong(h0) * RANK + uint(d0); + TF_UNROLL + for (short c = 0; c < 4; c++) { + TF_UNROLL + for (short j = 0; j < 2; j++) { + frag o = acc[c][j]; + TF_UNROLL + for (short e = 0; e < 8; e++) { + const short h = e >> 2; + const float denom = l[h] + fast::exp(sink[ulong(h0) + uint(home.y) + 8u * uint(h)] - m[h]); + o[e] = denom == 0.0f ? 0.0f : o[e] / denom; + } + dsv41_frag_put(o, obase, RANK, 0, 32 * c + 16 * j, home); + } + } +} + +// The same pass over only the compressed rows a one-row window actually reads: the picks name the positions. +kernel void dsv41_dense_kv_picked(const device uchar *src [[buffer(0)]], device ushort *dense [[buffer(1)]], + constant DenseKv &d [[buffer(2)]], const device int *picks [[buffer(3)]], + uint2 gid [[thread_position_in_grid]]) { + if (gid.x >= d.rows || gid.y * 4 >= d.width) return; + const int pos = picks[gid.x]; + if (pos < 0) return; + const device uchar *k = src + ulong(pos) * d.stride; + const uint dd = gid.y * 4; + device ushort *o = dense + ulong(d.first_row + uint(pos)) * d.width + dd; + bfloat4 v; + const float s = dsv41_e4(k[d.width / 2 + (dd >> 4)]); + const uchar2 c = *(const device uchar2 *)(k + dd / 2); + v[0] = bfloat(dsv41_bf(dsv41_round(dsv41_e2(c[0] & 15) * s))); + v[1] = bfloat(dsv41_bf(dsv41_round(dsv41_e2(c[0] >> 4) * s))); + v[2] = bfloat(dsv41_bf(dsv41_round(dsv41_e2(c[1] & 15) * s))); + v[3] = bfloat(dsv41_bf(dsv41_round(dsv41_e2(c[1] >> 4) * s))); + *(device bfloat4 *)o = v; +} + +// THE MERGE'S GRID IS FOUR THREADGROUPS: each takes one accumulator chunk at 16 threadgroups, bit-identical output. +[[kernel]] void dsv41_sparse_merge_split(device const float *parts [[buffer(0)]], device ushort *out [[buffer(1)]], + device const float *sink [[buffer(2)]], constant Dsv41Attention &p [[buffer(3)]], + uint s [[simdgroup_index_in_threadgroup]], uint lane [[thread_index_in_simdgroup]], + uint3 tg [[threadgroup_position_in_grid]]) { + if (tg.x * GROUP >= p.heads || tg.y >= p.rows) return; + const uint row = tg.y, h0 = tg.x * GROUP, d0 = s * SLICE; + const uint c = tg.z; // this threadgroup's accumulator chunk + const short2 home = frag_home(ushort(lane)); + const ulong groups = ulong(p.heads / GROUP); + float m[2] = {-1e30f, -1e30f}; + for (uint sp = 0; sp < p.splits; ++sp) { + const device float *part = parts + ((((ulong(row) * p.splits + ulong(sp)) * groups + ulong(tg.x)) * 4 + ulong(s)) * 32 + ulong(lane)) * 68; + m[0] = max(m[0], part[0]); + m[1] = max(m[1], part[1]); + } + float l[2] = {0.0f, 0.0f}; + frag acc[2]; + TF_UNROLL + for (short j = 0; j < 2; j++) { + acc[j] = frag(0); + TF_UNROLL + for (short e = 0; e < 8; e++) acc[j][e] = 0.0f; + } + for (uint sp = 0; sp < p.splits; ++sp) { + const device float *part = parts + ((((ulong(row) * p.splits + ulong(sp)) * groups + ulong(tg.x)) * 4 + ulong(s)) * 32 + ulong(lane)) * 68; + float f[2]; + TF_UNROLL + for (short h = 0; h < 2; ++h) { + f[h] = fast::exp(part[h] - m[h]); + l[h] += part[2 + h] * f[h]; + } + TF_UNROLL + for (short j = 0; j < 2; j++) + TF_UNROLL + for (short e = 0; e < 8; e++) acc[j][e] += part[4 + c * 16 + j * 8 + e] * f[e >> 2]; + } + device ushort *obase = out + ulong(row) * p.q_stride + ulong(h0) * RANK + uint(d0); + TF_UNROLL + for (short j = 0; j < 2; j++) { + frag o = acc[j]; + TF_UNROLL + for (short e = 0; e < 8; e++) { + const short h = e >> 2; + const float denom = l[h] + fast::exp(sink[ulong(h0) + uint(home.y) + 8u * uint(h)] - m[h]); + o[e] = denom == 0.0f ? 0.0f : o[e] / denom; + } + dsv41_frag_put(o, obase, RANK, 0, 32 * c + 16 * j, home); + } +} + +// A decode window's splits, summed in split order, then the sink and the division the plain path does. +[[kernel]] void dsv41_sparse_merge(device const float *parts [[buffer(0)]], device ushort *out [[buffer(1)]], + device const float *sink [[buffer(2)]], constant Dsv41Attention &p [[buffer(3)]], + uint s [[simdgroup_index_in_threadgroup]], uint lane [[thread_index_in_simdgroup]], + uint3 tg [[threadgroup_position_in_grid]]) { + if (tg.x * GROUP >= p.heads || tg.y >= p.rows) return; + const uint row = tg.y, h0 = tg.x * GROUP, d0 = s * SLICE; + const short2 home = frag_home(ushort(lane)); + const ulong groups = ulong(p.heads / GROUP); + const uint base = lane * 68; + float m[2] = {-1e30f, -1e30f}; + for (uint sp = 0; sp < p.splits; ++sp) { + const device float *part = parts + ((((ulong(row) * p.splits + ulong(sp)) * groups + ulong(tg.x)) * 4 + ulong(s)) * 32 + ulong(lane)) * 68; + m[0] = max(m[0], part[0]); + m[1] = max(m[1], part[1]); + } + float l[2] = {0.0f, 0.0f}; + frag acc[4][2]; + TF_UNROLL + for (short c = 0; c < 4; c++) + TF_UNROLL + for (short j = 0; j < 2; j++) { + acc[c][j] = frag(0); + TF_UNROLL + for (short e = 0; e < 8; e++) acc[c][j][e] = 0.0f; + } + for (uint sp = 0; sp < p.splits; ++sp) { + const device float *part = parts + ((((ulong(row) * p.splits + ulong(sp)) * groups + ulong(tg.x)) * 4 + ulong(s)) * 32 + ulong(lane)) * 68; + float f[2]; + TF_UNROLL + for (short h = 0; h < 2; h++) { + f[h] = fast::exp(part[h] - m[h]); + l[h] += part[2 + h] * f[h]; + } + TF_UNROLL + for (short c = 0; c < 4; c++) + TF_UNROLL + for (short j = 0; j < 2; j++) + TF_UNROLL + for (short e = 0; e < 8; e++) acc[c][j][e] += part[4 + c * 16 + j * 8 + e] * f[e >> 2]; + } + device ushort *obase = out + ulong(row) * p.q_stride + ulong(h0) * RANK + uint(d0); + TF_UNROLL + for (short c = 0; c < 4; c++) { + TF_UNROLL + for (short j = 0; j < 2; j++) { + frag o = acc[c][j]; + TF_UNROLL + for (short e = 0; e < 8; e++) { + const short h = e >> 2; + const float denom = l[h] + fast::exp(sink[ulong(h0) + uint(home.y) + 8u * uint(h)] - m[h]); + o[e] = denom == 0.0f ? 0.0f : o[e] / denom; + } + dsv41_frag_put(o, obase, RANK, 0, 32 * c + 16 * j, home); + } + } +} diff --git a/zig/kernels/metal/deepseek_v41/csa2_rows.metal b/zig/kernels/metal/deepseek_v41/csa2_rows.metal new file mode 100644 index 00000000000..4a9bd5f81fe --- /dev/null +++ b/zig/kernels/metal/deepseek_v41/csa2_rows.metal @@ -0,0 +1,221 @@ +// Batched decode windows: one row a slot; state via addr (live, 0, selection, 0), mains (owner rows), pos tables. +struct Dsv41AttentionRows { + uint rows, heads, width, q_stride, window, ring_stride, chunk_stride, main_stride, ring_off, owner; + uint ratio, index_topk, dense_rows, splits; + float scale; +}; +static_assert(sizeof(Dsv41AttentionRows) == 60, "Dsv41AttentionRows must mirror csa2.zig's RowsParams"); + +// Four dims of a packed key, as dsv41_dense_kv decodes them: kind 0 the window's e4 rows, 1 the compressed e2 rows. +inline bfloat4 dsv41_dense_dec4(const device uchar *k, uint width, uint dd, uint kind) { + bfloat4 v; + if (kind == 0) { + const float s = as_type(uint(k[width + (dd >> 5)]) << 23); + const uchar4 c = *(const device uchar4 *)(k + dd); + TF_UNROLL + for (short i = 0; i < 4; i++) v[i] = bfloat(dsv41_bf(dsv41_round(dsv41_e4(c[i]) * s))); + } else { + const float s = dsv41_e4(k[width / 2 + (dd >> 4)]); + const uchar2 c = *(const device uchar2 *)(k + dd / 2); + v[0] = bfloat(dsv41_bf(dsv41_round(dsv41_e2(c[0] & 15) * s))); + v[1] = bfloat(dsv41_bf(dsv41_round(dsv41_e2(c[0] >> 4) * s))); + v[2] = bfloat(dsv41_bf(dsv41_round(dsv41_e2(c[1] & 15) * s))); + v[3] = bfloat(dsv41_bf(dsv41_round(dsv41_e2(c[1] >> 4) * s))); + } + return v; +} + +// Every slot's visible keys decoded once into its dense table (ring, this row, picks). +kernel void dsv41_dense_kv_rows(device const ulong *addr [[buffer(0)]], device const uint *pos [[buffer(1)]], + device const uchar *chunk [[buffer(2)]], device ushort *dense [[buffer(3)]], + constant Dsv41AttentionRows &p [[buffer(4)]], device const ulong *mains [[buffer(5)]], + uint3 gid [[thread_position_in_grid]]) { + const uint slot = gid.z, key = gid.x, dd = gid.y * 4; + if (slot >= p.rows || dd >= p.width || key >= p.dense_rows) return; + const uint position = pos[slot]; + const device uchar *k; + uint kind = 0; + if (key < p.window) { + if (key >= min(position, p.window)) return; + k = reinterpret_cast(addr[4 * slot]) + p.ring_off + ulong(key) * p.ring_stride; + } else if (key == p.window) { + k = chunk + ulong(slot) * p.chunk_stride; + } else { + if (!p.ratio) return; + const uint comp = (position + 1) / p.ratio; + const uint i = key - p.window - 1; + if (i >= min(p.index_topk, comp)) return; + const int pick = reinterpret_cast(addr[4 * slot + 2])[i]; + if (pick < 0 || uint(pick) >= comp) return; + k = reinterpret_cast(mains[4 * slot + p.owner]) + ulong(pick) * p.main_stride; + kind = 1; + } + *(device bfloat4 *)(dense + (ulong(slot) * p.dense_rows + key) * p.width + dd) = dsv41_dense_dec4(k, p.width, dd, kind); +} + +#ifndef TF_SIMD_FRAGS +// dsv41_sparse_nax for decode windows of one row each: row tg.y is slot tg.y, its keys in its own dense table. +[[kernel]] void dsv41_sparse_nax_rows(device const ushort *q [[buffer(0)]], device const ulong *addr [[buffer(1)]], + device const uint *pos [[buffer(2)]], device const float *sink [[buffer(3)]], + device ushort *out [[buffer(4)]], constant Dsv41AttentionRows &p [[buffer(5)]], + device const ushort *dense_all [[buffer(6)]], device float *parts [[buffer(7)]], + uint s [[simdgroup_index_in_threadgroup]], uint lane [[thread_index_in_simdgroup]], + uint3 tg [[threadgroup_position_in_grid]]) { + threadgroup float partial[4][32][16]; + threadgroup int keyrow[BLOCK]; + threadgroup uint keyoff[BLOCK]; + if (tg.x * GROUP >= p.heads || tg.y >= p.rows) return; + const uint row = tg.y, query = pos[row]; + const uint columns = query == 0 ? 1u : p.window; + const uint comp = p.ratio ? (query + 1) / p.ratio : 0u; // the slot's compressed rows + const uint compressed = p.ratio ? min(p.index_topk, comp) : 0u; // min(topk, min(compressed rows, visible)) + const uint count = columns + compressed; + const device int *indices = reinterpret_cast(addr[4 * row + 2]); + const device ushort *dense = dense_all + ulong(row) * p.dense_rows * p.width; + const int h0 = int(tg.x) * GROUP, d0 = int(s) * SLICE; + const short2 home = frag_home(ushort(lane)); + const device bfloat *qb = reinterpret_cast(q + ulong(row) * p.q_stride + ulong(h0) * RANK + uint(d0)); + frag qf[8]; + TF_UNROLL + for (short t = 0; t < 8; t++) frag_get(qf[t], qb, RANK, 0, 16 * t, home); + frag acc[4][2]; + float m[2], l[2]; + TF_UNROLL + for (short c = 0; c < 4; c++) { + acc[c][0] = frag(0); + acc[c][1] = frag(0); + } + m[0] = m[1] = -1e30f; + l[0] = l[1] = 0.0f; + const uint split = tg.z, per = (count + p.splits - 1) / max(p.splits, 1u); + const uint j_begin = split * per, j_end = min(count, j_begin + per); + for (uint j0 = j_begin; j0 < j_end; j0 += BLOCK) { + if (s == 0 && lane < uint(BLOCK)) { + const uint j = j0 + lane; + int enc = -1; + uint dense_row = 0; + if (j < j_end) { + if (j < columns) { + // dsv41_slot_at's window part: absolute position `wpos`, its dense row the ring slot (or this row's) + uint wpos; + if (query == 0) wpos = 0; + else if (query + 1 < p.window) wpos = (query + 1 + j) % p.window; + else wpos = (query + 1 > p.window ? query + 1 - p.window : 0) + j; + if (wpos <= query) { + enc = int(wpos); + dense_row = wpos >= query ? p.window : wpos % p.window; + } + } else { + const int pick = indices[j - columns]; + if (pick >= 0 && uint(pick) < min(comp, (query + 1) / p.ratio)) { + enc = int(0x40000000u | uint(pick)); + dense_row = p.window + 1 + (j - columns); + } + } + } + keyrow[lane] = enc; + keyoff[lane] = enc < 0 ? 0u : dense_row * p.width; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + frag lo_s = frag(0), hi_s = frag(0); + TF_UNROLL + for (short t = 0; t < 8; t++) { + const uint d = uint(d0) + 16u * uint(t) + uint(home.x); + const bfloat4 a = dsv41_dense4_off(keyrow[home.y], keyoff[home.y], dense, d); + const bfloat4 b = dsv41_dense4_off(keyrow[short(home.y + 8)], keyoff[short(home.y + 8)], dense, d); + const bfloat4 c = dsv41_dense4_off(keyrow[short(16 + home.y)], keyoff[short(16 + home.y)], dense, d); + const bfloat4 e = dsv41_dense4_off(keyrow[short(24 + home.y)], keyoff[short(24 + home.y)], dense, d); + mma_16x32(lo_s, hi_s, qf[t], frag(a, b), frag(c, e)); + } + TF_UNROLL + for (short e = 0; e < 8; e++) { + partial[s][lane][e] = lo_s[e]; + partial[s][lane][8 + e] = hi_s[e]; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + float sc[16]; + TF_UNROLL + for (short i = 0; i < 16; i++) { + const float v = ((partial[0][lane][i] + partial[1][lane][i]) + partial[2][lane][i]) + partial[3][lane][i]; + const short e = i & 7; + const int key = (i < 8 ? 0 : 16) + p_col(e, home); + sc[i] = keyrow[key] >= 0 ? v * p.scale : NO_SCORE; + } + float factor[2]; + TF_UNROLL + for (short h = 0; h < 2; h++) { + float bmax = NO_SCORE; + TF_UNROLL + for (short i = 0; i < 4; i++) bmax = max(bmax, max(sc[4 * h + i], sc[8 + 4 * h + i])); + const float new_max = max(m[h], row_max(bmax)); + factor[h] = fast::exp(m[h] - new_max); + m[h] = new_max; + } + frag p1[2]; + float bsum[2] = {0.0f, 0.0f}; + TF_UNROLL + for (short i = 0; i < 16; i++) { + const short e = i & 7, h = e >> 2, kb = i < 8 ? 0 : 1; + const float pp = sc[i] > NO_SCORE ? fast::exp(sc[i] - m[h]) : 0.0f; + bsum[h] += pp; + p1[kb][e] = bfloat(dsv41_bf(dsv41_round(pp))); + } + TF_UNROLL + for (short h = 0; h < 2; h++) l[h] = l[h] * factor[h] + row_sum(bsum[h]); + if (!simd_all(factor[0] == 1.0f && factor[1] == 1.0f)) + TF_UNROLL + for (short c = 0; c < 4; c++) { + TF_UNROLL + for (short e = 0; e < 8; e++) { + acc[c][0][e] *= factor[e >> 2]; + acc[c][1][e] *= factor[e >> 2]; + } + } + TF_UNROLL + for (short kb = 0; kb < 2; kb++) { + TF_UNROLL + for (short c = 0; c < 4; c++) { + const uint d = uint(d0) + 32u * uint(c) + uint(home.x); + const bfloat4 a = dsv41_dense4_off(keyrow[16 * kb + home.y], keyoff[16 * kb + home.y], dense, d); + const bfloat4 b = dsv41_dense4_off(keyrow[16 * kb + short(home.y + 8)], keyoff[16 * kb + short(home.y + 8)], dense, d); + frag v0(a, b); + const bfloat4 a2 = dsv41_dense4_off(keyrow[16 * kb + home.y], keyoff[16 * kb + home.y], dense, d + 16); + const bfloat4 b2 = dsv41_dense4_off(keyrow[16 * kb + short(home.y + 8)], keyoff[16 * kb + short(home.y + 8)], dense, d + 16); + frag v1(a2, b2); + mma_16x32(acc[c][0], acc[c][1], p1[kb], v0, v1); + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + } + if (p.splits > 1) { + device float *part = parts + ((((ulong(tg.y) * ulong(p.splits) + ulong(split)) * ulong(p.heads / GROUP) + ulong(tg.x)) * 4 + ulong(s)) * 32 + ulong(lane)) * 68; + part[0] = m[0]; + part[1] = m[1]; + part[2] = l[0]; + part[3] = l[1]; + TF_UNROLL + for (short c = 0; c < 4; c++) + TF_UNROLL + for (short j = 0; j < 2; j++) + TF_UNROLL + for (short e = 0; e < 8; e++) part[4 + c * 16 + j * 8 + e] = acc[c][j][e]; + return; + } + device ushort *obase = out + ulong(row) * p.q_stride + ulong(h0) * RANK + uint(d0); + TF_UNROLL + for (short c = 0; c < 4; c++) { + TF_UNROLL + for (short j = 0; j < 2; j++) { + frag o = acc[c][j]; + TF_UNROLL + for (short e = 0; e < 8; e++) { + const short h = e >> 2; + const float denom = l[h] + fast::exp(sink[ulong(h0) + uint(home.y) + 8u * uint(h)] - m[h]); + o[e] = denom == 0.0f ? 0.0f : o[e] / denom; + } + dsv41_frag_put(o, obase, RANK, 0, 32 * c + 16 * j, home); + } + } +} + +#endif diff --git a/zig/kernels/metal/deepseek_v41/early.metal b/zig/kernels/metal/deepseek_v41/early.metal index 05ad1313e81..de4b66a2fcc 100644 --- a/zig/kernels/metal/deepseek_v41/early.metal +++ b/zig/kernels/metal/deepseek_v41/early.metal @@ -8,6 +8,7 @@ using namespace metal; struct TfEarlyPickArgs { uint vocab; // logits a row (the row stride) }; +static_assert(sizeof(TfEarlyPickArgs) == 4, "TfEarlyPickArgs must mirror metal/early_picks.zig's vocab row stride"); // The better of two (value, id) pairs: the larger value, ties to the lower id (no NaN reaches here). inline void tf_early_better(thread float& v, thread uint& i, float ov, uint oi) { @@ -52,6 +53,7 @@ struct TfEarlyKeyedArgs { uint vocab; // logits a row (the row stride) float t; // the temperature (at least 1e-6, as the host floors it) }; +static_assert(sizeof(TfEarlyKeyedArgs) == 8, "TfEarlyKeyedArgs must mirror metal/early_picks.zig's vocab and temperature"); // A raced row's keyed pick: the largest x / t + gumbel(key); a value not finite picks none (the host sorts such rows). [[max_total_threads_per_threadgroup(TF_TG)]] kernel void tf_dsv41_early_keyed( @@ -110,6 +112,7 @@ struct TfEarlyAcceptArgs { uint skew; // tests: 1 swaps an accepted count of 0 and 1, so the chain parts from the host's commit uint pos_lo, pos_hi; // the next ask's first draft's position less the accepted count }; +static_assert(sizeof(TfEarlyAcceptArgs) == 20, "TfEarlyAcceptArgs must mirror metal/early.zig's accept plan"); // The drafts the picks accept (the host's rule), each count's plan copied in, the bonus into the block and the result. [[max_total_threads_per_threadgroup(TF_TG)]] kernel void tf_dsv41_early_accept( diff --git a/zig/kernels/metal/deepseek_v41/engram.metal b/zig/kernels/metal/deepseek_v41/engram.metal index 0b414ef4586..3bca3139b97 100644 --- a/zig/kernels/metal/deepseek_v41/engram.metal +++ b/zig/kernels/metal/deepseek_v41/engram.metal @@ -15,6 +15,7 @@ struct TfEngramArgs { uint R, cols, dim; float eps, dscale; }; +static_assert(sizeof(TfEngramArgs) == 20, "TfEngramArgs must mirror metal/engram.zig's Args"); // Exact: the seven magnitude bits of E4M3 placed as a half's exponent and mantissa, then scaled by 2^8. inline float tf_engram_e4m3(uint code) { diff --git a/zig/kernels/metal/deepseek_v41/engram_exl3.metal b/zig/kernels/metal/deepseek_v41/engram_exl3.metal new file mode 100644 index 00000000000..fc1c2dd6fd3 --- /dev/null +++ b/zig/kernels/metal/deepseek_v41/engram_exl3.metal @@ -0,0 +1,160 @@ +// Math/layout attribution: DeepSeek AI DeepSeek-V4.1-Flash inference/{engram,model}.py (MIT). +#include +using namespace metal; +inline float rd(const device uchar* p, ulong i, uint dtype) { + if (dtype == 1u) return ((const device float*)p)[i]; + if (dtype == 2u) return float(((const device half*)p)[i]); + return as_type(uint(((const device ushort*)p)[i]) << 16); +} + +struct EngramLayer { + uint layer_id, rows; + ulong multipliers[4]; + uint primes[24], offsets[24]; +}; +static_assert(sizeof(EngramLayer) == 232, "EngramLayer must mirror engram_hash.zig's Layer"); +struct EngramHistory { int tail[3]; uint available; }; +static_assert(sizeof(EngramHistory) == 16, "EngramHistory must mirror engram.zig's History"); +struct EngramHashArgs { uint tokens, pad, masked; }; +static_assert(sizeof(EngramHashArgs) == 12, "EngramHashArgs must mirror engram.zig's HashArgs"); + +inline int engram_token(const device uint* ids, const device uint* map, + const device uchar* mask, uint pos, uint masked) { + return masked && mask[pos] == 0 ? -1 : int(map[ids[pos]]); +} + +// One lane per token; history is immutable until all layers have hashed this chunk. +kernel void tf_v41_engram_hash(const device uint* ids [[buffer(0)]], + const device uint* map [[buffer(1)]], + const device uchar* mask [[buffer(2)]], + const device EngramHistory& history [[buffer(3)]], + device uint* out [[buffer(4)]], + constant EngramLayer& layer [[buffer(5)]], + constant EngramHashArgs& args [[buffer(6)]], + uint pos [[thread_position_in_grid]]) { + if (pos >= args.tokens) return; + bool blocked = false; + ulong rolling = 0; + for (uint shift = 0; shift < 4; shift++) { + int token; + if (shift <= pos) token = engram_token(ids, map, mask, pos - shift, args.masked); + else { + const uint back = shift - pos - 1; + token = back < history.available ? history.tail[back] : -1; + } + blocked = blocked || token == -1; + const ulong compressed = blocked ? args.pad : uint(token); + rolling ^= compressed * layer.multipliers[shift]; + if (shift != 0) for (uint head = 0; head < 8; head++) { + const uint col = (shift - 1) * 8 + head; + out[size_t(pos) * 24 + col] = uint(rolling % layer.primes[col]) + layer.offsets[col]; + } + } +} + +// Called exactly once after all Engram layers hash a chunk, never once per layer. +kernel void tf_v41_engram_commit(const device uint* ids [[buffer(0)]], + const device uint* map [[buffer(1)]], + const device uchar* mask [[buffer(2)]], + device EngramHistory& history [[buffer(3)]], + constant EngramHashArgs& args [[buffer(4)]]) { + int tail[3]; + for (uint i = 0; i < 3; i++) { + tail[i] = i < args.tokens ? engram_token(ids, map, mask, args.tokens - i - 1, args.masked) + : i - args.tokens < history.available ? history.tail[i - args.tokens] : -1; + } + for (uint i = 0; i < 3; i++) history.tail[i] = tail[i]; + history.available = min(3u, history.available + args.tokens); +} + +kernel void tf_v41_engram_reset(device EngramHistory& history [[buffer(0)]]) { + for (uint i = 0; i < 3; i++) history.tail[i] = -1; + history.available = 0; +} + +inline float engram_e4m3(uchar bits) { + const uint magnitude = bits & 127, exponent = magnitude >> 3, mantissa = magnitude & 7; + float value = magnitude == 127 ? NAN : exponent == 0 ? float(mantissa) * 0x1p-9f + : ldexp(1.0f + float(mantissa) * 0.125f, int(exponent) - 7); + return bits & 128 ? -value : value; +} +inline float engram_ue8m0(uchar bits) { + return bits == 255 ? NAN : as_type(bits == 0 ? 0x00400000u : uint(bits) << 23); +} + +struct EngramGatherArgs { + ulong weight_stride, scale_stride, output_stride; + uint tokens, columns, head_dim, scale_block; +}; +static_assert(sizeof(EngramGatherArgs) == 40, "EngramGatherArgs must mirror engram.zig's GatherArgs"); + +// Read only the selected E4M3FN rows; one UE8M0 scale per 32 values of each row. +kernel void tf_v41_engram_gather(const device uint* ids [[buffer(0)]], + const device uchar* table [[buffer(1)]], + const device uchar* scales [[buffer(2)]], + device bfloat* out [[buffer(3)]], + constant EngramGatherArgs& args [[buffer(4)]], + uint2 pos [[thread_position_in_grid]]) { + if (pos.y >= args.tokens || pos.x >= args.columns * args.head_dim) return; + const uint col = pos.x / args.head_dim, d = pos.x % args.head_dim; + const size_t row = ids[size_t(pos.y) * args.columns + col]; + const float value = engram_e4m3(table[row * args.weight_stride + d]); + const float scale = engram_ue8m0(scales[row * args.scale_stride + d / args.scale_block]); + out[size_t(pos.y) * args.output_stride + pos.x] = bfloat(value * scale); +} + +struct EngramGateArgs { + ulong hidden_stride, kv_stride, output_stride; + uint dim, copies, masked, weight_dtype; + float eps; +}; +static_assert(sizeof(EngramGateArgs) == 48, "EngramGateArgs must mirror engram.zig's GateArgs"); + +// Each copy gets its own RMS dot gate; all copies share the value following the flattened keys. +kernel void tf_v41_engram_gate(const device bfloat* hidden [[buffer(0)]], + const device bfloat* kv [[buffer(1)]], + const device uchar* q_weight [[buffer(2)]], + const device uchar* k_weight [[buffer(3)]], + const device uchar* mask [[buffer(4)]], + device bfloat* out [[buffer(5)]], + constant EngramGateArgs& args [[buffer(6)]], + uint2 group [[threadgroup_position_in_grid]], + uint t [[thread_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]], + uint sg [[simdgroup_index_in_threadgroup]]) { + threadgroup float3 sums[8]; + threadgroup float gate; + const size_t hbase = size_t(group.x) * args.hidden_stride + size_t(group.y) * args.dim; + const size_t kbase = size_t(group.x) * args.kv_stride + size_t(group.y) * args.dim; + const size_t wbase = size_t(group.y) * args.dim; + float3 acc = 0; + for (uint d = t; d < args.dim; d += 256) { + const float h = float(hidden[hbase + d]), k = float(kv[kbase + d]); + const float weight = rd(q_weight, wbase + d, args.weight_dtype) * rd(k_weight, wbase + d, args.weight_dtype); + acc += float3(h * h, k * k, (h * weight) * k); + } + acc = float3(simd_sum(acc.x), simd_sum(acc.y), simd_sum(acc.z)); + if (lane == 0) sums[sg] = acc; + threadgroup_barrier(mem_flags::mem_threadgroup); + if (sg == 0) { + acc = lane < 8 ? sums[lane] : float3(0); + acc = float3(simd_sum(acc.x), simd_sum(acc.y), simd_sum(acc.z)); + if (lane == 0) { + float rstd; + { +#pragma clang fp contract(off) + const float factor = 1.0f / float(args.dim); + rstd = metal::precise::rsqrt(acc.x * factor + args.eps) + * metal::precise::rsqrt(acc.y * factor + args.eps); + } + const float dot = (acc.z * rstd) * metal::precise::rsqrt(float(args.dim)); + const float signed_root = copysign(metal::precise::sqrt(max(abs(dot), 1e-6f)), dot); + gate = args.masked && mask[group.x] == 0 ? 0.0f : 1.0f / (1.0f + metal::precise::exp(-signed_root)); + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + const size_t vbase = size_t(group.x) * args.kv_stride + size_t(args.copies) * args.dim; + const size_t obase = size_t(group.x) * args.output_stride + size_t(group.y) * args.dim; + for (uint d = t; d < args.dim; d += 256) + out[obase + d] = bfloat(float(hidden[hbase + d]) + gate * float(kv[vbase + d])); +} diff --git a/zig/kernels/metal/deepseek_v41/experts.metal b/zig/kernels/metal/deepseek_v41/experts.metal index 9eb0bd3fba9..2496c338c7c 100644 --- a/zig/kernels/metal/deepseek_v41/experts.metal +++ b/zig/kernels/metal/deepseek_v41/experts.metal @@ -9,6 +9,7 @@ struct DsArgs { uint K, N, topk, rows_max; float limit; }; +static_assert(sizeof(DsArgs) == 20, "DsArgs must mirror metal/experts.zig's UpArgs"); constant constexpr uint DS_KMAX = 5120; diff --git a/zig/kernels/metal/deepseek_v41/experts_kimi.metal b/zig/kernels/metal/deepseek_v41/experts_kimi.metal index c510ba2c82b..9ee1bafa6e0 100644 --- a/zig/kernels/metal/deepseek_v41/experts_kimi.metal +++ b/zig/kernels/metal/deepseek_v41/experts_kimi.metal @@ -30,10 +30,12 @@ struct ExpertPtrs { device const uchar* w2p; device const uchar* w2s; }; +static_assert(sizeof(ExpertPtrs) == 48, "ExpertPtrs must mirror metal/experts.zig's ExpertPtrs"); struct PlanArgs { uint pairs, experts, first, last; }; +static_assert(sizeof(PlanArgs) == 16, "PlanArgs must mirror metal/experts.zig's PlanArgs"); constant constexpr uint NOWHERE = 0xFFFFFFFFu; @@ -89,6 +91,7 @@ struct XpArgs { uint K, N, topk, rows_max; float beta, lin; }; +static_assert(sizeof(XpArgs) == 24, "XpArgs must mirror metal/experts.zig's XpArgs"); // The slot's activation rows (pairs' rows) staged in threadgroup memory, RP rows at a time. template diff --git a/zig/kernels/metal/deepseek_v41/experts_mma.metal b/zig/kernels/metal/deepseek_v41/experts_mma.metal index a66cfab4d1c..291585f7200 100644 --- a/zig/kernels/metal/deepseek_v41/experts_mma.metal +++ b/zig/kernels/metal/deepseek_v41/experts_mma.metal @@ -9,6 +9,7 @@ struct XmArgs { uint K, N, topk, pairs; float limit; }; +static_assert(sizeof(XmArgs) == 20, "XmArgs must mirror metal/experts_mma.zig's XmArgs"); // One tile per (expert, 16 consecutive pair positions of a slot): {expert, first position, rows}; entry 0 is the count. [[kernel, max_total_threads_per_threadgroup(32)]] void tf_dsv41_xm_tiles( diff --git a/zig/kernels/metal/deepseek_v41/fold.metal b/zig/kernels/metal/deepseek_v41/fold.metal index a95d93fe32c..213bcd91bf2 100644 --- a/zig/kernels/metal/deepseek_v41/fold.metal +++ b/zig/kernels/metal/deepseek_v41/fold.metal @@ -20,6 +20,7 @@ inline float tf_o_run(float v) { return TF_CTL == 3 ? float(half(v)) : v; } struct TfOPostArgs { uint dim, rows, topk, per_group, groups; }; +static_assert(sizeof(TfOPostArgs) == 20, "TfOPostArgs must mirror metal/fold.zig's PostArgs"); // Kimi's routed combine (group fmas, then the group tree) plus the shared expert into B, then hc_post into Y. [[kernel, max_total_threads_per_threadgroup(64)]] void tf_dsv41_o_combpost( @@ -55,7 +56,7 @@ struct TfOPostArgs { if (TF_CTL == 4 && g.x == 0) Y[ulong(a.rows) * 4u * a.dim + g.y] = bfloat(1.0f); } -// glue_tmp's helpers (tf_g_tree, the act_quant round trip), the same expressions. +// glue_rows's helpers (tf_g_tree, the act_quant round trip), the same expressions. inline float tf_o_tree(float v) { for (ushort m = 1; m < 32; m *= 2) v += simd_shuffle_xor(v, m); return v; @@ -89,10 +90,11 @@ struct TfONormArgs { uint dim, rows; float eps; }; +static_assert(sizeof(TfONormArgs) == 12, "TfONormArgs must mirror metal/fold.zig's NormArgs"); // hc_pre (H), rmsnorm (HN) and act_quant (HQ) of a row in a group of 1024; POST first makes X1 = hc_post(BR, X). -// The sum of squares runs on threads 0..255 as glue_tmp's rmsnorm: every 256th value, the butterfly, eight partials. +// The sum of squares runs on threads 0..255 as glue_rows's rmsnorm: every 256th value, the butterfly, eight partials. template [[kernel, max_total_threads_per_threadgroup(TF_O_TG)]] void tf_dsv41_o_prenorm( const device bfloat* X [[buffer(0)]], const device float* PRE [[buffer(1)]], const device float* Wt [[buffer(2)]], diff --git a/zig/kernels/metal/deepseek_v41/fp8_mma.metal b/zig/kernels/metal/deepseek_v41/fp8_mma.metal index 4a4b1fa18f8..b8baec14f52 100644 --- a/zig/kernels/metal/deepseek_v41/fp8_mma.metal +++ b/zig/kernels/metal/deepseek_v41/fp8_mma.metal @@ -37,6 +37,7 @@ using namespace metal; struct TfDsv41Fp8MmaArgs { uint K, N, R; }; +static_assert(sizeof(TfDsv41Fp8MmaArgs) == 12, "TfDsv41Fp8MmaArgs must mirror metal/fp8_mma.zig's Args"); #ifndef TF_RS #define TF_RS 4 // simdgroups a threadgroup, 8 rows each: they share the decoded 32x32 weight blocks of two K groups diff --git a/zig/kernels/metal/deepseek_v41/fp8_rows.metal b/zig/kernels/metal/deepseek_v41/fp8_rows.metal index de51361bb0c..137309205ba 100644 --- a/zig/kernels/metal/deepseek_v41/fp8_rows.metal +++ b/zig/kernels/metal/deepseek_v41/fp8_rows.metal @@ -37,6 +37,7 @@ using namespace metal; struct TfDsv41Fp8Args { uint K, N, R, groups, tiles, blocks; }; +static_assert(sizeof(TfDsv41Fp8Args) == 24, "TfDsv41Fp8Args must mirror metal/fp8_rows.zig's Args"); // Exact: the seven magnitude bits of E4M3 placed as a half's exponent and mantissa, then scaled by 2^8. inline float tf_dsv41_e4m3(uint code) { @@ -187,6 +188,7 @@ struct TfDsv41Fp8WArgs { uint K, N, R, groups, tiles, blocks; long xs, ws, ss, ys; // byte strides between the launches of a batch (grid y) }; +static_assert(sizeof(TfDsv41Fp8WArgs) == 56, "TfDsv41Fp8WArgs must mirror metal/fp8_rows.zig's WholeArgs"); // Part and finish in one group: simdgroup t is tile t of CL * NB columns; the roots meet in the same zero-padded tree. template diff --git a/zig/kernels/metal/deepseek_v41/fp8_tile.metal b/zig/kernels/metal/deepseek_v41/fp8_tile.metal index b8d9ea6fe27..08e1707bd59 100644 --- a/zig/kernels/metal/deepseek_v41/fp8_tile.metal +++ b/zig/kernels/metal/deepseek_v41/fp8_tile.metal @@ -10,6 +10,7 @@ struct TfDsv41Fp8TileArgs { uint K, N, R, groups, per, sgs; long xs, ws, ss, ys; // byte strides between the launches of a batch (grid y) }; +static_assert(sizeof(TfDsv41Fp8TileArgs) == 56, "TfDsv41Fp8TileArgs must mirror kernel_sources' tile arguments"); #define TF_TLD 36 // staged row stride of one column's 32 decoded K values (floats) #define TF_TLV 10 // pair-tree levels a simdgroup's slice holds (up to 512 groups) diff --git a/zig/kernels/metal/deepseek_v41/fused.metal b/zig/kernels/metal/deepseek_v41/fused.metal index b63de6e71cd..0dbda62ea52 100644 --- a/zig/kernels/metal/deepseek_v41/fused.metal +++ b/zig/kernels/metal/deepseek_v41/fused.metal @@ -1,4 +1,4 @@ -// DeepSeek V4.1 decode kernels that split or fuse the phase-1 glue launches, each keeping the glue's bits exactly. +// DeepSeek V4.1 decode kernels that split or fuse the row glue launches, each keeping the glue's bits exactly. #include using namespace metal; #pragma clang fp contract(off) @@ -15,7 +15,7 @@ inline float tf_f_in(float v) { return (TF_CTL == 1 && !isfinite(v)) ? 0.0f : v; inline float tf_f_run(float v) { return TF_CTL == 3 ? float(half(v)) : v; } -// A float's adjacent-lane butterfly: the same tree whatever the launch (glue_tmp's tf_g_tree). +// A float's adjacent-lane butterfly: the same tree whatever the launch (glue_rows's tf_g_tree). inline float tf_f_tree(float v) { for (ushort m = 1; m < 32; m *= 2) v += simd_shuffle_xor(v, m); return v; @@ -25,6 +25,7 @@ struct TfFHcArgs { uint dim, rows, iters; float eps, hc_eps, alpha; }; +static_assert(sizeof(TfFHcArgs) == 24, "TfFHcArgs must mirror metal/fused.zig's FhcArgs"); // The hc mix's sums by simdgroup: group (m, sg, row) is simdgroup sg of matvec m's 256-thread sum (m 24: squares). [[kernel, max_total_threads_per_threadgroup(32)]] void tf_dsv41_f_hcmix_part( @@ -58,7 +59,7 @@ struct TfFHcArgs { if (TF_CTL == 4 && lane == 0 && m == TF_F_MIX) P[(ulong(r) * (TF_F_MIX + 1u) + m + 1u) * TF_F_SG + sg] = 1.0f; // control 4: one partial past the row } -// glue_tmp's hcmix tail, a simdgroup a row: lane m holds mix m (lane 8 + 4j + k comb[j][k]), sums in the same order. +// glue_rows's hcmix tail, a simdgroup a row: lane m holds mix m (lane 8 + 4j + k comb[j][k]), sums in the same order. [[kernel, max_total_threads_per_threadgroup(32)]] void tf_dsv41_f_hcmix_fin( const device float* P [[buffer(0)]], const device float* SCALE [[buffer(1)]], const device float* BASE [[buffer(2)]], device float* PRE [[buffer(3)]], device float* POST [[buffer(4)]], device float* COMB [[buffer(5)]], @@ -98,7 +99,7 @@ struct TfFHcArgs { if (TF_CTL == 4 && L == 8) COMB[r * 16 + 16] = 1.0f; } -// glue_tmp's act_quant helpers, the same expressions. +// glue_rows's act_quant helpers, the same expressions. inline float tf_f_pow2(int e) { return as_type(uint(e + 127) << 23); } inline int tf_f_log2c(float v) { @@ -123,7 +124,7 @@ inline bfloat tf_f_actq(float v) { return bfloat(bad ? NAN : (signbit(v) ? -q : q)); } -// A threadgroup of 256's sum: each simdgroup's tree, then the eight in order (glue_tmp's tf_g_sum). +// A threadgroup of 256's sum: each simdgroup's tree, then the eight in order (glue_rows's tf_g_sum). inline float tf_f_sum(float v, threadgroup float* part, uint lane, uint sg) { v = tf_f_tree(v); threadgroup_barrier(mem_flags::mem_threadgroup); @@ -138,8 +139,9 @@ struct TfFNormArgs { uint dim, rows; float eps; }; +static_assert(sizeof(TfFNormArgs) == 12, "TfFNormArgs must mirror metal/fused.zig's NormArgs"); -// glue_tmp's (hcpre with COLLAPSE,) rmsnorm and actq of a row in a group of 256; dim a multiple of 32, <= 256 NV. +// glue_rows's (hcpre with COLLAPSE,) rmsnorm and actq of a row in a group of 256; dim a multiple of 32, <= 256 NV. template [[kernel, max_total_threads_per_threadgroup(256)]] void tf_dsv41_f_norm( const device bfloat* X [[buffer(0)]], const device float* PRE [[buffer(1)]], const device float* Wt [[buffer(2)]], @@ -199,8 +201,9 @@ struct TfFKvArgs { uint dim, rows, reps; float eps; }; +static_assert(sizeof(TfFKvArgs) == 16, "TfFKvArgs must mirror metal/fused.zig's KvArgs"); -// glue_tmp's rmsnorm, rope, actq and scatter of a window key row (dim 512) in a group of 256, into D[reps r + k]. +// glue_rows's rmsnorm, rope, actq and scatter of a window key row (dim 512) in a group of 256, into D[reps r + k]. inline void tf_f_kv_row(const device bfloat* X, const device float* Wt, device bfloat* KVN, device bfloat* KVR, device bfloat* KVQ, device bfloat* WIN, const device int* P, const device float* CS, const device int* D, constant TfFKvArgs& a, uint r, uint t, uint lane, uint sg, @@ -262,8 +265,9 @@ struct TfFSwiArgs { uint n; float limit; }; +static_assert(sizeof(TfFSwiArgs) == 8, "TfFSwiArgs must mirror metal/fused.zig's SwiArgs"); -// The shared expert's clamped SwiGLU (glue_tmp's swiglu) and its act_quant, a block of 32 a simdgroup; n % 32 == 0. +// The shared expert's clamped SwiGLU (glue_rows's swiglu) and its act_quant, a block of 32 a simdgroup; n % 32 == 0. kernel void tf_dsv41_f_swiglu(const device bfloat* G [[buffer(0)]], const device bfloat* U [[buffer(1)]], device bfloat* Y [[buffer(2)]], device bfloat* YQ [[buffer(3)]], constant TfFSwiArgs& a [[buffer(4)]], uint i [[thread_position_in_grid]]) { @@ -278,8 +282,9 @@ kernel void tf_dsv41_f_swiglu(const device bfloat* G [[buffer(0)]], const device struct TfFPostArgs { uint dim, rows; }; +static_assert(sizeof(TfFPostArgs) == 8, "TfFPostArgs must mirror metal/fused.zig's PostArgs"); -// The MoE join (routed fp32 plus shared bf16, one rounding, into B) and hc_post of it (glue_tmp's join and hcpost). +// The MoE join (routed fp32 plus shared bf16, one rounding, into B) and hc_post of it (glue_rows's join and hcpost). kernel void tf_dsv41_f_joinpost(const device float* RT [[buffer(0)]], const device bfloat* SH [[buffer(1)]], device bfloat* B [[buffer(2)]], const device bfloat* RES [[buffer(3)]], const device float* POST [[buffer(4)]], const device float* COMB [[buffer(5)]], @@ -351,8 +356,9 @@ template [[host_name("tf_dsv41_f_pre_a_v32")]] [[kernel]] decltype(tf_dsv41_f_pr struct TfFQuantArgs { uint k, nb, na, sa, sb, ta, tb; }; +static_assert(sizeof(TfFQuantArgs) == 28, "TfFQuantArgs must mirror metal/fused.zig's QuantArgs"); -// glue_tmp's actq a thread a value (its strides), a block of 32 on one simdgroup's lanes; k a multiple of 32. +// glue_rows's actq a thread a value (its strides), a block of 32 on one simdgroup's lanes; k a multiple of 32. kernel void tf_dsv41_f_actq(const device bfloat* X [[buffer(0)]], device bfloat* Y [[buffer(1)]], constant TfFQuantArgs& a [[buffer(2)]], uint3 g [[thread_position_in_grid]]) { if (g.x - g.x % 32u >= a.k || g.y >= a.nb || g.z >= a.na) return; diff --git a/zig/kernels/metal/deepseek_v41/gate_gemm.metal b/zig/kernels/metal/deepseek_v41/gate_gemm.metal new file mode 100644 index 00000000000..f6d4f0ffbc1 --- /dev/null +++ b/zig/kernels/metal/deepseek_v41/gate_gemm.metal @@ -0,0 +1,348 @@ +// The router gate's prefill GEMMs on the M5 tensor unit, including the fp32-destination entry route reads. +#include +using namespace metal; +typedef bfloat bfloat16_t; +typedef half float16_t; +#include "../nax.h" + +namespace tfp { + +// One 32-deep K step of a simdgroup's 32x32 block; kk is the step's K offset from A and B, kn the K values left there. +template +inline void gemm_step(thread frag (&acc)[2][2], const device T* A, const device T* B, int lda, int ldb, int kk, + int kn, int rows, int cols, short2 home) { + frag a[2][2], b[2][2]; // a[m][k], b[k][n]: 16x16 blocks of A and B in their stored orientation + TF_UNROLL + for (short i = 0; i < 2; i++) { + TF_UNROLL + for (short j = 0; j < 2; j++) { + const int ar = TA ? kk + 16 * j : 16 * i, ac = TA ? 16 * i : kk + 16 * j; + const int br = TB ? 16 * j : kk + 16 * i, bc = TB ? kk + 16 * i : 16 * j; +#ifdef TF_SIMD_FRAGS + // simdgroup matrices: a transposed operand loads with its stored rows on the column pattern + if (BOUND) { + if (TA) frag_get_t_in(a[i][j], A, lda, ar, ac, home, kk + kn, rows); + else frag_get_in(a[i][j], A, lda, ar, ac, home, rows, kk + kn); + if (TB) frag_get_t_in(b[i][j], B, ldb, br, bc, home, cols, kk + kn); + else frag_get_in(b[i][j], B, ldb, br, bc, home, kk + kn, cols); + } else { + if (TA) frag_get_t(a[i][j], A, lda, ar, ac, home); + else frag_get(a[i][j], A, lda, ar, ac, home); + if (TB) frag_get_t(b[i][j], B, ldb, br, bc, home); + else frag_get(b[i][j], B, ldb, br, bc, home); + } +#else + if (BOUND) { + frag_get_in(a[i][j], A, lda, ar, ac, home, TA ? kk + kn : rows, TA ? rows : kk + kn); + frag_get_in(b[i][j], B, ldb, br, bc, home, TB ? cols : kk + kn, TB ? kk + kn : cols); + } else { + frag_get(a[i][j], A, lda, ar, ac, home); + frag_get(b[i][j], B, ldb, br, bc, home); + } +#endif + } + } + TF_UNROLL + for (short m = 0; m < 2; m++) { + TF_UNROLL + for (short k = 0; k < 2; k++) { + mma_16x32(acc[m][0], acc[m][1], a[m][k], b[k][0], b[k][1]); + } + } +} + +// A simdgroup's 32x32 block over K: whole BK blocks first (barrier each), then 32-deep steps zero-padded past K. +template +inline void gemm_block(thread frag (&acc)[2][2], const device T* A, const device T* B, int lda, int ldb, + int K, int kblocks, int rows, int cols, short2 home) { + TF_UNROLL + for (short i = 0; i < 2; i++) { + TF_UNROLL + for (short j = 0; j < 2; j++) { + acc[i][j] = frag(0); + } + } + const bool live = rows > 0 && cols > 0; +#pragma clang loop unroll(disable) + for (int kb = 0; kb < kblocks; kb++) { + threadgroup_barrier(mem_flags::mem_none); + if (!FULL && !live) { + continue; + } +#pragma clang loop unroll(disable) + for (int kk = 0; kk < BK; kk += 32) { + gemm_step(acc, A, B, lda, ldb, kk, 32, rows, cols, home); + } + A += TA ? BK * lda : BK; + B += TB ? BK : BK * ldb; + } + const int rest = K - kblocks * BK; + if (rest > 0) { + simdgroup_barrier(mem_flags::mem_none); + if (!FULL && !live) { + return; + } +#pragma clang loop unroll(disable) + for (int kk = 0; kk < rest; kk += 32) { + gemm_step(acc, A, B, lda, ldb, kk, max(0, rest - kk), rows, cols, home); + } + } +} + +template +inline void gemm_store(thread const frag (&acc)[2][2], device O* D, int ldd, int rows, int cols, short2 home) { + TF_UNROLL + for (short i = 0; i < 2; i++) { + TF_UNROLL + for (short j = 0; j < 2; j++) { + if (FULL) { + frag_put(acc[i][j], D, ldd, 16 * i, 16 * j, home); + } else { + frag_put_in(acc[i][j], D, ldd, 16 * i, 16 * j, home, rows, cols); + } + } + } +} + +// D = A * B per batch, steel_gemm_fused_nax without epilogue; P holds the GEMM_PARAMS fields of check_prefill_ops. +template +inline void gemm_nax(const device T* A, const device T* B, device O* D, const device int* P, uint3 tg, uint sg, + uint lane) { + static_assert(BM / WM == 32 && BN / WN == 32, "a simdgroup owns a 32x32 block"); + const int swz = P[8]; + const int ty = (int(tg.y) << swz) + (int(tg.x) & ((1 << swz) - 1)), tx = int(tg.x) >> swz; + if (tx >= P[6] || ty >= P[7]) { + return; + } + const int lda = P[3], ldb = P[4], ldd = P[5]; + const int row = ty * BM + 32 * int(sg / WN), col = tx * BN + 32 * int(sg % WN); + A += long(P[13]) + long(P[10]) * tg.z + (TA ? long(row) : long(row) * lda); + B += long(P[14]) + long(P[11]) * tg.z + (TB ? long(col) * ldb : long(col)); + D += long(P[12]) * tg.z + long(row) * ldd + col; + const int rows = AM ? 32 : min(32, P[0] - row), cols = AN ? 32 : min(32, P[1] - col); + const bool full = (AM || rows == 32) && (AN || cols == 32); + const short2 home = frag_home(ushort(lane)); + frag acc[2][2]; + if (full) { + gemm_block(acc, A, B, lda, ldb, P[2], P[9], rows, cols, home); + gemm_store(acc, D, ldd, rows, cols, home); + } else { + gemm_block(acc, A, B, lda, ldb, P[2], P[9], rows, cols, home); + if (rows > 0 && cols > 0) { + gemm_store(acc, D, ldd, rows, cols, home); + } + } +} + +// One K partition's fp32 block, steel_gemm_splitk_nax; P holds the SPLITK_PARAMS fields of check_prefill_ops. +template +inline void gemm_splitk_nax(const device T* A, const device T* B, device float* C, const device int* P, uint3 tg, + uint sg, uint lane) { + static_assert(BM / WM == 32 && BN / WN == 32, "a simdgroup owns a 32x32 block"); + const int swz = P[11]; + const int span_n = P[6] << swz, span_m = (P[7] + (1 << swz) - 1) >> swz; + const int part = int(tg.x) / (span_n * span_m), at = int(tg.x) % (span_n * span_m); + const int gx = at % span_n, gy = at / span_n; + const int ty = (gy << swz) + (gx & ((1 << swz) - 1)), tx = gx >> swz; + if (tx >= P[6] || ty >= P[7]) { + return; + } + const int lda = P[3], ldb = P[4], ldc = P[5]; + const int k0 = P[10] * part, kn = min(k0 + P[10], P[2]) - k0; + const int row = ty * BM + 32 * int(sg / WN), col = tx * BN + 32 * int(sg % WN); + A += long(P[12]) + (TA ? long(row) + long(k0) * lda : long(k0) + long(row) * lda); + B += long(P[13]) + (TB ? long(k0) + long(col) * ldb : long(col) + long(k0) * ldb); + C += long(P[9]) * part + long(row) * ldc + col; + const int rows = AM ? 32 : min(32, P[0] - row), cols = AN ? 32 : min(32, P[1] - col); + const bool full = (AM || rows == 32) && (AN || cols == 32); + const short2 home = frag_home(ushort(lane)); + frag acc[2][2]; + if (full) { + gemm_block(acc, A, B, lda, ldb, kn, kn / BK, rows, cols, home); + gemm_store(acc, C, ldc, rows, cols, home); + } else { + gemm_block(acc, A, B, lda, ldb, kn, kn / BK, rows, cols, home); + gemm_store(acc, C, ldc, rows, cols, home); + } +} + +// D = the partitions' fp32 blocks summed in partition order from 0, steel_gemm_splitk_accum. P: parts stride ldd. +template +inline void gemm_splitk_sum(const device float* C, device O* D, const device int* P, uint3 at) { + const long i = long(at.x) + long(at.y) * P[2]; + float s = 0; + for (int p = 0; p < P[0]; p++) { + s += C[i + long(p) * P[1]]; + } + D[i] = O(s); +} + +} // namespace tfp +// ---- entry points: generated by tools/zig/check_prefill_ops.py --write ---- +[[max_total_threads_per_threadgroup(256)]] +[[kernel]] void custom_kernel_tf_gemm_nax_bf16_n_t_n_n_n_64_128_256_2_4_bfloat16_t_bfloat16_t_int32_t_bfloat16_t( + const device bfloat16_t* A [[buffer(0)]], + const device bfloat16_t* B [[buffer(1)]], + const device int32_t* P [[buffer(2)]], + device bfloat16_t* D [[buffer(3)]], + uint simdgroup_index_in_threadgroup [[simdgroup_index_in_threadgroup]], + uint thread_index_in_simdgroup [[thread_index_in_simdgroup]], + uint3 threadgroup_position_in_grid [[threadgroup_position_in_grid]]) { + tfp::gemm_nax(A, B, D, P, threadgroup_position_in_grid, simdgroup_index_in_threadgroup, thread_index_in_simdgroup); + +} +[[max_total_threads_per_threadgroup(256)]] +[[kernel]] void custom_kernel_tf_gemm_nax_bf16_n_t_n_t_n_64_128_256_2_4_bfloat16_t_bfloat16_t_int32_t_bfloat16_t( + const device bfloat16_t* A [[buffer(0)]], + const device bfloat16_t* B [[buffer(1)]], + const device int32_t* P [[buffer(2)]], + device bfloat16_t* D [[buffer(3)]], + uint simdgroup_index_in_threadgroup [[simdgroup_index_in_threadgroup]], + uint thread_index_in_simdgroup [[thread_index_in_simdgroup]], + uint3 threadgroup_position_in_grid [[threadgroup_position_in_grid]]) { + tfp::gemm_nax(A, B, D, P, threadgroup_position_in_grid, simdgroup_index_in_threadgroup, thread_index_in_simdgroup); + +} +// The same n_t_n_t_n block with an fp32 destination, so a consumer that reads fp32. +[[max_total_threads_per_threadgroup(256)]] +[[kernel]] void custom_kernel_tf_gemm_nax_bf16_f32out_n_t_n_t_n_64_128_256_2_4_bfloat16_t_bfloat16_t_int32_t_float( + const device bfloat16_t* A [[buffer(0)]], + const device bfloat16_t* B [[buffer(1)]], + const device int32_t* P [[buffer(2)]], + device float* D [[buffer(3)]], + uint simdgroup_index_in_threadgroup [[simdgroup_index_in_threadgroup]], + uint thread_index_in_simdgroup [[thread_index_in_simdgroup]], + uint3 threadgroup_position_in_grid [[threadgroup_position_in_grid]]) { + tfp::gemm_nax(A, B, D, P, threadgroup_position_in_grid, simdgroup_index_in_threadgroup, thread_index_in_simdgroup); + +} +// The f16 twin of the same block, fp32 destination. +[[max_total_threads_per_threadgroup(256)]] +[[kernel]] void custom_kernel_tf_gemm_nax_f16_f32out_n_t_n_t_n_64_128_256_2_4_float16_t_float16_t_int32_t_float( + const device float16_t* A [[buffer(0)]], + const device float16_t* B [[buffer(1)]], + const device int32_t* P [[buffer(2)]], + device float* D [[buffer(3)]], + uint simdgroup_index_in_threadgroup [[simdgroup_index_in_threadgroup]], + uint thread_index_in_simdgroup [[thread_index_in_simdgroup]], + uint3 threadgroup_position_in_grid [[threadgroup_position_in_grid]]) { + tfp::gemm_nax(A, B, D, P, threadgroup_position_in_grid, simdgroup_index_in_threadgroup, thread_index_in_simdgroup); + +} + +[[max_total_threads_per_threadgroup(256)]] +[[kernel]] void custom_kernel_tf_gemm_nax_bf16_n_t_t_n_n_64_128_256_2_4_bfloat16_t_bfloat16_t_int32_t_bfloat16_t( + const device bfloat16_t* A [[buffer(0)]], + const device bfloat16_t* B [[buffer(1)]], + const device int32_t* P [[buffer(2)]], + device bfloat16_t* D [[buffer(3)]], + uint simdgroup_index_in_threadgroup [[simdgroup_index_in_threadgroup]], + uint thread_index_in_simdgroup [[thread_index_in_simdgroup]], + uint3 threadgroup_position_in_grid [[threadgroup_position_in_grid]]) { + tfp::gemm_nax(A, B, D, P, threadgroup_position_in_grid, simdgroup_index_in_threadgroup, thread_index_in_simdgroup); + +} +[[max_total_threads_per_threadgroup(256)]] +[[kernel]] void custom_kernel_tf_gemm_nax_bf16_n_t_t_t_n_64_128_256_2_4_bfloat16_t_bfloat16_t_int32_t_bfloat16_t( + const device bfloat16_t* A [[buffer(0)]], + const device bfloat16_t* B [[buffer(1)]], + const device int32_t* P [[buffer(2)]], + device bfloat16_t* D [[buffer(3)]], + uint simdgroup_index_in_threadgroup [[simdgroup_index_in_threadgroup]], + uint thread_index_in_simdgroup [[thread_index_in_simdgroup]], + uint3 threadgroup_position_in_grid [[threadgroup_position_in_grid]]) { + tfp::gemm_nax(A, B, D, P, threadgroup_position_in_grid, simdgroup_index_in_threadgroup, thread_index_in_simdgroup); + +} +[[max_total_threads_per_threadgroup(256)]] +[[kernel]] void custom_kernel_tf_gemm_nax_f32_n_n_n_n_n_64_128_256_2_4_float_float_int32_t_float( + const device float* A [[buffer(0)]], + const device float* B [[buffer(1)]], + const device int32_t* P [[buffer(2)]], + device float* D [[buffer(3)]], + uint simdgroup_index_in_threadgroup [[simdgroup_index_in_threadgroup]], + uint thread_index_in_simdgroup [[thread_index_in_simdgroup]], + uint3 threadgroup_position_in_grid [[threadgroup_position_in_grid]]) { + tfp::gemm_nax(A, B, D, P, threadgroup_position_in_grid, simdgroup_index_in_threadgroup, thread_index_in_simdgroup); + +} +[[max_total_threads_per_threadgroup(256)]] +[[kernel]] void custom_kernel_tf_gemm_nax_f32_n_n_t_n_n_64_128_256_2_4_float_float_int32_t_float( + const device float* A [[buffer(0)]], + const device float* B [[buffer(1)]], + const device int32_t* P [[buffer(2)]], + device float* D [[buffer(3)]], + uint simdgroup_index_in_threadgroup [[simdgroup_index_in_threadgroup]], + uint thread_index_in_simdgroup [[thread_index_in_simdgroup]], + uint3 threadgroup_position_in_grid [[threadgroup_position_in_grid]]) { + tfp::gemm_nax(A, B, D, P, threadgroup_position_in_grid, simdgroup_index_in_threadgroup, thread_index_in_simdgroup); + +} +[[max_total_threads_per_threadgroup(256)]] +[[kernel]] void custom_kernel_tf_gemm_nax_f32_n_n_t_n_t_64_128_256_2_4_float_float_int32_t_float( + const device float* A [[buffer(0)]], + const device float* B [[buffer(1)]], + const device int32_t* P [[buffer(2)]], + device float* D [[buffer(3)]], + uint simdgroup_index_in_threadgroup [[simdgroup_index_in_threadgroup]], + uint thread_index_in_simdgroup [[thread_index_in_simdgroup]], + uint3 threadgroup_position_in_grid [[threadgroup_position_in_grid]]) { + tfp::gemm_nax(A, B, D, P, threadgroup_position_in_grid, simdgroup_index_in_threadgroup, thread_index_in_simdgroup); + +} +[[max_total_threads_per_threadgroup(256)]] +[[kernel]] void custom_kernel_tf_gemm_nax_f32_t_t_t_t_n_64_128_256_2_4_float_float_int32_t_float( + const device float* A [[buffer(0)]], + const device float* B [[buffer(1)]], + const device int32_t* P [[buffer(2)]], + device float* D [[buffer(3)]], + uint simdgroup_index_in_threadgroup [[simdgroup_index_in_threadgroup]], + uint thread_index_in_simdgroup [[thread_index_in_simdgroup]], + uint3 threadgroup_position_in_grid [[threadgroup_position_in_grid]]) { + tfp::gemm_nax(A, B, D, P, threadgroup_position_in_grid, simdgroup_index_in_threadgroup, thread_index_in_simdgroup); + +} +[[max_total_threads_per_threadgroup(256)]] +[[kernel]] void custom_kernel_tf_gemm_nax_f32_t_t_t_t_t_64_128_256_2_4_float_float_int32_t_float( + const device float* A [[buffer(0)]], + const device float* B [[buffer(1)]], + const device int32_t* P [[buffer(2)]], + device float* D [[buffer(3)]], + uint simdgroup_index_in_threadgroup [[simdgroup_index_in_threadgroup]], + uint thread_index_in_simdgroup [[thread_index_in_simdgroup]], + uint3 threadgroup_position_in_grid [[threadgroup_position_in_grid]]) { + tfp::gemm_nax(A, B, D, P, threadgroup_position_in_grid, simdgroup_index_in_threadgroup, thread_index_in_simdgroup); + +} +[[max_total_threads_per_threadgroup(128)]] +[[kernel]] void custom_kernel_tf_gemm_splitk_nax_bf16_n_t_n_t_64_64_256_2_2_bfloat16_t_bfloat16_t_int32_t_float( + const device bfloat16_t* A [[buffer(0)]], + const device bfloat16_t* B [[buffer(1)]], + const device int32_t* P [[buffer(2)]], + device float* C [[buffer(3)]], + uint simdgroup_index_in_threadgroup [[simdgroup_index_in_threadgroup]], + uint thread_index_in_simdgroup [[thread_index_in_simdgroup]], + uint3 threadgroup_position_in_grid [[threadgroup_position_in_grid]]) { + tfp::gemm_splitk_nax(A, B, C, P, threadgroup_position_in_grid, simdgroup_index_in_threadgroup, thread_index_in_simdgroup); + +} +[[max_total_threads_per_threadgroup(128)]] +[[kernel]] void custom_kernel_tf_gemm_splitk_nax_bf16_n_t_t_t_64_64_256_2_2_bfloat16_t_bfloat16_t_int32_t_float( + const device bfloat16_t* A [[buffer(0)]], + const device bfloat16_t* B [[buffer(1)]], + const device int32_t* P [[buffer(2)]], + device float* C [[buffer(3)]], + uint simdgroup_index_in_threadgroup [[simdgroup_index_in_threadgroup]], + uint thread_index_in_simdgroup [[thread_index_in_simdgroup]], + uint3 threadgroup_position_in_grid [[threadgroup_position_in_grid]]) { + tfp::gemm_splitk_nax(A, B, C, P, threadgroup_position_in_grid, simdgroup_index_in_threadgroup, thread_index_in_simdgroup); + +} +[[kernel]] void custom_kernel_tf_gemm_splitk_sum_bf16_float_int32_t_bfloat16_t( + const device float* C [[buffer(0)]], + const device int32_t* P [[buffer(1)]], + device bfloat16_t* D [[buffer(2)]], + uint3 thread_position_in_grid [[thread_position_in_grid]]) { + tfp::gemm_splitk_sum(C, D, P, thread_position_in_grid); + +} diff --git a/zig/kernels/metal/deepseek_v41/glue.metal b/zig/kernels/metal/deepseek_v41/glue.metal index ea5f085f510..8b9c36d568a 100644 --- a/zig/kernels/metal/deepseek_v41/glue.metal +++ b/zig/kernels/metal/deepseek_v41/glue.metal @@ -8,10 +8,15 @@ using namespace metal; #endif struct TfRmsArgs { uint D, R; float eps; }; +static_assert(sizeof(TfRmsArgs) == 12, "TfRmsArgs must mirror metal/glue_k.zig's RmsArgs"); struct TfEmbedArgs { uint D, R, V, reps; int lo; }; +static_assert(sizeof(TfEmbedArgs) == 20, "TfEmbedArgs must mirror metal/glue_k.zig's EmbedArgs"); struct TfMeanArgs { uint D, R, hc; }; +static_assert(sizeof(TfMeanArgs) == 12, "TfMeanArgs must mirror metal/glue_k.zig's MeanArgs"); struct TfRopeArgs { uint R, H, pairs, ldx, hx, ox, ldy, hy, oy; }; +static_assert(sizeof(TfRopeArgs) == 36, "TfRopeArgs must mirror metal/glue_k.zig's RopeArgs"); struct TfQuantArgs { uint N, R; }; +static_assert(sizeof(TfQuantArgs) == 8, "TfQuantArgs must mirror metal/glue_k.zig's QuantArgs"); // Control 1 of every kernel: a non-finite input is read as 0, so the output class changes. inline float tf_g_in(float v) { return (TF_CTL == 1 && !isfinite(v)) ? 0.0f : v; } diff --git a/zig/kernels/metal/deepseek_v41/glue_tmp.metal b/zig/kernels/metal/deepseek_v41/glue_rows.metal similarity index 93% rename from zig/kernels/metal/deepseek_v41/glue_tmp.metal rename to zig/kernels/metal/deepseek_v41/glue_rows.metal index 4e24a6fa386..8d935e9cd1f 100644 --- a/zig/kernels/metal/deepseek_v41/glue_tmp.metal +++ b/zig/kernels/metal/deepseek_v41/glue_rows.metal @@ -1,4 +1,4 @@ -// DeepSeek V4.1's phase-1 glue on Metal, the bits glue.metal, compress.metal and the fused kernels are checked against. +// DeepSeek V4.1's row glue on Metal, the bits glue.metal, compress.metal and the fused kernels are checked against. #include using namespace metal; #pragma clang fp contract(off) @@ -71,6 +71,7 @@ struct TfGNormArgs { uint dim, in_stride, out_stride; float eps; }; +static_assert(sizeof(TfGNormArgs) == 16, "TfGNormArgs must mirror metal/glue.zig's GNormArgs"); // RMSNorm of a bf16 row: x * rsqrt(mean(x^2) + eps), times the fp32 weight, rounded to bf16 once. kernel void tf_dsv41_g_rmsnorm(const device bfloat* X [[buffer(0)]], const device float* Wt [[buffer(1)]], @@ -91,6 +92,7 @@ kernel void tf_dsv41_g_rmsnorm(const device bfloat* X [[buffer(0)]], const devic struct TfGRopeArgs { uint pairs, heads, head_stride, row_stride, off, positions; }; +static_assert(sizeof(TfGRopeArgs) == 24, "TfGRopeArgs must mirror metal/glue.zig's GRopeArgs"); // A head copied with its dims from `off` on rotated by the table at the row's position (pairs as complex numbers). kernel void tf_dsv41_g_rope(const device bfloat* X [[buffer(0)]], device bfloat* Y [[buffer(1)]], @@ -116,6 +118,7 @@ kernel void tf_dsv41_g_rope(const device bfloat* X [[buffer(0)]], device bfloat* struct TfGFp4Args { uint blocks, in_stride, code_row, scale_row, scale_off, use_dest; }; +static_assert(sizeof(TfGFp4Args) == 24, "TfGFp4Args must mirror metal/glue.zig's GFp4Args"); // fp4_act_quant's packing: E2M1 codes (low nibble first) over a power-of-two scale a 32-value block; dest < 0 skips. kernel void tf_dsv41_g_fp4pack(const device bfloat* X [[buffer(0)]], device uchar* C [[buffer(1)]], @@ -142,6 +145,7 @@ kernel void tf_dsv41_g_fp4pack(const device bfloat* X [[buffer(0)]], device ucha struct TfGFp4RtArgs { uint blocks, in_stride, out_row; }; +static_assert(sizeof(TfGFp4RtArgs) == 12, "TfGFp4RtArgs must mirror metal/glue.zig's GFp4RtArgs"); // The compressed KV's round trip: E2M1 over an E4M3 scale a 16-value block, back to bf16 at row dest (< 0 skips). kernel void tf_dsv41_g_fp4rt(const device bfloat* X [[buffer(0)]], device bfloat* Y [[buffer(1)]], @@ -165,6 +169,7 @@ kernel void tf_dsv41_g_fp4rt(const device bfloat* X [[buffer(0)]], device bfloat struct TfGPoolArgs { uint rows, dim; }; +static_assert(sizeof(TfGPoolArgs) == 8, "TfGPoolArgs must mirror metal/glue.zig's GPoolArgs"); // The ratio-2 compressor over a launch's rows in order: each row fills slot pos % 2, an odd position pools both slots. kernel void tf_dsv41_g_pool2(const device float* KV [[buffer(0)]], const device float* SC [[buffer(1)]], @@ -192,6 +197,7 @@ kernel void tf_dsv41_g_pool2(const device float* KV [[buffer(0)]], const device struct TfGMvArgs { uint k, n; }; +static_assert(sizeof(TfGMvArgs) == 8, "TfGMvArgs must keep its 8-byte (k, n) pair (glue_rows's own mv kernel)"); // A bf16-weight matvec, one simdgroup an output: lane chains over K in steps of 32, then the butterfly. template @@ -215,6 +221,7 @@ template [[host_name("tf_dsv41_g_mv_bf16")]] [[kernel]] decltype(tf_dsv41_g_mv +using namespace metal; + +constant constexpr int kCopies = 4; // hc_mult +constant constexpr int kWidth = 5120; // one copy's width +constant constexpr int kStream = kCopies * kWidth; // the flattened hc stream +constant constexpr int kMixes = (2 + kCopies) * kCopies; // pre, post and the comb cells +constant constexpr int kSlices = kStream / 1024; // the mix projection's column slices +constant constexpr int kParts = kMixes + 1; // the mixes and the stream's squares + +struct HcArgs { float eps; float hc_eps; int iters; }; +static_assert(sizeof(HcArgs) == 12, "HcArgs must mirror mhc.zig's BoundaryArgs"); + +inline float hc_round(float v) { return float(bfloat(v)); } + +// One thread's four adjacent columns of a slice: the stream's squares and its products against the 24 hc_fn rows. +inline void hc_mix_column(const float* v, const device float* fn, int col, float* out) { + out[kMixes] = v[0] * v[0] + v[1] * v[1] + v[2] * v[2] + v[3] * v[3]; + for (int q = 0; q < kMixes; q++) { + const device float* f = fn + size_t(q) * kStream + col; + out[q] = f[0] * v[0] + f[1] * v[1] + f[2] * v[2] + f[3] * v[3]; + } +} + +// A slice's reduction: the warp sums, then the first kParts threads add the eight warps in index order and publish. +inline void hc_publish_slice(threadgroup float* warp, device float* part, const float* m, + uint lane, uint sg, uint t, uint r, uint j) { + for (int q = 0; q <= kMixes; q++) { + const float s = simd_sum(m[q]); + if (lane == 0) warp[sg * kParts + q] = s; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (int(t) <= kMixes) { + float s = 0.0f; + for (int k = 0; k < 8; k++) s += warp[k * kParts + int(t)]; + part[(size_t(r) * kSlices + j) * kParts + t] = s; + } +} + +// The mix projection's partials: a threadgroup a (1024-column slice, row), 256 threads, four columns a thread. +[[kernel]] void tf_hc_mix_part(const device bfloat* X [[buffer(0)]], const device float* FN [[buffer(1)]], + device float* PART [[buffer(2)]], uint2 tg [[threadgroup_position_in_grid]], + uint2 tpos [[thread_position_in_threadgroup]], uint lane [[thread_index_in_simdgroup]], + uint sg [[simdgroup_index_in_threadgroup]]) { + threadgroup float warp[8 * kParts]; + const int j = int(tg.x), r = int(tg.y); + const uint t = tpos.x; + const int col = 1024 * j + 4 * int(t); + const device bfloat* x = X + size_t(r) * kStream + col; + float v[4]; + for (int i = 0; i < 4; i++) v[i] = float(x[i]); + float parts[kParts]; + hc_mix_column(v, FN, col, parts); + hc_publish_slice(&warp[0], PART, parts, lane, sg, t, uint(r), uint(j)); +} + +// The pending branch into XO (the release's hc_post) and the same slice partials from the bf16 written. +[[kernel]] void tf_hc_expand_mix(const device bfloat* X [[buffer(0)]], const device bfloat* BR [[buffer(1)]], + const device float* POST [[buffer(2)]], const device float* COMB [[buffer(3)]], + const device float* FN [[buffer(4)]], device float* PART [[buffer(5)]], + device bfloat* XO [[buffer(6)]], uint2 tg [[threadgroup_position_in_grid]], + uint2 tpos [[thread_position_in_threadgroup]], uint lane [[thread_index_in_simdgroup]], + uint sg [[simdgroup_index_in_threadgroup]]) { + threadgroup float warp[8 * kParts]; + const int j = int(tg.x), r = int(tg.y); + const uint t = tpos.x; + const int col = 1024 * j + 4 * int(t); + const int k = col / kWidth, d0 = col % kWidth; + const device bfloat* x = X + size_t(r) * kStream; + const device float* comb = COMB + r * kCopies * kCopies; + float v[4]; + for (int i = 0; i < 4; i++) { + const int d = d0 + i; + const float branch = float(BR[size_t(r) * kWidth + d]); + float stream[kCopies]; + for (int jj = 0; jj < kCopies; jj++) stream[jj] = float(x[jj * kWidth + d]); + float mixed = 0.0f; + for (int jj = 0; jj < kCopies; jj++) mixed += comb[jj * kCopies + k] * stream[jj]; + const bfloat out = bfloat(POST[r * kCopies + k] * branch + mixed); + XO[size_t(r) * kStream + col + i] = out; + v[i] = float(out); + } + float parts[kParts]; + hc_mix_column(v, FN, col, parts); + hc_publish_slice(&warp[0], PART, parts, lane, sg, t, uint(r), uint(j)); +} + +// The release's split (kernel.py hc_split_sinkhorn_kernel): lanes 0-3 carry pre and post. +inline void hc_split_row(threadgroup const float* tot, constant const HcArgs& a, + const device float* base, const device float* scale, uint lane, uint r, + device float* pre_out, device float* post_out, device float* comb_out) { + const float rstd = precise::rsqrt(tot[kMixes] / float(kStream) + a.eps); + if (lane < uint(kCopies)) { + pre_out[r * kCopies + lane] = + 1.0f / (1.0f + precise::exp(-(tot[lane] * rstd * scale[0] + base[lane]))) + a.hc_eps; + post_out[r * kCopies + lane] = + 2.0f / (1.0f + precise::exp(-(tot[kCopies + lane] * rstd * scale[1] + base[kCopies + lane]))); + } + const bool live = lane < uint(kCopies * kCopies); + const uint cell = live ? lane : 0; + const float z = tot[2 * kCopies + cell] * rstd * scale[2] + base[2 * kCopies + cell]; + float top = max(z, simd_shuffle_xor(z, ushort(1))); + top = max(top, simd_shuffle_xor(top, ushort(2))); + const float e = precise::exp(z - top); + // Match the unfused split's FP32 butterfly: row XOR 2,1; column XOR 8,4. + float row = e + simd_shuffle_xor(e, ushort(2)); + row = row + simd_shuffle_xor(row, ushort(1)); + float comb = live ? e / row + a.hc_eps : 0.0f; + for (uint it = 0; it < uint(a.iters); it++) { + if (it > 0) { + float row_sum = comb + simd_shuffle_xor(comb, ushort(2)); + row_sum = row_sum + simd_shuffle_xor(row_sum, ushort(1)); + comb = live ? comb / (row_sum + a.hc_eps) : 0.0f; + } + float col_sum = comb + simd_shuffle_xor(comb, ushort(8)); + col_sum = col_sum + simd_shuffle_xor(col_sum, ushort(4)); + comb = live ? comb / (col_sum + a.hc_eps) : 0.0f; + } + if (live) comb_out[r * kCopies * kCopies + lane] = comb; +} + +// A threadgroup a row, 1024 threads: the split, collapse and norm; MIXES=false consumes a pre made elsewhere. +template +[[kernel]] void tf_hc_boundary(const device bfloat* X [[buffer(0)]], const device float* PART [[buffer(1)]], + const device float* BASE [[buffer(2)]], const device float* SCALE [[buffer(3)]], + const device float* PRE_IN [[buffer(4)]], const device bfloat* NORMW [[buffer(5)]], + constant HcArgs& a [[buffer(6)]], device float* PRE_OUT [[buffer(7)]], + device float* POST_OUT [[buffer(8)]], device float* COMB_OUT [[buffer(9)]], + device bfloat* NORMED [[buffer(10)]], uint r [[threadgroup_position_in_grid]], + uint t [[thread_position_in_threadgroup]], uint lane [[thread_index_in_simdgroup]], + uint sg [[simdgroup_index_in_threadgroup]]) { + threadgroup float sums[32]; + threadgroup float slice[kParts]; + threadgroup float pre[kCopies]; + const device bfloat* x = X + size_t(r) * kStream; + // The slices' totals beside the lagged collapse, which overlaps the norm's reduction. + if (MIXES && int(t) <= kMixes) { + float s = 0.0f; + for (int j = 0; j < kSlices; j++) s += PART[(size_t(r) * kSlices + j) * kParts + t]; + slice[t] = s; + } + if (t < uint(kCopies)) pre[t] = PRE_IN[r * kCopies + t]; + threadgroup_barrier(mem_flags::mem_threadgroup); + float y[5]; + float squares = 0.0f; + for (int i = 0; i < 5; i++) { + const int d = int(t) + 1024 * i; + float v = 0.0f; + for (int s = 0; s < kCopies; s++) v += pre[s] * float(x[s * kWidth + d]); + y[i] = hc_round(v); + squares += y[i] * y[i]; + } + const float lane_squares = simd_sum(squares); + if (lane == 0) sums[sg] = lane_squares; + threadgroup_barrier(mem_flags::mem_threadgroup); + if (MIXES && sg == 0) hc_split_row(&slice[0], a, BASE, SCALE, lane, r, PRE_OUT, POST_OUT, COMB_OUT); + if (t == 32) { // simdgroup 1, while simdgroup 0 runs the split + float s = 0.0f; + for (int k = 0; k < 32; k++) s += sums[k]; + pre[0] = precise::rsqrt(s / float(kWidth) + a.eps); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + const float inv = pre[0]; + for (int i = 0; i < 5; i++) { + const int d = int(t) + 1024 * i; + NORMED[size_t(r) * kWidth + d] = bfloat(float(NORMW[d]) * (y[i] * inv)); + } +} + +template [[host_name("tf_hc_boundary_mix")]] [[kernel]] decltype(tf_hc_boundary) tf_hc_boundary; +template [[host_name("tf_hc_boundary_plain")]] [[kernel]] decltype(tf_hc_boundary) tf_hc_boundary; + +// The launch-overhead probe: a work-free dispatch that reads the boundary's own partial sums and writes them back. +kernel void tf_hc_probe(const device float *part [[buffer(0)]], device float *sink [[buffer(1)]], + uint g [[threadgroup_position_in_grid]], uint tid [[thread_index_in_threadgroup]]) { + const uint at = g * (kSlices * kParts) + tid; + if (tid <= uint(kMixes)) sink[at] = part[at]; +} + +// The independent form of the probe: each dispatch has its own sink, so the chain carries no memory dependency. +kernel void tf_hc_probe_indep(const device float *part [[buffer(0)]], device float *sink [[buffer(1)]], + uint g [[threadgroup_position_in_grid]], uint tid [[thread_index_in_threadgroup]]) { + if (tid <= uint(kMixes)) sink[tid] = part[tid]; +} diff --git a/zig/kernels/metal/deepseek_v41/index.metal b/zig/kernels/metal/deepseek_v41/index.metal index 4a45dd19e25..310a9f8a8d6 100644 --- a/zig/kernels/metal/deepseek_v41/index.metal +++ b/zig/kernels/metal/deepseek_v41/index.metal @@ -23,6 +23,7 @@ struct TfDsv41IxArgs { uint rows, keys, start, ratio, chunk, out_stride, w_stride, ik_stride, mask_stride; float w_scale; // softmax_scale * n_heads^-0.5 (model.py:556, 513): scales each bf16 weight once, in fp32 }; +static_assert(sizeof(TfDsv41IxArgs) == 40, "TfDsv41IxArgs must mirror metal/index.zig's Args"); // One E2M1 code by its bit fields: 0, 0.5, 1, 1.5, 2, 3, 4, 6 and their negatives (the format has no NaN or infinity). static inline float tf_ix_e2m1(const uint c) { diff --git a/zig/kernels/metal/deepseek_v41/index_exl3.metal b/zig/kernels/metal/deepseek_v41/index_exl3.metal new file mode 100644 index 00000000000..d2a87b98518 --- /dev/null +++ b/zig/kernels/metal/deepseek_v41/index_exl3.metal @@ -0,0 +1,264 @@ +// Source is compiled after kv.metal; no query-by-key-by-head score tensor is materialized. +#include "../nax.h" +using namespace tfp; +struct Dsv41Index { + uint rows, heads, width, q_stride, weight_stride, position, ratio, keys, key_stride; + uint tile_start, tile_width, topk, candidate_topk, block_size, use_candidates, make_candidates; + // `layer`/`skip_mask` sit before `scale`; leaving them out made `scale` read `layer`'s bits and every score 0.0. + uint layer, skip_mask; + // 0 = the heap path's per-row score slots (row * tile_width), 1 = the decode select's tile-major ones. + uint score_layout; + float scale; +}; +static_assert(sizeof(Dsv41Index) == 80, "Dsv41Index must mirror csa2_index.zig's Params"); + +// A key's score slot: the heap path keeps one tile a row, the decode select keeps every tile. +inline device float *dsv41_score_slot(device float *scores, constant Dsv41Index &p, uint row, uint tile) { + if (p.score_layout == 0u) return scores + size_t(row) * p.tile_width; + return scores + (size_t(tile) * p.rows + row) * p.tile_width; +} + +inline const device float *dsv41_score_slot_ro(const device float *scores, constant Dsv41Index &p, uint row, uint tile) { + if (p.score_layout == 0u) return scores + size_t(row) * p.tile_width; + return scores + (size_t(tile) * p.rows + row) * p.tile_width; +} + +// The fp32 score's monotone 32-bit image: float order == uint order. +inline uint dsv41_index_mono(float s) { + const uint b = as_type(s == 0.0f ? 0.0f : s); + return (b & 0x80000000u) ? ~b : (b | 0x80000000u); +} +struct Dsv41Pick { float score; int position; }; +static_assert(sizeof(Dsv41Pick) == 8, "Dsv41Pick must keep its 8-byte (float score, int position) record"); +inline bool dsv41_less(Dsv41Pick a, Dsv41Pick b) { + return a.score < b.score || (a.score == b.score && a.position > b.position); +} +inline void dsv41_heap(device Dsv41Pick *h, uint size, Dsv41Pick v) { + if (!dsv41_less(h[0], v)) return; + uint at = 0; + while (2 * at + 1 < size) { + uint child = 2 * at + 1; + if (child + 1 < size && dsv41_less(h[child + 1], h[child])) ++child; + if (!dsv41_less(h[child], v)) break; + h[at] = h[child]; at = child; + } + h[at] = v; +} +inline int dsv41_index_position(uint local, uint row, device const Dsv41Pick *candidates, + constant Dsv41Index &p) { + uint slot = p.tile_start + local; + if (!p.use_candidates) return int(slot); + uint block = slot / p.block_size; + if (block >= p.candidate_topk) return -1; + int id = candidates[row * p.candidate_topk + block].position; + return id < 0 ? -1 : id * int(p.block_size) + int(slot % p.block_size); +} +kernel void dsv41_index_score(device const ushort *q [[buffer(0)]], device const ushort *weight [[buffer(1)]], + device const uchar *key [[buffer(2)]], device const Dsv41Pick *candidates [[buffer(3)]], + device float *scores [[buffer(4)]], constant Dsv41Index &p [[buffer(5)]], + uint3 g [[threadgroup_position_in_grid]], uint tid [[thread_index_in_threadgroup]], + uint3 tptg [[threads_per_threadgroup]]) { + const uint warps = tptg.x / 32u, lane = tid % 32u; + // The query's scaled per-head weights do not depend on the key. + threadgroup float scaled[64]; + const uint row = g.y; + if (tid < min(p.heads, 64u)) + scaled[tid] = dsv41_bf(dsv41_round(dsv41_bf(weight[row * p.weight_stride + tid]) * p.scale)); + threadgroup_barrier(mem_flags::mem_threadgroup); + uint local = g.x * warps + tid / 32u; + if (local >= p.tile_width || row >= p.rows) return; + int pos = dsv41_index_position(local, row, candidates, p); + uint visible = min(p.keys, (p.position + row + 1) / p.ratio); + if (pos < 0 || uint(pos) >= visible) { + if (lane == 0) *(dsv41_score_slot(scores, p, row, p.tile_start / p.tile_width) + local) = -INFINITY; + return; + } + device const uchar *k = key + uint(pos) * p.key_stride; + float key_values[4]; + for (uint d = 0; d < p.width / 32; ++d) key_values[d] = dsv41_unpack(k, lane + 32 * d, p.width, 32, 2); + float total = 0; + for (uint head = 0; head < p.heads; ++head) { + float dot = 0; + for (uint d = 0; d < p.width / 32; ++d) + dot += dsv41_bf(q[row * p.q_stride + head * p.width + lane + 32 * d]) * key_values[d]; + dot = dsv41_bf(dsv41_round(simd_sum(dot))); + total += dsv41_bf(dsv41_round(max(dot, 0.0f) * scaled[head])); + } + if (lane == 0) *(dsv41_score_slot(scores, p, row, p.tile_start / p.tile_width) + local) = dsv41_bf(dsv41_round(total)); +} +// The index keys a layer scores, decoded from the packed fp4 cache once into bf16 rows of p.width. +kernel void dsv41_index_keys_dense(device const uchar *key [[buffer(0)]], device ushort *dense [[buffer(1)]], + constant Dsv41Index &p [[buffer(2)]], uint i [[thread_position_in_grid]]) { + const uint total = p.keys * (p.width / 2u); + if (i >= total) return; + const uint k = i / (p.width / 2u), n = i % (p.width / 2u); // a thread a 2-value byte pair + const device uchar *row = key + uint(k) * p.key_stride; + device ushort *out = dense + uint(k) * p.width + 2u * n; + out[0] = ushort(as_type(bfloat(dsv41_unpack(row, 2u * n, p.width, 32, 2)))); + out[1] = ushort(as_type(bfloat(dsv41_unpack(row, 2u * n + 1u, p.width, 32, 2)))); +} + +// Every visible key is selected: no more compressed keys than the selection keeps. +kernel void dsv41_index_identity(device int *positions [[buffer(0)]], constant Dsv41Index &p [[buffer(1)]], + uint2 i [[thread_position_in_grid]]) { + if (i.y >= p.rows || i.x >= p.topk) return; + const uint visible = min(p.keys, (p.position + i.y + 1) / p.ratio); + positions[i.y * p.topk + i.x] = i.x < visible ? int(i.x) : -1; +} +kernel void dsv41_index_clear(device Dsv41Pick *top [[buffer(0)]], device Dsv41Pick *candidate [[buffer(1)]], + constant Dsv41Index &p [[buffer(2)]], uint2 i [[thread_position_in_grid]]) { + if (i.y >= p.rows) return; + if (i.x < p.topk) top[i.y * p.topk + i.x] = {-INFINITY, -1}; + if (p.make_candidates && i.x < p.candidate_topk) candidate[i.y * p.candidate_topk + i.x] = {-INFINITY, -1}; +} +kernel void dsv41_index_merge(device const float *scores [[buffer(0)]], device Dsv41Pick *top [[buffer(1)]], + device Dsv41Pick *candidate [[buffer(2)]], constant Dsv41Index &p [[buffer(3)]], + uint row [[thread_position_in_grid]]) { + if (row >= p.rows) return; + device Dsv41Pick *heap = top + row * p.topk; + // Only the tile's visible keys exist; the rest of the width holds -INFINITY and the heap ignores those anyway. + const uint visible = min(p.keys, (p.position + row + 1) / p.ratio); + const uint have = visible > p.tile_start ? min(p.tile_width, visible - p.tile_start) : 0u; + for (uint i = 0; i < have; ++i) { + float score = scores[row * p.tile_width + i]; + int pos = dsv41_index_position(i, row, candidate, p); + if (isfinite(score)) dsv41_heap(heap, p.topk, {score, pos}); + } + if (!p.make_candidates) return; + device Dsv41Pick *blocks = candidate + row * p.candidate_topk; + for (uint base = 0; base < have; base += p.block_size) { + float score = -INFINITY; + for (uint j = 0; j < p.block_size; ++j) score = max(score, scores[row * p.tile_width + base + j]); + uint block = (p.tile_start + base) / p.block_size; + if (visible && block == (visible - 1) / p.block_size) score = INFINITY; + if (score > -INFINITY) dsv41_heap(blocks, p.candidate_topk, {score, int(block)}); + } +} +// One thread a row: fill an empty heap from the tile's first keys and publish where to resume. +kernel void dsv41_index_seed(device const float *scores [[buffer(0)]], device Dsv41Pick *top [[buffer(1)]], + device Dsv41Pick *candidate [[buffer(2)]], device uint *seed_end [[buffer(3)]], + constant Dsv41Index &p [[buffer(4)]], uint row [[thread_position_in_grid]]) { + if (row >= p.rows) return; + device Dsv41Pick *heap = top + row * p.topk; + const uint visible = min(p.keys, (p.position + row + 1) / p.ratio); + const uint have = visible > p.tile_start ? min(p.tile_width, visible - p.tile_start) : 0u; + uint at = 0; + if (heap[0].position < 0) { // the clear kernel's empty state: fill it + uint filled = 0; + while (at < have && filled < p.topk) { + const float score = scores[row * p.tile_width + at]; + const int pos = dsv41_index_position(at, row, candidate, p); + if (isfinite(score) && pos >= 0) { + dsv41_heap(heap, p.topk, {score, pos}); + ++filled; + } + ++at; + } + } + seed_end[row] = at; +} + +// One thread a key: the merge's scan, in parallel. +kernel void dsv41_index_filter(device const float *scores [[buffer(0)]], device const Dsv41Pick *top [[buffer(1)]], + device const Dsv41Pick *candidate [[buffer(2)]], device Dsv41Pick *picks [[buffer(3)]], + device const uint *seed_end [[buffer(4)]], device atomic_uint *count [[buffer(5)]], + constant Dsv41Index &p [[buffer(6)]], + uint3 g [[threadgroup_position_in_grid]], uint tid [[thread_index_in_threadgroup]], + uint3 tptg [[threads_per_threadgroup]]) { + const uint row = g.y; + if (row >= p.rows) return; // uniform across the threadgroup + const uint local = g.x * tptg.x + tid; + const uint visible = min(p.keys, (p.position + row + 1) / p.ratio); + Dsv41Pick v = { -INFINITY, -1 }; + bool keeps = false; + // Every lane runs the ballot below, so no condition may return early: they set the predicate. + if (local < p.tile_width && local >= seed_end[row] && visible > p.tile_start + local) { + const float score = scores[row * p.tile_width + local]; + if (isfinite(score)) { + const int pos = dsv41_index_position(local, row, candidate, p); + if (pos >= 0) { + v = { score, pos }; + keeps = dsv41_less(top[row * p.topk], v); + } + } + } + if (!keeps) return; + const uint at = atomic_fetch_add_explicit(&count[row], 1u, memory_order_relaxed); + if (at < p.tile_width) picks[row * p.tile_width + at] = v; +} + +// The merge's serial part, now only the keys the filter kept. +kernel void dsv41_index_insert(device Dsv41Pick *top [[buffer(0)]], device const Dsv41Pick *picks [[buffer(1)]], + device atomic_uint *count [[buffer(2)]], device Dsv41Pick *candidate [[buffer(3)]], + device const float *scores [[buffer(4)]], constant Dsv41Index &p [[buffer(5)]], + uint row [[thread_position_in_grid]]) { + if (row >= p.rows) return; + device Dsv41Pick *heap = top + row * p.topk; + const uint kept = atomic_load_explicit(&count[row], memory_order_relaxed); + for (uint i = 0; i < kept; ++i) dsv41_heap(heap, p.topk, picks[row * p.tile_width + i]); + atomic_store_explicit(&count[row], 0u, memory_order_relaxed); + if (!p.make_candidates) return; + const uint visible = min(p.keys, (p.position + row + 1) / p.ratio); + const uint have = visible > p.tile_start ? min(p.tile_width, visible - p.tile_start) : 0u; + device Dsv41Pick *blocks = candidate + row * p.candidate_topk; + for (uint base = 0; base < have; base += p.block_size) { + float score = -INFINITY; + for (uint j = 0; j < p.block_size; ++j) score = max(score, scores[row * p.tile_width + base + j]); + uint block = (p.tile_start + base) / p.block_size; + if (visible && block == (visible - 1) / p.block_size) score = INFINITY; + if (score > -INFINITY) dsv41_heap(blocks, p.candidate_topk, {score, int(block)}); + } +} + +inline void dsv41_sort_positions(device Dsv41Pick *p, uint size) { + // Selection is score-ordered; attention sees the reference's ascending position order. + uint valid = 0; + for (uint i = 0; i < size; ++i) if (p[i].position >= 0) p[valid++] = p[i]; + for (uint i = 1; i < valid; ++i) { + const Dsv41Pick value = p[i]; uint j = i; + while (j > 0 && p[j - 1].position > value.position) { p[j] = p[j - 1]; --j; } + p[j] = value; + } + for (uint i = valid; i < size; ++i) p[i] = { -INFINITY, -1 }; +} +kernel void dsv41_index_finish(device Dsv41Pick *top [[buffer(0)]], device Dsv41Pick *candidate [[buffer(1)]], + device int *positions [[buffer(2)]], constant Dsv41Index &p [[buffer(3)]], uint row [[thread_position_in_grid]]) { + if (row >= p.rows) return; + device Dsv41Pick *heap = top + row * p.topk; + dsv41_sort_positions(heap, p.topk); + for (uint i = 0; i < p.topk; ++i) positions[row * p.topk + i] = heap[i].position; + if (p.make_candidates) dsv41_sort_positions(candidate + row * p.candidate_topk, p.candidate_topk); +} + +// The finish's PARALLEL form -- a threadgroup a row instead of one THREAD a row. +kernel void dsv41_index_finish_par(device Dsv41Pick *top [[buffer(0)]], device Dsv41Pick *candidate [[buffer(1)]], + device int *positions [[buffer(2)]], constant Dsv41Index &p [[buffer(3)]], + uint row [[threadgroup_position_in_grid]], uint tid [[thread_index_in_threadgroup]]) { + if (row >= p.rows) return; + const uint TG = 256; + threadgroup uint sh[512]; + device Dsv41Pick *heap = top + row * p.topk; + for (uint i = tid; i < p.topk; i += TG) { + const int pos = heap[i].position; + sh[i] = pos < 0 ? 0xFFFFFFFFu : uint(pos); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + // A bitonic sort of the positions, ascending. Each compare-exchange pair is owned by one thread. + for (uint k = 2; k <= p.topk; k <<= 1) { + for (uint j = k >> 1; j > 0; j >>= 1) { + for (uint i = tid; i < p.topk; i += TG) { + const uint ixj = i ^ j; + if (ixj > i) { + const bool asc = (i & k) == 0; + const uint a = sh[i], b = sh[ixj]; + if (asc ? (a > b) : (a < b)) { sh[i] = b; sh[ixj] = a; } + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + } + } + for (uint i = tid; i < p.topk; i += TG) { + const uint key = sh[i]; + positions[row * p.topk + i] = key == 0xFFFFFFFFu ? -1 : int(key); + } +} diff --git a/zig/kernels/metal/deepseek_v41/index_exl3_nax.metal b/zig/kernels/metal/deepseek_v41/index_exl3_nax.metal new file mode 100644 index 00000000000..cbbbfd2e37e --- /dev/null +++ b/zig/kernels/metal/deepseek_v41/index_exl3_nax.metal @@ -0,0 +1,520 @@ +// Source is compiled after kv.metal and index_exl3.metal; the tensor-unit score kernels only. +using namespace tfp; + +// Prompt scores on the tensor units: the scalar scorer's arithmetic as 64x64 tiles, one 128-dim MMA a head. +constant constexpr int INAX_D = 128, INAX_PAD = INAX_D + 8; + +inline frag inax_frag(const device bfloat* r0, const device bfloat* r1, int c, short2 home) { +#ifndef TF_SIMD_FRAGS + return frag(*(const device bfloat4*)(r0 + c + home.x), *(const device bfloat4*)(r1 + c + home.x)); +#else + frag f; + TF_UNROLL + for (short e = 0; e < 8; e++) f[e] = (e < 4 ? r0 : r1)[c + home.x + TF_COL(e)]; + return f; +#endif +} + +kernel void dsv41_index_scores_nax(device const ushort *qp [[buffer(0)]], device const ushort *wp [[buffer(1)]], + device const ushort *kp [[buffer(2)]], device float *scores [[buffer(3)]], + constant Dsv41Index &p [[buffer(4)]], uint sg [[simdgroup_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]], uint3 tg [[threadgroup_position_in_grid]]) { + const device bfloat* Q = reinterpret_cast(qp); + const device bfloat* W = reinterpret_cast(wp); + const device bfloat* K = reinterpret_cast(kp); + threadgroup bfloat tile[64 * INAX_PAD]; + const int t0 = int(p.tile_start) + int(tg.x) * 64, r0 = int(tg.y) * 64; + const int rows = min(64, int(p.rows) - r0); + const uint t = sg * 32u + lane; + if (p.keys == 0 or p.ratio == 0) return; + // A tile past the last row's visible keys scores -inf and is not staged. + if (t0 >= int((p.position + uint(r0) + uint(rows)) / p.ratio)) { + for (uint i = t; i < 64u * 64u; i += 128u) { + const int r = int(i) / 64, k = t0 + int(i) % 64; + if (r < rows && k < int(p.keys)) + *(dsv41_score_slot(scores, p, r0 + r, p.tile_start / p.tile_width) + (k - int(p.tile_start))) = -INFINITY; + } + return; + } + for (uint i = t; i < 64u * (INAX_D / 8u); i += 128u) { + const uint rr = i / (INAX_D / 8u), cc = (i % (INAX_D / 8u)) * 8u; + const int k = min(t0 + int(rr), int(p.keys) - 1); + *(threadgroup uint4*)(tile + rr * INAX_PAD + cc) = *(const device uint4*)(K + size_t(k) * INAX_D + cc); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + const short2 home = frag_home(ushort(lane)); + const int tm = 32 * int(sg / 2), tn = 32 * int(sg % 2); + const device bfloat* qr[2][2]; + const device bfloat* wr[2][2]; + TF_UNROLL + for (short m = 0; m < 2; m++) { + TF_UNROLL + for (short h = 0; h < 2; h++) { + const int r = tm + 16 * m + home.y + 8 * h; + const int at = r0 + (r < rows ? r : 0); // a dead row reads a live one; its scores are never stored + qr[m][h] = Q + size_t(at) * p.q_stride; + wr[m][h] = W + size_t(at) * p.weight_stride; + } + } + frag total[2][2]; + TF_UNROLL + for (short m = 0; m < 2; m++) { + total[m][0] = frag(0); + total[m][1] = frag(0); + } + for (int hd = 0; hd < int(p.heads); hd++) { + frag s[2][2]; + TF_UNROLL + for (short m = 0; m < 2; m++) { + s[m][0] = frag(0); + s[m][1] = frag(0); + } + TF_UNROLL + for (short q = 0; q < INAX_D / 16; q++) { + frag k0, k1; + frag_get_t(k0, (const threadgroup bfloat*)tile, INAX_PAD, tn, 16 * q, home); + frag_get_t(k1, (const threadgroup bfloat*)tile, INAX_PAD, tn + 16, 16 * q, home); + TF_UNROLL + for (short m = 0; m < 2; m++) { + const frag qa = inax_frag(qr[m][0] + hd * INAX_D, qr[m][1] + hd * INAX_D, 16 * q, home); + mma_16x32(s[m][0], s[m][1], qa, k0, k1); + } + } + // the head's term as the scalar makes it: bf16 dot, relu, times the bf16-rounded scaled weight, summed in fp32 + TF_UNROLL + for (short m = 0; m < 2; m++) { + const float w0 = dsv41_bf(dsv41_round(float(wr[m][0][hd]) * p.scale)); + const float w1 = dsv41_bf(dsv41_round(float(wr[m][1][hd]) * p.scale)); + TF_UNROLL + for (short j = 0; j < 2; j++) { + TF_UNROLL + for (short e = 0; e < 8; e++) { + const float dot = dsv41_bf(dsv41_round(s[m][j][e])); + total[m][j][e] += dsv41_bf(dsv41_round(max(dot, 0.0f) * (e < 4 ? w0 : w1))); + } + } + } + } + TF_UNROLL + for (short m = 0; m < 2; m++) { + TF_UNROLL + for (short j = 0; j < 2; j++) { + TF_UNROLL + for (short e = 0; e < 8; e++) { + const int r = tm + 16 * m + home.y + (e >> 2) * 8; + const int k = t0 + tn + 16 * j + home.x + TF_COL(e); + if (r < rows && k < int(p.keys)) + *(dsv41_score_slot(scores, p, r0 + r, p.tile_start / p.tile_width) + (k - int(p.tile_start))) = + dsv41_bf(dsv41_round(total[m][j][e])); + } + } + } +} + +// This is that kernel's own body with the tile's row extent cut to sixteen -- the MMA's M granularity. +kernel void dsv41_index_scores_row(device const ushort *qp [[buffer(0)]], device const ushort *wp [[buffer(1)]], + device const ushort *kp [[buffer(2)]], device float *scores [[buffer(3)]], + constant Dsv41Index &p [[buffer(4)]], uint sg [[simdgroup_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]], uint3 tg [[threadgroup_position_in_grid]]) { + const device bfloat* Q = reinterpret_cast(qp); + const device bfloat* W = reinterpret_cast(wp); + const device bfloat* K = reinterpret_cast(kp); + threadgroup bfloat tile[64 * INAX_PAD]; + const int t0 = int(p.tile_start) + int(tg.x) * 64, r0 = int(tg.y) * 16; + const int rows = min(16, int(p.rows) - r0); + const uint t = sg * 32u + lane; + if (p.keys == 0 or p.ratio == 0) return; + if (t0 >= int((p.position + uint(r0) + uint(rows)) / p.ratio)) { + for (uint i = t; i < 16u * 64u; i += 128u) { + const int r = int(i) / 64, k = t0 + int(i) % 64; + if (r < rows && k < int(p.keys)) + *(dsv41_score_slot(scores, p, r0 + r, p.tile_start / p.tile_width) + (k - int(p.tile_start))) = -INFINITY; + } + return; + } + for (uint i = t; i < 64u * (INAX_D / 8u); i += 128u) { + const uint rr = i / (INAX_D / 8u), cc = (i % (INAX_D / 8u)) * 8u; + const int k = min(t0 + int(rr), int(p.keys) - 1); + *(threadgroup uint4*)(tile + rr * INAX_PAD + cc) = *(const device uint4*)(K + size_t(k) * INAX_D + cc); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (int(sg) >= 2) return; // sixteen rows by sixty-four keys is two 16x32 column blocks + const short2 home = frag_home(ushort(lane)); + const int tn = 32 * int(sg); + const int tm = 0; + const device bfloat* qr[2]; + const device bfloat* wr[2]; + TF_UNROLL + for (short h = 0; h < 2; h++) { + const int r = tm + home.y + 8 * h; + const int at = r0 + (r < rows ? r : 0); + qr[h] = Q + size_t(at) * p.q_stride; + wr[h] = W + size_t(at) * p.weight_stride; + } + frag total0 = frag(0), total1 = frag(0); + for (int hd = 0; hd < int(p.heads); hd++) { + frag s0 = frag(0), s1 = frag(0); + TF_UNROLL + for (short q = 0; q < INAX_D / 16; q++) { + frag k0, k1; + frag_get_t(k0, (const threadgroup bfloat*)tile, INAX_PAD, tn, 16 * q, home); + frag_get_t(k1, (const threadgroup bfloat*)tile, INAX_PAD, tn + 16, 16 * q, home); + const frag qa = inax_frag(qr[0] + hd * INAX_D, qr[1] + hd * INAX_D, 16 * q, home); + mma_16x32(s0, s1, qa, k0, k1); + } + // the head's term as the scalar makes it: bf16 dot, relu, times the bf16-rounded scaled weight, fp32 sum + const float w0 = dsv41_bf(dsv41_round(float(wr[0][hd]) * p.scale)); + const float w1 = dsv41_bf(dsv41_round(float(wr[1][hd]) * p.scale)); + TF_UNROLL + for (short j = 0; j < 2; j++) { + TF_UNROLL + for (short e = 0; e < 8; e++) { + const float dot = dsv41_bf(dsv41_round((j == 0 ? s0 : s1)[e])); + const float add = dsv41_bf(dsv41_round(max(dot, 0.0f) * (e < 4 ? w0 : w1))); + if (j == 0) total0[e] += add; else total1[e] += add; + } + } + } + TF_UNROLL + for (short j = 0; j < 2; j++) { + TF_UNROLL + for (short e = 0; e < 8; e++) { + const int r = tm + home.y + (e >> 2) * 8; + const int k = t0 + tn + 16 * j + home.x + TF_COL(e); + if (r < rows && k < int(p.keys)) + *(dsv41_score_slot(scores, p, r0 + r, p.tile_start / p.tile_width) + (k - int(p.tile_start))) = + dsv41_bf(dsv41_round((j == 0 ? total0 : total1)[e])); + } + } +} + +// The keys-on-M score tile: keys are the M operand and head queries the N, so a one-row step fills every MMA row. +kernel void dsv41_index_scores_keys(device const ushort *qp [[buffer(0)]], device const ushort *wp [[buffer(1)]], + device const ushort *kp [[buffer(2)]], device float *scores [[buffer(3)]], + constant Dsv41Index &p [[buffer(4)]], uint sg [[simdgroup_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]], uint3 tg [[threadgroup_position_in_grid]]) { + const device bfloat* Q = reinterpret_cast(qp); + const device bfloat* W = reinterpret_cast(wp); + const device bfloat* K = reinterpret_cast(kp); + threadgroup bfloat tile[64 * INAX_PAD]; + threadgroup bfloat terms[64 * 32]; + const int t0 = int(p.tile_start) + int(tg.x) * 64; + const uint t = sg * 32u + lane; + if (p.keys == 0 or p.ratio == 0) return; + const int rows = int(p.rows); + // A tile past the last row's visible keys scores -inf and is not staged. + if (t0 >= int((p.position + uint(rows)) / p.ratio)) { + for (uint r = 0; r < uint(rows); r++) + for (uint i = t; i < 64u; i += 128u) { + const int k = t0 + int(i); + if (k < int(p.keys)) + *(dsv41_score_slot(scores, p, int(r), p.tile_start / p.tile_width) + (k - int(p.tile_start))) = -INFINITY; + } + return; + } + for (uint i = t; i < 64u * (INAX_D / 8u); i += 128u) { + const uint rr = i / (INAX_D / 8u), cc = (i % (INAX_D / 8u)) * 8u; + const int k = min(t0 + int(rr), int(p.keys) - 1); + *(threadgroup uint4*)(tile + rr * INAX_PAD + cc) = *(const device uint4*)(K + size_t(k) * INAX_D + cc); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + const short2 home = frag_home(ushort(lane)); + const int m0 = 16 * int(sg); + for (int r = 0; r < rows; r++) { + const device bfloat* qrow = Q + size_t(r) * p.q_stride; + const device bfloat* wrow = W + size_t(r) * p.weight_stride; + frag s0 = frag(0), s1 = frag(0); + TF_UNROLL + for (short q = 0; q < INAX_D / 16; q++) { + frag ka, b0, b1; + frag_get(ka, (const threadgroup bfloat*)tile, INAX_PAD, m0, 16 * q, home); + frag_get_t(b0, qrow, INAX_D, 0, 16 * q, home); + frag_get_t(b1, qrow, INAX_D, 16, 16 * q, home); + mma_16x32(s0, s1, ka, b0, b1); + } + TF_UNROLL + for (short j = 0; j < 2; j++) { + TF_UNROLL + for (short e = 0; e < 8; e++) { + const int key = m0 + home.y + (e >> 2) * 8; + const int h = 16 * j + home.x + TF_COL(e); + const float w = dsv41_bf(dsv41_round(float(wrow[h]) * p.scale)); + const float dot = dsv41_bf(dsv41_round((j == 0 ? s0 : s1)[e])); + terms[key * 32 + h] = bfloat(dsv41_bf(dsv41_round(max(dot, 0.0f) * w))); + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (t < 64u) { + const int k = t0 + int(t); + if (k < int(p.keys)) { + float total = 0.0f; + TF_UNROLL + for (short h = 0; h < 32; h++) total += float(terms[t * 32u + uint(h)]); + *(dsv41_score_slot(scores, p, r, p.tile_start / p.tile_width) + (k - int(p.tile_start))) = + dsv41_bf(dsv41_round(total)); + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + } +} + +// The decode selection is one dispatch: the heap path costs 27 dispatches and ~1,000 one-thread pushes a row. +inline void dsv41_ixsort(threadgroup uint *sh, uint n, uint tid) { + const uint TG = 256u; + for (uint k = 2; k <= n; k <<= 1) { + for (uint j = k >> 1; j > 0; j >>= 1) { + for (uint i = tid; i < n; i += TG) { + const uint ixj = i ^ j; + if (ixj > i) { + const bool asc = (i & k) == 0; + const uint a = sh[i], b = sh[ixj]; + if (asc ? (a > b) : (a < b)) { sh[i] = b; sh[ixj] = a; } + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + } + } +} + +kernel void dsv41_index_select(device const float *scores [[buffer(0)]], + device int *positions [[buffer(1)]], + constant Dsv41Index &p [[buffer(2)]], + uint row [[threadgroup_position_in_grid]], + uint tid [[thread_index_in_threadgroup]]) { + const uint TG = 256u, topk = 512u; + if (row >= p.rows) return; + threadgroup uint hist[256]; + threadgroup uint sel[512]; + threadgroup uint ties[512]; + threadgroup atomic_uint counter; + const uint visible = min(p.keys, (p.position + row + 1) / p.ratio); + if (visible <= topk) { // every visible key is kept: the identity branch's array + for (uint i = tid; i < topk; i += TG) positions[row * topk + i] = i < visible ? int(i) : -1; + return; + } + // ---- the radix select: `prefix` converges to the k-th largest's image, `above` is the count above it + uint prefix = 0u, above = 0u, need = topk; + for (uint pass = 0; pass < 4u; ++pass) { + const uint shift = 24u - 8u * pass; + for (uint i = tid; i < 256u; i += TG) hist[i] = 0u; + threadgroup_barrier(mem_flags::mem_threadgroup); + for (uint t = 0, base = 0; base < visible; ++t, base += p.tile_width) { + const device float *slot = dsv41_score_slot_ro(scores, p, row, t); + const uint n = min(p.tile_width, visible - base); + for (uint i = tid; i < n; i += TG) { + const uint u = dsv41_index_mono(slot[i]); + if (pass == 0u || (u >> (shift + 8u)) == prefix) { + atomic_fetch_add_explicit((threadgroup atomic_uint *)&hist[(u >> shift) & 0xFFu], 1u, + memory_order_relaxed); + } + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + threadgroup uint digit, ran; + // Digit/ran are threadgroup memory; only tid 0 initialises them, or a late zero can erase the chosen digit. + if (tid == 0u) { + uint cum = 0u; + digit = 0u; ran = 0u; + for (int d = 255; d >= 0; --d) { + const uint c = hist[uint(d)]; + if (cum + c >= need) { digit = uint(d); ran = cum; break; } + cum += c; + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + prefix = (pass == 0u) ? digit : ((prefix << 8u) | digit); + above += ran; + need -= ran; + } + // ---- the filter: every key above the threshold (exactly `above` of them), compacted in arrival order + if (tid == 0u) atomic_store_explicit(&counter, 0u, memory_order_relaxed); + threadgroup_barrier(mem_flags::mem_threadgroup); + for (uint t = 0, base = 0; base < visible; ++t, base += p.tile_width) { + const device float *slot = dsv41_score_slot_ro(scores, p, row, t); + const uint n = min(p.tile_width, visible - base); + for (uint i = tid; i < n; i += TG) { + if (dsv41_index_mono(slot[i]) > prefix) { + const uint at = atomic_fetch_add_explicit(&counter, 1u, memory_order_relaxed); + if (at < topk) sel[at] = base + i; + } + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + // ---- the ties at the threshold, the lowest `need` positions of them + const uint have = min(atomic_load_explicit(&counter, memory_order_relaxed), topk); + // The ties pass below reuses this counter, so it has to be zeroed AFTER every thread has read `have`. + threadgroup_barrier(mem_flags::mem_threadgroup); + if (tid == 0u) atomic_store_explicit(&counter, 0u, memory_order_relaxed); + threadgroup_barrier(mem_flags::mem_threadgroup); + for (uint t = 0, base = 0; base < visible; ++t, base += p.tile_width) { + const device float *slot = dsv41_score_slot_ro(scores, p, row, t); + const uint n = min(p.tile_width, visible - base); + for (uint i = tid; i < n; i += TG) { + if (dsv41_index_mono(slot[i]) == prefix) { + const uint at = atomic_fetch_add_explicit(&counter, 1u, memory_order_relaxed); + if (at < 512u) ties[at] = base + i; + } + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + const uint nties = atomic_load_explicit(&counter, memory_order_relaxed); + if (need > 0u) { + if (nties <= 512u) { // sort the ties ascending and take the first `need` + for (uint i = nties + tid; i < 512u; i += TG) ties[i] = 0xFFFFFFFFu; + threadgroup_barrier(mem_flags::mem_threadgroup); + dsv41_ixsort(ties, 512u, tid); + for (uint i = tid; i < need && have + i < topk; i += TG) sel[have + i] = ties[i]; + } else { // more ties than a threadgroup array: the lowest positions, scanned in order + if (tid == 0u) { + uint got = 0u; + for (uint t = 0, base = 0; base < visible && got < need; ++t, base += p.tile_width) { + const device float *slot = dsv41_score_slot_ro(scores, p, row, t); + const uint n = min(p.tile_width, visible - base); + for (uint i = 0; i < n && got < need; ++i) + if (dsv41_index_mono(slot[i]) == prefix && have + got < topk) { sel[have + got] = base + i; ++got; } + } + } + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + // ---- the ascending positions array the finish writes: the same array, sorted the same way + for (uint i = have + need + tid; i < topk; i += TG) sel[i] = 0xFFFFFFFFu; + threadgroup_barrier(mem_flags::mem_threadgroup); + dsv41_ixsort(sel, 512u, tid); + for (uint i = tid; i < topk; i += TG) + positions[row * topk + i] = sel[i] == 0xFFFFFFFFu ? -1 : int(sel[i]); +} + + + +// The one-dispatch select with vector reads, a two-pass radix and the ties folded into the filter. +kernel void dsv41_index_select_v(device const float *scores [[buffer(0)]], + device int *positions [[buffer(1)]], + constant Dsv41Index &p [[buffer(2)]], + uint row [[threadgroup_position_in_grid]], + uint tid [[thread_index_in_threadgroup]]) { + const uint TG = 256u, topk = 512u; + if (row >= p.rows) return; + threadgroup uint hist[256]; + threadgroup uint sel[512]; + threadgroup uint ties[512]; + threadgroup atomic_uint counter; + threadgroup atomic_uint tcounter; + const uint visible = min(p.keys, (p.position + row + 1) / p.ratio); + if (visible <= topk) { // every visible key is kept: the identity branch's array + for (uint i = tid; i < topk; i += TG) positions[row * topk + i] = i < visible ? int(i) : -1; + return; + } + // ---- the two-pass radix: bits 31..24 then 23..16; the low 16 are zero by the bf16 invariant + uint prefix = 0u, above = 0u, need = topk; + for (uint pass = 0; pass < 2u; ++pass) { + const uint shift = 24u - 8u * pass; + for (uint i = tid; i < 256u; i += TG) hist[i] = 0u; + threadgroup_barrier(mem_flags::mem_threadgroup); + for (uint t = 0, base = 0; base < visible; ++t, base += p.tile_width) { + const device float *slot = dsv41_score_slot_ro(scores, p, row, t); + const uint n = min(p.tile_width, visible - base); + const uint n4 = n & ~3u; + const device float4 *s4 = (const device float4 *)slot; + for (uint i = tid; i < n4 / 4u; i += TG) { + const float4 v = s4[i]; + const uint u[4] = {dsv41_index_mono(v.x), dsv41_index_mono(v.y), + dsv41_index_mono(v.z), dsv41_index_mono(v.w)}; + for (uint j = 0; j < 4u; ++j) + if (pass == 0u || (u[j] >> (shift + 8u)) == prefix) + atomic_fetch_add_explicit((threadgroup atomic_uint *)&hist[(u[j] >> shift) & 0xFFu], + 1u, memory_order_relaxed); + } + for (uint i = n4 + tid; i < n; i += TG) { + const uint u = dsv41_index_mono(slot[i]); + if (pass == 0u || (u >> (shift + 8u)) == prefix) + atomic_fetch_add_explicit((threadgroup atomic_uint *)&hist[(u >> shift) & 0xFFu], + 1u, memory_order_relaxed); + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + threadgroup uint digit, ran; + // Digit/ran are threadgroup memory; only tid 0 initialises them, or a late zero can erase the chosen digit. + if (tid == 0u) { + uint cum = 0u; + digit = 0u; ran = 0u; + for (int d = 255; d >= 0; --d) { + const uint c = hist[uint(d)]; + if (cum + c >= need) { digit = uint(d); ran = cum; break; } + cum += c; + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + prefix = (pass == 0u) ? digit : ((prefix << 8u) | digit); + above += ran; + need -= ran; + } + // The two passes leave the top sixteen bits in the low half. mono()'s low sixteen are 0 for a positive bf16 score. + prefix = (prefix << 16u) | (((prefix & 0x8000u) == 0u) ? 0xFFFFu : 0u); + // ---- the filter and the ties in one pass: every key above the threshold (exactly `above` of them) + if (tid == 0u) { + atomic_store_explicit(&counter, 0u, memory_order_relaxed); + atomic_store_explicit(&tcounter, 0u, memory_order_relaxed); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + for (uint t = 0, base = 0; base < visible; ++t, base += p.tile_width) { + const device float *slot = dsv41_score_slot_ro(scores, p, row, t); + const uint n = min(p.tile_width, visible - base); + const uint n4 = n & ~3u; + const device float4 *s4 = (const device float4 *)slot; + for (uint i = tid; i < n4 / 4u; i += TG) { + const float4 v = s4[i]; + const uint u[4] = {dsv41_index_mono(v.x), dsv41_index_mono(v.y), + dsv41_index_mono(v.z), dsv41_index_mono(v.w)}; + for (uint j = 0; j < 4u; ++j) { + const uint at = base + i * 4u + j; + if (u[j] > prefix) { + const uint k = atomic_fetch_add_explicit(&counter, 1u, memory_order_relaxed); + if (k < topk) sel[k] = at; + } else if (u[j] == prefix && need > 0u) { + const uint k = atomic_fetch_add_explicit(&tcounter, 1u, memory_order_relaxed); + if (k < 512u) ties[k] = at; + } + } + } + for (uint i = n4 + tid; i < n; i += TG) { + const uint u = dsv41_index_mono(slot[i]); + const uint at = base + i; + if (u > prefix) { + const uint k = atomic_fetch_add_explicit(&counter, 1u, memory_order_relaxed); + if (k < topk) sel[k] = at; + } else if (u == prefix && need > 0u) { + const uint k = atomic_fetch_add_explicit(&tcounter, 1u, memory_order_relaxed); + if (k < 512u) ties[k] = at; + } + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + const uint have = min(atomic_load_explicit(&counter, memory_order_relaxed), topk); + const uint nties = atomic_load_explicit(&tcounter, memory_order_relaxed); + if (need > 0u) { + if (nties <= 512u) { // sort the ties ascending and take the first `need` + for (uint i = nties + tid; i < 512u; i += TG) ties[i] = 0xFFFFFFFFu; + threadgroup_barrier(mem_flags::mem_threadgroup); + dsv41_ixsort(ties, 512u, tid); + for (uint i = tid; i < need && have + i < topk; i += TG) sel[have + i] = ties[i]; + } else { // more ties than a threadgroup array: the lowest positions, scanned in order + if (tid == 0u) { + uint got = 0u; + for (uint t = 0, base = 0; base < visible && got < need; ++t, base += p.tile_width) { + const device float *slot = dsv41_score_slot_ro(scores, p, row, t); + const uint n = min(p.tile_width, visible - base); + for (uint i = 0; i < n && got < need; ++i) + if (dsv41_index_mono(slot[i]) == prefix && have + got < topk) { sel[have + got] = base + i; ++got; } + } + } + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + // ---- the ascending positions array the finish writes: the same array, sorted the same way + for (uint i = have + need + tid; i < topk; i += TG) sel[i] = 0xFFFFFFFFu; + threadgroup_barrier(mem_flags::mem_threadgroup); + dsv41_ixsort(sel, 512u, tid); + for (uint i = tid; i < topk; i += TG) + positions[row * topk + i] = sel[i] == 0xFFFFFFFFu ? -1 : int(sel[i]); +} diff --git a/zig/kernels/metal/deepseek_v41/kv.metal b/zig/kernels/metal/deepseek_v41/kv.metal new file mode 100644 index 00000000000..900479ea180 --- /dev/null +++ b/zig/kernels/metal/deepseek_v41/kv.metal @@ -0,0 +1,181 @@ +// DeepSeek V4.1 cache quantization and pooling, following the official inference kernels. +#include +using namespace metal; +inline float dsv41_bf(ushort x) { return as_type(uint(x) << 16); } +inline ushort dsv41_round(float x) { + uint u = as_type(x); + if ((u & 0x7fffffff) > 0x7f800000) return ushort((u >> 16) | 0x40); + return ushort((u + 0x7fff + ((u >> 16) & 1)) >> 16); +} +inline float dsv41_e4(uchar c) { + if ((c & 127) == 127) return NAN; + uint e = (c >> 3) & 15, m = c & 7; + float v = e == 0 ? float(m) * 0x1p-9f : ldexp(1.0f + float(m) / 8.0f, int(e) - 7); + return (c & 128) ? -v : v; +} +inline uchar dsv41_e4code(float x) { + float a = min(abs(x), 448.0f); + if (a == 0) return signbit(x) ? 128 : 0; + int e = max(-6, int((as_type(a) >> 23) & 255) - 127); + int q = int(rint(ldexp(a, 3 - e))); + uint c = e == -6 && q < 8 ? uint(q) : uint((e + 7) * 8 + q - 8); + return uchar(min(c, 126u) | (signbit(x) ? 128u : 0u)); +} +inline float dsv41_e2(uchar c) { + const float v[8] = {0, .5f, 1, 1.5f, 2, 3, 4, 6}; + return (c & 8) ? -v[c & 7] : v[c & 7]; +} +inline uchar dsv41_e2code(float x) { + float a = min(abs(x), 6.0f); + uint pick = a <= .25f ? 0 : a < .75f ? 1 : a <= 1.25f ? 2 : a < 1.75f ? 3 + : a <= 2.5f ? 4 : a < 3.5f ? 5 : a <= 5.0f ? 6 : 7; + return uchar(pick | (signbit(x) ? 8 : 0)); +} +inline float dsv41_unpack(device const uchar *p, uint d, uint width, uint block, uint kind) { + if (kind == 0) { + float s = as_type(uint(p[width + d / 32]) << 23); + return dsv41_bf(dsv41_round(dsv41_e4(p[d]) * s)); + } + uchar c = p[d / 2]; + float s = kind == 1 ? dsv41_e4(p[width / 2 + d / block]) + : as_type(uint(p[width / 2 + d / block]) << 23); + return dsv41_bf(dsv41_round(dsv41_e2((d & 1) ? c >> 4 : c & 15) * s)); +} +struct Dsv41Pack { uint rows, width, stride, packed_stride, block, kind, first, ring, inplace; }; +static_assert(sizeof(Dsv41Pack) == 36, "Dsv41Pack must mirror kv.zig's Pack"); +kernel void dsv41_pack(device ushort *x [[buffer(0)]], device uchar *out [[buffer(1)]], + constant Dsv41Pack &p [[buffer(2)]], uint2 g [[threadgroup_position_in_grid]], + uint lane [[thread_index_in_threadgroup]]) { + uint row = g.y, group = g.x, d = group * p.block + lane; + if (row >= p.rows) return; + float v = lane < p.block ? dsv41_bf(x[row * p.stride + d]) : 0; + float a = simd_max(abs(v)); + float scale; uchar sc; + if (p.kind == 1) { + sc = dsv41_e4code(max(a, 6.0f * 0x1p-9f) / 6.0f); scale = dsv41_e4(sc); + } else { + float minimum = p.kind == 0 ? 1e-4f : 6.0f * 0x1p-126f; + float z = max(a, minimum) / (p.kind == 0 ? 448.0f : 6.0f); + uint bits = as_type(z); + int exp = int((bits >> 23) & 255) - 127 + ((bits & 0x7fffff) != 0); + sc = uchar(exp + 127); scale = ldexp(1.0f, exp); + } + uint dst = p.ring ? (p.first + row) % p.ring : p.first + row; + device uchar *packed = out + dst * p.packed_stride; + if (lane == 0) packed[(p.kind == 0 ? p.width : p.width / 2) + group] = sc; + if (lane >= p.block) return; + if (p.kind == 0) { + uchar c = dsv41_e4code(v / scale); packed[d] = c; + if (p.inplace) x[row * p.stride + d] = dsv41_round(dsv41_e4(c) * scale); + } else { + uchar c = dsv41_e2code(v / scale); + uchar other = uchar(simd_shuffle_xor(uint(c), 1)); + if (!(lane & 1)) packed[d / 2] = c | (other << 4); + if (p.inplace) x[row * p.stride + d] = dsv41_round(dsv41_e2(c) * scale); + } +} +struct Dsv41Pool { uint rows, width, ratio, position, stride, input_f32; float eps; uint capture_rows; }; +static_assert(sizeof(Dsv41Pool) == 32, "Dsv41Pool must mirror kv.zig's Pool"); +kernel void dsv41_pool(device const uchar *values [[buffer(0)]], device const float *gate [[buffer(1)]], + device float *partial [[buffer(2)]], device const ushort *weight [[buffer(3)]], + device ushort *latent [[buffer(4)]], device float *capture [[buffer(5)]], + constant Dsv41Pool &p [[buffer(6)]], + uint group [[threadgroup_position_in_grid]], uint lane [[thread_index_in_threadgroup]]) { + // A group reads the prior chunk's tail before the independent tail-update dispatch. + uint start = (p.position / p.ratio + group) * p.ratio; + threadgroup float pooled[512]; + float square = 0; + for (uint d = lane; d < p.width; d += 128) { + float mx = -INFINITY, sum = 0, total = 0; + for (uint j = 0; j < p.ratio; ++j) { + uint pos = start + j; + float score = p.ratio == 1 ? 0 : (pos < p.position ? partial[p.ratio * p.width + (pos % p.ratio) * p.width + d] + : gate[(pos - p.position) * p.stride + d]); + mx = max(mx, score); + } + float slots[2], exponent[2], gslots[2]; + for (uint j = 0; j < p.ratio; ++j) { + uint pos = start + j; + slots[j] = pos < p.position ? partial[(pos % p.ratio) * p.width + d] + : (p.input_f32 ? reinterpret_cast(values)[(pos - p.position) * p.stride + d] + : dsv41_bf(reinterpret_cast(values)[(pos - p.position) * p.stride + d])); + float score = p.ratio == 1 ? 0 : (pos < p.position ? partial[p.ratio * p.width + (pos % p.ratio) * p.width + d] + : gate[(pos - p.position) * p.stride + d]); + gslots[j] = score; + exponent[j] = exp(score - mx); sum += exponent[j]; + } + // The raw row's capture (values, gate), a slot a position; a call's last capture_rows positions write it. + uint done = (p.position + p.rows) / p.ratio - p.position / p.ratio; + if (p.capture_rows != 0 && group + p.capture_rows / p.ratio >= done) { + for (uint j = 0; j < p.ratio; ++j) { + uint pos = start + j; + uint slot = pos % p.capture_rows; + capture[slot * 2 * p.width + d] = slots[j]; + capture[slot * 2 * p.width + p.width + d] = gslots[j]; + } + } + for (uint j = 0; j < p.ratio; ++j) total += slots[j] * (exponent[j] / sum); + float v = dsv41_bf(dsv41_round(total)); pooled[d] = v; square += v * v; + } + threadgroup float sums[4]; + float ss = simd_sum(square); + if (!(lane % 32)) sums[lane / 32] = ss; + threadgroup_barrier(mem_flags::mem_threadgroup); + float inv = rsqrt((sums[0] + sums[1] + sums[2] + sums[3]) / p.width + p.eps); + for (uint d = lane; d < p.width; d += 128) + latent[group * p.width + d] = dsv41_round(pooled[d] * inv * dsv41_bf(weight[d])); +} +kernel void dsv41_pool_tail(device const float *values [[buffer(0)]], device const float *gate [[buffer(1)]], + device float *partial [[buffer(2)]], constant Dsv41Pool &p [[buffer(3)]], + uint d [[thread_position_in_grid]]) { + if (d >= p.width || p.ratio == 1) return; + uint end = p.position + p.rows, tail = end % p.ratio; + for (uint j = 0; j < tail; ++j) { + uint pos = end - tail + j; + if (pos < p.position) continue; + partial[j * p.width + d] = values[(pos - p.position) * p.stride + d]; + partial[p.ratio * p.width + j * p.width + d] = gate[(pos - p.position) * p.stride + d]; + } +} +kernel void dsv41_copy(device const uchar *src [[buffer(0)]], device uchar *dst [[buffer(1)]], + constant uint &bytes [[buffer(2)]], uint i [[thread_position_in_grid]]) { + if (i < bytes) dst[i] = src[i]; +} +kernel void dsv41_publish_window(device const uchar *chunk [[buffer(0)]], device uchar *ring [[buffer(1)]], + constant uint4 &p [[buffer(2)]], uint2 i [[thread_position_in_grid]]) { + uint count = min(p.x, 128u), first = p.x - count; + if (i.x >= p.z || i.y >= count) return; + uint row = first + i.y, slot = (p.y + row) % 128; + ring[slot * p.w + i.x] = chunk[row * p.z + i.x]; +} +// Batched publish: slot z's chunk row into its ring at pos[z] % 128; p = (ring offset, row stride, row bytes, 0). +kernel void dsv41_publish_rows(device const uchar *chunk [[buffer(0)]], constant uint4 &p [[buffer(1)]], + device const ulong *addr [[buffer(2)]], device const uint *pos [[buffer(3)]], uint2 i [[thread_position_in_grid]]) { + if (i.x >= p.z) return; + device uchar *ring = reinterpret_cast(addr[4 * i.y]) + p.x; + ring[(pos[i.y] % 128) * p.y + i.x] = chunk[i.y * p.y + i.x]; +} +kernel void dsv41_unpack_rows(device const uchar *packed [[buffer(0)]], device ushort *out [[buffer(1)]], + constant Dsv41Pack &p [[buffer(2)]], uint2 i [[thread_position_in_grid]]) { + if (i.x >= p.width || i.y >= p.rows) return; + uint row = p.ring ? (p.first + i.y) % p.ring : p.first + i.y; + out[i.y * p.stride + i.x] = dsv41_round(dsv41_unpack(packed + row * p.packed_stride, + i.x, p.width, p.block, p.kind)); +} + +// The window ring's slot stash/restore. +struct Dsv41RingMove { uint layers, move_rows, max_rows, window, position, stride_words, first, to_stash; }; +static_assert(sizeof(Dsv41RingMove) == 32, "Dsv41RingMove must mirror kv.zig's RingMove"); +kernel void dsv41_ring_move(device uint *dst [[buffer(0)]], device const uint *src [[buffer(1)]], + constant Dsv41RingMove &p [[buffer(2)]], uint i [[thread_position_in_grid]]) { + if (i >= p.layers * p.move_rows * p.stride_words) return; + uint w = i % p.stride_words; + uint row = i / p.stride_words; + uint layer = row / p.move_rows, rr = row % p.move_rows; + uint r = p.first + rr; + uint slot = (p.position + r) % p.window; + uint stash_index = (layer * p.max_rows + r) * p.stride_words + w; + uint ring_index = (layer * p.window + slot) * p.stride_words + w; + if (p.to_stash != 0) dst[stash_index] = src[ring_index]; + else dst[ring_index] = src[stash_index]; +} diff --git a/zig/kernels/metal/deepseek_v41/kv_glue.metal b/zig/kernels/metal/deepseek_v41/kv_glue.metal new file mode 100644 index 00000000000..d693648f01d --- /dev/null +++ b/zig/kernels/metal/deepseek_v41/kv_glue.metal @@ -0,0 +1,97 @@ +// DeepSeek V4.1 served engine: the window KV's RMS norm + RoPE + fp8 cache pack as ONE dispatch. +#include +using namespace metal; + +struct Dsv41KvGlue { + uint rows, width, stride, packed_stride, block, position, rotary, write_y; + float eps; +}; +static_assert(sizeof(Dsv41KvGlue) == 36, "Dsv41KvGlue must mirror kv.zig's Glue"); + +inline float dsv41kg_bf(ushort x) { return as_type(uint(x) << 16); } +inline ushort dsv41kg_round(float x) { + uint u = as_type(x); + return ushort((u + 0x7fff + ((u >> 16) & 1)) >> 16); +} +inline uchar dsv41kg_e4code(float x) { + float a = min(abs(x), 448.0f); + if (a == 0) return signbit(x) ? 128 : 0; + int e = max(-6, int((as_type(a) >> 23) & 255) - 127); + int q = int(rint(ldexp(a, 3 - e))); + uint c = e == -6 && q < 8 ? uint(q) : uint((e + 7) * 8 + q - 8); + return uchar(min(c, 126u) | (signbit(x) ? 128u : 0u)); +} + +// One row's norm + rope + pack; `position` is the row's absolute position (its rope factor row). +inline void dsv41_kv_glue_body(const device ushort* X, const device ushort* W, const device float2* F, device uchar* PACKED, + device ushort* Y, constant Dsv41KvGlue& p, threadgroup float* part, uint2 g, uint t, + uint lane, uint sg, uint position) { + const device ushort* x = X + ulong(g.y) * p.stride; + // dsv41_rms: s = fma(v1, v1, fma(v0, v0, 0)) over i = t, t+256, then the xor butterfly and part[0..7]. + const float v0 = dsv41kg_bf(x[t]), v1 = dsv41kg_bf(x[t + 256u]); + float s = fma(v0, v0, 0.0f); + s = fma(v1, v1, s); + for (uint m = 16; m > 0; m >>= 1) s += simd_shuffle_xor(s, m); + if (lane == 0) part[sg] = s; + threadgroup_barrier(mem_flags::mem_threadgroup); + float total = part[0]; + for (uint j = 1; j < 8; ++j) total += part[j]; + const float r = precise::rsqrt(precise::divide(total, float(p.width)) + p.eps); + // Only the first simdgroup packs this threadgroup's block; the rest have done their part of the sum. + if (sg != 0u) return; + const uint d = g.x * p.block + lane; + // dsv41_rms's output expression, rounded to bf16 exactly once. + ushort yb = dsv41kg_round(dsv41kg_bf(W[d]) * (dsv41kg_bf(x[d]) * r)); + // rope.metal, applied to the pair's two pre-rotation bf16 values. + if (d >= p.width - p.rotary) { + const float a0 = dsv41kg_bf(yb); + const float other = dsv41kg_bf(ushort(simd_shuffle_xor(uint(yb), 1))); + const uint pr = (d - (p.width - p.rotary)) / 2u; + const float2 cs = F[ulong(position) * (p.rotary / 2u) + pr]; + uint u; + if ((d & 1u) == 0u) u = as_type(a0 * cs.x - other * cs.y); + else u = as_type(other * cs.y + a0 * cs.x); + yb = ushort((u + 0x7fff + ((u >> 16) & 1)) >> 16); + } + if (p.write_y != 0u) Y[ulong(g.y) * p.width + d] = yb; + // dsv41_pack (window_fp8): one 32-lane simdgroup a block, the same max, scale exponent and code. + const float v = dsv41kg_bf(yb); + const float a = simd_max(abs(v)); + const float z = max(a, 1e-4f) / 448.0f; + const uint bits = as_type(z); + const int exp = int((bits >> 23) & 255) - 127 + ((bits & 0x7fffff) != 0); + const uchar sc = uchar(exp + 127); + const float scale = ldexp(1.0f, exp); + const uchar c = dsv41kg_e4code(v / scale); + device uchar* out = PACKED + ulong(g.y) * p.packed_stride; + out[d] = c; + if (lane == 0) out[p.width + g.x] = sc; +} + +kernel void dsv41_kv_glue( + const device ushort* X [[buffer(0)]], // raw [rows, stride] (kv projection output) + const device ushort* W [[buffer(1)]], // kv_norm weight [width] (bf16) + const device float2* F [[buffer(2)]], // rope factors, selected spectrum, position-indexed + device uchar* PACKED [[buffer(3)]], // [rows, packed_stride] window_fp8 + device ushort* Y [[buffer(4)]], // optional norm+rope writeback (write_y); never X + constant Dsv41KvGlue& p [[buffer(5)]], + uint2 g [[threadgroup_position_in_grid]], // g.x block, g.y row + uint t [[thread_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]], + uint sg [[simdgroup_index_in_threadgroup]]) { + if (g.y >= p.rows) return; + threadgroup float part[8]; + dsv41_kv_glue_body(X, W, F, PACKED, Y, p, part, g, t, lane, sg, p.position + g.y); +} + +// A batched decode window: row g.y is one slot's one row, at that slot's position `pos[g.y]`; p.position is unused. +kernel void dsv41_kv_glue_rows( + const device ushort* X [[buffer(0)]], const device ushort* W [[buffer(1)]], const device float2* F [[buffer(2)]], + device uchar* PACKED [[buffer(3)]], device ushort* Y [[buffer(4)]], constant Dsv41KvGlue& p [[buffer(5)]], + const device uint* pos [[buffer(6)]], uint2 g [[threadgroup_position_in_grid]], + uint t [[thread_index_in_threadgroup]], uint lane [[thread_index_in_simdgroup]], + uint sg [[simdgroup_index_in_threadgroup]]) { + if (g.y >= p.rows) return; + threadgroup float part[8]; + dsv41_kv_glue_body(X, W, F, PACKED, Y, p, part, g, t, lane, sg, pos[g.y]); +} diff --git a/zig/kernels/metal/deepseek_v41/markov.metal b/zig/kernels/metal/deepseek_v41/markov.metal index 5802c2e87c4..5c702db92fe 100644 --- a/zig/kernels/metal/deepseek_v41/markov.metal +++ b/zig/kernels/metal/deepseek_v41/markov.metal @@ -9,6 +9,7 @@ struct TfMarkovArgs { uint parts; // threadgroups an ask's search is cut into uint dim; // the hidden size (the confidence head's first part) }; +static_assert(sizeof(TfMarkovArgs) == 20, "TfMarkovArgs must mirror metal/markov.zig's Args"); // An ask's draws: greedy, or keyed (seed, the first draft's position, T) as the host races a row. struct TfMarkovAsk { @@ -17,6 +18,7 @@ struct TfMarkovAsk { float t; uint sampled; }; +static_assert(sizeof(TfMarkovAsk) == 24, "TfMarkovAsk must mirror metal/markov.zig's Ask"); inline float tf_mk_bf16(uint b) { return as_type(b << 16); diff --git a/zig/kernels/metal/deepseek_v41/mhc.metal b/zig/kernels/metal/deepseek_v41/mhc.metal new file mode 100644 index 00000000000..afd449235b7 --- /dev/null +++ b/zig/kernels/metal/deepseek_v41/mhc.metal @@ -0,0 +1,416 @@ +// Reference: DeepSeek-V4.1-Flash inference/model.py and kernel.py, revision 2cba9e42aa026125f3ed06c6d98c1db82f7ca027. +#include +using namespace metal; +inline float bf(ushort x) { return as_type(uint(x)<<16); } +inline ushort rb(float x) { + uint u=as_type(x); + if ((u&0x7fffffff)>0x7f800000) return ushort((u>>16)|0x40); + return ushort((u+0x7fff+((u>>16)&1))>>16); +} +// Torch CUDA materializes FP32 squares before MeanOps accumulation. +#pragma clang fp contract(off) +struct Rms { uint rows,width,stream_stride; float eps; }; +static_assert(sizeof(Rms) == 16, "Rms must mirror mhc.zig's Rms"); +kernel void dsv41_hc_rms(const device ushort* x [[buffer(0)]], device float* inv [[buffer(1)]], + constant Rms& d [[buffer(2)]], uint row [[threadgroup_position_in_grid]], + uint t [[thread_index_in_threadgroup]], uint lane [[thread_index_in_simdgroup]], + uint sg [[simdgroup_index_in_threadgroup]]) { + // Fixed single-row CUDA tree: four vector accumulators, stride 512, independent of prefill chunks. + threadgroup float sums[512]; + float4 accum=0.0f; + for (uint i=4*t;i<4*d.width;i+=4*512) { + float4 a=float4(bf(x[ulong(row)*d.stream_stride+i]), + bf(x[ulong(row)*d.stream_stride+i+1]), + bf(x[ulong(row)*d.stream_stride+i+2]), + bf(x[ulong(row)*d.stream_stride+i+3])); + float4 square=a*a; + accum+=square; + } + float s=((accum.x+accum.y)+accum.z)+accum.w; + sums[t]=s; + for (uint offset=256;offset>=32;offset>>=1) { + threadgroup_barrier(mem_flags::mem_threadgroup); + if (t0;offset>>=1) s+=simd_shuffle_down(s,offset); + // MeanOps projects with a rounded FP32 factor, not a division of the sum. + float factor=1.0f/float(4*d.width); + if (lane==0) inv[row]=rsqrt(s*factor+d.eps); + } +} +#pragma clang fp contract(on) +struct Split { uint rows,mix_stride,coefficient_stride,comb_stride; float eps; }; +static_assert(sizeof(Split) == 20, "Split must mirror mhc.zig's Split"); +kernel void dsv41_hc_split(const device float* mixes [[buffer(0)]], const device float* inv [[buffer(1)]], + const device float* scale [[buffer(2)]], const device float* base [[buffer(3)]], + device float* pre [[buffer(4)]], device float* post [[buffer(5)]], + device float* comb [[buffer(6)]], constant Split& d [[buffer(7)]], + uint row [[thread_position_in_grid]]) { + if (row>=d.rows) return; + float m[16]; + for (uint j=0;j<4;j++) { + float a=fma(mixes[ulong(row)*d.mix_stride+j]*inv[row],scale[0],base[j]); + float b=fma(mixes[ulong(row)*d.mix_stride+4+j]*inv[row],scale[1],base[4+j]); + pre[ulong(row)*d.coefficient_stride+j]=1.0f/(1.0f+exp(-a))+d.eps; + post[ulong(row)*d.coefficient_stride+j]=2.0f/(1.0f+exp(-b)); + for (uint k=0;k<4;k++) { + uint q=4*j+k; + m[q]=fma(mixes[ulong(row)*d.mix_stride+8+q]*inv[row],scale[2],base[8+q]); + } + } + // Initial row softmax + eps, then a column normalization. This counts as iteration one. + for (uint j=0;j<4;j++) { + float mx=max(max(m[4*j],m[4*j+1]),max(m[4*j+2],m[4*j+3])); + for (uint k=0;k<4;k++) m[4*j+k]=exp(m[4*j+k]-mx); + // Pinned TileLang HC row/column sums use FP32 butterfly pairs. + float s=(m[4*j]+m[4*j+2])+(m[4*j+1]+m[4*j+3]); + for (uint k=0;k<4;k++) m[4*j+k]=m[4*j+k]/s+d.eps; + } + for (uint it=0;it<20;it++) { + if (it>0) { + for (uint j=0;j<4;j++) { + float s=((m[4*j]+m[4*j+2])+(m[4*j+1]+m[4*j+3]))+d.eps; + for (uint k=0;k<4;k++) m[4*j+k]/=s; + } + } + for (uint k=0;k<4;k++) { + float s=((m[k]+m[8+k])+(m[4+k]+m[12+k]))+d.eps; + for (uint j=0;j<4;j++) m[4*j+k]/=s; + } + } + for (uint q=0;q<16;q++) comb[ulong(row)*d.comb_stride+q]=m[q]; +} +// PyTorch materializes these FP32 products before reduction and branch addition. +#pragma clang fp contract(off) +struct Collapse { uint rows,width,stream_stride,y_stride,pre_stride; }; +static_assert(sizeof(Collapse) == 20, "Collapse must mirror mhc.zig's Collapse"); +kernel void dsv41_hc_collapse(const device ushort* x [[buffer(0)]], const device float* previous_pre [[buffer(1)]], + device ushort* y [[buffer(2)]], constant Collapse& d [[buffer(3)]], + uint2 i [[thread_position_in_grid]]) { + if (i.x>=d.width || i.y>=d.rows) return; + float s=0; + for (uint c=0;c<4;c++) s+=previous_pre[ulong(i.y)*d.pre_stride+c]*bf(x[ulong(i.y)*d.stream_stride+ulong(c)*d.width+i.x]); + y[ulong(i.y)*d.y_stride+i.x]=rb(s); +} +struct Post { uint rows,width,branch_stride,residual_stride,y_stride,coefficient_stride,comb_stride; }; +static_assert(sizeof(Post) == 28, "Post must mirror mhc.zig's Post"); +kernel void dsv41_hc_post(const device ushort* branch [[buffer(0)]], const device ushort* residual [[buffer(1)]], + const device float* post [[buffer(2)]], const device float* comb [[buffer(3)]], + device ushort* y [[buffer(4)]], constant Post& d [[buffer(5)]], + uint2 i [[thread_position_in_grid]]) { + if (i.x>=d.width || i.y>=d.rows) return; + float r[4]; + for (uint j=0;j<4;j++) r[j]=bf(residual[ulong(i.y)*d.residual_stride+ulong(j)*d.width+i.x]); + float b=bf(branch[ulong(i.y)*d.branch_stride+i.x]); + for (uint k=0;k<4;k++) { + float s=0; + for (uint j=0;j<4;j++) s+=comb[ulong(i.y)*d.comb_stride+4*j+k]*r[j]; + y[ulong(i.y)*d.y_stride+ulong(k)*d.width+i.x]=rb(post[ulong(i.y)*d.coefficient_stride+k]*b+s); + } +} +#pragma clang fp contract(on) +struct Expand { uint rows,width,x_stride,stream_stride,pre_stride; }; +static_assert(sizeof(Expand) == 20, "Expand must mirror mhc.zig's Expand"); +kernel void dsv41_hc_expand(const device ushort* x [[buffer(0)]], device ushort* stream [[buffer(1)]], + device float* pre [[buffer(2)]], constant Expand& d [[buffer(3)]], + uint2 i [[thread_position_in_grid]]) { + if (i.x>=d.width || i.y>=d.rows) return; + for (uint c=0;c<4;c++) stream[ulong(i.y)*d.stream_stride+ulong(c)*d.width+i.x]=x[ulong(i.y)*d.x_stride+i.x]; + if (i.x==0) for (uint c=0;c<4;c++) pre[ulong(i.y)*d.pre_stride+c]=c==0?1.0f:0.0f; +} + +struct MixDense { uint rows, k, n, x_stride; }; +static_assert(sizeof(MixDense) == 16, "MixDense must mirror mhc.zig's MixDense"); +// One threadgroup a column: the 24 mix outputs read the whole 20480-wide projection once, coalesced. +kernel void dsv41_mix_dense(const device ushort* x [[buffer(0)]], + const device float* w [[buffer(1)]], + device float* y [[buffer(2)]], + constant MixDense& d [[buffer(3)]], + uint3 tg [[threadgroup_position_in_grid]], + uint t [[thread_index_in_threadgroup]], uint lane [[thread_index_in_simdgroup]], + uint sg [[simdgroup_index_in_threadgroup]]) { + threadgroup float sums[512]; + const uint j = tg.x, row = tg.y; + if (j >= d.n || row >= d.rows) return; + const device ushort* xr = x + ulong(row) * d.x_stride; + const device float* wr = w + ulong(j) * d.k; + float acc = 0.0f; + for (uint k = t; k < d.k; k += 512) acc += bf(xr[k]) * wr[k]; + sums[t] = acc; + for (uint offset = 256; offset >= 32; offset >>= 1) { + threadgroup_barrier(mem_flags::mem_threadgroup); + if (t < offset) { acc += sums[t + offset]; sums[t] = acc; } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (sg == 0) { + for (uint offset = 16; offset > 0; offset >>= 1) acc += simd_shuffle_down(acc, offset); + if (lane == 0) y[ulong(row) * d.n + j] = acc; + } +} + +struct ColDense { uint rows, k, n, x_stride, bf16_w; }; +static_assert(sizeof(ColDense) == 20, "ColDense must mirror mhc.zig's ColDense"); +// One threadgroup a column, for the narrow projections decode uses: out[row][j] = x[row,:] . w[j,:]. +kernel void dsv41_dense_col(const device ushort* x [[buffer(0)]], + const device ushort* w [[buffer(1)]], + device float* y [[buffer(2)]], + constant ColDense& d [[buffer(3)]], + uint3 tg [[threadgroup_position_in_grid]], + uint t [[thread_index_in_threadgroup]], uint lane [[thread_index_in_simdgroup]], + uint sg [[simdgroup_index_in_threadgroup]]) { + threadgroup float sums[512]; + const uint j = tg.x, row = tg.y; + if (j >= d.n || row >= d.rows) return; + const device ushort* xr = x + ulong(row) * d.x_stride; + const device ushort* wr = w + ulong(j) * d.k; + float acc = 0.0f; + for (uint k = t; k < d.k; k += 512) + acc += bf(xr[k]) * (d.bf16_w ? bf(wr[k]) : float(as_type(wr[k]))); + sums[t] = acc; + for (uint offset = 256; offset >= 32; offset >>= 1) { + threadgroup_barrier(mem_flags::mem_threadgroup); + if (t < offset) { acc += sums[t + offset]; sums[t] = acc; } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (sg == 0) { + for (uint offset = 16; offset > 0; offset >>= 1) acc += simd_shuffle_down(acc, offset); + if (lane == 0) y[ulong(row) * d.n + j] = acc; + } +} + +struct GateTree { uint rows, k, n, x_stride, bf16_w; }; +static_assert(sizeof(GateTree) == 20, "GateTree must mirror mhc.zig's GateTree"); +// A bit-exact tiled twin of dsv41_dense_col: a 4x4 cell a threadgroup, the shipped reduction order without a barrier. +kernel void dsv41_gate_tree(const device ushort* x [[buffer(0)]], + const device ushort* w [[buffer(1)]], + device float* y [[buffer(2)]], + constant GateTree& d [[buffer(3)]], + uint3 tg [[threadgroup_position_in_grid]], + uint t [[thread_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]], + uint sg [[simdgroup_index_in_threadgroup]]) { + const uint row0 = tg.y * 4u, col0 = tg.x * 4u; + if (row0 >= d.rows || col0 >= d.n) return; + const uint nrow = min(4u, d.rows - row0), ncol = min(4u, d.n - col0); + threadgroup ushort xs[4][512]; + threadgroup ushort ws[4][512]; + float V[4][16]; + for (uint r = 0; r < 4u; ++r) + for (uint i = 0; i < 16u; ++i) V[r][i] = 0.0f; + for (uint c = 0; c < d.k; c += 512u) { + for (uint idx = t; idx < 2048u; idx += 128u) { + const uint r = idx >> 9u, col = idx & 511u, kk = c + col; + xs[r][col] = (r < nrow and kk < d.k) ? x[ulong(row0 + r) * d.x_stride + kk] : ushort(0); + ws[r][col] = (r < ncol and kk < d.k) ? w[ulong(col0 + r) * d.k + kk] : ushort(0); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (sg < ncol) { + for (uint r = 0; r < nrow; ++r) { + for (uint i = 0; i < 16u; ++i) { + const uint p = lane + 32u * i, kk = c + p; + if (kk < d.k) { + const float xv = bf(xs[r][p]); + const float wv = d.bf16_w ? bf(ws[sg][p]) : float(as_type(ws[sg][p])); + V[r][i] += xv * wv; + } + } + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + } + if (sg < ncol) { + for (uint r = 0; r < nrow; ++r) { + for (uint h = 8u; h >= 1u; h >>= 1u) + for (uint i = 0; i < h; ++i) V[r][i] += V[r][i + h]; + float acc = V[r][0]; + acc += simd_shuffle_down(acc, 16); + acc += simd_shuffle_down(acc, 8); + acc += simd_shuffle_down(acc, 4); + acc += simd_shuffle_down(acc, 2); + acc += simd_shuffle_down(acc, 1); + if (lane == 0) y[ulong(row0 + r) * d.n + col0 + sg] = acc; + } + } +} + +struct GateTree4 { uint rows, k, n, x_stride, bf16_w; }; +static_assert(sizeof(GateTree4) == 20, "GateTree4 must mirror mhc.zig's GateTree4"); +// The vectorized bit-exact gate: one warp a 2x2 cell tile, contiguous reads, no threadgroup memory or barrier. +inline float tf_bf_h(ushort x) { return as_type(uint(x) << 16); } +inline float tf_w_h(ushort x, uint bf16_w) { return bf16_w ? as_type(uint(x) << 16) : float(as_type(x)); } +inline ushort tf_h4(const uint4& v, uint j) { + const uint w = (j >> 1) == 0u ? v.x : (j >> 1) == 1u ? v.y : (j >> 1) == 2u ? v.z : v.w; + return ushort((j & 1u) ? (w >> 16) : (w & 0xffffu)); +} +// The same bit-exact gate on a wider threadgroup with the x and w tiles staged in threadgroup memory. +#define TF_GATE_R 8u +#define TF_GATE_C 4u +#define TF_GATE_BK 512u +#define TF_GATE_WARPS 8u +kernel void dsv41_gate_tree8(const device ushort* x [[buffer(0)]], + const device ushort* w [[buffer(1)]], + device float* y [[buffer(2)]], + constant GateTree4& d [[buffer(3)]], + uint2 tg [[threadgroup_position_in_grid]], + uint tid [[thread_index_in_threadgroup]], + uint sg [[simdgroup_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]]) { + threadgroup uint4 xt4[TF_GATE_R * (TF_GATE_BK / 8u)]; + threadgroup uint4 wt4[TF_GATE_C * (TF_GATE_BK / 8u)]; + const uint row0 = tg.y * TF_GATE_R, col0 = tg.x * TF_GATE_C; + if (row0 >= d.rows || col0 >= d.n) return; + // Eight warps: four row pairs by two column pairs, each warp the shipped 2x2 cell tile. + const uint wr = (sg / 2u) * 2u, wc = (sg % 2u) * 2u; + const uint r0 = row0 + wr, c0 = col0 + wc; + const uint nr = min(2u, d.rows - r0), nc = min(2u, d.n - c0); + float V[4][16]; + for (uint c4 = 0; c4 < 4u; ++c4) + for (uint i = 0; i < 16u; ++i) V[c4][i] = 0.0f; + const uint base = 16u * lane; // this lane's first t in every 512-k chunk + for (uint c = 0; c < d.k; c += TF_GATE_BK) { + const uint avail = d.k - c < TF_GATE_BK ? d.k - c : TF_GATE_BK; + // Stage the threadgroup's tiles: eight rows of x and four columns of w, once a chunk. + threadgroup_barrier(mem_flags::mem_threadgroup); + { + constexpr uint XV = TF_GATE_BK / 8u; // the uint4 slots a row + for (uint i = tid; i < TF_GATE_R * XV; i += TF_GATE_WARPS * 32u) { + const uint r = i / XV, cc = (i % XV) * 8u; + uint4 v = uint4(0u); + if (r < d.rows - row0) { + const device ushort* p = x + (row0 + r) * d.x_stride + c + cc; + if (cc + 8u <= avail) { + v = *(const device uint4*)p; + } else { + ushort t8[8]; + for (uint q = 0; q < 8u; ++q) t8[q] = (cc + q < avail) ? p[q] : 0; + v = uint4(t8[0] | (uint(t8[1]) << 16), t8[2] | (uint(t8[3]) << 16), t8[4] | (uint(t8[5]) << 16), t8[6] | (uint(t8[7]) << 16)); + } + } + xt4[i] = v; + } + for (uint i = tid; i < TF_GATE_C * XV; i += TF_GATE_WARPS * 32u) { + const uint cc = i / XV, kk = (i % XV) * 8u; + uint4 v = uint4(0u); + if (cc < d.n - col0) { + const device ushort* p = w + (col0 + cc) * d.k + c + kk; + if (kk + 8u <= avail) { + v = *(const device uint4*)p; + } else { + ushort t8[8]; + for (uint q = 0; q < 8u; ++q) t8[q] = (kk + q < avail) ? p[q] : 0; + v = uint4(t8[0] | (uint(t8[1]) << 16), t8[2] | (uint(t8[3]) << 16), t8[4] | (uint(t8[5]) << 16), t8[6] | (uint(t8[7]) << 16)); + } + } + wt4[i] = v; + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + float xv[2][16]; + float wv[2][16]; + const bool live = base < avail; + const bool full = base + 16u <= avail; + for (uint r = 0; r < 2u; ++r) { + if (r < nr and live) { + const threadgroup ushort* p = reinterpret_cast(xt4 + (wr + r) * (TF_GATE_BK / 8u)) + base; + const uint4 a = *(const threadgroup uint4*)p, b = *(const threadgroup uint4*)(p + 8); + for (uint i = 0; i < 16u; ++i) xv[r][i] = (full or base + i < avail) ? tf_bf_h(tf_h4(i < 8u ? a : b, i & 7u)) : 0.0f; + } else { + for (uint i = 0; i < 16u; ++i) xv[r][i] = 0.0f; + } + } + for (uint j = 0; j < 2u; ++j) { + if (j < nc and live) { + const threadgroup ushort* p = reinterpret_cast(wt4 + (wc + j) * (TF_GATE_BK / 8u)) + base; + const uint4 a = *(const threadgroup uint4*)p, b = *(const threadgroup uint4*)(p + 8); + for (uint i = 0; i < 16u; ++i) wv[j][i] = (full or base + i < avail) ? tf_w_h(tf_h4(i < 8u ? a : b, i & 7u), d.bf16_w) : 0.0f; + } else { + for (uint i = 0; i < 16u; ++i) wv[j][i] = 0.0f; + } + } + for (uint r = 0; r < 2u; ++r) + for (uint j = 0; j < 2u; ++j) + for (uint i = 0; i < 16u; ++i) V[r * 2u + j][i] += xv[r][i] * wv[j][i]; + } + for (uint r = 0; r < 2u; ++r) { + if (r >= nr) continue; + for (uint j = 0; j < 2u; ++j) { + if (j >= nc) continue; + float* v = V[r * 2u + j]; + for (uint i = 0; i < 16u; ++i) { + v[i] += simd_shuffle_xor(v[i], 16); + v[i] += simd_shuffle_xor(v[i], 8); + v[i] += simd_shuffle_xor(v[i], 4); + v[i] += simd_shuffle_xor(v[i], 2); + v[i] += simd_shuffle_xor(v[i], 1); + } + for (uint h = 8u; h >= 1u; h >>= 1u) + for (uint i = 0; i < h; ++i) v[i] += v[i + h]; + if (lane == 0) y[ulong(r0 + r) * d.n + c0 + j] = v[0]; + } + } +} + +kernel void dsv41_gate_tree4(const device ushort* x [[buffer(0)]], + const device ushort* w [[buffer(1)]], + device float* y [[buffer(2)]], + constant GateTree4& d [[buffer(3)]], + uint2 tg [[threadgroup_position_in_grid]], + uint lane [[thread_index_in_simdgroup]]) { + const uint row0 = tg.y * 2u, col0 = tg.x * 2u; + if (row0 >= d.rows || col0 >= d.n) return; + const uint nr = min(2u, d.rows - row0), nc = min(2u, d.n - col0); + float V[4][16]; + for (uint c4 = 0; c4 < 4u; ++c4) + for (uint i = 0; i < 16u; ++i) V[c4][i] = 0.0f; + const uint base = 16u * lane; // this lane's first t in every 512-k chunk + for (uint c = 0; c < d.k; c += 512u) { + const uint avail = d.k - c < 512u ? d.k - c : 512u; + float xv[2][16]; + float wv[2][16]; + const bool live = base < avail; + const bool full = base + 16u <= avail; + for (uint r = 0; r < 2u; ++r) { + if (r < nr and live) { + const device ushort* p = x + ulong(row0 + r) * d.x_stride + c + base; + const uint4 a = *(const device uint4*)p, b = *(const device uint4*)(p + 8); + for (uint i = 0; i < 16u; ++i) xv[r][i] = (full or base + i < avail) ? tf_bf_h(tf_h4(i < 8u ? a : b, i & 7u)) : 0.0f; + } else { + for (uint i = 0; i < 16u; ++i) xv[r][i] = 0.0f; + } + } + for (uint j = 0; j < 2u; ++j) { + if (j < nc and live) { + const device ushort* p = w + ulong(col0 + j) * d.k + c + base; + const uint4 a = *(const device uint4*)p, b = *(const device uint4*)(p + 8); + for (uint i = 0; i < 16u; ++i) wv[j][i] = (full or base + i < avail) ? tf_w_h(tf_h4(i < 8u ? a : b, i & 7u), d.bf16_w) : 0.0f; + } else { + for (uint i = 0; i < 16u; ++i) wv[j][i] = 0.0f; + } + } + for (uint r = 0; r < 2u; ++r) + for (uint j = 0; j < 2u; ++j) + for (uint i = 0; i < 16u; ++i) V[r * 2u + j][i] += xv[r][i] * wv[j][i]; + } + for (uint r = 0; r < 2u; ++r) { + if (r >= nr) continue; + for (uint j = 0; j < 2u; ++j) { + if (j >= nc) continue; + float* v = V[r * 2u + j]; + for (uint i = 0; i < 16u; ++i) { + v[i] += simd_shuffle_xor(v[i], 16); + v[i] += simd_shuffle_xor(v[i], 8); + v[i] += simd_shuffle_xor(v[i], 4); + v[i] += simd_shuffle_xor(v[i], 2); + v[i] += simd_shuffle_xor(v[i], 1); + } + for (uint h = 8u; h >= 1u; h >>= 1u) + for (uint i = 0; i < h; ++i) v[i] += v[i + h]; + if (lane == 0) y[ulong(row0 + r) * d.n + col0 + j] = v[0]; + } + } +} diff --git a/zig/kernels/metal/deepseek_v41/mv.metal b/zig/kernels/metal/deepseek_v41/mv.metal index 482287c245d..32c77ae5585 100644 --- a/zig/kernels/metal/deepseek_v41/mv.metal +++ b/zig/kernels/metal/deepseek_v41/mv.metal @@ -10,6 +10,7 @@ using namespace metal; struct TfDsv41MvArgs { uint k, n, rows; }; +static_assert(sizeof(TfDsv41MvArgs) == 12, "TfDsv41MvArgs must mirror metal/mv.zig's Args"); inline float tf_dsv41_mv_x(bfloat v) { const float f = float(v); diff --git a/zig/kernels/metal/deepseek_v41/mv_mma.metal b/zig/kernels/metal/deepseek_v41/mv_mma.metal index 85c678a9426..d70c64cc54b 100644 --- a/zig/kernels/metal/deepseek_v41/mv_mma.metal +++ b/zig/kernels/metal/deepseek_v41/mv_mma.metal @@ -12,6 +12,7 @@ using namespace metal; struct TfDsv41MvMmaArgs { uint k, n, rows; }; +static_assert(sizeof(TfDsv41MvMmaArgs) == 12, "TfDsv41MvMmaArgs must mirror its Zig launch arguments"); inline float tf_dsv41_mv_mma_x(uint bits) { const float f = as_type(bits); diff --git a/zig/kernels/metal/deepseek_v41/ops.metal b/zig/kernels/metal/deepseek_v41/ops.metal new file mode 100644 index 00000000000..e6e2a301149 --- /dev/null +++ b/zig/kernels/metal/deepseek_v41/ops.metal @@ -0,0 +1,312 @@ +// Math: deepseek-ai/DeepSeek-V4.1-Flash inference/model.py, revision 2cba9e42aa026125f3ed06c6d98c1db82f7ca027. +#include +using namespace metal; +inline float bf(ushort x) { return as_type(uint(x) << 16); } +inline ushort rb(float x) { + uint u = as_type(x); + if ((u & 0x7fffffff) > 0x7f800000) return ushort((u >> 16) | 0x40); + return ushort((u + 0x7fff + ((u >> 16) & 1)) >> 16); +} +inline float rd(const device uchar* p, ulong i, uint dtype) { + if (dtype==1) return ((const device float*)p)[i]; + if (dtype==2) return float(((const device half*)p)[i]); + return bf(((const device ushort*)p)[i]); +} +struct Rms { uint rows, width, x_stride, y_stride; float eps; uint weight_f32; }; +static_assert(sizeof(Rms) == 24, "Rms must mirror ops.zig's RmsArgs"); +#pragma clang fp contract(off) +kernel void dsv41_rms(const device ushort* x [[buffer(0)]], const device uchar* w [[buffer(1)]], + device ushort* y [[buffer(2)]], constant Rms& d [[buffer(3)]], + uint row [[threadgroup_position_in_grid]], uint t [[thread_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]], uint sg [[simdgroup_index_in_threadgroup]]) { + threadgroup float sums[8]; + float s = 0; + for (uint i = t; i < d.width; i += 256) { float a = bf(x[ulong(row)*d.x_stride+i]); s += a*a; } + s = simd_sum(s); + if (lane == 0) sums[sg] = s; + threadgroup_barrier(mem_flags::mem_threadgroup); + if (sg == 0) { + float total = simd_sum(lane < 8 ? sums[lane] : 0.0f); + const float factor = 1.0f / float(d.width); + if (lane == 0) sums[0] = rsqrt(total * factor + d.eps); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + for (uint i = t; i < d.width; i += 256) + y[ulong(row)*d.y_stride+i] = rb((bf(x[ulong(row)*d.x_stride+i])*sums[0])*rd(w,i,d.weight_f32)); +} +#pragma clang fp contract(on) +// Each SIMD group emits four columns; compensated dots do not depend on token count. + +// Precision: 0=BF16, 1=FP32, 2=FP16; FP16 weights never round through BF16. +inline void dense_add(thread float& high, thread float& low, float value) { + float next = high + value; + float borrowed = next - high; + low += (high - (next - borrowed)) + (value - borrowed); + high = next; +} +struct Dense { uint rows, k, n, groups, x_stride, w_stride, y_stride, x_dtype, w_dtype, y_dtype; }; +static_assert(sizeof(Dense) == 40, "Dense must mirror ops.zig's Dense"); +kernel void dsv41_dense_col1(const device uchar* x [[buffer(0)]], const device uchar* w [[buffer(1)]], + device uchar* y [[buffer(2)]], constant Dense& d [[buffer(3)]], + uint3 g [[threadgroup_position_in_grid]], uint lane [[thread_index_in_simdgroup]], + uint sg [[simdgroup_index_in_threadgroup]]) { + const uint col = g.x*4 + sg; + if (col >= d.n) return; + float a = 0, residual = 0; + for (uint k = lane; k < d.k; k += 32) { + float v = rd(x, ulong(g.y)*d.x_stride+ulong(g.z)*d.k+k, d.x_dtype); + float weight = rd(w, (ulong(g.z)*d.n+col)*d.w_stride+k, d.w_dtype); + float product = v * weight; + dense_add(a, residual, product); + if (d.x_dtype == 1 || d.w_dtype == 1) residual += fma(v, weight, -product); + } + for (uint offset = 16; offset != 0; offset >>= 1) { + float other = simd_shuffle_xor(a, offset); + float other_residual = simd_shuffle_xor(residual, offset); + dense_add(a, residual, other); + residual += other_residual; + } + float v = a + residual; + if (lane == 0) { + ulong i = ulong(g.y)*d.y_stride+ulong(g.z)*d.n+col; + if (d.y_dtype==1) ((device float*)y)[i]=v; + else if (d.y_dtype==2) ((device half*)y)[i]=half(v); + else ((device ushort*)y)[i]=rb(v); + } +} + +// The one-column dot with the weight dtype resolved at compile time and four k-steps of loads hoisted; same adds. +inline float dsv41_hf(ushort u) { return float(as_type(u)); } +#define DSV41_DENSE_COL1_SPEC(NAME, LOADW) \ +kernel void NAME(const device uchar* x [[buffer(0)]], const device uchar* w [[buffer(1)]], \ + device uchar* y [[buffer(2)]], constant Dense& d [[buffer(3)]], \ + uint3 g [[threadgroup_position_in_grid]], uint lane [[thread_index_in_simdgroup]], \ + uint sg [[simdgroup_index_in_threadgroup]]) { \ + const uint col = g.x*4 + sg; \ + if (col >= d.n) return; \ + const device ushort* xr = (const device ushort*)x + ulong(g.y)*d.x_stride; \ + const device ushort* wr = (const device ushort*)w + (ulong(g.z)*d.n+col)*d.w_stride; \ + float a = 0, residual = 0; \ + uint k = lane; \ + for (; k + 96 < d.k; k += 128) { \ + float v0 = bf(xr[k]); float w0 = LOADW(wr[k]); \ + float v1 = bf(xr[k+32]); float w1 = LOADW(wr[k+32]); \ + float v2 = bf(xr[k+64]); float w2 = LOADW(wr[k+64]); \ + float v3 = bf(xr[k+96]); float w3 = LOADW(wr[k+96]); \ + float p0 = v0*w0; dense_add(a, residual, p0); if (d.x_dtype == 1 || d.w_dtype == 1) residual += fma(v0, w0, -p0); \ + float p1 = v1*w1; dense_add(a, residual, p1); if (d.x_dtype == 1 || d.w_dtype == 1) residual += fma(v1, w1, -p1); \ + float p2 = v2*w2; dense_add(a, residual, p2); if (d.x_dtype == 1 || d.w_dtype == 1) residual += fma(v2, w2, -p2); \ + float p3 = v3*w3; dense_add(a, residual, p3); if (d.x_dtype == 1 || d.w_dtype == 1) residual += fma(v3, w3, -p3); \ + } \ + for (; k < d.k; k += 32) { \ + float v = bf(xr[k]); \ + float weight = LOADW(wr[k]); \ + float product = v * weight; \ + dense_add(a, residual, product); \ + if (d.x_dtype == 1 || d.w_dtype == 1) residual += fma(v, weight, -product); \ + } \ + for (uint offset = 16; offset != 0; offset >>= 1) { \ + float other = simd_shuffle_xor(a, offset); \ + float other_residual = simd_shuffle_xor(residual, offset); \ + dense_add(a, residual, other); \ + residual += other_residual; \ + } \ + float v = a + residual; \ + if (lane == 0) { \ + ulong i = ulong(g.y)*d.y_stride+ulong(g.z)*d.n+col; \ + if (d.y_dtype==1) ((device float*)y)[i]=v; \ + else if (d.y_dtype==2) ((device half*)y)[i]=half(v); \ + else ((device ushort*)y)[i]=rb(v); \ + } \ +} +DSV41_DENSE_COL1_SPEC(dsv41_dense_col1_bf16, bf) +DSV41_DENSE_COL1_SPEC(dsv41_dense_col1_f16, dsv41_hf) +kernel void dsv41_dense(const device uchar* x [[buffer(0)]], const device uchar* w [[buffer(1)]], + device uchar* y [[buffer(2)]], constant Dense& d [[buffer(3)]], + uint3 g [[threadgroup_position_in_grid]], uint lane [[thread_index_in_simdgroup]], + uint sg [[simdgroup_index_in_threadgroup]]) { + uint col = g.x*16 + sg*4; + float a[4] = {0,0,0,0}, residual[4] = {0,0,0,0}; + for (uint k = lane; k < d.k; k += 32) { + float v = rd(x,ulong(g.y)*d.x_stride+ulong(g.z)*d.k+k,d.x_dtype); + for (uint j=0;j<4;j++) if (col+j>= 1) { + float other = simd_shuffle_xor(a[j], offset); + float other_residual = simd_shuffle_xor(residual[j], offset); + dense_add(a[j], residual[j], other); + residual[j] += other_residual; + } + float v = a[j] + residual[j]; + if (lane==0 && col+j=d.width || i.y>=d.rows) return; + ushort v=table[ulong(ids[i.y])*d.table_stride+i.x]; + for (uint c=0;c=d.width || i.y>=d.rows) return; + ulong k=ulong(i.y)*d.input_stride+i.x; + float a=min(rd(gate,k,d.input_f32),10.0f), b=clamp(rd(up,k,d.input_f32),-10.0f,10.0f); + float v=(a/(1.0f+exp(-a)))*b; + if (d.weighted) v=weights[i.y]*v; + y[ulong(i.y)*d.output_stride+i.x]=rb(v); +} +// The drafter's conditioning: the mean of the hyper-connection's four stream copies, one row into a slot. +struct StreamMean { uint rows, width, stream_stride, out_stride, slot, row_base, ring; }; +static_assert(sizeof(StreamMean) == 28, "StreamMean must mirror ops.zig's StreamMean"); +kernel void dsv41_stream_mean(const device ushort* stream [[buffer(0)]], device ushort* out [[buffer(1)]], + constant StreamMean& d [[buffer(2)]], uint2 i [[thread_position_in_grid]]) { + if (i.x >= d.width || i.y >= d.rows) return; + const ulong s = ulong(i.y) * d.stream_stride + i.x; + const float mean = (bf(stream[s]) + bf(stream[s + d.width]) + bf(stream[s + 2 * ulong(d.width)]) + bf(stream[s + 3 * ulong(d.width)])) * 0.25f; + // The drafter's conditioning reads the three target layers as one 15,360-wide row: a layer a third. + const ulong row = (ulong(d.row_base) + i.y) % ulong(d.ring); + out[row * ulong(3u * d.out_stride) + ulong(d.slot) * ulong(d.out_stride) + i.x] = rb(mean); +} +// The drafter's input: a projected hidden state plus a token's embedding, both bf16 rows. +struct Add { uint rows, width, a_stride, b_stride, y_stride; }; +static_assert(sizeof(Add) == 20, "Add must mirror ops.zig's Add"); +kernel void dsv41_add(const device ushort* a [[buffer(0)]], const device ushort* b [[buffer(1)]], + device ushort* y [[buffer(2)]], constant Add& d [[buffer(3)]], + uint2 i [[thread_position_in_grid]]) { + if (i.x >= d.width || i.y >= d.rows) return; + y[ulong(i.y) * d.y_stride + i.x] = rb(bf(a[ulong(i.y) * d.a_stride + i.x]) + bf(b[ulong(i.y) * d.b_stride + i.x])); +} +struct Combine { uint rows,width,routed_row_stride,slot_stride,shared_stride,y_stride,input_f32,id_stride; }; +static_assert(sizeof(Combine) == 32, "Combine must mirror ops.zig's Combine"); +kernel void dsv41_combine(const device uchar* routed [[buffer(0)]], const device uchar* shared [[buffer(1)]], + const device uint* ids [[buffer(2)]], device ushort* y [[buffer(3)]], + constant Combine& d [[buffer(4)]], + uint2 i [[thread_position_in_grid]], uint t [[thread_index_in_threadgroup]]) { + threadgroup uint slots[6]; + if (t==0) { + for (uint a=0;a0 && ids[ulong(i.y)*d.id_stride+slots[j-1]]>ids[ulong(i.y)*d.id_stride+slot]) { + slots[j]=slots[j-1]; j--; + } + slots[j]=slot; + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (i.x>=d.width || i.y>=d.rows) return; + for (uint slot=0;slot=384) { + y[ulong(i.y)*d.y_stride+i.x]=rb(NAN); + return; + } + float s=0; + for (uint rank=0;rank