Download code/tt_raon/weights/source.py from changh95/Raon-Speech-9B: direct link, hf CLI and curl.
- Browser
- Download file 4.74 kB
-
https://huggingface.co/changh95/Raon-Speech-9B/resolve/main/code/tt_raon/weights/source.py
- Command line
-
hf download hf://changh95/Raon-Speech-9B/code/tt_raon/weights/source.py
-
curl -L -o source.py https://huggingface.co/changh95/Raon-Speech-9B/resolve/main/code/tt_raon/weights/source.py
4.74 kB
| # SPDX-License-Identifier: Apache-2.0 | |
| """Lazy access to the Raon-Speech-9B checkpoint (4 bf16 safetensors shards + index) and the ECAPA checkpoint. | |
| ck = Checkpoint() # RAON_MODEL_DIR, else the pinned commit (HF cache) | |
| w = ck.get("text_model.layers.0.self_attn.q_proj.weight") # torch tensor, dtype as stored (bf16) | |
| e = ck.rows("text_model.embed_tokens.weight", [151644, 872]) # [2, 4096] rows without loading the table | |
| ck.source_id # cache key: sha256 of the index + shard sizes (16 hex) | |
| Shards are memory-mapped by safetensors (one open handle per shard, kept); nothing is converted unless asked | |
| (``get(name, dtype=torch.float32)``). Never executes code from the snapshot (configs are read as JSON data). | |
| """ | |
| from __future__ import annotations | |
| import hashlib | |
| import json | |
| import os | |
| import threading | |
| from typing import Dict, Iterable, List, Optional | |
| from ..config import resolve_weights | |
| class Checkpoint: | |
| def __init__(self, model_dir: Optional[str] = None): | |
| self.dir = model_dir or resolve_weights("raon") | |
| with open(os.path.join(self.dir, "model.safetensors.index.json")) as f: | |
| self.index: Dict[str, str] = json.load(f)["weight_map"] | |
| with open(os.path.join(self.dir, "config.json")) as f: | |
| self.config = json.load(f) | |
| self._handles: Dict[str, object] = {} | |
| self._lock = threading.Lock() | |
| self._source_id: Optional[str] = None | |
| # ------------------------------------------------------------------ identity | |
| def source_id(self) -> str: | |
| if self._source_id is None: | |
| h = hashlib.sha256() | |
| with open(os.path.join(self.dir, "model.safetensors.index.json"), "rb") as f: | |
| h.update(f.read()) | |
| for shard in sorted(set(self.index.values())): | |
| h.update(f"{shard}:{os.path.getsize(os.path.join(self.dir, shard))}".encode()) | |
| self._source_id = h.hexdigest()[:16] | |
| return self._source_id | |
| # ------------------------------------------------------------------ access | |
| def _handle(self, shard: str): | |
| with self._lock: | |
| h = self._handles.get(shard) | |
| if h is None: | |
| from safetensors import safe_open | |
| h = self._handles[shard] = safe_open(os.path.join(self.dir, shard), framework="pt") | |
| return h | |
| def __contains__(self, name: str) -> bool: | |
| return name in self.index | |
| def names(self, prefix: str = "") -> List[str]: | |
| return sorted(k for k in self.index if k.startswith(prefix)) | |
| def shape(self, name: str) -> List[int]: | |
| return list(self._handle(self.index[name]).get_slice(name).get_shape()) | |
| def get(self, name: str, dtype=None): | |
| """Tensor ``name`` (as stored, or converted to ``dtype``).""" | |
| if name not in self.index: | |
| raise KeyError(f"{name} not in the checkpoint") | |
| t = self._handle(self.index[name]).get_tensor(name) | |
| return t if dtype is None else t.to(dtype) | |
| def get_many(self, names: Iterable[str], dtype=None, strip: str = "") -> Dict[str, object]: | |
| return {n[len(strip):] if strip and n.startswith(strip) else n: self.get(n, dtype) for n in names} | |
| def prefix(self, prefix: str, dtype=None) -> Dict[str, object]: | |
| """Every tensor under ``prefix`` with the prefix stripped from the names.""" | |
| return self.get_many(self.names(prefix), dtype, strip=prefix) | |
| def rows(self, name: str, ids, dtype=None): | |
| """Rows ``ids`` of a 2-D tensor without materializing it (embedding gathers on the host).""" | |
| import torch | |
| sl = self._handle(self.index[name]).get_slice(name) | |
| out = torch.stack([sl[int(i):int(i) + 1][0] for i in ids]) if len(ids) else torch.zeros( | |
| 0, self.shape(name)[1], dtype=torch.bfloat16) | |
| return out if dtype is None else out.to(dtype) | |
| def close(self) -> None: | |
| self._handles.clear() | |
| def ecapa_state_dict(ecapa_dir: Optional[str] = None): | |
| """speechbrain ECAPA ``embedding_model.ckpt`` (``torch.load(weights_only=True)``, untrusted download).""" | |
| import torch | |
| import hashlib | |
| from ..config import ECAPA_SHA256 | |
| d = ecapa_dir or resolve_weights("ecapa") | |
| path = os.path.join(d, "embedding_model.ckpt") | |
| with open(path, "rb") as f: | |
| digest = hashlib.sha256(f.read()).hexdigest() | |
| if digest != ECAPA_SHA256: # the pinned commit's file; anything else is refused before unpickling | |
| raise ValueError(f"{path}: sha256 {digest[:16]}... is not the pinned ECAPA checkpoint ({ECAPA_SHA256[:16]}...)") | |
| return torch.load(path, map_location="cpu", weights_only=True) | |