Commit
•
8b50b9b
0
Parent(s):
Duplicate from RWKV/rwkv-5-world-3b
Browse filesCo-authored-by: Kalei Neely <KaleiNeely@users.noreply.huggingface.co>
- .gitattributes +35 -0
- README.md +173 -0
- config.json +24 -0
- configuration_rwkv5.py +118 -0
- generation_config.json +12 -0
- modeling_rwkv5.py +845 -0
- pytorch_model.bin +3 -0
- special_tokens_map.json +6 -0
- tokenization_rwkv5.py +230 -0
- tokenization_rwkv_world.py +549 -0
- tokenizer_config.json +23 -0
- vocab.txt +0 -0
.gitattributes
ADDED
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
*.7z filter=lfs diff=lfs merge=lfs -text
|
2 |
+
*.arrow filter=lfs diff=lfs merge=lfs -text
|
3 |
+
*.bin filter=lfs diff=lfs merge=lfs -text
|
4 |
+
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
5 |
+
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
6 |
+
*.ftz filter=lfs diff=lfs merge=lfs -text
|
7 |
+
*.gz filter=lfs diff=lfs merge=lfs -text
|
8 |
+
*.h5 filter=lfs diff=lfs merge=lfs -text
|
9 |
+
*.joblib filter=lfs diff=lfs merge=lfs -text
|
10 |
+
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
11 |
+
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
12 |
+
*.model filter=lfs diff=lfs merge=lfs -text
|
13 |
+
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
14 |
+
*.npy filter=lfs diff=lfs merge=lfs -text
|
15 |
+
*.npz filter=lfs diff=lfs merge=lfs -text
|
16 |
+
*.onnx filter=lfs diff=lfs merge=lfs -text
|
17 |
+
*.ot filter=lfs diff=lfs merge=lfs -text
|
18 |
+
*.parquet filter=lfs diff=lfs merge=lfs -text
|
19 |
+
*.pb filter=lfs diff=lfs merge=lfs -text
|
20 |
+
*.pickle filter=lfs diff=lfs merge=lfs -text
|
21 |
+
*.pkl filter=lfs diff=lfs merge=lfs -text
|
22 |
+
*.pt filter=lfs diff=lfs merge=lfs -text
|
23 |
+
*.pth filter=lfs diff=lfs merge=lfs -text
|
24 |
+
*.rar filter=lfs diff=lfs merge=lfs -text
|
25 |
+
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
26 |
+
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
27 |
+
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
28 |
+
*.tar filter=lfs diff=lfs merge=lfs -text
|
29 |
+
*.tflite filter=lfs diff=lfs merge=lfs -text
|
30 |
+
*.tgz filter=lfs diff=lfs merge=lfs -text
|
31 |
+
*.wasm filter=lfs diff=lfs merge=lfs -text
|
32 |
+
*.xz filter=lfs diff=lfs merge=lfs -text
|
33 |
+
*.zip filter=lfs diff=lfs merge=lfs -text
|
34 |
+
*.zst filter=lfs diff=lfs merge=lfs -text
|
35 |
+
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
README.md
ADDED
@@ -0,0 +1,173 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
### Run Huggingface RWKV5 World Model
|
2 |
+
|
3 |
+
|
4 |
+
#### CPU
|
5 |
+
|
6 |
+
```python
|
7 |
+
import torch
|
8 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
9 |
+
|
10 |
+
def generate_prompt(instruction, input=""):
|
11 |
+
instruction = instruction.strip().replace('\r\n','\n').replace('\n\n','\n')
|
12 |
+
input = input.strip().replace('\r\n','\n').replace('\n\n','\n')
|
13 |
+
if input:
|
14 |
+
return f"""Instruction: {instruction}
|
15 |
+
|
16 |
+
Input: {input}
|
17 |
+
|
18 |
+
Response:"""
|
19 |
+
else:
|
20 |
+
return f"""User: hi
|
21 |
+
|
22 |
+
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.
|
23 |
+
|
24 |
+
User: {instruction}
|
25 |
+
|
26 |
+
Assistant:"""
|
27 |
+
|
28 |
+
|
29 |
+
model = AutoModelForCausalLM.from_pretrained("RWKV/rwkv-5-world-3b", trust_remote_code=True).to(torch.float32)
|
30 |
+
tokenizer = AutoTokenizer.from_pretrained("RWKV/rwkv-5-world-3b", trust_remote_code=True)
|
31 |
+
|
32 |
+
text = "请介绍北京的旅游景点"
|
33 |
+
prompt = generate_prompt(text)
|
34 |
+
|
35 |
+
inputs = tokenizer(prompt, return_tensors="pt")
|
36 |
+
output = model.generate(inputs["input_ids"], max_new_tokens=333, do_sample=True, temperature=1.0, top_p=0.3, top_k=0, )
|
37 |
+
print(tokenizer.decode(output[0].tolist(), skip_special_tokens=True))
|
38 |
+
```
|
39 |
+
|
40 |
+
output:
|
41 |
+
|
42 |
+
```shell
|
43 |
+
User: hi
|
44 |
+
|
45 |
+
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.
|
46 |
+
|
47 |
+
User: 请介绍北京的旅游景点
|
48 |
+
|
49 |
+
Assistant: 北京是中国的首都,拥有众多的旅游景点,以下是其中一些著名的景点:
|
50 |
+
1. 故宫:位于北京市中心,是明清两代的皇宫,内有大量的文物和艺术品。
|
51 |
+
2. 天安门广场:是中国最著名的广场之一,是中国人民政治协商会议的旧址,也是中国人民政治协商会议的中心。
|
52 |
+
3. 颐和园:是中国古代皇家园林之一,有着悠久的历史和丰富的文化内涵。
|
53 |
+
4. 长城:是中国古代的一道长城,全长约万里,是中国最著名的旅游景点之一。
|
54 |
+
5. 北京大学:是中国著名的高等教育机构之一,有着悠久的历史和丰富的文化内涵。
|
55 |
+
6. 北京动物园:是中国最大的动物园之一,有着丰富的动物资源和丰富的文化内涵。
|
56 |
+
7. 故宫博物院:是中国最著名的博物馆之一,收藏了大量的文物和艺术品,是中国最重要的文化遗产之一。
|
57 |
+
8. 天坛:是中国古代皇家
|
58 |
+
```
|
59 |
+
|
60 |
+
#### GPU
|
61 |
+
|
62 |
+
```python
|
63 |
+
import torch
|
64 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
65 |
+
|
66 |
+
def generate_prompt(instruction, input=""):
|
67 |
+
instruction = instruction.strip().replace('\r\n','\n').replace('\n\n','\n')
|
68 |
+
input = input.strip().replace('\r\n','\n').replace('\n\n','\n')
|
69 |
+
if input:
|
70 |
+
return f"""Instruction: {instruction}
|
71 |
+
|
72 |
+
Input: {input}
|
73 |
+
|
74 |
+
Response:"""
|
75 |
+
else:
|
76 |
+
return f"""User: hi
|
77 |
+
|
78 |
+
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.
|
79 |
+
|
80 |
+
User: {instruction}
|
81 |
+
|
82 |
+
Assistant:"""
|
83 |
+
|
84 |
+
|
85 |
+
model = AutoModelForCausalLM.from_pretrained("RWKV/rwkv-5-world-3b", trust_remote_code=True, torch_dtype=torch.float16).to(0)
|
86 |
+
tokenizer = AutoTokenizer.from_pretrained("RWKV/rwkv-5-world-3b", trust_remote_code=True)
|
87 |
+
|
88 |
+
text = "介绍一下大熊猫"
|
89 |
+
prompt = generate_prompt(text)
|
90 |
+
|
91 |
+
inputs = tokenizer(prompt, return_tensors="pt").to(0)
|
92 |
+
output = model.generate(inputs["input_ids"], max_new_tokens=128, do_sample=True, temperature=1.0, top_p=0.3, top_k=0, )
|
93 |
+
print(tokenizer.decode(output[0].tolist(), skip_special_tokens=True))
|
94 |
+
```
|
95 |
+
|
96 |
+
output:
|
97 |
+
|
98 |
+
```shell
|
99 |
+
User: hi
|
100 |
+
|
101 |
+
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.
|
102 |
+
|
103 |
+
User: 介绍一下大熊猫
|
104 |
+
|
105 |
+
Assistant: 大熊猫是一种中国特有的哺乳动物,也是中国的国宝之一。它们的外貌特征是圆形的黑白相间的身体,有着黑色的毛发和白色的耳朵。大熊猫的食物主要是竹子,它们会在竹林中寻找竹子,并且会将竹子放在竹笼中进行储存。大熊猫的寿命约为20至30年,但由于栖息地的丧失和人类活动的
|
106 |
+
```
|
107 |
+
|
108 |
+
#### Batch Inference
|
109 |
+
|
110 |
+
```python
|
111 |
+
import torch
|
112 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
113 |
+
|
114 |
+
def generate_prompt(instruction, input=""):
|
115 |
+
instruction = instruction.strip().replace('\r\n', '\n').replace('\n\n', '\n')
|
116 |
+
input = input.strip().replace('\r\n', '\n').replace('\n\n', '\n')
|
117 |
+
if input:
|
118 |
+
return f"""Instruction: {instruction}
|
119 |
+
|
120 |
+
Input: {input}
|
121 |
+
|
122 |
+
Response:"""
|
123 |
+
else:
|
124 |
+
return f"""User: hi
|
125 |
+
|
126 |
+
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.
|
127 |
+
|
128 |
+
User: {instruction}
|
129 |
+
|
130 |
+
Assistant:"""
|
131 |
+
|
132 |
+
model = AutoModelForCausalLM.from_pretrained("RWKV/rwkv-5-world-3b", trust_remote_code=True).to(torch.float32)
|
133 |
+
tokenizer = AutoTokenizer.from_pretrained("RWKV/rwkv-5-world-3b", trust_remote_code=True, padding_side='left')
|
134 |
+
|
135 |
+
texts = ["请介绍北京的旅游景点", "介绍一下大熊猫", "乌兰察布"]
|
136 |
+
prompts = [generate_prompt(text) for text in texts]
|
137 |
+
|
138 |
+
inputs = tokenizer(prompts, return_tensors="pt", padding=True)
|
139 |
+
outputs = model.generate(inputs["input_ids"], max_new_tokens=128, do_sample=True, temperature=1.0, top_p=0.3, top_k=0, )
|
140 |
+
|
141 |
+
for output in outputs:
|
142 |
+
print(tokenizer.decode(output.tolist(), skip_special_tokens=True))
|
143 |
+
|
144 |
+
```
|
145 |
+
|
146 |
+
output:
|
147 |
+
|
148 |
+
```shell
|
149 |
+
User: hi
|
150 |
+
|
151 |
+
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.
|
152 |
+
|
153 |
+
User: 请介绍北京的旅游景点
|
154 |
+
|
155 |
+
Assistant: 北京是中国的首都,拥有丰富的旅游资源和历史文化遗产。以下是一些北京的旅游景点:
|
156 |
+
1. 故宫:位于北京市中心,是明清两代的皇宫,是中国最大的古代宫殿建筑群之一。
|
157 |
+
2. 天安门广场:位于北京市中心,是中国最著名的城市广场之一,也是中国最大的城市广场。
|
158 |
+
3. 颐和
|
159 |
+
User: hi
|
160 |
+
|
161 |
+
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.
|
162 |
+
|
163 |
+
User: 介绍一下大熊猫
|
164 |
+
|
165 |
+
Assistant: 大熊猫是一种生活在中国中部地区的哺乳动物,也是中国的国宝之一。它们的外貌特征是圆形的黑白相间的身体,有着黑色的毛发和圆圆的眼睛。大熊猫是一种濒危物种,目前只有在野外的几个保护区才能看到它们的身影。大熊猫的食物主要是竹子,它们会在竹子上寻找食物,并且可以通
|
166 |
+
User: hi
|
167 |
+
|
168 |
+
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.
|
169 |
+
|
170 |
+
User: 乌兰察布
|
171 |
+
|
172 |
+
Assistant: 乌兰察布是中国新疆维吾尔自治区的一个县级市,位于新疆维吾尔自治区中部,是新疆的第二大城市。乌兰察布市是新疆的第一大城市,也是新疆的重要城市之一。乌兰察布市是新疆的经济中心,也是新疆的重要交通枢纽之一。乌兰察布市的人口约为2.5万人,其中汉族占绝大多数。乌
|
173 |
+
```
|
config.json
ADDED
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"architectures": [
|
3 |
+
"Rwkv5ForCausalLM"
|
4 |
+
],
|
5 |
+
"auto_map": {
|
6 |
+
"AutoConfig": "configuration_rwkv5.Rwkv5Config",
|
7 |
+
"AutoModelForCausalLM": "modeling_rwkv5.Rwkv5ForCausalLM"
|
8 |
+
},
|
9 |
+
"attention_hidden_size": 2560,
|
10 |
+
"bos_token_id": 0,
|
11 |
+
"eos_token_id": 0,
|
12 |
+
"head_size": 64,
|
13 |
+
"hidden_size": 2560,
|
14 |
+
"intermediate_size": null,
|
15 |
+
"layer_norm_epsilon": 1e-05,
|
16 |
+
"model_type": "rwkv5",
|
17 |
+
"num_attention_heads": 64,
|
18 |
+
"num_hidden_layers": 32,
|
19 |
+
"rescale_every": 6,
|
20 |
+
"tie_word_embeddings": false,
|
21 |
+
"transformers_version": "4.34.0",
|
22 |
+
"use_cache": true,
|
23 |
+
"vocab_size": 65536
|
24 |
+
}
|
configuration_rwkv5.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 |
+
RWKV5_PRETRAINED_CONFIG_ARCHIVE_MAP = {}
|
25 |
+
|
26 |
+
|
27 |
+
class Rwkv5Config(PretrainedConfig):
|
28 |
+
"""
|
29 |
+
This is the configuration class to store the configuration of a [`Rwkv5Model`]. It is used to instantiate a RWKV5
|
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 RWKV5 model. Defines the number of different tokens that can be represented by the
|
41 |
+
`inputs_ids` passed when calling [`Rwkv5Model`].
|
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 rwkv5 self_attention module.
|
50 |
+
head_size (`int`, *optional*, defaults to 64): head_size of rwkv5 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 Rwkv5Config, Rwkv5Model
|
72 |
+
|
73 |
+
>>> # Initializing a Rwkv5 configuration
|
74 |
+
>>> configuration = Rwkv5Config()
|
75 |
+
|
76 |
+
>>> # Initializing a model (with random weights) from the configuration
|
77 |
+
>>> model = Rwkv5Model(configuration)
|
78 |
+
|
79 |
+
>>> # Accessing the model configuration
|
80 |
+
>>> configuration = model.config
|
81 |
+
```"""
|
82 |
+
|
83 |
+
model_type = "rwkv5"
|
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_rwkv5.py
ADDED
@@ -0,0 +1,845 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 RWKV5 World model."""
|
16 |
+
|
17 |
+
from dataclasses import dataclass
|
18 |
+
from pathlib import Path
|
19 |
+
from typing import List, Optional, Tuple, Union
|
20 |
+
|
21 |
+
import torch
|
22 |
+
import torch.nn.functional as F
|
23 |
+
import torch.utils.checkpoint
|
24 |
+
from torch import nn
|
25 |
+
from torch.nn import CrossEntropyLoss
|
26 |
+
|
27 |
+
from transformers.modeling_utils import PreTrainedModel
|
28 |
+
from transformers.utils import (
|
29 |
+
ModelOutput,
|
30 |
+
add_code_sample_docstrings,
|
31 |
+
add_start_docstrings,
|
32 |
+
add_start_docstrings_to_model_forward,
|
33 |
+
is_bitsandbytes_available,
|
34 |
+
is_ninja_available,
|
35 |
+
is_torch_cuda_available,
|
36 |
+
logging,
|
37 |
+
)
|
38 |
+
|
39 |
+
from .configuration_rwkv5 import Rwkv5Config
|
40 |
+
|
41 |
+
|
42 |
+
logger = logging.get_logger(__name__)
|
43 |
+
|
44 |
+
_CHECKPOINT_FOR_DOC = "RWKV/rwkv-5-world-1b5"
|
45 |
+
_CONFIG_FOR_DOC = "Rwkv5Config"
|
46 |
+
|
47 |
+
rwkv5_cuda_kernel = None
|
48 |
+
|
49 |
+
|
50 |
+
# Copied from https://github.com/huggingface/transformers/blob/18cbaf13dcaca7145f5652aefb9b19734c56c3cd/src/transformers/models/rwkv/modeling_rwkv.py#L65
|
51 |
+
def load_wkv5_cuda_kernel(head_size):
|
52 |
+
from torch.utils.cpp_extension import load as load_kernel
|
53 |
+
|
54 |
+
global rwkv5_cuda_kernel
|
55 |
+
|
56 |
+
kernel_folder = Path(__file__).parent.resolve()
|
57 |
+
cuda_kernel_files = [kernel_folder / f for f in ["wkv5_op.cpp", "wkv5_cuda.cu"]]
|
58 |
+
|
59 |
+
# Only load the kernel if it's not been loaded yet or if we changed the context length
|
60 |
+
if rwkv5_cuda_kernel is not None and rwkv5_cuda_kernel.head_size == head_size:
|
61 |
+
return
|
62 |
+
|
63 |
+
logger.info(f"Loading CUDA kernel for RWKV5 at head size of {head_size}.")
|
64 |
+
|
65 |
+
flags = [
|
66 |
+
"-res-usage",
|
67 |
+
"--maxrregcount 60",
|
68 |
+
"--use_fast_math",
|
69 |
+
"-O3",
|
70 |
+
"-Xptxas -O3",
|
71 |
+
"--extra-device-vectorization",
|
72 |
+
f"-D_N_={head_size}",
|
73 |
+
]
|
74 |
+
rwkv5_cuda_kernel = load_kernel(
|
75 |
+
name=f"wkv_{head_size}",
|
76 |
+
sources=cuda_kernel_files,
|
77 |
+
verbose=(logging.get_verbosity() == logging.DEBUG),
|
78 |
+
extra_cuda_cflags=flags,
|
79 |
+
)
|
80 |
+
rwkv5_cuda_kernel.head_size = head_size
|
81 |
+
|
82 |
+
|
83 |
+
class Rwkv5LinearAttention(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 |
+
batch, seq_length, hidden_size = key.shape
|
94 |
+
num_heads = time_decay.shape[0]
|
95 |
+
ctx.batch = batch
|
96 |
+
ctx.seq_length = seq_length
|
97 |
+
ctx.hidden_size = hidden_size
|
98 |
+
ctx.num_heads = num_heads
|
99 |
+
e_time_decay = (-torch.exp(time_decay.float())).contiguous()
|
100 |
+
ee_time_decay = (torch.exp(e_time_decay)).contiguous()
|
101 |
+
assert ee_time_decay.dtype == torch.float32
|
102 |
+
ctx.save_for_backward(receptance, key, value, ee_time_decay, e_time_decay, time_first)
|
103 |
+
out = torch.empty(
|
104 |
+
(batch, seq_length, hidden_size),
|
105 |
+
device=receptance.device,
|
106 |
+
dtype=torch.bfloat16,
|
107 |
+
memory_format=torch.contiguous_format,
|
108 |
+
)
|
109 |
+
state = state.clone()
|
110 |
+
rwkv5_cuda_kernel.forward_bf16(
|
111 |
+
batch,
|
112 |
+
seq_length,
|
113 |
+
hidden_size,
|
114 |
+
num_heads,
|
115 |
+
state,
|
116 |
+
receptance,
|
117 |
+
key,
|
118 |
+
value,
|
119 |
+
ee_time_decay,
|
120 |
+
time_first,
|
121 |
+
out,
|
122 |
+
)
|
123 |
+
return out, state
|
124 |
+
|
125 |
+
@staticmethod
|
126 |
+
def backward(ctx, gout):
|
127 |
+
with torch.no_grad():
|
128 |
+
assert gout.dtype == torch.bfloat16
|
129 |
+
batch = ctx.batch
|
130 |
+
seq_length = ctx.seq_length
|
131 |
+
hidden_size = ctx.hidden_size
|
132 |
+
num_heads = ctx.num_heads
|
133 |
+
receptance, key, value, ee_time_decay, e_time_decay, time_first = ctx.saved_tensors
|
134 |
+
|
135 |
+
global_shape = (batch, seq_length, hidden_size)
|
136 |
+
|
137 |
+
# TODO dtype should not be forced here IMO
|
138 |
+
greceptance = torch.empty(
|
139 |
+
global_shape,
|
140 |
+
device=gout.device,
|
141 |
+
requires_grad=False,
|
142 |
+
dtype=torch.bfloat16,
|
143 |
+
memory_format=torch.contiguous_format,
|
144 |
+
)
|
145 |
+
g_key = torch.empty(
|
146 |
+
global_shape,
|
147 |
+
device=gout.device,
|
148 |
+
requires_grad=False,
|
149 |
+
dtype=torch.bfloat16,
|
150 |
+
memory_format=torch.contiguous_format,
|
151 |
+
)
|
152 |
+
g_value = torch.empty(
|
153 |
+
global_shape,
|
154 |
+
device=gout.device,
|
155 |
+
requires_grad=False,
|
156 |
+
dtype=torch.bfloat16,
|
157 |
+
memory_format=torch.contiguous_format,
|
158 |
+
)
|
159 |
+
g_time_decay = torch.empty(
|
160 |
+
(batch, hidden_size),
|
161 |
+
device=gout.device,
|
162 |
+
requires_grad=False,
|
163 |
+
dtype=torch.bfloat16,
|
164 |
+
memory_format=torch.contiguous_format,
|
165 |
+
)
|
166 |
+
g_time_first = torch.empty(
|
167 |
+
(batch, hidden_size),
|
168 |
+
device=gout.device,
|
169 |
+
requires_grad=False,
|
170 |
+
dtype=torch.bfloat16,
|
171 |
+
memory_format=torch.contiguous_format,
|
172 |
+
)
|
173 |
+
rwkv5_cuda_kernel.backward_bf16(
|
174 |
+
batch,
|
175 |
+
seq_length,
|
176 |
+
hidden_size,
|
177 |
+
num_heads,
|
178 |
+
receptance,
|
179 |
+
key,
|
180 |
+
value,
|
181 |
+
ee_time_decay,
|
182 |
+
e_time_decay,
|
183 |
+
time_first,
|
184 |
+
gout,
|
185 |
+
greceptance,
|
186 |
+
g_key,
|
187 |
+
g_value,
|
188 |
+
g_time_decay,
|
189 |
+
g_time_first,
|
190 |
+
)
|
191 |
+
head_size = hidden_size // num_heads
|
192 |
+
g_time_decay = torch.sum(g_time_decay, 0).view(num_heads, head_size)
|
193 |
+
g_time_first = torch.sum(g_time_first, 0).view(num_heads, head_size)
|
194 |
+
return (None, None, None, None, greceptance, g_key, g_value, g_time_decay, g_time_first)
|
195 |
+
|
196 |
+
|
197 |
+
def rwkv5_linear_attention_cpu(receptance, key, value, time_decay, time_first, state):
|
198 |
+
input_dtype = receptance.dtype
|
199 |
+
# For CPU fallback. Will be slower and probably take more memory than the custom CUDA kernel if not executed
|
200 |
+
# within a torch.no_grad.
|
201 |
+
batch, seq_length, hidden_size = receptance.shape
|
202 |
+
num_heads, head_size = time_first.shape
|
203 |
+
key = key.float().view(batch, seq_length, num_heads, head_size).transpose(1, 2).transpose(-2, -1)
|
204 |
+
value = value.float().view(batch, seq_length, num_heads, head_size).transpose(1, 2)
|
205 |
+
receptance = receptance.float().view(batch, seq_length, num_heads, head_size).transpose(1, 2)
|
206 |
+
time_decay = torch.exp(-torch.exp(time_decay.float())).reshape(-1, 1, 1).reshape(num_heads, -1, 1)
|
207 |
+
time_first = time_first.float().reshape(-1, 1, 1).reshape(num_heads, -1, 1)
|
208 |
+
out = torch.zeros_like(key).reshape(batch, seq_length, num_heads, head_size)
|
209 |
+
|
210 |
+
for current_index in range(seq_length):
|
211 |
+
current_receptance = receptance[:, :, current_index:current_index+1, :]
|
212 |
+
current_key = key[:, :, :, current_index:current_index+1]
|
213 |
+
current_value = value[:, :, current_index:current_index+1, :]
|
214 |
+
attention_output = current_key @ current_value
|
215 |
+
out[:, current_index] = (current_receptance @ (time_first * attention_output + state)).squeeze(2)
|
216 |
+
with torch.no_grad():
|
217 |
+
state = attention_output + time_decay * state
|
218 |
+
|
219 |
+
return out, state
|
220 |
+
|
221 |
+
# copied from RWKV but with receptance
|
222 |
+
def RWKV5_linear_attention(training, receptance, key, value, time_decay, time_first, state):
|
223 |
+
no_cuda = any(t.device.type != "cuda" for t in [time_decay, time_first, key, value])
|
224 |
+
# Launching the CUDA kernel for just one token will actually be slower (there is no for loop in the CPU version
|
225 |
+
# in this case).
|
226 |
+
one_token = key.size(1) == 1
|
227 |
+
if not training or rwkv5_cuda_kernel is None or no_cuda or one_token:
|
228 |
+
return rwkv5_linear_attention_cpu(
|
229 |
+
receptance, key, value, time_decay, time_first, state
|
230 |
+
)
|
231 |
+
else:
|
232 |
+
return Rwkv5LinearAttention.apply(receptance, key, value, time_decay, time_first, state)
|
233 |
+
|
234 |
+
|
235 |
+
class Rwkv5SelfAttention(nn.Module):
|
236 |
+
def __init__(self, config, layer_id=0):
|
237 |
+
super().__init__()
|
238 |
+
self.config = config
|
239 |
+
kernel_loaded = rwkv5_cuda_kernel is not None and rwkv5_cuda_kernel.head_size == config.head_size
|
240 |
+
if is_ninja_available() and is_torch_cuda_available() and not kernel_loaded:
|
241 |
+
try:
|
242 |
+
load_wkv5_cuda_kernel(config.head_size)
|
243 |
+
except Exception:
|
244 |
+
logger.info("Could not load the custom CUDA kernel for RWKV5 attention.")
|
245 |
+
self.layer_id = layer_id
|
246 |
+
hidden_size = config.hidden_size
|
247 |
+
attention_hidden_size = config.attention_hidden_size
|
248 |
+
self.attention_hidden_size = attention_hidden_size
|
249 |
+
head_size = config.head_size
|
250 |
+
num_heads = attention_hidden_size // head_size
|
251 |
+
|
252 |
+
self.time_decay = nn.Parameter(torch.empty(num_heads, head_size))
|
253 |
+
self.time_faaaa = nn.Parameter(torch.empty(num_heads, head_size))
|
254 |
+
self.time_mix_gate = nn.Parameter(torch.empty(1, 1, hidden_size))
|
255 |
+
|
256 |
+
self.time_mix_key = nn.Parameter(torch.empty(1, 1, hidden_size))
|
257 |
+
self.time_mix_value = nn.Parameter(torch.empty(1, 1, hidden_size))
|
258 |
+
self.time_mix_receptance = nn.Parameter(torch.empty(1, 1, hidden_size))
|
259 |
+
|
260 |
+
self.time_shift = nn.ZeroPad2d((0, 0, 1, -1))
|
261 |
+
self.key = nn.Linear(hidden_size, attention_hidden_size, bias=False)
|
262 |
+
self.value = nn.Linear(hidden_size, attention_hidden_size, bias=False)
|
263 |
+
self.receptance = nn.Linear(hidden_size, attention_hidden_size, bias=False)
|
264 |
+
self.gate = nn.Linear(hidden_size, attention_hidden_size, bias=False)
|
265 |
+
self.output = nn.Linear(attention_hidden_size, hidden_size, bias=False)
|
266 |
+
self.ln_x = nn.GroupNorm(num_heads, hidden_size)
|
267 |
+
|
268 |
+
def extract_key_value(self, hidden, state=None):
|
269 |
+
# Mix hidden with the previous timestep to produce key, value, receptance
|
270 |
+
if hidden.size(1) == 1 and state is not None:
|
271 |
+
shifted = state[0][:, :, self.layer_id]
|
272 |
+
else:
|
273 |
+
shifted = self.time_shift(hidden)
|
274 |
+
if state is not None:
|
275 |
+
shifted[:, 0] = state[0][:, :, self.layer_id]
|
276 |
+
if len(shifted.size()) == 2:
|
277 |
+
shifted = shifted.unsqueeze(1)
|
278 |
+
|
279 |
+
key = hidden * self.time_mix_key + shifted * (1 - self.time_mix_key)
|
280 |
+
value = hidden * self.time_mix_value + shifted * (1 - self.time_mix_value)
|
281 |
+
receptance = hidden * self.time_mix_receptance + shifted * (1 - self.time_mix_receptance)
|
282 |
+
gate = hidden * self.time_mix_gate + shifted * (1 - self.time_mix_gate)
|
283 |
+
|
284 |
+
key = self.key(key)
|
285 |
+
value = self.value(value)
|
286 |
+
receptance = self.receptance(receptance)
|
287 |
+
gate = F.silu(self.gate(gate))
|
288 |
+
|
289 |
+
if state is not None:
|
290 |
+
state[0][:, :, self.layer_id] = hidden[:, -1]
|
291 |
+
|
292 |
+
return receptance, key, value, gate, state
|
293 |
+
|
294 |
+
def forward(self, hidden, state=None, use_cache=False, seq_mode=True):
|
295 |
+
receptance, key, value, gate, state = self.extract_key_value(hidden, state=state)
|
296 |
+
|
297 |
+
B,T,C = receptance.shape
|
298 |
+
H, S = self.time_faaaa.shape
|
299 |
+
|
300 |
+
layer_state = state[1][:, :, :, :, self.layer_id] if state is not None else None
|
301 |
+
out, layer_state = RWKV5_linear_attention(
|
302 |
+
self.training, receptance, key, value, self.time_decay, self.time_faaaa, layer_state
|
303 |
+
)
|
304 |
+
|
305 |
+
if layer_state is not None:
|
306 |
+
state[1][:, :, :, :, self.layer_id] = layer_state
|
307 |
+
|
308 |
+
out = out.reshape(B * T, H * S)
|
309 |
+
out = F.group_norm(out / self.config.head_size_divisor, 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)
|
310 |
+
out = out.to(dtype=hidden.dtype) * gate
|
311 |
+
out = self.output(out)
|
312 |
+
return out, state
|
313 |
+
|
314 |
+
# Copied from rwkv exceot for the intermediate size
|
315 |
+
class Rwkv5FeedForward(nn.Module):
|
316 |
+
def __init__(self, config, layer_id=0):
|
317 |
+
super().__init__()
|
318 |
+
self.config = config
|
319 |
+
self.layer_id = layer_id
|
320 |
+
hidden_size = config.hidden_size
|
321 |
+
intermediate_size = (
|
322 |
+
config.intermediate_size
|
323 |
+
if config.intermediate_size is not None
|
324 |
+
else int((config.hidden_size * 3.5) // 32 * 32)
|
325 |
+
)
|
326 |
+
|
327 |
+
self.time_shift = nn.ZeroPad2d((0, 0, 1, -1))
|
328 |
+
self.time_mix_key = nn.Parameter(torch.empty(1, 1, hidden_size))
|
329 |
+
self.time_mix_receptance = nn.Parameter(torch.empty(1, 1, hidden_size))
|
330 |
+
|
331 |
+
self.key = nn.Linear(hidden_size, intermediate_size, bias=False)
|
332 |
+
self.receptance = nn.Linear(hidden_size, hidden_size, bias=False)
|
333 |
+
self.value = nn.Linear(intermediate_size, hidden_size, bias=False)
|
334 |
+
|
335 |
+
def forward(self, hidden, state=None):
|
336 |
+
if hidden.size(1) == 1 and state is not None:
|
337 |
+
shifted = state[2][:, :, self.layer_id]
|
338 |
+
else:
|
339 |
+
shifted = self.time_shift(hidden)
|
340 |
+
if state is not None:
|
341 |
+
shifted[:, 0] = state[2][:, :, self.layer_id]
|
342 |
+
if len(shifted.size()) == 2:
|
343 |
+
shifted = shifted.unsqueeze(1)
|
344 |
+
key = hidden * self.time_mix_key + shifted * (1 - self.time_mix_key)
|
345 |
+
receptance = hidden * self.time_mix_receptance + shifted * (1 - self.time_mix_receptance)
|
346 |
+
|
347 |
+
key = torch.square(torch.relu(self.key(key)))
|
348 |
+
value = self.value(key)
|
349 |
+
receptance = torch.sigmoid(self.receptance(receptance))
|
350 |
+
|
351 |
+
if state is not None:
|
352 |
+
state[2][:, :, self.layer_id] = hidden[:, -1]
|
353 |
+
|
354 |
+
return receptance * value, state
|
355 |
+
|
356 |
+
|
357 |
+
# Copied from transformers.models.rwkv.modeling_rwkv.RwkvBlock with Rwkv->Rwkv5
|
358 |
+
class Rwkv5Block(nn.Module):
|
359 |
+
def __init__(self, config, layer_id):
|
360 |
+
super().__init__()
|
361 |
+
self.config = config
|
362 |
+
self.layer_id = layer_id
|
363 |
+
|
364 |
+
if layer_id == 0:
|
365 |
+
self.pre_ln = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_epsilon)
|
366 |
+
|
367 |
+
self.ln1 = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_epsilon)
|
368 |
+
self.ln2 = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_epsilon)
|
369 |
+
|
370 |
+
self.attention = Rwkv5SelfAttention(config, layer_id)
|
371 |
+
self.feed_forward = Rwkv5FeedForward(config, layer_id)
|
372 |
+
|
373 |
+
def forward(self, hidden, state=None, use_cache=False, output_attentions=False, seq_mode=True):
|
374 |
+
if self.layer_id == 0:
|
375 |
+
hidden = self.pre_ln(hidden)
|
376 |
+
attention, state = self.attention(self.ln1(hidden), state=state, use_cache=use_cache, seq_mode=seq_mode)
|
377 |
+
hidden = hidden + attention
|
378 |
+
|
379 |
+
feed_forward, state = self.feed_forward(self.ln2(hidden), state=state)
|
380 |
+
hidden = hidden + feed_forward
|
381 |
+
|
382 |
+
outputs = (hidden, state)
|
383 |
+
if output_attentions:
|
384 |
+
outputs += (attention,)
|
385 |
+
else:
|
386 |
+
outputs += (None,)
|
387 |
+
|
388 |
+
return outputs
|
389 |
+
|
390 |
+
|
391 |
+
# Copied from transformers.models.rwkv.modeling_rwkv.RwkvPreTrainedModel with Rwkv->Rwkv5
|
392 |
+
class Rwkv5PreTrainedModel(PreTrainedModel):
|
393 |
+
"""
|
394 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
395 |
+
models.
|
396 |
+
"""
|
397 |
+
|
398 |
+
config_class = Rwkv5Config
|
399 |
+
base_model_prefix = "rwkv5"
|
400 |
+
_no_split_modules = ["Rwkv5Block"]
|
401 |
+
_keep_in_fp32_modules = ["time_decay", "time_first"]
|
402 |
+
supports_gradient_checkpointing = True
|
403 |
+
|
404 |
+
def _init_weights(self, module):
|
405 |
+
"""Initialize the weights."""
|
406 |
+
if isinstance(module, Rwkv5SelfAttention):
|
407 |
+
layer_id = module.layer_id
|
408 |
+
num_hidden_layers = module.config.num_hidden_layers
|
409 |
+
hidden_size = module.config.hidden_size
|
410 |
+
attention_hidden_size = module.attention_hidden_size
|
411 |
+
head_size = module.config.head_size
|
412 |
+
num_heads = attention_hidden_size // head_size
|
413 |
+
|
414 |
+
ratio_0_to_1 = layer_id / (num_hidden_layers - 1) # 0 to 1
|
415 |
+
ratio_1_to_almost0 = 1.0 - (layer_id / num_hidden_layers) # 1 to ~0
|
416 |
+
|
417 |
+
time_weight = torch.tensor(
|
418 |
+
[i / hidden_size for i in range(hidden_size)],
|
419 |
+
dtype=module.time_mix_key.dtype,
|
420 |
+
device=module.time_mix_key.device,
|
421 |
+
)
|
422 |
+
time_weight = time_weight[None, None, :]
|
423 |
+
|
424 |
+
decay_speed = [
|
425 |
+
-6.0 + 5.0 * (h / (attention_hidden_size - 1)) ** (0.7 + 1.3 * ratio_0_to_1)
|
426 |
+
for h in range(attention_hidden_size)
|
427 |
+
]
|
428 |
+
decay_speed = torch.tensor(decay_speed, dtype=module.time_decay.dtype, device=module.time_decay.device)
|
429 |
+
tmp = torch.tensor(
|
430 |
+
[
|
431 |
+
(1.0 - (i / (attention_hidden_size - 1.0))) * ratio_0_to_1 + 0.1 * ((i + 1) % 3 - 1)
|
432 |
+
for i in range(attention_hidden_size)
|
433 |
+
],
|
434 |
+
dtype=module.time_faaaa.dtype,
|
435 |
+
device=module.time_faaaa.device,
|
436 |
+
)
|
437 |
+
|
438 |
+
with torch.no_grad():
|
439 |
+
module.time_decay.data = decay_speed.reshape(num_heads, head_size)
|
440 |
+
module.time_faaaa.data = tmp.reshape(num_heads, head_size)
|
441 |
+
module.time_mix_key.data = torch.pow(time_weight, ratio_1_to_almost0)
|
442 |
+
|
443 |
+
module.time_mix_value.data = torch.pow(time_weight, ratio_1_to_almost0) + 0.3 * ratio_0_to_1
|
444 |
+
module.time_mix_receptance.data = torch.pow(time_weight, 0.5 * ratio_1_to_almost0)
|
445 |
+
module.time_mix_gate.data = torch.pow(time_weight, 0.5 * ratio_1_to_almost0)
|
446 |
+
|
447 |
+
elif isinstance(module, Rwkv5FeedForward):
|
448 |
+
layer_id = module.layer_id
|
449 |
+
num_hidden_layers = module.config.num_hidden_layers
|
450 |
+
hidden_size = module.config.hidden_size
|
451 |
+
|
452 |
+
ratio_1_to_almost0 = 1.0 - (layer_id / num_hidden_layers) # 1 to ~0
|
453 |
+
|
454 |
+
time_weight = torch.tensor(
|
455 |
+
[i / hidden_size for i in range(hidden_size)],
|
456 |
+
dtype=module.time_mix_key.dtype,
|
457 |
+
device=module.time_mix_key.device,
|
458 |
+
)
|
459 |
+
time_weight = time_weight[None, None, :]
|
460 |
+
|
461 |
+
with torch.no_grad():
|
462 |
+
module.time_mix_key.data = torch.pow(time_weight, ratio_1_to_almost0)
|
463 |
+
module.time_mix_receptance.data = torch.pow(time_weight, ratio_1_to_almost0)
|
464 |
+
|
465 |
+
|
466 |
+
# Copied from transformers.models.rwkv.modeling_rwkv.RwkvOutput with Rwkv->Rwkv5
|
467 |
+
@dataclass
|
468 |
+
class Rwkv5Output(ModelOutput):
|
469 |
+
"""
|
470 |
+
Class for the RWKV5 model outputs.
|
471 |
+
|
472 |
+
Args:
|
473 |
+
last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
|
474 |
+
Sequence of hidden-states at the output of the last layer of the model.
|
475 |
+
state (list of five `torch.FloatTensor` of shape `(batch_size, hidden_size, num_hidden_layers)`):
|
476 |
+
The state of the model at the last time step. Can be used in a forward method with the next `input_ids` to
|
477 |
+
avoid providing the old `input_ids`.
|
478 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
479 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
|
480 |
+
one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of
|
481 |
+
the model at the output of each layer plus the optional initial embedding outputs.
|
482 |
+
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
483 |
+
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
484 |
+
sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in
|
485 |
+
the self-attention heads.
|
486 |
+
"""
|
487 |
+
|
488 |
+
last_hidden_state: torch.FloatTensor = None
|
489 |
+
state: Optional[List[torch.FloatTensor]] = None
|
490 |
+
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
|
491 |
+
attentions: Optional[Tuple[torch.FloatTensor]] = None
|
492 |
+
|
493 |
+
|
494 |
+
# Copied from transformers.models.rwkv.modeling_rwkv.RwkvCausalLMOutput with Rwkv->Rwkv5
|
495 |
+
@dataclass
|
496 |
+
class Rwkv5CausalLMOutput(ModelOutput):
|
497 |
+
"""
|
498 |
+
Base class for causal language model (or autoregressive) outputs.
|
499 |
+
|
500 |
+
Args:
|
501 |
+
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
|
502 |
+
Language modeling loss (for next-token prediction).
|
503 |
+
logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
|
504 |
+
Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
|
505 |
+
state (list of five `torch.FloatTensor` of shape `(batch_size, hidden_size, num_hidden_layers)`):
|
506 |
+
The state of the model at the last time step. Can be used in a forward method with the next `input_ids` to
|
507 |
+
avoid providing the old `input_ids`.
|
508 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
509 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
|
510 |
+
one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of
|
511 |
+
the model at the output of each layer plus the optional initial embedding outputs.
|
512 |
+
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
513 |
+
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
514 |
+
sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in
|
515 |
+
the self-attention heads.
|
516 |
+
"""
|
517 |
+
|
518 |
+
loss: Optional[torch.FloatTensor] = None
|
519 |
+
logits: torch.FloatTensor = None
|
520 |
+
state: Optional[List[torch.FloatTensor]] = None
|
521 |
+
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
|
522 |
+
attentions: Optional[Tuple[torch.FloatTensor]] = None
|
523 |
+
|
524 |
+
|
525 |
+
RWKV5_START_DOCSTRING = r"""
|
526 |
+
This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
|
527 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
528 |
+
etc.) This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module)
|
529 |
+
subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to
|
530 |
+
general usage and behavior.
|
531 |
+
|
532 |
+
Parameters:
|
533 |
+
config ([`Rwkv5Config`]): Model configuration class with all the parameters of the model.
|
534 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
535 |
+
configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
536 |
+
"""
|
537 |
+
|
538 |
+
RWKV5_INPUTS_DOCSTRING = r"""
|
539 |
+
Args:
|
540 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`):
|
541 |
+
`input_ids_length` = `sequence_length` if `past_key_values` is `None` else
|
542 |
+
`past_key_values[0][0].shape[-2]` (`sequence_length` of input past key value states). Indices of input
|
543 |
+
sequence tokens in the vocabulary. If `past_key_values` is used, only `input_ids` that do not have their
|
544 |
+
past calculated should be passed as `input_ids`. Indices can be obtained using [`AutoTokenizer`]. See
|
545 |
+
[`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. [What are input
|
546 |
+
IDs?](../glossary#input-ids)
|
547 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
548 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
549 |
+
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
|
550 |
+
model's internal embedding lookup matrix.
|
551 |
+
state (tuple of five `torch.FloatTensor` of shape `(batch_size, hidden_size, num_hidden_layers)`, *optional*):
|
552 |
+
If passed along, the model uses the previous state in all the blocks (which will give the output for the
|
553 |
+
`input_ids` provided as if the model add `state_input_ids + input_ids` as context).
|
554 |
+
use_cache (`bool`, *optional*):
|
555 |
+
If set to `True`, the last state is returned and can be used to quickly generate the next logits.
|
556 |
+
output_attentions (`bool`, *optional*):
|
557 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
558 |
+
tensors for more detail.
|
559 |
+
output_hidden_states (`bool`, *optional*):
|
560 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
561 |
+
more detail.
|
562 |
+
return_dict (`bool`, *optional*):
|
563 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
564 |
+
"""
|
565 |
+
|
566 |
+
|
567 |
+
@add_start_docstrings(
|
568 |
+
"The bare RWKV5 Model transformer outputting raw hidden-states without any specific head on top.",
|
569 |
+
RWKV5_START_DOCSTRING,
|
570 |
+
)
|
571 |
+
class Rwkv5Model(Rwkv5PreTrainedModel):
|
572 |
+
def __init__(self, config):
|
573 |
+
super().__init__(config)
|
574 |
+
|
575 |
+
self.embeddings = nn.Embedding(config.vocab_size, config.hidden_size)
|
576 |
+
self.blocks = nn.ModuleList([Rwkv5Block(config, layer_id=idx) for idx in range(config.num_hidden_layers)])
|
577 |
+
self.ln_out = nn.LayerNorm(config.hidden_size)
|
578 |
+
|
579 |
+
self.layers_are_rescaled = False
|
580 |
+
self.gradient_checkpointing = False
|
581 |
+
|
582 |
+
# Initialize weights and apply final processing
|
583 |
+
self.post_init()
|
584 |
+
|
585 |
+
def get_input_embeddings(self):
|
586 |
+
return self.embeddings
|
587 |
+
|
588 |
+
def set_input_embeddings(self, new_embeddings):
|
589 |
+
self.embeddings = new_embeddings
|
590 |
+
|
591 |
+
@add_start_docstrings_to_model_forward(RWKV5_INPUTS_DOCSTRING)
|
592 |
+
@add_code_sample_docstrings(
|
593 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
594 |
+
output_type=Rwkv5Output,
|
595 |
+
config_class=_CONFIG_FOR_DOC,
|
596 |
+
)
|
597 |
+
def forward(
|
598 |
+
self,
|
599 |
+
input_ids: Optional[torch.LongTensor] = None,
|
600 |
+
attention_mask: Optional[torch.LongTensor] = None, # noqa
|
601 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
602 |
+
state: Optional[List[torch.FloatTensor]] = None,
|
603 |
+
use_cache: Optional[bool] = None,
|
604 |
+
output_attentions: Optional[bool] = None,
|
605 |
+
output_hidden_states: Optional[bool] = None,
|
606 |
+
return_dict: Optional[bool] = None,
|
607 |
+
) -> Union[Tuple, Rwkv5Output]:
|
608 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
609 |
+
output_hidden_states = (
|
610 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
611 |
+
)
|
612 |
+
# FIXME - training is supportable with the CUDA code
|
613 |
+
# rwkv5 only support inference in huggingface.
|
614 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
615 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
616 |
+
|
617 |
+
if self.training == self.layers_are_rescaled and (
|
618 |
+
self.embeddings.weight.dtype == torch.float16 or self.embeddings.weight.dtype == torch.bfloat16
|
619 |
+
):
|
620 |
+
self._rescale_layers()
|
621 |
+
|
622 |
+
if input_ids is not None and inputs_embeds is not None:
|
623 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
624 |
+
elif input_ids is None and inputs_embeds is None:
|
625 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
626 |
+
|
627 |
+
if inputs_embeds is None:
|
628 |
+
inputs_embeds = self.embeddings(input_ids)
|
629 |
+
|
630 |
+
if state is None:
|
631 |
+
state = []
|
632 |
+
head_size = self.config.head_size
|
633 |
+
num_heads = self.config.attention_hidden_size // head_size
|
634 |
+
state_attn_x = torch.zeros(
|
635 |
+
(inputs_embeds.size(0), self.config.hidden_size, self.config.num_hidden_layers),
|
636 |
+
dtype=inputs_embeds.dtype,
|
637 |
+
requires_grad=False,
|
638 |
+
device=inputs_embeds.device,
|
639 |
+
).contiguous()
|
640 |
+
state_attn_kv = torch.zeros(
|
641 |
+
(
|
642 |
+
inputs_embeds.size(0),
|
643 |
+
num_heads,
|
644 |
+
head_size,
|
645 |
+
head_size,
|
646 |
+
self.config.num_hidden_layers,
|
647 |
+
),
|
648 |
+
dtype=torch.float32,
|
649 |
+
requires_grad=False,
|
650 |
+
device=inputs_embeds.device,
|
651 |
+
).contiguous()
|
652 |
+
state_ffn_x = torch.zeros(
|
653 |
+
(inputs_embeds.size(0), self.config.hidden_size, self.config.num_hidden_layers),
|
654 |
+
dtype=inputs_embeds.dtype,
|
655 |
+
requires_grad=False,
|
656 |
+
device=inputs_embeds.device,
|
657 |
+
).contiguous()
|
658 |
+
state.append(state_attn_x)
|
659 |
+
state.append(state_attn_kv)
|
660 |
+
state.append(state_ffn_x)
|
661 |
+
|
662 |
+
seq_mode = inputs_embeds.shape[1] > 1
|
663 |
+
hidden_states = inputs_embeds
|
664 |
+
|
665 |
+
all_self_attentions = () if output_attentions else None
|
666 |
+
all_hidden_states = () if output_hidden_states else None
|
667 |
+
for idx, block in enumerate(self.blocks):
|
668 |
+
hidden_states, state, attentions = block(
|
669 |
+
hidden_states, state=state, use_cache=use_cache, output_attentions=output_attentions, seq_mode=seq_mode
|
670 |
+
)
|
671 |
+
if (
|
672 |
+
self.layers_are_rescaled
|
673 |
+
and self.config.rescale_every > 0
|
674 |
+
and (idx + 1) % self.config.rescale_every == 0
|
675 |
+
):
|
676 |
+
hidden_states = hidden_states / 2
|
677 |
+
|
678 |
+
if output_hidden_states:
|
679 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
680 |
+
|
681 |
+
if output_attentions:
|
682 |
+
all_self_attentions = all_self_attentions + (attentions,)
|
683 |
+
|
684 |
+
hidden_states = self.ln_out(hidden_states)
|
685 |
+
|
686 |
+
if output_hidden_states:
|
687 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
688 |
+
|
689 |
+
if not return_dict:
|
690 |
+
return (hidden_states, state, all_hidden_states, all_self_attentions)
|
691 |
+
|
692 |
+
return Rwkv5Output(
|
693 |
+
last_hidden_state=hidden_states,
|
694 |
+
state=state,
|
695 |
+
hidden_states=all_hidden_states, # None
|
696 |
+
attentions=all_self_attentions, # None
|
697 |
+
)
|
698 |
+
|
699 |
+
def _rescale_layers(self):
|
700 |
+
# Layers should be rescaled for inference only.
|
701 |
+
if self.layers_are_rescaled == (not self.training):
|
702 |
+
return
|
703 |
+
if self.config.rescale_every > 0:
|
704 |
+
with torch.no_grad():
|
705 |
+
for block_id, block in enumerate(self.blocks):
|
706 |
+
if self.training:
|
707 |
+
block.attention.output.weight.mul_(2 ** int(block_id // self.config.rescale_every))
|
708 |
+
block.feed_forward.value.weight.mul_(2 ** int(block_id // self.config.rescale_every))
|
709 |
+
else:
|
710 |
+
# Deal with quantization statistics
|
711 |
+
if hasattr(block.attention.output.weight, "SCB"):
|
712 |
+
block.attention.output.weight.SCB.div_(2 ** int(block_id // self.config.rescale_every))
|
713 |
+
block.feed_forward.value.weight.SCB.div_(2 ** int(block_id // self.config.rescale_every))
|
714 |
+
elif hasattr(block.attention.output.weight, "quant_state"):
|
715 |
+
self._bnb_4bit_dequantize_and_rescale(block.attention.output, block_id)
|
716 |
+
self._bnb_4bit_dequantize_and_rescale(block.feed_forward.value, block_id)
|
717 |
+
else:
|
718 |
+
block.attention.output.weight.div_(2 ** int(block_id // self.config.rescale_every))
|
719 |
+
block.feed_forward.value.weight.div_(2 ** int(block_id // self.config.rescale_every))
|
720 |
+
|
721 |
+
self.layers_are_rescaled = not self.training
|
722 |
+
|
723 |
+
def _bnb_4bit_dequantize_and_rescale(self, target_layer, block_id):
|
724 |
+
r"""
|
725 |
+
Perform the dequantization and rescaling of the weights of a given layer. After that operation the layer will
|
726 |
+
be quantized again.
|
727 |
+
"""
|
728 |
+
if not is_bitsandbytes_available():
|
729 |
+
raise ImportError("Please install bitsandbytes to use this method.")
|
730 |
+
import bitsandbytes as bnb
|
731 |
+
|
732 |
+
dequant_weights = bnb.functional.dequantize_4bit(target_layer.weight.data, target_layer.weight.quant_state)
|
733 |
+
|
734 |
+
dequant_weights.div_(2 ** int(block_id // self.config.rescale_every))
|
735 |
+
|
736 |
+
# re-quantize the model:
|
737 |
+
# we need to put it first on CPU then back to the device
|
738 |
+
# this will create an overhead :/
|
739 |
+
# We set requires_grad=False as we cannot compute gradients on top of 4bit parameters anyway and to avoid
|
740 |
+
# bugs with bnb
|
741 |
+
quant_weight = bnb.nn.Params4bit(dequant_weights.to("cpu"), requires_grad=False).to(dequant_weights.device)
|
742 |
+
setattr(target_layer, "weight", quant_weight)
|
743 |
+
|
744 |
+
|
745 |
+
# copied from HuggingFace https://github.com/huggingface/transformers/blob/main/src/transformers/models/rwkv/modeling_rwkv.py
|
746 |
+
@add_start_docstrings(
|
747 |
+
"""
|
748 |
+
The RWKV5 Model transformer with a language modeling head on top (linear layer with weights tied to the input
|
749 |
+
embeddings).
|
750 |
+
""",
|
751 |
+
RWKV5_START_DOCSTRING,
|
752 |
+
)
|
753 |
+
# Copied from transformers.models.rwkv.modeling_rwkv.RwkvForCausalLM with Rwkv->Rwkv5
|
754 |
+
class Rwkv5ForCausalLM(Rwkv5PreTrainedModel):
|
755 |
+
_tied_weights_keys = ["head.weight"]
|
756 |
+
|
757 |
+
def __init__(self, config):
|
758 |
+
super().__init__(config)
|
759 |
+
self.rwkv = Rwkv5Model(config)
|
760 |
+
self.head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
761 |
+
|
762 |
+
# Initialize weights and apply final processing
|
763 |
+
self.post_init()
|
764 |
+
|
765 |
+
def get_output_embeddings(self):
|
766 |
+
return self.head
|
767 |
+
|
768 |
+
def set_output_embeddings(self, new_embeddings):
|
769 |
+
self.head = new_embeddings
|
770 |
+
|
771 |
+
def prepare_inputs_for_generation(self, input_ids, state=None, inputs_embeds=None, **kwargs):
|
772 |
+
# only last token for inputs_ids if the state is passed along.
|
773 |
+
if state is not None:
|
774 |
+
input_ids = input_ids[:, -1].unsqueeze(-1)
|
775 |
+
|
776 |
+
# if `inputs_embeds` are passed, we only want to use them in the 1st generation step
|
777 |
+
if inputs_embeds is not None and state is None:
|
778 |
+
model_inputs = {"inputs_embeds": inputs_embeds}
|
779 |
+
else:
|
780 |
+
model_inputs = {"input_ids": input_ids}
|
781 |
+
|
782 |
+
model_inputs["state"] = state
|
783 |
+
return model_inputs
|
784 |
+
|
785 |
+
@add_start_docstrings_to_model_forward(RWKV5_INPUTS_DOCSTRING)
|
786 |
+
@add_code_sample_docstrings(
|
787 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
788 |
+
output_type=Rwkv5CausalLMOutput,
|
789 |
+
config_class=_CONFIG_FOR_DOC,
|
790 |
+
)
|
791 |
+
def forward(
|
792 |
+
self,
|
793 |
+
input_ids: Optional[torch.LongTensor] = None,
|
794 |
+
attention_mask: Optional[torch.LongTensor] = None,
|
795 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
796 |
+
state: Optional[List[torch.FloatTensor]] = None,
|
797 |
+
labels: Optional[torch.LongTensor] = None,
|
798 |
+
use_cache: Optional[bool] = None,
|
799 |
+
output_attentions: Optional[bool] = None,
|
800 |
+
output_hidden_states: Optional[bool] = None,
|
801 |
+
return_dict: Optional[bool] = None,
|
802 |
+
) -> Union[Tuple, Rwkv5CausalLMOutput]:
|
803 |
+
r"""
|
804 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
805 |
+
Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
|
806 |
+
`labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
|
807 |
+
are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
|
808 |
+
"""
|
809 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
810 |
+
|
811 |
+
outputs = self.rwkv(
|
812 |
+
input_ids,
|
813 |
+
inputs_embeds=inputs_embeds,
|
814 |
+
state=state,
|
815 |
+
use_cache=use_cache,
|
816 |
+
output_attentions=output_attentions,
|
817 |
+
output_hidden_states=output_hidden_states,
|
818 |
+
return_dict=return_dict,
|
819 |
+
)
|
820 |
+
hidden_states = outputs[0]
|
821 |
+
|
822 |
+
logits = self.head(hidden_states)
|
823 |
+
|
824 |
+
loss = None
|
825 |
+
if labels is not None:
|
826 |
+
# move labels to correct device to enable model parallelism
|
827 |
+
labels = labels.to(logits.device)
|
828 |
+
# Shift so that tokens < n predict n
|
829 |
+
shift_logits = logits[..., :-1, :].contiguous()
|
830 |
+
shift_labels = labels[..., 1:].contiguous()
|
831 |
+
# Flatten the tokens
|
832 |
+
loss_fct = CrossEntropyLoss()
|
833 |
+
loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
|
834 |
+
|
835 |
+
if not return_dict:
|
836 |
+
output = (logits,) + outputs[1:]
|
837 |
+
return ((loss,) + output) if loss is not None else output
|
838 |
+
|
839 |
+
return Rwkv5CausalLMOutput(
|
840 |
+
loss=loss,
|
841 |
+
logits=logits,
|
842 |
+
state=outputs.state,
|
843 |
+
hidden_states=outputs.hidden_states,
|
844 |
+
attentions=outputs.attentions,
|
845 |
+
)
|
pytorch_model.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:270b507b47e08b5f71442380a08668567124a77ea0b1d2e273f85751bc795aa3
|
3 |
+
size 6126083713
|
special_tokens_map.json
ADDED
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"bos_token": "<s>",
|
3 |
+
"eos_token": "<s>",
|
4 |
+
"pad_token": "<s>",
|
5 |
+
"unk_token": "<s>"
|
6 |
+
}
|
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))
|
tokenization_rwkv_world.py
ADDED
@@ -0,0 +1,549 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2018 The Open AI Team Authors and The HuggingFace Inc. team.
|
3 |
+
#
|
4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
5 |
+
# you may not use this file except in compliance with the License.
|
6 |
+
# You may obtain a copy of the License at
|
7 |
+
#
|
8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
9 |
+
#
|
10 |
+
# Unless required by applicable law or agreed to in writing, software
|
11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
13 |
+
# See the License for the specific language governing permissions and
|
14 |
+
# limitations under the License.
|
15 |
+
"""Tokenization classes for RWKV5."""
|
16 |
+
|
17 |
+
import json
|
18 |
+
import os
|
19 |
+
from typing import TYPE_CHECKING, List, Optional, Tuple, Union
|
20 |
+
|
21 |
+
from transformers.tokenization_utils import PreTrainedTokenizer
|
22 |
+
from transformers.tokenization_utils_base import (
|
23 |
+
BatchEncoding,
|
24 |
+
EncodedInput,
|
25 |
+
TextInput,
|
26 |
+
TruncationStrategy,
|
27 |
+
)
|
28 |
+
from transformers.utils import PaddingStrategy, TensorType, logging, to_py_obj
|
29 |
+
|
30 |
+
|
31 |
+
if TYPE_CHECKING:
|
32 |
+
from transformers.pipelines.conversational import Conversation
|
33 |
+
|
34 |
+
logger = logging.get_logger(__name__)
|
35 |
+
|
36 |
+
VOCAB_FILES_NAMES = {
|
37 |
+
"vocab_file": "rwkv_vocab_v20230424.txt",
|
38 |
+
}
|
39 |
+
PRETRAINED_VOCAB_FILES_MAP = {
|
40 |
+
"vocab_file": {
|
41 |
+
"RWKV/rwkv-5-world-169m": "https://huggingface.co/RWKV/rwkv-5-world-169m/blob/main/rwkv_vocab_v20230424.txt",
|
42 |
+
},
|
43 |
+
}
|
44 |
+
|
45 |
+
|
46 |
+
class TRIE:
|
47 |
+
__slots__ = tuple("ch,to,values,front".split(","))
|
48 |
+
to: list
|
49 |
+
values: set
|
50 |
+
|
51 |
+
def __init__(self, front=None, ch=None):
|
52 |
+
self.ch = ch
|
53 |
+
self.to = [None for ch in range(256)]
|
54 |
+
self.values = set()
|
55 |
+
self.front = front
|
56 |
+
|
57 |
+
def __repr__(self):
|
58 |
+
fr = self
|
59 |
+
ret = []
|
60 |
+
while fr is not None:
|
61 |
+
if fr.ch is not None:
|
62 |
+
ret.append(fr.ch)
|
63 |
+
fr = fr.front
|
64 |
+
return "<TRIE %s %s>" % (ret[::-1], self.values)
|
65 |
+
|
66 |
+
def add(self, key: bytes, idx: int = 0, val=None):
|
67 |
+
if idx == len(key):
|
68 |
+
if val is None:
|
69 |
+
val = key
|
70 |
+
self.values.add(val)
|
71 |
+
return self
|
72 |
+
ch = key[idx]
|
73 |
+
if self.to[ch] is None:
|
74 |
+
self.to[ch] = TRIE(front=self, ch=ch)
|
75 |
+
return self.to[ch].add(key, idx=idx + 1, val=val)
|
76 |
+
|
77 |
+
def find_longest(self, key: bytes, idx: int = 0):
|
78 |
+
u: TRIE = self
|
79 |
+
ch: int = key[idx]
|
80 |
+
|
81 |
+
while u.to[ch] is not None:
|
82 |
+
u = u.to[ch]
|
83 |
+
idx += 1
|
84 |
+
if u.values:
|
85 |
+
ret = idx, u, u.values
|
86 |
+
if idx == len(key):
|
87 |
+
break
|
88 |
+
ch = key[idx]
|
89 |
+
return ret
|
90 |
+
|
91 |
+
|
92 |
+
class RWKVWorldTokenizer(PreTrainedTokenizer):
|
93 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
94 |
+
model_input_names = ["input_ids", "attention_mask"]
|
95 |
+
|
96 |
+
def __init__(self, vocab_file, errors="replace", pad_token="0", **kwargs):
|
97 |
+
self.add_bos_token = False
|
98 |
+
self.encoder = {}
|
99 |
+
sorted = [] # must be already sorted
|
100 |
+
with open(vocab_file, "r", encoding="utf-8") as f:
|
101 |
+
lines = f.readlines()
|
102 |
+
for l in lines:
|
103 |
+
idx = int(l[: l.index(" ")])
|
104 |
+
x = eval(l[l.index(" ") : l.rindex(" ")])
|
105 |
+
x = x.encode("utf-8") if isinstance(x, str) else x
|
106 |
+
assert isinstance(x, bytes)
|
107 |
+
assert len(x) == int(l[l.rindex(" ") :])
|
108 |
+
sorted += [x]
|
109 |
+
self.encoder[idx] = x
|
110 |
+
|
111 |
+
self.decoder = {}
|
112 |
+
for k, v in self.encoder.items():
|
113 |
+
self.decoder[v] = int(k)
|
114 |
+
|
115 |
+
self.trie = TRIE()
|
116 |
+
for t, i in self.decoder.items():
|
117 |
+
_ = self.trie.add(t, val=(t, i))
|
118 |
+
self.errors = errors # how to handle errors in decoding
|
119 |
+
self.cache = {}
|
120 |
+
self.first_max_length = 0
|
121 |
+
super().__init__(
|
122 |
+
errors=errors,
|
123 |
+
**kwargs,
|
124 |
+
)
|
125 |
+
|
126 |
+
@property
|
127 |
+
def eos_token_id(self) -> Optional[int]:
|
128 |
+
return 0
|
129 |
+
|
130 |
+
@property
|
131 |
+
def eot_token_id(self) -> Optional[int]:
|
132 |
+
return 0
|
133 |
+
|
134 |
+
@property
|
135 |
+
def pad_token_id(self) -> Optional[int]:
|
136 |
+
return 0
|
137 |
+
|
138 |
+
@property
|
139 |
+
def vocab_size(self):
|
140 |
+
return len(self.encoder)
|
141 |
+
|
142 |
+
def get_vocab(self):
|
143 |
+
return dict(self.encoder, **self.added_tokens_encoder)
|
144 |
+
|
145 |
+
def add_tokens(self, new_tokens, special_tokens: bool = False):
|
146 |
+
for token in new_tokens:
|
147 |
+
token_id = self.convert_tokens_to_ids(token)
|
148 |
+
self.added_tokens_decoder[token_id] = token
|
149 |
+
|
150 |
+
def convert_ids_to_tokens(self, ids, skip_special_tokens=False):
|
151 |
+
if isinstance(ids, int):
|
152 |
+
ids = [ids]
|
153 |
+
tokens = []
|
154 |
+
for id_ in ids:
|
155 |
+
if id_ in self.added_tokens_decoder:
|
156 |
+
tokens.append(self.added_tokens_decoder[id_])
|
157 |
+
else:
|
158 |
+
tokens.append(self._convert_id_to_token(id_))
|
159 |
+
return tokens
|
160 |
+
|
161 |
+
def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
|
162 |
+
if self.add_bos_token:
|
163 |
+
bos_token_ids = [self.bos_token_id]
|
164 |
+
else:
|
165 |
+
bos_token_ids = []
|
166 |
+
|
167 |
+
output = bos_token_ids + token_ids_0
|
168 |
+
|
169 |
+
if token_ids_1 is None:
|
170 |
+
return output
|
171 |
+
|
172 |
+
return output + bos_token_ids + token_ids_1
|
173 |
+
|
174 |
+
def get_special_tokens_mask(
|
175 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
|
176 |
+
) -> List[int]:
|
177 |
+
"""
|
178 |
+
Retrieves sequence ids from a token list that has no special tokens added. This method is called when adding
|
179 |
+
special tokens using the tokenizer `prepare_for_model` or `encode_plus` methods.
|
180 |
+
|
181 |
+
Args:
|
182 |
+
token_ids_0 (`List[int]`):
|
183 |
+
List of IDs.
|
184 |
+
token_ids_1 (`List[int]`, *optional*):
|
185 |
+
Optional second list of IDs for sequence pairs.
|
186 |
+
already_has_special_tokens (`bool`, *optional*, defaults to `False`):
|
187 |
+
Whether or not the token list is already formatted with special tokens for the model.
|
188 |
+
|
189 |
+
Returns:
|
190 |
+
`List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
|
191 |
+
"""
|
192 |
+
if already_has_special_tokens:
|
193 |
+
return super().get_special_tokens_mask(
|
194 |
+
token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
|
195 |
+
)
|
196 |
+
|
197 |
+
if not self.add_bos_token:
|
198 |
+
return super().get_special_tokens_mask(
|
199 |
+
token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=False
|
200 |
+
)
|
201 |
+
|
202 |
+
if token_ids_1 is None:
|
203 |
+
return [1] + ([0] * len(token_ids_0))
|
204 |
+
return [1] + ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1))
|
205 |
+
|
206 |
+
def encodeBytes(self, src: bytes):
|
207 |
+
idx: int = 0
|
208 |
+
tokens = []
|
209 |
+
while idx < len(src):
|
210 |
+
_idx: int = idx
|
211 |
+
idx, _, values = self.trie.find_longest(src, idx)
|
212 |
+
assert idx != _idx
|
213 |
+
_, token = next(iter(values))
|
214 |
+
tokens.append(token)
|
215 |
+
return tokens
|
216 |
+
|
217 |
+
def decodeBytes(self, tokens):
|
218 |
+
return b"".join(map(lambda i: self.encoder[i], tokens)) # noqa
|
219 |
+
|
220 |
+
def _tokenize(self, text, **kwargs):
|
221 |
+
"""Tokenize a string."""
|
222 |
+
return self.encodeBytes(text.encode("utf-8"))
|
223 |
+
|
224 |
+
def _decode_tokens(self, tokens):
|
225 |
+
try:
|
226 |
+
return self.decodeBytes(tokens).decode("utf-8")
|
227 |
+
except Exception:
|
228 |
+
return "\ufffd" # bad utf-8
|
229 |
+
|
230 |
+
def _decode(
|
231 |
+
self,
|
232 |
+
token_ids: Union[int, List[int]],
|
233 |
+
skip_special_tokens: bool = False,
|
234 |
+
**kwargs,
|
235 |
+
) -> str:
|
236 |
+
def remove_zeros_from_first_segment(token_ids, first_max_length):
|
237 |
+
first_segment = token_ids[:first_max_length]
|
238 |
+
first_segment_cleaned = [token for token in first_segment if token != 0]
|
239 |
+
return first_segment_cleaned + token_ids[first_max_length:]
|
240 |
+
|
241 |
+
# Convert inputs to python lists
|
242 |
+
token_ids = to_py_obj(token_ids)
|
243 |
+
token_ids = remove_zeros_from_first_segment(token_ids, self.first_max_length)
|
244 |
+
if isinstance(token_ids, int):
|
245 |
+
if token_ids in self.all_special_ids and skip_special_tokens:
|
246 |
+
return ""
|
247 |
+
return self.encoder.get(token_ids, self.unk_token)
|
248 |
+
elif isinstance(token_ids, list):
|
249 |
+
self.first_max_length
|
250 |
+
out_str = ""
|
251 |
+
out_last = 0
|
252 |
+
out_tokens = []
|
253 |
+
for i, token in enumerate(token_ids):
|
254 |
+
if token == 0:
|
255 |
+
break
|
256 |
+
out_tokens += [token]
|
257 |
+
tmp = self._decode_tokens(out_tokens[out_last:])
|
258 |
+
if "\ufffd" not in tmp:
|
259 |
+
out_str += tmp
|
260 |
+
out_last = i + 1
|
261 |
+
return out_str
|
262 |
+
else:
|
263 |
+
return token_ids
|
264 |
+
|
265 |
+
def _convert_token_to_id(self, token):
|
266 |
+
"""Converts a token (str) in an id using the vocab."""
|
267 |
+
return self.encoder.get(token, self.encoder.get(self.unk_token))
|
268 |
+
|
269 |
+
def _convert_id_to_token(self, index):
|
270 |
+
"""Converts an index (integer) in a token (str) using the vocab."""
|
271 |
+
return self.decoder.get(index)
|
272 |
+
|
273 |
+
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
|
274 |
+
if not os.path.exists(save_directory):
|
275 |
+
os.mkdir(save_directory)
|
276 |
+
if not os.path.isdir(save_directory):
|
277 |
+
logger.error(f"Vocabulary path ({save_directory}) should be a directory")
|
278 |
+
return
|
279 |
+
vocab_file = os.path.join(
|
280 |
+
save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
|
281 |
+
)
|
282 |
+
|
283 |
+
with open(vocab_file, "w", encoding="utf-8") as f:
|
284 |
+
for idx, x in self.encoder.items():
|
285 |
+
if isinstance(x, str):
|
286 |
+
x = x.decode("utf-8")
|
287 |
+
line = f"{idx} {repr(x)} {len(x)}\n"
|
288 |
+
f.write(line)
|
289 |
+
|
290 |
+
return (vocab_file,)
|
291 |
+
|
292 |
+
def prepare_for_tokenization(self, text, **kwargs):
|
293 |
+
return (text, kwargs)
|
294 |
+
|
295 |
+
def _get_padding_truncation_strategies(
|
296 |
+
self, padding=False, truncation=None, max_length=None, pad_to_multiple_of=None, verbose=True, **kwargs
|
297 |
+
):
|
298 |
+
return PaddingStrategy.LONGEST, TruncationStrategy.DO_NOT_TRUNCATE, -1, kwargs
|
299 |
+
|
300 |
+
def _encode_plus(
|
301 |
+
self,
|
302 |
+
text: Union[TextInput, EncodedInput],
|
303 |
+
add_special_tokens: bool = True,
|
304 |
+
padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
|
305 |
+
truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
|
306 |
+
max_length: Optional[int] = None,
|
307 |
+
stride: int = 0,
|
308 |
+
pad_to_multiple_of: Optional[int] = None,
|
309 |
+
return_tensors: Optional[Union[str, TensorType]] = None,
|
310 |
+
return_token_type_ids: Optional[bool] = None,
|
311 |
+
return_attention_mask: Optional[bool] = None,
|
312 |
+
return_overflowing_tokens: bool = False,
|
313 |
+
return_special_tokens_mask: bool = False,
|
314 |
+
return_offsets_mapping: bool = False,
|
315 |
+
return_length: bool = False,
|
316 |
+
verbose: bool = True,
|
317 |
+
**kwargs,
|
318 |
+
) -> BatchEncoding:
|
319 |
+
def get_input_ids(text, max_length=None, pad_token_id=0):
|
320 |
+
def pad_sequence(seq, max_len, pad_tok):
|
321 |
+
return [pad_tok] * (max_len - len(seq)) + seq
|
322 |
+
|
323 |
+
if isinstance(text, str):
|
324 |
+
tokens = self._tokenize(text)
|
325 |
+
if max_length is not None:
|
326 |
+
tokens = pad_sequence(tokens, max_length, pad_token_id)
|
327 |
+
return tokens
|
328 |
+
|
329 |
+
elif isinstance(text, list) and len(text) > 0 and isinstance(text[0], str):
|
330 |
+
tokenized_texts = [self._tokenize(t) for t in text]
|
331 |
+
if max_length is None:
|
332 |
+
max_length = max(len(t) for t in tokenized_texts)
|
333 |
+
return [pad_sequence(t, max_length, pad_token_id) for t in tokenized_texts]
|
334 |
+
|
335 |
+
elif isinstance(text, (list, tuple)) and len(text) > 0 and isinstance(text[0], int):
|
336 |
+
if max_length is not None and len(text) < max_length:
|
337 |
+
return pad_sequence(text, max_length, pad_token_id)
|
338 |
+
return text
|
339 |
+
|
340 |
+
else:
|
341 |
+
raise ValueError(
|
342 |
+
"Input is not valid. Should be a string, a list/tuple of strings or a list/tuple of integers."
|
343 |
+
)
|
344 |
+
|
345 |
+
if return_offsets_mapping:
|
346 |
+
raise NotImplementedError(
|
347 |
+
"return_offset_mapping is not available when using Python tokenizers. "
|
348 |
+
"To use this feature, change your tokenizer to one deriving from "
|
349 |
+
"transformers.PreTrainedTokenizerFast. "
|
350 |
+
"More information on available tokenizers at "
|
351 |
+
"https://github.com/huggingface/transformers/pull/2674"
|
352 |
+
)
|
353 |
+
|
354 |
+
first_ids = get_input_ids(text)
|
355 |
+
|
356 |
+
return self.prepare_for_model(
|
357 |
+
first_ids,
|
358 |
+
pair_ids=None,
|
359 |
+
add_special_tokens=add_special_tokens,
|
360 |
+
padding=padding_strategy.value,
|
361 |
+
truncation=truncation_strategy.value,
|
362 |
+
max_length=max_length,
|
363 |
+
stride=stride,
|
364 |
+
pad_to_multiple_of=pad_to_multiple_of,
|
365 |
+
return_tensors=return_tensors,
|
366 |
+
prepend_batch_axis=True,
|
367 |
+
return_attention_mask=return_attention_mask,
|
368 |
+
return_token_type_ids=return_token_type_ids,
|
369 |
+
return_overflowing_tokens=return_overflowing_tokens,
|
370 |
+
return_special_tokens_mask=return_special_tokens_mask,
|
371 |
+
return_length=return_length,
|
372 |
+
verbose=verbose,
|
373 |
+
)
|
374 |
+
|
375 |
+
def _batch_encode_plus(
|
376 |
+
self,
|
377 |
+
batch_text_or_text_pairs: Union[
|
378 |
+
List[TextInput],
|
379 |
+
List[EncodedInput],
|
380 |
+
],
|
381 |
+
add_special_tokens: bool = True,
|
382 |
+
padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
|
383 |
+
truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
|
384 |
+
max_length: Optional[int] = None,
|
385 |
+
stride: int = 0,
|
386 |
+
pad_to_multiple_of: Optional[int] = None,
|
387 |
+
return_tensors: Optional[Union[str, TensorType]] = None,
|
388 |
+
return_token_type_ids: Optional[bool] = None,
|
389 |
+
return_attention_mask: Optional[bool] = None,
|
390 |
+
return_overflowing_tokens: bool = False,
|
391 |
+
return_special_tokens_mask: bool = False,
|
392 |
+
return_offsets_mapping: bool = False,
|
393 |
+
return_length: bool = False,
|
394 |
+
verbose: bool = True,
|
395 |
+
**kwargs,
|
396 |
+
) -> BatchEncoding:
|
397 |
+
def get_input_ids(text, max_length=None, pad_token_id=0):
|
398 |
+
def pad_sequence(seq, max_len, pad_tok):
|
399 |
+
return [pad_tok] * (max_len - len(seq)) + seq
|
400 |
+
|
401 |
+
if isinstance(text, str):
|
402 |
+
tokens = self._tokenize(text)
|
403 |
+
if max_length is not None:
|
404 |
+
tokens = pad_sequence(tokens, max_length, pad_token_id)
|
405 |
+
return tokens
|
406 |
+
|
407 |
+
elif isinstance(text, list) and len(text) > 0 and isinstance(text[0], str):
|
408 |
+
tokenized_texts = [self._tokenize(t) for t in text]
|
409 |
+
if max_length is None:
|
410 |
+
max_length = max(len(t) for t in tokenized_texts)
|
411 |
+
return [pad_sequence(t, max_length, pad_token_id) for t in tokenized_texts]
|
412 |
+
|
413 |
+
elif isinstance(text, (list, tuple)) and len(text) > 0 and isinstance(text[0], int):
|
414 |
+
if max_length is not None and len(text) < max_length:
|
415 |
+
return pad_sequence(text, max_length, pad_token_id)
|
416 |
+
return text
|
417 |
+
|
418 |
+
else:
|
419 |
+
raise ValueError(
|
420 |
+
"Input is not valid. Should be a string, a list/tuple of strings or a list/tuple of integers."
|
421 |
+
)
|
422 |
+
|
423 |
+
if return_offsets_mapping:
|
424 |
+
raise NotImplementedError(
|
425 |
+
"return_offset_mapping is not available when using Python tokenizers. "
|
426 |
+
"To use this feature, change your tokenizer to one deriving from "
|
427 |
+
"transformers.PreTrainedTokenizerFast."
|
428 |
+
)
|
429 |
+
|
430 |
+
first_max_length = 0
|
431 |
+
second_max_length = 0
|
432 |
+
for ids_or_pair_ids in batch_text_or_text_pairs:
|
433 |
+
if not isinstance(ids_or_pair_ids, (list, tuple)):
|
434 |
+
ids, pair_ids = ids_or_pair_ids, None
|
435 |
+
else:
|
436 |
+
ids, pair_ids = ids_or_pair_ids
|
437 |
+
first_ids = get_input_ids(ids)
|
438 |
+
second_ids = get_input_ids(pair_ids) if pair_ids is not None else None
|
439 |
+
first_max_length = max(first_max_length, len(first_ids))
|
440 |
+
if second_ids is not None:
|
441 |
+
second_max_length = max(second_max_length, len(second_ids))
|
442 |
+
|
443 |
+
self.first_max_length = first_max_length
|
444 |
+
input_ids = []
|
445 |
+
for ids_or_pair_ids in batch_text_or_text_pairs:
|
446 |
+
if not isinstance(ids_or_pair_ids, (list, tuple)):
|
447 |
+
ids, pair_ids = ids_or_pair_ids, None
|
448 |
+
else:
|
449 |
+
ids, pair_ids = ids_or_pair_ids
|
450 |
+
|
451 |
+
first_ids = get_input_ids(ids, max_length=first_max_length)
|
452 |
+
second_ids = get_input_ids(pair_ids, max_length=second_max_length) if pair_ids is not None else None
|
453 |
+
input_ids.append((first_ids, second_ids))
|
454 |
+
|
455 |
+
batch_outputs = self._batch_prepare_for_model(
|
456 |
+
input_ids,
|
457 |
+
add_special_tokens=add_special_tokens,
|
458 |
+
padding_strategy=padding_strategy,
|
459 |
+
truncation_strategy=truncation_strategy,
|
460 |
+
max_length=max_length,
|
461 |
+
stride=stride,
|
462 |
+
pad_to_multiple_of=pad_to_multiple_of,
|
463 |
+
return_attention_mask=return_attention_mask,
|
464 |
+
return_token_type_ids=return_token_type_ids,
|
465 |
+
return_overflowing_tokens=return_overflowing_tokens,
|
466 |
+
return_special_tokens_mask=return_special_tokens_mask,
|
467 |
+
return_length=return_length,
|
468 |
+
return_tensors=return_tensors,
|
469 |
+
verbose=verbose,
|
470 |
+
)
|
471 |
+
|
472 |
+
return BatchEncoding(batch_outputs)
|
473 |
+
|
474 |
+
def decode(
|
475 |
+
self,
|
476 |
+
token_ids: Union[int, List[int]],
|
477 |
+
skip_special_tokens: bool = False,
|
478 |
+
clean_up_tokenization_spaces: bool = None,
|
479 |
+
**kwargs,
|
480 |
+
) -> str:
|
481 |
+
"""
|
482 |
+
Converts a sequence of ids in a string, using the tokenizer and vocabulary with options to remove special
|
483 |
+
tokens and clean up tokenization spaces.
|
484 |
+
|
485 |
+
Similar to doing `self.convert_tokens_to_string(self.convert_ids_to_tokens(token_ids))`.
|
486 |
+
|
487 |
+
Args:
|
488 |
+
token_ids (`Union[int, List[int], np.ndarray, torch.Tensor, tf.Tensor]`):
|
489 |
+
List of tokenized input ids. Can be obtained using the `__call__` method.
|
490 |
+
skip_special_tokens (`bool`, *optional*, defaults to `False`):
|
491 |
+
Whether or not to remove special tokens in the decoding.
|
492 |
+
clean_up_tokenization_spaces (`bool`, *optional*):
|
493 |
+
Whether or not to clean up the tokenization spaces. If `None`, will default to
|
494 |
+
`self.clean_up_tokenization_spaces`.
|
495 |
+
kwargs (additional keyword arguments, *optional*):
|
496 |
+
Will be passed to the underlying model specific decode method.
|
497 |
+
|
498 |
+
Returns:
|
499 |
+
`str`: The decoded sentence.
|
500 |
+
"""
|
501 |
+
# Convert inputs to python lists
|
502 |
+
return self._decode(
|
503 |
+
token_ids=token_ids,
|
504 |
+
skip_special_tokens=skip_special_tokens,
|
505 |
+
clean_up_tokenization_spaces=clean_up_tokenization_spaces,
|
506 |
+
**kwargs,
|
507 |
+
)
|
508 |
+
|
509 |
+
def batch_decode(
|
510 |
+
self,
|
511 |
+
sequences: Union[List[int], List[List[int]]],
|
512 |
+
skip_special_tokens: bool = False,
|
513 |
+
clean_up_tokenization_spaces: bool = None,
|
514 |
+
**kwargs,
|
515 |
+
) -> List[str]:
|
516 |
+
"""
|
517 |
+
Convert a list of lists of token ids into a list of strings by calling decode.
|
518 |
+
|
519 |
+
Args:
|
520 |
+
sequences (`Union[List[int], List[List[int]], np.ndarray, torch.Tensor, tf.Tensor]`):
|
521 |
+
List of tokenized input ids. Can be obtained using the `__call__` method.
|
522 |
+
skip_special_tokens (`bool`, *optional*, defaults to `False`):
|
523 |
+
Whether or not to remove special tokens in the decoding.
|
524 |
+
clean_up_tokenization_spaces (`bool`, *optional*):
|
525 |
+
Whether or not to clean up the tokenization spaces. If `None`, will default to
|
526 |
+
`self.clean_up_tokenization_spaces`.
|
527 |
+
kwargs (additional keyword arguments, *optional*):
|
528 |
+
Will be passed to the underlying model specific decode method.
|
529 |
+
|
530 |
+
Returns:
|
531 |
+
`List[str]`: The list of decoded sentences.
|
532 |
+
"""
|
533 |
+
return [
|
534 |
+
self.decode(
|
535 |
+
seq,
|
536 |
+
skip_special_tokens=skip_special_tokens,
|
537 |
+
clean_up_tokenization_spaces=clean_up_tokenization_spaces,
|
538 |
+
**kwargs,
|
539 |
+
)
|
540 |
+
for seq in sequences
|
541 |
+
]
|
542 |
+
|
543 |
+
def _build_conversation_input_ids(self, conversation: "Conversation") -> List[int]:
|
544 |
+
input_ids = []
|
545 |
+
for is_user, text in conversation.iter_texts():
|
546 |
+
input_ids.extend(self.encode(text, add_special_tokens=False) + [self.eos_token_id])
|
547 |
+
if len(input_ids) > self.model_max_length:
|
548 |
+
input_ids = input_ids[-self.model_max_length :]
|
549 |
+
return input_ids
|
tokenizer_config.json
ADDED
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"auto_map": {
|
3 |
+
"AutoTokenizer": [
|
4 |
+
"tokenization_rwkv5.Rwkv5Tokenizer",
|
5 |
+
null
|
6 |
+
]
|
7 |
+
},
|
8 |
+
"added_tokens_decoder": {
|
9 |
+
"0": {
|
10 |
+
"content": "<s>",
|
11 |
+
"lstrip": false,
|
12 |
+
"normalized": true,
|
13 |
+
"rstrip": false,
|
14 |
+
"single_word": false,
|
15 |
+
"special": false
|
16 |
+
}
|
17 |
+
},
|
18 |
+
"bos_token": "<s>",
|
19 |
+
"clean_up_tokenization_spaces": true,
|
20 |
+
"eos_token": "<s>",
|
21 |
+
"model_max_length": 1000000000000000019884624838656,
|
22 |
+
"unk_token": "<s>"
|
23 |
+
}
|
vocab.txt
ADDED
The diff for this file is too large to render.
See raw diff
|
|