CELL 0 (markdown)
# Setup

Install InterProt, load ESM and SAE

CELL 1 (code)
%%capture
!pip install git+https://github.com/etowahadams/interprot.git

CELL 2 (code)
import csv
import os
import torch
import warnings

import numpy as np
import pandas as pd
import polars as pl

from huggingface_hub import hf_hub_download
from safetensors.torch import load_file
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import GridSearchCV, PredefinedSplit
from sklearn.metrics import accuracy_score
from tqdm import tqdm
from transformers import AutoTokenizer, EsmModel

from interprot.sae_model import SparseAutoencoder
from interprot.utils import get_layer_activations

ESM_DIM = 1280
SAE_DIM = 4096
LAYER = 28

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

# Load ESM model
tokenizer = AutoTokenizer.from_pretrained("facebook/esm2_t33_650M_UR50D")
esm_model = EsmModel.from_pretrained("facebook/esm2_t33_650M_UR50D")
esm_model.to(device)
esm_model.eval()

# Load SAE model
checkpoint_path = hf_hub_download(
    repo_id="liambai/InterProt-ESM2-SAEs",
    filename="esm2_plm1280_l28_sae4096.safetensors"
)
sae_model = SparseAutoencoder(ESM_DIM, SAE_DIM)
sae_model.load_state_dict(load_file(checkpoint_path))
sae_model.to(device)
sae_model.eval()

CELL 3 (markdown)
Load the subcellular localization dataset

CELL 4 (code)
# Download subcellular localization dataset from https://zenodo.org/records/10631963
!gdown https://drive.google.com/uc?id=1BG91Eu80t546q-9wIDxCaSYpzGh4lPHX

data_path = "balanced.csv"
df = pl.read_csv(data_path)
df = df.filter(pl.col("sequence").str.len_chars() <= 1000)

train_df = df.filter(pl.col("set") == "train")
test_df = df.filter(pl.col("set") != "train")

df.head()

CELL 5 (markdown)
Define some helpers for linear classified training, evaluation, and inspection.

CELL 6 (code)
def train_classifier(seq_acts):
    """Trains a linear classifier with a predefined validation split.

    Uses grid search over regularization strengths to find the best classifier.
    """
    X_train = []
    y_train = []
    test_fold = []

    for row in train_df.iter_rows(named=True):
        X_train.append(seq_acts[row['sequence']].cpu().detach().numpy())
        y_train.append(row['target'])
        if row['validation']:
            test_fold.append(0)
        else:
            test_fold.append(-1)

    X_train = np.array(X_train)
    y_train = np.array(y_train)

    classifier = LogisticRegression(multi_class='ovr')
    ps = PredefinedSplit(test_fold=test_fold)
    param_grid = {'C': [0.01, 0.1, 1, 10, 100]}
    grid_search = GridSearchCV(classifier, param_grid, cv=ps, scoring='accuracy')
    grid_search.fit(X_train, y_train)

    best_classifier = grid_search.best_estimator_
    return best_classifier, grid_search.best_params_['C'], grid_search.best_score_


def evaluate_classifier(classifier, seq_acts):
    """Computes the accuracy of the classifier over a test set"""
    X_test = []
    y_test = []
    for row in test_df.iter_rows(named=True):
        X_test.append(seq_acts[row['sequence']].cpu().detach().numpy())
        y_test.append(row['target'])
    X_test = np.array(X_test)
    y_test = np.array(y_test)

    y_pred = classifier.predict(X_test)

    accuracy = accuracy_score(y_test, y_pred)
    return accuracy


def write_sorted_weights(classifier, output_dir):
    """Writes model weights to CSV files in sorted order.

    For multi-class models, writes one CSV per class.
    Each CSV has columns "Index" and "Weight" sorted descending.

    Args:
        output_dir: Directory to write CSV files to
    """
    os.makedirs(output_dir, exist_ok=True)

    for i, class_label in enumerate(classifier.classes_):
        class_label = class_label.replace("/", "_").lower()
        output_file = os.path.join(output_dir, f"class_{class_label}_weights.csv")

        print(f"Class: {class_label}")
        class_weights = classifier.coef_[i]
        sorted_weights = sorted(enumerate(class_weights), key=lambda x: x[1], reverse=True)
        with open(output_file, 'w', newline='') as csvfile:
            writer = csv.writer(csvfile)
            writer.writerow(['Index', 'Weight'])
            for index, weight in sorted_weights:
                writer.writerow([index, weight])

        print(pd.read_csv(output_file).head())

CELL 7 (markdown)
# ESM & SAE Inference

Compute and store mean-pooled embeddings for both ESM and SAE

CELL 8 (code)
seq_esm_acts = {}
seq_sae_acts = {}

for seq_idx, row in tqdm(enumerate(df.iter_rows(named=True)), total=len(df)):
    seq = row['sequence']
    esm_layer_acts = get_layer_activations(
        tokenizer=tokenizer, plm=esm_model, seqs=[seq], layer=LAYER
    )[0][1:-1] # Trim off BoS and EoS tokens

    seq_esm_acts[seq] = torch.mean(esm_layer_acts, axis=0)

    sae_acts = sae_model.get_acts(esm_layer_acts)
    seq_sae_acts[seq] = torch.mean(sae_acts, axis=0)

CELL 9 (markdown)
# Linear classifiers

- Train classifier on ESM embedding (for accuracy comparison)
- Train classifier on SAE embedding
- Inspect and write the weights of the SAE classifier

CELL 10 (code)
with warnings.catch_warnings():
    warnings.simplefilter("ignore")

    print("Training ESM classifier")
    esm_classifier, _, _ = train_classifier(seq_esm_acts)
    esm_accuracy = evaluate_classifier(esm_classifier, seq_esm_acts)
    print(f"ESM accuracy: {esm_accuracy}")

    print("Training SAE classifier")
    sae_classifier, _, _ = train_classifier(seq_sae_acts)
    sae_accuracy = evaluate_classifier(sae_classifier, seq_sae_acts)
    print(f"SAE accuracy: {sae_accuracy}")
    write_sorted_weights(sae_classifier, 'weights')