Skip to main content

weirdnet_model/
limits.rs

1//! Per-model limits for media and requests, and the record a node keeps of them.
2//!
3//! What a client needs to fit images, audio (or a video's frames and soundtrack) to one model:
4//! the context the model runs with, images per request and what one costs, audio length and
5//! what it costs, and the largest request. Every field is absent when it isn't known, never
6//! defaulted, so a client can say what is missing instead of guessing.
7//!
8//! - [`ModelLimits`]: the figures, with [`or`](ModelLimits::or) (operator settings over measured
9//!   ones), [`tightest`](ModelLimits::tightest) and cost helpers. With the `agent` feature they
10//!   convert to and from `weirdnet_agent::MediaLimits`, which catalog entries carry.
11//! - [`from_projector`]: what a llama.cpp projector's header (`mmproj`) says images and audio
12//!   cost, for the projector types whose costs follow from the header alone.
13//! - [`measure`]: read a model's GGUF (and its projector) when it loads, with the context the
14//!   node runs it at, into a [`LimitsRecord`]; [`ModelStore::record_limits`](crate::ModelStore::record_limits)
15//!   keeps it next to the model's files and [`StoredModel::limits`](crate::StoredModel::limits)
16//!   reads it back.
17//!
18//! Costs from headers follow llama.cpp's `mtmd` (2026-11): a flag such as `--image-max-tokens`
19//! changes them, so a node that passes one sets the result over the header's with
20//! [`ModelLimits::or`].
21
22use std::path::Path;
23
24use serde::{Deserialize, Serialize};
25
26use crate::gguf::{GgufKind, ProjectorInfo};
27use crate::{Error, Result};
28
29/// [`LimitsRecord::format`].
30pub const LIMITS_FORMAT: &str = "weirdnet-limits/1";
31/// The name a GGUF model's limits record gets next to its first file: `<file>.limits.json`.
32pub const LIMITS_SUFFIX: &str = ".limits.json";
33/// The limits record's name inside a safetensors or MLX model directory.
34pub const LIMITS_FILE: &str = ".limits.json";
35
36/// Seconds of audio llama.cpp's Whisper-style encoders take at a time (3000 mel frames at
37/// 16 kHz with a 160-sample hop); longer audio is cut into pieces this long, the last one
38/// padded.
39pub const WHISPER_CHUNK_SECONDS: u32 = 30;
40const WHISPER_CHUNK_FRAMES: u32 = 3000;
41/// llama.cpp's own cap on one image for Qwen-VL projectors, when the header has no
42/// `clip.vision.image_max_pixels` and the node passes no `--image-max-tokens`.
43const QWEN_VL_MAX_IMAGE_TOKENS: u32 = 4096;
44
45/// Media and request limits for one model. See the [module docs](self).
46#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
47#[non_exhaustive]
48pub struct ModelLimits {
49    /// The context in tokens the model runs with on this node (per slot: llama.cpp's
50    /// `--ctx-size` divided by `--parallel`), not the context it was trained for.
51    #[serde(default, skip_serializing_if = "Option::is_none")]
52    pub context_tokens: Option<u32>,
53    /// Most images one request may carry.
54    #[serde(default, skip_serializing_if = "Option::is_none")]
55    pub max_images: Option<u32>,
56    /// Tokens one image costs. With [`image_patch`](Self::image_patch) set, the most one image
57    /// costs; otherwise every image costs this much.
58    #[serde(default, skip_serializing_if = "Option::is_none")]
59    pub image_tokens: Option<u32>,
60    /// For models whose image cost grows with size: the edge in pixels of the square one image
61    /// token covers. Absent: a fixed cost per image.
62    #[serde(default, skip_serializing_if = "Option::is_none")]
63    pub image_patch: Option<u32>,
64    /// The longest image edge in pixels the model uses; larger images are scaled down to it.
65    #[serde(default, skip_serializing_if = "Option::is_none")]
66    pub image_edge: Option<u32>,
67    /// Longest audio input in seconds.
68    #[serde(default, skip_serializing_if = "Option::is_none")]
69    pub audio_max_seconds: Option<u32>,
70    /// Tokens one minute of audio costs.
71    #[serde(default, skip_serializing_if = "Option::is_none")]
72    pub audio_tokens_per_minute: Option<u32>,
73    /// Audio is encoded in pieces this many seconds long, the last one padded, so a short clip
74    /// costs a whole piece ([`audio_chunk_tokens`](Self::audio_chunk_tokens)).
75    #[serde(default, skip_serializing_if = "Option::is_none")]
76    pub audio_chunk_seconds: Option<u32>,
77    /// Tokens one piece of [`audio_chunk_seconds`](Self::audio_chunk_seconds) costs.
78    #[serde(default, skip_serializing_if = "Option::is_none")]
79    pub audio_chunk_tokens: Option<u32>,
80    /// Longest video the model takes whole, in seconds (models that read video natively).
81    #[serde(default, skip_serializing_if = "Option::is_none")]
82    pub video_max_seconds: Option<u32>,
83    /// Largest video the model takes whole, in bytes.
84    #[serde(default, skip_serializing_if = "Option::is_none")]
85    pub video_max_bytes: Option<u64>,
86    /// Largest request body in bytes the serving side accepts.
87    #[serde(default, skip_serializing_if = "Option::is_none")]
88    pub max_request_bytes: Option<u64>,
89}
90
91impl ModelLimits {
92    /// No limits known.
93    pub const UNKNOWN: Self = Self {
94        context_tokens: None,
95        max_images: None,
96        image_tokens: None,
97        image_patch: None,
98        image_edge: None,
99        audio_max_seconds: None,
100        audio_tokens_per_minute: None,
101        audio_chunk_seconds: None,
102        audio_chunk_tokens: None,
103        video_max_seconds: None,
104        video_max_bytes: None,
105        max_request_bytes: None,
106    };
107
108    pub fn new() -> Self {
109        Self::UNKNOWN
110    }
111
112    /// Whether no limit is known.
113    pub fn is_unknown(&self) -> bool {
114        *self == Self::UNKNOWN
115    }
116
117    pub fn with_context_tokens(mut self, tokens: u32) -> Self {
118        self.context_tokens = Some(tokens);
119        self
120    }
121
122    pub fn with_max_images(mut self, n: u32) -> Self {
123        self.max_images = Some(n);
124        self
125    }
126
127    /// Every image costs `tokens` (or at most that, with [`with_image_patch`](Self::with_image_patch)).
128    pub fn with_image_tokens(mut self, tokens: u32) -> Self {
129        self.image_tokens = Some(tokens);
130        self
131    }
132
133    /// The image cost grows with size: one token per `patch` x `patch` pixels.
134    pub fn with_image_patch(mut self, patch: u32) -> Self {
135        self.image_patch = Some(patch);
136        self
137    }
138
139    pub fn with_image_edge(mut self, pixels: u32) -> Self {
140        self.image_edge = Some(pixels);
141        self
142    }
143
144    pub fn with_audio_max_seconds(mut self, seconds: u32) -> Self {
145        self.audio_max_seconds = Some(seconds);
146        self
147    }
148
149    pub fn with_audio_tokens_per_minute(mut self, tokens: u32) -> Self {
150        self.audio_tokens_per_minute = Some(tokens);
151        self
152    }
153
154    /// Audio is encoded in `seconds`-long pieces of `tokens` each; sets
155    /// [`audio_tokens_per_minute`](Self::audio_tokens_per_minute) to match.
156    pub fn with_audio_chunks(mut self, seconds: u32, tokens: u32) -> Self {
157        self.audio_chunk_seconds = Some(seconds);
158        self.audio_chunk_tokens = Some(tokens);
159        if seconds > 0 {
160            self.audio_tokens_per_minute = u32::try_from(u64::from(tokens) * 60 / u64::from(seconds)).ok();
161        }
162        self
163    }
164
165    pub fn with_video_max_seconds(mut self, seconds: u32) -> Self {
166        self.video_max_seconds = Some(seconds);
167        self
168    }
169
170    pub fn with_video_max_bytes(mut self, bytes: u64) -> Self {
171        self.video_max_bytes = Some(bytes);
172        self
173    }
174
175    pub fn with_max_request_bytes(mut self, bytes: u64) -> Self {
176        self.max_request_bytes = Some(bytes);
177        self
178    }
179
180    /// [`audio_tokens_per_minute`](Self::audio_tokens_per_minute) per second.
181    pub fn audio_tokens_per_second(&self) -> Option<f64> {
182        self.audio_tokens_per_minute.map(|t| f64::from(t) / 60.0)
183    }
184
185    /// What one `width` x `height` image costs in tokens, if known: the fixed cost, or with
186    /// [`image_patch`](Self::image_patch) the patches after scaling down to
187    /// [`image_edge`](Self::image_edge), capped at [`image_tokens`](Self::image_tokens).
188    pub fn image_cost(&self, width: u32, height: u32) -> Option<u32> {
189        let Some(patch) = self.image_patch.filter(|p| *p > 0) else {
190            return self.image_tokens;
191        };
192        let (w, h) = self.scaled(width, height);
193        let tokens = u64::from(w.div_ceil(patch)) * u64::from(h.div_ceil(patch));
194        let tokens = u32::try_from(tokens).unwrap_or(u32::MAX);
195        Some(self.image_tokens.map_or(tokens, |cap| tokens.min(cap)))
196    }
197
198    /// `width` x `height` scaled down (aspect kept) so the longer edge fits
199    /// [`image_edge`](Self::image_edge); unchanged when it fits or no edge is known.
200    pub fn scaled(&self, width: u32, height: u32) -> (u32, u32) {
201        let long = width.max(height);
202        match self.image_edge {
203            Some(edge) if edge > 0 && long > edge => {
204                let s = |v: u32| ((u64::from(v) * u64::from(edge)).div_ceil(u64::from(long)) as u32).max(1);
205                (s(width), s(height))
206            }
207            _ => (width, height),
208        }
209    }
210
211    /// What `millis` of audio costs in tokens, if known: whole pieces when the model encodes
212    /// audio in pieces ([`audio_chunk_seconds`](Self::audio_chunk_seconds)), else the per-minute
213    /// rate rounded up.
214    pub fn audio_cost(&self, millis: u64) -> Option<u64> {
215        if let (Some(secs), Some(tokens)) = (self.audio_chunk_seconds.filter(|s| *s > 0), self.audio_chunk_tokens) {
216            return Some(millis.div_ceil(u64::from(secs) * 1000).max(1) * u64::from(tokens));
217        }
218        self.audio_tokens_per_minute.map(|t| (u64::from(t) * millis).div_ceil(60_000))
219    }
220
221    /// Each field from `self` when known, else from `fallback`: operator settings over measured
222    /// ones (`operator.or(measured)`).
223    pub fn or(self, fallback: Self) -> Self {
224        Self {
225            context_tokens: self.context_tokens.or(fallback.context_tokens),
226            max_images: self.max_images.or(fallback.max_images),
227            image_tokens: self.image_tokens.or(fallback.image_tokens),
228            image_patch: self.image_patch.or(fallback.image_patch),
229            image_edge: self.image_edge.or(fallback.image_edge),
230            audio_max_seconds: self.audio_max_seconds.or(fallback.audio_max_seconds),
231            audio_tokens_per_minute: self.audio_tokens_per_minute.or(fallback.audio_tokens_per_minute),
232            audio_chunk_seconds: self.audio_chunk_seconds.or(fallback.audio_chunk_seconds),
233            audio_chunk_tokens: self.audio_chunk_tokens.or(fallback.audio_chunk_tokens),
234            video_max_seconds: self.video_max_seconds.or(fallback.video_max_seconds),
235            video_max_bytes: self.video_max_bytes.or(fallback.video_max_bytes),
236            max_request_bytes: self.max_request_bytes.or(fallback.max_request_bytes),
237        }
238    }
239
240    /// The stricter of two copies, field by field: less context, fewer images, a smaller edge,
241    /// shorter audio and video, fewer request bytes, a smaller patch and higher token costs. A
242    /// field known on one side only keeps that side's value; a field neither side knows stays
243    /// absent.
244    pub fn tightest(self, other: Self) -> Self {
245        fn pick<T: Ord>(a: Option<T>, b: Option<T>, f: fn(T, T) -> T) -> Option<T> {
246            match (a, b) {
247                (Some(a), Some(b)) => Some(f(a, b)),
248                (a, b) => a.or(b),
249            }
250        }
251        Self {
252            context_tokens: pick(self.context_tokens, other.context_tokens, Ord::min),
253            max_images: pick(self.max_images, other.max_images, Ord::min),
254            image_tokens: pick(self.image_tokens, other.image_tokens, Ord::max),
255            image_patch: pick(self.image_patch, other.image_patch, Ord::min),
256            image_edge: pick(self.image_edge, other.image_edge, Ord::min),
257            audio_max_seconds: pick(self.audio_max_seconds, other.audio_max_seconds, Ord::min),
258            audio_tokens_per_minute: pick(self.audio_tokens_per_minute, other.audio_tokens_per_minute, Ord::max),
259            audio_chunk_seconds: pick(self.audio_chunk_seconds, other.audio_chunk_seconds, Ord::max),
260            audio_chunk_tokens: pick(self.audio_chunk_tokens, other.audio_chunk_tokens, Ord::max),
261            video_max_seconds: pick(self.video_max_seconds, other.video_max_seconds, Ord::min),
262            video_max_bytes: pick(self.video_max_bytes, other.video_max_bytes, Ord::min),
263            max_request_bytes: pick(self.max_request_bytes, other.max_request_bytes, Ord::min),
264        }
265    }
266}
267
268#[cfg(feature = "agent")]
269impl ModelLimits {
270    /// The fields `weirdnet_agent::MediaLimits` carries (catalog entries and capability
271    /// records); the context goes in the catalog entry's own `context`, and the audio piece
272    /// size and video fields are left out until the agent's type has them.
273    pub fn to_media(&self) -> weirdnet_agent::MediaLimits {
274        let mut m = weirdnet_agent::MediaLimits::new();
275        m.max_images = self.max_images;
276        m.image_tokens = self.image_tokens;
277        m.image_patch = self.image_patch;
278        m.image_edge = self.image_edge;
279        m.audio_max_seconds = self.audio_max_seconds;
280        m.audio_tokens_per_minute = self.audio_tokens_per_minute;
281        m.max_request_bytes = self.max_request_bytes;
282        m
283    }
284
285    /// The fields of `weirdnet_agent::MediaLimits` (an operator's settings, say); the rest absent.
286    pub fn from_media(m: &weirdnet_agent::MediaLimits) -> Self {
287        Self {
288            max_images: m.max_images,
289            image_tokens: m.image_tokens,
290            image_patch: m.image_patch,
291            image_edge: m.image_edge,
292            audio_max_seconds: m.audio_max_seconds,
293            audio_tokens_per_minute: m.audio_tokens_per_minute,
294            max_request_bytes: m.max_request_bytes,
295            ..Self::UNKNOWN
296        }
297    }
298}
299
300#[cfg(feature = "agent")]
301impl From<ModelLimits> for weirdnet_agent::MediaLimits {
302    fn from(l: ModelLimits) -> Self {
303        l.to_media()
304    }
305}
306
307#[cfg(feature = "agent")]
308impl From<weirdnet_agent::MediaLimits> for ModelLimits {
309    fn from(m: weirdnet_agent::MediaLimits) -> Self {
310        Self::from_media(&m)
311    }
312}
313
314/// What image and audio inputs cost, from a projector's header, for the projector types whose
315/// costs follow from the header alone (as llama.cpp's `mtmd` computes them, 2026-11):
316///
317/// - `gemma3`: every image is resized to `image_size` square and costs
318///   `(image_size / patch_size / scale)²` tokens (scale 4 unless the header sets one): 256 for
319///   Gemma 3.
320/// - `qwen2vl_merger`, `qwen2.5vl_merger`, `qwen3vl_merger` and the image side of `qwen2.5o`:
321///   one token per `2 * patch_size` pixels square, at most `image_max_pixels` (or llama.cpp's
322///   4096 tokens) per image.
323/// - `voxtral`, `ultravox`, `qwen2a` and the audio side of `qwen2.5o`: 30-second pieces of
324///   3000 mel frames, stacked (`stack_factor`), halved by the encoder and halved again by
325///   pooling (`voxtral`, `qwen2a`): 187 tokens a piece for Voxtral and Ultravox, 750 for Qwen2
326///   audio.
327///
328/// Other types, and figures a header lacks, stay absent. Nothing here says how many images a
329/// request may carry, how long audio may be or what context the model runs at.
330pub fn from_projector(p: &ProjectorInfo) -> ModelLimits {
331    let mut l = ModelLimits::new();
332    match p.image_type() {
333        Some("gemma3") => {
334            let merge = p.scale_factor.unwrap_or(4);
335            if let (Some(size), Some(patch)) = (p.image_size, p.patch_size)
336                && patch > 0
337                && merge > 0
338                && size % patch == 0
339                && (size / patch) % merge == 0
340            {
341                let side = size / patch / merge;
342                l = l.with_image_tokens(side * side).with_image_edge(size);
343            }
344        }
345        Some("qwen2vl_merger" | "qwen2.5vl_merger" | "qwen3vl_merger" | "qwen2.5o") => {
346            if let Some(patch) = p.patch_size.filter(|p| *p > 0)
347                && p.spatial_merge.unwrap_or(2) == 2
348            {
349                let unit = patch * 2;
350                let cap = match p.image_max_pixels {
351                    Some(px) => u32::try_from(px / (u64::from(unit) * u64::from(unit))).unwrap_or(u32::MAX),
352                    None => QWEN_VL_MAX_IMAGE_TOKENS,
353                };
354                l = l.with_image_patch(unit).with_image_tokens(cap);
355            }
356        }
357        _ => {}
358    }
359    let audio = match p.audio_type() {
360        Some("voxtral") => p.audio_stack_factor.map(|s| (s, true)),
361        Some("ultravox") => p.audio_stack_factor.map(|s| (s, false)),
362        Some("qwen2a" | "qwen2.5o") => Some((1, true)),
363        _ => None,
364    };
365    if let Some((stack, pool)) = audio.filter(|(s, _)| *s > 0) {
366        let mut n = WHISPER_CHUNK_FRAMES.div_ceil(stack) / 2;
367        if pool {
368            n /= 2;
369        }
370        l = l.with_audio_chunks(WHISPER_CHUNK_SECONDS, n);
371    }
372    l
373}
374
375/// How a [`LimitsRecord`]'s figures were found.
376#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
377#[serde(rename_all = "snake_case")]
378#[non_exhaustive]
379pub enum LimitSource {
380    /// Read from the model's files and the settings it was loaded with ([`measure`]).
381    #[default]
382    Measured,
383    /// Set by the node's operator for this hardware.
384    Operator,
385    /// Something this version doesn't know.
386    #[serde(other)]
387    Other,
388}
389
390fn limits_format() -> String {
391    LIMITS_FORMAT.into()
392}
393
394/// A model's limits as a node found them when it loaded the model, kept next to its files
395/// ([`ModelStore::record_limits`](crate::ModelStore::record_limits)). Unknown fields are kept in
396/// [`extra`](Self::extra) and written back.
397#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
398#[non_exhaustive]
399pub struct LimitsRecord {
400    /// [`LIMITS_FORMAT`].
401    #[serde(default = "limits_format")]
402    pub format: String,
403    #[serde(default)]
404    pub limits: ModelLimits,
405    #[serde(default)]
406    pub source: LimitSource,
407    /// What ran the model, such as `llama.cpp`.
408    #[serde(default, skip_serializing_if = "Option::is_none")]
409    pub engine: Option<String>,
410    /// The projector file's name, when one was loaded with the model.
411    #[serde(default, skip_serializing_if = "Option::is_none")]
412    pub projector: Option<String>,
413    /// The context the model was trained for (`<arch>.context_length`), for reference: the one
414    /// it runs at is [`ModelLimits::context_tokens`].
415    #[serde(default, skip_serializing_if = "Option::is_none")]
416    pub trained_context: Option<u64>,
417    /// Bytes of the model's files when this was recorded; a record whose model has since changed
418    /// size is stale and not read back.
419    #[serde(default, skip_serializing_if = "Option::is_none")]
420    pub model_bytes: Option<u64>,
421    /// When it was recorded, in seconds since the Unix epoch.
422    #[serde(default, skip_serializing_if = "Option::is_none")]
423    pub recorded_at: Option<u64>,
424    #[serde(flatten)]
425    pub extra: serde_json::Map<String, serde_json::Value>,
426}
427
428impl Default for LimitsRecord {
429    fn default() -> Self {
430        Self::new(ModelLimits::UNKNOWN, LimitSource::Measured)
431    }
432}
433
434impl LimitsRecord {
435    pub fn new(limits: ModelLimits, source: LimitSource) -> Self {
436        Self {
437            format: LIMITS_FORMAT.into(),
438            limits,
439            source,
440            engine: None,
441            projector: None,
442            trained_context: None,
443            model_bytes: None,
444            recorded_at: None,
445            extra: Default::default(),
446        }
447    }
448
449    pub fn with_engine(mut self, engine: impl Into<String>) -> Self {
450        self.engine = Some(engine.into());
451        self
452    }
453
454    /// Stamps the record with the current time.
455    pub fn stamped(mut self) -> Self {
456        self.recorded_at = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).ok().map(|d| d.as_secs());
457        self
458    }
459}
460
461fn header_of(path: &Path) -> Result<crate::gguf::GgufHeader> {
462    let f = std::fs::File::open(path).map_err(|e| Error::Model(format!("{}: {e}", path.display())))?;
463    crate::gguf::read_header(std::io::BufReader::new(f)).map_err(|e| Error::Model(format!("{}: {e}", path.display())))
464}
465
466/// Reads a GGUF model (the first file of a split model) and its projector, if any, as a node
467/// loads them, into a record: what the projector's header says images and audio cost
468/// ([`from_projector`]), the context the node runs the model at (`context_tokens`, per slot;
469/// `None` when the caller doesn't know it, never the trained context) and the trained context
470/// for reference. Fails when `model` is not a GGUF model or `projector` not a projector.
471pub fn measure(model: &Path, projector: Option<&Path>, context_tokens: Option<u32>) -> Result<LimitsRecord> {
472    let m = header_of(model)?;
473    if m.kind != GgufKind::Model {
474        return Err(Error::Model(format!("{} is not a GGUF model", model.display())));
475    }
476    let mut limits = ModelLimits::new();
477    let mut projector_name = None;
478    if let Some(path) = projector {
479        let p = header_of(path)?;
480        let Some(info) = p.projector.filter(|_| p.kind.is_projector()) else {
481            return Err(Error::Model(format!("{} is not a projector", path.display())));
482        };
483        limits = from_projector(&info);
484        projector_name = path.file_name().map(|n| n.to_string_lossy().into_owned());
485    }
486    limits.context_tokens = context_tokens;
487    let mut record = LimitsRecord::new(limits, LimitSource::Measured).stamped();
488    record.projector = projector_name;
489    record.trained_context = m.info.and_then(|i| i.context_length);
490    Ok(record)
491}
492
493#[cfg(test)]
494mod tests {
495    use super::*;
496    use crate::gguf::{header, projector_header, read_header};
497    use serde_json::json;
498
499    fn info(which: &str) -> ProjectorInfo {
500        read_header(&projector_header(which)[..]).unwrap().projector.unwrap()
501    }
502
503    #[test]
504    fn unknown_is_empty_on_the_wire() {
505        assert!(ModelLimits::default().is_unknown());
506        assert_eq!(serde_json::to_string(&ModelLimits::UNKNOWN).unwrap(), "{}");
507        let back: ModelLimits = serde_json::from_str("{}").unwrap();
508        assert!(back.is_unknown());
509        let l = ModelLimits::new().with_context_tokens(8192).with_max_images(4).with_audio_chunks(30, 187).with_video_max_bytes(1 << 20);
510        let j = serde_json::to_value(l).unwrap();
511        assert_eq!(
512            j,
513            json!({"context_tokens": 8192, "max_images": 4, "audio_tokens_per_minute": 374, "audio_chunk_seconds": 30, "audio_chunk_tokens": 187, "video_max_bytes": 1048576})
514        );
515        assert_eq!(serde_json::from_value::<ModelLimits>(j).unwrap(), l);
516        // Fields from a newer version are ignored, not an error.
517        let newer: ModelLimits = serde_json::from_value(json!({"max_images": 2, "video_frame_rate": 2})).unwrap();
518        assert_eq!(newer, ModelLimits::new().with_max_images(2));
519    }
520
521    #[test]
522    fn costs() {
523        let fixed = ModelLimits::new().with_image_tokens(256);
524        assert_eq!(fixed.image_cost(4000, 3000), Some(256));
525        assert_eq!(ModelLimits::UNKNOWN.image_cost(10, 10), None);
526        let patched = ModelLimits::new().with_image_patch(28).with_image_edge(896);
527        assert_eq!(patched.scaled(1792, 896), (896, 448));
528        assert_eq!(patched.image_cost(1792, 896), Some(32 * 16));
529        assert_eq!(patched.with_image_tokens(100).image_cost(1792, 896), Some(100), "capped");
530        let chunks = ModelLimits::new().with_audio_chunks(30, 187);
531        assert_eq!(chunks.audio_tokens_per_minute, Some(374));
532        assert_eq!(chunks.audio_cost(5_000), Some(187), "a short clip costs a whole piece");
533        assert_eq!(chunks.audio_cost(30_000), Some(187));
534        assert_eq!(chunks.audio_cost(30_001), Some(374));
535        assert_eq!(chunks.audio_cost(0), Some(187));
536        let rate = ModelLimits::new().with_audio_tokens_per_minute(375);
537        assert_eq!(rate.audio_tokens_per_second(), Some(6.25));
538        assert_eq!(rate.audio_cost(1_000), Some(7));
539        assert_eq!(ModelLimits::UNKNOWN.audio_cost(1_000), None);
540        assert_eq!(ModelLimits::new().with_audio_chunks(0, 10).audio_tokens_per_minute, None, "no rate from a zero-length piece");
541    }
542
543    #[test]
544    fn operator_over_measured_and_tightest() {
545        let measured = ModelLimits::new().with_context_tokens(8192).with_image_tokens(256).with_image_edge(896);
546        let operator = ModelLimits::new().with_max_images(2).with_image_tokens(300);
547        let both = operator.or(measured);
548        assert_eq!((both.max_images, both.image_tokens, both.image_edge, both.context_tokens), (Some(2), Some(300), Some(896), Some(8192)));
549        let a = ModelLimits::new().with_context_tokens(4096).with_max_images(8).with_audio_chunks(30, 187).with_video_max_seconds(60);
550        let b = ModelLimits::new().with_context_tokens(8192).with_max_images(2).with_audio_chunks(30, 750).with_max_request_bytes(1 << 20);
551        let t = a.tightest(b);
552        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)));
553        assert_eq!((t.video_max_seconds, t.max_request_bytes), (Some(60), Some(1 << 20)), "one side only keeps its value");
554        assert_eq!(a.tightest(ModelLimits::UNKNOWN), a);
555    }
556
557    #[test]
558    fn projector_costs_follow_llama_cpp() {
559        // Gemma 3: 896 / 14 = 64 patches a side, pooled by 4: 256 tokens.
560        let g = from_projector(&info("gemma3"));
561        assert_eq!(g, ModelLimits::new().with_image_tokens(256).with_image_edge(896));
562        // Qwen2.5-VL: one token per 28 px square, up to llama.cpp's 4096.
563        let q = from_projector(&info("qwen2.5vl"));
564        assert_eq!(q, ModelLimits::new().with_image_patch(28).with_image_tokens(4096));
565        assert_eq!(q.image_cost(560, 280), Some(20 * 10));
566        assert_eq!(from_projector(&info("qwen3vl")).image_patch, Some(32));
567        // Voxtral: 3000 frames / 4 stacked / 2 (conv) / 2 (pool) = 187 per 30 s.
568        let v = from_projector(&info("voxtral"));
569        assert_eq!(v, ModelLimits::new().with_audio_chunks(30, 187));
570        assert_eq!(v.audio_tokens_per_minute, Some(374));
571        // Ultravox: 3000 / 8 / 2 = 187, no pooling.
572        assert_eq!(from_projector(&info("ultravox")).audio_chunk_tokens, Some(187));
573        // Qwen2.5-Omni: both sides; Qwen2 audio is 3000 / 2 / 2 = 750 per piece.
574        let o = from_projector(&info("qwen2.5o"));
575        assert_eq!((o.image_patch, o.audio_chunk_tokens, o.audio_tokens_per_minute), (Some(28), Some(750), Some(1500)));
576        // Nothing about images per request, audio length or context comes from a header.
577        for l in [g, q, v, o] {
578            assert_eq!((l.max_images, l.audio_max_seconds, l.context_tokens, l.max_request_bytes), (None, None, None, None));
579        }
580    }
581
582    #[test]
583    fn unknown_projectors_and_missing_figures_stay_absent() {
584        let mut p = ProjectorInfo {
585            vision: true,
586            audio: true,
587            vision_projector: Some("gemma4v".into()),
588            audio_projector: Some("gemma4a".into()),
589            ..Default::default()
590        };
591        p.image_size = Some(224);
592        p.patch_size = Some(16);
593        assert!(from_projector(&p).is_unknown(), "types this version doesn't know are not guessed");
594        let mut g = info("gemma3");
595        g.patch_size = None;
596        assert!(from_projector(&g).is_unknown());
597        let mut g = info("gemma3");
598        g.scale_factor = Some(3);
599        assert!(from_projector(&g).is_unknown(), "64 patches don't pool evenly by 3");
600        let mut v = info("voxtral");
601        v.audio_stack_factor = None;
602        assert!(from_projector(&v).is_unknown(), "Voxtral needs its stack factor");
603        let mut q = info("qwen2.5vl");
604        q.spatial_merge = Some(4);
605        assert!(from_projector(&q).is_unknown(), "llama.cpp refuses a merge other than 2");
606        q.spatial_merge = None;
607        q.image_max_pixels = Some(28 * 28 * 1280);
608        assert_eq!(from_projector(&q).image_tokens, Some(1280), "the header's max pixels set the cap");
609        let mut no_encoder = info("gemma3");
610        no_encoder.vision = false;
611        assert!(from_projector(&no_encoder).is_unknown(), "a type without its encoder flag says nothing");
612    }
613
614    fn write(dir: &Path, name: &str, bytes: &[u8]) -> std::path::PathBuf {
615        let p = dir.join(name);
616        std::fs::write(&p, bytes).unwrap();
617        p
618    }
619
620    fn voxtral_model() -> Vec<u8> {
621        header(&[
622            ("general.architecture", json!("llama")),
623            ("general.type", json!("model")),
624            ("llama.block_count", json!(30)),
625            ("llama.context_length", json!(131072)),
626            ("llama.embedding_length", json!(3072)),
627            ("llama.attention.head_count", json!(32)),
628            ("llama.attention.head_count_kv", json!(8)),
629            ("llama.attention.key_length", json!(128)),
630            ("llama.attention.value_length", json!(128)),
631        ])
632    }
633
634    #[test]
635    fn measures_a_model_and_projector_at_load() {
636        let tmp = tempfile::tempdir().unwrap();
637        let model = write(tmp.path(), "Voxtral-Mini-3B-2507-Q4_K_M.gguf", &voxtral_model());
638        let mmproj = write(tmp.path(), "mmproj-Voxtral-Mini-3B-2507-Q8_0.gguf", &projector_header("voxtral"));
639        let r = measure(&model, Some(&mmproj), Some(16384)).unwrap();
640        assert_eq!(r.format, LIMITS_FORMAT);
641        assert_eq!(r.source, LimitSource::Measured);
642        assert_eq!(r.limits, ModelLimits::new().with_audio_chunks(30, 187).with_context_tokens(16384));
643        assert_eq!((r.projector.as_deref(), r.trained_context), (Some("mmproj-Voxtral-Mini-3B-2507-Q8_0.gguf"), Some(131072)));
644        assert!(r.recorded_at.is_some());
645        // Without the context or a projector, those stay absent; the trained context is not used.
646        let bare = measure(&model, None, None).unwrap();
647        assert!(bare.limits.is_unknown());
648        assert_eq!(bare.trained_context, Some(131072));
649        // Wrong kinds and missing files fail.
650        assert!(measure(&mmproj, None, None).is_err(), "a projector is not a model");
651        assert!(measure(&model, Some(&model), None).is_err(), "a model is not a projector");
652        let lora = write(tmp.path(), "lora.gguf", &crate::gguf::lora_header("llama"));
653        assert!(measure(&lora, None, None).is_err());
654        assert!(measure(&tmp.path().join("gone.gguf"), None, None).is_err());
655    }
656
657    #[test]
658    fn records_round_trip_and_keep_unknown_fields() {
659        let mut r = LimitsRecord::new(ModelLimits::new().with_context_tokens(4096), LimitSource::Operator).with_engine("llama.cpp");
660        r.model_bytes = Some(10);
661        let back: LimitsRecord = serde_json::from_str(&serde_json::to_string(&r).unwrap()).unwrap();
662        assert_eq!(back, r);
663        let newer: LimitsRecord =
664            serde_json::from_value(json!({"format": LIMITS_FORMAT, "limits": {"max_images": 1}, "source": "probe", "app": {"x": 1}})).unwrap();
665        assert_eq!((newer.source, newer.limits.max_images), (LimitSource::Other, Some(1)));
666        assert_eq!(serde_json::to_value(&newer).unwrap()["app"], json!({"x": 1}));
667        let empty: LimitsRecord = serde_json::from_str("{}").unwrap();
668        assert_eq!(empty, LimitsRecord::default());
669    }
670
671    #[cfg(feature = "agent")]
672    #[test]
673    fn converts_to_and_from_the_agent_limits() {
674        let l = ModelLimits::new()
675            .with_context_tokens(8192)
676            .with_max_images(3)
677            .with_image_tokens(256)
678            .with_image_edge(896)
679            .with_audio_chunks(30, 187)
680            .with_max_request_bytes(1 << 20)
681            .with_video_max_seconds(10);
682        let m: weirdnet_agent::MediaLimits = l.into();
683        assert_eq!(
684            m,
685            weirdnet_agent::MediaLimits::new()
686                .with_max_images(3)
687                .with_image_tokens(256)
688                .with_image_edge(896)
689                .with_audio_tokens_per_minute(374)
690                .with_max_request_bytes(1 << 20)
691        );
692        let back = ModelLimits::from(m);
693        assert_eq!(back, ModelLimits { context_tokens: None, audio_chunk_seconds: None, audio_chunk_tokens: None, video_max_seconds: None, ..l });
694        assert!(ModelLimits::from(weirdnet_agent::MediaLimits::UNKNOWN).is_unknown());
695    }
696}