Coverage for transformer_lens/model_bridge/generalized_components/moe.py: 91%
368 statements
« prev ^ index » next coverage.py v7.10.1, created at 2026-11-25 00:28 +0000
« prev ^ index » next coverage.py v7.10.1, created at 2026-11-25 00:28 +0000
1"""Mixture of Experts bridge component.
3This module contains the bridge component for Mixture of Experts layers.
4"""
6from __future__ import annotations
8import logging
9import warnings
10from functools import wraps
11from inspect import currentframe, getclosurevars
12from threading import Lock
13from types import CodeType, FunctionType, MethodType
14from typing import Any, Callable, Dict, List, Mapping, Optional, Tuple
16import torch
17from torch import nn
19from transformer_lens.hook_points import HookPoint
20from transformer_lens.model_bridge.generalized_components.base import (
21 GeneralizedComponent,
22)
23from transformer_lens.model_bridge.generalized_components.linear import LinearBridge
24from transformer_lens.model_bridge.generalized_components.mlp import (
25 normalize_mlp_weight,
26 weight_layout_in_out,
27)
29# transformers stores a whole expert stack in one 3-D Parameter under a fixed
30# vocabulary of names. The role has to come from the name: in the untransposed
31# layout down_proj is [n_experts, d_model, d_mlp], so its d_model axis is
32# indistinguishable by shape from an input projection's.
33_BATCHED_INPUT_PROJECTIONS = frozenset({"gate_up_proj", "gate_proj", "up_proj"})
34_BATCHED_OUTPUT_PROJECTIONS = frozenset({"down_proj"})
35_BATCHED_PROJECTIONS = _BATCHED_INPUT_PROJECTIONS | _BATCHED_OUTPUT_PROJECTIONS
37_MPS_OUTPUT_SLICE_RESULTS: Dict[Tuple[torch.device, torch.dtype], bool] = {}
38_MPS_OUTPUT_SLICE_LOCK = Lock()
39_MPS_EXPERTS_WARNED = False
40_MPS_EXPERTS_WARNING_LOCK = Lock()
43def _warn_mps_experts_once() -> None:
44 """Warn once at the first caller outside the model and runtime-checking libraries."""
45 global _MPS_EXPERTS_WARNED
46 with _MPS_EXPERTS_WARNING_LOCK:
47 if _MPS_EXPERTS_WARNED:
48 return
49 _MPS_EXPERTS_WARNED = True
50 frame = None
51 emitted = False
52 try:
53 frame = currentframe()
54 stacklevel = 1
55 while frame is not None: 55 ↛ 64line 55 didn't jump to line 64 because the condition on line 55 was always true
56 module = frame.f_globals.get("__name__", "")
57 if not any(
58 module == prefix or module.startswith(prefix + ".")
59 for prefix in ("transformer_lens", "transformers", "torch", "jaxtyping", "beartype")
60 ):
61 break
62 frame = frame.f_back
63 stacklevel += 1
64 warnings.warn(
65 "Using eager experts on MPS after detecting incorrect "
66 "matmul output-slice writes; expert execution may be slower.",
67 RuntimeWarning,
68 stacklevel=stacklevel,
69 )
70 emitted = True
71 finally:
72 del frame
73 if not emitted:
74 with _MPS_EXPERTS_WARNING_LOCK:
75 _MPS_EXPERTS_WARNED = False
78def _probe_mps_output_slice_writes(device: torch.device, dtype: torch.dtype) -> bool:
79 """Check for incorrect nonzero-offset matmul output writes using isolated tensors."""
80 with torch.no_grad(), torch.autocast(device_type=device.type, enabled=False):
81 generator = torch.Generator(device="cpu").manual_seed(0)
82 inputs = torch.randn(10, 64, generator=generator).to(device=device, dtype=dtype)
83 weights = torch.randn(4, 64, 32, generator=generator).to(device=device, dtype=dtype)
84 output = torch.zeros(10, 32, device=device, dtype=dtype)
85 expected = inputs[5:] @ weights[3]
86 torch.mm(inputs[5:], weights[3], out=output[5:])
87 rtol = max(1e-5, 2 * torch.finfo(dtype).eps)
88 prefix_intact = torch.count_nonzero(output[:5]).item() == 0
89 products_match = torch.allclose(output[5:], expected, rtol=rtol, atol=1e-5)
90 return not (prefix_intact and products_match)
93def _mps_output_slice_writes_are_broken(device: torch.device, dtype: torch.dtype) -> bool:
94 """Cache the primitive check once per device and dtype, including concurrent first use."""
95 key = (device, dtype)
96 with _MPS_OUTPUT_SLICE_LOCK:
97 if key not in _MPS_OUTPUT_SLICE_RESULTS:
98 try:
99 _MPS_OUTPUT_SLICE_RESULTS[key] = _probe_mps_output_slice_writes(device, dtype)
100 except (RuntimeError, TypeError) as error:
101 raise RuntimeError(
102 f"Cannot verify MPS matmul output-slice writes on {device} with {dtype}. "
103 "Select eager experts explicitly or use CPU execution."
104 ) from error
105 return _MPS_OUTPUT_SLICE_RESULTS[key]
108def _mps_experts_forward(experts: nn.Module, *args: Any, **kwargs: Any) -> Any:
109 """Dispatch locally, without changing the config shared by other expert layers."""
110 hidden_states = args[0] if args else kwargs.get("hidden_states")
111 forward = type(experts).forward
112 config: Any = getattr(experts, "config", None)
113 eager = None
114 if (
115 isinstance(hidden_states, torch.Tensor)
116 and hidden_states.device.type == "mps"
117 and getattr(config, "_experts_implementation", None) == "grouped_mm"
118 ):
119 eager = _hf_eager_experts_forward(forward)
120 if eager is not None:
121 dtypes = {
122 parameter.dtype
123 for parameter in experts.parameters(recurse=False)
124 if parameter.ndim == 3 and parameter.is_floating_point()
125 } or {hidden_states.dtype}
126 if any(
127 _mps_output_slice_writes_are_broken(hidden_states.device, dtype) for dtype in dtypes
128 ):
129 _warn_mps_experts_once()
130 return eager(experts, *args, **kwargs)
131 return forward(experts, *args, **kwargs)
134def _hf_eager_experts_forward(forward: Any) -> Optional[Callable[..., Any]]:
135 """Recognize HF's shared grouped dispatcher and recover its original eager forward."""
136 from transformers.integrations.moe import (
137 ExpertsInterface,
138 grouped_mm_experts_forward,
139 use_experts_implementation,
140 )
142 if not isinstance(forward, FunctionType): 142 ↛ 143line 142 didn't jump to line 143 because the condition on line 142 was never true
143 return None
144 if not any(
145 forward.__code__ is candidate
146 for wrapper in use_experts_implementation.__code__.co_consts
147 if isinstance(wrapper, CodeType) and wrapper.co_name == "wrapper"
148 for candidate in wrapper.co_consts
149 if isinstance(candidate, CodeType) and candidate.co_name == "forward"
150 ):
151 return None
152 closure = getclosurevars(forward).nonlocals
153 original = closure.get("original_forward")
154 interface = closure.get("experts_interface")
155 if (
156 not callable(original)
157 or original is not getattr(forward, "__wrapped__", None)
158 or not isinstance(interface, ExpertsInterface)
159 or interface.get_interface("grouped_mm", original) is not grouped_mm_experts_forward
160 ):
161 return None
162 return original
165def _guard_mps_experts(component: nn.Module) -> None:
166 """Install instance-local dispatch only for HF's shared grouped expert implementation.
168 The bound method preserves the forward signature, nn.Module hooks, and deepcopy
169 semantics. Configs and global dispatch tables remain untouched, including during
170 concurrent forwards.
171 """
172 experts = getattr(component, "experts", None)
173 if not isinstance(experts, nn.Module):
174 return
175 experts = unwrap_bridge(experts)
176 forward = type(experts).forward
177 if getattr(experts.forward, "__func__", None) is not forward:
178 return
179 if _hf_eager_experts_forward(forward) is None:
180 return
182 @wraps(forward)
183 def guarded_forward(experts: nn.Module, *args: Any, **kwargs: Any) -> Any:
184 return _mps_experts_forward(experts, *args, **kwargs)
186 setattr(experts, "forward", MethodType(guarded_forward, experts))
189class UnfoldableMoEParameter(Exception):
190 """A parameter whose relationship to the MoE block's input cannot be established."""
193def unwrap_bridge(module: nn.Module) -> nn.Module:
194 """Descend through bridge wrappers to the module that owns the weights."""
195 while True:
196 original = getattr(module, "original_component", None)
197 if not isinstance(original, nn.Module):
198 return module
199 module = original
202def has_batched_experts(module: nn.Module) -> bool:
203 """Whether this MoE block stores its experts as batched 3-D Parameters.
205 Those parameters are not ``weight``/``bias`` leaves of a declared bridge
206 submodule, so ``TransformerBridge.state_dict()`` drops them and no state-dict
207 pass can reach them.
208 """
209 return any(
210 parameter.ndim == 3 and name.rpartition(".")[2] in _BATCHED_PROJECTIONS
211 for name, parameter in unwrap_bridge(module).named_parameters()
212 )
215def _input_axis(
216 owner: nn.Module, leaf: str, parameter: torch.Tensor, d_model: int
217) -> Optional[int]:
218 """Axis the block's input flows into, or None when the parameter never reads it.
220 Raises UnfoldableMoEParameter when the role cannot be established, so the caller
221 can decline rather than guess — a fold that misses one reader is silently wrong.
222 """
223 if leaf == "bias" or leaf.endswith("_bias"):
224 return None # folding a norm's gain never touches a downstream bias
225 if parameter.ndim == 1:
226 raise UnfoldableMoEParameter(
227 f"{leaf}: 1-D weight inside the MoE block looks like a normalization gain, "
228 "which would re-normalize away the scale being folded"
229 )
230 if parameter.ndim == 2:
231 in_features = getattr(owner, "in_features", None)
232 if in_features is not None:
233 return -1 if in_features == d_model else None
234 # Routers hold a bare Parameter and consume it through F.linear, i.e. [out, in].
235 if parameter.shape[0] == d_model and parameter.shape[-1] != d_model: 235 ↛ 236line 235 didn't jump to line 236 because the condition on line 235 was never true
236 raise UnfoldableMoEParameter(
237 f"{leaf}: 2-D {tuple(parameter.shape)} on {type(owner).__name__} has "
238 "d_model on the output axis, so its orientation is not F.linear's"
239 )
240 if parameter.shape[-1] != d_model: 240 ↛ 241line 240 didn't jump to line 241 because the condition on line 240 was never true
241 return None
242 if parameter.shape[0] == d_model: 242 ↛ 243line 242 didn't jump to line 243 because the condition on line 242 was never true
243 raise UnfoldableMoEParameter(f"{leaf}: square {tuple(parameter.shape)} is ambiguous")
244 return -1
245 if parameter.ndim == 3: 245 ↛ 267line 245 didn't jump to line 267 because the condition on line 245 was always true
246 if leaf in _BATCHED_OUTPUT_PROJECTIONS:
247 return None # reads the expert intermediate, not the block input
248 if leaf not in _BATCHED_INPUT_PROJECTIONS:
249 raise UnfoldableMoEParameter(f"{leaf}: unrecognized batched expert parameter")
250 transposed = getattr(owner, "is_transposed", None)
251 if transposed is not None:
252 axis = 1 if transposed else -1
253 if parameter.shape[axis] != d_model: 253 ↛ 254line 253 didn't jump to line 254 because the condition on line 253 was never true
254 raise UnfoldableMoEParameter(
255 f"{leaf}: {tuple(parameter.shape)} has no d_model on the axis "
256 f"is_transposed={transposed} implies"
257 )
258 return axis
259 # A few experts classes (Llama4) predate the layout flag; fall back to shape.
260 candidates = [axis for axis in (1, -1) if parameter.shape[axis] == d_model]
261 if len(candidates) != 1:
262 raise UnfoldableMoEParameter(
263 f"{leaf}: {type(owner).__name__} declares no is_transposed and "
264 f"{tuple(parameter.shape)} does not pin d_model to one axis"
265 )
266 return candidates[0]
267 raise UnfoldableMoEParameter(f"{leaf}: unexpected {parameter.ndim}-D parameter")
270def fold_scale_into_moe_block(module: nn.Module, scale: torch.Tensor) -> bool:
271 """Scale every parameter of a MoE block that reads the block's input, in place.
273 Routed experts, shared experts and the router all read the preceding norm's
274 output; only the down-projections read the expert intermediate. Returns False
275 without touching anything when any parameter's role is unclear, because a fold
276 that reaches some readers and not others changes what the model computes.
277 """
278 block = unwrap_bridge(module)
279 d_model = int(scale.shape[0])
280 plan: List[Tuple[torch.Tensor, int]] = []
281 try:
282 for name, parameter in block.named_parameters():
283 prefix, _, leaf = name.rpartition(".")
284 owner = block.get_submodule(prefix) if prefix else block
285 axis = _input_axis(owner, leaf, parameter, d_model)
286 if axis is not None:
287 plan.append((parameter, axis))
288 except UnfoldableMoEParameter as reason:
289 logging.warning("Not folding the layer norm into %s: %s", type(block).__name__, reason)
290 return False
291 if not plan: 291 ↛ 292line 291 didn't jump to line 292 because the condition on line 291 was never true
292 return False
293 with torch.no_grad():
294 for target, axis in plan:
295 shape = [1] * target.ndim
296 shape[axis] = d_model
297 target.mul_(scale.reshape(shape).to(dtype=target.dtype, device=target.device))
298 return True
301class MoEBridge(GeneralizedComponent):
302 """Bridge component for Mixture of Experts layers.
304 This component wraps a Mixture of Experts layer from a remote model and provides a consistent interface
305 for accessing its weights and performing MoE operations.
307 hook_router_scores fires only when the wrapped block returns a tuple
308 (gpt_oss, LLaDA2 remote); 5.13-native SparseMoeBlocks return a plain
309 tensor, so router observability comes from the ``gate`` submodule's
310 hook_out instead.
311 """
313 hook_aliases = {"hook_pre": "hook_in", "hook_post": "hook_out"}
315 # Deliberately NOT gate/in/out: ``gate`` is the ROUTER on sparse layers of
316 # the same model, so reusing it would flip the meaning of
317 # blocks.N.mlp.gate.hook_out per layer (#1645's own confusion). dense_gate
318 # is absent on ungated feed-forwards (Switch's wi/wo); the alias set
319 # follows the bound shape.
320 DENSE_SUBMODULE_KEYS = ("dense_in", "dense_out")
321 DENSE_GATE_KEY = "dense_gate"
322 _DENSE_HOOK_ALIASES = {
323 "hook_pre": "dense_in.hook_out",
324 "hook_post": "dense_out.hook_in",
325 }
326 _DENSE_GATED_HOOK_ALIASES = {
327 "hook_pre": "dense_gate.hook_out",
328 "hook_pre_linear": "dense_in.hook_out",
329 "hook_post": "dense_out.hook_in",
330 }
331 _DENSE_PROPERTY_ALIASES = {
332 "b_gate": "dense_gate.bias",
333 "b_in": "dense_in.bias",
334 "b_out": "dense_out.bias",
335 }
337 def __init__(
338 self,
339 name: str,
340 config: Optional[Any] = None,
341 submodules: Optional[Dict[str, GeneralizedComponent]] = {},
342 optional: bool = False,
343 sparse_required: Tuple[str, ...] = (),
344 ):
345 """Initialize the MoE bridge.
347 Args:
348 name: The name of the component in the model
349 config: Optional configuration (unused for MoEBridge)
350 submodules: Dictionary of GeneralizedComponent submodules to register
351 optional: If True, setup skips this subtree when absent (dense layers)
352 sparse_required: Submodule keys that must be declared ``optional``
353 (dense layers of an interleaved stack do not have them) but whose
354 absence on a SPARSE layer is an error rather than a silent skip.
355 Routers belong here: HF creates them unconditionally on sparse
356 blocks, so a skip means the attribute was renamed or moved, and
357 plain ``optional`` would drop their hooks without a word.
358 """
359 super().__init__(name, config, submodules=submodules, optional=optional)
360 self.hook_router_scores = HookPoint()
361 self._bound_dense = False
362 self._bound_dense_gate = False
363 # A misspelled key would silently disable the very guard that exists to
364 # stop silent degradation, so the opt-in is validated on construction.
365 unknown = set(sparse_required) - set(submodules or {})
366 if unknown:
367 raise ValueError(
368 f"{name}: sparse_required {sorted(unknown)} are not declared "
369 f"submodules (declared: {sorted(submodules or {})})"
370 )
371 self._sparse_required = sparse_required
372 # HookedTransformer exposes the routing observables on the MoE block
373 # itself; the bridge fires them on the router submodule, whose adapter
374 # key differs ("gate" on 5.13 SparseMoeBlocks, "router" on GPT-OSS).
375 # Alias so code migrated from HT finds them under the HT name.
376 self._router_hook_aliases = self._build_router_hook_aliases(submodules or {})
377 self.hook_aliases = {**self.hook_aliases, **self._router_hook_aliases}
379 @staticmethod
380 def _build_router_hook_aliases(
381 submodules: Mapping[str, GeneralizedComponent],
382 ) -> Dict[str, str]:
383 """Map HT's block-level routing hook names onto the router submodule."""
384 aliases: Dict[str, str] = {}
385 for key, component in submodules.items():
386 if not isinstance(component, MoERouterBridge):
387 continue
388 if component.weights_index is not None:
389 aliases["hook_expert_weights"] = f"{key}.hook_expert_weights"
390 if component.indices_index is not None:
391 aliases["hook_expert_indices"] = f"{key}.hook_expert_indices"
392 break
393 return aliases
395 def _binds_dense_projections(self, component: torch.nn.Module) -> bool:
396 """Whether this layer is the dense variant of an interleaved MoE stack.
398 Positive detection only: the adapter must have declared the dense
399 projections AND the wrapped module must actually expose them. Guessing
400 from the absence of ``experts`` would risk silently stripping hooks off
401 a sparse block whose experts are named differently.
402 """
403 declared = [self.submodules.get(key) for key in self.DENSE_SUBMODULE_KEYS]
404 if not all(declared):
405 return False
406 return all(
407 sub is not None and sub.name is not None and hasattr(component, sub.name)
408 for sub in declared
409 )
411 def _binds_dense_gate(self, component: torch.nn.Module) -> bool:
412 """Whether the bound dense MLP is gated (SiLU-gated) rather than plain.
414 A declared-but-unresolvable gate means the HF attribute was renamed,
415 not that the MLP is ungated — binding it as ungated would silently
416 alias hook_pre to the UP projection, so raise instead.
417 """
418 gate = self.submodules.get(self.DENSE_GATE_KEY)
419 if gate is None or gate.name is None:
420 return False # never declared: a genuinely ungated dense MLP
421 if hasattr(component, gate.name):
422 return True
423 raise ValueError(
424 f"{self.name}: dense layer wrapped {type(component).__name__} which has "
425 f"no {gate.name!r}, but this adapter declares {self.DENSE_GATE_KEY!r} — "
426 "so its dense MLPs are gated and the attribute was renamed or moved. "
427 "Binding it as ungated would alias hook_pre to the up projection. "
428 "Update the adapter's submodule name, or drop the declaration if this "
429 "architecture's dense layers really are ungated."
430 )
432 def set_original_component(self, component: torch.nn.Module) -> None:
433 """Bind the layer, adopting gated-MLP semantics on dense layers.
435 Dense layers of interleaved MoE stacks get neuron-basis hooks and
436 weight accessors instead of MoE boundary tensors under those names.
437 """
438 super().set_original_component(component)
439 is_dense = self._binds_dense_projections(component)
440 if is_dense == self._bound_dense:
441 # First sparse bind, or an idempotent rebind: nothing to morph.
442 if not is_dense: 442 ↛ 444line 442 didn't jump to line 444 because the condition on line 442 was always true
443 return
444 self._bound_dense = is_dense
445 if is_dense:
446 self._bound_dense_gate = self._binds_dense_gate(component)
447 self.hook_aliases = dict(
448 self._DENSE_GATED_HOOK_ALIASES
449 if self._bound_dense_gate
450 else self._DENSE_HOOK_ALIASES
451 )
452 dense_props = dict(self._DENSE_PROPERTY_ALIASES)
453 if not self._bound_dense_gate:
454 dense_props.pop("b_gate", None)
455 self.property_aliases = {**self.property_aliases, **dense_props}
456 # A dense layer has no router; leaving the hook in hook_dict would
457 # advertise an intervention point that can never fire.
458 if hasattr(self, "hook_router_scores"): 458 ↛ exitline 458 didn't return from function 'set_original_component' because the condition on line 458 was always true
459 self._hook_registry.pop("hook_router_scores", None)
460 del self.hook_router_scores
461 else:
462 # Symmetric restore so a rebinding harness cannot leave a chimera.
463 self.hook_aliases = {**type(self).hook_aliases, **self._router_hook_aliases}
464 self.property_aliases = {
465 key: value
466 for key, value in self.property_aliases.items()
467 if key not in self._DENSE_PROPERTY_ALIASES
468 }
469 self._bound_dense_gate = False
470 if not hasattr(self, "hook_router_scores"): 470 ↛ exitline 470 didn't return from function 'set_original_component' because the condition on line 470 was always true
471 self.hook_router_scores = HookPoint()
473 def validate_after_setup(self, skipped_optional: list[str]) -> None:
474 """Fail loudly when a sparse layer is missing a submodule only dense
475 layers may lack (see ``sparse_required``).
477 Called by setup_submodules once every submodule has resolved — the
478 skipped set is not knowable at bind time.
479 """
480 if self._bound_dense or not self._sparse_required:
481 return
482 missing = [key for key in self._sparse_required if key in skipped_optional]
483 if missing:
484 component = type(self.original_component).__name__
485 raise ValueError(
486 f"{self.name}: sparse MoE layer wrapped {component} but required "
487 f"submodule(s) {missing} were absent. These are optional only so "
488 "dense layers of an interleaved stack can skip them; on a sparse "
489 "layer their absence means the HF attribute was renamed or moved. "
490 "Update the adapter's submodule name(s) rather than losing the hooks."
491 )
493 @property
494 def bound_dense(self) -> bool:
495 """Whether this layer bound the dense variant of an interleaved MoE stack.
497 Public so weight-collection helpers can find the projections under
498 ``DENSE_SUBMODULE_KEYS`` instead of the sparse ``gate`` (the router).
499 """
500 return self._bound_dense
502 def _dense_projection(self, key: str) -> Any:
503 """Return a bound dense projection.
505 Raises AttributeError on sparse layers (per-expert weights, no single
506 W_*) so ``hasattr`` stays False and weight collection skips them.
507 """
508 if not self._bound_dense:
509 raise AttributeError(f"{self.name}: {key} exists only on dense layers")
510 module = getattr(self, key, None)
511 if module is None: 511 ↛ 512line 511 didn't jump to line 512 because the condition on line 511 was never true
512 raise AttributeError(f"{self.name}: dense projection {key!r} is not bound")
513 return module
515 @property
516 def W_gate(self) -> torch.Tensor:
517 """Gated dense layer's gate weight in TL orientation [d_model, d_mlp]."""
518 if not self._bound_dense_gate:
519 raise AttributeError(f"{self.name}: this dense layer is ungated (no W_gate)")
520 module = self._dense_projection("dense_gate")
521 return normalize_mlp_weight(
522 module.weight, weight_layout_in_out(module), module, pattern="in"
523 )
525 @property
526 def W_in(self) -> torch.Tensor:
527 """Dense-layer input weight in TL orientation [d_model, d_mlp]."""
528 module = self._dense_projection("dense_in")
529 return normalize_mlp_weight(
530 module.weight, weight_layout_in_out(module), module, pattern="in"
531 )
533 @property
534 def W_out(self) -> torch.Tensor:
535 """Dense-layer output weight in TL orientation [d_mlp, d_model]."""
536 module = self._dense_projection("dense_out")
537 return normalize_mlp_weight(
538 module.weight, weight_layout_in_out(module), module, pattern="out"
539 )
541 def get_random_inputs(
542 self,
543 batch_size: int = 2,
544 seq_len: int = 8,
545 device: Optional[torch.device] = None,
546 dtype: Optional[torch.dtype] = None,
547 ) -> Dict[str, Any]:
548 """Generate random inputs for component testing.
550 Args:
551 batch_size: Batch size for generated inputs
552 seq_len: Sequence length for generated inputs
553 device: Device to place tensors on
554 dtype: Dtype for generated tensors (defaults to float32)
556 Returns:
557 Dictionary of input tensors matching the component's expected input signature
558 """
559 if device is None: 559 ↛ 560line 559 didn't jump to line 560 because the condition on line 559 was never true
560 device = torch.device("cpu")
561 if dtype is None: 561 ↛ 562line 561 didn't jump to line 562 because the condition on line 561 was never true
562 dtype = torch.float32
563 d_model = self.config.d_model if self.config and hasattr(self.config, "d_model") else 768
564 # Use positional args to avoid parameter name mismatches across MoE implementations
565 # (e.g., Mixtral uses "hidden_states", GraniteMoe uses "layer_input")
566 return {"args": (torch.randn(batch_size, seq_len, d_model, device=device, dtype=dtype),)}
568 def forward(self, *args: Any, **kwargs: Any) -> Any:
569 """Forward pass through the MoE bridge.
571 Args:
572 *args: Input arguments
573 **kwargs: Input keyword arguments
575 Returns:
576 Same return type as original component (tuple or tensor).
577 For MoE models that return (hidden_states, router_scores), preserves the tuple.
578 Router scores are also captured via hook for inspection.
579 """
580 if self.original_component is None: 580 ↛ 581line 580 didn't jump to line 581 because the condition on line 580 was never true
581 raise RuntimeError(
582 f"Original component not set for {self.name}. Call set_original_component() first."
583 )
584 if len(args) > 0:
585 hooked = self.hook_in(args[0])
586 args = (hooked,) + args[1:]
587 elif "hidden_states" in kwargs: 587 ↛ 590line 587 didn't jump to line 590 because the condition on line 587 was always true
588 hooked = self.hook_in(kwargs["hidden_states"])
589 kwargs = {**kwargs, "hidden_states": hooked}
590 _guard_mps_experts(self.original_component)
591 output = self.original_component(*args, **kwargs)
592 if isinstance(output, tuple):
593 if not output:
594 raise TypeError(
595 f"{self.name}: expected a non-empty tuple whose first "
596 "element is a torch.Tensor from the wrapped MoE component, "
597 "got an empty tuple."
598 )
600 hidden_states = output[0]
601 if not isinstance(hidden_states, torch.Tensor):
602 raise TypeError(
603 f"{self.name}: expected the first tuple element from the "
604 f"wrapped MoE component to be a torch.Tensor, got "
605 f"{type(hidden_states).__name__}."
606 )
607 if len(output) > 1: 607 ↛ 620line 607 didn't jump to line 620 because the condition on line 607 was always true
608 router_scores = output[1]
609 # Some MoEs pack extras with the logits (LLaDA2 returns
610 # (router_logits, topk_idx)); hook the first tensor.
611 if isinstance(router_scores, tuple):
612 router_scores = next(
613 (t for t in router_scores if isinstance(t, torch.Tensor)), None
614 )
615 # The hook is removed on dense binds (no router exists there), so
616 # a dense layer whose wrapped module still returns a tuple must
617 # pass the extras through untouched rather than raise.
618 if isinstance(router_scores, torch.Tensor) and hasattr(self, "hook_router_scores"):
619 self.hook_router_scores(router_scores)
620 hidden_states = self.hook_out(hidden_states)
621 return (hidden_states,) + output[1:]
622 else:
623 hidden_states = self.hook_out(output)
624 return hidden_states
627class MoERouterBridge(LinearBridge):
628 """Bridge MoE router logits while preserving HF's tuple return.
630 5.13 TopKRouters return ``(router_logits, topk_weights, topk_indices)``;
631 hook_out fires on the logits (element ``logits_index`` — JetMoe puts them
632 last) and the tuple is re-packed so HF's unpacking is undisturbed.
634 ``hook_expert_weights`` / ``hook_expert_indices`` mirror the HookedTransformer
635 MoE routing hooks. HF routers hand back top-k-shaped weights
636 ``[tokens, top_k]``, so the weights are scattered to HT's
637 ``[tokens, num_experts]`` before firing and gathered back afterwards — an
638 unedited round trip returns the values bit-for-bit. Any weight edit
639 re-derives the top-k selection from the edited tensor, so boosting a
640 suppressed expert re-routes the token (HT's pre-top-k contract); unlike
641 HT's mixtral component, edited weights are used as-is with no
642 renormalization after the hook.
643 """
645 def __init__(
646 self,
647 *args: Any,
648 logits_index: int = 0,
649 weights_index: Optional[int] = 1,
650 indices_index: Optional[int] = 2,
651 **kwargs: Any,
652 ):
653 super().__init__(*args, **kwargs)
654 self.logits_index = logits_index
655 self.weights_index = weights_index
656 self.indices_index = indices_index
657 # None means this router's tuple has no clean [tokens, top_k] pair
658 # (JetMoe returns a sorted-expert layout); registering the hook anyway
659 # would advertise an intervention point that can never fire.
660 if weights_index is not None:
661 self.hook_expert_weights = HookPoint()
662 if indices_index is not None:
663 self.hook_expert_indices = HookPoint()
665 def forward(self, input: torch.Tensor, *args: Any, **kwargs: Any) -> Any:
666 if self.original_component is None: 666 ↛ 667line 666 didn't jump to line 667 because the condition on line 666 was never true
667 raise RuntimeError(
668 f"Original component not set for {self.name}. Call set_original_component() first."
669 )
670 input = self.hook_in(input)
671 output = self.original_component(input, *args, **kwargs)
672 if not isinstance(output, tuple) or len(output) == 0: 672 ↛ 673line 672 didn't jump to line 673 because the condition on line 672 was never true
673 return self.hook_out(output)
674 parts = list(output)
675 count = len(parts)
676 logits_at = self.logits_index % count
677 parts[logits_at] = self.hook_out(parts[logits_at])
679 weights_at = None if self.weights_index is None else self.weights_index % count
680 indices_at = None if self.indices_index is None else self.indices_index % count
681 if weights_at is None and indices_at is None: 681 ↛ 682line 681 didn't jump to line 682 because the condition on line 681 was never true
682 return tuple(parts)
684 indices = None if indices_at is None else parts[indices_at]
685 expanded = None
686 if weights_at is not None: 686 ↛ 704line 686 didn't jump to line 704 because the condition on line 686 was always true
687 scattered = self._expand_expert_weights(parts[weights_at], indices, parts[logits_at])
688 expanded = self.hook_expert_weights(scattered)
689 if (
690 indices is not None
691 and expanded.shape != parts[weights_at].shape
692 and not torch.equal(expanded, scattered)
693 ):
694 # An edit outside the current top-k would otherwise be discarded
695 # by the gather below (those columns have no downstream reader in
696 # the [tokens, top_k] layout). Re-derive the selection from the
697 # edited tensor so boosting a suppressed expert re-routes, as it
698 # does on HookedTransformer's pre-top-k hook. The edited values
699 # are used as-is — no per-arch renormalization is re-applied.
700 _, new_indices = torch.topk(expanded, indices.shape[-1], dim=-1)
701 indices = new_indices.to(indices.dtype)
702 if indices_at is not None: 702 ↛ 704line 702 didn't jump to line 704 because the condition on line 702 was always true
703 parts[indices_at] = indices
704 if indices_at is not None: 704 ↛ 707line 704 didn't jump to line 707 because the condition on line 704 was always true
705 indices = self.hook_expert_indices(indices)
706 parts[indices_at] = indices
707 if weights_at is not None: 707 ↛ 711line 707 didn't jump to line 711 because the condition on line 707 was always true
708 # Gathered after the indices hook so re-routing picks up the weight
709 # sitting at the newly selected expert, as HookedTransformer does.
710 parts[weights_at] = self._collapse_expert_weights(expanded, indices, parts[weights_at])
711 return tuple(parts)
713 def _expand_expert_weights(
714 self,
715 weights: torch.Tensor,
716 indices: Optional[torch.Tensor],
717 logits: torch.Tensor,
718 ) -> torch.Tensor:
719 """Scatter top-k weights into HT's ``[tokens, num_experts]`` layout."""
720 if not self._is_top_k_shaped(weights, indices, logits): 720 ↛ 721line 720 didn't jump to line 721 because the condition on line 720 was never true
721 return weights
722 assert indices is not None
723 scattered = torch.zeros(
724 (*weights.shape[:-1], logits.shape[-1]),
725 dtype=weights.dtype,
726 device=weights.device,
727 )
728 scattered.scatter_(-1, indices.long(), weights)
729 return scattered
731 def _collapse_expert_weights(
732 self,
733 expanded: Optional[torch.Tensor],
734 indices: Optional[torch.Tensor],
735 original: torch.Tensor,
736 ) -> torch.Tensor:
737 """Gather the expanded weights back to the top-k layout HF expects."""
738 if expanded is None or indices is None or expanded.shape == original.shape: 738 ↛ 739line 738 didn't jump to line 739 because the condition on line 738 was never true
739 return expanded if expanded is not None else original
740 return expanded.gather(-1, indices.long())
742 @staticmethod
743 def _is_top_k_shaped(
744 weights: torch.Tensor,
745 indices: Optional[torch.Tensor],
746 logits: torch.Tensor,
747 ) -> bool:
748 """Whether the weights are the top-k slice rather than full expert width."""
749 return (
750 indices is not None
751 and isinstance(weights, torch.Tensor)
752 and isinstance(logits, torch.Tensor)
753 and weights.shape == indices.shape
754 and weights.shape[-1] != logits.shape[-1]
755 )
757 def set_processed_weights(
758 self, weights: Mapping[str, Optional[torch.Tensor]], verbose: bool = False
759 ) -> None:
760 """Copy router weights onto nested params by dotted path (JetMoe nests its
761 Linear at ``router.layer.weight``); router weights are never processed."""
762 if "weight" in weights:
763 super().set_processed_weights(weights, verbose=verbose)
764 return
765 if self.original_component is None: 765 ↛ 766line 765 didn't jump to line 766 because the condition on line 765 was never true
766 raise RuntimeError(f"Original component not set for {self.name}")
767 for key, tensor in weights.items():
768 if tensor is None: 768 ↛ 769line 768 didn't jump to line 769 because the condition on line 768 was never true
769 continue
770 target: Any = self.original_component
771 *path, leaf = key.split(".")
772 for part in path:
773 target = getattr(target, part)
774 param = getattr(target, leaf)
775 if param.shape != tensor.shape:
776 raise ValueError(
777 f"Router weight {key} shape {tuple(tensor.shape)} does not match "
778 f"parameter shape {tuple(param.shape)} on {self.name}"
779 )
780 with torch.no_grad():
781 param.copy_(tensor.to(dtype=param.dtype, device=param.device))