Jordine's picture
Upload code_extra/xsize/hf_range.py with huggingface_hub
05a48dc verified
Raw History Blame Contribute Delete
8.43 kB
"""Read arbitrary rows of safetensors tensors from a Hugging Face repo via HTTP Range requests.
No full downloads: the safetensors header (8-byte LE length + JSON) is fetched once per shard and cached under
/tmp/xsize_cache; row reads are coalesced into contiguous byte ranges and fetched in parallel.
from xsize.hf_range import Repo
r = Repo("Qwen/Qwen3.5-9B")
name = r.mlp("up_proj", 3) # -> 'model.language_model.layers.3.mlp.up_proj.weight'
X = r.read_rows(name, range(0, 1000)) # float32 [1000, 4096]
HF_TOKEN (env) is sent as a Bearer token; it is never printed or written to disk.
"""
import json, os, re, time, threading
from concurrent.futures import ThreadPoolExecutor
import numpy as np
import requests
CACHE = os.environ.get("XSIZE_CACHE", "/tmp/xsize_cache")
os.makedirs(CACHE, exist_ok=True)
_HDR = {"Authorization": f"Bearer {os.environ['HF_TOKEN']}"} if os.environ.get("HF_TOKEN") else {}
_tls = threading.local()
DTYPES = {"BF16": (2, None), "F16": (2, np.float16), "F32": (4, np.float32)}
SKIP_PREFIX_WORDS = ("visual", "vision", "mtp", "multi_modal", "audio", "image")
class Budget:
def __init__(self):
self.bytes = 0; self.requests = 0; self.lock = threading.Lock()
def add(self, n):
with self.lock:
self.bytes += n; self.requests += 1
BUDGET = Budget()
def _session():
s = getattr(_tls, "s", None)
if s is None:
s = requests.Session(); _tls.s = s
return s
def _get(url, headers=None, tries=6, timeout=120):
h = dict(_HDR); h.update(headers or {})
err = None
for i in range(tries):
try:
r = _session().get(url, headers=h, timeout=timeout, allow_redirects=True)
if r.status_code in (200, 206):
return r
if r.status_code in (401, 403, 404):
raise RuntimeError(f"HTTP {r.status_code} for {url}")
err = RuntimeError(f"HTTP {r.status_code} for {url}")
except (requests.RequestException,) as e:
err = e
time.sleep(min(30, 1.5 * 2 ** i))
raise err
def _range(url, start, end_incl):
r = _get(url, {"Range": f"bytes={start}-{end_incl}"})
data = r.content
want = end_incl - start + 1
if r.status_code == 200: # server ignored Range: refuse silently downloading a whole shard
raise RuntimeError(f"Range ignored for {url}")
if len(data) != want:
raise RuntimeError(f"short read {len(data)} != {want} for {url}")
BUDGET.add(want)
return data
def bf16_to_f32(buf):
u = np.frombuffer(buf, dtype=np.uint16).astype(np.uint32) << 16
return u.view(np.float32)
class Repo:
def __init__(self, repo_id, revision="main"):
self.repo_id, self.revision = repo_id, revision
self.base = f"https://huggingface.co/{repo_id}/resolve/{revision}/"
self._headers = {}
self.weight_map = self._load_index()
self.names = sorted(self.weight_map)
self._config = None
# ---------- metadata ----------
def _cache_path(self, fname):
return os.path.join(CACHE, (self.repo_id + "__" + self.revision + "__" + fname).replace("/", "__"))
def _json_file(self, fname):
p = self._cache_path(fname)
if os.path.exists(p):
return json.load(open(p))
j = _get(self.base + fname).json()
json.dump(j, open(p, "w"))
return j
def _load_index(self):
try:
return self._json_file("model.safetensors.index.json")["weight_map"]
except RuntimeError:
h = self.header("model.safetensors")
return {k: "model.safetensors" for k in h if k != "__metadata__"}
@property
def config(self):
if self._config is None:
c = self._json_file("config.json")
self._config = c.get("text_config", c)
self._config["_root"] = c
return self._config
def header(self, fname):
if fname in self._headers:
return self._headers[fname]
p = self._cache_path(fname + ".header.json")
if os.path.exists(p):
h = json.load(open(p))
else:
url = self.base + fname
first = _range(url, 0, 262143)
n = int.from_bytes(first[:8], "little")
raw = first[8:8 + n] if n + 8 <= len(first) else first[8:] + _range(url, len(first), 8 + n - 1)
h = json.loads(raw.decode("utf-8"))
h["__data_start__"] = 8 + n
json.dump(h, open(p, "w"))
self._headers[fname] = h
return h
def info(self, name):
f = self.weight_map[name]
h = self.header(f)
t = h[name]
return f, t["dtype"], t["shape"], h["__data_start__"] + t["data_offsets"][0]
def shape(self, name):
return self.info(name)[2]
# ---------- name discovery ----------
def _text_names(self):
return [n for n in self.names if not any(p.startswith(SKIP_PREFIX_WORDS) for p in n.split("."))]
def embed(self):
c = [n for n in self._text_names() if n.endswith("embed_tokens.weight")]
if len(c) != 1:
c = [n for n in self._text_names() if re.search(r"(embed_tokens|wte|word_embeddings)\.weight$", n)]
assert len(c) == 1, (self.repo_id, c)
return c[0]
def mlp(self, proj, layer):
pat = re.compile(rf"(^|\.)layers\.{layer}\.mlp\.{proj}\.weight$")
c = [n for n in self._text_names() if pat.search(n)]
assert len(c) == 1, (self.repo_id, proj, layer, c)
return c[0]
def up(self, layer):
"""(tensor name, row offset, n_neurons, d_model) of the MLP up projection; handles fused gate_up_proj
(Phi-3/4 layout: rows [0, I) = gate, rows [I, 2I) = up)."""
try:
n = self.mlp("up_proj", layer); I, d = self.shape(n); return n, 0, I, d
except AssertionError:
n = self.mlp("gate_up_proj", layer); I2, d = self.shape(n); return n, I2 // 2, I2 // 2, d
def read_up(self, layer, rows):
n, off, I, d = self.up(layer)
return self.read_rows(n, np.asarray(rows) + off)
def n_layers(self):
return int(self.config["num_hidden_layers"])
# ---------- data ----------
def read_rows(self, name, rows, max_gap_bytes=262144, chunk_bytes=16 << 20, workers=16):
"""Return float32 array [len(rows), ncols] in the order of `rows` (duplicates allowed)."""
f, dt, shape, off = self.info(name)
if len(shape) == 1:
shape = [shape[0], 1]
R, C = shape[0], int(np.prod(shape[1:]))
isz, npdt = DTYPES[dt]
rb = C * isz
rows = np.asarray(list(rows), dtype=np.int64)
assert rows.min() >= 0 and rows.max() < R, (name, rows.min(), rows.max(), R)
uniq = np.unique(rows)
# coalesce into runs [a, b) allowing small gaps
gap_rows = max(0, max_gap_bytes // rb)
runs, a, b = [], uniq[0], uniq[0] + 1
for r in uniq[1:]:
if r - b <= gap_rows and (r + 1 - a) * rb <= chunk_bytes:
b = r + 1
else:
runs.append((a, b)); a, b = r, r + 1
runs.append((a, b))
url = self.base + f
def fetch(run):
a, b = run
return run, _range(url, off + a * rb, off + b * rb - 1)
out = {}
with ThreadPoolExecutor(workers) as ex:
for (a, b), buf in ex.map(fetch, runs):
arr = bf16_to_f32(buf) if dt == "BF16" else np.frombuffer(buf, dtype=npdt).astype(np.float32)
arr = arr.reshape(b - a, C)
out[(a, b)] = arr
starts = np.array([r[0] for r in runs]); ends = np.array([r[1] for r in runs])
idx = np.searchsorted(starts, rows, side="right") - 1
res = np.empty((len(rows), C), dtype=np.float32)
for k, (r, i) in enumerate(zip(rows, idx)):
res[k] = out[(starts[i], ends[i])][r - starts[i]]
return res
def block_indices(n_total, n_want, block, rng, lo=0):
"""n_want indices from [lo, n_total) as non-overlapping contiguous blocks of `block` (cheap to range-read)."""
nb = max(1, n_want // block)
span = n_total - lo
if span <= n_want:
return np.arange(lo, n_total)
slots = span // block
pick = np.sort(rng.choice(slots, size=min(nb, slots), replace=False))
return np.concatenate([lo + np.arange(p * block, p * block + block) for p in pick])