Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

scaling.py 48 KB

You have to be logged in to leave a comment. Sign In
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
  1. # Copyright 2022 Xiaomi Corp. (authors: Daniel Povey)
  2. #
  3. # See ../../../../LICENSE for clarification regarding multiple authors
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. import collections
  17. import logging
  18. import random
  19. import math
  20. from functools import reduce
  21. from itertools import repeat
  22. from typing import Optional, Tuple, Union
  23. import torch
  24. import torch.nn as nn
  25. import torch.nn.functional as F
  26. from torch import Tensor
  27. from torch.nn import Embedding as ScaledEmbedding
  28. from utils import Transpose
  29. class ActivationBalancerFunction(torch.autograd.Function):
  30. @staticmethod
  31. def forward(
  32. ctx,
  33. x: Tensor,
  34. scale_factor: Tensor,
  35. sign_factor: Optional[Tensor],
  36. channel_dim: int,
  37. ) -> Tensor:
  38. if channel_dim < 0:
  39. channel_dim += x.ndim
  40. ctx.channel_dim = channel_dim
  41. xgt0 = x > 0
  42. if sign_factor is None:
  43. ctx.save_for_backward(xgt0, scale_factor)
  44. else:
  45. ctx.save_for_backward(xgt0, scale_factor, sign_factor)
  46. return x
  47. @staticmethod
  48. def backward(ctx, x_grad: Tensor) -> Tuple[Tensor, None, None, None]:
  49. if len(ctx.saved_tensors) == 3:
  50. xgt0, scale_factor, sign_factor = ctx.saved_tensors
  51. for _ in range(ctx.channel_dim, x_grad.ndim - 1):
  52. scale_factor = scale_factor.unsqueeze(-1)
  53. sign_factor = sign_factor.unsqueeze(-1)
  54. factor = sign_factor + scale_factor * (xgt0.to(x_grad.dtype) - 0.5)
  55. else:
  56. xgt0, scale_factor = ctx.saved_tensors
  57. for _ in range(ctx.channel_dim, x_grad.ndim - 1):
  58. scale_factor = scale_factor.unsqueeze(-1)
  59. factor = scale_factor * (xgt0.to(x_grad.dtype) - 0.5)
  60. neg_delta_grad = x_grad.abs() * factor
  61. return (
  62. x_grad - neg_delta_grad,
  63. None,
  64. None,
  65. None,
  66. )
  67. def _compute_scale_factor(
  68. x: Tensor,
  69. channel_dim: int,
  70. min_abs: float,
  71. max_abs: float,
  72. gain_factor: float,
  73. max_factor: float,
  74. ) -> Tensor:
  75. if channel_dim < 0:
  76. channel_dim += x.ndim
  77. sum_dims = [d for d in range(x.ndim) if d != channel_dim]
  78. x_abs_mean = torch.mean(x.abs(), dim=sum_dims).to(torch.float32)
  79. if min_abs == 0.0:
  80. below_threshold = 0.0
  81. else:
  82. # below_threshold is 0 if x_abs_mean > min_abs, can be at most max_factor if
  83. # x_abs)_mean , min_abs.
  84. below_threshold = (
  85. (min_abs - x_abs_mean) * (gain_factor / min_abs)
  86. ).clamp(min=0, max=max_factor)
  87. above_threshold = ((x_abs_mean - max_abs) * (gain_factor / max_abs)).clamp(
  88. min=0, max=max_factor
  89. )
  90. return below_threshold - above_threshold
  91. def _compute_sign_factor(
  92. x: Tensor,
  93. channel_dim: int,
  94. min_positive: float,
  95. max_positive: float,
  96. gain_factor: float,
  97. max_factor: float,
  98. ) -> Tensor:
  99. if channel_dim < 0:
  100. channel_dim += x.ndim
  101. sum_dims = [d for d in range(x.ndim) if d != channel_dim]
  102. proportion_positive = torch.mean((x > 0).to(torch.float32), dim=sum_dims)
  103. if min_positive == 0.0:
  104. factor1 = 0.0
  105. else:
  106. # 0 if proportion_positive >= min_positive, else can be
  107. # as large as max_factor.
  108. factor1 = (
  109. (min_positive - proportion_positive) * (gain_factor / min_positive)
  110. ).clamp_(min=0, max=max_factor)
  111. if max_positive == 1.0:
  112. factor2 = 0.0
  113. else:
  114. # 0 if self.proportion_positive <= max_positive, else can be
  115. # as large as -max_factor.
  116. factor2 = (
  117. (proportion_positive - max_positive)
  118. * (gain_factor / (1.0 - max_positive))
  119. ).clamp_(min=0, max=max_factor)
  120. sign_factor = factor1 - factor2
  121. # require min_positive != 0 or max_positive != 1:
  122. assert not isinstance(sign_factor, float)
  123. return sign_factor
  124. class ActivationScaleBalancerFunction(torch.autograd.Function):
  125. """
  126. This object is used in class ActivationBalancer when the user specified
  127. min_positive=0, max_positive=1, so there are no constraints on the signs
  128. of the activations and only the absolute value has a constraint.
  129. """
  130. @staticmethod
  131. def forward(
  132. ctx,
  133. x: Tensor,
  134. sign_factor: Tensor,
  135. scale_factor: Tensor,
  136. channel_dim: int,
  137. ) -> Tensor:
  138. if channel_dim < 0:
  139. channel_dim += x.ndim
  140. ctx.channel_dim = channel_dim
  141. xgt0 = x > 0
  142. ctx.save_for_backward(xgt0, sign_factor, scale_factor)
  143. return x
  144. @staticmethod
  145. def backward(ctx, x_grad: Tensor) -> Tuple[Tensor, None, None, None]:
  146. xgt0, sign_factor, scale_factor = ctx.saved_tensors
  147. for _ in range(ctx.channel_dim, x_grad.ndim - 1):
  148. sign_factor = sign_factor.unsqueeze(-1)
  149. scale_factor = scale_factor.unsqueeze(-1)
  150. factor = sign_factor + scale_factor * (xgt0.to(x_grad.dtype) - 0.5)
  151. neg_delta_grad = x_grad.abs() * factor
  152. return (
  153. x_grad - neg_delta_grad,
  154. None,
  155. None,
  156. None,
  157. )
  158. class RandomClampFunction(torch.autograd.Function):
  159. @staticmethod
  160. def forward(
  161. ctx,
  162. x: Tensor,
  163. min: Optional[float],
  164. max: Optional[float],
  165. prob: float,
  166. reflect: float,
  167. ) -> Tensor:
  168. x_clamped = torch.clamp(x, min=min, max=max)
  169. mask = torch.rand_like(x) < prob
  170. ans = torch.where(mask, x_clamped, x)
  171. if x.requires_grad:
  172. ctx.save_for_backward(ans == x)
  173. ctx.reflect = reflect
  174. if reflect != 0.0:
  175. ans = ans * (1.0 + reflect) - (x * reflect)
  176. return ans
  177. @staticmethod
  178. def backward(
  179. ctx, ans_grad: Tensor
  180. ) -> Tuple[Tensor, None, None, None, None]:
  181. (is_same,) = ctx.saved_tensors
  182. x_grad = ans_grad * is_same.to(ans_grad.dtype)
  183. reflect = ctx.reflect
  184. if reflect != 0.0:
  185. x_grad = x_grad * (1.0 + reflect) - (ans_grad * reflect)
  186. return x_grad, None, None, None, None
  187. def random_clamp(
  188. x: Tensor,
  189. min: Optional[float] = None,
  190. max: Optional[float] = None,
  191. prob: float = 0.5,
  192. reflect: float = 0.0,
  193. ):
  194. return RandomClampFunction.apply(x, min, max, prob, reflect)
  195. def random_cast_to_half(x: Tensor, min_abs: float = 5.0e-06) -> Tensor:
  196. """
  197. A randomized way of casting a floating point value to half precision.
  198. """
  199. if x.dtype == torch.float16:
  200. return x
  201. x_abs = x.abs()
  202. is_too_small = x_abs < min_abs
  203. # for elements where is_too_small is true, random_val will contain +-min_abs with
  204. # probability (x.abs() / min_abs), and 0.0 otherwise. [so this preserves expectations,
  205. # for those elements].
  206. random_val = min_abs * x.sign() * (torch.rand_like(x) * min_abs < x_abs)
  207. return torch.where(is_too_small, random_val, x).to(torch.float16)
  208. class RandomGradFunction(torch.autograd.Function):
  209. """
  210. Does nothing in forward pass; in backward pass, gets rid of very small grads using
  211. randomized approach that preserves expectations (intended to reduce roundoff).
  212. """
  213. @staticmethod
  214. def forward(ctx, x: Tensor, min_abs: float) -> Tensor:
  215. ctx.min_abs = min_abs
  216. return x
  217. @staticmethod
  218. def backward(ctx, ans_grad: Tensor) -> Tuple[Tensor, None]:
  219. if ans_grad.dtype == torch.float16:
  220. return (
  221. random_cast_to_half(
  222. ans_grad.to(torch.float32), min_abs=ctx.min_abs
  223. ),
  224. None,
  225. )
  226. else:
  227. return ans_grad, None
  228. class RandomGrad(torch.nn.Module):
  229. """
  230. Gets rid of very small gradients using an expectation-preserving method, intended to increase
  231. accuracy of training when using amp (automatic mixed precision)
  232. """
  233. def __init__(self, min_abs: float = 5.0e-06):
  234. super(RandomGrad, self).__init__()
  235. self.min_abs = min_abs
  236. def forward(self, x: Tensor):
  237. if (
  238. torch.jit.is_scripting()
  239. or not self.training
  240. or torch.jit.is_tracing()
  241. ):
  242. return x
  243. else:
  244. return RandomGradFunction.apply(x, self.min_abs)
  245. class SoftmaxFunction(torch.autograd.Function):
  246. """
  247. Tries to handle half-precision derivatives in a randomized way that should
  248. be more accurate for training than the default behavior.
  249. """
  250. @staticmethod
  251. def forward(ctx, x: Tensor, dim: int):
  252. ans = x.softmax(dim=dim)
  253. # if x dtype is float16, x.softmax() returns a float32 because
  254. # (presumably) that op does not support float16, and autocast
  255. # is enabled.
  256. if torch.is_autocast_enabled():
  257. ans = ans.to(torch.float16)
  258. ctx.save_for_backward(ans)
  259. ctx.x_dtype = x.dtype
  260. ctx.dim = dim
  261. return ans
  262. @staticmethod
  263. def backward(ctx, ans_grad: Tensor):
  264. (ans,) = ctx.saved_tensors
  265. with torch.cuda.amp.autocast(enabled=False):
  266. ans_grad = ans_grad.to(torch.float32)
  267. ans = ans.to(torch.float32)
  268. x_grad = ans_grad * ans
  269. x_grad = x_grad - ans * x_grad.sum(dim=ctx.dim, keepdim=True)
  270. return x_grad, None
  271. def softmax(x: Tensor, dim: int):
  272. if torch.jit.is_scripting() or torch.jit.is_tracing():
  273. return x.softmax(dim)
  274. return SoftmaxFunction.apply(x, dim)
  275. class MaxEigLimiterFunction(torch.autograd.Function):
  276. @staticmethod
  277. def forward(
  278. ctx,
  279. x: Tensor,
  280. coeffs: Tensor,
  281. direction: Tensor,
  282. channel_dim: int,
  283. grad_scale: float,
  284. ) -> Tensor:
  285. ctx.channel_dim = channel_dim
  286. ctx.grad_scale = grad_scale
  287. ctx.save_for_backward(x.detach(), coeffs.detach(), direction.detach())
  288. return x
  289. @staticmethod
  290. def backward(ctx, x_grad, *args):
  291. with torch.enable_grad():
  292. (x_orig, coeffs, new_direction) = ctx.saved_tensors
  293. x_orig.requires_grad = True
  294. num_channels = x_orig.shape[ctx.channel_dim]
  295. x = x_orig.transpose(ctx.channel_dim, -1).reshape(-1, num_channels)
  296. new_direction.requires_grad = False
  297. x = x - x.mean(dim=0)
  298. x_var = (x ** 2).mean()
  299. x_residual = x - coeffs * new_direction
  300. x_residual_var = (x_residual ** 2).mean()
  301. # `variance_proportion` is the proportion of the variance accounted for
  302. # by the top eigen-direction. This is to be minimized.
  303. variance_proportion = (x_var - x_residual_var) / (x_var + 1.0e-20)
  304. variance_proportion.backward()
  305. x_orig_grad = x_orig.grad
  306. x_extra_grad = (
  307. x_orig.grad
  308. * ctx.grad_scale
  309. * x_grad.norm()
  310. / (x_orig_grad.norm() + 1.0e-20)
  311. )
  312. return x_grad + x_extra_grad.detach(), None, None, None, None
  313. class BasicNorm(torch.nn.Module):
  314. """
  315. This is intended to be a simpler, and hopefully cheaper, replacement for
  316. LayerNorm. The observation this is based on, is that Transformer-type
  317. networks, especially with pre-norm, sometimes seem to set one of the
  318. feature dimensions to a large constant value (e.g. 50), which "defeats"
  319. the LayerNorm because the output magnitude is then not strongly dependent
  320. on the other (useful) features. Presumably the weight and bias of the
  321. LayerNorm are required to allow it to do this.
  322. So the idea is to introduce this large constant value as an explicit
  323. parameter, that takes the role of the "eps" in LayerNorm, so the network
  324. doesn't have to do this trick. We make the "eps" learnable.
  325. Args:
  326. num_channels: the number of channels, e.g. 512.
  327. channel_dim: the axis/dimension corresponding to the channel,
  328. interprted as an offset from the input's ndim if negative.
  329. shis is NOT the num_channels; it should typically be one of
  330. {-2, -1, 0, 1, 2, 3}.
  331. eps: the initial "epsilon" that we add as ballast in:
  332. scale = ((input_vec**2).mean() + epsilon)**-0.5
  333. Note: our epsilon is actually large, but we keep the name
  334. to indicate the connection with conventional LayerNorm.
  335. learn_eps: if true, we learn epsilon; if false, we keep it
  336. at the initial value.
  337. eps_min: float
  338. eps_max: float
  339. """
  340. def __init__(
  341. self,
  342. num_channels: int,
  343. channel_dim: int = -1, # CAUTION: see documentation.
  344. eps: float = 0.25,
  345. learn_eps: bool = True,
  346. eps_min: float = -3.0,
  347. eps_max: float = 3.0,
  348. ) -> None:
  349. super(BasicNorm, self).__init__()
  350. self.num_channels = num_channels
  351. self.channel_dim = channel_dim
  352. if learn_eps:
  353. self.eps = nn.Parameter(torch.tensor(eps).log().detach())
  354. else:
  355. self.register_buffer("eps", torch.tensor(eps).log().detach())
  356. self.eps_min = eps_min
  357. self.eps_max = eps_max
  358. def forward(self, x: Tensor) -> Tensor:
  359. assert x.shape[self.channel_dim] == self.num_channels
  360. eps = self.eps
  361. if self.training and random.random() < 0.25:
  362. # with probability 0.25, in training mode, clamp eps between the min
  363. # and max; this will encourage it to learn parameters within the
  364. # allowed range by making parameters that are outside the allowed
  365. # range noisy.
  366. # gradients to allow the parameter to get back into the allowed
  367. # region if it happens to exit it.
  368. eps = eps.clamp(min=self.eps_min, max=self.eps_max)
  369. scales = (
  370. torch.mean(x ** 2, dim=self.channel_dim, keepdim=True) + eps.exp()
  371. ) ** -0.5
  372. return x * scales
  373. def ScaledLinear(*args, initial_scale: float = 1.0, **kwargs) -> nn.Linear:
  374. """
  375. Behaves like a constructor of a modified version of nn.Linear
  376. that gives an easy way to set the default initial parameter scale.
  377. Args:
  378. Accepts the standard args and kwargs that nn.Linear accepts
  379. e.g. in_features, out_features, bias=False.
  380. initial_scale: you can override this if you want to increase
  381. or decrease the initial magnitude of the module's output
  382. (affects the initialization of weight_scale and bias_scale).
  383. Another option, if you want to do something like this, is
  384. to re-initialize the parameters.
  385. """
  386. ans = nn.Linear(*args, **kwargs)
  387. with torch.no_grad():
  388. ans.weight[:] *= initial_scale
  389. if ans.bias is not None:
  390. torch.nn.init.uniform_(
  391. ans.bias, -0.1 * initial_scale, 0.1 * initial_scale
  392. )
  393. return ans
  394. def ScaledConv1d(
  395. *args,
  396. initial_scale: float = 1.0,
  397. kernel_size: int = 3,
  398. padding: str = "same",
  399. **kwargs,
  400. ) -> nn.Conv1d:
  401. """
  402. Behaves like a constructor of a modified version of nn.Conv1d
  403. that gives an easy way to set the default initial parameter scale.
  404. Args:
  405. Accepts the standard args and kwargs that nn.Linear accepts
  406. e.g. in_features, out_features, bias=False.
  407. initial_scale: you can override this if you want to increase
  408. or decrease the initial magnitude of the module's output
  409. (affects the initialization of weight_scale and bias_scale).
  410. Another option, if you want to do something like this, is
  411. to re-initialize the parameters.
  412. """
  413. ans = nn.Conv1d(*args, kernel_size=kernel_size, padding=padding, **kwargs)
  414. with torch.no_grad():
  415. ans.weight[:] *= initial_scale
  416. if ans.bias is not None:
  417. torch.nn.init.uniform_(
  418. ans.bias, -0.1 * initial_scale, 0.1 * initial_scale
  419. )
  420. return ans
  421. def TransposeScaledConv1d(
  422. *args,
  423. initial_scale: float = 1.0,
  424. kernel_size: int = 3,
  425. padding: str = "same",
  426. **kwargs,
  427. ) -> nn.Sequential:
  428. """
  429. Transpose -> ScaledConv1d
  430. """
  431. return nn.Sequential(
  432. Transpose(),
  433. ScaledConv1d(
  434. *args,
  435. initial_scale=initial_scale,
  436. kernel_size=kernel_size,
  437. padding=padding,
  438. **kwargs,
  439. ),
  440. )
  441. def ScaledConv1dTranspose(
  442. *args,
  443. initial_scale: float = 1.0,
  444. kernel_size: int = 3,
  445. padding: str = "same",
  446. **kwargs,
  447. ) -> nn.Sequential:
  448. """
  449. Transpose -> ScaledConv1d
  450. """
  451. return nn.Sequential(
  452. ScaledConv1d(
  453. *args,
  454. initial_scale=initial_scale,
  455. kernel_size=kernel_size,
  456. padding=padding,
  457. **kwargs,
  458. ),
  459. Transpose(),
  460. )
  461. def TransposeConv1d(
  462. *args, kernel_size: int = 3, padding: str = "same", **kwargs
  463. ) -> nn.Sequential:
  464. """
  465. Transpose -> Conv1d
  466. """
  467. return nn.Sequential(
  468. Transpose(),
  469. nn.Conv1d(*args, kernel_size=kernel_size, padding=padding, **kwargs),
  470. )
  471. def Conv1dTranspose(
  472. *args, kernel_size: int = 3, padding: str = "same", **kwargs
  473. ) -> nn.Sequential:
  474. """
  475. ScaledConv1d -> Transpose
  476. """
  477. return nn.Sequential(
  478. nn.Conv1d(*args, kernel_size=kernel_size, padding=padding, **kwargs),
  479. Transpose(),
  480. )
  481. class SRLinear(nn.Linear):
  482. """https://arxiv.org/abs/2303.06296
  483. Stabilizing Transformer Training by Preventing Attention Entropy Collapse
  484. """
  485. def __init__(self, in_features, out_features, bias=True, **kwargs):
  486. super().__init__(in_features, out_features, bias=bias, **kwargs)
  487. self.register_buffer(
  488. "u", nn.functional.normalize(torch.randn(in_features), dim=0)
  489. )
  490. with torch.no_grad():
  491. sigma = self.get_sigma()
  492. self.register_buffer("spectral_norm", sigma)
  493. self.sigma = nn.Parameter(torch.ones(1))
  494. def get_sigma(self):
  495. with torch.no_grad():
  496. u = self.u
  497. v = self.weight.mv(u)
  498. v = nn.functional.normalize(v, dim=0)
  499. u = self.weight.T.mv(v)
  500. u = nn.functional.normalize(u, dim=0)
  501. self.u.data.copy_(u)
  502. return torch.einsum("c,cd,d->", v, self.weight, u)
  503. def get_weight(self):
  504. sigma = self.get_sigma()
  505. if self.training:
  506. self.spectral_norm.data.copy_(sigma)
  507. weight = (self.sigma / sigma) * self.weight
  508. return weight
  509. def forward(self, x):
  510. return nn.functional.linear(x, self.get_weight(), self.bias)
  511. class SRConv1d(SRLinear):
  512. def __init__(
  513. self,
  514. in_features,
  515. out_features,
  516. kernel_size,
  517. stride: int = 1,
  518. padding: str = "same",
  519. bias: bool = True,
  520. **kwargs,
  521. ):
  522. in_features = in_features * kernel_size
  523. super().__init__(in_features, out_features, bias=bias, **kwargs)
  524. nn.init.kaiming_uniform_(self.weight, a=math.sqrt(5))
  525. self.kernel_size = kernel_size
  526. self.stride = stride
  527. self.padding = padding
  528. def forward(self, x):
  529. in_features = self.in_features // self.kernel_size
  530. weight = self.get_weight().view(
  531. self.out_features, in_features, self.kernel_size
  532. )
  533. return nn.functional.conv1d(
  534. x, weight, bias=self.bias, stride=self.stride, padding=self.padding
  535. )
  536. def TransposeSRConv1d(
  537. *args, kernel_size: int = 3, padding: str = "same", **kwargs
  538. ) -> nn.Sequential:
  539. """
  540. Transpose -> SRConv1d
  541. """
  542. return nn.Sequential(
  543. Transpose(),
  544. SRConv1d(*args, kernel_size=kernel_size, padding=padding, **kwargs),
  545. )
  546. def SRConv1dTranspose(
  547. *args, kernel_size: int = 3, padding: str = "same", **kwargs
  548. ) -> nn.Sequential:
  549. """
  550. SRConv1d -> Transpose
  551. """
  552. return nn.Sequential(
  553. SRConv1d(*args, kernel_size=kernel_size, padding=padding, **kwargs),
  554. Transpose(),
  555. )
  556. class ActivationBalancer(torch.nn.Module):
  557. """
  558. Modifies the backpropped derivatives of a function to try to encourage, for
  559. each channel, that it is positive at least a proportion `threshold` of the
  560. time. It does this by multiplying negative derivative values by up to
  561. (1+max_factor), and positive derivative values by up to (1-max_factor),
  562. interpolated from 1 at the threshold to those extremal values when none
  563. of the inputs are positive.
  564. Args:
  565. num_channels: the number of channels
  566. channel_dim: the dimension/axis corresponding to the channel, e.g.
  567. -1, 0, 1, 2; will be interpreted as an offset from x.ndim if negative.
  568. min_positive: the minimum, per channel, of the proportion of the time
  569. that (x > 0), below which we start to modify the derivatives.
  570. max_positive: the maximum, per channel, of the proportion of the time
  571. that (x > 0), above which we start to modify the derivatives.
  572. max_factor: the maximum factor by which we modify the derivatives for
  573. either the sign constraint or the magnitude constraint;
  574. e.g. with max_factor=0.02, the the derivatives would be multiplied by
  575. values in the range [0.98..1.02].
  576. sign_gain_factor: determines the 'gain' with which we increase the
  577. change in gradient once the constraints on min_positive and max_positive
  578. are violated.
  579. scale_gain_factor: determines the 'gain' with which we increase the
  580. change in gradient once the constraints on min_abs and max_abs
  581. are violated.
  582. min_abs: the minimum average-absolute-value difference from the mean
  583. value per channel, which we allow, before we start to modify
  584. the derivatives to prevent this.
  585. max_abs: the maximum average-absolute-value difference from the mean
  586. value per channel, which we allow, before we start to modify
  587. the derivatives to prevent this.
  588. min_prob: determines the minimum probability with which we modify the
  589. gradients for the {min,max}_positive and {min,max}_abs constraints,
  590. on each forward(). This is done randomly to prevent all layers
  591. from doing it at the same time. Early in training we may use
  592. higher probabilities than this; it will decay to this value.
  593. """
  594. def __init__(
  595. self,
  596. num_channels: int,
  597. channel_dim: int,
  598. min_positive: float = 0.05,
  599. max_positive: float = 0.95,
  600. max_factor: float = 0.04,
  601. sign_gain_factor: float = 0.01,
  602. scale_gain_factor: float = 0.02,
  603. min_abs: float = 0.2,
  604. max_abs: float = 100.0,
  605. min_prob: float = 0.1,
  606. ):
  607. super(ActivationBalancer, self).__init__()
  608. self.num_channels = num_channels
  609. self.channel_dim = channel_dim
  610. self.min_positive = min_positive
  611. self.max_positive = max_positive
  612. self.max_factor = max_factor
  613. self.min_abs = min_abs
  614. self.max_abs = max_abs
  615. self.min_prob = min_prob
  616. self.sign_gain_factor = sign_gain_factor
  617. self.scale_gain_factor = scale_gain_factor
  618. # count measures how many times the forward() function has been called.
  619. # We occasionally sync this to a tensor called `count`, that exists to
  620. # make sure it is synced to disk when we load and save the model.
  621. self.cpu_count = 0
  622. self.register_buffer("count", torch.tensor(0, dtype=torch.int64))
  623. def forward(self, x: Tensor) -> Tensor:
  624. if (
  625. torch.jit.is_scripting()
  626. or not x.requires_grad
  627. or torch.jit.is_tracing()
  628. ):
  629. return _no_op(x)
  630. count = self.cpu_count
  631. self.cpu_count += 1
  632. if random.random() < 0.01:
  633. # Occasionally sync self.cpu_count with self.count.
  634. # count affects the decay of 'prob'. don't do this on every iter,
  635. # because syncing with the GPU is slow.
  636. self.cpu_count = max(self.cpu_count, self.count.item())
  637. self.count.fill_(self.cpu_count)
  638. # the prob of doing some work exponentially decreases from 0.5 till it hits
  639. # a floor at min_prob (==0.1, by default)
  640. prob = max(self.min_prob, 0.5 ** (1 + (count / 4000.0)))
  641. if random.random() < prob:
  642. sign_gain_factor = 0.5
  643. if self.min_positive != 0.0 or self.max_positive != 1.0:
  644. sign_factor = _compute_sign_factor(
  645. x,
  646. self.channel_dim,
  647. self.min_positive,
  648. self.max_positive,
  649. gain_factor=self.sign_gain_factor / prob,
  650. max_factor=self.max_factor,
  651. )
  652. else:
  653. sign_factor = None
  654. scale_factor = _compute_scale_factor(
  655. x.detach(),
  656. self.channel_dim,
  657. min_abs=self.min_abs,
  658. max_abs=self.max_abs,
  659. gain_factor=self.scale_gain_factor / prob,
  660. max_factor=self.max_factor,
  661. )
  662. return ActivationBalancerFunction.apply(
  663. x,
  664. scale_factor,
  665. sign_factor,
  666. self.channel_dim,
  667. )
  668. else:
  669. return _no_op(x)
  670. def penalize_abs_values_gt(x: Tensor, limit: float, penalty: float) -> Tensor:
  671. """
  672. Returns x unmodified, but in backprop will put a penalty for the excess of
  673. the absolute values of elements of x over the limit "limit". E.g. if
  674. limit == 10.0, then if x has any values over 10 it will get a penalty.
  675. Caution: the value of this penalty will be affected by grad scaling used
  676. in automatic mixed precision training. For this reasons we use this,
  677. it shouldn't really matter, or may even be helpful; we just use this
  678. to disallow really implausible values of scores to be given to softmax.
  679. """
  680. x_sign = x.sign()
  681. over_limit = (x.abs() - limit) > 0
  682. # The following is a memory efficient way to penalize the absolute values of
  683. # x that's over the limit. (The memory efficiency comes when you think
  684. # about which items torch needs to cache for the autograd, and which ones it
  685. # can throw away). The numerical value of aux_loss as computed here will
  686. # actually be larger than it should be, by limit * over_limit.sum(), but it
  687. # has the same derivative as the real aux_loss which is penalty * (x.abs() -
  688. # limit).relu().
  689. aux_loss = penalty * ((x_sign * over_limit).to(torch.int8) * x)
  690. # note: we don't do sum() here on aux)_loss, but it's as if we had done
  691. # sum() due to how with_loss() works.
  692. x = with_loss(x, aux_loss)
  693. # you must use x for something, or this will be ineffective.
  694. return x
  695. def _diag(x: Tensor): # like .diag(), but works for tensors with 3 dims.
  696. if x.ndim == 2:
  697. return x.diag()
  698. else:
  699. (batch, dim, dim) = x.shape
  700. x = x.reshape(batch, dim * dim)
  701. x = x[:, :: dim + 1]
  702. assert x.shape == (batch, dim)
  703. return x
  704. def _whitening_metric(x: Tensor, num_groups: int):
  705. """
  706. Computes the "whitening metric", a value which will be 1.0 if all the eigenvalues of
  707. of the centered feature covariance are the same within each group's covariance matrix
  708. and also between groups.
  709. Args:
  710. x: a Tensor of shape (*, num_channels)
  711. num_groups: the number of groups of channels, a number >=1 that divides num_channels
  712. Returns:
  713. Returns a scalar Tensor that will be 1.0 if the data is "perfectly white" and
  714. greater than 1.0 otherwise.
  715. """
  716. assert x.dtype != torch.float16
  717. x = x.reshape(-1, x.shape[-1])
  718. (num_frames, num_channels) = x.shape
  719. assert num_channels % num_groups == 0
  720. channels_per_group = num_channels // num_groups
  721. x = x.reshape(num_frames, num_groups, channels_per_group).transpose(0, 1)
  722. # x now has shape (num_groups, num_frames, channels_per_group)
  723. # subtract the mean so we use the centered, not uncentered, covariance.
  724. # My experience has been that when we "mess with the gradients" like this,
  725. # it's better not do anything that tries to move the mean around, because
  726. # that can easily cause instability.
  727. x = x - x.mean(dim=1, keepdim=True)
  728. # x_covar: (num_groups, channels_per_group, channels_per_group)
  729. x_covar = torch.matmul(x.transpose(1, 2), x)
  730. x_covar_mean_diag = _diag(x_covar).mean()
  731. # the following expression is what we'd get if we took the matrix product
  732. # of each covariance and measured the mean of its trace, i.e.
  733. # the same as _diag(torch.matmul(x_covar, x_covar)).mean().
  734. x_covarsq_mean_diag = (x_covar ** 2).sum() / (
  735. num_groups * channels_per_group
  736. )
  737. # this metric will be >= 1.0; the larger it is, the less 'white' the data was.
  738. metric = x_covarsq_mean_diag / (x_covar_mean_diag ** 2 + 1.0e-20)
  739. return metric
  740. class WhiteningPenaltyFunction(torch.autograd.Function):
  741. @staticmethod
  742. def forward(
  743. ctx,
  744. x: Tensor,
  745. num_groups: int,
  746. whitening_limit: float,
  747. grad_scale: float,
  748. ) -> Tensor:
  749. ctx.save_for_backward(x)
  750. ctx.num_groups = num_groups
  751. ctx.whitening_limit = whitening_limit
  752. ctx.grad_scale = grad_scale
  753. return x
  754. @staticmethod
  755. def backward(ctx, x_grad: Tensor):
  756. (x_orig,) = ctx.saved_tensors
  757. with torch.enable_grad():
  758. with torch.cuda.amp.autocast(enabled=False):
  759. x_detached = x_orig.to(torch.float32).detach()
  760. x_detached.requires_grad = True
  761. metric = _whitening_metric(x_detached, ctx.num_groups)
  762. if random.random() < 0.005 or __name__ == "__main__":
  763. logging.info(
  764. f"Whitening: num_groups={ctx.num_groups}, num_channels={x_orig.shape[-1]}, "
  765. f"metric={metric.item():.2f} vs. limit={ctx.whitening_limit}"
  766. )
  767. (metric - ctx.whitening_limit).relu().backward()
  768. penalty_grad = x_detached.grad
  769. scale = ctx.grad_scale * (
  770. x_grad.to(torch.float32).norm()
  771. / (penalty_grad.norm() + 1.0e-20)
  772. )
  773. penalty_grad = penalty_grad * scale
  774. return x_grad + penalty_grad.to(x_grad.dtype), None, None, None
  775. class Whiten(nn.Module):
  776. def __init__(
  777. self,
  778. num_groups: int,
  779. whitening_limit: float,
  780. prob: Union[float, Tuple[float, float]],
  781. grad_scale: float,
  782. ):
  783. """
  784. Args:
  785. num_groups: the number of groups to divide the channel dim into before
  786. whitening. We will attempt to make the feature covariance
  787. within each group, after mean subtraction, as "white" as possible,
  788. while having the same trace across all groups.
  789. whitening_limit: a value greater than 1.0, that dictates how much
  790. freedom we have to violate the constraints. 1.0 would mean perfectly
  791. white, with exactly the same trace across groups; larger values
  792. give more freedom. E.g. 2.0.
  793. prob: the probability with which we apply the gradient modification
  794. (also affects the grad scale). May be supplied as a float,
  795. or as a pair (min_prob, max_prob)
  796. grad_scale: determines the scale on the gradient term from this object,
  797. relative to the rest of the gradient on the attention weights.
  798. E.g. 0.02 (you may want to use smaller values than this if prob is large)
  799. """
  800. super(Whiten, self).__init__()
  801. assert num_groups >= 1
  802. assert whitening_limit >= 1
  803. assert grad_scale >= 0
  804. self.num_groups = num_groups
  805. self.whitening_limit = whitening_limit
  806. if isinstance(prob, float):
  807. assert 0 < prob <= 1
  808. self.prob = prob
  809. else:
  810. (self.min_prob, self.max_prob) = prob
  811. assert 0 < self.min_prob < self.max_prob <= 1
  812. self.prob = self.max_prob
  813. self.grad_scale = grad_scale
  814. def forward(self, x: Tensor) -> Tensor:
  815. """
  816. In the forward pass, this function just returns the input unmodified.
  817. In the backward pass, it will modify the gradients to ensure that the
  818. distribution in each group has close to (lambda times I) as the covariance
  819. after mean subtraction, with the same lambda across groups.
  820. For whitening_limit > 1, there will be more freedom to violate this
  821. constraint.
  822. Args:
  823. x: the input of shape (*, num_channels)
  824. Returns:
  825. x, unmodified. You should make sure
  826. you use the returned value, or the graph will be freed
  827. and nothing will happen in backprop.
  828. """
  829. if (
  830. not x.requires_grad
  831. or random.random() > self.prob
  832. or self.grad_scale == 0
  833. ):
  834. return _no_op(x)
  835. else:
  836. if hasattr(self, "min_prob") and random.random() < 0.25:
  837. # occasionally switch between min_prob and max_prob, based on whether
  838. # we are above or below the threshold.
  839. if (
  840. _whitening_metric(x.to(torch.float32), self.num_groups)
  841. > self.whitening_limit
  842. ):
  843. # there would be a change to the grad.
  844. self.prob = self.max_prob
  845. else:
  846. self.prob = self.min_prob
  847. return WhiteningPenaltyFunction.apply(
  848. x, self.num_groups, self.whitening_limit, self.grad_scale
  849. )
  850. class WithLoss(torch.autograd.Function):
  851. @staticmethod
  852. def forward(ctx, x: Tensor, y: Tensor):
  853. ctx.y_shape = y.shape
  854. return x
  855. @staticmethod
  856. def backward(ctx, ans_grad: Tensor):
  857. return ans_grad, torch.ones(
  858. ctx.y_shape, dtype=ans_grad.dtype, device=ans_grad.device
  859. )
  860. def with_loss(x, y):
  861. if torch.jit.is_scripting() or torch.jit.is_tracing():
  862. return x
  863. # returns x but adds y.sum() to the loss function.
  864. return WithLoss.apply(x, y)
  865. def _no_op(x: Tensor) -> Tensor:
  866. if torch.jit.is_scripting() or torch.jit.is_tracing():
  867. return x
  868. else:
  869. # a no-op function that will have a node in the autograd graph,
  870. # to avoid certain bugs relating to backward hooks
  871. return x.chunk(1, dim=-1)[0]
  872. class Identity(torch.nn.Module):
  873. def __init__(self):
  874. super(Identity, self).__init__()
  875. def forward(self, x):
  876. return _no_op(x)
  877. class MaxEig(torch.nn.Module):
  878. """
  879. Modifies the backpropped derivatives of a function to try to discourage
  880. that any given direction in activation space accounts for more than
  881. a specified proportion of the covariance (e.g. 0.2).
  882. Args:
  883. num_channels: the number of channels
  884. channel_dim: the dimension/axis corresponding to the channel, e.g.
  885. -1, 0, 1, 2; will be interpreted as an offset from x.ndim if negative.
  886. max_var_per_eig: the maximum proportion of the variance of the
  887. features/channels, after mean subtraction, that can come from
  888. any given eigenvalue.
  889. min_prob: the minimum probability with which we apply this during any invocation
  890. of forward(), assuming last time we applied the constraint it was
  891. not active; supplied for speed.
  892. scale: determines the scale with which we modify the gradients, relative
  893. to the existing / unmodified gradients
  894. """
  895. def __init__(
  896. self,
  897. num_channels: int,
  898. channel_dim: int,
  899. max_var_per_eig: float = 0.2,
  900. min_prob: float = 0.01,
  901. scale: float = 0.01,
  902. ):
  903. super(MaxEig, self).__init__()
  904. self.num_channels = num_channels
  905. self.channel_dim = channel_dim
  906. self.scale = scale
  907. assert max_var_per_eig == 0.0 or max_var_per_eig > 1.0 / num_channels
  908. self.max_var_per_eig = max_var_per_eig
  909. # we figure out the dominant direction using the power method: starting with
  910. # a random vector, keep multiplying by the covariance and renormalizing.
  911. with torch.no_grad():
  912. # arbitrary.. would use randn() but want to leave the rest of the model's
  913. # random parameters unchanged for comparison
  914. direction = torch.arange(num_channels).to(torch.float)
  915. direction = direction / direction.norm()
  916. self.register_buffer("max_eig_direction", direction)
  917. self.min_prob = min_prob
  918. # cur_prob is the current probability we'll use to apply the ActivationBalancer.
  919. # We'll regress this towards prob, each tiem we try to apply it and it is not
  920. # active.
  921. self.cur_prob = 1.0
  922. def forward(self, x: Tensor) -> Tensor:
  923. if (
  924. torch.jit.is_scripting()
  925. or self.max_var_per_eig <= 0
  926. or random.random() > self.cur_prob
  927. or torch.jit.is_tracing()
  928. ):
  929. return _no_op(x)
  930. with torch.cuda.amp.autocast(enabled=False):
  931. eps = 1.0e-20
  932. orig_x = x
  933. x = x.to(torch.float32)
  934. with torch.no_grad():
  935. x = x.transpose(self.channel_dim, -1).reshape(
  936. -1, self.num_channels
  937. )
  938. x = x - x.mean(dim=0)
  939. new_direction, coeffs = self._find_direction_coeffs(
  940. x, self.max_eig_direction
  941. )
  942. x_var = (x ** 2).mean()
  943. x_residual = x - coeffs * new_direction
  944. x_residual_var = (x_residual ** 2).mean()
  945. # `variance_proportion` is the proportion of the variance accounted for
  946. # by the top eigen-direction.
  947. variance_proportion = (x_var - x_residual_var) / (
  948. x_var + 1.0e-20
  949. )
  950. # ensure new direction is nonzero even if x == 0, by including `direction`.
  951. self._set_direction(
  952. 0.1 * self.max_eig_direction + new_direction
  953. )
  954. if random.random() < 0.01 or __name__ == "__main__":
  955. logging.info(
  956. f"variance_proportion = {variance_proportion.item()}, shape={tuple(orig_x.shape)}, cur_prob={self.cur_prob}"
  957. )
  958. if variance_proportion >= self.max_var_per_eig:
  959. # The constraint is active. Note, we should quite rarely
  960. # reach here, only near the beginning of training if we are
  961. # starting to diverge, should this constraint be active.
  962. cur_prob = self.cur_prob
  963. self.cur_prob = (
  964. 1.0 # next time, do the update with probability 1.0.
  965. )
  966. return MaxEigLimiterFunction.apply(
  967. orig_x, coeffs, new_direction, self.channel_dim, self.scale
  968. )
  969. else:
  970. # let self.cur_prob exponentially approach self.min_prob, as
  971. # long as the constraint is inactive.
  972. self.cur_prob = 0.75 * self.cur_prob + 0.25 * self.min_prob
  973. return orig_x
  974. def _set_direction(self, direction: Tensor):
  975. """
  976. Sets self.max_eig_direction to a normalized version of `direction`
  977. """
  978. direction = direction.detach()
  979. direction = direction / direction.norm()
  980. direction_sum = direction.sum().item()
  981. if direction_sum - direction_sum == 0: # no inf/nan
  982. self.max_eig_direction[:] = direction
  983. else:
  984. logging.info(
  985. f"Warning: sum of direction in MaxEig is {direction_sum}, "
  986. "num_channels={self.num_channels}, channel_dim={self.channel_dim}"
  987. )
  988. def _find_direction_coeffs(
  989. self, x: Tensor, prev_direction: Tensor
  990. ) -> Tuple[Tensor, Tensor, Tensor]:
  991. """
  992. Figure out (an approximation to) the proportion of the variance of a set of
  993. feature vectors that can be attributed to the top eigen-direction.
  994. Args:
  995. x: a Tensor of shape (num_frames, num_channels), with num_frames > 1.
  996. prev_direction: a Tensor of shape (num_channels,), that is our previous estimate
  997. of the top eigen-direction, or a random direction if this is the first
  998. iteration. Does not have to be normalized, but should be nonzero.
  999. Returns: (cur_direction, coeffs), where:
  1000. cur_direction: a Tensor of shape (num_channels,) that is the current
  1001. estimate of the top eigen-direction.
  1002. coeffs: a Tensor of shape (num_frames, 1) that minimizes, or
  1003. approximately minimizes, (x - coeffs * cur_direction).norm()
  1004. """
  1005. (num_frames, num_channels) = x.shape
  1006. assert num_channels > 1 and num_frames > 1
  1007. assert prev_direction.shape == (num_channels,)
  1008. # `coeffs` are the coefficients of `prev_direction` in x.
  1009. # actually represent the coeffs up to a constant positive factor.
  1010. coeffs = (x * prev_direction).sum(dim=1, keepdim=True) + 1.0e-10
  1011. cur_direction = (x * coeffs).sum(dim=0) / (
  1012. (coeffs ** 2).sum() + 1.0e-20
  1013. )
  1014. return cur_direction, coeffs
  1015. class DoubleSwishFunction(torch.autograd.Function):
  1016. """
  1017. double_swish(x) = x * torch.sigmoid(x-1)
  1018. This is a definition, originally motivated by its close numerical
  1019. similarity to swish(swish(x)), where swish(x) = x * sigmoid(x).
  1020. Memory-efficient derivative computation:
  1021. double_swish(x) = x * s, where s(x) = torch.sigmoid(x-1)
  1022. double_swish'(x) = d/dx double_swish(x) = x * s'(x) + x' * s(x) = x * s'(x) + s(x).
  1023. Now, s'(x) = s(x) * (1-s(x)).
  1024. double_swish'(x) = x * s'(x) + s(x).
  1025. = x * s(x) * (1-s(x)) + s(x).
  1026. = double_swish(x) * (1-s(x)) + s(x)
  1027. ... so we just need to remember s(x) but not x itself.
  1028. """
  1029. @staticmethod
  1030. def forward(ctx, x: Tensor) -> Tensor:
  1031. requires_grad = x.requires_grad
  1032. x_dtype = x.dtype
  1033. if x.dtype == torch.float16:
  1034. x = x.to(torch.float32)
  1035. s = torch.sigmoid(x - 1.0)
  1036. y = x * s
  1037. if requires_grad:
  1038. deriv = y * (1 - s) + s
  1039. # notes on derivative of x * sigmoid(x - 1):
  1040. # https://www.wolframalpha.com/input?i=d%2Fdx+%28x+*+sigmoid%28x-1%29%29
  1041. # min \simeq -0.043638. Take floor as -0.043637 so it's a lower bund
  1042. # max \simeq 1.1990. Take ceil to be 1.2 so it's an upper bound.
  1043. # the combination of "+ torch.rand_like(deriv)" and casting to torch.uint8 (which
  1044. # floors), should be expectation-preserving.
  1045. floor = -0.043637
  1046. ceil = 1.2
  1047. d_scaled = (deriv - floor) * (
  1048. 255.0 / (ceil - floor)
  1049. ) + torch.rand_like(deriv)
  1050. if __name__ == "__main__":
  1051. # for self-testing only.
  1052. assert d_scaled.min() >= 0.0
  1053. assert d_scaled.max() < 256.0
  1054. d_int = d_scaled.to(torch.uint8)
  1055. ctx.save_for_backward(d_int)
  1056. if x.dtype == torch.float16 or torch.is_autocast_enabled():
  1057. y = y.to(torch.float16)
  1058. return y
  1059. @staticmethod
  1060. def backward(ctx, y_grad: Tensor) -> Tensor:
  1061. (d,) = ctx.saved_tensors
  1062. # the same constants as used in forward pass.
  1063. floor = -0.043637
  1064. ceil = 1.2
  1065. d = d * ((ceil - floor) / 255.0) + floor
  1066. return y_grad * d
  1067. class DoubleSwish(torch.nn.Module):
  1068. def forward(self, x: Tensor) -> Tensor:
  1069. """Return double-swish activation function which is an approximation to Swish(Swish(x)),
  1070. that we approximate closely with x * sigmoid(x-1).
  1071. """
  1072. if torch.jit.is_scripting() or torch.jit.is_tracing():
  1073. return x * torch.sigmoid(x - 1.0)
  1074. return DoubleSwishFunction.apply(x)
  1075. def BalancedDoubleSwish(
  1076. d_model, channel_dim=-1, max_abs=10.0, min_prob=0.25
  1077. ) -> nn.Sequential:
  1078. """
  1079. ActivationBalancer -> DoubleSwish
  1080. """
  1081. balancer = ActivationBalancer(
  1082. d_model, channel_dim=channel_dim, max_abs=max_abs, min_prob=min_prob
  1083. )
  1084. return nn.Sequential(
  1085. balancer,
  1086. DoubleSwish(),
  1087. )
  1088. def _test_max_eig():
  1089. for proportion in [0.1, 0.5, 10.0]:
  1090. logging.info(f"proportion = {proportion}")
  1091. x = torch.randn(100, 128)
  1092. direction = torch.randn(128)
  1093. coeffs = torch.randn(100, 1)
  1094. x += proportion * direction * coeffs
  1095. x.requires_grad = True
  1096. num_channels = 128
  1097. m = MaxEig(
  1098. num_channels, 1, 0.5, scale=0.1 # channel_dim # max_var_per_eig
  1099. ) # grad_scale
  1100. for _ in range(4):
  1101. y = m(x)
  1102. y_grad = torch.randn_like(x)
  1103. y.backward(gradient=y_grad)
  1104. if proportion < 0.2:
  1105. assert torch.allclose(x.grad, y_grad, atol=1.0e-02)
  1106. elif proportion > 1.0:
  1107. assert not torch.allclose(x.grad, y_grad)
  1108. def _test_whiten():
  1109. for proportion in [0.1, 0.5, 10.0]:
  1110. logging.info(f"_test_whiten(): proportion = {proportion}")
  1111. x = torch.randn(100, 128)
  1112. direction = torch.randn(128)
  1113. coeffs = torch.randn(100, 1)
  1114. x += proportion * direction * coeffs
  1115. x.requires_grad = True
  1116. num_channels = 128
  1117. m = Whiten(
  1118. 1, 5.0, prob=1.0, grad_scale=0.1 # num_groups # whitening_limit,
  1119. ) # grad_scale
  1120. for _ in range(4):
  1121. y = m(x)
  1122. y_grad = torch.randn_like(x)
  1123. y.backward(gradient=y_grad)
  1124. if proportion < 0.2:
  1125. assert torch.allclose(x.grad, y_grad)
  1126. elif proportion > 1.0:
  1127. assert not torch.allclose(x.grad, y_grad)
  1128. def _test_activation_balancer_sign():
  1129. probs = torch.arange(0, 1, 0.01)
  1130. N = 1000
  1131. x = 1.0 * (
  1132. (2.0 * (torch.rand(probs.numel(), N) < probs.unsqueeze(-1))) - 1.0
  1133. )
  1134. x = x.detach()
  1135. x.requires_grad = True
  1136. m = ActivationBalancer(
  1137. probs.numel(),
  1138. channel_dim=0,
  1139. min_positive=0.05,
  1140. max_positive=0.95,
  1141. max_factor=0.2,
  1142. min_abs=0.0,
  1143. )
  1144. y_grad = torch.sign(torch.randn(probs.numel(), N))
  1145. y = m(x)
  1146. y.backward(gradient=y_grad)
  1147. print("_test_activation_balancer_sign: x = ", x)
  1148. print("_test_activation_balancer_sign: y grad = ", y_grad)
  1149. print("_test_activation_balancer_sign: x grad = ", x.grad)
  1150. def _test_activation_balancer_magnitude():
  1151. magnitudes = torch.arange(0, 1, 0.01)
  1152. N = 1000
  1153. x = torch.sign(torch.randn(magnitudes.numel(), N)) * magnitudes.unsqueeze(
  1154. -1
  1155. )
  1156. x = x.detach()
  1157. x.requires_grad = True
  1158. m = ActivationBalancer(
  1159. magnitudes.numel(),
  1160. channel_dim=0,
  1161. min_positive=0.0,
  1162. max_positive=1.0,
  1163. max_factor=0.2,
  1164. min_abs=0.2,
  1165. max_abs=0.8,
  1166. min_prob=1.0,
  1167. )
  1168. y_grad = torch.sign(torch.randn(magnitudes.numel(), N))
  1169. y = m(x)
  1170. y.backward(gradient=y_grad)
  1171. print("_test_activation_balancer_magnitude: x = ", x)
  1172. print("_test_activation_balancer_magnitude: y grad = ", y_grad)
  1173. print("_test_activation_balancer_magnitude: x grad = ", x.grad)
  1174. def _test_basic_norm():
  1175. num_channels = 128
  1176. m = BasicNorm(num_channels=num_channels, channel_dim=1)
  1177. x = torch.randn(500, num_channels)
  1178. y = m(x)
  1179. assert y.shape == x.shape
  1180. x_rms = (x ** 2).mean().sqrt()
  1181. y_rms = (y ** 2).mean().sqrt()
  1182. print("x rms = ", x_rms)
  1183. print("y rms = ", y_rms)
  1184. assert y_rms < x_rms
  1185. assert y_rms > 0.5 * x_rms
  1186. def _test_double_swish_deriv():
  1187. x = torch.randn(10, 12, dtype=torch.double) * 3.0
  1188. x.requires_grad = True
  1189. m = DoubleSwish()
  1190. tol = (1.2 - (-0.043637)) / 255.0
  1191. torch.autograd.gradcheck(m, x, atol=tol)
  1192. # for self-test.
  1193. x = torch.randn(1000, 1000, dtype=torch.double) * 3.0
  1194. x.requires_grad = True
  1195. y = m(x)
  1196. def _test_softmax():
  1197. a = torch.randn(2, 10, dtype=torch.float64)
  1198. b = a.clone()
  1199. a.requires_grad = True
  1200. b.requires_grad = True
  1201. a.softmax(dim=1)[:, 0].sum().backward()
  1202. print("a grad = ", a.grad)
  1203. softmax(b, dim=1)[:, 0].sum().backward()
  1204. print("b grad = ", b.grad)
  1205. assert torch.allclose(a.grad, b.grad)
  1206. if __name__ == "__main__":
  1207. logging.getLogger().setLevel(logging.INFO)
  1208. torch.set_num_threads(1)
  1209. torch.set_num_interop_threads(1)
  1210. _test_softmax()
  1211. _test_whiten()
  1212. _test_max_eig()
  1213. _test_activation_balancer_sign()
  1214. _test_activation_balancer_magnitude()
  1215. _test_basic_norm()
  1216. _test_double_swish_deriv()
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...