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