cazyundee commited on
Commit
2456ebd
·
verified ·
1 Parent(s): a6debd5

Rewrite benchmark: use llama.cpp binary directly instead of llama-cpp-python

Browse files
Files changed (1) hide show
  1. app.py +111 -52
app.py CHANGED
@@ -386,7 +386,7 @@ from gradio.routes import App as GradioApp
386
 
387
  _orig_create_app = GradioApp.create_app
388
 
389
- # CPU LLM models for benchmarking
390
  _BENCHMARK_MODELS = [
391
  {
392
  "name": "Gemma 4 E4B",
@@ -412,82 +412,133 @@ _BENCHMARK_MODELS = [
412
  ]
413
  _BENCHMARK_CACHE = os.path.join(tempfile.gettempdir(), "llm_benchmark")
414
  _BENCHMARK_RESULTS = [] # cached after first run
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
415
 
416
 
417
  def _run_benchmark():
418
- """Run CPU benchmark on all models. Returns list of results."""
419
  global _BENCHMARK_RESULTS
420
  if _BENCHMARK_RESULTS:
421
  return _BENCHMARK_RESULTS
422
 
423
- # Install llama-cpp-python at runtime (not in requirements to avoid build issues)
424
- try:
425
- from llama_cpp import Llama
426
- except ImportError:
427
- _log("Benchmark: installing llama-cpp-python...")
428
- import subprocess
429
- # Try pre-built wheels first, fall back to source build
430
- try:
431
- subprocess.check_call(
432
- [sys.executable, "-m", "pip", "install", "llama-cpp-python>=0.4.0", "--only-binary=:all:"],
433
- stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
434
- )
435
- except subprocess.CalledProcessError:
436
- _log("Benchmark: no pre-built wheel, building from source...")
437
- subprocess.check_call(
438
- [sys.executable, "-m", "pip", "install", "llama-cpp-python>=0.4.0"],
439
- stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
440
- )
441
- from llama_cpp import Llama
442
 
443
  os.makedirs(_BENCHMARK_CACHE, exist_ok=True)
444
- results = []
445
  n_threads = _parse_cpu_count() or 8
 
 
446
 
447
  for model_info in _BENCHMARK_MODELS:
448
  result = {"name": model_info["name"], "status": "error"}
449
  try:
450
- _log(f"Benchmark: downloading {model_info['name']}...")
451
- from huggingface_hub import hf_hub_download
452
  model_path = hf_hub_download(
453
  repo_id=model_info["repo"],
454
  filename=model_info["file"],
455
  cache_dir=_BENCHMARK_CACHE,
456
  )
457
 
458
- _log(f"Benchmark: loading {model_info['name']} with {n_threads} threads...")
459
- t0 = time.time()
460
- llm = Llama(model_path=model_path, n_ctx=2048, n_threads=n_threads, n_batch=512, verbose=False)
461
- load_time = time.time() - t0
462
-
463
- _log(f"Benchmark: generating with {model_info['name']}...")
 
 
 
 
 
 
 
464
  t0 = time.time()
465
- output = llm(model_info["prompt"], max_tokens=128, temperature=0.7, top_p=0.9, echo=True)
466
- gen_time = time.time() - t0
467
-
468
- prompt_tokens = output["usage"]["prompt_tokens"]
469
- completion_tokens = output["usage"]["completion_tokens"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
470
 
471
  result.update({
472
  "status": "success",
473
- "load_time_sec": round(load_time, 1),
474
- "total_time_sec": round(gen_time, 2),
475
- "prompt_tokens": prompt_tokens,
476
- "completion_tokens": completion_tokens,
477
- "prompt_tokens_per_sec": round(prompt_tokens / gen_time, 1),
478
- "generation_tokens_per_sec": round(completion_tokens / gen_time, 1),
479
- "output": output["choices"][0]["text"],
480
  })
481
- _log(f"Benchmark: {model_info['name']} -> {result['generation_tokens_per_sec']} tok/s")
482
- del llm
483
-
484
- # Free disk cache between models
485
- import glob as _glob
486
- for f in _glob.glob(os.path.join(_BENCHMARK_CACHE, "**", "*.gguf"), recursive=True):
487
- try:
488
- os.unlink(f)
489
- except Exception:
490
- pass
491
 
492
  except Exception as e:
493
  result["error"] = str(e)
@@ -495,6 +546,14 @@ def _run_benchmark():
495
 
496
  results.append(result)
497
 
 
 
 
 
 
 
 
 
498
  _BENCHMARK_RESULTS = results
499
  return results
500
 
 
386
 
387
  _orig_create_app = GradioApp.create_app
388
 
389
+ # CPU LLM models for benchmarking via llama.cpp binary
390
  _BENCHMARK_MODELS = [
391
  {
392
  "name": "Gemma 4 E4B",
 
412
  ]
413
  _BENCHMARK_CACHE = os.path.join(tempfile.gettempdir(), "llm_benchmark")
414
  _BENCHMARK_RESULTS = [] # cached after first run
415
+ _LLAMA_CPP_BIN = None # path to downloaded llama-cli binary
416
+
417
+
418
+ def _ensure_llama_cpp():
419
+ """Download pre-built llama.cpp binary if not cached."""
420
+ global _LLAMA_CPP_BIN
421
+ if _LLAMA_CPP_BIN and os.path.isfile(_LLAMA_CPP_BIN):
422
+ return _LLAMA_CPP_BIN
423
+
424
+ import subprocess
425
+ import zipfile
426
+ import urllib.request
427
+
428
+ os.makedirs(_BENCHMARK_CACHE, exist_ok=True)
429
+ bin_dir = os.path.join(_BENCHMARK_CACHE, "llama_cpp")
430
+ os.makedirs(bin_dir, exist_ok=True)
431
+
432
+ llama_cli = os.path.join(bin_dir, "llama-cli")
433
+ if os.path.isfile(llama_cli):
434
+ _LLAMA_CPP_BIN = llama_cli
435
+ return llama_cli
436
+
437
+ _log("Benchmark: downloading llama.cpp binary...")
438
+ # Use a known stable release
439
+ release = "b5440"
440
+ url = f"https://github.com/ggml-org/llama.cpp/releases/download/{release}/llama-{release}-bin-ubuntu-x64.zip"
441
+ zip_path = os.path.join(bin_dir, "llama.zip")
442
+ urllib.request.urlretrieve(url, zip_path)
443
+
444
+ _log("Benchmark: extracting llama.cpp...")
445
+ with zipfile.ZipFile(zip_path) as zf:
446
+ for name in zf.namelist():
447
+ if name.endswith("llama-cli"):
448
+ # Extract to bin_dir
449
+ data = zf.read(name)
450
+ with open(llama_cli, "wb") as f:
451
+ f.write(data)
452
+ break
453
+ os.chmod(llama_cli, 0o755)
454
+ os.unlink(zip_path)
455
+
456
+ _LLAMA_CPP_BIN = llama_cli
457
+ _log(f"Benchmark: llama.cpp ready at {llama_cli}")
458
+ return llama_cli
459
 
460
 
461
  def _run_benchmark():
462
+ """Run CPU benchmark on all models using llama.cpp binary."""
463
  global _BENCHMARK_RESULTS
464
  if _BENCHMARK_RESULTS:
465
  return _BENCHMARK_RESULTS
466
 
467
+ import subprocess
468
+ from huggingface_hub import hf_hub_download
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
469
 
470
  os.makedirs(_BENCHMARK_CACHE, exist_ok=True)
471
+ llama_cli = _ensure_llama_cpp()
472
  n_threads = _parse_cpu_count() or 8
473
+ results = []
474
+ prompt = "Explain recursion in programming in 3 sentences."
475
 
476
  for model_info in _BENCHMARK_MODELS:
477
  result = {"name": model_info["name"], "status": "error"}
478
  try:
479
+ _log(f"Benchmark: downloading {model_info['name']} (~{model_info['size_gb']} GB)...")
 
480
  model_path = hf_hub_download(
481
  repo_id=model_info["repo"],
482
  filename=model_info["file"],
483
  cache_dir=_BENCHMARK_CACHE,
484
  )
485
 
486
+ _log(f"Benchmark: running {model_info['name']} with {n_threads} threads...")
487
+ cmd = [
488
+ llama_cli,
489
+ "-m", model_path,
490
+ "-t", str(n_threads),
491
+ "-c", "2048",
492
+ "-n", "128",
493
+ "--temp", "0.7",
494
+ "--top-p", "0.9",
495
+ "-p", prompt,
496
+ "--no-display-prompt",
497
+ "--log-disable",
498
+ ]
499
  t0 = time.time()
500
+ proc = subprocess.run(
501
+ cmd, capture_output=True, text=True, timeout=300,
502
+ )
503
+ wall_time = time.time() - t0
504
+ output_text = proc.stdout.strip()
505
+
506
+ # Parse llama.cpp stderr for timing info
507
+ # llama.cpp outputs: "llama_perf_sampler_print: ... prompt N tokens ... M tokens/s"
508
+ # and "llama_perf_sampler_print: ... eval N tokens ... M tokens/s"
509
+ prompt_tps = 0.0
510
+ gen_tps = 0.0
511
+ prompt_tok = 0
512
+ gen_tok = 0
513
+ for line in proc.stderr.splitlines():
514
+ if "prompt eval time" in line:
515
+ # e.g. "prompt eval time = 1234.56 ms / 12 tokens (102.88 ms per token, 9.72 tokens per second)"
516
+ import re
517
+ m = re.search(r"(\d+\.?\d*) tokens per second", line)
518
+ if m:
519
+ prompt_tps = float(m.group(1))
520
+ m2 = re.search(r"/ (\d+) tokens", line)
521
+ if m2:
522
+ prompt_tok = int(m2.group(1))
523
+ elif "eval time" in line and "prompt" not in line:
524
+ import re
525
+ m = re.search(r"(\d+\.?\d*) tokens per second", line)
526
+ if m:
527
+ gen_tps = float(m.group(1))
528
+ m2 = re.search(r"/ (\d+) tokens", line)
529
+ if m2:
530
+ gen_tok = int(m2.group(1))
531
 
532
  result.update({
533
  "status": "success",
534
+ "total_time_sec": round(wall_time, 2),
535
+ "prompt_tokens": prompt_tok,
536
+ "completion_tokens": gen_tok,
537
+ "prompt_tokens_per_sec": round(prompt_tps, 1),
538
+ "generation_tokens_per_sec": round(gen_tps, 1),
539
+ "output": output_text[:500],
 
540
  })
541
+ _log(f"Benchmark: {model_info['name']} -> {gen_tps:.1f} gen tok/s, {prompt_tps:.1f} prompt tok/s")
 
 
 
 
 
 
 
 
 
542
 
543
  except Exception as e:
544
  result["error"] = str(e)
 
546
 
547
  results.append(result)
548
 
549
+ # Free disk cache between models to make room for next
550
+ import glob as _glob
551
+ for f in _glob.glob(os.path.join(_BENCHMARK_CACHE, "**", "*.gguf"), recursive=True):
552
+ try:
553
+ os.unlink(f)
554
+ except Exception:
555
+ pass
556
+
557
  _BENCHMARK_RESULTS = results
558
  return results
559