-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrain_gpt2_ben.py
2243 lines (1820 loc) · 99.1 KB
/
train_gpt2_ben.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
from dataclasses import dataclass
import torch
import torch.nn as nn
from torch.nn import functional as F
import math
import tiktoken
import time
import hellaswag
import torch.autograd as autograd
def log1mexp(x: torch.Tensor) -> torch.Tensor:
"""Numerically accurate evaluation of log(1 - exp(x)) for x < 0.
See [Maechler2012accurate]_ for details.
"""
mask = -math.log(2) < x # x < 0
return torch.where(
mask,
(-x.expm1()).log(),
(-x.exp()).log1p(),
)
class DualModule(nn.Module):
def __init__(self):
super(DualModule, self).__init__()
class BenNorm(nn.Module):
def __init__(self):
pass
def forward(self, x):
return x / x.max(dim=-1, keepdim=True).values
class SigmoidAttention(nn.Module):
def __init__(self, config):
super().__init__()
assert config.n_embd % config.n_head == 0
# key, query, value projections for all heads, but in a batch
self.c_attn = nn.Linear(config.n_embd, 3 * config.n_embd)
self.n_head = config.n_head
self.n_embd = config.n_embd
# flash attention make GPU go brrrrr but support is only in PyTorch >= 2.0
self.register_buffer("bias", torch.tril(torch.ones(config.block_size, config.block_size),diagonal=-1).view(1, 1, config.block_size, config.block_size))
def forward(self, x, z):
B, T, C = x.size() # batch size, sequence length, embedding dimensionality (n_embd)
# calculate query, key, values for all heads in batch and move head forward to be the batch dim
q, k, v = self.c_attn(x).split(self.n_embd, dim=2)
k = k.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
q = q.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
v = v.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
# manual implementation of attention
att = (q @ k.transpose(-2, -1)) * (1.0 / math.sqrt(k.size(-1)))
att = att.masked_fill(self.bias[:,:,:T,:T] == 0, float('-inf'))
att = F.sigmoid(att) #broadcasts, .view(1, 1, T, T) # (B, nh, T, T)
y = att @ z.unsqueeze(1) # (B, nh, T, T) x (B, nh, T, hs) -> (B, nh, T, n_embd)
y = y.sum(dim=1) # sum up the head dimension
return y
class GeLUAttention(nn.Module):
def __init__(self, config):
super().__init__()
assert config.n_embd % config.n_head == 0
# key, query, value projections for all heads, but in a batch
self.c_attn = nn.Linear(config.n_embd, 3 * config.n_embd)
self.n_head = config.n_head
self.n_embd = config.n_embd
self.c_proj = nn.Linear(config.n_embd, config.n_embd)
self.register_buffer("bias", torch.tril(
torch.ones(config.block_size, config.block_size))
.view(1,1,config.block_size,config.block_size)
)
self.gelu = nn.GELU(approximate='tanh')
def forward(self, x, z=None,print_weights=False):
B, T, C = x.size() # batch size, sequence length, embedding dimensionality (n_embd)
# calculate query, key, values for all heads in batch and move head forward to be the batch dim
q, k, v = self.c_attn(x).split(self.n_embd, dim=2)
k = k.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
q = q.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
v = v.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
# manual implementation of attention
att = (q @ k.transpose(-2, -1)) * (1.0 / math.sqrt(k.size(-1)))
# mask = torch.triu(torch.ones(T, T, device=x.device), diagonal=1).bool() # Upper triangular matrix with diagonal offset by 1
# mask = mask.unsqueeze(0).unsqueeze(0)
# # mask = self.bias[:, :, :T, :T] == 0
# att = att.masked_fill(mask, float('-inf'))
att = self.gelu(att) #broadcasts, .view(1, 1, T, T) # (B, nh, T, T)
att = att.masked_fill(self.bias[:,:,:T,:T] == 0, 0.0)
# if print_weights:
# with torch.no_grad():
# torch.set_printoptions(linewidth=300, sci_mode=False)
# bprint(f"Attn {T} {att[-1,-1,:,:]}") #TODO uncomment
y = att @ v
# # attention
# att = (q @ k.transpose(-2, -1)) * (1.0 / math.sqrt(k.size(-1)))
# mask = torch.triu(torch.ones(T, T, device=x.device), diagonal=1).bool() # Upper triangular matrix with diagonal offset by 1
# mask = mask.unsqueeze(0).unsqueeze(0)
# # mask = self.bias[:, :, :T, :T] == 0
# att = att.masked_fill(mask, float('-inf')) # only attend to historic tokens
# # att = F.softmax(att, dim=-1) # normalize attention
# # y = att @ v # (B, nh, T, T) x (B, nh, T, hs) -> (B, nh, T, hs)
y = y.transpose(1, 2).contiguous().view(B, T, C) # reassemble all head outputs
y = self.c_proj(y)
return y, None, None
# The general idea:
# input stream is not tokens, but embedded tokens
# evaluate a single layer
# compute loss for the previous layer using confidence of current layer
# have some confidence threshold for "what we consider external output"
# if previous layer was already very confident (i.e. "output something"), then evaluate that output against the true target
class CausalSelfAttention(DualModule):
"""In parallel multiple heads/streams, outputs concatenated"""
def __init__(self, config):
super().__init__()
assert config.n_embd % config.n_head == 0
# key, query batched for all heads
if not VALUE_MATRIX:
self.c_attn = nn.Linear(config.n_embd, 2*config.n_embd, bias=False)
else:
self.c_attn = nn.Linear(config.n_embd, 3*config.n_embd, bias=False)
# value (normally, we should batch) self.c_attn_value = nn.Linear(config.n_embd, 3*config.n_embd, bias=False)
# self.c_attn_value = nn.Linear(config.n_embd, config.n_embd, bias=False)
self.c_proj = nn.Linear(config.n_embd, config.n_embd)
self.c_proj.NANOGPT_SCALE_INIT = 1 # a flag for scaling initialization to compensate for increase in variance due to residual connections (variance grows if I keep summing)
# regularization
self.n_head = config.n_head
self.n_embd = config.n_embd
self.ln = nn.LayerNorm(config.n_embd, elementwise_affine=ELEMENTWISEAFFINE)
if ATTN_LAYER_NORM:
self.ln1 = nn.LayerNorm(config.n_embd, elementwise_affine=ELEMENTWISEAFFINE)
self.ln2 = nn.LayerNorm(config.n_embd, elementwise_affine=ELEMENTWISEAFFINE)
self.ln3 = nn.LayerNorm(config.n_embd, elementwise_affine=ELEMENTWISEAFFINE)
self.cachedResW = None
# self.cachedY = None
# Don't need this once we switched to flashattention
# # not really a 'bias', more of a mask, following OpenAI naming
# self.register_buffer("bias", torch.tril(
# torch.ones(config.block_size, config.block_size))
# .view(1,1,config.block_size,config.block_size)
# )
# no zeros
# @flag attention mask [ATTENTION_MASK]
# if ATTENTION_MASK:
# if ATTENTION_SINK:
# T = config.block_size + 1
# else:
# T = config.block_size
# mask = torch.triu(torch.ones(T, T),diagonal=1)
# mask = torch.where(mask == 1, float("-inf"), torch.tensor(0.0))
# if ATTENTION_SINK:
# mask[:,0] = 2*(torch.arange(0, T) + 1).log()
# mask = mask.view(1, 1, T, T)
# self.register_buffer("mask", mask)
# @endflag attention mask
# print(torch.diagonal(self.mask, dim1=-2, dim2=-1).sum().item())
if DELETE_SELF_CONTRIBUTION or EXTRACT_SELF_CONTRIBUTION:
T = config.block_size
self.register_buffer("nodiagonal", (1 - torch.eye(T, T)).view(1, 1, T, T))
# # ^ 0s on diagonal, 1 everywhere else
def forward(self, x, z=None,print_weights=False):
# x used to compute Q, K; z replaces v if VALUE_MATRIX = False
# z must be same dim as x
B, T, C = x.size()
TwithCache = T
metadata = {}
# calculate query, key, value for all heads in batch and move head forward to be the batch
# nh is "number of heads", hs is "head size", C is number of channels is nh * hs
# e.g. GPT2 (124M), n_head = 12, hs = 64, nh*hs=C=768 channels
# each token emits three vectors query, key, value
if VALUE_MATRIX or z is None:
kqv = self.c_attn(x) # (B, T, C) -> (B, T, 2*C)
k,q,v = kqv.split(self.n_embd, dim=2)
if ATTENTION_SINK:
# (1, 1, C)
# add an all zeros token to beginning x ("Zero Sink" from literature)
s = torch.zeros(B, 1, C, device=x.device, dtype=x.dtype) # (B, 1, C)
k = torch.cat((s, k), dim=1)
v = torch.cat((s, v), dim=1)
# ^ (B, T, C) -> (B, T+1, C)
TwithCache = k.size(1)
if ATTN_LAYER_NORM:
q = self.ln1(q)
k = self.ln2(k)
v = self.ln3(v)
v = v.view(B, TwithCache, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
# # NOTE: don't need the below because we are not calculating ResW
# if ATTENTION_SINK_ROUTER:
# # NOTE: commandeer the last dimension to hold our data (the network
# # better not store anything useful there)
# extra_zeros = torch.ones(C // self.n_head, device=x.device, dtype=x.dtype) # (hs)
# extra_zeros[-1] = 0
# v = v * extra_zeros # zero out the last dimension (broadcast)
# v[:, :, 0, :] = 0 # zero out first token everywhere
# v[:, :, 0, -1] = 1
if MEASURE_SELF_CONTRIBUTION or DELETE_SELF_CONTRIBUTION or EXTRACT_SELF_CONTRIBUTION:
v2 = v
v = torch.eye(T, device=x.device).view(1, 1, T, T) # (B, nh, T, T)
# TODO a faster way to get the diagonal?
else:
qk = self.c_attn(x)
q,k = qk.split(self.n_embd, dim=2)
v = torch.eye(T, device=x.device).view(1, 1, T, T) # (B, nh, T, T)
# v = z.unsqueeze(1) # (B, 1, T, C)
# if print_weights:
# bprint(f"Kraw: {k[-1, -1, :10]}")
# bprint(f"Qraw: {q[-1, -1, :10]}")
# treat heads as batches
k = k.view(B, TwithCache, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
q = q.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
with torch.no_grad():
metadata["q_norm_mean"] = f"{torch.linalg.norm(q, dim=-1).mean():.4f}"
metadata["k_norm_mean"] = f"{torch.linalg.norm(k, dim=-1).mean():.4f}"
metadata["v_norm_mean"] = f"{torch.linalg.norm(v, dim=-1).mean():.4f}"
# TODO figure out what is wrong with the below code and why it breaks training if we use it instead of the pytorch version
# # Note: C = n_embd
# # head size = C // self.n_head = 64
# # FlashAttention: fuse kernels for attention
# # Does more flops (tradeoff) but because of operator fusion, much faster
# # In particular, att never gets written to global memory (T x T = 1024 * 1024)
# # attention
# att = (q @ k.transpose(-2, -1)) * (1.0 / math.sqrt(k.size(-1)))
# mask = torch.triu(torch.ones(T, T, device=x.device), diagonal=1).bool() # Upper triangular matrix with diagonal offset by 1
# mask = mask.unsqueeze(0).unsqueeze(0)
# # mask = self.bias[:, :, :T, :T] == 0
# att = att.masked_fill(mask, float('-inf')) # only attend to historic tokens
# att = F.softmax(att, dim=-1) # normalize attention
# y = att @ v # (B, nh, T, T) x (B, nh, T, hs) -> (B, nh, T, hs)
# Just have Pytorch use FlashAttention for us. #TODO NVM
# y = F.scaled_dot_product_attention(q, k, v, is_causal=True)
# if print_weights:
# bprint(f"dtype {self.mask.dtype}")
# # bprint(f"my mask: {self.mask[:,:,:T,:T]}")
if ATTENTION_MASK:
y = F.scaled_dot_product_attention(q, k, v, attn_mask=self.mask[:,:,:T,:T])
else:
# was is_causal=True
from torch.nn.attention.bias import causal_lower_right
attn_bias = causal_lower_right(T, TwithCache)
y = F.scaled_dot_product_attention(q, k, v, attn_bias)
if print_weights and PRINT_ATTN_WEIGHTS:
with torch.no_grad():
vv = torch.eye(TwithCache, device=x.device).view(1, 1, TwithCache, TwithCache)
if ATTENTION_MASK:
yy = F.scaled_dot_product_attention(q.detach(), k.detach(), vv, attn_mask=self.mask[:,:,:T,:T])
else:
yy = F.scaled_dot_product_attention(q.detach(), k.detach(), vv, attn_bias)
torch.set_printoptions(linewidth=600, sci_mode=False)
# bprint(f"Attn {TwithCache} {yy[-1,-1,:,:]}") #TODO uncomment
rawATT = q @ k.transpose(-2, -1) * (1.0 / math.sqrt(k.size(-1)))
norm = torch.linalg.norm(rawATT[-1,-1,:,:], dim=-1).mean()
bprint(f"Attn {norm} {rawATT[-1,-1,:,:]}")
deterK, _ = torch.linalg.eig(self.c_attn.weight[:self.n_embd, :])
deterQ, _ = torch.linalg.eig(self.c_attn.weight[self.n_embd:2*self.n_embd, :])
deterV, _ = torch.linalg.eig(self.c_attn.weight[self.n_embd*2:, :])
bprint(f"\Eigenvals: k {deterK.abs().topk(k=20)}\nq {deterQ.abs().topk(k=20)}\nv {deterV.abs().topk(k=20)}")
#TODO uncomment
# bprint(f"Kweights\n{self.c_attn.weight[:self.n_embd, :]}")
# bprint(f"K: {k[-1, -1, -1, :]}")
# bprint(f"Qweights\n{self.c_attn.weight[self.n_embd:2*self.n_embd, :]}")
# bprint(f"Q: {q[-1, -1, -1, :]}")
# bprint(f"RAWVALUES (nomask)\n{rawATT[-1,-1,:,:]}")
# if ATTENTION_MASK:
# bprint(f"RAWVALUES (withmask)\n{rawATT[-1,-1,:,:] + self.mask[:,:,:T,:T]}")
# if self.cachedResW is not None:
# torch.set_printoptions(linewidth=200, sci_mode=True, threshold=float('inf'))
# bprint(f"GRAD\n{self.cachedResW.grad[-1, -8:, :]}")
# # bprint(f"========")
# y = F.scaled_dot_product_attention(q, k, v, attn_mask=self.mask[:,:,:T,:T])
# ^ need to do the [:,:,:T,:T] because sometimes T is smaller than block_size (i.e. when doing inference on small prompts)
scores = None
if VALUE_MATRIX or z is None:
if MEASURE_SELF_CONTRIBUTION:
# y is currently attention matrix
scores = torch.diagonal(y, dim1=-2, dim2=-1).detach() # (B, nh, T)
scores = scores.sum(dim=1).unsqueeze(-1) # (B, T, 1)
if EXTRACT_SELF_CONTRIBUTION:
# v2 is (B, nh, T, hs)
# diagonal ith location is how much ith column attends with itself
resx = torch.diagonal(y, dim1=-2, dim2=-1).unsqueeze(-1) * v2 # (B, nh, T, hs)
resx = resx.transpose(1, 2).contiguous().view(B, T, C)
resx = self.c_proj(resx) # (B, T, C) -> (B, T, C)
if DELETE_SELF_CONTRIBUTION or EXTRACT_SELF_CONTRIBUTION:
y = y*self.nodiagonal[:,:,:T,:T] # delete the self contribution
if MEASURE_SELF_CONTRIBUTION or DELETE_SELF_CONTRIBUTION or EXTRACT_SELF_CONTRIBUTION:
y = y @ v2
# if ATTENTION_SINK_ROUTER:
# # y[:,:,:,-1] currently contains for each B, head, T, the weight
# # assigned to the attention sink.
# # we only use the head with the lowest attention score.
# # y has size (B, nh, T, hs)
# # y[:,:,:,-1] has size (B, nh, T)
# _, idxs = y[:,:,:,-1].topk(1, dim=1, largest=False)
# # idxs should have size (B, 1, T)
# B_idxs = torch.arange(B, device=y.device).view(B, 1, 1).expand(-1, 1, T)
# T_idxs = torch.arange(T, device=y.device).view(1, 1, T).expand(B, 1, -1)
# y = y[B_idxs,idxs,T_idxs,:]
# y = y.squeeze(dim=1) # (B, 1, T, hs) -> (B, T, hs)
# y = self.c_proj(y) # (B, T, hs) -> (B, T, C)
# # # y is (B, nh, T, hs), but last dimension is useless
# # resw = y[:,:,:,-1].sum(dim=1).unsqueeze(-1) / self.n_head # (B, T, 1)
# # # print(f"RESWMean: {resw[:, 1:, :].mean()}")
# # if print_weights:
# # torch.set_printoptions(linewidth=200, sci_mode=False)
# # bprint(f"RESW: {resw[-1, :, :]}") # last batch
# # # resw = torch.ones(B, T, 1, device=x.device, dtype=x.dtype)
# # # self.cachedResW = resw
# # # self.cachedResW.requires_grad_(True)
# # # self.cachedResW.retain_grad()
# # # belwo unnecessary? should be learned by proj matrix or mlp TODO check
# # # y = y * extra_zeros # zero out the last row again
else:
y = y.transpose(1, 2).contiguous().view(B, T, C) # reassemble all head outputs side by side
# (B, T, n_embd)
# output projection
y = self.c_proj(y) # NOTE: what is the point of this (to support dimension reduction from before, i don't think we actualy need to do dimension reduction)
else:
# TODO ATTENTION SINK NOT SUPPORTED YET
if MEASURE_SELF_CONTRIBUTION:
# without value matrix: (B, nh, T, T)
scores = torch.diagonal(y, dim1=-2, dim2=-1).detach() # (B, nh, T)
scores = scores.sum(dim=1).unsqueeze(-1) # (B, T, 1)
if EXTRACT_SELF_CONTRIBUTION:
resx = torch.diagonal(y, dim1=-2, dim2=-1).unsqueeze(-1) * z.unsqueeze(1) # (B, nh, T, 1) * (B, 1, T, C)
resx = resx.sum(dim=1) / self.n_head
if DELETE_SELF_CONTRIBUTION or EXTRACT_SELF_CONTRIBUTION:
y = y*self.nodiagonal[:,:,:T,:T] # delete the self contribution
y = y @ z.unsqueeze(1) # (B, nh, T, T) @ (B, 1, T, C) -> (B, nh, T, C)
y = y.sum(dim=1) / self.n_head # sum up the head dimension
return y, metadata
class Gate(DualModule):
def __init__(self, config):
super().__init__()
self.c_fc = nn.Linear(config.n_embd, 4 * config.n_embd)
# smoother ReLU, also maybe helps dead neurons empirically?
# (should just delete dead neurons)
self.gelu = nn.GELU(approximate='tanh') # should just use 'none' if not trying to copy GPT2
self.c_proj = nn.Linear(4 * config.n_embd, config.n_embd)
def forward(self, x):
x = self.c_fc(x)
x = self.gelu(x)
x = self.c_proj(x)
x = x.sum(dim=-1, keepdim=True) # sum over the last dimension
x = torch.sigmoid(x)
return x
class MLPFewParams(nn.Module):
def __init__(self, config):
super().__init__()
self.inputWidth = config.n_embd
self.hiddenWidth = MLP_HIDDENWIDTH_INTERPRETER
self.gelu = nn.GELU(approximate='tanh') # consider using somehting else
# TODO: should inner matrix really be square?
self.fU = nn.Parameter(torch.empty(MLPMAT_INNER_SIZE, self.inputWidth))
self.fV = nn.Parameter(torch.empty(self.hiddenWidth, MLPMAT_INNER_SIZE))
self.bU = nn.Parameter(torch.empty(MLPMAT_INNER_SIZE, self.hiddenWidth))
self.bV = nn.Parameter(torch.empty(self.inputWidth, MLPMAT_INNER_SIZE))
torch.nn.init.normal_(self.fU, mean=0.0, std=0.02)
torch.nn.init.normal_(self.fV, mean=0.0, std=0.02)
torch.nn.init.normal_(self.bU, mean=0.0, std=0.02)
torch.nn.init.normal_(self.bV, mean=0.0, std=0.02)
def forward(self, x, front, back, hiddenBias):
B, T, paramSize = front.size()
B2, T2, paramSize2 = back.size()
B3, T3, C = x.size()
B4, T4, hiddenWidth = hiddenBias.size()
assert hiddenWidth == self.hiddenWidth, f"pMLPMAT wrong hidden width {hiddenWidth} {self.hiddenWidth}"
assert B == B2 and T == T2 and paramSize == paramSize2, f"Parametrized MLP misconfig {B} {T} {paramSize} {B2} {T2} {paramSize2}"
assert B == B3 and T == T3, f"pMLPMAT wrong x size {B} {T} {B3} {T3}"
assert MLPMAT_INNER_SIZE**2 == paramSize, f"pMLPMAT misconfig {MLPMAT_INNER_SIZE} {paramSize}"
compressedFront = front.view(B, T, MLPMAT_INNER_SIZE, MLPMAT_INNER_SIZE)
compressedBack = back.view(B, T, MLPMAT_INNER_SIZE, MLPMAT_INNER_SIZE)
x = x.unsqueeze(-1) # (B, T, C, 1)
# apply the forward MLP
x = (self.fV @ (compressedFront @ (self.fU @ x))) # (B, T, hidden_width, 1)
x = x + hiddenBias.unsqueeze(-1)
# apply gelu
x = self.gelu(x)
# apply the backward MLP
x = (self.bV @ (compressedBack @ (self.bU @ x))) # (B, T, inputWidth, 1)
x = x.squeeze(-1)
# NOTE: last layer probably doesn't need a bias, see `14-nooutlinearbiasmlp` experiment
return x
class BenCompiler(nn.Module):
def __init__(self, config):
super().__init__()
self.c_fc = nn.Linear(config.n_embd, MLP_SCALE * config.n_embd)
# smoother ReLU, also maybe helps dead neurons empirically?
# (should just delete dead neurons)
self.gelu = nn.GELU(approximate='tanh') # should just use 'none' if not trying to copy GPT2
self.c_proj = nn.Linear(MLP_SCALE * config.n_embd, MLP_HIDDENWIDTH_INTERPRETER + 2*MLPMAT_INNER_SIZE*MLPMAT_INNER_SIZE)
self.c_proj.NANOGPT_SCALE_INIT = 1
self.n_embd = config.n_embd
def forward(self, x):
x = self.c_fc(x)
x = self.gelu(x)
x = self.c_proj(x)
hiddenBias, fParams, bParams = x.split([MLP_HIDDENWIDTH_INTERPRETER, MLPMAT_INNER_SIZE*MLPMAT_INNER_SIZE, MLPMAT_INNER_SIZE*MLPMAT_INNER_SIZE], dim=-1)
return hiddenBias, fParams, bParams
class BenCompiler2(nn.Module):
def __init__(self, config):
super().__init__()
self.c_fc = nn.Linear(config.n_embd, MLP_SCALE * config.n_embd)
# smoother ReLU, also maybe helps dead neurons empirically?
# (should just delete dead neurons)
self.gelu = nn.GELU(approximate='tanh') # should just use 'none' if not trying to copy GPT2
self.c_proj = nn.Linear(MLP_SCALE * config.n_embd, config.n_embd + MLPMAT_INNER_SIZE*MLPMAT_INNER_SIZE)
# self.c_proj.NANOGPT_SCALE_INIT = 1
self.n_embd = config.n_embd
def forward(self, x):
x = self.c_fc(x)
x = self.gelu(x)
x = self.c_proj(x)
hiddenBias, fParams = x.split([self.n_embd, MLPMAT_INNER_SIZE*MLPMAT_INNER_SIZE], dim=-1)
return {"bias": hiddenBias, "fparams": fParams}
class MLPMatApply(nn.Module):
def __init__(self, config):
super().__init__()
self.U = nn.Parameter(torch.empty(config.n_embd, MLPMAT_INNER_SIZE))
self.V = nn.Parameter(torch.empty(MLPMAT_INNER_SIZE, config.n_embd))
torch.nn.init.normal_(self.U, mean=0.0, std=0.02)
torch.nn.init.normal_(self.V, mean=0.0, std=0.02)
def forward(self, program, attn):
# m has dimension (B, T, 3*C)
m = program["fparams"]
bias = program["bias"]
B, T, matnumparams = m.size()
assert MLPMAT_INNER_SIZE**2 == matnumparams, f"MLPMAT misconfig {MLPMAT_INNER_SIZE} {matnumparams}"
m = m.view(B, T, MLPMAT_INNER_SIZE, MLPMAT_INNER_SIZE)
attn = attn.unsqueeze(-1) # (B, T, C, 1)
# self.U @ m --> (C, 48) @ (B, T, 48, 48) = (B, T, C, 48)
# Above @ V --> (B, T, C, 48) @ (48, C) = (B, T, C, C)
# Above @ attn --> (B, T, C, C) @ (B, T, C, 1) = (B, T, C, 1)
return (self.U @ (m @ (self.V @ attn))).squeeze(-1) + bias
class BenCompilerNoOp(nn.Module):
def __init__(self, config):
super().__init__()
def forward(self, x):
return x
class MLPConcat(nn.Module):
def __init__(self, config):
super().__init__()
self.c_fc = nn.Linear(config.n_embd * 2, MLP_SCALE * config.n_embd)
# smoother ReLU, also maybe helps dead neurons empirically?
# (should just delete dead neurons)
self.gelu = nn.GELU(approximate='tanh') # should just use 'none' if not trying to copy GPT2
self.c_proj = nn.Linear(MLP_SCALE * config.n_embd, config.n_embd, bias=False)
self.c_proj.NANOGPT_SCALE_INIT = 1
self.ln = nn.LayerNorm(config.n_embd, elementwise_affine=ELEMENTWISEAFFINE)
def forward(self, x, attn):
x = self.ln(x)
z = torch.cat((x, attn), dim=-1) # (B, T, 2C)
x = self.c_fc(z)
x = self.gelu(x)
x = self.c_proj(x)
return x
# @flag machine_code [UNSET]
class MultExecute(nn.Module):
def __init__(self, config):
super().__init__()
self.mlp = MLP(config)
def forward(self, program, attn):
return self.mlp(program) * attn
# @endflag machine_code
class BenExecute(nn.Module):
def __init__(self, config):
super().__init__()
self.mlp = MLPConcat(config)
def forward(self, program, attn):
return self.mlp(program, attn)
class MLPSoftmaxExecute(nn.Module):
def __init__(self, config):
super().__init__()
self.c_fc = nn.Linear(config.n_embd, MLP_SCALE * config.n_embd)
self.c_proj = nn.Linear(MLP_SCALE * config.n_embd, config.n_embd, bias=False)
self.c_proj.NANOGPT_SCALE_INIT = 1
self.ln_2 = nn.LayerNorm(config.n_embd, elementwise_affine=ELEMENTWISEAFFINE)
def forward(self, x, attn):
# @noflag mlpalt
inp = self.ln_2(x + attn) # (B, T, n)
y = self.c_fc(inp) # (B, T, 4n)
y = y*F.softmax(y, dim=-1) # (B, T, 4n)
mlp = self.c_proj(y)
return mlp + attn
# @noendflag mlpalt
class VanillaExecute(nn.Module):
def __init__(self, config):
super().__init__()
self.c_fc = nn.Linear(config.n_embd, MLP_SCALE * config.n_embd)
# smoother ReLU, also maybe helps dead neurons empirically?
# (should just delete dead neurons)
self.gelu = nn.GELU(approximate='tanh') # should just use 'none' if not trying to copy GPT2
self.c_proj = nn.Linear(MLP_SCALE * config.n_embd, config.n_embd, bias=False)
self.c_proj.NANOGPT_SCALE_INIT = 1
# self.ln_2 = nn.LayerNorm(config.n_embd, elementwise_affine=ELEMENTWISEAFFINE)
# self.ln_0 = nn.LayerNorm(config.n_embd, elementwise_affine=ELEMENTWISEAFFINE)
# self.ln_1 = nn.LayerNorm(config.n_embd, elementwise_affine=ELEMENTWISEAFFINE)
def forward(self, x):
# return self.ln_2(attn)
# self.ln_2(x + attn)
y = self.c_fc(x)
y = self.gelu(y)
mlp = self.c_proj(y)
return mlp
class NoAttnExecute(nn.Module):
def __init__(self, config):
super().__init__()
self.c_fc = nn.Linear(config.n_embd, MLP_SCALE * config.n_embd)
self.gelu = nn.GELU(approximate='tanh') # should just use 'none' if not trying to copy GPT2
self.c_proj = nn.Linear(MLP_SCALE * config.n_embd, config.n_embd, bias=False)
self.c_proj.NANOGPT_SCALE_INIT = 1
self.ln_2 = nn.LayerNorm(config.n_embd, elementwise_affine=ELEMENTWISEAFFINE)
def forward(self, x, attn):
inp = self.ln_2(x)
y = self.c_fc(inp)
y = self.gelu(y)
mlp = self.c_proj(y)
return mlp
class BenBlock(nn.Module):
def __init__(self, config):
super().__init__()
self.ln_1 = nn.LayerNorm(config.n_embd, elementwise_affine=ELEMENTWISEAFFINE)
self.ln_2 = nn.LayerNorm(config.n_embd, elementwise_affine=ELEMENTWISEAFFINE)
self.ln_5 = nn.LayerNorm(config.n_embd, elementwise_affine=ELEMENTWISEAFFINE)
self.ln_6 = nn.LayerNorm(config.n_embd, elementwise_affine=ELEMENTWISEAFFINE)
self.n_head = config.n_head
self.n_layer = config.n_layer
# @flag machine_modules
self.attn = CausalSelfAttention(config)
self.mlp = VanillaExecute(config)
# @endflag machine_modules
# self.throughput = nn.Parameter(torch.tensor(-2.0))
# torch.nn.init.normal_(self.throughput, mean=-2.0, std=0.02)
# self.mlp = MLP(config)
def forward(self, x, print_weights=False,step=0, metadata={}):
if step > 3 and step < self.n_layer - 3:
print_weights = False
# stronger attention should result in machineOutput with larger norm,
# which should then get normalized; then learning to output a larger norm
# vs a smaller norm is our mechanism for gating attention
# First LN important to make sure the signal to attn does not get too small.
# cannot LN the output, why?
# @flag block_logic
y = self.ln_1(x)
attn, _metadata = self.attn(y, y, print_weights=print_weights)
x = x + attn
newx = x + self.ln_2(self.mlp(x))
# @endflag block_logic
# as opposed to Pre-LN
# x = x + self.attn(self.ln_1(x))
# x = x + self.mlp(self.ln_2(x))
# Post-LN
for key in _metadata:
metadata[key] = metadata.get(key, []) + [_metadata[key]]
metadata["_norm_attn"] = attn.std(dim=-1).mean() / self.n_layer #torch.linalg.norm(attn, dim=-1).mean().item()
metadata["_norm_y"] = 0.0 / self.n_layer # should be 1 / 12
metadata["_norm_x"] = x.std(dim=-1).mean() / self.n_layer
metadata["_norm_output"] = 0.0 / self.n_layer
x = newx
# if scores is not None:
# a = scores.detach()
# metadata["zero"] = (a < 5).sum().item()
# metadata["neg"] = (a < 0.5).sum().item()
# metadata["pos"] = (a > 5).sum().item()
return x, metadata
class ApplyMatrixFromFewParams(nn.Module):
def __init__(self, config):
super().__init__()
self.U = nn.Parameter(torch.empty(config.n_embd, MLPMAT_INNER_SIZE))
self.V = nn.Parameter(torch.empty(MLPMAT_INNER_SIZE, config.n_embd))
torch.nn.init.normal_(self.U, mean=0.0, std=0.02)
torch.nn.init.normal_(self.V, mean=0.0, std=0.02)
def forward(self, m, attn):
# m has dimension (B, T, 3*C)
B, T, matnumparams = m.size()
assert MLPMAT_INNER_SIZE**2 == matnumparams, f"MLPMAT misconfig {MLPMAT_INNER_SIZE} {matnumparams}"
m = m.view(B, T, MLPMAT_INNER_SIZE, MLPMAT_INNER_SIZE)
attn = attn.unsqueeze(-1) # (B, T, C, 1)
# self.U @ m --> (C, 48) @ (B, T, 48, 48) = (B, T, C, 48)
# Above @ V --> (B, T, C, 48) @ (48, C) = (B, T, C, C)
# Above @ attn --> (B, T, C, C) @ (B, T, C, 1) = (B, T, C, 1)
return (self.U @ (m @ (self.V @ attn))).squeeze(-1)
class MLP(DualModule):
def __init__(self, config):
super().__init__()
self.c_fc = nn.Linear(config.n_embd, MLP_SCALE * config.n_embd)
# smoother ReLU, also maybe helps dead neurons empirically?
# (should just delete dead neurons)
self.gelu = nn.GELU(approximate='tanh') # should just use 'none' if not trying to copy GPT2
self.c_proj = nn.Linear(MLP_SCALE * config.n_embd, config.n_embd, bias=False)
self.c_proj.NANOGPT_SCALE_INIT = 1
def forward(self, x):
x = self.c_fc(x)
x = self.gelu(x)
x = self.c_proj(x)
return x
class FatMLP(DualModule):
def __init__(self, config):
super().__init__()
self.c_fc = nn.Linear(config.n_embd, MLP_SCALE * config.n_embd)
# smoother ReLU, also maybe helps dead neurons empirically?
# (should just delete dead neurons)
self.gelu = nn.GELU(approximate='tanh') # should just use 'none' if not trying to copy GPT2
self.c_proj = nn.Linear(MLP_SCALE * config.n_embd, config.n_embd + MATRIX_NUM_PARAMS)
self.c_proj.NANOGPT_SCALE_INIT = 1
self.n_embd = config.n_embd
def forward(self, x):
x = self.c_fc(x)
x = self.gelu(x)
x = self.c_proj(x)
b, m = x.split([self.n_embd, MATRIX_NUM_PARAMS], dim=-1)
return m, b
class VanillaBlock(nn.Module):
def __init__(self, config):
super().__init__()
self.ln_1 = nn.LayerNorm(config.n_embd, elementwise_affine=ELEMENTWISEAFFINE)
self.attn = CausalSelfAttention(config)
self.ln_2 = nn.LayerNorm(config.n_embd, elementwise_affine=ELEMENTWISEAFFINE)
self.mlp = MLP(config)
self.n_head = config.n_head
def forward(self, x,print_weights=False):
# # VANILLA
# x = x + self.attn(self.ln_1(x))
# x = x + self.mlp(self.ln_2(x))
# # AXM
# y = self.ln_1(x)
# x = x + self.attn(y)*self.mlp(y)
# y = self.ln_1(x)
# attn = self.attn(y)
# m, bias = self.fatmlp(y) # (B, T, 3*C), (B,T,C)
# M = self.applymat(m, attn) #(B, T, 3*C), (B, T, C) -> (B, T, C)
# x = M + bias + x
metadata = {}
# y = self.ln_1(x)
# attn = self.attn(y,y)
# siz = torch.linalg.vecdot(y, y,dim=-1).unsqueeze(-1) # (B, T, 1)
# app = torch.linalg.vecdot(attn, y,dim=-1).unsqueeze(-1) / siz # may be greater than 1
# app = (torch.sigmoid(torch.abs(app)) - 0.5) * 2 # [0, 1]
# m, bias = self.fatmlp(y)
# M = self.applymat(m, attn) #(B, T, 3*C), (B, T, C) -> (B, T, C)
# x = M + bias + x
# scores is (B, T, 1)
# y = self.ln_1(x)
# attn, scores = self.attn(y, y)
# x = x + self.mlp(attn)
y = self.ln_1(x)
attn, scores = self.attn(y, y,print_weights=print_weights)
x = x + attn
x = y + self.mlp(self.ln_2(x))
# print(scores[-1,-1,-1])
if scores is not None:
a = scores.detach()
metadata["zero"] = (a < 5).sum().item()
metadata["neg"] = (a < 0.5).sum().item()
metadata["pos"] = (a > 5).sum().item()
return x, metadata
class Block(DualModule):
def __init__(self, config):
super().__init__()
self.ln = nn.RMSNorm(config.n_embd, elementwise_affine=ELEMENTWISEAFFINE)
self.attn = CausalSelfAttention(config)
self.gate = Gate(config)
self.mlp = MLP(config)
# self.rotator = nn.Linear(config.n_embd, config.n_embd)
def forward(self, x, res, y):
# note residual connection res
# out = self.ln_1(x)
# NOTE, for some reason LN(x) + self.attn(LN(x)) doesn't work as well.
# ^ it is incredibly important that the residual is not passed through the layer norm... (TODO why??? Layers can no-op?)
# x = x + self.attn(self.ln_1(x)) # reduce operation (all to all)
# NOTE: res will generally be very large...
# mlp2 = self.mlp2(x)
attn = self.attn(x, x)
mlp = self.mlp(x)
midx = mlp
y = mlp*res
x = y + res + attn
newres = x
x = self.ln(x)
# res + self.attn(x) # NOTE that the residual connection x is already layer normed, unlike usual transformer implementation # TODO add back residual res + . NOTE x + self.attn(x) is simply horrible (why?)... we cannot layer norm it (prev too big or too small?)
# Maybe the layernorm just destroys relative magnitude of things...
# NOTE, likewise LN(x) + mlp(LN(x)) doesn't work as well? The residual literally has to be untouched.
# midx = y # TODO UNCOMMENT, and then try removing res (applying attn to res)
# NOTE: NEXT is usually ~1.0, prev is usually < 1.0 early on.
# NOTE: By step 116, prev is much larger, ~2.0
# also seems to get bigger as layer number grows...
# so the layer norm really makes things bigger.
# NOTE: if x + self.mlp, prev grows much much quicker, ~30 by step 48
# ^ but it seems to get a bit smaller over time
# Large (and increasing over layer num) prev remains true even if we don't
# compute loss for every layer. (This is probably due to reuse...)
# NOTE: growth continues even if transformer block is not reused
# ^ again, in vanilla GPT, it gets smaller over time.
# NOTE: for some reason, for res*attn(x) with x*mlp(LN(x)), std is always 0 even for alllayer
# NOTE: doing res * attn(x) and x + mlp(LN(x)) explodes the prev when training last layer only, but when doing all layer loss, it is reasonable... (why?)
# NOTE seems quite good res + attn(x), comment out ln_1
return x, newres, midx, y, attn, mlp, res
@dataclass
class GPTConfig:
block_size: int = 1024
vocab_size: int = 50257 # number of tokens: 50000 BPE merges + 256 bytes tokens + 1 eot token
n_layer: int = 12 # number of layers # NOTE: layers become redundant in my architecture
n_head: int = 12 # number of heads
n_embd: int = 768 # embedding dimensionality
class GPT(DualModule):
def __init__(self, config):
super().__init__()
self.config = config
self.VANILLA = True
sharedBlock = Block(config)
if CODE_MODE:
self.T2 = config.block_size
self.code = nn.Parameter(torch.zeros(self.T2, config.n_embd, dtype=torch.float32))
else:
self.T2 = 0
if self.VANILLA:
if REUSE_WEIGHTS:
sharedBlock = BenBlock(config)
self.transformer = nn.ModuleDict(dict(
wte = nn.Embedding(config.vocab_size, config.n_embd),
wpe = nn.Embedding(config.block_size + self.T2, config.n_embd),
sharedblock = sharedBlock,
ln_f = nn.LayerNorm(config.n_embd, elementwise_affine=ELEMENTWISEAFFINE),
))
else:
self.transformer = nn.ModuleDict(dict(
wte = nn.Embedding(config.vocab_size, config.n_embd),
wpe = nn.Embedding(config.block_size + self.T2, config.n_embd),
h = nn.ModuleList([BenBlock(config) for _ in range(config.n_layer)]),
ln_f = nn.LayerNorm(config.n_embd, elementwise_affine=ELEMENTWISEAFFINE),
))
# @noflag attn_weights [TIE_ATTN_WEIGHTS]
if TIE_ATTN_WEIGHTS:
# Tie model weights together
firstBlock = self.transformer.h[0]
for block in self.transformer.h:
block.attn.c_attn.weight = firstBlock.attn.c_attn.weight
# @noendflag attn_weights
# @flag mlp_weights [TIE_MLP_WEIGHTS]
if TIE_MLP_WEIGHTS:
# Only works with BenBlock, set module to be the same
firstBlock = self.transformer.h[0]
for block in self.transformer.h:
block.execute = firstBlock.execute
# @endflag mlp_weights
else:
self.transformer = nn.ModuleDict(dict(
# weights of token embedding
wte = nn.Embedding(config.vocab_size, config.n_embd),
# weights of position embedding
wpe = nn.Embedding(config.block_size, config.n_embd),
# h = nn.ModuleList([Block(config) for _ in range(config.n_layer)]), # COMMEZNT
sharedblock = sharedBlock, # NOTE: this does not seem to degrade performance at least early in the training process
# weights of layer normalization
ln_f = sharedBlock.ln, # nn.LayerNorm(config.n_embd),
# NOTE we share ALL layer norms which may not be necessarily wise
))
self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
# weight sharing scheme
self.transformer.wte.weight = self.lm_head.weight # copies the data pointer
# self.router = nn.Parameter(torch.zeros(config.n_layer, config.n_layer, dtype=torch.float32))
# param initialization
self.apply(self._init_weights) # apply iterates all submodules
# @flag fixed_attn [NO_GRAD_ATTN]
if NO_GRAD_ATTN:
for block in self.transformer.h:
block.attn.c_attn.weight.requires_grad = False
# @endflag fixed_attn
def _init_weights(self, module):
# No need to change default initialization of LayerNorm
if isinstance(module, nn.Linear):
stdConfig = 0.02
if hasattr(module, 'ATTN_SCALE_INIT'):
#module.weight shoudl have dimension n_embd * 3n_embd
# this should make res 1
N = self.config.n_embd
torch.nn.init.normal_(module.weight[:N,:], mean=-1.0, std=stdConfig)
with torch.no_grad():
module.weight[N:2*N,:] = -1 * module.weight[:N,:]
torch.nn.init.normal_(module.weight[2*N:,:], mean=0.0, std=stdConfig)
elif hasattr(module, 'ATTN_INIT'):
head_size = self.config.n_embd // self.config.n_head
STD_DIM = math.sqrt(1.0 / head_size)
torch.nn.init.normal_(module.weight, mean=0.0, std=STD_DIM) # init to random matrix (todo consider Rademacher matrix or something sparser)
else:
if hasattr(module, 'NANOGPT_SCALE_INIT'):
# 2x because we have two linears per layer: block.attn and block.mlp
stdConfig *= (2 * self.config.n_layer) ** -0.5
torch.nn.init.normal_(module.weight, mean=0.0, std=stdConfig)
if module.bias is not None:
torch.nn.init.zeros_(module.bias)
elif isinstance(module, nn.Embedding):
torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
# @flag init_logic [CODE_MODE]
elif isinstance(module, GPT) and CODE_MODE:
torch.nn.init.normal_(module.code, mean=0.0, std=5)
# @endflag init_logic
def vanillaforward(self, idx, targets=None,print_weights=False):
device = idx.device
b, t = idx.size()
assert t <= self.config.block_size, f"Cannot forward sequence of length {t}, block size is only {self.config.block_size}"
t2 = min(t, self.T2)
# forward the GPT model itself
tok_emb = self.transformer.wte(idx) # token embeddings of shape (b, t, n_embd)