mlx_native/kernel_registry.rs
1//! [`KernelRegistry`] — lazy compilation and caching of Metal compute pipelines.
2//!
3//! MSL shader source is embedded at compile time via `include_str!`. On first
4//! access, the source is compiled into a Metal library, the named function is
5//! extracted, and a `ComputePipelineState` is created and cached. Subsequent
6//! calls return the cached pipeline.
7//!
8//! ## Precompiled `.metallib` fast path
9//!
10//! `build.rs` runs `xcrun metal -O3` on every `.metal` file under
11//! `src/shaders/` and links the results into a single `default.metallib`
12//! placed in `OUT_DIR`. We embed the bytes via `include_bytes!`.
13//!
14//! When `MLX_PRECOMPILED_METALLIB=1` is set, `get_pipeline` and
15//! `get_pipeline_with_constants` first try to resolve the kernel function
16//! against this precompiled library; if found, build the pipeline from it
17//! (saves Apple's runtime source-compile pass). On any failure (function
18//! missing, empty embedded blob, load error) the code transparently falls
19//! back to the original source-compile path — byte-identical behavior.
20//!
21//! Default-ON; precompiled gives ~+6% on gemma4 Q-sliding decode (M5 Max).
22
23use std::collections::HashMap;
24use std::sync::OnceLock;
25
26use metal::{ComputePipelineDescriptor, ComputePipelineState, FunctionConstantValues, MTLDataType};
27
28use crate::error::{MlxError, Result};
29
30/// Bytes of the precompiled `default.metallib` produced by `build.rs` from
31/// every `src/shaders/*.metal` file. Empty when `MLX_NATIVE_SKIP_METALLIB`
32/// was set at build time or xcrun was unavailable.
33const EMBEDDED_METALLIB: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/default.metallib"));
34
35/// Returns `true` when the precompiled `.metallib` fast path is enabled
36/// (default-ON). Set `MLX_PRECOMPILED_METALLIB=0` (or `false`, `off`)
37/// to opt out — useful for diagnosing kernel-compile regressions or
38/// A/B benching.
39fn precompiled_enabled() -> bool {
40 static FLAG: OnceLock<bool> = OnceLock::new();
41 *FLAG.get_or_init(|| {
42 match std::env::var("MLX_PRECOMPILED_METALLIB").as_deref() {
43 Ok("0") | Ok("false") | Ok("off") => false,
44 _ => true,
45 }
46 })
47}
48
49/// Returns `true` when the precompiled `.metallib` is consulted for
50/// `get_pipeline_with_constants` (FCV-specialized) kernels. Inherits
51/// the master gate [`precompiled_enabled`]; both must be ON for the
52/// FCV path to use precompiled. Default-ON.
53fn precompiled_fcv_enabled() -> bool {
54 static FLAG: OnceLock<bool> = OnceLock::new();
55 *FLAG.get_or_init(|| {
56 match std::env::var("MLX_PRECOMPILED_METALLIB_FCV").as_deref() {
57 Ok("0") | Ok("false") | Ok("off") => false,
58 _ => true,
59 }
60 })
61}
62
63// MTLDataType numeric values (from metal-rs argument.rs, confirmed in Apple Metal spec):
64// Int = 29
65// Bool = 53
66// These are used when calling set_constant_value_at_index so the Metal runtime
67// knows how wide each constant value is.
68
69/// Registry that lazily compiles and caches Metal compute pipelines from
70/// embedded MSL source.
71///
72/// # Usage
73///
74/// ```ignore
75/// let mut registry = KernelRegistry::new();
76/// let pipeline = registry.get_pipeline("elementwise_add", device.metal_device())?;
77/// encoder.encode(&pipeline, &buffers, grid, tg);
78/// ```
79///
80/// # Thread Safety
81///
82/// `KernelRegistry` is **not** `Sync` by default (it uses `&mut self` for
83/// `get_pipeline` to allow mutable cache insertion). If you need concurrent
84/// access, wrap it in a `Mutex` or use one registry per thread.
85pub struct KernelRegistry {
86 /// Cached pipelines keyed by kernel function name.
87 cache: HashMap<String, ComputePipelineState>,
88 /// MSL source text keyed by kernel function name.
89 ///
90 /// Populated at construction time with all embedded shader sources.
91 sources: HashMap<String, &'static str>,
92 /// Precompiled `default.metallib` (lazy).
93 ///
94 /// `None` initially. On first `get_pipeline*` call under
95 /// `MLX_PRECOMPILED_METALLIB=1`, populated via
96 /// `device.new_library_with_data(EMBEDDED_METALLIB)` — or set to a
97 /// sentinel "load-failed" marker (still `None`) so we don't retry.
98 /// Set to `Some(library)` on success.
99 ///
100 /// Lazily filled because we need a `&metal::DeviceRef` to load it
101 /// and `KernelRegistry::new()` does not have one.
102 precompiled_lib: Option<metal::Library>,
103 /// Whether we've already attempted to load the precompiled library.
104 /// Prevents repeated load attempts on failure.
105 precompiled_load_attempted: bool,
106}
107
108impl KernelRegistry {
109 /// Create a new registry with all embedded shader sources pre-registered.
110 ///
111 /// No compilation happens here — shaders are compiled lazily on first use.
112 pub fn new() -> Self {
113 let mut sources = HashMap::new();
114
115 // Register embedded shader sources.
116 sources.insert(
117 "placeholder".into(),
118 include_str!("shaders/placeholder.metal"),
119 );
120 sources.insert(
121 "quantized_matmul".into(),
122 include_str!("shaders/quantized_matmul.metal"),
123 );
124 sources.insert(
125 "quantized_matmul_simd".into(),
126 include_str!("shaders/quantized_matmul.metal"),
127 );
128 sources.insert(
129 "quantized_matmul_simd_bf16".into(),
130 include_str!("shaders/quantized_matmul.metal"),
131 );
132 sources.insert(
133 "quantized_matmul_simd_bf16_expert".into(),
134 include_str!("shaders/quantized_matmul.metal"),
135 );
136
137 // GGML block-format quantized mat-vec kernels (ADR-006 Phase 3)
138 let ggml_src: &'static str =
139 include_str!("shaders/quantized_matmul_ggml.metal");
140 sources.insert("kernel_mul_mv_q4_0_f32".into(), ggml_src);
141 sources.insert("kernel_mul_mv_q8_0_f32".into(), ggml_src);
142 // ADR-028 iter-368: peer-style NSG=4 NR=2 variant (128 threads/TG).
143 sources.insert("kernel_mul_mv_q8_0_f32_nr2".into(), ggml_src);
144 sources.insert("kernel_mul_mv_q6_K_f32".into(), ggml_src);
145 // ADR-028 iter-309 — q6_K mat-vec with nr0=2 + cached yl[16]
146 // (peer-pattern port of llama.cpp's `kernel_mul_mv_q6_K_f32_impl`
147 // with N_R0_Q6_K=2; 4 rows/TG vs baseline's 2). Env-gated via
148 // `HF2Q_Q6K_MV_NR2=1` in the dispatcher.
149 sources.insert("kernel_mul_mv_q6_K_f32_nr2".into(), ggml_src);
150 // ADR-022 Phase 1 — Q5_1 / IQ4_NL dense mat-vec.
151 sources.insert("kernel_mul_mv_q5_1_f32".into(), ggml_src);
152 sources.insert("kernel_mul_mv_iq4_nl_f32".into(), ggml_src);
153 // ADR-013 P7 — Q4_K dense decode mat-vec (port of llama.cpp's
154 // kernel_mul_mv_q4_K_f32 at ggml-metal.metal:7715-7821).
155 sources.insert("kernel_mul_mv_q4_K_f32".into(), ggml_src);
156 // ADR-022 Phase 2 — Q5_K dense mv kernel.
157 sources.insert("kernel_mul_mv_q5_K_f32".into(), ggml_src);
158
159 // GGML block-format quantized matrix-matrix kernels
160 // (ADR-011 Phase 3 Wave P3a: port of llama.cpp's kernel_mul_mm_<q>_f32).
161 // Used at prefill m > 8 to reuse each weight tile across a 32-row
162 // block via threadgroup-staged simdgroup MMA, instead of re-reading
163 // every block per prompt-token as the mv kernel does.
164 let ggml_mm_src: &'static str =
165 include_str!("shaders/quantized_matmul_mm.metal");
166 sources.insert("kernel_mul_mm_q4_0_f32".into(), ggml_mm_src);
167 sources.insert("kernel_mul_mm_q8_0_f32".into(), ggml_mm_src);
168 sources.insert("kernel_mul_mm_q6_K_f32".into(), ggml_mm_src);
169 // ADR-022 Phase 1 — dense Q5_1 / IQ4_NL mm.
170 sources.insert("kernel_mul_mm_q5_1_f32".into(), ggml_mm_src);
171 sources.insert("kernel_mul_mm_iq4_nl_f32".into(), ggml_mm_src);
172 // ADR-022 Phase 2 — dense Q5_K mm.
173 sources.insert("kernel_mul_mm_q5_K_f32".into(), ggml_mm_src);
174 // ADR-022 Phase 3 — dense Q4_K mm.
175 sources.insert("kernel_mul_mm_q4_K_f32".into(), ggml_mm_src);
176
177 // GGML block-format quantized matrix-matrix kernels — tensor API
178 // variant (ADR-011 Phase 3 Wave P3b-tensor: port of llama.cpp's
179 // kernel_mul_mm_impl `#ifdef GGML_METAL_HAS_TENSOR` branch).
180 // Uses Apple's MetalPerformancePrimitives `tensor_ops::matmul2d`
181 // primitive which on M3+ dispatches to hardware tensor cores for
182 // 2-3x the effective FLOP throughput vs the simdgroup MMA path.
183 // Only compiled on devices where the tensor API is available; the
184 // kernel_registry's runtime-probe (see MlxDevice::has_tensor) gates
185 // compilation so non-tensor devices transparently fall back to the
186 // non-tensor `kernel_mul_mm_<q>_f32` kernels.
187 let ggml_mm_tensor_src: &'static str =
188 include_str!("shaders/quantized_matmul_mm_tensor.metal");
189 sources.insert("kernel_mul_mm_q4_0_tensor_f32".into(), ggml_mm_tensor_src);
190 sources.insert("kernel_mul_mm_q4_0_tensor_bf16_perm021".into(), ggml_mm_tensor_src);
191 sources.insert("kernel_mul_mm_q6_K_tensor_bf16_perm021".into(), ggml_mm_tensor_src);
192 sources.insert("kernel_mul_mm_q8_0_tensor_f32".into(), ggml_mm_tensor_src);
193 sources.insert("kernel_mul_mm_q6_K_tensor_f32".into(), ggml_mm_tensor_src);
194 // ADR-022 Phase 1 — Q5_1 / IQ4_NL tensor mm.
195 sources.insert("kernel_mul_mm_q5_1_tensor_f32".into(), ggml_mm_tensor_src);
196 sources.insert("kernel_mul_mm_iq4_nl_tensor_f32".into(), ggml_mm_tensor_src);
197 // ADR-022 Phase 2 — Q5_K tensor mm.
198 sources.insert("kernel_mul_mm_q5_K_tensor_f32".into(), ggml_mm_tensor_src);
199 // ADR-022 Phase 3 — Q4_K tensor mm + Q8_0 perm021.
200 sources.insert("kernel_mul_mm_q4_K_tensor_f32".into(), ggml_mm_tensor_src);
201 sources.insert("kernel_mul_mm_q8_0_tensor_bf16_perm021".into(), ggml_mm_tensor_src);
202 // ADR-029 iter-30 H29-speed — F16-weight V2 large-tile mm.
203 // Same source file as the V2 quantized variants; reads F16 weight
204 // directly from device memory (no per-call dequant). Used when
205 // MlxQWeight.f16_shadow is populated and m > MM_ROUTING_THRESHOLD.
206 sources.insert("hf2q_mul_mm_tensor_v2_f16".into(), ggml_mm_tensor_src);
207 // ADR-029 iter-36 H28-D — F16-weight perm021 mm for O-projection.
208 // Same source file; reads F16 weight from MlxQWeight.f16_shadow when
209 // populated, bypassing the per-call quantized dequant. B-stage
210 // (bfloat permuted [n_heads, seq_len, head_dim] input) is byte-
211 // identical to the quantized variant.
212 sources.insert("kernel_mul_mm_f16_tensor_bf16_perm021".into(), ggml_mm_tensor_src);
213 // ADR-029 iter-23 H28-A — V2 large-tile tensor mm (NRA=64 M, NRB=128 N).
214 // Same source file as V1 tensor mm; distinct kernel host names so the
215 // dispatcher can pick V1 vs V2 at runtime via HF2Q_LARGE_TILE_MM.
216 sources.insert("kernel_mul_mm_q4_0_tensor_v2_f32".into(), ggml_mm_tensor_src);
217 sources.insert("kernel_mul_mm_q8_0_tensor_v2_f32".into(), ggml_mm_tensor_src);
218 sources.insert("kernel_mul_mm_q6_K_tensor_v2_f32".into(), ggml_mm_tensor_src);
219 sources.insert("kernel_mul_mm_q5_1_tensor_v2_f32".into(), ggml_mm_tensor_src);
220 sources.insert("kernel_mul_mm_iq4_nl_tensor_v2_f32".into(), ggml_mm_tensor_src);
221 sources.insert("kernel_mul_mm_q5_K_tensor_v2_f32".into(), ggml_mm_tensor_src);
222 sources.insert("kernel_mul_mm_q4_K_tensor_v2_f32".into(), ggml_mm_tensor_src);
223 // ADR-029 iter-28 H29 — whole-tensor dequant from block_q → F16.
224 // Used at model load to materialize an F16 shadow of attn/dense MLP
225 // weights so the runtime dispatch can use kernel_mul_mm_f16_f32_*
226 // (peer's gemma4 pattern). Trades ~1 GB resident memory for 2-3×
227 // faster per-call dense matmul at prefill.
228 let dequant_to_f16_src: &'static str =
229 include_str!("shaders/dequant_to_f16.metal");
230 sources.insert("hf2q_dequant_q4_0_to_f16".into(), dequant_to_f16_src);
231 sources.insert("hf2q_dequant_q8_0_to_f16".into(), dequant_to_f16_src);
232 sources.insert("hf2q_dequant_q5_1_to_f16".into(), dequant_to_f16_src);
233 sources.insert("hf2q_dequant_iq4_nl_to_f16".into(), dequant_to_f16_src);
234 sources.insert("hf2q_dequant_q4_K_to_f16".into(), dequant_to_f16_src);
235 sources.insert("hf2q_dequant_q5_K_to_f16".into(), dequant_to_f16_src);
236 sources.insert("hf2q_dequant_q6_K_to_f16".into(), dequant_to_f16_src);
237
238 // ADR-022 Phase 1 P1.7 — Q5_1 / IQ4_NL mul_mv_ext r1 family.
239 // Eight instantiations (2 types × 4 r1ptg widths). Each PSO is
240 // additionally specialized at PSO-compile time with FC_mul_mv_nsg
241 // (function_constant 600) and FC_mul_mv_nxpsg (function_constant 601).
242 let mul_mv_ext_src: &'static str = include_str!("shaders/mul_mv_ext.metal");
243 sources.insert("kernel_mul_mv_ext_q5_1_f32_r1_2".into(), mul_mv_ext_src);
244 sources.insert("kernel_mul_mv_ext_q5_1_f32_r1_3".into(), mul_mv_ext_src);
245 sources.insert("kernel_mul_mv_ext_q5_1_f32_r1_4".into(), mul_mv_ext_src);
246 sources.insert("kernel_mul_mv_ext_q5_1_f32_r1_5".into(), mul_mv_ext_src);
247 sources.insert("kernel_mul_mv_ext_iq4_nl_f32_r1_2".into(), mul_mv_ext_src);
248 sources.insert("kernel_mul_mv_ext_iq4_nl_f32_r1_3".into(), mul_mv_ext_src);
249 sources.insert("kernel_mul_mv_ext_iq4_nl_f32_r1_4".into(), mul_mv_ext_src);
250 sources.insert("kernel_mul_mv_ext_iq4_nl_f32_r1_5".into(), mul_mv_ext_src);
251 // ADR-022 Phase 4 — Q4_0 / Q8_0 / Q4_K / Q5_K / Q6_K mv_ext.
252 // 5 types × 4 r1ptg widths = 20 instantiations.
253 for r1 in [2, 3, 4, 5].iter() {
254 for ty in ["q4_0", "q8_0", "q4_K", "q5_K", "q6_K"].iter() {
255 let name = format!("kernel_mul_mv_ext_{ty}_f32_r1_{r1}");
256 sources.insert(name, mul_mv_ext_src);
257 }
258 }
259
260 // Dense bf16×f32 → f32 tensor-API matmul (non-flash-attention
261 // prefill Q@K^T and scores@V, modeled on llama.cpp's
262 // kernel_mul_mm_bf16_f32 with the GGML_METAL_HAS_TENSOR branch
263 // active). Tile geometry and write-back identical to the
264 // quantized tensor kernel; only the A-stage copy (bfloat →
265 // bfloat, no dequantize) differs.
266 let dense_mm_bf16_tensor_src: &'static str =
267 include_str!("shaders/dense_mm_bf16_tensor.metal");
268 sources.insert("hf2q_dense_mm_bf16_f32_tensor".into(), dense_mm_bf16_tensor_src);
269 // ADR-029 iter-80 H60: V2 large-tile variant (NRA=64, NRB=128).
270 // Same source file (`dense_mm_bf16_tensor.metal`) — second host_name
271 // entry resolves to the V2 kernel appended at the bottom of that
272 // file. Picked at dispatch time when HF2Q_LARGE_TILE_MM=1.
273 sources.insert("hf2q_dense_mm_bf16_f32_tensor_v2".into(), dense_mm_bf16_tensor_src);
274
275 // Dense f32×f32 → f32 tensor-API matmul (F32-everywhere
276 // sibling of dense_mm_bf16_tensor). Used by hf2q's ADR-005
277 // iter-118 BF16-vs-F32 ViT attention A/B diagnostic to remove
278 // the BF16 K-stage cast as a confounding variable. Port of
279 // llama.cpp's kernel_mul_mm_f32_f32 specialization
280 // (ggml-metal.metal:10098) on the GGML_METAL_HAS_TENSOR
281 // branch. Same tile geometry (NR0=64 NR1=32 NK=32) but
282 // float-everywhere shmem staging.
283 let dense_mm_f32_f32_tensor_src: &'static str =
284 include_str!("shaders/dense_mm_f32_f32.metal");
285 sources.insert("hf2q_dense_mm_f32_f32_tensor".into(), dense_mm_f32_f32_tensor_src);
286
287 // Dense f16×f32 → f32 tensor-API matmul (F16-staging sibling
288 // of dense_mm_bf16_tensor). Used by hf2q's ADR-005 Phase 2c
289 // iter-128 gemma4v ViT precision-parity path: every mmproj
290 // weight is stored as F16 in GGUF, peer's `kernel_mul_mm_f16_f32`
291 // (`ggml-metal.metal:10099`) stages BOTH A and B as `half` in
292 // shmem and computes on `simdgroup_half8x8`. Matches peer
293 // per-element rounding budget exactly (10-bit mantissa vs
294 // BF16's 7-bit), closing the 1.16x/block cascade compound that
295 // iter-127 numerically bisected to BF16 staging. Same tile
296 // geometry as the BF16 sibling (NR0=64 NR1=32 NK=32, 8 KB
297 // shmem) — half and bfloat share 16-bit storage.
298 let dense_mm_f16_tensor_src: &'static str =
299 include_str!("shaders/dense_mm_f16_tensor.metal");
300 sources.insert("hf2q_dense_mm_f16_f32_tensor".into(), dense_mm_f16_tensor_src);
301
302 // Dense bf16×f32 → f32 GEMV (matrix-vector multiply) — optimized
303 // for M=1 single-token decode. Port of llama.cpp's
304 // kernel_mul_mv_bf16_f32_4 (bfloat4-vectorized GEMV kernel).
305 // Used in apply_linear_projection_f32 when seq_len=1 and the
306 // weight matrix is BF16, replacing the MM kernel (~2× faster for
307 // M=1 due to better memory bandwidth utilization per thread).
308 let dense_gemv_bf16_src: &'static str =
309 include_str!("shaders/dense_gemv_bf16.metal");
310 sources.insert("hf2q_dense_gemv_bf16_f32_4".into(), dense_gemv_bf16_src);
311
312 // Fused scale-mask-softmax for the non-flash-attention prefill
313 // path. One row-local threadgroup per (head, query) pair
314 // replaces three separate dispatches (scale, mask-add, softmax);
315 // reads a bf16 mask (-INF at masked positions, matching
316 // flash_attn_prefill_mask.metal) that is shared across heads.
317 let scale_mask_softmax_src: &'static str =
318 include_str!("shaders/scale_mask_softmax.metal");
319 sources.insert("scale_mask_softmax_f32".into(), scale_mask_softmax_src);
320 // ADR-029 iter-93 H71: float4-vectorized variant for peer parity
321 // with kernel_soft_max_f32_4. Same source file; v4 host_name resolves
322 // to the second kernel appended at the bottom of scale_mask_softmax.metal.
323 sources.insert("scale_mask_softmax_f32_v4".into(), scale_mask_softmax_src);
324
325 // Expert-routed (MoE) quantized matmul kernel (Story 2.1)
326 sources.insert(
327 "quantized_matmul_id".into(),
328 include_str!("shaders/quantized_matmul_id.metal"),
329 );
330
331 // Expert-routed (MoE) GGML block-format quantized matmul kernels
332 let ggml_id_src: &'static str =
333 include_str!("shaders/quantized_matmul_id_ggml.metal");
334 sources.insert("kernel_mul_mv_id_q4_0_f32".into(), ggml_id_src);
335 sources.insert("kernel_mul_mv_id_q8_0_f32".into(), ggml_id_src);
336 // ADR-013 P7 — Q4_K MoE expert-routed mat-vec (port of
337 // llama.cpp's kernel_mul_mv_id_q4_K_f32 at ggml-metal.metal:10349).
338 sources.insert("kernel_mul_mv_id_q4_K_f32".into(), ggml_id_src);
339 sources.insert("kernel_mul_mv_id_q5_K_f32".into(), ggml_id_src);
340 sources.insert("kernel_mul_mv_id_q6_K_f32".into(), ggml_id_src);
341 // ADR-028 iter-321 — q6_K _id with nr0=2 + cached yl[16]
342 // (peer-pattern port mirroring iter-309's non-_id variant).
343 // Env-gated via HF2Q_Q6K_ID_MV_NR2=1 in dispatch_id_mv.
344 sources.insert("kernel_mul_mv_id_q6_K_f32_nr2".into(), ggml_id_src);
345 // ADR-029 iter-6 — q8_0 _id with nr0=2 + nsg=4 cross-SG reduce
346 // (peer-pattern port; peer N_R0_Q8_0=2 + N_SG_Q8_0=4 in
347 // /opt/llama.cpp/ggml/src/ggml-metal/ggml-metal-impl.h:27,40).
348 // Env-gated via HF2Q_Q8_0_ID_MV_NR2=1 in dispatch_id_mv.
349 sources.insert("kernel_mul_mv_id_q8_0_f32_nr2".into(), ggml_id_src);
350 // ADR-022 Phase 1 — Q5_1 / IQ4_NL MoE expert-routed mat-vec.
351 sources.insert("kernel_mul_mv_id_q5_1_f32".into(), ggml_id_src);
352 sources.insert("kernel_mul_mv_id_iq4_nl_f32".into(), ggml_id_src);
353 // Fused-SwiGLU mv_id variants (ADR-012 §Optimize / Task #15):
354 // computes y[r][n] = sum_k(dequant(W[expert][n][k]) * silu(gate[r][k]) * up[r][k])
355 // in one dispatch — replaces silu_mul + expert_down sequence.
356 sources.insert("kernel_mul_mv_id_q4_0_f32_swiglu".into(), ggml_id_src);
357
358 // Expert-routed (MoE) GGML block-format QUANTIZED MATRIX-MATRIX kernels
359 // (ADR-011 Phase 3 Wave P3a: port of llama.cpp's
360 // `kernel_mul_mm_id_map0_ne20_N` + `kernel_mul_mm_id_<q>_f32`).
361 // Two-stage dispatch: map0 regroups the token-to-expert table into
362 // per-expert routed-token lists, then mm_id stages a 64x32 expert
363 // weight tile into threadgroup shmem and reuses it across a 32-row
364 // block of that expert's routed tokens.
365 let ggml_id_mm_src: &'static str =
366 include_str!("shaders/quantized_matmul_id_mm.metal");
367 sources.insert("kernel_mul_mm_id_map0_ne20_1".into(), ggml_id_mm_src);
368 sources.insert("kernel_mul_mm_id_map0_ne20_8".into(), ggml_id_mm_src);
369 sources.insert("kernel_mul_mm_id_q4_0_f32".into(), ggml_id_mm_src);
370 sources.insert("kernel_mul_mm_id_q8_0_f32".into(), ggml_id_mm_src);
371 sources.insert("kernel_mul_mm_id_q6_K_f32".into(), ggml_id_mm_src);
372 // ADR-013 P16 — Q4_K mm_id (port of llama.cpp ggml-metal.metal:10169).
373 sources.insert("kernel_mul_mm_id_q4_K_f32".into(), ggml_id_mm_src);
374 // ADR-022 Phase 1 P1.6 — Q5_1 / IQ4_NL mm_id template instantiations.
375 sources.insert("kernel_mul_mm_id_q5_1_f32".into(), ggml_id_mm_src);
376 sources.insert("kernel_mul_mm_id_iq4_nl_f32".into(), ggml_id_mm_src);
377 // ADR-022 Phase 2 — Q5_K mm_id template instantiation.
378 sources.insert("kernel_mul_mm_id_q5_K_f32".into(), ggml_id_mm_src);
379
380 // ADR-033 §Pi Task #20 / ADR-034 §93 — fused MoE gate+up+silu_mul
381 // mm_id kernel for Q6_K. Replaces 3 dispatches (gate_mm_id, up_mm_id,
382 // silu_mul_id) with 1 fused dispatch per MoE FFN per layer. Closes
383 // hf2q-vs-llama.cpp prefill gap at production Qwen MoE shapes.
384 let fused_q6_k_mm_id_src: &'static str =
385 include_str!("shaders/fused_gate_up_silu_mm_id_q6_K.metal");
386 sources.insert("kernel_fused_gate_up_silu_mm_id_q6_K_f32".into(), fused_q6_k_mm_id_src);
387
388 // MoE-routed quantized matrix-matrix kernels — tensor API variant
389 // (ADR-011 Phase 3 Wave P3b-tensor). Uses the MPP tensor_ops
390 // matmul2d primitive for hardware-tensor-core MMA on M3+. Only
391 // the mm_id kernel is ported — map0 is a short pre-pass (not
392 // matmul) and continues to use the simdgroup version.
393 let ggml_id_mm_tensor_src: &'static str =
394 include_str!("shaders/quantized_matmul_id_mm_tensor.metal");
395 sources.insert("kernel_mul_mm_id_q4_0_tensor_f32".into(), ggml_id_mm_tensor_src);
396 sources.insert("kernel_mul_mm_id_q8_0_tensor_f32".into(), ggml_id_mm_tensor_src);
397 sources.insert("kernel_mul_mm_id_q6_K_tensor_f32".into(), ggml_id_mm_tensor_src);
398 // ADR-013 P16 — Q4_K tensor-API mm_id.
399 sources.insert("kernel_mul_mm_id_q4_K_tensor_f32".into(), ggml_id_mm_tensor_src);
400 // ADR-022 Phase 1 P1.6 — Q5_1 / IQ4_NL tensor-API mm_id.
401 sources.insert("kernel_mul_mm_id_q5_1_tensor_f32".into(), ggml_id_mm_tensor_src);
402 sources.insert("kernel_mul_mm_id_iq4_nl_tensor_f32".into(), ggml_id_mm_tensor_src);
403 // ADR-022 Phase 2 — Q5_K tensor-API mm_id.
404 sources.insert("kernel_mul_mm_id_q5_K_tensor_f32".into(), ggml_id_mm_tensor_src);
405
406 // Embedding kernels (Story 1.5)
407 let embedding_src: &'static str = include_str!("shaders/embedding.metal");
408 sources.insert("embedding_gather_4bit".into(), embedding_src);
409 sources.insert("embedding_gather_6bit".into(), embedding_src);
410
411 // MoE gate kernel (Story 1.5)
412 let moe_gate_src: &'static str = include_str!("shaders/moe_gate.metal");
413 sources.insert("moe_gate".into(), moe_gate_src);
414
415 // MoE dispatch kernels (Story 1.5)
416 let moe_dispatch_src: &'static str = include_str!("shaders/moe_dispatch.metal");
417 sources.insert("fused_gelu_mul".into(), moe_dispatch_src);
418 sources.insert("moe_swiglu_fused".into(), moe_dispatch_src);
419 sources.insert("moe_swiglu_batch".into(), moe_dispatch_src);
420 sources.insert("moe_swiglu_seq".into(), moe_dispatch_src);
421 sources.insert("moe_accumulate".into(), moe_dispatch_src);
422 sources.insert("moe_weighted_sum".into(), moe_dispatch_src);
423 sources.insert("moe_weighted_sum_seq".into(), moe_dispatch_src);
424 sources.insert("zero_buffer".into(), moe_dispatch_src);
425 sources.insert("naive_matvec_f32".into(), moe_dispatch_src);
426 sources.insert("moe_gather_topk_weights".into(), moe_dispatch_src);
427 // bf16 variants (Phase 2 bf16 activation path)
428 sources.insert("fused_gelu_mul_bf16".into(), moe_dispatch_src);
429 sources.insert("moe_swiglu_seq_bf16".into(), moe_dispatch_src);
430 sources.insert("moe_weighted_sum_seq_bf16_input".into(), moe_dispatch_src);
431
432 // ADR-033 §Pi next-iter arc — two-pass MoE mm_id (iter A: map0).
433 // Pre-pass that sorts tokens by expert assignment before the main
434 // mm_id kernel. Ported from llama.cpp's kernel_mul_mm_id_map0; one
435 // template specialization per supported ne20 (n_expert_used).
436 let moe_mm_id_map0_src: &'static str =
437 include_str!("shaders/moe_mm_id_map0.metal");
438 sources.insert("moe_mm_id_map0_ne20_1".into(), moe_mm_id_map0_src);
439 sources.insert("moe_mm_id_map0_ne20_2".into(), moe_mm_id_map0_src);
440 sources.insert("moe_mm_id_map0_ne20_4".into(), moe_mm_id_map0_src);
441 sources.insert("moe_mm_id_map0_ne20_5".into(), moe_mm_id_map0_src);
442 sources.insert("moe_mm_id_map0_ne20_6".into(), moe_mm_id_map0_src);
443 sources.insert("moe_mm_id_map0_ne20_8".into(), moe_mm_id_map0_src);
444 sources.insert("moe_mm_id_map0_ne20_10".into(), moe_mm_id_map0_src);
445 sources.insert("moe_mm_id_map0_ne20_16".into(), moe_mm_id_map0_src);
446 sources.insert("moe_mm_id_map0_ne20_22".into(), moe_mm_id_map0_src);
447
448 // ADR-033 §Pi iter B-1 — main mm_id kernel skeleton (Q4_0). Body
449 // pending iter B-2 (simdgroup matmul + Q4_0 dequant chain). NOT
450 // registered: the shader currently writes zeros for routed tiles, so
451 // registering it would expose a known-wrong pipeline (and prewarm_all
452 // would compile it). The shader file is retained for iter B-2; re-add
453 // the source insert once the real matmul body lands.
454 // let moe_mm_id_q4_0_src = include_str!("shaders/moe_mm_id_q4_0.metal");
455 // sources.insert("moe_mm_id_q4_0_f32_skeleton".into(), moe_mm_id_q4_0_src);
456 // ADR-020 iter-11h-e3a: backward kernels for moe_weighted_sum_seq.
457 sources.insert(
458 "moe_weighted_sum_seq_backward_outputs_f32".into(),
459 moe_dispatch_src,
460 );
461 sources.insert(
462 "moe_weighted_sum_seq_backward_weights_f32".into(),
463 moe_dispatch_src,
464 );
465 // ADR-020 iter-11h-e3b: fused backward kernel for moe_swiglu_seq.
466 sources.insert(
467 "moe_swiglu_seq_backward_f32".into(),
468 moe_dispatch_src,
469 );
470
471 // Batched KV cache copy kernels
472 let kv_cache_src: &'static str = include_str!("shaders/kv_cache_copy.metal");
473 sources.insert("kv_cache_copy_batch_f32".into(), kv_cache_src);
474 sources.insert("kv_cache_copy_batch_f32_to_f16".into(), kv_cache_src);
475 sources.insert("kv_cache_copy_seq_f32".into(), kv_cache_src);
476 sources.insert("kv_cache_copy_seq_f32_to_f16".into(), kv_cache_src);
477 // Wave P4.11 — fused K+V copy variants
478 sources.insert("kv_cache_copy_seq_f32_kv_dual".into(), kv_cache_src);
479 sources.insert("kv_cache_copy_seq_f32_to_f16_kv_dual".into(), kv_cache_src);
480 // ADR-028 iter-145 — fused single-position K+V copy variants (decode shape)
481 sources.insert("kv_cache_copy_batch_f32_kv_dual".into(), kv_cache_src);
482 sources.insert("kv_cache_copy_batch_f32_to_f16_kv_dual".into(), kv_cache_src);
483 // bf16-source KV cache copy (Phase 2 bf16 activation path)
484 sources.insert("kv_cache_copy_seq_bf16".into(), kv_cache_src);
485 // ADR-030 iter-95 — bit-exact BF16→BF16 head-major cache copy for
486 // Option A xlen verify (avoids F16 round-trip precision drift).
487 sources.insert("kv_cache_copy_seq_bf16_to_bf16_head_major".into(), kv_cache_src);
488
489 // Elementwise and transpose kernels (Story 1.5)
490 let elementwise_src: &'static str = include_str!("shaders/elementwise.metal");
491 sources.insert("elementwise_add_f32".into(), elementwise_src);
492 sources.insert("elementwise_add_f16".into(), elementwise_src);
493 sources.insert("elementwise_mul_f32".into(), elementwise_src);
494 sources.insert("elementwise_mul_f16".into(), elementwise_src);
495 sources.insert("elementwise_add_bf16".into(), elementwise_src);
496 sources.insert("elementwise_mul_bf16".into(), elementwise_src);
497 sources.insert("cast_f16_to_f32".into(), elementwise_src);
498 sources.insert("cast_f32_to_f16".into(), elementwise_src);
499 sources.insert("cast_bf16_to_f32".into(), elementwise_src);
500 sources.insert("cast_f32_to_bf16".into(), elementwise_src);
501 sources.insert("cast_bf16_to_f16".into(), elementwise_src);
502 sources.insert("cast_f16_to_bf16".into(), elementwise_src);
503 sources.insert("scalar_mul_bf16".into(), elementwise_src);
504 sources.insert("scalar_mul_f32".into(), elementwise_src);
505 sources.insert("embedding_gather_scale_f32".into(), elementwise_src);
506 sources.insert("embedding_gather_scale_batch_f32".into(), elementwise_src);
507 sources.insert("permute_021_bf16".into(), elementwise_src);
508 sources.insert("transpose_last2_bf16".into(), elementwise_src);
509 sources.insert("transpose_last2_f16".into(), elementwise_src);
510 sources.insert("permute_021_f32".into(), elementwise_src);
511 sources.insert("permute_021_bf16_to_f32".into(), elementwise_src);
512 sources.insert("permute_021_f32_to_f16".into(), elementwise_src);
513 sources.insert("transpose_2d_f32".into(), elementwise_src);
514 sources.insert("transpose_2d_f16".into(), elementwise_src);
515
516 // Attention kernels (Story 1.3)
517 let sdpa_src: &'static str = include_str!("shaders/sdpa.metal");
518 sources.insert("sdpa".into(), sdpa_src);
519 sources.insert("sdpa_bf16".into(), sdpa_src);
520 let sdpa_sliding_src: &'static str = include_str!("shaders/sdpa_sliding.metal");
521 sources.insert("sdpa_sliding".into(), sdpa_sliding_src);
522 sources.insert("sdpa_sliding_bf16".into(), sdpa_sliding_src);
523
524 // Flash-attention tiled prefill kernel (ADR-011 Phase 1).
525 // Ten entry points; all backed by the same shader source.
526 // Pipelines are compiled with function constants via
527 // `get_pipeline_with_bool_constants` — not `get_pipeline`.
528 let flash_attn_prefill_src: &'static str =
529 include_str!("shaders/flash_attn_prefill.metal");
530 // D=256 variants (BQ=32, BK=16, WM=4, WN=1 — 128 threads/threadgroup)
531 sources.insert(
532 "steel_attention_float32_bq32_bk16_bd256_wm4_wn1_maskfloat32".into(),
533 flash_attn_prefill_src,
534 );
535 sources.insert(
536 "steel_attention_float32_bq32_bk16_bd256_wm4_wn1_maskbool_".into(),
537 flash_attn_prefill_src,
538 );
539 sources.insert(
540 "steel_attention_bfloat16_bq32_bk16_bd256_wm4_wn1_maskbfloat16".into(),
541 flash_attn_prefill_src,
542 );
543 sources.insert(
544 "steel_attention_bfloat16_bq32_bk16_bd256_wm4_wn1_maskbool_".into(),
545 flash_attn_prefill_src,
546 );
547 sources.insert(
548 "steel_attention_float16_bq32_bk16_bd256_wm4_wn1_maskfloat16".into(),
549 flash_attn_prefill_src,
550 );
551 sources.insert(
552 "steel_attention_float16_bq32_bk16_bd256_wm4_wn1_maskbool_".into(),
553 flash_attn_prefill_src,
554 );
555 // D=512 variants (BQ=8, BK=8, WM=1, WN=1 — 32 threads/threadgroup)
556 // NOTE: f32 at D=512 is NOT instantiated — threadgroup memory exceeds
557 // the 32 KB Metal limit (candle sdpa.rs:86-94).
558 sources.insert(
559 "steel_attention_bfloat16_bq8_bk8_bd512_wm1_wn1_maskbfloat16".into(),
560 flash_attn_prefill_src,
561 );
562 sources.insert(
563 "steel_attention_bfloat16_bq8_bk8_bd512_wm1_wn1_maskbool_".into(),
564 flash_attn_prefill_src,
565 );
566 sources.insert(
567 "steel_attention_float16_bq8_bk8_bd512_wm1_wn1_maskfloat16".into(),
568 flash_attn_prefill_src,
569 );
570 sources.insert(
571 "steel_attention_float16_bq8_bk8_bd512_wm1_wn1_maskbool_".into(),
572 flash_attn_prefill_src,
573 );
574
575 // Flash attention vector kernels — SIMD-vectorized decode-path SDPA
576 // (ported from llama.cpp flash_attn_ext_vec)
577 let flash_attn_vec_src: &'static str =
578 include_str!("shaders/flash_attn_vec.metal");
579 sources.insert("flash_attn_vec_dk256".into(), flash_attn_vec_src);
580 sources.insert("flash_attn_vec_dk512".into(), flash_attn_vec_src);
581 sources.insert("flash_attn_vec_reduce_dk128".into(), flash_attn_vec_src);
582 sources.insert("flash_attn_vec_reduce_dk256".into(), flash_attn_vec_src);
583 sources.insert("flash_attn_vec_reduce_dk512".into(), flash_attn_vec_src);
584 // F16 KV variants (Phase 4a)
585 sources.insert("flash_attn_vec_f16kv_dk256".into(), flash_attn_vec_src);
586 sources.insert("flash_attn_vec_f16kv_dk512".into(), flash_attn_vec_src);
587
588 // ADR-037 Phase E1.1 (2026-05-22) — tree-attention kernel for
589 // EAGLE-3 + dynamic tree speculative decoding. Variant of
590 // flash_attn_vec consuming an explicit per-(query, kv_pos) mask
591 // buffer instead of implicit causal. Reduce pass reuses
592 // flash_attn_vec_reduce_* (identical output layout).
593 let tree_attention_src: &'static str =
594 include_str!("shaders/tree_attention.metal");
595 sources.insert("tree_attention_dk128".into(), tree_attention_src);
596 sources.insert("tree_attention_dk256".into(), tree_attention_src);
597 sources.insert("tree_attention_dk512".into(), tree_attention_src);
598 sources.insert("tree_attention_f16kv_dk128".into(), tree_attention_src);
599 sources.insert("tree_attention_f16kv_dk256".into(), tree_attention_src);
600 sources.insert("tree_attention_f16kv_dk512".into(), tree_attention_src);
601
602 // RoPE, normalization, activation kernels (Story 1.4)
603 let rope_src: &'static str = include_str!("shaders/rope.metal");
604 sources.insert("rope_f32".into(), rope_src);
605 sources.insert("rope_f16".into(), rope_src);
606 sources.insert("rope_bf16".into(), rope_src);
607 sources.insert("rope_neox_bf16".into(), rope_src);
608 sources.insert("rope_neox_f32".into(), rope_src);
609 let rms_norm_src: &'static str = include_str!("shaders/rms_norm.metal");
610 sources.insert("rms_norm_f32".into(), rms_norm_src);
611 // ADR-028 iter-310 — float4 + simd_sum variants (peer-pattern,
612 // ported from llama.cpp kernel_rms_norm_fuse_impl<float4, 1>).
613 // Env-gated via HF2Q_RMS_NORM_V2=1 in the dispatchers.
614 sources.insert("rms_norm_f32_v2".into(), rms_norm_src);
615 sources.insert("rms_norm_no_scale_f32_v2".into(), rms_norm_src);
616 sources.insert("rms_norm_f16".into(), rms_norm_src);
617 sources.insert("rms_norm_bf16".into(), rms_norm_src);
618 sources.insert("rms_norm_no_scale_bf16".into(), rms_norm_src);
619 sources.insert("rms_norm_no_scale_f32".into(), rms_norm_src);
620 sources.insert("rms_norm_no_scale_f32_dual".into(), rms_norm_src);
621 sources.insert("rms_norm_f32_triple".into(), rms_norm_src);
622 sources.insert("fused_post_attn_triple_norm_f32".into(), rms_norm_src);
623 // ADR-028 iter-370: V2 (float4 + simd_sum) variant of triple_norm.
624 sources.insert("fused_post_attn_triple_norm_f32_v2".into(), rms_norm_src);
625 // ADR-028 iter-217: fused post-FF norm 2 + end-of-layer FINAL
626 // (combines 2 sequential fused_norm_add dispatches into 1 kernel).
627 sources.insert("fused_post_ff_norm2_endlayer_f32".into(), rms_norm_src);
628 // ADR-028 iter-362: V2 (float4 + simd_sum) variant of the above.
629 // Same math, 75% fewer barriers per dispatch (4 vs 16 at tg=256).
630 sources.insert("fused_post_ff_norm2_endlayer_f32_v2".into(), rms_norm_src);
631 // ADR-028 iter-367: V2 fusion of moe_weighted_sum INTO Path A end-of-layer.
632 // Eliminates 1 dispatch + moe_accum round-trip from gemma4 decode default.
633 sources.insert("fused_moe_wsum_post_ff_norm2_endlayer_f32_v2".into(), rms_norm_src);
634 sources.insert("rms_norm_no_scale_f32_dual_perm".into(), rms_norm_src);
635 // Fused RMS norm + elementwise multiply kernels (Phase 4e.2)
636 sources.insert("rms_norm_mul_f32".into(), rms_norm_src);
637 sources.insert("rms_norm_mul_f16".into(), rms_norm_src);
638 sources.insert("rms_norm_mul_bf16".into(), rms_norm_src);
639 // L2 norm kernels (ADR-013 Decision 3 — Gated DeltaNet Q/K norm)
640 let l2_norm_src: &'static str = include_str!("shaders/l2_norm.metal");
641 sources.insert("l2_norm_f32".into(), l2_norm_src);
642 sources.insert("l2_norm_f16".into(), l2_norm_src);
643 sources.insert("l2_norm_bf16".into(), l2_norm_src);
644 // ADR-015 iter59a — fused L2 norm + scalar multiply (DN q-path).
645 sources.insert("l2_norm_scale_f32".into(), l2_norm_src);
646 // Cumulative-sum kernels (ADR-013 Decision 4 — DeltaNet decay-mask base)
647 let cumsum_src: &'static str = include_str!("shaders/cumsum.metal");
648 sources.insert("cumsum_f32".into(), cumsum_src);
649 sources.insert("cumsum_bf16".into(), cumsum_src);
650 // SSM conv kernels (ADR-013 Decision 7 — DeltaNet 1D causal conv + SiLU)
651 let ssm_conv_src: &'static str = include_str!("shaders/ssm_conv.metal");
652 sources.insert("ssm_conv_forward_f32".into(), ssm_conv_src);
653 sources.insert("ssm_conv_forward_bf16".into(), ssm_conv_src);
654 sources.insert("ssm_conv_state_update_f32".into(), ssm_conv_src);
655 sources.insert("ssm_conv_state_update_bf16".into(), ssm_conv_src);
656 // Tri-solve kernels (ADR-013 Decision 5 — chunked DeltaNet debug path)
657 let tri_solve_src: &'static str = include_str!("shaders/tri_solve.metal");
658 sources.insert("tri_solve_lower_unit_f32".into(), tri_solve_src);
659 sources.insert("tri_solve_lower_unit_bf16".into(), tri_solve_src);
660 // Rope-multi kernels (ADR-013 Decision 10 — IMROPE for Qwen3.5)
661 let rope_multi_src: &'static str = include_str!("shaders/rope_multi.metal");
662 sources.insert("rope_multi_f32".into(), rope_multi_src);
663 sources.insert("rope_multi_bf16".into(), rope_multi_src);
664 // Gated DeltaNet fused kernel (ADR-013 Decision 6 — centerpiece)
665 let gdn_src: &'static str = include_str!("shaders/gated_delta_net.metal");
666 sources.insert("gated_delta_net_f32".into(), gdn_src);
667 // ADR-015 iter56 — decode-only `simd_sum` variant. Three NSG-templated
668 // host names share the same source; selection is by D_k via
669 // `dispatch_gated_delta_net_decode`. Drop-in for the fused kernel
670 // above when n_tokens=1.
671 let gdn_decode_src: &'static str =
672 include_str!("shaders/gated_delta_net_decode.metal");
673 sources.insert("gated_delta_net_decode_f32_1".into(), gdn_decode_src);
674 sources.insert("gated_delta_net_decode_f32_2".into(), gdn_decode_src);
675 sources.insert("gated_delta_net_decode_f32_4".into(), gdn_decode_src);
676 // Wave 5b — chunk-parallel inter-chunk state-recurrence kernel
677 // (the one new kernel in the chunk-parallel pipeline; spec source:
678 // arXiv 2412.06464 §4 + FLA chunk_delta_h.py:43-298).
679 let gdn_chunk_src: &'static str =
680 include_str!("shaders/gated_delta_net_chunk.metal");
681 sources.insert(
682 "gated_delta_net_chunk_inter_state_bf16".into(),
683 gdn_chunk_src,
684 );
685 // ADR-033 §Pi Task #25 iter 19 — K=256 native variant. Same algorithm
686 // as gated_delta_net_chunk_inter_state_bf16 but with compile-time
687 // 32-tile MMA loops (vs 16 for K=128). Required for Qwen3.6's
688 // head_dim=256 chunk-scan path support. Per the K=128 kernel's
689 // documented constraint at gated_delta_net_chunk.metal:441, runtime-K
690 // bounds defeat MMA scheduling — this separate kernel keeps K=256
691 // compile-time-known, avoiding the 3.15× regression.
692 let gdn_chunk_k256_src: &'static str =
693 include_str!("shaders/gated_delta_net_chunk_k256.metal");
694 sources.insert(
695 "gated_delta_net_chunk_inter_state_bf16_k256".into(),
696 gdn_chunk_k256_src,
697 );
698 // ADR-033 §Pi Task #25 iter 20 — K=256 native chunk_o variant.
699 // Sister kernel to iter 19's inter_state_k256. Bumped from K=128's
700 // num_k_tiles=16 to num_k_tiles=32; bo_acc/bA_acc accumulators are
701 // V/BT-indexed (not K-indexed) so they keep their original sizes.
702 let gdn_chunk_o_k256_src: &'static str =
703 include_str!("shaders/gated_delta_net_chunk_o_k256.metal");
704 sources.insert(
705 "gated_delta_net_chunk_o_bf16_k256".into(),
706 gdn_chunk_o_k256_src,
707 );
708 // Wave 5b.1 iter 2 — chunk_scaled_dot_kkt kernel (input-side of
709 // the chunk pipeline; spec source: FLA chunk_scaled_dot_kkt.py:36-99).
710 let gdn_kkt_src: &'static str =
711 include_str!("shaders/gated_delta_net_kkt.metal");
712 sources.insert("gated_delta_net_kkt_bf16".into(), gdn_kkt_src);
713 // Wave 5b.1 iter 2 — recompute_w_u_fwd kernel (applies post-solve A
714 // to (β·v) and (β·k·exp(g)) to produce w and u; spec source: FLA
715 // wy_fast.py:29-117).
716 let gdn_recompute_wu_src: &'static str =
717 include_str!("shaders/gated_delta_net_recompute_wu.metal");
718 sources.insert(
719 "gated_delta_net_recompute_wu_bf16".into(),
720 gdn_recompute_wu_src,
721 );
722 // Wave 5b.1 iter 3 — chunk_fwd_o kernel (per-chunk output: closes
723 // the chunk pipeline; spec source: FLA chunk_o.py:42-138).
724 let gdn_chunk_o_src: &'static str =
725 include_str!("shaders/gated_delta_net_chunk_o.metal");
726 sources.insert("gated_delta_net_chunk_o_bf16".into(), gdn_chunk_o_src);
727 // Wave 5b.1 iter 4 — orchestrator helper kernels:
728 // chunk_local_cumsum_g_f32 — per-chunk prefix sum on g [B, T, H]
729 // chunk_tri_solve_invert_f32 — per-chunk-block (I + A_strict)^-1
730 // on FLA's [B, T, H, BT] layout.
731 let chunk_local_cumsum_g_src: &'static str =
732 include_str!("shaders/chunk_local_cumsum_g.metal");
733 sources.insert(
734 "chunk_local_cumsum_g_f32".into(),
735 chunk_local_cumsum_g_src,
736 );
737 let chunk_tri_solve_invert_src: &'static str =
738 include_str!("shaders/chunk_gated_delta_rule_tri_solve_invert.metal");
739 sources.insert(
740 "chunk_tri_solve_invert_f32".into(),
741 chunk_tri_solve_invert_src,
742 );
743 // Sigmoid-gated elementwise multiply (ADR-013 Decision 9 — full-attn output gate)
744 let sigmoid_mul_src: &'static str = include_str!("shaders/sigmoid_mul.metal");
745 sources.insert("sigmoid_mul_f32".into(), sigmoid_mul_src);
746 sources.insert("sigmoid_mul_bf16".into(), sigmoid_mul_src);
747 let silu_mul_src: &'static str = include_str!("shaders/silu_mul.metal");
748 sources.insert("silu_mul_f32".into(), silu_mul_src);
749 // ADR-033 §Pi Task #25 iter 16 — K-bank slice copy for K=256 → 2×K=128
750 // bank-split chunk-scan path (Qwen3.6 head_dim=256 support).
751 let bank_slice_bf16_src: &'static str =
752 include_str!("shaders/bank_slice_bf16.metal");
753 sources.insert("bank_slice_bf16".into(), bank_slice_bf16_src);
754 // ADR-033 §Pi Task #25 iter 17 — F32 variants (for h0 input and
755 // final_state output) + concat (inverse of slice, for assembling
756 // the K=256 final_state from per-bank K=128 outputs). Same source
757 // file — multiple kernels share the BankSliceParams struct.
758 sources.insert("bank_slice_f32".into(), bank_slice_bf16_src);
759 sources.insert("bank_concat_f32".into(), bank_slice_bf16_src);
760 // ADR-034 task #93 — fused gate_proj + up_proj + silu_mul Q8_0.
761 let fused_gate_up_silu_q8_0_src: &'static str =
762 include_str!("shaders/fused_gate_up_silu_q8_0.metal");
763 sources.insert(
764 "kernel_fused_gate_up_silu_q8_0_f32".into(),
765 fused_gate_up_silu_q8_0_src,
766 );
767 // ADR-034 task #94 — fused dual Q4_0 projection (FA Q/K/V/gate fuse).
768 let fused_dual_proj_q4_0_src: &'static str =
769 include_str!("shaders/fused_dual_proj_q4_0.metal");
770 sources.insert(
771 "kernel_fused_dual_proj_q4_0_f32".into(),
772 fused_dual_proj_q4_0_src,
773 );
774 // ADR-034 task #93 cont. 24 — fused gate+up+silu_mul Q4_K (broader quant coverage).
775 #[allow(non_snake_case)]
776 let fused_gate_up_silu_q4_K_src: &'static str =
777 include_str!("shaders/fused_gate_up_silu_q4_K.metal");
778 sources.insert(
779 "kernel_fused_gate_up_silu_q4_K_f32".into(),
780 fused_gate_up_silu_q4_K_src,
781 );
782 // ADR-034 task #93 cont. 26 — fused gate+up+silu_mul IQ4_NL.
783 let fused_gate_up_silu_iq4_nl_src: &'static str =
784 include_str!("shaders/fused_gate_up_silu_iq4_nl.metal");
785 sources.insert(
786 "kernel_fused_gate_up_silu_iq4_nl_f32".into(),
787 fused_gate_up_silu_iq4_nl_src,
788 );
789 // ADR-034 task #93 cont. 27 — fused gate+up+silu_mul Q5_K.
790 #[allow(non_snake_case)]
791 let fused_gate_up_silu_q5_K_src: &'static str =
792 include_str!("shaders/fused_gate_up_silu_q5_K.metal");
793 sources.insert(
794 "kernel_fused_gate_up_silu_q5_K_f32".into(),
795 fused_gate_up_silu_q5_K_src,
796 );
797 // ADR-034 task #93 cont. 28 — fused gate+up+silu_mul Q6_K.
798 #[allow(non_snake_case)]
799 let fused_gate_up_silu_q6_K_src: &'static str =
800 include_str!("shaders/fused_gate_up_silu_q6_K.metal");
801 sources.insert(
802 "kernel_fused_gate_up_silu_q6_K_f32".into(),
803 fused_gate_up_silu_q6_K_src,
804 );
805 let compute_g_beta_src: &'static str = include_str!("shaders/compute_g_beta.metal");
806 sources.insert("compute_g_beta_f32".into(), compute_g_beta_src);
807 let ssm_norm_gate_src: &'static str = include_str!("shaders/ssm_norm_gate.metal");
808 sources.insert("ssm_norm_gate_f32".into(), ssm_norm_gate_src);
809 let gelu_src: &'static str = include_str!("shaders/gelu.metal");
810 sources.insert("gelu_f32".into(), gelu_src);
811 sources.insert("gelu_f16".into(), gelu_src);
812 sources.insert("gelu_bf16".into(), gelu_src);
813 let softmax_src: &'static str = include_str!("shaders/softmax.metal");
814 sources.insert("softmax_f32".into(), softmax_src);
815 sources.insert("softmax_f16".into(), softmax_src);
816 sources.insert("softmax_bf16".into(), softmax_src);
817 let softmax_backward_src: &'static str =
818 include_str!("shaders/softmax_backward.metal");
819 sources.insert("softmax_backward_f32".into(), softmax_backward_src);
820 let log_elementwise_src: &'static str =
821 include_str!("shaders/log_elementwise.metal");
822 sources.insert("log_f32".into(), log_elementwise_src);
823 sources.insert("log_backward_f32".into(), log_elementwise_src);
824 let row_sum_src: &'static str = include_str!("shaders/row_sum.metal");
825 sources.insert("row_sum_f32".into(), row_sum_src);
826 sources.insert("row_sum_backward_f32".into(), row_sum_src);
827 // ADR-020 iter-10a: GGUF-legacy quantize-dequantize round-trip kernels
828 // (Q4_0 + Q8_0). Used by hf2q's dynamic_quant Track 1 to produce
829 // W_low / W_high for the gradient-Taylor sensitivity formula.
830 let qdq_legacy_src: &'static str = include_str!("shaders/qdq_legacy.metal");
831 sources.insert("qdq_q4_0_f32".into(), qdq_legacy_src);
832 sources.insert("qdq_q8_0_f32".into(), qdq_legacy_src);
833 // ADR-020 iter-10b: RMSNorm reverse-mode autograd kernels.
834 // r_inv helper is reused by both backward kernels; dx and dw cover
835 // the full backward identity for `y = x * rsqrt(mean(x²) + eps) * w`.
836 let rms_norm_backward_src: &'static str =
837 include_str!("shaders/rms_norm_backward.metal");
838 sources.insert(
839 "rms_norm_compute_rms_inv_f32".into(),
840 rms_norm_backward_src,
841 );
842 sources.insert("rms_norm_backward_dx_f32".into(), rms_norm_backward_src);
843 sources.insert("rms_norm_backward_dw_f32".into(), rms_norm_backward_src);
844 // ADR-020 iter-11a: 2-D row-major slice + concat-by-column kernels.
845 // Used by hf2q's multi-head SDPA on GpuTape (slice Q/K/V into
846 // per-head views, run per-head SDPA, concat per-head contexts
847 // back to full attention output).
848 let slice_concat_2d_src: &'static str =
849 include_str!("shaders/slice_concat_2d.metal");
850 sources.insert("slice_2d_cols_f32".into(), slice_concat_2d_src);
851 sources.insert("copy_2d_cols_into_f32".into(), slice_concat_2d_src);
852 // ADR-020 iter-11b: SiLU forward + backward kernels for GpuTape
853 // SwiGLU FFN composition.
854 let silu_backward_src: &'static str =
855 include_str!("shaders/silu_backward.metal");
856 sources.insert("silu_f32".into(), silu_backward_src);
857 sources.insert("silu_backward_f32".into(), silu_backward_src);
858 // ADR-020 iter-11d: FP32 embedding lookup + scatter-add backward.
859 let embedding_autograd_src: &'static str =
860 include_str!("shaders/embedding_autograd.metal");
861 sources.insert("embedding_lookup_f32".into(), embedding_autograd_src);
862 sources.insert(
863 "embedding_scatter_add_f32".into(),
864 embedding_autograd_src,
865 );
866 // ADR-020 iter-13a: Adam optimizer step kernel for Track 2
867 // DWQ-proper training loop.
868 let adam_update_src: &'static str =
869 include_str!("shaders/adam_update.metal");
870 sources.insert("adam_update_f32".into(), adam_update_src);
871 // ADR-020 iter-13b: differentiable affine qdq kernels for the
872 // DWQ-proper training loop. Init + forward + backward (scales,
873 // biases) — q_int is FROZEN, scales+biases learnable.
874 let qdq_affine_src: &'static str =
875 include_str!("shaders/qdq_affine.metal");
876 sources.insert("qdq_affine_init_f32".into(), qdq_affine_src);
877 sources.insert("qdq_affine_forward_f32".into(), qdq_affine_src);
878 sources.insert(
879 "qdq_affine_backward_scales_f32".into(),
880 qdq_affine_src,
881 );
882 sources.insert(
883 "qdq_affine_backward_biases_f32".into(),
884 qdq_affine_src,
885 );
886 // ADR-020 iter-15: fused affine quantized matmul for DWQ inference.
887 // Per-element kernel; one thread per (m, n) output element.
888 // Tiled + simdgroup-MMA variant lands in iter-15b.
889 let qmm_affine_src: &'static str =
890 include_str!("shaders/qmm_affine.metal");
891 sources.insert("qmm_affine_t_f32".into(), qmm_affine_src);
892 // ADR-020 iter-15b: tiled variant — 16x16 thread block with
893 // cooperative-load X/W tiles in threadgroup-shared memory for
894 // 2-5x speedup over the per-element kernel.
895 let qmm_affine_tiled_src: &'static str =
896 include_str!("shaders/qmm_affine_tiled.metal");
897 sources.insert(
898 "qmm_affine_t_f32_tiled".into(),
899 qmm_affine_tiled_src,
900 );
901 // ADR-020 iter-15c: simdgroup-MMA variant — uses Apple GPU
902 // hardware `simdgroup_matrix<float, 8, 8>` MMA for the inner
903 // reduction. Per-tile algorithmic 8× over scalar tiled, lands
904 // as ~3-4× wall after launch / load amortization.
905 let qmm_affine_simd_src: &'static str =
906 include_str!("shaders/qmm_affine_simd.metal");
907 sources.insert(
908 "qmm_affine_t_f32_simd".into(),
909 qmm_affine_simd_src,
910 );
911 // ADR-020 iter-15c-2: 4-simdgroup-per-TG variant — 32×32
912 // output tile, 4 simdgroups arranged as 2×2 grid each owning
913 // a 16×16 sub-tile = 4 simdgroup_matrix accumulators. Same
914 // math as 15c-1, fuller warp-pool exploitation.
915 let qmm_affine_simd4_src: &'static str =
916 include_str!("shaders/qmm_affine_simd4.metal");
917 sources.insert(
918 "qmm_affine_t_f32_simd4".into(),
919 qmm_affine_simd4_src,
920 );
921 // ADR-020 iter-15c-2b: gs=64 variant (mlx-lm dynamic_quant
922 // canonical default). Same 4-simdgroup geometry, BK=64
923 // instead of 32 (= 8 sub-K-tiles per K-step instead of 4).
924 let qmm_affine_simd4_gs64_src: &'static str =
925 include_str!("shaders/qmm_affine_simd4_gs64.metal");
926 sources.insert(
927 "qmm_affine_t_f32_simd4_gs64".into(),
928 qmm_affine_simd4_gs64_src,
929 );
930 // ADR-020 AC#5 Iter A: packed-U32 dense affine matmul (bits=4,
931 // gs=32) — production decode/prefill kernel for serving DWQ
932 // safetensors directly without a load-time unpack pass.
933 let qmm_affine_t_packed_simd4_b4_src: &'static str =
934 include_str!("shaders/qmm_affine_t_packed_simd4_b4.metal");
935 sources.insert(
936 "qmm_affine_t_packed_simd4_b4".into(),
937 qmm_affine_t_packed_simd4_b4_src,
938 );
939 // ADR-020 iter-11h-b: training-mode causal depthwise 1D
940 // convolution (forward + backward dx + backward dw). Used by
941 // GpuTape autograd for differentiable Qwen3.5MoE forward
942 // (GatedDeltaNet's conv1d step).
943 let conv1d_dwc_src: &'static str =
944 include_str!("shaders/conv1d_depthwise_causal.metal");
945 sources.insert(
946 "conv1d_depthwise_causal_forward_f32".into(),
947 conv1d_dwc_src,
948 );
949 sources.insert(
950 "conv1d_depthwise_causal_backward_dx_f32".into(),
951 conv1d_dwc_src,
952 );
953 sources.insert(
954 "conv1d_depthwise_causal_backward_dw_f32".into(),
955 conv1d_dwc_src,
956 );
957 // ADR-020 iter-11h-c1: elementwise exp forward + backward.
958 // Building block for GatedDeltaNet's alpha = exp(-g) state-decay.
959 let exp_src: &'static str =
960 include_str!("shaders/exp_elementwise.metal");
961 sources.insert("exp_f32".into(), exp_src);
962 sources.insert("exp_backward_f32".into(), exp_src);
963 // ADR-020 iter-11h-c2: vector outer product (forward + dlhs +
964 // drhs). Building block for gated_delta_update's
965 // outer(delta, k) state-update term.
966 let outer_src: &'static str =
967 include_str!("shaders/outer_product.metal");
968 sources.insert("outer_product_f32".into(), outer_src);
969 sources.insert("outer_product_backward_lhs_f32".into(), outer_src);
970 sources.insert("outer_product_backward_rhs_f32".into(), outer_src);
971 // ADR-020 iter-11h-e1: take_along_axis (gather) + scatter-backward.
972 // Building block for MoE router on GpuTape.
973 let taa_src: &'static str =
974 include_str!("shaders/take_along_axis.metal");
975 sources.insert("take_along_axis_f32".into(), taa_src);
976 sources.insert("take_along_axis_backward_f32".into(), taa_src);
977 // ADR-020 iter-11h-misc-1: elementwise divide forward + backward.
978 let div_src: &'static str =
979 include_str!("shaders/divide_elementwise.metal");
980 sources.insert("divide_f32".into(), div_src);
981 sources.insert("divide_backward_f32".into(), div_src);
982 // ADR-020 iter-11h-misc-3: elementwise sqrt forward + backward.
983 let sqrt_src: &'static str =
984 include_str!("shaders/sqrt_elementwise.metal");
985 sources.insert("sqrt_f32".into(), sqrt_src);
986 sources.insert("sqrt_backward_f32".into(), sqrt_src);
987 let softcap_src: &'static str = include_str!("shaders/softcap.metal");
988 sources.insert("softcap_f32".into(), softcap_src);
989 sources.insert("softcap_f16".into(), softcap_src);
990 sources.insert("softcap_bf16".into(), softcap_src);
991
992 // Fused norm-add kernels — Gemma4 post-attention / post-FFN ordering:
993 // normed = rms_norm(input, weight, eps); output = residual + normed
994 let fused_norm_add_src: &'static str =
995 include_str!("shaders/fused_norm_add_bf16.metal");
996 sources.insert("fused_norm_add_bf16".into(), fused_norm_add_src);
997 sources.insert("fused_norm_add_no_weight_bf16".into(), fused_norm_add_src);
998
999 // Fused head-norm + RoPE f32 kernel — replaces separate rms_norm + rope_neox_f32
1000 let fused_hnr_f32_src: &'static str =
1001 include_str!("shaders/fused_head_norm_rope_f32.metal");
1002 sources.insert("fused_head_norm_rope_f32".into(), fused_hnr_f32_src);
1003 // ADR-028 iter-337 — float4 + simd_sum Phase 1 variant. Phases
1004 // 2-4 byte-identical to v1; race-fix barrier preserved. Env-gated
1005 // via HF2Q_FUSED_HEAD_NORM_ROPE_V2 (default ON, opt-out via =0).
1006 sources.insert("fused_head_norm_rope_f32_v2".into(), fused_hnr_f32_src);
1007
1008 // Fused head-norm + RoPE bf16 kernels (single-token + batch prefill)
1009 // Both entry points live in the same .metal file.
1010 let fused_hnr_bf16_src: &'static str =
1011 include_str!("shaders/fused_head_norm_rope_bf16.metal");
1012 sources.insert("fused_head_norm_rope_bf16".into(), fused_hnr_bf16_src);
1013 sources.insert("fused_head_norm_rope_batch_bf16".into(), fused_hnr_bf16_src);
1014
1015 // Fused norm-add f32 kernels — post-attention / post-FFN / end-of-layer
1016 let fused_norm_add_f32_src: &'static str =
1017 include_str!("shaders/fused_norm_add_f32.metal");
1018 sources.insert("fused_norm_add_f32".into(), fused_norm_add_f32_src);
1019 // ADR-028 iter-331 — float4 + simd_sum variant (peer-pattern,
1020 // ported from llama.cpp kernel_rms_norm_fuse_impl<float4, 3>).
1021 // Env-gated via HF2Q_FUSED_NORM_ADD_V2=1 in the dispatcher
1022 // (default ON since iter-331; opt-out via =0/false/off).
1023 sources.insert("fused_norm_add_f32_v2".into(), fused_norm_add_f32_src);
1024 sources.insert("fused_residual_norm_f32".into(), fused_norm_add_f32_src);
1025 sources.insert("fused_residual_norm_scalar_f32".into(), fused_norm_add_f32_src);
1026 sources.insert("fused_moe_routing_f32".into(), fused_norm_add_f32_src);
1027 // ADR-028 iter-363: V2 (simd_max + simd_sum) variant of MoE routing.
1028 sources.insert("fused_moe_routing_f32_v2".into(), fused_norm_add_f32_src);
1029 // ADR-029 iter-175 Step 1i: V3 = V2 + parallel SG-tournament top-K
1030 // (replaces V2's single-thread serial scan for k = 0..top_k).
1031 sources.insert("fused_moe_routing_f32_v3".into(), fused_norm_add_f32_src);
1032 sources.insert("fused_moe_routing_batch_f32".into(), fused_norm_add_f32_src);
1033 // ADR-029 iter-175 Step 1j: batched-prefill V3 (same parallel
1034 // SG-tournament top-K as fused_moe_routing_f32_v3, applied per-token
1035 // within each TG of the batched dispatch).
1036 sources.insert("fused_moe_routing_batch_f32_v3".into(), fused_norm_add_f32_src);
1037 sources.insert("fused_norm_add_scalar_f32".into(), fused_norm_add_f32_src);
1038 sources.insert("fused_moe_wsum_norm_add_f32".into(), fused_norm_add_f32_src);
1039 sources.insert("fused_moe_wsum_dnorm_add_f32".into(), fused_norm_add_f32_src);
1040
1041 // Argsort kernel (Story 2.3) — MoE top-K routing
1042 let argsort_src: &'static str = include_str!("shaders/argsort.metal");
1043 sources.insert("argsort_desc_f32".into(), argsort_src);
1044
1045 // Gather / index_select kernel (Story 2.4)
1046 let gather_src: &'static str = include_str!("shaders/gather.metal");
1047 sources.insert("gather_f32".into(), gather_src);
1048
1049 // F32 KV cache copy kernel (Session merge S1+S2)
1050 let kv_cache_copy_src: &'static str =
1051 include_str!("shaders/kv_cache_copy.metal");
1052 sources.insert("kv_cache_copy".into(), kv_cache_copy_src);
1053 sources.insert("kv_cache_copy_f32".into(), kv_cache_copy_src);
1054
1055 // Strided copy kernel (Story 2.5)
1056 let copy_src: &'static str = include_str!("shaders/copy.metal");
1057 sources.insert("strided_copy_f32".into(), copy_src);
1058 sources.insert("offset_copy_f32".into(), copy_src);
1059
1060 // Fused-QKV split kernel (ADR-005 W-5b.18 — replaces hf2q CPU
1061 // download → triple-loop split → 3× upload round-trip in
1062 // gpu_delta_net::layer_qkv_deinterleave).
1063 let qkv_split_src: &'static str = include_str!("shaders/qkv_split.metal");
1064 sources.insert("qkv_split_f32".into(), qkv_split_src);
1065
1066 // Tiled-GQA broadcast kernel (ADR-005 W-5b.19 — replaces hf2q CPU
1067 // tiled-replicate at gpu_delta_net::apply_gated_delta_net_chunk
1068 // GQA pre-expansion, ~497 ms / 10.4 ms-per-layer at PP4106).
1069 let repeat_tiled_src: &'static str =
1070 include_str!("shaders/repeat_tiled.metal");
1071 sources.insert("repeat_tiled_f32".into(), repeat_tiled_src);
1072
1073 // Dense F16 GEMM kernel (Story 2.6) — lm_head projection
1074 let dense_gemm_src: &'static str = include_str!("shaders/dense_gemm.metal");
1075 sources.insert("dense_gemm_f16".into(), dense_gemm_src);
1076 sources.insert("dense_matvec_f16".into(), dense_gemm_src);
1077 sources.insert("dense_matvec_f16w_f32io".into(), dense_gemm_src);
1078 // BF16-weight mat-vec: BF16 weights × F32 input → F32 output (decode lm_head)
1079 sources.insert("dense_matvec_bf16w_f32io".into(), dense_gemm_src);
1080 // Pure F32 mat-vec: F32 weights × F32 input → F32 output (decode lm_head)
1081 sources.insert("dense_matvec_f32".into(), dense_gemm_src);
1082
1083 // Standalone FWHT for TurboQuant pre/post-rotation (SIMD shuffle, zero barriers)
1084 let fwht_src: &'static str = include_str!("shaders/fwht_standalone.metal");
1085 sources.insert("fwht_standalone_f32_d256".into(), fwht_src);
1086 sources.insert("fwht_standalone_f32_d512".into(), fwht_src);
1087 // ADR-007 iter-14 D1 SRHT variants: sign pre-mult (for Q) + sign undo (for output)
1088 sources.insert("fwht_sign_premult_f32_d256".into(), fwht_src);
1089 sources.insert("fwht_sign_premult_f32_d512".into(), fwht_src);
1090 sources.insert("fwht_sign_undo_f32_d256".into(), fwht_src);
1091 sources.insert("fwht_sign_undo_f32_d512".into(), fwht_src);
1092
1093 // Fast Hadamard quantize (SIMD shuffle, zero barriers)
1094 let hq_fast_src: &'static str = include_str!("shaders/hadamard_quantize_kv_fast.metal");
1095 sources.insert("hadamard_quantize_kv_fast_d256".into(), hq_fast_src);
1096 sources.insert("hadamard_quantize_kv_fast_d512".into(), hq_fast_src);
1097 // ADR-028 iter-485 (Phase 7d / H4): fused K+V single-position 4-bit encoder.
1098 sources.insert("hadamard_quantize_kv_fast_dual_d256".into(), hq_fast_src);
1099 sources.insert("hadamard_quantize_kv_fast_dual_d512".into(), hq_fast_src);
1100 // Track B (iter-21): higher-bit (5/6-bit) quantize kernels (byte-packed)
1101 sources.insert("hadamard_quantize_kv_hb_d256".into(), hq_fast_src);
1102 sources.insert("hadamard_quantize_kv_hb_d512".into(), hq_fast_src);
1103 // ADR-028 iter-148: fused K+V single-position HB encoder
1104 sources.insert("hadamard_quantize_kv_hb_dual_d256".into(), hq_fast_src);
1105 sources.insert("hadamard_quantize_kv_hb_dual_d512".into(), hq_fast_src);
1106 // ADR-028 Phase 10e.5 (iter-351): no-FWHT V quantize for hybrid path.
1107 // Same byte-packed Lloyd-Max codebook output, but skips the Hadamard
1108 // rotation so dequant in SDPA recovers raw V (no FWHT-undo needed).
1109 sources.insert("kv_quantize_v_no_fwht_d256".into(), hq_fast_src);
1110 sources.insert("kv_quantize_v_no_fwht_d512".into(), hq_fast_src);
1111 // ADR-028 Phase 10c.5 (iter-354): fused F16-K-copy + V-no-FWHT-encode.
1112 // Saves 30 KV-write dispatches/decode-token at gemma4 30L by combining
1113 // the per-layer K-cast and V-encode into a single dispatch (Z-dim).
1114 sources.insert("kv_copy_kf16_quantize_v_no_fwht_d256".into(), hq_fast_src);
1115 sources.insert("kv_copy_kf16_quantize_v_no_fwht_d512".into(), hq_fast_src);
1116
1117 // iter-20 Leg F: TQ KV dequantize kernel (nibbles+norms → F32)
1118 let tq_dq_src: &'static str = include_str!("shaders/tq_dequantize_kv.metal");
1119 sources.insert("tq_dequantize_kv".into(), tq_dq_src);
1120 // Track B (iter-21): higher-bit dequantize kernel (byte-packed indices)
1121 sources.insert("tq_dequantize_hb_kv".into(), tq_dq_src);
1122 // ADR-027 Phase B iter-30 (hf2q sub-sub-iter 23c-β.1): sequence-batch
1123 // dequant variant. Same MSL source; new kernel entry point
1124 // `tq_dequantize_hb_kv_seq` reads positions [start_pos..start_pos+n_tokens)
1125 // in one dispatch (one threadgroup per (kv_head, position)). Unblocks
1126 // hf2q's TQ-aware prefill SDPA path (current per-position kernel
1127 // requires cur_len separate dispatches).
1128 sources.insert("tq_dequantize_hb_kv_seq".into(), tq_dq_src);
1129
1130 // iter-24: native higher-bit (5/6/8-bit) TQ SDPA kernel (byte-packed K/V)
1131 let tq_hb_src: &'static str = include_str!("shaders/flash_attn_vec_tq_hb.metal");
1132 sources.insert("flash_attn_vec_tq_hb_dk256".into(), tq_hb_src);
1133 sources.insert("flash_attn_vec_tq_hb_dk512".into(), tq_hb_src);
1134
1135 // ADR-028 §iter-485 (Phase 7d H3): fused TQ-HB reduce + FWHT-sign-undo.
1136 // Combines flash_attn_vec_reduce + fwht_sign_undo_f32 into a single
1137 // dispatch, saving 1 dispatch + 1 forced barrier per layer per decode
1138 // token. Gated by env flag `HF2Q_TQ_HB_OUT_FUSED=1` in forward_mlx.rs.
1139 let reduce_undo_src: &'static str = include_str!("shaders/flash_attn_vec_reduce_tq_hb_undo.metal");
1140 sources.insert("flash_attn_vec_reduce_tq_hb_undo_dk256".into(), reduce_undo_src);
1141 sources.insert("flash_attn_vec_reduce_tq_hb_undo_dk512".into(), reduce_undo_src);
1142
1143 // ADR-028 Phase 10d (iter-349): hybrid F16-K + TQ-HB-V SDPA kernel.
1144 // Same V-side codebook as flash_attn_vec_tq_hb (5/6/8-bit Lloyd-Max);
1145 // K-side reads F16 dense — peer-equivalent layout, no codebook lookup.
1146 let hybrid_src: &'static str = include_str!("shaders/flash_attn_vec_hybrid.metal");
1147 sources.insert("flash_attn_vec_hybrid_dk256".into(), hybrid_src);
1148 sources.insert("flash_attn_vec_hybrid_dk512".into(), hybrid_src);
1149 // ADR-040 M4 — batched multi-seq decode flash (same source file).
1150 sources.insert("flash_attn_vec_hybrid_batched_dk256".into(), hybrid_src);
1151 sources.insert("flash_attn_vec_hybrid_batched_dk512".into(), hybrid_src);
1152
1153 // ADR-029: verbatim llama.cpp peer port.
1154 // F16-K + F16-V, DK=DV=256, NWG=1, NSG=1, NE=1. No function constants — baked.
1155 let peer_port_src: &'static str = include_str!("shaders/flash_attn_vec_peer_port_f16.metal");
1156 sources.insert("flash_attn_vec_peer_port_f16_dk256_dv256".into(), peer_port_src);
1157
1158 // ADR-029 iter-134: peer reduce kernel (verbatim port of ggml-metal.metal 7235-7275).
1159 // Pairs with the NWG=32 vec kernel to match peer's actual runtime dispatch.
1160 let peer_port_reduce_src: &'static str =
1161 include_str!("shaders/flash_attn_vec_peer_port_f16_reduce.metal");
1162 sources.insert(
1163 "flash_attn_vec_peer_port_f16_reduce_dv256_nwg32".into(),
1164 peer_port_reduce_src,
1165 );
1166
1167 // ADR-029 iter-135: NWG=32 variant of the verbatim peer port. Same body as
1168 // flash_attn_vec_peer_port_f16.metal with NWG=1→32. Pairs with iter-134 reduce kernel.
1169 let peer_port_nwg32_src: &'static str =
1170 include_str!("shaders/flash_attn_vec_peer_port_f16_nwg32.metal");
1171 sources.insert(
1172 "flash_attn_vec_peer_port_f16_nwg32_dk256_dv256".into(),
1173 peer_port_nwg32_src,
1174 );
1175
1176 // GPU sampling kernels — eliminate logits readback (Phase 6)
1177 let argmax_src: &'static str = include_str!("shaders/argmax.metal");
1178 sources.insert("argmax_f32".into(), argmax_src);
1179 let softmax_sample_src: &'static str =
1180 include_str!("shaders/softmax_sample.metal");
1181 sources.insert("softmax_sample_f32".into(), softmax_sample_src);
1182 // Top-K kernel for Q8 rerank: avoids full-logits readback.
1183 let top_k_src: &'static str = include_str!("shaders/top_k.metal");
1184 sources.insert("top_k_f32".into(), top_k_src);
1185
1186 // MoE GPU routing + weighted reduce (ADR-013 P13.3 perf).
1187 // Replaces CPU softmax+topk round-trip and CPU weighted accumulate.
1188 let moe_stk_src: &'static str =
1189 include_str!("shaders/moe_softmax_topk.metal");
1190 sources.insert("moe_softmax_topk_f32".into(), moe_stk_src);
1191 let moe_wr_src: &'static str =
1192 include_str!("shaders/moe_weighted_reduce.metal");
1193 sources.insert("moe_weighted_reduce_f32".into(), moe_wr_src);
1194 let sdpa_decode_src: &'static str =
1195 include_str!("shaders/sdpa_decode.metal");
1196 sources.insert("sdpa_decode".into(), sdpa_decode_src);
1197
1198 Self {
1199 cache: HashMap::new(),
1200 sources,
1201 precompiled_lib: None,
1202 precompiled_load_attempted: false,
1203 }
1204 }
1205
1206 /// Try to obtain the precompiled `default.metallib` Library, loading it
1207 /// lazily on first call. Returns `None` when:
1208 /// - `MLX_PRECOMPILED_METALLIB` is unset (default)
1209 /// - The embedded blob is empty (build.rs skipped metallib build)
1210 /// - `device.new_library_with_data` failed previously
1211 /// - The previous load attempt already failed (no retry)
1212 fn try_precompiled_lib(
1213 &mut self,
1214 device: &metal::DeviceRef,
1215 ) -> Option<&metal::LibraryRef> {
1216 if !precompiled_enabled() {
1217 return None;
1218 }
1219 if !self.precompiled_load_attempted {
1220 self.precompiled_load_attempted = true;
1221 if EMBEDDED_METALLIB.is_empty() {
1222 return None;
1223 }
1224 // Apple's `newLibraryWithData:` expects a dispatch_data_t.
1225 // metal-rs wraps this via `new_library_with_data` which takes
1226 // a `&[u8]`.
1227 match device.new_library_with_data(EMBEDDED_METALLIB) {
1228 Ok(lib) => self.precompiled_lib = Some(lib),
1229 Err(_) => self.precompiled_lib = None,
1230 }
1231 }
1232 self.precompiled_lib.as_deref()
1233 }
1234
1235 /// Register a shader source at runtime (useful for testing and dynamic
1236 /// kernel generation).
1237 pub fn register_source(&mut self, name: impl Into<String>, source: &'static str) {
1238 let name = name.into();
1239 // Invalidate any cached pipeline for this name since the source changed.
1240 self.cache.remove(&name);
1241 self.sources.insert(name, source);
1242 }
1243
1244 /// ADR-033 §Pi Task #20 iter 11 (2026-05-23) — eagerly compile a list
1245 /// of kernel pipelines to move first-call JIT/PSO-creation cost out of
1246 /// the prefill hot path and into the model-load window.
1247 ///
1248 /// The profiler showed that on Qwen3.6 35B-A3B MoE prefill at seq=553,
1249 /// the FIRST FA layer + FIRST FFN layer take ~40ms each (vs ~14µs
1250 /// warm) — that's 80ms of the 221ms prefill, dominated by Metal
1251 /// pipeline state creation. Pre-creating these pipelines at load time
1252 /// (when 3.3s is already being spent on model parse + upload) is a
1253 /// strict perf win for measured prefill throughput.
1254 ///
1255 /// Best-effort: silently skips kernels that aren't registered (e.g.,
1256 /// list contains a kernel name for an arch this build doesn't use).
1257 /// Logs at debug level on failure to keep load-path quiet.
1258 ///
1259 /// Returns the count of pipelines successfully prewarmed.
1260 pub fn prewarm_pipelines(
1261 &mut self,
1262 device: &metal::DeviceRef,
1263 names: &[&str],
1264 ) -> usize {
1265 let mut warmed = 0_usize;
1266 for name in names {
1267 // Skip if already cached.
1268 if self.cache.contains_key(*name) {
1269 warmed += 1;
1270 continue;
1271 }
1272 // Skip if no source registered for this name.
1273 if !self.sources.contains_key(*name) {
1274 continue;
1275 }
1276 // Best-effort: ignore errors so one broken kernel doesn't
1277 // poison the whole prewarm pass.
1278 if self.get_pipeline(name, device).is_ok() {
1279 warmed += 1;
1280 }
1281 }
1282 warmed
1283 }
1284
1285 /// ADR-033 §Pi Task #20 iter 12 (2026-05-23) — prewarm pipelines that
1286 /// require `[[function_constant]]` specialization. Each entry is
1287 /// `(name, &[(constant_index, bool_value)])`. Mirrors
1288 /// `prewarm_pipelines` but routes through
1289 /// `get_pipeline_with_bool_constants` so kernels declaring
1290 /// `function_constant` decls without defaults can be safely
1291 /// prewarmed.
1292 ///
1293 /// Use case: hot-path kernels like `flash_attn_prefill_bf16_d256`
1294 /// (uses bool constants 200/201/300/301/303 for align/mask/causal/blk
1295 /// flags) cannot be safely prewarmed without specialization — Metal
1296 /// `validateWithDevice:` asserts and aborts the process. Provide
1297 /// the constants production uses and prewarming becomes safe.
1298 ///
1299 /// Returns count warmed.
1300 pub fn prewarm_pipelines_with_bool_constants(
1301 &mut self,
1302 device: &metal::DeviceRef,
1303 entries: &[(&str, &[(usize, bool)])],
1304 ) -> usize {
1305 let mut warmed = 0_usize;
1306 for (name, bool_constants) in entries {
1307 if !self.sources.contains_key(*name) {
1308 continue;
1309 }
1310 if self
1311 .get_pipeline_with_bool_constants(name, device, bool_constants)
1312 .is_ok()
1313 {
1314 warmed += 1;
1315 }
1316 }
1317 warmed
1318 }
1319
1320 /// ADR-033 §Pi Task #20 iter 11 (2026-05-23) — prewarm every registered
1321 /// kernel source. Useful when the exact set of needed kernels is hard
1322 /// to enumerate (e.g., serving paths that span multiple arches).
1323 /// Total cost is bounded by the number of registered kernels times
1324 /// the per-pipeline PSO creation cost (~5-15ms typical on M-series).
1325 ///
1326 /// Returns (warmed, skipped) counts.
1327 pub fn prewarm_all(&mut self, device: &metal::DeviceRef) -> (usize, usize) {
1328 let names: Vec<String> = self.sources.keys().cloned().collect();
1329 let mut warmed = 0_usize;
1330 let mut skipped = 0_usize;
1331 for name in &names {
1332 if self.cache.contains_key(name) {
1333 warmed += 1;
1334 continue;
1335 }
1336 if self.get_pipeline(name, device).is_ok() {
1337 warmed += 1;
1338 } else {
1339 skipped += 1;
1340 }
1341 }
1342 (warmed, skipped)
1343 }
1344
1345 /// Get a compiled compute pipeline for the named kernel function.
1346 ///
1347 /// On first call for a given name, this compiles the MSL source into a
1348 /// Metal library, extracts the named function, and creates a
1349 /// `ComputePipelineState`. Subsequent calls return the cached pipeline.
1350 ///
1351 /// # Errors
1352 ///
1353 /// * `MlxError::KernelNotFound` — no source registered for this name.
1354 /// * `MlxError::ShaderCompilationError` — MSL compilation or pipeline
1355 /// creation failed.
1356 pub fn get_pipeline(
1357 &mut self,
1358 name: &str,
1359 device: &metal::DeviceRef,
1360 ) -> Result<&ComputePipelineState> {
1361 if !self.cache.contains_key(name) {
1362 // ADR-029 iter-175 Step 1l: precompiled .metallib fast path.
1363 // When MLX_PRECOMPILED_METALLIB=1 AND the kernel exists in the
1364 // embedded library, use it. Otherwise fall through to runtime
1365 // source compile. Empirically ~+5.89% faster on q6_K matvec
1366 // (iter 1k bench).
1367 let precompiled_function = self
1368 .try_precompiled_lib(device)
1369 .and_then(|lib| lib.get_function(name, None).ok());
1370
1371 let function = match precompiled_function {
1372 Some(f) => f,
1373 None => {
1374 // Slow path: compile the shader.
1375 let source = self.sources.get(name).ok_or_else(|| {
1376 MlxError::KernelNotFound(name.to_string())
1377 })?;
1378
1379 let compile_opts = metal::CompileOptions::new();
1380 let library = device
1381 .new_library_with_source(source, &compile_opts)
1382 .map_err(|msg| MlxError::ShaderCompilationError {
1383 name: name.to_string(),
1384 message: msg,
1385 })?;
1386
1387 library
1388 .get_function(name, None)
1389 .map_err(|msg| MlxError::ShaderCompilationError {
1390 name: name.to_string(),
1391 message: msg,
1392 })?
1393 }
1394 };
1395
1396 // Build the pipeline through a descriptor so we can attach a
1397 // human-readable label. The label propagates into Instruments /
1398 // xctrace Metal System Trace as the per-pipeline identifier
1399 // (`metal-object-label` schema), giving us per-kernel attribution
1400 // instead of the generic "Compute Command 0" placeholder.
1401 //
1402 // `MTLComputePipelineState.label` is read-only after creation per
1403 // the Apple Metal spec; the only supported way to set it is via
1404 // the descriptor before pipeline creation. ADR-015 iter9b.
1405 let descriptor = ComputePipelineDescriptor::new();
1406 descriptor.set_compute_function(Some(&function));
1407 descriptor.set_label(name);
1408 // ADR-028 iter-376: threadGroupSizeIsMultipleOfThreadExecutionWidth
1409 // hint allows the Metal compiler to skip bounds checks and use more
1410 // aggressive codegen. Opt-in via HF2Q_PIPELINE_TG_MULT_HINT=1.
1411 // SAFETY: every dispatched threadgroup MUST be a multiple of 32 at
1412 // runtime — Apple specifies undefined behavior otherwise. Our hot
1413 // kernels use tg_size ∈ {32, 64, 256, 1024} (all multiples of 32).
1414 if std::env::var("HF2Q_PIPELINE_TG_MULT_HINT").ok().as_deref() == Some("1") {
1415 descriptor.set_thread_group_size_is_multiple_of_thread_execution_width(true);
1416 }
1417
1418 let pipeline = device
1419 .new_compute_pipeline_state(&descriptor)
1420 .map_err(|msg| MlxError::ShaderCompilationError {
1421 name: name.to_string(),
1422 message: msg,
1423 })?;
1424
1425 self.cache.insert(name.to_string(), pipeline);
1426 }
1427
1428 // At this point the pipeline is guaranteed to be in the cache.
1429 // We use `ok_or_else` instead of `expect` to satisfy the no-panic policy.
1430 self.cache.get(name).ok_or_else(|| {
1431 MlxError::KernelNotFound(name.to_string())
1432 })
1433 }
1434
1435 /// Get a compiled compute pipeline for the named kernel, specialized with
1436 /// Metal function constants (both bool and i32 in one call).
1437 ///
1438 /// `bool_constants` contains `(index, value)` pairs mapping to
1439 /// `[[function_constant(index)]]` bool declarations in the MSL shader.
1440 /// `int_constants` contains `(index, value)` pairs mapping to
1441 /// `[[function_constant(index)]]` int (int32_t) declarations in the MSL
1442 /// shader.
1443 ///
1444 /// Pipelines are cached by a composite key:
1445 /// `"<name>|<index>:b<0|1>|...|<index>:i<value>|..."`. The 'b' prefix
1446 /// marks bool entries and the 'i' prefix marks i32 entries, making the
1447 /// format unambiguous regardless of constant ordering. Distinct
1448 /// `(name, constants)` combinations each compile to a separate pipeline;
1449 /// the slow compilation path runs at most once per unique combination.
1450 ///
1451 /// # Errors
1452 ///
1453 /// * `MlxError::KernelNotFound` — no source registered for this name.
1454 /// * `MlxError::ShaderCompilationError` — MSL compilation, function
1455 /// specialisation, or pipeline creation failed.
1456 pub fn get_pipeline_with_constants(
1457 &mut self,
1458 name: &str,
1459 device: &metal::DeviceRef,
1460 bool_constants: &[(usize, bool)],
1461 int_constants: &[(usize, i32)],
1462 ) -> Result<&ComputePipelineState> {
1463 // Build a composite cache key so distinct constant combinations each
1464 // compile to their own pipeline. Bool entries use the 'b' type marker
1465 // and i32 entries use 'i'; this prevents a collision between, e.g.,
1466 // bool index 5 value 1 and int index 5 value 1.
1467 let mut cache_key = name.to_string();
1468 for &(index, value) in bool_constants {
1469 cache_key.push('|');
1470 cache_key.push_str(&index.to_string());
1471 cache_key.push_str(if value { ":b1" } else { ":b0" });
1472 }
1473 for &(index, value) in int_constants {
1474 cache_key.push('|');
1475 cache_key.push_str(&index.to_string());
1476 cache_key.push(':');
1477 cache_key.push('i');
1478 cache_key.push_str(&value.to_string());
1479 }
1480
1481 if !self.cache.contains_key(&cache_key) {
1482 // Build the FunctionConstantValues object with all bool and i32
1483 // constants. Metal's set_constant_value_at_index reads the value
1484 // through a raw pointer; the pointed-to bytes must match the size
1485 // declared in the MSL shader (1 byte for bool, 4 bytes for int).
1486 let fcv = FunctionConstantValues::new();
1487
1488 for &(index, value) in bool_constants {
1489 // MTLDataType::Bool = 53 (metal-rs argument.rs).
1490 // The Metal runtime reads it as an Objective-C BOOL (uint8_t).
1491 let v: u8 = if value { 1 } else { 0 };
1492 fcv.set_constant_value_at_index(
1493 (&v as *const u8).cast::<std::ffi::c_void>(),
1494 MTLDataType::Bool,
1495 index as u64,
1496 );
1497 }
1498
1499 for &(index, value) in int_constants {
1500 // MTLDataType::Int = 29 (metal-rs argument.rs).
1501 // The Metal runtime reads 4 bytes as a signed 32-bit integer,
1502 // matching the Metal shader type `constant int`.
1503 fcv.set_constant_value_at_index(
1504 (&value as *const i32).cast::<std::ffi::c_void>(),
1505 MTLDataType::Int,
1506 index as u64,
1507 );
1508 }
1509
1510 // ADR-029 iter-175 Step 1l: try precompiled .metallib first.
1511 // Step 1m: gated separately on MLX_PRECOMPILED_METALLIB_FCV=1
1512 // so we can isolate whether the integration regression at
1513 // Step 1l (tg50 95.4 → 62.1) lives in this FCV path vs the
1514 // no-FCV path in `get_pipeline`.
1515 //
1516 // get_function with FCV takes ownership of the FCV, so we
1517 // build a separate one for the precompiled probe.
1518 let precompiled_function = if precompiled_fcv_enabled() {
1519 let probe_fcv = FunctionConstantValues::new();
1520 for &(index, value) in bool_constants {
1521 let v: u8 = if value { 1 } else { 0 };
1522 probe_fcv.set_constant_value_at_index(
1523 (&v as *const u8).cast::<std::ffi::c_void>(),
1524 MTLDataType::Bool,
1525 index as u64,
1526 );
1527 }
1528 for &(index, value) in int_constants {
1529 probe_fcv.set_constant_value_at_index(
1530 (&value as *const i32).cast::<std::ffi::c_void>(),
1531 MTLDataType::Int,
1532 index as u64,
1533 );
1534 }
1535 self.try_precompiled_lib(device)
1536 .and_then(|lib| lib.get_function(name, Some(probe_fcv)).ok())
1537 } else {
1538 None
1539 };
1540
1541 let function = match precompiled_function {
1542 Some(f) => f,
1543 None => {
1544 // Slow path: compile the shader with function constant specialisation.
1545 let source = self.sources.get(name).ok_or_else(|| {
1546 MlxError::KernelNotFound(name.to_string())
1547 })?;
1548
1549 let compile_opts = metal::CompileOptions::new();
1550 let library = device
1551 .new_library_with_source(source, &compile_opts)
1552 .map_err(|msg| MlxError::ShaderCompilationError {
1553 name: name.to_string(),
1554 message: msg,
1555 })?;
1556
1557 library
1558 .get_function(name, Some(fcv))
1559 .map_err(|msg| MlxError::ShaderCompilationError {
1560 name: name.to_string(),
1561 message: msg,
1562 })?
1563 }
1564 };
1565
1566 // Label this specialisation with the full composite cache key
1567 // (e.g. `kernel_mul_mv_q4_0_f32|0:b1|3:i32`) so xctrace Metal
1568 // System Trace shows each function-constant variant as a distinct
1569 // pipeline. Without this, all specialisations share a generic
1570 // "Compute Command 0" identifier and we cannot attribute µs/token
1571 // to a specific (kernel, constants) combination. ADR-015 iter9b.
1572 let descriptor = ComputePipelineDescriptor::new();
1573 descriptor.set_compute_function(Some(&function));
1574 descriptor.set_label(&cache_key);
1575 // ADR-028 iter-376: same hint as primary pipeline path.
1576 if std::env::var("HF2Q_PIPELINE_TG_MULT_HINT").ok().as_deref() == Some("1") {
1577 descriptor.set_thread_group_size_is_multiple_of_thread_execution_width(true);
1578 }
1579
1580 let pipeline = device
1581 .new_compute_pipeline_state(&descriptor)
1582 .map_err(|msg| MlxError::ShaderCompilationError {
1583 name: name.to_string(),
1584 message: msg,
1585 })?;
1586
1587 self.cache.insert(cache_key.clone(), pipeline);
1588 }
1589
1590 self.cache.get(&cache_key).ok_or_else(|| {
1591 MlxError::KernelNotFound(name.to_string())
1592 })
1593 }
1594
1595 /// Get a compiled compute pipeline for the named kernel, specialized with
1596 /// Metal bool function constants.
1597 ///
1598 /// The `bool_constants` slice contains `(index, value)` pairs. Each pair
1599 /// maps to a `[[function_constant(index)]]` declaration in the MSL shader.
1600 ///
1601 /// This is a thin wrapper around [`get_pipeline_with_constants`] that
1602 /// passes an empty `int_constants` slice. Existing callers continue to
1603 /// work without modification; the cache-key format for pure-bool pipelines
1604 /// is compatible (bool entries carry the 'b' type marker, which is the
1605 /// only format ever written by this wrapper).
1606 ///
1607 /// # Errors
1608 ///
1609 /// * `MlxError::KernelNotFound` — no source registered for this name.
1610 /// * `MlxError::ShaderCompilationError` — MSL compilation, function
1611 /// specialisation, or pipeline creation failed.
1612 pub fn get_pipeline_with_bool_constants(
1613 &mut self,
1614 name: &str,
1615 device: &metal::DeviceRef,
1616 bool_constants: &[(usize, bool)],
1617 ) -> Result<&ComputePipelineState> {
1618 self.get_pipeline_with_constants(name, device, bool_constants, &[])
1619 }
1620
1621 /// Check if a pipeline for the given name is already compiled and cached.
1622 pub fn is_cached(&self, name: &str) -> bool {
1623 self.cache.contains_key(name)
1624 }
1625
1626 /// Number of compiled pipelines currently in the cache.
1627 pub fn cached_count(&self) -> usize {
1628 self.cache.len()
1629 }
1630
1631 /// Number of registered shader sources.
1632 pub fn source_count(&self) -> usize {
1633 self.sources.len()
1634 }
1635}
1636
1637impl Default for KernelRegistry {
1638 fn default() -> Self {
1639 Self::new()
1640 }
1641}
1642
1643#[cfg(test)]
1644mod tests {
1645 use super::*;
1646
1647 /// Minimal Metal shader that uses a single int function constant.
1648 ///
1649 /// The kernel writes the constant value N into the first element of the
1650 /// output buffer, allowing the test to verify that the Metal compiler
1651 /// actually sees distinct specialisations for N=4 and N=8.
1652 ///
1653 /// The shader is intentionally trivial — we only need it to *compile* with
1654 /// an int function constant; correctness of the kernel logic is not under
1655 /// test here.
1656 const INT_FC_TEST_SHADER: &str = r#"
1657#include <metal_stdlib>
1658using namespace metal;
1659
1660constant int test_N [[function_constant(100)]];
1661
1662kernel void int_fc_test_kernel(
1663 device int* out [[buffer(0)]],
1664 uint tid [[thread_position_in_grid]])
1665{
1666 if (tid == 0) {
1667 out[0] = test_N;
1668 }
1669}
1670"#;
1671
1672 /// Verify that `get_pipeline_with_constants` produces distinct cached
1673 /// pipelines for different i32 function-constant values, and that
1674 /// `get_pipeline_with_bool_constants` (the backward-compat wrapper) still
1675 /// works correctly with the new 'b'-prefixed cache-key format.
1676 ///
1677 /// This test requires a real Metal device and is therefore marked
1678 /// `#[ignore]` on non-Apple platforms, but runs unconditionally on macOS.
1679 #[test]
1680 fn test_int_fc_distinct_pipelines_and_bool_compat() {
1681 let device = metal::Device::system_default()
1682 .expect("no Metal device — run on Apple Silicon or x86 Mac with Metal support");
1683
1684 let mut registry = KernelRegistry::new();
1685
1686 // Register the inline test shader under a name that cannot collide with
1687 // any production kernel.
1688 registry.register_source("int_fc_test_kernel", INT_FC_TEST_SHADER);
1689
1690 // Compile with N=4.
1691 let p4_ptr = registry
1692 .get_pipeline_with_constants(
1693 "int_fc_test_kernel",
1694 &device,
1695 &[], // no bool constants
1696 &[(100, 4_i32)], // int constant index 100 = 4
1697 )
1698 .expect("pipeline N=4 should compile") as *const _;
1699
1700 // Cache must now have exactly 1 entry for this kernel.
1701 // (Other production kernels may already be in cache from new(); here
1702 // we check that the N=4 key was inserted.)
1703 let count_after_n4 = registry.cached_count();
1704
1705 // Compile with N=8 — must produce a SEPARATE pipeline.
1706 let p8_ptr = registry
1707 .get_pipeline_with_constants(
1708 "int_fc_test_kernel",
1709 &device,
1710 &[],
1711 &[(100, 8_i32)],
1712 )
1713 .expect("pipeline N=8 should compile") as *const _;
1714
1715 // Cache must have grown by exactly 1.
1716 assert_eq!(
1717 registry.cached_count(),
1718 count_after_n4 + 1,
1719 "N=8 must produce a new cache entry"
1720 );
1721
1722 // The two pipelines must be distinct objects in the cache.
1723 assert_ne!(
1724 p4_ptr, p8_ptr,
1725 "N=4 and N=8 specialisations must be separate ComputePipelineState objects"
1726 );
1727
1728 // A second call with N=4 must return the SAME pipeline (cache hit, no
1729 // new compilation).
1730 let p4_again_ptr = registry
1731 .get_pipeline_with_constants(
1732 "int_fc_test_kernel",
1733 &device,
1734 &[],
1735 &[(100, 4_i32)],
1736 )
1737 .expect("pipeline N=4 cache hit should succeed") as *const _;
1738
1739 assert_eq!(
1740 registry.cached_count(),
1741 count_after_n4 + 1,
1742 "repeated N=4 call must be a cache hit, not a new entry"
1743 );
1744 assert_eq!(
1745 p4_ptr, p4_again_ptr,
1746 "repeated N=4 call must return the same pipeline pointer"
1747 );
1748
1749 // Verify backward compatibility: get_pipeline_with_bool_constants must
1750 // still route through get_pipeline_with_constants and produce a cached
1751 // pipeline without panicking.
1752 //
1753 // We register a separate bool-constant shader that does NOT use a bool
1754 // function constant (so the Metal compiler ignores missing FCs for
1755 // this trivial case) — but the call path and cache-key format are what
1756 // matter here. We reuse the int_fc_test_kernel source; the bool FC is
1757 // simply unused by the shader (Metal allows unused FCs when the shader
1758 // declares them with `function_constant` but the value is never read).
1759 //
1760 // To avoid a Metal compiler error for an undeclared function constant,
1761 // we register a separate bare-kernel shader for the bool wrapper test.
1762 const BARE_SHADER: &str = r#"
1763#include <metal_stdlib>
1764using namespace metal;
1765kernel void bare_kernel(device int* out [[buffer(0)]], uint tid [[thread_position_in_grid]]) {
1766 if (tid == 0) { out[0] = 42; }
1767}
1768"#;
1769 registry.register_source("bare_kernel", BARE_SHADER);
1770
1771 let count_before_bool = registry.cached_count();
1772 let _bool_pipeline = registry
1773 .get_pipeline_with_bool_constants("bare_kernel", &device, &[])
1774 .expect("bool-constants wrapper with empty slice must succeed");
1775
1776 assert_eq!(
1777 registry.cached_count(),
1778 count_before_bool + 1,
1779 "bool-constants wrapper must insert one new cache entry"
1780 );
1781 }
1782
1783 /// Verify that the `MTLComputePipelineState.label` produced by
1784 /// `get_pipeline` and `get_pipeline_with_constants` actually propagates
1785 /// from the descriptor to the resulting pipeline state.
1786 ///
1787 /// This is the in-process smoke check for ADR-015 iter9b: we cannot
1788 /// reach into xctrace from Rust, but we can read back the same `label`
1789 /// property xctrace consumes via `ComputePipelineStateRef::label()`.
1790 /// If labels are missing or wrong here, the MST trace will also show
1791 /// generic identifiers — so this test gates the iter9 retry's
1792 /// per-Q4_0-kernel attribution.
1793 #[test]
1794 fn test_pipeline_labels_propagate_for_mst() {
1795 let device = metal::Device::system_default()
1796 .expect("no Metal device — run on Apple Silicon or x86 Mac with Metal support");
1797
1798 let mut registry = KernelRegistry::new();
1799
1800 // Reuse the same trivial shaders as the int-FC test.
1801 registry.register_source("int_fc_test_kernel", INT_FC_TEST_SHADER);
1802
1803 const BARE_SHADER_LABEL_TEST: &str = r#"
1804#include <metal_stdlib>
1805using namespace metal;
1806kernel void label_smoke_kernel(device int* out [[buffer(0)]], uint tid [[thread_position_in_grid]]) {
1807 if (tid == 0) { out[0] = 7; }
1808}
1809"#;
1810 registry.register_source("label_smoke_kernel", BARE_SHADER_LABEL_TEST);
1811
1812 // Plain get_pipeline path — label must equal the kernel name.
1813 // Capture as owned String so the cache borrow is released before
1814 // the next get_pipeline_with_constants call below.
1815 let plain_label = registry
1816 .get_pipeline("label_smoke_kernel", &device)
1817 .expect("plain pipeline must compile")
1818 .label()
1819 .to_string();
1820 assert_eq!(
1821 plain_label, "label_smoke_kernel",
1822 "get_pipeline must label the pipeline with the kernel name (xctrace MST attribution)"
1823 );
1824
1825 // Constants path — label must equal the composite cache key so each
1826 // function-constant variant is individually attributable in MST.
1827 // We capture the label as an owned String to release the borrow on
1828 // the cache before fetching the next specialisation.
1829 let label_v7 = registry
1830 .get_pipeline_with_constants(
1831 "int_fc_test_kernel",
1832 &device,
1833 &[],
1834 &[(100, 7_i32)],
1835 )
1836 .expect("specialised pipeline must compile")
1837 .label()
1838 .to_string();
1839 assert_eq!(
1840 label_v7, "int_fc_test_kernel|100:i7",
1841 "get_pipeline_with_constants must label with the cache_key so each \
1842 specialisation is distinct in xctrace MST"
1843 );
1844
1845 // A second specialisation must produce a different label.
1846 let label_v13 = registry
1847 .get_pipeline_with_constants(
1848 "int_fc_test_kernel",
1849 &device,
1850 &[],
1851 &[(100, 13_i32)],
1852 )
1853 .expect("second specialised pipeline must compile")
1854 .label()
1855 .to_string();
1856 assert_eq!(label_v13, "int_fc_test_kernel|100:i13");
1857 assert_ne!(
1858 label_v7, label_v13,
1859 "distinct constant values must yield distinct pipeline labels"
1860 );
1861 }
1862}