Skip to main content

weirdnet_model/
download.rs

1//! Consent-gated download of one model file, or every part of a split model, or a LoRA adapter
2//! ([`download_adapter`]): resumes a `.part`, checks the size and the SHA-256, and only then
3//! renames it into place. Requests carry the
4//! store's Hugging Face token when it may go to the store's Hub (see [`ModelStore::from_env`]).
5
6use std::io::{Read, Write};
7use std::path::{Path, PathBuf};
8
9use sha2::{Digest, Sha256};
10
11use crate::catalog::{ModelSpec, human};
12use crate::hf::{AdapterFormat, RepoAdapter, check_file, check_repo};
13use crate::store::{ModelStore, StoredAdapter};
14use crate::{Error, Result};
15
16/// The user said yes to downloading this model. [`download`] needs one, so nothing downloads
17/// without an explicit OK. Create it only after showing [`ModelSpec::consent_text`].
18///
19/// A model under a restricting license ([`hw::restricted_license`](crate::hw::restricted_license),
20/// such as Fish Audio Drama 3 under [`FISH_AUDIO_COMMUNITY`](crate::speech::FISH_AUDIO_COMMUNITY))
21/// also needs the operator's explicit acceptance of that license:
22/// [`accepting_license`](Self::accepting_license).
23#[derive(Debug, Clone, PartialEq, Eq)]
24pub struct Consent {
25    id: String,
26    adapter: bool,
27    license: Option<String>,
28}
29
30impl Consent {
31    pub fn given(spec: &ModelSpec) -> Self {
32        Self { id: spec.id.clone(), adapter: false, license: None }
33    }
34
35    /// The user said yes to downloading this adapter ([`download_adapter`]). It doesn't cover a
36    /// model of the same id, nor the other way round.
37    pub fn given_adapter(adapter: &RepoAdapter) -> Self {
38        Self { id: adapter.id.clone(), adapter: true, license: None }
39    }
40
41    /// The operator explicitly accepted `license` (by name, such as `fish-audio-community`, as
42    /// with Ymir's `--accept-license fish-audio-community`), which a restricted model's download
43    /// needs. Ask for it only after showing the license; it covers that license only. Since 0.5.5.
44    pub fn accepting_license(mut self, license: impl Into<String>) -> Self {
45        self.license = Some(license.into());
46        self
47    }
48
49    /// Whether this consent accepts `license`.
50    pub fn accepts_license(&self, license: &str) -> bool {
51        self.license.as_deref().is_some_and(|l| l.eq_ignore_ascii_case(license))
52    }
53}
54
55/// How far a download is.
56#[derive(Debug, Clone, Copy, PartialEq, Eq)]
57pub struct Progress {
58    pub done: u64,
59    pub total: u64,
60}
61
62impl Progress {
63    /// 0.0 to 1.0.
64    pub fn fraction(&self) -> f32 {
65        if self.total == 0 { 0.0 } else { (self.done as f64 / self.total as f64).min(1.0) as f32 }
66    }
67}
68
69/// Downloads `spec` into `store`. `progress` returns `false` to cancel (the `.part` is kept so a
70/// later call resumes). Returns the file's path; an already complete, matching file is kept.
71pub fn download(store: &ModelStore, spec: &ModelSpec, consent: &Consent, progress: &mut dyn FnMut(Progress) -> bool) -> Result<PathBuf> {
72    if consent.adapter || consent.id != spec.id {
73        return Err(Error::Consent);
74    }
75    if let Some(license) = crate::hw::restricted_license(spec)
76        && !consent.accepts_license(license)
77    {
78        return Err(Error::Model(format!(
79            "{} is under the {license} license, which restricts how it may be used; download it only after the operator accepts that license explicitly",
80            spec.id
81        )));
82    }
83    check_file(&spec.file)?;
84    let file = File { url: spec.url(store.hub()), repo: &spec.repo, name: &spec.file, size: spec.size, sha256: spec.sha256.as_deref() };
85    fetch(store, &file, &store.path(spec), &store.part_path(spec), progress)
86}
87
88/// One file to fetch.
89struct File<'a> {
90    url: String,
91    repo: &'a str,
92    /// The name in the repo (for messages).
93    name: &'a str,
94    size: u64,
95    sha256: Option<&'a str>,
96}
97
98/// Fetches `file` to `dest` through `part`, resuming, checking the size and the hash.
99fn fetch(store: &ModelStore, file: &File<'_>, dest: &Path, part: &Path, progress: &mut dyn FnMut(Progress) -> bool) -> Result<PathBuf> {
100    let (dest, part) = (dest.to_path_buf(), part.to_path_buf());
101    std::fs::create_dir_all(dest.parent().unwrap_or(store.dir()))?;
102    let total = file.size;
103    if total > 0 && std::fs::metadata(&dest).is_ok_and(|m| m.len() == total) {
104        match &file.sha256 {
105            Some(want) if !sha256_of(&dest)?.eq_ignore_ascii_case(want) => std::fs::remove_file(&dest)?,
106            _ => {
107                progress(Progress { done: total, total });
108                return Ok(dest);
109            }
110        }
111    }
112    let have = std::fs::metadata(&part).map(|m| m.len()).unwrap_or(0);
113    let mut done = have;
114    if have < total || total == 0 {
115        let mut req = store.hub_client().get(&file.url);
116        if have > 0 && have < total {
117            req = req.header("Range", format!("bytes={have}-"));
118        }
119        let mut resp = req.call().map_err(|e| Error::Http(e.to_string()))?;
120        let status = resp.status().as_u16();
121        done = match status {
122            206 => have,
123            200 => 0,
124            s @ (401 | 403) if !store.has_token() => {
125                return Err(Error::Http(format!("the Hub answered {s}; {} may be gated or private (set HF_TOKEN on this node)", file.repo)));
126            }
127            s => return Err(Error::Http(format!("the Hub answered {s}"))),
128        };
129        let mut file = std::fs::OpenOptions::new().create(true).write(true).append(done > 0).truncate(done == 0).open(&part)?;
130        let mut body = resp.body_mut().as_reader();
131        let mut buf = vec![0u8; 1 << 16];
132        loop {
133            if !progress(Progress { done, total }) {
134                return Err(Error::Cancelled { done: human(done), total: human(total) });
135            }
136            let n = body.read(&mut buf)?;
137            if n == 0 {
138                break;
139            }
140            file.write_all(&buf[..n])?;
141            done += n as u64;
142            if done > total {
143                break;
144            }
145        }
146        file.flush()?;
147    }
148    if done != total {
149        if done > total {
150            let _ = std::fs::remove_file(&part);
151        }
152        return Err(Error::Incomplete { done: human(done), total: human(total) });
153    }
154    if let Some(want) = &file.sha256 {
155        let got = sha256_of(&part)?;
156        if !got.eq_ignore_ascii_case(want) {
157            let _ = std::fs::remove_file(&part);
158            return Err(Error::Checksum { name: file.name.to_string(), got });
159        }
160    }
161    std::fs::rename(&part, &dest)?;
162    progress(Progress { done, total });
163    Ok(dest)
164}
165
166/// Downloads every part of a split model (or the one file of a single one), in order, with one
167/// [`Consent`] for the model: all `parts` must share its id (as
168/// [`RepoModel::specs`](crate::hf::RepoModel::specs) makes them). Progress counts all parts
169/// together. Returns the first part's path, which llama.cpp loads the whole model from.
170pub fn download_parts(store: &ModelStore, parts: &[ModelSpec], consent: &Consent, progress: &mut dyn FnMut(Progress) -> bool) -> Result<PathBuf> {
171    let first = parts.first().ok_or_else(|| Error::Model("no files to download".into()))?;
172    if parts.iter().any(|p| p.id != consent.id) {
173        return Err(Error::Consent);
174    }
175    let total: u64 = parts.iter().map(|p| p.size).sum();
176    let mut before = 0;
177    for p in parts {
178        download(store, p, consent, &mut |pr| progress(Progress { done: before + pr.done.min(p.size), total }))?;
179        before += p.size;
180    }
181    Ok(store.path(first))
182}
183
184/// Downloads a LoRA adapter of `repo` (from [`Hub::adapters`](crate::hf::Hub::adapters)) into
185/// `<store>/adapters/<id>/`, with the same resume, size and SHA-256 checks as [`download`], under
186/// a [`Consent::given_adapter`]. A GGUF adapter's header is checked once it is in place (deleted
187/// when it is not a LoRA adapter). Writes `adapter.json` next to the files, so
188/// [`ModelStore::adapters`] knows the repo, format and base model later. Returns the GGUF file,
189/// or the PEFT directory (what vLLM's `--lora-modules` takes).
190pub fn download_adapter(
191    store: &ModelStore,
192    repo: &str,
193    adapter: &RepoAdapter,
194    consent: &Consent,
195    progress: &mut dyn FnMut(Progress) -> bool,
196) -> Result<PathBuf> {
197    if !consent.adapter || consent.id != adapter.id {
198        return Err(Error::Consent);
199    }
200    check_repo(repo)?;
201    let dir = store.adapter_dir(&adapter.id)?;
202    if adapter.files.is_empty() {
203        return Err(Error::Model(format!("adapter {} has no files", adapter.id)));
204    }
205    let total: u64 = adapter.files.iter().map(|f| f.size).sum();
206    let mut before = 0;
207    let mut paths = Vec::new();
208    for f in &adapter.files {
209        check_file(&f.name)?;
210        let base = f.name.rsplit('/').next().unwrap_or(&f.name);
211        let dest = dir.join(base);
212        let part = dir.join(format!("{base}.part"));
213        let file =
214            File { url: format!("{}/{repo}/resolve/main/{}", store.hub(), f.name), repo, name: &f.name, size: f.size, sha256: f.sha256.as_deref() };
215        let size = f.size;
216        paths.push(fetch(store, &file, &dest, &part, &mut |p| progress(Progress { done: before + p.done.min(size), total }))?);
217        before += size;
218    }
219    let path = match adapter.format {
220        AdapterFormat::GgufLora => {
221            let gguf = paths[0].clone();
222            let header = crate::gguf::read_header(std::fs::File::open(&gguf)?);
223            if !header.as_ref().is_ok_and(|h| h.kind.is_lora()) {
224                let _ = std::fs::remove_dir_all(&dir);
225                return Err(Error::Model(format!("{} is not a LoRA adapter GGUF; it was deleted", adapter.files[0].name)));
226            }
227            gguf
228        }
229        _ => dir.clone(),
230    };
231    let info = StoredAdapter {
232        id: adapter.id.clone(),
233        format: adapter.format,
234        path: path.clone(),
235        size: total,
236        base_model: adapter.base_model.clone(),
237        architecture: adapter.architecture.clone(),
238        repo: Some(repo.to_string()),
239        rank: adapter.rank,
240        alpha: adapter.alpha,
241        provenance: None,
242    };
243    crate::store::write_adapter_info(&dir, &info)?;
244    Ok(path)
245}
246
247/// Lower-case hex SHA-256 of a file.
248pub fn sha256_of(path: &Path) -> Result<String> {
249    let mut hasher = Sha256::new();
250    std::io::copy(&mut std::fs::File::open(path)?, &mut hasher)?;
251    Ok(hasher.finalize().iter().map(|b| format!("{b:02x}")).collect())
252}
253
254#[cfg(test)]
255mod tests {
256    use super::*;
257    use crate::hf::AdapterFormat;
258    use crate::testing::MockHub;
259
260    fn body() -> Vec<u8> {
261        (0..2_000_000u32).map(|i| (i % 251) as u8).collect()
262    }
263
264    fn spec_for(body: &[u8]) -> ModelSpec {
265        let sum = Sha256::digest(body).iter().map(|b| format!("{b:02x}")).collect::<String>();
266        ModelSpec { id: "t".into(), label: "Test".into(), repo: "o/n".into(), file: "t.gguf".into(), size: body.len() as u64, sha256: Some(sum) }
267    }
268
269    #[test]
270    fn downloads_checks_and_renames() {
271        let b = body();
272        let hub = MockHub::start("/o/n/resolve/main/t.gguf", b.clone());
273        let tmp = tempfile::tempdir().unwrap();
274        let store = ModelStore::new(tmp.path()).with_hub(hub.url());
275        let spec = spec_for(&b);
276        let mut last = 0.0;
277        let path = download(&store, &spec, &Consent::given(&spec), &mut |p| {
278            last = p.fraction();
279            true
280        })
281        .unwrap();
282        assert_eq!(std::fs::read(&path).unwrap(), b);
283        assert_eq!(last, 1.0);
284        assert!(store.installed(&spec));
285        assert_eq!(store.partial_bytes(&spec), 0);
286        // A second call keeps the verified file and makes no request.
287        let hits = hub.requests();
288        download(&store, &spec, &Consent::given(&spec), &mut |_| true).unwrap();
289        assert_eq!(hub.requests(), hits);
290    }
291
292    #[test]
293    fn a_cancelled_download_resumes_with_a_range_request() {
294        let b = body();
295        let hub = MockHub::start("/o/n/resolve/main/t.gguf", b.clone());
296        let tmp = tempfile::tempdir().unwrap();
297        let store = ModelStore::new(tmp.path()).with_hub(hub.url());
298        let spec = spec_for(&b);
299        let mut calls = 0;
300        let err = download(&store, &spec, &Consent::given(&spec), &mut |_| {
301            calls += 1;
302            calls < 2
303        })
304        .unwrap_err();
305        assert!(matches!(err, Error::Cancelled { .. }), "{err}");
306        let kept = store.partial_bytes(&spec);
307        assert!(kept > 0 && kept < b.len() as u64, "kept {kept}");
308        download(&store, &spec, &Consent::given(&spec), &mut |_| true).unwrap();
309        assert_eq!(std::fs::read(store.path(&spec)).unwrap(), b);
310        assert_eq!(hub.last_range(), Some(format!("bytes={kept}-")));
311    }
312
313    #[test]
314    fn a_wrong_checksum_deletes_the_part_and_names_the_file() {
315        let b = body();
316        let hub = MockHub::start("/o/n/resolve/main/t.gguf", b.clone());
317        let tmp = tempfile::tempdir().unwrap();
318        let store = ModelStore::new(tmp.path()).with_hub(hub.url());
319        let mut spec = spec_for(&b);
320        spec.sha256 = Some("0".repeat(64));
321        let err = download(&store, &spec, &Consent::given(&spec), &mut |_| true).unwrap_err();
322        assert!(matches!(err, Error::Checksum { ref name, .. } if name == "t.gguf"), "{err}");
323        assert_eq!(store.partial_bytes(&spec), 0);
324        assert!(!store.installed(&spec));
325    }
326
327    #[test]
328    fn consent_for_another_model_is_refused_and_http_errors_are_reported() {
329        let b = body();
330        let hub = MockHub::start("/o/n/resolve/main/other.gguf", b.clone());
331        let tmp = tempfile::tempdir().unwrap();
332        let store = ModelStore::new(tmp.path()).with_hub(hub.url());
333        let spec = spec_for(&b);
334        let mut other = spec.clone();
335        other.id = "other".into();
336        assert!(matches!(download(&store, &spec, &Consent::given(&other), &mut |_| true), Err(Error::Consent)));
337        let err = download(&store, &spec, &Consent::given(&spec), &mut |_| true).unwrap_err();
338        assert!(matches!(err, Error::Http(ref m) if m.contains("404")), "{err}");
339    }
340
341    #[test]
342    fn split_models_download_every_part_into_their_directory() {
343        let (a, b) = (body(), body()[..500_000].to_vec());
344        let hub = MockHub::start_with(vec![
345            ("/o/n/resolve/main/Q8_0/m-00001-of-00002.gguf".into(), "application/octet-stream", a.clone()),
346            ("/o/n/resolve/main/Q8_0/m-00002-of-00002.gguf".into(), "application/octet-stream", b.clone()),
347        ]);
348        let tmp = tempfile::tempdir().unwrap();
349        let store = ModelStore::new(tmp.path()).with_hub(hub.url()).with_token(crate::HfToken::new("hf_t"));
350        let mut parts = Vec::new();
351        for (name, data) in [("Q8_0/m-00001-of-00002.gguf", &a), ("Q8_0/m-00002-of-00002.gguf", &b)] {
352            let mut s = spec_for(data);
353            (s.id, s.file) = ("m".into(), name.into());
354            parts.push(s);
355        }
356        let mut seen = Vec::new();
357        let path = download_parts(&store, &parts, &Consent::given(&parts[0]), &mut |p| {
358            seen.push(p);
359            true
360        })
361        .unwrap();
362        assert_eq!(path, tmp.path().join("Q8_0/m-00001-of-00002.gguf"));
363        assert_eq!(std::fs::read(tmp.path().join("Q8_0/m-00002-of-00002.gguf")).unwrap(), b);
364        let total = (a.len() + b.len()) as u64;
365        assert!(seen.iter().all(|p| p.total == total));
366        assert!(seen.windows(2).all(|w| w[0].done <= w[1].done), "progress only goes up");
367        assert_eq!(seen.last().unwrap().done, total);
368        assert!(hub.seen().iter().all(|s| s.auth.as_deref() == Some("Bearer hf_t")));
369        let mut other = parts[0].clone();
370        other.id = "x".into();
371        assert!(matches!(download_parts(&store, &parts, &Consent::given(&other), &mut |_| true), Err(Error::Consent)));
372        let mut evil = parts[0].clone();
373        evil.file = "../evil.gguf".into();
374        assert!(download(&store, &evil, &Consent::given(&evil), &mut |_| true).is_err());
375    }
376
377    #[test]
378    fn adapters_download_into_their_own_directory_with_consent() {
379        let hub = crate::testing::adapter_hub();
380        let tmp = tempfile::tempdir().unwrap();
381        let store = ModelStore::new(tmp.path()).with_hub(hub.url());
382        let found = store.hub_client().adapters("o/n").unwrap();
383        let (gguf, peft) = (&found[0], &found[1]);
384        let spec =
385            ModelSpec { id: gguf.id.clone(), label: String::new(), repo: "o/n".into(), file: "m-LoRA-F16.gguf".into(), size: 1500, sha256: None };
386        assert!(matches!(download_adapter(&store, "o/n", gguf, &Consent::given(&spec), &mut |_| true), Err(Error::Consent)), "model consent");
387        assert!(matches!(download(&store, &spec, &Consent::given_adapter(gguf), &mut |_| true), Err(Error::Consent)), "adapter consent");
388        assert!(matches!(download_adapter(&store, "o/n", gguf, &Consent::given_adapter(peft), &mut |_| true), Err(Error::Consent)));
389
390        let path = download_adapter(&store, "o/n", gguf, &Consent::given_adapter(gguf), &mut |_| true).unwrap();
391        assert_eq!(path, tmp.path().join("adapters/m-LoRA-F16/m-LoRA-F16.gguf"));
392        let mut seen = Vec::new();
393        let dir = download_adapter(&store, "o/n", peft, &Consent::given_adapter(peft), &mut |p| {
394            seen.push(p);
395            true
396        })
397        .unwrap();
398        assert_eq!(dir, tmp.path().join("adapters/tune"));
399        assert!(dir.join("adapter_config.json").is_file() && dir.join("adapter_model.safetensors").is_file());
400        assert_eq!(seen.last().map(|p| (p.done, p.total)), Some((peft.size, peft.size)));
401        assert!(seen.windows(2).all(|w| w[0].done <= w[1].done));
402
403        let stored = store.adapters();
404        assert_eq!(
405            stored.iter().map(|a| (a.id.as_str(), a.format)).collect::<Vec<_>>(),
406            [("m-LoRA-F16", AdapterFormat::GgufLora), ("tune", AdapterFormat::Peft)]
407        );
408        assert_eq!((stored[0].path.clone(), stored[0].architecture.as_deref(), stored[0].repo.as_deref()), (path, Some("qwen3"), Some("o/n")));
409        assert_eq!((stored[1].base_model.as_deref(), stored[1].rank), (Some("Org/Base-8B"), Some(16)));
410        let info = std::fs::read_to_string(dir.join(crate::store::ADAPTER_INFO)).unwrap();
411        assert!(!info.contains(&tmp.path().display().to_string()), "adapter.json holds no machine paths: {info}");
412        assert!(store.list().is_empty(), "adapters are not models");
413
414        let mut evil = gguf.clone();
415        evil.id = "../x".into();
416        assert!(download_adapter(&store, "o/n", &evil, &Consent::given_adapter(&evil), &mut |_| true).is_err());
417        let mut bad = gguf.clone();
418        bad.files[0].sha256 = Some("0".repeat(64));
419        bad.id = "bad".into();
420        assert!(matches!(download_adapter(&store, "o/n", &bad, &Consent::given_adapter(&bad), &mut |_| true), Err(Error::Checksum { .. })));
421        assert!(store.adapters().iter().all(|a| a.id != "bad"), "an unfinished adapter is not listed");
422
423        assert_eq!(store.remove_adapter(&stored[1]).unwrap(), peft.size);
424        assert!(!dir.exists());
425        assert_eq!(store.adapters().len(), 1);
426    }
427
428    #[test]
429    fn a_model_gguf_is_not_kept_as_an_adapter() {
430        let hub = crate::testing::adapter_hub();
431        let tmp = tempfile::tempdir().unwrap();
432        let store = ModelStore::new(tmp.path()).with_hub(hub.url());
433        let mut fake = store.hub_client().adapters("o/n").unwrap().remove(0);
434        fake.files[0].name = "m-Q4_0.gguf".into();
435        fake.files[0].size = 4000;
436        fake.files[0].sha256 = None;
437        let err = download_adapter(&store, "o/n", &fake, &Consent::given_adapter(&fake), &mut |_| true).unwrap_err();
438        assert!(err.to_string().contains("not a LoRA adapter"), "{err}");
439        assert!(!tmp.path().join("adapters/m-LoRA-F16").exists());
440    }
441
442    #[test]
443    fn a_short_body_is_incomplete_and_kept_for_resume() {
444        let b = body();
445        let hub = MockHub::start("/o/n/resolve/main/t.gguf", b[..1000].to_vec());
446        let tmp = tempfile::tempdir().unwrap();
447        let store = ModelStore::new(tmp.path()).with_hub(hub.url());
448        let spec = spec_for(&b);
449        let err = download(&store, &spec, &Consent::given(&spec), &mut |_| true).unwrap_err();
450        assert!(matches!(err, Error::Incomplete { .. }), "{err}");
451        assert_eq!(store.partial_bytes(&spec), 1000);
452    }
453
454    #[test]
455    fn a_restricted_license_needs_explicit_acceptance() {
456        let b = body();
457        let mut spec = spec_for(&b);
458        spec.id = "my-drama".into();
459        spec.repo = "ggml-org/drama-3-GGUF".into();
460        let hub = MockHub::start("/ggml-org/drama-3-GGUF/resolve/main/t.gguf", b.clone());
461        let tmp = tempfile::tempdir().unwrap();
462        let store = ModelStore::new(tmp.path()).with_hub(hub.url());
463        for consent in [Consent::given(&spec), Consent::given(&spec).accepting_license("apache-2.0")] {
464            let err = download(&store, &spec, &consent, &mut |_| true).unwrap_err();
465            assert!(err.to_string().contains("fish-audio-community"), "{err}");
466        }
467        assert_eq!(hub.requests(), 0, "refused before any request");
468        let consent = Consent::given(&spec).accepting_license("Fish-Audio-Community");
469        assert!(consent.accepts_license(crate::speech::FISH_AUDIO_COMMUNITY));
470        let path = download(&store, &spec, &consent, &mut |_| true).unwrap();
471        assert_eq!(std::fs::read(path).unwrap(), b);
472        // Other models need no acceptance.
473        let free = spec_for(&b);
474        assert!(!Consent::given(&free).accepts_license("fish-audio-community"));
475    }
476}