frink-cli 0.74.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
//! `frink quantize`: read a GGUF, write a GGUF whose eligible tensors
//! are re-encoded to a quantization frink can actually produce.
//!
//! Today that is Q8_0, Q4_0, Q4_K, Q5_K and Q6_K, and the seven
//! llama.cpp targets built from them. See [`policy`] for why the other
//! targets refuse by name instead of being approximated and for the
//! tensor-eligibility rules this shares with llama.cpp, and [`recipe`]
//! for the per-tensor MIX -- the reason a `Q4_K_M` file has a Q6_K output head and Q6_K
//! `ffn_down` on a quarter of its layers.
//!
//! `--imatrix` feeds an importance matrix (`frink imatrix` or
//! `llama-imatrix`, either format) to the K-quant encoders, the way
//! `llama-quantize --imatrix` does (`src/llama-quant.cpp:913-934`):
//! each tensor looks its own name up, a tensor with no entry is
//! quantized unweighted with a printed notice, and an entry of the
//! wrong width is a refusal -- except on `token_embd.weight`, which
//! upstream exempts because its imatrix is routinely the wrong shape.
//! Q8_0 ignores the matrix (`ggml-quants.c:2088-2093`); Q4_0 takes it
//! (`quantize_row_q4_0_impl`). Of the targets this tool writes, only
//! Q4_0 reads `has_imatrix` in the mix (upstream consults it for the IQ
//! tiers and Q4_0/Q5_0, `ee467158:src/llama-quant.cpp:710`): with one,
//! the first eighth of the `ffn_down` layers become Q4_1, which frink
//! cannot write, so that plan is refused. Under every other target the
//! plan is the same with and without one; only the bytes inside each
//! K-quant (and Q4_0) tensor change. The four `quantize.imatrix.*`
//! keys llama.cpp records in the output (`tools/quantize/quantize.cpp:
//! 532-566`) are written too, with its 127-byte truncation.
//!
//! The pass is streaming: the input is mmap'd, tensors are re-encoded
//! one at a time, and the output is written through a `BufWriter`. A
//! 70B checkpoint costs the output's page cache plus one tensor's f32
//! expansion, not the model.

pub mod arch;
pub mod imatrix_input;
pub mod model_shape;
pub mod policy;
pub mod recipe;
#[cfg(test)]
mod recipe_golden;
#[cfg(test)]
mod recipe_golden_arch;
#[cfg(test)]
mod recipe_golden_qwen35;

use std::collections::BTreeMap;
use std::io::BufWriter;
use std::path::{Path, PathBuf};

use anyhow::{bail, Context, Result};
use clap::Parser;
use frink_gguf::{GgmlType, GgufFile, GgufValue, GgufWriter, TensorPlan};
use rayon::prelude::*;

use arch::QuantArch;
use imatrix_input::{imatrix_for_tensor, imatrix_metadata, load_imatrix};
use model_shape::ModelShape;
use policy::{
    allows_quantization, disposition, first_unused_kv_layer, parse_target, unused_kv_type,
    Disposition, Target,
};
use recipe::Recipe;

/// `general.quantization_version`, ggml's `GGML_QNT_VERSION`. Every
/// tool in the ecosystem reads it; a file without it looks pre-2023.
const GGML_QNT_VERSION: u32 = 2;

/// Rows re-encoded per rayon task. Big enough that the per-task
/// overhead disappears, small enough that a 128k-row embedding table
/// does not become 128k allocations.
const ROWS_PER_TASK: usize = 64;

#[derive(Parser, Debug)]
pub struct QuantizeArgs {
    /// Source GGUF. Its quantizable tensors must be F32, F16 or BF16:
    /// re-quantizing an already-quantized checkpoint compounds two
    /// roundings and is refused rather than done quietly.
    pub input: PathBuf,

    /// Destination GGUF. Defaults to `<input stem>-<TYPE>.gguf` beside
    /// the input. (llama-quantize's default is `ggml-model-<TYPE>.gguf`
    /// in the same directory, which collides the moment two models
    /// share one; this one does not.)
    pub output: Option<PathBuf>,

    /// Quantization to write: Q8_0, Q4_0, Q4_K_S, Q4_K_M, Q5_K_S, Q5_K_M
    /// or Q6_K. Every other llama.cpp target is refused BY NAME -- frink
    /// reads them all and encodes five, and a subcommand that pretended
    /// otherwise would hand back a file that loads and is worse.
    #[arg(long = "type", default_value = "Q8_0")]
    pub ty: String,

    /// Skip llama.cpp's per-tensor mix and write every quantizable
    /// tensor as `--type`, the way `llama-quantize --pure` does.
    ///
    /// Optional, and it changes the file: without it a `Q4_K_M` output
    /// head is Q6_K and a quarter of its `ffn_down` tensors are too.
    /// This used to be MANDATORY for the K-quant mixes, because frink
    /// had no Q5_K or Q6_K encoder to promote anything to.
    #[arg(long)]
    pub pure: bool,

    /// Print the plan (per tensor: quantize or copy, and why) and the
    /// resulting size, without writing anything.
    #[arg(long)]
    pub dry_run: bool,

    /// Overwrite the output if it already exists.
    #[arg(long)]
    pub force: bool,

    /// Importance matrix from `frink imatrix` or `llama-imatrix`, in
    /// either the GGUF or the legacy `.dat` format. Weights the K-quant
    /// and Q4_0 fits by measured activation energy; Q8_0 tensors are
    /// unaffected.
    #[arg(long)]
    pub imatrix: Option<PathBuf>,
}

/// One tensor's decided fate, and the numbers that follow from it.
pub(crate) struct Planned {
    pub(crate) name: String,
    pub(crate) shape: Vec<u64>,
    source_dtype: GgmlType,
    out_dtype: GgmlType,
    source_bytes: usize,
    out_bytes: usize,
    /// `None` for a tensor being copied; `Some(reason)` is the reason.
    copy_reason: Option<&'static str>,
}

pub fn run(args: QuantizeArgs) -> Result<()> {
    let target = parse_target(&args.ty).map_err(|e| anyhow::anyhow!("{e}"))?;

    let file =
        GgufFile::open(&args.input).with_context(|| format!("opening {}", args.input.display()))?;

    // A split checkpoint's shards each carry a slice of the tensors and
    // a `split.*` header that would be a lie on a single output file.
    // Refuse by name rather than silently quantizing one thirteenth of
    // a model.
    if file
        .metadata_u64(frink_gguf::sharded::SPLIT_COUNT_KEY)
        .is_some_and(|n| n > 1)
    {
        bail!(
            "{} is one shard of a split GGUF. `frink quantize` writes a single file and has no \
             --keep-split; merge the shards first, or quantize the unsplit source.",
            args.input.display()
        );
    }

    let output = args
        .output
        .clone()
        .unwrap_or_else(|| default_output_path(&args.input, target));
    if !args.dry_run {
        if output == args.input {
            bail!("output would overwrite the input ({})", output.display());
        }
        if output.exists() && !args.force {
            bail!(
                "{} already exists (pass --force to overwrite)",
                output.display()
            );
        }
    }

    let planned = plan(&file, target, args.pure, args.imatrix.is_some())?;

    let imatrix = match &args.imatrix {
        Some(p) => Some(load_imatrix(p)?),
        None => None,
    };

    let mut metadata: BTreeMap<String, GgufValue> = file
        .metadata
        .iter()
        .map(|(k, v)| (k.clone(), v.clone()))
        .collect();
    metadata.insert(
        "general.file_type".to_string(),
        GgufValue::U32(target.llama_ftype()),
    );
    metadata.insert(
        "general.quantization_version".to_string(),
        GgufValue::U32(GGML_QNT_VERSION),
    );
    if let (Some(im), Some(p)) = (&imatrix, &args.imatrix) {
        imatrix_metadata(&mut metadata, im, p);
    }

    let src_total: u64 = planned.iter().map(|p| p.source_bytes as u64).sum();
    let out_total: u64 = planned.iter().map(|p| p.out_bytes as u64).sum();
    let n_quantized = planned.iter().filter(|p| p.copy_reason.is_none()).count();

    println!(
        "quantize: {} -> {}",
        args.input.display(),
        if args.dry_run {
            "(dry run, nothing written)".to_string()
        } else {
            output.display().to_string()
        }
    );
    println!("  target: {}", target.name());
    for (i, p) in planned.iter().enumerate() {
        match p.copy_reason {
            Some(reason) => println!(
                "  [{:>4}/{}] {:<44} {:?} {:>10} B  copy ({reason})",
                i + 1,
                planned.len(),
                p.name,
                p.source_dtype,
                p.source_bytes
            ),
            None => println!(
                "  [{:>4}/{}] {:<44} {:?} {:>10} B -> {:?} {:>10} B",
                i + 1,
                planned.len(),
                p.name,
                p.source_dtype,
                p.source_bytes,
                p.out_dtype,
                p.out_bytes
            ),
        }
    }
    println!(
        "  {n_quantized}/{} tensors quantized; {:.2} MiB -> {:.2} MiB ({:.2}x)",
        planned.len(),
        src_total as f64 / (1024.0 * 1024.0),
        out_total as f64 / (1024.0 * 1024.0),
        src_total as f64 / out_total.max(1) as f64,
    );

    if args.dry_run {
        return Ok(());
    }

    let plan_entries: Vec<TensorPlan> = planned
        .iter()
        .map(|p| TensorPlan {
            name: p.name.clone(),
            shape: p.shape.clone(),
            dtype: p.out_dtype,
            byte_len: p.out_bytes,
        })
        .collect();

    let out_file =
        std::fs::File::create(&output).with_context(|| format!("creating {}", output.display()))?;
    let mut writer = GgufWriter::create(
        BufWriter::with_capacity(4 << 20, out_file),
        &metadata,
        plan_entries,
    )?;

    for p in &planned {
        let src = file.tensor_bytes(&p.name)?;
        if p.copy_reason.is_some() {
            writer.write_tensor(&p.name, src)?;
        } else {
            let qw = match &imatrix {
                Some(im) => imatrix_for_tensor(im, p)?,
                None => None,
            };
            let encoded = encode_tensor(p, src, qw)?;
            writer.write_tensor(&p.name, &encoded)?;
        }
    }
    writer.finish()?.into_inner()?;

    println!("wrote {}", output.display());
    Ok(())
}

fn default_output_path(input: &Path, target: Target) -> PathBuf {
    let stem = input
        .file_stem()
        .map(|s| s.to_string_lossy().into_owned())
        .unwrap_or_else(|| "ggml-model".to_string());
    input.with_file_name(format!("{stem}-{}.gguf", target.name()))
}

/// Decides every tensor's fate and sizes the output, refusing before a
/// single byte is written. The refusals here are the point: a tensor
/// this build cannot encode must stop the run, not be quietly copied
/// through at F16 into a file labelled Q8_0.
fn plan(file: &GgufFile, target: Target, pure: bool, has_imatrix: bool) -> Result<Vec<Planned>> {
    let mut out = Vec::with_capacity(file.tensors.len());

    // The mix is positional -- `i_attention_wv` and `i_ffn_down` are
    // running counters -- and the order they advance in is llama.cpp's
    // `weight_name_comparer`, NOT this file's tensor order. So the
    // whole map is resolved up front by `resolve_all`, which owns that
    // ordering, and this loop only looks types up. Walking
    // `file.tensors` and asking per tensor was the obvious thing and it
    // was wrong for 12 of Llama-3.2-1B's 113 tensors.
    //
    // `--pure` is llama.cpp's `if (!params->pure && ...)`: the mix is
    // not consulted AND its counters do not advance, so there is
    // nothing to resolve.
    let arch_name = file.metadata_str("general.architecture").unwrap_or("");
    let arch = QuantArch::from_name(arch_name);
    let chosen_types = if pure {
        BTreeMap::new()
    } else {
        let tensors: Vec<(String, Vec<u64>, GgmlType)> = file
            .tensors
            .iter()
            .map(|t| (t.name.clone(), t.shape.clone(), t.dtype))
            .collect();
        Recipe::resolve_all(
            target,
            ModelShape::from_header(file)?,
            has_imatrix,
            &tensors,
            |name, shape| allows_quantization(arch, name, shape).is_none(),
        )?
    };
    // A shared-KV checkpoint's unused `attn_k` / `attn_v` (gemma3n,
    // gemma4): llama-quantize overrides the mix, `--pure` included.
    let key = |suffix: &str| file.metadata_u64(&format!("{arch_name}.{suffix}"));
    let unused_kv_from =
        first_unused_kv_layer(key("block_count"), key("attention.shared_kv_layers"));

    for t in &file.tensors {
        let source_bytes = t.byte_len().ok_or_else(|| {
            anyhow::anyhow!(
                "tensor '{}' has dtype {:?}, whose block layout this build does not know, so it \
                 cannot even be copied through",
                t.name,
                t.dtype
            )
        })?;
        let copy_through = |reason: &'static str| Planned {
            name: t.name.clone(),
            shape: t.shape.clone(),
            source_dtype: t.dtype,
            out_dtype: t.dtype,
            source_bytes,
            out_bytes: source_bytes,
            copy_reason: Some(reason),
        };

        if let Some(reason) = allows_quantization(arch, &t.name, &t.shape) {
            out.push(copy_through(reason));
            continue;
        }

        // A shared-KV layer's unused `attn_k` / `attn_v` take the
        // planner's override after the mix (which still advanced its
        // counters for them in `resolve_all`), as upstream overrides
        // `llama_tensor_get_type`'s answer (`:3419`).
        let unused_kv = unused_kv_type(&t.name, t.shape[0], unused_kv_from);
        let chosen = if let Some(ty) = unused_kv {
            ty
        } else if pure {
            target.ggml_type()
        } else {
            // Every eligible tensor is in the map: `resolve_all` was
            // given the same `allows_quantization` this loop just
            // consulted. `expect` rather than a fallback, because a
            // fallback here would silently write the target's block
            // format for a tensor the mix meant to promote.
            *chosen_types
                .get(&t.name)
                .expect("resolve_all and allows_quantization disagree about a tensor")
        };

        match disposition(t.dtype, chosen) {
            Disposition::Copy(reason) => out.push(copy_through(reason)),
            Disposition::Quantize(ty) => {
                if !matches!(t.dtype, GgmlType::F32 | GgmlType::F16 | GgmlType::BF16) {
                    bail!(
                        "tensor '{}' is {:?}. `frink quantize` reads F32/F16/BF16 sources only: \
                         re-quantizing an already-quantized tensor stacks a second rounding on \
                         the first, and the result is worse than quantizing the original \
                         checkpoint once. Convert from the original weights instead.",
                        t.name,
                        t.dtype
                    );
                }
                if row_encoder(ty).is_none() {
                    let why = if unused_kv.is_some() {
                        format!(
                            "it belongs to a layer that shares an earlier layer's KV cache \
                             ({arch_name}.attention.shared_kv_layers), and llama-quantize writes \
                             such a tensor as {ty:?} under every target"
                        )
                    } else if ty == recipe::Q4_0_IMATRIX_FFN_DOWN_FIRST_EIGHTH {
                        "llama-quantize --type Q4_0 with an imatrix writes the first eighth of \
                         the ffn_down layers as Q4_1"
                            .to_string()
                    } else {
                        format!("the {} mix chooses it", target.name())
                    };
                    bail!(
                        "tensor '{}' would be {ty:?}: {why}. frink has no {ty:?} encoder, so it \
                         stops rather than write a different type than llama-quantize would.",
                        t.name
                    );
                }
                let (block_bytes, block_elems) = ty.block_layout();
                let n_cols = t.shape[0] as usize;
                // The block size that matters is the CHOSEN type's, not
                // the target's: under Q4_K_M an `output.weight` is Q6_K
                // and a Q4_K-sized check would pass a row Q6_K cannot
                // tile. Both are 256 today and would be the same
                // number, which is exactly why reading it off the wrong
                // one is a bug nothing would notice.
                if block_elems == 0 || !n_cols.is_multiple_of(block_elems) {
                    bail!(
                        "tensor '{}' has {n_cols} columns, which is not a multiple of {:?}'s \
                         block size ({block_elems}). {}",
                        t.name,
                        ty,
                        target.fallback_note()
                    );
                }
                let n_elements = t.element_count().ok_or_else(|| {
                    anyhow::anyhow!("tensor '{}' declares an unrepresentable shape", t.name)
                })?;
                out.push(Planned {
                    name: t.name.clone(),
                    shape: t.shape.clone(),
                    source_dtype: t.dtype,
                    out_dtype: ty,
                    source_bytes,
                    out_bytes: n_elements / block_elems * block_bytes,
                    copy_reason: None,
                });
            }
        }
    }
    Ok(out)
}

/// Re-encodes one tensor, row by row, in parallel over row groups.
///
/// Row-wise and not whole-tensor because a Q8_0 block must not straddle
/// two rows: the reader walks a row at a time, so a block spanning the
/// boundary would be decoded with the wrong scale for half its values.
/// `n_cols % block_elems == 0` (checked in `plan`) is what makes the
/// row-wise and flat tilings identical -- but relying on that instead
/// of tiling per row is how the next format, with a 256-element block,
/// would silently break.
///
/// `imatrix`, when present, is `n_cols * ne2` weights: one per column,
/// and for a 3-D expert stack one set per expert, so row `r`'s set is
/// the one for expert `r / ne1` (`llama-quant.cpp:984`, `imatrix +
/// i03 * n_per_row`). For a 2-D tensor that index is always 0.
fn encode_tensor(p: &Planned, src: &[u8], imatrix: Option<&[f32]>) -> Result<Vec<u8>> {
    let n_cols = p.shape[0] as usize;
    let n_rows = (p.shape.iter().product::<u64>() as usize)
        .checked_div(n_cols)
        .unwrap_or(0);
    let ne1 = p.shape.get(1).copied().unwrap_or(1).max(1) as usize;
    let src_row_bytes = source_bytes_per_element(p.source_dtype) * n_cols;
    let out_row_bytes = p.out_bytes / n_rows.max(1);

    let groups: Vec<Vec<u8>> = (0..n_rows)
        .collect::<Vec<_>>()
        .par_chunks(ROWS_PER_TASK)
        .map(|rows| {
            let mut buf = Vec::with_capacity(rows.len() * out_row_bytes);
            let mut scratch = vec![0f32; n_cols];
            for &r in rows {
                let row = &src[r * src_row_bytes..(r + 1) * src_row_bytes];
                decode_source_row(p.source_dtype, row, &mut scratch)?;
                let qw = imatrix.map(|im| {
                    let mat = r / ne1;
                    &im[mat * n_cols..(mat + 1) * n_cols]
                });
                encode_row(p.out_dtype, &scratch, qw, &mut buf)?.ok_or_else(|| {
                    anyhow::anyhow!(
                        "tensor '{}' row length {n_cols} is not a whole number of {:?} blocks",
                        p.name,
                        p.out_dtype
                    )
                })?;
            }
            Ok(buf)
        })
        .collect::<Result<Vec<Vec<u8>>>>()?;

    let mut out = Vec::with_capacity(p.out_bytes);
    for g in groups {
        out.extend_from_slice(&g);
    }
    debug_assert_eq!(out.len(), p.out_bytes);
    Ok(out)
}

/// One row's encoder: f32 values and the row's importance weights in,
/// block bytes appended to `out`, `None` for a row that is not a whole
/// number of blocks.
pub(crate) type RowEncoder = fn(&[f32], Option<&[f32]>, &mut Vec<u8>) -> Option<()>;

/// The one place a ggml type is turned into the encoder that writes it,
/// and so the one answer to "can frink write this type": `plan` refuses
/// a type this returns `None` for before any byte is written, and
/// `encode_row` dispatches through it.
///
/// Keyed on the tensor's CHOSEN type, not on the target, because under
/// a mix they differ per tensor: one `Q4_K_M` run writes Q4_K, Q5_K,
/// Q6_K and Q8_0 rows, and every target writes Q4_0 for a shared-KV
/// layer's unused `attn_k` / `attn_v`.
///
/// Q8_0 takes no importance weights, because `quantize_q8_0` discards
/// its `quant_weights` (`ggml-quants.c:2089`), and passing them through
/// would read as coverage.
pub(crate) fn row_encoder(ty: GgmlType) -> Option<RowEncoder> {
    let enc: RowEncoder = match ty {
        GgmlType::Q8_0 => |row, _qw, out| frink_quant::encode_row_q8_0(row, out),
        GgmlType::Q4_0 => frink_quant::encode_row_q4_0,
        GgmlType::Q4K => frink_quant::encode_row_q4_k,
        GgmlType::Q5K => frink_quant::encode_row_q5_k,
        GgmlType::Q6K => frink_quant::encode_row_q6_k,
        _ => return None,
    };
    Some(enc)
}

/// Encodes one row as `ty`. `Err` for a type `plan` should have refused
/// before reaching here -- an encoder dispatch whose fallthrough
/// silently copies or zero-fills is how a format becomes "supported" in
/// a table and nowhere else.
fn encode_row(
    ty: GgmlType,
    row: &[f32],
    qw: Option<&[f32]>,
    out: &mut Vec<u8>,
) -> Result<Option<()>> {
    let Some(enc) = row_encoder(ty) else {
        bail!(
            "the plan chose {ty:?} for a tensor and `frink quantize` has no encoder for it. \
             This is a bug in the planner, not in the checkpoint: `plan` refuses an unwritable \
             type before any byte is written."
        );
    };
    Ok(enc(row, qw, out))
}

fn source_bytes_per_element(dtype: GgmlType) -> usize {
    match dtype {
        GgmlType::F32 => 4,
        GgmlType::F16 | GgmlType::BF16 => 2,
        // `plan` refuses every other source dtype before this is
        // reached; 0 would produce a zero-length row and a silently
        // wrong file, so make it impossible to compute one.
        other => unreachable!("source dtype {other:?} reached the encoder"),
    }
}

fn decode_source_row(dtype: GgmlType, row: &[u8], out: &mut [f32]) -> Result<()> {
    match dtype {
        GgmlType::F32 => {
            for (o, c) in out.iter_mut().zip(row.as_chunks::<4>().0) {
                *o = f32::from_le_bytes(*c);
            }
        }
        GgmlType::F16 => {
            for (o, c) in out.iter_mut().zip(row.as_chunks::<2>().0) {
                *o = half::f16::from_le_bytes(*c).to_f32();
            }
        }
        GgmlType::BF16 => {
            // BF16 is f32's top 16 bits, so the widening is a shift,
            // not a format conversion.
            for (o, c) in out.iter_mut().zip(row.as_chunks::<2>().0) {
                *o = f32::from_bits(u32::from(u16::from_le_bytes(*c)) << 16);
            }
        }
        other => bail!("source dtype {other:?} reached the encoder"),
    }
    Ok(())
}

#[cfg(test)]
mod tests;