Repository navigation
Expand file tree
/
Copy pathcli.py
More file actions
510 lines (433 loc) · 19.3 KB
/
Copy pathcli.py
File metadata and controls
510 lines (433 loc) · 19.3 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
#!/usr/bin/env python3
r"""
ml-benchmark CLI — interactive REPL on local LLM backends.
Default usage (interactive):
python3 cli.py --backend mlx --tier light
python3 cli.py --backend gguf --tier flash
python3 cli.py --backend mlc --tier light --max-tokens 1024
This downloads the model if missing, loads it, warms it up, then drops you
at a `> ` prompt. Type any prompt and press Enter; the response prints with
its tokens-per-second. `:q` (or Ctrl-D) exits and releases the model.
Diagnostic sub-commands:
python3 cli.py info # hardware + tiers + models
python3 cli.py download mlx light # pre-download a model
python3 cli.py jit light # MLC JIT step-by-step diag
Tiers are loaded dynamically from shared/repository.json
(currently: light, speed, flash, blaze, ultra).
Always run with the app's venv:
~/Library/Application\ Support/MLBenchmark/venv/bin/python3 cli.py ...
"""
import sys
import os
import argparse
import contextlib
import platform
import time
import traceback
from pathlib import Path
# ── Add app/ to sys.path so imports (utils, model_runner_*) work ──────────
CLI_DIR = Path(__file__).resolve().parent
APP_DIR = CLI_DIR / "app"
sys.path.insert(0, str(APP_DIR))
@contextlib.contextmanager
def _suppress_native_io():
"""Redirect C-level stdout/stderr to /dev/null while inside the block.
Used to silence benign TVM/LLVM logs printed during mlc_llm import
(e.g. 'Using LLVM 19.1.7 with -mcpu=apple-m1 is not valid…').
Python-level exceptions still propagate normally."""
# Flush any buffered Python output BEFORE swapping the fds, otherwise
# pending writes get redirected to /dev/null and lost.
sys.stdout.flush()
sys.stderr.flush()
saved_out = os.dup(1)
saved_err = os.dup(2)
devnull = os.open(os.devnull, os.O_WRONLY)
try:
os.dup2(devnull, 1)
os.dup2(devnull, 2)
yield
finally:
# Flush again so anything written inside the block (which went to
# devnull at the C level) is also drained at the Python level.
sys.stdout.flush()
sys.stderr.flush()
os.dup2(saved_out, 1)
os.dup2(saved_err, 2)
os.close(saved_out)
os.close(saved_err)
os.close(devnull)
# ─────────────────────────────────────────────────────────────────────────────
# Helpers
# ─────────────────────────────────────────────────────────────────────────────
def _load_tier_map() -> dict:
"""Build {lower_tier_id: 'TierName__ModelName'} dynamically from
shared/repository.json. Insertion order from the JSON is preserved
(Light, Speed, Flash, Blaze, Ultra) so argparse help reads naturally."""
import json
repo_path = Path(__file__).resolve().parent / "shared" / "repository.json"
if not repo_path.exists():
return {}
try:
with open(repo_path, encoding="utf-8") as f:
repo = json.load(f)
except Exception:
return {}
out = {}
for key in repo:
parts = key.split("__")
if len(parts) >= 3:
tier_id = parts[0] # e.g. "Light"
prefix = "__".join(parts[:2]) # e.g. "Light__Qwen2.5-0.5B-Instruct"
out.setdefault(tier_id.lower(), prefix)
return out
TIER_KEYS = _load_tier_map()
TIERS = list(TIER_KEYS.keys()) # e.g. ["light", "speed", "flash", "blaze", "ultra"]
BACKENDS = ["mlx", "gguf", "mlc"]
def models_dir() -> Path:
"""Return the models directory — Application Support if it exists, otherwise
the local fallback (created on demand by `cli.py download`).
Always returns a Path; never raises. Use `p.exists()` to check presence."""
app_support = Path.home() / "Library" / "Application Support" / "MLBenchmark" / "models"
if app_support.exists():
return app_support
return CLI_DIR / "models"
def model_path(tier: str, backend: str) -> Path:
"""Resolve the on-disk folder for a (tier, backend) pair using the same
key→folder scheme used by download_model.py (Tier{N}/{BACKEND})."""
from utils import key_to_folder
key = f"{TIER_KEYS[tier]}__{backend.upper()}"
return models_dir() / key_to_folder(key)
def hr(char="─", width=60):
print(char * width)
def section(title: str):
print()
hr()
print(f" {title}")
hr()
def ok(msg): print(f" ✓ {msg}")
def fail(msg): print(f" ✗ {msg}")
def info(msg): print(f" {msg}")
def warn(msg): print(f" ⚠ {msg}")
# ─────────────────────────────────────────────────────────────────────────────
# Command: info
# ─────────────────────────────────────────────────────────────────────────────
def cmd_info(_args):
section("System")
info(f"Python {sys.version}")
info(f"macOS {platform.mac_ver()[0]} (darwin {platform.release()})")
info(f"Arch {platform.machine()}")
section("Venv / packages")
info(f"Executable {sys.executable}")
for pkg in ["mlc_llm", "mlx", "llama_cpp", "tvm"]:
try:
with _suppress_native_io():
mod = __import__(pkg)
ver = getattr(mod, "__version__", "?")
ok(f"{pkg} {ver}")
except ImportError as e:
fail(f"{pkg} — {e}")
section("Models on disk")
try:
mdir = models_dir()
info(f"Directory: {mdir}")
for tier in TIERS:
for backend in BACKENDS:
p = model_path(tier, backend)
if p.exists():
size_gb = sum(f.stat().st_size for f in p.rglob("*") if f.is_file()) / 1e9
ok(f"{tier:10s} {backend.upper():5s} {size_gb:.1f} GB → {p.name}")
else:
info(f"{tier:10s} {backend.upper():5s} not downloaded")
except FileNotFoundError as e:
fail(str(e))
section("Hardware (from utils.py)")
try:
from utils import detect_apple_chip, detect_memory_gb, get_available_tiers
chip = detect_apple_chip()
ram = detect_memory_gb()
ok(f"Chip: {chip} | RAM: {ram} GB")
tiers = get_available_tiers()
ok(f"Available tiers: {[t['name'] for t in tiers]}")
except Exception as e:
fail(f"utils.py unavailable: {e}")
# ─────────────────────────────────────────────────────────────────────────────
# Command: jit (MLC compile diagnostics only — no inference)
# ─────────────────────────────────────────────────────────────────────────────
def cmd_jit(args):
tier = args.tier.lower()
section(f"MLC JIT diagnostics — {tier}")
# 1. Import
info("1/5 Import mlc_llm…")
try:
with _suppress_native_io():
import mlc_llm
ok(f"mlc_llm imported ({mlc_llm.__file__})")
except ImportError as e:
fail(f"mlc_llm not available: {e}")
return
# 2. Import TVM
info("2/5 Import tvm…")
try:
with _suppress_native_io():
import tvm
from tvm.relax.block_builder import BlockBuilder
bb = BlockBuilder()
ok(f"tvm {getattr(tvm, '__version__', '?')}")
ok("BlockBuilder() instantiated without errors")
except AttributeError as e:
fail(f"BlockBuilder AttributeError → {e}")
fail("This is the bug that causes JIT crashes on macOS 26!")
info("The tvm installed in the venv is incompatible with darwin25.x")
info("Details and updates: https://mlbenchmark.app/docs/MLBW_W002")
return
except Exception as e:
fail(f"TVM error: {type(e).__name__}: {e}")
return
# 3. Verify model path
info("3/5 Verify model path…")
p = model_path(tier, "mlc")
if not p.exists():
fail(f"Model not found: {p}")
return
ok(f"Path: {p}")
cfg = p / "mlc-chat-config.json"
if cfg.exists():
ok("mlc-chat-config.json present")
else:
warn("mlc-chat-config.json missing")
# 4. Target detection
info("4/5 MLC target detection…")
try:
from mlc_llm.interface import jit as mlc_jit
import inspect
ok(f"mlc_llm.interface.jit loaded from {mlc_jit.__file__}")
except Exception as e:
fail(f"Cannot load jit.py: {e}")
# 5. JIT compilation test
info("5/5 Attempting JIT compilation (this is the critical step)…")
info(" Stdout/stderr from the compiler follow:")
print()
try:
from mlc_llm.interface.jit import jit as do_jit
t0 = time.time()
result = do_jit(
model_path=p,
overrides={},
device="metal",
)
elapsed = time.time() - t0
ok(f"JIT completed in {elapsed:.1f}s → {result}")
except RuntimeError as e:
elapsed = time.time() - t0
fail(f"JIT failed after {elapsed:.1f}s: {e}")
traceback.print_exc()
except Exception as e:
fail(f"Unexpected error: {type(e).__name__}: {e}")
traceback.print_exc()
# ─────────────────────────────────────────────────────────────────────────────
# Helper: download a model on demand (used by both `download` and `test`/`prompt`)
# ─────────────────────────────────────────────────────────────────────────────
def _ensure_model_downloaded(tier: str, backend: str) -> bool:
"""Make sure the model for (tier, backend) is on disk.
Returns True on success, False on failure. Prints progress via print()."""
key = f"{TIER_KEYS[tier]}__{backend.upper()}"
try:
from download_model import download_model as do_download
except ImportError as e:
fail(f"download_model unavailable: {e}")
return False
# download_model invokes the callback with (downloaded_bytes, total_bytes)
# roughly twice per second from a monitor thread. Throttle the printout.
last_logged = [0.0]
def _progress(downloaded_bytes: int, total_bytes: int):
mb_now = downloaded_bytes / (1024 * 1024)
# Print at most every ~50 MB so we don't spam stdout
if mb_now - last_logged[0] < 50 and downloaded_bytes < (total_bytes or 0):
return
last_logged[0] = mb_now
if total_bytes:
pct = 100.0 * downloaded_bytes / total_bytes
print(f" {mb_now:7.1f} MB ({pct:5.1f}%)", flush=True)
else:
print(f" {mb_now:7.1f} MB", flush=True)
try:
result = do_download(key, progress_callback=_progress)
except Exception as e:
fail(f"{type(e).__name__}: {e}")
traceback.print_exc()
return False
if result.get("success"):
ok(result.get("message", "Download completed."))
return True
fail(result.get("message", "Download failed."))
return False
# ─────────────────────────────────────────────────────────────────────────────
# Command: download (fetch model from Hugging Face explicitly)
# ─────────────────────────────────────────────────────────────────────────────
def cmd_download(args):
tier = args.tier.lower()
backend = args.backend.lower()
section(f"Download {backend.upper()} — {tier}")
info(f"Model key: {TIER_KEYS[tier]}__{backend.upper()}")
_ensure_model_downloaded(tier, backend)
# ─────────────────────────────────────────────────────────────────────────────
# Interactive REPL (default mode: --backend X --tier Y)
# ─────────────────────────────────────────────────────────────────────────────
def _load_runner(backend: str, model_dir: Path):
"""Load the right backend runner module, return (runner, repo_arg).
`repo_arg` is what gets passed to runner.run_prompt() — depends on backend."""
if backend == "mlx":
import model_runner_mlx as runner
return runner, str(model_dir)
if backend == "gguf":
import model_runner_gguf as runner
ggufs = list(model_dir.glob("*.gguf"))
if not ggufs:
raise RuntimeError(f"No .gguf file in {model_dir}")
return runner, str(ggufs[0])
if backend == "mlc":
with _suppress_native_io():
import model_runner_mlc as runner
# MLC may have flagged itself as incompatible at import time
if getattr(runner, "MLC_JIT_ERROR", None):
raise RuntimeError(
f"MLC backend not available: {runner.MLC_JIT_ERROR}\n"
f" See https://mlbenchmark.app/docs/MLBW_W002"
)
return runner, str(model_dir.resolve())
raise RuntimeError(f"Unknown backend: {backend}")
def cmd_chat(args):
"""Interactive REPL: download → load → warm-up → loop → release."""
tier = args.tier.lower()
backend = args.backend.lower()
section(f"Interactive — {backend.upper()} / {tier}")
# 1. Ensure model on disk
p = model_path(tier, backend)
if not p.exists():
info(f"Model not on disk → downloading {TIER_KEYS[tier]}__{backend.upper()}")
if not _ensure_model_downloaded(tier, backend):
return
p = model_path(tier, backend)
if not p.exists():
fail(f"Download finished but model still missing at {p}")
return
ok(f"Model at {p}")
# 2. Load runner
info(f"Loading {backend.upper()} runner…")
try:
runner, repo = _load_runner(backend, p)
except Exception as e:
fail(f"{type(e).__name__}: {e}")
traceback.print_exc()
return
ok("Runner loaded")
# 3. Warm-up (also forces the model to load fully into memory)
info("Warming up…")
t0 = time.time()
try:
runner.run_prompt("Say hello in one word.", 16, repo, ctx_max=4096)
except Exception as e:
fail(f"Warm-up failed: {type(e).__name__}: {e}")
traceback.print_exc()
_release_quietly(runner)
return
ok(f"Ready (warm-up in {time.time()-t0:.1f}s)")
# 4. REPL loop
print()
info("Type a prompt and press Enter. ':q' or Ctrl-D to exit.")
print()
try:
while True:
try:
line = input("> ")
except EOFError:
print()
break
except KeyboardInterrupt:
# Ctrl-C at the prompt: confirm exit
print()
break
line = line.strip()
if not line:
continue
if line in (":q", ":quit", ":exit"):
break
if line in (":h", ":help", ":?"):
print(" :q | :quit | :exit — leave the REPL")
print(" Ctrl-D — leave the REPL")
print(" Ctrl-C — interrupt current generation")
continue
t0 = time.time()
try:
out, reason, ntok = runner.run_prompt(
line, args.max_tokens, repo, ctx_max=4096
)
except KeyboardInterrupt:
print()
warn("Generation interrupted.")
continue
except Exception as e:
fail(f"{type(e).__name__}: {e}")
continue
elapsed = time.time() - t0
tps = ntok / elapsed if elapsed > 0 else 0
print()
print(out)
print()
ok(f"{tps:.1f} t/s ({ntok} tok in {elapsed:.1f}s, finish={reason})")
print()
finally:
# 5. Release the model
_release_quietly(runner)
def _release_quietly(runner):
"""Best-effort model unload — runners expose release_model() per the
documented interface."""
info("Releasing model…")
try:
if hasattr(runner, "release_model"):
runner.release_model()
ok("Done.")
except Exception as e:
warn(f"release_model() raised {type(e).__name__}: {e}")
# ─────────────────────────────────────────────────────────────────────────────
# Entry point
# ─────────────────────────────────────────────────────────────────────────────
def main():
parser = argparse.ArgumentParser(
description="ml-benchmark CLI — interactive REPL on local LLM backends",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog=__doc__,
)
# Top-level flags drive the default (interactive) mode
parser.add_argument("--backend", choices=BACKENDS,
help="backend for the interactive session")
parser.add_argument("--tier", choices=TIERS,
help="model tier for the interactive session")
parser.add_argument("--max-tokens", type=int, default=512, dest="max_tokens",
help="cap on tokens per response (default 512)")
sub = parser.add_subparsers(dest="cmd") # NOT required → no subcmd → REPL
# info
sub.add_parser("info", help="Hardware, packages, models on disk")
# download
p_dl = sub.add_parser("download", help="Download a model from Hugging Face")
p_dl.add_argument("backend", choices=BACKENDS)
p_dl.add_argument("tier", choices=TIERS)
# jit
p_jit = sub.add_parser("jit", help="Step-by-step MLC JIT diagnostics")
p_jit.add_argument("tier", choices=TIERS)
args = parser.parse_args()
dispatch = {
"info": cmd_info,
"download": cmd_download,
"jit": cmd_jit,
}
if args.cmd:
dispatch[args.cmd](args)
elif args.backend and args.tier:
cmd_chat(args)
else:
parser.print_help()
sys.exit(1)
print()
if __name__ == "__main__":
main()