"""Trainable router shell for the frozen Fable host and frozen donor experts. The production campaign keeps host and expert tensors immutable. This module adds an explicit host-only route, a bounded expert residual, deterministic forced routes for counterfactual discovery, and state helpers for the small router-only checkpoints. """ from __future__ import annotations import contextlib import math from dataclasses import dataclass from pathlib import Path from typing import Any, Iterator import torch import torch.nn as nn import torch.nn.functional as F from torch.utils.checkpoint import checkpoint PROJECTIONS = ("gate_proj", "up_proj", "down_proj") def inverse_softplus(value: float) -> float: if value <= 0: raise ValueError("softplus target must be positive") return math.log(math.expm1(value)) class FrozenSwiGLUExpert(nn.Module): def __init__(self, hidden_size: int = 2048, intermediate_size: int = 512): super().__init__() self.gate_proj = nn.Linear(hidden_size, intermediate_size, bias=False, device="meta") self.up_proj = nn.Linear(hidden_size, intermediate_size, bias=False, device="meta") self.down_proj = nn.Linear(intermediate_size, hidden_size, bias=False, device="meta") def materialize(self, weights: dict[str, torch.Tensor], device: torch.device, dtype: torch.dtype) -> None: for name in PROJECTIONS: tensor = weights[f"{name}.weight"].to(device=device, dtype=dtype, non_blocking=True) module = getattr(self, name) module.weight = nn.Parameter(tensor, requires_grad=False) def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: if self.gate_proj.weight.device == hidden_states.device: return self.down_proj(F.silu(self.gate_proj(hidden_states)) * self.up_proj(hidden_states)) # Free 16 GiB runtimes cannot safely keep the 6.04 GiB frozen donor # bank beside the 5.3 GiB host and long-context activations. The # expert branch is detached by FrozenExpertRouterBlock, so immutable # projections can be staged one active expert at a time without # retaining a weight-gradient graph. This preserves arithmetic: bank # tensors are cast to the same device/dtype used by resident experts. device, dtype = hidden_states.device, hidden_states.dtype gate_weight = self.gate_proj.weight.to(device=device, dtype=dtype) up_weight = self.up_proj.weight.to(device=device, dtype=dtype) activated = F.silu(F.linear(hidden_states, gate_weight)) * F.linear(hidden_states, up_weight) del gate_weight, up_weight down_weight = self.down_proj.weight.to(device=device, dtype=dtype) output = F.linear(activated, down_weight) del down_weight return output class ExplicitOffRouter(nn.Module): """Expert logits plus a fixed zero-logit host-only class. The off class is explicit in the classification/ranking objective but adds no new trainable parameter beyond the frozen contract's router gate. """ def __init__(self, hidden_size: int, num_experts: int): super().__init__() self.gate = nn.Linear(hidden_size, num_experts, bias=False) nn.init.normal_(self.gate.weight, mean=0.0, std=0.01) self.num_experts = num_experts def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: # Router and scale are the only trainable parameters. Keep their # master precision at FP32 even when the frozen host and experts run in # FP16; casting this tiny trainable gate to FP16 caused its task-loss # gradient to underflow to exactly zero on T4. expert_logits = self.gate(hidden_states.to(self.gate.weight.dtype)) off_logits = torch.zeros( (*expert_logits.shape[:-1], 1), dtype=expert_logits.dtype, device=expert_logits.device, ) return torch.cat((expert_logits, off_logits), dim=-1) @dataclass class RouteTrace: logits: torch.Tensor selected_experts: torch.Tensor selected_weights: torch.Tensor off_probability: torch.Tensor active_scale: torch.Tensor class FrozenExpertRouterBlock(nn.Module): """A sparse, bounded residual over one frozen host layer output.""" def __init__( self, expert_ids: list[int], *, hidden_size: int = 2048, intermediate_size: int = 512, top_k: int = 2, initial_scale: float = 0.005, maximum_scale: float = 0.1, ): super().__init__() if len(expert_ids) != 32 or len(set(expert_ids)) != 32: raise ValueError("a frozen bank layer must contain 32 unique experts") if not 1 <= top_k <= len(expert_ids): raise ValueError("top_k is outside the expert bank") self.expert_ids = tuple(int(item) for item in expert_ids) self.router = ExplicitOffRouter(hidden_size, len(expert_ids)) self.experts = nn.ModuleList( FrozenSwiGLUExpert(hidden_size, intermediate_size) for _ in expert_ids ) self.expert_scale = nn.Parameter(torch.tensor(inverse_softplus(initial_scale))) self.top_k = top_k self.maximum_scale = float(maximum_scale) self.enabled = True self.checkpoint_enabled = False self._forced_expert: int | None = None self._forced_scale: float | None = None self.last_trace: RouteTrace | None = None @property def off_class_index(self) -> int: return len(self.expert_ids) @contextlib.contextmanager def forced_route(self, local_expert: int | None, scale: float = 0.025) -> Iterator[None]: if local_expert is not None and not 0 <= local_expert < len(self.expert_ids): raise ValueError("forced expert index is outside the local bank") old_expert, old_scale = self._forced_expert, self._forced_scale self._forced_expert, self._forced_scale = local_expert, float(scale) try: yield finally: self._forced_expert, self._forced_scale = old_expert, old_scale def load_router_warmstart(self, weight: torch.Tensor) -> None: if tuple(weight.shape) != tuple(self.router.gate.weight.shape): raise ValueError( f"router warm-start shape {tuple(weight.shape)} does not match " f"{tuple(self.router.gate.weight.shape)}" ) with torch.no_grad(): self.router.gate.weight.copy_(weight.to(self.router.gate.weight)) def materialize_experts( self, bank_path: Path, layer: int, *, device: torch.device, dtype: torch.dtype, ) -> None: from safetensors import safe_open with safe_open(str(bank_path), framework="pt", device="cpu") as bank: for local_index, global_expert in enumerate(self.expert_ids): prefix = f"model.layers.{layer}.mlp.experts.{global_expert}" weights = { f"{projection}.weight": bank.get_tensor(f"{prefix}.{projection}.weight") for projection in PROJECTIONS } self.experts[local_index].materialize(weights, device, dtype) for parameter in self.experts.parameters(): parameter.requires_grad_(False) def _expert_output( self, flat: torch.Tensor, selected: torch.Tensor, weights: torch.Tensor, ) -> torch.Tensor: output = torch.zeros_like(flat) detached = flat.detach() for local_index, expert in enumerate(self.experts): positions = (selected == local_index).nonzero(as_tuple=False) if positions.numel() == 0: continue token_indices, rank_indices = positions.unbind(dim=1) expert_values = expert(detached.index_select(0, token_indices)).detach() weighted = expert_values * weights[token_indices, rank_indices].unsqueeze(-1) output = output.index_add(0, token_indices, weighted) return output def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: if not self.enabled: self.last_trace = None return hidden_states original_shape = hidden_states.shape flat = hidden_states.reshape(-1, original_shape[-1]) logits = self.router(flat) if self._forced_expert is not None: selected = torch.full( (flat.shape[0], 1), self._forced_expert, dtype=torch.long, device=flat.device ) weights = torch.ones((flat.shape[0], 1), dtype=flat.dtype, device=flat.device) off_probability = torch.zeros(flat.shape[0], dtype=flat.dtype, device=flat.device) scale = torch.as_tensor(self._forced_scale, dtype=flat.dtype, device=flat.device) else: probabilities = torch.softmax(logits.float(), dim=-1).to(flat.dtype) expert_probabilities = probabilities[:, :-1] weights, selected = expert_probabilities.topk(self.top_k, dim=-1) off_probability = probabilities[:, -1] scale = torch.clamp(F.softplus(self.expert_scale), max=self.maximum_scale).to(flat.dtype) expert_output = self._expert_output(flat, selected, weights) host_std = flat.float().std().detach().clamp_min(1e-6) expert_std = expert_output.float().std().detach().clamp_min(1e-6) expert_output = expert_output * torch.clamp(host_std / expert_std, max=2.0).to(flat.dtype) self.last_trace = RouteTrace(logits, selected, weights, off_probability, scale) return hidden_states + (scale * expert_output).reshape(original_shape) class AugmentedHostLayer(nn.Module): def __init__(self, host_layer: nn.Module, expert_block: FrozenExpertRouterBlock): super().__init__() self.host_layer = host_layer self.expert_block = expert_block self.is_attention_layer = getattr(host_layer, "is_attention_layer", False) def forward(self, hidden_states: torch.Tensor, *args: Any, **kwargs: Any) -> torch.Tensor: output = self.host_layer(hidden_states, *args, **kwargs) if not isinstance(output, torch.Tensor): raise TypeError(f"unsupported LFM2 layer output type: {type(output)!r}") if self.expert_block.checkpoint_enabled and self.training and torch.is_grad_enabled(): return checkpoint( self.expert_block, output, use_reentrant=False, preserve_rng_state=False, ) return self.expert_block(output) def attach_router_block(model: nn.Module, layer: int, block: FrozenExpertRouterBlock) -> AugmentedHostLayer: layers = model.model.layers if not 0 <= layer < len(layers): raise ValueError(f"layer {layer} outside host model with {len(layers)} layers") wrapper = AugmentedHostLayer(layers[layer], block) layers[layer] = wrapper return wrapper def freeze_except_routers(model: nn.Module) -> dict[str, int]: counts = {"hostAndExperts": 0, "router": 0, "expertScale": 0, "trainable": 0} for name, parameter in model.named_parameters(): if ".expert_block.router.gate.weight" in name: parameter.requires_grad_(True) counts["router"] += parameter.numel() elif name.endswith(".expert_block.expert_scale"): parameter.requires_grad_(True) counts["expertScale"] += parameter.numel() else: parameter.requires_grad_(False) counts["hostAndExperts"] += parameter.numel() if parameter.requires_grad: counts["trainable"] += parameter.numel() assert_trainable_isolation(model) return counts def assert_trainable_isolation(model: nn.Module) -> list[str]: names = [name for name, parameter in model.named_parameters() if parameter.requires_grad] invalid = [ name for name in names if ".expert_block.router.gate.weight" not in name and not name.endswith(".expert_block.expert_scale") ] if invalid: raise RuntimeError(f"trainable-parameter isolation failed: {invalid[:5]}") if not names: raise RuntimeError("trainable-parameter isolation found no router parameters") return names def router_state_dict(model: nn.Module) -> dict[str, torch.Tensor]: return { name: tensor.detach().cpu().contiguous() for name, tensor in model.state_dict().items() if ".expert_block.router.gate.weight" in name or name.endswith(".expert_block.expert_scale") } def load_router_state_dict(model: nn.Module, state: dict[str, torch.Tensor]) -> None: expected = set(router_state_dict(model)) if set(state) != expected: raise RuntimeError( f"router checkpoint identity mismatch: missing={sorted(expected-set(state))}, " f"extra={sorted(set(state)-expected)}" ) current = model.state_dict() with torch.no_grad(): for name, tensor in state.items(): current[name].copy_(tensor.to(current[name])) def benefit_targets(host_nll: torch.Tensor, candidate_nll: torch.Tensor, margin: float) -> torch.Tensor: """Return the best expert index, or the explicit off class if none earns its cost. ``candidate_nll`` is shaped ``[tokens, candidates]`` and must contain exact detached counterfactual losses generated outside the served path. """ if host_nll.ndim != 1 or candidate_nll.ndim != 2 or candidate_nll.shape[0] != host_nll.shape[0]: raise ValueError("counterfactual NLL shapes are incompatible") best_nll, best_index = candidate_nll.min(dim=-1) off_index = candidate_nll.shape[-1] off = torch.full_like(best_index, off_index) return torch.where(best_nll + margin < host_nll, best_index, off) def benefit_weighted_router_loss( logits: torch.Tensor, targets: torch.Tensor, host_nll: torch.Tensor, candidate_nll: torch.Tensor, ) -> torch.Tensor: best_nll = candidate_nll.min(dim=-1).values benefit = (host_nll - best_nll).clamp_min(0).detach() weights = torch.where(targets == logits.shape[-1] - 1, torch.ones_like(benefit), 1 + benefit) return (F.cross_entropy(logits.float(), targets, reduction="none") * weights.float()).mean()