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::speech::SpeechProfile;
28use crate::{Error, Result};
29
30/// [`LimitsRecord::format`].
31pub const LIMITS_FORMAT: &str = "weirdnet-limits/1";
32/// The name a GGUF model's limits record gets next to its first file: `<file>.limits.json`.
33pub const LIMITS_SUFFIX: &str = ".limits.json";
34/// The limits record's name inside a safetensors or MLX model directory.
35pub const LIMITS_FILE: &str = ".limits.json";
36
37/// Seconds of audio llama.cpp's Whisper-style encoders take at a time (3000 mel frames at
38/// 16 kHz with a 160-sample hop); longer audio is cut into pieces this long, the last one
39/// padded.
40pub const WHISPER_CHUNK_SECONDS: u32 = 30;
41const WHISPER_CHUNK_FRAMES: u32 = 3000;
42/// llama.cpp's own cap on one image for Qwen-VL projectors, when the header has no
43/// `clip.vision.image_max_pixels` and the node passes no `--image-max-tokens`.
44const QWEN_VL_MAX_IMAGE_TOKENS: u32 = 4096;
45
46/// Media and request limits for one model. See the [module docs](self).
47#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
48#[non_exhaustive]
49pub struct ModelLimits {
50    /// The context in tokens the model runs with on this node (per slot: llama.cpp's
51    /// `--ctx-size` divided by `--parallel`), not the context it was trained for.
52    #[serde(default, skip_serializing_if = "Option::is_none")]
53    pub context_tokens: Option<u32>,
54    /// Most images one request may carry.
55    #[serde(default, skip_serializing_if = "Option::is_none")]
56    pub max_images: Option<u32>,
57    /// Tokens one image costs. With [`image_patch`](Self::image_patch) set, the most one image
58    /// costs; otherwise every image costs this much.
59    #[serde(default, skip_serializing_if = "Option::is_none")]
60    pub image_tokens: Option<u32>,
61    /// For models whose image cost grows with size: the edge in pixels of the square one image
62    /// token covers. Absent: a fixed cost per image.
63    #[serde(default, skip_serializing_if = "Option::is_none")]
64    pub image_patch: Option<u32>,
65    /// The longest image edge in pixels the model uses; larger images are scaled down to it.
66    #[serde(default, skip_serializing_if = "Option::is_none")]
67    pub image_edge: Option<u32>,
68    /// Longest audio input in seconds.
69    #[serde(default, skip_serializing_if = "Option::is_none")]
70    pub audio_max_seconds: Option<u32>,
71    /// Tokens one minute of audio costs.
72    #[serde(default, skip_serializing_if = "Option::is_none")]
73    pub audio_tokens_per_minute: Option<u32>,
74    /// Audio is encoded in pieces this many seconds long, the last one padded, so a short clip
75    /// costs a whole piece ([`audio_chunk_tokens`](Self::audio_chunk_tokens)).
76    #[serde(default, skip_serializing_if = "Option::is_none")]
77    pub audio_chunk_seconds: Option<u32>,
78    /// Tokens one piece of [`audio_chunk_seconds`](Self::audio_chunk_seconds) costs.
79    #[serde(default, skip_serializing_if = "Option::is_none")]
80    pub audio_chunk_tokens: Option<u32>,
81    /// Longest video the model takes whole, in seconds (models that read video natively).
82    #[serde(default, skip_serializing_if = "Option::is_none")]
83    pub video_max_seconds: Option<u32>,
84    /// Largest video the model takes whole, in bytes.
85    #[serde(default, skip_serializing_if = "Option::is_none")]
86    pub video_max_bytes: Option<u64>,
87    /// Most frames the model reads from one minute of video sent whole (120 for 2 a second),
88    /// kept per minute so the type stays `Eq`. Since 0.5.5.
89    #[serde(default, skip_serializing_if = "Option::is_none")]
90    pub video_frames_per_minute: Option<u32>,
91    /// Largest request body in bytes the serving side accepts.
92    #[serde(default, skip_serializing_if = "Option::is_none")]
93    pub max_request_bytes: Option<u64>,
94}
95
96impl ModelLimits {
97    /// No limits known.
98    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    /// Whether no limit is known.
119    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    /// Every image costs `tokens` (or at most that, with [`with_image_patch`](Self::with_image_patch)).
134    pub fn with_image_tokens(mut self, tokens: u32) -> Self {
135        self.image_tokens = Some(tokens);
136        self
137    }
138
139    /// The image cost grows with size: one token per `patch` x `patch` pixels.
140    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    /// Audio is encoded in `seconds`-long pieces of `tokens` each; sets
161    /// [`audio_tokens_per_minute`](Self::audio_tokens_per_minute) to match.
162    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    /// The model reads at most `frames` frames per minute of video (120 for 2 a second).
182    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    /// [`video_frames_per_minute`](Self::video_frames_per_minute) per second.
188    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    /// [`audio_tokens_per_minute`](Self::audio_tokens_per_minute) per second.
198    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    /// What one `width` x `height` image costs in tokens, if known: the fixed cost, or with
203    /// [`image_patch`](Self::image_patch) the patches after scaling down to
204    /// [`image_edge`](Self::image_edge), capped at [`image_tokens`](Self::image_tokens).
205    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    /// `width` x `height` scaled down (aspect kept) so the longer edge fits
216    /// [`image_edge`](Self::image_edge); unchanged when it fits or no edge is known.
217    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    /// What `millis` of audio costs in tokens, if known: whole pieces when the model encodes
229    /// audio in pieces ([`audio_chunk_seconds`](Self::audio_chunk_seconds)), else the per-minute
230    /// rate rounded up.
231    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    /// Each field from `self` when known, else from `fallback`: operator settings over measured
239    /// ones (`operator.or(measured)`).
240    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    /// The stricter of two copies, field by field: less context, fewer images, a smaller edge,
259    /// shorter audio and video, fewer video frames per minute, fewer request bytes, a smaller patch and higher token costs. A
260    /// field known on one side only keeps that side's value; a field neither side knows stays
261    /// absent.
262    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    /// The fields `weirdnet_agent::MediaLimits` carries (catalog entries and capability
290    /// records), video included (since 0.5.5, `weirdnet-agent` 0.5.10); the context goes in the
291    /// catalog entry's own `context`, and the audio piece size is left out (the agent's type
292    /// carries the per-minute rate).
293    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    /// The fields of `weirdnet_agent::MediaLimits` (an operator's settings, say); the rest absent.
309    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
340/// What image and audio inputs cost, from a projector's header, for the projector types whose
341/// costs follow from the header alone (as llama.cpp's `mtmd` computes them, 2026-11):
342///
343/// - `gemma3`: every image is resized to `image_size` square and costs
344///   `(image_size / patch_size / scale)²` tokens (scale 4 unless the header sets one): 256 for
345///   Gemma 3.
346/// - `qwen2vl_merger`, `qwen2.5vl_merger`, `qwen3vl_merger` and the image side of `qwen2.5o`:
347///   one token per `2 * patch_size` pixels square, at most `image_max_pixels` (or llama.cpp's
348///   4096 tokens) per image.
349/// - `voxtral`, `ultravox`, `qwen2a` and the audio side of `qwen2.5o`: 30-second pieces of
350///   3000 mel frames, stacked (`stack_factor`), halved by the encoder and halved again by
351///   pooling (`voxtral`, `qwen2a`): 187 tokens a piece for Voxtral and Ultravox, 750 for Qwen2
352///   audio.
353///
354/// Other types, and figures a header lacks, stay absent. Nothing here says how many images a
355/// request may carry, how long audio may be or what context the model runs at.
356pub 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/// How a [`LimitsRecord`]'s figures were found.
402#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
403#[serde(rename_all = "snake_case")]
404#[non_exhaustive]
405pub enum LimitSource {
406    /// Read from the model's files and the settings it was loaded with ([`measure`]).
407    #[default]
408    Measured,
409    /// Set by the node's operator for this hardware.
410    Operator,
411    /// Something this version doesn't know.
412    #[serde(other)]
413    Other,
414}
415
416fn limits_format() -> String {
417    LIMITS_FORMAT.into()
418}
419
420/// A model's limits as a node found them when it loaded the model, kept next to its files
421/// ([`ModelStore::record_limits`](crate::ModelStore::record_limits)). Unknown fields are kept in
422/// [`extra`](Self::extra) and written back.
423#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
424#[non_exhaustive]
425pub struct LimitsRecord {
426    /// [`LIMITS_FORMAT`].
427    #[serde(default = "limits_format")]
428    pub format: String,
429    #[serde(default)]
430    pub limits: ModelLimits,
431    #[serde(default)]
432    pub source: LimitSource,
433    /// What ran the model, such as `llama.cpp`.
434    #[serde(default, skip_serializing_if = "Option::is_none")]
435    pub engine: Option<String>,
436    /// The projector file's name, when one was loaded with the model.
437    #[serde(default, skip_serializing_if = "Option::is_none")]
438    pub projector: Option<String>,
439    /// The context the model was trained for (`<arch>.context_length`), for reference: the one
440    /// it runs at is [`ModelLimits::context_tokens`].
441    #[serde(default, skip_serializing_if = "Option::is_none")]
442    pub trained_context: Option<u64>,
443    /// Bytes of the model's files when this was recorded; a record whose model has since changed
444    /// size is stale and not read back.
445    #[serde(default, skip_serializing_if = "Option::is_none")]
446    pub model_bytes: Option<u64>,
447    /// When it was recorded, in seconds since the Unix epoch.
448    #[serde(default, skip_serializing_if = "Option::is_none")]
449    pub recorded_at: Option<u64>,
450    /// What a speech model does ([`Purpose::Speak`](crate::hw::Purpose::Speak)): from the
451    /// headers at load ([`measure`], [`speech::from_gguf`](crate::speech::from_gguf)) or what
452    /// the engine reported, kept with the limits. `None` for models that don't speak, and in
453    /// records from before 0.5.5. Since 0.5.5.
454    #[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    /// Sets the speech profile ([`speech`](Self::speech)), such as what the engine reported
488    /// over what [`measure`] read.
489    pub fn with_speech(mut self, speech: SpeechProfile) -> Self {
490        self.speech = Some(speech);
491        self
492    }
493
494    /// Stamps the record with the current time.
495    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
506/// Reads a GGUF model (the first file of a split model) and its projector, if any, as a node
507/// loads them, into a record: what the projector's header says images and audio cost
508/// ([`from_projector`]), the context the node runs the model at (`context_tokens`, per slot;
509/// `None` when the caller doesn't know it, never the trained context) and the trained context
510/// for reference. A speech model's projector also gives its speech profile
511/// ([`LimitsRecord::speech`], see [`speech::from_gguf`](crate::speech::from_gguf)). Fails when
512/// `model` is not a GGUF model or `projector` not a projector.
513pub 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        // Fields from a newer version are ignored, not an error.
562        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        // Gemma 3: 896 / 14 = 64 patches a side, pooled by 4: 256 tokens.
605        let g = from_projector(&info("gemma3"));
606        assert_eq!(g, ModelLimits::new().with_image_tokens(256).with_image_edge(896));
607        // Qwen2.5-VL: one token per 28 px square, up to llama.cpp's 4096.
608        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        // Voxtral: 3000 frames / 4 stacked / 2 (conv) / 2 (pool) = 187 per 30 s.
613        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        // Ultravox: 3000 / 8 / 2 = 187, no pooling.
617        assert_eq!(from_projector(&info("ultravox")).audio_chunk_tokens, Some(187));
618        // Qwen2.5-Omni: both sides; Qwen2 audio is 3000 / 2 / 2 = 750 per piece.
619        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        // Nothing about images per request, audio length or context comes from a header.
622        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        // Without the context or a projector, those stay absent; the trained context is not used.
691        let bare = measure(&model, None, None).unwrap();
692        assert!(bare.limits.is_unknown());
693        assert_eq!(bare.trained_context, Some(131072));
694        // Wrong kinds and missing files fail.
695        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        // A speech profile is kept, and absent from records without one.
715        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        // Models that don't speak have none.
736        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}