llm-host/llmhost/hfcache.py
neil 8611d92cf4 MLX: cap KV caches and recover from crashes; add llmhost watch
- mlx_lm.server kept up to 10 conversations' KV caches with no byte
  limit and prefilled 8 prompts at once, which ran a 16 GB Mac out of
  GPU memory. The plan now gives the live request half the free memory
  (at least 32k tokens), caps --prompt-cache-bytes to the rest, and on
  small machines prefills one prompt at a time.
- When its generation thread dies, mlx_lm.server keeps running but fails
  every request. The proxy now restarts it.
- llmhost watch: one live line with download progress (bytes, speed,
  time left), then loading, until the model answers. Setup and switch
  point at it instead of llmhost logs -f.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QaE1hpvyZTJixEbUUMj9Ca
2026-11-02 07:45:12 -08:00

61 lines
2 KiB
Python

"""Read-only checks against the Hugging Face cache (no huggingface_hub dependency)."""
import json
import os
from . import paths
def repo_dir(repo):
return paths.hf_hub_dir() / ("models--" + repo.replace("/", "--"))
def is_downloaded(repo):
"""True when a snapshot has every weight file its index lists (or a single-file model)."""
snaps = repo_dir(repo) / "snapshots"
if not snaps.is_dir():
return False
for snap in snaps.iterdir():
idx = snap / "model.safetensors.index.json"
if idx.exists():
try:
files = set(json.loads(idx.read_text())["weight_map"].values())
except (OSError, ValueError, KeyError):
continue
if files and all(os.path.exists(snap / f) for f in files):
return True
elif (snap / "model.safetensors").exists():
return True
return False
def disk_gib(repo):
"""Size of this repo's downloaded files, in GiB. Measured through the snapshot symlinks
because newer huggingface_hub versions keep large blobs in a shared hub/blobs directory."""
seen, total = set(), 0
snaps = repo_dir(repo) / "snapshots"
if snaps.is_dir():
for root, _dirs, files in os.walk(snaps):
for name in files:
real = os.path.realpath(os.path.join(root, name))
if real in seen:
continue
seen.add(real)
try:
total += os.stat(real).st_size
except OSError:
pass
return total / 2**30
def download_gib(repo):
"""Bytes downloaded so far, in GiB: finished files plus ones still being written
(huggingface_hub writes those as blobs/*.incomplete inside the repo's own folder)."""
total = disk_gib(repo) * 2**30
blobs = repo_dir(repo) / "blobs"
if blobs.is_dir():
for f in blobs.glob("*.incomplete"):
try:
total += f.stat().st_size
except OSError:
pass
return total / 2**30