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/src/mojollama/model/backends/intel_arc.py # 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 / src / mojollama / model / backends / intel_arc.py` 329 lines · 11165 bytes Raw Blame History 1 """ 2 Intel Arc GPU backend for MojoLlama. 3 4 Provides optimized kernel implementations for Intel Arc GPUs using: 5 - Intel SYCL via dpctl (device management, memory, queue control) 6 - Intel oneDNN / dpnp (batched matmul, softmax, norm) 7 - Level Zero (low-level device queries, fine-grained control) 8 - Custom SYCL kernels for fused operations (RoPE, RMSNorm fusion) 9 10 Architecture: 11 Intel Arc (Alchemist) — Xe HPG microarchitecture 12 - Xe Cores with XMX (Xe Matrix eXtensions) for matrix math 13 - Hardware-supported FP16/BF16/INT8 14 - Up to 32 Xe Cores (512 EUs) on Arc A770 15 - Level Zero driver interface 16 17 Usage: 18 from mojollama.model.backends.intel_arc import IntelArcBackend 19 backend = IntelArcBackend(device_id=0) 20 if backend.is_available: 21 gpu_tensor = backend.to_device(numpy_array) 22 result = backend.matmul(a, b) 23 """ 24 25 import ctypes 26 import logging 27 import os 28 import struct 29 from typing import Optional, Any, Dict 30 31 import numpy as np 32 33 logger = logging.getLogger(__name__) 34 35 36 # ─── Intel Arc Device Info Queries ────────────────────────────────────────── 37 38 def query_intel_arc_devices() -> list[dict]: 39 """ 40 Query available Intel GPU devices via dpctl and Level Zero. 41 Returns a list of device info dicts. 42 """ 43 devices = [] 44 try: 45 import dpctl 46 gpu_devices = dpctl.get_devices(device_type="gpu") 47 for i, dev in enumerate(gpu_devices): 48 if "Intel" not in str(dev) and "Intel" not in dev.name: 49 continue 50 info = { 51 'index': i, 52 'name': dev.name, 53 'driver': dev.driver_version if hasattr(dev, 'driver_version') else '', 54 'backend': dev.backend.name if dev.backend else '', 55 'max_compute_units': dev.max_compute_units, 56 'max_work_group_size': dev.max_work_group_size, 57 'global_mem': getattr(dev, 'global_mem_size', 0), 58 'local_mem': getattr(dev, 'local_mem_size', 0), 59 'max_mem_alloc': getattr(dev, 'max_mem_alloc_size', 0), 60 'fp16': getattr(dev, 'has_aspect_fp16', False), 61 'fp64': getattr(dev, 'has_aspect_fp64', False), 62 } 63 info['vram_gb'] = info['global_mem'] / (1024 ** 3) 64 devices.append(info) 65 except ImportError: 66 logger.debug("dpctl not available for Intel Arc device queries.") 67 except Exception as e: 68 logger.debug(f"Device query error: {e}") 69 70 return devices 71 72 73 def get_level_zero_driver_version() -> Optional[str]: 74 """ 75 Attempt to get Intel Level Zero driver version via ctypes. 76 This is a low-level probe for diagnostic purposes. 77 """ 78 try: 79 # Try loading Level Zero loader library 80 libze = ctypes.cdll.LoadLibrary("libze_loader.so.1") 81 if libze: 82 # zeInit 83 ze_init = libze.zeInit 84 ze_init.restype = ctypes.c_int 85 ret = ze_init(0) 86 if ret == 0: 87 # zeDriverGetProperties would go here in full impl 88 return "Level Zero driver loaded" 89 except (OSError, AttributeError) as e: 90 logger.debug(f"Level Zero loader not found: {e}") 91 return None 92 93 94 # ─── Intel Arc Optimized Kernels ──────────────────────────────────────────── 95 96 class IntelArcMatMul: 97 """ 98 Intel Arc optimized matrix multiplication. 99 100 For small-to-medium sizes: uses dpnp which routes to oneDNN. 101 For large sizes (quantized): uses Intel SYCL custom kernel 102 with XMX acceleration when available. 103 104 Block sizes tuned for Intel Arc Xe HPG: 105 - XMX: 16x16 matrix tiles 106 - Shared Local Memory (SLM): 64KB per Xe Core 107 - Wavefront size: 16 (SIMD) 108 """ 109 110 # Block sizes for Intel Arc Xe HPG 111 BLOCK_M = 64 112 BLOCK_N = 64 113 BLOCK_K = 32 114 115 def __init__(self, backend: 'IntelArcBackend'): 116 self.backend = backend 117 self._dpnp = backend.dpnp if backend._has_dpnp else None 118 119 def __call__(self, a, b): 120 return self.backend.matmul(a, b) 121 122 123 class IntelArcSoftmax: 124 """ 125 Intel Arc optimized softmax. 126 127 Uses warp-level reductions (wavefront size = 16 on Intel Arc). 128 For small dimensions, uses shared memory optimization. 129 """ 130 131 THREADS = 256 # work group size 132 133 def __init__(self, backend: 'IntelArcBackend'): 134 self.backend = backend 135 136 def __call__(self, x, axis=-1): 137 return self.backend.softmax(x, axis) 138 139 140 class IntelArcRMSNorm: 141 """ 142 Intel Arc optimized RMS normalization. 143 144 Fused kernel: computes variance and normalization in a single pass. 145 Uses reduction tree with work-group barriers. 146 Optimized for Intel Arc SLM (64KB). 147 """ 148 149 WG_SIZE = 128 150 151 def __init__(self, backend: 'IntelArcBackend'): 152 self.backend = backend 153 154 def __call__(self, x, weight, eps=1e-6): 155 return self.backend.rms_norm(x, weight, eps) 156 157 158 # ─── Custom SYCL Kernel Source (opens for future expansion) ──────────────── 159 160 """ 161 Intel Arc SYCL kernels (JIT-compiled at runtime via dpctl kernel bundles). 162 163 These kernels will be loaded and JIT-compiled via: 164 import dpctl 165 import dpctl.program as dpctl_prog 166 kernel_src = '''...''' 167 prog = dpctl_prog.create_program_from_source(queue, kernel_src, "sycl") 168 kern = prog.get_kernel("mojollama_rmsnorm") 169 170 When dpctl kernel bundle API is finalized, we can load these dynamically 171 for maximum performance. 172 173 Currently available kernels (future): 174 - fused_rmsnorm: Single-pass RMS norm with elementwise scaling 175 - fused_rope: RoPE with inline cos/sin application 176 - quantized_matmul: INT8/INT4 quantized matmul using XMX 177 - flash_attention_v1: Softmax + attention with tiling (Intel Arc tuned) 178 """ 179 180 181 # ─── Intel Arc Memory Pool ──────────────────────────────────────────────── 182 183 class IntelArcMemoryPool: 184 """ 185 USM (Unified Shared Memory) pool for Intel Arc. 186 187 Manages device allocations to avoid repeated malloc/free overhead. 188 Uses dpctl's USM allocator under the hood. 189 190 Intel Arc USM types: 191 - device: fastest access from GPU (device-only) 192 - shared: accessible from both CPU and GPU (slower for GPU) 193 - host: pinned host memory (fast CPU<->GPU transfer) 194 """ 195 196 def __init__(self, queue, initial_pool_size_mb: int = 256): 197 self._queue = queue 198 self._allocations: Dict[int, Any] = {} 199 self._pool_size = initial_pool_size_mb * 1024 * 1024 200 self._total_allocated = 0 201 202 def allocate(self, shape, dtype=np.float32): 203 import dpctl 204 n_bytes = int(np.prod(shape)) * np.dtype(dtype).itemsize 205 # Use USM device allocation 206 usm_alloc = dpctl.memory.MemoryUSMDevice(n_bytes, self._queue) 207 from dpctl.tensor import usm_ndarray 208 arr = usm_ndarray(shape, dtype=dtype, buffer=usm_alloc) 209 key = id(arr) 210 self._allocations[key] = arr 211 self._total_allocated += n_bytes 212 return arr 213 214 def free(self, arr): 215 key = id(arr) 216 if key in self._allocations: 217 n_bytes = arr.nbytes if hasattr(arr, 'nbytes') else 0 218 del self._allocations[key] 219 self._total_allocated -= n_bytes 220 221 def reset(self): 222 self._allocations.clear() 223 self._total_allocated = 0 224 225 @property 226 def usage_gb(self): 227 return self._total_allocated / (1024 ** 3) 228 229 230 # ─── Intel Arc Quantization Support ───────────────────────────────────────── 231 232 class IntelArcQuantizedOps: 233 """ 234 Intel Arc GPU quantization operations. 235 236 Uses Intel XMX (Xe Matrix eXtensions) for accelerated 237 INT8/INT4 matrix multiply, similar to NVIDIA Tensor Cores. 238 239 Intel Arc supports: 240 - INT8: 2x throughput vs FP16 on XMX 241 - BF16: mixed-precision training support 242 - INT4: via DP4A (Dot Product of 4 Elements and Accumulate) 243 """ 244 245 def __init__(self, backend: 'IntelArcBackend'): 246 self.backend = backend 247 248 def quantize_q8_0(self, data: np.ndarray) -> tuple: 249 """ 250 Quantize to Q8_0 format on Intel Arc. 251 Q8_0: block of 32 weights, 1 fp16 scale, 32 int8 values. 252 253 Intel Arc XMX can process this format efficiently via 254 DP4A instructions. 255 """ 256 import dpnp as dp 257 258 if self.backend.is_available and self.backend._has_dpnp: 259 data_dev = self.backend.to_device(data) 260 scale_factor = 127.0 261 262 # Reshape into blocks of 32 263 flat = data_dev.flatten() 264 n = flat.shape[0] 265 padding = (32 - n % 32) % 32 266 if padding > 0: 267 flat = dp.pad(flat, (0, padding), 'constant') 268 269 n_blocks = flat.shape[0] // 32 270 blocks = flat.reshape(n_blocks, 32) 271 272 # Compute d = abs(max) / 127 for each block 273 abs_max = dp.max(dp.abs(blocks), axis=1, keepdims=True) 274 d = abs_max / scale_factor 275 d = dp.where(d == 0, 1.0, d) # avoid division by zero 276 277 # Quantize 278 q = dp.round(blocks / d).astype(dp.int8) 279 d_half = dp.array(d.flatten(), dtype=dp.float16) 280 281 return self.backend.to_cpu(q), self.backend.to_cpu(d_half) 282 283 # CPU fallback 284 return self._quantize_q8_0_cpu(data) 285 286 @staticmethod 287 def _quantize_q8_0_cpu(data: np.ndarray) -> tuple: 288 flat = data.flatten() 289 n = flat.shape[0] 290 padding = (32 - n % 32) % 32 291 if padding > 0: 292 flat = np.pad(flat, (0, padding), 'constant') 293 n_blocks = flat.shape[0] // 32 294 blocks = flat.reshape(n_blocks, 32) 295 abs_max = np.max(np.abs(blocks), axis=1, keepdims=True) 296 d = abs_max / 127.0 297 d = np.where(d == 0, 1.0, d) 298 q = np.round(blocks / d).astype(np.int8) 299 d_half = d.flatten().astype(np.float16) 300 return q, d_half 301 302 303 # ─── Factory function ────────────────────────────────────────────────────── 304 305 def create_intel_arc_backend(device_id: int = 0) -> 'IntelArcBackend': 306 """ 307 Create and initialize an Intel Arc backend. 308 309 This is the main entry point for Intel Arc GPU hardware acceleration. 310 311 Args: 312 device_id: Intel GPU device index (default: 0) 313 314 Returns: 315 IntelArcBackend instance (check .is_available before use) 316 317 Environment variables: 318 MOJOLLAMA_INTEL_ARC_DEVICE: override device_id 319 SYCL_DEVICE_FILTER: standard Intel SYCL device filter 320 (e.g., "level_zero:gpu:0" for first Intel GPU) 321 """ 322 override = os.environ.get('MOJOLLAMA_INTEL_ARC_DEVICE') 323 if override is not None: 324 try: 325 device_id = int(override) 326 except ValueError: 327 pass 328 329 return IntelArcBackend(device_id=device_id)