Skip to content

Commit ca58c6d

Browse files
voidstackloopclaude
andcommitted
hub: from_pretrained-style snapshot cache (curl), sharded safetensors index loading, path-traversal guards
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
1 parent 0a33653 commit ca58c6d

2 files changed

Lines changed: 170 additions & 0 deletions

File tree

‎crates/oxideon-core/src/hub.rs‎

Lines changed: 169 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,169 @@
1+
//! `from_pretrained`-style model loading: resolve a Hugging Face repo (or a local directory) to files on disk, and read
2+
//! (sharded) safetensors weights from it.
3+
//!
4+
//! The crate has no HTTP dependency, so downloads shell out to the system `curl` (present on Windows 10+, macOS and
5+
//! practically every Linux). Files are cached under `$OXIDEON_HOME/hub` (default `~/.cache/oxideon/hub`) and never
6+
//! re-downloaded. `HF_TOKEN` is sent as a bearer token when set; `HF_ENDPOINT` overrides `https://huggingface.co`.
7+
//!
8+
//! ```no_run
9+
//! # use oxideon_core::hub;
10+
//! let dir = hub::snapshot("org/model", "main", &["config.json", "model.safetensors"]).unwrap();
11+
//! let weights = hub::load_weights(&dir).unwrap();
12+
//! ```
13+
14+
use crate::error::{Error, Result};
15+
use crate::tensor::Tensor;
16+
use std::collections::HashMap;
17+
use std::path::{Path, PathBuf};
18+
19+
fn err(m: impl Into<String>) -> Error {
20+
Error::Msg(format!("hub: {}", m.into()))
21+
}
22+
23+
/// Root of the download cache.
24+
pub fn cache_dir() -> PathBuf {
25+
if let Some(p) = std::env::var_os("OXIDEON_HOME") {
26+
return PathBuf::from(p).join("hub");
27+
}
28+
let home = std::env::var_os("USERPROFILE").or_else(|| std::env::var_os("HOME")).map(PathBuf::from).unwrap_or_else(std::env::temp_dir);
29+
home.join(".cache").join("oxideon").join("hub")
30+
}
31+
32+
fn safe_component(s: &str) -> Result<()> {
33+
if s.is_empty() || s.contains("..") || s.starts_with('/') || s.starts_with('\\') || s.contains(':') {
34+
return Err(err(format!("unsafe path component {s:?}")));
35+
}
36+
Ok(())
37+
}
38+
39+
/// Downloads `url` to `dest` with `curl` (atomically: written to `<dest>.part`, then renamed).
40+
pub fn download(url: &str, dest: &Path, token: Option<&str>) -> Result<()> {
41+
if let Some(parent) = dest.parent() {
42+
std::fs::create_dir_all(parent).map_err(|e| err(format!("creating {}: {e}", parent.display())))?;
43+
}
44+
let part = PathBuf::from(format!("{}.part", dest.display()));
45+
let mut cmd = std::process::Command::new("curl");
46+
cmd.args(["--fail", "--location", "--silent", "--show-error", "--output"]).arg(&part);
47+
if let Some(t) = token {
48+
cmd.arg("--header").arg(format!("Authorization: Bearer {t}"));
49+
}
50+
cmd.arg(url);
51+
let out = cmd.output().map_err(|e| err(format!("cannot run curl: {e}")))?;
52+
if !out.status.success() {
53+
let _ = std::fs::remove_file(&part);
54+
return Err(err(format!("download of {url} failed: {}", String::from_utf8_lossy(&out.stderr).trim())));
55+
}
56+
std::fs::rename(&part, dest).map_err(|e| err(format!("saving {}: {e}", dest.display())))
57+
}
58+
59+
/// A directory holding `files` of `repo` at `revision`: `repo` may also be an existing local directory, which is
60+
/// returned as is. Missing files are downloaded into the cache; files already there are left alone.
61+
pub fn snapshot(repo: &str, revision: &str, files: &[&str]) -> Result<PathBuf> {
62+
let local = Path::new(repo);
63+
if local.is_dir() {
64+
return Ok(local.to_path_buf());
65+
}
66+
for part in repo.split('/') {
67+
safe_component(part)?;
68+
}
69+
safe_component(revision)?;
70+
let dir = cache_dir().join(repo.replace('/', "--")).join(revision);
71+
let endpoint = std::env::var("HF_ENDPOINT").unwrap_or_else(|_| "https://huggingface.co".into());
72+
let token = std::env::var("HF_TOKEN").ok();
73+
for f in files {
74+
safe_component(f)?;
75+
let dest = dir.join(f);
76+
if !dest.exists() {
77+
download(&format!("{}/{repo}/resolve/{revision}/{f}", endpoint.trim_end_matches('/')), &dest, token.as_deref())?;
78+
}
79+
}
80+
Ok(dir)
81+
}
82+
83+
/// The weight files named by `model.safetensors.index.json` (sharded checkpoints), or the single `model.safetensors`.
84+
pub fn weight_files(dir: &Path) -> Result<Vec<PathBuf>> {
85+
let index = dir.join("model.safetensors.index.json");
86+
if index.exists() {
87+
let text = std::fs::read_to_string(&index).map_err(|e| err(format!("{}: {e}", index.display())))?;
88+
let v = crate::tokenizer::json::Json::parse(&text).map_err(|e| err(format!("bad index json: {e}")))?;
89+
let map = v.get("weight_map").and_then(|m| m.as_object()).ok_or_else(|| err("index has no weight_map"))?;
90+
let mut names: Vec<String> = map.iter().filter_map(|(_, f)| f.as_str().map(str::to_string)).collect();
91+
names.sort();
92+
names.dedup();
93+
for n in &names {
94+
safe_component(n)?;
95+
}
96+
return Ok(names.into_iter().map(|n| dir.join(n)).collect());
97+
}
98+
let single = dir.join("model.safetensors");
99+
if single.exists() {
100+
return Ok(vec![single]);
101+
}
102+
Err(err(format!("no model.safetensors or model.safetensors.index.json in {}", dir.display())))
103+
}
104+
105+
/// Reads every weight in `dir` (single file or shards) into one name → tensor map.
106+
pub fn load_weights(dir: impl AsRef<Path>) -> Result<HashMap<String, Tensor>> {
107+
let mut all = HashMap::new();
108+
for f in weight_files(dir.as_ref())? {
109+
all.extend(crate::serialize::load_safetensors(&f)?);
110+
}
111+
Ok(all)
112+
}
113+
114+
#[cfg(test)]
115+
mod tests {
116+
use super::*;
117+
118+
#[test]
119+
fn sharded_and_single_checkpoints_load_and_unsafe_paths_are_refused() {
120+
let dir = std::env::temp_dir().join("oxideon_hub_test");
121+
let _ = std::fs::remove_dir_all(&dir);
122+
std::fs::create_dir_all(&dir).unwrap();
123+
let a: HashMap<String, Tensor> = [("w1".to_string(), Tensor::from_slice(&[1.0f32, 2.0], &[2]).unwrap())].into();
124+
let b: HashMap<String, Tensor> = [("w2".to_string(), Tensor::from_slice(&[3.0f32], &[1]).unwrap())].into();
125+
crate::serialize::save_safetensors(&a, dir.join("model-00001-of-00002.safetensors")).unwrap();
126+
crate::serialize::save_safetensors(&b, dir.join("model-00002-of-00002.safetensors")).unwrap();
127+
std::fs::write(
128+
dir.join("model.safetensors.index.json"),
129+
r#"{"metadata":{},"weight_map":{"w1":"model-00001-of-00002.safetensors","w2":"model-00002-of-00002.safetensors"}}"#,
130+
)
131+
.unwrap();
132+
let w = load_weights(&dir).unwrap();
133+
assert_eq!(w["w1"].to_vec::<f32>().unwrap(), vec![1.0, 2.0]);
134+
assert_eq!(w["w2"].to_vec::<f32>().unwrap(), vec![3.0]);
135+
// a local directory is its own snapshot
136+
assert_eq!(snapshot(dir.to_str().unwrap(), "main", &[]).unwrap(), dir);
137+
// an index must not point outside the directory
138+
std::fs::write(dir.join("model.safetensors.index.json"), r#"{"weight_map":{"w":"../evil.safetensors"}}"#).unwrap();
139+
assert!(weight_files(&dir).is_err());
140+
assert!(snapshot("../x", "main", &["a"]).is_err());
141+
assert!(snapshot("org/model", "main", &["../../etc/passwd"]).is_err());
142+
let _ = std::fs::remove_dir_all(&dir);
143+
}
144+
145+
#[test]
146+
fn download_works_through_curl_and_is_atomic() {
147+
let dir = std::env::temp_dir().join("oxideon_hub_dl");
148+
let _ = std::fs::remove_dir_all(&dir);
149+
std::fs::create_dir_all(&dir).unwrap();
150+
let src = dir.join("src.txt");
151+
std::fs::write(&src, b"hello").unwrap();
152+
let dest = dir.join("out").join("copy.txt");
153+
let url = format!("file:///{}", src.display().to_string().replace('\\', "/"));
154+
match download(&url, &dest, None) {
155+
Ok(()) => {
156+
assert_eq!(std::fs::read(&dest).unwrap(), b"hello");
157+
assert!(!dir.join("out").join("copy.txt.part").exists());
158+
}
159+
Err(e) if e.to_string().contains("cannot run curl") => {} // curl absent: nothing to test
160+
Err(e) => panic!("{e}"),
161+
}
162+
// a failing download leaves no partial file behind
163+
let bad = dir.join("out").join("missing.txt");
164+
if download("file:///definitely/not/here", &bad, None).is_err() {
165+
assert!(!bad.exists() && !dir.join("out").join("missing.txt.part").exists());
166+
}
167+
let _ = std::fs::remove_dir_all(&dir);
168+
}
169+
}

‎crates/oxideon-core/src/lib.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,7 @@ pub mod signal;
112112
pub mod sparse;
113113
pub mod structured;
114114
pub mod checkpoint;
115+
pub mod hub;
115116
pub mod loader;
116117
pub mod train_loop;
117118
pub mod profiler;

0 commit comments

Comments
 (0)