-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtc_peek_backend.py
2694 lines (2226 loc) · 95.9 KB
/
tc_peek_backend.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
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import gc
import enum
import os
import copy
import json
import dataclasses
import numpy as np
import zipfile
import os.path
if __package__ is not None and __package__ != "":
from . import render
from . import backend_import_cfg
else:
import render
import backend_import_cfg
from dataclasses import dataclass
from typing import Optional, List, Dict
from threading import RLock
# okay, in this next part, we're gonna do some real funky stuff
# for some background: torch, huggingface_hub, and especially transformer_lens can expensive libraries to load
# if we're just rendering a session, then we don't need to load them
# as such, we only want to load them if necessary
# to do this, we'll create "dummy classes" that pretend to be the modules in question, but do nothing
# then, if the flag backend_import_cfg.import_expensive_modules is set, then we use the real modules
# otherwise, we use the dummies
class Dummy:
def __init__(self, *args, name=""):
self.name = name
def __getattr__(self, other):
new_obj = type(self)(name=self.name+'.'+other)
return new_obj
class DecoratorDummy(Dummy):
def __call__(self, *args, **kwargs):
def decorator(func):
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
return decorator
if backend_import_cfg.import_expensive_modules:
import torch
import safetensors
import huggingface_hub as hf_hub
from transformer_lens import HookedTransformer
no_grad = torch.no_grad
if torch.cuda.is_available():
device = 'cuda'
else:
device = 'cpu'
dtype = torch.float32
else:
torch = Dummy(name='torch')
hf_hub = Dummy()
safetensors = Dummy()
HookedTransformer = Dummy()
no_grad = DecoratorDummy(name='torch.no_grad')
DTYPE_DICT = {
None: torch.float32,
'float64': torch.float64,
'float32': torch.float32,
'float16': torch.float16,
'bfloat16': torch.bfloat16,
'uint8': torch.uint8,
'int8': torch.int8,
'int16': torch.int16,
'int32': torch.int32,
'int64': torch.int64,
'torch.float64': torch.float64,
'torch.float32': torch.float32,
'torch.float16': torch.float16,
'torch.bfloat16': torch.bfloat16,
'torch.uint8': torch.uint8,
'torch.int8': torch.int8,
'torch.int16': torch.int16,
'torch.int32': torch.int32,
'torch.int64': torch.int64,
}
def _to_numpy(x):
x = x.detach().cpu()
try:
x = x.numpy()
except TypeError:
x = x.to(torch.float32).numpy()
return x
# NOTE: currently, doesn't support sublayers beyond the following
class Sublayer(enum.Enum):
PRE_LOGITS = enum.auto() # post-ln_f
LOGITS = enum.auto() # post unembed
EMBED = enum.auto()
RESID_PRE = enum.auto()
ATTN_IN = enum.auto() # post-LN1
ATTN_OUT = enum.auto() # not necessarily same as resid_mid because of parallel models (curse you Pythia!)
RESID_MID = enum.auto()
MLP_IN = enum.auto() # post-LN2
MLP_OUT = enum.auto()
RESID_POST = enum.auto() # same as mlp_out
def __str__(self):
if self == type(self).EMBED:
return "embed"
if self == type(self).RESID_PRE:
return 'pre'
elif self == type(self).ATTN_IN:
return 'attn_in'
elif self == type(self).ATTN_OUT:
return 'attn_out'
elif self == type(self).RESID_MID:
return 'mid'
elif self == type(self).MLP_IN:
return 'mlp_in'
elif self == type(self).MLP_OUT:
return 'mlp_out'
elif self == type(self).RESID_POST:
return 'post'
elif self == type(self).PRE_LOGITS:
return 'pre_logits'
elif self == type(self).LOGITS:
return 'logits'
def serialize(self):
return str(self)
@classmethod
def deserialize(cls, s):
if s == "embed":
return cls.EMBED
if s == 'pre':
return cls.RESID_PRE
elif s == 'attn_in':
return cls.ATTN_IN
elif s == 'attn_out':
return cls.ATTN_OUT
elif s == 'mid':
return cls.RESID_MID
elif s == 'mlp_in':
return cls.MLP_IN
elif s == 'mlp_out':
return cls.MLP_OUT
elif s == 'post':
return cls.RESID_POST
elif s == 'pre_logits':
return cls.PRE_LOGITS
elif s == 'logits':
return cls.LOGITS
class LayerSublayer:
def __init__(self, layer, sublayer, parallel_attn_mlp=False):
self.layer = layer
self.sublayer = sublayer
self.parallel_attn_mlp = parallel_attn_mlp
@classmethod
def from_hookpoint_str(cls, hookpoint):
# TODO: hookpoint str validation
if hookpoint == "hook_embed":
return cls(0, Sublayer.EMBED)
split_str = hookpoint.split(".")
layer = int(split_str[1])
if split_str[-1] == 'hook_normalized':
if split_str[2] == 'ln1':
sublayer = Sublayer.ATTN_IN
elif split_str[2] == 'ln2':
sublayer = Sublayer.MLP_IN
elif split_str[2] == 'ln_f':
sublayer = Sublayer.PRE_LOGITS
elif split_str[2] == 'hook_resid_pre':
sublayer = Sublayer.RESID_PRE
elif split_str[2] == 'hook_resid_mid':
sublayer = Sublayer.RESID_MID
elif split_str[2] == 'hook_attn_out':
sublayer = Sublayer.ATTN_OUT
elif split_str[2] == 'hook_mlp_out':
sublayer = Sublayer.MLP_OUT
elif split_str[2] == 'hook_resid_post':
sublayer = Sublayer.RESID_POST
retval = cls(layer, sublayer)
return retval
def to_hookpoint_str(self):
if self.sublayer == Sublayer.EMBED:
return "hook_embed"
if self.sublayer == Sublayer.RESID_PRE:
suffix = 'hook_resid_pre'
elif self.sublayer == Sublayer.ATTN_IN:
suffix = 'ln1.hook_normalized'
elif self.sublayer == Sublayer.ATTN_OUT:
suffix = 'hook_attn_out'
elif self.sublayer == Sublayer.RESID_MID:
suffix = 'hook_resid_mid'
elif self.sublayer == Sublayer.MLP_IN:
suffix = 'ln2.hook_normalized'
elif self.sublayer == Sublayer.MLP_OUT:
suffix = 'hook_mlp_out'
elif self.sublayer == Sublayer.RESID_POST:
suffix = 'hook_resid_post'
elif self.sublayer == Sublayer.PRE_LOGITS:
return 'ln_final.hook_normalized'
elif self.sublayer == Sublayer.LOGITS:
return None # logits don't have a hook point
try:
return f'blocks.{self.layer}.{suffix}'
except:
print(self.layer, self.sublayer)
raise Exception
# intended for use in ordinal comparisons -- actual values
def val(self):
sublayer_val = self.sublayer.value
if self.sublayer == Sublayer.ATTN_OUT:
if self.parallel_attn_mlp:
sublayer_val = Sublayer.RESID_POST.value
else:
sublayer_val = Sublayer.RESID_MID.value
elif self.sublayer == Sublayer.MLP_IN:
if self.parallel_attn_mlp:
sublayer_val = Sublayer.ATTN_IN.value
elif self.sublayer == Sublayer.MLP_OUT:
sublayer_val = Sublayer.RESID_POST.value
return self.layer + sublayer_val/Sublayer.RESID_POST.value
def __lt__(self, other):
return self.val() < other.val()
def __le__(self, other):
return self.val() <= other.val()
def __eq__(self, other):
return self.layer == other.layer and self.sublayer == other.sublayer
def __str__(self):
return f'{self.layer}{str(self.sublayer)}'
def serialize(self):
return { 'layer': self.layer, 'sublayer': self.sublayer.serialize(), 'parallel_attn_mlp': self.parallel_attn_mlp }
@classmethod
def deserialize(cls, d):
return cls(
layer=d['layer'],
sublayer=Sublayer.deserialize(d['sublayer']),
parallel_attn_mlp=d['parallel_attn_mlp']
)
### FeatureInfo-related classes/methods ###
class FeatureType(enum.Enum):
SAE = 'sae'
OBSERVABLE = 'observable'
PULLBACK = 'pullback'
OTHER = 'other'
def serialize(self):
return self.value
@classmethod
def deserialize(cls, s):
return {x.value: x for x in cls}[s]
class FeatureInfo:
def __init__(self):
self.name = ''
self.description = ''
self.encoder_vector = None
self.encoder_bias = 0
self.decoder_vector = None
self.input_layer : LayerSublayer = None
self.output_layer : LayerSublayer = None
self.feature_type : FeatureType = None
self.use_relu : bool = False
self.attn_head = None
self.observable_tokens = None
self.observable_weights = None
self.sae_info = None
self.feature_idx = None
def serialize(self):
retdict = {
'name': self.name,
'description': self.description,
'encoder_bias': self.encoder_bias,
'input_layer': self.input_layer.serialize(),
'output_layer': self.output_layer.serialize(),
'feature_type': self.feature_type.serialize(),
'use_relu': self.use_relu,
'attn_head': self.attn_head,
'observable_tokens': self.observable_tokens,
'observable_weights': self.observable_weights,
'sae_info': self.sae_info.serialize() if self.sae_info is not None else None,
'feature_idx': self.feature_idx,
'metadata_only': self.encoder_vector is None or self.decoder_vector is None
}
return retdict
@classmethod
def deserialize(cls, d):
new_info = cls()
new_info.name = d['name']
new_info.description = d['description']
new_info.encoder_bias = d['encoder_bias']
new_info.input_layer = LayerSublayer.deserialize(d['input_layer'])
new_info.output_layer = LayerSublayer.deserialize(d['output_layer'])
new_info.feature_type = FeatureType.deserialize(d['feature_type'])
new_info.use_relu = d['use_relu']
new_info.attn_head = d['attn_head']
new_info.observable_tokens = d['observable_tokens']
new_info.observable_weights = d['observable_weights']
new_info.sae_info = SAEInfo.deserialize(d['sae_info']) if 'sae_info' in d and d['sae_info'] is not None else None
new_info.feature_idx = d['feature_idx']
return new_info
def save(self, dirpath, json_filename="feature.json", tensors_filename="feature_tensors.safetensors", save_tensors=True, out_zipfile=None):
# note: tensors_filename is relative to the same directory in which the json will be saved
if out_zipfile is None:
if not os.path.exists(dirpath):
os.mkdir(dirpath)
"""else:
if not zipfile.Path(out_zipfile, dirpath).exists():
out_zipfile.mkdir(dirpath)"""
retdict = self.serialize()
if save_tensors:
tensors_dict = { 'encoder_vector': self.encoder_vector, 'decoder_vector': self.decoder_vector }
if out_zipfile is None:
safetensors.torch.save_file(tensors_dict, os.path.join(dirpath, tensors_filename))
else:
tensor_bytes = safetensors.torch.save(tensors_dict)
with out_zipfile.open(os.path.join(dirpath, tensors_filename), "w") as ofp:
ofp.write(tensor_bytes)
retdict['tensors_filename'] = tensors_filename
else:
retdict['tensors_filename'] = None
if out_zipfile is None:
with open(os.path.join(dirpath, json_filename), "w") as ofp:
json.dump(retdict, ofp)
else:
with out_zipfile.open(os.path.join(dirpath, json_filename), "w") as ofp:
s = json.dumps(retdict)
ofp.write(bytes(s, 'ascii'))
return json_filename
@classmethod
def load(cls, json_path, load_tensors=True, in_zipfile=None):
if in_zipfile is None:
with open(json_path, "r") as fp:
d = json.load(fp)
else:
with in_zipfile.open(json_path, "r") as fp:
d = json.load(fp)
new_info = cls.deserialize(d)
tensors_filename = d['tensors_filename']
if load_tensors and tensors_filename is not None:
dirname = os.path.dirname(json_path)
if in_zipfile is None:
with safetensors.safe_open(os.path.join(dirname, tensors_filename), framework="pt", device=device) as tensors:
new_info.encoder_vector = tensors.get_tensor('encoder_vector')
new_info.decoder_vector = tensors.get_tensor('decoder_vector')
else:
with in_zipfile.open(os.path.join(dirname, tensors_filename), "r") as fp:
tensor_bytes = fp.read()
tensors = safetensors.torch.load(tensor_bytes)
new_info.encoder_vector = tensors['encoder_vector'].to(device=device, dtype=dtype)
new_info.decoder_vector = tensors['decoder_vector'].to(device=device, dtype=dtype)
return new_info
@classmethod
@no_grad()
def init_from_sae_feature(cls, sae_info : 'SAEInfo', feature_idx : int, name=None, description=None):
feature = cls()
sae = sae_info.sae
if name is None or name == '':
feature.name = f'{sae_info.short_name}[{feature_idx}]'
else: feature.name = name
if description is not None: feature.description = description
feature.encoder_vector = sae.W_enc[:, feature_idx].clone().detach().to(device=device, dtype=dtype)
#feature.encoder_bias = (sae.b_enc[feature_idx] - (sae.b_dec @ sae.W_enc)[feature_idx]).item()
feature.encoder_bias = sae.b_enc[feature_idx].item()
feature.decoder_vector = sae.W_dec[feature_idx].clone().detach().to(device=device, dtype=dtype)
feature.input_layer = sae_info.input_layer
feature.output_layer = sae_info.output_layer
feature.feature_type = FeatureType.SAE
feature.use_relu = True
feature.sae_info = sae_info
feature.feature_idx = feature_idx
return feature
@classmethod
@no_grad()
def init_from_observable(cls, model : HookedTransformer, token_strs : List[str], weights : List[float], do_unembed_pullback : bool=False, name=None, description=None):
feature = cls()
if name is None or name == '':
feature.name = 'observable'
else: feature.name = name
if description is not None: feature.description = description
feature.observable_tokens = token_strs
feature.observable_weights = weights
observable = torch.zeros(model.W_U.shape[-1])
for token_str, weight in zip(token_strs, weights):
try:
token_idx = model.to_single_token(token_str)
except AssertionError:
raise Exception(f"Invalid token: \"{token_str}\" is not a single token")
observable[token_idx] = weight
observable = observable.to(device=device, dtype=dtype)
feature.encoder_bias = 0
feature.output_layer = LayerSublayer(len(model.blocks), Sublayer.LOGITS)
feature.decoder_vector = observable/(torch.linalg.norm(observable)**2)
if not do_unembed_pullback:
feature.encoder_vector = observable
feature.input_layer = feature.output_layer
else:
feature.encoder_vector = model.W_U @ observable
feature.input_layer = LayerSublayer(len(model.blocks), Sublayer.PRE_LOGITS)
feature.feature_type = FeatureType.OBSERVABLE
return feature
@classmethod
@no_grad()
def init_from_attn_pullback(cls, model : HookedTransformer, base_feature : 'FeatureInfo', layer : int, head : int):
feature = cls()
feature.name = f'attn{layer}[{head}]'
feature.encoder_bias = 0
feature.input_layer = LayerSublayer(layer, Sublayer.ATTN_IN)
feature.output_layer = LayerSublayer(layer, Sublayer.RESID_POST if model.cfg.parallel_attn_mlp else Sublayer.RESID_MID)
feature.decoder_vector = base_feature.encoder_vector/(torch.linalg.norm(base_feature.encoder_vector)**2)
feature.encoder_vector = model.OV[layer, head] @ base_feature.encoder_vector
feature.attn_head = head
feature.feature_type = FeatureType.PULLBACK
return feature
@classmethod
@no_grad()
def init_from_vector(cls, model : HookedTransformer, layer : LayerSublayer, vector, name=None, contravariant=True):
feature = cls()
if name is None:
feature.name = f'{layer}_vector'
else:
feature.name = name
feature.encoder_bias = 0
feature.input_layer = layer
feature.output_layer = layer
if contravariant:
feature.encoder_vector = vector/(torch.linalg.norm(vector)**2)
feature.decoder_vector = vector
else:
feature.encoder_vector = vector
feature.decoder_vector = vector/(torch.linalg.norm(vector)**2)
feature.feature_type = FeatureType.OTHER
return feature
@no_grad()
def get_activs(self, tensor, use_relu=None):
# tensor: [batch, tokens, dim]
if tensor.dtype != self.encoder_vector.dtype:
# hack to take care of transformerlens forcibly storing layernorm activations as float32
tensor = tensor.to(dtype=self.encoder_vector.dtype)
pre_acts = torch.einsum('d, ...d -> ...', self.encoder_vector, tensor)
acts = pre_acts + self.encoder_bias
if use_relu is None: use_relu = self.use_relu
if use_relu: acts = torch.nn.functional.relu(acts)
return _to_numpy(acts)
@no_grad()
def get_deembeddings(self, model : HookedTransformer):
return _to_numpy(model.W_E @ self.encoder_vector)
### Computational=path-related classes/methods ###
@dataclass
class AttribInfo:
feature_info : Optional[FeatureInfo] = None
token_pos : Optional[int] = None
invar_factor : float = 1.0
ln_constant : float = 1.0
attn_factor : float = 1.0
feature_activ : float = 1.0
total_invar_factor : Optional[float] = None
total_ln_constant : Optional[float] = None
total_attn_factor : Optional[float] = None
total_attrib : Optional[float] = None
parent_ln_constant : Optional[float] = None
total_parent_ln_constant : Optional[float] = None
top_child_components : Optional[List['ComponentInfo']] = None
top_child_contribs : Optional[List[float]] = None
name : Optional[str] = None
description : Optional[str] = None
# for use with steering vectors
# is_unsteered_attrib : bool = False
unsteered_attrib : Optional['AttribInfo'] = None
def serialize_base(self):
return {
'token_pos': self.token_pos,
'invar_factor': self.invar_factor,
'ln_constant': self.ln_constant,
'attn_factor': self.attn_factor,
'feature_activ': self.feature_activ,
'parent_ln_constant': self.parent_ln_constant,
'total_parent_ln_constant': self.total_parent_ln_constant,
'total_invar_factor': self.total_invar_factor,
'total_ln_constant': self.total_ln_constant,
'total_attn_factor': self.total_attn_factor,
'total_attrib': self.total_attrib,
'unsteered_attrib': None if self.unsteered_attrib is None else self.unsteered_attrib.serialize()
}
def serialize(self):
retdict = self.serialize_base()
retdict = {**retdict,
'top_child_components': [x.serialize() for x in self.top_child_components] if self.top_child_components is not None else None,
'top_child_contribs': self.top_child_contribs,
'name': self.name,
'description': self.description
}
retdict['feature_info'] = self.feature_info.serialize()
return retdict
def save(self, dirpath, json_filename="attrib.json", save_tensors=True, out_zipfile=None):
if out_zipfile is None:
if not os.path.exists(dirpath):
os.mkdir(dirpath)
"""else:
if not zipfile.Path(out_zipfile, dirpath).exists():
out_zipfile.mkdir(dirpath)"""
retdict = self.serialize()
# save feature info
retdict['feature_json_filename'] = self.feature_info.save(dirpath, save_tensors=save_tensors, out_zipfile=out_zipfile)
if out_zipfile is None:
with open(os.path.join(dirpath, json_filename), "w") as ofp:
json.dump(retdict, ofp)
else:
with out_zipfile.open(os.path.join(dirpath, json_filename), "w") as ofp:
s = json.dumps(retdict)
ofp.write(bytes(s, 'ascii'))
return json_filename
@classmethod
def deserialize(cls, d):
new_info = cls(
feature_info=FeatureInfo.deserialize(d['feature_info']),
token_pos=d['token_pos'],
invar_factor=d['invar_factor'],
ln_constant=d['ln_constant'],
attn_factor=d['attn_factor'],
feature_activ=d['feature_activ'],
total_invar_factor=d['total_invar_factor'],
total_ln_constant=d['total_ln_constant'],
total_attn_factor=d['total_attn_factor'],
total_attrib=d['total_attrib'],
total_parent_ln_constant=d['total_parent_ln_constant'] if 'total_parent_ln_constant' in d else None,
parent_ln_constant=d['parent_ln_constant'] if 'parent_ln_constant' in d else None,
top_child_components=[ComponentInfo.deserialize(x) for x in d['top_child_components']] if 'top_child_components' in d and d['top_child_components'] is not None else None,
top_child_contribs=d['top_child_contribs'] if 'top_child_contribs' in d else None,
name=d['name'] if 'name' in d else None,
description=d['description'] if 'description' in d else None,
unsteered_attrib=cls.deserialize(d['unsteered_attrib']) if 'unsteered_attrib' in d and d['unsteered_attrib'] is not None else None,
)
return new_info
@classmethod
def load(cls, json_path, load_tensors=True, in_zipfile=None):
if in_zipfile is None:
with open(json_path, "r") as fp:
d = json.load(fp)
else:
with in_zipfile.open(json_path, "r") as fp:
d = json.load(fp)
new_info = cls.deserialize(d)
feature_info_filename = d['feature_json_filename']
dirname = os.path.dirname(json_path)
new_info.feature_info = FeatureInfo.load(os.path.join(dirname, feature_info_filename), load_tensors=load_tensors, in_zipfile=in_zipfile)
return new_info
class ComponentType(enum.Enum):
SAE_FEATURE = 0
ATTN_HEAD = 1
EMBED = 2
def serialize(self):
return self.name.lower()
@classmethod
def deserialize(cls, s):
return {x.name.lower(): x for x in cls}[s]
@dataclass
class ComponentInfo:
component_type : ComponentType
token_pos : int
attn_head : Optional[int] = None
attn_layer : Optional[int] = None
sae_idx : Optional[int] = None
feature_idx : Optional[int] = None
embed_vocab_idx : Optional[int] = None
def serialize(self):
retdict = {
"component_type": self.component_type.serialize(),
"token_pos": self.token_pos,
"attn_head": self.attn_head,
"attn_layer": self.attn_layer,
"sae_idx": self.sae_idx,
"feature_idx": self.feature_idx,
"embed_vocab_idx": self.embed_vocab_idx
}
return retdict
@classmethod
def deserialize(cls, d):
new_info = cls(
component_type=ComponentType.deserialize(d['component_type']),
token_pos=d['token_pos'],
attn_head=d['attn_head'],
attn_layer=d['attn_layer'],
sae_idx=d['sae_idx'],
feature_idx=d['feature_idx'],
embed_vocab_idx=d['embed_vocab_idx']
)
return new_info
class ComputationalPath:
def __init__(self, name : str, description : str = ""):
self.name = name
self.description = description
self.nodes : List[AttribInfo] = []
self.is_outdated : bool = False
self.outdated_token_strs : Optional[List[str]] = None
def save(self, dirpath, json_filename="path.json", save_tensors=True, out_zipfile=None):
if out_zipfile is None:
if not os.path.exists(dirpath):
os.mkdir(dirpath)
retdict = {
'name': self.name,
'description': self.description,
'node_json_filenames': [],
'is_outdated': self.is_outdated,
'outdated_token_strs': self.outdated_token_strs
}
for i, node in enumerate(self.get_total_attribs()):
node_dir_rel_path = f'node_{i}'
attrib_json_filename = node.save(os.path.join(dirpath, node_dir_rel_path), save_tensors=save_tensors, out_zipfile=out_zipfile)
retdict['node_json_filenames'].append(
os.path.join(node_dir_rel_path, attrib_json_filename)
)
if out_zipfile is None:
with open(os.path.join(dirpath, json_filename), "w") as ofp:
json.dump(retdict, ofp)
else:
with out_zipfile.open(os.path.join(dirpath, json_filename), "w") as ofp:
s = json.dumps(retdict)
ofp.write(bytes(s, 'ascii'))
return json_filename
@classmethod
def load(cls, json_path, load_tensors=True, in_zipfile=None):
if in_zipfile is None:
with open(json_path, "r") as fp:
d = json.load(fp)
else:
with in_zipfile.open(json_path, "r") as fp:
d = json.load(fp)
new_info = cls(name=d['name'], description=d['description'])
new_info.is_outdated = d['is_outdated']
new_info.outdated_token_strs = d['outdated_token_strs']
dirname = os.path.dirname(json_path)
for node_json_filename in d['node_json_filenames']:
new_node_info = AttribInfo.load(os.path.join(dirname, node_json_filename), load_tensors=load_tensors, in_zipfile=in_zipfile)
new_info.nodes.append(new_node_info)
return new_info
def _get_total_attribs_for_node_list(self, node_list):
root = node_list[0]
if root.total_attrib is None:
retlist = [AttribInfo(
feature_info = root.feature_info,
token_pos = root.token_pos,
invar_factor = root.invar_factor,
ln_constant = root.ln_constant,
attn_factor = root.attn_factor,
feature_activ = root.feature_activ,
total_invar_factor = root.invar_factor,
total_ln_constant = root.ln_constant,
total_attn_factor = root.attn_factor,
top_child_components = root.top_child_components,
top_child_contribs = root.top_child_contribs,
name = root.name if root.name is not None else root.feature_info.name
)]
retlist[0].total_attrib = retlist[0].invar_factor * retlist[0].attn_factor * retlist[0].feature_activ
else:
retlist = [root]
retlist[0].parent_ln_constant = 1.0
retlist[0].total_parent_ln_constant = 1.0
for i in range(1, len(node_list)):
cur_node = node_list[i]
if cur_node.total_attrib is not None:
retlist.append(cur_node)
continue
prev_node = retlist[i-1]
cur_node.total_invar_factor = cur_node.invar_factor * prev_node.total_invar_factor
cur_node.total_ln_constant = cur_node.ln_constant * prev_node.total_ln_constant
cur_node.total_attn_factor = cur_node.attn_factor * prev_node.total_attn_factor
cur_node.parent_ln_constant = prev_node.ln_constant
cur_node.total_parent_ln_constant = prev_node.total_ln_constant
# IMPORTANT: note that we use the PREVIOUS NODE's layernorm constant to compute the current node's attrib
cur_node.total_attrib = cur_node.total_invar_factor * prev_node.total_ln_constant * cur_node.total_attn_factor * cur_node.feature_activ
if cur_node.name is None: cur_node.name = cur_node.feature_info.name
retlist.append(cur_node)
return retlist
def get_total_attribs(self):
if len(self.nodes) == 0: return []
retlist = self._get_total_attribs_for_node_list(self.nodes)
for original_node, new_node in zip(self.nodes, retlist):
new_node.unsteered_attrib = original_node.unsteered_attrib
self.nodes = retlist
# now, do the same for each node's unsteered_attrib
# ASSUMPTION: either all unsteered_attribs are None or no unsteered_attribs are None
unsteered_attribs = []
unsteered_attrib_none = False
for node in self.nodes:
if node.unsteered_attrib is None:
unsteered_attrib_none = True
break
unsteered_attribs.append(node.unsteered_attrib)
if not unsteered_attrib_none:
unsteered_attribs = self._get_total_attribs_for_node_list(unsteered_attribs)
for node, unsteered_attrib in zip(self.nodes, unsteered_attribs):
node.unsteered_attrib = unsteered_attrib
return retlist
### SAE-related classes/methods ###
# the SAEConfig and SAE classes are inspired by the SAELens classes
# but these classes are trimmed down, since we don't focus on training SAEs
# the SAEConfig class only contains info essential to performing inference
# with a given SAE
# (in contrast, the SAEInfo class contains auxiliary metadata related to
# whence one procures an SAE)
@dataclass
class SAEConfig:
d_in : int
num_features : int
d_out : Optional[int] = None
dtype : torch.dtype = torch.float32
act_fn : str = "relu"
top_k : Optional[int] = None
def __post_init__(self):
if self.d_out is None: self.d_out = self.d_in
def serialize(self):
d = dataclasses.asdict(self)
d['dtype'] = str(d['dtype'])
return d
@classmethod
def deserialize(cls, d):
return cls(
d_in=d['d_in'],
num_features=d['num_features'],
d_out=d.get('d_out', None),
dtype=DTYPE_DICT[d.get('dtype', None)],
act_fn=d.get('act_fn', 'relu'),
top_k=d.get('top_k', None)
)
if backend_import_cfg.import_expensive_modules:
sae_superclass = torch.nn.Module
else:
sae_superclass = object
class SAE(sae_superclass):
def __init__(self, cfg : SAEConfig, load_tensors=True):
super().__init__()
self.cfg = cfg
if load_tensors and backend_import_cfg.import_expensive_modules:
self.W_enc = torch.nn.Parameter(
torch.empty(
self.cfg.d_in, self.cfg.num_features, dtype=self.cfg.dtype
)
)
self.b_enc = torch.nn.Parameter(
torch.empty(
self.cfg.num_features, dtype=self.cfg.dtype
)
)
self.W_dec = torch.nn.Parameter(
torch.empty(
self.cfg.num_features, self.cfg.d_out, dtype=self.cfg.dtype
)
)
self.b_dec = torch.nn.Parameter(
torch.empty(
self.cfg.d_out, dtype=self.cfg.dtype
)
)
act_fns = {
'relu': torch.nn.functional.relu,
'id': lambda x: x,
'top_k': lambda x: self._top_k(x)
}
self.act_fn = act_fns[self.cfg.act_fn]
def _top_k(self, x):
acts = torch.zeros(x.shape, dtype=x.dtype).to(device=x.device)
vals, idxs = torch.topk(x, k=self.cfg.top_k)
return torch.scatter(acts, -1, idxs, vals)
def get_activs(self, x):
if x.dtype != self.W_enc.dtype:
# hack to take care of transformerlens forcibly storing layernorm activations as float32
x = x.to(dtype=self.W_enc.dtype)
pre_acts = torch.einsum('df, ...d -> ...f', self.W_enc, x)
acts = self.act_fn(pre_acts + self.b_enc)
return acts
def forward(self, x):
acts = self.get_activs(x)
post_acts = torch.einsum('fd, ...f -> ...d', self.W_dec, acts)
outs = post_acts + self.b_dec
return outs
def save(self, dirpath, json_filename="sae.json", save_tensors=False, tensors_filename=None, out_zipfile=None):
if tensors_filename is None:
tensors_filename = f"{os.path.splitext(json_filename)[0]}.safetensors"
cfg_dict = self.cfg.serialize()
if out_zipfile is None:
if not os.path.exists(dirpath):
os.mkdir(dirpath)
"""else:
if not zipfile.Path(out_zipfile, dirpath).exists():
out_zipfile.mkdir(dirpath)"""
if save_tensors:
tensors_dict = { 'W_enc': self.W_enc, 'W_dec': self.W_dec, 'b_enc': self.b_enc, 'b_dec': self.b_dec }
if out_zipfile is None:
safetensors.torch.save_file(tensors_dict, os.path.join(dirpath, tensors_filename))
else:
tensor_bytes = safetensors.torch.save(tensors_dict)
with out_zipfile.open(os.path.join(dirpath, tensors_filename), "w") as ofp:
ofp.write(tensor_bytes)
cfg_dict['tensors_filename'] = tensors_filename
else:
cfg_dict['tensors_filename'] = None
if out_zipfile is None:
with open(os.path.join(dirpath, json_filename), "w") as ofp:
json.dump(cfg_dict, ofp)
else:
with out_zipfile.open(os.path.join(dirpath, json_filename), "w") as ofp:
s = json.dumps(cfg_dict)
ofp.write(bytes(s, 'ascii'))
return json_filename
def load_tensors(self, tensors_path, in_zipfile=None):
if in_zipfile is None:
with safetensors.safe_open(tensors_path, framework="pt", device="cpu") as tensors:
self.W_enc.data = tensors.get_tensor('W_enc')
self.W_dec.data = tensors.get_tensor('W_dec')
self.b_enc.data = tensors.get_tensor('b_enc')
self.b_dec.data = tensors.get_tensor('b_dec')
else:
with in_zipfile.open(tensors_path, "r") as fp:
tensor_bytes = fp.read()
tensors = safetensors.torch.load(tensor_bytes)
self.W_enc.data = tensors['W_enc']
self.W_dec.data = tensors['W_dec']
self.b_enc.data = tensors['b_enc']
self.b_dec.data = tensors['b_dec']
@classmethod
@no_grad()
def load(cls, json_path, load_tensors=True, in_zipfile=None):
if in_zipfile is None:
with open(json_path, "r") as fp:
d = json.load(fp)
else:
with in_zipfile.open(json_path, "r") as fp:
d = json.load(fp)
cfg = SAEConfig.deserialize(d)
new_sae = cls(cfg)
tensors_filename = d['tensors_filename']
if load_tensors and tensors_filename is not None:
dirname = os.path.dirname(json_path)
tensors_path = os.path.join(dirname, tensors_filename)
new_sae.load_tensors(tensors_path, in_zipfile)
return new_sae