Download code/tt_raon/weights/cache.py from changh95/Raon-Speech-9B: direct link, hf CLI and curl.
- Browser
- Download file 3.42 kB
-
https://huggingface.co/changh95/Raon-Speech-9B/resolve/main/code/tt_raon/weights/cache.py
- Command line
-
hf download hf://changh95/Raon-Speech-9B/code/tt_raon/weights/cache.py
-
curl -L -o cache.py https://huggingface.co/changh95/Raon-Speech-9B/resolve/main/code/tt_raon/weights/cache.py
3.42 kB
| # SPDX-License-Identifier: Apache-2.0 | |
| """On-disk cache of converted weights / tables / packed streams (``config.cache_root()``: ``RAON_CACHE_DIR``, else | |
| ``TT_DIT_CACHE_DIR``, else ``~/.cache/tt_raon``). | |
| t = cached_tensors("oad", ["rvq_tables", ck.source_id], lambda: {"tables": build()}) # safetensors | |
| a = cached_arrays("mk_thinker", ["streams", ck.source_id, recipe], lambda: {"w00_A": np_array, ...}) # .npy dir | |
| Entries are keyed by ``sha1("|".join(parts))[:16]`` under ``<root>/<stage>/``; writes are atomic (temp name, then | |
| ``os.replace``), so concurrent builders at worst duplicate work. ``.npy`` entries are returned memory-mapped. | |
| """ | |
| from __future__ import annotations | |
| import hashlib | |
| import os | |
| import shutil | |
| import time | |
| from typing import Callable, Dict, Iterable, Optional | |
| from ..config import cache_root as _root | |
| LAYOUT = "raon-cache-v1" | |
| def cache_root() -> str: | |
| return _root() | |
| def cache_key(parts: Iterable[object]) -> str: | |
| s = "|".join([LAYOUT] + [repr(p) if not isinstance(p, str) else p for p in parts]) | |
| return hashlib.sha1(s.encode()).hexdigest()[:16] | |
| def entry_path(stage: str, parts: Iterable[object], ext: str = ".safetensors") -> str: | |
| return os.path.join(cache_root(), stage, cache_key(parts) + ext) | |
| def cached_tensors(stage: str, parts: Iterable[object], builder: Callable[[], Dict[str, object]], | |
| use_cache: bool = True, log: Optional[Callable[[str], None]] = None) -> Dict[str, object]: | |
| """dict of torch tensors, stored as one safetensors file.""" | |
| from safetensors.torch import load_file, save_file | |
| parts = list(parts) | |
| path = entry_path(stage, parts) | |
| if use_cache and os.path.exists(path): | |
| return load_file(path) | |
| t0 = time.time() | |
| out = builder() | |
| if use_cache: | |
| os.makedirs(os.path.dirname(path), exist_ok=True) | |
| tmp = f"{path}.tmp{os.getpid()}" | |
| save_file({k: v.contiguous() for k, v in out.items()}, tmp, metadata={"parts": "|".join(map(str, parts))}) | |
| os.replace(tmp, path) | |
| if log: | |
| log(f"[cache] {stage}/{os.path.basename(path)} built in {time.time() - t0:.1f}s") | |
| return out | |
| def cached_arrays(stage: str, parts: Iterable[object], builder: Callable[[], Dict[str, object]], | |
| use_cache: bool = True, log: Optional[Callable[[str], None]] = None) -> Dict[str, object]: | |
| """dict of numpy arrays, stored as a directory of .npy files (returned memory-mapped).""" | |
| import numpy as np | |
| parts = list(parts) | |
| path = entry_path(stage, parts, ext="") | |
| done = os.path.join(path, ".complete") | |
| if use_cache and os.path.exists(done): | |
| return {f[:-4]: np.load(os.path.join(path, f), mmap_mode="r") for f in sorted(os.listdir(path)) | |
| if f.endswith(".npy")} | |
| t0 = time.time() | |
| out = builder() | |
| if use_cache: | |
| tmp = f"{path}.tmp{os.getpid()}" | |
| shutil.rmtree(tmp, ignore_errors=True) | |
| os.makedirs(tmp, exist_ok=True) | |
| for k, v in out.items(): | |
| np.save(os.path.join(tmp, f"{k}.npy"), np.ascontiguousarray(v)) | |
| with open(os.path.join(tmp, ".complete"), "w") as f: | |
| f.write("|".join(map(str, parts))) | |
| if os.path.exists(path): | |
| shutil.rmtree(path, ignore_errors=True) | |
| os.replace(tmp, path) | |
| if log: | |
| log(f"[cache] {stage}/{os.path.basename(path)} built in {time.time() - t0:.1f}s") | |
| return out | |