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

modeling_rwkv.py 60 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
  1. ########################################################################################################
  2. # The RWKV Language Model - https://github.com/BlinkDL/RWKV-LM
  3. ########################################################################################################
  4. from typing import Optional
  5. import types, gc, os, time, re
  6. import torch
  7. import torch.nn as nn
  8. from torch.nn import functional as F
  9. torch.backends.cudnn.benchmark = True
  10. torch.backends.cudnn.allow_tf32 = True
  11. torch.backends.cuda.matmul.allow_tf32 = True
  12. current_path = os.path.dirname(os.path.abspath(__file__))
  13. ########################################################################################################
  14. if os.environ.get('RWKV_JIT_ON') != '0':
  15. os.environ["RWKV_JIT_ON"] = '1'
  16. MyModule = torch.jit.ScriptModule
  17. MyFunction = torch.jit.script_method
  18. MyStatic = torch.jit.script
  19. else:
  20. MyModule = torch.nn.Module
  21. def __nop(ob):
  22. return ob
  23. MyFunction = __nop
  24. MyStatic = __nop
  25. if os.environ.get('RWKV_CUDA_ON') == '1':
  26. from torch.utils.cpp_extension import load
  27. try:
  28. load(
  29. name=f"wkv_cuda",
  30. sources=[f"{current_path}/cuda/wrapper.cpp", f"{current_path}/cuda/operators.cu", f"{current_path}/cuda/gemm_fp16_cublas.cpp"],
  31. verbose=True,
  32. extra_ldflags=["cublas.lib" if os.name == "nt" else ""],
  33. extra_cuda_cflags=["--use_fast_math", "-O3", "--extra-device-vectorization"],
  34. is_python_module=False)
  35. DISABLE_CUBLAS_GEMM = False
  36. except:
  37. print("Failed to build cuBLAS matmul, falling back to torch.matmul. Small model with fp16 will overflow.")
  38. load(
  39. name=f"wkv_cuda",
  40. sources=[f"{current_path}/cuda/wrapper.cpp", f"{current_path}/cuda/operators.cu"],
  41. verbose=True,
  42. extra_cuda_cflags=["--use_fast_math", "-O3", "--extra-device-vectorization"],
  43. extra_cflags=["-DDISABLE_CUBLAS_GEMM"],
  44. is_python_module=False)
  45. DISABLE_CUBLAS_GEMM = True
  46. @MyStatic
  47. def cuda_wkv(T: int, C: int, w, u, k, v, aa, bb, pp):
  48. assert 1 * C % min(C, 32) == 0
  49. assert k.dtype == v.dtype == torch.float16 or k.dtype == v.dtype == torch.float32
  50. assert w.dtype == u.dtype == aa.dtype == bb.dtype == pp.dtype == torch.float32
  51. w = w.contiguous()
  52. u = u.contiguous()
  53. k = k.contiguous()
  54. v = v.contiguous()
  55. y = torch.empty((T, C), device=w.device, memory_format=torch.contiguous_format, dtype=k.dtype)
  56. torch.ops.rwkv.wkv_forward(1, T, C, w, u, k, v, y, aa, bb, pp)
  57. return y, aa, bb, pp
  58. @MyStatic
  59. def cuda_mm8_seq(B: int, N: int, M: int, x, w, mx, rx, my, ry):
  60. assert x.dtype == mx.dtype == rx.dtype == my.dtype == ry.dtype
  61. assert x.dtype == torch.float32 or x.dtype == torch.float16
  62. assert w.dtype == torch.uint8
  63. assert x.shape == (B, N)
  64. assert w.shape == (N, M)
  65. assert rx.shape == mx.shape == (M,)
  66. assert ry.shape == my.shape == (N, 1)
  67. y = torch.empty((B, M), device=w.device, dtype=x.dtype)
  68. torch.ops.rwkv.mm8_seq(B, N, M, x, w, mx, rx, my, ry, y)
  69. return y
  70. @MyStatic
  71. def cuda_mm8_one(N: int, M: int, x, w, mx, rx, my, ry):
  72. assert x.dtype == mx.dtype == rx.dtype == my.dtype == ry.dtype
  73. assert x.dtype == torch.float32 or x.dtype == torch.float16
  74. assert w.dtype == torch.uint8
  75. assert x.shape == (N,)
  76. assert w.shape == (N, M)
  77. assert rx.shape == mx.shape == (M,)
  78. assert ry.shape == my.shape == (N, 1)
  79. y = torch.zeros((M,), device=w.device, dtype=torch.float32)
  80. torch.ops.rwkv.mm8_one(N, M, x, w, mx, rx, my, ry, y)
  81. return y.to(dtype=x.dtype)
  82. else:
  83. os.environ["RWKV_CUDA_ON"] = '0'
  84. @MyStatic
  85. def torch_mm8_seq(x, w, mx, rx, my, ry):
  86. return x @ ((w.to(dtype=x.dtype) + 0.5) * ry * rx + my + mx)
  87. @MyStatic
  88. def torch_mm8_one(x, w, mx, rx, my, ry):
  89. return x @ ((w.to(dtype=x.dtype) + 0.5) * ry * rx + my + mx)
  90. if os.environ.get('RWKV_CUDA_ON') == '1':
  91. @MyStatic
  92. def mm8_seq(x, w, mx, rx, my, ry):
  93. if w.device.type == 'cuda' and x.dtype == torch.float16:
  94. B, N, M = x.shape[0], w.shape[0], w.shape[1]
  95. return cuda_mm8_seq(B, N, M, x, w, mx, rx, my, ry)
  96. else:
  97. return torch_mm8_seq(x, w, mx, rx, my, ry)
  98. @MyStatic
  99. def mm8_one(x, w, mx, rx, my, ry):
  100. if w.device.type == 'cuda':
  101. N, M = w.shape[0], w.shape[1]
  102. return cuda_mm8_one(N, M, x, w, mx, rx, my, ry)
  103. else:
  104. return torch_mm8_one(x, w, mx, rx, my, ry)
  105. else:
  106. @MyStatic
  107. def mm8_seq(x, w, mx, rx, my, ry):
  108. return torch_mm8_seq(x, w, mx, rx, my, ry)
  109. @MyStatic
  110. def mm8_one(x, w, mx, rx, my, ry):
  111. return torch_mm8_one(x, w, mx, rx, my, ry)
  112. def mm8(x: torch.Tensor, w: torch.Tensor, mx: torch.Tensor, rx: torch.Tensor, my: torch.Tensor, ry: torch.Tensor):
  113. if len(x.shape) == 1:
  114. return mm8_one(x, w, mx, rx, my, ry)
  115. return mm8_seq(x, w, mx, rx, my, ry)
  116. def matmul(a, b, mx: Optional[torch.Tensor]=None, rx: Optional[torch.Tensor]=None, my: Optional[torch.Tensor]=None, ry: Optional[torch.Tensor]=None, output_dtype: Optional[torch.dtype]=None) -> torch.Tensor:
  117. if output_dtype is None:
  118. output_dtype = a.dtype
  119. if b.dtype in [torch.float16, torch.bfloat16, torch.float32]:
  120. assert a.dtype == b.dtype
  121. return matmul_float(a, b, output_dtype=output_dtype)
  122. elif b.dtype == torch.uint8:
  123. assert mx is not None
  124. assert rx is not None
  125. assert my is not None
  126. assert ry is not None
  127. return mm8(a, b, mx, rx, my, ry).to(output_dtype)
  128. else:
  129. raise ValueError("Unsupported dtype")
  130. if os.environ.get('RWKV_CUDA_ON') == '1' and not DISABLE_CUBLAS_GEMM:
  131. def matmul_float(a, b, output_dtype: Optional[torch.dtype]=None):
  132. if output_dtype is None:
  133. output_dtype = a.dtype
  134. if a.dtype == b.dtype == torch.float16 and a.device.type == 'cuda':
  135. if len(a.shape) == 1:
  136. assert len(b.shape) == 2
  137. c = torch.empty((b.shape[-1],), dtype=output_dtype, device=a.device)
  138. a = a.unsqueeze(0)
  139. else:
  140. assert len(a.shape) == len(b.shape)
  141. assert len(a.shape) == 2 or len(a.shape) == 3
  142. # torch.empty((*a.shape[:-1], b.shape[-1])) doesn't work with jit
  143. if len(a.shape) == 2:
  144. c = torch.empty((a.shape[0], b.shape[-1]), dtype=output_dtype, device=a.device)
  145. else:
  146. c = torch.empty((a.shape[0], a.shape[1], b.shape[-1]), dtype=output_dtype, device=a.device)
  147. torch.ops.rwkv.gemm_fp16_cublas(a, b, c)
  148. return c
  149. else:
  150. return (a @ b).to(output_dtype)
  151. else:
  152. def matmul_float(a, b, output_dtype: Optional[torch.dtype]=None):
  153. return (a @ b).to(output_dtype)
  154. if os.environ.get('RWKV_DML_ON') == '1':
  155. import torch_directml
  156. print("PyTorch with DirectML Enabled")
  157. ########################################################################################################
  158. class RWKV(MyModule):
  159. def __init__(self, model, strategy, verbose = True, convert_and_save_and_exit = None):
  160. super().__init__()
  161. if verbose:
  162. prxxx = lambda *args, **kwargs: print(*args, **kwargs)
  163. else:
  164. prxxx = lambda *args, **kwargs: None
  165. STRATEGY_REGEX = r"^(?:(?:^|->) *(?:cuda(?::[\d]+)?|cpu|mps|dml) (?:fp(?:16|32)|bf16)(?:i8|i4|i3)?(?: \*[\d]+\+?)? *)+$"
  166. if not re.match(STRATEGY_REGEX, strategy):
  167. raise ValueError("Invalid strategy. Please read https://pypi.org/project/rwkv/")
  168. strategy = ('->'.join([x.strip() for x in strategy.split('->')])).replace('->', ' -> ')
  169. self.args = types.SimpleNamespace()
  170. args = self.args
  171. args.MODEL_NAME = model
  172. args.strategy_string = strategy
  173. # Rescale for fp16 mode: set x = x/2 every X layer (to avoid fp16 overflow)
  174. try:
  175. self.RESCALE_LAYER = int(os.environ["RWKV_RESCALE_LAYER"]) # !!! NOTE: SEEMS YOU SHOULD SET IT TO 999 (disable) FOR RWKV-MUSIC MODELS !!!
  176. except:
  177. self.RESCALE_LAYER = 6 if 'fp16' in strategy else 0
  178. prxxx(f'RWKV_JIT_ON {os.environ["RWKV_JIT_ON"]} RWKV_CUDA_ON {os.environ["RWKV_CUDA_ON"]} RESCALE_LAYER {self.RESCALE_LAYER}\n')
  179. args.MODEL_NAME = args.MODEL_NAME.strip()
  180. if not args.MODEL_NAME.endswith('.pth'):
  181. args.MODEL_NAME += '.pth'
  182. prxxx(f'Loading {args.MODEL_NAME} ...')
  183. with torch.no_grad():
  184. self.w = torch.load(args.MODEL_NAME, map_location='cpu') # load model to CPU first
  185. gc.collect()
  186. w = self.w
  187. ALREADY_CONVERTED = False
  188. if '_strategy' in w:
  189. ALREADY_CONVERTED = True
  190. assert convert_and_save_and_exit == None # you should only convert a raw model
  191. prxxx(f"Converted model: strategy {w['_strategy']}, version {w['_version']}\n")
  192. assert w['_strategy'] == args.strategy_string # if you are using a new strategy, re-convert the model
  193. assert float(w['_version']) >= 0.7 # sometimes you should re-convert using latest convert_model.py
  194. assert w['_rescale_layer'] == self.RESCALE_LAYER # must use same RESCALE_LAYER to avoid mistakes
  195. del w['_strategy']
  196. del w['_version']
  197. del w['_rescale_layer']
  198. args.n_embd = w['emb.weight'].shape[1]
  199. args.n_att = w['blocks.0.att.key.weight'].shape[0] # note: transposed matrix
  200. args.n_ffn = w['blocks.0.ffn.key.weight'].shape[0] # note: transposed matrix
  201. args.n_layer = 0
  202. keys = list(w.keys())
  203. self.version = 4
  204. for x in keys:
  205. layer_id = int(x.split('.')[1]) if ('blocks.' in x) else 0
  206. args.n_layer = max(args.n_layer, layer_id+1)
  207. if 'ln_x' in x:
  208. self.version = max(5, self.version)
  209. if 'gate.weight' in x:
  210. self.version = max(5.1, self.version)
  211. if int(self.version) == 5 and 'att.time_decay' in x:
  212. args.n_head = w[x].shape[0]
  213. if len(w[x].shape) > 1:
  214. if w[x].shape[1] > 1:
  215. self.version = max(5.2, self.version)
  216. if 'time_maa' in x:
  217. self.version = max(6, self.version)
  218. if int(self.version) == 6 and 'time_faaaa' in x:
  219. args.n_head = w[x].shape[0]
  220. prxxx(f'Model detected: v{self.version:.1f}')
  221. ####################### Compute strategy
  222. s = [x.strip().split(' ') for x in strategy.split('->')]
  223. plan = [0] * len(s)
  224. stream_i = -1
  225. stream_count = 0
  226. to_allocate = args.n_layer + 1
  227. allocated = 0
  228. free_slots = 0
  229. for i in range(len(s)):
  230. si = s[i]
  231. si1 = si[1]
  232. if si1.startswith('fp32'): si[1] = [torch.float]
  233. elif si1.startswith('fp16'): si[1] = [torch.float16]
  234. elif si1.startswith('bf16'): si[1] = [torch.bfloat16]
  235. if si1.endswith('i8'): si[1] += [torch.uint8]
  236. else: si[1] += [si[1][0]]
  237. if len(si) > 2:
  238. ss = si[2]
  239. assert ss.startswith('*')
  240. if ss.endswith('+'):
  241. plan[i] = int(ss[1:-1])
  242. stream_i = i
  243. else:
  244. plan[i] = int(ss[1:])
  245. allocated += plan[i]
  246. if allocated >= to_allocate:
  247. plan[i] += to_allocate - allocated
  248. break
  249. else:
  250. free_slots += 1
  251. if stream_i < 0:
  252. if free_slots > 0 and to_allocate > allocated:
  253. for i in range(len(s)):
  254. if plan[i] == 0:
  255. plan[i] = (to_allocate - allocated) // free_slots
  256. allocated += plan[i]
  257. free_slots -= 1
  258. if to_allocate > allocated:
  259. plan[len(s)-1] += to_allocate - allocated
  260. else:
  261. if to_allocate > allocated:
  262. stream_count = to_allocate - allocated
  263. plan[stream_i] += stream_count
  264. prxxx(f'Strategy: (total {args.n_layer}+1={args.n_layer+1} layers)')
  265. for i in range(len(s)):
  266. ss = s[i]
  267. if i != stream_i:
  268. prxxx(f'* {ss[0]} {str(ss[1]).replace("torch.","")}, store {plan[i]} layers')
  269. else:
  270. prxxx(f'* {ss[0]} {str(ss[1]).replace("torch.","")}, store {plan[i]-stream_count} layers, stream {stream_count} layers')
  271. plan[i] += (0 if i == 0 else plan[i-1])
  272. self.strategy = [None] * (args.n_layer + 1)
  273. strategy = self.strategy
  274. for n in range(args.n_layer + 1):
  275. for i in range(len(s)):
  276. if n < plan[i]:
  277. strategy[n] = types.SimpleNamespace()
  278. strategy[n].device = s[i][0]
  279. strategy[n].atype = s[i][1][0]
  280. strategy[n].wtype = s[i][1][1]
  281. strategy[n].stream = False
  282. if strategy[n].device == 'dml':
  283. strategy[n].device = torch_directml.device()
  284. if i == stream_i and n >= (plan[i] - stream_count):
  285. strategy[n].stream = True
  286. break
  287. prxxx(f"{n}-{strategy[n].device}-{str(strategy[n].atype).replace('torch.','')}-{str(strategy[n].wtype).replace('torch.','')}{'-stream' if strategy[n].stream else ''}",end=' ')
  288. prxxx()
  289. ####################### Load weights to self.w
  290. if not ALREADY_CONVERTED:
  291. try: # precompute embedding
  292. w['emb.weight'] = F.layer_norm(w['emb.weight'], (args.n_embd,), weight=w['blocks.0.ln0.weight'], bias=w['blocks.0.ln0.bias'])
  293. except:
  294. w['emb.weight'] = F.layer_norm(w['emb.weight'].float(), (args.n_embd,), weight=w['blocks.0.ln0.weight'].float(), bias=w['blocks.0.ln0.bias'].float())
  295. # del w['blocks.0.ln0.weight']
  296. # del w['blocks.0.ln0.bias']
  297. print_need_newline = False
  298. REAL_TIME_FIRST = False
  299. for x in list(w.keys()):
  300. if '.time_faaaa' in x: REAL_TIME_FIRST = True
  301. if REAL_TIME_FIRST:
  302. w = {k.replace('.time_faaaa','.time_first') if '.time_faaaa' in k else k: v for k, v in w.items()}
  303. self.w = w
  304. keys = list(w.keys())
  305. for x in keys:
  306. w[x].requires_grad = False
  307. layer_id = int(x.split('.')[1]) if ('blocks.' in x) else 0
  308. if ('ln_out.' in x) or ('head.' in x):
  309. layer_id = args.n_layer
  310. dd = strategy[layer_id]
  311. DEVICE = dd.device
  312. ATYPE = dd.atype
  313. WTYPE = dd.wtype
  314. if not ALREADY_CONVERTED:
  315. if self.RESCALE_LAYER > 0:
  316. if 'att.output.weight' in x:
  317. w[x] = w[x] / (2 ** int(layer_id // self.RESCALE_LAYER))
  318. if 'ffn.value.weight' in x:
  319. w[x] = w[x] / (2 ** int(layer_id // self.RESCALE_LAYER))
  320. if '.time_' in x:
  321. w[x] = w[x].squeeze()
  322. if 'key.weight' in x or 'value.weight' in x or 'receptance.weight' in x or 'gate.weight' in x or 'output.weight' in x or 'head.weight' in x:
  323. w[x] = w[x].t()
  324. if '.time_decay' in x and '_w' not in x: # need fp32 for this
  325. if self.version == 4:
  326. w[x] = -torch.exp(w[x].float())
  327. elif int(self.version) == 5:
  328. w[x] = torch.exp(-torch.exp(w[x].float())).reshape(-1,1,1)
  329. if self.version == 5.2:
  330. w[x] = w[x].reshape(args.n_head, -1, 1)
  331. elif self.version == 6.0:
  332. w[x] = w[x].float().reshape(args.n_head, -1, 1)
  333. elif '.time_first' in x: # need fp32 for this
  334. if self.version == 4:
  335. w[x] = w[x].float()
  336. elif int(self.version) in [5, 6]:
  337. if REAL_TIME_FIRST:
  338. w[x] = w[x].float().reshape(-1,1,1)
  339. else:
  340. w[x] = torch.exp(w[x].float()).reshape(-1,1,1)
  341. if self.version in [5.2, 6.0]:
  342. w[x] = w[x].reshape(args.n_head, -1, 1)
  343. elif '.ln_x' in x: # need fp32 for group_norm
  344. w[x] = w[x].float()
  345. else:
  346. if (len(w[x].shape) == 2) and ('emb' not in x):
  347. if WTYPE != torch.uint8:
  348. w[x] = w[x].to(dtype=WTYPE)
  349. else:
  350. w[x] = w[x].float()
  351. if w[x].shape[0] > w[x].shape[1]:
  352. w[x+'_my'] = torch.amin(w[x], dim=1).unsqueeze(1)
  353. w[x] = w[x] - w[x+'_my']
  354. w[x+'_mx'] = torch.amin(w[x], dim=0)
  355. w[x] = w[x] - w[x+'_mx']
  356. w[x+'_rx'] = torch.amax(w[x], dim=0)
  357. w[x] = w[x] / w[x+'_rx']
  358. w[x+'_ry'] = torch.amax(w[x], dim=1).unsqueeze(1)
  359. w[x] = w[x] / w[x+'_ry']
  360. else:
  361. w[x+'_mx'] = torch.amin(w[x], dim=0)
  362. w[x] = w[x] - w[x+'_mx']
  363. w[x+'_my'] = torch.amin(w[x], dim=1).unsqueeze(1)
  364. w[x] = w[x] - w[x+'_my']
  365. w[x+'_rx'] = torch.amax(w[x], dim=0)
  366. w[x] = w[x] / w[x+'_rx']
  367. w[x+'_ry'] = torch.amax(w[x], dim=1).unsqueeze(1)
  368. w[x] = w[x] / w[x+'_ry']
  369. w[x] = torch.clip(torch.floor(w[x] * 256), min=0, max=255).to(dtype=torch.uint8)
  370. w[x+'_mx'] = w[x+'_mx'].to(dtype=ATYPE).contiguous()
  371. w[x+'_rx'] = (w[x+'_rx'] / 16).to(dtype=ATYPE).contiguous()
  372. w[x+'_my'] = w[x+'_my'].to(dtype=ATYPE).contiguous()
  373. w[x+'_ry'] = (w[x+'_ry'] / 16).to(dtype=ATYPE).contiguous()
  374. else:
  375. w[x] = w[x].to(dtype=ATYPE)
  376. if convert_and_save_and_exit == None:
  377. if 'emb.' in x:
  378. w[x] = w[x].contiguous()
  379. elif (dd.stream) and (x.endswith('key.weight') or x.endswith('value.weight') or x.endswith('receptance.weight') or x.endswith('output.weight')):
  380. try:
  381. w[x] = w[x].contiguous().pin_memory() # if you see "CUDA error: out of memory" here, that's out of CPU RAM, not VRAM. Get more RAM :)
  382. except:
  383. print('Note: You are running out of RAM. Get more CPU RAM. Now this will run much slower.')
  384. elif DEVICE != 'cpu':
  385. w[x] = w[x].to(device=DEVICE).contiguous()
  386. if (dd.stream) or (DEVICE != 'cpu'):
  387. try:
  388. w[x+'_mx'] = w[x+'_mx'].to(device=DEVICE).contiguous()
  389. w[x+'_rx'] = w[x+'_rx'].to(device=DEVICE).contiguous()
  390. w[x+'_my'] = w[x+'_my'].to(device=DEVICE).contiguous()
  391. w[x+'_ry'] = w[x+'_ry'].to(device=DEVICE).contiguous()
  392. except:
  393. pass
  394. if 'ffn.value.weight' in x:
  395. gc.collect()
  396. if 'cuda' in args.strategy_string:
  397. torch.cuda.empty_cache()
  398. shape = [i for i in w[x].shape if i != 1]
  399. if len(shape) > 1:
  400. shape = f" {str(shape[0]).rjust(5)} {str(shape[1]).rjust(5)}"
  401. else:
  402. shape = f" {str(shape[0]).rjust(5)} "
  403. if layer_id == 0 or layer_id >= args.n_layer-1:
  404. if print_need_newline:
  405. prxxx('\n', end = '')
  406. print_need_newline = False
  407. dt = str(w[x].dtype).replace('torch.', '')
  408. dt = dt.replace('float32', 'f32').replace('bfloat16', 'bf16').replace('float16', 'f16').replace('uint8', 'i8')
  409. prxxx(x.ljust(32), dt.rjust(4), str(w[x].device).rjust(8), shape, ' (pinned)' if w[x].is_pinned() else '')
  410. else:
  411. print_need_newline = True
  412. prxxx('.', end = '', flush = True)
  413. if convert_and_save_and_exit:
  414. w['_strategy'] = args.strategy_string
  415. w['_rescale_layer'] = self.RESCALE_LAYER
  416. w['_version'] = '0.7'
  417. if not convert_and_save_and_exit.endswith('.pth'):
  418. convert_and_save_and_exit += '.pth'
  419. prxxx(f'Saving to {convert_and_save_and_exit}...')
  420. torch.save(w, convert_and_save_and_exit)
  421. prxxx(f'Converted and saved. Now this will exit.')
  422. exit(0)
  423. if self.version == 5.2 and os.environ["RWKV_CUDA_ON"] == '1':
  424. HEAD_SIZE = args.n_att // args.n_head
  425. rwkv5 = load(name="rwkv5", sources=[f"{current_path}/cuda/rwkv5_op.cpp", f"{current_path}/cuda/rwkv5.cu"],
  426. verbose=True, extra_cuda_cflags=["-res-usage", "--use_fast_math", "-O3", "-Xptxas -O3" if os.name != "nt" else "", "--extra-device-vectorization", f"-D_N_={HEAD_SIZE}"])
  427. class RWKV_5(torch.autograd.Function):
  428. @staticmethod
  429. def forward(ctx, B, T, C, H, state, r, k, v, w, u):
  430. with torch.no_grad():
  431. assert HEAD_SIZE == C // H
  432. ctx.B = B
  433. ctx.T = T
  434. ctx.C = C
  435. ctx.H = H
  436. assert state.dtype == torch.float32
  437. assert w.dtype == torch.float32
  438. assert r.is_contiguous()
  439. assert k.is_contiguous()
  440. assert v.is_contiguous()
  441. assert w.is_contiguous()
  442. assert u.is_contiguous()
  443. assert state.is_contiguous()
  444. y = torch.empty((B, T, C), device=w.device, dtype=r.dtype, memory_format=torch.contiguous_format)
  445. if r.dtype == torch.bfloat16:
  446. rwkv5.forward_bf16(B, T, C, H, state, r, k, v, w, u, y)
  447. elif r.dtype == torch.float16:
  448. rwkv5.forward_fp16(B, T, C, H, state, r, k, v, w, u, y)
  449. elif r.dtype == torch.float32:
  450. rwkv5.forward_fp32(B, T, C, H, state, r, k, v, w, u, y)
  451. return y, state
  452. self.RWKV_5 = RWKV_5
  453. if self.version == 6.0 and os.environ["RWKV_CUDA_ON"] == '1':
  454. HEAD_SIZE = args.n_att // args.n_head
  455. rwkv6 = load(name="rwkv6", sources=[f"{current_path}/cuda/rwkv6_op.cpp", f"{current_path}/cuda/rwkv6.cu"],
  456. verbose=True, extra_cuda_cflags=["-res-usage", "--use_fast_math", "-O3", "-Xptxas -O3", "--extra-device-vectorization", f"-D_N_={HEAD_SIZE}", f"-D_T_={4096}"])
  457. class RWKV_6(torch.autograd.Function):
  458. @staticmethod
  459. def forward(ctx, B, T, C, H, state, r, k, v, w, u):
  460. with torch.no_grad():
  461. assert HEAD_SIZE == C // H
  462. ctx.B = B
  463. ctx.T = T
  464. ctx.C = C
  465. ctx.H = H
  466. assert state.dtype == torch.float32
  467. assert w.dtype == torch.float32
  468. assert r.is_contiguous()
  469. assert k.is_contiguous()
  470. assert v.is_contiguous()
  471. assert w.is_contiguous()
  472. assert u.is_contiguous()
  473. eew = torch.exp(-torch.exp(w.float())).contiguous()
  474. y = torch.empty((B, T, C), device=w.device, dtype=r.dtype, memory_format=torch.contiguous_format)
  475. if r.dtype == torch.bfloat16:
  476. rwkv6.forward_bf16(B, T, C, H, state, r, k, v, eew, u, y)
  477. elif r.dtype == torch.float16:
  478. rwkv6.forward_fp16(B, T, C, H, state, r, k, v, eew, u, y)
  479. elif r.dtype == torch.float32:
  480. rwkv6.forward_fp32(B, T, C, H, state, r, k, v, eew, u, y)
  481. return y, state
  482. self.RWKV_6 = RWKV_6
  483. gc.collect()
  484. if 'cuda' in args.strategy_string:
  485. torch.cuda.empty_cache()
  486. def RUN_RWKV_5(self, B, T, C, H, state, r, k, v, w, u):
  487. return self.RWKV_5.apply(B, T, C, H, state, r, k, v, w, u)
  488. def RUN_RWKV_6(self, B, T, C, H, state, r, k, v, w, u):
  489. return self.RWKV_6.apply(B, T, C, H, state, r, k, v, w, u)
  490. ########################################################################################################
  491. @MyFunction
  492. def ffn_one(self, x, sx, ln_w, ln_b, k_mix, r_mix, kw, vw, rw, kmx, krx, kmy, kry, vmx, vrx, vmy, vry, rmx, rrx, rmy, rry):
  493. xx = F.layer_norm(x, (x.shape[-1],), weight=ln_w, bias=ln_b)
  494. kx = xx * k_mix + sx * (1 - k_mix)
  495. rx = xx * r_mix + sx * (1 - r_mix)
  496. r = torch.sigmoid(matmul(rx, rw, rmx, rrx, rmy, rry))
  497. vx = torch.relu(matmul(kx, kw, kmx, krx, kmy, kry)) ** 2
  498. out = r * matmul(vx, vw, vmx, vrx, vmy, vry)
  499. return x + out, xx
  500. @MyFunction
  501. def ffn_seq(self, x, sx, ln_w, ln_b, k_mix, r_mix, kw, vw, rw, kmx, krx, kmy, kry, vmx, vrx, vmy, vry, rmx, rrx, rmy, rry):
  502. xx = F.layer_norm(x, (x.shape[-1],), weight=ln_w, bias=ln_b)
  503. sx = torch.cat((sx.unsqueeze(0), xx[:-1,:]))
  504. kx = xx * k_mix + sx * (1 - k_mix)
  505. rx = xx * r_mix + sx * (1 - r_mix)
  506. r = torch.sigmoid(matmul(rx, rw, rmx, rrx, rmy, rry))
  507. vx = torch.relu(matmul(kx, kw, kmx, krx, kmy, kry)) ** 2
  508. out = r * matmul(vx, vw, vmx, vrx, vmy, vry)
  509. return x + out, xx[-1,:]
  510. @MyFunction
  511. def ffn_one_v6(self, x, sx, ln_w, ln_b, k_maa, r_maa, kw, vw, rw, kmx, krx, kmy, kry, vmx, vrx, vmy, vry, rmx, rrx, rmy, rry):
  512. xx = F.layer_norm(x, (x.shape[-1],), weight=ln_w, bias=ln_b)
  513. sx = sx - xx
  514. kx = xx + sx * k_maa
  515. rx = xx + sx * r_maa
  516. r = torch.sigmoid(matmul(rx, rw, rmx, rrx, rmy, rry))
  517. vx = torch.relu(matmul(kx, kw, kmx, krx, kmy, kry)) ** 2
  518. out = r * matmul(vx, vw, vmx, vrx, vmy, vry)
  519. return x + out, xx
  520. @MyFunction
  521. def ffn_seq_v6(self, x, sx, ln_w, ln_b, k_maa, r_maa, kw, vw, rw, kmx, krx, kmy, kry, vmx, vrx, vmy, vry, rmx, rrx, rmy, rry):
  522. xx = F.layer_norm(x, (x.shape[-1],), weight=ln_w, bias=ln_b)
  523. sx = torch.cat((sx.unsqueeze(0), xx[:-1,:]))
  524. sx = sx - xx
  525. kx = xx + sx * k_maa
  526. rx = xx + sx * r_maa
  527. r = torch.sigmoid(matmul(rx, rw, rmx, rrx, rmy, rry))
  528. vx = torch.relu(matmul(kx, kw, kmx, krx, kmy, kry)) ** 2
  529. out = r * matmul(vx, vw, vmx, vrx, vmy, vry)
  530. return x + out, xx[-1,:]
  531. ########################################################################################################
  532. @MyFunction
  533. def att_one(self, x, sx, aa, bb, pp, ln_w, ln_b, k_mix, v_mix, r_mix, t_decay, t_first, kw, vw, rw, ow, kmx, krx, kmy, kry, vmx, vrx, vmy, vry, rmx, rrx, rmy, rry, omx, orx, omy, ory):
  534. xx = F.layer_norm(x, (x.shape[-1],), weight=ln_w, bias=ln_b)
  535. kx = xx * k_mix + sx * (1 - k_mix)
  536. vx = xx * v_mix + sx * (1 - v_mix)
  537. rx = xx * r_mix + sx * (1 - r_mix)
  538. r = torch.sigmoid(matmul(rx, rw, rmx, rrx, rmy, rry))
  539. k = matmul(kx, kw, kmx, krx, kmy, kry, output_dtype=torch.float32)
  540. v = matmul(vx, vw, vmx, vrx, vmy, vry, output_dtype=torch.float32)
  541. ww = t_first + k
  542. p = torch.maximum(pp, ww)
  543. e1 = torch.exp(pp - p)
  544. e2 = torch.exp(ww - p)
  545. wkv = ((e1 * aa + e2 * v) / (e1 * bb + e2)).to(dtype=x.dtype)
  546. ww = t_decay + pp
  547. p = torch.maximum(ww, k)
  548. e1 = torch.exp(ww - p)
  549. e2 = torch.exp(k - p)
  550. out = matmul(r * wkv, ow, omx, orx, omy, ory)
  551. return x + out, xx, e1 * aa + e2 * v, e1 * bb + e2, p
  552. @MyFunction
  553. def att_seq(self, x, sx, aa, bb, pp, ln_w, ln_b, k_mix, v_mix, r_mix, t_decay, t_first, kw, vw, rw, ow, kmx, krx, kmy, kry, vmx, vrx, vmy, vry, rmx, rrx, rmy, rry, omx, orx, omy, ory):
  554. xx = F.layer_norm(x, (x.shape[-1],), weight=ln_w, bias=ln_b)
  555. sx = torch.cat((sx.unsqueeze(0), xx[:-1,:]))
  556. kx = xx * k_mix + sx * (1 - k_mix)
  557. vx = xx * v_mix + sx * (1 - v_mix)
  558. rx = xx * r_mix + sx * (1 - r_mix)
  559. r = torch.sigmoid(matmul(rx, rw, rmx, rrx, rmy, rry))
  560. k = matmul(kx, kw, kmx, krx, kmy, kry, output_dtype=torch.float32)
  561. v = matmul(vx, vw, vmx, vrx, vmy, vry, output_dtype=torch.float32)
  562. T = x.shape[0]
  563. for t in range(T):
  564. kk = k[t]
  565. vv = v[t]
  566. ww = t_first + kk
  567. p = torch.maximum(pp, ww)
  568. e1 = torch.exp(pp - p)
  569. e2 = torch.exp(ww - p)
  570. sx[t] = ((e1 * aa + e2 * vv) / (e1 * bb + e2)).to(dtype=x.dtype)
  571. ww = t_decay + pp
  572. p = torch.maximum(ww, kk)
  573. e1 = torch.exp(ww - p)
  574. e2 = torch.exp(kk - p)
  575. aa = e1 * aa + e2 * vv
  576. bb = e1 * bb + e2
  577. pp = p
  578. out = matmul(r * sx, ow, omx, orx, omy, ory)
  579. return x + out, xx[-1,:], aa, bb, pp
  580. ########################################################################################################
  581. @MyFunction
  582. def att_one_v5(self, x, sx, s, ln_w, ln_b, lx_w, lx_b, k_mix, v_mix, r_mix, t_decay, t_first, kw, vw, rw, ow, kmx, krx, kmy, kry, vmx, vrx, vmy, vry, rmx, rrx, rmy, rry, omx, orx, omy, ory):
  583. xx = F.layer_norm(x, (x.shape[-1],), weight=ln_w, bias=ln_b)
  584. kx = xx * k_mix + sx * (1 - k_mix)
  585. vx = xx * v_mix + sx * (1 - v_mix)
  586. rx = xx * r_mix + sx * (1 - r_mix)
  587. H = t_decay.shape[0]
  588. N = x.shape[-1] // H
  589. r = matmul(rx, rw, rmx, rrx, rmy, rry, output_dtype=torch.float32).view(H, 1, N)
  590. k = matmul(kx, kw, kmx, krx, kmy, kry, output_dtype=torch.float32).view(H, N, 1)
  591. v = matmul(vx, vw, vmx, vrx, vmy, vry, output_dtype=torch.float32).view(H, 1, N)
  592. a = matmul(k, v)
  593. out = r @ (t_first * a + s)
  594. s = a + t_decay * s
  595. out = out.flatten()
  596. out = F.group_norm(out.unsqueeze(0), num_groups=H, weight=lx_w, bias=lx_b, eps = 64e-5).squeeze(0)
  597. out = out.to(dtype=x.dtype)
  598. out = matmul(out, ow, omx, orx, omy, ory)
  599. return x + out, xx, s
  600. @MyFunction
  601. def att_seq_v5(self, x, sx, s, ln_w, ln_b, lx_w, lx_b, k_mix, v_mix, r_mix, t_decay, t_first, kw, vw, rw, ow, kmx, krx, kmy, kry, vmx, vrx, vmy, vry, rmx, rrx, rmy, rry, omx, orx, omy, ory):
  602. xx = F.layer_norm(x, (x.shape[-1],), weight=ln_w, bias=ln_b)
  603. sx = torch.cat((sx.unsqueeze(0), xx[:-1,:]))
  604. kx = xx * k_mix + sx * (1 - k_mix)
  605. vx = xx * v_mix + sx * (1 - v_mix)
  606. rx = xx * r_mix + sx * (1 - r_mix)
  607. H = t_decay.shape[0]
  608. N = x.shape[-1] // H
  609. T = x.shape[0]
  610. w = t_decay.reshape(-1, 1)
  611. u = t_first.reshape(-1, 1)
  612. ws = w.pow(T).reshape(H, 1, 1)
  613. ind = torch.arange(T-1, -1, -1, device=w.device).unsqueeze(0).repeat(H, 1)
  614. w = w.repeat(1, T).pow(ind)
  615. wk = w.reshape(H, 1, T)
  616. wb = wk.transpose(-2, -1).flip(1)
  617. w = torch.cat([w[:, 1:], u], dim=1)
  618. w = F.pad(w, (0, T))
  619. w = torch.tile(w, [T])
  620. w = w[:, :-T].reshape(-1, T, 2 * T - 1)
  621. w = w[:, :, T-1:].reshape(H, T, T)
  622. r = matmul(rx, rw, rmx, rrx, rmy, rry, output_dtype=torch.float32).view(T, H, N).transpose(0, 1)
  623. k = matmul(kx, kw, kmx, krx, kmy, kry, output_dtype=torch.float32).view(T, H, N).permute(1, 2, 0)
  624. v = matmul(vx, vw, vmx, vrx, vmy, vry, output_dtype=torch.float32).view(T, H, N).transpose(0, 1)
  625. out = ((r @ k) * w) @ v + (r @ s) * wb
  626. s = ws * s + (k * wk) @ v
  627. out = out.transpose(0, 1).contiguous().reshape(T, H*N)
  628. out = F.group_norm(out, num_groups=H, weight=lx_w, bias=lx_b, eps = 64e-5)
  629. out = out.to(dtype=x.dtype)
  630. out = matmul(out, ow, omx, orx, omy, ory)
  631. return x + out, xx[-1,:], s
  632. ########################################################################################################
  633. @MyFunction
  634. def att_one_v5_1(self, x, sx, s, ln_w, ln_b, lx_w, lx_b, k_mix, v_mix, r_mix, g_mix, t_decay, t_first, kw, vw, rw, gw, ow, kmx, krx, kmy, kry, vmx, vrx, vmy, vry, rmx, rrx, rmy, rry, gmx, grx, gmy, gry, omx, orx, omy, ory):
  635. xx = F.layer_norm(x, (x.shape[-1],), weight=ln_w, bias=ln_b)
  636. kx = xx * k_mix + sx * (1 - k_mix)
  637. vx = xx * v_mix + sx * (1 - v_mix)
  638. rx = xx * r_mix + sx * (1 - r_mix)
  639. gx = xx * g_mix + sx * (1 - g_mix)
  640. H = t_decay.shape[0]
  641. N = x.shape[-1] // H
  642. r = matmul(rx, rw, rmx, rrx, rmy, rry, output_dtype=torch.float32).view(H, 1, N)
  643. k = matmul(kx, kw, kmx, krx, kmy, kry, output_dtype=torch.float32).view(H, N, 1)
  644. v = matmul(vx, vw, vmx, vrx, vmy, vry, output_dtype=torch.float32).view(H, 1, N)
  645. g = F.silu(matmul(gx, gw, gmx, grx, gmy, gry))
  646. a = matmul(k, v)
  647. out = r @ (t_first * a + s)
  648. s = a + t_decay * s
  649. out = out.flatten()
  650. out = F.group_norm(out.unsqueeze(0), num_groups=H, weight=lx_w, bias=lx_b, eps = 64e-5).squeeze(0)
  651. out = out.to(dtype=x.dtype) * g
  652. out = matmul(out, ow, omx, orx, omy, ory)
  653. return x + out, xx, s
  654. @MyFunction
  655. def att_seq_v5_1(self, x, sx, s, ln_w, ln_b, lx_w, lx_b, k_mix, v_mix, r_mix, g_mix, t_decay, t_first, kw, vw, rw, gw, ow, kmx, krx, kmy, kry, vmx, vrx, vmy, vry, rmx, rrx, rmy, rry, gmx, grx, gmy, gry, omx, orx, omy, ory):
  656. xx = F.layer_norm(x, (x.shape[-1],), weight=ln_w, bias=ln_b)
  657. sx = torch.cat((sx.unsqueeze(0), xx[:-1,:]))
  658. kx = xx * k_mix + sx * (1 - k_mix)
  659. vx = xx * v_mix + sx * (1 - v_mix)
  660. rx = xx * r_mix + sx * (1 - r_mix)
  661. gx = xx * g_mix + sx * (1 - g_mix)
  662. H = t_decay.shape[0]
  663. N = x.shape[-1] // H
  664. T = x.shape[0]
  665. w = t_decay.reshape(-1, 1)
  666. u = t_first.reshape(-1, 1)
  667. ws = w.pow(T).reshape(H, 1, 1)
  668. ind = torch.arange(T-1, -1, -1, device=w.device).unsqueeze(0).repeat(H, 1)
  669. w = w.repeat(1, T).pow(ind)
  670. wk = w.reshape(H, 1, T)
  671. wb = wk.transpose(-2, -1).flip(1)
  672. w = torch.cat([w[:, 1:], u], dim=1)
  673. w = F.pad(w, (0, T))
  674. w = torch.tile(w, [T])
  675. w = w[:, :-T].reshape(-1, T, 2 * T - 1)
  676. w = w[:, :, T-1:].reshape(H, T, T)
  677. r = matmul(rx, rw, rmx, rrx, rmy, rry, output_dtype=torch.float32).view(T, H, N).transpose(0, 1)
  678. k = matmul(kx, kw, kmx, krx, kmy, kry, output_dtype=torch.float32).view(T, H, N).permute(1, 2, 0)
  679. v = matmul(vx, vw, vmx, vrx, vmy, vry, output_dtype=torch.float32).view(T, H, N).transpose(0, 1)
  680. g = F.silu(matmul(gx, gw, gmx, grx, gmy, gry))
  681. out = ((r @ k) * w) @ v + (r @ s) * wb
  682. s = ws * s + (k * wk) @ v
  683. out = out.transpose(0, 1).contiguous().reshape(T, H*N)
  684. out = F.group_norm(out, num_groups=H, weight=lx_w, bias=lx_b, eps = 64e-5)
  685. out = out.to(dtype=x.dtype) * g
  686. out = matmul(out, ow, omx, orx, omy, ory)
  687. return x + out, xx[-1,:], s
  688. ########################################################################################################
  689. @MyFunction
  690. def att_seq_v5_2(self, x, sx, s, ln_w, ln_b, lx_w, lx_b, k_mix, v_mix, r_mix, g_mix, t_decay, t_first, kw, vw, rw, gw, ow, kmx, krx, kmy, kry, vmx, vrx, vmy, vry, rmx, rrx, rmy, rry, gmx, grx, gmy, gry, omx, orx, omy, ory):
  691. xx = F.layer_norm(x, (x.shape[-1],), weight=ln_w, bias=ln_b)
  692. sx = torch.cat((sx.unsqueeze(0), xx[:-1,:]))
  693. kx = xx * k_mix + sx * (1 - k_mix)
  694. vx = xx * v_mix + sx * (1 - v_mix)
  695. rx = xx * r_mix + sx * (1 - r_mix)
  696. gx = xx * g_mix + sx * (1 - g_mix)
  697. H = t_decay.shape[0]
  698. N = x.shape[-1] // H
  699. T = x.shape[0]
  700. r = matmul(rx, rw, rmx, rrx, rmy, rry, output_dtype=torch.float32).view(T, H, N).transpose(0, 1)
  701. k = matmul(kx, kw, kmx, krx, kmy, kry, output_dtype=torch.float32).view(T, H, N).permute(1, 2, 0)
  702. v = matmul(vx, vw, vmx, vrx, vmy, vry, output_dtype=torch.float32).view(T, H, N).transpose(0, 1)
  703. g = F.silu(matmul(gx, gw, gmx, grx, gmy, gry))
  704. out = torch.empty((T, H, N), dtype=r.dtype, device=r.device)
  705. for t in range(T):
  706. rt = r[:,t:t+1,:]
  707. kt = k[:,:,t:t+1]
  708. vt = v[:,t:t+1,:]
  709. at = matmul(kt, vt)
  710. out[t] = (rt @ (t_first * at + s)).squeeze(1)
  711. s = at + t_decay * s
  712. out = out.reshape(T, H*N)
  713. out = F.group_norm(out, num_groups=H, weight=lx_w, bias=lx_b, eps = 64e-5)
  714. out = out.to(dtype=x.dtype) * g
  715. out = matmul(out, ow, omx, orx, omy, ory)
  716. return x + out, xx[-1,:], s
  717. ########################################################################################################
  718. @MyFunction
  719. def att_one_v6_0(self, x, sx, s, ln_w, ln_b, lx_w, lx_b, x_maa, w_maa, k_maa, v_maa, r_maa, g_maa, tm_w1, tm_w2, td_w1, td_w2, t_decay, t_first, kw, vw, rw, gw, ow, kmx, krx, kmy, kry, vmx, vrx, vmy, vry, rmx, rrx, rmy, rry, gmx, grx, gmy, gry, omx, orx, omy, ory):
  720. xx = F.layer_norm(x, (x.shape[-1],), weight=ln_w, bias=ln_b)
  721. sx = sx - xx
  722. xxx = xx + sx * x_maa
  723. xxx = torch.tanh(xxx @ tm_w1).view(5, 1, -1)
  724. xxx = torch.bmm(xxx, tm_w2).view(5, -1)
  725. mw, mk, mv, mr, mg = xxx.unbind(dim=0)
  726. wx = xx + sx * (w_maa + mw)
  727. kx = xx + sx * (k_maa + mk)
  728. vx = xx + sx * (v_maa + mv)
  729. rx = xx + sx * (r_maa + mr)
  730. gx = xx + sx * (g_maa + mg)
  731. H = t_decay.shape[0]
  732. N = x.shape[-1] // H
  733. r = matmul(rx, rw, rmx, rrx, rmy, rry, output_dtype=torch.float32).view(H, 1, N)
  734. k = matmul(kx, kw, kmx, krx, kmy, kry, output_dtype=torch.float32).view(H, N, 1)
  735. v = matmul(vx, vw, vmx, vrx, vmy, vry, output_dtype=torch.float32).view(H, 1, N)
  736. g = F.silu(matmul(gx, gw, gmx, grx, gmy, gry))
  737. w = t_decay + (torch.tanh(wx @ td_w1) @ td_w2).float().view(H, N, 1)
  738. w = torch.exp(-torch.exp(w.float()))
  739. a = matmul(k, v)
  740. out = r @ (t_first * a + s)
  741. s = a + w * s
  742. out = out.flatten()
  743. out = F.group_norm(out.unsqueeze(0), num_groups=H, weight=lx_w, bias=lx_b, eps = 64e-5).squeeze(0)
  744. out = out.to(dtype=x.dtype) * g
  745. out = matmul(out, ow, omx, orx, omy, ory)
  746. return x + out, xx, s
  747. @MyFunction
  748. def att_seq_v6_0(self, x, sx, s, ln_w, ln_b, lx_w, lx_b, x_maa, w_maa, k_maa, v_maa, r_maa, g_maa, tm_w1, tm_w2, td_w1, td_w2, t_decay, t_first, kw, vw, rw, gw, ow, kmx, krx, kmy, kry, vmx, vrx, vmy, vry, rmx, rrx, rmy, rry, gmx, grx, gmy, gry, omx, orx, omy, ory):
  749. H = t_decay.shape[0]
  750. N = x.shape[-1] // H
  751. T = x.shape[0]
  752. xx = F.layer_norm(x, (x.shape[-1],), weight=ln_w, bias=ln_b)
  753. sx = torch.cat((sx.unsqueeze(0), xx[:-1,:])) - xx
  754. xxx = xx + sx * x_maa
  755. xxx = torch.tanh(xxx @ tm_w1).view(T, 5, -1).transpose(0, 1)
  756. xxx = torch.bmm(xxx, tm_w2).view(5, T, -1)
  757. mw, mk, mv, mr, mg = xxx.unbind(dim=0)
  758. wx = xx + sx * (w_maa + mw)
  759. kx = xx + sx * (k_maa + mk)
  760. vx = xx + sx * (v_maa + mv)
  761. rx = xx + sx * (r_maa + mr)
  762. gx = xx + sx * (g_maa + mg)
  763. r = matmul(rx, rw, rmx, rrx, rmy, rry, output_dtype=torch.float32).view(T, H, N).transpose(0, 1)
  764. k = matmul(kx, kw, kmx, krx, kmy, kry, output_dtype=torch.float32).view(T, H, N).permute(1, 2, 0)
  765. v = matmul(vx, vw, vmx, vrx, vmy, vry, output_dtype=torch.float32).view(T, H, N).transpose(0, 1)
  766. g = F.silu(matmul(gx, gw, gmx, grx, gmy, gry))
  767. w = t_decay.view(1, H, N, 1) + (torch.tanh(wx @ td_w1) @ td_w2).float().view(T, H, N, 1)
  768. w = torch.exp(-torch.exp(w.float()))
  769. out = torch.empty((T, H, N), dtype=r.dtype, device=r.device)
  770. for t in range(T):
  771. rt = r[:,t:t+1,:]
  772. kt = k[:,:,t:t+1]
  773. vt = v[:,t:t+1,:]
  774. at = matmul(kt, vt)
  775. out[t] = (rt @ (t_first * at + s)).squeeze(1)
  776. s = at + w[t] * s
  777. out = out.reshape(T, H*N)
  778. out = F.group_norm(out, num_groups=H, weight=lx_w, bias=lx_b, eps = 64e-5)
  779. out = out.to(dtype=x.dtype) * g
  780. out = matmul(out, ow, omx, orx, omy, ory)
  781. return x + out, xx[-1,:], s
  782. ########################################################################################################
  783. if os.environ["RWKV_CUDA_ON"] == '1':
  784. @MyFunction
  785. def cuda_att_seq(self, x, sx, aa, bb, pp, ln_w, ln_b, k_mix, v_mix, r_mix, t_decay, t_first, kw, vw, rw, ow, kmx, krx, kmy, kry, vmx, vrx, vmy, vry, rmx, rrx, rmy, rry, omx, orx, omy, ory):
  786. T, C = x.shape
  787. xx = F.layer_norm(x, (C,), weight=ln_w, bias=ln_b)
  788. sx = torch.cat((sx.unsqueeze(0), xx[:-1,:]))
  789. kx = xx * k_mix + sx * (1 - k_mix)
  790. vx = xx * v_mix + sx * (1 - v_mix)
  791. rx = xx * r_mix + sx * (1 - r_mix)
  792. r = torch.sigmoid(matmul(rx, rw, rmx, rrx, rmy, rry))
  793. k = matmul(kx, kw, kmx, krx, kmy, kry, output_dtype=torch.float32)
  794. v = matmul(vx, vw, vmx, vrx, vmy, vry, output_dtype=torch.float32)
  795. y, aa, bb, pp = cuda_wkv(T, C, t_decay, t_first, k, v, aa, bb, pp)
  796. out = matmul(r * y.to(x.dtype), ow, omx, orx, omy, ory)
  797. return x + out, xx[-1,:], aa, bb, pp
  798. @MyFunction
  799. def v5_2_before(self, x, sx, s, ln_w, ln_b, lx_w, lx_b, k_mix, v_mix, r_mix, g_mix, t_decay, t_first, kw, vw, rw, gw, ow, kmx, krx, kmy, kry, vmx, vrx, vmy, vry, rmx, rrx, rmy, rry, gmx, grx, gmy, gry, omx, orx, omy, ory):
  800. xx = F.layer_norm(x, (x.shape[-1],), weight=ln_w, bias=ln_b)
  801. sx = torch.cat((sx.unsqueeze(0), xx[:-1,:]))
  802. kx = xx * k_mix + sx * (1 - k_mix)
  803. vx = xx * v_mix + sx * (1 - v_mix)
  804. rx = xx * r_mix + sx * (1 - r_mix)
  805. gx = xx * g_mix + sx * (1 - g_mix)
  806. r = matmul(rx, rw, rmx, rrx, rmy, rry, output_dtype=torch.float32)
  807. k = matmul(kx, kw, kmx, krx, kmy, kry, output_dtype=torch.float32)
  808. v = matmul(vx, vw, vmx, vrx, vmy, vry, output_dtype=torch.float32)
  809. g = F.silu(matmul(gx, gw, gmx, grx, gmy, gry))
  810. return r, k, v, g, xx[-1,:], s.transpose(-1,-2).contiguous()
  811. @MyFunction
  812. def v5_2_after(self, t_decay, out, s, x, xxx, g, lx_w, lx_b, ow, omx, orx, omy, ory):
  813. H = t_decay.shape[0]
  814. N = x.shape[-1] // H
  815. T = x.shape[0]
  816. s = s.transpose(-1,-2)
  817. out = out.reshape(T, H*N)
  818. out = F.group_norm(out, num_groups=H, weight=lx_w, bias=lx_b, eps = 64e-5)
  819. out = out.to(dtype=x.dtype) * g
  820. out = matmul(out, ow, omx, orx, omy, ory)
  821. return x + out, xxx, s
  822. def cuda_att_seq_v5_2(self, x, sx, s, ln_w, ln_b, lx_w, lx_b, k_mix, v_mix, r_mix, g_mix, t_decay, t_first, kw, vw, rw, gw, ow, kmx, krx, kmy, kry, vmx, vrx, vmy, vry, rmx, rrx, rmy, rry, gmx, grx, gmy, gry, omx, orx, omy, ory):
  823. H = t_decay.shape[0]
  824. N = x.shape[-1] // H
  825. T = x.shape[0]
  826. r, k, v, g, xxx, ss = self.v5_2_before(x, sx, s, ln_w, ln_b, lx_w, lx_b, k_mix, v_mix, r_mix, g_mix, t_decay, t_first, kw, vw, rw, gw, ow, kmx, krx, kmy, kry, vmx, vrx, vmy, vry, rmx, rrx, rmy, rry, gmx, grx, gmy, gry, omx, orx, omy, ory)
  827. out, s = self.RUN_RWKV_5(1, T, self.args.n_att, H, ss, r, k, v, w=t_decay, u=t_first)
  828. return self.v5_2_after(t_decay, out, s, x, xxx, g, lx_w, lx_b, ow, omx, orx, omy, ory)
  829. @MyFunction
  830. def v6_0_before(self, x, sx, s, ln_w, ln_b, lx_w, lx_b, x_maa, w_maa, k_maa, v_maa, r_maa, g_maa, tm_w1, tm_w2, td_w1, td_w2, t_decay, t_first, kw, vw, rw, gw, ow, kmx, krx, kmy, kry, vmx, vrx, vmy, vry, rmx, rrx, rmy, rry, gmx, grx, gmy, gry, omx, orx, omy, ory):
  831. H = t_decay.shape[0]
  832. N = x.shape[-1] // H
  833. T = x.shape[0]
  834. xx = F.layer_norm(x, (x.shape[-1],), weight=ln_w, bias=ln_b)
  835. sx = torch.cat((sx.unsqueeze(0), xx[:-1,:])) - xx
  836. xxx = xx + sx * x_maa
  837. xxx = torch.tanh(xxx @ tm_w1).view(T, 5, -1).transpose(0, 1)
  838. xxx = torch.bmm(xxx, tm_w2).view(5, T, -1)
  839. mw, mk, mv, mr, mg = xxx.unbind(dim=0)
  840. wx = xx + sx * (w_maa + mw)
  841. kx = xx + sx * (k_maa + mk)
  842. vx = xx + sx * (v_maa + mv)
  843. rx = xx + sx * (r_maa + mr)
  844. gx = xx + sx * (g_maa + mg)
  845. r = matmul(rx, rw, rmx, rrx, rmy, rry, output_dtype=torch.float32)
  846. k = matmul(kx, kw, kmx, krx, kmy, kry, output_dtype=torch.float32)
  847. v = matmul(vx, vw, vmx, vrx, vmy, vry, output_dtype=torch.float32)
  848. g = F.silu(matmul(gx, gw, gmx, grx, gmy, gry))
  849. w = t_decay.view(1, H, N, 1) + (torch.tanh(wx @ td_w1) @ td_w2).float().view(T, H, N, 1)
  850. return r, k, v, g, w, xx[-1,:], s.transpose(-1,-2).contiguous()
  851. def cuda_att_seq_v6_0(self, x, sx, s, ln_w, ln_b, lx_w, lx_b, x_maa, w_maa, k_maa, v_maa, r_maa, g_maa, tm_w1, tm_w2, td_w1, td_w2, t_decay, t_first, kw, vw, rw, gw, ow, kmx, krx, kmy, kry, vmx, vrx, vmy, vry, rmx, rrx, rmy, rry, gmx, grx, gmy, gry, omx, orx, omy, ory):
  852. H = t_decay.shape[0]
  853. N = x.shape[-1] // H
  854. T = x.shape[0]
  855. r, k, v, g, w, xxx, ss = self.v6_0_before(x, sx, s, ln_w, ln_b, lx_w, lx_b, x_maa, w_maa, k_maa, v_maa, r_maa, g_maa, tm_w1, tm_w2, td_w1, td_w2, t_decay, t_first, kw, vw, rw, gw, ow, kmx, krx, kmy, kry, vmx, vrx, vmy, vry, rmx, rrx, rmy, rry, gmx, grx, gmy, gry, omx, orx, omy, ory)
  856. out, s = self.RUN_RWKV_6(1, T, self.args.n_att, H, ss, r, k, v, w=w, u=t_first)
  857. return self.v5_2_after(t_decay, out, s, x, xxx, g, lx_w, lx_b, ow, omx, orx, omy, ory)
  858. ########################################################################################################
  859. def forward(self, tokens=None, state=None, full_output=False, embs=None):
  860. with torch.no_grad():
  861. w = self.w
  862. args = self.args
  863. if state == None:
  864. if self.version == 4:
  865. state = [None] * args.n_layer * 5
  866. for i in range(args.n_layer): # state: 0=att_xx 1=att_aa 2=att_bb 3=att_pp 4=ffn_xx
  867. dd = self.strategy[i]
  868. dev = dd.device
  869. atype = dd.atype
  870. state[i*5+0] = torch.zeros(args.n_embd, dtype=atype, requires_grad=False, device=dev).contiguous()
  871. state[i*5+1] = torch.zeros(args.n_att, dtype=torch.float, requires_grad=False, device=dev).contiguous()
  872. state[i*5+2] = torch.zeros(args.n_att, dtype=torch.float, requires_grad=False, device=dev).contiguous()
  873. state[i*5+3] = torch.zeros(args.n_att, dtype=torch.float, requires_grad=False, device=dev).contiguous() - 1e30
  874. state[i*5+4] = torch.zeros(args.n_embd, dtype=atype, requires_grad=False, device=dev).contiguous()
  875. elif int(self.version) in [5,6]:
  876. state = [None] * args.n_layer * 3
  877. for i in range(args.n_layer): # state: 0=att_xx 1=att_kv 2=ffn_xx
  878. dd = self.strategy[i]
  879. dev = dd.device
  880. atype = dd.atype
  881. state[i*3+0] = torch.zeros(args.n_embd, dtype=atype, requires_grad=False, device=dev).contiguous()
  882. state[i*3+1] = torch.zeros((args.n_head, args.n_att//args.n_head, args.n_att//args.n_head), dtype=torch.float, requires_grad=False, device=dev).contiguous()
  883. state[i*3+2] = torch.zeros(args.n_embd, dtype=atype, requires_grad=False, device=dev).contiguous()
  884. if embs is None:
  885. seq_mode = len(tokens) > 1
  886. x = w['emb.weight'][tokens if seq_mode else tokens[0]]
  887. else:
  888. x = embs
  889. seq_mode = True
  890. for i in range(args.n_layer):
  891. bbb = f'blocks.{i}.'
  892. att = f'blocks.{i}.att.'
  893. ffn = f'blocks.{i}.ffn.'
  894. dd = self.strategy[i]
  895. dev = dd.device
  896. atype = dd.atype
  897. wtype = dd.wtype
  898. if seq_mode:
  899. cuda_applicable = os.environ["RWKV_CUDA_ON"] == '1' and 'cuda' in str(dev)
  900. if cuda_applicable:
  901. ATT = self.cuda_att_seq
  902. else:
  903. ATT = self.att_seq
  904. if self.version == 5:
  905. ATT = self.att_seq_v5
  906. elif self.version == 5.1:
  907. ATT = self.att_seq_v5_1
  908. elif self.version == 5.2:
  909. ATT = self.att_seq_v5_2
  910. if cuda_applicable:
  911. ATT = self.cuda_att_seq_v5_2
  912. elif self.version == 6.0:
  913. ATT = self.att_seq_v6_0
  914. if cuda_applicable:
  915. ATT = self.cuda_att_seq_v6_0
  916. FFN = self.ffn_seq
  917. if self.version >= 6.0:
  918. FFN = self.ffn_seq_v6
  919. else:
  920. ATT = self.att_one
  921. if self.version == 5:
  922. ATT = self.att_one_v5
  923. elif self.version == 5.1:
  924. ATT = self.att_one_v5_1
  925. elif self.version == 5.2:
  926. ATT = self.att_one_v5_1 # same as v5.1
  927. elif self.version == 6.0:
  928. ATT = self.att_one_v6_0
  929. FFN = self.ffn_one
  930. if self.version >= 6.0:
  931. FFN = self.ffn_one_v6
  932. x = x.to(dtype=atype, device=dev)
  933. kw = w[f'{att}key.weight']
  934. vw = w[f'{att}value.weight']
  935. rw = w[f'{att}receptance.weight']
  936. ow = w[f'{att}output.weight']
  937. if dd.stream:
  938. kw = kw.to(device=dev, non_blocking=True)
  939. vw = vw.to(device=dev, non_blocking=True)
  940. rw = rw.to(device=dev, non_blocking=True)
  941. ow = ow.to(device=dev, non_blocking=True)
  942. kmx = w[f'{att}key.weight_mx'] if wtype == torch.uint8 else x
  943. krx = w[f'{att}key.weight_rx'] if wtype == torch.uint8 else x
  944. kmy = w[f'{att}key.weight_my'] if wtype == torch.uint8 else x
  945. kry = w[f'{att}key.weight_ry'] if wtype == torch.uint8 else x
  946. vmx = w[f'{att}value.weight_mx'] if wtype == torch.uint8 else x
  947. vrx = w[f'{att}value.weight_rx'] if wtype == torch.uint8 else x
  948. vmy = w[f'{att}value.weight_my'] if wtype == torch.uint8 else x
  949. vry = w[f'{att}value.weight_ry'] if wtype == torch.uint8 else x
  950. rmx = w[f'{att}receptance.weight_mx'] if wtype == torch.uint8 else x
  951. rrx = w[f'{att}receptance.weight_rx'] if wtype == torch.uint8 else x
  952. rmy = w[f'{att}receptance.weight_my'] if wtype == torch.uint8 else x
  953. rry = w[f'{att}receptance.weight_ry'] if wtype == torch.uint8 else x
  954. omx = w[f'{att}output.weight_mx'] if wtype == torch.uint8 else x
  955. orx = w[f'{att}output.weight_rx'] if wtype == torch.uint8 else x
  956. omy = w[f'{att}output.weight_my'] if wtype == torch.uint8 else x
  957. ory = w[f'{att}output.weight_ry'] if wtype == torch.uint8 else x
  958. if self.version in [5.1, 5.2, 6.0]:
  959. gw = w[f'{att}gate.weight']
  960. if dd.stream:
  961. gw = gw.to(device=dev, non_blocking=True)
  962. gmx = w[f'{att}gate.weight_mx'] if wtype == torch.uint8 else x
  963. grx = w[f'{att}gate.weight_rx'] if wtype == torch.uint8 else x
  964. gmy = w[f'{att}gate.weight_my'] if wtype == torch.uint8 else x
  965. gry = w[f'{att}gate.weight_ry'] if wtype == torch.uint8 else x
  966. if self.version == 4:
  967. x, state[i*5+0], state[i*5+1], state[i*5+2], state[i*5+3] = ATT(
  968. x, state[i*5+0], state[i*5+1], state[i*5+2], state[i*5+3],
  969. w[f'{bbb}ln1.weight'], w[f'{bbb}ln1.bias'],
  970. w[f'{att}time_mix_k'], w[f'{att}time_mix_v'], w[f'{att}time_mix_r'],
  971. w[f'{att}time_decay'], w[f'{att}time_first'],
  972. kw, vw, rw, ow,
  973. kmx, krx, kmy, kry,
  974. vmx, vrx, vmy, vry,
  975. rmx, rrx, rmy, rry,
  976. omx, orx, omy, ory,
  977. )
  978. elif self.version == 5:
  979. x, state[i*3+0], state[i*3+1] = ATT(
  980. x, state[i*3+0], state[i*3+1],
  981. w[f'{bbb}ln1.weight'], w[f'{bbb}ln1.bias'],
  982. w[f'{att}ln_x.weight'], w[f'{att}ln_x.bias'],
  983. w[f'{att}time_mix_k'], w[f'{att}time_mix_v'], w[f'{att}time_mix_r'],
  984. w[f'{att}time_decay'], w[f'{att}time_first'],
  985. kw, vw, rw, ow,
  986. kmx, krx, kmy, kry,
  987. vmx, vrx, vmy, vry,
  988. rmx, rrx, rmy, rry,
  989. omx, orx, omy, ory,
  990. )
  991. elif self.version in [5.1, 5.2]:
  992. x, state[i*3+0], state[i*3+1] = ATT(
  993. x, state[i*3+0], state[i*3+1],
  994. w[f'{bbb}ln1.weight'], w[f'{bbb}ln1.bias'],
  995. w[f'{att}ln_x.weight'], w[f'{att}ln_x.bias'],
  996. w[f'{att}time_mix_k'], w[f'{att}time_mix_v'], w[f'{att}time_mix_r'], w[f'{att}time_mix_g'],
  997. w[f'{att}time_decay'], w[f'{att}time_first'],
  998. kw, vw, rw, gw, ow,
  999. kmx, krx, kmy, kry,
  1000. vmx, vrx, vmy, vry,
  1001. rmx, rrx, rmy, rry,
  1002. gmx, grx, gmy, gry,
  1003. omx, orx, omy, ory,
  1004. )
  1005. elif self.version == 6.0:
  1006. x, state[i*3+0], state[i*3+1] = ATT(
  1007. x, state[i*3+0], state[i*3+1],
  1008. w[f'{bbb}ln1.weight'], w[f'{bbb}ln1.bias'],
  1009. w[f'{att}ln_x.weight'], w[f'{att}ln_x.bias'],
  1010. w[f'{att}time_maa_x'], w[f'{att}time_maa_w'], w[f'{att}time_maa_k'], w[f'{att}time_maa_v'], w[f'{att}time_maa_r'], w[f'{att}time_maa_g'],
  1011. w[f'{att}time_maa_w1'], w[f'{att}time_maa_w2'], w[f'{att}time_decay_w1'], w[f'{att}time_decay_w2'],
  1012. w[f'{att}time_decay'], w[f'{att}time_first'],
  1013. kw, vw, rw, gw, ow,
  1014. kmx, krx, kmy, kry,
  1015. vmx, vrx, vmy, vry,
  1016. rmx, rrx, rmy, rry,
  1017. gmx, grx, gmy, gry,
  1018. omx, orx, omy, ory,
  1019. )
  1020. if dd.stream:
  1021. del kw, vw, rw, ow
  1022. if self.version in [5.1, 5.2, 6.0]:
  1023. del gw
  1024. kw = w[f'{ffn}key.weight']
  1025. vw = w[f'{ffn}value.weight']
  1026. rw = w[f'{ffn}receptance.weight']
  1027. if dd.stream:
  1028. kw = kw.to(device=dev, non_blocking=True)
  1029. vw = vw.to(device=dev, non_blocking=True)
  1030. rw = rw.to(device=dev, non_blocking=True)
  1031. kmx = w[f'{ffn}key.weight_mx'] if wtype == torch.uint8 else x
  1032. krx = w[f'{ffn}key.weight_rx'] if wtype == torch.uint8 else x
  1033. kmy = w[f'{ffn}key.weight_my'] if wtype == torch.uint8 else x
  1034. kry = w[f'{ffn}key.weight_ry'] if wtype == torch.uint8 else x
  1035. vmx = w[f'{ffn}value.weight_mx'] if wtype == torch.uint8 else x
  1036. vrx = w[f'{ffn}value.weight_rx'] if wtype == torch.uint8 else x
  1037. vmy = w[f'{ffn}value.weight_my'] if wtype == torch.uint8 else x
  1038. vry = w[f'{ffn}value.weight_ry'] if wtype == torch.uint8 else x
  1039. rmx = w[f'{ffn}receptance.weight_mx'] if wtype == torch.uint8 else x
  1040. rrx = w[f'{ffn}receptance.weight_rx'] if wtype == torch.uint8 else x
  1041. rmy = w[f'{ffn}receptance.weight_my'] if wtype == torch.uint8 else x
  1042. rry = w[f'{ffn}receptance.weight_ry'] if wtype == torch.uint8 else x
  1043. if self.version == 4:
  1044. offset = i*5+4
  1045. elif int(self.version) in [5,6]:
  1046. offset = i*3+2
  1047. if self.version < 6.0:
  1048. x, state[offset] = FFN(
  1049. x, state[offset],
  1050. w[f'{bbb}ln2.weight'], w[f'{bbb}ln2.bias'],
  1051. w[f'{ffn}time_mix_k'], w[f'{ffn}time_mix_r'],
  1052. kw, vw, rw,
  1053. kmx, krx, kmy, kry,
  1054. vmx, vrx, vmy, vry,
  1055. rmx, rrx, rmy, rry,
  1056. )
  1057. else:
  1058. x, state[offset] = FFN(
  1059. x, state[offset],
  1060. w[f'{bbb}ln2.weight'], w[f'{bbb}ln2.bias'],
  1061. w[f'{ffn}time_maa_k'], w[f'{ffn}time_maa_r'],
  1062. kw, vw, rw,
  1063. kmx, krx, kmy, kry,
  1064. vmx, vrx, vmy, vry,
  1065. rmx, rrx, rmy, rry,
  1066. )
  1067. if dd.stream:
  1068. del kw, vw, rw
  1069. if self.RESCALE_LAYER > 0:
  1070. if (i+1) % self.RESCALE_LAYER == 0:
  1071. x = x / 2
  1072. dd = self.strategy[args.n_layer]
  1073. x = x[-1,:] if (seq_mode and (not full_output)) else x
  1074. x = x.to(dtype=dd.atype, device=dd.device)
  1075. x = F.layer_norm(x, (args.n_embd,), weight=w['ln_out.weight'], bias=w['ln_out.bias'])
  1076. if w['head.weight'].dtype != torch.uint8:
  1077. x = x @ w['head.weight']
  1078. else:
  1079. if seq_mode and full_output:
  1080. x = mm8_seq(x, w['head.weight'], w['head.weight_mx'], w['head.weight_rx'], w['head.weight_my'], w['head.weight_ry'])
  1081. else:
  1082. x = mm8_one(x, w['head.weight'], w['head.weight_mx'], w['head.weight_rx'], w['head.weight_my'], w['head.weight_ry'])
  1083. return x.float(), state
Tip!

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

Comments

Loading...