interplane.Get Omega
Read in your language

MojoLlama

Archived Mojo/MAX quantizer and serving research repository (read-only history)

Brought by drakestapleton

branch main Branches Tags History

MojoLlama / src / mojollama / detect.py

548 lines · 18661 bytes Raw Blame History
1#!/usr/bin/env python3
2"""MojoLlama hardware detection — CPU, GPU, and accelerator capabilities.
3
4Detects:
5 - CPU features: AVX2, AVX512, AMX, NEON, SVE, FMA
6 - CPU topology: physical cores, SMT threads, NUMA nodes, cache
7 - GPU backends: NVIDIA CUDA (with version), AMD ROCm, Intel SYCL, Vulkan
8 - Apple Metal / MPS
9 - Hybrid offloading capability
10
11Usage:
12 from mojollama.detect import detect_hardware, HardwareInfo
13 hw = detect_hardware()
14 print(hw.summary())
15 print(hw.recommended_flags())
16"""
17
18import os
19import sys
20import re
21import json
22import subprocess
23import multiprocessing as mp
24from pathlib import Path
25from typing import Dict, List, Optional, Any
26
27
28def read_proc_cpuinfo() -> Dict[str, Any]:
29 """Read /proc/cpuinfo and extract CPU features."""
30 info = {"flags": set(), "vendor": "unknown", "model": "unknown",
31 "cores": mp.cpu_count(), "phys_cores": 0, "sockets": 0}
32
33 try:
34 with open("/proc/cpuinfo") as f:
35 text = f.read()
36
37 # Count physical cores (unique core ids per socket)
38 cores_seen = set()
39 socket = 0
40 phys_id = -1
41 core_id = -1
42
43 for line in text.split("\n"):
44 if line.startswith("processor"):
45 socket += 1
46 if line.startswith("physical id"):
47 phys_id = int(line.split(":")[1].strip())
48 if line.startswith("core id"):
49 core_id = int(line.split(":")[1].strip())
50 cores_seen.add((phys_id, core_id))
51 if line.startswith("flags"):
52 info["flags"] = set(line.split(":")[1].strip().split())
53 if line.startswith("model name"):
54 info["model"] = line.split(":")[1].strip()
55 if line.startswith("vendor_id"):
56 info["vendor"] = line.split(":")[1].strip()
57
58 info["phys_cores"] = len(cores_seen)
59 info["sockets"] = max(1, phys_id + 1) if phys_id >= 0 else 1
60
61 except FileNotFoundError:
62 # macOS or non-Linux
63 pass
64
65 return info
66
67
68def detect_cpu_features(cpuinfo: Dict[str, Any]) -> Dict[str, Any]:
69 """Detect CPU capabilities from flags."""
70 flags = cpuinfo.get("flags", set())
71
72 features = {
73 "arch": "x86_64", # default
74 "avx2": "avx2" in flags,
75 "avx512f": "avx512f" in flags,
76 "avx512_vnni": "avx512_vnni" in flags,
77 "avx512_bf16": "avx512_bf16" in flags,
78 "amx_int8": "amx_int8" in flags,
79 "amx_bf16": "amx_bf16" in flags,
80 "fma": "fma" in flags,
81 "f16c": "f16c" in flags,
82 "bmi2": "bmi2" in flags,
83 "sse3": "sse3" in flags,
84 "ssse3": "ssse3" in flags,
85 "neon": False,
86 "sve": False,
87 "apple_silicon": False,
88 }
89
90 # Detect architecture
91 if "avx512f" in flags:
92 features["arch"] = "x86_64_avx512"
93 elif "avx2" in flags:
94 features["arch"] = "x86_64_avx2"
95 elif "sse3" in flags:
96 features["arch"] = "x86_64"
97
98 # Detect ARM
99 try:
100 with open("/proc/cpuinfo") as f:
101 text = f.read()
102 if "CPU architecture: 8" in text or "aarch64" in text:
103 features["arch"] = "aarch64"
104 features["neon"] = True
105 if "sve" in text:
106 features["sve"] = True
107 except: pass
108
109 # macOS Apple Silicon
110 if sys.platform == "darwin":
111 try:
112 result = subprocess.run(["sysctl", "-n", "machdep.cpu.brand_string"],
113 capture_output=True, text=True, timeout=5)
114 if "Apple" in result.stdout:
115 features["arch"] = "aarch64_apple"
116 features["apple_silicon"] = True
117 features["neon"] = True
118 except: pass
119
120 return features
121
122
123def detect_nvidia_gpu() -> Optional[Dict[str, Any]]:
124 """Detect NVIDIA GPU and CUDA version."""
125 try:
126 # nvidia-smi for GPU info
127 result = subprocess.run(
128 ["nvidia-smi", "--query-gpu=name,memory.total,compute_cap",
129 "--format=csv,noheader,nounits"],
130 capture_output=True, text=True, timeout=10
131 )
132 if result.returncode != 0:
133 return None
134
135 gpus = []
136 for line in result.stdout.strip().split("\n"):
137 if not line.strip():
138 continue
139 parts = [p.strip() for p in line.split(",")]
140 gpus.append({
141 "name": parts[0] if len(parts) > 0 else "unknown",
142 "vram_mb": int(parts[1]) if len(parts) > 1 and parts[1].isdigit() else 0,
143 "compute_cap": parts[2] if len(parts) > 2 else "?",
144 })
145
146 # CUDA version
147 cuda_version = None
148 try:
149 r = subprocess.run(["nvcc", "--version"], capture_output=True, text=True, timeout=5)
150 m = re.search(r"release (\d+\.\d+)", r.stdout)
151 if m:
152 cuda_version = m.group(1)
153 except: pass
154
155 if not cuda_version:
156 try:
157 r = subprocess.run(["nvidia-smi"], capture_output=True, text=True, timeout=10)
158 m = re.search(r"CUDA Version:\s+(\d+\.\d+)", r.stdout)
159 if m:
160 cuda_version = m.group(1)
161 except: pass
162
163 return {
164 "available": True,
165 "count": len(gpus),
166 "gpus": gpus,
167 "cuda_version": cuda_version,
168 "cuda_major": int(cuda_version.split(".")[0]) if cuda_version else None,
169 }
170 except FileNotFoundError:
171 return None
172 except Exception:
173 return None
174
175
176def detect_rocm() -> Optional[Dict[str, Any]]:
177 """Detect AMD ROCm."""
178 try:
179 # Check for rocminfo
180 result = subprocess.run(["rocminfo"], capture_output=True, text=True, timeout=10)
181 if result.returncode != 0:
182 return None
183
184 gpu_count = 0
185 gpu_names = []
186 for line in result.stdout.split("\n"):
187 if "Name:" in line and "GPU" in result.stdout.split(line)[0] if False else False:
188 pass
189 m = re.search(r'Name:\s+(AMD\s+\S+)', line)
190 if m:
191 gpu_names.append(m.group(1))
192 gpu_count += 1
193
194 if not gpu_names:
195 gpu_count = result.stdout.count("GPU Agent")
196 if gpu_count == 0:
197 return None
198
199 return {
200 "available": True,
201 "count": max(1, gpu_count),
202 "gpus": gpu_names if gpu_names else ["AMD GPU"],
203 }
204 except FileNotFoundError:
205 return None
206
207
208def detect_sycl() -> Optional[Dict[str, Any]]:
209 """Detect Intel SYCL/oneAPI."""
210 try:
211 result = subprocess.run(["sycl-ls"], capture_output=True, text=True, timeout=10)
212 if result.returncode != 0:
213 return None
214 devices = [line.strip() for line in result.stdout.split("\n") if line.strip()]
215 return {
216 "available": len(devices) > 0,
217 "devices": devices,
218 }
219 except FileNotFoundError:
220 return None
221
222
223def detect_vulkan() -> Optional[Dict[str, Any]]:
224 """Detect Vulkan devices."""
225 try:
226 result = subprocess.run(["vulkaninfo", "--summary"],
227 capture_output=True, text=True, timeout=15)
228 if result.returncode != 0:
229 return None
230 devices = re.findall(r'GPU\d+:\s+(\S+)', result.stdout)
231 return {
232 "available": len(devices) > 0,
233 "devices": devices,
234 }
235 except FileNotFoundError:
236 return None
237
238
239def detect_apple_metal() -> Optional[Dict[str, Any]]:
240 """Detect Apple Metal / MPS."""
241 try:
242 # Check for Metal framework
243 result = subprocess.run(
244 ["system_profiler", "SPHardwareDataType"],
245 capture_output=True, text=True, timeout=10
246 )
247 has_apple_gpu = "Apple" in result.stdout and ("GPU" in result.stdout or "Chip" in result.stdout)
248
249 # Check MPS availability via Python
250 mps_available = False
251 try:
252 import torch
253 mps_available = torch.backends.mps.is_available()
254 except: pass
255
256 return {
257 "available": has_apple_gpu or mps_available,
258 "mps_available": mps_available,
259 }
260 except FileNotFoundError:
261 return None
262
263
264def detect_llamacpp_backends() -> Dict[str, bool]:
265 """Check which llama.cpp backends are compiled in."""
266 backends = {"metal": False, "cuda": False, "vulkan": False, "sycl": False}
267
268 # Check the built llama-server binary
269 binary = "/tmp/llama.cpp/build/bin/llama-server"
270 if not os.path.exists(binary):
271 return backends
272
273 try:
274 result = subprocess.run([binary, "--help"], capture_output=True, text=True, timeout=5)
275 help_text = result.stdout + result.stderr
276
277 # Check for backend-specific flags
278 backends["cuda"] = "--gpu-layers" in help_text or "n-gpu-layers" in help_text
279 backends["metal"] = "metal" in help_text.lower()
280 backends["vulkan"] = "vulkan" in help_text.lower()
281 backends["sycl"] = "sycl" in help_text.lower()
282 except: pass
283
284 return backends
285
286
287def detect_moe_capability() -> Dict[str, Any]:
288 """Check if models can use MoE-specific offloading."""
289 binary = "/tmp/llama.cpp/build/bin/llama-server"
290 has_moe_flag = False
291 try:
292 result = subprocess.run([binary, "--help"], capture_output=True, text=True, timeout=5)
293 has_moe_flag = "--n-cpu-moe" in (result.stdout + result.stderr) or "-ncmoe" in (result.stdout + result.stderr)
294 except: pass
295
296 return {
297 "expert_offloading": has_moe_flag,
298 "flag": "-ncmoe" if has_moe_flag else None,
299 }
300
301
302def detect_hardware() -> Dict[str, Any]:
303 """Full hardware detection. Returns complete system capabilities."""
304 cpuinfo = read_proc_cpuinfo()
305 cpu_features = detect_cpu_features(cpuinfo)
306 nvidia = detect_nvidia_gpu()
307 rocm = detect_rocm()
308 sycl = detect_sycl()
309 vulkan = detect_vulkan()
310 metal = detect_apple_metal()
311 llama = detect_llamacpp_backends()
312 moe = detect_moe_capability()
313
314 hw = {
315 "cpu": {
316 "model": cpuinfo["model"],
317 "vendor": cpuinfo["vendor"],
318 "logical_cores": cpuinfo["cores"],
319 "physical_cores": cpuinfo["phys_cores"],
320 "sockets": cpuinfo["sockets"],
321 "smt": cpuinfo["cores"] > cpuinfo["phys_cores"],
322 "smt_threads": cpuinfo["cores"] // max(1, cpuinfo["phys_cores"]),
323 "features": cpu_features,
324 "llama_cpu_mask": _generate_cpu_mask(cpuinfo),
325 },
326 "gpu": {
327 "nvidia": nvidia,
328 "rocm": rocm,
329 "sycl": sycl,
330 "vulkan": vulkan,
331 "metal": metal,
332 "primary": _detect_primary_gpu(nvidia, rocm, sycl, vulkan, metal),
333 },
334 "llamacpp_backends": llama,
335 "moe": moe,
336 "os": sys.platform,
337 }
338
339 return hw
340
341
342def _generate_cpu_mask(cpuinfo: Dict[str, Any]) -> str:
343 """Generate CPU mask for physical cores only (no SMT)."""
344 n_phys = cpuinfo.get("phys_cores", 0)
345 if n_phys == 0:
346 return "0x0"
347 # Mask with lowest n_phys bits set
348 mask = (1 << n_phys) - 1
349 return f"0x{mask:016X}"
350
351
352def _detect_primary_gpu(nvidia, rocm, sycl, vulkan, metal) -> Optional[str]:
353 """Determine the primary GPU backend."""
354 if nvidia and nvidia.get("available"):
355 cuda_major = nvidia.get("cuda_major")
356 if cuda_major:
357 return f"cuda_{cuda_major}"
358 return "cuda"
359 if rocm and rocm.get("available"):
360 return "rocm"
361 if sycl and sycl.get("available"):
362 return "sycl"
363 if vulkan and vulkan.get("available"):
364 return "vulkan"
365 if metal and metal.get("available"):
366 return "metal"
367 return None
368
369
370def recommend_llamacpp_flags(hw: Dict[str, Any], model_path: str = "") -> Dict[str, Any]:
371 """Generate optimal llama.cpp flags based on hardware detection."""
372 cpu = hw.get("cpu", {})
373 cpu_feat = cpu.get("features", {})
374 gpu = hw.get("gpu", {})
375 primary = gpu.get("primary")
376 llama_b = hw.get("llamacpp_backends", {})
377
378 flags = {
379 "threads": cpu.get("physical_cores", 32),
380 "threads_batch": max(1, cpu.get("physical_cores", 32) // 2),
381 "batch_size": 4096 if cpu_feat.get("arch") in ("x86_64_avx2", "x86_64_avx512") else 2048,
382 "ubatch_size": 512,
383 "n_parallel": min(cpu.get("physical_cores", 32), 64),
384 "mlock": True,
385 "cont_batching": True,
386 "flash_attn": cpu_feat.get("f16c", False),
387 "cpu_mask": cpu.get("llama_cpu_mask", "0x0"),
388 }
389
390 # GPU offloading
391 if primary and primary.startswith("cuda"):
392 cuda_major = int(primary.split("_")[1]) if "_" in primary else 12
393 flags["gpu"] = "cuda"
394 flags["gpu_layers"] = -1 # offload all layers
395 flags["cuda_version"] = f"cuda_{cuda_major}"
396 flags["cuda_arch"] = f"sm_{80 if cuda_major >= 11 else 70}"
397
398 # CUDA-specific tuning
399 if cuda_major >= 13:
400 flags["cuda_fusion"] = True # hypothetical future feature
401 elif cuda_major >= 12:
402 flags["flash_attn"] = True # CUDA 12 has better FA support
403 elif cuda_major == 11:
404 flags["flash_attn"] = False # FA on CUDA 11 can be slower
405
406 elif primary == "rocm":
407 flags["gpu"] = "rocm"
408 flags["gpu_layers"] = -1
409 flags["flash_attn"] = True
410
411 elif primary == "metal":
412 flags["gpu"] = "metal"
413 flags["gpu_layers"] = -1 # Apple Silicon unified memory — offload everything
414
415 elif primary == "vulkan":
416 flags["gpu"] = "vulkan"
417 flags["gpu_layers"] = -1 if llama_b.get("vulkan") else 0
418
419 elif primary == "sycl":
420 flags["gpu"] = "sycl"
421 flags["gpu_layers"] = -1 if llama_b.get("sycl") else 0
422
423 # MoE-specific: if n_parallel is high and GPU is weak, keep experts on CPU
424 if hw.get("moe", {}).get("expert_offloading"):
425 flags["n_cpu_moe_experts"] = 0 # 0 = auto, let llama.cpp decide
426
427 # CPU pinning only useful without GPU offloading (or partial offload)
428 if not primary or flags.get("gpu_layers", 0) == 0:
429 flags["cpu_mask"] = cpu.get("llama_cpu_mask", "0x0")
430 else:
431 flags["cpu_mask"] = "0x0" # no pinning when GPU is active
432
433 return flags
434
435
436def format_recommendation(flags: Dict[str, Any]) -> str:
437 """Format recommended flags as a llama-server command."""
438 cmd_parts = ["llama-server", "-m", "model.gguf", "-c", "4096"]
439
440 mapping = {
441 "threads": "-t",
442 "threads_batch": "-tb",
443 "batch_size": "-b",
444 "ubatch_size": "-ub",
445 "n_parallel": "-np",
446 "gpu_layers": "-ngl",
447 "n_cpu_moe_experts": "-ncmoe",
448 }
449
450 for key, flag in mapping.items():
451 val = flags.get(key)
452 if val is not None and val != 0:
453 cmd_parts.extend([flag, str(val)])
454
455 if flags.get("mlock"):
456 cmd_parts.append("--mlock")
457 if flags.get("cont_batching"):
458 cmd_parts.append("--cont-batching")
459 if flags.get("flash_attn"):
460 cmd_parts.extend(["-fa", "1"])
461
462 cpu_mask = flags.get("cpu_mask", "0x0")
463 if cpu_mask and cpu_mask != "0x0":
464 cmd_parts.extend(["-C", cpu_mask])
465
466 return " ".join(cmd_parts)
467
468
469def summary(hw: Dict[str, Any]) -> str:
470 """Human-readable summary of detected hardware."""
471 cpu = hw["cpu"]
472 feat = cpu["features"]
473 gpu_info = hw["gpu"]
474
475 lines = [
476 "═══ Hardware Detection ═══",
477 f"CPU: {cpu['model']}",
478 f" {cpu['logical_cores']} logical / {cpu['physical_cores']} physical cores",
479 f" {cpu['sockets']} socket(s), SMT: {cpu['smt']} ({cpu['smt_threads']}×)",
480 f" Arch: {feat['arch']}",
481 ]
482
483 # CPU features
484 feat_list = []
485 if feat["avx512f"]: feat_list.append("AVX-512F")
486 if feat["avx512_vnni"]: feat_list.append("AVX-512-VNNI")
487 if feat["avx2"]: feat_list.append("AVX2")
488 if feat["fma"]: feat_list.append("FMA")
489 if feat["f16c"]: feat_list.append("F16C")
490 if feat["amx_int8"]: feat_list.append("AMX-INT8")
491 if feat["neon"]: feat_list.append("NEON")
492 if feat["apple_silicon"]: feat_list.append("Apple Silicon")
493 if feat_list:
494 lines.append(f" ISA: {', '.join(feat_list)}")
495
496 # GPU
497 nv = gpu_info.get("nvidia")
498 if nv and nv.get("available"):
499 for g in nv.get("gpus", []):
500 lines.append(f"GPU: NVIDIA {g['name']} ({g.get('vram_mb', '?')} MB VRAM, CC {g.get('compute_cap', '?')})")
501 if nv.get("cuda_version"):
502 lines.append(f" CUDA {nv['cuda_version']}")
503
504 rocm = gpu_info.get("rocm")
505 if rocm and rocm.get("available"):
506 lines.append(f"GPU: AMD ROCm ({rocm.get('count', '?')} devices)")
507
508 metal = gpu_info.get("metal")
509 if metal and metal.get("available"):
510 lines.append(f"GPU: Apple Metal (MPS: {metal.get('mps_available', False)})")
511
512 sycl_d = gpu_info.get("sycl")
513 if sycl_d and sycl_d.get("available"):
514 lines.append(f"GPU: Intel SYCL ({len(sycl_d.get('devices', []))} devices)")
515
516 vulkan_d = gpu_info.get("vulkan")
517 if vulkan_d and vulkan_d.get("available"):
518 lines.append(f"GPU: Vulkan ({len(vulkan_d.get('devices', []))} devices)")
519
520 if not any([
521 nv and nv.get("available"),
522 rocm and rocm.get("available"),
523 metal and metal.get("available"),
524 sycl_d and sycl_d.get("available"),
525 vulkan_d and vulkan_d.get("available"),
526 ]):
527 lines.append("GPU: None detected (CPU-only mode)")
528
529 lines.append("═══════════════════════")
530 return "\n".join(lines)
531
532
533# ─── CLI ──────────────────────────────────────────────────────────────
534
535if __name__ == "__main__":
536 hw = detect_hardware()
537 print(summary(hw))
538 print()
539
540 flags = recommend_llamacpp_flags(hw)
541 print("Recommended llama-server flags:")
542 print(f" {format_recommendation(flags)}")
543 print()
544
545 # Detect AVX2 vs AVX512 performance (if applicable)
546 if hw["cpu"]["features"]["avx512f"]:
547 print("⚠️ AVX-512 detected — llama.cpp may be faster with AVX2-only build")
548 print(" (AVX-512 can throttle CPU frequency on some processors)")