|
| 1 | +"""Score every legal (inp, out) Block pairing using data-driven activation response. |
| 2 | +
|
| 3 | +Attempts |
| 4 | +-------- |
| 5 | +v1 — Mean residual magnitude (SUPERSEDED, see commented block below) |
| 6 | + score = mean_i ||W_out · relu(W_inp · x_i + b_inp) + b_out||_2 |
| 7 | + Result: std=0.33, gap-to-2nd=0.02 — the bias term dominates ||R||_2 regardless |
| 8 | + of H, giving poor within-row discrimination (only 6/48 assignments at row min). |
| 9 | +
|
| 10 | +v2 — Pearson correlation between mean activation pattern and column attention (CURRENT) |
| 11 | + For a trained (inp, out) pair: |
| 12 | + - inp uses a specific subset of the 96 hidden neurons on real data |
| 13 | + → measured by mean_act[inp][k] = E[relu(W_inp[k,:] · x + b_inp[k])] |
| 14 | + - out has been trained to attend to exactly those neurons |
| 15 | + → measured by col_norm[out][k] = ||W_out[:, k]||_2 |
| 16 | +
|
| 17 | + Pearson correlation(mean_act[inp], col_norm[out]) should be strongly positive |
| 18 | + for trained pairs and near-zero for random ones. |
| 19 | +
|
| 20 | + score = 1 - pearson_r (lower = better, consistent with Hungarian minimization) |
| 21 | +
|
| 22 | + Bias terms are irrelevant: mean_act uses only the inp bias inside ReLU (shifts the |
| 23 | + active set, which is part of the signal), and col_norm ignores b_out entirely. |
| 24 | +""" |
| 25 | +import io |
| 26 | +import logging |
| 27 | +import numpy as np |
| 28 | +import pandas as pd |
| 29 | +import torch |
| 30 | +from flowthru import step |
| 31 | + |
| 32 | +logger = logging.getLogger(__name__) |
| 33 | + |
| 34 | + |
| 35 | +@step( |
| 36 | + inputs=["PieceMetadata", "PieceBlob", "BlockCandidate", "MeasurementSchema"], |
| 37 | + outputs=["PairingScore"], |
| 38 | +) |
| 39 | +def compute_activation_scores( |
| 40 | + piece_metadata: pd.DataFrame, |
| 41 | + pieces: pd.DataFrame, |
| 42 | + legal_pairings: pd.DataFrame, |
| 43 | + historical_data: pd.DataFrame, |
| 44 | +) -> pd.DataFrame: |
| 45 | + """Score each legal (inp, out) pairing by activation-pattern / attention alignment. |
| 46 | +
|
| 47 | + Uses Pearson correlation between: |
| 48 | + - mean_act[inp]: which of the 96 hidden neurons inp activates most strongly on data |
| 49 | + - col_norm[out]: which of the 96 hidden neurons out pays most attention to |
| 50 | +
|
| 51 | + A trained pair has high positive correlation; mismatched pairs are near zero. |
| 52 | + score = 1 - pearson_r (lower = better for Hungarian minimization). |
| 53 | +
|
| 54 | + Args: |
| 55 | + piece_metadata: Structural metadata for all pieces (LayerType, dims). |
| 56 | + pieces: Raw byte blobs indexed by PieceIndex. |
| 57 | + legal_pairings: Dimension-valid (InpPieceIndex, OutPieceIndex) candidates. |
| 58 | + historical_data: Sensor measurements used to probe inp activation patterns. |
| 59 | +
|
| 60 | + Returns: |
| 61 | + DataFrame with [InpPieceIndex, OutPieceIndex, CoherenceScore]. |
| 62 | + Lower CoherenceScore indicates a more likely trained pair. |
| 63 | + """ |
| 64 | + blob_by_index: dict[int, bytes] = { |
| 65 | + int(r["PieceIndex"]): r["Data"] for _, r in pieces.iterrows() |
| 66 | + } |
| 67 | + |
| 68 | + legal_set: set[tuple[int, int]] = set( |
| 69 | + zip( |
| 70 | + legal_pairings["InpPieceIndex"].astype(int), |
| 71 | + legal_pairings["OutPieceIndex"].astype(int), |
| 72 | + ) |
| 73 | + ) |
| 74 | + |
| 75 | + inp_indices = ( |
| 76 | + piece_metadata[piece_metadata["LayerType"] == "BlockInp"]["PieceIndex"] |
| 77 | + .astype(int) |
| 78 | + .tolist() |
| 79 | + ) |
| 80 | + out_indices = ( |
| 81 | + piece_metadata[piece_metadata["LayerType"] == "BlockOut"]["PieceIndex"] |
| 82 | + .astype(int) |
| 83 | + .tolist() |
| 84 | + ) |
| 85 | + |
| 86 | + logger.info( |
| 87 | + f"[compute_activation_scores] {len(inp_indices)} inp × {len(out_indices)} out = " |
| 88 | + f"{len(legal_set)} legal pairs" |
| 89 | + ) |
| 90 | + |
| 91 | + feature_cols = [f"measurement_{i}" for i in range(48)] |
| 92 | + X_t = torch.tensor( |
| 93 | + historical_data[feature_cols].values, dtype=torch.float32 |
| 94 | + ).T # (48, N) |
| 95 | + |
| 96 | + def load_state(piece_idx: int) -> dict[str, torch.Tensor]: |
| 97 | + return torch.load( |
| 98 | + io.BytesIO(blob_by_index[piece_idx]), |
| 99 | + weights_only=True, |
| 100 | + map_location=torch.device("cpu"), |
| 101 | + ) |
| 102 | + |
| 103 | + # ------------------------------------------------------------------ |
| 104 | + # mean_act[inp]: (96,) — average activation of each hidden neuron over the dataset |
| 105 | + # ------------------------------------------------------------------ |
| 106 | + mean_act: dict[int, np.ndarray] = {} |
| 107 | + with torch.no_grad(): |
| 108 | + for inp_idx in inp_indices: |
| 109 | + sd = load_state(inp_idx) |
| 110 | + H = torch.relu(sd["weight"] @ X_t + sd["bias"].unsqueeze(1)) # (96, N) |
| 111 | + mean_act[inp_idx] = H.mean(dim=1).numpy() # (96,) |
| 112 | + |
| 113 | + # ------------------------------------------------------------------ |
| 114 | + # col_norm[out]: (96,) — L2 norm of each column of W_out |
| 115 | + # column k corresponds to how much out "attends to" hidden neuron k |
| 116 | + # ------------------------------------------------------------------ |
| 117 | + col_norm: dict[int, np.ndarray] = {} |
| 118 | + for out_idx in out_indices: |
| 119 | + sd = load_state(out_idx) |
| 120 | + col_norm[out_idx] = np.linalg.norm(sd["weight"].numpy(), axis=0) # (96,) |
| 121 | + |
| 122 | + # ------------------------------------------------------------------ |
| 123 | + # Pearson correlation → score = 1 - r (lower = better) |
| 124 | + # ------------------------------------------------------------------ |
| 125 | + def pearson_r(a: np.ndarray, b: np.ndarray) -> float: |
| 126 | + a_c = a - a.mean() |
| 127 | + b_c = b - b.mean() |
| 128 | + denom = np.linalg.norm(a_c) * np.linalg.norm(b_c) |
| 129 | + return float(np.dot(a_c, b_c) / denom) if denom > 1e-8 else 0.0 |
| 130 | + |
| 131 | + rows = [] |
| 132 | + for inp_idx in inp_indices: |
| 133 | + for out_idx in out_indices: |
| 134 | + if (inp_idx, out_idx) not in legal_set: |
| 135 | + continue |
| 136 | + r = pearson_r(mean_act[inp_idx], col_norm[out_idx]) |
| 137 | + rows.append({ |
| 138 | + "InpPieceIndex": inp_idx, |
| 139 | + "OutPieceIndex": out_idx, |
| 140 | + "CoherenceScore": 1.0 - r, # lower = better alignment |
| 141 | + }) |
| 142 | + |
| 143 | + logger.info(f"[compute_activation_scores] Computed {len(rows)} scores") |
| 144 | + return pd.DataFrame(rows, columns=["InpPieceIndex", "OutPieceIndex", "CoherenceScore"]) |
| 145 | + |
| 146 | + |
| 147 | +# ============================================================================= |
| 148 | +# v1 — SUPERSEDED: mean residual magnitude |
| 149 | +# Bias dominates ||W_out @ H + b_out||_2 regardless of H; poor within-row gaps. |
| 150 | +# ============================================================================= |
| 151 | +# def compute_activation_scores_v1(...): |
| 152 | +# ... |
| 153 | +# for inp_idx in inp_indices: |
| 154 | +# H = inp_activations[inp_idx] |
| 155 | +# for out_idx in out_indices: |
| 156 | +# W_out, b_out = out_params[out_idx] |
| 157 | +# R = W_out @ H + b_out.unsqueeze(1) |
| 158 | +# score = float(torch.norm(R, dim=0).mean()) |
| 159 | +# rows.append({"InpPieceIndex": inp_idx, "OutPieceIndex": out_idx, |
| 160 | +# "CoherenceScore": score}) |
| 161 | + |
0 commit comments