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
//! End-to-end tests of `frink quantize` through real GGUF files.

use super::*;

fn tmp_dir(tag: &str) -> PathBuf {
    let dir = std::env::temp_dir().join(format!(
        "frink-quantize-{}-{}-{:?}",
        tag,
        std::process::id(),
        std::thread::current().id()
    ));
    std::fs::create_dir_all(&dir).unwrap();
    dir
}

/// One place the test `QuantizeArgs` are built.
///
/// Six hand-written literals of this struct is the shape ADR 0004
/// names first: adding `--pure` had to be spelled six times, and
/// six copies is five chances to give one of them a different
/// default from the CLI's. The builder takes what each test varies
/// and nothing else.
fn args(input: &Path, output: &Path, ty: &str) -> QuantizeArgs {
    QuantizeArgs {
        input: input.to_path_buf(),
        output: Some(output.to_path_buf()),
        ty: ty.into(),
        pure: false,
        dry_run: false,
        force: true,
        imatrix: None,
    }
}

/// Writes a tiny but structurally real F16 GGUF: a 2-D weight to
/// quantize, a 1-D tensor (the dimension rule), a 2-D norm and a
/// 2-D router gate (the keep-list rules).
///
/// The norm is 2-D on purpose. A 1-D one would be kept by the
/// dimension rule alone, so deleting `_norm.weight` from the
/// keep-list would leave this test green -- which it did, until the
/// sabotage pass found it.
/// `n_cols` is a parameter because the targets have different block
/// sizes: 64 columns is a whole number of Q8_0 blocks and NOT of
/// Q4_K super-blocks, and a fixture that only ever had one width
/// could not tell the two refusals apart.
///
/// `output.weight` is here so the MIX has something to promote. It
/// is the tensor every K-quant mix sends to Q6_K, so without it a
/// `--pure` run and a mixed run of this fixture would produce
/// identical files and the mix would be untested end to end.
fn write_f16_source(path: &Path, n_cols: usize) -> Vec<f32> {
    let n = n_cols;
    let values: Vec<f32> = (0..n * 2)
        .map(|i| ((i as f32) * 0.037).sin() * 0.8)
        .collect();
    let f16_bytes = |vals: &[f32]| -> Vec<u8> {
        vals.iter()
            .flat_map(|v| half::f16::from_f32(*v).to_le_bytes())
            .collect()
    };
    let mut metadata = BTreeMap::new();
    metadata.insert(
        "general.architecture".to_string(),
        GgufValue::String("llama".into()),
    );
    metadata.insert("general.file_type".to_string(), GgufValue::U32(1));

    let w = f16_bytes(&values);
    let one_d = f16_bytes(&values[..n]);
    let norm = f16_bytes(&values);
    let gate = f16_bytes(&values);
    let head = f16_bytes(&values);
    let plan = vec![
        TensorPlan {
            name: "blk.0.attn_q.weight".into(),
            shape: vec![n as u64, 2],
            dtype: GgmlType::F16,
            byte_len: w.len(),
        },
        TensorPlan {
            name: "blk.0.attn_q.bias".into(),
            shape: vec![n as u64],
            dtype: GgmlType::F16,
            byte_len: one_d.len(),
        },
        TensorPlan {
            name: "blk.0.attn_norm.weight".into(),
            shape: vec![n as u64, 2],
            dtype: GgmlType::F16,
            byte_len: norm.len(),
        },
        TensorPlan {
            name: "blk.0.ffn_gate_inp.weight".into(),
            shape: vec![n as u64, 2],
            dtype: GgmlType::F16,
            byte_len: gate.len(),
        },
        TensorPlan {
            name: "output.weight".into(),
            shape: vec![n as u64, 2],
            dtype: GgmlType::F16,
            byte_len: head.len(),
        },
    ];
    let f = std::fs::File::create(path).unwrap();
    let mut wr = GgufWriter::create(BufWriter::new(f), &metadata, plan).unwrap();
    wr.write_tensor("blk.0.attn_q.weight", &w).unwrap();
    wr.write_tensor("blk.0.attn_q.bias", &one_d).unwrap();
    wr.write_tensor("blk.0.attn_norm.weight", &norm).unwrap();
    wr.write_tensor("blk.0.ffn_gate_inp.weight", &gate).unwrap();
    wr.write_tensor("output.weight", &head).unwrap();
    wr.finish().unwrap().into_inner().unwrap();
    values
}

/// End to end: an F16 GGUF in, a Q8_0 GGUF out, read back by the
/// same reader the engine loads models with. The tensors that
/// llama.cpp keeps at source precision are still F16, the one it
/// quantizes is Q8_0, and the values survive within Q8_0's error.
#[test]
fn an_f16_gguf_round_trips_through_quantize_and_reads_back_as_q8_0() {
    let dir = tmp_dir("roundtrip");
    let src = dir.join("src.gguf");
    let dst = dir.join("dst.gguf");
    let values = write_f16_source(&src, 64);

    run(args(&src, &dst, "Q8_0")).unwrap();

    let out = GgufFile::open(&dst).unwrap();
    assert_eq!(out.metadata_u64("general.file_type"), Some(7));
    assert_eq!(out.metadata_u64("general.quantization_version"), Some(2));
    assert_eq!(out.metadata_str("general.architecture"), Some("llama"));

    let q = out.find_tensor("blk.0.attn_q.weight").unwrap();
    assert_eq!(q.dtype, GgmlType::Q8_0);
    assert_eq!(q.shape, vec![64, 2]);
    // The 2-D norm and the router gate are llama.cpp's keep-list;
    // the bias is the dimension rule and the not-a-weight rule.
    for kept in [
        "blk.0.attn_q.bias",
        "blk.0.attn_norm.weight",
        "blk.0.ffn_gate_inp.weight",
    ] {
        assert_eq!(
            out.find_tensor(kept).unwrap().dtype,
            GgmlType::F16,
            "{kept} should have been kept at source precision"
        );
    }

    let back = frink_quant::dequant_q8_0(out.tensor_bytes("blk.0.attn_q.weight").unwrap()).unwrap();
    assert_eq!(back.len(), values.len());
    for (i, (&want, &have)) in values.iter().zip(back.iter()).enumerate() {
        assert!((want - have).abs() < 0.01, "element {i}: {want} -> {have}");
    }
    std::fs::remove_dir_all(&dir).ok();
}

/// The quantized bytes are the ones llama.cpp's encoder would have
/// written for the same row, not merely bytes that decode to
/// similar numbers. `frink-quant`'s golden pins the encoder; this
/// pins the pipeline that feeds it -- row tiling, F16 decode, and
/// the writer's data-section layout all have to be right for these
/// bytes to land where the reader looks.
#[test]
fn the_quantized_tensor_bytes_are_what_the_encoder_produces_for_those_rows() {
    let dir = tmp_dir("bytes");
    let src = dir.join("src.gguf");
    let dst = dir.join("dst.gguf");
    let values = write_f16_source(&src, 64);
    run(args(&src, &dst, "q8_0")).unwrap();

    // Re-encode independently, from the f16 the source stored (not
    // from `values`, which is f32 and would round differently).
    let mut want = Vec::new();
    let f16_roundtrip: Vec<f32> = values
        .iter()
        .map(|v| half::f16::from_f32(*v).to_f32())
        .collect();
    for row in f16_roundtrip.chunks(64) {
        frink_quant::encode_row_q8_0(row, &mut want).unwrap();
    }
    let out = GgufFile::open(&dst).unwrap();
    assert_eq!(out.tensor_bytes("blk.0.attn_q.weight").unwrap(), &want[..]);
    std::fs::remove_dir_all(&dir).ok();
}

/// The refusal this subcommand is scoped around, exercised through
/// the real entry point rather than only through `parse_target`.
#[test]
fn asking_for_a_target_with_no_encoder_refuses_before_touching_the_filesystem() {
    let dir = tmp_dir("refuse");
    let src = dir.join("src.gguf");
    let dst = dir.join("dst.gguf");
    write_f16_source(&src, 64);
    // Q6_K used to be the example here and is writable now, which
    // is what this change is for. Q3_K_M is the next mix up with no
    // encoder.
    let err = run(args(&src, &dst, "Q3_K_M")).unwrap_err();
    let msg = err.to_string();
    assert!(msg.contains("cannot WRITE Q3_K_M"), "{msg}");
    assert!(msg.contains("Q8_0"), "{msg}");
    assert!(!dst.exists(), "a refused run must not leave a file behind");
    std::fs::remove_dir_all(&dir).ok();
}

/// A source tensor that is already quantized is refused by name.
/// Requantizing stacks two roundings, and the file would carry no
/// sign that it happened.
#[test]
fn an_already_quantized_source_tensor_is_refused_by_name() {
    let dir = tmp_dir("requant");
    let src = dir.join("src.gguf");
    let bytes = vec![0u8; 144 * 2]; // two Q4_K super-blocks
    let plan = vec![TensorPlan {
        name: "blk.0.attn_q.weight".into(),
        shape: vec![256, 2],
        dtype: GgmlType::Q4K,
        byte_len: bytes.len(),
    }];
    let f = std::fs::File::create(&src).unwrap();
    let mut wr = GgufWriter::create(BufWriter::new(f), &BTreeMap::new(), plan).unwrap();
    wr.write_tensor("blk.0.attn_q.weight", &bytes).unwrap();
    wr.finish().unwrap().into_inner().unwrap();

    let err = run(QuantizeArgs {
        dry_run: true,
        ..args(&src, &dir.join("dst.gguf"), "Q8_0")
    })
    .unwrap_err();
    assert!(
        err.to_string().contains("F32/F16/BF16 sources only"),
        "{err}"
    );
    std::fs::remove_dir_all(&dir).ok();
}

/// A row length that is not a whole number of blocks stops the run.
/// The alternative -- padding the row -- writes more elements than
/// the shape declares, and every later row decodes shifted.
#[test]
fn a_row_length_that_is_not_a_multiple_of_the_block_size_is_refused() {
    let dir = tmp_dir("ragged");
    let src = dir.join("src.gguf");
    let bytes = vec![0u8; 33 * 2 * 2];
    let plan = vec![TensorPlan {
        name: "blk.0.attn_q.weight".into(),
        shape: vec![33, 2],
        dtype: GgmlType::F16,
        byte_len: bytes.len(),
    }];
    let f = std::fs::File::create(&src).unwrap();
    let mut wr = GgufWriter::create(BufWriter::new(f), &BTreeMap::new(), plan).unwrap();
    wr.write_tensor("blk.0.attn_q.weight", &bytes).unwrap();
    wr.finish().unwrap().into_inner().unwrap();

    let err = run(QuantizeArgs {
        dry_run: true,
        ..args(&src, &dir.join("dst.gguf"), "Q8_0")
    })
    .unwrap_err();
    assert!(err.to_string().contains("not a multiple of"), "{err}");
    std::fs::remove_dir_all(&dir).ok();
}

#[test]
fn an_existing_output_is_not_overwritten_without_force() {
    let dir = tmp_dir("clobber");
    let src = dir.join("src.gguf");
    let dst = dir.join("dst.gguf");
    write_f16_source(&src, 64);
    std::fs::write(&dst, b"precious").unwrap();
    let err = run(QuantizeArgs {
        force: false,
        ..args(&src, &dst, "Q8_0")
    })
    .unwrap_err();
    assert!(err.to_string().contains("--force"), "{err}");
    assert_eq!(std::fs::read(&dst).unwrap(), b"precious");
    std::fs::remove_dir_all(&dir).ok();
}

/// `--type q4_k_m` names a MIX, and the mix is now applied: the
/// same file quantized with and without `--pure` must DIFFER, and
/// differ in the tensor the mix promotes.
///
/// This replaces the refusal that used to stand here. It is the
/// assertion most likely to be argued away later ("Q4_K everywhere
/// is close enough"), so it goes through the real entry point and
/// names the tensor.
#[test]
fn the_q4_k_m_mix_promotes_the_output_head_and_pure_does_not() {
    let dir = tmp_dir("mix");
    let src = dir.join("src.gguf");
    write_f16_source(&src, 256);

    let mixed = dir.join("mixed.gguf");
    run(args(&src, &mixed, "q4_k_m")).unwrap();
    let pure = dir.join("pure.gguf");
    run(QuantizeArgs {
        pure: true,
        ..args(&src, &pure, "q4_k_m")
    })
    .unwrap();

    let m = GgufFile::open(&mixed).unwrap();
    let p = GgufFile::open(&pure).unwrap();
    // The mix sends `output.weight` to Q6_K; `--pure` leaves it at
    // the target's block format.
    assert_eq!(m.find_tensor("output.weight").unwrap().dtype, GgmlType::Q6K);
    assert_eq!(p.find_tensor("output.weight").unwrap().dtype, GgmlType::Q4K);
    // And the tensor the mix does NOT touch is Q4_K in both.
    for f in [&m, &p] {
        assert_eq!(
            f.find_tensor("blk.0.attn_q.weight").unwrap().dtype,
            GgmlType::Q4K
        );
    }
    // Both still declare Q4_K_M, which is precisely why the bytes
    // having to differ is worth asserting: `general.file_type`
    // alone cannot tell the two files apart.
    assert_eq!(m.metadata_u64("general.file_type"), Some(15));
    assert_eq!(p.metadata_u64("general.file_type"), Some(15));
    assert_ne!(
        std::fs::read(&mixed).unwrap(),
        std::fs::read(&pure).unwrap()
    );
    std::fs::remove_dir_all(&dir).ok();
}

/// End to end for the K-quant: an F16 GGUF in, a `--pure` Q4_K
/// GGUF out, read back by the reader the engine loads models with.
///
/// The bytes are compared against the encoder rather than against a
/// tolerance, because `frink-quant`'s golden already pins the
/// encoder to llama.cpp's; what this adds is the pipeline around it
/// -- 256-wide row tiling, F16 decode, the writer's data-section
/// layout, and the `general.file_type` that tells every other tool
/// what the file is.
#[test]
fn an_f16_gguf_round_trips_through_quantize_and_reads_back_as_q4_k() {
    let dir = tmp_dir("q4k");
    let src = dir.join("src.gguf");
    let dst = dir.join("dst.gguf");
    let values = write_f16_source(&src, 256);

    run(QuantizeArgs {
        pure: true,
        ..args(&src, &dst, "q4_k_s")
    })
    .unwrap();

    let out = GgufFile::open(&dst).unwrap();
    // 14 is LLAMA_FTYPE_MOSTLY_Q4_K_S. `q4_k_m` would write 15 from
    // the same bytes, which is the whole reason the two are
    // separate targets.
    assert_eq!(out.metadata_u64("general.file_type"), Some(14));
    let q = out.find_tensor("blk.0.attn_q.weight").unwrap();
    assert_eq!(q.dtype, GgmlType::Q4K);
    assert_eq!(q.shape, vec![256, 2]);
    // `--pure` skips llama.cpp's per-layer mix, NOT its keep-list:
    // a norm quantized to Q4_K is a broken model either way.
    for kept in [
        "blk.0.attn_q.bias",
        "blk.0.attn_norm.weight",
        "blk.0.ffn_gate_inp.weight",
    ] {
        assert_eq!(
            out.find_tensor(kept).unwrap().dtype,
            GgmlType::F16,
            "{kept} should have been kept at source precision"
        );
    }

    let mut want = Vec::new();
    let f16_roundtrip: Vec<f32> = values
        .iter()
        .map(|v| half::f16::from_f32(*v).to_f32())
        .collect();
    for row in f16_roundtrip.chunks(256) {
        frink_quant::encode_row_q4_k(row, None, &mut want).unwrap();
    }
    assert_eq!(out.tensor_bytes("blk.0.attn_q.weight").unwrap(), &want[..]);
    std::fs::remove_dir_all(&dir).ok();
}

/// The block-size refusal has to say the right thing for the right
/// target. 64 columns is a whole number of Q8_0 blocks and not of
/// Q4_K super-blocks, and llama.cpp's answers differ: it throws for
/// Q8_0 and silently rewrites the tensor to Q5_0 for Q4_K. One
/// sentence covering both was true of only Q8_0.
#[test]
fn a_row_too_narrow_for_a_super_block_is_refused_and_names_llama_cpps_fallback() {
    let dir = tmp_dir("narrow");
    let src = dir.join("src.gguf");
    write_f16_source(&src, 64);
    let err = run(QuantizeArgs {
        pure: true,
        dry_run: true,
        ..args(&src, &dir.join("dst.gguf"), "q4_k_s")
    })
    .unwrap_err();
    let msg = err.to_string();
    assert!(
        msg.contains("not a multiple of Q4K's block size (256)"),
        "{msg}"
    );
    assert!(msg.contains("Q4_K -> Q5_0"), "{msg}");
    std::fs::remove_dir_all(&dir).ok();
}

/// `--imatrix` end to end: the weighted bytes are what the encoder
/// produces for that row with that slice, they differ from the
/// unweighted run, and the output records the imatrix keys. The
/// whole-model byte identity is measured outside CI; this pins the
/// plumbing from flag to encoder.
#[test]
fn an_imatrix_reaches_the_encoder_and_is_recorded_in_the_metadata() {
    let dir = tmp_dir("imatrix");
    let src = dir.join("src.gguf");
    let values = write_f16_source(&src, 256);
    let im_path = dir.join("im.gguf");
    let mut stats = BTreeMap::new();
    stats.insert(
        "blk.0.attn_q.weight".to_string(),
        crate::imatrix::file::Stats {
            values: (0..256).map(|i| 1.0 + (i % 7) as f32).collect(),
            counts: vec![4],
        },
    );
    crate::imatrix::file::write(
        &im_path,
        crate::imatrix::file::OutputFormat::Gguf,
        &stats,
        &["calib.txt".to_string()],
        2,
        512,
    )
    .unwrap();

    let plain = dir.join("plain.gguf");
    run(QuantizeArgs {
        pure: true,
        ..args(&src, &plain, "q4_k_s")
    })
    .unwrap();
    let weighted = dir.join("weighted.gguf");
    run(QuantizeArgs {
        pure: true,
        imatrix: Some(im_path.clone()),
        ..args(&src, &weighted, "q4_k_s")
    })
    .unwrap();

    let qw: Vec<f32> = (0..256).map(|i| (1.0 + (i % 7) as f32) / 4.0).collect();
    let mut want = Vec::new();
    for row in values.chunks(256) {
        let f16_row: Vec<f32> = row
            .iter()
            .map(|v| half::f16::from_f32(*v).to_f32())
            .collect();
        frink_quant::encode_row_q4_k(&f16_row, Some(&qw), &mut want).unwrap();
    }
    let w = GgufFile::open(&weighted).unwrap();
    let p = GgufFile::open(&plain).unwrap();
    assert_eq!(w.tensor_bytes("blk.0.attn_q.weight").unwrap(), &want[..]);
    assert_ne!(
        w.tensor_bytes("blk.0.attn_q.weight").unwrap(),
        p.tensor_bytes("blk.0.attn_q.weight").unwrap()
    );
    assert_eq!(w.metadata_u64("quantize.imatrix.entries_count"), Some(1));
    assert_eq!(w.metadata_u64("quantize.imatrix.chunks_count"), Some(2));
    assert_eq!(
        w.metadata_str("quantize.imatrix.dataset"),
        Some("calib.txt")
    );
    assert!(p.metadata_str("quantize.imatrix.file").is_none());
    std::fs::remove_dir_all(&dir).ok();
}

#[test]
fn the_default_output_name_carries_the_target_and_sits_beside_the_input() {
    assert_eq!(
        default_output_path(Path::new("/m/Llama-3.2-1B-F16.gguf"), Target::Q8_0),
        PathBuf::from("/m/Llama-3.2-1B-F16-Q8_0.gguf")
    );
}

/// A two-layer llama whose second layer shares the first's KV cache.
fn shared_kv_file(shared: u32) -> GgufFile {
    let dir = std::env::temp_dir().join(format!(
        "frink-quantize-shared-kv-{}-{shared}",
        std::process::id()
    ));
    std::fs::create_dir_all(&dir).unwrap();
    let path = dir.join("src.gguf");
    let mut metadata = BTreeMap::new();
    metadata.insert(
        "general.architecture".to_string(),
        GgufValue::String("llama".into()),
    );
    metadata.insert("llama.block_count".to_string(), GgufValue::U32(2));
    metadata.insert(
        "llama.attention.shared_kv_layers".to_string(),
        GgufValue::U32(shared),
    );
    let bytes = vec![0u8; 256 * 2 * 2];
    let names = ["blk.0.attn_k.weight", "blk.1.attn_k.weight"];
    let plan_entries = names
        .iter()
        .map(|n| TensorPlan {
            name: (*n).into(),
            shape: vec![256, 2],
            dtype: GgmlType::F16,
            byte_len: bytes.len(),
        })
        .collect();
    let f = std::fs::File::create(&path).unwrap();
    let mut wr = GgufWriter::create(BufWriter::new(f), &metadata, plan_entries).unwrap();
    for n in names {
        wr.write_tensor(n, &bytes).unwrap();
    }
    wr.finish().unwrap().into_inner().unwrap();
    GgufFile::open(&path).unwrap()
}

/// llama-quantize writes an unused `attn_k` / `attn_v` as Q4_0 under
/// every mix and under `--pure` (`goldens/shared_kv.golden`); frink has
/// no Q4_0 encoder, so it refuses by name before writing anything. The
/// layer that keeps its own KV cache is planned as usual.
#[test]
fn an_unused_kv_tensor_of_a_shared_kv_layer_is_refused_by_name() {
    let file = shared_kv_file(1);
    for pure in [false, true] {
        for target in [Target::Q4_K_M, Target::Q8_0] {
            let err = match plan(&file, target, pure) {
                Ok(_) => panic!("{target:?} pure={pure}: planned a shared-KV layer"),
                Err(e) => e.to_string(),
            };
            assert!(err.contains("blk.1.attn_k.weight"), "{err}");
            assert!(err.contains("Q4_0"), "{err}");
            assert!(err.contains("shared_kv_layers"), "{err}");
        }
    }
    // Without the key, the same file plans.
    let plain = shared_kv_file(0);
    assert!(plan(&plain, Target::Q8_0, false).is_ok());
}