Skip to main content

weirdnet_model/
hf.rs

1//! Hugging Face Hub: search for GGUF repos, read a repo's GGUF files (split files grouped into
2//! one model), read a file's header for KV sizing, so any repo can become a [`ModelSpec`]; and
3//! find a repo's LoRA adapters ([`Hub::adapters`]: GGUF LoRA files and PEFT safetensors), which
4//! are never listed as models.
5//!
6//! [`Hub`] sends this node's [`HfToken`] (if any) with every request; redirects to other hosts
7//! (the file CDN) don't carry it.
8
9use serde::{Deserialize, Serialize};
10use serde_json::Value;
11
12use crate::catalog::ModelSpec;
13use crate::gguf::{self, GgufHeader, GgufInfo};
14use crate::token::HfToken;
15use crate::{Error, Result};
16/// A repo id: `owner/name`, Hub characters only (never a path trick).
17pub fn check_repo(id: &str) -> Result<()> {
18    let ok = |p: &str| !p.is_empty() && p != "." && p != ".." && p.chars().all(|c| c.is_ascii_alphanumeric() || "-_.".contains(c));
19    match id.split_once('/') {
20        Some((o, n)) if ok(o) && ok(n) => Ok(()),
21        _ => Err(Error::BadRepo(id.to_string())),
22    }
23}
24
25/// One GGUF file in a repo.
26#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
27pub struct RepoFile {
28    pub name: String,
29    pub size: u64,
30    pub sha256: Option<String>,
31}
32
33/// The GGUF files of `repo` on the Hub at `hub` (names, sizes and hashes from the file metadata;
34/// no weights are downloaded). Projector (`mmproj-`) and draft (`mtp-`, `dspark-`) files and
35/// importance matrices (`imatrix`) are left out. No
36/// token; see [`Hub::repo_files`].
37pub fn repo_files(hub: &str, repo: &str) -> Result<Vec<RepoFile>> {
38    Hub::new(hub).repo_files(repo)
39}
40
41/// Every file in a repo's model info (`siblings`).
42fn siblings(v: &Value) -> Vec<RepoFile> {
43    v["siblings"]
44        .as_array()
45        .into_iter()
46        .flatten()
47        .filter_map(|s| {
48            let name = s["rfilename"].as_str()?;
49            Some(RepoFile { name: name.to_string(), size: s["size"].as_u64().unwrap_or(0), sha256: s["lfs"]["sha256"].as_str().map(str::to_string) })
50        })
51        .collect()
52}
53
54/// The Hub's file list in a repo's model info (`siblings`), GGUF model files only: not
55/// projectors (`mmproj-`), draft models for speculative decoding (`mtp-`, `dspark-`; a repo's
56/// smallest GGUF is often one) nor importance matrices (`imatrix`, which are not models).
57pub fn parse_files(v: &Value) -> Vec<RepoFile> {
58    siblings(v)
59        .into_iter()
60        .filter(|f| {
61            let file = f.name.rsplit('/').next().unwrap_or(&f.name);
62            let lower = file.to_ascii_lowercase();
63            lower.ends_with(".gguf")
64                && !lower.starts_with("mmproj")
65                && !lower.starts_with("mtp-")
66                && !lower.starts_with("dspark-")
67                && !lower.starts_with("imatrix")
68        })
69        .collect()
70}
71
72/// Whether a file name hints at an adapter: a `lora`, `qlora`, `adapter` or `adapters` word in
73/// it (`Qwen3-8B-tune-LoRA-F16.gguf`). Only a hint: [`gguf::read_header`] decides.
74pub fn adapter_hint(name: &str) -> bool {
75    let file = name.rsplit('/').next().unwrap_or(name).to_ascii_lowercase();
76    file.split(|c: char| !c.is_ascii_alphanumeric()).any(|w| matches!(w, "lora" | "qlora" | "adapter" | "adapters"))
77}
78
79/// Hub tags that mark a repo as an adapter: `base_model:adapter:...`, or the `peft` library.
80fn adapter_tags(v: &Value) -> bool {
81    v["library_name"].as_str() == Some("peft")
82        || v["tags"].as_array().into_iter().flatten().filter_map(Value::as_str).any(|t| t == "peft" || t.starts_with("base_model:adapter:"))
83}
84
85/// The base model a repo's tags or model card name (`base_model:adapter:owner/name`, then the
86/// card's `base_model`).
87fn tagged_base(v: &Value) -> Option<String> {
88    let tagged = v["tags"].as_array().into_iter().flatten().filter_map(Value::as_str).find_map(|t| t.strip_prefix("base_model:adapter:"));
89    let card = match &v["cardData"]["base_model"] {
90        Value::String(s) => Some(s.as_str()),
91        Value::Array(a) => a.first().and_then(Value::as_str),
92        _ => None,
93    };
94    tagged.or(card).filter(|b| check_repo(b).is_ok()).map(str::to_string)
95}
96
97/// How an adapter is stored.
98#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
99#[serde(rename_all = "snake_case")]
100#[non_exhaustive]
101pub enum AdapterFormat {
102    /// One GGUF file (`general.type` = `adapter`, `adapter.type` = `lora`), for llama.cpp.
103    GgufLora,
104    /// A PEFT directory (`adapter_config.json` and `adapter_model.safetensors`), for vLLM.
105    Peft,
106}
107
108/// One LoRA adapter in a repo ([`Hub::adapters`]).
109#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
110#[non_exhaustive]
111pub struct RepoAdapter {
112    /// The GGUF file stem, or the PEFT directory's name (the repo's name for one at the root).
113    pub id: String,
114    pub format: AdapterFormat,
115    /// The files to fetch: the GGUF, or `adapter_config.json` then the weights.
116    pub files: Vec<RepoFile>,
117    pub size: u64,
118    /// `general.architecture` of a GGUF adapter; PEFT configs don't say.
119    pub architecture: Option<String>,
120    /// The base model as a Hub id: from the GGUF header, PEFT's `base_model_name_or_path`, or the
121    /// repo's tags.
122    pub base_model: Option<String>,
123    /// PEFT `r`; GGUF adapters don't record it.
124    pub rank: Option<u32>,
125    /// `adapter.lora.alpha` or PEFT `lora_alpha`.
126    pub alpha: Option<f32>,
127}
128
129/// `(rank, alpha, base model)` from a PEFT `adapter_config.json`, if it is a LoRA one.
130pub(crate) fn peft_lora(config: &Value) -> Option<(Option<u32>, Option<f32>, Option<String>)> {
131    let kind = config["peft_type"].as_str().unwrap_or("LORA");
132    if !kind.eq_ignore_ascii_case("lora") {
133        return None;
134    }
135    let rank = config["r"].as_u64().and_then(|r| u32::try_from(r).ok());
136    let alpha = config["lora_alpha"].as_f64().map(|a| a as f32);
137    let base = config["base_model_name_or_path"].as_str().filter(|b| check_repo(b).is_ok()).map(str::to_string);
138    Some((rank, alpha, base))
139}
140
141impl ModelSpec {
142    /// A spec for one file of `repo`, as listed by [`repo_files`]. The id is the file stem.
143    pub fn from_repo_file(repo: &str, file: &RepoFile) -> Result<Self> {
144        check_repo(repo)?;
145        let name = file.name.rsplit('/').next().unwrap_or(&file.name);
146        let stem = name.strip_suffix(".gguf").or_else(|| name.strip_suffix(".GGUF")).unwrap_or(name);
147        Ok(Self {
148            id: stem.to_string(),
149            label: stem.to_string(),
150            repo: repo.to_string(),
151            file: file.name.clone(),
152            size: file.size,
153            sha256: file.sha256.clone(),
154        })
155    }
156}
157
158/// A file name inside a repo: relative, `/`-separated, no `.`/`..` parts (never a path trick).
159pub fn check_file(name: &str) -> Result<()> {
160    let ok = !name.is_empty()
161        && !name.starts_with('/')
162        && !name.contains('\\')
163        && name.split('/').all(|p| !p.is_empty() && p != "." && p != ".." && !p.contains(':'));
164    if ok { Ok(()) } else { Err(Error::Model(format!("{name:?} is not a file name inside a repo"))) }
165}
166
167/// A Hub search: repos matching `query`, most downloaded first.
168#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
169#[non_exhaustive]
170pub struct Search {
171    pub query: String,
172    /// At most this many hits (capped at 100).
173    pub limit: usize,
174    /// Only repos tagged `gguf` (default on).
175    pub gguf_only: bool,
176    /// Keep adapter repos (PEFT or `base_model:adapter:` tags; default off, so hits are models).
177    #[serde(default)]
178    pub adapters: bool,
179}
180
181impl Search {
182    pub fn new(query: impl Into<String>) -> Self {
183        Self { query: query.into(), limit: 20, gguf_only: true, adapters: false }
184    }
185
186    pub fn with_limit(mut self, limit: usize) -> Self {
187        self.limit = limit;
188        self
189    }
190
191    pub fn with_gguf_only(mut self, on: bool) -> Self {
192        self.gguf_only = on;
193        self
194    }
195
196    /// Keep adapter repos in the hits ([`SearchHit::adapter`] marks them).
197    pub fn with_adapters(mut self, on: bool) -> Self {
198        self.adapters = on;
199        self
200    }
201}
202
203/// One repo in [`Hub::search`] results.
204#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
205#[non_exhaustive]
206pub struct SearchHit {
207    /// `owner/name`.
208    pub id: String,
209    pub downloads: u64,
210    pub likes: u64,
211    /// The repo needs an accepted licence and a token (`auto` or `manual` approval on the Hub).
212    pub gated: bool,
213    pub pipeline_tag: Option<String>,
214    pub last_modified: Option<String>,
215    /// The repo holds an adapter, not a model (its Hub tags say PEFT or `base_model:adapter:`).
216    #[serde(default)]
217    pub adapter: bool,
218}
219
220/// Parses the Hub's `/api/models` answer; entries without a valid repo id are dropped.
221pub fn parse_search(v: &Value) -> Vec<SearchHit> {
222    v.as_array()
223        .into_iter()
224        .flatten()
225        .filter_map(|m| {
226            let id = m["id"].as_str().or_else(|| m["modelId"].as_str())?;
227            check_repo(id).ok()?;
228            Some(SearchHit {
229                id: id.to_string(),
230                downloads: m["downloads"].as_u64().unwrap_or(0),
231                likes: m["likes"].as_u64().unwrap_or(0),
232                gated: match &m["gated"] {
233                    Value::Bool(b) => *b,
234                    Value::String(s) => !s.is_empty() && s != "false",
235                    _ => false,
236                },
237                pipeline_tag: m["pipeline_tag"].as_str().map(str::to_string),
238                last_modified: m["lastModified"].as_str().map(str::to_string),
239                adapter: adapter_tags(m),
240            })
241        })
242        .collect()
243}
244
245/// One downloadable model in a repo: a single GGUF, or every part of a split GGUF
246/// (`name-00001-of-00003.gguf` ...), in order.
247#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
248#[non_exhaustive]
249pub struct RepoModel {
250    /// The file stem without the split suffix, such as `Qwen3-32B-Q4_K_M`; the [`ModelSpec`] id.
251    pub id: String,
252    /// The quantization read from the file name, such as `Q4_K_M` (see [`quant_of`]).
253    pub quant: Option<String>,
254    /// The files, first part first. llama.cpp loads a split model from its first part.
255    pub parts: Vec<RepoFile>,
256    /// All parts together.
257    pub size: u64,
258    /// Every part of a split model is in the repo.
259    pub complete: bool,
260}
261
262impl RepoModel {
263    /// The first (or only) file.
264    pub fn first(&self) -> &RepoFile {
265        &self.parts[0]
266    }
267
268    pub fn is_split(&self) -> bool {
269        self.parts.len() > 1
270    }
271
272    /// One [`ModelSpec`] per part, all with this model's id, for
273    /// [`download_parts`](crate::download::download_parts).
274    pub fn specs(&self, repo: &str) -> Result<Vec<ModelSpec>> {
275        check_repo(repo)?;
276        self.parts
277            .iter()
278            .map(|f| {
279                check_file(&f.name)?;
280                Ok(ModelSpec {
281                    id: self.id.clone(),
282                    label: self.id.clone(),
283                    repo: repo.to_string(),
284                    file: f.name.clone(),
285                    size: f.size,
286                    sha256: f.sha256.clone(),
287                })
288            })
289            .collect()
290    }
291}
292
293/// `(stem, part, of)` for a split file name such as `dir/m-Q4_K_M-00002-of-00003.gguf`.
294pub fn split_part(name: &str) -> Option<(&str, u32, u32)> {
295    let file = name.rsplit('/').next().unwrap_or(name);
296    let stem = file.strip_suffix(".gguf").or_else(|| file.strip_suffix(".GGUF"))?;
297    let (rest, of) = stem.rsplit_once("-of-")?;
298    let (base, part) = rest.rsplit_once('-')?;
299    let digits = |s: &str| s.len() == 5 && s.chars().all(|c| c.is_ascii_digit());
300    if !digits(part) || !digits(of) || base.is_empty() {
301        return None;
302    }
303    let (part, of): (u32, u32) = (part.parse().ok()?, of.parse().ok()?);
304    (part >= 1 && part <= of).then_some((base, part, of))
305}
306
307/// GGUF quantization names, longer ones first so `Q4_K_M` wins over `Q4_K`.
308const QUANTS: &[&str] = &[
309    "IQ1_S", "IQ1_M", "IQ2_XXS", "IQ2_XS", "IQ2_S", "IQ2_M", "IQ3_XXS", "IQ3_XS", "IQ3_S", "IQ3_M", "IQ4_XS", "IQ4_NL", "TQ1_0", "TQ2_0", "Q2_K_XL",
310    "Q2_K_L", "Q2_K_S", "Q3_K_XL", "Q3_K_L", "Q3_K_M", "Q3_K_S", "Q4_K_XL", "Q4_K_L", "Q4_K_M", "Q4_K_S", "Q5_K_XL", "Q5_K_L", "Q5_K_M", "Q5_K_S",
311    "Q6_K_XL", "Q6_K_L", "Q8_K_XL", "Q2_K", "Q3_K", "Q4_K", "Q5_K", "Q6_K", "Q4_0", "Q4_1", "Q5_0", "Q5_1", "Q8_0", "MXFP4", "NVFP4", "BF16", "F16",
312    "F32",
313];
314
315/// The quantization in a GGUF file name (`Qwen3-8B-Q4_K_M.gguf` is `Q4_K_M`), if it names one.
316pub fn quant_of(name: &str) -> Option<String> {
317    let file = name.rsplit('/').next().unwrap_or(name).to_ascii_uppercase();
318    let stem = file.strip_suffix(".GGUF").unwrap_or(&file);
319    let bounded = |at: usize, len: usize| {
320        let before = stem[..at].chars().next_back();
321        let after = stem[at + len..].chars().next();
322        before.is_none_or(|c| !c.is_ascii_alphanumeric()) && after.is_none_or(|c| !c.is_ascii_alphanumeric())
323    };
324    QUANTS.iter().find(|q| stem.match_indices(**q).any(|(at, _)| bounded(at, q.len()))).map(|q| q.to_string())
325}
326
327/// Groups GGUF files into models: split parts together (ordered), single files alone. Sorted
328/// by size, smallest first.
329pub fn group_files(files: &[RepoFile]) -> Vec<RepoModel> {
330    let mut singles = Vec::new();
331    let mut splits: std::collections::BTreeMap<(String, u32), Vec<(u32, RepoFile)>> = Default::default();
332    for f in files {
333        match split_part(&f.name) {
334            Some((base, part, of)) => {
335                let dir = f.name.rsplit_once('/').map(|(d, _)| format!("{d}/")).unwrap_or_default();
336                splits.entry((format!("{dir}{base}"), of)).or_default().push((part, f.clone()));
337            }
338            None => singles.push(f.clone()),
339        }
340    }
341    let mut out: Vec<RepoModel> = singles
342        .into_iter()
343        .map(|f| {
344            let file = f.name.rsplit('/').next().unwrap_or(&f.name);
345            let id = file.strip_suffix(".gguf").or_else(|| file.strip_suffix(".GGUF")).unwrap_or(file).to_string();
346            RepoModel { id, quant: quant_of(&f.name), size: f.size, parts: vec![f], complete: true }
347        })
348        .collect();
349    for ((path, of), mut parts) in splits {
350        parts.sort_by_key(|(n, _)| *n);
351        parts.dedup_by_key(|(n, _)| *n);
352        let complete = parts.len() as u32 == of && parts[0].0 == 1;
353        let id = path.rsplit('/').next().unwrap_or(&path).to_string();
354        let parts: Vec<RepoFile> = parts.into_iter().map(|(_, f)| f).collect();
355        let size = parts.iter().map(|p| p.size).sum();
356        out.push(RepoModel { id, quant: quant_of(&format!("{path}.gguf")), size, parts, complete });
357    }
358    out.sort_by(|a, b| a.size.cmp(&b.size).then_with(|| a.id.cmp(&b.id)));
359    out
360}
361
362/// A Hub client: the base URL and this node's token.
363#[derive(Debug, Clone, PartialEq, Eq)]
364pub struct Hub {
365    url: String,
366    token: Option<HfToken>,
367}
368
369impl Hub {
370    /// The Hub at `url` (such as [`HUB`](crate::store::HUB) or a mirror), without a token.
371    pub fn new(url: impl Into<String>) -> Self {
372        Self { url: url.into().trim_end_matches('/').to_string(), token: None }
373    }
374
375    /// Sends `token` with requests (gated and private repos).
376    pub fn with_token(mut self, token: Option<HfToken>) -> Self {
377        self.token = token;
378        self
379    }
380
381    pub fn url(&self) -> &str {
382        &self.url
383    }
384
385    pub fn has_token(&self) -> bool {
386        self.token.is_some()
387    }
388
389    pub(crate) fn agent() -> ureq::Agent {
390        ureq::Agent::config_builder().http_status_as_error(false).redirect_auth_headers(ureq::config::RedirectAuthHeaders::SameHost).build().into()
391    }
392
393    pub(crate) fn get(&self, url: &str) -> ureq::RequestBuilder<ureq::typestate::WithoutBody> {
394        let req = Self::agent().get(url);
395        match &self.token {
396            Some(t) => req.header("Authorization", t.bearer()),
397            None => req,
398        }
399    }
400
401    fn json(&self, req: ureq::RequestBuilder<ureq::typestate::WithoutBody>, what: &str) -> Result<Value> {
402        let mut resp = req.header("Accept", "application/json").call().map_err(|e| Error::Http(e.to_string()))?;
403        match resp.status().as_u16() {
404            200 => {}
405            s @ (401 | 403) => {
406                let hint = if self.token.is_some() { "the token has no access" } else { "it may be gated or private; set HF_TOKEN on this node" };
407                return Err(Error::Http(format!("the Hub answered {s} for {what} ({hint})")));
408            }
409            s => return Err(Error::Http(format!("the Hub answered {s} for {what}"))),
410        }
411        let text = resp.body_mut().read_to_string().map_err(|e| Error::Http(e.to_string()))?;
412        serde_json::from_str(&text).map_err(|e| Error::Http(format!("the Hub's answer is not JSON: {e}")))
413    }
414
415    /// Repos matching the search, most downloaded first.
416    pub fn search(&self, search: &Search) -> Result<Vec<SearchHit>> {
417        let mut req = self
418            .get(&format!("{}/api/models", self.url))
419            .query("search", search.query.trim())
420            .query("sort", "downloads")
421            .query("direction", "-1")
422            .query("limit", search.limit.clamp(1, 100).to_string());
423        if search.gguf_only {
424            req = req.query("filter", "gguf");
425        }
426        let mut hits = parse_search(&self.json(req, "the search")?);
427        if !search.adapters {
428            hits.retain(|h| !h.adapter);
429        }
430        Ok(hits)
431    }
432
433    fn repo_info(&self, repo: &str) -> Result<Value> {
434        check_repo(repo)?;
435        self.json(self.get(&format!("{}/api/models/{repo}?blobs=true", self.url)), repo)
436    }
437
438    /// The GGUF model files of `repo` (see [`repo_files`]). Adapters are still in this list;
439    /// [`Hub::models`] leaves them out.
440    pub fn repo_files(&self, repo: &str) -> Result<Vec<RepoFile>> {
441        Ok(parse_files(&self.repo_info(repo)?))
442    }
443
444    /// The downloadable models of `repo`, split files grouped ([`group_files`]). Adapters are
445    /// left out: a file whose name hints at one ([`adapter_hint`]) has its header read, and is
446    /// dropped when the header says `general.type` = `adapter`.
447    pub fn models(&self, repo: &str) -> Result<Vec<RepoModel>> {
448        let files: Vec<RepoFile> = self
449            .repo_files(repo)?
450            .into_iter()
451            .filter(|f| !(adapter_hint(&f.name) && self.gguf_header(repo, &f.name).is_ok_and(|h| h.kind.is_adapter())))
452            .collect();
453        Ok(group_files(&files))
454    }
455
456    fn header_body(&self, repo: &str, file: &str) -> Result<ureq::http::Response<ureq::Body>> {
457        check_repo(repo)?;
458        check_file(file)?;
459        let url = format!("{}/{repo}/resolve/main/{file}", self.url);
460        let resp = self.get(&url).header("Range", format!("bytes=0-{}", gguf::HEADER_LIMIT - 1)).call().map_err(|e| Error::Http(e.to_string()))?;
461        match resp.status().as_u16() {
462            200 | 206 => Ok(resp),
463            s => Err(Error::Http(format!("the Hub answered {s} for {file}"))),
464        }
465    }
466
467    /// The header of `file` in `repo` (its first [`gguf::HEADER_LIMIT`] bytes at most, through a
468    /// `Range` request), for KV sizing. For a split model pass its first part. Fails on adapters;
469    /// see [`Hub::gguf_header`].
470    pub fn gguf_info(&self, repo: &str, file: &str) -> Result<GgufInfo> {
471        gguf::read_info(self.header_body(repo, file)?.body_mut().as_reader())
472    }
473
474    /// The header of `file` in `repo`, of any kind ([`gguf::read_header`]): whether it is a model
475    /// or an adapter, its architecture and base model.
476    pub fn gguf_header(&self, repo: &str, file: &str) -> Result<GgufHeader> {
477        gguf::read_header(self.header_body(repo, file)?.body_mut().as_reader())
478    }
479
480    /// The LoRA adapters in `repo`: GGUF files whose header says `general.type` = `adapter` and
481    /// `adapter.type` = `lora` (files with an [`adapter_hint`] in the name, or every GGUF when
482    /// the repo's tags mark it as an adapter), and PEFT directories (an `adapter_config.json`
483    /// with `peft_type` LORA next to `adapter_model.safetensors` or `adapter_model.bin`). Sorted
484    /// by id.
485    pub fn adapters(&self, repo: &str) -> Result<Vec<RepoAdapter>> {
486        let v = self.repo_info(repo)?;
487        let all = siblings(&v);
488        let tagged = adapter_tags(&v);
489        let base = tagged_base(&v);
490        let mut out = Vec::new();
491        for f in parse_files(&v).into_iter().filter(|f| tagged || adapter_hint(&f.name)) {
492            let Ok(h) = self.gguf_header(repo, &f.name) else { continue };
493            let gguf::GgufKind::Adapter { alpha, .. } = &h.kind else { continue };
494            if !h.kind.is_lora() {
495                continue;
496            }
497            let file = f.name.rsplit('/').next().unwrap_or(&f.name);
498            let id = file.strip_suffix(".gguf").or_else(|| file.strip_suffix(".GGUF")).unwrap_or(file).to_string();
499            out.push(RepoAdapter {
500                id,
501                format: AdapterFormat::GgufLora,
502                size: f.size,
503                architecture: Some(h.architecture.clone()),
504                base_model: h.base_model.clone().or_else(|| base.clone()),
505                rank: None,
506                alpha: *alpha,
507                files: vec![f],
508            });
509        }
510        for config in all.iter().filter(|f| f.name == "adapter_config.json" || f.name.ends_with("/adapter_config.json")) {
511            let dir = config.name.strip_suffix("adapter_config.json").unwrap_or("");
512            let Some(weights) =
513                ["adapter_model.safetensors", "adapter_model.bin"].iter().find_map(|w| all.iter().find(|f| f.name == format!("{dir}{w}")))
514            else {
515                continue;
516            };
517            check_file(&config.name)?;
518            let Ok(json) = self.json(self.get(&format!("{}/{repo}/resolve/main/{}", self.url, config.name)), &config.name) else { continue };
519            let Some((rank, alpha, peft_base)) = peft_lora(&json) else { continue };
520            let id = match dir.trim_end_matches('/').rsplit('/').next() {
521                Some(d) if !d.is_empty() => d.to_string(),
522                _ => repo.rsplit('/').next().unwrap_or(repo).to_string(),
523            };
524            out.push(RepoAdapter {
525                id,
526                format: AdapterFormat::Peft,
527                size: config.size + weights.size,
528                architecture: None,
529                base_model: peft_base.or_else(|| base.clone()),
530                rank,
531                alpha,
532                files: vec![config.clone(), weights.clone()],
533            });
534        }
535        out.sort_by(|a, b| a.id.cmp(&b.id));
536        Ok(out)
537    }
538}
539
540#[cfg(test)]
541mod tests {
542    use super::*;
543    use crate::testing::MockHub;
544
545    const REPO_JSON: &str = r#"{"id":"o/n","siblings":[
546        {"rfilename":"README.md","size":10},
547        {"rfilename":"m-Q4_0.gguf","size":100,"lfs":{"sha256":"abc"}},
548        {"rfilename":"mmproj-m-BF16.gguf","size":5,"lfs":{"sha256":"d"}},
549        {"rfilename":"mtp-m-Q4_0.gguf","size":6},
550        {"rfilename":"sub/m-Q8_0.GGUF","size":200}]}"#;
551
552    #[test]
553    fn repo_ids_must_look_like_owner_slash_name() {
554        assert!(check_repo("ggml-org/gemma-4-E2B-it-GGUF").is_ok());
555        for bad in ["", "a", "a/b/c", "../x", "a/..", "a b/c", "/x"] {
556            assert!(check_repo(bad).is_err(), "{bad}");
557        }
558    }
559
560    #[test]
561    fn only_model_ggufs_are_listed() {
562        let files = parse_files(&serde_json::from_str(REPO_JSON).unwrap());
563        assert_eq!(files.iter().map(|f| f.name.as_str()).collect::<Vec<_>>(), ["m-Q4_0.gguf", "sub/m-Q8_0.GGUF"]);
564        assert_eq!(files[0].sha256.as_deref(), Some("abc"));
565        assert_eq!(files[1].sha256, None);
566        let spec = ModelSpec::from_repo_file("o/n", &files[1]).unwrap();
567        assert_eq!((spec.id.as_str(), spec.file.as_str(), spec.size), ("m-Q8_0", "sub/m-Q8_0.GGUF", 200));
568    }
569
570    #[test]
571    fn a_repo_with_a_draft_model_and_an_importance_matrix_lists_only_the_models() {
572        // caveman-so/caveling-2-mini-GGUF (sizes and hashes from the Hub, 2026-12-02).
573        let json = r#"{"id":"caveman-so/caveling-2-mini-GGUF","siblings":[
574            {"rfilename":".gitattributes","size":1902},
575            {"rfilename":"Caveling-2-Mini-NVFP4.gguf","size":18233040256,"lfs":{"sha256":"ee853ce261856ba163a3a7b57712fb6c0302065257ed4359fbe1856979126117"}},
576            {"rfilename":"Caveling-2-Mini-Q4_K_M.gguf","size":18398579616,"lfs":{"sha256":"aab63d16dac44b32f57d53aa1982e9f18f130b88b992c10539f24feee87cd254"}},
577            {"rfilename":"dspark-Caveling-2-Mini-Q8_0.gguf","size":404128928,"lfs":{"sha256":"a042ef0a944da93159ca28a31537098a80421e26dff6de577598bec08182ea87"}},
578            {"rfilename":"imatrix.gguf","size":90752032,"lfs":{"sha256":"2c1fcde64556de9d2324798270c4b32ffcbc2f47e35cb0b8974b51971d4331fa"}},
579            {"rfilename":"mmproj-Caveling-2-Mini-BF16.gguf","size":641806400},
580            {"rfilename":"mmproj-Caveling-2-Mini-Q8_0.gguf","size":345911360}]}"#;
581        let files = parse_files(&serde_json::from_str(json).unwrap());
582        let models = group_files(&files);
583        let named: Vec<_> = models.iter().map(|m| (m.id.as_str(), m.quant.as_deref())).collect();
584        // The smallest file is no longer the 386 MiB drafter.
585        assert_eq!(named, [("Caveling-2-Mini-NVFP4", Some("NVFP4")), ("Caveling-2-Mini-Q4_K_M", Some("Q4_K_M"))]);
586        assert_eq!(quant_of("m-nvfp4.gguf").as_deref(), Some("NVFP4"));
587    }
588
589    #[test]
590    fn file_names_stay_inside_the_repo() {
591        for ok in ["m.gguf", "Q4_K_M/m-00001-of-00002.gguf"] {
592            assert!(check_file(ok).is_ok(), "{ok}");
593        }
594        for bad in ["", "/m.gguf", "../m.gguf", "a/../m.gguf", "a//m.gguf", "a\\m.gguf", "C:m.gguf", "./m.gguf"] {
595            assert!(check_file(bad).is_err(), "{bad}");
596        }
597    }
598
599    #[test]
600    fn quants_come_from_file_names() {
601        assert_eq!(quant_of("Qwen3-8B-Q4_K_M.gguf").as_deref(), Some("Q4_K_M"));
602        assert_eq!(quant_of("gpt-oss-20b-MXFP4.gguf").as_deref(), Some("MXFP4"));
603        assert_eq!(quant_of("Q8_0/Big-Q8_0-00001-of-00002.gguf").as_deref(), Some("Q8_0"));
604        assert_eq!(quant_of("m-UD-Q4_K_XL.gguf").as_deref(), Some("Q4_K_XL"));
605        assert_eq!(quant_of("m-iq4_xs.gguf").as_deref(), Some("IQ4_XS"));
606        assert_eq!(quant_of("m-bf16.gguf").as_deref(), Some("BF16"));
607        assert_eq!(quant_of("model.gguf"), None);
608        assert_eq!(quant_of("XQ4_0Y.gguf"), None);
609    }
610
611    fn rf(name: &str, size: u64) -> RepoFile {
612        RepoFile { name: name.into(), size, sha256: None }
613    }
614
615    #[test]
616    fn split_files_group_into_one_model() {
617        assert_eq!(split_part("d/m-Q4_K_M-00002-of-00003.gguf"), Some(("m-Q4_K_M", 2, 3)));
618        assert_eq!(split_part("m-00004-of-00003.gguf"), None);
619        assert_eq!(split_part("m-1-of-3.gguf"), None);
620        let files = vec![
621            rf("Q8_0/m-Q8_0-00002-of-00002.gguf", 20),
622            rf("m-Q4_K_M.gguf", 10),
623            rf("Q8_0/m-Q8_0-00001-of-00002.gguf", 25),
624            rf("BF16/m-BF16-00001-of-00003.gguf", 30),
625            rf("BF16/m-BF16-00003-of-00003.gguf", 30),
626        ];
627        let models = group_files(&files);
628        assert_eq!(
629            models.iter().map(|m| (m.id.as_str(), m.size, m.complete)).collect::<Vec<_>>(),
630            [("m-Q4_K_M", 10, true), ("m-Q8_0", 45, true), ("m-BF16", 60, false)]
631        );
632        let q8 = &models[1];
633        assert!(q8.is_split());
634        assert_eq!(q8.first().name, "Q8_0/m-Q8_0-00001-of-00002.gguf");
635        assert_eq!(q8.quant.as_deref(), Some("Q8_0"));
636        let specs = q8.specs("o/n").unwrap();
637        assert_eq!(
638            specs.iter().map(|s| (s.id.as_str(), s.file.as_str())).collect::<Vec<_>>(),
639            [("m-Q8_0", "Q8_0/m-Q8_0-00001-of-00002.gguf"), ("m-Q8_0", "Q8_0/m-Q8_0-00002-of-00002.gguf")]
640        );
641        let mut bad = q8.clone();
642        bad.parts[1].name = "../x.gguf".into();
643        assert!(bad.specs("o/n").is_err());
644    }
645
646    const SEARCH_JSON: &str = r#"[
647        {"id":"o/a-GGUF","downloads":50,"likes":3,"gated":false,"pipeline_tag":"text-generation","lastModified":"2026-11-01T00:00:00.000Z"},
648        {"id":"o/b-GGUF","downloads":7,"gated":"manual"},
649        {"id":"../bad","downloads":1}]"#;
650
651    #[test]
652    fn searches_send_the_query_and_the_token() {
653        let hub = MockHub::start_with(vec![("/api/models".into(), "application/json", SEARCH_JSON.as_bytes().to_vec())]);
654        let client = Hub::new(hub.url()).with_token(HfToken::new("hf_x"));
655        let hits = client.search(&Search::new("qwen 3").with_limit(500)).unwrap();
656        assert_eq!(hits.iter().map(|h| (h.id.as_str(), h.downloads, h.gated)).collect::<Vec<_>>(), [("o/a-GGUF", 50, false), ("o/b-GGUF", 7, true)]);
657        assert_eq!(hits[0].pipeline_tag.as_deref(), Some("text-generation"));
658        let seen = hub.seen();
659        let path = &seen[0].path;
660        assert!(
661            path.contains("search=qwen") && path.contains("filter=gguf") && path.contains("limit=100") && path.contains("sort=downloads"),
662            "{path}"
663        );
664        assert_eq!(seen[0].auth.as_deref(), Some("Bearer hf_x"));
665        Hub::new(hub.url()).search(&Search::new("q").with_gguf_only(false)).unwrap();
666        let seen = hub.seen();
667        assert!(!seen[1].path.contains("filter=gguf"));
668        assert_eq!(seen[1].auth, None, "no token, no header");
669    }
670
671    #[test]
672    fn missing_repos_report_the_status() {
673        let hub = MockHub::start_with(vec![]);
674        let err = Hub::new(hub.url()).repo_files("o/n").unwrap_err();
675        assert!(err.to_string().contains("404"), "{err}");
676    }
677
678    #[test]
679    fn reads_a_header_with_a_range_request() {
680        let mut body = crate::gguf::header(&[
681            ("general.architecture", serde_json::json!("llama")),
682            ("llama.block_count", serde_json::json!(2)),
683            ("llama.attention.head_count", serde_json::json!(4)),
684            ("llama.attention.head_count_kv", serde_json::json!(2)),
685            ("llama.attention.key_length", serde_json::json!(16)),
686        ]);
687        body.extend(vec![0u8; 1000]);
688        let hub = MockHub::start("/o/n/resolve/main/d/m.gguf", body);
689        let info = Hub::new(hub.url()).gguf_info("o/n", "d/m.gguf").unwrap();
690        assert_eq!(info.kv_bytes_per_token(), 2 * 2 * 32 * 2);
691        assert_eq!(hub.last_range().as_deref(), Some("bytes=0-67108863"));
692        assert!(Hub::new(hub.url()).gguf_info("o/n", "../m.gguf").is_err());
693    }
694
695    #[test]
696    fn reads_a_repo_from_the_hub_api() {
697        let hub = MockHub::start_with(vec![("/api/models/o/n".into(), "application/json", REPO_JSON.as_bytes().to_vec())]);
698        assert_eq!(repo_files(hub.url(), "o/n").unwrap().len(), 2);
699        assert!(matches!(repo_files(hub.url(), "o/missing"), Err(Error::Http(ref m)) if m.contains("404")));
700        assert!(matches!(repo_files(hub.url(), "bad"), Err(Error::BadRepo(_))));
701    }
702
703    #[test]
704    fn adapter_hints_are_whole_words() {
705        for yes in ["m-LoRA-F16.gguf", "d/qwen3_lora.gguf", "tune-adapter.gguf", "x.QLoRA.gguf"] {
706            assert!(adapter_hint(yes), "{yes}");
707        }
708        for no in ["Flora-7B-Q4_0.gguf", "explorer.gguf", "m-Q4_0.gguf", "lorax.gguf"] {
709            assert!(!adapter_hint(no), "{no}");
710        }
711    }
712
713    #[test]
714    fn models_leave_adapters_out_and_adapters_finds_them() {
715        let hub = crate::testing::adapter_hub();
716        let client = Hub::new(hub.url());
717        assert_eq!(client.repo_files("o/n").unwrap().len(), 2, "the raw list still has both GGUFs");
718        let models = client.models("o/n").unwrap();
719        assert_eq!(models.iter().map(|m| m.id.as_str()).collect::<Vec<_>>(), ["m-Q4_0"]);
720        let header = client.gguf_header("o/n", "m-LoRA-F16.gguf").unwrap();
721        assert!(header.kind.is_lora());
722        assert!(client.gguf_info("o/n", "m-LoRA-F16.gguf").is_err(), "an adapter has no KV shape");
723        assert_eq!(client.gguf_header("o/n", "m-Q4_0.gguf").unwrap().info.map(|i| i.layers), Some(2));
724
725        let found = client.adapters("o/n").unwrap();
726        assert_eq!(found.len(), 2, "{found:?}");
727        let (gguf, peft) = (&found[0], &found[1]);
728        assert_eq!((gguf.id.as_str(), gguf.format, gguf.size), ("m-LoRA-F16", AdapterFormat::GgufLora, 1500));
729        assert_eq!(
730            (gguf.architecture.as_deref(), gguf.base_model.as_deref(), gguf.alpha, gguf.rank),
731            (Some("qwen3"), Some("Org/Base-8B"), Some(32.5), None)
732        );
733        assert_eq!((peft.id.as_str(), peft.format, peft.rank, peft.alpha), ("tune", AdapterFormat::Peft, Some(16), Some(32.0)));
734        assert_eq!(peft.files.iter().map(|f| f.name.as_str()).collect::<Vec<_>>(), ["tune/adapter_config.json", "tune/adapter_model.safetensors"]);
735        assert_eq!(peft.base_model.as_deref(), Some("Org/Base-8B"));
736
737        let root = client.adapters("o/peft").unwrap();
738        assert_eq!(root.len(), 1);
739        assert_eq!((root[0].id.as_str(), root[0].rank), ("peft", Some(8)));
740        assert_eq!(root[0].base_model.as_deref(), Some("Org/Base-8B"), "a local base path is ignored; the tag names the base");
741        assert!(client.models("o/peft").unwrap().is_empty());
742    }
743
744    #[test]
745    fn searches_leave_adapter_repos_out_unless_asked() {
746        let body = r#"[{"id":"o/m-GGUF","tags":["gguf"]},{"id":"o/tune","library_name":"peft","tags":["peft"]},
747            {"id":"o/lora-GGUF","tags":["gguf","base_model:adapter:Org/Base-8B"]}]"#;
748        let hub = MockHub::start_with(vec![("/api/models".into(), "application/json", body.as_bytes().to_vec())]);
749        let client = Hub::new(hub.url());
750        let hits = client.search(&Search::new("x")).unwrap();
751        assert_eq!(hits.iter().map(|h| h.id.as_str()).collect::<Vec<_>>(), ["o/m-GGUF"]);
752        let all = client.search(&Search::new("x").with_adapters(true)).unwrap();
753        assert_eq!(
754            all.iter().map(|h| (h.id.as_str(), h.adapter)).collect::<Vec<_>>(),
755            [("o/m-GGUF", false), ("o/tune", true), ("o/lora-GGUF", true)]
756        );
757    }
758
759    /// The real Hub: `cargo test -- --ignored live_hub` (reads a few MB of one header).
760    #[test]
761    #[ignore = "uses the network"]
762    fn live_hub() {
763        let hub = Hub::new(crate::store::HUB).with_token(HfToken::from_env());
764        let hits = hub.search(&Search::new("Qwen3-0.6B").with_limit(5)).unwrap();
765        assert!(!hits.is_empty());
766        let models = hub.models("ggml-org/gemma-4-E2B-it-GGUF").unwrap();
767        let q4 = models.iter().find(|m| m.quant.as_deref() == Some("Q4_0")).expect("a Q4_0 file");
768        let info = hub.gguf_info("ggml-org/gemma-4-E2B-it-GGUF", &q4.first().name).unwrap();
769        assert!(info.layers > 0 && info.kv_bytes_per_token() > 0, "{info:?}");
770        let fit = crate::fit::choose(
771            &models,
772            &crate::hw::Budget { pool_bytes: 0, reserve_bytes: 0, usable_bytes: 8 << 30 },
773            &crate::fit::FitOptions::default().with_info(&info),
774        );
775        assert!(fit.is_some());
776        eprintln!("{} hits; {} models; {info:?}; best {:?}", hits.len(), models.len(), fit.map(|f| (f.model.id, f.footprint)));
777    }
778}