-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathtrain_gpt2.mojo
2098 lines (1769 loc) · 70.1 KB
/
train_gpt2.mojo
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 algorithm import vectorize, parallelize
from collections.vector import InlinedFixedVector
from math import sqrt, exp, tanh, cosh, log
from memory import UnsafePointer, memset, memset_zero, memcpy
from python import Python
from sys import exit
from sys.info import is_apple_silicon, simdwidthof, sizeof
from time import perf_counter_ns
from utils import StringRef
from buffer import Buffer
fn get_simd_width() -> Int:
if is_apple_silicon():
return 4 * simdwidthof[dtype]()
else:
return 2 * simdwidthof[dtype]()
alias dtype = DType.float32 # must be float32 for now
alias dtype_int = DType.int32 # must be int32 for now
alias SIZEOF_FLOAT = sizeof[dtype]()
alias SIZEOF_INT = sizeof[dtype_int]()
alias SIMD_WIDTH = get_simd_width()
alias RU32_HEX = 0x2545F4914F6CDD1D
alias RF32_DIV = 16777216.0
alias FLOAT = SIMD[dtype, 1]
alias INT = SIMD[dtype_int, 1]
alias NULL = UnsafePointer[Scalar[dtype]]()
alias NULL_INT = UnsafePointer[Scalar[dtype_int]]()
alias M_PI: FLOAT = 3.141592653589793115997963468544185161590576171875
alias GPT2_EOT = 50256
alias NUM_PARALLELIZE = 8
alias UNROLL_FACTOR = 4
## ----------------------------------------------------------------------------
# all the individual layers' forward and backward passes
fn encoder_forward(
out: UnsafePointer[Scalar[dtype]],
inp: UnsafePointer[Scalar[dtype_int]],
wte: UnsafePointer[Scalar[dtype]],
wpe: UnsafePointer[Scalar[dtype]],
B: Int,
T: Int,
C: Int,
):
@parameter
fn _calc(b: Int):
for t in range(T):
# seek to the output position in out[b,t,:]
var out_bt: UnsafePointer[Scalar[dtype]] = out + b * T * C + t * C
# get the index of the token at inp[b, t]
var ix = inp[b * T + t]
# seek to the position in wte corresponding to the token
var wte_ix: UnsafePointer[Scalar[dtype]] = wte + int(ix) * C
# seek to the position in wpe corresponding to the position
var wpe_t: UnsafePointer[Scalar[dtype]] = wpe + t * C
# add the two vectors and store the result in out[b,t,:]
@parameter
fn _op[width: Int](iv: Int):
out_bt.store(
iv,
wte_ix.load[width=width](iv) + wpe_t.load[width=width](iv),
)
vectorize[_op, SIMD_WIDTH, unroll_factor=UNROLL_FACTOR](size=C)
parallelize[_calc](B)
fn encoder_backward(
dwte: UnsafePointer[Scalar[dtype]],
dwpe: UnsafePointer[Scalar[dtype]],
dout: UnsafePointer[Scalar[dtype]],
inp: UnsafePointer[Scalar[dtype_int]],
B: Int,
T: Int,
C: Int,
):
@parameter
fn _calc(b: Int):
for t in range(T):
var dout_bt: UnsafePointer[Scalar[dtype]] = dout + b * T * C + t * C
var ix = inp[b * T + t]
var dwte_ix: UnsafePointer[Scalar[dtype]] = dwte + int(ix) * C
var dwpe_t: UnsafePointer[Scalar[dtype]] = dwpe + t * C
@parameter
fn _op[width: Int](iv: Int):
var d = dout_bt.load[width=width](iv)
dwte_ix.store(iv, dwte_ix.load[width=width](iv) + d)
dwpe_t.store(iv, dwpe_t.load[width=width](iv) + d)
vectorize[_op, SIMD_WIDTH, unroll_factor=UNROLL_FACTOR](size=C)
parallelize[_calc](B)
fn layernorm_forward(
out: UnsafePointer[Scalar[dtype]],
mean: UnsafePointer[Scalar[dtype]],
rstd: UnsafePointer[Scalar[dtype]],
inp: UnsafePointer[Scalar[dtype]],
weight: UnsafePointer[Scalar[dtype]],
bias: UnsafePointer[Scalar[dtype]],
B: Int,
T: Int,
C: Int,
):
var eps: FLOAT = 1e-5
@parameter
fn _calc(b: Int):
for t in range(T):
# seek to the input position inp[b,t,:]
var x: UnsafePointer[Scalar[dtype]] = inp + b * T * C + t * C
# calculate the mean
var m: FLOAT = 0.0
@parameter
fn _op[width: Int](iv: Int):
m += x.load[width=width](iv).reduce_add[1]()
vectorize[_op, SIMD_WIDTH, unroll_factor=UNROLL_FACTOR](size=C)
m = m / C
# calculate the variance (without any bias correction)
var v: FLOAT = 0.0
@parameter
fn _op2[width: Int](iv: Int):
var xshift = x.load[width=width](iv) - m
v += pow(xshift, 2).reduce_add[1]()
vectorize[_op2, SIMD_WIDTH, unroll_factor=UNROLL_FACTOR](size=C)
v = v / C
# calculate the rstd
var s: FLOAT = FLOAT(1.0) / sqrt(v + eps)
# seek to the output position in out[b,t,:]
var out_bt: UnsafePointer[Scalar[dtype]] = out + b * T * C + t * C
@parameter
fn _op3[width: Int](iv: Int):
var n = s * (x.load[width=width](iv) - m) # normalized output
out_bt.store(
iv,
n * weight.load[width=width](iv)
+ bias.load[width=width](iv),
) # scale and shift it
vectorize[_op3, SIMD_WIDTH, unroll_factor=UNROLL_FACTOR](size=C)
# cache the mean and rstd for the backward pass later
mean[b * T + t] = m
rstd[b * T + t] = s
parallelize[_calc](B)
fn layernorm_backward(
dinp: UnsafePointer[Scalar[dtype]],
dweight: UnsafePointer[Scalar[dtype]],
dbias: UnsafePointer[Scalar[dtype]],
dout: UnsafePointer[Scalar[dtype]],
inp: UnsafePointer[Scalar[dtype]],
weight: UnsafePointer[Scalar[dtype]],
mean: UnsafePointer[Scalar[dtype]],
rstd: UnsafePointer[Scalar[dtype]],
B: Int,
T: Int,
C: Int,
):
@parameter
fn _calc(b: Int):
for t in range(T):
var dout_bt: UnsafePointer[Scalar[dtype]] = dout + b * T * C + t * C
var inp_bt: UnsafePointer[Scalar[dtype]] = inp + b * T * C + t * C
var dinp_bt: UnsafePointer[Scalar[dtype]] = dinp + b * T * C + t * C
var mean_bt: FLOAT = mean[b * T + t]
var rstd_bt: FLOAT = rstd[b * T + t]
# first: two reduce operations
var dnorm_mean: FLOAT = 0.0
var dnorm_norm_mean: FLOAT = 0.0
@parameter
fn _op[width: Int](iv: Int):
var norm_bti = (
inp_bt.load[width=width](iv) - mean_bt
) * rstd_bt
var dnorm_i = weight.load[width=width](iv) * dout_bt.load[
width=width
](iv)
dnorm_mean += dnorm_i.reduce_add[1]()
dnorm_norm_mean += (dnorm_i * norm_bti).reduce_add[1]()
vectorize[_op, SIMD_WIDTH, unroll_factor=UNROLL_FACTOR](size=C)
dnorm_mean = dnorm_mean / C
dnorm_norm_mean = dnorm_norm_mean / C
# now iterate again and accumulate all the gradients
@parameter
fn _op2[width: Int](iv: Int):
var norm_bti = (
inp_bt.load[width=width](iv) - mean_bt
) * rstd_bt
var dnorm_i = weight.load[width=width](iv) * dout_bt.load[
width=width
](iv)
# gradient contribution to bias
dbias.store(
iv,
dbias.load[width=width](iv) + dout_bt.load[width=width](iv),
)
# gradient contribution to weight
dweight.store(
iv,
dweight.load[width=width](iv)
+ norm_bti * dout_bt.load[width=width](iv),
)
# gradient contribution to input
dinp_bt.store(
iv,
dinp_bt.load[width=width](iv)
+ (dnorm_i - dnorm_mean - (norm_bti * dnorm_norm_mean))
* rstd_bt,
)
vectorize[_op2, SIMD_WIDTH, unroll_factor=UNROLL_FACTOR](size=C)
parallelize[_calc](B)
fn matmul_forward(
out: UnsafePointer[Scalar[dtype]],
inp: UnsafePointer[Scalar[dtype]],
weight: UnsafePointer[Scalar[dtype]],
bias: UnsafePointer[Scalar[dtype]],
B: Int,
T: Int,
C: Int,
OC: Int,
):
# most of the running time is spent here and in matmul_backward
# OC is short for "output channels"
# inp is (B,T,C), weight is (OC, C), bias is (OC)
# out will be (B,T,OC)
# pragma omp parallel for collapse(2)
@parameter
fn _calc(b: Int):
for t in range(T):
var out_bt: UnsafePointer[Scalar[dtype]] = out + b * T * OC + t * OC
var inp_bt: UnsafePointer[Scalar[dtype]] = inp + b * T * C + t * C
for o in range(OC):
var val: FLOAT = 0.0
if bias != NULL:
val = bias[o]
var wrow: UnsafePointer[Scalar[dtype]] = weight + o * C
@parameter
fn _op[width: Int](iv: Int):
var t = inp_bt.load[width=width](iv) * wrow.load[
width=width
](iv)
val += t.reduce_add[1]()
vectorize[_op, SIMD_WIDTH, unroll_factor=UNROLL_FACTOR](size=C)
out_bt[o] = val
parallelize[_calc](B)
fn matmul_backward(
dinp: UnsafePointer[Scalar[dtype]],
dweight: UnsafePointer[Scalar[dtype]],
dbias: UnsafePointer[Scalar[dtype]],
dout: UnsafePointer[Scalar[dtype]],
inp: UnsafePointer[Scalar[dtype]],
weight: UnsafePointer[Scalar[dtype]],
B: Int,
T: Int,
C: Int,
OC: Int,
):
# most of the running time is spent here and in matmul_forward
# this backward could be done in a single "round" of loops
# but that doesn't afford an efficient parallelization strategy
# backward into inp first, parallelize over B,T
# pragma omp parallel for collapse(2)
@parameter
fn _calc(b: Int):
for t in range(T):
var dout_bt: UnsafePointer[
Scalar[dtype]
] = dout + b * T * OC + t * OC
var dinp_bt: UnsafePointer[Scalar[dtype]] = dinp + b * T * C + t * C
for o in range(OC):
var wrow: UnsafePointer[Scalar[dtype]] = weight + o * C
var d: FLOAT = dout_bt[o]
@parameter
fn _op[width: Int](iv: Int):
dinp_bt.store(
iv,
dinp_bt.load[width=width](iv)
+ wrow.load[width=width](iv) * d,
) # scale and shift it
vectorize[_op, SIMD_WIDTH, unroll_factor=UNROLL_FACTOR](size=C)
parallelize[_calc](B)
# backward into weight/bias, parallelize over output channels OC
# pragma omp parallel for
@parameter
fn _calc2(o: Int):
for b in range(B):
for t in range(T):
var dout_bt: UnsafePointer[
Scalar[dtype]
] = dout + b * T * OC + t * OC
var inp_bt: UnsafePointer[
Scalar[dtype]
] = inp + b * T * C + t * C
var dwrow: UnsafePointer[Scalar[dtype]] = dweight + o * C
var d: FLOAT = dout_bt[o]
if dbias != NULL:
dbias[o] += d
@parameter
fn _op[width: Int](iv: Int):
dwrow.store(
iv,
dwrow.load[width=width](iv)
+ inp_bt.load[width=width](iv) * d,
) # scale and shift it
vectorize[_op, SIMD_WIDTH, unroll_factor=UNROLL_FACTOR](size=C)
parallelize[_calc2](OC)
fn attention_forward(
out: UnsafePointer[Scalar[dtype]],
preatt: UnsafePointer[Scalar[dtype]],
att: UnsafePointer[Scalar[dtype]],
inp: UnsafePointer[Scalar[dtype]],
B: Int,
T: Int,
C: Int,
NH: Int,
):
# input is (B, T, 3C) Q,K,V
# preatt, att are (B, NH, T, T)
# output is (B, T, C)
var C3: Int = C * 3
var hs: Int = C // NH # head size
var scale: FLOAT = FLOAT(1.0) / sqrt(hs)
# pragma omp parallel for collapse(3)
@parameter
fn _calc(b: Int):
# for b in range(B):
for t in range(T):
for h in range(NH):
var query_t: UnsafePointer[
Scalar[dtype]
] = inp + b * T * C3 + t * C3 + h * hs
var preatt_bth: UnsafePointer[
Scalar[dtype]
] = preatt + b * NH * T * T + h * T * T + t * T
var att_bth: UnsafePointer[
Scalar[dtype]
] = att + b * NH * T * T + h * T * T + t * T
# pass 1: calculate query dot key and maxval
var maxval: FLOAT = -10000.0 # TODO something better
for t2 in range(t + 1):
var key_t2: UnsafePointer[
Scalar[dtype]
] = inp + b * T * C3 + t2 * C3 + h * hs + C # +C because it's key
# (query_t) dot (key_t2)
var val: FLOAT = 0.0
@parameter
fn _op[width: Int](iv: Int):
var t = query_t.load[width=width](iv) * key_t2.load[
width=width
](iv)
val += t.reduce_add[1]()
vectorize[_op, SIMD_WIDTH, unroll_factor=UNROLL_FACTOR](
size=hs
)
val *= scale
if val > maxval:
maxval = val
preatt_bth[t2] = val
# pass 2: calculate the exp and keep track of sum
var expsum: FLOAT = 0.0
@parameter
fn _op2[width: Int](iv: Int):
var expv = exp(preatt_bth.load[width=width](iv) - maxval)
expsum += expv.reduce_add[1]()
att_bth.store(iv, expv)
vectorize[_op2, SIMD_WIDTH, unroll_factor=UNROLL_FACTOR](
size=t + 1
)
var expsum_inv: FLOAT = 0.0
if expsum != 0.0:
expsum_inv = FLOAT(1.0) / expsum
# pass 3: normalize to get the softmax
@parameter
fn _op3[width: Int](t2: Int):
att_bth.store(
t2, att_bth.load[width=width](t2) * expsum_inv
)
vectorize[_op3, SIMD_WIDTH, unroll_factor=UNROLL_FACTOR](
size=t + 1
)
memset_zero(att_bth + t + 1, T - t - 1)
# pass 4: accumulate weighted values into the output of attention
var out_bth: UnsafePointer[
Scalar[dtype]
] = out + b * T * C + t * C + h * hs
# for i in range(hs):
# out_bth[i] = 0.0
memset_zero(out_bth, hs)
for t2 in range(t + 1):
var value_t2 = inp + b * T * C3 + t2 * C3 + h * hs + C * 2 # +C*2 because it's value
var att_btht2: FLOAT = att_bth[t2]
@parameter
fn _op4[width: Int](iv: Int):
out_bth.store(
iv,
out_bth.load[width=width](iv)
+ att_btht2 * value_t2.load[width=width](iv),
)
vectorize[_op4, SIMD_WIDTH, unroll_factor=UNROLL_FACTOR](
size=hs
)
parallelize[_calc](B)
fn attention_backward(
dinp: UnsafePointer[Scalar[dtype]],
dpreatt: UnsafePointer[Scalar[dtype]],
datt: UnsafePointer[Scalar[dtype]],
dout: UnsafePointer[Scalar[dtype]],
inp: UnsafePointer[Scalar[dtype]],
att: UnsafePointer[Scalar[dtype]],
B: Int,
T: Int,
C: Int,
NH: Int,
):
# inp/dinp are (B, T, 3C) Q,K,V
# att/datt/dpreatt are (B, NH, T, T)
# dout is (B, T, C)
var C3: Int = C * 3
var hs: Int = C // NH # head size
var scale: FLOAT = FLOAT(1.0) / sqrt(hs)
@parameter
fn _calc(b: Int):
for t in range(T):
for h in range(NH):
var att_bth: UnsafePointer[
Scalar[dtype]
] = att + b * NH * T * T + h * T * T + t * T
var datt_bth: UnsafePointer[
Scalar[dtype]
] = datt + b * NH * T * T + h * T * T + t * T
var dpreatt_bth: UnsafePointer[
Scalar[dtype]
] = dpreatt + b * NH * T * T + h * T * T + t * T
var dquery_t: UnsafePointer[
Scalar[dtype]
] = dinp + b * T * C3 + t * C3 + h * hs
var query_t: UnsafePointer[
Scalar[dtype]
] = inp + b * T * C3 + t * C3 + h * hs
# backward pass 4, through the value accumulation
var dout_bth: UnsafePointer[
Scalar[dtype]
] = dout + b * T * C + t * C + h * hs
for t2 in range(t + 1):
var value_t2: UnsafePointer[
Scalar[dtype]
] = inp + b * T * C3 + t2 * C3 + h * hs + C * 2 # +C*2 because it's value
var dvalue_t2: UnsafePointer[
Scalar[dtype]
] = dinp + b * T * C3 + t2 * C3 + h * hs + C * 2
@parameter
fn _op[width: Int](iv: Int):
# for i in range(hs):
# in the forward pass this was:
# out_bth[i] += att_bth[t2] * value_t2[i]
# so now we have:
datt_bth[t2] += (
value_t2.load[width=width](iv)
* dout_bth.load[width=width](iv)
).reduce_add[1]()
dvalue_t2.store(
iv,
dvalue_t2.load[width=width](iv)
+ att_bth[t2] * dout_bth.load[width=width](iv),
)
vectorize[_op, SIMD_WIDTH, unroll_factor=UNROLL_FACTOR](
size=hs
)
# backward pass 2 & 3, the softmax
# note that softmax (like e.g. tanh) doesn't need the input (preatt) to backward
for t2 in range(t + 1):
@parameter
fn _op3[width: Int](t3: Int):
var local_derivative = -att_bth[t2] * att_bth.load[
width=width
](t3)
dpreatt_bth.store(
t3,
dpreatt_bth.load[width=width](t3)
+ local_derivative * datt_bth[t2],
)
vectorize[_op3, SIMD_WIDTH, unroll_factor=UNROLL_FACTOR](
size=t + 1
)
dpreatt_bth[t2] += att_bth[t2] * datt_bth[t2]
# backward pass 1, the query @ key matmul
for t2 in range(t + 1):
var key_t2: UnsafePointer[
Scalar[dtype]
] = inp + b * T * C3 + t2 * C3 + h * hs + C # +C because it's key
var dkey_t2: UnsafePointer[
Scalar[dtype]
] = dinp + b * T * C3 + t2 * C3 + h * hs + C # +C because it's key
@parameter
fn _op2[width: Int](iv: Int):
# for i in range(hs):
# in the forward pass this was:
# preatt_bth[t2] += (query_t[i] * key_t2[i]) * scale
# so now we have:
dquery_t.store(
iv,
dquery_t.load[width=width](iv)
+ key_t2.load[width=width](iv)
* dpreatt_bth[t2]
* scale,
)
dkey_t2.store(
iv,
dkey_t2.load[width=width](iv)
+ query_t.load[width=width](iv)
* dpreatt_bth[t2]
* scale,
)
vectorize[_op2, SIMD_WIDTH, unroll_factor=UNROLL_FACTOR](
size=hs
)
parallelize[_calc](B)
fn gelu_forward(
out: UnsafePointer[Scalar[dtype]], inp: UnsafePointer[Scalar[dtype]], N: Int
):
var s: FLOAT = sqrt(2.0 / M_PI)
var num_vectorize = N // NUM_PARALLELIZE
@parameter
fn _calc(ip: Int):
@parameter
fn _op[width: Int](_iv: Int):
var iv = ip * num_vectorize + _iv
var x = inp.load[width=width](iv)
var cube = 0.044715 * pow(x, 3)
out.store(iv, 0.5 * x * (1.0 + tanh(s * (x + cube))))
vectorize[_op, SIMD_WIDTH, unroll_factor=UNROLL_FACTOR](num_vectorize)
parallelize[_calc](NUM_PARALLELIZE)
fn gelu_backward(
dinp: UnsafePointer[Scalar[dtype]],
inp: UnsafePointer[Scalar[dtype]],
dout: UnsafePointer[Scalar[dtype]],
N: Int,
):
var s: FLOAT = sqrt(2.0 / M_PI)
var num_vectorize = N // NUM_PARALLELIZE
@parameter
fn _calc(ip: Int):
@parameter
fn _op[width: Int](_iv: Int):
var iv = ip * num_vectorize + _iv
var x = inp.load[width=width](iv)
var cube = 0.044715 * pow(x, 3)
var tanh_arg = s * (x + cube)
var tanh_out = tanh(tanh_arg)
var coshf_out = cosh(tanh_arg)
var sech_out = FLOAT(1.0) / (coshf_out * coshf_out)
var local_grad = 0.5 * (1.0 + tanh_out) + x * 0.5 * sech_out * s * (
1.0 + 3.0 * 0.044715 * x * x
)
dinp.store(
iv,
dinp.load[width=width](iv)
+ local_grad * dout.load[width=width](iv),
)
vectorize[_op, SIMD_WIDTH, unroll_factor=UNROLL_FACTOR](num_vectorize)
parallelize[_calc](NUM_PARALLELIZE)
fn residual_forward(
out: UnsafePointer[Scalar[dtype]],
inp1: UnsafePointer[Scalar[dtype]],
inp2: UnsafePointer[Scalar[dtype]],
N: Int,
):
var num_vectorize = N // NUM_PARALLELIZE
@parameter
fn _calc(ip: Int):
@parameter
fn _op[width: Int](_iv: Int):
var iv = ip * num_vectorize + _iv
out.store(
iv, inp1.load[width=width](iv) + inp2.load[width=width](iv)
) # scale and shift it
vectorize[_op, SIMD_WIDTH, unroll_factor=UNROLL_FACTOR](num_vectorize)
parallelize[_calc](NUM_PARALLELIZE)
fn residual_backward(
dinp1: UnsafePointer[Scalar[dtype]],
dinp2: UnsafePointer[Scalar[dtype]],
dout: UnsafePointer[Scalar[dtype]],
N: Int,
):
var num_vectorize = N // NUM_PARALLELIZE
@parameter
fn _calc(ip: Int):
@parameter
fn _op[width: Int](_iv: Int):
var iv = ip * num_vectorize + _iv
dinp1.store(
iv, dinp1.load[width=width](iv) + dout.load[width=width](iv)
) # scale and shift it
dinp2.store(
iv, dinp2.load[width=width](iv) + dout.load[width=width](iv)
) # scale and shift it
vectorize[_op, SIMD_WIDTH, unroll_factor=UNROLL_FACTOR](num_vectorize)
parallelize[_calc](NUM_PARALLELIZE)
fn softmax_forward(
probs: UnsafePointer[Scalar[dtype]],
logits: UnsafePointer[Scalar[dtype]],
B: Int,
T: Int,
V: Int,
Vp: Int,
):
# output: probs are (B,T,Vp) of the probabilities (sums to 1.0 in each b,t position)
# input: logits is (B,T,Vp) of the unnormalized log probabilities
# Vp is the padded vocab size (for efficiency), V is the "real" vocab size
# example: Vp is 50304 and V is 50257
@parameter
fn _calc(b: Int):
# for b in range(B):
for t in range(T):
# probs <- softmax(logits)
var logits_bt: UnsafePointer[
Scalar[dtype]
] = logits + b * T * Vp + t * Vp
var probs_bt: UnsafePointer[
Scalar[dtype]
] = probs + b * T * Vp + t * Vp
var maxval: FLOAT = -10000.0 # TODO something better
for i in range(V):
if logits_bt[i] > maxval:
maxval = logits_bt[i]
var sum: FLOAT = 0.0
@parameter
fn _op[width: Int](iv: Int):
probs_bt.store(
iv, exp(logits_bt.load[width=width](iv) - maxval)
)
sum += probs_bt.load[width=width](iv).reduce_add[1]()
vectorize[_op, SIMD_WIDTH, unroll_factor=UNROLL_FACTOR](size=V)
@parameter
fn _op2[width: Int](iv: Int):
probs_bt.store(
iv, probs_bt.load[width=width](iv) / sum
) # scale and shift it
vectorize[_op2, SIMD_WIDTH, unroll_factor=UNROLL_FACTOR](size=V)
# for extra super safety we may wish to include this too,
# forcing the probabilities here to be zero, but it shouldn't matter
memset_zero(probs_bt + V, Vp - V)
parallelize[_calc](B)
fn crossentropy_forward(
losses: UnsafePointer[Scalar[dtype]],
probs: UnsafePointer[Scalar[dtype]],
targets: UnsafePointer[Scalar[dtype_int]],
B: Int,
T: Int,
Vp: Int,
):
# output: losses is (B,T) of the individual losses at each position
# input: probs are (B,T,Vp) of the probabilities
# input: targets is (B,T) of integers giving the correct index in logits
@parameter
fn _calc(b: Int):
for t in range(T): # todo
# loss = -log(probs[target])
var probs_bt: UnsafePointer[
Scalar[dtype]
] = probs + b * T * Vp + t * Vp
var ix = targets[b * T + t]
losses[b * T + t] = -log(probs_bt.load(ix))
parallelize[_calc](B)
fn crossentropy_softmax_backward(
dlogits: UnsafePointer[Scalar[dtype]],
dlosses: UnsafePointer[Scalar[dtype]],
probs: UnsafePointer[Scalar[dtype]],
targets: UnsafePointer[Scalar[dtype_int]],
B: Int,
T: Int,
V: Int,
Vp: Int,
):
# backwards through both softmax and crossentropy
@parameter
fn _calc(b: Int):
for t in range(T):
var dlogits_bt: UnsafePointer[
Scalar[dtype]
] = dlogits + b * T * Vp + t * Vp
var probs_bt: UnsafePointer[
Scalar[dtype]
] = probs + b * T * Vp + t * Vp
var dloss: FLOAT = dlosses[b * T + t]
var ix = targets[b * T + t]
@parameter
fn _op[width: Int](iv: Int):
dlogits_bt.store(
iv,
dlogits_bt.load[width=width](iv)
+ probs_bt.load[width=width](iv) * dloss,
)
vectorize[_op, SIMD_WIDTH, unroll_factor=UNROLL_FACTOR](size=V)
if ix >= 0 and ix < V:
dlogits_bt.store(ix, dlogits_bt.load(ix) - dloss)
parallelize[_calc](B)
# ----------------------------------------------------------------------------
# GPT-2 model definition
# the parameters of the model
alias NUM_PARAMETER_TENSORS = 16
struct ParameterTensors:
var params_memory: UnsafePointer[Scalar[dtype]]
var wte: UnsafePointer[Scalar[dtype]] # (V, C)
var wpe: UnsafePointer[Scalar[dtype]] # (maxT, C)
var ln1w: UnsafePointer[Scalar[dtype]] # (L, C)
var ln1b: UnsafePointer[Scalar[dtype]] # (L, C)
var qkvw: UnsafePointer[Scalar[dtype]] # (L, 3*C, C)
var qkvb: UnsafePointer[Scalar[dtype]] # (L, 3*C)
var attprojw: UnsafePointer[Scalar[dtype]] # (L, C, C)
var attprojb: UnsafePointer[Scalar[dtype]] # (L, C)
var ln2w: UnsafePointer[Scalar[dtype]] # (L, C)
var ln2b: UnsafePointer[Scalar[dtype]] # (L, C)
var fcw: UnsafePointer[Scalar[dtype]] # (L, 4*C, C)
var fcb: UnsafePointer[Scalar[dtype]] # (L, 4*C)
var fcprojw: UnsafePointer[Scalar[dtype]] # (L, C, 4*C)
var fcprojb: UnsafePointer[Scalar[dtype]] # (L, C)
var lnfw: UnsafePointer[Scalar[dtype]] # (C)
var lnfb: UnsafePointer[Scalar[dtype]] # (C)
fn __init__(out self):
self.params_memory = UnsafePointer[Scalar[dtype]]()
self.wte = UnsafePointer[Scalar[dtype]]()
self.wpe = UnsafePointer[Scalar[dtype]]()
self.ln1w = UnsafePointer[Scalar[dtype]]()
self.ln1b = UnsafePointer[Scalar[dtype]]()
self.qkvw = UnsafePointer[Scalar[dtype]]()
self.qkvb = UnsafePointer[Scalar[dtype]]()
self.attprojw = UnsafePointer[Scalar[dtype]]()
self.attprojb = UnsafePointer[Scalar[dtype]]()
self.ln2w = UnsafePointer[Scalar[dtype]]()
self.ln2b = UnsafePointer[Scalar[dtype]]()
self.fcw = UnsafePointer[Scalar[dtype]]()
self.fcb = UnsafePointer[Scalar[dtype]]()
self.fcprojw = UnsafePointer[Scalar[dtype]]()
self.fcprojb = UnsafePointer[Scalar[dtype]]()
self.lnfw = UnsafePointer[Scalar[dtype]]()
self.lnfb = UnsafePointer[Scalar[dtype]]()
fn alloc_and_point_parameters(
mut self,
param_sizes: InlinedFixedVector[type=Int, size=NUM_PARAMETER_TENSORS],
) -> UnsafePointer[Scalar[dtype]]:
var num_parameters: Int = 0
for i in range(NUM_PARAMETER_TENSORS):
num_parameters += param_sizes[i]
# malloc all parameters all at once
self.params_memory = UnsafePointer[Scalar[dtype]]().alloc(
num_parameters
)
# assign all the tensors
var ptrs = List(
UnsafePointer.address_of(self.wte),
UnsafePointer.address_of(self.wpe),
UnsafePointer.address_of(self.ln1w),
UnsafePointer.address_of(self.ln1b),
UnsafePointer.address_of(self.qkvw),
UnsafePointer.address_of(self.qkvb),
UnsafePointer.address_of(self.attprojw),
UnsafePointer.address_of(self.attprojb),
UnsafePointer.address_of(self.ln2w),
UnsafePointer.address_of(self.ln2b),
UnsafePointer.address_of(self.fcw),
UnsafePointer.address_of(self.fcb),
UnsafePointer.address_of(self.fcprojw),
UnsafePointer.address_of(self.fcprojb),
UnsafePointer.address_of(self.lnfw),
UnsafePointer.address_of(self.lnfb),
)
var params_memory_iterator: UnsafePointer[
Scalar[dtype]
] = self.params_memory
for i in range(NUM_PARAMETER_TENSORS):
ptrs[i][] = params_memory_iterator
params_memory_iterator += param_sizes[i]
return self.params_memory
alias NUM_ACTIVATION_TENSORS = 23
@value
struct ActivationTensors:
var encoded: UnsafePointer[Scalar[dtype]] # (B, T, C)
var ln1: UnsafePointer[Scalar[dtype]] # (L, B, T, C)
var ln1_mean: UnsafePointer[Scalar[dtype]] # (L, B, T)
var ln1_rstd: UnsafePointer[Scalar[dtype]] # (L, B, T)
var qkv: UnsafePointer[Scalar[dtype]] # (L, B, T, 3*C)
var atty: UnsafePointer[Scalar[dtype]] # (L, B, T, C)
var preatt: UnsafePointer[Scalar[dtype]] # (L, B, NH, T, T)
var att: UnsafePointer[Scalar[dtype]] # (L, B, NH, T, T)
var attproj: UnsafePointer[Scalar[dtype]] # (L, B, T, C)
var residual2: UnsafePointer[Scalar[dtype]] # (L, B, T, C)
var ln2: UnsafePointer[Scalar[dtype]] # (L, B, T, C)
var ln2_mean: UnsafePointer[Scalar[dtype]] # (L, B, T)
var ln2_rstd: UnsafePointer[Scalar[dtype]] # (L, B, T)
var fch: UnsafePointer[Scalar[dtype]] # (L, B, T, 4*C)
var fch_gelu: UnsafePointer[Scalar[dtype]] # (L, B, T, 4*C)
var fcproj: UnsafePointer[Scalar[dtype]] # (L, B, T, C)
var residual3: UnsafePointer[Scalar[dtype]] # (L, B, T, C)
var lnf: UnsafePointer[Scalar[dtype]] # (B, T, C)
var lnf_mean: UnsafePointer[Scalar[dtype]] # (B, T)
var lnf_rstd: UnsafePointer[Scalar[dtype]] # (B, T)
var logits: UnsafePointer[Scalar[dtype]] # (B, T, V)
var probs: UnsafePointer[Scalar[dtype]] # (B, T, V)
var losses: UnsafePointer[Scalar[dtype]] # (B, T)
fn __init__(
out self,
):
self.encoded = UnsafePointer[Scalar[dtype]]()
self.ln1 = UnsafePointer[Scalar[dtype]]()
self.ln1_mean = UnsafePointer[Scalar[dtype]]()
self.ln1_rstd = UnsafePointer[Scalar[dtype]]()
self.qkv = UnsafePointer[Scalar[dtype]]()
self.atty = UnsafePointer[Scalar[dtype]]()
self.preatt = UnsafePointer[Scalar[dtype]]()
self.att = UnsafePointer[Scalar[dtype]]()
self.attproj = UnsafePointer[Scalar[dtype]]()
self.residual2 = UnsafePointer[Scalar[dtype]]()
self.ln2 = UnsafePointer[Scalar[dtype]]()
self.ln2_mean = UnsafePointer[Scalar[dtype]]()
self.ln2_rstd = UnsafePointer[Scalar[dtype]]()
self.fch = UnsafePointer[Scalar[dtype]]()
self.fch_gelu = UnsafePointer[Scalar[dtype]]()
self.fcproj = UnsafePointer[Scalar[dtype]]()
self.residual3 = UnsafePointer[Scalar[dtype]]()
self.lnf = UnsafePointer[Scalar[dtype]]()
self.lnf_mean = UnsafePointer[Scalar[dtype]]()
self.lnf_rstd = UnsafePointer[Scalar[dtype]]()
self.logits = UnsafePointer[Scalar[dtype]]()
self.probs = UnsafePointer[Scalar[dtype]]()
self.losses = UnsafePointer[Scalar[dtype]]()
fn alloc_and_point_activations(
mut self,
act_sizes: InlinedFixedVector[type=Int, size=NUM_ACTIVATION_TENSORS],
) -> UnsafePointer[Scalar[dtype]]:
var ptrs = List(
UnsafePointer.address_of(self.encoded),
UnsafePointer.address_of(self.ln1),
UnsafePointer.address_of(self.ln1_mean),
UnsafePointer.address_of(self.ln1_rstd),
UnsafePointer.address_of(self.qkv),
UnsafePointer.address_of(self.atty),
UnsafePointer.address_of(self.preatt),
UnsafePointer.address_of(self.att),