Skip to main content

zsfm_mitra/
convert.rs

1use std::fs::File;
2use std::io::BufWriter;
3use std::path::{Path, PathBuf};
4
5use anyhow::Context;
6use indicatif::{ProgressBar, ProgressStyle};
7use safetensors::Dtype as StDtype;
8use safetensors::SafeTensors;
9
10use zsfm_gguf::{GGMLType, GGUFMetaValue, GGUFWriter};
11
12use crate::config::{MitraConfig, Task};
13use crate::tensor_map::map_tensor_name;
14
15pub struct ConvertOptions {
16    pub output_dtype: GGMLType,
17}
18
19pub fn convert(
20    shard_paths: &[PathBuf],
21    config: &MitraConfig,
22    opts: &ConvertOptions,
23    output_path: &Path,
24) -> anyhow::Result<()> {
25    let mut writer = GGUFWriter::new();
26    write_metadata(&mut writer, config);
27
28    let shard_bytes: Vec<Vec<u8>> = shard_paths
29        .iter()
30        .map(|p| std::fs::read(p).with_context(|| format!("read {}", p.display())))
31        .collect::<anyhow::Result<_>>()?;
32    let shard_views: Vec<SafeTensors> = shard_bytes
33        .iter()
34        .map(|b| SafeTensors::deserialize(b).context("deserialize shard"))
35        .collect::<anyhow::Result<_>>()?;
36
37    let total: usize = shard_views.iter().map(|s| s.len()).sum();
38    let pb = ProgressBar::new(total as u64);
39    pb.set_style(
40        ProgressStyle::with_template(
41            "{spinner:.green} [{elapsed_precise}] [{bar:40.cyan/blue}] {pos}/{len} {msg}",
42        )
43        .unwrap()
44        .progress_chars("=>-"),
45    );
46
47    let mut mapped = 0usize;
48    let mut skipped: Vec<String> = Vec::new();
49    let mut fallback_count = 0usize;
50
51    for shard in &shard_views {
52        for (hf_name, tensor_view) in shard.tensors() {
53            pb.set_message(hf_name.to_string());
54
55            let gguf_name = match map_tensor_name(&hf_name) {
56                Some(n) => n,
57                None => {
58                    skipped.push(hf_name.to_string());
59                    pb.inc(1);
60                    continue;
61                }
62            };
63
64            let src_dtype = ggml_type_from_st(tensor_view.dtype())
65                .with_context(|| format!("tensor {hf_name}: unsupported dtype {:?}", tensor_view.dtype()))?;
66
67            let raw_data = tensor_view.data();
68            let py_shape = tensor_view.shape();
69            let n_elems: usize = py_shape.iter().product();
70            let innermost = py_shape.last().copied().unwrap_or(1);
71
72            let (dst_dtype, gguf_shape, tensor_data) =
73                if opts.output_dtype == GGMLType::Q8_0 && (innermost % 32 != 0 || n_elems % 32 != 0) {
74                    fallback_count += 1;
75                    let data = cast_data(raw_data, src_dtype, GGMLType::F32)
76                        .with_context(|| format!("tensor {hf_name}: cast failed"))?;
77                    let gs = py_shape.iter().rev().map(|&d| d as u64).collect();
78                    (GGMLType::F32, gs, data)
79                } else {
80                    let dst = opts.output_dtype;
81                    let data = cast_data(raw_data, src_dtype, dst)
82                        .with_context(|| format!("tensor {hf_name}: cast failed"))?;
83                    let gs = py_shape.iter().rev().map(|&d| d as u64).collect();
84                    (dst, gs, data)
85                };
86
87            writer.add_tensor(gguf_name, gguf_shape, dst_dtype, tensor_data);
88            mapped += 1;
89            pb.inc(1);
90        }
91    }
92
93    pb.finish_with_message("tensors processed");
94
95    if !skipped.is_empty() {
96        eprintln!("\nWarning: {} tensor(s) skipped:", skipped.len());
97        for name in &skipped {
98            eprintln!("  {name}");
99        }
100    }
101    if fallback_count > 0 {
102        eprintln!("\nNote: {fallback_count} tensor(s) fell back to F32.");
103    }
104
105    println!("Writing {mapped} tensors to {} …", output_path.display());
106    let out_file = File::create(output_path).with_context(|| format!("create {}", output_path.display()))?;
107    let mut buf_writer = BufWriter::new(out_file);
108    writer.write_to(&mut buf_writer)?;
109    println!("Done.");
110    Ok(())
111}
112
113fn write_metadata(writer: &mut GGUFWriter, config: &MitraConfig) {
114    writer.add_metadata("general.architecture", GGUFMetaValue::String("mitra".into()));
115    writer.add_metadata(
116        "general.name",
117        GGUFMetaValue::String(
118            match config.task {
119                Task::Classification => "autogluon/mitra-classifier",
120                Task::Regression => "autogluon/mitra-regressor",
121            }
122            .into(),
123        ),
124    );
125    writer.add_metadata(
126        "task",
127        GGUFMetaValue::String(
128            match config.task {
129                Task::Classification => "classification",
130                Task::Regression => "regression",
131            }
132            .into(),
133        ),
134    );
135    writer.add_metadata("mitra.dim", GGUFMetaValue::Uint32(config.dim as u32));
136    writer.add_metadata("mitra.n_layers", GGUFMetaValue::Uint32(config.n_layers as u32));
137    writer.add_metadata("mitra.n_heads", GGUFMetaValue::Uint32(config.n_heads as u32));
138    writer.add_metadata("mitra.dim_output", GGUFMetaValue::Uint32(config.dim_output as u32));
139}
140
141fn ggml_type_from_st(dtype: StDtype) -> anyhow::Result<GGMLType> {
142    match dtype {
143        StDtype::F32 => Ok(GGMLType::F32),
144        StDtype::F16 => Ok(GGMLType::F16),
145        StDtype::BF16 => Ok(GGMLType::BF16),
146        other => anyhow::bail!("unsupported safetensors dtype: {other:?}"),
147    }
148}
149
150fn cast_data(data: &[u8], src: GGMLType, dst: GGMLType) -> anyhow::Result<Vec<u8>> {
151    if src == dst {
152        return Ok(data.to_vec());
153    }
154    if dst == GGMLType::Q8_0 {
155        let f32_values = decode_to_f32(data, src)?;
156        return quantize_q8_0(&f32_values);
157    }
158    match (src, dst) {
159        (GGMLType::F32, GGMLType::F16) => {
160            let vals = parse_f32_le(data)?;
161            let mut out = Vec::with_capacity(vals.len() * 2);
162            for v in vals {
163                out.extend_from_slice(&f32_to_f16_bits(v).to_le_bytes());
164            }
165            Ok(out)
166        }
167        (GGMLType::F32, GGMLType::BF16) => {
168            let vals = parse_f32_le(data)?;
169            let mut out = Vec::with_capacity(vals.len() * 2);
170            for v in vals {
171                out.extend_from_slice(&((v.to_bits() >> 16) as u16).to_le_bytes());
172            }
173            Ok(out)
174        }
175        (GGMLType::F16, GGMLType::BF16) => {
176            let mut out = Vec::with_capacity(data.len());
177            for c in data.chunks_exact(2) {
178                let f32_val = f16_to_f32(u16::from_le_bytes([c[0], c[1]]));
179                out.extend_from_slice(&((f32_val.to_bits() >> 16) as u16).to_le_bytes());
180            }
181            Ok(out)
182        }
183        (GGMLType::BF16, GGMLType::F32) => {
184            let mut out = Vec::with_capacity(data.len() * 2);
185            for c in data.chunks_exact(2) {
186                let bits = (u16::from_le_bytes([c[0], c[1]]) as u32) << 16;
187                out.extend_from_slice(&bits.to_le_bytes());
188            }
189            Ok(out)
190        }
191        (GGMLType::BF16, GGMLType::F16) => {
192            let mut out = Vec::with_capacity(data.len());
193            for c in data.chunks_exact(2) {
194                let bits = (u16::from_le_bytes([c[0], c[1]]) as u32) << 16;
195                out.extend_from_slice(&f32_to_f16_bits(f32::from_bits(bits)).to_le_bytes());
196            }
197            Ok(out)
198        }
199        (GGMLType::F16, GGMLType::F32) => {
200            let mut out = Vec::with_capacity(data.len() * 2);
201            for c in data.chunks_exact(2) {
202                out.extend_from_slice(&f16_to_f32(u16::from_le_bytes([c[0], c[1]])).to_bits().to_le_bytes());
203            }
204            Ok(out)
205        }
206        _ => anyhow::bail!("unsupported cast: {src:?} → {dst:?}"),
207    }
208}
209
210fn decode_to_f32(data: &[u8], src: GGMLType) -> anyhow::Result<Vec<f32>> {
211    match src {
212        GGMLType::F32 => parse_f32_le(data),
213        GGMLType::F16 => data
214            .chunks_exact(2)
215            .map(|c| Ok(f16_to_f32(u16::from_le_bytes([c[0], c[1]]))))
216            .collect(),
217        GGMLType::BF16 => data
218            .chunks_exact(2)
219            .map(|c| Ok(f32::from_bits((u16::from_le_bytes([c[0], c[1]]) as u32) << 16)))
220            .collect(),
221        GGMLType::Q8_0 => anyhow::bail!("Q8_0 as source not supported"),
222    }
223}
224
225fn quantize_q8_0(values: &[f32]) -> anyhow::Result<Vec<u8>> {
226    const BLOCK: usize = 32;
227    if values.len() % BLOCK != 0 {
228        anyhow::bail!("Q8_0 requires count divisible by {BLOCK}");
229    }
230    let n_blocks = values.len() / BLOCK;
231    let mut out = vec![0u8; n_blocks * 34];
232    for b in 0..n_blocks {
233        let blk = &values[b * BLOCK..(b + 1) * BLOCK];
234        let amax = blk.iter().copied().map(f32::abs).fold(0.0f32, f32::max);
235        let d = if amax == 0.0 { 0.0f32 } else { amax / 127.0 };
236        let d_inv = if d == 0.0 { 0.0f32 } else { 1.0 / d };
237        let base = b * 34;
238        out[base..base + 2].copy_from_slice(&f32_to_f16_bits(d).to_le_bytes());
239        for i in 0..BLOCK {
240            out[base + 2 + i] = (blk[i] * d_inv).round().clamp(-127.0, 127.0) as i8 as u8;
241        }
242    }
243    Ok(out)
244}
245
246fn parse_f32_le(data: &[u8]) -> anyhow::Result<Vec<f32>> {
247    if data.len() % 4 != 0 {
248        anyhow::bail!("f32 data length not divisible by 4");
249    }
250    Ok(data.chunks_exact(4).map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])).collect())
251}
252
253fn f32_to_f16_bits(v: f32) -> u16 {
254    let bits = v.to_bits();
255    let sign = ((bits >> 16) & 0x8000) as u16;
256    let exp = ((bits >> 23) & 0xFF) as i32;
257    let mantissa = bits & 0x007F_FFFF;
258    if exp == 0xFF {
259        return sign | 0x7C00 | if mantissa != 0 { 0x0200 } else { 0 };
260    }
261    let new_exp = exp - 127 + 15;
262    if new_exp >= 31 {
263        return sign | 0x7C00;
264    }
265    if new_exp <= 0 {
266        if new_exp < -10 {
267            return sign;
268        }
269        let m = (mantissa | 0x0080_0000) >> (1 - new_exp);
270        return sign | (m >> 13) as u16;
271    }
272    sign | ((new_exp as u16) << 10) | (mantissa >> 13) as u16
273}
274
275fn f16_to_f32(bits: u16) -> f32 {
276    let sign = ((bits & 0x8000) as u32) << 16;
277    let exp = ((bits >> 10) & 0x1F) as i32;
278    let mantissa = (bits & 0x03FF) as u32;
279    let f32_bits = if exp == 0 {
280        if mantissa == 0 {
281            sign
282        } else {
283            let mut m = mantissa;
284            let mut e = 0i32;
285            while m & 0x0400 == 0 {
286                m <<= 1;
287                e += 1;
288            }
289            sign | ((127 - 15 - e + 1) as u32) << 23 | (m & 0x03FF) << 13
290        }
291    } else if exp == 31 {
292        sign | 0x7F80_0000 | (mantissa << 13)
293    } else {
294        sign | ((exp + 127 - 15) as u32) << 23 | (mantissa << 13)
295    };
296    f32::from_bits(f32_bits)
297}