Distributed Alignment Search (DAS): Searching for Linearly Encoded Concepts in Model Representations¶
Imagine we want to edit a model to think that Paris is in the country of Brazil, without changing whatever else the model knows about Paris (e.g., its language, continent, ...). Which representations in the model encode this fact about Paris?
In this tutorial, we'll go over Distributed Alignment Search, or DAS, which helps us automatically identify a set of linear subspaces in a model's representations that encode a particular concept.
Note
You can follow along on this Colab notebook.
Before you start. Two things make this tutorial easier to follow:
- Activation patching, which DAS builds directly on.
- Gradients in nnsight, since DAS trains its intervention by backpropagating through the model.
import plotly.io as pio
from IPython.display import clear_output
try:
import google.colab
is_colab = True
except ImportError:
is_colab = False
if is_colab:
pio.renderers.default = "colab"
!pip install -U nnsight
else:
pio.renderers.default = "plotly_mimetype+notebook_connected+notebook"
clear_output()
Note
In this tutorial, we use the Llama-3.2 1B model. Before starting the tutorial, please go to the model's huggingface page and request permission to use the model. Then, log in to this notebook with your huggingface access token.
# Authenticate with Hugging Face to download gated models like Llama.
# In a notebook you can instead run `from huggingface_hub import notebook_login; notebook_login()`.
from huggingface_hub import get_token, login
if get_token() is None:
login() # paste your Hugging Face token when prompted
/home/localjadenfk/miniconda3/envs/ndif2/lib/python3.12/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html from .autonotebook import tqdm as notebook_tqdm
# (try to) set seeds for reproducibility
import random
import torch
random.seed(12)
torch.manual_seed(12)
torch.cuda.manual_seed(12)
Making surgical edits - residual streams capture too much information¶
When we ask a language model questions about the city of Paris, it seems to know the city's country, its continent, and its language. Yet where are these properties of Paris stored?
One way to start investigating this is activation patching. When we patch the residual stream of the 8th layer's activation for the Paris token, we change its country from France to Brazil.

# load model
import torch
from nnsight import TransformersModel
from IPython.display import clear_output
# We load in float32: DAS trains a rotation matrix by backpropagating through the
# model's forward pass, and keeping activations in full precision makes that
# optimization well behaved (the frozen model weights easily fit in memory at this size).
model = TransformersModel(
"meta-llama/Llama-3.2-1B",
device_map="auto",
dispatch=True,
dtype=torch.float32,
)
clear_output()
# base run - does our model know where Paris is?
import torch
base_prompt = "Paris is in the country of"
# get logits from the model's output
with torch.no_grad():
with model.trace(base_prompt) as tracer:
base_logits = model.output.logits[:, -1, :].save()
# apply softmax to convert logits to probability distribution over tokens
base_probs = torch.softmax(base_logits, dim=-1)
top_completions = torch.topk(base_probs, 3, sorted=True)
for v, i in zip(top_completions.values[0], top_completions.indices[0]):
print(f'{model.tokenizer.decode(i.item())} ({v.item():.2f})')
[transformers] Ignoring clean_up_tokenization_spaces=True for BPE tokenizer TokenizersBackend. The clean_up_tokenization post-processing step is designed for WordPiece tokenizers and is destructive for BPE (it strips spaces before punctuation). Set clean_up_tokenization_spaces=False to suppress this warning, or set clean_up_tokenization_spaces_for_bpe_even_though_it_will_corrupt_output=True to force cleanup anyway.
France (0.65) the (0.05) love (0.01)
# source run - collect representations for a city from a different country
source_prompt = "Rio is in the country of"
source_country = model.tokenizer(" Brazil")["input_ids"][1] # includes a space
source_hidden_states = []
with torch.no_grad():
with model.trace(source_prompt) as tracer:
# a decoder layer's `.output` is the residual-stream hidden state
# (shape [batch, seq, hidden]); save one tensor per layer.
for layer in model.model.layers:
source_hidden_states.append(layer.output.save())
# patched run - by patching at layer 8 over Paris, we change its country from France to Brazil!
TOKEN_INDEX = 1
LAYER_INDEX = 8
with model.trace(base_prompt) as tracer:
# apply the same patch we did before
model.model.layers[LAYER_INDEX].output[:, TOKEN_INDEX, :] = source_hidden_states[LAYER_INDEX][:, TOKEN_INDEX, :]
patched_logits = model.output.logits[:, -1, :].save()
patched_probs = torch.softmax(patched_logits, dim=-1)
top_completions = torch.topk(patched_probs, 3, sorted=True)
for v, i in zip(top_completions.values[0], top_completions.indices[0]):
print(f'{model.tokenizer.decode(i.item())} ({v.item():.2f})')
Brazil (0.61) the (0.05) Portugal (0.01)
However, we also accidentally edit other facts about Paris, such as its continent and language!
# by changing Paris's country, we also changed its continent!
TOKEN_INDEX = 1
LAYER_INDEX = 8
new_base_prompt = "Paris is in the continent of"
with model.trace(new_base_prompt) as tracer:
# apply the same patch we did before
model.model.layers[LAYER_INDEX].output[:, TOKEN_INDEX, :] = \
source_hidden_states[LAYER_INDEX][:, TOKEN_INDEX, :]
patched_logits = model.output.logits[:, -1, :].save()
patched_probs = torch.softmax(patched_logits, dim=-1)
top_completions = torch.topk(patched_probs, 3, sorted=True)
for v, i in zip(top_completions.values[0], top_completions.indices[0]):
print(f'{model.tokenizer.decode(i.item())} ({v.item():.2f})')
South (0.55) America (0.11) North (0.10)
# as well as its language!
new_base_prompt = "Paris is a city whose main language is"
with model.trace(new_base_prompt) as tracer:
# apply the same patch we did before
model.model.layers[LAYER_INDEX].output[:, TOKEN_INDEX, :] = \
source_hidden_states[LAYER_INDEX][:, TOKEN_INDEX, :]
patched_logits = model.output.logits[:, -1, :].save()
patched_probs = torch.softmax(patched_logits, dim=-1)
top_completions = torch.topk(patched_probs, 3, sorted=True)
for v, i in zip(top_completions.values[0], top_completions.indices[0]):
print(f'{model.tokenizer.decode(i.item())} ({v.item():.2f})')
Portuguese (0.57) Spanish (0.12) English (0.10)
Takeaway. The patch needs to be more precise, which means patching a unit of computation smaller than the whole residual stream. There are several reasonable choices, such as sets of neurons. This tutorial uses linear subspaces.
The example comes from RAVEL, a benchmark that measures whether interpretability methods can localize a specific concept (a city's country as against its language, say) inside a model's activations. The paper and dataset carry a full analysis of where current methods fall short.
Choosing the right unit of computation - how do models represent concepts?¶
What are we patching to begin with? Let's take a look at the source activations we collected.
source_activations = source_hidden_states[LAYER_INDEX][:, TOKEN_INDEX, :]
source_activations
tensor([[ 0.0111, -0.0206, -0.2613, ..., -0.0281, -0.1300, 0.0346]],
device='cuda:0')
source_activations.shape
torch.Size([1, 2048])
Can we break down the residual stream activation into smaller, meaningful units of computation?
One idea is to look at single neurons - that is, single indices within the large 2048-dimensional vector.
Another idea, motivated by the Linear Representation Hypothesis, is that transformer-based neural networks tend to use linear subspaces as units of computation. Thinking about a model's activation as one giant vector, perhaps concepts are each encoded in a separate linear dimension within the vector.

To patch a set of neurons, we could simply index into the ones we think encode important concepts in the model. However, enumerating all subsets of neurons is computationally infeasible.

# change the list of indices to try a set of neurons to patch!
NEURON_INDICES = [0, 1, 2, 4]
base_prompt = "Paris is in the country of"
with model.trace(base_prompt) as tracer:
# Apply the patch from the source hidden states to the base hidden states
model.model.layers[LAYER_INDEX].output[:, TOKEN_INDEX, NEURON_INDICES] = \
source_hidden_states[LAYER_INDEX][:, TOKEN_INDEX, NEURON_INDICES]
patched_logits = model.output.logits[:, -1, :]
patched_probs = torch.softmax(patched_logits, dim=-1).save()
top_completions = torch.topk(patched_probs, 3, sorted=True)
for v, i in zip(top_completions.values[0], top_completions.indices[0]):
print(f'{model.tokenizer.decode(i.item())} ({v.item():.2f})')
France (0.64) the (0.05) love (0.01)
To patch a set of linear subspaces, we can follow a similar procedure, with a slight twist...
First, we rotate our base and source vectors. This creates two new vectors, whose neurons are linear combinations of the original vector. Next, we patch linear subspaces just as we would in the regular set-up. Lastly, we rotate back the patched vector, so that it's in the same basis as the original run.

# construct a rotation matrix (model_dim x model_dim)
MODEL_HIDDEN_DIM = 2048
def make_rotator(seed=12):
# seeded so that every rotator below starts from the same orthogonal matrix
torch.manual_seed(seed)
rotator = torch.nn.Linear(MODEL_HIDDEN_DIM, MODEL_HIDDEN_DIM, bias=False)
torch.nn.init.orthogonal_(rotator.weight)
return torch.nn.utils.parametrizations.orthogonal(rotator).to(model.device)
rotator = make_rotator()
clear_output()
# play around with how many linear dimensions we patch!
N_PATCHING_DIMS = 1
base_prompt = "Paris is in the country of"
def patch_linear_subspaces(rotator, base_prompt, source_hidden_states, with_grad=False):
grad_env = torch.enable_grad if with_grad else torch.no_grad
with grad_env():
with model.trace(base_prompt) as tracer:
# rotate the base representation
base = model.model.layers[LAYER_INDEX].output[:, TOKEN_INDEX, :].clone()
rotated_base = rotator(base)
# rotate the source representation
source = source_hidden_states[LAYER_INDEX][:, TOKEN_INDEX, :]
rotated_source = rotator(source)
# patch the first n dimensions in the rotated space
# (NOTE: same thing as `rotated_base[:, 0] = rotated_source[:, 0]` but we want the gradient to flow)
rotated_patch = torch.cat([
rotated_source[:, :N_PATCHING_DIMS],
rotated_base[:, N_PATCHING_DIMS:]
], dim=1)
# unrotate patched vector back to the original space
patch = torch.matmul(rotated_patch, rotator.weight.T)
# replace base with patch
model.model.layers[LAYER_INDEX].output[:, TOKEN_INDEX, :] = patch
patched_logits = model.output.logits[:, -1, :].save()
return patched_logits
patched_logits = patch_linear_subspaces(rotator, base_prompt, source_hidden_states, with_grad=False)
patched_probs = torch.softmax(patched_logits, dim=-1)
top_completions = torch.topk(patched_probs, 3, sorted=True)
for v, i in zip(top_completions.values[0], top_completions.indices[0]):
print(f'{model.tokenizer.decode(i.item())} ({v.item():.2f})')
France (0.24) the (0.06) Belgium (0.02)
There is nothing special about a rotation. A model might use a vector's magnitude rather than its direction, and other intermediate transformations could expose other units of computation. Two properties are needed:
- invertible, so the transformation can be undone and the representation returned to its original space
- separable, so concepts don't interfere with each other while transformed
The causal abstraction theory paper covers the rest of their properties and their grounding.
Patching the first few dimensions of an arbitrary rotation left the country alone, so changing the unit of computation from neurons to linear subspaces has not bought us anything by itself. An arbitrary basis is no more likely to line up with the concept than the neuron basis was.
So how do we find the subspaces we care about?
Takeaway. A model representation has several plausible units of computation. Treating it as one large vector, we can patch linear subspaces by first rotating it into a different basis. Which subspaces to patch is what DAS answers.
Enter DAS - automatically finding relevant linear subspaces¶
By rotating the hidden representations of our model, we can patch different linear subspaces. But how can we find the right linear subspace to patch?
We can optimize the rotation itself. Train the rotation matrix so that patching its first dimension makes the model say "Brazil" where it would have said "France", and whatever basis makes that work is the one we get.
# let's train our rotation matrix so that the patch output is Brazil instead of France
from tqdm import trange
rotator = make_rotator()
# optimize only the rotation parameters (the LLM stays frozen).
# Adam's default learning rate of 1e-3 is too large for a 2048 x 2048 orthogonal
# parametrization here: the loss reaches 0.05 by epoch 5 and then bounces back
# above 4. At 1e-4 it falls monotonically.
optimizer = torch.optim.Adam(rotator.parameters(), lr=1e-4)
# use language modeling loss - increase likelihood of outputing Brazil
loss_fn = torch.nn.CrossEntropyLoss()
counterfactual_answer = torch.tensor([model.tokenizer(" Brazil")["input_ids"][1]]).to(model.device)
losses = []
with trange(30) as progress_bar: # train for 30 epochs
for epoch in progress_bar:
optimizer.zero_grad()
# get patched logits using our rotation vector
patched_logits = patch_linear_subspaces(rotator, base_prompt, source_hidden_states, with_grad=True)
# cross entropy loss - make last token be Brazil instead of France
loss = loss_fn(patched_logits, counterfactual_answer)
losses.append(loss.item())
progress_bar.set_postfix({'loss': loss.item()})
loss.backward()
optimizer.step()
print(f'epoch 0 loss {losses[0]:.3f} epoch {len(losses) - 1} loss {losses[-1]:.4f}')
print(f'largest increase between consecutive epochs: '
f'{max(0.0, max(b - a for a, b in zip(losses, losses[1:]))):.4f}')
epoch 0 loss 4.253 epoch 29 loss 0.0003 largest increase between consecutive epochs: 0.0000
The loss falls from 4.25 to under 0.001 and never rises between epochs, so the rotation we end on is the one the optimizer converged to rather than wherever the last step happened to land. Watch for that: at Adam's default learning rate this same objective oscillates, and the final epoch can be worse than epoch 5.
Patching that one rotated dimension from Rio into Paris now changes the country.
base_prompt = "Paris is in the country of"
patched_logits = patch_linear_subspaces(rotator, base_prompt, source_hidden_states, with_grad=False)
patched_probs = torch.softmax(patched_logits, dim=-1)
top_completions = torch.topk(patched_probs, 3, sorted=True)
for v, i in zip(top_completions.values[0], top_completions.indices[0]):
print(f'{model.tokenizer.decode(i.item())} ({v.item():.2f})')
Brazil (1.00) Brasil (0.00) Brazil (0.00)
Does the patch leave the rest of Paris alone?¶
The point of a narrow intervention is that it changes one thing. Checking that means comparing each probe against its unpatched completion, not just looking at the patched one and deciding it seems fine.
def show(label, logits):
probs = torch.softmax(logits, dim=-1)
top = torch.topk(probs, 3, sorted=True)
joined = ' '.join(f'{model.tokenizer.decode(i.item())} ({v.item():.2f})'
for v, i in zip(top.values[0], top.indices[0]))
print(f'{label:16}{joined}')
def collect_source(prompt):
"""One saved residual-stream tensor per layer, for use as a patching donor."""
states = []
with torch.no_grad():
with model.trace(prompt) as tracer:
for layer in model.model.layers:
states.append(layer.output.save())
return states
probes = [
"Paris is in the country of",
"Paris is in the continent of",
"Paris is a city whose main language is",
]
for probe in probes:
with torch.no_grad():
with model.trace(probe) as tracer:
unpatched_logits = model.output.logits[:, -1, :].save()
patched_logits = patch_linear_subspaces(rotator, probe, source_hidden_states, with_grad=False)
print(probe)
show(' unpatched', unpatched_logits)
show(' patched', patched_logits)
print()
Paris is in the country of unpatched France (0.65) the (0.05) love (0.01) patched Brazil (1.00) Brasil (0.00) Brazil (0.00) Paris is in the continent of unpatched Europe (0.80) Africa (0.05) France (0.03) patched Brazil (1.00) Brasil (0.00) Bras (0.00)
Paris is a city whose main language is unpatched French (0.80) English (0.04) the (0.03) patched Portuguese (0.33) Brazil (0.32) the (0.13)
The country changed, and so did everything else. The continent prompt, which the model answers with Europe on its own, now answers Brazil. The language prompt loses French. Trained to convergence on this one example, the subspace is not surgical at all.
That is worth sitting with, because the failure is easy to hide. Stop training early, while the loss is still bouncing, and the same patch leaves Europe and French on top with lower probabilities, which reads like specificity if you never run the unpatched column.
Two controls¶
The subspace was chosen by an optimizer with 2048 x 2048 free parameters and a single training example. Before believing it carries Paris's country, ask what else it can do.
The first control follows from what the patch is supposed to mean. If that dimension transports the donor's country into the base run, then changing the donor should change the answer: patch from Berlin and Paris should land in Germany.
# the rotation was fitted with Rio as the donor. Try other donors in the same frame.
# (all four cities are a single token here, so they occupy the same position)
for source_city in ['Rio', 'Berlin', 'London', 'Toronto']:
source_states = collect_source(f'{source_city} is in the country of')
patched_logits = patch_linear_subspaces(rotator, base_prompt, source_states, with_grad=False)
show(f'from {source_city}', patched_logits)
from Rio Brazil (1.00) Brasil (0.00) Brazil (0.00)
from Berlin Brazil (1.00) Brasil (0.00) Brazil (0.00) from London Brazil (1.00) Brasil (0.00) Brazil (0.00)
from Toronto Brazil (1.00) Brasil (0.00) Brazil (0.00)
Every donor gives Brazil. Berlin, London and Toronto sit in the prompt frame exactly where Rio does, and the dimension ignores all of them. Whatever it carries, it is not the donor's country.
The second control comes at it from the other side. Train the same single dimension, from the same Rio activation, toward a country that has nothing to do with Rio. Then train it from a donor prompt with no city in it at all.
def train_subspace(target, source_states, epochs=30, lr=1e-4):
"""Train one rotated dimension so that the patched run emits `target`."""
trained = make_rotator()
optimizer = torch.optim.Adam(trained.parameters(), lr=lr)
answer = torch.tensor([model.tokenizer(target)["input_ids"][1]]).to(model.device)
for epoch in range(epochs):
optimizer.zero_grad()
logits = patch_linear_subspaces(trained, base_prompt, source_states, with_grad=True)
loss_fn(logits, answer).backward()
optimizer.step()
return trained
# same Rio donor, arbitrary targets
for target in [" Japan", " Norway"]:
trained = train_subspace(target, source_hidden_states)
show(f'-> {target.strip()}', patch_linear_subspaces(trained, base_prompt, source_hidden_states))
# donor prompts with no city in them, target " Brazil"
for donor in ['Gravity', 'Tuesday']:
donor_states = collect_source(f'{donor} is in the country of')
trained = train_subspace(" Brazil", donor_states)
show(f'from {donor}', patch_linear_subspaces(trained, base_prompt, donor_states))
-> Japan Japan (1.00) Japan (0.00) Japanese (0.00)
-> Norway Norway (1.00) Norwegian (0.00) the (0.00)
from Gravity Brazil (1.00) Brasil (0.00) Brazil (0.00)
from Tuesday Brazil (1.00) Brasil (0.00) Brazil (0.00)
All four succeed. The same dimension of the same rotation will make the model say Japan or Norway as readily as Brazil, and it will say Brazil from a donor prompt about gravity.
Put the two controls together and the reading is clear. The optimizer did not find where Paris's country lives. It found a direction that writes an output token, and which token gets written is set by the loss rather than by the donor. This is the standard criticism of an unconstrained DAS: with a free full-rank rotation and enough capacity, "the model represents X here" and "I can make the model say X from here" come apart, and only the second one has been tested.
The nulls are what separate them, and they cost four training runs.
# train the rotation to change one property and leave another alone
rotator_mt = make_rotator()
optimizer = torch.optim.Adam(rotator_mt.parameters(), lr=1e-4)
counterfactual_answer = torch.tensor([model.tokenizer(" Brazil")["input_ids"][1]]).to(model.device)
# we can directly specify things we want to stay the same!
new_base_prompt = "Paris is in the continent of"
new_base_answer = torch.tensor([model.tokenizer(" Europe")["input_ids"][1]]).to(model.device)
with trange(30) as progress_bar:
for epoch in progress_bar:
optimizer.zero_grad()
# get loss for counterfactual behavior (what we want to CHANGE)
patched_logits = patch_linear_subspaces(rotator_mt, base_prompt, source_hidden_states, with_grad=True)
counterfactual_loss = loss_fn(patched_logits, counterfactual_answer)
# get loss for base behavior (what we want to STAY THE SAME)
patched_logits = patch_linear_subspaces(rotator_mt, new_base_prompt, source_hidden_states, with_grad=True)
new_base_loss = loss_fn(patched_logits, new_base_answer)
# can add more examples of base behavior to keep the same if we want!
# ...
# add up all losses together
loss = counterfactual_loss + new_base_loss
progress_bar.set_postfix({'change': counterfactual_loss.item(), 'keep': new_base_loss.item()})
loss.backward()
optimizer.step()
Now run the same three probes against the multi-task rotation.
for probe in probes:
patched_logits = patch_linear_subspaces(rotator_mt, probe, source_hidden_states, with_grad=False)
print(probe)
show(' patched', patched_logits)
# does the multi-task rotation read the donor any better?
print()
for source_city in ['Rio', 'Berlin', 'Toronto']:
source_states = collect_source(f'{source_city} is in the country of')
show(f'from {source_city}', patch_linear_subspaces(rotator_mt, base_prompt, source_states))
Paris is in the country of patched Brazil (1.00) Brazil (0.00) Brasil (0.00) Paris is in the continent of patched Europe (1.00) Europe (0.00) European (0.00) Paris is a city whose main language is patched Spanish (0.30) English (0.20) Italian (0.11) from Rio Brazil (1.00) Brazil (0.00) Brasil (0.00) from Berlin Brazil (1.00) Brazil (0.00) Brasil (0.00)
from Toronto Brazil (1.00) Brazil (0.00) Brasil (0.00)
The country moves to Brazil and the continent stays Europe, both at 1.00. The language prompt still breaks, and it was never in the objective. That is the shape of a multi-task DAS: it preserves what you name and nothing else, so the list of preserved properties is a claim you write down and check rather than something the method hands you.
The donor test still fails, though. Berlin and Toronto still give Brazil. A preservation term narrowed what the intervention damages; it did not make the dimension read its source. Getting that would need the counterfactual term itself to vary the donor, which is what RAVEL does with many entities and many properties and a different source per example. One base prompt and one donor cannot separate a direction that transports a variable from a direction that writes a token, however many preservation terms sit beside it.
Wrapping up¶
DAS turns a coarse intervention, "overwrite the whole residual stream", into a learned one: a single rotated dimension, optimized to carry a city's country. The nnsight ingredient that makes it possible is that gradients flow through the tracing context, so an ordinary loss.backward() / optimizer.step() loop can train a module (rotator) that lives inside the model's forward pass while the model's own weights stay frozen. For a standalone look at that mechanism, see the Gradients feature guide.
The other half of the tutorial is the part that is easy to skip. A trained intervention will always succeed at the thing it was trained on, so the evidence that it found a representation is in the controls: the unpatched baseline, a swapped donor, and an arbitrary target the same subspace should not have been able to reach.
Where to go next:
- Activation Patching, the coarse-grained intervention DAS refines.
- Causal Mediation Analysis II, locating where a fact lives before deciding how to edit it.
- The RAVEL benchmark, which measures how cleanly methods like DAS isolate one concept from another.
- The nnsight API reference for the tracing and intervention primitives used here.