Use this skill when working with transcoder-based circuit analysis of large language models, including training transcoders, analyzing MLP sublayers, reverse-engineering LLM circuits, and creating feature dashboards for interpretability research.
Installer avec Codex ou Claude Copiez ce prompt, collez-le dans Codex, Claude ou un autre assistant, puis laissez-le vérifier la page du skill et l'installer pour vous.
Une commande directe contourne le prompt de vérification. Examinez la source avant de l'exécuter.
Use this skill when working with transcoder-based circuit analysis of large language models, including training transcoders, analyzing MLP sublayers, reverse-engineering LLM circuits, and creating feature dashboards for interpretability research.
Transcoder Circuits: Reverse-Engineering LLM Circuits with Transcoders
When to Use
Activate this skill when:
Reverse-engineering circuits inside transformer language models (GPT-2, Pythia, etc.)
Training transcoders to decompose MLP sublayers into sparse linear combinations of features
Analyzing interpretable features in LLMs using sparse autoencoders or transcoders
Building feature dashboards or activation visualizations
Performing mechanistic interpretability research on neural networks
Comparing SAE vs. transcoder feature interpretability
Running circuit analysis, replacement contexts, or activation patching
This script installs dependencies and downloads transcoder weights from HuggingFace (pchlenski/gpt2-transcoders).
Manual Installation
pip install -r requirements.txt
Requirements (from requirements.txt)
Key dependencies include:
transformer_lens — for loading and hooking into transformer models
torch — PyTorch
einops
datasets
huggingface_hub
wandb (optional, for training logging)
Core Features
Transcoder Training: Train transcoders on LLM MLP sublayers to decompose activations into sparse interpretable features (sae_training/)
Circuit Analysis: Reverse-engineer fine-grained feature circuits within a model (transcoder_circuits/circuit_analysis.py)
Feature Dashboards: Generate dashboards for exploring transcoder and SAE features (transcoder_circuits/feature_dashboards.py)
Replacement Context: Swap MLP sublayers with transcoder reconstructions during inference (transcoder_circuits/replacement_ctx.py)
Activations Store: Stream tokens and generate/store activations during training (sae_training/activations_store.py)
Geometric Median: Utility for computing geometric median for initialization (sae_training/geom_median/)
SAE/Transcoder Comparison: Evaluation notebooks comparing SAEs and transcoders on Pythia-410M
Usage Examples
Loading a Transcoder and Running Replacement Context
import torch
from transformer_lens import HookedTransformer
from transcoder_circuits.replacement_ctx import TranscoderReplacementContext
# Load GPT-2 small via TransformerLens
model = HookedTransformer.from_pretrained("gpt2")
# Load transcoder weights (downloaded via setup.sh)
transcoder = torch.load("path/to/transcoder_layer_0.pt")
# Use replacement context to patch MLP with transcoderwith TranscoderReplacementContext(model, {0: transcoder}):
tokens = model.to_tokens("Hello, world!")
logits = model(tokens)
Training a Transcoder
python train_transcoder.py
Or programmatically:
from sae_training.config import LanguageModelSAERunnerConfig
from sae_training.train_sae_on_language_model import language_model_sae_runner
cfg = LanguageModelSAERunnerConfig(
model_name="gpt2",
hook_point="blocks.0.hook_mlp_out",
hook_point_layer=0,
d_in=768,
expansion_factor=4,
# ... other config options
)
language_model_sae_runner(cfg)
Circuit Analysis
from transcoder_circuits.circuit_analysis import get_circuit_scores
# Analyze which transcoder features contribute most to a given output
scores = get_circuit_scores(model, transcoders, tokens, metric_fn)
Feature Dashboards
from transcoder_circuits.feature_dashboards import make_feature_dashboard
# Generate a dashboard for a specific transcoder feature
dashboard = make_feature_dashboard(
transcoder=transcoder,
model=model,
feature_idx=42,
dataset=dataset,
)
Key APIs / Models
Models Supported
GPT-2 small (primary, weights available at pchlenski/gpt2-transcoders)
Pythia-410M (used in sweep/comparison experiments)
Core Classes
Class
Module
Description
ActivationsStore
sae_training/activations_store.py
Streams tokens and stores LLM activations for training
RunnerConfig
sae_training/config.py
Base config shared across all training runners
LanguageModelSAERunnerConfig
sae_training/config.py
Config for training transcoders/SAEs on a language model
CacheActivationsRunnerConfig
sae_training/config.py
Config for caching LLM activations to disk
SparseAutoencoder
sae_training/sparse_autoencoder.py
The transcoder/SAE model class
Key Functions
Function
Module
Description
language_model_sae_runner
sae_training/train_sae_on_language_model.py
Main training entry point
get_circuit_scores
transcoder_circuits/circuit_analysis.py
Compute feature circuit attribution scores
make_feature_dashboard
transcoder_circuits/feature_dashboards.py
Generate feature visualization dashboards
Related Tools
Anthropic has open-sourced circuit-tracer, a Python library that builds on the (cross-layer) MLP transcoder formulation to extract feature circuits directly from open-weights models such as Gemma-2-2B and Llama-3.2-1B. Given a prompt, it computes the direct effect of every active transcoder feature, transcoder error node, and input token on every other active feature and output logit, and surfaces the resulting attribution graph through a Neuronpedia-hosted frontend. It pairs naturally with the training and feature-analysis primitives in this skill: train or load transcoders here, then plug them into circuit-tracer's ReplacementModel.from_pretrained to obtain end-to-end circuits.
"""
Launch a transcoder training run.
Args:
cfg: LanguageModelSAERunnerConfig instance
Returns:
Trained SparseAutoencoder (transcoder) object
"""
from
import
print
f"Starting transcoder training:"
print
f" Model: {cfg.model_name}"
print
f" Layer: {cfg.hook_point_layer}"
print
f" Hook point: {cfg.hook_point}"
print
f" d_in: {cfg.d_in}"
print
f" d_hidden: {cfg.d_in * cfg.expansion_factor}"
print
f" Total tokens: {cfg.total_training_tokens:,}"
print
f" Device: {cfg.device}"
print
return
def
evaluate_transcoder
transcoder, model, prompt: str = "The Eiffel Tower is located in"
"""
Quick evaluation: check reconstruction quality on a sample prompt.
Args:
transcoder: Trained SparseAutoencoder object
model: HookedTransformer model
prompt: Sample text to evaluate on
Returns:
dict with evaluation metrics
"""
from
import
if
hasattr
'cfg'
else
0
# Get original MLP activations
f"blocks.{layer}.hook_mlp_out"
1
1
with
2
0
float
0
float
sum
1
"reconstruction_mse"
"feature_sparsity"
"mean_l0"
"n_features"
1
print
"Evaluation metrics:"
for
in
print
f" {k}: {v:.6f}"
return
def
main
"""Main training demonstration."""
print
"="
60
print
"Transcoder Training Example"
print
"="
60
# Build config
print
"\n--- Building Training Config ---"
"gpt2"
0
4
500_000
# Small run for demo
False
print
"\nConfig summary:"
print
f" Hook: {cfg.hook_point}"
print
f" Features: {cfg.d_in * cfg.expansion_factor}"
print
f" LR: {cfg.lr}, L1: {cfg.l1_coefficient}"
# Run training
print
"\n--- Starting Training ---"
try
print
"\nTraining complete!"
# Evaluate
print
"\n--- Evaluating Transcoder ---"
from
import
"gpt2"
eval
except
as
print
f"Training failed: {e}"
print
"\nMake sure you have run: bash setup.sh"
raise
if
"__main__"
f"Transcoder weights not found at {weights_path}.\n"
"Run: bash setup.sh to download from https://huggingface.co/pchlenski/gpt2-transcoders"
print
f"Loaded transcoder from {weights_path}"
return
def
run_with_replacement_context
model, transcoders_by_layer: dict, prompt: str
"""
Run model inference with MLP layers replaced by transcoder reconstructions.
Args:
model: HookedTransformer model
transcoders_by_layer: Dict mapping layer index to transcoder object
e.g., {0: tc_layer0, 1: tc_layer1}
prompt: Input text prompt
Returns:
logits tensor from the patched model
"""
try
from
import
except
raise
"transcoder_circuits not found. Ensure you're in the repo root."
print
f"Tokens shape: {tokens.shape}"
with
print
f"Logits shape: {logits.shape}"
return
def
get_top_predicted_tokens
model, logits: torch.Tensor, k: int = 5
"""
Extract the top-k predicted next tokens from model logits.
Args:
model: HookedTransformer model (used for token decoding)
logits: Output logits tensor of shape (batch, seq, vocab)
k: Number of top tokens to return
Returns:
List of (token_string, probability) tuples
"""
0
1
# shape: (vocab,)
1
for
in
zip
print
f" Token: {repr(token_str):15s} Prob: {prob:.4f}"
return
def
cache_activations_example
model, prompt: str, layer: int = 0
"""
Cache intermediate MLP activations for a given prompt using TransformerLens hooks.
Args:
model: HookedTransformer model
prompt: Input text
layer: Layer index to cache activations from
Returns:
Activation tensor at the specified MLP hook point
"""
f"blocks.{layer}.hook_mlp_out"
# shape: (batch, seq, d_model)
print
f"Cached activations at {hook_point}: shape {activations.shape}"