1use std::fs::File;
2use std::io::BufWriter;
3use std::path::{Path, PathBuf};
4
5use anyhow::Context;
6use indicatif::{ProgressBar, ProgressStyle};
7use safetensors::SafeTensors;
8use safetensors::Dtype as StDtype;
9
10use zsfm_gguf::{GGMLType, GGUFMetaValue, GGUFWriter};
11
12use crate::config::Moirai2Config;
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: &Moirai2Config,
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"))?;
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 let _outermost = py_shape.first().copied().unwrap_or(1);
72
73 let (dst_dtype, gguf_shape, tensor_data) =
74 if opts.output_dtype == GGMLType::Q8_0 && (innermost % 32 != 0 || n_elems % 32 != 0) {
75 fallback_count += 1;
76 let data = cast_data(raw_data, src_dtype, GGMLType::F32)?;
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 let gs = py_shape.iter().rev().map(|&d| d as u64).collect();
83 (dst, gs, data)
84 };
85
86 writer.add_tensor(gguf_name, gguf_shape, dst_dtype, tensor_data);
87 mapped += 1;
88 pb.inc(1);
89 }
90 }
91
92 pb.finish_with_message("tensors processed");
93
94 if !skipped.is_empty() {
95 eprintln!("\nWarning: {} tensor(s) skipped:", skipped.len());
96 for name in &skipped { eprintln!(" {name}"); }
97 }
98 if fallback_count > 0 {
99 eprintln!("\nNote: {fallback_count} tensor(s) fell back to F32.");
100 }
101
102 println!("Writing {mapped} tensors to {} …", output_path.display());
103 let out_file = File::create(output_path)?;
104 let mut buf_writer = BufWriter::new(out_file);
105 writer.write_to(&mut buf_writer)?;
106 println!("Done.");
107 Ok(())
108}
109
110fn write_metadata(writer: &mut GGUFWriter, config: &Moirai2Config) {
111 writer.add_metadata("general.architecture", GGUFMetaValue::String("moirai2".into()));
112 writer.add_metadata("general.name", GGUFMetaValue::String("Moirai-2.0-R-small".into()));
113 writer.add_metadata("moirai2.d_model", GGUFMetaValue::Uint32(config.d_model as u32));
114 writer.add_metadata("moirai2.n_layers", GGUFMetaValue::Uint32(config.n_layers as u32));
115 writer.add_metadata("moirai2.n_heads", GGUFMetaValue::Uint32(config.n_heads as u32));
116 writer.add_metadata("moirai2.head_dim", GGUFMetaValue::Uint32(config.head_dim as u32));
117 writer.add_metadata("moirai2.d_ff", GGUFMetaValue::Uint32(config.d_ff as u32));
118 writer.add_metadata("moirai2.patch_size", GGUFMetaValue::Uint32(config.patch_size as u32));
119 writer.add_metadata("moirai2.num_predict_token", GGUFMetaValue::Uint32(config.num_predict_token as u32));
120 writer.add_metadata("moirai2.num_quantiles", GGUFMetaValue::Uint32(config.num_quantiles as u32));
121 writer.add_metadata("moirai2.max_seq_len", GGUFMetaValue::Uint32(config.max_seq_len as u32));
122 writer.add_metadata("moirai2.rope_dim", GGUFMetaValue::Uint32(config.rope_dim as u32));
123}
124
125fn ggml_type_from_st(dtype: StDtype) -> anyhow::Result<GGMLType> {
126 match dtype {
127 StDtype::F32 => Ok(GGMLType::F32),
128 StDtype::F16 => Ok(GGMLType::F16),
129 StDtype::BF16 => Ok(GGMLType::BF16),
130 other => anyhow::bail!("unsupported dtype: {other:?}"),
131 }
132}
133
134fn cast_data(data: &[u8], src: GGMLType, dst: GGMLType) -> anyhow::Result<Vec<u8>> {
135 if src == dst { return Ok(data.to_vec()); }
136 if dst == GGMLType::Q8_0 { return quantize_q8_0(&decode_to_f32(data, src)?); }
137 match (src, dst) {
138 (GGMLType::F32, GGMLType::F16) => {
139 let vals = parse_f32_le(data)?;
140 let mut out = Vec::with_capacity(vals.len() * 2);
141 for v in vals { out.extend_from_slice(&f32_to_f16_bits(v).to_le_bytes()); }
142 Ok(out)
143 }
144 (GGMLType::F32, GGMLType::BF16) => {
145 let vals = parse_f32_le(data)?;
146 let mut out = Vec::with_capacity(vals.len() * 2);
147 for v in vals { out.extend_from_slice(&((v.to_bits() >> 16) as u16).to_le_bytes()); }
148 Ok(out)
149 }
150 (GGMLType::F16, GGMLType::BF16) => {
151 let mut out = Vec::with_capacity(data.len());
152 for c in data.chunks_exact(2) {
153 let f32_val = f16_to_f32(u16::from_le_bytes([c[0], c[1]]));
154 out.extend_from_slice(&((f32_val.to_bits() >> 16) as u16).to_le_bytes());
155 }
156 Ok(out)
157 }
158 (GGMLType::BF16, GGMLType::F32) => {
159 let mut out = Vec::with_capacity(data.len() * 2);
160 for c in data.chunks_exact(2) {
161 let bits = (u16::from_le_bytes([c[0], c[1]]) as u32) << 16;
162 out.extend_from_slice(&bits.to_le_bytes());
163 }
164 Ok(out)
165 }
166 (GGMLType::BF16, GGMLType::F16) => {
167 let mut out = Vec::with_capacity(data.len());
168 for c in data.chunks_exact(2) {
169 let bits = (u16::from_le_bytes([c[0], c[1]]) as u32) << 16;
170 out.extend_from_slice(&f32_to_f16_bits(f32::from_bits(bits)).to_le_bytes());
171 }
172 Ok(out)
173 }
174 (GGMLType::F16, GGMLType::F32) => {
175 let mut out = Vec::with_capacity(data.len() * 2);
176 for c in data.chunks_exact(2) {
177 out.extend_from_slice(&f16_to_f32(u16::from_le_bytes([c[0], c[1]])).to_bits().to_le_bytes());
178 }
179 Ok(out)
180 }
181 _ => anyhow::bail!("unsupported cast: {src:?} → {dst:?}"),
182 }
183}
184
185fn decode_to_f32(data: &[u8], src: GGMLType) -> anyhow::Result<Vec<f32>> {
186 match src {
187 GGMLType::F32 => parse_f32_le(data),
188 GGMLType::F16 => data.chunks_exact(2).map(|c| Ok(f16_to_f32(u16::from_le_bytes([c[0], c[1]])))).collect(),
189 GGMLType::BF16 => data.chunks_exact(2).map(|c| Ok(f32::from_bits((u16::from_le_bytes([c[0], c[1]]) as u32) << 16))).collect(),
190 GGMLType::Q8_0 => anyhow::bail!("Q8_0 as source not supported"),
191 }
192}
193
194fn quantize_q8_0(values: &[f32]) -> anyhow::Result<Vec<u8>> {
195 const BLOCK: usize = 32;
196 if values.len() % BLOCK != 0 { anyhow::bail!("Q8_0 requires divisibility by {BLOCK}"); }
197 let n_blocks = values.len() / BLOCK;
198 let mut out = vec![0u8; n_blocks * 34];
199 for b in 0..n_blocks {
200 let blk = &values[b * BLOCK..(b + 1) * BLOCK];
201 let amax = blk.iter().copied().map(f32::abs).fold(0.0f32, f32::max);
202 let d = if amax == 0.0 { 0.0f32 } else { amax / 127.0 };
203 let d_inv = if d == 0.0 { 0.0f32 } else { 1.0 / d };
204 let base = b * 34;
205 out[base..base + 2].copy_from_slice(&f32_to_f16_bits(d).to_le_bytes());
206 for i in 0..BLOCK { out[base + 2 + i] = (blk[i] * d_inv).round().clamp(-127.0, 127.0) as i8 as u8; }
207 }
208 Ok(out)
209}
210
211fn parse_f32_le(data: &[u8]) -> anyhow::Result<Vec<f32>> {
212 if data.len() % 4 != 0 { anyhow::bail!("f32 data length not divisible by 4"); }
213 Ok(data.chunks_exact(4).map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])).collect())
214}
215
216fn f32_to_f16_bits(v: f32) -> u16 {
217 let bits = v.to_bits();
218 let sign = ((bits >> 16) & 0x8000) as u16;
219 let exp = ((bits >> 23) & 0xFF) as i32;
220 let mantissa = bits & 0x007F_FFFF;
221 if exp == 0xFF { return sign | 0x7C00 | if mantissa != 0 { 0x0200 } else { 0 }; }
222 let new_exp = exp - 127 + 15;
223 if new_exp >= 31 { return sign | 0x7C00; }
224 if new_exp <= 0 {
225 if new_exp < -10 { return sign; }
226 let m = (mantissa | 0x0080_0000) >> (1 - new_exp);
227 return sign | (m >> 13) as u16;
228 }
229 sign | ((new_exp as u16) << 10) | (mantissa >> 13) as u16
230}
231
232fn f16_to_f32(bits: u16) -> f32 {
233 let sign = ((bits & 0x8000) as u32) << 16;
234 let exp = ((bits >> 10) & 0x1F) as i32;
235 let mantissa = (bits & 0x03FF) as u32;
236 let f32_bits = if exp == 0 {
237 if mantissa == 0 { sign }
238 else {
239 let mut m = mantissa; let mut e = 0i32;
240 while m & 0x0400 == 0 { m <<= 1; e += 1; }
241 sign | ((127 - 15 - e + 1) as u32) << 23 | (m & 0x03FF) << 13
242 }
243 } else if exp == 31 { sign | 0x7F80_0000 | (mantissa << 13) }
244 else { sign | ((exp + 127 - 15) as u32) << 23 | (mantissa << 13) };
245 f32::from_bits(f32_bits)
246}