Darok commited on
Commit
f9d1bfe
·
verified ·
1 Parent(s): 758ef3e

Upload 8 files

Browse files
Files changed (4) hide show
  1. modeling_rwkv5.py +862 -0
  2. tokenization_rwkv5.py +229 -0
  3. tokenizer_config.json +11 -11
  4. vocab.txt +0 -0
modeling_rwkv5.py ADDED
@@ -0,0 +1,862 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 Bo Peng and HuggingFace Inc. team.
3
+ # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ """PyTorch RWKV5 World model."""
17
+
18
+ from dataclasses import dataclass
19
+ from typing import List, Optional, Tuple, Union
20
+
21
+ import torch
22
+ import torch.nn.functional as F
23
+ import torch.utils.checkpoint
24
+ from torch import nn
25
+ from torch.nn import CrossEntropyLoss
26
+
27
+ from transformers.modeling_utils import PreTrainedModel
28
+ from transformers.utils import (
29
+ ModelOutput,
30
+ add_code_sample_docstrings,
31
+ add_start_docstrings,
32
+ add_start_docstrings_to_model_forward,
33
+ is_ninja_available,
34
+ is_torch_cuda_available,
35
+ logging,
36
+ )
37
+
38
+ from .configuration_rwkv5 import Rwkv5Config
39
+
40
+
41
+ logger = logging.get_logger(__name__)
42
+
43
+ _CHECKPOINT_FOR_DOC = "RWKV/rwkv-5-world-1b5"
44
+ _CONFIG_FOR_DOC = "Rwkv5Config"
45
+
46
+ RWKV5_PRETRAINED_MODEL_ARCHIVE_LIST = [
47
+ "RWKV/rwkv-5-world-1b5",
48
+ "RWKV/rwkv-5-world-3b",
49
+ # See all RWKV models at https://huggingface.co/models?filter=rwkv
50
+ ]
51
+
52
+ rwkv5_cuda_kernel = None
53
+
54
+
55
+ def load_wkv5_cuda_kernel(head_size):
56
+ from torch.utils.cpp_extension import load as load_kernel
57
+
58
+ global rwkv5_cuda_kernel
59
+
60
+ kernel_folder = Path(__file__).resolve().parent.parent.parent / "kernels" / "rwkv5"
61
+ cuda_kernel_files = [kernel_folder / f for f in ["wkv5_op.cpp", "wkv5_cuda.cu"]]
62
+
63
+ # Only load the kernel if it's not been loaded yet or if we changed the context length
64
+ if rwkv5_cuda_kernel is not None and rwkv5_cuda_kernel.head_size == head_size:
65
+ return
66
+
67
+ logger.info(f"Loading CUDA kernel for RWKV at head size of {head_size}.")
68
+
69
+ flags = [
70
+ "-res-usage",
71
+ "--maxrregcount 60",
72
+ "--use_fast_math",
73
+ "-O3",
74
+ "-Xptxas -O3",
75
+ "--extra-device-vectorization",
76
+ f"-D_N_={head_size}",
77
+ ]
78
+ rwkv5_cuda_kernel = load_kernel(
79
+ name=f"wkv_{head_size}",
80
+ sources=cuda_kernel_files,
81
+ verbose=(logging.get_verbosity() == logging.DEBUG),
82
+ extra_cuda_cflags=flags,
83
+ )
84
+ rwkv5_cuda_kernel.head_size = head_size
85
+
86
+
87
+ class WKV_5(torch.autograd.Function):
88
+ @staticmethod
89
+ def forward(ctx, B, T, C, H, r, k, v, w, u, s):
90
+ with torch.no_grad():
91
+ assert r.dtype == torch.bfloat16
92
+ assert k.dtype == torch.bfloat16
93
+ assert v.dtype == torch.bfloat16
94
+ assert w.dtype == torch.bfloat16
95
+ assert u.dtype == torch.bfloat16
96
+ assert s.dtype == torch.float32
97
+ ctx.B = B
98
+ ctx.T = T
99
+ ctx.C = C
100
+ ctx.H = H
101
+ assert r.is_contiguous()
102
+ assert k.is_contiguous()
103
+ assert v.is_contiguous()
104
+ assert w.is_contiguous()
105
+ assert u.is_contiguous()
106
+ ew = (-torch.exp(w.float())).contiguous()
107
+ eew = (torch.exp(ew)).contiguous()
108
+ ctx.save_for_backward(r, k, v, eew, ew, u)
109
+ y = torch.empty(
110
+ (B, T, C), device=r.device, dtype=torch.bfloat16, memory_format=torch.contiguous_format
111
+ ) # .uniform_(-1, 1)
112
+ rwkv5_cuda_kernel.forward(B, T, C, H, r, k, v, eew, u, y, s)
113
+ return y, s
114
+
115
+ @staticmethod
116
+ def backward(ctx, gy):
117
+ with torch.no_grad():
118
+ assert gy.dtype == torch.bfloat16
119
+ B = ctx.B
120
+ T = ctx.T
121
+ C = ctx.C
122
+ H = ctx.H
123
+ assert gy.is_contiguous()
124
+ r, k, v, eew, ew, u = ctx.saved_tensors
125
+ gr = torch.empty(
126
+ (B, T, C),
127
+ device=gy.device,
128
+ requires_grad=False,
129
+ dtype=torch.bfloat16,
130
+ memory_format=torch.contiguous_format,
131
+ ) # .uniform_(-1, 1)
132
+ gk = torch.empty(
133
+ (B, T, C),
134
+ device=gy.device,
135
+ requires_grad=False,
136
+ dtype=torch.bfloat16,
137
+ memory_format=torch.contiguous_format,
138
+ ) # .uniform_(-1, 1)
139
+ gv = torch.empty(
140
+ (B, T, C),
141
+ device=gy.device,
142
+ requires_grad=False,
143
+ dtype=torch.bfloat16,
144
+ memory_format=torch.contiguous_format,
145
+ ) # .uniform_(-1, 1)
146
+ gw = torch.empty(
147
+ (B, C),
148
+ device=gy.device,
149
+ requires_grad=False,
150
+ dtype=torch.bfloat16,
151
+ memory_format=torch.contiguous_format,
152
+ ) # .uniform_(-1, 1)
153
+ gu = torch.empty(
154
+ (B, C),
155
+ device=gy.device,
156
+ requires_grad=False,
157
+ dtype=torch.bfloat16,
158
+ memory_format=torch.contiguous_format,
159
+ ) # .uniform_(-1, 1)
160
+ rwkv5_cuda_kernel.backward(B, T, C, H, r, k, v, eew, ew, u, gy, gr, gk, gv, gw, gu)
161
+ gw = torch.sum(gw, 0).view(H, C // H)
162
+ gu = torch.sum(gu, 0).view(H, C // H)
163
+ return (None, None, None, None, gr, gk, gv, gw, gu)
164
+
165
+
166
+ def rwkv_linear_attention_v5_cpu(
167
+ B,
168
+ H,
169
+ S,
170
+ T,
171
+ n_head,
172
+ hidden,
173
+ time_decay,
174
+ time_first,
175
+ receptance,
176
+ key,
177
+ value,
178
+ gate,
179
+ lxw,
180
+ lxb,
181
+ ow,
182
+ state,
183
+ ):
184
+ key = key.to(torch.float32).view(B, T, H, S).transpose(1, 2).transpose(-2, -1)
185
+ value = value.to(torch.float32).view(B, T, H, S).transpose(1, 2)
186
+ receptance = receptance.to(torch.float32).view(B, T, H, S).transpose(1, 2)
187
+ time_decay = torch.exp(-torch.exp(time_decay.float())).reshape(-1, 1, 1).reshape(n_head, -1, 1)
188
+ time_first = time_first.float().reshape(-1, 1, 1).reshape(n_head, -1, 1)
189
+ lxw = lxw.float()
190
+ lxb = lxb.float()
191
+ out = torch.zeros_like(key).reshape(B, T, H, S)
192
+ for t in range(T):
193
+ rt = receptance[:, :, t : t + 1, :]
194
+ kt = key[:, :, :, t : t + 1]
195
+ vt = value[:, :, t : t + 1, :]
196
+ at = kt @ vt
197
+ out[:, t] = (rt @ (time_first * at + state)).squeeze(2)
198
+ with torch.no_grad():
199
+ state = at + time_decay * state
200
+
201
+ out = out.reshape(B * T, H * S)
202
+ out = F.group_norm(out, num_groups=H, weight=lxw, bias=lxb).reshape(B, T, H * S)
203
+ out = out.to(dtype=hidden.dtype) * gate
204
+ out = out @ ow
205
+
206
+ return out, state
207
+
208
+
209
+ def rwkv_linear_attention(
210
+ B,
211
+ H,
212
+ S,
213
+ T,
214
+ n_head,
215
+ hidden,
216
+ time_decay,
217
+ time_first,
218
+ receptance,
219
+ key,
220
+ value,
221
+ gate,
222
+ lxw,
223
+ lxb,
224
+ ow,
225
+ state,
226
+ ):
227
+ no_cuda = any(t.device.type != "cuda" for t in [time_decay, time_first, receptance, key, value])
228
+ # Launching the CUDA kernel for just one token will actually be slower (there is no for loop in the CPU version
229
+ # in this case).
230
+ one_token = key.size(1) == 1
231
+ if rwkv5_cuda_kernel is None or no_cuda or one_token:
232
+ return rwkv_linear_attention_v5_cpu(
233
+ B,
234
+ H,
235
+ S,
236
+ T,
237
+ n_head,
238
+ hidden,
239
+ time_decay,
240
+ time_first,
241
+ receptance,
242
+ key,
243
+ value,
244
+ gate,
245
+ lxw,
246
+ lxb,
247
+ ow,
248
+ state,
249
+ )
250
+ else:
251
+ out, state = WKV_5.apply(B, T, H * S, H, receptance, key, value, time_decay, time_first, state)
252
+ out = out.reshape(B * T, H * S)
253
+ out = F.group_norm(out, num_groups=H, weight=lxw, bias=lxb).reshape(B, T, H * S)
254
+ out = out.to(dtype=hidden.dtype) * gate
255
+ out = out @ ow
256
+ return out, state
257
+
258
+
259
+ class RwkvSelfAttention(nn.Module):
260
+ def __init__(self, config, layer_id=0):
261
+ super().__init__()
262
+ self.config = config
263
+ kernel_loaded = rwkv5_cuda_kernel is not None and rwkv5_cuda_kernel.head_size == config.head_size
264
+ if is_ninja_available() and is_torch_cuda_available() and not kernel_loaded:
265
+ try:
266
+ load_wkv5_cuda_kernel(config.context_length)
267
+ except Exception:
268
+ logger.info("Could not load the custom CUDA kernel for RWKV5 attention.")
269
+ self.layer_id = layer_id
270
+ hidden_size = config.hidden_size
271
+ # https://github.com/BlinkDL/RWKV-LM/blob/main/RWKV-v4neo/src/model.py#L146
272
+ num_attention_heads = hidden_size // config.head_size
273
+ self.num_attention_heads = num_attention_heads
274
+ attention_hidden_size = (
275
+ config.attention_hidden_size if config.attention_hidden_size is not None else hidden_size
276
+ )
277
+ self.attention_hidden_size = attention_hidden_size
278
+
279
+ self.time_decay = nn.Parameter(torch.empty(num_attention_heads, config.head_size))
280
+ self.time_faaaa = nn.Parameter(torch.empty(num_attention_heads, config.head_size))
281
+ self.time_mix_gate = nn.Parameter(torch.empty(1, 1, hidden_size))
282
+
283
+ self.time_mix_key = nn.Parameter(torch.empty(1, 1, hidden_size))
284
+ self.time_mix_value = nn.Parameter(torch.empty(1, 1, hidden_size))
285
+ self.time_mix_receptance = nn.Parameter(torch.empty(1, 1, hidden_size))
286
+
287
+ self.time_shift = nn.ZeroPad2d((0, 0, 1, -1))
288
+ self.key = nn.Linear(hidden_size, attention_hidden_size, bias=False)
289
+ self.value = nn.Linear(hidden_size, attention_hidden_size, bias=False)
290
+ self.receptance = nn.Linear(hidden_size, attention_hidden_size, bias=False)
291
+ self.gate = nn.Linear(hidden_size, attention_hidden_size, bias=False)
292
+ self.output = nn.Linear(attention_hidden_size, hidden_size, bias=False)
293
+ # https://github.com/BlinkDL/RWKV-LM/blob/3db37a72356b736966ddd377268f02b80963af3f/RWKV-v4neo/src/model.py#L190C1-L190C1
294
+ self.ln_x = nn.GroupNorm(hidden_size // config.head_size, hidden_size)
295
+
296
+ # TODO: maybe jit, otherwise move inside forward
297
+ def extract_key_value(self, B, H, S, T, hidden, state=None):
298
+ # Mix hidden with the previous timestep to produce key, value, receptance
299
+ if hidden.size(1) == 1 and state is not None:
300
+ shifted = state[0][:, :, self.layer_id]
301
+ else:
302
+ shifted = self.time_shift(hidden)
303
+ if state is not None:
304
+ shifted[:, 0] = state[0][:, :, self.layer_id]
305
+ if len(shifted.size()) == 2:
306
+ shifted = shifted.unsqueeze(1)
307
+ key = hidden * self.time_mix_key + shifted * (1 - self.time_mix_key)
308
+ value = hidden * self.time_mix_value + shifted * (1 - self.time_mix_value)
309
+ receptance = hidden * self.time_mix_receptance + shifted * (1 - self.time_mix_receptance)
310
+ gate = hidden * self.time_mix_gate + shifted * (1 - self.time_mix_gate)
311
+
312
+ # https://github.com/BlinkDL/ChatRWKV/blob/main/rwkv_pip_package/src/rwkv/model.py#L693
313
+ key = self.key(key)
314
+ value = self.value(value)
315
+ receptance = self.receptance(receptance)
316
+ gate = F.silu(self.gate(gate))
317
+
318
+ if state is not None:
319
+ state[0][:, :, self.layer_id] = hidden[:, -1]
320
+
321
+ return receptance, key, value, gate, state
322
+
323
+ def forward(self, hidden, state=None, use_cache=False, seq_mode=True):
324
+ B = hidden.shape[0]
325
+ H = self.time_decay.shape[0]
326
+ S = hidden.shape[-1] // H
327
+ T = hidden.shape[1]
328
+
329
+ receptance, key, value, gate, state = self.extract_key_value(B, H, S, T, hidden, state=state)
330
+ layer_state = state[1][:, :, :, :, self.layer_id] if state is not None else None
331
+ rwkv, layer_state = rwkv_linear_attention(
332
+ B,
333
+ H,
334
+ S,
335
+ T,
336
+ self.num_attention_heads,
337
+ hidden,
338
+ self.time_decay,
339
+ self.time_faaaa,
340
+ receptance,
341
+ key,
342
+ value,
343
+ gate,
344
+ self.ln_x.weight,
345
+ self.ln_x.bias,
346
+ self.output.weight.t(),
347
+ state=layer_state,
348
+ )
349
+
350
+ if layer_state is not None:
351
+ state[1][:, :, :, :, self.layer_id] = layer_state
352
+
353
+ return rwkv, state
354
+
355
+
356
+ class RwkvFeedForward(nn.Module):
357
+ def __init__(self, config, layer_id=0):
358
+ super().__init__()
359
+ self.config = config
360
+ self.layer_id = layer_id
361
+ hidden_size = config.hidden_size
362
+ # https://github.com/BlinkDL/RWKV-LM/blob/3db37a72356b736966ddd377268f02b80963af3f/RWKV-v4neo/train.py#L168
363
+ intermediate_size = (
364
+ config.intermediate_size
365
+ if config.intermediate_size is not None
366
+ else int((config.hidden_size * 3.5) // 32 * 32)
367
+ )
368
+
369
+ self.time_shift = nn.ZeroPad2d((0, 0, 1, -1))
370
+ self.time_mix_key = nn.Parameter(torch.empty(1, 1, hidden_size))
371
+ self.time_mix_receptance = nn.Parameter(torch.empty(1, 1, hidden_size))
372
+
373
+ self.key = nn.Linear(hidden_size, intermediate_size, bias=False)
374
+ self.receptance = nn.Linear(hidden_size, hidden_size, bias=False)
375
+ self.value = nn.Linear(intermediate_size, hidden_size, bias=False)
376
+
377
+ def forward(self, hidden, state=None):
378
+ if hidden.size(1) == 1 and state is not None:
379
+ shifted = state[2][:, :, self.layer_id]
380
+ else:
381
+ shifted = self.time_shift(hidden)
382
+ if state is not None:
383
+ shifted[:, 0] = state[2][:, :, self.layer_id]
384
+ if len(shifted.size()) == 2:
385
+ shifted = shifted.unsqueeze(1)
386
+ key = hidden * self.time_mix_key + shifted * (1 - self.time_mix_key)
387
+ receptance = hidden * self.time_mix_receptance + shifted * (1 - self.time_mix_receptance)
388
+
389
+ key = torch.square(torch.relu(self.key(key)))
390
+ value = self.value(key)
391
+ receptance = torch.sigmoid(self.receptance(receptance))
392
+
393
+ if state is not None:
394
+ state[2][:, :, self.layer_id] = hidden[:, -1]
395
+
396
+ return receptance * value, state
397
+
398
+
399
+ class RwkvBlock(nn.Module):
400
+ def __init__(self, config, layer_id):
401
+ super().__init__()
402
+ self.config = config
403
+ self.layer_id = layer_id
404
+
405
+ if layer_id == 0:
406
+ self.pre_ln = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_epsilon)
407
+
408
+ self.ln1 = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_epsilon)
409
+ self.ln2 = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_epsilon)
410
+
411
+ self.attention = RwkvSelfAttention(config, layer_id)
412
+ self.feed_forward = RwkvFeedForward(config, layer_id)
413
+
414
+ def forward(self, hidden, state=None, use_cache=False, output_attentions=False, seq_mode=True):
415
+ if self.layer_id == 0:
416
+ hidden = self.pre_ln(hidden)
417
+ attention, state = self.attention(self.ln1(hidden), state=state, use_cache=use_cache, seq_mode=seq_mode)
418
+ hidden = hidden + attention
419
+
420
+ feed_forward, state = self.feed_forward(self.ln2(hidden), state=state)
421
+ hidden = hidden + feed_forward
422
+
423
+ outputs = (hidden, state)
424
+ if output_attentions:
425
+ outputs += (attention,)
426
+ else:
427
+ outputs += (None,)
428
+
429
+ return outputs
430
+
431
+
432
+ class Rwkv5PreTrainedModel(PreTrainedModel):
433
+ """
434
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
435
+ models.
436
+ """
437
+
438
+ config_class = Rwkv5Config
439
+ base_model_prefix = "rwkv"
440
+ _no_split_modules = ["RwkvBlock"]
441
+ _keep_in_fp32_modules = ["time_decay", "time_first"]
442
+ supports_gradient_checkpointing = True
443
+
444
+ def _init_weights(self, module):
445
+ """Initialize the weights."""
446
+ if isinstance(module, RwkvSelfAttention):
447
+ layer_id = module.layer_id
448
+ num_hidden_layers = module.config.num_hidden_layers
449
+ hidden_size = module.config.hidden_size
450
+ attention_hidden_size = module.attention_hidden_size
451
+ num_attention_heads = hidden_size // module.config.num_attention_heads
452
+
453
+ ratio_0_to_1 = layer_id / (num_hidden_layers - 1) # 0 to 1
454
+ ratio_1_to_almost0 = 1.0 - (layer_id / num_hidden_layers) # 1 to ~0
455
+
456
+ time_weight = torch.tensor(
457
+ [i / hidden_size for i in range(hidden_size)],
458
+ dtype=module.time_mix_key.dtype,
459
+ device=module.time_mix_key.device,
460
+ )
461
+ time_weight = time_weight[None, None, :]
462
+
463
+ # https://github.com/BlinkDL/RWKV-LM/blob/main/RWKV-v4neo/src/model.py#L398
464
+ decay_speed = [
465
+ -6.0 + 5.0 * (h / (attention_hidden_size - 1)) ** (0.7 + 1.3 * ratio_0_to_1)
466
+ for h in range(attention_hidden_size)
467
+ ]
468
+ decay_speed = torch.tensor(decay_speed, dtype=module.time_decay.dtype, device=module.time_decay.device)
469
+ tmp = torch.tensor(
470
+ [
471
+ (1.0 - (i / (attention_hidden_size - 1.0))) * ratio_0_to_1 + 0.1 * ((i + 1) % 3 - 1)
472
+ for i in range(attention_hidden_size)
473
+ ],
474
+ dtype=module.time_faaaa.dtype,
475
+ device=module.time_faaaa.device,
476
+ )
477
+
478
+ with torch.no_grad():
479
+ module.time_decay.data = decay_speed.reshape(num_attention_heads, module.config.num_attention_heads)
480
+ module.time_faaaa.data = tmp.reshape(num_attention_heads, module.config.num_attention_heads)
481
+ module.time_mix_key.data = torch.pow(time_weight, ratio_1_to_almost0)
482
+
483
+ module.time_mix_value.data = torch.pow(time_weight, ratio_1_to_almost0) + 0.3 * ratio_0_to_1
484
+ module.time_mix_receptance.data = torch.pow(time_weight, 0.5 * ratio_1_to_almost0)
485
+ module.time_mix_gate.data = torch.pow(time_weight, 0.5 * ratio_1_to_almost0)
486
+
487
+ elif isinstance(module, RwkvFeedForward):
488
+ layer_id = module.layer_id
489
+ num_hidden_layers = module.config.num_hidden_layers
490
+ hidden_size = module.config.hidden_size
491
+
492
+ ratio_1_to_almost0 = 1.0 - (layer_id / num_hidden_layers) # 1 to ~0
493
+
494
+ time_weight = torch.tensor(
495
+ [i / hidden_size for i in range(hidden_size)],
496
+ dtype=module.time_mix_key.dtype,
497
+ device=module.time_mix_key.device,
498
+ )
499
+ time_weight = time_weight[None, None, :]
500
+
501
+ with torch.no_grad():
502
+ module.time_mix_key.data = torch.pow(time_weight, ratio_1_to_almost0)
503
+ module.time_mix_receptance.data = torch.pow(time_weight, ratio_1_to_almost0)
504
+
505
+
506
+ @dataclass
507
+ class Rwkv5Output(ModelOutput):
508
+ """
509
+ Class for the RWKV model outputs.
510
+
511
+ Args:
512
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
513
+ Sequence of hidden-states at the output of the last layer of the model.
514
+ state (list of five `torch.FloatTensor` of shape `(batch_size, hidden_size, num_hidden_layers)`):
515
+ The state of the model at the last time step. Can be used in a forward method with the next `input_ids` to
516
+ avoid providing the old `input_ids`.
517
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
518
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
519
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of
520
+ the model at the output of each layer plus the optional initial embedding outputs.
521
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
522
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
523
+ sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in
524
+ the self-attention heads.
525
+ """
526
+
527
+ last_hidden_state: torch.FloatTensor = None
528
+ state: Optional[List[torch.FloatTensor]] = None
529
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
530
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
531
+
532
+
533
+ @dataclass
534
+ class Rwkv5CausalLMOutput(ModelOutput):
535
+ """
536
+ Base class for causal language model (or autoregressive) outputs.
537
+
538
+ Args:
539
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
540
+ Language modeling loss (for next-token prediction).
541
+ logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
542
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
543
+ state (list of five `torch.FloatTensor` of shape `(batch_size, hidden_size, num_hidden_layers)`):
544
+ The state of the model at the last time step. Can be used in a forward method with the next `input_ids` to
545
+ avoid providing the old `input_ids`.
546
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
547
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
548
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of
549
+ the model at the output of each layer plus the optional initial embedding outputs.
550
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
551
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
552
+ sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in
553
+ the self-attention heads.
554
+ """
555
+
556
+ loss: Optional[torch.FloatTensor] = None
557
+ logits: torch.FloatTensor = None
558
+ state: Optional[List[torch.FloatTensor]] = None
559
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
560
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
561
+
562
+
563
+ RWKV_START_DOCSTRING = r"""
564
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
565
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
566
+ etc.) This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module)
567
+ subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to
568
+ general usage and behavior.
569
+
570
+ Parameters:
571
+ config ([`Rwkv5Config`]): Model configuration class with all the parameters of the model.
572
+ Initializing with a config file does not load the weights associated with the model, only the
573
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
574
+ """
575
+
576
+ RWKV_INPUTS_DOCSTRING = r"""
577
+ Args:
578
+ input_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`):
579
+ `input_ids_length` = `sequence_length` if `past_key_values` is `None` else
580
+ `past_key_values[0][0].shape[-2]` (`sequence_length` of input past key value states). Indices of input
581
+ sequence tokens in the vocabulary. If `past_key_values` is used, only `input_ids` that do not have their
582
+ past calculated should be passed as `input_ids`. Indices can be obtained using [`AutoTokenizer`]. See
583
+ [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. [What are input
584
+ IDs?](../glossary#input-ids)
585
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
586
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
587
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
588
+ model's internal embedding lookup matrix.
589
+ state (tuple of five `torch.FloatTensor` of shape `(batch_size, hidden_size, num_hidden_layers)`, *optional*):
590
+ If passed along, the model uses the previous state in all the blocks (which will give the output for the
591
+ `input_ids` provided as if the model add `state_input_ids + input_ids` as context).
592
+ use_cache (`bool`, *optional*):
593
+ If set to `True`, the last state is returned and can be used to quickly generate the next logits.
594
+ output_attentions (`bool`, *optional*):
595
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
596
+ tensors for more detail.
597
+ output_hidden_states (`bool`, *optional*):
598
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
599
+ more detail.
600
+ return_dict (`bool`, *optional*):
601
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
602
+ """
603
+
604
+
605
+ @add_start_docstrings(
606
+ "The bare RWKV Model transformer outputting raw hidden-states without any specific head on top.",
607
+ RWKV_START_DOCSTRING,
608
+ )
609
+ class Rwkv5Model(Rwkv5PreTrainedModel):
610
+ def __init__(self, config):
611
+ super().__init__(config)
612
+
613
+ self.embeddings = nn.Embedding(config.vocab_size, config.hidden_size)
614
+ self.blocks = nn.ModuleList([RwkvBlock(config, layer_id=idx) for idx in range(config.num_hidden_layers)])
615
+ self.ln_out = nn.LayerNorm(config.hidden_size)
616
+
617
+ self.layers_are_rescaled = False
618
+ self.gradient_checkpointing = False
619
+
620
+ # Initialize weights and apply final processing
621
+ self.post_init()
622
+
623
+ def get_input_embeddings(self):
624
+ return self.embeddings
625
+
626
+ def set_input_embeddings(self, new_embeddings):
627
+ self.embeddings = new_embeddings
628
+
629
+ @add_start_docstrings_to_model_forward(RWKV_INPUTS_DOCSTRING)
630
+ @add_code_sample_docstrings(
631
+ checkpoint=_CHECKPOINT_FOR_DOC,
632
+ output_type=Rwkv5Output,
633
+ config_class=_CONFIG_FOR_DOC,
634
+ )
635
+ def forward(
636
+ self,
637
+ input_ids: Optional[torch.LongTensor] = None,
638
+ attention_mask: Optional[torch.LongTensor] = None, # noqa
639
+ inputs_embeds: Optional[torch.FloatTensor] = None,
640
+ state: Optional[List[torch.FloatTensor]] = None,
641
+ use_cache: Optional[bool] = None,
642
+ output_attentions: Optional[bool] = None,
643
+ output_hidden_states: Optional[bool] = None,
644
+ return_dict: Optional[bool] = None,
645
+ ) -> Union[Tuple, Rwkv5Output]:
646
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
647
+ output_hidden_states = (
648
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
649
+ )
650
+ # rwkv5 only support inference in huggingface.
651
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
652
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
653
+
654
+ if self.training == self.layers_are_rescaled and (
655
+ self.embeddings.weight.dtype == torch.float16 or self.embeddings.weight.dtype == torch.bfloat16
656
+ ):
657
+ self._rescale_layers()
658
+
659
+ if input_ids is not None and inputs_embeds is not None:
660
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
661
+ elif input_ids is None and inputs_embeds is None:
662
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
663
+
664
+ if inputs_embeds is None:
665
+ inputs_embeds = self.embeddings(input_ids)
666
+
667
+ if use_cache and state is None:
668
+ # https://github.com/BlinkDL/ChatRWKV/blob/main/rwkv_pip_package/src/rwkv/model.py#L904-L906
669
+ state = []
670
+ num_attention_heads = self.config.hidden_size // self.config.num_attention_heads
671
+ state.append(
672
+ torch.zeros(
673
+ (inputs_embeds.size(0), self.config.hidden_size, self.config.num_hidden_layers),
674
+ dtype=inputs_embeds.dtype,
675
+ requires_grad=False,
676
+ device=inputs_embeds.device,
677
+ ).contiguous()
678
+ )
679
+ state.append(
680
+ torch.zeros(
681
+ (
682
+ inputs_embeds.size(0),
683
+ num_attention_heads,
684
+ self.config.hidden_size // num_attention_heads,
685
+ self.config.hidden_size // num_attention_heads,
686
+ self.config.num_hidden_layers,
687
+ ),
688
+ dtype=torch.float32,
689
+ requires_grad=False,
690
+ device=inputs_embeds.device,
691
+ ).contiguous()
692
+ )
693
+ state.append(
694
+ torch.zeros(
695
+ (inputs_embeds.size(0), self.config.hidden_size, self.config.num_hidden_layers),
696
+ dtype=inputs_embeds.dtype,
697
+ requires_grad=False,
698
+ device=inputs_embeds.device,
699
+ ).contiguous()
700
+ )
701
+
702
+ seq_mode = inputs_embeds.shape[1] > 1
703
+ hidden_states = inputs_embeds
704
+
705
+ all_self_attentions = () if output_attentions else None
706
+ all_hidden_states = () if output_hidden_states else None
707
+ for idx, block in enumerate(self.blocks):
708
+ hidden_states, state, attentions = block(
709
+ hidden_states, state=state, use_cache=use_cache, output_attentions=output_attentions, seq_mode=seq_mode
710
+ )
711
+ if (
712
+ self.layers_are_rescaled
713
+ and self.config.rescale_every > 0
714
+ and (idx + 1) % self.config.rescale_every == 0
715
+ ):
716
+ hidden_states = hidden_states / 2
717
+
718
+ if output_hidden_states:
719
+ all_hidden_states = all_hidden_states + (hidden_states,)
720
+
721
+ if output_attentions:
722
+ all_self_attentions = all_self_attentions + (attentions,)
723
+
724
+ hidden_states = self.ln_out(hidden_states)
725
+
726
+ if output_hidden_states:
727
+ all_hidden_states = all_hidden_states + (hidden_states,)
728
+
729
+ if not return_dict:
730
+ return (hidden_states, state, all_hidden_states, all_self_attentions)
731
+
732
+ return Rwkv5Output(
733
+ last_hidden_state=hidden_states,
734
+ state=state,
735
+ hidden_states=all_hidden_states, # None
736
+ attentions=all_self_attentions, # None
737
+ )
738
+
739
+ def _rescale_layers(self):
740
+ # Layers should be rescaled for inference only.
741
+ if self.layers_are_rescaled == (not self.training):
742
+ return
743
+ if self.config.rescale_every > 0:
744
+ with torch.no_grad():
745
+ for block_id, block in enumerate(self.blocks):
746
+ if self.training:
747
+ block.attention.output.weight.mul_(2 ** int(block_id // self.config.rescale_every))
748
+ block.feed_forward.value.weight.mul_(2 ** int(block_id // self.config.rescale_every))
749
+ else:
750
+ # Deal with quantization statistics
751
+ if hasattr(block.attention.output.weight, "SCB"):
752
+ block.attention.output.weight.SCB.div_(2 ** int(block_id // self.config.rescale_every))
753
+ block.feed_forward.value.weight.SCB.div_(2 ** int(block_id // self.config.rescale_every))
754
+ elif hasattr(block.attention.output.weight, "quant_state"):
755
+ self._bnb_4bit_dequantize_and_rescale(block.attention.output, block_id)
756
+ self._bnb_4bit_dequantize_and_rescale(block.feed_forward.value, block_id)
757
+ else:
758
+ block.attention.output.weight.div_(2 ** int(block_id // self.config.rescale_every))
759
+ block.feed_forward.value.weight.div_(2 ** int(block_id // self.config.rescale_every))
760
+
761
+ self.layers_are_rescaled = not self.training
762
+
763
+
764
+ @add_start_docstrings(
765
+ """
766
+ The RWKV Model transformer with a language modeling head on top (linear layer with weights tied to the input
767
+ embeddings).
768
+ """,
769
+ RWKV_START_DOCSTRING,
770
+ )
771
+ class Rwkv5ForCausalLM(Rwkv5PreTrainedModel):
772
+ _tied_weights_keys = ["head.weight"]
773
+
774
+ def __init__(self, config):
775
+ super().__init__(config)
776
+ self.rwkv = Rwkv5Model(config)
777
+ self.head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
778
+
779
+ # Initialize weights and apply final processing
780
+ self.post_init()
781
+
782
+ def get_output_embeddings(self):
783
+ return self.head
784
+
785
+ def set_output_embeddings(self, new_embeddings):
786
+ self.head = new_embeddings
787
+
788
+ def prepare_inputs_for_generation(self, input_ids, state=None, inputs_embeds=None, **kwargs):
789
+ # only last token for inputs_ids if the state is passed along.
790
+ if state is not None:
791
+ input_ids = input_ids[:, -1].unsqueeze(-1)
792
+
793
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
794
+ if inputs_embeds is not None and state is None:
795
+ model_inputs = {"inputs_embeds": inputs_embeds}
796
+ else:
797
+ model_inputs = {"input_ids": input_ids}
798
+
799
+ model_inputs["state"] = state
800
+ return model_inputs
801
+
802
+ @add_start_docstrings_to_model_forward(RWKV_INPUTS_DOCSTRING)
803
+ @add_code_sample_docstrings(
804
+ checkpoint=_CHECKPOINT_FOR_DOC,
805
+ output_type=Rwkv5CausalLMOutput,
806
+ config_class=_CONFIG_FOR_DOC,
807
+ )
808
+ def forward(
809
+ self,
810
+ input_ids: Optional[torch.LongTensor] = None,
811
+ attention_mask: Optional[torch.LongTensor] = None,
812
+ inputs_embeds: Optional[torch.FloatTensor] = None,
813
+ state: Optional[List[torch.FloatTensor]] = None,
814
+ labels: Optional[torch.LongTensor] = None,
815
+ use_cache: Optional[bool] = None,
816
+ output_attentions: Optional[bool] = None,
817
+ output_hidden_states: Optional[bool] = None,
818
+ return_dict: Optional[bool] = None,
819
+ ) -> Union[Tuple, Rwkv5CausalLMOutput]:
820
+ r"""
821
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
822
+ Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
823
+ `labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
824
+ are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
825
+ """
826
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
827
+
828
+ rwkv_outputs = self.rwkv(
829
+ input_ids,
830
+ inputs_embeds=inputs_embeds,
831
+ state=state,
832
+ use_cache=use_cache,
833
+ output_attentions=output_attentions,
834
+ output_hidden_states=output_hidden_states,
835
+ return_dict=return_dict,
836
+ )
837
+ hidden_states = rwkv_outputs[0]
838
+
839
+ logits = self.head(hidden_states)
840
+
841
+ loss = None
842
+ if labels is not None:
843
+ # move labels to correct device to enable model parallelism
844
+ labels = labels.to(logits.device)
845
+ # Shift so that tokens < n predict n
846
+ shift_logits = logits[..., :-1, :].contiguous()
847
+ shift_labels = labels[..., 1:].contiguous()
848
+ # Flatten the tokens
849
+ loss_fct = CrossEntropyLoss()
850
+ loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
851
+
852
+ if not return_dict:
853
+ output = (logits,) + rwkv_outputs[1:]
854
+ return ((loss,) + output) if loss is not None else output
855
+
856
+ return Rwkv5CausalLMOutput(
857
+ loss=loss,
858
+ logits=logits,
859
+ state=rwkv_outputs.state,
860
+ hidden_states=rwkv_outputs.hidden_states,
861
+ attentions=rwkv_outputs.attentions,
862
+ )
tokenization_rwkv5.py ADDED
@@ -0,0 +1,229 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Tokenization classes for RWKV5."""
16
+
17
+ import os
18
+ import re
19
+ from typing import TYPE_CHECKING, List, Optional, Tuple
20
+
21
+ from transformers.tokenization_utils import AddedToken, PreTrainedTokenizer
22
+ from transformers.utils import logging
23
+
24
+
25
+ if TYPE_CHECKING:
26
+ pass
27
+
28
+ logger = logging.get_logger(__name__)
29
+
30
+ VOCAB_FILES_NAMES = {
31
+ "vocab_file": "vocab.txt",
32
+ }
33
+ PRETRAINED_VOCAB_FILES_MAP = {
34
+ "vocab_file": {
35
+ "ArthurZ/rwkv-5-utf": "https://huggingface.co/ArthurZ/rwkv-5-utf/blob/main/vocab.txt",
36
+ },
37
+ }
38
+
39
+
40
+ def whitespace_tokenize(text):
41
+ """Runs basic whitespace cleaning and splitting on a piece of text.
42
+ The separators are kept
43
+ """
44
+ text = text.strip()
45
+ if not text:
46
+ return []
47
+ tokens = re.split(b"(?= )", text)
48
+ return tokens
49
+
50
+
51
+ class WordpieceTokenizer(object):
52
+ """Runs WordPiece tokenization."""
53
+
54
+ def __init__(self, vocab, unk_token):
55
+ self.vocab = vocab
56
+ self.unk_token = unk_token
57
+
58
+ def tokenize(self, text):
59
+ """
60
+ Tokenizes a piece of text into its word pieces. This uses a greedy longest-match-first algorithm to perform
61
+ tokenization using the given vocabulary.
62
+
63
+ For example, `input = "unaffable"` wil return as output `["un", "##aff", "##able"]`.
64
+
65
+ Args:
66
+ text: A single token or whitespace separated tokens. This should have
67
+ already been passed through *BasicTokenizer*.
68
+
69
+ Returns:
70
+ A list of wordpiece tokens.
71
+ """
72
+
73
+ output_tokens = []
74
+ for token in whitespace_tokenize(text):
75
+ chars = list(token)
76
+ is_bad = False
77
+ start = 0
78
+ sub_tokens = []
79
+ while start < len(chars):
80
+ end = len(chars)
81
+ cur_substr = None
82
+ while start < end:
83
+ substr = bytes(chars[start:end])
84
+ if substr in self.vocab:
85
+ cur_substr = substr
86
+ break
87
+ end -= 1
88
+ if cur_substr is None:
89
+ is_bad = True
90
+ break
91
+ try:
92
+ cur_substr = cur_substr.decode()
93
+ except UnicodeDecodeError:
94
+ cur_substr = str(cur_substr)
95
+ sub_tokens.append(cur_substr)
96
+ start = end
97
+ if is_bad:
98
+ output_tokens.append(self.unk_token)
99
+ else:
100
+ output_tokens.extend(sub_tokens)
101
+ return output_tokens
102
+
103
+
104
+ class Rwkv5Tokenizer(PreTrainedTokenizer):
105
+ vocab_files_names = VOCAB_FILES_NAMES
106
+ pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
107
+ max_model_input_sizes = {"ArthurZ/rwkv-5-utf": 2048}
108
+
109
+ model_input_names = ["input_ids", "attention_mask"]
110
+
111
+ def __init__(self, vocab_file, bos_token="<s>", eos_token="<s>", unk_token="<s>", **kwargs):
112
+ if not os.path.isfile(vocab_file):
113
+ raise ValueError(
114
+ f"Can't find a vocabulary file at path '{vocab_file}'. To load the vocabulary from a Google pretrained"
115
+ " model use `tokenizer = BertTokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`"
116
+ )
117
+
118
+ with open(vocab_file, "r") as reader:
119
+ tokens = reader.readlines()
120
+ vocab = {}
121
+ for index, token in enumerate(tokens):
122
+ token = eval(token.rstrip("\n"))
123
+ vocab[token] = index
124
+
125
+ self.add_bos_token = True
126
+ self.encoder = vocab
127
+ self.decoder = {v: k for k, v in vocab.items()}
128
+ self.wordpiece_tokenizer = WordpieceTokenizer(vocab=self.encoder, unk_token=str(unk_token))
129
+ self._added_tokens_decoder = {0: AddedToken(str(bos_token))}
130
+ super().__init__(bos_token=bos_token, eos_token=eos_token, unk_token=unk_token, **kwargs)
131
+
132
+ @property
133
+ def vocab_size(self):
134
+ return len(self.encoder)
135
+
136
+ def get_vocab(self):
137
+ vocab = {str(self.convert_ids_to_tokens(i)): i for i in range(self.vocab_size)}
138
+ vocab.update(self.added_tokens_encoder)
139
+ return vocab
140
+
141
+ def _tokenize(self, text, split_special_tokens=False):
142
+ return self.wordpiece_tokenizer.tokenize(text.encode("utf-8"))
143
+
144
+ def _convert_token_to_id(self, token):
145
+ """Converts a token (byte) to an id using the vocab."""
146
+ if token.startswith("b'\\"):
147
+ token = eval(token)
148
+ elif not isinstance(token, bytes):
149
+ token = token.encode("utf-8", errors="replace")
150
+ return self.encoder.get(token, self.unk_token_id)
151
+
152
+ def _convert_id_to_token(self, index):
153
+ """Converts an index (integer) in a token (byte) using the vocab."""
154
+ token = self.decoder.get(index, self.unk_token)
155
+ if isinstance(token, (bytes)):
156
+ token = token.decode("utf-8", errors="replace")
157
+ return token
158
+
159
+ def convert_tokens_to_string(self, tokens):
160
+ """Converts a sequence of tokens (bytes) in a single string. Additional tokens are encoded to bytes"""
161
+ out_string = b"".join([k.encode(errors="replace") if isinstance(k, str) else k for k in tokens]).decode(
162
+ "utf-8"
163
+ )
164
+ return out_string
165
+
166
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
167
+ index = 0
168
+ if os.path.isdir(save_directory):
169
+ vocab_file = os.path.join(
170
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
171
+ )
172
+ else:
173
+ vocab_file = (filename_prefix + "-" if filename_prefix else "") + save_directory
174
+ with open(vocab_file, "w") as writer:
175
+ for token, token_index in sorted(self.encoder.items(), key=lambda kv: kv[1]):
176
+ if index != token_index:
177
+ logger.warning(
178
+ f"Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive."
179
+ " Please check that the vocabulary is not corrupted!"
180
+ )
181
+ index = token_index
182
+ writer.write(str(token) + "\n")
183
+ index += 1
184
+ return (vocab_file,)
185
+
186
+ def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
187
+ if self.add_bos_token:
188
+ bos_token_ids = [self.bos_token_id]
189
+ else:
190
+ bos_token_ids = []
191
+
192
+ output = bos_token_ids + token_ids_0
193
+
194
+ if token_ids_1 is None:
195
+ return output
196
+
197
+ return output + bos_token_ids + token_ids_1
198
+
199
+ def get_special_tokens_mask(
200
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
201
+ ) -> List[int]:
202
+ """
203
+ Retrieves sequence ids from a token list that has no special tokens added. This method is called when adding
204
+ special tokens using the tokenizer `prepare_for_model` or `encode_plus` methods.
205
+
206
+ Args:
207
+ token_ids_0 (`List[int]`):
208
+ List of IDs.
209
+ token_ids_1 (`List[int]`, *optional*):
210
+ Optional second list of IDs for sequence pairs.
211
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
212
+ Whether or not the token list is already formatted with special tokens for the model.
213
+
214
+ Returns:
215
+ `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
216
+ """
217
+ if already_has_special_tokens:
218
+ return super().get_special_tokens_mask(
219
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
220
+ )
221
+
222
+ if not self.add_bos_token:
223
+ return super().get_special_tokens_mask(
224
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=False
225
+ )
226
+
227
+ if token_ids_1 is None:
228
+ return [1] + ([0] * len(token_ids_0))
229
+ return [1] + ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1))
tokenizer_config.json CHANGED
@@ -1,12 +1,12 @@
1
  {
2
- "name_or_path": "rwkv-world",
3
- "add_prefix_space": false,
4
- "tokenizer_class": "RWKVWorldTokenizer",
5
- "use_fast": false,
6
- "auto_map": {
7
- "AutoTokenizer": [
8
- "tokenization_rwkv_world.RWKVWorldTokenizer",
9
- null
10
- ]
11
- }
12
- }
 
1
  {
2
+ "name_or_path": "rwkv-5-tokenizer",
3
+ "add_prefix_space": false,
4
+ "tokenizer_class": "Rwkv5Tokenizer",
5
+ "use_fast": false,
6
+ "auto_map": {
7
+ "AutoTokenizer": [
8
+ "tokenization_rwkv5.Rwkv5Tokenizer",
9
+ null
10
+ ]
11
+ }
12
+ }
vocab.txt ADDED
The diff for this file is too large to render. See raw diff