frink-cli 0.72.0

llama.cpp-style CLI for the Frink inference engine
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
//! llama.cpp's per-tensor MIX, transcribed from `llama_tensor_get_type`
//! in b7650's `src/llama-quant.cpp:178` and brought to the pin
//! (`ee467158`, `llama_tensor_get_type_impl` at `:517`, #750): the
//! tensor categories of `tensor_get_category` (`:127`), where
//! `attn_qkv`, the fused `attn_qkv_gate` and `attn_kv_b` take the
//! `attn_v` arm, counter and all (#714), and `ffn_latent` and
//! `attn_gate` have categories of their own; the three
//! architecture-specific rules in [`super::arch`]; `layer_info`'s
//! refusals and `dec.blk.%d.`; and `n_layer_all` as the FFN denominator
//! ([`super::model_shape`]). Line numbers below without a version are
//! b7650's.
//!
//! Evidence: the pin's `llama-quantize --dry-run` on one synthetic
//! checkpoint per architecture-specific rule
//! ([`super::recipe_golden_arch`]), on a synthetic Qwen3.5
//! ([`super::recipe_golden_qwen35`]), and b7650's on Llama-3.2-1B
//! ([`super::recipe_golden`]).
//!
//! `--type Q4_K_M` does not mean "every tensor Q4_K". It means a
//! specific set of promotions: `output.weight` to Q6_K, `attn_v` on
//! roughly a quarter of the layers to Q6_K, `ffn_down` on the same
//! layers to Q6_K, `attn_qkv` to Q5_K. Writing uniform Q4_K under that
//! name produces a file that loads, runs, reports `general.file_type =
//! Q4_K_M`, and is a different file from the one every other tool in
//! the ecosystem means by the name. That is the failure this module
//! exists to close: [`Recipe`] is why `--pure` stopped being mandatory
//! for the K-quant mixes.
//!
//! # One table, and why the rest is not in it
//!
//! [`PROMOTIONS`] is upstream's else-if chain, in upstream's order, as
//! data: one row per (role, ftype) arm, first match wins. It is the
//! chain, so it is a table.
//!
//! Three things upstream does are NOT chain arms and are therefore not
//! rows -- they are `if` statements that run AFTER the chain has picked
//! a type, and can override it:
//!
//! * the `LLM_TYPE_70B` bump (`llama-quant.cpp:305`), Q3_K/Q4_K -> Q5_K;
//! * `n_expert == 8` -> Q8_0 on `attn_v` and `attn_k`
//!   (`llama-quant.cpp:311`, `:319`);
//! * the output head's shape and Falcon checks.
//!
//! Encoding a post-condition as a chain row would put it in the wrong
//! place: on a Mixtral, `attn_v` matches the Q4_K_M row AND then gets
//! overridden to Q8_0, and a table that could only express "first match
//! wins" would have to choose one. So they are code, each carrying the
//! upstream line it came from, and [`tests`] asserts the ordering.
//!
//! # This is stateful, and the state is the point
//!
//! `i_attention_wv` and `i_ffn_down` are running counters over the
//! tensors that REACH each arm -- not layer indices parsed from the
//! name (except on MoE checkpoints, where upstream falls back to
//! parsing `blk.%d.` precisely because the counter is wrong there).
//! [`Recipe::tensor_type`] therefore takes `&mut self` and must be
//! called once per eligible tensor, in llama.cpp's order, for exactly
//! the tensors llama.cpp would call it for. Calling it for a tensor
//! llama.cpp skips, or in the wrong order, shifts every later layer's
//! decision by one.
//!
//! **That order is NOT the file's.** llama.cpp reaches these tensors
//! through `llama_model_loader::weights_map`, a `std::map` keyed by
//! name with a `weight_name_comparer` (`llama-model-loader.h:53`) that
//! sorts by the layer number parsed out of `blk.%d.` first and by name
//! second. A GGUF written by `convert_hf_to_gguf.py` is not in that
//! order, so walking `file.tensors` gives different answers -- measured
//! on Llama-3.2-1B, 12 of 113 tensors got the wrong type that way,
//! because the counter reached `blk.9.ffn_down` while llama.cpp was at
//! `blk.8`. [`Recipe::resolve_all`] exists so no caller has to know
//! this: it sorts, walks, and hands back a name -> type map.

use std::collections::BTreeMap;

use anyhow::{bail, Result};
use frink_gguf::GgmlType;

use super::arch::{self, Early, QuantArch};
use super::model_shape::{llama_cpp_weight_order, scan_layer, ModelShape};
use super::policy::Target;

/// The tensor roles `llama_tensor_get_type` branches on, in the order
/// its else-if chain tests them.
///
/// The order is load-bearing and is not the obvious one:
/// `attn_qkv.weight` is tested AFTER `ffn_down` and `attn_output`, and
/// `output.weight` before everything. [`Role::of`] preserves it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Role {
    /// `output.weight`, or `token_embd.weight` on a checkpoint with no
    /// separate output head (tied embeddings).
    Output,
    /// `token_embd.weight` when `output.weight` also exists.
    TokenEmbd,
    AttnV,
    AttnK,
    AttnQ,
    FfnDown,
    AttnOutput,
    /// `attn_qkv` or the fused `[attn_qkv | attn_gate]` (`attn_qkv_gate`,
    /// Qwen3.5 at the pin), whose qkv rows decide its type.
    AttnQkv,
    /// MLA's `attn_kv_b`.
    AttnKvB,
    FfnGate,
    FfnUp,
    /// `ffn_latent`: no arm of its own; MUSE_SPARK's Q8_0 bump reads it.
    FfnLatent,
    /// `attn_gate.weight`: no arm of its own; MUSE_SPARK's bump and
    /// RAON1_MINI's floor read it.
    AttnGate,
    Other,
}

impl Role {
    /// `category_is_attn_v` (`ee467158:src/llama-quant.cpp:153`): the
    /// roles that take the `attn_v` arm and advance its counter. The one
    /// definition both [`Recipe::new`]'s count and
    /// [`Recipe::tensor_type`]'s arm read, so they cannot disagree.
    pub fn is_attn_v_like(self) -> bool {
        matches!(self, Role::AttnV | Role::AttnQkv | Role::AttnKvB)
    }
}

impl Role {
    /// Which arm of the chain a tensor name lands in.
    ///
    /// `has_output` is whether the file carries an `output.weight` at
    /// all: without one, `token_embd.weight` IS the output head and
    /// gets the output head's type, which is how a tied-embedding
    /// model's Q4_K_M file ends up with a Q6_K embedding table.
    pub fn of(name: &str, has_output: bool) -> Role {
        // `llama-quant.cpp:207`: the output arm's condition, then the
        // token-embd arm's at `:237`. Both are exact-name matches
        // against `LLM_TN(arch)(...)`, which for these two tensors is
        // the same spelling for every architecture.
        if name == "output.weight" {
            return Role::Output;
        }
        let is_token_embd = name == "token_embd.weight" || name == "per_layer_token_embd.weight";
        if is_token_embd {
            return if has_output {
                Role::TokenEmbd
            } else {
                Role::Output
            };
        }
        // From here the categories are substring matches in the pin's
        // order (`ee467158:src/llama-quant.cpp:131-141`): the qkv pair,
        // `attn_kv_b`, `attn_v`, `attn_k`, `attn_q`, `attn_output`,
        // `ffn_up`, `ffn_gate`, `ffn_latent`, `attn_gate.weight`, then
        // `ffn_down`. One ordered list rather than a match on a parsed
        // suffix, because the first needle a name contains wins: a
        // `ffn_latent_down` is `FfnLatent`, not `FfnDown`.
        for (needle, role) in [
            ("attn_qkv.weight", Role::AttnQkv),
            ("attn_qkv_gate.weight", Role::AttnQkv),
            ("attn_kv_b.weight", Role::AttnKvB),
            ("attn_v.weight", Role::AttnV),
            ("attn_k.weight", Role::AttnK),
            ("attn_q.weight", Role::AttnQ),
            ("attn_output.weight", Role::AttnOutput),
            ("ffn_up", Role::FfnUp),
            ("ffn_gate", Role::FfnGate),
            ("ffn_latent", Role::FfnLatent),
            ("attn_gate.weight", Role::AttnGate),
            ("ffn_down", Role::FfnDown),
        ] {
            if name.contains(needle) {
                return role;
            }
        }
        Role::Other
    }
}

/// The layer condition a promotion is gated on.
///
/// These four are every condition the five mixes frink can write
/// actually use. A fifth would be a new variant and a new match arm,
/// which is the point: a condition spelled inline in one row's closure
/// would be a condition nothing else could see.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum When {
    /// No condition: the arm fires for every tensor of this role.
    Always,
    /// `use_more_bits(i, n)` (`llama-quant.cpp:185`).
    UseMoreBits,
    /// `i < n/8`.
    FirstEighth,
    /// `i < 4`, which only `Q4_K_S`'s `attn_v` arm uses.
    FirstFour,
}

impl When {
    fn holds(self, i: usize, n: usize) -> bool {
        match self {
            When::Always => true,
            // `i_layer < n_layers/8 || i_layer >= 7*n_layers/8 ||
            //  (i_layer - n_layers/8) % 3 == 2`, with C's integer
            // division. The third term is only evaluated when the first
            // is false, so `i - n/8` cannot go negative -- which is the
            // only reason a `usize` subtraction is safe here, and the
            // reason it is written with the guard rather than as a
            // three-way `||`.
            When::UseMoreBits => {
                if i < n / 8 {
                    return true;
                }
                if n != 0 && i >= 7 * n / 8 {
                    return true;
                }
                (i - n / 8) % 3 == 2
            }
            When::FirstEighth => i < n / 8,
            When::FirstFour => i < 4,
        }
    }
}

/// One arm of `llama_tensor_get_type`'s else-if chain.
struct Promotion {
    role: Role,
    ftype: Target,
    /// Whether this arm is guarded by upstream's inline
    /// `arch != LLM_ARCH_FALCON`. There is no `only_falcon` counterpart
    /// because the two Falcon-only arms these mixes reach both need a
    /// fraction (`i < n/16`) or a shape no other arm uses, so they are
    /// code in [`Recipe::tensor_type`] rather than rows.
    not_falcon: bool,
    when: When,
    to: GgmlType,
}

/// `llama_tensor_get_type`'s else-if chain for the five mixes frink
/// can write, in upstream's order. First matching row wins.
///
/// A row per arm, and the row's `to` is the type that arm assigns. An
/// arm that assigns the default type (so, no promotion) has no row: the
/// absence IS the "leave it alone" case, and `the_recipe_only_promotes_
/// to_types_frink_can_encode` is what stops a row from naming a type
/// with no encoder.
///
/// The `not_falcon` rows, and the Falcon arms in code, are checked
/// against the pin's `llama-quantize` on a synthetic 16-layer Falcon
/// (`goldens/falcon.golden`, #750).
const PROMOTIONS: &[Promotion] = &[
    // --- the output head (`llama-quant.cpp:207`) ---------------------
    // `else if (new_type != GGML_TYPE_Q8_0) new_type = GGML_TYPE_Q6_K;`
    // -- every K-quant mix sends the output head to Q6_K. The Falcon
    // and awkward-shape arms above it both send it to Q8_0 and are
    // handled in `tensor_type` because they read the tensor's shape.
    Promotion {
        role: Role::Output,
        ftype: Target::Q4_K_S,
        not_falcon: true,
        when: When::Always,
        to: GgmlType::Q6K,
    },
    Promotion {
        role: Role::Output,
        ftype: Target::Q4_K_M,
        not_falcon: true,
        when: When::Always,
        to: GgmlType::Q6K,
    },
    Promotion {
        role: Role::Output,
        ftype: Target::Q5_K_S,
        not_falcon: true,
        when: When::Always,
        to: GgmlType::Q6K,
    },
    Promotion {
        role: Role::Output,
        ftype: Target::Q5_K_M,
        not_falcon: true,
        when: When::Always,
        to: GgmlType::Q6K,
    },
    // Q6_K's own output head is already Q6_K, so the arm assigns the
    // default and there is deliberately no row.

    // --- attn_v (`llama-quant.cpp:279`) ------------------------------
    // `(Q4_K_M || Q5_K_M) && use_more_bits(i_attention_wv, n_attention_wv)`
    Promotion {
        role: Role::AttnV,
        ftype: Target::Q4_K_M,
        not_falcon: false,
        when: When::UseMoreBits,
        to: GgmlType::Q6K,
    },
    Promotion {
        role: Role::AttnV,
        ftype: Target::Q5_K_M,
        not_falcon: false,
        when: When::UseMoreBits,
        to: GgmlType::Q6K,
    },
    // `Q4_K_S && qs.i_attention_wv < 4`
    Promotion {
        role: Role::AttnV,
        ftype: Target::Q4_K_S,
        not_falcon: false,
        when: When::FirstFour,
        to: GgmlType::Q5K,
    },
    // --- ffn_down (`llama-quant.cpp:336`) ----------------------------
    // Q4_K_M on Falcon: `i < n/16 ? Q6_K : use_more_bits ? Q5_K : Q4_K`.
    // The `i < n/16` half has no `When` of its own because no other arm
    // needs it; it is folded into `tensor_type`'s Falcon branch below.
    Promotion {
        role: Role::FfnDown,
        ftype: Target::Q4_K_M,
        not_falcon: true,
        when: When::UseMoreBits,
        to: GgmlType::Q6K,
    },
    Promotion {
        role: Role::FfnDown,
        ftype: Target::Q5_K_M,
        not_falcon: false,
        when: When::UseMoreBits,
        to: GgmlType::Q6K,
    },
    Promotion {
        role: Role::FfnDown,
        ftype: Target::Q4_K_S,
        not_falcon: true,
        when: When::FirstEighth,
        to: GgmlType::Q5K,
    },
    // `attn_qkv`'s own arm (`ee467158:src/llama-quant.cpp:734`, a flat
    // Q5_K / Q6_K) has no rows: at the pin `category_is_attn_v` sends
    // every qkv tensor down the `attn_v` arm above first, so that arm
    // is unreachable for the five mixes (#714).
];

/// The Falcon-only `ffn_down` arm for Q4_K_M, which needs `i < n/16`
/// and is the only place that fraction appears.
const FALCON_Q4KM_FFN_DOWN_SIXTEENTH: GgmlType = GgmlType::Q6K;

/// A checkpoint's mix, walked once in tensor order.
///
/// Build it with [`Recipe::new`], which needs the whole tensor list
/// because `n_attention_wv` is a count over ALL tensors and
/// `has_output` is a question about the file, not about the tensor in
/// hand.
pub struct Recipe {
    target: Target,
    shape: ModelShape,
    /// Counted over every tensor in the file, before any type is
    /// chosen (`llama-quant.cpp:709`).
    n_attention_wv: usize,
    has_output: bool,
    i_attention_wv: usize,
    i_ffn_down: usize,
    i_ffn_gate: usize,
    i_ffn_up: usize,
}

impl Recipe {
    /// `tensor_names` must be every tensor in the file, in file order.
    pub fn new(target: Target, shape: ModelShape, tensor_names: &[String]) -> Recipe {
        // `init_quantize_state_counters` (`ee467158:src/llama-quant.cpp
        // :3202`): n_attention_wv counts every tensor whose category is
        // attn_v-like, over the whole file, and the same tensors advance
        // `i_attention_wv` in the arm.
        let has_output = tensor_names.iter().any(|n| n == "output.weight");
        let n_attention_wv = tensor_names
            .iter()
            .filter(|n| Role::of(n, has_output).is_attn_v_like())
            .count();
        Recipe {
            target,
            shape,
            n_attention_wv,
            has_output,
            i_attention_wv: 0,
            i_ffn_down: 0,
            i_ffn_gate: 0,
            i_ffn_up: 0,
        }
    }

    /// The type llama.cpp would give this tensor, and the counter
    /// bookkeeping that goes with it. `source` is the tensor's own type,
    /// which RAON1_MINI keeps for its MLA latents under Q6_K and Q8_0.
    ///
    /// MUST be called once per eligible tensor, in llama.cpp's order.
    /// Prefer [`Recipe::resolve_all`], which owns that order; this is
    /// public for the tests that step the counters one tensor at a time.
    ///
    /// `Err` where `llama-quantize` throws: an FFN tensor of a MoE
    /// checkpoint whose layer cannot be read from its name, or is past
    /// `n_layer` (`layer_info`, `ee467158:src/llama-quant.cpp:528-541`).
    pub fn tensor_type(&mut self, name: &str, shape: &[u64], source: GgmlType) -> Result<GgmlType> {
        let role = Role::of(name, self.has_output);
        let falcon = self.shape.arch == QuantArch::Falcon;

        // The architecture rules above the chain (`:542-567`). A
        // `Return` skips the chain, its counters and the floors.
        let default = match arch::early(
            self.shape.arch,
            self.target,
            role,
            name,
            self.target.ggml_type(),
            source,
        ) {
            Early::Return(t) => return Ok(t),
            Early::Start(t) => t,
        };

        let ty = match role {
            Role::Output => self.output_head_type(shape, default),
            Role::AttnV | Role::AttnQkv | Role::AttnKvB => {
                // One arm for the three (`category_is_attn_v`): the rows
                // are keyed on `AttnV`.
                let t = self.chain(
                    Role::AttnV,
                    self.i_attention_wv,
                    self.n_attention_wv,
                    default,
                );
                // `llama-quant.cpp:305`, AFTER the chain: the 70B bump.
                let t = if self.shape.is_70b && matches!(t, GgmlType::Q3K | GgmlType::Q4K) {
                    GgmlType::Q5K
                } else {
                    t
                };
                // `llama-quant.cpp:311`, after that: 8 experts -> Q8_0,
                // overriding everything the chain and the 70B bump
                // decided. Last write wins, which is why this is not a
                // table row.
                let t = if self.shape.n_expert == 8 {
                    GgmlType::Q8_0
                } else {
                    t
                };
                self.i_attention_wv += 1;
                t
            }
            Role::AttnK => {
                // `llama-quant.cpp:319`. No counter: upstream does not
                // increment anything on this arm.
                if self.shape.n_expert == 8 {
                    GgmlType::Q8_0
                } else {
                    default
                }
            }
            Role::FfnDown => {
                let (i, n) = self.ffn_layer(name, self.i_ffn_down)?;
                let t = if falcon && self.target == Target::Q4_K_M {
                    // The one arm that needs `i < n/16`.
                    if i < n / 16 {
                        FALCON_Q4KM_FFN_DOWN_SIXTEENTH
                    } else if When::UseMoreBits.holds(i, n) {
                        GgmlType::Q5K
                    } else {
                        default
                    }
                } else {
                    self.chain(role, i, n, default)
                };
                self.i_ffn_down += 1;
                t
            }
            Role::AttnOutput => {
                // `llama-quant.cpp:390`: the only Q4_K arm here is the
                // 8-expert one, and it is inside `if (arch != FALCON)`.
                if !falcon
                    && self.shape.n_expert == 8
                    && matches!(self.target, Target::Q4_K_S | Target::Q4_K_M)
                {
                    GgmlType::Q5K
                } else {
                    default
                }
            }
            Role::FfnGate => {
                let (i, n) = self.ffn_layer(name, self.i_ffn_gate)?;
                let t = self.chain(role, i, n, default);
                self.i_ffn_gate += 1;
                t
            }
            Role::FfnUp => {
                let (i, n) = self.ffn_layer(name, self.i_ffn_up)?;
                let t = self.chain(role, i, n, default);
                self.i_ffn_up += 1;
                t
            }
            Role::AttnQ | Role::TokenEmbd | Role::FfnLatent | Role::AttnGate | Role::Other => {
                self.chain(role, 0, 0, default)
            }
        };

        // RAON1_MINI's floors, after the counters (`:745-773`).
        let ty = if self.shape.arch == QuantArch::Raon1Mini {
            arch::raon_floor(self.target, role, name, ty)
        } else {
            ty
        };

        // `llama-quant.cpp:436`: the chosen type is then checked
        // against the tensor's row length, and an awkward row falls
        // back to a DIFFERENT type. frink refuses that case in `plan`
        // instead of following the fallback, because it would need Q5_0
        // and Q5_1 encoders it does not have -- so this returns the
        // type llama.cpp would have picked and the caller stops.
        Ok(ty)
    }

    /// `llama-quant.cpp:207`, the two arms above the K-quant one.
    fn output_head_type(&self, shape: &[u64], default: GgmlType) -> GgmlType {
        let nx = shape.first().copied().unwrap_or(0) as usize;
        let qk_k = default.block_layout().1;
        if self.shape.arch == QuantArch::Falcon || qk_k == 0 || !nx.is_multiple_of(qk_k) {
            return GgmlType::Q8_0;
        }
        // `else if (new_type != GGML_TYPE_Q8_0) new_type = Q6_K;`
        self.chain(Role::Output, 0, 0, default)
    }

    /// First matching row of [`PROMOTIONS`] for this role and mix, or
    /// the default type.
    fn chain(&self, role: Role, i: usize, n: usize, default: GgmlType) -> GgmlType {
        for p in PROMOTIONS {
            if p.role != role || p.ftype != self.target {
                continue;
            }
            if p.not_falcon && self.shape.arch == QuantArch::Falcon {
                continue;
            }
            if p.when.holds(i, n) {
                return p.to;
            }
            // Upstream's chain: an arm whose ftype matches but whose
            // condition fails falls THROUGH to the next `else if`, it
            // does not stop the chain. So this keeps scanning.
        }
        default
    }

    /// Every eligible tensor's type, keyed by name. `tensors` is every
    /// tensor of the file: name, shape and source type.
    ///
    /// This is the entry point the planner uses, and it exists because
    /// the ORDER the counters see is llama.cpp's and not the file's.
    /// Sorting here rather than at the call site means a caller cannot
    /// get it wrong by iterating the obvious thing -- which is exactly
    /// what happened: walking `file.tensors` gave 12 of Llama-3.2-1B's
    /// 113 tensors a different type from `llama-quantize`, and the file
    /// still loaded and answered.
    ///
    /// `eligible` decides which tensors llama.cpp would call
    /// `llama_tensor_get_type` for; it is `policy::allows_quantization`
    /// in production and is passed in so this module does not have to
    /// depend on the keep-list to be tested.
    pub fn resolve_all<F>(
        target: Target,
        shape: ModelShape,
        tensors: &[(String, Vec<u64>, GgmlType)],
        eligible: F,
    ) -> Result<BTreeMap<String, GgmlType>>
    where
        F: Fn(&str, &[u64]) -> bool,
    {
        let names: Vec<String> = tensors.iter().map(|(n, _, _)| n.clone()).collect();
        let mut recipe = Recipe::new(target, shape, &names);

        let mut order: Vec<usize> = (0..tensors.len()).collect();
        order.sort_by(|&a, &b| llama_cpp_weight_order(&tensors[a].0, &tensors[b].0));

        let mut out = BTreeMap::new();
        for i in order {
            let (name, shape, source) = &tensors[i];
            if eligible(name, shape) {
                out.insert(name.clone(), recipe.tensor_type(name, shape, *source)?);
            }
        }
        Ok(out)
    }

    /// `layer_info` (`ee467158:src/llama-quant.cpp:525`): the layer index
    /// for an FFN tensor, and the denominator (`n_layer_all`).
    ///
    /// On a dense model this is the running counter. On a MoE model
    /// (`n_expert > 1`) upstream scans `blk.%d.` out of the name instead,
    /// because Mixtral's expert FFN tensors are not in layer order in the
    /// file and the counter would name the wrong layer. A decision head's
    /// `dec.blk.%d.` is read the same way, unchecked. A name neither scan
    /// reads, or a `blk.` layer outside `[0, n_layer)`, is a `throw`
    /// upstream, and a refusal here.
    fn ffn_layer(&self, name: &str, counter: usize) -> Result<(usize, usize)> {
        let n = self.shape.n_layer;
        if self.shape.n_expert.max(1) <= 1 {
            return Ok((counter, n));
        }
        if let Some(i) = scan_layer(name, "blk.") {
            if i < 0 || i >= n as i64 {
                bail!(
                    "tensor {name} is in layer {i} of a {n}-layer mixture-of-experts checkpoint; \
                     llama-quantize stops here (`Bad layer {i} for tensor {name}. Must be in [0, \
                     {n})`), and so does frink"
                );
            }
            return Ok((i as usize, n));
        }
        match scan_layer(name, "dec.blk.") {
            // The decision head's blocks are numbered from 0 and treated
            // like backbone layer N. A negative N reaches `use_more_bits`
            // as a negative int upstream; it cannot be a usize here.
            Some(i) if i >= 0 => Ok((i as usize, n)),
            _ => bail!(
                "cannot tell which layer {name} is in, and on a mixture-of-experts checkpoint \
                 llama-quantize reads the FFN layer from the name (`Failed to determine layer \
                 for tensor {name}`); frink stops too"
            ),
        }
    }
}

#[cfg(test)]
mod tests;