trueno_quant/ggml_type.rs
1//! ONE ggml tensor-type enum, and ONE table of what each type weighs.
2//!
3//! # Why this module exists (PMAT-3430, PP-QUANT-001 M1)
4//!
5//! aprender named ggml tensor types in three independent enums — serve's
6//! `GgmlQuantType` (16 ids), core's `GgmlType` (12), compute's `GgmlType` (15)
7//! — plus a fourth private label table, against 35 live ids upstream. They
8//! disagreed about which ids exist, about spelling, and about SIZES. Nothing
9//! compared any of them to upstream, so `NVFP4` (40), `Q1_0` (41) and `Q2_0`
10//! (42) appeared upstream with no signal here at all.
11//!
12//! # The oracle is upstream, by reference
13//!
14//! Operator ruling 2026-09-20, clauses 2' and 3: upstream ggml at
15//! `scripts/llama_pin.toml` `build_commit` is the reference; in-tree values are
16//! the defendant. Every number in [`TRAITS`] is extracted from ggml's own
17//! compiled `type_traits` table by `scripts/extract_ggml_traits.sh` into
18//! `fixtures/ggml_traits.json`, and `tests/ggml_traits_fixture.rs` fails if a
19//! single row here stops matching that fixture. The fixture records the sha it
20//! was read from; a repo-level invariant (`monorepo_invariants.rs`) fails if
21//! that sha stops being the pin — so bumping the comparator turns this RED in
22//! the bump's own PR rather than silently later (clause 2a, generalised by
23//! #3563).
24//!
25//! # What this module is NOT
26//!
27//! It is not an admission policy. [`GgmlType::from_id`] knows all 35 live ids;
28//! whether a given crate should ACCEPT a given id at a parse boundary is that
29//! crate's decision, and M1 preserves each one exactly as it was (#3430 Q1-c).
30//! It also carries no dequantiser: knowing that `IQ3_S` is 110 bytes per 256
31//! elements is not the same as being able to read one.
32
33use core::fmt;
34
35/// How a type stores its numbers.
36///
37/// This is aprender's classification, not upstream's: ggml's table has no
38/// family column, only an `is_quantized` flag. The link back to upstream that
39/// CAN fail is exactly that flag — [`GgmlFamily::Float`] and [`GgmlFamily::Int`]
40/// are the non-quantized families, every other live family is quantized, and
41/// `tests/ggml_traits_fixture.rs` checks that against the fixture.
42#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
43pub enum GgmlFamily {
44 /// IEEE / bfloat floats stored one per "block": `F32`, `F16`, `F64`, `BF16`.
45 Float,
46 /// Plain integers, one per "block": `I8`, `I16`, `I32`, `I64`.
47 Int,
48 /// The legacy fixed-block quants — a scale (and for the `_1` forms a min)
49 /// plus packed weights: `Q4_0`, `Q4_1`, `Q5_0`, `Q5_1`, `Q8_0`, `Q8_1`, and
50 /// upstream's newer `Q1_0` (128/block) and `Q2_0` (64/block).
51 Affine,
52 /// K-quants: 256-element super-blocks with per-sub-block scales.
53 KQuant,
54 /// The importance-matrix / codebook quants (`IQ*`), 256-element super-blocks
55 /// except `IQ4_NL`, which is 32.
56 Codebook,
57 /// Ternary packings `TQ1_0` and `TQ2_0`.
58 Ternary,
59 /// Microscaling floats: `MXFP4` (E8M0 scale, 32/block) and `NVFP4`
60 /// (UE4M3 sub-block scales, 64/block).
61 MicroscaleFp,
62 /// An id upstream has removed. No [`GgmlType`] variant constructs one; the
63 /// slot exists so [`TRAITS`] can stay indexed by id.
64 Removed,
65}
66
67/// What one ggml tensor type weighs, and what to call it.
68///
69/// `blck_size` and `type_size` are ggml's own field names, and ggml's own
70/// values: `type_size` bytes hold exactly `blck_size` elements. Both are 0 for
71/// a removed id.
72#[derive(Debug, Clone, Copy, PartialEq, Eq)]
73pub struct QuantTraits {
74 /// The upstream ENUM name without its `GGML_TYPE_` prefix — `"Q4_K"`,
75 /// `"IQ2_XXS"`, `"BF16"`. This is the GGUF-facing spelling and what
76 /// [`GgmlType::as_str`] returns.
77 pub name: &'static str,
78 /// The name `ggml_type_name()` returns — `"q4_K"`, `"iq2_xxs"`, `"bf16"`.
79 /// Differs from [`Self::name`] in case only, which the fixture test asserts.
80 pub ggml_name: &'static str,
81 /// Elements per block. 1 for the unquantized types, 0 for a removed id.
82 pub blck_size: u32,
83 /// Bytes per block. 0 for a removed id.
84 pub type_size: u32,
85 /// aprender's family classification (see [`GgmlFamily`]).
86 pub family: GgmlFamily,
87}
88
89/// Why an id is not a [`GgmlType`].
90///
91/// The distinction is the point: `4` is not an unknown id, it is `Q4_2`, which
92/// upstream removed. A loader that says "unknown tensor type 4" sends its
93/// reader looking for a type that was deleted in 2023.
94#[derive(Debug, Clone, Copy, PartialEq, Eq)]
95pub enum GgmlTypeError {
96 /// The id names a type upstream has removed.
97 Removed {
98 /// The removed id.
99 id: u32,
100 /// Its upstream name, e.g. `"Q4_0_4_8"`.
101 name: &'static str,
102 },
103 /// The id is not in `0..GGML_TYPE_COUNT` at the pinned commit.
104 Unknown {
105 /// The id that was offered.
106 id: u32,
107 },
108}
109
110impl fmt::Display for GgmlTypeError {
111 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
112 match self {
113 Self::Removed { id, name } => {
114 write!(f, "ggml tensor type {id} ({name}) was removed upstream")
115 }
116 Self::Unknown { id } => write!(f, "unknown ggml tensor type {id}"),
117 }
118 }
119}
120
121impl std::error::Error for GgmlTypeError {}
122
123/// The number of id slots upstream defines (`GGML_TYPE_COUNT`).
124pub const GGML_TYPE_COUNT: u32 = 43;
125
126// GENERATED ROWS: the `GgmlType` variants and the `TRAITS` table below are
127// emitted from fixtures/ggml_traits.json, which scripts/extract_ggml_traits.sh
128// extracted from upstream ggml at the pinned comparator commit. Editing a row
129// by hand turns tests/ggml_traits_fixture.rs RED.
130
131/// A ggml tensor type, by its upstream id.
132///
133/// 35 variants: every LIVE id at the pinned commit, and only those. The 8 ids
134/// upstream removed are not constructible — see [`GgmlType::try_from_id`], which
135/// tells a removed id apart from one that never existed — but they keep their
136/// slots in [`TRAITS`] so the table is indexed by id.
137#[repr(u32)]
138#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
139#[allow(non_camel_case_types)] // upstream ids: Q4_0, TQ1_0 — the tree's spelling
140pub enum GgmlType {
141 /// `F32` — ggml `f32`: `blck_size` 1, `type_size` 4.
142 F32 = 0,
143 /// `F16` — ggml `f16`: `blck_size` 1, `type_size` 2.
144 F16 = 1,
145 /// `Q4_0` — ggml `q4_0`: `blck_size` 32, `type_size` 18.
146 Q4_0 = 2,
147 /// `Q4_1` — ggml `q4_1`: `blck_size` 32, `type_size` 20.
148 Q4_1 = 3,
149 /// `Q5_0` — ggml `q5_0`: `blck_size` 32, `type_size` 22.
150 Q5_0 = 6,
151 /// `Q5_1` — ggml `q5_1`: `blck_size` 32, `type_size` 24.
152 Q5_1 = 7,
153 /// `Q8_0` — ggml `q8_0`: `blck_size` 32, `type_size` 34.
154 Q8_0 = 8,
155 /// `Q8_1` — ggml `q8_1`: `blck_size` 32, `type_size` 36.
156 Q8_1 = 9,
157 /// `Q2_K` — ggml `q2_K`: `blck_size` 256, `type_size` 84.
158 Q2K = 10,
159 /// `Q3_K` — ggml `q3_K`: `blck_size` 256, `type_size` 110.
160 Q3K = 11,
161 /// `Q4_K` — ggml `q4_K`: `blck_size` 256, `type_size` 144.
162 Q4K = 12,
163 /// `Q5_K` — ggml `q5_K`: `blck_size` 256, `type_size` 176.
164 Q5K = 13,
165 /// `Q6_K` — ggml `q6_K`: `blck_size` 256, `type_size` 210.
166 Q6K = 14,
167 /// `Q8_K` — ggml `q8_K`: `blck_size` 256, `type_size` 292.
168 Q8K = 15,
169 /// `IQ2_XXS` — ggml `iq2_xxs`: `blck_size` 256, `type_size` 66.
170 IQ2XXS = 16,
171 /// `IQ2_XS` — ggml `iq2_xs`: `blck_size` 256, `type_size` 74.
172 IQ2XS = 17,
173 /// `IQ3_XXS` — ggml `iq3_xxs`: `blck_size` 256, `type_size` 98.
174 IQ3XXS = 18,
175 /// `IQ1_S` — ggml `iq1_s`: `blck_size` 256, `type_size` 50.
176 IQ1S = 19,
177 /// `IQ4_NL` — ggml `iq4_nl`: `blck_size` 32, `type_size` 18.
178 IQ4NL = 20,
179 /// `IQ3_S` — ggml `iq3_s`: `blck_size` 256, `type_size` 110.
180 IQ3S = 21,
181 /// `IQ2_S` — ggml `iq2_s`: `blck_size` 256, `type_size` 82.
182 IQ2S = 22,
183 /// `IQ4_XS` — ggml `iq4_xs`: `blck_size` 256, `type_size` 136.
184 IQ4XS = 23,
185 /// `I8` — ggml `i8`: `blck_size` 1, `type_size` 1.
186 I8 = 24,
187 /// `I16` — ggml `i16`: `blck_size` 1, `type_size` 2.
188 I16 = 25,
189 /// `I32` — ggml `i32`: `blck_size` 1, `type_size` 4.
190 I32 = 26,
191 /// `I64` — ggml `i64`: `blck_size` 1, `type_size` 8.
192 I64 = 27,
193 /// `F64` — ggml `f64`: `blck_size` 1, `type_size` 8.
194 F64 = 28,
195 /// `IQ1_M` — ggml `iq1_m`: `blck_size` 256, `type_size` 56.
196 IQ1M = 29,
197 /// `BF16` — ggml `bf16`: `blck_size` 1, `type_size` 2.
198 BF16 = 30,
199 /// `TQ1_0` — ggml `tq1_0`: `blck_size` 256, `type_size` 54.
200 TQ1_0 = 34,
201 /// `TQ2_0` — ggml `tq2_0`: `blck_size` 256, `type_size` 66.
202 TQ2_0 = 35,
203 /// `MXFP4` — ggml `mxfp4`: `blck_size` 32, `type_size` 17.
204 MXFP4 = 39,
205 /// `NVFP4` — ggml `nvfp4`: `blck_size` 64, `type_size` 36.
206 NVFP4 = 40,
207 /// `Q1_0` — ggml `q1_0`: `blck_size` 128, `type_size` 18.
208 Q1_0 = 41,
209 /// `Q2_0` — ggml `q2_0`: `blck_size` 64, `type_size` 18.
210 Q2_0 = 42,
211}
212
213/// The ggml tensor-type table, INDEXED BY ID, all 43 slots including the 8 removed.
214///
215/// Dense so that `TRAITS[t.as_id() as usize]` is the lookup and no id needs a
216/// search. A removed slot carries `family: GgmlFamily::Removed` and upstream's
217/// own zeroes, which is what ggml reports for it.
218pub const TRAITS: [QuantTraits; 43] = [
219 QuantTraits {
220 name: "F32",
221 ggml_name: "f32",
222 blck_size: 1,
223 type_size: 4,
224 family: GgmlFamily::Float,
225 }, // 0
226 QuantTraits {
227 name: "F16",
228 ggml_name: "f16",
229 blck_size: 1,
230 type_size: 2,
231 family: GgmlFamily::Float,
232 }, // 1
233 QuantTraits {
234 name: "Q4_0",
235 ggml_name: "q4_0",
236 blck_size: 32,
237 type_size: 18,
238 family: GgmlFamily::Affine,
239 }, // 2
240 QuantTraits {
241 name: "Q4_1",
242 ggml_name: "q4_1",
243 blck_size: 32,
244 type_size: 20,
245 family: GgmlFamily::Affine,
246 }, // 3
247 QuantTraits {
248 name: "Q4_2",
249 ggml_name: "DEPRECATED",
250 blck_size: 0,
251 type_size: 0,
252 family: GgmlFamily::Removed,
253 }, // 4
254 QuantTraits {
255 name: "Q4_3",
256 ggml_name: "DEPRECATED",
257 blck_size: 0,
258 type_size: 0,
259 family: GgmlFamily::Removed,
260 }, // 5
261 QuantTraits {
262 name: "Q5_0",
263 ggml_name: "q5_0",
264 blck_size: 32,
265 type_size: 22,
266 family: GgmlFamily::Affine,
267 }, // 6
268 QuantTraits {
269 name: "Q5_1",
270 ggml_name: "q5_1",
271 blck_size: 32,
272 type_size: 24,
273 family: GgmlFamily::Affine,
274 }, // 7
275 QuantTraits {
276 name: "Q8_0",
277 ggml_name: "q8_0",
278 blck_size: 32,
279 type_size: 34,
280 family: GgmlFamily::Affine,
281 }, // 8
282 QuantTraits {
283 name: "Q8_1",
284 ggml_name: "q8_1",
285 blck_size: 32,
286 type_size: 36,
287 family: GgmlFamily::Affine,
288 }, // 9
289 QuantTraits {
290 name: "Q2_K",
291 ggml_name: "q2_K",
292 blck_size: 256,
293 type_size: 84,
294 family: GgmlFamily::KQuant,
295 }, // 10
296 QuantTraits {
297 name: "Q3_K",
298 ggml_name: "q3_K",
299 blck_size: 256,
300 type_size: 110,
301 family: GgmlFamily::KQuant,
302 }, // 11
303 QuantTraits {
304 name: "Q4_K",
305 ggml_name: "q4_K",
306 blck_size: 256,
307 type_size: 144,
308 family: GgmlFamily::KQuant,
309 }, // 12
310 QuantTraits {
311 name: "Q5_K",
312 ggml_name: "q5_K",
313 blck_size: 256,
314 type_size: 176,
315 family: GgmlFamily::KQuant,
316 }, // 13
317 QuantTraits {
318 name: "Q6_K",
319 ggml_name: "q6_K",
320 blck_size: 256,
321 type_size: 210,
322 family: GgmlFamily::KQuant,
323 }, // 14
324 QuantTraits {
325 name: "Q8_K",
326 ggml_name: "q8_K",
327 blck_size: 256,
328 type_size: 292,
329 family: GgmlFamily::KQuant,
330 }, // 15
331 QuantTraits {
332 name: "IQ2_XXS",
333 ggml_name: "iq2_xxs",
334 blck_size: 256,
335 type_size: 66,
336 family: GgmlFamily::Codebook,
337 }, // 16
338 QuantTraits {
339 name: "IQ2_XS",
340 ggml_name: "iq2_xs",
341 blck_size: 256,
342 type_size: 74,
343 family: GgmlFamily::Codebook,
344 }, // 17
345 QuantTraits {
346 name: "IQ3_XXS",
347 ggml_name: "iq3_xxs",
348 blck_size: 256,
349 type_size: 98,
350 family: GgmlFamily::Codebook,
351 }, // 18
352 QuantTraits {
353 name: "IQ1_S",
354 ggml_name: "iq1_s",
355 blck_size: 256,
356 type_size: 50,
357 family: GgmlFamily::Codebook,
358 }, // 19
359 QuantTraits {
360 name: "IQ4_NL",
361 ggml_name: "iq4_nl",
362 blck_size: 32,
363 type_size: 18,
364 family: GgmlFamily::Codebook,
365 }, // 20
366 QuantTraits {
367 name: "IQ3_S",
368 ggml_name: "iq3_s",
369 blck_size: 256,
370 type_size: 110,
371 family: GgmlFamily::Codebook,
372 }, // 21
373 QuantTraits {
374 name: "IQ2_S",
375 ggml_name: "iq2_s",
376 blck_size: 256,
377 type_size: 82,
378 family: GgmlFamily::Codebook,
379 }, // 22
380 QuantTraits {
381 name: "IQ4_XS",
382 ggml_name: "iq4_xs",
383 blck_size: 256,
384 type_size: 136,
385 family: GgmlFamily::Codebook,
386 }, // 23
387 QuantTraits {
388 name: "I8",
389 ggml_name: "i8",
390 blck_size: 1,
391 type_size: 1,
392 family: GgmlFamily::Int,
393 }, // 24
394 QuantTraits {
395 name: "I16",
396 ggml_name: "i16",
397 blck_size: 1,
398 type_size: 2,
399 family: GgmlFamily::Int,
400 }, // 25
401 QuantTraits {
402 name: "I32",
403 ggml_name: "i32",
404 blck_size: 1,
405 type_size: 4,
406 family: GgmlFamily::Int,
407 }, // 26
408 QuantTraits {
409 name: "I64",
410 ggml_name: "i64",
411 blck_size: 1,
412 type_size: 8,
413 family: GgmlFamily::Int,
414 }, // 27
415 QuantTraits {
416 name: "F64",
417 ggml_name: "f64",
418 blck_size: 1,
419 type_size: 8,
420 family: GgmlFamily::Float,
421 }, // 28
422 QuantTraits {
423 name: "IQ1_M",
424 ggml_name: "iq1_m",
425 blck_size: 256,
426 type_size: 56,
427 family: GgmlFamily::Codebook,
428 }, // 29
429 QuantTraits {
430 name: "BF16",
431 ggml_name: "bf16",
432 blck_size: 1,
433 type_size: 2,
434 family: GgmlFamily::Float,
435 }, // 30
436 QuantTraits {
437 name: "Q4_0_4_4",
438 ggml_name: "TYPE_Q4_0_4_4 REMOVED, use Q4_0 with runtime repacking",
439 blck_size: 0,
440 type_size: 0,
441 family: GgmlFamily::Removed,
442 }, // 31
443 QuantTraits {
444 name: "Q4_0_4_8",
445 ggml_name: "TYPE_Q4_0_4_8 REMOVED, use Q4_0 with runtime repacking",
446 blck_size: 0,
447 type_size: 0,
448 family: GgmlFamily::Removed,
449 }, // 32
450 QuantTraits {
451 name: "Q4_0_8_8",
452 ggml_name: "TYPE_Q4_0_8_8 REMOVED, use Q4_0 with runtime repacking",
453 blck_size: 0,
454 type_size: 0,
455 family: GgmlFamily::Removed,
456 }, // 33
457 QuantTraits {
458 name: "TQ1_0",
459 ggml_name: "tq1_0",
460 blck_size: 256,
461 type_size: 54,
462 family: GgmlFamily::Ternary,
463 }, // 34
464 QuantTraits {
465 name: "TQ2_0",
466 ggml_name: "tq2_0",
467 blck_size: 256,
468 type_size: 66,
469 family: GgmlFamily::Ternary,
470 }, // 35
471 QuantTraits {
472 name: "IQ4_NL_4_4",
473 ggml_name: "TYPE_IQ4_NL_4_4 REMOVED, use IQ4_NL with runtime repacking",
474 blck_size: 0,
475 type_size: 0,
476 family: GgmlFamily::Removed,
477 }, // 36
478 QuantTraits {
479 name: "IQ4_NL_4_8",
480 ggml_name: "TYPE_IQ4_NL_4_8 REMOVED, use IQ4_NL with runtime repacking",
481 blck_size: 0,
482 type_size: 0,
483 family: GgmlFamily::Removed,
484 }, // 37
485 QuantTraits {
486 name: "IQ4_NL_8_8",
487 ggml_name: "TYPE_IQ4_NL_8_8 REMOVED, use IQ4_NL with runtime repacking",
488 blck_size: 0,
489 type_size: 0,
490 family: GgmlFamily::Removed,
491 }, // 38
492 QuantTraits {
493 name: "MXFP4",
494 ggml_name: "mxfp4",
495 blck_size: 32,
496 type_size: 17,
497 family: GgmlFamily::MicroscaleFp,
498 }, // 39
499 QuantTraits {
500 name: "NVFP4",
501 ggml_name: "nvfp4",
502 blck_size: 64,
503 type_size: 36,
504 family: GgmlFamily::MicroscaleFp,
505 }, // 40
506 QuantTraits {
507 name: "Q1_0",
508 ggml_name: "q1_0",
509 blck_size: 128,
510 type_size: 18,
511 family: GgmlFamily::Affine,
512 }, // 41
513 QuantTraits {
514 name: "Q2_0",
515 ggml_name: "q2_0",
516 blck_size: 64,
517 type_size: 18,
518 family: GgmlFamily::Affine,
519 }, // 42
520];
521
522const fn from_id_inner(id: u32) -> Option<GgmlType> {
523 match id {
524 0 => Some(GgmlType::F32),
525 1 => Some(GgmlType::F16),
526 2 => Some(GgmlType::Q4_0),
527 3 => Some(GgmlType::Q4_1),
528 6 => Some(GgmlType::Q5_0),
529 7 => Some(GgmlType::Q5_1),
530 8 => Some(GgmlType::Q8_0),
531 9 => Some(GgmlType::Q8_1),
532 10 => Some(GgmlType::Q2K),
533 11 => Some(GgmlType::Q3K),
534 12 => Some(GgmlType::Q4K),
535 13 => Some(GgmlType::Q5K),
536 14 => Some(GgmlType::Q6K),
537 15 => Some(GgmlType::Q8K),
538 16 => Some(GgmlType::IQ2XXS),
539 17 => Some(GgmlType::IQ2XS),
540 18 => Some(GgmlType::IQ3XXS),
541 19 => Some(GgmlType::IQ1S),
542 20 => Some(GgmlType::IQ4NL),
543 21 => Some(GgmlType::IQ3S),
544 22 => Some(GgmlType::IQ2S),
545 23 => Some(GgmlType::IQ4XS),
546 24 => Some(GgmlType::I8),
547 25 => Some(GgmlType::I16),
548 26 => Some(GgmlType::I32),
549 27 => Some(GgmlType::I64),
550 28 => Some(GgmlType::F64),
551 29 => Some(GgmlType::IQ1M),
552 30 => Some(GgmlType::BF16),
553 34 => Some(GgmlType::TQ1_0),
554 35 => Some(GgmlType::TQ2_0),
555 39 => Some(GgmlType::MXFP4),
556 40 => Some(GgmlType::NVFP4),
557 41 => Some(GgmlType::Q1_0),
558 42 => Some(GgmlType::Q2_0),
559 _ => None,
560 }
561}
562
563/// The 8 ids upstream has removed: constructible by no one, but distinguishable
564/// from an id that never existed. `// GGML_TYPE_Q4_0_4_8 = 32,` in ggml.h says
565/// nothing about being removed, so membership here is positional, never textual.
566const REMOVED_IDS: [u32; 8] = [4, 5, 31, 32, 33, 36, 37, 38];
567
568/// Every live variant, in id order — the iteration surface for tests and callers.
569pub const ALL: [GgmlType; 35] = [
570 GgmlType::F32,
571 GgmlType::F16,
572 GgmlType::Q4_0,
573 GgmlType::Q4_1,
574 GgmlType::Q5_0,
575 GgmlType::Q5_1,
576 GgmlType::Q8_0,
577 GgmlType::Q8_1,
578 GgmlType::Q2K,
579 GgmlType::Q3K,
580 GgmlType::Q4K,
581 GgmlType::Q5K,
582 GgmlType::Q6K,
583 GgmlType::Q8K,
584 GgmlType::IQ2XXS,
585 GgmlType::IQ2XS,
586 GgmlType::IQ3XXS,
587 GgmlType::IQ1S,
588 GgmlType::IQ4NL,
589 GgmlType::IQ3S,
590 GgmlType::IQ2S,
591 GgmlType::IQ4XS,
592 GgmlType::I8,
593 GgmlType::I16,
594 GgmlType::I32,
595 GgmlType::I64,
596 GgmlType::F64,
597 GgmlType::IQ1M,
598 GgmlType::BF16,
599 GgmlType::TQ1_0,
600 GgmlType::TQ2_0,
601 GgmlType::MXFP4,
602 GgmlType::NVFP4,
603 GgmlType::Q1_0,
604 GgmlType::Q2_0,
605];
606
607impl GgmlType {
608 /// The type with this id, or `None` if no live type has it.
609 ///
610 /// Returns `None` for both a removed id and an id that never existed; use
611 /// [`Self::try_from_id`] when the difference should reach the user. The
612 /// signature is `Option` because that is what serve's `GgmlQuantType::from_id`
613 /// returned, and M1 does not move its callers.
614 #[must_use]
615 pub const fn from_id(id: u32) -> Option<Self> {
616 from_id_inner(id)
617 }
618
619 /// The type with this id, naming WHY it is not one when it is not.
620 ///
621 /// # Errors
622 ///
623 /// [`GgmlTypeError::Removed`] for the 8 ids upstream has deleted,
624 /// [`GgmlTypeError::Unknown`] for anything else outside the live set.
625 pub const fn try_from_id(id: u32) -> Result<Self, GgmlTypeError> {
626 match from_id_inner(id) {
627 Some(t) => Ok(t),
628 None => {
629 if id < GGML_TYPE_COUNT {
630 // In range and not live => one of the 8 removed slots, whose
631 // TRAITS row still carries upstream's name for it.
632 Err(GgmlTypeError::Removed {
633 id,
634 name: TRAITS[id as usize].name,
635 })
636 } else {
637 Err(GgmlTypeError::Unknown { id })
638 }
639 }
640 }
641 }
642
643 /// This type's upstream id.
644 #[must_use]
645 pub const fn as_id(self) -> u32 {
646 self as u32
647 }
648
649 /// This type's upstream id as a byte, for the APR tensor header.
650 ///
651 /// Total, with no truncation to hide: the largest id at the pin is 42.
652 #[must_use]
653 pub const fn as_byte(self) -> u8 {
654 self as u8
655 }
656
657 /// The GGUF-facing name: `"Q4_K"`, `"IQ2_XXS"`, `"BF16"`.
658 #[must_use]
659 pub const fn as_str(self) -> &'static str {
660 self.traits().name
661 }
662
663 /// The name ggml itself prints: `"q4_K"`, `"iq2_xxs"`, `"bf16"`.
664 #[must_use]
665 pub const fn ggml_name(self) -> &'static str {
666 self.traits().ggml_name
667 }
668
669 /// This type's row in [`TRAITS`].
670 #[must_use]
671 pub const fn traits(self) -> &'static QuantTraits {
672 &TRAITS[self as usize]
673 }
674
675 /// This type's family.
676 #[must_use]
677 pub const fn family(self) -> GgmlFamily {
678 self.traits().family
679 }
680
681 /// Bytes per block — ggml's `type_size`.
682 #[must_use]
683 pub const fn block_bytes(&self) -> usize {
684 self.traits().type_size as usize
685 }
686
687 /// Elements per block — ggml's `blck_size`.
688 #[must_use]
689 pub const fn block_size(&self) -> usize {
690 self.traits().blck_size as usize
691 }
692
693 /// Bytes for `n_elements` weights, rounding a partial block UP.
694 ///
695 /// This is compute's arithmetic, unchanged, because its callers depend on
696 /// the rounding. It says nothing about whether a partial block is LEGAL —
697 /// [`Self::checked_tensor_bytes`] is the one that refuses.
698 #[must_use]
699 pub const fn tensor_bytes(&self, n_elements: usize) -> usize {
700 let bs = self.block_size();
701 let n_blocks = n_elements.div_ceil(bs);
702 n_blocks * self.block_bytes()
703 }
704
705 /// Bytes for `n_elements` weights, or `None` if that is not a whole number
706 /// of blocks or the product overflows.
707 ///
708 /// A quantized tensor whose element count is not a multiple of `blck_size`
709 /// is not a short tensor, it is a malformed one; rounding it up produces a
710 /// plausible byte count for a file that cannot be read.
711 #[must_use]
712 pub const fn checked_tensor_bytes(self, n_elements: usize) -> Option<usize> {
713 let bs = self.block_size();
714 if bs == 0 || !n_elements.is_multiple_of(bs) {
715 return None;
716 }
717 match (n_elements / bs).checked_mul(self.block_bytes()) {
718 Some(bytes) => Some(bytes),
719 None => None,
720 }
721 }
722
723 /// Parse a GGUF-facing name, accepting its exact spelling or its all-lowercase
724 /// form — `"Q4_K"` and `"q4_k"`, as serve's `from_str_lossy` accepted them.
725 ///
726 /// Note that ggml's own `"q4_K"` is neither, and is deliberately still not
727 /// accepted: M1 changes no parser's admitted set.
728 #[must_use]
729 pub fn from_str_lossy(s: &str) -> Option<Self> {
730 ALL.into_iter().find(|t| {
731 let name = t.as_str();
732 s == name
733 || (s.eq_ignore_ascii_case(name) && s.chars().all(|c| !c.is_ascii_uppercase()))
734 })
735 }
736}
737
738impl fmt::Display for GgmlType {
739 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
740 f.write_str(self.as_str())
741 }
742}
743
744// ---------------------------------------------------------------------------
745// Const assertions: these fail the BUILD, not a test run.
746// ---------------------------------------------------------------------------
747
748/// `TRAITS` is indexed by id, so every variant must find its own row there.
749const _: () = {
750 let mut i = 0;
751 while i < ALL.len() {
752 let t = ALL[i];
753 assert!(
754 TRAITS[t.as_id() as usize].blck_size > 0,
755 "a live type indexes a removed TRAITS row"
756 );
757 i += 1;
758 }
759};
760
761/// Every removed id is a removed row, and there are exactly 8 of them.
762const _: () = {
763 let mut i = 0;
764 while i < REMOVED_IDS.len() {
765 let id = REMOVED_IDS[i];
766 assert!(
767 TRAITS[id as usize].type_size == 0,
768 "a removed id has a non-zero type_size"
769 );
770 assert!(from_id_inner(id).is_none(), "a removed id is constructible");
771 i += 1;
772 }
773 assert!(
774 REMOVED_IDS.len() + ALL.len() == TRAITS.len(),
775 "live + removed != 43"
776 );
777};
778
779// ---------------------------------------------------------------------------
780// Kani harness (KANI-GGMLT-001, contracts/ggml-type-v1.yaml)
781// ---------------------------------------------------------------------------
782
783/// Exhaustive over the id space: resolution agrees with the table, and no
784/// method panics or overflows on a live type.
785#[cfg(kani)]
786#[kani::proof]
787#[kani::unwind(44)]
788fn verify_ggml_type_id_space() {
789 let id: u32 = kani::any();
790 kani::assume(id < GGML_TYPE_COUNT);
791
792 let live = TRAITS[id as usize].blck_size > 0;
793 assert_eq!(GgmlType::from_id(id).is_some(), live);
794 assert_eq!(GgmlType::try_from_id(id).is_ok(), live);
795
796 if let Some(t) = GgmlType::from_id(id) {
797 assert_eq!(t.as_id(), id);
798 assert!(t.block_size() > 0);
799 assert!(t.block_bytes() > 0);
800 assert_eq!(t.tensor_bytes(t.block_size()), t.block_bytes());
801 assert_eq!(
802 t.checked_tensor_bytes(t.block_size()),
803 Some(t.block_bytes())
804 );
805 }
806}