Skip to main content

What Makes The Linear Representation Hypothesis Brittle? Data

author: Brian Muhia

based on: this tutorial from the Technical Safety & Governance Lab

A famous hypothesis among AI researchers in the age of the large language model is that features correspond to directions (phi) \(\phi \in \mathbb{R}^d\) in activation space. The projection \(\phi^\top h_l(x)\) on the residual stream \(h\) of layer \(l\) approximately measures the intensity of that feature for input \(x\), and features combine additvely \(h_l(x) \approx \sum_i {\alpha_i \phi_i }\). This implies features can be detected via linear probes and added or removed via vector arithmetic on the \(h_l(x)\). While this hypothesis can lead to the development of useful probes, “lenses” and steering mechanisms, I want to show here how I accidentally learned that this is a brittle mechanism if the data used to design the probe is not distributed robustly. Lessons learned:

  1. constant vigilance is needed,
  2. look at your data,
  3. create your own data, it may or may not create the “accidents” that break the model
  4. pay attention, observe and notice things
  5. when learning, don’t just copy the code, explore and think about what’s happening.
  6. approximations can break down easily.
# import requirements and load the model into the CUDA GPU
import torch
from transformers import GPT2LMHeadModel, GPT2Tokenizer

# Setup Model and Tokenizer
model_name = "gpt2" # a small 125M parameter language model, can fit in less than 800MB of VRAM
tokenizer = GPT2Tokenizer.from_pretrained(model_name)
model = GPT2LMHeadModel.from_pretrained(model_name)
device = "cuda" if torch.cuda.is_available() else "cpu"
model.to(device)
model.eval()

print(f"Model loaded on {device}")
Model loaded on cuda

1. Extracting Activations

We can define a helper function to extract residual stream activations at a specific layer. For each input text, we retrieve the hidden state of the last token at that layer.

def get_activations(text, layer_idx):
    """Return the residual stream activations of text at a specific layer index."""
    inputs = tokenizer(text, return_tensors="pt").to(device)
    with torch.no_grad():
        outputs = model(**inputs, output_hidden_states=True)
        # Activation shape: (batch, seq_len, hidden_dimension)
        # We want to extract the state at the last token (-1).
        hidden_states = outputs.hidden_states[layer_idx][0,-1,:]
    return hidden_states

2. Computing a Feature Direction

According to the Linear Representation Hypothesis, features correspond to directions \(\phi \in \mathbb R^d\) in activation space. We extract a “sentiment direction” using the Difference in Means method

\[\phi = \frac{1}{|P|}\sum_{x \in P} h_l(x) - \frac{1}{N}\sum_{x \in N} h_l(x) \]

where \(P\) is a set of positive (happy) examples and \(N\) is a set of negative (sad) examples.

# using an earlier layer often works better for steering
layer_to_probe = 5

# Examples
positive_examples = ["I am happy today", "Today was a good day", "We were all smiling", 
                     "What a joy!", "This is exciting!", "I love this"]
negative_examples = ["I am so sad", "Life is terrible", "Feeling down today",
                     "This is awful", "I hate this", "What a disaster"]

# Collect activations for each set
happy_acts = torch.stack([get_activations(x, layer_to_probe) for x in positive_examples])
sad_acts = torch.stack([get_activations(x, layer_to_probe) for x in negative_examples])
# compute difference-in-means
# Feature Direction phi = mean(happy_acts) - mean(sad_acts)
sentiment_direction = (happy_acts.mean(dim=0) - sad_acts.mean(dim=0))
phi = sentiment_direction / torch.norm(sentiment_direction) # Normalize

3. Detection: Linear Probing

If the Linear Representation Hypothesis is true, then we can detect the existence and intensity of a concept by computing a projection \(\phi^\top h_l(x)\). A higher positive value indicates more “happiness” in the activation, while a negative value indicates more “sadness” in the activation. The decision boundary is zero (0).

# Test the projection φᵀ · h
test_prompts = ["That's so cool!", "I feel terrible", "Feeling nice today"]
print("Sentiment Intensity")
print(50 * "-")
for test_prompt in test_prompts:
    h_test = get_activations(test_prompt, layer_to_probe)
    intensity = torch.dot(phi, h_test).item()
    sentiment = "positive" if intensity > 0 else "negative"
    print(f"Test Prompt: {test_prompt}")
    print(f"Intensity: {intensity} -> ({sentiment})")
    print(20 * "-")
Sentiment Intensity
--------------------------------------------------
Test Prompt: That's so cool!
Intensity: 12.03903865814209 -> (positive)
--------------------
Test Prompt: I feel terrible
Intensity: -32.89968490600586 -> (negative)
--------------------
Test Prompt: Feeling nice today
Intensity: -2.602116346359253 -> (negative)
--------------------

The third prompt “Feeling nice today” is classified negative by our probe! This is not what I expected, so I thought for a minute about what could be going on. Maybe the examples used to extract activations had punctuation only in one class, and the probe overfits to that, failing to generalize out of that distribution because one of the positive examples in the test prompt has an exclamation mark. Let’s add a full-stop to the third sentence (positive) to balance it out. Note also that the third sentence’s intensity is closer to the decision boundary (0) than the other negative sentence, so it is more positive than the most negative example while still below the threshold for positive value according to the probe. What is pushing the boundary down into negative space? To test a hypothesis, let’s try changing the data minimally.

# Test the projection φᵀ · h
test_prompts = ["That's so cool!", "I feel terrible", "Feeling nice today."]
print("Sentiment intensity")
print(50 * "-")
for test_prompt in test_prompts:
    h_test = get_activations(test_prompt, layer_to_probe)
    intensity = torch.dot(phi, h_test).item()
    sentiment = "positive" if intensity > 0 else "negative"
    print(f"Test Prompt: {test_prompt}")
    print(f"Intensity: {intensity} -> ({sentiment})")
    print(20 * "-")
Sentiment intensity
--------------------------------------------------
Test Prompt: That's so cool!
Intensity: 12.03903865814209 -> (positive)
--------------------
Test Prompt: I feel terrible
Intensity: -32.89968490600586 -> (negative)
--------------------
Test Prompt: Feeling nice today.
Intensity: 1.8853144645690918 -> (positive)
--------------------

Correct detection after adding a full-stop to the third sentence. Very interesting. But I needed to dig deeper, so I modified the prompts further, swapping only the punctuation between the happy examples and sad examples. I only change two out of six examples.

4. Creating new examples with the punctuation swapped between ‘happy’ and ‘sad’ sentences


happy = ["I am happy today", "Today was a good day", "We were all smiling", 
                     "What a joy", "This is exciting", "I love this"]
sad = ["I am so sad", "Life is terrible", "Feeling down today",
                     "This is awful!", "I hate this", "What a disaster."]

# Collect activations for each set
happy_acts2 = torch.stack([get_activations(x, layer_to_probe) for x in happy])
sad_acts2 = torch.stack([get_activations(x, layer_to_probe) for x in sad])
# compute difference-in-means
# Feature Direction phi = mean(happy_acts) - mean(sad_acts)
sentiment_direction2 = (happy_acts2.mean(dim=0) - sad_acts2.mean(dim=0))
phi2 = sentiment_direction2 / torch.norm(sentiment_direction2) # Normalize
# Test the projection φᵀ · h
test_prompts = ["That's so cool!", "I feel terrible", "Feeling nice today"]
print("Sentiment Intensity")
print(50 * "-")
for test_prompt in test_prompts:
    h_test2 = get_activations(test_prompt, layer_to_probe)
    intensity2 = torch.dot(phi2, h_test2).item()
    sentiment2 = "positive" if intensity2 > 0 else "negative"
    print(f"Test Prompt: {test_prompt}")
    print(f"Intensity: {intensity2} -> ({sentiment2})")
    print(20 * "-")
Sentiment Intensity
--------------------------------------------------
Test Prompt: That's so cool!
Intensity: -16.722721099853516 -> (negative)
--------------------
Test Prompt: I feel terrible
Intensity: -15.254180908203125 -> (negative)
--------------------
Test Prompt: Feeling nice today
Intensity: 0.4732609689235687 -> (positive)
--------------------

The happiest prompt gets classified as even sadder than the most negative prompt. This does not look linear at all. If we swap the puncuations again, it is even worse.

# Test the projection φᵀ · h
test_prompts = ["That's so cool", "I feel terrible!", "Feeling nice today!"]
print("Sentiment Intensity")
print(50 * "-")
for test_prompt in test_prompts:
    h_test2 = get_activations(test_prompt, layer_to_probe)
    intensity2 = torch.dot(phi2, h_test2).item()
    sentiment2 = "positive" if intensity2 > 0 else "negative"
    print(f"Test Prompt: {test_prompt}")
    print(f"Intensity: {intensity2} -> ({sentiment2})")
    print(20 * "-")
Sentiment Intensity
--------------------------------------------------
Test Prompt: That's so cool
Intensity: -1.4703407287597656 -> (negative)
--------------------
Test Prompt: I feel terrible!
Intensity: -20.277606964111328 -> (negative)
--------------------
Test Prompt: Feeling nice today!
Intensity: -15.574231147766113 -> (negative)
--------------------

As you can see in the above examples, the feature direction is very sensitive to the input formatting and distribution. This makes many applications of this kind of detection brittle to data hygiene during the probe’s design. Examples have to be cleanly separable, at the token level, not just the conceptual level, which seems to matter less when the token distribution is highly imbalanced. It also points to how prompt injection and jailbreaking works. By understanding the distribution of data e.g. on the Internet, an attacker (AI-assisted human or AI alone) can come up enough data instances of a particular weird shape that fools the model into saying or doing things it “knows” it shouldn’t, in principle. Certain input data will reduce the effectiveness by which the concept directions that have been trained into it can tell that a specific concept is present.