hf2q 0.1.33

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
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
//! Model-free Metal gates for the live-tile MoE layer
//! (`HF2Q_QWEN_MOE_LIVE_TILES=1`, [`super::moe_live_tiles`]) at the
//! Qwen3.6-35B-A3B layer shape, on the random layers of
//! [`super::moe_batched_tests`].
//!
//! * row independence: every row of a width-8, -16, -24 or -32 step, in any
//!   order, beside any other rows and under a DFlash2 verify-row mask, is
//!   bitwise the row this route computes alone, including its expert ids and
//!   routing weights;
//! * masked rows: a row the mask removed is never read (its input is NaN)
//!   and the live rows keep their bits;
//! * determinism: two encodings of one step agree bitwise;
//! * the fused expert stages ([`super::moe_live_tiles_fused`]) against the
//!   stage-by-stage form ([`super::moe_live_tiles`]): every output element,
//!   expert id and routing weight of whole layers bitwise equal, masked and
//!   unmasked, at widths 1 to 32, with experts of more than eight routes;
//! * the fallback: a layer the fused stages refuse (routed and shared down
//!   in different formats) runs the stage-by-stage form through the route's
//!   entry point, bitwise and with that form's dispatches;
//! * F64 reference of the whole layer with a K-scaled bound: BF16 expert
//!   inputs and SwiGLU, half expert weights, FP32 sums, for the routed
//!   experts and the shared expert.
//!
//! Run: `cargo test --release --bin hf2q moe_live_tiles_tests -- --test-threads=1 --nocapture`

use mlx_native::ops::dflash2_attention_pack::DFlash2MoeRouteMaskParams;
use mlx_native::ops::quantized_matmul_ggml::GgmlType;
use mlx_native::{DType, KernelRegistry, MlxBuffer, MlxDevice};

use super::decode_pool;
use super::gpu_ffn::MoeFfnWeightsGpuQ;
use super::moe_batched::{
    build_moe_ffn_layer_gpu_batched_route_into, DFlash2MoeRouteMask, MoeDenseStorage,
    MoeExpertRoute,
};
use super::moe_batched_tests::{
    bits, dequant_rows, packed, router_logits_f64, rows, shape, silu, top_k_f64, Layer, RowResult,
    H, MI, MSH, NE, TOP_K,
};

const LANE_ROWS: usize = 8;

/// Native-storage weights of `layer` with the live-tile planes prepared.
fn live_tile_weights(
    device: &MlxDevice,
    registry: &mut KernelRegistry,
    layer: &Layer,
) -> MoeFfnWeightsGpuQ {
    let weights = layer.gpu(device, true, &layer.gpu_experts(device));
    prepare_live_tile_planes(device, registry, weights)
}

/// Prepare the expert planes and the shared expert's planes of `weights`.
fn prepare_live_tile_planes(
    device: &MlxDevice,
    registry: &mut KernelRegistry,
    weights: MoeFfnWeightsGpuQ,
) -> MoeFfnWeightsGpuQ {
    let mut weights = super::gpu_expert_test_support::complete_experts(weights, shape(), device, registry);
    let mut enc = device.command_encoder().expect("prepare encoder");
    // The process switch is unset in tests: prepare the live-tile state directly.
    let live_tiles = weights
        .prepare_live_tiles(&mut enc, registry, device, H as u32, MSH as u32)
        .expect("prepare shared expert planes");
    enc.commit_and_wait_labeled("test.qwen.moe_live_tiles.prepare")
        .expect("commit preparation");
    weights.live_tiles = Some(live_tiles);
    weights
}

/// One live-tile layer over the rows `select` (in that order). `verify_rows`
/// masks each lane of eight rows to its first `verify_rows[lane]` rows.
fn run_live_tiles(
    device: &MlxDevice,
    registry: &mut KernelRegistry,
    weights: &MoeFfnWeightsGpuQ,
    x: &[Vec<f32>],
    residual: &[Vec<f32>],
    select: &[usize],
    verify_rows: Option<&[u32]>,
) -> Vec<RowResult> {
    run_route(
        device,
        registry,
        weights,
        x,
        residual,
        select,
        verify_rows,
        MoeExpertRoute::LiveTiles,
    )
}

/// [`run_live_tiles`] on an explicit expert route.
#[allow(clippy::too_many_arguments)]
fn run_route(
    device: &MlxDevice,
    registry: &mut KernelRegistry,
    weights: &MoeFfnWeightsGpuQ,
    x: &[Vec<f32>],
    residual: &[Vec<f32>],
    select: &[usize],
    verify_rows: Option<&[u32]>,
    route: MoeExpertRoute,
) -> Vec<RowResult> {
    run_layer(
        device,
        registry,
        weights,
        x,
        residual,
        select,
        verify_rows,
        Some(route),
    )
}

/// One layer over the rows `select` on `route`, or on the live-tile route's
/// stage-by-stage form when `route` is `None`.
#[allow(clippy::too_many_arguments)]
fn run_layer(
    device: &MlxDevice,
    registry: &mut KernelRegistry,
    weights: &MoeFfnWeightsGpuQ,
    x: &[Vec<f32>],
    residual: &[Vec<f32>],
    select: &[usize],
    verify_rows: Option<&[u32]>,
    route: Option<MoeExpertRoute>,
) -> Vec<RowResult> {
    decode_pool::checked_reset_decode_pool().expect("reset decode pool");
    let r = select.len();
    let xin = packed(x, select, device);
    let res = packed(residual, select, device);
    let mut out = device
        .alloc_buffer(r * H * 4, DType::F32, vec![r, H])
        .expect("alloc out");
    let verify_buffer: Option<MlxBuffer> = verify_rows.map(|rows| {
        let mut buffer = device
            .alloc_buffer(rows.len() * 4, DType::U32, vec![rows.len()])
            .expect("verify rows");
        buffer
            .as_mut_slice::<u32>()
            .expect("verify slice")
            .copy_from_slice(rows);
        buffer
    });
    let route_mask = verify_buffer
        .as_ref()
        .map(|verify_rows| DFlash2MoeRouteMask {
            verify_rows,
            params: DFlash2MoeRouteMaskParams {
                physical_lane: [0, 1, 2, 3],
                lanes: (r / LANE_ROWS) as u32,
                rows_per_lane: LANE_ROWS as u32,
                top_k: TOP_K as u32,
                n_experts: NE as u32,
                width: r as u32,
            },
        });
    let mut enc = device.command_encoder().expect("encoder");
    let routing = match route {
        Some(route) => build_moe_ffn_layer_gpu_batched_route_into(
            &mut enc,
            device,
            registry,
            &xin,
            weights,
            shape(),
            Some(&res),
            &mut out,
            r as u32,
            0,
            route_mask,
            route,
        ),
        None => super::moe_live_tiles::build_moe_ffn_layer_tile_stages_into(
            &mut enc,
            device,
            registry,
            &xin,
            weights,
            shape(),
            Some(&res),
            &mut out,
            r as u32,
            0,
            route_mask,
        ),
    }
    .expect("batched MoE layer");
    enc.commit_and_wait_labeled("test.qwen.moe_live_tiles")
        .expect("commit");
    let out = out.as_slice::<f32>().expect("read out");
    let ids = routing.ids.as_slice::<u32>().expect("read ids");
    let w = routing.weights.as_slice::<f32>().expect("read weights");
    (0..r)
        .map(|i| RowResult {
            out: out[i * H..(i + 1) * H].to_vec(),
            ids: ids[i * TOP_K..(i + 1) * TOP_K].to_vec(),
            weights: w[i * TOP_K..(i + 1) * TOP_K].to_vec(),
        })
        .collect()
}

/// A fully live width-32 staged-M8 step: its gathered rows are exactly a
/// 2 MiB pool bucket without the rows the last eight-row tile reads past the
/// route list, which mlx-native now requires.
#[test]
fn staged_m8_full_width_step_reserves_the_tile_slack() {
    const ROWS: usize = 32;
    let _gpu = crate::inference::hf2q_gpu_test_lock();
    let device = MlxDevice::new().expect("device");
    let mut registry = KernelRegistry::new();
    let layer = Layer::random(GgmlType::Q4_K, 0x51ac);
    let weights = live_tile_weights(&device, &mut registry, &layer);
    let (x, residual) = rows(ROWS, 0x51ac ^ 0x5eed);
    let all: Vec<usize> = (0..ROWS).collect();
    let mut run = || {
        run_route(
            &device,
            &mut registry,
            &weights,
            &x,
            &residual,
            &all,
            None,
            MoeExpertRoute::StagedM8,
        )
    };
    let first = run();
    let again = run();
    for (row, (first, again)) in first.iter().zip(&again).enumerate() {
        assert!(
            first.out.iter().all(|v| v.is_finite()),
            "row {row} is not finite"
        );
        assert_eq!(
            bits(&first.out),
            bits(&again.out),
            "row {row} is not repeatable"
        );
    }
}

/// The live-tile route (fused expert stages, router blocks in one dispatch)
/// against its stage-by-stage form: whole layers, every element.
fn fused_stages_equal_tile_stages(down_t: GgmlType, seed: u64) {
    const ROWS: usize = 32;
    let _gpu = crate::inference::hf2q_gpu_test_lock();
    let device = MlxDevice::new().expect("device");
    let mut registry = KernelRegistry::new();
    let layer = Layer::random(down_t, seed);
    let weights = live_tile_weights(&device, &mut registry, &layer);
    let (x, residual) = rows(ROWS, seed ^ 0xf05e);
    let all: Vec<usize> = (0..ROWS).collect();
    // (rows of the step, verify rows per lane of eight).
    let mut steps: Vec<(Vec<usize>, Option<Vec<u32>>)> = vec![
        (all.clone(), None),
        (all.iter().rev().copied().collect(), None),
        ((0..24).collect(), None),
        ((8..24).collect(), None),
        ((24..32).collect(), None),
        ((0..17).collect(), None),
        (vec![6, 4, 6], None),
        (vec![9], None),
        // Experts of more than eight routes: one row in every place (its
        // eight experts hold 32 routes each), and three rows in turn.
        (vec![5; ROWS], None),
        ((0..ROWS).map(|row| row % 3).collect(), None),
    ];
    for verify_rows in [[5u32, 8, 1, 3], [8, 8, 8, 8], [1, 1, 1, 1], [2, 7, 4, 6]] {
        steps.push((all.clone(), Some(verify_rows.to_vec())));
    }
    steps.push(((8..24).collect(), Some(vec![3, 8])));
    steps.push(((24..32).collect(), Some(vec![4])));
    steps.push((
        (0..ROWS).map(|row| row % 3).collect(),
        Some(vec![8, 5, 8, 2]),
    ));
    let mut wide_experts = 0usize;
    for (select, verify_rows) in &steps {
        let label = format!("{down_t:?} rows {select:?} mask {verify_rows:?}");
        let mut run = |route| {
            run_layer(
                &device,
                &mut registry,
                &weights,
                &x,
                &residual,
                select,
                verify_rows.as_deref(),
                route,
            )
        };
        let stages = run(None);
        let fused = run(Some(MoeExpertRoute::LiveTiles));
        assert!(
            stages
                .iter()
                .all(|row| row.out.iter().all(|value| value.is_finite())),
            "{label}: non-finite output"
        );
        for (place, (fused, stages)) in fused.iter().zip(&stages).enumerate() {
            assert_row(fused, stages, &format!("{label}: place {place}"));
        }
        let mut counts = vec![0usize; NE];
        for id in stages.iter().flat_map(|row| &row.ids) {
            if (*id as usize) < NE {
                counts[*id as usize] += 1;
            }
        }
        wide_experts += counts.iter().filter(|count| **count > LANE_ROWS).count();
    }
    assert!(
        wide_experts > 0,
        "no step held an expert of more than eight routes"
    );
    eprintln!(
        "moe_live_tiles {down_t:?}: {} whole layers bitwise equal to the stage-by-stage form \
         ({wide_experts} experts of more than eight routes)",
        steps.len()
    );
}

#[test]
fn live_tile_route_equals_its_stage_form_bitwise_down_q6_k() {
    fused_stages_equal_tile_stages(GgmlType::Q6_K, 0x0f5e_d001);
}

#[test]
fn live_tile_route_equals_its_stage_form_bitwise_down_q4_k() {
    fused_stages_equal_tile_stages(GgmlType::Q4_K, 0x0f5e_d002);
}

/// `run` with the dispatches and barriers it encoded.
fn counted<T>(run: impl FnOnce() -> T) -> (T, u64, u64) {
    let (dispatches, barriers) = (mlx_native::dispatch_count(), mlx_native::barrier_count());
    let result = run();
    (
        result,
        mlx_native::dispatch_count() - dispatches,
        mlx_native::barrier_count() - barriers,
    )
}

/// A layer the fused stages refuse (routed down Q6_K beside a shared down
/// Q4_K) through the route's entry point: the stage-by-stage form, bitwise,
/// with that form's dispatches; and the load-time count sees it.
#[test]
fn live_tile_route_runs_a_refused_layer_stage_by_stage() {
    const ROWS: usize = 32;
    let _gpu = crate::inference::hf2q_gpu_test_lock();
    let device = MlxDevice::new().expect("device");
    let mut registry = KernelRegistry::new();
    let routed = Layer::random(GgmlType::Q6_K, 0x0fa1_1b06);
    let other = Layer::random(GgmlType::Q4_K, 0x0fa1_1b04);
    let mixed = Layer {
        shared_down: other.shared_down,
        ..routed
    };
    let mut weights = mixed.gpu(&device, true, &mixed.gpu_experts(&device));
    weights.dense_storage = MoeDenseStorage::Native {
        shared_gate_up: GgmlType::Q4_K,
        shared_down: GgmlType::Q4_K,
    };
    let weights = prepare_live_tile_planes(&device, &mut registry, weights);
    assert_eq!(
        super::moe_live_tiles_fused::live_tile_layer_is_fused(&weights, shape()),
        Some(false),
        "the mixed-format layer was admitted to the fused stages"
    );
    let admitted = live_tile_weights(
        &device,
        &mut registry,
        &Layer::random(GgmlType::Q6_K, 0x0fa1_1b06),
    );
    assert_eq!(
        super::moe_live_tiles_fused::live_tile_layer_is_fused(&admitted, shape()),
        Some(true),
        "a one-format layer was refused by the fused stages"
    );
    let unprepared = mixed.gpu(&device, true, &mixed.gpu_experts(&device));
    assert_eq!(
        super::moe_live_tiles_fused::live_tile_layer_is_fused(&unprepared, shape()),
        None
    );

    let (x, residual) = rows(ROWS, 0x0fa1_1bff);
    let all: Vec<usize> = (0..ROWS).collect();
    let steps: Vec<(Vec<usize>, Option<Vec<u32>>)> = vec![
        (all.clone(), None),
        (all.clone(), Some(vec![5, 8, 1, 3])),
        (all.clone(), Some(vec![0, 0, 0, 0])),
        ((0..8).collect(), None),
        ((8..24).collect(), Some(vec![3, 8])),
        ((0..17).collect(), None),
        (vec![9], None),
        // Experts of more than eight routes.
        ((0..ROWS).map(|row| row % 3).collect(), None),
    ];
    for (select, verify_rows) in &steps {
        let label = format!("mixed formats, rows {select:?} mask {verify_rows:?}");
        let (entry, entry_dispatches, entry_barriers) = counted(|| {
            run_layer(
                &device,
                &mut registry,
                &weights,
                &x,
                &residual,
                select,
                verify_rows.as_deref(),
                Some(MoeExpertRoute::LiveTiles),
            )
        });
        let (stages, stage_dispatches, stage_barriers) = counted(|| {
            run_layer(
                &device,
                &mut registry,
                &weights,
                &x,
                &residual,
                select,
                verify_rows.as_deref(),
                None,
            )
        });
        assert_eq!(
            (entry_dispatches, entry_barriers),
            (stage_dispatches, stage_barriers),
            "{label}: the entry point did not encode the stage-by-stage form"
        );
        for (place, (entry, stages)) in entry.iter().zip(&stages).enumerate() {
            let live = verify_rows.as_ref().map_or(true, |verify_rows| {
                place % LANE_ROWS < verify_rows[place / LANE_ROWS] as usize
            });
            assert!(
                !live || entry.out.iter().all(|value| value.is_finite()),
                "{label}: place {place} is not finite"
            );
            assert_row(entry, stages, &format!("{label}: place {place}"));
        }
    }

    // The same full-width steps on the admitted layer run the fused stages:
    // eight dispatches, where the refused layer encodes the stage form's.
    for verify_rows in [None, Some(vec![5u32, 8, 1, 3])] {
        let mut dispatches = |weights: &MoeFfnWeightsGpuQ| {
            counted(|| {
                run_layer(
                    &device,
                    &mut registry,
                    weights,
                    &x,
                    &residual,
                    &all,
                    verify_rows.as_deref(),
                    Some(MoeExpertRoute::LiveTiles),
                )
            })
            .1
        };
        let (fused, fallback) = (dispatches(&admitted), dispatches(&weights));
        assert_eq!(fused, 8, "mask {verify_rows:?}: fused dispatches");
        assert!(
            fallback > 2 * fused,
            "mask {verify_rows:?}: the refused layer encoded {fallback} dispatches"
        );
    }
    eprintln!(
        "moe_live_tiles: a refused layer runs the stage-by-stage form through the entry point, \
         {} steps bitwise",
        steps.len()
    );
}

fn assert_row(actual: &RowResult, expected: &RowResult, label: &str) {
    assert_eq!(actual.ids, expected.ids, "{label}: expert ids");
    assert_eq!(
        bits(&actual.weights),
        bits(&expected.weights),
        "{label}: routing weights"
    );
    assert_eq!(bits(&actual.out), bits(&expected.out), "{label}: output");
}

fn rows_are_independent(down_t: GgmlType, seed: u64) {
    const ROWS: usize = 32;
    let _gpu = crate::inference::hf2q_gpu_test_lock();
    let device = MlxDevice::new().expect("device");
    let mut registry = KernelRegistry::new();
    let layer = Layer::random(down_t, seed);
    let weights = live_tile_weights(&device, &mut registry, &layer);
    let (x, residual) = rows(ROWS, seed ^ 0x711e);

    let single: Vec<RowResult> = (0..ROWS)
        .map(|row| {
            run_live_tiles(
                &device,
                &mut registry,
                &weights,
                &x,
                &residual,
                &[row],
                None,
            )
            .remove(0)
        })
        .collect();
    assert!(
        single.iter().all(|r| r.out.iter().all(|v| v.is_finite())),
        "non-finite output"
    );

    // Determinism and every width, order and repeat.
    let all: Vec<usize> = (0..ROWS).collect();
    let mut steps: Vec<Vec<usize>> = vec![
        all.clone(),
        all.clone(),
        all.iter().rev().copied().collect(),
        (0..24).collect(),
        (8..24).collect(),
        (24..32).collect(),
        vec![3, 1, 0, 2],
        vec![6, 4, 6],
        (0..17).collect(),
    ];
    // Rows that share experts: the same row in every lane.
    steps.push((0..ROWS).map(|row| row % LANE_ROWS).collect());
    for select in &steps {
        let step = run_live_tiles(
            &device,
            &mut registry,
            &weights,
            &x,
            &residual,
            select,
            None,
        );
        for (place, &row) in select.iter().enumerate() {
            assert_row(
                &step[place],
                &single[row],
                &format!("{down_t:?} rows {select:?}: row {row}"),
            );
        }
    }

    // Verify-row masks: live rows keep their bits while the masked rows'
    // inputs are NaN, so no live result read a masked row.
    for verify_rows in [[5u32, 8, 1, 3], [8, 8, 8, 8], [1, 1, 1, 1], [2, 7, 4, 6]] {
        let live = |row: usize| (row % LANE_ROWS) < verify_rows[row / LANE_ROWS] as usize;
        let mut masked_x = x.clone();
        for row in (0..ROWS).filter(|row| !live(*row)) {
            masked_x[row].fill(f32::NAN);
        }
        let step = run_live_tiles(
            &device,
            &mut registry,
            &weights,
            &masked_x,
            &residual,
            &all,
            Some(&verify_rows),
        );
        for row in 0..ROWS {
            if live(row) {
                assert_row(
                    &step[row],
                    &single[row],
                    &format!("{down_t:?} mask {verify_rows:?}: row {row}"),
                );
            } else {
                assert!(
                    step[row].ids.iter().all(|&id| id == NE as u32)
                        && step[row].weights.iter().all(|&w| w == 0.0),
                    "{down_t:?} mask {verify_rows:?}: row {row} kept a route"
                );
            }
        }
    }
    eprintln!(
        "moe_live_tiles {down_t:?}: {} unmasked steps and 4 masked width-32 steps bitwise equal to rows = 1 \
         (register path {})",
        steps.len(),
        weights
            .live_tiles
            .as_ref()
            .expect("prepared")
            .column_tile
    );
}

#[test]
fn live_tile_rows_equal_single_row_route_bitwise_down_q6_k() {
    rows_are_independent(GgmlType::Q6_K, 0x711e_06);
}

#[test]
fn live_tile_rows_equal_single_row_route_bitwise_down_q4_k() {
    rows_are_independent(GgmlType::Q4_K, 0x711e_04);
}

/// Relative rounding error of BF16.
const BF16_ULP: f64 = 1.0 / 256.0;
/// A half below this magnitude is subnormal: its rounding error is absolute.
const HALF_MIN_NORMAL: f64 = 1.0 / 16384.0;
const F32_ULP: f64 = 1.0 / 16_777_216.0;

/// `(sum w x, sum |x| (|w| + HALF_MIN_NORMAL))` for each of `rows` rows of `w`.
fn dot_rows(w: &[f32], x: &[f64], rows: usize, cols: usize) -> (Vec<f64>, Vec<f64>) {
    (0..rows)
        .map(|row| {
            w[row * cols..(row + 1) * cols].iter().zip(x).fold(
                (0.0, 0.0),
                |(sum, abs), (&w, &x)| {
                    let w = f64::from(w);
                    (sum + w * x, abs + x.abs() * (w.abs() + HALF_MIN_NORMAL))
                },
            )
        })
        .unzip()
}

/// Worst-case relative error of a live-tile dot product of `k` terms: BF16
/// inputs when `rounded_input`, half weights, an FP32 sum of `k` products.
fn tile_epsilon(k: usize, rounded_input: bool) -> f64 {
    let input = if rounded_input { BF16_ULP } else { 0.0 };
    (1.0 + input) * (1.0 + 2.0f64.powi(-11) + 2.0 * F32_ULP) * (1.0 + (k as f64 + 2.0) * F32_ULP)
        - 1.0
}

/// One expert's F64 output for the row `x` and the worst-case error of its
/// live tiles: `(y, bound)` per output element.
fn expert_reference(
    gate_w: &[f32],
    up_w: &[f32],
    down_w: &[f32],
    x: &[f64],
    intermediate: usize,
) -> (Vec<f64>, Vec<f64>) {
    let epsilon = tile_epsilon(H, true);
    let (gate, gate_abs) = dot_rows(gate_w, x, intermediate, H);
    let (up, up_abs) = dot_rows(up_w, x, intermediate, H);
    let hidden: Vec<f64> = gate.iter().zip(&up).map(|(&g, &u)| silu(g) * u).collect();
    // |SiLU'| <= 1.1; the FP32 SwiGLU rounds to BF16 once.
    let hidden_bound: Vec<f64> = (0..intermediate)
        .map(|j| {
            let (gate_bound, up_bound) = (epsilon * gate_abs[j], epsilon * up_abs[j]);
            let exact =
                1.1 * gate_bound * (up[j].abs() + up_bound) + silu(gate[j]).abs() * up_bound;
            exact + (BF16_ULP + 2.0f64.powi(-16)) * (hidden[j].abs() + exact)
        })
        .collect();
    let epsilon = tile_epsilon(intermediate, false);
    (0..H)
        .map(|i| {
            let w = &down_w[i * intermediate..(i + 1) * intermediate];
            let (mut y, mut bound) = (0.0f64, 0.0f64);
            for j in 0..intermediate {
                let w = f64::from(w[j]);
                y += w * hidden[j];
                bound += w.abs() * hidden_bound[j]
                    + epsilon * (w.abs() + HALF_MIN_NORMAL) * (hidden[j].abs() + hidden_bound[j]);
            }
            (y, bound)
        })
        .unzip()
}

fn matches_f64_reference(down_t: GgmlType, seed: u64) {
    const ROWS: usize = 32;
    let _gpu = crate::inference::hf2q_gpu_test_lock();
    let device = MlxDevice::new().expect("device");
    let mut registry = KernelRegistry::new();
    let layer = Layer::random(down_t, seed);
    let weights = live_tile_weights(&device, &mut registry, &layer);
    let (x, residual) = rows(ROWS, seed ^ 0xf64);
    let all: Vec<usize> = (0..ROWS).collect();
    let gpu = run_live_tiles(&device, &mut registry, &weights, &x, &residual, &all, None);
    let shared = (
        dequant_rows(&layer.shared_gate, GgmlType::Q4_K, 0, MSH, H),
        dequant_rows(&layer.shared_up, GgmlType::Q4_K, 0, MSH, H),
        dequant_rows(&layer.shared_down, down_t, 0, H, MSH),
    );
    // FP32 stages (routing weights, shared gate, reduce): the batched
    // route's envelope per unit of accumulated magnitude.
    let dense = 8.0 * (H + MSH) as f64 * F32_ULP;
    let (mut worst, mut squared_error, mut squared_norm) = (0.0f64, 0.0f64, 0.0f64);
    for row in 0..ROWS {
        let xf: Vec<f64> = x[row].iter().map(|&v| f64::from(v)).collect();
        let (ids, route_weights, _) = top_k_f64(&router_logits_f64(&layer.router, &x[row]));
        let gpu_ids: Vec<usize> = gpu[row].ids.iter().map(|&id| id as usize).collect();
        assert_eq!(
            gpu_ids, ids,
            "{down_t:?} row {row}: expert ids differ from F64"
        );
        let mut out: Vec<f64> = residual[row].iter().map(|&v| f64::from(v)).collect();
        let mut bound: Vec<f64> = out.iter().map(|v| dense * v.abs()).collect();
        let mut add = |weight: f64, (y, y_bound): (Vec<f64>, Vec<f64>)| {
            for i in 0..H {
                out[i] += weight * y[i];
                bound[i] += weight * (y_bound[i] + dense * (y[i].abs() + y_bound[i]));
            }
        };
        for (&expert, &weight) in ids.iter().zip(&route_weights) {
            let gate_w = dequant_rows(&layer.gate_exps, GgmlType::Q4_K, expert * MI, MI, H);
            let up_w = dequant_rows(&layer.up_exps, GgmlType::Q4_K, expert * MI, MI, H);
            let down_w = dequant_rows(&layer.down_exps, down_t, expert * H, H, MI);
            add(weight, expert_reference(&gate_w, &up_w, &down_w, &xf, MI));
        }
        let logit: f64 = layer
            .gate_inp
            .iter()
            .zip(&xf)
            .map(|(&w, &v)| f64::from(w) * v)
            .sum();
        add(
            1.0 / (1.0 + (-logit).exp()),
            expert_reference(&shared.0, &shared.1, &shared.2, &xf, MSH),
        );
        for i in 0..H {
            let error = (f64::from(gpu[row].out[i]) - out[i]).abs();
            assert!(
                error <= bound[i],
                "{down_t:?} row {row} [{i}]: |{} - {}| = {error:e} > {:e}",
                gpu[row].out[i],
                out[i],
                bound[i]
            );
            worst = worst.max(error / bound[i]);
            squared_error += error * error;
            squared_norm += (out[i] - f64::from(residual[row][i])).powi(2);
        }
    }
    eprintln!(
        "moe_live_tiles {down_t:?} vs F64: all {ROWS} rows checked, exact expert ids, \
         relative RMS error of the FFN term {:.3e}, worst error/bound {worst:.3}",
        (squared_error / squared_norm).sqrt()
    );
}

#[test]
fn live_tile_route_matches_f64_reference_down_q6_k() {
    matches_f64_reference(GgmlType::Q6_K, 0x64_16);
}

#[test]
fn live_tile_route_matches_f64_reference_down_q4_k() {
    matches_f64_reference(GgmlType::Q4_K, 0x64_14);
}

/// Every combination of the three MoE switches either selects one route or
/// fails: none falls back to another route.
#[test]
fn expert_switch_combinations_resolve_or_fail_closed() {
    use super::moe_batched::resolve_moe_expert_route as resolve;
    let on = Some("1");
    let off = [
        None,
        Some(""),
        Some("  "),
        Some("0"),
        Some("off"),
        Some("false"),
    ];
    for batched in [false, true] {
        for staged in off {
            for live in off {
                assert_eq!(resolve(batched, staged, live), Ok(MoeExpertRoute::Matvec));
            }
        }
    }
    assert_eq!(resolve(true, on, None), Ok(MoeExpertRoute::StagedM8));
    assert_eq!(
        resolve(true, Some("TRUE"), Some("off")),
        Ok(MoeExpertRoute::StagedM8)
    );
    assert_eq!(resolve(true, on, on), Ok(MoeExpertRoute::LiveTiles));
    assert_eq!(
        resolve(true, Some(" on "), Some("True")),
        Ok(MoeExpertRoute::LiveTiles)
    );

    let fails = |batched, staged, live, needle: &str| {
        let error = resolve(batched, staged, live).expect_err("combination must fail");
        assert!(error.contains(needle), "{error:?} does not name {needle:?}");
    };
    // Staged M8 without the batched route.
    fails(
        false,
        on,
        None,
        "HF2Q_QWEN_MOE_STAGED_M8=1 requires HF2Q_QWEN_MOE_BATCHED=1",
    );
    fails(
        false,
        on,
        on,
        "HF2Q_QWEN_MOE_STAGED_M8=1 requires HF2Q_QWEN_MOE_BATCHED=1",
    );
    // Live tiles without staged M8, with and without the batched route.
    fails(
        true,
        None,
        on,
        "HF2Q_QWEN_MOE_LIVE_TILES=1 requires HF2Q_QWEN_MOE_STAGED_M8=1",
    );
    fails(
        true,
        Some("0"),
        on,
        "HF2Q_QWEN_MOE_LIVE_TILES=1 requires HF2Q_QWEN_MOE_STAGED_M8=1",
    );
    fails(
        false,
        None,
        on,
        "HF2Q_QWEN_MOE_LIVE_TILES=1 requires HF2Q_QWEN_MOE_STAGED_M8=1",
    );
    // Invalid values, whatever the other switches say.
    for batched in [false, true] {
        for other in [None, on] {
            fails(
                batched,
                other,
                Some("bogus"),
                "HF2Q_QWEN_MOE_LIVE_TILES must be",
            );
            fails(batched, Some("2"), other, "HF2Q_QWEN_MOE_STAGED_M8 must be");
        }
    }
    assert_eq!(MoeExpertRoute::Matvec.label(), "matvec");
    assert_eq!(MoeExpertRoute::StagedM8.label(), "staged_m8");
    assert_eq!(MoeExpertRoute::LiveTiles.label(), "live_tiles");
}

/// Canonical storage preserves forced-MV/NR2 arithmetic and masking, and every
/// cache incarnation borrows the loaded model's same source-free owner.
#[test]
fn canonical_matvec_matches_raw_through_cache_rebuild_and_masking() {
    use std::sync::Arc;
    use super::weight_loader::{MoeFfnWeightsQ, MoeNativeDenseQ};
    let _gpu = crate::inference::hf2q_gpu_test_lock();
    let device = MlxDevice::new().expect("device");
    let (x, residual) = rows(32, 0xcac4_e013);
    for (down_t, q6_nr2) in [(GgmlType::Q4_K, false), (GgmlType::Q6_K, false), (GgmlType::Q6_K, true)] {
        let mut registry = KernelRegistry::new();
        let mut policy = mlx_native::GgmlRoutingPolicy::default();
        policy.expert_q6k_mv_nr2 = q6_nr2;
        registry.freeze_ggml_routing_policy(policy).expect("freeze model-bound routing");
        let layer = Layer::random(down_t, 0xcac4_e030);
        let raw = layer.gpu(&device, true, &layer.gpu_experts(&device));
        let canonical = super::gpu_expert_test_support::complete_experts(
            layer.gpu(&device, true, &layer.gpu_experts(&device)),
            shape(), &device, &mut registry,
        );
        let loaded = MoeFfnWeightsQ {
            experts: canonical.experts,
            ggml_type_gate_up: canonical.ggml_type_gate_up,
            ggml_type_down: canonical.ggml_type_down,
            router: Vec::new(), shared_gate_logit: Vec::new(),
            shared_gate: Vec::new(), shared_up: Vec::new(), shared_down: Vec::new(),
            native_dense: Some(MoeNativeDenseQ {
                router: canonical.router, shared_gate_inp: canonical.shared_gate_inp,
                shared_gate: canonical.shared_gate, shared_up: canonical.shared_up,
                shared_down: canonical.shared_down,
                ggml_type_shared_gate_up: GgmlType::Q4_K, ggml_type_shared_down: down_t,
            }),
        };
        let make_cache = || MoeFfnWeightsGpuQ::from_quantized(
            &loaded, NE as u32, MI as u32, H as u32, &device,
        ).expect("cache borrows canonical storage");
        let cache = make_cache();
        assert!(Arc::ptr_eq(&cache.experts, &loaded.experts));
        assert!(cache.experts.completed().is_some());
        drop(cache);
        assert_eq!(Arc::strong_count(&loaded.experts), 1);
        let cache = make_cache();
        assert!(Arc::ptr_eq(&cache.experts, &loaded.experts));
        for width in [1, 8, 32] {
            let select: Vec<usize> = (0..width).collect();
            let expected = run_route(
                &device, &mut registry, &raw, &x, &residual, &select, None, MoeExpertRoute::Matvec,
            );
            let actual = run_route(
                &device, &mut registry, &cache, &x, &residual, &select, None, MoeExpertRoute::Matvec,
            );
            for row in 0..width {
                assert_row(&actual[row], &expected[row], &format!("{down_t:?} width {width} row {row}"));
            }
        }
        let select: Vec<usize> = (0..32).collect();
        let verify = [5, 8, 1, 3];
        let expected = run_route(
            &device, &mut registry, &raw, &x, &residual, &select, Some(&verify), MoeExpertRoute::Matvec,
        );
        let actual = run_route(
            &device, &mut registry, &cache, &x, &residual, &select, Some(&verify), MoeExpertRoute::Matvec,
        );
        for row in 0..32 {
            assert_row(&actual[row], &expected[row], &format!("{down_t:?} masked row {row}"));
        }
        let mut enc = device.command_encoder().expect("encoder");
        let input = packed(&x, &[0], &device);
        let mut output = device.alloc_buffer(H * 4, DType::F32, vec![1, H]).expect("output");
        assert!(build_moe_ffn_layer_gpu_batched_route_into(
            &mut enc, &device, &mut registry, &input, &raw, shape(), None, &mut output,
            1, 0, None, MoeExpertRoute::StagedM8,
        ).is_err(), "a staged request must not fall back to raw matvec");
    }
}