-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
4471 lines (3892 loc) · 173 KB
/
Copy pathserver.py
File metadata and controls
4471 lines (3892 loc) · 173 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""MLXr — management server for Apple MLX model engine.
Exposes a JSON API and serves a dashboard for loading MLX language models,
running streaming inference, and inspecting host + engine state.
"""
from __future__ import annotations
import asyncio
import hashlib
import json
import logging
import os
import shutil
import sys
import threading
import time
import urllib.request
import uuid
from dataclasses import dataclass, field
from pathlib import Path
from threading import Lock
from typing import Any, AsyncIterator, Optional
import psutil
from fastapi import FastAPI, HTTPException
from fastapi.responses import StreamingResponse
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel, Field
log = logging.getLogger("mlxr")
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s")
# Suppress uvicorn access-log spam from the dashboard's polling loops.
# /api/status and /api/hf/downloads are hit every 2-3 seconds; they clutter
# the log and make real events (tool calls, errors, model loads) hard to find.
_POLL_PATHS = frozenset(["/api/status", "/api/hf/downloads"])
class _PollFilter(logging.Filter):
def filter(self, record: logging.LogRecord) -> bool:
msg = record.getMessage()
return not any(p in msg for p in _POLL_PATHS)
logging.getLogger("uvicorn.access").addFilter(_PollFilter())
STATIC_DIR = Path(__file__).parent / "static"
SETTINGS_PATH = Path(os.environ.get("MLXR_SETTINGS_PATH", str(Path.home() / ".mlxr" / "settings.json")))
# Only these packages may be upgraded via the dashboard. Prevents the API from
# being abused to `pip install` arbitrary things.
ALLOWED_UPGRADE_PACKAGES = ("mlx", "mlx-lm", "mlx-vlm", "huggingface_hub", "transformers")
PACKAGE_TO_MODULE = {
"mlx": "mlx",
"mlx-lm": "mlx_lm",
"mlx-vlm": "mlx_vlm",
"huggingface_hub": "huggingface_hub",
"transformers": "transformers",
}
# run.sh watches for this exit code and re-launches the server.
RESTART_EXIT_CODE = 42
SUGGESTED_MODELS = [
"mlx-community/Llama-3.2-1B-Instruct-4bit",
"mlx-community/Llama-3.2-3B-Instruct-4bit",
"mlx-community/Qwen2.5-1.5B-Instruct-4bit",
"mlx-community/Qwen2.5-7B-Instruct-4bit",
"mlx-community/Mistral-7B-Instruct-v0.3-4bit",
"mlx-community/Phi-3.5-mini-instruct-4bit",
]
MLXR_MAX_MODELS = max(1, int(os.environ.get("MLXR_MAX_MODELS", "1")))
# HuggingFace auth token — read once at startup.
# Set HF_TOKEN (or the legacy HUGGINGFACE_HUB_TOKEN) in the environment to
# authenticate downloads. Without it, requests are rate-limited and large
# model downloads become impractically slow.
_HF_TOKEN: Optional[str] = (
os.environ.get("HF_TOKEN") or os.environ.get("HUGGINGFACE_HUB_TOKEN") or None
)
if _HF_TOKEN:
# Configure huggingface_hub globally so every call (model_info, snapshot_download,
# try_to_load_from_cache, etc.) uses the token without each call site having to
# pass it explicitly.
try:
from huggingface_hub import login as _hf_login
_hf_login(token=_HF_TOKEN, add_to_git_credential=False)
log.info("HuggingFace: authenticated via HF_TOKEN")
except Exception as _e:
log.warning("HuggingFace: token login failed (%s) — continuing unauthenticated", _e)
else:
log.warning(
"HuggingFace: no HF_TOKEN set — downloads will be rate-limited. "
"Set HF_TOKEN in your environment for faster, authenticated access."
)
@dataclass
class LoadedModel:
name: str
loaded_at: float
model: Any
tokenizer: Any
context_length: int = 32768 # auto-detected from model config at load time
generations: int = 0
total_tokens: int = 0
last_used: float = field(default_factory=time.time)
# Per-generation perf metrics updated after each inference call.
last_ttft: Optional[float] = None # Time To First Token (seconds)
last_tps: Optional[float] = None # tokens / second (generation throughput)
is_vlm: bool = False
def _detect_context_length(tokenizer: Any, model_name: str) -> int:
"""Return the model's context window size.
Priority:
1. tokenizer.model_max_length — set correctly by most modern tokenizers
but some (e.g. very old or debug tokenizers) set it to sys.maxsize.
2. config.json in the HF cache — check max_position_embeddings at
top level and inside text_config (VLMs nest it there).
3. Fallback: 32768 (conservative but safe for all current Apple Silicon).
"""
# 1. Tokenizer attribute
tok_max = getattr(tokenizer, "model_max_length", None)
if tok_max and isinstance(tok_max, int) and tok_max < 10_000_000:
return tok_max
# 2. HF cache config.json
try:
from huggingface_hub import try_to_load_from_cache
config_path = try_to_load_from_cache(model_name, "config.json")
if config_path:
import json as _json
cfg = _json.loads(open(config_path).read())
for source in (cfg, cfg.get("text_config", {})):
for key in ("max_position_embeddings", "n_positions", "seq_length"):
val = source.get(key)
if val and isinstance(val, int):
return val
except Exception as e:
log.debug("context length detection failed: %s", e)
return 32768
def _clear_mlx_cache() -> None:
"""Ask MLX to release Metal buffer cache. Silently ignored if MLX is not installed."""
try:
import mlx.core as mx
mx.metal.clear_cache()
except Exception:
pass
# ---- HuggingFace cache helpers -------------------------------------------
def _is_model_cached(name: str) -> bool:
"""Return True if the model is fully available locally.
Accepts either a HuggingFace repo ID (org/model) or an absolute/relative
local path. For HF repos, checks whether a complete snapshot exists in the
local hub cache; for local paths, checks that the directory exists.
This is used before loading to prevent mlx-lm from silently downloading
large model weights inside the Load call (which has no progress feedback).
"""
# Local path — just check the directory.
p = Path(name)
if p.is_absolute() or name.startswith("./") or name.startswith("../"):
return p.is_dir()
# HuggingFace repo ID — look for a refs/main (or any revision) snapshot.
try:
from huggingface_hub.constants import HF_HUB_CACHE
cache_root = Path(HF_HUB_CACHE) / f"models--{name.replace('/', '--')}"
if not cache_root.exists():
return False
# A complete snapshot has at least one entry under snapshots/ that
# contains a non-empty directory (the actual files are in blobs/).
snapshots_dir = cache_root / "snapshots"
if not snapshots_dir.is_dir():
return False
for snapshot in snapshots_dir.iterdir():
if snapshot.is_dir() and any(snapshot.iterdir()):
return True
return False
except Exception:
# If we can't check, allow the load to proceed.
return True
# ---- VLM helpers ---------------------------------------------------------
# Structural keys: presence of a non-empty vision tower config block is the
# only reliable VLM signal. Token-id-only signals (image_token_id, etc.) leak
# into text-only Qwen3 quantizations whose configs were copied from a
# multimodal sibling — those models will FAIL to load through mlx_vlm because
# their weight files don't contain the vision-tower parameters.
_VLM_VISION_CONFIG_KEYS = ("vision_config", "visual_config", "vision_tower")
# quant_method values that MLX's loaders can read. Anything else (paroquant,
# awq, gptq, bitsandbytes, …) requires its own runtime — mlx_lm / mlx_vlm
# will produce a confusing weight-shape error mid-load otherwise.
_MLX_KNOWN_QUANT_METHODS = frozenset({"mlx", ""})
# Hints for the user when we encounter a non-MLX quant method.
_QUANT_METHOD_HINTS = {
"paroquant": (
"ParoQuant has its own runtime — install with "
"'pip install \"paroquant[mlx]\"' and run "
"'python -m paroquant.cli.serve --model {name} --port 8001'."
),
"awq": "AWQ models need vLLM or AutoAWQ; MLX cannot load them directly.",
"gptq": "GPTQ models need AutoGPTQ or vLLM; MLX cannot load them directly.",
"bitsandbytes": "bitsandbytes-quantized weights require CUDA; MLX cannot load them.",
}
def _check_supported_quant_method(name: str) -> None:
"""Raise a friendly error if the model uses a quant method MLX can't read."""
try:
from huggingface_hub import try_to_load_from_cache
cfg_path = try_to_load_from_cache(name, "config.json")
if not cfg_path:
return
cfg = json.loads(open(cfg_path).read())
qcfg = cfg.get("quantization_config") or {}
method = (qcfg.get("quant_method") or "").lower()
except Exception:
return
if not method or method in _MLX_KNOWN_QUANT_METHODS:
return
hint = _QUANT_METHOD_HINTS.get(method, "")
msg = (
f"{name} is quantized with '{method}', which MLX cannot load. "
"Use a model quantized with MLX (mlx-community / unsloth MLX builds) instead."
)
if hint:
msg += " " + hint.format(name=name)
raise RuntimeError(msg)
def _is_vlm_model(name: str) -> bool:
"""Check model config.json for VLM indicators. Returns False on any error.
Requires a non-empty vision_config/visual_config/vision_tower block.
Models that only carry image_token_id without an actual vision tower are
treated as text-only LLMs (their weights wouldn't satisfy mlx_vlm anyway).
"""
try:
from huggingface_hub import try_to_load_from_cache
cfg_path = try_to_load_from_cache(name, "config.json")
if not cfg_path:
return False
cfg = json.loads(open(cfg_path).read())
for key in _VLM_VISION_CONFIG_KEYS:
val = cfg.get(key)
# Must be a non-empty dict/object — empty {} or absent → not VLM
if isinstance(val, dict) and val:
return True
if val and not isinstance(val, (dict, list)):
# E.g. vision_tower as a string class name
return True
except Exception:
pass
return False
def _load_llm(name: str) -> LoadedModel:
from mlx_lm import load as mlx_load
model, tokenizer = mlx_load(name)
auto_ctx = _detect_context_length(tokenizer, name)
saved_ctx = settings.get_model(name).get("context_length")
ctx = int(saved_ctx) if saved_ctx else auto_ctx
log.info("Context length for %s: %d%s", name, ctx, " (overridden)" if saved_ctx else " (auto)")
return LoadedModel(name=name, loaded_at=time.time(), model=model, tokenizer=tokenizer, context_length=ctx)
def _load_vlm(name: str) -> LoadedModel:
try:
from mlx_vlm import load as vlm_load
except ImportError:
raise RuntimeError(
f"{name} appears to be a VLM but mlx-vlm is not installed. "
"Run: pip install mlx-vlm torch torchvision"
)
model, processor = vlm_load(name)
tokenizer = getattr(processor, "tokenizer", processor)
auto_ctx = _detect_context_length(tokenizer, name)
saved_ctx = settings.get_model(name).get("context_length")
ctx = int(saved_ctx) if saved_ctx else auto_ctx
log.info("VLM context length for %s: %d", name, ctx)
return LoadedModel(
name=name, loaded_at=time.time(),
model=model, tokenizer=processor, # store full processor as tokenizer
context_length=ctx, is_vlm=True,
)
class EnginePool:
"""LRU pool of loaded MLX models.
MLXR_MAX_MODELS controls capacity (default 1, preserving backward compat).
A single _gen_lock serialises ALL inference across ALL models — MLX/Metal
crashes with concurrent eval() calls.
"""
def __init__(self) -> None:
self._lock = Lock()
# Single gen lock shared across all models — Metal requirement.
self._gen_lock = Lock()
# canonical name → LoadedModel, insertion order = load order
self._models: dict[str, LoadedModel] = {}
self._loading: Optional[str] = None
# ---- properties (backward compat) ------------------------------------
@property
def gen_lock(self) -> Lock:
return self._gen_lock
@property
def current(self) -> Optional[LoadedModel]:
"""Most recently used model (first in reverse-insertion order)."""
with self._lock:
if not self._models:
return None
# Return the model with the highest last_used timestamp.
return max(self._models.values(), key=lambda m: m.last_used)
@property
def loading(self) -> Optional[str]:
return self._loading
# ---- public API ------------------------------------------------------
def get(self, name: str) -> Optional[LoadedModel]:
"""Look up by canonical name or alias."""
if not name:
return None
with self._lock:
if name in self._models:
return self._models[name]
# Check aliases
for m in self._models.values():
saved = settings.get_model(m.name)
if saved.get("alias") == name:
return m
return None
def loaded_models(self) -> list[LoadedModel]:
"""All loaded models, newest-used first."""
with self._lock:
return sorted(self._models.values(), key=lambda m: m.last_used, reverse=True)
def load(self, name: str) -> LoadedModel:
"""Load a model into the pool, evicting LRU if at capacity."""
with self._lock:
if self._loading:
raise RuntimeError(f"Another load is in progress: {self._loading}")
if name in self._models:
# Already loaded — bump last_used and return.
m = self._models[name]
m.last_used = time.time()
return m
self._loading = name
try:
# Evict LRU models until we're below capacity.
with self._lock:
while len(self._models) >= MLXR_MAX_MODELS:
lru_name = min(self._models, key=lambda k: self._models[k].last_used)
log.info("Pool full — evicting LRU model %s", lru_name)
del self._models[lru_name]
# Refuse to load a model that isn't in the local HF cache.
# mlx-lm would silently download it (potentially many GB) with no
# progress feedback. Direct the user to the Import panel instead.
if not _is_model_cached(name):
raise RuntimeError(
f"'{name}' is not in the local HuggingFace cache. "
"Use the 'Import from Hugging Face' panel to download it first, "
"then Load."
)
log.info("Loading model %s", name)
_check_supported_quant_method(name)
t0 = time.time()
is_vlm = _is_vlm_model(name)
if is_vlm:
log.info("Detected VLM architecture for %s", name)
loaded = _load_vlm(name)
else:
loaded = _load_llm(name)
log.info("Loaded %s in %.1fs", name, time.time() - t0)
with self._lock:
self._models[name] = loaded
self._loading = None
return loaded
except Exception:
with self._lock:
self._loading = None
raise
def unload(self, name: Optional[str] = None) -> bool:
"""Unload by canonical name/alias, or the LRU model if name is None."""
with self._lock:
if not self._models:
return False
if name is None:
# Unload LRU
target = min(self._models.values(), key=lambda m: m.last_used)
del self._models[target.name]
else:
# Find by name or alias
found_key = None
if name in self._models:
found_key = name
else:
for k, m in self._models.items():
saved = settings.get_model(m.name)
if saved.get("alias") == name:
found_key = k
break
if found_key is None:
return False
del self._models[found_key]
_clear_mlx_cache()
return True
class Settings:
"""Per-model generation defaults + engine preferences, persisted to JSON.
File layout:
{ "models": { "<repo-id>": { "system": "...", "temperature": 0.7, ... } },
"general": { ... reserved ... } }
"""
def __init__(self, path: Path) -> None:
self.path = path
self._lock = Lock()
self._data = self._load()
def _load(self) -> dict:
if not self.path.exists():
return {"models": {}, "general": {}}
try:
return json.loads(self.path.read_text())
except Exception as e:
log.warning("settings read failed (%s), starting empty", e)
return {"models": {}, "general": {}}
def _save_locked(self) -> None:
self.path.parent.mkdir(parents=True, exist_ok=True)
tmp = self.path.with_suffix(self.path.suffix + ".tmp")
tmp.write_text(json.dumps(self._data, indent=2, sort_keys=True))
tmp.replace(self.path)
def snapshot(self) -> dict:
with self._lock:
return json.loads(json.dumps(self._data))
def get_model(self, repo_id: str) -> dict:
with self._lock:
return dict(self._data.get("models", {}).get(repo_id, {}))
def set_model(self, repo_id: str, values: dict) -> dict:
with self._lock:
models = self._data.setdefault("models", {})
# Merge rather than replace, so clients can PATCH a single field.
merged = {**models.get(repo_id, {}), **values}
# Drop Nones so defaults cleanly revert.
merged = {k: v for k, v in merged.items() if v is not None}
models[repo_id] = merged
self._save_locked()
return dict(merged)
def delete_model(self, repo_id: str) -> bool:
with self._lock:
removed = self._data.get("models", {}).pop(repo_id, None)
if removed is not None:
self._save_locked()
return removed is not None
def autoload_name(self) -> Optional[str]:
with self._lock:
for repo_id, cfg in self._data.get("models", {}).items():
if cfg.get("autoload"):
return repo_id
return None
@dataclass
class DownloadJob:
repo_id: str
status: str = "queued" # queued | downloading | done | error | cancelled
started_at: float = 0.0
finished_at: float = 0.0
bytes_downloaded: int = 0
total_bytes: int = 0
files_total: int = 0
files_done: int = 0
error: Optional[str] = None
local_dir: Optional[str] = None
def to_dict(self) -> dict:
return {
"repo_id": self.repo_id,
"status": self.status,
"started_at": self.started_at,
"finished_at": self.finished_at,
"bytes_downloaded": self.bytes_downloaded,
"total_bytes": self.total_bytes,
"files_total": self.files_total,
"files_done": self.files_done,
"error": self.error,
"local_dir": self.local_dir,
"percent": (self.bytes_downloaded / self.total_bytes * 100.0) if self.total_bytes else None,
}
class HFManager:
"""HuggingFace browse / download / cache operations."""
def __init__(self) -> None:
self._jobs: dict[str, DownloadJob] = {}
self._lock = Lock()
# ---- search --------------------------------------------------------
def search(self, query: str, author: Optional[str], limit: int) -> list[dict]:
from huggingface_hub import HfApi
api = HfApi()
# MLX-compatible models are typically published by the mlx-community org,
# but we also allow library="mlx" and free-form search.
kwargs: dict[str, Any] = {"limit": limit, "sort": "downloads"}
if query:
kwargs["search"] = query
if author:
kwargs["author"] = author
results = []
try:
try:
# hf_hub <1.0 used `direction=-1` for descending; 1.x removed it
# and sorts descending by default for known sort keys.
iterator = api.list_models(**kwargs, direction=-1)
except TypeError:
iterator = api.list_models(**kwargs)
for m in iterator:
tags = list(getattr(m, "tags", []) or [])
results.append({
"id": m.modelId if hasattr(m, "modelId") else m.id,
"downloads": getattr(m, "downloads", None),
"likes": getattr(m, "likes", None),
"last_modified": str(getattr(m, "lastModified", "") or getattr(m, "last_modified", "") or ""),
"tags": tags,
"pipeline_tag": getattr(m, "pipeline_tag", None),
})
except Exception as e:
log.warning("HF list_models failed: %s", e)
raise
return results
# ---- downloads -----------------------------------------------------
def start_download(self, repo_id: str) -> DownloadJob:
with self._lock:
existing = self._jobs.get(repo_id)
if existing and existing.status in ("queued", "downloading"):
return existing
job = DownloadJob(repo_id=repo_id, status="queued", started_at=time.time())
self._jobs[repo_id] = job
t = threading.Thread(target=self._run_download, args=(job,), daemon=True)
t.start()
return job
def _run_download(self, job: DownloadJob) -> None:
try:
from huggingface_hub import HfApi, snapshot_download
job.status = "downloading"
# Determine total size up front so the UI can show a progress bar.
try:
info = HfApi(token=_HF_TOKEN).model_info(job.repo_id, files_metadata=True)
siblings = getattr(info, "siblings", []) or []
job.files_total = len(siblings)
job.total_bytes = sum(int(getattr(s, "size", 0) or 0) for s in siblings)
except Exception as e:
log.warning("model_info failed for %s: %s", job.repo_id, e)
stop_event = threading.Event()
poll = threading.Thread(target=self._poll_progress, args=(job, stop_event), daemon=True)
poll.start()
try:
local_dir = snapshot_download(
repo_id=job.repo_id,
token=_HF_TOKEN,
# Avoid blowing up memory for tokenizer-less repos; MLX models are small-ish.
allow_patterns=None,
)
finally:
stop_event.set()
poll.join(timeout=1.0)
job.local_dir = str(local_dir)
# Final size read
try:
job.bytes_downloaded = _dir_size(Path(local_dir))
job.files_done = _file_count(Path(local_dir))
except Exception:
pass
job.status = "done"
job.finished_at = time.time()
log.info("downloaded %s -> %s", job.repo_id, job.local_dir)
except Exception as e:
log.exception("download failed for %s", job.repo_id)
job.status = "error"
job.error = str(e)
job.finished_at = time.time()
def _poll_progress(self, job: DownloadJob, stop: threading.Event) -> None:
from huggingface_hub import try_to_load_from_cache # noqa: F401
from huggingface_hub.constants import HF_HUB_CACHE
cache_root = Path(HF_HUB_CACHE) / f"models--{job.repo_id.replace('/', '--')}"
while not stop.is_set():
try:
if cache_root.exists():
job.bytes_downloaded = _dir_size(cache_root)
job.files_done = _file_count(cache_root)
except Exception:
pass
stop.wait(0.75)
def jobs(self) -> list[dict]:
with self._lock:
return [j.to_dict() for j in self._jobs.values()]
# ---- cache ---------------------------------------------------------
def cache(self) -> dict:
from huggingface_hub import scan_cache_dir
try:
info = scan_cache_dir()
except Exception as e:
return {"size_on_disk": 0, "repos": [], "error": str(e)}
repos = []
for repo in info.repos:
revisions = [
{
"commit_hash": r.commit_hash,
"size_on_disk": r.size_on_disk,
"last_modified": r.last_modified,
"nb_files": r.nb_files,
"refs": sorted(list(r.refs)) if r.refs else [],
}
for r in repo.revisions
]
repos.append({
"repo_id": repo.repo_id,
"repo_type": repo.repo_type,
"size_on_disk": repo.size_on_disk,
"nb_files": repo.nb_files,
"last_accessed": repo.last_accessed,
"last_modified": repo.last_modified,
"repo_path": str(repo.repo_path),
"revisions": revisions,
})
repos.sort(key=lambda r: r["size_on_disk"], reverse=True)
return {"size_on_disk": info.size_on_disk, "repos": repos}
def delete_repo(self, repo_id: str) -> dict:
from huggingface_hub import scan_cache_dir
info = scan_cache_dir()
revisions = []
for repo in info.repos:
if repo.repo_id == repo_id and repo.repo_type == "model":
revisions.extend(r.commit_hash for r in repo.revisions)
if not revisions:
raise ValueError(f"{repo_id!r} not found in cache")
strategy = info.delete_revisions(*revisions)
freed = strategy.expected_freed_size
strategy.execute()
return {"ok": True, "freed_bytes": freed, "revisions": len(revisions)}
def _dir_size(path: Path) -> int:
total = 0
for p in path.rglob("*"):
try:
if p.is_file() and not p.is_symlink():
total += p.stat().st_size
except OSError:
continue
return total
def _file_count(path: Path) -> int:
return sum(1 for p in path.rglob("*") if p.is_file() and not p.is_symlink())
# ────────────────────────────────────────────────────────────────────
# Tiered KV-cache (RAM hot tier → SSD cold tier)
# ────────────────────────────────────────────────────────────────────
KVC_ENABLED = os.environ.get("MLXR_KVC_ENABLED", "1") not in ("0", "false", "no")
KVC_MAX_RAM_ENTRIES = int(os.environ.get("MLXR_KVC_RAM_ENTRIES", "8"))
KVC_MAX_DISK_ENTRIES = int(os.environ.get("MLXR_KVC_DISK_ENTRIES", "32"))
KVC_CACHE_DIR = Path(os.environ.get("MLXR_KVC_DIR",
str(Path.home() / ".mlxr" / "kvcache")))
KVC_MIN_PREFIX_LEN = int(os.environ.get("MLXR_KVC_MIN_PREFIX", "64"))
def _kvc_model_key(name: str) -> str:
return name.replace("/", "_").replace("\\", "_").replace(":", "_")
def _kvc_prefix_hash(token_ids: list, length: int) -> str:
buf = b"".join(int(t).to_bytes(4, "little") for t in token_ids[:length])
return hashlib.sha256(buf).hexdigest()[:32]
def _kvc_serialize(cache: list, path: Path) -> bool:
"""Save a KV-cache to a compressed NPZ file. Returns True on success."""
try:
import numpy as np
import mlx.core as mx
path.parent.mkdir(parents=True, exist_ok=True)
arrays: dict = {}
n = 0
for i, layer in enumerate(cache):
k = getattr(layer, "keys", None)
v = getattr(layer, "values", None)
off = getattr(layer, "offset", None)
if k is None or v is None or not off:
continue
mx.eval(k, v)
ks = k[..., :off, :]
vs = v[..., :off, :]
mx.eval(ks, vs)
arrays[f"l{i}k"] = np.array(ks)
arrays[f"l{i}v"] = np.array(vs)
arrays[f"l{i}o"] = np.array([off], dtype=np.int64)
n += 1
if not n:
return False
np.savez_compressed(str(path), **arrays)
log.info("kvc: saved %d layers (%.1f MB) → %s",
n, path.stat().st_size / 1e6, path.name)
return True
except Exception as e:
log.warning("kvc: serialize failed: %s", e)
return False
def _kvc_deserialize(path: Path, model: Any) -> Optional[list]:
"""Restore a KV-cache from an NPZ file. Returns None on failure."""
try:
import numpy as np
import mlx.core as mx
if not path.exists() or not hasattr(model, "make_cache"):
return None
data = dict(np.load(str(path)))
cache = model.make_cache()
n = 0
for i, layer in enumerate(cache):
if f"l{i}k" not in data:
continue
layer.keys = mx.array(data[f"l{i}k"])
layer.values = mx.array(data[f"l{i}v"])
if hasattr(layer, "offset"):
layer.offset = int(data[f"l{i}o"][0])
n += 1
if not n:
return None
log.info("kvc: restored %d layers from %s", n, path.name)
return cache
except Exception as e:
log.warning("kvc: deserialize failed (%s): %s", path.name, e)
return None
class KVCacheManager:
"""Two-tier KV-cache for prompt-prefix reuse.
**Hot tier (RAM):** in-process dict of { hash → (cache_list, token_len, ts) }.
**Cold tier (SSD):** compressed NPZ files under KVC_CACHE_DIR.
Keys are SHA-256 hashes of token-ID prefixes at power-of-2 lengths.
On a new request, the manager scans from longest to shortest candidate
prefix and returns the first (longest) hit, together with the number of
tokens that are already computed so the caller can skip them.
"""
def __init__(self) -> None:
self._lock = Lock()
self._ram: dict[str, dict[str, tuple]] = {} # mkey→{h→(cache,len,ts)}
self._disk: dict[str, dict[str, dict]] = {} # mkey→{h→{"path","tok_len","ts"}}
self._load_disk_index()
# ── public ──────────────────────────────────────────────────────
def find(self, model_name: str, model: Any, token_ids: list) -> Optional[tuple]:
"""Return (cache_list, prefix_token_len) or None."""
if not KVC_ENABLED or len(token_ids) < KVC_MIN_PREFIX_LEN:
return None
mkey = _kvc_model_key(model_name)
with self._lock:
ram = dict(self._ram.get(mkey, {}))
disk = dict(self._disk.get(mkey, {}))
for exp in range(14, 5, -1): # 16384 → 64
clen = 1 << exp
if clen > len(token_ids) - 1 or clen < KVC_MIN_PREFIX_LEN:
continue
h = _kvc_prefix_hash(token_ids, clen)
if h in ram:
cache, tl, _ = ram[h]
with self._lock:
t = self._ram.get(mkey, {})
if h in t:
t[h] = (cache, tl, time.time())
log.info("kvc: RAM hit — %d tokens for %s", tl, model_name)
return cache, tl
if h in disk:
cache = _kvc_deserialize(disk[h]["path"], model)
if cache is not None:
tl = disk[h]["tok_len"]
self._put_ram(mkey, h, cache, tl)
log.info("kvc: disk→RAM hit — %d tokens for %s", tl, model_name)
return cache, tl
return None
def store(self, model_name: str, token_ids: list, cache: list) -> None:
"""Store cache checkpoints at every power-of-2 prefix length."""
if not KVC_ENABLED or len(token_ids) < KVC_MIN_PREFIX_LEN:
return
mkey = _kvc_model_key(model_name)
for exp in range(6, 15): # 64 → 16384
clen = 1 << exp
if clen >= len(token_ids):
break
h = _kvc_prefix_hash(token_ids, clen)
self._put_ram(mkey, h, cache, clen)
# Full-length entry
h = _kvc_prefix_hash(token_ids, len(token_ids))
self._put_ram(mkey, h, cache, len(token_ids))
def clear(self, model_name: Optional[str] = None) -> dict:
with self._lock:
if model_name:
mk = _kvc_model_key(model_name)
rn = len(self._ram.pop(mk, {}))
dn = len(self._disk.pop(mk, {}))
shutil.rmtree(KVC_CACHE_DIR / mk, ignore_errors=True)
else:
rn = sum(len(v) for v in self._ram.values())
dn = sum(len(v) for v in self._disk.values())
self._ram.clear(); self._disk.clear()
shutil.rmtree(KVC_CACHE_DIR, ignore_errors=True)
return {"ram_cleared": rn, "disk_cleared": dn}
def stats(self) -> dict:
with self._lock:
rn = sum(len(v) for v in self._ram.values())
dn = sum(len(v) for v in self._disk.values())
db = sum(f.stat().st_size for f in KVC_CACHE_DIR.rglob("*.npz")
if f.exists()) if KVC_CACHE_DIR.exists() else 0
return {
"enabled": KVC_ENABLED, "ram_entries": rn, "ram_max": KVC_MAX_RAM_ENTRIES,
"disk_entries": dn, "disk_max": KVC_MAX_DISK_ENTRIES,
"disk_bytes": db, "cache_dir": str(KVC_CACHE_DIR),
}
# ── internal ────────────────────────────────────────────────────
def _put_ram(self, mkey: str, h: str, cache: list, tl: int) -> None:
with self._lock:
tier = self._ram.setdefault(mkey, {})
tier[h] = (cache, tl, time.time())
while len(tier) > KVC_MAX_RAM_ENTRIES:
old_h = min(tier, key=lambda x: tier[x][2])
old_c, old_l, _ = tier.pop(old_h)
threading.Thread(
target=self._spill, args=(mkey, old_h, old_c, old_l), daemon=True
).start()
def _spill(self, mkey: str, h: str, cache: list, tl: int) -> None:
with self._lock:
disk = self._disk.get(mkey, {})
if len(disk) >= KVC_MAX_DISK_ENTRIES:
old_h = min(disk, key=lambda x: disk[x]["ts"])
try:
disk.pop(old_h)["path"].unlink(missing_ok=True)
except Exception:
pass
path = KVC_CACHE_DIR / mkey / f"{h}.npz"
if _kvc_serialize(cache, path):
with self._lock:
self._disk.setdefault(mkey, {})[h] = {"path": path, "tok_len": tl, "ts": time.time()}
self._save_meta(mkey)
def _load_disk_index(self) -> None:
if not KVC_CACHE_DIR.exists():
return
for d in KVC_CACHE_DIR.iterdir():
if not d.is_dir():
continue
mkey = d.name
meta_p = d / "_meta.json"
if meta_p.exists():
try:
for h, info in json.loads(meta_p.read_text()).items():
p = d / f"{h}.npz"
if p.exists():
self._disk.setdefault(mkey, {})[h] = {
"path": p, "tok_len": info.get("tok_len", 0), "ts": info.get("ts", 0.0)
}
except Exception as e:
log.debug("kvc: meta error %s: %s", d.name, e)
def _save_meta(self, mkey: str) -> None:
d = KVC_CACHE_DIR / mkey
d.mkdir(parents=True, exist_ok=True)
with self._lock:
meta = {h: {"tok_len": v["tok_len"], "ts": v["ts"]}
for h, v in self._disk.get(mkey, {}).items()}
(d / "_meta.json").write_text(json.dumps(meta, indent=2))
kvc = KVCacheManager()
engine = EnginePool()
hf = HFManager()
settings = Settings(SETTINGS_PATH)
app = FastAPI(title="MLXr", version="0.1.0")
# CORS — allow any browser/frontend origin so OpenWebUI, LibreChat, custom UIs,
# and Jupyter notebooks can call the API directly without a reverse-proxy.
from fastapi.middleware.cors import CORSMiddleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_methods=["*"],
allow_headers=["*"],
)
# Optional API-key gate on /v1/ routes.
# Set MLXR_API_KEY in the environment to require clients to send
# Authorization: Bearer <key>
# When the env var is not set, any value (or no header) is accepted, which
# preserves the existing "no auth required" behaviour.
_API_KEY: Optional[str] = os.environ.get("MLXR_API_KEY") or None
async def _idle_unload_task() -> None:
"""Background task: auto-unload models that have been idle past their TTL.
Checks every 60 seconds. The TTL (``idle_timeout_minutes``) is a per-model
setting stored in ~/.mlxr/settings.json. A value of None means 'never
auto-unload', preserving backward-compatible behaviour for all existing
model configs.
"""
while True:
await asyncio.sleep(60)
for m in engine.loaded_models():
saved = settings.get_model(m.name)
timeout_min = saved.get("idle_timeout_minutes")
if timeout_min and (time.time() - m.last_used) >= timeout_min * 60:
log.info(
"Auto-unloading %s: idle %.1f min >= TTL %d min",
m.name, (time.time() - m.last_used) / 60, timeout_min,
)
engine.unload(m.name)
@app.on_event("startup")
async def _autoload_on_start() -> None:
# Warm up the tool-mapping registry singleton (loads builtin_mappings.json).
from tool_mappings import get_registry
get_registry()
name = settings.autoload_name()
if name:
log.info("Autoloading %s per settings", name)
def _go():
try:
engine.load(name)
except Exception as e:
log.warning("autoload failed: %s", e)
threading.Thread(target=_go, daemon=True).start()