GGUFGuy's picture
Duplicate from GGUFGuy/hyperdex-trainer
2a49d9a
Raw History Blame Contribute Delete
8.77 kB
"""
Durable storage on a Hugging Face bucket.
A Space's container filesystem dies on every rebuild, restart and garbage
collection, which would otherwise mean losing every model, every loss curve and
the whole 1.5B-token cache each time the code changes. This module mirrors the
three things worth keeping into a bucket:
cache/tokens.u16 + cache/tokens.meta the shared fineweb-edu token cache
runs/<job_id>/meta.json the job row, its metrics and logs
runs/<job_id>/<weights, tokenizer, …> the finished checkpoint
The design is deliberately append-only and keyed by job id: a finished run is
written once and never mutated. That removes every concurrency problem a rolling
deploy would otherwise create, because two containers never contend for the same
object — unlike syncing one shared SQLite file, where the last writer would
silently clobber the other.
On boot the local database is rebuilt from the run metadata in the bucket.
Checkpoints are pulled on demand, the first time someone opens or publishes a
model, so startup stays fast.
Runs that were in flight when a container died are NOT recoverable — the
optimizer state lives only in that process. They come back marked interrupted.
"""
import json
import os
import shutil
import threading
import time
BUCKET_ID = os.environ.get("NANODEX_BUCKET", "hugging-science/nanodex-store")
CACHE_PREFIX = "cache/"
RUNS_PREFIX = "runs/"
# Files worth keeping from a finished run directory.
CHECKPOINT_FILES = (
"config.json",
"generation_config.json",
"model.safetensors",
"tokenizer.json",
"tokenizer_config.json",
"special_tokens_map.json",
"training_run.json",
)
_lock = threading.Lock()
_state = {"enabled": None, "error": None, "restored": 0, "last_error_at": 0}
def _api():
from huggingface_hub import HfApi
tok = os.environ.get("HF_TOKEN") or os.environ.get("NANODEX_HF_TOKEN")
return HfApi(token=tok) if tok else HfApi()
def state():
return dict(_state)
def available(log=print):
"""True when the bucket is reachable and writable by this Space."""
if _state["enabled"] is not None:
return _state["enabled"]
with _lock:
if _state["enabled"] is not None:
return _state["enabled"]
try:
_api().bucket_info(BUCKET_ID)
_state["enabled"] = True
log(f"[store] bucket ready: {BUCKET_ID}")
except Exception as exc:
_state.update(enabled=False, error=repr(exc))
log(f"[store] bucket unavailable ({exc!r}) — "
"running with container-local storage only")
return _state["enabled"]
def _note_error(what, exc, log=print):
_state.update(error=f"{what}: {exc!r}", last_error_at=time.time())
log(f"[store] {what} failed: {exc!r}")
# --------------------------------------------------------------- uploads ----
def put_files(pairs, log=print):
"""pairs: [(local_path, remote_path)] — uploaded in one batch."""
if not pairs or not available(log):
return False
try:
_api().batch_bucket_files(
BUCKET_ID, add=[(str(l), r) for l, r in pairs])
return True
except Exception as exc:
_note_error(f"upload of {len(pairs)} file(s)", exc, log)
return False
def put_json(obj, remote_path, log=print):
if not available(log):
return False
try:
payload = json.dumps(obj, indent=2).encode()
_api().batch_bucket_files(BUCKET_ID, add=[(payload, remote_path)])
return True
except Exception as exc:
_note_error(f"upload of {remote_path}", exc, log)
return False
def save_run(job_id, run_dir, meta, log=print):
"""Persist one finished run: its metadata and its checkpoint files."""
if not available(log):
return False
ok = put_json(meta, f"{RUNS_PREFIX}{job_id}/meta.json", log)
pairs = []
for fn in CHECKPOINT_FILES:
p = os.path.join(run_dir, fn)
if os.path.exists(p):
pairs.append((p, f"{RUNS_PREFIX}{job_id}/{fn}"))
if pairs:
ok = put_files(pairs, log) and ok
log(f"[store] saved run {job_id} ({len(pairs)} files)")
return ok
def save_token_cache(tokens_path, meta_path, log=print):
"""Upload the shared token cache so the next container skips tokenizing."""
if not available(log) or not os.path.exists(tokens_path):
return False
log("[store] uploading token cache (this happens once)")
t0 = time.time()
ok = put_files([(tokens_path, CACHE_PREFIX + "tokens.u16"),
(meta_path, CACHE_PREFIX + "tokens.meta")], log)
if ok:
log(f"[store] token cache uploaded in {time.time() - t0:.0f}s")
return ok
# ------------------------------------------------------------- downloads ----
def _remote_size(path, log=print):
try:
return _api().get_bucket_file_metadata(BUCKET_ID, path).size
except Exception:
return None
def fetch_token_cache(tokens_path, meta_path, log=print):
"""
Pull the token cache if the bucket has one at least as complete as what is
on disk. Returns the number of tokens now available locally, or 0.
"""
if not available(log):
return 0
try:
raw = _api().download_bucket_files(
BUCKET_ID,
[(CACHE_PREFIX + "tokens.meta", meta_path + ".remote")],
raise_on_missing_files=True)
except Exception:
return 0 # nothing stored yet — normal first boot
try:
with open(meta_path + ".remote") as f:
remote_tokens = int(f.read().strip())
except Exception:
return 0
finally:
try:
os.unlink(meta_path + ".remote")
except OSError:
pass
local_tokens = 0
if os.path.exists(meta_path):
try:
with open(meta_path) as f:
local_tokens = int(f.read().strip())
except Exception:
local_tokens = 0
if remote_tokens <= local_tokens:
return local_tokens
log(f"[store] downloading cached {remote_tokens:,} tokens "
f"(beats re-tokenizing from scratch)")
t0 = time.time()
try:
_api().download_bucket_files(
BUCKET_ID, [(CACHE_PREFIX + "tokens.u16", tokens_path)],
raise_on_missing_files=True)
with open(meta_path, "w") as f:
f.write(str(remote_tokens))
log(f"[store] token cache restored in {time.time() - t0:.0f}s")
return remote_tokens
except Exception as exc:
_note_error("token cache download", exc, log)
return local_tokens
def list_runs(log=print):
"""Job ids that have metadata stored in the bucket."""
if not available(log):
return []
try:
ids = set()
for entry in _api().list_bucket_tree(BUCKET_ID, prefix=RUNS_PREFIX,
recursive=True):
path = getattr(entry, "path", None) or getattr(entry, "name", "")
rest = str(path)[len(RUNS_PREFIX):] if str(path).startswith(RUNS_PREFIX) else ""
if "/" in rest:
ids.add(rest.split("/", 1)[0])
return sorted(ids)
except Exception as exc:
_note_error("listing runs", exc, log)
return []
def fetch_run_meta(job_id, log=print):
if not available(log):
return None
tmp = f"/tmp/nanodex-meta-{job_id}.json"
try:
_api().download_bucket_files(
BUCKET_ID, [(f"{RUNS_PREFIX}{job_id}/meta.json", tmp)],
raise_on_missing_files=True)
with open(tmp) as f:
return json.load(f)
except Exception:
return None
finally:
try:
os.unlink(tmp)
except OSError:
pass
def fetch_checkpoint(job_id, run_dir, log=print):
"""
Restore a finished run's weights into run_dir. Called lazily, the first
time somebody opens the playground or publishes after a restart.
"""
if not available(log):
return False
if os.path.exists(os.path.join(run_dir, "model.safetensors")):
return True
os.makedirs(run_dir, exist_ok=True)
wanted = [(f"{RUNS_PREFIX}{job_id}/{fn}", os.path.join(run_dir, fn))
for fn in CHECKPOINT_FILES]
try:
_api().download_bucket_files(BUCKET_ID, wanted,
raise_on_missing_files=False)
except Exception as exc:
_note_error(f"checkpoint download for {job_id}", exc, log)
return False
ok = os.path.exists(os.path.join(run_dir, "model.safetensors"))
if ok:
log(f"[store] restored checkpoint {job_id}")
else:
shutil.rmtree(run_dir, ignore_errors=True)
return ok