howard-hou commited on
Commit
cf69cf0
1 Parent(s): c1fe8ee

Upload 2 files

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