# Tested with transformers==4.44.2 and PyTorch.
import json
from pathlib import Path
import matplotlib.pyplot as plt
import numpy as np
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
checkpoint = "openai-community/gpt2"
revision = "607a30d783dfa663caf39e06633721c8d4cfcd7e"
tokenizer = AutoTokenizer.from_pretrained(checkpoint, revision=revision, clean_up_tokenization_spaces=False)
model = AutoModelForCausalLM.from_pretrained(checkpoint, revision=revision,
attn_implementation="eager").eval()
model.requires_grad_(False)
torch.set_num_threads(1)Demo: Reading Position from GPT-2
Can we recover where a word appeared from its hidden state alone? We will fit a linear classifier to frozen GPT-2 states and test it on words the classifier never saw during training. GPT-2 uses a learned position table. Later in this notebook we compare that construction with rotary embeddings.
Hold out the words
Use eight words at a time. Include all eight cyclic shifts of each ordering so every word appears equally often in each position. The training and test lists use different words. We supply a leading space on every token, including the first, so its spelling gives away nothing about its position.
train_words = "ant bell book boot bowl cake card coin crow desk door drum duck farm fish fork".split()
test_words = "ball bear bird boat flag frog gift goat hat hill sky lamp leaf moon nest pear".split()
rng = np.random.default_rng(23)
length = 8
def sequences(words, groups):
encoded = [tokenizer.encode(" " + word) for word in words]
assert all(len(ids) == 1 for ids in encoded)
ids = [item[0] for item in encoded]
rows = []
for _ in range(groups):
order = rng.choice(ids, length, replace=False)
rows.extend(np.roll(order, offset) for offset in range(length))
return torch.tensor(np.stack(rows))
train = sequences(train_words, 24)
test = sequences(test_words, 8)
assert set(train.flatten().tolist()).isdisjoint(test.flatten().tolist())Fit a probe at each layer
Give each position its own score and predict the position with the largest score. We fit the scores to one-hot position labels by ridge regression. For a control, repeat the fit using just the token embedding, before adding position. The final checkpoint below is the output after the model’s final normalization.
stages = ["Token only", "Input", "Block 4", "Block 8", "Final"]
def features(ids):
batches = {stage: [] for stage in stages}
for batch in ids.split(16):
states = model.transformer(batch, output_hidden_states=True).hidden_states
layers = [model.transformer.wte(batch), states[0], states[4], states[8], states[-1]]
for name, layer in zip(stages, layers):
batches[name].append(layer.flatten(0, 1).double())
return {name: torch.cat(parts) for name, parts in batches.items()}
train_features, test_features = features(train), features(test)
train_labels = torch.arange(length).repeat(len(train))
test_labels = torch.arange(length).repeat(len(test))
targets = torch.nn.functional.one_hot(train_labels, length).double()
def fit_probe(x, z):
mean = x.mean(0)
x = x - mean
# Ridge regression with an intercept. The labels are balanced.
gram = x.T @ x
ridge = 0.001 * gram.trace() / len(gram)
weights = torch.linalg.solve(gram + ridge * torch.eye(len(gram)), x.T @ (targets - targets.mean(0)))
return ((z - mean) @ weights + targets.mean(0)).argmax(1)
counts = []
for name in stages:
prediction = fit_probe(train_features[name], test_features[name])
matrix = torch.bincount(length * test_labels + prediction, minlength=length**2).reshape(length, length)
counts.append(matrix.tolist())
print(f"{name:>10}: {(prediction == test_labels).double().mean():.1%}")Token only: 12.5%
Input: 88.3%
Block 4: 56.4%
Block 8: 60.9%
Final: 49.2%
Each row collects test tokens from one actual position. Read across the row to see where the probe placed them. Try changing the block or the vocabulary and running the experiment again.
fig, axes = plt.subplots(1, len(stages), figsize=(11, 2.6), layout="constrained")
for axis, name, matrix in zip(axes, stages, counts):
axis.imshow(np.array(matrix) / len(test), cmap="Blues", vmin=0, vmax=1)
axis.set_title(name)
axis.set_xticks([0, 7], [1, 8])
axis.set_yticks([0, 7], [1, 8])
axes[0].set_ylabel("Actual position")
fig.supxlabel("Predicted position")
plt.show()
record = dict(model=checkpoint, revision=revision, stages=stages, counts=counts,
train_sequences=len(train), test_sequences=len(test), positions=length)
Path("position-probe.json").write_text(json.dumps(record) + "\n");
When Do RoPE Scores Form Diagonal Stripes?
RoPE rotates queries and keys by absolute position while making their dot products depend on relative offset. We will compare repeated content with content that changes from position to position.
Each pair of coordinates rotates by position times its frequency. The loop below writes the two-coordinate rotation explicitly.
from pathlib import Path
import numpy as np
import matplotlib.pyplot as plt
style_path = Path("../figure_style.mplstyle")
plt.style.use(str(style_path) if style_path.exists() else
"https://csci145.rtealwitter.com/topics/figure_style.mplstyle")
rng = np.random.default_rng(22)
positions, d = 24, 8
base = 10000.0
theta = base ** (-2 * np.arange(d // 2) / d)Rotating Each Coordinate Pair
def rope(vectors):
rotated = np.empty_like(vectors)
for position in range(len(vectors)):
for pair in range(d // 2):
angle = position * theta[pair]
cosine = np.cos(angle)
sine = np.sin(angle)
x, y = vectors[position, 2 * pair:2 * pair + 2]
rotated[position, 2 * pair] = cosine * x - sine * y
rotated[position, 2 * pair + 1] = sine * x + cosine * y
return rotatedUse one query and key at every position for the first sequence. Draw fresh content at each position for the second.
q = rng.standard_normal(d)
k = rng.standard_normal(d)
Q_repeated = np.tile(q, (positions, 1))
K_repeated = np.tile(k, (positions, 1))
Q_varied = rng.standard_normal((positions, d))
K_varied = rng.standard_normal((positions, d))Question: When Are RoPE Scores Constant along Diagonals?
With repeated content, every pair at the same relative offset starts from the same query and key. With varied content, the offset may match while the vectors do not. Predict which score matrix will show diagonal stripes.
scores_repeated = rope(Q_repeated) @ rope(K_repeated).T / np.sqrt(d)
scores_varied = rope(Q_varied) @ rope(K_varied).T / np.sqrt(d)
vmax = max(np.abs(scores_repeated).max(), np.abs(scores_varied).max())
fig, axes = plt.subplots(1, 2, figsize=(8, 3.5), layout="constrained")
for ax, scores, label in zip(
axes,
[scores_repeated, scores_varied],
["Repeated content", "Position-dependent content"],
):
im = ax.imshow(scores, cmap="RdBu", vmin=-vmax, vmax=vmax)
ax.set_xlabel("Key Position")
ax.set_title(label)
ax.set_ylabel("Query Position")
fig.colorbar(im, ax=axes, fraction=0.045, pad=0.03, label="Attention Score")
plt.show()
A diagonal contains pairs with the same relative offset. Measure how much the scores vary within each diagonal.
for name, scores in [("Repeated content", scores_repeated), ("Varied content", scores_varied)]:
largest_deviation = 0.0
for offset in range(-positions + 1, positions):
diagonal = scores.diagonal(offset)
deviation = np.max(np.abs(diagonal - diagonal.mean()))
largest_deviation = max(largest_deviation, deviation)
print(f"{name}: largest diagonal deviation = {largest_deviation:.2e}")Repeated content: largest diagonal deviation = 6.66e-16
Varied content: largest diagonal deviation = 3.36e+00
Answer. Repeated content produces a Toeplitz score matrix up to floating-point error: each diagonal corresponds to one relative offset. Varying content breaks the visible stripes because every score depends on both content and offset.
RoPE makes the positional part of the comparison depend on the relative offset. With varied content, scores at the same offset can still differ.