Download bench.py from new-arc/opaiv2: direct link, hf CLI and curl.
- Browser
- Download file 5.42 kB
-
https://huggingface.co/spaces/new-arc/opaiv2/resolve/main/bench.py
- Command line
-
hf download hf://spaces/new-arc/opaiv2/bench.py
-
curl -L -o bench.py https://huggingface.co/spaces/new-arc/opaiv2/resolve/main/bench.py
5.42 kB
| import argparse | |
| import gc | |
| import json | |
| import os | |
| import time | |
| from typing import Any, Dict, List, Optional | |
| from huggingface_hub import hf_hub_download | |
| def _load_model_path(repo: str, filename: str) -> str: | |
| print(f"Downloading {repo} / {filename} ...") | |
| path = hf_hub_download(repo_id=repo, filename=filename) | |
| print(f"Model downloaded to {path}") | |
| return path | |
| def _run_once(model_path: str, prompt: str, max_tokens: int, cfg: Dict[str, Any]) -> Dict[str, Any]: | |
| from llama_cpp import Llama | |
| t0 = time.perf_counter() | |
| llm = Llama( | |
| model_path=model_path, | |
| n_ctx=cfg["n_ctx"], | |
| n_threads=cfg["n_threads"], | |
| n_threads_batch=cfg["n_threads_batch"], | |
| n_batch=cfg["n_batch"], | |
| n_ubatch=cfg["n_ubatch"], | |
| use_mmap=cfg["use_mmap"], | |
| use_mlock=cfg["use_mlock"], | |
| numa=cfg["numa"], | |
| flash_attn=cfg["flash_attn"], | |
| n_gpu_layers=0, | |
| verbose=False, | |
| ) | |
| stream = llm.create_completion( | |
| prompt=prompt, | |
| max_tokens=max_tokens, | |
| temperature=0.7, | |
| top_p=0.9, | |
| stream=True, | |
| ) | |
| first = None | |
| chunk_count = 0 | |
| for _ in stream: | |
| chunk_count += 1 | |
| if first is None: | |
| first = time.perf_counter() | |
| t1 = time.perf_counter() | |
| ttft = (first - t0) if first is not None else (t1 - t0) | |
| total = t1 - t0 | |
| # Help the GC release memory between runs. | |
| del llm | |
| gc.collect() | |
| return { | |
| "ttft_s": ttft, | |
| "total_s": total, | |
| "chunk_count": chunk_count, | |
| } | |
| def _default_configs() -> List[Dict[str, Any]]: | |
| base = { | |
| "name": "base", | |
| "n_ctx": 1024, | |
| "n_threads": 2, | |
| "n_threads_batch": 2, | |
| "n_batch": 128, | |
| "n_ubatch": 64, | |
| "use_mmap": False, | |
| "use_mlock": True, | |
| "numa": False, | |
| "flash_attn": False, | |
| } | |
| return [ | |
| base, | |
| {**base, "name": "mmap_on", "use_mmap": True, "use_mlock": False}, | |
| {**base, "name": "threads_1", "n_threads": 1}, | |
| {**base, "name": "small_batch", "n_batch": 64, "n_ubatch": 32}, | |
| {**base, "name": "flash_on", "flash_attn": True}, | |
| {**base, "name": "batch_threads_1", "n_threads_batch": 1}, | |
| ] | |
| def _pick_best(results: List[Dict[str, Any]]) -> Optional[Dict[str, Any]]: | |
| ok = [r for r in results if r.get("error") is None] | |
| if not ok: | |
| return None | |
| return sorted(ok, key=lambda r: (r["total_s"], r["ttft_s"]))[0] | |
| def _env_lines(cfg: Dict[str, Any]) -> List[str]: | |
| return [ | |
| f"N_CTX={cfg['n_ctx']}", | |
| f"N_THREADS={cfg['n_threads']}", | |
| f"N_THREADS_BATCH={cfg['n_threads_batch']}", | |
| f"N_BATCH={cfg['n_batch']}", | |
| f"N_UBATCH={cfg['n_ubatch']}", | |
| f"USE_MMAP={'1' if cfg['use_mmap'] else '0'}", | |
| f"USE_MLOCK={'1' if cfg['use_mlock'] else '0'}", | |
| f"NUMA={'1' if cfg['numa'] else '0'}", | |
| f"FLASH_ATTN={'1' if cfg['flash_attn'] else '0'}", | |
| ] | |
| def main() -> int: | |
| parser = argparse.ArgumentParser(description="Benchmark llama-cpp-python configs on CPU.") | |
| parser.add_argument("--repo", default=os.environ.get("GGUF_REPO", "Qwen/Qwen2.5-1.5B-Instruct-GGUF")) | |
| parser.add_argument("--file", default=os.environ.get("GGUF_FILE", "qwen2.5-1.5b-instruct-q4_k_m.gguf")) | |
| parser.add_argument("--prompt", default="Write a short answer about CPU inference.", help="Prompt text.") | |
| parser.add_argument("--max-tokens", type=int, default=128) | |
| parser.add_argument("--warmup", action="store_true", help="Run one warmup pass on base config.") | |
| parser.add_argument("--repeats", type=int, default=1) | |
| parser.add_argument("--write-env", default=".env.recommended", help="Write best config to this file.") | |
| args = parser.parse_args() | |
| model_path = _load_model_path(args.repo, args.file) | |
| configs = _default_configs() | |
| results: List[Dict[str, Any]] = [] | |
| if args.warmup: | |
| try: | |
| _run_once(model_path, args.prompt, args.max_tokens, configs[0]) | |
| except Exception as exc: | |
| print(f"Warmup failed: {exc}") | |
| for cfg in configs: | |
| for i in range(args.repeats): | |
| label = f"{cfg['name']}-run{i+1}" | |
| print(f"Running {label} ...") | |
| record = { | |
| "name": cfg["name"], | |
| "run": i + 1, | |
| "config": cfg, | |
| "error": None, | |
| } | |
| try: | |
| metrics = _run_once(model_path, args.prompt, args.max_tokens, cfg) | |
| record.update(metrics) | |
| print(f" ttft={metrics['ttft_s']:.3f}s total={metrics['total_s']:.3f}s chunks={metrics['chunk_count']}") | |
| except Exception as exc: | |
| record["error"] = str(exc) | |
| print(f" error={exc}") | |
| results.append(record) | |
| best = _pick_best(results) | |
| print("\nSummary:") | |
| print(json.dumps(results, indent=2)) | |
| if best is None: | |
| print("\nNo successful runs.") | |
| return 1 | |
| print("\nBest config:") | |
| print(json.dumps(best, indent=2)) | |
| env_lines = _env_lines(best["config"]) | |
| with open(args.write_env, "w", encoding="utf-8") as f: | |
| f.write("\n".join(env_lines) + "\n") | |
| print(f"\nWrote {args.write_env}") | |
| print("Apply these as env vars and restart the app:") | |
| for line in env_lines: | |
| print(line) | |
| return 0 | |
| if __name__ == "__main__": | |
| raise SystemExit(main()) | |