From 7495b0ae942b760494bd779db18cc525cc2e9797 Mon Sep 17 00:00:00 2001 From: EugeneClaw Date: Fri, 6 Nov 2026 12:46:22 +0000 Subject: [PATCH 001/117] =?UTF-8?q?DeepSeek-V4.1-Flash=20on=20Metal:=20the?= =?UTF-8?q?=20EXL3=202.9bpw=20lane=20=E2=80=94=20trellis-decoded=20kernels?= =?UTF-8?q?,=20streamed=20Engram,=20drafted=20decode,=20retained=20prompt?= =?UTF-8?q?=20cache?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 3 + THIRD_PARTY_NOTICES.md | 15 + bench/patch527-asserts.py | 102 + bench/patch527-mirrors.py | 193 + bench/patch537-prefill-many.diff | 445 ++ bench/patch538-prompt-merge.diff | 830 +++ bench/r536-compare.py | 46 + bench/r536-multi8.py | 142 + bench/r536-prefill-sweep.py | 160 + bench/r538-compare.py | 50 + bench/r538-multi8.py | 152 + bench/r538-pair.py | 68 + bench/r542_long.py | 21 + bench/r542_prof.py | 24 + bench/r543_sampled.py | 138 + build.zig | 6 +- docs/deepseek-v41-mhc-fp64.json | 103 + docs/deepseek-v41.md | 129 + tools/zig/check_dsv41_metal_mirrors.sh | 24 + tools/zig/dsv41_metal_struct_sizes.py | 216 + tools/zig/lean_check.py | 4 +- zig/build/deepseek_v41.zig | 80 + zig/build/exl3.zig | 13 +- zig/build/metal_targets.zig | 69 +- zig/deepseek_v41_checks.zig | 14 + zig/deepseek_v41_reference_checks.zig | 21 + zig/deepseek_v41_run.zig | 447 ++ zig/deepseek_v41_weights_checks.zig | 8 + zig/dsv41_core_family.zig | 14 + zig/dsv41_token_map.zig | 27 +- zig/exl3_projection_bench.zig | 2 +- zig/kernels/metal/core/affine_mm.metal | 146 +- zig/kernels/metal/core/affine_mm_i8.h | 125 + zig/kernels/metal/core/exl3_projection.metal | 1381 +++- .../metal/core/exl3_projection_i8.metal | 117 + .../metal/core/exl3_projection_nax.metal | 5886 ++++++++++++++++ .../metal/core/exl3_projection_nax_i8.metal | 752 ++ zig/kernels/metal/core/expert_groups.metal | 45 + zig/kernels/metal/core/mlx/gather.metal | 14 + zig/kernels/metal/core/mlx/mlx_steel.h | 6267 +++++++++++++++++ zig/kernels/metal/deepseek_v41/cand.metal | 1 + zig/kernels/metal/deepseek_v41/compress.metal | 3 + zig/kernels/metal/deepseek_v41/csa2.metal | 105 + .../metal/deepseek_v41/csa2_attn.metal | 2 + zig/kernels/metal/deepseek_v41/csa2_nax.metal | 493 ++ zig/kernels/metal/deepseek_v41/engram.metal | 1 + .../metal/deepseek_v41/engram_exl3.metal | 160 + zig/kernels/metal/deepseek_v41/experts.metal | 1 + .../metal/deepseek_v41/experts_kimi.metal | 3 + .../metal/deepseek_v41/experts_mma.metal | 1 + zig/kernels/metal/deepseek_v41/fold.metal | 2 + zig/kernels/metal/deepseek_v41/fp8_mma.metal | 1 + zig/kernels/metal/deepseek_v41/fp8_rows.metal | 2 + zig/kernels/metal/deepseek_v41/fused.metal | 6 + zig/kernels/metal/deepseek_v41/glue.metal | 5 + zig/kernels/metal/deepseek_v41/glue_tmp.metal | 12 + zig/kernels/metal/deepseek_v41/hc.metal | 2 + .../metal/deepseek_v41/hc_boundary.metal | 185 + zig/kernels/metal/deepseek_v41/index.metal | 1 + .../metal/deepseek_v41/index_exl3.metal | 855 +++ zig/kernels/metal/deepseek_v41/kv.metal | 176 + zig/kernels/metal/deepseek_v41/kv_glue.metal | 85 + zig/kernels/metal/deepseek_v41/mhc.metal | 437 ++ zig/kernels/metal/deepseek_v41/mv.metal | 1 + zig/kernels/metal/deepseek_v41/ops.metal | 325 + zig/kernels/metal/deepseek_v41/rope.metal | 18 + zig/kernels/metal/deepseek_v41/route.metal | 1 + .../metal/deepseek_v41/route_exl3.metal | 85 + .../metal/deepseek_v41/struct_sizes.txt | 89 + zig/kernels/metal/deepseek_v41/topk512.metal | 1 + zig/kernels/metal/prefill/gemm_nax.metal | 37 +- zig/kernels/metal/sources.zig | 32 +- zig/src/core/affine_mm.zig | 13 +- zig/src/core/contract/registry.zig | 2 + zig/src/core/engine_api.zig | 4 + zig/src/core/exl3_layout.zig | 4 +- zig/src/core/exl3_projection.zig | 1565 +++- zig/src/core/exl3_projection_gpu_test.zig | 88 + zig/src/core/expert_groups.zig | 122 + zig/src/core/gpu_counters.zig | 78 +- zig/src/core/lane_stream.zig | 2 +- zig/src/core/lanes/config.zig | 3 + zig/src/core/lanes/engine.zig | 87 + zig/src/core/lanes/stream.zig | 1 + zig/src/core/prompt_cache.zig | 119 +- zig/src/core/prompt_cache_end_test.zig | 139 + zig/src/core/prompt_cache_index.zig | 14 + zig/src/core/prompt_rules.zig | 11 + zig/src/core/root.zig | 13 + zig/src/core/tokenizer/tokenizer.zig | 3 + zig/src/families/deepseek_v41/attention.zig | 1137 +++ zig/src/families/deepseek_v41/backend.zig | 1290 ++++ zig/src/families/deepseek_v41/csa2.zig | 278 + zig/src/families/deepseek_v41/csa2_index.zig | 464 ++ zig/src/families/deepseek_v41/csa2_test.zig | 571 ++ zig/src/families/deepseek_v41/draft/lanes.zig | 9 +- zig/src/families/deepseek_v41/engram.zig | 269 + .../deepseek_v41/engram_rows_safetensors.zig | 576 ++ .../engram_rows_safetensors_test.zig | 237 + zig/src/families/deepseek_v41/engram_test.zig | 334 + .../fixtures/hc_attention_rms.json | 25 + .../deepseek_v41/fixtures/hc_fp64_rows.json | 1 + .../deepseek_v41/index_precision_test.zig | 57 + zig/src/families/deepseek_v41/kv.zig | 255 + zig/src/families/deepseek_v41/kv/sess.zig | 2 +- zig/src/families/deepseek_v41/kv_state.zig | 203 +- zig/src/families/deepseek_v41/kv_test.zig | 356 + zig/src/families/deepseek_v41/load.zig | 332 +- zig/src/families/deepseek_v41/metal/cand.zig | 5 +- .../families/deepseek_v41/metal/compress.zig | 11 +- .../families/deepseek_v41/metal/csa2_attn.zig | 4 +- .../families/deepseek_v41/metal/engram.zig | 2 +- .../families/deepseek_v41/metal/experts.zig | 6 +- .../deepseek_v41/metal/experts_mma.zig | 2 +- zig/src/families/deepseek_v41/metal/fold.zig | 8 +- .../families/deepseek_v41/metal/fp8_mma.zig | 2 +- .../families/deepseek_v41/metal/fp8_rows.zig | 7 +- zig/src/families/deepseek_v41/metal/fused.zig | 22 +- zig/src/families/deepseek_v41/metal/glue.zig | 40 +- .../families/deepseek_v41/metal/glue_k.zig | 13 +- zig/src/families/deepseek_v41/metal/hc.zig | 4 +- zig/src/families/deepseek_v41/metal/index.zig | 5 +- .../deepseek_v41/metal/index_mirror.zig | 211 + zig/src/families/deepseek_v41/metal/mv.zig | 2 +- zig/src/families/deepseek_v41/mhc.zig | 309 + zig/src/families/deepseek_v41/mhc_test.zig | 209 + .../families/deepseek_v41/mirror_checked.zig | 132 + zig/src/families/deepseek_v41/model.zig | 4144 ++++++++++- zig/src/families/deepseek_v41/ops.zig | 373 + zig/src/families/deepseek_v41/ops_check.zig | 241 + zig/src/families/deepseek_v41/pack.zig | 24 +- zig/src/families/deepseek_v41/profiler.zig | 97 + .../deepseek_v41/review_session_test.zig | 4 +- zig/src/families/deepseek_v41/rope.zig | 136 + zig/src/families/deepseek_v41/route.zig | 58 + zig/src/families/deepseek_v41/route_test.zig | 187 + zig/src/families/deepseek_v41/scan_probe.zig | 141 + zig/src/families/deepseek_v41/shared_test.zig | 1 + .../families/deepseek_v41/test_support.zig | 40 + zig/src/families/deepseek_v41/token_map.zig | 463 ++ zig/src/families/deepseek_v41/view.zig | 25 + zig/src/families/deepseek_v41/weights.zig | 748 ++ zig/src/families/deepseek_v41/workspace.zig | 184 + zig/src/metal/command.zig | 35 + zig/src/metal/counters.zig | 4 +- zig/src/metal/library.zig | 23 + zig/src/metal/metal.zig | 2 + zig/src/metal_counter_consumer.zig | 8 +- zig/src/native/deepseek_v41_lane_host.zig | 258 + zig/src/native/metal.zig | 3 + zig/src/server/cli.zig | 15 +- zig/src/tensorfold.zig | 19 + zig/tests/contract/metal_limits.zig | 6 + .../deepseek_v41_reference/attention_math.zig | 498 ++ .../deepseek_v41_reference/engram_math.zig | 148 + .../deepseek_v41_reference/exl3_int8_tile.zig | 86 + zig/tests/deepseek_v41_reference/margins.zig | 94 + zig/tests/deepseek_v41_reference/math.zig | 424 ++ .../operator_affine_i8_fp64.zig | 119 + .../operator_attention.zig | 155 + .../operator_combine_fp64.zig | 158 + .../operator_csa2_fp64.zig | 338 + .../operator_csa2_index_fp64.zig | 275 + .../operator_csa2_pack_fp64.zig | 103 + .../operator_csa2_rope_fp64.zig | 136 + .../operator_csa2_sparse_fp64.zig | 544 ++ .../operator_diagnostic.zig | 125 + .../operator_exl3_projection_fp64.zig | 1842 +++++ .../deepseek_v41_reference/operator_hc.zig | 98 + .../operator_hc_amplify_fp64.zig | 284 + .../operator_hc_fp64.zig | 515 ++ .../operator_hc_split_fp64.zig | 303 + .../operator_history.zig | 298 + .../deepseek_v41_reference/operator_moe.zig | 409 ++ .../deepseek_v41_reference/operators.zig | 92 + zig/tests/deepseek_v41_reference/profile.zig | 52 + .../deepseek_v41_reference/projection.zig | 510 ++ zig/tests/deepseek_v41_reference/qualify.zig | 230 + .../deepseek_v41_reference/reference.zig | 329 + .../rope_frequencies.json | 14 + .../deepseek_v41_reference/row_invariance.zig | 217 + .../deepseek_v41_reference/stagediff.zig | 610 ++ zig/tests/deepseek_v41_reference/trace.zig | 381 + .../deepseek_v41_reference/wo_a_fusion.zig | 152 + zig/tests/dsv41_gate_bench.zig | 474 ++ zig/tests/dsv41_gemm_bench.zig | 5667 +++++++++++++++ zig/tests/dsv41_scan_bench.zig | 338 + zig/tests/fp8_repack.zig | 350 + zig/tests/mlx_gather.zig | 147 + zig/tests/mm_bench.zig | 11 +- zig/tests/r519_bf16_mma.metal | 128 + zig/tf_ids_tmp.zig | 23 + 192 files changed, 54645 insertions(+), 356 deletions(-) create mode 100644 bench/patch527-asserts.py create mode 100644 bench/patch527-mirrors.py create mode 100644 bench/patch537-prefill-many.diff create mode 100644 bench/patch538-prompt-merge.diff create mode 100644 bench/r536-compare.py create mode 100644 bench/r536-multi8.py create mode 100644 bench/r536-prefill-sweep.py create mode 100755 bench/r538-compare.py create mode 100755 bench/r538-multi8.py create mode 100644 bench/r538-pair.py create mode 100644 bench/r542_long.py create mode 100644 bench/r542_prof.py create mode 100644 bench/r543_sampled.py create mode 100644 docs/deepseek-v41-mhc-fp64.json create mode 100644 docs/deepseek-v41.md create mode 100755 tools/zig/check_dsv41_metal_mirrors.sh create mode 100755 tools/zig/dsv41_metal_struct_sizes.py create mode 100644 zig/build/deepseek_v41.zig create mode 100644 zig/deepseek_v41_checks.zig create mode 100644 zig/deepseek_v41_reference_checks.zig create mode 100644 zig/deepseek_v41_run.zig create mode 100644 zig/deepseek_v41_weights_checks.zig create mode 100644 zig/dsv41_core_family.zig create mode 100644 zig/kernels/metal/core/affine_mm_i8.h create mode 100644 zig/kernels/metal/core/exl3_projection_i8.metal create mode 100644 zig/kernels/metal/core/exl3_projection_nax.metal create mode 100644 zig/kernels/metal/core/exl3_projection_nax_i8.metal create mode 100644 zig/kernels/metal/core/expert_groups.metal create mode 100644 zig/kernels/metal/core/mlx/gather.metal create mode 100644 zig/kernels/metal/core/mlx/mlx_steel.h create mode 100644 zig/kernels/metal/deepseek_v41/csa2.metal create mode 100644 zig/kernels/metal/deepseek_v41/csa2_nax.metal create mode 100644 zig/kernels/metal/deepseek_v41/engram_exl3.metal create mode 100644 zig/kernels/metal/deepseek_v41/hc_boundary.metal create mode 100644 zig/kernels/metal/deepseek_v41/index_exl3.metal create mode 100644 zig/kernels/metal/deepseek_v41/kv.metal create mode 100644 zig/kernels/metal/deepseek_v41/kv_glue.metal create mode 100644 zig/kernels/metal/deepseek_v41/mhc.metal create mode 100644 zig/kernels/metal/deepseek_v41/ops.metal create mode 100644 zig/kernels/metal/deepseek_v41/rope.metal create mode 100644 zig/kernels/metal/deepseek_v41/route_exl3.metal create mode 100644 zig/kernels/metal/deepseek_v41/struct_sizes.txt create mode 100644 zig/src/core/expert_groups.zig create mode 100644 zig/src/core/prompt_cache_end_test.zig create mode 100644 zig/src/families/deepseek_v41/attention.zig create mode 100644 zig/src/families/deepseek_v41/backend.zig create mode 100644 zig/src/families/deepseek_v41/csa2.zig create mode 100644 zig/src/families/deepseek_v41/csa2_index.zig create mode 100644 zig/src/families/deepseek_v41/csa2_test.zig create mode 100644 zig/src/families/deepseek_v41/engram.zig create mode 100644 zig/src/families/deepseek_v41/engram_rows_safetensors.zig create mode 100644 zig/src/families/deepseek_v41/engram_rows_safetensors_test.zig create mode 100644 zig/src/families/deepseek_v41/engram_test.zig create mode 100644 zig/src/families/deepseek_v41/fixtures/hc_attention_rms.json create mode 100644 zig/src/families/deepseek_v41/fixtures/hc_fp64_rows.json create mode 100644 zig/src/families/deepseek_v41/index_precision_test.zig create mode 100644 zig/src/families/deepseek_v41/kv.zig create mode 100644 zig/src/families/deepseek_v41/kv_test.zig create mode 100644 zig/src/families/deepseek_v41/metal/index_mirror.zig create mode 100644 zig/src/families/deepseek_v41/mhc.zig create mode 100644 zig/src/families/deepseek_v41/mhc_test.zig create mode 100644 zig/src/families/deepseek_v41/mirror_checked.zig create mode 100644 zig/src/families/deepseek_v41/ops.zig create mode 100644 zig/src/families/deepseek_v41/ops_check.zig create mode 100644 zig/src/families/deepseek_v41/profiler.zig create mode 100644 zig/src/families/deepseek_v41/rope.zig create mode 100644 zig/src/families/deepseek_v41/route.zig create mode 100644 zig/src/families/deepseek_v41/route_test.zig create mode 100644 zig/src/families/deepseek_v41/scan_probe.zig create mode 100644 zig/src/families/deepseek_v41/test_support.zig create mode 100644 zig/src/families/deepseek_v41/token_map.zig create mode 100644 zig/src/families/deepseek_v41/view.zig create mode 100644 zig/src/families/deepseek_v41/weights.zig create mode 100644 zig/src/families/deepseek_v41/workspace.zig create mode 100644 zig/src/native/deepseek_v41_lane_host.zig create mode 100644 zig/tests/deepseek_v41_reference/attention_math.zig create mode 100644 zig/tests/deepseek_v41_reference/engram_math.zig create mode 100644 zig/tests/deepseek_v41_reference/exl3_int8_tile.zig create mode 100644 zig/tests/deepseek_v41_reference/margins.zig create mode 100644 zig/tests/deepseek_v41_reference/math.zig create mode 100644 zig/tests/deepseek_v41_reference/operator_affine_i8_fp64.zig create mode 100644 zig/tests/deepseek_v41_reference/operator_attention.zig create mode 100644 zig/tests/deepseek_v41_reference/operator_combine_fp64.zig create mode 100644 zig/tests/deepseek_v41_reference/operator_csa2_fp64.zig create mode 100644 zig/tests/deepseek_v41_reference/operator_csa2_index_fp64.zig create mode 100644 zig/tests/deepseek_v41_reference/operator_csa2_pack_fp64.zig create mode 100644 zig/tests/deepseek_v41_reference/operator_csa2_rope_fp64.zig create mode 100644 zig/tests/deepseek_v41_reference/operator_csa2_sparse_fp64.zig create mode 100644 zig/tests/deepseek_v41_reference/operator_diagnostic.zig create mode 100644 zig/tests/deepseek_v41_reference/operator_exl3_projection_fp64.zig create mode 100644 zig/tests/deepseek_v41_reference/operator_hc.zig create mode 100644 zig/tests/deepseek_v41_reference/operator_hc_amplify_fp64.zig create mode 100644 zig/tests/deepseek_v41_reference/operator_hc_fp64.zig create mode 100644 zig/tests/deepseek_v41_reference/operator_hc_split_fp64.zig create mode 100644 zig/tests/deepseek_v41_reference/operator_history.zig create mode 100644 zig/tests/deepseek_v41_reference/operator_moe.zig create mode 100644 zig/tests/deepseek_v41_reference/operators.zig create mode 100644 zig/tests/deepseek_v41_reference/profile.zig create mode 100644 zig/tests/deepseek_v41_reference/projection.zig create mode 100644 zig/tests/deepseek_v41_reference/qualify.zig create mode 100644 zig/tests/deepseek_v41_reference/reference.zig create mode 100644 zig/tests/deepseek_v41_reference/rope_frequencies.json create mode 100644 zig/tests/deepseek_v41_reference/row_invariance.zig create mode 100644 zig/tests/deepseek_v41_reference/stagediff.zig create mode 100644 zig/tests/deepseek_v41_reference/trace.zig create mode 100644 zig/tests/deepseek_v41_reference/wo_a_fusion.zig create mode 100644 zig/tests/dsv41_gate_bench.zig create mode 100644 zig/tests/dsv41_gemm_bench.zig create mode 100644 zig/tests/dsv41_scan_bench.zig create mode 100644 zig/tests/fp8_repack.zig create mode 100644 zig/tests/mlx_gather.zig create mode 100644 zig/tests/r519_bf16_mma.metal create mode 100644 zig/tf_ids_tmp.zig diff --git a/.gitignore b/.gitignore index 6e647ef2c26..46242339862 100644 --- a/.gitignore +++ b/.gitignore @@ -28,6 +28,9 @@ zig-out/ # Versioned GUI build resources, generated app engines stay ignored in app/.gitignore. !app/build/ +# mHC fp64 qualification receipts. +/receipts/ +*.log # 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/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index e9889018a67..59bda48543d 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -268,6 +268,13 @@ TensorFold ships no model weights. The `z-lab/Qwen3.8-27B-DFlash2` model card st The optional `incoai/GLM-5.3-Flash-DFlash2` model card states CC BY-NC-ND 4.0, for non-commercial use without derivatives; only the Python engine reads that drafter. 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 @@ -424,6 +431,14 @@ No external reference, captured cubin, model shard or CUDA compiler is bundled b The shared EXL3 resolver split and CUDA lane option forwarding retain work from PR #728 by @ajensenwaud, with the common EXL3 and DeepSeek contributor credits preserved. +## BobClawblaw/TensorFold: the int8 affine kernels + +`zig/kernels/metal/core/affine_mm.metal` and `affine_mm_i8.h` are copied whole from +[BobClawblaw/TensorFold](https://github.com/BobClawblaw/TensorFold), branch `deepseek-v41-main`, commit +`72a552ed` ("deepseek_v41: prompt chunks' routed experts in int8 x int8"), Apache License 2.0, +Copyright 2026 Bob. They are the working int8 ground truth for the DeepSeek-V4.1 gated int8 expert path: +the compiled code settles the fragment packing and the store mapping. With `TF_I8` undefined they reduce +to the bf16 kernels this tree already carried. ## MiaAI-Lab Flash Next prompt expert staging `zig/kernels/cuda/nvfp4_experts_tile.cu` adapts the K32 shared-memory pipeline in patch0014 of diff --git a/bench/patch527-asserts.py b/bench/patch527-asserts.py new file mode 100644 index 00000000000..9dd9e25835a --- /dev/null +++ b/bench/patch527-asserts.py @@ -0,0 +1,102 @@ +#!/usr/bin/env python3 +"""ROUND-527: add the 20 missing `static_assert(sizeof(T) == N)` lines to the DeepSeek V4.1 Metal sources. + +Each size comes from the Metal compiler's own record-layout dump (tools/zig/dsv41_metal_struct_sizes.py), +not from hand arithmetic. The assert is inserted on its own line straight after the struct's closing +`};`, in the file that defines the struct. Idempotent: a struct that already asserts its size is left alone. +""" +import os +import sys + +ASSERTS = { + "ops.metal": [ + ("Dense", 40, "Dense must mirror ops.zig's Dense"), + ("Activation", 24, "Activation must mirror ops.zig's Activation"), + ("Copy", 16, "Copy must mirror ops.zig's Copy"), + ("Combine", 32, "Combine must mirror ops.zig's Combine"), + ], + "index_exl3.metal": [ + ("Dsv41Pick", 8, "Dsv41Pick must keep its 8-byte (float score, int position) record"), + ], + "engram_exl3.metal": [ + ("EngramHistory", 16, "EngramHistory must mirror engram.zig's History"), + ], + "cand.metal": [ + ("TfCandArgs", 12, "TfCandArgs must mirror metal/cand.zig's Args"), + ], + "fused.metal": [ + ("TfFPostArgs", 8, "TfFPostArgs must mirror metal/fused.zig's PostArgs"), + ("TfFQuantArgs", 28, "TfFQuantArgs must mirror metal/glue.zig's Strides"), + ], + "glue_tmp.metal": [ + ("TfGCandArgs", 12, "TfGCandArgs must mirror metal/glue.zig's GCandArgs"), + ("TfGEmbedArgs", 12, "TfGEmbedArgs must mirror metal/glue.zig's GEmbedArgs"), + ("TfGFp4Args", 24, "TfGFp4Args must mirror metal/glue.zig's GFp4Args"), + ("TfGFp4RtArgs", 12, "TfGFp4RtArgs must mirror metal/glue.zig's GFp4RtArgs"), + ("TfGHcArgs2", 8, "TfGHcArgs2 must mirror metal/glue.zig's GHcArgs2"), + ("TfGMeanArgs", 12, "TfGMeanArgs must mirror metal/glue.zig's GMeanArgs"), + ("TfGMvArgs", 8, "TfGMvArgs must keep its 8-byte (k, n) pair (glue_tmp's own mv kernel)"), + ("TfGPoolArgs", 8, "TfGPoolArgs must mirror metal/glue.zig's GPoolArgs"), + ("TfGRopeArgs", 24, "TfGRopeArgs must mirror metal/glue.zig's GRopeArgs"), + ("TfGScatterArgs", 12, "TfGScatterArgs must mirror metal/glue.zig's GScatterArgs"), + ], + "compress.metal": [ + ("TfCPoolArgs", 8, "TfCPoolArgs must mirror metal/compress.zig's PoolArgs"), + ("TfCRtArgs", 12, "TfCRtArgs must mirror metal/compress.zig's RtArgs"), + ("TfCPackArgs", 24, "TfCPackArgs must mirror metal/compress.zig's PackArgs"), + ], + "fold.metal": [ + ("TfOPostArgs", 20, "TfOPostArgs must mirror metal/fold.zig's PostArgs"), + ], + "topk512.metal": [ + ("TfTopk512Args", 4, "TfTopk512Args must mirror metal/glue.zig's TopkArgs"), + ], +} + + +def insert_assert(text, name, size, message): + """Insert the assert right after `struct name { ... };`, or report that it is already asserted.""" + marker = f"struct {name} {{" + at = text.find(marker) + while at != -1: + # A definition, not a use: after the closing brace of the body there is a `;`. + depth, i = 1, at + len(marker) + while i < len(text) and depth: + if text[i] == "{": + depth += 1 + elif text[i] == "}": + depth -= 1 + i += 1 + end = text.find(";", i) + if end == -1: + raise SystemExit(f"struct {name}: no closing `;`") + line_end = text.find("\n", end) + line_end = len(text) if line_end == -1 else line_end + after = text[line_end:] + if after.lstrip().startswith(f"static_assert(sizeof({name})"): + return text, False + line = f'\nstatic_assert(sizeof({name}) == {size}, "{message}");' + return text[:line_end] + line + after, True + raise SystemExit(f"struct {name}: definition not found") + + +def main(directory): + changed = [] + for source, table in ASSERTS.items(): + path = os.path.join(directory, source) + text = open(path, encoding="utf-8").read() + for name, size, message in table: + text, did = insert_assert(text, name, size, message) + if did: + changed.append(f"{source}:{name}") + open(path, "w", encoding="utf-8").write(text) + print(f"asserts added: {len(changed)}") + for line in changed: + print(" " + line) + return 0 + + +if __name__ == "__main__": + root = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + sys.exit(main(sys.argv[1] if len(sys.argv) > 1 else + os.path.join(root, "zig", "kernels", "metal", "deepseek_v41"))) diff --git a/bench/patch527-mirrors.py b/bench/patch527-mirrors.py new file mode 100644 index 00000000000..3559a3c3e04 --- /dev/null +++ b/bench/patch527-mirrors.py @@ -0,0 +1,193 @@ +#!/usr/bin/env python3 +"""ROUND-527 part 2: the Zig side of the struct sweep. + +The R-526 audit's 20 unchecked kernel arguments were mostly positional `[N]u32` payloads built at the callsite +from a semantic Zig struct (ops.Dense, ops.Combine, glue.Strides ...). A tuple cannot be checked: reorder the +Zig struct's fields and the payload silently changes meaning while every size stays put -- the R-468 bug class +exactly. This patch gives each payload a NAMED `extern struct` whose fields are the Metal struct's fields in +the Metal struct's order, builds the payload with NAMED initialisers, and registers the pair in +`mirror_checked.zig`, so `index_mirror.check` compares names, types, array lengths, offsets and total at +comptime. + +No arithmetic, no dispatch, no kernel text changes: every payload's bytes are the same as the tuple's. +""" +import os +import sys + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +FAMILY = os.path.join(ROOT, "zig", "src", "families", "deepseek_v41") + + +def edit(path, pairs): + full = os.path.join(FAMILY, path) + text = open(full, encoding="utf-8").read() + for old, new, count in pairs: + have = text.count(old) + if have != count: + raise SystemExit(f"{path}: expected {count} of\n---\n{old}\n---\nfound {have}") + text = text.replace(old, new) + open(full, "w", encoding="utf-8").write(text) + print(f"edited {path}") + + +# ---- ops.zig: the four payloads that had named structs and still went out as tuples -------------------- +DENSE_ARGS = """ +/// ROUND-527: the kernel's `Dense` record, field for field (it was a positional payload until this round). +pub const DenseArgs = extern struct { rows: u32, k: u32, n: u32, groups: u32, x_stride: u32, w_stride: u32, y_stride: u32, x_dtype: u32, w_dtype: u32, y_dtype: u32 }; +""" +ACTIVATION_ARGS = """ +/// ROUND-527: the kernel's `Activation` record, field for field (`weighted`/`input_f32` as the kernel's uints). +pub const ActivationArgs = extern struct { rows: u32, width: u32, input_stride: u32, output_stride: u32, weighted: u32, input_f32: u32 }; +""" +COMBINE_ARGS = """ +/// ROUND-527: the kernel's `Combine` record, field for field (`input_f32` as the kernel's uint). +pub const CombineArgs = extern struct { rows: u32, width: u32, routed_row_stride: u32, slot_stride: u32, shared_stride: u32, y_stride: u32, input_f32: u32, id_stride: u32 }; +""" +COPY_ARGS = """ +/// ROUND-527: the kernel's `Copy` record, field for field. +pub const CopyArgs = extern struct { rows: u32, width: u32, x_stride: u32, y_stride: u32 }; +""" +edit("ops.zig", [ + (" y_dtype: Dtype = .bf16,\n};", + " y_dtype: Dtype = .bf16,\n};\n" + DENSE_ARGS, 1), + (" input_f32: bool = false,\n};", + " input_f32: bool = false,\n};\n" + ACTIVATION_ARGS, 1), + ("pub const Copy = struct { rows: u32, width: u32, x_stride: u32, y_stride: u32 };", + "pub const Copy = struct { rows: u32, width: u32, x_stride: u32, y_stride: u32 };\n" + COPY_ARGS, 1), + (" id_stride: u32 = 6,\n};", + " id_stride: u32 = 6,\n};\n" + COMBINE_ARGS, 1), + ("e.setValue([10]u32{ d.rows, d.k, d.n, d.groups, d.x_stride, d.w_stride, d.y_stride, @backingInt(d.x_dtype), @backingInt(d.w_dtype), @backingInt(d.y_dtype) }, 3);", + "e.setValue(DenseArgs{ .rows = d.rows, .k = d.k, .n = d.n, .groups = d.groups, .x_stride = d.x_stride, .w_stride = d.w_stride, .y_stride = d.y_stride, .x_dtype = @backingInt(d.x_dtype), .w_dtype = @backingInt(d.w_dtype), .y_dtype = @backingInt(d.y_dtype) }, 3);", 2), + ("e.setValue([6]u32{ d.rows, d.width, d.input_stride, d.output_stride, @intFromBool(d.weighted), @intFromBool(d.input_f32) }, 4);", + "e.setValue(ActivationArgs{ .rows = d.rows, .width = d.width, .input_stride = d.input_stride, .output_stride = d.output_stride, .weighted = @intFromBool(d.weighted), .input_f32 = @intFromBool(d.input_f32) }, 4);", 1), + ("e.setValue([4]u32{ d.rows, d.width, d.x_stride, d.y_stride }, 2);", + "e.setValue(CopyArgs{ .rows = d.rows, .width = d.width, .x_stride = d.x_stride, .y_stride = d.y_stride }, 2);", 1), + ("e.setValue([8]u32{ d.rows, d.width, d.routed_row_stride, d.slot_stride, d.shared_stride, d.y_stride, @intFromBool(d.input_f32), d.id_stride }, 4);", + "e.setValue(CombineArgs{ .rows = d.rows, .width = d.width, .routed_row_stride = d.routed_row_stride, .slot_stride = d.slot_stride, .shared_stride = d.shared_stride, .y_stride = d.y_stride, .input_f32 = @intFromBool(d.input_f32), .id_stride = d.id_stride }, 4);", 1), +]) + +# ---- metal/glue.zig: glue_tmp's live argument records --------------------------------------------------- +GLUE_ARGS = """ +/// ROUND-527: the argument records of glue_tmp's kernels, one named extern struct each so the mirror check +/// compares them field by field (they were positional `[N]u32` payloads until this round). +pub const GRopeArgs = extern struct { pairs: u32, heads: u32, head_stride: u32, row_stride: u32, off: u32, positions: u32 }; +pub const GCandArgs = extern struct { keys: u32, blocks: u32, topk: u32 }; +pub const GHcArgs2 = extern struct { dim: u32, rows: u32 }; +pub const GScatterArgs = extern struct { words: u32, items: u32, rep: u32 }; +pub const GEmbedArgs = extern struct { dim: u32, rows: u32, vocab: u32 }; +pub const GMeanArgs = extern struct { dim: u32, rows: u32, stride: u32 }; +pub const TopkArgs = extern struct { width: u32 }; +""" +edit("metal/glue.zig", [ + ("pub const RouteArgs = extern struct { rows: i32, topk: i32, scale: f32, eps: f32 };", + "pub const RouteArgs = extern struct { rows: i32, topk: i32, scale: f32, eps: f32 };\n" + GLUE_ARGS, 1), + ("pub const Strides = struct { k: u32, nb: u32, na: u32 = 1, sa: u32 = 0, sb: u32, ta: u32 = 0, tb: u32 };", + "pub const Strides = extern struct { k: u32, nb: u32, na: u32, sa: u32, sb: u32, ta: u32, tb: u32 };", 1), + ("e.setValue([6]u32{ head / 2, heads, head, heads * head, head - 64, positions }, 4);", + "e.setValue(GRopeArgs{ .pairs = head / 2, .heads = heads, .head_stride = head, .row_stride = heads * head, .off = head - 64, .positions = positions }, 4);", 1), + ("e.setValue([3]u32{ keys, blocks, topk }, 4);", + "e.setValue(GCandArgs{ .keys = keys, .blocks = blocks, .topk = topk }, 4);", 1), + ("e.setValue([2]u32{ dim, rows }, 3);", + "e.setValue(GHcArgs2{ .dim = dim, .rows = rows }, 3);", 1), + ("e.setValue([2]u32{ dim, rows }, 5);", + "e.setValue(GHcArgs2{ .dim = dim, .rows = rows }, 5);", 1), + ("e.setValue([3]u32{ bytes / 4, items, rep }, 3);", + "e.setValue(GScatterArgs{ .words = bytes / 4, .items = items, .rep = rep }, 3);", 1), + ("e.setValue([3]u32{ dim, rows, vocab }, 4);", + "e.setValue(GEmbedArgs{ .dim = dim, .rows = rows, .vocab = vocab }, 4);", 1), + ("e.setValue([3]u32{ dim, rows, stride }, 2);", + "e.setValue(GMeanArgs{ .dim = dim, .rows = rows, .stride = stride }, 2);", 1), + ("e.setValue([1]u32{width}, 0);", + "e.setValue(TopkArgs{ .width = width }, 0);", 1), +]) + +# ---- metal/cand.zig ------------------------------------------------------------------------------------- +edit("metal/cand.zig", [ + ("/// Candidate blocks of scores [rows][keys] (vis[row] keys count): mask bytes, 1 = candidate; keyed u32 scratch.", + "/// ROUND-527: the kernel's `TfCandArgs` record, field for field (a positional payload until this round).\npub const Args = extern struct { keys: u32, blocks: u32, topk: u32 };\n\n/// Candidate blocks of scores [rows][keys] (vis[row] keys count): mask bytes, 1 = candidate; keyed u32 scratch.", 1), + ("e.setValue([3]u32{ keys, blocks, @min(topk, max_topk) }, 0);", + "e.setValue(Args{ .keys = keys, .blocks = blocks, .topk = @min(topk, max_topk) }, 0);", 1), +]) + +# ---- metal/fused.zig ------------------------------------------------------------------------------------ +edit("metal/fused.zig", [ + ("pub const SwiArgs = extern struct { n: u32, limit: f32 };", + "pub const SwiArgs = extern struct { n: u32, limit: f32 };\n/// ROUND-527: the kernel's `TfFPostArgs` record, field for field.\npub const PostArgs = extern struct { dim: u32, rows: u32 };\n/// ROUND-527: the kernel's `TfFQuantArgs` record, field for field (glue.Strides' fields in the kernel's order).\npub const QuantArgs = extern struct { k: u32, nb: u32, na: u32, sa: u32, sb: u32, ta: u32, tb: u32 };", 1), + ("e.setValue([2]u32{ dim, rows }, 7);", + "e.setValue(PostArgs{ .dim = dim, .rows = rows }, 7);", 1), + ("e.setValue([7]u32{ s.k, s.nb, s.na, s.sa, s.sb, s.ta, s.tb }, 2);", + "e.setValue(QuantArgs{ .k = s.k, .nb = s.nb, .na = s.na, .sa = s.sa, .sb = s.sb, .ta = s.ta, .tb = s.tb }, 2);", 1), +]) + +# ---- metal/compress.zig ---------------------------------------------------------------------------------- +edit("metal/compress.zig", [ + ("pub const threads = 32;", + """pub const threads = 32; + +/// ROUND-527: compress.metal's three argument records, field for field (positional payloads until this round). +pub const PoolArgs = extern struct { rows: u32, dim: u32 }; +pub const RtArgs = extern struct { blocks: u32, in_stride: u32, out_row: u32 }; +pub const PackArgs = extern struct { blocks: u32, in_stride: u32, code_row: u32, scale_row: u32, scale_off: u32, use_dest: u32 };""", 1), + ("e.setValue([2]u32{ rows, dim }, 5);", + "e.setValue(PoolArgs{ .rows = rows, .dim = dim }, 5);", 1), + ("e.setValue([3]u32{ dim / 16, dim, dim }, 3);", + "e.setValue(RtArgs{ .blocks = dim / 16, .in_stride = dim, .out_row = dim }, 3);", 1), + ("e.setValue([6]u32{ k.blocks, k.in_stride, k.code_row, k.scale_row, k.scale_off, @intFromBool(k.dest != null) }, 4);", + "e.setValue(PackArgs{ .blocks = k.blocks, .in_stride = k.in_stride, .code_row = k.code_row, .scale_row = k.scale_row, .scale_off = k.scale_off, .use_dest = @intFromBool(k.dest != null) }, 4);", 1), +]) + +# ---- metal/fold.zig --------------------------------------------------------------------------------------- +edit("metal/fold.zig", [ + ("pub const Routed = struct { out: Ref, where: Ref, weights: Ref, ids: Ref, sum: Ref, topk: u32, per_group: u32 };", + "pub const Routed = struct { out: Ref, where: Ref, weights: Ref, ids: Ref, sum: Ref, topk: u32, per_group: u32 };\n/// ROUND-527: the kernel's `TfOPostArgs` record, field for field.\npub const PostArgs = extern struct { dim: u32, rows: u32, topk: u32, per_group: u32, groups: u32 };", 1), + ("e.setValue([5]u32{ dim, rows, r.topk, r.per_group, 8 }, 10);", + "e.setValue(PostArgs{ .dim = dim, .rows = rows, .topk = r.topk, .per_group = r.per_group, .groups = 8 }, 10);", 1), +]) + +# ---- the one metal message that names the Zig type the wire record lives in ------------------------------ +edit("../../../kernels/metal/deepseek_v41/fused.metal", [ + ('"TfFQuantArgs must mirror metal/glue.zig\'s Strides"', '"TfFQuantArgs must mirror metal/fused.zig\'s QuantArgs"', 1), +]) + +# ---- engram.zig: the 16-byte history record -------------------------------------------------------------- +edit("engram.zig", [ + ("pub const history_bytes = 16;", + """pub const history_bytes = 16; + +/// ROUND-527: engram_exl3.metal's `EngramHistory`, field for field: three token slots and the count. +pub const History = extern struct { tail: [3]i32, available: u32 }; +comptime { + if (@sizeOf(History) != history_bytes) @compileError("engram.History must stay 16 bytes"); +}""", 1), +]) + +# ---- the registry ---------------------------------------------------------------------------------------- +edit("mirror_checked.zig", [ + ('const attn = @import("metal/csa2_attn.zig");', + 'const attn = @import("metal/csa2_attn.zig");\nconst cand = @import("metal/cand.zig");\nconst compress = @import("metal/compress.zig");', 1), + (' mirror.check(fused.SwiArgs, sources.dsv41.fused, "TfFSwiArgs");', + ''' mirror.check(fused.SwiArgs, sources.dsv41.fused, "TfFSwiArgs"); + + // ROUND-527: the payloads that used to be positional literals -- one named extern struct a twin, so + // a reorder or a same-size retype on either side is a build error, not a silent argument shift. + mirror.check(ops.DenseArgs, sources.deepseek_v41_ops, "Dense"); + mirror.check(ops.ActivationArgs, sources.deepseek_v41_ops, "Activation"); + mirror.check(ops.CopyArgs, sources.deepseek_v41_ops, "Copy"); + mirror.check(ops.CombineArgs, sources.deepseek_v41_ops, "Combine"); + mirror.check(glue.GRopeArgs, sources.dsv41.glue_tmp, "TfGRopeArgs"); + mirror.check(glue.GCandArgs, sources.dsv41.glue_tmp, "TfGCandArgs"); + mirror.check(glue.GHcArgs2, sources.dsv41.glue_tmp, "TfGHcArgs2"); + mirror.check(glue.GScatterArgs, sources.dsv41.glue_tmp, "TfGScatterArgs"); + mirror.check(glue.GEmbedArgs, sources.dsv41.glue_tmp, "TfGEmbedArgs"); + mirror.check(glue.GMeanArgs, sources.dsv41.glue_tmp, "TfGMeanArgs"); + mirror.check(glue.TopkArgs, sources.dsv41.topk512, "TfTopk512Args"); + mirror.check(cand.Args, sources.dsv41.cand, "TfCandArgs"); + mirror.check(fused.PostArgs, sources.dsv41.fused, "TfFPostArgs"); + mirror.check(fused.QuantArgs, sources.dsv41.fused, "TfFQuantArgs"); + mirror.check(compress.PoolArgs, sources.dsv41.compress, "TfCPoolArgs"); + mirror.check(compress.RtArgs, sources.dsv41.compress, "TfCRtArgs"); + mirror.check(compress.PackArgs, sources.dsv41.compress, "TfCPackArgs"); + mirror.check(fold.PostArgs, sources.dsv41.fold, "TfOPostArgs"); + mirror.check(engram.History, sources.deepseek_v41_engram, "EngramHistory");''', 1), +]) +print("round 527 part 2 applied") diff --git a/bench/patch537-prefill-many.diff b/bench/patch537-prefill-many.diff new file mode 100644 index 00000000000..626e8b5f05a --- /dev/null +++ b/bench/patch537-prefill-many.diff @@ -0,0 +1,445 @@ +# ROUND-537 -- prefill_many on Metal: built and priced, NOT landed (default off; the served path falls back). +# +# What works: the admission burst window (TF_DSV41_BATCH_HOLD_MS) forms a 4-request batch; the lane core calls +# backend.prefill_many; the slots restore/reset; forwardSegs runs one forward over the concatenated suffixes and +# the row-wise layers (embedding, router, routed experts, shared expert, mHC) are shared. `Logits.segments` +# returns each segment's last row (one logits row a stream) and each stream's keep hook fires at its own end. +# +# What stops it: the attention cannot yet run a MANY-ROW segment. +# * encodeMulti is the decode rung (one-row segments, <= 8 rows) -> error.InvalidAttentionChunk +# * the shipped prompt rung per segment (attention.encode with a shifted .normalized/.branch view) +# -> error.MissingAttentionSelection, because the index selection is staged per (layer, position, rows) +# and a segment's CONSUMER layer reads whatever the LAST segment's SOURCE layer left in the one +# selection buffer. +# The next build is a per-segment selection (row-indexed picks + per-row positions), not a new kernel. +# +# Measured before the refusal: `many: batch 4 of 4 taken, 4 free lanes` on every turn's admission wave, then +# `4 prompts together: MissingAttentionSelection; each goes alone`. Fallback is exact (each stream alone; the +# 16-token shas reproduce the control), so the arm is safe but buys nothing until the selection is per segment. +# +# Apply with: git apply bench/patch537-prefill-many.diff +diff --git a/zig/src/core/lane_host.zig b/zig/src/core/lane_host.zig +index e242fb171..3725fa801 100644 +--- a/zig/src/core/lane_host.zig ++++ b/zig/src/core/lane_host.zig +@@ -310,6 +310,11 @@ pub const LaneHost = struct { + /// The next queued request into a free lane (or several, when the backend batches prompts); false when none can go. + pub fn admitOne(h: *LaneHost) bool { + if (admit.batches(h)) return admit.many(h); ++ // ROUND-537: a family that batches prompts gets a burst window, then re-checks (see admit.holdForBurst). ++ if (h.core.batchesPrompts()) { ++ admit.holdForBurst(h); ++ if (admit.batches(h)) return admit.many(h); ++ } + const job = switch (h.takeJob()) { + .none => return false, + .failed => return true, +diff --git a/zig/src/core/lane_host_admit.zig b/zig/src/core/lane_host_admit.zig +index e0de99e83..9aed78ef2 100644 +--- a/zig/src/core/lane_host_admit.zig ++++ b/zig/src/core/lane_host_admit.zig +@@ -1,4 +1,5 @@ + //! Which queued request a lane host admits next: the head, or one behind a head that waits for pool room. ++const std = @import("std"); + const LaneHost = @import("lane_host.zig").LaneHost; + const Job = LaneHost.Job; + const lanes = @import("lanes"); +@@ -50,6 +51,44 @@ fn choose(h: *LaneHost) ?usize { + return null; + } + ++/// ROUND-537: the burst window. A family that batches prompts needs two requests queued AND two lanes free, ++/// but the host admits each arrival into a free lane as it is read -- so the first is always gone before the ++/// second lands, and `batches()` can never fire on a real burst. When the window is non-zero, a free-lane ++/// admission waits up to that many milliseconds for a second request (a lane already decoding pauses at most ++/// that long, against the ~0.6 s a suffix pass costs). Default 0: the shipped path, unchanged. ++pub fn holdForBurst(h: *LaneHost) void { ++ const ms = holdMs(); ++ if (ms == 0) return; ++ const dbg = std.c.getenv("TF_DSV41_BATCH_DEBUG") != null; ++ var waited: u32 = 0; ++ var last: usize = 0; ++ while (waited < ms) { ++ h.lock(); ++ const queued = h.queued.items.len; ++ const free = @min(h.info_.lanes, h.memory_lanes orelse h.info_.lanes) -| h.admitted.items.len; ++ h.unlock(); ++ last = queued; ++ if (queued >= 2 or free < 2) break; ++ std.Io.sleep(h.io, .fromMilliseconds(1), .awake) catch { ++ if (dbg) std.log.info("hold: sleep failed after {d} ms, queued {d}", .{ waited, last }); ++ return; ++ }; ++ waited += 1; ++ } ++ if (dbg) std.log.info("hold: waited {d} of {d} ms, queued {d}", .{ waited, ms, last }); ++} ++ ++fn holdMs() u32 { ++ const S = struct { ++ var cached: i64 = -1; ++ }; ++ if (S.cached < 0) S.cached = if (std.c.getenv("TF_DSV41_BATCH_HOLD_MS")) |v| ++ (std.fmt.parseInt(u32, std.mem.span(v), 10) catch 0) ++ else ++ 0; ++ return @intCast(@min(S.cached, 500)); ++} ++ + /// Whether `job` fits now: the host's ledger when it has one, else the family's own pool. + fn fits(h: *const LaneHost, job: *const Job) bool { + if (h.kv != null) return ledger.fits(h, job); +@@ -73,6 +112,8 @@ pub fn many(h: *LaneHost) bool { + var began: [lanes.Engine.max_together]i96 = undefined; + var n: usize = 0; + var took = false; ++ var soloed: usize = 0; ++ const free_lanes = @min(h.info_.lanes, h.memory_lanes orelse h.info_.lanes) -| h.admitted.items.len; + while (n < jobs.len) { + const job = switch (h.takeJob()) { + .none => break, +@@ -84,14 +125,29 @@ pub fn many(h: *LaneHost) bool { + }; + took = true; + const at = h.setup(job) orelse continue; +- if (h.startsAlone(job) or (h.core.fills() and !h.core.batchable(&job.stream))) { // long, image, resumed: filled ++ // ROUND-537: a family that batches prompts without a chunked fill (`prefill_many` and no ++ // `prefill_step`) must still gate on `batchable`: it is what keeps an interior-mark or tail-snapshot ++ // stream out of the batch, where it would make the whole pass refuse. A chunked-fill family ++ // (GLM's CUDA path) keeps its own condition. ++ const alone = if (h.core.backend.vtable.prefill_many != null and !h.core.fills()) ++ !h.core.batchable(&job.stream) ++ else ++ (h.core.fills() and !h.core.batchable(&job.stream)); ++ // ROUND-537: a prompt that CAN batch waits for the batch rather than taking the lone driver. The lone ++ // driver is what made a turn-boundary burst four separate prompt passes: `many` sets every job up ++ // before launching any, so each one saw an idle host and `startsAlone` was true for all of them. ++ const can_batch = h.core.batchesPrompts() and job.request.max_tokens != 0 and h.core.batchable(&job.stream); ++ if (alone or (h.startsAlone(job) and !can_batch) or (can_batch and n >= free_lanes)) { // long, image, resumed: filled + _ = h.launch(job, at); ++ soloed += 1; + continue; + } + jobs[n] = job; + began[n] = at; + n += 1; + } ++ if (std.c.getenv("TF_DSV41_BATCH_DEBUG") != null) ++ std.log.info("many: batch {d} of {d} taken, {d} free lanes", .{ n, n + soloed, free_lanes }); + if (n == 1) return h.launch(jobs[0], began[0]); + var streams: [lanes.Engine.max_together]*lanes.Stream = undefined; + for (jobs[0..n], 0..) |job, i| streams[i] = &job.stream; +diff --git a/zig/src/core/lanes/open.zig b/zig/src/core/lanes/open.zig +index ab4df82fb..5e8d9d92b 100644 +--- a/zig/src/core/lanes/open.zig ++++ b/zig/src/core/lanes/open.zig +@@ -59,10 +59,24 @@ pub fn addStreams(e: *Engine, ss: []const *Stream, errs: []?anyerror, done: []bo + }; + } + +-/// Whether `s` may join a batched prompt pass beside chunked fills: short, text only, nothing kept to resume from. ++/// Whether `s` may join a batched prompt pass beside chunked fills: short, text only, and -- when the store ++/// keeps a state -- a pass the batch can capture whole. + pub fn batchable(e: *const Engine, s: *const Stream) bool { + const n = e.backend.vtable.many_rows; +- return n > 0 and s.prompt_len <= n and s.images.len == 0 and s.reuse.saved == null; ++ if (!(n > 0 and s.prompt_len <= n and s.images.len == 0)) return false; ++ // ROUND-537: a resumed suffix may join when its whole pass is ONE chunk and the store wants only the ++ // state at its end (every mark at `prompt_len`, no tail snapshot). An interior mark must be captured ++ // while the forward runs past it, which the batched pass does not do -- so such a stream is filled alone, ++ // where `prefill`'s own mark machinery handles it. A cold prompt follows the same rule. ++ var end_mark = s.reuse.hook == null; ++ for (s.reuse.marks) |m| { ++ // ROUND-537: the tail snapshot is an extra state the batched pass does not capture (the end state, ++ // which is what the next turn resumes from, is). Any other interior mark still sends the stream alone. ++ if (m != s.prompt_len and m != s.reuse.snap_at) return false; ++ if (m == s.prompt_len) end_mark = true; ++ } ++ if (!end_mark) return false; ++ return s.reuse.saved == null or s.reuse.at < s.prompt_len; + } + + fn addEach(e: *Engine, ss: []const *Stream, errs: []?anyerror, done: []bool) void { +diff --git a/zig/src/families/deepseek_v41/backend.zig b/zig/src/families/deepseek_v41/backend.zig +index 340e3a0a7..6e43bf181 100644 +--- a/zig/src/families/deepseek_v41/backend.zig ++++ b/zig/src/families/deepseek_v41/backend.zig +@@ -311,6 +311,9 @@ const MtpCache = struct { pending: u32, drafts: [4]u32, count: u32 = 3 }; + pub const Backend = struct { + gpa: std.mem.Allocator, + model: *ds.Model, ++ /// ROUND-537: the family vtable, stored (never a literal's address -- see `backend`). ++ vt: be.Backend.VTable = undefined, ++ vt_ready: bool = false, + by: std.AutoHashMapUnmanaged(*Stream, u32) = .empty, + /// Drawn tokens by handle: every read waits for its forward anyway (one sub-forward a window). + ring: [RING]u32 = undefined, +@@ -425,18 +428,29 @@ pub const Backend = struct { + if (b.pen_row.len > 0) b.gpa.free(b.pen_row); + } + ++ /// ROUND-537: THE VTABLE IS STORED IN THE BACKEND, not a literal taken by address. `&.{...}` was a static ++ /// temporary only while every field was comptime-known; a runtime `prefill_many` (the env-gated arm) made ++ /// the same expression a pointer to a stack temporary, and every call through it jumped into garbage. + pub fn backend(b: *Backend) be.Backend { +- return .{ .ptr = b, .penalties = true, .vtable = &.{ +- .prefill = prefill, +- .first = firstFn, +- .queue = queue, +- .read = read, +- .verify = verify, +- .keep = keep, +- .draft = draft, +- .tree = tree, +- .release = release, +- } }; ++ if (!b.vt_ready) { ++ const many = prefillManyOn(); ++ b.vt = .{ ++ .prefill = prefill, ++ .prefill_many = if (many) prefillMany else null, ++ .many_rows = if (many) b.model.workspace.plan.rows else 0, ++ .first = firstFn, ++ .queue = queue, ++ .read = read, ++ .verify = verify, ++ .keep = keep, ++ .draft = draft, ++ .tree = tree, ++ .release = release, ++ }; ++ b.vt_ready = true; ++ if (many) std.log.info("prefill many: armed, {d} rows a pass", .{b.model.workspace.plan.rows}); ++ } ++ return .{ .ptr = b, .penalties = true, .vtable = &b.vt }; + } + + /// A window of any width runs exactly as its slot's own forward; the lane core may bundle streams freely. +@@ -492,9 +506,10 @@ pub const Backend = struct { + /// to be the greedy argmax under any temperature, which is the one draw the owner's echo-prone long system + /// prompts could seed a degenerate turn with. The key is the drawn token's absolute position (drawFirst + /// passes prompt_len; queueNext passes the new cache length), the same key verify's rows use. +- fn draw(b: *Backend, slot: u32, s: *Stream, position: u64) !u32 { +- if (std.c.getenv("TF_DSV41_DRAFT_DEBUG") != null) std.log.info("draw: slot {d} pos {d}", .{ slot, b.model.caches[slot].position }); +- const row = b.model.workspace.logits(1); ++ /// ROUND-537: the draw over an explicit logits row, so a batched prompt pass can draw each segment's ++ /// first token from its own row of the same forward's `.segments` logits. ++ fn drawRow(b: *Backend, s: *Stream, row: []const f32, position: u64) !u32 { ++ _ = b; + if (s.sampling) |sp| if (sp.temperature > 0) { + const first = try sampleRow(row, sp, position); + if (std.c.getenv("TF_DSV41_PEN_DEBUG") != null) std.log.info("first draw: sampled {d} at {d}", .{ first, position }); +@@ -512,6 +527,106 @@ pub const Backend = struct { + return best; + } + ++ fn draw(b: *Backend, slot: u32, s: *Stream, position: u64) !u32 { ++ if (std.c.getenv("TF_DSV41_DRAFT_DEBUG") != null) std.log.info("draw: slot {d} pos {d}", .{ slot, b.model.caches[slot].position }); ++ return drawRow(b, s, b.model.workspace.logits(1), position); ++ } ++ ++ var prefill_many_on: ?bool = null; ++ /// ROUND-537: the batched prompt pass. Default OFF until the A/B receipt lands (ROUND-536 priced the ++ /// merge at -3,806 ms of GPU for eight 284-row suffixes); `TF_DSV41_PREFILL_MANY=1` arms it, `=0` is the ++ /// same-binary control. ++ fn prefillManyOn() bool { ++ if (prefill_many_on) |v| return v; ++ const v = std.c.getenv("TF_DSV41_PREFILL_MANY"); ++ prefill_many_on = if (v) |e| !std.mem.eql(u8, std.mem.span(e), "0") else false; ++ return prefill_many_on.?; ++ } ++ ++ /// ROUND-537: several prompts in one forward. Each stream's suffix is one segment: the row-wise layers ++ /// run once over every segment's rows, the attention core once a segment against that slot's own state ++ /// (R-531's `forwardSegs`), and each stream's first token is drawn from its own segment's last row. ++ /// Admitted only when every stream's whole pass is ONE chunk and the store wants only its end state: ++ /// an interior mark would have to be captured inside the chunk, which this pass cannot do, so such a ++ /// stream is marked not-batchable on the lane side and filled alone. Any error leaves none prefilled ++ /// (`addStreams` falls back to one-by-one). ++ fn prefillMany(ptr: *anyopaque, ss: []const *Stream) anyerror!bool { ++ const b = self(ptr); ++ const dbg = std.c.getenv("TF_DSV41_BATCH_DEBUG") != null; ++ if (ss.len < 2 or ss.len > 8) { ++ if (dbg) std.log.info("prefill many: refused, {d} streams", .{ss.len}); ++ return false; ++ } ++ if (!prefillManyOn() or !batchOn() or !noBatchInstrument()) { ++ if (dbg) std.log.info("prefill many: refused, arm {} batch {} instrument {}", .{ prefillManyOn(), batchOn(), !noBatchInstrument() }); ++ return false; ++ } ++ const rows_cap: u32 = b.model.workspace.plan.rows; ++ var from: [8]u32 = undefined; ++ var total: u32 = 0; ++ for (ss, 0..) |s, k| { ++ const prompt = s.prompt(); ++ if (prompt.len == 0 or s.isCancelled()) return false; ++ if (s.images.len != 0 or s.embedding != null) return false; ++ const f: u32 = if (s.reuse.saved != null) s.reuse.at else 0; ++ if (f >= prompt.len) return false; ++ const n: u32 = @intCast(prompt.len - f); ++ if (n > rows_cap) return false; ++ var end_mark = s.reuse.hook == null; ++ for (s.reuse.marks) |mk| { ++ if (mk != prompt.len and mk != s.reuse.snap_at) { ++ if (dbg) std.log.info("prefill many: refused, stream {d} mark {d} of {d}", .{ k, mk, prompt.len }); ++ return false; ++ } ++ if (mk == prompt.len) end_mark = true; ++ } ++ if (!end_mark) { ++ if (dbg) std.log.info("prefill many: refused, stream {d} no end mark", .{k}); ++ return false; ++ } ++ from[k] = f; ++ total += n; ++ } ++ if (total > rows_cap) return false; ++ var segs_buf: [8]ds.Seg = undefined; ++ var slots: [8]u32 = undefined; ++ var made: usize = 0; ++ errdefer { ++ for (ss[0..made]) |s| _ = b.by.remove(s); ++ for (slots[0..made]) |sl| b.model.resetSlot(sl) catch {}; ++ } ++ for (ss, 0..) |s, k| { ++ const prompt = s.prompt(); ++ const i = b.free() orelse return error.NoFreeSlot; ++ const state = &b.model.caches[i]; ++ if (prompt.len + s.max_new + 1 > state.plan.capacity) return error.ContextFull; ++ try b.by.put(b.gpa, s, i); ++ slots[k] = i; ++ made += 1; ++ if (s.reuse.saved) |saved| { ++ const snap: *ds.Model.Snapshot = @ptrCast(@alignCast(saved)); ++ try b.model.snapshotRestore(i, snap); ++ s.cached = from[k]; ++ b.history[i].clearRetainingCapacity(); ++ b.history[i].appendSlice(b.gpa, prompt[0..from[k]]) catch {}; ++ } else { ++ try b.model.resetSlot(i); ++ b.history[i].clearRetainingCapacity(); ++ s.cached = 0; ++ } ++ segs_buf[k] = .{ .slot = i, .ids = prompt[from[k]..], .p0 = from[k] }; ++ } ++ const lg = try b.model.forwardSegs(segs_buf[0..ss.len], .segments); ++ if (std.c.getenv("TF_DSV41_BATCH_DEBUG") != null) std.log.info("prefill many: streams={d} rows={d} gpu={d:.3} ms", .{ ss.len, total, b.model.last_gpu_seconds * 1e3 }); ++ for (ss, 0..) |s, k| { ++ const prompt = s.prompt(); ++ const row = lg[@as(usize, k) * 129280 ..][0..129280]; ++ b.first[slots[k]] = try drawRow(b, s, row, @intCast(prompt.len)); ++ if (s.reuse.hook) |hook| hook.at(hook.ptr, s, @intCast(prompt.len)); ++ } ++ return true; ++ } ++ + fn prefill(ptr: *anyopaque, s: *Stream) anyerror!void { + const b = self(ptr); + const prompt = s.prompt(); +diff --git a/zig/src/families/deepseek_v41/model.zig b/zig/src/families/deepseek_v41/model.zig +index c7cbb5011..949f3e99b 100644 +--- a/zig/src/families/deepseek_v41/model.zig ++++ b/zig/src/families/deepseek_v41/model.zig +@@ -36,7 +36,7 @@ fn nowNs() u64 { + } + + pub const prefill_step = 15872; +-pub const Logits = enum { none, last, all }; ++pub const Logits = enum { none, last, all, segments }; + + /// ROUND-531: one slot's rows of a batched forward: the slot's window, its ids, and the position its + /// first row lands at. The batch rung is one-row segments (the shared round's lanes). +@@ -1264,7 +1264,7 @@ pub const Model = struct { + /// attention weights, not to batch prefill or to run a profiler. + pub fn forwardSegs(m: *Model, segs: []const Seg, logits: Logits) ![]const f32 { + if (!m.valid) return error.InvalidModelState; +- if (segs.len == 0 or segs.len > 4) return error.InvalidLaneSlot; ++ if (segs.len == 0 or segs.len > 8) return error.InvalidLaneSlot; + const first_seg = segs[0]; + const slot = first_seg.slot; + if (slot >= m.lanes) return error.InvalidLaneSlot; +@@ -1400,10 +1400,12 @@ pub const Model = struct { + enc.barrier(); + hid.record(enc, &p.ops, m.streamView(), rows, .embed, 0); + var asegs: [8]attention.Seg = undefined; ++ var seg_row0: [8]u32 = @splat(0); + { + var at: u32 = 0; + for (segs, 0..) |sg, si| { + asegs[si] = .{ .state = &m.caches[sg.slot], .p0 = sg.p0, .r0 = at, .n = @intCast(sg.ids.len) }; ++ seg_row0[si] = at; + at += @intCast(sg.ids.len); + } + } +@@ -1547,8 +1549,25 @@ pub const Model = struct { + e = aprof.cb; + } else if (m.attention_observer) |attention_observer| + try attention.encodeDiagnostic(&p.attention, enc, &layer.attn, state, &m.attention_workspace, ws.view(.normalized), ws.view(.branch), &p.projection, ws.projection(), @intCast(index), rows, m.cfg, true, attention_observer, null, &.{}) +- else if (segs.len > 1) +- try attention.encodeDiagnostic(&p.attention, enc, &layer.attn, state, &m.attention_workspace, ws.view(.normalized), ws.view(.branch), &p.projection, ws.projection(), @intCast(index), rows, m.cfg, false, null, null, asegs[0..segs.len]) ++ else if (segs.len > 1) multi: { ++ // ROUND-537: a prompt batch's segments are many rows each, which the decode rung refuses. ++ // Each segment's attention runs on the SHIPPED prompt path over its own row range and its ++ // own state, so the arithmetic is the chunk that stream would have run alone; the row-wise ++ // layers around it stay shared over every segment's rows. ++ var multi_rows = false; ++ for (segs) |sg| if (sg.ids.len != 1) { ++ multi_rows = true; ++ break; ++ }; ++ if (!multi_rows) { ++ try attention.encodeDiagnostic(&p.attention, enc, &layer.attn, state, &m.attention_workspace, ws.view(.normalized), ws.view(.branch), &p.projection, ws.projection(), @intCast(index), rows, m.cfg, false, null, null, asegs[0..segs.len]); ++ break :multi; ++ } ++ for (segs, 0..) |sg, si| { ++ const r0 = seg_row0[si]; ++ try attention.encode(&p.attention, enc, &layer.attn, &m.caches[sg.slot], &m.attention_workspace, ws.view(.normalized).shifted(@as(usize, r0) * 5120 * 2), ws.view(.branch).shifted(@as(usize, r0) * 5120 * 2), &p.projection, ws.projection(), @intCast(index), @intCast(sg.ids.len), m.cfg); ++ } ++ } + else + try attention.encode(&p.attention, enc, &layer.attn, state, &m.attention_workspace, ws.view(.normalized), ws.view(.branch), &p.projection, ws.projection(), @intCast(index), rows, m.cfg); + } +@@ -1650,7 +1669,12 @@ pub const Model = struct { + } + if (logits != .none) { + try m.profileSpan(&enc, .head); +- const output_rows: u32 = if (logits == .all) rows else 1; ++ // ROUND-537: `.segments` writes one logits row a segment (its own last row), so a batched ++ // prompt pass draws each stream's first token from the same forward. The collapse runs once a ++ // segment into `.collapsed` row k; the norm and the head then run over N rows exactly as they ++ // run over one. Nothing else about the head moves. ++ const seg_mode = logits == .segments; ++ const output_rows: u32 = if (seg_mode) @intCast(segs.len) else if (logits == .all) rows else 1; + const first: usize = if (logits == .all) 0 else rows - 1; + if (p.hc_boundary) |*bp| { + if (m.pending_expand) { +@@ -1660,13 +1684,18 @@ pub const Model = struct { + const next = if (m.stream_alt) wsx.view(.stream) else wsx.view(.stream_next); + enc.setPipeline(bp.expand_mix); + inline for (.{ cur, wsx.view(.branch), wsx.view(.post), wsx.view(.comb), tensor(last.projection), wsx.view(.hc_part), next }, 0..) |r, i| enc.setBuffer(r.buffer, r.offset, i); +- enc.dispatchGroups(.{ .width = 20, .height = if (logits == .all) rows else 1 }, .{ .width = 256 }); ++ enc.dispatchGroups(.{ .width = 20, .height = if (logits == .all or seg_mode) rows else 1 }, .{ .width = 256 }); + enc.barrier(); + m.stream_alt = !m.stream_alt; + m.pending_expand = false; + } + } +- mhc.encodeCollapse(enc, &p.mhc, m.streamView().shifted(first * 20480 * 2), ws.view(.previous_pre).shifted(first * 4 * 4), ws.view(.collapsed), .{ .rows = output_rows, .width = 5120, .stream_stride = 20480, .y_stride = 5120 }); ++ if (seg_mode) { ++ for (segs, 0..) |sg, k| { ++ const row = seg_row0[k] + @as(u32, @intCast(sg.ids.len)) - 1; ++ mhc.encodeCollapse(enc, &p.mhc, m.streamView().shifted(@as(usize, row) * 20480 * 2), ws.view(.previous_pre).shifted(@as(usize, row) * 4 * 4), ws.view(.collapsed).shifted(@as(usize, k) * 5120 * 2), .{ .rows = 1, .width = 5120, .stream_stride = 20480, .y_stride = 5120 }); ++ } ++ } else mhc.encodeCollapse(enc, &p.mhc, m.streamView().shifted(first * 20480 * 2), ws.view(.previous_pre).shifted(first * 4 * 4), ws.view(.collapsed), .{ .rows = output_rows, .width = 5120, .stream_stride = 20480, .y_stride = 5120 }); + enc.barrier(); + m.normalize(enc, ws.view(.collapsed), m.weights.norm, ws.view(.normalized), output_rows); + // ROUND-375: the trunk's own head input (the row 0 of the window), so the drafter's head input +@@ -1830,7 +1859,7 @@ pub const Model = struct { + for (segs) |sg| try m.caches[sg.slot].append(@intCast(sg.ids.len)); + m.last_gpu_seconds = e.gpuSeconds() + pipe_gpu_extra / 1e3; + m.valid = true; +- m.logits_rows = if (logits == .all) rows else if (logits == .last) 1 else 0; ++ m.logits_rows = if (logits == .all) rows else if (logits == .last) 1 else if (logits == .segments) segs.len else 0; + return ws.logits(m.logits_rows); + } + diff --git a/bench/patch538-prompt-merge.diff b/bench/patch538-prompt-merge.diff new file mode 100644 index 00000000000..3aa802e8648 --- /dev/null +++ b/bench/patch538-prompt-merge.diff @@ -0,0 +1,830 @@ +diff --git a/zig/src/core/lane_host.zig b/zig/src/core/lane_host.zig +index e242fb171..3725fa801 100644 +--- a/zig/src/core/lane_host.zig ++++ b/zig/src/core/lane_host.zig +@@ -310,6 +310,11 @@ pub const LaneHost = struct { + /// The next queued request into a free lane (or several, when the backend batches prompts); false when none can go. + pub fn admitOne(h: *LaneHost) bool { + if (admit.batches(h)) return admit.many(h); ++ // ROUND-537: a family that batches prompts gets a burst window, then re-checks (see admit.holdForBurst). ++ if (h.core.batchesPrompts()) { ++ admit.holdForBurst(h); ++ if (admit.batches(h)) return admit.many(h); ++ } + const job = switch (h.takeJob()) { + .none => return false, + .failed => return true, +diff --git a/zig/src/core/lane_host_admit.zig b/zig/src/core/lane_host_admit.zig +index e0de99e83..866a6a7dd 100644 +--- a/zig/src/core/lane_host_admit.zig ++++ b/zig/src/core/lane_host_admit.zig +@@ -1,4 +1,5 @@ + //! Which queued request a lane host admits next: the head, or one behind a head that waits for pool room. ++const std = @import("std"); + const LaneHost = @import("lane_host.zig").LaneHost; + const Job = LaneHost.Job; + const lanes = @import("lanes"); +@@ -50,6 +51,44 @@ fn choose(h: *LaneHost) ?usize { + return null; + } + ++/// ROUND-537: the burst window. A family that batches prompts needs two requests queued AND two lanes free, ++/// but the host admits each arrival into a free lane as it is read -- so the first is always gone before the ++/// second lands, and `batches()` can never fire on a real burst. When the window is non-zero, a free-lane ++/// admission waits up to that many milliseconds for a second request (a lane already decoding pauses at most ++/// that long, against the ~0.6 s a suffix pass costs). Default 0: the shipped path, unchanged. ++pub fn holdForBurst(h: *LaneHost) void { ++ const ms = holdMs(); ++ if (ms == 0) return; ++ const dbg = std.c.getenv("TF_DSV41_BATCH_DEBUG") != null; ++ var waited: u32 = 0; ++ var last: usize = 0; ++ while (waited < ms) { ++ h.lock(); ++ const queued = h.queued.items.len; ++ const free = @min(h.info_.lanes, h.memory_lanes orelse h.info_.lanes) -| h.admitted.items.len; ++ h.unlock(); ++ last = queued; ++ if (queued >= 2 or free < 2) break; ++ std.Io.sleep(h.io, .fromMilliseconds(1), .awake) catch { ++ if (dbg) std.log.info("hold: sleep failed after {d} ms, queued {d}", .{ waited, last }); ++ return; ++ }; ++ waited += 1; ++ } ++ if (dbg) std.log.info("hold: waited {d} of {d} ms, queued {d}", .{ waited, ms, last }); ++} ++ ++fn holdMs() u32 { ++ const S = struct { ++ var cached: i64 = -1; ++ }; ++ if (S.cached < 0) S.cached = if (std.c.getenv("TF_DSV41_BATCH_HOLD_MS")) |v| ++ (std.fmt.parseInt(u32, std.mem.span(v), 10) catch 0) ++ else ++ 0; ++ return @intCast(@min(S.cached, 500)); ++} ++ + /// Whether `job` fits now: the host's ledger when it has one, else the family's own pool. + fn fits(h: *const LaneHost, job: *const Job) bool { + if (h.kv != null) return ledger.fits(h, job); +@@ -73,6 +112,14 @@ pub fn many(h: *LaneHost) bool { + var began: [lanes.Engine.max_together]i96 = undefined; + var n: usize = 0; + var took = false; ++ var soloed: usize = 0; ++ const free_lanes = @min(h.info_.lanes, h.memory_lanes orelse h.info_.lanes) -| h.admitted.items.len; ++ // ROUND-538: the batch is also bounded by ROWS, not just lanes. `many_rows` is the family's one-pass row ++ // budget (DSV41's workspace), and `prefillMany` refuses the whole set when the rows do not fit -- so a ++ // turn-boundary burst of eight short prompts was one refused batch and eight solo passes. Take the ++ // prefix that fits and launch the rest alone; the merge then applies to as many lanes as the pass holds. ++ const row_cap: u32 = h.core.backend.vtable.many_rows; ++ var batch_rows: u32 = 0; + while (n < jobs.len) { + const job = switch (h.takeJob()) { + .none => break, +@@ -84,14 +131,37 @@ pub fn many(h: *LaneHost) bool { + }; + took = true; + const at = h.setup(job) orelse continue; +- if (h.startsAlone(job) or (h.core.fills() and !h.core.batchable(&job.stream))) { // long, image, resumed: filled ++ // ROUND-537: a family that batches prompts without a chunked fill (`prefill_many` and no ++ // `prefill_step`) must still gate on `batchable`: it is what keeps an interior-mark or tail-snapshot ++ // stream out of the batch, where it would make the whole pass refuse. A chunked-fill family ++ // (GLM's CUDA path) keeps its own condition. ++ const alone = if (h.core.backend.vtable.prefill_many != null and !h.core.fills()) ++ !h.core.batchable(&job.stream) ++ else ++ (h.core.fills() and !h.core.batchable(&job.stream)); ++ // ROUND-537: a prompt that CAN batch waits for the batch rather than taking the lone driver. The lone ++ // driver is what made a turn-boundary burst four separate prompt passes: `many` sets every job up ++ // before launching any, so each one saw an idle host and `startsAlone` was true for all of them. ++ const can_batch = h.core.batchesPrompts() and job.request.max_tokens != 0 and h.core.batchable(&job.stream); ++ const need: u32 = blk: { ++ if (h.core.backend.vtable.prefill_many == null) break :blk 0; ++ const p: u32 = @intCast(job.stream.prompt_len); ++ const from: u32 = if (job.stream.reuse.saved != null) job.stream.reuse.at else 0; ++ break :blk p -| from; ++ }; ++ const over_rows = h.core.backend.vtable.prefill_many != null and n != 0 and batch_rows + need > row_cap; ++ if (alone or (h.startsAlone(job) and !can_batch) or (can_batch and (n >= free_lanes or over_rows))) { // long, image, resumed: filled + _ = h.launch(job, at); ++ soloed += 1; + continue; + } + jobs[n] = job; + began[n] = at; + n += 1; ++ batch_rows += need; + } ++ if (std.c.getenv("TF_DSV41_BATCH_DEBUG") != null) ++ std.log.info("many: batch {d} of {d} taken, {d} free lanes", .{ n, n + soloed, free_lanes }); + if (n == 1) return h.launch(jobs[0], began[0]); + var streams: [lanes.Engine.max_together]*lanes.Stream = undefined; + for (jobs[0..n], 0..) |job, i| streams[i] = &job.stream; +diff --git a/zig/src/core/lanes/open.zig b/zig/src/core/lanes/open.zig +index ab4df82fb..6d248aef3 100644 +--- a/zig/src/core/lanes/open.zig ++++ b/zig/src/core/lanes/open.zig +@@ -59,10 +59,29 @@ pub fn addStreams(e: *Engine, ss: []const *Stream, errs: []?anyerror, done: []bo + }; + } + +-/// Whether `s` may join a batched prompt pass beside chunked fills: short, text only, nothing kept to resume from. ++/// Whether `s` may join a batched prompt pass beside chunked fills: short, text only, and -- when the store ++/// keeps a state -- a pass the batch can capture whole. + pub fn batchable(e: *const Engine, s: *const Stream) bool { + const n = e.backend.vtable.many_rows; +- return n > 0 and s.prompt_len <= n and s.images.len == 0 and s.reuse.saved == null; ++ if (!(n > 0 and s.prompt_len <= n and s.images.len == 0)) return false; ++ // ROUND-538: no planned state, nothing to capture: the store keeps nothing for this pass (a prompt below ++ // its keep threshold, or none wanted), so a batched pass and a solo one are equally complete. ROUND-537's ++ // rule assumed every pass has an end mark; for a short prompt the marks list is empty and the batch would ++ // have been refused for a state that does not exist. ++ if (s.reuse.marks.len == 0) return true; ++ // ROUND-537: a resumed suffix may join when its whole pass is ONE chunk and the store wants only the ++ // state at its end (every mark at `prompt_len`, no tail snapshot). An interior mark must be captured ++ // while the forward runs past it, which the batched pass does not do -- so such a stream is filled alone, ++ // where `prefill`'s own mark machinery handles it. A cold prompt follows the same rule. ++ var end_mark = s.reuse.hook == null; ++ for (s.reuse.marks) |m| { ++ // ROUND-537: the tail snapshot is an extra state the batched pass does not capture (the end state, ++ // which is what the next turn resumes from, is). Any other interior mark still sends the stream alone. ++ if (m != s.prompt_len and m != s.reuse.snap_at) return false; ++ if (m == s.prompt_len) end_mark = true; ++ } ++ if (!end_mark) return false; ++ return s.reuse.saved == null or s.reuse.at < s.prompt_len; + } + + fn addEach(e: *Engine, ss: []const *Stream, errs: []?anyerror, done: []bool) void { +diff --git a/zig/src/families/deepseek_v41/attention.zig b/zig/src/families/deepseek_v41/attention.zig +index 0d6d35ffc..5ac53345a 100644 +--- a/zig/src/families/deepseek_v41/attention.zig ++++ b/zig/src/families/deepseek_v41/attention.zig +@@ -170,8 +170,10 @@ pub const Workspace = struct { + candidate_rows: u32 = 0, + /// ROUND-504: a merged tail chunk's PREFIX (its rows before the tail mark) is published into this stash ring + /// as well as the whole chunk into the live one, so the state at the mark can be copied from it. +- publish_limit: u32 = 0, +- publish_stash: ?View = null, ++ /// ROUND-538: ONE PER SEGMENT -- a batched prompt pass can carry up to four tail marks (one a stream), each ++ /// with its own mark offset and its own slot's stash ring. Segment 0 is the solo path's. ++ pub_limit: [4]u32 = .{ 0, 0, 0, 0 }, ++ pub_stash: [4]?View = .{ null, null, null, null }, + + /// The selection scratch of batch segment `s`; the one-stream path is segment 0. + pub fn selectionFor(w: *Workspace, s: usize) *index.Scratch { +@@ -386,12 +388,23 @@ fn splitScan() u32 { + } + + pub fn encode(p: *const Pipelines, e: mtl.ComputeEncoder, w: *const weights.Attention, state: *State, work: *Workspace, x: View, y: View, ep: *const exl3.Pipelines, scratch: exl3.View, layer: u32, rows: u32, c: config.Config) !void { +- return encodeDiagnostic(p, e, w, state, work, x, y, ep, scratch, layer, rows, c, false, null, null, &.{}); ++ return encodeSeg(p, e, w, state, work, x, y, ep, scratch, layer, rows, c, 0); ++} ++ ++/// ROUND-538: the prompt path for ONE segment of a batched prompt pass. The arithmetic is `encode`'s; the ++/// only change is that this call's index selection lives in the segment's own scratch (R-531's `selectionFor`) ++/// and its cache key is the segment's own `(layer, position, rows)`. The picks buffer is row-indexed and every ++/// segment has its own rows and its own state, so a consumer layer must read the picks its own source layer ++/// wrote -- with one scratch (and one tuple) a batched pass let the last segment's source layer overwrite it ++/// for all the others (ROUND-537's `MissingAttentionSelection`). Segment 0 is the shipped `work.selection`, so ++/// the one-stream path is byte for byte the same call. ++pub fn encodeSeg(p: *const Pipelines, e: mtl.ComputeEncoder, w: *const weights.Attention, state: *State, work: *Workspace, x: View, y: View, ep: *const exl3.Pipelines, scratch: exl3.View, layer: u32, rows: u32, c: config.Config, seg: usize) !void { ++ return encodeDiagnostic(p, e, w, state, work, x, y, ep, scratch, layer, rows, c, false, null, null, &.{}, seg); + } + + /// ROUND-427: the same encode with the per-block GPU split armed (TF_DSV41_ATTN_PROF). + pub fn encodeProfiled(p: *const Pipelines, e: mtl.ComputeEncoder, w: *const weights.Attention, state: *State, work: *Workspace, x: View, y: View, ep: *const exl3.Pipelines, scratch: exl3.View, layer: u32, rows: u32, c: config.Config, prof: *Prof) !void { +- return encodeDiagnostic(p, e, w, state, work, x, y, ep, scratch, layer, rows, c, false, null, prof, &.{}); ++ return encodeDiagnostic(p, e, w, state, work, x, y, ep, scratch, layer, rows, c, false, null, prof, &.{}, 0); + } + + /// Same encoder and arithmetic as encode, with optional copies at operator boundaries. +@@ -589,13 +602,15 @@ fn encodeMulti(p: *const Pipelines, e_in: mtl.ComputeEncoder, w: *const weights. + try projection(ep, e, .{ .trellis = w.wo_b }, grouped, y, scratch, rows, group_output, c.hidden, .bf16); + } + +-pub fn encodeDiagnostic(p: *const Pipelines, e_in: mtl.ComputeEncoder, w: *const weights.Attention, state: *State, work: *Workspace, x: View, y: View, ep: *const exl3.Pipelines, scratch: exl3.View, layer: u32, rows: u32, c: config.Config, comptime diagnostic: bool, observer: ?DiagnosticObserver, prof: ?*Prof, segs: []const Seg) !void { ++pub fn encodeDiagnostic(p: *const Pipelines, e_in: mtl.ComputeEncoder, w: *const weights.Attention, state: *State, work: *Workspace, x: View, y: View, ep: *const exl3.Pipelines, scratch: exl3.View, layer: u32, rows: u32, c: config.Config, comptime diagnostic: bool, observer: ?DiagnosticObserver, prof: ?*Prof, segs: []const Seg, seg: usize) !void { + if (segs.len > 1) return encodeMulti(p, e_in, w, work, x, y, ep, scratch, layer, c, segs); + var e = e_in; + if (layer >= 40 or rows == 0 or rows > work.max_rows or + state.position > state.plan.capacity or rows > state.plan.capacity - state.position) + return error.InvalidAttentionChunk; + attnBegin(layer); ++ // ROUND-538: the segment's own selection scratch. Segment 0 is `work.selection` (the shipped call). ++ const selw = work.selectionFor(seg); + // Start the first block from a fresh buffer so the "pre" window is not charged to `qkv`. + if (prof) |pf| pf.split("pre", layer, &e); + const position = state.position; +@@ -606,7 +621,7 @@ pub fn encodeDiagnostic(p: *const Pipelines, e_in: mtl.ComputeEncoder, w: *const + const q = work.view(.query); + var raw = work.view(.raw_kv); + const ring = try state.ring(layer); +- const chunk = work.selection.windowChunk(); ++ const chunk = selw.windowChunk(); + e.barrier(); + const dense_passes: u32 = if (std.c.getenv("TF_DSV41_DOUBLE_ATTN_DENSE") != null) 2 else 1; + const dup_view: View = .{ .buffer = work.dup, .offset = 0 }; +@@ -809,7 +824,7 @@ pub fn encodeDiagnostic(p: *const Pipelines, e_in: mtl.ComputeEncoder, w: *const + attnMark(layer, "iq_proj", prof, &e); + try rotate(p, e, iq, rows, c.index_heads, c.index_dim, position, ratio, 1, false, c); + attnMark(layer, "iq_rope", prof, &e); +- try p.cache.encodePack(e, iq, work.selection.queryPacked(), .{ .rows = rows * c.index_heads, .width = c.index_dim, .stride = c.index_dim, .packed_stride = kv.cache.index_stride, .block = 32, .kind = .index_fp4, .inplace = 1 }); ++ try p.cache.encodePack(e, iq, selw.queryPacked(), .{ .rows = rows * c.index_heads, .width = c.index_dim, .stride = c.index_dim, .packed_stride = kv.cache.index_stride, .block = 32, .kind = .index_fp4, .inplace = 1 }); + attnMark(layer, "iq_pack", prof, &e); + const iq_w_args: ops.Dense = .{ .rows = rows, .k = c.hidden, .n = c.index_heads, .x_stride = c.hidden, .w_stride = c.hidden, .y_stride = c.index_heads, .w_dtype = switch (selector.weights_proj.dtype) { + .bf16 => .bf16, +@@ -887,29 +902,29 @@ pub fn encodeDiagnostic(p: *const Pipelines, e_in: mtl.ComputeEncoder, w: *const + }; + const sel: index.Params = .{ .rows = rows, .q_stride = iq_width, .weight_stride = c.index_heads, .position = position, .ratio = ratio, .keys = compressed_rows, .make_candidates = @intFromBool(make_candidates), .use_candidates = @intFromBool(use_candidates), .layer = layer, .skip_mask = skip_mask }; + if (std.c.getenv("TF_DSV41_SKIP_INDEX") == null) { +- if (few_keys) p.select.encodeIdentity(e, work.selection, sel) else for (0..passes) |_| try p.select.encode(e, iq, iw, source.index, work.selection, sel); ++ if (few_keys) p.select.encodeIdentity(e, selw.*, sel) else for (0..passes) |_| try p.select.encode(e, iq, iw, source.index, selw.*, sel); + } + // ROUND-525: the same selection a second time, on unchanged inputs -- the arm that says whether the + // kernel is deterministic at all. Measurement only; the second picks are the ones the scan reads. + if (std.c.getenv("TF_DSV41_SELECT_TWICE") != null and scan_probe.active(layer) and !few_keys) { + e.barrier(); +- scan_probe.record(e, &p.plain, work.selection.positions(), rows, 512 * 4 / 2, .pos, layer); +- scan_probe.record(e, &p.plain, work.selection.positions().shifted(@as(usize, rows - 1) * 512 * 4), 1, 512 * 4 / 2, .posl1, layer); +- scan_probe.recordStrided(e, &p.plain, work.selection.scores(), rows, 8192, 8192, .scof1, layer); ++ scan_probe.record(e, &p.plain, selw.positions(), rows, 512 * 4 / 2, .pos, layer); ++ scan_probe.record(e, &p.plain, selw.positions().shifted(@as(usize, rows - 1) * 512 * 4), 1, 512 * 4 / 2, .posl1, layer); ++ scan_probe.recordStrided(e, &p.plain, selw.scores(), rows, 8192, 8192, .scof1, layer); + if (ratio != 0 and rows > 1) { + var sk1: u32 = 0; + while (sk1 < 4 and sk1 < rows) : (sk1 += 1) { + const r1 = rows - 1 - @as(u32, @intCast((@as(usize, rows - 1) * sk1) / 3)); + const vis1: u32 = @intCast((position + r1 + 1) / ratio); +- if (vis1 != 0) scan_probe.recordStrided(e, &p.plain, work.selection.scores().shifted(@as(usize, r1) * 4096 * 4), 1, 4096, vis1 * 2, .sco1, 400000 + r1); ++ if (vis1 != 0) scan_probe.recordStrided(e, &p.plain, selw.scores().shifted(@as(usize, r1) * 4096 * 4), 1, 4096, vis1 * 2, .sco1, 400000 + r1); + } + } + e.barrier(); +- try p.select.encode(e, iq, iw, source.index, work.selection, sel); ++ try p.select.encode(e, iq, iw, source.index, selw.*, sel); + e.barrier(); +- scan_probe.record(e, &p.plain, work.selection.positions(), rows, 512 * 4 / 2, .pos2, layer); +- scan_probe.record(e, &p.plain, work.selection.positions().shifted(@as(usize, rows - 1) * 512 * 4), 1, 512 * 4 / 2, .posl2, layer); +- scan_probe.recordStrided(e, &p.plain, work.selection.scores(), rows, 8192, 8192, .scof2, layer); ++ scan_probe.record(e, &p.plain, selw.positions(), rows, 512 * 4 / 2, .pos2, layer); ++ scan_probe.record(e, &p.plain, selw.positions().shifted(@as(usize, rows - 1) * 512 * 4), 1, 512 * 4 / 2, .posl2, layer); ++ scan_probe.recordStrided(e, &p.plain, selw.scores(), rows, 8192, 8192, .scof2, layer); + e.barrier(); + } + attnMark(layer, "select", prof, &e); +@@ -918,7 +933,7 @@ pub fn encodeDiagnostic(p: *const Pipelines, e_in: mtl.ComputeEncoder, w: *const + // The receipt of this round's bug lives here: every score was 0.0, so the heap tied at 0 and + // kept positions 0..511; a healthy selection spreads over the whole visible range. + if (std.c.getenv("TF_DSV41_DUMP_SELECT") != null and prof != null) { +- const v = work.selection.positions(); ++ const v = selw.positions(); + const base: [*]const u8 = @ptrCast(v.buffer.contents()); + const pos: [*]const i32 = @ptrCast(@alignCast(base + v.offset)); + var lo: i32 = std.math.maxInt(i32); +@@ -940,10 +955,10 @@ pub fn encodeDiagnostic(p: *const Pipelines, e_in: mtl.ComputeEncoder, w: *const + sum +%= @as(u32, @bitCast(key)); + xr ^= @as(u32, @bitCast(key)) *% 2654435761; + } +- const hv = work.selection.heap(); ++ const hv = selw.heap(); + const hb: [*]const u8 = @ptrCast(hv.buffer.contents()); + const hf: [*]const f32 = @ptrCast(@alignCast(hb + hv.offset)); +- const sv = work.selection.scores(); ++ const sv = selw.scores(); + const sb: [*]const u8 = @ptrCast(sv.buffer.contents()); + const sf: [*]const f32 = @ptrCast(@alignCast(sb + sv.offset)); + if (std.c.getenv("TF_DSV41_DUMP_SELECT_REF") != null) { +@@ -1025,15 +1040,15 @@ pub fn encodeDiagnostic(p: *const Pipelines, e_in: mtl.ComputeEncoder, w: *const + } + std.log.info("select dump l{d}: cr={d} topk={d} pos={d} rows={d} few={} | live={d} lo={d} hi={d} over={d} | heap0_score={d} sum={d} xr={d} first4={d},{d},{d},{d} scores0to3={d},{d},{d},{d} shash={x} allhash={x} nan={d}", .{ layer, compressed_rows, c.index_topk, position, rows, compressed_rows <= c.index_topk, live, lo, hi, over, hf[0], sum, xr, pos[0], pos[1], pos[2], pos[3], sf[0], sf[1], sf[2], sf[3], score_hash, all_hash, nan }); + } +- work.selection_layer = layer; +- work.selection_position = position; +- work.selection_rows = rows; ++ selw.sel_layer = layer; ++ selw.sel_position = position; ++ selw.sel_rows = rows; + if (make_candidates) { + work.candidate_position = position; + work.candidate_rows = rows; + } +- } else if (work.selection_layer != precedingIndex(layer) or +- work.selection_position != position or work.selection_rows != rows) return error.MissingAttentionSelection; ++ } else if (selw.sel_layer != precedingIndex(layer) or ++ selw.sel_position != position or selw.sel_rows != rows) return error.MissingAttentionSelection; + // Index K consumes the normalized latent before this in-place RoPE mutates it. + if (source.owner == layer and complete != 0) { + try rotate(p, e, latent, complete, 1, c.head_dim, position / ratio * ratio, ratio, ratio, false, c); +@@ -1048,17 +1063,17 @@ pub fn encodeDiagnostic(p: *const Pipelines, e_in: mtl.ComputeEncoder, w: *const + scan_probe.record(e, &p.plain, tensor(w.sink), 1, 128, .sink, layer); + if (ratio != 0 and compressed_rows != 0) + scan_probe.record(e, &p.plain, main, compressed_rows, 288 / 2, .main, layer); +- scan_probe.record(e, &p.plain, work.selection.positions(), rows, 512 * 4 / 2, .pos, layer); ++ scan_probe.record(e, &p.plain, selw.positions(), rows, 512 * 4 / 2, .pos, layer); + if (ratio != 0 and rows > 1) { + var sk: u32 = 0; + while (sk < 4 and sk < rows) : (sk += 1) { + const r = rows - 1 - @as(u32, @intCast((@as(usize, rows - 1) * sk) / 3)); + const vis: u32 = @intCast((position + r + 1) / ratio); +- if (vis != 0) scan_probe.recordStrided(e, &p.plain, work.selection.scores().shifted(@as(usize, r) * 4096 * 4), 1, 4096, vis * 2, .sco, 300000 + r); ++ if (vis != 0) scan_probe.recordStrided(e, &p.plain, selw.scores().shifted(@as(usize, r) * 4096 * 4), 1, 4096, vis * 2, .sco, 300000 + r); + } + } + } +- try p.sparse.encode(e, q, ring, chunk, main, work.selection.positions(), tensor(w.sink), q, work.dense(), work.splitPartials(), .{ .rows = rows, .q_stride = q_width, .position = position, .chunk_rows = rows, .ratio = ratio, .compressed_rows = compressed_rows, .topk = @min(c.index_topk, compressed_rows), .splits = if (rows <= 8) splitScan() else 1 }); ++ try p.sparse.encode(e, q, ring, chunk, main, selw.positions(), tensor(w.sink), q, work.dense(), work.splitPartials(), .{ .rows = rows, .q_stride = q_width, .position = position, .chunk_rows = rows, .ratio = ratio, .compressed_rows = compressed_rows, .topk = @min(c.index_topk, compressed_rows), .splits = if (rows <= 8) splitScan() else 1 }); + if (scan_probe.active(layer)) { + e.barrier(); + scan_probe.record(e, &p.plain, q, rows, @intCast(q_width), .q_post, layer); +@@ -1073,7 +1088,7 @@ pub fn encodeDiagnostic(p: *const Pipelines, e_in: mtl.ComputeEncoder, w: *const + if (scan_probe.stage) |stg| { + ops.encodeCopy(e, &p.plain, .{ .buffer = stg, .offset = 0 }, q, .{ .rows = rows, .width = @intCast(q_width), .x_stride = @intCast(q_width), .y_stride = @intCast(q_width) }); + e.barrier(); +- try p.sparse.encode(e, q, ring, chunk, main, work.selection.positions(), tensor(w.sink), q, work.dense(), work.splitPartials(), .{ .rows = rows, .q_stride = q_width, .position = position, .chunk_rows = rows, .ratio = ratio, .compressed_rows = compressed_rows, .topk = @min(c.index_topk, compressed_rows), .splits = if (rows <= 8) splitScan() else 1 }); ++ try p.sparse.encode(e, q, ring, chunk, main, selw.positions(), tensor(w.sink), q, work.dense(), work.splitPartials(), .{ .rows = rows, .q_stride = q_width, .position = position, .chunk_rows = rows, .ratio = ratio, .compressed_rows = compressed_rows, .topk = @min(c.index_topk, compressed_rows), .splits = if (rows <= 8) splitScan() else 1 }); + e.barrier(); + scan_probe.record(e, &p.plain, q, rows, @intCast(q_width), .q_post2, layer); + } +@@ -1082,8 +1097,8 @@ pub fn encodeDiagnostic(p: *const Pipelines, e_in: mtl.ComputeEncoder, w: *const + e.barrier(); + attnMark(layer, "sparse", prof, &e); + if (diagnostic) try DiagnosticObserver.observe(true, observer, e, layer, .sparse_o, q); +- if (work.publish_stash) |stash| if (work.publish_limit != 0) { +- const prefix = @min(rows, work.publish_limit); ++ if (work.pub_stash[seg]) |stash| if (work.pub_limit[seg] != 0) { ++ const prefix = @min(rows, work.pub_limit[seg]); + if (prefix < rows) try p.cache.publishWindow(e, chunk, .{ .buffer = stash.buffer, .offset = stash.offset + @as(usize, layer) * kv.cache.window * kv.cache.ring_stride }, prefix, position); + }; + try p.cache.publishWindow(e, chunk, ring, rows, position); +diff --git a/zig/src/families/deepseek_v41/backend.zig b/zig/src/families/deepseek_v41/backend.zig +index 340e3a0a7..b7a9c744f 100644 +--- a/zig/src/families/deepseek_v41/backend.zig ++++ b/zig/src/families/deepseek_v41/backend.zig +@@ -311,6 +311,9 @@ const MtpCache = struct { pending: u32, drafts: [4]u32, count: u32 = 3 }; + pub const Backend = struct { + gpa: std.mem.Allocator, + model: *ds.Model, ++ /// ROUND-537: the family vtable, stored (never a literal's address -- see `backend`). ++ vt: be.Backend.VTable = undefined, ++ vt_ready: bool = false, + by: std.AutoHashMapUnmanaged(*Stream, u32) = .empty, + /// Drawn tokens by handle: every read waits for its forward anyway (one sub-forward a window). + ring: [RING]u32 = undefined, +@@ -425,18 +428,29 @@ pub const Backend = struct { + if (b.pen_row.len > 0) b.gpa.free(b.pen_row); + } + ++ /// ROUND-537: THE VTABLE IS STORED IN THE BACKEND, not a literal taken by address. `&.{...}` was a static ++ /// temporary only while every field was comptime-known; a runtime `prefill_many` (the env-gated arm) made ++ /// the same expression a pointer to a stack temporary, and every call through it jumped into garbage. + pub fn backend(b: *Backend) be.Backend { +- return .{ .ptr = b, .penalties = true, .vtable = &.{ +- .prefill = prefill, +- .first = firstFn, +- .queue = queue, +- .read = read, +- .verify = verify, +- .keep = keep, +- .draft = draft, +- .tree = tree, +- .release = release, +- } }; ++ if (!b.vt_ready) { ++ const many = prefillManyOn(); ++ b.vt = .{ ++ .prefill = prefill, ++ .prefill_many = if (many) prefillMany else null, ++ .many_rows = if (many) b.model.workspace.plan.rows else 0, ++ .first = firstFn, ++ .queue = queue, ++ .read = read, ++ .verify = verify, ++ .keep = keep, ++ .draft = draft, ++ .tree = tree, ++ .release = release, ++ }; ++ b.vt_ready = true; ++ if (many) std.log.info("prefill many: armed, {d} rows a pass", .{b.model.workspace.plan.rows}); ++ } ++ return .{ .ptr = b, .penalties = true, .vtable = &b.vt }; + } + + /// A window of any width runs exactly as its slot's own forward; the lane core may bundle streams freely. +@@ -492,9 +506,10 @@ pub const Backend = struct { + /// to be the greedy argmax under any temperature, which is the one draw the owner's echo-prone long system + /// prompts could seed a degenerate turn with. The key is the drawn token's absolute position (drawFirst + /// passes prompt_len; queueNext passes the new cache length), the same key verify's rows use. +- fn draw(b: *Backend, slot: u32, s: *Stream, position: u64) !u32 { +- if (std.c.getenv("TF_DSV41_DRAFT_DEBUG") != null) std.log.info("draw: slot {d} pos {d}", .{ slot, b.model.caches[slot].position }); +- const row = b.model.workspace.logits(1); ++ /// ROUND-537: the draw over an explicit logits row, so a batched prompt pass can draw each segment's ++ /// first token from its own row of the same forward's `.segments` logits. ++ fn drawRow(b: *Backend, s: *Stream, row: []const f32, position: u64) !u32 { ++ _ = b; + if (s.sampling) |sp| if (sp.temperature > 0) { + const first = try sampleRow(row, sp, position); + if (std.c.getenv("TF_DSV41_PEN_DEBUG") != null) std.log.info("first draw: sampled {d} at {d}", .{ first, position }); +@@ -512,6 +527,133 @@ pub const Backend = struct { + return best; + } + ++ fn draw(b: *Backend, slot: u32, s: *Stream, position: u64) !u32 { ++ if (std.c.getenv("TF_DSV41_DRAFT_DEBUG") != null) std.log.info("draw: slot {d} pos {d}", .{ slot, b.model.caches[slot].position }); ++ return drawRow(b, s, b.model.workspace.logits(1), position); ++ } ++ ++ var prefill_many_on: ?bool = null; ++ /// ROUND-537: the batched prompt pass. Default OFF until the A/B receipt lands (ROUND-536 priced the ++ /// merge at -3,806 ms of GPU for eight 284-row suffixes); `TF_DSV41_PREFILL_MANY=1` arms it, `=0` is the ++ /// same-binary control. ++ fn prefillManyOn() bool { ++ if (prefill_many_on) |v| return v; ++ const v = std.c.getenv("TF_DSV41_PREFILL_MANY"); ++ prefill_many_on = if (v) |e| !std.mem.eql(u8, std.mem.span(e), "0") else false; ++ return prefill_many_on.?; ++ } ++ ++ /// ROUND-537: several prompts in one forward. Each stream's suffix is one segment: the row-wise layers ++ /// run once over every segment's rows, the attention core once a segment against that slot's own state ++ /// (R-531's `forwardSegs`), and each stream's first token is drawn from its own segment's last row. ++ /// Admitted only when every stream's whole pass is ONE chunk and the store wants only its end state: ++ /// an interior mark would have to be captured inside the chunk, which this pass cannot do, so such a ++ /// stream is marked not-batchable on the lane side and filled alone. Any error leaves none prefilled ++ /// (`addStreams` falls back to one-by-one). ++ fn prefillMany(ptr: *anyopaque, ss: []const *Stream) anyerror!bool { ++ const b = self(ptr); ++ const dbg = std.c.getenv("TF_DSV41_BATCH_DEBUG") != null; ++ if (ss.len < 2 or ss.len > 8) { ++ if (dbg) std.log.info("prefill many: refused, {d} streams", .{ss.len}); ++ return false; ++ } ++ if (!prefillManyOn() or !batchOn() or !noBatchInstrument()) { ++ if (dbg) std.log.info("prefill many: refused, arm {} batch {} instrument {}", .{ prefillManyOn(), batchOn(), !noBatchInstrument() }); ++ return false; ++ } ++ const rows_cap: u32 = b.model.workspace.plan.rows; ++ var from: [8]u32 = undefined; ++ var tail: [8]u32 = @splat(0); ++ var ntail: usize = 0; ++ var total: u32 = 0; ++ for (ss, 0..) |s, k| { ++ const prompt = s.prompt(); ++ if (prompt.len == 0 or s.isCancelled()) return false; ++ if (s.images.len != 0 or s.embedding != null) return false; ++ const f: u32 = if (s.reuse.saved != null) s.reuse.at else 0; ++ if (f >= prompt.len) return false; ++ const n: u32 = @intCast(prompt.len - f); ++ if (n > rows_cap) return false; ++ var end_mark = s.reuse.hook == null; ++ for (s.reuse.marks) |mk| { ++ if (mk != prompt.len and mk != s.reuse.snap_at) { ++ if (dbg) std.log.info("prefill many: refused, stream {d} mark {d} of {d}", .{ k, mk, prompt.len }); ++ return false; ++ } ++ if (mk == prompt.len) end_mark = true; ++ } ++ if (!end_mark) { ++ if (dbg) std.log.info("prefill many: refused, stream {d} no end mark", .{k}); ++ return false; ++ } ++ from[k] = f; ++ // ROUND-538: THE TAIL MARK MUST BE CAPTURED. The store resumes a conversation at the tile tail it ++ // planned (a mark inside the pass), not at the prompt end for every suffix class (R-502/505); a ++ // batched pass that skipped it made the next turn a full miss (measured: turn 1 1.86 -> 9.84 s at ++ // two lanes). The pass therefore runs to each stream's tail mark, keeps it, then runs the tails. ++ const snap = s.reuse.snap_at; ++ if (snap > f and snap < prompt.len) tail[k] = snap; ++ if (tail[k] != 0) ntail += 1; ++ total += n; ++ } ++ if (total > rows_cap) return false; ++ var segs_buf: [8]ds.Seg = undefined; ++ var slots: [8]u32 = undefined; ++ var made: usize = 0; ++ errdefer { ++ b.model.endSnapTail(); ++ for (ss[0..made]) |s| _ = b.by.remove(s); ++ for (slots[0..made]) |sl| b.model.resetSlot(sl) catch {}; ++ } ++ for (ss, 0..) |s, k| { ++ const prompt = s.prompt(); ++ const i = b.free() orelse return error.NoFreeSlot; ++ const state = &b.model.caches[i]; ++ if (prompt.len + s.max_new + 1 > state.plan.capacity) return error.ContextFull; ++ try b.by.put(b.gpa, s, i); ++ slots[k] = i; ++ made += 1; ++ if (s.reuse.saved) |saved| { ++ const snap: *ds.Model.Snapshot = @ptrCast(@alignCast(saved)); ++ try b.model.snapshotRestore(i, snap); ++ s.cached = from[k]; ++ b.history[i].clearRetainingCapacity(); ++ b.history[i].appendSlice(b.gpa, prompt[0..from[k]]) catch {}; ++ } else { ++ try b.model.resetSlot(i); ++ b.history[i].clearRetainingCapacity(); ++ s.cached = 0; ++ } ++ segs_buf[k] = .{ .slot = i, .ids = prompt[from[k]..], .p0 = from[k] }; ++ } ++ // ROUND-538: EVERY TAIL MARK IS STASHED BEFORE THE PASS. R-504's merged tail (the chunk runs past the ++ // mark, and each layer publishes the rows before it into the slot's stash ring) applied to each ++ // segment: the pass keeps the solo chunk's own class -- ONE chunk from `from` to the prompt end -- so ++ // every row, and the state at the mark, is the one that stream alone would have produced. A pass that ++ // instead split at the marks would move the chunk class and with it the reply (R-505). ++ for (ss, 0..) |s, k| if (tail[k] != 0) { ++ const prompt = s.prompt(); ++ if (!b.model.beginSnapTail(slots[k], prompt[@max(0, @as(usize, tail[k]) - 4)..tail[k]], tail[k], from[k], k)) ++ return error.SnapMarkUnavailable; ++ }; ++ const lg = try b.model.forwardSegs(segs_buf[0..ss.len], .segments); ++ // The marks first (each is the state at its own position, assembled from its own stash), then the ends. ++ for (ss, 0..) |s, k| if (tail[k] != 0) { ++ if (s.reuse.hook) |hook| hook.at(hook.ptr, s, tail[k]); ++ }; ++ for (ss, 0..) |s, k| { ++ const prompt = s.prompt(); ++ const row = lg[@as(usize, k) * 129280 ..][0..129280]; ++ b.first[slots[k]] = try drawRow(b, s, row, @intCast(prompt.len)); ++ // The end mark, exactly as the solo pass fires it (at the store's marks, not unconditionally). ++ if (s.reuse.hook) |hook| if (std.mem.indexOfScalar(u32, s.reuse.marks, @as(u32, @intCast(prompt.len))) != null) ++ hook.at(hook.ptr, s, @intCast(prompt.len)); ++ } ++ if (dbg) std.log.info("prefill many: streams={d} rows={d} tails={d} gpu={d:.3} ms", .{ ss.len, total, ntail, b.model.last_gpu_seconds * 1e3 }); ++ b.model.endSnapTail(); ++ return true; ++ } ++ + fn prefill(ptr: *anyopaque, s: *Stream) anyerror!void { + const b = self(ptr); + const prompt = s.prompt(); +@@ -565,7 +707,7 @@ pub const Backend = struct { + }; + const last = end == prompt.len; + var merge: u32 = if (snap_at > at and snap_at < end and end - at >= 64) snap_at else 0; +- if (merge != 0 and !b.model.beginSnapTail(i, prompt[@max(0, @as(usize, merge) - 4)..merge], merge, at)) merge = 0; ++ if (merge != 0 and !b.model.beginSnapTail(i, prompt[@max(0, @as(usize, merge) - 4)..merge], merge, at, 0)) merge = 0; + if (last) { + _ = try b.model.forwardOn(i, prompt[at..end], .last); + b.first[i] = try b.draw(i, s, @intCast(prompt.len)); +@@ -589,11 +731,11 @@ pub const Backend = struct { + return self(ptr).model.snapshotBytes(); + } + +- pub fn snapSave(ptr: *anyopaque, owner: ?*anyopaque, _: u32) anyerror!*anyopaque { ++ pub fn snapSave(ptr: *anyopaque, owner: ?*anyopaque, at: u32) anyerror!*anyopaque { + const b = self(ptr); + const s: *Stream = @ptrCast(@alignCast(owner orelse return error.NoStream)); + const i = try b.slotOf(s); +- return @ptrCast(try b.model.snapshotSave(i)); ++ return @ptrCast(try b.model.snapshotSave(i, at)); + } + + pub fn snapRestore(_: *anyopaque, _: ?*anyopaque, _: *anyopaque) anyerror!void { +diff --git a/zig/src/families/deepseek_v41/model.zig b/zig/src/families/deepseek_v41/model.zig +index c7cbb5011..61c90b004 100644 +--- a/zig/src/families/deepseek_v41/model.zig ++++ b/zig/src/families/deepseek_v41/model.zig +@@ -36,7 +36,20 @@ fn nowNs() u64 { + } + + pub const prefill_step = 15872; +-pub const Logits = enum { none, last, all }; ++pub const Logits = enum { none, last, all, segments }; ++ ++/// ROUND-538: one slot's merged tail-mark metadata (R-504's mark, now per slot). A batched prompt pass runs ++/// every segment's chunk past its own mark, so each slot keeps the mark its own stream planned; the store's ++/// save is handed the mark's position and merges only when it matches. ++const SnapMark = struct { ++ merge: bool = false, ++ position: u32 = 0, ++ hist: [4]u32 = .{ 0, 0, 0, 0 }, ++ taps_row: u32 = 0, ++ taps_n: u32 = 0, ++ taps_last: u32 = 0, ++ taps_base: u32 = 0, ++}; + + /// ROUND-531: one slot's rows of a batched forward: the slot's window, its ids, and the position its + /// first row lands at. The batch rung is one-row segments (the shared round's lanes). +@@ -634,6 +647,8 @@ pub const Model = struct { + taps_stash: mtl.Buffer, + publish_limit: u32 = 0, + snap_pos: u32 = 0, ++ /// ROUND-538: per-slot marks (256 = the lane cap), so a batched prompt pass can capture each stream's tail. ++ snap_mark: [256]SnapMark = @splat(SnapMark{}), + snap_hist: [4]u32 = .{ 0, 0, 0, 0 }, + snap_taps_row: u32 = 0, + snap_taps_n: u32 = 0, +@@ -995,7 +1010,7 @@ pub const Model = struct { + /// than the window keeps the older slots -- the mark's metadata is recorded, and `publish_limit` makes the + /// chunk's per-layer publish and tap capture also write its PREFIX into the stash. + /// Returns false when the mark's history cannot be built; the caller then keeps the cut. +- pub fn beginSnapTail(m: *Model, slot: u32, hist: []const u32, at: u32, from: u32) bool { ++ pub fn beginSnapTail(m: *Model, slot: u32, hist: []const u32, at: u32, from: u32, seg: usize) bool { + if (hist.len < 3) return false; + const state = &m.caches[slot]; + const q = at - from; +@@ -1018,8 +1033,18 @@ pub const Model = struct { + const ring_bytes = @as(usize, state.plan.layers) * kv.cache.window * kv.cache.ring_stride; + @memcpy(m.snap_ring.contents()[@as(usize, slot) * ring_bytes ..][0..ring_bytes], state.live.contents()[0..ring_bytes]); + @memcpy(m.taps_stash.contents()[0..m.taps.length()], m.taps.contents()[0..m.taps.length()]); +- m.attention_workspace.publish_limit = q; +- m.attention_workspace.publish_stash = .{ .buffer = m.snap_ring, .offset = @as(usize, slot) * ring_bytes }; ++ m.snap_mark[slot] = .{ ++ .merge = true, ++ .position = at, ++ .hist = m.snap_hist, ++ .taps_row = m.snap_taps_row, ++ .taps_n = m.snap_taps_n, ++ .taps_last = m.snap_taps_last, ++ .taps_base = m.snap_taps_base, ++ }; ++ // ROUND-538: the segment's own publication target (segment 0 is the solo path). ++ m.attention_workspace.pub_limit[seg] = q; ++ m.attention_workspace.pub_stash[seg] = .{ .buffer = m.snap_ring, .offset = @as(usize, slot) * ring_bytes }; + return true; + } + +@@ -1032,8 +1057,9 @@ pub const Model = struct { + + pub fn endSnapTail(m: *Model) void { + m.publish_limit = 0; +- m.attention_workspace.publish_limit = 0; +- m.attention_workspace.publish_stash = null; ++ for (&m.attention_workspace.pub_limit) |*v| v.* = 0; ++ for (&m.attention_workspace.pub_stash) |*v| v.* = null; ++ for (m.snap_mark[0..@min(m.lanes, 256)]) |*x| x.merge = false; + } + + /// The bytes one kept state holds: fixed, whatever its position (the slot's whole cache). +@@ -1042,7 +1068,7 @@ pub const Model = struct { + return @as(u64, plan.packedBytes()) + plan.mutableBytes() + m.taps.length(); + } + +- pub fn snapshotSave(m: *Model, slot: u32) !*Snapshot { ++ pub fn snapshotSave(m: *Model, slot: u32, at: u32) !*Snapshot { + if (slot >= m.lanes) return error.InvalidLaneSlot; + const state = &m.caches[slot]; + const snap = try m.gpa.create(Snapshot); +@@ -1054,7 +1080,11 @@ pub const Model = struct { + // ROUND-504: a merged tail chunk's copy is THE STATE AT THE MARK, not at the chunk end: the taps ring and + // the window ring come from the stash the chunk's prefix published, the four-token history is the + // caller's, and the compressed partials at a tile mark are empty. +- const merging = m.publish_limit != 0; ++ // ROUND-538: THE MARK IS THE SLOT'S, MATCHED BY POSITION. A batched prompt pass stashes each stream's ++ // tail mark, and the store saves that stream at that position; an end-state save at another position ++ // (or a mark the store refused) must not merge. ++ const mark = m.snap_mark[slot]; ++ const merging = mark.merge and mark.position == at; + const taps_src = if (merging) m.taps_stash else m.taps; + const taps = try m.gpa.dupe(u8, taps_src.contents()[0..m.taps.length()]); + errdefer m.gpa.free(taps); +@@ -1066,13 +1096,13 @@ pub const Model = struct { + .storage = storage, + .live = live, + .taps = taps, +- .position = if (merging) m.snap_pos else state.position, +- .history = if (merging) m.snap_hist else history, +- .taps_row = if (merging) m.snap_taps_row else m.taps_row, +- .taps_n = if (merging) m.snap_taps_n else m.taps_n, +- .taps_rows_last = if (merging) m.snap_taps_last else m.taps_rows_last, ++ .position = if (merging) mark.position else state.position, ++ .history = if (merging) mark.hist else history, ++ .taps_row = if (merging) mark.taps_row else m.taps_row, ++ .taps_n = if (merging) mark.taps_n else m.taps_n, ++ .taps_rows_last = if (merging) mark.taps_last else m.taps_rows_last, + .taps_rows_valid = if (merging) 0 else m.taps_rows_valid, +- .taps_base = if (merging) m.snap_taps_base else m.taps_base, ++ .taps_base = if (merging) mark.taps_base else m.taps_base, + }; + if (merging) { + const ring_bytes = @as(usize, state.plan.layers) * kv.cache.window * kv.cache.ring_stride; +@@ -1091,7 +1121,11 @@ pub const Model = struct { + hs.update(storage); + var ht = std.hash.Wyhash.init(3); + ht.update(taps); +- std.log.info("snap hash: pos {d} merging {} ring {x} layer0 {x} storage {x} taps {x} hist {d} {d} {d} {d} tapsrow {d} tapsn {d} last {d}", .{ snap.position, merging, h.final(), hl.final(), hs.final(), ht.final(), snap.history[0], snap.history[1], snap.history[2], snap.history[3], snap.taps_row, snap.taps_n, snap.taps_rows_last }); ++ // ROUND-538 instrument: the WHOLE live buffer, so a difference outside the ring (the compressed ++ // path's partials and captures, which the ring hash cannot see) is visible too. ++ var hf = std.hash.Wyhash.init(4); ++ hf.update(live); ++ std.log.info("snap hash: pos {d} merging {} ring {x} layer0 {x} storage {x} taps {x} full {x} hist {d} {d} {d} {d} tapsrow {d} tapsn {d} last {d}", .{ snap.position, merging, h.final(), hl.final(), hs.final(), ht.final(), hf.final(), snap.history[0], snap.history[1], snap.history[2], snap.history[3], snap.taps_row, snap.taps_n, snap.taps_rows_last }); + } + return snap; + } +@@ -1264,7 +1298,7 @@ pub const Model = struct { + /// attention weights, not to batch prefill or to run a profiler. + pub fn forwardSegs(m: *Model, segs: []const Seg, logits: Logits) ![]const f32 { + if (!m.valid) return error.InvalidModelState; +- if (segs.len == 0 or segs.len > 4) return error.InvalidLaneSlot; ++ if (segs.len == 0 or segs.len > 8) return error.InvalidLaneSlot; + const first_seg = segs[0]; + const slot = first_seg.slot; + if (slot >= m.lanes) return error.InvalidLaneSlot; +@@ -1400,10 +1434,12 @@ pub const Model = struct { + enc.barrier(); + hid.record(enc, &p.ops, m.streamView(), rows, .embed, 0); + var asegs: [8]attention.Seg = undefined; ++ var seg_row0: [8]u32 = @splat(0); + { + var at: u32 = 0; + for (segs, 0..) |sg, si| { + asegs[si] = .{ .state = &m.caches[sg.slot], .p0 = sg.p0, .r0 = at, .n = @intCast(sg.ids.len) }; ++ seg_row0[si] = at; + at += @intCast(sg.ids.len); + } + } +@@ -1546,9 +1582,27 @@ pub const Model = struct { + enc = aprof.enc; + e = aprof.cb; + } else if (m.attention_observer) |attention_observer| +- try attention.encodeDiagnostic(&p.attention, enc, &layer.attn, state, &m.attention_workspace, ws.view(.normalized), ws.view(.branch), &p.projection, ws.projection(), @intCast(index), rows, m.cfg, true, attention_observer, null, &.{}) +- else if (segs.len > 1) +- try attention.encodeDiagnostic(&p.attention, enc, &layer.attn, state, &m.attention_workspace, ws.view(.normalized), ws.view(.branch), &p.projection, ws.projection(), @intCast(index), rows, m.cfg, false, null, null, asegs[0..segs.len]) ++ try attention.encodeDiagnostic(&p.attention, enc, &layer.attn, state, &m.attention_workspace, ws.view(.normalized), ws.view(.branch), &p.projection, ws.projection(), @intCast(index), rows, m.cfg, true, attention_observer, null, &.{}, 0) ++ else if (segs.len > 1) multi: { ++ // ROUND-537/538: one-row segments take the shared decode rung (`encodeMulti`, <= 4); a ++ // prompt batch's segments are many rows each, which that rung refuses. Each such segment's ++ // attention runs on the SHIPPED prompt path over its own row range, its own state and its ++ // own selection scratch (`encodeSeg`), so the arithmetic is the chunk that stream would ++ // have run alone; the row-wise layers around it stay shared over every segment's rows. ++ var multi_rows = false; ++ for (segs) |sg| if (sg.ids.len != 1) { ++ multi_rows = true; ++ break; ++ }; ++ if (!multi_rows and segs.len <= 4) { ++ try attention.encodeDiagnostic(&p.attention, enc, &layer.attn, state, &m.attention_workspace, ws.view(.normalized), ws.view(.branch), &p.projection, ws.projection(), @intCast(index), rows, m.cfg, false, null, null, asegs[0..segs.len], 0); ++ break :multi; ++ } ++ for (segs, 0..) |sg, si| { ++ const r0 = seg_row0[si]; ++ try attention.encodeSeg(&p.attention, enc, &layer.attn, &m.caches[sg.slot], &m.attention_workspace, ws.view(.normalized).shifted(@as(usize, r0) * 5120 * 2), ws.view(.branch).shifted(@as(usize, r0) * 5120 * 2), &p.projection, ws.projection(), @intCast(index), @intCast(sg.ids.len), m.cfg, si); ++ } ++ } + else + try attention.encode(&p.attention, enc, &layer.attn, state, &m.attention_workspace, ws.view(.normalized), ws.view(.branch), &p.projection, ws.projection(), @intCast(index), rows, m.cfg); + } +@@ -1650,7 +1704,12 @@ pub const Model = struct { + } + if (logits != .none) { + try m.profileSpan(&enc, .head); +- const output_rows: u32 = if (logits == .all) rows else 1; ++ // ROUND-537: `.segments` writes one logits row a segment (its own last row), so a batched ++ // prompt pass draws each stream's first token from the same forward. The collapse runs once a ++ // segment into `.collapsed` row k; the norm and the head then run over N rows exactly as they ++ // run over one. Nothing else about the head moves. ++ const seg_mode = logits == .segments; ++ const output_rows: u32 = if (seg_mode) @intCast(segs.len) else if (logits == .all) rows else 1; + const first: usize = if (logits == .all) 0 else rows - 1; + if (p.hc_boundary) |*bp| { + if (m.pending_expand) { +@@ -1660,13 +1719,18 @@ pub const Model = struct { + const next = if (m.stream_alt) wsx.view(.stream) else wsx.view(.stream_next); + enc.setPipeline(bp.expand_mix); + inline for (.{ cur, wsx.view(.branch), wsx.view(.post), wsx.view(.comb), tensor(last.projection), wsx.view(.hc_part), next }, 0..) |r, i| enc.setBuffer(r.buffer, r.offset, i); +- enc.dispatchGroups(.{ .width = 20, .height = if (logits == .all) rows else 1 }, .{ .width = 256 }); ++ enc.dispatchGroups(.{ .width = 20, .height = if (logits == .all or seg_mode) rows else 1 }, .{ .width = 256 }); + enc.barrier(); + m.stream_alt = !m.stream_alt; + m.pending_expand = false; + } + } +- mhc.encodeCollapse(enc, &p.mhc, m.streamView().shifted(first * 20480 * 2), ws.view(.previous_pre).shifted(first * 4 * 4), ws.view(.collapsed), .{ .rows = output_rows, .width = 5120, .stream_stride = 20480, .y_stride = 5120 }); ++ if (seg_mode) { ++ for (segs, 0..) |sg, k| { ++ const row = seg_row0[k] + @as(u32, @intCast(sg.ids.len)) - 1; ++ mhc.encodeCollapse(enc, &p.mhc, m.streamView().shifted(@as(usize, row) * 20480 * 2), ws.view(.previous_pre).shifted(@as(usize, row) * 4 * 4), ws.view(.collapsed).shifted(@as(usize, k) * 5120 * 2), .{ .rows = 1, .width = 5120, .stream_stride = 20480, .y_stride = 5120 }); ++ } ++ } else mhc.encodeCollapse(enc, &p.mhc, m.streamView().shifted(first * 20480 * 2), ws.view(.previous_pre).shifted(first * 4 * 4), ws.view(.collapsed), .{ .rows = output_rows, .width = 5120, .stream_stride = 20480, .y_stride = 5120 }); + enc.barrier(); + m.normalize(enc, ws.view(.collapsed), m.weights.norm, ws.view(.normalized), output_rows); + // ROUND-375: the trunk's own head input (the row 0 of the window), so the drafter's head input +@@ -1830,7 +1894,7 @@ pub const Model = struct { + for (segs) |sg| try m.caches[sg.slot].append(@intCast(sg.ids.len)); + m.last_gpu_seconds = e.gpuSeconds() + pipe_gpu_extra / 1e3; + m.valid = true; +- m.logits_rows = if (logits == .all) rows else if (logits == .last) 1 else 0; ++ m.logits_rows = if (logits == .all) rows else if (logits == .last) 1 else if (logits == .segments) segs.len else 0; + return ws.logits(m.logits_rows); + } + +diff --git a/zig/tests/deepseek_v41_reference/operator_history.zig b/zig/tests/deepseek_v41_reference/operator_history.zig +index dd7dd3b72..89b82dfe0 100644 +--- a/zig/tests/deepseek_v41_reference/operator_history.zig ++++ b/zig/tests/deepseek_v41_reference/operator_history.zig +@@ -97,7 +97,7 @@ pub fn runAttentionHistory(gpa: std.mem.Allocator, io: std.Io, model: *Model, tr + errdefer if (encoding) enc.end(); + for (model.checkpoint.shards.items) |shard| enc.useResource(shard.buffer, mtl.ResourceUsage.read); + if (target) { +- try attention.encodeDiagnostic(&model.pipelines.attention, enc, &model.weights.layers[prior].attn, model.cache, &model.attention_workspace, input, model.workspace.view(.branch), &model.pipelines.projection, model.workspace.projection(), @intCast(prior), 1, cfg, true, .{ .ctx = &capture, .capture = AttentionCapture.gpu }); ++ try attention.encodeDiagnostic(&model.pipelines.attention, enc, &model.weights.layers[prior].attn, model.cache, &model.attention_workspace, input, model.workspace.view(.branch), &model.pipelines.projection, model.workspace.projection(), @intCast(prior), 1, cfg, true, .{ .ctx = &capture, .capture = AttentionCapture.gpu }, &.{}, 0); + @memcpy(std.mem.sliceAsBytes(&retained_branch), blob[snapshot_offset + 51200 ..][0..10240]); + } else { + try attention.encode(&model.pipelines.attention, enc, &model.weights.layers[prior].attn, model.cache, &model.attention_workspace, input, model.workspace.view(.branch), &model.pipelines.projection, model.workspace.projection(), @intCast(prior), 1, cfg); diff --git a/bench/r536-compare.py b/bench/r536-compare.py new file mode 100644 index 00000000000..81c102e60b2 --- /dev/null +++ b/bench/r536-compare.py @@ -0,0 +1,46 @@ +#!/usr/bin/env python3 +"""R536: compare the 8-lane cached multi-turn arm (A, parallel 8 + batch) with the solo replay (B).""" +import json +import os +import sys + +HOME = os.path.expanduser("~/rehearse") +A = json.load(open(os.path.join(HOME, "r536-A-8t.json"))) +B = json.load(open(os.path.join(HOME, "r536-B-8t.json"))) + +key = lambda r: (r["turn"], r["lane"]) +a = {key(r): r for r in A["arms"]} +b = {key(r): r for r in B["arms"]} +turns = sorted({k[0] for k in a}) +lanes = sorted({k[1] for k in a}) +ok = 0 +bad = [] +for k in sorted(a): + same = a[k]["sha16"] == b[k]["sha16"] + ok += 1 if same else 0 + if not same: + bad.append((k, a[k]["sha16"], b[k]["sha16"])) +print("token-identical lanes x turns: %d/%d" % (ok, len(a))) +for k, x, y in bad: + print(" MOVED", k, x, y) +print() +for t in turns: + aggA = a[(t, lanes[0])]["agg"] + wallA = a[(t, lanes[0])]["turn_wall"] + wallB = b[(t, lanes[0])]["turn_wall"] + print("turn %d: A wall %.2f s aggregate %.1f | B wall %.2f s" % (t, wallA, aggA, wallB)) +print() +print("lane turn A ttft A tok/s A sha B ttft B tok/s B sha cached") +for k in sorted(a): + t, l = k + print("%-5s %-4d %7.3f %8.2f %-16s %7.3f %8.2f %-16s %s" % ( + l, t, a[k]["ttft"] or 0, a[k]["tok_s"] or 0, a[k]["sha16"], + b[k]["ttft"] or 0, b[k]["tok_s"] or 0, b[k]["sha16"], a[k].get("prompt"))) +deg = max((r["deg"]["max_ngram"] for r in A["arms"]), default=0) +words = min((r["deg"]["words"] for r in A["arms"]), default=0) +print("\nworst repeat n-gram in arm A: %d; shortest reply %d words" % (deg, words)) +# cached row counts from the serve's done lines, per turn +cached = [d["cached"] for d in A["done"]] +print("done lines: %d, all resumed after turn 0: %s" % ( + len(cached), all(c > 0 for c in cached[8:]))) +print("verdict:", "PASS" if ok == len(a) and all(c > 0 for c in cached[8:]) and deg <= 1 else "FAIL") diff --git a/bench/r536-multi8.py b/bench/r536-multi8.py new file mode 100644 index 00000000000..caa6979445d --- /dev/null +++ b/bench/r536-multi8.py @@ -0,0 +1,142 @@ +#!/usr/bin/env python3 +"""R536: the retained cache + the batch at the SHIPPING concurrency (--parallel 8). + +Eight conversations, each a distinct ~6.5k-token opening, four original writing turns. Arm A fires all +eight lanes together every turn on the shipped default (parallel 8, batch on, four-window groups); arm B +replays every conversation solo (parallel 1) on the same binary. The properties: each lane, each turn is +token-identical to its solo replay; every turn after the first resumes; no degenerate turn; memory bounded. +This is the first receipt of the batch + retained cache at eight lanes (R-535 receipted 8 lanes at one +turn and no cache; R-534 receipted 4 lanes and four turns). +""" +import hashlib, json, os, re, sys, threading, time, urllib.request +from collections import Counter + +sys.path.insert(0, os.path.expanduser("~/rehearse")) +import rehearse as R + +BASE_CHARS = int(os.environ.get("R536_BASE", "26000")) +GEN = int(os.environ.get("R536_GEN", "160")) +N = int(os.environ.get("R536_LANES", "8")) +TURNS = [ + ("Write an original short story of about 700 words. Setting: a lighthouse on the Cornish coast " + "in March 1902. Characters: the keeper, Thomas Poldean, 58, and his granddaughter, Eliza, 11. " + "Include one specific date, one named ship, and a storm. Do not summarize, quote or paraphrase " + "the passage above; write only the story."), + ("Now rewrite the same events as a letter from the keeper's wife, Maud, to her sister in " + "Plymouth. Keep the date and the ship's name. About 500 words."), + ("Now write a dialogue-only scene, about 450 words, in which Eliza argues with the " + "harbourmaster about what she saw that night. No narration."), + ("Now write the harbourmaster's official report of the wreck, about 450 words. Keep the date " + "and the ship's name, and make the report's conclusion ambiguous."), +] + + +def chat_raw(messages, max_tokens, barrier=None): + body = {"model": R.MODEL_NAME, "messages": messages, "max_tokens": max_tokens, + "temperature": 0, "top_p": 0.95, "top_k": 20, "seed": 1234, "draft": False, + "stream": True, "stream_options": {"include_usage": True}, + "chat_template_kwargs": {"enable_thinking": False}} + req = urllib.request.Request(R.BASE + "/v1/chat/completions", data=json.dumps(body).encode(), + headers={"Content-Type": "application/json"}) + if barrier is not None: + barrier.wait() + t0 = time.time(); first = last = None; usage = None; text = "" + with urllib.request.urlopen(req, timeout=7200) as r: + for line in r: + line = line.decode().strip() + if not line.startswith("data:"): + continue + d = line[5:].strip() + if d == "[DONE]": + break + j = json.loads(d) + if j.get("usage"): + usage = j["usage"] + ch = j.get("choices") or [] + if ch and ch[0].get("delta", {}).get("content"): + now = time.time() + if first is None: + first = now + last = now + text += ch[0]["delta"]["content"] + n = usage["completion_tokens"] if usage else 0 + return {"prompt": usage["prompt_tokens"] if usage else None, "gen": n, + "ttft": round(first - t0, 3) if first else None, + "decode_s": round(last - first, 3) if first and last else None, + "tok_s": round(n / (last - first), 2) if first and last and last > first else None, + "wall": round(time.time() - t0, 3), + "sha16": hashlib.sha256(text.encode()).hexdigest()[:16], "text": text} + + +def degenerate(text): + w = re.findall(r"[A-Za-z0-9']+", text.lower()) + best = 0 + for n in (6, 8, 12): + g = [" ".join(w[i:i + n]) for i in range(max(0, len(w) - n + 1))] + if g: + best = max(best, Counter(g).most_common(1)[0][1]) + return {"words": len(w), "distinct": len(set(w)), "max_ngram": best} + + +def fire(msgs, tags): + bar = threading.Barrier(len(tags)); out = {}; ths = [] + for tg in tags: + th = threading.Thread(target=lambda tg=tg: out.__setitem__(tg, chat_raw(msgs[tg], GEN, barrier=bar))) + th.start(); ths.append(th) + for th in ths: + th.join() + return out + + +DONE_RE = re.compile(r"done \S+ prompt=(\d+) cached=(\d+).*?tokens=(\d+) sha=(\w+) .*?" + r"ttft=([\d.]+) decode=([\d.]+) elapsed=([\d.]+).*?queued=([\d.]+) tok/s=([\d.]+)") + + +def done_lines(path): + t = open(path, "rb").read().decode("utf-8", "replace") + return [{"prompt": int(m.group(1)), "cached": int(m.group(2)), "tokens": int(m.group(3)), + "sha": m.group(4), "ttft": float(m.group(5)), "decode": float(m.group(6)), + "elapsed": float(m.group(7)), "queued": float(m.group(8)), "tok_s": float(m.group(9))} + for m in DONE_RE.finditer(t)] + + +def main(): + arm = sys.argv[1] if len(sys.argv) > 1 else "A" + text = R.corpus() + lanes = ["c%d" % i for i in range(N)] + msgs = {tg: [{"role": "user", "content": text[i * BASE_CHARS:(i + 1) * BASE_CHARS] + "\n\n" + TURNS[0]}] + for i, tg in enumerate(lanes)} + tag = "r536-%s" % arm + S = R.Serve(tag, 4, extra_env={"TF_DSV41_BATCH_DEBUG": "1"}, parallel=N if arm == "A" else 1) + boot = S.start() + rows = [] + reply = {} + for t in range(len(TURNS)): + if t > 0: + for tg in lanes: + msgs[tg].append({"role": "assistant", "content": reply[tg]}) + msgs[tg].append({"role": "user", "content": TURNS[t]}) + t0 = time.time() + if arm == "A": + out = fire(msgs, lanes) + else: + out = {tg: chat_raw(msgs[tg], GEN) for tg in lanes} + reply = {tg: out[tg]["text"] for tg in lanes} + wall = time.time() - t0 + agg = sum(a["gen"] for a in out.values()) / max(a["decode_s"] for a in out.values()) + for tg in lanes: + a = out[tg] + rows.append(dict(a, turn=t, lane=tg, agg=round(agg, 1), turn_wall=round(wall, 3), + deg=degenerate(a["text"]))) + print("turn %d wall %.2f aggregate %.1f | %s" % ( + t, wall, agg, " ".join("%s %.1f/%s" % (tg, out[tg]["tok_s"] or 0, out[tg]["sha16"][:8]) for tg in lanes))) + boot["stop"] = S.stop() + path = os.path.expanduser("~/rehearse/r536-%s-8t.json" % arm) + json.dump({"boot": boot, "arms": rows, "done": done_lines(S.log_path), "arm": arm, + "gen": GEN, "base_chars": BASE_CHARS}, open(path, "w")) + print("json", path) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/bench/r536-prefill-sweep.py b/bench/r536-prefill-sweep.py new file mode 100644 index 00000000000..32e39d3534e --- /dev/null +++ b/bench/r536-prefill-sweep.py @@ -0,0 +1,160 @@ +#!/usr/bin/env python3 +"""R536: the prompt pass's fixed term, shape by shape -- the price of `prefill_many`. + +One serve, cache off, TF_DSV41_STAGE_CB=1 (the GPU's own per-stage seconds; the wall is the instrument's). +A prompt of N rows is one forward; the same text at 280/560/1,120/2,240/4,480 rows gives each stage's +fixed + marginal cost. The merge question: does one 2,240-row pass cost less than eight 280-row passes? +The stage sums answer it directly, and the same table prices the per-chunk intercept the cached turn pays +(R-534's 0.7-2.8 s suffix ttfts). + +Usage (on studio): python3 r536-prefill-sweep.py OUT.json +""" +import bisect +import json +import os +import re +import sys +import time +import urllib.request + +sys.path.insert(0, os.path.expanduser("~/rehearse")) +import rehearse as R # noqa: E402 + +STAGE = re.compile(r"stage (\w+) layer (\d+): gpu\s+([\d.]+) ms, dispatches (\d+), threadgroups (\d+)") +DONE = re.compile(r"done \S+ prompt=(\d+) cached=(\d+) .*?tokens=(\d+) sha=(\w+) .*?ttft=([\d.]+) decode=([\d.]+)") + +LENGTHS = [280, 560, 1120, 2240, 4480] +CHARS_PER_TOKEN = 4.006 # 88,000 chars -> 21,966 tokens in the standing corpus prompt + + +def request(messages, max_tokens): + body = {"model": R.MODEL_NAME, "messages": messages, "max_tokens": max_tokens, + "temperature": 0, "top_p": 0.95, "top_k": 20, "seed": 1234, + "draft": False, "stream": True, "stream_options": {"include_usage": True}, + "chat_template_kwargs": {"enable_thinking": False}} + req = urllib.request.Request(R.BASE + "/v1/chat/completions", data=json.dumps(body).encode(), + headers={"Content-Type": "application/json"}) + t0 = time.time() + first = last = None + usage = None + out = "" + with urllib.request.urlopen(req, timeout=7200) as r: + for line in r: + line = line.decode().strip() + if not line.startswith("data:"): + continue + d = line[5:].strip() + if d == "[DONE]": + break + j = json.loads(d) + if j.get("usage"): + usage = j["usage"] + ch = j.get("choices") or [] + if ch and ch[0].get("delta", {}).get("content"): + now = time.time() + if first is None: + first = now + last = now + out += ch[0]["delta"]["content"] + return {"prompt": usage["prompt_tokens"] if usage else None, + "gen": usage["completion_tokens"] if usage else None, + "wall": round(time.time() - t0, 3), + "ttft": round((first - t0), 3) if first else None, + "decode_s": round((last - first), 3) if first and last else None, + "sha16": __import__("hashlib").sha256(out.encode()).hexdigest()[:16]} + + +def cycles(log): + out, cur = [], None + for m in STAGE.finditer(log): + label, layer = m.group(1), int(m.group(2)) + if label == "engram" and layer == 0: + if cur: + out.append(cur) + cur = [] + if cur is not None: + cur.append({"label": label, "layer": layer, "ms": float(m.group(3)), + "dispatches": int(m.group(4)), "threadgroups": int(m.group(5)), + "at": m.start()}) + if cur: + out.append(cur) + return out + + +def summary(rows): + tot = {} + for r in rows: + a = tot.setdefault(r["label"], {"ms": 0.0, "dispatches": 0}) + a["ms"] += r["ms"] + a["dispatches"] += r["dispatches"] + return {k: {"ms": round(v["ms"], 3), "dispatches": v["dispatches"]} for k, v in tot.items()} + + +def total(cyc): + return sum(r["ms"] for r in cyc) + + +def main(): + out_path = sys.argv[1] if len(sys.argv) > 1 else os.path.expanduser("~/rehearse/r536-prefill-sweep.json") + text = R.corpus() + srv = R.Serve("r536-prefill", 0, {"TF_DSV41_STAGE_CB": "1"}) + boots = [srv.start()] + results = [] + try: + for n in LENGTHS: + chars = int(n * CHARS_PER_TOKEN) + prompt = text[:chars] + R.S + # two arms: the first touch (Engram pages cold for this slice) and the warm replay + for rep in (0, 1): + a = request(R.msgs(prompt), 2) + a["tag"] = "rows~%d-rep%d" % (n, rep) + a["target"] = n + results.append(a) + finally: + boots.append(srv.stop()) + log = open(srv.log_path, "rb").read().decode("utf-8", "replace") + + done_at = [m.start() for m in DONE.finditer(log)] + allc = cycles(log) + report = {"tree": R.tree_state(), "boots": boots, "arms": [], "lengths": LENGTHS} + for a in results: + report["arms"].append({"tag": a["tag"], "arm": a, "cycles": []}) + for cyc in allc: + i = bisect.bisect_left(done_at, cyc[0]["at"]) + i = min(i, len(report["arms"]) - 1) + report["arms"][i]["cycles"].append(cyc) + for e in report["arms"]: + cycs = e["cycles"] + biggest = max((total(c) for c in cycs), default=0.0) + prompt = [c for c in cycs if total(c) > 0.25 * biggest] + e["prompt_cycles"] = [round(total(c), 2) for c in prompt] + e["prompt"] = [summary(c) for c in prompt] + e["stage_ms"] = {} + for s in e["prompt"]: + for k, v in s.items(): + e["stage_ms"][k] = round(e["stage_ms"].get(k, 0.0) + v["ms"], 3) + e["gpu_ms"] = round(sum(total(c) for c in prompt), 3) + report["arms"] = [{k: v for k, v in e.items() if k != "cycles"} for e in report["arms"]] + + # the decision table: per stage, the fixed + marginal fit, and the merge comparison + rows = [] + for e in report["arms"]: + if e["arm"]["tag"].endswith("rep1"): + rows.append((e["arm"]["prompt"], e["stage_ms"], e["gpu_ms"])) + print("%-8s %-10s %-8s %s" % ("prompt", "gpu_ms", "ttft", "stages")) + for e in report["arms"]: + print("%-14s %-8s %-8s %s" % (e["tag"], e["gpu_ms"], e["arm"]["ttft"], + " ".join("%s=%.1f" % (k, v) for k, v in sorted(e["stage_ms"].items())))) + print("\nmerge price (warm arms):") + for e in report["arms"]: + if e["arm"]["tag"].endswith("rep1"): + n = e["arm"]["prompt"] + print(" %d rows: gpu %.1f ms = %.3f ms/row; routed %.1f" % ( + n, e["gpu_ms"], e["gpu_ms"] / max(n, 1), e["stage_ms"].get("swiglu", 0) + e["stage_ms"].get("down", 0))) + json.dump(report, open(out_path, "w"), indent=1) + print("json", out_path) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/bench/r538-compare.py b/bench/r538-compare.py new file mode 100755 index 00000000000..675803178a3 --- /dev/null +++ b/bench/r538-compare.py @@ -0,0 +1,50 @@ +#!/usr/bin/env python3 +"""R538: compare the 8-lane prompt-batch arm (A) with the same binary's solo replay (B).""" +import json +import os +import sys + +HOME = os.path.expanduser("~/rehearse") +AJ = sys.argv[1] if len(sys.argv) > 1 else "r538-A-many-8t.json" +BJ = sys.argv[2] if len(sys.argv) > 2 else "r538-B-ctl-8t.json" +A = json.load(open(os.path.join(HOME, AJ))) +B = json.load(open(os.path.join(HOME, BJ))) + +key = lambda r: (r["turn"], r["lane"]) +a = {key(r): r for r in A["arms"]} +b = {key(r): r for r in B["arms"]} +turns = sorted({k[0] for k in a}) +lanes = sorted({k[1] for k in a}) +ok = 0 +bad = [] +for k in sorted(a): + same = a[k]["sha16"] == b[k]["sha16"] + ok += 1 if same else 0 + if not same: + bad.append((k, a[k]["sha16"], b[k]["sha16"])) +print("token-identical lanes x turns: %d/%d" % (ok, len(a))) +for k, x, y in bad: + print(" MOVED", k, x, y) +print() +for t in turns: + aggA = a[(t, lanes[0])]["agg"] + wallA = a[(t, lanes[0])]["turn_wall"] + wallB = b[(t, lanes[0])]["turn_wall"] + print("turn %d: A wall %.2f s aggregate %.1f | B wall %.2f s" % (t, wallA, aggA, wallB)) +print() +print("lane turn A ttft A tok/s A sha B ttft B tok/s B sha cached") +for k in sorted(a): + t, l = k + print("%-5s %-4d %7.3f %8.2f %-16s %7.3f %8.2f %-16s %s" % ( + l, t, a[k]["ttft"] or 0, a[k]["tok_s"] or 0, a[k]["sha16"], + b[k]["ttft"] or 0, b[k]["tok_s"] or 0, b[k]["sha16"], a[k].get("prompt"))) +deg = max((r["deg"]["max_ngram"] for r in A["arms"]), default=0) +words = min((r["deg"]["words"] for r in A["arms"]), default=0) +print("\nworst repeat n-gram in arm A: %d; shortest reply %d words" % (deg, words)) +cached = [d["cached"] for d in A["done"]] +print("done lines: %d, all resumed after turn 0: %s" % ( + len(cached), all(c > 0 for c in cached[8:]))) +print("many events in A:", len(A.get("many", []))) +for line in A.get("many", [])[:12]: + print(" ", line) +print("verdict:", "PASS" if ok == len(a) and all(c > 0 for c in cached[8:]) and deg <= 1 else "FAIL") diff --git a/bench/r538-multi8.py b/bench/r538-multi8.py new file mode 100755 index 00000000000..2982297bcc7 --- /dev/null +++ b/bench/r538-multi8.py @@ -0,0 +1,152 @@ +#!/usr/bin/env python3 +"""R538: the prompt-batch merge at the shipping concurrency (--parallel 8). + +Same shape as R536's r536-multi8.py: eight conversations, each a distinct ~6.5k-token opening, four +original writing turns. Arm A fires all eight lanes together every turn on the shipped default (parallel +8, decode batching on); arm B replays every conversation solo (parallel 1) on the same binary. The new +property is the PROMPT merge: with TF_DSV41_PREFILL_MANY=1 and TF_DSV41_BATCH_HOLD_MS=100 the warm turns' +eight suffixes (about 284 rows each) run as ONE forward, so the turn wall should fall by the merge's +-3,806 ms of GPU while every lane stays token-identical to its solo replay. +""" +import hashlib, json, os, re, sys, threading, time, urllib.request +from collections import Counter + +sys.path.insert(0, os.path.expanduser("~/rehearse")) +import rehearse as R + +BASE_CHARS = int(os.environ.get("R536_BASE", "26000")) +GEN = int(os.environ.get("R536_GEN", "160")) +N = int(os.environ.get("R536_LANES", "8")) +CACHE = float(os.environ.get("R538_CACHE", "3")) +TURNS = [ + ("Write an original short story of about 700 words. Setting: a lighthouse on the Cornish coast " + "in March 1902. Characters: the keeper, Thomas Poldean, 58, and his granddaughter, Eliza, 11. " + "Include one specific date, one named ship, and a storm. Do not summarize, quote or paraphrase " + "the passage above; write only the story."), + ("Now rewrite the same events as a letter from the keeper's wife, Maud, to her sister in " + "Plymouth. Keep the date and the ship's name. About 500 words."), + ("Now write a dialogue-only scene, about 450 words, in which Eliza argues with the " + "harbourmaster about what she saw that night. No narration."), + ("Now write the harbourmaster's official report of the wreck, about 450 words. Keep the date " + "and the ship's name, and make the report's conclusion ambiguous."), +] + + +def chat_raw(messages, max_tokens, barrier=None): + body = {"model": R.MODEL_NAME, "messages": messages, "max_tokens": max_tokens, + "temperature": 0, "top_p": 0.95, "top_k": 20, "seed": 1234, "draft": False, + "stream": True, "stream_options": {"include_usage": True}, + "chat_template_kwargs": {"enable_thinking": False}} + req = urllib.request.Request(R.BASE + "/v1/chat/completions", data=json.dumps(body).encode(), + headers={"Content-Type": "application/json"}) + if barrier is not None: + barrier.wait() + t0 = time.time(); first = last = None; usage = None; text = "" + with urllib.request.urlopen(req, timeout=7200) as r: + for line in r: + line = line.decode().strip() + if not line.startswith("data:"): + continue + d = line[5:].strip() + if d == "[DONE]": + break + j = json.loads(d) + if j.get("usage"): + usage = j["usage"] + ch = j.get("choices") or [] + if ch and ch[0].get("delta", {}).get("content"): + now = time.time() + if first is None: + first = now + last = now + text += ch[0]["delta"]["content"] + n = usage["completion_tokens"] if usage else 0 + return {"prompt": usage["prompt_tokens"] if usage else None, "gen": n, + "ttft": round(first - t0, 3) if first else None, + "decode_s": round(last - first, 3) if first and last else None, + "tok_s": round(n / (last - first), 2) if first and last and last > first else None, + "wall": round(time.time() - t0, 3), + "sha16": hashlib.sha256(text.encode()).hexdigest()[:16], "text": text} + + +def degenerate(text): + w = re.findall(r"[A-Za-z0-9']+", text.lower()) + best = 0 + for n in (6, 8, 12): + g = [" ".join(w[i:i + n]) for i in range(max(0, len(w) - n + 1))] + if g: + best = max(best, Counter(g).most_common(1)[0][1]) + return {"words": len(w), "distinct": len(set(w)), "max_ngram": best} + + +def fire(msgs, tags): + bar = threading.Barrier(len(tags)); out = {}; ths = [] + for tg in tags: + th = threading.Thread(target=lambda tg=tg: out.__setitem__(tg, chat_raw(msgs[tg], GEN, barrier=bar))) + th.start(); ths.append(th) + for th in ths: + th.join() + return out + + +DONE_RE = re.compile(r"done \S+ prompt=(\d+) cached=(\d+).*?tokens=(\d+) sha=(\w+) .*?" + r"ttft=([\d.]+) decode=([\d.]+) elapsed=([\d.]+).*?queued=([\d.]+) tok/s=([\d.]+)") + + +def done_lines(path): + t = open(path, "rb").read().decode("utf-8", "replace") + return [{"prompt": int(m.group(1)), "cached": int(m.group(2)), "tokens": int(m.group(3)), + "sha": m.group(4), "ttft": float(m.group(5)), "decode": float(m.group(6)), + "elapsed": float(m.group(7)), "queued": float(m.group(8)), "tok_s": float(m.group(9))} + for m in DONE_RE.finditer(t)] + + +def many_lines(path): + t = open(path, "rb").read().decode("utf-8", "replace") + return re.findall(r"(hold: [^\n]*|many: [^\n]*|prefill many: [^\n]*)", t) + + +def main(): + arm = sys.argv[1] if len(sys.argv) > 1 else "A" + text = R.corpus() + lanes = ["c%d" % i for i in range(N)] + msgs = {tg: [{"role": "user", "content": text[i * BASE_CHARS:(i + 1) * BASE_CHARS] + "\n\n" + TURNS[0]}] + for i, tg in enumerate(lanes)} + mode = "many" if os.environ.get("TF_DSV41_PREFILL_MANY", "0") == "1" else "ctl" + tag = "r538-%s-%s" % (arm, mode) + S = R.Serve(tag, CACHE, extra_env={"TF_DSV41_BATCH_DEBUG": "1"}, parallel=N if arm == "A" else 1) + boot = S.start() + rows = [] + reply = {} + for t in range(len(TURNS)): + if t > 0: + for tg in lanes: + msgs[tg].append({"role": "assistant", "content": reply[tg]}) + msgs[tg].append({"role": "user", "content": TURNS[t]}) + t0 = time.time() + if arm == "A": + out = fire(msgs, lanes) + else: + out = {tg: chat_raw(msgs[tg], GEN) for tg in lanes} + reply = {tg: out[tg]["text"] for tg in lanes} + wall = time.time() - t0 + agg = sum(a["gen"] for a in out.values()) / max(a["decode_s"] for a in out.values()) + for tg in lanes: + a = out[tg] + rows.append(dict(a, turn=t, lane=tg, agg=round(agg, 1), turn_wall=round(wall, 3), + deg=degenerate(a["text"]))) + print("turn %d wall %.2f aggregate %.1f | %s" % ( + t, wall, agg, " ".join("%s %.1f/%s" % (tg, out[tg]["tok_s"] or 0, out[tg]["sha16"][:8]) for tg in lanes)), flush=True) + boot["stop"] = S.stop() + path = os.path.expanduser("~/rehearse/r538-%s-%s-8t.json" % (arm, mode)) + json.dump({"boot": boot, "arms": rows, "done": done_lines(S.log_path), "arm": arm, + "gen": GEN, "base_chars": BASE_CHARS, "many": many_lines(S.log_path), + "prefill_many": os.environ.get("TF_DSV41_PREFILL_MANY", "0"), "mode": mode, + "hold_ms": os.environ.get("TF_DSV41_BATCH_HOLD_MS", "0")}, open(path, "w")) + print("json", path) + print("many events:", len(many_lines(S.log_path))) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/bench/r538-pair.py b/bench/r538-pair.py new file mode 100644 index 00000000000..223e93bfc9e --- /dev/null +++ b/bench/r538-pair.py @@ -0,0 +1,68 @@ +#!/usr/bin/env python3 +"""R538 micro-test: is a two-stream prompt batch token-identical to the same prompts run alone? + +Two short prompts (~600 chars) are each run alone, then fired together so the lane host forms one +two-segment prompt pass. Temperature 0, drafting off, so the first token is the greedy argmax of the +pass's own logits. If the batch's tokens differ from the solo ones the prompt merge moves the reply. +""" +import hashlib, json, os, sys, threading, urllib.request + +sys.path.insert(0, os.path.expanduser("~/rehearse")) +import rehearse as R + +TEXT = R.corpus() +CH = int(os.environ.get("R538_PAIR_CHARS", "600")) +PROMPTS = [TEXT[0:CH], TEXT[6000:6000 + CH]] +N = int(os.environ.get("R538_PAIR_N", "8")) + + +def chat(content, barrier=None): + body = {"model": R.MODEL_NAME, "messages": [{"role": "user", "content": content}], + "max_tokens": N, "temperature": 0, "top_p": 0.95, "top_k": 20, "seed": 1234, + "draft": False, "stream": True, "stream_options": {"include_usage": True}, + "chat_template_kwargs": {"enable_thinking": False}} + req = urllib.request.Request(R.BASE + "/v1/chat/completions", data=json.dumps(body).encode(), + headers={"Content-Type": "application/json"}) + if barrier is not None: + barrier.wait() + text = "" + with urllib.request.urlopen(req, timeout=3600) as r: + for line in r: + line = line.decode().strip() + if not line.startswith("data:"): + continue + d = line[5:].strip() + if d == "[DONE]": + break + j = json.loads(d) + ch = j.get("choices") or [] + if ch and ch[0].get("delta", {}).get("content"): + text += ch[0]["delta"]["content"] + return {"sha16": hashlib.sha256(text.encode()).hexdigest()[:16], "text": text} + + +def main(): + S = R.Serve("r538-pair", 1, extra_env={"TF_DSV41_BATCH_DEBUG": "1"}, parallel=2) + boot = S.start() + solo = [chat(p) for p in PROMPTS] + out = [None, None] + bar = threading.Barrier(2) + ths = [threading.Thread(target=lambda i=i: out.__setitem__(i, chat(PROMPTS[i], barrier=bar))) for i in range(2)] + for t in ths: + t.start() + for t in ths: + t.join() + boot["stop"] = S.stop() + ok = sum(1 for i in range(2) if solo[i]["sha16"] == out[i]["sha16"]) + for i in range(2): + print("prompt %d solo %s batch %s %s" % (i, solo[i]["sha16"], out[i]["sha16"], + "SAME" if solo[i]["sha16"] == out[i]["sha16"] else "MOVED")) + print(" solo :", repr(solo[i]["text"][:100])) + print(" batch:", repr(out[i]["text"][:100])) + print("verdict:", "SAME" if ok == 2 else "MOVED %d/2" % (2 - ok)) + json.dump({"solo": solo, "batch": out, "boot": boot}, open(os.path.expanduser("~/rehearse/r538-pair.json"), "w")) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/bench/r542_long.py b/bench/r542_long.py new file mode 100644 index 00000000000..889dbe051c1 --- /dev/null +++ b/bench/r542_long.py @@ -0,0 +1,21 @@ +import json, os, sys +sys.path.insert(0, os.path.expanduser("~/rehearse")) +import rehearse as R + +def arm(phase, env): + S = R.Serve(phase, 0, extra_env=env) + boot = S.start() + text = R.corpus() + out = [] + out.append(R.chat(S, R.msgs(text[:88000] + R.S), False, 128, tag="21k-plain-128")) + out.append(R.chat(S, R.msgs(text[:88000] + R.S), True, 128, tag="21k-draft-128")) + stop = S.stop() + return {"phase": phase, "env": env, "boot": boot, "arms": out, "stop": stop} + +res = [] +for phase in sys.argv[1:]: + env = {"TF_DSV41_INDEX_SCORE_ONE": "0"} if phase.endswith("-off") else {} + r = arm(phase, env) + res.append(r) + print(json.dumps(r, default=str)) +open("/tmp/r542_long.json", "w").write(json.dumps(res, indent=1, default=str)) diff --git a/bench/r542_prof.py b/bench/r542_prof.py new file mode 100644 index 00000000000..b79cf5b93b5 --- /dev/null +++ b/bench/r542_prof.py @@ -0,0 +1,24 @@ +import json, os, sys, urllib.request +sys.path.insert(0, os.path.expanduser("~/rehearse")) +import rehearse as R +env = {} +if sys.argv[1] == "off": + env = {"TF_DSV41_DENSE_COL_BF16": "0", "TF_DSV41_INDEX_SCORE_ONE": "0"} +S = R.Serve("r542-prof2-"+sys.argv[1], 0, extra_env=dict({"TF_DSV41_ATTN_PROF":"1","TF_DSV41_ATTN_PROF_LAYERS":"2"}, **env), parallel=1) +print("boot", S.start()["pid"]) +text = R.corpus()[:84000] +msgs=[{"role":"user","content":text+"\n\nName the one colour the passage mentions most."}] +body={"model":R.MODEL_NAME,"messages":msgs,"max_tokens":2,"temperature":0,"top_p":0.95,"top_k":20,"seed":1234,"draft":False,"stream":True,"stream_options":{"include_usage":True},"chat_template_kwargs":{"enable_thinking":False}} +req=urllib.request.Request(R.BASE+"/v1/chat/completions",data=json.dumps(body).encode(),headers={"Content-Type":"application/json"}) +out="" +with urllib.request.urlopen(req,timeout=7200) as r: + for line in r: + line=line.decode().strip() + if not line.startswith("data:"): continue + d=line[5:].strip() + if d=="[DONE]": break + j=json.loads(d); ch=j.get("choices") or [] + if ch and ch[0].get("delta",{}).get("content"): out+=ch[0]["delta"]["content"] +print("reply", repr(out)) +print(S.new_log()) +print("STOP", S.stop()) diff --git a/bench/r543_sampled.py b/bench/r543_sampled.py new file mode 100644 index 00000000000..688b9b14ff6 --- /dev/null +++ b/bench/r543_sampled.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""R543: sampled, unequal-length concurrency -- the property the batch has never been asked for. + +The batch's receipts are greedy and lockstep (R-531/532/534/535/536). Real serving samples and its lanes +stop at different lengths. This harness runs four ~22k conversations, three original writing turns, each +lane with its own max_tokens and all lanes at temperature 0.7 / top_p 0.95 / seed 1234, on the shipped +default (parallel 4, batch on, cache 4 GiB); arm B replays every conversation solo (parallel 1) with the +same sampling. The property is per (lane, turn): sha16(A) == sha16(B). Greedy equality is the batch's old +bar; a sampled draw is keyed by (seed, position, id), so a sampled stream exposes any row-wise logit +difference the greedy pick hides. +""" +import hashlib +import json +import os +import re +import sys +import threading +import time +import urllib.request +from collections import Counter + +sys.path.insert(0, os.path.expanduser("~/rehearse")) +import rehearse as R + +BASE_CHARS = int(os.environ.get("R543_BASE", "88000")) +TURNS = [ + ("Write an original short story of about 800 words. Setting: a lighthouse on the Cornish coast in " + "March 1902. Characters: the keeper, Thomas Poldean, 58, and his granddaughter, Eliza, 11. Include " + "one specific date, one named ship, and a storm. Do not summarize or quote the passage above."), + ("Now rewrite the same events as a letter from the keeper's wife, Maud, to her sister in Plymouth. " + "Keep the date and the ship's name. About 550 words."), + ("Now write a dialogue-only scene, about 500 words, in which Eliza argues with the harbourmaster about " + "what she saw that night. No narration."), +] +GEN = [int(x) for x in os.environ.get("R543_GEN", "240,160,200,120").split(",")] + + +def chat_raw(messages, max_tokens, barrier=None): + body = {"model": R.MODEL_NAME, "messages": messages, "max_tokens": max_tokens, + "temperature": 0.7, "top_p": 0.95, "top_k": 20, "seed": 1234, "draft": False, + "stream": True, "stream_options": {"include_usage": True}, + "chat_template_kwargs": {"enable_thinking": False}} + req = urllib.request.Request(R.BASE + "/v1/chat/completions", data=json.dumps(body).encode(), + headers={"Content-Type": "application/json"}) + if barrier is not None: + barrier.wait() + t0 = time.time() + first = last = None + usage = None + text = "" + with urllib.request.urlopen(req, timeout=7200) as r: + for line in r: + line = line.decode().strip() + if not line.startswith("data:"): + continue + d = line[5:].strip() + if d == "[DONE]": + break + j = json.loads(d) + if j.get("usage"): + usage = j["usage"] + ch = j.get("choices") or [] + if ch and ch[0].get("delta", {}).get("content"): + now = time.time() + if first is None: + first = now + last = now + text += ch[0]["delta"]["content"] + n = usage["completion_tokens"] if usage else 0 + return {"prompt": usage["prompt_tokens"] if usage else None, "gen": n, + "ttft": round(first - t0, 3) if first else None, + "decode_s": round(last - first, 3) if first and last else None, + "tok_s": round(n / (last - first), 2) if first and last and last > first else None, + "wall": round(time.time() - t0, 3), + "sha16": hashlib.sha256(text.encode()).hexdigest()[:16], "text": text} + + +def degenerate(text): + w = re.findall(r"[A-Za-z0-9']+", text.lower()) + best = 0 + for n in (6, 8, 12): + g = [" ".join(w[i:i + n]) for i in range(max(0, len(w) - n + 1))] + if g: + best = max(best, Counter(g).most_common(1)[0][1]) + return {"words": len(w), "distinct": len(set(w)), "max_ngram": best} + + +def fire(msgs, tags): + bar = threading.Barrier(len(tags)) + out = {} + ths = [] + for tg in tags: + th = threading.Thread(target=lambda tg=tg: out.__setitem__(tg, chat_raw(msgs[tg], GEN[int(tg[1:])], barrier=bar))) + th.start() + ths.append(th) + for th in ths: + th.join() + return out + + +def main(): + arm = sys.argv[1] if len(sys.argv) > 1 else "A" + text = R.corpus() + lanes = ["c%d" % i for i in range(len(GEN))] + msgs = {tg: [{"role": "user", "content": text[i * BASE_CHARS:(i + 1) * BASE_CHARS] + "\n\n" + TURNS[0]}] + for i, tg in enumerate(lanes)} + tag = "r543-%s" % arm + S = R.Serve(tag, 4, extra_env={"TF_DSV41_BATCH_DEBUG": "1"}, parallel=len(GEN) if arm == "A" else 1) + boot = S.start() + rows = [] + reply = {} + for t in range(len(TURNS)): + if t > 0: + for tg in lanes: + msgs[tg].append({"role": "assistant", "content": reply[tg]}) + msgs[tg].append({"role": "user", "content": TURNS[t]}) + t0 = time.time() + out = fire(msgs, lanes) if arm == "A" else {tg: chat_raw(msgs[tg], GEN[int(tg[1:])]) for tg in lanes} + reply = {tg: out[tg]["text"] for tg in lanes} + wall = time.time() - t0 + agg = sum(a["gen"] for a in out.values()) / max(a["decode_s"] for a in out.values()) + for tg in lanes: + a = out[tg] + rows.append(dict(a, turn=t, lane=tg, asked=GEN[int(tg[1:])], agg=round(agg, 1), + turn_wall=round(wall, 3), deg=degenerate(a["text"]))) + print("turn %d wall %.2f aggregate %.1f | %s" % ( + t, wall, agg, " ".join("%s %d/%s %.1f" % (tg, out[tg]["gen"], out[tg]["sha16"][:8], out[tg]["tok_s"] or 0) for tg in lanes))) + boot["stop"] = S.stop() + path = os.path.expanduser("~/rehearse/r543-%s.json" % arm) + json.dump({"boot": boot, "arms": rows, "log_tail": S.new_log()[-4000:], "arm": arm, + "gen": GEN, "base_chars": BASE_CHARS, "sampling": {"temperature": 0.7, "top_p": 0.95, "seed": 1234}}, + open(path, "w")) + print("json", path) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/build.zig b/build.zig index 3aa689962af..4210c496f07 100644 --- a/build.zig +++ b/build.zig @@ -102,7 +102,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); @@ -115,7 +115,7 @@ pub fn build(b: *std.Build) void { @import("zig/build/flashnext_batch_host.zig").tests(b, test_step); @import("zig/build/lfm3_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/fsr.zig").deviceSteps(b, budget_mods.metal, budget_mods.engine, budget_mods.sources); @@ -175,7 +175,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..45806629dfa --- /dev/null +++ b/docs/deepseek-v41.md @@ -0,0 +1,129 @@ +# 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) and are tuned on one +M5 Ultra (256 GB unified memory, 80-core GPU); receipts name that hardware class and no +other checkpoint or chip is claimed. + +The lane core runs one stream per slot and windows of rows, so concurrent requests keep +their own caches and Engram cursor. The served checks hold: 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. + +## 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; the inference code is MIT and the native reference follows it (see + THIRD_PARTY_NOTICES). +- 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.56 s on the receipt prompt). + +## The kernels + +The lane ships **36 Metal kernel source files** (16 new for this lane, 20 evolved from +upstream's release-checkpoint line) under `zig/kernels/metal/deepseek_v41/` plus the +`core/exl3_projection*` and `core/expert_groups` group. The kernel contract registers the +family at **89 kernel variants: 89/89 pass gates 1–4, 0 fail, 186/186 planted controls +caught red, 2 documented limit records** (`tf-kernel-contract --only dsv41` on the shipped +tree). The headline tensor-unit paths report themselves at boot: `tf_exl3_matmul_prefill_nax` +(prompt) and `tf_exl3_matmul_decode_nax` / the register-only `tf_exl3_matmul_decode_fma` +(decode), beside the CSA2 attention, the sparse index block, the Engram gather and the +hyper-connection boundary. + +## 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 (R-495), 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 (R-529/543). +- **Cold concurrent prefill serializes.** Four simultaneous cold 22k prefills put up to + ~73 s of first-token wait on the last lane (R-543); only a prompt merge would compress + it, and the merge moves the reply (R-538), 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 (R-466); 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 (R-448/456). + +## 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: the FP32 oracle against the FP64 oracle on the same +tokens is 2.90% NRMS, Metal against FP32 is 4.10% at 2.9bpw (the error grows as the +quantization coarsens, the signature of the model amplifying FP32-level differences), and +the indexer's 512-pick selection boundary lands inside an exact BF16 tie at every indexed +layer past the window fill — so pick order there is decided by sub-quantum noise, folded +into the sensitivity accounting. The 1% absolute gate stays a trip-wire next to argmax +agreement, which held at every width. + +Context-labelled standing (M5 Ultra, 256 GB, the streamed line above): prefill 1,276 tok/s +at 3,002 tokens; plain decode 44.9 tok/s at 4.5k and 44.1 at 21k, flat to 42k; drafted +decode 49.4 at 4.5k / 55.3 at 21k / ~49 at 64k; batched four-lane aggregate 59.3 tok/s; +a resumed 21,966-token turn reads its 78-row suffix in 0.56 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/tools/zig/check_dsv41_metal_mirrors.sh b/tools/zig/check_dsv41_metal_mirrors.sh new file mode 100755 index 00000000000..f21c6a775b2 --- /dev/null +++ b/tools/zig/check_dsv41_metal_mirrors.sh @@ -0,0 +1,24 @@ +#!/bin/sh +# ROUND-480: compile the DeepSeek V4.1 family's Metal sources at build time, exactly as the engine concatenates +# them at run time, so their `static_assert(sizeof(...) == N)` mirror checks fail the BUILD, not the boot. +# ROUND-527: the same pass now also enforces COMPLETENESS and a MANIFEST: +# +# * every struct a kernel takes by `constant T&` or `device T*` must assert its own size in the unit that +# compiles it (the R-526 audit found 20 without one; a new kernel argument cannot land without it), +# * every struct the sources define must keep the size the Metal compiler gives it today, as recorded in +# `zig/kernels/metal/deepseek_v41/struct_sizes.txt` (`--update` regenerates it), so any Metal-side edit or +# compiler layout change is a build error even for a struct no Zig type mirrors. +# +# The work is `tools/zig/dsv41_metal_struct_sizes.py`: it reproduces the engine's three run-time joins +# (csa2.zig:91, csa2_index.zig:164, metal/pipelines.zig:122) in a temporary tree that also holds a copy of +# `nax.h` (the sources `#include "../nax.h"`), compiles every unit with `-Xclang -fdump-record-layouts`, +# and reports the compiler's own message on a failure. +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..76736fe54e5 --- /dev/null +++ b/tools/zig/dsv41_metal_struct_sizes.py @@ -0,0 +1,216 @@ +#!/usr/bin/env python3 +"""ROUND-527: the DeepSeek V4.1 Metal struct manifest. + +Every struct the family's Metal sources define is compiled once, in the same translation unit the engine +compiles it in (the three run-time joins plus one unit a source), and its C size is read from the Metal +compiler's own record-layout dump. The result is a checked-in manifest (`struct_sizes.txt`), and this +tool fails the build when: + + * a struct's size differs from the manifest (a Metal-side edit, or a compiler layout change), + * a kernel argument struct has no `static_assert(sizeof(T) == N)` in its unit (the R-526 audit's 20), + * a struct defined in a source has no record layout in the unit that compiles it. + +Usage: dsv41_metal_struct_sizes.py [--update] [DIR] + +DIR defaults to the repository's zig/kernels/metal/deepseek_v41. `--update` rewrites the manifest. +""" +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), by ROUND-480's +# check_dsv41_metal_mirrors.sh. A source that only compiles inside a join is assigned to it below. +JOINS = [ + ("csa2-kv-join", ["kv.metal", "csa2.metal", "csa2_nax.metal"], None), + ("index-kv-join", ["kv.metal", "index_exl3.metal"], None), + ("route-defines", ["route.metal"], "#define TF_DSV41_E 384\n#define TF_DSV41_TOPK 6\n"), +] +JOIN_ONLY = {"csa2.metal", "csa2_nax.metal", "index_exl3.metal", "route.metal"} + +STRUCT_DEF = re.compile(r"\bstruct\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 + for entry in sorted(os.listdir(directory)): + if not entry.endswith(".metal") or entry in JOIN_ONLY: + continue + texts[entry[:-6]] = open(os.path.join(directory, entry), encoding="utf-8").read() + 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, so the + # unit is compiled where the engine's own sources sit: a directory one level under `nax.h`. + 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 STRUCT_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)) + 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 7b7f3f59918..74610eecb4a 100644 --- a/tools/zig/lean_check.py +++ b/tools/zig/lean_check.py @@ -12,9 +12,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", diff --git a/zig/build/deepseek_v41.zig b/zig/build/deepseek_v41.zig new file mode 100644 index 00000000000..d20f1f2434e --- /dev/null +++ b/zig/build/deepseek_v41.zig @@ -0,0 +1,80 @@ +//! Experimental DS4.1 weight-loading qualification targets. +const std = @import("std"); + +pub fn weights( + b: *std.Build, + target: std.Build.ResolvedTarget, + optimize: std.builtin.OptimizeMode, + metal: *std.Build.Module, + core: *std.Build.Module, +) *std.Build.Step { + const host = b.addTest(.{ .root_module = b.createModule(.{ + .root_source_file = b.path("zig/deepseek_v41_weights_checks.zig"), + .target = target, + .optimize = optimize, + .link_libc = true, + .imports = &.{ + .{ .name = "metal", .module = metal }, + .{ .name = "core", .module = core }, + }, + }) }); + const step = b.step("test-deepseek-v41-weights", "V4.1 configuration, Engram table plans and resident weight staging"); + step.dependOn(&b.addRunArtifact(host).step); + return step; +} + +pub fn checks( + b: *std.Build, + target: std.Build.ResolvedTarget, + optimize: std.builtin.OptimizeMode, + metal: *std.Build.Module, + sources: *std.Build.Module, + engine: *std.Build.Module, + core: *std.Build.Module, +) struct { device: *std.Build.Step, reference: *std.Build.Step } { + const device = b.addTest(.{ .root_module = b.createModule(.{ + .root_source_file = b.path("zig/deepseek_v41_checks.zig"), + .target = target, + .optimize = optimize, + .link_libc = true, + .imports = &.{ + .{ .name = "metal", .module = metal }, + .{ .name = "kernel_sources", .module = sources }, + .{ .name = "core", .module = core }, + }, + }) }); + const device_step = b.step("test-deepseek-v41", "Experimental DS4.1 EXL3, Engram, mHC and sparse attention on Metal"); + device_step.dependOn(&b.addRunArtifact(device).step); + // A one-test slice of the same module: the index select's determinism probe, so a kernel-level + // race can be iterated in seconds instead of a model boot. + const probe = b.addTest(.{ .root_module = b.createModule(.{ + .root_source_file = b.path("zig/deepseek_v41_checks.zig"), + .target = target, + .optimize = optimize, + .link_libc = true, + .imports = &.{ + .{ .name = "metal", .module = metal }, + .{ .name = "kernel_sources", .module = sources }, + .{ .name = "core", .module = core }, + }, + }), .filters = &.{"index one-shot select"} }); + const probe_run = b.addRunArtifact(probe); + b.step("test-deepseek-v41-index-probe", "The index one-shot select's same-input determinism, one test").dependOn(&probe_run.step); + const reference = b.addTest(.{ + .root_module = b.createModule(.{ + .root_source_file = b.path("zig/deepseek_v41_reference_checks.zig"), + .target = target, + .optimize = optimize, + .link_libc = true, + .imports = &.{ + .{ .name = "tensorfold", .module = engine }, + .{ .name = "metal", .module = metal }, + .{ .name = "contract", .module = @import("kernel_contract.zig").module(b, target, optimize) }, + }, + }), + .filters = &.{"tests.deepseek_v41_reference."}, + }); + const reference_step = b.step("test-deepseek-v41-reference", "Independent CPU teacher-oracle arithmetic boundaries"); + reference_step.dependOn(&b.addRunArtifact(reference).step); + return .{ .device = device_step, .reference = reference_step }; +} diff --git a/zig/build/exl3.zig b/zig/build/exl3.zig index 646dee6f2c8..8eff4bc3f7b 100644 --- a/zig/build/exl3.zig +++ b/zig/build/exl3.zig @@ -3,8 +3,19 @@ const std = @import("std"); pub fn targets(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, metal: *std.Build.Module, host_tests: *std.Build.Step) void { const files = b.addWriteFiles(); _ = files.addCopyFile(b.path("zig/kernels/metal/core/exl3_projection.metal"), "exl3_projection.metal"); + _ = files.addCopyFile(b.path("zig/kernels/metal/core/exl3_projection_nax.metal"), "exl3_projection_nax.metal"); + _ = files.addCopyFile(b.path("zig/kernels/metal/core/exl3_projection_nax_i8.metal"), "exl3_projection_nax_i8.metal"); + _ = files.addCopyFile(b.path("zig/kernels/metal/core/exl3_projection_i8.metal"), "exl3_projection_i8.metal"); + _ = files.addCopyFile(b.path("zig/kernels/metal/nax.h"), "nax.h"); + // The engine activation glue, for the fused SwiGLU+rotate differential (its precise silu is the reference). + _ = files.addCopyFile(b.path("zig/kernels/metal/deepseek_v41/ops.metal"), "deepseek_v41_ops.metal"); const sources = b.createModule(.{ - .root_source_file = files.add("sources.zig", "pub const core_exl3_projection = @embedFile(\"exl3_projection.metal\");\n"), + .root_source_file = files.add("sources.zig", "pub const core_exl3_projection = @embedFile(\"exl3_projection.metal\");\n" ++ + "pub const core_exl3_projection_i8 = @embedFile(\"exl3_projection_i8.metal\");\n" ++ + "pub const core_exl3_projection_nax = @embedFile(\"exl3_projection_nax.metal\");\n" ++ + "pub const core_exl3_projection_nax_i8 = @embedFile(\"exl3_projection_nax_i8.metal\");\n" ++ + "pub const nax = @embedFile(\"nax.h\");\n" ++ + "pub const deepseek_v41_ops = @embedFile(\"deepseek_v41_ops.metal\");\n"), }); const imports: []const std.Build.Module.Import = &.{ .{ .name = "metal", .module = metal }, .{ .name = "kernel_sources", .module = sources } }; diff --git a/zig/build/metal_targets.zig b/zig/build/metal_targets.zig index 35352c3e9d4..4e7f3635104 100644 --- a/zig/build/metal_targets.zig +++ b/zig/build/metal_targets.zig @@ -82,7 +82,14 @@ pub fn nativeServer(b: *std.Build, target: std.Build.ResolvedTarget, optimize: s return exe; } const install = b.addInstallArtifact(exe, .{ .dest_dir = .{ .override = .{ .custom = "native/bin" } } }); - b.step("native", "tensorfold-native with the Metal engines into zig-out/native/bin (bundles: -Dcpu=apple_m1)").dependOn(&install.step); + // ROUND-480: the family's shared structs are checked twice -- `index_mirror.check` at comptime, and the + // .metal files' own `static_assert`s by compiling them here, with the run-time joins the engine uses. + const mirrors = b.addSystemCommand(&.{ "sh", "tools/zig/check_dsv41_metal_mirrors.sh" }); + mirrors.setCwd(b.path(".")); + b.step("metal-mirrors", "The DeepSeek V4.1 Metal sources compile with their shared-struct static_asserts").dependOn(&mirrors.step); + const native_step = b.step("native", "tensorfold-native with the Metal engines into zig-out/native/bin (bundles: -Dcpu=apple_m1)"); + native_step.dependOn(&install.step); + native_step.dependOn(&mirrors.step); // Link libSystem's memcpy to avoid compiler-rt's weak replacement. const libc_mem = b.addSystemCommand(&.{ "sh", "-c", "nm -m \"$0\" | grep -q 'external _memcpy (from libSystem)' || { echo 'tensorfold-native links its own memcpy: find the typed std.json int parse or 128-bit float conversion that pulled in compiler-rt'; exit 1; }" }); libc_mem.addArtifactArg(exe); @@ -169,11 +176,24 @@ pub fn metalTargets(b: *std.Build, target: std.Build.ResolvedTarget, optimize: s b.getInstallStep().dependOn(&b.addInstallFile(fast_lib, "lib/nemotron_fastmath.metallib").step); b.getInstallStep().dependOn(&lib_install.step); - const mods = metalEngineModules(b, target, optimize, draft_ids); + // One tokenizer module for the whole binary: the V4.1 Engram token-map builder decodes the release tokenizer. + const tokenizer = b.createModule(.{ .root_source_file = b.path("zig/src/core/tokenizer/tokenizer.zig"), .target = target, .optimize = optimize, .link_libc = true }); + const mods = metalEngineModules(b, target, optimize, draft_ids, tokenizer); const metal = mods.metal; const kernels_mod = embedded(b, lib, "tensorfold.metallib"); counters_build.targets(b, target, optimize, metal, mods.sources, test_step); + // DeepSeek V4.1: the operator qualification steps registered beside the other families'. + const dsv41_build = @import("deepseek_v41.zig"); + // The family reaches core through `@import("core")`; this facade owns exactly the files it names. + const core_root = b.createModule(.{ .root_source_file = b.path("zig/dsv41_core_family.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{ .{ .name = "gpu_memory", .module = @import("gpu_memory.zig").module(b, target) }, .{ .name = "tokenizer", .module = tokenizer }, .{ .name = "metal", .module = metal }, .{ .name = "kernel_sources", .module = mods.sources } } }); + test_step.dependOn(dsv41_build.weights(b, target, optimize, metal, core_root)); + + // Core's own tests run in one place: the V4.1 lanes name core, so those files cannot also be path-owned there. + const core_tests = b.addTest(.{ .root_module = b.createModule(.{ .root_source_file = b.path("zig/src/core/root.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "gpu_memory", .module = @import("gpu_memory.zig").module(b, target) } } }) }); + const core_step = b.step("test-core", "The shared core's own unit tests, rooted at core/root.zig"); + core_step.dependOn(&b.addRunArtifact(core_tests).step); + // The engines registry: the families this platform's binaries serve; the CLI reads it for models/info/pull. const api = b.createModule(.{ .root_source_file = b.path("zig/src/core/engine_api.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{.{ .name = "lanes", .module = mods.lanes }} }); const engines = b.createModule(.{ @@ -181,7 +201,7 @@ pub fn metalTargets(b: *std.Build, target: std.Build.ResolvedTarget, optimize: s .target = target, .optimize = optimize, .link_libc = true, - .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "engine_api", .module = api }, .{ .name = "tensorfold", .module = mods.engine } }, + .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "engine_api", .module = api }, .{ .name = "tensorfold", .module = mods.engine }, .{ .name = "tokenizer", .module = tokenizer } }, }); engines.addImport("living", mods.living); @import("drama3_metal.zig").addNative(b, target, optimize, metal, engines, metal_std); @@ -192,6 +212,31 @@ pub fn metalTargets(b: *std.Build, target: std.Build.ResolvedTarget, optimize: s .{ .name = "tf-dispatch-bench", .path = "zig/tests/dispatch_bench.zig", .about = "Dispatch boundary benchmark" }, .{ .name = "tf-kernel-exact", .path = "zig/tests/kernel_exact.zig", .about = "Bit-exact check of a kernel against an MLX oracle case" }, }; + // The DSV41 qualification tool on real weights (this branch has the source but no step). + { + const run_mod = b.createModule(.{ + .root_source_file = b.path("zig/deepseek_v41_run.zig"), + .target = target, .optimize = optimize, .link_libc = true, + .imports = &.{ + .{ .name = "tensorfold", .module = mods.engine }, + .{ .name = "metal", .module = metal }, + .{ .name = "contract", .module = @import("kernel_contract.zig").module(b, target, optimize) }, + }, + }); + const run_exe = b.addExecutable(.{ .name = "tf-dsv41-run", .root_module = run_mod }); + b.installArtifact(run_exe); + b.step("tf-dsv41-run", "DSV41 qualification receipts on real weights").dependOn(&b.addInstallArtifact(run_exe, .{}).step); + + const ids_mod = b.createModule(.{ + .root_source_file = b.path("zig/tf_ids_tmp.zig"), + .target = target, .optimize = optimize, .link_libc = true, + .imports = &.{.{ .name = "tokenizer", .module = tokenizer }}, + }); + const ids_exe = b.addExecutable(.{ .name = "tf-ids", .root_module = ids_mod }); + b.installArtifact(ids_exe); + b.step("tf-ids", "text to token ids JSON").dependOn(&b.addInstallArtifact(ids_exe, .{}).step); + } + for (programs) |p| { const mod = b.createModule(.{ .root_source_file = b.path(p.path), @@ -259,6 +304,11 @@ pub fn metalTargets(b: *std.Build, target: std.Build.ResolvedTarget, optimize: s b.getInstallStep().dependOn(&b.addInstallFile(packed_lib, "lib/nemotron_packed.metallib").step); sources.addImport("nemotron_packed_metallib", embedded(b, packed_lib, "nemotron_packed.metallib")); const engine = mods.engine; + { + const dsv41 = dsv41_build.checks(b, target, optimize, metal, sources, engine, core_root); + test_step.dependOn(dsv41.device); + test_step.dependOn(dsv41.reference); + } // FlashNext's CPU contracts, with the family module's imports so the replay graph type-checks const flash_host = b.addTest(.{ .root_module = b.createModule(.{ .root_source_file = b.path("zig/flashnext_host.zig"), @@ -331,6 +381,11 @@ pub fn metalTargets(b: *std.Build, target: std.Build.ResolvedTarget, optimize: s .{ .name = "tf-moss-image-decoder", .path = "zig/tests/moss_image_decoder.zig", .about = "MOSS-Image's image decoder on latents, gated against float64 beside torch float32, then timed" }, .{ .name = "tf-glm-attn-probe", .path = "zig/tests/glm_attn_probe.zig", .about = "GLM-5.3-Flash's dense latent attention kernels on given inputs (scores, probabilities, outputs)" }, .{ .name = "tf-moe-bench", .path = "zig/tests/moe_bench.zig", .about = "Routed-expert prompt kernels from .metal files on a skewed routing: chained speed, bits against the first" }, + .{ .name = "tf-mlx-gather", .path = "zig/tests/mlx_gather.zig", .about = "The reference MLX gathered quantised matmul (MIT, mlx_steel.h) at our routed shapes: ms, GB/s, weights/s" }, + .{ .name = "tf-gemm-bench", .path = "zig/tests/dsv41_gemm_bench.zig", .about = "MLXs gemm_nax at prompt shapes: the boxs bf16 tensor-unit GEMM rate" }, + .{ .name = "tf-fp8-repack", .path = "zig/tests/fp8_repack.zig", .about = "One EXL3 projection decoded to its unrotated W_q and requantized to E4M3 in the fp8 dense body tile order" }, + .{ .name = "tf-gate-bench", .path = "zig/tests/dsv41_gate_bench.zig", .about = "The router gate: tf-dense-col, the tensor-unit gate GEMM (f16/bf16), each against fp64" }, + .{ .name = "tf-scan-bench", .path = "zig/tests/dsv41_scan_bench.zig", .about = "The prompt scan at its real shape: the dense-key pass, the tensor-unit sparse attention, key and split sweeps" }, .{ .name = "tf-mm-bench", .path = "zig/tests/mm_bench.zig", .about = "Prompt matmul kernels from .metal files: chained speed at one shape, bits against the first, error against fp64" }, .{ .name = "tf-sq-bench", .path = "zig/tests/sq_bench.zig", .about = "Row-exact 4-bit prompt tiles before the M5: chained speed at one shape, every output's bits against the first" }, .{ .name = "tf-gemma4-kernels", .path = "zig/tests/gemma4/kernels.zig", .about = "Gemma 4 dense decode kernels against the reference's dumped fixtures, bit for bit by window width" }, @@ -346,8 +401,6 @@ pub fn metalTargets(b: *std.Build, target: std.Build.ResolvedTarget, optimize: s .{ .name = "tf-llama-run", .path = "zig/tests/llama/run.zig", .about = "Llama on Metal: greedy tokens, every position's logits or a prompt's last logits, for the reference's check" }, .{ .name = "tf-qwen36-row-seam", .path = "zig/tests/qwen36_row_seam.zig", .about = "Model-free fixture: the row projection's bias sums stay fp32 at every width" }, }; - // the tokenizer for the programs that tokenize prompts themselves (the engine module has none) - const tokenizer = b.createModule(.{ .root_source_file = b.path("zig/src/core/tokenizer/tokenizer.zig"), .target = target, .optimize = optimize, .link_libc = true }); for (engine_programs) |p| { const mod = b.createModule(.{ .root_source_file = b.path(p.path), @@ -494,7 +547,7 @@ pub fn metalTargets(b: *std.Build, target: std.Build.ResolvedTarget, optimize: s } } -pub fn metalEngineModules(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, draft_ids: *std.Build.Module) struct { metal: *std.Build.Module, lanes: *std.Build.Module, fabric: *std.Build.Module, sources: *std.Build.Module, engine: *std.Build.Module, living: *std.Build.Module, qwen27: qwen27_build.Shared } { +pub fn metalEngineModules(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, draft_ids: *std.Build.Module, tokenizer: *std.Build.Module) struct { metal: *std.Build.Module, lanes: *std.Build.Module, fabric: *std.Build.Module, sources: *std.Build.Module, engine: *std.Build.Module, living: *std.Build.Module, qwen27: qwen27_build.Shared } { const metal = b.createModule(.{ .root_source_file = b.path("zig/src/metal/metal.zig"), .target = target, @@ -515,13 +568,13 @@ pub fn metalEngineModules(b: *std.Build, target: std.Build.ResolvedTarget, optim .target = target, .optimize = optimize, .link_libc = true, - .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "kernel_sources", .module = sources }, .{ .name = "nemotron_draft_ids", .module = draft_ids }, .{ .name = "lanes", .module = lanes }, .{ .name = "fabric", .module = fabric }, .{ .name = "living", .module = living } }, + .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "kernel_sources", .module = sources }, .{ .name = "nemotron_draft_ids", .module = draft_ids }, .{ .name = "lanes", .module = lanes }, .{ .name = "fabric", .module = fabric }, .{ .name = "living", .module = living }, .{ .name = "tokenizer", .module = tokenizer } }, }); return .{ .metal = metal, .lanes = lanes, .fabric = fabric, .sources = sources, .engine = engine, .living = living, .qwen27 = qwen27_build.engineModules(b, target, metal, sources, engine) }; } pub fn distMetalServer(b: *std.Build, target: std.Build.ResolvedTarget, draft_ids: *std.Build.Module, build_options: *std.Build.Step.Options, sdk: []const u8) *std.Build.Step.Compile { - const m = metalEngineModules(b, target, .fast, draft_ids); + const m = metalEngineModules(b, target, .fast, draft_ids, b.createModule(.{ .root_source_file = b.path("zig/src/core/tokenizer/tokenizer.zig"), .target = target, .optimize = .ReleaseSafe, .link_libc = true })); // the release binary embeds the same prebuilt packed-kernel metallib as the development build const flags = [_][]const u8{ b.fmt("-std={s}", .{mlxMetalStd(b)}), "-fmetal-math-mode=safe", "-fmetal-math-fp32-functions=fast" }; m.sources.addImport("nemotron_packed_metallib", embedded(b, metallib(b, "nemotron_packed", &nemotron_packed, &flags), "nemotron_packed.metallib")); diff --git a/zig/deepseek_v41_checks.zig b/zig/deepseek_v41_checks.zig new file mode 100644 index 00000000000..37fa3c8c8da --- /dev/null +++ b/zig/deepseek_v41_checks.zig @@ -0,0 +1,14 @@ +//! Source-built V4.1 operator qualification; real Metal execution, no checkpoint needed. +test { + _ = @import("core").exl3_projection_gpu_test; + _ = @import("src/families/deepseek_v41/engram.zig"); + _ = @import("src/families/deepseek_v41/csa2.zig"); + _ = @import("src/families/deepseek_v41/kv_test.zig"); + _ = @import("src/families/deepseek_v41/ops_check.zig"); + _ = @import("src/families/deepseek_v41/load.zig"); + _ = @import("src/families/deepseek_v41/index_precision_test.zig"); + _ = @import("src/families/deepseek_v41/config.zig"); + _ = @import("src/families/deepseek_v41/profiler.zig"); + _ = @import("core").gpu_counters; + _ = @import("core").expert_groups; +} diff --git a/zig/deepseek_v41_reference_checks.zig b/zig/deepseek_v41_reference_checks.zig new file mode 100644 index 00000000000..4dd983daa7e --- /dev/null +++ b/zig/deepseek_v41_reference_checks.zig @@ -0,0 +1,21 @@ +//! Independent CPU arithmetic boundaries used by the resident-checkpoint teacher oracle. +test { + _ = @import("tests/deepseek_v41_reference/projection.zig"); + _ = @import("tests/deepseek_v41_reference/math.zig"); + _ = @import("tests/deepseek_v41_reference/attention_math.zig"); + _ = @import("tests/deepseek_v41_reference/qualify.zig"); + _ = @import("tests/deepseek_v41_reference/operator_hc_fp64.zig"); + _ = @import("tests/deepseek_v41_reference/operator_hc_split_fp64.zig"); + _ = @import("tests/deepseek_v41_reference/operator_hc_amplify_fp64.zig"); + _ = @import("tests/deepseek_v41_reference/operator_csa2_fp64.zig"); + _ = @import("tests/deepseek_v41_reference/operator_csa2_pack_fp64.zig"); + _ = @import("tests/deepseek_v41_reference/operator_csa2_sparse_fp64.zig"); + _ = @import("tests/deepseek_v41_reference/operator_csa2_rope_fp64.zig"); + _ = @import("tests/deepseek_v41_reference/operator_csa2_index_fp64.zig"); + _ = @import("tests/deepseek_v41_reference/operator_exl3_projection_fp64.zig"); + _ = @import("tests/deepseek_v41_reference/operator_combine_fp64.zig"); + _ = @import("tests/deepseek_v41_reference/operator_affine_i8_fp64.zig"); + _ = @import("tests/deepseek_v41_reference/wo_a_fusion.zig"); + _ = @import("tests/deepseek_v41_reference/row_invariance.zig"); + _ = @import("tests/deepseek_v41_reference/exl3_int8_tile.zig"); +} diff --git a/zig/deepseek_v41_run.zig b/zig/deepseek_v41_run.zig new file mode 100644 index 00000000000..5190b2494e6 --- /dev/null +++ b/zig/deepseek_v41_run.zig @@ -0,0 +1,447 @@ +//! Full-checkpoint admission and execution receipts; no synthetic weights or replay substitute. +const std = @import("std"); +const mtl = @import("metal"); +const tf = @import("tensorfold"); +const ds = tf.deepseek_v41; +const config = tf.deepseek_v41_config; +const load = tf.deepseek_v41_load; +const weights = tf.deepseek_v41_weights; +const process_memory = @import("src/server/process_memory.zig"); +const oracle = @import("tests/deepseek_v41_reference/qualify.zig"); +const margins = @import("tests/deepseek_v41_reference/margins.zig"); +const profile = @import("tests/deepseek_v41_reference/profile.zig"); +const trace = @import("tests/deepseek_v41_reference/trace.zig"); +const operators = @import("tests/deepseek_v41_reference/operators.zig"); +const attention_operators = @import("tests/deepseek_v41_reference/operator_attention.zig"); +const history_operators = @import("tests/deepseek_v41_reference/operator_history.zig"); +const hc_operators = @import("tests/deepseek_v41_reference/operator_hc.zig"); +const moe_operators = @import("tests/deepseek_v41_reference/operator_moe.zig"); +const stagediff = @import("tests/deepseek_v41_reference/stagediff.zig"); + +fn usage(code: u8) noreturn { + std.debug.print("usage: tf-dsv41-run plan MODEL TABLES\n" ++ + " tf-dsv41-run teacher MODEL TABLES IDS_JSON OUT_DIR [CHUNK]\n" ++ + " tf-dsv41-run seams MODEL TABLES IDS_JSON OUT_DIR\n" ++ + " tf-dsv41-run oracle MODEL TABLES IDS_JSON OUT_DIR\n" ++ + " tf-dsv41-run oracle-fp64 MODEL TABLES IDS_JSON OUT_DIR\n" ++ + " tf-dsv41-run margins MODEL TABLES IDS_JSON OUT_DIR [DEEP]\n" ++ + " tf-dsv41-run profile MODEL TABLES IDS_JSON OUT_DIR\n" ++ + " tf-dsv41-run trace MODEL TABLES IDS_JSON OUT_DIR\n" ++ + " tf-dsv41-run gate MODEL TABLES IDS_JSON OUT_DIR\n" ++ + " tf-dsv41-run operators MODEL TABLES OUT_DIR\n" ++ + " tf-dsv41-run attention-sameinput MODEL TABLES TRACE_CPU_BIN OUT_DIR [LAYER]\n" ++ + " tf-dsv41-run attention-history-sameinput MODEL TABLES TRACE_DIR OUT_DIR TOKEN LAYER\n" ++ + " tf-dsv41-run hc-sameinput MODEL TABLES TRACE_CPU_BIN OUT_DIR [LAYER]\n" ++ + " tf-dsv41-run moe-sameinput MODEL TABLES TRACE_GPU_BIN OUT_DIR [LAYER]\n" ++ + " tf-dsv41-run stagediff MODEL TABLES IDS_JSON OUT_DIR [STEPS] [ROWS]\n" ++ + " tf-dsv41-run draftloop MODEL TABLES IDS_JSON OUT_DIR [ROUNDS] [ROWS]\n" ++ + " tf-dsv41-run generate MODEL TABLES IDS_JSON OUT_DIR [TOKENS]\n" ++ + " tf-dsv41-run lanes MODEL TABLES IDS_JSON OUT_DIR [CHUNK] [CONTEXT]\n" ++ + "IDS_JSON: nonempty JSON array of token IDs below 129280.\n" ++ + "Limits: oracle/trace 16 IDs; profile 256 IDs; teacher/seams/lanes 4096 IDs.\n" ++ + "History: TOKEN below 4096; retained normalized prefix at most 256 MiB.\n" ++ + "Local diagnostics do not qualify the model. Oracle retains the independent 1% NRMS gate.\n", .{}); + std.process.exit(code); +} +fn number(s: []const u8) !u32 { + return std.fmt.parseInt(u32, s, 10); +} +fn validArguments(args: []const [:0]const u8) bool { + if (args.len < 2) return false; + const mode = args[1]; + for ([_][]const u8{ "plan", "operators" }, [_]usize{ 4, 5 }) |name, count| + if (std.mem.eql(u8, mode, name)) return args.len == count; + if (std.mem.eql(u8, mode, "attention-history-sameinput")) return args.len == 8; + for ([_][]const u8{ "teacher", "generate", "attention-sameinput", "hc-sameinput", "moe-sameinput", "margins" }) |name| + if (std.mem.eql(u8, mode, name)) return args.len == 6 or args.len == 7; + if (std.mem.eql(u8, mode, "seams") or std.mem.eql(u8, mode, "stagediff") or std.mem.eql(u8, mode, "draftloop")) return args.len == 6 or args.len == 7 or args.len == 8; + if (std.mem.eql(u8, mode, "lanes")) return args.len == 6 or args.len == 7 or args.len == 8; + for ([_][]const u8{ "oracle", "oracle-fp64", "profile", "trace", "gate" }) |name| + if (std.mem.eql(u8, mode, name)) return args.len == 6; + return false; +} +test "lanes takes its optional chunk and context arguments" { + const six = [_][:0]const u8{ "tf-dsv41-run", "lanes", "model", "tables", "ids.json", "out" }; + const seven = [_][:0]const u8{ "tf-dsv41-run", "lanes", "model", "tables", "ids.json", "out", "16" }; + const eight = [_][:0]const u8{ "tf-dsv41-run", "lanes", "model", "tables", "ids.json", "out", "16", "4096" }; + const five = [_][:0]const u8{ "tf-dsv41-run", "lanes", "model", "tables", "ids.json" }; + const nine = [_][:0]const u8{ "tf-dsv41-run", "lanes", "model", "tables", "ids.json", "out", "16", "4096", "x" }; + try std.testing.expect(validArguments(&six)); + try std.testing.expect(validArguments(&seven)); + try std.testing.expect(validArguments(&eight)); + try std.testing.expect(!validArguments(&five)); + try std.testing.expect(!validArguments(&nine)); +} + +fn argmax(row: []const f32) !u32 { + var best: u32 = 0; + if (row.len == 0) return error.EmptyLogits; + var score = -std.math.inf(f32); + for (row, 0..) |v, i| { + if (!std.math.isFinite(v)) return error.NonfiniteLogits; + if (v > 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"); + 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], + // LOCAL (receipt run): stream the Engram tables from the release, the class this machine can hold. + .stream_dir = if (std.c.getenv("TF_DSV41_ENGRAM_STREAM_DIR")) |d| std.mem.span(d) else null, + .token_map = map, + .lanes = if (is_lanes or is_draftloop) 2 else 1, + // Two full-capacity caches sit at the machine's wired edge; the receipt needs only the prompt's window. + .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(); + const before = try counters(); + var execution_after: ?Counters = null; + var execution_error: ?anyerror = null; + execute(a, io, model, args, ids, map_blob, dir, before, &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; + const receipt = try std.json.Stringify.valueAlloc(a, .{ + .mode = mode, + .evidence_origin = "current_invocation_not_historical_qualification", + .context_capacity = model.cache.plan.capacity, + .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", + .execution_disk_read_bytes = after.disk_read - before.disk_read, + .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; +} + +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, 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) { + try operators.run(a, io, model, dir); + _ = try oracle.run(a, io, model, ids, map_blob, dir); + } else if (is_oracle_fp64) { + // ROUND-377: the same window against the FP64 chain (the reference chain at its ideal contract). + try operators.run(a, io, model, dir); + _ = try oracle.runF64(a, io, model, ids, map_blob, dir); + } 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, which is what makes every later + // stage comparison arithmetic-only. The pass/fail evaluation reads the artefacts this writes. + 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); + // Capture execution before writing the receipt, not filesystem metadata reads from the receipt itself. + 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..b3d4fedcacf --- /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.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..9e17f10fd9f --- /dev/null +++ b/zig/dsv41_core_family.zig @@ -0,0 +1,14 @@ +//! The core modules the DeepSeek V4.1 family names as `core`: the family is its own module, so it cannot climb out. +pub const checkpoint_metal = @import("src/core/checkpoint_metal.zig"); +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..1b526f493c9 100644 --- a/zig/dsv41_token_map.zig +++ b/zig/dsv41_token_map.zig @@ -1,6 +1,4 @@ -//! Builds the canonical Engram token map from the release tokenizer and typed configuration. - -// Algorithm: DeepSeek AI inference/engram.py, MIT; the pinned revision is retained in source below. +// The Engram token map builder's CLI; the lane host runs the same build to write a missing map. const std = @import("std"); const tok = @import("src/core/tokenizer/tokenizer.zig"); const unicode = @import("src/core/tokenizer/unicode.zig"); @@ -10,19 +8,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 +127,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 +136,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_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/affine_mm.metal b/zig/kernels/metal/core/affine_mm.metal index 0ff4b7b9f64..bb98749a276 100644 --- a/zig/kernels/metal/core/affine_mm.metal +++ b/zig/kernels/metal/core/affine_mm.metal @@ -1,3 +1,7 @@ +// Ported whole from BobClawblaw/TensorFold, branch deepseek-v41-main, commit 72a552ed +// ("deepseek_v41: prompt chunks' routed experts in int8 x int8"), Apache-2.0; see THIRD_PARTY_NOTICES.md. +// Unmodified below except for this header. The rest of the file is the sibling's own, so its fragment +// layout and epilogue are the compiled code that carries their KL receipt. // x W^T for MLX affine W on the tensor units: exact codes (4-bit ones plus 128) in the MMAs, fp32 group sums scaled, bias times fp32 row sums. #include using namespace metal; @@ -8,11 +12,30 @@ using namespace tfp; #ifndef TF_OUT_T #define TF_OUT_T bfloat #endif +// TF_I8: x as int8 with an fp32 scale a TF_QG columns (32 or 64), int8 codes, int32 sums (affine_mm_i8.h). +#if defined(TF_I8) +#if TF_GROUP == 128 || TF_QG > TF_GROUP +#error "TF_I8 takes groups of 32 or 64, TF_QG within one" +#endif +typedef int8_t AM_T; // x's and the code tile's element +typedef int32_t AM_ACC; // a group's sums +#define AM_XA , const device float* XA [[buffer(14)]] +#define AM_XA_ARG XA +#else +typedef bfloat AM_T; +typedef float AM_ACC; +#define AM_XA +#define AM_XA_ARG nullptr +#endif constant constexpr int STEP_BYTES = 8 * TF_BITS; // a weight row's bytes in one 64-deep step constant constexpr int HALF_BYTES = 4 * TF_BITS; // a thread's half of them (32 codes) constant constexpr int NG = TF_GROUP > 64 ? 1 : 64 / TF_GROUP; // groups a step touches (g128: one, over two steps) -constant constexpr int PAD = 64 + 8; // the code tile's row pitch (bf16) +constant constexpr int PAD = 64 + 8; // the code tile's row pitch (elements) +#if defined(TF_I8) +constant constexpr float OFF = TF_BITS == 8 ? -128.0f : 0.0f; // 8-bit codes as int8 (q - 128); bias + 128 scale undoes it +#else constant constexpr float OFF = TF_BITS == 4 ? 128.0f : 0.0f; // bf16(128 + q) is q's bits ORed with 0x4300; bias - 128 scale undoes it +#endif struct MmArgs { int rows, n, k, experts; // rows (sorted by expert for a gather), outputs a row, depth, experts (gather) @@ -24,6 +47,7 @@ struct MmStrides { }; // Each row's fp32 sum over each group of x (row pitch a.n, or a.k when 0), in order: the bias's operand. +#if !defined(TF_I8) // int8: affine_mm_i8.h [[kernel]] void tf_affine_row_sums(const device bfloat* X [[buffer(0)]], constant MmArgs& a [[buffer(5)]], device float* XS [[buffer(6)]], uint2 gid [[thread_position_in_grid]]) { const int g = int(gid.x), r = int(gid.y), groups = a.k / TF_GROUP; @@ -35,18 +59,19 @@ struct MmStrides { } XS[long(r) * groups + g] = sum; } +#endif // (lo | hi) = a * (b0 | b1): a group's first 16-deep slice, its destination overwritten. -inline void am_first(thread frag& lo, thread frag& hi, thread const frag& a, - thread const frag& b0, thread const frag& b1) { +inline void am_first(thread frag& lo, thread frag& hi, thread const frag& a, + thread const frag& b0, thread const frag& b1) { #ifndef TF_SIMD_FRAGS using namespace mpp::tensor_ops; constexpr auto shape = matmul2d_descriptor(16, 32, 16, false, true, true, matmul2d_descriptor::mode::multiply); matmul2d op; - auto left = op.template get_left_input_cooperative_tensor(); - auto right = op.template get_right_input_cooperative_tensor(); + auto left = op.template get_left_input_cooperative_tensor(); + auto right = op.template get_right_input_cooperative_tensor(); auto acc = op.template get_destination_cooperative_tensor, - metal::remove_addrspace_t, float>(); + metal::remove_addrspace_t, AM_ACC>(); TF_UNROLL for (short e = 0; e < 8; e++) { left[e] = a[e]; @@ -152,21 +177,28 @@ inline void am_codes(thread const Codes& c, threadgroup bfloat* out) { #endif } + // A block of the code tile as the transposed right operand: 8-byte loads on M5 (PAD rows, 16-column blocks). -#ifndef TF_SIMD_FRAGS +#if !defined(TF_I8) && !defined(TF_SIMD_FRAGS) // int8: affine_mm_i8.h #define am_tile_frag frag_get_tg -#else +#elif !defined(TF_I8) #define am_tile_frag frag_get_t #endif // A lane's two rows (home.y and home.y + 8) of each of its TM fragments: their starts in x and in the row sums. template struct AmRows { - const device bfloat* x[TM][2]; + const device AM_T* x[TM][2]; const device float* s[TM][2]; +#if defined(TF_I8) + const device float* a[TM][2]; // the rows' int8 scales, one a TF_QG columns +#endif }; // The fragment of x at column c from a lane's two row starts (8-byte loads on M5). +#if defined(TF_I8) +#include "affine_mm_i8.h" +#else inline frag am_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)); @@ -179,8 +211,10 @@ inline frag am_frag(const device bfloat* r0, const device bfloat* r1, in return f; #endif } +#endif // One step's MMAs and group epilogues for the first TL of TM row fragments (TL < TM: a tile's tail, the rest dead). +#if !defined(TF_I8) // int8: affine_mm_i8.h template inline void am_step(thread frag (&acc)[TM][2], thread const AmRows& rows, int k, const threadgroup bfloat* tile, const threadgroup float* sb, int tn, short2 home) { @@ -222,6 +256,7 @@ inline void am_step(thread frag (&acc)[TM][2], thread const AmRows& r } } } +#endif // am_step at g128: a group spans two steps, so its sums carry over (`part`) and its epilogue follows the second. template @@ -267,8 +302,8 @@ inline void am_step128(thread frag (&acc)[TM][2], thread frag (&pa template inline void am_k_loop(thread frag (&acc)[TM][2], thread const AmRows& rows, int K, int live, const device uchar* wq, const device bfloat* scales, const device bfloat* biases, - threadgroup bfloat* tile, threadgroup float* sb, int tn, uint t, short2 home) { - threadgroup bfloat* mine = tile + (t / 2) * PAD + 32 * (t % 2); + threadgroup AM_T* tile, threadgroup float* sb, int tn, uint t, short2 home) { + threadgroup AM_T* mine = tile + (t / 2) * PAD + 32 * (t % 2); const int g_mine = TF_GROUP == 32 ? int(t % 2) : 0; // at g32 each thread of a pair takes one group's scale and bias #if TF_GROUP == 128 frag part[TM][2]; // a group's sums across its two steps @@ -367,8 +402,8 @@ inline bool am_tile(const device int32_t* offsets, int experts, int total, int t // A simdgroup's row starts: rows [row, row + rows) of x and its row sums, or with `order` sorted rows' token rows (order / topk). template -inline AmRows am_rows(const device bfloat* x, int ldx, const device float* xs, int ldxs, int row, int rows, int tm, - short2 home, const device int32_t* order, int topk) { +inline AmRows am_rows(const device AM_T* x, int ldx, const device float* xs, int ldxs, int row, int rows, int tm, + short2 home, const device int32_t* order, int topk, const device float* xa) { AmRows r; TF_UNROLL for (short m = 0; m < TM; m++) { @@ -379,6 +414,9 @@ inline AmRows am_rows(const device bfloat* x, int ldx, const device float* x const long src = order != nullptr ? long(order[at] / topk) : long(at); r.x[m][h] = x + src * ldx; r.s[m][h] = xs + src * ldxs; +#if defined(TF_I8) + r.a[m][h] = xa + src * ldxs * (TF_GROUP / TF_QG); +#endif } } return r; @@ -386,18 +424,18 @@ inline AmRows am_rows(const device bfloat* x, int ldx, const device float* x // Rows [row, row + rows) of x times weight rows [wrow0, wrow0 + 64) of a [*, K] matrix into y (ld N) at column col. template -inline void am_block(const device bfloat* x, int ldx, const device float* xs, int ldxs, int row, int rows, int K, +inline void am_block(const device AM_T* x, int ldx, const device float* xs, int ldxs, int row, int rows, int K, int ldy, int col, long wrow0, const device uint32_t* w, const device bfloat* scales, - const device bfloat* biases, device TF_OUT_T* y, threadgroup bfloat* tile, threadgroup float* sb, - uint sg, uint lane, const device int32_t* dst = nullptr, const device int32_t* order = nullptr, - int topk = 1) { + const device bfloat* biases, device TF_OUT_T* y, threadgroup AM_T* tile, threadgroup float* sb, + uint sg, uint lane, const device float* xa, const device int32_t* dst = nullptr, + const device int32_t* order = nullptr, int topk = 1) { constexpr int SM = BM / 2; constexpr int TM = SM / 16; const int t = int(sg) * 32 + int(lane); const int tm = SM * int(sg / 2), tn = 32 * int(sg % 2), live = clamp(rows - tm, 0, SM); const long wrow = wrow0 + t / 2; const short2 home = frag_home(ushort(lane)); - const AmRows starts = am_rows(x, ldx, xs, ldxs, row, rows, tm, home, order, topk); + const AmRows starts = am_rows(x, ldx, xs, ldxs, row, rows, tm, home, order, topk, xa); frag acc[TM][2]; am_k_loop(acc, starts, K, live, (const device uchar*)w + wrow * (K * TF_BITS / 8) + HALF_BYTES * (t % 2), scales + wrow * (K / TF_GROUP), biases + wrow * (K / TF_GROUP), tile, sb, tn, uint(t), home); @@ -409,34 +447,39 @@ inline void am_block(const device bfloat* x, int ldx, const device float* xs, in } // y [rows, n] = x [rows, k] W^T, n a multiple of 64: 64x64 tiles, a batch along tg.z (MmStrides). -[[kernel]] void tf_affine_mm(const device bfloat* X [[buffer(0)]], const device uint32_t* W [[buffer(1)]], +[[kernel]] void tf_affine_mm(const device AM_T* X [[buffer(0)]], const device uint32_t* W [[buffer(1)]], const device bfloat* S [[buffer(2)]], const device bfloat* B [[buffer(3)]], const device float* XS [[buffer(4)]], constant MmArgs& a [[buffer(5)]], - device TF_OUT_T* Y [[buffer(6)]], constant MmStrides& st [[buffer(7)]], + device TF_OUT_T* Y [[buffer(6)]], constant MmStrides& st [[buffer(7)]] AM_XA, uint sg [[simdgroup_index_in_threadgroup]], uint lane [[thread_index_in_simdgroup]], uint3 tg [[threadgroup_position_in_grid]]) { - threadgroup bfloat tile[64 * PAD]; + threadgroup AM_T tile[64 * PAD]; threadgroup float sb[NG * 128]; const int row = int(tg.y) * 64, col = int(tg.x) * 64, b = int(tg.z); am_block<64>(X + long(b) * st.x_batch, st.x_row, XS + long(b) * st.sums_batch * (a.k / TF_GROUP), st.sums_row * (a.k / TF_GROUP), row, min(64, a.rows - row), a.k, st.y_row, col, - long(b) * st.w_batch + col, W, S, B, Y + long(b) * st.y_batch, tile, sb, sg, lane); + long(b) * st.w_batch + col, W, S, B, Y + long(b) * st.y_batch, tile, sb, sg, lane, +#if defined(TF_I8) + XA + long(b) * st.sums_batch * (a.k / TF_GROUP)); +#else + nullptr); +#endif } #define TF_GATHER(BM) \ [[kernel]] void tf_affine_gather_##BM( \ - const device bfloat* X [[buffer(0)]], const device uint32_t* W [[buffer(1)]], \ + const device AM_T* X [[buffer(0)]], const device uint32_t* W [[buffer(1)]], \ const device bfloat* S [[buffer(2)]], const device bfloat* B [[buffer(3)]], \ const device float* XS [[buffer(4)]], constant MmArgs& a [[buffer(5)]], device TF_OUT_T* Y [[buffer(6)]], \ - const device int32_t* OFFS [[buffer(7)]], uint sg [[simdgroup_index_in_threadgroup]], \ + const device int32_t* OFFS [[buffer(7)]] AM_XA, uint sg [[simdgroup_index_in_threadgroup]], \ uint lane [[thread_index_in_simdgroup]], uint3 tg [[threadgroup_position_in_grid]]) { \ - threadgroup bfloat tile[64 * PAD]; \ + threadgroup AM_T tile[64 * PAD]; \ threadgroup float sb[NG * 128]; \ int expert, row, rows; \ if (!am_tile(OFFS, a.experts, a.rows, int(tg.y), lane, expert, row, rows)) return; \ const int col = int(tg.x) * 64; \ am_block(X, a.k, XS, a.k / TF_GROUP, row, rows, a.k, a.n, col, long(expert) * a.n + col, W, S, B, Y, \ - tile, sb, sg, lane); \ + tile, sb, sg, lane, AM_XA_ARG); \ } TF_GATHER(32) TF_GATHER(64) @@ -444,26 +487,33 @@ TF_GATHER(64) // The gathers with each sorted row's output put back at row DST[row] (e.g. the (row, slot) pairs' own order). #define TF_GATHER_SCATTER(BM) \ [[kernel]] void tf_affine_gather_scatter_##BM( \ - const device bfloat* X [[buffer(0)]], const device uint32_t* W [[buffer(1)]], \ + const device AM_T* X [[buffer(0)]], const device uint32_t* W [[buffer(1)]], \ const device bfloat* S [[buffer(2)]], const device bfloat* B [[buffer(3)]], \ const device float* XS [[buffer(4)]], constant MmArgs& a [[buffer(5)]], device TF_OUT_T* Y [[buffer(6)]], \ - const device int32_t* OFFS [[buffer(7)]], const device int32_t* DST [[buffer(8)]], \ + const device int32_t* OFFS [[buffer(7)]], const device int32_t* DST [[buffer(8)]] AM_XA, \ uint sg [[simdgroup_index_in_threadgroup]], uint lane [[thread_index_in_simdgroup]], \ uint3 tg [[threadgroup_position_in_grid]]) { \ - threadgroup bfloat tile[64 * PAD]; \ + threadgroup AM_T tile[64 * PAD]; \ threadgroup float sb[NG * 128]; \ int expert, row, rows; \ if (!am_tile(OFFS, a.experts, a.rows, int(tg.y), lane, expert, row, rows)) return; \ const int col = int(tg.x) * 64; \ am_block(X, a.k, XS, a.k / TF_GROUP, row, rows, a.k, a.n, col, long(expert) * a.n + col, W, S, B, Y, \ - tile, sb, sg, lane, DST); \ + tile, sb, sg, lane, AM_XA_ARG, DST); \ } TF_GATHER_SCATTER(32) TF_GATHER_SCATTER(64) -#ifdef TF_GLU_PLAIN +#if defined(TF_GLU_WEIGHTED) +// DeepSeek-V4.1's SwiGLU: bf16-rounded gate and up, w * silu(min(g, limit)) * clamp(u, +-limit) in fp32, rounded once. +inline bfloat am_swiglu(float g, float u, float limit, float w) { + const float gate = min(float(bfloat(g)), limit); + const float up = clamp(float(bfloat(u)), -limit, limit); + return bfloat(w * (gate / (1.0f + metal::precise::exp(-gate)) * up)); +} +#elif defined(TF_GLU_PLAIN) // mlx-lm's compiled SwiGLU on bf16 rows (LFM2): silu(g) * u, rounded to bf16 at each step; `limit` unused. -inline bfloat am_swiglu(float g, float u, float limit) { +inline bfloat am_swiglu(float g, float u, float limit, float) { const float gt = float(bfloat(g)); const bfloat s = static_cast(1.0f / (1.0f + metal::precise::exp(-gt))); const bfloat silu = static_cast(gt * float(s)); @@ -477,7 +527,7 @@ inline bfloat am_sigmoid(bfloat x) { return (x < 0) ? y : (bfloat(1) - y); } -inline bfloat am_swiglu(float g, float u, float limit) { +inline bfloat am_swiglu(float g, float u, float limit, float) { const float lim = float(bfloat(limit)); const bfloat gt = bfloat(metal::min(float(bfloat(g)), lim)); const bfloat up = bfloat(metal::min(metal::max(float(bfloat(u)), -lim), lim)); @@ -486,34 +536,47 @@ inline bfloat am_swiglu(float g, float u, float limit) { } #endif -// A simdgroup's gate (j 0) and up (j 1) fragments as SwiGLU outputs into y (ld N), rows below live only. +// Gate (j 0) and up (j 1) fragments as SwiGLU outputs into y (ld N), rows below live only; ws: rows' route weights. template inline void am_store_glu(thread const frag (&acc)[TM][2], device bfloat* y, int N, int live, short2 home, - float limit) { + float limit, const device float* ws) { TF_UNROLL for (short i = 0; i < TM; i++) { TF_UNROLL for (short e = 0; e < 8; e++) { const int r = 16 * i + home.y + (e >> 2) * 8; - if (r < live) y[long(r) * N + home.x + TF_COL(e)] = am_swiglu(acc[i][0][e], acc[i][1][e], limit); +#if defined(TF_GLU_WEIGHTED) + const float w = r < live ? ws[r] : 0.0f; +#else + const float w = 1.0f; +#endif + if (r < live) y[long(r) * N + home.x + TF_COL(e)] = am_swiglu(acc[i][0][e], acc[i][1][e], limit, w); } } } +#if defined(TF_GLU_WEIGHTED) +#define TF_GLU_WS , const device float *WS [[buffer(13)]] +#define TF_GLU_WS_AT(r) (WS + (r)) +#else +#define TF_GLU_WS +#define TF_GLU_WS_AT(r) nullptr +#endif + // The routed experts' gate and up over token rows read through ORDER (pair / topk), SwiGLU'd into act [rows, n]: 32 columns a tile. #define TF_GATHER_GLU(BM) \ [[kernel]] void tf_affine_gather_glu_##BM( \ - const device bfloat* X [[buffer(0)]], const device uint32_t* WG [[buffer(1)]], \ + const device AM_T* X [[buffer(0)]], const device uint32_t* WG [[buffer(1)]], \ const device bfloat* SG [[buffer(2)]], const device bfloat* BG [[buffer(3)]], \ const device float* XS [[buffer(4)]], constant MmArgs& a [[buffer(5)]], device bfloat* Y [[buffer(6)]], \ const device int32_t* OFFS [[buffer(7)]], const device int32_t* ORDER [[buffer(8)]], \ const device uint32_t* WU [[buffer(9)]], const device bfloat* SU [[buffer(10)]], \ - const device bfloat* BU [[buffer(11)]], constant float2& glu [[buffer(12)]], \ + const device bfloat* BU [[buffer(11)]], constant float2& glu [[buffer(12)]] TF_GLU_WS AM_XA, \ uint sg [[simdgroup_index_in_threadgroup]], uint lane [[thread_index_in_simdgroup]], \ uint3 tg [[threadgroup_position_in_grid]]) { \ constexpr int SM = BM / 2; \ constexpr int TM = SM / 16; \ - threadgroup bfloat tile[64 * PAD]; \ + threadgroup AM_T tile[64 * PAD]; \ threadgroup float sb[NG * 128]; \ int expert, row, rows; \ if (!am_tile(OFFS, a.experts, a.rows, int(tg.y), lane, expert, row, rows)) return; \ @@ -522,13 +585,14 @@ inline void am_store_glu(thread const frag (&acc)[TM][2], device bfloat* const long wrow = long(expert) * a.n + c0 + (tr >> 5) * 16 + (tr & 15); \ const int tm = SM * int(sg / 2), tn = 32 * int(sg % 2), live = clamp(rows - tm, 0, SM); \ const short2 home = frag_home(ushort(lane)); \ - const AmRows starts = am_rows(X, a.k, XS, a.k / TF_GROUP, row, rows, tm, home, ORDER, int(glu.x)); \ + const AmRows starts = am_rows(X, a.k, XS, a.k / TF_GROUP, row, rows, tm, home, ORDER, int(glu.x), \ + AM_XA_ARG); \ frag acc[TM][2]; \ am_k_loop(acc, starts, a.k, live, \ (const device uchar*)(up ? WU : WG) + wrow * (a.k * TF_BITS / 8) + HALF_BYTES * (t % 2), \ (up ? SU : SG) + wrow * (a.k / TF_GROUP), (up ? BU : BG) + wrow * (a.k / TF_GROUP), tile, sb, tn, \ uint(t), home); \ - am_store_glu(acc, Y + long(row + tm) * a.n + c0 + tn / 2, a.n, live, home, glu.y); \ + am_store_glu(acc, Y + long(row + tm) * a.n + c0 + tn / 2, a.n, live, home, glu.y, TF_GLU_WS_AT(row + tm)); \ } TF_GATHER_GLU(32) TF_GATHER_GLU(64) diff --git a/zig/kernels/metal/core/affine_mm_i8.h b/zig/kernels/metal/core/affine_mm_i8.h new file mode 100644 index 00000000000..0297269b17f --- /dev/null +++ b/zig/kernels/metal/core/affine_mm_i8.h @@ -0,0 +1,125 @@ +// Ported whole from BobClawblaw/TensorFold, branch deepseek-v41-main, commit 72a552ed +// ("deepseek_v41: prompt chunks' routed experts in int8 x int8"), Apache-2.0; see THIRD_PARTY_NOTICES.md. +// Unmodified below except for this header. The rest of the file is the sibling's own, so its fragment +// layout and epilogue are the compiled code that carries their KL receipt. +// int8 forms of affine_mm.metal's tile pieces (TF_I8), inlined there below AmRows: x and the codes as int8, int32 sums. + +// The codes as int8 into the tile row (q - 128 at 8 bits): code i of the little-endian bit stream at byte i. +inline void am_codes(thread const Codes& c, threadgroup int8_t* out) { + threadgroup uint* o = (threadgroup uint*)out; +#if TF_BITS == 2 + TF_UNROLL + for (short i = 0; i < 2; i++) { // byte j of a word holds codes 4j..4j+3, two bits each from the low end + const uint w = c.v[i]; + TF_UNROLL + for (short j = 0; j < 4; j++) { + const uint b = (w >> (8 * j)) & 0xffu; + o[4 * i + j] = (b & 3u) | (((b >> 2) & 3u) << 8) | (((b >> 4) & 3u) << 16) | ((b >> 6) << 24); + } + } +#elif TF_BITS == 8 + TF_UNROLL + for (short i = 0; i < 8; i++) o[i] = c.v[i / 4][i % 4] ^ 0x80808080u; // q - 128 as int8: the top bit flipped +#elif TF_BITS == 4 + TF_UNROLL + for (short i = 0; i < 4; i++) { + const uint w = c.v[0][i]; + const uint lo = w & 0x0f0f0f0fu, hi = (w >> 4) & 0x0f0f0f0fu; // byte j: codes 2j (low nibble) and 2j + 1 + o[2 * i] = (lo & 0xffu) | ((hi & 0xffu) << 8) | (((lo >> 8) & 0xffu) << 16) | (((hi >> 8) & 0xffu) << 24); + o[2 * i + 1] = ((lo >> 16) & 0xffu) | (((hi >> 16) & 0xffu) << 8) | ((lo >> 24) << 16) | ((hi >> 24) << 24); + } +#else + TF_UNROLL + for (short i = 0; i < 8; i++) { + uint packed = 0; + TF_UNROLL + for (short j = 0; j < 4; j++) { + const short at = TF_BITS * (4 * i + j), word = at / 32, shift = at % 32; + uint v = c.v[word] >> shift; + if (shift + TF_BITS > 32) v |= c.v[word + 1] << (32 - shift); + packed |= (v & ((1u << TF_BITS) - 1u)) << (8 * j); + } + o[i] = packed; + } +#endif +} + +// A block of the int8 code tile as the transposed right operand (PAD rows, 16-column blocks). +inline void am_tile_frag(thread frag& f, const threadgroup int8_t* p, int ld, int r, int c, short2 home) { + const threadgroup int8_t* q = p + (r + home.y) * ld + (c + home.x); + const char4 v0 = *(const threadgroup char4*)q, v1 = *(const threadgroup char4*)(q + 8 * ld); + f = frag(v0.x, v0.y, v0.z, v0.w, v1.x, v1.y, v1.z, v1.w); +} + +// The fragment of x at column c from a lane's two row starts, int8. +inline frag am_frag(const device int8_t* r0, const device int8_t* r1, int c, short2 home) { + const char4 v0 = *(const device char4*)(r0 + c + home.x), v1 = *(const device char4*)(r1 + c + home.x); + return frag(v0.x, v0.y, v0.z, v0.w, v1.x, v1.y, v1.z, v1.w); +} + +// am_step in int8: each TF_QG columns' int32 sums scaled by the weights' and x's scales; at a group's end its bias. +template +inline void am_step(thread frag (&acc)[TM][2], thread const AmRows& rows, int k, + const threadgroup AM_T* tile, const threadgroup float* sb, int tn, short2 home) { + frag part[TL][2]; + TF_UNROLL + for (short q = 0; q < 4; q++) { // the step's four 16-deep slices, every row fragment's chain interleaved + frag b0, b1, a[TL]; + am_tile_frag(b0, tile, PAD, tn, 16 * q, home); + am_tile_frag(b1, tile, PAD, tn + 16, 16 * q, home); + TF_UNROLL + for (short m = 0; m < TL; m++) { + a[m] = am_frag(rows.x[m][0], rows.x[m][1], k + 16 * q, home); + } + TF_UNROLL + for (short m = 0; m < TL; m++) { + if (q % (TF_QG / 16) == 0) { + am_first(part[m][0], part[m][1], a[m], b0, b1); + } else { + mma_16x32(part[m][0], part[m][1], a[m], b0, b1); + } + } + if ((q + 1) % (TF_QG / 16) == 0) { // a scale's columns done: weight scale times x's scale; at a group's end its bias + const int g = q / (TF_GROUP / 16), h = q / (TF_QG / 16); + const bool ends = (q + 1) % (TF_GROUP / 16) == 0; + const threadgroup float* sg = sb + g * 128; + TF_UNROLL + for (short m = 0; m < TL; m++) { + const float xa0 = rows.a[m][0][k / TF_QG + h], xa1 = rows.a[m][1][k / TF_QG + h]; + const float xr0 = ends ? rows.s[m][0][k / TF_GROUP + g] : 0.0f, xr1 = ends ? rows.s[m][1][k / TF_GROUP + g] : 0.0f; + TF_UNROLL + for (short j = 0; j < 2; j++) { + TF_UNROLL + for (short c = 0; c < 4; c++) { + const int col = tn + 16 * j + home.x + TF_COL(c); + const float s = sg[col], b = ends ? sg[64 + col] : 0.0f; + acc[m][j][c] += s * (xa0 * float(part[m][j][c])) + b * xr0; + acc[m][j][4 + c] += s * (xa1 * float(part[m][j][4 + c])) + b * xr1; + } + } + } + } + } +} + +// The row sums, and x as int8 (XQ [rows, k]) with each scale (XA, max |x| / 127): x ~ a * q, q rounded to nearest. +[[kernel]] void tf_affine_row_sums(const device bfloat* X [[buffer(0)]], constant MmArgs& a [[buffer(5)]], + device float* XS [[buffer(6)]], device int8_t* XQ [[buffer(7)]], + device float* XA [[buffer(8)]], uint2 gid [[thread_position_in_grid]]) { + const int g = int(gid.x), r = int(gid.y), groups = a.k / TF_GROUP; + if (g >= groups || r >= a.rows) return; + const device bfloat* x = X + long(r) * (a.n > 0 ? a.n : a.k) + g * TF_GROUP; + float sum = 0.0f; + for (int i = 0; i < TF_GROUP; i++) { + sum += float(x[i]); + } + XS[long(r) * groups + g] = sum; + for (int h = 0; h < TF_GROUP / TF_QG; h++) { + float top = 0.0f; + for (int i = TF_QG * h; i < TF_QG * (h + 1); i++) top = max(top, fabs(float(x[i]))); + const float inv = top > 0.0f ? 127.0f / top : 0.0f; + device int8_t* q = XQ + long(r) * a.k + g * TF_GROUP; + for (int i = TF_QG * h; i < TF_QG * (h + 1); i++) q[i] = int8_t(clamp(rint(float(x[i]) * inv), -127.0f, 127.0f)); + XA[(long(r) * groups + g) * (TF_GROUP / TF_QG) + h] = top / 127.0f; + } +} diff --git a/zig/kernels/metal/core/exl3_projection.metal b/zig/kernels/metal/core/exl3_projection.metal index 0eca0d80c57..cb7a89d9e3b 100644 --- a/zig/kernels/metal/core/exl3_projection.metal +++ b/zig/kernels/metal/core/exl3_projection.metal @@ -6,8 +6,9 @@ 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; + uint pair; }; // Metal 3 / argument-buffer tier 2 descriptors are populated once from resident buffers' GPU addresses. @@ -37,11 +38,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))); } @@ -87,13 +90,18 @@ 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: the dispatch needs four times fewer + // threadgroups, and at a prompt chunk these passes were a million threadgroups a layer. 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,14 +112,69 @@ 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 +// (built from format.codebookValue, the format's own decoder, and qualified entry-for-entry by +// tf_exl3_codebook_check). Bit-identical by construction; this arm only moves the work from ALU to a load. +inline half tf_exl3_table_value(const device half* table, uint codebook, ushort state) { + return table[codebook * 65536u + uint(state)]; +} + +// ROUND-338: the mul1 value depends only on the state's byte sum, so the 65,536-entry table holds 1,024 +// distinct values and a threadgroup can hold them all. The structure is mlx-serve's prefill kernel's +// (dig_lut_fill, MIT/Apache-2.0, NOTICE per-file): the table is filled once a threadgroup and the decode +// reads it in place of the 384 KB resident table's load. +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 (the +1024 bias +// rides in the mantissa, exactly as the format's own decoder puts it). +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))))); +} + +// ROUND-338: the lane's eight windows at compile-time shifts. C_cur is the 32-bit window at the lane's first +// state (its bit 31 is that window's first stream bit) and C_next the window 32 bits later; S is the states' +// stride in bits (halves / 2) and J the state's index, so every shift below folds at compile time. The +// structure is the comparator's (mlx-serve's dsv41_exl3_mul1h_k3 decode kernel, MIT/Apache-2.0, NOTICE +// per-file): one funnel shift a block, then the windows at fixed 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), so a verify + // window's row keeps the solo order instead of collapsing to row 0. + const uint rb = a.splits > 1 ? 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; const device uchar* data = a.indexed ? descriptors[id].trellis : trellis; @@ -120,25 +183,82 @@ inline void tf_exl3_matmul_impl(const device half* x, const device uchar* trelli 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, + // the shift each window needs and its threadgroup slot all depend only on the lane, so they live in registers. + 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 + 32 * j, ring = 128 * halves; + 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, 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 +270,18 @@ 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; + // FP16 products are exact in FP32; the compensation TwoSum keeps is measured against the canon hashes. + 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 +291,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 +305,27 @@ 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). Same k order, +// same FP32 sums and the same FP16 values as tf_exl3_value, so its output is bit-identical. +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. @@ -207,10 +343,16 @@ 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; + // ROUND-394: an indexed batch may carry entries of different output width (descriptor.reserved, 0 = the + // call's n). The entry's own width bounds the columns this row writes; single-width tables are unchanged. + 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; @@ -229,6 +371,117 @@ kernel void tf_exl3_rotate_out(const device float* sums [[buffer(0)]], } } +// ROUND-520: the pre-rotated int8 pack's epilogue. The byte body leaves f32 sums; the rotated pack has no +// Hadamard/svh left to apply, so this is one cast into the caller's bf16 output at its own row stride. +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]); +} + +// ROUND-395: THE ONE-ROW TRANSFORM FOLD -- the projection's output transform, the RMS norm and the next +// projection's input transform in ONE dispatch (the chain wq_a -> q_norm -> wq_b). ROUND-360 section 3 designed +// it and section 3b named the blocker: the butterfly's lane layout (a lane holds lane+32j) against this +// family's STRIDED norm (thread t holds t, t+256, ...). Here the row goes through threadgroup memory, so the +// permutation is a shared-memory write/read, not a shuffle. The arithmetic is the three shipped kernels' own: +// rotate_out: v = sums[..]; hadamard(v); out = (v * 0.08838834764831845) * sv; +bias; bfloat(out) +// dsv41_rms: s = sum over i = t, t+256, ... of bf(x)^2; simd_sum; the eight simdgroups' partials; +// rsqrt(total / width + eps); y = rb((bf(x) * inv) * bf(w)) +// rotate_in: v = bf(normed) * su; hadamard(v); half(v * 0.08838834764831845) +// so every value is the shipped value. The merged wq_a+wkv sums carry two rows of different width (1280, 512): +// threadgroup 1 does wkv's output transform alone and writes raw. +struct TfExl3NormTransform { + uint n0, n1, k_next; + uint su_signs, sv_signs0, sv_signs1; + float eps; +}; + +// BF16 bits to float (the ops kernel's bf()). +inline float tf_exl3_nt_bf(ushort x) { return as_type(uint(x) << 16); } + +// The norm's own round-to-bfloat16 (ops.metal's rb, RNE with the NaN passthrough). +inline ushort tf_exl3_nt_rb(float x) { + uint u = as_type(x); + if ((u & 0x7fffffffu) > 0x7f800000u) return ushort((u >> 16) | 0x40u); + return ushort((u + 0x7fffu + ((u >> 16) & 1u)) >> 16); +} + +kernel void tf_exl3_norm_transform(const device float* sums [[buffer(0)]], + const device ushort* sv0 [[buffer(1)]], + const device ushort* sv1 [[buffer(2)]], + const device ushort* weight [[buffer(3)]], + const device ushort* su_next [[buffer(4)]], + device ushort* qr [[buffer(5)]], + device ushort* raw [[buffer(6)]], + device half* rotated [[buffer(7)]], + constant TfExl3NormTransform& a [[buffer(8)]], + uint r [[threadgroup_position_in_grid]], + uint t [[thread_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]], + uint sg [[simdgroup_index_in_threadgroup]]) { + threadgroup ushort sh[1280]; + threadgroup float psum[8]; + threadgroup float inv[1]; + const uint n = r == 0 ? a.n0 : a.n1; + if (r == 0) { + // The wq_a output transform: 1280 = ten 128-blocks, one block a simdgroup. + for (uint blk = sg; blk * 128 < n; blk += 8) { + float v[4]; + for (uint j = 0; j < 4; ++j) v[j] = sums[blk * 128 + lane + 32 * j]; + tf_exl3_hadamard(v, lane); + for (uint j = 0; j < 4; ++j) { + const uint idx = blk * 128 + lane + 32 * j; + const float out = (v[j] * 0.08838834764831845f) * tf_exl3_scale(sv0, idx, a.sv_signs0); + sh[idx] = as_type(bfloat(out)); + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + // The q_norm: dsv41_rms's own strided partition and order. + float s = 0.0f; + for (uint i = t; i < n; i += 256) { const float x = tf_exl3_nt_bf(sh[i]); s += x * x; } + s = simd_sum(s); + if (lane == 0) psum[sg] = s; + threadgroup_barrier(mem_flags::mem_threadgroup); + if (sg == 0) { + const float total = simd_sum(lane < 8 ? psum[lane] : 0.0f); + if (lane == 0) inv[0] = rsqrt(total * (1.0f / float(n)) + a.eps); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + for (uint i = t; i < n; i += 256) { + const ushort bits = tf_exl3_nt_rb((tf_exl3_nt_bf(sh[i]) * inv[0]) * tf_exl3_nt_bf(weight[i])); + sh[i] = bits; + qr[i] = bits; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + // wq_b's input transform: the normalized row, one 128-block a simdgroup, f16 into the scratch. + for (uint blk = sg; blk * 128 < a.k_next; blk += 8) { + float v[4]; + for (uint j = 0; j < 4; ++j) { + const uint idx = blk * 128 + lane + 32 * j; + v[j] = tf_exl3_nt_bf(sh[idx]) * tf_exl3_scale(su_next, idx, a.su_signs); + } + tf_exl3_hadamard(v, lane); + for (uint j = 0; j < 4; ++j) + rotated[blk * 128 + lane + 32 * j] = half(v[j] * 0.08838834764831845f); + } + } else { + // wkv's output transform alone: 512 = four 128-blocks. + for (uint blk = sg; blk * 128 < n; blk += 8) { + float v[4]; + for (uint j = 0; j < 4; ++j) v[j] = sums[a.n0 + blk * 128 + lane + 32 * j]; + tf_exl3_hadamard(v, lane); + for (uint j = 0; j < 4; ++j) { + const uint idx = blk * 128 + lane + 32 * j; + const float out = (v[j] * 0.08838834764831845f) * tf_exl3_scale(sv1, idx, a.sv_signs1); + raw[idx] = as_type(bfloat(out)); + } + } + } +} + // 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 +494,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,6 +515,7 @@ 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]]) { @@ -300,3 +568,1064 @@ 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; +} + + +// ------------------------------------------------------------------------------------------------ +// SwiGLU + the down projection's rotate_in, fused (TF_DSV41_SWIGLU_ROT; default off until its differential and +// the canons are green). Ported mechanism: mlx-serve's q3_prefill_dig2_swiglu_2304_x writes the down projection's +// rotated input in its SwiGLU pass instead of a separate rotate (src/sdk/quant/exl3/stream/kernels/exl3/, +// MIT/Apache-2.0; attribution required). The arithmetic here is ours: the same bf16 round of silu(gate)*up, the +// same per-expert su scale and the same 128-point Sylvester rotation tf_exl3_rotate_in applies, so a row's +// rotated bits are the two-pass path's bits. Each SIMDgroup owns one 128-element block of one row, and the row +// is written to the destination slot its expert tile occupies. +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); +} + +// Wide one-row / narrow-window tile: eight SIMDgroups each own one 16-column tile of the same 128-column group, +// so a threadgroup reads eight contiguous n tiles of a k block, and the shared activation tile is double +// buffered, so a block costs one threadgroup barrier instead of two. Each SIMDgroup runs the same decode, the +// same 16-product FP32 sum and the same k order as tf_exl3_matmul_tab, so the output is bit-identical. +// Bench arm for ROUND-323's one-row tile geometry; not dispatched by the engine yet. +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, + threadgroup half* lut = nullptr) { + 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. The other seven warps + // decode their weight tiles while it runs, so the load's latency is covered by work, not a second barrier. + 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]] = Decode ? (Lut ? lut[tf_exl3_mul1_index(s)] + : (Table ? tf_exl3_table_value(table, codebook, s) : tf_exl3_value(s, codebook))) + : half(0.5f + float((lane + j) & 7u)); + } + } 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] = Decode ? (Lut ? lut[tf_exl3_mul1_index(state)] + : (Table ? tf_exl3_table_value(table, codebook, state) : tf_exl3_value(state, codebook))) + : half(0.5f + float((lane + j) & 7u)); + } + 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]; + } + } +} + +kernel void tf_exl3_matmul_wide_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]], + uint sg [[simdgroup_index_in_threadgroup]], + uint3 tg [[threadgroup_position_in_grid]]) { + threadgroup half wx[8 * 256]; + threadgroup float xx[2 * 128]; + tf_exl3_matmul_wide_impl(x, trellis, sums, a, routes, descriptors, partials, table, lane, sg, tg, wx, xx); +} + +// ROUND-338: the wide one-row body with the static state selection -- the comparator's structure (mlx-serve's +// dsv41_exl3_mul1h_k3 decode kernel, MIT/Apache-2.0, NOTICE per-file). The shipped body picks each state's +// word pair and bit offset at run time (the `rel[k]` cursor the record named as one of the body's two bounds); +// here one funnel shift a block puts the lane's window at a known place and the eight windows then sit at +// compile-time shifts, so the cursor leaves the inner loop and the lane reads three stream words, not four. +// The tile, the activation load, the 16-product FP32 sums and the k order are the shipped body's, so the output +// is bit-identical. S is the states' stride in bits (halves / 2) and must satisfy 7*S + 16 <= 64. +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, const device half* table, + 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 (its bit 31 is that window's + // first stream bit) and C_next the window 32 bits later. + 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 ? lut[tf_exl3_mul1_index(TF_EXL3_W(J))] : tf_exl3_table_value(table, codebook, 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]; + } + } +} + +// ROUND-338 bench arm: the static state selection with the codebook read from the resident table. +kernel void tf_exl3_matmul_wide_static_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]], + uint sg [[simdgroup_index_in_threadgroup]], + uint3 tg [[threadgroup_position_in_grid]]) { + threadgroup half wx[8 * 256]; + threadgroup float xx[2 * 128]; + if (a.halves == 12u) + tf_exl3_matmul_wide_static_impl(x, trellis, sums, a, routes, descriptors, partials, table, lane, sg, tg, wx, xx, nullptr); + else if (a.halves == 10u) + tf_exl3_matmul_wide_static_impl(x, trellis, sums, a, routes, descriptors, partials, table, lane, sg, tg, wx, xx, nullptr); + else if (a.halves == 6u) + tf_exl3_matmul_wide_static_impl(x, trellis, sums, a, routes, descriptors, partials, table, lane, sg, tg, wx, xx, nullptr); + else + // A width the static selection is not specialised for: the shipped body, which reads the states the same way. + tf_exl3_matmul_wide_impl(x, trellis, sums, a, routes, descriptors, partials, table, lane, sg, tg, wx, xx); +} + +// ROUND-338 bench arm: the static state selection with the codebook read from a 1024-entry threadgroup LUT. +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), so it is only the right + // table for that codebook; any other reads the resident table, and any width the static selection is not + // specialised for reads the shipped body's states. + 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(x, trellis, sums, a, routes, descriptors, partials, table, lane, sg, tg, wx, xx, lut); + else if (a.halves == 10u) + tf_exl3_matmul_wide_static_impl(x, trellis, sums, a, routes, descriptors, partials, table, lane, sg, tg, wx, xx, lut); + else if (a.halves == 6u) + tf_exl3_matmul_wide_static_impl(x, trellis, sums, a, routes, descriptors, partials, table, 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); +} + +// ROUND-339: the static one-row body with a deeper weight prefetch (PF blocks of stream words in flight a +// lane). The shipped body issues the next block's three stream words at the top of the current block, so a +// block's DRAM latency is hidden by one block's compute only. The narrow one-row shapes (n = 2304, 1280, 512 +// -- the shared expert's gate/up and the attention's wq_a) have one wave of threadgroups and nothing else to +// hide it with: the bench reads them at 70-240 GB/s against the box's 1,120 GB/s. The prefetch ring below +// keeps PF blocks of stream words in registers, so PF blocks' loads are in flight at once. Same states, same +// codebook values, same products, same k order, same partials: bit-identical. +template +inline void tf_exl3_matmul_wide_static_pf_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, + 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; + uint a1 = wi0 + 1; if (a1 >= words) a1 -= words; + uint a2 = wi0 + 2; if (a2 >= words) a2 -= words; + const uint sh0 = (32u - off0) & 31u; + const uint m0 = 0u - uint(off0 != 0u); + // The prefetch ring: PF blocks of three stream words a lane, in registers (PF a compile-time constant, so + // the array never lands in thread-local memory). + uint pf[PF][3]; + TF_UNROLL + for (uint p = 0; p < PF; ++p) { + if (b0 + p < b1) { + const device ushort* t = reinterpret_cast(data + ulong(b0 + p) * ks + ulong(nb / 16) * ns); + pf[p][0] = tf_exl3_word(t, wi0); + pf[p][1] = tf_exl3_word(t, a1); + pf[p][2] = tf_exl3_word(t, a2); + } + } + uint b = b0; + const uint main_end = b0 + ((b1 - b0) / PF) * PF; + while (b < main_end) { + TF_UNROLL + for (uint p = 0; p < PF; ++p) { + const uint blk = b + p; + threadgroup float* xx = xx_all + ((blk - 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 + blk * 16 + j % 16]) : 0.0f; + } + } + const uint w0 = pf[p][0], w1 = pf[p][1], w2 = pf[p][2]; + // The next PF blocks' words, issued now: PF loads in flight a lane instead of one. + if (blk + PF < b1) { + const device ushort* tn = reinterpret_cast(data + ulong(blk + PF) * ks + ulong(nb / 16) * ns); + pf[p][0] = tf_exl3_word(tn, wi0); + pf[p][1] = tf_exl3_word(tn, a1); + pf[p][2] = tf_exl3_word(tn, a2); + } + 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 ? lut[tf_exl3_mul1_index(TF_EXL3_W(J))] : tf_exl3_table_value(table, codebook, 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]); + } + } + b += PF; + } + // The tail: the blocks the pipelined loop did not cover (fewer than PF). + for (; 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 device ushort* t = reinterpret_cast(data + ulong(b) * ks + ulong(nb / 16) * ns); + const uint w0 = tf_exl3_word(t, wi0), w1 = tf_exl3_word(t, a1), w2 = tf_exl3_word(t, a2); + 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 ? lut[tf_exl3_mul1_index(TF_EXL3_W(J))] : tf_exl3_table_value(table, codebook, 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]; + } + } +} + +// ROUND-339 bench arm: the static one-row body with the codebook LUT and a two-block prefetch. +kernel void tf_exl3_matmul_wide_static_lut_pf2(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]; + 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_pf_impl(x, trellis, sums, a, routes, descriptors, partials, table, lane, sg, tg, wx, xx, lut); + else if (a.halves == 10u) + tf_exl3_matmul_wide_static_pf_impl(x, trellis, sums, a, routes, descriptors, partials, table, lane, sg, tg, wx, xx, lut); + else if (a.halves == 6u) + tf_exl3_matmul_wide_static_pf_impl(x, trellis, sums, a, routes, descriptors, partials, table, 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); +} + +// ROUND-339 bench arm: the static one-row body with the codebook LUT and a four-block prefetch. +kernel void tf_exl3_matmul_wide_static_lut_pf4(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]; + 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_pf_impl(x, trellis, sums, a, routes, descriptors, partials, table, lane, sg, tg, wx, xx, lut); + else if (a.halves == 10u) + tf_exl3_matmul_wide_static_pf_impl(x, trellis, sums, a, routes, descriptors, partials, table, lane, sg, tg, wx, xx, lut); + else if (a.halves == 6u) + tf_exl3_matmul_wide_static_pf_impl(x, trellis, sums, a, routes, descriptors, partials, table, 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); +} + +// ROUND-338 bench arm: the shipped dynamic selection with the codebook read from a 1024-entry threadgroup LUT. +// The separation experiment's fourth cell: the table load removed, the cursor left in. +kernel void tf_exl3_matmul_wide_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]; + for (uint b = sg * 32u + lane; b < 1024u; b += 256u) lut[b] = tf_exl3_mul1_value(b); + threadgroup_barrier(mem_flags::mem_threadgroup); + tf_exl3_matmul_wide_impl(x, trellis, sums, a, routes, descriptors, partials, table, lane, sg, tg, wx, xx, lut); +} + +// Diagnostic arm (ROUND-327): the wide body with the trellis load and the codebook value removed, so the difference +// against tf_exl3_matmul_wide_tab prices the decode (loads + bit extraction + table read) in the dispatch. Values +// are meaningless; timing only. +kernel void tf_exl3_matmul_wide_noload_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]], + uint sg [[simdgroup_index_in_threadgroup]], + uint3 tg [[threadgroup_position_in_grid]]) { + threadgroup half wx[8 * 256]; + threadgroup float xx[2 * 128]; + tf_exl3_matmul_wide_impl(x, trellis, sums, a, routes, descriptors, partials, table, lane, sg, tg, wx, xx); +} + +// 32-k continuation of the wide one-row tile (ROUND-327): eight SIMDgroups own 128 columns, and each block decodes +// two consecutive 16-k tiles before one barrier, so the barrier count halves and a threadgroup reads 1.5 KB of +// contiguous trellis a block. Each 16-k tile is decoded exactly as tf_exl3_matmul_wide_tab decodes it (same maps, +// same table value) and the accumulation still ascends k in order, so the output is bit-identical by construction. +inline void tf_exl3_wide2_decode16(const device ushort* tile, uint wi0, uint a1, uint a2, uint a3, + threadgroup half* dst, + const thread uint* at, const thread uint* off, const thread uint* sh, + const thread uint* rel, const thread uint* maps, uint lane, + const device half* table, uint codebook, bool table_on, bool fast) { + if (fast) { + const uint w0 = tf_exl3_word(tile, wi0), w1 = tf_exl3_word(tile, a1); + const uint w2 = tf_exl3_word(tile, a2), w3 = tf_exl3_word(tile, a3); + 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); + dst[at[j]] = table_on ? 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 s = tf_exl3_mapped_state(tile, maps[j]); + dst[r * 16 + c] = table_on ? tf_exl3_table_value(table, codebook, s) : tf_exl3_value(s, codebook); + } + } +} + +template +inline void tf_exl3_matmul_wide2_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 * 512; + 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}; + 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; + const bool fast = (halves & 1u) == 0 and halves <= 16; + const uint a1 = wi0 + 1 < words ? wi0 + 1 : wi0 + 1 - words; + const uint a2 = wi0 + 2 < words ? wi0 + 2 : wi0 + 2 - words; + const uint a3 = wi0 + 3 < words ? wi0 + 3 : wi0 + 3 - words; + uint b = b0; + for (; b + 1 < b1; b += 2) { + threadgroup float* xx = xx_all + (((b - b0) >> 1) & 1u) * 256; + // One warp loads the 8-row x 32-k activation tile for all eight; zeros past a.rows. + if (sg == 0) { + for (uint j = lane; j < 256; j += 32) { + const uint row = rb + j / 32; + const uint kk = b * 16 + j % 32; + xx[j] = (kk < a.k and tf_exl3_active(routes, a, row)) ? float(x[ulong(row) * a.k + kk]) : 0.0f; + } + } + const device ushort* tileA = reinterpret_cast(data + ulong(b) * ks + ulong(nb / 16) * ns); + const device ushort* tileB = reinterpret_cast(data + ulong(b + 1) * ks + ulong(nb / 16) * ns); + tf_exl3_wide2_decode16(tileA, wi0, a1, a2, a3, wx, at, off, sh, rel, maps, lane, table, codebook, Table, fast); + tf_exl3_wide2_decode16(tileB, wi0, a1, a2, a3, wx + 256, at, off, sh, rel, maps, lane, table, codebook, Table, fast); + 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 < 32; ++k) high[i] += xx[(at_i / 16) * 32 + k] * float(wx[k * 16 + col]); + } + } + if (b < b1) { + threadgroup float* xx = xx_all + (((b - b0) >> 1) & 1u) * 256; + if (sg == 0) { + for (uint j = lane; j < 128; j += 32) { + const uint row = rb + j / 16; + xx[(j / 16) * 32 + j % 16] = tf_exl3_active(routes, a, row) ? float(x[ulong(row) * a.k + b * 16 + j % 16]) : 0.0f; + } + } + const device ushort* tileA = reinterpret_cast(data + ulong(b) * ks + ulong(nb / 16) * ns); + tf_exl3_wide2_decode16(tileA, wi0, a1, a2, a3, wx, at, off, sh, rel, maps, lane, table, codebook, Table, fast); + 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) * 32 + 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]; + else sums[ulong(row) * a.n + nb + at_i % 16] = high[i]; + } + } +} + +kernel void tf_exl3_matmul_wide2_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]], + uint sg [[simdgroup_index_in_threadgroup]], + uint3 tg [[threadgroup_position_in_grid]]) { + threadgroup half wx[8 * 512]; + threadgroup float xx[2 * 256]; + tf_exl3_matmul_wide2_impl(x, trellis, sums, a, routes, descriptors, partials, table, lane, sg, tg, wx, xx); +} + +// Direct-register one-row decode (ROUND-327): a lane owns one output column, decodes that column's 16 states for +// a 16-k block into registers (eight stream words; the window is sized for halves <= 14), reads the codebook table and +// accumulates ascending k. No threadgroup weight tile, no barrier, no shared round trip; a warp covers 32 columns. +// The k order, the table entry and the FP32 FMA sequence are the wide body's, so the one-row output is +// bit-identical by construction (halves = 6, the shipped pack; guarded on that in the caller). +kernel void tf_exl3_matmul_direct_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]], + uint sg [[simdgroup_index_in_threadgroup]], + uint3 tptg [[threads_per_threadgroup]], + uint3 tg [[threadgroup_position_in_grid]]) { + const uint split = a.splits > 1 ? tg.y : 0; + const uint span = tptg.x; + const uint nb = tg.x * span + sg * 32 + lane; + if (nb >= a.n) 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; + const uint words = 4 * halves; + const uint c = lane & 15u; + // The tile state of (k, c): p = base + 8*(k/2) + (k&1) - 30*(k/8), from the wide body's at[] map. + const uint base = 32u * (c % 8u) + 4u * (c / 8u); + uint rel[16], off[16], wnext[8]; + uint wbase = 0; +#if defined(TF_DIRECT_NW) + uint maxrel = 0; +#endif + for (uint k = 0; k < 16; ++k) { + const uint p = base + 8u * (k >> 1) + (k & 1u) - 30u * ((k >> 3) & 1u); + const uint map = tf_exl3_map_of(p, halves); + const uint wi = map & 63u; + if (k == 0) wbase = wi; + rel[k] = (wi + words - wbase) % words; +#if defined(TF_DIRECT_NW) + maxrel = max(maxrel, rel[k]); +#endif + off[k] = (map >> 6) & 31u; + } + for (uint i = 0; i < 8; ++i) wnext[i] = (wbase + i) % words; +#if defined(TF_DIRECT_NW) + // ROUND-335: the sixteen states of a column span 27 ring positions; at halves = 10 the union is six words + // (max(rel) = 4), at halves = 12 seven (max(rel) = 5), at halves = 6 five. The body's eight-word load is two + // or three words more than the `rel[k] + 1` access ever reaches; load only what the map names. + const uint nw = min(maxrel + 2u, words); +#endif + float high = 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; + for (uint b = b0; b < b1; ++b) { + const device ushort* tile = reinterpret_cast(data + ulong(b) * ks + ulong(nb / 16) * ns); + uint w[8]; +#if defined(TF_DIRECT_NW) + switch (nw) { + case 3: { TF_UNROLL for (uint i = 0; i < 3; ++i) w[i] = tf_exl3_word(tile, wnext[i]); break; } + case 4: { TF_UNROLL for (uint i = 0; i < 4; ++i) w[i] = tf_exl3_word(tile, wnext[i]); break; } + case 5: { TF_UNROLL for (uint i = 0; i < 5; ++i) w[i] = tf_exl3_word(tile, wnext[i]); break; } + case 6: { TF_UNROLL for (uint i = 0; i < 6; ++i) w[i] = tf_exl3_word(tile, wnext[i]); break; } + case 7: { TF_UNROLL for (uint i = 0; i < 7; ++i) w[i] = tf_exl3_word(tile, wnext[i]); break; } + default: { TF_UNROLL for (uint i = 0; i < 8; ++i) w[i] = tf_exl3_word(tile, wnext[i]); break; } + } +#else + TF_UNROLL + for (uint i = 0; i < 8; ++i) w[i] = tf_exl3_word(tile, wnext[i]); +#endif + TF_UNROLL + for (uint k = 0; k < 16; ++k) { + const uint lo = w[rel[k]], hi = w[rel[k] + 1]; + const uint carry = (hi >> ((32u - off[k]) & 31u)) & (0u - uint(off[k] != 0)); + const ushort s = ushort(((lo << off[k]) | carry) >> 16); + high += float(x[ulong(b) * 16 + k]) * float(tf_exl3_table_value(table, codebook, s)); + } + } + if (a.splits > 1) partials[ulong(split) * a.rows * a.n + nb] = high; + else sums[nb] = high; +} + +// ROUND-330: the routed decode's direct-register descriptor body. The routed stage reads its weights through +// descriptors[expert] (one row an expert), so the dense direct body's weight source does not apply; this is the +// same register body with the descriptor's trellis, strides, width and codebook in place of the dense arguments. +// A lane owns one output column of one row, decodes that column's sixteen states per 16-k block into registers +// (eight stream words), and accumulates ascending k in FP32: no threadgroup weight tile, no barrier, no MMA, +// and with splits == 1 no split reduce. The tile map is the dense body's, which is the inverse of the routed MMA +// body's at[] map, so the same (row, column) elements are decoded. Our own design; no ported code. +kernel void tf_exl3_matmul_direct_desc(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 tptg [[threads_per_threadgroup]], + uint3 tg [[threadgroup_position_in_grid]]) { + const uint row = tg.y; + if (row >= a.rows) return; + const uint expert = routes[row]; + if (expert >= a.experts) return; + const uint split = a.splits > 1 ? tg.z : 0; + const uint span = tptg.x; + const uint nb = tg.x * span + sg * 32u + lane; + if (nb >= 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 words = 4 * halves; + const uint c = nb & 15u; + // The tile state of (k, c): p = base + 8*(k/2) + (k&1) - 30*(k/8), the dense body's map. + const uint base = 32u * (c % 8u) + 4u * (c / 8u); + uint rel[16], off[16], wnext[8]; + uint wbase = 0; + for (uint k = 0; k < 16; ++k) { + const uint p = base + 8u * (k >> 1) + (k & 1u) - 30u * ((k >> 3) & 1u); + const uint map = tf_exl3_map_of(p, halves); + const uint wi = map & 63u; + if (k == 0) wbase = wi; + rel[k] = (wi + words - wbase) % words; + off[k] = (map >> 6) & 31u; + } + for (uint i = 0; i < 8; ++i) wnext[i] = (wbase + i) % words; + float high = 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; + const device half* xr = x + ulong(row) * a.k; + uint w[8]; + if (b0 < b1) { + const device ushort* tile = reinterpret_cast(data + ulong(b0) * ks + ulong(nb / 16) * ns); + TF_UNROLL + for (uint i = 0; i < 8; ++i) w[i] = tf_exl3_word(tile, wnext[i]); + } + for (uint b = b0; b < b1; ++b) { + // The next block's words are in flight while this block multiplies: the routed stage's weights come from the + // expert stream, so the load latency is the wall. + uint wn[8]; + if (b + 1 < b1) { + const device ushort* tn = reinterpret_cast(data + ulong(b + 1) * ks + ulong(nb / 16) * ns); + TF_UNROLL + for (uint i = 0; i < 8; ++i) wn[i] = tf_exl3_word(tn, wnext[i]); + } + TF_UNROLL + for (uint k = 0; k < 16; ++k) { + const uint lo = w[rel[k]], hi = w[rel[k] + 1]; + const uint carry = (hi >> ((32u - off[k]) & 31u)) & (0u - uint(off[k] != 0)); + const ushort s = ushort(((lo << off[k]) | carry) >> 16); +#if defined(TF_DIRECT_DESC_ARITH) + high += float(xr[ulong(b) * 16 + k]) * float(tf_exl3_value(s, codebook)); +#else + high += float(xr[ulong(b) * 16 + k]) * float(tf_exl3_table_value(table, codebook, s)); +#endif + } + TF_UNROLL + for (uint i = 0; i < 8; ++i) w[i] = wn[i]; + } + if (a.splits > 1) partials[ulong(split) * a.rows * a.n + ulong(row) * a.n + nb] = high; + else sums[ulong(row) * a.n + nb] = high; +} + +// The direct-register one-row body with a wider load width (ROUND-331): the trellis stream word is read as one +// 32-bit load instead of two 16-bit loads, and the activation row is read as four half4 loads instead of sixteen +// 16-bit loads. The bytes read and their order are unchanged, the codebook entry is the same table entry and the +// accumulation still ascends k in the same FP32 order, so the output is bit-identical by construction. +// The caller must guarantee the alignment the wide loads need: the trellis base 4-byte aligned and the tile +// strides a multiple of four (the EXL3 tile stride is halves*16 bytes, always a multiple of four), and the +// activation row 8-byte aligned. The narrow body (tf_exl3_matmul_direct_tab) is the fallback for the rest. +kernel void tf_exl3_matmul_direct_tab_v(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 tptg [[threads_per_threadgroup]], + uint3 tg [[threadgroup_position_in_grid]]) { + const uint split = a.splits > 1 ? tg.y : 0; + const uint span = tptg.x; + const uint nb = tg.x * span + sg * 32 + lane; + if (nb >= a.n) 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; + const uint words = 4 * halves; + const uint c = lane & 15u; + // The tile state of (k, c): p = base + 8*(k/2) + (k&1) - 30*(k/8), from the wide body's at[] map. + const uint base = 32u * (c % 8u) + 4u * (c / 8u); + uint rel[16], off[16], wnext[8]; + uint wbase = 0; + for (uint k = 0; k < 16; ++k) { + const uint p = base + 8u * (k >> 1) + (k & 1u) - 30u * ((k >> 3) & 1u); + const uint map = tf_exl3_map_of(p, halves); + const uint wi = map & 63u; + if (k == 0) wbase = wi; + rel[k] = (wi + words - wbase) % words; + off[k] = (map >> 6) & 31u; + } + for (uint i = 0; i < 8; ++i) wnext[i] = (wbase + i) % words; + float high = 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; + for (uint b = b0; b < b1; ++b) { + const device ushort* tile = reinterpret_cast(data + ulong(b) * ks + ulong(nb / 16) * ns); + uint w[8]; + TF_UNROLL + for (uint i = 0; i < 8; ++i) w[i] = *reinterpret_cast(tile + 2 * wnext[i]); + float xv[16]; + const device half4* x4 = reinterpret_cast(x + ulong(b) * 16); + TF_UNROLL + for (uint j = 0; j < 4; ++j) { + const half4 h = x4[j]; + xv[4 * j] = float(h.x); + xv[4 * j + 1] = float(h.y); + xv[4 * j + 2] = float(h.z); + xv[4 * j + 3] = float(h.w); + } + TF_UNROLL + for (uint k = 0; k < 16; ++k) { + const uint lo = w[rel[k]], hi = w[rel[k] + 1]; + const uint carry = (hi >> ((32u - off[k]) & 31u)) & (0u - uint(off[k] != 0)); + const ushort s = ushort(((lo << off[k]) | carry) >> 16); + high += xv[k] * float(tf_exl3_table_value(table, codebook, s)); + } + } + if (a.splits > 1) partials[ulong(split) * a.rows * a.n + nb] = high; + else sums[nb] = high; +} + +// The direct-register one-row body with its stream words named (ROUND-332): the eight stream words of a 16-k +// block are read into named scalars and selected with a comparison chain, instead of an array indexed by the +// runtime cursor `rel[k]`. An array with a runtime index cannot live in registers on this target, so the +// narrow body was reading and writing thread-local memory sixteen times a block. The words read, the windows +// extracted, the codebook entry and the ascending-k FP32 accumulation are all unchanged, so the output is +// bit-identical by construction. The ninth word is the carry word of the last window: the narrow body indexed +// `w[rel[k] + 1]` past its eight entries when rel[k] was 7, which this one reads correctly. +kernel void tf_exl3_matmul_direct_tab_r(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 tptg [[threads_per_threadgroup]], + uint3 tg [[threadgroup_position_in_grid]]) { + const uint split = a.splits > 1 ? tg.y : 0; + const uint span = tptg.x; + const uint nb = tg.x * span + sg * 32 + lane; + if (nb >= a.n) 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; + const uint words = 4 * halves; + const uint c = lane & 15u; + // The tile state of (k, c): p = base + 8*(k/2) + (k&1) - 30*(k/8), from the wide body's at[] map. + const uint base = 32u * (c % 8u) + 4u * (c / 8u); + uint rel[16], off[16], wnext[9]; + uint wbase = 0; + for (uint k = 0; k < 16; ++k) { + const uint p = base + 8u * (k >> 1) + (k & 1u) - 30u * ((k >> 3) & 1u); + const uint map = tf_exl3_map_of(p, halves); + const uint wi = map & 63u; + if (k == 0) wbase = wi; + rel[k] = (wi + words - wbase) % words; + off[k] = (map >> 6) & 31u; + } + for (uint i = 0; i < 9; ++i) wnext[i] = (wbase + i) % words; + float high = 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; + for (uint b = b0; b < b1; ++b) { + const device ushort* tile = reinterpret_cast(data + ulong(b) * ks + ulong(nb / 16) * ns); + uint w0, w1, w2, w3, w4, w5, w6, w7, w8; + TF_UNROLL + for (uint i = 0; i < 9; ++i) { + const uint v = tf_exl3_word(tile, wnext[i]); + if (i == 0) w0 = v; + if (i == 1) w1 = v; + if (i == 2) w2 = v; + if (i == 3) w3 = v; + if (i == 4) w4 = v; + if (i == 5) w5 = v; + if (i == 6) w6 = v; + if (i == 7) w7 = v; + if (i == 8) w8 = v; + } + TF_UNROLL + for (uint k = 0; k < 16; ++k) { + const uint r = rel[k]; + const uint lo = r == 0 ? w0 : r == 1 ? w1 : r == 2 ? w2 : r == 3 ? w3 : r == 4 ? w4 : r == 5 ? w5 : r == 6 ? w6 : r == 7 ? w7 : w8; + const uint hi = r == 0 ? w1 : r == 1 ? w2 : r == 2 ? w3 : r == 3 ? w4 : r == 4 ? w5 : r == 5 ? w6 : r == 6 ? w7 : w8; + const uint carry = (hi >> ((32u - off[k]) & 31u)) & (0u - uint(off[k] != 0)); + const ushort s = ushort(((lo << off[k]) | carry) >> 16); + high += float(x[ulong(b) * 16 + k]) * float(tf_exl3_table_value(table, codebook, s)); + } + } + if (a.splits > 1) partials[ulong(split) * a.rows * a.n + nb] = high; + else sums[nb] = high; +} 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..6dd6b8e5757 --- /dev/null +++ b/zig/kernels/metal/core/exl3_projection_i8.metal @@ -0,0 +1,117 @@ +//! The trellis tile as int8 with its own per-tile scale, on the GPU: the numerical core of the gated int8 +//! expert path, checked against the CPU int8 oracle (projection.applyF32TrellisInt8). +#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; + uint pair; +}; + +// 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. +// One threadgroup a (16-row, 16-column) output tile: 32 lanes decode the 256 states eight each, quantize, and +// each lane owns eight output cells. +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.metal b/zig/kernels/metal/core/exl3_projection_nax.metal new file mode 100644 index 00000000000..964ad1cfdee --- /dev/null +++ b/zig/kernels/metal/core/exl3_projection_nax.metal @@ -0,0 +1,5886 @@ +// Native EXL3 on the tensor units: the same stored trellis, decoded into a threadgroup tile and reduced by +// cooperative matmul instead of per-lane scalar FMAs. The decode is unchanged (measured free); only the reduction moves. +#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; + uint pair; +}; + +// 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); +} + +// ROUND-352: the same stream word as one 4-byte load. The shipped read is two 2-byte loads (a word is a +// little-endian pair of int16s), so a lane issues four memory instructions a block where the comparator +// reads two; the bytes, the values and the order are the same. `W` is a template parameter, so only one +// path is compiled. The caller checks that the tile's byte address is 4-byte aligned. +template +inline uint tf_exl3_word_t(const device ushort* tile, uint i) { + if (W) return *reinterpret_cast(reinterpret_cast(tile) + 4u * 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)]; +} + +// The same bitstream read from a tile staged in threadgroup memory: one coalesced pass over 256 bytes, then every +// decoded element hits threadgroup memory instead of a scattered device load. +inline uint tf_exl3_word_tg(const threadgroup ushort* tile, uint i) { + return uint(tile[2 * i]) | (uint(tile[2 * i + 1]) << 16); +} + +inline ushort tf_exl3_mapped_state_tg(const threadgroup ushort* tile, uint map) { + const uint wi = map & 63u, off = (map >> 6) & 31u; + const uint lo = tf_exl3_word_tg(tile, wi); + const uint hi = tf_exl3_word_tg(tile, map >> 11); + const uint carry = (hi >> ((32 - off) & 31u)) & (0u - uint(off != 0)); + return ushort(((lo << off) | carry) >> 16); +} + +// 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) { + // Ported from mlx-serve's dsv41_exl3_mul1h kernel (MIT/Apache-2.0, NOTICE per-file): the four byte sums + // collapse into one 16-bit lane and the +1024 bias is added as half 0x6400, so the state maps to the + // half h in five ALU ops instead of nine. The fma is the same one the scalar reference does. + 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, as mlx-serve's prefill kernel does: +// four ALU ops and a shared load, no 384 KB table and no per-weight L2 miss. +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]; +} + +// ROUND-347: the funnel with the value read cheaply -- the window extraction and the store stay, the codebook +// arithmetic goes. A diagnostic: it prices the value path's share of the tile (the value it stores is not the +// weight's, so its output differs by construction). The stored value is a small integer, so no denormal reaches +// the tensor units and the timing is the extraction's alone. +inline void tf_exl3_decode_funnel_cheap(threadgroup half* wx, const uint* at, uint b0, uint stride, uint w0, uint w1) { + const ulong r = (ulong(w0) << (b0 + 5u)) | (ulong(w1) >> (27u - b0)); + TF_UNROLL + for (uint k = 0; k < 8u; ++k) { + const ushort state = ushort((r >> (stride * (7u - k))) & 0xffffu); + wx[at[k]] = half(float(state & 0xFFu)); + } +} + +// ROUND-338: the lane's eight windows at compile-time shifts. C_cur is the 32-bit window at the lane's first +// state (its bit 31 is that window's first stream bit) and C_next the window 32 bits later; S is the states' +// stride in bits (halves / 2) and J the state's index, so every shift below folds at compile time. The +// structure is the comparator's (mlx-serve's dsv41_exl3_mul1h_k3 decode kernel, MIT/Apache-2.0, NOTICE +// per-file): one funnel shift a block, then the windows at fixed 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, the scalar bounds path only +// when the lane's lower row (home.y + 8) falls past the last live row. The values loaded are the same elements +// frag_get_in reads, so the arithmetic is unchanged; this only replaces eight scalar loads with two vector ones. +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, four +// columns from home.x. `c + home.x` must be a multiple of 4 and `ld` a multiple of 4. +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); +} + +// 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. This is the Fast path's +// inner decode lifted out so the double-buffered body can run it against the buffer the multiply is not reading. +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); + } +} + +// ROUND-346: the funnel read in the prompt body -- the comparator's structure (mlx-serve's dsv41_exl3_mul1h_k3 +// decode kernel, MIT/Apache-2.0, attribution in the kernel), on our map and our ring. +// +// A lane owns eight states; the states' sixteen-bit windows are `stride` bits apart (three at the routed pack's +// halves = 6), so the run of eight windows spans stride*7 + 16 bits -- thirty-seven at halves = 6 -- and two +// stream words hold it. The run is assembled once a block into the register R (R's top bit is the run's first +// bit, R's bit 0 its last), and the eight windows then sit at compile-time shifts: one shift and one mask a +// state, where the cursor's select chain was. The values, their order and the k order are the shipped body's, +// so the output is bit-identical; only the word traffic and the select chain leave. +// +// The ring's order is MSB-first inside a word, so the run's bits are assembled the other way round: R's bit +// (run - 1) is the run's first bit, and the two words' pieces meet without overlapping. +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) { + // ROUND-433: the windows are Stride bits apart, so the run is 16 + Stride * (States - 1) bits. Halves = 6 + // is Stride 3 (25 bits for a four-state lane, 37 for eight); halves = 8 is Stride 4 (28 bits for four). The + // stride is compile time now, so the shifts below are literals; the runtime argument is kept for the + // callers and ignored. + (void)stride; + constexpr uint run = 16u + Stride * (States - 1u); + // ROUND-348: the run's first bit is w0's bit (31 - b0) and it has to land on r's bit (run - 1). A run of + // thirty-seven bits (eight windows) always straddles two words; a run of twenty-five (four windows, the + // 128-row tile's lane) sits inside one word when its start leaves room for it (b0 <= 32 - run) and + // straddles otherwise. The window offsets are the same (stride a window apart), so the states are the + // shipped body's -- only the assembly of the run changes. + 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]] = NoValue ? half(state) : tf_exl3_pick(table, lut, state, codebook); + } +} + +// ROUND-390: the routed tile's STORE PATH, priced. The shipped body writes each lane's eight decoded +// weights as eight scattered two-byte threadgroup stores; the comparator writes a lane's values as wide +// contiguous stores (mlx-serve's dig_dec_job: sixteen values, two sixteen-byte stores, MIT/Apache-2.0, +// attribution in the kernel). These modes price the difference. +// Mode 1: the decode stays, the eight stores go -- the value is folded into a register accumulator so the +// compiler cannot eliminate the decode. A diagnostic: the tile is never written, so the output +// differs by construction. +// Mode 2: the eight stores stay, the EXTRACTION goes -- the stored value is a cheap function of the k +// block, so the stores cannot be hoisted out of the loop. A diagnostic. +// Mode 3: the decode stays, the eight stores become CONTIGUOUS -- one lane's run of eight halves, the +// comparator's form. The tile's contents change, so the output differs by construction. +// Mode 4: the shipped store PLUS the Mode 1 accumulator -- the calibration for the accumulator's cost. +template +inline uint tf_exl3_decode_funnel_store(threadgroup half* wx, const device half* table, const threadgroup half* lut, + uint codebook, const uint* at, uint b0, uint stride, uint w0, uint w1, + uint acc, uint salt, uint slot) { + constexpr uint run = 16u + 3u * (States - 1u); + 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); + const half v = tf_exl3_pick(table, lut, state, codebook); + if (Mode == 1) { + acc ^= uint(as_type(v)); + } else if (Mode == 2) { + wx[at[k]] = half(float(salt + k)); + } else if (Mode == 3) { + wx[slot * States + k] = v; + } else { + wx[at[k]] = v; + if (Mode == 4) acc ^= uint(as_type(v)); + } + } + return acc; +} + +// ROUND-350: the funnel's extraction in thirty-two-bit words, the windows at compile-time shifts -- the +// comparator's structure (mlx-serve's dsv41_prefill_dig_gemm's dig_dec_job and dig_windows, MIT/Apache-2.0, +// NOTICE per-file: it reads its stream words into 32-bit registers and shifts them by literal amounts, because +// Apple GPUs emulate a 64-bit shift with several 32-bit ops, so the shipped funnel paid that emulation once a +// window). The lane's first window starts at bit b0 of the ring's word (the ring is MSB-first inside a word): +// G holds the thirty-two ring bits from there and h5 the five above them, so the eight windows sit at G's +// compile-time shifts (16 - 3k) and the last two take their high bits from h5. The same windows, the same +// values, the same order -- the output is bit-identical to the shipped funnel. +template +inline void tf_exl3_decode_funnel32(threadgroup half* wx, const device half* table, const threadgroup half* lut, + uint codebook, const uint* at, uint b0, uint w0, uint w1) { + const uint G = (w0 << b0) | ((w1 >> 1u) >> (31u - b0)); + const uint h5 = (w1 >> (27u - b0)) & 0x1Fu; + TF_UNROLL + for (uint k = 0; k < States; ++k) { + uint state; + if (States == 8u and k == 6u) { + state = ((G & 0x3FFFu) << 2u) | ((h5 >> 3u) & 3u); + } else if (States == 8u and k == 7u) { + state = ((G & 0x7FFu) << 5u) | (h5 & 0x1Fu); + } else { + state = (G >> (16u - 3u * k)) & 0xFFFFu; + } + wx[at[k]] = NoValue ? half(state) : tf_exl3_pick(table, lut, ushort(state), codebook); + } +} + +// A threadgroup owns RG sixteen-row groups by CG sixty-four-column groups, one SIMDgroup a (row group, column +// group). Dense rows share one matrix; grouped rows are sixty-four-row aligned, so one expert owns the tile and +// its weights decode once. A wider column tile re-reads the activation tile for fewer output tiles. `Fast` keeps +// the per-state cursor out of the k loop and reads the three stream words an eight-state block can touch. +template +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; + // ROUND-389: the activation's staging area, carved from the tail of the weight tile (the kernel entries + // allocate it): the tile's rows by the block's sixteen k columns. + threadgroup half* ax = wx + 16u * 64u * CG; + 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 uint didx = a.indexed ? tile_expert : 0; + const device uchar* data = a.indexed ? descriptors[didx].trellis : trellis; + const ulong ks = a.indexed ? descriptors[didx].tile_k_stride : a.tile_k_stride; + const ulong ns = a.indexed ? descriptors[didx].tile_n_stride : a.tile_n_stride; + const uint halves = a.indexed ? descriptors[didx].halves : a.halves; + const uint codebook = a.indexed ? descriptors[didx].codebook : a.codebook; + const short2 home = frag_home(ushort(lane)); + const uint rows_here = min(trows, a.rows - rb); + const uint cols_here = min(64u * CG, a.n - nb); + // Four warps decode a sixty-four-column group; a threadgroup with more warps a group than that splits the sixteen + // states of each lane between them instead of leaving those warps to wait at the barrier. + // ROUND-350: the warps decoding one sixteen-column block. With Rpg row groups a warp (the comparator's + // thirty-two-row simdgroup) the block is decoded by one warp, so the lane still owns eight states and + // still reads eight bits a weight -- the tile's height and the traffic per weight are decoupled. + 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; + uint at[8], off[8], sh[8], rel[8]; + const uint words = 4 * halves; + const uint wi0 = tf_exl3_map_for(p0, halves) & 63u; + const uint b0 = (tf_exl3_map_for(p0, halves) >> 6) & 31u; + if (Fast) { + const uint ring = 128 * halves; + const uint cur = (wi0 << 5) | ((tf_exl3_map_for(p0, halves) >> 6) & 31u); + TF_UNROLL + for (uint k = 0; k < states; ++k) { + const uint p = p0 + k, l = p / 8, e = p % 8; + at[k] = (2 * (l % 4) + (e & 1u) + 8 * ((e >> 1) & 1u)) * (64u * CG) + hg + h * 16u + (l / 4 + 8 * (e >> 2)); + uint c8 = cur + k * (halves >> 1); + if (c8 >= ring) c8 -= ring; + const uint wi = c8 >> 5; + // ROUND-352: with F6 the funnel path is the only one, and the cursor arrays the Fast path needs are + // dead there -- but they are live registers across the whole k loop, so they are not computed at all. + if (!F6) { + off[k] = c8 & 31u; + sh[k] = (32u - off[k]) & 31u; + rel[k] = wi >= wi0 ? wi - wi0 : wi + words - wi0; + } + } + } + // ROUND-350: this SIMDgroup's row groups (Rpg of them) and its column group. + const uint sgr = Rpg * (sg % (RG / Rpg)), sgc = sg / (RG / Rpg); + // ROUND-347: the routed tile's padded rows need no multiply. Each expert's block is padded to sixty-four rows + // (the padding rows carry the sentinel expert id), and a warp owns sixteen rows of the tile, so a warp reads + // its own sixteen route ids and skips the multiply when they are all padding. The decode stays: the other + // warps read the whole sixty-four-column tile. The real rows' values, their order and the k order are the + // shipped body's, so the reply is bit-identical. + // ROUND-350: the skip is per sixteen-row group, so a warp that owns two groups (the comparator's shape) + // still multiplies the real one. The mask keeps the per-group answer in a scalar (no local memory). + 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, their latency overlaps + // the multiply and the next block's decode instead of stalling at the top of every k block. + uint p0v = 0, p1v = 0, p2v = 0, p3v = 0; + // ROUND-390: the store path's accumulator (the decode's values kept live in a register). + uint sacc = 0; + // ROUND-350: the cooperative read -- this lane holds the block's word at its own index and the two words it + // needs arrive by a shuffle, so the warp reads the block's ninety-six bytes once instead of 2.67 times over. + uint mine = 0, wi1s = 0; + if (Funnel and Coop and decodes) { + const device ushort* tile0 = reinterpret_cast(data + ulong(nb / 16 + hg / 16u + h) * ns); + mine = (lane < words) ? tf_exl3_word_t(tile0, lane) : 0u; + wi1s = (wi0 + 1u < words) ? wi0 + 1u : wi0 + 1u - words; + } + if (Fast and decodes) { + const device ushort* tile0 = reinterpret_cast(data + ulong(nb / 16 + hg / 16u + h) * ns); + 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_t(tile0, wi0); + p1v = tf_exl3_word_t(tile0, a1); + p2v = tf_exl3_word_t(tile0, a2); + p3v = tf_exl3_word_t(tile0, a3); + } + for (uint kb = 0; kb < a.k; kb += 16) { + // One thread owns 8 consecutive states of one 16x16 tile. The bit cursor advances by `halves` a state, so it + // rolls forward with one add and one conditional subtract instead of recomputing the map formula. + if (decodes) { + { + const device ushort* tile = reinterpret_cast( + data + ulong(kb / 16) * ks + ulong(nb / 16 + hg / 16u + h) * ns); + if (Funnel and (F6 or halves == 6) and (states == 8 or states == 4)) { + // Two words a lane: the funnel holds the lane's eight windows (three bits apart), so the state's window + // is one shift and one mask from the funnel, with no cursor and no select chain. + const uint nkb = kb + 16; + if (Coop) { + // ROUND-350: the words come from the cooperative read -- a shuffle from the lane that holds the word. + const uint w0 = simd_shuffle(mine, wi0); + const uint w1 = simd_shuffle(mine, wi1s); + if (nkb < a.k) { + const device ushort* tile_n = reinterpret_cast( + data + ulong(nkb / 16) * ks + ulong(nb / 16 + hg / 16u + h) * ns); + mine = (lane < words) ? tf_exl3_word_t(tile_n, lane) : 0u; + } + if (Cheap) tf_exl3_decode_funnel_cheap(wx, at, b0, halves >> 1, w0, w1); + else if (Funnel32) tf_exl3_decode_funnel32(wx, table, lut, codebook, at, b0, w0, w1); + else tf_exl3_decode_funnel(wx, table, lut, codebook, at, b0, halves >> 1, w0, w1); + } else { + const uint w0 = p0v, w1 = p1v; + if (nkb < a.k) { + const device ushort* tile_n = reinterpret_cast( + data + ulong(nkb / 16) * ks + ulong(nb / 16 + hg / 16u + h) * ns); + p0v = tf_exl3_word_t(tile_n, wi0); + p1v = tf_exl3_word_t(tile_n, wi0 + 1 < words ? wi0 + 1 : wi0 + 1 - words); + } + if (Store != 0) { + sacc = tf_exl3_decode_funnel_store(wx, table, lut, codebook, at, b0, halves >> 1, w0, w1, sacc, kb, tid); + } else if (Cheap) tf_exl3_decode_funnel_cheap(wx, at, b0, halves >> 1, w0, w1); + else if (Funnel32) tf_exl3_decode_funnel32(wx, table, lut, codebook, at, b0, w0, w1); + else tf_exl3_decode_funnel(wx, table, lut, codebook, at, b0, halves >> 1, w0, w1); + } + } else if (Fast and (halves & 1u) == 0 and 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( + data + ulong(nkb / 16) * ks + ulong(nb / 16 + hg / 16u + h) * ns); + 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 = 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]] = NoValue ? half(ushort(((lo << off[k]) | carry) >> 16)) + : tf_exl3_pick(table, lut, ushort(((lo << off[k]) | carry) >> 16), codebook); + } + } else if (halves <= 16 and (halves & 1u) == 0 and states == 8) { + const uint ring = 128 * 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_t(tile, wi0); + const uint w1 = tf_exl3_word_t(tile, at1), w2 = tf_exl3_word_t(tile, at2); + const uint w3 = tf_exl3_word_t(tile, at3), w4 = tf_exl3_word_t(tile, at4); + uint cur = (wi0 << 5) | ((tf_exl3_map_for(p0, 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 * (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), 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, halves)), codebook); + } + } + } + } + // This SIMDgroup's rows of the k block, read straight into fragments: no staging buffer, one barrier. + // ROUND-350: Rpg sixteen-row groups a warp -- the weight fragments are read once for all of them. + // ROUND-389: the activation's three forms. Act == 1 reads the fragment ONCE, before the k loop (a + // diagnostic: the output differs by construction and the delta against Act == 0 IS the per-block read). + // Act == 2 stages the fragment in threadgroup memory once a k block, so the two column groups of a row + // group SHARE one device read -- the record's "occupancy-keeping form" (one column tile's activation read + // shared by two column groups, the fragment in threadgroup memory). The staging is published by the SAME + // barrier that publishes the weight tile, so the block's barrier count is unchanged. + frag av[Rpg]; + if (Act == 1) { + 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), 0, home, int(rb + rows_here)); + } + } + } + if (Act == 2) { + // The staging: the column group's first warp reads its row group's activation from the device once and + // writes it into the tile's staging area (the tile's rows, the block's sixteen k columns). The other + // column group's warps read it back from there AFTER the barrier that publishes it, so the device read + // happens once a row group, not once a column group. The values, their order and the k order are the + // shipped body's. + if (sgc == 0 and any_live) { + TF_UNROLL + for (uint r = 0; r < Rpg; ++r) { + if (group_live[r]) { + const int r0 = int(rb + (sgr + r) * 16) + int(home.y); + const int r1 = r0 + 8; + const int c0 = int(kb) + int(home.x); + half4 v0 = half4(0.0h, 0.0h, 0.0h, 0.0h); + half4 v1 = half4(0.0h, 0.0h, 0.0h, 0.0h); + if (r0 < int(rb + rows_here)) v0 = *(const device half4*)(x + r0 * int(a.k) + c0); + if (r1 < int(rb + rows_here)) v1 = *(const device half4*)(x + r1 * int(a.k) + c0); + *(threadgroup half4*)(ax + int((sgr + r) * 16 + uint(home.y)) * 16 + int(home.x)) = v0; + *(threadgroup half4*)(ax + int((sgr + r) * 16 + uint(home.y) + 8u) * 16 + int(home.x)) = v1; + } + } + } + } + if (Act == 0) { + 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 + rows_here)); + } + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (Act == 2) { + // The staged fragment, read back after the barrier that published it. + TF_UNROLL + for (uint r = 0; r < Rpg; ++r) { + if (group_live[r]) tf_frag_get_tg4(av[r], ax, 16, int((sgr + r) * 16), 0, home); + } + } + 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); + } + // ROUND-390: the accumulator is folded into the first output element, so the decode's values cannot be + // eliminated. A diagnostic: the output differs by construction. + if (Store == 1 or Store == 4) { + const float t = lo0[0][0]; + lo0[0][0] = t + float(sacc); + } + 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), so the + // bounds must be absolute too: the last live row is rb + rows_here and the last live column is + // nb + cols_here. The relative counts (rows_here - sg*16, cols_here) left every row past 32 and + // every column past 16 unwritten, which is what made this kernel's answers wrong. + 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 + rows_here), int(nb + cols_here)); + frag_put_in(hi0[r], sums, int(a.n), r0 + int(r * 16), c0 + 16, home, int(rb + rows_here), int(nb + cols_here)); + frag_put_in(lo1[r], sums, int(a.n), r0 + int(r * 16), c0 + 32, home, int(rb + rows_here), int(nb + cols_here)); + frag_put_in(hi1[r], sums, int(a.n), r0 + int(r * 16), c0 + 48, home, int(rb + rows_here), int(nb + cols_here)); + } + } +} + + +// Two-blocks-ahead prompt body: the stream words for block b+1 are issued two iterations before they are decoded, +// so a DRAM-latency miss is covered by two blocks of multiply and decode instead of one. Two threadgroup tiles and +// two register word sets; the arithmetic (values, k order, MMA order) is the double-buffered body's, unchanged. +template +inline void tf_exl3_prefill_body_pf(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 uint didx = a.indexed ? tile_expert : 0; + const device uchar* data = a.indexed ? descriptors[didx].trellis : trellis; + const ulong ks = a.indexed ? descriptors[didx].tile_k_stride : a.tile_k_stride; + const ulong ns = a.indexed ? descriptors[didx].tile_n_stride : a.tile_n_stride; + const uint halves = a.indexed ? descriptors[didx].halves : a.halves; + const uint codebook = a.indexed ? descriptors[didx].codebook : a.codebook; + if ((halves & 1u) != 0 or halves > 16) { + tf_exl3_prefill_body(wx, x, trellis, sums, a, routes, descriptors, nullptr, nullptr, lane, sg, tid, tptg, tg); + return; + } + const short2 home = frag_home(ushort(lane)); + const uint rows_here = min(trows, a.rows - rb); + const uint cols_here = min(64u * CG, a.n - nb); + constexpr uint wpg = RG / 4u; + 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; + uint at[8], off[8], sh[8], rel[8]; + const uint words = 4 * halves; + const uint wi0 = tf_exl3_map_for(p0, halves) & 63u; + const uint ring = 128 * halves; + { + const uint cur = (wi0 << 5) | ((tf_exl3_map_for(p0, halves) >> 6) & 31u); + TF_UNROLL + for (uint k = 0; k < states; ++k) { + const uint p = p0 + k, l = p / 8, e = p % 8; + at[k] = (2 * (l % 4) + (e & 1u) + 8 * ((e >> 1) & 1u)) * (64u * CG) + hg + h * 16u + (l / 4 + 8 * (e >> 2)); + uint c8 = cur + k * (halves >> 1); + if (c8 >= ring) c8 -= ring; + const uint wi = c8 >> 5; + off[k] = c8 & 31u; + sh[k] = (32u - off[k]) & 31u; + rel[k] = wi >= wi0 ? wi - wi0 : wi + words - wi0; + } + } + const uint sgr = sg % RG, sgc = sg / RG; + frag lo0 = frag(0), hi0 = frag(0), lo1 = frag(0), hi1 = frag(0); + const uint blocks = a.k / 16; + // Block 0 decodes straight from its words; blocks 1 and 2 are issued into the two register sets behind it. + if (decodes) { + const uint w0 = tf_exl3_block_word(data, ks, ns, 0, nb, hg, h, wi0, words); + const uint w1 = tf_exl3_block_word(data, ks, ns, 0, nb, hg, h, wi0 + 1, words); + const uint w2 = tf_exl3_block_word(data, ks, ns, 0, nb, hg, h, wi0 + 2, words); + const uint w3 = tf_exl3_block_word(data, ks, ns, 0, nb, hg, h, wi0 + 3, words); + tf_exl3_decode_fast(wx, codebook, at, off, sh, rel, w0, w1, w2, w3); + } + uint A0 = 0, A1 = 0, A2 = 0, A3 = 0, B0 = 0, B1 = 0, B2 = 0, B3 = 0; + if (decodes and blocks > 1) { + A0 = tf_exl3_block_word(data, ks, ns, 16, nb, hg, h, wi0, words); + A1 = tf_exl3_block_word(data, ks, ns, 16, nb, hg, h, wi0 + 1, words); + A2 = tf_exl3_block_word(data, ks, ns, 16, nb, hg, h, wi0 + 2, words); + A3 = tf_exl3_block_word(data, ks, ns, 16, nb, hg, h, wi0 + 3, words); + } + if (decodes and blocks > 2) { + B0 = tf_exl3_block_word(data, ks, ns, 32, nb, hg, h, wi0, words); + B1 = tf_exl3_block_word(data, ks, ns, 32, nb, hg, h, wi0 + 1, words); + B2 = tf_exl3_block_word(data, ks, ns, 32, nb, hg, h, wi0 + 2, words); + B3 = tf_exl3_block_word(data, ks, ns, 32, nb, hg, h, wi0 + 3, words); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + for (uint b = 0; b < blocks; ++b) { + const uint cur_buf = b & 1u; + // Decode block b+1 from the set issued two iterations ago (before this block's multiply, into the free tile). + if (b + 1 < blocks and decodes) { + const bool even = ((b + 1) & 1u) == 0u; + const uint w0 = even ? A0 : B0, w1 = even ? A1 : B1, w2 = even ? A2 : B2, w3 = even ? A3 : B3; + tf_exl3_decode_fast(wx + (cur_buf ^ 1u) * (16u * 64u * CG), codebook, at, off, sh, rel, w0, w1, w2, w3); + } + frag av; + tf_frag_get_dev4(av, (const device half*)x, int(a.k), int(rb + sgr * 16), int(b * 16), home, int(rb + rows_here)); + 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); + mma_16x32(lo0, hi0, av, 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); + mma_16x32(lo1, hi1, av, b0, b1); + } + // Issue block b+3 into the set just decoded (its consumers are two iterations away). + if (b + 3 < blocks and decodes) { + const bool even = ((b + 3) & 1u) == 0u; + const uint n3 = (b + 3) * 16; + const uint q0 = tf_exl3_block_word(data, ks, ns, n3, nb, hg, h, wi0, words); + const uint q1 = tf_exl3_block_word(data, ks, ns, n3, nb, hg, h, wi0 + 1, words); + const uint q2 = tf_exl3_block_word(data, ks, ns, n3, nb, hg, h, wi0 + 2, words); + const uint q3 = tf_exl3_block_word(data, ks, ns, n3, nb, hg, h, wi0 + 3, words); + if (even) { A0 = q0; A1 = q1; A2 = q2; A3 = q3; } + else { B0 = q0; B1 = q1; B2 = q2; B3 = q3; } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + } + const int r0 = int(rb + sgr * 16); + const int c0 = int(nb + sgc * 64u); + frag_put_in(lo0, sums, int(a.n), r0, c0, home, int(rb + rows_here), int(nb + cols_here)); + frag_put_in(hi0, sums, int(a.n), r0, c0 + 16, home, int(rb + rows_here), int(nb + cols_here)); + frag_put_in(lo1, sums, int(a.n), r0, c0 + 32, home, int(rb + rows_here), int(nb + cols_here)); + frag_put_in(hi1, sums, int(a.n), r0, c0 + 48, home, int(rb + rows_here), int(nb + cols_here)); +} + +// Double-buffered prompt body: the next k block decodes into the tile the multiply is not reading, and the multiply +// is issued before that decode, so the tensor units and the codebook ALU are in flight together. One barrier a block +// instead of two; the even-halves Fast cursor is the only path doubled (the shipped body covers the rest). +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 uint didx = a.indexed ? tile_expert : 0; + const device uchar* data = a.indexed ? descriptors[didx].trellis : trellis; + const ulong ks = a.indexed ? descriptors[didx].tile_k_stride : a.tile_k_stride; + const ulong ns = a.indexed ? descriptors[didx].tile_n_stride : a.tile_n_stride; + const uint halves = a.indexed ? descriptors[didx].halves : a.halves; + const uint codebook = a.indexed ? descriptors[didx].codebook : a.codebook; + const short2 home = frag_home(ushort(lane)); + const uint rows_here = min(trows, a.rows - rb); + const uint cols_here = min(64u * CG, a.n - nb); + // ROUND-351: with Rpg row groups a SIMDgroup (the comparator's shape: a simdgroup owns thirty-two rows), + // the warps decoding one column group are RG / (4 * Rpg) and a lane owns 8 / that many states. Rpg = 1 is + // the shipped body, bit for bit. + 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; + // ROUND-433: the funnel is admissible where the lane's run fits two 32-bit words: halves = 6 (stride 3) with + // four or eight states, and halves = 8 (stride 4) with four states. Everything else keeps the cursor path. + const bool use_funnel = Funnel and ((halves == 6u and (states == 8u or states == 4u)) or + (halves == 8u and states == 4u)); + if ((halves & 1u) != 0 or halves > 16) { + tf_exl3_prefill_body(wx, x, trellis, sums, a, routes, descriptors, table, nullptr, lane, sg, tid, tptg, tg); + return; + } + uint at[8], off[8], sh[8], rel[8]; + const uint words = 4 * halves; + const uint wi0 = tf_exl3_map_for(p0, halves) & 63u; + const uint b0 = (tf_exl3_map_for(p0, halves) >> 6) & 31u; + { + const uint ring = 128 * halves; + const uint cur = (wi0 << 5) | ((tf_exl3_map_for(p0, halves) >> 6) & 31u); + TF_UNROLL + for (uint k = 0; k < states; ++k) { + const uint p = p0 + k, l = p / 8, e = p % 8; + at[k] = (2 * (l % 4) + (e & 1u) + 8 * ((e >> 1) & 1u)) * (64u * CG) + hg + h * 16u + (l / 4 + 8 * (e >> 2)); + uint c8 = cur + k * (halves >> 1); + if (c8 >= ring) c8 -= ring; + const uint wi = c8 >> 5; + off[k] = c8 & 31u; + sh[k] = (32u - off[k]) & 31u; + rel[k] = wi >= wi0 ? wi - wi0 : wi + words - wi0; + } + } + 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(data, ks, ns, 0, nb, hg, h, wi0, words); + const uint w1 = tf_exl3_block_word(data, ks, ns, 0, nb, hg, h, wi0 + 1, words); + if (use_funnel) { + if (halves == 8u) tf_exl3_decode_funnel(wx, table, nullptr, codebook, at, b0, 4, w0, w1); + else tf_exl3_decode_funnel(wx, table, nullptr, codebook, at, b0, halves >> 1, w0, w1); + } else { + const uint w2 = tf_exl3_block_word(data, ks, ns, 0, nb, hg, h, wi0 + 2, words); + const uint w3 = tf_exl3_block_word(data, ks, ns, 0, nb, hg, h, wi0 + 3, words); + if (UseTable) tf_exl3_decode_table(wx, table, codebook, at, off, sh, rel, w0, w1, w2, w3); + else tf_exl3_decode_fast(wx, codebook, at, off, sh, 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(data, ks, ns, nkb, nb, hg, h, wi0, words); + nw1 = tf_exl3_block_word(data, ks, ns, nkb, nb, hg, h, wi0 + 1, words); + if (!use_funnel) { + nw2 = tf_exl3_block_word(data, ks, ns, nkb, nb, hg, h, wi0 + 2, words); + nw3 = tf_exl3_block_word(data, ks, ns, 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 + 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 (halves == 8u) tf_exl3_decode_funnel(nxt, table, nullptr, codebook, at, b0, 4, nw0, nw1); + else tf_exl3_decode_funnel(nxt, table, nullptr, codebook, at, b0, halves >> 1, nw0, nw1); + } else if (UseTable) tf_exl3_decode_table(nxt, table, codebook, at, off, sh, rel, nw0, nw1, nw2, nw3); + else tf_exl3_decode_fast(nxt, codebook, at, off, sh, 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 + rows_here), int(nb + cols_here)); + frag_put_in(hi0[r], sums, int(a.n), r0, c0 + 16, home, int(rb + rows_here), int(nb + cols_here)); + frag_put_in(lo1[r], sums, int(a.n), r0, c0 + 32, home, int(rb + rows_here), int(nb + cols_here)); + frag_put_in(hi1[r], sums, int(a.n), r0, c0 + 48, home, int(rb + rows_here), int(nb + 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) + at[k]]); + sums[tid] = acc; + } +} + +kernel void tf_exl3_matmul_prefill_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)]], + 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_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: each SIMDgroup decodes its own expert's 16x32 tile once and +// multiplies the single row it owns, writing only that row of the sixteen-row tensor-unit product. +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, and one barrier a block + // replaces two because the tile a multiply reads is never the tile a decode writes. + // TF_DECODE_TABLE: the codebook value is read from the resident table (the engine binds it at buffer 7 for + // every stage) instead of derived in the ALU. The table holds the format's own decoder's values, qualified + // entry for entry against the arithmetic path, so the decoded tile -- and the product -- is bit-identical. +#if defined(TF_DECODE_COMPACT) + // Compact: one row a threadgroup, two 16x32 tiles only (1 KB), so many more groups fit the threadgroup + // memory and the decode's issue rate is not occupancy-bound (round 173's probe: 0.84 against 0.50e12). + 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, which is four + // times the threadgroups for the same work (TF_DSV41_EXL3_MOE_ROWS). +#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; + 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 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, so a split takes a + // slice of the k blocks and the reduce kernel sums the parts in split order. + 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 three stream words they can touch are + // read once and the cursor and the tile slot come from registers (the prompt kernel's inner loop). + uint at[8], off[8], sh[8], rel[8]; + const uint words = 4 * halves; + const uint wi0 = tf_exl3_map_for(lane * 8u, halves) & 63u; + // TF_DECODE_FUNNEL: the routed pack's halves = 6. Eight consecutive states a lane span 37 bits from + // start + 16, so two 32-bit stream words cover all eight and the per-state word-pair selection collapses to + // a two-way select. For halves = 6 the rel = 1 states always start at bit offset <= 16, so the next word + // after the pair contributes only below the 16-bit state and can be dropped. Bit-identical to the four-word + // path (verified against tf_exl3_mapped_state for every lane and state); halves != 6 keeps the general path. +#if defined(TF_DECODE_FUNNEL) + // ROUND-443: halves = 8 (the drafter's routed pack) joins halves = 6 ONLY under TF_DECODE_FUNNEL_H8, the + // bench's arm. At halves = 8 every lane's run starts at off0 = 20 (the map's start is 1012 + 32*lane mod + // 1024), so eight four-bit-spaced states span exactly 44 bits and sit in two words with every rel = 1 state + // at an offset <= 16 -- the same two-word form. The arm is priced at 3-6 % SLOWER than the four-word + // cursor body, so no engine path selects it; the shipped gate stays halves = 6. +#if defined(TF_DECODE_FUNNEL_H8) + const bool funnel = halves == 6u or halves == 8u; +#else + const bool funnel = halves == 6u; +#endif +#else + const bool funnel = false; +#endif +// ROUND-443: THE TWO-WORD READ AT halves = 8 WITHOUT THE FUNNEL'S ASSEMBLY. Every lane's eight states start +// at off0 = 20 and sit in exactly two stream words (rel in {0, 1}); the general path loads four. This drops +// the two words it cannot touch and keeps the cursor's select-chain extraction. Bit-identical by construction +// (the two words it drops feed only rel >= 2, which does not occur at halves = 8). +#if defined(TF_DECODE_TWO) + const bool two_word = halves == 8u; +#else + const bool two_word = false; +#endif + { + const uint ring = 128 * halves; + 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 p = lane * 8u + k, l = p / 8, e = p % 8; + off[k] = (cur + k * (halves >> 1)) % ring & 31u; + const uint c8 = (cur + k * (halves >> 1)) % ring; + sh[k] = (32u - off[k]) & 31u; + rel[k] = (c8 >> 5) >= wi0 ? (c8 >> 5) - wi0 : (c8 >> 5) + words - wi0; + at[k] = (2 * (l % 4) + (e & 1u) + 8 * ((e >> 1) & 1u)) * 32u + (l / 4 + 8 * (e >> 2)); + } + } + 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 = (halves & 1u) == 0 and halves <= 16; + 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; + if (pipeline) { + const device ushort* t0 = reinterpret_cast(data + ulong(b0) * ks + ulong(nb / 16) * ns); + pre[0][0] = tf_exl3_word(t0, wi0); + pre[0][1] = tf_exl3_word(t0, a1); + if (!funnel and !two_word) { + pre[0][2] = tf_exl3_word(t0, a2); + pre[0][3] = tf_exl3_word(t0, a3); + } + if (nb + 16 < a.n) { + const device ushort* t1 = reinterpret_cast(data + ulong(b0) * ks + ulong(nb / 16 + 1) * ns); + pre[1][0] = tf_exl3_word(t1, wi0); + pre[1][1] = tf_exl3_word(t1, a1); + if (!funnel and !two_word) { + pre[1][2] = tf_exl3_word(t1, a2); + pre[1][3] = tf_exl3_word(t1, a3); + } + } + } + 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(data + ulong(nxt) * ks + ulong(nb / 16 + h) * ns); + pre[h][0] = tf_exl3_word(tn, wi0); + pre[h][1] = tf_exl3_word(tn, a1); + if (!funnel and !two_word) { + pre[h][2] = tf_exl3_word(tn, a2); + pre[h][3] = tf_exl3_word(tn, a3); + } + } + if (funnel) { + // Two words a lane: the comparator's two-word read (mlx-serve's dsv41_exl3_mul1h_k3 kernels, + // MIT/Apache-2.0, NOTICE per-file), on our map and with our left-shift funnel. The rel = 1 states + // start at bit offset <= 16 at halves = 6, so the second word's carry is the whole state's source. + TF_UNROLL + for (uint k = 0; k < 8; ++k) { + const uint lo8 = rel[k] == 0 ? w0 : w1; + const uint hi8 = rel[k] == 0 ? w1 : 0; + const uint carry = (hi8 >> sh[k]) & (0u - uint(off[k] != 0)); +#if defined(TF_DECODE_TABLE) + wxc[at[k] + h * 16] = tf_exl3_table_value(table, ushort(((lo8 << off[k]) | carry) >> 16), codebook); +#else + wxc[at[k] + h * 16] = tf_exl3_value(ushort(((lo8 << off[k]) | carry) >> 16), codebook); +#endif + } + } else { + TF_UNROLL + for (uint k = 0; k < 8; ++k) { + const uint lo8 = rel[k] == 0 ? w0 : rel[k] == 1 ? w1 : w2; + const uint hi8 = rel[k] == 0 ? w1 : rel[k] == 1 ? w2 : w3; + const uint carry = (hi8 >> sh[k]) & (0u - uint(off[k] != 0)); +#if defined(TF_DECODE_TABLE) + wxc[at[k] + h * 16] = tf_exl3_table_value(table, ushort(((lo8 << off[k]) | carry) >> 16), codebook); +#else + wxc[at[k] + h * 16] = tf_exl3_value(ushort(((lo8 << off[k]) | carry) >> 16), 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( + data + ulong(kb / 16) * ks + ulong(nb / 16 + h) * ns); + 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, halves)), codebook); +#else + wxc[r * 32 + h * 16 + c] = tf_exl3_value(tf_exl3_mapped_state(tile, tf_exl3_map_for(p, halves)), 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)); +} + +// One row, four column tiles a threadgroup: a dense projection at decode width on the tensor units. Each +// SIMDgroup decodes its own 32-column tile once and multiplies the single row, writing only row 0. +kernel void tf_exl3_matvec_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)]], + 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[4 * 16 * 32]; + threadgroup half xx[16 * 16]; + const uint nb = tg.x * 128 + sg * 32; + if (nb >= a.n || a.rows == 0) return; + const device uchar* base = trellis; + const uint cols_here = min(32u, a.n - nb); + const short2 home = frag_home(ushort(lane)); + threadgroup half* wxg = wx + sg * (16 * 32); + frag lo = frag(0), hi = frag(0); + for (uint kb = 0; kb < a.k; kb += 16) { + 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( + base + ulong(kb / 16) * a.tile_k_stride + ulong(nb / 16 + h) * a.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); + wxg[r * 32 + h * 16 + c] = tf_exl3_value(tf_exl3_mapped_state(tile, tf_exl3_map_for(p, a.halves)), a.codebook); + } + TF_UNROLL + for (uint t = 0; t < 8; ++t) { + const uint idx = lane + 32 * t, r = idx / 16, c = idx % 16; + xx[idx] = r == 0 ? *(const device half*)(x + ulong(kb) + c) : half(0); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + frag av, b0, b1; + tf_frag_get_tg4(av, xx, 16, 0, 0, home); + tf_frag_get_tg4(b0, wxg, 32, 0, 0, home); + tf_frag_get_tg4(b1, wxg, 32, 0, 16, home); + mma_16x32(lo, hi, av, b0, b1); + threadgroup_barrier(mem_flags::mem_threadgroup); + } + frag_put_in(lo, sums, int(a.n), 0, int(nb), home, 1, int(nb + cols_here)); + frag_put_in(hi, sums, int(a.n), 0, int(nb + 16), home, 1, int(nb + cols_here)); +} + + +// ROUND-444 bench-only arm: the register-direct MMA decode-free floor. `tf_exl3_matvec_nax` stages the +// decoded B tile in threadgroup memory and reads it back as fragments; the port the handoff names would decode +// the lane's eight values straight into the fragment registers, so this kernel is that form's upper bound: the +// B fragments are constants (no trellis read, no state extraction, no value, no threadgroup tile, no barrier on +// the B side), while the A staging, the MMA sequence and the output store are the matvec body's own. If this +// floor is not faster than the register-only FMA body at a shape, no register-direct decode can be: the decode +// and its staging are the only things left to remove, and they are already gone here. Timing only, values +// meaningless; no engine path selects it. +kernel void tf_exl3_matvec_nax_regfloor(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 tg [[threadgroup_position_in_grid]]) { + threadgroup half xx[16 * 16]; + const uint nb = tg.x * 128 + sg * 32; + if (nb >= a.n || a.rows == 0) return; + const uint cols_here = min(32u, a.n - nb); + const short2 home = frag_home(ushort(lane)); + frag lo = frag(0), hi = frag(0); + frag b0, b1; + TF_UNROLL + for (uint e = 0; e < 8; ++e) { b0[e] = half(1); b1[e] = half(1); } + for (uint kb = 0; kb < a.k; kb += 16) { + TF_UNROLL + for (uint t = 0; t < 8; ++t) { + const uint idx = lane + 32 * t, r = idx / 16, c = idx % 16; + xx[idx] = r == 0 ? *(const device half*)(x + ulong(kb) + c) : half(0); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + frag av; + tf_frag_get_tg4(av, xx, 16, 0, 0, home); + mma_16x32(lo, hi, av, b0, b1); + threadgroup_barrier(mem_flags::mem_threadgroup); + } + frag_put_in(lo, sums, int(a.n), 0, int(nb), home, 1, int(nb + cols_here)); + frag_put_in(hi, sums, int(a.n), 0, int(nb + 16), home, 1, int(nb + cols_here)); +} + + +// ROUND-445 bench-only arm: THE ONE-SIMDGROUP-PER-COLUMN ROUTED DECODE, on the EXL3 tile layout. The +// comparator's routed decode gives a simdgroup one output column and lets its lanes walk k: that works on +// its affine pack because a column's weights are self-contained. Our pack's trellis is a 16-column x +// 16-row bit-sharing tile (256 states in 96 bytes, each state a 16-bit window advancing three bits), so a +// column's sixteen states are interleaved with its fifteen neighbours in the same bytes, and this arm must +// read every tile its column shares. It is the arm the handoff asked for, priced as-is: the tile reads are +// 16x the packed bytes by construction, and the map's per-weight address chain is eight ALU ops where the +// tile body amortises one over 256 states. Timing arm only; no engine path selects it. +kernel void tf_exl3_matvec_col_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)]], + const device half* table [[buffer(7)]], + uint lane [[thread_index_in_simdgroup]], + uint sg [[simdgroup_index_in_threadgroup]], + uint3 tg [[threadgroup_position_in_grid]]) { + const uint row = tg.y; + const uint col = tg.x * 4u + sg; + if (row >= a.rows || col >= a.n) return; + const uint expert = routes[row]; + if (expert >= a.experts) 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 cb = col / 16u, cc = col & 15u, q = cc & 7u; + const device half* xr = x + ulong(row) * a.k; + float acc[8] = {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}; + uint slot = 0u; + for (uint k = lane; k < a.k; k += 32u) { + // The inverse of the tile's state map: (row-in-tile r, column c) -> the stream position p. + const uint b = k / 16u, r = k % 16u; + const uint u = (r >> 3) & 1u, m = (r >> 1) & 3u, rb = r & 1u; + const uint e = 2u * u + rb + 4u * (cc >> 3); + const uint p = 8u * (4u * q + m) + e; + const device ushort* tile = reinterpret_cast(data + ulong(b) * ks + ulong(cb) * ns); + const ushort s = tf_exl3_mapped_state(tile, tf_exl3_map_for(p, halves)); + const float v = float(tf_exl3_table_value(table, s, codebook)); + acc[slot] = fma(float(xr[k]), v, acc[slot]); + slot = (slot + 1u) & 7u; + } + float t = ((acc[0] + acc[1]) + (acc[2] + acc[3])) + ((acc[4] + acc[5]) + (acc[6] + acc[7])); + t += simd_shuffle_xor(t, 16u); + t += simd_shuffle_xor(t, 8u); + t += simd_shuffle_xor(t, 4u); + t += simd_shuffle_xor(t, 2u); + t += simd_shuffle_xor(t, 1u); + if (lane == 0u) sums[ulong(row) * a.n + col] = t; +} + +#ifndef TF_AFF_WARPS +#define TF_AFF_WARPS 16 +#endif + +// ROUND-445 bench-only arm: THE 3-BIT AFFINE TILE BODY, in our own geometry. The price above says the affine +// value path (code*scale, 2 ops) beats the trellis value path (hash + byte sum + LUT, ~7) only at the verify's +// slot counts, and the twin that priced it pays 4.5 bits a weight and a 36-group hazard at k = 2304. This body +// is what a repack would actually dispatch: a 16-column x 16-k tile of straight 3-bit codes (256 codes in +// 96 bytes, no bit sharing), group-64 bf16 scales, our sixteen-warp k split, and the fma body's activation +// reads and reduction. Codes are exact integers times their group's scale; the trellis decode is gone. +kernel void tf_affine_tile3_nax(const device half* x [[buffer(0)]], + const device uchar* codes [[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* scales [[buffer(7)]], + uint lane [[thread_index_in_simdgroup]], + uint sg [[simdgroup_index_in_threadgroup]], + uint3 tg [[threadgroup_position_in_grid]]) { + 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; + 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 blocks = a.k / 16u; + const uint G = a.k / 64u; + const uint W = TF_AFF_WARPS; + const uint b0 = blocks * sg / W, b1 = blocks * (sg + 1u) / W; + // The lane's eight codes are one 24-bit run of the tile: words (3L)/4 and +1, at a byte phase of 3L mod 4. + const uint w0i = (3u * lane) / 4u, sh = 8u * (3u * lane & 3u); + const uint cn = lane / 4u, cf = cn + 8u; + const device half* scn = scales + (ulong(expert) * a.n + nb + cn) * G; + const device half* scf = scales + (ulong(expert) * a.n + nb + cf) * G; + const device half* xr = x + ulong(row) * a.k; + float acc[8] = {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}; + float sn = 0.0f, sf = 0.0f; + // The next block's two words are loaded a block early (the shipped body's own prefetch): without it every + // block's DRAM latency is exposed once and the body runs at a third of its rate. + const ulong base_nb = ulong(nb / 16u) * ns; + uint lo = 0u, hi = 0u; + { + const device uint* t0 = reinterpret_cast(data + ulong(b0) * ks + base_nb); + lo = t0[w0i]; + hi = t0[w0i + 1u]; + } + for (uint bb = b0; bb < b1; ++bb) { + const uint kb = bb * 16u; + const uint c0 = lo, c1 = hi; + if (bb + 1u < b1) { + const device uint* tn = reinterpret_cast(data + ulong(bb + 1u) * ks + base_nb); + lo = tn[w0i]; + hi = tn[w0i + 1u]; + } + const uint funnel = sh == 0u ? c0 : ((c0 >> sh) | (c1 << ((32u - sh) & 31u))); + if ((bb & 3u) == 0u) { + sn = float(scn[bb / 4u]); + sf = float(scf[bb / 4u]); + } + const device half* xrow = xr + kb + 2u * (lane & 3u); + const half2 xa = *(const device half2*)xrow; + const half2 xb = *(const device half2*)(xrow + 8); + const float x0 = float(xa.x), x1 = float(xa.y), x2 = float(xb.x), x3 = float(xb.y); + TF_UNROLL + for (uint k = 0; k < 8; ++k) { + const float code = float((funnel >> (3u * k)) & 7u); + const float scale = k < 4u ? sn : sf; + 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, code * scale, acc[k]); + } + } + float acc0 = (acc[0] + acc[1]) + (acc[2] + acc[3]); + float acc1 = (acc[4] + acc[5]) + (acc[6] + acc[7]); + threadgroup float red[TF_AFF_WARPS][64]; + red[sg][lane] = acc0; + red[sg][32 + lane] = acc1; + threadgroup_barrier(mem_flags::mem_threadgroup); + if (sg != 0u) return; + acc0 = 0.0f; + acc1 = 0.0f; + for (uint w = 0; w < W; ++w) { + acc0 += red[w][lane]; + acc1 += red[w][32 + 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(row) * a.n + nb + lane / 4u] = acc0; + sums[ulong(row) * a.n + nb + 8u + lane / 4u] = acc1; + } +} + +// ROUND-448 bench-only arm: THE FAIR 3-BIT AFFINE TILE BODY, rebuilt on its own geometry. ROUND-445's tile3 +// instrument was never a price: its bench arm handed the body a 288-byte tile stride (`halves * 8 * halves`) for +// a 96-byte 16x16 3-bit tile, and the shared timer then repointed its descriptors at the EXL3 trellis copies, so +// the body read three times its packed bytes out of a buffer it did not own. This body is the form a repack +// would dispatch: a 16-column x 16-k tile of straight 3-bit codes (256 codes, 96 bytes, no bit sharing), +// group-64 bf16 scales, W warps a threadgroup splitting k, register-only accumulators, a two-block prefetch, +// and no threadgroup round trip at W = 1. The code index of (k, col) inside a tile is +// 32*(col & 7) + 8*((k >> 1) & 3) + ((k & 1) + 2*((k >> 3) & 1)) + 4*((col >> 3) & 1), +// which is the pack's own choice; `tf_affine_tile3_ref` decodes the same bytes by the same map. +#ifndef TF_AFF_WARPS +#define TF_AFF_WARPS 16 +#endif + +kernel void tf_affine_tile3b_nax(const device half* x [[buffer(0)]], + const device uchar* codes [[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* scales [[buffer(7)]], + uint lane [[thread_index_in_simdgroup]], + uint sg [[simdgroup_index_in_threadgroup]], + uint3 tg [[threadgroup_position_in_grid]]) { + 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; + 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 blocks = a.k / 16u; + const uint G = a.k / 64u; + const uint W = TF_AFF_WARPS; + const uint b0 = blocks * sg / W, b1 = blocks * (sg + 1u) / W; + if (b0 >= b1) return; + // The lane's eight codes are one 24-bit run: words (3L)/4 and +1 at a byte phase of 3L mod 4. + const uint w0i = (3u * lane) / 4u, sh = 8u * (3u * lane & 3u); + const uint cn = lane / 4u, cf = cn + 8u; + const device half* scn = scales + (ulong(expert) * a.n + nb + cn) * G; + const device half* scf = scales + (ulong(expert) * a.n + nb + cf) * G; + const device half* xr = x + ulong(row) * a.k; + const ulong base_nb = ulong(nb / 16u) * ns; + float acc[8] = {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}; + float sn = 0.0f, sf = 0.0f; + uint c0 = 0u, c1 = 0u, n0 = 0u, n1 = 0u; + { + const device uint* t0 = reinterpret_cast(data + ulong(b0) * ks + base_nb); + c0 = t0[w0i]; + c1 = t0[w0i + 1u]; + } + if (b0 + 1u < b1) { + const device uint* t1 = reinterpret_cast(data + ulong(b0 + 1u) * ks + base_nb); + n0 = t1[w0i]; + n1 = t1[w0i + 1u]; + } + for (uint bb = b0; bb < b1; ++bb) { + const uint l0 = c0, l1 = c1; + c0 = n0; + c1 = n1; + if (bb + 2u < b1) { + const device uint* tn = reinterpret_cast(data + ulong(bb + 2u) * ks + base_nb); + n0 = tn[w0i]; + n1 = tn[w0i + 1u]; + } else { + n0 = 0u; + n1 = 0u; + } + const uint funnel = sh == 0u ? l0 : ((l0 >> sh) | (l1 << ((32u - sh) & 31u))); + if ((bb & 3u) == 0u) { + sn = float(scn[bb / 4u]); + sf = float(scf[bb / 4u]); + } + const device half* xrow = xr + bb * 16u + 2u * (lane & 3u); + const half2 xa = *(const device half2*)xrow; + const half2 xb = *(const device half2*)(xrow + 8); + const float x0 = float(xa.x), x1 = float(xa.y), x2 = float(xb.x), x3 = float(xb.y); + TF_UNROLL + for (uint k = 0; k < 8; ++k) { + const float code = float((funnel >> (3u * k)) & 7u); + const float scale = k < 4u ? sn : sf; + 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, code * scale, acc[k]); + } + } + float t0 = (acc[0] + acc[1]) + (acc[2] + acc[3]); + float t1 = (acc[4] + acc[5]) + (acc[6] + acc[7]); + t0 += simd_shuffle_xor(t0, 1u); + t0 += simd_shuffle_xor(t0, 2u); + t1 += simd_shuffle_xor(t1, 1u); + t1 += simd_shuffle_xor(t1, 2u); + if (W == 1u) { + if ((lane & 3u) == 0u) { + sums[ulong(row) * a.n + nb + lane / 4u] = t0; + sums[ulong(row) * a.n + nb + 8u + lane / 4u] = t1; + } + return; + } + threadgroup float red[TF_AFF_WARPS][64]; + red[sg][lane] = t0; + red[sg][32u + lane] = t1; + threadgroup_barrier(mem_flags::mem_threadgroup); + if (sg != 0u) return; + float u0 = 0.0f, u1 = 0.0f; + for (uint w = 0; w < W; ++w) { + u0 += red[w][lane]; + u1 += red[w][32u + lane]; + } + if ((lane & 3u) == 0u) { + sums[ulong(row) * a.n + nb + lane / 4u] = u0; + sums[ulong(row) * a.n + nb + 8u + lane / 4u] = u1; + } +} + +kernel void tf_affine_fill_one(device ushort* t [[buffer(0)]], + uint gid [[thread_position_in_grid]]) { + t[gid] = 0x3C00u; +} + +// ROUND-448 bench-only: a scale fixture with a known pattern -- group g gets 1.0 at even g and 2.0 at odd g, +// so a body that mis-indexes the group changes its answer by a measurable amount. +kernel void tf_affine_fill_alt(device ushort* t [[buffer(0)]], + constant uint& G [[buffer(1)]], + uint gid [[thread_position_in_grid]]) { + t[gid] = ((gid / G) & 1u) == 0u ? 0x3C00u : 0x4000u; +} + + +// ROUND-448 bench-only arm: THE 3-BIT AFFINE TILE BODY WITH A PER-GROUP BIAS -- the quality-viable form. A +// min/max affine quantizer needs both a scale and a bias (eight uniform levels spanning the group's range), and +// the comparator's own tile_qmv body carries scales AND biases. Buffer 7 holds them interleaved per group: +// [scale, bias] at 2*((expert*n + col)*G + g). The extra per-weight op is one fma: code*scale + bias. +kernel void tf_affine_tile3s_nax(const device half* x [[buffer(0)]], + const device uchar* codes [[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* scales [[buffer(7)]], + uint lane [[thread_index_in_simdgroup]], + uint sg [[simdgroup_index_in_threadgroup]], + uint3 tg [[threadgroup_position_in_grid]]) { + 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; + 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 blocks = a.k / 16u; + const uint G = a.k / 64u; + const uint W = TF_AFF_WARPS; + const uint b0 = blocks * sg / W, b1 = blocks * (sg + 1u) / W; + if (b0 >= b1) return; + const uint w0i = (3u * lane) / 4u, sh = 8u * (3u * lane & 3u); + const uint cn = lane / 4u, cf = cn + 8u; + const device half* scn = scales + 2ull * (ulong(expert) * a.n + nb + cn) * G; + const device half* scf = scales + 2ull * (ulong(expert) * a.n + nb + cf) * G; + const device half* xr = x + ulong(row) * a.k; + const ulong base_nb = ulong(nb / 16u) * ns; + float acc[8] = {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}; + float sn = 0.0f, sf = 0.0f, bn = 0.0f, bf = 0.0f; + uint c0 = 0u, c1 = 0u, n0 = 0u, n1 = 0u; + { + const device uint* t0 = reinterpret_cast(data + ulong(b0) * ks + base_nb); + c0 = t0[w0i]; + c1 = t0[w0i + 1u]; + } + if (b0 + 1u < b1) { + const device uint* t1 = reinterpret_cast(data + ulong(b0 + 1u) * ks + base_nb); + n0 = t1[w0i]; + n1 = t1[w0i + 1u]; + } + for (uint bb = b0; bb < b1; ++bb) { + const uint l0 = c0, l1 = c1; + c0 = n0; + c1 = n1; + if (bb + 2u < b1) { + const device uint* tn = reinterpret_cast(data + ulong(bb + 2u) * ks + base_nb); + n0 = tn[w0i]; + n1 = tn[w0i + 1u]; + } else { + n0 = 0u; + n1 = 0u; + } + const uint funnel = sh == 0u ? l0 : ((l0 >> sh) | (l1 << ((32u - sh) & 31u))); + if ((bb & 3u) == 0u) { + const uint gi = 2u * (bb / 4u); + sn = float(scn[gi]); + bn = float(scn[gi + 1u]); + sf = float(scf[gi]); + bf = float(scf[gi + 1u]); + } + const device half* xrow = xr + bb * 16u + 2u * (lane & 3u); + const half2 xa = *(const device half2*)xrow; + const half2 xb = *(const device half2*)(xrow + 8); + const float x0 = float(xa.x), x1 = float(xa.y), x2 = float(xb.x), x3 = float(xb.y); + TF_UNROLL + for (uint k = 0; k < 8; ++k) { + const float code = float((funnel >> (3u * k)) & 7u); + const float scale = k < 4u ? sn : sf; + const float bias = k < 4u ? bn : bf; + 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, fma(code, scale, bias), acc[k]); + } + } + float t0 = (acc[0] + acc[1]) + (acc[2] + acc[3]); + float t1 = (acc[4] + acc[5]) + (acc[6] + acc[7]); + t0 += simd_shuffle_xor(t0, 1u); + t0 += simd_shuffle_xor(t0, 2u); + t1 += simd_shuffle_xor(t1, 1u); + t1 += simd_shuffle_xor(t1, 2u); + if (W == 1u) { + if ((lane & 3u) == 0u) { + sums[ulong(row) * a.n + nb + lane / 4u] = t0; + sums[ulong(row) * a.n + nb + 8u + lane / 4u] = t1; + } + return; + } + threadgroup float red[TF_AFF_WARPS][64]; + red[sg][lane] = t0; + red[sg][32u + lane] = t1; + threadgroup_barrier(mem_flags::mem_threadgroup); + if (sg != 0u) return; + float u0 = 0.0f, u1 = 0.0f; + for (uint w = 0; w < W; ++w) { + u0 += red[w][lane]; + u1 += red[w][32u + lane]; + } + if ((lane & 3u) == 0u) { + sums[ulong(row) * a.n + nb + lane / 4u] = u0; + sums[ulong(row) * a.n + nb + 8u + lane / 4u] = u1; + } +} + +// ROUND-448 bench-only: the scalar reference for `tf_affine_tile3b_nax`. One thread an output, the same bytes, +// the same map, a serial k walk: a mismatch is a port bug in the warp body, not a numerics class. +kernel void tf_affine_tile3_ref(const device half* x [[buffer(0)]], + const device uchar* codes [[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* scales [[buffer(7)]], + uint2 gid [[thread_position_in_grid]]) { + const uint col = gid.x, row = gid.y; + if (row >= a.rows || col >= a.n) return; + const uint expert = routes[row]; + if (expert >= a.experts) 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 p = col & 7u, h = (col >> 3u) & 1u, cb = col / 16u; + const uint G = a.k / 64u; + const device half* sc = scales + (ulong(expert) * a.n + col) * G; + const device half* xr = x + ulong(row) * a.k; + const ulong tile = ulong(cb) * ns; + float acc = 0.0f; + for (uint k = 0; k < a.k; ++k) { + const uint b = k / 16u, kk = k & 15u; + const uint q = (kk >> 1) & 3u; + const uint j = (kk & 1u) + 2u * ((kk >> 3u) & 1u) + 4u * h; + const uint idx = 32u * p + 8u * q + j; + const uint bit = 3u * idx; + const device uchar* tp = data + ulong(b) * ks + tile; + // A 3-bit code can straddle a 32-bit word, so read the two bytes that hold it (a code never starts in the + // last byte of a tile at an offset that would leave the 96-byte tile). + const device uchar* bp = tp + (bit >> 3u); + const uint two = uint(bp[0]) | (uint(bp[1]) << 8); + const uint code = (two >> (bit & 7u)) & 7u; + acc = fma(float(xr[k]), float(code) * float(sc[k >> 6u]), acc); + } + sums[ulong(row) * a.n + col] = acc; +} + +// ROUND-445 bench-only arm: THE 3-BIT AFFINE BODY ON A COLUMN-SEQUENTIAL PACK. The repack can order the pack +// any way, so this is the form the comparator's plan actually needs: a column's k-run is contiguous (a +// 32-code block is 12 aligned bytes), the lanes walk blocks, and the 16-column bit-sharing tile -- and its +// 13.8 KB k-stride -- are gone. Four warps a threadgroup, a warp a column; codes are exact integers times +// their group-64 scale. Timing arm only; no engine path selects it. +kernel void tf_affine_col3_nax(const device half* x [[buffer(0)]], + const device uchar* codes [[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* scales [[buffer(7)]], + uint lane [[thread_index_in_simdgroup]], + uint sg [[simdgroup_index_in_threadgroup]], + uint3 tg [[threadgroup_position_in_grid]]) { + const uint row = tg.y; + const uint col = tg.x * 4u + sg; + if (row >= a.rows || col >= a.n) return; + const uint expert = routes[row]; + if (expert >= a.experts) return; + const uint blocks = a.k / 32u; + const device uint* colp = reinterpret_cast( + descriptors[expert].trellis + ulong(col) * ulong(blocks) * 12u); + const device half* scp = scales + (ulong(expert) * a.n + col) * (a.k / 64u); + const device half* xr = x + ulong(row) * a.k; + float acc[8] = {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}; + for (uint b = lane; b < blocks; b += 32u) { + const uint k0 = b * 32u; + const uint w0 = colp[3u * b], w1 = colp[3u * b + 1u], w2 = colp[3u * b + 2u]; + const float s = float(scp[b >> 1u]); + const device half* xb = xr + k0; + TF_UNROLL + for (uint i = 0; i < 32; ++i) { + const uint bit = 3u * i, word = bit >> 5, sh = bit & 31u; + const uint wc = word == 0u ? w0 : (word == 1u ? w1 : w2); + const uint wn = word == 0u ? w1 : (word == 1u ? w2 : 0u); + const uint carry = sh == 0u ? 0u : (wn << (32u - sh)); + const float code = float(((wc >> sh) | carry) & 7u); + acc[i & 7u] = fma(float(xb[i]), code * s, acc[i & 7u]); + } + } + float t = ((acc[0] + acc[1]) + (acc[2] + acc[3])) + ((acc[4] + acc[5]) + (acc[6] + acc[7])); + t += simd_shuffle_xor(t, 16u); + t += simd_shuffle_xor(t, 8u); + t += simd_shuffle_xor(t, 4u); + t += simd_shuffle_xor(t, 2u); + t += simd_shuffle_xor(t, 1u); + if (lane == 0u) sums[ulong(row) * a.n + col] = t; +} + +// ROUND-318 queue item 2: the routed 64 x 128 tile on four warps. One warp owns sixteen rows and both sixty-four +// column halves, so a threadgroup decodes the same 16 x 128 weight tile that nax3's eight warps decode, but the +// activation fragment for those sixteen rows is read once instead of twice -- the LSU constraint ROUND-309 +// priced. Eight accumulator fragments a lane (64 float registers). k order, MMA order and per-value arithmetic +// are nax5's, so the output is bit-identical; only the dispatch geometry moves. +template +inline void tf_exl3_prefill_body_wide(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 rb = tg.y * 64u, nb = tg.x * 128u; + 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 uint didx = a.indexed ? tile_expert : 0; + const device uchar* data = a.indexed ? descriptors[didx].trellis : trellis; + const ulong ks = a.indexed ? descriptors[didx].tile_k_stride : a.tile_k_stride; + const ulong ns = a.indexed ? descriptors[didx].tile_n_stride : a.tile_n_stride; + const uint halves = a.indexed ? descriptors[didx].halves : a.halves; + const uint codebook = a.indexed ? descriptors[didx].codebook : a.codebook; + const short2 home = frag_home(ushort(lane)); + const uint rows_here = min(64u, a.rows - rb); + const uint cols_here = min(128u, a.n - nb); + // Four warps: this warp is row group `sg` and decodes column tiles h and h+4 of the 128-column group. + const uint h = sg; + const uint p0 = lane * 8u; + uint at[8], off[8], sh[8], rel[8]; + const uint words = 4 * halves; + const uint wi0 = tf_exl3_map_for(p0, halves) & 63u; + { + const uint ring = 128 * halves; + const uint cur = (wi0 << 5) | ((tf_exl3_map_for(p0, halves) >> 6) & 31u); + TF_UNROLL + for (uint k = 0; k < 8; ++k) { + const uint p = p0 + k, l = p / 8, e = p % 8; + at[k] = (2 * (l % 4) + (e & 1u) + 8 * ((e >> 1) & 1u)) * 128u + h * 16u + (l / 4 + 8 * (e >> 2)); + uint c8 = cur + k * (halves >> 1); + if (c8 >= ring) c8 -= ring; + const uint wi = c8 >> 5; + off[k] = c8 & 31u; + sh[k] = (32u - off[k]) & 31u; + rel[k] = wi >= wi0 ? wi - wi0 : wi + words - wi0; + } + } + const uint a1 = wi0 + 1 < words ? wi0 + 1 : wi0 + 1 - words; + const uint a2 = wi0 + 2 < words ? wi0 + 2 : wi0 + 2 - words; + const uint a3 = wi0 + 3 < words ? wi0 + 3 : wi0 + 3 - words; + uint p0v = 0, p1v = 0, p2v = 0, p3v = 0, q0v = 0, q1v = 0, q2v = 0, q3v = 0; + if (Fast) { + const device ushort* t0 = reinterpret_cast(data + ulong(nb / 16 + h) * ns); + const device ushort* t1 = reinterpret_cast(data + ulong(nb / 16 + h + 4) * ns); + p0v = tf_exl3_word(t0, wi0); p1v = tf_exl3_word(t0, a1); p2v = tf_exl3_word(t0, a2); p3v = tf_exl3_word(t0, a3); + q0v = tf_exl3_word(t1, wi0); q1v = tf_exl3_word(t1, a1); q2v = tf_exl3_word(t1, a2); q3v = tf_exl3_word(t1, a3); + } + frag lo0 = frag(0), hi0 = frag(0), lo1 = frag(0), hi1 = frag(0); + frag lo2 = frag(0), hi2 = frag(0), lo3 = frag(0), hi3 = frag(0); + for (uint kb = 0; kb < a.k; kb += 16) { + { + const device ushort* t0 = reinterpret_cast(data + ulong(kb / 16) * ks + ulong(nb / 16 + h) * ns); + const device ushort* t1 = reinterpret_cast(data + ulong(kb / 16) * ks + ulong(nb / 16 + h + 4) * ns); + if (Fast and (halves & 1u) == 0 and halves <= 16) { + const uint w0 = p0v, w1 = p1v, w2 = p2v, w3 = p3v; + const uint v0 = q0v, v1 = q1v, v2 = q2v, v3 = q3v; + const uint nkb = kb + 16; + if (nkb < a.k) { + const device ushort* n0 = reinterpret_cast(data + ulong(nkb / 16) * ks + ulong(nb / 16 + h) * ns); + const device ushort* n1 = reinterpret_cast(data + ulong(nkb / 16) * ks + ulong(nb / 16 + h + 4) * ns); + p0v = tf_exl3_word(n0, wi0); p1v = tf_exl3_word(n0, a1); p2v = tf_exl3_word(n0, a2); p3v = tf_exl3_word(n0, a3); + q0v = tf_exl3_word(n1, wi0); q1v = tf_exl3_word(n1, a1); q2v = tf_exl3_word(n1, a2); q3v = tf_exl3_word(n1, a3); + } + TF_UNROLL + for (uint k = 0; k < 8; ++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); + const uint loq = rel[k] == 0 ? v0 : rel[k] == 1 ? v1 : v2; + const uint hiq = rel[k] == 0 ? v1 : rel[k] == 1 ? v2 : v3; + const uint carryq = (hiq >> sh[k]) & (0u - uint(off[k] != 0)); + wx[at[k] + 64u] = tf_exl3_value(ushort(((loq << off[k]) | carryq) >> 16), codebook); + } + } else { + TF_UNROLL + for (uint k = 0; k < 8; ++k) { + const uint p = p0 + k; + wx[at[k]] = tf_exl3_value(tf_exl3_mapped_state(t0, tf_exl3_map_for(p, halves)), codebook); + wx[at[k] + 64u] = tf_exl3_value(tf_exl3_mapped_state(t1, tf_exl3_map_for(p, halves)), codebook); + } + } + } + frag av; + tf_frag_get_dev4(av, (const device half*)x, int(a.k), int(rb + sg * 16), int(kb), home, int(rb + rows_here)); + threadgroup_barrier(mem_flags::mem_threadgroup); + { + frag b0, b1; + tf_frag_get_tg4(b0, wx, 128, 0, 0, home); + tf_frag_get_tg4(b1, wx, 128, 0, 16, home); + mma_16x32(lo0, hi0, av, b0, b1); + tf_frag_get_tg4(b0, wx, 128, 0, 32, home); + tf_frag_get_tg4(b1, wx, 128, 0, 48, home); + mma_16x32(lo1, hi1, av, b0, b1); + tf_frag_get_tg4(b0, wx, 128, 0, 64, home); + tf_frag_get_tg4(b1, wx, 128, 0, 80, home); + mma_16x32(lo2, hi2, av, b0, b1); + tf_frag_get_tg4(b0, wx, 128, 0, 96, home); + tf_frag_get_tg4(b1, wx, 128, 0, 112, home); + mma_16x32(lo3, hi3, av, b0, b1); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + } + const int r0 = int(rb + sg * 16); + const int c0 = int(nb); + frag_put_in(lo0, sums, int(a.n), r0, c0, home, int(rb + rows_here), int(nb + cols_here)); + frag_put_in(hi0, sums, int(a.n), r0, c0 + 16, home, int(rb + rows_here), int(nb + cols_here)); + frag_put_in(lo1, sums, int(a.n), r0, c0 + 32, home, int(rb + rows_here), int(nb + cols_here)); + frag_put_in(hi1, sums, int(a.n), r0, c0 + 48, home, int(rb + rows_here), int(nb + cols_here)); + frag_put_in(lo2, sums, int(a.n), r0, c0 + 64, home, int(rb + rows_here), int(nb + cols_here)); + frag_put_in(hi2, sums, int(a.n), r0, c0 + 80, home, int(rb + rows_here), int(nb + cols_here)); + frag_put_in(lo3, sums, int(a.n), r0, c0 + 96, home, int(rb + rows_here), int(nb + cols_here)); + frag_put_in(hi3, sums, int(a.n), r0, c0 + 112, home, int(rb + rows_here), int(nb + cols_here)); +} + +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); +} + + +// ROUND-389: the OCCUPANCY-KEEPING FORM -- the routed prompt tile with the activation staged in threadgroup +// memory, once a k block, and SHARED by the two column groups of a row group (one column tile's activation read +// shared by two column groups; the fragment in threadgroup memory; one more barrier a block -- here the SAME +// barrier that publishes the weight tile, so the block's barrier count is unchanged). The two column groups of a +// row group read the device ONCE and read the staged fragment back, so the activation's device traffic falls by +// half against the same tile widened to 128 columns. The values, their order, the k order and the MMA order are +// the shipped body's, so the output is bit-identical. +kernel void tf_exl3_matmul_prefill_nax61(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 * 2 + 4 * 16 * 16]; + tf_exl3_prefill_body(wx, x, trellis, sums, a, routes, descriptors, nullptr, nullptr, lane, sg, tid, tptg.x, tg); +} + +// ROUND-389: the ABLATION -- the activation fragment is read ONCE, before the k loop, and reused. A diagnostic: +// the output differs by construction, and the delta against the same body reading it every block IS the +// activation's per-block cost (the record's instrument first: the activation read's share of the routed tile). +kernel void tf_exl3_matmul_prefill_nax62(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); +} + +// ROUND-389: the CONTROL for nax61 -- the same 128-column tile with the shipped per-warp activation read (so +// the two arms differ only in the staging). Bit-identical to nax48 by construction. +kernel void tf_exl3_matmul_prefill_nax63(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); +} + +// ROUND-346: the engine's routed 64 x 64 prompt tile with the funnel read -- the comparator's structure (two +// stream words a lane, the eight windows at one shift a state), on our map and our layout. The values, their order +// and the k order are the shipped body's, so the output is bit-identical; only the word traffic and the cursor's +// select chain leave. +kernel void tf_exl3_matmul_prefill_nax40(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 same body with the mul1 value dropped (the raw state stored): the window extraction and the stores without +// the codebook arithmetic. A diagnostic -- it prices the value path inside the decode; its output differs. +kernel void tf_exl3_matmul_prefill_nax41(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); +} + +// ROUND-346: the engine's routed 64 x 64 prompt tile with the funnel read -- the comparator's structure (the +// two-word funnel and the eight windows at compile-time shifts, mlx-serve's dsv41_exl3_mul1h_k3 decode kernel, +// MIT/Apache-2.0, attribution in the kernel) on our map and our ring. The values, their order and the k order +// are the shipped body's, so the output is bit-identical; only the word traffic and the cursor's select chain +// leave. The funnel needs the routed pack's width (halves = 6, three bits a state); at any other width the +// kernel reads the shipped path's four words and decodes as before. +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); +} + +// ROUND-347: the funnel read with the value read from the resident codebook table (buffer 7). One load a state +// instead of the mul1's ALU. The table holds the format's own decoder's values, so the values, their order and +// the k order are the shipped body's: bit-identical. +kernel void tf_exl3_matmul_prefill_nax43(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]], + 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, table, nullptr, lane, sg, tid, tptg.x, tg); +} + +// ROUND-347: the funnel read with the value read from the 1024-entry threadgroup LUT (the comparator's prefill +// kernel's read). The LUT's entries are the table's, so the values are the same, bit-identical. +kernel void tf_exl3_matmul_prefill_nax44(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]; + threadgroup half lut[1024]; + const half scale = as_type(ushort(0x1EEEu)); + const half bias = as_type(ushort(0xC931u)); + TF_UNROLL + for (uint j = 0; j < 8u; ++j) lut[tid + 128u * j] = half(fma(float(tid + 128u * j + 1024u), float(scale), float(bias))); + threadgroup_barrier(mem_flags::mem_threadgroup); + tf_exl3_prefill_body(wx, x, trellis, sums, a, routes, descriptors, nullptr, lut, lane, sg, tid, tptg.x, tg); +} + +// ROUND-347: the funnel read with the value read cheaply -- a diagnostic; its output differs by construction. +kernel void tf_exl3_matmul_prefill_nax47(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); +} + +// ROUND-347: the double-buffered routed tile with the funnel read. The double-buffered body decodes the next k +// block into the tile the multiply is not reading and issues the multiply before that decode, so the tensor units +// and the codebook ALU are in flight together; the funnel makes the decode cheap enough for the overlap to pay. +kernel void tf_exl3_matmul_prefill_nax46(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 * 16 * 64]; + tf_exl3_prefill_body_db<4, 1, true, 4, false, true>(wx, x, trellis, sums, a, routes, descriptors, nullptr, lane, sg, tid, tptg.x, tg); +} + +// ROUND-347: the routed 64 x 64 prompt tile with the funnel read and the padded rows skipped. The engine's +// grouping pads each expert's block to sixty-four rows, so a 3,619-token prompt's 21,714 routed rows are +// dispatched as 45,888 rows -- 2.11 times the real work; the padding rows carry the sentinel expert id, so a warp +// reads its own sixteen route ids and skips its multiply when they are all padding. The real rows' values, their +// order and the k order are the shipped body's, so the reply is bit-identical. +// ROUND-390: the routed tile's store path, priced. nax64 -- the eight decoded values written CONTIGUOUSLY, +// one lane's run of eight halves: the comparator's store form (a lane's values go out as wide stores, not as +// eight scattered two-byte stores). The tile's contents change, so the output differs by construction. +kernel void tf_exl3_matmul_prefill_nax64(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); +} + +// ROUND-390: nax65 -- the DECODE KEPT, the eight scattered stores GONE (the values are folded into a register +// accumulator instead). The floor of the store path. A diagnostic: the tile is never written. +kernel void tf_exl3_matmul_prefill_nax65(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); +} + +// ROUND-390: nax66 -- the SHIPPED body plus the Mode 1 accumulator: the calibration for the accumulator's +// own cost, so the store path's price is nax66 - nax65. +kernel void tf_exl3_matmul_prefill_nax66(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); +} + +// ROUND-390: nax67 -- the shipped body with the codebook arithmetic dropped (the raw window stored, the +// extraction and the stores kept). The value path's price, in the shipped configuration. A diagnostic. +kernel void tf_exl3_matmul_prefill_nax67(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); +} + +// ROUND-390: nax68 -- the eight stores KEPT, the EXTRACTION dropped (the stored value is a cheap function of +// the k block, so the stores stay in the loop). The extraction's price, in the shipped configuration. +kernel void tf_exl3_matmul_prefill_nax68(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); +} + +// ROUND-352: the routed 64x64 prompt tile with the stream word read as one 4-byte load -- the comparator's +// read (its lane reads 32-bit stream words; ours read the same bytes as two 2-byte loads, so a lane issued +// four memory instructions a block where it now issues two). The values, their order, the k order and the +// MMA order are nax48's, so the output is bit-identical. The kernel falls back to the shipped read when the +// tile's byte address is not 4-byte aligned. +kernel void tf_exl3_matmul_prefill_nax57(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]; + // The tile's byte address: the expert's trellis plus the tile's k and n offsets. A 4-byte load needs it + // 4-byte aligned, and the strides must keep it there. + 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 device uchar* data = (a.indexed != 0u) ? descriptors[e].trellis : trellis; + const ulong ks = (a.indexed != 0u) ? descriptors[e].tile_k_stride : a.tile_k_stride; + const ulong ns = (a.indexed != 0u) ? descriptors[e].tile_n_stride : a.tile_n_stride; + const bool wide = (reinterpret_cast(data) & 3ul) == 0ul and (ks & 3ul) == 0ul and (ns & 3ul) == 0ul; + if (wide) { + 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); + } +} + +// ROUND-390: the store path's modes on the ENGINE's body (nax59: the funnel path as its only path, the +// twenty-four dead cursor registers not computed -- ROUND-352's landing, the default). The store path's +// prices are only worth anything on the body the engine runs. +// nax69: the eight decoded values written CONTIGUOUSLY, one lane's run of eight halves -- the comparator's +// store form (a lane's values go out as wide stores, not as eight scattered two-byte stores). +// nax70: the decode KEPT, the eight scattered stores GONE (the values are folded into a register +// accumulator). The floor of the store path. +// nax71: the shipped store PLUS the accumulator -- the calibration for the accumulator's own cost. +// nax72: the codebook arithmetic dropped (the extraction and the stores kept) -- the value path's price. +// nax73: the eight stores KEPT, the EXTRACTION dropped -- the extraction's price. +// nax69..nax73 are diagnostics: their outputs differ by construction. +kernel void tf_exl3_matmul_prefill_nax69(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_nax70(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_nax71(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_nax72(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_nax73(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); +} + +// ROUND-352: the routed 64x64 prompt tile with the funnel path as the only path (nax59). The cursor arrays +// the Fast path needs -- off, sh and rel, twenty-four registers -- are dead in the funnel path but live +// across the k loop, so the shipped body carries them for nothing. Here they are not computed. The values, +// their order, the k order and the MMA order are nax48's, so the output is bit-identical. +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[16 * 64]; + // The funnel path is the one the routed pack's width (halves = 6) takes; the expert's own descriptor says + // so, so the kernel picks the specialised body per expert and falls back to the shipped one otherwise. + 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) { + 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); + } +} + +// ROUND-409: THE EXPERT'S SLAB DECODED ONCE FOR THE TILE'S ROWS (nax76). The plan's padding is ~30 % of the +// routed tile because the WEIGHT DECODE IS PER TILE: an expert with more than sixty-four rows spans several +// tiles and its slab is decoded once a tile, so the decode is paid again for every row block the expert has. +// This body is ONE HUNDRED AND TWENTY-EIGHT ROWS TALL with TWO ROW GROUPS A WARP (four warps a threadgroup, +// eight states a lane, the same funnel, the same two words a lane): the decode is amortised over eight row +// groups instead of four, so the plan's own histogram grouped at 128 rows gives 407 working tiles against the +// 64-row plan's 537 -- 24 % less weight decode. The values, their order, the k order and the MMA order are the +// shipped body's, so the output is bit-identical. +kernel void tf_exl3_matmul_prefill_nax76(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]; + const uint rb = tg.y * 128u; + 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) { + 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); + } +} + +// ROUND-409: the same form one step further -- TWO HUNDRED AND FIFTY-SIX ROWS TALL with FOUR ROW GROUPS A +// WARP (nax77). The plan's own histogram grouped at 256 rows gives 370 working tiles (31 % less weight decode +// than the 64-row plan's 537; the ideal, one decode an expert, is 359). Sixteen accumulator fragments a lane: +// the register wall is the price of the form, and the bench prices it. +kernel void tf_exl3_matmul_prefill_nax77(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]; + const uint rb = tg.y * 256u; + 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) { + 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); + } +} + +// ROUND-348: the routed 128-row tile (eight row groups, eight warps). The grouped plan pads each expert's block +// to a multiple of the tile's rows, so a sixty-four-row tile spends a second tile's weight decode on the tail of +// every expert with more than sixty-four rows: at 3,619 tokens the plan dispatches 717 tiles for 384 experts, so +// the routed stage decodes 1.87 times the weights it has to. A 128-row tile halves that (the plan's own bound: +// 384 + (21,714 - 384) / 128 tiles), and the weight decode is per tile, so the tile's decode cost falls with it. +// The eight warps make a lane own four states instead of eight, so the funnel reads a twenty-five-bit run (four +// windows) instead of a thirty-seven-bit one; the values, their order, the k order and the per-row arithmetic are +// the shipped body's, so the reply is bit-identical. +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); +} + +// ROUND-350: the routed 64 x 64 prompt tile with the funnel read and the extraction in thirty-two-bit words +// (the comparator's dig_dec_job structure, MIT/Apache-2.0, NOTICE per-file). The windows, the values, their +// order and the k order are the shipped funnel's, so the output is bit-identical. +kernel void tf_exl3_matmul_prefill_nax50(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); +} + +// ROUND-350: the routed 64 x 64 prompt tile with the funnel read and the block's words delivered by a +// cooperative load and a shuffle (one lane a word loads the block's twenty-four words; the two a lane needs +// arrive by a shuffle). The words, the windows, the values and the order are the shipped funnel's, so the output +// is bit-identical. +kernel void tf_exl3_matmul_prefill_nax52(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); +} + +// ROUND-350: the routed 64 x 64 prompt tile with the funnel read, the grouping's padded rows skipped, and the +// block's words delivered by a cooperative load and a shuffle (one lane a word loads the block's twenty-four +// words; the two a lane needs arrive by a shuffle). The words, the windows, the values and the order are the +// shipped tile's, so the output is bit-identical. +kernel void tf_exl3_matmul_prefill_nax53(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); +} + +// ROUND-350: the routed 128-row tile with a warp that does thirty-two rows (the comparator's NAXTile shape: +// a simdgroup owns thirty-two rows, so the block is decoded by one warp and the lane keeps eight states and +// eight bits a weight). The tile covers twice the rows, so the grouped plan spends half the tiles, and the +// weight fragments are read once for two row groups. The values, their order, the k order and the MMA order per +// output are the shipped tile's, so the output is bit-identical. +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); +} + +// The routed 64 x 128 tile on four warps (ROUND-318's nax37); 128 threads, one 16 x 128 threadgroup tile. +kernel void tf_exl3_matmul_prefill_nax37(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_wide(wx, x, trellis, sums, a, routes, descriptors, 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); +} + +// The routed prompt tile, double-buffered: two 16x128 tiles (8 KB) and one barrier a k block. +kernel void tf_exl3_matmul_prefill_nax7(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 * 16 * 128]; + tf_exl3_prefill_body_db<4, 2, true, 4, false>(wx, x, trellis, sums, a, routes, descriptors, nullptr, lane, sg, tid, tptg.x, tg); +} + +// Diagnostics: nax8 is the same tile with the per-block decode removed (the prologue tile reused), nax9 keeps the +// decode but issues one of the four multiplies. nax7 - nax8 prices the decode, nax8 prices the multiply. +kernel void tf_exl3_matmul_prefill_nax8(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 * 16 * 128]; + tf_exl3_prefill_body_db<4, 2, false, 4, false>(wx, x, trellis, sums, a, routes, descriptors, nullptr, lane, sg, tid, tptg.x, tg); +} + +kernel void tf_exl3_matmul_prefill_nax9(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 * 16 * 128]; + tf_exl3_prefill_body_db<4, 2, true, 1, false>(wx, x, trellis, sums, a, routes, descriptors, nullptr, lane, sg, tid, tptg.x, tg); +} + +// The routed tile with the codebook as a resident table (buffer 7): the mul1 state maps to a half by one load. +kernel void tf_exl3_matmul_prefill_nax10(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)]], + const device half* const table [[buffer(7)]], + 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 * 16 * 128]; + tf_exl3_prefill_body_db<4, 2, true, 4, true>(wx, x, trellis, sums, a, routes, descriptors, table, lane, sg, tid, tptg.x, tg); +} + +// Warp-specialised routed tile: eight warps multiply the current block, eight decode the next into the other +// buffer, so the tensor units and the codebook ALU are in flight on different warps instead of interleaved in one. +template +inline void tf_exl3_prefill_body_ws(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 sg0, uint tid, uint3 tg) { + const uint rb = tg.y * 64u, 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 uint didx = a.indexed ? tile_expert : 0; + const device uchar* data = a.indexed ? descriptors[didx].trellis : trellis; + const ulong ks = a.indexed ? descriptors[didx].tile_k_stride : a.tile_k_stride; + const ulong ns = a.indexed ? descriptors[didx].tile_n_stride : a.tile_n_stride; + const uint halves = a.indexed ? descriptors[didx].halves : a.halves; + const uint codebook = a.indexed ? descriptors[didx].codebook : a.codebook; + const short2 home = frag_home(ushort(lane)); + const uint rows_here = min(64u, a.rows - rb); + const uint cols_here = min(64u * CG, a.n - nb); + constexpr uint mma_warps = 4u * CG; + const bool is_decode = tid >= mma_warps * 32u; + const uint ws = tid / 32u; + // MMA role: four row groups by CG column groups. + const uint sgr = ws % 4u, sgc = ws / 4u; + // Decode role: four column groups by CG sixty-four-column halves. + const uint dg = ws - mma_warps, h = dg % 4u, hg = (dg / 4u) * 64u; + const bool decodes = is_decode && (nb + hg + h * 16u < a.n); + const uint p0 = lane * 8u; + uint at[8], off[8], sh[8], rel[8]; + const uint words = 4 * halves; + const uint wi0 = tf_exl3_map_for(p0, halves) & 63u; + { + const uint ring = 128 * halves; + const uint cur = (wi0 << 5) | ((tf_exl3_map_for(p0, halves) >> 6) & 31u); + TF_UNROLL + for (uint k = 0; k < 8; ++k) { + const uint p = p0 + k, l = p / 8, e = p % 8; + at[k] = (2 * (l % 4) + (e & 1u) + 8 * ((e >> 1) & 1u)) * (64u * CG) + hg + h * 16u + (l / 4 + 8 * (e >> 2)); + uint c8 = cur + k * (halves >> 1); + if (c8 >= ring) c8 -= ring; + const uint wi = c8 >> 5; + off[k] = c8 & 31u; + sh[k] = (32u - off[k]) & 31u; + rel[k] = wi >= wi0 ? wi - wi0 : wi + words - wi0; + } + } + frag lo0 = frag(0), hi0 = frag(0), lo1 = frag(0), hi1 = frag(0); + if (decodes) { + const uint w0 = tf_exl3_block_word(data, ks, ns, 0, nb, hg, h, wi0, words); + const uint w1 = tf_exl3_block_word(data, ks, ns, 0, nb, hg, h, wi0 + 1, words); + const uint w2 = tf_exl3_block_word(data, ks, ns, 0, nb, hg, h, wi0 + 2, words); + const uint w3 = tf_exl3_block_word(data, ks, ns, 0, nb, hg, h, wi0 + 3, words); + if (table != nullptr) tf_exl3_decode_table<8>(wx, table, codebook, at, off, sh, rel, w0, w1, w2, w3); + else tf_exl3_decode_fast<8>(wx, codebook, at, off, sh, 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; + if (!is_decode) { + frag av; + tf_frag_get_dev4(av, (const device half*)x, int(a.k), int(rb + sgr * 16), int(kb), home, int(rb + rows_here)); + 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); + mma_16x32(lo0, hi0, av, 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); + mma_16x32(lo1, hi1, av, b0, b1); + } else if (nkb < a.k and decodes) { + const uint nw0 = tf_exl3_block_word(data, ks, ns, nkb, nb, hg, h, wi0, words); + const uint nw1 = tf_exl3_block_word(data, ks, ns, nkb, nb, hg, h, wi0 + 1, words); + const uint nw2 = tf_exl3_block_word(data, ks, ns, nkb, nb, hg, h, wi0 + 2, words); + const uint nw3 = tf_exl3_block_word(data, ks, ns, nkb, nb, hg, h, wi0 + 3, words); + threadgroup half* nxt = wx + (cur_buf ^ 1u) * (16u * 64u * CG); + if (table != nullptr) tf_exl3_decode_table<8>(nxt, table, codebook, at, off, sh, rel, nw0, nw1, nw2, nw3); + else tf_exl3_decode_fast<8>(nxt, codebook, at, off, sh, rel, nw0, nw1, nw2, nw3); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + cur_buf ^= 1u; + } + if (!is_decode) { + const int r0 = int(rb + sgr * 16); + const int c0 = int(nb + sgc * 64u); + frag_put_in(lo0, sums, int(a.n), r0, c0, home, int(rb + rows_here), int(nb + cols_here)); + frag_put_in(hi0, sums, int(a.n), r0, c0 + 16, home, int(rb + rows_here), int(nb + cols_here)); + frag_put_in(lo1, sums, int(a.n), r0, c0 + 32, home, int(rb + rows_here), int(nb + cols_here)); + frag_put_in(hi1, sums, int(a.n), r0, c0 + 48, home, int(rb + rows_here), int(nb + cols_here)); + } +} + +kernel void tf_exl3_matmul_prefill_nax11(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 * 16 * 128]; + tf_exl3_prefill_body_ws<2>(wx, x, trellis, sums, a, routes, descriptors, nullptr, lane, sg, tid, tg); +} + +kernel void tf_exl3_matmul_prefill_nax12(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)]], + const device half* const table [[buffer(7)]], + 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 * 16 * 128]; + tf_exl3_prefill_body_ws<2>(wx, x, trellis, sums, a, routes, descriptors, table, lane, sg, tid, tg); +} + +// Wider column tiles: CG=4 re-reads the activation tile nine times instead of eighteen, CG=8 five times. +kernel void tf_exl3_matmul_prefill_nax13(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 * 16 * 256]; + tf_exl3_prefill_body_db<4, 4, true, 4, false>(wx, x, trellis, sums, a, routes, descriptors, nullptr, lane, sg, tid, tptg.x, tg); +} + +kernel void tf_exl3_matmul_prefill_nax14(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 * 16 * 512]; + tf_exl3_prefill_body_db<4, 8, true, 4, false>(wx, x, trellis, sums, a, routes, descriptors, nullptr, lane, sg, tid, tptg.x, tg); +} + +kernel void tf_exl3_matmul_prefill_nax15(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 * 16 * 256]; + tf_exl3_prefill_body_ws<4>(wx, x, trellis, sums, a, routes, descriptors, nullptr, lane, sg, tid, tg); +} + +kernel void tf_exl3_matmul_prefill_nax16(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)]], + const device half* const table [[buffer(7)]], + 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 * 16 * 128]; + tf_exl3_prefill_body_db<4, 2, true, 0, true>(wx, x, trellis, sums, a, routes, descriptors, table, lane, sg, tid, tptg.x, tg); +} + +kernel void tf_exl3_matmul_prefill_nax17(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 * 16 * 128]; + tf_exl3_prefill_body_db<4, 2, true, 0, false>(wx, x, trellis, sums, a, routes, descriptors, nullptr, lane, sg, tid, tptg.x, tg); +} + +// The 64x64 grouped tile the engine actually selects (nax5's tile): table decode and double buffer. +kernel void tf_exl3_matmul_prefill_nax18(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)]], + const device half* const table [[buffer(7)]], + 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 * 16 * 64]; + tf_exl3_prefill_body_db<4, 1, true, 4, true>(wx, x, trellis, sums, a, routes, descriptors, table, lane, sg, tid, tptg.x, tg); +} + +kernel void tf_exl3_matmul_prefill_nax19(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 * 16 * 64]; + tf_exl3_prefill_body_db<4, 1, true, 4, false>(wx, x, trellis, sums, a, routes, descriptors, nullptr, lane, sg, tid, tptg.x, tg); +} + +kernel void tf_exl3_matmul_prefill_nax20(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 * 16 * 64]; + tf_exl3_prefill_body_db<4, 1, false, 4, false>(wx, x, trellis, sums, a, routes, descriptors, nullptr, lane, sg, tid, tptg.x, tg); +} + +kernel void tf_exl3_matmul_prefill_nax21(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)]], + const device half* const table [[buffer(7)]], + 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 * 16 * 64]; + tf_exl3_prefill_body_db<4, 1, true, 0, true>(wx, x, trellis, sums, a, routes, descriptors, table, lane, sg, tid, tptg.x, tg); +} + +// The engine's 64x64 grouped tile with the codebook table and the shipped single buffer: the table gain without +// the double buffer's extra 2 KB of threadgroup memory (which cost more occupancy than it returned). +kernel void tf_exl3_matmul_prefill_nax22(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)]], + const device half* const table [[buffer(7)]], + 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, table, nullptr, lane, sg, tid, tptg.x, tg); +} + +// Activation-fragment reuse: four warps (one a row group), each decodes two 16x64 weight tiles into one 16x128 +// buffer, loads its `av` fragment once, and multiplies both tiles. The 36x activation re-read halves without +// adding warps; the decode work is the same, only the activation loads drop. +template +inline void tf_exl3_prefill_body_reuse(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, uint3 tg) { + const uint rb = tg.y * 64u, nb = tg.x * 128u; + 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 uint didx = a.indexed ? tile_expert : 0; + const device uchar* data = a.indexed ? descriptors[didx].trellis : trellis; + const ulong ks = a.indexed ? descriptors[didx].tile_k_stride : a.tile_k_stride; + const ulong ns = a.indexed ? descriptors[didx].tile_n_stride : a.tile_n_stride; + const uint halves = a.indexed ? descriptors[didx].halves : a.halves; + const uint codebook = a.indexed ? descriptors[didx].codebook : a.codebook; + const short2 home = frag_home(ushort(lane)); + const uint rows_here = min(64u, a.rows - rb); + const uint cols_here = min(128u, a.n - nb); + const uint h = sg; // four warps, one a row group + const uint p0 = lane * 8u; + const uint words = 4 * halves; + const uint wi0 = tf_exl3_map_for(p0, halves) & 63u; + uint atA[8], atB[8], off[8], sh[8], rel[8]; + { + const uint ring = 128 * halves; + const uint cur = (wi0 << 5) | ((tf_exl3_map_for(p0, halves) >> 6) & 31u); + TF_UNROLL + for (uint k = 0; k < 8; ++k) { + const uint p = p0 + k, l = p / 8, e = p % 8; + const uint at = (2 * (l % 4) + (e & 1u) + 8 * ((e >> 1) & 1u)) * 128u + h * 16u + (l / 4 + 8 * (e >> 2)); + atA[k] = at; + atB[k] = at + 64u; + uint c8 = cur + k * (halves >> 1); + if (c8 >= ring) c8 -= ring; + const uint wi = c8 >> 5; + off[k] = c8 & 31u; + sh[k] = (32u - off[k]) & 31u; + rel[k] = wi >= wi0 ? wi - wi0 : wi + words - wi0; + } + } + frag lo0 = frag(0), hi0 = frag(0), lo1 = frag(0), hi1 = frag(0); + frag lo2 = frag(0), hi2 = frag(0), lo3 = frag(0), hi3 = frag(0); + for (uint kb = 0; kb < a.k; kb += 16) { + const uint nA0 = tf_exl3_block_word(data, ks, ns, kb, nb, 0, h, wi0, words); + const uint nA1 = tf_exl3_block_word(data, ks, ns, kb, nb, 0, h, wi0 + 1, words); + const uint nA2 = tf_exl3_block_word(data, ks, ns, kb, nb, 0, h, wi0 + 2, words); + const uint nA3 = tf_exl3_block_word(data, ks, ns, kb, nb, 0, h, wi0 + 3, words); + const uint nB0 = tf_exl3_block_word(data, ks, ns, kb, nb + 64u, 0, h, wi0, words); + const uint nB1 = tf_exl3_block_word(data, ks, ns, kb, nb + 64u, 0, h, wi0 + 1, words); + const uint nB2 = tf_exl3_block_word(data, ks, ns, kb, nb + 64u, 0, h, wi0 + 2, words); + const uint nB3 = tf_exl3_block_word(data, ks, ns, kb, nb + 64u, 0, h, wi0 + 3, words); + if (Table) { + tf_exl3_decode_table<8>(wx, table, codebook, atA, off, sh, rel, nA0, nA1, nA2, nA3); + tf_exl3_decode_table<8>(wx, table, codebook, atB, off, sh, rel, nB0, nB1, nB2, nB3); + } else { + tf_exl3_decode_fast<8>(wx, codebook, atA, off, sh, rel, nA0, nA1, nA2, nA3); + tf_exl3_decode_fast<8>(wx, codebook, atB, off, sh, rel, nB0, nB1, nB2, nB3); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + frag av; + frag_get_in(av, (const device half*)x, int(a.k), int(rb + h * 16), int(kb), home, int(rb + rows_here), int(kb) + 16); + frag b0, b1; + tf_frag_get_tg4(b0, wx, 128, 0, 0, home); + tf_frag_get_tg4(b1, wx, 128, 0, 16, home); + mma_16x32(lo0, hi0, av, b0, b1); + tf_frag_get_tg4(b0, wx, 128, 0, 32, home); + tf_frag_get_tg4(b1, wx, 128, 0, 48, home); + mma_16x32(lo1, hi1, av, b0, b1); + tf_frag_get_tg4(b0, wx, 128, 0, 64, home); + tf_frag_get_tg4(b1, wx, 128, 0, 80, home); + mma_16x32(lo2, hi2, av, b0, b1); + tf_frag_get_tg4(b0, wx, 128, 0, 96, home); + tf_frag_get_tg4(b1, wx, 128, 0, 112, home); + mma_16x32(lo3, hi3, av, b0, b1); + threadgroup_barrier(mem_flags::mem_threadgroup); + } + const int r0 = int(rb + h * 16); + const int c0 = int(nb); + frag_put_in(lo0, sums, int(a.n), r0, c0, home, int(rb + rows_here), int(nb + cols_here)); + frag_put_in(hi0, sums, int(a.n), r0, c0 + 16, home, int(rb + rows_here), int(nb + cols_here)); + frag_put_in(lo1, sums, int(a.n), r0, c0 + 32, home, int(rb + rows_here), int(nb + cols_here)); + frag_put_in(hi1, sums, int(a.n), r0, c0 + 48, home, int(rb + rows_here), int(nb + cols_here)); + frag_put_in(lo2, sums, int(a.n), r0, c0 + 64, home, int(rb + rows_here), int(nb + cols_here)); + frag_put_in(hi2, sums, int(a.n), r0, c0 + 80, home, int(rb + rows_here), int(nb + cols_here)); + frag_put_in(lo3, sums, int(a.n), r0, c0 + 96, home, int(rb + rows_here), int(nb + cols_here)); + frag_put_in(hi3, sums, int(a.n), r0, c0 + 112, home, int(rb + rows_here), int(nb + cols_here)); +} + +kernel void tf_exl3_matmul_prefill_nax23(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 * 128]; + tf_exl3_prefill_body_reuse(wx, x, trellis, sums, a, routes, descriptors, nullptr, lane, sg, tid, tg); +} + +kernel void tf_exl3_matmul_prefill_nax24(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)]], + const device half* const table [[buffer(7)]], + 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_reuse(wx, x, trellis, sums, a, routes, descriptors, table, lane, sg, tid, tg); +} + +// The 64x64 grouped tile with the mul1 byte-sum LUT built in threadgroup memory (1024 halves, 2 KB): the +// comparator's decode shape, no 384 KB table, no per-weight L2 miss. +kernel void tf_exl3_matmul_prefill_nax25(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]; + threadgroup half lut[1024]; + const half scale = as_type(ushort(0x1EEEu)); + const half bias = as_type(ushort(0xC931u)); + TF_UNROLL + for (uint j = 0; j < 8u; ++j) lut[tid + 128u * j] = half(fma(float(tid + 128u * j + 1024u), float(scale), float(bias))); + threadgroup_barrier(mem_flags::mem_threadgroup); + tf_exl3_prefill_body(wx, x, trellis, sums, a, routes, descriptors, nullptr, lut, lane, sg, tid, tptg.x, tg); +} + +// Dense 128x64 tile (nax2's shape): double-buffered + codebook table, and single-buffer + threadgroup LUT. +kernel void tf_exl3_matmul_prefill_nax26(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)]], + const device half* const table [[buffer(7)]], + 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 * 16 * 64]; + tf_exl3_prefill_body_db<8, 1, true, 4, true>(wx, x, trellis, sums, a, routes, descriptors, table, lane, sg, tid, tptg.x, tg); +} + +kernel void tf_exl3_matmul_prefill_nax27(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]; + threadgroup half lut[1024]; + const half scale = as_type(ushort(0x1EEEu)); + const half bias = as_type(ushort(0xC931u)); + TF_UNROLL + for (uint j = 0; j < 4u; ++j) lut[tid + 256u * j] = half(fma(float(tid + 256u * j + 1024u), float(scale), float(bias))); + threadgroup_barrier(mem_flags::mem_threadgroup); + tf_exl3_prefill_body(wx, x, trellis, sums, a, routes, descriptors, nullptr, lut, lane, sg, tid, tptg.x, tg); +} + +// Dense 128x128 tile: sixteen warps, the comparator's tile shape, with the 1024-entry LUT amortised over +// twice the decode (2 entries built a thread, 4 states decoded) and half the activation re-read. +kernel void tf_exl3_matmul_prefill_nax28(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 * 128]; + threadgroup half lut[1024]; + const half scale = as_type(ushort(0x1EEEu)); + const half bias = as_type(ushort(0xC931u)); + TF_UNROLL + for (uint j = 0; j < 2u; ++j) lut[tid + 512u * j] = half(fma(float(tid + 512u * j + 1024u), float(scale), float(bias))); + threadgroup_barrier(mem_flags::mem_threadgroup); + tf_exl3_prefill_body(wx, x, trellis, sums, a, routes, descriptors, nullptr, lut, lane, sg, tid, tptg.x, tg); +} + +kernel void tf_exl3_matmul_prefill_nax29(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 * 128]; + tf_exl3_prefill_body(wx, x, trellis, sums, a, routes, descriptors, nullptr, nullptr, lane, sg, tid, tptg.x, tg); +} + +// Diagnostics for the dense 128x64 tile (RG=8, 256 threads), the attention-dense body: nax30 is the same body +// with the per-block decode removed (the prologue tile reused), nax31 keeps it, nax32 issues one of the four +// multiplies. nax31 - nax30 prices the decode at the dense tile, nax30 prices the decode-free multiply. +kernel void tf_exl3_matmul_prefill_nax30(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 * 16 * 64]; + tf_exl3_prefill_body_db<8, 1, false, 4, false>(wx, x, trellis, sums, a, routes, descriptors, nullptr, lane, sg, tid, tptg.x, tg); +} + +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 * 16 * 64]; + tf_exl3_prefill_body_db<8, 1, true, 4, false>(wx, x, trellis, sums, a, routes, descriptors, nullptr, lane, sg, tid, tptg.x, tg); +} + +// ROUND-431: THE DOUBLE-BUFFERED 128-COLUMN DENSE BODY. nax31's decode, k order and MMA order per output, +// at twice the tile width: one activation block is read for 128 columns instead of 64 and one barrier covers +// twice the multiply. nax79 reads the codebook from the resident device table (buffer 7); nax80 is the same +// body on the ALU codebook. Both must agree with nax31 bit-for-bit at every output. +kernel void tf_exl3_matmul_prefill_nax79(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)]], + const device half* const table [[buffer(7)]], + 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 * 16 * 128]; + tf_exl3_prefill_body_db<8, 2, true, 4, true>(wx, x, trellis, sums, a, routes, descriptors, table, lane, sg, tid, tptg.x, tg); +} + +kernel void tf_exl3_matmul_prefill_nax80(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 * 16 * 128]; + tf_exl3_prefill_body_db<8, 2, true, 4, false>(wx, x, trellis, sums, a, routes, descriptors, nullptr, lane, sg, tid, tptg.x, tg); +} + +// ROUND-431: the 64-row x 128-column double-buffered dense body: the same 8,192-element tile area as nax31, +// eight warps / 256 threads (nax31's occupancy), eight decode groups so one threadgroup owns all 128 columns +// the fused output transform needs. nax31's k order and MMA order per output. +kernel void tf_exl3_matmul_prefill_nax82(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 * 16 * 128]; + tf_exl3_prefill_body_db<4, 2, true, 4, false>(wx, x, trellis, sums, a, routes, descriptors, nullptr, lane, sg, tid, tptg.x, tg); +} + +// ROUND-432: ONE 8-WARP THREADGROUP OVER 128 ROWS AND BOTH 64-COLUMN HALVES. Two accumulator sets (eight +// fragments, 64 f32 a lane) and two double-buffered 16x64 tiles; the activation block is loaded once and +// multiplied into both halves. Per output this is nax31's weight-decode amortisation (128 rows) and nax31's +// eight-warp threadgroup, with half its activation reads. nax31's k order and MMA order per output, so `sums` +// is bit-identical. +template +inline void tf_exl3_prefill_body_db2(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 = 128u; + const uint rb = tg.y * trows, nb = tg.x * 128u; + if (a.indexed == 1 || rb >= a.rows || nb >= a.n) return; + const device uchar* data = trellis; + const ulong ks = a.tile_k_stride, ns = a.tile_n_stride; + const uint halves = a.halves, codebook = a.codebook; + if ((halves & 1u) != 0 or halves > 16) return; + const short2 home = frag_home(ushort(lane)); + const uint rows_here = min(trows, a.rows - rb); + const uint cols_here = min(128u, a.n - nb); + constexpr uint wpg = 2u; + constexpr uint states = 4u; + const uint gwarp = tid / 32u, group = gwarp / wpg, wg = gwarp % wpg; + const uint h = group % 4u; + const uint p0 = (wg * 32u + tid % 32u) * states; + const bool decodes = group < 4u and nb + 64u + h * 16u < a.n; + uint at[8], off[8], sh[8], rel[8]; + const uint words = 4 * halves; + const uint wi0 = tf_exl3_map_for(p0, halves) & 63u; + { + const uint ring = 128 * halves; + const uint cur = (wi0 << 5) | ((tf_exl3_map_for(p0, halves) >> 6) & 31u); + TF_UNROLL + for (uint k = 0; k < states; ++k) { + const uint p = p0 + k, l = p / 8, e = p % 8; + at[k] = (2 * (l % 4) + (e & 1u) + 8 * ((e >> 1) & 1u)) * 64u + h * 16u + (l / 4 + 8 * (e >> 2)); + uint c8 = cur + k * (halves >> 1); + if (c8 >= ring) c8 -= ring; + const uint wi = c8 >> 5; + off[k] = c8 & 31u; + sh[k] = (32u - off[k]) & 31u; + rel[k] = wi >= wi0 ? wi - wi0 : wi + words - wi0; + } + } + const uint sgr = sg; + frag lo0 = frag(0), hi0 = frag(0), lo1 = frag(0), hi1 = frag(0); + frag lo2 = frag(0), hi2 = frag(0), lo3 = frag(0), hi3 = frag(0); + if (decodes) { + uint w0 = tf_exl3_block_word(data, ks, ns, 0, nb, 0, h, wi0, words); + uint w1 = tf_exl3_block_word(data, ks, ns, 0, nb, 0, h, wi0 + 1, words); + uint w2 = tf_exl3_block_word(data, ks, ns, 0, nb, 0, h, wi0 + 2, words); + uint w3 = tf_exl3_block_word(data, ks, ns, 0, nb, 0, h, wi0 + 3, words); + if (UseTable) tf_exl3_decode_table(wx, table, codebook, at, off, sh, rel, w0, w1, w2, w3); + else tf_exl3_decode_fast(wx, codebook, at, off, sh, rel, w0, w1, w2, w3); + w0 = tf_exl3_block_word(data, ks, ns, 0, nb + 64u, 0, h, wi0, words); + w1 = tf_exl3_block_word(data, ks, ns, 0, nb + 64u, 0, h, wi0 + 1, words); + w2 = tf_exl3_block_word(data, ks, ns, 0, nb + 64u, 0, h, wi0 + 2, words); + w3 = tf_exl3_block_word(data, ks, ns, 0, nb + 64u, 0, h, wi0 + 3, words); + if (UseTable) tf_exl3_decode_table(wx + 2u * (16u * 64u), table, codebook, at, off, sh, rel, w0, w1, w2, w3); + else tf_exl3_decode_fast(wx + 2u * (16u * 64u), codebook, at, off, sh, rel, w0, w1, w2, w3); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + uint cur0 = 0u, cur1 = 2u; + for (uint kb = 0; kb < a.k; kb += 16) { + const uint nkb = kb + 16; + uint nw0 = 0, nw1 = 0, nw2 = 0, nw3 = 0, nw4 = 0, nw5 = 0, nw6 = 0, nw7 = 0; + if (nkb < a.k and decodes) { + nw0 = tf_exl3_block_word(data, ks, ns, nkb, nb, 0, h, wi0, words); + nw1 = tf_exl3_block_word(data, ks, ns, nkb, nb, 0, h, wi0 + 1, words); + nw2 = tf_exl3_block_word(data, ks, ns, nkb, nb, 0, h, wi0 + 2, words); + nw3 = tf_exl3_block_word(data, ks, ns, nkb, nb, 0, h, wi0 + 3, words); + nw4 = tf_exl3_block_word(data, ks, ns, nkb, nb + 64u, 0, h, wi0, words); + nw5 = tf_exl3_block_word(data, ks, ns, nkb, nb + 64u, 0, h, wi0 + 1, words); + nw6 = tf_exl3_block_word(data, ks, ns, nkb, nb + 64u, 0, h, wi0 + 2, words); + nw7 = tf_exl3_block_word(data, ks, ns, nkb, nb + 64u, 0, h, wi0 + 3, words); + } + frag av; + tf_frag_get_dev4(av, (const device half*)x, int(a.k), int(rb + sgr * 16u), int(kb), home, int(rb + rows_here)); + { + const threadgroup half* cur = wx + cur0 * (16u * 64u); + frag b0f, b1f; + tf_frag_get_tg4(b0f, cur, 64, 0, 0, home); + tf_frag_get_tg4(b1f, cur, 64, 0, 16, home); + mma_16x32(lo0, hi0, av, b0f, b1f); + tf_frag_get_tg4(b0f, cur, 64, 0, 32, home); + tf_frag_get_tg4(b1f, cur, 64, 0, 48, home); + mma_16x32(lo1, hi1, av, b0f, b1f); + } + { + const threadgroup half* cur = wx + cur1 * (16u * 64u); + frag b0f, b1f; + tf_frag_get_tg4(b0f, cur, 64, 0, 0, home); + tf_frag_get_tg4(b1f, cur, 64, 0, 16, home); + mma_16x32(lo2, hi2, av, b0f, b1f); + tf_frag_get_tg4(b0f, cur, 64, 0, 32, home); + tf_frag_get_tg4(b1f, cur, 64, 0, 48, home); + mma_16x32(lo3, hi3, av, b0f, b1f); + } + if (nkb < a.k and decodes) { + if (UseTable) { + tf_exl3_decode_table(wx + (cur0 ^ 1u) * (16u * 64u), table, codebook, at, off, sh, rel, nw0, nw1, nw2, nw3); + tf_exl3_decode_table(wx + (cur1 ^ 1u) * (16u * 64u), table, codebook, at, off, sh, rel, nw4, nw5, nw6, nw7); + } else { + tf_exl3_decode_fast(wx + (cur0 ^ 1u) * (16u * 64u), codebook, at, off, sh, rel, nw0, nw1, nw2, nw3); + tf_exl3_decode_fast(wx + (cur1 ^ 1u) * (16u * 64u), codebook, at, off, sh, rel, nw4, nw5, nw6, nw7); + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + cur0 ^= 1u; + cur1 ^= 1u; + } + const int r0 = int(rb + sgr * 16u); + const int c0 = int(nb), c1 = int(nb + 64u); + frag_put_in(lo0, sums, int(a.n), r0, c0, home, int(rb + rows_here), int(nb + cols_here)); + frag_put_in(hi0, sums, int(a.n), r0, c0 + 16, home, int(rb + rows_here), int(nb + cols_here)); + frag_put_in(lo1, sums, int(a.n), r0, c0 + 32, home, int(rb + rows_here), int(nb + cols_here)); + frag_put_in(hi1, sums, int(a.n), r0, c0 + 48, home, int(rb + rows_here), int(nb + cols_here)); + frag_put_in(lo2, sums, int(a.n), r0, c1, home, int(rb + rows_here), int(nb + cols_here)); + frag_put_in(hi2, sums, int(a.n), r0, c1 + 16, home, int(rb + rows_here), int(nb + cols_here)); + frag_put_in(lo3, sums, int(a.n), r0, c1 + 32, home, int(rb + rows_here), int(nb + cols_here)); + frag_put_in(hi3, sums, int(a.n), r0, c1 + 48, home, int(rb + rows_here), int(nb + cols_here)); +} + +kernel void tf_exl3_matmul_prefill_nax83(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[4 * 16 * 64]; + tf_exl3_prefill_body_db2(wx, x, trellis, sums, a, routes, descriptors, nullptr, lane, sg, tid, tptg.x, tg); +} + +// ROUND-348: the dense 128x64 prompt tile (nax31's geometry) with the funnel read. The dense tile is 128 rows +// (eight row groups), so a lane owns four states and the funnel reads a twenty-five-bit run -- two words, where +// the cursor path reads four. The values, their order, the k order and the MMA order are nax31's, so the output is +// bit-identical; only the word traffic and the select chain leave. +kernel void tf_exl3_matmul_prefill_nax51(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 * 16 * 64]; + tf_exl3_prefill_body_db<8, 1, true, 4, false, true>(wx, x, trellis, sums, a, routes, descriptors, nullptr, lane, sg, tid, tptg.x, tg); +} + +// ROUND-351: the dense 128x64 prompt tile with a SIMDgroup that owns thirty-two rows -- the comparator's +// NAXTile shape (a simdgroup owns thirty-two rows, so one threadgroup's eight row groups become four groups +// of two). The lane keeps eight states, so the stream words it reads cover twice the states, and the weight +// fragments are read once for two row groups, so the tile's threadgroup traffic per row halves. The values, +// their order, the k order and the MMA order per output are nax31's, so the output is bit-identical. +kernel void tf_exl3_matmul_prefill_nax56(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 * 16 * 64]; + tf_exl3_prefill_body_db<8, 1, true, 4, false, false, 2>(wx, x, trellis, sums, a, routes, descriptors, nullptr, lane, sg, tid, tptg.x, tg); +} + +kernel void tf_exl3_matmul_prefill_nax32(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 * 16 * 64]; + tf_exl3_prefill_body_db<8, 1, true, 1, false>(wx, x, trellis, sums, a, routes, descriptors, nullptr, lane, sg, tid, tptg.x, tg); +} + +// Dense row-height diagnostics: RG=16 (256 rows a threadgroup, 512 threads) and RG=32 (512 rows, 1024 threads). +// The decoded 16x64 weight tile is shared by every row group, so the per-weight decode halves at RG=16 and +// quarters at RG=32; the per-row MMA order is unchanged (each SIMDgroup still owns its sixteen rows). +kernel void tf_exl3_matmul_prefill_nax33(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); +} + +kernel void tf_exl3_matmul_prefill_nax34(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); +} + +// Two-blocks-ahead prompt bodies: the routed 64x64 tile (nax35) and the dense 128x64 tile (nax36). +kernel void tf_exl3_matmul_prefill_nax35(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 * 16 * 64]; + tf_exl3_prefill_body_pf<4, 1, 4>(wx, x, trellis, sums, a, routes, descriptors, lane, sg, tid, tptg.x, tg); +} + +kernel void tf_exl3_matmul_prefill_nax36(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 * 16 * 64]; + tf_exl3_prefill_body_pf<8, 1, 4>(wx, x, trellis, sums, a, routes, descriptors, lane, sg, tid, tptg.x, tg); +} + +// ROUND-336: the comparator's decode structure on our map -- one threadgroup a sixteen-column tile, one k +// walk, no split-K, no partials and no reduce dispatch, and the decoded weights stay in REGISTERS: there is +// no threadgroup weight tile, no barrier in the k loop and no threadgroup memory round trip. +// Structure ported from mlx-serve's dsv41_exl3_guone_k3 / dsv41_exl3_mul1h_k3 decode kernels +// (MIT/Apache-2.0, NOTICE per-file): one warp owns a sixteen-column tile of one row, each lane holds two +// output columns and the four k rows it reads, the eight decoded weights stay in registers, and the four +// lanes that share a column reduce once, at the end of the walk. +// TF_FMA_WARPS: the warps a threadgroup. Each warp walks its own slice of the k blocks and the warps' partial +// sums are added once, at the end of the walk, through a threadgroup reduction -- so a split-K dispatch's +// parallelism without its partials round trip and its reduce dispatch. +// Our map is unchanged: the lane's eight states are the same eight the tensor-unit body reads (the same +// stream words, the same bit offsets, the same codebook values), so the products are the same products. +// The reduction order is the comparator's, not the tensor unit's: the sums are FP32 either way, but the +// tensor unit reduces sixteen k at a time and this body adds them one at a time, so the two are not +// bit-identical (the numerics band prices the difference). +#ifndef TF_FMA_WARPS +#define TF_FMA_WARPS 1 +#endif +// ROUND-416: THE PREFETCH DEPTH OF THE REGISTER-ONLY BODY'S K-WALK. The shipped body keeps ONE block of +// stream words in flight (the next block's three words are read at the top of the walk and consumed at the top +// of the next step), so a block's DRAM latency is exposed once a block unless the block's own work hides it -- +// and a block's work is eight states, far less than a DRAM round trip. TF_FMA_PF blocks in flight (a ring of +// word triples) hides it behind PF blocks of work. The values, their order and the arithmetic are untouched: +// the ring only moves the LOADS in time, so every arm is BIT-IDENTICAL to the shipped body. +#ifndef TF_FMA_PF +#define TF_FMA_PF 1 +#endif +// ROUND-416: THE STREAM WORD AS ONE 4-BYTE LOAD (the comparator's read, ROUND-352's form). The shipped read is +// two 2-byte loads a word (a stream word is a little-endian pair of int16s), so the decode's lane issues SIX +// load instructions a k-block where the comparator issues three; the bytes, the values and the order are the +// same, so the arm is BIT-IDENTICAL. The prefill tiles already read their words this way (tf_exl3_word_t +// with W = true); the register-only decode body did not. TF_FMA_WIDE_WORD = 1 turns it on there. +#ifndef TF_FMA_WIDE_WORD +#define TF_FMA_WIDE_WORD 0 +#endif + +// ROUND-428: THE TWO-WORD FUNNEL AT halves = 6 IN THE STATIC BODY. The static body reads three stream words a +// lane a block (a run of 7*S + 16 bits; at S = 3 that is 37 bits), but at halves = 6 every lane run starts at +// off0 in {3,11,19,27}, so the run is contained in two 32-bit words and only the top five bits of the funnel +// second register are read (states J = 6, 7 at bit 18/21 use c_next >> 30 / >> 27). The third word feeds only +// the low off0 <= 27 bits of c_next, which the extraction never reads. Dropping it is bit-identical BY +// CONSTRUCTION (the same argument as ROUND-334 routed funnel); the bench hash prices it. +#ifndef TF_FMA_TWO +#define TF_FMA_TWO 0 +#endif +// ROUND-416: THE VALUE PATH'S FORM. The register-only body's mul1 value comes from a 1024-entry THREADGROUP LUT +// (the index is the state's byte sum), and the ladder prices that whole path (the hash, the byte sum, the index +// and the shared load) at 27 % of the ROUTED stage. The alternative form is the ARITHMETIC one the format's own +// decoder uses (tf_exl3_value: the same byte sum, the same half, the same fma) -- the LUT's entries ARE those +// values, entry for entry, so the two forms are BIT-IDENTICAL and the choice is a pure cost question. +// TF_FMA_VALUE_ARITH = 1 takes the arithmetic form. +#ifndef TF_FMA_VALUE_ARITH +#define TF_FMA_VALUE_ARITH 0 +#endif +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; + // ROUND-394: 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 (the tensor-unit body's own fallback) for any other width. + const bool pipeline = (halves & 1u) == 0 and halves <= 16; + // ROUND-337: one accumulator a state, so the eight products of a block meet in a tree at the end instead of + // in two chains of four. The comparator's body adds the terms one at a time; two chains of 1,280 additions + // are 2.5x less accurate against an fp64 reference than the tensor unit's 320-step chain of sixteen-term + // trees (NRMS 6.0e-7 against 2.3e-7, measured). Eight accumulators make the two the same class. + 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 + // ROUND-416 (the instrument, BENCH-ONLY): the ACTIVATION READ gone -- the x row is not read at all. + // The FMA stays (the weight is still needed) and the constant is a RUNTIME value (the args' rows), so + // the compiler cannot fold the multiply away and the arm prices the read, not the arithmetic. + 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; + } +} + +// ROUND-338: one state, one product: the state's window at a compile-time shift (the static selection) and +// the lane's activation row for that state. +// ROUND-369: the state's value alone (the window at a compile-time shift, then the codebook's value). The +// decode is the ALU-bound part of the register-only body, so the multi-row body decodes it ONCE a block and +// gives the value to every row's product. +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) + // ROUND-415 (the instrument, BENCH-ONLY -- inert unless the bench compiles the source with the define): + // the decode's share at the decode's own shapes, where the tile's work is one row. TF_DIAG_DECODE = 1 keeps the + // state's extraction and the trellis read and drops the VALUE path (the hash, the byte sum, the index and the + // LUT load); = 2 drops the whole decode, so the compiler removes the trellis reads too. The output differs by + // construction (a timing arm only -- it is never dispatched by the engine). + 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) + // ROUND-417 (the instrument, BENCH-ONLY -- inert unless the bench compiles the source with the define): + // THE VALUE PATH'S SPLIT, at the routed shapes. The ladder (TF_DIAG_DECODE = 1) prices the whole value path + // (the hash, the byte sum, the index and the load) as one term; this splits it. d6 KEEPS THE LOAD and drops + // the index arithmetic (the value is the LUT's entry at a state-derived index -- the same random access + // pattern, none of the arithmetic); d7 KEEPS THE INDEX ARITHMETIC and drops the load (the value is the + // index's low bit). Both arms' outputs differ from the body's by construction -- they are timing arms, never + // dispatched by the engine. The mul1 codebook's index is the byte sum of the hash, folded under 1,024; the + // table codebooks' value IS the load, so their d6 is the shipped arm and their d7 is the load alone. + 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 +// ROUND-417: THE BRANCH MUST TEST THE VALUE, NOT defined(): the define defaults to 0, and defined() is true +// for 0, so the engine was silently taking the ARITHMETIC value path (the format-s own decoder) instead of +// the threadgroup LUT. The two are BIT-IDENTICAL (the bench-s hash says so) but the arithmetic form is the +// slower of the two in situ (the control arm read 38.73 tok/s against the standing 41.61). The arm stays a +// bench-only instrument; the engine keeps the LUT. +#elif defined(TF_FMA_VALUE_ARITH) && TF_FMA_VALUE_ARITH + // ROUND-416: 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 +} + +// ROUND-369: one state, one product, with the weight already decoded. The product is the shipped body's: +// the same activation pick and the same fma. +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 + // ROUND-416 (the instrument, BENCH-ONLY -- inert unless the bench compiles the source with the define): + // the per-weight FP op DOUBLED. A removal arm would let the compiler delete the whole decode (the weight + // would be dead), so the price of the arithmetic is read as the MARGINAL cost of one more FMA -- the + // record's own doubling-arm discipline ("a doubling arm prices a dispatch's marginal cost"). + *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); +} + +// ROUND-338: the register-only routed decode with the static state selection. The shipped body picks each +// state's word pair and bit offset at run time (the `rel[k]` cursor); here one funnel shift a block puts the +// lane's window at a known place and the eight windows then sit at compile-time shifts, so the cursor and the +// per-state bit offset leave the inner loop. The lane's eight states, the stream words, the bit offsets, the +// codebook values, the products and the reduction tree are the shipped body's, so the output is bit-identical. +// S is the states' stride in bits (halves / 2); the body is specialised for the widths the pack uses. +// ROUND-340: `Dense` is the dense one-row path's variant of the same body. The routed decode reads its weights +// through descriptors[expert] (one expert a row); a dense matrix has one trellis and its strides live in the +// args, so the dense variant reads them from there and needs no descriptor table at all. The two differ only in +// where the five fields come from: the walk, the windows, the products, the reduction tree and the output are +// the same code, so the routed path's values do not move. +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; + const device uchar* data; + ulong ks; + ulong ns; + uint halves; + uint codebook; + uint width = a.n; + if (Dense) { + data = trellis; + ks = a.tile_k_stride; + ns = a.tile_n_stride; + halves = a.halves; + codebook = a.codebook; + } else { + const uint expert = routes[row]; + if (expert >= a.experts) return; + data = descriptors[expert].trellis; + ks = descriptors[expert].tile_k_stride; + ns = descriptors[expert].tile_n_stride; + halves = descriptors[expert].halves; + codebook = descriptors[expert].codebook; + // ROUND-394: the entry own output width (0 = the call n), for a batch of entries that differ in n. + if (descriptors[expert].reserved != 0) width = descriptors[expert].reserved; + } + if (nb >= 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 uint words = 4 * halves; + const uint wi0 = tf_exl3_map_for(lane * 8u, halves) & 63u; + // The lane's bit offset inside its first word: the one runtime shift of the body. + const uint off0 = (tf_exl3_map_for(lane * 8u, halves) >> 6) & 31u; + const uint sh0 = (32u - off0) & 31u; + const uint m0 = 0u - uint(off0 != 0u); + uint a1 = wi0 + 1; if (a1 >= words) a1 -= words; + uint a2 = wi0 + 2; if (a2 >= words) a2 -= words; + // Three stream words: the lane's window spans at most 7*S + 16 bits from its first state. + // ROUND-416: the ring of TF_FMA_PF triples (one block in flight is the shipped form). + uint pre[TF_FMA_PF][3]; + { + const device ushort* t0 = reinterpret_cast(data + ulong(b0) * ks + ulong(nb / 16) * ns); +#if TF_FMA_WIDE_WORD + pre[0][0] = tf_exl3_word_t(t0, wi0); + pre[0][1] = tf_exl3_word_t(t0, a1); + pre[0][2] = Two ? 0u : tf_exl3_word_t(t0, a2); +#else + pre[0][0] = tf_exl3_word(t0, wi0); + pre[0][1] = tf_exl3_word(t0, a1); + pre[0][2] = Two ? 0u : tf_exl3_word(t0, a2); +#endif +#if TF_FMA_PF > 1 + // The ring is primed: the first TF_FMA_PF blocks' words are in flight before the walk starts. + for (uint p = 1; p < TF_FMA_PF; ++p) { + if (b0 + p < b1) { + const device ushort* tp = reinterpret_cast(data + ulong(b0 + p) * ks + ulong(nb / 16) * ns); + pre[p][0] = tf_exl3_word(tp, wi0); + pre[p][1] = tf_exl3_word(tp, a1); + pre[p][2] = Two ? 0u : tf_exl3_word(tp, a2); + } + } +#endif + } + 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; +#if TF_FMA_PF > 1 + const uint slot = (bb - b0) % TF_FMA_PF; + const uint w0 = pre[slot][0], w1 = pre[slot][1], w2 = pre[slot][2]; + // The block TF_FMA_PF ahead takes this slot: its words are in flight while PF blocks are walked. + if (bb + TF_FMA_PF < b1) { + const device ushort* tn = reinterpret_cast(data + ulong(bb + TF_FMA_PF) * ks + ulong(nb / 16) * ns); +#if TF_FMA_WIDE_WORD + pre[slot][0] = tf_exl3_word_t(tn, wi0); + pre[slot][1] = tf_exl3_word_t(tn, a1); + pre[slot][2] = Two ? 0u : tf_exl3_word_t(tn, a2); +#else + pre[slot][0] = tf_exl3_word(tn, wi0); + pre[slot][1] = tf_exl3_word(tn, a1); + pre[slot][2] = Two ? 0u : tf_exl3_word(tn, a2); +#endif + } +#else + const uint w0 = pre[0][0], w1 = pre[0][1], w2 = pre[0][2]; + if (bb + 1 < b1) { + const device ushort* tn = reinterpret_cast(data + ulong(bb + 1) * ks + ulong(nb / 16) * ns); +#if TF_FMA_WIDE_WORD + pre[0][0] = tf_exl3_word_t(tn, wi0); + pre[0][1] = tf_exl3_word_t(tn, a1); + pre[0][2] = Two ? 0u : tf_exl3_word_t(tn, a2); +#else + pre[0][0] = tf_exl3_word(tn, wi0); + pre[0][1] = tf_exl3_word(tn, a1); + pre[0][2] = Two ? 0u : tf_exl3_word(tn, a2); +#endif + } +#endif + // The lane's window: one runtime funnel shift, then the eight windows at compile-time shifts. + const uint c_cur = (w0 << off0) | ((w1 >> sh0) & m0); + const uint c_next = Two ? (w1 << off0) : ((w1 << off0) | ((w2 >> sh0) & m0)); + // 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 + // ROUND-416 (the instrument, BENCH-ONLY): the ACTIVATION READ gone -- the x row is not read at all. + // The FMA stays (the weight is still needed) and the constant is a RUNTIME value (the args' rows), so + // the compiler cannot fold the multiply away and the arm prices the read, not the arithmetic. + 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, codebook, x0, x1, x2, x3, lut); + tf_exl3_fma_step(&acc[1], c_cur, c_next, table, codebook, x0, x1, x2, x3, lut); + tf_exl3_fma_step(&acc[2], c_cur, c_next, table, codebook, x0, x1, x2, x3, lut); + tf_exl3_fma_step(&acc[3], c_cur, c_next, table, codebook, x0, x1, x2, x3, lut); + tf_exl3_fma_step(&acc[4], c_cur, c_next, table, codebook, x0, x1, x2, x3, lut); + tf_exl3_fma_step(&acc[5], c_cur, c_next, table, codebook, x0, x1, x2, x3, lut); + tf_exl3_fma_step(&acc[6], c_cur, c_next, table, codebook, x0, x1, x2, x3, lut); + tf_exl3_fma_step(&acc[7], c_cur, c_next, table, 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 + // ROUND-416 (the instrument, BENCH-ONLY): the CROSS-WARP REDUCTION gone (the warps' partials through the + // threadgroup memory): each warp keeps its own partial and the first warp alone stores it, so the arm + // prices the threadgroup round trip (the barrier, the partials' traffic and the sum). +#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; + } +} + +// ROUND-369: THE MULTI-ROW DENSE DECODE BODY. One threadgroup computes R rows of the SAME dense matrix, so +// the weight decode -- the ALU-bound part of the register-only body -- is shared by the rows instead of paid +// once a row (the shipped body is one row a threadgroup: `row = tg.y`, and the dispatch's height is the row +// count, so a four-row window decodes the attention's dense weights four times over). Each row keeps the +// shipped per-row arithmetic exactly: the same k blocks, the same warp split, the same accumulator tree, the +// same cross-warp sum and the same lane shuffles -- so every row's sum is bit-identical to the one-row body's. +// The comparator's structure is the same shape (mlx-serve's dspark/pair kernels, MIT/Apache-2.0; the +// attribution is carried in the kernel): one decode for the rows that share a weight. +template +inline void tf_exl3_decode_fma_dense_multi_body(const device half* x, const device uchar* trellis, + device float* sums, constant TfExl3Args& a, + const device half* table, uint lane, uint sg, uint3 tg, + threadgroup float* red_all, threadgroup half* lut = nullptr) { + const uint row0 = tg.y * R; + const uint nb = tg.x * 16u; + if (row0 >= a.rows or nb >= a.n) 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; + const uint blocks = a.k / 16; + const uint W = TF_FMA_WARPS; + const uint b0 = blocks * sg / W, b1 = blocks * (sg + 1u) / W; + const uint words = 4 * halves; + const uint wi0 = tf_exl3_map_for(lane * 8u, halves) & 63u; + // The lane's bit offset inside its first word: the one runtime shift of the body. + const uint off0 = (tf_exl3_map_for(lane * 8u, halves) >> 6) & 31u; + const uint sh0 = (32u - off0) & 31u; + const uint m0 = 0u - uint(off0 != 0u); + uint a1 = wi0 + 1; if (a1 >= words) a1 -= words; + uint a2 = wi0 + 2; if (a2 >= words) a2 -= words; + // 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(data + ulong(b0) * ks + ulong(nb / 16) * ns); + pre[0] = tf_exl3_word(t0, wi0); + pre[1] = tf_exl3_word(t0, a1); + pre[2] = tf_exl3_word(t0, a2); + } + float acc[R][8]; + for (uint r = 0; r < R; ++r) for (uint j = 0; j < 8u; ++j) acc[r][j] = 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(data + ulong(bb + 1) * ks + ulong(nb / 16) * ns); + pre[0] = tf_exl3_word(tn, wi0); + pre[1] = tf_exl3_word(tn, a1); + pre[2] = tf_exl3_word(tn, a2); + } + // The lane's window: one runtime funnel shift, then the eight windows at compile-time shifts. + const uint c_cur = (w0 << off0) | ((w1 >> sh0) & m0); + const uint c_next = (w1 << off0) | ((w2 >> sh0) & m0); + // ROUND-369: the eight weights are decoded ONCE for the block, and every row's product uses them. + float wgt[8]; + wgt[0] = tf_exl3_fma_weight(c_cur, c_next, table, codebook, lut); + wgt[1] = tf_exl3_fma_weight(c_cur, c_next, table, codebook, lut); + wgt[2] = tf_exl3_fma_weight(c_cur, c_next, table, codebook, lut); + wgt[3] = tf_exl3_fma_weight(c_cur, c_next, table, codebook, lut); + wgt[4] = tf_exl3_fma_weight(c_cur, c_next, table, codebook, lut); + wgt[5] = tf_exl3_fma_weight(c_cur, c_next, table, codebook, lut); + wgt[6] = tf_exl3_fma_weight(c_cur, c_next, table, codebook, lut); + wgt[7] = tf_exl3_fma_weight(c_cur, c_next, table, codebook, lut); + for (uint r = 0; r < R; ++r) { + const uint row = row0 + r; + if (row >= a.rows) break; + // 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 + // ROUND-416 (the instrument, BENCH-ONLY): the ACTIVATION READ gone (the multi body's own read). + 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_w<0>(&acc[r][0], wgt[0], x0, x1, x2, x3); + tf_exl3_fma_step_w<1>(&acc[r][1], wgt[1], x0, x1, x2, x3); + tf_exl3_fma_step_w<2>(&acc[r][2], wgt[2], x0, x1, x2, x3); + tf_exl3_fma_step_w<3>(&acc[r][3], wgt[3], x0, x1, x2, x3); + tf_exl3_fma_step_w<4>(&acc[r][4], wgt[4], x0, x1, x2, x3); + tf_exl3_fma_step_w<5>(&acc[r][5], wgt[5], x0, x1, x2, x3); + tf_exl3_fma_step_w<6>(&acc[r][6], wgt[6], x0, x1, x2, x3); + tf_exl3_fma_step_w<7>(&acc[r][7], wgt[7], x0, x1, x2, x3); + } + } + // The eight accumulators meet in a tree: the first four are the near column, the last four the far one. + // One row a turn, with the threadgroup's partials reused: the tree, the cross-warp sum and the lane + // shuffles are the shipped body's, so the row's sum does not move. + for (uint r = 0; r < R; ++r) { + const uint row = row0 + r; + if (row >= a.rows) break; + float acc0 = (acc[r][0] + acc[r][1]) + (acc[r][2] + acc[r][3]); + float acc1 = (acc[r][4] + acc[r][5]) + (acc[r][6] + acc[r][7]); +#if defined(TF_DIAG_DECODE) && TF_DIAG_DECODE == 5 + // ROUND-416 (the instrument, BENCH-ONLY): the CROSS-WARP REDUCTION gone (the multi body's own). +#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) { + 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); + if (sg == 0 and (lane & 3u) == 0u) { + sums[ulong(row) * a.n + nb + lane / 4] = acc0; + sums[ulong(row) * a.n + nb + 8 + lane / 4] = acc1; + } +#if TF_FMA_WARPS > 1 + // The next row reuses the partials: every thread reaches this barrier. + threadgroup_barrier(mem_flags::mem_threadgroup); +#endif + } +} + +// ROUND-338 bench arm: the register-only routed decode with the static state selection and the codebook read +// from a 1024-entry threadgroup LUT (the mul1 value depends only on the state's byte sum, so the 65,536-entry +// table holds 1,024 distinct values). The LUT's values are the table's, entry for entry, so the output is +// bit-identical; what the arm removes is the table's L2 traffic. +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; any other codebook reads + // the resident table (and the branch is uniform across the threadgroup, which shares one expert). + 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]); + } +} + +// ROUND-340: the register-only body on the DENSE one-row path. The routed decode (ROUND-336/337) already runs +// this structure -- one warp a sixteen-column tile, the eight decoded weights a lane in registers, no +// threadgroup weight tile and no barrier in the k walk, no split-K and no partials round trip -- and reaches +// 492 GB/s on the routed stage's shapes, while the dense one-row path's 128-column threadgroup-tile body runs +// the same shape class at half that rate. The dense matrix has no expert descriptor, so this kernel reads the +// trellis from the buffer and the strides, the width and the codebook from the args: the walk, the windows, +// the products and the reduction tree are the routed body's own code (the comparator's structure, from +// mlx-serve's dsv41_exl3_mul1h_k3 decode kernels, MIT/Apache-2.0; attribution per NOTICE), so the only +// difference from the routed body is where the five fields come from. +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; the + // LUT's values are the resident table's, entry for entry, so the output is the table's. + 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]); + } +} + +// ROUND-369: the multi-row dense body, two rows a threadgroup and four rows a threadgroup. The width is the +// matrix's (the dense pack's are 6, 10, 12 and 8 halves), so the body is specialised on it at dispatch. +template +inline void tf_exl3_decode_fma_dense_multi_kernel(const device half* x, const device uchar* trellis, + device float* sums, constant TfExl3Args& a, + const device half* table, uint lane, uint sg, uint tid, + uint3 tptg, uint3 tg, threadgroup float* red, + threadgroup half* lut) { + const uint halves = a.halves; + const bool mul1 = a.codebook == 2u; + if (halves == 6u) { + if (mul1) tf_exl3_decode_fma_dense_multi_body<3, true, R>(x, trellis, sums, a, table, lane, sg, tg, red, lut); + else tf_exl3_decode_fma_dense_multi_body<3, false, R>(x, trellis, sums, a, table, lane, sg, tg, red); + } else + if (halves == 10u) { + if (mul1) tf_exl3_decode_fma_dense_multi_body<5, true, R>(x, trellis, sums, a, table, lane, sg, tg, red, lut); + else tf_exl3_decode_fma_dense_multi_body<5, false, R>(x, trellis, sums, a, table, lane, sg, tg, red); + } else + if (halves == 12u) { + if (mul1) tf_exl3_decode_fma_dense_multi_body<6, true, R>(x, trellis, sums, a, table, lane, sg, tg, red, lut); + else tf_exl3_decode_fma_dense_multi_body<6, false, R>(x, trellis, sums, a, table, lane, sg, tg, red); + } else + if (halves == 8u) { + if (mul1) tf_exl3_decode_fma_dense_multi_body<4, true, R>(x, trellis, sums, a, table, lane, sg, tg, red, lut); + else tf_exl3_decode_fma_dense_multi_body<4, false, R>(x, trellis, sums, a, table, lane, sg, tg, red); + } else + if (halves == 4u) { + if (mul1) tf_exl3_decode_fma_dense_multi_body<2, true, R>(x, trellis, sums, a, table, lane, sg, tg, red, lut); + else tf_exl3_decode_fma_dense_multi_body<2, false, R>(x, trellis, sums, a, table, lane, sg, tg, red); + } else + if (halves == 2u) { + if (mul1) tf_exl3_decode_fma_dense_multi_body<1, true, R>(x, trellis, sums, a, table, lane, sg, tg, red, lut); + else tf_exl3_decode_fma_dense_multi_body<1, false, R>(x, trellis, sums, a, table, lane, sg, tg, red); + } +} + +// ROUND-443: THE SIXTEEN-STATE LANE PACKING (HANDOFF-80 item 0), BENCH-ONLY. The shipped register-only +// dense body gives a lane EIGHT consecutive states -- two columns by four k-rows of a 16x16 tile -- and reads +// three 32-bit stream words to decode them (7*S + 16 bits from its first state). This body gives a lane +// SIXTEEN consecutive states -- two columns by eight k-rows, p = 16L..16L+15 -- so the same lane reads four +// words (S = 5: the run is 15*5 + 16 = 91 bits) and the words a weight costs fall from 3/8 to 4/16. The warp +// still owns ONE sixteen-column tile: lanes 0..15 walk one 16-k block and lanes 16..31 the next, so the +// dispatch geometry, the column coverage and the split-K warp count are the shipped body's. The reduction +// order changes (two lanes a column, eight accumulators a column) so this is NOT bit-identical: it is a bench +// arm, and a landing would owe the FP64 reference and the band. The body is only compiled when TF_FMA_S16 is +// defined; no engine path selects it. +#if defined(TF_FMA_S16) +// The sixteen windows of a lane at compile-time shifts, from the four aligned 32-bit windows c0..c3 of its +// stream run. Same semantics as tf_exl3_state_static: the state's 16-bit window starts S*J bits into the run. +template +inline ushort tf_exl3_state_s16(uint c0, uint c1, uint c2, uint c3) { + const uint bit = S * J; + if (bit <= 16u) return ushort((c0 >> (16u - bit)) & 0xFFFFu); + if (bit <= 32u) return ushort(((c0 << (bit - 16u)) | (c1 >> (48u - bit))) & 0xFFFFu); + if (bit <= 48u) return ushort((c1 >> (48u - bit)) & 0xFFFFu); + if (bit <= 64u) return ushort(((c1 << (bit - 48u)) | (c2 >> (80u - bit))) & 0xFFFFu); + if (bit <= 80u) return ushort((c2 >> (80u - bit)) & 0xFFFFu); + if (bit <= 96u) return ushort(((c2 << (bit - 80u)) | (c3 >> (112u - bit))) & 0xFFFFu); + return ushort((c3 >> (112u - bit)) & 0xFFFFu); +} + +// One state, one product: the value from the resident table and the activation row the state's (row, column) +// pair names. The xv order is the caller's: index 4*(J>>3) + 2*((J>>1)&1) + (J&1), rows +// B + 2*(J>>3) + (J&1) + 8*((J>>1)&1) for the lane's B = 4*(L&1). +template +inline void tf_exl3_s16_step(float* acc, uint c0, uint c1, uint c2, uint c3, + const device half* table, uint codebook, const float* xv) { + const ushort s = tf_exl3_state_s16(c0, c1, c2, c3); + const float w = float(tf_exl3_table_value(table, s, codebook)); + const uint idx = 4u * (J >> 3) + 2u * ((J >> 1) & 1u) + (J & 1u); + *acc = fma(xv[idx], w, *acc); +} + +template +inline void tf_exl3_decode_s16_body(const device half* x, const device uchar* trellis, + device float* sums, constant TfExl3Args& a, + const device half* table, uint lane, uint sg, + uint3 tg, threadgroup float* red_all) { + const uint row = tg.y; + const uint nb = tg.x * 16u; + if (row >= a.rows or nb >= a.n) return; + const uint L = lane & 15u; + const uint g = lane >> 4; + const uint blocks = a.k / 16u; + const uint W = TF_FMA_WARPS; + const uint b0 = blocks * sg / W, b1 = blocks * (sg + 1u) / W; + const uint words = 4u * a.halves; + const uint p0 = L * 16u; + const uint wi0 = tf_exl3_map_for(p0, a.halves) & 63u; + const uint off0 = (tf_exl3_map_for(p0, a.halves) >> 6) & 31u; + const uint sh0 = (32u - off0) & 31u; + const uint m0 = 0u - uint(off0 != 0u); + uint a1 = wi0 + 1u; if (a1 >= words) a1 -= words; + uint a2 = wi0 + 2u; if (a2 >= words) a2 -= words; + uint a3 = wi0 + 3u; if (a3 >= words) a3 -= words; + uint a4 = wi0 + 4u; if (a4 >= words) a4 -= words; + // Four words cover S = 5 (91 bits); five cover S = 6 (106 bits from an offset of 22). + uint pre[5]; + const uint first = b0 + g; + if (first < b1) { + const device ushort* t0 = reinterpret_cast( + trellis + ulong(first) * a.tile_k_stride + ulong(nb / 16u) * a.tile_n_stride); + pre[0] = tf_exl3_word(t0, wi0); + pre[1] = tf_exl3_word(t0, a1); + pre[2] = tf_exl3_word(t0, a2); + pre[3] = tf_exl3_word(t0, a3); + if (S > 5u) pre[4] = tf_exl3_word(t0, a4); + } + float acc[16] = {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, + 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}; + for (uint bb = b0 + g; bb < b1; bb += 2u) { + const uint kb = bb * 16u; + const uint w0 = pre[0], w1 = pre[1], w2 = pre[2], w3 = pre[3]; + uint w4 = 0u; + if (S > 5u) w4 = pre[4]; + if (bb + 2u < b1) { + const device ushort* tn = reinterpret_cast( + trellis + ulong(bb + 2u) * a.tile_k_stride + ulong(nb / 16u) * a.tile_n_stride); + pre[0] = tf_exl3_word(tn, wi0); + pre[1] = tf_exl3_word(tn, a1); + pre[2] = tf_exl3_word(tn, a2); + pre[3] = tf_exl3_word(tn, a3); + if (S > 5u) pre[4] = tf_exl3_word(tn, a4); + } + // The lane's run as aligned 32-bit windows: one funnel shift a word, then fixed shifts a state. + const uint c0 = (w0 << off0) | ((w1 >> sh0) & m0); + const uint c1 = (w1 << off0) | ((w2 >> sh0) & m0); + const uint c2 = (w2 << off0) | ((w3 >> sh0) & m0); + uint c3 = 0u; + if (S > 5u) c3 = (w3 << off0) | ((w4 >> sh0) & m0); + // Eight activation values: the lane's eight k-rows, the same rows its two columns share. + const uint xo = kb + 4u * (L & 1u); + const device half* xr = x + ulong(row) * a.k + xo; + const half2 xa0 = *(const device half2*)xr; + const half2 xa1 = *(const device half2*)(xr + 2); + const half2 xb0 = *(const device half2*)(xr + 8); + const half2 xb1 = *(const device half2*)(xr + 10); + float xv[8]; + xv[0] = float(xa0.x); xv[1] = float(xa0.y); + xv[2] = float(xb0.x); xv[3] = float(xb0.y); + xv[4] = float(xa1.x); xv[5] = float(xa1.y); + xv[6] = float(xb1.x); xv[7] = float(xb1.y); + tf_exl3_s16_step(&acc[0], c0, c1, c2, c3, table, a.codebook, xv); + tf_exl3_s16_step(&acc[1], c0, c1, c2, c3, table, a.codebook, xv); + tf_exl3_s16_step(&acc[2], c0, c1, c2, c3, table, a.codebook, xv); + tf_exl3_s16_step(&acc[3], c0, c1, c2, c3, table, a.codebook, xv); + tf_exl3_s16_step(&acc[4], c0, c1, c2, c3, table, a.codebook, xv); + tf_exl3_s16_step(&acc[5], c0, c1, c2, c3, table, a.codebook, xv); + tf_exl3_s16_step(&acc[6], c0, c1, c2, c3, table, a.codebook, xv); + tf_exl3_s16_step(&acc[7], c0, c1, c2, c3, table, a.codebook, xv); + tf_exl3_s16_step(&acc[8], c0, c1, c2, c3, table, a.codebook, xv); + tf_exl3_s16_step(&acc[9], c0, c1, c2, c3, table, a.codebook, xv); + tf_exl3_s16_step(&acc[10], c0, c1, c2, c3, table, a.codebook, xv); + tf_exl3_s16_step(&acc[11], c0, c1, c2, c3, table, a.codebook, xv); + tf_exl3_s16_step(&acc[12], c0, c1, c2, c3, table, a.codebook, xv); + tf_exl3_s16_step(&acc[13], c0, c1, c2, c3, table, a.codebook, xv); + tf_exl3_s16_step(&acc[14], c0, c1, c2, c3, table, a.codebook, xv); + tf_exl3_s16_step(&acc[15], c0, c1, c2, c3, table, a.codebook, xv); + } + // Eight accumulators a column meet in a tree: the near column is J mod 8 < 4, the far one the rest. + float accA = ((acc[0] + acc[1]) + (acc[2] + acc[3])) + ((acc[8] + acc[9]) + (acc[10] + acc[11])); + float accB = ((acc[4] + acc[5]) + (acc[6] + acc[7])) + ((acc[12] + acc[13]) + (acc[14] + acc[15])); +#if TF_FMA_WARPS > 1 + red_all[sg * 64u + lane] = accA; + red_all[sg * 64u + 32u + lane] = accB; + threadgroup_barrier(mem_flags::mem_threadgroup); + if (sg != 0) return; + accA = 0.0f; + accB = 0.0f; + TF_UNROLL + for (uint w = 0; w < W; ++w) { + accA += red_all[w * 64u + lane]; + accB += red_all[w * 64u + 32u + lane]; + } +#endif + // Two lanes a column pair inside a 16-k block (the 8-row halves), then the two block halves. + accA += simd_shuffle_xor(accA, 1); + accB += simd_shuffle_xor(accB, 1); + accA += simd_shuffle_xor(accA, 16); + accB += simd_shuffle_xor(accB, 16); + if (sg == 0 and (lane & 17u) == 0u) { + const uint j = lane >> 1; + sums[ulong(row) * a.n + nb + j] = accA; + sums[ulong(row) * a.n + nb + 8u + j] = accB; + } +} + +kernel void tf_exl3_matmul_decode_fma_s16(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]], + uint tid [[thread_index_in_threadgroup]], + uint3 tptg [[threads_per_threadgroup]], + uint3 tg [[threadgroup_position_in_grid]]) { + threadgroup float red[TF_FMA_WARPS][64]; + if (a.halves == 10u) tf_exl3_decode_s16_body<5>(x, trellis, sums, a, table, lane, sg, tg, &red[0][0]); + else if (a.halves == 12u) tf_exl3_decode_s16_body<6>(x, trellis, sums, a, table, lane, sg, tg, &red[0][0]); +} +#endif + +kernel void tf_exl3_matmul_decode_fma_dense_multi2(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 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); + } + tf_exl3_decode_fma_dense_multi_kernel<2>(x, trellis, sums, a, +#if defined(TF_DECODE_TABLE) + table, +#else + nullptr, +#endif + lane, sg, tid, tptg, tg, &red[0][0], lut); +} + +kernel void tf_exl3_matmul_decode_fma_dense_multi4(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 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); + } + tf_exl3_decode_fma_dense_multi_kernel<4>(x, trellis, sums, a, +#if defined(TF_DECODE_TABLE) + table, +#else + nullptr, +#endif + lane, sg, tid, tptg, tg, &red[0][0], lut); +} + +template +inline void tf_exl3_decode_fma_static_pair_body(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_all, + threadgroup half* lut = nullptr) { + const uint row = tg.y; + const uint nb = tg.x * 16u; + if (row >= a.rows or nb >= a.n) return; + // ROUND-370: THE PAIR. The entries that name the same expert, in entry order, are ranked; the even ranks + // lead a pair (their entry and the next one with the same expert) and the odd ranks exit, so the weight + // decode -- and the weight traffic -- is paid once for the pair. The comparator's own shape + // (mlx-serve's dspark pair kernel, MIT/Apache-2.0; the attribution is carried in the kernel): one decode + // for the rows that share a weight. Each row keeps the shipped per-row arithmetic, so the pair's rows are + // bit-identical to the single-row body's. + const uint slot = routes[row]; + uint rank = 0u; + uint mate = row; + for (uint j = 0; j < a.rows; ++j) { + const uint same = (routes[j] == slot) ? 1u : 0u; + rank += (j < row) ? same : 0u; + if (mate == row and j > row and same == 1u) mate = j; + } + if ((rank & 1u) != 0u) return; // the odd rank's row is computed by its leader + const bool paired = mate != row; + const device uchar* data; + ulong ks; + ulong ns; + uint halves; + uint codebook; + { + const uint expert = slot; + if (expert >= a.experts) return; + data = descriptors[expert].trellis; + ks = descriptors[expert].tile_k_stride; + ns = descriptors[expert].tile_n_stride; + halves = descriptors[expert].halves; + 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; + const uint words = 4 * halves; + const uint wi0 = tf_exl3_map_for(lane * 8u, halves) & 63u; + // The lane's bit offset inside its first word: the one runtime shift of the body. + const uint off0 = (tf_exl3_map_for(lane * 8u, halves) >> 6) & 31u; + const uint sh0 = (32u - off0) & 31u; + const uint m0 = 0u - uint(off0 != 0u); + uint a1 = wi0 + 1; if (a1 >= words) a1 -= words; + uint a2 = wi0 + 2; if (a2 >= words) a2 -= words; + // 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(data + ulong(b0) * ks + ulong(nb / 16) * ns); + pre[0] = tf_exl3_word(t0, wi0); + pre[1] = tf_exl3_word(t0, a1); + pre[2] = tf_exl3_word(t0, a2); + } + float acc[8] = {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}; + float accb[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(data + ulong(bb + 1) * ks + ulong(nb / 16) * ns); + pre[0] = tf_exl3_word(tn, wi0); + pre[1] = tf_exl3_word(tn, a1); + pre[2] = tf_exl3_word(tn, a2); + } + // The lane's window: one runtime funnel shift, then the eight windows at compile-time shifts. + const uint c_cur = (w0 << off0) | ((w1 >> sh0) & m0); + const uint c_next = (w1 << off0) | ((w2 >> sh0) & m0); + // 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 + // ROUND-416 (the instrument, BENCH-ONLY): the ACTIVATION READ gone -- the x row is not read at all. + // The FMA stays (the weight is still needed) and the constant is a RUNTIME value (the args' rows), so + // the compiler cannot fold the multiply away and the arm prices the read, not the arithmetic. + 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, codebook, x0, x1, x2, x3, lut); + tf_exl3_fma_step(&acc[1], c_cur, c_next, table, codebook, x0, x1, x2, x3, lut); + tf_exl3_fma_step(&acc[2], c_cur, c_next, table, codebook, x0, x1, x2, x3, lut); + tf_exl3_fma_step(&acc[3], c_cur, c_next, table, codebook, x0, x1, x2, x3, lut); + tf_exl3_fma_step(&acc[4], c_cur, c_next, table, codebook, x0, x1, x2, x3, lut); + tf_exl3_fma_step(&acc[5], c_cur, c_next, table, codebook, x0, x1, x2, x3, lut); + tf_exl3_fma_step(&acc[6], c_cur, c_next, table, codebook, x0, x1, x2, x3, lut); + tf_exl3_fma_step(&acc[7], c_cur, c_next, table, codebook, x0, x1, x2, x3, lut); + if (paired) { + // The mate's row: the same weights, the same products, the mate's own activations. + const device half* xm = x + ulong(mate) * a.k + kb + 2 * (lane & 3u); + const half2 ma = *(const device half2*)xm; + const half2 mb = *(const device half2*)(xm + 8); + const float y0 = float(ma.x), y1 = float(ma.y), y2 = float(mb.x), y3 = float(mb.y); + tf_exl3_fma_step(&accb[0], c_cur, c_next, table, codebook, y0, y1, y2, y3, lut); + tf_exl3_fma_step(&accb[1], c_cur, c_next, table, codebook, y0, y1, y2, y3, lut); + tf_exl3_fma_step(&accb[2], c_cur, c_next, table, codebook, y0, y1, y2, y3, lut); + tf_exl3_fma_step(&accb[3], c_cur, c_next, table, codebook, y0, y1, y2, y3, lut); + tf_exl3_fma_step(&accb[4], c_cur, c_next, table, codebook, y0, y1, y2, y3, lut); + tf_exl3_fma_step(&accb[5], c_cur, c_next, table, codebook, y0, y1, y2, y3, lut); + tf_exl3_fma_step(&accb[6], c_cur, c_next, table, codebook, y0, y1, y2, y3, lut); + tf_exl3_fma_step(&accb[7], c_cur, c_next, table, codebook, y0, y1, y2, y3, lut); + } + } + // The eight accumulators meet in a tree: the first four are the near column, the last four the far one. + // The shipped tree, the shipped cross-warp sum and the shipped lane shuffles, one row a turn. + for (uint part = 0; part < 2u; ++part) { + const uint out_row = part == 0 ? row : mate; + if (part == 1u and !paired) break; + float acc0 = (acc[0] + acc[1]) + (acc[2] + acc[3]); + float acc1 = (acc[4] + acc[5]) + (acc[6] + acc[7]); + if (part == 1u) { + acc0 = (accb[0] + accb[1]) + (accb[2] + accb[3]); + acc1 = (accb[4] + accb[5]) + (accb[6] + accb[7]); + } +#if defined(TF_DIAG_DECODE) && TF_DIAG_DECODE == 5 + // ROUND-416 (the instrument, BENCH-ONLY): the CROSS-WARP REDUCTION gone (the multi body's own). +#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) { + 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); + if (sg == 0 and (lane & 3u) == 0u) { + sums[ulong(out_row) * a.n + nb + lane / 4] = acc0; + sums[ulong(out_row) * a.n + nb + 8 + lane / 4] = acc1; + } +#if TF_FMA_WARPS > 1 + // The mate's turn reuses the partials: every thread reaches this barrier. + threadgroup_barrier(mem_flags::mem_threadgroup); +#endif + } +} + + +// ROUND-370: the paired routed decode (the resident table): the entries +// that name the same expert are computed in one threadgroup, one weight decode for the pair. The comparator's +// own shape (mlx-serve's dspark pair kernel, MIT/Apache-2.0; the attribution is carried in the kernel). +kernel void tf_exl3_matmul_decode_fma_static_pair(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 mul1 codebook's values depend only on the state's byte sum, so 1,024 entries hold every value; the + // LUT's values are the resident table's, entry for entry, so the output is the table's. + 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) + tf_exl3_decode_fma_static_pair_body<3, false>(x, trellis, sums, a, routes, descriptors, +#if defined(TF_DECODE_TABLE) + table, +#else + nullptr, +#endif + lane, sg, tg, &red[0][0]); + else if (halves == 10u) + tf_exl3_decode_fma_static_pair_body<5, false>(x, trellis, sums, a, routes, descriptors, +#if defined(TF_DECODE_TABLE) + table, +#else + nullptr, +#endif + lane, sg, tg, &red[0][0]); + else if (halves == 12u) + tf_exl3_decode_fma_static_pair_body<6, false>(x, trellis, sums, a, routes, descriptors, +#if defined(TF_DECODE_TABLE) + table, +#else + nullptr, +#endif + lane, sg, tg, &red[0][0]); + else if (halves == 8u) + tf_exl3_decode_fma_static_pair_body<4, false>(x, trellis, sums, a, routes, descriptors, +#if defined(TF_DECODE_TABLE) + table, +#else + nullptr, +#endif + lane, sg, tg, &red[0][0]); + else if (halves == 4u) + tf_exl3_decode_fma_static_pair_body<2, false>(x, trellis, sums, a, routes, descriptors, +#if defined(TF_DECODE_TABLE) + table, +#else + nullptr, +#endif + lane, sg, tg, &red[0][0]); + else if (halves == 2u) + tf_exl3_decode_fma_static_pair_body<1, false>(x, trellis, sums, a, routes, descriptors, +#if defined(TF_DECODE_TABLE) + table, +#else + nullptr, +#endif + lane, sg, tg, &red[0][0]); +} + +// ROUND-370: the paired routed decode (with the codebook LUT): the entries +// that name the same expert are computed in one threadgroup, one weight decode for the pair. The comparator's +// own shape (mlx-serve's dspark pair kernel, MIT/Apache-2.0; the attribution is carried in the kernel). +kernel void tf_exl3_matmul_decode_fma_static_pair_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 mul1 codebook's values depend only on the state's byte sum, so 1,024 entries hold every value; the + // LUT's values are the resident table's, entry for entry, so the output is the table's. + 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) + tf_exl3_decode_fma_static_pair_body<3, true>(x, trellis, sums, a, routes, descriptors, +#if defined(TF_DECODE_TABLE) + table, +#else + nullptr, +#endif + lane, sg, tg, &red[0][0], lut); + else if (halves == 10u) + tf_exl3_decode_fma_static_pair_body<5, true>(x, trellis, sums, a, routes, descriptors, +#if defined(TF_DECODE_TABLE) + table, +#else + nullptr, +#endif + lane, sg, tg, &red[0][0], lut); + else if (halves == 12u) + tf_exl3_decode_fma_static_pair_body<6, true>(x, trellis, sums, a, routes, descriptors, +#if defined(TF_DECODE_TABLE) + table, +#else + nullptr, +#endif + lane, sg, tg, &red[0][0], lut); + else if (halves == 8u) + tf_exl3_decode_fma_static_pair_body<4, true>(x, trellis, sums, a, routes, descriptors, +#if defined(TF_DECODE_TABLE) + table, +#else + nullptr, +#endif + lane, sg, tg, &red[0][0], lut); + else if (halves == 4u) + tf_exl3_decode_fma_static_pair_body<2, true>(x, trellis, sums, a, routes, descriptors, +#if defined(TF_DECODE_TABLE) + table, +#else + nullptr, +#endif + lane, sg, tg, &red[0][0], lut); + else if (halves == 2u) + tf_exl3_decode_fma_static_pair_body<1, true>(x, trellis, sums, a, routes, descriptors, +#if defined(TF_DECODE_TABLE) + table, +#else + nullptr, +#endif + lane, sg, tg, &red[0][0], lut); +} +// ROUND-338 bench arm: the register-only routed decode with the static state selection. 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]); +} +// ROUND-435: THE COMPARATOR'S ROUTED PREFILL GEOMETRY (mlx-serve's dsv41_prefill_dig_gemm_*_m128, MIT/Apache-2.0, +// attribution). BM 128, BN 64, BK 64: eight simdgroups (WM 4 x WN 2), each owning a 32 x 32 output tile; the +// eight simdgroups cooperatively decode the whole 64 x 64 weight stage (two 16x16 trellis tiles each) into one +// row-major B tile, and every simdgroup multiplies the shared stage. Per output the k order and the MMA order are +// nax31's, so `sums` is bit-identical; only the stage depth, the warp tile and the cooperative decode differ. +// The stage is DOUBLE-BUFFERED and the next stage's decode is issued before the current stage's multiply, so +// the codebook ALU and the stream loads overlap the tensor units (the comparator's deeper stage, our overlap). +template +inline void tf_exl3_cmp_decode_stage(threadgroup half* wx, const device uchar* data, ulong ks, ulong ns, + uint nb, uint s, uint sg, uint wi0, uint words, uint b0, uint halves, + uint codebook, const device half* table, + const uint* k_l, const uint* c_l, const uint* off, const uint* sh, const uint* rel) { + const uint tiles_t = sg * 2u; + TF_UNROLL + for (uint j = 0; j < 2u; ++j) { + const uint t = tiles_t + j; + const uint nt = t & 3u, kt = t >> 2u; + uint at[8]; + TF_UNROLL + for (uint k = 0; k < 8u; ++k) at[k] = (kt * 16u + k_l[k]) * 72u + nt * 16u + c_l[k]; + const uint kb = s + kt * 16u; + const uint w0 = tf_exl3_block_word(data, ks, ns, kb, nb, 0, nt, wi0, words); + const uint w1 = tf_exl3_block_word(data, ks, ns, kb, nb, 0, nt, wi0 + 1u, words); + if (UseTable and halves == 6u) { + // The lane's eight 3-bit windows are 37 bits, so two words hold the run (the funnel path). + tf_exl3_decode_funnel<8>(wx, table, nullptr, codebook, at, b0, halves >> 1, w0, w1); + } else if (UseTable) { + const uint w2 = tf_exl3_block_word(data, ks, ns, kb, nb, 0, nt, wi0 + 2u, words); + const uint w3 = tf_exl3_block_word(data, ks, ns, kb, nb, 0, nt, wi0 + 3u, words); + tf_exl3_decode_table<8>(wx, table, codebook, at, off, sh, rel, w0, w1, w2, w3); + } else { + const uint w2 = tf_exl3_block_word(data, ks, ns, kb, nb, 0, nt, wi0 + 2u, words); + const uint w3 = tf_exl3_block_word(data, ks, ns, kb, nb, 0, nt, wi0 + 3u, words); + tf_exl3_decode_fast<8>(wx, codebook, at, off, sh, rel, w0, w1, w2, w3); + } + } +} + +template +inline void tf_exl3_prefill_body_cmp(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, uint3 tg) { + constexpr uint LDB = 72u; + constexpr uint STAGE = 64u * 72u; + const uint trows = 128u; + const uint rb = tg.y * trows, nb = tg.x * 64u; + if (a.indexed == 1 || rb >= a.rows || nb >= a.n) return; + const uint tile_expert = a.indexed ? routes[rb] : a.expert_id; + if (a.indexed && tile_expert >= a.experts) return; + const uint didx = a.indexed ? tile_expert : 0; + const device uchar* data = a.indexed ? descriptors[didx].trellis : trellis; + const ulong ks = a.indexed ? descriptors[didx].tile_k_stride : a.tile_k_stride; + const ulong ns = a.indexed ? descriptors[didx].tile_n_stride : a.tile_n_stride; + const uint halves = a.indexed ? descriptors[didx].halves : a.halves; + const uint codebook = a.indexed ? descriptors[didx].codebook : a.codebook; + const short2 home = frag_home(ushort(lane)); + const uint rows_here = min(trows, a.rows - rb); + const uint cols_here = min(64u, a.n - nb); + const uint tm = 32u * (sg >> 1u), tn = 32u * (sg & 1u); + // This lane's eight consecutive states of one 16x16 tile; the same map the shipped body uses. + const uint p0 = lane * 8u; + const uint m0 = tf_exl3_map_for(p0, halves); + const uint wi0 = m0 & 63u; + const uint b0 = (m0 >> 6) & 31u; + const uint words = 4u * halves; + const uint ring = 128u * halves; + const uint cur0 = (wi0 << 5) | b0; + uint k_l[8], c_l[8], off[8], sh[8], rel[8]; + TF_UNROLL + for (uint k = 0; k < 8u; ++k) { + const uint p = p0 + k, l = p / 8u, e = p % 8u; + // The pack's per-state map: k_local is the 64-stride axis, c_local the +1 axis. + k_l[k] = 2u * (l % 4u) + (e & 1u) + 8u * ((e >> 1u) & 1u); + c_l[k] = l / 4u + 8u * (e >> 2u); + uint c8 = cur0 + k * (halves >> 1); + if (c8 >= ring) c8 -= ring; + const uint wi = c8 >> 5; + off[k] = c8 & 31u; + sh[k] = (32u - off[k]) & 31u; + rel[k] = wi >= wi0 ? wi - wi0 : wi + words - wi0; + } + // The padded-row skip at the 16-row group (nax59/nax76's form). + bool lo_live = true, hi_live = true; + if (a.indexed != 0) { + const uint g = rb + tm + lane; + const bool gv = g < a.rows and routes[g] != 0xffffffffu; + lo_live = simd_any(gv and lane < 16u); + hi_live = simd_any(gv and lane >= 16u); + } + frag lo0 = frag(0), hi0 = frag(0); + frag lo1 = frag(0), hi1 = frag(0); + // Stage 0 into buffer 0, then one barrier before the first multiply. + tf_exl3_cmp_decode_stage(wx, data, ks, ns, nb, 0u, sg, wi0, words, b0, halves, codebook, table, + k_l, c_l, off, sh, rel); + threadgroup_barrier(mem_flags::mem_threadgroup); + uint nst = 0u; + for (uint s = 0; s + 64u <= a.k; s += 64u, ++nst) { + const threadgroup half* bs = wx + (nst & 1u) * STAGE; + if (lo_live or hi_live) { + TF_UNROLL + for (uint i = 0; i < 2u; ++i) { + frag av0, av1; + if (lo_live) tf_frag_get_dev4(av0, x, int(a.k), int(rb + tm), int(s + i * 32u), home, int(rb + rows_here)); + if (hi_live) tf_frag_get_dev4(av1, x, int(a.k), int(rb + tm + 16u), int(s + i * 32u), home, int(rb + rows_here)); + TF_UNROLL + for (uint kk = 0; kk < 2u; ++kk) { + const int kc = int(i * 32u + kk * 16u); + frag bb0, bb1; + tf_frag_get_tg4(bb0, bs, int(LDB), kc, int(tn), home); + tf_frag_get_tg4(bb1, bs, int(LDB), kc, int(tn + 16u), home); + if (lo_live) mma_16x32(lo0, hi0, av0, bb0, bb1); + if (hi_live) mma_16x32(lo1, hi1, av1, bb0, bb1); + } + } + } + if (s + 64u < a.k) { + tf_exl3_cmp_decode_stage(wx + ((nst & 1u) ^ 1u) * STAGE, data, ks, ns, nb, s + 64u, sg, + wi0, words, b0, halves, codebook, table, k_l, c_l, off, sh, rel); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + } + const int r0 = int(rb + tm), c0 = int(nb + tn); + frag_put_in(lo0, sums, int(a.n), r0, c0, home, int(rb + rows_here), int(nb + cols_here)); + frag_put_in(hi0, sums, int(a.n), r0, c0 + 16, home, int(rb + rows_here), int(nb + cols_here)); + frag_put_in(lo1, sums, int(a.n), r0 + 16, c0, home, int(rb + rows_here), int(nb + cols_here)); + frag_put_in(hi1, sums, int(a.n), r0 + 16, c0 + 16, home, int(rb + rows_here), int(nb + cols_here)); +} + +kernel void tf_exl3_matmul_prefill_nax84(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)]], + const device half* const table [[buffer(7)]], + 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 * 64 * 72]; + tf_exl3_prefill_body_cmp(wx, x, trellis, sums, a, routes, descriptors, table, lane, sg, tid, tg); +} + + +// --------------------------------------------------------------------------------------------------------------- +// ROUND-437 (instrument, bench-only): the routed prompt stream's READ arms. These kernels read the trellis bytes +// with the shipped tile's addresses and no decode / no activation / no MMA, so the stream's own rate can be priced +// without the two other LSU streams. They are never selected by the engine (no dispatcher references them). +// The sink index is tg.x * 128 + tg.y * 8192 + tid, so every arm writes a distinct word and no load is dead. +// --------------------------------------------------------------------------------------------------------------- +kernel void tf_exl3_stream_read_nax90(const device half* x [[buffer(0)]], + const device uchar* trellis [[buffer(1)]], + device uint* sink [[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]]) { + const uint rb = tg.y * 64u, nb = tg.x * 64u; + if (rb >= a.rows) return; + const uint e = routes[rb]; + if (e >= a.experts) return; + const device uchar* data = descriptors[e].trellis; + const ulong ks = descriptors[e].tile_k_stride, ns = descriptors[e].tile_n_stride; + const uint halves = descriptors[e].halves, words = 4u * halves; + const uint h = sg & 3u; + const device ushort* t0 = reinterpret_cast(data + ulong(nb / 16u + h) * ns); + uint acc = 0u; + uint cur = (lane < words) ? tf_exl3_word(t0, lane) : 0u; + for (uint kb = 0; kb < a.k; kb += 16u) { + const uint nkb = kb + 16u; + uint nxt = 0u; + if (nkb < a.k and lane < words) { + const device ushort* tn = reinterpret_cast(data + ulong(nkb / 16u) * ks + ulong(nb / 16u + h) * ns); + nxt = tf_exl3_word(tn, lane); + } + acc ^= cur; + cur = nxt; + } + sink[tg.x * 128u + tg.y * 8192u + tid] = acc; +} + +kernel void tf_exl3_stream_read_nax91(const device half* x [[buffer(0)]], + const device uchar* trellis [[buffer(1)]], + device uint* sink [[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]]) { + const uint rb = tg.y * 64u, nb = tg.x * 64u; + if (rb >= a.rows) return; + const uint e = routes[rb]; + if (e >= a.experts) return; + const device uchar* data = descriptors[e].trellis; + const ulong ks = descriptors[e].tile_k_stride, ns = descriptors[e].tile_n_stride; + const uint halves = descriptors[e].halves, words = 4u * halves; + const uint h = sg & 3u; + const uint nwords = words / 4u; + const device ushort* t0 = reinterpret_cast(data + ulong(nb / 16u + h) * ns); + uint acc = 0u; + uint4 cur = uint4(0u, 0u, 0u, 0u); + if (lane < nwords) cur = reinterpret_cast(t0)[lane]; + for (uint kb = 0; kb < a.k; kb += 16u) { + const uint nkb = kb + 16u; + uint4 nxt = uint4(0u, 0u, 0u, 0u); + if (nkb < a.k and lane < nwords) { + const device ushort* tn = reinterpret_cast(data + ulong(nkb / 16u) * ks + ulong(nb / 16u + h) * ns); + nxt = reinterpret_cast(tn)[lane]; + } + acc ^= cur.x ^ cur.y ^ cur.z ^ cur.w; + cur = nxt; + } + sink[tg.x * 128u + tg.y * 8192u + tid] = acc; +} + +// The shipped per-lane cursor: two 32-bit words a lane, eight states a lane (the nax59 funnel's read count). +kernel void tf_exl3_stream_read_nax92(const device half* x [[buffer(0)]], + const device uchar* trellis [[buffer(1)]], + device uint* sink [[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]]) { + const uint rb = tg.y * 64u, nb = tg.x * 64u; + if (rb >= a.rows) return; + const uint e = routes[rb]; + if (e >= a.experts) return; + const device uchar* data = descriptors[e].trellis; + const ulong ks = descriptors[e].tile_k_stride, ns = descriptors[e].tile_n_stride; + const uint halves = descriptors[e].halves, words = 4u * halves; + const uint h = sg & 3u; + const uint p0 = (tid % 32u) * 8u; + const uint wi0 = tf_exl3_map_for(p0, halves) & 63u; + const uint wi1 = (wi0 + 1u < words) ? wi0 + 1u : wi0 + 1u - words; + const device ushort* t0 = reinterpret_cast(data + ulong(nb / 16u + h) * ns); + uint acc = 0u; + uint w0 = tf_exl3_word(t0, wi0), w1 = tf_exl3_word(t0, wi1); + for (uint kb = 0; kb < a.k; kb += 16u) { + const uint nkb = kb + 16u; + uint n0 = 0u, n1 = 0u; + if (nkb < a.k) { + const device ushort* tn = reinterpret_cast(data + ulong(nkb / 16u) * ks + ulong(nb / 16u + h) * ns); + n0 = tf_exl3_word(tn, wi0); n1 = tf_exl3_word(tn, wi1); + } + acc ^= w0 ^ w1; + w0 = n0; w1 = n1; + } + sink[tg.x * 128u + tg.y * 8192u + tid] = acc; +} + +// The whole expert slab, one threadgroup an expert: the fully sequential schedule (144 n-tiles a k block). +kernel void tf_exl3_stream_read_nax93(const device half* x [[buffer(0)]], + const device uchar* trellis [[buffer(1)]], + device uint* sink [[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]]) { + const uint e = tg.y; + if (e >= a.experts) return; + const device uchar* data = descriptors[e].trellis; + const ulong ks = descriptors[e].tile_k_stride, ns = descriptors[e].tile_n_stride; + const uint halves = descriptors[e].halves, words = 4u * halves; + const uint nwords = words / 4u; + const uint base = sg * 36u; + uint acc = 0u; + for (uint kb = 0; kb < a.k; kb += 16u) { + for (uint g = 0; g < 36u; g += 4u) { + uint4 v0 = uint4(0u, 0u, 0u, 0u), v1 = uint4(0u, 0u, 0u, 0u), v2 = uint4(0u, 0u, 0u, 0u), v3 = uint4(0u, 0u, 0u, 0u); + if (lane < nwords) { + const ulong koff = ulong(kb / 16u) * ks; + const ulong boff = ulong(base + g) * ns; + v0 = reinterpret_cast(data + koff + boff)[lane]; + v1 = reinterpret_cast(data + koff + boff + ns)[lane]; + v2 = reinterpret_cast(data + koff + boff + 2u * ns)[lane]; + v3 = reinterpret_cast(data + koff + boff + 3u * ns)[lane]; + } + acc ^= v0.x ^ v0.y ^ v0.z ^ v0.w ^ v1.x ^ v1.y ^ v1.z ^ v1.w ^ + v2.x ^ v2.y ^ v2.z ^ v2.w ^ v3.x ^ v3.y ^ v3.z ^ v3.w; + } + } + sink[tg.x * 128u + tg.y * 8192u + tid] = acc; +} + +// The same read with the GRID TRANSPOSED: consecutive threadgroups are experts at the same column tile. +kernel void tf_exl3_stream_read_nax94(const device half* x [[buffer(0)]], + const device uchar* trellis [[buffer(1)]], + device uint* sink [[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]]) { + const uint rb = tg.x * 64u, nb = tg.y * 64u; + if (rb >= a.rows) return; + const uint e = routes[rb]; + if (e >= a.experts) return; + const device uchar* data = descriptors[e].trellis; + const ulong ks = descriptors[e].tile_k_stride, ns = descriptors[e].tile_n_stride; + const uint halves = descriptors[e].halves, words = 4u * halves; + const uint h = sg & 3u; + const device ushort* t0 = reinterpret_cast(data + ulong(nb / 16u + h) * ns); + uint acc = 0u; + uint cur = (lane < words) ? tf_exl3_word(t0, lane) : 0u; + for (uint kb = 0; kb < a.k; kb += 16u) { + const uint nkb = kb + 16u; + uint nxt = 0u; + if (nkb < a.k and lane < words) { + const device ushort* tn = reinterpret_cast(data + ulong(nkb / 16u) * ks + ulong(nb / 16u + h) * ns); + nxt = tf_exl3_word(tn, lane); + } + acc ^= cur; + cur = nxt; + } + sink[tg.x * 128u + tg.y * 8192u + tid] = acc; +} + +// Eight warps a threadgroup, the k walk split in two halves: more independent streams per threadgroup. +kernel void tf_exl3_stream_read_nax95(const device half* x [[buffer(0)]], + const device uchar* trellis [[buffer(1)]], + device uint* sink [[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]]) { + const uint rb = tg.y * 64u, nb = tg.x * 64u; + if (rb >= a.rows) return; + const uint e = routes[rb]; + if (e >= a.experts) return; + const device uchar* data = descriptors[e].trellis; + const ulong ks = descriptors[e].tile_k_stride, ns = descriptors[e].tile_n_stride; + const uint halves = descriptors[e].halves, words = 4u * halves; + const uint h = sg & 3u, kh = sg >> 2; + const device ushort* t0 = reinterpret_cast(data + ulong(nb / 16u + h) * ns); + uint acc = 0u; + uint cur = (lane < words) ? tf_exl3_word(reinterpret_cast(data + ulong(kh) * ks + ulong(nb / 16u + h) * ns), lane) : 0u; + for (uint kb = kh * 16u; kb < a.k; kb += 32u) { + const uint nkb = kb + 32u; + uint nxt = 0u; + if (nkb < a.k and lane < words) { + const device ushort* tn = reinterpret_cast(data + ulong(nkb / 16u) * ks + ulong(nb / 16u + h) * ns); + nxt = tf_exl3_word(tn, lane); + } + acc ^= cur; + cur = nxt; + } + sink[tg.x * 128u + tg.y * 8192u + tid] = acc; +} + + +// ROUND-437: the 64-column tile's four 16-column n-tiles are CONTIGUOUS (ns = 96 B), so one 384-byte chunk a k +// block. This arm reads that chunk with 24 lanes of 16-byte loads -- the same bytes, a quarter of the requests. +kernel void tf_exl3_stream_read_nax96(const device half* x [[buffer(0)]], + const device uchar* trellis [[buffer(1)]], + device uint* sink [[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]]) { + const uint rb = tg.y * 64u, nb = tg.x * 64u; + if (rb >= a.rows) return; + const uint e = routes[rb]; + if (e >= a.experts) return; + const device uchar* data = descriptors[e].trellis; + const ulong ks = descriptors[e].tile_k_stride, ns = descriptors[e].tile_n_stride; + const uint blocks = a.k / 16u; + const uint per = (blocks + 3u) / 4u; + const uint kb0 = sg * per; + const uint kb1 = min(kb0 + per, blocks); + uint acc = 0u; + uint4 cur = uint4(0u, 0u, 0u, 0u); + if (lane < 24u and kb0 < kb1) { + const device uchar* ch = data + ulong(kb0) * ks + ulong(nb / 16u) * ns; + cur = reinterpret_cast(ch)[lane]; + } + for (uint kb = kb0; kb < kb1; ++kb) { + uint4 nxt = uint4(0u, 0u, 0u, 0u); + if (lane < 24u and kb + 1u < kb1) { + const device uchar* ch = data + ulong(kb + 1u) * ks + ulong(nb / 16u) * ns; + nxt = reinterpret_cast(ch)[lane]; + } + acc ^= cur.x ^ cur.y ^ cur.z ^ cur.w; + cur = nxt; + } + sink[tg.x * 128u + tg.y * 8192u + tid] = acc; +} + +kernel void tf_exl3_stream_read_nax97(const device half* x [[buffer(0)]], + const device uchar* trellis [[buffer(1)]], + device uint* sink [[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]]) { + const uint rb = tg.y * 64u, nb = tg.x * 64u; + if (rb >= a.rows) return; + const uint e = routes[rb]; + if (e >= a.experts) return; + const device uchar* data = descriptors[e].trellis; + const ulong ks = descriptors[e].tile_k_stride, ns = descriptors[e].tile_n_stride; + const uint blocks = a.k / 16u; + const uint per = (blocks + 7u) / 8u; + const uint kb0 = sg * per; + const uint kb1 = min(kb0 + per, blocks); + uint acc = 0u; + uint4 cur = uint4(0u, 0u, 0u, 0u); + if (lane < 24u and kb0 < kb1) { + const device uchar* ch = data + ulong(kb0) * ks + ulong(nb / 16u) * ns; + cur = reinterpret_cast(ch)[lane]; + } + for (uint kb = kb0; kb < kb1; ++kb) { + uint4 nxt = uint4(0u, 0u, 0u, 0u); + if (lane < 24u and kb + 1u < kb1) { + const device uchar* ch = data + ulong(kb + 1u) * ks + ulong(nb / 16u) * ns; + nxt = reinterpret_cast(ch)[lane]; + } + acc ^= cur.x ^ cur.y ^ cur.z ^ cur.w; + cur = nxt; + } + sink[tg.x * 128u + (tg.y * 8192u) + tid] = acc; +} + +// The expert slab with sixteen warps, each nine n-tiles a k block: nine independent 16-byte loads a lane. +kernel void tf_exl3_stream_read_nax98(const device half* x [[buffer(0)]], + const device uchar* trellis [[buffer(1)]], + device uint* sink [[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]]) { + const uint e = tg.y; + if (e >= a.experts) return; + const device uchar* data = descriptors[e].trellis; + const ulong ks = descriptors[e].tile_k_stride, ns = descriptors[e].tile_n_stride; + const uint base = sg * 9u; + uint acc = 0u; + for (uint kb = 0; kb < a.k; kb += 16u) { + const ulong koff = ulong(kb / 16u) * ks; + uint4 v0 = uint4(0u, 0u, 0u, 0u), v1 = uint4(0u, 0u, 0u, 0u), v2 = uint4(0u, 0u, 0u, 0u); + uint4 v3 = uint4(0u, 0u, 0u, 0u), v4 = uint4(0u, 0u, 0u, 0u), v5 = uint4(0u, 0u, 0u, 0u); + uint4 v6 = uint4(0u, 0u, 0u, 0u), v7 = uint4(0u, 0u, 0u, 0u), v8 = uint4(0u, 0u, 0u, 0u); + if (lane < 6u) { + v0 = reinterpret_cast(data + koff + ulong(base) * ns)[lane]; + v1 = reinterpret_cast(data + koff + ulong(base + 1u) * ns)[lane]; + v2 = reinterpret_cast(data + koff + ulong(base + 2u) * ns)[lane]; + v3 = reinterpret_cast(data + koff + ulong(base + 3u) * ns)[lane]; + v4 = reinterpret_cast(data + koff + ulong(base + 4u) * ns)[lane]; + v5 = reinterpret_cast(data + koff + ulong(base + 5u) * ns)[lane]; + v6 = reinterpret_cast(data + koff + ulong(base + 6u) * ns)[lane]; + v7 = reinterpret_cast(data + koff + ulong(base + 7u) * ns)[lane]; + v8 = reinterpret_cast(data + koff + ulong(base + 8u) * ns)[lane]; + } + acc ^= v0.x ^ v0.y ^ v0.z ^ v0.w ^ v1.x ^ v1.y ^ v1.z ^ v1.w ^ v2.x ^ v2.y ^ v2.z ^ v2.w ^ + v3.x ^ v3.y ^ v3.z ^ v3.w ^ v4.x ^ v4.y ^ v4.z ^ v4.w ^ v5.x ^ v5.y ^ v5.z ^ v5.w ^ + v6.x ^ v6.y ^ v6.z ^ v6.w ^ v7.x ^ v7.y ^ v7.z ^ v7.w ^ v8.x ^ v8.y ^ v8.z ^ v8.w; + } + sink[tg.x * 128u + tg.y * 8192u + tid] = acc; +} + + +// ROUND-437: the absolute ceiling control -- 1.716 GB read LINEARLY, one threadgroup a 122,880-byte contiguous +// range, four independent 16-byte loads a thread a wave. If this does not reach the box's peak, the peak is not +// available to a cold stream of this size; if it does, the scattered slabs' pattern is the difference. +kernel void tf_exl3_stream_read_nax99(const device half* x [[buffer(0)]], + const device uchar* trellis [[buffer(1)]], + device uint* sink [[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]]) { + const ulong base = (ulong(tg.y) * 36u + ulong(tg.x)) * 122880u; + const ulong stride = ulong(tptg.x) * 64u; + uint acc = 0u; + for (ulong off = ulong(tid) * 64u; off < 122880u; off += stride) { + const uint4 v0 = reinterpret_cast(trellis + base + off)[0]; + const uint4 v1 = reinterpret_cast(trellis + base + off)[1]; + const uint4 v2 = reinterpret_cast(trellis + base + off)[2]; + const uint4 v3 = reinterpret_cast(trellis + base + off)[3]; + acc ^= v0.x ^ v0.y ^ v0.z ^ v0.w ^ v1.x ^ v1.y ^ v1.z ^ v1.w ^ + v2.x ^ v2.y ^ v2.z ^ v2.w ^ v3.x ^ v3.y ^ v3.z ^ v3.w; + } + sink[tg.x * 128u + tg.y * 8192u + tid] = acc; +} + +// ROUND-438: THE FP8/E4M3 DENSE BODY (bench-only arm). The weight tensor is repacked to one byte a weight, in +// the kernel's own 16-k x 64-n block order ([k][n] inside a block), so the decode is one 4-byte load a thread +// and the comparator's exact e4m3 -> half bit trick (attribution: mlx-serve, +// src/kernels/linear/fp8_block128_header.metal, fp8r_halves; MIT/Apache-2.0), no codebook, no table, no +// per-state shift. This arm prices the RATE at the attention shapes; per-row scales are not applied here. +inline void tf_fp8_expand8(threadgroup half* wx, uint tid, uint2 q) { + const half2 k256 = half2(256.0h, 256.0h); + const uint u0 = q.x, u1 = q.y; + const half2 a0 = as_type(((u0 & 0x007F007Fu) << 7) | ((u0 << 8) & 0x80008000u)); + const half2 b0 = as_type(((u0 >> 1) & 0x3F803F80u) | (u0 & 0x80008000u)); + const half2 a1 = as_type(((u1 & 0x007F007Fu) << 7) | ((u1 << 8) & 0x80008000u)); + const half2 b1 = as_type(((u1 >> 1) & 0x3F803F80u) | (u1 & 0x80008000u)); + threadgroup half2* o = (threadgroup half2*)(wx + 8u * tid); + o[0] = half2(a0.x, b0.x) * k256; + o[1] = half2(a0.y, b0.y) * k256; + o[2] = half2(a1.x, b1.x) * k256; + o[3] = half2(a1.y, b1.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))); +} + +inline void tf_i8_expand8(threadgroup half* wx, uint tid, uint2 q) { + const uint u0 = q.x, u1 = q.y; + const int a0 = int(u0 << 24) >> 24, a1 = int(u0 << 16) >> 24, a2 = int(u0 << 8) >> 24, a3 = int(u0) >> 24; + const int b0 = int(u1 << 24) >> 24, b1 = int(u1 << 16) >> 24, b2 = int(u1 << 8) >> 24, b3 = int(u1) >> 24; + threadgroup half2* o = (threadgroup half2*)(wx + 8u * tid); + o[0] = half2(half(float(a0)), half(float(a1))); + o[1] = half2(half(float(a2)), half(float(a3))); + o[2] = half2(half(float(b0)), half(float(b1))); + o[3] = half2(half(float(b2)), half(float(b3))); +} + +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; +} + +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 (WIDE) { + if (tid < 128u) { + const uint2 q = *reinterpret_cast(w8 + ((block) << 10) + 8u * tid); + if (a.halves == 0u) tf_i8_expand8(wx, tid, q); else tf_fp8_expand8(wx, tid, q); + } + } else 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; + uint2 nq = uint2(0u); + if (nkb < a.k) { + if (WIDE) { + if (tid < 128u) nq = *reinterpret_cast(w8 + (((nkb >> 4) * nb64 + block) << 10) + 8u * tid); + } else 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 (WIDE) { + if (tid < 128u) { + if (a.halves == 0u) tf_i8_expand8(wx + (cur_buf ^ 1u) * 1024u, tid, nq); + else tf_fp8_expand8(wx + (cur_buf ^ 1u) * 1024u, tid, nq); + } + } else 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); + // ROUND-520: a bf16 destination is the caller's final output (the pre-rotated pack has no epilogue + // transform), so it carries the call's y stride; an f32 destination is the internal sums tile and is + // contiguous at n. sizeof(float) == 4 separates the two instantiations. + const int out_ld = (sizeof(O) == 4) ? int(a.n) : int(a.y_stride); + if (scales != nullptr) { + // ROUND-438: the per-output-row E4M3 scale. One multiply an output, applied to the finished accumulator, + // so the MMA ran on the codes alone and the row scale stays exact. + 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)); +} + +// ROUND-440: THE BLOCK-SCALED INT8 BODY for the pre-rotated pack. W_target's columns are quantized with one int8 +// grid per 128-k block (scales[kb * n + col], f32). The block scale is folded into the half weight at the expand +// step (the exact half product of the int8 code and the half scale), so the MMA loop keeps the shipped body's +// single accumulator and geometry. The four/eight scale half2s are loaded ONCE per 128-k block and reused by its +// eight 16-k expands: loading them per expand cost 21.5% at wo_a (3,619 rows) because the scale reads beat the +// weight tile's own bytes. The f32-accumulate form cost 18.5% at wq_b (four extra fragment accumulators). +inline void tf_i8_expand4s(threadgroup half* wx, uint tid, uint u, half2 s01, half2 s23) { + 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))) * s01; + o[1] = half2(half(float(b2)), half(float(b3))) * s23; +} + +inline void tf_i8_expand8s(threadgroup half* wx, uint tid, uint2 q, half2 s01, half2 s23, half2 s45, half2 s67) { + const uint u0 = q.x, u1 = q.y; + const int a0 = int(u0 << 24) >> 24, a1 = int(u0 << 16) >> 24, a2 = int(u0 << 8) >> 24, a3 = int(u0) >> 24; + const int b0 = int(u1 << 24) >> 24, b1 = int(u1 << 16) >> 24, b2 = int(u1 << 8) >> 24, b3 = int(u1) >> 24; + threadgroup half2* o = (threadgroup half2*)(wx + 8u * tid); + o[0] = half2(half(float(a0)), half(float(a1))) * s01; + o[1] = half2(half(float(a2)), half(float(a3))) * s23; + o[2] = half2(half(float(b0)), half(float(b1))) * s45; + o[3] = half2(half(float(b2)), half(float(b3))) * s67; +} + +template +inline void tf_exl3_prefill_body_i8b(threadgroup half* wx, const device half* x, const device uchar* w8, + const device float* bscales, device float* sums, constant TfExl3Args& a, + uint lane, uint sg, uint tid, uint3 tg) { + constexpr uint RG = 8u; + 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; + // The four (narrow) or eight (wide) output columns this thread's packed bytes cover, constant across k. + const uint n0 = WIDE ? ((tid & 7u) * 8u) : ((tid & 15u) * 4u); + half2 s01, s23, s45, s67; + const device float* bs0 = bscales + nb; + s01 = half2(half(bs0[n0]), half(bs0[n0 + 1u])); + s23 = half2(half(bs0[n0 + 2u]), half(bs0[n0 + 3u])); + s45 = half2(half(bs0[n0 + 4u]), half(bs0[n0 + 5u])); + s67 = half2(half(bs0[n0 + 6u]), half(bs0[n0 + 7u])); + frag lo0, hi0, lo1, hi1; + lo0 = frag(0); hi0 = frag(0); lo1 = frag(0); hi1 = frag(0); + if (WIDE) { + if (tid < 128u) { + const uint2 q = *reinterpret_cast(w8 + ((block) << 10) + 8u * tid); + tf_i8_expand8s(wx, tid, q, s01, s23, s45, s67); + } + } else if (tid < 256u) { + const uint u = *reinterpret_cast(w8 + ((block) << 10) + 4u * tid); + tf_i8_expand4s(wx, tid, u, s01, s23); + } + 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; + uint2 nq = uint2(0u); + if (nkb < a.k) { + if (WIDE) { + if (tid < 128u) nq = *reinterpret_cast(w8 + (((nkb >> 4) * nb64 + block) << 10) + 8u * tid); + } else if (tid < 256u) { + nu = *reinterpret_cast(w8 + (((nkb >> 4) * nb64 + block) << 10) + 4u * tid); + } + } + frag av; + tf_frag_get_dev4(av, x, int(a.k), 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) { + // One scale load per 128-k block, reused by its eight 16-k expands. + if ((nkb & 127u) == 0u) { + const device float* bs = bscales + ulong(nkb >> 7) * a.n + nb; + s01 = half2(half(bs[n0]), half(bs[n0 + 1u])); + s23 = half2(half(bs[n0 + 2u]), half(bs[n0 + 3u])); + s45 = half2(half(bs[n0 + 4u]), half(bs[n0 + 5u])); + s67 = half2(half(bs[n0 + 6u]), half(bs[n0 + 7u])); + } + if (WIDE) { + if (tid < 128u) tf_i8_expand8s(wx + (cur_buf ^ 1u) * 1024u, tid, nq, s01, s23, s45, s67); + } else if (tid < 256u) { + tf_i8_expand4s(wx + (cur_buf ^ 1u) * 1024u, tid, nu, s01, s23); + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + cur_buf ^= 1u; + } + const int c0 = int(nb + sgc * 64u); + const int r0 = int(rb + sgr * 16u); + frag_put_in(lo0, sums, int(a.n), r0, c0, home, int(rb + rows_here), int(nb + cols_here)); + frag_put_in(hi0, sums, int(a.n), r0, c0 + 16, home, int(rb + rows_here), int(nb + cols_here)); + frag_put_in(lo1, sums, int(a.n), r0, c0 + 32, home, int(rb + rows_here), int(nb + cols_here)); + frag_put_in(hi1, sums, int(a.n), r0, c0 + 48, home, int(rb + rows_here), int(nb + cols_here)); +} + +kernel void tf_exl3_matmul_prefill_i8b(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 bscales [[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_i8b(wx, x, w8, bscales, sums, a, lane, sg, tid, tg); +} + +kernel void tf_exl3_matmul_prefill_i8bw(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 bscales [[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_i8b(wx, x, w8, bscales, sums, a, lane, sg, tid, tg); +} + +// ROUND-440 (v1, exact f32 accumulate): the block-scaled int8 body for the pre-rotated pack. W_target's columns are quantized with one int8 +// grid per 128-k block (scales[kb * n + col], f32), because a single per-row grid loses up to 24% of the layer +// agreement once both Hadamards are baked in (wo_a 1.05e-2 -> 6.67e-3 with 128-k blocks). The accumulate order is +// the same 16-k MMA order; each block's finished fragment is scaled and added to the running f32 accumulator, so +// the result is sum_kb scale_kb * sum_{k in kb} code[k,n]*x[k] -- the exact linear map of the stored W_hat. +template +inline void tf_exl3_prefill_body_i8a(threadgroup half* wx, const device half* x, const device uchar* w8, + const device float* bscales, device float* sums, constant TfExl3Args& a, + uint lane, uint sg, uint tid, uint3 tg) { + constexpr uint RG = 8u; + 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; // the current 128-k block + frag acc0, acc1, acc2, acc3; // the scaled running sum + lo0 = frag(0); hi0 = frag(0); lo1 = frag(0); hi1 = frag(0); + acc0 = frag(0); acc1 = frag(0); acc2 = frag(0); acc3 = frag(0); + const int c0 = int(nb + sgc * 64u); + if (WIDE) { + if (tid < 128u) { + const uint2 q = *reinterpret_cast(w8 + ((block) << 10) + 8u * tid); + tf_i8_expand8(wx, tid, q); + } + } else if (tid < 256u) { + const uint u = *reinterpret_cast(w8 + ((block) << 10) + 4u * tid); + tf_i8_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; + uint2 nq = uint2(0u); + if (nkb < a.k) { + if (WIDE) { + if (tid < 128u) nq = *reinterpret_cast(w8 + (((nkb >> 4) * nb64 + block) << 10) + 8u * tid); + } else if (tid < 256u) { + nu = *reinterpret_cast(w8 + (((nkb >> 4) * nb64 + block) << 10) + 4u * tid); + } + } + if ((kb & 127u) == 0u) { + lo0 = frag(0); hi0 = frag(0); lo1 = frag(0); hi1 = frag(0); + } + frag av; + tf_frag_get_dev4(av, x, int(a.k), 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 (WIDE) { + if (tid < 128u) tf_i8_expand8(wx + (cur_buf ^ 1u) * 1024u, tid, nq); + } else if (tid < 256u) { + tf_i8_expand4(wx + (cur_buf ^ 1u) * 1024u, tid, nu); + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + cur_buf ^= 1u; + // nkb is the first k of the NEXT block: at every 128 boundary the finished fragment is scaled and folded. + if ((nkb & 127u) == 0u) { + const uint bi = kb >> 7; + const device float* bs = bscales + ulong(bi) * a.n; + TF_UNROLL + for (short e = 0; e < 8; e++) { + const int cA = c0 + home.x + (e & 3); + acc0[e] = fma(lo0[e], bs[cA], acc0[e]); + acc1[e] = fma(hi0[e], bs[cA + 16], acc1[e]); + acc2[e] = fma(lo1[e], bs[cA + 32], acc2[e]); + acc3[e] = fma(hi1[e], bs[cA + 48], acc3[e]); + } + } + } + const int r0 = int(rb + sgr * 16u); + frag_put_in(acc0, sums, int(a.n), r0, c0, home, int(rb + rows_here), int(nb + cols_here)); + frag_put_in(acc1, sums, int(a.n), r0, c0 + 16, home, int(rb + rows_here), int(nb + cols_here)); + frag_put_in(acc2, sums, int(a.n), r0, c0 + 32, home, int(rb + rows_here), int(nb + cols_here)); + frag_put_in(acc3, sums, int(a.n), r0, c0 + 48, home, int(rb + rows_here), int(nb + cols_here)); +} + + +kernel void tf_exl3_matmul_prefill_i8a(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 bscales [[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_i8a(wx, x, w8, bscales, sums, a, lane, sg, tid, tg); +} + +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); +} + +kernel void tf_exl3_matmul_prefill_fp8w(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); +} + +// ROUND-520: the same byte body with a bf16 destination, for a pre-rotated pack (TF_DSV41_I8_ROT=1): the row +// scale is applied in the body's own epilogue, so no rotate_out (Hadamard + svh) and no f32 sums round trip. +kernel void tf_exl3_matmul_prefill_fp8b(const device half* const x [[buffer(0)]], + const device uchar* const w8 [[buffer(1)]], + device bfloat* const y [[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, y, a, lane, sg, tid, tg); +} diff --git a/zig/kernels/metal/core/exl3_projection_nax_i8.metal b/zig/kernels/metal/core/exl3_projection_nax_i8.metal new file mode 100644 index 00000000000..2ee4c38573d --- /dev/null +++ b/zig/kernels/metal/core/exl3_projection_nax_i8.metal @@ -0,0 +1,752 @@ +// Native EXL3 on the tensor units: the same stored trellis, decoded into a threadgroup tile and reduced by +// cooperative matmul instead of per-lane scalar FMAs. The decode is unchanged (measured free); only the reduction moves. +#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; + uint pair; +}; + +// 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)]; +} + +// The same bitstream read from a tile staged in threadgroup memory: one coalesced pass over 256 bytes, then every +// decoded element hits threadgroup memory instead of a scattered device load. +inline uint tf_exl3_word_tg(const threadgroup ushort* tile, uint i) { + return uint(tile[2 * i]) | (uint(tile[2 * i + 1]) << 16); +} + +inline ushort tf_exl3_mapped_state_tg(const threadgroup ushort* tile, uint map) { + const uint wi = map & 63u, off = (map >> 6) & 31u; + const uint lo = tf_exl3_word_tg(tile, wi); + const uint hi = tf_exl3_word_tg(tile, map >> 11); + const uint carry = (hi >> ((32 - off) & 31u)) & (0u - uint(off != 0)); + return ushort(((lo << off) | carry) >> 16); +} + +// 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) { + const uint h = 1024 + (x & 255) + ((x >> 8) & 255) + ((x >> 16) & 255) + (x >> 24); + return half(fma(float(h), 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)))); +} + +// 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, four +// columns from home.x. `c + home.x` must be a multiple of 4 and `ld` a multiple of 4. +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 threadgroup owns RG sixteen-row groups by CG sixty-four-column groups, one SIMDgroup a (row group, column +// group). Dense rows share one matrix; grouped rows are sixty-four-row aligned, so one expert owns the tile and +// its weights decode once. A wider column tile re-reads the activation tile for fewer output tiles. `Fast` keeps +// the per-state cursor out of the k loop and reads the three stream words an eight-state block can touch. + +// One 16x16 fragment to int8 with its own peak (127 levels): the scalar int8 core's rule, on the tensor path. +inline float tf_frag_quantise(thread frag& q, thread const frag& v) { + float peak = 0.0f; + TF_UNROLL + for (short e = 0; e < 8; e++) peak = max(peak, fabs(float(v[e]))); + peak = simd_max(peak); + const float s = peak > 0 ? peak / 127.0f : 1.0f; + TF_UNROLL + for (short e = 0; e < 8; e++) q[e] = int8_t(clamp(rint(float(v[e]) / s), -127.0f, 127.0f)); + return s; +} + +template +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, + 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 uint didx = a.indexed ? tile_expert : 0; + const device uchar* data = a.indexed ? descriptors[didx].trellis : trellis; + const ulong ks = a.indexed ? descriptors[didx].tile_k_stride : a.tile_k_stride; + const ulong ns = a.indexed ? descriptors[didx].tile_n_stride : a.tile_n_stride; + const uint halves = a.indexed ? descriptors[didx].halves : a.halves; + const uint codebook = a.indexed ? descriptors[didx].codebook : a.codebook; + const short2 home = frag_home(ushort(lane)); + const uint rows_here = min(trows, a.rows - rb); + const uint cols_here = min(64u * CG, a.n - nb); + // Four warps decode a sixty-four-column group; a threadgroup with more warps a group than that splits the sixteen + // states of each lane between them instead of leaving those warps to wait at the barrier. + constexpr uint wpg = RG / 4u; // 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; + uint at[8], off[8], sh[8], rel[8]; + const uint words = 4 * halves; + const uint wi0 = tf_exl3_map_for(p0, halves) & 63u; + if (Fast) { + const uint ring = 128 * halves; + const uint cur = (wi0 << 5) | ((tf_exl3_map_for(p0, halves) >> 6) & 31u); + TF_UNROLL + for (uint k = 0; k < states; ++k) { + const uint p = p0 + k, l = p / 8, e = p % 8; + at[k] = (2 * (l % 4) + (e & 1u) + 8 * ((e >> 1) & 1u)) * (64u * CG) + hg + h * 16u + (l / 4 + 8 * (e >> 2)); + uint c8 = cur + k * (halves >> 1); + if (c8 >= ring) c8 -= ring; + const uint wi = c8 >> 5; + off[k] = c8 & 31u; + sh[k] = (32u - off[k]) & 31u; + rel[k] = wi >= wi0 ? wi - wi0 : wi + words - wi0; + } + } + const uint sgr = sg % RG, sgc = sg / RG; // this SIMDgroup's row group and column group + frag lo0 = frag(0), hi0 = frag(0), lo1 = frag(0), hi1 = frag(0); + // The four stream words a block needs are loaded a block early: issued before the barrier, their latency overlaps + // the multiply and the next block's decode instead of stalling at the top of every k block. + uint p0v, p1v, p2v, p3v; + if (Fast and decodes) { + const device ushort* tile0 = reinterpret_cast(data + ulong(nb / 16 + hg / 16u + h) * ns); + 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. The bit cursor advances by `halves` a state, so it + // rolls forward with one add and one conditional subtract instead of recomputing the map formula. + if (decodes) { + { + const device ushort* tile = reinterpret_cast( + data + ulong(kb / 16) * ks + ulong(nb / 16 + hg / 16u + h) * ns); + if (Fast and (halves & 1u) == 0 and 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( + data + ulong(nkb / 16) * ks + ulong(nb / 16 + hg / 16u + h) * ns); + 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 = 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); + } + } else if (halves <= 16 and (halves & 1u) == 0 and states == 8) { + const uint ring = 128 * 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, 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 * (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_value(ushort(((lo << off) | carry) >> 16), 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_value(tf_exl3_mapped_state(tile, tf_exl3_map_for(p, halves)), codebook); + } + } + } + } + // This SIMDgroup's sixteen rows of the k block, read straight into fragments: no staging buffer, one barrier. + frag av; + frag_get_in(av, (const device half*)x, int(a.k), int(rb + sgr * 16), int(kb), home, int(rb + rows_here), int(kb) + 16); + threadgroup_barrier(mem_flags::mem_threadgroup); + { + 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); + mma_16x32(lo0, hi0, av, 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); + mma_16x32(lo1, hi1, av, 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), so the + // bounds must be absolute too: the last live row is rb + rows_here and the last live column is + // nb + cols_here. The relative counts (rows_here - sg*16, cols_here) left every row past 32 and + // every column past 16 unwritten, which is what made this kernel's answers wrong. + frag_put_in(lo0, sums, int(a.n), r0, c0, home, int(rb + rows_here), int(nb + cols_here)); + frag_put_in(hi0, sums, int(a.n), r0, c0 + 16, home, int(rb + rows_here), int(nb + cols_here)); + frag_put_in(lo1, sums, int(a.n), r0, c0 + 32, home, int(rb + rows_here), int(nb + cols_here)); + frag_put_in(hi1, sums, int(a.n), r0, c0 + 48, home, int(rb + rows_here), int(nb + cols_here)); +} + +template +inline void tf_exl3_prefill_body_i8(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 uint didx = a.indexed ? tile_expert : 0; + const device uchar* data = a.indexed ? descriptors[didx].trellis : trellis; + const ulong ks = a.indexed ? descriptors[didx].tile_k_stride : a.tile_k_stride; + const ulong ns = a.indexed ? descriptors[didx].tile_n_stride : a.tile_n_stride; + const uint halves = a.indexed ? descriptors[didx].halves : a.halves; + const uint codebook = a.indexed ? descriptors[didx].codebook : a.codebook; + const short2 home = frag_home(ushort(lane)); + const uint rows_here = min(trows, a.rows - rb); + const uint cols_here = min(64u * CG, a.n - nb); + // Four warps decode a sixty-four-column group; a threadgroup with more warps a group than that splits the sixteen + // states of each lane between them instead of leaving those warps to wait at the barrier. + constexpr uint wpg = RG / 4u; // 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; + uint at[8], off[8], sh[8], rel[8]; + const uint words = 4 * halves; + const uint wi0 = tf_exl3_map_for(p0, halves) & 63u; + if (Fast) { + const uint ring = 128 * halves; + const uint cur = (wi0 << 5) | ((tf_exl3_map_for(p0, halves) >> 6) & 31u); + TF_UNROLL + for (uint k = 0; k < states; ++k) { + const uint p = p0 + k, l = p / 8, e = p % 8; + at[k] = (2 * (l % 4) + (e & 1u) + 8 * ((e >> 1) & 1u)) * (64u * CG) + hg + h * 16u + (l / 4 + 8 * (e >> 2)); + uint c8 = cur + k * (halves >> 1); + if (c8 >= ring) c8 -= ring; + const uint wi = c8 >> 5; + off[k] = c8 & 31u; + sh[k] = (32u - off[k]) & 31u; + rel[k] = wi >= wi0 ? wi - wi0 : wi + words - wi0; + } + } + const uint sgr = sg % RG, sgc = sg / RG; // this SIMDgroup's row group and column group + frag lo0 = frag(0), hi0 = frag(0), lo1 = frag(0), hi1 = frag(0); + // The four stream words a block needs are loaded a block early: issued before the barrier, their latency overlaps + // the multiply and the next block's decode instead of stalling at the top of every k block. + uint p0v, p1v, p2v, p3v; + if (Fast and decodes) { + const device ushort* tile0 = reinterpret_cast(data + ulong(nb / 16 + hg / 16u + h) * ns); + 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. The bit cursor advances by `halves` a state, so it + // rolls forward with one add and one conditional subtract instead of recomputing the map formula. + if (decodes) { + { + const device ushort* tile = reinterpret_cast( + data + ulong(kb / 16) * ks + ulong(nb / 16 + hg / 16u + h) * ns); + if (Fast and (halves & 1u) == 0 and 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( + data + ulong(nkb / 16) * ks + ulong(nb / 16 + hg / 16u + h) * ns); + 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 = 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); + } + } else if (halves <= 16 and (halves & 1u) == 0 and states == 8) { + const uint ring = 128 * 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, 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 * (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_value(ushort(((lo << off) | carry) >> 16), 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_value(tf_exl3_mapped_state(tile, tf_exl3_map_for(p, halves)), codebook); + } + } + } + } + // This SIMDgroup's sixteen rows of the k block, read straight into fragments: no staging buffer, one barrier. + // int8 body, register-lean: one weight fragment and one int accumulator pair live at a time, each pair flushed + // into the float accumulators before the registers are reused. The tile and the x block are quantised per 16x16 + // fragment with their own peak/127 scales, the int32 sums are exact, and every k block flushes because its + // scales differ. This is the trellis skeleton's own decode with the multiply moved to int8 on the tensor units. + threadgroup_barrier(mem_flags::mem_threadgroup); + { + const int wc = int(sgc * 64u); + frag xv; + frag_get_in(xv, (const device half*)x, int(a.k), int(rb + sgr * 16), int(kb), home, int(rb + rows_here), int(kb) + 16); + frag aq; + const float xs = tf_frag_quantise(aq, xv); + frag wo; + frag b0, b1; + frag acc; + tf_frag_get_tg4(wo, wx, int(64u * CG), 0, wc, home); + const float s0 = tf_frag_quantise(b0, wo) * xs; + tf_frag_get_tg4(wo, wx, int(64u * CG), 0, wc + 16, home); + const float s1 = tf_frag_quantise(b1, wo) * xs; + acc = frag(0); + mma_16x32(acc, acc, aq, b0, b1); + TF_UNROLL + for (short e = 0; e < 8; e++) { + lo0[e] += float(acc[e]) * s0; + hi0[e] += float(acc[e]) * s1; + } + tf_frag_get_tg4(wo, wx, int(64u * CG), 0, wc + 32, home); + const float s2 = tf_frag_quantise(b0, wo) * xs; + tf_frag_get_tg4(wo, wx, int(64u * CG), 0, wc + 48, home); + const float s3 = tf_frag_quantise(b1, wo) * xs; + acc = frag(0); + mma_16x32(acc, acc, aq, b0, b1); + TF_UNROLL + for (short e = 0; e < 8; e++) { + lo1[e] += float(acc[e]) * s2; + hi1[e] += float(acc[e]) * s3; + } + } + 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), so the + // bounds must be absolute too: the last live row is rb + rows_here and the last live column is + // nb + cols_here. The relative counts (rows_here - sg*16, cols_here) left every row past 32 and + // every column past 16 unwritten, which is what made this kernel's answers wrong. + frag_put_in(lo0, sums, int(a.n), r0, c0, home, int(rb + rows_here), int(nb + cols_here)); + frag_put_in(hi0, sums, int(a.n), r0, c0 + 16, home, int(rb + rows_here), int(nb + cols_here)); + frag_put_in(lo1, sums, int(a.n), r0, c0 + 32, home, int(rb + rows_here), int(nb + cols_here)); + frag_put_in(hi1, sums, int(a.n), r0, c0 + 48, home, int(rb + rows_here), int(nb + cols_here)); +} + +kernel void tf_exl3_matmul_prefill_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)]], + 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, lane, sg, tid, tptg.x, tg); +} + +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, lane, sg, tid, tptg.x, tg); +} + +// One row an expert, four rows a threadgroup: each SIMDgroup decodes its own expert's 16x32 tile once and +// multiplies the single row it owns, writing only that row of the sixteen-row tensor-unit product. +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)]], + 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, and one barrier a block + // replaces two because the tile a multiply reads is never the tile a decode writes. +#if defined(TF_DECODE_COMPACT) + // Compact: one row a threadgroup, two 16x32 tiles only (1 KB), so many more groups fit the threadgroup + // memory and the decode's issue rate is not occupancy-bound (round 173's probe: 0.84 against 0.50e12). + 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, which is four + // times the threadgroups for the same work (TF_DSV41_EXL3_MOE_ROWS). +#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; + 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 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, so a split takes a + // slice of the k blocks and the reduce kernel sums the parts in split order. + 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 three stream words they can touch are + // read once and the cursor and the tile slot come from registers (the prompt kernel's inner loop). + uint at[8], off[8], sh[8], rel[8]; + const uint words = 4 * halves; + const uint wi0 = tf_exl3_map_for(lane * 8u, halves) & 63u; + { + const uint ring = 128 * halves; + 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 p = lane * 8u + k, l = p / 8, e = p % 8; + off[k] = (cur + k * (halves >> 1)) % ring & 31u; + const uint c8 = (cur + k * (halves >> 1)) % ring; + sh[k] = (32u - off[k]) & 31u; + rel[k] = (c8 >> 5) >= wi0 ? (c8 >> 5) - wi0 : (c8 >> 5) + words - wi0; + at[k] = (2 * (l % 4) + (e & 1u) + 8 * ((e >> 1) & 1u)) * 32u + (l / 4 + 8 * (e >> 2)); + } + } + 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 = (halves & 1u) == 0 and halves <= 16; + 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; + if (pipeline) { + const device ushort* t0 = reinterpret_cast(data + ulong(b0) * ks + ulong(nb / 16) * ns); + pre[0][0] = tf_exl3_word(t0, wi0); + pre[0][1] = tf_exl3_word(t0, a1); + pre[0][2] = tf_exl3_word(t0, a2); + pre[0][3] = tf_exl3_word(t0, a3); + if (nb + 16 < a.n) { + const device ushort* t1 = reinterpret_cast(data + ulong(b0) * ks + ulong(nb / 16 + 1) * ns); + pre[1][0] = tf_exl3_word(t1, wi0); + pre[1][1] = tf_exl3_word(t1, a1); + pre[1][2] = tf_exl3_word(t1, a2); + pre[1][3] = tf_exl3_word(t1, a3); + } + } + 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], w2 = pre[h][2], w3 = pre[h][3]; + const uint nxt = bb + 1; + if (nxt < b1) { + const device ushort* tn = reinterpret_cast(data + ulong(nxt) * ks + ulong(nb / 16 + h) * ns); + pre[h][0] = tf_exl3_word(tn, wi0); + pre[h][1] = tf_exl3_word(tn, a1); + pre[h][2] = tf_exl3_word(tn, a2); + pre[h][3] = tf_exl3_word(tn, a3); + } + TF_UNROLL + for (uint k = 0; k < 8; ++k) { + const uint lo8 = rel[k] == 0 ? w0 : rel[k] == 1 ? w1 : w2; + const uint hi8 = rel[k] == 0 ? w1 : rel[k] == 1 ? w2 : w3; + const uint carry = (hi8 >> sh[k]) & (0u - uint(off[k] != 0)); + wxc[at[k] + h * 16] = tf_exl3_value(ushort(((lo8 << off[k]) | carry) >> 16), codebook); + } + } + } 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( + data + ulong(kb / 16) * ks + ulong(nb / 16 + h) * ns); + 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); + wxc[r * 32 + h * 16 + c] = tf_exl3_value(tf_exl3_mapped_state(tile, tf_exl3_map_for(p, halves)), codebook); + } + } + 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)); +} + +// One row, four column tiles a threadgroup: a dense projection at decode width on the tensor units. Each +// SIMDgroup decodes its own 32-column tile once and multiplies the single row, writing only row 0. +kernel void tf_exl3_matvec_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)]], + 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[4 * 16 * 32]; + threadgroup half xx[16 * 16]; + const uint nb = tg.x * 128 + sg * 32; + if (nb >= a.n || a.rows == 0) return; + const device uchar* base = trellis; + const uint cols_here = min(32u, a.n - nb); + const short2 home = frag_home(ushort(lane)); + threadgroup half* wxg = wx + sg * (16 * 32); + frag lo = frag(0), hi = frag(0); + for (uint kb = 0; kb < a.k; kb += 16) { + 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( + base + ulong(kb / 16) * a.tile_k_stride + ulong(nb / 16 + h) * a.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); + wxg[r * 32 + h * 16 + c] = tf_exl3_value(tf_exl3_mapped_state(tile, tf_exl3_map_for(p, a.halves)), a.codebook); + } + TF_UNROLL + for (uint t = 0; t < 8; ++t) { + const uint idx = lane + 32 * t, r = idx / 16, c = idx % 16; + xx[idx] = r == 0 ? *(const device half*)(x + ulong(kb) + c) : half(0); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + frag av, b0, b1; + tf_frag_get_tg4(av, xx, 16, 0, 0, home); + tf_frag_get_tg4(b0, wxg, 32, 0, 0, home); + tf_frag_get_tg4(b1, wxg, 32, 0, 16, home); + mma_16x32(lo, hi, av, b0, b1); + threadgroup_barrier(mem_flags::mem_threadgroup); + } + frag_put_in(lo, sums, int(a.n), 0, int(nb), home, 1, int(nb + cols_here)); + frag_put_in(hi, sums, int(a.n), 0, int(nb + 16), home, 1, int(nb + cols_here)); +} + +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, 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, 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, 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, lane, sg, tid, tptg.x, tg); +} + +// The int8 routed body: the trellis skeleton's decode, the tile and x block quantised per 16x16 fragment and +// multiplied as int8 x int8 on the tensor units (TF_DSV41_INT8_BODY). +kernel void tf_exl3_matmul_prefill_nax_i8(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_i8(wx, x, trellis, sums, a, routes, descriptors, lane, sg, tid, tptg.x, tg); +} diff --git a/zig/kernels/metal/core/expert_groups.metal b/zig/kernels/metal/core/expert_groups.metal new file mode 100644 index 00000000000..a4339c7e0e6 --- /dev/null +++ b/zig/kernels/metal/core/expert_groups.metal @@ -0,0 +1,45 @@ +// Group routed slots into padded expert tiles (sixty-four rows, or the tile's own width -- ROUND-348); +// 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; + // ROUND-348: each expert's block is padded to a multiple of the tile's rows (the tile reads one expert's + // weights, so a tile may not straddle two experts); the tile's width is the plan's own. + 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 (gate picks, then up picks one table entry + // further), so a slot's token is its position inside its block, not a running quotient. + 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: the fused SwiGLU+rotate pass writes a row's + // rotated down input where the tile GEMM reads it, so the down call skips its rotate_in. + destinations[i] = destination; +} diff --git a/zig/kernels/metal/core/mlx/gather.metal b/zig/kernels/metal/core/mlx/gather.metal new file mode 100644 index 00000000000..c9b08c6b767 --- /dev/null +++ b/zig/kernels/metal/core/mlx/gather.metal @@ -0,0 +1,14 @@ +// The reference's gathered quantised matmul for our routed shapes. +// Ported from ml-explore/mlx v0.32.4 (MIT): mlx/backend/metal/kernels/quantized.h and steel/gemm/**, flattened +// into mlx_steel.h with attribution. These entries are TensorFold's: a kernel function cannot call another, so +// each is the reference template instantiated at one geometry (the form MLX itself uses). +#include "mlx_steel.h" + +template [[host_name("tf_gather_qmm_f32_gs64_b4")]] [[kernel]] decltype(affine_gather_qmm_rhs) affine_gather_qmm_rhs; +template [[host_name("tf_gather_qmm_f32_gs64_b4_bn64")]] [[kernel]] decltype(affine_gather_qmm_rhs) affine_gather_qmm_rhs; + +// Wider warp grids: more MMA issue slots per threadgroup. WM/WN are the warp grid, so 4x2 = 256 threads, +// 4x4 = 512. These are the geometries that could raise the tensor rate above the 2x2 baseline. +template [[host_name("tf_gather_qmm_w4x2")]] [[kernel]] decltype(affine_gather_qmm_rhs) affine_gather_qmm_rhs; +template [[host_name("tf_gather_qmm_w4x4")]] [[kernel]] decltype(affine_gather_qmm_rhs) affine_gather_qmm_rhs; +template [[host_name("tf_gather_qmm_bm128")]] [[kernel]] decltype(affine_gather_qmm_rhs) affine_gather_qmm_rhs; diff --git a/zig/kernels/metal/core/mlx/mlx_steel.h b/zig/kernels/metal/core/mlx/mlx_steel.h new file mode 100644 index 00000000000..7c1399fdfac --- /dev/null +++ b/zig/kernels/metal/core/mlx/mlx_steel.h @@ -0,0 +1,6267 @@ +// Flattened MLX Metal headers (ml-explore/mlx v0.32.4, MIT), includes resolved recursively. +// Files, in dependency order: +// bf16.h +// bf16_math.h +// complex.h +// defines.h +// logging.h +// utils.h +// quantized_utils.h +// steel/defines.h +// steel/gemm/loader.h +// steel/utils.h +// steel/gemm/transforms.h +// steel/utils/type_traits.h +// steel/utils/integral_constant.h +// steel/gemm/mma.h +// steel/gemm/params.h +// steel/gemm/gemm.h +// quantized.h + +// ==== bf16.h +// Copyright © 2023 Apple Inc. + +#pragma once + +#include + +using namespace metal; + +typedef bfloat bfloat16_t; +inline uint16_t bfloat16_to_uint16(const bfloat16_t x) { + return as_type(x); +} + +inline bfloat16_t uint16_to_bfloat16(const uint16_t x) { + return as_type(x); +} +// ==== bf16_math.h +// Copyright © 2023 Apple Inc. + +#pragma once + +/////////////////////////////////////////////////////////////////////////////// +// Metal math for bfloat16 +/////////////////////////////////////////////////////////////////////////////// + +/* + +Following the Metal Shading Language Specification (Metal 3.1) + +"bfloat is an extended itypeing point type that only allows implicit conversion + to a type of greater itypeing point rank. While bfloat can be implicitly + converted to itype, it cannot be implicitly converted to half, and neither + itype nor half can be implicitly converted to bfloat." + +Further, as far as I can tell, the stdlib math/simd functions are not defined +for bfloat and calling with an argument of type bfloat will result in that +argument getting implicitly converted to itype which then returns an output +that is (likely) a itype which cannot be implicitly converted into a bfloat + +This leads to situations where +bfloat a = 5.0bf; +bfloat b = metal::abs(a); // this will throw an error since abs return itype +bfloat c = static_cast(metal::abs(a)); // this is fine + +For the moment, I will be adding overloaded instantiations of the math +functions to accordingly automatically handle the casting + +*/ + +#define instantiate_metal_math_funcs(itype, otype, ctype, mfast) \ + \ + METAL_FUNC otype abs(itype x) { \ + return static_cast(__metal_fabs(static_cast(x), mfast)); \ + } \ + METAL_FUNC otype acos(itype x) { \ + return static_cast(__metal_acos(static_cast(x), mfast)); \ + } \ + METAL_FUNC otype acosh(itype x) { \ + return static_cast(__metal_acosh(static_cast(x), mfast)); \ + } \ + METAL_FUNC otype asin(itype x) { \ + return static_cast(__metal_asin(static_cast(x), mfast)); \ + } \ + METAL_FUNC otype asinh(itype x) { \ + return static_cast(__metal_asinh(static_cast(x), mfast)); \ + } \ + METAL_FUNC otype atan(itype y_over_x) { \ + return static_cast( \ + __metal_atan(static_cast(y_over_x), mfast)); \ + } \ + METAL_FUNC otype atan2(itype y, itype x) { \ + return static_cast( \ + __metal_atan2(static_cast(y), static_cast(x), mfast)); \ + } \ + METAL_FUNC otype atanh(itype x) { \ + return static_cast(__metal_atanh(static_cast(x), mfast)); \ + } \ + METAL_FUNC otype ceil(itype x) { \ + return static_cast(__metal_ceil(static_cast(x), mfast)); \ + } \ + METAL_FUNC otype cos(itype x) { \ + return static_cast(__metal_cos(static_cast(x), mfast)); \ + } \ + METAL_FUNC otype cosh(itype x) { \ + return static_cast(__metal_cosh(static_cast(x), mfast)); \ + } \ + METAL_FUNC otype cospi(itype x) { \ + return static_cast(__metal_cospi(static_cast(x), mfast)); \ + } \ + METAL_FUNC otype divide(itype x, itype y) { \ + return static_cast( \ + __metal_divide(static_cast(x), static_cast(y), mfast)); \ + } \ + METAL_FUNC otype exp(itype x) { \ + return static_cast(__metal_exp(static_cast(x), mfast)); \ + } \ + METAL_FUNC otype exp10(itype x) { \ + return static_cast(__metal_exp10(static_cast(x), mfast)); \ + } \ + METAL_FUNC otype exp2(itype x) { \ + return static_cast(__metal_exp2(static_cast(x), mfast)); \ + } \ + METAL_FUNC otype fabs(itype x) { \ + return static_cast(__metal_fabs(static_cast(x), mfast)); \ + } \ + METAL_FUNC otype fdim(itype x, itype y) { \ + ctype t = static_cast(x - y); \ + return static_cast(select(t, ctype(0), t < ctype(0) || x == y)); \ + } \ + METAL_FUNC otype floor(itype x) { \ + return static_cast(__metal_floor(static_cast(x), mfast)); \ + } \ + METAL_FUNC otype fma(itype x, itype y, itype z) { \ + return static_cast(__metal_fma( \ + static_cast(x), static_cast(y), static_cast(z))); \ + } \ + METAL_FUNC otype fmax(itype x, itype y) { \ + return static_cast( \ + __metal_fmax(static_cast(x), static_cast(y), mfast)); \ + } \ + METAL_FUNC otype fmax3(itype x, itype y, itype z) { \ + return static_cast(__metal_fmax3( \ + static_cast(x), \ + static_cast(y), \ + static_cast(z), \ + mfast)); \ + } \ + METAL_FUNC otype fmedian3(itype x, itype y, itype z) { \ + return static_cast(__metal_fmedian3( \ + static_cast(x), \ + static_cast(y), \ + static_cast(z), \ + mfast)); \ + } \ + METAL_FUNC otype fmin(itype x, itype y) { \ + return static_cast( \ + __metal_fmin(static_cast(x), static_cast(y), mfast)); \ + } \ + METAL_FUNC otype fmin3(itype x, itype y, itype z) { \ + return static_cast(__metal_fmin3( \ + static_cast(x), \ + static_cast(y), \ + static_cast(z), \ + mfast)); \ + } \ + METAL_FUNC otype fmod(itype x, itype y) { \ + return static_cast( \ + __metal_fmod(static_cast(x), static_cast(y), mfast)); \ + } \ + METAL_FUNC otype fract(itype x) { \ + return static_cast(__metal_fract(static_cast(x), mfast)); \ + } \ + METAL_FUNC otype frexp(itype x, thread int& exp) { \ + return static_cast(__metal_frexp(static_cast(x), &exp)); \ + } \ + METAL_FUNC otype ldexp(itype x, int k) { \ + return static_cast(__metal_ldexp(static_cast(x), k, mfast)); \ + } \ + METAL_FUNC otype log(itype x) { \ + return static_cast(__metal_log(static_cast(x), mfast)); \ + } \ + METAL_FUNC otype log10(itype x) { \ + return static_cast(__metal_log10(static_cast(x), mfast)); \ + } \ + METAL_FUNC otype log2(itype x) { \ + return static_cast(__metal_log2(static_cast(x), mfast)); \ + } \ + METAL_FUNC otype max(itype x, itype y) { \ + return static_cast( \ + __metal_fmax(static_cast(x), static_cast(y), mfast)); \ + } \ + METAL_FUNC otype max3(itype x, itype y, itype z) { \ + return static_cast(__metal_fmax3( \ + static_cast(x), \ + static_cast(y), \ + static_cast(z), \ + mfast)); \ + } \ + METAL_FUNC otype median3(itype x, itype y, itype z) { \ + return static_cast(__metal_fmedian3( \ + static_cast(x), \ + static_cast(y), \ + static_cast(z), \ + mfast)); \ + } \ + METAL_FUNC otype min(itype x, itype y) { \ + return static_cast( \ + __metal_fmin(static_cast(x), static_cast(y), mfast)); \ + } \ + METAL_FUNC otype min3(itype x, itype y, itype z) { \ + return static_cast(__metal_fmin3( \ + static_cast(x), \ + static_cast(y), \ + static_cast(z), \ + mfast)); \ + } \ + METAL_FUNC otype nextafter(itype x, itype y) { \ + return static_cast( \ + __metal_nextafter(static_cast(x), static_cast(y))); \ + } \ + METAL_FUNC otype pow(itype x, itype y) { \ + return static_cast( \ + __metal_pow(static_cast(x), static_cast(y), mfast)); \ + } \ + METAL_FUNC otype powr(itype x, itype y) { \ + return static_cast( \ + __metal_powr(static_cast(x), static_cast(y), mfast)); \ + } \ + METAL_FUNC otype rint(itype x) { \ + return static_cast(__metal_rint(static_cast(x), mfast)); \ + } \ + METAL_FUNC otype round(itype x) { \ + return static_cast(__metal_round(static_cast(x), mfast)); \ + } \ + METAL_FUNC otype rsqrt(itype x) { \ + return static_cast(__metal_rsqrt(static_cast(x), mfast)); \ + } \ + METAL_FUNC otype sin(itype x) { \ + return static_cast(__metal_sin(static_cast(x), mfast)); \ + } \ + METAL_FUNC otype sinh(itype x) { \ + return static_cast(__metal_sinh(static_cast(x), mfast)); \ + } \ + METAL_FUNC otype sinpi(itype x) { \ + return static_cast(__metal_sinpi(static_cast(x), mfast)); \ + } \ + METAL_FUNC otype sqrt(itype x) { \ + return static_cast(__metal_sqrt(static_cast(x), mfast)); \ + } \ + METAL_FUNC otype tan(itype x) { \ + return static_cast(__metal_tan(static_cast(x), mfast)); \ + } \ + METAL_FUNC otype tanh(itype x) { \ + return static_cast(__metal_tanh(static_cast(x), mfast)); \ + } \ + METAL_FUNC otype tanpi(itype x) { \ + return static_cast(__metal_tanpi(static_cast(x), mfast)); \ + } \ + METAL_FUNC otype trunc(itype x) { \ + return static_cast(__metal_trunc(static_cast(x), mfast)); \ + } + +namespace metal { + +instantiate_metal_math_funcs( + bfloat16_t, + bfloat16_t, + float, + __METAL_MAYBE_FAST_MATH__); + +namespace fast { + +instantiate_metal_math_funcs( + bfloat16_t, + bfloat16_t, + float, + __METAL_FAST_MATH__); + +} // namespace fast + +namespace precise { + +instantiate_metal_math_funcs( + bfloat16_t, + bfloat16_t, + float, + __METAL_PRECISE_MATH__); + +} // namespace precise + +} // namespace metal + +/////////////////////////////////////////////////////////////////////////////// +// Metal simd for bfloat16 +/////////////////////////////////////////////////////////////////////////////// + +#define instantiate_metal_simd_comm_funcs( \ + itype, otype, ctype, itype_to_ctype, ctype_to_otype) \ + \ + METAL_FUNC otype simd_broadcast(itype data, ushort broadcast_lane_id) { \ + return ctype_to_otype( \ + __metal_simd_broadcast(itype_to_ctype(data), broadcast_lane_id)); \ + } \ + \ + METAL_FUNC otype simd_shuffle(itype data, ushort simd_lane_id) { \ + return ctype_to_otype( \ + __metal_simd_shuffle(itype_to_ctype(data), simd_lane_id)); \ + } \ + \ + METAL_FUNC otype simd_shuffle_and_fill_down( \ + itype data, itype filling_data, ushort delta, ushort modulo) { \ + return ctype_to_otype(__metal_simd_shuffle_and_fill_down( \ + itype_to_ctype(data), itype_to_ctype(filling_data), delta, modulo)); \ + } \ + \ + METAL_FUNC otype simd_shuffle_and_fill_down( \ + itype data, itype filling_data, ushort delta) { \ + return ctype_to_otype(__metal_simd_shuffle_and_fill_down( \ + itype_to_ctype(data), \ + itype_to_ctype(filling_data), \ + delta, \ + __metal_get_simdgroup_size(ushort()))); \ + } \ + \ + METAL_FUNC otype simd_shuffle_and_fill_up( \ + itype data, itype filling_data, ushort delta, ushort modulo) { \ + return ctype_to_otype(__metal_simd_shuffle_and_fill_up( \ + itype_to_ctype(data), itype_to_ctype(filling_data), delta, modulo)); \ + } \ + \ + METAL_FUNC otype simd_shuffle_and_fill_up( \ + itype data, itype filling_data, ushort delta) { \ + return ctype_to_otype(__metal_simd_shuffle_and_fill_up( \ + itype_to_ctype(data), \ + itype_to_ctype(filling_data), \ + delta, \ + __metal_get_simdgroup_size(ushort()))); \ + } \ + \ + METAL_FUNC otype simd_shuffle_down(itype data, ushort delta) { \ + return ctype_to_otype( \ + __metal_simd_shuffle_down(itype_to_ctype(data), delta)); \ + } \ + \ + METAL_FUNC otype simd_shuffle_rotate_down(itype data, ushort delta) { \ + return ctype_to_otype( \ + __metal_simd_shuffle_rotate_down(itype_to_ctype(data), delta)); \ + } \ + \ + METAL_FUNC otype simd_shuffle_rotate_up(itype data, ushort delta) { \ + return ctype_to_otype( \ + __metal_simd_shuffle_rotate_up(itype_to_ctype(data), delta)); \ + } \ + \ + METAL_FUNC otype simd_shuffle_up(itype data, ushort delta) { \ + return ctype_to_otype( \ + __metal_simd_shuffle_up(itype_to_ctype(data), delta)); \ + } \ + \ + METAL_FUNC otype simd_shuffle_xor(itype data, ushort mask) { \ + return ctype_to_otype( \ + __metal_simd_shuffle_xor(itype_to_ctype(data), mask)); \ + } + +#define instantiate_metal_simd_reduction_funcs(itype, otype, ctype) \ + \ + METAL_FUNC otype simd_max(itype data) { \ + return static_cast(__metal_simd_max(static_cast(data))); \ + } \ + \ + METAL_FUNC otype simd_min(itype data) { \ + return static_cast(__metal_simd_min(static_cast(data))); \ + } \ + \ + METAL_FUNC otype simd_prefix_exclusive_product(itype data) { \ + return static_cast( \ + __metal_simd_prefix_exclusive_product(static_cast(data))); \ + } \ + \ + METAL_FUNC otype simd_prefix_exclusive_sum(itype data) { \ + return static_cast( \ + __metal_simd_prefix_exclusive_sum(static_cast(data))); \ + } \ + \ + METAL_FUNC otype simd_prefix_inclusive_product(itype data) { \ + return static_cast( \ + __metal_simd_prefix_inclusive_product(static_cast(data))); \ + } \ + \ + METAL_FUNC otype simd_prefix_inclusive_sum(itype data) { \ + return static_cast( \ + __metal_simd_prefix_inclusive_sum(static_cast(data))); \ + } \ + \ + METAL_FUNC otype simd_product(itype data) { \ + return static_cast(__metal_simd_product(static_cast(data))); \ + } \ + \ + METAL_FUNC otype simd_sum(itype data) { \ + return static_cast(__metal_simd_sum(static_cast(data))); \ + } \ + \ + METAL_FUNC otype simd_xor(itype data) { \ + return static_cast(__metal_simd_xor(static_cast(data))); \ + } + +namespace metal { + +instantiate_metal_simd_comm_funcs( + bfloat16_t, + bfloat16_t, + uint16_t, + bfloat16_to_uint16, + uint16_to_bfloat16); +instantiate_metal_simd_reduction_funcs(bfloat16_t, bfloat16_t, float); + +} // namespace metal +// ==== complex.h +// Copyright © 2023 Apple Inc. + +#pragma once + +#include + + +using namespace metal; + +template +struct complex_t; + +template +static constexpr constant bool is_complex_v = false; + +template +static constexpr constant bool is_complex_v> = true; + +// Metal accepts explicit bfloat casts that is_convertible_v reports as false. +template +static constexpr constant bool is_lane_convertible_v = + is_convertible_v || + (is_same_v && is_convertible_v) || + (is_same_v && is_convertible_v); + +template +struct complex_t { + using value_type = T; + + T real; + T imag; + + // Constructors + constexpr complex_t(T real, T imag) thread : real(real), imag(imag) {}; + constexpr complex_t() thread : real(0), imag(0) {}; + constexpr complex_t() threadgroup : real(0), imag(0) {}; + + // Conversions from scalar types + template < + typename U, + typename = typename enable_if< + !is_complex_v && is_lane_convertible_v>::type> + constexpr complex_t(U x) thread : real(static_cast(x)), + imag(static_cast(0)) {} + + template < + typename U, + typename = typename enable_if< + !is_complex_v && is_lane_convertible_v>::type> + constexpr complex_t(U x) threadgroup : real(static_cast(x)), + imag(static_cast(0)) {} + + template < + typename U, + typename = typename enable_if< + !is_complex_v && is_lane_convertible_v>::type> + constexpr complex_t(U x) device : real(static_cast(x)), + imag(static_cast(0)) {} + + template < + typename U, + typename = typename enable_if< + !is_complex_v && is_lane_convertible_v>::type> + constexpr complex_t(U x) constant : real(static_cast(x)), + imag(static_cast(0)) {} + + // Conversions between complex types + template < + typename U, + typename = typename enable_if< + !is_same_v && is_lane_convertible_v>::type> + constexpr complex_t(complex_t x) thread : real(static_cast(x.real)), + imag(static_cast(x.imag)) {} + + template < + typename U, + typename = typename enable_if< + !is_same_v && is_lane_convertible_v>::type> + constexpr complex_t(complex_t x) threadgroup + : real(static_cast(x.real)), + imag(static_cast(x.imag)) {} + + template < + typename U, + typename = typename enable_if< + !is_same_v && is_lane_convertible_v>::type> + constexpr complex_t(complex_t x) device : real(static_cast(x.real)), + imag(static_cast(x.imag)) {} + + template < + typename U, + typename = typename enable_if< + !is_same_v && is_lane_convertible_v>::type> + constexpr complex_t(complex_t x) constant : real(static_cast(x.real)), + imag(static_cast(x.imag)) {} + + // Conversions to and from two-lane vectors (the FFT lane representation) + constexpr complex_t(vec v) thread : real(v.x), imag(v.y) {}; + constexpr complex_t(vec v) threadgroup : real(v.x), imag(v.y) {}; + constexpr complex_t(vec v) device : real(v.x), imag(v.y) {}; + constexpr complex_t(vec v) constant : real(v.x), imag(v.y) {}; + + constexpr operator vec() const thread { + return vec(real, imag); + } + + constexpr operator vec() const threadgroup { + return vec(real, imag); + } + + constexpr operator vec() const device { + return vec(real, imag); + } + + constexpr operator vec() const constant { + return vec(real, imag); + } + + // Conversions to scalar types + template < + typename U, + typename = typename enable_if< + !is_complex_v && is_lane_convertible_v>::type> + constexpr operator U() const thread { + return static_cast(real); + } + + template < + typename U, + typename = typename enable_if< + !is_complex_v && is_lane_convertible_v>::type> + constexpr operator U() const threadgroup { + return static_cast(real); + } + + template < + typename U, + typename = typename enable_if< + !is_complex_v && is_lane_convertible_v>::type> + constexpr operator U() const device { + return static_cast(real); + } + + template < + typename U, + typename = typename enable_if< + !is_complex_v && is_lane_convertible_v>::type> + constexpr operator U() const constant { + return static_cast(real); + } +}; + +using complex32_t = complex_t; +using complex64_t = complex_t; + +static_assert(sizeof(complex32_t) == 2 * sizeof(half)); +static_assert(sizeof(complex64_t) == 2 * sizeof(float)); +static_assert(sizeof(complex_t) == 2 * sizeof(bfloat16_t)); + +template +constexpr complex_t operator-(complex_t x) { + return {-x.real, -x.imag}; +} + +template +constexpr bool operator>=(complex_t a, complex_t b) { + return (a.real > b.real) || (a.real == b.real && a.imag >= b.imag); +} + +template +constexpr bool operator>(complex_t a, complex_t b) { + return (a.real > b.real) || (a.real == b.real && a.imag > b.imag); +} + +template +constexpr bool operator<=(complex_t a, complex_t b) { + return operator>=(b, a); +} + +template +constexpr bool operator<(complex_t a, complex_t b) { + return operator>(b, a); +} + +template +constexpr bool operator==(complex_t a, complex_t b) { + return a.real == b.real && a.imag == b.imag; +} + +template +constexpr complex_t operator+(complex_t a, complex_t b) { + return {a.real + b.real, a.imag + b.imag}; +} + +template +constexpr thread complex_t& operator+=( + thread complex_t& a, + complex_t b) { + a.real += b.real; + a.imag += b.imag; + return a; +} + +template +constexpr threadgroup complex_t& operator+=( + threadgroup complex_t& a, + complex_t b) { + a.real += b.real; + a.imag += b.imag; + return a; +} + +template +constexpr device complex_t& operator+=( + device complex_t& a, + complex_t b) { + a.real += b.real; + a.imag += b.imag; + return a; +} + +template < + typename T, + typename U, + enable_if_t && is_lane_convertible_v, bool> = true> +constexpr complex_t operator+(U a, complex_t b) { + return {static_cast(a) + b.real, b.imag}; +} + +template < + typename T, + typename U, + enable_if_t && is_lane_convertible_v, bool> = true> +constexpr complex_t operator+(complex_t a, U b) { + return {a.real + static_cast(b), a.imag}; +} + +template +constexpr complex_t operator-(complex_t a, complex_t b) { + return {a.real - b.real, a.imag - b.imag}; +} + +template < + typename T, + typename U, + enable_if_t && is_lane_convertible_v, bool> = true> +constexpr complex_t operator-(U a, complex_t b) { + return {static_cast(a) - b.real, -b.imag}; +} + +template < + typename T, + typename U, + enable_if_t && is_lane_convertible_v, bool> = true> +constexpr complex_t operator-(complex_t a, U b) { + return {a.real - static_cast(b), a.imag}; +} + +template +constexpr complex_t operator*(complex_t a, complex_t b) { + return {a.real * b.real - a.imag * b.imag, a.real * b.imag + a.imag * b.real}; +} + +template +constexpr complex_t operator/(complex_t a, complex_t b) { + float ar = a.real, ai = a.imag; + float br = b.real, bi = b.imag; + if (abs(br) >= abs(bi)) { + auto ratio = bi / br; + auto denom = br + bi * ratio; + return { + static_cast((ar + ai * ratio) / denom), + static_cast((ai - ar * ratio) / denom)}; + } + auto ratio = br / bi; + auto denom = bi + br * ratio; + return { + static_cast((ar * ratio + ai) / denom), + static_cast((ai * ratio - ar) / denom)}; +} + +template < + typename T, + typename U, + enable_if_t && is_lane_convertible_v, bool> = true> +constexpr complex_t operator/(U a, complex_t b) { + return complex_t(a) / b; +} + +template +constexpr complex_t operator%(complex_t a, complex_t b) { + auto real = a.real - (b.real * static_cast(a.real / b.real)); + auto imag = a.imag - (b.imag * static_cast(a.imag / b.imag)); + if (real != 0 && (real < 0 != b.real < 0)) { + real += b.real; + } + if (imag != 0 && (imag < 0 != b.imag < 0)) { + imag += b.imag; + } + return {real, imag}; +} + +static_assert( + (complex_t{1.0h, 2.0h} * complex_t{3.0h, 4.0h}).real == -5.0h); +static_assert( + (complex_t{bfloat16_t(1.0f), bfloat16_t(2.0f)} * + complex_t{bfloat16_t(3.0f), bfloat16_t(4.0f)}) + .real == bfloat16_t(-5.0f)); +// ==== defines.h +// Copyright © 2023 Apple Inc. + +#pragma once + +#if defined __METAL__ || defined MLX_METAL_JIT +#define MTL_CONST constant +#else +#define MTL_CONST +#endif + +static MTL_CONST constexpr int MAX_REDUCE_SPECIALIZED_DIMS = 4; +static MTL_CONST constexpr int REDUCE_N_READS = 4; +static MTL_CONST constexpr int REDUCE_N_WRITES = 4; +static MTL_CONST constexpr int SOFTMAX_N_READS = 4; +static MTL_CONST constexpr int RMS_N_READS = 4; +static MTL_CONST constexpr int RMS_LOOPED_LIMIT = 4096; +static MTL_CONST constexpr int CROSS_ENTROPY_N_READS = 4; + +// Instantiate a templated kernel. +// Extra args are used as template parameters: +// e.g. instantiate_kernel(binary_int, binary, a, b) -> +// [[host_name(binary_int)]] [kernel] binary +#define instantiate_kernel(name, func, ...) \ + template [[host_name( \ + name)]] [[kernel]] decltype(func<__VA_ARGS__>) func<__VA_ARGS__>; +// ==== logging.h +// Copyright © 2025 Apple Inc. + +#pragma once + +#if defined(__METAL_VERSION__) && (__METAL_VERSION__ >= 320) +#include + +namespace mlx { +using os_log = metal::os_log; +} // namespace mlx + +#else + +namespace mlx { +struct os_log { + constexpr os_log(constant char*, constant char*) constant {} + + template + void log_debug(constant char*, Args...) const thread {} + + template + void log_debug(constant char*, Args...) const constant {} +}; +} // namespace mlx + +#endif +// ==== utils.h +// Copyright © 2023-2024 Apple Inc. + +#pragma once + +#include + + +typedef half float16_t; + +// Work per thread values for different types. The values here are expected to +// match get_work_per_thread in mlx/backend/metal/utils.h +template +struct WorkPerThread { + static_assert(sizeof(U) <= 8, "Type too large"); + static constexpr int constant n = 8 / sizeof(U); +}; + +/////////////////////////////////////////////////////////////////////////////// +// Type limits utils +/////////////////////////////////////////////////////////////////////////////// + +template +struct Limits { + static const constant U max = metal::numeric_limits::max(); + static const constant U min = metal::numeric_limits::min(); + static const constant U finite_max = metal::numeric_limits::max(); + static const constant U finite_min = metal::numeric_limits::min(); +}; + +#define instantiate_default_limit(type) \ + template <> \ + struct Limits { \ + static constexpr constant type max = metal::numeric_limits::max(); \ + static constexpr constant type min = metal::numeric_limits::min(); \ + static constexpr constant type finite_max = \ + metal::numeric_limits::max(); \ + static constexpr constant type finite_min = \ + metal::numeric_limits::min(); \ + }; + +instantiate_default_limit(uint8_t); +instantiate_default_limit(uint16_t); +instantiate_default_limit(uint32_t); +instantiate_default_limit(uint64_t); +instantiate_default_limit(int8_t); +instantiate_default_limit(int16_t); +instantiate_default_limit(int32_t); +instantiate_default_limit(int64_t); + +#define instantiate_float_limit(type) \ + template <> \ + struct Limits { \ + static constexpr constant type max = \ + metal::numeric_limits::infinity(); \ + static constexpr constant type min = \ + -metal::numeric_limits::infinity(); \ + static constexpr constant type finite_max = \ + metal::numeric_limits::max(); \ + static constexpr constant type finite_min = \ + -metal::numeric_limits::max(); \ + }; + +instantiate_float_limit(half); +instantiate_float_limit(float); +instantiate_float_limit(bfloat16_t); + +template <> +struct Limits { + static constexpr constant bool max = true; + static constexpr constant bool min = false; +}; + +template +struct Limits> { + inline static constexpr constant complex_t max = complex_t( + metal::numeric_limits::infinity(), + metal::numeric_limits::infinity()); + inline static constexpr constant complex_t min = complex_t( + -metal::numeric_limits::infinity(), + -metal::numeric_limits::infinity()); +}; + +/////////////////////////////////////////////////////////////////////////////// +// Indexing utils +/////////////////////////////////////////////////////////////////////////////// + +#define MLX_MTL_PRAGMA_UNROLL _Pragma("clang loop unroll(full)") + +/////////////////////////////////////////////////////////////////////////////// +// Single Array with generic dims + +template +METAL_FUNC IdxT elem_to_loc( + IdxT elem, + constant const int* shape, + constant const int64_t* strides, + int ndim) { + IdxT loc = 0; + for (int i = ndim - 1; i >= 0 && elem > 0; --i) { + loc += (elem % shape[i]) * IdxT(strides[i]); + elem /= shape[i]; + } + return loc; +} + +// Non templated version to handle arbitrary dims +template +METAL_FUNC IdxT elem_to_loc( + uint3 elem, + constant const int* shape, + constant const int64_t* strides, + int ndim) { + IdxT loc = + elem.x * IdxT(strides[ndim - 1]) + elem.y * IdxT(strides[ndim - 2]); + for (int d = ndim - 3; d >= 0; --d) { + loc += (elem.z % shape[d]) * IdxT(strides[d]); + elem.z /= shape[d]; + } + return loc; +} + +/////////////////////////////////////////////////////////////////////////////// +// Single Array with fixed N dims + +template +METAL_FUNC IdxT elem_to_loc_1(uint elem, constant const int64_t& stride) { + return elem * IdxT(stride); +} + +template +METAL_FUNC IdxT elem_to_loc_2(uint2 elem, constant const int64_t strides[2]) { + return elem.x * IdxT(strides[1]) + elem.y * IdxT(strides[0]); +} + +template +METAL_FUNC IdxT elem_to_loc_3(uint3 elem, constant const int64_t strides[3]) { + return elem.x * IdxT(strides[2]) + elem.y * IdxT(strides[1]) + + elem.z * IdxT(strides[0]); +} + +/////////////////////////////////////////////////////////////////////////////// +// Multiple Arrays with generic dims + +template +METAL_FUNC vec elem_to_loc_2_nd( + uint3 elem, + constant const int* shape, + constant const int64_t* a_strides, + constant const int64_t* b_strides, + int ndim) { + vec loc = { + IdxT( + elem.x * IdxT(a_strides[ndim - 1]) + + IdxT(elem.y) * IdxT(a_strides[ndim - 2])), + IdxT( + elem.x * IdxT(b_strides[ndim - 1]) + + elem.y * IdxT(b_strides[ndim - 2]))}; + for (int d = ndim - 3; d >= 0; --d) { + uint l = elem.z % shape[d]; + loc.x += l * IdxT(a_strides[d]); + loc.y += l * IdxT(b_strides[d]); + elem.z /= shape[d]; + } + return loc; +} + +template +METAL_FUNC vec elem_to_loc_3_nd( + uint3 elem, + constant const int* shape, + constant const int64_t* a_strides, + constant const int64_t* b_strides, + constant const int64_t* c_strides, + int ndim) { + vec loc = { + IdxT(elem.x * IdxT(a_strides[ndim - 1])) + + IdxT(elem.y * IdxT(a_strides[ndim - 2])), + IdxT(elem.x * IdxT(b_strides[ndim - 1])) + + IdxT(elem.y * IdxT(b_strides[ndim - 2])), + IdxT(elem.x * IdxT(c_strides[ndim - 1])) + + IdxT(elem.y * IdxT(c_strides[ndim - 2]))}; + for (int d = ndim - 3; d >= 0; --d) { + uint l = elem.z % shape[d]; + loc.x += l * IdxT(a_strides[d]); + loc.y += l * IdxT(b_strides[d]); + loc.z += l * IdxT(c_strides[d]); + elem.z /= shape[d]; + } + return loc; +} + +/////////////////////////////////////////////////////////////////////////////// +// Elem to loc in a loop utils +/////////////////////////////////////////////////////////////////////////////// + +template +struct LoopedElemToLoc { + int dim; + LoopedElemToLoc inner_looper; + OffsetT offset{0}; + int index{0}; + + LoopedElemToLoc(int dim) thread : dim(dim), inner_looper(dim - 1) {} + + void next(const constant int* shape, const constant int64_t* strides) thread { + if (dim == 0) { + return; + } + index++; + offset += OffsetT(strides[dim - 1]); + if (index >= shape[dim - 1]) { + index = 0; + inner_looper.next(shape, strides); + offset = inner_looper.offset; + } + } + + void next(int n, const constant int* shape, const constant int64_t* strides) + thread { + if (dim == 0) { + return; + } + index += n; + offset += n * OffsetT(strides[dim - 1]); + + if (index >= shape[dim - 1]) { + int extra = index - shape[dim - 1]; + if (extra >= shape[dim - 1]) { + inner_looper.next(1 + extra / shape[dim - 1], shape, strides); + extra = extra % shape[dim - 1]; + } else { + inner_looper.next(shape, strides); + } + index = 0; + offset = inner_looper.offset; + if (extra > 0) { + next(extra, shape, strides); + } + } + } + + OffsetT location() thread { + return offset; + } +}; + +template +struct LoopedElemToLoc<1, OffsetT, true> { + int dim; + OffsetT offset{0}; + uint index{0}; + + LoopedElemToLoc(int dim) thread : dim(dim) {} + + void next(const constant int* shape, const constant int64_t* strides) thread { + index++; + if (dim > 1) { + offset = elem_to_loc(index, shape, strides, dim); + } else { + offset += OffsetT(strides[0]); + } + } + + void next(int n, const constant int* shape, const constant int64_t* strides) + thread { + index += n; + if (dim > 1) { + offset = elem_to_loc(index, shape, strides, dim); + } else { + offset = index * OffsetT(strides[0]); + } + } + + OffsetT location() thread { + return offset; + } +}; + +template +struct LoopedElemToLoc<1, OffsetT, false> { + OffsetT offset{0}; + + LoopedElemToLoc(int) thread {} + + void next(const constant int*, const constant int64_t* strides) thread { + offset += OffsetT(strides[0]); + } + + void next(int n, const constant int*, const constant int64_t* strides) + thread { + offset += n * OffsetT(strides[0]); + } + + OffsetT location() thread { + return offset; + } +}; + +/////////////////////////////////////////////////////////////////////////////// +// Calculation utils +/////////////////////////////////////////////////////////////////////////////// + +/** Compute ceil((float)N/(float)M) */ +template +inline T ceildiv(T N, U M) { + return (N + M - 1) / M; +} + +// https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html#1202 +inline float log1p(float x) { + float xp1 = 1.0f + x; + if (xp1 == Limits::max) { + return Limits::max; + } + if (xp1 == 1.0f) { + return x; + } + + return x * (metal::log(xp1) / (xp1 - 1.0f)); +} + +inline bfloat16_t log1p(bfloat16_t x) { + float xp1 = 1.0f + static_cast(x); + if (xp1 == Limits::max) { + return Limits::max; + } + if (xp1 == 1.0f) { + return x; + } + + return bfloat16_t(x * (metal::log(xp1) / (xp1 - 1.0f))); +} + +inline complex64_t log1p(complex64_t in) { + float x = in.real; + float y = in.imag; + float zabs = metal::precise::sqrt(x * x + y * y); + float theta = metal::atan2(y, x + 1); + if (zabs < 0.5f) { + float r = x * (2 + x) + y * y; + if (r == 0) { // handle underflow + return {x, theta}; + } + return {0.5f * log1p(r), theta}; + } else { + auto z0 = metal::sqrt((x + 1) * (x + 1) + y * y); + return {metal::log(z0), theta}; + } +} + +// https://github.com/pytorch/pytorch/blob/a82aae9d4a7827849ce50f31c4c7ee8f278d05f5/c10/metal/utils.h#L554 +inline float hypot(float x, float y) { + if (metal::isinf(x) || metal::isinf(y)) { + return metal::numeric_limits::infinity(); + } + if (metal::isnan(x) || metal::isnan(y)) { + return metal::numeric_limits::quiet_NaN(); + } + float a = metal::fmax(metal::fabs(x), metal::fabs(y)); + float b = metal::fmin(metal::fabs(x), metal::fabs(y)); + if (a == 0.0f) { + return 0.0f; + } + float r = (b / a) * (b / a); + float sqrt_1_plus_r = metal::precise::sqrt(1.0f + r); + float h1 = metal::sqrt(2.0f) * a; + float h2 = a + a * r / 2.0f; + float h3 = a * sqrt_1_plus_r; + bool is_h1 = (a == b); + bool is_h2 = ((sqrt_1_plus_r == 1.0f) && (r > 0.0f)); + return metal::select(metal::select(h3, h2, is_h2), h1, is_h1); +} + +/////////////////////////////////////////////////////////////////////////////// +// SIMD shuffle ops +/////////////////////////////////////////////////////////////////////////////// + +inline uint64_t simd_shuffle_down(uint64_t data, uint16_t delta) { + return as_type( + metal::simd_shuffle_down(as_type(data), delta)); +} + +inline int64_t simd_shuffle_down(int64_t data, uint16_t delta) { + return as_type( + metal::simd_shuffle_down(as_type(data), delta)); +} + +inline bool simd_shuffle_down(bool data, uint16_t delta) { + return simd_shuffle_down(static_cast(data), delta); +} + +inline complex64_t simd_shuffle_down(complex64_t data, uint16_t delta) { + return complex64_t( + simd_shuffle_down(data.real, delta), simd_shuffle_down(data.imag, delta)); +} + +inline uint64_t simd_shuffle_up(uint64_t data, uint16_t delta) { + return as_type(metal::simd_shuffle_up(as_type(data), delta)); +} + +inline int64_t simd_shuffle_up(int64_t data, uint16_t delta) { + return as_type(metal::simd_shuffle_up(as_type(data), delta)); +} + +inline bool simd_shuffle_up(bool data, uint16_t delta) { + return simd_shuffle_up(static_cast(data), delta); +} + +inline complex64_t simd_shuffle_up(complex64_t data, uint16_t delta) { + return complex64_t( + simd_shuffle_up(data.real, delta), simd_shuffle_up(data.imag, delta)); +} + +inline uint64_t +simd_shuffle_and_fill_up(uint64_t data, uint64_t filling, uint16_t delta) { + return as_type(metal::simd_shuffle_and_fill_up( + as_type(data), as_type(filling), delta)); +} + +inline int64_t +simd_shuffle_and_fill_up(int64_t data, int64_t filling, uint16_t delta) { + return as_type(metal::simd_shuffle_and_fill_up( + as_type(data), as_type(filling), delta)); +} + +inline bool simd_shuffle_and_fill_up(bool data, bool filling, uint16_t delta) { + return simd_shuffle_and_fill_up( + static_cast(data), static_cast(filling), delta); +} + +inline complex64_t simd_shuffle_and_fill_up( + complex64_t data, + complex64_t filling, + uint16_t delta) { + return complex64_t( + simd_shuffle_and_fill_up(data.real, filling.real, delta), + simd_shuffle_and_fill_up(data.imag, filling.imag, delta)); +} + +inline uint64_t simd_shuffle(uint64_t data, uint16_t lane) { + return as_type(metal::simd_shuffle(as_type(data), lane)); +} + +inline int64_t simd_shuffle(int64_t data, uint16_t lane) { + return as_type(metal::simd_shuffle(as_type(data), lane)); +} + +inline bool simd_shuffle(bool data, uint16_t lane) { + return simd_shuffle(static_cast(data), lane); +} + +inline complex64_t simd_shuffle(complex64_t data, uint16_t lane) { + return complex64_t( + simd_shuffle(data.real, lane), simd_shuffle(data.imag, lane)); +} + +// std::conditional is not included with Metal +template +struct ConditionalType { + using type = U; +}; + +template +struct ConditionalType { + using type = T; +}; + +/////////////////////////////////////////////////////////////////////////////// +// Type casting utils +/////////////////////////////////////////////////////////////////////////////// + +template +inline U cast_to(T val) { + return static_cast(val); +} + +template <> +inline bool cast_to(float val) { + return (as_type(val) & 0x7FFFFFFF) != 0; +} + +template <> +inline bool cast_to(bfloat16_t val) { + return (as_type(val) & 0x7FFF) != 0; +} + +template <> +inline bool cast_to(complex64_t val) { + return cast_to(val.real) || cast_to(val.imag); +} + +/////////////////////////////////////////////////////////////////////////////// +// Row tile scheduling utils +/////////////////////////////////////////////////////////////////////////////// + +// helper function to identify the tile, called from gather_mm / gather_qmm +template +METAL_FUNC bool schedule_row_tile( + const device int32_t* offsets, + const int num_groups, + const int M, + const int tile, + const uint simd_lane_id, + thread int& row, + thread int& group, + thread short& rows) { + int tiles_before = 0; + // each lane process an expert + for (int e = 0; e < num_groups; e += 32) { + const int g = e + simd_lane_id; // shift by lane id + int start = M; + int end = M; + if (g < num_groups) { + // start of the experts activations + start = offsets[g]; + // end of the experts activations + end = g + 1 < num_groups ? offsets[g + 1] : M; + } + // number of tiles per expert + const int n = (end - start + BM - 1) / BM; + // the total number of tiles up to and including this expert + const int tiles_through = tiles_before + simd_prefix_inclusive_sum(n); + const ushort owner_lane = ushort(simd_sum(int(tiles_through <= tile))); + if (owner_lane < 32) { + // if true, we found an owner + group = e + owner_lane; + // fill the row to start + row = simd_shuffle(start, owner_lane) + + (tile - simd_shuffle(tiles_through - n, owner_lane)) * BM; + // number of valid rows in the tile + rows = short(min(BM, simd_shuffle(end, owner_lane) - row)); + return true; + } + tiles_before = simd_shuffle(tiles_through, 31); + } + return false; +} +// ==== quantized_utils.h +// Copyright © 2023-2024 Apple Inc. + +#include +#include + +template +METAL_FUNC void gemm_loop_aligned( + threadgroup T* As, + threadgroup T* Bs, + thread mma_t& mma_op, + thread loader_a_t& loader_a, + thread loader_b_t& loader_b, + const int k_iterations) { + for (int k = 0; k < k_iterations; k++) { + threadgroup_barrier(mem_flags::mem_threadgroup); + + // Load elements into threadgroup memory + loader_a.load_unsafe(); + loader_b.load_unsafe(); + + threadgroup_barrier(mem_flags::mem_threadgroup); + + // Multiply and accumulate threadgroup elements + mma_op.mma(As, Bs); + + // Prepare for next iteration + loader_a.next(); + loader_b.next(); + } +} + +template < + bool rows_aligned, + bool cols_aligned, + bool transpose, + typename T, + typename mma_t, + typename loader_a_t, + typename loader_b_t> +METAL_FUNC void gemm_loop_unaligned( + threadgroup T* As, + threadgroup T* Bs, + thread mma_t& mma_op, + thread loader_a_t& loader_a, + thread loader_b_t& loader_b, + const int k_iterations, + const short tgp_bm, + const short tgp_bn, + const short tgp_bk) { + for (int k = 0; k < k_iterations; k++) { + threadgroup_barrier(mem_flags::mem_threadgroup); + + // Load elements into threadgroup memory + if (rows_aligned) { + loader_a.load_unsafe(); + } else { + loader_a.load_safe(short2(tgp_bk, tgp_bm)); + } + if (cols_aligned) { + loader_b.load_unsafe(); + } else { + loader_b.load_safe( + transpose ? short2(tgp_bk, tgp_bn) : short2(tgp_bn, tgp_bk)); + } + + threadgroup_barrier(mem_flags::mem_threadgroup); + + // Multiply and accumulate threadgroup elements + mma_op.mma(As, Bs); + + // Prepare for next iteration + loader_a.next(); + loader_b.next(); + } +} + +template +METAL_FUNC void gemm_loop_finalize( + threadgroup T* As, + threadgroup T* Bs, + thread mma_t& mma_op, + thread loader_a_t& loader_a, + thread loader_b_t& loader_b, + const short2 tile_a, + const short2 tile_b) { + loader_a.load_safe(tile_a); + loader_b.load_safe(tile_b); + threadgroup_barrier(mem_flags::mem_threadgroup); + mma_op.mma(As, Bs); +} +// ==== steel/defines.h +// Copyright © 2024 Apple Inc. + +#pragma once + +#define STEEL_CONST static constant constexpr const +#define STEEL_PRAGMA_UNROLL _Pragma("clang loop unroll(full)") +#define STEEL_PRAGMA_NO_UNROLL _Pragma("clang loop unroll(disable)") +// ==== steel/gemm/loader.h +// Copyright © 2024 Apple Inc. + +#pragma once + + +/////////////////////////////////////////////////////////////////////////////// +// Loading helper +/////////////////////////////////////////////////////////////////////////////// + +namespace mlx { +namespace steel { + +template < + typename T, + short BROWS, + short BCOLS, + short dst_ld, + short reduction_dim, + short tgp_size, + short alignment = 1, + short n_reads = (BCOLS * BROWS) / (tgp_size), + short TCOLS = BCOLS / n_reads, + short TROWS = tgp_size / TCOLS> +struct BlockLoader { + STEEL_CONST short n_rows = (BROWS + TROWS - 1) / TROWS; + STEEL_CONST short vec_size = n_reads; + + // Leading dimension for src + const int src_ld; + const int tile_stride; + + // Thread location indices + const short thread_idx; + const short bi; + const short bj; + + // threadgroup and device memory + threadgroup T* dst; + const device T* src; + + struct alignas(alignment * sizeof(T)) ReadVector { + uint8_t v[sizeof(T) * vec_size]; + }; + + /* Constructor */ + METAL_FUNC BlockLoader( + const device T* src_, + const int src_ld_, + threadgroup T* dst_, + ushort simd_group_id [[simdgroup_index_in_threadgroup]], + ushort simd_lane_id [[thread_index_in_simdgroup]]) thread + : src_ld(src_ld_), + tile_stride(reduction_dim ? BCOLS : BROWS* src_ld), + thread_idx(simd_group_id * 32 + simd_lane_id), + bi(thread_idx / TCOLS), + bj(vec_size*(thread_idx % TCOLS)), + dst(dst_ + bi * dst_ld + bj), + src(src_ + bi * src_ld + bj) {} + + /* Apply operation to threadgroup without bound checking */ + template + METAL_FUNC void apply_inplace_op(thread const UnaryOp& op) const thread { + STEEL_PRAGMA_UNROLL + for (short i = 0; i < BROWS; i += TROWS) { + STEEL_PRAGMA_UNROLL + for (short j = 0; j < vec_size; j++) { + dst[i * dst_ld + j] = op.apply(dst[i * dst_ld + j]); + } + } + } + + /* Load from device memory into threadgroup memory - without bound checking */ + METAL_FUNC void load_unsafe() const thread { + STEEL_PRAGMA_UNROLL + for (short i = 0; i < BROWS; i += TROWS) { + *((threadgroup ReadVector*)(&dst[i * dst_ld])) = + *((const device ReadVector*)(&src[i * src_ld])); + } + } + + /* Load from device memory into threadgroup memory - with bound checking */ + METAL_FUNC void load_safe(short2 src_tile_dim) const thread { + src_tile_dim = src_tile_dim - short2(bj, bi); + + // Skip loading if thread has no valid reads + if (src_tile_dim.x <= 0 || src_tile_dim.y <= 0) { + STEEL_PRAGMA_UNROLL + for (short i = 0; i < BROWS; i += TROWS) { + STEEL_PRAGMA_UNROLL + for (short j = 0; j < vec_size; j++) { + dst[i * dst_ld + j] = T(0); + } + } + return; + } + + // Use fast thread memory for bound checks + bool tmp_idx[vec_size]; + T tmp_val[vec_size]; + + STEEL_PRAGMA_UNROLL + for (short i = 0; i < BROWS; i += TROWS) { + // Make sure tmp_idx only contains valid indices + STEEL_PRAGMA_UNROLL + for (short j = 0; j < vec_size; j++) { + tmp_idx[j] = (i < src_tile_dim.y) && (j < src_tile_dim.x); + } + + // Read valid indices into tmp_val + STEEL_PRAGMA_UNROLL + for (short j = 0; j < vec_size; j++) { + tmp_val[j] = src[(tmp_idx[j] ? i * src_ld + j : 0)]; + } + + // Zero out unneeded values + STEEL_PRAGMA_UNROLL + for (short j = 0; j < vec_size; j++) { + tmp_val[j] = tmp_idx[j] ? tmp_val[j] : T(0); + } + + // Copy values to threadgroup memory + STEEL_PRAGMA_UNROLL + for (short j = 0; j < vec_size; j++) { + dst[i * dst_ld + j] = tmp_val[j]; + } + } + } + + /* Iteration helper */ + METAL_FUNC void next() thread { + src += tile_stride; + } +}; + +} // namespace steel +} // namespace mlx +// ==== steel/utils.h +// Copyright © 2024 Apple Inc. + +#pragma once + +#include + +METAL_FUNC ulong2 elem_to_loc_broadcast( + uint elem, + constant const int* shape, + constant const int64_t* a_strides, + constant const int64_t* b_strides, + int ndim) { + ulong loc_a{0}; + ulong loc_b{0}; + for (int i = ndim - 1; i >= 0 && elem > 0; --i) { + int pos_in_dim = (elem % shape[i]); + elem /= shape[i]; + loc_a += pos_in_dim * a_strides[i]; + loc_b += pos_in_dim * b_strides[i]; + } + return ulong2(loc_a, loc_b); +} + +METAL_FUNC ulong3 elem_to_loc_broadcast( + uint elem, + constant const int* shape, + constant const int64_t* a_strides, + constant const int64_t* b_strides, + constant const int64_t* c_strides, + int ndim) { + ulong loc_a{0}; + ulong loc_b{0}; + ulong loc_c{0}; + for (int i = ndim - 1; i >= 0 && elem > 0; --i) { + int pos_in_dim = (elem % shape[i]); + elem /= shape[i]; + loc_a += pos_in_dim * a_strides[i]; + loc_b += pos_in_dim * b_strides[i]; + loc_c += pos_in_dim * c_strides[i]; + } + return ulong3(loc_a, loc_b, loc_c); +} +// ==== steel/gemm/transforms.h +// Copyright © 2024 Apple Inc. + +#pragma once + + +/////////////////////////////////////////////////////////////////////////////// +// Transforms and Epilogues +/////////////////////////////////////////////////////////////////////////////// + +namespace mlx { +namespace steel { + +template +struct TransformNone { + static METAL_FUNC OutT apply(InT x) { + return static_cast(x); + } + + static METAL_FUNC OutT apply(InT x, OutT) { + return static_cast(x); + } +}; + +template +struct TransformAdd { + TransformAdd(const float, const float) thread {} + + static METAL_FUNC OutT apply(InT x) { + return static_cast(x); + } + + static METAL_FUNC OutT apply(InT x, OutT c) { + return static_cast(x) + c; + } +}; + +template +struct TransformAxpby { + const float alpha; + const float beta; + + TransformAxpby(const float alpha_, const float beta_) thread : alpha(alpha_), + beta(beta_) {} + + static METAL_FUNC OutT apply(InT x) { + return static_cast(x); + } + + METAL_FUNC OutT apply(InT x, OutT c) const thread { + return static_cast( + x * static_cast(alpha) + (static_cast(beta) * c)); + } +}; + +template +struct AccumHelper { + typedef float accum_type; +}; + +struct BlockSwizzle { + static METAL_FUNC int2 + swizzle(uint3 tid [[threadgroup_position_in_grid]], const int swizzle_log) { + const int tid_x = (tid.x) >> swizzle_log; + const int tid_y = + ((tid.y) << swizzle_log) + ((tid.x) & ((1 << swizzle_log) - 1)); + return int2(tid_x, tid_y); + } +}; + +} // namespace steel +} // namespace mlx +// ==== steel/utils/type_traits.h +// Copyright © 2024 Apple Inc. + +#pragma once + +#include + +#pragma METAL internals : enable + +namespace metal { + +template +struct is_empty : metal::bool_constant<__is_empty(T)> {}; + +#ifdef __cpp_variable_templates +template +constexpr constant bool is_empty_v = is_empty::value; +#endif + +template +struct make_void { + typedef void type; +}; + +template +using void_t = typename make_void::type; + +template +struct is_static : metal::bool_constant>::value> {}; + +template +struct pointer_element {}; + +template +struct pointer_element { + using type = remove_cv_t; +}; +template +struct pointer_element { + using type = remove_cv_t; +}; +template +struct pointer_element { + using type = remove_cv_t; +}; +template +struct pointer_element { + using type = remove_cv_t; +}; + +template +using pointer_element_t = typename pointer_element>::type; + +} // namespace metal + +#pragma METAL internals : disable +// ==== steel/utils/integral_constant.h +// Copyright © 2024 Apple Inc. + +#pragma once + +#include + +#pragma METAL internals : enable + +namespace mlx { +namespace steel { + +/////////////////////////////////////////////////////////////////////////////// +// Integral constant with casting +/////////////////////////////////////////////////////////////////////////////// + +template +struct integral_constant { + static constexpr constant T value = v; + using value_type = T; + using type = integral_constant; + + METAL_FUNC constexpr operator value_type() const thread noexcept { + return value; + } +}; + +template +using bool_constant = integral_constant; +using true_type = bool_constant; +using false_type = bool_constant; + +template +struct is_integral : bool_constant::value> {}; + +template +struct is_integral> + : bool_constant::value> {}; + +template +constexpr constant bool is_integral_v = is_integral::value; + +template +using Int = integral_constant; + +/////////////////////////////////////////////////////////////////////////////// +// Binary Operators on Integral constants +/////////////////////////////////////////////////////////////////////////////// + +#define integral_const_binop(__op__, __operator__) \ + template \ + METAL_FUNC constexpr auto __operator__( \ + integral_constant, integral_constant) { \ + constexpr auto res = tv __op__ uv; \ + using res_t = metal::remove_addrspace_t; \ + return integral_constant{}; \ + } + +integral_const_binop(+, operator+); +integral_const_binop(-, operator-); +integral_const_binop(*, operator*); +integral_const_binop(/, operator/); + +integral_const_binop(==, operator==); +integral_const_binop(!=, operator!=); +integral_const_binop(<, operator<); +integral_const_binop(>, operator>); +integral_const_binop(<=, operator<=); +integral_const_binop(>=, operator>=); + +integral_const_binop(&&, operator&&); +integral_const_binop(||, operator||); + +template >> +METAL_FUNC constexpr auto operator||(true_type, T) { + return true_type{}; +} +template >> +METAL_FUNC constexpr auto operator||(T, true_type) { + return true_type{}; +} + +template >> +METAL_FUNC constexpr auto operator&&(false_type, T) { + return false_type{}; +} + +template >> +METAL_FUNC constexpr auto operator&&(T, false_type) { + return false_type{}; +} + +// Dispatch utilities +template +void dispatch_bool(bool v, F f) { + if (v) { + f(true_type{}); + } else { + f(false_type{}); + } +} + +template +constexpr void const_for_loop(F f) { + if constexpr (start < stop) { + constexpr auto idx = Int{}; + f(idx); + const_for_loop(f); + } +} + +#undef integral_const_binop + +/////////////////////////////////////////////////////////////////////////////// +// Reduction operators +/////////////////////////////////////////////////////////////////////////////// + +template +METAL_FUNC constexpr T sum(T x) { + return x; +} + +template +METAL_FUNC constexpr auto sum(T x, Us... us) { + return x + sum(us...); +} + +} // namespace steel +} // namespace mlx + +#pragma METAL internals : disable +// ==== steel/gemm/mma.h +// Copyright © 2024 Apple Inc. + +#pragma once + +#include +#include +#include + + +using namespace metal; + +/////////////////////////////////////////////////////////////////////////////// +// MMA helper +/////////////////////////////////////////////////////////////////////////////// + +namespace mlx { +namespace steel { + +template +struct BaseMMAFrag { + static_assert( + kFragRows_ == 8, + "Only 8 x 8 fragment matrices are currently supported"); + static_assert( + kFragCols_ == 8, + "Only 8 x 8 fragment matrices are currently supported"); +}; + +template +struct BaseMMAFrag { + STEEL_CONST int kFragRows = 8; + STEEL_CONST int kFragCols = 8; + + STEEL_CONST int kElemsPerFrag = (kFragRows * kFragCols) / 32; + + STEEL_CONST int kElemRows = 1; + STEEL_CONST int kElemCols = 2; + + static_assert( + kElemRows * kElemCols == kElemsPerFrag, + "MMAFrag shape is not consistent with MMAFrag size"); + + typedef metal::simdgroup_matrix mat_type; + typedef metal::vec frag_type; + + METAL_FUNC static constexpr short2 get_coord( + ushort simd_lane_id [[thread_index_in_simdgroup]]) { + const short qid = simd_lane_id / 4; + const short fm = (qid & 4) + ((simd_lane_id / 2) % 4); + const short fn = (qid & 2) * 2 + (simd_lane_id % 2) * 2; + return short2{fn, fm}; + } + + template + METAL_FUNC static constexpr void + load(thread frag_type& dst, SrcPtrType src, StrX str_x, StrY str_y) { + STEEL_PRAGMA_UNROLL + for (short i = 0; i < kElemRows; i++) { + STEEL_PRAGMA_UNROLL + for (short j = 0; j < kElemCols; j++) { + dst[i * kElemCols + j] = static_cast(src[i * str_x + j * str_y]); + } + } + } + + template < + typename SrcPtrType, + typename StrX, + typename StrY, + typename LimX, + typename LimY, + typename OffX, + typename OffY> + METAL_FUNC static constexpr void load_safe( + thread frag_type& dst, + SrcPtrType src, + StrX str_x, + StrY str_y, + LimX lim_x, + LimY lim_y, + OffX off_x = Int<0>{}, + OffY off_y = Int<0>{}) { + STEEL_PRAGMA_UNROLL + for (short i = 0; i < kElemRows; i++) { + STEEL_PRAGMA_UNROLL + for (short j = 0; j < kElemCols; j++) { + if ((off_x + i) < lim_x && (off_y + j) < lim_y) { + dst[i * kElemCols + j] = + static_cast(src[(off_x + i) * str_x + (off_y + j) * str_y]); + } else { + dst[i * kElemCols + j] = T(0); + } + } + } + } + + template + METAL_FUNC static constexpr void + store(const thread frag_type& src, DstPtrType dst, StrX str_x, StrY str_y) { + using U = pointer_element_t; + + STEEL_PRAGMA_UNROLL + for (short i = 0; i < kElemRows; i++) { + STEEL_PRAGMA_UNROLL + for (short j = 0; j < kElemCols; j++) { + dst[i * str_x + j * str_y] = static_cast(src[i * kElemCols + j]); + } + } + } + + template < + typename DstPtrType, + typename StrX, + typename StrY, + typename LimX, + typename LimY, + typename OffX, + typename OffY> + METAL_FUNC static constexpr void store_safe( + const thread frag_type& src, + DstPtrType dst, + StrX str_x, + StrY str_y, + LimX lim_x, + LimY lim_y, + OffX off_x = Int<0>{}, + OffY off_y = Int<0>{}) { + using U = pointer_element_t; + + STEEL_PRAGMA_UNROLL + for (short i = 0; i < kElemRows; i++) { + STEEL_PRAGMA_UNROLL + for (short j = 0; j < kElemCols; j++) { + if ((off_x + i) < lim_x && (off_y + j) < lim_y) { + dst[(off_x + i) * str_x + (off_y + j) * str_y] = + static_cast(src[i * kElemCols + j]); + } + } + } + } + + template < + typename DstPtrType, + typename StrX, + typename StrY, + typename StartX, + typename StopX, + typename StartY, + typename StopY, + typename OffX, + typename OffY> + METAL_FUNC static constexpr void store_slice( + const thread frag_type& src, + DstPtrType dst, + StrX str_x, + StrY str_y, + StartX start_x, + StopX stop_x, + StartY start_y, + StopY stop_y, + OffX off_x = Int<0>{}, + OffY off_y = Int<0>{}) { + using U = pointer_element_t; + + STEEL_PRAGMA_UNROLL + for (short i = 0; i < kElemRows; i++) { + STEEL_PRAGMA_UNROLL + for (short j = 0; j < kElemCols; j++) { + if ((off_x + i) < stop_x && (off_x + i) >= start_x && + (off_y + j) < stop_y && (off_y + j) >= start_y) { + dst[(off_x + i) * str_x + (off_y + j) * str_y] = + static_cast(src[i * kElemCols + j]); + } + } + } + } + + METAL_FUNC static constexpr void mma( + thread frag_type& D, + thread frag_type& A, + thread frag_type& B, + thread frag_type& C) { + mat_type D_mat; + mat_type A_mat; + mat_type B_mat; + mat_type C_mat; + + reinterpret_cast(A_mat.thread_elements()) = A; + reinterpret_cast(B_mat.thread_elements()) = B; + reinterpret_cast(C_mat.thread_elements()) = C; + + mma(D_mat, A_mat, B_mat, C_mat); + + D = reinterpret_cast(D_mat.thread_elements()); + } + + METAL_FUNC static constexpr void mma( + thread mat_type& D, + thread mat_type& A, + thread mat_type& B, + thread mat_type& C) { + simdgroup_multiply_accumulate(D, A, B, C); + } +}; + +template < + typename T, + int kTileRows_, + int kTileCols_, + class MMAFrag_ = BaseMMAFrag> +struct MMATile { + using MMAFrag_t = MMAFrag_; + using elem_type = T; + STEEL_CONST int kFragRows = MMAFrag_t::kFragRows; + STEEL_CONST int kFragCols = MMAFrag_t::kFragCols; + STEEL_CONST int kElemsPerFrag = MMAFrag_t::kElemsPerFrag; + + STEEL_CONST int kTileRows = kTileRows_; + STEEL_CONST int kTileCols = kTileCols_; + + STEEL_CONST int kRows = kTileRows * kFragRows; + STEEL_CONST int kCols = kTileCols * kFragCols; + + STEEL_CONST int kNumFrags = kTileRows * kTileCols; + STEEL_CONST int kElemsPerTile = kNumFrags * kElemsPerFrag; + + typedef typename MMAFrag_t::mat_type mat_type; + typedef typename MMAFrag_t::frag_type frag_type; + + frag_type val_frags[kNumFrags] = {frag_type(0)}; + + METAL_FUNC MMATile() thread {} + + METAL_FUNC constexpr void clear() thread { + STEEL_PRAGMA_UNROLL + for (short i = 0; i < kNumFrags; ++i) { + val_frags[i] = frag_type(0); + } + } + + METAL_FUNC constexpr thread frag_type& frag_at(const short i, const short j) + thread { + return val_frags[i * kTileCols + j]; + } + + METAL_FUNC constexpr const thread frag_type& frag_at( + const short i, + const short j) const thread { + return val_frags[i * kTileCols + j]; + } + + METAL_FUNC mat_type mat_at(const short i, const short j) thread { + mat_type val_mat; + STEEL_PRAGMA_UNROLL + for (short ii = 0; ii < kElemsPerFrag; ++ii) { + val_mat.thread_elements()[ii] = frag_at(i, j)[ii]; + } + return val_mat; + } + + METAL_FUNC thread elem_type* elems() thread { + return reinterpret_cast(val_frags); + } + + METAL_FUNC const thread elem_type* elems() const thread { + return reinterpret_cast(val_frags); + } + + template + METAL_FUNC void load(const threadgroup U* src) thread { + STEEL_PRAGMA_UNROLL + for (short i = 0; i < kTileRows; ++i) { + STEEL_PRAGMA_UNROLL + for (short j = 0; j < kTileCols; ++j) { + MMAFrag_t::load( + frag_at(i, j), + &( + src[(i * kFragRows) * w_x * str_x + + (j * kFragCols) * w_y * str_y]), + Int{}, + Int{}); + } + } + } + + template + METAL_FUNC void store(threadgroup U* dst) const thread { + STEEL_PRAGMA_UNROLL + for (short i = 0; i < kTileRows; ++i) { + STEEL_PRAGMA_UNROLL + for (short j = 0; j < kTileCols; ++j) { + MMAFrag_t::store( + frag_at(i, j), + &( + dst[(i * kFragRows) * w_x * str_x + + (j * kFragCols) * w_y * str_y]), + Int{}, + Int{}); + } + } + } + + template + METAL_FUNC void load(const device U* src, const int ld) thread { + STEEL_PRAGMA_UNROLL + for (short i = 0; i < kTileRows; ++i) { + STEEL_PRAGMA_UNROLL + for (short j = 0; j < kTileCols; ++j) { + MMAFrag_t::load( + frag_at(i, j), + &(src[(i * kFragRows) * w_x * ld + (j * kFragCols) * w_y]), + ld, + Int<1>{}); + } + } + } + + template + METAL_FUNC void store(device U* dst, const int ld) const thread { + STEEL_PRAGMA_UNROLL + for (short i = 0; i < kTileRows; ++i) { + STEEL_PRAGMA_UNROLL + for (short j = 0; j < kTileCols; ++j) { + MMAFrag_t::store( + frag_at(i, j), + &(dst[(i * kFragRows) * w_x * ld + (j * kFragCols) * w_y]), + ld, + Int<1>{}); + } + } + } + + template + METAL_FUNC void load_safe( + const device U* src, + const int ld, + const short2 src_tile_dims) thread { + STEEL_PRAGMA_UNROLL + for (int i = 0; i < kTileRows; ++i) { + STEEL_PRAGMA_UNROLL + for (int j = 0; j < kTileCols; ++j) { + MMAFrag_t::load_safe( + frag_at(i, j), + src, + ld, + Int<1>{}, + src_tile_dims.y, + src_tile_dims.x, + (i * kFragRows) * w_x, + (j * kFragCols) * w_y); + } + } + } + + template + METAL_FUNC void store_safe( + device U* dst, + const int ld, + const short2 dst_tile_dims) const thread { + STEEL_PRAGMA_UNROLL + for (int i = 0; i < kTileRows; ++i) { + STEEL_PRAGMA_UNROLL + for (int j = 0; j < kTileCols; ++j) { + MMAFrag_t::store_safe( + frag_at(i, j), + dst, + ld, + Int<1>{}, + dst_tile_dims.y, + dst_tile_dims.x, + (i * kFragRows) * w_x, + (j * kFragCols) * w_y); + } + } + } + + template + METAL_FUNC void store_slice( + device U* dst, + const int ld, + const short2 start, + const short2 stop) const thread { + STEEL_PRAGMA_UNROLL + for (int i = 0; i < kTileRows; ++i) { + STEEL_PRAGMA_UNROLL + for (int j = 0; j < kTileCols; ++j) { + MMAFrag_t::store_slice( + frag_at(i, j), + dst, + ld, + Int<1>{}, + start.y, + stop.y, + start.x, + stop.x, + (i * kFragRows) * w_x, + (j * kFragCols) * w_y); + } + } + } +}; + +template +METAL_FUNC void tile_matmad( + thread MMATile& D, + thread MMATile& A, + thread MMATile& B, + thread MMATile& C) { + STEEL_PRAGMA_UNROLL + for (short m = 0; m < M; ++m) { + STEEL_PRAGMA_UNROLL + for (short n = 0; n < N; ++n) { + short n_serp = (m % 2) ? (N - 1 - n) : n; + STEEL_PRAGMA_UNROLL + for (short k = 0; k < K; ++k) { + MMATile::MMAFrag_t::mma( + D.frag_at(m, n_serp), + A.frag_at(m, k), + B.frag_at(k, n_serp), + C.frag_at(m, n_serp)); + } + } + } +} + +template +struct TransformNone { + static METAL_FUNC complex64_t apply(complex64_t x) { + return x; + } + static METAL_FUNC complex64_t apply(complex64_t x, complex64_t) { + return x; + } +}; + +template < + typename T, + typename U, + int BM, + int BN, + int BK, + int WM, + int WN, + bool transpose_a, + bool transpose_b, + short lda_tgp, + short ldb_tgp, + typename AccumType = float, + typename Epilogue = TransformNone> +struct BlockMMA { + // MMAFrag size + STEEL_CONST short kFragSize = 8; + using MMAFrag_acc_t = BaseMMAFrag; + + // Warp tile simdgroup matrix strides along M + STEEL_CONST short TM_stride = kFragSize * WM; + // Warp tile simdgroup matrix strides along M + STEEL_CONST short TN_stride = kFragSize * WN; + + // Warp tile size along M + STEEL_CONST short TM = BM / (kFragSize * WM); + // Warp tile size along N + STEEL_CONST short TN = BN / (kFragSize * WN); + + // Threadgroup A strides + STEEL_CONST short A_str_m = transpose_a ? 1 : lda_tgp; // M + STEEL_CONST short A_str_k = transpose_a ? lda_tgp : 1; // K + + // Threadgroup B strides + STEEL_CONST short B_str_k = transpose_b ? 1 : ldb_tgp; // K + STEEL_CONST short B_str_n = transpose_b ? ldb_tgp : 1; // N + + // Threadgroup strides along K + STEEL_CONST short tile_stride_a = kFragSize * A_str_k; + STEEL_CONST short tile_stride_b = kFragSize * B_str_k; + + // Simdgroup matrices + MMATile Atile; + MMATile Btile; + MMATile Ctile; + + // Offsets within threadgroup + short sm; + short sn; + + short As_offset; + short Bs_offset; + + /* Constructor */ + METAL_FUNC BlockMMA( + ushort simd_group_id [[simdgroup_index_in_threadgroup]], + ushort simd_lane_id [[thread_index_in_simdgroup]]) thread { + // Determine thread position in simdgroup matrix + short tm = kFragSize * (simd_group_id / WN); + short tn = kFragSize * (simd_group_id % WN); + + short2 simd_coord = MMAFrag_acc_t::get_coord(simd_lane_id); + sm = simd_coord.y; + sn = simd_coord.x; + + // Determine thread and simdgroup offset + As_offset = (tm + sm) * A_str_m + (sn)*A_str_k; // M, K + Bs_offset = (sm)*B_str_k + (tn + sn) * B_str_n; // K, N + + sm += tm; + sn += tn; + } + + /* (BM, BK) X (BK, BN) multiply accumulate function */ + METAL_FUNC void mma(const threadgroup T* As, const threadgroup T* Bs) thread { + // Adjust for simdgroup and thread location + As += As_offset; + Bs += Bs_offset; + + // Iterate over BK in blocks of kFragSize + STEEL_PRAGMA_UNROLL + for (short kk = 0; kk < BK; kk += kFragSize) { + simdgroup_barrier(mem_flags::mem_none); + + Atile.template load(As); + + simdgroup_barrier(mem_flags::mem_none); + + Btile.template load(Bs); + + simdgroup_barrier(mem_flags::mem_none); + + tile_matmad(Ctile, Atile, Btile, Ctile); + + // Progress to next simdgroup tile + As += tile_stride_a; + Bs += tile_stride_b; + } + } + + /* Store results from simdgroup_matrix results into device memory */ + METAL_FUNC void store_result(device U* D, const int ldd) thread { + // Apply epilogue + STEEL_PRAGMA_UNROLL + for (short i = 0; i < decltype(Ctile)::kElemsPerTile; i++) { + Ctile.elems()[i] = Epilogue::apply(Ctile.elems()[i]); + } + + // Adjust for simdgroup and thread location + D += sm * ldd + sn; + + Ctile.template store(D, ldd); + } + + METAL_FUNC void store_result_slice( + device U* D, + const int ldd, + short2 start, + short2 stop) thread { + // Apply epilogue + STEEL_PRAGMA_UNROLL + for (short i = 0; i < decltype(Ctile)::kElemsPerTile; i++) { + Ctile.elems()[i] = Epilogue::apply(Ctile.elems()[i]); + } + + D += sm * ldd + sn; + start -= short2(sn, sm); + stop -= short2(sn, sm); + + // TODO: Check the start as well + if (stop.y <= 0 || stop.x <= 0) { + return; + } + + Ctile.template store_slice(D, ldd, start, stop); + } + + METAL_FUNC void + store_result_safe(device U* D, const int ldd, short2 dst_tile_dims) thread { + // Apply epilogue + STEEL_PRAGMA_UNROLL + for (short i = 0; i < decltype(Ctile)::kElemsPerTile; i++) { + Ctile.elems()[i] = Epilogue::apply(Ctile.elems()[i]); + } + + // Adjust for simdgroup and thread location + D += sm * ldd + sn; + dst_tile_dims -= short2(sn, sm); + + if (dst_tile_dims.x <= 0 || dst_tile_dims.y <= 0) + return; + + Ctile.template store_safe(D, ldd, dst_tile_dims); + } + + /* Apply epilogue */ + template + METAL_FUNC void apply_epilogue( + thread const UnaryEpilogue& epilogue_op) thread { + // Loop over all simdgroup tiles + STEEL_PRAGMA_UNROLL + for (short i = 0; i < decltype(Ctile)::kElemsPerTile; i++) { + Ctile.elems()[i] = epilogue_op.apply(Ctile.elems()[i]); + } + } + + /* Apply epilogue */ + template + METAL_FUNC void apply_epilogue( + const device U* C, + const int ldc, + const int fdc, + thread const BinaryEpilogue& epilogue_op) thread { + // Adjust for simdgroup and thread location + C += (sm)*ldc + (sn)*fdc; + + // Loop over all simdgroup tiles + STEEL_PRAGMA_UNROLL + for (short i = 0; i < TM; i++) { + STEEL_PRAGMA_UNROLL + for (short j = 0; j < TN; j++) { + // Get accumulated result and associated offset in C + thread auto& accum = Ctile.frag_at(i, j); + int offset_c = (i * TM_stride) * ldc + (j * TN_stride) * fdc; + + // Apply epilogue + STEEL_PRAGMA_UNROLL + for (short k = 0; k < decltype(Ctile)::kElemsPerFrag; k++) { + accum[k] = epilogue_op.apply(accum[k], C[offset_c + k * fdc]); + } + } + } + } + + /* Apply epilogue */ + template + METAL_FUNC void apply_epilogue_safe( + const device U* C, + const int ldc, + const int fdc, + short2 dst_tile_dims, + thread const BinaryEpilogue& epilogue_op) thread { + // Adjust for simdgroup and thread location + C += (sm)*ldc + (sn)*fdc; + dst_tile_dims -= short2(sn, sm); + + if (dst_tile_dims.x <= 0 || dst_tile_dims.y <= 0) + return; + + // Loop over all simdgroup tiles + STEEL_PRAGMA_UNROLL + for (short i = 0; i < TM; i++) { + STEEL_PRAGMA_UNROLL + for (short j = 0; j < TN; j++) { + // Get accumulated result and associated offset in C + thread auto& accum = Ctile.frag_at(i, j); + int offset_c = (i * TM_stride) * ldc + (j * TN_stride) * fdc; + + constexpr short kelems = decltype(Ctile)::kElemsPerFrag; + + // Read C + U c_elems[kelems] = {0}; + + STEEL_PRAGMA_UNROLL + for (short k = 0; k < kelems; k++) { + if ((j * TN_stride + k) < dst_tile_dims.x) { + c_elems[k] = C[offset_c + k * fdc]; + } + } + + // Apply epilogue + STEEL_PRAGMA_UNROLL + for (short k = 0; k < kelems; k++) { + accum[k] = epilogue_op.apply(accum[k], c_elems[k]); + } + } + } + } + + /* Store results from simdgroup_matrix results into device memory */ + METAL_FUNC void store_result( + device U* D, + const int ldd, + const device U* C, + const int ldc, + const int fdc, + thread const Epilogue& epilogue_op) const thread { + // Adjust for simdgroup and thread location + C += (sm)*ldc + (sn)*fdc; + D += (sm)*ldd + sn; + + constexpr short kelems = decltype(Ctile)::kElemsPerFrag; + + // Loop over all simdgroup tiles + STEEL_PRAGMA_UNROLL + for (short i = 0; i < TM; i++) { + STEEL_PRAGMA_UNROLL + for (short j = 0; j < TN; j++) { + // Get accumulated result and associated offset in C + thread const auto& accum = Ctile.frag_at(i, j); + int offset_c = (i * TM_stride) * ldc + (j * TN_stride) * fdc; + int offset_d = (i * TM_stride) * ldd + (j * TN_stride); + + // Apply epilogue + STEEL_PRAGMA_UNROLL + for (short k = 0; k < kelems; k++) { + D[offset_d + k] = epilogue_op.apply(accum[k], C[offset_c + k * fdc]); + } + } + } + } + + METAL_FUNC void store_result_safe( + device U* D, + const int ldd, + const device U* C, + const int ldc, + const int fdc, + short2 dst_tile_dims, + thread const Epilogue& epilogue_op) const thread { + // Adjust for simdgroup and thread location + C += (sm)*ldc + (sn)*fdc; + D += (sm)*ldd + sn; + dst_tile_dims -= short2(sn, sm); + + if (dst_tile_dims.x <= 0 || dst_tile_dims.y <= 0) + return; + + constexpr short kelems = decltype(Ctile)::kElemsPerFrag; + + STEEL_PRAGMA_UNROLL + for (int i = 0; i < TM; i++) { + if (i * TM_stride < dst_tile_dims.y) { + STEEL_PRAGMA_UNROLL + for (int j = 0; j < TN; j++) { + // Get accumulated result and associated offset in C + thread const auto& accum = Ctile.frag_at(i, j); + int offset_c = (i * TM_stride) * ldc + (j * TN_stride) * fdc; + int offset_d = (i * TM_stride) * ldd + (j * TN_stride); + + // Apply epilogue + STEEL_PRAGMA_UNROLL + for (short k = 0; k < kelems; k++) { + if ((j * TN_stride + k) < dst_tile_dims.x) { + D[offset_d + k] = + epilogue_op.apply(accum[k], C[offset_c + k * fdc]); + } + } + } + } + } + } +}; + +template < + typename U, + int BM, + int BN, + int BK, + int WM, + int WN, + bool transpose_a, + bool transpose_b, + short lda_tgp, + short ldb_tgp, + typename AccumType, + typename Epilogue> +struct BlockMMA< + complex64_t, + U, + BM, + BN, + BK, + WM, + WN, + transpose_a, + transpose_b, + lda_tgp, + ldb_tgp, + AccumType, + Epilogue> { + static_assert( + metal::is_same_v, + "BlockMMA expects float accumulators"); + static_assert( + metal::is_same_v, + "For complex BlockMMA, U must be complex64_t; use a different epilogue for projections"); + // MMAFrag size + STEEL_CONST short kFragSize = 8; + using MMAFrag_acc_t = BaseMMAFrag; + + // Warp tile simdgroup matrix strides along M + STEEL_CONST short TM_stride = kFragSize * WM; + // Warp tile simdgroup matrix strides along M + STEEL_CONST short TN_stride = kFragSize * WN; + + // Warp tile size along M + STEEL_CONST short TM = BM / (kFragSize * WM); + // Warp tile size along N + STEEL_CONST short TN = BN / (kFragSize * WN); + + // Threadgroup A strides + STEEL_CONST short A_str_m = transpose_a ? 1 : lda_tgp; // M + STEEL_CONST short A_str_k = transpose_a ? lda_tgp : 1; // K + + // Threadgroup B strides + STEEL_CONST short B_str_k = transpose_b ? 1 : ldb_tgp; // K + STEEL_CONST short B_str_n = transpose_b ? ldb_tgp : 1; // N + + // Threadgroup strides along K + STEEL_CONST short tile_stride_a = kFragSize * A_str_k; + STEEL_CONST short tile_stride_b = kFragSize * B_str_k; + + // When indexing complex as float[2] + STEEL_CONST short A_str_m_f = A_str_m * 2; + STEEL_CONST short A_str_k_f = A_str_k * 2; + STEEL_CONST short B_str_k_f = B_str_k * 2; + STEEL_CONST short B_str_n_f = B_str_n * 2; + STEEL_CONST short tile_stride_a_f = tile_stride_a * 2; + STEEL_CONST short tile_stride_b_f = tile_stride_b * 2; + + // Accumulators (real/imag) + MMATile Ctile_r; + MMATile Ctile_i; + + // Offsets within threadgroup + short sm, sn; + short As_offset, Bs_offset; + + /* Constructor */ + METAL_FUNC BlockMMA( + ushort simd_group_id [[simdgroup_index_in_threadgroup]], + ushort simd_lane_id [[thread_index_in_simdgroup]]) thread { + // Determine thread position in simdgroup matrix + short tm = kFragSize * (simd_group_id / WN); + short tn = kFragSize * (simd_group_id % WN); + + short2 simd_coord = MMAFrag_acc_t::get_coord(simd_lane_id); + sm = simd_coord.y; + sn = simd_coord.x; + + // Determine thread and simdgroup offset + As_offset = (tm + sm) * A_str_m + (sn)*A_str_k; // (M,K) + Bs_offset = (sm)*B_str_k + (tn + sn) * B_str_n; // (K,N) + + sm += tm; + sn += tn; + } + + /* Karatsuba MMA: 3 real MMAs per K-chunk */ + METAL_FUNC void mma( + const threadgroup complex64_t* As, + const threadgroup complex64_t* Bs) thread { + // Adjust for simdgroup and thread location + As += As_offset; + Bs += Bs_offset; + threadgroup const float* As_f = + reinterpret_cast(As); + threadgroup const float* Bs_f = + reinterpret_cast(Bs); + + // Iterate over BK in blocks of kFragSize + STEEL_PRAGMA_UNROLL + for (short kk = 0; kk < BK; kk += kFragSize) { + simdgroup_barrier(mem_flags::mem_none); + + MMATile Ar, Ai; + Ar.template load(As_f + 0); + Ai.template load(As_f + 1); + + simdgroup_barrier(mem_flags::mem_none); + + MMATile Br, Bi; + Br.template load(Bs_f + 0); + Bi.template load(Bs_f + 1); + + simdgroup_barrier(mem_flags::mem_none); + + // P = Ar*Br ; Q = Ai*Bi ; R = (Ar+Ai)*(Br+Bi) + MMATile P, Q, R; + + tile_matmad(P, Ar, Br, P); + tile_matmad(Q, Ai, Bi, Q); + + STEEL_PRAGMA_UNROLL + for (short i = 0; i < decltype(Ar)::kElemsPerTile; ++i) + Ar.elems()[i] += Ai.elems()[i]; + STEEL_PRAGMA_UNROLL + for (short i = 0; i < decltype(Br)::kElemsPerTile; ++i) + Br.elems()[i] += Bi.elems()[i]; + + tile_matmad(R, Ar, Br, R); + + // C_r += P - Q ; C_i -= Q + STEEL_PRAGMA_UNROLL + for (short i = 0; i < decltype(Ctile_r)::kElemsPerTile; ++i) { + const auto p = P.elems()[i]; + const auto q = Q.elems()[i]; + const auto r = R.elems()[i]; + Ctile_r.elems()[i] += (p - q); + Ctile_i.elems()[i] += (r - p - q); + } + + // Progress to next simdgroup tile + As_f += tile_stride_a_f; + Bs_f += tile_stride_b_f; + } + } + + /* Store results from simdgroup_matrix results into device memory */ + METAL_FUNC void store_result(device U* D, const int ldd) thread { + // Adjust for simdgroup and thread location + D += sm * ldd + sn; + + STEEL_PRAGMA_UNROLL + for (short i = 0; i < TM; i++) { + STEEL_PRAGMA_UNROLL + for (short j = 0; j < TN; j++) { + thread const auto& r = Ctile_r.frag_at(i, j); + thread const auto& im = Ctile_i.frag_at(i, j); + int off = (i * TM_stride) * ldd + (j * TN_stride); + STEEL_PRAGMA_UNROLL + for (short k = 0; k < decltype(Ctile_r)::kElemsPerFrag; k++) { + D[off + k] = Epilogue::apply(complex64_t(r[k], im[k])); + } + } + } + } + + METAL_FUNC void store_result_slice( + device U* D, + const int ldd, + short2 start, + short2 stop) thread { + D += sm * ldd + sn; + start -= short2(sn, sm); + stop -= short2(sn, sm); + + if (stop.y <= 0 || stop.x <= 0) + return; + + STEEL_PRAGMA_UNROLL + for (short i = 0; i < TM; ++i) { + const int row = i * TM_stride; + if (row >= start.y && row < stop.y) { + STEEL_PRAGMA_UNROLL + for (short j = 0; j < TN; ++j) { + const int off = row * ldd + (j * TN_stride); + thread const auto& r = Ctile_r.frag_at(i, j); + thread const auto& im = Ctile_i.frag_at(i, j); + + STEEL_PRAGMA_UNROLL + for (short k = 0; k < decltype(Ctile_r)::kElemsPerFrag; ++k) { + const int col = j * TN_stride + k; + if (col >= start.x && col < stop.x) { + D[off + k] = Epilogue::apply(complex64_t(r[k], im[k])); + } + } + } + } + } + } + + METAL_FUNC void + store_result_safe(device U* D, const int ldd, short2 dst_tile_dims) thread { + D += sm * ldd + sn; + dst_tile_dims -= short2(sn, sm); + if (dst_tile_dims.x <= 0 || dst_tile_dims.y <= 0) + return; + STEEL_PRAGMA_UNROLL + for (short i = 0; i < TM; i++) { + if (i * TM_stride < dst_tile_dims.y) { + STEEL_PRAGMA_UNROLL + for (short j = 0; j < TN; j++) { + int off = (i * TM_stride) * ldd + (j * TN_stride); + thread const auto& r = Ctile_r.frag_at(i, j); + thread const auto& im = Ctile_i.frag_at(i, j); + STEEL_PRAGMA_UNROLL + for (short k = 0; k < decltype(Ctile_r)::kElemsPerFrag; k++) { + if ((j * TN_stride + k) < dst_tile_dims.x) { + D[off + k] = Epilogue::apply(complex64_t(r[k], im[k])); + } + } + } + } + } + } + + /* Apply epilogue */ + template + METAL_FUNC void apply_epilogue( + thread const UnaryEpilogue& epilogue_op) thread { + STEEL_PRAGMA_UNROLL + for (short i = 0; i < decltype(Ctile_r)::kElemsPerTile; i++) { + complex64_t out = epilogue_op.apply( + complex64_t(Ctile_r.elems()[i], Ctile_i.elems()[i])); + Ctile_r.elems()[i] = out.real; + Ctile_i.elems()[i] = out.imag; + } + } + + /* Apply epilogue */ + template + METAL_FUNC void apply_epilogue( + const device U* C, + const int ldc, + const int fdc, + thread const BinaryEpilogue& epilogue_op) thread { + // Adjust for simdgroup and thread location + C += (sm)*ldc + (sn)*fdc; + + // Loop over all simdgroup tiles + STEEL_PRAGMA_UNROLL + for (short i = 0; i < TM; i++) { + STEEL_PRAGMA_UNROLL + for (short j = 0; j < TN; j++) { + // Get accumulated result and associated offset in Cr, Ci + thread auto& r = Ctile_r.frag_at(i, j); + thread auto& im = Ctile_i.frag_at(i, j); + int offset_c = (i * TM_stride) * ldc + (j * TN_stride) * fdc; + + STEEL_PRAGMA_UNROLL + for (short k = 0; k < decltype(Ctile_r)::kElemsPerFrag; k++) { + complex64_t out = epilogue_op.apply( + complex64_t(r[k], im[k]), C[offset_c + k * fdc]); + r[k] = out.real; + im[k] = out.imag; + } + } + } + } + + /* Apply epilogue */ + template + METAL_FUNC void apply_epilogue_safe( + const device U* C, + const int ldc, + const int fdc, + short2 dst_tile_dims, + thread const BinaryEpilogue& epilogue_op) thread { + // Adjust for simdgroup and thread location + C += (sm)*ldc + (sn)*fdc; + dst_tile_dims -= short2(sn, sm); + + if (dst_tile_dims.x <= 0 || dst_tile_dims.y <= 0) + return; + + // Loop over all simdgroup tiles + STEEL_PRAGMA_UNROLL + for (short i = 0; i < TM; i++) { + STEEL_PRAGMA_UNROLL + for (short j = 0; j < TN; j++) { + // Get accumulated result and associated offset in Cr, Ci + thread auto& r = Ctile_r.frag_at(i, j); + thread auto& im = Ctile_i.frag_at(i, j); + int offset_c = (i * TM_stride) * ldc + (j * TN_stride) * fdc; + + constexpr short kelems = decltype(Ctile_r)::kElemsPerFrag; + complex64_t tmp[kelems]; + + STEEL_PRAGMA_UNROLL + for (short k = 0; k < kelems; k++) { + if ((j * TN_stride + k) < dst_tile_dims.x && + (i * TM_stride) < dst_tile_dims.y) { + tmp[k] = C[offset_c + k * fdc]; + } else { + tmp[k] = complex64_t(0.0f, 0.0f); + } + } + + // Apply epilogue + STEEL_PRAGMA_UNROLL + for (short k = 0; k < kelems; k++) { + complex64_t out = epilogue_op.apply(complex64_t(r[k], im[k]), tmp[k]); + r[k] = out.real; + im[k] = out.imag; + } + } + } + } + + /* Store results from simdgroup_matrix results into device memory */ + METAL_FUNC void store_result( + device U* D, + const int ldd, + const device U* C, + const int ldc, + const int fdc, + thread const Epilogue& epilogue_op) const thread { + // Adjust for simdgroup and thread location + C += (sm)*ldc + (sn)*fdc; + D += (sm)*ldd + sn; + + constexpr short kelems = decltype(Ctile_r)::kElemsPerFrag; + + // Loop over all simdgroup tiles + STEEL_PRAGMA_UNROLL + for (short i = 0; i < TM; i++) { + STEEL_PRAGMA_UNROLL + for (short j = 0; j < TN; j++) { + // Get accumulated result and associated offset in Cr, Ci + thread const auto& r = Ctile_r.frag_at(i, j); + thread const auto& im = Ctile_i.frag_at(i, j); + int off_c = (i * TM_stride) * ldc + (j * TN_stride) * fdc; + int off_d = (i * TM_stride) * ldd + (j * TN_stride); + + // Apply epilogue + STEEL_PRAGMA_UNROLL + for (short k = 0; k < kelems; k++) { + D[off_d + k] = + epilogue_op.apply(complex64_t(r[k], im[k]), C[off_c + k * fdc]); + } + } + } + } + + METAL_FUNC void store_result_safe( + device U* D, + const int ldd, + const device U* C, + const int ldc, + const int fdc, + short2 dst_tile_dims, + thread const Epilogue& epilogue_op) const thread { + // Adjust for simdgroup and thread location + C += (sm)*ldc + (sn)*fdc; + D += (sm)*ldd + sn; + dst_tile_dims -= short2(sn, sm); + + if (dst_tile_dims.x <= 0 || dst_tile_dims.y <= 0) + return; + + constexpr short kelems = decltype(Ctile_r)::kElemsPerFrag; + + STEEL_PRAGMA_UNROLL + for (int i = 0; i < TM; i++) { + if (i * TM_stride < dst_tile_dims.y) { + STEEL_PRAGMA_UNROLL + for (int j = 0; j < TN; j++) { + // Get accumulated result and associated offset in Cr, Ci + thread const auto& r = Ctile_r.frag_at(i, j); + thread const auto& im = Ctile_i.frag_at(i, j); + int off_c = (i * TM_stride) * ldc + (j * TN_stride) * fdc; + int off_d = (i * TM_stride) * ldd + (j * TN_stride); + + // Apply epilogue + STEEL_PRAGMA_UNROLL + for (short k = 0; k < kelems; k++) { + if ((j * TN_stride + k) < dst_tile_dims.x) { + D[off_d + k] = epilogue_op.apply( + complex64_t(r[k], im[k]), C[off_c + k * fdc]); + } + } + } + } + } + } +}; + +} // namespace steel +} // namespace mlx +// ==== steel/gemm/params.h +// Copyright © 2024 Apple Inc. + +#pragma once + +/////////////////////////////////////////////////////////////////////////////// +// GEMM param classes +/////////////////////////////////////////////////////////////////////////////// + +namespace mlx { +namespace steel { + +struct GEMMParams { + const int M; + const int N; + const int K; + + const int lda; + const int ldb; + const int ldd; + + const int tiles_n; + const int tiles_m; + + const int64_t batch_stride_a; + const int64_t batch_stride_b; + const int64_t batch_stride_d; + + const int swizzle_log; + const int gemm_k_iterations_aligned; + + const int batch_ndim; +}; + +struct GEMMSpiltKParams { + const int M; + const int N; + const int K; + + const int lda; + const int ldb; + const int ldc; + + const int tiles_n; + const int tiles_m; + + const int split_k_partitions; + const int split_k_partition_stride; + const int split_k_partition_size; + + const int swizzle_log; + const int gemm_k_iterations_aligned; +}; + +struct GEMMAddMMParams { + const int ldc; + const int fdc; + + const int64_t batch_stride_c; + + const float alpha; + const float beta; +}; + +} // namespace steel +} // namespace mlx +// ==== steel/gemm/gemm.h +// Copyright © 2024 Apple Inc. + +#pragma once + + +using namespace metal; + +/////////////////////////////////////////////////////////////////////////////// +// GEMM kernel class +/////////////////////////////////////////////////////////////////////////////// + +namespace mlx { +namespace steel { + +template +struct LoopAlignment {}; + +template < + typename T, + typename U, + int BM, + int BN, + int BK, + int WM, + int WN, + bool transpose_a, + bool transpose_b, + bool MN_aligned, + bool K_aligned, + typename AccumType = typename AccumHelper::accum_type, + typename Epilogue = TransformNone> +struct GEMMKernel { + STEEL_CONST short tgp_padding_a = 16 / sizeof(T); + STEEL_CONST short tgp_padding_b = 16 / sizeof(T); + STEEL_CONST short tgp_mem_size_a = + transpose_a ? BK * (BM + tgp_padding_a) : BM * (BK + tgp_padding_a); + STEEL_CONST short tgp_mem_size_b = + transpose_b ? BN * (BK + tgp_padding_b) : BK * (BN + tgp_padding_b); + STEEL_CONST short tgp_mem_size = tgp_mem_size_a + tgp_mem_size_b; + + STEEL_CONST short tgp_size = WM * WN * 32; + + using loader_a_t = BlockLoader< + T, + transpose_a ? BK : BM, + transpose_a ? BM : BK, + transpose_a ? BM + tgp_padding_a : BK + tgp_padding_a, + !transpose_a, + tgp_size>; + using loader_b_t = BlockLoader< + T, + transpose_b ? BN : BK, + transpose_b ? BK : BN, + transpose_b ? BK + tgp_padding_b : BN + tgp_padding_b, + transpose_b, + tgp_size>; + using mma_t = BlockMMA< + T, + U, + BM, + BN, + BK, + WM, + WN, + transpose_a, + transpose_b, + transpose_a ? BM + tgp_padding_a : BK + tgp_padding_a, + transpose_b ? BK + tgp_padding_b : BN + tgp_padding_b, + AccumType, + Epilogue>; + + /* Main kernel function */ + template + static METAL_FUNC void gemm_loop( + threadgroup T* As [[threadgroup(0)]], + threadgroup T* Bs [[threadgroup(1)]], + const int gemm_k_iterations, + thread loader_a_t& loader_a, + thread loader_b_t& loader_b, + thread mma_t& mma_op, + thread const short& tgp_bm, + thread const short& tgp_bn, + thread const short& lbk, + LoopAlignment l = {}) { + // Appease the compiler + (void)l; + + short2 tile_dims_A = transpose_a ? short2(tgp_bm, BK) : short2(BK, tgp_bm); + + short2 tile_dims_B = transpose_b ? short2(BK, tgp_bn) : short2(tgp_bn, BK); + + for (int k = 0; k < gemm_k_iterations; k++) { + threadgroup_barrier(mem_flags::mem_threadgroup); + // Load elements into threadgroup + if (M_aligned) { + loader_a.load_unsafe(); + } else { + loader_a.load_safe(tile_dims_A); + } + + if (N_aligned) { + loader_b.load_unsafe(); + } else { + loader_b.load_safe(tile_dims_B); + } + + threadgroup_barrier(mem_flags::mem_threadgroup); + + // Multiply and accumulate threadgroup elements + mma_op.mma(As, Bs); + + // Prepare for next iteration + loader_a.next(); + loader_b.next(); + } + + if (!K_aligned_) { + threadgroup_barrier(mem_flags::mem_threadgroup); + + short2 tile_dims_A_last = + transpose_a ? short2(tgp_bm, lbk) : short2(lbk, tgp_bm); + short2 tile_dims_B_last = + transpose_b ? short2(lbk, tgp_bn) : short2(tgp_bn, lbk); + + loader_a.load_safe(tile_dims_A_last); + loader_b.load_safe(tile_dims_B_last); + + threadgroup_barrier(mem_flags::mem_threadgroup); + + mma_op.mma(As, Bs); + } + } + + /* Main kernel function */ + static METAL_FUNC void run( + const device T* A [[buffer(0)]], + const device T* B [[buffer(1)]], + device U* D [[buffer(2)]], + const constant GEMMParams* params [[buffer(3)]], + threadgroup T* As [[threadgroup(0)]], + threadgroup T* Bs [[threadgroup(1)]], + uint simd_lane_id [[thread_index_in_simdgroup]], + uint simd_group_id [[simdgroup_index_in_threadgroup]], + uint3 tid [[threadgroup_position_in_grid]], + uint3 lid [[thread_position_in_threadgroup]]) { + // Pacifying compiler + (void)lid; + + const int tid_y = ((tid.y) << params->swizzle_log) + + ((tid.x) & ((1 << params->swizzle_log) - 1)); + const int tid_x = (tid.x) >> params->swizzle_log; + + if (params->tiles_n <= tid_x || params->tiles_m <= tid_y) { + return; + } + + threadgroup_barrier(mem_flags::mem_none); + + // Find block in A, B, C + const int c_row = tid_y * BM; + const int c_col = tid_x * BN; + const size_t c_row_long = size_t(c_row); + const size_t c_col_long = size_t(c_col); + + A += transpose_a ? c_row_long : c_row_long * params->lda; + B += transpose_b ? c_col_long * params->ldb : c_col_long; + D += c_row_long * params->ldd + c_col_long; + + // Prepare threadgroup loading operations + thread loader_a_t loader_a(A, params->lda, As, simd_group_id, simd_lane_id); + thread loader_b_t loader_b(B, params->ldb, Bs, simd_group_id, simd_lane_id); + + // Prepare threadgroup mma operation + thread mma_t mma_op(simd_group_id, simd_lane_id); + + int gemm_k_iterations = params->gemm_k_iterations_aligned; + + /////////////////////////////////////////////////////////////////////////////// + // MNK aligned loop + if (MN_aligned) { + for (int k = 0; k < gemm_k_iterations; k++) { + threadgroup_barrier(mem_flags::mem_threadgroup); + // Load elements into threadgroup + loader_a.load_unsafe(); + loader_b.load_unsafe(); + + threadgroup_barrier(mem_flags::mem_threadgroup); + + // Multiply and accumulate threadgroup elements + mma_op.mma(As, Bs); + + // Prepare for next iteration + loader_a.next(); + loader_b.next(); + } + + threadgroup_barrier(mem_flags::mem_none); + + // Loop tail + if (!K_aligned) { + int lbk = params->K - params->gemm_k_iterations_aligned * BK; + short2 tile_dims_A = transpose_a ? short2(BM, lbk) : short2(lbk, BM); + short2 tile_dims_B = transpose_b ? short2(lbk, BN) : short2(BN, lbk); + + loader_a.load_safe(tile_dims_A); + loader_b.load_safe(tile_dims_B); + + threadgroup_barrier(mem_flags::mem_threadgroup); + + mma_op.mma(As, Bs); + } + + // Store results to device memory + mma_op.store_result(D, params->ldd); + return; + + } + /////////////////////////////////////////////////////////////////////////////// + // MN unaligned loop + else { // Loop over K - unaligned case + short tgp_bm = min(BM, params->M - c_row); + short tgp_bn = min(BN, params->N - c_col); + short leftover_bk = params->K - params->gemm_k_iterations_aligned * BK; + + if (tgp_bm == BM && tgp_bn == BN) { + gemm_loop( + As, + Bs, + gemm_k_iterations, + loader_a, + loader_b, + mma_op, + tgp_bm, + tgp_bn, + leftover_bk); + + mma_op.store_result(D, params->ldd); + return; + + } else if (tgp_bn == BN) { + gemm_loop( + As, + Bs, + gemm_k_iterations, + loader_a, + loader_b, + mma_op, + tgp_bm, + tgp_bn, + leftover_bk); + + mma_op.store_result_safe(D, params->ldd, short2(tgp_bn, tgp_bm)); + return; + + } else if (tgp_bm == BM) { + gemm_loop( + As, + Bs, + gemm_k_iterations, + loader_a, + loader_b, + mma_op, + tgp_bm, + tgp_bn, + leftover_bk); + + mma_op.store_result_safe(D, params->ldd, short2(tgp_bn, tgp_bm)); + return; + + } else { + gemm_loop( + As, + Bs, + gemm_k_iterations, + loader_a, + loader_b, + mma_op, + tgp_bm, + tgp_bn, + leftover_bk); + + mma_op.store_result_safe(D, params->ldd, short2(tgp_bn, tgp_bm)); + return; + } + } + } +}; + +} // namespace steel +} // namespace mlx +// ==== quantized.h +// Copyright © 2023-2024 Apple Inc. + +#include +#include + +constant bool align_M [[function_constant(200)]]; +constant bool align_N [[function_constant(201)]]; +constant bool align_K [[function_constant(202)]]; + +using namespace metal; + +#define MLX_MTL_CONST static constant constexpr const + +MLX_MTL_CONST int SIMD_SIZE = 32; +MLX_MTL_CONST int QUAD_SIZE = 4; + +template +inline constexpr short get_pack_factor() { + return (bits == 3 || bits == 5) ? 8 : (bits == 6 ? 4 : wsize / bits); +} + +template +inline constexpr short get_bytes_per_pack() { + constexpr int power_of_2_bits = (bits & (bits - 1)) == 0; + return power_of_2_bits ? (wsize / 8) : (bits == 5 ? 5 : 3); +} + +template +inline U load_vector(const device T* x, thread U* x_thread) { + static_assert( + bits == 1 || bits == 2 || bits == 3 || bits == 4 || bits == 5 || + bits == 6 || bits == 8, + "Template undefined for bits not in {1, 2, 3, 4, 5, 6, 8}"); + + U sum = 0; + + if (bits == 1) { + for (int i = 0; i < values_per_thread; i += 8) { + sum += x[i] + x[i + 1] + x[i + 2] + x[i + 3] + x[i + 4] + x[i + 5] + + x[i + 6] + x[i + 7]; + x_thread[i] = x[i]; + x_thread[i + 1] = x[i + 1]; + x_thread[i + 2] = x[i + 2]; + x_thread[i + 3] = x[i + 3]; + x_thread[i + 4] = x[i + 4]; + x_thread[i + 5] = x[i + 5]; + x_thread[i + 6] = x[i + 6]; + x_thread[i + 7] = x[i + 7]; + } + } + + else if (bits == 2) { + for (int i = 0; i < values_per_thread; i += 4) { + sum += U(x[i]) + U(x[i + 1]) + U(x[i + 2]) + U(x[i + 3]); + x_thread[i] = x[i]; + x_thread[i + 1] = x[i + 1] / 4.0f; + x_thread[i + 2] = x[i + 2] / 16.0f; + x_thread[i + 3] = x[i + 3] / 64.0f; + } + } + + else if (bits == 3) { + for (int i = 0; i < values_per_thread; i += 8) { + sum += U(x[i]) + U(x[i + 1]) + U(x[i + 2]) + U(x[i + 3]) + U(x[i + 4]) + + U(x[i + 5]) + U(x[i + 6]) + U(x[i + 7]); + x_thread[i] = x[i]; + x_thread[i + 1] = x[i + 1] / 8.0f; + x_thread[i + 2] = x[i + 2] / 64.0f; + x_thread[i + 3] = x[i + 3] / 2.0f; + x_thread[i + 4] = x[i + 4] / 16.0f; + x_thread[i + 5] = x[i + 5] / 128.0f; + x_thread[i + 6] = x[i + 6] / 4.0f; + x_thread[i + 7] = x[i + 7] / 32.0f; + } + } + + else if (bits == 4) { + for (int i = 0; i < values_per_thread; i += 4) { + sum += U(x[i]) + U(x[i + 1]) + U(x[i + 2]) + U(x[i + 3]); + x_thread[i] = x[i]; + x_thread[i + 1] = x[i + 1] / 16.0f; + x_thread[i + 2] = x[i + 2] / 256.0f; + x_thread[i + 3] = x[i + 3] / 4096.0f; + } + } + + else if (bits == 5) { + for (int i = 0; i < values_per_thread; i += 8) { + sum += U(x[i]) + U(x[i + 1]) + U(x[i + 2]) + U(x[i + 3]) + U(x[i + 4]) + + U(x[i + 5]) + U(x[i + 6]) + U(x[i + 7]); + x_thread[i] = x[i]; + x_thread[i + 1] = x[i + 1] / 32.0f; + x_thread[i + 2] = x[i + 2] / 4.0f; + x_thread[i + 3] = x[i + 3] / 128.0f; + x_thread[i + 4] = x[i + 4] / 16.0f; + x_thread[i + 5] = x[i + 5] / 2.0f; + x_thread[i + 6] = x[i + 6] / 64.0f; + x_thread[i + 7] = x[i + 7] / 8.0f; + } + } + + else if (bits == 6) { + for (int i = 0; i < values_per_thread; i += 4) { + sum += U(x[i]) + U(x[i + 1]) + U(x[i + 2]) + U(x[i + 3]); + x_thread[i] = x[i]; + x_thread[i + 1] = x[i + 1] / 64.0f; + x_thread[i + 2] = x[i + 2] / 16.0f; + x_thread[i + 3] = x[i + 3] / 4.0f; + } + } + + else if (bits == 8) { + for (int i = 0; i < values_per_thread; i++) { + sum += x[i]; + x_thread[i] = x[i]; + } + } + + return sum; +} + +template +inline U load_vector_safe(const device T* x, thread U* x_thread, int N) { + static_assert( + bits == 1 || bits == 2 || bits == 3 || bits == 4 || bits == 5 || + bits == 6 || bits == 8, + "Template undefined for bits not in {1, 2, 3, 4, 5, 6, 8}"); + + U sum = 0; + + if (bits == 1) { + for (int i = 0; i < N; i += 8) { + sum += x[i] + x[i + 1] + x[i + 2] + x[i + 3] + x[i + 4] + x[i + 5] + + x[i + 6] + x[i + 7]; + x_thread[i] = x[i]; + x_thread[i + 1] = x[i + 1]; + x_thread[i + 2] = x[i + 2]; + x_thread[i + 3] = x[i + 3]; + x_thread[i + 4] = x[i + 4]; + x_thread[i + 5] = x[i + 5]; + x_thread[i + 6] = x[i + 6]; + x_thread[i + 7] = x[i + 7]; + } + } + + else if (bits == 2) { + for (int i = 0; i < N; i += 4) { + sum += U(x[i]) + U(x[i + 1]) + U(x[i + 2]) + U(x[i + 3]); + x_thread[i] = x[i]; + x_thread[i + 1] = x[i + 1] / 4.0f; + x_thread[i + 2] = x[i + 2] / 16.0f; + x_thread[i + 3] = x[i + 3] / 64.0f; + } + } + + else if (bits == 3) { + for (int i = 0; i < N; i += 8) { + sum += U(x[i]) + U(x[i + 1]) + U(x[i + 2]) + U(x[i + 3]) + U(x[i + 4]) + + U(x[i + 5]) + U(x[i + 6]) + U(x[i + 7]); + + x_thread[i] = x[i]; + x_thread[i + 1] = x[i + 1] / 8.0f; + x_thread[i + 2] = x[i + 2] / 64.0f; + x_thread[i + 3] = x[i + 3] / 2.0f; + x_thread[i + 4] = x[i + 4] / 16.0f; + x_thread[i + 5] = x[i + 5] / 128.0f; + x_thread[i + 6] = x[i + 6] / 4.0f; + x_thread[i + 7] = x[i + 7] / 32.0f; + } + } + + else if (bits == 4) { + for (int i = 0; i < N; i += 4) { + sum += U(x[i]) + U(x[i + 1]) + U(x[i + 2]) + U(x[i + 3]); + x_thread[i] = x[i]; + x_thread[i + 1] = x[i + 1] / 16.0f; + x_thread[i + 2] = x[i + 2] / 256.0f; + x_thread[i + 3] = x[i + 3] / 4096.0f; + } + } + + else if (bits == 5) { + for (int i = 0; i < N; i += 8) { + sum += U(x[i]) + U(x[i + 1]) + U(x[i + 2]) + U(x[i + 3]) + U(x[i + 4]) + + U(x[i + 5]) + U(x[i + 6]) + U(x[i + 7]); + x_thread[i] = x[i]; + x_thread[i + 1] = x[i + 1] / 32.0f; + x_thread[i + 2] = x[i + 2] / 4.0f; + x_thread[i + 3] = x[i + 3] / 128.0f; + x_thread[i + 4] = x[i + 4] / 16.0f; + x_thread[i + 5] = x[i + 5] / 2.0f; + x_thread[i + 6] = x[i + 6] / 64.0f; + x_thread[i + 7] = x[i + 7] / 8.0f; + } + } + + else if (bits == 6) { + for (int i = 0; i < N; i += 4) { + sum += U(x[i]) + U(x[i + 1]) + U(x[i + 2]) + U(x[i + 3]); + x_thread[i] = x[i]; + x_thread[i + 1] = x[i + 1] / 64.0f; + x_thread[i + 2] = x[i + 2] / 16.0f; + x_thread[i + 3] = x[i + 3] / 4.0f; + } + } + + else if (bits == 8) { + for (int i = 0; i < N; i++) { + sum += x[i]; + x_thread[i] = x[i]; + } + } + + for (int i = N; i < values_per_thread; i++) { + x_thread[i] = 0; + } + + return sum; +} + +template +inline U qdot( + const device uint8_t* w, + const thread U* x_thread, + U scale, + U bias, + U sum) { + static_assert( + bits == 1 || bits == 2 || bits == 3 || bits == 4 || bits == 5 || + bits == 6 || bits == 8, + "Template undefined for bits not in {1, 2, 3, 4, 5, 6, 8}"); + + U accum = 0; + + if (bits == 1) { + for (int i = 0; i < (values_per_thread / 8); i++) { + uint8_t wb = w[i]; + accum += select(U(0), x_thread[8 * i], bool(wb & 0x01)); + accum += select(U(0), x_thread[8 * i + 1], bool(wb & 0x02)); + accum += select(U(0), x_thread[8 * i + 2], bool(wb & 0x04)); + accum += select(U(0), x_thread[8 * i + 3], bool(wb & 0x08)); + accum += select(U(0), x_thread[8 * i + 4], bool(wb & 0x10)); + accum += select(U(0), x_thread[8 * i + 5], bool(wb & 0x20)); + accum += select(U(0), x_thread[8 * i + 6], bool(wb & 0x40)); + accum += select(U(0), x_thread[8 * i + 7], bool(wb & 0x80)); + } + } + + else if (bits == 2) { + for (int i = 0; i < (values_per_thread / 4); i++) { + accum += + (x_thread[4 * i] * (w[i] & 0x03) + + x_thread[4 * i + 1] * (w[i] & 0x0c) + + x_thread[4 * i + 2] * (w[i] & 0x30) + + x_thread[4 * i + 3] * (w[i] & 0xc0)); + } + } + + else if (bits == 3) { + for (int i = 0; i < (values_per_thread / 8); i++) { + x_thread += 8 * i; + w += 3 * i; + + accum += (w[0] & 0x07) * x_thread[0]; + accum += (w[0] & 0x38) * x_thread[1]; + accum += (w[0] & 0xc0) * x_thread[2]; + accum += (w[1] & 0x01) * (x_thread[2] * 256.0f); + + accum += (w[1] & 0x0e) * x_thread[3]; + accum += (w[1] & 0x70) * x_thread[4]; + accum += (w[1] & 0x80) * x_thread[5]; + accum += (w[2] & 0x03) * (x_thread[5] * 256.0f); + + accum += (w[2] & 0x1c) * x_thread[6]; + accum += (w[2] & 0xe0) * x_thread[7]; + } + } + + else if (bits == 4) { + const device uint16_t* ws = (const device uint16_t*)w; + for (int i = 0; i < (values_per_thread / 4); i++) { + accum += + (x_thread[4 * i] * (ws[i] & 0x000f) + + x_thread[4 * i + 1] * (ws[i] & 0x00f0) + + x_thread[4 * i + 2] * (ws[i] & 0x0f00) + + x_thread[4 * i + 3] * (ws[i] & 0xf000)); + } + } + + else if (bits == 5) { + for (int i = 0; i < (values_per_thread / 8); i++) { + x_thread += 8 * i; + w += 5 * i; + + accum += (w[0] & 0x1f) * x_thread[0]; + accum += (w[0] & 0xe0) * x_thread[1]; + accum += (w[1] & 0x3) * (x_thread[1] * 256.0f); + accum += (w[1] & 0x7c) * x_thread[2]; + accum += (w[1] & 0x80) * x_thread[3]; + accum += (w[2] & 0xf) * (x_thread[3] * 256.0f); + accum += (w[2] & 0xf0) * x_thread[4]; + accum += (w[3] & 0x1) * (x_thread[4] * 256.0f); + accum += (w[3] & 0x3e) * x_thread[5]; + accum += (w[3] & 0xc0) * x_thread[6]; + accum += (w[4] & 0x7) * (x_thread[6] * 256.0f); + accum += (w[4] & 0xf8) * x_thread[7]; + } + } + + else if (bits == 6) { + for (int i = 0; i < (values_per_thread / 4); i++) { + x_thread += 4 * i; + w += 3 * i; + + accum += (w[0] & 0x3f) * x_thread[0]; + + accum += (w[0] & 0xc0) * x_thread[1]; + accum += (w[1] & 0x0f) * (x_thread[1] * 256.0f); + + accum += (w[1] & 0xf0) * x_thread[2]; + accum += (w[2] & 0x03) * (x_thread[2] * 256.0f); + + accum += (w[2] & 0xfc) * x_thread[3]; + } + } + + else if (bits == 8) { + for (int i = 0; i < values_per_thread; i++) { + accum += x_thread[i] * w[i]; + } + } + + return scale * accum + sum * bias; +} + +template +inline U qdot_safe( + const device uint8_t* w, + const thread U* x_thread, + U scale, + U bias, + U sum, + int N) { + static_assert( + bits == 1 || bits == 2 || bits == 3 || bits == 4 || bits == 5 || + bits == 6 || bits == 8, + "Template undefined for bits not in {1, 2, 3, 4, 5, 6, 8}"); + + U accum = 0; + + if (bits == 1) { + for (int i = 0; i < (N / 8); i++) { + uint8_t wb = w[i]; + accum += select(U(0), x_thread[8 * i], bool(wb & 0x01)); + accum += select(U(0), x_thread[8 * i + 1], bool(wb & 0x02)); + accum += select(U(0), x_thread[8 * i + 2], bool(wb & 0x04)); + accum += select(U(0), x_thread[8 * i + 3], bool(wb & 0x08)); + accum += select(U(0), x_thread[8 * i + 4], bool(wb & 0x10)); + accum += select(U(0), x_thread[8 * i + 5], bool(wb & 0x20)); + accum += select(U(0), x_thread[8 * i + 6], bool(wb & 0x40)); + accum += select(U(0), x_thread[8 * i + 7], bool(wb & 0x80)); + } + } + + else if (bits == 2) { + for (int i = 0; i < (N / 4); i++) { + accum += + (x_thread[4 * i] * (w[i] & 0x03) + + x_thread[4 * i + 1] * (w[i] & 0x0c) + + x_thread[4 * i + 2] * (w[i] & 0x30) + + x_thread[4 * i + 3] * (w[i] & 0xc0)); + } + } + + else if (bits == 3) { + for (int i = 0; i < (N / 8); i++) { + x_thread += 8 * i; + w += 3 * i; + + accum += (w[0] & 0x07) * x_thread[0]; + accum += (w[0] & 0x38) * x_thread[1]; + accum += (w[0] & 0xc0) * x_thread[2]; + accum += (w[1] & 0x01) * (x_thread[2] * 256.0f); + + accum += (w[1] & 0x0e) * x_thread[3]; + accum += (w[1] & 0x70) * x_thread[4]; + accum += (w[1] & 0x80) * x_thread[5]; + accum += (w[2] & 0x03) * (x_thread[5] * 256.0f); + + accum += (w[2] & 0x1c) * x_thread[6]; + accum += (w[2] & 0xe0) * x_thread[7]; + } + } + + else if (bits == 4) { + const device uint16_t* ws = (const device uint16_t*)w; + for (int i = 0; i < (N / 4); i++) { + accum += + (x_thread[4 * i] * (ws[i] & 0x000f) + + x_thread[4 * i + 1] * (ws[i] & 0x00f0) + + x_thread[4 * i + 2] * (ws[i] & 0x0f00) + + x_thread[4 * i + 3] * (ws[i] & 0xf000)); + } + } + + else if (bits == 5) { + for (int i = 0; i < (N / 8); i++) { + x_thread += 8 * i; + w += 5 * i; + + accum += (w[0] & 0x1f) * x_thread[0]; + accum += (w[0] & 0xe0) * x_thread[1]; + accum += (w[1] & 0x3) * (x_thread[1] * 256.0f); + accum += (w[1] & 0x7c) * x_thread[2]; + accum += (w[1] & 0x80) * x_thread[3]; + accum += (w[2] & 0xf) * (x_thread[3] * 256.0f); + accum += (w[2] & 0xf0) * x_thread[4]; + accum += (w[3] & 0x1) * (x_thread[4] * 256.0f); + accum += (w[3] & 0x3e) * x_thread[5]; + accum += (w[3] & 0xc0) * x_thread[6]; + accum += (w[4] & 0x7) * (x_thread[6] * 256.0f); + accum += (w[4] & 0xf8) * x_thread[7]; + } + } + + else if (bits == 6) { + for (int i = 0; i < (N / 4); i++) { + x_thread += 4 * i; + w += 3 * i; + + accum += (w[0] & 0x3f) * x_thread[0]; + + accum += (w[0] & 0xc0) * x_thread[1]; + accum += (w[1] & 0x0f) * (x_thread[1] * 256.0f); + + accum += (w[1] & 0xf0) * x_thread[2]; + accum += (w[2] & 0x03) * (x_thread[2] * 256.0f); + + accum += (w[2] & 0xfc) * x_thread[3]; + } + } + + else if (bits == 8) { + for (int i = 0; i < N; i++) { + accum += x_thread[i] * w[i]; + } + } + + return scale * accum + sum * bias; +} + +template +inline void +qouter(const thread uint8_t* w, U x, U scale, U bias, thread U* result) { + static_assert( + bits == 1 || bits == 2 || bits == 3 || bits == 4 || bits == 5 || + bits == 6 || bits == 8, + "Template undefined for bits not in {1, 2, 3, 4, 5, 6, 8}"); + + if (bits == 1) { + for (int i = 0; i < (values_per_thread / 8); i++) { + uint8_t wb = w[i]; + result[8 * i] += x * (select(U(0), scale, bool(wb & 0x01)) + bias); + result[8 * i + 1] += x * (select(U(0), scale, bool(wb & 0x02)) + bias); + result[8 * i + 2] += x * (select(U(0), scale, bool(wb & 0x04)) + bias); + result[8 * i + 3] += x * (select(U(0), scale, bool(wb & 0x08)) + bias); + result[8 * i + 4] += x * (select(U(0), scale, bool(wb & 0x10)) + bias); + result[8 * i + 5] += x * (select(U(0), scale, bool(wb & 0x20)) + bias); + result[8 * i + 6] += x * (select(U(0), scale, bool(wb & 0x40)) + bias); + result[8 * i + 7] += x * (select(U(0), scale, bool(wb & 0x80)) + bias); + } + } + + else if (bits == 2) { + U s[4] = {scale, scale / 4.0f, scale / 16.0f, scale / 64.0f}; + for (int i = 0; i < (values_per_thread / 4); i++) { + result[4 * i] += x * (s[0] * (w[i] & 0x03) + bias); + result[4 * i + 1] += x * (s[1] * (w[i] & 0x0c) + bias); + result[4 * i + 2] += x * (s[2] * (w[i] & 0x30) + bias); + result[4 * i + 3] += x * (s[3] * (w[i] & 0xc0) + bias); + } + } + + else if (bits == 3) { + for (int i = 0; i < (values_per_thread / 8); i++) { + uint8_t w0 = w[3 * i]; + uint8_t w1 = w[3 * i + 1]; + uint8_t w2 = w[3 * i + 2]; + + result[8 * i] += x * ((w0 & 0x7) * scale + bias); + result[8 * i + 1] += x * (((w0 & 0x38) >> 3) * scale + bias); + result[8 * i + 2] += + x * ((((w0 & 0xc0) >> 6) + ((w1 & 0x1) << 2)) * scale + bias); + result[8 * i + 3] += x * (((w1 & 0xe) >> 1) * scale + bias); + result[8 * i + 4] += x * (((w1 & 0x70) >> 4) * scale + bias); + result[8 * i + 5] += + x * ((((w1 & 0x80) >> 7) + ((w2 & 0x3) << 1)) * scale + bias); + result[8 * i + 6] += x * (((w2 & 0x1c) >> 2) * scale + bias); + result[8 * i + 7] += x * (((w2 & 0xe0) >> 5) * scale + bias); + } + } + + else if (bits == 4) { + U s[2] = {scale, scale / 16.0f}; + for (int i = 0; i < (values_per_thread / 2); i++) { + result[2 * i] += x * (s[0] * (w[i] & 0x0f) + bias); + result[2 * i + 1] += x * (s[1] * (w[i] & 0xf0) + bias); + } + } + + else if (bits == 5) { + for (int i = 0; i < (values_per_thread / 8); i++) { + uint8_t w0 = w[5 * i]; + uint8_t w1 = w[5 * i + 1]; + uint8_t w2 = w[5 * i + 2]; + uint8_t w3 = w[5 * i + 3]; + uint8_t w4 = w[5 * i + 4]; + result[8 * i] += x * ((w0 & 0x1f) * scale + bias); + result[8 * i + 1] += + x * ((((w0 & 0xe0) >> 5) + ((w1 & 0x3) << 3)) * scale + bias); + result[8 * i + 2] += x * (((w1 & 0x7c) >> 2) * scale + bias); + result[8 * i + 3] += + x * ((((w1 & 0x80) >> 7) + ((w2 & 0xf) << 1)) * scale + bias); + result[8 * i + 4] += + x * ((((w2 & 0xf0) >> 4) + ((w3 & 0x1) << 4)) * scale + bias); + result[8 * i + 5] += x * (((w3 & 0x3e) >> 1) * scale + bias); + result[8 * i + 6] += + x * ((((w3 & 0xc0) >> 6) + ((w4 & 0x7) << 2)) * scale + bias); + result[8 * i + 7] += x * (((w4 & 0xf8) >> 3) * scale + bias); + } + } + + else if (bits == 6) { + for (int i = 0; i < (values_per_thread / 4); i++) { + uint8_t w0 = w[3 * i]; + uint8_t w1 = w[3 * i + 1]; + uint8_t w2 = w[3 * i + 2]; + + result[4 * i] += x * ((w0 & 0x3f) * scale + bias); + result[4 * i + 1] += + x * ((((w0 >> 6) & 0x03) + ((w1 & 0x0f) << 2)) * scale + bias); + result[4 * i + 2] += + x * ((((w1 >> 4) & 0x0f) + ((w2 & 0x03) << 4)) * scale + bias); + result[4 * i + 3] += x * (((w2 >> 2) & 0x3f) * scale + bias); + } + } + + else if (bits == 8) { + for (int i = 0; i < values_per_thread; i++) { + result[i] += x * (scale * w[i] + bias); + } + } +} + +// Decode one quantized block (scale * q + bias) into w_local. W (the output +// pointer type) serves the threadgroup block loader or a thread-local decode. +template +inline void dequantize(const device uint8_t* w, U scale, U bias, W w_local) { + static_assert( + bits == 1 || bits == 2 || bits == 3 || bits == 4 || bits == 5 || + bits == 6 || bits == 8, + "Template undefined for bits not in {1, 2, 3, 4, 5, 6, 8}"); + + const float s = float(scale); + const float b = float(bias); + + if (bits == 1) { + float sc[8] = { + s, + s / 2.0f, + s / 4.0f, + s / 8.0f, + s / 16.0f, + s / 32.0f, + s / 64.0f, + s / 128.0f}; + for (int i = 0; i < (N / 8); i++) { + w_local[8 * i] = static_cast(sc[0] * (w[i] & 0x01) + b); + w_local[8 * i + 1] = static_cast(sc[1] * (w[i] & 0x02) + b); + w_local[8 * i + 2] = static_cast(sc[2] * (w[i] & 0x04) + b); + w_local[8 * i + 3] = static_cast(sc[3] * (w[i] & 0x08) + b); + w_local[8 * i + 4] = static_cast(sc[4] * (w[i] & 0x10) + b); + w_local[8 * i + 5] = static_cast(sc[5] * (w[i] & 0x20) + b); + w_local[8 * i + 6] = static_cast(sc[6] * (w[i] & 0x40) + b); + w_local[8 * i + 7] = static_cast(sc[7] * (w[i] & 0x80) + b); + } + } + + else if (bits == 2) { + float sc[4] = {s, s / 4.0f, s / 16.0f, s / 64.0f}; + for (int i = 0; i < (N / 4); i++) { + w_local[4 * i] = static_cast(sc[0] * (w[i] & 0x03) + b); + w_local[4 * i + 1] = static_cast(sc[1] * (w[i] & 0x0c) + b); + w_local[4 * i + 2] = static_cast(sc[2] * (w[i] & 0x30) + b); + w_local[4 * i + 3] = static_cast(sc[3] * (w[i] & 0xc0) + b); + } + } + + else if (bits == 3) { + for (int i = 0; i < (N / 8); i++) { + w_local += 8 * i; + w += 3 * i; + + w_local[0] = static_cast((w[0] & 0x7) * s + b); + w_local[1] = static_cast(((w[0] & 0x38) >> 3) * s + b); + w_local[2] = + static_cast((((w[0] & 0xc0) >> 6) + ((w[1] & 0x1) << 2)) * s + b); + w_local[3] = static_cast(((w[1] & 0xe) >> 1) * s + b); + w_local[4] = static_cast(((w[1] & 0x70) >> 4) * s + b); + w_local[5] = + static_cast((((w[1] & 0x80) >> 7) + ((w[2] & 0x3) << 1)) * s + b); + w_local[6] = static_cast(((w[2] & 0x1c) >> 2) * s + b); + w_local[7] = static_cast(((w[2] & 0xe0) >> 5) * s + b); + } + } + + else if (bits == 4) { + float sc[2] = {s, s / 16.0f}; + for (int i = 0; i < (N / 2); i++) { + w_local[2 * i] = static_cast(sc[0] * (w[i] & 0x0f) + b); + w_local[2 * i + 1] = static_cast(sc[1] * (w[i] & 0xf0) + b); + } + } + + else if (bits == 5) { + for (int i = 0; i < (N / 8); i++) { + w_local += 8 * i; + w += 5 * i; + + w_local[0] = static_cast((w[0] & 0x1f) * s + b); + w_local[1] = + static_cast((((w[0] & 0xe0) >> 5) + ((w[1] & 0x3) << 3)) * s + b); + w_local[2] = static_cast(((w[1] & 0x7c) >> 2) * s + b); + w_local[3] = + static_cast((((w[1] & 0x80) >> 7) + ((w[2] & 0xf) << 1)) * s + b); + w_local[4] = + static_cast((((w[2] & 0xf0) >> 4) + ((w[3] & 0x1) << 4)) * s + b); + w_local[5] = static_cast(((w[3] & 0x3e) >> 1) * s + b); + w_local[6] = + static_cast((((w[3] & 0xc0) >> 6) + ((w[4] & 0x7) << 2)) * s + b); + w_local[7] = static_cast(((w[4] & 0xf8) >> 3) * s + b); + } + } + + else if (bits == 6) { + for (int i = 0; i < (N / 4); i++) { + w_local += 4 * i; + w += 3 * i; + w_local[0] = static_cast((w[0] & 0x3f) * s + b); + w_local[1] = + static_cast((((w[0] >> 6) & 0x03) + ((w[1] & 0x0f) << 2)) * s + b); + w_local[2] = + static_cast((((w[1] >> 4) & 0x0f) + ((w[2] & 0x03) << 4)) * s + b); + w_local[3] = static_cast(((w[2] >> 2) & 0x3f) * s + b); + } + } + + else if (bits == 8) { + for (int i = 0; i < N; i++) { + w_local[i] = static_cast(s * w[i] + b); + } + } +} + +template < + typename T, + short BROWS, + short BCOLS, + short dst_ld, + short reduction_dim, + short tgp_size, + short group_size, + short bits> +struct QuantizedBlockLoader { + static_assert( + BCOLS <= group_size, + "The group size should be larger than the columns"); + static_assert( + group_size % BCOLS == 0, + "The group size should be divisible by the columns"); + static_assert( + bits == 1 || bits == 2 || bits == 3 || bits == 4 || bits == 5 || + bits == 6 || bits == 8, + "Template undefined for bits not in {1, 2, 3, 4, 5, 6, 8}"); + + MLX_MTL_CONST short pack_factor = get_pack_factor(); + MLX_MTL_CONST short bytes_per_pack = get_bytes_per_pack(); + MLX_MTL_CONST short BCOLS_PACKED = BCOLS / pack_factor; + MLX_MTL_CONST short n_reads = + (BCOLS_PACKED * BROWS < tgp_size) ? 1 : (BCOLS_PACKED * BROWS) / tgp_size; + MLX_MTL_CONST short group_steps = group_size / BCOLS; + + MLX_MTL_CONST bool partial_cols = group_size % BCOLS != 0; + + static_assert( + group_size % (n_reads * pack_factor) == 0, + "The group size must be a multiple of the columns read per thread."); + + const int src_ld; + const int tile_stride; + short group_step_cnt; + const int group_stride; + + const short thread_idx; + const short bi; + const short bj; + + threadgroup T* dst; + const device uint8_t* src; + const device T* scales; + const device T* biases; + + QuantizedBlockLoader( + const device uint8_t* src_, + const device T* scales_, + const device T* biases_, + const int src_ld_, + threadgroup T* dst_, + ushort simd_group_id [[simdgroup_index_in_threadgroup]], + ushort simd_lane_id [[thread_index_in_simdgroup]]) thread + : src_ld(src_ld_), + tile_stride( + reduction_dim ? BCOLS_PACKED* bytes_per_pack + : BROWS * src_ld * bytes_per_pack / pack_factor), + group_step_cnt(0), + group_stride(BROWS* src_ld / group_size), + thread_idx(simd_group_id * 32 + simd_lane_id), + bi(n_reads* thread_idx / BCOLS_PACKED), + bj((n_reads * thread_idx) % BCOLS_PACKED), + dst(dst_ + bi * dst_ld + bj * pack_factor), + src(src_ + bi * src_ld * bytes_per_pack / pack_factor + + bj * bytes_per_pack), + scales(scales_ + bi * src_ld / group_size), + biases(biases_ + bi * src_ld / group_size) {} + + void load_unsafe() const thread { + if (BCOLS_PACKED * BROWS < tgp_size && bi >= BROWS) { + return; + } + + T scale = *scales; + T bias = *biases; + for (int i = 0; i < n_reads; i++) { + dequantize( + src + i * bytes_per_pack, scale, bias, dst + i * pack_factor); + } + } + + void load_safe(short2 src_tile_dim) const thread { + if (BCOLS_PACKED * BROWS < tgp_size && bi >= BROWS) { + return; + } + + if (bi >= src_tile_dim.y) { + for (int i = 0; i < n_reads * pack_factor; i++) { + dst[i] = T(0); + } + return; + } + + T scale = *scales; + T bias = *biases; + for (int i = 0; i < n_reads; i++) { + dequantize( + (device uint8_t*)(src + i * bytes_per_pack), + scale, + bias, + dst + i * pack_factor); + } + } + + void next() thread { + src += tile_stride; + if (reduction_dim == 1) { + if (group_steps > 1) { + group_step_cnt++; + if (group_step_cnt == group_steps) { + group_step_cnt = 0; + scales++; + biases++; + } + } else { + scales++; + biases++; + } + } else { + scales += group_stride; + biases += group_stride; + } + } +}; + +template +METAL_FUNC void qmv_quad_impl( + const device uint32_t* w, + const device T* scales, + const device T* biases, + const device T* x, + device T* y, + constant int& in_vec_size, + const constant int& out_vec_size, + uint3 tid [[threadgroup_position_in_grid]], + uint quad_gid [[quadgroup_index_in_threadgroup]], + uint quad_lid [[thread_index_in_quadgroup]]) { + constexpr int quads_per_simd = SIMD_SIZE / QUAD_SIZE; + constexpr int pack_factor = 32 / bits; + constexpr int values_per_thread = D / QUAD_SIZE; + constexpr int packs_per_thread = values_per_thread / pack_factor; + constexpr int scale_step_per_thread = group_size / values_per_thread; + constexpr int results_per_quadgroup = 8; + + typedef float U; + + thread U x_thread[values_per_thread]; + thread U result[results_per_quadgroup] = {0}; + + // Adjust positions + const int in_vec_size_w = in_vec_size / pack_factor; + const int in_vec_size_g = in_vec_size / group_size; + const int out_row = tid.y * quads_per_simd * results_per_quadgroup + quad_gid; + + w += out_row * in_vec_size_w + quad_lid * packs_per_thread; + scales += out_row * in_vec_size_g + quad_lid / scale_step_per_thread; + biases += out_row * in_vec_size_g + quad_lid / scale_step_per_thread; + x += tid.x * in_vec_size + quad_lid * values_per_thread; + y += tid.x * out_vec_size + out_row; + + U sum = load_vector(x, x_thread); + + for (int row = 0; row < results_per_quadgroup; row++) { + auto wl = (const device uint8_t*)(w + row * in_vec_size_w * quads_per_simd); + const device T* sl = scales + row * in_vec_size_g * quads_per_simd; + const device T* bl = biases + row * in_vec_size_g * quads_per_simd; + + U s = sl[0]; + U b = bl[0]; + if (row * quads_per_simd + out_row < out_vec_size) { + result[row] += qdot(wl, x_thread, s, b, sum); + } + } + + for (int row = 0; row < results_per_quadgroup; row++) { + result[row] = quad_sum(result[row]); + if (quad_lid == 0 && row * quads_per_simd + out_row < out_vec_size) { + y[row * quads_per_simd] = static_cast(result[row]); + } + } +} + +template +METAL_FUNC void qmv_fast_impl( + const device uint32_t* w, + const device T* scales, + const device T* biases, + const device T* x, + device T* y, + const constant int& in_vec_size, + const constant int& out_vec_size, + uint3 tid [[threadgroup_position_in_grid]], + uint simd_gid [[simdgroup_index_in_threadgroup]], + uint simd_lid [[thread_index_in_simdgroup]]) { + constexpr int packs_per_thread = + bits <= 2 ? 1 : 2; // 1-bit: 1 pack (vpt=32) for occupancy + constexpr int num_simdgroups = 2; + constexpr int results_per_simdgroup = 4; + constexpr int pack_factor = get_pack_factor(); + constexpr int bytes_per_pack = get_bytes_per_pack(); + constexpr int values_per_thread = pack_factor * packs_per_thread; + constexpr int block_size = values_per_thread * SIMD_SIZE; + constexpr int scale_step_per_thread = group_size / values_per_thread; + + const device uint8_t* ws = (const device uint8_t*)w; + + typedef float U; + + thread U x_thread[values_per_thread]; + thread U result[results_per_simdgroup] = {0}; + + // Adjust positions + const int in_vec_size_w = in_vec_size * bytes_per_pack / pack_factor; + const int in_vec_size_g = in_vec_size / group_size; + const int out_row = tid.y * (num_simdgroups * results_per_simdgroup) + + simd_gid * results_per_simdgroup; + + // With partial rows the output size need not be a multiple of 8. Rows of the + // last SIMD-group that fall past the output reuse the weights of the last + // valid output row, so the reduction loop needs no per-row bounds check, and + // are not stored. + int last_row = results_per_simdgroup - 1; + if constexpr (partial_rows) { + if (out_row >= out_vec_size) { + return; + } + last_row = min(last_row, out_vec_size - 1 - out_row); + } + + ws += out_row * in_vec_size_w + simd_lid * packs_per_thread * bytes_per_pack; + scales += out_row * in_vec_size_g + simd_lid / scale_step_per_thread; + biases += out_row * in_vec_size_g + simd_lid / scale_step_per_thread; + x += tid.x * in_vec_size + simd_lid * values_per_thread; + y += tid.x * out_vec_size + out_row; + + const int aligned_end = (in_vec_size / block_size) * block_size; + + for (int k = 0; k < aligned_end; k += block_size) { + U sum = load_vector(x, x_thread); + + for (int row = 0; row < results_per_simdgroup; row++) { + int src = row; + if constexpr (partial_rows) { + src = min(row, last_row); + } + auto wl = (const device uint8_t*)(ws + src * in_vec_size_w); + const device T* sl = scales + src * in_vec_size_g; + const device T* bl = biases + src * in_vec_size_g; + + U s = sl[0]; + U b = bl[0]; + result[row] += qdot(wl, x_thread, s, b, sum); + } + + ws += block_size * bytes_per_pack / pack_factor; + scales += block_size / group_size; + biases += block_size / group_size; + x += block_size; + } + + // Tail block: handles K that is a multiple of 512 (dispatch gate) but not + // of block_size. Only 1-bit has block_size > 512 (it uses 2048), so for + // >=2-bit this is a no-op. Out-of-bounds lanes skip the qdot call entirely; + // their result[row] stays at 0 and contributes 0 to the simd_sum below. + if (aligned_end < in_vec_size) { + bool in_bounds = + (aligned_end + static_cast(simd_lid) * values_per_thread) < + in_vec_size; + if (in_bounds) { + U sum = load_vector(x, x_thread); + + for (int row = 0; row < results_per_simdgroup; row++) { + int src = row; + if constexpr (partial_rows) { + src = min(row, last_row); + } + auto wl = (const device uint8_t*)(ws + src * in_vec_size_w); + const device T* sl = scales + src * in_vec_size_g; + const device T* bl = biases + src * in_vec_size_g; + + U s = sl[0]; + U b = bl[0]; + result[row] += + qdot(wl, x_thread, s, b, sum); + } + } + } + + for (int row = 0; row < results_per_simdgroup; row++) { + result[row] = simd_sum(result[row]); + if (simd_lid == 0 && row <= last_row) { + y[row] = static_cast(result[row]); + } + } +} + +template +METAL_FUNC void qmv_impl( + const device uint32_t* w, + const device T* scales, + const device T* biases, + const device T* x, + device T* y, + const constant int& in_vec_size, + const constant int& out_vec_size, + uint3 tid [[threadgroup_position_in_grid]], + uint simd_gid [[simdgroup_index_in_threadgroup]], + uint simd_lid [[thread_index_in_simdgroup]]) { + constexpr int num_simdgroups = 2; + constexpr int results_per_simdgroup = 4; + constexpr int packs_per_thread = 1; + constexpr int pack_factor = get_pack_factor(); + constexpr int bytes_per_pack = get_bytes_per_pack(); + + constexpr int values_per_thread = pack_factor * packs_per_thread; + constexpr int block_size = values_per_thread * SIMD_SIZE; + constexpr int scale_step_per_thread = group_size / values_per_thread; + + const device uint8_t* ws = (const device uint8_t*)w; + + typedef float U; + + thread U x_thread[values_per_thread]; + thread U result[results_per_simdgroup] = {0}; + + // Adjust positions + const int in_vec_size_w = in_vec_size * bytes_per_pack / pack_factor; + const int in_vec_size_g = in_vec_size / group_size; + const int out_row = tid.y * (num_simdgroups * results_per_simdgroup) + + simd_gid * results_per_simdgroup; + const int used_out_row = min(out_vec_size - results_per_simdgroup, out_row); + + if (out_row >= out_vec_size) { + return; + } + + // In this case we need to properly guard all our reads because there isn't + // even 1 tile in the matrix + if (out_vec_size < (num_simdgroups * results_per_simdgroup)) { + ws += + out_row * in_vec_size_w + simd_lid * packs_per_thread * bytes_per_pack; + scales += out_row * in_vec_size_g + simd_lid / scale_step_per_thread; + biases += out_row * in_vec_size_g + simd_lid / scale_step_per_thread; + x += tid.x * in_vec_size + simd_lid * values_per_thread; + y += tid.x * out_vec_size + out_row; + + int k = 0; + for (; k < in_vec_size - block_size; k += block_size) { + U sum = load_vector(x, x_thread); + + for (int row = 0; + row < results_per_simdgroup && out_row + row < out_vec_size; + row++) { + auto wl = (const device uint8_t*)(ws + row * in_vec_size_w); + const device T* sl = scales + row * in_vec_size_g; + const device T* bl = biases + row * in_vec_size_g; + + U s = sl[0]; + U b = bl[0]; + result[row] += + qdot(wl, x_thread, s, b, sum); + } + + ws += block_size * bytes_per_pack / pack_factor; + scales += block_size / group_size; + biases += block_size / group_size; + x += block_size; + } + const int remaining = clamp( + static_cast(in_vec_size - k - simd_lid * values_per_thread), + 0, + values_per_thread); + if (remaining > 0) { + U sum = load_vector_safe( + x, x_thread, remaining); + + for (int row = 0; + row < results_per_simdgroup && out_row + row < out_vec_size; + row++) { + auto wl = (const device uint8_t*)(ws + row * in_vec_size_w); + const device T* sl = scales + row * in_vec_size_g; + const device T* bl = biases + row * in_vec_size_g; + + U s = sl[0]; + U b = bl[0]; + result[row] += qdot_safe( + wl, x_thread, s, b, sum, remaining); + } + } + + for (int row = 0; + row < results_per_simdgroup && out_row + row < out_vec_size; + row++) { + result[row] = simd_sum(result[row]); + if (simd_lid == 0) { + y[row] = static_cast(result[row]); + } + } + } + + // In this case the last tile is moved back to redo some output values + else { + ws += used_out_row * in_vec_size_w + + simd_lid * packs_per_thread * bytes_per_pack; + scales += used_out_row * in_vec_size_g + simd_lid / scale_step_per_thread; + biases += used_out_row * in_vec_size_g + simd_lid / scale_step_per_thread; + x += tid.x * in_vec_size + simd_lid * values_per_thread; + y += tid.x * out_vec_size + used_out_row; + + int k = 0; + for (; k < in_vec_size - block_size; k += block_size) { + U sum = load_vector(x, x_thread); + + for (int row = 0; row < results_per_simdgroup; row++) { + auto wl = (const device uint8_t*)(ws + row * in_vec_size_w); + const device T* sl = scales + row * in_vec_size_g; + const device T* bl = biases + row * in_vec_size_g; + + U s = sl[0]; + U b = bl[0]; + result[row] += + qdot(wl, x_thread, s, b, sum); + } + + ws += block_size * bytes_per_pack / pack_factor; + scales += block_size / group_size; + biases += block_size / group_size; + x += block_size; + } + const int remaining = clamp( + static_cast(in_vec_size - k - simd_lid * values_per_thread), + 0, + values_per_thread); + if (remaining > 0) { + U sum = load_vector_safe( + x, x_thread, remaining); + + for (int row = 0; row < results_per_simdgroup; row++) { + auto wl = (const device uint8_t*)(ws + row * in_vec_size_w); + const device T* sl = scales + row * in_vec_size_g; + const device T* bl = biases + row * in_vec_size_g; + + U s = sl[0]; + U b = bl[0]; + result[row] += qdot_safe( + wl, x_thread, s, b, sum, remaining); + } + } + for (int row = 0; row < results_per_simdgroup; row++) { + result[row] = simd_sum(result[row]); + if (simd_lid == 0) { + y[row] = static_cast(result[row]); + } + } + } +} + +// Affine analog of fp_qmv_wide. Weights carry a scale and bias per group, so +// each group is decoded in 8-value sub-chunks (scale * q + bias, registers +// bounded for any group_size) and reused across the vecs_per_tg vectors. +template +METAL_FUNC void qmv_wide_impl( + const device uint32_t* w, + const device T* scales, + const device T* biases, + const device T* x, + device T* y, + const constant int& in_vec_size, + const constant int& out_vec_size, + const constant int& M, + uint3 tid [[threadgroup_position_in_grid]], + uint simd_gid [[simdgroup_index_in_threadgroup]], + uint simd_lid [[thread_index_in_simdgroup]]) { + constexpr int num_simdgroups = 2; + constexpr int results_per_simdgroup = SIMD_SIZE / k_lanes; + constexpr int sub = 8; // values per sub-chunk (== bits bytes, byte-aligned) + + typedef float U; + + const short k_lane = simd_lid % k_lanes; + const short sg_row = simd_lid / k_lanes; + + const int out_row = tid.y * (results_per_simdgroup * num_simdgroups) + + results_per_simdgroup * simd_gid + sg_row; + const int vec0 = tid.x * vecs_per_tg; + + const int row = min(out_row, out_vec_size - 1); + + const int in_vec_size_w = in_vec_size * bits / 8; // bytes per weight row + const int in_vec_size_g = in_vec_size / group_size; + const device uint8_t* wrow = (const device uint8_t*)w + row * in_vec_size_w; + const device T* srow = scales + row * in_vec_size_g; + const device T* brow = biases + row * in_vec_size_g; + + const device T* xv[vecs_per_tg]; + for (int v = 0; v < vecs_per_tg; v++) { + xv[v] = x + min(vec0 + v, M - 1) * in_vec_size; + } + + U result[vecs_per_tg] = {0}; + + // Each lane reduces a strided subset of the row's groups: decode the group in + // 8-value sub-chunks and reuse each chunk across the streamed vectors. + for (int g = k_lane; g < in_vec_size_g; g += k_lanes) { + U scale = srow[g]; + U bias = brow[g]; +#pragma unroll + for (int sc = 0; sc < group_size / sub; sc++) { + const int k0 = g * group_size + sc * sub; + const device uint8_t* wc = wrow + k0 * bits / 8; + U w_dq[sub]; + dequantize(wc, scale, bias, w_dq); +#pragma unroll + for (int v = 0; v < vecs_per_tg; v++) { + const device T* xc = xv[v] + k0; + U acc = 0; +#pragma unroll + for (int i = 0; i < sub; i++) { + acc += static_cast(xc[i]) * w_dq[i]; + } + result[v] += acc; + } + } + } + + // Reduce each vector's partial over its k_lanes with a shuffle ladder: + // simd_sum would mix the results_per_simdgroup rows a simdgroup spans. + for (int v = 0; v < vecs_per_tg; v++) { + if constexpr (k_lanes >= 32) { + result[v] += simd_shuffle_down(result[v], 16); + } + if constexpr (k_lanes >= 16) { + result[v] += simd_shuffle_down(result[v], 8); + } + if constexpr (k_lanes >= 8) { + result[v] += simd_shuffle_down(result[v], 4); + } + if constexpr (k_lanes >= 4) { + result[v] += simd_shuffle_down(result[v], 2); + } + if constexpr (k_lanes >= 2) { + result[v] += simd_shuffle_down(result[v], 1); + } + } + + if (k_lane == 0 && out_row < out_vec_size) { + for (int v = 0; v < vecs_per_tg; v++) { + if (vec0 + v < M) { + y[(vec0 + v) * out_vec_size + out_row] = static_cast(result[v]); + } + } + } +} + +template +METAL_FUNC void qvm_impl( + const device uint32_t* w, + const device T* scales, + const device T* biases, + const device T* x, + device T* y, + const int in_vec_size, + const int out_vec_size, + const int in_vec_stride, + uint3 tid [[threadgroup_position_in_grid]], + uint simd_gid [[simdgroup_index_in_threadgroup]], + uint simd_lid [[thread_index_in_simdgroup]]) { + constexpr int power_of_2_bits = (bits & (bits - 1)) == 0; + constexpr int num_simdgroups = 2; + constexpr int pack_factor = get_pack_factor(); + constexpr int bytes_per_pack = get_bytes_per_pack(); + + constexpr int tn = 32 / pack_factor; + constexpr int block_size = SIMD_SIZE; + + using W_T = + typename ConditionalType::type; + const device W_T* ws = (const device W_T*)w; + + typedef float U; + typedef struct { + W_T wi[tn * bytes_per_pack]; + } vec_w; + + thread vec_w w_local; + thread U result[tn * pack_factor] = {0}; + thread U scale = 1; + thread U bias = 0; + thread U x_local = 0; + + // Adjust positions + const int out_vec_size_w = out_vec_size * bytes_per_pack / pack_factor; + const int out_vec_size_g = out_vec_size / group_size; + int out_col = pack_factor * tn * (tid.y * num_simdgroups + simd_gid); + ws += out_col * bytes_per_pack / pack_factor + simd_lid * out_vec_size_w; + scales += out_col / group_size + simd_lid * out_vec_size_g; + biases += out_col / group_size + simd_lid * out_vec_size_g; + x += tid.x * in_vec_stride + simd_lid; + y += tid.x * out_vec_size + out_col; + + if (out_col >= out_vec_size) { + return; + } + + // Loop over in_vec in blocks of block_size + int remaining = in_vec_size % block_size; + if (remaining == 0) { + for (int i = 0; i < in_vec_size; i += block_size) { + x_local = *x; + scale = *scales; + bias = *biases; + w_local = *((device vec_w*)ws); + qouter( + (thread uint8_t*)&w_local, x_local, scale, bias, result); + + x += block_size; + scales += block_size * out_vec_size_g; + biases += block_size * out_vec_size_g; + ws += block_size * out_vec_size_w; + } + } else { + for (int i = block_size; i < in_vec_size; i += block_size) { + x_local = *x; + scale = *scales; + bias = *biases; + w_local = *((device vec_w*)ws); + + qouter( + (thread uint8_t*)&w_local, x_local, scale, bias, result); + + x += block_size; + scales += block_size * out_vec_size_g; + biases += block_size * out_vec_size_g; + ws += block_size * out_vec_size_w; + } + if (static_cast(simd_lid) < remaining) { + x_local = *x; + scale = *scales; + bias = *biases; + w_local = *((device vec_w*)ws); + } else { + x_local = 0; + scale = 0; + bias = 0; + } + qouter( + (thread uint8_t*)&w_local, x_local, scale, bias, result); + } + +// Accumulate in the simdgroup +#pragma clang loop unroll(full) + for (int k = 0; k < tn * pack_factor; k++) { + result[k] = simd_sum(result[k]); + } + + // Store the result + if (simd_lid == 0) { +#pragma clang loop unroll(full) + for (int k = 0; k < tn * pack_factor; k++) { + y[k] = static_cast(result[k]); + } + } +} + +template < + typename T, + const int group_size, + const int bits, + const bool aligned_N, + typename U = T, + const int BM = 32, + const int BK = 32, + const int BN = 32> +METAL_FUNC void qmm_t_impl( + const device uint32_t* w, + const device T* scales, + const device T* biases, + const device T* x, + device U* y, + threadgroup T* Xs, + threadgroup T* Ws, + const constant int& K, + const constant int& N, + const constant int& M, + const constant int& K_eff, + uint3 tid [[threadgroup_position_in_grid]], + uint lid [[thread_index_in_threadgroup]], + uint simd_gid [[simdgroup_index_in_threadgroup]], + uint simd_lid [[thread_index_in_simdgroup]]) { + static_assert(BK >= SIMD_SIZE, "BK should be larger than SIMD_SIZE"); + static_assert(BK % SIMD_SIZE == 0, "BK should be divisible by SIMD_SIZE"); + + (void)lid; + + constexpr int WM = 2; + constexpr int WN = 2; + constexpr int pack_factor = get_pack_factor(); + constexpr int bytes_per_pack = get_bytes_per_pack(); + + constexpr int BK_padded = (BK + 16 / sizeof(T)); + + // Instantiate the appropriate BlockMMA and Loader + using mma_t = mlx::steel:: + BlockMMA; + using loader_x_t = + mlx::steel::BlockLoader; + using loader_w_t = QuantizedBlockLoader< + T, + BN, + BK, + BK_padded, + 1, + WM * WN * SIMD_SIZE, + group_size, + bits>; + + // Set the block + const int K_w = K * bytes_per_pack / pack_factor; + const int K_g = K / group_size; + const int y_row = tid.y * BM; + const int y_col = tid.x * BN; + + auto wl = (const device uint8_t*)w; + + x += y_row * static_cast(K); + wl += y_col * K_w; + scales += y_col * K_g; + biases += y_col * K_g; + y += y_row * static_cast(N) + y_col; + + // Make the x loader and mma operation + const short num_els = min(BM, M - y_row); + const short num_outs = min(BN, N - y_col); + loader_x_t loader_x(x, K, Xs, simd_gid, simd_lid); + loader_w_t loader_w(wl, scales, biases, K, Ws, simd_gid, simd_lid); + mma_t mma_op(simd_gid, simd_lid); + + if (num_els < BM) { + if (!aligned_N && num_outs < BN) { + for (int k = 0; k < K_eff; k += BK) { + threadgroup_barrier(mem_flags::mem_threadgroup); + loader_x.load_safe(short2(BK, num_els)); + loader_w.load_safe(short2(BK, num_outs)); + threadgroup_barrier(mem_flags::mem_threadgroup); + mma_op.mma(Xs, Ws); + loader_x.next(); + loader_w.next(); + } + } else { + for (int k = 0; k < K_eff; k += BK) { + threadgroup_barrier(mem_flags::mem_threadgroup); + loader_x.load_safe(short2(BK, num_els)); + loader_w.load_unsafe(); + threadgroup_barrier(mem_flags::mem_threadgroup); + mma_op.mma(Xs, Ws); + loader_x.next(); + loader_w.next(); + } + } + } else { + if (!aligned_N && num_outs < BN) { + for (int k = 0; k < K_eff; k += BK) { + threadgroup_barrier(mem_flags::mem_threadgroup); + loader_x.load_unsafe(); + loader_w.load_safe(short2(BK, num_outs)); + threadgroup_barrier(mem_flags::mem_threadgroup); + mma_op.mma(Xs, Ws); + loader_x.next(); + loader_w.next(); + } + } else { + for (int k = 0; k < K_eff; k += BK) { + threadgroup_barrier(mem_flags::mem_threadgroup); + loader_x.load_unsafe(); + loader_w.load_unsafe(); + threadgroup_barrier(mem_flags::mem_threadgroup); + + mma_op.mma(Xs, Ws); + loader_x.next(); + loader_w.next(); + } + } + } + + // Store results to device memory + threadgroup_barrier(mem_flags::mem_threadgroup); + if (num_els < BM || num_outs < BN) { + mma_op.store_result_safe(y, N, short2(num_outs, num_els)); + } else { + mma_op.store_result(y, N); + } +} + +template < + typename T, + const int group_size, + const int bits, + const int BM = 32, + const int BK = 32, + const int BN = 32> +METAL_FUNC void qmm_n_impl( + const device uint32_t* w, + const device T* scales, + const device T* biases, + const device T* x, + device T* y, + threadgroup T* Xs, + threadgroup T* Ws, + const constant int& K, + const constant int& N, + const constant int& M, + uint3 tid [[threadgroup_position_in_grid]], + uint lid [[thread_index_in_threadgroup]], + uint simd_gid [[simdgroup_index_in_threadgroup]], + uint simd_lid [[thread_index_in_simdgroup]]) { + static_assert(BK >= SIMD_SIZE, "BK should be larger than SIMD_SIZE"); + static_assert(BK % SIMD_SIZE == 0, "BK should be divisible by SIMD_SIZE"); + + (void)lid; + + constexpr int WM = 2; + constexpr int WN = 2; + constexpr int pack_factor = get_pack_factor(); + constexpr int bytes_per_pack = get_bytes_per_pack(); + + constexpr int BK_padded = (BK + 16 / sizeof(T)); + constexpr int BN_padded = (BN + 16 / sizeof(T)); + + // Instantiate the appropriate BlockMMA and Loader + using mma_t = mlx::steel:: + BlockMMA; + using loader_x_t = mlx::steel:: + BlockLoader; + using loader_w_t = QuantizedBlockLoader< + T, + BK, + BN, + BN_padded, + 0, + WM * WN * SIMD_SIZE, + group_size, + bits>; + + auto wl = (const device uint8_t*)w; + + // Set the block + const int y_row = tid.y * BM; + const int y_col = tid.x * BN; + x += y_row * static_cast(K); + wl += y_col * bytes_per_pack / pack_factor; + scales += y_col / group_size; + biases += y_col / group_size; + y += y_row * static_cast(N) + y_col; + + // Make the x loader and mma operation + const short num_els = min(BM, M - y_row); + loader_x_t loader_x(x, K, Xs, simd_gid, simd_lid); + loader_w_t loader_w(wl, scales, biases, N, Ws, simd_gid, simd_lid); + mma_t mma_op(simd_gid, simd_lid); + + if (num_els < BM) { + if ((K % BK) != 0) { + const int k_blocks = K / BK; + for (int k = 0; k < k_blocks; k++) { + threadgroup_barrier(mem_flags::mem_threadgroup); + loader_x.load_safe(short2(BK, num_els)); + loader_w.load_unsafe(); + threadgroup_barrier(mem_flags::mem_threadgroup); + mma_op.mma(Xs, Ws); + loader_x.next(); + loader_w.next(); + } + const short num_k = K - k_blocks * BK; + threadgroup_barrier(mem_flags::mem_threadgroup); + loader_x.load_safe(short2(num_k, num_els)); + loader_w.load_safe(short2(BN, num_k)); + threadgroup_barrier(mem_flags::mem_threadgroup); + mma_op.mma(Xs, Ws); + } else { + for (int k = 0; k < K; k += BK) { + threadgroup_barrier(mem_flags::mem_threadgroup); + loader_x.load_safe(short2(BK, num_els)); + loader_w.load_unsafe(); + threadgroup_barrier(mem_flags::mem_threadgroup); + mma_op.mma(Xs, Ws); + loader_x.next(); + loader_w.next(); + } + } + } else { + if ((K % BK) != 0) { + const int k_blocks = K / BK; + for (int k = 0; k < k_blocks; k++) { + threadgroup_barrier(mem_flags::mem_threadgroup); + loader_x.load_unsafe(); + loader_w.load_unsafe(); + threadgroup_barrier(mem_flags::mem_threadgroup); + mma_op.mma(Xs, Ws); + loader_x.next(); + loader_w.next(); + } + const short num_k = K - k_blocks * BK; + threadgroup_barrier(mem_flags::mem_threadgroup); + loader_x.load_safe(short2(num_k, BM)); + loader_w.load_safe(short2(BN, num_k)); + threadgroup_barrier(mem_flags::mem_threadgroup); + mma_op.mma(Xs, Ws); + } else { + for (int k = 0; k < K; k += BK) { + threadgroup_barrier(mem_flags::mem_threadgroup); + loader_x.load_unsafe(); + loader_w.load_unsafe(); + threadgroup_barrier(mem_flags::mem_threadgroup); + mma_op.mma(Xs, Ws); + loader_x.next(); + loader_w.next(); + } + } + } + + // Store results to device memory + threadgroup_barrier(mem_flags::mem_threadgroup); + if (num_els < BM) { + mma_op.store_result_safe(y, N, short2(BN, num_els)); + } else { + mma_op.store_result(y, N); + } +} + +template +METAL_FUNC void adjust_matrix_offsets( + const device T*& x, + const device uint32_t*& w, + const device T*& scales, + const device T*& biases, + device T*& y, + int output_stride, + const constant int& x_batch_ndims, + const constant int* x_shape, + const constant int64_t* x_strides, + const constant int& w_batch_ndims, + const constant int* w_shape, + const constant int64_t* w_strides, + const constant int64_t* s_strides, + const constant int64_t* b_strides, + uint3 tid [[threadgroup_position_in_grid]]) { + // Set the input/output matrices + uint32_t x_idx = tid.z; + uint32_t w_idx = tid.z; + if (x_batch_ndims == 1) { + x += x_idx * x_strides[0]; + } else { + x += elem_to_loc(x_idx, x_shape, x_strides, x_batch_ndims); + } + if (w_batch_ndims == 1) { + w += w_idx * w_strides[0]; + scales += w_idx * s_strides[0]; + biases += w_idx * b_strides[0]; + } else { + ulong3 idx = elem_to_loc_broadcast( + w_idx, w_shape, w_strides, s_strides, b_strides, w_batch_ndims); + w += idx.x; + scales += idx.y; + biases += idx.z; + } + y += tid.z * output_stride; +} + +template +METAL_FUNC void adjust_matrix_offsets( + const device T*& x, + const device uint32_t*& w, + const device T*& scales, + const device T*& biases, + const device uint32_t* lhs_indices, + const device uint32_t* rhs_indices, + device T*& y, + int output_stride, + const constant int& batch_ndims, + const constant int* batch_shape, + const constant int64_t* lhs_strides, + const constant int64_t* rhs_strides, + const constant int& x_batch_ndims, + const constant int* x_shape, + const constant int64_t* x_strides, + const constant int& w_batch_ndims, + const constant int* w_shape, + const constant int64_t* w_strides, + const constant int64_t* s_strides, + const constant int64_t* b_strides, + uint3 tid [[threadgroup_position_in_grid]]) { + // Set the input/output matrices + uint32_t x_idx; + uint32_t w_idx; + if (batch_ndims == 1) { + x_idx = lhs_indices[tid.z * lhs_strides[0]]; + w_idx = rhs_indices[tid.z * rhs_strides[0]]; + } else { + ulong2 idx = elem_to_loc_broadcast( + tid.z, batch_shape, lhs_strides, rhs_strides, batch_ndims); + x_idx = lhs_indices[idx.x]; + w_idx = rhs_indices[idx.y]; + } + if (x_batch_ndims == 1) { + x += x_idx * x_strides[0]; + } else { + x += elem_to_loc(x_idx, x_shape, x_strides, x_batch_ndims); + } + if (w_batch_ndims == 1) { + w += w_idx * w_strides[0]; + scales += w_idx * s_strides[0]; + biases += w_idx * b_strides[0]; + } else { + ulong3 idx = elem_to_loc_broadcast( + w_idx, w_shape, w_strides, s_strides, b_strides, w_batch_ndims); + w += idx.x; + scales += idx.y; + biases += idx.z; + } + y += tid.z * output_stride; +} + +template +[[kernel]] void affine_qmv_quad( + const device uint32_t* w [[buffer(0)]], + const device T* scales [[buffer(1)]], + const device T* biases [[buffer(2)]], + const device T* x [[buffer(3)]], + device T* y [[buffer(4)]], + const constant int& in_vec_size [[buffer(5)]], + const constant int& out_vec_size [[buffer(6)]], + const constant int& x_batch_ndims [[buffer(7)]], + const constant int* x_shape [[buffer(8)]], + const constant int64_t* x_strides [[buffer(9)]], + const constant int& w_batch_ndims [[buffer(10)]], + const constant int* w_shape [[buffer(11)]], + const constant int64_t* w_strides [[buffer(12)]], + const constant int64_t* s_strides [[buffer(13)]], + const constant int64_t* b_strides [[buffer(14)]], + uint3 tid [[threadgroup_position_in_grid]], + uint quad_gid [[quadgroup_index_in_threadgroup]], + uint quad_lid [[thread_index_in_quadgroup]]) { + if (batched) { + int M = x_shape[x_batch_ndims]; + adjust_matrix_offsets( + x, + w, + scales, + biases, + y, + out_vec_size * M, + x_batch_ndims, + x_shape, + x_strides, + w_batch_ndims, + w_shape, + w_strides, + s_strides, + b_strides, + tid); + } + qmv_quad_impl( + w, + scales, + biases, + x, + y, + in_vec_size, + out_vec_size, + tid, + quad_gid, + quad_lid); +} + +template < + typename T, + int group_size, + int bits, + bool batched, + bool partial_rows = false, + bool has_global_scale = false, + int results_per_simdgroup = 4> +[[kernel]] void affine_qmv_fast( + const device uint32_t* w [[buffer(0)]], + const device T* scales [[buffer(1)]], + const device T* biases [[buffer(2)]], + const device T* x [[buffer(3)]], + device T* y [[buffer(4)]], + const constant int& in_vec_size [[buffer(5)]], + const constant int& out_vec_size [[buffer(6)]], + const constant int& x_batch_ndims [[buffer(7)]], + const constant int* x_shape [[buffer(8)]], + const constant int64_t* x_strides [[buffer(9)]], + const constant int& w_batch_ndims [[buffer(10)]], + const constant int* w_shape [[buffer(11)]], + const constant int64_t* w_strides [[buffer(12)]], + const constant int64_t* s_strides [[buffer(13)]], + const constant int64_t* b_strides [[buffer(14)]], + uint3 tid [[threadgroup_position_in_grid]], + uint simd_gid [[simdgroup_index_in_threadgroup]], + uint simd_lid [[thread_index_in_simdgroup]]) { + if (batched) { + int M = x_shape[x_batch_ndims]; + adjust_matrix_offsets( + x, + w, + scales, + biases, + y, + out_vec_size * M, + x_batch_ndims, + x_shape, + x_strides, + w_batch_ndims, + w_shape, + w_strides, + s_strides, + b_strides, + tid); + } + qmv_fast_impl( + w, + scales, + biases, + x, + y, + in_vec_size, + out_vec_size, + tid, + simd_gid, + simd_lid); +} + +template < + typename T, + int group_size, + const int bits, + bool batched, + bool partial_rows = false, + bool has_global_scale = false, + int results_per_simdgroup = 4> +[[kernel]] void affine_qmv( + const device uint32_t* w [[buffer(0)]], + const device T* scales [[buffer(1)]], + const device T* biases [[buffer(2)]], + const device T* x [[buffer(3)]], + device T* y [[buffer(4)]], + const constant int& in_vec_size [[buffer(5)]], + const constant int& out_vec_size [[buffer(6)]], + const constant int& x_batch_ndims [[buffer(7)]], + const constant int* x_shape [[buffer(8)]], + const constant int64_t* x_strides [[buffer(9)]], + const constant int& w_batch_ndims [[buffer(10)]], + const constant int* w_shape [[buffer(11)]], + const constant int64_t* w_strides [[buffer(12)]], + const constant int64_t* s_strides [[buffer(13)]], + const constant int64_t* b_strides [[buffer(14)]], + uint3 tid [[threadgroup_position_in_grid]], + uint simd_gid [[simdgroup_index_in_threadgroup]], + uint simd_lid [[thread_index_in_simdgroup]]) { + if (batched) { + int M = x_shape[x_batch_ndims]; + adjust_matrix_offsets( + x, + w, + scales, + biases, + y, + out_vec_size * M, + x_batch_ndims, + x_shape, + x_strides, + w_batch_ndims, + w_shape, + w_strides, + s_strides, + b_strides, + tid); + } + qmv_impl( + w, + scales, + biases, + x, + y, + in_vec_size, + out_vec_size, + tid, + simd_gid, + simd_lid); +} + +template < + typename T, + int group_size, + int bits, + int vecs_per_tg, + int k_lanes, + bool batched> +[[kernel]] void affine_qmv_wide( + const device uint32_t* w, + const device T* scales, + const device T* biases, + const device T* x, + device T* y, + const constant int& in_vec_size, + const constant int& out_vec_size, + const constant int& M, + const constant int& x_batch_ndims, + const constant int* x_shape, + const constant int64_t* x_strides, + const constant int& w_batch_ndims, + const constant int* w_shape, + const constant int64_t* w_strides, + const constant int64_t* s_strides, + const constant int64_t* b_strides, + uint3 tid [[threadgroup_position_in_grid]], + uint simd_gid [[simdgroup_index_in_threadgroup]], + uint simd_lid [[thread_index_in_simdgroup]]) { + if (batched) { + adjust_matrix_offsets( + x, + w, + scales, + biases, + y, + out_vec_size * M, + x_batch_ndims, + x_shape, + x_strides, + w_batch_ndims, + w_shape, + w_strides, + s_strides, + b_strides, + tid); + } + qmv_wide_impl( + w, + scales, + biases, + x, + y, + in_vec_size, + out_vec_size, + M, + tid, + simd_gid, + simd_lid); +} + +template < + typename T, + const int group_size, + const int bits, + bool batched, + bool has_global_scale = false> +[[kernel]] void affine_qvm( + const device uint32_t* w [[buffer(0)]], + const device T* scales [[buffer(1)]], + const device T* biases [[buffer(2)]], + const device T* x [[buffer(3)]], + device T* y [[buffer(4)]], + const constant int& in_vec_size [[buffer(5)]], + const constant int& out_vec_size [[buffer(6)]], + const constant int& x_batch_ndims [[buffer(7)]], + const constant int* x_shape [[buffer(8)]], + const constant int64_t* x_strides [[buffer(9)]], + const constant int& w_batch_ndims [[buffer(10)]], + const constant int* w_shape [[buffer(11)]], + const constant int64_t* w_strides [[buffer(12)]], + const constant int64_t* s_strides [[buffer(13)]], + const constant int64_t* b_strides [[buffer(14)]], + uint3 tid [[threadgroup_position_in_grid]], + uint simd_gid [[simdgroup_index_in_threadgroup]], + uint simd_lid [[thread_index_in_simdgroup]]) { + if (batched) { + int M = x_shape[x_batch_ndims]; + adjust_matrix_offsets( + x, + w, + scales, + biases, + y, + out_vec_size * M, + x_batch_ndims, + x_shape, + x_strides, + w_batch_ndims, + w_shape, + w_strides, + s_strides, + b_strides, + tid); + } + qvm_impl( + w, + scales, + biases, + x, + y, + in_vec_size, + out_vec_size, + in_vec_size, + tid, + simd_gid, + simd_lid); +} + +template +[[kernel]] void affine_qvm_split_k( + const device uint32_t* w [[buffer(0)]], + const device T* scales [[buffer(1)]], + const device T* biases [[buffer(2)]], + const device T* x [[buffer(3)]], + device T* y [[buffer(4)]], + const constant int& in_vec_size [[buffer(5)]], + const constant int& out_vec_size [[buffer(6)]], + const constant int& x_batch_ndims [[buffer(7)]], + const constant int* x_shape [[buffer(8)]], + const constant int64_t* x_strides [[buffer(9)]], + const constant int& w_batch_ndims [[buffer(10)]], + const constant int* w_shape [[buffer(11)]], + const constant int64_t* w_strides [[buffer(12)]], + const constant int64_t* s_strides [[buffer(13)]], + const constant int64_t* b_strides [[buffer(14)]], + const constant int& final_block_size [[buffer(15)]], + uint3 tid [[threadgroup_position_in_grid]], + uint simd_gid [[simdgroup_index_in_threadgroup]], + uint simd_lid [[thread_index_in_simdgroup]]) { + int M = x_shape[x_batch_ndims]; + adjust_matrix_offsets( + x, + w, + scales, + biases, + y, + out_vec_size * M, + x_batch_ndims, + x_shape, + x_strides, + w_batch_ndims, + w_shape, + w_strides, + s_strides, + b_strides, + tid); + + // When (in_vec_size % split_k != 0) the final block needs to be smaller + int in_vec_size_adj = + tid.z % split_k == split_k - 1 ? final_block_size : in_vec_size; + + // The in_vec_stride is the full K dimension, not the partition size + int in_vec_stride = (split_k - 1) * in_vec_size + final_block_size; + + qvm_impl( + w, + scales, + biases, + x, + y, + in_vec_size_adj, + out_vec_size, + in_vec_stride, + tid, + simd_gid, + simd_lid); +} + +template < + typename T, + const int group_size, + const int bits, + const bool aligned_N, + const bool batched, + const bool has_global_scale = false, + const int BM = 32, + const int BK = 32, + const int BN = 32> +[[kernel]] void affine_qmm_t( + const device uint32_t* w [[buffer(0)]], + const device T* scales [[buffer(1)]], + const device T* biases [[buffer(2)]], + const device T* x [[buffer(3)]], + device T* y [[buffer(4)]], + const constant int& K [[buffer(5)]], + const constant int& N [[buffer(6)]], + const constant int& M [[buffer(7)]], + const constant int& x_batch_ndims [[buffer(8)]], + const constant int* x_shape [[buffer(9)]], + const constant int64_t* x_strides [[buffer(10)]], + const constant int& w_batch_ndims [[buffer(11)]], + const constant int* w_shape [[buffer(12)]], + const constant int64_t* w_strides [[buffer(13)]], + const constant int64_t* s_strides [[buffer(14)]], + const constant int64_t* b_strides [[buffer(15)]], + uint3 tid [[threadgroup_position_in_grid]], + uint lid [[thread_index_in_threadgroup]], + uint simd_gid [[simdgroup_index_in_threadgroup]], + uint simd_lid [[thread_index_in_simdgroup]]) { + (void)lid; + + constexpr int BK_padded = (BK + 16 / sizeof(T)); + + threadgroup T Xs[BM * BK_padded]; + threadgroup T Ws[BN * BK_padded]; + + if (batched) { + adjust_matrix_offsets( + x, + w, + scales, + biases, + y, + M * N, + x_batch_ndims, + x_shape, + x_strides, + w_batch_ndims, + w_shape, + w_strides, + s_strides, + b_strides, + tid); + } + qmm_t_impl( + w, + scales, + biases, + x, + y, + Xs, + Ws, + K, + N, + M, + K, + tid, + lid, + simd_gid, + simd_lid); +} + +template < + typename T, + const int group_size, + const int bits, + const bool aligned_N, + const int BM = 32, + const int BK = 32, + const int BN = 32> +[[kernel]] void affine_qmm_t_splitk( + const device uint32_t* w [[buffer(0)]], + const device T* scales [[buffer(1)]], + const device T* biases [[buffer(2)]], + const device T* x [[buffer(3)]], + device float* y [[buffer(4)]], + const constant int& K [[buffer(5)]], + const constant int& N [[buffer(6)]], + const constant int& M [[buffer(7)]], + const constant int& k_partition_size [[buffer(8)]], + const constant int& split_k_partition_stride [[buffer(9)]], + uint3 tid [[threadgroup_position_in_grid]], + uint lid [[thread_index_in_threadgroup]], + uint simd_gid [[simdgroup_index_in_threadgroup]], + uint simd_lid [[thread_index_in_simdgroup]]) { + (void)lid; + + constexpr int BK_padded = (BK + 16 / sizeof(T)); + constexpr int pack_factor = get_pack_factor(); + constexpr int bytes_per_pack = get_bytes_per_pack(); + + threadgroup T Xs[BM * BK_padded]; + threadgroup T Ws[BN * BK_padded]; + + const int k_start = tid.z * k_partition_size; + x += k_start; + + auto wl = (const device uint8_t*)w; + wl += k_start * bytes_per_pack / pack_factor; + scales += k_start / group_size; + biases += k_start / group_size; + y += tid.z * static_cast(split_k_partition_stride); + + qmm_t_impl( + (const device uint32_t*)wl, + scales, + biases, + x, + y, + Xs, + Ws, + K, + N, + M, + k_partition_size, + tid, + lid, + simd_gid, + simd_lid); +} + +template < + typename T, + int group_size, + int bits, + bool batched, + bool has_global_scale = false, + int BM = 32, + int BK = 32, + int BN = 32> +[[kernel]] void affine_qmm_n( + const device uint32_t* w [[buffer(0)]], + const device T* scales [[buffer(1)]], + const device T* biases [[buffer(2)]], + const device T* x [[buffer(3)]], + device T* y [[buffer(4)]], + const constant int& K [[buffer(5)]], + const constant int& N [[buffer(6)]], + const constant int& M [[buffer(7)]], + const constant int& x_batch_ndims [[buffer(8)]], + const constant int* x_shape [[buffer(9)]], + const constant int64_t* x_strides [[buffer(10)]], + const constant int& w_batch_ndims [[buffer(11)]], + const constant int* w_shape [[buffer(12)]], + const constant int64_t* w_strides [[buffer(13)]], + const constant int64_t* s_strides [[buffer(14)]], + const constant int64_t* b_strides [[buffer(15)]], + uint3 tid [[threadgroup_position_in_grid]], + uint lid [[thread_index_in_threadgroup]], + uint simd_gid [[simdgroup_index_in_threadgroup]], + uint simd_lid [[thread_index_in_simdgroup]]) { + (void)lid; + + constexpr int BK_padded = (BK + 16 / sizeof(T)); + constexpr int BN_padded = (BN + 16 / sizeof(T)); + + threadgroup T Xs[BM * BK_padded]; + threadgroup T Ws[BK * BN_padded]; + + if (batched) { + adjust_matrix_offsets( + x, + w, + scales, + biases, + y, + M * N, + x_batch_ndims, + x_shape, + x_strides, + w_batch_ndims, + w_shape, + w_strides, + s_strides, + b_strides, + tid); + } + + qmm_n_impl( + w, scales, biases, x, y, Xs, Ws, K, N, M, tid, lid, simd_gid, simd_lid); +} + +template +[[kernel]] void affine_gather_qmv_fast( + const device uint32_t* w [[buffer(0)]], + const device T* scales [[buffer(1)]], + const device T* biases [[buffer(2)]], + const device T* x [[buffer(3)]], + const device uint32_t* lhs_indices [[buffer(4)]], + const device uint32_t* rhs_indices [[buffer(5)]], + device T* y [[buffer(6)]], + const constant int& in_vec_size [[buffer(7)]], + const constant int& out_vec_size [[buffer(8)]], + const constant int& x_batch_ndims [[buffer(9)]], + const constant int* x_shape [[buffer(10)]], + const constant int64_t* x_strides [[buffer(11)]], + const constant int& w_batch_ndims [[buffer(12)]], + const constant int* w_shape [[buffer(13)]], + const constant int64_t* w_strides [[buffer(14)]], + const constant int64_t* s_strides [[buffer(15)]], + const constant int64_t* b_strides [[buffer(16)]], + const constant int& batch_ndims [[buffer(17)]], + const constant int* batch_shape [[buffer(18)]], + const constant int64_t* lhs_strides [[buffer(19)]], + const constant int64_t* rhs_strides [[buffer(20)]], + uint3 tid [[threadgroup_position_in_grid]], + uint simd_gid [[simdgroup_index_in_threadgroup]], + uint simd_lid [[thread_index_in_simdgroup]]) { + int M = x_shape[x_batch_ndims]; + adjust_matrix_offsets( + x, + w, + scales, + biases, + lhs_indices, + rhs_indices, + y, + out_vec_size * M, + batch_ndims, + batch_shape, + lhs_strides, + rhs_strides, + x_batch_ndims, + x_shape, + x_strides, + w_batch_ndims, + w_shape, + w_strides, + s_strides, + b_strides, + tid); + qmv_fast_impl( + w, + scales, + biases, + x, + y, + in_vec_size, + out_vec_size, + tid, + simd_gid, + simd_lid); +} + +template +[[kernel]] void affine_gather_qmv( + const device uint32_t* w [[buffer(0)]], + const device T* scales [[buffer(1)]], + const device T* biases [[buffer(2)]], + const device T* x [[buffer(3)]], + const device uint32_t* lhs_indices [[buffer(4)]], + const device uint32_t* rhs_indices [[buffer(5)]], + device T* y [[buffer(6)]], + const constant int& in_vec_size [[buffer(7)]], + const constant int& out_vec_size [[buffer(8)]], + const constant int& x_batch_ndims [[buffer(9)]], + const constant int* x_shape [[buffer(10)]], + const constant int64_t* x_strides [[buffer(11)]], + const constant int& w_batch_ndims [[buffer(12)]], + const constant int* w_shape [[buffer(13)]], + const constant int64_t* w_strides [[buffer(14)]], + const constant int64_t* s_strides [[buffer(15)]], + const constant int64_t* b_strides [[buffer(16)]], + const constant int& batch_ndims [[buffer(17)]], + const constant int* batch_shape [[buffer(18)]], + const constant int64_t* lhs_strides [[buffer(19)]], + const constant int64_t* rhs_strides [[buffer(20)]], + uint3 tid [[threadgroup_position_in_grid]], + uint simd_gid [[simdgroup_index_in_threadgroup]], + uint simd_lid [[thread_index_in_simdgroup]]) { + int M = x_shape[x_batch_ndims]; + adjust_matrix_offsets( + x, + w, + scales, + biases, + lhs_indices, + rhs_indices, + y, + out_vec_size * M, + batch_ndims, + batch_shape, + lhs_strides, + rhs_strides, + x_batch_ndims, + x_shape, + x_strides, + w_batch_ndims, + w_shape, + w_strides, + s_strides, + b_strides, + tid); + qmv_impl( + w, + scales, + biases, + x, + y, + in_vec_size, + out_vec_size, + tid, + simd_gid, + simd_lid); +} + +template +[[kernel]] void affine_gather_qvm( + const device uint32_t* w [[buffer(0)]], + const device T* scales [[buffer(1)]], + const device T* biases [[buffer(2)]], + const device T* x [[buffer(3)]], + const device uint32_t* lhs_indices [[buffer(4)]], + const device uint32_t* rhs_indices [[buffer(5)]], + device T* y [[buffer(6)]], + const constant int& in_vec_size [[buffer(7)]], + const constant int& out_vec_size [[buffer(8)]], + const constant int& x_batch_ndims [[buffer(9)]], + const constant int* x_shape [[buffer(10)]], + const constant int64_t* x_strides [[buffer(11)]], + const constant int& w_batch_ndims [[buffer(12)]], + const constant int* w_shape [[buffer(13)]], + const constant int64_t* w_strides [[buffer(14)]], + const constant int64_t* s_strides [[buffer(15)]], + const constant int64_t* b_strides [[buffer(16)]], + const constant int& batch_ndims [[buffer(17)]], + const constant int* batch_shape [[buffer(18)]], + const constant int64_t* lhs_strides [[buffer(19)]], + const constant int64_t* rhs_strides [[buffer(20)]], + uint3 tid [[threadgroup_position_in_grid]], + uint simd_gid [[simdgroup_index_in_threadgroup]], + uint simd_lid [[thread_index_in_simdgroup]]) { + int M = x_shape[x_batch_ndims]; + adjust_matrix_offsets( + x, + w, + scales, + biases, + lhs_indices, + rhs_indices, + y, + out_vec_size * M, + batch_ndims, + batch_shape, + lhs_strides, + rhs_strides, + x_batch_ndims, + x_shape, + x_strides, + w_batch_ndims, + w_shape, + w_strides, + s_strides, + b_strides, + tid); + qvm_impl( + w, + scales, + biases, + x, + y, + in_vec_size, + out_vec_size, + in_vec_size, + tid, + simd_gid, + simd_lid); +} + +template < + typename T, + const int group_size, + const int bits, + const bool aligned_N, + const bool has_global_scale = false, + const int BM = 32, + const int BK = 32, + const int BN = 32> +[[kernel]] void affine_gather_qmm_t( + const device uint32_t* w [[buffer(0)]], + const device T* scales [[buffer(1)]], + const device T* biases [[buffer(2)]], + const device T* x [[buffer(3)]], + const device uint32_t* lhs_indices [[buffer(4)]], + const device uint32_t* rhs_indices [[buffer(5)]], + device T* y [[buffer(6)]], + const constant int& K [[buffer(7)]], + const constant int& N [[buffer(8)]], + const constant int& M [[buffer(9)]], + const constant int& x_batch_ndims [[buffer(10)]], + const constant int* x_shape [[buffer(11)]], + const constant int64_t* x_strides [[buffer(12)]], + const constant int& w_batch_ndims [[buffer(13)]], + const constant int* w_shape [[buffer(14)]], + const constant int64_t* w_strides [[buffer(15)]], + const constant int64_t* s_strides [[buffer(16)]], + const constant int64_t* b_strides [[buffer(17)]], + const constant int& batch_ndims [[buffer(18)]], + const constant int* batch_shape [[buffer(19)]], + const constant int64_t* lhs_strides [[buffer(20)]], + const constant int64_t* rhs_strides [[buffer(21)]], + uint3 tid [[threadgroup_position_in_grid]], + uint lid [[thread_index_in_threadgroup]], + uint simd_gid [[simdgroup_index_in_threadgroup]], + uint simd_lid [[thread_index_in_simdgroup]]) { + (void)lid; + + constexpr int BK_padded = (BK + 16 / sizeof(T)); + + threadgroup T Xs[BM * BK_padded]; + threadgroup T Ws[BN * BK_padded]; + + adjust_matrix_offsets( + x, + w, + scales, + biases, + lhs_indices, + rhs_indices, + y, + M * N, + batch_ndims, + batch_shape, + lhs_strides, + rhs_strides, + x_batch_ndims, + x_shape, + x_strides, + w_batch_ndims, + w_shape, + w_strides, + s_strides, + b_strides, + tid); + qmm_t_impl( + w, + scales, + biases, + x, + y, + Xs, + Ws, + K, + N, + M, + K, + tid, + lid, + simd_gid, + simd_lid); +} + +template < + typename T, + int group_size, + int bits, + bool has_global_scale = false, + int BM = 32, + int BK = 32, + int BN = 32> +[[kernel]] void affine_gather_qmm_n( + const device uint32_t* w [[buffer(0)]], + const device T* scales [[buffer(1)]], + const device T* biases [[buffer(2)]], + const device T* x [[buffer(3)]], + const device uint32_t* lhs_indices [[buffer(4)]], + const device uint32_t* rhs_indices [[buffer(5)]], + device T* y [[buffer(6)]], + const constant int& K [[buffer(7)]], + const constant int& N [[buffer(8)]], + const constant int& M [[buffer(9)]], + const constant int& x_batch_ndims [[buffer(10)]], + const constant int* x_shape [[buffer(11)]], + const constant int64_t* x_strides [[buffer(12)]], + const constant int& w_batch_ndims [[buffer(13)]], + const constant int* w_shape [[buffer(14)]], + const constant int64_t* w_strides [[buffer(15)]], + const constant int64_t* s_strides [[buffer(16)]], + const constant int64_t* b_strides [[buffer(17)]], + const constant int& batch_ndims [[buffer(18)]], + const constant int* batch_shape [[buffer(19)]], + const constant int64_t* lhs_strides [[buffer(20)]], + const constant int64_t* rhs_strides [[buffer(21)]], + uint3 tid [[threadgroup_position_in_grid]], + uint lid [[thread_index_in_threadgroup]], + uint simd_gid [[simdgroup_index_in_threadgroup]], + uint simd_lid [[thread_index_in_simdgroup]]) { + (void)lid; + + constexpr int BK_padded = (BK + 16 / sizeof(T)); + constexpr int BN_padded = (BN + 16 / sizeof(T)); + + threadgroup T Xs[BM * BK_padded]; + threadgroup T Ws[BK * BN_padded]; + + adjust_matrix_offsets( + x, + w, + scales, + biases, + lhs_indices, + rhs_indices, + y, + M * N, + batch_ndims, + batch_shape, + lhs_strides, + rhs_strides, + x_batch_ndims, + x_shape, + x_strides, + w_batch_ndims, + w_shape, + w_strides, + s_strides, + b_strides, + tid); + qmm_n_impl( + w, scales, biases, x, y, Xs, Ws, K, N, M, tid, lid, simd_gid, simd_lid); +} + +template < + typename T, + int group_size, + int bits, + int BM, + int BN, + int BK, + int WM, + int WN, + bool transpose> +[[kernel]] void affine_gather_qmm_rhs( + const device T* x [[buffer(0)]], + const device uint32_t* w [[buffer(1)]], + const device T* scales [[buffer(2)]], + const device T* biases [[buffer(3)]], + const device int32_t* offsets [[buffer(4)]], + device T* y [[buffer(5)]], + const constant int& M [[buffer(6)]], + const constant int& N [[buffer(7)]], + const constant int& K [[buffer(8)]], + const constant int& num_groups [[buffer(9)]], + uint3 tid [[threadgroup_position_in_grid]], + uint simd_group_id [[simdgroup_index_in_threadgroup]], + uint simd_lane_id [[thread_index_in_simdgroup]]) { + constexpr int pack_factor = get_pack_factor(); + constexpr int bytes_per_pack = get_bytes_per_pack(); + constexpr int BK_padded = (BK + 16 / sizeof(T)); + constexpr int BN_padded = (BN + 16 / sizeof(T)); + + using mma_t = mlx::steel::BlockMMA< + T, + T, + BM, + BN, + BK, + WM, + WN, + false, + transpose, + BK_padded, + transpose ? BK_padded : BN_padded>; + using loader_x_t = + mlx::steel::BlockLoader; + using loader_w_t = QuantizedBlockLoader< + T, + transpose ? BN : BK, + transpose ? BK : BN, + transpose ? BK_padded : BN_padded, + transpose, + WM * WN * SIMD_SIZE, + group_size, + bits>; + + threadgroup T Xs[BM * BK_padded]; + threadgroup T Ws[transpose ? BN * BK_padded : BK * BN_padded]; + + // Compute the block + const int K_w = K * bytes_per_pack / pack_factor; + const int K_g = K / group_size; + const int N_w = N * bytes_per_pack / pack_factor; + const int N_g = N / group_size; + const int K_it = K / BK; + const size_t stride_w = transpose ? N * K_w : K * N_w; + const size_t stride_s = transpose ? N * K_g : K * N_g; + int y_row; + int group; + short tgp_bm; + if (!schedule_row_tile( + offsets, num_groups, M, tid.y, simd_lane_id, y_row, group, tgp_bm)) { + return; + } + const int y_col = tid.x * BN; + const size_t y_row_long = size_t(y_row); + const size_t y_col_long = size_t(y_col); + + // Prepare threadgroup bounds + const short tgp_bn = align_N ? BN : short(min(BN, N - y_col)); + + // Calculate the final tiles in the case that K is not aligned + const int k_remain = K - K_it * BK; + const short2 tile_x = short2(k_remain, tgp_bm); + const short2 tile_w = + transpose ? short2(k_remain, tgp_bn) : short2(tgp_bn, k_remain); + + // Move x and output to the correct block + auto wl = (const device uint8_t*)w; + x += y_row_long * K; + y += y_row_long * N + y_col_long; + wl += transpose ? y_col_long * K_w : y_col * bytes_per_pack / pack_factor; + scales += transpose ? y_col_long * K_g : y_col / group_size; + biases += transpose ? y_col_long * K_g : y_col / group_size; + + // Prepare threadgroup mma operation + thread mma_t mma_op(simd_group_id, simd_lane_id); + + // Prepare threadgroup loading operations + thread loader_x_t loader_x(x, K, Xs, simd_group_id, simd_lane_id); + thread loader_w_t loader_w( + wl + group * stride_w, + scales + group * stride_s, + biases + group * stride_s, + transpose ? K : N, + Ws, + simd_group_id, + simd_lane_id); + + // Tile aligned so check outside of the hot loop + if (tgp_bm == BM && (align_N || tgp_bn == BN)) { + gemm_loop_aligned(Xs, Ws, mma_op, loader_x, loader_w, K_it); + if (!align_K) { + threadgroup_barrier(mem_flags::mem_threadgroup); + gemm_loop_finalize(Xs, Ws, mma_op, loader_x, loader_w, tile_x, tile_w); + } + mma_op.store_result(y, N); + } + + // Tile partially aligned check rows + else if (align_N || tgp_bn == BN) { + gemm_loop_unaligned( + Xs, Ws, mma_op, loader_x, loader_w, K_it, tgp_bm, tgp_bn, BK); + if (!align_K) { + threadgroup_barrier(mem_flags::mem_threadgroup); + gemm_loop_finalize(Xs, Ws, mma_op, loader_x, loader_w, tile_x, tile_w); + } + mma_op.store_result_safe(y, N, short2(BN, tgp_bm)); + } + + // Tile partially aligned check cols + else if (tgp_bm == BM) { + gemm_loop_unaligned( + Xs, Ws, mma_op, loader_x, loader_w, K_it, tgp_bm, tgp_bn, BK); + if (!align_K) { + threadgroup_barrier(mem_flags::mem_threadgroup); + gemm_loop_finalize(Xs, Ws, mma_op, loader_x, loader_w, tile_x, tile_w); + } + mma_op.store_result_safe(y, N, short2(tgp_bn, BM)); + } + + // Nothing aligned so check both rows and cols + else { + gemm_loop_unaligned( + Xs, Ws, mma_op, loader_x, loader_w, K_it, tgp_bm, tgp_bn, BK); + if (!align_K) { + threadgroup_barrier(mem_flags::mem_threadgroup); + gemm_loop_finalize(Xs, Ws, mma_op, loader_x, loader_w, tile_x, tile_w); + } + mma_op.store_result_safe(y, N, short2(tgp_bn, tgp_bm)); + } +} + +template +[[kernel]] void affine_quantize( + const device T* w [[buffer(0)]], + device uint8_t* out [[buffer(1)]], + device T* scales [[buffer(2)]], + device T* biases [[buffer(3)]], + uint2 index [[thread_position_in_grid]], + uint2 grid_dim [[threads_per_grid]]) { + constexpr float eps = 1e-7; + constexpr int simd_size = 32; + constexpr float n_bins = (1 << bits) - 1; + constexpr int pack_factor = get_pack_factor(); + constexpr int bytes_per_pack = get_bytes_per_pack(); + constexpr int values_per_reduce = group_size / simd_size; + constexpr int writes_per_reduce = pack_factor / values_per_reduce; + constexpr int writes_per_pack = + writes_per_reduce > 1 ? 1 : values_per_reduce / pack_factor; + constexpr int power_of_2_bits = (bits & (bits - 1)) == 0; + + static_assert( + group_size % simd_size == 0, + "Group size must be divisible by simd size."); + + size_t offset = index.x + grid_dim.x * size_t(index.y); + size_t in_index = offset * values_per_reduce; + size_t out_index = power_of_2_bits + ? offset * writes_per_pack + : offset * bytes_per_pack / writes_per_reduce; + + float w_thread[values_per_reduce]; + float w_min = Limits::max; + float w_max = 0; + +#pragma clang loop unroll(full) + for (int i = 0; i < values_per_reduce; i++) { + float val = w[in_index + i]; + w_thread[i] = val; + w_min = min(w_min, val); + w_max = max(w_max, val); + } + + w_min = simd_min(w_min); + w_max = simd_max(w_max); + + float scale; + float bias; + + if (bits == 1) { + // Affine 1-bit: bit 0 -> w_min, bit 1 -> w_max + scale = max(w_max - w_min, eps); + bias = w_min; + } else { + scale = max((w_max - w_min) / n_bins, eps); + bool side = abs(w_min) > abs(w_max); + scale = side ? scale : -scale; + float edge = side ? w_min : w_max; + float q0 = round(edge / scale); + bool at_zero = q0 == 0.0f; + scale = at_zero ? scale : edge / q0; + bias = at_zero ? 0 : edge; + } + + // Write out the scales and biases + size_t gindex = in_index / group_size; + if (in_index % group_size == 0) { + scales[gindex] = static_cast(scale); + biases[gindex] = static_cast(bias); + } + + using OutType = metal::conditional_t; + OutType output = 0; + +#pragma clang loop unroll(full) + for (int i = 0; i < values_per_reduce; i++) { + uint8_t val = min(round((w_thread[i] - bias) / scale), n_bins); + if (bits == 8) { + output = val; + } else { + output |= val << (bits * (i % pack_factor)); + } + + if (pack_factor < values_per_reduce && i % pack_factor == pack_factor - 1) { + out[out_index + i / pack_factor] = output; + output = 0; + } else { +#pragma clang loop unroll(full) + for (int j = 1; j < writes_per_reduce; j++) { + uint8_t sval = simd_shuffle_down(val, j); + output |= static_cast(sval) + << (bits * (j * values_per_reduce + i)); + } + } + } + if (bits == 3 || bits == 6) { + if (in_index % pack_factor == 0 && out_index % bytes_per_pack == 0) { + out[out_index] = output & 0xff; + out[out_index + 1] = (output & 0xff00) >> 8; + out[out_index + 2] = (output & 0xff0000) >> 16; + } + } else if (bits == 5) { + if (in_index % pack_factor == 0 && out_index % bytes_per_pack == 0) { + out[out_index] = output & 0xff; + out[out_index + 1] = (output & 0xff00) >> 8; + out[out_index + 2] = (output & 0xff0000) >> 16; + out[out_index + 3] = (output & 0xff000000) >> 24; + out[out_index + 4] = (output & 0xff00000000) >> 32; + } + } else { + if (writes_per_reduce > 0 && out_index % writes_per_reduce == 0) { + out[out_index / writes_per_reduce] = output; + } + } +} + +template +[[kernel]] void affine_dequantize( + const device uint8_t* w [[buffer(0)]], + const device T* scales [[buffer(1)]], + const device T* biases [[buffer(2)]], + device T* out [[buffer(3)]], + uint2 index [[thread_position_in_grid]], + uint2 grid_dim [[threads_per_grid]]) { + constexpr int pack_factor = get_pack_factor(); + constexpr int bytes_per_pack = get_bytes_per_pack(); + + size_t offset = index.x + grid_dim.x * size_t(index.y); + size_t oindex = offset * pack_factor; + size_t gindex = oindex / group_size; + T scale = scales[gindex]; + T bias = biases[gindex]; + + out += oindex; + + if (bits == 3) { + w += offset * bytes_per_pack; + out[0] = (w[0] & 0x7) * scale + bias; + out[1] = ((w[0] & 0x38) >> 3) * scale + bias; + out[2] = (((w[0] & 0xc0) >> 6) + ((w[1] & 0x1) << 2)) * scale + bias; + out[3] = ((w[1] & 0xe) >> 1) * scale + bias; + out[4] = ((w[1] & 0x70) >> 4) * scale + bias; + out[5] = (((w[1] & 0x80) >> 7) + ((w[2] & 0x3) << 1)) * scale + bias; + out[6] = ((w[2] & 0x1c) >> 2) * scale + bias; + out[7] = ((w[2] & 0xe0) >> 5) * scale + bias; + } else if (bits == 5) { + w += offset * bytes_per_pack; + out[0] = (w[0] & 0x1f) * scale + bias; + out[1] = (((w[0] & 0xe0) >> 5) + ((w[1] & 0x3) << 3)) * scale + bias; + out[2] = ((w[1] & 0x7c) >> 2) * scale + bias; + out[3] = (((w[1] & 0x80) >> 7) + ((w[2] & 0xf) << 1)) * scale + bias; + out[4] = (((w[2] & 0xf0) >> 4) + ((w[3] & 0x1) << 4)) * scale + bias; + out[5] = ((w[3] & 0x3e) >> 1) * scale + bias; + out[6] = (((w[3] & 0xc0) >> 6) + ((w[4] & 0x7) << 2)) * scale + bias; + out[7] = ((w[4] & 0xf8) >> 3) * scale + bias; + } else if (bits == 6) { + w += offset * bytes_per_pack; + out[0] = (w[0] & 0x3f) * scale + bias; + out[1] = (((w[0] >> 6) & 0x03) + ((w[1] & 0x0f) << 2)) * scale + bias; + out[2] = (((w[1] >> 4) & 0x0f) + ((w[2] & 0x03) << 4)) * scale + bias; + out[3] = ((w[2] >> 2) & 0x3f) * scale + bias; + } else { + uint val = w[offset]; +#pragma clang loop unroll(full) + for (int i = 0; i < pack_factor; i++) { + uint8_t d; + if (bits == 1) { + d = (val >> i) & 0x01; + } else if (bits == 2) { + d = (val >> (bits * i)) & 0x03; + } else if (bits == 4) { + d = (val >> (bits * i)) & 0x0f; + } else if (bits == 8) { + d = val; + } + out[i] = scale * d + bias; + } + } +} diff --git a/zig/kernels/metal/deepseek_v41/cand.metal b/zig/kernels/metal/deepseek_v41/cand.metal index 0cc1d371f49..7bc23326ff5 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 bc38d948b39..46ecb4b70c6 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. [[kernel, max_total_threads_per_threadgroup(32)]] void tf_dsv41_c_pool2( @@ -78,6 +79,7 @@ struct TfCPoolArgs { 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). [[kernel, max_total_threads_per_threadgroup(32)]] void tf_dsv41_c_fp4rt( @@ -108,6 +110,7 @@ struct TfCRtArgs { 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). [[kernel, max_total_threads_per_threadgroup(32)]] void tf_dsv41_c_fp4pack( diff --git a/zig/kernels/metal/deepseek_v41/csa2.metal b/zig/kernels/metal/deepseek_v41/csa2.metal new file mode 100644 index 00000000000..797ee647e05 --- /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; // ROUND-365: 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 dc6bb83fb98..cf52c26d21a 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..2ebde2b8f7b --- /dev/null +++ b/zig/kernels/metal/deepseek_v41/csa2_nax.metal @@ -0,0 +1,493 @@ +// DSV41's prompt sparse attention on the tensor units: GLM's fragment structure over the packed cache. +// Compiled by csa2.zig after kv.metal (the exact packed-cache decoders) and csa2.metal (Dsv41Attention); +// nax.h is inlined at load, so the same text also builds for GPUs without tensor units (per-element decode). +#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, the bare position for a window one. The window and pick rules are csa2.metal's, byte for byte. +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 (or 2 for +// the nibble rows) in practice, but only the pointer says so for sure. +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, so the +// mma's bf16 products are the scalar's products. Missing keys decode to zero (their score is NO_SCORE anyway). +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 over each row's +// window plus its compressed picks. grid (head groups, rows); one threadgroup of four simdgroups per row. +[[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]; // the running max and sum of this lane's two heads (the scalar's -1e30 start) + 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; a split takes a slice of it and the merge + // kernel sums the online-softmax parts in split order. + 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). + // The row offset a key's loads need is resolved here, once, beside the slot -- it used to be recomputed by + // every load of every fragment (4,480 times a block). + if (s == 0 && lane < uint(BLOCK)) { + const int enc = j0 + lane < count ? 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, so the values are four loads and not four + // packed decodes: same bytes, a thirteenth of the arithmetic. + 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. + // Each of the four SIMDgroups holds its own 128-dimensional slice, so the parts are keyed by SIMDgroup too. + 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, so +// the dense rows keep their position indexing and the sparse kernel is unchanged. +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; +} + +// ROUND-402 (the arm): THE MERGE'S GRID IS FOUR THREADGROUPS. The shipped merge gives each threadgroup +// sixteen heads and all four simdgroups' dims, so the whole layer's reduction runs on 4 x 128 = 512 threads +// -- and it costs 35 us a layer (1.40 ms a token, priced by the round's doubling arm). This form gives each +// threadgroup ONE of the four accumulator chunks: the grid is four times wider (16 threadgroups), each lane +// reads its own chunk's sixteen floats per split (the same traffic, the same split order, the same per +// output sums) and the fragment's dim offset is the chunk's own -- so the output is BIT-IDENTICAL. +[[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/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 af126a54e02..a84de21e26a 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..229e377d557 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( @@ -89,6 +90,7 @@ 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). diff --git a/zig/kernels/metal/deepseek_v41/fp8_mma.metal b/zig/kernels/metal/deepseek_v41/fp8_mma.metal index 04efa73b1d8..bf3d16e43be 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 one decoded 32x32 weight block a K group diff --git a/zig/kernels/metal/deepseek_v41/fp8_rows.metal b/zig/kernels/metal/deepseek_v41/fp8_rows.metal index 02593756f8e..e70096a97b2 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/fused.metal b/zig/kernels/metal/deepseek_v41/fused.metal index 61b85f63c55..a3c463e0b2c 100644 --- a/zig/kernels/metal/deepseek_v41/fused.metal +++ b/zig/kernels/metal/deepseek_v41/fused.metal @@ -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( @@ -138,6 +139,7 @@ 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. template @@ -199,6 +201,7 @@ 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]. [[kernel, max_total_threads_per_threadgroup(256)]] void tf_dsv41_f_kv( @@ -246,6 +249,7 @@ 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. kernel void tf_dsv41_f_swiglu(const device bfloat* G [[buffer(0)]], const device bfloat* U [[buffer(1)]], @@ -262,6 +266,7 @@ 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). kernel void tf_dsv41_f_joinpost(const device float* RT [[buffer(0)]], const device bfloat* SH [[buffer(1)]], @@ -335,6 +340,7 @@ 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. kernel void tf_dsv41_f_actq(const device bfloat* X [[buffer(0)]], device bfloat* Y [[buffer(1)]], 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_tmp.metal index 4e24a6fa386..c6e72f732a2 100644 --- a/zig/kernels/metal/deepseek_v41/glue_tmp.metal +++ b/zig/kernels/metal/deepseek_v41/glue_tmp.metal @@ -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_tmp'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 S = 4, D = 5120, F = S * D, MIX = (2 + S) * S, SLICES = F / 1024; + +struct HcArgs { float eps; float hc_eps; int iters; }; +static_assert(sizeof(HcArgs) == 12, "HcArgs must mirror mhc.zig's BoundaryArgs"); + +inline float hc_bf(float v) { return float(bfloat(v)); } + +// The mixes' partial sums: a threadgroup a (1024-column slice, row), 24 products and a sum of squares to PART. +[[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 red[8][MIX + 1]; + const int j = int(tg.x), r = int(tg.y); + const uint t = tpos.x; + const device bfloat* x = X + size_t(r) * F + 1024 * j + 4 * int(t); + float v[4]; + for (int i = 0; i < 4; i++) v[i] = float(x[i]); + float acc[MIX + 1]; + acc[MIX] = v[0] * v[0] + v[1] * v[1] + v[2] * v[2] + v[3] * v[3]; + for (int m = 0; m < MIX; m++) { + const device float* f = FN + size_t(m) * F + 1024 * j + 4 * int(t); + acc[m] = f[0] * v[0] + f[1] * v[1] + f[2] * v[2] + f[3] * v[3]; + } + for (int m = 0; m <= MIX; m++) { + const float s = simd_sum(acc[m]); + if (lane == 0) red[sg][m] = s; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (int(t) <= MIX) { + float s = 0.0f; + for (int k = 0; k < 8; k++) s += red[k][t]; + PART[(size_t(r) * SLICES + j) * (MIX + 1) + t] = s; + } +} + +// The pending branch into XO and the slice's mix sums from the bf16 written: one pass over the streams. +[[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 red[8][MIX + 1]; + 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 / D, d0 = col % D; + const device bfloat* x = X + size_t(r) * F; + const device float* cm = COMB + r * S * S; + float v[4]; + for (int i = 0; i < 4; i++) { + const int d = d0 + i; + const float b = float(BR[size_t(r) * D + d]); + float xs[S]; + for (int jj = 0; jj < S; jj++) xs[jj] = float(x[jj * D + d]); + float mm = 0.0f; + for (int jj = 0; jj < S; jj++) mm += cm[jj * S + k] * xs[jj]; + const bfloat o = bfloat(POST[r * S + k] * b + mm); + XO[size_t(r) * F + col + i] = o; + v[i] = float(o); + } + float acc[MIX + 1]; + acc[MIX] = v[0] * v[0] + v[1] * v[1] + v[2] * v[2] + v[3] * v[3]; + for (int m = 0; m < MIX; m++) { + const device float* f = FN + size_t(m) * F + col; + acc[m] = f[0] * v[0] + f[1] * v[1] + f[2] * v[2] + f[3] * v[3]; + } + for (int m = 0; m <= MIX; m++) { + const float s = simd_sum(acc[m]); + if (lane == 0) red[sg][m] = s; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (int(t) <= MIX) { + float s = 0.0f; + for (int q = 0; q < 8; q++) s += red[q][t]; + PART[(size_t(r) * SLICES + j) * (MIX + 1) + t] = s; + } +} + +// A threadgroup of 1024 a row: (MIXES) the boundary's pre, post and Sinkhorn comb; the streams collapsed and normed. +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 red[32][MIX + 1]; + threadgroup float tot[MIX + 1]; + threadgroup float pre_in[S]; + const device bfloat* x = X + size_t(r) * F; + // the mixes' totals beside the previous boundary's lagged collapse, which overlaps the split's rms reduction + if (MIXES && int(t) <= MIX) { + float s = 0.0f; + for (int j = 0; j < SLICES; j++) s += PART[(size_t(r) * SLICES + j) * (MIX + 1) + t]; + tot[t] = s; + } + if (t < uint(S)) pre_in[t] = PRE_IN[r * S + t]; + threadgroup_barrier(mem_flags::mem_threadgroup); + float ys[5]; + float ss = 0.0f; + for (int i = 0; i < 5; i++) { + const int d = int(t) + 1024 * i; + float y = 0.0f; + for (int s = 0; s < S; s++) y += pre_in[s] * float(x[s * D + d]); + ys[i] = hc_bf(y); + ss += ys[i] * ys[i]; + } + const float s1 = simd_sum(ss); + if (lane == 0) red[sg][0] = s1; + threadgroup_barrier(mem_flags::mem_threadgroup); + // the split on simdgroup 0: a pre and post a lane (0-3), a comb cell a lane (0-15), row and column sums by xor + if (MIXES && sg == 0) { + const float rs = precise::rsqrt(tot[MIX] / float(F) + a.eps); + if (lane < uint(S)) { + PRE_OUT[r * S + lane] = 1.0f / (1.0f + precise::exp(-(tot[lane] * rs * SCALE[0] + BASE[lane]))) + a.hc_eps; + POST_OUT[r * S + lane] = 2.0f / (1.0f + precise::exp(-(tot[S + lane] * rs * SCALE[1] + BASE[S + lane]))); + } + const bool act = lane < uint(S * S); + const uint cell = act ? lane : 0; + const float v = tot[2 * S + cell] * rs * SCALE[2] + BASE[2 * S + cell]; + float mx = max(v, simd_shuffle_xor(v, ushort(1))); + mx = max(mx, simd_shuffle_xor(mx, ushort(2))); + const float e = precise::exp(v - mx); + float row = e + simd_shuffle_xor(e, ushort(1)); + row = row + simd_shuffle_xor(row, ushort(2)); + float cm = act ? e / row + a.hc_eps : 0.0f; + for (int it = 0; it < a.iters; it++) { + if (it > 0) { + float rsum = cm + simd_shuffle_xor(cm, ushort(1)); + rsum = rsum + simd_shuffle_xor(rsum, ushort(2)); + cm = act ? cm / (rsum + a.hc_eps) : 0.0f; + } + float csum = cm + simd_shuffle_xor(cm, ushort(4)); + csum = csum + simd_shuffle_xor(csum, ushort(8)); + cm = act ? cm / (csum + a.hc_eps) : 0.0f; + } + if (act) COMB_OUT[r * S * S + lane] = cm; + } + if (t == 32) { // simdgroup 1, while simdgroup 0 runs the split + float s = 0.0f; + for (int k = 0; k < 32; k++) s += red[k][0]; + pre_in[0] = precise::rsqrt(s / float(D) + a.eps); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + const float inv = pre_in[0]; + for (int i = 0; i < 5; i++) { + const int d = int(t) + 1024 * i; + NORMED[size_t(r) * D + d] = bfloat(float(NORMW[d]) * (ys[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; + +// ROUND-407: THE LAUNCH-OVERHEAD PROBE. A dispatch that reads the boundary's own partial sums and +// writes them back, so the split that follows DEPENDS on it: a chain of them prices the GPU's +// dependent-dispatch latency -- the piece every glue fusion would save -- and the probe's threadgroup +// size sweeps that latency's shape. The values are unchanged, so the reply cannot move. +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 * (SLICES * (MIX + 1)) + tid; + if (tid <= uint(MIX)) sink[at] = part[at]; +} + +// ROUND-407: THE INDEPENDENT-DISPATCH PROBE. The same work-free dispatch, but each one writes its OWN +// sink (the host binds a different buffer a dispatch), so the chain carries no memory dependency between +// the probe dispatches: the GPU may run them concurrently. The gap between this form and tf_hc_probe is +// the GPU's DEPENDENT-dispatch latency -- the part of the launch cost that only a FOLD (not a reorder) +// can remove. The values the boundary reads are untouched, so the reply cannot move. +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(MIX)) sink[tid] = part[tid]; +} diff --git a/zig/kernels/metal/deepseek_v41/index.metal b/zig/kernels/metal/deepseek_v41/index.metal index a5b741574b4..c1c00b751ee 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..7af784f35b9 --- /dev/null +++ b/zig/kernels/metal/deepseek_v41/index_exl3.metal @@ -0,0 +1,855 @@ +// 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; + // ROUND-468: `layer` and `skip_mask` are the Zig Params' own fields (ROUND-411's removal arms). They are + // not read here, but they sit BEFORE `scale`, and leaving them out made `scale` read `layer`'s bits -- + // a denormal near zero, so every scaled weight and every score was 0.0 and the heap's ties kept the + // first 512 positions. The assert keeps the two declarations in step. + uint layer, skip_mask; + // ROUND-469: 0 = the heap path's per-row score slots (row * tile_width), 1 = the decode select's + // tile-major ones ((tile * rows + row) * tile_width, every tile resident). + 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, so a radix select on it is exact. +// -0.0f is folded to +0.0f so the two zeros cannot split a tie. +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]]) { + // A warp a key: the reduction is across its 32 lanes, so a threadgroup of W warps scores W adjacent keys and the + // dispatch needs W times fewer threadgroups (one a key cost 4.8e9 of them at a 15k prompt). Four keys a warp with + // the query hoisted measured slower: the state it keeps costs more than the loads it saves. + const uint warps = tptg.x / 32u, lane = tid % 32u; + // The query's scaled per-head weights do not depend on the key, and every warp of a threadgroup scores a + // different key: compute them once here instead of once for every key a warp handles. + 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: the +// table a tensor-unit score tile stages in threadgroup memory. Same rounding as the scorer's own +// dsv41_unpack, so a table read and a packed read give the same values. +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, so the picks are the +// identity in ascending position order -- the same set, in the same order, that the score/heap/sort path +// returns for those keys. The identity's row bound is the same visible formula the merge uses. +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, so the +// parallel filter never starts against a root of -infinity. A layer's first tile used to insert all 4096 +// of its keys on one thread; it now inserts topk and hands the rest to the filter. +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. The comparator is a total order (score, then +// position), so which keys reach the heap does not depend on the order they arrive in and the compacted +// list needs no ordering of its own. Keys the running worst already beats are dropped here; the insert +// re-checks anyway, so a permissive filter changes nothing. +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; + // A per-key atomic: warp aggregation measured wrong here (the suite's index case rejects it), so the + // counter stays one increment a kept key until that is understood. + 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 (and the candidate-block highs, which are +// a block a pass and stay here because they are one a tile). +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. Only the valid picks + // matter — attention skips an invalid one — so they are compacted first and the sort then costs what the live + // keys cost, not what the slots cost. + 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); +} + +// ROUND-411: the finish's PARALLEL form -- a threadgroup a row instead of one THREAD a row. The shipped +// finish sorts the row's topk picks with an insertion sort (~65k moves a row at topk 512), one thread +// a row: the removal arms put ~46 ms of the block's 69 ms a prompt in that sort. This form stages the +// picks' positions in threadgroup memory and sorts them with a bitonic sort: the keys are the +// positions (the invalid ones share the last key, so they land last, where the insertion sort's +// compaction leaves them), the valid ones are distinct, so the ascending order is the same array the +// insertion sort produced -- BIT-IDENTICAL, and nothing downstream moves. +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); + } +} + + +// ---------------------------------------------------------------- prompt scores on the tensor units +// The scalar scorer's arithmetic, a tile at a time: 64 keys by 64 rows, four SIMDgroups of 32x32, the +// 64x128 key tile staged once and read by every row group; one 128-dim transposed MMA a head instead of a +// warp a key with sixty-four simd_sums. The epilogue is the scalar kernel's own term -- bf16 dot, relu, times +// the bf16-rounded scaled weight, summed in fp32 in head order -- so only the dot's summation order differs. +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])); + } + } + } +} + +// ---------------------------------------------------------------- the decode-shaped score tile (ROUND-470) +// The prompt tile above scores a 64-row by 64-key tile, so ONE decode row pays 64 rows of tensor-unit work +// (its dispatch count and its bytes are small; 98.4 % of the MMAs are dead). This is that kernel's own body +// with the tile's row extent cut to sixteen -- the MMA's M granularity, so nothing narrower can help -- and +// the same operand roles, the same 128-dim k steps in the same order, the same epilogue term by term and +// the same store expression, so a live row's score is BIT-IDENTICAL to dsv41_index_scores_nax's. A +// threadgroup keeps its 64 keys and two SIMDgroups take 32 keys each (tn), the other two stage and stop: +// the tile's MMA work is a quarter of the prompt tile's at one row whatever the window's row count. +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 (ROUND-481) +// The row tile above cuts the prompt tile's row extent to the MMA's sixteen, but a one-row step still runs a +// sixteen-row MMA: fifteen of sixteen M rows are dead. This form swaps the operand roles -- the KEYS are the +// M operand (four 16-key blocks, one a SIMDgroup) and the head queries are the N operand (32 heads) -- so a +// threadgroup scores 64 keys x 32 heads with eight MMAs a SIMDgroup instead of a quarter of 1024. The k +// chain (128 dims in sixteen-wide steps, ascending), the per-head term (bf16 dot, relu, the bf16-rounded +// scaled weight) and the head-ordered fp32 sum are the scalar's own: the head terms are staged as bf16 (the +// value is already bf16) and summed 0..31 in order by one lane a key, so a score is BIT-IDENTICAL to +// dsv41_index_scores_row's. The key tile is staged once and reused by every row of the window. +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, one dispatch +// ROUND-469: at decode rows the heap path costs 27 dispatches and ~1,000 one-thread pushes a source. This +// does the same selection in ONE threadgroup a row: a radix select on the score's monotone image (four +// 8-bit passes over the resident scores) fixes the k-th largest exactly, a threshold filter keeps the k +// keys above it (plus the lowest-positioned ties), and the finish's bitonic sort writes the ascending +// positions. The heap's total order is (score desc, position asc), so the SET and the array are the same. +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; + // ROUND-526: digit/ran are threadgroup memory. Initialising them here was a race: every + // thread wrote 0 to them and tid 0 wrote the chosen digit, with no ordering between the two + // writes before the barrier, so a late thread's zero could land on top of the digit. A zero + // prefix then made the next pass's histogram empty and the filter count every visible key as + // above the threshold, which the first 512 atomic arrivals truncated -- a nondeterministic + // key SET from unchanged scores. Only tid 0 writes them now, and it writes them once. + 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); + // ROUND-526: the ties pass below reuses this counter, so it has to be zeroed AFTER every thread + // has read `have`. Without the barrier the zero could land first and leave `have` divergent + // across the threadgroup -- the ties then got written at different slots (and the sentinel fill + // started at a different index) per thread, which is a second nondeterministic key SET. + 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]); +} + + + +// ROUND-483: the one-dispatch select with vector reads, a two-pass radix and the ties folded into the +// filter. Exactness: every score this path ranks is bf16-valued (the scorer stores dsv41_bf(x)), so +// mono(score)'s low 16 bits are zero and its top 16 bits fix the order; two 8-bit passes converge on +// the k-th image. The filter/ties compaction order differs from the shipped kernel's, but the array +// is sorted before it is written, so the output is the same array. +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; + // ROUND-526: digit/ran are threadgroup memory. Initialising them here was a race: every + // thread wrote 0 to them and tid 0 wrote the chosen digit, with no ordering between the two + // writes before the barrier, so a late thread's zero could land on top of the digit. A zero + // prefix then made the next pass's histogram empty and the filter count every visible key as + // above the threshold, which the first 512 atomic arrivals truncated -- a nondeterministic + // key SET from unchanged scores. Only tid 0 writes them now, and it writes them once. + 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 and 0xFFFF for a negative one (mono is b's complement there), so the full + // image is (prefix << 16) | (negative ? 0xFFFF : 0). + 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..147baf236e7 --- /dev/null +++ b/zig/kernels/metal/deepseek_v41/kv.metal @@ -0,0 +1,176 @@ +// 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); + return ushort((u + 0x7fff + ((u >> 16) & 1)) >> 16); +} +inline float dsv41_e4(uchar c) { + 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]; + } + // ROUND-367: the raw row's capture -- the row's own values and its gate, one slot a position. + // The rollback's open group is re-cut from it, so a rejected window's rows need no second + // forward (the no-re-feed port). + if (p.capture_rows != 0) { + 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]; +} +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)); +} + +// ROUND-398: the window ring's slot stash/restore. A verify window publishes every row it writes, +// including rows the round later rejects; once the ring has wrapped (position > 128) a rejected +// row's slot aliases a position that is still visible to the next forward. `beginSlot` stashes the +// slots the window is about to overwrite, and the keep path puts the rejected ones back. +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..ab91ccad463 --- /dev/null +++ b/zig/kernels/metal/deepseek_v41/kv_glue.metal @@ -0,0 +1,85 @@ +// DeepSeek V4.1 served engine: the window KV's RMS norm + RoPE + fp8 cache pack as ONE dispatch, at the +// pack's own threadgroup geometry (16 threadgroups a row, 256 threads each). Each threadgroup recomputes +// the row's RMS with the shipped dsv41_rms kernel's reduction order (t and t+256, xor butterfly 16..1, +// part[8] summed in order) and packs its own 32-value block; the blocks are disjoint, so the norm reads +// are read-only and there is no cross-threadgroup race. The rope expression is rope.metal's source, +// bit for bit; the pack expression is kv.metal's dsv41_pack, bit for bit. This translation unit +// deliberately does NOT set fp contract(off): rope.metal is compiled without it and the rotation must +// contract (or not) exactly as it does there. +#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)); +} + +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]; + 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(p.position + g.y) * (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; +} diff --git a/zig/kernels/metal/deepseek_v41/mhc.metal b/zig/kernels/metal/deepseek_v41/mhc.metal new file mode 100644 index 00000000000..6cc3208b732 --- /dev/null +++ b/zig/kernels/metal/deepseek_v41/mhc.metal @@ -0,0 +1,437 @@ +// 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. The shipped kernel spends one 512-thread threadgroup on one output +// cell and rereads the activation row once a column (14 GB of x a layer at prompt rows). This kernel computes a +// 4x4 cell tile per 128-thread threadgroup, stages a 512-k chunk of four activation rows and four weight rows in +// threadgroup memory, and reproduces the shipped sum exactly: each lane owns the sixteen partials +// t = lane + 32*i, so the four threadgroup tree levels over 512 become register adds (V[i] += V[i+8], then +// V[i+4], V[i+2], V[i+1]), after which every lane holds the shipped sums[t] for t = lane, and the last five +// levels are the shipped simd_shuffle_down over lanes 16, 8, 4, 2, 1. No barrier is in the reduction. +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, no threadgroup memory and no barrier. Lane l owns the +// sixteen partials t = 16*l + i, contiguous, so a lane reads one 32-byte run of a row per 512-k chunk (two uint4 +// loads) instead of sixteen 2-byte gathers. The shipped reduction order is reproduced exactly: the 512-partial +// tree levels 256/128/64/32 are simd_shuffle_xor 16/8/4/2 over the sixteen registers, the level-16 step is +// simd_shuffle_xor 1, and the last four levels are the register adds V[i] += V[i+8], V[i+4], V[i+2], V[i+1] -- +// the same pairs, in the same order, as dsv41_dense_col's threadgroup tree followed by its warp tree. +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)); +} +// ROUND-349: the same bit-exact gate on a wider threadgroup with the x and w tiles staged in threadgroup +// memory. The shipped gate is a warp a 2x2 cell tile, so the whole x (37 MB) is re-read by each of the 192 +// column pairs and the whole w (3.93 MB) by each of the 1,810 row pairs: 14.2 GB a layer, 2.46 TB/s of L2 -- +// the box's L2 rate, while the arithmetic is 1.23 TMAC/s and the ALU floor is 0.55 ms. A threadgroup that covers +// eight rows and four columns, with the tiles staged once, cuts that traffic 2.7x. +// +// The order is untouched: a lane still owns the sixteen consecutive partials t = 16*lane + i of every 512-k +// chunk, still accumulates the chunks in order, and the tree is the same (simd_shuffle_xor 16/8/4/2 over the +// sixteen registers, then shuffle_xor 1, then the register adds V[i] += V[i+8], V[i+4], V[i+2], V[i+1]). So the +// gate's logits are bit-identical and the router's picks cannot move. +#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. Sixteen bytes a + // thread (eight ushorts), so the global reads coalesce; a scalar copy here is eight times the traffic. + 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/ops.metal b/zig/kernels/metal/deepseek_v41/ops.metal new file mode 100644 index 00000000000..f3724a70113 --- /dev/null +++ b/zig/kernels/metal/deepseek_v41/ops.metal @@ -0,0 +1,325 @@ +// 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"); +// ---------------------------------------------------------------- one column a SIMDgroup (ROUND-482) +// The four-column form above gives a 2-threadgroup grid for a 32-wide projection (the indexer's +// weights_proj), and at 1 row it reads as 0.26 ms: 128 threads each chain four columns' 160 k-steps and the +// loads sit inside rd()'s dtype branch. This is the SAME per-column work (lane k-stride 32, the 16..1 +// butterfly, dense_add's compensated order) with one column a SIMDgroup and one load a step, so its output is +// BIT-IDENTICAL and the grid is ceil(n/4) threadgroups; measured 203 -> 39 us at n=32, k=5120. +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); + } +} + +// ROUND-546: the one-column dot with the weight dtype resolved at compile time and four k-steps of loads +// hoisted. The dense_add sequence is the shipped one (lane, lane+32, lane+64, lane+96, ...), so the output is +// bit-identical; only the loads move ahead of the adds. The caller picks k % 128 == 0. +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