MojoLlama
Archived Mojo/MAX quantizer and serving research repository (read-only history)
Brought by drakestapleton
MojoLlama / src / mojollama / model / device.py
| 1 | """ |
| 2 | MojoLlama — Device abstraction layer with Intel Arc GPU support. |
| 3 | |
| 4 | Auto-detects available compute devices and provides a unified backend interface. |
| 5 | Supports Intel Arc (via Intel SYCL / dpctl / dpnp), NVIDIA CUDA, AMD ROCm, and CPU. |
| 6 | |
| 7 | Usage: |
| 8 | from mojollama.model.device import get_device, DeviceType |
| 9 | |
| 10 | device = get_device() # auto-detect best available |
| 11 | device = get_device('intel_arc') # force Intel Arc |
| 12 | device = get_device('cpu') # force CPU |
| 13 | |
| 14 | arr = device.to_device(numpy_array) # move array to device memory |
| 15 | result = device.matmul(a, b) # device-aware matmul |
| 16 | numpy_result = device.to_cpu(result) # bring back to host |
| 17 | """ |
| 18 | |
| 19 | import enum |
| 20 | import logging |
| 21 | import os |
| 22 | from typing import Optional, Callable |
| 23 | |
| 24 | logger = logging.getLogger(__name__) |
| 25 | |
| 26 | |
| 27 | class DeviceType(enum.Enum): |
| 28 | """Supported device types.""" |
| 29 | CPU = 'cpu' |
| 30 | NVIDIA_CUDA = 'nvidia' |
| 31 | AMD_ROCM = 'amd' |
| 32 | INTEL_ARC = 'intel_arc' |
| 33 | |
| 34 | |
| 35 | class DeviceCapability: |
| 36 | """Hardware capabilities of a compute device.""" |
| 37 | |
| 38 | def __init__(self, name: str, vram_gb: float = 0, compute_units: int = 0, |
| 39 | supports_fp16: bool = False, supports_bf16: bool = False, |
| 40 | max_work_group_size: int = 0): |
| 41 | self.name = name |
| 42 | self.vram_gb = vram_gb |
| 43 | self.compute_units = compute_units |
| 44 | self.supports_fp16 = supports_fp16 |
| 45 | self.supports_bf16 = supports_bf16 |
| 46 | self.max_work_group_size = max_work_group_size |
| 47 | |
| 48 | def __repr__(self): |
| 49 | return (f"DeviceCapability(name='{self.name}', vram={self.vram_gb}GB, " |
| 50 | f"compute_units={self.compute_units}, fp16={self.supports_fp16})") |
| 51 | |
| 52 | |
| 53 | class DeviceBackend: |
| 54 | """Base class for all device backends. Subclass per device type.""" |
| 55 | |
| 56 | device_type: DeviceType = DeviceType.CPU |
| 57 | capability: Optional[DeviceCapability] = None |
| 58 | is_available: bool = False |
| 59 | |
| 60 | def __init__(self): |
| 61 | self._stream = None # compute stream / queue |
| 62 | |
| 63 | def to_device(self, array): |
| 64 | """Move a numpy array to device memory.""" |
| 65 | raise NotImplementedError |
| 66 | |
| 67 | def to_cpu(self, array): |
| 68 | """Move a device array back to host (numpy).""" |
| 69 | raise NotImplementedError |
| 70 | |
| 71 | def matmul(self, a, b): |
| 72 | """Matrix multiply: C = A @ B""" |
| 73 | raise NotImplementedError |
| 74 | |
| 75 | def rms_norm(self, x, weight, eps: float = 1e-6): |
| 76 | """RMS normalization.""" |
| 77 | raise NotImplementedError |
| 78 | |
| 79 | def silu(self, x): |
| 80 | """SiLU activation.""" |
| 81 | raise NotImplementedError |
| 82 | |
| 83 | def softmax(self, x, axis=-1): |
| 84 | """Softmax.""" |
| 85 | raise NotImplementedError |
| 86 | |
| 87 | def rope(self, x, cos, sin): |
| 88 | """Apply rotary position embeddings.""" |
| 89 | raise NotImplementedError |
| 90 | |
| 91 | def copy(self, dst, src): |
| 92 | """Copy src to dst on device.""" |
| 93 | raise NotImplementedError |
| 94 | |
| 95 | def synchronize(self): |
| 96 | """Block until all pending operations complete.""" |
| 97 | pass |
| 98 | |
| 99 | def __repr__(self): |
| 100 | return f"<{self.__class__.__name__}: {self.capability}>" |
| 101 | |
| 102 | |
| 103 | # ─── CPU Backend (default fallback) ────────────────────────────────────────── |
| 104 | |
| 105 | class CpuBackend(DeviceBackend): |
| 106 | """Pure NumPy CPU backend — always available.""" |
| 107 | |
| 108 | device_type = DeviceType.CPU |
| 109 | |
| 110 | def __init__(self): |
| 111 | import numpy as np |
| 112 | self.np = np |
| 113 | self.is_available = True |
| 114 | self.capability = DeviceCapability( |
| 115 | name=f"CPU ({os.uname().nodename})", |
| 116 | compute_units=os.cpu_count() or 1, |
| 117 | ) |
| 118 | |
| 119 | def to_device(self, array): |
| 120 | return self.np.asarray(array, dtype=self.np.float32) |
| 121 | |
| 122 | def to_cpu(self, array): |
| 123 | return self.np.asarray(array) |
| 124 | |
| 125 | def matmul(self, a, b): |
| 126 | return a @ b |
| 127 | |
| 128 | def rms_norm(self, x, weight, eps=1e-6): |
| 129 | variance = self.np.mean(x.astype(self.np.float32) ** 2, axis=-1, keepdims=True) |
| 130 | return x / self.np.sqrt(variance + self.np.float32(eps)) * weight.astype(self.np.float32) |
| 131 | |
| 132 | def silu(self, x): |
| 133 | return x / (1 + self.np.exp(-x)) |
| 134 | |
| 135 | def softmax(self, x, axis=-1): |
| 136 | x_max = self.np.max(x, axis=axis, keepdims=True) |
| 137 | x_exp = self.np.exp(x - x_max) |
| 138 | return x_exp / self.np.sum(x_exp, axis=axis, keepdims=True) |
| 139 | |
| 140 | def rope(self, x, cos, sin): |
| 141 | n, h, d = x.shape |
| 142 | x2 = x.reshape(n, h, d // 2, 2) |
| 143 | xr = self.np.stack([-x2[..., 1], x2[..., 0]], axis=-1) |
| 144 | c = cos[:n, self.np.newaxis, :d // 2, self.np.newaxis] |
| 145 | s = sin[:n, self.np.newaxis, :d // 2, self.np.newaxis] |
| 146 | return (x2 * c + xr * s).reshape(n, h, d) |
| 147 | |
| 148 | def copy(self, dst, src): |
| 149 | self.np.copyto(dst, src) |
| 150 | |
| 151 | |
| 152 | # ─── Intel Arc Backend ─────────────────────────────────────────────────────── |
| 153 | |
| 154 | class IntelArcBackend(DeviceBackend): |
| 155 | """ |
| 156 | Intel Arc GPU backend using Intel SYCL via dpctl + dpnp. |
| 157 | |
| 158 | Requirements: |
| 159 | - Intel GPU with Level Zero driver (kernel driver: i915) |
| 160 | - dpctl >= 0.14 |
| 161 | - dpnp >= 0.13 |
| 162 | |
| 163 | These are available from: |
| 164 | pip install dpctl dpnp |
| 165 | (Requires Intel GPU runtime: libze-intel-gpu1, level-zero-gpu) |
| 166 | """ |
| 167 | |
| 168 | device_type = DeviceType.INTEL_ARC |
| 169 | |
| 170 | def __init__(self, device_id: int = 0): |
| 171 | self._has_dpctl = False |
| 172 | self._has_dpnp = False |
| 173 | self._sycl_device = None |
| 174 | self._queue = None |
| 175 | self._init_backend(device_id) |
| 176 | |
| 177 | def _init_backend(self, device_id: int): |
| 178 | """Try to initialize Intel SYCL/dpctl device.""" |
| 179 | try: |
| 180 | import dpctl |
| 181 | self._has_dpctl = True |
| 182 | except ImportError: |
| 183 | logger.warning("dpctl not installed. Intel Arc backend unavailable.") |
| 184 | return |
| 185 | |
| 186 | try: |
| 187 | import dpnp as _dpnp |
| 188 | self._has_dpnp = True |
| 189 | self.dpnp = _dpnp |
| 190 | except ImportError: |
| 191 | logger.warning("dpnp not installed. Intel Arc backend limited to memory management only.") |
| 192 | self.dpnp = None |
| 193 | |
| 194 | try: |
| 195 | # Enumerate available Intel GPU devices |
| 196 | devices = dpctl.get_devices(device_type="gpu") |
| 197 | intel_gpus = [d for d in devices if d.backend.name == "level_zero" |
| 198 | or "Intel" in str(d) or "Intel" in d.name] |
| 199 | |
| 200 | if not intel_gpus: |
| 201 | logger.info("No Intel GPU devices found via dpctl.") |
| 202 | return |
| 203 | |
| 204 | if device_id < len(intel_gpus): |
| 205 | self._sycl_device = intel_gpus[device_id] |
| 206 | else: |
| 207 | self._sycl_device = intel_gpus[0] |
| 208 | |
| 209 | self._queue = dpctl.SyclQueue(self._sycl_device) |
| 210 | |
| 211 | # Gather device capabilities |
| 212 | name = self._sycl_device.name |
| 213 | max_compute_units = self._sycl_device.max_compute_units |
| 214 | max_wg_size = self._sycl_device.max_work_group_size |
| 215 | |
| 216 | # Estimate VRAM from device info |
| 217 | try: |
| 218 | global_mem = self._sycl_device.global_mem_size |
| 219 | vram_gb = global_mem / (1024 ** 3) |
| 220 | except Exception: |
| 221 | vram_gb = 0.0 |
| 222 | |
| 223 | # Check FP16/BF16 support (subgroup support) |
| 224 | fp16 = False |
| 225 | bf16 = False |
| 226 | try: |
| 227 | fp16 = self._sycl_device.has_aspect_fp16 |
| 228 | except Exception: |
| 229 | pass |
| 230 | try: |
| 231 | bf16 = self._sycl_device.has_aspect_fp64 # not exact but indicative |
| 232 | except Exception: |
| 233 | pass |
| 234 | |
| 235 | self.capability = DeviceCapability( |
| 236 | name=f"Intel Arc ({name})", |
| 237 | vram_gb=vram_gb, |
| 238 | compute_units=max_compute_units, |
| 239 | supports_fp16=fp16, |
| 240 | supports_bf16=bf16, |
| 241 | max_work_group_size=max_wg_size, |
| 242 | ) |
| 243 | self.is_available = True |
| 244 | logger.info(f"Intel Arc GPU detected: {name}, VRAM: {vram_gb:.1f}GB, " |
| 245 | f"EUs: {max_compute_units}") |
| 246 | |
| 247 | except Exception as e: |
| 248 | logger.warning(f"Failed to initialize Intel Arc backend: {e}") |
| 249 | |
| 250 | def to_device(self, array): |
| 251 | if not self.is_available: |
| 252 | return array # fall back to CPU array |
| 253 | if self._has_dpnp: |
| 254 | return self.dpnp.asarray(array, dtype=array.dtype) |
| 255 | # Fallback: use dpctl memory + USM |
| 256 | import dpctl |
| 257 | import numpy as np |
| 258 | ary = np.ascontiguousarray(array) |
| 259 | from dpctl import tensor as dpctl_tensor |
| 260 | return dpctl_tensor.usm_ndarray( |
| 261 | ary.shape, |
| 262 | dtype=ary.dtype, |
| 263 | buffer="device", |
| 264 | queue=self._queue, |
| 265 | ) |
| 266 | |
| 267 | def to_cpu(self, array): |
| 268 | import numpy as np |
| 269 | if hasattr(array, 'asnumpy'): |
| 270 | return array.asnumpy() |
| 271 | return np.asarray(array) |
| 272 | |
| 273 | def matmul(self, a, b): |
| 274 | if not self.is_available or not self._has_dpnp: |
| 275 | # Fall back to numpy via to_cpu |
| 276 | import numpy as np |
| 277 | a_cpu = self.to_cpu(a) |
| 278 | b_cpu = self.to_cpu(b) |
| 279 | return np.asarray(a_cpu @ b_cpu) |
| 280 | return self.dpnp.matmul(a, b) |
| 281 | |
| 282 | def rms_norm(self, x, weight, eps=1e-6): |
| 283 | if not self.is_available or not self._has_dpnp: |
| 284 | import numpy as np |
| 285 | return CpuBackend().rms_norm(self.to_cpu(x), self.to_cpu(weight), eps) |
| 286 | dpnp = self.dpnp |
| 287 | variance = dpnp.mean(x.astype(dpnp.float64) ** 2, axis=-1, keepdims=True) |
| 288 | result = x / dpnp.sqrt(variance + eps) * weight.astype(dpnp.float32) |
| 289 | return result |
| 290 | |
| 291 | def silu(self, x): |
| 292 | if not self.is_available or not self._has_dpnp: |
| 293 | import numpy as np |
| 294 | return CpuBackend().silu(self.to_cpu(x)) |
| 295 | dpnp = self.dpnp |
| 296 | return x / (1 + dpnp.exp(-x)) |
| 297 | |
| 298 | def softmax(self, x, axis=-1): |
| 299 | if not self.is_available or not self._has_dpnp: |
| 300 | import numpy as np |
| 301 | return CpuBackend().softmax(self.to_cpu(x), axis) |
| 302 | dpnp = self.dpnp |
| 303 | x_max = dpnp.max(x, axis=axis, keepdims=True) |
| 304 | x_exp = dpnp.exp(x - x_max) |
| 305 | return x_exp / dpnp.sum(x_exp, axis=axis, keepdims=True) |
| 306 | |
| 307 | def rope(self, x, cos, sin): |
| 308 | if not self.is_available or not self._has_dpnp: |
| 309 | import numpy as np |
| 310 | return CpuBackend().rope(self.to_cpu(x), self.to_cpu(cos), self.to_cpu(sin)) |
| 311 | dpnp = self.dpnp |
| 312 | n, h, d = x.shape |
| 313 | half_d = d // 2 |
| 314 | x2 = x.reshape(n, h, half_d, 2) |
| 315 | neg = dpnp.stack([-x2[..., 1], x2[..., 0]], axis=-1) |
| 316 | c = cos[:n, dpnp.newaxis, :half_d, dpnp.newaxis] |
| 317 | s = sin[:n, dpnp.newaxis, :half_d, dpnp.newaxis] |
| 318 | return (x2 * c + neg * s).reshape(n, h, d) |
| 319 | |
| 320 | def copy(self, dst, src): |
| 321 | if hasattr(dst, '__setitem__') and hasattr(src, '__getitem__'): |
| 322 | dst[:] = src # dpnp supports item assignment |
| 323 | else: |
| 324 | import numpy as np |
| 325 | np.copyto(self.to_cpu(dst), self.to_cpu(src)) |
| 326 | |
| 327 | def synchronize(self): |
| 328 | if self._queue is not None: |
| 329 | self._queue.wait() |
| 330 | |
| 331 | |
| 332 | # ─── NVIDIA CUDA Backend (for comparison) ──────────────────────────────────── |
| 333 | |
| 334 | class CudaBackend(DeviceBackend): |
| 335 | """NVIDIA CUDA backend using cupy/cublas (reference).""" |
| 336 | |
| 337 | device_type = DeviceType.NVIDIA_CUDA |
| 338 | |
| 339 | def __init__(self, device_id: int = 0): |
| 340 | try: |
| 341 | import cupy as cp |
| 342 | self.cp = cp |
| 343 | self.is_available = True |
| 344 | with cp.cuda.Device(device_id): |
| 345 | props = cp.cuda.runtime.getDeviceProperties(device_id) |
| 346 | mem_info = cp.cuda.runtime.memGetInfo() |
| 347 | free_mem = mem_info[0] |
| 348 | total_mem = mem_info[1] |
| 349 | self.capability = DeviceCapability( |
| 350 | name=f"NVIDIA {props['name'].decode()}", |
| 351 | vram_gb=total_mem / (1024 ** 3), |
| 352 | compute_units=props['multiProcessorCount'], |
| 353 | supports_fp16=True, |
| 354 | supports_bf16=props.get('major', 0) >= 8, |
| 355 | ) |
| 356 | logger.info(f"NVIDIA CUDA backend initialized: {self.capability.name}") |
| 357 | except ImportError: |
| 358 | logger.debug("cupy not installed. NVIDIA CUDA backend unavailable.") |
| 359 | except Exception as e: |
| 360 | logger.warning(f"CUDA backend init failed: {e}") |
| 361 | |
| 362 | def to_device(self, array): |
| 363 | return self.cp.asarray(array) |
| 364 | |
| 365 | def to_cpu(self, array): |
| 366 | return self.cp.asnumpy(array) |
| 367 | |
| 368 | def matmul(self, a, b): |
| 369 | return a @ b |
| 370 | |
| 371 | def rms_norm(self, x, weight, eps=1e-6): |
| 372 | cp = self.cp |
| 373 | x64 = x.astype(cp.float64) |
| 374 | variance = cp.mean(x64 ** 2, axis=-1, keepdims=True) |
| 375 | return x / cp.sqrt(variance + eps) * weight.astype(cp.float32) |
| 376 | |
| 377 | def silu(self, x): |
| 378 | return x / (1 + self.cp.exp(-x)) |
| 379 | |
| 380 | def softmax(self, x, axis=-1): |
| 381 | cp = self.cp |
| 382 | x_max = cp.max(x, axis=axis, keepdims=True) |
| 383 | x_exp = cp.exp(x - x_max) |
| 384 | return x_exp / cp.sum(x_exp, axis=axis, keepdims=True) |
| 385 | |
| 386 | def rope(self, x, cos, sin): |
| 387 | cp = self.cp |
| 388 | n, h, d = x.shape |
| 389 | half_d = d // 2 |
| 390 | x2 = x.reshape(n, h, half_d, 2) |
| 391 | xr = cp.stack([-x2[..., 1], x2[..., 0]], axis=-1) |
| 392 | c = cos[:n, cp.newaxis, :half_d, cp.newaxis] |
| 393 | s = sin[:n, cp.newaxis, :half_d, cp.newaxis] |
| 394 | return (x2 * c + xr * s).reshape(n, h, d) |
| 395 | |
| 396 | def copy(self, dst, src): |
| 397 | dst[:] = src |
| 398 | |
| 399 | def synchronize(self): |
| 400 | self.cp.cuda.runtime.deviceSynchronize() |
| 401 | |
| 402 | |
| 403 | # ─── Factory ───────────────────────────────────────────────────────────────── |
| 404 | |
| 405 | _BACKEND_INSTANCES: dict = {} |
| 406 | _BACKEND_CLASSES = [ |
| 407 | ('intel_arc', IntelArcBackend), |
| 408 | ('nvidia', CudaBackend), |
| 409 | ('cpu', CpuBackend), |
| 410 | ] |
| 411 | |
| 412 | |
| 413 | def get_device(device_name: Optional[str] = None) -> DeviceBackend: |
| 414 | """ |
| 415 | Get or create a device backend. |
| 416 | |
| 417 | Args: |
| 418 | device_name: One of 'auto', 'cpu', 'intel_arc', 'nvidia', 'amd'. |
| 419 | 'auto' (default) tries Intel Arc, then NVIDIA, then CPU. |
| 420 | If not available, falls back to CPU. |
| 421 | |
| 422 | Returns: |
| 423 | A DeviceBackend instance. |
| 424 | """ |
| 425 | env_device = os.environ.get('MOJOLLAMA_DEVICE', '').lower() |
| 426 | |
| 427 | if device_name is None or device_name == 'auto': |
| 428 | device_name = env_device or 'auto' |
| 429 | |
| 430 | if device_name == 'auto': |
| 431 | return _auto_detect() |
| 432 | |
| 433 | if device_name == 'cpu': |
| 434 | return _get_or_create('cpu', CpuBackend) |
| 435 | |
| 436 | for key, cls in _BACKEND_CLASSES: |
| 437 | if device_name == key: |
| 438 | return _get_or_create(key, cls) |
| 439 | |
| 440 | logger.warning(f"Unknown device '{device_name}', falling back to CPU.") |
| 441 | return _get_or_create('cpu', CpuBackend) |
| 442 | |
| 443 | |
| 444 | def _auto_detect() -> DeviceBackend: |
| 445 | """Auto-detect best available device.""" |
| 446 | # Priority: Intel Arc -> NVIDIA CUDA -> CPU |
| 447 | for key, cls in _BACKEND_CLASSES: |
| 448 | if key == 'cpu': |
| 449 | continue # CPU is last resort |
| 450 | instance = _get_or_create(key, cls) |
| 451 | if instance.is_available: |
| 452 | logger.info(f"Auto-selected device: {key} ({instance.capability})") |
| 453 | return instance |
| 454 | |
| 455 | cpu = _get_or_create('cpu', CpuBackend) |
| 456 | logger.info(f"Auto-selected device: cpu ({cpu.capability})") |
| 457 | return cpu |
| 458 | |
| 459 | |
| 460 | def _get_or_create(key: str, backend_cls: type) -> DeviceBackend: |
| 461 | """Get cached backend instance or create one.""" |
| 462 | if key not in _BACKEND_INSTANCES: |
| 463 | _BACKEND_INSTANCES[key] = backend_cls() |
| 464 | return _BACKEND_INSTANCES[key] |
| 465 | |
| 466 | |
| 467 | def list_devices() -> list[dict]: |
| 468 | """List all available compute devices and their capabilities.""" |
| 469 | results = [] |
| 470 | for key, cls in _BACKEND_CLASSES: |
| 471 | if key == 'cpu': |
| 472 | continue |
| 473 | try: |
| 474 | inst = _get_or_create(key, cls) |
| 475 | if inst.is_available and inst.capability: |
| 476 | results.append({ |
| 477 | 'device': key, |
| 478 | 'name': inst.capability.name, |
| 479 | 'vram_gb': inst.capability.vram_gb, |
| 480 | 'compute_units': inst.capability.compute_units, |
| 481 | 'fp16': inst.capability.supports_fp16, |
| 482 | }) |
| 483 | except Exception: |
| 484 | pass |
| 485 | |
| 486 | results.append({ |
| 487 | 'device': 'cpu', |
| 488 | 'name': f"CPU ({os.cpu_count()} cores)", |
| 489 | 'vram_gb': 0, |
| 490 | 'compute_units': os.cpu_count(), |
| 491 | 'fp16': False, |
| 492 | }) |
| 493 | |
| 494 | return results |