Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/MojoLlama/blob/main/mojollama-bench-helper # MojoLlama Archived Mojo/MAX quantizer and serving research repository (read-only history) Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `MojoLlama / mojollama-bench-helper` 130 lines ยท 6211 bytes Raw Blame History 1 #!/usr/bin/env python3 2 """Benchmark helper: measure vLLM/SGLang/llama.cpp throughput for a model. 3 Outputs JSON: {"framework": "vllm", "model": "...", "pp": tok/s, "tg": tok/s, ...} 4 Usage: python3 bench_backend.py vllm --model meta-llama/Llama-3.2-1B 5 python3 bench_backend.py sglang --model meta-llama/Llama-3.2-1B 6 python3 bench_backend.py llamacpp --model /path/to/model.gguf 7 """ 8 import sys, json, os, subprocess, time 9 10 def bench_vllm(model: str) -> dict: 11 """Benchmark vLLM via its benchmark_latency.py script.""" 12 result = {"framework": "vllm", "model": model, "error": None} 13 try: 14 import vllm # noqa: F401 15 # Try using vllm's benchmark script 16 script = os.path.join(os.path.dirname(vllm.__file__), "..", "benchmarks", "benchmark_latency.py") 17 if os.path.exists(script): 18 out = subprocess.run( 19 [sys.executable, script, "--model", model, "--num-iters", "10", 20 "--num-prompts", "5", "--input-len", "512", "--output-len", "128"], 21 capture_output=True, text=True, timeout=120 22 ) 23 result["raw_output"] = out.stdout 24 # Parse: look for "avg latency" or throughput numbers 25 for line in out.stdout.split("\n"): 26 if "tok/s" in line.lower() or "throughput" in line.lower(): 27 result["throughput_line"] = line.strip() 28 else: 29 # Fallback: simple API benchmark 30 result["note"] = "benchmark_latency.py not found, using API" 31 except ImportError: 32 result["error"] = "vllm not installed" 33 except Exception as e: 34 result["error"] = str(e) 35 return result 36 37 def bench_sglang(model: str) -> dict: 38 """Benchmark SGLang via its benchmark scripts.""" 39 result = {"framework": "sglang", "model": model, "error": None} 40 try: 41 import sglang # noqa: F401 42 script = os.path.expanduser("~/sglang/benchmark/benchmark_serving.py") 43 if os.path.exists(script): 44 out = subprocess.run( 45 [sys.executable, script, "--model", model, "--num-prompts", "5", 46 "--request-rate", "1", "--backend", "sglang"], 47 capture_output=True, text=True, timeout=120 48 ) 49 result["raw_output"] = out.stdout 50 else: 51 result["note"] = "benchmark script not found" 52 except ImportError: 53 result["error"] = "sglang not installed" 54 except Exception as e: 55 result["error"] = str(e) 56 return result 57 58 def bench_llamacpp(model: str) -> dict: 59 """Benchmark llama.cpp via llama-bench.""" 60 result = {"framework": "llamacpp", "model": model, "error": None} 61 bench_bin = os.environ.get("LLAMA_BENCH", "/tmp/llama.cpp/build/bin/llama-bench") 62 if not os.path.exists(bench_bin): 63 result["error"] = f"llama-bench not found at {bench_bin}" 64 return result 65 try: 66 out = subprocess.run( 67 [bench_bin, "-m", model, "-n", "128", "-p", "512", "-t", os.environ.get("MOJO_BENCH_THREADS", "32")], 68 capture_output=True, text=True, timeout=120 69 ) 70 # Parse output: model|size|threads|pp|tg|... 71 for line in out.stdout.strip().split("\n"): 72 if "|" in line and model.split("/")[-1].split(".")[0] in line: 73 parts = line.split("|") 74 if len(parts) >= 5: 75 result["pp_tok_s"] = float(parts[3]) if parts[3] else 0 76 result["tg_tok_s"] = float(parts[4]) if parts[4] else 0 77 result["threads"] = int(parts[2]) if parts[2] else 32 78 break 79 result["raw_output"] = out.stdout.strip() 80 except Exception as e: 81 result["error"] = str(e) 82 return result 83 84 def get_gguf_dims(path: str) -> dict: 85 """Read GGUF header to extract model dimensions.""" 86 result = {"n_embd": 0, "n_layers": 0, "n_heads": 0, "n_kv_heads": 0, "vocab_size": 0} 87 try: 88 import gguf, numpy as np 89 _to_int = lambda x: int(x.item() if hasattr(x, 'item') else x) 90 reader = gguf.GGUFReader(path) 91 for key in ["llama.embedding_length", "bert.embedding_length", "gpt2.embedding_length", 92 "SSM.embedding_length", "t5.embedding_length", "mpt.embedding_length"]: 93 f = reader.fields.get(key) 94 if f: result["n_embd"] = _to_int(f.parts[-1]); break 95 for fname in ["llama.block_count", "gpt2.block_count", "bert.block_count", "SSM.block_count", "mpt.block_count"]: 96 f = reader.fields.get(fname) 97 if f: result["n_layers"] = _to_int(f.parts[-1]); break 98 for fname in ["llama.attention.head_count", "gpt2.attention.head_count", "mpt.attention.head_count"]: 99 f = reader.fields.get(fname) 100 if f: result["n_heads"] = _to_int(f.parts[-1]); break 101 for fname in ["llama.attention.head_count_kv", "gpt2.attention.head_count_kv"]: 102 f = reader.fields.get(fname) 103 if f: result["n_kv_heads"] = _to_int(f.parts[-1]); break 104 for fname in ["llama.vocab_size", "gpt2.vocab_size", "bert.vocab_size"]: 105 f = reader.fields.get(fname) 106 if f: result["vocab_size"] = _to_int(f.parts[-1]); break 107 arch_f = reader.fields.get("general.architecture") 108 if arch_f: result["arch"] = str(bytes(arch_f.parts[-1]).decode('utf-8')) 109 for k in result: 110 if isinstance(result[k], (np.integer, np.floating)): result[k] = _to_int(result[k]) 111 except Exception as e: 112 result["error"] = str(e) 113 return result 114 115 if __name__ == "__main__": 116 if len(sys.argv) < 3: 117 print(json.dumps({"error": "Usage: bench_backend.py --model "})) 118 sys.exit(1) 119 backend = sys.argv[1] 120 model = sys.argv[sys.argv.index("--model") + 1] if "--model" in sys.argv else "" 121 if backend == "vllm": 122 print(json.dumps(bench_vllm(model))) 123 elif backend == "sglang": 124 print(json.dumps(bench_sglang(model))) 125 elif backend == "llamacpp": 126 print(json.dumps(bench_llamacpp(model))) 127 elif backend == "ggufinfo": 128 print(json.dumps(get_gguf_dims(model))) 129 else: 130 print(json.dumps({"error": f"Unknown backend: {backend}"}))