MoE Capture and Probing
Active-only per-expert CETT capture for Mixture-of-Experts models (issue #41). Routed experts are replayed read-only (the capture wrapper is bit-exact against the unmodified forward), always-on shared experts are captured alongside, and decision-token features are assembled into a sparse probe design with a routing-only control.
hprobes.moe
Active-only per-expert CETT capture for MoE models (issue #41, phase 0).
Design
Routed experts contribute to a token's residual stream only when the router
selects them; unselected experts contribute exactly zero. So we capture
active-only: for every token and selected (expert, slot), the pre-down_proj
activation a (the same tensor dense CETT hooks), keyed by
(layer, token, expert), plus the router gate weight g.
Per-expert sketches accumulate only over tokens where the expert was active:
mean/variance of the raw activation (order-preserving Welford, so masked
passes reproduce full passes bit-for-bit) and mean |gate|. Contribution
magnitudes are |a * w_down| scaled by the gate as appropriate per
architecture; the sketch records the raw activation so downstream code can
form any of these without re-running forwards.
This module is deliberately model-family-agnostic: it works through the "experts module receives (hidden_states, top_k_index, top_k_weights)" contract shared by Olmoe/Qwen2Moe/Qwen3.5MoE/DeepSeek-style blocks in transformers.
MoECapture
Capture active-only per-expert activations + router decisions.
Install on the experts module of each MoE layer:
cap = MoECapture(num_experts)
handle = cap.attach(experts_module, layer_idx)
...
handle.remove()
col_norms (optional) maps expert -> ||w_down^e|| column norms for
contribution magnitudes; pass the down_proj parameter rows.
Source code in src/hprobes/moe.py
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 | |
attach(experts_module, allow_eager_switch=False)
Wrap the experts module forward to capture per-expert activations.
The family loop calls F.linear(act, down_proj[e]) on parameter
slices, so module hooks cannot see it; the supported contract is the
loop's one-hot mapping from (top_k_index, top_k_weights). The
wrapper replays that mapping: every expert receives exactly the rows
the family's own one-hot would select, and we reuse the model's
weights (gate_up_proj / down_proj parameters) to recompute them.
Outputs are bit-identical to the family implementation.
Requires the model to run the eager experts implementation:
transformers dispatches batched_mm/grouped_mm fast experts
paths for loaded models, and the eager replay would then diverge from
the model's actual forward. Load with
experts_implementation="eager", or pass
allow_eager_switch=True to switch a loaded model's config in
place (a warning is emitted; every subsequent forward of the model
then runs the eager loop).
CPU/disk-offloaded experts (accelerate device_map offload) are
supported when the module carries accelerate's device hook: the
wrapper materializes the weights through pre_forward for the
replay and offloads them again via post_forward, mirroring
accelerate's own forward wrapper. Meta-device parameters without a
usable offload hook are rejected loudly instead of silently producing
NaN features.
Source code in src/hprobes/moe.py
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 | |
clear_records()
Drop recorded per-forward rows.
Recorded activations are only valid for the forward that produced them; callers running multiple forwards (per-sample loops, counterfactual conditions) must clear between forwards so features never leak across samples.
Source code in src/hprobes/moe.py
record_expert(expert, activations, top_k_pos=None, token_idx=None)
Called once per expert per layer-forward with its pre-down_proj activations.
top_k_pos and token_idx are the (slot, token) routing rows for
this expert in the family loop's row order; the wrapping loop passes
its own indices so recorded rows pair 1:1 with activations.
External callers may omit them: they are then re-derived in the same
slot-major order of the loop's (k, T) expert mask.
Source code in src/hprobes/moe.py
routing_table()
set_intervention(expert, features, alpha=None, ablate=False)
Routing-aware intervention on one expert's neurons (#41 causal).
With ablate=True the listed neurons are zeroed; with alpha
given they are scaled by it. Applies only inside this expert's routed
rows, i.e. exclusively at tokens where the router selected the expert
-- the structural-zeros requirement of the issue.
Source code in src/hprobes/moe.py
set_routing_override(positions, experts, weights=None)
Force router decisions at chosen token positions (#42).
experts is (n_positions, k) forced expert indices (same k
as the model's top-k); weights optionally overrides the gates for
those slots (default: keep the sample's own gates). Positions index
the flattened token dimension the experts module receives. Effective
routing (overridden values) is what routing_table() reports.
Source code in src/hprobes/moe.py
MoESketch
dataclass
Incremental per-(layer, expert) activation sketch.
Pure-Python Welford with an ordered pass: seeded bootstrap slices of the captured row list reproduce a full pass bit-for-bit.
Source code in src/hprobes/moe.py
update(layer, expert, activations, gates)
Incorporate one (layer, expert) batch: activations (T, d), gates (T,).
Source code in src/hprobes/moe.py
MoESparseDataset
Legacy two-stage feature selection and sparse row assembly for MoE probes.
.. deprecated::
This path is not used by :func:fit_moe_probe; new code should use
_design_from_features. Its score semantics differ from
_design_from_features (notably mean_abs here is the active-row
mean) and are kept only for backward compatibility.
Stage 1: per-expert neuron candidates, ranked within each expert by the
chosen score (this legacy path: variance or active-row mean |activation|),
floored by n_active >= min_active to drop statistically-starved experts.
Stage 2: global top-k across all (layer, expert, neuron) candidates.
Rows are then assembled sparse: a token contributes values only for its
active experts' selected neurons; everything else is a structural zero.
Source code in src/hprobes/moe.py
522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 | |
assemble_rows()
Sparse per-token rows over the resolved features (single forward pass).
For every token, a feature fires only where its expert was selected;
the value is gate x activation (gate_weighted) or the raw
activation. Returns a CSR-style bundle: dense rows for tests,
plus CSR arrays for scalable consumers.
Source code in src/hprobes/moe.py
resolve_features()
Two-stage selection over all captures; returns the chosen features.
Source code in src/hprobes/moe.py
SharedExpertCapture
Read-only capture of an always-on (shared) expert's activation.
MoE blocks with a dense shared expert (Qwen2Moe / Qwen3.5-style) apply it
to every token, so unlike routed experts there is no routing decision to
replay: the module's own forward runs untouched and we only observe it.
Hooks mlp.shared_expert.down_proj (input = pre-down_proj activation)
and, when present, mlp.shared_expert_gate (output -> sigmoid gate).
Source code in src/hprobes/moe.py
decision_feature(pos)
(tokens, acts, gates) for one token position, or None.
Source code in src/hprobes/moe.py
fit_moe_probe(artifact, l1_C=1.0, validation_split=0.2, seed=42, fusion='concat', routing_only=False, stability=False, stability_runs=5, stability_n_jobs=None)
Fit a probe on decision-token MoE features (#41).
routing_only fits the routing control instead (features = per-layer
routed-expert indicators). fusion="concat" in the default neuron-only
mode appends the routing columns so the probe can use both; the separate
routing-only result is returned alongside by the caller.
stability=True adds a full-pipeline bootstrap (#72): each replicate
resamples samples, rebuilds the design, refits L1, and records the named
selected features. stability_n_jobs uses the dense resolver.
top_k=0 in capture_meta keeps all candidates (no global cap),
matching the dense path's "0 = all features" convention.
Source code in src/hprobes/moe.py
moe_col_norms(model, layers)
Per-expert column norms ||w_down^(l,e)[:, j]|| for routed experts.
Mirrors cett.precompute_col_norms for the stacked-expert layout:
down_proj has shape (num_experts, d_model, intermediate).