inky-engine 3.0.1

A hand-fused Metal inference engine for Thinking Machines' Inkling 2 Mini, for Apple M5 Macs
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
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
//! Fast-path report: every speed path the engine can take, ON or OFF, and for each OFF the setting that gated it.
//!
//! The gate functions here are the predicates the engine itself calls when it picks kernels (`prefill_tc_attn`,
//! the decode attention choice, the tail trim, the grouped MoE decode, ...), so the report cannot drift from what
//! runs: change a gate and both the kernel choice and the report move together. [`report`] evaluates them for one
//! configuration ([`Inputs`]), which needs no GPU and no model weights, only their types. See
//! `docs/fast-path-audit.md` for the audit behind each entry.

use crate::gguf::*;

/// Why a fast path is off.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum OffKind {
    /// An explicit switch that names this path turned it off (`INK_NO_TC_ATTN`, `--no-kv-stitch`, ...).
    OptOut,
    /// Off by default because it measured slower; turning it on is an experiment arm.
    Default,
    /// Another setting, the mode or the hardware rules it out (`--exact`, `--kv8`, no tensor units).
    Mode,
    /// Nobody has written the kernel or the wiring for this combination or weight format yet.
    Missing,
}

impl OffKind {
    pub const fn name(self) -> &'static str {
        match self {
            OffKind::OptOut => "opt_out",
            OffKind::Default => "default_off",
            OffKind::Mode => "mode",
            OffKind::Missing => "missing",
        }
    }
}

/// One gate's verdict for a configuration.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Gate {
    On,
    Off(OffKind, &'static str),
}

impl Gate {
    pub const fn is_on(self) -> bool {
        matches!(self, Gate::On)
    }
}

/// Metal 4 tensor (MPP) kernels: `--no-mpp`, `INKY_DISABLE_MPP`, `INK_NO_TENSOR`, or a tuning without them.
pub const fn mpp_gate(no_mpp_flag: bool, disable_mpp_env: bool, no_tensor_env: bool, tuning_use_mpp: bool) -> Gate {
    if no_mpp_flag {
        Gate::Off(OffKind::OptOut, "--no-mpp")
    } else if disable_mpp_env {
        Gate::Off(OffKind::OptOut, "INKY_DISABLE_MPP")
    } else if no_tensor_env {
        Gate::Off(OffKind::OptOut, "INK_NO_TENSOR")
    } else if !tuning_use_mpp {
        Gate::Off(OffKind::Mode, "this machine's tuning has no Metal 4 tensor kernels (use_mpp = false)")
    } else {
        Gate::On
    }
}

/// fp16 prefill GEMMs and the half-precision attention path: needs MPP, no `INK_NO_HGEMM`, and the tensor
/// accumulator layout probe (`Engine::layout_ok`) passing on this GPU/OS.
pub const fn hgemm_gate(use_mpp: bool, no_hgemm_env: bool, layout_ok: bool) -> Gate {
    if !use_mpp {
        Gate::Off(OffKind::Mode, "Metal 4 tensor kernels are off (mpp_tensor)")
    } else if no_hgemm_env {
        Gate::Off(OffKind::OptOut, "INK_NO_HGEMM")
    } else if !layout_ok {
        Gate::Off(OffKind::Mode, "the tensor accumulator layout probe failed on this GPU/OS")
    } else {
        Gate::On
    }
}

/// Tensor-core prefill attention (`k_attn_tc_fixed_b`, `k_attn_tc_fixed_blk`), every cache format.
pub const fn tc_prefill_attn_gate(hgemm: bool, exact: bool, no_tc_attn_env: bool) -> Gate {
    if !hgemm {
        Gate::Off(OffKind::Mode, "the fp16 path is off (hgemm)")
    } else if exact {
        Gate::Off(OffKind::Mode, "--exact: prefill must write decode's bits")
    } else if no_tc_attn_env {
        Gate::Off(OffKind::OptOut, "INK_NO_TC_ATTN")
    } else {
        Gate::On
    }
}

/// Tensor-core decode attention (`k_attn_tc_dec`, `_solo`, `k_attn_tc_sparse_dec`): opt-in `INK_TC_ATTN_DEC`,
/// FP16 and KV4 only (the KV8 kernel bodies are stubs).
pub const fn tc_decode_attn_gate(hgemm: bool, exact: bool, no_tc_attn_env: bool, kv8: bool, tc_attn_dec_env: bool) -> Gate {
    if !tc_attn_dec_env {
        return Gate::Off(OffKind::Default, "off by default (measured slower at 32-64 lanes); INK_TC_ATTN_DEC=1 opts in");
    }
    match tc_prefill_attn_gate(hgemm, exact, no_tc_attn_env) {
        Gate::On if kv8 => Gate::Off(OffKind::Missing, "--kv8: no tensor-core KV8 decode kernels"),
        g => g,
    }
}

/// Last-layer tail trim, configuration part. Per step ([`tail_trim_step`]) it also needs a prefill step that is not
/// verify; then each span longer than `TAIL_MIN_T` is trimmed ([`tail_trim_start`]), one span in place, several
/// through `TailPlan` (compact rows).
pub const fn tail_trim_gate(hgemm: bool, tail: bool) -> Gate {
    if !hgemm {
        Gate::Off(OffKind::Mode, "the fp16 path is off (hgemm)")
    } else if !tail {
        Gate::Off(OffKind::OptOut, "INK_NO_TAIL")
    } else {
        Gate::On
    }
}

/// Rows of a span the last layer's query side keeps when the span is trimmed. The first three see the post-conv
/// state instead of their real predecessors and the next three inherit that through the FFN post-conv, so rows
/// `>= t - 2` are exact: the final row (logits) and the last three rows of both branch outputs (conv states).
pub const TAIL_ROWS: usize = 8;
/// A span is trimmed only when it is longer than this.
pub const TAIL_MIN_T: usize = 16;

/// The engine's per-step tail-trim predicate: [`tail_trim_gate`], on a prefill step (a decode step has one row per
/// span) that is not verify (it needs every row's logits). Any number of spans.
pub const fn tail_trim_step(hgemm: bool, tail: bool, dec: bool, verify: bool) -> bool {
    tail_trim_gate(hgemm, tail).is_on() && !dec && !verify
}

/// Local first row of a span's last-layer query side: `t - TAIL_ROWS` for a span longer than `TAIL_MIN_T`, else 0.
pub const fn tail_trim_start(t: usize) -> usize {
    if t > TAIL_MIN_T {
        t - TAIL_ROWS
    } else {
        0
    }
}

/// Separate split-attention combine pass (`serve` refuses to start without it).
pub const fn sep_comb_gate(sep_comb: bool) -> Gate {
    if sep_comb {
        Gate::On
    } else {
        Gate::Off(OffKind::OptOut, "INK_FUSE_COMB")
    }
}

/// Router top-k fused into the router pass.
pub const fn fused_topk_gate(sep_topk: bool) -> Gate {
    if sep_topk {
        Gate::Off(OffKind::OptOut, "INK_SEP_TOPK")
    } else {
        Gate::On
    }
}

/// Shared-K/V grouped decode attention (`k_attn_grp_dec`).
pub const fn grouped_decode_attn_gate(no_grp_dec: bool) -> Gate {
    if no_grp_dec {
        Gate::Off(OffKind::OptOut, "INK_NO_GRP_DEC")
    } else {
        Gate::On
    }
}

/// Right-sized single-read grouped MoE decode (`k_moe_dec_sg4/sg8`), configuration part (per step it also needs
/// `Engine::want_decode_sized`).
pub const fn grouped_moe_decode_gate(hgemm: bool, old_moe_dec_env: bool) -> Gate {
    if !hgemm {
        Gate::Off(OffKind::Mode, "the fp16 path is off (hgemm)")
    } else if old_moe_dec_env {
        Gate::Off(OffKind::OptOut, "INK_OLD_MOE_DEC")
    } else {
        Gate::On
    }
}

/// Multi-token grouped tiles of the grouped MoE decode (`INK_NO_GRP_MOE` falls back to `cnt = 1` tiles).
pub const fn grouped_moe_tiles_gate(no_grp_moe: bool) -> Gate {
    if no_grp_moe {
        Gate::Off(OffKind::OptOut, "INK_NO_GRP_MOE")
    } else {
        Gate::On
    }
}

/// Decode-sized dense fp16 GEMMs (`Engine::gemm_h_dec`), configuration part.
pub const fn decode_gemm_gate(old_moe_dec_env: bool) -> Gate {
    if old_moe_dec_env {
        Gate::Off(OffKind::OptOut, "INK_OLD_MOE_DEC")
    } else {
        Gate::On
    }
}

/// Concurrent batched mixer jobs (`k_mix_b_*`).
pub const fn batched_mix_gate(old_mixb_env: bool) -> Gate {
    if old_mixb_env {
        Gate::Off(OffKind::OptOut, "INK_OLD_MIXB")
    } else {
        Gate::On
    }
}

/// 16 query rows per tensor-core attention threadgroup (`prefill_attn_grid`); `--full-attn-budget` drops to 1.
pub const fn tc_attn_row_blocks_gate(full_attn_budget: bool) -> Gate {
    if full_attn_budget {
        Gate::Off(OffKind::Missing, "--full-attn-budget: one query row per threadgroup")
    } else {
        Gate::On
    }
}

/// The setting that drops the default `--sparse-topk` when the user did not name it, if any. `parse_serve` and
/// `inky run` call this to decide; the report calls it to say why. `--dspark` (and prompt lookup) keep it: verify
/// rows past the activation attend on the sparse decode kernels (`Engine::encode_verify_sparse_rows`).
pub const fn default_sparse_topk_dropped_by(exact: bool, full_attn_budget: bool) -> Option<Gate> {
    if exact {
        Some(Gate::Off(OffKind::Mode, "--exact: sparse retrieval is approximate"))
    } else if full_attn_budget {
        Some(Gate::Off(OffKind::Mode, "--full-attn-budget: one far-key pruning scheme at a time"))
    } else {
        None
    }
}

/// Sparse top-k full attention (above `--sparse-min-ctx`).
pub const fn sparse_topk_gate(sparse_topk: bool, exact: bool, full_attn_budget: bool) -> Gate {
    if sparse_topk {
        return Gate::On;
    }
    match default_sparse_topk_dropped_by(exact, full_attn_budget) {
        Some(g) => g,
        None => Gate::Off(OffKind::OptOut, "--sparse-topk off"),
    }
}

/// Sparse top-k prefill attention (`INK_SPARSE_PREFILL`, `src/engine/sparse_prefill.rs`): off by default until it is
/// measured; when on it needs tensor-core prefill attention (the masked kernel is `k_attn_tc_fixed_blk`), the
/// `--sparse-topk` block sketches and no `--full-attn-budget`. `Engine::encode_spans` calls this per span pass with
/// that step's `tc_attn`; a span past the floor that it turns away runs dense and counts a fallback.
pub const fn sparse_prefill_gate(on_env: bool, tc_prefill_attn: bool, sparse_topk: bool, full_attn_budget: bool) -> Gate {
    if !on_env {
        Gate::Off(OffKind::Default, "off by default (not measured on M5 yet); INK_SPARSE_PREFILL=1 opts in")
    } else if !tc_prefill_attn {
        Gate::Off(OffKind::Mode, "tensor-core prefill attention is off (tc_prefill_attn): the mask lives in that kernel")
    } else if !sparse_topk {
        Gate::Off(OffKind::Mode, "--sparse-topk is off: no block sketches to select by")
    } else if full_attn_budget {
        Gate::Off(OffKind::Mode, "--full-attn-budget: one far-key pruning scheme at a time")
    } else {
        Gate::On
    }
}

/// `INK_TC_EXP2` (`TC_ATT_EXP2` in `prefill.metal`): the tensor-core prefill softmax in log2 units, `exp2` for `exp`.
/// An inexact reordering of the float math, so off by default and KV8 only (`--kv8` promises no bits; FP16 and KV4
/// keep theirs). `tc_softmax_defines` in `engine.rs` compiles the define exactly when this is on with
/// `tc_prefill_attn = true`; the report also names tensor-core prefill attention being off, when the define would
/// sit in kernels that never run.
pub const fn tc_exp2_gate(on_env: bool, kv8: bool, tc_prefill_attn: bool) -> Gate {
    tc_softmax_reorder_gate(
        on_env,
        kv8,
        tc_prefill_attn,
        "off by default (inexact: reorders the softmax float math); INK_TC_EXP2=1 opts in under --kv8",
    )
}

/// `INK_TC_LAZY_RESCALE` (`TC_ATT_LAZY_RESCALE`): a row's reference max moves only when the tile max passes it by more
/// than 8, so most tiles skip the `O *= alpha` pass. Inexact, off by default, KV8 only, as [`tc_exp2_gate`].
pub const fn tc_lazy_rescale_gate(on_env: bool, kv8: bool, tc_prefill_attn: bool) -> Gate {
    tc_softmax_reorder_gate(
        on_env,
        kv8,
        tc_prefill_attn,
        "off by default (inexact: reorders the softmax float math); INK_TC_LAZY_RESCALE=1 opts in under --kv8",
    )
}

const fn tc_softmax_reorder_gate(on_env: bool, kv8: bool, tc_prefill_attn: bool, default_off: &'static str) -> Gate {
    if !on_env {
        Gate::Off(OffKind::Default, default_off)
    } else if !kv8 {
        Gate::Off(OffKind::Mode, "KV8 only: FP16 and KV4 keep the exact softmax order, the switch is refused")
    } else if !tc_prefill_attn {
        Gate::Off(OffKind::Mode, "tensor-core prefill attention is off (tc_prefill_attn): the reordering lives in that kernel")
    } else {
        Gate::On
    }
}

/// Approximate Zero-RoPE K/V stitching across turns and cartridges.
pub const fn kv_stitch_gate(kv_stitch: bool, exact: bool) -> Gate {
    if kv_stitch {
        Gate::On
    } else if exact {
        Gate::Off(OffKind::Mode, "--exact: stitched K/V is approximate")
    } else {
        Gate::Off(OffKind::OptOut, "--no-kv-stitch")
    }
}

/// Attention projections as the GGUF's GEMMs alone. `INK_LORA` (an experiment arm) adds a runtime LoRA beside
/// q / k / v / o: two more dispatches after each projection group (`Engine::lora_apply`), every other path kept.
pub const fn attn_proj_plain_gate(lora: bool) -> Gate {
    if lora {
        Gate::Off(OffKind::OptOut, "INK_LORA: y += scale * B (A x) beside q/k/v/o, two extra dispatches per projection group")
    } else {
        Gate::On
    }
}

/// Environment switches the report reads. The engine reads the same names at load or step time.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct EnvFlags {
    pub disable_mpp: bool,
    pub no_tensor: bool,
    pub no_hgemm: bool,
    pub no_tc_attn: bool,
    pub tc_attn_dec: bool,
    pub old_moe_dec: bool,
    pub old_mixb: bool,
    pub generic_moe: bool,
    pub tc_exp2: bool,
    pub tc_lazy_rescale: bool,
}

/// `value` set to something other than empty or `0`.
fn truthy(v: Option<String>) -> bool {
    v.is_some_and(|v| !v.is_empty() && v != "0")
}

impl EnvFlags {
    /// Read through `get` (the process environment in production), with each name's own rule: the engine tests
    /// some for presence (`var_os(..).is_some()`) and others for a truthy value.
    pub fn read(get: impl Fn(&str) -> Option<String>) -> EnvFlags {
        EnvFlags {
            disable_mpp: truthy(get("INKY_DISABLE_MPP")),
            no_tensor: get("INK_NO_TENSOR").is_some(),
            no_hgemm: get("INK_NO_HGEMM").is_some(),
            no_tc_attn: get("INK_NO_TC_ATTN").is_some(),
            tc_attn_dec: get("INK_TC_ATTN_DEC").is_some(),
            old_moe_dec: get("INK_OLD_MOE_DEC").is_some(),
            old_mixb: get("INK_OLD_MIXB").is_some(),
            generic_moe: truthy(get("INK_GENERIC_MOE")),
            tc_exp2: truthy(get("INK_TC_EXP2")),
            tc_lazy_rescale: truthy(get("INK_TC_LAZY_RESCALE")),
        }
    }
    pub fn from_process() -> EnvFlags {
        Self::read(|name| std::env::var_os(name).map(|v| v.to_string_lossy().into_owned()))
    }
}

/// Everything the report depends on: the engine's resolved settings, the serve options and the expert formats.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Inputs {
    pub no_mpp_flag: bool,
    pub tuning_use_mpp: bool,
    /// Engine `use_mpp` after load.
    pub use_mpp: bool,
    /// Engine `hgemm` after load (and the `layout_ok` fallback).
    pub hgemm: bool,
    pub exact: bool,
    pub kv8: bool,
    pub sep_comb: bool,
    pub sep_topk: bool,
    pub tail: bool,
    pub no_grp_dec: bool,
    pub no_grp_moe: bool,
    pub full_attn_budget: bool,
    pub sparse_topk: bool,
    /// `INK_SPARSE_PREFILL` as the engine parsed it at load.
    pub sparse_prefill: bool,
    pub kv_stitch: bool,
    /// a runtime LoRA adapter is loaded (`INK_LORA`)
    pub lora: bool,
    /// `(gate/up, down)` weight type of each layer's experts.
    pub expert_types: Vec<(u32, u32)>,
    pub env: EnvFlags,
}

impl Inputs {
    #[cfg(test)]
    /// The default `inky serve` configuration on an M5 (KV4, sparse top-k, stitching), Q4_K / Q8_0 experts.
    pub fn serve_default() -> Inputs {
        Inputs {
            no_mpp_flag: false,
            tuning_use_mpp: true,
            use_mpp: true,
            hgemm: true,
            exact: false,
            kv8: false,
            sep_comb: true,
            sep_topk: false,
            tail: true,
            no_grp_dec: false,
            no_grp_moe: false,
            full_attn_budget: false,
            sparse_topk: true,
            sparse_prefill: false,
            kv_stitch: true,
            lora: false,
            expert_types: vec![(T_Q4_K, T_Q8_0); 2],
            env: EnvFlags::default(),
        }
    }
}

impl crate::engine::Engine {
    /// The report inputs of this loaded engine, read the way the engine reads them: its resolved settings, the
    /// process environment, and the serve option it cannot see (`--kv-stitch`). `--no-mpp` is read from
    /// `DISABLE_MPP`, the switch `into_engine_mode` itself read when it chose `use_mpp`.
    pub fn fast_path_inputs(&self, kv_stitch: bool) -> Inputs {
        let (chip, mem) = crate::tuning::this_machine();
        Inputs {
            no_mpp_flag: crate::engine::DISABLE_MPP.load(std::sync::atomic::Ordering::Relaxed),
            tuning_use_mpp: crate::tuning::select(&chip, mem).use_mpp,
            use_mpp: self.use_mpp,
            hgemm: self.hgemm,
            exact: self.exact,
            kv8: self.kv8,
            sep_comb: self.sep_comb,
            sep_topk: self.sep_topk,
            tail: self.tail.get(),
            no_grp_dec: self.no_grp_dec.get(),
            no_grp_moe: self.no_grp_moe.get(),
            full_attn_budget: self.full_attn_budget().is_some(),
            sparse_topk: self.sparse_topk().is_some(),
            sparse_prefill: self.sparse_prefill().is_some(),
            kv_stitch,
            lora: !self.lora.is_empty(),
            expert_types: self.layers.iter().map(|l| (l.gu.ty, l.dn.ty)).collect(),
            env: EnvFlags::from_process(),
        }
    }
}

/// One fast path's state.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct FastPath {
    pub id: &'static str,
    pub what: &'static str,
    pub on: bool,
    pub kind: Option<OffKind>,
    pub reason: Option<String>,
}

/// Every fast path, in a fixed order.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Report {
    pub paths: Vec<FastPath>,
}

/// Every id the report can carry (`INK_FAST_PATH_OPT_OUT` accepts these).
pub const IDS: [&str; 21] = [
    "mpp_tensor",
    "hgemm",
    "tc_prefill_attn",
    "tc_decode_attn",
    "tail_trim",
    "sep_comb",
    "fused_topk",
    "grouped_decode_attn",
    "grouped_moe_decode",
    "grouped_moe_tiles",
    "decode_gemm",
    "batched_mix",
    "moe_prefill_specialised",
    "moe_decode_specialised",
    "tc_attn_row_blocks",
    "sparse_topk",
    "sparse_prefill",
    "kv_stitch",
    "attn_proj_plain",
    "tc_exp2",
    "tc_lazy_rescale",
];

fn path(id: &'static str, what: &'static str, gate: Gate) -> FastPath {
    match gate {
        Gate::On => FastPath { id, what, on: true, kind: None, reason: None },
        Gate::Off(kind, why) => FastPath { id, what, on: false, kind: Some(kind), reason: Some(why.to_string()) },
    }
}

fn type_name(ty: u32) -> String {
    match ty {
        T_Q4_K => "Q4_K".into(),
        T_Q5_0 => "Q5_0".into(),
        T_Q6_K => "Q6_K".into(),
        T_Q8_0 => "Q8_0".into(),
        T_Q2_K => "Q2_K".into(),
        T_Q3_K => "Q3_K".into(),
        T_Q3_0 => "Q3_0".into(),
        T_NV4 => "NV4".into(),
        T_MX8 => "MX8".into(),
        T_BF16 => "BF16".into(),
        other => format!("type {other}"),
    }
}

/// Expert formats that take a generic kernel: `kernel(ty, situ)` is the engine's own selector, `generic` its
/// fallback name. `None` when every expert tensor has a specialised kernel.
fn generic_formats(types: &[(u32, u32)], kernel: impl Fn(u32, bool) -> &'static str, generic: &str) -> Option<String> {
    let mut hits: Vec<String> = Vec::new();
    for &(gu, dn) in types {
        for (ty, situ, part) in [(gu, true, "gate/up"), (dn, false, "down")] {
            if kernel(ty, situ) == generic {
                let s = format!("{part} {}", type_name(ty));
                if !hits.contains(&s) {
                    hits.push(s);
                }
            }
        }
    }
    (!hits.is_empty()).then(|| hits.join(", "))
}

/// The fast-path report for `i`.
pub fn report(i: &Inputs) -> Report {
    let env = i.env;
    let mut paths = vec![
        path("mpp_tensor", "Metal 4 tensor kernels", mpp_gate(i.no_mpp_flag, env.disable_mpp, env.no_tensor, i.tuning_use_mpp)),
    ];
    // `hgemm` as resolved; when it is off with MPP on and no INK_NO_HGEMM, the layout probe turned it off.
    let layout_ok = i.hgemm || !i.use_mpp || env.no_hgemm;
    paths.push(path("hgemm", "fp16 prefill GEMMs and half attention I/O", hgemm_gate(i.use_mpp, env.no_hgemm, layout_ok)));
    paths.push(path(
        "tc_prefill_attn",
        "tensor-core prefill attention",
        tc_prefill_attn_gate(i.hgemm, i.exact, env.no_tc_attn),
    ));
    paths.push(path(
        "tc_decode_attn",
        "tensor-core decode attention",
        tc_decode_attn_gate(i.hgemm, i.exact, env.no_tc_attn, i.kv8, env.tc_attn_dec),
    ));
    paths.push(path("tail_trim", "last-layer tail trim (prefill, one or many spans)", tail_trim_gate(i.hgemm, i.tail)));
    paths.push(path("sep_comb", "separate split-attention combine", sep_comb_gate(i.sep_comb)));
    paths.push(path("fused_topk", "router top-k fused into the router", fused_topk_gate(i.sep_topk)));
    paths.push(path("grouped_decode_attn", "shared-K/V grouped decode attention", grouped_decode_attn_gate(i.no_grp_dec)));
    paths.push(path(
        "grouped_moe_decode",
        "grouped single-read MoE decode",
        grouped_moe_decode_gate(i.hgemm, env.old_moe_dec),
    ));
    paths.push(path("grouped_moe_tiles", "multi-token grouped MoE decode tiles", grouped_moe_tiles_gate(i.no_grp_moe)));
    paths.push(path("decode_gemm", "decode-sized dense fp16 GEMMs", decode_gemm_gate(env.old_moe_dec)));
    paths.push(path("batched_mix", "concurrent batched mixer jobs", batched_mix_gate(env.old_mixb)));
    // The prefill MoE kernels exist only on the fp16 path; there the selector is `moe_sg_kernel_for`.
    let prefill_moe = if !i.hgemm {
        path("moe_prefill_specialised", "format-specialised prefill MoE", Gate::Off(OffKind::Mode, "the fp16 path is off (hgemm)"))
    } else if env.generic_moe {
        path("moe_prefill_specialised", "format-specialised prefill MoE", Gate::Off(OffKind::OptOut, "INK_GENERIC_MOE"))
    } else {
        let generic = crate::engine::moe_sg_kernel_for(1, u32::MAX, true, false);
        match generic_formats(&i.expert_types, |ty, situ| crate::engine::moe_sg_kernel_for(1, ty, situ, false), generic) {
            None => path("moe_prefill_specialised", "format-specialised prefill MoE", Gate::On),
            Some(fmts) => FastPath {
                id: "moe_prefill_specialised",
                what: "format-specialised prefill MoE",
                on: false,
                kind: Some(OffKind::Missing),
                reason: Some(format!("no specialised prefill MoE kernel for experts {fmts}")),
            },
        }
    };
    paths.push(prefill_moe);
    let decode_moe = if !grouped_moe_decode_gate(i.hgemm, env.old_moe_dec).is_on() {
        path(
            "moe_decode_specialised",
            "format-specialised grouped MoE decode",
            Gate::Off(OffKind::Mode, "grouped MoE decode is off (grouped_moe_decode)"),
        )
    } else {
        let generic = crate::engine::moe_dec_sg4_kernel(u32::MAX, true);
        match generic_formats(&i.expert_types, crate::engine::moe_dec_sg4_kernel, generic) {
            None => path("moe_decode_specialised", "format-specialised grouped MoE decode", Gate::On),
            Some(fmts) => FastPath {
                id: "moe_decode_specialised",
                what: "format-specialised grouped MoE decode",
                on: false,
                kind: Some(OffKind::Missing),
                reason: Some(format!("no specialised decode MoE kernel for experts {fmts}")),
            },
        }
    };
    paths.push(decode_moe);
    paths.push(path(
        "tc_attn_row_blocks",
        "16 query rows per tensor-core attention threadgroup",
        tc_attn_row_blocks_gate(i.full_attn_budget),
    ));
    paths.push(path(
        "sparse_topk",
        "sparse top-k full attention past --sparse-min-ctx",
        sparse_topk_gate(i.sparse_topk, i.exact, i.full_attn_budget),
    ));
    paths.push(path(
        "sparse_prefill",
        "sparse top-k prefill attention past INK_SPARSE_PREFILL_MIN_CTX",
        sparse_prefill_gate(
            i.sparse_prefill,
            tc_prefill_attn_gate(i.hgemm, i.exact, env.no_tc_attn).is_on(),
            i.sparse_topk,
            i.full_attn_budget,
        ),
    ));
    paths.push(path("kv_stitch", "stitched K/V reuse", kv_stitch_gate(i.kv_stitch, i.exact)));
    paths.push(path("attn_proj_plain", "attention projections without runtime-LoRA side kernels", attn_proj_plain_gate(i.lora)));
    let tc_prefill = tc_prefill_attn_gate(i.hgemm, i.exact, env.no_tc_attn).is_on();
    paths.push(path(
        "tc_exp2",
        "exp2 softmax in tensor-core prefill attention (inexact, KV8)",
        tc_exp2_gate(env.tc_exp2, i.kv8, tc_prefill),
    ));
    paths.push(path(
        "tc_lazy_rescale",
        "lazy O rescale in tensor-core prefill attention (inexact, KV8)",
        tc_lazy_rescale_gate(env.tc_lazy_rescale, i.kv8, tc_prefill),
    ));
    Report { paths }
}

/// The `INK_REQUIRE_FAST_PATHS` policy: refuse to start when a path is off for a reason other than an explicit
/// opt-out naming it, a measured default, or an id listed in `INK_FAST_PATH_OPT_OUT`.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Policy {
    pub require: bool,
    pub opt_out: Vec<String>,
}

impl Policy {
    /// Read `INK_REQUIRE_FAST_PATHS` (`0` or `1`) and `INK_FAST_PATH_OPT_OUT` (comma-separated report ids).
    pub fn read(get: impl Fn(&str) -> Option<String>) -> Result<Policy, String> {
        let require = match get("INK_REQUIRE_FAST_PATHS").as_deref() {
            None | Some("") | Some("0") => false,
            Some("1") => true,
            Some(_) => return Err("INK_REQUIRE_FAST_PATHS must be 0 or 1".into()),
        };
        let mut opt_out = Vec::new();
        for id in get("INK_FAST_PATH_OPT_OUT").unwrap_or_default().split(',').map(str::trim).filter(|s| !s.is_empty()) {
            if !IDS.contains(&id) {
                return Err(format!("INK_FAST_PATH_OPT_OUT: unknown fast path {id:?} (known: {})", IDS.join(", ")));
            }
            opt_out.push(id.to_string());
        }
        Ok(Policy { require, opt_out })
    }
}

impl Report {
    #[cfg(test)]
    pub fn get(&self, id: &str) -> Option<&FastPath> {
        self.paths.iter().find(|p| p.id == id)
    }

    /// Paths that are off for a reason the policy does not accept: anything but an explicit opt-out naming the path
    /// or a measured default, unless the id is in `opt_out`.
    pub fn unaccepted<'a>(&'a self, policy: &Policy) -> Vec<&'a FastPath> {
        self.paths
            .iter()
            .filter(|p| !p.on)
            .filter(|p| !matches!(p.kind, Some(OffKind::OptOut | OffKind::Default)))
            .filter(|p| !policy.opt_out.iter().any(|o| o == p.id))
            .collect()
    }

    /// `/health` `fast_paths`: `{ id: { "on": bool, "kind": ..., "reason": ... } }` plus `off` and `unaccepted` counts.
    pub fn to_json(&self, policy: &Policy) -> serde_json::Value {
        let mut paths = serde_json::Map::new();
        for p in &self.paths {
            let mut o = serde_json::Map::new();
            o.insert("on".into(), serde_json::json!(p.on));
            if let Some(k) = p.kind {
                o.insert("kind".into(), serde_json::json!(k.name()));
            }
            if let Some(r) = &p.reason {
                o.insert("reason".into(), serde_json::json!(r));
            }
            paths.insert(p.id.into(), serde_json::Value::Object(o));
        }
        let unaccepted: Vec<&str> = self.unaccepted(policy).iter().map(|p| p.id).collect();
        serde_json::json!({
            "paths": paths,
            "off": self.paths.iter().filter(|p| !p.on).count(),
            "unaccepted": unaccepted,
            "require": policy.require,
            "opt_out": policy.opt_out,
        })
    }

    /// The startup block: one line per path, OFF lines with their reason, `!!` on the ones the policy does not accept.
    pub fn log_lines(&self, policy: &Policy) -> Vec<String> {
        let bad: Vec<&str> = self.unaccepted(policy).iter().map(|p| p.id).collect();
        let off = self.paths.iter().filter(|p| !p.on).count();
        let mut out = vec![format!(
            "[fast-paths] {} of {} on, {} off, {} off without an opt-out{}",
            self.paths.len() - off,
            self.paths.len(),
            off,
            bad.len(),
            if policy.require { " (INK_REQUIRE_FAST_PATHS=1)" } else { "" }
        )];
        for p in &self.paths {
            if p.on {
                out.push(format!("[fast-paths]    ON   {:<24} {}", p.id, p.what));
            } else {
                let mark = if bad.contains(&p.id) { "!!" } else { "  " };
                out.push(format!(
                    "[fast-paths] {mark} OFF  {:<24} {} -- {} ({})",
                    p.id,
                    p.what,
                    p.reason.as_deref().unwrap_or(""),
                    p.kind.map_or("", OffKind::name)
                ));
            }
        }
        if !bad.is_empty() && !policy.require {
            out.push(format!(
                "[fast-paths] WARNING: {} switched off by another setting: {}. Name them in INK_FAST_PATH_OPT_OUT to accept, INK_REQUIRE_FAST_PATHS=1 refuses to start",
                if bad.len() == 1 { "a fast path is" } else { "fast paths are" },
                bad.join(", ")
            ));
        }
        out
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn off(r: &Report, id: &str) -> (OffKind, String) {
        let p = r.get(id).unwrap_or_else(|| panic!("no {id}"));
        assert!(!p.on, "{id} should be off");
        (p.kind.unwrap(), p.reason.clone().unwrap())
    }

    fn on(r: &Report, id: &str) -> bool {
        r.get(id).unwrap_or_else(|| panic!("no {id}")).on
    }

    #[test]
    fn every_id_is_reported_once_in_order() {
        let r = report(&Inputs::serve_default());
        let ids: Vec<&str> = r.paths.iter().map(|p| p.id).collect();
        assert_eq!(ids, IDS);
    }

    #[test]
    fn serve_default_keeps_every_path_but_measured_tc_decode() {
        let r = report(&Inputs::serve_default());
        let offs: Vec<&str> = r.paths.iter().filter(|p| !p.on).map(|p| p.id).collect();
        assert_eq!(offs, ["tc_decode_attn", "sparse_prefill", "tc_exp2", "tc_lazy_rescale"]);
        for id in offs {
            assert_eq!(off(&r, id).0, OffKind::Default, "{id}");
        }
        assert!(r.unaccepted(&Policy::default()).is_empty());
    }

    #[test]
    fn sparse_prefill_is_default_off_and_names_what_blocks_it_when_on() {
        let mut i = Inputs::serve_default();
        i.sparse_prefill = true;
        assert!(on(&report(&i), "sparse_prefill"));
        i.env.no_tc_attn = true;
        assert_eq!(off(&report(&i), "sparse_prefill").0, OffKind::Mode);
        i.env.no_tc_attn = false;
        i.exact = true;
        assert!(off(&report(&i), "sparse_prefill").1.contains("tc_prefill_attn"));
        i.exact = false;
        i.sparse_topk = false;
        assert!(off(&report(&i), "sparse_prefill").1.contains("--sparse-topk"));
        i.sparse_topk = true;
        i.full_attn_budget = true;
        assert!(off(&report(&i), "sparse_prefill").1.contains("--full-attn-budget"));
    }

    #[test]
    fn kv8_keeps_tc_prefill_and_blocks_tc_decode_only_when_asked_for() {
        let mut i = Inputs::serve_default();
        i.kv8 = true;
        let r = report(&i);
        assert!(on(&r, "tc_prefill_attn"), "#234: KV8 prefill is on the tensor cores");
        assert_eq!(off(&r, "tc_decode_attn").0, OffKind::Default);
        i.env.tc_attn_dec = true;
        let r = report(&i);
        let (kind, why) = off(&r, "tc_decode_attn");
        assert_eq!(kind, OffKind::Missing);
        assert!(why.contains("--kv8"), "{why}");
        assert_eq!(r.unaccepted(&Policy::default()).iter().map(|p| p.id).collect::<Vec<_>>(), ["tc_decode_attn"]);
        i.kv8 = false;
        let r = report(&i);
        assert!(on(&r, "tc_decode_attn"));
    }

    #[test]
    fn tc_softmax_reorderings_are_kv8_opt_ins_refused_elsewhere() {
        for (id, env) in [("tc_exp2", "INK_TC_EXP2"), ("tc_lazy_rescale", "INK_TC_LAZY_RESCALE")] {
            let mut i = Inputs::serve_default();
            i.kv8 = true;
            let (kind, why) = off(&report(&i), id);
            assert_eq!(kind, OffKind::Default, "{id}");
            assert!(why.contains(env), "{id}: {why}");
            i.env = EnvFlags::read(|name| (name == env).then(|| "1".to_string()));
            assert!(on(&report(&i), id), "{id}: {env}=1 under --kv8");
            i.env = EnvFlags::read(|name| (name == env).then(|| "0".to_string()));
            assert_eq!(off(&report(&i), id).0, OffKind::Default, "{id}: {env}=0 is off");
            i.env = EnvFlags::read(|name| (name == env).then(|| "1".to_string()));
            i.kv8 = false;
            let r = report(&i);
            let (kind, why) = off(&r, id);
            assert_eq!(kind, OffKind::Mode, "{id}");
            assert!(why.contains("KV8 only"), "{id}: {why}");
            assert_eq!(r.unaccepted(&Policy::default()).iter().map(|p| p.id).collect::<Vec<_>>(), [id]);
            i.kv8 = true;
            i.env.no_tc_attn = true;
            assert!(off(&report(&i), id).1.contains("tc_prefill_attn"), "{id}");
        }
    }

    #[test]
    fn tc_softmax_defines_follow_the_gates() {
        for bits in 0u32..8 {
            let b = |n: u32| bits & (1 << n) != 0;
            let (kv8, exp2, lazy) = (b(0), b(1), b(2));
            let d = crate::engine::tc_softmax_defines(kv8, exp2, lazy);
            assert_eq!(d.contains("#define TC_ATT_EXP2 1"), tc_exp2_gate(exp2, kv8, true).is_on());
            assert_eq!(d.contains("#define TC_ATT_LAZY_RESCALE 1"), tc_lazy_rescale_gate(lazy, kv8, true).is_on());
        }
    }

    #[test]
    fn exact_turns_off_tc_prefill_sparse_and_stitch_as_mode() {
        let mut i = Inputs::serve_default();
        i.exact = true;
        i.sparse_topk = false;
        i.kv_stitch = false;
        let r = report(&i);
        for id in ["tc_prefill_attn", "sparse_topk", "kv_stitch"] {
            let (kind, why) = off(&r, id);
            assert_eq!(kind, OffKind::Mode, "{id}");
            assert!(why.contains("--exact"), "{id}: {why}");
        }
        // tc decode stays a measured default, not an --exact loss
        assert_eq!(off(&r, "tc_decode_attn").0, OffKind::Default);
        let ids: Vec<&str> = r.unaccepted(&Policy::default()).iter().map(|p| p.id).collect();
        assert_eq!(ids, ["tc_prefill_attn", "sparse_topk", "kv_stitch"]);
        let accepted = Policy { require: true, opt_out: ids.iter().map(|s| s.to_string()).collect() };
        assert!(r.unaccepted(&accepted).is_empty());
    }

    #[test]
    fn dspark_keeps_sparse_and_only_exact_or_budget_drop_it() {
        // --dspark no longer drops the default: the parser and the report call the same function
        assert!(default_sparse_topk_dropped_by(false, false).is_none());
        let i = Inputs::serve_default();
        assert!(on(&report(&i), "sparse_topk"));
        // without --exact or --full-attn-budget, sparse off can only be the user's own choice
        let mut i = Inputs::serve_default();
        i.sparse_topk = false;
        assert_eq!(off(&report(&i), "sparse_topk").0, OffKind::OptOut);
    }

    #[test]
    fn ink_lora_is_reported_as_an_accepted_opt_out_and_costs_no_other_path() {
        let mut i = Inputs::serve_default();
        i.lora = true;
        let r = report(&i);
        let (kind, why) = off(&r, "attn_proj_plain");
        assert_eq!(kind, OffKind::OptOut);
        assert!(why.contains("INK_LORA"), "{why}");
        // only the measured tc decode default, the default-off sparse prefill, the default-off inexact tc softmax
        // switches and the LoRA arm itself are off; the policy accepts them
        let offs: Vec<&str> = r.paths.iter().filter(|p| !p.on).map(|p| p.id).collect();
        assert_eq!(offs, ["tc_decode_attn", "sparse_prefill", "attn_proj_plain", "tc_exp2", "tc_lazy_rescale"]);
        assert!(r.unaccepted(&Policy { require: true, opt_out: vec![] }).is_empty());
    }

    #[test]
    fn full_attn_budget_loses_row_blocks_and_sparse() {
        let mut i = Inputs::serve_default();
        i.full_attn_budget = true;
        i.sparse_topk = false;
        let r = report(&i);
        assert_eq!(off(&r, "tc_attn_row_blocks").0, OffKind::Missing);
        assert_eq!(off(&r, "sparse_topk").0, OffKind::Mode);
    }

    #[test]
    fn no_mpp_cascades_to_every_fp16_path() {
        let mut i = Inputs::serve_default();
        i.no_mpp_flag = true;
        i.use_mpp = false;
        i.hgemm = false;
        let r = report(&i);
        assert_eq!(off(&r, "mpp_tensor"), (OffKind::OptOut, "--no-mpp".into()));
        for id in ["hgemm", "tc_prefill_attn", "tail_trim", "grouped_moe_decode", "moe_prefill_specialised", "moe_decode_specialised"] {
            assert_eq!(off(&r, id).0, OffKind::Mode, "{id}");
        }
    }

    #[test]
    fn tail_trim_step_is_the_gate_on_prefill_steps() {
        for (hgemm, tail) in [(true, true), (true, false), (false, true), (false, false)] {
            let on = tail_trim_gate(hgemm, tail).is_on();
            assert_eq!(tail_trim_step(hgemm, tail, false, false), on);
            assert!(!tail_trim_step(hgemm, tail, true, false), "a decode step");
            assert!(!tail_trim_step(hgemm, tail, false, true), "verify needs every row");
        }
        assert_eq!(tail_trim_start(1), 0);
        assert_eq!(tail_trim_start(TAIL_MIN_T), 0);
        assert_eq!(tail_trim_start(TAIL_MIN_T + 1), TAIL_MIN_T + 1 - TAIL_ROWS);
        assert_eq!(tail_trim_start(4096), 4096 - TAIL_ROWS);
    }

    #[test]
    fn layout_probe_failure_is_named() {
        let mut i = Inputs::serve_default();
        i.hgemm = false;
        let (kind, why) = off(&report(&i), "hgemm");
        assert_eq!(kind, OffKind::Mode);
        assert!(why.contains("layout"), "{why}");
        i.env.no_hgemm = true;
        assert_eq!(off(&report(&i), "hgemm"), (OffKind::OptOut, "INK_NO_HGEMM".into()));
    }

    #[test]
    fn dev_switches_are_named_opt_outs() {
        let mut i = Inputs::serve_default();
        i.env = EnvFlags::read(|name| {
            matches!(name, "INK_NO_TC_ATTN" | "INK_OLD_MOE_DEC" | "INK_OLD_MIXB" | "INK_GENERIC_MOE").then(|| "1".to_string())
        });
        i.no_grp_dec = true;
        i.no_grp_moe = true;
        i.tail = false;
        i.sep_topk = true;
        let r = report(&i);
        for (id, why) in [
            ("tc_prefill_attn", "INK_NO_TC_ATTN"),
            ("grouped_moe_decode", "INK_OLD_MOE_DEC"),
            ("decode_gemm", "INK_OLD_MOE_DEC"),
            ("batched_mix", "INK_OLD_MIXB"),
            ("moe_prefill_specialised", "INK_GENERIC_MOE"),
            ("grouped_decode_attn", "INK_NO_GRP_DEC"),
            ("grouped_moe_tiles", "INK_NO_GRP_MOE"),
            ("tail_trim", "INK_NO_TAIL"),
            ("fused_topk", "INK_SEP_TOPK"),
        ] {
            assert_eq!(off(&r, id), (OffKind::OptOut, why.to_string()), "{id}");
        }
        // INK_NO_TC_ATTN takes TC decode with it even if INK_TC_ATTN_DEC asks for it, and the report names that switch:
        // it opts out of tensor-core attention, prefill and decode alike
        i.env.tc_attn_dec = true;
        assert_eq!(off(&report(&i), "tc_decode_attn"), (OffKind::OptOut, "INK_NO_TC_ATTN".into()));
    }

    #[test]
    fn expert_formats_without_specialised_kernels_are_named() {
        let mut i = Inputs::serve_default();
        i.expert_types = vec![(T_Q4_K, T_Q8_0), (T_NV4, T_NV4), (T_Q3_K, T_Q5_0)];
        let r = report(&i);
        let (kind, why) = off(&r, "moe_decode_specialised");
        assert_eq!(kind, OffKind::Missing);
        assert!(why.contains("gate/up NV4") && why.contains("down NV4") && why.contains("gate/up Q3_K"), "{why}");
        assert!(!why.contains("Q4_K") && !why.contains("Q8_0") && !why.contains("Q5_0"), "{why}");
        let (_, why) = off(&r, "moe_prefill_specialised");
        assert!(why.contains("Q3_K") && !why.contains("NV4"), "prefill has NV4 kernels: {why}");
        i.expert_types = vec![(T_MX8, T_MX8)];
        assert!(on(&report(&i), "moe_prefill_specialised"));
    }

    #[test]
    fn gates_agree_with_the_engine_predicates() {
        for bits in 0u32..32 {
            let b = |n: u32| bits & (1 << n) != 0;
            let (hgemm, exact, no_tc, kv8, dec) = (b(0), b(1), b(2), b(3), b(4));
            assert_eq!(tc_prefill_attn_gate(hgemm, exact, no_tc).is_on(), crate::engine::prefill_tc_attn(hgemm, exact, no_tc));
            assert_eq!(
                tc_decode_attn_gate(hgemm, exact, no_tc, kv8, dec).is_on(),
                crate::engine::prefill_tc_attn(hgemm, exact, no_tc) && !kv8 && dec
            );
            assert_eq!(hgemm_gate(b(0), b(1), b(2)).is_on(), crate::engine::Engine::resolve_effective_hgemm(b(0), b(1), b(2)));
            // `ArithKnobs::split_attn` now derives from the decode gate; it keeps its old formula
            let set = |name: &str| (name == "INK_NO_TC_ATTN" && no_tc) || (name == "INK_TC_ATTN_DEC" && dec);
            assert_eq!(
                crate::engine::split_attn(hgemm, exact, kv8, set),
                crate::engine::prefill_tc_attn(hgemm, exact, no_tc) && (kv8 || !dec)
            );
        }
    }

    #[test]
    fn policy_reads_and_validates() {
        let env = |pairs: &'static [(&'static str, &'static str)]| {
            move |name: &str| pairs.iter().find(|(k, _)| *k == name).map(|(_, v)| v.to_string())
        };
        assert_eq!(Policy::read(env(&[])).unwrap(), Policy::default());
        let p = Policy::read(env(&[("INK_REQUIRE_FAST_PATHS", "1"), ("INK_FAST_PATH_OPT_OUT", "sparse_topk, kv_stitch")])).unwrap();
        assert!(p.require);
        assert_eq!(p.opt_out, ["sparse_topk", "kv_stitch"]);
        assert!(Policy::read(env(&[("INK_REQUIRE_FAST_PATHS", "yes")])).unwrap_err().contains("0 or 1"));
        assert!(Policy::read(env(&[("INK_FAST_PATH_OPT_OUT", "tc_attn")])).unwrap_err().contains("unknown fast path"));
    }

    #[test]
    fn json_and_log_block_name_every_off_path() {
        let mut i = Inputs::serve_default();
        i.full_attn_budget = true;
        i.sparse_topk = false;
        let r = report(&i);
        let policy = Policy::default();
        let j = r.to_json(&policy);
        assert_eq!(j["paths"]["sparse_topk"]["on"], false);
        assert_eq!(j["paths"]["sparse_topk"]["kind"], "mode");
        assert_eq!(j["paths"]["tc_attn_row_blocks"]["kind"], "missing");
        assert_eq!(j["paths"]["tc_prefill_attn"]["on"], true);
        assert_eq!(j["off"], 6);
        assert_eq!(j["unaccepted"], serde_json::json!(["tc_attn_row_blocks", "sparse_topk"]));
        let lines = r.log_lines(&policy);
        assert!(lines[0].contains("6 off, 2 off without an opt-out"), "{}", lines[0]);
        assert!(lines.iter().any(|l| l.contains("!! OFF  sparse_topk") && l.contains("--full-attn-budget")), "{lines:?}");
        assert!(lines.last().unwrap().contains("WARNING") && lines.last().unwrap().contains("sparse_topk"));
    }
}