1use crate::units::MIB;
21use serde::{Deserialize, Serialize};
22use std::collections::BTreeMap;
23use thiserror::Error;
24
25pub const MAX_KEPT_INT_ARRAY: u64 = 4096;
27pub const MAX_LAYERS: u64 = 65_536;
30pub const DEFAULT_CTX: u64 = 4096;
33pub const DEFAULT_CTX_CAP: u64 = 8192;
34pub const FALLBACK_FACTOR: f64 = 1.2;
36pub const SAFETENSORS_MAX_HEADER: u64 = 100_000_000;
38
39#[derive(Debug, Error, Clone, PartialEq, Eq)]
40pub enum GgufError {
41 #[error("not a GGUF file (bad magic)")]
42 BadMagic,
43 #[error("unsupported GGUF version {0}")]
44 Version(u32),
45 #[error("header truncated at byte {0}")]
46 Truncated(usize),
47 #[error("invalid value type {0}")]
48 BadType(u32),
49 #[error("invalid utf-8 in key or string")]
50 Utf8,
51}
52
53#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
55#[serde(untagged)]
56pub enum GgufValue {
57 Int(i64),
58 UInt(u64),
59 Float(f64),
60 Bool(bool),
61 Str(String),
62 Array {
64 len: u64,
65 },
66 IntArray(Vec<i64>),
68}
69
70impl GgufValue {
71 pub fn as_u64(&self) -> Option<u64> {
72 match self {
73 GgufValue::UInt(v) => Some(*v),
74 GgufValue::Int(v) if *v >= 0 => Some(*v as u64),
75 _ => None,
76 }
77 }
78 pub fn as_str(&self) -> Option<&str> {
79 match self {
80 GgufValue::Str(s) => Some(s),
81 _ => None,
82 }
83 }
84 pub fn as_u64_list(&self) -> Option<Vec<u64>> {
86 match self {
87 GgufValue::IntArray(v) => v.iter().map(|x| u64::try_from(*x).ok()).collect(),
88 other => other.as_u64().map(|x| vec![x]),
89 }
90 }
91}
92
93#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
94pub struct GgufMeta {
95 pub version: u32,
96 pub tensor_count: u64,
97 pub kv: BTreeMap<String, GgufValue>,
98 pub truncated: bool,
100}
101
102impl GgufMeta {
103 pub fn architecture(&self) -> Option<&str> {
104 self.kv.get("general.architecture").and_then(|v| v.as_str())
105 }
106 pub fn name(&self) -> Option<&str> {
107 self.kv.get("general.name").and_then(|v| v.as_str())
108 }
109 pub fn file_type(&self) -> Option<u64> {
111 self.kv.get("general.file_type").and_then(|v| v.as_u64())
112 }
113 fn arch_value(&self, suffix: &str) -> Option<&GgufValue> {
114 let arch = self.architecture()?;
115 self.kv.get(&format!("{arch}.{suffix}"))
116 }
117 fn arch_u64(&self, suffix: &str) -> Option<u64> {
118 self.arch_value(suffix).and_then(|v| v.as_u64())
119 }
120 fn arch_u64_max(&self, suffix: &str) -> Option<u64> {
122 self.arch_value(suffix)?.as_u64_list()?.into_iter().max()
123 }
124 pub fn n_layers(&self) -> Option<u64> {
126 self.arch_u64("block_count").filter(|l| *l <= MAX_LAYERS)
127 }
128 pub fn n_heads(&self) -> Option<u64> {
129 self.arch_u64_max("attention.head_count")
130 }
131 pub fn n_kv_heads(&self) -> Option<u64> {
133 self.arch_u64_max("attention.head_count_kv")
134 .or_else(|| self.n_heads())
135 }
136 pub fn kv_heads_per_layer(&self) -> Option<Vec<u64>> {
138 let layers = self.n_layers()?;
139 let v = self.kv_heads_list()?;
140 match v.len() {
141 1 => Some(vec![v[0]; layers as usize]),
142 n if n as u64 == layers => Some(v),
143 _ => None,
144 }
145 }
146 fn kv_heads_list(&self) -> Option<Vec<u64>> {
147 self.arch_value("attention.head_count_kv")
148 .or_else(|| self.arch_value("attention.head_count"))?
149 .as_u64_list()
150 }
151 pub fn kv_heads_sum(&self) -> Option<u64> {
153 let layers = self.n_layers()?;
154 let v = self.kv_heads_list()?;
155 match v.len() {
156 1 => Some(v[0].saturating_mul(layers)),
157 n if n as u64 == layers => Some(v.iter().fold(0u64, |a, b| a.saturating_add(*b))),
158 _ => None,
159 }
160 }
161 pub fn embedding_length(&self) -> Option<u64> {
162 self.arch_u64("embedding_length")
163 }
164 pub fn context_length(&self) -> Option<u64> {
165 self.arch_u64("context_length")
166 }
167 pub fn head_dim(&self) -> Option<u64> {
169 self.arch_u64("attention.key_length").or_else(|| {
170 let e = self.embedding_length()?;
171 let h = self.n_heads()?;
172 (h > 0).then(|| e / h)
173 })
174 }
175 pub fn value_dim(&self) -> Option<u64> {
177 self.arch_u64("attention.value_length")
178 .or_else(|| self.head_dim())
179 }
180 pub fn expert_count(&self) -> Option<u64> {
181 self.arch_u64("expert_count")
182 }
183}
184
185struct Cursor<'a> {
186 buf: &'a [u8],
187 pos: usize,
188}
189
190impl<'a> Cursor<'a> {
191 fn take(&mut self, n: usize) -> Result<&'a [u8], GgufError> {
192 let end = self.pos.checked_add(n).ok_or(GgufError::Truncated(self.pos))?;
193 if end > self.buf.len() {
194 return Err(GgufError::Truncated(self.pos));
195 }
196 let s = &self.buf[self.pos..end];
197 self.pos = end;
198 Ok(s)
199 }
200 fn arr<const N: usize>(&mut self) -> Result<[u8; N], GgufError> {
201 let s = self.take(N)?;
202 let mut a = [0u8; N];
203 a.copy_from_slice(s);
204 Ok(a)
205 }
206 fn u32(&mut self) -> Result<u32, GgufError> {
207 Ok(u32::from_le_bytes(self.arr()?))
208 }
209 fn u64(&mut self) -> Result<u64, GgufError> {
210 Ok(u64::from_le_bytes(self.arr()?))
211 }
212 fn len(&mut self) -> Result<usize, GgufError> {
213 let at = self.pos;
214 usize::try_from(self.u64()?).map_err(|_| GgufError::Truncated(at))
215 }
216 fn string(&mut self) -> Result<String, GgufError> {
217 let len = self.len()?;
218 let b = self.take(len)?;
219 String::from_utf8(b.to_vec()).map_err(|_| GgufError::Utf8)
220 }
221 fn string_lossy(&mut self) -> Result<String, GgufError> {
224 let len = self.len()?;
225 let b = self.take(len)?;
226 Ok(String::from_utf8_lossy(b).into_owned())
227 }
228 fn skip_string(&mut self) -> Result<(), GgufError> {
229 let len = self.len()?;
230 self.take(len).map(|_| ())
231 }
232 fn scalar_size(ty: u32) -> Option<usize> {
233 match ty {
234 0 | 1 | 7 => Some(1),
235 2 | 3 => Some(2),
236 4..=6 => Some(4),
237 10..=12 => Some(8),
238 _ => None,
239 }
240 }
241 fn int_scalar(&mut self, ty: u32) -> Result<Option<i64>, GgufError> {
242 Ok(match ty {
243 0 => Some(self.take(1)?[0] as i64),
244 1 => Some(self.take(1)?[0] as i8 as i64),
245 2 => Some(u16::from_le_bytes(self.arr()?) as i64),
246 3 => Some(i16::from_le_bytes(self.arr()?) as i64),
247 4 => Some(self.u32()? as i64),
248 5 => Some(self.u32()? as i32 as i64),
249 10 => Some(i64::try_from(self.u64()?).unwrap_or(i64::MAX)),
250 11 => Some(self.u64()? as i64),
251 _ => None,
252 })
253 }
254 fn value(&mut self, ty: u32, depth: u32) -> Result<GgufValue, GgufError> {
255 Ok(match ty {
256 0 => GgufValue::UInt(self.take(1)?[0] as u64),
257 1 => GgufValue::Int(self.take(1)?[0] as i8 as i64),
258 2 => GgufValue::UInt(u16::from_le_bytes(self.arr()?) as u64),
259 3 => GgufValue::Int(i16::from_le_bytes(self.arr()?) as i64),
260 4 => GgufValue::UInt(self.u32()? as u64),
261 5 => GgufValue::Int(self.u32()? as i32 as i64),
262 6 => GgufValue::Float(f32::from_bits(self.u32()?) as f64),
263 7 => GgufValue::Bool(self.take(1)?[0] != 0),
264 8 => GgufValue::Str(self.string_lossy()?),
265 9 => {
266 if depth > 8 {
267 return Err(GgufError::BadType(9));
268 }
269 let item_ty = self.u32()?;
270 let len = self.u64()?;
271 let is_int = matches!(item_ty, 0..=5 | 10 | 11);
272 if is_int && len <= MAX_KEPT_INT_ARRAY {
273 let mut v = Vec::with_capacity(len as usize);
274 for _ in 0..len {
275 if let Some(x) = self.int_scalar(item_ty)? {
276 v.push(x);
277 }
278 }
279 return Ok(GgufValue::IntArray(v));
280 }
281 if let Some(sz) = Self::scalar_size(item_ty) {
282 let total = usize::try_from(len)
283 .ok()
284 .and_then(|l| l.checked_mul(sz))
285 .ok_or(GgufError::Truncated(self.pos))?;
286 self.take(total)?;
287 } else if item_ty == 8 {
288 for _ in 0..len {
289 self.skip_string()?;
290 }
291 } else if item_ty == 9 {
292 for _ in 0..len {
294 self.value(9, depth + 1)?;
295 }
296 } else {
297 return Err(GgufError::BadType(item_ty));
298 }
299 GgufValue::Array { len }
300 }
301 10 => GgufValue::UInt(self.u64()?),
302 11 => GgufValue::Int(self.u64()? as i64),
303 12 => GgufValue::Float(f64::from_bits(self.u64()?)),
304 other => return Err(GgufError::BadType(other)),
305 })
306 }
307}
308
309pub fn parse_gguf_header(buf: &[u8]) -> Result<GgufMeta, GgufError> {
312 let mut c = Cursor { buf, pos: 0 };
313 if c.take(4).map_err(|_| GgufError::BadMagic)? != b"GGUF" {
314 return Err(GgufError::BadMagic);
315 }
316 let version = c.u32()?;
317 if !(2..=3).contains(&version) {
318 return Err(GgufError::Version(version));
319 }
320 let tensor_count = c.u64()?;
321 let kv_count = c.u64()?;
322 let mut meta = GgufMeta {
323 version,
324 tensor_count,
325 ..Default::default()
326 };
327 for _ in 0..kv_count {
328 let key = match c.string() {
329 Ok(k) => k,
330 Err(GgufError::Truncated(_)) => {
331 meta.truncated = true;
332 break;
333 }
334 Err(e) => return Err(e),
335 };
336 let ty = match c.u32() {
337 Ok(t) => t,
338 Err(_) => {
339 meta.truncated = true;
340 break;
341 }
342 };
343 match c.value(ty, 0) {
344 Ok(v) => {
345 meta.kv.insert(key, v);
346 }
347 Err(GgufError::Truncated(_)) => {
348 meta.truncated = true;
349 break;
350 }
351 Err(e) => return Err(e),
352 }
353 }
354 Ok(meta)
355}
356
357#[derive(Debug, Error, Clone, PartialEq, Eq)]
362pub enum SafetensorsError {
363 #[error("header truncated: need {needed} bytes")]
365 Truncated { needed: u64 },
366 #[error("header too large ({0} bytes)")]
367 TooLarge(u64),
368 #[error("invalid header JSON: {0}")]
369 Json(String),
370}
371
372#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
374#[serde(default)]
375pub struct SafetensorsHeader {
376 pub header_len: u64,
378 pub n_tensors: u64,
379 pub tensor_bytes: u64,
381 pub dtypes: BTreeMap<String, u64>,
383 pub metadata: BTreeMap<String, String>,
385}
386
387pub fn safetensors_dtype_bytes(dtype: &str) -> Option<f64> {
389 Some(match dtype {
390 "F64" | "I64" | "U64" => 8.0,
391 "F32" | "I32" | "U32" => 4.0,
392 "F16" | "BF16" | "I16" | "U16" => 2.0,
393 "F8_E4M3" | "F8_E5M2" | "F8_E8M0" | "I8" | "U8" | "BOOL" => 1.0,
394 "F4" | "F6_E2M3" | "F6_E3M2" => 0.5,
395 _ => return None,
396 })
397}
398
399pub fn parse_safetensors_header(buf: &[u8]) -> Result<SafetensorsHeader, SafetensorsError> {
402 if buf.len() < 8 {
403 return Err(SafetensorsError::Truncated { needed: 8 });
404 }
405 let mut lenb = [0u8; 8];
406 lenb.copy_from_slice(&buf[..8]);
407 let n = u64::from_le_bytes(lenb);
408 if n > SAFETENSORS_MAX_HEADER {
409 return Err(SafetensorsError::TooLarge(n));
410 }
411 let end = 8 + n as usize;
412 if buf.len() < end {
413 return Err(SafetensorsError::Truncated { needed: end as u64 });
414 }
415 let v: serde_json::Value =
416 serde_json::from_slice(&buf[8..end]).map_err(|e| SafetensorsError::Json(e.to_string()))?;
417 let obj = v
418 .as_object()
419 .ok_or_else(|| SafetensorsError::Json("header is not an object".into()))?;
420 let mut h = SafetensorsHeader {
421 header_len: n,
422 ..Default::default()
423 };
424 for (name, t) in obj {
425 if name == "__metadata__" {
426 if let Some(m) = t.as_object() {
427 for (k, val) in m {
428 if let Some(s) = val.as_str() {
429 h.metadata.insert(k.clone(), s.to_string());
430 }
431 }
432 }
433 continue;
434 }
435 let dtype = t.get("dtype").and_then(|d| d.as_str()).unwrap_or("?");
436 let bytes = match t.get("data_offsets").and_then(|o| o.as_array()).map(|o| {
437 (
438 o.first().and_then(|x| x.as_u64()),
439 o.get(1).and_then(|x| x.as_u64()),
440 )
441 }) {
442 Some((Some(a), Some(b))) if b >= a => b - a,
443 _ => {
444 let elems: Option<u64> = t.get("shape").and_then(|s| s.as_array()).and_then(|s| {
447 s.iter()
448 .try_fold(1u64, |acc, x| acc.checked_mul(x.as_u64().unwrap_or(0)))
449 });
450 match (elems, safetensors_dtype_bytes(dtype)) {
451 (Some(e), Some(b)) => (e as f64 * b).ceil() as u64,
452 _ => 0,
453 }
454 }
455 };
456 h.n_tensors += 1;
457 h.tensor_bytes = h.tensor_bytes.saturating_add(bytes);
458 *h.dtypes.entry(dtype.to_string()).or_insert(0) += 1;
459 }
460 Ok(h)
461}
462
463#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
465#[serde(default)]
466pub struct SafetensorsIndex {
467 pub total_size: Option<u64>,
469 pub shards: Vec<String>,
471 pub n_tensors: u64,
472}
473
474impl SafetensorsIndex {
475 pub fn weights(&self, shard_size: impl Fn(&str) -> Option<u64>) -> Option<u64> {
477 if let Some(t) = self.total_size.filter(|t| *t > 0) {
478 return Some(t);
479 }
480 if self.shards.is_empty() {
481 return None;
482 }
483 self.shards
484 .iter()
485 .try_fold(0u64, |acc, s| Some(acc.saturating_add(shard_size(s)?)))
486 }
487}
488
489pub fn parse_safetensors_index(json: &str) -> Result<SafetensorsIndex, SafetensorsError> {
491 let v: serde_json::Value =
492 serde_json::from_str(json).map_err(|e| SafetensorsError::Json(e.to_string()))?;
493 let total_size = v.get("metadata").and_then(|m| m.get("total_size")).and_then(|t| {
494 t.as_u64()
495 .or_else(|| t.as_f64().map(|f| f as u64))
496 .or_else(|| t.as_str()?.parse().ok())
497 });
498 let map = v
499 .get("weight_map")
500 .and_then(|m| m.as_object())
501 .ok_or_else(|| SafetensorsError::Json("weight_map missing".into()))?;
502 let mut shards: Vec<String> = map
503 .values()
504 .filter_map(|s| s.as_str().map(str::to_string))
505 .collect();
506 shards.sort();
507 shards.dedup();
508 Ok(SafetensorsIndex {
509 total_size,
510 shards,
511 n_tensors: map.len() as u64,
512 })
513}
514
515#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
521#[serde(default)]
522pub struct LlmDims {
523 pub n_layers: u64,
524 pub kv_heads_sum: u64,
526 pub n_kv_heads: u64,
528 pub key_length: u64,
529 pub value_length: u64,
530 pub context_length: Option<u64>,
531}
532
533impl LlmDims {
534 pub fn from_gguf(m: &GgufMeta) -> Option<LlmDims> {
537 let n_layers = m.n_layers().filter(|l| *l > 0)?;
538 let kv_heads_sum = m.kv_heads_sum()?;
539 let key_length = m.head_dim().filter(|d| *d > 0)?;
540 let value_length = m.value_dim().filter(|d| *d > 0).unwrap_or(key_length);
541 if kv_heads_sum == 0 {
542 return None;
543 }
544 Some(LlmDims {
545 n_layers,
546 kv_heads_sum,
547 n_kv_heads: m.kv_heads_list()?.into_iter().max().unwrap_or(0),
548 key_length,
549 value_length,
550 context_length: m.context_length(),
551 })
552 }
553
554 pub fn from_hf_config(json: &str) -> Option<LlmDims> {
556 let root: serde_json::Value = serde_json::from_str(json).ok()?;
557 let cfg = root
558 .get("text_config")
559 .filter(|t| t.get("num_hidden_layers").is_some())
560 .unwrap_or(&root);
561 let get = |k: &str| cfg.get(k).and_then(|v| v.as_u64());
562 let n_layers = get("num_hidden_layers")
563 .or_else(|| get("n_layer"))
564 .filter(|l| *l > 0 && *l <= MAX_LAYERS)?;
565 let heads = get("num_attention_heads")
566 .or_else(|| get("n_head"))
567 .filter(|h| *h > 0)?;
568 let kv = get("num_key_value_heads").unwrap_or(heads);
569 let hidden = get("hidden_size").or_else(|| get("n_embd"));
570 let head_dim = get("head_dim")
571 .or_else(|| hidden.map(|h| h / heads))
572 .filter(|d| *d > 0)?;
573 Some(LlmDims {
574 n_layers,
575 kv_heads_sum: n_layers.saturating_mul(kv),
576 n_kv_heads: kv,
577 key_length: head_dim,
578 value_length: head_dim,
579 context_length: get("max_position_embeddings").or_else(|| get("n_positions")),
580 })
581 }
582
583 pub fn kv_bytes(&self, ctx: u64, kv_type_bytes: f64, n_parallel: u64) -> u64 {
585 let v = self.kv_heads_sum as f64
586 * (self.key_length as f64 + self.value_length as f64)
587 * ctx as f64
588 * kv_type_bytes.max(0.0)
589 * n_parallel.max(1) as f64;
590 if v.is_finite() && v < u64::MAX as f64 {
591 v as u64
592 } else {
593 u64::MAX
594 }
595 }
596}
597
598#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
600#[serde(default)]
601pub struct ModelEstimate {
602 pub weights: u64,
603 pub kv: u64,
604 pub overhead: u64,
605 pub need: u64,
606 pub fallback: bool,
608 pub ctx: Option<u64>,
609 pub note: String,
610}
611
612#[derive(Debug, Clone, PartialEq)]
614pub struct KvParams {
615 pub ctx: Option<u64>,
617 pub kv_type_bytes: f64,
619 pub n_parallel: u64,
620}
621
622impl Default for KvParams {
623 fn default() -> Self {
624 KvParams {
625 ctx: None,
626 kv_type_bytes: 2.0,
627 n_parallel: 1,
628 }
629 }
630}
631
632pub fn kv_type_bytes(name: &str) -> Option<f64> {
634 Some(match name.trim().to_ascii_lowercase().as_str() {
635 "f32" => 4.0,
636 "f16" | "bf16" => 2.0,
637 "q8_0" => 34.0 / 32.0,
638 "q5_1" => 24.0 / 32.0,
639 "q5_0" => 22.0 / 32.0,
640 "q4_1" => 20.0 / 32.0,
641 "q4_0" | "iq4_nl" => 18.0 / 32.0,
642 _ => return None,
643 })
644}
645
646pub fn overhead_for(weights: u64) -> u64 {
647 (512 * MIB).max(weights / 20)
648}
649
650fn resolve_ctx(kv: &KvParams, model_ctx: Option<u64>) -> u64 {
651 kv.ctx.filter(|c| *c > 0).unwrap_or_else(|| {
652 model_ctx
653 .filter(|c| *c > 0)
654 .unwrap_or(DEFAULT_CTX)
655 .min(DEFAULT_CTX_CAP)
656 })
657}
658
659pub fn estimate_llm_dims(weights: u64, dims: Option<&LlmDims>, kv: &KvParams) -> ModelEstimate {
661 let Some(d) = dims else {
662 return estimate_unknown(weights);
663 };
664 let ctx = resolve_ctx(kv, d.context_length);
665 let kv_bytes = d.kv_bytes(ctx, kv.kv_type_bytes, kv.n_parallel);
666 let overhead = overhead_for(weights);
667 let head = if d.key_length == d.value_length {
668 format!("{} dim", d.key_length)
669 } else {
670 format!("{}+{} dim", d.key_length, d.value_length)
671 };
672 ModelEstimate {
673 weights,
674 kv: kv_bytes,
675 overhead,
676 need: weights.saturating_add(kv_bytes).saturating_add(overhead),
677 fallback: false,
678 ctx: Some(ctx),
679 note: format!(
680 "{} layers × {} kv heads × {head} × ctx {ctx}{}",
681 d.n_layers,
682 d.n_kv_heads,
683 if kv.n_parallel > 1 {
684 format!(" × {} parallel", kv.n_parallel)
685 } else {
686 String::new()
687 }
688 ),
689 }
690}
691
692pub fn estimate_llm(file_size: u64, meta: Option<&GgufMeta>, kv: &KvParams) -> ModelEstimate {
694 let dims = meta.and_then(LlmDims::from_gguf);
695 estimate_llm_dims(file_size, dims.as_ref(), kv)
696}
697
698pub fn estimate_safetensors_llm(weights: u64, hf_config: Option<&str>, kv: &KvParams) -> ModelEstimate {
700 let dims = hf_config.and_then(LlmDims::from_hf_config);
701 estimate_llm_dims(weights, dims.as_ref(), kv)
702}
703
704pub fn estimate_unknown(file_size: u64) -> ModelEstimate {
706 let need = (file_size as f64 * FALLBACK_FACTOR) as u64;
707 ModelEstimate {
708 weights: file_size,
709 kv: 0,
710 overhead: need.saturating_sub(file_size),
711 need,
712 fallback: true,
713 ctx: None,
714 note: "no metadata: 1.2 × file size".into(),
715 }
716}
717
718#[derive(Debug, Clone, Copy, PartialEq)]
720pub struct DiffusionCalibration {
721 pub model: &'static str,
722 pub width: u32,
723 pub height: u32,
724 pub compute_bytes: u64,
726}
727
728pub const DIFFUSION_CALIBRATION: &[DiffusionCalibration] = &[DiffusionCalibration {
733 model: "qwen-image-2.1 (sd.cpp, Metal)",
734 width: 256,
735 height: 256,
736 compute_bytes: 650_756_751, }];
738
739pub fn diffusion_activations(width: u32, height: u32) -> u64 {
741 let pixels = width as u128 * height as u128;
742 let act = DIFFUSION_CALIBRATION
743 .iter()
744 .filter(|c| c.width > 0 && c.height > 0)
745 .map(|c| c.compute_bytes as u128 * pixels / (c.width as u128 * c.height as u128))
746 .max()
747 .unwrap_or(0);
748 u64::try_from(act).unwrap_or(u64::MAX).max(512 * MIB)
749}
750
751pub fn estimate_diffusion(component_sizes: &[u64], width: u32, height: u32) -> ModelEstimate {
754 let weights: u64 = component_sizes.iter().fold(0u64, |a, b| a.saturating_add(*b));
755 let act = diffusion_activations(width, height);
756 ModelEstimate {
757 weights,
758 kv: 0,
759 overhead: act,
760 need: weights.saturating_add(act),
761 fallback: false,
762 ctx: None,
763 note: format!(
764 "{} components + activations for {width}×{height} (calibrated: {})",
765 component_sizes.len(),
766 DIFFUSION_CALIBRATION
767 .iter()
768 .map(|c| c.model)
769 .collect::<Vec<_>>()
770 .join(", ")
771 ),
772 }
773}
774
775#[cfg(test)]
776pub(crate) mod tests {
777 use super::*;
778 use crate::units::GIB;
779
780 fn push_str(b: &mut Vec<u8>, s: &str) {
781 b.extend_from_slice(&(s.len() as u64).to_le_bytes());
782 b.extend_from_slice(s.as_bytes());
783 }
784 fn push_kv_u32(b: &mut Vec<u8>, k: &str, v: u32) {
785 push_str(b, k);
786 b.extend_from_slice(&4u32.to_le_bytes());
787 b.extend_from_slice(&v.to_le_bytes());
788 }
789
790 pub(crate) fn synthetic_gguf() -> Vec<u8> {
792 let mut b = Vec::new();
793 b.extend_from_slice(b"GGUF");
794 b.extend_from_slice(&3u32.to_le_bytes());
795 b.extend_from_slice(&291u64.to_le_bytes()); b.extend_from_slice(&7u64.to_le_bytes()); push_str(&mut b, "general.architecture");
798 b.extend_from_slice(&8u32.to_le_bytes());
799 push_str(&mut b, "llama");
800 push_kv_u32(&mut b, "llama.block_count", 32);
801 push_kv_u32(&mut b, "llama.attention.head_count", 32);
802 push_kv_u32(&mut b, "llama.attention.head_count_kv", 8);
803 push_kv_u32(&mut b, "llama.embedding_length", 4096);
804 push_kv_u32(&mut b, "llama.context_length", 131072);
805 push_str(&mut b, "tokenizer.ggml.tokens");
807 b.extend_from_slice(&9u32.to_le_bytes());
808 b.extend_from_slice(&8u32.to_le_bytes());
809 b.extend_from_slice(&3u64.to_le_bytes());
810 for t in ["<s>", "</s>", "hi"] {
811 push_str(&mut b, t);
812 }
813 b
814 }
815
816 #[test]
817 fn parses_header() {
818 let buf = synthetic_gguf();
819 let m = parse_gguf_header(&buf).unwrap();
820 assert_eq!(m.version, 3);
821 assert_eq!(m.tensor_count, 291);
822 assert_eq!(m.architecture(), Some("llama"));
823 assert_eq!(m.n_layers(), Some(32));
824 assert_eq!(m.n_kv_heads(), Some(8));
825 assert_eq!(m.head_dim(), Some(128));
826 assert_eq!(m.context_length(), Some(131072));
827 assert_eq!(
828 m.kv.get("tokenizer.ggml.tokens"),
829 Some(&GgufValue::Array { len: 3 })
830 );
831 assert!(!m.truncated);
832 }
833
834 #[test]
835 fn gguf_v2_parses_like_v3() {
836 let mut buf = synthetic_gguf();
837 buf[4..8].copy_from_slice(&2u32.to_le_bytes());
838 let m = parse_gguf_header(&buf).unwrap();
839 assert_eq!(m.version, 2);
840 assert_eq!(m.n_layers(), Some(32));
841 buf[4..8].copy_from_slice(&3u32.to_be_bytes());
843 assert_eq!(
844 parse_gguf_header(&buf),
845 Err(GgufError::Version(3u32.swap_bytes()))
846 );
847 }
848
849 #[test]
850 fn truncated_and_bad_magic() {
851 let buf = synthetic_gguf();
852 let m = parse_gguf_header(&buf[..60]).unwrap();
853 assert!(m.truncated);
854 for n in 0..buf.len() {
855 let _ = parse_gguf_header(&buf[..n]);
857 }
858 assert_eq!(parse_gguf_header(b"GGML...."), Err(GgufError::BadMagic));
859 assert_eq!(parse_gguf_header(b""), Err(GgufError::BadMagic));
860 let mut v1 = b"GGUF".to_vec();
861 v1.extend_from_slice(&1u32.to_le_bytes());
862 assert_eq!(parse_gguf_header(&v1), Err(GgufError::Version(1)));
863 }
864
865 #[test]
866 fn llm_estimate() {
867 let m = parse_gguf_header(&synthetic_gguf()).unwrap();
868 let e = estimate_llm(8 * GIB, Some(&m), &KvParams::default());
869 assert_eq!(e.kv, GIB);
871 assert_eq!(e.overhead, 512 * MIB);
873 assert_eq!(overhead_for(20 * GIB), GIB);
874 assert_eq!(e.need, e.weights + e.kv + e.overhead);
875 let f = estimate_llm(1000, None, &KvParams::default());
876 assert!(f.fallback);
877 assert_eq!(f.need, 1200);
878 let q8 = estimate_llm(
879 8 * GIB,
880 Some(&m),
881 &KvParams {
882 ctx: Some(4096),
883 kv_type_bytes: kv_type_bytes("q8_0").unwrap(),
884 n_parallel: 2,
885 },
886 );
887 assert_eq!(q8.kv, (GIB as f64 / 2.0 * 1.0625 / 2.0 * 2.0) as u64);
888 }
889
890 #[test]
891 fn per_layer_kv_heads() {
892 let mut b = Vec::new();
893 b.extend_from_slice(b"GGUF");
894 b.extend_from_slice(&3u32.to_le_bytes());
895 b.extend_from_slice(&0u64.to_le_bytes());
896 b.extend_from_slice(&5u64.to_le_bytes());
897 push_str(&mut b, "general.architecture");
898 b.extend_from_slice(&8u32.to_le_bytes());
899 push_str(&mut b, "hybrid");
900 push_kv_u32(&mut b, "hybrid.block_count", 4);
901 push_kv_u32(&mut b, "hybrid.attention.head_count", 16);
902 push_kv_u32(&mut b, "hybrid.embedding_length", 2048);
903 push_str(&mut b, "hybrid.attention.head_count_kv");
905 b.extend_from_slice(&9u32.to_le_bytes());
906 b.extend_from_slice(&5u32.to_le_bytes());
907 b.extend_from_slice(&4u64.to_le_bytes());
908 for v in [4i32, 0, 4, 0] {
909 b.extend_from_slice(&v.to_le_bytes());
910 }
911 let m = parse_gguf_header(&b).unwrap();
912 assert_eq!(m.kv_heads_per_layer(), Some(vec![4, 0, 4, 0]));
913 let d = LlmDims::from_gguf(&m).unwrap();
914 assert_eq!(d.kv_heads_sum, 8);
915 assert_eq!(d.key_length, 128);
916 assert_eq!(d.kv_bytes(1000, 2.0, 1), 8 * 256 * 1000 * 2);
917 }
918
919 #[test]
920 fn safetensors_header_and_index() {
921 let json = br#"{"__metadata__":{"format":"pt"},"a":{"dtype":"BF16","shape":[4,8],"data_offsets":[0,64]},"b":{"dtype":"F32","shape":[10],"data_offsets":[64,104]}}"#;
922 let mut buf = (json.len() as u64).to_le_bytes().to_vec();
923 buf.extend_from_slice(json);
924 let h = parse_safetensors_header(&buf).unwrap();
925 assert_eq!(h.n_tensors, 2);
926 assert_eq!(h.tensor_bytes, 104);
927 assert_eq!(h.dtypes.get("BF16"), Some(&1));
928 assert_eq!(h.metadata.get("format").map(String::as_str), Some("pt"));
929 assert_eq!(
930 parse_safetensors_header(&buf[..20]),
931 Err(SafetensorsError::Truncated {
932 needed: buf.len() as u64
933 })
934 );
935 assert!(parse_safetensors_header(&[1, 2]).is_err());
936 let mut huge = u64::MAX.to_le_bytes().to_vec();
937 huge.push(b'{');
938 assert!(matches!(
939 parse_safetensors_header(&huge),
940 Err(SafetensorsError::TooLarge(_))
941 ));
942
943 let idx = r#"{"metadata":{"total_size":16060522496},"weight_map":{"a":"model-00001-of-00002.safetensors","b":"model-00002-of-00002.safetensors","c":"model-00001-of-00002.safetensors"}}"#;
944 let i = parse_safetensors_index(idx).unwrap();
945 assert_eq!(i.total_size, Some(16_060_522_496));
946 assert_eq!(i.shards.len(), 2);
947 assert_eq!(i.n_tensors, 3);
948 assert_eq!(i.weights(|_| None), Some(16_060_522_496));
949 let no_total = r#"{"weight_map":{"a":"s1","b":"s2"}}"#;
950 let i = parse_safetensors_index(no_total).unwrap();
951 assert_eq!(i.weights(|s| Some(if s == "s1" { 10 } else { 20 })), Some(30));
952 assert_eq!(i.weights(|s| (s == "s1").then_some(10)), None);
953 assert!(parse_safetensors_index("{}").is_err());
954 }
955
956 #[test]
957 fn hf_config_dims() {
958 let cfg = r#"{"num_hidden_layers":32,"num_attention_heads":32,"num_key_value_heads":8,"hidden_size":4096,"max_position_embeddings":131072}"#;
959 let d = LlmDims::from_hf_config(cfg).unwrap();
960 assert_eq!(d.kv_heads_sum, 256);
961 assert_eq!(d.key_length, 128);
962 let e = estimate_safetensors_llm(16 * GIB, Some(cfg), &KvParams::default());
963 assert_eq!(e.kv, GIB);
964 assert!(!e.fallback);
965 let mm = r#"{"text_config":{"num_hidden_layers":36,"num_attention_heads":32,"num_key_value_heads":8,"head_dim":128}}"#;
966 assert_eq!(LlmDims::from_hf_config(mm).unwrap().n_layers, 36);
967 assert!(estimate_safetensors_llm(100, Some("not json"), &KvParams::default()).fallback);
968 }
969
970 fn header(arch: &str, kvs: &[(&str, u32)], extra: impl FnOnce(&mut Vec<u8>) -> u64) -> Vec<u8> {
971 let mut body = Vec::new();
972 push_str(&mut body, "general.architecture");
973 body.extend_from_slice(&8u32.to_le_bytes());
974 push_str(&mut body, arch);
975 for (k, v) in kvs {
976 push_kv_u32(&mut body, k, *v);
977 }
978 let n_extra = extra(&mut body);
979 let mut b = Vec::new();
980 b.extend_from_slice(b"GGUF");
981 b.extend_from_slice(&3u32.to_le_bytes());
982 b.extend_from_slice(&0u64.to_le_bytes());
983 b.extend_from_slice(&(1 + kvs.len() as u64 + n_extra).to_le_bytes());
984 b.extend_from_slice(&body);
985 b
986 }
987
988 #[test]
989 fn corrupt_block_count_does_not_allocate_or_overflow() {
990 let b = header(
992 "x",
993 &[
994 ("x.block_count", u32::MAX),
995 ("x.attention.head_count", u32::MAX),
996 ("x.attention.head_count_kv", u32::MAX),
997 ("x.embedding_length", u32::MAX),
998 ],
999 |_| 0,
1000 );
1001 let m = parse_gguf_header(&b).unwrap();
1002 assert_eq!(m.n_layers(), None);
1003 assert_eq!(m.kv_heads_per_layer(), None);
1004 let e = estimate_llm(GIB, Some(&m), &KvParams::default());
1005 assert!(e.fallback);
1006 let b = header(
1008 "y",
1009 &[
1010 ("y.block_count", 60_000),
1011 ("y.attention.head_count", 1),
1012 ("y.attention.head_count_kv", u32::MAX),
1013 ("y.attention.key_length", u32::MAX),
1014 ],
1015 |_| 0,
1016 );
1017 let m = parse_gguf_header(&b).unwrap();
1018 let d = LlmDims::from_gguf(&m).unwrap();
1019 assert_eq!(d.kv_heads_sum, 60_000 * u32::MAX as u64);
1020 assert_eq!(d.kv_bytes(u64::MAX, 4.0, u64::MAX), u64::MAX);
1021 let dims = LlmDims {
1022 n_layers: 1,
1023 kv_heads_sum: 1,
1024 n_kv_heads: 1,
1025 key_length: u64::MAX,
1026 value_length: u64::MAX,
1027 context_length: None,
1028 };
1029 assert_eq!(dims.kv_bytes(1, 1.0, 1), u64::MAX);
1030 let hf = r#"{"num_hidden_layers":4000,"num_attention_heads":1,"num_key_value_heads":18446744073709551615,"head_dim":1}"#;
1031 assert_eq!(LlmDims::from_hf_config(hf).unwrap().kv_heads_sum, u64::MAX);
1032 }
1033
1034 #[test]
1035 fn invalid_utf8_value_keeps_the_header() {
1036 let b = header("llama", &[("llama.block_count", 2)], |b| {
1037 push_str(b, "general.name");
1038 b.extend_from_slice(&8u32.to_le_bytes());
1039 b.extend_from_slice(&3u64.to_le_bytes());
1040 b.extend_from_slice(&[b'a', 0xff, b'b']);
1041 1
1042 });
1043 let m = parse_gguf_header(&b).unwrap();
1044 assert_eq!(m.n_layers(), Some(2));
1045 assert_eq!(m.name(), Some("a\u{fffd}b"));
1046 }
1047
1048 #[test]
1049 fn malformed_safetensors_never_panics() {
1050 let json = br#"{"a":{"dtype":"F32","shape":[4294967296,4294967296,4294967296]},"b":{"dtype":"F16","shape":[3,5]},"c":{"dtype":"F32","data_offsets":[10,2]}}"#;
1051 let mut buf = (json.len() as u64).to_le_bytes().to_vec();
1052 buf.extend_from_slice(json);
1053 let h = parse_safetensors_header(&buf).unwrap();
1054 assert_eq!(h.n_tensors, 3);
1055 assert_eq!(h.tensor_bytes, 30);
1056 let idx = SafetensorsIndex {
1057 total_size: None,
1058 shards: vec!["a".into(), "b".into()],
1059 n_tensors: 2,
1060 };
1061 assert_eq!(idx.weights(|_| Some(u64::MAX)), Some(u64::MAX));
1062 }
1063
1064 #[test]
1065 fn kv_types() {
1066 assert_eq!(kv_type_bytes("F16"), Some(2.0));
1067 assert_eq!(kv_type_bytes("q4_0"), Some(0.5625));
1068 assert_eq!(kv_type_bytes("q2_k"), None);
1069 }
1070
1071 #[test]
1072 fn diffusion_calibration_point() {
1073 assert_eq!(diffusion_activations(256, 256), 650_756_751);
1075 assert_eq!(diffusion_activations(64, 64), 512 * MIB);
1077 assert!(diffusion_activations(1024, 1024) > diffusion_activations(512, 512));
1078 let e = estimate_diffusion(&[GIB, 2 * GIB], 256, 256);
1079 assert_eq!(e.need, 3 * GIB + 650_756_751);
1080 }
1081}