frink-cli 0.75.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
//! What `llama-quantize` actually chose, tensor by tensor, for a real
//! checkpoint -- and the test that [`super::recipe`] chooses the same.
//!
//! Every other test of the recipe checks it against a reading of
//! `llama_tensor_get_type`. This one checks it against the BINARY:
//! llama.cpp b7650's `llama-quantize` was run over an F16 Llama-3.2-1B
//! three times, once per mix, and the types below were read back out of
//! its three output files with frink's own GGUF reader. A transcription
//! that is wrong in the same way twice -- in the code and in a test that
//! restates the code -- cannot survive this, because nothing here came
//! from reading the C.
//!
//! # Reproducing it
//!
//! The local checkpoints are all already quantized and both quantizers
//! refuse a quantized source, so the F16 input was made by dequantizing
//! `models/Llama-3.2-1B-Instruct-Q8_0.gguf` through frink's reader and
//! re-emitting every tensor as F16. Then, for each of `Q4_K_M`,
//! `Q5_K_M`, `Q6_K`:
//!
//! ```text
//! llama-quantize llama1b-f16.gguf llama1b-<MIX>.gguf <MIX> 8
//! ```
//!
//! and the three outputs' tensor types were dumped and pasted below.
//!
//! # Why this model
//!
//! Llama-3.2-1B has TIED EMBEDDINGS: there is no `output.weight`, so
//! `token_embd.weight` takes the output head's arm and comes back Q6_K
//! under every mix. That is the branch a recipe is most likely to miss,
//! because on an untied model the same code path is invisible -- and it
//! is the norm on every modern small model. 16 layers also makes
//! `use_more_bits` pick a non-trivial pattern (0, 1, 4, 7, 10, 13, 14,
//! 15) rather than everything or nothing.
//!
//! # What it does NOT cover
//!
//! One architecture, dense, not Falcon, not 70B, not 8-expert, no fused
//! QKV. The fused QKV arm is the pin's binary's answer in
//! [`super::recipe_golden_qwen35`]; Falcon, 70B, 8 experts and the
//! architecture-specific rules are the pin's binary's answers in
//! [`super::recipe_golden_arch`].

use frink_gguf::GgmlType;

use super::arch::QuantArch;
use super::model_shape::ModelShape;
use super::policy::{allows_quantization, Target};
use super::recipe::Recipe;

/// `llama-quantize` b7650's own answer for every tensor of an F16
/// Llama-3.2-1B.
///
/// The rows are in the order llama.cpp's OUTPUT file carries them,
/// which is `weight_name_comparer` order (layer number, then name) --
/// not the order the F16 input carried them in. The test below feeds
/// them to `resolve_all` in a deliberately different order and expects
/// the same answers, because sorting into llama.cpp's order is
/// `resolve_all`'s job and a test that handed them over already sorted
/// would not notice if it stopped doing it.
///
/// Columns: tensor name, its SHAPE, then the type chosen under
/// `Q4_K_M`, `Q5_K_M` and `Q6_K`. `-` is a tensor llama.cpp left at
/// source precision, so this table is also the keep-list's evidence --
/// and the shape is the real one, because the 1-D rule is half of that
/// keep-list and a first version carrying only the leading dimension
/// made `rope_freqs.weight` look 2-D and hid it.
///
/// ONE table rather than a name list plus a type list: the two would
/// have had to agree about order, and order is exactly what decides
/// which layers `use_more_bits` promotes.
const LLAMA_QUANTIZE_CHOSE: &str = "\
output_norm.weight        2048         -   -   -  
rope_freqs.weight         32           -   -   -  
token_embd.weight         2048x128256  Q6K Q6K Q6K
blk.0.attn_k.weight       2048x512     Q4K Q5K Q6K
blk.0.attn_norm.weight    2048         -   -   -  
blk.0.attn_output.weight  2048x2048    Q4K Q5K Q6K
blk.0.attn_q.weight       2048x2048    Q4K Q5K Q6K
blk.0.attn_v.weight       2048x512     Q6K Q6K Q6K
blk.0.ffn_down.weight     8192x2048    Q6K Q6K Q6K
blk.0.ffn_gate.weight     2048x8192    Q4K Q5K Q6K
blk.0.ffn_norm.weight     2048         -   -   -  
blk.0.ffn_up.weight       2048x8192    Q4K Q5K Q6K
blk.1.attn_k.weight       2048x512     Q4K Q5K Q6K
blk.1.attn_norm.weight    2048         -   -   -  
blk.1.attn_output.weight  2048x2048    Q4K Q5K Q6K
blk.1.attn_q.weight       2048x2048    Q4K Q5K Q6K
blk.1.attn_v.weight       2048x512     Q6K Q6K Q6K
blk.1.ffn_down.weight     8192x2048    Q6K Q6K Q6K
blk.1.ffn_gate.weight     2048x8192    Q4K Q5K Q6K
blk.1.ffn_norm.weight     2048         -   -   -  
blk.1.ffn_up.weight       2048x8192    Q4K Q5K Q6K
blk.2.attn_k.weight       2048x512     Q4K Q5K Q6K
blk.2.attn_norm.weight    2048         -   -   -  
blk.2.attn_output.weight  2048x2048    Q4K Q5K Q6K
blk.2.attn_q.weight       2048x2048    Q4K Q5K Q6K
blk.2.attn_v.weight       2048x512     Q4K Q5K Q6K
blk.2.ffn_down.weight     8192x2048    Q4K Q5K Q6K
blk.2.ffn_gate.weight     2048x8192    Q4K Q5K Q6K
blk.2.ffn_norm.weight     2048         -   -   -  
blk.2.ffn_up.weight       2048x8192    Q4K Q5K Q6K
blk.3.attn_k.weight       2048x512     Q4K Q5K Q6K
blk.3.attn_norm.weight    2048         -   -   -  
blk.3.attn_output.weight  2048x2048    Q4K Q5K Q6K
blk.3.attn_q.weight       2048x2048    Q4K Q5K Q6K
blk.3.attn_v.weight       2048x512     Q4K Q5K Q6K
blk.3.ffn_down.weight     8192x2048    Q4K Q5K Q6K
blk.3.ffn_gate.weight     2048x8192    Q4K Q5K Q6K
blk.3.ffn_norm.weight     2048         -   -   -  
blk.3.ffn_up.weight       2048x8192    Q4K Q5K Q6K
blk.4.attn_k.weight       2048x512     Q4K Q5K Q6K
blk.4.attn_norm.weight    2048         -   -   -  
blk.4.attn_output.weight  2048x2048    Q4K Q5K Q6K
blk.4.attn_q.weight       2048x2048    Q4K Q5K Q6K
blk.4.attn_v.weight       2048x512     Q6K Q6K Q6K
blk.4.ffn_down.weight     8192x2048    Q6K Q6K Q6K
blk.4.ffn_gate.weight     2048x8192    Q4K Q5K Q6K
blk.4.ffn_norm.weight     2048         -   -   -  
blk.4.ffn_up.weight       2048x8192    Q4K Q5K Q6K
blk.5.attn_k.weight       2048x512     Q4K Q5K Q6K
blk.5.attn_norm.weight    2048         -   -   -  
blk.5.attn_output.weight  2048x2048    Q4K Q5K Q6K
blk.5.attn_q.weight       2048x2048    Q4K Q5K Q6K
blk.5.attn_v.weight       2048x512     Q4K Q5K Q6K
blk.5.ffn_down.weight     8192x2048    Q4K Q5K Q6K
blk.5.ffn_gate.weight     2048x8192    Q4K Q5K Q6K
blk.5.ffn_norm.weight     2048         -   -   -  
blk.5.ffn_up.weight       2048x8192    Q4K Q5K Q6K
blk.6.attn_k.weight       2048x512     Q4K Q5K Q6K
blk.6.attn_norm.weight    2048         -   -   -  
blk.6.attn_output.weight  2048x2048    Q4K Q5K Q6K
blk.6.attn_q.weight       2048x2048    Q4K Q5K Q6K
blk.6.attn_v.weight       2048x512     Q4K Q5K Q6K
blk.6.ffn_down.weight     8192x2048    Q4K Q5K Q6K
blk.6.ffn_gate.weight     2048x8192    Q4K Q5K Q6K
blk.6.ffn_norm.weight     2048         -   -   -  
blk.6.ffn_up.weight       2048x8192    Q4K Q5K Q6K
blk.7.attn_k.weight       2048x512     Q4K Q5K Q6K
blk.7.attn_norm.weight    2048         -   -   -  
blk.7.attn_output.weight  2048x2048    Q4K Q5K Q6K
blk.7.attn_q.weight       2048x2048    Q4K Q5K Q6K
blk.7.attn_v.weight       2048x512     Q6K Q6K Q6K
blk.7.ffn_down.weight     8192x2048    Q6K Q6K Q6K
blk.7.ffn_gate.weight     2048x8192    Q4K Q5K Q6K
blk.7.ffn_norm.weight     2048         -   -   -  
blk.7.ffn_up.weight       2048x8192    Q4K Q5K Q6K
blk.8.attn_k.weight       2048x512     Q4K Q5K Q6K
blk.8.attn_norm.weight    2048         -   -   -  
blk.8.attn_output.weight  2048x2048    Q4K Q5K Q6K
blk.8.attn_q.weight       2048x2048    Q4K Q5K Q6K
blk.8.attn_v.weight       2048x512     Q4K Q5K Q6K
blk.8.ffn_down.weight     8192x2048    Q4K Q5K Q6K
blk.8.ffn_gate.weight     2048x8192    Q4K Q5K Q6K
blk.8.ffn_norm.weight     2048         -   -   -  
blk.8.ffn_up.weight       2048x8192    Q4K Q5K Q6K
blk.9.attn_k.weight       2048x512     Q4K Q5K Q6K
blk.9.attn_norm.weight    2048         -   -   -  
blk.9.attn_output.weight  2048x2048    Q4K Q5K Q6K
blk.9.attn_q.weight       2048x2048    Q4K Q5K Q6K
blk.9.attn_v.weight       2048x512     Q4K Q5K Q6K
blk.9.ffn_down.weight     8192x2048    Q4K Q5K Q6K
blk.9.ffn_gate.weight     2048x8192    Q4K Q5K Q6K
blk.9.ffn_norm.weight     2048         -   -   -  
blk.9.ffn_up.weight       2048x8192    Q4K Q5K Q6K
blk.10.attn_k.weight      2048x512     Q4K Q5K Q6K
blk.10.attn_norm.weight   2048         -   -   -  
blk.10.attn_output.weight 2048x2048    Q4K Q5K Q6K
blk.10.attn_q.weight      2048x2048    Q4K Q5K Q6K
blk.10.attn_v.weight      2048x512     Q6K Q6K Q6K
blk.10.ffn_down.weight    8192x2048    Q6K Q6K Q6K
blk.10.ffn_gate.weight    2048x8192    Q4K Q5K Q6K
blk.10.ffn_norm.weight    2048         -   -   -  
blk.10.ffn_up.weight      2048x8192    Q4K Q5K Q6K
blk.11.attn_k.weight      2048x512     Q4K Q5K Q6K
blk.11.attn_norm.weight   2048         -   -   -  
blk.11.attn_output.weight 2048x2048    Q4K Q5K Q6K
blk.11.attn_q.weight      2048x2048    Q4K Q5K Q6K
blk.11.attn_v.weight      2048x512     Q4K Q5K Q6K
blk.11.ffn_down.weight    8192x2048    Q4K Q5K Q6K
blk.11.ffn_gate.weight    2048x8192    Q4K Q5K Q6K
blk.11.ffn_norm.weight    2048         -   -   -  
blk.11.ffn_up.weight      2048x8192    Q4K Q5K Q6K
blk.12.attn_k.weight      2048x512     Q4K Q5K Q6K
blk.12.attn_norm.weight   2048         -   -   -  
blk.12.attn_output.weight 2048x2048    Q4K Q5K Q6K
blk.12.attn_q.weight      2048x2048    Q4K Q5K Q6K
blk.12.attn_v.weight      2048x512     Q4K Q5K Q6K
blk.12.ffn_down.weight    8192x2048    Q4K Q5K Q6K
blk.12.ffn_gate.weight    2048x8192    Q4K Q5K Q6K
blk.12.ffn_norm.weight    2048         -   -   -  
blk.12.ffn_up.weight      2048x8192    Q4K Q5K Q6K
blk.13.attn_k.weight      2048x512     Q4K Q5K Q6K
blk.13.attn_norm.weight   2048         -   -   -  
blk.13.attn_output.weight 2048x2048    Q4K Q5K Q6K
blk.13.attn_q.weight      2048x2048    Q4K Q5K Q6K
blk.13.attn_v.weight      2048x512     Q6K Q6K Q6K
blk.13.ffn_down.weight    8192x2048    Q6K Q6K Q6K
blk.13.ffn_gate.weight    2048x8192    Q4K Q5K Q6K
blk.13.ffn_norm.weight    2048         -   -   -  
blk.13.ffn_up.weight      2048x8192    Q4K Q5K Q6K
blk.14.attn_k.weight      2048x512     Q4K Q5K Q6K
blk.14.attn_norm.weight   2048         -   -   -  
blk.14.attn_output.weight 2048x2048    Q4K Q5K Q6K
blk.14.attn_q.weight      2048x2048    Q4K Q5K Q6K
blk.14.attn_v.weight      2048x512     Q6K Q6K Q6K
blk.14.ffn_down.weight    8192x2048    Q6K Q6K Q6K
blk.14.ffn_gate.weight    2048x8192    Q4K Q5K Q6K
blk.14.ffn_norm.weight    2048         -   -   -  
blk.14.ffn_up.weight      2048x8192    Q4K Q5K Q6K
blk.15.attn_k.weight      2048x512     Q4K Q5K Q6K
blk.15.attn_norm.weight   2048         -   -   -  
blk.15.attn_output.weight 2048x2048    Q4K Q5K Q6K
blk.15.attn_q.weight      2048x2048    Q4K Q5K Q6K
blk.15.attn_v.weight      2048x512     Q6K Q6K Q6K
blk.15.ffn_down.weight    8192x2048    Q6K Q6K Q6K
blk.15.ffn_gate.weight    2048x8192    Q4K Q5K Q6K
blk.15.ffn_norm.weight    2048         -   -   -  
blk.15.ffn_up.weight      2048x8192    Q4K Q5K Q6K";

/// Llama-3.2-1B's header, as `ModelShape::from_header` would read it.
/// Spelled out because the test does not open the 2.3 GB F16 file.
const LLAMA_3_2_1B: ModelShape = ModelShape {
    arch: QuantArch::Other,
    n_layer: 16,
    n_expert: 0,
    // 16 layers, not 80.
    is_70b: false,
};

pub(super) struct Row<const N: usize> {
    pub(super) name: &'static str,
    pub(super) shape: Vec<u64>,
    /// `None` where llama.cpp kept the tensor at source precision.
    pub(super) chosen: Option<[GgmlType; N]>,
}

/// A golden's type spelling: frink's `GgmlType` names, `F32` for a
/// tensor the mix leaves at (F32) source precision.
fn golden_type(name: &str, t: &str) -> GgmlType {
    match t {
        "Q4K" => GgmlType::Q4K,
        "Q5K" => GgmlType::Q5K,
        "Q6K" => GgmlType::Q6K,
        "Q8_0" => GgmlType::Q8_0,
        "Q4_0" => GgmlType::Q4_0,
        "F16" => GgmlType::F16,
        "F32" => GgmlType::F32,
        other => panic!("{name}: unknown type {other} in the golden"),
    }
}

/// One golden table's rows: name, shape, then `N` type columns. Lines
/// starting with `#` are the header and are skipped here.
pub(super) fn rows<const N: usize>(table: &'static str) -> Vec<Row<N>> {
    table
        .lines()
        .filter(|l| !l.starts_with('#') && !l.trim().is_empty())
        .map(|line| {
            let mut f = line.split_whitespace();
            let name = f.next().expect("name");
            let shape: Vec<u64> = f
                .next()
                .expect("shape")
                .split('x')
                .map(|d| d.parse().expect("shape dimension"))
                .collect();
            let tys: Vec<&str> = f.collect();
            assert_eq!(tys.len(), N, "{name}: expected {N} type columns");
            let chosen = if tys[0] == "-" {
                assert!(tys.iter().all(|t| *t == "-"), "{name}: mixed - and types");
                None
            } else {
                Some(std::array::from_fn(|i| golden_type(name, tys[i])))
            };
            Row {
                name,
                shape,
                chosen,
            }
        })
        .collect()
}

/// The mixes, in the order their columns appear in the golden.
const MIXES: [Target; 3] = [Target::Q4_K_M, Target::Q5_K_M, Target::Q6_K];

/// Every tensor of `table` gets, under each of `mixes`, the type
/// `llama-quantize` chose, and the keep-list agrees on the rest. The
/// rows are handed over reversed, so `resolve_all` must sort them back
/// into llama.cpp's order itself. `source` is the tensors' type in the
/// file `llama-quantize` read. A row whose type is a shared-KV layer's
/// Q4_0 under another target is the planner's override, not the mix's,
/// so it is counted and left to `recipe_golden_arch`'s plan test.
/// Returns how many tensors each mix quantized.
pub(super) fn assert_frink_chooses_what_llama_quantize_chose<const N: usize>(
    table: &'static str,
    mixes: [Target; N],
    shape: ModelShape,
    source: GgmlType,
) -> usize {
    let rows = rows::<N>(table);
    let arch = shape.arch;
    let scrambled: Vec<(String, Vec<u64>, GgmlType)> = rows
        .iter()
        .rev()
        .map(|r| (r.name.to_string(), r.shape.clone(), source))
        .collect();
    let mut per_mix = None;
    for (col, mix) in mixes.iter().enumerate() {
        let got = Recipe::resolve_all(*mix, shape, false, &scrambled, |name, shape| {
            allows_quantization(arch, name, shape).is_none()
        })
        .expect("llama-quantize quantized this file");
        let mut quantized = 0;
        for r in &rows {
            let allowed = allows_quantization(arch, r.name, &r.shape);
            match (&r.chosen, allowed) {
                (Some(want), None) => {
                    quantized += 1;
                    if want[col] == GgmlType::Q4_0 && *mix != Target::Q4_0 {
                        continue;
                    }
                    let have = got[r.name];
                    assert_eq!(
                        have, want[col],
                        "{:?}: {} -> frink {:?}, llama-quantize {:?}",
                        mix, r.name, have, want[col]
                    );
                }
                (None, Some(_)) => assert!(!got.contains_key(r.name), "{}", r.name),
                (Some(_), Some(reason)) => panic!(
                    "{}: llama-quantize quantized it, frink keeps it at source precision \
                     ({reason})",
                    r.name
                ),
                (None, None) => panic!(
                    "{}: llama-quantize kept it at source precision, frink would quantize it",
                    r.name
                ),
            }
        }
        assert_eq!(
            got.len(),
            quantized,
            "{mix:?}: resolve_all returned extra tensors"
        );
        assert_eq!(
            *per_mix.get_or_insert(quantized),
            quantized,
            "{mix:?}: a different tensor count from the first mix"
        );
    }
    per_mix.unwrap_or(0)
}

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

    /// For a real model's tensor list, the type frink chooses per
    /// tensor equals the type `llama-quantize` chose.
    ///
    /// This is the whole point of `recipe.rs`. Every disagreement it
    /// can catch is a file that would load, run, report the right
    /// `general.file_type`, and not be the file its name promises.
    #[test]
    fn frink_chooses_the_same_type_llama_quantize_chose_for_every_tensor() {
        assert_eq!(
            rows::<3>(LLAMA_QUANTIZE_CHOSE).len(),
            147,
            "the golden lost rows"
        );
        // Reversed inside: before `resolve_all` sorted, twelve of these
        // tensors came out wrong.
        let quantized = assert_frink_chooses_what_llama_quantize_chose(
            LLAMA_QUANTIZE_CHOSE,
            MIXES,
            LLAMA_3_2_1B,
            GgmlType::F16,
        );
        assert_eq!(quantized, 113, "wrong number of quantized tensors");
    }

    /// The golden is not three copies of one column. If it were, the
    /// test above would pass for a recipe that ignored the mix.
    #[test]
    fn the_three_mixes_actually_disagree_in_the_golden() {
        let rows = rows::<3>(LLAMA_QUANTIZE_CHOSE);
        let differing = rows
            .iter()
            .filter_map(|r| r.chosen.as_ref())
            .filter(|c| c[0] != c[1] || c[1] != c[2])
            .count();
        assert!(
            differing > 50,
            "only {differing} tensors differ between mixes"
        );
        // And within one mix, more than one type is chosen -- otherwise
        // a uniform file would pass.
        for col in 0..3 {
            let distinct: std::collections::BTreeSet<_> = rows
                .iter()
                .filter_map(|r| r.chosen.as_ref())
                .map(|c| format!("{:?}", c[col]))
                .collect();
            let want = if col == 2 { 1 } else { 2 };
            assert_eq!(
                distinct.len(),
                want,
                "{:?} column has types {distinct:?}",
                MIXES[col]
            );
        }
    }
}