hf2q 0.1.32

Pure Rust CLI for converting HuggingFace models to hardware-optimized formats and serving them over an OpenAI-compatible API on Apple Silicon
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
//! Batched MoE FFN decode route (`HF2Q_QWEN_MOE_BATCHED=1`).
//!
//! One MoE FFN layer over `rows = 1..=32` decode or DFlash2 target rows in one
//! encoder segment, with the router and shared expert read in their GGUF storage types:
//!
//! | phase | dispatch | kernel |
//! |---|---|---|
//! | A | router logits `[rows, n_experts]` | `dense_matvec_f32_rows` (F32) |
//! | A | shared-expert gate logit `[rows, 1]` | `dense_matvec_f32_rows` (F32) |
//! | A | shared gate, shared up `[rows, shared_i]` | `quantized_matmul_ggml` m = rows (`kernel_mul_mv_<q>_f32` at 1 row, `_mN_r1_<rows>` at 2..5) |
//! | B | softmax + top-k + renorm over all rows | `moe_softmax_topk_simd_f32` |
//! | B | shared SwiGLU | `silu_mul_f32` |
//! | C | expert gate, expert up over `rows * top_k` pairs | `kernel_mul_mv_id_q4_K_f32_nr2` (Q4_K) or `kernel_mul_mv_id_<q>_f32` (forced matvec route) |
//! | C | shared down `[rows, hidden]` | `quantized_matmul_ggml` m = rows |
//! | D | expert SwiGLU | `silu_mul_f32` |
//! | E | expert down over `rows * top_k` pairs | `kernel_mul_mv_id_q4_K_f32_nr2` (Q4_K) or `kernel_mul_mv_id_<q>_f32[_nr2]` (forced matvec route) |
//! | F | weighted reduce + sigmoid(shared gate) * shared + residual | `moe_weighted_reduce_f32` |
//!
//! With `HF2Q_QWEN_MOE_STAGED_M8=1`, phases C–E instead use prepared
//! Q4_K/Q6_K planes. Gate and up remain separate F32 projections so the
//! established F32 SwiGLU and down-projection input preserve task quality;
//! both projections reuse one compact route schedule and gathered input.
//! Under a DFlash2 verify-row mask the schedule skips masked routes, so an
//! unselected row costs no expert tile and phase F never reads its rows.
//! With `HF2Q_QWEN_MOE_LIVE_TILES=1` as well, the layer runs
//! [`super::moe_live_tiles_fused`] instead: row-exact router logits at every
//! width, one schedule and one gate/up and down pass for the routed experts
//! and the shared expert, a BF16 SwiGLU intermediate, and passes that launch
//! the live tiles alone.
//!
//! Decode dispatches of one to eight rows preserve the established bitwise
//! single-row invariant. The DFlash2 verifier's width-32 pass uses dense MM
//! for the F32 router and shared-gate logits and is qualified against the F64
//! whole-layer reference instead. The serial decode builder
//! ([`super::gpu_ffn::build_moe_ffn_layer_gpu_q_into`] at one row) and the
//! joint step both run this route whenever the layer's weights were loaded
//! in native storage, so the switch is decided once at load.


use anyhow::{anyhow, bail, ensure, Context, Result};
use mlx_native::ops::dflash2_attention_pack::{
    dispatch_dflash2_mask_moe_routes, DFlash2MoeRouteMaskParams,
};
use mlx_native::ops::dense_matvec_f32_rows::{
    dispatch_dense_matvec_f32_rows, DENSE_MATVEC_F32_ROWS_MAX_ROWS,
};
use mlx_native::ops::dense_mm_f32_f32::{dense_matmul_f32_f32_tensor, DenseMmF32F32Params};
use mlx_native::ops::moe_softmax_topk::dispatch_moe_softmax_topk_simd;
use mlx_native::ops::moe_weighted_reduce::{
    dispatch_moe_weighted_reduce, dispatch_moe_weighted_reduce_masked,
};
use mlx_native::ops::quantized_matmul_ggml::{GgmlQuantizedMatmulParams, GgmlType};
use mlx_native::ops::quantized_matmul_id_ggml::{
    quantized_matmul_id_ggml_grouped_m8_epilogue,
    quantized_matmul_id_ggml_grouped_m8_epilogue_masked, quantized_matmul_id_ggml_mv,
    quantized_matmul_id_ggml_mv_masked, quantized_matmul_id_ggml_mv_q4_k_nr2,
    quantized_matmul_id_ggml_mv_q4_k_nr2_masked, GgmlQuantizedMatmulIdParams, GroupedM8Epilogue,
    GroupedM8Input,
};
use mlx_native::ops::silu_mul::dispatch_silu_mul;
use mlx_native::{CommandEncoder, DType, KernelRegistry, MlxBuffer, MlxDevice};

use super::decode_pool::pooled_alloc_buffer;
use super::execution_dispatch::quantized_matmul_ggml;
use super::ffn::MoeFfnShape;
use super::expert_storage::{ExpertRole, ExpertRoleRef};
use super::gpu_ffn::MoeFfnWeightsGpuQ;
use crate::inference::spec_decode::dflash2::route_profile;

/// Switch for the batched native-storage MoE decode route. On, with the two
/// expert switches below, in the Qwen3.6 route profile of a qualified
/// DFlash2 pair; off for every other artifact.
pub(crate) const QWEN_MOE_BATCHED_ENV: &str = "HF2Q_QWEN_MOE_BATCHED";
/// Experimental prepared staged-M8 route for Q4_K/Q6_K expert stacks.
/// This requires the batched native-storage MoE decode route.
pub(crate) const QWEN_MOE_STAGED_M8_ENV: &str = "HF2Q_QWEN_MOE_STAGED_M8";

/// Experimental live-tile expert route over the staged-M8 planes
/// ([`super::moe_live_tiles_fused`]). Requires [`QWEN_MOE_STAGED_M8_ENV`].
pub(crate) const QWEN_MOE_LIVE_TILES_ENV: &str = "HF2Q_QWEN_MOE_LIVE_TILES";

/// How one batched layer runs its routed experts.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum MoeExpertRoute {
    /// Native-block expert matvecs.
    Matvec,
    /// [`QWEN_MOE_STAGED_M8_ENV`]: separate F32 gate and up tiles.
    StagedM8,
    /// [`QWEN_MOE_LIVE_TILES_ENV`].
    LiveTiles,
}

impl MoeExpertRoute {
    /// Name of the route in the worker's configuration log.
    pub(crate) fn label(self) -> &'static str {
        match self {
            Self::Matvec => "matvec",
            Self::StagedM8 => "staged_m8",
            Self::LiveTiles => "live_tiles",
        }
    }
}

/// The expert route for the resolved batched switch and the raw values of
/// [`QWEN_MOE_STAGED_M8_ENV`] and [`QWEN_MOE_LIVE_TILES_ENV`] (unset or blank
/// means off). An invalid value, staged M8 without the batched route and
/// live tiles without staged M8 are errors: no combination falls back to
/// another route.
pub(crate) fn resolve_moe_expert_route(
    batched: bool,
    staged_m8: Option<&str>,
    live_tiles: Option<&str>,
) -> Result<MoeExpertRoute, String> {
    use super::joint_step_options::parse_switch;
    let staged = parse_switch(QWEN_MOE_STAGED_M8_ENV, staged_m8)?;
    let live = parse_switch(QWEN_MOE_LIVE_TILES_ENV, live_tiles)?;
    if staged && !batched {
        return Err(format!(
            "{QWEN_MOE_STAGED_M8_ENV}=1 requires {QWEN_MOE_BATCHED_ENV}=1"
        ));
    }
    if live && !staged {
        return Err(format!(
            "{QWEN_MOE_LIVE_TILES_ENV}=1 requires {QWEN_MOE_STAGED_M8_ENV}=1"
        ));
    }
    Ok(match (staged, live) {
        (_, true) => MoeExpertRoute::LiveTiles,
        (true, false) => MoeExpertRoute::StagedM8,
        (false, false) => MoeExpertRoute::Matvec,
    })
}

/// [`resolve_moe_expert_route`] over the routes resolved for the model this
/// thread loads or serves. Model load calls this before any upload, so an
/// invalid value or combination fails startup.
pub(crate) fn qwen_moe_expert_route() -> Result<MoeExpertRoute> {
    const STAGED_M8: route_profile::Switch = route_profile::switch(QWEN_MOE_STAGED_M8_ENV);
    const LIVE_TILES: route_profile::Switch = route_profile::switch(QWEN_MOE_LIVE_TILES_ENV);
    let batched = qwen_moe_batched_requested();
    route_profile::with_value(STAGED_M8, |staged_m8| {
        route_profile::with_value(LIVE_TILES, |live_tiles| {
            resolve_moe_expert_route(batched, staged_m8, live_tiles)
        })
    })
    .map_err(|error| anyhow::anyhow!("{error}"))
}

/// Widest row count one batched MoE layer accepts: the DFlash2 target width.
pub(crate) const MOE_BATCHED_MAX_ROWS: usize = 32;

/// Parse [`QWEN_MOE_BATCHED_ENV`]; unset or blank means off.
pub(crate) fn parse_qwen_moe_batched(raw: Option<&str>) -> Result<bool, String> {
    let Some(raw) = raw.map(str::trim).filter(|raw| !raw.is_empty()) else {
        return Ok(false);
    };
    match raw.to_ascii_lowercase().as_str() {
        "1" | "on" | "true" => Ok(true),
        "0" | "off" | "false" => Ok(false),
        _ => Err(format!(
            "{QWEN_MOE_BATCHED_ENV} must be 1/on/true or 0/off/false, got {raw:?}"
        )),
    }
}

/// [`QWEN_MOE_BATCHED_ENV`] as resolved for the model this thread loads or
/// serves. Invalid values warn once and keep the default (off).
pub(crate) fn qwen_moe_batched_requested() -> bool {
    const SWITCH: route_profile::Switch = route_profile::switch(QWEN_MOE_BATCHED_ENV);
    route_profile::with_value(SWITCH, parse_qwen_moe_batched).unwrap_or_else(|error| {
        static WARNED: std::sync::Once = std::sync::Once::new();
        WARNED.call_once(|| {
            tracing::warn!(error, fallback = false, "invalid Qwen MoE batched switch");
        });
        false
    })
}

/// Shared-expert storage types the batched route admits. Their GGML matmul
/// routes support the full `m = 1..=32` interval.
pub(crate) fn native_shared_types_supported(gate_up: GgmlType, down: GgmlType) -> bool {
    let exact = |t: GgmlType| matches!(t, GgmlType::Q4_K | GgmlType::Q6_K);
    exact(gate_up) && exact(down)
}

/// How a MoE layer stores its router and shared-expert weights on the GPU.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum MoeDenseStorage {
    /// Router, shared gate logit and shared gate/up/down uploaded as BF16
    /// (dequantized at load). Decode runs the serial builder once per row.
    Bf16,
    /// GGUF storage: router and shared gate logit F32, shared gate/up/down
    /// raw GGML blocks. Decode runs [`build_moe_ffn_layer_gpu_batched_into`].
    Native {
        shared_gate_up: GgmlType,
        shared_down: GgmlType,
    },
}

impl MoeDenseStorage {
    pub fn is_native(self) -> bool {
        matches!(self, Self::Native { .. })
    }
}

/// One of the router / shared-expert projections of a MoE layer.
#[derive(Clone, Copy, Debug)]
pub(crate) enum MoeDenseRole {
    Router,
    SharedGateLogit,
    SharedGate,
    SharedUp,
    SharedDown,
}

impl MoeDenseRole {
    pub(crate) fn weight(self, weights: &MoeFfnWeightsGpuQ) -> &MlxBuffer {
        match self {
            Self::Router => &weights.router,
            Self::SharedGateLogit => &weights.shared_gate_inp,
            Self::SharedGate => &weights.shared_gate,
            Self::SharedUp => &weights.shared_up,
            Self::SharedDown => &weights.shared_down,
        }
    }
}

/// Encode `output[rows, out] = input[rows, in] @ W^T` for a native-storage
/// router / shared-expert weight. F32 weights take the row-exact
/// `dense_matvec_f32_rows` at `rows <= 8` (the tensor matmul above, for
/// prefill chunks); GGML weights take `quantized_matmul_ggml` at `m = rows`.
#[allow(clippy::too_many_arguments)]
pub(crate) fn encode_native_dense_proj(
    enc: &mut CommandEncoder,
    registry: &mut KernelRegistry,
    device: &MlxDevice,
    input: &MlxBuffer,
    weights: &MoeFfnWeightsGpuQ,
    role: MoeDenseRole,
    output: &MlxBuffer,
    rows: u32,
    in_features: u32,
    out_features: u32,
) -> Result<()> {
    let MoeDenseStorage::Native {
        shared_gate_up,
        shared_down,
    } = weights.dense_storage
    else {
        bail!("{role:?}: native projection requested on BF16 MoE storage");
    };
    let weight = role.weight(weights);
    match role {
        MoeDenseRole::Router | MoeDenseRole::SharedGateLogit => {
            ensure!(
                weight.dtype() == DType::F32,
                "{role:?}: native router weights must be F32, got {:?}",
                weight.dtype()
            );
            if rows <= DENSE_MATVEC_F32_ROWS_MAX_ROWS {
                dispatch_dense_matvec_f32_rows(
                    enc,
                    registry,
                    device,
                    input,
                    weight,
                    output,
                    rows,
                    out_features,
                    in_features,
                )
                .with_context(|| format!("{role:?} dense_matvec_f32_rows"))
            } else {
                dense_matmul_f32_f32_tensor(
                    enc,
                    registry,
                    device,
                    weight,
                    input,
                    output,
                    &DenseMmF32F32Params {
                        m: rows,
                        n: out_features,
                        k: in_features,
                        src0_batch: 1,
                        src1_batch: 1,
                    },
                )
                .with_context(|| format!("{role:?} dense_matmul_f32_f32_tensor"))
            }
        }
        MoeDenseRole::SharedGate | MoeDenseRole::SharedUp | MoeDenseRole::SharedDown => {
            let ggml_type = if matches!(role, MoeDenseRole::SharedDown) {
                shared_down
            } else {
                shared_gate_up
            };
            quantized_matmul_ggml(
                enc,
                registry,
                device,
                input,
                weight,
                output,
                &GgmlQuantizedMatmulParams {
                    m: rows,
                    n: out_features,
                    k: in_features,
                    ggml_type,
                },
            )
            .map_err(|e| anyhow!("{role:?} quantized_matmul_ggml {ggml_type:?}: {e}"))
        }
    }
}

/// Expert matvec over `params.n_tokens * params.top_k` pairs on the forced
/// `mv_id` route (never the grouped `mm_id` route, whose reduction differs),
/// behind the same imatrix intercept as the serial builder. Q4_K experts take
/// the peer-layout kernel (`kernel_mul_mv_id_q4_K_f32_nr2`) at every width,
/// including one row, so a pair's result never depends on the width.
#[allow(clippy::too_many_arguments)]
fn dispatch_expert_mv(
    enc: &mut CommandEncoder,
    registry: &mut KernelRegistry,
    device: &MlxDevice,
    input: &MlxBuffer,
    weight: ExpertRoleRef<'_>,
    ids: &MlxBuffer,
    output: &MlxBuffer,
    params: &GgmlQuantizedMatmulIdParams,
    tag: &'static str,
    layer: usize,
    masked: bool,
) -> Result<()> {
    if let ExpertRoleRef::Prepared(planes) = weight {
        ensure!(!crate::quantize::imatrix::is_active(), "canonical expert storage cannot collect imatrix inputs");
        use mlx_native::ops::quantized_matmul_id_ggml as native;
        let routing = registry.ggml_routing_policy().copied()
            .unwrap_or_else(mlx_native::ggml_routing_policy_from_environment);
        let dispatched = match (params.ggml_type, masked) {
            (GgmlType::Q4_K, false) => native::quantized_matmul_id_ggml_prepared_mv_q4_k_nr2(
                enc, registry, device, input, planes, ids, output, params,
            ),
            (GgmlType::Q4_K, true) => native::quantized_matmul_id_ggml_prepared_mv_q4_k_nr2_masked(
                enc, registry, device, input, planes, ids, output, params,
            ),
            (_, false) => native::quantized_matmul_id_ggml_prepared_mv_with_policy(
                enc, registry, device, input, planes, ids, output, params, &routing,
            ),
            (_, true) => native::quantized_matmul_id_ggml_prepared_mv_masked_with_policy(
                enc, registry, device, input, planes, ids, output, params, &routing,
            ),
        };
        return dispatched.map_err(|e| anyhow!("{tag} prepared mul_mv_id: {e}"));
    }
    let ExpertRoleRef::Ggml(weight) = weight else {
        bail!("{tag}: forced expert matvec does not support affine storage");
    };
    crate::quantize::imatrix::intercept_qmatmul_id_with_hint(
        crate::quantize::imatrix::ImatrixHint::Layered { tag, layer },
        params.n_tokens as usize,
        params.top_k as usize,
        params.k as usize,
        || {
            if let Err(e) = enc.commit_wait_and_rotate() {
                eprintln!(
                    "[hf2q imatrix moe intercept ({tag})] commit_wait_and_rotate failed: {e}"
                );
                return None;
            }
            input.as_slice::<f32>().ok().map(|sl| sl.to_vec())
        },
        || ids.as_slice::<u32>().ok().map(|sl| sl.to_vec()),
    )
    .map_err(|e| anyhow!("imatrix moe intercept ({tag}): {e}"))?;
    let dispatched = match (params.ggml_type, masked) {
        (GgmlType::Q4_K, false) => quantized_matmul_id_ggml_mv_q4_k_nr2(
            enc, registry, device, input, weight, ids, output, params,
        ),
        (GgmlType::Q4_K, true) => quantized_matmul_id_ggml_mv_q4_k_nr2_masked(
            enc, registry, device, input, weight, ids, output, params,
        ),
        (_, false) => {
            quantized_matmul_id_ggml_mv(enc, registry, device, input, weight, ids, output, params)
        }
        (_, true) => quantized_matmul_id_ggml_mv_masked(
            enc, registry, device, input, weight, ids, output, params,
        ),
    };
    dispatched.map_err(|e| anyhow!("{tag} mul_mv_id: {e}"))
}

/// Routing produced by one batched layer: `[rows * top_k]` expert ids and
/// renormalized weights, row-major. Pooled; valid until the next decode-pool
/// reset. Production callers drop it; the batched-vs-serial tests read the
/// routing back.
#[cfg_attr(not(test), allow(dead_code))]
pub(crate) struct MoeBatchedRouting {
    pub ids: MlxBuffer,
    pub weights: MlxBuffer,
}

#[derive(Clone, Copy)]
pub(crate) struct DFlash2MoeRouteMask<'a> {
    pub verify_rows: &'a MlxBuffer,
    pub params: DFlash2MoeRouteMaskParams,
}

pub(super) fn pooled(device: &MlxDevice, elements: usize, dtype: DType, shape: Vec<usize>, label: &str) -> Result<MlxBuffer> {
    pooled_alloc_buffer(device, elements * dtype.size_of(), dtype, shape)
        .map_err(|e| anyhow!("allocate batched MoE {label}: {e}"))
}

/// Encode one MoE FFN layer over `rows` packed decode rows into `out`
/// (`[rows, hidden]`), adding `residual` (`[rows, hidden]`) when given.
/// `x` is `[rows, hidden]` F32. Scratch comes from the decode pool. Does not
/// commit.
#[allow(clippy::too_many_arguments)]
pub(crate) fn build_moe_ffn_layer_gpu_batched_into(
    enc: &mut CommandEncoder,
    device: &MlxDevice,
    registry: &mut KernelRegistry,
    x: &MlxBuffer,
    weights: &MoeFfnWeightsGpuQ,
    shape: MoeFfnShape,
    residual: Option<&MlxBuffer>,
    out: &mut MlxBuffer,
    rows: u32,
    layer_idx: usize,
    route_mask: Option<DFlash2MoeRouteMask<'_>>,
) -> Result<MoeBatchedRouting> {
    build_moe_ffn_layer_gpu_batched_route_into(
        enc,
        device,
        registry,
        x,
        weights,
        shape,
        residual,
        out,
        rows,
        layer_idx,
        route_mask,
        qwen_moe_expert_route()?,
    )
}

/// [`build_moe_ffn_layer_gpu_batched_into`] on an explicit expert route.
#[allow(clippy::too_many_arguments)]
pub(crate) fn build_moe_ffn_layer_gpu_batched_route_into(
    enc: &mut CommandEncoder,
    device: &MlxDevice,
    registry: &mut KernelRegistry,
    x: &MlxBuffer,
    weights: &MoeFfnWeightsGpuQ,
    shape: MoeFfnShape,
    residual: Option<&MlxBuffer>,
    out: &mut MlxBuffer,
    rows: u32,
    layer_idx: usize,
    route_mask: Option<DFlash2MoeRouteMask<'_>>,
    route: MoeExpertRoute,
) -> Result<MoeBatchedRouting> {
    ensure!(
        (1..=MOE_BATCHED_MAX_ROWS).contains(&(rows as usize)),
        "batched MoE layer {layer_idx} accepts 1..={MOE_BATCHED_MAX_ROWS} rows, got {rows}"
    );
    ensure!(
        weights.dense_storage.is_native(),
        "batched MoE layer {layer_idx} requires native router/shared-expert storage"
    );
    ensure!(
        !weights.experts.has_affine(),
        "batched MoE layer {layer_idx} does not support DWQ affine expert overlays"
    );
    if route == MoeExpertRoute::LiveTiles {
        return super::moe_live_tiles_fused::build_moe_ffn_layer_live_tiles_into(
            enc, device, registry, x, weights, shape, residual, out, rows, layer_idx, route_mask,
        );
    }
    let staged_m8 = route == MoeExpertRoute::StagedM8;
    if staged_m8 {
        ensure!(
            matches!(shape.num_experts_per_tok, 1 | 6 | 8)
                && shape.hidden_size % 64 == 0
                && shape.moe_intermediate_size % 64 == 0
                && matches!(weights.ggml_type_gate_up, GgmlType::Q4_K | GgmlType::Q6_K)
                && matches!(weights.ggml_type_down, GgmlType::Q4_K | GgmlType::Q6_K)
                && !crate::quantize::imatrix::is_active(),
            "{QWEN_MOE_STAGED_M8_ENV}=1 requires top-k 1/6/8, \
             64-column-aligned Q4_K/Q6_K native expert stacks and no imatrix collector"
        );
    }
    let prepared_m8 = if staged_m8 {
        Some(
            weights.experts.completed()
                .context("staged M8 route requires canonical completed expert planes")?,
        )
    } else {
        None
    };
    let r = rows as usize;
    let h = shape.hidden_size as usize;
    let top_k = shape.num_experts_per_tok as usize;
    let m_moe = shape.moe_intermediate_size as usize;
    let m_sh = shape.shared_intermediate_size as usize;
    let ne = shape.num_experts;
    ensure!(
        x.element_count() >= r * h,
        "batched MoE layer {layer_idx}: input has {} values, need {rows} x {h}",
        x.element_count()
    );
    let pairs = r * top_k;

    let logits = pooled(
        device,
        r * ne as usize,
        DType::F32,
        vec![r, ne as usize],
        "router logits",
    )?;
    let sh_logit = pooled(device, r, DType::F32, vec![r, 1], "shared gate logit")?;
    let a_s = pooled(device, r * m_sh, DType::F32, vec![r, m_sh], "shared gate")?;
    let b_s = pooled(device, r * m_sh, DType::F32, vec![r, m_sh], "shared up")?;
    let h_s = pooled(device, r * m_sh, DType::F32, vec![r, m_sh], "shared swiglu")?;
    let y_s = pooled(device, r * h, DType::F32, vec![r, h], "shared down")?;
    let ids = pooled(device, pairs, DType::U32, vec![pairs], "expert ids")?;
    let routing_weights = pooled(device, pairs, DType::F32, vec![pairs], "routing weights")?;
    let gate_all = pooled(
        device,
        pairs * m_moe,
        DType::F32,
        vec![pairs, m_moe],
        "expert gate",
    )?;
    let up_all = pooled(
        device,
        pairs * m_moe,
        DType::F32,
        vec![pairs, m_moe],
        "expert up",
    )?;
    let h_all = pooled(
        device,
        pairs * m_moe,
        DType::F32,
        vec![pairs, m_moe],
        "expert swiglu",
    )?;
    let y_all = pooled(device, pairs * h, DType::F32, vec![pairs, h], "expert down")?;
    let gathered_m8 = staged_m8
        .then(|| {
            let width = h.max(m_moe);
            // The route list and the rows its last eight-row tile reads past it.
            let gathered_rows =
                mlx_native::grouped_m8_gathered_rows(rows, shape.num_experts_per_tok, ne)
                    .map_err(|e| anyhow!("staged M8 gathered rows: {e}"))?;
            pooled(
                device,
                gathered_rows * width,
                DType::BF16,
                vec![gathered_rows, width],
                "staged M8 gathered input",
            )
        })
        .transpose()?;
    let mut silu_sh_params = pooled(device, 1, DType::U32, vec![1], "shared swiglu params")?;
    let mut silu_params = pooled(device, 1, DType::U32, vec![1], "expert swiglu params")?;
    let n_h_s = (r * m_sh) as u32;
    let n_h_all = (pairs * m_moe) as u32;
    silu_sh_params
        .as_mut_slice::<u32>()
        .map_err(|e| anyhow!("batched MoE shared swiglu params: {e}"))?[0] = n_h_s;
    silu_params
        .as_mut_slice::<u32>()
        .map_err(|e| anyhow!("batched MoE expert swiglu params: {e}"))?[0] = n_h_all;
    let dummy_residual;
    let residual_ref = match residual {
        Some(buffer) => buffer,
        None => {
            dummy_residual = pooled(device, 1, DType::F32, vec![1], "dummy residual")?;
            &dummy_residual
        }
    };

    let h32 = shape.hidden_size;
    let m_sh32 = shape.shared_intermediate_size;
    // ---- A: router, shared gate logit, shared gate/up (all read x) ----
    for (role, output, out_features) in [
        (MoeDenseRole::Router, &logits, ne),
        (MoeDenseRole::SharedGateLogit, &sh_logit, 1),
        (MoeDenseRole::SharedGate, &a_s, m_sh32),
        (MoeDenseRole::SharedUp, &b_s, m_sh32),
    ] {
        encode_native_dense_proj(
            enc,
            registry,
            device,
            x,
            weights,
            role,
            output,
            rows,
            h32,
            out_features,
        )
        .with_context(|| format!("batched MoE layer {layer_idx}"))?;
    }
    enc.memory_barrier();

    // ---- B: routing over every row, shared SwiGLU ----
    dispatch_moe_softmax_topk_simd(
        enc,
        registry,
        device,
        &logits,
        &ids,
        &routing_weights,
        rows,
        ne,
        shape.num_experts_per_tok,
    )
    .map_err(|e| anyhow!("batched MoE layer {layer_idx} top-k: {e}"))?;
    // The route mask reads and rewrites the top-k outputs. Without this
    // explicit RAW barrier, its dispatch can race the selector and expose
    // partially written expert IDs or weights to the masked expert kernels.
    // The failure is scheduling-dependent and corrupts otherwise-live rows,
    // so it appears as intermittent greedy token and tool-argument drift.
    if route_mask.is_some() {
        enc.memory_barrier();
    }
    if let Some(mask) = route_mask {
        dispatch_dflash2_mask_moe_routes(
            enc,
            registry,
            device,
            mask.verify_rows,
            &ids,
            &routing_weights,
            mask.params,
        )
        .map_err(|e| anyhow!("batched MoE layer {layer_idx} DFlash2 route mask: {e}"))?;
    }
    dispatch_silu_mul(
        enc,
        registry,
        device.metal_device(),
        &a_s,
        &b_s,
        &h_s,
        &silu_sh_params,
        n_h_s,
    )
    .map_err(|e| anyhow!("batched MoE layer {layer_idx} shared swiglu: {e}"))?;
    enc.memory_barrier();

    // ---- C: expert gate/up over rows * top_k pairs (row t feeds pairs
    // t * top_k ..), shared down ----
    let gate_params = GgmlQuantizedMatmulIdParams {
        n_tokens: rows,
        top_k: shape.num_experts_per_tok,
        n: shape.moe_intermediate_size,
        k: h32,
        n_experts: ne,
        expert_stride: weights.expert_gate_stride,
        ggml_type: weights.ggml_type_gate_up,
    };
    let up_params = GgmlQuantizedMatmulIdParams {
        expert_stride: weights.expert_up_stride,
        ..gate_params
    };
    // The route mask rewrote unselected rows' ids to `num_experts`. The
    // masked projection keeps them out of the compact schedule; the plain one
    // would treat them as invalid metadata and skip every row's expert work.
    let staged_projection = if route_mask.is_some() {
        quantized_matmul_id_ggml_grouped_m8_epilogue_masked
    } else {
        quantized_matmul_id_ggml_grouped_m8_epilogue
    };
    if staged_m8 {
        super::decode_pool::with_id_mm_scratch(
            super::decode_pool::MmIdSlot::Gate,
            device,
            ne,
            rows * shape.num_experts_per_tok,
            |scratch| {
                let prepared = prepared_m8.expect("validated prepared M8");
                staged_projection(
                    enc,
                    registry,
                    device,
                    x,
                    gathered_m8.as_ref().expect("allocated staged M8 input"),
                    &prepared.gate,
                    &ids,
                    &gate_all,
                    None,
                    scratch,
                    &gate_params,
                    false,
                    false,
                    false,
                    GroupedM8Input::F32,
                    GroupedM8Epilogue::F32,
                )?;
                staged_projection(
                    enc,
                    registry,
                    device,
                    x,
                    gathered_m8.as_ref().expect("allocated staged M8 input"),
                    &prepared.up,
                    &ids,
                    &up_all,
                    None,
                    scratch,
                    &up_params,
                    false,
                    true,
                    true,
                    GroupedM8Input::F32,
                    GroupedM8Epilogue::F32,
                )
            },
        )
        .map_err(|e| anyhow!("batched MoE layer {layer_idx} staged M8 gate/up: {e}"))?;
    } else {
        dispatch_expert_mv(
            enc,
            registry,
            device,
            x,
            weights.experts.role(ExpertRole::Gate),
            &ids,
            &gate_all,
            &gate_params,
            "ffn_gate_exps",
            layer_idx,
            route_mask.is_some(),
        )?;
        dispatch_expert_mv(
            enc,
            registry,
            device,
            x,
            weights.experts.role(ExpertRole::Up),
            &ids,
            &up_all,
            &up_params,
            "ffn_up_exps",
            layer_idx,
            route_mask.is_some(),
        )?;
    }
    encode_native_dense_proj(
        enc,
        registry,
        device,
        &h_s,
        weights,
        MoeDenseRole::SharedDown,
        &y_s,
        rows,
        m_sh32,
        h32,
    )
    .with_context(|| format!("batched MoE layer {layer_idx}"))?;
    enc.memory_barrier();

    // ---- D: expert SwiGLU in the established F32 activation domain ----
    dispatch_silu_mul(
        enc,
        registry,
        device.metal_device(),
        &gate_all,
        &up_all,
        &h_all,
        &silu_params,
        n_h_all,
    )
    .map_err(|e| anyhow!("batched MoE layer {layer_idx} expert swiglu: {e}"))?;
    enc.memory_barrier();

    // ---- E: expert down, one pair per input row ----
    let down_params = GgmlQuantizedMatmulIdParams {
        n_tokens: pairs as u32,
        top_k: 1,
        n: h32,
        k: shape.moe_intermediate_size,
        n_experts: ne,
        expert_stride: weights.expert_down_stride,
        ggml_type: weights.ggml_type_down,
    };
    if staged_m8 {
        let slotted_down_params = GgmlQuantizedMatmulIdParams {
            n_tokens: rows,
            top_k: shape.num_experts_per_tok,
            ..down_params
        };
        super::decode_pool::with_id_mm_scratch(
            super::decode_pool::MmIdSlot::Gate,
            device,
            ne,
            rows * shape.num_experts_per_tok,
            |scratch| {
                staged_projection(
                    enc,
                    registry,
                    device,
                    &h_all,
                    gathered_m8.as_ref().expect("allocated staged M8 input"),
                    &prepared_m8.expect("validated prepared M8").down,
                    &ids,
                    &y_all,
                    None,
                    scratch,
                    &slotted_down_params,
                    true,
                    true,
                    false,
                    GroupedM8Input::F32,
                    GroupedM8Epilogue::F32,
                )
            },
        )
        .map_err(|e| anyhow!("batched MoE layer {layer_idx} staged M8 down: {e}"))?;
    } else {
        dispatch_expert_mv(
            enc,
            registry,
            device,
            &h_all,
            weights.experts.role(ExpertRole::Down),
            &ids,
            &y_all,
            &down_params,
            "ffn_down_exps",
            layer_idx,
            route_mask.is_some(),
        )?;
    }
    enc.memory_barrier();

    // ---- F: weighted reduce + sigmoid(shared gate) * shared + residual ----
    // A masked staged projection leaves masked routes' rows unwritten.
    let weighted_reduce = if staged_m8 && route_mask.is_some() {
        dispatch_moe_weighted_reduce_masked
    } else {
        dispatch_moe_weighted_reduce
    };
    weighted_reduce(
        enc,
        registry,
        device,
        &routing_weights,
        &y_all,
        &sh_logit,
        &y_s,
        residual_ref,
        out,
        rows,
        shape.num_experts_per_tok,
        h32,
        residual.is_some(),
    )
    .map_err(|e| anyhow!("batched MoE layer {layer_idx} weighted reduce: {e}"))?;

    #[cfg(test)]
    retain_routing_for_tests(&logits, &ids, &routing_weights, r, ne as usize, top_k)?;

    Ok(MoeBatchedRouting {
        ids,
        weights: routing_weights,
    })
}

/// Retain a layer's routing for the ADR-063 invariance captures.
#[cfg(test)]
pub(super) fn retain_routing_for_tests(
    logits: &MlxBuffer,
    ids: &MlxBuffer,
    routing_weights: &MlxBuffer,
    rows: usize,
    experts: usize,
    top_k: usize,
) -> Result<()> {
    use crate::adr063_invariance::qwen::retain_current;
    retain_current("moe_router_logits", logits, vec![rows, experts]).map_err(anyhow::Error::msg)?;
    retain_current("moe_router_ids", ids, vec![rows, top_k]).map_err(anyhow::Error::msg)?;
    retain_current("moe_router_weights", routing_weights, vec![rows, top_k])
        .map_err(anyhow::Error::msg)
}