fuel-ir 0.24.0

Core types and traits for the fuel ML framework
Documentation
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
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
// SPDX-License-Identifier: MIT OR Apache-2.0
//! FDX code-conversion functions — the **binding** that makes FDX the normative
//! owner of the shared dtype/quant/granularity/substrate/backend codes
//! (spec `docs/specs/dlpack-extension.md` §6.0, §6.1, §6.2, §6.6, Appendix B).
//!
//! Every *forward* conversion is an **exhaustive `match`** on the source enum
//! with **no wildcard arm** (and never `as` on the enum's discriminant). That is
//! the §6.0 "reorder breaks the build" guarantee: adding, removing, or reordering
//! a source variant fails to compile *here* rather than silently shifting the
//! stable FDX ABI. The source enums (`DType`, `GgmlDType`, `ScaleGranularity`,
//! `BackendId`, `SubstrateClass`) are explicitly allowed to evolve; the FDX codes
//! in [`super::codes`] are the fixed cross-tool contract, and these `match`-es +
//! the build-time mapping test below are what keep the two pinned together.
//!
//! `BackendId` / `SubstrateClass` are `#[non_exhaustive]`, but this module lives
//! **inside** the defining crate (`fuel-core-types`), so an exhaustive `match`
//! with no `_` arm is permitted — and is exactly what we want: a new variant must
//! break the build here so its FDX code is assigned deliberately (§6.0).
//!
//! Reverse conversions return `Option`: some FDX codes have no Fuel source
//! variant (e.g. the §6.1 microscaling/escape/reserved codes
//! `GENERIC_LOW_BIT_*`, `COMPLEX64`, `BOOL`), and an out-of-range integer is not
//! a valid code. `None` means "no corresponding Fuel value", never a panic (G6).

use super::abi::{DLDataType, dtype_code};
use super::codes::*;
use super::sidecar::{FDXAffine, FDXAffineTerm, FDXExtent};
use crate::backend::SubstrateClass;
use crate::dtype::DType;
use crate::probe::BackendId;
use crate::quant_scale::ScaleGranularity;
use crate::quantized::GgmlDType;
use crate::shape::Extent;
use crate::symbol::SymId;

// ─────────────────────────────────────────────────────────────────────────────
// DType ⇄ FDX logical-dtype code (§6.1)
// ─────────────────────────────────────────────────────────────────────────────

/// The FDX logical-dtype disposition of a Fuel [`DType`] in the SIDECAR namespace
/// (§6.1) — the value that fills `FDXDTypeExt.logical_dtype`, `FDXBufferRef.dtype`,
/// and the `FDXQuant` scale/zero-point dtype fields. Returned by [`dtype_to_fdx`].
///
/// Three outcomes are kept DISTINCT because they are three different facts, and
/// collapsing any two is a wire-level bug:
/// - [`Coded`](Self::Coded)`(u16)` — the dtype has an assigned `FDX_DTYPE_*` code.
/// - [`RidesBase`](Self::RidesBase)`(u16)` — the element type is faithfully named
///   by the **base** DLPack `DLDataType` (§6.1.1: `Bool`→`kDLBool`), so a plain
///   tensor needs **no `FDXDTypeExt` sidecar at all**. The payload is the reserved
///   namespace code (`FDX_DTYPE_BOOL`), written into a namespace field ONLY when a
///   sidecar already exists for some OTHER reason (multi-buffer / quant / residency
///   / symbolic); it is never emitted as a standalone `FDXDTypeExt`.
/// - a DECLINE is the `Err` arm of [`dtype_to_fdx`]: `F8E5M2` (code unassigned,
///   GAP-097) and `F8E6M2` (encoding unauthored, GAP-045), by [`Error`] message.
///
/// An `Option<u16>` return would conflate `RidesBase` (no code *needed*) with a
/// decline (no code *exists*); a bare `u16` cannot express `RidesBase` at all
/// without fabricating the very sidecar §6.1.1 forbids. This type answers a
/// caller's two independent questions separately: "does a plain tensor need a
/// sidecar?" (match the variant — `RidesBase` says no) and "what code fills a
/// namespace field if a sidecar exists anyway?" ([`namespace_code`](Self::namespace_code)).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FdxDtype {
    /// The dtype has an assigned `FDX_DTYPE_*` code (§6.1).
    Coded(u16),
    /// The dtype rides the base DLPack descriptor (§6.1.1) and needs no sidecar;
    /// the payload is the reserved namespace code for the sidecar-exists-anyway case.
    RidesBase(u16),
}

impl FdxDtype {
    /// The `u16` to write into a sidecar NAMESPACE field (`FDXBufferRef.dtype`,
    /// `FDXQuant` scale/zero-point, `FDXDTypeExt.logical_dtype`). Both variants
    /// carry one — `Coded` its assigned code, `RidesBase` its reserved §6.1.1
    /// placeholder — because a namespace field, once a sidecar exists, must be
    /// filled either way. This is NOT the decision of whether to emit a sidecar;
    /// that decision belongs to the variant, not to this code.
    pub fn namespace_code(self) -> u16 {
        match self {
            FdxDtype::Coded(c) | FdxDtype::RidesBase(c) => c,
        }
    }
}

/// Map a Fuel [`DType`] to its FDX logical-dtype disposition ([`FdxDtype`], §6.1).
///
/// **Exhaustive `match`, no wildcard** — adding/removing/reordering a `DType`
/// variant breaks this compile (the §6.0 guarantee). NEVER `d as u16`: the FDX
/// code is the stable contract, decoupled from the source discriminant.
///
/// # The three dispositions (why not a bare `u16`)
///
/// Most dtypes map to an assigned code — [`FdxDtype::Coded`]. Two others do not,
/// for two DIFFERENT reasons, and this function keeps all three apart:
///
/// **Rides the base ([`FdxDtype::RidesBase`]).** `Bool` is faithfully named by the
/// base DLPack descriptor (`kDLBool`, §6.1.1), so a plain `Bool` tensor emits no
/// `FDXDTypeExt` at all. It is NOT a decline (Bool is fully supported) and it must
/// NOT emit a standalone sidecar code — returning `Coded(0x0201)` would emit the
/// exact sidecar the spec says not to. `Complex64` (`0x0200`) is the twin row and
/// would land here identically; there is no `DType::Complex` today, so no arm
/// exists for it — the compile-time exhaustiveness check adds one the day it does.
///
/// **Declines (`Err`, GAP-059).** `F8E6M2` is token-only: Fuel can name and parse
/// it but its encoding is deliberately unauthored (GAP-045), so there is no
/// correct FDX code — every answer would be invented, and an FDX code is a stable
/// wire contract a foreign process reads as a real claim about the bytes.
/// `F8E5M2`'s encoding IS OCP-standard, but §6.1 has assigned it no code yet
/// (GAP-097); this module's rule is that a code is assigned deliberately, never
/// inferred from adjacency. Both decline; declining is sound whatever the encoding
/// turns out to be, whereas a fabricated code must be guessed right today and
/// migrated later. When either is authored, its arm becomes a `Coded` mapping and
/// the signature does not change again.
pub fn dtype_to_fdx(d: DType) -> crate::Result<FdxDtype> {
    Ok(match d {
        // GAP-097: E5M2's encoding is NOT unauthored — it is OCP-standard and
        // `float8::F8E5M2` exists. It declines for a different reason: the FDX
        // §6.1 table has no code ASSIGNED to it yet, and this module's own rule
        // is that a code is a stable wire contract assigned deliberately, never
        // inferred. A DELIBERATE UNDER-SHIPMENT pending that assignment — unlike
        // F8E6M2 below, where there is no encoding to assign a code *to*.
        DType::F8E5M2 => {
            return Err(crate::Error::UnsupportedDTypeForOp(
                DType::F8E5M2,
                "no FDX logical-dtype code has been assigned to F8E5M2 yet (GAP-097); declining rather than inferring one from adjacency",
            ));
        }
        // GAP-045: encoding unauthored — decline, never invent a wire code.
        DType::F8E6M2 => {
            return Err(crate::Error::UnsupportedDTypeForOp(
                DType::F8E6M2,
                "FDX logical-dtype encoding is not authored yet (GAP-045); \
                 declining rather than emitting an invented wire code",
            ));
        }
        // §6.1.1: Bool is faithfully named by the base descriptor (`kDLBool`), so a
        // plain tensor rides the base and emits NO `FDXDTypeExt`. This is neither a
        // code (`Coded`) nor a decline (`Err`) — it is the third disposition. The
        // payload is the reserved namespace code, written into a field ONLY when a
        // sidecar exists for another reason (never as a standalone sidecar).
        DType::Bool => FdxDtype::RidesBase(FDX_DTYPE_BOOL),
        DType::U8 => FdxDtype::Coded(FDX_DTYPE_U8),
        DType::I8 => FdxDtype::Coded(FDX_DTYPE_I8),
        DType::U32 => FdxDtype::Coded(FDX_DTYPE_U32),
        DType::I16 => FdxDtype::Coded(FDX_DTYPE_I16),
        DType::I32 => FdxDtype::Coded(FDX_DTYPE_I32),
        DType::I64 => FdxDtype::Coded(FDX_DTYPE_I64),
        DType::BF16 => FdxDtype::Coded(FDX_DTYPE_BF16),
        DType::F16 => FdxDtype::Coded(FDX_DTYPE_F16),
        DType::F32 => FdxDtype::Coded(FDX_DTYPE_F32),
        DType::F64 => FdxDtype::Coded(FDX_DTYPE_F64),
        DType::F8E4M3 => FdxDtype::Coded(FDX_DTYPE_F8E4M3),
        DType::F6E2M3 => FdxDtype::Coded(FDX_DTYPE_F6E2M3),
        DType::F6E3M2 => FdxDtype::Coded(FDX_DTYPE_F6E3M2),
        DType::F4 => FdxDtype::Coded(FDX_DTYPE_F4),
        DType::F8E8M0 => FdxDtype::Coded(FDX_DTYPE_F8E8M0),
    })
}

/// Map an FDX logical-dtype code back to a Fuel [`DType`].
///
/// `None` for codes that have no Fuel `DType` (the §6.1 escape/reserved codes
/// `GENERIC_LOW_BIT_*` / `COMPLEX64` / `BOOL`, the `NONE` sentinel, and any
/// out-of-range integer). All 15 real `DType` codes round-trip.
pub fn fdx_to_dtype(code: u16) -> Option<DType> {
    let d = match code {
        FDX_DTYPE_U8 => DType::U8,
        FDX_DTYPE_I8 => DType::I8,
        FDX_DTYPE_U32 => DType::U32,
        FDX_DTYPE_I16 => DType::I16,
        FDX_DTYPE_I32 => DType::I32,
        FDX_DTYPE_I64 => DType::I64,
        FDX_DTYPE_BF16 => DType::BF16,
        FDX_DTYPE_F16 => DType::F16,
        FDX_DTYPE_F32 => DType::F32,
        FDX_DTYPE_F64 => DType::F64,
        FDX_DTYPE_F8E4M3 => DType::F8E4M3,
        FDX_DTYPE_F6E2M3 => DType::F6E2M3,
        FDX_DTYPE_F6E3M2 => DType::F6E3M2,
        FDX_DTYPE_F4 => DType::F4,
        FDX_DTYPE_F8E8M0 => DType::F8E8M0,
        _ => return None,
    };
    Some(d)
}

// ─────────────────────────────────────────────────────────────────────────────
// DType → standard DLPack DLDataType (§5.1, §3) — the FAITHFUL {code,bits,lanes}
// ─────────────────────────────────────────────────────────────────────────────

/// Map a Fuel [`DType`] to its **faithful** standard-DLPack [`DLDataType`]
/// (`{code, bits, lanes}`, `dlpack.h` §5.1). This is the honest descriptor of
/// the *logical* element type — F32 → `{kDLFloat, 32, 1}`, BF16 →
/// `{kDLBfloat, 16, 1}`, U8 → `{kDLUInt, 8, 1}`, etc.
///
/// **Exhaustive `match`, no wildcard** — a new `DType` variant breaks this
/// compile (the §6.0 guarantee).
///
/// For the sub-byte dtypes whose `DType::size_in_bytes() == 0`
/// (`F4`/`F6E2M3`/`F6E3M2`) this returns a faithful *low-bit* descriptor
/// (`bits < 8`). The honesty invariant (§3, §3.4) requires the **base
/// `DLTensor`** to carry the `{kDLUInt, 8, 1}` stand-in for these — substituting
/// that stand-in is the *view's* job (it carries the true low-bit width in
/// `FDXDTypeExt`), NOT this function's: `dl_dtype` is the plain faithful map.
/// # Why this returns `Result` (GAP-059)
///
/// Same reason as [`dtype_to_fdx`], and if anything sharper here. A
/// `DLDataType` is `{code, bits, lanes}` — a **numeric claim about the element
/// width**. `F8E6M2`'s encoding is unauthored (GAP-045), so any `bits` value
/// emitted for it is a guess that a *consumer in another process* will use to
/// stride over memory. The failure mode is not a wrong answer in Fuel; it is a
/// foreign runtime reading the wrong bytes.
///
/// A guess would also be *plausible* — 8, by analogy with the other fp8s —
/// which is what makes it dangerous: it would look right in review and never
/// trip a test, because nothing here can distinguish "correct width" from
/// "width nobody has decided yet".
pub fn dl_dtype(d: DType) -> crate::Result<DLDataType> {
    use dtype_code::*;
    let (code, bits): (u8, u8) = match d {
        // GAP-097: E5M2 declines, and READ THE REASON BEFORE "FIXING" THIS BY
        // ANALOGY WITH F8E4M3 ABOVE — the obvious argument is backwards.
        //
        // E5M2's width is KNOWN and CORRECT (8 bits, OCP-standard), unlike
        // F8E6M2 below whose width is unauthored. That sounds like a reason to
        // emit. It is the reason NOT to, and the difference is the failure mode:
        //
        //   * F8E6M2 — width is a guess. A wrong width MIS-STRIDES the buffer,
        //     so the consumer desynchronises and the damage is LOUD and fails
        //     fast.
        //   * F8E5M2 — width is right, so `(K_DL_FLOAT, 8)` strides PERFECTLY.
        //     DLPack has no dedicated fp8 code, so E4M3 and E5M2 both render as
        //     `(float, 8)`, distinguished ONLY by the FDX logical code in the
        //     sidecar — which E5M2 has not been assigned (see `dtype_to_fdx`).
        //     A foreign consumer therefore reads it as the fp8 it already knows,
        //     E4M3. Every element lands in exactly the right place and decodes
        //     to the WRONG NUMBER — same bytes, different exponent bias.
        //
        // A correct stride carrying a wrong interpretation is SILENT numerical
        // corruption: no layout check, bounds check, or shape assertion can see
        // it. That is strictly worse than F8E6M2's loud mis-stride, so knowing
        // the width makes declining MORE important here, not less.
        //
        // Becomes a plain mapping the moment an FDX code is assigned to E5M2 —
        // the decline is waiting on that assignment, not on a design question.
        DType::F8E5M2 => {
            return Err(crate::Error::UnsupportedDTypeForOp(
                DType::F8E5M2,
                "F8E5M2 has no assigned FDX code, and DLPack's `(float, 8)` cannot distinguish it from F8E4M3; declining rather than exporting an fp8 a consumer would mis-read (GAP-097)",
            ));
        }
        // GAP-045: encoding unauthored — decline rather than assert a width.
        DType::F8E6M2 => {
            return Err(crate::Error::UnsupportedDTypeForOp(
                DType::F8E6M2,
                "DLPack element width is not authored yet (GAP-045); declining \
                 rather than asserting a bit-width a consumer would stride on",
            ));
        }
        // GAP-247. Spec-backed, NOT an analogy: FDX §6.1 assigns bool three
        // times over — `kDLBool = 6` in the `DLDataTypeCode` enum
        // (`dlpack-extension.md:724`), the mapping "bool → `kDLBool`" (`:1049`),
        // and the table row "`BOOL` … 8 bits … DLPack `kDLBool`" (`:1029`).
        //
        // Contrast the fp8 declines above, which exist precisely because no
        // authority had made the call. Here one had, and the arm was simply
        // never added when `Bool` shipped — `K_DL_BOOL` has been sitting in
        // `abi.rs:29` unused, because no gate builds `--features dlpack`.
        DType::Bool => (K_DL_BOOL, 8),
        DType::U8 => (K_DL_UINT, 8),
        DType::I8 => (K_DL_INT, 8),
        DType::U32 => (K_DL_UINT, 32),
        DType::I16 => (K_DL_INT, 16),
        DType::I32 => (K_DL_INT, 32),
        DType::I64 => (K_DL_INT, 64),
        DType::BF16 => (K_DL_BFLOAT, 16),
        DType::F16 => (K_DL_FLOAT, 16),
        DType::F32 => (K_DL_FLOAT, 32),
        DType::F64 => (K_DL_FLOAT, 64),
        // F8E4M3 / F8E8M0 are 8-bit floats; DLPack has no dedicated fp8 code, so
        // the faithful descriptor is a kDLFloat of 8 bits (the true bit-width).
        // The sidecar `FDXDTypeExt` carries the precise fp8 variant.
        DType::F8E4M3 => (K_DL_FLOAT, 8),
        DType::F8E8M0 => (K_DL_FLOAT, 8),
        // Sub-byte (size_in_bytes()==0): faithful low-bit float descriptors.
        DType::F6E2M3 => (K_DL_FLOAT, 6),
        DType::F6E3M2 => (K_DL_FLOAT, 6),
        DType::F4 => (K_DL_FLOAT, 4),
    };
    Ok(DLDataType {
        code,
        bits,
        lanes: 1,
    })
}

// ─────────────────────────────────────────────────────────────────────────────
// GgmlDType ⇄ FDX ggml_dtype code (§6.2)
// ─────────────────────────────────────────────────────────────────────────────

/// Map a [`GgmlDType`] to its FDX `ggml_dtype` code (`FDX_GGML_*`, §6.2).
///
/// **Exhaustive `match`, no wildcard** — a new `GgmlDType` variant breaks this
/// compile. The codes mirror `GgmlDType::to_u32` (the cross-tool ggml numbering:
/// `Q4_0=2`, `Q5_0=6`, `Q4K=12`, `Q8K=15`, `F16=1`, `BF16=30`), but are pinned
/// here by `match` to the FDX symbols, never read off `to_u32` positionally.
pub fn ggml_to_fdx(g: GgmlDType) -> u16 {
    match g {
        GgmlDType::F32 => FDX_GGML_F32,
        GgmlDType::F16 => FDX_GGML_F16,
        GgmlDType::BF16 => FDX_GGML_BF16,
        GgmlDType::Q4_0 => FDX_GGML_Q4_0,
        GgmlDType::Q4_1 => FDX_GGML_Q4_1,
        GgmlDType::Q5_0 => FDX_GGML_Q5_0,
        GgmlDType::Q5_1 => FDX_GGML_Q5_1,
        GgmlDType::Q8_0 => FDX_GGML_Q8_0,
        GgmlDType::Q8_1 => FDX_GGML_Q8_1,
        GgmlDType::Q2K => FDX_GGML_Q2K,
        GgmlDType::Q3K => FDX_GGML_Q3K,
        GgmlDType::Q4K => FDX_GGML_Q4K,
        GgmlDType::Q5K => FDX_GGML_Q5K,
        GgmlDType::Q6K => FDX_GGML_Q6K,
        GgmlDType::Q8K => FDX_GGML_Q8K,
        GgmlDType::Iq4Nl => FDX_GGML_IQ4_NL,
        GgmlDType::Iq4Xs => FDX_GGML_IQ4_XS,
        GgmlDType::Iq2Xxs => FDX_GGML_IQ2_XXS,
        GgmlDType::Iq2Xs => FDX_GGML_IQ2_XS,
        GgmlDType::Iq3Xxs => FDX_GGML_IQ3_XXS,
        GgmlDType::Iq1S => FDX_GGML_IQ1_S,
        GgmlDType::Iq3S => FDX_GGML_IQ3_S,
        GgmlDType::Iq2S => FDX_GGML_IQ2_S,
        GgmlDType::Iq1M => FDX_GGML_IQ1_M,
        GgmlDType::Tq1_0 => FDX_GGML_TQ1_0,
        GgmlDType::Tq2_0 => FDX_GGML_TQ2_0,
        GgmlDType::Mxfp4 => FDX_GGML_MXFP4,
        GgmlDType::Nvfp4 => FDX_GGML_NVFP4,
    }
}

/// Map an FDX `ggml_dtype` code back to a [`GgmlDType`].
///
/// `None` for `FDX_QUANT_NONE` (`0xFFFF`, the "not GGML" sentinel) and any code
/// outside the ggml numbering (e.g. the gaps at 4/5 in the ggml type space).
pub fn fdx_to_ggml(code: u16) -> Option<GgmlDType> {
    let g = match code {
        FDX_GGML_F32 => GgmlDType::F32,
        FDX_GGML_F16 => GgmlDType::F16,
        FDX_GGML_BF16 => GgmlDType::BF16,
        FDX_GGML_Q4_0 => GgmlDType::Q4_0,
        FDX_GGML_Q4_1 => GgmlDType::Q4_1,
        FDX_GGML_Q5_0 => GgmlDType::Q5_0,
        FDX_GGML_Q5_1 => GgmlDType::Q5_1,
        FDX_GGML_Q8_0 => GgmlDType::Q8_0,
        FDX_GGML_Q8_1 => GgmlDType::Q8_1,
        FDX_GGML_Q2K => GgmlDType::Q2K,
        FDX_GGML_Q3K => GgmlDType::Q3K,
        FDX_GGML_Q4K => GgmlDType::Q4K,
        FDX_GGML_Q5K => GgmlDType::Q5K,
        FDX_GGML_Q6K => GgmlDType::Q6K,
        FDX_GGML_Q8K => GgmlDType::Q8K,
        FDX_GGML_IQ4_NL => GgmlDType::Iq4Nl,
        FDX_GGML_IQ4_XS => GgmlDType::Iq4Xs,
        FDX_GGML_IQ2_XXS => GgmlDType::Iq2Xxs,
        FDX_GGML_IQ2_XS => GgmlDType::Iq2Xs,
        FDX_GGML_IQ3_XXS => GgmlDType::Iq3Xxs,
        FDX_GGML_IQ1_S => GgmlDType::Iq1S,
        FDX_GGML_IQ3_S => GgmlDType::Iq3S,
        FDX_GGML_IQ2_S => GgmlDType::Iq2S,
        FDX_GGML_IQ1_M => GgmlDType::Iq1M,
        FDX_GGML_TQ1_0 => GgmlDType::Tq1_0,
        FDX_GGML_TQ2_0 => GgmlDType::Tq2_0,
        FDX_GGML_MXFP4 => GgmlDType::Mxfp4,
        FDX_GGML_NVFP4 => GgmlDType::Nvfp4,
        _ => return None,
    };
    Some(g)
}

// ─────────────────────────────────────────────────────────────────────────────
// ScaleGranularity ⇄ FDX scale-granularity code (§6.2)
// ─────────────────────────────────────────────────────────────────────────────

/// Map a [`ScaleGranularity`] to its FDX code (`FDX_SCALE_GRAN_*`, §6.2).
///
/// **Exhaustive `match`, no wildcard** — a new `ScaleGranularity` variant breaks
/// this compile. Note FDX additionally owns `PerBlock` (code 3), which has **no**
/// `ScaleGranularity` source variant (it is MX-family-only block grain, §6.2);
/// that code is therefore only producible from FDX-side construction, and
/// [`fdx_to_scale_granularity`] returns `None` for it.
pub fn scale_granularity_to_fdx(g: ScaleGranularity) -> u8 {
    match g {
        ScaleGranularity::PerTensor => FDX_SCALE_GRAN_PER_TENSOR,
        ScaleGranularity::PerToken => FDX_SCALE_GRAN_PER_TOKEN,
        ScaleGranularity::PerChannel => FDX_SCALE_GRAN_PER_CHANNEL,
    }
}

/// Map an FDX scale-granularity code back to a [`ScaleGranularity`].
///
/// `None` for `FDX_SCALE_GRAN_PER_BLOCK` (MX-only, no Fuel variant — §6.2) and
/// any out-of-range value.
pub fn fdx_to_scale_granularity(code: u8) -> Option<ScaleGranularity> {
    let g = match code {
        FDX_SCALE_GRAN_PER_TENSOR => ScaleGranularity::PerTensor,
        FDX_SCALE_GRAN_PER_TOKEN => ScaleGranularity::PerToken,
        FDX_SCALE_GRAN_PER_CHANNEL => ScaleGranularity::PerChannel,
        // FDX_SCALE_GRAN_PER_BLOCK is MX-only with no ScaleGranularity variant.
        _ => return None,
    };
    Some(g)
}

// ─────────────────────────────────────────────────────────────────────────────
// BackendId ⇄ FDX backend code (§6.0 / §6.6)
// ─────────────────────────────────────────────────────────────────────────────

/// Map a [`BackendId`] to its FDX backend code (`FDX_BACKEND_*`, §6.6).
///
/// **Exhaustive `match`, no wildcard** — even though `BackendId` is
/// `#[non_exhaustive]`, we are inside the defining crate, so this is allowed and
/// REQUIRED: a new backend variant must break this compile so its FDX code is
/// assigned in the §6.6 table deliberately (`Aocl`/`Mkl` were already retired,
/// which is exactly the kind of change this `match` is meant to surface).
pub fn backend_to_fdx(b: BackendId) -> u8 {
    match b {
        BackendId::Cpu => FDX_BACKEND_CPU,
        BackendId::Cuda => FDX_BACKEND_CUDA,
        BackendId::Vulkan => FDX_BACKEND_VULKAN,
        BackendId::Metal => FDX_BACKEND_METAL,
    }
}

/// Map an FDX backend code back to a [`BackendId`]. `None` if out of range.
pub fn fdx_to_backend(code: u8) -> Option<BackendId> {
    let b = match code {
        FDX_BACKEND_CPU => BackendId::Cpu,
        FDX_BACKEND_CUDA => BackendId::Cuda,
        FDX_BACKEND_VULKAN => BackendId::Vulkan,
        FDX_BACKEND_METAL => BackendId::Metal,
        _ => return None,
    };
    Some(b)
}

// ─────────────────────────────────────────────────────────────────────────────
// SubstrateClass ⇄ FDX substrate code (§6.0 / §6.6)
// ─────────────────────────────────────────────────────────────────────────────

/// Map a [`SubstrateClass`] to its FDX substrate code (`FDX_SUBSTRATE_*`, §6.6).
///
/// **Exhaustive `match`, no wildcard** — `SubstrateClass` is `#[non_exhaustive]`
/// but we are inside the defining crate, so the exhaustive `match` is allowed and
/// REQUIRED: a new substrate variant breaks this compile so its FDX code is
/// assigned deliberately. `substrate` + `backend_id` + `device_index` reproduce
/// Fuel's `shares_storage` aliasing predicate across the boundary (§6.6).
pub fn substrate_to_fdx(s: SubstrateClass) -> u8 {
    match s {
        SubstrateClass::HostBytes => FDX_SUBSTRATE_HOST_BYTES,
        SubstrateClass::CudaUntyped => FDX_SUBSTRATE_CUDA_UNTYPED,
        SubstrateClass::VulkanBuffer => FDX_SUBSTRATE_VULKAN_BUFFER,
        SubstrateClass::MetalBuffer => FDX_SUBSTRATE_METAL_BUFFER,
    }
}

/// Map an FDX substrate code back to a [`SubstrateClass`]. `None` if out of range.
pub fn fdx_to_substrate(code: u8) -> Option<SubstrateClass> {
    let s = match code {
        FDX_SUBSTRATE_HOST_BYTES => SubstrateClass::HostBytes,
        FDX_SUBSTRATE_CUDA_UNTYPED => SubstrateClass::CudaUntyped,
        FDX_SUBSTRATE_VULKAN_BUFFER => SubstrateClass::VulkanBuffer,
        FDX_SUBSTRATE_METAL_BUFFER => SubstrateClass::MetalBuffer,
        _ => return None,
    };
    Some(s)
}

// ─────────────────────────────────────────────────────────────────────────────
// Extent ⇄ FDXExtent (Appendix B)
// ─────────────────────────────────────────────────────────────────────────────

/// Map a Fuel [`Extent`] to an [`FDXExtent`] (Appendix B).
///
/// **Exhaustive `match`, no wildcard** — a new `Extent` variant breaks this
/// compile. Only the two Fuel `Extent` variants are producible here:
///
/// - [`Extent::Scalar`]`(v)` → `kind = 0` (Scalar), `min == capacity == v`,
///   `sym_id = FDX_SYM_NONE`.
/// - [`Extent::Range`]`{min, max, sym}` → `kind = 1` (Range), `capacity = max`
///   (what `dims()` reports / strides key to — P4), `sym_id = sym`.
///
/// The third FDX extent kind, `AFFINE` (`kind = 2`, §6.4.2), has **no** Fuel
/// `Extent` source variant — it is produced directly from a symbolic-affine
/// combination, not from this enum — so it is never emitted here and
/// [`fdx_to_extent`] returns `None` for it.
///
/// The `affine`/`cap_kind` sub-block is zeroed (the Scalar/Range-degenerate form
/// required by validator V7), and `sym_scope` is left `0` (`InputDetermined`,
/// the advisory default).
pub fn extent_to_fdx(e: Extent) -> FDXExtent {
    let zero_affine = FDXAffine {
        c0: 0,
        term_count: 0,
        _pad: [0; 7],
        terms: [FDXAffineTerm {
            coeff: 0,
            sym_id: FDX_SYM_NONE,
            _pad: 0,
        }; FDX_AFFINE_MAX_TERMS],
    };
    let (kind, min, capacity, sym_id) = match e {
        Extent::Scalar(v) => (FDX_EXTENT_SCALAR as u8, v as u64, v as u64, FDX_SYM_NONE),
        Extent::Range { min, max, sym } => (FDX_EXTENT_RANGE as u8, min as u64, max as u64, sym.0),
    };
    FDXExtent {
        kind,
        _pad: [0; 3],
        min,
        capacity,
        sym_id,
        sym_scope: 0,
        _pad2: [0; 3],
        cap_kind: FDX_CAP_KIND_EXPLICIT as u8,
        _pad3: [0; 3],
        _pad4: 0,
        affine: zero_affine,
        reserved: [0; 2],
    }
}

/// Map an [`FDXExtent`] back to a Fuel [`Extent`].
///
/// `None` for `kind = AFFINE` (no Fuel `Extent` variant — §6.4.2) and any
/// unknown `kind` byte. Scalar/Range round-trip (a `usize` narrowing of `u64`
/// is performed; the realize-time u64↔usize OOB guard is the validators' job,
/// §6.4 / V14 — this fn is the plain code/field mapping).
pub fn fdx_to_extent(x: &FDXExtent) -> Option<Extent> {
    match x.kind as u16 {
        FDX_EXTENT_SCALAR => Some(Extent::Scalar(x.capacity as usize)),
        FDX_EXTENT_RANGE => Some(Extent::Range {
            min: x.min as usize,
            max: x.capacity as usize,
            sym: SymId(x.sym_id),
        }),
        // FDX_EXTENT_AFFINE has no Fuel `Extent` variant; unknown kinds → None.
        _ => None,
    }
}

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

    // ── DType ─────────────────────────────────────────────────────────────

    #[test]
    fn dtype_roundtrips_for_every_variant() {
        // Population is `DType::ALL` (GAP-248: reminded-complete, measured 18 at
        // head), not a hand-list that silently goes stale — the dead `F8E6M2`
        // branch this test once carried is now LIVE. Each variant is asserted at
        // its OWN disposition; a skip would let a decline start passing as an
        // invented code (GAP-059), the exact failure guarded here.
        for &d in DType::ALL {
            match d {
                // GAP-045/097: no authored/assigned FDX code — must DECLINE, never
                // round-trip through an invented one.
                DType::F8E5M2 | DType::F8E6M2 => assert!(
                    dtype_to_fdx(d).is_err(),
                    "{d:?} must decline until its FDX code is authored, never round-trip through an invented code"
                ),
                // §6.1.1: Bool rides the base — `RidesBase`, no `fdx_to_dtype`
                // round-trip (0x0201 is a reserved placeholder the base speaks for).
                DType::Bool => assert!(
                    matches!(dtype_to_fdx(d), Ok(FdxDtype::RidesBase(_))),
                    "Bool must ride the base as RidesBase, not a coded round-trip"
                ),
                // Every other variant has an assigned code that round-trips. A new
                // variant lands here by default; if it is actually a decline or
                // rides-base, this arm fails loudly (expect/round-trip), forcing it
                // into an arm above.
                _ => {
                    let code = dtype_to_fdx(d)
                        .expect("every coded dtype encodes")
                        .namespace_code();
                    assert_eq!(
                        fdx_to_dtype(code),
                        Some(d),
                        "DType {d:?} (code {code}) must round-trip"
                    );
                }
            }
        }
    }

    #[test]
    fn dtype_anchor_codes_match_spec_6_1() {
        // Anchors pinned against the §6.1 logical-dtype table. `.namespace_code()`
        // is the u16 the field carries; these are all `Coded`, so it equals the
        // assigned code (the born-red below covers the `RidesBase`/decline splits).
        assert_eq!(
            dtype_to_fdx(DType::U8).unwrap().namespace_code(),
            FDX_DTYPE_U8
        );
        assert_eq!(dtype_to_fdx(DType::U8).unwrap().namespace_code(), 0);
        assert_eq!(dtype_to_fdx(DType::I8).unwrap().namespace_code(), 1);
        assert_eq!(
            dtype_to_fdx(DType::F32).unwrap().namespace_code(),
            FDX_DTYPE_F32
        );
        assert_eq!(dtype_to_fdx(DType::F32).unwrap().namespace_code(), 8);
        assert_eq!(dtype_to_fdx(DType::F64).unwrap().namespace_code(), 9);
        // The sub-byte / microscaling ones the spec calls out explicitly.
        assert_eq!(dtype_to_fdx(DType::F8E4M3).unwrap().namespace_code(), 10);
        assert_eq!(dtype_to_fdx(DType::F6E2M3).unwrap().namespace_code(), 11);
        assert_eq!(dtype_to_fdx(DType::F6E3M2).unwrap().namespace_code(), 12);
        assert_eq!(dtype_to_fdx(DType::F4).unwrap().namespace_code(), 13);
        assert_eq!(dtype_to_fdx(DType::F8E8M0).unwrap().namespace_code(), 14);
    }

    #[test]
    fn bool_rides_the_base_as_a_third_disposition_distinct_from_a_decline() {
        // §6.1.1: `Bool` is faithfully named by the base DLPack descriptor
        // (`kDLBool`), so it needs NO FDX sidecar code. That is a THIRD outcome —
        // neither "has a code" nor "declined" — and it must be observable in the
        // RETURN, not merely asserted in a comment. This test discriminates all
        // three, so a Bool implemented as a decline (the conflating fabrication)
        // or as `Coded(0x0201)` (emitting the sidecar §6.1.1 forbids) fails it.

        // (1) Bool is SUPPORTED — not a decline. Fails if `Bool => Err`.
        let bool_result = dtype_to_fdx(DType::Bool);
        assert!(
            bool_result.is_ok(),
            "Bool rides the base and must not decline; got {bool_result:?}"
        );
        let bool_disp = bool_result.expect("asserted Ok directly above"); // FdxDtype: Copy

        // (2) Bool is `RidesBase`, never `Coded` — so it can never be emitted as a
        //     standalone sidecar code (the reserved 0x0201 included). Fails if
        //     `Bool => Coded(_)` for ANY code, 0x0201 included.
        assert_eq!(
            bool_disp,
            FdxDtype::RidesBase(FDX_DTYPE_BOOL),
            "Bool must be RidesBase(0x0201) — a Coded value is a wire claim the base already makes"
        );
        assert_eq!(
            FDX_DTYPE_BOOL, 0x0201,
            "the reserved BOOL namespace code is 0x0201 (§6.1)"
        );
        assert!(
            !matches!(bool_disp, FdxDtype::Coded(_)),
            "Bool must never be Coded — a plain Bool tensor emits no standalone FDXDTypeExt"
        );

        // (3) The three dispositions are pairwise distinct IN THE RETURN. An
        //     `Option<u16>` would collapse `RidesBase` and the F8E5M2 decline to
        //     `None`; here Bool is `Ok(RidesBase)`, F8E5M2 is `Err`, F32 is
        //     `Ok(Coded)` — three shapes.
        assert!(
            matches!(dtype_to_fdx(DType::F32), Ok(FdxDtype::Coded(_))),
            "a normal dtype is Coded — distinct from RidesBase and from a decline"
        );
        assert!(
            dtype_to_fdx(DType::F8E5M2).is_err(),
            "F8E5M2's code is unassigned (GAP-097) — a decline, distinct from Bool's RidesBase"
        );

        // The namespace code Bool writes into a field (only when a sidecar exists
        // for another reason) IS 0x0201 — same u16 a `Coded` would carry, but the
        // variant, not the code, is what says "no standalone sidecar".
        assert_eq!(dtype_to_fdx(DType::Bool).unwrap().namespace_code(), 0x0201);
    }

    #[test]
    fn dl_dtype_faithful_descriptors() {
        use dtype_code::*;
        // Standard faithful dtypes — {code, bits, lanes}.
        assert_eq!(
            dl_dtype(DType::F32).unwrap(),
            DLDataType {
                code: K_DL_FLOAT,
                bits: 32,
                lanes: 1
            }
        );
        assert_eq!(
            dl_dtype(DType::F16).unwrap(),
            DLDataType {
                code: K_DL_FLOAT,
                bits: 16,
                lanes: 1
            }
        );
        assert_eq!(
            dl_dtype(DType::BF16).unwrap(),
            DLDataType {
                code: K_DL_BFLOAT,
                bits: 16,
                lanes: 1
            }
        );
        assert_eq!(
            dl_dtype(DType::F64).unwrap(),
            DLDataType {
                code: K_DL_FLOAT,
                bits: 64,
                lanes: 1
            }
        );
        assert_eq!(
            dl_dtype(DType::I32).unwrap(),
            DLDataType {
                code: K_DL_INT,
                bits: 32,
                lanes: 1
            }
        );
        assert_eq!(
            dl_dtype(DType::I64).unwrap(),
            DLDataType {
                code: K_DL_INT,
                bits: 64,
                lanes: 1
            }
        );
        assert_eq!(
            dl_dtype(DType::U8).unwrap(),
            DLDataType {
                code: K_DL_UINT,
                bits: 8,
                lanes: 1
            }
        );
        assert_eq!(
            dl_dtype(DType::U32).unwrap(),
            DLDataType {
                code: K_DL_UINT,
                bits: 32,
                lanes: 1
            }
        );
        assert_eq!(
            dl_dtype(DType::I8).unwrap(),
            DLDataType {
                code: K_DL_INT,
                bits: 8,
                lanes: 1
            }
        );
        assert_eq!(
            dl_dtype(DType::I16).unwrap(),
            DLDataType {
                code: K_DL_INT,
                bits: 16,
                lanes: 1
            }
        );
        // Sub-byte ones get a faithful low-bit width (< 8); the VIEW substitutes
        // the {kDLUInt,8,1} honesty stand-in for these, not dl_dtype itself.
        assert_eq!(dl_dtype(DType::F4).unwrap().bits, 4);
        assert_eq!(dl_dtype(DType::F6E2M3).unwrap().bits, 6);
        assert_eq!(dl_dtype(DType::F6E3M2).unwrap().bits, 6);
        assert_eq!(dl_dtype(DType::F8E4M3).unwrap().bits, 8);
        assert_eq!(dl_dtype(DType::F8E8M0).unwrap().bits, 8);
        // Lanes always 1 for scalar dtypes.
        for &d in DType::ALL {
            match d {
                // F8E5M2 (GAP-097) and F8E6M2 (GAP-045) decline a base width —
                // asserted, not skipped: a skip starts passing silently if a
                // decline is ever replaced by a fabricated width.
                DType::F8E5M2 | DType::F8E6M2 => assert!(
                    dl_dtype(d).is_err(),
                    "{d:?} must decline a base width, not assert one"
                ),
                // Every other variant (Bool included) has a faithful scalar
                // descriptor with lanes = 1.
                _ => assert_eq!(
                    dl_dtype(d).unwrap().lanes,
                    1,
                    "DType {d:?} must be scalar (lanes=1)"
                ),
            }
        }
    }

    #[test]
    fn dtype_codes_have_no_duplicates() {
        // GAP-059: only dtypes with an AUTHORED encoding have a code to collide.
        // F8E5M2/F8E6M2 decline (GAP-097/045); `flatten()` drops them. Bool
        // contributes its reserved RidesBase code (0x0201), distinct from the
        // 0..=14 assigned codes. The count is taken from what was collected, so the
        // assertion stays exact rather than comparing against a hand-list length.
        let mut codes: Vec<u16> = DType::ALL
            .iter()
            .copied()
            .flat_map(dtype_to_fdx)
            .map(FdxDtype::namespace_code)
            .collect();
        let n = codes.len();
        codes.sort_unstable();
        codes.dedup();
        assert_eq!(
            codes.len(),
            n,
            "FDX_DTYPE_* set must have no duplicate codes"
        );
    }

    #[test]
    fn fdx_to_dtype_rejects_escape_and_reserved_codes() {
        // §6.1 escape/reserved codes have no Fuel DType.
        assert_eq!(fdx_to_dtype(0x0100), None); // GENERIC_LOW_BIT_INT
        assert_eq!(fdx_to_dtype(0x0101), None); // GENERIC_LOW_BIT_FLOAT
        assert_eq!(fdx_to_dtype(FDX_DTYPE_I4), None); // packed S4 — sidecar-only, no Fuel DType
        assert_eq!(fdx_to_dtype(FDX_DTYPE_U4), None); // packed U4 — sidecar-only
        assert_eq!(fdx_to_dtype(FDX_DTYPE_B1), None); // bitpacked Bin — sidecar-only
        assert_eq!(fdx_to_dtype(0x0200), None); // COMPLEX64 (reserved)
        assert_eq!(fdx_to_dtype(0x0201), None); // BOOL (reserved)
        assert_eq!(fdx_to_dtype(FDX_DTYPE_NONE), None); // 0xFFFF NONE
        assert_eq!(fdx_to_dtype(15), None); // first unused contiguous code
    }

    // ── GgmlDType ─────────────────────────────────────────────────────────

    const ALL_GGML: [GgmlDType; 28] = [
        GgmlDType::F32,
        GgmlDType::F16,
        GgmlDType::BF16,
        GgmlDType::Q4_0,
        GgmlDType::Q4_1,
        GgmlDType::Q5_0,
        GgmlDType::Q5_1,
        GgmlDType::Q8_0,
        GgmlDType::Q8_1,
        GgmlDType::Q2K,
        GgmlDType::Q3K,
        GgmlDType::Q4K,
        GgmlDType::Q5K,
        GgmlDType::Q6K,
        GgmlDType::Q8K,
        GgmlDType::Iq4Nl,
        GgmlDType::Iq4Xs,
        GgmlDType::Iq2Xxs,
        GgmlDType::Iq2Xs,
        GgmlDType::Iq3Xxs,
        GgmlDType::Iq1S,
        GgmlDType::Iq3S,
        GgmlDType::Iq2S,
        GgmlDType::Iq1M,
        GgmlDType::Tq1_0,
        GgmlDType::Tq2_0,
        GgmlDType::Mxfp4,
        GgmlDType::Nvfp4,
    ];

    #[test]
    fn ggml_roundtrips_for_every_variant() {
        for g in ALL_GGML {
            let code = ggml_to_fdx(g);
            assert_eq!(
                fdx_to_ggml(code),
                Some(g),
                "GgmlDType {g:?} (code {code}) must round-trip"
            );
        }
    }

    #[test]
    fn ggml_codes_match_source_numbering_and_anchors() {
        // FDX ggml codes mirror GgmlDType::to_u32 (the cross-tool numbering).
        for g in ALL_GGML {
            assert_eq!(
                ggml_to_fdx(g) as u32,
                g.to_u32(),
                "FDX ggml code must equal GgmlDType::to_u32 for {g:?}"
            );
        }
        // The §6.2-named anchors.
        assert_eq!(ggml_to_fdx(GgmlDType::Q4K), FDX_GGML_Q4K);
        assert_eq!(ggml_to_fdx(GgmlDType::Q4K), 12);
        assert_eq!(ggml_to_fdx(GgmlDType::Q4_0), 2);
        assert_eq!(ggml_to_fdx(GgmlDType::Q5_0), 6);
        assert_eq!(ggml_to_fdx(GgmlDType::Q8K), 15);
        assert_eq!(ggml_to_fdx(GgmlDType::Iq4Nl), 20);
        assert_eq!(ggml_to_fdx(GgmlDType::Iq4Xs), 23);
        assert_eq!(ggml_to_fdx(GgmlDType::Iq2Xxs), 16);
        assert_eq!(ggml_to_fdx(GgmlDType::Iq2Xs), 17);
        assert_eq!(ggml_to_fdx(GgmlDType::Iq3Xxs), 18);
        assert_eq!(ggml_to_fdx(GgmlDType::Iq1S), 19);
        assert_eq!(ggml_to_fdx(GgmlDType::Iq3S), 21);
        assert_eq!(ggml_to_fdx(GgmlDType::Iq2S), 22);
        assert_eq!(ggml_to_fdx(GgmlDType::Iq1M), 29);
        assert_eq!(ggml_to_fdx(GgmlDType::Tq1_0), 34);
        assert_eq!(ggml_to_fdx(GgmlDType::Tq2_0), 35);
        assert_eq!(ggml_to_fdx(GgmlDType::Mxfp4), 39);
        assert_eq!(ggml_to_fdx(GgmlDType::Nvfp4), 40);
        assert_eq!(ggml_to_fdx(GgmlDType::F16), 1);
        assert_eq!(ggml_to_fdx(GgmlDType::BF16), 30);
    }

    #[test]
    fn fdx_to_ggml_rejects_gaps_and_none() {
        assert_eq!(fdx_to_ggml(FDX_QUANT_NONE), None); // 0xFFFF
        assert_eq!(fdx_to_ggml(4), None); // gap in ggml numbering
        assert_eq!(fdx_to_ggml(5), None); // gap in ggml numbering
        assert_eq!(fdx_to_ggml(24), None); // I8: not a Fuel GgmlDType
        assert_eq!(fdx_to_ggml(41), None); // Q1_0: not a Fuel GgmlDType
    }

    // ── ScaleGranularity ──────────────────────────────────────────────────

    const ALL_GRAN: [ScaleGranularity; 3] = [
        ScaleGranularity::PerTensor,
        ScaleGranularity::PerToken,
        ScaleGranularity::PerChannel,
    ];

    #[test]
    fn scale_granularity_roundtrips_for_every_variant() {
        for g in ALL_GRAN {
            let code = scale_granularity_to_fdx(g);
            assert_eq!(
                fdx_to_scale_granularity(code),
                Some(g),
                "gran {g:?} round-trip"
            );
        }
        assert_eq!(scale_granularity_to_fdx(ScaleGranularity::PerTensor), 0);
        assert_eq!(scale_granularity_to_fdx(ScaleGranularity::PerToken), 1);
        assert_eq!(scale_granularity_to_fdx(ScaleGranularity::PerChannel), 2);
    }

    #[test]
    fn per_block_granularity_has_no_fuel_variant() {
        // §6.2: PerBlock (code 3) is MX-only — no ScaleGranularity source.
        assert_eq!(fdx_to_scale_granularity(FDX_SCALE_GRAN_PER_BLOCK), None);
        assert_eq!(fdx_to_scale_granularity(4), None);
    }

    // ── BackendId ─────────────────────────────────────────────────────────

    const ALL_BACKENDS: [BackendId; 4] = [
        BackendId::Cpu,
        BackendId::Cuda,
        BackendId::Vulkan,
        BackendId::Metal,
    ];

    #[test]
    fn backend_roundtrips_for_every_variant() {
        for b in ALL_BACKENDS {
            let code = backend_to_fdx(b);
            assert_eq!(fdx_to_backend(code), Some(b), "backend {b:?} round-trip");
        }
        assert_eq!(backend_to_fdx(BackendId::Cpu), 0);
        assert_eq!(backend_to_fdx(BackendId::Cuda), 1);
        assert_eq!(backend_to_fdx(BackendId::Vulkan), 2);
        assert_eq!(backend_to_fdx(BackendId::Metal), 3);
        assert_eq!(fdx_to_backend(4), None);
    }

    // ── SubstrateClass ────────────────────────────────────────────────────

    const ALL_SUBSTRATES: [SubstrateClass; 4] = [
        SubstrateClass::HostBytes,
        SubstrateClass::CudaUntyped,
        SubstrateClass::VulkanBuffer,
        SubstrateClass::MetalBuffer,
    ];

    #[test]
    fn substrate_roundtrips_for_every_variant() {
        for s in ALL_SUBSTRATES {
            let code = substrate_to_fdx(s);
            assert_eq!(
                fdx_to_substrate(code),
                Some(s),
                "substrate {s:?} round-trip"
            );
        }
        assert_eq!(substrate_to_fdx(SubstrateClass::HostBytes), 0);
        assert_eq!(substrate_to_fdx(SubstrateClass::CudaUntyped), 1);
        assert_eq!(substrate_to_fdx(SubstrateClass::VulkanBuffer), 2);
        assert_eq!(substrate_to_fdx(SubstrateClass::MetalBuffer), 3);
        assert_eq!(fdx_to_substrate(4), None);
    }

    // ── Extent ────────────────────────────────────────────────────────────

    #[test]
    fn extent_scalar_roundtrips() {
        let e = Extent::Scalar(4096);
        let x = extent_to_fdx(e);
        assert_eq!(x.kind as u16, FDX_EXTENT_SCALAR);
        assert_eq!(x.capacity, 4096);
        assert_eq!(x.min, 4096);
        assert_eq!(x.sym_id, FDX_SYM_NONE);
        assert_eq!(x.affine.term_count, 0);
        assert_eq!(fdx_to_extent(&x), Some(e));
    }

    #[test]
    fn extent_range_roundtrips() {
        let e = Extent::Range {
            min: 1,
            max: 8192,
            sym: SymId(7),
        };
        let x = extent_to_fdx(e);
        assert_eq!(x.kind as u16, FDX_EXTENT_RANGE);
        assert_eq!(x.min, 1);
        assert_eq!(x.capacity, 8192); // capacity == max (P4); strides key to it
        assert_eq!(x.sym_id, 7);
        assert_eq!(fdx_to_extent(&x), Some(e));
    }

    #[test]
    fn affine_extent_has_no_fuel_variant() {
        // §6.4.2: AFFINE has no Fuel `Extent` source; reverse → None.
        let mut x = extent_to_fdx(Extent::Scalar(1));
        x.kind = FDX_EXTENT_AFFINE as u8;
        assert_eq!(fdx_to_extent(&x), None);
        // Unknown kind byte → None (no panic).
        x.kind = 99;
        assert_eq!(fdx_to_extent(&x), None);
    }

    // ── "mapping is total" (value correctness over every variant) ─────────

    #[test]
    fn every_source_variant_maps_to_a_distinct_real_code() {
        // DType: every dtype with an assigned §6.1 code maps to a distinct non-NONE
        // code THAT ROUND-TRIPS. GAP-097/045: F8E5M2/F8E6M2 decline and contribute
        // no code. §6.1.1: Bool is `RidesBase` — its reserved 0x0201 is deliberately
        // NOT a round-trippable code (the base speaks for it), so this "maps to a
        // real code" claim is about `Coded` variants only; filter to them.
        let dt: Vec<u16> = DType::ALL
            .iter()
            .copied()
            .filter_map(|d| match dtype_to_fdx(d) {
                Ok(FdxDtype::Coded(c)) => Some(c),
                _ => None,
            })
            .collect();
        for &c in &dt {
            assert_ne!(c, FDX_DTYPE_NONE);
            assert!(fdx_to_dtype(c).is_some());
        }
        assert_eq!(
            {
                let mut v = dt.clone();
                v.sort_unstable();
                v.dedup();
                v.len()
            },
            dt.len()
        );

        // GgmlDType: 15 variants → 15 distinct codes, none == NONE sentinel.
        let gg: Vec<u16> = ALL_GGML.iter().copied().map(ggml_to_fdx).collect();
        for &c in &gg {
            assert_ne!(c, FDX_QUANT_NONE);
            assert!(fdx_to_ggml(c).is_some());
        }
        assert_eq!(
            {
                let mut v = gg.clone();
                v.sort_unstable();
                v.dedup();
                v.len()
            },
            gg.len()
        );

        // ScaleGranularity / BackendId / SubstrateClass: total + distinct.
        let gr: Vec<u8> = ALL_GRAN
            .iter()
            .copied()
            .map(scale_granularity_to_fdx)
            .collect();
        assert!(gr.iter().all(|&c| fdx_to_scale_granularity(c).is_some()));
        let bk: Vec<u8> = ALL_BACKENDS.iter().copied().map(backend_to_fdx).collect();
        assert!(bk.iter().all(|&c| fdx_to_backend(c).is_some()));
        let su: Vec<u8> = ALL_SUBSTRATES
            .iter()
            .copied()
            .map(substrate_to_fdx)
            .collect();
        assert!(su.iter().all(|&c| fdx_to_substrate(c).is_some()));
    }
}