-
Notifications
You must be signed in to change notification settings - Fork 40
/
buffer.py
450 lines (388 loc) · 17.2 KB
/
buffer.py
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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
import torch as t
from nnsight import LanguageModel
import gc
from tqdm import tqdm
from .config import DEBUG
if DEBUG:
tracer_kwargs = {'scan' : True, 'validate' : True}
else:
tracer_kwargs = {'scan' : False, 'validate' : False}
class ActivationBuffer:
"""
Implements a buffer of activations. The buffer stores activations from a model,
yields them in batches, and refreshes them when the buffer is less than half full.
"""
def __init__(self,
data, # generator which yields text data
model : LanguageModel, # LanguageModel from which to extract activations
submodule, # submodule of the model from which to extract activations
d_submodule=None, # submodule dimension; if None, try to detect automatically
io='out', # can be 'in' or 'out'; whether to extract input or output activations
n_ctxs=3e4, # approximate number of contexts to store in the buffer
ctx_len=128, # length of each context
refresh_batch_size=512, # size of batches in which to process the data when adding to buffer
out_batch_size=8192, # size of batches in which to yield activations
device='cpu' # device on which to store the activations
):
if io not in ['in', 'out']:
raise ValueError("io must be either 'in' or 'out'")
if d_submodule is None:
try:
if io == 'in':
d_submodule = submodule.in_features
else:
d_submodule = submodule.out_features
except:
raise ValueError("d_submodule cannot be inferred and must be specified directly")
self.activations = t.empty(0, d_submodule, device=device)
self.read = t.zeros(0).bool()
self.data = data
self.model = model
self.submodule = submodule
self.d_submodule = d_submodule
self.io = io
self.n_ctxs = n_ctxs
self.ctx_len = ctx_len
self.activation_buffer_size = n_ctxs * ctx_len
self.refresh_batch_size = refresh_batch_size
self.out_batch_size = out_batch_size
self.device = device
def __iter__(self):
return self
def __next__(self):
"""
Return a batch of activations
"""
with t.no_grad():
# if buffer is less than half full, refresh
if (~self.read).sum() < self.activation_buffer_size // 2:
self.refresh()
# return a batch
unreads = (~self.read).nonzero().squeeze()
idxs = unreads[t.randperm(len(unreads), device=unreads.device)[:self.out_batch_size]]
self.read[idxs] = True
return self.activations[idxs]
def text_batch(self, batch_size=None):
"""
Return a list of text
"""
if batch_size is None:
batch_size = self.refresh_batch_size
try:
return [
next(self.data) for _ in range(batch_size)
]
except StopIteration:
raise StopIteration("End of data stream reached")
def tokenized_batch(self, batch_size=None):
"""
Return a batch of tokenized inputs.
"""
texts = self.text_batch(batch_size=batch_size)
return self.model.tokenizer(
texts,
return_tensors='pt',
max_length=self.ctx_len,
padding=True,
truncation=True
)
def refresh(self):
gc.collect()
t.cuda.empty_cache()
self.activations = self.activations[~self.read]
current_idx = len(self.activations)
new_activations = t.empty(self.activation_buffer_size, self.d_submodule, device=self.device)
new_activations[: len(self.activations)] = self.activations
self.activations = new_activations
# Optional progress bar when filling buffer. At larger models / buffer sizes (e.g. gemma-2-2b, 1M tokens on a 4090) this can take a couple minutes.
# pbar = tqdm(total=self.activation_buffer_size, initial=current_idx, desc="Refreshing activations")
while current_idx < self.activation_buffer_size:
with t.no_grad():
with self.model.trace(
self.text_batch(),
**tracer_kwargs,
invoker_args={"truncation": True, "max_length": self.ctx_len},
):
if self.io == "in":
hidden_states = self.submodule.input[0].save()
else:
hidden_states = self.submodule.output.save()
input = self.model.input.save()
attn_mask = input.value[1]["attention_mask"]
hidden_states = hidden_states.value
if isinstance(hidden_states, tuple):
hidden_states = hidden_states[0]
hidden_states = hidden_states[attn_mask != 0]
remaining_space = self.activation_buffer_size - current_idx
assert remaining_space > 0
hidden_states = hidden_states[:remaining_space]
self.activations[current_idx : current_idx + len(hidden_states)] = hidden_states.to(
self.device
)
current_idx += len(hidden_states)
# pbar.update(len(hidden_states))
# pbar.close()
self.read = t.zeros(len(self.activations), dtype=t.bool, device=self.device)
@property
def config(self):
return {
'd_submodule' : self.d_submodule,
'io' : self.io,
'n_ctxs' : self.n_ctxs,
'ctx_len' : self.ctx_len,
'refresh_batch_size' : self.refresh_batch_size,
'out_batch_size' : self.out_batch_size,
'device' : self.device
}
def close(self):
"""
Close the text stream and the underlying compressed file.
"""
self.text_stream.close()
class HeadActivationBuffer:
"""
This is specifically designed for training SAEs for individual attn heads in Llama3.
Much redundant code; can eventually be merged to ActivationBuffer.
Implements a buffer of activations. The buffer stores activations from a model,
yields them in batches, and refreshes them when the buffer is less than half full.
"""
def __init__(self,
data, # generator which yields text data
model : LanguageModel, # LanguageModel from which to extract activations
layer, # submodule of the model from which to extract activations
n_ctxs=3e4, # approximate number of contexts to store in the buffer
ctx_len=128, # length of each context
refresh_batch_size=512, # size of batches in which to process the data when adding to buffer
out_batch_size=8192, # size of batches in which to yield activations
device='cpu', # device on which to store the activations
apply_W_O = False,
remote = False,
):
self.layer = layer
self.n_heads = model.config.num_attention_heads
self.resid_dim = model.config.hidden_size
self.head_dim = self.resid_dim //self.n_heads
self.data = data
self.model = model
self.n_ctxs = n_ctxs
self.ctx_len = ctx_len
self.refresh_batch_size = refresh_batch_size
self.out_batch_size = out_batch_size
self.device = device
self.apply_W_O = apply_W_O
self.remote = remote
self.activations = t.empty(0, self.n_heads, self.head_dim, device=device) # [seq-pos, n_layers, n_head, head_dim]
self.read = t.zeros(0).bool()
def __iter__(self):
return self
def __next__(self):
"""
Return a batch of activations
"""
with t.no_grad():
# if buffer is less than half full, refresh
if (~self.read).sum() < self.n_ctxs * self.ctx_len // 2:
self.refresh()
# return a batch
unreads = (~self.read).nonzero().squeeze()
idxs = unreads[t.randperm(len(unreads), device=unreads.device)[:self.out_batch_size]]
self.read[idxs] = True
return self.activations[idxs]
def text_batch(self, batch_size=None):
"""
Return a list of text
"""
if batch_size is None:
batch_size = self.refresh_batch_size
try:
return [
next(self.data) for _ in range(batch_size)
]
except StopIteration:
raise StopIteration("End of data stream reached")
def tokenized_batch(self, batch_size=None):
"""
Return a batch of tokenized inputs.
"""
texts = self.text_batch(batch_size=batch_size)
return self.model.tokenizer(
texts,
return_tensors='pt',
max_length=self.ctx_len,
padding=True,
truncation=True
)
def refresh(self):
self.activations = self.activations[~self.read]
while len(self.activations) < self.n_ctxs * self.ctx_len:
with t.no_grad():
with self.model.trace(self.text_batch(), **tracer_kwargs, invoker_args={'truncation': True, 'max_length': self.ctx_len}, remote=self.remote):
input = self.model.input.save()
hidden_states = self.model.model.layers[self.layer].self_attn.o_proj.input[0][0]#.save()
if isinstance(hidden_states, tuple):
hidden_states = hidden_states[0]
# Reshape by head
new_shape = hidden_states.size()[:-1] + (self.n_heads, self.head_dim) # (batch_size, seq_len, n_heads, head_dim)
hidden_states = hidden_states.view(*new_shape)
# Optionally map from head dim to resid dim
if self.apply_W_O:
hidden_states_W_O_shape = hidden_states.size()[:-1] + (self.model.config.hidden_size,) # (batch_size, seq_len, n_heads, resid_dim)
hidden_states_W_O = t.zeros(hidden_states_W_O_shape, device=hidden_states.device)
for h in range (self.n_heads):
start = h*self.head_dim
end = (h+1)*self.head_dim
hidden_states_W_O[..., h, start:end] = hidden_states[..., h, :]
hidden_states = self.model.model.layers[self.layer].self_attn.o_proj(hidden_states_W_O).save()
# Apply attention mask
attn_mask = input.value[1]['attention_mask']
hidden_states = hidden_states[attn_mask != 0]
# Save results
self.activations = t.cat([self.activations, hidden_states.to(self.device)], dim=0)
self.read = t.zeros(len(self.activations), dtype=t.bool, device=self.device)
@property
def config(self):
return {
'layer': self.layer,
'n_ctxs' : self.n_ctxs,
'ctx_len' : self.ctx_len,
'refresh_batch_size' : self.refresh_batch_size,
'out_batch_size' : self.out_batch_size,
'device' : self.device
}
def close(self):
"""
Close the text stream and the underlying compressed file.
"""
self.text_stream.close()
class NNsightActivationBuffer:
"""
Implements a buffer of activations. The buffer stores activations from a model,
yields them in batches, and refreshes them when the buffer is less than half full.
"""
def __init__(
self,
data, # generator which yields text data
model: LanguageModel, # LanguageModel from which to extract activations
submodule, # submodule of the model from which to extract activations
d_submodule=None, # submodule dimension; if None, try to detect automatically
io="out", # can be 'in' or 'out'; whether to extract input or output activations, "in_and_out" for transcoders
n_ctxs=3e4, # approximate number of contexts to store in the buffer
ctx_len=128, # length of each context
refresh_batch_size=512, # size of batches in which to process the data when adding to buffer
out_batch_size=8192, # size of batches in which to yield activations
device="cpu", # device on which to store the activations
):
if io not in ["in", "out", "in_and_out"]:
raise ValueError("io must be either 'in' or 'out' or 'in_and_out'")
if d_submodule is None:
try:
if io == "in":
d_submodule = submodule.in_features
else:
d_submodule = submodule.out_features
except:
raise ValueError("d_submodule cannot be inferred and must be specified directly")
if io in ["in", "out"]:
self.activations = t.empty(0, d_submodule, device=device)
elif io == "in_and_out":
self.activations = t.empty(0, 2, d_submodule, device=device)
self.read = t.zeros(0).bool()
self.data = data
self.model = model
self.submodule = submodule
self.d_submodule = d_submodule
self.io = io
self.n_ctxs = n_ctxs
self.ctx_len = ctx_len
self.refresh_batch_size = refresh_batch_size
self.out_batch_size = out_batch_size
self.device = device
def __iter__(self):
return self
def __next__(self):
"""
Return a batch of activations
"""
with t.no_grad():
# if buffer is less than half full, refresh
if (~self.read).sum() < self.n_ctxs * self.ctx_len // 2:
self.refresh()
# return a batch
unreads = (~self.read).nonzero().squeeze()
idxs = unreads[t.randperm(len(unreads), device=unreads.device)[: self.out_batch_size]]
self.read[idxs] = True
return self.activations[idxs]
def tokenized_batch(self, batch_size=None):
"""
Return a batch of tokenized inputs.
"""
texts = self.text_batch(batch_size=batch_size)
return self.model.tokenizer(
texts, return_tensors="pt", max_length=self.ctx_len, padding=True, truncation=True
)
def token_batch(self, batch_size=None):
"""
Return a list of text
"""
if batch_size is None:
batch_size = self.refresh_batch_size
try:
return t.tensor([next(self.data) for _ in range(batch_size)], device=self.device)
except StopIteration:
raise StopIteration("End of data stream reached")
def text_batch(self, batch_size=None):
"""
Return a list of text
"""
# if batch_size is None:
# batch_size = self.refresh_batch_size
# try:
# return [next(self.data) for _ in range(batch_size)]
# except StopIteration:
# raise StopIteration("End of data stream reached")
return self.token_batch(batch_size)
def _reshaped_activations(self, hidden_states):
hidden_states = hidden_states.value
if isinstance(hidden_states, tuple):
hidden_states = hidden_states[0]
batch_size, seq_len, d_model = hidden_states.shape
hidden_states = hidden_states.view(batch_size * seq_len, d_model)
return hidden_states
def refresh(self):
self.activations = self.activations[~self.read]
while len(self.activations) < self.n_ctxs * self.ctx_len:
with t.no_grad(), self.model.trace(
self.token_batch(),
**tracer_kwargs,
invoker_args={"truncation": True, "max_length": self.ctx_len},
):
if self.io in ["in", "in_and_out"]:
hidden_states_in = self.submodule.input[0].save()
if self.io in ["out", "in_and_out"]:
hidden_states_out = self.submodule.output.save()
if self.io == "in":
hidden_states = self._reshaped_activations(hidden_states_in)
elif self.io == "out":
hidden_states = self._reshaped_activations(hidden_states_out)
elif self.io == "in_and_out":
hidden_states_in = self._reshaped_activations(hidden_states_in).unsqueeze(1)
hidden_states_out = self._reshaped_activations(hidden_states_out).unsqueeze(1)
hidden_states = t.cat([hidden_states_in, hidden_states_out], dim=1)
self.activations = t.cat([self.activations, hidden_states.to(self.device)], dim=0)
self.read = t.zeros(len(self.activations), dtype=t.bool, device=self.device)
@property
def config(self):
return {
"d_submodule": self.d_submodule,
"io": self.io,
"n_ctxs": self.n_ctxs,
"ctx_len": self.ctx_len,
"refresh_batch_size": self.refresh_batch_size,
"out_batch_size": self.out_batch_size,
"device": self.device,
}
def close(self):
"""
Close the text stream and the underlying compressed file.
"""
self.text_stream.close()