I want to reverse engineer gpt2-small as far as I can. I want to actually undestand what is going on inside, so I want to avoid introducing further black boxes like training a network on top of it. What can I do to understand the token embedding? Singular value decomposition of the embedding matrix gives some interpretable structure, but it's not good enough to actually understand it, I think this is because it forces the singular directions to be orthogonal to each other while the directions it is most useful to think about will often correlate. There are some approaches that give a sparse representation but those ignore the linear structure in the embedding that is useful for computation. I want to understand that structure, so those approaches also aren't good enough.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
You're absolutely right in your approach — trying to reverse-engineer GPT-2 (or any transformer model) without introducing black boxes is a very powerful and underexplored path. Understanding the token embedding space is a foundational step, and you're also correctly identifying the limitations of common tools like SVD or sparse coding.
Let’s break this down into a roadmap that will help you understand token embeddings and their role in computation inside the network, while avoiding new black boxes:
🔍 Goal: Understand the Token Embedding Space of gpt2-small
We'll focus on:
Structure of the embedding matrix (wte in HuggingFace terminology).
How tokens relate to each other geometrically.
How these relationships interact with the rest of the model (e.g., attention heads, MLPs).
1. 📊 Load and Inspect the Embedding Matrix
Start by loading the model and inspecting the embedding matrix:
python
from transformers import GPT2Tokenizer, GPT2Model
import torch
model = GPT2Model.from_pretrained('gpt2-small')
wte = model.get_input_embeddings().weight # shape: [vocab_size, d_model]
You can also get the tokenizer and map token IDs to strings:
Instead of SVD, look at cosine similarity between token vectors.
python
from sklearn.metrics.pairwise import cosine_similarity
def get_similar_tokens(token, top_k=10):
idx = tokenizer.convert_tokens_to_ids(token)
vec = wte[idx].unsqueeze(0)
sims = cosine_similarity(vec, wte).squeeze()
indices = torch.topk(sims, top_k + 1).indices[1:] # exclude self
return [(vocab[i], sims[i].item()) for i in indices]
get_similar_tokens("king")
This reveals how tokens are related in the embedding space, which may reflect semantic or syntactic relations.
Try "king", "United", "States", "of", "the", "apple", etc.
b. Cluster Tokens by Similarity
Use simple clustering like KMeans or hierarchical clustering to group similar tokens.
python
from sklearn.cluster import KMeans
# Cluster tokens into k groups
kmeans = KMeans(n_clusters=100)
clusters = kmeans.fit_predict(wte.detach().numpy())
# Map clusters back to tokens
clustered_tokens = defaultdict(list)
for i, cluster_id in enumerate(clusters):
clustered_tokens[cluster_id].append(vocab[i])
Now you can explore what kind of tokens fall into the same cluster — maybe numbers, punctuation, verbs, etc.
3. 🔗 Connect Embeddings to Attention Heads
Once you understand the structure of the embedding space, ask:
How do these tokens behave when passed through attention heads?
You can compute attention patterns from early layers to see if certain tokens attend to similar ones.
For example, extract attention weights from layer 0:
python
from transformers import GPT2Tokenizer, GPT2Model
import torch
tokenizer = GPT2Tokenizer.from_pretrained('gpt2-small')
model = GPT2Model.from_pretrained('gpt2-small', output_attentions=True)
inputs = tokenizer("The United States of America", return_tensors="pt")
with torch.no_grad():
outputs = model(**inputs)
attentions = outputs.attentions # list of tensors per layer
layer_0_attention = attentions[0] # shape: [1, n_heads, seq_len, seq_len]
Then visualize how tokens like "United" attend to "States", or "of", etc.
This helps you see whether the attention mechanism picks up on similarities already present in the embedding space.
4. 🔄 Probing Linear Structures
You’re right that SVD forces orthogonality and might obscure meaningful directions.
Instead, try:
a. Manually Defined Directions
Find interpretable directions like:
Gender: "he" - "she"
Tense: "walked" - "walking"
Capitalization: "New York" - "new york"
Project all token embeddings onto these directions:
python
vec_he = wte[tokenizer.convert_tokens_to_ids("he")]
vec_she = wte[tokenizer.convert_tokens_to_ids("she")]
gender_dir = vec_he - vec_she
scores = torch.mv(wte, gender_dir) # project all tokens onto gender direction
top_indices = torch.topk(scores, 10).indices
bottom_indices = torch.topk(-scores, 10).indices
print("Top male-associated:", [vocab[i] for i in top_indices])
print("Top female-associated:", [vocab[i] for i in bottom_indices])
This gives insight into how linear subspaces encode meaning, without assuming orthogonality.
b. Use PCA Locally
Instead of global SVD, try local PCA around subsets of tokens (e.g., just adjectives, or named entities):
python
subset_indices = [i for i, t in enumerate(vocab) if t.startswith("Ġ") and t[1:].lower() in ["united", "states", "america", ...]]
local_embeddings = wte[subset_indices]
U, S, V = torch.pca_lowrank(local_embeddings, q=3)
Now you can interpret the principal components in context.
5. 🧩 Combine with Positional Embeddings
GPT-2 adds positional embeddings to token embeddings. Look at:
You're doing something very valuable and challenging. The goal isn't necessarily to find a single explanation of the embedding space, but rather to build a coherent set of hypotheses about how tokens are represented and how those representations feed into downstream computations.
If you want, I can help guide you step-by-step through a Jupyter notebook-style analysis, or walk through specific parts like attention pattern interpretation or probing linear subspaces.