MojoLlama
Archived Mojo/MAX quantizer and serving research repository (read-only history)
Brought by drakestapleton
MojoLlama / src / mojollama / model / architectures.py
| 1 | """ |
| 2 | architectures.py — Dynamic model architecture detection for MojoLlama. |
| 3 | |
| 4 | Reads GGUF metadata (general.architecture field) or Hugging Face config.json |
| 5 | (model_type field) and returns a standardized ForwardPassType enum value. |
| 6 | |
| 7 | This is the single source of truth for determining which forward pass |
| 8 | implementation the MojoLlama engine should use (DENSE, MOE, GEMMA, etc.). |
| 9 | |
| 10 | Usage: |
| 11 | from mojollama.model.architectures import ( |
| 12 | detect_architecture, |
| 13 | get_forward_pass_type, |
| 14 | get_model_params, |
| 15 | print_supported_models, |
| 16 | ForwardPassType, |
| 17 | ) |
| 18 | |
| 19 | # GGUF reader |
| 20 | reader = gguf.GGUFReader(path) |
| 21 | arch = detect_architecture(reader) |
| 22 | fwd_type = get_forward_pass_type(arch) |
| 23 | |
| 24 | # HF config |
| 25 | import json |
| 26 | with open("config.json") as f: |
| 27 | cfg = json.load(f) |
| 28 | fwd_type = get_forward_pass_type(cfg) |
| 29 | """ |
| 30 | |
| 31 | import json |
| 32 | import logging |
| 33 | import sys |
| 34 | from enum import Enum |
| 35 | from pathlib import Path |
| 36 | from typing import Any, Dict, Optional, Union |
| 37 | |
| 38 | # Conditional imports so this module can work without every dependency |
| 39 | try: |
| 40 | import gguf |
| 41 | from gguf import MODEL_ARCH, MODEL_ARCH_NAMES, MODEL_TENSORS, MODEL_TENSOR |
| 42 | _HAS_GGUF = True |
| 43 | except ImportError: |
| 44 | _HAS_GGUF = False |
| 45 | |
| 46 | logger = logging.getLogger(__name__) |
| 47 | |
| 48 | |
| 49 | # ────────────────────────────────────────────── |
| 50 | # Forward Pass Type Enum |
| 51 | # ────────────────────────────────────────────── |
| 52 | |
| 53 | |
| 54 | class ForwardPassType(str, Enum): |
| 55 | """Standardized forward-pass categories for MojoLlama. |
| 56 | |
| 57 | Each value maps to a specific forward-pass implementation in the engine. |
| 58 | """ |
| 59 | DENSE = "dense" |
| 60 | """Standard dense transformer (LLaMA, Mistral, Qwen2, etc.). |
| 61 | Uses: RMSNorm → attention → RoPE → SwiGLU FFN.""" |
| 62 | |
| 63 | MOE = "moe" |
| 64 | """Mixture-of-Experts transformer (Qwen3 MoE, DeepSeek V2, Mixtral, GPT-OSS). |
| 65 | Uses: RMSNorm → attention → RoPE → router → top-k experts.""" |
| 66 | |
| 67 | DEEPSEEK_V4 = "deepseek_v4" |
| 68 | """DeepSeek V4 Flash (MLA, HC, sparse attention, hash+learned MoE routing). |
| 69 | 43L/4096D/64H/1KV, Q_lora=1024, O_lora=1024, 256 experts×6. |
| 70 | Uses: embed → HC-expand → (HC-pre → attn_norm → MLA → HC-post → |
| 71 | HC-pre → ffn_norm → MoE-FFN → HC-post)x43 → HC-head → norm → lm_head.""" |
| 72 | |
| 73 | GEMMA = "gemma" |
| 74 | """Google Gemma/Gemma2 (GeGLU activation, pre-norm, no RoPE on K). |
| 75 | Uses: RMSNorm → attention → GeGLU FFN (or gating variant).""" |
| 76 | |
| 77 | GEMMA3 = "gemma3" |
| 78 | """Google Gemma 3 (with sliding window attention, multi-layer kv heads).""" |
| 79 | |
| 80 | QWEN2 = "qwen2" |
| 81 | """Qwen2 dense (SwiGLU, advanced RoPE with mrope/dual-ft, TNT embedding).""" |
| 82 | |
| 83 | QWEN3 = "qwen3" |
| 84 | """Qwen3 dense variant (SwiGLU, TNT, mrope, optional prefix-lm).""" |
| 85 | |
| 86 | STARCODER = "starcoder" |
| 87 | """StarCoder / StarCoder2 (Falcon-style parallel attention + MLP).""" |
| 88 | |
| 89 | DEEPSEEK = "deepseek" |
| 90 | """DeepSeek V1/V2 dense (SwiGLU, MLA attention for V2).""" |
| 91 | |
| 92 | COMMAND_R = "command-r" |
| 93 | """Cohere Command-R dense (SwiGLU, tanh-gated RoPE, layer-wise LR).""" |
| 94 | |
| 95 | BERT = "bert" |
| 96 | """Encoder-only BERT-style (masked language modelling).""" |
| 97 | |
| 98 | UNKNOWN = "unknown" |
| 99 | """Unrecognised architecture; fall back to DENSE.""" |
| 100 | |
| 101 | # ── Classification helpers ── |
| 102 | |
| 103 | @property |
| 104 | def is_moe(self) -> bool: |
| 105 | return self in (ForwardPassType.MOE,) |
| 106 | |
| 107 | @property |
| 108 | def is_dense(self) -> bool: |
| 109 | return self not in (ForwardPassType.MOE, ForwardPassType.UNKNOWN) |
| 110 | |
| 111 | @property |
| 112 | def is_gemma_family(self) -> bool: |
| 113 | return self in (ForwardPassType.GEMMA, ForwardPassType.GEMMA3) |
| 114 | |
| 115 | |
| 116 | # ────────────────────────────────────────────── |
| 117 | # Architecture string → ForwardPassType mapping |
| 118 | # ────────────────────────────────────────────── |
| 119 | |
| 120 | # Maps GGUF general.architecture values to ForwardPassType |
| 121 | GGUF_ARCH_MAP: Dict[str, ForwardPassType] = { |
| 122 | # ── Dense ── |
| 123 | "llama": ForwardPassType.DENSE, |
| 124 | "llama2": ForwardPassType.DENSE, |
| 125 | "llama3": ForwardPassType.DENSE, |
| 126 | "llama4": ForwardPassType.DENSE, |
| 127 | "codellama": ForwardPassType.DENSE, |
| 128 | "mistral": ForwardPassType.DENSE, |
| 129 | "mistral3": ForwardPassType.DENSE, |
| 130 | "mistral4": ForwardPassType.DENSE, |
| 131 | "qwen2": ForwardPassType.QWEN2, |
| 132 | "qwen2vl": ForwardPassType.DENSE, |
| 133 | "qwen3": ForwardPassType.QWEN3, |
| 134 | "qwen35": ForwardPassType.QWEN3, |
| 135 | "starcoder2": ForwardPassType.STARCODER, |
| 136 | "starcoder": ForwardPassType.STARCODER, |
| 137 | "command-r": ForwardPassType.COMMAND_R, |
| 138 | "cohere2": ForwardPassType.COMMAND_R, |
| 139 | "deepseek": ForwardPassType.DEEPSEEK, |
| 140 | "internlm2": ForwardPassType.DENSE, |
| 141 | "phi3": ForwardPassType.DENSE, |
| 142 | "gpt2": ForwardPassType.DENSE, |
| 143 | "gptneox": ForwardPassType.DENSE, |
| 144 | "falcon": ForwardPassType.DENSE, |
| 145 | "stablelm": ForwardPassType.DENSE, |
| 146 | "xverse": ForwardPassType.DENSE, |
| 147 | "olmo": ForwardPassType.DENSE, |
| 148 | "olmo2": ForwardPassType.DENSE, |
| 149 | "baichuan": ForwardPassType.DENSE, |
| 150 | "llama-embed": ForwardPassType.DENSE, |
| 151 | |
| 152 | # ── MoE ── |
| 153 | "qwen2moe": ForwardPassType.MOE, |
| 154 | "qwen3moe": ForwardPassType.MOE, |
| 155 | "qwen35moe": ForwardPassType.MOE, |
| 156 | "gpt-oss": ForwardPassType.MOE, |
| 157 | "mixtral": ForwardPassType.MOE, |
| 158 | "deepseek2": ForwardPassType.MOE, |
| 159 | "deepseek3": ForwardPassType.MOE, |
| 160 | "deepseek_v4": ForwardPassType.DEEPSEEK_V4, |
| 161 | "dbrx": ForwardPassType.MOE, |
| 162 | "qwen3next": ForwardPassType.MOE, |
| 163 | "olmoe": ForwardPassType.MOE, |
| 164 | "arctic": ForwardPassType.MOE, |
| 165 | "phimoe": ForwardPassType.MOE, |
| 166 | "grokt": ForwardPassType.MOE, |
| 167 | "granitemoe": ForwardPassType.MOE, |
| 168 | "bailingmoe": ForwardPassType.MOE, |
| 169 | "afmoe": ForwardPassType.MOE, |
| 170 | "llada-moe": ForwardPassType.MOE, |
| 171 | "seed_oss": ForwardPassType.MOE, |
| 172 | "grovemoe": ForwardPassType.MOE, |
| 173 | "hunyuan-moe": ForwardPassType.MOE, |
| 174 | "ernie4_5-moe": ForwardPassType.MOE, |
| 175 | "smallthinker": ForwardPassType.MOE, |
| 176 | |
| 177 | # ── Gemma family ── |
| 178 | "gemma": ForwardPassType.GEMMA, |
| 179 | "gemma2": ForwardPassType.GEMMA, |
| 180 | "gemma3": ForwardPassType.GEMMA3, |
| 181 | "gemma3n": ForwardPassType.GEMMA3, |
| 182 | "gemma4": ForwardPassType.GEMMA3, |
| 183 | } |
| 184 | |
| 185 | # Maps HuggingFace model_type strings (from config.json) to ForwardPassType |
| 186 | HF_MODEL_TYPE_MAP: Dict[str, ForwardPassType] = { |
| 187 | # ── Dense ── |
| 188 | "llama": ForwardPassType.DENSE, |
| 189 | "mistral": ForwardPassType.DENSE, |
| 190 | "qwen2": ForwardPassType.QWEN2, |
| 191 | "qwen2_vl": ForwardPassType.DENSE, |
| 192 | "qwen2_5_vl": ForwardPassType.DENSE, |
| 193 | "qwen2_moe": ForwardPassType.MOE, |
| 194 | "qwen3": ForwardPassType.QWEN3, |
| 195 | "starcoder2": ForwardPassType.STARCODER, |
| 196 | "cohere": ForwardPassType.COMMAND_R, |
| 197 | "cohere2": ForwardPassType.COMMAND_R, |
| 198 | "deepseek_v2": ForwardPassType.MOE, |
| 199 | "deepseek": ForwardPassType.DEEPSEEK, |
| 200 | "internlm2": ForwardPassType.DENSE, |
| 201 | "phi3": ForwardPassType.DENSE, |
| 202 | "stablelm": ForwardPassType.DENSE, |
| 203 | "falcon": ForwardPassType.DENSE, |
| 204 | "baichuan": ForwardPassType.DENSE, |
| 205 | "olmo": ForwardPassType.DENSE, |
| 206 | "olmo2": ForwardPassType.DENSE, |
| 207 | "xverse": ForwardPassType.DENSE, |
| 208 | "gpt2": ForwardPassType.DENSE, |
| 209 | "gpt_neox": ForwardPassType.DENSE, |
| 210 | "bloom": ForwardPassType.DENSE, |
| 211 | "refact": ForwardPassType.DENSE, |
| 212 | "codegen": ForwardPassType.DENSE, |
| 213 | "gemma": ForwardPassType.GEMMA, |
| 214 | "gemma2": ForwardPassType.GEMMA, |
| 215 | "gemma3": ForwardPassType.GEMMA3, |
| 216 | "gemma4": ForwardPassType.GEMMA3, |
| 217 | "command-r": ForwardPassType.COMMAND_R, |
| 218 | "phi": ForwardPassType.DENSE, |
| 219 | "phi2": ForwardPassType.DENSE, |
| 220 | "phi-2": ForwardPassType.DENSE, |
| 221 | "phi-3": ForwardPassType.DENSE, |
| 222 | "minicpm": ForwardPassType.DENSE, |
| 223 | "minicpm3": ForwardPassType.DENSE, |
| 224 | "minicpm": ForwardPassType.DENSE, |
| 225 | |
| 226 | # ── MoE ── |
| 227 | "qwen3_moe": ForwardPassType.MOE, |
| 228 | "mixtral": ForwardPassType.MOE, |
| 229 | "deepseek": ForwardPassType.DEEPSEEK, # V1 dense |
| 230 | "deepseek_v2": ForwardPassType.MOE, |
| 231 | "jetmoe": ForwardPassType.MOE, |
| 232 | "dbry": ForwardPassType.MOE, |
| 233 | "olmoe": ForwardPassType.MOE, |
| 234 | "grok": ForwardPassType.MOE, |
| 235 | "phimoe": ForwardPassType.MOE, |
| 236 | "granite_moe": ForwardPassType.MOE, |
| 237 | "gpt_oss": ForwardPassType.MOE, |
| 238 | "qwen2_moe": ForwardPassType.MOE, |
| 239 | |
| 240 | # ── Other ── |
| 241 | "bert": ForwardPassType.BERT, |
| 242 | "bert-large": ForwardPassType.BERT, |
| 243 | "roberta": ForwardPassType.BERT, |
| 244 | "albert": ForwardPassType.BERT, |
| 245 | } |
| 246 | |
| 247 | |
| 248 | # ────────────────────────────────────────────── |
| 249 | # Core detection functions |
| 250 | # ────────────────────────────────────────────── |
| 251 | |
| 252 | |
| 253 | def _get_gguf_field_str(reader, field_name: str) -> Optional[str]: |
| 254 | """Extract a string value from a GGUF metadata field.""" |
| 255 | if not _HAS_GGUF: |
| 256 | return None |
| 257 | try: |
| 258 | field = reader.get_field(field_name) |
| 259 | if field is None: |
| 260 | return None |
| 261 | # GGUFReader fields have .parts — the last element is the value |
| 262 | part = field.parts[-1] |
| 263 | if isinstance(part, bytes): |
| 264 | return part.decode("utf-8", errors="replace").strip("\x00") |
| 265 | if hasattr(part, "tobytes"): |
| 266 | return part.tobytes().decode("utf-8", errors="replace").strip("\x00") |
| 267 | return str(part).strip() |
| 268 | except Exception: |
| 269 | return None |
| 270 | |
| 271 | |
| 272 | def _get_gguf_arch(reader) -> Optional[str]: |
| 273 | """Extract architecture string from a GGUF reader.""" |
| 274 | return _get_gguf_field_str(reader, "general.architecture") |
| 275 | |
| 276 | |
| 277 | def _get_hf_config_type(config: Dict[str, Any]) -> Optional[str]: |
| 278 | """Extract model_type from an HF config.json dict.""" |
| 279 | return config.get("model_type", None) |
| 280 | |
| 281 | |
| 282 | def detect_architecture( |
| 283 | source: Union["gguf.GGUFReader", Dict[str, Any], str], |
| 284 | ) -> ForwardPassType: |
| 285 | """Detect architecture from a GGUF reader, HF config dict, or arch string. |
| 286 | |
| 287 | Args: |
| 288 | source: One of: |
| 289 | - A ``gguf.GGUFReader`` instance (reads general.architecture field) |
| 290 | - A ``dict`` loaded from an HF ``config.json`` (reads model_type key) |
| 291 | - A raw architecture string (e.g. ``"qwen3moe"``, ``"llama"``) |
| 292 | |
| 293 | Returns: |
| 294 | The detected ``ForwardPassType`` (falls back to UNKNOWN). |
| 295 | |
| 296 | Examples: |
| 297 | # From GGUF file |
| 298 | reader = gguf.GGUFReader("model.gguf") |
| 299 | arch = detect_architecture(reader) |
| 300 | |
| 301 | # From HF config |
| 302 | with open("config.json") as f: |
| 303 | cfg = json.load(f) |
| 304 | arch = detect_architecture(cfg) |
| 305 | |
| 306 | # From string |
| 307 | arch = detect_architecture("qwen3moe") |
| 308 | """ |
| 309 | # ForwardPassType passthrough (must check before str, since ForwardPassType inherits str) |
| 310 | if isinstance(source, ForwardPassType): |
| 311 | return source |
| 312 | |
| 313 | arch_str: Optional[str] = None |
| 314 | |
| 315 | if isinstance(source, str): |
| 316 | # Raw architecture string provided directly |
| 317 | arch_str = source |
| 318 | |
| 319 | elif isinstance(source, dict): |
| 320 | # HF config.json dict |
| 321 | arch_str = _get_hf_config_type(source) |
| 322 | |
| 323 | elif _HAS_GGUF and isinstance(source, gguf.GGUFReader): |
| 324 | # GGUF reader — try the metadata field |
| 325 | arch_str = _get_gguf_arch(source) |
| 326 | |
| 327 | # If we still didn't get an arch string, scan tensor names for MoE patterns |
| 328 | if arch_str is None or arch_str == "unknown": |
| 329 | try: |
| 330 | # Look at the gguf package's built-in MODEL_ARCH detection |
| 331 | # (the reader might have it cached) |
| 332 | if hasattr(source, "arch") and source.arch: |
| 333 | arch_str = source.arch |
| 334 | except Exception: |
| 335 | pass |
| 336 | |
| 337 | else: |
| 338 | logger.warning( |
| 339 | "detect_architecture: unsupported source type %s", |
| 340 | type(source).__name__, |
| 341 | ) |
| 342 | return ForwardPassType.UNKNOWN |
| 343 | |
| 344 | if not arch_str: |
| 345 | return ForwardPassType.UNKNOWN |
| 346 | |
| 347 | # Normalise: strip, lowercase |
| 348 | arch_str = arch_str.strip().lower().replace("-", "_").replace(" ", "_") |
| 349 | |
| 350 | # Direct lookup in GGUF map (covers the known list) |
| 351 | result = GGUF_ARCH_MAP.get(arch_str) |
| 352 | if result is not None: |
| 353 | return result |
| 354 | |
| 355 | # Also try without underscores (for normalized strings like "gpt_oss" → check "gpt-oss") |
| 356 | result = GGUF_ARCH_MAP.get(arch_str.replace("_", "-")) |
| 357 | if result is not None: |
| 358 | return result |
| 359 | |
| 360 | # Try HF model type map before prefix matching (HF model_types can use |
| 361 | # underscore separators like "qwen3_moe" that should not be swallowed by |
| 362 | # a short prefix like "qwen3") |
| 363 | result = HF_MODEL_TYPE_MAP.get(arch_str) |
| 364 | if result is not None: |
| 365 | return result |
| 366 | |
| 367 | # Try fuzzy prefix matching for versioned archs (e.g. "deepseek3" -> MOE) |
| 368 | # Sort by length descending so more specific prefixes match first |
| 369 | for pattern, fptype in sorted( |
| 370 | _PREFIX_MAP.items(), key=lambda x: len(x[0]), reverse=True |
| 371 | ): |
| 372 | if arch_str.startswith(pattern): |
| 373 | return fptype |
| 374 | |
| 375 | # Last resort: use gguf's MODEL_ARCH enum to classify by analysing |
| 376 | # required tensors — if the arch has expert weight tensors it's MoE |
| 377 | if _HAS_GGUF: |
| 378 | try: |
| 379 | arch_enum_val = None |
| 380 | for name, val in MODEL_ARCH.__members__.items(): |
| 381 | if name.lower().replace("_", "") == arch_str.replace("_", ""): |
| 382 | arch_enum_val = val |
| 383 | break |
| 384 | # Also try with common naming conventions |
| 385 | name_norm = MODEL_ARCH_NAMES.get(val, "") |
| 386 | if name_norm and name_norm.replace("-", "_").replace(".", "_") == arch_str: |
| 387 | arch_enum_val = val |
| 388 | break |
| 389 | if arch_enum_val is not None: |
| 390 | tensors = MODEL_TENSORS.get(arch_enum_val, set()) |
| 391 | required_tensor_names = {t.name for t in tensors} |
| 392 | moe_tensors = {"FFN_GATE_EXP", "FFN_UP_EXP", "FFN_DOWN_EXP"} |
| 393 | if moe_tensors.intersection(required_tensor_names): |
| 394 | return ForwardPassType.MOE |
| 395 | return ForwardPassType.DENSE |
| 396 | except Exception: |
| 397 | pass |
| 398 | |
| 399 | return ForwardPassType.UNKNOWN |
| 400 | |
| 401 | |
| 402 | # Prefix-based fallback map for architectures that may have version suffixes |
| 403 | _PREFIX_MAP: Dict[str, ForwardPassType] = { |
| 404 | "llama": ForwardPassType.DENSE, |
| 405 | "mistral": ForwardPassType.DENSE, |
| 406 | "qwen2moe": ForwardPassType.MOE, |
| 407 | "qwen3moe": ForwardPassType.MOE, |
| 408 | "qwen35moe": ForwardPassType.MOE, |
| 409 | "qwen2": ForwardPassType.QWEN2, |
| 410 | "qwen2vl": ForwardPassType.DENSE, |
| 411 | "qwen3": ForwardPassType.QWEN3, |
| 412 | "qwen": ForwardPassType.QWEN2, |
| 413 | "deepseek": ForwardPassType.MOE, |
| 414 | "mixtral": ForwardPassType.MOE, |
| 415 | "gemma": ForwardPassType.GEMMA, |
| 416 | "starcoder": ForwardPassType.STARCODER, |
| 417 | "command": ForwardPassType.COMMAND_R, |
| 418 | "cohere": ForwardPassType.COMMAND_R, |
| 419 | "gpt": ForwardPassType.DENSE, |
| 420 | "phi": ForwardPassType.DENSE, |
| 421 | "falcon": ForwardPassType.DENSE, |
| 422 | "bloom": ForwardPassType.DENSE, |
| 423 | "bert": ForwardPassType.BERT, |
| 424 | } |
| 425 | |
| 426 | |
| 427 | # ────────────────────────────────────────────── |
| 428 | # Tensor-name-based MoE detection (runtime) |
| 429 | # ────────────────────────────────────────────── |
| 430 | |
| 431 | |
| 432 | def _has_moe_tensors(source) -> bool: |
| 433 | """Check if a GGUF reader has expert weight tensors (MoE indicator). |
| 434 | |
| 435 | Looks for the presence of ``ffn_gate_exps.weight``, |
| 436 | ``ffn_up_exps.weight``, or ``ffn_down_exps.weight`` in any layer. |
| 437 | """ |
| 438 | if not _HAS_GGUF: |
| 439 | return False |
| 440 | if not isinstance(source, gguf.GGUFReader): |
| 441 | return False |
| 442 | try: |
| 443 | tensors = source.tensors |
| 444 | for t in tensors: |
| 445 | name = t.name |
| 446 | if any( |
| 447 | pat in name |
| 448 | for pat in (".ffn_gate_exps.", ".ffn_up_exps.", ".ffn_down_exps.") |
| 449 | ): |
| 450 | return True |
| 451 | except Exception: |
| 452 | pass |
| 453 | return False |
| 454 | |
| 455 | |
| 456 | # ────────────────────────────────────────────── |
| 457 | # Forward pass type resolution |
| 458 | # ────────────────────────────────────────────── |
| 459 | |
| 460 | |
| 461 | def get_forward_pass_type( |
| 462 | arch_or_config: Union[ForwardPassType, "gguf.GGUFReader", Dict[str, Any], str], |
| 463 | ) -> ForwardPassType: |
| 464 | """Resolve the forward pass type from any supported input. |
| 465 | |
| 466 | This is a convenience wrapper around ``detect_architecture`` that also |
| 467 | accepts an already-resolved ``ForwardPassType`` (passes it through). |
| 468 | |
| 469 | Args: |
| 470 | arch_or_config: One of: |
| 471 | - ``ForwardPassType`` (returned as-is) |
| 472 | - ``gguf.GGUFReader`` |
| 473 | - ``dict`` (HF config.json) |
| 474 | - ``str`` (architecture name) |
| 475 | |
| 476 | Returns: |
| 477 | The matching ``ForwardPassType``. |
| 478 | """ |
| 479 | if isinstance(arch_or_config, ForwardPassType): |
| 480 | return arch_or_config |
| 481 | return detect_architecture(arch_or_config) |
| 482 | |
| 483 | |
| 484 | # ────────────────────────────────────────────── |
| 485 | # Model parameter extraction |
| 486 | # ────────────────────────────────────────────── |
| 487 | |
| 488 | |
| 489 | def _get_gguf_scalar(reader, key: str, default=0) -> Any: |
| 490 | """Read a scalar (int/float) from a GGUF metadata field.""" |
| 491 | try: |
| 492 | field = reader.get_field(key) |
| 493 | if field is None: |
| 494 | return default |
| 495 | part = field.parts[-1] |
| 496 | if hasattr(part, "item"): |
| 497 | return part.item() |
| 498 | if isinstance(part, (int, float)): |
| 499 | return part |
| 500 | if isinstance(part, bytes): |
| 501 | try: |
| 502 | return int(part) |
| 503 | except ValueError: |
| 504 | return float(part) |
| 505 | return int(part) |
| 506 | except Exception: |
| 507 | return default |
| 508 | |
| 509 | |
| 510 | def _get_gguf_scalar_with_prefixes( |
| 511 | reader, key_suffix: str, prefixes: list, default=0 |
| 512 | ) -> Any: |
| 513 | """Try reading *prefix* + *key_suffix* across a list of prefixes.""" |
| 514 | for prefix in prefixes: |
| 515 | val = _get_gguf_scalar(reader, f"{prefix}{key_suffix}") |
| 516 | if val: |
| 517 | return val |
| 518 | return default |
| 519 | |
| 520 | |
| 521 | def get_model_params( |
| 522 | gguf_reader_or_config: Union["gguf.GGUFReader", Dict[str, Any]], |
| 523 | ) -> Dict[str, Any]: |
| 524 | """Extract common model hyperparameters from GGUF metadata or HF config. |
| 525 | |
| 526 | Returns a dict with keys: |
| 527 | ``arch``, ``n_layers``, ``n_embd``, ``n_head``, ``n_kv_head``, |
| 528 | ``n_ff``, ``max_seq_len``, ``norm_eps``, ``rope_theta``, |
| 529 | ``vocab_size``, ``forward_pass_type`` |
| 530 | |
| 531 | Args: |
| 532 | gguf_reader_or_config: Either a ``gguf.GGUFReader`` or a ``dict`` |
| 533 | (as loaded from ``config.json``). |
| 534 | |
| 535 | Returns: |
| 536 | A dict of model parameters, or an empty dict on failure. |
| 537 | """ |
| 538 | params: Dict[str, Any] = {} |
| 539 | |
| 540 | try: |
| 541 | if _HAS_GGUF and isinstance(gguf_reader_or_config, gguf.GGUFReader): |
| 542 | reader = gguf_reader_or_config |
| 543 | arch_str = _get_gguf_arch(reader) or "unknown" |
| 544 | params["arch"] = arch_str |
| 545 | params["forward_pass_type"] = detect_architecture(reader) |
| 546 | |
| 547 | # Resolve prefixes to try for GGUF key lookup |
| 548 | # (Architecture-specific key prefixes like "qwen2.block_count") |
| 549 | prefixes = _get_prefixes_for_arch(arch_str) |
| 550 | |
| 551 | params["n_layers"] = int( |
| 552 | _get_gguf_scalar_with_prefixes(reader, "block_count", prefixes, 0) |
| 553 | ) |
| 554 | params["n_embd"] = int( |
| 555 | _get_gguf_scalar_with_prefixes(reader, "embedding_length", prefixes, 0) |
| 556 | ) |
| 557 | params["n_head"] = int( |
| 558 | _get_gguf_scalar_with_prefixes( |
| 559 | reader, "attention.head_count", prefixes, 0 |
| 560 | ) |
| 561 | ) |
| 562 | params["n_kv_head"] = int( |
| 563 | _get_gguf_scalar_with_prefixes( |
| 564 | reader, "attention.head_count_kv", prefixes, 0 |
| 565 | ) |
| 566 | ) |
| 567 | params["n_ff"] = int( |
| 568 | _get_gguf_scalar_with_prefixes( |
| 569 | reader, "feed_forward_length", prefixes, 0 |
| 570 | ) |
| 571 | ) |
| 572 | params["max_seq_len"] = int( |
| 573 | _get_gguf_scalar_with_prefixes(reader, "context_length", prefixes, 32768) |
| 574 | ) |
| 575 | # Also try max_position_embeddings as fallback |
| 576 | if params["max_seq_len"] <= 0: |
| 577 | params["max_seq_len"] = int( |
| 578 | _get_gguf_scalar_with_prefixes( |
| 579 | reader, "max_position_embeddings", prefixes, 32768 |
| 580 | ) |
| 581 | ) |
| 582 | |
| 583 | params["norm_eps"] = float( |
| 584 | _get_gguf_scalar_with_prefixes( |
| 585 | reader, |
| 586 | "attention.layer_norm_rms_epsilon", |
| 587 | prefixes, |
| 588 | 1e-6, |
| 589 | ) |
| 590 | ) |
| 591 | # Also fallback to attn_layer_norm_rms_epsilon (older GGUF convention) |
| 592 | if params["norm_eps"] <= 0: |
| 593 | params["norm_eps"] = float( |
| 594 | _get_gguf_scalar_with_prefixes( |
| 595 | reader, "attn_layer_norm_rms_epsilon", prefixes, 1e-6 |
| 596 | ) |
| 597 | ) |
| 598 | |
| 599 | base = _get_gguf_scalar_with_prefixes( |
| 600 | reader, "rope.freq_base", prefixes, None |
| 601 | ) |
| 602 | params["rope_theta"] = float(base) if base is not None else 1000000.0 |
| 603 | |
| 604 | # Vocab size from tokenizer metadata |
| 605 | try: |
| 606 | token_field = reader.get_field("tokenizer.ggml.tokens") |
| 607 | if token_field is not None: |
| 608 | parts = list(token_field.parts) |
| 609 | n_tokens = int(parts[4].item()) if len(parts) > 4 else 0 |
| 610 | params["vocab_size"] = n_tokens |
| 611 | else: |
| 612 | params["vocab_size"] = int( |
| 613 | _get_gguf_scalar_with_prefixes( |
| 614 | reader, "vocab_size", prefixes, 0 |
| 615 | ) |
| 616 | ) |
| 617 | except Exception: |
| 618 | params["vocab_size"] = 0 |
| 619 | |
| 620 | # MoE-specific parameters |
| 621 | fwd = params["forward_pass_type"] |
| 622 | if fwd == ForwardPassType.MOE or fwd.is_moe: |
| 623 | params["n_experts"] = int( |
| 624 | _get_gguf_scalar_with_prefixes( |
| 625 | reader, "attention.expert_count", prefixes, 0 |
| 626 | ) |
| 627 | ) |
| 628 | if params["n_experts"] <= 0: |
| 629 | params["n_experts"] = int( |
| 630 | _get_gguf_scalar_with_prefixes( |
| 631 | reader, "expert_count", prefixes, 0 |
| 632 | ) |
| 633 | ) |
| 634 | params["n_experts_per_tok"] = int( |
| 635 | _get_gguf_scalar_with_prefixes( |
| 636 | reader, "attention.expert_used_count", prefixes, 1 |
| 637 | ) |
| 638 | ) |
| 639 | if params["n_experts_per_tok"] <= 0: |
| 640 | params["n_experts_per_tok"] = int( |
| 641 | _get_gguf_scalar_with_prefixes( |
| 642 | reader, "expert_used_count", prefixes, 1 |
| 643 | ) |
| 644 | ) |
| 645 | else: |
| 646 | params["n_experts"] = 0 |
| 647 | params["n_experts_per_tok"] = 0 |
| 648 | |
| 649 | # Rope type |
| 650 | params["rope_type"] = str( |
| 651 | _get_gguf_scalar_with_prefixes(reader, "rope.type", prefixes, "default") |
| 652 | ) |
| 653 | |
| 654 | # Parallel residual (for Falcon-style) |
| 655 | params["parallel_residual"] = bool( |
| 656 | _get_gguf_scalar_with_prefixes( |
| 657 | reader, "use_parallel_residual", prefixes, 0 |
| 658 | ) |
| 659 | ) |
| 660 | |
| 661 | elif isinstance(gguf_reader_or_config, dict): |
| 662 | cfg = gguf_reader_or_config |
| 663 | model_type = cfg.get("model_type", "unknown") |
| 664 | params["arch"] = model_type |
| 665 | params["forward_pass_type"] = detect_architecture(cfg) |
| 666 | params["n_layers"] = int(cfg.get("num_hidden_layers", 0)) |
| 667 | params["n_embd"] = int(cfg.get("hidden_size", 0)) |
| 668 | params["n_head"] = int( |
| 669 | cfg.get("num_attention_heads", 0) |
| 670 | ) |
| 671 | params["n_kv_head"] = int( |
| 672 | cfg.get("num_key_value_heads", cfg.get("num_attention_heads", 0)) |
| 673 | ) |
| 674 | params["n_ff"] = int( |
| 675 | cfg.get("intermediate_size", 0) |
| 676 | ) |
| 677 | params["max_seq_len"] = int( |
| 678 | cfg.get("max_position_embeddings", cfg.get("max_seq_len", 32768)) |
| 679 | ) |
| 680 | params["norm_eps"] = float( |
| 681 | cfg.get("rms_norm_eps", cfg.get("layer_norm_epsilon", 1e-6)) |
| 682 | ) |
| 683 | params["rope_theta"] = float( |
| 684 | cfg.get("rope_theta", cfg.get("rope_theta", 1000000.0)) |
| 685 | ) |
| 686 | params["vocab_size"] = int( |
| 687 | cfg.get("vocab_size", 0) |
| 688 | ) |
| 689 | params["rope_type"] = str(cfg.get("rope_type", "default")) |
| 690 | params["parallel_residual"] = bool( |
| 691 | cfg.get("parallel_residual", cfg.get("use_parallel_residual", False)) |
| 692 | ) |
| 693 | |
| 694 | # MoE-specific |
| 695 | fwd = params["forward_pass_type"] |
| 696 | if fwd == ForwardPassType.MOE or fwd.is_moe: |
| 697 | num_experts = cfg.get("num_experts", 0) or cfg.get("num_local_experts", 0) |
| 698 | params["n_experts"] = int(num_experts) |
| 699 | params["n_experts_per_tok"] = int( |
| 700 | cfg.get("num_experts_per_tok", cfg.get("top_k", 1)) |
| 701 | ) |
| 702 | else: |
| 703 | params["n_experts"] = 0 |
| 704 | params["n_experts_per_tok"] = 0 |
| 705 | else: |
| 706 | logger.error( |
| 707 | "get_model_params: unsupported type %s", |
| 708 | type(gguf_reader_or_config).__name__, |
| 709 | ) |
| 710 | return {} |
| 711 | |
| 712 | # Compute head_dim |
| 713 | n_embd = params.get("n_embd", 0) |
| 714 | n_head = params.get("n_head", 1) |
| 715 | params["head_dim"] = n_embd // n_head if n_head > 0 else 0 |
| 716 | |
| 717 | except Exception as exc: |
| 718 | logger.error("get_model_params failed: %s", exc) |
| 719 | return {} |
| 720 | |
| 721 | return params |
| 722 | |
| 723 | |
| 724 | def _get_prefixes_for_arch(arch_str: str) -> list: |
| 725 | """Return a list of GGUF key prefixes to try for the given architecture. |
| 726 | |
| 727 | Different archs store metadata under different prefixes in GGUF files: |
| 728 | e.g. ``qwen2.block_count``, ``gemma.block_count``. |
| 729 | """ |
| 730 | base = arch_str.lower().replace("-", "_") |
| 731 | |
| 732 | # Architecture-to-prefix mappings |
| 733 | prefix_map = { |
| 734 | "llama": ["llama.", "llama2.", "llama3.", "codellama."], |
| 735 | "mistral": ["mistral.", "llama."], |
| 736 | "qwen2": ["qwen2.", "qwen2moe.", "llama."], |
| 737 | "qwen2vl": ["qwen2vl.", "qwen2.", "llama."], |
| 738 | "qwen3": ["qwen3.", "qwen3moe.", "llama."], |
| 739 | "qwen2moe": ["qwen2moe.", "qwen2.", "llama."], |
| 740 | "qwen3moe": ["qwen3moe.", "qwen3.", "llama."], |
| 741 | "qwen": ["qwen2.", "qwen2moe.", "llama."], |
| 742 | "gemma": ["gemma.", "gemma2.", "llama."], |
| 743 | "gemma2": ["gemma2.", "gemma.", "llama."], |
| 744 | "gemma3": ["gemma3.", "gemma2.", "gemma.", "llama."], |
| 745 | "deepseek": ["deepseek.", "deepseek2.", "llama."], |
| 746 | "deepseek2": ["deepseek2.", "deepseek.", "llama."], |
| 747 | "mixtral": ["mixtral.", "llama."], |
| 748 | "command": ["command-r.", "commandr.", "llama."], |
| 749 | "starcoder": ["starcoder.", "llama."], |
| 750 | "falcon": ["falcon.", "llama."], |
| 751 | "phi": ["phi3.", "phi2.", "llama."], |
| 752 | "gpt_oss": ["gpt-oss.", "llama."], |
| 753 | } |
| 754 | |
| 755 | # Try exact match |
| 756 | if base in prefix_map: |
| 757 | prefixes = list(prefix_map[base]) |
| 758 | else: |
| 759 | # Try partial match |
| 760 | prefixes = [] |
| 761 | for key, pfx_list in prefix_map.items(): |
| 762 | if base.startswith(key) or key.startswith(base): |
| 763 | prefixes.extend(pfx_list) |
| 764 | if not prefixes: |
| 765 | prefixes = [f"{base}.", "llama."] |
| 766 | |
| 767 | # Always add the base arch as first try |
| 768 | if prefixes and prefixes[0] != f"{base}.": |
| 769 | prefixes.insert(0, f"{base}.") |
| 770 | elif not prefixes: |
| 771 | prefixes = [f"{base}.", "llama."] |
| 772 | |
| 773 | return prefixes |
| 774 | |
| 775 | |
| 776 | # ────────────────────────────────────────────── |
| 777 | # CLI helper |
| 778 | # ────────────────────────────────────────────── |
| 779 | |
| 780 | |
| 781 | def print_supported_models() -> None: |
| 782 | """Print a formatted table of supported architectures to stdout. |
| 783 | |
| 784 | This is designed for CLI usage:: |
| 785 | |
| 786 | python -c "from mojollama.model.architectures import print_supported_models; print_supported_models()" |
| 787 | """ |
| 788 | max_name_width = 20 |
| 789 | |
| 790 | header = f"{'Architecture Key':<{max_name_width}} {'Forward Pass Type':<18} {'Notes'}" |
| 791 | sep = "-" * len(header) |
| 792 | |
| 793 | # Group and sort |
| 794 | dense_archs: list[tuple[str, str]] = [] |
| 795 | moe_archs: list[tuple[str, str]] = [] |
| 796 | gemma_archs: list[tuple[str, str]] = [] |
| 797 | other_archs: list[tuple[str, str]] = [] |
| 798 | |
| 799 | for arch_key, fptype in sorted(GGUF_ARCH_MAP.items()): |
| 800 | note = "" |
| 801 | if fptype == ForwardPassType.DENSE: |
| 802 | if arch_key in ("llama", "mistral", "qwen2"): |
| 803 | note = "Base dense (LLaMA/Mistral/Qwen2)" |
| 804 | else: |
| 805 | note = "Dense transformer" |
| 806 | dense_archs.append((arch_key, note)) |
| 807 | elif fptype == ForwardPassType.MOE: |
| 808 | if arch_key in ("qwen3moe", "deepseek2", "mixtral", "gpt-oss"): |
| 809 | note = "MoE (router + top-k experts)" |
| 810 | else: |
| 811 | note = "Mixture of Experts" |
| 812 | moe_archs.append((arch_key, note)) |
| 813 | elif fptype in (ForwardPassType.GEMMA, ForwardPassType.GEMMA3): |
| 814 | note = "Gemma family (GeGLU)" |
| 815 | gemma_archs.append((arch_key, note)) |
| 816 | else: |
| 817 | if fptype == ForwardPassType.COMMAND_R: |
| 818 | note = "Cohere Command-R dense" |
| 819 | elif fptype == ForwardPassType.STARCODER: |
| 820 | note = "StarCoder dense" |
| 821 | elif fptype == ForwardPassType.QWEN2: |
| 822 | note = "Qwen2 dense" |
| 823 | elif fptype == ForwardPassType.QWEN3: |
| 824 | note = "Qwen3 dense" |
| 825 | elif fptype == ForwardPassType.DEEPSEEK: |
| 826 | note = "DeepSeek V1 dense" |
| 827 | else: |
| 828 | note = "Other" |
| 829 | other_archs.append((arch_key, note)) |
| 830 | |
| 831 | def _print_section(title: str, items: list) -> None: |
| 832 | if not items: |
| 833 | return |
| 834 | print(f"\n [{title}]\n") |
| 835 | for key, note in items: |
| 836 | fptype_name = GGUF_ARCH_MAP.get(key, ForwardPassType.UNKNOWN).value |
| 837 | print(f" {key:<{max_name_width}} {fptype_name:<18} {note}") |
| 838 | |
| 839 | print(f"\n{'MojoLlama — Supported Model Architectures':^{len(header)}}") |
| 840 | print(sep) |
| 841 | print(header) |
| 842 | print(sep) |
| 843 | |
| 844 | _print_section("Dense", dense_archs) |
| 845 | _print_section("MoE", moe_archs) |
| 846 | _print_section("Gemma", gemma_archs) |
| 847 | _print_section("Other", other_archs) |
| 848 | |
| 849 | print() |
| 850 | print(" ForwardPassType enum values can be used to select the correct") |
| 851 | print(" forward pass implementation in the MojoLlama engine.") |
| 852 | print() |
| 853 | |
| 854 | # Also print the ForwardPassType enum summary |
| 855 | print(f" {'ForwardPassType':<30} {'Description'}") |
| 856 | print(f" {'─'*30:<30} {'─'*40}") |
| 857 | for fptype in ForwardPassType: |
| 858 | print(f" {fptype.value:<30} {fptype.name}") |
| 859 | print() |
| 860 | |
| 861 | |
| 862 | # ────────────────────────────────────────────── |
| 863 | # Quick self-test |
| 864 | # ────────────────────────────────────────────── |
| 865 | |
| 866 | |
| 867 | def _self_test() -> None: |
| 868 | """Run a quick smoke test of architecture detection.""" |
| 869 | test_cases = [ |
| 870 | # (input, expected type, description) |
| 871 | ("llama", ForwardPassType.DENSE, "LLaMA GGUF"), |
| 872 | ("mistral", ForwardPassType.DENSE, "Mistral GGUF"), |
| 873 | ("qwen2", ForwardPassType.QWEN2, "Qwen2 GGUF"), |
| 874 | ("qwen3moe", ForwardPassType.MOE, "Qwen3 MoE GGUF"), |
| 875 | ("gpt-oss", ForwardPassType.MOE, "GPT-OSS MoE"), |
| 876 | ("mixtral", ForwardPassType.MOE, "Mixtral MoE"), |
| 877 | ("gemma", ForwardPassType.GEMMA, "Gemma"), |
| 878 | ("gemma2", ForwardPassType.GEMMA, "Gemma2"), |
| 879 | ("deepseek2", ForwardPassType.MOE, "DeepSeek V2 MoE"), |
| 880 | ("starcoder2", ForwardPassType.STARCODER, "StarCoder2"), |
| 881 | ("command-r", ForwardPassType.COMMAND_R, "Cohere Command-R"), |
| 882 | # HF config.json model_type values |
| 883 | ({"model_type": "llama"}, ForwardPassType.DENSE, "HF LLaMA config"), |
| 884 | ({"model_type": "qwen2"}, ForwardPassType.QWEN2, "HF Qwen2 config"), |
| 885 | ({"model_type": "qwen3_moe"}, ForwardPassType.MOE, "HF Qwen3 MoE config"), |
| 886 | ({"model_type": "mixtral"}, ForwardPassType.MOE, "HF Mixtral config"), |
| 887 | ({"model_type": "gemma2"}, ForwardPassType.GEMMA, "HF Gemma2 config"), |
| 888 | # ForwardPassType passthrough |
| 889 | (ForwardPassType.MOE, ForwardPassType.MOE, "Passthrough MoE"), |
| 890 | (ForwardPassType.DENSE, ForwardPassType.DENSE, "Passthrough DENSE"), |
| 891 | ] |
| 892 | |
| 893 | all_ok = True |
| 894 | for inp, expected, desc in test_cases: |
| 895 | try: |
| 896 | result = detect_architecture(inp) |
| 897 | if result == expected: |
| 898 | print(f" OK {desc:<35} -> {result.value}") |
| 899 | else: |
| 900 | print( |
| 901 | f" FAIL {desc:<35} expected={expected.value} got={result.value}" |
| 902 | ) |
| 903 | all_ok = False |
| 904 | except Exception as e: |
| 905 | print(f" ERR {desc:<35} exception={e}") |
| 906 | all_ok = False |
| 907 | |
| 908 | print() |
| 909 | if all_ok: |
| 910 | print(" All self-tests passed!") |
| 911 | else: |
| 912 | print(" Some self-tests FAILED!") |
| 913 | |
| 914 | |
| 915 | if __name__ == "__main__": |
| 916 | print_supported_models() |
| 917 | print() |
| 918 | _self_test() |