Skip to main content

weirdnet_model/
store.rs

1//! Where model files live on disk, and which Hub they come from. LoRA adapters live apart, in
2//! `adapters/<id>/` ([`ModelStore::adapters`]), and are never listed as models.
3
4use std::path::{Path, PathBuf};
5
6use serde::{Deserialize, Serialize};
7
8use crate::catalog::ModelSpec;
9use crate::hf::{AdapterFormat, Hub, adapter_hint, split_part};
10use crate::token::HfToken;
11
12/// The store's subdirectory for adapters: one directory per adapter id.
13pub const ADAPTERS_DIR: &str = "adapters";
14/// What [`download_adapter`](crate::download::download_adapter) records next to an adapter's files.
15pub const ADAPTER_INFO: &str = "adapter.json";
16
17/// The public Hugging Face Hub.
18pub const HUB: &str = "https://huggingface.co";
19
20#[derive(Debug, Clone, PartialEq, Eq)]
21pub struct ModelStore {
22    dir: PathBuf,
23    hub: String,
24    token: Option<HfToken>,
25    /// The token goes to any hub, not only the public one (set by [`ModelStore::with_token`]).
26    token_any_hub: bool,
27}
28
29/// A model file (or split model) in the store, from [`ModelStore::list`].
30#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
31#[non_exhaustive]
32pub struct StoredModel {
33    /// The file stem without the split suffix, as in [`RepoModel::id`](crate::hf::RepoModel::id).
34    pub id: String,
35    /// Paths relative to the store directory, first part first.
36    pub files: Vec<String>,
37    pub size: u64,
38    /// Every part of a split model is there.
39    pub complete: bool,
40}
41
42/// A LoRA adapter in the store, from [`ModelStore::adapters`].
43#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
44#[non_exhaustive]
45pub struct StoredAdapter {
46    /// Its directory's name under `adapters/`.
47    pub id: String,
48    pub format: AdapterFormat,
49    /// The GGUF file (llama.cpp `--lora`), or the PEFT directory (vLLM `--lora-modules`).
50    pub path: PathBuf,
51    /// All its files together.
52    pub size: u64,
53    /// The base model as a Hub id, when known.
54    pub base_model: Option<String>,
55    /// `general.architecture` of a GGUF adapter.
56    pub architecture: Option<String>,
57    /// The Hub repo it was downloaded from, when known.
58    pub repo: Option<String>,
59    pub rank: Option<u32>,
60    pub alpha: Option<f32>,
61}
62
63/// `adapter.json`: a [`StoredAdapter`] without machine paths (the file name only).
64#[derive(Debug, Clone, Serialize, Deserialize)]
65struct AdapterInfo {
66    id: String,
67    format: AdapterFormat,
68    /// The GGUF's file name; `None` for PEFT (the directory).
69    #[serde(default)]
70    file: Option<String>,
71    #[serde(default)]
72    base_model: Option<String>,
73    #[serde(default)]
74    architecture: Option<String>,
75    #[serde(default)]
76    repo: Option<String>,
77    #[serde(default)]
78    rank: Option<u32>,
79    #[serde(default)]
80    alpha: Option<f32>,
81}
82
83pub(crate) fn write_adapter_info(dir: &Path, a: &StoredAdapter) -> crate::Result<()> {
84    let file = match a.format {
85        AdapterFormat::GgufLora => a.path.file_name().map(|f| f.to_string_lossy().into_owned()),
86        _ => None,
87    };
88    let info = AdapterInfo {
89        id: a.id.clone(),
90        format: a.format,
91        file,
92        base_model: a.base_model.clone(),
93        architecture: a.architecture.clone(),
94        repo: a.repo.clone(),
95        rank: a.rank,
96        alpha: a.alpha,
97    };
98    let json = serde_json::to_vec_pretty(&info).map_err(|e| crate::Error::Model(e.to_string()))?;
99    std::fs::write(dir.join(ADAPTER_INFO), json)?;
100    Ok(())
101}
102
103/// A LoRA GGUF by its header.
104fn is_adapter_gguf(path: &Path) -> bool {
105    std::fs::File::open(path).ok().and_then(|f| crate::gguf::read_header(std::io::BufReader::new(f)).ok()).is_some_and(|h| h.kind.is_adapter())
106}
107
108/// Bytes of an adapter's files in `dir` (not `.part` files nor `adapter.json`).
109fn dir_size(dir: &Path) -> u64 {
110    std::fs::read_dir(dir)
111        .into_iter()
112        .flatten()
113        .flatten()
114        .filter(|e| e.file_type().is_ok_and(|t| t.is_file()) && !e.file_name().to_string_lossy().ends_with(".part") && e.file_name() != ADAPTER_INFO)
115        .filter_map(|e| e.metadata().ok().map(|m| m.len()))
116        .sum()
117}
118
119impl ModelStore {
120    pub fn new(dir: impl Into<PathBuf>) -> Self {
121        Self { dir: dir.into(), hub: HUB.into(), token: None, token_any_hub: false }
122    }
123
124    /// `$WEIRDNET_MODELS_DIR`, else `<user data dir>/weirdnet/models`; the Hub from
125    /// `$WEIRDNET_HF_URL` (a mirror) when set; this node's Hugging Face token
126    /// ([`HfToken::from_env`]), which is sent only to the public Hub, never to a mirror.
127    pub fn from_env() -> Self {
128        let dir = std::env::var_os("WEIRDNET_MODELS_DIR")
129            .filter(|d| !d.is_empty())
130            .map(PathBuf::from)
131            .unwrap_or_else(|| dirs::data_dir().unwrap_or_else(std::env::temp_dir).join("weirdnet").join("models"));
132        let mut store = Self::new(dir);
133        if let Some(hub) = std::env::var("WEIRDNET_HF_URL").ok().filter(|u| !u.trim().is_empty()) {
134            store.hub = hub.trim_end_matches('/').to_string();
135        }
136        store.token = HfToken::from_env();
137        store
138    }
139
140    /// Sends `token` to this store's Hub, whichever it is (a mirror too).
141    pub fn with_token(mut self, token: Option<HfToken>) -> Self {
142        self.token = token;
143        self.token_any_hub = true;
144        self
145    }
146
147    /// The token requests to this store's Hub carry, if any.
148    pub(crate) fn token(&self) -> Option<&HfToken> {
149        self.token.as_ref().filter(|_| self.token_any_hub || self.hub == HUB)
150    }
151
152    /// Whether requests to the Hub carry a token.
153    pub fn has_token(&self) -> bool {
154        self.token().is_some()
155    }
156
157    /// A [`Hub`] client for this store's Hub, with the token when it may go there.
158    pub fn hub_client(&self) -> Hub {
159        Hub::new(&self.hub).with_token(self.token().cloned())
160    }
161
162    /// Use another Hub (a mirror, or a local server in tests).
163    pub fn with_hub(mut self, hub: impl Into<String>) -> Self {
164        self.hub = hub.into().trim_end_matches('/').to_string();
165        self
166    }
167
168    pub fn dir(&self) -> &Path {
169        &self.dir
170    }
171
172    pub fn hub(&self) -> &str {
173        &self.hub
174    }
175
176    /// Where `spec`'s file goes.
177    pub fn path(&self, spec: &ModelSpec) -> PathBuf {
178        self.dir.join(&spec.file)
179    }
180
181    /// Downloaded and complete: the size matches (the checksum was checked when it finished).
182    pub fn installed(&self, spec: &ModelSpec) -> bool {
183        std::fs::metadata(self.path(spec)).is_ok_and(|m| m.len() == spec.size)
184    }
185
186    /// Bytes of a partial download, if any.
187    pub fn partial_bytes(&self, spec: &ModelSpec) -> u64 {
188        std::fs::metadata(self.part_path(spec)).map(|m| m.len()).unwrap_or(0)
189    }
190
191    pub(crate) fn part_path(&self, spec: &ModelSpec) -> PathBuf {
192        self.dir.join(format!("{}.part", spec.file))
193    }
194
195    /// Deletes the file and any partial download. Returns whether a file was removed.
196    pub fn remove(&self, spec: &ModelSpec) -> bool {
197        let _ = std::fs::remove_file(self.part_path(spec));
198        std::fs::remove_file(self.path(spec)).is_ok()
199    }
200
201    /// The GGUF models in the store (split parts grouped; projector, draft and `.part` files
202    /// left out), sorted by id. Adapters are not models: `adapters/` is skipped, and so is a
203    /// GGUF whose name hints at an adapter ([`adapter_hint`]) when its header says it is one.
204    pub fn list(&self) -> Vec<StoredModel> {
205        let mut files = Vec::new();
206        walk(&self.dir, &self.dir, 0, &mut files);
207        files.retain(|(rel, _)| !(adapter_hint(rel) && is_adapter_gguf(&self.dir.join(rel))));
208        let mut out: std::collections::BTreeMap<String, (Vec<Part>, u32)> = Default::default();
209        for (rel, size) in files {
210            let (key, part, of) = match split_part(&rel) {
211                Some((base, part, of)) => {
212                    let dir = rel.rsplit_once('/').map(|(d, _)| format!("{d}/")).unwrap_or_default();
213                    (format!("{dir}{base}"), part, of)
214                }
215                None => (rel.strip_suffix(".gguf").or_else(|| rel.strip_suffix(".GGUF")).unwrap_or(&rel).to_string(), 1, 1),
216            };
217            let e = out.entry(key).or_default();
218            e.0.push((part, rel, size));
219            e.1 = of;
220        }
221        let mut models: Vec<StoredModel> = out
222            .into_iter()
223            .map(|(key, (mut parts, of))| {
224                parts.sort();
225                let complete = parts.len() as u32 == of && parts[0].0 == 1;
226                StoredModel {
227                    id: key.rsplit('/').next().unwrap_or(&key).to_string(),
228                    size: parts.iter().map(|p| p.2).sum(),
229                    files: parts.into_iter().map(|p| p.1).collect(),
230                    complete,
231                }
232            })
233            .collect();
234        models.sort_by(|a, b| a.id.cmp(&b.id).then_with(|| a.files.cmp(&b.files)));
235        models
236    }
237
238    /// Deletes a listed model's files (and their `.part` files) and the directories that leaves
239    /// empty. Returns the bytes freed. Paths outside the store are refused.
240    pub fn remove_local(&self, model: &StoredModel) -> crate::Result<u64> {
241        let mut freed = 0;
242        for rel in &model.files {
243            crate::hf::check_file(rel)?;
244            let path = self.dir.join(rel);
245            let _ = std::fs::remove_file(self.dir.join(format!("{rel}.part")));
246            if let Ok(m) = std::fs::metadata(&path) {
247                std::fs::remove_file(&path)?;
248                freed += m.len();
249            }
250            let mut dir = path.parent().map(Path::to_path_buf);
251            while let Some(d) = dir.filter(|d| d.starts_with(&self.dir) && *d != self.dir) {
252                if std::fs::remove_dir(&d).is_err() {
253                    break;
254                }
255                dir = d.parent().map(Path::to_path_buf);
256            }
257        }
258        Ok(freed)
259    }
260}
261
262impl ModelStore {
263    /// Where adapter `id` goes: `<store>/adapters/<id>`. The id must be one plain path part.
264    pub fn adapter_dir(&self, id: &str) -> crate::Result<PathBuf> {
265        if id.contains('/') || crate::hf::check_file(id).is_err() {
266            return Err(crate::Error::Model(format!("{id:?} is not an adapter id")));
267        }
268        Ok(self.dir.join(ADAPTERS_DIR).join(id))
269    }
270
271    /// The complete LoRA adapters under `adapters/`, sorted by id: from `adapter.json` when
272    /// [`download_adapter`](crate::download::download_adapter) wrote one, else a LoRA GGUF (by
273    /// its header) or a PEFT directory (`adapter_config.json` and its weights) found there.
274    pub fn adapters(&self) -> Vec<StoredAdapter> {
275        let mut out: Vec<StoredAdapter> = std::fs::read_dir(self.dir.join(ADAPTERS_DIR))
276            .into_iter()
277            .flatten()
278            .flatten()
279            .filter(|e| e.file_type().is_ok_and(|t| t.is_dir()))
280            .filter_map(|e| Self::adapter_in(&e.path(), &e.file_name().to_string_lossy()))
281            .collect();
282        out.sort_by(|a, b| a.id.cmp(&b.id));
283        out
284    }
285
286    fn adapter_in(dir: &Path, id: &str) -> Option<StoredAdapter> {
287        let info: Option<AdapterInfo> = std::fs::read(dir.join(ADAPTER_INFO)).ok().and_then(|b| serde_json::from_slice(&b).ok());
288        let peft_weights = ["adapter_model.safetensors", "adapter_model.bin"].iter().any(|w| dir.join(w).is_file());
289        let peft_config = || -> Option<serde_json::Value> { serde_json::from_slice(&std::fs::read(dir.join("adapter_config.json")).ok()?).ok() };
290        let gguf = || {
291            std::fs::read_dir(dir)
292                .ok()?
293                .flatten()
294                .map(|e| e.path())
295                .find(|p| p.extension().is_some_and(|x| x.eq_ignore_ascii_case("gguf")) && p.is_file() && is_adapter_gguf(p))
296        };
297        let mut a = StoredAdapter {
298            id: id.to_string(),
299            format: AdapterFormat::Peft,
300            path: dir.to_path_buf(),
301            size: dir_size(dir),
302            base_model: None,
303            architecture: None,
304            repo: None,
305            rank: None,
306            alpha: None,
307        };
308        match info {
309            Some(i) => {
310                a.format = i.format;
311                (a.base_model, a.architecture, a.repo, a.rank, a.alpha) = (i.base_model, i.architecture, i.repo, i.rank, i.alpha);
312                match i.format {
313                    AdapterFormat::GgufLora => {
314                        let file = dir.join(i.file.filter(|f| !f.contains('/') && !f.contains('\\'))?);
315                        if !file.is_file() {
316                            return None;
317                        }
318                        a.path = file;
319                    }
320                    _ if !(peft_weights && dir.join("adapter_config.json").is_file()) => return None,
321                    _ => {}
322                }
323            }
324            None if peft_weights => {
325                let (rank, alpha, base) = crate::hf::peft_lora(&peft_config()?)?;
326                (a.rank, a.alpha, a.base_model) = (rank, alpha, base);
327            }
328            None => {
329                let file = gguf()?;
330                let h = crate::gguf::read_header(std::io::BufReader::new(std::fs::File::open(&file).ok()?)).ok()?;
331                a.format = AdapterFormat::GgufLora;
332                a.alpha = match h.kind {
333                    crate::gguf::GgufKind::Adapter { alpha, .. } => alpha,
334                    _ => None,
335                };
336                (a.architecture, a.base_model, a.path) = (Some(h.architecture), h.base_model, file);
337            }
338        }
339        Some(a)
340    }
341
342    /// Deletes a stored adapter's directory. Returns the bytes freed. Ids that are not one plain
343    /// path part are refused.
344    pub fn remove_adapter(&self, adapter: &StoredAdapter) -> crate::Result<u64> {
345        let dir = self.adapter_dir(&adapter.id)?;
346        if !dir.exists() {
347            return Ok(0);
348        }
349        let freed = dir_size(&dir);
350        std::fs::remove_dir_all(&dir)?;
351        let _ = std::fs::remove_dir(self.dir.join(ADAPTERS_DIR));
352        Ok(freed)
353    }
354}
355
356/// A file of a stored model: part number, path relative to the store, size.
357type Part = (u32, String, u64);
358
359/// Model GGUFs under `dir`, as `/`-separated paths relative to `root` (four levels deep at most).
360fn walk(root: &Path, dir: &Path, depth: usize, out: &mut Vec<(String, u64)>) {
361    let Ok(entries) = std::fs::read_dir(dir) else { return };
362    for e in entries.flatten() {
363        let Ok(ft) = e.file_type() else { continue };
364        let path = e.path();
365        if ft.is_dir() && depth == 0 && e.file_name() == ADAPTERS_DIR {
366            continue;
367        } else if ft.is_dir() && depth < 4 {
368            walk(root, &path, depth + 1, out);
369        } else if ft.is_file() {
370            let name = e.file_name().to_string_lossy().to_ascii_lowercase();
371            if !name.ends_with(".gguf") || name.starts_with("mmproj") || name.starts_with("mtp-") {
372                continue;
373            }
374            let Ok(rel) = path.strip_prefix(root) else { continue };
375            let rel: Vec<String> = rel.components().map(|c| c.as_os_str().to_string_lossy().into_owned()).collect();
376            out.push((rel.join("/"), e.metadata().map(|m| m.len()).unwrap_or(0)));
377        }
378    }
379}
380
381#[cfg(test)]
382mod tests {
383    use super::*;
384    use crate::catalog;
385
386    #[test]
387    fn paths_follow_the_file_name_and_remove_clears_parts() {
388        let tmp = tempfile::tempdir().unwrap();
389        let store = ModelStore::new(tmp.path());
390        let spec = catalog::default_for(catalog::Device::Phone);
391        assert_eq!(store.path(&spec), tmp.path().join("gemma-4-E2B-it-Q4_0.gguf"));
392        assert!(!store.installed(&spec));
393        std::fs::write(store.part_path(&spec), b"abc").unwrap();
394        assert_eq!(store.partial_bytes(&spec), 3);
395        assert!(!store.remove(&spec));
396        assert_eq!(store.partial_bytes(&spec), 0);
397    }
398
399    #[test]
400    fn lists_and_removes_models_with_their_parts() {
401        let tmp = tempfile::tempdir().unwrap();
402        let store = ModelStore::new(tmp.path());
403        let w = |rel: &str, n: usize| {
404            let p = tmp.path().join(rel);
405            std::fs::create_dir_all(p.parent().unwrap()).unwrap();
406            std::fs::write(p, vec![0u8; n]).unwrap();
407        };
408        w("a-Q4_0.gguf", 3);
409        w("mmproj-a.gguf", 1);
410        w("b.gguf.part", 1);
411        w("Q8_0/b-Q8_0-00001-of-00002.gguf", 5);
412        w("Q8_0/b-Q8_0-00002-of-00002.gguf", 6);
413        w("c-00002-of-00002.gguf", 2);
414        let list = store.list();
415        assert_eq!(
416            list.iter().map(|m| (m.id.as_str(), m.size, m.complete)).collect::<Vec<_>>(),
417            [("a-Q4_0", 3, true), ("b-Q8_0", 11, true), ("c", 2, false)]
418        );
419        assert_eq!(list[1].files, ["Q8_0/b-Q8_0-00001-of-00002.gguf", "Q8_0/b-Q8_0-00002-of-00002.gguf"]);
420        w("Q8_0/b-Q8_0-00002-of-00002.gguf.part", 1);
421        assert_eq!(store.remove_local(&list[1]).unwrap(), 11);
422        assert!(!tmp.path().join("Q8_0").exists(), "the emptied directory goes too");
423        assert_eq!(store.list().len(), 2);
424        let mut evil = list[0].clone();
425        evil.files = vec!["../x.gguf".into()];
426        assert!(store.remove_local(&evil).is_err());
427    }
428
429    #[test]
430    fn adapters_are_found_without_adapter_json_and_never_listed_as_models() {
431        let tmp = tempfile::tempdir().unwrap();
432        let store = ModelStore::new(tmp.path());
433        let w = |rel: &str, b: &[u8]| {
434            let p = tmp.path().join(rel);
435            std::fs::create_dir_all(p.parent().unwrap()).unwrap();
436            std::fs::write(p, b).unwrap();
437        };
438        w("m-Q4_0.gguf", b"GGUF....");
439        w("stray-LoRA-F16.gguf", &crate::gguf::lora_header("qwen3"));
440        w("lora-merged-Q4_0.gguf", b"not an adapter header");
441        w("adapters/hand/hand.gguf", &crate::gguf::lora_header("llama"));
442        let config = br#"{"peft_type":"LORA","r":4,"lora_alpha":8,"base_model_name_or_path":"Org/B"}"#;
443        w("adapters/peft/adapter_config.json", config);
444        w("adapters/peft/adapter_model.safetensors", &[1; 10]);
445        w("adapters/half/adapter_config.json", br#"{"peft_type":"LORA"}"#);
446        w("adapters/ia3/adapter_config.json", br#"{"peft_type":"IA3"}"#);
447        w("adapters/ia3/adapter_model.safetensors", &[1; 10]);
448        assert_eq!(store.list().iter().map(|m| m.id.as_str()).collect::<Vec<_>>(), ["lora-merged-Q4_0", "m-Q4_0"], "the header decides");
449        let a = store.adapters();
450        assert_eq!(
451            a.iter().map(|a| (a.id.as_str(), a.format)).collect::<Vec<_>>(),
452            [("hand", AdapterFormat::GgufLora), ("peft", AdapterFormat::Peft)]
453        );
454        assert_eq!((a[0].architecture.as_deref(), a[0].path.clone()), (Some("llama"), tmp.path().join("adapters/hand/hand.gguf")));
455        assert_eq!((a[1].rank, a[1].alpha, a[1].base_model.as_deref(), a[1].size), (Some(4), Some(8.0), Some("Org/B"), 10 + config.len() as u64));
456        assert!(store.adapter_dir("a/b").is_err() && store.adapter_dir("..").is_err());
457        let mut evil = a[0].clone();
458        evil.id = "../m-Q4_0.gguf".into();
459        assert!(store.remove_adapter(&evil).is_err());
460        assert!(tmp.path().join("m-Q4_0.gguf").exists());
461    }
462
463    #[test]
464    fn tokens_go_to_the_public_hub_or_where_they_were_set() {
465        let t = HfToken::new("hf_x");
466        let mut store = ModelStore::new("/x");
467        store.token = t.clone();
468        assert!(store.has_token() && store.hub_client().has_token());
469        let mirror = store.clone().with_hub("http://mirror");
470        assert!(!mirror.has_token(), "an environment token never goes to a mirror");
471        assert!(mirror.with_token(t).has_token());
472        assert!(format!("{store:?}").contains("<redacted>"));
473    }
474
475    #[test]
476    fn a_mirror_loses_its_trailing_slash() {
477        assert_eq!(ModelStore::new("/x").with_hub("http://127.0.0.1:1/").hub(), "http://127.0.0.1:1");
478    }
479}