### Print first token dataset example Source: https://github.com/adamkarvonen/saebench/blob/main/sae_bench/evals/sparse_probing/testing_notebooks/testing_gemma.ipynb Prints the first example from the tokenized dataset to inspect its structure. ```python print(token_dataset[0]) ``` -------------------------------- ### Install pre-commit hook Source: https://github.com/adamkarvonen/saebench/blob/main/README.md Installs the pre-commit hook that runs ruff and pyright on each commit. ```bash poetry run pre-commit install ``` -------------------------------- ### Install SAE Bench from repository with constraints Source: https://github.com/adamkarvonen/saebench/blob/main/README.md Stable installation from the repository. Requires Python >= 3.10 and a virtual environment. Uses the constraints.txt file to pin tested dependencies. ```bash git clone https://github.com/adamkarvonen/SAEBench.git cd SAEBench pip install -e . -c constraints.txt ``` -------------------------------- ### Install development dependencies with Poetry Source: https://github.com/adamkarvonen/saebench/blob/main/README.md Installs development dependencies for the project using Poetry. Run this before other development commands. ```bash poetry install ``` -------------------------------- ### Install SAE Bench from PyPI Source: https://github.com/adamkarvonen/saebench/blob/main/README.md Alternative installation from PyPI. May encounter dependency issues as libraries evolve; if so, uncomment fixed versions in pyproject.toml. ```bash pip install sae-bench ``` -------------------------------- ### Upload folder to Hugging Face dataset (commented example) Source: https://github.com/adamkarvonen/saebench/blob/main/sae_bench/sae_bench_utils/misc_notebooks/modify_old_results.ipynb Commented-out example of uploading a local folder to the Hugging Face dataset `adamkarvonen/sae_bench_results` using `HfApi.upload_folder`. Shows the parameters for `folder_path`, `path_in_repo`, `repo_id`, `repo_type`, and `ignore_patterns`. ```python # from huggingface_hub import HfApi # api = HfApi() # api.upload_folder( # folder_path="temp_sae_evals_2", # path_in_repo="", # repo_id="adamkarvonen/sae_bench_results", # repo_type="dataset", # # allow_patterns="*eval_results.json" # ignore_patterns=[".DS_Store"] # ) ``` -------------------------------- ### Setup environment and imports for SAE Bench Source: https://github.com/adamkarvonen/saebench/blob/main/sae_bench_demo.ipynb Imports necessary modules, sets up output folders, selects eval types, and configures the model and device. Note that autointerp must be run as a script, and unlearning requires a model with at least 2B parameters and permission for the WMDP dataset. ```python import os import torch import sae_bench.custom_saes.custom_sae_config as custom_sae_config import sae_bench.custom_saes.relu_sae as relu_sae import sae_bench.custom_saes.run_all_evals_custom_saes as run_all_evals_custom_saes import sae_bench.evals.core.main as core import sae_bench.evals.sparse_probing.main as sparse_probing import sae_bench.sae_bench_utils.general_utils as general_utils from sae_bench.sae_bench_utils.sae_selection_utils import get_saes_from_regex RANDOM_SEED = 42 output_folders = { "absorption": "eval_results/absorption", "autointerp": "eval_results/autointerp", "core": "eval_results/core", "scr": "eval_results/scr", "tpp": "eval_results/tpp", "sparse_probing": "eval_results/sparse_probing", "unlearning": "eval_results/unlearning", } # Note: Unlearning is not recommended for models with < 2B parameters and we recommend an instruct tuned model # Unlearning will also require requesting permission for the WMDP dataset (see unlearning/README.md) # Absorption not recommended for models < 2B parameters # asyncio doesn't like notebooks, so autointerp must be ran using a python script # Select your eval types here. eval_types = [ "absorption", # "autointerp", "core", "scr", "tpp", "sparse_probing", # "unlearning", ] if "autointerp" in eval_types: raise ValueError("autointerp must be ran using a python script") device = general_utils.setup_environment() model_name = "pythia-70m-deduped" llm_batch_size = 512 torch_dtype = torch.float32 # Currently all evals take str_dtype instead of torch_dtype. We did this for serialization purposes, but it was probably a mistake. # For now we will just use the str_dtype. TODO: Fix this str_dtype = torch_dtype.__str__().split(".")[-1] # If evaluating multiple SAEs on the same layer, set save_activations to True # This will require at least 100GB of disk space save_activations = False ``` -------------------------------- ### Install json-schema-to-typescript globally Source: https://github.com/adamkarvonen/saebench/blob/main/sae_bench/evals_outputs_typescript_types/README.md Installs the json-schema-to-typescript tool globally via npm, required for generating Typescript types from JSON schemas. ```bash npm install json-schema-to-typescript --global ``` -------------------------------- ### Run Absorption Evaluation via CLI Source: https://github.com/adamkarvonen/saebench/blob/main/sae_bench/sae_bench_utils/misc_notebooks/eval_template.ipynb Example command to execute the absorption evaluation using specific regex patterns for SAE selection and model configuration. ```bash python evals/absorption/main.py \ --sae_regex_pattern "sae_bench_pythia70m_sweep_standard_ctx128_0712" \ --sae_block_pattern "blocks.4.hook_resid_post__trainer_.*" \ --model_name pythia-70m-deduped \ --output_folder results ``` -------------------------------- ### Map trainer loaders and get all HF repo autoencoders Source: https://github.com/adamkarvonen/saebench/blob/main/sae_bench/sae_bench_utils/misc_notebooks/test_dictionary_learning.ipynb Defines a mapping from trainer names to their corresponding SAE loader functions and implements get_all_hf_repo_autoencoders, which downloads all config.json files from a Hugging Face repo and returns the directory locations of each autoencoder. The function uses snapshot_download with allow_patterns for config files and extracts the relative path after the download location. The example then calls this function on the repo 'adamkarvonen/sae_test' and prints the resulting locations. ```python import os import torch from huggingface_hub import snapshot_download import sae_bench.custom_saes.batch_topk_sae as batch_topk_sae import sae_bench.custom_saes.gated_sae as gated_sae import sae_bench.custom_saes.jumprelu_sae as jumprelu_sae import sae_bench.custom_saes.relu_sae as relu_sae import sae_bench.custom_saes.topk_sae as topk_sae TRAINER_LOADERS = { "StandardTrainer": relu_sae.load_dictionary_learning_relu_sae, "StandardTrainerAprilUpdate": relu_sae.load_dictionary_learning_relu_sae, "PAnnealTrainer": relu_sae.load_dictionary_learning_relu_sae, "TopKTrainer": topk_sae.load_dictionary_learning_topk_sae, "JumpReluTrainer": jumprelu_sae.load_dictionary_learning_jump_relu_sae, "BatchTopKTrainer": batch_topk_sae.load_dictionary_learning_batch_topk_sae, "GatedSAETrainer": gated_sae.load_dictionary_learning_gated_sae, } def get_all_hf_repo_autoencoders( repo_id: str, download_location: str = "downloaded_saes" ) -> list[str]: download_location = os.path.join(download_location, repo_id.replace("/", "_")) config_dir = snapshot_download( repo_id, allow_patterns=["*config.json"], local_dir=download_location, force_download=False, ) configs = [] for root, _, files in os.walk(config_dir): for file in files: if file == "config.json": configs.append(os.path.join(root, file)) repo_locations = [] for config in configs: repo_location = config.split(f"{download_location}/")[1].split("config.json")[0] repo_locations.append(repo_location) return repo_locations repo_id = "adamkarvonen/sae_test" locations = get_all_hf_repo_autoencoders(repo_id) print(locations) ``` -------------------------------- ### Run eval programmatically with SparseProbingSaeProbesEvalConfig Source: https://github.com/adamkarvonen/saebench/blob/main/sae_bench/evals/sparse_probing_sae_probes/README.md Programmatic usage: configure the eval, load a SAE with SAE.from_pretrained, and run the eval with run_eval. The example uses a subset of datasets, custom k values, and enables the LLM baseline. ```python from sae_bench.evals.sparse_probing_sae_probes.eval_config import SparseProbingSaeProbesEvalConfig from sae_bench.evals.sparse_probing_sae_probes.main import run_eval from sae_lens import SAE # Configure the eval config = SparseProbingSaeProbesEvalConfig( model_name="gpt2", dataset_names=["118_us_state_CA", "119_us_state_TX"], # Subset of datasets ks=[1, 2, 5, 10], # Custom k values include_llm_baseline=True, # Compare against LLM residual stream baseline results_path="artifacts/sparse_probing_sae_probes", model_cache_path="cache/models", ) # Load your SAE sae = SAE.from_pretrained("gpt2-small-res-jb", "blocks.4.hook_resid_pre")[0] # Run the eval results = run_eval( config=config, selected_saes=[("my_sae_release", sae)], device="cuda", output_path="eval_results/sparse_probing_sae_probes", ) ``` -------------------------------- ### Get selected SAEs and print Source: https://github.com/adamkarvonen/saebench/blob/main/sae_regex_selection.ipynb Calls `get_saes_from_regex` with the defined patterns and prints the number of selected SAEs along with each release and ID. ```python selected_saes = get_saes_from_regex(sae_regex_pattern, sae_block_pattern) print(f"Selected {len(selected_saes)} SAEs:") for sae_release, sae_id in selected_saes: print(f"{sae_release} - {sae_id}") ``` -------------------------------- ### Run eval from command line Source: https://github.com/adamkarvonen/saebench/blob/main/sae_bench/evals/sparse_probing_sae_probes/README.md Run the sparse probing eval from the command line with a model, SAE regex pattern, and SAE block pattern. The example uses gpt2 and the gpt2-small-res-jb SAE release at blocks.4.hook_resid_pre. ```bash python sae_bench/evals/sparse_probing_sae_probes/main.py \ --model_name gpt2 \ --sae_regex_pattern "gpt2-small-res-jb" \ --sae_block_pattern "blocks.4.hook_resid_pre" ``` -------------------------------- ### Configure eval with dataset subset Source: https://github.com/adamkarvonen/saebench/blob/main/sae_bench/evals/sparse_probing_sae_probes/README.md Configure the eval to run on a subset of datasets by specifying dataset_names. The example includes three US state datasets. ```python config = SparseProbingSaeProbesEvalConfig( model_name="gpt2", dataset_names=["118_us_state_CA", "119_us_state_TX", "120_us_state_NY"], # ... other config ) ``` -------------------------------- ### Load and test a dictionary learning SAE Source: https://github.com/adamkarvonen/saebench/blob/main/sae_bench/sae_bench_utils/misc_notebooks/test_dictionary_learning.ipynb Defines load_dictionary_learning_sae, which selects the appropriate loader from TRAINER_LOADERS based on the location string and returns the loaded SAE. It raises a ValueError if no matching trainer is found. The example then loads an SAE from the first location in the previously obtained list and runs its test_sae method on the specified model. ```python import sae_bench.custom_saes.base_sae as base_sae layer = 3 device = "cuda" if torch.cuda.is_available() else "cpu" dtype = torch.float32 model_name = "EleutherAI/pythia-70m-deduped" def load_dictionary_learning_sae( repo_id: str, location: str, layer: int, model_name, device: str, dtype: torch.dtype ) -> base_sae.BaseSAE: for key, loader in TRAINER_LOADERS.items(): if key in location: sae = loader( repo_id=repo_id, filename=location, layer=layer, model_name=model_name, device=device, dtype=dtype, ) return sae raise ValueError(f"Could not find a loader for {location}") sae = load_dictionary_learning_sae( repo_id, f"{locations[0]}ae.pt", layer, model_name, device, dtype ) sae.test_sae(model_name) ``` -------------------------------- ### Run sparse probing evaluation with SAE Lens Source: https://github.com/adamkarvonen/saebench/blob/main/README.md Run a sparse probing evaluation on a single SAE Bench Pythia-70M SAE. Results are saved to the eval_results/sparse_probing directory. Use regex patterns to select SAE Lens SAEs; see sae_regex_selection.ipynb for more examples. ```bash python -m sae_bench.evals.sparse_probing.main \ --sae_regex_pattern "sae_bench_pythia70m_sweep_standard_ctx128_0712" \ --sae_block_pattern "blocks.4.hook_resid_post__trainer_10" \ --model_name pythia-70m-deduped ``` -------------------------------- ### Run eval with custom k values Source: https://github.com/adamkarvonen/saebench/blob/main/sae_bench/evals/sparse_probing_sae_probes/README.md Run the eval with custom k values by passing the --ks flag. The example uses k values 3, 7, 15, 25, and 50. ```bash python sae_bench/evals/sparse_probing_sae_probes/main.py \ --model_name gpt2 \ --sae_regex_pattern "gpt2-small-res-jb" \ --sae_block_pattern "blocks.4.hook_resid_pre" \ --ks 3 7 15 25 50 ``` -------------------------------- ### Set up evaluation and image paths Source: https://github.com/adamkarvonen/saebench/blob/main/sae_bench/evals/mdl/graphing_mdl.ipynb Sets up directory paths for evaluation results and images, creating the image directory if it does not exist. ```python eval_path = "./evals/mdl" image_path = os.path.join(eval_path, "images") results_path = os.path.join(eval_path, "results") if not os.path.exists(image_path): os.makedirs(image_path) ``` -------------------------------- ### Get and filter multi-label data Source: https://github.com/adamkarvonen/saebench/blob/main/sae_bench/evals/sparse_probing/testing_notebooks/dataset_testing.ipynb Gets multi-label train/test data from provided dataframes, then filters to chosen classes. ```python train_data, test_data = dataset_utils.get_multi_label_train_test_data( train_df, test_df, dataset_name, 4000, 1000, 42, ) chosen_classes = dataset_info.chosen_classes_per_dataset[dataset_name] train_data = dataset_utils.filter_dataset(train_data, chosen_classes) test_data = dataset_utils.filter_dataset(test_data, chosen_classes) ``` -------------------------------- ### prepare_probe_data: balance and batch probe activations Source: https://github.com/adamkarvonen/saebench/blob/main/sae_bench/evals/sparse_probing/testing_notebooks/probe_training.ipynb Prepares balanced probe training data by pairing all positive-class activations with a random sample of negative-class activations, then shuffling and batching them. The optional select_top_k parameter zeroes out features that differ least between classes for k-sparse probing experiments. Requires dataset_info.POSITIVE_CLASS_LABEL and dataset_info.NEGATIVE_CLASS_LABEL to be defined. ```python @jaxtyped(typechecker=beartype) def prepare_probe_data( all_activations: dict[str, Float[torch.Tensor, "num_datapoints d_model"]], class_idx: str, batch_size: int, select_top_k: int | None = None, # experimental feature ) -> tuple[ list[Float[torch.Tensor, "batch_size d_model"]], list[Int[torch.Tensor, "batch_size"]], ]: positive_acts_BD = all_activations[class_idx] device = positive_acts_BD.device num_positive = len(positive_acts_BD) # Collect all negative class activations and labels negative_acts = [] for idx, acts in all_activations.items(): if idx != class_idx: negative_acts.append(acts) negative_acts = torch.cat(negative_acts) # Randomly select num_positive samples from negative class indices = torch.randperm(len(negative_acts))[:num_positive] selected_negative_acts_BD = negative_acts[indices] assert selected_negative_acts_BD.shape == positive_acts_BD.shape # Experimental feature: find the top k features that differ the most between in distribution and out of distribution # zero out the rest. Useful for k-sparse probing experiments. if select_top_k is not None: positive_distribution_D = positive_acts_BD.mean(dim=(0)) negative_distribution_D = negative_acts.mean(dim=(0)) distribution_diff_D = (positive_distribution_D - negative_distribution_D).abs() top_k_indices_D = torch.argsort(distribution_diff_D, descending=True)[ :select_top_k ] mask_D = torch.ones( distribution_diff_D.shape[0], dtype=torch.bool, device=positive_acts_BD.device, ) mask_D[top_k_indices_D] = False masked_positive_acts_BD = positive_acts_BD.clone() masked_negative_acts_BD = selected_negative_acts_BD.clone() masked_positive_acts_BD[:, mask_D] = 0.0 masked_negative_acts_BD[:, mask_D] = 0.0 else: masked_positive_acts_BD = positive_acts_BD masked_negative_acts_BD = selected_negative_acts_BD # Combine positive and negative samples combined_acts = torch.cat([masked_positive_acts_BD, masked_negative_acts_BD]) combined_labels = torch.empty(len(combined_acts), dtype=torch.int, device=device) combined_labels[:num_positive] = dataset_info.POSITIVE_CLASS_LABEL combined_labels[num_positive:] = dataset_info.NEGATIVE_CLASS_LABEL # Shuffle the combined data shuffle_indices = torch.randperm(len(combined_acts)) shuffled_acts = combined_acts[shuffle_indices] shuffled_labels = combined_labels[shuffle_indices] # Reshape into lists of tensors with specified batch_size num_samples = len(shuffled_acts) num_batches = num_samples // batch_size batched_acts = [ shuffled_acts[i * batch_size : (i + 1) * batch_size] for i in range(num_batches) ] batched_labels = [ shuffled_labels[i * batch_size : (i + 1) * batch_size] for i in range(num_batches) ] return batched_acts, batched_labels ``` -------------------------------- ### Set up plotting and torch imports Source: https://github.com/adamkarvonen/saebench/blob/main/sae_bench/evals/sparse_probing/testing_notebooks/testing_gemma.ipynb Imports plotly.express and torch, sets a port for visualization, and disables gradient computation for efficiency. ```python # Standard imports # Imports for displaying vis in Colab / notebook import plotly.express as px import torch PORT = 8000 torch.set_grad_enabled(False) ``` -------------------------------- ### Get multi-label train/test data Source: https://github.com/adamkarvonen/saebench/blob/main/sae_bench/evals/sparse_probing/testing_notebooks/dataset_testing.ipynb Fetches multi-label train and test data from the specified dataset with given sizes and seed. ```python train_data, test_data = dataset_utils.get_multi_label_train_test_data( dataset_name, 4000, 1000, 42 ) ``` -------------------------------- ### Run formatting with make format Source: https://github.com/adamkarvonen/saebench/blob/main/README.md Runs Ruff formatting on the codebase. Use this to automatically format code. ```bash make format ``` -------------------------------- ### Configure result folders and eval type Source: https://github.com/adamkarvonen/saebench/blob/main/graphing.ipynb Sets up result folders and selects the eval type (core or absorption) for graphing. Creates the image output directory if it does not exist. ```python results_folders = [ "./matroyshka_0117", local_dir, ] # eval_type = "sparse_probing" # If we want to graph L0 vs Loss Recovered, we can set the eval type to core eval_type = "core" eval_type = "absorption" eval_folders = [] core_folders = [] for results_folder in results_folders: eval_folders.append(f"{results_folder}/{eval_type}") core_folders.append(f"{results_folder}/core") image_path = "./images" if not os.path.exists(image_path): os.makedirs(image_path) ``` -------------------------------- ### Load pretrained SAE from release Source: https://github.com/adamkarvonen/saebench/blob/main/sae_bench/evals/sparse_probing/testing_notebooks/testing_gemma.ipynb Loads a specific SAE from the 'sae_bench_pythia70m_sweep_topk_ctx128_0730' release using the given SAE ID, and moves it to the selected device. ```python # the cfg dict is returned alongside the SAE since it may contain useful information for analysing the SAE (eg: instantiating an activation store) # Note that this is not the same as the SAEs config dict, rather it is whatever was in the HF repo, from which we can extract the SAE config dict # We also return the feature sparsities which are stored in HF for convenience. sae = SAE.from_pretrained( release="sae_bench_pythia70m_sweep_topk_ctx128_0730", sae_id="blocks.4.hook_resid_post__trainer_10", device=device, ) sae = sae.to(device=device) ``` -------------------------------- ### Generate interactive 3D plot with plot_interactive_3var_graph Source: https://github.com/adamkarvonen/saebench/blob/main/sae_bench/evals/mdl/graphing_mdl.ipynb Generate an interactive 3D HTML plot for the custom metric. Requires plotting_results, custom_metric, title_3var, and image_base_name to be set as in the previous examples. ```python plot_interactive_3var_graph( plotting_results, custom_metric, title=title_3var, output_filename=f"{image_base_name}_3var_interactive.html", ) ``` -------------------------------- ### Select device based on availability Source: https://github.com/adamkarvonen/saebench/blob/main/sae_bench/evals/sparse_probing/testing_notebooks/testing_gemma.ipynb Chooses 'mps' if available, otherwise 'cuda' if available, else 'cpu'. Prints the selected device. ```python if torch.backends.mps.is_available(): device = "mps" else: device = "cuda" if torch.cuda.is_available() else "cpu" print(f"Device: {device}") ``` -------------------------------- ### List dataset keys and inspect structure Source: https://github.com/adamkarvonen/saebench/blob/main/sae_bench/evals/sparse_probing/testing_notebooks/probe_training.ipynb After tokenization, prints the first class key and its sub-keys to confirm required fields like 'input_ids'. ```python first_key = next(iter(train_data.keys())) print(first_key) print(train_data[first_key].keys()) ``` -------------------------------- ### Get meaned SAE activations Source: https://github.com/adamkarvonen/saebench/blob/main/sae_bench/evals/sparse_probing/testing_notebooks/probe_training.ipynb Computes meaned SAE activations over non-masked tokens for each class, processing in batches. Assumes masked tokens are zeroed out. Uses sae.encode and einops reductions. ```python @jaxtyped(typechecker=beartype) @torch.no_grad def get_sae_meaned_activations( all_llm_activations_BLD: dict[ str, Float[torch.Tensor, "batch_size seq_len d_model"] ], sae: SAE, sae_batch_size: int, dtype: torch.dtype, ) -> dict[str, Float[torch.Tensor, "batch_size d_sae"]]: """VERY IMPORTANT NOTE: We assume that the activations have been zeroed out for masked tokens.""" all_sae_activations_BF = {} for class_name in tqdm(all_llm_activations_BLD): all_acts_BLD = all_llm_activations_BLD[class_name] all_acts_BF = [] for i in range(len(all_acts_BLD) // sae_batch_size): acts_BLD = all_acts_BLD[i * sae_batch_size : (i + 1) * sae_batch_size] acts_BLF = sae.encode(acts_BLD) activations_BL = einops.reduce(acts_BLD, "B L D -> B L", "sum") nonzero_acts_BL = (activations_BL != 0.0).to(dtype=dtype) nonzero_acts_B = einops.reduce(nonzero_acts_BL, "B L -> B", "sum") acts_BLF = acts_BLF * nonzero_acts_BL[:, :, None] acts_BF = ( einops.reduce(acts_BLF, "B L F -> B F", "sum") / nonzero_acts_B[:, None] ) acts_BF = acts_BF.to(dtype=dtype) all_acts_BF.append(acts_BF) all_acts_BF = torch.cat(all_acts_BF, dim=0) all_sae_activations_BF[class_name] = all_acts_BF return all_sae_activations_BF ``` -------------------------------- ### Print model structure and submodule guidance Source: https://github.com/adamkarvonen/saebench/blob/main/sae_bench/sae_bench_utils/misc_notebooks/test_submodule.ipynb Prints guidance on locating the correct submodule for activation extraction. It notes that for this model the module is model.gpt_neox.layers[layer_num] and advises checking SAE's L0/MSE to verify the correct submodule. Finally, it prints the full model structure. ```python print("For this model, the module is model.gpt_neox.layers[layer_num]") print("You will have to pattern match and get the appropriate submodule for your model") print("It may be worth checking your SAE's L0 / MSE on the activations to ensure you have the correct submodule") print(model) ``` -------------------------------- ### Run linting with make lint Source: https://github.com/adamkarvonen/saebench/blob/main/README.md Runs Ruff linting on the codebase. Use this to check for linting issues. ```bash make lint ``` -------------------------------- ### Define SAE basic info and custom results dictionaries Source: https://github.com/adamkarvonen/saebench/blob/main/sae_bench/evals/sparse_probing/testing_notebooks/testing_gemma.ipynb Defines example dictionaries for SAE basic evaluation results and custom evaluation results, showing the expected structure for storing sparse probing scores. ```python sae_basic_info = { "pythia70m_sweep_topk_ctx128_0730/resid_post_layer_4/trainer_9": { "sae_config_dictionary_learning": {}, "basic_eval_results": {"l0": 80, "frac_recovered": 0.99}, } } custom_results_dict = { "custom_eval_config": {"dataset": "Bib", "n_inputs": 100}, "custom_eval_results": { "pythia70m_sweep_topk_ctx128_0730/resid_post_layer_4/trainer_9": { "sparse_probing_k_1": 0.55 } }, } ``` -------------------------------- ### Plot correlation scatter with plot_correlation_scatter Source: https://github.com/adamkarvonen/saebench/blob/main/sae_bench/evals/mdl/graphing_mdl.ipynb Plots a scatter plot correlating two sparse probe accuracy metrics with thresholds 50 and 100. The commented line shows a simple example usage with L0 vs fraction recovered. ```python # Simple example usage: # plot_metric_scatter(plotting_results, metric_x="l0", metric_y="frac_recovered", title="L0 vs Fraction Recovered") threshold_x = 50 threshold_y = 100 metric_x = f"sae_top_{threshold_x}_test_accuracy" metric_y = f"sae_top_{threshold_y}_test_accuracy" title = "" x_label = "k=1 Sparse Probe Accuracy" y_label = "k=100 Sparse Probe Accuracy" output_filename = os.path.join( image_path, f"sparse_probing_result_correlation_for_thresholds_{threshold_y}_{threshold_y}.png", ) plot_correlation_scatter( plotting_results, metric_x=metric_x, metric_y=metric_y, title=title, x_label=x_label, y_label=y_label, output_filename=output_filename, ) ``` -------------------------------- ### Load pretrained SAE from HuggingFace Source: https://github.com/adamkarvonen/saebench/blob/main/sae_bench/evals/sparse_probing/testing_notebooks/probe_training.ipynb Loads SAE config, context size, hook layer, and batch size from a 'trainer_10' checkpoint; the returned cfg is separate from SAE.cfg. ```python # the cfg dict is returned alongside the SAE since it may contain useful information for analysing the SAE (eg: instantiating an activation store) # Note that this is not the same as the SAEs config dict, rather it is whatever was in the HF repo, from which we can extract the SAE config dict # We also return the feature sparsities which are stored in HF for convenience. sae = SAE.from_pretrained( release="sae_bench_pythia70m_sweep_topk_ctx128_0730", sae_id="blocks.4.hook_resid_post__trainer_10", device=device, ) print(sae.cfg) context_length = sae.cfg.context_size layer = sae.cfg.hook_layer batch_size = 128 ``` -------------------------------- ### Import json, torch, and graphing_utils Source: https://github.com/adamkarvonen/saebench/blob/main/sae_bench_demo.ipynb Imports json, torch, and graphing_utils for later result processing and plotting. ```python import json import torch import sae_bench.sae_bench_utils.graphing_utils as graphing_utils ``` -------------------------------- ### Output JSON structure Source: https://github.com/adamkarvonen/saebench/blob/main/sae_bench/evals/sparse_probing_sae_probes/README.md Example JSON output structure showing the eval type ID, metrics for LLM and SAE, per-k metrics, and per-dataset details. The output includes hardcoded fields for standard k values and a flexible sae_metrics_by_k dictionary. ```json { "eval_type_id": "sparse_probing_sae_probes", "eval_result_metrics": { "llm": { "llm_test_accuracy": 0.85, "llm_test_auc": 0.92, "llm_test_f1": 0.83 }, "sae": { "sae_top_1_test_accuracy": 0.78, "sae_top_1_test_auc": 0.85, "sae_top_1_test_f1": 0.76, "sae_top_2_test_accuracy": 0.81, ... } }, "sae_metrics_by_k": { "1": {"test_accuracy": 0.78, "test_auc": 0.85, "test_f1": 0.76}, "2": {"test_accuracy": 0.81, "test_auc": 0.87, "test_f1": 0.79}, ... }, "eval_result_details": [ { "dataset_name": "118_us_state_CA", "llm_test_accuracy": 0.90, "sae_top_1_test_accuracy": 0.82, "sae_metrics_by_k": { "1": {"test_accuracy": 0.82, ...}, ... } }, ... ] } ``` -------------------------------- ### Import SAE loading and selection utilities Source: https://github.com/adamkarvonen/saebench/blob/main/sae_bench/sae_bench_utils/misc_notebooks/modify_old_results.ipynb Imports the functions used to load SAE configs from Hugging Face and to select SAEs based on regex patterns. ```python from sae_lens.loading.pretrained_sae_loaders import ( load_sae_config_from_huggingface ) from sae_bench.sae_bench_utils.sae_selection_utils import ( select_saes_multiple_patterns, ) ``` -------------------------------- ### Remove eval_result_unstructured key from JSON files Source: https://github.com/adamkarvonen/saebench/blob/main/sae_bench/sae_bench_utils/misc_notebooks/modify_old_results.ipynb Recursively processes all JSON files under a directory, removing the `eval_result_unstructured` key to reduce file size. Prints each processed file and the total count of modified files. The function is called with the current directory as the starting point. ```python # purpose: remove the llm generations, which is over 99% of the file size import json import os def process_json_files(directory): """Recursively process all JSON files in directory and its subdirectories""" count = 0 for root, _, files in os.walk(directory): for file in files: if file.endswith(".json"): filepath = os.path.join(root, file) try: # Read the JSON file with open(filepath) as f: data = json.load(f) # Remove the key if it exists if "eval_result_unstructured" in data: del data["eval_result_unstructured"] count += 1 # Write back the modified data with open(filepath, "w") as f: json.dump(data, f) print(f"Processed: {filepath}") except Exception as e: print(f"Error processing {filepath}: {str(e)}") return count # Process files starting from the current directory starting_dir = "." files_modified = process_json_files(starting_dir) print(f"\nCompleted! Modified {files_modified} files.") ``` -------------------------------- ### Print activation shapes and create meaned activations Source: https://github.com/adamkarvonen/saebench/blob/main/sae_bench/evals/sparse_probing/testing_notebooks/probe_training.ipynb Shows how to inspect activation shapes and convert batched activation dictionaries to meaned activations using create_meaned_model_activations. Prints the original shape for the first key and the shape after meaned conversion. Requires all_train_acts_BLD and all_test_acts_BLD dictionaries and model_dtype. ```python first_key = next(iter(all_train_acts_BLD.keys())) print(all_train_acts_BLD[first_key].shape) all_train_acts_BD = create_meaned_model_activations(all_train_acts_BLD, model_dtype) all_test_acts_BD = create_meaned_model_activations(all_test_acts_BLD, model_dtype) print(all_train_acts_BD[first_key].shape) ``` -------------------------------- ### Load and filter dataset with streaming Source: https://github.com/adamkarvonen/saebench/blob/main/sae_bench/evals/sparse_probing/testing_notebooks/dataset_testing.ipynb Loads a streaming dataset and filters rows by character length, then initializes a HookedTransformer model. ```python from datasets import load_dataset from transformer_lens import HookedTransformer import sae_bench.sae_bench_utils.dataset_utils as dataset_utils dataset_name = "monology/pile-uncopyrighted" def get_dataset_list_of_strs( dataset_name: str, column_name: str, min_row_chars: int, total_chars: int ) -> list[str]: dataset = load_dataset(dataset_name, split="train", streaming=True) total_chars_so_far = 0 result = [] for row in dataset: if len(row[column_name]) > min_row_chars: result.append(row[column_name]) total_chars_so_far += len(row[column_name]) if total_chars_so_far > total_chars: break return result model = HookedTransformer.from_pretrained_no_processing("pythia-70m-deduped") dataset_list_of_strs = get_dataset_list_of_strs(dataset_name, "text", 100, 10_000_000) ``` -------------------------------- ### Compute unlearning score from metrics DataFrame Source: https://github.com/adamkarvonen/saebench/blob/main/sae_bench/evals/unlearning/example.ipynb Computes an unlearning score by taking the minimum wmdp-bio accuracy across rows where the aggregate side-effect score is at least 0.99; otherwise the score is set to 1. Lower is better, and 1 indicates no unlearning effect. The comment notes that the example rows use large multipliers and none pass the 0.99 side-effect threshold. ```python def get_unlearning_scores(df): # approach: return min of wmdp-bio for all rows where all_side_effects_mcq > 0.99 # set unlearning_effect_mmlu_0_99 = wmdp-bio, if all_side_effect_mcq > 0.99 otherwise 1 df["unlearning_effect_mmlu_0_99"] = df["wmdp-bio"] df.loc[df["all_side_effects_mcq"] < 0.99, "unlearning_effect_mmlu_0_99"] = 1 # return min of unlearning_effect_mmlu_0_99 return df["unlearning_effect_mmlu_0_99"].min() score = get_unlearning_scores(df) print(score) # lower the better. 1 means no unlearning effect # here the examples all use large multipliers, so none of them pass the 0.99 side-effect threshold on MMLU ``` -------------------------------- ### Load and tokenize dataset in one call Source: https://github.com/adamkarvonen/saebench/blob/main/sae_bench/evals/sparse_probing/testing_notebooks/dataset_testing.ipynb Loads and tokenizes a dataset in one step, returning a token tensor. ```python tokens2 = dataset_utils.load_and_tokenize_dataset( dataset_name, 128, 2_000_000, model.tokenizer ) ``` -------------------------------- ### Load HookedTransformer with bfloat16 Source: https://github.com/adamkarvonen/saebench/blob/main/sae_bench/evals/sparse_probing/testing_notebooks/probe_training.ipynb Create the Pythia-70M deduped model in bfloat16 precision on selected device via transformer_lens. ```python from sae_lens import SAE from transformer_lens import HookedTransformer model_dtype = torch.bfloat16 model = HookedTransformer.from_pretrained( "pythia-70m-deduped", device=device, dtype=model_dtype ) ``` -------------------------------- ### Organize JSON files into prefix folders (organize_files_in_folders) Source: https://github.com/adamkarvonen/saebench/blob/main/sae_bench/sae_bench_utils/misc_notebooks/export_results.ipynb Moves JSON files in the current directory into subfolders named after a configured prefix (e.g., 'saebench_pythia-160m-deduped_width-2pow14_date-0108'). Processes a list of folder paths, creating the prefix folders if needed, and raises a ValueError if no matching files are found. Requires the os module (imported elsewhere) and uses shutil.move. ```python import shutil def organize_files_in_folders(folder_paths): # Define the prefixes we're looking for prefixes = [ "saebench_pythia-160m-deduped_width-2pow14_date-0108", # 'sae_bench_gemma-2-2b_vanilla_width-2pow16_date-1109' ] for folder in folder_paths: if not os.path.exists(folder): print(f"Folder {folder} does not exist. Skipping.") continue # Get all json files in the current directory files = [f for f in os.listdir(".") if f.endswith(".json")] if len(files) == 0: print(f"No json files found in {folder}. Skipping.") continue num_files_with_prefix = 0 for prefix in prefixes: num_files_with_prefix += len([f for f in files if f.startswith(prefix)]) if num_files_with_prefix == 0: raise ValueError(f"No files with prefix {prefixes} found in {folder}.") os.chdir(folder) # Change to the target directory print(f"Processing folder: {folder}") # Create folders if they don't exist for prefix in prefixes: if not os.path.exists(prefix): os.makedirs(prefix) # Move files to appropriate folders for file in files: for prefix in prefixes: if file.startswith(prefix): shutil.move(file, os.path.join(prefix, file)) print(f"Moved {file} to {prefix}/") break os.chdir("..") # Return to the original directory if __name__ == "__main__": # List of folders to process folder_paths = [ "absorption", "autointerp", "core", "scr", "sparse_probing", "tpp", "unlearning", ] organize_files_in_folders(folder_paths) ``` -------------------------------- ### Train linear probe on activations with BCEWithLogitsLoss Source: https://github.com/adamkarvonen/saebench/blob/main/sae_bench/evals/sparse_probing/testing_notebooks/probe_training.ipynb Defines a linear probe model and functions to train and evaluate it on activation data. The Probe uses a single linear layer with BCEWithLogitsLoss; test_probe computes overall, class-0, and class-1 accuracies without gradients. train_probe runs AdamW optimization over epochs and returns the trained probe and test accuracy; train_probe_on_activations iterates over professions, prepares data via prepare_probe_data, and collects probes and accuracies. Requires pre-existing train_activations/test_activations dictionaries and prepare_probe_data. ```python class Probe(nn.Module): def __init__(self, activation_dim: int, dtype: torch.dtype): super().__init__() self.net = nn.Linear(activation_dim, 1, bias=True, dtype=dtype) def forward(self, x): return self.net(x).squeeze(-1) def test_probe( input_batches: list[Float[torch.Tensor, "batch_size d_model"]], label_batches: list[Int[torch.Tensor, "batch_size"]], probe: Probe, ) -> float: criterion = nn.BCEWithLogitsLoss() with torch.no_grad(): corrects_0 = [] corrects_1 = [] all_corrects = [] losses = [] for acts_BD, labels_B in zip(input_batches, label_batches): logits_B = probe(acts_BD) preds_B = (logits_B > 0.0).long() correct_B = (preds_B == labels_B).float() all_corrects.append(correct_B) corrects_0.append(correct_B[labels_B == 0]) corrects_1.append(correct_B[labels_B == 1]) loss = criterion(logits_B, labels_B.to(dtype=probe.net.weight.dtype)) losses.append(loss) accuracy_all = torch.cat(all_corrects).mean().item() accuracy_0 = torch.cat(corrects_0).mean().item() if corrects_0 else 0.0 accuracy_1 = torch.cat(corrects_1).mean().item() if corrects_1 else 0.0 loss = torch.stack(losses).mean().item() return accuracy_all def train_probe( train_input_batches: list[Float[torch.Tensor, "batch_size d_model"]], train_label_batches: list[Int[torch.Tensor, "batch_size"]], test_input_batches: list[Float[torch.Tensor, "batch_size d_model"]], test_label_batches: list[Int[torch.Tensor, "batch_size"]], dim: int, epochs: int, device: str, model_dtype: torch.dtype, lr: float, verbose: bool = False, ) -> tuple[Probe, float]: probe = Probe(dim, model_dtype).to(device) optimizer = torch.optim.AdamW(probe.parameters(), lr=lr) criterion = nn.BCEWithLogitsLoss() for epoch in range(epochs): for acts_BD, labels_B in zip(train_input_batches, train_label_batches): logits_B = probe(acts_BD) loss = criterion( logits_B, labels_B.clone().detach().to(device=device, dtype=model_dtype) ) optimizer.zero_grad() loss.backward() optimizer.step() train_accuracy = test_probe(train_input_batches, train_label_batches, probe) test_accuracy = test_probe(test_input_batches, test_label_batches, probe) if epoch == epochs - 1 and verbose: print( f"\nEpoch {epoch + 1}/{epochs} Loss: {loss.item()}, train accuracy: {train_accuracy}, test accuracy: {test_accuracy}\n" ) return probe, test_accuracy def train_probe_on_activations( train_activations: dict[str, Float[torch.Tensor, "num_datapoints d_model"]], test_activations: dict[str, Float[torch.Tensor, "num_datapoints d_model"]], probe_batch_size: int, epochs: int, lr: float, model_dtype: torch.dtype, device: str, select_top_k: int | None = None, ) -> tuple[dict[str, Probe], dict[str, float]]: torch.set_grad_enabled(True) probes, test_accuracies = {}, {} for profession in train_activations.keys(): train_acts, train_labels = prepare_probe_data( train_activations, profession, probe_batch_size, select_top_k ) test_acts, test_labels = prepare_probe_data( test_activations, profession, probe_batch_size, select_top_k ) activation_dim = train_acts[0].shape[1] print(f"activation dim: {activation_dim}") probe, test_accuracy = train_probe( train_acts, train_labels, test_acts, test_labels, epochs=epochs, dim=activation_dim, device=device, model_dtype=model_dtype, lr=lr, verbose=False, ) print(f"Test accuracy for {profession}: {test_accuracy}") probes[profession] = probe test_accuracies[profession] = test_accuracy return probes, test_accuracies ``` -------------------------------- ### Import matplotlib and set paths Source: https://github.com/adamkarvonen/saebench/blob/main/sae_bench/sae_bench_utils/misc_notebooks/blog_post_graphs.ipynb Imports matplotlib and defines local directory and image path variables. ```python import matplotlib.pyplot as plt local_dir = "./graphing_eval_results/" image_path = "./temp_images" ``` -------------------------------- ### Find eval and core result files Source: https://github.com/adamkarvonen/saebench/blob/main/sae_bench_demo.ipynb Builds folder paths for sparse probing and core results, then finds the result files using graphing_utils. Prints the discovered filenames. ```python results_folders = ["./eval_results"] eval_type = "sparse_probing" eval_folders = [] core_folders = [] for results_folder in results_folders: eval_folders.append(f"{results_folder}/{eval_type}") core_folders.append(f"{results_folder}/core") eval_filenames = graphing_utils.find_eval_results_files(eval_folders) core_filenames = graphing_utils.find_eval_results_files(core_folders) print(f"eval_filenames: {eval_filenames}") print(f"core_filenames: {core_filenames}") ``` -------------------------------- ### Run all CI checks with make check-ci Source: https://github.com/adamkarvonen/saebench/blob/main/README.md Runs all CI checks locally: linting, formatting, type checking, and unit tests. Run this before submitting a PR. ```bash make check-ci ``` -------------------------------- ### Configure VSCode for Ruff auto-formatting Source: https://github.com/adamkarvonen/saebench/blob/main/README.md VSCode settings to enable auto-formatting with the Ruff plugin. Add this to your `.vscode/settings.json` file. ```json { "[python]": { "editor.formatOnSave": true, "editor.codeActionsOnSave": { "source.fixAll": "explicit", "source.organizeImports": "explicit" }, "editor.defaultFormatter": "charliermarsh.ruff" } } ``` -------------------------------- ### Create meaned LLM activations Source: https://github.com/adamkarvonen/saebench/blob/main/sae_bench/evals/sparse_probing/testing_notebooks/probe_training.ipynb Computes meaned activations over non-masked tokens for each class. Assumes masked tokens are zeroed out. Uses einops reductions and supports dtype conversion. ```python @jaxtyped(typechecker=beartype) def create_meaned_model_activations( all_llm_activations_BLD: dict[ str, Float[torch.Tensor, "batch_size seq_len d_model"] ], dtype: torch.dtype, ) -> dict[str, Float[torch.Tensor, "batch_size d_model"]]: """VERY IMPORTANT NOTE: We assume that the activations have been zeroed out for masked tokens.""" all_llm_activations_BD = {} for class_name in all_llm_activations_BLD: acts_BLD = all_llm_activations_BLD[class_name] activations_BL = einops.reduce(acts_BLD, "B L D -> B L", "sum") nonzero_acts_BL = (activations_BL != 0.0).to(dtype=dtype) nonzero_acts_B = einops.reduce(nonzero_acts_BL, "B L -> B", "sum") meaned_acts_BD = ( einops.reduce(acts_BLD, "B L D -> B D", "sum") / nonzero_acts_B[:, None] ) all_llm_activations_BD[class_name] = meaned_acts_BD return all_llm_activations_BD ``` -------------------------------- ### Inspect code training data Source: https://github.com/adamkarvonen/saebench/blob/main/sae_bench/evals/sparse_probing/testing_notebooks/dataset_testing.ipynb Prints the keys of the code training data and a sample entry for the 'C' language. ```python print(train_code_data.keys()) print(train_code_data["C"][0]) ``` -------------------------------- ### Print model architecture from config Source: https://github.com/adamkarvonen/saebench/blob/main/sae_bench/sae_bench_utils/misc_notebooks/test_submodule.ipynb Prints the first architecture name from the model's configuration. This helps identify the model type, which is useful for locating the correct submodule for activation extraction. ```python print(model.config.architectures[0]) ``` -------------------------------- ### Import and print SAE releases Source: https://github.com/adamkarvonen/saebench/blob/main/sae_regex_selection.ipynb Imports functions from `sae_bench.sae_bench_utils.sae_selection_utils` and prints all SAE releases and details for 'gpt2-small-res-jb'. ```python from sae_bench.sae_bench_utils.sae_selection_utils import ( get_saes_from_regex, print_all_sae_releases, print_release_details, ) # Callum came up with this format which I like visually. print_all_sae_releases() print_release_details("gpt2-small-res-jb") ```