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
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
//! Synthetic tests of [`super::Recipe`] against a reading of the C.
//! The binary's own answers are in `recipe_golden*`.
use super::*;

fn shape(n_layer: usize) -> ModelShape {
    ModelShape {
        n_layer,
        n_expert: 0,
        arch: QuantArch::Other,
        is_70b: false,
    }
}

fn names(n_layer: usize, fused_qkv: bool) -> Vec<String> {
    let mut v = vec!["token_embd.weight".to_string()];
    for i in 0..n_layer {
        if fused_qkv {
            v.push(format!("blk.{i}.attn_qkv.weight"));
        } else {
            v.push(format!("blk.{i}.attn_q.weight"));
            v.push(format!("blk.{i}.attn_k.weight"));
            v.push(format!("blk.{i}.attn_v.weight"));
        }
        v.push(format!("blk.{i}.attn_output.weight"));
        v.push(format!("blk.{i}.ffn_gate.weight"));
        v.push(format!("blk.{i}.ffn_up.weight"));
        v.push(format!("blk.{i}.ffn_down.weight"));
    }
    v.push("output.weight".to_string());
    v
}

/// Walks a synthetic tensor list the way the quantizer does and
/// returns every tensor's chosen type.
fn walk(target: Target, sh: ModelShape, names: &[String]) -> Vec<(String, GgmlType)> {
    let mut r = Recipe::new(target, sh, names);
    names
        .iter()
        .map(|n| {
            (
                n.clone(),
                r.tensor_type(n, &[4096, 4096], GgmlType::F16).unwrap(),
            )
        })
        .collect()
}

/// `use_more_bits` is C's integer arithmetic, and getting it wrong
/// is invisible on a small model and wrong on a large one. These
/// are the values upstream's expression produces for n = 32.
#[test]
fn use_more_bits_is_llama_cpps_integer_arithmetic() {
    let n = 32;
    let got: Vec<usize> = (0..n).filter(|&i| When::UseMoreBits.holds(i, n)).collect();
    // i < 4, or i >= 28, or (i - 4) % 3 == 2 -> 6, 9, 12, ...
    assert_eq!(
        got,
        vec![0, 1, 2, 3, 6, 9, 12, 15, 18, 21, 24, 27, 28, 29, 30, 31]
    );
    // n = 0 must not divide by zero or panic on the subtraction.
    assert!(!When::UseMoreBits.holds(0, 0));
}

/// The output head is the promotion everyone notices, because it
/// is the one that makes a "Q4_K_M" file bigger than uniform Q4_K.
#[test]
fn every_k_quant_mix_sends_the_output_head_to_q6_k() {
    for t in [
        Target::Q4_K_S,
        Target::Q4_K_M,
        Target::Q5_K_S,
        Target::Q5_K_M,
    ] {
        let ns = names(4, false);
        let got = walk(t, shape(4), &ns);
        let out = got.iter().find(|(n, _)| n == "output.weight").unwrap();
        assert_eq!(out.1, GgmlType::Q6K, "{t:?}");
        // And token_embd is NOT promoted when a real output head
        // exists -- it takes the default.
        let emb = got.iter().find(|(n, _)| n == "token_embd.weight").unwrap();
        assert_eq!(emb.1, t.ggml_type(), "{t:?} token_embd");
    }
    // Q6_K's own head is already Q6_K.
    let ns = names(4, false);
    let got = walk(Target::Q6_K, shape(4), &ns);
    assert_eq!(
        got.iter().find(|(n, _)| n == "output.weight").unwrap().1,
        GgmlType::Q6K
    );
}

/// With tied embeddings there is no `output.weight`, and
/// `token_embd.weight` inherits the output head's type. A recipe
/// that missed this would leave a Q4_K embedding table where
/// llama.cpp writes Q6_K -- on every modern small model, since
/// tied embeddings are the norm there.
#[test]
fn a_tied_embedding_table_gets_the_output_heads_type() {
    let ns: Vec<String> = names(4, false)
        .into_iter()
        .filter(|n| n != "output.weight")
        .collect();
    let got = walk(Target::Q4_K_M, shape(4), &ns);
    assert_eq!(
        got.iter()
            .find(|(n, _)| n == "token_embd.weight")
            .unwrap()
            .1,
        GgmlType::Q6K
    );
}

/// The per-layer half of the mix: `attn_v` and `ffn_down` are
/// promoted on the layers `use_more_bits` selects and left at the
/// default elsewhere. A recipe that promoted all of them or none of
/// them would still produce a loadable file of the wrong size.
#[test]
fn q4_k_m_promotes_attn_v_and_ffn_down_on_exactly_the_use_more_bits_layers() {
    let n = 16;
    let ns = names(n, false);
    let got = walk(Target::Q4_K_M, shape(n), &ns);
    for (role, want_hits) in [("attn_v", true), ("ffn_down", true)] {
        let hits: Vec<usize> = got
            .iter()
            .filter(|(name, _)| name.contains(role))
            .enumerate()
            .filter(|(_, (_, t))| *t == GgmlType::Q6K)
            .map(|(i, _)| i)
            .collect();
        let want: Vec<usize> = (0..n).filter(|&i| When::UseMoreBits.holds(i, n)).collect();
        assert_eq!(hits, want, "{role}");
        assert!(want_hits && !hits.is_empty());
    }
    // attn_q and attn_k are untouched by this mix.
    for (name, t) in &got {
        if name.contains("attn_q.weight") || name.contains("attn_k.weight") {
            assert_eq!(*t, GgmlType::Q4K, "{name}");
        }
    }
}

/// Q4_K_S promotes a fixed prefix, not a `use_more_bits` pattern:
/// the first four `attn_v` and the first eighth of `ffn_down`. Two
/// different conditions on two roles in one mix, which is why
/// `When` is per row rather than per mix.
#[test]
fn q4_k_s_promotes_a_prefix_where_q4_k_m_promotes_a_pattern() {
    let n = 16;
    let ns = names(n, false);
    let got = walk(Target::Q4_K_S, shape(n), &ns);
    let v: Vec<GgmlType> = got
        .iter()
        .filter(|(name, _)| name.contains("attn_v"))
        .map(|(_, t)| *t)
        .collect();
    assert_eq!(&v[..4], &[GgmlType::Q5K; 4]);
    assert!(v[4..].iter().all(|t| *t == GgmlType::Q4K));
    let d: Vec<GgmlType> = got
        .iter()
        .filter(|(name, _)| name.contains("ffn_down"))
        .map(|(_, t)| *t)
        .collect();
    assert_eq!(&d[..2], &[GgmlType::Q5K; 2]); // n/8 == 2
    assert!(d[2..].iter().all(|t| *t == GgmlType::Q4K));
}

/// A fused-QKV checkpoint's `attn_qkv` takes the `attn_v` arm at the
/// pin (`category_is_attn_v`, #714): promoted on the `use_more_bits`
/// layers under Q4_K_M and Q5_K_M and on the first four under
/// Q4_K_S, with `n_attention_wv` counting them and `i_attention_wv`
/// advancing on them. b7650 gave every one a flat Q5_K / Q6_K.
#[test]
fn a_fused_qkv_checkpoint_takes_the_attn_v_arm() {
    let n = 16;
    let ns = names(n, true);
    let qkv = |target: Target| -> Vec<GgmlType> {
        walk(target, shape(n), &ns)
            .into_iter()
            .filter(|(name, _)| name.contains("attn_qkv"))
            .map(|(_, t)| t)
            .collect()
    };
    let pattern: Vec<bool> = (0..n).map(|i| When::UseMoreBits.holds(i, n)).collect();
    for (target, promoted, plain) in [
        (Target::Q4_K_M, GgmlType::Q6K, GgmlType::Q4K),
        (Target::Q5_K_M, GgmlType::Q6K, GgmlType::Q5K),
    ] {
        let want: Vec<GgmlType> = pattern
            .iter()
            .map(|&p| if p { promoted } else { plain })
            .collect();
        assert_eq!(qkv(target), want, "{target:?}");
    }
    let s = qkv(Target::Q4_K_S);
    assert_eq!(&s[..4], &[GgmlType::Q5K; 4]);
    assert!(s[4..].iter().all(|t| *t == GgmlType::Q4K));
    let r = Recipe::new(Target::Q4_K_M, shape(n), &ns);
    assert_eq!(r.n_attention_wv, n);
}

/// The three post-chain overrides, each of which must beat the row
/// the chain picked. Encoding them as rows would have let the chain
/// win instead, and on a Mixtral that is the difference between a
/// Q8_0 and a Q6_K `attn_v`.
#[test]
fn the_post_chain_overrides_beat_the_chain_row_they_follow() {
    let n = 16;
    let ns = names(n, false);

    // 8 experts: attn_v and attn_k go to Q8_0 even on a layer where
    // `use_more_bits` had already promoted attn_v to Q6_K.
    let moe = ModelShape {
        n_expert: 8,
        ..shape(n)
    };
    let got = walk(Target::Q4_K_M, moe, &ns);
    assert!(got
        .iter()
        .filter(|(name, _)| name.contains("attn_v") || name.contains("attn_k"))
        .all(|(_, t)| *t == GgmlType::Q8_0));
    // attn_output picks up the 8-expert Q5_K arm.
    assert!(got
        .iter()
        .filter(|(name, _)| name.contains("attn_output"))
        .all(|(_, t)| *t == GgmlType::Q5K));

    // 70B: an attn_v the chain left at Q4_K becomes Q5_K, and one
    // the chain promoted to Q6_K stays Q6_K.
    let big = ModelShape {
        is_70b: true,
        ..shape(n)
    };
    let got = walk(Target::Q4_K_M, big, &ns);
    let v: Vec<GgmlType> = got
        .iter()
        .filter(|(name, _)| name.contains("attn_v"))
        .map(|(_, t)| *t)
        .collect();
    for (i, t) in v.iter().enumerate() {
        let want = if When::UseMoreBits.holds(i, n) {
            GgmlType::Q6K
        } else {
            GgmlType::Q5K
        };
        assert_eq!(*t, want, "layer {i}");
    }

    // Falcon: the output head goes to Q8_0, not Q6_K.
    let falcon = ModelShape {
        arch: QuantArch::Falcon,
        ..shape(n)
    };
    let got = walk(Target::Q4_K_M, falcon, &ns);
    assert_eq!(
        got.iter().find(|(n, _)| n == "output.weight").unwrap().1,
        GgmlType::Q8_0
    );
}

/// An output head whose row length is not a whole number of the
/// default type's blocks goes to Q8_0, whose blocks are 32 wide.
/// This is the arm that fires on a vocabulary that is not a
/// multiple of 256, and it is above the Q6_K arm.
#[test]
fn an_output_head_with_an_awkward_row_length_goes_to_q8_0() {
    let ns = names(2, false);
    let mut r = Recipe::new(Target::Q4_K_M, shape(2), &ns);
    assert_eq!(
        r.tensor_type("output.weight", &[4096 + 32, 100], GgmlType::F16)
            .unwrap(),
        GgmlType::Q8_0
    );
    let mut r = Recipe::new(Target::Q4_K_M, shape(2), &ns);
    assert_eq!(
        r.tensor_type("output.weight", &[4096, 100], GgmlType::F16)
            .unwrap(),
        GgmlType::Q6K
    );
}

/// A gate that reads as coverage: every type the table can produce
/// must be one this build can actually encode. Adding a row naming
/// a type with no encoder would otherwise produce a plan that
/// refuses only once a tensor reaches the encoder dispatch, halfway
/// through writing a file.
#[test]
fn the_recipe_only_promotes_to_types_frink_can_encode() {
    let writable = |t: GgmlType| crate::quantize::row_encoder(t).is_some();
    for p in PROMOTIONS {
        assert!(
            writable(p.to),
            "{:?}/{:?} promotes to {:?}, which has no frink encoder",
            p.role,
            p.ftype,
            p.to
        );
    }
    assert!(writable(FALCON_Q4KM_FFN_DOWN_SIXTEENTH));
    // And the post-chain overrides, which are code rather than rows.
    for t in [GgmlType::Q5K, GgmlType::Q8_0, GgmlType::Q6K] {
        assert!(writable(t));
    }
    // The one exception, and why it is one: Q4_0's imatrix arm names a
    // type frink cannot write, and the planner refuses it by name
    // (`q4_0_with_an_imatrix_refuses_the_q4_1_ffn_down_by_name`).
    assert!(!writable(Q4_0_IMATRIX_FFN_DOWN_FIRST_EIGHTH));
}

/// `--type Q4_0`'s mix (`ee467158:src/llama-quant.cpp:578-600, 710`):
/// the output head goes to Q6_K (Q8_0 on Falcon), the embedding stays
/// Q4_0, and only with an imatrix do the first eighth of the `ffn_down`
/// layers become Q4_1.
#[test]
fn the_q4_0_mix_is_upstreams() {
    let n = 16;
    let ns = names(n, false);
    let ty =
        |got: &[(String, GgmlType)], name: &str| got.iter().find(|(n, _)| n == name).unwrap().1;
    let plain = walk(Target::Q4_0, shape(n), &ns);
    assert_eq!(ty(&plain, "output.weight"), GgmlType::Q6K);
    assert_eq!(ty(&plain, "token_embd.weight"), GgmlType::Q4_0);
    for (name, t) in &plain {
        if name != "output.weight" {
            assert_eq!(*t, GgmlType::Q4_0, "{name}");
        }
    }
    let mut r = Recipe::new(Target::Q4_0, shape(n), &ns).with_imatrix(true);
    let with_im: Vec<(String, GgmlType)> = ns
        .iter()
        .map(|n| {
            (
                n.clone(),
                r.tensor_type(n, &[4096, 4096], GgmlType::F16).unwrap(),
            )
        })
        .collect();
    for i in 0..n {
        let want = if i < n / 8 {
            GgmlType::Q4_1
        } else {
            GgmlType::Q4_0
        };
        assert_eq!(
            ty(&with_im, &format!("blk.{i}.ffn_down.weight")),
            want,
            "{i}"
        );
        assert_eq!(
            ty(&with_im, &format!("blk.{i}.attn_v.weight")),
            GgmlType::Q4_0
        );
    }
    let falcon = ModelShape {
        arch: QuantArch::Falcon,
        ..shape(n)
    };
    assert_eq!(
        ty(&walk(Target::Q4_0, falcon, &ns), "output.weight"),
        GgmlType::Q8_0
    );
}

/// Every mix in the table is a mix `parse_target` admits, and the
/// two mixes with NO rows are the two that genuinely have none.
///
/// The second half is the one that matters: a target added to the
/// CLI without rows here would silently get a uniform file under a
/// mix's name, which is the exact failure this module exists to
/// close. Naming the two exceptions explicitly means adding a
/// seventh target turns this red rather than passing quietly.
#[test]
fn the_table_and_the_target_list_cover_each_other() {
    for p in PROMOTIONS {
        assert!(Target::ALL.contains(&p.ftype), "{:?}", p.ftype);
    }
    let no_rows: Vec<&'static str> = Target::ALL
        .iter()
        .filter(|t| !PROMOTIONS.iter().any(|p| p.ftype == **t))
        .map(|t| t.name())
        .collect();
    // Q8_0: `llama_tensor_get_type`'s output arm reaches Q8_0 and
    // assigns Q8_0, because the promotion is `else if (new_type !=
    // GGML_TYPE_Q8_0)`. Q6_K: same arm, same reason, and no
    // per-layer arm mentions Q6_K as an ftype at all. Both still
    // pass through `tensor_type`, which is where their shape and
    // 8-expert overrides live.
    assert_eq!(no_rows, vec!["Q8_0", "Q6_K"]);
}

/// `Role::of` keeps the pin's category order. `attn_qkv_gate.weight`
/// does not contain `attn_qkv.weight`, so it needs its own needle;
/// `ffn_gate_up_exps` contains `ffn_gate` and not `ffn_up`; and
/// `ffn_latent` and `attn_gate.weight` are categories of their own,
/// tested before `ffn_down`.
#[test]
fn tensor_names_land_in_llama_cpps_arms() {
    let cases: &[(&str, Role)] = &[
        ("output.weight", Role::Output),
        ("token_embd.weight", Role::TokenEmbd),
        ("blk.0.attn_v.weight", Role::AttnV),
        ("blk.0.attn_k.weight", Role::AttnK),
        ("blk.0.attn_q.weight", Role::AttnQ),
        ("blk.0.attn_qkv.weight", Role::AttnQkv),
        ("blk.0.attn_qkv_gate.weight", Role::AttnQkv),
        ("blk.0.attn_kv_b.weight", Role::AttnKvB),
        ("blk.0.attn_gate.weight", Role::AttnGate),
        ("blk.0.ffn_latent_down.weight", Role::FfnLatent),
        ("blk.0.ffn_gate_up_exps.weight", Role::FfnGate),
        ("blk.0.attn_output.weight", Role::AttnOutput),
        ("blk.0.ffn_down.weight", Role::FfnDown),
        ("blk.0.ffn_down_exps.weight", Role::FfnDown),
        ("blk.0.ffn_down_shexp.weight", Role::FfnDown),
        ("blk.0.ffn_gate.weight", Role::FfnGate),
        ("blk.0.ffn_up.weight", Role::FfnUp),
        ("blk.0.attn_norm.weight", Role::Other),
    ];
    for (name, want) in cases {
        assert_eq!(Role::of(name, true), *want, "{name}");
    }
    // Without an output.weight in the file, token_embd IS the head.
    assert_eq!(Role::of("token_embd.weight", false), Role::Output);
}

/// `resolve_all` gives the same answer whatever order the tensors
/// arrive in, which is what makes the planner's own loop order
/// irrelevant. Before it existed the planner walked the file and
/// twelve of Llama-3.2-1B's tensors came out with a different type
/// from `llama-quantize`'s -- a file that loaded and answered.
#[test]
fn resolve_all_is_independent_of_the_order_it_is_handed_the_tensors() {
    let n = 16;
    let tensors: Vec<(String, Vec<u64>, GgmlType)> = names(n, false)
        .into_iter()
        .map(|s| (s, vec![4096u64, 4096], GgmlType::F16))
        .collect();
    let forward =
        Recipe::resolve_all(Target::Q4_K_M, shape(n), false, &tensors, |_, _| true).unwrap();

    let mut reversed = tensors.clone();
    reversed.reverse();
    assert_eq!(
        forward,
        Recipe::resolve_all(Target::Q4_K_M, shape(n), false, &reversed, |_, _| true).unwrap()
    );

    // A lexicographic shuffle is the one that actually moved
    // llama.cpp's answers, because it interleaves blk.1x with blk.1.
    let mut lexicographic = tensors.clone();
    lexicographic.sort_by(|a, b| a.0.cmp(&b.0));
    assert_eq!(
        forward,
        Recipe::resolve_all(Target::Q4_K_M, shape(n), false, &lexicographic, |_, _| true).unwrap()
    );

    // And it is not a constant map: if it were, order-independence
    // would be trivial.
    let distinct: std::collections::BTreeSet<_> =
        forward.values().map(|t| format!("{t:?}")).collect();
    assert!(distinct.len() > 1, "{distinct:?}");
}

/// On a MoE checkpoint the layer index is parsed from the name, not
/// taken from the counter, because Mixtral's expert tensors are not
/// in layer order. Feeding them out of order must still give each
/// its own layer's answer.
#[test]
fn a_moe_checkpoints_ffn_layer_comes_from_the_name_not_the_counter() {
    let n = 16;
    let mut ns = names(n, false);
    ns.retain(|s| !s.contains("ffn_down"));
    let moe = ModelShape {
        n_expert: 4,
        ..shape(n)
    };
    let mut r = Recipe::new(Target::Q4_K_M, moe, &ns);
    // Layer 5 first: `use_more_bits(5, 16)` is false, while the
    // counter would say layer 0, which is true. So a recipe reading
    // the counter here answers Q6_K and this answers Q4_K.
    assert_eq!(
        r.tensor_type("blk.5.ffn_down.weight", &[4096, 4096], GgmlType::F16)
            .unwrap(),
        GgmlType::Q4K
    );
    assert_eq!(
        r.tensor_type("blk.0.ffn_down.weight", &[4096, 4096], GgmlType::F16)
            .unwrap(),
        GgmlType::Q6K
    );
}

/// Where `llama-quantize` throws in `layer_info`, frink refuses: a MoE
/// FFN tensor past `n_layer`, and one whose layer no scan reads. A
/// decision head's `dec.blk.N.` is read, unchecked. The pin's binary
/// refuses the first (`goldens/moe_bad_layer.golden`).
#[test]
fn a_moe_ffn_tensor_whose_layer_llama_cpp_cannot_place_is_refused() {
    let moe = ModelShape {
        n_expert: 4,
        ..shape(2)
    };
    let ns = names(2, false);
    let mut r = Recipe::new(Target::Q4_K_M, moe, &ns);
    let err = r
        .tensor_type("blk.5.ffn_down.weight", &[512, 32], GgmlType::F32)
        .unwrap_err()
        .to_string();
    assert!(err.contains("Bad layer 5"), "{err}");
    assert!(r
        .tensor_type("x.ffn_down.weight", &[512, 32], GgmlType::F32)
        .is_err());
    assert!(r
        .tensor_type("dec.blk.1.ffn_down.weight", &[512, 32], GgmlType::F32)
        .is_ok());
    // A dense checkpoint counts instead and never looks at the name.
    let mut dense = Recipe::new(Target::Q4_K_M, shape(2), &ns);
    assert!(dense
        .tensor_type("x.ffn_down.weight", &[512, 32], GgmlType::F32)
        .is_ok());
}