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