Skip to main content

zsfm_toto/
convert.rs

1use std::fs::File;
2use std::io::BufWriter;
3use std::path::Path;
4
5use anyhow::Context;
6use indicatif::{ProgressBar, ProgressStyle};
7use safetensors::SafeTensors;
8
9use safetensors::Dtype as StDtype;
10
11use zsfm_gguf::{GGMLType, GGUFMetaValue, GGUFWriter};
12use zsfm_hub::ModelFiles;
13
14use crate::config::TotoConfig;
15use crate::tensor_map::map_tensor_name;
16
17/// Options that control how tensors are stored in the output GGUF.
18pub struct ConvertOptions {
19    /// Target dtype for all tensors in the output file.
20    pub output_dtype: GGMLType,
21}
22
23/// Read `files`, convert every tensor, and write a GGUF file to `output_path`.
24pub fn convert(
25    model_id: &str,
26    files: &ModelFiles,
27    config: &TotoConfig,
28    opts: &ConvertOptions,
29    output_path: &Path,
30) -> anyhow::Result<()> {
31    let mut writer = GGUFWriter::new();
32
33    // Embed Toto architecture metadata.
34    write_metadata(&mut writer, model_id, config);
35
36    // Discover all tensor names across shards before writing (we need a total
37    // for the progress bar and to detect duplicates).
38    let shard_bytes = load_shard_bytes(&files.safetensors_shards)?;
39    let shard_views: Vec<SafeTensors> = shard_bytes
40        .iter()
41        .map(|b| SafeTensors::deserialize(b).context("deserialize shard"))
42        .collect::<anyhow::Result<_>>()?;
43
44    let total_tensors: usize = shard_views.iter().map(|s| s.len()).sum();
45    println!(
46        "Found {} tensors across {} shard(s).",
47        total_tensors,
48        shard_views.len()
49    );
50
51    let pb = ProgressBar::new(total_tensors as u64);
52    pb.set_style(
53        ProgressStyle::with_template(
54            "{spinner:.green} [{elapsed_precise}] [{bar:40.cyan/blue}] {pos}/{len} {msg}",
55        )
56        .unwrap()
57        .progress_chars("=>-"),
58    );
59
60    let mut mapped = 0usize;
61    let mut skipped: Vec<String> = Vec::new();
62    let mut fallback_count = 0usize;
63
64    for shard in &shard_views {
65        for (hf_name, tensor_view) in shard.tensors() {
66            pb.set_message(hf_name.to_string());
67
68            let gguf_name = match map_tensor_name(&hf_name) {
69                Some(n) => n,
70                None => {
71                    skipped.push(hf_name.to_string());
72                    pb.inc(1);
73                    continue;
74                }
75            };
76
77            let src_dtype = ggml_type_from_st(tensor_view.dtype())
78                .with_context(|| format!("tensor {hf_name}: unsupported dtype {:?}", tensor_view.dtype()))?;
79
80            let raw_data = tensor_view.data();
81            let py_shape = tensor_view.shape(); // Python row-major: [d0, d1, ..., d_inner]
82            let n_elems: usize = py_shape.iter().product();
83            let innermost = py_shape.last().copied().unwrap_or(1);
84            let outermost = py_shape.first().copied().unwrap_or(1);
85
86            // Q8_0: candle requires the innermost dimension (last Python dim, first GGUF dim) to
87            // be divisible by 32. When that fails for a 2D weight with a block-aligned outermost
88            // dim, we transpose the data and flip the GGUF shape so candle sees the weight with
89            // the divisible dimension as innermost. The inference loader corrects the orientation.
90            let (dst_dtype, gguf_shape, tensor_data) =
91                if opts.output_dtype == GGMLType::Q8_0 && innermost % 32 != 0 {
92                    if py_shape.len() == 2 && outermost % 32 == 0 && n_elems % 32 == 0 {
93                        // Transpose: (d_out × d_in) → (d_in × d_out) so d_out becomes innermost.
94                        let f32_vals = decode_to_f32(raw_data, src_dtype)
95                            .with_context(|| format!("tensor {hf_name}: decode failed"))?;
96                        let transposed = transpose_f32(&f32_vals, outermost, innermost);
97                        let qdata = quantize_q8_0(&transposed)
98                            .with_context(|| format!("tensor {hf_name}: quantize failed"))?;
99                        // GGUF shape = Python shape order (NOT reversed). Candle reverses it back,
100                        // seeing (d_in, d_out) with last dim d_out divisible by 32.
101                        let gs = py_shape.iter().map(|&d| d as u64).collect();
102                        (GGMLType::Q8_0, gs, qdata)
103                    } else {
104                        // Can't transpose (1D scalar/bias or no suitable fallback dim) → F32.
105                        fallback_count += 1;
106                        let data = cast_data(raw_data, src_dtype, GGMLType::F32)
107                            .with_context(|| format!("tensor {hf_name}: cast failed"))?;
108                        let gs = py_shape.iter().rev().map(|&d| d as u64).collect();
109                        (GGMLType::F32, gs, data)
110                    }
111                } else if opts.output_dtype == GGMLType::Q8_0 && n_elems % 32 != 0 {
112                    // Scalar / tiny tensor — fall back to F32.
113                    fallback_count += 1;
114                    let data = cast_data(raw_data, src_dtype, GGMLType::F32)
115                        .with_context(|| format!("tensor {hf_name}: cast failed"))?;
116                    let gs = py_shape.iter().rev().map(|&d| d as u64).collect();
117                    (GGMLType::F32, gs, data)
118                } else {
119                    let dst = opts.output_dtype;
120                    let data = cast_data(raw_data, src_dtype, dst)
121                        .with_context(|| format!("tensor {hf_name}: cast failed"))?;
122                    let gs = py_shape.iter().rev().map(|&d| d as u64).collect();
123                    (dst, gs, data)
124                };
125
126            writer.add_tensor(gguf_name, gguf_shape, dst_dtype, tensor_data);
127            mapped += 1;
128            pb.inc(1);
129        }
130    }
131
132    pb.finish_with_message("tensors processed");
133
134    if !skipped.is_empty() {
135        eprintln!(
136            "\nWarning: {} tensor(s) had unrecognised names and were skipped:",
137            skipped.len()
138        );
139        for name in &skipped {
140            eprintln!("  {name}");
141        }
142        eprintln!("Update tensor_map.rs to include these if needed.");
143    }
144
145    if fallback_count > 0 {
146        eprintln!(
147            "\nNote: {fallback_count} tensor(s) fell back to F32 (scalars/biases too \
148             small for Q8_0 blocks)."
149        );
150    }
151    println!("Writing {mapped} tensors to {} …", output_path.display());
152    let out_file = File::create(output_path)
153        .with_context(|| format!("create output file {}", output_path.display()))?;
154    let mut buf_writer = BufWriter::new(out_file);
155    writer.write_to(&mut buf_writer)?;
156    println!("Done.");
157
158    Ok(())
159}
160
161fn ggml_type_from_st(dtype: StDtype) -> anyhow::Result<GGMLType> {
162    match dtype {
163        StDtype::F32 => Ok(GGMLType::F32),
164        StDtype::F16 => Ok(GGMLType::F16),
165        StDtype::BF16 => Ok(GGMLType::BF16),
166        other => anyhow::bail!("unsupported safetensors dtype: {other:?}"),
167    }
168}
169
170/// Build the GGUF metadata section from the parsed config.
171fn write_metadata(writer: &mut GGUFWriter, model_id: &str, config: &TotoConfig) {
172    writer.add_metadata("general.architecture", GGUFMetaValue::String("toto2".into()));
173    writer.add_metadata("general.name", GGUFMetaValue::String(model_id.into()));
174    writer.add_metadata(
175        "toto2.block_count",
176        GGUFMetaValue::Uint32(config.num_hidden_layers),
177    );
178    writer.add_metadata(
179        "toto2.embedding_length",
180        GGUFMetaValue::Uint32(config.hidden_size),
181    );
182    writer.add_metadata(
183        "toto2.attention.head_count",
184        GGUFMetaValue::Uint32(config.num_attention_heads),
185    );
186    writer.add_metadata(
187        "toto2.attention.head_count_kv",
188        GGUFMetaValue::Uint32(config.num_key_value_heads),
189    );
190    writer.add_metadata(
191        "toto2.attention.head_dim",
192        GGUFMetaValue::Uint32(config.head_dim),
193    );
194    writer.add_metadata(
195        "toto2.patch_size",
196        GGUFMetaValue::Uint32(config.patch_size),
197    );
198    writer.add_metadata(
199        "toto2.quantile_count",
200        GGUFMetaValue::Uint32(config.num_quantiles),
201    );
202}
203
204/// Memory-map and read each shard file into a `Vec<u8>`.
205fn load_shard_bytes(shards: &[std::path::PathBuf]) -> anyhow::Result<Vec<Vec<u8>>> {
206    shards
207        .iter()
208        .map(|p| {
209            std::fs::read(p).with_context(|| format!("read shard {}", p.display()))
210        })
211        .collect()
212}
213
214/// Cast tensor bytes from `src_dtype` to `dst_dtype`.
215/// If both are the same non-quantized dtype, returns a copy of the input bytes.
216fn cast_data(data: &[u8], src: GGMLType, dst: GGMLType) -> anyhow::Result<Vec<u8>> {
217    if src == dst {
218        return Ok(data.to_vec());
219    }
220
221    // For Q8_0 destination: decode to f32 first, then quantize.
222    if dst == GGMLType::Q8_0 {
223        let f32_values = decode_to_f32(data, src)?;
224        return quantize_q8_0(&f32_values);
225    }
226
227    match (src, dst) {
228        (GGMLType::F32, GGMLType::F16) => {
229            let f32_values = parse_f32_le(data)?;
230            let mut out = Vec::with_capacity(f32_values.len() * 2);
231            for v in f32_values {
232                let bits = f32_to_f16_bits(v);
233                out.extend_from_slice(&bits.to_le_bytes());
234            }
235            Ok(out)
236        }
237        (GGMLType::F32, GGMLType::BF16) => {
238            let f32_values = parse_f32_le(data)?;
239            let mut out = Vec::with_capacity(f32_values.len() * 2);
240            for v in f32_values {
241                let bits = (v.to_bits() >> 16) as u16;
242                out.extend_from_slice(&bits.to_le_bytes());
243            }
244            Ok(out)
245        }
246        (GGMLType::F16, GGMLType::BF16) => {
247            let mut out = Vec::with_capacity(data.len());
248            for chunk in data.chunks_exact(2) {
249                let f16_bits = u16::from_le_bytes([chunk[0], chunk[1]]);
250                let f32_val = f16_to_f32(f16_bits);
251                let bits = (f32_val.to_bits() >> 16) as u16;
252                out.extend_from_slice(&bits.to_le_bytes());
253            }
254            Ok(out)
255        }
256        (GGMLType::BF16, GGMLType::F32) => {
257            let mut out = Vec::with_capacity(data.len() * 2);
258            for chunk in data.chunks_exact(2) {
259                let bf16_bits = u16::from_le_bytes([chunk[0], chunk[1]]);
260                let f32_bits = (bf16_bits as u32) << 16;
261                out.extend_from_slice(&f32_bits.to_le_bytes());
262            }
263            Ok(out)
264        }
265        (GGMLType::BF16, GGMLType::F16) => {
266            // BF16 → F32 → F16
267            let mut out = Vec::with_capacity(data.len());
268            for chunk in data.chunks_exact(2) {
269                let bf16_bits = u16::from_le_bytes([chunk[0], chunk[1]]);
270                let f32_bits = (bf16_bits as u32) << 16;
271                let f32_val = f32::from_bits(f32_bits);
272                let f16_bits = f32_to_f16_bits(f32_val);
273                out.extend_from_slice(&f16_bits.to_le_bytes());
274            }
275            Ok(out)
276        }
277        (GGMLType::F16, GGMLType::F32) => {
278            let mut out = Vec::with_capacity(data.len() * 2);
279            for chunk in data.chunks_exact(2) {
280                let f16_bits = u16::from_le_bytes([chunk[0], chunk[1]]);
281                let f32_val = f16_to_f32(f16_bits);
282                out.extend_from_slice(&f32_val.to_bits().to_le_bytes());
283            }
284            Ok(out)
285        }
286        _ => anyhow::bail!("unsupported cast: {src:?} → {dst:?}"),
287    }
288}
289
290/// Decode any supported float dtype to a Vec<f32>.
291fn decode_to_f32(data: &[u8], src: GGMLType) -> anyhow::Result<Vec<f32>> {
292    match src {
293        GGMLType::F32 => parse_f32_le(data),
294        GGMLType::F16 => {
295            data.chunks_exact(2)
296                .map(|c| Ok(f16_to_f32(u16::from_le_bytes([c[0], c[1]]))))
297                .collect()
298        }
299        GGMLType::BF16 => {
300            data.chunks_exact(2)
301                .map(|c| {
302                    let bf16_bits = u16::from_le_bytes([c[0], c[1]]);
303                    Ok(f32::from_bits((bf16_bits as u32) << 16))
304                })
305                .collect()
306        }
307        GGMLType::Q8_0 => anyhow::bail!("Q8_0 → Q8_0 re-quantization not supported as source"),
308    }
309}
310
311/// Transpose a flat (n_rows × n_cols) row-major F32 array to (n_cols × n_rows).
312fn transpose_f32(data: &[f32], n_rows: usize, n_cols: usize) -> Vec<f32> {
313    let mut out = vec![0.0f32; n_rows * n_cols];
314    for r in 0..n_rows {
315        for c in 0..n_cols {
316            out[c * n_rows + r] = data[r * n_cols + c];
317        }
318    }
319    out
320}
321
322/// Quantize a slice of f32 values to GGML Q8_0 block format.
323///
324/// Each block: `[f16 scale (2 bytes)][32 × i8 (32 bytes)]` = 34 bytes.
325/// Requires `values.len()` to be a multiple of 32.
326fn quantize_q8_0(values: &[f32]) -> anyhow::Result<Vec<u8>> {
327    const BLOCK: usize = 32;
328    if values.len() % BLOCK != 0 {
329        anyhow::bail!(
330            "Q8_0 requires element count divisible by {BLOCK}, got {}",
331            values.len()
332        );
333    }
334    let n_blocks = values.len() / BLOCK;
335    let mut out = vec![0u8; n_blocks * 34];
336
337    for b in 0..n_blocks {
338        let blk = &values[b * BLOCK..(b + 1) * BLOCK];
339        let amax = blk.iter().copied().map(f32::abs).fold(0.0f32, f32::max);
340        let d = if amax == 0.0 { 0.0f32 } else { amax / 127.0 };
341        let d_inv = if d == 0.0 { 0.0f32 } else { 1.0 / d };
342
343        let base = b * 34;
344        let d_f16 = f32_to_f16_bits(d);
345        out[base..base + 2].copy_from_slice(&d_f16.to_le_bytes());
346        for i in 0..BLOCK {
347            let q = (blk[i] * d_inv).round().clamp(-127.0, 127.0) as i8;
348            out[base + 2 + i] = q as u8;
349        }
350    }
351    Ok(out)
352}
353
354/// Parse a little-endian byte slice into a Vec<f32> (len must be divisible by 4).
355fn parse_f32_le(data: &[u8]) -> anyhow::Result<Vec<f32>> {
356    if data.len() % 4 != 0 {
357        anyhow::bail!("f32 data length not divisible by 4");
358    }
359    Ok(data.chunks_exact(4)
360        .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]]))
361        .collect())
362}
363
364/// Convert f32 to IEEE 754 binary16 bit pattern.
365fn f32_to_f16_bits(v: f32) -> u16 {
366    // Fast software path — no hardware f16 needed.
367    let bits = v.to_bits();
368    let sign = ((bits >> 16) & 0x8000) as u16;
369    let exp = ((bits >> 23) & 0xFF) as i32;
370    let mantissa = bits & 0x007F_FFFF;
371
372    if exp == 0xFF {
373        // NaN or Inf
374        return sign | 0x7C00 | if mantissa != 0 { 0x0200 } else { 0 };
375    }
376
377    let new_exp = exp - 127 + 15;
378    if new_exp >= 31 {
379        return sign | 0x7C00; // Inf
380    }
381    if new_exp <= 0 {
382        if new_exp < -10 {
383            return sign; // Underflow to zero
384        }
385        // Subnormal
386        let m = (mantissa | 0x0080_0000) >> (1 - new_exp);
387        return sign | (m >> 13) as u16;
388    }
389    sign | ((new_exp as u16) << 10) | (mantissa >> 13) as u16
390}
391
392/// Convert IEEE 754 binary16 bit pattern to f32.
393fn f16_to_f32(bits: u16) -> f32 {
394    let sign = ((bits & 0x8000) as u32) << 16;
395    let exp = ((bits >> 10) & 0x1F) as i32;
396    let mantissa = (bits & 0x03FF) as u32;
397
398    let f32_bits = if exp == 0 {
399        if mantissa == 0 {
400            sign
401        } else {
402            // Subnormal → normalise
403            let mut m = mantissa;
404            let mut e = 0i32;
405            while m & 0x0400 == 0 {
406                m <<= 1;
407                e += 1;
408            }
409            sign | ((127 - 15 - e + 1) as u32) << 23 | (m & 0x03FF) << 13
410        }
411    } else if exp == 31 {
412        sign | 0x7F80_0000 | (mantissa << 13)
413    } else {
414        sign | ((exp + 127 - 15) as u32) << 23 | (mantissa << 13)
415    };
416    f32::from_bits(f32_bits)
417}