"""Build a TITAN model from an MLX checkpoint: the host architecture (attention, norms, router) is mlx-lm's own module tree; every layer's `switch_mlp` is replaced by a TitanSwitchGLU over a slot table. Expert weights are never materialised from the checkpoint by mlx-lm: they are read on demand by the ExpertStore. `capacity` = number of resident experts per layer (num_experts = everything resident). """ from __future__ import annotations import os from typing import Dict, List, Optional import mlx.core as mx import mlx.nn as nn from mlx_lm.utils import load_model, load_tokenizer from .moe import TitanSwitchGLU from .registry import ModelSpec, load_spec from .slots import EvictionPolicy, LFUPolicy, SlotTable from .store import ExpertStore POLICIES = {"lru": EvictionPolicy, "lfu": LFUPolicy} class TitanModel: def __init__(self, model_dir: str, capacity: Optional[int] = None, policy: str = "lru", nocache: bool = False, on_route=None): self.model_dir = os.path.realpath(model_dir) self.spec: ModelSpec = load_spec(self.model_dir) self.store = ExpertStore(self.spec, nocache=nocache) self.capacity = capacity or self.spec.num_experts self.policy_name = policy # Load the host model lazily so the stacked expert tensors are never evaluated. from pathlib import Path self.model, cfg = load_model(Path(self.model_dir), lazy=True) self.tokenizer = load_tokenizer(Path(self.model_dir)) q = cfg.get("quantization") or cfg.get("quantization_config") self.tables: List[SlotTable] = [] self.blocks: List[TitanSwitchGLU] = [] for l, layer in enumerate(self.model.model.layers): table = SlotTable(l, self.capacity, self.store, POLICIES[policy]()) block = TitanSwitchGLU(table, q["group_size"], q["bits"], on_route=on_route) # drop the lazy stacked weights and splice in the TITAN block mlp = layer.mlp del mlp.switch_mlp # removes the lazy stacked SwitchGLU (never evaluated) mlp.switch_mlp = block # plain attribute: not an nn.Module, not in parameters() self.tables.append(table) self.blocks.append(block) mx.eval(self.model.parameters()) # dense weights only # convenience ----------------------------------------------------------------- @property def layers(self): return self.model.layers def __call__(self, inputs, cache=None): return self.model(inputs, cache=cache) def warm_all(self): """Load every expert (only meaningful when capacity == num_experts).""" for t in self.tables: t.ensure(list(range(self.spec.num_experts))) t.reset_stats() self.store.reset_stats() def cache_stats(self) -> Dict: per = [t.stats() for t in self.tables] hits = sum(p["hits"] for p in per) misses = sum(p["misses"] for p in per) return {"layers": per, "hits": hits, "misses": misses, "hit_rate": hits / (hits + misses) if hits + misses else None, "stall_time_s": sum(p["stall_time_s"] for p in per), "store": self.store.stats()} def reset_stats(self): for t in self.tables: t.reset_stats() self.store.reset_stats()