SmerkyG commited on
Commit
2d157bd
1 Parent(s): 2347724

Upload folder using huggingface_hub

Browse files
config.json ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "attention_hidden_size": 2560,
3
+ "bos_token_id": 0,
4
+ "eos_token_id": 0,
5
+ "head_size": 64,
6
+ "head_size_divisor": 8,
7
+ "hidden_size": 2560,
8
+ "intermediate_size": null,
9
+ "layer_norm_epsilon": 1e-05,
10
+ "max_context_length": 4096,
11
+ "model_type": "rwkv6",
12
+ "num_attention_heads": 64,
13
+ "num_hidden_layers": 32,
14
+ "rescale_every": 6,
15
+ "tie_word_embeddings": false,
16
+ "transformers_version": "4.37.2",
17
+ "use_cache": true,
18
+ "vocab_size": 65536
19
+ }
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
special_tokens_map.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {}
tokenization_rwkv5.py ADDED
@@ -0,0 +1,230 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from typing import TYPE_CHECKING, List, Optional, Tuple
19
+ import re
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
+
41
+ def whitespace_tokenize(text):
42
+ """Runs basic whitespace cleaning and splitting on a piece of text.
43
+ The separators are kept
44
+ """
45
+ text = text.strip()
46
+ if not text:
47
+ return []
48
+ tokens = re.split(b"(?= )", text)
49
+ return tokens
50
+
51
+
52
+ class WordpieceTokenizer(object):
53
+ """Runs WordPiece tokenization."""
54
+
55
+ def __init__(self, vocab, unk_token, max_input_chars_per_word=100):
56
+ self.vocab = vocab
57
+ self.unk_token = unk_token
58
+ self.max_input_chars_per_word = max_input_chars_per_word
59
+
60
+ def tokenize(self, text):
61
+ """
62
+ Tokenizes a piece of text into its word pieces. This uses a greedy longest-match-first algorithm to perform
63
+ tokenization using the given vocabulary.
64
+
65
+ For example, `input = "unaffable"` wil return as output `["un", "##aff", "##able"]`.
66
+
67
+ Args:
68
+ text: A single token or whitespace separated tokens. This should have
69
+ already been passed through *BasicTokenizer*.
70
+
71
+ Returns:
72
+ A list of wordpiece tokens.
73
+ """
74
+
75
+ output_tokens = []
76
+ for token in whitespace_tokenize(text):
77
+ chars = list(token)
78
+ if len(chars) > self.max_input_chars_per_word:
79
+ output_tokens.append(self.unk_token)
80
+ continue
81
+
82
+ is_bad = False
83
+ start = 0
84
+ sub_tokens = []
85
+ while start < len(chars):
86
+ end = len(chars)
87
+ cur_substr = None
88
+ while start < end:
89
+ substr = bytes(chars[start:end])
90
+ if substr in self.vocab:
91
+ cur_substr = substr
92
+ break
93
+ end -= 1
94
+ if cur_substr is None:
95
+ is_bad = True
96
+ break
97
+ sub_tokens.append(cur_substr.decode())
98
+ start = end
99
+
100
+ if is_bad:
101
+ output_tokens.append(self.unk_token)
102
+ else:
103
+ output_tokens.extend(sub_tokens)
104
+ return output_tokens
105
+
106
+
107
+ class Rwkv5Tokenizer(PreTrainedTokenizer):
108
+ vocab_files_names = VOCAB_FILES_NAMES
109
+ pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
110
+ max_model_input_sizes = {"ArthurZ/rwkv-5-utf": 2048}
111
+
112
+ model_input_names = ["input_ids", "attention_mask"]
113
+
114
+ def __init__(self, vocab_file, bos_token="<s>", eos_token="<s>", unk_token="<s>", pad_token="<s>",**kwargs):
115
+ if not os.path.isfile(vocab_file):
116
+ raise ValueError(
117
+ f"Can't find a vocabulary file at path '{vocab_file}'. To load the vocabulary from a Google pretrained"
118
+ " model use `tokenizer = BertTokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`"
119
+ )
120
+
121
+ with open(vocab_file, "r") as reader:
122
+ tokens = reader.readlines()
123
+ vocab = {}
124
+ for index, token in enumerate(tokens):
125
+ token = eval(token.rstrip("\n"))
126
+ vocab[token] = index
127
+
128
+ self.add_bos_token = True
129
+ self.encoder = vocab
130
+ self.decoder = {v: k for k, v in vocab.items()}
131
+ self.wordpiece_tokenizer = WordpieceTokenizer(vocab=self.encoder, unk_token=str(unk_token))
132
+ self._added_tokens_decoder = {0: AddedToken(str(bos_token))}
133
+ super().__init__(bos_token=bos_token, eos_token=eos_token, unk_token=unk_token, pad_token=pad_token, **kwargs)
134
+
135
+ @property
136
+ def vocab_size(self):
137
+ return len(self.encoder)
138
+
139
+ def get_vocab(self):
140
+ vocab = {str(self.convert_ids_to_tokens(i)): i for i in range(self.vocab_size)}
141
+ vocab.update(self.added_tokens_encoder)
142
+ return vocab
143
+
144
+ def _tokenize(self, text, split_special_tokens=False):
145
+ return self.wordpiece_tokenizer.tokenize(text.encode("utf-8"))
146
+
147
+ def _convert_token_to_id(self, token):
148
+ """Converts a token (byte) to an id using the vocab."""
149
+ if not isinstance(token, bytes):
150
+ token = token.encode("utf-8", errors="replace")
151
+ return self.encoder.get(token, self.unk_token_id)
152
+
153
+ def _convert_id_to_token(self, index):
154
+ """Converts an index (integer) in a token (byte) using the vocab."""
155
+ token = self.decoder.get(index, self.unk_token)
156
+ if isinstance(token, (bytes)):
157
+ token = token.decode("utf-8", errors="replace")
158
+ return token
159
+
160
+ def convert_tokens_to_string(self, tokens):
161
+ """Converts a sequence of tokens (bytes) in a single string. Additional tokens are encoded to bytes"""
162
+ out_string = b"".join([k.encode(errors="replace") if isinstance(k, str) else k for k in tokens]).decode(
163
+ "utf-8"
164
+ )
165
+ return out_string
166
+
167
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
168
+ index = 0
169
+ if os.path.isdir(save_directory):
170
+ vocab_file = os.path.join(
171
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
172
+ )
173
+ else:
174
+ vocab_file = (filename_prefix + "-" if filename_prefix else "") + save_directory
175
+ with open(vocab_file, "w") as writer:
176
+ for token, token_index in sorted(self.encoder.items(), key=lambda kv: kv[1]):
177
+ if index != token_index:
178
+ logger.warning(
179
+ f"Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive."
180
+ " Please check that the vocabulary is not corrupted!"
181
+ )
182
+ index = token_index
183
+ writer.write(str(token) + "\n")
184
+ index += 1
185
+ return (vocab_file,)
186
+
187
+ def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
188
+ if self.add_bos_token:
189
+ bos_token_ids = [self.bos_token_id]
190
+ else:
191
+ bos_token_ids = []
192
+
193
+ output = bos_token_ids + token_ids_0
194
+
195
+ if token_ids_1 is None:
196
+ return output
197
+
198
+ return output + bos_token_ids + token_ids_1
199
+
200
+ def get_special_tokens_mask(
201
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
202
+ ) -> List[int]:
203
+ """
204
+ Retrieves sequence ids from a token list that has no special tokens added. This method is called when adding
205
+ special tokens using the tokenizer `prepare_for_model` or `encode_plus` methods.
206
+
207
+ Args:
208
+ token_ids_0 (`List[int]`):
209
+ List of IDs.
210
+ token_ids_1 (`List[int]`, *optional*):
211
+ Optional second list of IDs for sequence pairs.
212
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
213
+ Whether or not the token list is already formatted with special tokens for the model.
214
+
215
+ Returns:
216
+ `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
217
+ """
218
+ if already_has_special_tokens:
219
+ return super().get_special_tokens_mask(
220
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
221
+ )
222
+
223
+ if not self.add_bos_token:
224
+ return super().get_special_tokens_mask(
225
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=False
226
+ )
227
+
228
+ if token_ids_1 is None:
229
+ return [1] + ([0] * len(token_ids_0))
230
+ return [1] + ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1))
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
+ }
vocab.txt ADDED
The diff for this file is too large to render. See raw diff