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 / bridge.py

337 lines · 12957 bytes Raw Blame History
1"""
2MojoLlama Bridge — Python backend for the Mojo op graph.
3
4Loads GGUF models, executes ops via numpy, handles tokenizer/sampling.
5When Mojo's native APIs mature, ops are swapped — the graph stays the same.
6
7Architecture:
8 bridge.py (Python) ← GGUF loading, tokenizer, numpy backend
9 ↕ (calls via Mojo interop or stdin/stdout)
10 ops.mojo (Mojo) ← Op graph definitions
11 kernels/ (Mojo, future) ← Native Mojo SIMD implementations
12 max/ (MAX, future) ← MAX GPU/CUDA/SYCL implementations
13
14Current: bridge.py executes the full forward pass via numpy.
15Future: bridge.py only handles I/O, ops execute in Mojo SIMD or MAX GPU.
16"""
17import numpy as np
18import gguf
19from gguf.constants import GGMLQuantizationType
20import struct
21import time
22import sys
23import os
24
25
26class MojoLlamaBridge:
27 """Python bridge for MojoLlama. Manages model loading and op execution."""
28
29 def __init__(self, path: str):
30 self.path = path
31 self.reader = gguf.GGUFReader(path)
32 self._tensors_by_name = {t.name: t for t in self.reader.tensors}
33 self._load_config()
34 self._load_weights()
35 self._kv_cache = None
36 self._cached_len = 0
37
38 def _load_config(self):
39 f = self.reader.get_field
40 self.arch = self._get_str(f('general.architecture'))
41 prefix = f'{self.arch}.'
42 self.n_layers = self._get_scalar(f(f'{prefix}block_count'))
43 self.n_embd = self._get_scalar(f(f'{prefix}embedding_length'))
44 self.n_head = self._get_scalar(f(f'{prefix}attention.head_count'))
45 self.n_kv_head = self._get_scalar(f(f'{prefix}attention.head_count_kv'))
46 self.n_ff = self._get_scalar(f(f'{prefix}feed_forward_length'))
47 self.norm_eps = self._get_scalar(f(f'{prefix}attention.layer_norm_rms_epsilon'))
48
49 def _get_scalar(self, f):
50 if f is None:
51 return 0
52 v = f.parts[-1]
53 if hasattr(v, 'item'):
54 return v.item()
55 return int(v)
56
57 def _get_str(self, f):
58 if f is None:
59 return 'unknown'
60 v = f.parts[-1]
61 if isinstance(v, bytes):
62 return v.decode('utf-8', errors='replace')
63 if hasattr(v, 'tobytes'):
64 return v.tobytes().decode('utf-8', errors='replace').strip('\x00')
65 return str(v)
66
67 def _get_int(self, f):
68 if f is None:
69 return 0
70 return int(f.parts[-1])
71
72 def _get_float(self, f):
73 if f is None:
74 return 1e-6
75 return float(f.parts[-1])
76
77 def _load_weights(self):
78 """Load all tensors, dequantizing Q4_0 to float32."""
79 self.weights = {}
80 for name, t in self._tensors_by_name.items():
81 if hasattr(t, 'tensor_type') and t.tensor_type is not None:
82 if t.tensor_type == GGMLQuantizationType.Q4_0:
83 # Dequantize Q4_0 to float32
84 arr = gguf.dequantize(t.data, t.tensor_type)
85 self.weights[name] = ('q4_0', arr)
86 else:
87 arr = gguf.dequantize(t.data, t.tensor_type)
88 self.weights[name] = ('f32', arr)
89 else:
90 self.weights[name] = ('f32', np.array(t.data, dtype=np.float32))
91
92 def embed(self, input_ids):
93 """EmbedOp: token_embd.weight[input_ids]"""
94 typ, embed = self.weights.get('token_embd.weight', (None, None))
95 if embed is None:
96 raise ValueError("token_embd.weight not found")
97 # Handle reverse shape: GGUF stores [in_cols, out_rows]
98 if embed.ndim == 2 and embed.shape[0] == self.n_embd:
99 embed = embed.T
100 return embed[input_ids].astype(np.float32)
101
102 def matmul(self, name, x):
103 """MatmulOp: x @ W.T for a named weight tensor."""
104 typ, w = self.weights.get(name, (None, None))
105 if w is None:
106 raise ValueError(f"Weight {name} not found")
107
108 if typ == 'q4_0':
109 # Q4_0: w is (out_rows, packed_cols) — dequantized via gguf
110 # gguf stores weights as 2D: shape=[cols, rows] but data is (rows, packed)
111 return x @ w.T
112 else:
113 # Float32 — always x @ W.T (GGUF stores transposed)
114 return x @ w.T
115
116 def _q4_matmul(self, raw, x):
117 """Compute x @ W.T for Q4_0 weight stored in GGUF raw format."""
118 import ctypes
119 # Load C kernel
120 lib_path = os.path.join(os.path.dirname(__file__), 'model', 'libq4matmul.so')
121 if not hasattr(self, '_q4_lib'):
122 self._q4_lib = ctypes.CDLL(lib_path)
123 self._q4_lib.q4_matmul_forward_t.argtypes = [
124 ctypes.POINTER(ctypes.c_uint8), ctypes.POINTER(ctypes.c_float),
125 ctypes.POINTER(ctypes.c_float), ctypes.c_int, ctypes.c_int, ctypes.c_int,
126 ]
127 self._q4_lib.q4_matmul_forward_t.restype = None
128
129 # Determine dimensions from raw GGUF format
130 # raw shape: (out_rows, N) where N = (in_cols / 32) * 18 for Q4_0
131 n_rows, row_bytes = raw.shape
132 in_cols = (row_bytes // 18) * 32
133
134 x_2d = x.reshape(-1, in_cols) if x.ndim == 1 else x
135 batch = x_2d.shape[0]
136
137 out = np.zeros((batch, n_rows), dtype=np.float32)
138 raw_buf = (ctypes.c_uint8 * raw.nbytes).from_buffer_copy(raw.tobytes())
139
140 self._q4_lib.q4_matmul_forward_t(
141 raw_buf,
142 x_2d.ctypes.data_as(ctypes.POINTER(ctypes.c_float)),
143 out.ctypes.data_as(ctypes.POINTER(ctypes.c_float)),
144 n_rows, in_cols, batch,
145 )
146 return out.reshape(x.shape[:-1] + (n_rows,))
147
148 def rms_norm(self, x, weight_name):
149 """RMSNormOp."""
150 _, w = self.weights[weight_name]
151 ss = np.mean(x ** 2, axis=-1, keepdims=True)
152 return x / np.sqrt(ss + self.norm_eps) * w
153
154 def rope(self, x, cos, sin):
155 """RoPEOp."""
156 n, h, d = x.shape
157 x2 = x.reshape(n, h, d // 2, 2)
158 xr = np.stack([-x2[..., 1], x2[..., 0]], axis=-1)
159 c = cos[:n, np.newaxis, :d // 2, np.newaxis]
160 s = sin[:n, np.newaxis, :d // 2, np.newaxis]
161 return (x2 * c + xr * s).reshape(n, h, d)
162
163 def silu(self, x):
164 """SiLUOp."""
165 return x / (1 + np.exp(-x))
166
167 def attention(self, q, k, v, mask):
168 """AttentionOp: softmax(Q @ K.T / sqrt(d)) @ V"""
169 d = q.shape[-1]
170 scores = (q @ k.swapaxes(-1, -2)) / (d ** 0.5) + mask
171 att = np.exp(scores - np.max(scores, axis=-1, keepdims=True))
172 att = att / np.sum(att, axis=-1, keepdims=True)
173 return att @ v
174
175 def forward(self, input_ids):
176 """Full forward pass — executes the Llama3 op graph via numpy."""
177 # Precompute RoPE
178 head_dim = self.n_embd // self.n_head
179 cos, sin = self._precompute_freqs(head_dim, len(input_ids))
180
181 # Embedding
182 h = self.embed(input_ids)
183
184 # KV cache
185 if self._kv_cache is not None:
186 cached_len = self._cached_len
187 new_ids = input_ids[cached_len:]
188 if len(new_ids) == 0:
189 return None
190 h = self.embed(new_ids)
191 return self._forward_step(h, cos, sin, cached_len)
192
193 # Full forward (prefill)
194 mask = np.triu(np.full((len(input_ids), len(input_ids)), -np.inf), 1)
195 return self._forward_full(h, cos, sin, mask)
196
197 def _forward_full(self, h, cos, sin, mask):
198 """Full forward pass through all layers."""
199 seq_len = h.shape[0]
200 head_dim = self.n_embd // self.n_head
201 n_rep = self.n_head // self.n_kv_head
202
203 self._kv_cache = []
204 self._cached_len = seq_len
205
206 for i in range(self.n_layers):
207 # Attention block
208 r = h
209 h = self.rms_norm(h, f'blk.{i}.attn_norm.weight')
210 q = self.matmul(f'blk.{i}.attn_q.weight', h)
211 k = self.matmul(f'blk.{i}.attn_k.weight', h)
212 v = self.matmul(f'blk.{i}.attn_v.weight', h)
213
214 q = q.reshape(seq_len, self.n_head, head_dim)
215 k = k.reshape(seq_len, self.n_kv_head, head_dim)
216 v = v.reshape(seq_len, self.n_kv_head, head_dim)
217 q = self.rope(q, cos, sin)
218 k = self.rope(k, cos, sin)
219
220 self._kv_cache.append((k.copy(), v.copy()))
221
222 if n_rep > 1:
223 k = np.repeat(k, n_rep, axis=1)
224 v = np.repeat(v, n_rep, axis=1)
225
226 # Transpose to (head, seq, dim) for attention
227 q_t = q.transpose(1, 0, 2)
228 k_t = k.transpose(1, 0, 2)
229 v_t = v.transpose(1, 0, 2)
230
231 att = self.attention(q_t, k_t, v_t, mask)
232 att = att.transpose(1, 0, 2).reshape(seq_len, self.n_embd)
233 h = r + self.matmul(f'blk.{i}.attn_output.weight', att)
234
235 # FFN block
236 r = h
237 h = self.rms_norm(h, f'blk.{i}.ffn_norm.weight')
238 gate = self.silu(self.matmul(f'blk.{i}.ffn_gate.weight', h))
239 up = self.matmul(f'blk.{i}.ffn_up.weight', h)
240 h = r + self.matmul(f'blk.{i}.ffn_down.weight', gate * up)
241
242 # Output
243 h = self.rms_norm(h, 'output_norm.weight')
244 logits = self.matmul('output.weight', h) if 'output.weight' in self.weights else h @ self.weights.get('token_embd.weight', (None, None))[1].T
245 return logits
246
247 def _forward_step(self, h, cos, sin, cached_len):
248 """Single-token forward with KV cache."""
249 new_len = h.shape[0]
250 new_total = cached_len + new_len
251 self._cached_len = new_total
252 head_dim = self.n_embd // self.n_head
253 n_rep = self.n_head // self.n_kv_head
254
255 for i in range(self.n_layers):
256 r = h
257 h = self.rms_norm(h, f'blk.{i}.attn_norm.weight')
258 q = self.matmul(f'blk.{i}.attn_q.weight', h)
259 k_new = self.matmul(f'blk.{i}.attn_k.weight', h)
260 v_new = self.matmul(f'blk.{i}.attn_v.weight', h)
261
262 q = q.reshape(new_len, self.n_head, head_dim)
263 k_new = k_new.reshape(new_len, self.n_kv_head, head_dim)
264 v_new = v_new.reshape(new_len, self.n_kv_head, head_dim)
265 q = self.rope(q, cos[cached_len:new_total], sin[cached_len:new_total])
266 k_new = self.rope(k_new, cos[cached_len:new_total], sin[cached_len:new_total])
267
268 k_cached, v_cached = self._kv_cache[i]
269 k = np.concatenate([k_cached, k_new], axis=0)
270 v = np.concatenate([v_cached, v_new], axis=0)
271 self._kv_cache[i] = (k, v)
272
273 if n_rep > 1:
274 k = np.repeat(k, n_rep, axis=1)
275 v = np.repeat(v, n_rep, axis=1)
276
277 mask = np.full((new_len, new_total), -np.inf, dtype=np.float32)
278 for j in range(new_len):
279 mask[j, :cached_len + j + 1] = 0.0
280
281 q_t = q.transpose(1, 0, 2)
282 k_t = k.transpose(1, 0, 2)
283 v_t = v.transpose(1, 0, 2)
284 att = self.attention(q_t, k_t, v_t, mask)
285 att = att.transpose(1, 0, 2).reshape(new_len, self.n_embd)
286 h = r + self.matmul(f'blk.{i}.attn_output.weight', att)
287
288 r = h
289 h = self.rms_norm(h, f'blk.{i}.ffn_norm.weight')
290 gate = self.silu(self.matmul(f'blk.{i}.ffn_gate.weight', h))
291 up = self.matmul(f'blk.{i}.ffn_up.weight', h)
292 h = r + self.matmul(f'blk.{i}.ffn_down.weight', gate * up)
293
294 h = self.rms_norm(h, 'output_norm.weight')
295 logits = self.matmul('output.weight', h) if 'output.weight' in self.weights else h @ self.weights['token_embd.weight'][1].T
296 return logits
297
298 def _precompute_freqs(self, dim, end):
299 theta = 500000.0
300 freqs = 1.0 / (theta ** (np.arange(0, dim, 2).astype(np.float32) / dim))
301 t = np.arange(end).astype(np.float32)
302 freqs = np.outer(t, freqs)
303 return np.cos(freqs), np.sin(freqs)
304
305 def generate(self, prompt: str, max_tokens: int = 50):
306 """Generate text from prompt."""
307 ids = self.tokenize(prompt)
308 out = []
309 self._kv_cache = None
310 self._cached_len = 0
311
312 for step in range(max_tokens):
313 logits = self.forward(ids)
314 if logits is None:
315 break
316 nid = int(np.argmax(logits[-1]))
317 if nid == self._eos_id():
318 break
319 out.append(nid)
320 ids.append(nid)
321
322 return self.detokenize(out)
323
324 def tokenize(self, text: str):
325 """Simple BPE tokenizer."""
326 from mojollama.model.inference import LLMInference
327 return LLMInference(self.path).encode(text)
328
329 def detokenize(self, ids):
330 from mojollama.model.inference import LLMInference
331 return LLMInference(self.path).decode(ids)
332
333 def _eos_id(self):
334 f = self.reader.get_field('tokenizer.ggml.eos_token_id')
335 if f is None:
336 return 2
337 return int(f.parts[-1].item()) if hasattr(f.parts[-1], 'item') else int(f.parts[-1])