MojoLlama
Archived Mojo/MAX quantizer and serving research repository (read-only history)
Brought by drakestapleton
MojoLlama / src / mojollama / model / inference.py
| 1 | """ |
| 2 | Python inference module for MojoLlama — memory-efficient per-layer processing. |
| 3 | Supports Qwen2 and Llama architectures from GGUF files. |
| 4 | With GPU acceleration: Intel Arc (SYCL), NVIDIA CUDA, or CPU. |
| 5 | """ |
| 6 | import gc |
| 7 | import logging |
| 8 | import os |
| 9 | import numpy as np |
| 10 | import gguf |
| 11 | # pyrefly: ignore [untyped-import] |
| 12 | import regex as re |
| 13 | |
| 14 | try: |
| 15 | from mojollama.model.device import get_device, DeviceBackend, DeviceType |
| 16 | except ImportError: |
| 17 | import sys, os |
| 18 | sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..')) |
| 19 | from mojollama.model.device import get_device, DeviceBackend, DeviceType |
| 20 | |
| 21 | try: |
| 22 | from mojollama.model.q4_kernels import Q4Matmul |
| 23 | _HAS_Q4 = True |
| 24 | except ImportError: |
| 25 | _HAS_Q4 = False |
| 26 | |
| 27 | try: |
| 28 | from mojollama.model.cq4_matmul import CQ4Matmul |
| 29 | _HAS_CQ4 = True |
| 30 | except ImportError: |
| 31 | _HAS_CQ4 = False |
| 32 | |
| 33 | logger = logging.getLogger(__name__) |
| 34 | |
| 35 | _gpt2_pat = re.compile(r"""(?:[sdmt]|ll|ve|re)| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+""") |
| 36 | # Llama 3 regex pattern (tiktoken-style pre-tokenization) |
| 37 | _llama3_pat = re.compile(r"""(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}{1,3}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+""") |
| 38 | |
| 39 | # GPT-2 byte-to-unicode encoder/decoder |
| 40 | _byte_encoder = {} |
| 41 | for i in range(ord('!'), ord('~') + 1): |
| 42 | _byte_encoder[i] = chr(i) |
| 43 | for i in range(ord('\xa1'), ord('\xac') + 1): |
| 44 | _byte_encoder[i] = chr(i) |
| 45 | for i in range(ord('\xae'), ord('\xff') + 1): |
| 46 | _byte_encoder[i] = chr(i) |
| 47 | bs = list(range(ord('!'), ord('~')+1)) + list(range(ord('\xa1'), ord('\xac')+1)) + list(range(ord('\xae'), ord('\xff')+1)) |
| 48 | n = 0 |
| 49 | for b in range(256): |
| 50 | if b not in bs: |
| 51 | _byte_encoder[b] = chr(256 + n) |
| 52 | n += 1 |
| 53 | _byte_decoder = {v: k for k, v in _byte_encoder.items()} |
| 54 | |
| 55 | def _bytes_to_unicode(s: bytes) -> str: |
| 56 | return ''.join(_byte_encoder[b] for b in s) |
| 57 | |
| 58 | def _unicode_to_bytes(s: str) -> bytes: |
| 59 | return bytes(_byte_decoder[c] for c in s) |
| 60 | |
| 61 | |
| 62 | def _get_np(val): |
| 63 | """Convert gguf scalar to Python value.""" |
| 64 | if val is None: |
| 65 | return None |
| 66 | if hasattr(val, 'parts'): |
| 67 | p = val.parts[-1] |
| 68 | if hasattr(p, 'item'): |
| 69 | return p.item() if p.size == 1 else p |
| 70 | return p |
| 71 | if isinstance(val, np.ndarray): |
| 72 | return val.item() if val.size == 1 else val |
| 73 | if isinstance(val, bytes): |
| 74 | return val.decode('utf-8', errors='replace') |
| 75 | return val |
| 76 | |
| 77 | |
| 78 | def to_cpu_if_needed(arr, device_backend=None): |
| 79 | """Convert device array to CPU numpy if needed.""" |
| 80 | if device_backend is not None and hasattr(arr, '__class__'): |
| 81 | import numpy as _np |
| 82 | if type(arr).__module__ != 'numpy': |
| 83 | try: |
| 84 | return _np.asarray(arr) |
| 85 | except Exception: |
| 86 | pass |
| 87 | return arr |
| 88 | |
| 89 | |
| 90 | class LLMInference: |
| 91 | """General LLM inference engine supporting multiple architectures from GGUF files.""" |
| 92 | |
| 93 | ARCH_PREFIXES = { |
| 94 | 'qwen2': ['qwen2.', 'qwen2moe.'], |
| 95 | 'llama': ['llama.', 'llama3.', 'llama2.', 'codellama.'], |
| 96 | } |
| 97 | |
| 98 | def __init__(self, path: str, device: str = 'auto'): |
| 99 | """ |
| 100 | Initialize inference engine. |
| 101 | |
| 102 | Args: |
| 103 | path: Path to GGUF model file |
| 104 | device: Compute device ('auto', 'cpu', 'intel_arc', 'nvidia') |
| 105 | Defaults to 'auto' which picks best available. |
| 106 | Override via MOJOLLAMA_DEVICE env var. |
| 107 | """ |
| 108 | # Initialize device backend |
| 109 | env_device = os.environ.get('MOJOLLAMA_DEVICE', '').lower() |
| 110 | self.device = get_device(env_device or device) |
| 111 | if not self.device.is_available: |
| 112 | print(f"[MojoLlama] Device '{self.device.device_type.value}' unavailable, falling back to CPU") |
| 113 | self.device = get_device('cpu') |
| 114 | print(f"[MojoLlama] Using device: {self.device.capability}") |
| 115 | |
| 116 | self.reader = gguf.GGUFReader(path) |
| 117 | self._tensors_by_name = {t.name: t for t in self.reader.tensors} |
| 118 | self._load_config() |
| 119 | self._build_tokenizer() |
| 120 | self._device_tensors = {} # GPU-side tensor cache |
| 121 | self._init_q4_matmuls() |
| 122 | |
| 123 | def _try_config(self, key: str, default=None): |
| 124 | f = self.reader.get_field |
| 125 | for prefix in self._config_prefixes: |
| 126 | v = f(f'{prefix}{key}') |
| 127 | if v is not None: |
| 128 | return _get_np(v) |
| 129 | v = f(key) |
| 130 | if v is not None: |
| 131 | return _get_np(v) |
| 132 | return default |
| 133 | |
| 134 | def _load_config(self): |
| 135 | f = self.reader.get_field |
| 136 | arch_field = f('general.architecture') |
| 137 | arch_val = _get_np(arch_field) if arch_field else None |
| 138 | if isinstance(arch_val, np.ndarray) and arch_val.dtype.kind == 'u': |
| 139 | arch_str = arch_val.tobytes().decode('utf-8', errors='replace') |
| 140 | elif isinstance(arch_val, bytes): |
| 141 | arch_str = arch_val.decode('utf-8', errors='replace') |
| 142 | elif arch_val is not None: |
| 143 | arch_str = str(arch_val) |
| 144 | else: |
| 145 | arch_str = 'unknown' |
| 146 | self.arch = arch_str |
| 147 | |
| 148 | if arch_str in self.ARCH_PREFIXES: |
| 149 | self._config_prefixes = self.ARCH_PREFIXES[arch_str] |
| 150 | else: |
| 151 | all_prefixes = set() |
| 152 | for prefixes in self.ARCH_PREFIXES.values(): |
| 153 | all_prefixes.update(prefixes) |
| 154 | self._config_prefixes = [f'{arch_str}.'] + sorted(all_prefixes) |
| 155 | |
| 156 | self.n_layers = int(self._try_config('block_count', 0)) |
| 157 | self.n_embd = int(self._try_config('embedding_length', 0)) |
| 158 | self.n_head = int(self._try_config('attention.head_count', 0)) |
| 159 | self.n_kv_head = int(self._try_config('attention.head_count_kv', 0)) |
| 160 | self.n_ff = int(self._try_config('feed_forward_length', 0)) |
| 161 | self.max_seq_len = int(self._try_config('context_length', |
| 162 | self._try_config('max_position_embeddings', 32768))) |
| 163 | self.norm_eps = float(self._try_config('attention.layer_norm_rms_epsilon', |
| 164 | self._try_config('attn_layer_norm_rms_epsilon', 1e-6))) |
| 165 | base = self._try_config('rope.freq_base', None) |
| 166 | self.rope_theta = float(base) if base is not None else 1000000.0 |
| 167 | self.rope_type = self._try_config('rope.type', 'default') |
| 168 | self.has_bias = False |
| 169 | t0 = self._tensors_by_name.get('blk.0.attn_q.bias') |
| 170 | if t0 is not None: |
| 171 | self.has_bias = True |
| 172 | |
| 173 | print(f"[MojoLlama] Architecture: {arch_str}") |
| 174 | print(f"[MojoLlama] Layers: {self.n_layers}, dim: {self.n_embd}, heads: {self.n_head}, kv_heads: {self.n_kv_head}") |
| 175 | print(f"[MojoLlama] FFN dim: {self.n_ff}, max_seq_len: {self.max_seq_len}") |
| 176 | print(f"[MojoLlama] norm_eps: {self.norm_eps}, rope_theta: {self.rope_theta}") |
| 177 | print(f"[MojoLlama] rope_type: {self.rope_type}, has_bias: {self.has_bias}") |
| 178 | |
| 179 | def _tensor(self, gguf_name: str): |
| 180 | """Load a tensor from GGUF and move to device if accelerator is active.""" |
| 181 | # Check device cache first |
| 182 | if gguf_name in self._device_tensors: |
| 183 | return self._device_tensors[gguf_name] |
| 184 | |
| 185 | t = self._tensors_by_name.get(gguf_name) |
| 186 | if t is None: |
| 187 | return None |
| 188 | |
| 189 | # Dequantize / load to numpy |
| 190 | if hasattr(t, 'tensor_type') and t.tensor_type is not None: |
| 191 | tt = t.tensor_type |
| 192 | if tt == gguf.GGMLQuantizationType.F32: |
| 193 | arr = np.array(t.data, dtype=np.float32) |
| 194 | elif tt == gguf.GGMLQuantizationType.F16: |
| 195 | arr = np.array(t.data, dtype=np.float16).astype(np.float32) |
| 196 | else: |
| 197 | try: |
| 198 | arr = gguf.dequantize(t.data, tt) |
| 199 | except Exception: |
| 200 | arr = np.array(t.data, dtype=np.float32) |
| 201 | else: |
| 202 | arr = np.array(t.data, dtype=np.float32) |
| 203 | |
| 204 | # Move to device if we have a GPU backend |
| 205 | if self.device.device_type != DeviceType.CPU: |
| 206 | device_arr = self.device.to_device(arr) |
| 207 | self._device_tensors[gguf_name] = device_arr |
| 208 | return device_arr |
| 209 | |
| 210 | return arr |
| 211 | |
| 212 | def _get_persistent(self, name: str): |
| 213 | if not hasattr(self, '_persistent_cache'): |
| 214 | self._persistent_cache = {} |
| 215 | if name not in self._persistent_cache: |
| 216 | self._persistent_cache[name] = self._tensor(name) |
| 217 | return self._persistent_cache[name] |
| 218 | |
| 219 | def _init_q4_matmuls(self): |
| 220 | """Pre-load all Q4_0 tensors as Q4Matmul objects (correct Python kernel).""" |
| 221 | self._q4_matmuls = {} |
| 222 | from gguf.constants import GGMLQuantizationType |
| 223 | count = 0 |
| 224 | kernel_type = "Python" |
| 225 | for name, t in self._tensors_by_name.items(): |
| 226 | if hasattr(t, 'tensor_type') and t.tensor_type == GGMLQuantizationType.Q4_0: |
| 227 | try: |
| 228 | if _HAS_Q4: |
| 229 | self._q4_matmuls[name] = Q4Matmul.from_gguf_tensor(t) |
| 230 | elif _HAS_CQ4: |
| 231 | self._q4_matmuls[name] = CQ4Matmul.from_gguf_tensor(t) |
| 232 | kernel_type = "C (may have wrong nibble order)" |
| 233 | else: |
| 234 | continue |
| 235 | count += 1 |
| 236 | except Exception: |
| 237 | pass |
| 238 | if count: |
| 239 | print(f"[MojoLlama] {kernel_type} Q4 kernel ready for {count} weight tensors") |
| 240 | |
| 241 | def _q4_matmul(self, name: str, x: np.ndarray, transposed: bool = True) -> np.ndarray: |
| 242 | """Compute x @ W.T (or x @ W) using Q4_0 kernel. |
| 243 | |
| 244 | Python Q4Matmul is preferred (correct GGUF format). Falls back to |
| 245 | C kernel (which has wrong nibble order - use at your own risk), |
| 246 | or dequant + BLAS as last resort. |
| 247 | """ |
| 248 | if _HAS_CQ4 and name in self._q4_matmuls: |
| 249 | return self._q4_matmuls[name].forward_t(x) |
| 250 | # Fallback: dequant + BLAS |
| 251 | W = self._tensor(name) |
| 252 | if transposed: |
| 253 | return x @ W.T |
| 254 | return x @ W |
| 255 | |
| 256 | def _build_tokenizer(self): |
| 257 | fields = self.reader.fields |
| 258 | token_field = fields.get('tokenizer.ggml.tokens') |
| 259 | merge_field = fields.get('tokenizer.ggml.merges') |
| 260 | |
| 261 | # Build vocab: raw_bytes -> token_id (for Llama 3), utf8_str -> token_id (for Qwen2) |
| 262 | self._token_bytes = {} # bytes -> id |
| 263 | self.vocab = {} # str -> id (for GPT-2 style) |
| 264 | header_size = 5 |
| 265 | if token_field: |
| 266 | parts = list(token_field.parts) |
| 267 | n_tokens = int(parts[4].item()) if len(parts) > 4 else 0 |
| 268 | for i in range(n_tokens): |
| 269 | data_idx = header_size + i * 2 + 1 |
| 270 | if data_idx >= len(parts): |
| 271 | break |
| 272 | token_data = parts[data_idx].tobytes() if hasattr(parts[data_idx], 'tobytes') else b'' |
| 273 | self._token_bytes[token_data] = i |
| 274 | try: |
| 275 | s = token_data.decode('utf-8', errors='replace') |
| 276 | self.vocab[s] = i |
| 277 | except: |
| 278 | self.vocab[token_data.hex()] = i |
| 279 | |
| 280 | # Build merge_ranks: (str, str) -> rank in GPT-2 encoded form |
| 281 | self.merge_ranks = {} |
| 282 | if merge_field: |
| 283 | parts = list(merge_field.parts) |
| 284 | n_merges = int(parts[4].item()) if len(parts) > 4 else 0 |
| 285 | for i in range(n_merges): |
| 286 | data_idx = header_size + i * 2 + 1 |
| 287 | if data_idx >= len(parts): |
| 288 | break |
| 289 | merge_data = parts[data_idx].tobytes() if hasattr(parts[data_idx], 'tobytes') else b'' |
| 290 | try: |
| 291 | s = merge_data.decode('utf-8', errors='replace') |
| 292 | sp = s.split(' ') |
| 293 | if len(sp) == 2: |
| 294 | self.merge_ranks[tuple(sp)] = i |
| 295 | except: |
| 296 | pass |
| 297 | |
| 298 | bos = fields.get('tokenizer.ggml.bos_token_id') |
| 299 | self.bos_id = int(_get_np(bos)) if bos else 1 |
| 300 | eos = fields.get('tokenizer.ggml.eos_token_id') |
| 301 | self.eos_id = int(_get_np(eos)) if eos else 2 |
| 302 | add = fields.get('tokenizer.ggml.add_bos_token') |
| 303 | self.add_bos = bool(int(_get_np(add))) if add else True |
| 304 | |
| 305 | # Detect if this is a tiktoken-style vocab (Llama 3+) |
| 306 | self._is_tiktok = len(self.vocab) >= 128000 and len(self.merge_ranks) > 250000 |
| 307 | |
| 308 | print(f"[MojoLlama] Vocab size: {len(self.vocab)}, merges: {len(self.merge_ranks)}") |
| 309 | print(f"[MojoLlama] BOS: {self.bos_id}, EOS: {self.eos_id}, add_bos: {self.add_bos}") |
| 310 | |
| 311 | def encode(self, text: str) -> list[int]: |
| 312 | """Encode text to token IDs using BPE.""" |
| 313 | ids = self._encode_bpe(text) |
| 314 | if self.add_bos: |
| 315 | ids = [self.bos_id] + ids |
| 316 | return ids |
| 317 | |
| 318 | def decode(self, ids: list[int]) -> str: |
| 319 | """Decode token IDs back to text.""" |
| 320 | # Build reverse lookup if not cached |
| 321 | if not hasattr(self, '_id_to_bytes'): |
| 322 | self._id_to_bytes = {v: k for k, v in self._token_bytes.items()} |
| 323 | raw_chunks = [] |
| 324 | for tid in ids: |
| 325 | tb = self._id_to_bytes.get(tid) |
| 326 | if tb is not None: |
| 327 | gpt2_str = tb.decode('utf-8', errors='replace') |
| 328 | raw_chunks.append(gpt2_str) |
| 329 | full_gpt2 = ''.join(raw_chunks) |
| 330 | try: |
| 331 | return _unicode_to_bytes(full_gpt2).decode('utf-8', errors='replace') |
| 332 | except: |
| 333 | return full_gpt2 |
| 334 | |
| 335 | def _encode_bpe(self, text: str) -> list[int]: |
| 336 | """BPE encoding. For tiktoken vocabs: uses GPT-2 byte encoding for merges, |
| 337 | then encodes as UTF-8 for vocab lookup.""" |
| 338 | import ftfy |
| 339 | text = ftfy.fix_text(text) |
| 340 | |
| 341 | if self._is_tiktok: |
| 342 | pat = _llama3_pat |
| 343 | else: |
| 344 | pat = _gpt2_pat |
| 345 | |
| 346 | tokens = [] |
| 347 | for m in re.findall(pat, text): |
| 348 | # Convert word to GPT-2 byte-encoded form |
| 349 | gpt2_str = _bytes_to_unicode(m.encode('utf-8')) |
| 350 | |
| 351 | # BPE merge loop on GPT-2 encoded string |
| 352 | pairs = list(gpt2_str) |
| 353 | while True: |
| 354 | best = None |
| 355 | rank = None |
| 356 | for i in range(len(pairs) - 1): |
| 357 | key = (pairs[i], pairs[i+1]) |
| 358 | r = self.merge_ranks.get(key) |
| 359 | if r is not None and (rank is None or r < rank): |
| 360 | best = i |
| 361 | rank = r |
| 362 | if best is None: |
| 363 | break |
| 364 | pairs = pairs[:best] + [pairs[best] + pairs[best+1]] + pairs[best+2:] |
| 365 | |
| 366 | # Look up each merged GPT-2 token: encode as UTF-8 and find in token_bytes |
| 367 | for token_gpt2 in pairs: |
| 368 | token_utf8 = token_gpt2.encode('utf-8') |
| 369 | tid = self._token_bytes.get(token_utf8, 0) |
| 370 | tokens.append(tid) |
| 371 | |
| 372 | return tokens |
| 373 | |
| 374 | # ─── Device-aware ops ────────────────────────────────────────────────── |
| 375 | |
| 376 | def rms_norm(self, x, weight, eps=1e-6): |
| 377 | return self.device.rms_norm(x, weight, eps) |
| 378 | |
| 379 | @staticmethod |
| 380 | def precompute_freqs_cis(dim: int, end: int, theta: float): |
| 381 | freqs = 1.0 / (theta ** (np.arange(0, dim, 2).astype(np.float32) / dim)) |
| 382 | t = np.arange(end).astype(np.float32) |
| 383 | freqs = np.outer(t, freqs) |
| 384 | return np.cos(freqs), np.sin(freqs) |
| 385 | |
| 386 | def apply_rope(self, x, cos, sin): |
| 387 | return self.device.rope(x, cos, sin) |
| 388 | |
| 389 | def silu(self, x): |
| 390 | return self.device.silu(x) |
| 391 | |
| 392 | def softmax(self, x, axis=-1): |
| 393 | return self.device.softmax(x, axis) |
| 394 | |
| 395 | # ─── Attention helper (device-aware) ─────────────────────────────────── |
| 396 | |
| 397 | def _attention_scores(self, q, k, head_dim: float): |
| 398 | """Compute attention scores using device-aware batch matmul.""" |
| 399 | # For single-query (cached step), use simple loop to avoid einsum overhead |
| 400 | if q.shape[0] == 1 and k.shape[0] <= 128: |
| 401 | # Simple dot product: (1, n_head, d) · (n_keys, n_head, d) for each head |
| 402 | q_t = q[0] # (n_head, d) |
| 403 | k_t = k # (n_keys, n_head, d) |
| 404 | # (n_head, 1, n_keys) = (n_head, d) · (n_head, d, n_keys) |
| 405 | scores = np.matmul(q_t[:, np.newaxis, :], k_t.transpose(1, 2, 0)) / head_dim |
| 406 | return scores.squeeze(1) # (n_head, n_keys) |
| 407 | q_t = q.transpose(1, 0, 2) |
| 408 | k_t = k.transpose(1, 0, 2) |
| 409 | return self.device.matmul(q_t, k_t.swapaxes(-1, -2)) / head_dim |
| 410 | |
| 411 | def _attention_apply(self, att, v): |
| 412 | """Apply attention weights to values.""" |
| 413 | if att.ndim == 2: |
| 414 | # Single-query: att is (n_head, n_keys), v is (n_keys, n_kv_head, d) |
| 415 | # (n_head, d) = (n_head, n_keys) · (n_keys, n_head, d) for each head |
| 416 | # Or simpler: v_rep shape is (n_keys, n_head, d) |
| 417 | # (n_head, d) = einsum('hk,khd->hd', att, v) |
| 418 | n_head = att.shape[0] |
| 419 | d = v.shape[2] |
| 420 | out = np.zeros((n_head, d), dtype=np.float32) |
| 421 | for h in range(n_head): |
| 422 | out[h] = att[h] @ v[:, h] |
| 423 | return out[np.newaxis, :, :] # (1, n_head, d) |
| 424 | v_t = v.transpose(1, 0, 2) |
| 425 | out = self.device.matmul(att, v_t) |
| 426 | return out.transpose(1, 0, 2) |
| 427 | |
| 428 | # ─── Forward passes ──────────────────────────────────────────────────── |
| 429 | |
| 430 | def forward(self, input_ids: list[int], use_cache: bool = True): |
| 431 | seq_len = len(input_ids) |
| 432 | h_ids = np.array(input_ids, dtype=np.int64) |
| 433 | embed = self._get_persistent('token_embd.weight') |
| 434 | |
| 435 | head_dim = self.n_embd // self.n_head |
| 436 | n_rep = self.n_head // self.n_kv_head |
| 437 | |
| 438 | # KV cache management |
| 439 | if use_cache and hasattr(self, '_kv_cache') and self._kv_cache is not None: |
| 440 | cached_len = self._cached_len |
| 441 | new_ids = h_ids[cached_len:] |
| 442 | x = embed[new_ids].astype(np.float32) |
| 443 | cos, sin = self.precompute_freqs_cis(head_dim, seq_len, self.rope_theta) |
| 444 | return self._forward_step(x, cos, sin, head_dim, n_rep, cached_len) |
| 445 | else: |
| 446 | # Full forward pass (prefill) |
| 447 | x = embed[h_ids].astype(np.float32) |
| 448 | cos, sin = self.precompute_freqs_cis(head_dim, seq_len, self.rope_theta) |
| 449 | mask = np.triu(np.full((seq_len, seq_len), -np.inf, dtype=np.float32), 1) |
| 450 | result = self._forward_full(x, cos, sin, mask, head_dim, n_rep, use_cache) |
| 451 | return result |
| 452 | |
| 453 | def _forward_full(self, x, cos, sin, mask, head_dim, n_rep, use_cache): |
| 454 | """Full forward pass (prefill).""" |
| 455 | seq_len = x.shape[0] |
| 456 | use_gpu = self.device.device_type != DeviceType.CPU |
| 457 | |
| 458 | if use_cache: |
| 459 | self._kv_cache = [] |
| 460 | self._cached_len = seq_len |
| 461 | |
| 462 | # Move inputs to device if using GPU |
| 463 | if use_gpu: |
| 464 | x = self.device.to_device(x) |
| 465 | cos = self.device.to_device(cos) |
| 466 | sin = self.device.to_device(sin) |
| 467 | mask = self.device.to_device(mask) |
| 468 | |
| 469 | for i in range(self.n_layers): |
| 470 | ln1 = self._tensor(f'blk.{i}.attn_norm.weight') |
| 471 | |
| 472 | r = x |
| 473 | x = self.rms_norm(x, ln1, self.norm_eps) |
| 474 | q = self._q4_matmul(f'blk.{i}.attn_q.weight', x) |
| 475 | k = self._q4_matmul(f'blk.{i}.attn_k.weight', x) |
| 476 | v = self._q4_matmul(f'blk.{i}.attn_v.weight', x) |
| 477 | |
| 478 | if self.has_bias: |
| 479 | for qkv_b_name in ['attn_q', 'attn_k', 'attn_v']: |
| 480 | b = self._tensor(f'blk.{i}.{qkv_b_name}.bias') |
| 481 | if b is not None: |
| 482 | if qkv_b_name == 'attn_q': |
| 483 | q = q + b |
| 484 | elif qkv_b_name == 'attn_k': |
| 485 | k = k + b |
| 486 | else: |
| 487 | v = v + b |
| 488 | |
| 489 | q = q.reshape(seq_len, self.n_head, head_dim) |
| 490 | k = k.reshape(seq_len, self.n_kv_head, head_dim) |
| 491 | v = v.reshape(seq_len, self.n_kv_head, head_dim) |
| 492 | q = self.apply_rope(q, cos, sin) |
| 493 | k = self.apply_rope(k, cos, sin) |
| 494 | |
| 495 | if use_cache: |
| 496 | self._kv_cache.append((k.copy() if hasattr(k, 'copy') else k[:], v.copy() if hasattr(v, 'copy') else v[:])) |
| 497 | |
| 498 | if n_rep > 1: |
| 499 | k = np.repeat(k, n_rep, axis=1) |
| 500 | v = np.repeat(v, n_rep, axis=1) |
| 501 | |
| 502 | att = self._attention_scores(q, k, np.sqrt(head_dim)) |
| 503 | att = att + mask |
| 504 | att = self.softmax(att, axis=-1) |
| 505 | out = self._attention_apply(att, v) |
| 506 | out = out.reshape(seq_len, self.n_embd) |
| 507 | out = self._q4_matmul(f'blk.{i}.attn_output.weight', out) |
| 508 | x = r + out |
| 509 | |
| 510 | r = x |
| 511 | x = self.rms_norm(x, self._tensor(f'blk.{i}.ffn_norm.weight'), self.norm_eps) |
| 512 | gate = self._q4_matmul(f'blk.{i}.ffn_gate.weight', x) |
| 513 | up = self._q4_matmul(f'blk.{i}.ffn_up.weight', x) |
| 514 | x = (self.silu(gate) * up) |
| 515 | x = self._q4_matmul(f'blk.{i}.ffn_down.weight', x) |
| 516 | x = r + x |
| 517 | |
| 518 | norm_w = self._tensor('output_norm.weight') |
| 519 | x = self.rms_norm(x, norm_w, self.norm_eps) |
| 520 | lm_w = self._tensor('output.weight') |
| 521 | if lm_w is None: |
| 522 | embed = self._get_persistent('token_embd.weight') |
| 523 | lm_w = embed |
| 524 | logits = self.device.matmul(x, lm_w.T) if use_gpu else x @ lm_w.T |
| 525 | |
| 526 | # Ensure logits are on CPU for Python consumption |
| 527 | if use_gpu: |
| 528 | logits = to_cpu_if_needed(logits) |
| 529 | return logits |
| 530 | |
| 531 | def _forward_step(self, x, cos, sin, head_dim, n_rep, cached_len): |
| 532 | """Single-token forward step using KV cache.""" |
| 533 | new_len = x.shape[0] |
| 534 | new_total = cached_len + new_len |
| 535 | self._cached_len = new_total |
| 536 | use_gpu = self.device.device_type != DeviceType.CPU |
| 537 | |
| 538 | # Move inputs to device if using GPU |
| 539 | if use_gpu: |
| 540 | x = self.device.to_device(x) |
| 541 | |
| 542 | for i in range(self.n_layers): |
| 543 | ln1 = self._tensor(f'blk.{i}.attn_norm.weight') |
| 544 | |
| 545 | r = x |
| 546 | x = self.rms_norm(x, ln1, self.norm_eps) |
| 547 | q = self._q4_matmul(f'blk.{i}.attn_q.weight', x) |
| 548 | k_new = self._q4_matmul(f'blk.{i}.attn_k.weight', x) |
| 549 | v_new = self._q4_matmul(f'blk.{i}.attn_v.weight', x) |
| 550 | |
| 551 | if self.has_bias: |
| 552 | for qkv_b_name in ['attn_q', 'attn_k', 'attn_v']: |
| 553 | b = self._tensor(f'blk.{i}.{qkv_b_name}.bias') |
| 554 | if b is not None: |
| 555 | if qkv_b_name == 'attn_q': |
| 556 | q = q + b |
| 557 | elif qkv_b_name == 'attn_k': |
| 558 | k_new = k_new + b |
| 559 | else: |
| 560 | v_new = v_new + b |
| 561 | |
| 562 | q = q.reshape(new_len, self.n_head, head_dim) |
| 563 | k_new = k_new.reshape(new_len, self.n_kv_head, head_dim) |
| 564 | v_new = v_new.reshape(new_len, self.n_kv_head, head_dim) |
| 565 | |
| 566 | # Apply RoPE to new token positions |
| 567 | q = self.apply_rope(q, cos[cached_len:new_total], sin[cached_len:new_total]) |
| 568 | k_new = self.apply_rope(k_new, cos[cached_len:new_total], sin[cached_len:new_total]) |
| 569 | |
| 570 | # Update KV cache |
| 571 | k_cached, v_cached = self._kv_cache[i] |
| 572 | k = np.concatenate([k_cached, k_new], axis=0) |
| 573 | v = np.concatenate([v_cached, v_new], axis=0) |
| 574 | self._kv_cache[i] = (k, v) |
| 575 | |
| 576 | if n_rep > 1: |
| 577 | k = np.repeat(k, n_rep, axis=1) |
| 578 | v = np.repeat(v, n_rep, axis=1) |
| 579 | |
| 580 | # Attention |
| 581 | att = self._attention_scores(q, k, np.sqrt(head_dim)) |
| 582 | # Build causal mask for new tokens |
| 583 | mask = np.full((new_len, new_total), -np.inf, dtype=np.float32) |
| 584 | for j in range(new_len): |
| 585 | pos = cached_len + j |
| 586 | mask[j, :pos+1] = 0.0 |
| 587 | if use_gpu: |
| 588 | mask = self.device.to_device(mask) |
| 589 | att = att + mask |
| 590 | att = self.softmax(att, axis=-1) |
| 591 | out = self._attention_apply(att, v) |
| 592 | out = out.reshape(new_len, self.n_embd) |
| 593 | out = self._q4_matmul(f'blk.{i}.attn_output.weight', out) |
| 594 | x = r + out |
| 595 | |
| 596 | r = x |
| 597 | x = self.rms_norm(x, self._tensor(f'blk.{i}.ffn_norm.weight'), self.norm_eps) |
| 598 | gate = self._q4_matmul(f'blk.{i}.ffn_gate.weight', x) |
| 599 | up = self._q4_matmul(f'blk.{i}.ffn_up.weight', x) |
| 600 | x = (self.silu(gate) * up) |
| 601 | x = self._q4_matmul(f'blk.{i}.ffn_down.weight', x) |
| 602 | x = r + x |
| 603 | |
| 604 | norm_w = self._tensor('output_norm.weight') |
| 605 | x = self.rms_norm(x, norm_w, self.norm_eps) |
| 606 | lm_w = self._tensor('output.weight') |
| 607 | if lm_w is None: |
| 608 | embed = self._get_persistent('token_embd.weight') |
| 609 | lm_w = embed |
| 610 | logits = self.device.matmul(x, lm_w.T) if use_gpu else x @ lm_w.T |
| 611 | |
| 612 | if use_gpu: |
| 613 | logits = to_cpu_if_needed(logits) |
| 614 | return logits |
| 615 | |
| 616 | def generate(self, prompt: str, max_tokens: int = 50) -> str: |
| 617 | ids = self.encode(prompt) |
| 618 | out = [] |
| 619 | # Reset KV cache |
| 620 | self._kv_cache = None |
| 621 | self._cached_len = 0 |
| 622 | |
| 623 | for step in range(max_tokens): |
| 624 | logits = self.forward(ids, use_cache=True) |
| 625 | logits_np = to_cpu_if_needed(logits) |
| 626 | nid = int(np.argmax(logits_np[-1])) |
| 627 | if nid == self.eos_id: |
| 628 | break |
| 629 | out.append(nid) |
| 630 | ids.append(nid) |
| 631 | if (step + 1) % 10 == 0: |
| 632 | print(f" [step {step+1}/{max_tokens}] token={nid}") |
| 633 | gc.collect() |
| 634 | return self.decode(out) |
| 635 | |
| 636 | |
| 637 | def load_model(path: str, device: str = 'auto'): |
| 638 | """Load a GGUF model with device auto-detection. |
| 639 | |
| 640 | Args: |
| 641 | path: Path to GGUF file. |
| 642 | device: Device to use. 'auto' (default) picks best available. |
| 643 | Options: 'auto', 'cpu', 'intel_arc', 'nvidia'. |
| 644 | Override via MOJOLLAMA_DEVICE env var. |
| 645 | """ |
| 646 | return LLMInference(path, device=device) |
| 647 | |
| 648 | |
| 649 | def list_compute_devices(): |
| 650 | """List all available compute devices.""" |
| 651 | from mojollama.model.device import list_devices |
| 652 | return list_devices() |
| 653 | |
| 654 | |
| 655 | if __name__ == '__main__': |
| 656 | import sys |
| 657 | if len(sys.argv) > 1: |
| 658 | path = sys.argv[1] |
| 659 | device_arg = sys.argv[4] if len(sys.argv) > 4 else 'auto' |
| 660 | print(f"Loading model from: {path}") |
| 661 | print(f"Device: {device_arg}") |
| 662 | model = load_model(path, device=device_arg) |
| 663 | prompt = sys.argv[2] if len(sys.argv) > 2 else "The capital of France is" |
| 664 | tokens = int(sys.argv[3]) if len(sys.argv) > 3 else 10 |
| 665 | print(f"Testing generate with prompt: '{prompt}' ({tokens} tokens)") |
| 666 | result = model.generate(prompt, max_tokens=tokens) |
| 667 | print(f"Generated: {result}") |
| 668 | else: |
| 669 | print("Usage: python inference.py <model.gguf> [prompt] [max_tokens] [device]") |
| 670 | print(" device: auto (default), cpu, intel_arc, nvidia") |
| 671 | print(" Or set MOJOLLAMA_DEVICE env var") |