zhiyuan8 commited on
Commit
a454ffd
·
verified ·
1 Parent(s): 32fbf18

Add files using upload-large-folder tool

Browse files
README.md ADDED
@@ -0,0 +1,208 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ ---
4
+ ### Huggingface RWKV v6 7B Model
5
+
6
+ > HF compatible model for v6-7B.
7
+
8
+ ![v6 Bird](./imgs/v6.jpg)
9
+
10
+
11
+ > **! Important Note !**
12
+ >
13
+ > The following is the HF transformers implementation of the v6 7B model. This is meant to be used with the huggingface transformers
14
+ >
15
+ >
16
+
17
+
18
+ ## Quickstart with the hugging face transformer library
19
+
20
+ ```
21
+ model = AutoModelForCausalLM.from_pretrained("zhiyuan8/RWKV-v6-7B-World-v3-GGUF", trust_remote_code=True).to(torch.float32)
22
+ tokenizer = AutoTokenizer.from_pretrained("zhiyuan8/RWKV-v6-7B-World-v3-GGUF", trust_remote_code=True)
23
+ ```
24
+
25
+
26
+ #### Running on CPU via HF transformers
27
+
28
+ ```python
29
+ import torch
30
+ from transformers import AutoModelForCausalLM, AutoTokenizer
31
+
32
+ def generate_prompt(instruction, input=""):
33
+ instruction = instruction.strip().replace('\r\n','\n').replace('\n\n','\n')
34
+ input = input.strip().replace('\r\n','\n').replace('\n\n','\n')
35
+ if input:
36
+ return f"""Instruction: {instruction}
37
+
38
+ Input: {input}
39
+
40
+ Response:"""
41
+ else:
42
+ return f"""User: hi
43
+
44
+ Assistant: Hi. I am your assistant and I will provide expert full response in full details. Please feel free to ask any question and I will always answer it.
45
+
46
+ User: {instruction}
47
+
48
+ Assistant:"""
49
+
50
+
51
+ model = AutoModelForCausalLM.from_pretrained("zhiyuan8/RWKV-v6-7B-World-v3-GGUF", trust_remote_code=True).to(torch.float32)
52
+ tokenizer = AutoTokenizer.from_pretrained("zhiyuan8/RWKV-v6-7B-World-v3-HF", trust_remote_code=True)
53
+
54
+ text = "请介绍北京的旅游景点"
55
+ prompt = generate_prompt(text)
56
+
57
+ inputs = tokenizer(prompt, return_tensors="pt")
58
+ output = model.generate(inputs["input_ids"], max_new_tokens=333, do_sample=True, temperature=1.0, top_p=0.3, top_k=0, )
59
+ print(tokenizer.decode(output[0].tolist(), skip_special_tokens=True))
60
+ ```
61
+
62
+ output:
63
+
64
+ ```shell
65
+ User: hi
66
+
67
+ Assistant: Hi. I am your assistant and I will provide expert full response in full details. Please feel free to ask any question and I will always answer it.
68
+
69
+ User: 请介绍北京的旅游景点
70
+
71
+ Assistant: 北京是中国的首都,拥有众多的旅游景点,以下是其中一些著名的景点:
72
+ 1. 故宫:位于北京市中心,是明清两代的皇宫,内有大量的文物和艺术品。
73
+ 2. 天安门广场:是中国最著名的广场之一,是中国人民政治协商会议的旧址,也是中国人民政治协商会议的中心。
74
+ 3. 颐和园:是中国古代皇家园林之一,有着悠久的历史和丰富的文化内涵。
75
+ 4. 长城:是中国古代的一道长城,全长约万里,是中国最著名的旅游景点之一。
76
+ 5. 北京大学:是中国著名的高等教育机构之一,有着悠久的历史和丰富的文化内涵。
77
+ 6. 北京动物园:是中国最大的动物园之一,有着丰富的动物资源和丰富的文化内涵。
78
+ 7. 故宫博物院:是中国最著名的博物馆之一,收藏了大量的文物和艺术品,是中国最重要的文化遗产之一。
79
+ 8. 天坛:是中国古代皇家
80
+ ```
81
+
82
+ #### Running on GPU via HF transformers
83
+
84
+ ```python
85
+ import torch
86
+ from transformers import AutoModelForCausalLM, AutoTokenizer
87
+
88
+ def generate_prompt(instruction, input=""):
89
+ instruction = instruction.strip().replace('\r\n','\n').replace('\n\n','\n')
90
+ input = input.strip().replace('\r\n','\n').replace('\n\n','\n')
91
+ if input:
92
+ return f"""Instruction: {instruction}
93
+
94
+ Input: {input}
95
+
96
+ Response:"""
97
+ else:
98
+ return f"""User: hi
99
+
100
+ Assistant: Hi. I am your assistant and I will provide expert full response in full details. Please feel free to ask any question and I will always answer it.
101
+
102
+ User: {instruction}
103
+
104
+ Assistant:"""
105
+
106
+
107
+ model = AutoModelForCausalLM.from_pretrained("zhiyuan8/RWKV-v6-7B-World-v3-HF", trust_remote_code=True, torch_dtype=torch.float16).to(0)
108
+ tokenizer = AutoTokenizer.from_pretrained("zhiyuan8/RWKV-v6-7B-World-v3-HF", trust_remote_code=True)
109
+
110
+ text = "介绍一下大熊猫"
111
+ prompt = generate_prompt(text)
112
+
113
+ inputs = tokenizer(prompt, return_tensors="pt").to(0)
114
+ output = model.generate(inputs["input_ids"], max_new_tokens=128, do_sample=True, temperature=1.0, top_p=0.3, top_k=0, )
115
+ print(tokenizer.decode(output[0].tolist(), skip_special_tokens=True))
116
+ ```
117
+
118
+ output:
119
+
120
+ ```shell
121
+ User: hi
122
+
123
+ Assistant: Hi. I am your assistant and I will provide expert full response in full details. Please feel free to ask any question and I will always answer it.
124
+
125
+ User: 介绍一下大熊猫
126
+
127
+ Assistant: 大熊猫是一种中国特有的哺乳动物,也是中国的国宝之一。它们的外貌特征是圆形的黑白相间的身体,有着黑色的毛发和白色的耳朵。大熊猫的食物主要是竹子,它们会在竹林中寻找竹子,并且会将竹子放在竹笼中进行储存。大熊猫的寿命约为20至30年,但由于栖息地的丧失和人类活动的
128
+ ```
129
+
130
+ #### Batch Inference
131
+
132
+ ```python
133
+ import torch
134
+ from transformers import AutoModelForCausalLM, AutoTokenizer
135
+
136
+ def generate_prompt(instruction, input=""):
137
+ instruction = instruction.strip().replace('\r\n', '\n').replace('\n\n', '\n')
138
+ input = input.strip().replace('\r\n', '\n').replace('\n\n', '\n')
139
+ if input:
140
+ return f"""Instruction: {instruction}
141
+
142
+ Input: {input}
143
+
144
+ Response:"""
145
+ else:
146
+ return f"""User: hi
147
+
148
+ Assistant: Hi. I am your assistant and I will provide expert full response in full details. Please feel free to ask any question and I will always answer it.
149
+
150
+ User: {instruction}
151
+
152
+ Assistant:"""
153
+
154
+ model = AutoModelForCausalLM.from_pretrained("zhiyuan8/RWKV-v6-7B-World-v3-HF", trust_remote_code=True).to(torch.float32)
155
+ tokenizer = AutoTokenizer.from_pretrained("zhiyuan8/RWKV-v6-7B-World-v3-HF", trust_remote_code=True)
156
+
157
+ texts = ["请介绍北京的旅游景点", "介绍一下大熊猫", "乌兰察布"]
158
+ prompts = [generate_prompt(text) for text in texts]
159
+
160
+ inputs = tokenizer(prompts, return_tensors="pt", padding=True)
161
+ outputs = model.generate(inputs["input_ids"], max_new_tokens=128, do_sample=True, temperature=1.0, top_p=0.3, top_k=0, )
162
+
163
+ for output in outputs:
164
+ print(tokenizer.decode(output.tolist(), skip_special_tokens=True))
165
+
166
+ ```
167
+
168
+ output:
169
+
170
+ ```shell
171
+ User: hi
172
+
173
+ Assistant: Hi. I am your assistant and I will provide expert full response in full details. Please feel free to ask any question and I will always answer it.
174
+
175
+ User: 请介绍北京的旅游景点
176
+
177
+ Assistant: 北京是中国的首都,拥有丰富的旅游资源和历史文化遗产。以下是一些北京的旅游景点:
178
+ 1. 故宫:位于北京市中心,是明清两代的皇宫,是中国最大的古代宫殿建筑群之一。
179
+ 2. 天安门广场:位于北京市中心,是中国最著名的城市广场之一,也是中国最大的城市广场。
180
+ 3. 颐和
181
+ User: hi
182
+
183
+ Assistant: Hi. I am your assistant and I will provide expert full response in full details. Please feel free to ask any question and I will always answer it.
184
+
185
+ User: 介绍一下大熊猫
186
+
187
+ Assistant: 大熊猫是一种生活在中国中部地区的哺乳动物,也是中国的国宝之一。它们的外貌特征是圆形的黑白相间的身体,有着黑色的毛发和圆圆的眼睛。大熊猫是一种濒危物种,目前只有在野外的几个保护区才能看到它们的身影。大熊猫的食物主要是竹子,它们会在竹子上寻找食物,并且可以通
188
+ User: hi
189
+
190
+ Assistant: Hi. I am your assistant and I will provide expert full response in full details. Please feel free to ask any question and I will always answer it.
191
+
192
+ User: 乌兰察布
193
+
194
+ Assistant: 乌兰察布是中国新疆维吾尔自治区的一个县级市,位于新疆维吾尔自治区中部,是新疆的第二大城市。乌兰察布市是新疆的第一大城市,也是新疆的重要城市之一。乌兰察布市是新疆的经济中心,也是新疆的重要交通枢纽之一。乌兰察布市的人口约为2.5万人,其中汉族占绝大多数。乌
195
+ ```
196
+
197
+ ## Links
198
+ - [Our wiki](https://wiki.rwkv.com)
199
+ - [Recursal.AI Cloud Platform](https://recursal.ai)
200
+ - [Featherless Inference](https://featherless.ai/models/RWKV/v6-14B)
201
+ - [Blog article, detailing our model launch](https://blog.rwkv.com/p/rwkv-v6-v6-14b-is-here)
202
+
203
+ ## Acknowledgement
204
+ We are grateful for the help and support from the following key groups:
205
+
206
+ - [Recursal.ai](https://recursal.ai) team for financing the GPU resources, and managing the training of this foundation model - you can run the v6 line of RWKV models on their cloud / on-premise platform today.
207
+ - EleutherAI for their support, especially in the v5/v6 Eagle/v6 paper
208
+ - Linux Foundation AI & Data group for supporting and hosting the RWKV project
added_tokens.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ {
2
+ "<s>": 0
3
+ }
config.json ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "Rwkv6ForCausalLM"
4
+ ],
5
+ "auto_map": {
6
+ "AutoConfig": "configuration_rwkv6.Rwkv6Config",
7
+ "AutoModelForCausalLM": "modeling_rwkv6.Rwkv6ForCausalLM"
8
+ },
9
+ "attention_hidden_size": 4096,
10
+ "bos_token_id": 0,
11
+ "eos_token_id": 0,
12
+ "head_size": 64,
13
+ "head_size_divisor": 8,
14
+ "hidden_size": 4096,
15
+ "intermediate_size": null,
16
+ "layer_norm_epsilon": 1e-05,
17
+ "model_type": "rwkv6",
18
+ "num_attention_heads": 64,
19
+ "num_hidden_layers": 32,
20
+ "rescale_every": 6,
21
+ "tie_word_embeddings": false,
22
+ "transformers_version": "4.34.0",
23
+ "use_cache": true,
24
+ "vocab_size": 65536
25
+ }
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
+ }
hf_rwkv_tokenizer.py ADDED
@@ -0,0 +1,279 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 RWKV6."""
16
+
17
+ import os
18
+ import re
19
+ from typing import TYPE_CHECKING, List, Optional, Tuple
20
+
21
+ from transformers.tokenization_utils import AddedToken, PreTrainedTokenizer
22
+ from transformers.utils import logging
23
+
24
+
25
+ if TYPE_CHECKING:
26
+ pass
27
+
28
+ logger = logging.get_logger(__name__)
29
+
30
+
31
+ VOCAB_FILES_NAMES = {
32
+ "vocab_file": "rwkv_vocab_v20230424.txt",
33
+ }
34
+
35
+ class TRIE:
36
+ __slots__ = tuple("ch,to,values,front".split(","))
37
+ to: list
38
+ values: set
39
+
40
+ def __init__(self, front=None, ch=None):
41
+ self.ch = ch
42
+ self.to = [None for ch in range(256)]
43
+ self.values = set()
44
+ self.front = front
45
+
46
+ def __repr__(self):
47
+ fr = self
48
+ ret = []
49
+ while fr != None:
50
+ if fr.ch != None:
51
+ ret.append(fr.ch)
52
+ fr = fr.front
53
+ return "<TRIE %s %s>" % (ret[::-1], self.values)
54
+
55
+ def add(self, key: bytes, idx: int = 0, val=None):
56
+ if idx == len(key):
57
+ if val is None:
58
+ val = key
59
+ self.values.add(val)
60
+ return self
61
+ ch = key[idx]
62
+ if self.to[ch] is None:
63
+ self.to[ch] = TRIE(front=self, ch=ch)
64
+ return self.to[ch].add(key, idx=idx + 1, val=val)
65
+
66
+ def find_longest(self, key: bytes, idx: int = 0):
67
+ u: TRIE = self
68
+ ch: int = key[idx]
69
+
70
+ while u.to[ch] is not None:
71
+ u = u.to[ch]
72
+ idx += 1
73
+ if u.values:
74
+ ret = idx, u, u.values
75
+ if idx == len(key):
76
+ break
77
+ ch = key[idx]
78
+ return ret
79
+
80
+
81
+ class RWKV_TOKENIZER:
82
+ def __init__(self, file_name):
83
+ self.idx2token = {}
84
+ sorted = [] # must be already sorted
85
+ with open(file_name, "r", encoding="utf-8") as f:
86
+ lines = f.readlines()
87
+ for l in lines:
88
+ idx = int(l[: l.index(" ")])
89
+ x = eval(l[l.index(" ") : l.rindex(" ")])
90
+ x = x.encode("utf-8") if isinstance(x, str) else x
91
+ assert isinstance(x, bytes)
92
+
93
+ assert len(x) == int(l[l.rindex(" ") :])
94
+ sorted += [x]
95
+ self.idx2token[idx] = x
96
+
97
+ self.token2idx = {}
98
+ for k, v in self.idx2token.items():
99
+ self.token2idx[v] = int(k)
100
+
101
+ self.root = TRIE()
102
+ for t, i in self.token2idx.items():
103
+ _ = self.root.add(t, val=(t, i))
104
+
105
+ def encodeBytes(self, src: bytes):
106
+ idx: int = 0
107
+ tokens = []
108
+ while idx < len(src):
109
+ _idx: int = idx
110
+ idx, _, values = self.root.find_longest(src, idx)
111
+ assert idx != _idx
112
+ _, token = next(iter(values))
113
+ tokens.append(token)
114
+ return tokens
115
+
116
+ def decodeBytes(self, tokens):
117
+ return b"".join(map(lambda i: self.idx2token[i], tokens))
118
+
119
+ def encode(self, src):
120
+ if isinstance(src, str):
121
+ return [self.encodeBytes(src.encode("utf-8"))]
122
+ elif isinstance(src, list):
123
+ return [self.encodeBytes(s.encode("utf-8")) for s in src]
124
+
125
+ def decode(self, tokens):
126
+ return [self.decodeBytes(batch).decode("utf-8") for batch in tokens]
127
+ # try:
128
+ # return self.decodeBytes(tokens).decode('utf-8')
129
+ # except:
130
+ # return '\ufffd' # bad utf-8
131
+
132
+ def printTokens(self, tokens):
133
+ for i in tokens:
134
+ s = self.idx2token[i]
135
+ try:
136
+ s = s.decode("utf-8")
137
+ except:
138
+ pass
139
+ print(f"{repr(s)}{i}", end=" ")
140
+ print()
141
+
142
+
143
+ class Rwkv6Tokenizer(PreTrainedTokenizer):
144
+ vocab_files_names = VOCAB_FILES_NAMES
145
+ model_input_names = ["input_ids", "attention_mask"]
146
+
147
+ def __init__(
148
+ self, vocab_file, bos_token="<s>", eos_token="<s>", unk_token="<s>", **kwargs
149
+ ):
150
+ if not os.path.isfile(vocab_file):
151
+ raise ValueError(
152
+ f"Can't find a vocabulary file at path '{vocab_file}'. To load the vocabulary from a Google pretrained"
153
+ " model use `tokenizer = BertTokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`"
154
+ )
155
+
156
+ with open(vocab_file, "r", encoding="utf-8") as reader:
157
+ tokens = reader.readlines()
158
+
159
+ if "add_bos_token" in kwargs:
160
+ self.add_bos_token = kwargs["add_bos_token"]
161
+ else:
162
+ self.add_bos_token = False
163
+ self.trie_tokenizer = RWKV_TOKENIZER(vocab_file)
164
+ vocab = self.trie_tokenizer.token2idx
165
+ self.encoder = vocab
166
+ self.decoder = {v: k for k, v in vocab.items()}
167
+ self._added_tokens_decoder = {0: AddedToken(str(bos_token))}
168
+ super().__init__(
169
+ bos_token=bos_token, eos_token=eos_token, unk_token=unk_token, **kwargs
170
+ )
171
+
172
+ @property
173
+ def vocab_size(self):
174
+ return len(self.encoder)
175
+
176
+ def get_vocab(self):
177
+ vocab = {str(self.convert_ids_to_tokens(i)): i for i in range(self.vocab_size)}
178
+ vocab.update(self.added_tokens_encoder)
179
+ return vocab
180
+
181
+ def _tokenize(self, text, split_special_tokens=False):
182
+ # return self.wordpiece_tokenizer.tokenize(text.encode("utf-8"))
183
+ return self.trie_tokenizer.encode(text)[0]
184
+
185
+ def _convert_token_to_id(self, token):
186
+ return token
187
+
188
+ def _convert_id_to_token(self, index):
189
+ """Converts an index (integer) in a token (byte) using the vocab."""
190
+ token = self.decoder.get(index, self.unk_token)
191
+ if isinstance(token, (bytes)):
192
+ token = token.decode("utf-8", errors="replace")
193
+ return token
194
+
195
+ def convert_tokens_to_string(self, tokens):
196
+ """Converts a sequence of tokens (bytes) in a single string. Additional tokens are encoded to bytes"""
197
+ out_string = b"".join(
198
+ [k.encode(errors="replace") if isinstance(k, str) else k for k in tokens]
199
+ ).decode("utf-8")
200
+ return out_string
201
+
202
+ def save_vocabulary(
203
+ self, save_directory: str, filename_prefix: Optional[str] = None
204
+ ) -> Tuple[str]:
205
+ index = 0
206
+ if os.path.isdir(save_directory):
207
+ vocab_file = os.path.join(
208
+ save_directory,
209
+ (filename_prefix + "-" if filename_prefix else "") + "vocab.txt",
210
+ )
211
+ else:
212
+ vocab_file = (
213
+ filename_prefix + "-" if filename_prefix else ""
214
+ ) + save_directory
215
+ with open(vocab_file, "w", encoding="utf-8") as writer:
216
+ for token, token_index in sorted(
217
+ self.encoder.items(), key=lambda kv: kv[1]
218
+ ):
219
+ if index != token_index:
220
+ logger.warning(
221
+ f"Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive."
222
+ " Please check that the vocabulary is not corrupted!"
223
+ )
224
+ index = token_index
225
+ writer.write(str(token) + "\n")
226
+ index += 1
227
+ return (vocab_file,)
228
+
229
+ def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
230
+ if self.add_bos_token:
231
+ bos_token_ids = [self.bos_token_id]
232
+ else:
233
+ bos_token_ids = []
234
+
235
+ output = bos_token_ids + token_ids_0
236
+
237
+ if token_ids_1 is None:
238
+ return output
239
+
240
+ return output + bos_token_ids + token_ids_1
241
+
242
+ def get_special_tokens_mask(
243
+ self,
244
+ token_ids_0: List[int],
245
+ token_ids_1: Optional[List[int]] = None,
246
+ already_has_special_tokens: bool = False,
247
+ ) -> List[int]:
248
+ """
249
+ Retrieves sequence ids from a token list that has no special tokens added. This method is called when adding
250
+ special tokens using the tokenizer `prepare_for_model` or `encode_plus` methods.
251
+
252
+ Args:
253
+ token_ids_0 (`List[int]`):
254
+ List of IDs.
255
+ token_ids_1 (`List[int]`, *optional*):
256
+ Optional second list of IDs for sequence pairs.
257
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
258
+ Whether or not the token list is already formatted with special tokens for the model.
259
+
260
+ Returns:
261
+ `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
262
+ """
263
+ if already_has_special_tokens:
264
+ return super().get_special_tokens_mask(
265
+ token_ids_0=token_ids_0,
266
+ token_ids_1=token_ids_1,
267
+ already_has_special_tokens=True,
268
+ )
269
+
270
+ if not self.add_bos_token:
271
+ return super().get_special_tokens_mask(
272
+ token_ids_0=token_ids_0,
273
+ token_ids_1=token_ids_1,
274
+ already_has_special_tokens=False,
275
+ )
276
+
277
+ if token_ids_1 is None:
278
+ return [1] + ([0] * len(token_ids_0))
279
+ return [1] + ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1))
imgs/crimson-finch-unsplash-david-clode.jpg ADDED
imgs/finch.jpg ADDED
modeling_rwkv6.py ADDED
@@ -0,0 +1,801 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import torch
21
+ import torch.nn.functional as F
22
+ import torch.utils.checkpoint
23
+ from torch import nn
24
+ from torch.nn import CrossEntropyLoss
25
+
26
+ from transformers.generation import GenerationMixin
27
+ from transformers.modeling_utils import PreTrainedModel
28
+ from transformers.utils import (
29
+ ModelOutput,
30
+ add_code_sample_docstrings,
31
+ add_start_docstrings,
32
+ add_start_docstrings_to_model_forward,
33
+ logging,
34
+ )
35
+
36
+ from .configuration_rwkv6 import Rwkv6Config
37
+
38
+
39
+ def check_dependencies():
40
+ missing_deps = []
41
+
42
+ try:
43
+ import triton # noqa: F401
44
+ except ImportError:
45
+ missing_deps.append("triton>=3.0.0")
46
+
47
+ try:
48
+ import rwkvfla # noqa: F401
49
+ except ImportError:
50
+ missing_deps.append("rwkv-fla")
51
+
52
+ if missing_deps:
53
+ install_instructions = """
54
+ Required dependencies are missing. Please install them using:
55
+
56
+ {}
57
+
58
+ """.strip()
59
+ install_commands = "\n".join(f"pip install {dep}" for dep in missing_deps)
60
+ print(install_instructions.format(install_commands))
61
+ return False
62
+ else:
63
+ return True
64
+
65
+
66
+ if check_dependencies():
67
+ # flake8: noqa: E402
68
+ from rwkvfla.ops.rwkv6.chunk import chunk_rwkv6 # pylint: disable=C0411
69
+ from rwkvfla.ops.rwkv6.fused_recurrent import fused_recurrent_rwkv6 # pylint: disable=C0411
70
+ from rwkvfla.ops.rwkv6.recurrent_naive import native_recurrent_rwkv6 # pylint: disable=C0411
71
+ else:
72
+ from .wkv6 import native_recurrent_rwkv6
73
+
74
+ chunk_rwkv6 = native_recurrent_rwkv6
75
+ fused_recurrent_rwkv6 = native_recurrent_rwkv6
76
+
77
+
78
+ logger = logging.get_logger(__name__)
79
+
80
+ _CHECKPOINT_FOR_DOC = "RWKV/rwkv-6-world-1b6"
81
+ _CONFIG_FOR_DOC = "Rwkv6Config"
82
+
83
+
84
+ def rwkv6_linear_attention(
85
+ training,
86
+ receptance,
87
+ key,
88
+ value,
89
+ time_decay,
90
+ time_first,
91
+ state,
92
+ ):
93
+ one_token = key.size(1) == 1
94
+ batch, seq_length, _ = receptance.shape
95
+ num_heads, head_size = time_first.shape
96
+ # pylint: disable=line-too-long
97
+ key = key.float().view(batch, seq_length, num_heads, head_size).transpose(1, 2) # B, T, H, K -> B, H, T, K
98
+ value = value.float().view(batch, seq_length, num_heads, head_size).transpose(1, 2) # B, T, H, K - > B, H, T, V
99
+ receptance = receptance.float().view(batch, seq_length, num_heads, head_size).transpose(1, 2) # B, H, T, K
100
+ time_decay = (
101
+ -torch.exp(time_decay.float()).view(batch, seq_length, num_heads, head_size).permute(0, 2, 1, 3)
102
+ ) # B, T, H, K -> B, H, T, K
103
+ time_first = time_first.float().reshape(num_heads, head_size) # H, K
104
+ if receptance.device.type == "cpu":
105
+ out, state = native_recurrent_rwkv6(
106
+ receptance, key, value, time_decay, time_first, scale=1.0, initial_state=state, output_final_state=True
107
+ )
108
+ elif one_token:
109
+ out, state = fused_recurrent_rwkv6(
110
+ receptance, key, value, time_decay, time_first, scale=1.0, initial_state=state, output_final_state=True
111
+ )
112
+ else:
113
+ out, state = chunk_rwkv6(
114
+ receptance, key, value, time_decay, time_first, scale=1.0, initial_state=state, output_final_state=True
115
+ )
116
+ return out.transpose(1, 2), state
117
+
118
+
119
+ class Rwkv6SelfAttention(nn.Module):
120
+ def __init__(self, config, layer_id=0):
121
+ super().__init__()
122
+ self.config = config
123
+ self.layer_id = layer_id
124
+ hidden_size = config.hidden_size
125
+ attention_hidden_size = config.attention_hidden_size
126
+ self.attention_hidden_size = attention_hidden_size
127
+ head_size = config.head_size
128
+ num_heads = attention_hidden_size // head_size
129
+
130
+ self.time_maa_x = nn.Parameter(torch.empty(1, 1, hidden_size))
131
+ self.time_maa_w = nn.Parameter(torch.empty(1, 1, hidden_size))
132
+ self.time_maa_k = nn.Parameter(torch.empty(1, 1, hidden_size))
133
+ self.time_maa_v = nn.Parameter(torch.empty(1, 1, hidden_size))
134
+ self.time_maa_r = nn.Parameter(torch.empty(1, 1, hidden_size))
135
+ self.time_maa_g = nn.Parameter(torch.empty(1, 1, hidden_size))
136
+
137
+ time_mix_extra_dim = 32 # generate TIME_MIX for w,k,v,r,g
138
+ if hidden_size == 4096: # 7b
139
+ time_mix_extra_dim = 64
140
+ self.time_maa_w1 = nn.Parameter(torch.empty(hidden_size, time_mix_extra_dim * 5))
141
+ self.time_maa_w2 = nn.Parameter(torch.empty(5, time_mix_extra_dim, hidden_size))
142
+
143
+ self.time_decay = nn.Parameter(torch.empty(1, 1, attention_hidden_size))
144
+
145
+ time_decay_extra_dim = 64
146
+ if hidden_size == 4096: # 7b
147
+ time_decay_extra_dim = 128
148
+ self.time_decay_w1 = nn.Parameter(torch.empty(hidden_size, time_decay_extra_dim))
149
+ self.time_decay_w2 = nn.Parameter(torch.empty(time_decay_extra_dim, attention_hidden_size))
150
+
151
+ self.time_faaaa = nn.Parameter(torch.empty(num_heads, config.head_size))
152
+
153
+ self.time_shift = nn.ZeroPad2d((0, 0, 1, -1))
154
+ self.receptance = nn.Linear(hidden_size, attention_hidden_size, bias=False)
155
+ self.key = nn.Linear(hidden_size, attention_hidden_size, bias=False)
156
+ self.value = nn.Linear(hidden_size, attention_hidden_size, bias=False)
157
+ self.gate = nn.Linear(hidden_size, attention_hidden_size, bias=False)
158
+ self.output = nn.Linear(attention_hidden_size, hidden_size, bias=False)
159
+ self.ln_x = nn.GroupNorm(num_heads, hidden_size, eps=(1e-5) * (config.head_size_divisor**2))
160
+
161
+ def extract_key_value(self, hidden, state=None):
162
+ # Mix hidden with the previous timestep to produce key, value,
163
+ # receptance
164
+ if hidden.size(1) == 1 and state is not None:
165
+ shifted = state[0][:, :, self.layer_id]
166
+ else:
167
+ shifted = self.time_shift(hidden)
168
+ if state is not None:
169
+ shifted[:, 0] = state[0][:, :, self.layer_id]
170
+ if len(shifted.size()) == 2:
171
+ shifted = shifted.unsqueeze(1)
172
+
173
+ x = hidden
174
+
175
+ B, T, C = hidden.shape
176
+
177
+ xx = shifted - x
178
+
179
+ xxx = x + xx * self.time_maa_x
180
+ xxx = torch.tanh(xxx @ self.time_maa_w1).view(B * T, 5, -1).transpose(0, 1)
181
+ xxx = torch.bmm(xxx, self.time_maa_w2).view(5, B, T, -1)
182
+ mw, mk, mv, mr, mg = xxx.unbind(dim=0)
183
+
184
+ time_decay = x + xx * (self.time_maa_w + mw)
185
+ key = x + xx * (self.time_maa_k + mk)
186
+ value = x + xx * (self.time_maa_v + mv)
187
+ receptance = x + xx * (self.time_maa_r + mr)
188
+ gate = x + xx * (self.time_maa_g + mg)
189
+
190
+ receptance = self.receptance(receptance)
191
+ key = self.key(key)
192
+ value = self.value(value)
193
+ gate = F.silu(self.gate(gate))
194
+
195
+ time_decay = torch.tanh(time_decay @ self.time_decay_w1) @ self.time_decay_w2
196
+ time_decay = self.time_decay + time_decay
197
+
198
+ if state is not None:
199
+ state[0][:, :, self.layer_id] = hidden[:, -1]
200
+
201
+ return receptance, key, value, gate, time_decay, state
202
+
203
+ def forward(self, hidden, state=None, use_cache=False, seq_mode=True):
204
+ receptance, key, value, gate, time_decay, state = self.extract_key_value(hidden, state=state)
205
+
206
+ B, T, _ = receptance.shape
207
+ H, S = self.time_faaaa.shape
208
+
209
+ layer_state = state[1][:, :, :, :, self.layer_id] if state is not None else None
210
+ out, layer_state = rwkv6_linear_attention(
211
+ self.training,
212
+ receptance,
213
+ key,
214
+ value,
215
+ time_decay,
216
+ self.time_faaaa,
217
+ layer_state,
218
+ )
219
+
220
+ if layer_state is not None:
221
+ state[1][:, :, :, :, self.layer_id] = layer_state
222
+
223
+ out = out.reshape(B * T, H * S)
224
+ out = F.group_norm(
225
+ out,
226
+ num_groups=H,
227
+ weight=self.ln_x.weight.to(out.dtype),
228
+ bias=self.ln_x.bias.to(out.dtype),
229
+ eps=self.ln_x.eps,
230
+ ).reshape(B, T, H * S)
231
+ out = out.to(dtype=hidden.dtype) * gate
232
+ out = self.output(out)
233
+ return out, state
234
+
235
+
236
+ class Rwkv6FeedForward(nn.Module):
237
+ def __init__(self, config, layer_id=0):
238
+ super().__init__()
239
+ self.config = config
240
+ self.layer_id = layer_id
241
+ hidden_size = config.hidden_size
242
+ # https://github.com/BlinkDL/RWKV-LM/blob/3db37a72356b736966ddd377268f02b80963af3f/RWKV-v4neo/train.py#L168
243
+ intermediate_size = (
244
+ config.intermediate_size
245
+ if config.intermediate_size is not None
246
+ else int((config.hidden_size * 3.5) // 32 * 32)
247
+ )
248
+
249
+ self.time_shift = nn.ZeroPad2d((0, 0, 1, -1))
250
+ self.time_maa_k = nn.Parameter(torch.empty(1, 1, hidden_size))
251
+ self.time_maa_r = nn.Parameter(torch.empty(1, 1, hidden_size))
252
+
253
+ self.key = nn.Linear(hidden_size, intermediate_size, bias=False)
254
+ self.receptance = nn.Linear(hidden_size, hidden_size, bias=False)
255
+ self.value = nn.Linear(intermediate_size, hidden_size, bias=False)
256
+
257
+ def forward(self, hidden, state=None):
258
+ if hidden.size(1) == 1 and state is not None:
259
+ shifted = state[2][:, :, self.layer_id]
260
+ else:
261
+ shifted = self.time_shift(hidden)
262
+ if state is not None:
263
+ shifted[:, 0] = state[2][:, :, self.layer_id]
264
+ if len(shifted.size()) == 2:
265
+ shifted = shifted.unsqueeze(1)
266
+
267
+ delta_hidden_to_shifted = shifted - hidden
268
+ key = hidden + delta_hidden_to_shifted * self.time_maa_k
269
+ receptance = hidden + delta_hidden_to_shifted * self.time_maa_r
270
+
271
+ key = torch.square(torch.relu(self.key(key)))
272
+ value = self.value(key)
273
+ receptance = torch.sigmoid(self.receptance(receptance))
274
+
275
+ if state is not None:
276
+ state[2][:, :, self.layer_id] = hidden[:, -1]
277
+
278
+ return receptance * value, state
279
+
280
+
281
+ class Rwkv6Block(nn.Module):
282
+ def __init__(self, config, layer_id):
283
+ super().__init__()
284
+ self.config = config
285
+ self.layer_id = layer_id
286
+
287
+ if layer_id == 0:
288
+ self.pre_ln = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_epsilon)
289
+
290
+ self.ln1 = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_epsilon)
291
+ self.ln2 = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_epsilon)
292
+
293
+ self.attention = Rwkv6SelfAttention(config, layer_id)
294
+ self.feed_forward = Rwkv6FeedForward(config, layer_id)
295
+
296
+ def forward(self, hidden, state=None, use_cache=False, output_attentions=False, seq_mode=True):
297
+ if self.layer_id == 0:
298
+ hidden = self.pre_ln(hidden)
299
+ attention, state = self.attention(self.ln1(hidden), state=state, use_cache=use_cache, seq_mode=seq_mode)
300
+ hidden = hidden + attention
301
+
302
+ feed_forward, state = self.feed_forward(self.ln2(hidden), state=state)
303
+ hidden = hidden + feed_forward
304
+
305
+ outputs = (hidden, state)
306
+ if output_attentions:
307
+ outputs += (attention,)
308
+ else:
309
+ outputs += (None,)
310
+
311
+ return outputs
312
+
313
+
314
+ class Rwkv6PreTrainedModel(PreTrainedModel):
315
+ # pylint: disable=line-too-long
316
+ """
317
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
318
+ models.
319
+ """
320
+
321
+ config_class = Rwkv6Config
322
+ base_model_prefix = "rwkv6"
323
+ _no_split_modules = ["Rwkv6Block"]
324
+ _keep_in_fp32_modules = ["time_decay", "time_first"]
325
+ supports_gradient_checkpointing = True
326
+
327
+ def _init_weights(self, module):
328
+ """Initialize the weights."""
329
+ if isinstance(module, Rwkv6SelfAttention):
330
+ layer_id = module.layer_id
331
+ num_hidden_layers = module.config.num_hidden_layers
332
+ hidden_size = module.config.hidden_size
333
+ attention_hidden_size = module.attention_hidden_size
334
+ head_size = module.config.head_size
335
+ num_heads = attention_hidden_size // head_size
336
+
337
+ ratio_0_to_1 = layer_id / (num_hidden_layers - 1) # 0 to 1
338
+ ratio_1_to_almost0 = 1.0 - (layer_id / num_hidden_layers) # 1 to ~0
339
+
340
+ time_weight = torch.tensor(
341
+ [i / hidden_size for i in range(hidden_size)],
342
+ dtype=module.time_maa_k.dtype,
343
+ device=module.time_maa_k.device,
344
+ )
345
+ time_weight = time_weight[None, None, :]
346
+
347
+ decay_speed = [
348
+ -6.0 + 5.0 * (h / (attention_hidden_size - 1)) ** (0.7 + 1.3 * ratio_0_to_1)
349
+ for h in range(attention_hidden_size)
350
+ ]
351
+ decay_speed = torch.tensor(decay_speed, dtype=module.time_decay.dtype, device=module.time_decay.device)
352
+ tmp = torch.tensor(
353
+ [
354
+ (1.0 - (i / (attention_hidden_size - 1.0))) * ratio_0_to_1 + 0.1 * ((i + 1) % 3 - 1)
355
+ for i in range(attention_hidden_size)
356
+ ],
357
+ dtype=module.time_faaaa.dtype,
358
+ device=module.time_faaaa.device,
359
+ )
360
+
361
+ with torch.no_grad():
362
+ module.time_maa_x.data = 1.0 - torch.pow(time_weight, ratio_1_to_almost0)
363
+ module.time_maa_w.data = 1.0 - torch.pow(time_weight, ratio_1_to_almost0)
364
+ module.time_maa_k.data = 1.0 - torch.pow(time_weight, ratio_1_to_almost0)
365
+ module.time_maa_v.data = 1.0 - (torch.pow(time_weight, ratio_1_to_almost0) + 0.3 * ratio_0_to_1)
366
+ module.time_maa_r.data = 1.0 - torch.pow(time_weight, 0.5 * ratio_1_to_almost0)
367
+ module.time_maa_g.data = 1.0 - torch.pow(time_weight, 0.5 * ratio_1_to_almost0)
368
+
369
+ TIME_MIX_EXTRA_DIM = 32 # generate TIME_MIX for w,k,v,r,g
370
+ module.time_maa_w1.data = torch.zeros(
371
+ hidden_size,
372
+ TIME_MIX_EXTRA_DIM * 5,
373
+ dtype=module.time_maa_w1.dtype,
374
+ device=module.time_maa_w1.device,
375
+ ).uniform_(-1e-4, 1e-4)
376
+ module.time_maa_w2.data = torch.zeros(
377
+ 5,
378
+ TIME_MIX_EXTRA_DIM,
379
+ hidden_size,
380
+ dtype=module.time_maa_w2.dtype,
381
+ device=module.time_maa_w2.device,
382
+ ).uniform_(-1e-4, 1e-4)
383
+
384
+ TIME_DECAY_EXTRA_DIM = 64
385
+ module.time_decay_w1.data = torch.zeros(
386
+ hidden_size,
387
+ TIME_DECAY_EXTRA_DIM,
388
+ dtype=module.time_decay_w1.dtype,
389
+ device=module.time_decay_w1.device,
390
+ ).uniform_(-1e-4, 1e-4)
391
+ module.time_decay_w2.data = torch.zeros(
392
+ TIME_DECAY_EXTRA_DIM,
393
+ attention_hidden_size,
394
+ dtype=module.time_decay_w2.dtype,
395
+ device=module.time_decay_w2.device,
396
+ ).uniform_(-1e-4, 1e-4)
397
+
398
+ module.time_decay.data = decay_speed.reshape(num_heads, head_size)
399
+ module.time_faaaa.data = tmp.reshape(num_heads, head_size)
400
+
401
+ elif isinstance(module, Rwkv6FeedForward):
402
+ layer_id = module.layer_id
403
+ num_hidden_layers = module.config.num_hidden_layers
404
+ hidden_size = module.config.hidden_size
405
+
406
+ ratio_1_to_almost0 = 1.0 - (layer_id / num_hidden_layers) # 1 to ~0
407
+
408
+ time_weight = torch.tensor(
409
+ [i / hidden_size for i in range(hidden_size)],
410
+ dtype=module.time_maa_k.dtype,
411
+ device=module.time_maa_k.device,
412
+ )
413
+ time_weight = time_weight[None, None, :]
414
+
415
+ with torch.no_grad():
416
+ module.time_maa_k.data = 1.0 - torch.pow(time_weight, ratio_1_to_almost0)
417
+ module.time_maa_r.data = 1.0 - torch.pow(time_weight, ratio_1_to_almost0)
418
+
419
+
420
+ @dataclass
421
+ class Rwkv6Output(ModelOutput):
422
+ # pylint: disable=line-too-long
423
+ """
424
+ Class for the RWKV model outputs.
425
+
426
+ Args:
427
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
428
+ Sequence of hidden-states at the output of the last layer of the model.
429
+ state (list of five `torch.FloatTensor` of shape `(batch_size, hidden_size, num_hidden_layers)`):
430
+ The state of the model at the last time step. Can be used in a forward method with the next `input_ids` to
431
+ avoid providing the old `input_ids`.
432
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
433
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
434
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of
435
+ the model at the output of each layer plus the optional initial embedding outputs.
436
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
437
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
438
+ sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in
439
+ the self-attention heads.
440
+ """
441
+
442
+ last_hidden_state: torch.FloatTensor = None
443
+ state: Optional[List[torch.FloatTensor]] = None
444
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
445
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
446
+
447
+
448
+ @dataclass
449
+ class Rwkv6CausalLMOutput(ModelOutput):
450
+ """
451
+ Base class for causal language model (or autoregressive) outputs.
452
+
453
+ Args:
454
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
455
+ Language modeling loss (for next-token prediction).
456
+ logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
457
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
458
+ state (list of five `torch.FloatTensor` of shape `(batch_size, hidden_size, num_hidden_layers)`):
459
+ The state of the model at the last time step. Can be used in a forward method with the next `input_ids` to
460
+ avoid providing the old `input_ids`.
461
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
462
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
463
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of
464
+ the model at the output of each layer plus the optional initial embedding outputs.
465
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
466
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
467
+ sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in
468
+ the self-attention heads.
469
+ """
470
+
471
+ loss: Optional[torch.FloatTensor] = None
472
+ logits: torch.FloatTensor = None
473
+ state: Optional[List[torch.FloatTensor]] = None
474
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
475
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
476
+
477
+
478
+ RWKV6_START_DOCSTRING = r"""
479
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
480
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
481
+ etc.) This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module)
482
+ subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to
483
+ general usage and behavior.
484
+
485
+ Parameters:
486
+ config ([`Rwkv6Config`]): Model configuration class with all the parameters of the model.
487
+ Initializing with a config file does not load the weights associated with the model, only the
488
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
489
+ """
490
+
491
+ RWKV6_INPUTS_DOCSTRING = r"""
492
+ Args:
493
+ input_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`):
494
+ `input_ids_length` = `sequence_length` if `past_key_values` is `None` else
495
+ `past_key_values[0][0].shape[-2]` (`sequence_length` of input past key value states). Indices of input
496
+ sequence tokens in the vocabulary. If `past_key_values` is used, only `input_ids` that do not have their
497
+ past calculated should be passed as `input_ids`. Indices can be obtained using [`AutoTokenizer`]. See
498
+ [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. [What are input
499
+ IDs?](../glossary#input-ids)
500
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
501
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
502
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
503
+ model's internal embedding lookup matrix.
504
+ state (tuple of five `torch.FloatTensor` of shape `(batch_size, hidden_size, num_hidden_layers)`, *optional*):
505
+ If passed along, the model uses the previous state in all the blocks (which will give the output for the
506
+ `input_ids` provided as if the model add `state_input_ids + input_ids` as context).
507
+ use_cache (`bool`, *optional*):
508
+ If set to `True`, the last state is returned and can be used to quickly generate the next logits.
509
+ output_attentions (`bool`, *optional*):
510
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
511
+ tensors for more detail.
512
+ output_hidden_states (`bool`, *optional*):
513
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
514
+ more detail.
515
+ return_dict (`bool`, *optional*):
516
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
517
+ """
518
+
519
+
520
+ @add_start_docstrings(
521
+ "The bare RWKV6 Model transformer outputting raw hidden-states without any specific head on top.",
522
+ RWKV6_START_DOCSTRING,
523
+ )
524
+ class Rwkv6Model(Rwkv6PreTrainedModel):
525
+ def __init__(self, config):
526
+ super().__init__(config)
527
+
528
+ self.embeddings = nn.Embedding(config.vocab_size, config.hidden_size)
529
+ self.blocks = nn.ModuleList([Rwkv6Block(config, layer_id=idx) for idx in range(config.num_hidden_layers)])
530
+ self.ln_out = nn.LayerNorm(config.hidden_size)
531
+
532
+ self.layers_are_rescaled = False
533
+ self.gradient_checkpointing = False
534
+
535
+ # Initialize weights and apply final processing
536
+ self.post_init()
537
+
538
+ def get_input_embeddings(self):
539
+ return self.embeddings
540
+
541
+ def set_input_embeddings(self, new_embeddings):
542
+ self.embeddings = new_embeddings
543
+
544
+ @add_start_docstrings_to_model_forward(RWKV6_INPUTS_DOCSTRING)
545
+ @add_code_sample_docstrings(
546
+ checkpoint=_CHECKPOINT_FOR_DOC,
547
+ output_type=Rwkv6Output,
548
+ config_class=_CONFIG_FOR_DOC,
549
+ )
550
+ def forward(
551
+ self,
552
+ input_ids: Optional[torch.LongTensor] = None,
553
+ attention_mask: Optional[torch.LongTensor] = None, # noqa
554
+ inputs_embeds: Optional[torch.FloatTensor] = None,
555
+ state: Optional[List[torch.FloatTensor]] = None,
556
+ use_cache: Optional[bool] = None,
557
+ output_attentions: Optional[bool] = None,
558
+ output_hidden_states: Optional[bool] = None,
559
+ return_dict: Optional[bool] = None,
560
+ ) -> Union[Tuple, Rwkv6Output]:
561
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
562
+ output_hidden_states = (
563
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
564
+ )
565
+ # training is supportable with the Triton kernel
566
+ # rwkv6 only support inference in huggingface.
567
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
568
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
569
+
570
+ if self.training == self.layers_are_rescaled and (
571
+ self.embeddings.weight.dtype == torch.float16 or self.embeddings.weight.dtype == torch.bfloat16
572
+ ):
573
+ self._rescale_layers()
574
+
575
+ if input_ids is not None and inputs_embeds is not None:
576
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
577
+ elif input_ids is None and inputs_embeds is None:
578
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
579
+
580
+ if inputs_embeds is None:
581
+ inputs_embeds = self.embeddings(input_ids)
582
+
583
+ if state is None:
584
+ state = []
585
+ head_size = self.config.head_size
586
+ num_heads = self.config.attention_hidden_size // head_size
587
+ state_attn_x = torch.zeros(
588
+ (inputs_embeds.size(0), self.config.hidden_size, self.config.num_hidden_layers),
589
+ dtype=inputs_embeds.dtype,
590
+ requires_grad=False,
591
+ device=inputs_embeds.device,
592
+ ).contiguous()
593
+ state_attn_kv = torch.zeros(
594
+ (
595
+ inputs_embeds.size(0),
596
+ num_heads,
597
+ head_size,
598
+ head_size,
599
+ self.config.num_hidden_layers,
600
+ ),
601
+ dtype=torch.float32,
602
+ requires_grad=False,
603
+ device=inputs_embeds.device,
604
+ ).contiguous()
605
+ state_ffn_x = torch.zeros(
606
+ (inputs_embeds.size(0), self.config.hidden_size, self.config.num_hidden_layers),
607
+ dtype=inputs_embeds.dtype,
608
+ requires_grad=False,
609
+ device=inputs_embeds.device,
610
+ ).contiguous()
611
+ state.append(state_attn_x)
612
+ state.append(state_attn_kv)
613
+ state.append(state_ffn_x)
614
+
615
+ seq_mode = inputs_embeds.shape[1] > 1
616
+ hidden_states = inputs_embeds
617
+
618
+ all_self_attentions = () if output_attentions else None
619
+ all_hidden_states = () if output_hidden_states else None
620
+ for idx, block in enumerate(self.blocks):
621
+ hidden_states, state, attentions = block(
622
+ hidden_states, state=state, use_cache=use_cache, output_attentions=output_attentions, seq_mode=seq_mode
623
+ )
624
+ if (
625
+ self.layers_are_rescaled
626
+ and self.config.rescale_every > 0
627
+ and (idx + 1) % self.config.rescale_every == 0
628
+ ):
629
+ hidden_states = hidden_states / 2
630
+
631
+ if output_hidden_states:
632
+ all_hidden_states = all_hidden_states + (hidden_states,)
633
+
634
+ if output_attentions:
635
+ all_self_attentions = all_self_attentions + (attentions,)
636
+
637
+ hidden_states = self.ln_out(hidden_states)
638
+
639
+ if output_hidden_states:
640
+ all_hidden_states = all_hidden_states + (hidden_states,)
641
+
642
+ if not return_dict:
643
+ return (hidden_states, state, all_hidden_states, all_self_attentions)
644
+
645
+ return Rwkv6Output(
646
+ last_hidden_state=hidden_states,
647
+ state=state,
648
+ hidden_states=all_hidden_states, # None
649
+ attentions=all_self_attentions, # None
650
+ )
651
+
652
+ def _rescale_layers(self):
653
+ # Layers should be rescaled for inference only.
654
+ if self.layers_are_rescaled == (not self.training):
655
+ return
656
+ if self.config.rescale_every > 0:
657
+ with torch.no_grad():
658
+ for block_id, block in enumerate(self.blocks):
659
+ if self.training:
660
+ block.attention.output.weight.mul_(2 ** int(block_id // self.config.rescale_every))
661
+ block.feed_forward.value.weight.mul_(2 ** int(block_id // self.config.rescale_every))
662
+ else:
663
+ # Deal with quantization statistics
664
+ if hasattr(block.attention.output.weight, "SCB"):
665
+ block.attention.output.weight.SCB.div_(2 ** int(block_id // self.config.rescale_every))
666
+ block.feed_forward.value.weight.SCB.div_(2 ** int(block_id // self.config.rescale_every))
667
+ elif hasattr(block.attention.output.weight, "quant_state"):
668
+ self._bnb_4bit_dequantize_and_rescale(block.attention.output, block_id)
669
+ self._bnb_4bit_dequantize_and_rescale(block.feed_forward.value, block_id)
670
+ else:
671
+ block.attention.output.weight.div_(2 ** int(block_id // self.config.rescale_every))
672
+ block.feed_forward.value.weight.div_(2 ** int(block_id // self.config.rescale_every))
673
+
674
+ self.layers_are_rescaled = not self.training
675
+
676
+ def _bnb_4bit_dequantize_and_rescale(self, target_layer, block_id):
677
+ r"""
678
+ Perform the dequantization and rescaling of the weights of a given layer. After that operation the layer will
679
+ be quantized again.
680
+ """
681
+ try:
682
+ import bitsandbytes as bnb
683
+ except ImportError:
684
+ raise ImportError("Please install bitsandbytes to use this method.")
685
+
686
+ dequant_weights = bnb.functional.dequantize_4bit(target_layer.weight.data, target_layer.weight.quant_state)
687
+
688
+ dequant_weights.div_(2 ** int(block_id // self.config.rescale_every))
689
+
690
+ # re-quantize the model:
691
+ # we need to put it first on CPU then back to the device
692
+ # this will create an overhead :/
693
+ # We set requires_grad=False as we cannot compute gradients on top of 4bit parameters anyway and to avoid
694
+ # bugs with bnb
695
+ quant_weight = bnb.nn.Params4bit(dequant_weights.to("cpu"), requires_grad=False).to(dequant_weights.device)
696
+ setattr(target_layer, "weight", quant_weight)
697
+
698
+
699
+ # copied from HuggingFace
700
+ # https://github.com/huggingface/transformers/blob/main/src/transformers/models/rwkv/modeling_rwkv.py
701
+ @add_start_docstrings(
702
+ """
703
+ The RWKV6 Model transformer with a language modeling head on top (linear layer with weights tied to the input
704
+ embeddings).
705
+ """,
706
+ RWKV6_START_DOCSTRING,
707
+ )
708
+ class Rwkv6ForCausalLM(Rwkv6PreTrainedModel, GenerationMixin):
709
+ _tied_weights_keys = ["head.weight"]
710
+
711
+ def __init__(self, config):
712
+ super().__init__(config)
713
+ self.rwkv = Rwkv6Model(config)
714
+ self.head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
715
+
716
+ # Initialize weights and apply final processing
717
+ self.post_init()
718
+
719
+ def get_output_embeddings(self):
720
+ return self.head
721
+
722
+ def set_output_embeddings(self, new_embeddings):
723
+ self.head = new_embeddings
724
+
725
+ def prepare_inputs_for_generation(self, input_ids, state=None, inputs_embeds=None, **kwargs):
726
+ # only last token for inputs_ids if the state is passed along.
727
+ if state is not None:
728
+ input_ids = input_ids[:, -1].unsqueeze(-1)
729
+
730
+ # if `inputs_embeds` are passed, we only want to use them in the 1st
731
+ # generation step
732
+ if inputs_embeds is not None and state is None:
733
+ model_inputs = {"inputs_embeds": inputs_embeds}
734
+ else:
735
+ model_inputs = {"input_ids": input_ids}
736
+
737
+ model_inputs["state"] = state
738
+ return model_inputs
739
+
740
+ @add_start_docstrings_to_model_forward(RWKV6_INPUTS_DOCSTRING)
741
+ @add_code_sample_docstrings(
742
+ checkpoint=_CHECKPOINT_FOR_DOC,
743
+ output_type=Rwkv6CausalLMOutput,
744
+ config_class=_CONFIG_FOR_DOC,
745
+ )
746
+ def forward(
747
+ self,
748
+ input_ids: Optional[torch.LongTensor] = None,
749
+ attention_mask: Optional[torch.LongTensor] = None,
750
+ inputs_embeds: Optional[torch.FloatTensor] = None,
751
+ state: Optional[List[torch.FloatTensor]] = None,
752
+ labels: Optional[torch.LongTensor] = None,
753
+ use_cache: Optional[bool] = None,
754
+ output_attentions: Optional[bool] = None,
755
+ output_hidden_states: Optional[bool] = None,
756
+ return_dict: Optional[bool] = None,
757
+ ) -> Union[Tuple, Rwkv6CausalLMOutput]:
758
+ # pylint: disable=line-too-long
759
+ r"""
760
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
761
+ Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
762
+ `labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
763
+ are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
764
+ """
765
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
766
+
767
+ outputs = self.rwkv(
768
+ input_ids,
769
+ inputs_embeds=inputs_embeds,
770
+ state=state,
771
+ use_cache=use_cache,
772
+ output_attentions=output_attentions,
773
+ output_hidden_states=output_hidden_states,
774
+ return_dict=return_dict,
775
+ )
776
+ hidden_states = outputs[0]
777
+
778
+ logits = self.head(hidden_states)
779
+
780
+ loss = None
781
+ if labels is not None:
782
+ # move labels to correct device to enable model parallelism
783
+ labels = labels.to(logits.device)
784
+ # Shift so that tokens < n predict n
785
+ shift_logits = logits[..., :-1, :].contiguous()
786
+ shift_labels = labels[..., 1:].contiguous()
787
+ # Flatten the tokens
788
+ loss_fct = CrossEntropyLoss()
789
+ loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
790
+
791
+ if not return_dict:
792
+ output = (logits,) + outputs[1:]
793
+ return ((loss,) + output) if loss is not None else output
794
+
795
+ return Rwkv6CausalLMOutput(
796
+ loss=loss,
797
+ logits=logits,
798
+ state=outputs.state,
799
+ hidden_states=outputs.hidden_states,
800
+ attentions=outputs.attentions,
801
+ )
pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5984baf1510cdf659b287166c2205fdaa10097ab7f4e4cdc57b640f14a0a965e
3
+ size 15271603150
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,5 @@
 
 
 
 
 
 
1
+ {
2
+ "bos_token": "<s>",
3
+ "eos_token": "<s>",
4
+ "unk_token": "<s>"
5
+ }
tokenizer_config.json ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name_or_path": "rwkv-6-tokenizer",
3
+ "add_prefix_space": false,
4
+ "tokenizer_class": "Rwkv6Tokenizer",
5
+ "use_fast": false,
6
+ "auto_map": {
7
+ "AutoTokenizer": [
8
+ "hf_rwkv_tokenizer.Rwkv6Tokenizer",
9
+ null
10
+ ]
11
+ }
12
+ }
wkv6.py ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ from typing import Optional, Tuple
4
+
5
+ import torch
6
+
7
+
8
+ def naive_recurrent_rwkv6(
9
+ q: torch.Tensor,
10
+ k: torch.Tensor,
11
+ v: torch.Tensor,
12
+ w: torch.Tensor,
13
+ u: torch.Tensor,
14
+ scale: float = 1.0,
15
+ initial_state: Optional[torch.Tensor] = None,
16
+ output_final_state: bool = False,
17
+ u_2d: bool = False,
18
+ ):
19
+ torch_dtype = q.dtype if q.dtype in [torch.float16, torch.float32, torch.float64] else torch.float32
20
+ orig_dtype = q.dtype
21
+ B, H, T, K, V = q.shape[0], q.shape[1], q.shape[2], q.shape[3], v.shape[-1]
22
+ q, k, v, w, u = (x.to(dtype=torch_dtype) for x in (q, k, v, w, u))
23
+ h = torch.zeros(B, H, K, V, dtype=torch_dtype, device=q.device)
24
+ o = torch.zeros_like(v)
25
+
26
+ if scale == -1.0:
27
+ scale = K**-0.5
28
+
29
+ if initial_state is not None:
30
+ h += initial_state.to(dtype=torch_dtype)
31
+
32
+ w = w.exp()
33
+
34
+ if u_2d:
35
+ u_expand = u[None, ..., None]
36
+ else:
37
+ u_expand = u[..., None]
38
+
39
+ for i in range(T):
40
+ q_i = q[:, :, i, :] * scale
41
+ k_i = k[:, :, i] * scale
42
+ v_i = v[:, :, i, :]
43
+ w_i = w[:, :, i]
44
+ kv_i = k_i[..., None] * v_i[..., None, :]
45
+ o_i = (h + u_expand * kv_i) * q_i[..., None]
46
+ o[:, :, i] = o_i.sum(-2)
47
+ h = h * w_i[..., None] + kv_i
48
+
49
+ ht = h if output_final_state else None
50
+ return o.to(orig_dtype), ht
51
+
52
+
53
+ def naive_recurrent_rwkv6_bwd(
54
+ q: torch.Tensor,
55
+ k: torch.Tensor,
56
+ v: torch.Tensor,
57
+ w: torch.Tensor,
58
+ u: torch.Tensor,
59
+ o: torch.Tensor,
60
+ do: torch.Tensor,
61
+ dh_t: Optional[torch.Tensor] = None,
62
+ initial_state: Optional[torch.Tensor] = None,
63
+ scale: float = 1.0,
64
+ u_2d: bool = False,
65
+ ):
66
+ torch_type = torch.float32 if q.dtype != torch.float16 else torch.float16
67
+ q, k, v, w, u, o, do = (x.to(dtype=torch_type) for x in (q, k, v, w, u, o, do))
68
+ B, H, T, K, V = q.shape[0], q.shape[1], q.shape[2], q.shape[3], v.shape[-1]
69
+ h = torch.zeros(B, H, K, V, dtype=torch_type, device=q.device)
70
+ dq = torch.zeros_like(q)
71
+ dq_aux = torch.zeros_like(q)
72
+
73
+ if initial_state is not None:
74
+ h += initial_state
75
+
76
+ if scale == -1.0:
77
+ scale = K**-0.5
78
+
79
+ w = w.exp()
80
+ if u_2d:
81
+ u_expand = u[None, ..., None]
82
+ sum_dims = [0, -1]
83
+ else:
84
+ u_expand = u[..., None]
85
+ sum_dims = [-1]
86
+
87
+ for i in range(T):
88
+ k_i = k[:, :, i] * scale
89
+ v_i = v[:, :, i]
90
+ w_i = w[:, :, i]
91
+ kv_i = k_i[..., None] * v_i[..., None, :]
92
+ h_i = h + u_expand * kv_i
93
+ dq_i = (do[:, :, i, None, :] * h_i).sum(-1)
94
+ dq_aux_i = (do[:, :, i, None, :] * h).sum(-1)
95
+ dq[:, :, i] = dq_i * scale
96
+ dq_aux[:, :, i] = dq_aux_i
97
+ h = h * w_i[..., None] + kv_i
98
+
99
+ du = torch.zeros_like(u)
100
+ dh = torch.zeros_like(h)
101
+ if dh_t is not None:
102
+ dh += dh_t
103
+ dk = torch.zeros_like(k)
104
+ dk_aux = torch.zeros_like(k)
105
+ dv = torch.zeros_like(v)
106
+
107
+ for i in range(T - 1, -1, -1):
108
+ q_i = q[:, :, i] * scale
109
+ k_i = k[:, :, i] * scale
110
+ v_i = v[:, :, i]
111
+
112
+ d_kv_i = do[:, :, i, None, :] * q_i[..., None]
113
+ du += (d_kv_i * k_i[..., None] * v_i[..., None, :]).sum(sum_dims)
114
+
115
+ dk_i = (dh * v_i[..., None, :]).sum(-1)
116
+ dk_aux[:, :, i] = dk_i
117
+ dk_i += (d_kv_i * u_expand * v_i[..., None, :]).sum(-1)
118
+
119
+ dv_i = (d_kv_i * u_expand * k_i[..., None]).sum(-2)
120
+ dv_i += (dh * k_i[..., None]).sum(-2)
121
+
122
+ dk[:, :, i] = dk_i * scale
123
+ dv[:, :, i] = dv_i
124
+ dh = dh * w[:, :, i, :, None] + d_kv_i
125
+
126
+ # dw = q * dq_aux - k * dk_aux
127
+ dw = torch.zeros_like(w)
128
+ for i in range(T - 2, -1, -1):
129
+ dw[:, :, i] = (
130
+ dw[:, :, i + 1] + dq_aux[:, :, i + 1] * q[:, :, i + 1] * scale - dk_aux[:, :, i] * k[:, :, i] * scale
131
+ )
132
+
133
+ return dq, dk, dv, dw, du, dh
134
+
135
+
136
+ class NativeRecurrentRWKV6Function(torch.autograd.Function):
137
+ @staticmethod
138
+ def forward(
139
+ ctx,
140
+ q,
141
+ k,
142
+ v,
143
+ w,
144
+ u,
145
+ scale,
146
+ initial_state,
147
+ output_final_state: bool = False,
148
+ u_2d: bool = False,
149
+ training: bool = True,
150
+ ):
151
+ o, ht = naive_recurrent_rwkv6(q, k, v, w, u, scale, initial_state, output_final_state, u_2d)
152
+ if initial_state is not None:
153
+ initial_state = initial_state.clone()
154
+ if training:
155
+ ctx.save_for_backward(q, k, v, w, u, o, initial_state)
156
+ ctx.u_2d = u_2d
157
+ ctx.scale = scale
158
+ return o, ht
159
+
160
+ @staticmethod
161
+ def backward(ctx, do, dht):
162
+ q, k, v, w, u, o, initial_state = ctx.saved_tensors
163
+ dq, dk, dv, dw, du, dh = naive_recurrent_rwkv6_bwd(
164
+ q, k, v, w, u, o, do, dht, initial_state, ctx.scale, ctx.u_2d
165
+ )
166
+ dh = dh if initial_state is not None else None
167
+ return dq, dk, dv, dw, du, None, dh, None, None, None
168
+
169
+
170
+ def native_recurrent_rwkv6(
171
+ r: torch.Tensor,
172
+ k: torch.Tensor,
173
+ v: torch.Tensor,
174
+ w: torch.Tensor,
175
+ u: torch.Tensor,
176
+ scale: float = 1.0,
177
+ initial_state: torch.Tensor = None,
178
+ output_final_state: bool = False,
179
+ training: bool = True,
180
+ causal: bool = True,
181
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
182
+ r"""
183
+ Args:
184
+ r (torch.Tensor):
185
+ reception of shape `(B, H, T, K)`. Alias: q, query in linear attention.
186
+ k (torch.Tensor):
187
+ keys of shape `(B, H, T, K)`
188
+ v (torch.Tensor):
189
+ values of shape `(B, H, T, V)`
190
+ w (torch.Tensor):
191
+ data-dependent decays of shape `(B, H, T, K)` in log space! Alias: g.
192
+ u (torch.Tensor):
193
+ bonus of shape `(H, K)` or `(B, H, K)` for each head.
194
+ scale (Optional[int]):
195
+ Scale factor for the RWKV6 attention scores.
196
+ If not provided, it will default to `1 / sqrt(K)`. Default: `None`.
197
+ initial_state (Optional[torch.Tensor]):
198
+ Initial state of shape `(B, H, K, V)`. Default: `None`.
199
+ output_final_state (Optional[bool]):
200
+ Whether to output the final state of shape `(B, H, K, V)`. Default: `False`.
201
+ """
202
+ if scale == -1.0:
203
+ scale = r.shape[-1] ** -0.5
204
+ u_2d = True if u.dim() == 2 else False
205
+ o, final_state = NativeRecurrentRWKV6Function.apply(
206
+ r, k, v, w, u, scale, initial_state, output_final_state, u_2d, training
207
+ )
208
+
209
+ return o, final_state