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 / model / ops.mojo

194 lines · 7434 bytes Raw Blame History
1# ===----------------------------------------------------------------------=== #
2# MojoLlama — Mojo inference ops (Phase 1)
3# Pure Mojo implementations of core neural network operations.
4# With Intel Arc GPU support via Python/SYCL interop bridge.
5# ===----------------------------------------------------------------------=== #
6
7from std.python import Python, PythonObject
8from std.math import rsqrt, exp
9
10
11# ─── Scalar ops (always available, CPU-only) ────────────────────────────────
12
13fn silu_scalar(x: Float32) -> Float32:
14 """SiLU activation: x / (1 + exp(-x))"""
15 return x / (1 + exp(-x))
16
17
18fn rmsnorm_scalar(x: Float32, weight: Float32, eps: Float32) -> Float32:
19 """RMSNorm element: x / sqrt(variance + eps) * weight"""
20 return x / rsqrt(x * x + eps) * weight
21
22
23# ─── Python interop ops (CPU via numpy) ─────────────────────────────────────
24
25fn silu(x: PythonObject) raises -> PythonObject:
26 """Apply SiLU activation to a numpy array. Uses Mojo scalar ops per element."""
27 var np = Python.evaluate("__import__('numpy')")
28 var arr = np.asarray(x, np.float32)
29 var out = np.zeros_like(arr)
30 for i in range(Int(py=arr.size())):
31 out.flat.__setitem__(i, value=silu_scalar(Float32(py=arr.flat.__getitem__(i))))
32 return out
33
34
35fn rmsnorm(x: PythonObject, weight: PythonObject, eps: PythonObject) raises -> PythonObject:
36 """Apply RMSNorm to numpy arrays. Uses Mojo scalar ops per element."""
37 var np = Python.evaluate("__import__('numpy')")
38 var arr = np.asarray(x, np.float32)
39 var w = np.asarray(weight, np.float32)
40 var eps_f = Float32(py=eps)
41 var out = np.zeros_like(arr)
42 var dim = Int(py=arr.shape[-1].__index__())
43 var n_rows = Int(py=arr.size()) // dim
44
45 for row in range(n_rows):
46 var offset = row * dim
47 # Compute sum of squares
48 var sum_sq: Float32 = 0.0
49 for j in range(dim):
50 var val = Float32(py=arr.flat.__getitem__(offset + j))
51 sum_sq += val * val
52 var inv_std = rsqrt(sum_sq / Float32(dim) + eps_f)
53 # Normalize and scale
54 for j in range(dim):
55 var xv = Float32(py=arr.flat.__getitem__(offset + j))
56 var wv = Float32(py=w.flat.__getitem__(j))
57 out.flat.__setitem__(offset + j, value=xv * inv_std * wv)
58 return out
59
60
61# ─── Intel Arc GPU dispatch (Phase 2) ──────────────────────────────────────
62#
63# These functions dispatch to Intel Arc GPU via Python SYCL bridge.
64# When an Intel Arc GPU is detected (via dpctl), operations are
65# offloaded to the SYCL device. Falls back to CPU numpy otherwise.
66#
67# Usage from Mojo:
68# from ops import intel_arc_silu, intel_arc_set_device
69# intel_arc_set_device() # auto-detect Intel Arc
70# result = intel_arc_silu(x_array) # runs on Arc GPU
71#
72# Prerequisites (at Python level):
73# pip install dpctl dpnp
74# Intel GPU driver (i915 + Level Zero)
75
76alias _INTEL_ARC_MODULE = "mojollama.model.backends.intel_arc"
77
78
79fn _ensure_intel_arc_module() raises -> PythonObject:
80 """Import the Intel Arc backend module (cached)."""
81 var sys = Python.evaluate("__import__('sys')")
82 var module_name = _INTEL_ARC_MODULE
83 if sys.modules.__contains__(module_name):
84 return sys.modules[module_name]
85 return Python.evaluate("__import__")(module_name)
86
87
88fn intel_arc_is_available() raises -> bool:
89 """Check if an Intel Arc GPU is available for compute."""
90 try:
91 var arc_mod = _ensure_intel_arc_module()
92 var backend = arc_mod.create_intel_arc_backend()
93 return Python.evaluate("lambda b: b.is_available")(backend)
94 except:
95 return False
96
97
98fn intel_arc_device_info() raises -> PythonObject:
99 """Get Intel Arc GPU device info, or None if unavailable."""
100 try:
101 var arc_mod = _ensure_intel_arc_module()
102 return arc_mod.query_intel_arc_devices()
103 except:
104 return Python.evaluate("[]")
105
106
107fn intel_arc_silu(x: PythonObject) raises -> PythonObject:
108 """Apply SiLU on Intel Arc GPU via SYCL/dpnp. Falls back to CPU."""
109 try:
110 var arc_mod = _ensure_intel_arc_module()
111 var backend = arc_mod.create_intel_arc_backend()
112 if Python.evaluate("lambda b: b.is_available")(backend):
113 var dev_x = backend.to_device(x)
114 var result = backend.silu(dev_x)
115 return backend.to_cpu(result)
116 except:
117 pass
118 # Fallback to CPU numpy
119 return silu(x)
120
121
122fn intel_arc_rmsnorm(x: PythonObject, weight: PythonObject, eps: PythonObject) raises -> PythonObject:
123 """Apply RMSNorm on Intel Arc GPU via SYCL/dpnp. Falls back to CPU."""
124 try:
125 var arc_mod = _ensure_intel_arc_module()
126 var backend = arc_mod.create_intel_arc_backend()
127 if Python.evaluate("lambda b: b.is_available")(backend):
128 var dev_x = backend.to_device(x)
129 var dev_w = backend.to_device(weight)
130 var result = backend.rms_norm(dev_x, dev_w, Float32(py=eps))
131 return backend.to_cpu(result)
132 except:
133 pass
134 # Fallback to CPU
135 return rmsnorm(x, weight, eps)
136
137
138fn intel_arc_matmul(a: PythonObject, b: PythonObject) raises -> PythonObject:
139 """Matrix multiply on Intel Arc GPU. Falls back to CPU numpy."""
140 try:
141 var arc_mod = _ensure_intel_arc_module()
142 var backend = arc_mod.create_intel_arc_backend()
143 if Python.evaluate("lambda b: b.is_available")(backend):
144 var dev_a = backend.to_device(a)
145 var dev_b = backend.to_device(b)
146 var result = backend.matmul(dev_a, dev_b)
147 return backend.to_cpu(result)
148 except:
149 pass
150 # Fallback to CPU matmul
151 var np = Python.evaluate("__import__('numpy')")
152 return np.asarray(a) @ np.asarray(b)
153
154
155# ─── Device auto-select ────────────────────────────────────────────────────
156#
157# intel_arc_prefer: When True (default), tries Intel Arc GPU first.
158# Set to False to force CPU path.
159#
160# intel_arc_active: True when Intel Arc GPU was detected and initialized.
161
162var intel_arc_prefer: Bool = True
163var intel_arc_active: Bool = False
164
165
166fn intel_arc_set_device(prefer: Bool = True) raises:
167 """Try to detect and initialize Intel Arc GPU.
168
169 Args:
170 prefer: When True, ops will use Intel Arc GPU if available.
171 When False, forces CPU-only path.
172
173 Returns:
174 True if Intel Arc GPU is now active.
175 """
176 intel_arc_prefer = prefer
177 if not prefer:
178 intel_arc_active = False
179 print("[MojoLlama] Intel Arc GPU: disabled (CPU mode)")
180 return
181
182 var available = intel_arc_is_available()
183 if available:
184 intel_arc_active = True
185 var info = intel_arc_device_info()
186 print("[MojoLlama] Intel Arc GPU: detected")
187 for i in range(Int(py=len(info))):
188 var dev = info[i]
189 print(" Device " + String(i) + ": " + String(dev["name"]))
190 var vram = Float64(py=dev.get("vram_gb", 0))
191 print(" VRAM: " + String(vram) + " GB")
192 else:
193 intel_arc_active = False
194 print("[MojoLlama] Intel Arc GPU: not available (using CPU)")