-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmisha.py
More file actions
168 lines (144 loc) · 4.17 KB
/
misha.py
File metadata and controls
168 lines (144 loc) · 4.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
# %%
import os
import pickle
import re
import sys
from pathlib import Path
from typing import List, Tuple
import datasets
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
import torch
import tqdm
from transformer_lens import HookedTransformer
import main
BATCH_SIZE = 2
# %%
print("Loading model")
device = "cuda" if torch.cuda.is_available() else "cpu"
model = HookedTransformer.from_pretrained(model_name=main.MODEL_ACTIVATIONS, device=device)
model.eval()
# %%
print("Loading dataset")
dataset = datasets.load_dataset("NeelNanda/pile-10k")
dataset_texts = [row["text"] for row in dataset["train"]]
# %%
LAYER_N = 31
NEURON_N = 892
def get_activations(texts: List[str]) -> Tuple[List[float], List[str]]:
tokenization_result = model.tokenizer(texts, return_tensors="pt", padding=True, truncation=True)
tokens = tokenization_result["input_ids"]
attention_mask = tokenization_result["attention_mask"]
out, cache = model.run_with_cache(tokens)
next_tokens = []
activations = []
end_indices = attention_mask.sum(axis=-1) - 1
neuron_activations = cache["post", LAYER_N, "mlp"][:, :, NEURON_N]
for batch_idx in range(len(texts)):
next_tokens.append(model.to_string(out[batch_idx, end_indices[batch_idx], :].argmax(axis=-1).item()))
batch_activations = neuron_activations[batch_idx, : end_indices[batch_idx] + 1]
activations.append(torch.max(batch_activations).item())
# activations.append(batch_activations[-1].item())
return activations, next_tokens
def get_activations_batched(texts: List[str], batch_size: int = 32) -> Tuple[List[float], List[str]]:
activations, next_tokens = [], []
for i in tqdm.tqdm(range(0, len(texts), batch_size)):
batch_activations, batch_next_tokens = get_activations(texts[i : i + batch_size])
activations.extend(batch_activations)
next_tokens.extend(batch_next_tokens)
return activations, next_tokens
# %%
print("Getting activations")
activations, next_tokens = get_activations_batched(dataset_texts, batch_size=BATCH_SIZE)
with open("activations.pickle", "wb") as f:
pickle.dump(activations, f)
with open("next_tokens.pickle", "wb") as f:
pickle.dump(next_tokens, f)
# %%
exit()
# %%
# FRUITS
# %%
fruits = [
"apple",
"banana",
"cherry",
"date",
"elderberry",
"fig",
"grape",
"honeydew",
"ice cream",
"jackfruit",
"kiwi",
"lemon",
"mango",
"nectarine",
"orange",
"pear",
"quince",
"raspberry",
"strawberry",
"tangerine",
"ugli fruit",
"vanilla",
"watermelon",
"xigua",
"yam",
"zucchini",
]
prompts = [
f"In the forest, there is a pineapple tree. You shake the tree, and down falls a pineapple. In the forest, there is a {fruit} tree. You shake the tree, and down falls"
for fruit in fruits
]
activations, next_tokens = get_activations(prompts)
print(activations)
df = pd.DataFrame(
dict(
fruit=fruits,
prompt=prompts,
activation=activations,
next_token=next_tokens,
)
)
df = df.sort_values("activation", ascending=False)
df
# %%
# WIKI
# %%
wiki_sentences = main.get_wiki_sentences()
# %%
aan_regex = re.compile(r"(.*)( an| a)\b")
sentences = []
labels = []
for sentence in wiki_sentences:
for prefix, aan in aan_regex.findall(sentence):
sentences.append(prefix + aan)
labels.append(aan == " an")
activations, next_tokens = get_activations_batched(sentences, 32)
# %%
df = pd.DataFrame(
dict(
sentence=sentences,
label=labels,
activation=activations,
next_token=next_tokens,
)
)
df = df.sort_values("activation", ascending=False)
df
# %%
sns.histplot(data=df[df["label"]], x="activation", multiple="stack", bins=50)
plt.show()
sns.histplot(data=df[~df["label"]], x="activation", multiple="stack", bins=50)
plt.show()
# %%
for row in list(df.itertuples())[:10]:
print(row.label, row.next_token, row.sentence, sep="\t")
print("===")
for row in list(df.itertuples())[-10:]:
print(row.label, row.next_token, row.sentence, sep="\t")
# %%
plt.plot(np.array(df.sort_values("activation").reset_index()["label"].tolist(), dtype=np.float32).cumsum())