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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Trainable router shell for the frozen Fable host and frozen donor experts.
|
| 2 |
+
|
| 3 |
+
The production campaign keeps host and expert tensors immutable. This module
|
| 4 |
+
adds an explicit host-only route, a bounded expert residual, deterministic
|
| 5 |
+
forced routes for counterfactual discovery, and state helpers for the small
|
| 6 |
+
router-only checkpoints.
|
| 7 |
+
"""
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
import contextlib
|
| 11 |
+
import math
|
| 12 |
+
from dataclasses import dataclass
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
from typing import Any, Iterator
|
| 15 |
+
|
| 16 |
+
import torch
|
| 17 |
+
import torch.nn as nn
|
| 18 |
+
import torch.nn.functional as F
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
PROJECTIONS = ("gate_proj", "up_proj", "down_proj")
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def inverse_softplus(value: float) -> float:
|
| 25 |
+
if value <= 0:
|
| 26 |
+
raise ValueError("softplus target must be positive")
|
| 27 |
+
return math.log(math.expm1(value))
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class FrozenSwiGLUExpert(nn.Module):
|
| 31 |
+
def __init__(self, hidden_size: int = 2048, intermediate_size: int = 512):
|
| 32 |
+
super().__init__()
|
| 33 |
+
self.gate_proj = nn.Linear(hidden_size, intermediate_size, bias=False, device="meta")
|
| 34 |
+
self.up_proj = nn.Linear(hidden_size, intermediate_size, bias=False, device="meta")
|
| 35 |
+
self.down_proj = nn.Linear(intermediate_size, hidden_size, bias=False, device="meta")
|
| 36 |
+
|
| 37 |
+
def materialize(self, weights: dict[str, torch.Tensor], device: torch.device, dtype: torch.dtype) -> None:
|
| 38 |
+
for name in PROJECTIONS:
|
| 39 |
+
tensor = weights[f"{name}.weight"].to(device=device, dtype=dtype, non_blocking=True)
|
| 40 |
+
module = getattr(self, name)
|
| 41 |
+
module.weight = nn.Parameter(tensor, requires_grad=False)
|
| 42 |
+
|
| 43 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 44 |
+
return self.down_proj(F.silu(self.gate_proj(hidden_states)) * self.up_proj(hidden_states))
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
class ExplicitOffRouter(nn.Module):
|
| 48 |
+
"""Expert logits plus a fixed zero-logit host-only class.
|
| 49 |
+
|
| 50 |
+
The off class is explicit in the classification/ranking objective but adds
|
| 51 |
+
no new trainable parameter beyond the frozen contract's router gate.
|
| 52 |
+
"""
|
| 53 |
+
|
| 54 |
+
def __init__(self, hidden_size: int, num_experts: int):
|
| 55 |
+
super().__init__()
|
| 56 |
+
self.gate = nn.Linear(hidden_size, num_experts, bias=False)
|
| 57 |
+
nn.init.normal_(self.gate.weight, mean=0.0, std=0.01)
|
| 58 |
+
self.num_experts = num_experts
|
| 59 |
+
|
| 60 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 61 |
+
expert_logits = self.gate(hidden_states)
|
| 62 |
+
off_logits = torch.zeros(
|
| 63 |
+
(*expert_logits.shape[:-1], 1),
|
| 64 |
+
dtype=expert_logits.dtype,
|
| 65 |
+
device=expert_logits.device,
|
| 66 |
+
)
|
| 67 |
+
return torch.cat((expert_logits, off_logits), dim=-1)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
@dataclass
|
| 71 |
+
class RouteTrace:
|
| 72 |
+
logits: torch.Tensor
|
| 73 |
+
selected_experts: torch.Tensor
|
| 74 |
+
selected_weights: torch.Tensor
|
| 75 |
+
off_probability: torch.Tensor
|
| 76 |
+
active_scale: torch.Tensor
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
class FrozenExpertRouterBlock(nn.Module):
|
| 80 |
+
"""A sparse, bounded residual over one frozen host layer output."""
|
| 81 |
+
|
| 82 |
+
def __init__(
|
| 83 |
+
self,
|
| 84 |
+
expert_ids: list[int],
|
| 85 |
+
*,
|
| 86 |
+
hidden_size: int = 2048,
|
| 87 |
+
intermediate_size: int = 512,
|
| 88 |
+
top_k: int = 2,
|
| 89 |
+
initial_scale: float = 0.005,
|
| 90 |
+
maximum_scale: float = 0.1,
|
| 91 |
+
):
|
| 92 |
+
super().__init__()
|
| 93 |
+
if len(expert_ids) != 32 or len(set(expert_ids)) != 32:
|
| 94 |
+
raise ValueError("a frozen bank layer must contain 32 unique experts")
|
| 95 |
+
if not 1 <= top_k <= len(expert_ids):
|
| 96 |
+
raise ValueError("top_k is outside the expert bank")
|
| 97 |
+
self.expert_ids = tuple(int(item) for item in expert_ids)
|
| 98 |
+
self.router = ExplicitOffRouter(hidden_size, len(expert_ids))
|
| 99 |
+
self.experts = nn.ModuleList(
|
| 100 |
+
FrozenSwiGLUExpert(hidden_size, intermediate_size) for _ in expert_ids
|
| 101 |
+
)
|
| 102 |
+
self.expert_scale = nn.Parameter(torch.tensor(inverse_softplus(initial_scale)))
|
| 103 |
+
self.top_k = top_k
|
| 104 |
+
self.maximum_scale = float(maximum_scale)
|
| 105 |
+
self.enabled = True
|
| 106 |
+
self._forced_expert: int | None = None
|
| 107 |
+
self._forced_scale: float | None = None
|
| 108 |
+
self.last_trace: RouteTrace | None = None
|
| 109 |
+
|
| 110 |
+
@property
|
| 111 |
+
def off_class_index(self) -> int:
|
| 112 |
+
return len(self.expert_ids)
|
| 113 |
+
|
| 114 |
+
@contextlib.contextmanager
|
| 115 |
+
def forced_route(self, local_expert: int | None, scale: float = 0.025) -> Iterator[None]:
|
| 116 |
+
if local_expert is not None and not 0 <= local_expert < len(self.expert_ids):
|
| 117 |
+
raise ValueError("forced expert index is outside the local bank")
|
| 118 |
+
old_expert, old_scale = self._forced_expert, self._forced_scale
|
| 119 |
+
self._forced_expert, self._forced_scale = local_expert, float(scale)
|
| 120 |
+
try:
|
| 121 |
+
yield
|
| 122 |
+
finally:
|
| 123 |
+
self._forced_expert, self._forced_scale = old_expert, old_scale
|
| 124 |
+
|
| 125 |
+
def load_router_warmstart(self, weight: torch.Tensor) -> None:
|
| 126 |
+
if tuple(weight.shape) != tuple(self.router.gate.weight.shape):
|
| 127 |
+
raise ValueError(
|
| 128 |
+
f"router warm-start shape {tuple(weight.shape)} does not match "
|
| 129 |
+
f"{tuple(self.router.gate.weight.shape)}"
|
| 130 |
+
)
|
| 131 |
+
with torch.no_grad():
|
| 132 |
+
self.router.gate.weight.copy_(weight.to(self.router.gate.weight))
|
| 133 |
+
|
| 134 |
+
def materialize_experts(
|
| 135 |
+
self,
|
| 136 |
+
bank_path: Path,
|
| 137 |
+
layer: int,
|
| 138 |
+
*,
|
| 139 |
+
device: torch.device,
|
| 140 |
+
dtype: torch.dtype,
|
| 141 |
+
) -> None:
|
| 142 |
+
from safetensors import safe_open
|
| 143 |
+
|
| 144 |
+
with safe_open(str(bank_path), framework="pt", device="cpu") as bank:
|
| 145 |
+
for local_index, global_expert in enumerate(self.expert_ids):
|
| 146 |
+
prefix = f"model.layers.{layer}.mlp.experts.{global_expert}"
|
| 147 |
+
weights = {
|
| 148 |
+
f"{projection}.weight": bank.get_tensor(f"{prefix}.{projection}.weight")
|
| 149 |
+
for projection in PROJECTIONS
|
| 150 |
+
}
|
| 151 |
+
self.experts[local_index].materialize(weights, device, dtype)
|
| 152 |
+
for parameter in self.experts.parameters():
|
| 153 |
+
parameter.requires_grad_(False)
|
| 154 |
+
|
| 155 |
+
def _expert_output(
|
| 156 |
+
self,
|
| 157 |
+
flat: torch.Tensor,
|
| 158 |
+
selected: torch.Tensor,
|
| 159 |
+
weights: torch.Tensor,
|
| 160 |
+
) -> torch.Tensor:
|
| 161 |
+
output = torch.zeros_like(flat)
|
| 162 |
+
detached = flat.detach()
|
| 163 |
+
for local_index, expert in enumerate(self.experts):
|
| 164 |
+
positions = (selected == local_index).nonzero(as_tuple=False)
|
| 165 |
+
if positions.numel() == 0:
|
| 166 |
+
continue
|
| 167 |
+
token_indices, rank_indices = positions.unbind(dim=1)
|
| 168 |
+
expert_values = expert(detached.index_select(0, token_indices)).detach()
|
| 169 |
+
weighted = expert_values * weights[token_indices, rank_indices].unsqueeze(-1)
|
| 170 |
+
output = output.index_add(0, token_indices, weighted)
|
| 171 |
+
return output
|
| 172 |
+
|
| 173 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 174 |
+
if not self.enabled:
|
| 175 |
+
self.last_trace = None
|
| 176 |
+
return hidden_states
|
| 177 |
+
original_shape = hidden_states.shape
|
| 178 |
+
flat = hidden_states.reshape(-1, original_shape[-1])
|
| 179 |
+
logits = self.router(flat)
|
| 180 |
+
|
| 181 |
+
if self._forced_expert is not None:
|
| 182 |
+
selected = torch.full(
|
| 183 |
+
(flat.shape[0], 1), self._forced_expert, dtype=torch.long, device=flat.device
|
| 184 |
+
)
|
| 185 |
+
weights = torch.ones((flat.shape[0], 1), dtype=flat.dtype, device=flat.device)
|
| 186 |
+
off_probability = torch.zeros(flat.shape[0], dtype=flat.dtype, device=flat.device)
|
| 187 |
+
scale = torch.as_tensor(self._forced_scale, dtype=flat.dtype, device=flat.device)
|
| 188 |
+
else:
|
| 189 |
+
probabilities = torch.softmax(logits.float(), dim=-1).to(flat.dtype)
|
| 190 |
+
expert_probabilities = probabilities[:, :-1]
|
| 191 |
+
weights, selected = expert_probabilities.topk(self.top_k, dim=-1)
|
| 192 |
+
off_probability = probabilities[:, -1]
|
| 193 |
+
scale = torch.clamp(F.softplus(self.expert_scale), max=self.maximum_scale).to(flat.dtype)
|
| 194 |
+
|
| 195 |
+
expert_output = self._expert_output(flat, selected, weights)
|
| 196 |
+
host_std = flat.float().std().detach().clamp_min(1e-6)
|
| 197 |
+
expert_std = expert_output.float().std().detach().clamp_min(1e-6)
|
| 198 |
+
expert_output = expert_output * torch.clamp(host_std / expert_std, max=2.0).to(flat.dtype)
|
| 199 |
+
self.last_trace = RouteTrace(logits, selected, weights, off_probability, scale)
|
| 200 |
+
return hidden_states + (scale * expert_output).reshape(original_shape)
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
class AugmentedHostLayer(nn.Module):
|
| 204 |
+
def __init__(self, host_layer: nn.Module, expert_block: FrozenExpertRouterBlock):
|
| 205 |
+
super().__init__()
|
| 206 |
+
self.host_layer = host_layer
|
| 207 |
+
self.expert_block = expert_block
|
| 208 |
+
self.is_attention_layer = getattr(host_layer, "is_attention_layer", False)
|
| 209 |
+
|
| 210 |
+
def forward(self, hidden_states: torch.Tensor, *args: Any, **kwargs: Any) -> torch.Tensor:
|
| 211 |
+
output = self.host_layer(hidden_states, *args, **kwargs)
|
| 212 |
+
if not isinstance(output, torch.Tensor):
|
| 213 |
+
raise TypeError(f"unsupported LFM2 layer output type: {type(output)!r}")
|
| 214 |
+
return self.expert_block(output)
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
def attach_router_block(model: nn.Module, layer: int, block: FrozenExpertRouterBlock) -> AugmentedHostLayer:
|
| 218 |
+
layers = model.model.layers
|
| 219 |
+
if not 0 <= layer < len(layers):
|
| 220 |
+
raise ValueError(f"layer {layer} outside host model with {len(layers)} layers")
|
| 221 |
+
wrapper = AugmentedHostLayer(layers[layer], block)
|
| 222 |
+
layers[layer] = wrapper
|
| 223 |
+
return wrapper
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
def freeze_except_routers(model: nn.Module) -> dict[str, int]:
|
| 227 |
+
counts = {"hostAndExperts": 0, "router": 0, "expertScale": 0, "trainable": 0}
|
| 228 |
+
for name, parameter in model.named_parameters():
|
| 229 |
+
if ".expert_block.router.gate.weight" in name:
|
| 230 |
+
parameter.requires_grad_(True)
|
| 231 |
+
counts["router"] += parameter.numel()
|
| 232 |
+
elif name.endswith(".expert_block.expert_scale"):
|
| 233 |
+
parameter.requires_grad_(True)
|
| 234 |
+
counts["expertScale"] += parameter.numel()
|
| 235 |
+
else:
|
| 236 |
+
parameter.requires_grad_(False)
|
| 237 |
+
counts["hostAndExperts"] += parameter.numel()
|
| 238 |
+
if parameter.requires_grad:
|
| 239 |
+
counts["trainable"] += parameter.numel()
|
| 240 |
+
assert_trainable_isolation(model)
|
| 241 |
+
return counts
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
def assert_trainable_isolation(model: nn.Module) -> list[str]:
|
| 245 |
+
names = [name for name, parameter in model.named_parameters() if parameter.requires_grad]
|
| 246 |
+
invalid = [
|
| 247 |
+
name
|
| 248 |
+
for name in names
|
| 249 |
+
if ".expert_block.router.gate.weight" not in name
|
| 250 |
+
and not name.endswith(".expert_block.expert_scale")
|
| 251 |
+
]
|
| 252 |
+
if invalid:
|
| 253 |
+
raise RuntimeError(f"trainable-parameter isolation failed: {invalid[:5]}")
|
| 254 |
+
if not names:
|
| 255 |
+
raise RuntimeError("trainable-parameter isolation found no router parameters")
|
| 256 |
+
return names
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
def router_state_dict(model: nn.Module) -> dict[str, torch.Tensor]:
|
| 260 |
+
return {
|
| 261 |
+
name: tensor.detach().cpu().contiguous()
|
| 262 |
+
for name, tensor in model.state_dict().items()
|
| 263 |
+
if ".expert_block.router.gate.weight" in name
|
| 264 |
+
or name.endswith(".expert_block.expert_scale")
|
| 265 |
+
}
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
def load_router_state_dict(model: nn.Module, state: dict[str, torch.Tensor]) -> None:
|
| 269 |
+
expected = set(router_state_dict(model))
|
| 270 |
+
if set(state) != expected:
|
| 271 |
+
raise RuntimeError(
|
| 272 |
+
f"router checkpoint identity mismatch: missing={sorted(expected-set(state))}, "
|
| 273 |
+
f"extra={sorted(set(state)-expected)}"
|
| 274 |
+
)
|
| 275 |
+
current = model.state_dict()
|
| 276 |
+
for name, tensor in state.items():
|
| 277 |
+
current[name].copy_(tensor.to(current[name]))
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
def benefit_targets(host_nll: torch.Tensor, candidate_nll: torch.Tensor, margin: float) -> torch.Tensor:
|
| 281 |
+
"""Return the best expert index, or the explicit off class if none earns its cost.
|
| 282 |
+
|
| 283 |
+
``candidate_nll`` is shaped ``[tokens, candidates]`` and must contain
|
| 284 |
+
exact detached counterfactual losses generated outside the served path.
|
| 285 |
+
"""
|
| 286 |
+
if host_nll.ndim != 1 or candidate_nll.ndim != 2 or candidate_nll.shape[0] != host_nll.shape[0]:
|
| 287 |
+
raise ValueError("counterfactual NLL shapes are incompatible")
|
| 288 |
+
best_nll, best_index = candidate_nll.min(dim=-1)
|
| 289 |
+
off_index = candidate_nll.shape[-1]
|
| 290 |
+
off = torch.full_like(best_index, off_index)
|
| 291 |
+
return torch.where(best_nll + margin < host_nll, best_index, off)
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
def benefit_weighted_router_loss(
|
| 295 |
+
logits: torch.Tensor,
|
| 296 |
+
targets: torch.Tensor,
|
| 297 |
+
host_nll: torch.Tensor,
|
| 298 |
+
candidate_nll: torch.Tensor,
|
| 299 |
+
) -> torch.Tensor:
|
| 300 |
+
best_nll = candidate_nll.min(dim=-1).values
|
| 301 |
+
benefit = (host_nll - best_nll).clamp_min(0).detach()
|
| 302 |
+
weights = torch.where(targets == logits.shape[-1] - 1, torch.ones_like(benefit), 1 + benefit)
|
| 303 |
+
return (F.cross_entropy(logits.float(), targets, reduction="none") * weights.float()).mean()
|
| 304 |
+
|