|
| 1 | +# %% |
| 2 | +from typing import Any |
| 3 | + |
| 4 | +import matplotlib.pyplot as plt |
| 5 | +import torch |
| 6 | +from muutils.dbg import dbg_auto |
| 7 | +from torch import Tensor |
| 8 | + |
| 9 | +from spd.clustering.activations import ( |
| 10 | + ProcessedActivations, |
| 11 | + component_activations, |
| 12 | + process_activations, |
| 13 | +) |
| 14 | +from spd.clustering.merge import merge_iteration, merge_iteration_ensemble |
| 15 | +from spd.clustering.merge_config import MergeConfig |
| 16 | +from spd.clustering.merge_history import MergeHistory, MergeHistoryEnsemble |
| 17 | +from spd.clustering.merge_sweep import sweep_multiple_parameters |
| 18 | +from spd.clustering.plotting.activations import plot_activations |
| 19 | +from spd.clustering.plotting.merge import ( |
| 20 | + plot_dists_distribution, |
| 21 | + plot_merge_iteration, |
| 22 | +) |
| 23 | +from spd.configs import Config |
| 24 | +from spd.experiments.resid_mlp.resid_mlp_dataset import ResidMLPDataset |
| 25 | +from spd.models.component_model import ComponentModel, SPDRunInfo |
| 26 | +from spd.registry import EXPERIMENT_REGISTRY |
| 27 | +from spd.utils.data_utils import DatasetGeneratedDataLoader |
| 28 | + |
| 29 | +DEVICE: str = "cuda" if torch.cuda.is_available() else "cpu" |
| 30 | + |
| 31 | +# magic autoreload |
| 32 | +# %load_ext autoreload |
| 33 | +# %autoreload 2 |
| 34 | + |
| 35 | +# %% |
| 36 | +# Load model |
| 37 | +# ============================================================ |
| 38 | +_CANONICAL_RUN: str | None = EXPERIMENT_REGISTRY["resid_mlp2"].canonical_run |
| 39 | +assert _CANONICAL_RUN is not None, "No canonical run found for resid_mlp2 experiment" |
| 40 | +SPD_RUN: SPDRunInfo = SPDRunInfo.from_path(_CANONICAL_RUN) |
| 41 | +MODEL: ComponentModel = ComponentModel.from_pretrained(SPD_RUN.checkpoint_path) |
| 42 | +MODEL.to(DEVICE) |
| 43 | +SPD_CONFIG: Config = SPD_RUN.config |
| 44 | + |
| 45 | +# %% |
| 46 | +# Setup dataset and dataloader |
| 47 | +# ============================================================ |
| 48 | +N_SAMPLES: int = 128 |
| 49 | + |
| 50 | +DATASET: ResidMLPDataset = ResidMLPDataset( |
| 51 | + n_features=MODEL.target_model.config.n_features, # pyright: ignore[reportAttributeAccessIssue, reportArgumentType], |
| 52 | + feature_probability=SPD_CONFIG.task_config.feature_probability, # pyright: ignore[reportAttributeAccessIssue] |
| 53 | + device=DEVICE, |
| 54 | + calc_labels=False, |
| 55 | + label_type=None, |
| 56 | + act_fn_name=None, |
| 57 | + label_fn_seed=None, |
| 58 | + label_coeffs=None, |
| 59 | + data_generation_type=SPD_CONFIG.task_config.data_generation_type, # pyright: ignore[reportAttributeAccessIssue] |
| 60 | +) |
| 61 | + |
| 62 | +dbg_auto( |
| 63 | + dict( |
| 64 | + n_features=DATASET.n_features, |
| 65 | + feature_probability=DATASET.feature_probability, |
| 66 | + data_generation_type=DATASET.data_generation_type, |
| 67 | + ) |
| 68 | +) |
| 69 | +DATALOADER = DatasetGeneratedDataLoader(DATASET, batch_size=N_SAMPLES, shuffle=False) |
| 70 | + |
| 71 | +# %% |
| 72 | +# Get component activations |
| 73 | +# ============================================================ |
| 74 | +COMPONENT_ACTS: dict[str, Tensor] = component_activations( |
| 75 | + model=MODEL, |
| 76 | + device=DEVICE, |
| 77 | + dataloader=DATALOADER, |
| 78 | + sigmoid_type="hard", |
| 79 | +) |
| 80 | + |
| 81 | +dbg_auto(COMPONENT_ACTS) |
| 82 | + |
| 83 | +# %% |
| 84 | + |
| 85 | +FILTER_DEAD_THRESHOLD: float = 0.1 |
| 86 | + |
| 87 | +# Process activations |
| 88 | +# ============================================================ |
| 89 | +PROCESSED_ACTIVATIONS: ProcessedActivations = process_activations( |
| 90 | + COMPONENT_ACTS, |
| 91 | + filter_dead_threshold=FILTER_DEAD_THRESHOLD, |
| 92 | + sort_components=False, # Test the new sorting functionality |
| 93 | +) |
| 94 | + |
| 95 | + |
| 96 | +plot_activations( |
| 97 | + processed_activations=PROCESSED_ACTIVATIONS, |
| 98 | + save_pdf=False, |
| 99 | +) |
| 100 | + |
| 101 | +# %% |
| 102 | +# run the merge iteration |
| 103 | +# ============================================================ |
| 104 | + |
| 105 | +MERGE_CFG: MergeConfig = MergeConfig( |
| 106 | + activation_threshold=0.1, |
| 107 | + alpha=1, |
| 108 | + iters=int(PROCESSED_ACTIVATIONS.n_components_alive * 0.9), |
| 109 | + merge_pair_sampling_method="range", |
| 110 | + merge_pair_sampling_kwargs={"threshold": 0.0}, |
| 111 | + pop_component_prob=0, |
| 112 | + filter_dead_threshold=FILTER_DEAD_THRESHOLD, |
| 113 | +) |
| 114 | + |
| 115 | + |
| 116 | +def _plot_func( |
| 117 | + costs: torch.Tensor, |
| 118 | + # merge_history: MergeHistory, |
| 119 | + current_merge: Any, |
| 120 | + current_coact: torch.Tensor, |
| 121 | + # current_act_mask: torch.Tensor, |
| 122 | + i: int, |
| 123 | + # k_groups: int, |
| 124 | + # activation_mask_orig: torch.Tensor, |
| 125 | + component_labels: list[str], |
| 126 | + # sweep_params: dict[str, Any], |
| 127 | + **kwargs: Any, |
| 128 | +) -> None: |
| 129 | + assert kwargs |
| 130 | + if (i % 50 == 0 and i > 0) or i == 1: |
| 131 | + # latest = merge_history.latest() |
| 132 | + # latest['merges'].plot() |
| 133 | + plot_merge_iteration( |
| 134 | + current_merge=current_merge, |
| 135 | + current_coact=current_coact, |
| 136 | + costs=costs, |
| 137 | + iteration=i, |
| 138 | + component_labels=component_labels, |
| 139 | + show=True, # Show the plot interactively |
| 140 | + ) |
| 141 | + |
| 142 | + |
| 143 | +MERGE_HIST: MergeHistory = merge_iteration( |
| 144 | + activations=PROCESSED_ACTIVATIONS.activations, |
| 145 | + merge_config=MERGE_CFG, |
| 146 | + component_labels=PROCESSED_ACTIVATIONS.labels, |
| 147 | + plot_callback=_plot_func, |
| 148 | +) |
| 149 | + |
| 150 | +# %% |
| 151 | +# Plot merge history |
| 152 | +# ============================================================ |
| 153 | + |
| 154 | +# plt.hist(mh[270]["merges"].components_per_group, bins=np.linspace(0, 56, 57)) |
| 155 | +# plt.yscale("log") |
| 156 | +# plt.xscale("log") |
| 157 | + |
| 158 | + |
| 159 | +# %% |
| 160 | +# compute and plot distances in an ensemble |
| 161 | +# ============================================================ |
| 162 | + |
| 163 | +ENSEMBLE: MergeHistoryEnsemble = merge_iteration_ensemble( |
| 164 | + activations=PROCESSED_ACTIVATIONS.activations, |
| 165 | + component_labels=PROCESSED_ACTIVATIONS.labels, |
| 166 | + merge_config=MERGE_CFG, |
| 167 | + ensemble_size=4, |
| 168 | +) |
| 169 | + |
| 170 | +DISTANCES = ENSEMBLE.get_distances(method="perm_invariant_hamming") |
| 171 | + |
| 172 | +plot_dists_distribution( |
| 173 | + distances=DISTANCES, |
| 174 | + mode="points", |
| 175 | + # label="v1" |
| 176 | +) |
| 177 | +plt.legend() |
| 178 | + |
| 179 | + |
| 180 | +# %% |
| 181 | +# do sweeps |
| 182 | +# ============================================================ |
| 183 | + |
| 184 | +SWEEP_RESULTS: dict[str, Any] = sweep_multiple_parameters( |
| 185 | + activations=PROCESSED_ACTIVATIONS.activations, |
| 186 | + parameter_sweeps={ |
| 187 | + "alpha": [1, 5], |
| 188 | + # "check_threshold": [0.0001, 0.001, 0.01, 0.1, 0.5], |
| 189 | + # "pop_component_prob": [0.0001, 0.01, 0.5], |
| 190 | + }, |
| 191 | + base_config=MERGE_CFG.model_dump(mode="json"), # pyright: ignore[reportArgumentType], |
| 192 | + component_labels=PROCESSED_ACTIVATIONS.labels, |
| 193 | + ensemble_size=4, |
| 194 | +) |
| 195 | + |
| 196 | +# Show all plots |
| 197 | +for param_name, (ensembles, fig, ax) in SWEEP_RESULTS.items(): # noqa: B007 |
| 198 | + plt.show() |
0 commit comments