Skip to main content

weirdnet_model/hw/
sizing.rs

1//! The usable memory budget and which models fit in it.
2
3use crate::ModelSpec;
4use serde::{Deserialize, Serialize};
5
6use super::{Accel, GIB, Hardware};
7
8/// What a model is for on a node (its role): `chat`, `embedding` or `transcribe` on the wire.
9#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
10#[serde(rename_all = "snake_case")]
11#[non_exhaustive]
12pub enum Purpose {
13    Chat,
14    Embedding,
15    /// Speech to text: audio in (an `input_audio` part), its transcript out, so a soundtrack can
16    /// become text for models that don't take audio. Never picked as a chat model.
17    Transcribe,
18}
19
20impl Purpose {
21    /// The name on the wire and in settings: `chat`, `embedding` or `transcribe`.
22    pub fn as_str(&self) -> &'static str {
23        match self {
24            Purpose::Chat => "chat",
25            Purpose::Embedding => "embedding",
26            Purpose::Transcribe => "transcribe",
27        }
28    }
29
30    /// The purpose named `name` (as [`as_str`](Self::as_str) writes it), if any.
31    pub fn parse(name: &str) -> Option<Purpose> {
32        [Purpose::Chat, Purpose::Embedding, Purpose::Transcribe].into_iter().find(|p| p.as_str() == name)
33    }
34}
35
36impl std::fmt::Display for Purpose {
37    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
38        f.write_str(self.as_str())
39    }
40}
41
42/// The speech-to-text entry ([`Purpose::Transcribe`]): Voxtral Mini 3B, which llama.cpp runs
43/// with its projector ([`CatalogEntry::projector`]).
44pub const VOXTRAL_MINI_3B: &str = "voxtral-mini-3b";
45
46/// A catalog model with what it needs in memory.
47#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
48pub struct CatalogEntry {
49    pub spec: ModelSpec,
50    pub purpose: Purpose,
51    pub quant: String,
52    /// Total and active parameters, in billions (they differ for mixture-of-experts models).
53    pub params_b: f32,
54    pub active_params_b: f32,
55    /// KV cache bytes per token at f16 (layers x KV heads x head dim x 2 x 2).
56    pub kv_bytes_per_token: u64,
57    /// Context the sizing assumes per slot.
58    pub context: u32,
59}
60
61impl CatalogEntry {
62    pub fn id(&self) -> &str {
63        &self.spec.id
64    }
65
66    /// Weights (and the projector's, for entries that need one) plus KV for `slots` concurrent
67    /// requests at the entry's context, plus 10% for compute buffers.
68    pub fn footprint(&self, slots: u32) -> u64 {
69        let kv = self.kv_bytes_per_token * self.context as u64 * slots as u64;
70        let weights = self.spec.size + self.projector().map_or(0, |p| p.size);
71        (weights + kv) + (weights + kv) / 10
72    }
73
74    /// The multimodal projector (llama.cpp `--mmproj`) the entry needs to take its input, pinned
75    /// like the model file: the audio encoder for [`VOXTRAL_MINI_3B`]. `None` for text models.
76    /// Download it with the same consent gate as the model.
77    pub fn projector(&self) -> Option<ModelSpec> {
78        match self.spec.id.as_str() {
79            VOXTRAL_MINI_3B => Some(spec(
80                "voxtral-mini-3b-mmproj",
81                "Voxtral Mini 3B audio encoder (Q8_0)",
82                "ggml-org/Voxtral-Mini-3B-2507-GGUF",
83                "mmproj-Voxtral-Mini-3B-2507-Q8_0.gguf",
84                715_714_080,
85                "4f24c4ef3ce929d02ed9d1cfb050ae9a7365f057c0ddec0d489580982ebe0d02",
86            )),
87            _ => None,
88        }
89    }
90
91    /// Whether this is a speech-to-text model ([`Purpose::Transcribe`]).
92    pub fn transcribes(&self) -> bool {
93        self.purpose == Purpose::Transcribe
94    }
95}
96
97fn spec(id: &str, label: &str, repo: &str, file: &str, size: u64, sha256: &str) -> ModelSpec {
98    ModelSpec { id: id.into(), label: label.into(), repo: repo.into(), file: file.into(), size, sha256: Some(sha256.into()) }
99}
100
101#[allow(clippy::too_many_arguments)]
102fn chat(spec: ModelSpec, quant: &str, params_b: f32, active_params_b: f32, kv_bytes_per_token: u64, context: u32) -> CatalogEntry {
103    CatalogEntry { spec, purpose: Purpose::Chat, quant: quant.into(), params_b, active_params_b, kv_bytes_per_token, context }
104}
105
106/// The tiered catalog: chat models smallest first, then the embedding model, then the
107/// speech-to-text model. Sizes and SHA-256 from the Hugging Face API (2026-11-19; Voxtral
108/// 2026-11-26); the Gemma 4 files are `weirdnet-model`'s own pinned entries.
109pub fn catalog() -> Vec<CatalogEntry> {
110    let gemma = |id: &str| crate::catalog::find(id).expect("weirdnet-model ships Gemma 4");
111    vec![
112        chat(
113            spec(
114                "smollm2-135m",
115                "SmolLM2 135M instruct (Q8_0)",
116                "bartowski/SmolLM2-135M-Instruct-GGUF",
117                "SmolLM2-135M-Instruct-Q8_0.gguf",
118                144_811_360,
119                "5a1395716f7913741cc51d98581b9b1228d80987a9f7d3664106742eb06bba83",
120            ),
121            "Q8_0",
122            0.135,
123            0.135,
124            23_040,
125            8192,
126        ),
127        chat(gemma(crate::catalog::GEMMA_4_E2B), "Q4_0", 5.1, 2.0, 32_768, 8192),
128        chat(gemma(crate::catalog::GEMMA_4_E4B), "Q4_0", 8.0, 4.0, 65_536, 8192),
129        chat(
130            spec(
131                "qwen3-8b",
132                "Qwen3 8B (Q4_K_M)",
133                "unsloth/Qwen3-8B-GGUF",
134                "Qwen3-8B-Q4_K_M.gguf",
135                5_027_784_512,
136                "120307ba529eb2439d6c430d94104dabd578497bc7bfe7e322b5d9933b449bd4",
137            ),
138            "Q4_K_M",
139            8.2,
140            8.2,
141            147_456,
142            8192,
143        ),
144        chat(
145            spec(
146                "qwen3-14b",
147                "Qwen3 14B (Q4_K_M)",
148                "unsloth/Qwen3-14B-GGUF",
149                "Qwen3-14B-Q4_K_M.gguf",
150                9_001_753_984,
151                "5eaa0870bd81ed3b58a630a271234cfa604e43ffb3a19cd68e54a80dd9d52a66",
152            ),
153            "Q4_K_M",
154            14.8,
155            14.8,
156            163_840,
157            8192,
158        ),
159        chat(
160            spec(
161                "gpt-oss-20b",
162                "gpt-oss 20B (MXFP4)",
163                "ggml-org/gpt-oss-20b-GGUF",
164                "gpt-oss-20b-MXFP4.gguf",
165                12_109_566_624,
166                "27cd6c432c7672cb812a92f611cf3ba7bbc35928262bb1e1253ff4ee6ae35901",
167            ),
168            "MXFP4",
169            21.0,
170            3.6,
171            49_152,
172            8192,
173        ),
174        chat(
175            spec(
176                "qwen3-30b-a3b",
177                "Qwen3 30B-A3B (Q4_K_M)",
178                "unsloth/Qwen3-30B-A3B-GGUF",
179                "Qwen3-30B-A3B-Q4_K_M.gguf",
180                18_556_686_912,
181                "9f1a24700a339b09c06009b729b5c809e0b64c213b8af5b711b3dbdfd0c5ba48",
182            ),
183            "Q4_K_M",
184            30.5,
185            3.3,
186            98_304,
187            8192,
188        ),
189        chat(
190            spec(
191                "qwen3-32b",
192                "Qwen3 32B (Q4_K_M)",
193                "unsloth/Qwen3-32B-GGUF",
194                "Qwen3-32B-Q4_K_M.gguf",
195                19_762_150_048,
196                "8df67573b2c23484e02ec7af295e39bed7ee774f3771d5fda2978265b59370e7",
197            ),
198            "Q4_K_M",
199            32.8,
200            32.8,
201            262_144,
202            8192,
203        ),
204        CatalogEntry {
205            spec: spec(
206                "qwen3-embedding-0.6b",
207                "Qwen3 Embedding 0.6B (Q8_0)",
208                "Qwen/Qwen3-Embedding-0.6B-GGUF",
209                "Qwen3-Embedding-0.6B-Q8_0.gguf",
210                639_150_592,
211                "06507c7b42688469c4e7298b0a1e16deff06caf291cf0a5b278c308249c3e439",
212            ),
213            purpose: Purpose::Embedding,
214            quant: "Q8_0".into(),
215            params_b: 0.6,
216            active_params_b: 0.6,
217            kv_bytes_per_token: 114_688,
218            context: 2048,
219        },
220        // Mistral's Voxtral Mini 3B (Apache-2.0): a Whisper-style audio encoder in front of a 3B
221        // decoder, transcription in eight languages; 30 seconds of audio cost 187 tokens in
222        // llama.cpp, so 16K of context holds about 20 minutes with its transcript.
223        CatalogEntry {
224            spec: spec(
225                VOXTRAL_MINI_3B,
226                "Voxtral Mini 3B speech to text (Q4_K_M)",
227                "ggml-org/Voxtral-Mini-3B-2507-GGUF",
228                "Voxtral-Mini-3B-2507-Q4_K_M.gguf",
229                2_473_001_920,
230                "4705be8ec22ca23d12632f4b4a3691faa95917d90a06d3cf3c3ec0e91958f1a8",
231            ),
232            purpose: Purpose::Transcribe,
233            quant: "Q4_K_M".into(),
234            params_b: 4.7,
235            active_params_b: 4.7,
236            kv_bytes_per_token: 122_880,
237            context: 16_384,
238        },
239    ]
240}
241
242/// The catalog entries for `purpose`, in catalog order.
243pub fn by_purpose(purpose: Purpose) -> Vec<CatalogEntry> {
244    catalog().into_iter().filter(|e| e.purpose == purpose).collect()
245}
246
247/// The speech-to-text model ([`Purpose::Transcribe`]) that fits `budget` with one request at
248/// a time, projector included, if any. [`plan`] never proposes one: transcription is optional,
249/// so an app adds it when it wants soundtracks turned into text.
250pub fn transcriber(budget: &Budget) -> Option<CatalogEntry> {
251    by_purpose(Purpose::Transcribe).into_iter().filter(|e| e.footprint(1) <= budget.usable_bytes).max_by(|a, b| a.params_b.total_cmp(&b.params_b))
252}
253
254/// The catalog entry with this id.
255pub fn find(id: &str) -> Option<CatalogEntry> {
256    catalog().into_iter().find(|e| e.spec.id == id)
257}
258
259/// How much memory models may use on this node.
260#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
261pub struct Budget {
262    /// VRAM of the first GPU, or system memory on unified and CPU-only machines.
263    pub pool_bytes: u64,
264    /// Kept for the OS (unified and CPU-only only).
265    pub reserve_bytes: u64,
266    pub usable_bytes: u64,
267}
268
269/// 85% of VRAM, or 85% of unified memory after the OS reserve (default: an eighth of RAM, at least
270/// 4 GiB). `memory_budget` overrides the result; `reserve` overrides the reserve.
271pub fn budget(hw: &Hardware, memory_budget: Option<u64>, reserve: Option<u64>) -> Budget {
272    let unified = hw.unified();
273    let pool_bytes = if unified { hw.ram_bytes } else { hw.gpus.first().map(|g| g.memory_bytes).unwrap_or(hw.ram_bytes) };
274    let reserve_bytes = if unified { reserve.unwrap_or_else(|| (hw.ram_bytes / 8).max(4 * GIB)) } else { 0 };
275    let usable = pool_bytes.saturating_sub(reserve_bytes) / 100 * 85;
276    Budget { pool_bytes, reserve_bytes, usable_bytes: memory_budget.unwrap_or(usable) }
277}
278
279/// What setup proposes for this node.
280#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
281pub struct Plan {
282    pub budget: Budget,
283    pub main: Option<CatalogEntry>,
284    pub standin: Option<CatalogEntry>,
285    pub embedding: Option<CatalogEntry>,
286    /// Concurrent requests each chat model is sized for.
287    pub slots: u32,
288    pub notes: Vec<String>,
289}
290
291/// Picks the largest chat model that fits with its KV budget, a Gemma 4 stand-in and the embedding
292/// model. CPU-only machines only get models with at most 4B active parameters, so answers stay
293/// usable.
294pub fn plan(hw: &Hardware, budget: Budget) -> Plan {
295    let slots = 2;
296    let cpu_only = hw.accel() == Accel::Cpu;
297    let mut notes = Vec::new();
298    let all = catalog();
299    let fits = |e: &&CatalogEntry| e.footprint(slots) <= budget.usable_bytes;
300    let main = all
301        .iter()
302        .filter(|e| e.purpose == Purpose::Chat && e.spec.id != "smollm2-135m")
303        .filter(|e| !cpu_only || e.active_params_b <= 4.0)
304        .filter(fits)
305        .max_by(|a, b| a.params_b.total_cmp(&b.params_b))
306        .cloned();
307    if cpu_only {
308        notes.push("CPU only: limited to models with at most 4B active parameters".into());
309    }
310    if main.is_none() {
311        notes.push("no catalog chat model fits this budget; add a smaller GGUF model".into());
312    }
313    let standin_id = if budget.usable_bytes >= 16 * GIB { crate::catalog::GEMMA_4_E4B } else { crate::catalog::GEMMA_4_E2B };
314    let standin = all.iter().find(|e| e.spec.id == standin_id).filter(fits).filter(|e| main.as_ref().is_none_or(|m| m.spec.id != e.spec.id)).cloned();
315    let embedding = all.iter().find(|e| e.purpose == Purpose::Embedding).filter(|e| e.footprint(1) <= budget.usable_bytes).cloned();
316    Plan { budget, main, standin, embedding, slots, notes }
317}
318
319#[cfg(test)]
320mod tests {
321    use super::*;
322    use crate::hw::{Gpu, parse_nvidia_smi};
323
324    fn box_with(gpus: Vec<Gpu>, ram_gib: u64) -> Hardware {
325        Hardware { os: "linux".into(), arch: "x86_64".into(), cpu_threads: 16, ram_bytes: ram_gib * GIB, gpus }
326    }
327
328    #[test]
329    fn rtx_3060_gets_an_8b() {
330        let hw = box_with(parse_nvidia_smi("NVIDIA GeForce RTX 3060, 12288, 8.6, 615.78.08", 62 * GIB), 62);
331        let b = budget(&hw, None, None);
332        assert_eq!(b.pool_bytes, 12 * GIB);
333        let p = plan(&hw, b);
334        assert_eq!(p.main.unwrap().id(), "qwen3-8b");
335        assert_eq!(p.standin.unwrap().id(), "gemma-4-e2b");
336        assert!(p.embedding.is_some());
337    }
338
339    #[test]
340    fn spark_gets_a_big_model() {
341        let hw = box_with(parse_nvidia_smi("NVIDIA GB10, [N/A], 12.1, 580.95.05", 128 * GIB), 128);
342        let b = budget(&hw, None, None);
343        assert_eq!(b.reserve_bytes, 16 * GIB);
344        let p = plan(&hw, b);
345        assert_eq!(p.main.unwrap().id(), "qwen3-32b");
346        assert_eq!(p.standin.unwrap().id(), "gemma-4-e4b");
347    }
348
349    #[test]
350    fn cpu_box_prefers_few_active_params() {
351        let hw = box_with(Vec::new(), 62);
352        let p = plan(&hw, budget(&hw, None, None));
353        assert_eq!(p.main.unwrap().id(), "qwen3-30b-a3b");
354    }
355
356    #[test]
357    fn tiny_box_gets_no_main() {
358        let hw = box_with(Vec::new(), 4);
359        let p = plan(&hw, budget(&hw, Some(GIB), None));
360        assert!(p.main.is_none());
361        assert!(!p.notes.is_empty());
362    }
363
364    #[test]
365    fn override_budget() {
366        let hw = box_with(Vec::new(), 64);
367        assert_eq!(budget(&hw, Some(10 * GIB), None).usable_bytes, 10 * GIB);
368        assert_eq!(budget(&hw, None, Some(14 * GIB)).reserve_bytes, 14 * GIB);
369    }
370
371    #[test]
372    fn transcribe_is_a_purpose_of_its_own() {
373        assert_eq!(serde_json::to_string(&Purpose::Transcribe).unwrap(), "\"transcribe\"");
374        for p in [Purpose::Chat, Purpose::Embedding, Purpose::Transcribe] {
375            assert_eq!(serde_json::from_str::<Purpose>(&format!("\"{p}\"")).unwrap(), p);
376            assert_eq!(Purpose::parse(p.as_str()), Some(p));
377        }
378        assert_eq!(Purpose::parse("speech"), None);
379        // Stored entries from before the variant still read.
380        assert_eq!(serde_json::from_str::<Purpose>("\"chat\"").unwrap(), Purpose::Chat);
381    }
382
383    #[test]
384    fn the_catalog_has_a_pinned_speech_to_text_model() {
385        let stt = by_purpose(Purpose::Transcribe);
386        assert_eq!(stt.len(), 1);
387        let v = &stt[0];
388        assert_eq!((v.id(), v.quant.as_str(), v.context), (VOXTRAL_MINI_3B, "Q4_K_M", 16_384));
389        assert!(v.transcribes());
390        assert_eq!(find(VOXTRAL_MINI_3B).as_ref(), Some(v));
391        assert_eq!(v.spec.repo, "ggml-org/Voxtral-Mini-3B-2507-GGUF");
392        assert_eq!(v.spec.sha256.as_deref().map(str::len), Some(64));
393        let p = v.projector().expect("Voxtral needs its audio encoder");
394        assert_eq!((p.repo.as_str(), p.file.as_str(), p.size), (v.spec.repo.as_str(), "mmproj-Voxtral-Mini-3B-2507-Q8_0.gguf", 715_714_080));
395        assert!(p.sha256.as_deref().is_some_and(|h| h.len() == 64 && h.chars().all(|c| c.is_ascii_hexdigit())));
396        assert_ne!(p.file, v.spec.file);
397        // 30 layers x 8 KV heads x (128 + 128) x 2 bytes.
398        assert_eq!(v.kv_bytes_per_token, 30 * 8 * 256 * 2);
399        // The projector counts in the footprint; text models have none.
400        let without = (v.spec.size + v.kv_bytes_per_token * 16_384) * 11 / 10;
401        assert!(v.footprint(1) > without);
402        assert!(catalog().iter().filter(|e| !e.transcribes()).all(|e| e.projector().is_none()));
403        // Catalog ids stay unique.
404        let mut ids: Vec<_> = catalog().iter().map(|e| e.id().to_string()).collect();
405        ids.sort();
406        ids.dedup();
407        assert_eq!(ids.len(), catalog().len());
408    }
409
410    #[test]
411    fn plans_never_pick_the_transcriber_and_it_fits_on_its_own() {
412        for (gpus, ram) in [(parse_nvidia_smi("NVIDIA GeForce RTX 3060, 12288, 8.6, 615.78.08", 62 * GIB), 62), (Vec::new(), 62), (Vec::new(), 8)] {
413            let hw = box_with(gpus, ram);
414            let p = plan(&hw, budget(&hw, None, None));
415            for e in [&p.main, &p.standin, &p.embedding].into_iter().flatten() {
416                assert!(!e.transcribes(), "{} in a plan", e.id());
417            }
418        }
419        let hw = box_with(Vec::new(), 62);
420        assert_eq!(transcriber(&budget(&hw, None, None)).map(|e| e.spec.id), Some(VOXTRAL_MINI_3B.into()));
421        assert_eq!(transcriber(&budget(&hw, Some(GIB), None)), None, "too small a budget");
422        assert!(by_purpose(Purpose::Embedding).iter().all(|e| e.purpose == Purpose::Embedding));
423    }
424}