1use std::path::Path;
23
24use serde::{Deserialize, Serialize};
25
26use crate::gguf::{GgufKind, ProjectorInfo};
27use crate::speech::SpeechProfile;
28use crate::{Error, Result};
29
30pub const LIMITS_FORMAT: &str = "weirdnet-limits/1";
32pub const LIMITS_SUFFIX: &str = ".limits.json";
34pub const LIMITS_FILE: &str = ".limits.json";
36
37pub const WHISPER_CHUNK_SECONDS: u32 = 30;
41const WHISPER_CHUNK_FRAMES: u32 = 3000;
42const QWEN_VL_MAX_IMAGE_TOKENS: u32 = 4096;
45
46#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
48#[non_exhaustive]
49pub struct ModelLimits {
50 #[serde(default, skip_serializing_if = "Option::is_none")]
53 pub context_tokens: Option<u32>,
54 #[serde(default, skip_serializing_if = "Option::is_none")]
56 pub max_images: Option<u32>,
57 #[serde(default, skip_serializing_if = "Option::is_none")]
60 pub image_tokens: Option<u32>,
61 #[serde(default, skip_serializing_if = "Option::is_none")]
64 pub image_patch: Option<u32>,
65 #[serde(default, skip_serializing_if = "Option::is_none")]
67 pub image_edge: Option<u32>,
68 #[serde(default, skip_serializing_if = "Option::is_none")]
70 pub audio_max_seconds: Option<u32>,
71 #[serde(default, skip_serializing_if = "Option::is_none")]
73 pub audio_tokens_per_minute: Option<u32>,
74 #[serde(default, skip_serializing_if = "Option::is_none")]
77 pub audio_chunk_seconds: Option<u32>,
78 #[serde(default, skip_serializing_if = "Option::is_none")]
80 pub audio_chunk_tokens: Option<u32>,
81 #[serde(default, skip_serializing_if = "Option::is_none")]
83 pub video_max_seconds: Option<u32>,
84 #[serde(default, skip_serializing_if = "Option::is_none")]
86 pub video_max_bytes: Option<u64>,
87 #[serde(default, skip_serializing_if = "Option::is_none")]
90 pub video_frames_per_minute: Option<u32>,
91 #[serde(default, skip_serializing_if = "Option::is_none")]
93 pub max_request_bytes: Option<u64>,
94}
95
96impl ModelLimits {
97 pub const UNKNOWN: Self = Self {
99 context_tokens: None,
100 max_images: None,
101 image_tokens: None,
102 image_patch: None,
103 image_edge: None,
104 audio_max_seconds: None,
105 audio_tokens_per_minute: None,
106 audio_chunk_seconds: None,
107 audio_chunk_tokens: None,
108 video_max_seconds: None,
109 video_max_bytes: None,
110 video_frames_per_minute: None,
111 max_request_bytes: None,
112 };
113
114 pub fn new() -> Self {
115 Self::UNKNOWN
116 }
117
118 pub fn is_unknown(&self) -> bool {
120 *self == Self::UNKNOWN
121 }
122
123 pub fn with_context_tokens(mut self, tokens: u32) -> Self {
124 self.context_tokens = Some(tokens);
125 self
126 }
127
128 pub fn with_max_images(mut self, n: u32) -> Self {
129 self.max_images = Some(n);
130 self
131 }
132
133 pub fn with_image_tokens(mut self, tokens: u32) -> Self {
135 self.image_tokens = Some(tokens);
136 self
137 }
138
139 pub fn with_image_patch(mut self, patch: u32) -> Self {
141 self.image_patch = Some(patch);
142 self
143 }
144
145 pub fn with_image_edge(mut self, pixels: u32) -> Self {
146 self.image_edge = Some(pixels);
147 self
148 }
149
150 pub fn with_audio_max_seconds(mut self, seconds: u32) -> Self {
151 self.audio_max_seconds = Some(seconds);
152 self
153 }
154
155 pub fn with_audio_tokens_per_minute(mut self, tokens: u32) -> Self {
156 self.audio_tokens_per_minute = Some(tokens);
157 self
158 }
159
160 pub fn with_audio_chunks(mut self, seconds: u32, tokens: u32) -> Self {
163 self.audio_chunk_seconds = Some(seconds);
164 self.audio_chunk_tokens = Some(tokens);
165 if seconds > 0 {
166 self.audio_tokens_per_minute = u32::try_from(u64::from(tokens) * 60 / u64::from(seconds)).ok();
167 }
168 self
169 }
170
171 pub fn with_video_max_seconds(mut self, seconds: u32) -> Self {
172 self.video_max_seconds = Some(seconds);
173 self
174 }
175
176 pub fn with_video_max_bytes(mut self, bytes: u64) -> Self {
177 self.video_max_bytes = Some(bytes);
178 self
179 }
180
181 pub fn with_video_frames_per_minute(mut self, frames: u32) -> Self {
183 self.video_frames_per_minute = Some(frames);
184 self
185 }
186
187 pub fn video_frame_rate(&self) -> Option<f64> {
189 self.video_frames_per_minute.map(|f| f64::from(f) / 60.0)
190 }
191
192 pub fn with_max_request_bytes(mut self, bytes: u64) -> Self {
193 self.max_request_bytes = Some(bytes);
194 self
195 }
196
197 pub fn audio_tokens_per_second(&self) -> Option<f64> {
199 self.audio_tokens_per_minute.map(|t| f64::from(t) / 60.0)
200 }
201
202 pub fn image_cost(&self, width: u32, height: u32) -> Option<u32> {
206 let Some(patch) = self.image_patch.filter(|p| *p > 0) else {
207 return self.image_tokens;
208 };
209 let (w, h) = self.scaled(width, height);
210 let tokens = u64::from(w.div_ceil(patch)) * u64::from(h.div_ceil(patch));
211 let tokens = u32::try_from(tokens).unwrap_or(u32::MAX);
212 Some(self.image_tokens.map_or(tokens, |cap| tokens.min(cap)))
213 }
214
215 pub fn scaled(&self, width: u32, height: u32) -> (u32, u32) {
218 let long = width.max(height);
219 match self.image_edge {
220 Some(edge) if edge > 0 && long > edge => {
221 let s = |v: u32| ((u64::from(v) * u64::from(edge)).div_ceil(u64::from(long)) as u32).max(1);
222 (s(width), s(height))
223 }
224 _ => (width, height),
225 }
226 }
227
228 pub fn audio_cost(&self, millis: u64) -> Option<u64> {
232 if let (Some(secs), Some(tokens)) = (self.audio_chunk_seconds.filter(|s| *s > 0), self.audio_chunk_tokens) {
233 return Some(millis.div_ceil(u64::from(secs) * 1000).max(1) * u64::from(tokens));
234 }
235 self.audio_tokens_per_minute.map(|t| (u64::from(t) * millis).div_ceil(60_000))
236 }
237
238 pub fn or(self, fallback: Self) -> Self {
241 Self {
242 context_tokens: self.context_tokens.or(fallback.context_tokens),
243 max_images: self.max_images.or(fallback.max_images),
244 image_tokens: self.image_tokens.or(fallback.image_tokens),
245 image_patch: self.image_patch.or(fallback.image_patch),
246 image_edge: self.image_edge.or(fallback.image_edge),
247 audio_max_seconds: self.audio_max_seconds.or(fallback.audio_max_seconds),
248 audio_tokens_per_minute: self.audio_tokens_per_minute.or(fallback.audio_tokens_per_minute),
249 audio_chunk_seconds: self.audio_chunk_seconds.or(fallback.audio_chunk_seconds),
250 audio_chunk_tokens: self.audio_chunk_tokens.or(fallback.audio_chunk_tokens),
251 video_max_seconds: self.video_max_seconds.or(fallback.video_max_seconds),
252 video_max_bytes: self.video_max_bytes.or(fallback.video_max_bytes),
253 video_frames_per_minute: self.video_frames_per_minute.or(fallback.video_frames_per_minute),
254 max_request_bytes: self.max_request_bytes.or(fallback.max_request_bytes),
255 }
256 }
257
258 pub fn tightest(self, other: Self) -> Self {
263 fn pick<T: Ord>(a: Option<T>, b: Option<T>, f: fn(T, T) -> T) -> Option<T> {
264 match (a, b) {
265 (Some(a), Some(b)) => Some(f(a, b)),
266 (a, b) => a.or(b),
267 }
268 }
269 Self {
270 context_tokens: pick(self.context_tokens, other.context_tokens, Ord::min),
271 max_images: pick(self.max_images, other.max_images, Ord::min),
272 image_tokens: pick(self.image_tokens, other.image_tokens, Ord::max),
273 image_patch: pick(self.image_patch, other.image_patch, Ord::min),
274 image_edge: pick(self.image_edge, other.image_edge, Ord::min),
275 audio_max_seconds: pick(self.audio_max_seconds, other.audio_max_seconds, Ord::min),
276 audio_tokens_per_minute: pick(self.audio_tokens_per_minute, other.audio_tokens_per_minute, Ord::max),
277 audio_chunk_seconds: pick(self.audio_chunk_seconds, other.audio_chunk_seconds, Ord::max),
278 audio_chunk_tokens: pick(self.audio_chunk_tokens, other.audio_chunk_tokens, Ord::max),
279 video_max_seconds: pick(self.video_max_seconds, other.video_max_seconds, Ord::min),
280 video_max_bytes: pick(self.video_max_bytes, other.video_max_bytes, Ord::min),
281 video_frames_per_minute: pick(self.video_frames_per_minute, other.video_frames_per_minute, Ord::min),
282 max_request_bytes: pick(self.max_request_bytes, other.max_request_bytes, Ord::min),
283 }
284 }
285}
286
287#[cfg(feature = "agent")]
288impl ModelLimits {
289 pub fn to_media(&self) -> weirdnet_agent::MediaLimits {
294 let mut m = weirdnet_agent::MediaLimits::new();
295 m.max_images = self.max_images;
296 m.image_tokens = self.image_tokens;
297 m.image_patch = self.image_patch;
298 m.image_edge = self.image_edge;
299 m.audio_max_seconds = self.audio_max_seconds;
300 m.audio_tokens_per_minute = self.audio_tokens_per_minute;
301 m.video_max_seconds = self.video_max_seconds;
302 m.video_max_bytes = self.video_max_bytes;
303 m.video_frames_per_minute = self.video_frames_per_minute;
304 m.max_request_bytes = self.max_request_bytes;
305 m
306 }
307
308 pub fn from_media(m: &weirdnet_agent::MediaLimits) -> Self {
310 Self {
311 max_images: m.max_images,
312 image_tokens: m.image_tokens,
313 image_patch: m.image_patch,
314 image_edge: m.image_edge,
315 audio_max_seconds: m.audio_max_seconds,
316 audio_tokens_per_minute: m.audio_tokens_per_minute,
317 video_max_seconds: m.video_max_seconds,
318 video_max_bytes: m.video_max_bytes,
319 video_frames_per_minute: m.video_frames_per_minute,
320 max_request_bytes: m.max_request_bytes,
321 ..Self::UNKNOWN
322 }
323 }
324}
325
326#[cfg(feature = "agent")]
327impl From<ModelLimits> for weirdnet_agent::MediaLimits {
328 fn from(l: ModelLimits) -> Self {
329 l.to_media()
330 }
331}
332
333#[cfg(feature = "agent")]
334impl From<weirdnet_agent::MediaLimits> for ModelLimits {
335 fn from(m: weirdnet_agent::MediaLimits) -> Self {
336 Self::from_media(&m)
337 }
338}
339
340pub fn from_projector(p: &ProjectorInfo) -> ModelLimits {
357 let mut l = ModelLimits::new();
358 match p.image_type() {
359 Some("gemma3") => {
360 let merge = p.scale_factor.unwrap_or(4);
361 if let (Some(size), Some(patch)) = (p.image_size, p.patch_size)
362 && patch > 0
363 && merge > 0
364 && size % patch == 0
365 && (size / patch) % merge == 0
366 {
367 let side = size / patch / merge;
368 l = l.with_image_tokens(side * side).with_image_edge(size);
369 }
370 }
371 Some("qwen2vl_merger" | "qwen2.5vl_merger" | "qwen3vl_merger" | "qwen2.5o") => {
372 if let Some(patch) = p.patch_size.filter(|p| *p > 0)
373 && p.spatial_merge.unwrap_or(2) == 2
374 {
375 let unit = patch * 2;
376 let cap = match p.image_max_pixels {
377 Some(px) => u32::try_from(px / (u64::from(unit) * u64::from(unit))).unwrap_or(u32::MAX),
378 None => QWEN_VL_MAX_IMAGE_TOKENS,
379 };
380 l = l.with_image_patch(unit).with_image_tokens(cap);
381 }
382 }
383 _ => {}
384 }
385 let audio = match p.audio_type() {
386 Some("voxtral") => p.audio_stack_factor.map(|s| (s, true)),
387 Some("ultravox") => p.audio_stack_factor.map(|s| (s, false)),
388 Some("qwen2a" | "qwen2.5o") => Some((1, true)),
389 _ => None,
390 };
391 if let Some((stack, pool)) = audio.filter(|(s, _)| *s > 0) {
392 let mut n = WHISPER_CHUNK_FRAMES.div_ceil(stack) / 2;
393 if pool {
394 n /= 2;
395 }
396 l = l.with_audio_chunks(WHISPER_CHUNK_SECONDS, n);
397 }
398 l
399}
400
401#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
403#[serde(rename_all = "snake_case")]
404#[non_exhaustive]
405pub enum LimitSource {
406 #[default]
408 Measured,
409 Operator,
411 #[serde(other)]
413 Other,
414}
415
416fn limits_format() -> String {
417 LIMITS_FORMAT.into()
418}
419
420#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
424#[non_exhaustive]
425pub struct LimitsRecord {
426 #[serde(default = "limits_format")]
428 pub format: String,
429 #[serde(default)]
430 pub limits: ModelLimits,
431 #[serde(default)]
432 pub source: LimitSource,
433 #[serde(default, skip_serializing_if = "Option::is_none")]
435 pub engine: Option<String>,
436 #[serde(default, skip_serializing_if = "Option::is_none")]
438 pub projector: Option<String>,
439 #[serde(default, skip_serializing_if = "Option::is_none")]
442 pub trained_context: Option<u64>,
443 #[serde(default, skip_serializing_if = "Option::is_none")]
446 pub model_bytes: Option<u64>,
447 #[serde(default, skip_serializing_if = "Option::is_none")]
449 pub recorded_at: Option<u64>,
450 #[serde(default, skip_serializing_if = "Option::is_none")]
455 pub speech: Option<SpeechProfile>,
456 #[serde(flatten)]
457 pub extra: serde_json::Map<String, serde_json::Value>,
458}
459
460impl Default for LimitsRecord {
461 fn default() -> Self {
462 Self::new(ModelLimits::UNKNOWN, LimitSource::Measured)
463 }
464}
465
466impl LimitsRecord {
467 pub fn new(limits: ModelLimits, source: LimitSource) -> Self {
468 Self {
469 format: LIMITS_FORMAT.into(),
470 limits,
471 source,
472 engine: None,
473 projector: None,
474 trained_context: None,
475 model_bytes: None,
476 recorded_at: None,
477 speech: None,
478 extra: Default::default(),
479 }
480 }
481
482 pub fn with_engine(mut self, engine: impl Into<String>) -> Self {
483 self.engine = Some(engine.into());
484 self
485 }
486
487 pub fn with_speech(mut self, speech: SpeechProfile) -> Self {
490 self.speech = Some(speech);
491 self
492 }
493
494 pub fn stamped(mut self) -> Self {
496 self.recorded_at = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).ok().map(|d| d.as_secs());
497 self
498 }
499}
500
501fn header_of(path: &Path) -> Result<crate::gguf::GgufHeader> {
502 let f = std::fs::File::open(path).map_err(|e| Error::Model(format!("{}: {e}", path.display())))?;
503 crate::gguf::read_header(std::io::BufReader::new(f)).map_err(|e| Error::Model(format!("{}: {e}", path.display())))
504}
505
506pub fn measure(model: &Path, projector: Option<&Path>, context_tokens: Option<u32>) -> Result<LimitsRecord> {
514 let m = header_of(model)?;
515 if m.kind != GgufKind::Model {
516 return Err(Error::Model(format!("{} is not a GGUF model", model.display())));
517 }
518 let mut limits = ModelLimits::new();
519 let mut projector_name = None;
520 let mut speech = None;
521 if let Some(path) = projector {
522 let p = header_of(path)?;
523 let Some(info) = p.projector.as_ref().filter(|_| p.kind.is_projector()) else {
524 return Err(Error::Model(format!("{} is not a projector", path.display())));
525 };
526 limits = from_projector(info);
527 speech = crate::speech::from_gguf(&m, &p);
528 projector_name = path.file_name().map(|n| n.to_string_lossy().into_owned());
529 }
530 limits.context_tokens = context_tokens;
531 let mut record = LimitsRecord::new(limits, LimitSource::Measured).stamped();
532 record.projector = projector_name;
533 record.speech = speech;
534 record.trained_context = m.info.and_then(|i| i.context_length);
535 Ok(record)
536}
537
538#[cfg(test)]
539mod tests {
540 use super::*;
541 use crate::gguf::{header, projector_header, read_header};
542 use serde_json::json;
543
544 fn info(which: &str) -> ProjectorInfo {
545 read_header(&projector_header(which)[..]).unwrap().projector.unwrap()
546 }
547
548 #[test]
549 fn unknown_is_empty_on_the_wire() {
550 assert!(ModelLimits::default().is_unknown());
551 assert_eq!(serde_json::to_string(&ModelLimits::UNKNOWN).unwrap(), "{}");
552 let back: ModelLimits = serde_json::from_str("{}").unwrap();
553 assert!(back.is_unknown());
554 let l = ModelLimits::new().with_context_tokens(8192).with_max_images(4).with_audio_chunks(30, 187).with_video_max_bytes(1 << 20);
555 let j = serde_json::to_value(l).unwrap();
556 assert_eq!(
557 j,
558 json!({"context_tokens": 8192, "max_images": 4, "audio_tokens_per_minute": 374, "audio_chunk_seconds": 30, "audio_chunk_tokens": 187, "video_max_bytes": 1048576})
559 );
560 assert_eq!(serde_json::from_value::<ModelLimits>(j).unwrap(), l);
561 let newer: ModelLimits = serde_json::from_value(json!({"max_images": 2, "video_frame_rate": 2})).unwrap();
563 assert_eq!(newer, ModelLimits::new().with_max_images(2));
564 }
565
566 #[test]
567 fn costs() {
568 let fixed = ModelLimits::new().with_image_tokens(256);
569 assert_eq!(fixed.image_cost(4000, 3000), Some(256));
570 assert_eq!(ModelLimits::UNKNOWN.image_cost(10, 10), None);
571 let patched = ModelLimits::new().with_image_patch(28).with_image_edge(896);
572 assert_eq!(patched.scaled(1792, 896), (896, 448));
573 assert_eq!(patched.image_cost(1792, 896), Some(32 * 16));
574 assert_eq!(patched.with_image_tokens(100).image_cost(1792, 896), Some(100), "capped");
575 let chunks = ModelLimits::new().with_audio_chunks(30, 187);
576 assert_eq!(chunks.audio_tokens_per_minute, Some(374));
577 assert_eq!(chunks.audio_cost(5_000), Some(187), "a short clip costs a whole piece");
578 assert_eq!(chunks.audio_cost(30_000), Some(187));
579 assert_eq!(chunks.audio_cost(30_001), Some(374));
580 assert_eq!(chunks.audio_cost(0), Some(187));
581 let rate = ModelLimits::new().with_audio_tokens_per_minute(375);
582 assert_eq!(rate.audio_tokens_per_second(), Some(6.25));
583 assert_eq!(rate.audio_cost(1_000), Some(7));
584 assert_eq!(ModelLimits::UNKNOWN.audio_cost(1_000), None);
585 assert_eq!(ModelLimits::new().with_audio_chunks(0, 10).audio_tokens_per_minute, None, "no rate from a zero-length piece");
586 }
587
588 #[test]
589 fn operator_over_measured_and_tightest() {
590 let measured = ModelLimits::new().with_context_tokens(8192).with_image_tokens(256).with_image_edge(896);
591 let operator = ModelLimits::new().with_max_images(2).with_image_tokens(300);
592 let both = operator.or(measured);
593 assert_eq!((both.max_images, both.image_tokens, both.image_edge, both.context_tokens), (Some(2), Some(300), Some(896), Some(8192)));
594 let a = ModelLimits::new().with_context_tokens(4096).with_max_images(8).with_audio_chunks(30, 187).with_video_max_seconds(60);
595 let b = ModelLimits::new().with_context_tokens(8192).with_max_images(2).with_audio_chunks(30, 750).with_max_request_bytes(1 << 20);
596 let t = a.tightest(b);
597 assert_eq!((t.context_tokens, t.max_images, t.audio_chunk_tokens, t.audio_tokens_per_minute), (Some(4096), Some(2), Some(750), Some(1500)));
598 assert_eq!((t.video_max_seconds, t.max_request_bytes), (Some(60), Some(1 << 20)), "one side only keeps its value");
599 assert_eq!(a.tightest(ModelLimits::UNKNOWN), a);
600 }
601
602 #[test]
603 fn projector_costs_follow_llama_cpp() {
604 let g = from_projector(&info("gemma3"));
606 assert_eq!(g, ModelLimits::new().with_image_tokens(256).with_image_edge(896));
607 let q = from_projector(&info("qwen2.5vl"));
609 assert_eq!(q, ModelLimits::new().with_image_patch(28).with_image_tokens(4096));
610 assert_eq!(q.image_cost(560, 280), Some(20 * 10));
611 assert_eq!(from_projector(&info("qwen3vl")).image_patch, Some(32));
612 let v = from_projector(&info("voxtral"));
614 assert_eq!(v, ModelLimits::new().with_audio_chunks(30, 187));
615 assert_eq!(v.audio_tokens_per_minute, Some(374));
616 assert_eq!(from_projector(&info("ultravox")).audio_chunk_tokens, Some(187));
618 let o = from_projector(&info("qwen2.5o"));
620 assert_eq!((o.image_patch, o.audio_chunk_tokens, o.audio_tokens_per_minute), (Some(28), Some(750), Some(1500)));
621 for l in [g, q, v, o] {
623 assert_eq!((l.max_images, l.audio_max_seconds, l.context_tokens, l.max_request_bytes), (None, None, None, None));
624 }
625 }
626
627 #[test]
628 fn unknown_projectors_and_missing_figures_stay_absent() {
629 let mut p = ProjectorInfo {
630 vision: true,
631 audio: true,
632 vision_projector: Some("gemma4v".into()),
633 audio_projector: Some("gemma4a".into()),
634 ..Default::default()
635 };
636 p.image_size = Some(224);
637 p.patch_size = Some(16);
638 assert!(from_projector(&p).is_unknown(), "types this version doesn't know are not guessed");
639 let mut g = info("gemma3");
640 g.patch_size = None;
641 assert!(from_projector(&g).is_unknown());
642 let mut g = info("gemma3");
643 g.scale_factor = Some(3);
644 assert!(from_projector(&g).is_unknown(), "64 patches don't pool evenly by 3");
645 let mut v = info("voxtral");
646 v.audio_stack_factor = None;
647 assert!(from_projector(&v).is_unknown(), "Voxtral needs its stack factor");
648 let mut q = info("qwen2.5vl");
649 q.spatial_merge = Some(4);
650 assert!(from_projector(&q).is_unknown(), "llama.cpp refuses a merge other than 2");
651 q.spatial_merge = None;
652 q.image_max_pixels = Some(28 * 28 * 1280);
653 assert_eq!(from_projector(&q).image_tokens, Some(1280), "the header's max pixels set the cap");
654 let mut no_encoder = info("gemma3");
655 no_encoder.vision = false;
656 assert!(from_projector(&no_encoder).is_unknown(), "a type without its encoder flag says nothing");
657 }
658
659 fn write(dir: &Path, name: &str, bytes: &[u8]) -> std::path::PathBuf {
660 let p = dir.join(name);
661 std::fs::write(&p, bytes).unwrap();
662 p
663 }
664
665 fn voxtral_model() -> Vec<u8> {
666 header(&[
667 ("general.architecture", json!("llama")),
668 ("general.type", json!("model")),
669 ("llama.block_count", json!(30)),
670 ("llama.context_length", json!(131072)),
671 ("llama.embedding_length", json!(3072)),
672 ("llama.attention.head_count", json!(32)),
673 ("llama.attention.head_count_kv", json!(8)),
674 ("llama.attention.key_length", json!(128)),
675 ("llama.attention.value_length", json!(128)),
676 ])
677 }
678
679 #[test]
680 fn measures_a_model_and_projector_at_load() {
681 let tmp = tempfile::tempdir().unwrap();
682 let model = write(tmp.path(), "Voxtral-Mini-3B-2507-Q4_K_M.gguf", &voxtral_model());
683 let mmproj = write(tmp.path(), "mmproj-Voxtral-Mini-3B-2507-Q8_0.gguf", &projector_header("voxtral"));
684 let r = measure(&model, Some(&mmproj), Some(16384)).unwrap();
685 assert_eq!(r.format, LIMITS_FORMAT);
686 assert_eq!(r.source, LimitSource::Measured);
687 assert_eq!(r.limits, ModelLimits::new().with_audio_chunks(30, 187).with_context_tokens(16384));
688 assert_eq!((r.projector.as_deref(), r.trained_context), (Some("mmproj-Voxtral-Mini-3B-2507-Q8_0.gguf"), Some(131072)));
689 assert!(r.recorded_at.is_some());
690 let bare = measure(&model, None, None).unwrap();
692 assert!(bare.limits.is_unknown());
693 assert_eq!(bare.trained_context, Some(131072));
694 assert!(measure(&mmproj, None, None).is_err(), "a projector is not a model");
696 assert!(measure(&model, Some(&model), None).is_err(), "a model is not a projector");
697 let lora = write(tmp.path(), "lora.gguf", &crate::gguf::lora_header("llama"));
698 assert!(measure(&lora, None, None).is_err());
699 assert!(measure(&tmp.path().join("gone.gguf"), None, None).is_err());
700 }
701
702 #[test]
703 fn records_round_trip_and_keep_unknown_fields() {
704 let mut r = LimitsRecord::new(ModelLimits::new().with_context_tokens(4096), LimitSource::Operator).with_engine("llama.cpp");
705 r.model_bytes = Some(10);
706 let back: LimitsRecord = serde_json::from_str(&serde_json::to_string(&r).unwrap()).unwrap();
707 assert_eq!(back, r);
708 let newer: LimitsRecord =
709 serde_json::from_value(json!({"format": LIMITS_FORMAT, "limits": {"max_images": 1}, "source": "probe", "app": {"x": 1}})).unwrap();
710 assert_eq!((newer.source, newer.limits.max_images), (LimitSource::Other, Some(1)));
711 assert_eq!(serde_json::to_value(&newer).unwrap()["app"], json!({"x": 1}));
712 let empty: LimitsRecord = serde_json::from_str("{}").unwrap();
713 assert_eq!(empty, LimitsRecord::default());
714 assert!(serde_json::to_value(&r).unwrap().get("speech").is_none());
716 let spoken = r.clone().with_speech(SpeechProfile::new().with_presets(["af_heart"]).with_sample_rate(24_000));
717 let j = serde_json::to_value(&spoken).unwrap();
718 assert_eq!(j["speech"], json!({"presets": ["af_heart"], "sample_rate": 24000}));
719 assert_eq!(serde_json::from_value::<LimitsRecord>(j).unwrap(), spoken);
720 assert!(empty.speech.is_none());
721 }
722
723 #[test]
724 fn measures_a_speech_model() {
725 let tmp = tempfile::tempdir().unwrap();
726 let model =
727 write(tmp.path(), "Kokoro-82M-F32.gguf", &header(&[("general.architecture", json!("kokoro")), ("kokoro.context_length", json!(512))]));
728 let mmproj = write(tmp.path(), "mmproj-Kokoro-82M-F16.gguf", &crate::gguf::speech_projector_header("kokoro"));
729 let r = measure(&model, Some(&mmproj), None).unwrap();
730 let s = r.speech.clone().expect("a speech projector gives a profile");
731 assert_eq!(s.presets.as_deref().and_then(|p| p.first()).map(String::as_str), Some("af_heart"));
732 assert!(r.limits.is_unknown(), "a speech projector's encoder prices no audio input");
733 let back: LimitsRecord = serde_json::from_str(&serde_json::to_string(&r).unwrap()).unwrap();
734 assert_eq!(back.speech.as_ref(), Some(&s));
735 let vox = write(tmp.path(), "v.gguf", &voxtral_model());
737 let vp = write(tmp.path(), "mmproj-v.gguf", &projector_header("voxtral"));
738 assert!(measure(&vox, Some(&vp), None).unwrap().speech.is_none());
739 assert!(measure(&model, None, None).unwrap().speech.is_none());
740 }
741
742 #[cfg(feature = "agent")]
743 #[test]
744 fn converts_to_and_from_the_agent_limits() {
745 let l = ModelLimits::new()
746 .with_context_tokens(8192)
747 .with_max_images(3)
748 .with_image_tokens(256)
749 .with_image_edge(896)
750 .with_audio_chunks(30, 187)
751 .with_max_request_bytes(1 << 20)
752 .with_video_max_seconds(10)
753 .with_video_max_bytes(50 << 20)
754 .with_video_frames_per_minute(120);
755 let m: weirdnet_agent::MediaLimits = l.into();
756 assert_eq!(
757 m,
758 weirdnet_agent::MediaLimits::new()
759 .with_max_images(3)
760 .with_image_tokens(256)
761 .with_image_edge(896)
762 .with_audio_tokens_per_minute(374)
763 .with_max_request_bytes(1 << 20)
764 .with_video_max_seconds(10)
765 .with_video_max_bytes(50 << 20)
766 .with_video_frames_per_minute(120)
767 );
768 assert_eq!(m.video_frame_rate(), l.video_frame_rate());
769 let back = ModelLimits::from(m);
770 assert_eq!(back, ModelLimits { context_tokens: None, audio_chunk_seconds: None, audio_chunk_tokens: None, ..l }, "video round-trips");
771 assert_eq!((back.video_max_seconds, back.video_max_bytes, back.video_frames_per_minute), (Some(10), Some(50 << 20), Some(120)));
772 assert!(ModelLimits::from(weirdnet_agent::MediaLimits::UNKNOWN).is_unknown());
773 }
774}