SmerkyG commited on
Commit
c4d7dce
0 Parent(s):

Duplicate from SmerkyG/rwkv-6-world-1b6

Browse files
.gitattributes ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ ---
config.json ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "Rwkv6ForCausalLM"
4
+ ],
5
+ "auto_map": {
6
+ "AutoConfig": "configuration_rwkv6.Rwkv6Config",
7
+ "AutoModelForCausalLM": "modeling_rwkv6.Rwkv6ForCausalLM"
8
+ },
9
+ "attention_hidden_size": 2048,
10
+ "bos_token_id": 0,
11
+ "eos_token_id": 0,
12
+ "head_size": 64,
13
+ "head_size_divisor": 8,
14
+ "hidden_size": 2048,
15
+ "intermediate_size": null,
16
+ "layer_norm_epsilon": 1e-05,
17
+ "max_context_length": 4096,
18
+ "model_type": "rwkv6",
19
+ "num_attention_heads": 64,
20
+ "num_hidden_layers": 24,
21
+ "rescale_every": 6,
22
+ "tie_word_embeddings": false,
23
+ "transformers_version": "4.37.2",
24
+ "use_cache": true,
25
+ "vocab_size": 65536
26
+ }
configuration_rwkv6.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 The OpenAI Team Authors 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
+ """ RWKV configuration"""
17
+
18
+ from transformers.configuration_utils import PretrainedConfig
19
+ from transformers.utils import logging
20
+
21
+
22
+ logger = logging.get_logger(__name__)
23
+
24
+ RWKV6_PRETRAINED_CONFIG_ARCHIVE_MAP = {}
25
+
26
+
27
+ class Rwkv6Config(PretrainedConfig):
28
+ """
29
+ This is the configuration class to store the configuration of a [`Rwkv6Model`]. It is used to instantiate a RWKV6
30
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
31
+ defaults will yield a similar configuration to that of the RWVK-4
32
+ [RWKV/rwkv-5-world-1b5](https://huggingface.co/RWKV/rwkv-5-world-1b5) architecture.
33
+
34
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
35
+ documentation from [`PretrainedConfig`] for more information.
36
+
37
+
38
+ Args:
39
+ vocab_size (`int`, *optional*, defaults to 65536):
40
+ Vocabulary size of the RWKV6 model. Defines the number of different tokens that can be represented by the
41
+ `inputs_ids` passed when calling [`Rwkv6Model`].
42
+ hidden_size (`int`, *optional*, defaults to 768):
43
+ Dimensionality of the embeddings and hidden states.
44
+ num_hidden_layers (`int`, *optional*, defaults to 24):
45
+ Number of hidden layers in the model.
46
+ attention_hidden_size (`int`, *optional*):
47
+ Dimensionality of the attention hidden states. Will default to `hidden_size` if unset.
48
+ num_attention_heads (`int`, *optional*, defaults to 64):
49
+ The attention heads to use in rwkv6 self_attention module.
50
+ head_size (`int`, *optional*, defaults to 64): head_size of rwkv6 self_attention module.
51
+ intermediate_size (`int`, *optional*):
52
+ Dimensionality of the inner feed-forward layers. Will default to 4 times `hidden_size` if unset.
53
+ layer_norm_epsilon (`float`, *optional*, defaults to 1e-05):
54
+ The epsilon to use in the layer normalization layers.
55
+ bos_token_id (`int`, *optional*, defaults to 0):
56
+ The id of the beginning of sentence token in the vocabulary. Defaults to 0.
57
+ eos_token_id (`int`, *optional*, defaults to 0):
58
+ The id of the end of sentence token in the vocabulary. Defaults to 0.
59
+ rescale_every (`int`, *optional*, defaults to 6):
60
+ At inference, the hidden states (and weights of the correponding output layers) are divided by 2 every
61
+ `rescale_every` layer. If set to 0 or a negative number, no rescale is done.
62
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
63
+ Whether or not to tie the word embeddings with the input token embeddings.
64
+ use_cache (`bool`, *optional*, defaults to `True`):
65
+ Whether or not the model should return the last state.
66
+
67
+
68
+ Example:
69
+
70
+ ```python
71
+ >>> from transformers import Rwkv6Config, Rwkv6Model
72
+
73
+ >>> # Initializing a Rwkv6 configuration
74
+ >>> configuration = Rwkv6Config()
75
+
76
+ >>> # Initializing a model (with random weights) from the configuration
77
+ >>> model = Rwkv6Model(configuration)
78
+
79
+ >>> # Accessing the model configuration
80
+ >>> configuration = model.config
81
+ ```"""
82
+
83
+ model_type = "rwkv6"
84
+
85
+ def __init__(
86
+ self,
87
+ vocab_size=65536,
88
+ hidden_size=768,
89
+ num_hidden_layers=24,
90
+ attention_hidden_size=None,
91
+ head_size=64,
92
+ head_size_divisor=8,
93
+ intermediate_size=None,
94
+ layer_norm_epsilon=1e-5,
95
+ bos_token_id=0,
96
+ eos_token_id=0,
97
+ rescale_every=6,
98
+ tie_word_embeddings=False,
99
+ use_cache=True,
100
+ **kwargs,
101
+ ):
102
+ self.vocab_size = vocab_size
103
+ self.hidden_size = hidden_size
104
+ self.num_hidden_layers = num_hidden_layers
105
+ self.attention_hidden_size = attention_hidden_size if attention_hidden_size is not None else hidden_size
106
+ self.head_size = head_size
107
+ self.head_size_divisor = head_size_divisor
108
+ self.intermediate_size = None
109
+ self.layer_norm_epsilon = layer_norm_epsilon
110
+ self.rescale_every = rescale_every
111
+ self.use_cache = use_cache
112
+
113
+ self.bos_token_id = bos_token_id
114
+ self.eos_token_id = eos_token_id
115
+
116
+ super().__init__(
117
+ tie_word_embeddings=tie_word_embeddings, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs
118
+ )
generation_config.json ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "chat_format": "chatml",
3
+ "eos_token_id": 0,
4
+ "pad_token_id": 0,
5
+ "max_window_size": 4096,
6
+ "max_new_tokens": 4096,
7
+ "do_sample": true,
8
+ "top_k": 0,
9
+ "top_p": 0.1,
10
+ "repetition_penalty": 1.0,
11
+ "transformers_version": "4.31.1"
12
+ }
modeling_rwkv6.py ADDED
@@ -0,0 +1,823 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The RWKV team and 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
+ """PyTorch RWKV6 World model."""
16
+
17
+ from dataclasses import dataclass
18
+ from typing import List, Optional, Tuple, Union
19
+
20
+ from pathlib import Path
21
+
22
+ import torch
23
+ import torch.nn.functional as F
24
+ import torch.utils.checkpoint
25
+ from torch import nn
26
+ from torch.nn import CrossEntropyLoss
27
+
28
+ from transformers.modeling_utils import PreTrainedModel
29
+ from transformers.utils import (
30
+ ModelOutput,
31
+ add_code_sample_docstrings,
32
+ add_start_docstrings,
33
+ add_start_docstrings_to_model_forward,
34
+ is_ninja_available,
35
+ is_torch_cuda_available,
36
+ logging,
37
+ )
38
+
39
+ from .configuration_rwkv6 import Rwkv6Config
40
+
41
+
42
+ logger = logging.get_logger(__name__)
43
+
44
+ _CHECKPOINT_FOR_DOC = "RWKV/rwkv-6-world-1b6"
45
+ _CONFIG_FOR_DOC = "Rwkv6Config"
46
+
47
+ rwkv6_cuda_kernel = None
48
+
49
+ def load_wkv6_cuda_kernel(head_size, ctx_len):
50
+ from torch.utils.cpp_extension import load as load_kernel
51
+
52
+ global rwkv6_cuda_kernel
53
+
54
+ kernel_folder = Path(__file__).parent.resolve()
55
+ cuda_kernel_files = [kernel_folder / f for f in ["wkv6_op.cpp", "wkv6_cuda.cu"]]
56
+
57
+ # Only load the kernel if it's not been loaded yet or if we changed the context length
58
+ if rwkv6_cuda_kernel is not None and rwkv6_cuda_kernel.head_size == head_size:
59
+ return
60
+
61
+ logger.info(f"Loading CUDA kernel for RWKV at head size of {head_size}.")
62
+
63
+ flags = [
64
+ "-res-usage",
65
+ # "--maxrregcount 60", # not sure, should we add this? its not in RWKV-LM
66
+ "--use_fast_math",
67
+ "-O3",
68
+ "-Xptxas -O3",
69
+ "--extra-device-vectorization",
70
+ f"-D_N_={head_size}",
71
+ f"-D_T_={ctx_len}"
72
+ ]
73
+ rwkv6_cuda_kernel = load_kernel(
74
+ name=f"wkv_{head_size}_{ctx_len}",
75
+ sources=cuda_kernel_files,
76
+ verbose=(logging.get_verbosity() == logging.DEBUG),
77
+ extra_cuda_cflags=flags,
78
+ )
79
+ rwkv6_cuda_kernel.head_size = head_size
80
+ rwkv6_cuda_kernel.ctx_len = ctx_len
81
+
82
+
83
+ class Rwkv6LinearAttention(torch.autograd.Function):
84
+ @staticmethod
85
+ def forward(ctx, receptance, key, value, time_decay, time_first, state):
86
+ with torch.no_grad():
87
+ assert receptance.dtype == torch.bfloat16
88
+ assert key.dtype == torch.bfloat16
89
+ assert value.dtype == torch.bfloat16
90
+ assert time_decay.dtype == torch.bfloat16
91
+ assert time_first.dtype == torch.bfloat16
92
+ assert state.dtype == torch.float32
93
+ #assert HEAD_SIZE == C // H
94
+ Batch, SequenceLength, HiddenSize = key.shape
95
+ NumHeads, HeadSize = time_decay.shape
96
+ ctx.Batch = Batch
97
+ ctx.SequenceLength = SequenceLength
98
+ ctx.HiddenSize = HiddenSize
99
+ ctx.NumHeads = NumHeads
100
+ assert receptance.is_contiguous()
101
+ assert key.is_contiguous()
102
+ assert value.is_contiguous()
103
+ assert time_decay.is_contiguous()
104
+ assert time_first.is_contiguous()
105
+ e_time_decay = (-torch.exp(time_decay.float())).contiguous()
106
+ ctx.save_for_backward(receptance, key, value, e_time_decay, time_first)
107
+ out = torch.empty((Batch, SequenceLength, HiddenSize), device=receptance.device, dtype=torch.bfloat16, memory_format=torch.contiguous_format)#.uniform_(-100, 100)
108
+ # FIXME - current kernel does not handle nor update state
109
+ rwkv6_cuda_kernel.forward(Batch, SequenceLength, HiddenSize, NumHeads, receptance, key, value, e_time_decay, time_first, out)
110
+ return out, state
111
+
112
+ @staticmethod
113
+ def backward(ctx, g_out, g_state):
114
+ with torch.no_grad():
115
+ assert g_out.dtype == torch.bfloat16
116
+ Batch = ctx.Batch
117
+ SequenceLength = ctx.SequenceLength
118
+ HiddenSize = ctx.HiddenSize
119
+ NumHeads = ctx.NumHeads
120
+ HeadSize = HiddenSize // NumHeads
121
+ assert g_out.is_contiguous()
122
+ receptance, key, value, e_time_decay, time_first = ctx.saved_tensors
123
+ g_receptance = torch.empty((B, T, C), device=gy.device, requires_grad=False, dtype=torch.bfloat16, memory_format=torch.contiguous_format)#.uniform_(-100, 100)
124
+ g_key = torch.empty((B, T, C), device=gy.device, requires_grad=False, dtype=torch.bfloat16, memory_format=torch.contiguous_format)#.uniform_(-100, 100)
125
+ g_value = torch.empty((B, T, C), device=gy.device, requires_grad=False, dtype=torch.bfloat16, memory_format=torch.contiguous_format)#.uniform_(-100, 100)
126
+ g_time_decay = torch.empty((B, T, C), device=gy.device, requires_grad=False, dtype=torch.bfloat16, memory_format=torch.contiguous_format)#.uniform_(-100, 100)
127
+ g_time_first = torch.empty((B, C), device=gy.device, requires_grad=False, dtype=torch.bfloat16, memory_format=torch.contiguous_format)#.uniform_(-100, 100)
128
+ #gs = torch.empty((B, C//H, H, H), device=gy.device, requires_grad=False, dtype=torch.float, memory_format=torch.contiguous_format)#.uniform_(-100, 100)
129
+ rwkv6_cuda_kernel.backward(B, T, C, H, receptance, key, value, e_time_decay, time_first, g_out, g_receptance, g_key, g_value, g_time_decay, g_time_first)
130
+ g_time_first = torch.sum(g_time_first, 0).view(NumHeads, HeadSize)
131
+ return (None, None, None, None, g_receptance, g_key, g_value, g_time_decay, g_time_first, None)
132
+
133
+ def rwkv6_linear_attention_cpu(receptance, key, value, time_decay, time_first, state):
134
+ input_dtype = receptance.dtype
135
+ # For CPU fallback. Will be slower and probably take more memory than the custom CUDA kernel if not executed
136
+ # within a torch.no_grad.
137
+ batch, seq_length, hidden_size = receptance.shape
138
+ num_heads, head_size = time_first.shape
139
+ key = key.float().view(batch, seq_length, num_heads, head_size).transpose(1, 2).transpose(-2, -1)
140
+ value = value.float().view(batch, seq_length, num_heads, head_size).transpose(1, 2)
141
+ receptance = receptance.float().view(batch, seq_length, num_heads, head_size).transpose(1, 2)
142
+ time_decay = torch.exp(-torch.exp(time_decay.float())).view(batch, seq_length, num_heads, head_size).permute(0, 2, 3, 1) # B, H, S, T
143
+ time_first = time_first.float().reshape(-1, 1, 1).reshape(num_heads, -1, 1)
144
+ out = torch.zeros_like(key).reshape(batch, seq_length, num_heads, head_size)
145
+
146
+ for current_index in range(seq_length):
147
+ current_receptance = receptance[:, :, current_index:current_index+1, :]
148
+ current_key = key[:, :, :, current_index:current_index+1]
149
+ current_value = value[:, :, current_index:current_index+1, :]
150
+ current_time_decay = time_decay[:, :, :, current_index:current_index+1]
151
+ attention_output = current_key @ current_value
152
+ out[:, current_index] = (current_receptance @ (time_first * attention_output + state)).squeeze(2)
153
+ with torch.no_grad():
154
+ state = attention_output + current_time_decay * state
155
+
156
+ return out, state
157
+
158
+ def rwkv6_linear_attention(
159
+ training,
160
+ receptance,
161
+ key,
162
+ value,
163
+ time_decay,
164
+ time_first,
165
+ state,
166
+ ):
167
+ no_cuda = any(t.device.type != "cuda" for t in [time_decay, time_first, receptance, key, value])
168
+ # Launching the CUDA kernel for just one token will actually be slower (there is no for loop in the CPU version
169
+ # in this case).
170
+ one_token = key.size(1) == 1
171
+ if not training or rwkv6_cuda_kernel is None or no_cuda or one_token:
172
+ return rwkv6_linear_attention_cpu(
173
+ receptance, key, value, time_decay, time_first, state
174
+ )
175
+ else:
176
+ return Rwkv6LinearAttention.apply(receptance, key, value, time_decay, time_first, state)
177
+
178
+
179
+ class Rwkv6SelfAttention(nn.Module):
180
+ def __init__(self, config, layer_id=0):
181
+ super().__init__()
182
+ self.config = config
183
+ kernel_loaded = rwkv6_cuda_kernel is not None and rwkv6_cuda_kernel.head_size == config.head_size
184
+ if is_ninja_available() and is_torch_cuda_available() and not kernel_loaded:
185
+ try:
186
+ load_wkv6_cuda_kernel(config.head_size, config.max_context_length) # FIXME - context_length is not a configured attribute
187
+ except Exception:
188
+ logger.info("Could not load the custom CUDA kernel for RWKV6 attention.")
189
+ self.layer_id = layer_id
190
+ hidden_size = config.hidden_size
191
+ attention_hidden_size = config.attention_hidden_size
192
+ self.attention_hidden_size = attention_hidden_size
193
+ head_size = config.head_size
194
+ num_heads = attention_hidden_size // head_size
195
+
196
+ self.time_maa_x = nn.Parameter(torch.empty(1, 1, hidden_size))
197
+ self.time_maa_w = nn.Parameter(torch.empty(1, 1, hidden_size))
198
+ self.time_maa_k = nn.Parameter(torch.empty(1, 1, hidden_size))
199
+ self.time_maa_v = nn.Parameter(torch.empty(1, 1, hidden_size))
200
+ self.time_maa_r = nn.Parameter(torch.empty(1, 1, hidden_size))
201
+ self.time_maa_g = nn.Parameter(torch.empty(1, 1, hidden_size))
202
+
203
+ TIME_MIX_EXTRA_DIM = 32 # generate TIME_MIX for w,k,v,r,g
204
+ self.time_maa_w1 = nn.Parameter(torch.empty(hidden_size, TIME_MIX_EXTRA_DIM*5))
205
+ self.time_maa_w2 = nn.Parameter(torch.empty(5, TIME_MIX_EXTRA_DIM, hidden_size))
206
+
207
+ self.time_decay = nn.Parameter(torch.empty(1, 1, attention_hidden_size))
208
+
209
+ TIME_DECAY_EXTRA_DIM = 64
210
+ self.time_decay_w1 = nn.Parameter(torch.empty(hidden_size, TIME_DECAY_EXTRA_DIM))
211
+ self.time_decay_w2 = nn.Parameter(torch.empty(TIME_DECAY_EXTRA_DIM, attention_hidden_size))
212
+
213
+ self.time_faaaa = nn.Parameter(torch.empty(num_heads, config.head_size))
214
+
215
+ self.time_shift = nn.ZeroPad2d((0, 0, 1, -1))
216
+ self.key = nn.Linear(hidden_size, attention_hidden_size, bias=False)
217
+ self.value = nn.Linear(hidden_size, attention_hidden_size, bias=False)
218
+ self.receptance = nn.Linear(hidden_size, attention_hidden_size, bias=False)
219
+ self.gate = nn.Linear(hidden_size, attention_hidden_size, bias=False)
220
+ self.output = nn.Linear(attention_hidden_size, hidden_size, bias=False)
221
+ self.ln_x = nn.GroupNorm(num_heads, hidden_size, eps=(1e-5)*(config.head_size_divisor**2))
222
+
223
+ def extract_key_value(self, hidden, state=None):
224
+ # Mix hidden with the previous timestep to produce key, value, receptance
225
+ if hidden.size(1) == 1 and state is not None:
226
+ shifted = state[0][:, :, self.layer_id]
227
+ else:
228
+ shifted = self.time_shift(hidden)
229
+ if state is not None:
230
+ shifted[:, 0] = state[0][:, :, self.layer_id]
231
+ if len(shifted.size()) == 2:
232
+ shifted = shifted.unsqueeze(1)
233
+
234
+ x = hidden
235
+
236
+ B, T, C = hidden.shape
237
+
238
+ xx = shifted - x
239
+
240
+ xxx = x + xx * self.time_maa_x
241
+ xxx = torch.tanh(xxx @ self.time_maa_w1).view(B*T, 5, -1).transpose(0, 1)
242
+ xxx = torch.bmm(xxx, self.time_maa_w2).view(5, B, T, -1)
243
+ mw, mk, mv, mr, mg = xxx.unbind(dim=0)
244
+
245
+ time_decay = x + xx * (self.time_maa_w + mw)
246
+ key = x + xx * (self.time_maa_k + mk)
247
+ value = x + xx * (self.time_maa_v + mv)
248
+ receptance = x + xx * (self.time_maa_r + mr)
249
+ gate = x + xx * (self.time_maa_g + mg)
250
+
251
+ receptance = self.receptance(receptance)
252
+ key = self.key(key)
253
+ value = self.value(value)
254
+ gate = F.silu(self.gate(gate))
255
+
256
+ time_decay = torch.tanh(time_decay @ self.time_decay_w1) @ self.time_decay_w2
257
+ time_decay = self.time_decay + time_decay
258
+
259
+ if state is not None:
260
+ state[0][:, :, self.layer_id] = hidden[:, -1]
261
+
262
+ return receptance, key, value, gate, time_decay, state
263
+
264
+ def forward(self, hidden, state=None, use_cache=False, seq_mode=True):
265
+ receptance, key, value, gate, time_decay, state = self.extract_key_value(hidden, state=state)
266
+
267
+ B,T,C = receptance.shape
268
+ H, S = self.time_faaaa.shape
269
+
270
+ layer_state = state[1][:, :, :, :, self.layer_id] if state is not None else None
271
+ out, layer_state = rwkv6_linear_attention(
272
+ self.training, receptance, key, value, time_decay, self.time_faaaa, layer_state,
273
+ )
274
+
275
+ if layer_state is not None:
276
+ state[1][:, :, :, :, self.layer_id] = layer_state
277
+
278
+ out = out.reshape(B * T, H * S)
279
+ out = F.group_norm(out, num_groups=H, weight=self.ln_x.weight.to(out.dtype), bias=self.ln_x.bias.to(out.dtype), eps=self.ln_x.eps).reshape(B, T, H * S)
280
+ out = out.to(dtype=hidden.dtype) * gate
281
+ out = self.output(out)
282
+ return out, state
283
+
284
+
285
+ class Rwkv6FeedForward(nn.Module):
286
+ def __init__(self, config, layer_id=0):
287
+ super().__init__()
288
+ self.config = config
289
+ self.layer_id = layer_id
290
+ hidden_size = config.hidden_size
291
+ # https://github.com/BlinkDL/RWKV-LM/blob/3db37a72356b736966ddd377268f02b80963af3f/RWKV-v4neo/train.py#L168
292
+ intermediate_size = (
293
+ config.intermediate_size
294
+ if config.intermediate_size is not None
295
+ else int((config.hidden_size * 3.5) // 32 * 32)
296
+ )
297
+
298
+ self.time_shift = nn.ZeroPad2d((0, 0, 1, -1))
299
+ self.time_maa_k = nn.Parameter(torch.empty(1, 1, hidden_size))
300
+ self.time_maa_r = nn.Parameter(torch.empty(1, 1, hidden_size))
301
+
302
+ self.key = nn.Linear(hidden_size, intermediate_size, bias=False)
303
+ self.receptance = nn.Linear(hidden_size, hidden_size, bias=False)
304
+ self.value = nn.Linear(intermediate_size, hidden_size, bias=False)
305
+
306
+ def forward(self, hidden, state=None):
307
+ if hidden.size(1) == 1 and state is not None:
308
+ shifted = state[2][:, :, self.layer_id]
309
+ else:
310
+ shifted = self.time_shift(hidden)
311
+ if state is not None:
312
+ shifted[:, 0] = state[2][:, :, self.layer_id]
313
+ if len(shifted.size()) == 2:
314
+ shifted = shifted.unsqueeze(1)
315
+
316
+ delta_hidden_to_shifted = shifted - hidden
317
+ key = hidden + delta_hidden_to_shifted * self.time_maa_k
318
+ receptance = hidden + delta_hidden_to_shifted * self.time_maa_r
319
+
320
+ key = torch.square(torch.relu(self.key(key)))
321
+ value = self.value(key)
322
+ receptance = torch.sigmoid(self.receptance(receptance))
323
+
324
+ if state is not None:
325
+ state[2][:, :, self.layer_id] = hidden[:, -1]
326
+
327
+ return receptance * value, state
328
+
329
+
330
+ class Rwkv6Block(nn.Module):
331
+ def __init__(self, config, layer_id):
332
+ super().__init__()
333
+ self.config = config
334
+ self.layer_id = layer_id
335
+
336
+ if layer_id == 0:
337
+ self.pre_ln = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_epsilon)
338
+
339
+ self.ln1 = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_epsilon)
340
+ self.ln2 = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_epsilon)
341
+
342
+ self.attention = Rwkv6SelfAttention(config, layer_id)
343
+ self.feed_forward = Rwkv6FeedForward(config, layer_id)
344
+
345
+ def forward(self, hidden, state=None, use_cache=False, output_attentions=False, seq_mode=True):
346
+ if self.layer_id == 0:
347
+ hidden = self.pre_ln(hidden)
348
+ attention, state = self.attention(self.ln1(hidden), state=state, use_cache=use_cache, seq_mode=seq_mode)
349
+ hidden = hidden + attention
350
+
351
+ feed_forward, state = self.feed_forward(self.ln2(hidden), state=state)
352
+ hidden = hidden + feed_forward
353
+
354
+ outputs = (hidden, state)
355
+ if output_attentions:
356
+ outputs += (attention,)
357
+ else:
358
+ outputs += (None,)
359
+
360
+ return outputs
361
+
362
+
363
+ class Rwkv6PreTrainedModel(PreTrainedModel):
364
+ """
365
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
366
+ models.
367
+ """
368
+
369
+ config_class = Rwkv6Config
370
+ base_model_prefix = "rwkv6"
371
+ _no_split_modules = ["Rwkv6Block"]
372
+ _keep_in_fp32_modules = ["time_decay", "time_first"]
373
+ supports_gradient_checkpointing = True
374
+
375
+ def _init_weights(self, module):
376
+ """Initialize the weights."""
377
+ if isinstance(module, Rwkv6SelfAttention):
378
+ layer_id = module.layer_id
379
+ num_hidden_layers = module.config.num_hidden_layers
380
+ hidden_size = module.config.hidden_size
381
+ attention_hidden_size = module.attention_hidden_size
382
+ head_size = module.config.head_size
383
+ num_heads = attention_hidden_size // head_size
384
+
385
+ ratio_0_to_1 = layer_id / (num_hidden_layers - 1) # 0 to 1
386
+ ratio_1_to_almost0 = 1.0 - (layer_id / num_hidden_layers) # 1 to ~0
387
+
388
+ time_weight = torch.tensor(
389
+ [i / hidden_size for i in range(hidden_size)],
390
+ dtype=module.time_maa_k.dtype,
391
+ device=module.time_maa_k.device,
392
+ )
393
+ time_weight = time_weight[None, None, :]
394
+
395
+ decay_speed = [
396
+ -6.0 + 5.0 * (h / (attention_hidden_size - 1)) ** (0.7 + 1.3 * ratio_0_to_1)
397
+ for h in range(attention_hidden_size)
398
+ ]
399
+ decay_speed = torch.tensor(decay_speed, dtype=module.time_decay.dtype, device=module.time_decay.device)
400
+ tmp = torch.tensor(
401
+ [
402
+ (1.0 - (i / (attention_hidden_size - 1.0))) * ratio_0_to_1 + 0.1 * ((i + 1) % 3 - 1)
403
+ for i in range(attention_hidden_size)
404
+ ],
405
+ dtype=module.time_faaaa.dtype,
406
+ device=module.time_faaaa.device,
407
+ )
408
+
409
+ with torch.no_grad():
410
+ module.time_maa_x.data = 1.0 - torch.pow(time_weight, ratio_1_to_almost0)
411
+ module.time_maa_w.data = 1.0 - torch.pow(time_weight, ratio_1_to_almost0)
412
+ module.time_maa_k.data = 1.0 - torch.pow(time_weight, ratio_1_to_almost0)
413
+ module.time_maa_v.data = 1.0 - (torch.pow(time_weight, ratio_1_to_almost0) + 0.3 * ratio_0_to_1)
414
+ module.time_maa_r.data = 1.0 - torch.pow(time_weight, 0.5 * ratio_1_to_almost0)
415
+ module.time_maa_g.data = 1.0 - torch.pow(time_weight, 0.5 * ratio_1_to_almost0)
416
+
417
+ TIME_MIX_EXTRA_DIM = 32 # generate TIME_MIX for w,k,v,r,g
418
+ module.time_maa_w1.data = torch.zeros(hidden_size, TIME_MIX_EXTRA_DIM*5, dtype=module.time_maa_w1.dtype, device=module.time_maa_w1.device).uniform_(-1e-4, 1e-4)
419
+ module.time_maa_w2.data = torch.zeros(5, TIME_MIX_EXTRA_DIM, hidden_size, dtype=module.time_maa_w2.dtype, device=module.time_maa_w2.device).uniform_(-1e-4, 1e-4)
420
+
421
+ TIME_DECAY_EXTRA_DIM = 64
422
+ module.time_decay_w1.data = torch.zeros(hidden_size, TIME_DECAY_EXTRA_DIM, dtype=module.time_decay_w1.dtype, device=module.time_decay_w1.device).uniform_(-1e-4, 1e-4)
423
+ module.time_decay_w2.data = torch.zeros(TIME_DECAY_EXTRA_DIM, attention_hidden_size, dtype=module.time_decay_w2.dtype, device=module.time_decay_w2.device).uniform_(-1e-4, 1e-4)
424
+
425
+ module.time_decay.data = decay_speed.reshape(num_heads, head_size)
426
+ module.time_faaaa.data = tmp.reshape(num_heads, head_size)
427
+
428
+ elif isinstance(module, Rwkv6FeedForward):
429
+ layer_id = module.layer_id
430
+ num_hidden_layers = module.config.num_hidden_layers
431
+ hidden_size = module.config.hidden_size
432
+
433
+ ratio_1_to_almost0 = 1.0 - (layer_id / num_hidden_layers) # 1 to ~0
434
+
435
+ time_weight = torch.tensor(
436
+ [i / hidden_size for i in range(hidden_size)],
437
+ dtype=module.time_maa_k.dtype,
438
+ device=module.time_maa_k.device,
439
+ )
440
+ time_weight = time_weight[None, None, :]
441
+
442
+ with torch.no_grad():
443
+ module.time_maa_k.data = 1.0 - torch.pow(time_weight, ratio_1_to_almost0)
444
+ module.time_maa_r.data = 1.0 - torch.pow(time_weight, ratio_1_to_almost0)
445
+
446
+
447
+ @dataclass
448
+ class Rwkv6Output(ModelOutput):
449
+ """
450
+ Class for the RWKV model outputs.
451
+
452
+ Args:
453
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
454
+ Sequence of hidden-states at the output of the last layer of the model.
455
+ state (list of five `torch.FloatTensor` of shape `(batch_size, hidden_size, num_hidden_layers)`):
456
+ The state of the model at the last time step. Can be used in a forward method with the next `input_ids` to
457
+ avoid providing the old `input_ids`.
458
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
459
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
460
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of
461
+ the model at the output of each layer plus the optional initial embedding outputs.
462
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
463
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
464
+ sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in
465
+ the self-attention heads.
466
+ """
467
+
468
+ last_hidden_state: torch.FloatTensor = None
469
+ state: Optional[List[torch.FloatTensor]] = None
470
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
471
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
472
+
473
+
474
+ @dataclass
475
+ class Rwkv6CausalLMOutput(ModelOutput):
476
+ """
477
+ Base class for causal language model (or autoregressive) outputs.
478
+
479
+ Args:
480
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
481
+ Language modeling loss (for next-token prediction).
482
+ logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
483
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
484
+ state (list of five `torch.FloatTensor` of shape `(batch_size, hidden_size, num_hidden_layers)`):
485
+ The state of the model at the last time step. Can be used in a forward method with the next `input_ids` to
486
+ avoid providing the old `input_ids`.
487
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
488
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
489
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of
490
+ the model at the output of each layer plus the optional initial embedding outputs.
491
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
492
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
493
+ sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in
494
+ the self-attention heads.
495
+ """
496
+
497
+ loss: Optional[torch.FloatTensor] = None
498
+ logits: torch.FloatTensor = None
499
+ state: Optional[List[torch.FloatTensor]] = None
500
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
501
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
502
+
503
+
504
+ RWKV6_START_DOCSTRING = r"""
505
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
506
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
507
+ etc.) This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module)
508
+ subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to
509
+ general usage and behavior.
510
+
511
+ Parameters:
512
+ config ([`Rwkv6Config`]): Model configuration class with all the parameters of the model.
513
+ Initializing with a config file does not load the weights associated with the model, only the
514
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
515
+ """
516
+
517
+ RWKV6_INPUTS_DOCSTRING = r"""
518
+ Args:
519
+ input_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`):
520
+ `input_ids_length` = `sequence_length` if `past_key_values` is `None` else
521
+ `past_key_values[0][0].shape[-2]` (`sequence_length` of input past key value states). Indices of input
522
+ sequence tokens in the vocabulary. If `past_key_values` is used, only `input_ids` that do not have their
523
+ past calculated should be passed as `input_ids`. Indices can be obtained using [`AutoTokenizer`]. See
524
+ [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. [What are input
525
+ IDs?](../glossary#input-ids)
526
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
527
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
528
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
529
+ model's internal embedding lookup matrix.
530
+ state (tuple of five `torch.FloatTensor` of shape `(batch_size, hidden_size, num_hidden_layers)`, *optional*):
531
+ If passed along, the model uses the previous state in all the blocks (which will give the output for the
532
+ `input_ids` provided as if the model add `state_input_ids + input_ids` as context).
533
+ use_cache (`bool`, *optional*):
534
+ If set to `True`, the last state is returned and can be used to quickly generate the next logits.
535
+ output_attentions (`bool`, *optional*):
536
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
537
+ tensors for more detail.
538
+ output_hidden_states (`bool`, *optional*):
539
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
540
+ more detail.
541
+ return_dict (`bool`, *optional*):
542
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
543
+ """
544
+
545
+
546
+ @add_start_docstrings(
547
+ "The bare RWKV6 Model transformer outputting raw hidden-states without any specific head on top.",
548
+ RWKV6_START_DOCSTRING,
549
+ )
550
+ class Rwkv6Model(Rwkv6PreTrainedModel):
551
+ def __init__(self, config):
552
+ super().__init__(config)
553
+
554
+ self.embeddings = nn.Embedding(config.vocab_size, config.hidden_size)
555
+ self.blocks = nn.ModuleList([Rwkv6Block(config, layer_id=idx) for idx in range(config.num_hidden_layers)])
556
+ self.ln_out = nn.LayerNorm(config.hidden_size)
557
+
558
+ self.layers_are_rescaled = False
559
+ self.gradient_checkpointing = False
560
+
561
+ # Initialize weights and apply final processing
562
+ self.post_init()
563
+
564
+ def get_input_embeddings(self):
565
+ return self.embeddings
566
+
567
+ def set_input_embeddings(self, new_embeddings):
568
+ self.embeddings = new_embeddings
569
+
570
+ @add_start_docstrings_to_model_forward(RWKV6_INPUTS_DOCSTRING)
571
+ @add_code_sample_docstrings(
572
+ checkpoint=_CHECKPOINT_FOR_DOC,
573
+ output_type=Rwkv6Output,
574
+ config_class=_CONFIG_FOR_DOC,
575
+ )
576
+ def forward(
577
+ self,
578
+ input_ids: Optional[torch.LongTensor] = None,
579
+ attention_mask: Optional[torch.LongTensor] = None, # noqa
580
+ inputs_embeds: Optional[torch.FloatTensor] = None,
581
+ state: Optional[List[torch.FloatTensor]] = None,
582
+ use_cache: Optional[bool] = None,
583
+ output_attentions: Optional[bool] = None,
584
+ output_hidden_states: Optional[bool] = None,
585
+ return_dict: Optional[bool] = None,
586
+ ) -> Union[Tuple, Rwkv6Output]:
587
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
588
+ output_hidden_states = (
589
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
590
+ )
591
+ # FIXME - training is supportable with the CUDA code
592
+ # rwkv6 only support inference in huggingface.
593
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
594
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
595
+
596
+ if self.training == self.layers_are_rescaled and (
597
+ self.embeddings.weight.dtype == torch.float16 or self.embeddings.weight.dtype == torch.bfloat16
598
+ ):
599
+ self._rescale_layers()
600
+
601
+ if input_ids is not None and inputs_embeds is not None:
602
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
603
+ elif input_ids is None and inputs_embeds is None:
604
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
605
+
606
+ if inputs_embeds is None:
607
+ inputs_embeds = self.embeddings(input_ids)
608
+
609
+ if state is None:
610
+ state = []
611
+ head_size = self.config.head_size
612
+ num_heads = self.config.attention_hidden_size // head_size
613
+ state_attn_x = torch.zeros(
614
+ (inputs_embeds.size(0), self.config.hidden_size, self.config.num_hidden_layers),
615
+ dtype=inputs_embeds.dtype,
616
+ requires_grad=False,
617
+ device=inputs_embeds.device,
618
+ ).contiguous()
619
+ state_attn_kv = torch.zeros(
620
+ (
621
+ inputs_embeds.size(0),
622
+ num_heads,
623
+ head_size,
624
+ head_size,
625
+ self.config.num_hidden_layers,
626
+ ),
627
+ dtype=torch.float32,
628
+ requires_grad=False,
629
+ device=inputs_embeds.device,
630
+ ).contiguous()
631
+ state_ffn_x = torch.zeros(
632
+ (inputs_embeds.size(0), self.config.hidden_size, self.config.num_hidden_layers),
633
+ dtype=inputs_embeds.dtype,
634
+ requires_grad=False,
635
+ device=inputs_embeds.device,
636
+ ).contiguous()
637
+ state.append(state_attn_x)
638
+ state.append(state_attn_kv)
639
+ state.append(state_ffn_x)
640
+
641
+ seq_mode = inputs_embeds.shape[1] > 1
642
+ hidden_states = inputs_embeds
643
+
644
+ all_self_attentions = () if output_attentions else None
645
+ all_hidden_states = () if output_hidden_states else None
646
+ for idx, block in enumerate(self.blocks):
647
+ hidden_states, state, attentions = block(
648
+ hidden_states, state=state, use_cache=use_cache, output_attentions=output_attentions, seq_mode=seq_mode
649
+ )
650
+ if (
651
+ self.layers_are_rescaled
652
+ and self.config.rescale_every > 0
653
+ and (idx + 1) % self.config.rescale_every == 0
654
+ ):
655
+ hidden_states = hidden_states / 2
656
+
657
+ if output_hidden_states:
658
+ all_hidden_states = all_hidden_states + (hidden_states,)
659
+
660
+ if output_attentions:
661
+ all_self_attentions = all_self_attentions + (attentions,)
662
+
663
+ hidden_states = self.ln_out(hidden_states)
664
+
665
+ if output_hidden_states:
666
+ all_hidden_states = all_hidden_states + (hidden_states,)
667
+
668
+ if not return_dict:
669
+ return (hidden_states, state, all_hidden_states, all_self_attentions)
670
+
671
+ return Rwkv6Output(
672
+ last_hidden_state=hidden_states,
673
+ state=state,
674
+ hidden_states=all_hidden_states, # None
675
+ attentions=all_self_attentions, # None
676
+ )
677
+
678
+ def _rescale_layers(self):
679
+ # Layers should be rescaled for inference only.
680
+ if self.layers_are_rescaled == (not self.training):
681
+ return
682
+ if self.config.rescale_every > 0:
683
+ with torch.no_grad():
684
+ for block_id, block in enumerate(self.blocks):
685
+ if self.training:
686
+ block.attention.output.weight.mul_(2 ** int(block_id // self.config.rescale_every))
687
+ block.feed_forward.value.weight.mul_(2 ** int(block_id // self.config.rescale_every))
688
+ else:
689
+ # Deal with quantization statistics
690
+ if hasattr(block.attention.output.weight, "SCB"):
691
+ block.attention.output.weight.SCB.div_(2 ** int(block_id // self.config.rescale_every))
692
+ block.feed_forward.value.weight.SCB.div_(2 ** int(block_id // self.config.rescale_every))
693
+ elif hasattr(block.attention.output.weight, "quant_state"):
694
+ self._bnb_4bit_dequantize_and_rescale(block.attention.output, block_id)
695
+ self._bnb_4bit_dequantize_and_rescale(block.feed_forward.value, block_id)
696
+ else:
697
+ block.attention.output.weight.div_(2 ** int(block_id // self.config.rescale_every))
698
+ block.feed_forward.value.weight.div_(2 ** int(block_id // self.config.rescale_every))
699
+
700
+ self.layers_are_rescaled = not self.training
701
+
702
+ def _bnb_4bit_dequantize_and_rescale(self, target_layer, block_id):
703
+ r"""
704
+ Perform the dequantization and rescaling of the weights of a given layer. After that operation the layer will
705
+ be quantized again.
706
+ """
707
+ if not is_bitsandbytes_available():
708
+ raise ImportError("Please install bitsandbytes to use this method.")
709
+ import bitsandbytes as bnb
710
+
711
+ dequant_weights = bnb.functional.dequantize_4bit(target_layer.weight.data, target_layer.weight.quant_state)
712
+
713
+ dequant_weights.div_(2 ** int(block_id // self.config.rescale_every))
714
+
715
+ # re-quantize the model:
716
+ # we need to put it first on CPU then back to the device
717
+ # this will create an overhead :/
718
+ # We set requires_grad=False as we cannot compute gradients on top of 4bit parameters anyway and to avoid
719
+ # bugs with bnb
720
+ quant_weight = bnb.nn.Params4bit(dequant_weights.to("cpu"), requires_grad=False).to(dequant_weights.device)
721
+ setattr(target_layer, "weight", quant_weight)
722
+
723
+
724
+ # copied from HuggingFace https://github.com/huggingface/transformers/blob/main/src/transformers/models/rwkv/modeling_rwkv.py
725
+ @add_start_docstrings(
726
+ """
727
+ The RWKV6 Model transformer with a language modeling head on top (linear layer with weights tied to the input
728
+ embeddings).
729
+ """,
730
+ RWKV6_START_DOCSTRING,
731
+ )
732
+ class Rwkv6ForCausalLM(Rwkv6PreTrainedModel):
733
+ _tied_weights_keys = ["head.weight"]
734
+
735
+ def __init__(self, config):
736
+ super().__init__(config)
737
+ self.rwkv = Rwkv6Model(config)
738
+ self.head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
739
+
740
+ # Initialize weights and apply final processing
741
+ self.post_init()
742
+
743
+ def get_output_embeddings(self):
744
+ return self.head
745
+
746
+ def set_output_embeddings(self, new_embeddings):
747
+ self.head = new_embeddings
748
+
749
+ def prepare_inputs_for_generation(self, input_ids, state=None, inputs_embeds=None, **kwargs):
750
+ # only last token for inputs_ids if the state is passed along.
751
+ if state is not None:
752
+ input_ids = input_ids[:, -1].unsqueeze(-1)
753
+
754
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
755
+ if inputs_embeds is not None and state is None:
756
+ model_inputs = {"inputs_embeds": inputs_embeds}
757
+ else:
758
+ model_inputs = {"input_ids": input_ids}
759
+
760
+ model_inputs["state"] = state
761
+ return model_inputs
762
+
763
+ @add_start_docstrings_to_model_forward(RWKV6_INPUTS_DOCSTRING)
764
+ @add_code_sample_docstrings(
765
+ checkpoint=_CHECKPOINT_FOR_DOC,
766
+ output_type=Rwkv6CausalLMOutput,
767
+ config_class=_CONFIG_FOR_DOC,
768
+ )
769
+ def forward(
770
+ self,
771
+ input_ids: Optional[torch.LongTensor] = None,
772
+ attention_mask: Optional[torch.LongTensor] = None,
773
+ inputs_embeds: Optional[torch.FloatTensor] = None,
774
+ state: Optional[List[torch.FloatTensor]] = None,
775
+ labels: Optional[torch.LongTensor] = None,
776
+ use_cache: Optional[bool] = None,
777
+ output_attentions: Optional[bool] = None,
778
+ output_hidden_states: Optional[bool] = None,
779
+ return_dict: Optional[bool] = None,
780
+ ) -> Union[Tuple, Rwkv6CausalLMOutput]:
781
+ r"""
782
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
783
+ Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
784
+ `labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
785
+ are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
786
+ """
787
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
788
+
789
+ outputs = self.rwkv(
790
+ input_ids,
791
+ inputs_embeds=inputs_embeds,
792
+ state=state,
793
+ use_cache=use_cache,
794
+ output_attentions=output_attentions,
795
+ output_hidden_states=output_hidden_states,
796
+ return_dict=return_dict,
797
+ )
798
+ hidden_states = outputs[0]
799
+
800
+ logits = self.head(hidden_states)
801
+
802
+ loss = None
803
+ if labels is not None:
804
+ # move labels to correct device to enable model parallelism
805
+ labels = labels.to(logits.device)
806
+ # Shift so that tokens < n predict n
807
+ shift_logits = logits[..., :-1, :].contiguous()
808
+ shift_labels = labels[..., 1:].contiguous()
809
+ # Flatten the tokens
810
+ loss_fct = CrossEntropyLoss()
811
+ loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
812
+
813
+ if not return_dict:
814
+ output = (logits,) + outputs[1:]
815
+ return ((loss,) + output) if loss is not None else output
816
+
817
+ return Rwkv6CausalLMOutput(
818
+ loss=loss,
819
+ logits=logits,
820
+ state=outputs.state,
821
+ hidden_states=outputs.hidden_states,
822
+ attentions=outputs.attentions,
823
+ )
pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:61fb002953dfb130ce86676978d5fdf6c8cba046cc7426b5f0ccaa5734caaa27
3
+ size 3199827070
rwkv_vocab_v20230424.txt ADDED
The diff for this file is too large to render. See raw diff
 
special_tokens_map.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {}
tokenization_rwkv_world.py ADDED
@@ -0,0 +1,549 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2018 The Open AI Team Authors and 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 json
18
+ import os
19
+ from typing import TYPE_CHECKING, List, Optional, Tuple, Union
20
+
21
+ from transformers.tokenization_utils import PreTrainedTokenizer
22
+ from transformers.tokenization_utils_base import (
23
+ BatchEncoding,
24
+ EncodedInput,
25
+ TextInput,
26
+ TruncationStrategy,
27
+ )
28
+ from transformers.utils import PaddingStrategy, TensorType, logging, to_py_obj
29
+
30
+
31
+ if TYPE_CHECKING:
32
+ from transformers.pipelines.conversational import Conversation
33
+
34
+ logger = logging.get_logger(__name__)
35
+
36
+ VOCAB_FILES_NAMES = {
37
+ "vocab_file": "rwkv_vocab_v20230424.txt",
38
+ }
39
+ PRETRAINED_VOCAB_FILES_MAP = {
40
+ "vocab_file": {
41
+ "RWKV/rwkv-5-world-169m": "https://huggingface.co/RWKV/rwkv-5-world-169m/blob/main/rwkv_vocab_v20230424.txt",
42
+ },
43
+ }
44
+
45
+
46
+ class TRIE:
47
+ __slots__ = tuple("ch,to,values,front".split(","))
48
+ to: list
49
+ values: set
50
+
51
+ def __init__(self, front=None, ch=None):
52
+ self.ch = ch
53
+ self.to = [None for ch in range(256)]
54
+ self.values = set()
55
+ self.front = front
56
+
57
+ def __repr__(self):
58
+ fr = self
59
+ ret = []
60
+ while fr is not None:
61
+ if fr.ch is not None:
62
+ ret.append(fr.ch)
63
+ fr = fr.front
64
+ return "<TRIE %s %s>" % (ret[::-1], self.values)
65
+
66
+ def add(self, key: bytes, idx: int = 0, val=None):
67
+ if idx == len(key):
68
+ if val is None:
69
+ val = key
70
+ self.values.add(val)
71
+ return self
72
+ ch = key[idx]
73
+ if self.to[ch] is None:
74
+ self.to[ch] = TRIE(front=self, ch=ch)
75
+ return self.to[ch].add(key, idx=idx + 1, val=val)
76
+
77
+ def find_longest(self, key: bytes, idx: int = 0):
78
+ u: TRIE = self
79
+ ch: int = key[idx]
80
+
81
+ while u.to[ch] is not None:
82
+ u = u.to[ch]
83
+ idx += 1
84
+ if u.values:
85
+ ret = idx, u, u.values
86
+ if idx == len(key):
87
+ break
88
+ ch = key[idx]
89
+ return ret
90
+
91
+
92
+ class RWKVWorldTokenizer(PreTrainedTokenizer):
93
+ vocab_files_names = VOCAB_FILES_NAMES
94
+ model_input_names = ["input_ids", "attention_mask"]
95
+
96
+ def __init__(self, vocab_file, errors="replace", pad_token="0", **kwargs):
97
+ self.add_bos_token = False
98
+ self.encoder = {}
99
+ sorted = [] # must be already sorted
100
+ with open(vocab_file, "r", encoding="utf-8") as f:
101
+ lines = f.readlines()
102
+ for l in lines:
103
+ idx = int(l[: l.index(" ")])
104
+ x = eval(l[l.index(" ") : l.rindex(" ")])
105
+ x = x.encode("utf-8") if isinstance(x, str) else x
106
+ assert isinstance(x, bytes)
107
+ assert len(x) == int(l[l.rindex(" ") :])
108
+ sorted += [x]
109
+ self.encoder[idx] = x
110
+
111
+ self.decoder = {}
112
+ for k, v in self.encoder.items():
113
+ self.decoder[v] = int(k)
114
+
115
+ self.trie = TRIE()
116
+ for t, i in self.decoder.items():
117
+ _ = self.trie.add(t, val=(t, i))
118
+ self.errors = errors # how to handle errors in decoding
119
+ self.cache = {}
120
+ self.first_max_length = 0
121
+ super().__init__(
122
+ errors=errors,
123
+ **kwargs,
124
+ )
125
+
126
+ @property
127
+ def eos_token_id(self) -> Optional[int]:
128
+ return 0
129
+
130
+ @property
131
+ def eot_token_id(self) -> Optional[int]:
132
+ return 0
133
+
134
+ @property
135
+ def pad_token_id(self) -> Optional[int]:
136
+ return 0
137
+
138
+ @property
139
+ def vocab_size(self):
140
+ return len(self.encoder)
141
+
142
+ def get_vocab(self):
143
+ return dict(self.encoder, **self.added_tokens_encoder)
144
+
145
+ def add_tokens(self, new_tokens, special_tokens: bool = False):
146
+ for token in new_tokens:
147
+ token_id = self.convert_tokens_to_ids(token)
148
+ self.added_tokens_decoder[token_id] = token
149
+
150
+ def convert_ids_to_tokens(self, ids, skip_special_tokens=False):
151
+ if isinstance(ids, int):
152
+ ids = [ids]
153
+ tokens = []
154
+ for id_ in ids:
155
+ if id_ in self.added_tokens_decoder:
156
+ tokens.append(self.added_tokens_decoder[id_])
157
+ else:
158
+ tokens.append(self._convert_id_to_token(id_))
159
+ return tokens
160
+
161
+ def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
162
+ if self.add_bos_token:
163
+ bos_token_ids = [self.bos_token_id]
164
+ else:
165
+ bos_token_ids = []
166
+
167
+ output = bos_token_ids + token_ids_0
168
+
169
+ if token_ids_1 is None:
170
+ return output
171
+
172
+ return output + bos_token_ids + token_ids_1
173
+
174
+ def get_special_tokens_mask(
175
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
176
+ ) -> List[int]:
177
+ """
178
+ Retrieves sequence ids from a token list that has no special tokens added. This method is called when adding
179
+ special tokens using the tokenizer `prepare_for_model` or `encode_plus` methods.
180
+
181
+ Args:
182
+ token_ids_0 (`List[int]`):
183
+ List of IDs.
184
+ token_ids_1 (`List[int]`, *optional*):
185
+ Optional second list of IDs for sequence pairs.
186
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
187
+ Whether or not the token list is already formatted with special tokens for the model.
188
+
189
+ Returns:
190
+ `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
191
+ """
192
+ if already_has_special_tokens:
193
+ return super().get_special_tokens_mask(
194
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
195
+ )
196
+
197
+ if not self.add_bos_token:
198
+ return super().get_special_tokens_mask(
199
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=False
200
+ )
201
+
202
+ if token_ids_1 is None:
203
+ return [1] + ([0] * len(token_ids_0))
204
+ return [1] + ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1))
205
+
206
+ def encodeBytes(self, src: bytes):
207
+ idx: int = 0
208
+ tokens = []
209
+ while idx < len(src):
210
+ _idx: int = idx
211
+ idx, _, values = self.trie.find_longest(src, idx)
212
+ assert idx != _idx
213
+ _, token = next(iter(values))
214
+ tokens.append(token)
215
+ return tokens
216
+
217
+ def decodeBytes(self, tokens):
218
+ return b"".join(map(lambda i: self.encoder[i], tokens)) # noqa
219
+
220
+ def _tokenize(self, text, **kwargs):
221
+ """Tokenize a string."""
222
+ return self.encodeBytes(text.encode("utf-8"))
223
+
224
+ def _decode_tokens(self, tokens):
225
+ try:
226
+ return self.decodeBytes(tokens).decode("utf-8")
227
+ except Exception:
228
+ return "\ufffd" # bad utf-8
229
+
230
+ def _decode(
231
+ self,
232
+ token_ids: Union[int, List[int]],
233
+ skip_special_tokens: bool = False,
234
+ **kwargs,
235
+ ) -> str:
236
+ def remove_zeros_from_first_segment(token_ids, first_max_length):
237
+ first_segment = token_ids[:first_max_length]
238
+ first_segment_cleaned = [token for token in first_segment if token != 0]
239
+ return first_segment_cleaned + token_ids[first_max_length:]
240
+
241
+ # Convert inputs to python lists
242
+ token_ids = to_py_obj(token_ids)
243
+ token_ids = remove_zeros_from_first_segment(token_ids, self.first_max_length)
244
+ if isinstance(token_ids, int):
245
+ if token_ids in self.all_special_ids and skip_special_tokens:
246
+ return ""
247
+ return self.encoder.get(token_ids, self.unk_token)
248
+ elif isinstance(token_ids, list):
249
+ self.first_max_length
250
+ out_str = ""
251
+ out_last = 0
252
+ out_tokens = []
253
+ for i, token in enumerate(token_ids):
254
+ if token == 0:
255
+ break
256
+ out_tokens += [token]
257
+ tmp = self._decode_tokens(out_tokens[out_last:])
258
+ if "\ufffd" not in tmp:
259
+ out_str += tmp
260
+ out_last = i + 1
261
+ return out_str
262
+ else:
263
+ return token_ids
264
+
265
+ def _convert_token_to_id(self, token):
266
+ """Converts a token (str) in an id using the vocab."""
267
+ return self.decoder.get(token.encode("utf-8"), self.unk_token_id)
268
+
269
+ def _convert_id_to_token(self, index):
270
+ """Converts an index (integer) in a token (str) using the vocab."""
271
+ return self.encoder.get(index)
272
+
273
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
274
+ if not os.path.exists(save_directory):
275
+ os.mkdir(save_directory)
276
+ if not os.path.isdir(save_directory):
277
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
278
+ return
279
+ vocab_file = os.path.join(
280
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
281
+ )
282
+
283
+ with open(vocab_file, "w", encoding="utf-8") as f:
284
+ for idx, x in self.encoder.items():
285
+ if isinstance(x, str):
286
+ x = x.decode("utf-8")
287
+ line = f"{idx} {repr(x)} {len(x)}\n"
288
+ f.write(line)
289
+
290
+ return (vocab_file,)
291
+
292
+ def prepare_for_tokenization(self, text, **kwargs):
293
+ return (text, kwargs)
294
+
295
+ def _get_padding_truncation_strategies(
296
+ self, padding=False, truncation=None, max_length=None, pad_to_multiple_of=None, verbose=True, **kwargs
297
+ ):
298
+ return PaddingStrategy.LONGEST, TruncationStrategy.DO_NOT_TRUNCATE, -1, kwargs
299
+
300
+ def _encode_plus(
301
+ self,
302
+ text: Union[TextInput, EncodedInput],
303
+ add_special_tokens: bool = True,
304
+ padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
305
+ truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
306
+ max_length: Optional[int] = None,
307
+ stride: int = 0,
308
+ pad_to_multiple_of: Optional[int] = None,
309
+ return_tensors: Optional[Union[str, TensorType]] = None,
310
+ return_token_type_ids: Optional[bool] = None,
311
+ return_attention_mask: Optional[bool] = None,
312
+ return_overflowing_tokens: bool = False,
313
+ return_special_tokens_mask: bool = False,
314
+ return_offsets_mapping: bool = False,
315
+ return_length: bool = False,
316
+ verbose: bool = True,
317
+ **kwargs,
318
+ ) -> BatchEncoding:
319
+ def get_input_ids(text, max_length=None, pad_token_id=0):
320
+ def pad_sequence(seq, max_len, pad_tok):
321
+ return [pad_tok] * (max_len - len(seq)) + seq
322
+
323
+ if isinstance(text, str):
324
+ tokens = self._tokenize(text)
325
+ if max_length is not None:
326
+ tokens = pad_sequence(tokens, max_length, pad_token_id)
327
+ return tokens
328
+
329
+ elif isinstance(text, list) and len(text) > 0 and isinstance(text[0], str):
330
+ tokenized_texts = [self._tokenize(t) for t in text]
331
+ if max_length is None:
332
+ max_length = max(len(t) for t in tokenized_texts)
333
+ return [pad_sequence(t, max_length, pad_token_id) for t in tokenized_texts]
334
+
335
+ elif isinstance(text, (list, tuple)) and len(text) > 0 and isinstance(text[0], int):
336
+ if max_length is not None and len(text) < max_length:
337
+ return pad_sequence(text, max_length, pad_token_id)
338
+ return text
339
+
340
+ else:
341
+ raise ValueError(
342
+ "Input is not valid. Should be a string, a list/tuple of strings or a list/tuple of integers."
343
+ )
344
+
345
+ if return_offsets_mapping:
346
+ raise NotImplementedError(
347
+ "return_offset_mapping is not available when using Python tokenizers. "
348
+ "To use this feature, change your tokenizer to one deriving from "
349
+ "transformers.PreTrainedTokenizerFast. "
350
+ "More information on available tokenizers at "
351
+ "https://github.com/huggingface/transformers/pull/2674"
352
+ )
353
+
354
+ first_ids = get_input_ids(text)
355
+
356
+ return self.prepare_for_model(
357
+ first_ids,
358
+ pair_ids=None,
359
+ add_special_tokens=add_special_tokens,
360
+ padding=padding_strategy.value,
361
+ truncation=truncation_strategy.value,
362
+ max_length=max_length,
363
+ stride=stride,
364
+ pad_to_multiple_of=pad_to_multiple_of,
365
+ return_tensors=return_tensors,
366
+ prepend_batch_axis=True,
367
+ return_attention_mask=return_attention_mask,
368
+ return_token_type_ids=return_token_type_ids,
369
+ return_overflowing_tokens=return_overflowing_tokens,
370
+ return_special_tokens_mask=return_special_tokens_mask,
371
+ return_length=return_length,
372
+ verbose=verbose,
373
+ )
374
+
375
+ def _batch_encode_plus(
376
+ self,
377
+ batch_text_or_text_pairs: Union[
378
+ List[TextInput],
379
+ List[EncodedInput],
380
+ ],
381
+ add_special_tokens: bool = True,
382
+ padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
383
+ truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
384
+ max_length: Optional[int] = None,
385
+ stride: int = 0,
386
+ pad_to_multiple_of: Optional[int] = None,
387
+ return_tensors: Optional[Union[str, TensorType]] = None,
388
+ return_token_type_ids: Optional[bool] = None,
389
+ return_attention_mask: Optional[bool] = None,
390
+ return_overflowing_tokens: bool = False,
391
+ return_special_tokens_mask: bool = False,
392
+ return_offsets_mapping: bool = False,
393
+ return_length: bool = False,
394
+ verbose: bool = True,
395
+ **kwargs,
396
+ ) -> BatchEncoding:
397
+ def get_input_ids(text, max_length=None, pad_token_id=0):
398
+ def pad_sequence(seq, max_len, pad_tok):
399
+ return [pad_tok] * (max_len - len(seq)) + seq
400
+
401
+ if isinstance(text, str):
402
+ tokens = self._tokenize(text)
403
+ if max_length is not None:
404
+ tokens = pad_sequence(tokens, max_length, pad_token_id)
405
+ return tokens
406
+
407
+ elif isinstance(text, list) and len(text) > 0 and isinstance(text[0], str):
408
+ tokenized_texts = [self._tokenize(t) for t in text]
409
+ if max_length is None:
410
+ max_length = max(len(t) for t in tokenized_texts)
411
+ return [pad_sequence(t, max_length, pad_token_id) for t in tokenized_texts]
412
+
413
+ elif isinstance(text, (list, tuple)) and len(text) > 0 and isinstance(text[0], int):
414
+ if max_length is not None and len(text) < max_length:
415
+ return pad_sequence(text, max_length, pad_token_id)
416
+ return text
417
+
418
+ else:
419
+ raise ValueError(
420
+ "Input is not valid. Should be a string, a list/tuple of strings or a list/tuple of integers."
421
+ )
422
+
423
+ if return_offsets_mapping:
424
+ raise NotImplementedError(
425
+ "return_offset_mapping is not available when using Python tokenizers. "
426
+ "To use this feature, change your tokenizer to one deriving from "
427
+ "transformers.PreTrainedTokenizerFast."
428
+ )
429
+
430
+ first_max_length = 0
431
+ second_max_length = 0
432
+ for ids_or_pair_ids in batch_text_or_text_pairs:
433
+ if not isinstance(ids_or_pair_ids, (list, tuple)):
434
+ ids, pair_ids = ids_or_pair_ids, None
435
+ else:
436
+ ids, pair_ids = ids_or_pair_ids
437
+ first_ids = get_input_ids(ids)
438
+ second_ids = get_input_ids(pair_ids) if pair_ids is not None else None
439
+ first_max_length = max(first_max_length, len(first_ids))
440
+ if second_ids is not None:
441
+ second_max_length = max(second_max_length, len(second_ids))
442
+
443
+ self.first_max_length = first_max_length
444
+ input_ids = []
445
+ for ids_or_pair_ids in batch_text_or_text_pairs:
446
+ if not isinstance(ids_or_pair_ids, (list, tuple)):
447
+ ids, pair_ids = ids_or_pair_ids, None
448
+ else:
449
+ ids, pair_ids = ids_or_pair_ids
450
+
451
+ first_ids = get_input_ids(ids, max_length=first_max_length)
452
+ second_ids = get_input_ids(pair_ids, max_length=second_max_length) if pair_ids is not None else None
453
+ input_ids.append((first_ids, second_ids))
454
+
455
+ batch_outputs = self._batch_prepare_for_model(
456
+ input_ids,
457
+ add_special_tokens=add_special_tokens,
458
+ padding_strategy=padding_strategy,
459
+ truncation_strategy=truncation_strategy,
460
+ max_length=max_length,
461
+ stride=stride,
462
+ pad_to_multiple_of=pad_to_multiple_of,
463
+ return_attention_mask=return_attention_mask,
464
+ return_token_type_ids=return_token_type_ids,
465
+ return_overflowing_tokens=return_overflowing_tokens,
466
+ return_special_tokens_mask=return_special_tokens_mask,
467
+ return_length=return_length,
468
+ return_tensors=return_tensors,
469
+ verbose=verbose,
470
+ )
471
+
472
+ return BatchEncoding(batch_outputs)
473
+
474
+ def decode(
475
+ self,
476
+ token_ids: Union[int, List[int]],
477
+ skip_special_tokens: bool = False,
478
+ clean_up_tokenization_spaces: bool = None,
479
+ **kwargs,
480
+ ) -> str:
481
+ """
482
+ Converts a sequence of ids in a string, using the tokenizer and vocabulary with options to remove special
483
+ tokens and clean up tokenization spaces.
484
+
485
+ Similar to doing `self.convert_tokens_to_string(self.convert_ids_to_tokens(token_ids))`.
486
+
487
+ Args:
488
+ token_ids (`Union[int, List[int], np.ndarray, torch.Tensor, tf.Tensor]`):
489
+ List of tokenized input ids. Can be obtained using the `__call__` method.
490
+ skip_special_tokens (`bool`, *optional*, defaults to `False`):
491
+ Whether or not to remove special tokens in the decoding.
492
+ clean_up_tokenization_spaces (`bool`, *optional*):
493
+ Whether or not to clean up the tokenization spaces. If `None`, will default to
494
+ `self.clean_up_tokenization_spaces`.
495
+ kwargs (additional keyword arguments, *optional*):
496
+ Will be passed to the underlying model specific decode method.
497
+
498
+ Returns:
499
+ `str`: The decoded sentence.
500
+ """
501
+ # Convert inputs to python lists
502
+ return self._decode(
503
+ token_ids=token_ids,
504
+ skip_special_tokens=skip_special_tokens,
505
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
506
+ **kwargs,
507
+ )
508
+
509
+ def batch_decode(
510
+ self,
511
+ sequences: Union[List[int], List[List[int]]],
512
+ skip_special_tokens: bool = False,
513
+ clean_up_tokenization_spaces: bool = None,
514
+ **kwargs,
515
+ ) -> List[str]:
516
+ """
517
+ Convert a list of lists of token ids into a list of strings by calling decode.
518
+
519
+ Args:
520
+ sequences (`Union[List[int], List[List[int]], np.ndarray, torch.Tensor, tf.Tensor]`):
521
+ List of tokenized input ids. Can be obtained using the `__call__` method.
522
+ skip_special_tokens (`bool`, *optional*, defaults to `False`):
523
+ Whether or not to remove special tokens in the decoding.
524
+ clean_up_tokenization_spaces (`bool`, *optional*):
525
+ Whether or not to clean up the tokenization spaces. If `None`, will default to
526
+ `self.clean_up_tokenization_spaces`.
527
+ kwargs (additional keyword arguments, *optional*):
528
+ Will be passed to the underlying model specific decode method.
529
+
530
+ Returns:
531
+ `List[str]`: The list of decoded sentences.
532
+ """
533
+ return [
534
+ self.decode(
535
+ seq,
536
+ skip_special_tokens=skip_special_tokens,
537
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
538
+ **kwargs,
539
+ )
540
+ for seq in sequences
541
+ ]
542
+
543
+ def _build_conversation_input_ids(self, conversation: "Conversation") -> List[int]:
544
+ input_ids = []
545
+ for is_user, text in conversation.iter_texts():
546
+ input_ids.extend(self.encode(text, add_special_tokens=False) + [self.eos_token_id])
547
+ if len(input_ids) > self.model_max_length:
548
+ input_ids = input_ids[-self.model_max_length :]
549
+ return input_ids
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +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
+ }