Skip to content

Routing Analysis

Routing statistics, donor matching, and causal routing interventions for MoE models (issue #42): gate entropy and routing churn between correct/incorrect answers, matched donor/random token swaps, and the CETT × routing overlap cross-check.

hprobes.routing

Routing-pattern analysis for MoE probes (issue #42).

Pure analysis over decision-token routing tables captured by :class:hprobes.moe.MoECapture -- no additional forwards. Compares routing of correct vs incorrect samples on selection frequencies, selected-set overlap (Jaccard), and gate-mass entropy, each guarded by a permutation null over labels. The counterfactual-routing machinery builds on the same captured tables.

cett_routing_overlap(cett_feature_names, stats)

Cross-check CETT-selected experts against routing-flagged experts (#42).

cett_feature_names are the selected feature names from fit_moe's probe (L{layer}:E{expert}:N{neuron}); stats is the routing_stats output. Agreement = routing-flagged experts hosting CETT-selected neurons -- overlap above chance argues routing and neurons capture the same signal; low overlap argues dissociation. Shared-expert features (L{layer}:S:N{neuron}) have no routing analog and are counted separately in n_shared_features.

Source code in src/hprobes/routing.py
def cett_routing_overlap(
    cett_feature_names: Sequence[str], stats: Dict[str, Any]
) -> Dict[str, Any]:
    """Cross-check CETT-selected experts against routing-flagged experts (#42).

    ``cett_feature_names`` are the ``selected`` feature names from
    ``fit_moe``'s probe (``L{layer}:E{expert}:N{neuron}``); ``stats`` is the
    ``routing_stats`` output. Agreement = routing-flagged experts hosting
    CETT-selected neurons -- overlap above chance argues routing and neurons
    capture the same signal; low overlap argues dissociation. Shared-expert
    features (``L{layer}:S:N{neuron}``) have no routing analog and are
    counted separately in ``n_shared_features``.
    """
    cett_experts = set()
    n_shared = 0
    for name in cett_feature_names:
        text = str(name)
        if _is_shared_feature_name(text):
            n_shared += 1
            continue
        parsed = _parse_expert_name(text)
        if parsed is not None:
            cett_experts.add(parsed)
    flagged = set()
    per_layer = []
    for layer_row in stats.get("per_layer", []):
        layer = int(layer_row["layer"])
        layer_flagged = {int(f["expert"]) for f in layer_row.get("top_flagged", [])}
        flagged.update((layer, e) for e in layer_flagged)
        layer_cett = {e for (li, e) in cett_experts if li == layer}
        layer_overlap = layer_cett & layer_flagged
        per_layer.append(
            {
                "layer": layer,
                "n_cett_experts": len(layer_cett),
                "n_routing_flagged": len(layer_flagged),
                "n_overlap": len(layer_overlap),
            }
        )
    overlap = sorted(cett_experts & flagged)
    union = cett_experts | flagged
    return {
        "n_cett_experts": len(cett_experts),
        "n_shared_features": n_shared,
        "n_routing_flagged": len(flagged),
        "overlap": [[li, e] for li, e in overlap],
        "jaccard": len(overlap) / len(union) if union else 0.0,
        "per_layer": per_layer,
    }

dose_rows(own_experts, own_weights, donor_experts, donor_weights, dose)

Replace the first dose routing slots with the donor's (#42 standard 1).

Dose is capped at the row length (top-k). dose >= k is a full routing takeover; dose == 0 is a no-op returning the own row unchanged.

Source code in src/hprobes/routing.py
def dose_rows(
    own_experts: Sequence[int],
    own_weights: Sequence[float],
    donor_experts: Sequence[int],
    donor_weights: Sequence[float],
    dose: int,
) -> tuple:
    """Replace the first ``dose`` routing slots with the donor's (#42 standard 1).

    Dose is capped at the row length (top-k). ``dose >= k`` is a full routing
    takeover; ``dose == 0`` is a no-op returning the own row unchanged.
    """
    k = len(own_experts)
    d = max(0, min(int(dose), k))
    experts = list(donor_experts[:d]) + list(own_experts[d:])
    weights = list(donor_weights[:d]) + list(own_weights[d:])
    return experts, weights

frequency_sampled_experts(usage, dose, k, seed)

dose distinct experts drawn by empirical usage frequency (#42 standard 4-c).

The random control draws from exactly the experts that were ever routed (positive usage), weighted by their usage counts -- frequency-matched by construction. Deterministic for a fixed seed.

Source code in src/hprobes/routing.py
def frequency_sampled_experts(usage: Dict[int, float], dose: int, k: int, seed: int) -> List[int]:
    """``dose`` distinct experts drawn by empirical usage frequency (#42 standard 4-c).

    The random control draws from exactly the experts that were ever routed
    (positive usage), weighted by their usage counts -- frequency-matched by
    construction. Deterministic for a fixed ``seed``.
    """
    import numpy as np  # noqa: PLC0415

    exp_ids = sorted(usage)
    counts = np.array([usage[e] for e in exp_ids], dtype=np.float64)
    total = counts.sum()
    if total <= 0 or dose <= 0:
        return []
    probs = counts / total
    rng = np.random.default_rng(seed)
    d = min(int(dose), len(exp_ids))
    picked = rng.choice(len(exp_ids), size=d, replace=d > len(exp_ids), p=probs)
    return [int(exp_ids[p]) for p in picked]

match_donors(labels, lengths, entropies)

Nearest opposite-label donor per sample (#42 standard 3).

Donor = argmin over samples of the opposite label of (|length diff|, |entropy diff|, index) -- a documented proxy for question difficulty (option count is already fixed per dataset here; extend the key when datasets mix option counts). Samples without any opposite-label candidate are simply absent from the result.

Source code in src/hprobes/routing.py
def match_donors(
    labels: Sequence[int],
    lengths: Sequence[int],
    entropies: Sequence[float],
) -> Dict[int, int]:
    """Nearest opposite-label donor per sample (#42 standard 3).

    Donor = argmin over samples of the opposite label of
    ``(|length diff|, |entropy diff|, index)`` -- a documented proxy for
    question difficulty (option count is already fixed per dataset here;
    extend the key when datasets mix option counts). Samples without any
    opposite-label candidate are simply absent from the result.
    """
    donors: Dict[int, int] = {}
    for i, lab in enumerate(labels):
        best: Optional[int] = None
        best_key = None
        for j, lab_j in enumerate(labels):
            if j == i or lab_j == lab:
                continue
            key = (abs(lengths[j] - lengths[i]), abs(entropies[j] - entropies[i]), j)
            if best_key is None or key < best_key:
                best, best_key = j, key
        if best is not None:
            donors[i] = int(best)
    return donors

routing_stats(routings, labels, gates=None, n_experts=None, n_perm=200, seed=0, top_flagged=10, alpha=0.05)

Compare decision-token routing between correct and incorrect samples.

Parameters

routings : per-sample (n_layers, k) int tensors of selected expert indices (MoECapture.routing_table() at the decision position). labels : 1 = incorrect (hallucination), 0 = correct. gates : optional per-sample (n_layers, k) routing weights. n_experts : population size for the indicator space (default: max index + 1). n_perm : permutation draws for the nulls.

Returns per-layer frequencies, usage deltas with two-sided permutation p-values and flagged experts, within/between-group Jaccard over (layer, expert) pairs, and gate-mass entropy comparison if gates were passed.

Source code in src/hprobes/routing.py
def routing_stats(
    routings: Sequence[torch.Tensor],
    labels: np.ndarray,
    gates: Optional[Sequence[torch.Tensor]] = None,
    n_experts: Optional[int] = None,
    n_perm: int = 200,
    seed: int = 0,
    top_flagged: int = 10,
    alpha: float = 0.05,
) -> Dict[str, Any]:
    """Compare decision-token routing between correct and incorrect samples.

    Parameters
    ----------
    routings : per-sample ``(n_layers, k)`` int tensors of selected expert
        indices (``MoECapture.routing_table()`` at the decision position).
    labels : 1 = incorrect (hallucination), 0 = correct.
    gates : optional per-sample ``(n_layers, k)`` routing weights.
    n_experts : population size for the indicator space (default: max index + 1).
    n_perm : permutation draws for the nulls.

    Returns per-layer frequencies, usage deltas with two-sided permutation
    p-values and flagged experts, within/between-group Jaccard over
    ``(layer, expert)`` pairs, and gate-mass entropy comparison if gates
    were passed.
    """
    rng = np.random.default_rng(seed)
    routing_np = _stack_tables(routings, "routing tables")
    y = np.asarray(labels).astype(bool)
    if y.shape[0] != routing_np.shape[0]:
        raise ValueError("labels length must match the number of samples")
    n_samples, n_layers, k = routing_np.shape
    if n_experts is None:
        n_experts = int(routing_np.max()) + 1

    n1 = int(y.sum())
    n0 = n_samples - n1

    per_layer: List[Dict[str, Any]] = []
    for layer in range(n_layers):
        X = _indicators(routing_np, layer, n_experts)
        delta, p = _delta_and_perm_p(X, y, rng, n_perm)
        freq_incorrect = X[y].sum(axis=0) / n1 if n1 else np.zeros(n_experts)
        freq_correct = X[~y].sum(axis=0) / n0 if n0 else np.zeros(n_experts)
        order = np.argsort(-np.abs(delta))
        flagged = [
            {"expert": int(e), "delta": float(delta[e]), "p": float(p[e])}
            for e in order[:top_flagged]
            if p[e] < alpha
        ]
        per_layer.append(
            {
                "layer": layer,
                "freq_correct": freq_correct.tolist(),
                "freq_incorrect": freq_incorrect.tolist(),
                "usage_delta": delta.tolist(),
                "perm_p_abs_delta": p.tolist(),
                "top_flagged": flagged,
            }
        )

    sets = [
        {(layer, int(e)) for layer in range(n_layers) for e in routing_np[i, layer].tolist()}
        for i in range(n_samples)
    ]
    correct_sets = [s for s, is_inc in zip(sets, y) if not is_inc]
    incorrect_sets = [s for s, is_inc in zip(sets, y) if is_inc]
    jaccard: Dict[str, Optional[float]] = {
        "within_correct": _mean_pairwise_jaccard(correct_sets),
        "within_incorrect": _mean_pairwise_jaccard(incorrect_sets),
        "between": (
            float(np.mean([_jaccard(a, b) for a in correct_sets for b in incorrect_sets]))
            if correct_sets and incorrect_sets
            else None
        ),
    }

    gate_entropy: Optional[Dict[str, Any]] = None
    if gates is not None:
        gates_np = _stack_tables([g.float() for g in gates], "gate tables")
        if gates_np.shape[:2] != routing_np.shape[:2]:
            raise ValueError("gate tables must match routing table shapes")
        h = _mean_gate_entropy(gates_np)
        if n1 and n0:
            delta_h = float(h[y].mean() - h[~y].mean())
            null = np.empty(n_perm)
            for b in range(n_perm):
                perm = rng.permutation(n_samples)
                null[b] = h[perm[:n1]].mean() - h[perm[n1:]].mean()
            p_val = (1 + int((np.abs(null) >= abs(delta_h)).sum())) / (1 + n_perm)
        else:
            delta_h, p_val = 0.0, 1.0
        gate_entropy = {
            "correct": float(h[~y].mean()) if n0 else 0.0,
            "incorrect": float(h[y].mean()) if n1 else 0.0,
            "delta": delta_h,
            "perm_p": p_val,
        }

    return {
        "n_samples": int(n_samples),
        "n_correct": n0,
        "n_incorrect": n1,
        "n_layers": int(n_layers),
        "k": int(k),
        "n_experts": int(n_experts),
        "per_layer": per_layer,
        "jaccard": jaccard,
        "gate_entropy": gate_entropy,
    }